diff --git a/README.md b/README.md index 5c71398..dc9f43f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ # bitbybit-assets Public Assets of Bit by bit developers platform -# License +# License Assets CC BY 4.0 -https://creativecommons.org/licenses/by/4.0/ \ No newline at end of file +https://creativecommons.org/licenses/by/4.0/ + +# License Code +MIT \ No newline at end of file diff --git a/runner/bitbybit-runner.js b/runner/bitbybit-runner.js index 627bdbc..87f0efc 100644 --- a/runner/bitbybit-runner.js +++ b/runner/bitbybit-runner.js @@ -1,2 +1,2 @@ /*! For license information please see bitbybit-runner.js.LICENSE.txt */ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.bitbybitRunner=t():e.bitbybitRunner=t()}(this,(()=>(()=>{var e={615:(e,t,i)=>{e.exports=function e(t,i,s){function r(o,a){if(!i[o]){if(!t[o]){if(n)return n(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var h=i[o]={exports:{}};t[o][0].call(h.exports,(function(e){return r(t[o][1][e]||e)}),h,h.exports,e,t,i,s)}return i[o].exports}for(var n=void 0,o=0;o=48&&e<=57}function T(e){return"0123456789abcdefABCDEF".indexOf(e)>=0}function y(e){return"01234567".indexOf(e)>=0}function S(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279].indexOf(e)>=0}function C(e){return 10===e||13===e||8232===e||8233===e}function E(e){return 64==e||36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||92===e||e>=128&&a.NonAsciiIdentifierStart.test(String.fromCharCode(e))}function A(e){return 36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||92===e||e>=128&&a.NonAsciiIdentifierPart.test(String.fromCharCode(e))}function P(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return!0;default:return!1}}function I(e){return"eval"===e||"arguments"===e}function R(e){if(c&&P(e))return!0;switch(e.length){case 2:return"if"===e||"in"===e||"do"===e;case 3:return"var"===e||"for"===e||"new"===e||"try"===e||"let"===e;case 4:return"this"===e||"else"===e||"case"===e||"void"===e||"with"===e||"enum"===e;case 5:return"while"===e||"break"===e||"catch"===e||"throw"===e||"const"===e||"yield"===e||"class"===e||"super"===e;case 6:return"return"===e||"typeof"===e||"delete"===e||"switch"===e||"export"===e||"import"===e;case 7:return"default"===e||"finally"===e||"extends"===e;case 8:return"function"===e||"continue"===e||"debugger"===e;case 10:return"instanceof"===e;default:return!1}}function M(e,t,i,s,r){var n;x("number"==typeof i,"Comment must have valid position"),g.lastCommentStart>=i||(g.lastCommentStart=i,n={type:e,value:t},v.range&&(n.range=[i,s]),v.loc&&(n.loc=r),v.comments.push(n),v.attachComment&&(v.leadingComments.push(n),v.trailingComments.push(n)))}function O(e){var t,i,s,r;for(t=u-e,i={start:{line:d,column:u-_-e}};u=p&&j({},o.UnexpectedToken,"ILLEGAL");else if(42===i){if(47===h.charCodeAt(u+1))return++u,++u,void(v.comments&&(s=h.slice(e+2,u-2),t.end={line:d,column:u-_},M("Block",s,e,u,t)));++u}else++u;j({},o.UnexpectedToken,"ILLEGAL")}function w(){var e,t;for(t=0===u;u>>="===(r=h.substr(u,4))?(u+=4,{type:t.Punctuator,value:r,lineNumber:d,lineStart:_,start:n,end:u}):">>>"===(s=r.substr(0,3))||"<<="===s||">>="===s?(u+=3,{type:t.Punctuator,value:s,lineNumber:d,lineStart:_,start:n,end:u}):l===(i=s.substr(0,2))[1]&&"+-<>&|".indexOf(l)>=0||"=>"===i?(u+=2,{type:t.Punctuator,value:i,lineNumber:d,lineStart:_,start:n,end:u}):"<>=!+-*%&|^/".indexOf(l)>=0?(++u,{type:t.Punctuator,value:l,lineNumber:d,lineStart:_,start:n,end:u}):void j({},o.UnexpectedToken,"ILLEGAL")}function k(){var e,i,s;if(x(b((s=h[u]).charCodeAt(0))||"."===s,"Numeric literal must start with a decimal digit or a decimal point"),i=u,e="","."!==s){if(e=h[u++],s=h[u],"0"===e){if("x"===s||"X"===s)return++u,function(e){for(var i="";u0&&(s=v.tokens[v.tokens.length-1]).range[0]===e&&"Punctuator"===s.type&&("/"!==s.value&&"/="!==s.value||v.tokens.pop()),v.tokens.push({type:"RegularExpression",value:i.literal,range:[e,u],loc:t})),i}function G(){var e,i,r;return w(),u>=p?{type:t.EOF,lineNumber:d,lineStart:_,start:u,end:u}:E(e=h.charCodeAt(u))?(i=u,{type:1===(r=92===h.charCodeAt(u)?F():L()).length?t.Identifier:R(r)?t.Keyword:"null"===r?t.NullLiteral:"true"===r||"false"===r?t.BooleanLiteral:t.Identifier,value:r,lineNumber:d,lineStart:_,start:i,end:u}):40===e||41===e||59===e?B():39===e||34===e?function(){var e,i,s,r,n,a,l,c,f="",m=!1;for(l=d,c=_,x("'"===(e=h[u])||'"'===e,"String literal must starts with a quote"),i=u,++u;u=0&&u=0?B():U()}return U()}return"Keyword"===e.type?U():B()}():B()}function z(){var e,s,r;return w(),e={start:{line:d,column:u-_}},s=G(),e.end={line:d,column:u-_},s.type!==t.EOF&&(r=h.slice(s.start,s.end),v.tokens.push({type:i[s.type],value:r,range:[s.start,s.end],loc:e})),s}function W(){var e;return u=(e=m).end,d=e.lineNumber,_=e.lineStart,m=void 0!==v.tokens?z():G(),u=e.end,d=e.lineNumber,_=e.lineStart,e}function H(){var e,t,i;e=u,t=d,i=_,m=void 0!==v.tokens?z():G(),u=e,d=t,_=i}function X(e,t){this.line=e,this.column=t}function Y(e,t,i,s){this.start=new X(e,t),this.end=new X(i,s)}function Q(){var e,t,i,s;return e=u,t=d,i=_,w(),s=d!==t,u=e,d=t,_=i,s}function j(e,t){var i,s=Array.prototype.slice.call(arguments,2),r=t.replace(/%(\d)/g,(function(e,t){return x(t":case"<=":case">=":case"instanceof":s=7;break;case"in":s=i?7:0;break;case"<<":case">>":case">>>":s=8;break;case"+":case"-":s=9;break;case"*":case"/":case"%":s=11}return s}function fe(){var e,t,i,s,r;return r=m,e=function(){var e,t,i,s,r,n,o,a,l,h;if(e=m,l=_e(),0===(r=pe(s=m,g.allowIn)))return l;for(s.prec=r,W(),t=[e,m],n=[l,s,o=_e()];(r=pe(m,g.allowIn))>0;){for(;n.length>2&&r<=n[n.length-2].prec;)o=n.pop(),a=n.pop().value,l=n.pop(),i=f.createBinaryExpression(a,l,o),t.pop(),e=t[t.length-1],f.markEnd(i,e),n.push(i);(s=W()).prec=r,n.push(s),t.push(m),i=_e(),n.push(i)}for(i=n[h=n.length-1],t.pop();h>1;)i=f.createBinaryExpression(n[h-1].value,n[h-2],i),h-=2,e=t.pop(),f.markEnd(i,e);return i}(),J("?")&&(W(),t=g.allowIn,g.allowIn=!0,i=me(),g.allowIn=t,q(":"),s=me(),e=f.createConditionalExpression(e,i,s),f.markEnd(e,r)),e}function me(){var e,i,s,n,a,l;return e=m,a=m,n=i=fe(),m.type===t.Punctuator&&("="===(l=m.value)||"*="===l||"/="===l||"%="===l||"+="===l||"-="===l||"<<="===l||">>="===l||">>>="===l||"&="===l||"^="===l||"|="===l)&&(ie(i)||K({},o.InvalidLHSInAssignment),c&&i.type===r.Identifier&&I(i.name)&&K(e,o.StrictLHSAssignment),e=W(),s=me(),n=f.markEnd(f.createAssignmentExpression(e.value,i,s),a)),n}function ge(){var e,t=m;if(e=me(),J(",")){for(e=f.createSequenceExpression([e]);u",i[t.Identifier]="Identifier",i[t.Keyword]="Keyword",i[t.NullLiteral]="Null",i[t.NumericLiteral]="Numeric",i[t.Punctuator]="Punctuator",i[t.StringLiteral]="String",i[t.RegularExpression]="RegularExpression",s=["(","{","[","in","typeof","instanceof","new","return","case","delete","throw","void","=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","&=","|=","^=",",","+","-","*","/","%","++","--","<<",">>",">>>","&","|","^","!","~","&&","||","?",":","===","==",">=","<=","<",">","!=","!=="],r={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DoWhileStatement:"DoWhileStatement",DebuggerStatement:"DebuggerStatement",EmptyStatement:"EmptyStatement",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",Identifier:"Identifier",IfStatement:"IfStatement",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement"},n={Data:1,Get:2,Set:4},o={UnexpectedToken:"Unexpected token %0",UnexpectedNumber:"Unexpected number",UnexpectedString:"Unexpected string",UnexpectedIdentifier:"Unexpected identifier",UnexpectedReserved:"Unexpected reserved word",UnexpectedEOS:"Unexpected end of input",NewlineAfterThrow:"Illegal newline after throw",InvalidRegExp:"Invalid regular expression",UnterminatedRegExp:"Invalid regular expression: missing /",InvalidLHSInAssignment:"Invalid left-hand side in assignment",InvalidLHSInForIn:"Invalid left-hand side in for-in",MultipleDefaultsInSwitch:"More than one default clause in switch statement",NoCatchOrFinally:"Missing catch or finally after try",UnknownLabel:"Undefined label '%0'",Redeclaration:"%0 '%1' has already been declared",IllegalContinue:"Illegal continue statement",IllegalBreak:"Illegal break statement",IllegalReturn:"Illegal return statement",StrictModeWith:"Strict mode code may not include a with statement",StrictCatchVariable:"Catch variable may not be eval or arguments in strict mode",StrictVarName:"Variable name may not be eval or arguments in strict mode",StrictParamName:"Parameter name eval or arguments is not allowed in strict mode",StrictParamDupe:"Strict mode function may not have duplicate parameter names",StrictFunctionName:"Function name may not be eval or arguments in strict mode",StrictOctalLiteral:"Octal literals are not allowed in strict mode.",StrictDelete:"Delete of an unqualified identifier in strict mode.",StrictDuplicateProperty:"Duplicate data property in object literal not allowed in strict mode",AccessorDataProperty:"Object literal may not have data and accessor property with the same name",AccessorGetSet:"Object literal may not have multiple get/set accessors with the same name",StrictLHSAssignment:"Assignment to eval or arguments is not allowed in strict mode",StrictLHSPostfix:"Postfix increment/decrement may not have eval or arguments operand in strict mode",StrictLHSPrefix:"Prefix increment/decrement may not have eval or arguments operand in strict mode",StrictReservedWord:"Use of future reserved word in strict mode"},a={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")},l={name:"SyntaxTree",processComment:function(e){var t,i;if(!(e.type===r.Program&&e.body.length>0)){for(v.trailingComments.length>0?v.trailingComments[0].range[0]>=e.range[1]?(i=v.trailingComments,v.trailingComments=[]):v.trailingComments.length=0:v.bottomRightStack.length>0&&v.bottomRightStack[v.bottomRightStack.length-1].trailingComments&&v.bottomRightStack[v.bottomRightStack.length-1].trailingComments[0].range[0]>=e.range[1]&&(i=v.bottomRightStack[v.bottomRightStack.length-1].trailingComments,delete v.bottomRightStack[v.bottomRightStack.length-1].trailingComments);v.bottomRightStack.length>0&&v.bottomRightStack[v.bottomRightStack.length-1].range[0]>=e.range[0];)t=v.bottomRightStack.pop();t?t.leadingComments&&t.leadingComments[t.leadingComments.length-1].range[1]<=e.range[0]&&(e.leadingComments=t.leadingComments,delete t.leadingComments):v.leadingComments.length>0&&v.leadingComments[v.leadingComments.length-1].range[1]<=e.range[0]&&(e.leadingComments=v.leadingComments,v.leadingComments=[]),i&&(e.trailingComments=i),v.bottomRightStack.push(e)}},markEnd:function(e,t){return v.range&&(e.range=[t.start,u]),v.loc&&(e.loc=new Y(void 0===t.startLineNumber?t.lineNumber:t.startLineNumber,t.start-(void 0===t.startLineStart?t.lineStart:t.startLineStart),d,u-_),this.postProcess(e)),v.attachComment&&this.processComment(e),e},postProcess:function(e){return v.source&&(e.loc.source=v.source),e},createArrayExpression:function(e){return{type:r.ArrayExpression,elements:e}},createAssignmentExpression:function(e,t,i){return{type:r.AssignmentExpression,operator:e,left:t,right:i}},createBinaryExpression:function(e,t,i){return{type:"||"===e||"&&"===e?r.LogicalExpression:r.BinaryExpression,operator:e,left:t,right:i}},createBlockStatement:function(e){return{type:r.BlockStatement,body:e}},createBreakStatement:function(e){return{type:r.BreakStatement,label:e}},createCallExpression:function(e,t){return{type:r.CallExpression,callee:e,arguments:t}},createCatchClause:function(e,t){return{type:r.CatchClause,param:e,body:t}},createConditionalExpression:function(e,t,i){return{type:r.ConditionalExpression,test:e,consequent:t,alternate:i}},createContinueStatement:function(e){return{type:r.ContinueStatement,label:e}},createDebuggerStatement:function(){return{type:r.DebuggerStatement}},createDoWhileStatement:function(e,t){return{type:r.DoWhileStatement,body:e,test:t}},createEmptyStatement:function(){return{type:r.EmptyStatement}},createExpressionStatement:function(e){return{type:r.ExpressionStatement,expression:e}},createForStatement:function(e,t,i,s){return{type:r.ForStatement,init:e,test:t,update:i,body:s}},createForInStatement:function(e,t,i){return{type:r.ForInStatement,left:e,right:t,body:i,each:!1}},createFunctionDeclaration:function(e,t,i,s){return{type:r.FunctionDeclaration,id:e,params:t,defaults:i,body:s,rest:null,generator:!1,expression:!1}},createFunctionExpression:function(e,t,i,s){return{type:r.FunctionExpression,id:e,params:t,defaults:i,body:s,rest:null,generator:!1,expression:!1}},createIdentifier:function(e){return{type:r.Identifier,name:e}},createIfStatement:function(e,t,i){return{type:r.IfStatement,test:e,consequent:t,alternate:i}},createLabeledStatement:function(e,t){return{type:r.LabeledStatement,label:e,body:t}},createLiteral:function(e){return{type:r.Literal,value:e.value,raw:h.slice(e.start,e.end)}},createMemberExpression:function(e,t,i){return{type:r.MemberExpression,computed:"["===e,object:t,property:i}},createNewExpression:function(e,t){return{type:r.NewExpression,callee:e,arguments:t}},createObjectExpression:function(e){return{type:r.ObjectExpression,properties:e}},createPostfixExpression:function(e,t){return{type:r.UpdateExpression,operator:e,argument:t,prefix:!1}},createProgram:function(e){return{type:r.Program,body:e}},createProperty:function(e,t,i){return{type:r.Property,key:t,value:i,kind:e}},createReturnStatement:function(e){return{type:r.ReturnStatement,argument:e}},createSequenceExpression:function(e){return{type:r.SequenceExpression,expressions:e}},createSwitchCase:function(e,t){return{type:r.SwitchCase,test:e,consequent:t}},createSwitchStatement:function(e,t){return{type:r.SwitchStatement,discriminant:e,cases:t}},createThisExpression:function(){return{type:r.ThisExpression}},createThrowStatement:function(e){return{type:r.ThrowStatement,argument:e}},createTryStatement:function(e,t,i,s){return{type:r.TryStatement,block:e,guardedHandlers:t,handlers:i,finalizer:s}},createUnaryExpression:function(e,t){return"++"===e||"--"===e?{type:r.UpdateExpression,operator:e,argument:t,prefix:!0}:{type:r.UnaryExpression,operator:e,argument:t,prefix:!0}},createVariableDeclaration:function(e,t){return{type:r.VariableDeclaration,declarations:e,kind:t}},createVariableDeclarator:function(e,t){return{type:r.VariableDeclarator,id:e,init:t}},createWhileStatement:function(e,t){return{type:r.WhileStatement,test:e,body:t}},createWithStatement:function(e,t){return{type:r.WithStatement,object:e,body:t}}},e.version="1.2.2",e.tokenize=function(e,i){var s;"string"==typeof e||e instanceof String||(e=String(e)),f=l,u=0,d=(h=e).length>0?1:0,_=0,p=h.length,m=null,g={allowIn:!0,labelSet:{},inFunctionBody:!1,inIteration:!1,inSwitch:!1,lastCommentStart:-1},v={},(i=i||{}).tokens=!0,v.tokens=[],v.tokenize=!0,v.openParenToken=-1,v.openCurlyToken=-1,v.range="boolean"==typeof i.range&&i.range,v.loc="boolean"==typeof i.loc&&i.loc,"boolean"==typeof i.comment&&i.comment&&(v.comments=[]),"boolean"==typeof i.tolerant&&i.tolerant&&(v.errors=[]);try{if(H(),m.type===t.EOF)return v.tokens;for(W();m.type!==t.EOF;)try{W()}catch(e){if(v.errors){v.errors.push(e);break}throw e}Oe(),s=v.tokens,void 0!==v.comments&&(s.comments=v.comments),void 0!==v.errors&&(s.errors=v.errors)}catch(e){throw e}finally{v={}}return s},e.parse=function(e,t){var i,s;s=String,"string"==typeof e||e instanceof String||(e=s(e)),f=l,u=0,d=(h=e).length>0?1:0,_=0,p=h.length,m=null,g={allowIn:!0,labelSet:{},inFunctionBody:!1,inIteration:!1,inSwitch:!1,lastCommentStart:-1},v={},void 0!==t&&(v.range="boolean"==typeof t.range&&t.range,v.loc="boolean"==typeof t.loc&&t.loc,v.attachComment="boolean"==typeof t.attachComment&&t.attachComment,v.loc&&null!==t.source&&void 0!==t.source&&(v.source=s(t.source)),"boolean"==typeof t.tokens&&t.tokens&&(v.tokens=[]),"boolean"==typeof t.comment&&t.comment&&(v.comments=[]),"boolean"==typeof t.tolerant&&t.tolerant&&(v.errors=[]),v.attachComment&&(v.range=!0,v.comments=[],v.bottomRightStack=[],v.trailingComments=[],v.leadingComments=[]));try{i=Me(),void 0!==v.comments&&(i.comments=v.comments),void 0!==v.tokens&&(Oe(),i.tokens=v.tokens),void 0!==v.errors&&(i.errors=v.errors)}catch(e){throw e}finally{v={}}return i},e.Syntax=function(){var e,t={};for(e in"function"==typeof Object.create&&(t=Object.create(null)),r)r.hasOwnProperty(e)&&(t[e]=r[e]);return"function"==typeof Object.freeze&&Object.freeze(t),t}()}))},{}],1:[function(e,t,i){(function(s){var r=function(){var e={trace:function(){},yy:{},symbols_:{error:2,JSON_PATH:3,DOLLAR:4,PATH_COMPONENTS:5,LEADING_CHILD_MEMBER_EXPRESSION:6,PATH_COMPONENT:7,MEMBER_COMPONENT:8,SUBSCRIPT_COMPONENT:9,CHILD_MEMBER_COMPONENT:10,DESCENDANT_MEMBER_COMPONENT:11,DOT:12,MEMBER_EXPRESSION:13,DOT_DOT:14,STAR:15,IDENTIFIER:16,SCRIPT_EXPRESSION:17,INTEGER:18,END:19,CHILD_SUBSCRIPT_COMPONENT:20,DESCENDANT_SUBSCRIPT_COMPONENT:21,"[":22,SUBSCRIPT:23,"]":24,SUBSCRIPT_EXPRESSION:25,SUBSCRIPT_EXPRESSION_LIST:26,SUBSCRIPT_EXPRESSION_LISTABLE:27,",":28,STRING_LITERAL:29,ARRAY_SLICE:30,FILTER_EXPRESSION:31,QQ_STRING:32,Q_STRING:33,$accept:0,$end:1},terminals_:{2:"error",4:"DOLLAR",12:"DOT",14:"DOT_DOT",15:"STAR",16:"IDENTIFIER",17:"SCRIPT_EXPRESSION",18:"INTEGER",19:"END",22:"[",24:"]",28:",",30:"ARRAY_SLICE",31:"FILTER_EXPRESSION",32:"QQ_STRING",33:"Q_STRING"},productions_:[0,[3,1],[3,2],[3,1],[3,2],[5,1],[5,2],[7,1],[7,1],[8,1],[8,1],[10,2],[6,1],[11,2],[13,1],[13,1],[13,1],[13,1],[13,1],[9,1],[9,1],[20,3],[21,4],[23,1],[23,1],[26,1],[26,3],[27,1],[27,1],[27,1],[25,1],[25,1],[25,1],[29,1],[29,1]],performAction:function(e,i,s,r,n,o,a){r.ast||(r.ast=t,t.initialize());var l=o.length-1;switch(n){case 1:return r.ast.set({expression:{type:"root",value:o[l]}}),r.ast.unshift(),r.ast.yield();case 2:return r.ast.set({expression:{type:"root",value:o[l-1]}}),r.ast.unshift(),r.ast.yield();case 3:return r.ast.unshift(),r.ast.yield();case 4:return r.ast.set({operation:"member",scope:"child",expression:{type:"identifier",value:o[l-1]}}),r.ast.unshift(),r.ast.yield();case 5:case 6:case 11:case 13:case 18:case 21:case 22:case 23:break;case 7:r.ast.set({operation:"member"}),r.ast.push();break;case 8:r.ast.set({operation:"subscript"}),r.ast.push();break;case 9:case 19:r.ast.set({scope:"child"});break;case 10:case 20:r.ast.set({scope:"descendant"});break;case 12:r.ast.set({scope:"child",operation:"member"});break;case 14:r.ast.set({expression:{type:"wildcard",value:o[l]}});break;case 15:r.ast.set({expression:{type:"identifier",value:o[l]}});break;case 16:r.ast.set({expression:{type:"script_expression",value:o[l]}});break;case 17:r.ast.set({expression:{type:"numeric_literal",value:parseInt(o[l])}});break;case 24:o[l].length>1?r.ast.set({expression:{type:"union",value:o[l]}}):this.$=o[l];break;case 25:this.$=[o[l]];break;case 26:this.$=o[l-2].concat(o[l]);break;case 27:this.$={expression:{type:"numeric_literal",value:parseInt(o[l])}},r.ast.set(this.$);break;case 28:this.$={expression:{type:"string_literal",value:o[l]}},r.ast.set(this.$);break;case 29:this.$={expression:{type:"slice",value:o[l]}},r.ast.set(this.$);break;case 30:this.$={expression:{type:"wildcard",value:o[l]}},r.ast.set(this.$);break;case 31:this.$={expression:{type:"script_expression",value:o[l]}},r.ast.set(this.$);break;case 32:this.$={expression:{type:"filter_expression",value:o[l]}},r.ast.set(this.$);break;case 33:case 34:this.$=o[l]}},table:[{3:1,4:[1,2],6:3,13:4,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9]},{1:[3]},{1:[2,1],5:10,7:11,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,3],5:21,7:11,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,12],12:[2,12],14:[2,12],22:[2,12]},{1:[2,14],12:[2,14],14:[2,14],22:[2,14]},{1:[2,15],12:[2,15],14:[2,15],22:[2,15]},{1:[2,16],12:[2,16],14:[2,16],22:[2,16]},{1:[2,17],12:[2,17],14:[2,17],22:[2,17]},{1:[2,18],12:[2,18],14:[2,18],22:[2,18]},{1:[2,2],7:22,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,5],12:[2,5],14:[2,5],22:[2,5]},{1:[2,7],12:[2,7],14:[2,7],22:[2,7]},{1:[2,8],12:[2,8],14:[2,8],22:[2,8]},{1:[2,9],12:[2,9],14:[2,9],22:[2,9]},{1:[2,10],12:[2,10],14:[2,10],22:[2,10]},{1:[2,19],12:[2,19],14:[2,19],22:[2,19]},{1:[2,20],12:[2,20],14:[2,20],22:[2,20]},{13:23,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9]},{13:24,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9],22:[1,25]},{15:[1,29],17:[1,30],18:[1,33],23:26,25:27,26:28,27:32,29:34,30:[1,35],31:[1,31],32:[1,36],33:[1,37]},{1:[2,4],7:22,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,6],12:[2,6],14:[2,6],22:[2,6]},{1:[2,11],12:[2,11],14:[2,11],22:[2,11]},{1:[2,13],12:[2,13],14:[2,13],22:[2,13]},{15:[1,29],17:[1,30],18:[1,33],23:38,25:27,26:28,27:32,29:34,30:[1,35],31:[1,31],32:[1,36],33:[1,37]},{24:[1,39]},{24:[2,23]},{24:[2,24],28:[1,40]},{24:[2,30]},{24:[2,31]},{24:[2,32]},{24:[2,25],28:[2,25]},{24:[2,27],28:[2,27]},{24:[2,28],28:[2,28]},{24:[2,29],28:[2,29]},{24:[2,33],28:[2,33]},{24:[2,34],28:[2,34]},{24:[1,41]},{1:[2,21],12:[2,21],14:[2,21],22:[2,21]},{18:[1,33],27:42,29:34,30:[1,35],32:[1,36],33:[1,37]},{1:[2,22],12:[2,22],14:[2,22],22:[2,22]},{24:[2,26],28:[2,26]}],defaultActions:{27:[2,23],29:[2,30],30:[2,31],31:[2,32]},parseError:function(e,t){if(!t.recoverable)throw new Error(e);this.trace(e)},parse:function(e){var t=this,i=[0],s=[null],r=[],n=this.table,o="",a=0,l=0,h=0,c=r.slice.call(arguments,1);this.lexer.setInput(e),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,void 0===this.lexer.yylloc&&(this.lexer.yylloc={});var u=this.lexer.yylloc;r.push(u);var d,_=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError?this.parseError=this.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var p,f,m,g,v,x,b,T,y,S={};;){if(m=i[i.length-1],this.defaultActions[m]?g=this.defaultActions[m]:(null==p&&(d=void 0,"number"!=typeof(d=t.lexer.lex()||1)&&(d=t.symbols_[d]||d),p=d),g=n[m]&&n[m][p]),void 0===g||!g.length||!g[0]){var C;for(x in y=[],n[m])this.terminals_[x]&&x>2&&y.push("'"+this.terminals_[x]+"'");C=this.lexer.showPosition?"Parse error on line "+(a+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+y.join(", ")+", got '"+(this.terminals_[p]||p)+"'":"Parse error on line "+(a+1)+": Unexpected "+(1==p?"end of input":"'"+(this.terminals_[p]||p)+"'"),this.parseError(C,{text:this.lexer.match,token:this.terminals_[p]||p,line:this.lexer.yylineno,loc:u,expected:y})}if(g[0]instanceof Array&&g.length>1)throw new Error("Parse Error: multiple actions possible at state: "+m+", token: "+p);switch(g[0]){case 1:i.push(p),s.push(this.lexer.yytext),r.push(this.lexer.yylloc),i.push(g[1]),p=null,f?(p=f,f=null):(l=this.lexer.yyleng,o=this.lexer.yytext,a=this.lexer.yylineno,u=this.lexer.yylloc,h>0&&h--);break;case 2:if(b=this.productions_[g[1]][1],S.$=s[s.length-b],S._$={first_line:r[r.length-(b||1)].first_line,last_line:r[r.length-1].last_line,first_column:r[r.length-(b||1)].first_column,last_column:r[r.length-1].last_column},_&&(S._$.range=[r[r.length-(b||1)].range[0],r[r.length-1].range[1]]),void 0!==(v=this.performAction.apply(S,[o,l,a,this.yy,g[1],s,r].concat(c))))return v;b&&(i=i.slice(0,-1*b*2),s=s.slice(0,-1*b),r=r.slice(0,-1*b)),i.push(this.productions_[g[1]][0]),s.push(S.$),r.push(S._$),T=n[i[i.length-2]][i[i.length-1]],i.push(T);break;case 3:return!0}}return!0}},t={initialize:function(){this._nodes=[],this._node={},this._stash=[]},set:function(e){for(var t in e)this._node[t]=e[t];return this._node},node:function(e){return arguments.length&&(this._node=e),this._node},push:function(){this._nodes.push(this._node),this._node={}},unshift:function(){this._nodes.unshift(this._node),this._node={}},yield:function(){var e=this._nodes;return this.initialize(),e}},i={EOF:1,parseError:function(e,t){if(!this.yy.parser)throw new Error(e);this.yy.parser.parseError(e,t)},setInput:function(e){return this._input=e,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},unput:function(e){var t=e.length,i=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t-1),this.offset-=t;var s=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),i.length-1&&(this.yylineno-=i.length-1);var r=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:i?(i.length===s.length?this.yylloc.first_column:0)+s[s.length-i.length].length-i[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[r[0],r[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(e){this.unput(this.match.slice(e))},pastInput:function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?"...":"")+e.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var e=this.pastInput(),t=new Array(e.length+1).join("-");return e+this.upcomingInput()+"\n"+t+"^"},test_match:function(e,t){var i,s,r;if(this.options.backtrack_lexer&&(r={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(r.yylloc.range=this.yylloc.range.slice(0))),(s=e[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=s.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:s?s[s.length-1].length-s[s.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],i=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),i)return i;if(this._backtrack){for(var n in r)this[n]=r[n];return!1}return!1},next:function(){if(this.done)return this.EOF;var e,t,i,s;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var r=this._currentRules(),n=0;nt[0].length)){if(t=i,s=n,this.options.backtrack_lexer){if(!1!==(e=this.test_match(i,r[n])))return e;if(this._backtrack){t=!1;continue}return!1}if(!this.options.flex)break}return t?!1!==(e=this.test_match(t,r[s]))&&e:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(e){this.conditionStack.push(e)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(e){return(e=this.conditionStack.length-1-Math.abs(e||0))>=0?this.conditionStack[e]:"INITIAL"},pushState:function(e){this.begin(e)},stateStackSize:function(){return this.conditionStack.length},options:{},performAction:function(e,t,i,s){switch(i){case 0:return 4;case 1:return 14;case 2:return 12;case 3:return 15;case 4:return 16;case 5:return 22;case 6:return 24;case 7:return 28;case 8:return 30;case 9:return 18;case 10:return t.yytext=t.yytext.substr(1,t.yyleng-2),32;case 11:return t.yytext=t.yytext.substr(1,t.yyleng-2),33;case 12:return 17;case 13:return 31}},rules:[/^(?:\$)/,/^(?:\.\.)/,/^(?:\.)/,/^(?:\*)/,/^(?:[a-zA-Z_]+[a-zA-Z0-9_]*)/,/^(?:\[)/,/^(?:\])/,/^(?:,)/,/^(?:((-?(?:0|[1-9][0-9]*)))?\:((-?(?:0|[1-9][0-9]*)))?(\:((-?(?:0|[1-9][0-9]*)))?)?)/,/^(?:(-?(?:0|[1-9][0-9]*)))/,/^(?:"(?:\\["bfnrt/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*")/,/^(?:'(?:\\['bfnrt/\\]|\\u[a-fA-F0-9]{4}|[^'\\])*')/,/^(?:\(.+?\)(?=\]))/,/^(?:\?\(.+?\)(?=\]))/],conditions:{INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,12,13],inclusive:!0}}};function s(){this.yy={}}return e.lexer=i,s.prototype=e,e.Parser=s,new s}();void 0!==e&&void 0!==i&&(i.parser=r,i.Parser=r.Parser,i.parse=function(){return r.parse.apply(r,arguments)},i.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),s.exit(1));var r=e("fs").readFileSync(e("path").normalize(t[1]),"utf8");return i.parser.parse(r)},void 0!==t&&e.main===t&&i.main(s.argv.slice(1)))}).call(this,e("_process"))},{_process:14,fs:12,path:13}],2:[function(e,t,i){t.exports={identifier:"[a-zA-Z_]+[a-zA-Z0-9_]*",integer:"-?(?:0|[1-9][0-9]*)",qq_string:'"(?:\\\\["bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4}|[^"\\\\])*"',q_string:"'(?:\\\\['bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4}|[^'\\\\])*'"}},{}],3:[function(e,t,i){var s=e("./dict"),r=e("fs"),n={lex:{macros:{esc:"\\\\",int:s.integer},rules:[["\\$","return 'DOLLAR'"],["\\.\\.","return 'DOT_DOT'"],["\\.","return 'DOT'"],["\\*","return 'STAR'"],[s.identifier,"return 'IDENTIFIER'"],["\\[","return '['"],["\\]","return ']'"],[",","return ','"],["({int})?\\:({int})?(\\:({int})?)?","return 'ARRAY_SLICE'"],["{int}","return 'INTEGER'"],[s.qq_string,"yytext = yytext.substr(1,yyleng-2); return 'QQ_STRING';"],[s.q_string,"yytext = yytext.substr(1,yyleng-2); return 'Q_STRING';"],["\\(.+?\\)(?=\\])","return 'SCRIPT_EXPRESSION'"],["\\?\\(.+?\\)(?=\\])","return 'FILTER_EXPRESSION'"]]},start:"JSON_PATH",bnf:{JSON_PATH:[["DOLLAR",'yy.ast.set({ expression: { type: "root", value: $1 } }); yy.ast.unshift(); return yy.ast.yield()'],["DOLLAR PATH_COMPONENTS",'yy.ast.set({ expression: { type: "root", value: $1 } }); yy.ast.unshift(); return yy.ast.yield()'],["LEADING_CHILD_MEMBER_EXPRESSION","yy.ast.unshift(); return yy.ast.yield()"],["LEADING_CHILD_MEMBER_EXPRESSION PATH_COMPONENTS",'yy.ast.set({ operation: "member", scope: "child", expression: { type: "identifier", value: $1 }}); yy.ast.unshift(); return yy.ast.yield()']],PATH_COMPONENTS:[["PATH_COMPONENT",""],["PATH_COMPONENTS PATH_COMPONENT",""]],PATH_COMPONENT:[["MEMBER_COMPONENT",'yy.ast.set({ operation: "member" }); yy.ast.push()'],["SUBSCRIPT_COMPONENT",'yy.ast.set({ operation: "subscript" }); yy.ast.push() ']],MEMBER_COMPONENT:[["CHILD_MEMBER_COMPONENT",'yy.ast.set({ scope: "child" })'],["DESCENDANT_MEMBER_COMPONENT",'yy.ast.set({ scope: "descendant" })']],CHILD_MEMBER_COMPONENT:[["DOT MEMBER_EXPRESSION",""]],LEADING_CHILD_MEMBER_EXPRESSION:[["MEMBER_EXPRESSION",'yy.ast.set({ scope: "child", operation: "member" })']],DESCENDANT_MEMBER_COMPONENT:[["DOT_DOT MEMBER_EXPRESSION",""]],MEMBER_EXPRESSION:[["STAR",'yy.ast.set({ expression: { type: "wildcard", value: $1 } })'],["IDENTIFIER",'yy.ast.set({ expression: { type: "identifier", value: $1 } })'],["SCRIPT_EXPRESSION",'yy.ast.set({ expression: { type: "script_expression", value: $1 } })'],["INTEGER",'yy.ast.set({ expression: { type: "numeric_literal", value: parseInt($1) } })'],["END",""]],SUBSCRIPT_COMPONENT:[["CHILD_SUBSCRIPT_COMPONENT",'yy.ast.set({ scope: "child" })'],["DESCENDANT_SUBSCRIPT_COMPONENT",'yy.ast.set({ scope: "descendant" })']],CHILD_SUBSCRIPT_COMPONENT:[["[ SUBSCRIPT ]",""]],DESCENDANT_SUBSCRIPT_COMPONENT:[["DOT_DOT [ SUBSCRIPT ]",""]],SUBSCRIPT:[["SUBSCRIPT_EXPRESSION",""],["SUBSCRIPT_EXPRESSION_LIST",'$1.length > 1? yy.ast.set({ expression: { type: "union", value: $1 } }) : $$ = $1']],SUBSCRIPT_EXPRESSION_LIST:[["SUBSCRIPT_EXPRESSION_LISTABLE","$$ = [$1]"],["SUBSCRIPT_EXPRESSION_LIST , SUBSCRIPT_EXPRESSION_LISTABLE","$$ = $1.concat($3)"]],SUBSCRIPT_EXPRESSION_LISTABLE:[["INTEGER",'$$ = { expression: { type: "numeric_literal", value: parseInt($1) } }; yy.ast.set($$)'],["STRING_LITERAL",'$$ = { expression: { type: "string_literal", value: $1 } }; yy.ast.set($$)'],["ARRAY_SLICE",'$$ = { expression: { type: "slice", value: $1 } }; yy.ast.set($$)']],SUBSCRIPT_EXPRESSION:[["STAR",'$$ = { expression: { type: "wildcard", value: $1 } }; yy.ast.set($$)'],["SCRIPT_EXPRESSION",'$$ = { expression: { type: "script_expression", value: $1 } }; yy.ast.set($$)'],["FILTER_EXPRESSION",'$$ = { expression: { type: "filter_expression", value: $1 } }; yy.ast.set($$)']],STRING_LITERAL:[["QQ_STRING","$$ = $1"],["Q_STRING","$$ = $1"]]}};r.readFileSync&&(n.moduleInclude=r.readFileSync(e.resolve("../include/module.js")),n.actionInclude=r.readFileSync(e.resolve("../include/action.js"))),t.exports=n},{"./dict":2,fs:12}],4:[function(e,t,i){var s=e("./aesprim"),r=e("./slice"),n=e("static-eval"),o=e("underscore").uniq,a=function(){return this.initialize.apply(this,arguments)};function l(t,i,r){var n=e("./index"),o=_(s.parse(i).body[0].expression,{"@":t.value}),a=r.replace(/\{\{\s*value\s*\}\}/g,o),l=n.nodes(t.value,a);return l.forEach((function(e){e.path=t.path.concat(e.path.slice(1))})),l}function h(e){return Array.isArray(e)}function c(e){return function(t,i,s,r){var n=t.value,o=t.path,a=[],l=function(t,n){var o;h(t)?(t.forEach((function(e,t){a.length>=r||s(t,e,i)&&a.push({path:n.concat(t),value:e})})),t.forEach((function(t,i){a.length>=r||e&&l(t,n.concat(i))}))):(o=t)&&!(o instanceof Array)&&o instanceof Object&&(this.keys(t).forEach((function(e){a.length>=r||s(e,t[e],i)&&a.push({path:n.concat(e),value:t[e]})})),this.keys(t).forEach((function(i){a.length>=r||e&&l(t[i],n.concat(i))})))}.bind(this);return l(n,o),a}}function u(e){return function(t,i,s){return this.descend(i,t.expression.value,e,s)}}function d(e){return function(t,i,s){return this.traverse(i,t.expression.value,e,s)}}function _(){try{return n.apply(this,arguments)}catch(e){}}function p(e){return e=e.filter((function(e){return e})),o(e,(function(e){return e.path.map((function(e){return String(e).replace("-","--")})).join("-")}))}function f(e){var t=String(e);return t.match(/^-?[0-9]+$/)?parseInt(t):null}a.prototype.initialize=function(){this.traverse=c(!0),this.descend=c()},a.prototype.keys=Object.keys,a.prototype.resolve=function(e){var t=[e.operation,e.scope,e.expression.type].join("-"),i=this._fns[t];if(!i)throw new Error("couldn't resolve key: "+t);return i.bind(this)},a.prototype.register=function(e,t){if(!t instanceof Function)throw new Error("handler must be a function");this._fns[e]=t},a.prototype._fns={"member-child-identifier":function(e,t){var i=e.expression.value,s=t.value;if(s instanceof Object&&i in s)return[{value:s[i],path:t.path.concat(i)}]},"member-descendant-identifier":d((function(e,t,i){return e==i})),"subscript-child-numeric_literal":u((function(e,t,i){return e===i})),"member-child-numeric_literal":u((function(e,t,i){return String(e)===String(i)})),"subscript-descendant-numeric_literal":d((function(e,t,i){return e===i})),"member-child-wildcard":u((function(){return!0})),"member-descendant-wildcard":d((function(){return!0})),"subscript-descendant-wildcard":d((function(){return!0})),"subscript-child-wildcard":u((function(){return!0})),"subscript-child-slice":function(e,t){if(h(t.value)){var i=e.expression.value.split(":").map(f),s=t.value.map((function(e,i){return{value:e,path:t.path.concat(i)}}));return r.apply(null,[s].concat(i))}},"subscript-child-union":function(e,t){var i=[];return e.expression.value.forEach((function(e){var s={operation:"subscript",scope:"child",expression:e.expression},r=this.resolve(s)(s,t);r&&(i=i.concat(r))}),this),p(i)},"subscript-descendant-union":function(t,i,s){var r=e(".."),n=this,o=[];return r.nodes(i,"$..*").slice(1).forEach((function(e){o.length>=s||t.expression.value.forEach((function(t){var i={operation:"subscript",scope:"child",expression:t.expression},s=n.resolve(i)(i,e);o=o.concat(s)}))})),p(o)},"subscript-child-filter_expression":function(e,t,i){var r=e.expression.value.slice(2,-1),n=s.parse(r).body[0].expression;return this.descend(t,null,(function(e,t){return _(n,{"@":t})}),i)},"subscript-descendant-filter_expression":function(e,t,i){var r=e.expression.value.slice(2,-1),n=s.parse(r).body[0].expression;return this.traverse(t,null,(function(e,t){return _(n,{"@":t})}),i)},"subscript-child-script_expression":function(e,t){return l(t,e.expression.value.slice(1,-1),"$[{{value}}]")},"member-child-script_expression":function(e,t){return l(t,e.expression.value.slice(1,-1),"$.{{value}}")},"member-descendant-script_expression":function(e,t){return l(t,e.expression.value.slice(1,-1),"$..value")}},a.prototype._fns["subscript-child-string_literal"]=a.prototype._fns["member-child-identifier"],a.prototype._fns["member-descendant-numeric_literal"]=a.prototype._fns["subscript-descendant-string_literal"]=a.prototype._fns["member-descendant-identifier"],t.exports=a},{"..":"jsonpath","./aesprim":"./aesprim","./index":5,"./slice":7,"static-eval":15,underscore:12}],5:[function(e,t,i){var s=e("assert"),r=e("./dict"),n=e("./parser"),o=e("./handlers"),a=function(){this.initialize.apply(this,arguments)};function l(e){return"[object String]"==Object.prototype.toString.call(e)}a.prototype.initialize=function(){this.parser=new n,this.handlers=new o},a.prototype.parse=function(e){return s.ok(l(e),"we need a path"),this.parser.parse(e)},a.prototype.parent=function(e,t){s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path");var i=this.nodes(e,t)[0];return i.path.pop(),this.value(e,i.path)},a.prototype.apply=function(e,t,i){s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),s.equal(typeof i,"function","fn needs to be function");var r=this.nodes(e,t).sort((function(e,t){return t.path.length-e.path.length}));return r.forEach((function(t){var s=t.path.pop(),r=this.value(e,this.stringify(t.path)),n=t.value=i.call(e,r[s]);r[s]=n}),this),r},a.prototype.value=function(e,t,i){if(s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),arguments.length>=3){var r=this.nodes(e,t).shift();if(!r)return this._vivify(e,t,i);var n=r.path.slice(-1).shift();this.parent(e,this.stringify(r.path))[n]=i}return this.query(e,this.stringify(t),1).shift()},a.prototype._vivify=function(e,t,i){var r=this;s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path");var n=this.parser.parse(t).map((function(e){return e.expression.value})),o=function(t,i){var s=t.pop(),n=r.value(e,t);n||(o(t.concat(),"string"==typeof s?{}:[]),n=r.value(e,t)),n[s]=i};return o(n,i),this.query(e,t)[0]},a.prototype.query=function(e,t,i){return s.ok(e instanceof Object,"obj needs to be an object"),s.ok(l(t),"we need a path"),this.nodes(e,t,i).map((function(e){return e.value}))},a.prototype.paths=function(e,t,i){return s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),this.nodes(e,t,i).map((function(e){return e.path}))},a.prototype.nodes=function(e,t,i){if(s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),0===i)return[];var r=this.parser.parse(t),n=this.handlers,o=[{path:["$"],value:e}],a=[];return r.length&&"root"==r[0].expression.type&&r.shift(),r.length?(r.forEach((function(e,t){if(!(a.length>=i)){var s=n.resolve(e),l=[];o.forEach((function(n){if(!(a.length>=i)){var o=s(e,n,i);t==r.length-1?a=a.concat(o||[]):l=l.concat(o||[])}})),o=l}})),i?a.slice(0,i):a):o},a.prototype.stringify=function(e){s.ok(e,"we need a path");var t="$",i={"descendant-member":"..{{value}}","child-member":".{{value}}","descendant-subscript":"..[{{value}}]","child-subscript":"[{{value}}]"};return(e=this._normalize(e)).forEach((function(e){if("root"!=e.expression.type){var s,r=[e.scope,e.operation].join("-"),n=i[r];if(s="string_literal"==e.expression.type?JSON.stringify(e.expression.value):e.expression.value,!n)throw new Error("couldn't find template "+r);t+=n.replace(/{{value}}/,s)}})),t},a.prototype._normalize=function(e){if(s.ok(e,"we need a path"),"string"==typeof e)return this.parser.parse(e);if(Array.isArray(e)&&"string"==typeof e[0]){var t=[{expression:{type:"root",value:"$"}}];return e.forEach((function(e,i){if("$"!=e||0!==i)if("string"==typeof e&&e.match("^"+r.identifier+"$"))t.push({operation:"member",scope:"child",expression:{value:e,type:"identifier"}});else{var s="number"==typeof e?"numeric_literal":"string_literal";t.push({operation:"subscript",scope:"child",expression:{value:e,type:s}})}})),t}if(Array.isArray(e)&&"object"==typeof e[0])return e;throw new Error("couldn't understand path "+e)},a.Handlers=o,a.Parser=n;var h=new a;h.JSONPath=a,t.exports=h},{"./dict":2,"./handlers":4,"./parser":6,assert:8}],6:[function(e,t,i){var s=e("./grammar"),r=e("../generated/parser"),n=function(){var e=new r.Parser,t=e.parseError;return e.yy.parseError=function(){e.yy.ast&&e.yy.ast.initialize(),t.apply(e,arguments)},e};n.grammar=s,t.exports=n},{"../generated/parser":1,"./grammar":3}],7:[function(e,t,i){function s(e){return String(e).match(/^[0-9]+$/)?parseInt(e):Number.isFinite(e)?parseInt(e,10):0}t.exports=function(e,t,i,r){if("string"==typeof t)throw new Error("start cannot be a string");if("string"==typeof i)throw new Error("end cannot be a string");if("string"==typeof r)throw new Error("step cannot be a string");var n=e.length;if(0===r)throw new Error("step cannot be zero");if(r=r?s(r):1,i=i<0?n+i:i,t=s(0===(t=t<0?n+t:t)?0:t||(r>0?0:n-1)),i=s(0===i?0:i||(r>0?n:-1)),t=r>0?Math.max(0,t):Math.min(n,t),i=r>0?Math.min(i,n):Math.max(-1,i),r>0&&i<=t)return[];if(r<0&&t<=i)return[];for(var o=[],a=t;a!=i&&!(r<0&&a<=i||r>0&&a>=i);a+=r)o.push(e[a]);return o}},{}],8:[function(e,t,i){var s=e("util/"),r=Array.prototype.slice,n=Object.prototype.hasOwnProperty,o=t.exports=c;function a(e,t){return s.isUndefined(t)?""+t:s.isNumber(t)&&!isFinite(t)||s.isFunction(t)||s.isRegExp(t)?t.toString():t}function l(e,t){return s.isString(e)?e.length=0;a--)if(l[a]!=h[a])return!1;for(a=l.length-1;a>=0;a--)if(!u(e[o=l[a]],t[o]))return!1;return!0}(e,t):e==t}function d(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function _(e,t){return!(!e||!t)&&("[object RegExp]"==Object.prototype.toString.call(t)?t.test(e):e instanceof t||!0===t.call({},e))}function p(e,t,i,r){var n;s.isString(i)&&(r=i,i=null);try{t()}catch(e){n=e}if(r=(i&&i.name?" ("+i.name+").":".")+(r?" "+r:"."),e&&!n&&h(n,i,"Missing expected exception"+r),!e&&_(n,i)&&h(n,i,"Got unwanted exception"+r),e&&n&&i&&!_(n,i)||!e&&n)throw n}o.AssertionError=function(e){this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=function(e){return l(JSON.stringify(e.actual,a),128)+" "+e.operator+" "+l(JSON.stringify(e.expected,a),128)}(this),this.generatedMessage=!0);var t=e.stackStartFunction||h;if(Error.captureStackTrace)Error.captureStackTrace(this,t);else{var i=new Error;if(i.stack){var s=i.stack,r=t.name,n=s.indexOf("\n"+r);if(n>=0){var o=s.indexOf("\n",n+1);s=s.substring(o+1)}this.stack=s}}},s.inherits(o.AssertionError,Error),o.fail=h,o.ok=c,o.equal=function(e,t,i){e!=t&&h(e,t,i,"==",o.equal)},o.notEqual=function(e,t,i){e==t&&h(e,t,i,"!=",o.notEqual)},o.deepEqual=function(e,t,i){u(e,t)||h(e,t,i,"deepEqual",o.deepEqual)},o.notDeepEqual=function(e,t,i){u(e,t)&&h(e,t,i,"notDeepEqual",o.notDeepEqual)},o.strictEqual=function(e,t,i){e!==t&&h(e,t,i,"===",o.strictEqual)},o.notStrictEqual=function(e,t,i){e===t&&h(e,t,i,"!==",o.notStrictEqual)},o.throws=function(e,t,i){p.apply(this,[!0].concat(r.call(arguments)))},o.doesNotThrow=function(e,t){p.apply(this,[!1].concat(r.call(arguments)))},o.ifError=function(e){if(e)throw e};var f=Object.keys||function(e){var t=[];for(var i in e)n.call(e,i)&&t.push(i);return t}},{"util/":11}],9:[function(e,t,i){"function"==typeof Object.create?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e}},{}],10:[function(e,t,i){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],11:[function(e,t,s){(function(t,i){var r=/%[sdj%]/g;s.format=function(e){if(!g(e)){for(var t=[],i=0;i=n)return e;switch(e){case"%s":return String(s[i++]);case"%d":return Number(s[i++]);case"%j":try{return JSON.stringify(s[i++])}catch(e){return"[Circular]"}default:return e}})),l=s[i];i=3&&(i.depth=arguments[2]),arguments.length>=4&&(i.colors=arguments[3]),p(t)?i.showHidden=t:t&&s._extend(i,t),v(i.showHidden)&&(i.showHidden=!1),v(i.depth)&&(i.depth=2),v(i.colors)&&(i.colors=!1),v(i.customInspect)&&(i.customInspect=!0),i.colors&&(i.stylize=l),c(i,e,i.depth)}function l(e,t){var i=a.styles[t];return i?"["+a.colors[i][0]+"m"+e+"["+a.colors[i][1]+"m":e}function h(e,t){return e}function c(e,t,i){if(e.customInspect&&t&&S(t.inspect)&&t.inspect!==s.inspect&&(!t.constructor||t.constructor.prototype!==t)){var r=t.inspect(i,e);return g(r)||(r=c(e,r,i)),r}var n=function(e,t){if(v(t))return e.stylize("undefined","undefined");if(g(t)){var i="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(i,"string")}return m(t)?e.stylize(""+t,"number"):p(t)?e.stylize(""+t,"boolean"):f(t)?e.stylize("null","null"):void 0}(e,t);if(n)return n;var o=Object.keys(t),a=function(e){var t={};return e.forEach((function(e,i){t[e]=!0})),t}(o);if(e.showHidden&&(o=Object.getOwnPropertyNames(t)),y(t)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return u(t);if(0===o.length){if(S(t)){var l=t.name?": "+t.name:"";return e.stylize("[Function"+l+"]","special")}if(x(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(T(t))return e.stylize(Date.prototype.toString.call(t),"date");if(y(t))return u(t)}var h,b="",C=!1,E=["{","}"];return _(t)&&(C=!0,E=["[","]"]),S(t)&&(b=" [Function"+(t.name?": "+t.name:"")+"]"),x(t)&&(b=" "+RegExp.prototype.toString.call(t)),T(t)&&(b=" "+Date.prototype.toUTCString.call(t)),y(t)&&(b=" "+u(t)),0!==o.length||C&&0!=t.length?i<0?x(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),h=C?function(e,t,i,s,r){for(var n=[],o=0,a=t.length;o60?i[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+i[1]:i[0]+t+" "+e.join(", ")+" "+i[1]}(h,b,E)):E[0]+b+E[1]}function u(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,i,s,r,n){var o,a,l;if((l=Object.getOwnPropertyDescriptor(t,r)||{value:t[r]}).get?a=l.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):l.set&&(a=e.stylize("[Setter]","special")),P(s,r)||(o="["+r+"]"),a||(e.seen.indexOf(l.value)<0?(a=f(i)?c(e,l.value,null):c(e,l.value,i-1)).indexOf("\n")>-1&&(a=n?a.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+a.split("\n").map((function(e){return" "+e})).join("\n")):a=e.stylize("[Circular]","special")),v(o)){if(n&&r.match(/^\d+$/))return a;(o=JSON.stringify(""+r)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+a}function _(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function f(e){return null===e}function m(e){return"number"==typeof e}function g(e){return"string"==typeof e}function v(e){return void 0===e}function x(e){return b(e)&&"[object RegExp]"===C(e)}function b(e){return"object"==typeof e&&null!==e}function T(e){return b(e)&&"[object Date]"===C(e)}function y(e){return b(e)&&("[object Error]"===C(e)||e instanceof Error)}function S(e){return"function"==typeof e}function C(e){return Object.prototype.toString.call(e)}function E(e){return e<10?"0"+e.toString(10):e.toString(10)}s.debuglog=function(e){if(v(n)&&(n=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!o[e])if(new RegExp("\\b"+e+"\\b","i").test(n)){var i=t.pid;o[e]=function(){var t=s.format.apply(s,arguments);console.error("%s %d: %s",e,i,t)}}else o[e]=function(){};return o[e]},s.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},s.isArray=_,s.isBoolean=p,s.isNull=f,s.isNullOrUndefined=function(e){return null==e},s.isNumber=m,s.isString=g,s.isSymbol=function(e){return"symbol"==typeof e},s.isUndefined=v,s.isRegExp=x,s.isObject=b,s.isDate=T,s.isError=y,s.isFunction=S,s.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},s.isBuffer=e("./support/isBuffer");var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function P(e,t){return Object.prototype.hasOwnProperty.call(e,t)}s.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[E(e.getHours()),E(e.getMinutes()),E(e.getSeconds())].join(":"),[e.getDate(),A[e.getMonth()],t].join(" ")),s.format.apply(s,arguments))},s.inherits=e("inherits"),s._extend=function(e,t){if(!t||!b(t))return e;for(var i=Object.keys(t),s=i.length;s--;)e[i[s]]=t[i[s]];return e}}).call(this,e("_process"),void 0!==i.g?i.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":10,_process:14,inherits:9}],12:[function(e,t,i){},{}],13:[function(e,t,i){(function(e){function t(e,t){for(var i=0,s=e.length-1;s>=0;s--){var r=e[s];"."===r?e.splice(s,1):".."===r?(e.splice(s,1),i++):i&&(e.splice(s,1),i--)}if(t)for(;i--;i)e.unshift("..");return e}function s(e,t){if(e.filter)return e.filter(t);for(var i=[],s=0;s=-1&&!r;n--){var o=n>=0?arguments[n]:e.cwd();if("string"!=typeof o)throw new TypeError("Arguments to path.resolve must be strings");o&&(i=o+"/"+i,r="/"===o.charAt(0))}return(r?"/":"")+(i=t(s(i.split("/"),(function(e){return!!e})),!r).join("/"))||"."},i.normalize=function(e){var n=i.isAbsolute(e),o="/"===r(e,-1);return(e=t(s(e.split("/"),(function(e){return!!e})),!n).join("/"))||n||(e="."),e&&o&&(e+="/"),(n?"/":"")+e},i.isAbsolute=function(e){return"/"===e.charAt(0)},i.join=function(){var e=Array.prototype.slice.call(arguments,0);return i.normalize(s(e,(function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e})).join("/"))},i.relative=function(e,t){function s(e){for(var t=0;t=0&&""===e[i];i--);return t>i?[]:e.slice(t,i-t+1)}e=i.resolve(e).substr(1),t=i.resolve(t).substr(1);for(var r=s(e.split("/")),n=s(t.split("/")),o=Math.min(r.length,n.length),a=o,l=0;l=1;--n)if(47===(t=e.charCodeAt(n))){if(!r){s=n;break}}else r=!1;return-1===s?i?"/":".":i&&1===s?"/":e.slice(0,s)},i.basename=function(e,t){var i=function(e){"string"!=typeof e&&(e+="");var t,i=0,s=-1,r=!0;for(t=e.length-1;t>=0;--t)if(47===e.charCodeAt(t)){if(!r){i=t+1;break}}else-1===s&&(r=!1,s=t+1);return-1===s?"":e.slice(i,s)}(e);return t&&i.substr(-1*t.length)===t&&(i=i.substr(0,i.length-t.length)),i},i.extname=function(e){"string"!=typeof e&&(e+="");for(var t=-1,i=0,s=-1,r=!0,n=0,o=e.length-1;o>=0;--o){var a=e.charCodeAt(o);if(47!==a)-1===s&&(r=!1,s=o+1),46===a?-1===t?t=o:1!==n&&(n=1):-1!==t&&(n=-1);else if(!r){i=o+1;break}}return-1===t||-1===s||0===n||1===n&&t===s-1&&t===i+1?"":e.slice(t,s)};var r=function(e,t,i){return e.substr(t,i)}}).call(this,e("_process"))},{_process:14}],14:[function(e,t,i){var s,r,n=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function l(e){if(s===setTimeout)return setTimeout(e,0);if((s===o||!s)&&setTimeout)return s=setTimeout,setTimeout(e,0);try{return s(e,0)}catch(t){try{return s.call(null,e,0)}catch(t){return s.call(this,e,0)}}}!function(){try{s="function"==typeof setTimeout?setTimeout:o}catch(e){s=o}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(e){r=a}}();var h,c=[],u=!1,d=-1;function _(){u&&h&&(u=!1,h.length?c=h.concat(c):d=-1,c.length&&p())}function p(){if(!u){var e=l(_);u=!0;for(var t=c.length;t;){for(h=c,c=[];++d1)for(var i=1;i"===_?h>d:">="===_?h>=d:"|"===_?h|d:"&"===_?h&d:"^"===_?h^d:"&&"===_?h&&d:"||"===_?h||d:i}if("Identifier"===r.type)return{}.hasOwnProperty.call(t,r.name)?t[r.name]:i;if("ThisExpression"===r.type)return{}.hasOwnProperty.call(t,"this")?t.this:i;if("CallExpression"===r.type){var p=e(r.callee);if(p===i)return i;if("function"!=typeof p)return i;var f=r.callee.object?e(r.callee.object):i;f===i&&(f=null);var m=[];for(l=0,h=r.arguments.length;l{e.exports=function(){var e={},t=this,i=(new Function("try {return this===window;}catch(e){ return false;}"),new Function("try {return this===global;}catch(e){return false;}")),s=new Function("try {return typeof importScripts === 'function';}catch(e){return false;}");if(i()&&s(),i()||s()){var r=t;if(s()){onmessage=function(e){if(e.data.className&&e.data.methodName){var i=(s=e.data.className,r=e.data.methodName,n=t,s.split(".").forEach((function(e){n&&(n=n[e])})),n?n[r]:null);if(!i)return console.error("could not find "+e.data.className+"."+e.data.methodName);postMessage({result:i.apply(null,e.data.args),id:e.data.id})}var s,r,n}}}return function(e,t,i){"use strict";t.geom=t.geom||{},t.exe=t.exe||{},t.eval=t.eval||{},t.core=t.core||{},t.promhx=t.promhx||{};var s={},r=function(){return P.__string_rec(this,"")};function n(e,t){function i(){}i.prototype=e;var s=new i;for(var r in t)s[r]=t[r];return t.toString!==Object.prototype.toString&&(s.toString=t.toString),s}var o=function(){};s.HxOverrides=o,o.__name__=["HxOverrides"],o.strDate=function(e){switch(e.length){case 8:var t=e.split(":"),i=new Date;return i.setTime(0),i.setUTCHours(t[0]),i.setUTCMinutes(t[1]),i.setUTCSeconds(t[2]),i;case 10:var s=e.split("-");return new Date(s[0],s[1]-1,s[2],0,0,0);case 19:var r=e.split(" "),n=r[0].split("-"),o=r[1].split(":");return new Date(n[0],n[1]-1,n[2],o[0],o[1],o[2]);default:throw new A("Invalid date format : "+e)}},o.cca=function(e,t){var i=e.charCodeAt(t);if(i==i)return i},o.substr=function(e,t,i){return null!=t&&0!=t&&null!=i&&i<0?"":(null==i&&(i=e.length),t<0?(t=e.length+t)<0&&(t=0):i<0&&(i=e.length+i-t),e.substr(t,i))},o.iter=function(e){return{cur:0,arr:e,hasNext:function(){return this.cur0&&(1==n?this.buf.b+="n":(this.buf.b+="u",this.buf.b+=null==n?"null":""+n),n=0),this.serialize(e[d]))}n>0&&(1==n?this.buf.b+="n":(this.buf.b+="u",this.buf.b+=null==n?"null":""+n)),this.buf.b+="h";break;case l:this.buf.b+="l";for(var _=e.h,f=null;null!=_;){var m;f=_[0],_=_[1],m=f,this.serialize(m)}this.buf.b+="h";break;case Date:var v=e;this.buf.b+="v",this.buf.add(v.getTime());break;case y:this.buf.b+="b";for(var T=e,C=T.keys();C.hasNext();){var E=C.next();this.serializeString(E),this.serialize(null!=ft[E]?T.getReserved(E):T.h[E])}this.buf.b+="h";break;case x:this.buf.b+="q";for(var I=e,R=I.keys();R.hasNext();){var M=R.next();this.buf.b+=":",this.buf.b+=null==M?"null":""+M,this.serialize(I.h[M])}this.buf.b+="h";break;case b:this.buf.b+="M";for(var O=e,D=O.keys();D.hasNext();){var w=D.next(),N=h.field(w,"__id__");h.deleteField(w,"__id__"),this.serialize(w),w.__id__=N,this.serialize(O.h[w.__id__])}this.buf.b+="h";break;case S:for(var F=e,L=0,B=F.length-2,k=new u,V=g.BASE64;L>2)),k.add(V.charAt(63&(U<<4|G>>4))),k.add(V.charAt(63&(G<<2|z>>6))),k.add(V.charAt(63&z))}if(L==B){var W=F.get(L++),H=F.get(L++);k.add(V.charAt(W>>2)),k.add(V.charAt(63&(W<<4|H>>4))),k.add(V.charAt(H<<2&63))}else if(L==B+1){var X=F.get(L++);k.add(V.charAt(X>>2)),k.add(V.charAt(X<<4&63))}var Y=k.b;this.buf.b+="s",null==Y.length?this.buf.b+="null":this.buf.b+=""+Y.length,this.buf.b+=":",this.buf.b+=null==Y?"null":""+Y;break;default:this.useCache&&this.cache.pop(),null!=e.hxSerialize?(this.buf.b+="C",this.serializeString(p.getClassName(r)),this.useCache&&this.cache.push(e),e.hxSerialize(this),this.buf.b+="g"):(this.buf.b+="c",this.serializeString(p.getClassName(r)),this.useCache&&this.cache.push(e),this.serializeFields(e))}break;case 4:if(P.__instanceof(e,_t)){var Q=p.getClassName(e);this.buf.b+="A",this.serializeString(Q)}else if(P.__instanceof(e,pt))this.buf.b+="B",this.serializeString(p.getEnumName(e));else{if(this.useCache&&this.serializeRef(e))return;this.buf.b+="o",this.serializeFields(e)}break;case 7:var j=t[2];if(this.useCache){if(this.serializeRef(e))return;this.cache.pop()}this.useEnumIndex?this.buf.b+="j":this.buf.b+="w",this.serializeString(p.getEnumName(j)),this.useEnumIndex?(this.buf.b+=":",this.buf.b+=c.string(e[1])):this.serializeString(e[0]),this.buf.b+=":";var K=e.length;this.buf.b+=c.string(K-2);for(var $=2;$57)break;e=10*e+(s-48),this.pos++}else{if(this.pos!=i)break;t=!0,this.pos++}}return t&&(e*=-1),e},readFloat:function(){for(var e=this.pos;;){var t=this.buf.charCodeAt(this.pos);if(!(t>=43&&t<58||101==t||69==t))break;this.pos++}return c.parseFloat(o.substr(this.buf,e,this.pos-e))},unserializeObject:function(e){for(;;){if(this.pos>=this.length)throw new A("Invalid object");if(103==this.buf.charCodeAt(this.pos))break;var t=this.unserialize();if("string"!=typeof t)throw new A("Invalid object key");var i=this.unserialize();e[t]=i}this.pos++},unserializeEnum:function(e,t){if(58!=this.get(this.pos++))throw new A("Invalid enum format");var i=this.readDigits();if(0==i)return p.createEnum(e,t);for(var s=[];i-- >0;)s.push(this.unserialize());return p.createEnum(e,t,s)},unserialize:function(){switch(this.get(this.pos++)){case 110:return null;case 116:return!0;case 102:return!1;case 122:return 0;case 105:return this.readDigits();case 100:return this.readFloat();case 121:var e=this.readDigits();if(58!=this.get(this.pos++)||this.length-this.pos=this.cache.length)throw new A("Invalid reference");return this.cache[a];case 82:var h=this.readDigits();if(h<0||h>=this.scache.length)throw new A("Invalid string reference");return this.scache[h];case 120:throw new A(this.unserialize());case 99:var c=this.unserialize(),u=this.resolver.resolveClass(c);if(null==u)throw new A("Class not found "+c);var _=p.createEmptyInstance(u);return this.cache.push(_),this.unserializeObject(_),_;case 119:var f=this.unserialize(),m=this.resolver.resolveEnum(f);if(null==m)throw new A("Enum not found "+f);var g=this.unserializeEnum(m,this.unserialize());return this.cache.push(g),g;case 106:var T=this.unserialize(),C=this.resolver.resolveEnum(T);if(null==C)throw new A("Enum not found "+T);this.pos++;var E=this.readDigits(),P=p.getEnumConstructs(C)[E];if(null==P)throw new A("Unknown enum index "+T+"@"+E);var I=this.unserializeEnum(C,P);return this.cache.push(I),I;case 108:var R=new l;for(this.cache.push(R),this.buf;104!=this.buf.charCodeAt(this.pos);)R.add(this.unserialize());return this.pos++,R;case 98:var M=new y;for(this.cache.push(M),this.buf;104!=this.buf.charCodeAt(this.pos);){var O=this.unserialize();M.set(O,this.unserialize())}return this.pos++,M;case 113:var D=new x;this.cache.push(D),this.buf;for(var w=this.get(this.pos++);58==w;){var N=this.readDigits();D.set(N,this.unserialize()),w=this.get(this.pos++)}if(104!=w)throw new A("Invalid IntMap format");return D;case 77:var F=new b;for(this.cache.push(F),this.buf;104!=this.buf.charCodeAt(this.pos);){var L=this.unserialize();F.set(L,this.unserialize())}return this.pos++,F;case 118:var B;if(this.buf.charCodeAt(this.pos)>=48&&this.buf.charCodeAt(this.pos)<=57&&this.buf.charCodeAt(this.pos+1)>=48&&this.buf.charCodeAt(this.pos+1)<=57&&this.buf.charCodeAt(this.pos+2)>=48&&this.buf.charCodeAt(this.pos+2)<=57&&this.buf.charCodeAt(this.pos+3)>=48&&this.buf.charCodeAt(this.pos+3)<=57&&45==this.buf.charCodeAt(this.pos+4)){var k=o.substr(this.buf,this.pos,19);B=o.strDate(k),this.pos+=19}else{var V=this.readFloat(),U=new Date;U.setTime(V),B=U}return this.cache.push(B),B;case 115:var G=this.readDigits(),z=this.buf;if(58!=this.get(this.pos++)||this.length-this.pos>2)+(Y>=2?Y-1:0);for(var Q=X+(G-Y),j=S.alloc(H),K=0;X>4);var Z=W[d.fastCodeAt(z,X++)];j.set(K++,q<<4|Z>>2);var J=W[d.fastCodeAt(z,X++)];j.set(K++,Z<<6|J)}if(Y>=2){var ee=W[d.fastCodeAt(z,X++)],te=W[d.fastCodeAt(z,X++)];if(j.set(K++,ee<<2|te>>4),3==Y){var ie=W[d.fastCodeAt(z,X++)];j.set(K++,te<<4|ie>>2)}}return this.pos+=G,this.cache.push(j),j;case 67:var se=this.unserialize(),re=this.resolver.resolveClass(se);if(null==re)throw new A("Class not found "+se);var ne=p.createEmptyInstance(re);if(this.cache.push(ne),ne.hxUnserialize(this),103!=this.get(this.pos++))throw new A("Invalid custom data");return ne;case 65:var oe=this.unserialize(),ae=this.resolver.resolveClass(oe);if(null==ae)throw new A("Class not found "+oe);return ae;case 66:var le=this.unserialize(),he=this.resolver.resolveEnum(le);if(null==he)throw new A("Enum not found "+le);return he}throw this.pos--,new A("Invalid char "+this.buf.charAt(this.pos)+" at position "+this.pos)},__class__:v};var x=function(){this.h={}};s["haxe.ds.IntMap"]=x,x.__name__=["haxe","ds","IntMap"],x.__interfaces__=[f],x.prototype={set:function(e,t){this.h[e]=t},remove:function(e){return!!this.h.hasOwnProperty(e)&&(delete this.h[e],!0)},keys:function(){var e=[];for(var t in this.h)this.h.hasOwnProperty(t)&&e.push(0|t);return o.iter(e)},__class__:x};var b=function(){this.h={},this.h.__keys__={}};s["haxe.ds.ObjectMap"]=b,b.__name__=["haxe","ds","ObjectMap"],b.__interfaces__=[f],b.prototype={set:function(e,t){var i=e.__id__||(e.__id__=++b.count);this.h[i]=t,this.h.__keys__[i]=e},keys:function(){var e=[];for(var t in this.h.__keys__)this.h.hasOwnProperty(t)&&e.push(this.h.__keys__[t]);return o.iter(e)},__class__:b};var T=s["haxe.ds.Option"]={__ename__:["haxe","ds","Option"],__constructs__:["Some","None"]};T.Some=function(e){var t=["Some",0,e];return t.__enum__=T,t.toString=r,t},T.None=["None",1],T.None.toString=r,T.None.__enum__=T;var y=function(){this.h={}};s["haxe.ds.StringMap"]=y,y.__name__=["haxe","ds","StringMap"],y.__interfaces__=[f],y.prototype={set:function(e,t){null!=ft[e]?this.setReserved(e,t):this.h[e]=t},get:function(e){return null!=ft[e]?this.getReserved(e):this.h[e]},setReserved:function(e,t){null==this.rh&&(this.rh={}),this.rh["$"+e]=t},getReserved:function(e){return null==this.rh?null:this.rh["$"+e]},keys:function(){var e=this.arrayKeys();return o.iter(e)},arrayKeys:function(){var e=[];for(var t in this.h)this.h.hasOwnProperty(t)&&e.push(t);if(null!=this.rh)for(var t in this.rh)36==t.charCodeAt(0)&&e.push(t.substr(1));return e},__class__:y};var S=function(e){this.length=e.byteLength,this.b=new gt(e),this.b.bufferValue=e,e.hxBytes=this,e.bytes=this.b};s["haxe.io.Bytes"]=S,S.__name__=["haxe","io","Bytes"],S.alloc=function(e){return new S(new mt(e))},S.prototype={get:function(e){return this.b[e]},set:function(e,t){this.b[e]=255&t},__class__:S};var C=s["haxe.io.Error"]={__ename__:["haxe","io","Error"],__constructs__:["Blocked","Overflow","OutsideBounds","Custom"]};C.Blocked=["Blocked",0],C.Blocked.toString=r,C.Blocked.__enum__=C,C.Overflow=["Overflow",1],C.Overflow.toString=r,C.Overflow.__enum__=C,C.OutsideBounds=["OutsideBounds",2],C.OutsideBounds.toString=r,C.OutsideBounds.__enum__=C,C.Custom=function(e){var t=["Custom",3,e];return t.__enum__=C,t.toString=r,t};var E=function(){};s["haxe.io.FPHelper"]=E,E.__name__=["haxe","io","FPHelper"],E.i32ToFloat=function(e){var t=e>>>23&255,i=8388607&e;return 0==i&&0==t?0:(1-(e>>>31<<1))*(1+Math.pow(2,-23)*i)*Math.pow(2,t-127)},E.floatToI32=function(e){if(0==e)return 0;var t;t=e<0?-e:e;var i=Math.floor(Math.log(t)/.6931471805599453);return i<-127?i=-127:i>128&&(i=128),(e<0?-2147483648:0)|i+127<<23|8388607&Math.round(8388608*(t/Math.pow(2,i)-1))},E.i64ToDouble=function(e,t){var i=(t>>20&2047)-1023,s=4294967296*(1048575&t)+2147483648*(e>>>31)+(2147483647&e);return 0==s&&-1023==i?0:(1-(t>>>31<<1))*(1+Math.pow(2,-52)*s)*Math.pow(2,i)},E.doubleToI64=function(e){var t=E.i64tmp;if(0==e)t.low=0,t.high=0;else{var i;i=e<0?-e:e;var s,r=Math.floor(Math.log(i)/.6931471805599453),n=4503599627370496*(i/Math.pow(2,r)-1),o=0|(s=Math.round(n)),a=s/4294967296|0;t.low=o,t.high=(e<0?-2147483648:0)|r+1023<<20|a}return t};var A=function(e){Error.call(this),this.val=e,this.message=String(e),Error.captureStackTrace&&Error.captureStackTrace(this,A)};s["js._Boot.HaxeError"]=A,A.__name__=["js","_Boot","HaxeError"],A.__super__=Error,A.prototype=n(Error.prototype,{__class__:A});var P=function(){};s["js.Boot"]=P,P.__name__=["js","Boot"],P.getClass=function(e){if(e instanceof Array&&null==e.__enum__)return Array;var t=e.__class__;if(null!=t)return t;var i=P.__nativeClassName(e);return null!=i?P.__resolveNativeClass(i):null},P.__string_rec=function(e,t){if(null==e)return"null";if(t.length>=5)return"<...>";var i=typeof e;switch("function"==i&&(e.__name__||e.__ename__)&&(i="object"),i){case"object":if(e instanceof Array){if(e.__enum__){if(2==e.length)return e[0];var s=e[0]+"(";t+="\t";for(var r=2,n=e.length;r0?",":"")+P.__string_rec(e[c],t)}return l+"]"}var u;try{u=e.toString}catch(e){return e instanceof A&&(e=e.val),"???"}if(null!=u&&u!=Object.toString&&"function"==typeof u){var d=e.toString();if("[object Object]"!=d)return d}var _=null,p="{\n";t+="\t";var f=null!=e.hasOwnProperty;for(var _ in e)f&&!e.hasOwnProperty(_)||"prototype"!=_&&"__class__"!=_&&"__super__"!=_&&"__interfaces__"!=_&&"__properties__"!=_&&(2!=p.length&&(p+=", \n"),p+=t+_+" : "+P.__string_rec(e[_],t));return p+"\n"+(t=t.substring(1))+"}";case"function":return"";case"string":return e;default:return String(e)}},P.__interfLoop=function(e,t){if(null==e)return!1;if(e==t)return!0;var i=e.__interfaces__;if(null!=i)for(var s=0,r=i.length;se.byteLength)throw new A(C.OutsideBounds)};s["js.html.compat.DataView"]=R,R.__name__=["js","html","compat","DataView"],R.prototype={getInt8:function(e){var t=this.buf.a[this.offset+e];return t>=128?t-256:t},getUint8:function(e){return this.buf.a[this.offset+e]},getInt16:function(e,t){var i=this.getUint16(e,t);return i>=32768?i-65536:i},getUint16:function(e,t){return t?this.buf.a[this.offset+e]|this.buf.a[this.offset+e+1]<<8:this.buf.a[this.offset+e]<<8|this.buf.a[this.offset+e+1]},getInt32:function(e,t){var i=this.offset+e,s=this.buf.a[i++],r=this.buf.a[i++],n=this.buf.a[i++],o=this.buf.a[i++];return t?s|r<<8|n<<16|o<<24:o|n<<8|r<<16|s<<24},getUint32:function(e,t){var i=this.getInt32(e,t);return i<0?i+4294967296:i},getFloat32:function(e,t){return E.i32ToFloat(this.getInt32(e,t))},getFloat64:function(e,t){var i=this.getInt32(e,t),s=this.getInt32(e+4,t);return E.i64ToDouble(t?i:s,t?s:i)},setInt8:function(e,t){this.buf.a[e+this.offset]=t<0?t+128&255:255&t},setUint8:function(e,t){this.buf.a[e+this.offset]=255&t},setInt16:function(e,t,i){this.setUint16(e,t<0?t+65536:t,i)},setUint16:function(e,t,i){var s=e+this.offset;i?(this.buf.a[s]=255&t,this.buf.a[s++]=t>>8&255):(this.buf.a[s++]=t>>8&255,this.buf.a[s]=255&t)},setInt32:function(e,t,i){this.setUint32(e,t,i)},setUint32:function(e,t,i){var s=e+this.offset;i?(this.buf.a[s++]=255&t,this.buf.a[s++]=t>>8&255,this.buf.a[s++]=t>>16&255,this.buf.a[s++]=t>>>24):(this.buf.a[s++]=t>>>24,this.buf.a[s++]=t>>16&255,this.buf.a[s++]=t>>8&255,this.buf.a[s++]=255&t)},setFloat32:function(e,t,i){this.setUint32(e,E.floatToI32(t),i)},setFloat64:function(e,t,i){var s=E.doubleToI64(t);i?(this.setUint32(e,s.low),this.setUint32(e,s.high)):(this.setUint32(e,s.high),this.setUint32(e,s.low))},__class__:R};var M=function(){};s["js.html.compat.Uint8Array"]=M,M.__name__=["js","html","compat","Uint8Array"],M._new=function(e,t,i){var s;if("number"==typeof e){s=[];for(var r=0;ri.byteLength)throw new A("set() outside of range");for(var r=0,n=e.byteLength;ri.byteLength)throw new A("set() outside of range");for(var l=0,h=a.length;l0||t.handleError(e._errorVal),e._resolved&&!e._pending)try{t.handleResolve(i(e._val))}catch(e){e instanceof A&&(e=e.val),t.handleError(e)}},O.linkAll=function(e,t){for(var i=function(i,s,r){if(0==i.length||O.allFulfilled(i)){for(var n,o=[],a=nt(e)();a.hasNext();){var l=a.next();o.push(l==s?r:l._val)}n=o,t.handleResolve(n)}},s=nt(e)();s.hasNext();){var r=s.next();r._update.push({async:t,linkf:function(e,t,i){return function(s){e(t,i,s)}}(i,function(t){for(var i=[],s=nt(e)();s.hasNext();){var n=s.next();n!=r&&i.push(n)}return i}(),r)})}O.allFulfilled(e)&&t.handleResolve(function(t){for(var i=[],s=nt(e)();s.hasNext();){var r=s.next();i.push(r._val)}return i}())},O.pipeLink=function(e,t,i){var s=!1,r=function(e){if(!s){s=!0;var r=i(e);r._update.push({async:t,linkf:lt(t,t.handleResolve)}),O.immediateLinkUpdate(r,t,(function(e){return e}))}};if(e._update.push({async:t,linkf:r}),e._resolved&&!e._pending)try{r(e._val)}catch(e){e instanceof A&&(e=e.val),t.handleError(e)}},O.allResolved=function(e){for(var t=nt(e)();t.hasNext();)if(!t.next()._resolved)return!1;return!0},O.allFulfilled=function(e){for(var t=nt(e)();t.hasNext();)if(!t.next()._fulfilled)return!1;return!0},O.prototype={catchError:function(e){return this._error.push(e),this},errorThen:function(e){return this._errorMap=e,this},isResolved:function(){return this._resolved},isErrored:function(){return this._errored},isErrorHandled:function(){return this._error.length>0},isErrorPending:function(){return this._errorPending},isFulfilled:function(){return this._fulfilled},isPending:function(){return this._pending},handleResolve:function(e){this._resolve(e)},_resolve:function(e){var t,i,s=this;this._pending?L.enqueue((t=lt(this,this._resolve),i=e,function(){t(i)})):(this._resolved=!0,this._pending=!0,L.queue.add((function(){s._val=e;for(var t=0,i=s._update;t0)for(var i=0,s=t._error;i0))throw new A(e);for(var n=0,o=t._update;n0&&null!=(t=L.queue.pop());)t();return L.queue.isEmpty()},L.clear=function(){L.queue=new l},L.f=function(){var e=L.queue.pop();null!=e&&e(),L.queue.isEmpty()||L.continueOnNextLoop()},L.continueOnNextLoop=function(){null!=L.nextLoop?L.nextLoop(L.f):setImmediate(L.f)};var B=s["promhx.error.PromiseError"]={__ename__:["promhx","error","PromiseError"],__constructs__:["AlreadyResolved","DownstreamNotFullfilled"]};B.AlreadyResolved=function(e){var t=["AlreadyResolved",0,e];return t.__enum__=B,t.toString=r,t},B.DownstreamNotFullfilled=function(e){var t=["DownstreamNotFullfilled",1,e];return t.__enum__=B,t.toString=r,t};var k=function(){};s["verb.Verb"]=k,k.__name__=["verb","Verb"],k.main=function(){e.log("verb 2.1.0")};var V=function(){};s["verb.core.ArrayExtensions"]=V,V.__name__=["verb","core","ArrayExtensions"],V.alloc=function(e,t){if(!(t<0))for(;e.length0;){for(var s=e.pop(),r=!0,n=0;ne)return 0;if(t>e-t&&(t=e-t),U.memo_exists(e,t))return U.get_memo(e,t);for(var i=1,s=e,r=1,n=t+1;re)return 0;t>e-t&&(t=e-t);for(var i=1,s=1,r=t+1;s=l&&o<=h||a>=l&&a<=h||l>=o&&l<=a||h>=o&&h<=a},G.prototype={fromPoint:function(e){return new G([e])},add:function(e){if(!this.initialized)return this.dim=e.length,this.min=e.slice(0),this.max=e.slice(0),this.initialized=!0,this;for(var t=0,i=this.dim;tthis.max[s]&&(this.max[s]=e[s]),e[s]e&&(e=n,t=r)}return t},getAxisLength:function(e){return e<0||e>this.dim-1?0:Math.abs(this.min[e]-this.max[e])},intersect:function(e,t){if(!this.initialized)return null;var i=this.min,s=this.max,r=e.min,n=e.max;if(!this.intersects(e,t))return null;for(var o=[],a=[],l=0,h=this.dim;l0?1:-1})),s=Math.floor(e.length/2),(r=new ue(e[s],n,i)).left=this.buildTree(e.slice(0,s),t+1,r),r.right=this.buildTree(e.slice(s+1),t+1,r),r)},nearest:function(e,t,i){var s,r=this,n=new he((function(e){return-e.item1})),o=null;s=o=function(i){for(var s,a,l,h,c=i.dimension,u=r.distanceFunction(e,i.kdPoint.point),d=[],_=0,p=r.dim;_t&&n.pop()},m=0,g=r.dim;m0&&(this.content[0]=t,this.sinkDown(0)),e},peek:function(){return this.content[0]},remove:function(e){for(var t=this.content.length,i=0;i0;){var i=Math.floor((e+1)/2)-1,s=this.content[i];if(!(this.scoreFunction(t)=0;){for(o=[],a=e[c],d=r-1;d>=0;){for(l=a[s-1]*t[s-1][d],u=s-2;u>=1;)h=u-1,l+=a[u]*t[u][d]+a[h]*t[h][d],u-=2;0==u&&(l+=a[0]*t[0][d]),o[d]=l,d--}n[c]=o,c--}return n},ge.add=function(e,t){for(var i=[],s=0,r=e.length;s=0;){for(n=a[i],s=i+1;ss?1:-1}));for(var l=[],h=0,c=r.length;h=.1*m*n||isNaN(u));)m*=.5,++x;if(m*g20)throw new A("Numerical gradient fails");if(d[m]=t[m]+g,r=e(d),d[m]=t[m]-g,n=e(d),d[m]=t[m],isNaN(r)||isNaN(n))g/=16;else{if(_[m]=(r-n)/(2*g),o=t[m]-g,a=t[m],l=t[m]+g,h=(r-s)/g,c=(s-n)/g,u=Ae.max([Math.abs(_[m]),Math.abs(s),Math.abs(r),Math.abs(n),Math.abs(o),Math.abs(a),Math.abs(l),1e-8]),!(Math.min(Ae.max([Math.abs(h-_[m]),Math.abs(c-_[m]),Math.abs(h-c)])/u,g/u)>.001))break;g/=16}}return _},Te.tensor=function(e,t){for(var i,s,r=e.length,n=t.length,o=[],a=r-1;a>=0;){i=[],s=e[a];for(var l=n-1;l>=3;)i[l]=s*t[l],i[--l]=s*t[l],i[--l]=s*t[l],i[--l]=s*t[l],--l;for(;l>=0;)i[l]=s*t[l],--l;o[a]=i,a--}return o};var ye=function(e,t,i,s,r,n){this.solution=e,this.value=t,this.gradient=i,this.invHessian=s,this.iterations=r,this.message=n};s["verb.core.MinimizationResult"]=ye,ye.__name__=["verb","core","MinimizationResult"],ye.prototype={__class__:ye};var Se=function(){};s["verb.core.ISerializable"]=Se,Se.__name__=["verb","core","ISerializable"],Se.prototype={__class__:Se};var Ce=t.core.Deserializer=function(){};s["verb.core.Deserializer"]=Ce,Ce.__name__=["verb","core","Deserializer"],Ce.deserialize=function(e){return new v(e).unserialize()};var Ee=t.core.Trig=function(){};s["verb.core.Trig"]=Ee,Ee.__name__=["verb","core","Trig"],Ee.isPointInPlane=function(e,t,i){return Math.abs(Ae.dot(Ae.sub(e,t.origin),t.normal))o?{u:r,pt:i}:{u:s+(r-s)*c/o,pt:Ae.add(a,Ae.mul(c,l))}};var Ae=t.core.Vec=function(){};s["verb.core.Vec"]=Ae,Ae.__name__=["verb","core","Vec"],Ae.angleBetween=function(e,t){return Math.acos(Ae.dot(e,t)/(Ae.norm(e)*Ae.norm(t)))},Ae.positiveAngleBetween=function(e,t,i){var s=Ae.cross(e,t),r=Ae.norm(e)*Ae.norm(t),n=Ae.dot(e,t),o=Ae.norm(s)/r,a=n/r,l=Math.atan2(o,a),h=Ae.dot(i,s);return Math.abs(h)0?l:-l},Ae.signedAngleBetween=function(e,t,i){var s=Ae.cross(e,t),r=Ae.norm(e)*Ae.norm(t),n=Ae.dot(e,t),o=Ae.norm(s)/r,a=n/r,l=Math.atan2(o,a);return Ae.dot(i,s)>0?l:2*Math.PI-l},Ae.angleBetweenNormalized2d=function(e,t){var i=e[0]*t[1]-e[1]*t[0];return Math.atan2(i,Ae.dot(e,t))},Ae.domain=function(e){return V.last(e)-V.first(e)},Ae.range=function(e){for(var t=[],i=0,s=0;st&&i>0)return[];if(t>e&&i<0)return[];for(var s=[],r=e;r<=t;)s.push(r),r+=i;return s},Ae.neg=function(e){return e.map((function(e){return-e}))},Ae.min=function(e){return a.fold(e,(function(e,t){return Math.min(e,t)}),1/0)},Ae.max=function(e){return a.fold(e,(function(e,t){return Math.max(e,t)}),-1/0)},Ae.all=function(e){return a.fold(e,(function(e,t){return t&&e}),!0)},Ae.finite=function(e){return e.map((function(e){return isFinite(e)}))},Ae.onRay=function(e,t,i){return Ae.add(e,Ae.mul(i,t))},Ae.lerp=function(e,t,i){return Ae.add(Ae.mul(e,t),Ae.mul(1-e,i))},Ae.normalized=function(e){return Ae.div(e,Ae.norm(e))},Ae.cross=function(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]},Ae.dist=function(e,t){return Ae.norm(Ae.sub(e,t))},Ae.distSquared=function(e,t){return Ae.normSquared(Ae.sub(e,t))},Ae.sum=function(e){return a.fold(e,(function(e,t){return t+e}),0)},Ae.addAll=function(e){var t=nt(e)();if(!t.hasNext())return null;var i=t.next().length;return a.fold(e,(function(e,t){return Ae.add(t,e)}),Ae.rep(i,0))},Ae.addAllMutate=function(e){for(var t=e[0],i=1,s=e.length;iz.TOLERANCE)return!1}return!0},Ae.sortedSetUnion=function(e,t){for(var i=[],s=0,r=0;s=e.length)i.push(t[r]),r++;else if(r>=t.length)i.push(e[s]),s++;else{var n=e[s]-t[r];Math.abs(n)0?(i.push(t[r]),r++):(i.push(e[s]),s++)}return i},Ae.sortedSetSub=function(e,t){for(var i=[],s=0,r=0;s=t.length?(i.push(e[s]),s++):Math.abs(e[s]-t[r])z.EPSILON&&(i=new Ie(r,0),t.push(i)),i.inc()}return t},Pe.isRationalSurfaceClosed=function(e,t){var i;null==t&&(t=!0);for(var s=0,r=(i=t?e.controlPoints:ge.transpose(e.controlPoints))[0].length;sh&&(A=d?[l+(A[0]-h),A[1]]:[h-z.EPSILON,A[1]]),A[1]u&&(A=_?[A[0],c+(A[0]-u)]:[A[0],u-z.EPSILON]),Ae.norm(Ae.mul(A[0]-r[0],i[1][0]))+Ae.norm(Ae.mul(A[1]-r[1],i[0][1]))x&&(A=b?v+(A-x):x),Ae.norm(Ae.mul(A-T,p[1]))(r=null!=s?s:Pe.rationalBezierCurveArcLength(e)))return V.last(e.knots);var n,o=e.knots[0],a=0,l=V.last(e.knots),h=r,c=0,u=0;for(n=null!=i?i:2*z.TOLERANCE;h-a>n;)c=(o+l)/2,(u=Pe.rationalBezierCurveArcLength(e,c))>t?(l=c,h=u):(o=c,a=u);return(o+l)/2},Pe.rationalCurveArcLength=function(e,t,i){null==i&&(i=16),null==t&&(t=V.last(e.knots));for(var s=Fe.decomposeCurveIntoBeziers(e),r=0,n=s[0],o=0;rz.EPSILON)return!1}i=V.last(e);for(var o=e.length-t-1,a=e.length;oz.EPSILON)return!1}return Re.isNonDecreasing(e)},Re.isNonDecreasing=function(e){for(var t=V.first(e),i=0,s=e.length;ir)return n;for(var o,a=t,l=0,h=a,c=0,u=0;l=t[l+1];)l++;o.push(l),n.push(De.basisFunctionsGivenKnotSpanIndex(l,a,e,t)),a+=r}return new q(o,n)},De.regularlySpacedDerivativeBasisFunctions=function(e,t,i){for(var s=t.length-e-2,r=(V.last(t)-t[0])/i,n=[],o=[],a=t[0],l=De.knotSpanGivenN(s,e,a,t),h=i+1,c=0;c=t[l+1];)l++;o.push(l),n.push(De.derivativeBasisFunctionsGivenNI(l,a,e,s,t)),a+=r}return new q(o,n)},De.surfacePointGivenBasesKnotSpans=function(e,t,i,s,r,n,o,a){for(var l,h=Ae.zeros1d(a),c=s-e,u=r-t,d=0,_=t+1;d<_;){var p=d++;l=Ae.zeros1d(a);for(var f=0,m=e+1;f=M&&(m[v][0]=m[g][0]/n[T+1][b],x=m[v][0]*n[b][T]);for(var O=b>=-1?1:-b,D=1+(P-1<=T?M-1:i-P);Os[e+1]-z.EPSILON)return e;if(i=s[o+1];)iz.EPSILON})),(function(e,t){var i=Ae.sub(e.min.uv0,t.min.uv0),s=Ae.dot(i,i),r=Ae.sub(e.max.uv0,t.max.uv0),n=Ae.dot(r,r),o=Ae.sub(e.min.uv0,t.max.uv0),a=Ae.dot(o,o),l=Ae.sub(e.max.uv0,t.min.uv0),h=Ae.dot(l,l);return s0&&(f.push(f[f.length-1].opp),u.push(f))}if(0==c.length&&r.length>0&&(_||d0;){var o=s.pop(),a=r.pop();if(!o.empty()&&!a.empty()&&o.boundingBox().intersects(a.boundingBox(),i)){var l=o.indivisible(i),h=a.indivisible(i);if(l&&h)n.push(new q(o.yield(),a.yield()));else if(!l||h)if(l||!h){var c=o.split(),u=a.split();s.push(c.item1),r.push(u.item1),s.push(c.item1),r.push(u.item0),s.push(c.item0),r.push(u.item1),s.push(c.item0),r.push(u.item0)}else{var d=o.split();s.push(d.item1),r.push(a),s.push(d.item0),r.push(a)}else{var _=a.split();s.push(o),r.push(_.item1),s.push(o),r.push(_.item0)}}}return n},we.curves=function(e,t,i){var s=we.boundingBoxTrees(new _e(e),new _e(t),0);return V.unique(s.map((function(s){return we.curvesWithEstimate(e,t,V.first(s.item0.knots),V.first(s.item1.knots),i)})).filter((function(e){return Ae.distSquared(e.point0,e.point1)h[_]+z.EPSILON||((null==c||vu.u)&&(u=new ne(v,Ae.onRay(e.origin,e.dir,v),Ae.onRay(n[_],o[_],g/h[_]))))}}return null==u||null==c?null:new Z(c,u)},we.mergeTriangleClipIntervals=function(e,t,i,s,r,n){if(t.min.u>e.max.u+z.EPSILON||e.min.u>t.max.u+z.EPSILON)return null;var o,a;o=e.min.u>t.min.u?new q(e.min,0):new q(t.min,1),a=e.max.uc&&(h=1,c=u),d>c&&(h=2,c=d),0==h?(n=t[1],o=t[2],a=s[1],l=s[2]):1==h?(n=t[0],o=t[2],a=s[0],l=s[2]):(n=t[0],o=t[1],a=s[0],l=s[1]);var _=-Ae.dot(e,t),p=-Ae.dot(i,s),f=n*l-o*a,m=(o*p-_*l)/f,g=(_*a-n*p)/f;return new X(0==h?[0,m,g]:1==h?[m,0,g]:[m,g,0],Ae.normalized(r))},we.threePlanes=function(e,t,i,s,r,n){var o=Ae.cross(i,r),a=Ae.dot(e,o);if(Math.abs(a)1)return null;var f=Ae.add(e,Ae.mul(p,c)),m=Ae.dot(a,l),g=Ae.dot(a,a),v=Ae.dot(l,l),x=Ae.sub(f,r),b=Ae.dot(x,a),T=Ae.dot(x,l),y=m*m-g*v;if(Math.abs(y)1+z.EPSILON||C>1+z.EPSILON||C<-z.EPSILON||S<-z.EPSILON||S+C>1+z.EPSILON?null:new re(f,S,C,p)},we.segmentAndPlane=function(e,t,i,s){var r=Ae.dot(s,Ae.sub(t,e));if(Math.abs(r)1+z.EPSILON||n<-z.EPSILON?null:{p:n}};var Ne=t.eval.Make=function(){};s["verb.eval.Make"]=Ne,Ne.__name__=["verb","eval","Make"],Ne.rationalTranslationalSurface=function(e,t){for(var i=De.rationalCurvePoint(t,V.first(t.knots)),s=V.first(t.knots),r=V.last(t.knots),n=2*t.controlPoints.length,o=(r-s)/(n-1),a=[],l=0;l=0&&(u-=n[o].mult),c=u>0?Fe.surfaceKnotRefine(e,Ae.rep(u,t),i):e;var d=De.knotSpan(r,t,s);return Math.abs(t-V.first(s))e.length-1&&(t=e.length-1);for(var s=e[0].knots,r=[],n=[],o=0,a=e[0].controlPoints.length;oz.EPSILON&&(E=Ae.mul(1/A,E),P=Ae.mul(1/A,P)),m[0][S]=o[S];var I=o[S];g[0][S]=a[S];for(var R=P,M=0,O=1,D=r+1;Ot?e:t},Fe.curveElevateDegree=function(e,t){if(t<=e.degree)return e;var i=e.knots.length-e.degree-2,s=e.degree,r=e.knots,n=e.controlPoints,o=t-e.degree,a=e.controlPoints[0].length,l=Ae.zeros2d(s+o+1,s+1),h=[],c=[],u=[],d=i+s+1,_=t,p=Math.floor(_/2),f=[],m=[];l[0][0]=1,l[_][s]=1;for(var g=1,v=p+1;g0?Math.floor((K+2)/2):1,X=D>0?Math.floor(_-(D+1)/2):_,D>0){for(var $=j-L,q=[],Z=s;Z>Q;)q[Z-Q-1]=$/(r[w+Z]-L),Z--;for(var J=1,ee=D+1;J=se;)h[re]=Ae.add(Ae.mul(q[re-se],h[re]),Ae.mul(1-q[re-se],h[re-1])),re--;u[ie]=h[s]}}for(var ne=H,oe=_+1;ne1)for(var de=O-2,_e=O,pe=j-L,fe=(j-m[O-1])/pe,me=1;mege;){if(ve=H){if(xe-ge<=O-_+K){var ye=(j-m[xe-ge])/pe;c[be]=Ae.lerp(ye,c[be],c[be+1])}}else c[be]=Ae.lerp(fe,c[be],c[be+1]);ve+=1,xe-=1,be-=1}de-=1,_e+=1}if(w!=s)for(var Se=0,Ce=_-K;Se=0;){for(;t[A]<=r[C]&&C>l;)c[E-i-1]=s[C-i-1],u[E]=r[C],E-=1,C-=1;c[E-i-1]=c[E-i];for(var P=1,I=i+1;Ps||!Ee.threePointsAreFlat(n,l,o,s)){var u=t+.5*(i-t),d=Le.rationalCurveAdaptiveSampleRange(e,t,u,s,r),_=Le.rationalCurveAdaptiveSampleRange(e,u,i,s,r);return d.slice(0,-1).concat(_)}return r?[[t].concat(n),[i].concat(o)]:[n,o]},Le.rationalSurfaceNaive=function(e,t,i){t<1&&(t=1),i<1&&(i=1),e.degreeU,e.degreeV,e.controlPoints;for(var s=e.knotsU,r=e.knotsV,n=(V.last(s)-s[0])/t,o=(V.last(r)-r[0])/i,a=[],l=[],h=[],c=0,u=t+1;cr?t.minDivsU=t.minDivsU:t.minDivsU=r,s=t.minDivsV>n?t.minDivsV=t.minDivsV:t.minDivsV=n;for(var o=V.last(e.knotsU),a=e.knotsU[0],l=V.last(e.knotsV),h=e.knotsV[0],c=(o-a)/i,u=(l-h)/s,d=[],_=[],p=0,f=s+1;pn.corners[0].uv[0]+r&&e.uv[0]n.corners[0].uv[1]+r&&e.uv[1]=e.maxDepth)return!1;if(this.hasBadNormals())return this.fixNormals(),!1;if(this.splitVert=Ae.normSquared(Ae.sub(this.corners[0].normal,this.corners[1].normal))>e.normTol||Ae.normSquared(Ae.sub(this.corners[2].normal,this.corners[3].normal))>e.normTol,this.splitHoriz=Ae.normSquared(Ae.sub(this.corners[1].normal,this.corners[2].normal))>e.normTol||Ae.normSquared(Ae.sub(this.corners[3].normal,this.corners[0].normal))>e.normTol,this.splitVert||this.splitHoriz)return!0;var i=this.center();return Ae.normSquared(Ae.sub(i.normal,this.corners[0].normal))>e.normTol||Ae.normSquared(Ae.sub(i.normal,this.corners[1].normal))>e.normTol||Ae.normSquared(Ae.sub(i.normal,this.corners[2].normal))>e.normTol||Ae.normSquared(Ae.sub(i.normal,this.corners[3].normal))>e.normTol},divide:function(e){null==e&&(e=new Be),null==e.normTol&&(e.normTol=.085),null==e.minDepth&&(e.minDepth=0),null==e.maxDepth&&(e.maxDepth=10),this._divide(e,0,!0)},_divide:function(e,t,i){if(this.evalCorners(),this.shouldDivide(e,t)){if(t++,this.splitVert&&!this.splitHoriz?i=!1:!this.splitVert&&this.splitHoriz&&(i=!0),this.horizontal=i,this.horizontal){var s=[this.corners[0],this.corners[1],this.midpoint(1),this.midpoint(3)],r=[this.midpoint(3),this.midpoint(1),this.corners[2],this.corners[3]];this.children=[new ke(this.srf,s),new ke(this.srf,r)],this.children[0].neighbors=[this.neighbors[0],this.neighbors[1],this.children[1],this.neighbors[3]],this.children[1].neighbors=[this.children[0],this.neighbors[1],this.neighbors[2],this.neighbors[3]]}else{var n=[this.corners[0],this.midpoint(0),this.midpoint(2),this.corners[3]],o=[this.midpoint(0),this.corners[1],this.corners[2],this.midpoint(2)];this.children=[new ke(this.srf,n),new ke(this.srf,o)],this.children[0].neighbors=[this.neighbors[0],this.children[1],this.neighbors[2],this.neighbors[3]],this.children[1].neighbors=[this.neighbors[0],this.neighbors[1],this.neighbors[2],this.children[0]]}for(var a=0,l=this.children;a0&&this._pool.length>0;){var i=this._queue.shift(),s=[i.id],r=[this._pool.shift()];this._working.h[s[0]]=r[0],r[0].onmessage=function(i,s){return function(r){t._working.remove(s[0]),t._pool.push(i[0]);try{t._callbacks.h.hasOwnProperty(s[0])&&(t._callbacks.h[s[0]](r.data.result),t._callbacks.remove(s[0]))}catch(t){t instanceof A&&(t=t.val),e.log(t)}t.processQueue()}}(r,s),r[0].postMessage(i)}},__class__:Ue};var Ge=function(e,t,i){this.className=e,this.methodName=t,this.args=i,this.id=Ge.uuid++};s["verb.exe._WorkerPool.Work"]=Ge,Ge.__name__=["verb","exe","_WorkerPool","Work"],Ge.prototype={__class__:Ge};var ze=function(){};s["verb.geom.ICurve"]=ze,ze.__name__=["verb","geom","ICurve"],ze.__interfaces__=[Se],ze.prototype={__class__:ze};var We=t.geom.NurbsCurve=function(e){this._data=Re.isValidNurbsCurveData(e)};s["verb.geom.NurbsCurve"]=We,We.__name__=["verb","geom","NurbsCurve"],We.__interfaces__=[ze],We.byKnotsControlPointsWeights=function(e,t,i,s){return new We(new Y(e,t.slice(),De.homogenize1d(i,s)))},We.byPoints=function(e,t){return null==t&&(t=3),new We(Ne.rationalInterpCurve(e,t))},We.__super__=W,We.prototype=n(W.prototype,{degree:function(){return this._data.degree},knots:function(){return this._data.knots.slice(0)},controlPoints:function(){return De.dehomogenize1d(this._data.controlPoints)},weights:function(){return De.weight1d(this._data.controlPoints)},asNurbs:function(){return new Y(this.degree(),this.knots(),De.homogenize1d(this.controlPoints(),this.weights()))},clone:function(){return new We(this._data)},domain:function(){return new Z(V.first(this._data.knots),V.last(this._data.knots))},transform:function(e){return new We(Fe.rationalCurveTransform(this._data,e))},transformAsync:function(e){return Ve.dispatchMethod(Fe,"rationalCurveTransform",[this._data,e]).then((function(e){return new We(e)}))},point:function(e){return De.rationalCurvePoint(this._data,e)},pointAsync:function(e){return Ve.dispatchMethod(De,"rationalCurvePoint",[this._data,e])},tangent:function(e){return De.rationalCurveTangent(this._data,e)},tangentAsync:function(e){return Ve.dispatchMethod(De,"rationalCurveTangent",[this._data,e])},derivatives:function(e,t){return null==t&&(t=1),De.rationalCurveDerivatives(this._data,e,t)},derivativesAsync:function(e,t){return null==t&&(t=1),Ve.dispatchMethod(De,"rationalCurveDerivatives",[this._data,e,t])},closestPoint:function(e){return Pe.rationalCurveClosestPoint(this._data,e)},closestPointAsync:function(e){return Ve.dispatchMethod(Pe,"rationalCurveClosestPoint",[this._data,e])},closestParam:function(e){return Pe.rationalCurveClosestParam(this._data,e)},closestParamAsync:function(e){return Ve.dispatchMethod(Pe,"rationalCurveClosestParam",[this._data,e])},length:function(){return Pe.rationalCurveArcLength(this._data)},lengthAsync:function(){return Ve.dispatchMethod(Pe,"rationalCurveArcLength",[this._data])},lengthAtParam:function(e){return Pe.rationalCurveArcLength(this._data,e)},lengthAtParamAsync:function(){return Ve.dispatchMethod(Pe,"rationalCurveArcLength",[this._data])},paramAtLength:function(e,t){return Pe.rationalCurveParamAtArcLength(this._data,e,t)},paramAtLengthAsync:function(e,t){return Ve.dispatchMethod(Pe,"rationalCurveParamAtArcLength",[this._data,e,t])},divideByEqualArcLength:function(e){return Me.rationalCurveByEqualArcLength(this._data,e)},divideByEqualArcLengthAsync:function(e){return Ve.dispatchMethod(Me,"rationalCurveByEqualArcLength",[this._data,e])},divideByArcLength:function(e){return Me.rationalCurveByArcLength(this._data,e)},divideByArcLengthAsync:function(e){return Ve.dispatchMethod(Me,"rationalCurveByArcLength",[this._data,e])},split:function(e){return Me.curveSplit(this._data,e).map((function(e){return new We(e)}))},splitAsync:function(e){return Ve.dispatchMethod(Me,"curveSplit",[this._data,e]).then((function(e){return e.map((function(e){return new We(e)}))}))},reverse:function(){return new We(Fe.curveReverse(this._data))},reverseAsync:function(){return Ve.dispatchMethod(Fe,"curveReverse",[this._data]).then((function(e){return new We(e)}))},tessellate:function(e){return Le.rationalCurveAdaptiveSample(this._data,e,!1)},tessellateAsync:function(e){return Ve.dispatchMethod(Le,"rationalCurveAdaptiveSample",[this._data,e,!1])},__class__:We});var He=t.geom.Arc=function(e,t,i,s,r,n){We.call(this,Ne.arc(e,t,i,s,r,n)),this._center=e,this._xaxis=t,this._yaxis=i,this._radius=s,this._minAngle=r,this._maxAngle=n};s["verb.geom.Arc"]=He,He.__name__=["verb","geom","Arc"],He.__super__=We,He.prototype=n(We.prototype,{center:function(){return this._center},xaxis:function(){return this._xaxis},yaxis:function(){return this._yaxis},radius:function(){return this._radius},minAngle:function(){return this._minAngle},maxAngle:function(){return this._maxAngle},__class__:He});var Xe=t.geom.BezierCurve=function(e,t){We.call(this,Ne.rationalBezierCurve(e,t))};s["verb.geom.BezierCurve"]=Xe,Xe.__name__=["verb","geom","BezierCurve"],Xe.__super__=We,Xe.prototype=n(We.prototype,{__class__:Xe});var Ye=t.geom.Circle=function(e,t,i,s){He.call(this,e,t,i,s,0,2*Math.PI)};s["verb.geom.Circle"]=Ye,Ye.__name__=["verb","geom","Circle"],Ye.__super__=He,Ye.prototype=n(He.prototype,{__class__:Ye});var Qe=function(){};s["verb.geom.ISurface"]=Qe,Qe.__name__=["verb","geom","ISurface"],Qe.__interfaces__=[Se],Qe.prototype={__class__:Qe};var je=t.geom.NurbsSurface=function(e){this._data=Re.isValidNurbsSurfaceData(e)};s["verb.geom.NurbsSurface"]=je,je.__name__=["verb","geom","NurbsSurface"],je.__interfaces__=[Qe],je.byKnotsControlPointsWeights=function(e,t,i,s,r,n){return new je(new Q(e,t,i,s,De.homogenize2d(r,n)))},je.byCorners=function(e,t,i,s){return new je(Ne.fourPointSurface(e,t,i,s))},je.byLoftingCurves=function(e,t){return new je(Ne.loftedSurface(function(t){for(var i=[],s=0;s{},439:()=>{},699:()=>{}},t={};function i(s){var r=t[s];if(void 0!==r)return r.exports;var n=t[s]={exports:{}};return e[s](n,n.exports,i),n.exports}i.d=(e,t)=>{for(var s in t)i.o(t,s)&&!i.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};return(()=>{"use strict";i.r(s),i.d(s,{Runner:()=>hY,fontsEnum:()=>eY,getRunnerInstance:()=>lY});var e={};i.r(e),i.d(e,{AbstractActionManager:()=>Y,AbstractAssetTask:()=>AI,AbstractEngine:()=>ns,AbstractMesh:()=>_o,AbstractScene:()=>X,AcquireNativeObjectAsync:()=>Zp,Action:()=>Ie,ActionEvent:()=>Re,ActionManager:()=>Qe,AddBlock:()=>rT,AddressMode:()=>mf,AdvancedTimer:()=>Sv,AlignBlock:()=>CC,AlphaState:()=>es,AmmoJSPlugin:()=>px,AnaglyphArcRotateCamera:()=>Ac,AnaglyphFreeCamera:()=>Pc,AnaglyphGamepadCamera:()=>Ic,AnaglyphPostProcess:()=>Cc,AnaglyphUniversalCamera:()=>Rc,Analyser:()=>fa,AndOrNotEvaluator:()=>bt,Angle:()=>$r,Animatable:()=>Qr,AnimatedInputBlockTypes:()=>pl,Animation:()=>Ft,AnimationAssetTask:()=>MI,AnimationEvent:()=>fn,AnimationGroup:()=>gn,AnimationGroupMask:()=>xn,AnimationGroupMaskMode:()=>Wr,AnimationKeyInterpolation:()=>$e,AnimationPropertiesOverride:()=>jr,AnimationRange:()=>qe,AnisotropyBlock:()=>XT,ApplyPostProcess:()=>Z_,Arc2:()=>qr,ArcFollowCamera:()=>fc,ArcRotateCamera:()=>hc,ArcRotateCameraGamepadInput:()=>Uh,ArcRotateCameraInputsManager:()=>Hh,ArcRotateCameraKeyboardMoveInput:()=>Gh,ArcRotateCameraMouseWheelInput:()=>zh,ArcRotateCameraPointersInput:()=>Wh,ArcRotateCameraVRDeviceOrientationInput:()=>Xh,ArcTan2Block:()=>PT,AssetContainer:()=>pa,AssetTaskState:()=>EI,AssetsManager:()=>kI,AssetsProgressEvent:()=>PI,AsyncLoop:()=>Ns,AttachToBoxBehavior:()=>ka,AudioEngine:()=>no,AudioSceneComponent:()=>va,AutoLayoutMode:()=>Pf,AutoReleaseWorkerPool:()=>Qg,AutoRotationBehavior:()=>Na,AxesViewer:()=>nd,Axis:()=>Xr,AxisDragGizmo:()=>rd,AxisScaleGizmo:()=>tg,BRDFTextureTools:()=>Ag,BabylonFileLoaderConfiguration:()=>yx,BackEase:()=>rn,BackgroundMaterial:()=>bg,BakedVertexAnimationManager:()=>ba,BallAndSocketConstraint:()=>yA,BaseCameraMouseWheelInput:()=>Ph,BaseCameraPointersInput:()=>Ih,BaseError:()=>Yt,BaseParticleSystem:()=>Yl,BaseSixDofDragBehavior:()=>Qa,BaseTexture:()=>ya,BasisFileInfo:()=>nb,BasisTools:()=>gb,BasisToolsOptions:()=>lb,BasisTranscodeConfiguration:()=>ob,BezierCurve:()=>Kr,BezierCurveEase:()=>pn,BiPlanarBlock:()=>dy,BinaryFileAssetTask:()=>DI,BindBonesParameters:()=>wo,BindFogParameters:()=>Co,BindLight:()=>Fo,BindLightProperties:()=>No,BindLights:()=>Lo,BindLogDepth:()=>So,BindMorphTargetParameters:()=>Io,BindSceneUniformBuffer:()=>Ro,BindTextureMatrix:()=>Oo,BlackAndWhitePostProcess:()=>$A,BlendFactor:()=>Df,BlendOperation:()=>wf,BloomEffect:()=>eP,BloomMergePostProcess:()=>JA,BlurPostProcess:()=>mg,Bone:()=>Yr,BoneAxesViewer:()=>od,BoneIKController:()=>Sh,BoneLookController:()=>Ch,BonesBlock:()=>Rb,BooleanGeometryBlock:()=>WC,BooleanGeometryOperations:()=>TS,BounceEase:()=>nn,BouncingBehavior:()=>Fa,BoundingBlock:()=>zC,BoundingBox:()=>Mn,BoundingBoxGizmo:()=>ig,BoundingBoxRenderer:()=>zP,BoundingInfo:()=>Ln,BoundingSphere:()=>On,BoxBlock:()=>zS,BoxBuilder:()=>ud,BoxParticleEmitter:()=>uE,Buffer:()=>Js,BufferBindingType:()=>Tf,BufferMapState:()=>lf,BufferUsage:()=>hf,CSG:()=>tS,Camera:()=>In,CameraGizmo:()=>fg,CameraInputTypes:()=>Fh,CameraInputsManager:()=>Lh,CannonJSPlugin:()=>dx,CanvasAlphaMode:()=>Wf,CapsuleBlock:()=>ZS,CapsuleBuilder:()=>gd,CascadedShadowGenerator:()=>Zv,ChromaticAberrationPostProcess:()=>tP,CircleEase:()=>sn,CircleOfConfusionPostProcess:()=>iP,ClampBlock:()=>oT,ClearCoatBlock:()=>QT,ClipPlanesBlock:()=>eT,ClipboardEventTypes:()=>Jm,ClipboardInfo:()=>eg,CloudBlock:()=>ly,CloudPoint:()=>jE,Collider:()=>Uu,Color3:()=>Ee,Color3Gradient:()=>EE,Color4:()=>Ae,ColorCorrectionPostProcess:()=>sP,ColorCurves:()=>Vs,ColorGradient:()=>CE,ColorGradingTexture:()=>kx,ColorMergerBlock:()=>uT,ColorSplitterBlock:()=>Ql,ColorWrite:()=>Of,CombineAction:()=>ze,CompareFunction:()=>xf,CompatibilityOptions:()=>Xn,CompilationMessageType:()=>Ef,CompleteGreasedLineColorTable:()=>LS,CompleteGreasedLineWidthTable:()=>FS,ComputeBindingType:()=>Wu,ComputeEffect:()=>zu,ComputeNormalsBlock:()=>pC,ComputePassTimestampLocation:()=>kf,ComputeShader:()=>Xu,ComputeShaderParticleSystem:()=>SE,Condition:()=>Me,ConditionBlock:()=>lC,ConditionBlockTests:()=>gS,ConditionalBlock:()=>ay,ConditionalBlockConditions:()=>ty,ConeParticleEmitter:()=>dE,Constants:()=>N_,ContainerAssetTask:()=>II,ConversionMode:()=>hI,ConvolutionPostProcess:()=>rP,Coordinate:()=>Gr,CopyTextureToTexture:()=>cI,CopyTools:()=>Aa,CreateBox:()=>cd,CreateBoxVertexData:()=>ld,CreateCapsule:()=>md,CreateCapsuleVertexData:()=>fd,CreateCylinder:()=>$u,CreateCylinderVertexData:()=>Ku,CreateDashedLines:()=>Gd,CreateDashedLinesVertexData:()=>kd,CreateDecal:()=>f_,CreateDisc:()=>yd,CreateDiscVertexData:()=>Td,CreateEnvTextureAsync:()=>yp,CreateGeodesic:()=>T_,CreateGoldberg:()=>C_,CreateGoldbergVertexData:()=>S_,CreateGreasedLine:()=>wS,CreateGreasedLineMaterial:()=>DS,CreateGround:()=>Iu,CreateGroundFromHeightMap:()=>Mu,CreateGroundFromHeightMapVertexData:()=>Pu,CreateGroundVertexData:()=>Eu,CreateHemisphere:()=>ug,CreateIcoSphere:()=>uh,CreateIcoSphereVertexData:()=>ch,CreateImageBitmapFromSource:()=>Jn,CreateImageDataArrayBufferViews:()=>Cp,CreateLathe:()=>t_,CreateLineSystem:()=>Vd,CreateLineSystemVertexData:()=>Bd,CreateLines:()=>Ud,CreatePlane:()=>Wa,CreatePlaneVertexData:()=>za,CreatePolygon:()=>jd,CreatePolygonVertexData:()=>Qd,CreatePolyhedron:()=>o_,CreatePolyhedronVertexData:()=>n_,CreateResizedCopy:()=>q_,CreateRibbon:()=>xd,CreateRibbonVertexData:()=>vd,CreateScreenshot:()=>aR,CreateScreenshotAsync:()=>lR,CreateScreenshotUsingRenderTarget:()=>cR,CreateScreenshotUsingRenderTargetAsync:()=>uR,CreateScreenshotWithResizeAsync:()=>hR,CreateSegmentedBoxVertexData:()=>hd,CreateSphere:()=>_d,CreateSphereVertexData:()=>dd,CreateText:()=>I_,CreateTextShapePaths:()=>P_,CreateTiledBox:()=>Id,CreateTiledBoxVertexData:()=>Pd,CreateTiledGround:()=>Ru,CreateTiledGroundVertexData:()=>Au,CreateTiledPlane:()=>Ed,CreateTiledPlaneVertexData:()=>Cd,CreateTorus:()=>wu,CreateTorusKnot:()=>Od,CreateTorusKnotVertexData:()=>Md,CreateTorusVertexData:()=>Du,CreateTube:()=>s_,CrossBlock:()=>aT,CubeMapToSphericalPolynomialTools:()=>$_,CubeTexture:()=>vg,CubeTextureAssetTask:()=>FI,CubicEase:()=>on,CullMode:()=>Mf,CurrentScreenBlock:()=>Dl,Curve3:()=>en,CurveBlock:()=>my,CurveBlockTypes:()=>sy,CustomBlock:()=>lT,CustomOptimization:()=>KI,CustomParticleEmitter:()=>xE,CustomProceduralTexture:()=>yb,CylinderBlock:()=>qS,CylinderBuilder:()=>qu,CylinderDirectedParticleEmitter:()=>pE,CylinderParticleEmitter:()=>_E,DDSTools:()=>_p,DataBuffer:()=>Qs,DataReader:()=>mR,DataStorage:()=>gR,Database:()=>cE,DebugBlock:()=>NC,DebugLayer:()=>ad,DebugLayerTab:()=>id,DecalBuilder:()=>m_,DecalMapConfiguration:()=>Ty,DecalMapDefines:()=>by,Decode:()=>qt,DecodeBase64ToBinary:()=>ei,DecodeBase64ToString:()=>Jt,DecodeBase64UrlToBinary:()=>xs,DecodeBase64UrlToString:()=>bs,DeepCopier:()=>Ye,DefaultCollisionCoordinator:()=>Gu,DefaultKTX2DecoderOptions:()=>Jg,DefaultLoadingScreen:()=>tx,DefaultRenderingPipeline:()=>EP,Deferred:()=>VI,DepthCullingState:()=>qi,DepthOfFieldBlurPostProcess:()=>nP,DepthOfFieldEffect:()=>lP,DepthOfFieldEffectBlurLevel:()=>aP,DepthOfFieldMergePostProcess:()=>oP,DepthPeelingRenderer:()=>XP,DepthPeelingSceneComponent:()=>YP,DepthReducer:()=>Yv,DepthRenderer:()=>Hv,DepthRendererSceneComponent:()=>WP,DepthSortedParticle:()=>XE,DerivativeBlock:()=>kb,DesaturateBlock:()=>WT,DetailMapConfiguration:()=>au,DeviceInputEventType:()=>yr,DeviceLostReason:()=>Hf,DeviceOrientationCamera:()=>cc,DeviceSource:()=>Ir,DeviceSourceManager:()=>Mr,DeviceType:()=>fr,DirectionalLight:()=>cg,DirectionalLightFrustumViewer:()=>w_,DiscBlock:()=>JS,DiscBuilder:()=>Sd,DiscardBlock:()=>Lb,DisplayPassPostProcess:()=>hP,DistanceBlock:()=>yT,DistanceConstraint:()=>SA,DistanceJoint:()=>tl,DivideBlock:()=>pT,DoNothingAction:()=>Ge,DomManagement:()=>zt,DotBlock:()=>hT,DracoCompression:()=>jy,DrawWrapper:()=>Un,DualSenseInput:()=>xr,DualShockButton:()=>wh,DualShockDpad:()=>Nh,DualShockInput:()=>vr,DualShockPad:()=>gc,DumpTools:()=>th,DynamicFloat32Array:()=>AR,DynamicTexture:()=>uu,EasingFunction:()=>tn,EdgesRenderer:()=>jP,Effect:()=>$i,EffectFallbacks:()=>Ll,EffectLayer:()=>wv,EffectLayerSceneComponent:()=>Nv,EffectRenderer:()=>Kl,EffectWrapper:()=>$l,ElasticEase:()=>an,ElbowBlock:()=>cy,EncodeArrayBufferToBase64:()=>Zt,EndsWith:()=>Kt,Engine:()=>oo,EngineFactory:()=>Zm,EngineFormat:()=>$g,EngineInstrumentation:()=>Ov,EngineStore:()=>re,EngineView:()=>k_,EnvironmentHelper:()=>Tg,EnvironmentTextureTools:()=>Mp,Epsilon:()=>J,EquiRectangularCubeTexture:()=>Vx,EquiRectangularCubeTextureAssetTask:()=>BI,ErrorCodes:()=>Qt,ErrorFilter:()=>Xf,EventConstants:()=>Sr,EventState:()=>Q,ExecuteCodeAction:()=>We,ExitFullscreen:()=>io,ExitPointerlock:()=>ro,ExponentialEase:()=>ln,ExternalTexture:()=>ym,ExtractHighlightsPostProcess:()=>ZA,ExtrudePolygon:()=>Kd,ExtrudeShape:()=>qd,ExtrudeShapeCustom:()=>Zd,FactorGradient:()=>AE,FadeInOutBehavior:()=>Va,FeatureName:()=>af,FileTools:()=>Ts,FileToolsOptions:()=>cs,FilesInput:()=>GI,FilesInputStore:()=>Ht,FilterMode:()=>gf,FilterPostProcess:()=>cP,FlowGraph:()=>iO,FlowGraphAbsBlock:()=>lD,FlowGraphAcosBlock:()=>VD,FlowGraphAcoshBlock:()=>YD,FlowGraphAddBlock:()=>qO,FlowGraphAsinBlock:()=>kD,FlowGraphAsinhBlock:()=>XD,FlowGraphAtan2Block:()=>GD,FlowGraphAtanBlock:()=>UD,FlowGraphAtanhBlock:()=>QD,FlowGraphBitwiseAndBlock:()=>uw,FlowGraphBitwiseLeftShiftBlock:()=>pw,FlowGraphBitwiseNotBlock:()=>cw,FlowGraphBitwiseOrBlock:()=>dw,FlowGraphBitwiseRightShiftBlock:()=>fw,FlowGraphBitwiseXorBlock:()=>_w,FlowGraphBlock:()=>QM,FlowGraphBranchBlock:()=>dO,FlowGraphCeilBlock:()=>dD,FlowGraphClampBlock:()=>TD,FlowGraphConditionalDataBlock:()=>IO,FlowGraphConnection:()=>AM,FlowGraphConnectionType:()=>EM,FlowGraphConsoleLogBlock:()=>oO,FlowGraphConstantBlock:()=>OO,FlowGraphContext:()=>ZM,FlowGraphContextLogger:()=>rO,FlowGraphCoordinateTransformBlock:()=>MO,FlowGraphCoordinator:()=>sO,FlowGraphCosBlock:()=>LD,FlowGraphCoshBlock:()=>WD,FlowGraphCountLeadingZerosBlock:()=>mw,FlowGraphCountOneBitsBlock:()=>vw,FlowGraphCountTrailingZerosBlock:()=>gw,FlowGraphCounterBlock:()=>bO,FlowGraphCrossBlock:()=>sw,FlowGraphCubeRootBlock:()=>JD,FlowGraphDataConnection:()=>zM,FlowGraphDebounceBlock:()=>yO,FlowGraphDegToRadBlock:()=>wD,FlowGraphDeterminantBlock:()=>aw,FlowGraphDivideBlock:()=>eD,FlowGraphDoNBlock:()=>_O,FlowGraphDotBlock:()=>iD,FlowGraphEBlock:()=>sD,FlowGraphEqBlock:()=>ED,FlowGraphEventBlock:()=>qM,FlowGraphExecutionBlock:()=>KM,FlowGraphExpBlock:()=>jD,FlowGraphFlipFlopBlock:()=>SO,FlowGraphFloorBlock:()=>uD,FlowGraphForLoopBlock:()=>pO,FlowGraphFractBlock:()=>_D,FlowGraphGetPropertyBlock:()=>DO,FlowGraphGetVariableBlock:()=>RO,FlowGraphGreaterThanBlock:()=>RD,FlowGraphGreaterThanOrEqualBlock:()=>MD,FlowGraphInfBlock:()=>nD,FlowGraphInterpolateBlock:()=>CD,FlowGraphInvertMatrixBlock:()=>lw,FlowGraphIsInfBlock:()=>DD,FlowGraphIsNanBlock:()=>OD,FlowGraphLengthBlock:()=>tw,FlowGraphLessThanBlock:()=>PD,FlowGraphLessThanOrEqualBlock:()=>ID,FlowGraphLog10Block:()=>qD,FlowGraphLog2Block:()=>$D,FlowGraphLogBlock:()=>KD,FlowGraphLogicAndBlock:()=>zO,FlowGraphLogicNotBlock:()=>HO,FlowGraphLogicOrBlock:()=>WO,FlowGraphMatMulBlock:()=>hw,FlowGraphMaxBlock:()=>vD,FlowGraphMeshPickEventBlock:()=>eO,FlowGraphMinBlock:()=>gD,FlowGraphMultiGateBlock:()=>gO,FlowGraphMultiplyBlock:()=>JO,FlowGraphNaNBlock:()=>oD,FlowGraphNegBlock:()=>pD,FlowGraphNormalizeBlock:()=>iw,FlowGraphPauseAnimationBlock:()=>PO,FlowGraphPiBlock:()=>rD,FlowGraphPlayAnimationBlock:()=>EO,FlowGraphPowBlock:()=>ew,FlowGraphRadToDegBlock:()=>ND,FlowGraphRandomBlock:()=>tD,FlowGraphReceiveCustomEventBlock:()=>bw,FlowGraphRemainderBlock:()=>mD,FlowGraphRotate2DBlock:()=>rw,FlowGraphRotate3DBlock:()=>nw,FlowGraphSaturateBlock:()=>SD,FlowGraphSceneReadyEventBlock:()=>xw,FlowGraphSceneTickEventBlock:()=>Tw,FlowGraphSendCustomEventBlock:()=>uO,FlowGraphSequenceBlock:()=>CO,FlowGraphSetPropertyBlock:()=>cO,FlowGraphSetVariableBlock:()=>aO,FlowGraphSignBlock:()=>hD,FlowGraphSignalConnection:()=>jM,FlowGraphSinBlock:()=>FD,FlowGraphSinhBlock:()=>zD,FlowGraphSqrtBlock:()=>ZD,FlowGraphState:()=>tO,FlowGraphStopAnimationBlock:()=>AO,FlowGraphSubtractBlock:()=>ZO,FlowGraphSwitchBlock:()=>vO,FlowGraphTanBlock:()=>BD,FlowGraphTanhBlock:()=>HD,FlowGraphThrottleBlock:()=>fO,FlowGraphTimerBlock:()=>mO,FlowGraphTransposeBlock:()=>ow,FlowGraphTruncBlock:()=>cD,FlowGraphWaitAllBlock:()=>xO,FlowGraphWhileLoopBlock:()=>TO,FluidRenderer:()=>fI,FluidRendererSceneComponent:()=>pI,FluidRenderingDebug:()=>oI,FluidRenderingObject:()=>sI,FluidRenderingObjectCustomParticles:()=>lI,FluidRenderingObjectParticleSystem:()=>rI,FluidRenderingTargetRenderer:()=>aI,FlyCamera:()=>dc,FlyCameraInputsManager:()=>uc,FlyCameraKeyboardInput:()=>Yh,FlyCameraMouseInput:()=>Qh,FogBlock:()=>Qb,FollowBehavior:()=>$a,FollowCamera:()=>pc,FollowCameraInputsManager:()=>_c,FollowCameraKeyboardMoveInput:()=>jh,FollowCameraMouseWheelInput:()=>Kh,FollowCameraPointersInput:()=>$h,FragCoordBlock:()=>Vb,FragDepthBlock:()=>Hb,FragmentOutputBlock:()=>El,FramingBehavior:()=>La,FreeCamera:()=>ac,FreeCameraDeviceOrientationInput:()=>ic,FreeCameraGamepadInput:()=>sc,FreeCameraInputsManager:()=>tc,FreeCameraKeyboardMoveInput:()=>qh,FreeCameraMouseInput:()=>Zh,FreeCameraMouseWheelInput:()=>Jh,FreeCameraTouchInput:()=>ec,FreeCameraVirtualJoystickInput:()=>nc,FresnelBlock:()=>xT,FresnelParameters:()=>Dx,FromHalfFloat:()=>ip,FrontFace:()=>Rf,FrontFacingBlock:()=>Bb,Frustum:()=>Fr,FxaaPostProcess:()=>uP,GIRSM:()=>xI,GIRSMManager:()=>bI,GIRSMRenderPluginMaterial:()=>yI,GPUParticleSystem:()=>UE,GUID:()=>Es,Gamepad:()=>kh,GamepadCamera:()=>Tc,GamepadManager:()=>vc,GamepadSystemSceneComponent:()=>xc,GaussianSplattingMaterial:()=>Vy,GaussianSplattingMesh:()=>aE,GenerateBase64StringFromPixelData:()=>Sa,GenerateBase64StringFromTexture:()=>Ca,GenerateBase64StringFromTextureAsync:()=>Ea,GenericPad:()=>Vh,GeodesicData:()=>b_,Geometry:()=>Yn,GeometryArcTan2Block:()=>HC,GeometryBufferRenderer:()=>mP,GeometryBufferRendererSceneComponent:()=>vP,GeometryClampBlock:()=>qC,GeometryCollectionBlock:()=>dC,GeometryCrossBlock:()=>ZC,GeometryCurveBlock:()=>JC,GeometryCurveBlockTypes:()=>yS,GeometryDesaturateBlock:()=>eE,GeometryDistanceBlock:()=>sE,GeometryDotBlock:()=>rE,GeometryElbowBlock:()=>_C,GeometryInfoBlock:()=>FC,GeometryInputBlock:()=>GS,GeometryLengthBlock:()=>nE,GeometryLerpBlock:()=>XC,GeometryModBlock:()=>KC,GeometryNLerpBlock:()=>YC,GeometryOptimizeBlock:()=>HS,GeometryOutputBlock:()=>VS,GeometryPosterizeBlock:()=>tE,GeometryPowBlock:()=>$C,GeometryReplaceColorBlock:()=>iE,GeometryRotate2dBlock:()=>oE,GeometrySmoothStepBlock:()=>jC,GeometryStepBlock:()=>QC,GeometryTextureBlock:()=>UC,GeometryTextureFetchBlock:()=>GC,GeometryTransformBlock:()=>xC,GeometryTrigonometryBlock:()=>vC,GeometryTrigonometryBlockOperations:()=>xS,GetClass:()=>W,GetClassName:()=>H,GetDOMTextContent:()=>Gt,GetEnvInfo:()=>bp,GetEnvironmentBRDFTexture:()=>Eg,GetFogState:()=>Uo,GetFontOffset:()=>Zn,GetInternalFormatFromBasisFormat:()=>hb,GetPointsCount:()=>NS,GetTGAHeader:()=>Jx,GetTextureDataAsync:()=>rp,Gizmo:()=>sd,GizmoAnchorPoint:()=>ed,GizmoCoordinatesMode:()=>td,GizmoManager:()=>lg,GlowLayer:()=>Fv,GoldbergMesh:()=>y_,GradientBlock:()=>FT,GradientBlockColorStep:()=>NT,GradientHelper:()=>PE,GrainPostProcess:()=>dP,GreasedLineBaseMesh:()=>RS,GreasedLineMaterialDefaults:()=>Ry,GreasedLineMesh:()=>MS,GreasedLineMeshColorDistribution:()=>cS,GreasedLineMeshColorDistributionType:()=>oy,GreasedLineMeshColorMode:()=>ny,GreasedLineMeshMaterialType:()=>ry,GreasedLineMeshWidthDistribution:()=>uS,GreasedLinePluginMaterial:()=>Dy,GreasedLineRibbonAutoDirectionMode:()=>hS,GreasedLineRibbonFacesMode:()=>lS,GreasedLineRibbonMesh:()=>OS,GreasedLineRibbonPointsMode:()=>aS,GreasedLineSimpleMaterial:()=>wy,GreasedLineTools:()=>My,GridBlock:()=>KS,GroundBuilder:()=>Ou,GroundMesh:()=>Cu,HDRCubeTexture:()=>nx,HDRCubeTextureAssetTask:()=>LI,HDRFiltering:()=>rx,HDRTools:()=>sx,Halton2DSequence:()=>zy,HandConstraintBehavior:()=>yh,HandConstraintOrientation:()=>bh,HandConstraintVisibility:()=>Th,HandConstraintZone:()=>xh,HandPart:()=>_h,HandleFallbacksForShadows:()=>Vo,HardwareScalingOptimization:()=>XI,HavokPlugin:()=>BA,HeightToNormalBlock:()=>Wb,HemisphereBuilder:()=>dg,HemisphericLight:()=>Zu,HemisphericParticleEmitter:()=>fE,HighlightLayer:()=>Bv,HighlightsPostProcess:()=>_P,Hinge2Joint:()=>rl,HingeConstraint:()=>CA,HingeJoint:()=>sl,HtmlElementTexture:()=>Ux,IWebXRControllerPhysicsOptions:()=>GR,IcoSphereBlock:()=>QS,IcoSphereBuilder:()=>dh,ImageAssetTask:()=>wI,ImageProcessingBlock:()=>wb,ImageProcessingConfiguration:()=>zs,ImageProcessingPostProcess:()=>pP,ImageSourceBlock:()=>Kb,IncrementValueAction:()=>ke,IndexFormat:()=>Ff,InputBlock:()=>Ol,InspectableType:()=>pR,InstancedLinesMesh:()=>Ld,InstancedMesh:()=>ca,InstancesBlock:()=>Mb,InstantiateBlock:()=>MC,InstantiateLinearBlock:()=>OC,InstantiateOnFacesBlock:()=>PC,InstantiateOnVerticesBlock:()=>AC,InstantiateOnVolumeBlock:()=>IC,InstantiateRadialBlock:()=>DC,InstantiatedEntries:()=>_a,IntFloatConverterBlock:()=>wC,InternalTexture:()=>ss,InternalTextureSource:()=>is,InterpolateValueAction:()=>Lt,IntersectionInfo:()=>Rn,IsBase64DataUrl:()=>gs,IsDocumentAvailable:()=>Ut,IsFileURL:()=>ms,IsNavigatorAvailable:()=>Vt,IsWindowObjectExist:()=>kt,IsWrapper:()=>Ws,JoystickAxis:()=>Mh,KeepAssets:()=>da,KeyboardEventTypes:()=>dr,KeyboardInfo:()=>_r,KeyboardInfoPre:()=>pr,KhronosTextureContainer:()=>Xg,KhronosTextureContainer2:()=>ev,LatheBuilder:()=>i_,Layer:()=>Vv,LayerSceneComponent:()=>kv,LengthBlock:()=>ST,LensFlare:()=>Uv,LensFlareSystem:()=>Gv,LensFlareSystemSceneComponent:()=>zv,LensFlaresOptimization:()=>jI,LensRenderingPipeline:()=>AP,LerpBlock:()=>_T,Light:()=>ua,LightBlock:()=>jb,LightGizmo:()=>pg,LightInformationBlock:()=>Db,LineEdgesRenderer:()=>KP,LinesBuilder:()=>zd,LinesMesh:()=>Fd,LoadFile:()=>ps,LoadFileError:()=>as,LoadImage:()=>ds,LoadOp:()=>Uf,LoadTextureFromTranscodeResult:()=>mb,LockConstraint:()=>AA,Logger:()=>Ne,MapMode:()=>cf,MapRangeBlock:()=>aC,MappingBlock:()=>LC,MappingTypes:()=>bS,Material:()=>ta,MaterialAnisotropicDefines:()=>wg,MaterialClearCoatDefines:()=>Rg,MaterialDefines:()=>xl,MaterialDetailMapDefines:()=>ou,MaterialFlags:()=>$c,MaterialGreasedLineDefines:()=>Oy,MaterialHelper:()=>wx,MaterialIridescenceDefines:()=>Og,MaterialPluginBase:()=>nu,MaterialPluginEvent:()=>fo,MaterialPluginManager:()=>Zc,MaterialSheenDefines:()=>Fg,MaterialSubSurfaceDefines:()=>Bg,MathBlock:()=>oC,MathBlockOperations:()=>mS,Matrix:()=>me,MatrixBuilderBlock:()=>ey,MatrixComposeBlock:()=>BC,MatrixDeterminantBlock:()=>_y,MatrixTransposeBlock:()=>py,MaxBlock:()=>bT,MergeGeometryBlock:()=>uC,MergeMeshesOptimization:()=>ZI,Mesh:()=>ha,MeshAssetTask:()=>RI,MeshAttributeExistsBlock:()=>fy,MeshAttributeExistsBlockTypes:()=>iy,MeshBlock:()=>YS,MeshBuilder:()=>R_,MeshDebugMode:()=>Fy,MeshDebugPluginMaterial:()=>By,MeshExploder:()=>UI,MeshLODLevel:()=>sa,MeshParticleEmitter:()=>bE,MeshUVSpaceRenderer:()=>iS,MeshoptCompression:()=>Ky,MinBlock:()=>TT,MinMaxReducer:()=>Xv,MipmapFilterMode:()=>vf,MirrorTexture:()=>gg,ModBlock:()=>JT,ModelShape:()=>HE,MorphTarget:()=>ox,MorphTargetManager:()=>lx,MorphTargetsBlock:()=>Ob,MotionBlurPostProcess:()=>xP,MotorEnabledJoint:()=>il,MultiMaterial:()=>ia,MultiObserver:()=>zI,MultiPointerScaleBehavior:()=>Ya,MultiRenderTarget:()=>xb,MultiplyBlock:()=>Wl,NLerpBlock:()=>LT,NativeDataStream:()=>fp,NativeEngine:()=>rf,NativePointerInput:()=>gr,NativeXRFrame:()=>CM,NativeXRLayerRenderTargetTextureProvider:()=>xu,NativeXRLayerWrapper:()=>vu,NativeXRRenderTarget:()=>bu,NegateBlock:()=>CT,Node:()=>Et,NodeGeometry:()=>WS,NodeGeometryBlock:()=>kS,NodeGeometryBlockConnectionPointTypes:()=>dS,NodeGeometryBuildState:()=>US,NodeGeometryConnectionPoint:()=>BS,NodeGeometryConnectionPointCompatibilityStates:()=>_S,NodeGeometryConnectionPointDirection:()=>pS,NodeGeometryContextualSources:()=>fS,NodeMaterial:()=>hh,NodeMaterialBlock:()=>Tl,NodeMaterialBlockConnectionPointMode:()=>dl,NodeMaterialBlockConnectionPointTypes:()=>al,NodeMaterialBlockTargets:()=>ll,NodeMaterialConnectionPoint:()=>bl,NodeMaterialConnectionPointCompatibilityStates:()=>hl,NodeMaterialConnectionPointCustomObject:()=>Ib,NodeMaterialConnectionPointDirection:()=>cl,NodeMaterialDefines:()=>lh,NodeMaterialModes:()=>Hl,NodeMaterialOptimizer:()=>gy,NodeMaterialSystemValues:()=>_l,NodeMaterialTeleportInBlock:()=>iT,NodeMaterialTeleportOutBlock:()=>sT,NoiseBlock:()=>cC,NoiseProceduralTexture:()=>Sb,NormalBlendBlock:()=>VT,NormalizeBlock:()=>cT,NormalizeVectorBlock:()=>mC,NullBlock:()=>eC,NullEngine:()=>L_,NullEngineOptions:()=>F_,Observable:()=>K,Observer:()=>j,OcclusionMaterial:()=>Nx,Octree:()=>Qu,OctreeBlock:()=>Yu,OctreeSceneComponent:()=>ju,OimoJSPlugin:()=>_x,OnAfterEnteringVRObservableEvent:()=>Bu,OneMinusBlock:()=>gT,Orientation:()=>zr,OutlineRenderer:()=>iI,PBRAnisotropicConfiguration:()=>Ng,PBRBaseMaterial:()=>Gg,PBRBaseSimpleMaterial:()=>Fx,PBRClearCoatConfiguration:()=>Mg,PBRIridescenceConfiguration:()=>Dg,PBRMaterial:()=>zg,PBRMaterialDefines:()=>Ug,PBRMetallicRoughnessBlock:()=>ZT,PBRMetallicRoughnessMaterial:()=>Lx,PBRSheenConfiguration:()=>Lg,PBRSpecularGlossinessMaterial:()=>Bx,PBRSubSurfaceConfiguration:()=>kg,PHI:()=>Z,PadNumber:()=>ti,PanoramaToCubeMapTools:()=>ix,Particle:()=>IE,ParticleBlendMultiplyBlock:()=>Fl,ParticleHelper:()=>zE,ParticleRampGradientBlock:()=>Nl,ParticleSystem:()=>VE,ParticleSystemSet:()=>GE,ParticleTextureBlock:()=>wl,ParticlesOptimization:()=>$I,PassCubePostProcess:()=>Sc,PassPostProcess:()=>yc,Path2:()=>Zr,Path3D:()=>Jr,PathCursor:()=>vn,PerfCollectionStrategy:()=>wR,PerfCounter:()=>wr,PerformanceConfigurator:()=>se,PerformanceMonitor:()=>Qn,PerformanceViewerCollector:()=>OR,PerturbNormalBlock:()=>Fb,PhotoDome:()=>Sg,Physics6DoFConstraint:()=>TA,Physics6DoFLimit:()=>bA,PhysicsActivationControl:()=>rA,PhysicsAggregate:()=>RA,PhysicsBody:()=>cA,PhysicsConstraint:()=>xA,PhysicsConstraintAxis:()=>ZE,PhysicsConstraintAxisLimitMode:()=>qE,PhysicsConstraintMotorType:()=>tA,PhysicsConstraintType:()=>JE,PhysicsEngine:()=>ux,PhysicsEngineV2:()=>hA,PhysicsEventType:()=>iA,PhysicsHelper:()=>UA,PhysicsImpostor:()=>nl,PhysicsJoint:()=>el,PhysicsMaterialCombineMode:()=>nA,PhysicsMotionType:()=>sA,PhysicsRadialExplosionEventOptions:()=>XA,PhysicsRadialImpulseFalloff:()=>oA,PhysicsRaycastResult:()=>cx,PhysicsShape:()=>uA,PhysicsShapeBox:()=>fA,PhysicsShapeCapsule:()=>_A,PhysicsShapeContainer:()=>vA,PhysicsShapeConvexHull:()=>mA,PhysicsShapeCylinder:()=>pA,PhysicsShapeMesh:()=>gA,PhysicsShapeSphere:()=>dA,PhysicsShapeType:()=>eA,PhysicsUpdraftEventOptions:()=>YA,PhysicsUpdraftMode:()=>aA,PhysicsViewer:()=>M_,PhysicsVortexEventOptions:()=>QA,PickingInfo:()=>tr,PipelineErrorReason:()=>Af,PivotTools:()=>Ga,Plane:()=>Nr,PlaneBlock:()=>XS,PlaneBuilder:()=>Ha,PlaneDragGizmo:()=>ng,PlaneRotationGizmo:()=>sg,PlayAnimationAction:()=>Ve,PlaySoundAction:()=>je,PointColor:()=>$E,PointLight:()=>ex,PointParticleEmitter:()=>mE,PointerDragBehavior:()=>Xa,PointerEventTypes:()=>lr,PointerInfo:()=>ur,PointerInfoBase:()=>hr,PointerInfoPre:()=>cr,PointerInput:()=>mr,PointsCloudSystem:()=>lA,PointsGroup:()=>KE,Polar:()=>Uy,Polygon:()=>Xd,PolygonBuilder:()=>$d,PolygonMeshBuilder:()=>Yd,PolyhedronBuilder:()=>a_,PolyhedronData:()=>x_,PositionGizmo:()=>og,PositionNormalTextureVertex:()=>Pl,PositionNormalVertex:()=>Al,PostProcess:()=>Vl,PostProcessManager:()=>ir,PostProcessRenderEffect:()=>qA,PostProcessRenderPipeline:()=>yP,PostProcessRenderPipelineManager:()=>SP,PostProcessRenderPipelineManagerSceneComponent:()=>CP,PostProcessesOptimization:()=>QI,PosterizeBlock:()=>OT,PowBlock:()=>ET,PowerEase:()=>hn,PowerPreference:()=>of,PrePassOutputBlock:()=>Yb,PrePassRenderer:()=>qP,PrePassRendererSceneComponent:()=>ZP,PrePassTextureBlock:()=>tT,PrecisionDate:()=>Wt,PredicateCondition:()=>De,PrepareAttributesForBakedVertexAnimation:()=>Do,PrepareAttributesForBones:()=>Bo,PrepareAttributesForInstances:()=>ko,PrepareAttributesForMorphTargets:()=>Ao,PrepareAttributesForMorphTargetsInfluencers:()=>Eo,PrepareDefinesForAttributes:()=>jo,PrepareDefinesForBakedVertexAnimation:()=>Qo,PrepareDefinesForBones:()=>Xo,PrepareDefinesForCamera:()=>Zo,PrepareDefinesForFrameBoundValues:()=>Ho,PrepareDefinesForLight:()=>Wo,PrepareDefinesForLights:()=>zo,PrepareDefinesForMergedUV:()=>Mo,PrepareDefinesForMisc:()=>Go,PrepareDefinesForMorphTargets:()=>Yo,PrepareDefinesForMultiview:()=>Ko,PrepareDefinesForOIT:()=>$o,PrepareDefinesForPrePass:()=>qo,PrepareUniformsAndSamplersForLight:()=>Jo,PrepareUniformsAndSamplersList:()=>ea,PressureObserverWrapper:()=>ER,PrimitiveTopology:()=>If,PrismaticConstraint:()=>PA,ProceduralTexture:()=>rh,ProceduralTextureSceneComponent:()=>sh,PropertyTypeForEdition:()=>ul,ProximityCastResult:()=>jA,PushAttributesForInstances:()=>Po,PushMaterial:()=>ml,QuadraticEase:()=>cn,QuadraticErrorSimplification:()=>PS,QuarticEase:()=>un,Quaternion:()=>fe,QueryType:()=>zf,QueueNewFrame:()=>rs,QuinticEase:()=>dn,RGBDTextureTools:()=>mp,RSMCreatePluginMaterial:()=>vI,Ragdoll:()=>OA,RagdollBoneProperties:()=>MA,RandomBlock:()=>hC,RandomBlockLocks:()=>vS,RandomGUID:()=>Cs,RandomNumberBlock:()=>AT,RawCubeTexture:()=>Cb,RawTexture:()=>Oa,RawTexture2DArray:()=>ax,RawTexture3D:()=>Eb,Ray:()=>Ua,RayHelper:()=>O_,ReadFile:()=>_s,ReadFileError:()=>hs,RecastJSCrowd:()=>hE,RecastJSPlugin:()=>lE,ReciprocalBlock:()=>RT,ReflectBlock:()=>GT,ReflectionBlock:()=>YT,ReflectionProbe:()=>fx,ReflectionTextureBaseBlock:()=>qb,ReflectionTextureBlock:()=>Zb,ReflectiveShadowMap:()=>mI,Reflector:()=>CR,RefractBlock:()=>zT,RefractionBlock:()=>KT,RefractionPostProcess:()=>bP,RefractionTexture:()=>Ab,RegisterClass:()=>z,RegisterMaterialPlugin:()=>iu,RegisterNativeTypeAsync:()=>Jp,RemapBlock:()=>Gl,RenderPassTimestampLocation:()=>Vf,RenderTargetTexture:()=>ih,RenderTargetWrapper:()=>Bl,RenderTargetsOptimization:()=>qI,RenderingGroup:()=>sr,RenderingGroupInfo:()=>rr,RenderingManager:()=>nr,ReplaceColorBlock:()=>MT,RequestFile:()=>fs,RequestFileError:()=>ls,RequestFullscreen:()=>to,RequestPointerlock:()=>so,ResizeImageBitmap:()=>eo,RetryStrategy:()=>Xt,RibbonBuilder:()=>bd,RichType:()=>IM,RichTypeAny:()=>RM,RichTypeBoolean:()=>DM,RichTypeColor3:()=>BM,RichTypeColor4:()=>kM,RichTypeFlowGraphInteger:()=>UM,RichTypeMatrix:()=>LM,RichTypeNumber:()=>OM,RichTypeQuaternion:()=>VM,RichTypeString:()=>MM,RichTypeVector2:()=>wM,RichTypeVector3:()=>NM,RichTypeVector4:()=>FM,RollingAverage:()=>jn,Rotate2dBlock:()=>UT,RotationGizmo:()=>rg,RotationXBlock:()=>bC,RotationYBlock:()=>TC,RotationZBlock:()=>yC,RuntimeAnimation:()=>Bt,RuntimeError:()=>jt,SSAO2RenderingPipeline:()=>IP,SSAORenderingPipeline:()=>RP,SSRRenderingPipeline:()=>LP,SamplerBindingType:()=>yf,Scalar:()=>be,ScaleBlock:()=>nT,ScaleGizmo:()=>ag,ScalingBlock:()=>SC,Scene:()=>Hr,SceneComponentConstants:()=>or,SceneDepthBlock:()=>Jb,SceneInstrumentation:()=>Dv,SceneLoader:()=>fl,SceneLoaderAnimationGroupLoadingMode:()=>ol,SceneLoaderFlags:()=>Hn,SceneOptimization:()=>WI,SceneOptimizer:()=>eR,SceneOptimizerOptions:()=>JI,ScenePerformancePriority:()=>Vr,SceneRecorder:()=>vR,SceneSerializer:()=>rR,ScreenSizeBlock:()=>Ub,ScreenSpaceBlock:()=>Gb,ScreenSpaceCurvaturePostProcess:()=>GP,ScreenSpaceReflectionPostProcess:()=>OP,ScreenshotTools:()=>_R,SerializationHelper:()=>St,SetBasisTranscoderWorker:()=>_b,SetColorsBlock:()=>rC,SetCorsBehavior:()=>us,SetMaterialIDBlock:()=>gC,SetNormalsBlock:()=>iC,SetParentAction:()=>He,SetPositionsBlock:()=>tC,SetStateAction:()=>Le,SetTangentsBlock:()=>nC,SetUVsBlock:()=>sC,SetValueAction:()=>Be,ShaderCodeInliner:()=>Bp,ShaderLanguage:()=>di,ShaderMaterial:()=>Nd,ShaderStage:()=>bf,ShaderStore:()=>Bi,ShadowDepthWrapper:()=>xy,ShadowGenerator:()=>Wv,ShadowGeneratorSceneComponent:()=>Jv,ShadowLight:()=>hg,ShadowMapBlock:()=>Xb,ShadowsOptimization:()=>YI,ShapeBuilder:()=>e_,ShapeCastResult:()=>KA,SharpenPostProcess:()=>TP,SheenBlock:()=>HT,SimplexPerlin3DBlock:()=>kT,SimplicationQueueSceneComponent:()=>IS,SimplificationQueue:()=>nS,SimplificationSettings:()=>rS,SimplificationType:()=>oS,SineEase:()=>_n,SixDofDragBehavior:()=>ja,Size:()=>At,Skeleton:()=>Da,SkeletonViewer:()=>D_,SliderConstraint:()=>EA,SmartArray:()=>Fs,SmartArrayNoDuplicate:()=>Ls,SmoothStepBlock:()=>IT,SolidParticle:()=>WE,SolidParticleSystem:()=>QE,SolidParticleVertex:()=>YE,Sound:()=>ma,SoundTrack:()=>ga,SourceTextureFormat:()=>jg,Space:()=>Ur,SphereBlock:()=>jS,SphereBuilder:()=>pd,SphereDirectedParticleEmitter:()=>vE,SphereParticleEmitter:()=>gE,Spherical:()=>Gy,SphericalHarmonics:()=>Q_,SphericalPolynomial:()=>j_,SpotLight:()=>_g,SpringConstraint:()=>IA,Sprite:()=>gx,SpriteManager:()=>bx,SpriteMap:()=>SI,SpritePackedManager:()=>CI,SpriteSceneComponent:()=>vx,Stage:()=>ar,StandardMaterial:()=>cu,StandardMaterialDefines:()=>hu,StandardRenderingPipeline:()=>DP,StartsWith:()=>$t,StateCondition:()=>we,StencilOperation:()=>Nf,StencilState:()=>Ji,StencilStateComposer:()=>Zi,StepBlock:()=>mT,StereoscopicArcRotateCamera:()=>wc,StereoscopicFreeCamera:()=>Nc,StereoscopicGamepadCamera:()=>Fc,StereoscopicInterlacePostProcess:()=>Oc,StereoscopicInterlacePostProcessI:()=>Mc,StereoscopicScreenUniversalCamera:()=>Bc,StereoscopicUniversalCamera:()=>Lc,StickValues:()=>Bh,StopAnimationAction:()=>Ue,StopSoundAction:()=>Ke,StorageBuffer:()=>Eh,StorageTextureAccess:()=>Cf,StoreOp:()=>Gf,StringDictionary:()=>Bs,StringTools:()=>ii,SubEmitter:()=>OE,SubEmitterType:()=>ME,SubMesh:()=>Gn,SubSurfaceBlock:()=>$T,SubSurfaceSceneComponent:()=>tI,SubtractBlock:()=>fT,SurfaceMagnetismBehavior:()=>Ka,SwitchBooleanAction:()=>Fe,SwitchInput:()=>Tr,TAARenderingPipeline:()=>BP,TBNBlock:()=>Nb,TGATools:()=>tb,Tags:()=>Tt,TargetCamera:()=>oc,TargetedAnimation:()=>mn,TeleportInBlock:()=>kC,TeleportOutBlock:()=>VC,TestBase64DataUrl:()=>vs,TextFileAssetTask:()=>OI,Texture:()=>Pa,TextureAspect:()=>pf,TextureAssetTask:()=>NI,TextureBlock:()=>$b,TextureDimension:()=>uf,TextureFormat:()=>ff,TextureOptimization:()=>HI,TexturePacker:()=>Tb,TexturePackerFrame:()=>bb,TextureSampleType:()=>Sf,TextureSampler:()=>ts,TextureTools:()=>np,TextureUsage:()=>df,TextureViewDimension:()=>_f,ThinEngine:()=>qs,ThinRenderTargetTexture:()=>Pb,ThinTexture:()=>Ta,TiledBoxBuilder:()=>Rd,TiledPlaneBuilder:()=>Ad,TimerState:()=>gv,TmpColors:()=>Pe,TmpVectors:()=>ve,ToGammaSpace:()=>$,ToHalfFloat:()=>tp,ToLinearSpace:()=>q,TonemapPostProcess:()=>VP,TonemappingOperator:()=>kP,Tools:()=>Ds,TorusBlock:()=>$S,TorusBuilder:()=>Nu,TorusKnotBuilder:()=>Dd,TouchCamera:()=>lc,TrailMesh:()=>sS,Trajectory:()=>xR,TrajectoryClassifier:()=>SR,TranscodeAsync:()=>pb,TranscodeTarget:()=>Kg,TransformBlock:()=>yl,TransformNode:()=>lo,TranslationBlock:()=>EC,TriPlanarBlock:()=>uy,TrigonometryBlock:()=>oh,TrigonometryBlockOperations:()=>nh,TubeBuilder:()=>r_,TwirlBlock:()=>zb,UniformBuffer:()=>Zs,UniversalCamera:()=>bc,UnregisterAllMaterialPlugins:()=>ru,UnregisterMaterialPlugin:()=>su,UploadContent:()=>eb,UploadEnvLevelsAsync:()=>Ep,UploadEnvSpherical:()=>Ip,UploadLevelsAsync:()=>Pp,UtilityLayerRenderer:()=>Ju,VRCameraMetrics:()=>Vc,VRDeviceOrientationArcRotateCamera:()=>Yc,VRDeviceOrientationFreeCamera:()=>Qc,VRDeviceOrientationGamepadCamera:()=>jc,VRDistortionCorrectionPostProcess:()=>Uc,VRExperienceHelper:()=>ku,VRMultiviewToSingleviewPostProcess:()=>Hc,ValidatedNativeDataStream:()=>nf,ValueCondition:()=>Oe,Vector2:()=>de,Vector2ToFixed:()=>Wy,Vector3:()=>_e,Vector3ToFixed:()=>Hy,Vector4:()=>pe,Vector4ToFixed:()=>Xy,VectorConverterBlock:()=>fC,VectorMergerBlock:()=>Ul,VectorSplitterBlock:()=>dT,VertexAnimationBaker:()=>wa,VertexBuffer:()=>er,VertexData:()=>Wn,VertexDataMaterialInfo:()=>zn,VertexFormat:()=>Lf,VertexOutputBlock:()=>Sl,VertexStepMode:()=>Bf,VideoDome:()=>Mv,VideoRecorder:()=>nR,VideoTexture:()=>Rv,ViewDirectionBlock:()=>vT,Viewport:()=>Pn,VirtualJoystick:()=>rc,VirtualJoysticksCamera:()=>kc,VolumetricLightScatteringPostProcess:()=>UP,VoronoiNoiseBlock:()=>hy,WaveBlock:()=>wT,WaveBlockKind:()=>DT,WebGL2ParticleSystem:()=>yE,WebGL2ShaderProcessor:()=>Ys,WebGLDataBuffer:()=>js,WebGLHardwareTexture:()=>Ks,WebGLPipelineContext:()=>ki,WebGPUCacheBindGroups:()=>Am,WebGPUCacheRenderPipeline:()=>gm,WebGPUCacheRenderPipelineTree:()=>xm,WebGPUCacheSampler:()=>_m,WebGPUDataBuffer:()=>lm,WebGPUDrawContext:()=>Cm,WebGPUEngine:()=>Ym,WebGPURenderTargetWrapper:()=>qm,WebGPUTintWASM:()=>Um,WebRequest:()=>Pt,WebXRAbstractFeature:()=>Ja,WebXRAbstractMotionController:()=>nv,WebXRAnchorSystem:()=>BR,WebXRBackgroundRemover:()=>UR,WebXRCamera:()=>iv,WebXRControllerComponent:()=>rv,WebXRControllerMovement:()=>$R,WebXRControllerPhysics:()=>zR,WebXRControllerPointerSelection:()=>pv,WebXRDefaultExperience:()=>Av,WebXRDefaultExperienceOptions:()=>Ev,WebXRDepthSensing:()=>uM,WebXRDomOverlay:()=>KR,WebXREnterExitUI:()=>Tv,WebXREnterExitUIButton:()=>xv,WebXREnterExitUIOptions:()=>bv,WebXRExperienceHelper:()=>sv,WebXREyeTracking:()=>ZR,WebXRFeatureName:()=>qa,WebXRFeaturePointSystem:()=>HR,WebXRFeaturesManager:()=>Za,WebXRGenericHandController:()=>mM,WebXRGenericTriggerMotionController:()=>ov,WebXRHTCViveMotionController:()=>yM,WebXRHand:()=>gh,WebXRHandJoint:()=>ph,WebXRHandTracking:()=>vh,WebXRHitTest:()=>WR,WebXRHitTestLegacy:()=>FR,WebXRImageTracking:()=>jR,WebXRInput:()=>_v,WebXRInputSource:()=>dv,WebXRLayerRenderTargetTextureProvider:()=>_u,WebXRLayers:()=>cM,WebXRLightEstimation:()=>qR,WebXRManagedOutputCanvas:()=>gu,WebXRManagedOutputCanvasOptions:()=>mu,WebXRMeshDetector:()=>YR,WebXRMicrosoftMixedRealityController:()=>vM,WebXRMotionControllerManager:()=>cv,WebXRMotionControllerTeleportation:()=>Cv,WebXRNearControllerMode:()=>mv,WebXRNearInteraction:()=>vv,WebXROculusTouchMotionController:()=>bM,WebXRPlaneDetector:()=>VR,WebXRProfiledMotionController:()=>lv,WebXRRawCameraAccess:()=>fM,WebXRSessionManager:()=>Tu,WebXRSpaceWarp:()=>pM,WebXRSpaceWarpRenderTargetTextureProvider:()=>_M,WebXRState:()=>yu,WebXRTrackingState:()=>Su,WebXRWalkingLocomotion:()=>sM,WeightedSound:()=>xa,WorkerPool:()=>Yg,WorleyNoise3DBlock:()=>BT,XRSpaceWarpRenderTarget:()=>dM,Xbox360Button:()=>Oh,Xbox360Dpad:()=>Dh,Xbox360Pad:()=>mc,XboxInput:()=>br,_BabylonLoaderRegistered:()=>Tx,_BasisTextureLoader:()=>vb,_CommonDispose:()=>qn,_CommonInit:()=>$n,_CreationDataStorage:()=>ra,_DDSTextureLoader:()=>Wg,_ENVTextureLoader:()=>Hg,_HDRTextureLoader:()=>sb,_InstancesBatch:()=>oa,_KTXTextureLoader:()=>tv,_MeshCollisionData:()=>ho,_OcclusionDataStorage:()=>B_,_PrimaryIsoTriangle:()=>v_,_TGATextureLoader:()=>ib,_TimeToken:()=>G_,_UpdateRGBDAsync:()=>Rp,_forceSceneHelpersToBundle:()=>Pv,_forceTransformFeedbackToBundle:()=>z_,_injectLTSFileTools:()=>ys,_staticOffsetValueColor3:()=>Dt,_staticOffsetValueColor4:()=>wt,_staticOffsetValueQuaternion:()=>It,_staticOffsetValueSize:()=>Ot,_staticOffsetValueVector2:()=>Mt,_staticOffsetValueVector3:()=>Rt,addClipPlaneUniforms:()=>mo,allocateAndCopyTypedBuffer:()=>Kn,bindClipPlane:()=>xo,captureEquirectangularFromScene:()=>NR,className:()=>ws,createDetailMapPlugin:()=>Iy,createPBRAnisotropicPlugin:()=>yy,createPBRBRDFPlugin:()=>Sy,createPBRClearCoatPlugin:()=>Cy,createPBRIridescencePlugin:()=>Ey,createPBRSheenPlugin:()=>Ay,createPBRSubSurfacePlugin:()=>Py,createYieldingScheduler:()=>Tn,editableInPropertyPage:()=>Cl,expandToProperty:()=>st,extractMinAndMax:()=>Vn,extractMinAndMaxIndexed:()=>kn,getRichTypeFromValue:()=>GM,inlineScheduler:()=>bn,makeAsyncFunction:()=>An,makeSyncFunction:()=>En,nativeOverride:()=>gt,normalizeEnvInfo:()=>Tp,prepareDefinesForClipPlanes:()=>vo,prepareStringDefinesForClipPlanes:()=>go,runCoroutine:()=>yn,runCoroutineAsync:()=>Cn,runCoroutineSync:()=>Sn,serialize:()=>rt,serializeAsCameraReference:()=>mt,serializeAsColor3:()=>ot,serializeAsColor4:()=>dt,serializeAsColorCurves:()=>ut,serializeAsFresnelParameters:()=>at,serializeAsImageProcessingConfiguration:()=>_t,serializeAsMatrix:()=>ft,serializeAsMeshReference:()=>ct,serializeAsQuaternion:()=>pt,serializeAsTexture:()=>nt,serializeAsVector2:()=>lt,serializeAsVector3:()=>ht,setAndStartTimer:()=>yv,setStereoscopicAnaglyphRigMode:()=>Ec,setStereoscopicRigMode:()=>Dc,setVRRigMode:()=>Xc});var t={};i.r(t),i.d(t,{AbstractButton3D:()=>AN,AdvancedDynamicTexture:()=>xN,AdvancedDynamicTextureInstrumentation:()=>bN,BaseGradient:()=>fN,BaseSlider:()=>Zw,Button:()=>Bw,Button3D:()=>PN,Checkbox:()=>Vw,CheckboxGroup:()=>tN,ColorPicker:()=>Ww,Container:()=>Dw,Container3D:()=>IN,Control:()=>Ow,Control3D:()=>CN,CornerHandle:()=>jN,CylinderPanel:()=>MN,DisplayGrid:()=>dN,Ellipse:()=>Hw,FluentBackplateMaterial:()=>LN,FluentButtonMaterial:()=>UN,FluentMaterial:()=>DN,FluentMaterialDefines:()=>ON,FocusableButton:()=>Xw,GUI3DManager:()=>vF,GizmoHandle:()=>YN,Grid:()=>zw,HandMenu:()=>NN,HandleMaterial:()=>HN,HandleState:()=>XN,HolographicBackplate:()=>BN,HolographicButton:()=>kN,HolographicSlate:()=>$N,Image:()=>Lw,ImageBasedSlider:()=>_N,ImageScrollBar:()=>aN,InputPassword:()=>Qw,InputText:()=>Gw,InputTextArea:()=>Yw,KeyPropertySet:()=>cN,Line:()=>jw,LinearGradient:()=>mN,MRDLBackplateMaterial:()=>oF,MRDLSliderBarMaterial:()=>iF,MRDLSliderThumbMaterial:()=>rF,MathTools:()=>Mw,Matrix2D:()=>Rw,Measure:()=>Pw,MeshButton3D:()=>qN,MultiLine:()=>$w,MultiLinePoint:()=>Kw,NearMenu:()=>ZN,PlanePanel:()=>JN,RadialGradient:()=>gN,RadioButton:()=>qw,RadioGroup:()=>iN,Rectangle:()=>ww,ScatterPanel:()=>eF,ScrollBar:()=>oN,ScrollViewer:()=>lN,SelectionPanel:()=>rN,SelectorGroup:()=>eN,SideHandle:()=>QN,SlateGizmo:()=>KN,Slider:()=>Jw,Slider3D:()=>aF,SliderGroup:()=>sN,SpherePanel:()=>lF,StackPanel:()=>kw,StackPanel3D:()=>hF,Style:()=>vN,TextBlock:()=>Fw,TextWrapper:()=>Uw,TextWrapping:()=>Nw,ToggleButton:()=>hN,TouchButton3D:()=>GN,TouchHolographicButton:()=>zN,TouchHolographicButtonV3:()=>gF,TouchHolographicMenu:()=>wN,TouchMeshButton3D:()=>cF,ValueAndUnit:()=>yw,Vector2WithInfo:()=>Iw,Vector3WithInfo:()=>SN,VirtualKeyboard:()=>uN,VolumeBasedPanel:()=>RN,XmlLoader:()=>yN,name:()=>pN});var r={};i.r(r),i.d(r,{LodDto:()=>Xz,lodEnum:()=>Bz});var n={};i.r(n),i.d(n,{Part:()=>Yz});var o={};i.r(o),i.d(o,{SerenitySwirlData:()=>jz,SerenitySwirlDto:()=>Qz});var a={};i.r(a),i.d(a,{ArabicArchwayData:()=>qz,ArabicArchwayDrawingPart:()=>Zz,ArabicArchwayDrawingPartShapes:()=>Jz,ArabicArchwayDto:()=>$z,ArabicArchwayDtoBase:()=>Kz});var l={};i.r(l),i.d(l,{ArabicArchway:()=>a,SerenitySwirl:()=>o});var h={};i.r(h),i.d(h,{EternalLoveData:()=>iW,EternalLoveDto:()=>tW,EternalLoveDtoBase:()=>eW});var c={};i.r(c),i.d(c,{EternalLove:()=>h});var u={};i.r(u),i.d(u,{CalmCupData:()=>nW,CalmCupDto:()=>rW,CalmCupDtoBase:()=>sW});var d={};i.r(d),i.d(d,{DragonCupData:()=>lW,DragonCupDto:()=>aW,DragonCupDtoBase:()=>oW,DragonCupModelDto:()=>hW});var _={};i.r(_),i.d(_,{CalmCup:()=>u,DragonCup:()=>d});var p={};i.r(p),i.d(p,{PhoneNestData:()=>dW,PhoneNestDrawDto:()=>gW,PhoneNestDrawingPart:()=>_W,PhoneNestDrawingPartShapes:()=>pW,PhoneNestDto:()=>uW,PhoneNestDtoBase:()=>cW,PhoneNestMainPart:()=>fW,PhoneNestModelDto:()=>mW});var f={};i.r(f),i.d(f,{PhoneNest:()=>p});var m={};i.r(m),i.d(m,{SpicyBoxData:()=>bW,SpicyBoxDto:()=>xW,SpicyBoxDtoBase:()=>vW,SpicyBoxModelDto:()=>TW});var g={};i.r(g),i.d(g,{SpicyBox:()=>m});var v={};i.r(v),i.d(v,{Boxes:()=>g,Cups:()=>_,Desktop:()=>f,Medals:()=>c,Vases:()=>l});var x={};i.r(x),i.d(x,{ZenHideoutData:()=>CW,ZenHideoutDrawingPart:()=>EW,ZenHideoutDrawingPartShapes:()=>AW,ZenHideoutDto:()=>SW,ZenHideoutDtoBase:()=>yW});var b={};i.r(b),i.d(b,{ZenHideout:()=>x});var T={};i.r(T),i.d(T,{BeamPart:()=>BW,CeilingPart:()=>YW,ColumnPart:()=>LW,CornerEntranceDto:()=>jW,CornerEntrancePart:()=>WW,CornerPart:()=>FW,CornerStairDto:()=>GW,CornerStairPart:()=>zW,FloorPart:()=>QW,Houses:()=>b,RoofBeamsPart:()=>VW,RoofCoverOneSidedDto:()=>HW,RoofCoverPart:()=>XW,RoofPanelPart:()=>UW,RoofPart:()=>kW,SandwitchPanelDto:()=>OW,SandwitchPanelFlexDto:()=>DW,SandwitchPart:()=>wW,SandwitchPartFlex:()=>NW,WindowCornerDto:()=>PW,WindowCornerPart:()=>MW,WindowRectangularDto:()=>IW,WindowRectangularPart:()=>RW});var y={};i.r(y),i.d(y,{WingtipVillaData:()=>$W,WingtipVillaDto:()=>KW});var S={};i.r(S),i.d(S,{ChirpyChaletData:()=>ZW,ChirpyChaletDto:()=>qW});var C={};i.r(C),i.d(C,{ChirpyChalet:()=>S,WingtipVilla:()=>y});var E={};i.r(E),i.d(E,{BirdHouses:()=>C});var A={};i.r(A),i.d(A,{SnakeChairData:()=>tH,SnakeChairDrawDto:()=>oH,SnakeChairDrawingPart:()=>iH,SnakeChairDrawingPartShapes:()=>sH,SnakeChairDto:()=>eH,SnakeChairDtoBase:()=>JW,SnakeChairMainPart:()=>rH,SnakeChairModelDto:()=>nH});var P={};i.r(P),i.d(P,{SnakeChair:()=>A});var I={};i.r(I),i.d(I,{ElegantTableData:()=>hH,ElegantTableDrawDto:()=>mH,ElegantTableDrawingPart:()=>cH,ElegantTableDrawingPartShapes:()=>uH,ElegantTableDto:()=>lH,ElegantTableDtoBase:()=>aH,ElegantTableLegByIndexDto:()=>pH,ElegantTableLegPart:()=>dH,ElegantTableModelDto:()=>fH,ElegantTableTopPart:()=>_H});var R={};i.r(R),i.d(R,{GoodCoffeeTableData:()=>xH,GoodCoffeeTableDrawDto:()=>PH,GoodCoffeeTableDrawingPart:()=>bH,GoodCoffeeTableDrawingPartShapes:()=>TH,GoodCoffeeTableDto:()=>vH,GoodCoffeeTableDtoBase:()=>gH,GoodCoffeeTableLegByIndexDto:()=>EH,GoodCoffeeTableLegPart:()=>yH,GoodCoffeeTableModelDto:()=>AH,GoodCoffeeTableShelfPart:()=>SH,GoodCoffeeTableTopPart:()=>CH});var M={};i.r(M),i.d(M,{SnakeTableData:()=>MH,SnakeTableDrawDto:()=>FH,SnakeTableDrawingPart:()=>OH,SnakeTableDrawingPartShapes:()=>DH,SnakeTableDto:()=>RH,SnakeTableDtoBase:()=>IH,SnakeTableMainPart:()=>wH,SnakeTableModelDto:()=>NH});var O={};i.r(O),i.d(O,{ElegantTable:()=>I,GoodCoffeeTable:()=>R,SnakeTable:()=>M});var D={};i.r(D),i.d(D,{Chairs:()=>P,Tables:()=>O});var w={};i.r(w),i.d(w,{Architecture:()=>T,Enums:()=>r,Furniture:()=>D,KidsCorner:()=>E,Shared:()=>n,ThreeDPrinting:()=>v});var N={};i.r(N),i.d(N,{FontDefinition:()=>GH,Text3DData:()=>VH,Text3DDto:()=>BH,Text3DFaceDefinitionDto:()=>WH,Text3DFaceDto:()=>kH,Text3DLetterByIndexDto:()=>UH,Text3DModelDto:()=>zH,Texts3DFaceDto:()=>HH,faceTextVarEnum:()=>Uz,faceTypeEnum:()=>Gz,fontVariantsEnum:()=>Vz,fontsEnum:()=>kz,fontsModel:()=>LH,recAlignmentEnum:()=>zz});var F={};i.r(F),i.d(F,{PyramidSimpeByIndexDto:()=>jH,PyramidSimpleAffectorsDto:()=>YH,PyramidSimpleCellPart:()=>sX,PyramidSimpleData:()=>QH,PyramidSimpleDto:()=>XH,PyramidSimpleFacePart:()=>rX,PyramidSimpleModelCellDto:()=>ZH,PyramidSimpleModelCellsDto:()=>$H,PyramidSimpleModelCellsIndexDto:()=>qH,PyramidSimpleModelDto:()=>KH,PyramidSimpleModelFaceCellIndexDto:()=>eX,PyramidSimpleModelFaceCellsUIndexDto:()=>tX,PyramidSimpleModelFaceCellsVIndexDto:()=>iX,PyramidSimpleModelFaceIndexDto:()=>JH});var L={};i.r(L),i.d(L,{PyramidSimple:()=>F});var B={};i.r(B),i.d(B,{FacePatterns:()=>L});var k={};i.r(k),i.d(k,{outputShapeEnum:()=>nX});var V={};i.r(V),i.d(V,{Enums:()=>k,Patterns:()=>B,Text3D:()=>N});var U={};i.r(U),i.d(U,{Asset:()=>rU,BabylonCamera:()=>nU,BabylonGaussianSplatting:()=>lU,BabylonIO:()=>oU,BabylonMaterial:()=>aU,BabylonMesh:()=>hU,BabylonMeshBuilder:()=>dU,BabylonNode:()=>SU,BabylonPick:()=>cU,BabylonRay:()=>uU,BabylonScene:()=>PU,BabylonTexture:()=>_U,BabylonWebXR:()=>pU,Base:()=>AU,Color:()=>fU,Draw:()=>mU,JSCAD:()=>gU,JSON:()=>vU,Line:()=>xU,Lists:()=>bU,Logic:()=>TU,Math:()=>yU,OCCT:()=>Jk,Point:()=>CU,Polyline:()=>EU,Tag:()=>IU,Text:()=>RU,Time:()=>MU,Transforms:()=>OU,Vector:()=>DU,Verb:()=>wU});const G={};function z(e,t){G[e]=t}function W(e){return G[e]}function H(e){for(const t in G)if(e instanceof G[t]&&!t.includes("Abstract"))return t;return"Unknown"}class X{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,s){for(const r in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,r)&&this._BabylonFileParsers[r](e,t,i,s)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach((t=>e=e.concat(t.bones))),e}}X._BabylonFileParsers={},X._IndividualBabylonFileParsers={},z("BABYLON.AbstractScene",X);class Y{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(const e in Y.Triggers)if(Object.prototype.hasOwnProperty.call(Y.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in Y.Triggers)if(Object.prototype.hasOwnProperty.call(Y.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in Y.Triggers)if(Object.prototype.hasOwnProperty.call(Y.Triggers,t)&&parseInt(t)===e)return!0;return!1}}Y.Triggers={};class Q{constructor(e,t=!1,i,s){this.initialize(e,t,i,s)}initialize(e,t=!1,i,s){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=s,this}}class j{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class K{static FromPromise(e,t){const i=new K;return e.then((e=>{i.notifyObservers(e)})).catch((e=>{if(!t)throw e;t.notifyObservers(e)})),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new Q(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,r=!1){if(!e)return null;const n=new j(e,t,s);return n.unregisterOnNextCall=r,i?this._observers.unshift(n):this._observers.push(n),this._onObserverAdded&&this._onObserverAdded(n),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(n,this._lastNotifiedValue),n._remove=()=>{this.remove(n)},n}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return!!e&&(e._remove=null,-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))}removeCallback(e,t){for(let i=0;i{this._remove(e)}),0))}_remove(e,t=!0){if(!e)return!1;const i=this._observers.indexOf(e);return-1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,s,r){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const n=this._eventState;n.mask=t,n.target=i,n.currentTarget=s,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=r;for(const i of this._observers)if(!i._willBeUnregistered&&(i.mask&t&&(i.unregisterOnNextCall&&this._deferUnregister(i),i.scope?n.lastReturnValue=i.callback.apply(i.scope,[e,n]):n.lastReturnValue=i.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const s=this._eventState;s.mask=i,s.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,s)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new K;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}const $=1/2.2,q=2.2,Z=(1+Math.sqrt(5))/2,J=.001;class ee{static BuildArray(e,t){const i=[];for(let s=0;sfunction(e,t,i){const s=e[t];if("function"!=typeof s)return null;const r=function(){const s=e.length,n=r.previous.apply(e,arguments);return i(t,s),n};return s.next=r,r.previous=s,e[t]=r,()=>{const i=r.previous;if(!i)return;const s=r.next;s?(i.next=s,s.previous=i):(i.next=void 0,e[t]=i),r.next=void 0,r.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{e?.()}))}}class se{static SetMatrixPrecision(e){if(se.MatrixTrackPrecisionChange=!1,e&&!se.MatrixUse64Bits&&se.MatrixTrackedMatrices)for(let e=0;eparseInt(e.toString().replace(/\W/g,""));class de{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=ue(this.x);return e=397*e^ue(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return de.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new de(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new de(this.x+e.x,this.y+e.y)}subtract(e){return new de(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new de(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new de(this.x*e,this.y*t)}divide(e){return new de(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new de(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.x=this.x-e,i.y=this.y-t,i}negate(){return new de(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new de(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=J){return e&&ne(this.x,e.x,t)&&ne(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new de(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new de(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotateToRef(e,t){const i=Math.cos(e),s=Math.sin(e),r=i*this.x-s*this.y,n=s*this.x+i*this.y;return t.x=r,t.y=n,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new de;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new de(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new de(0,0)}static One(){return new de(1,1)}static Random(e=0,t=1){return new de(oe(e,t),oe(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(oe(e,t),oe(e,t))}static get ZeroReadOnly(){return de._ZeroReadOnly}static FromArray(e,t=0){return new de(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,a=.5*(2*t.x+(-e.x+i.x)*r+(2*e.x-5*t.x+4*i.x-s.x)*n+(-e.x+3*t.x-3*i.x+s.x)*o),l=.5*(2*t.y+(-e.y+i.y)*r+(2*e.y-5*t.y+4*i.y-s.y)*n+(-e.y+3*t.y-3*i.y+s.y)*o);return new de(a,l)}static ClampToRef(e,t,i,s){return s.x=le(e.x,t.x,i.x),s.y=le(e.y,t.y,i.y),s}static Clamp(e,t,i){const s=le(e.x,t.x,i.x),r=le(e.y,t.y,i.y);return new de(s,r)}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.x*a+i.x*l+t.x*h+s.x*c,d=e.y*a+i.y*l+t.y*h+s.y*c;return new de(u,d)}static Hermite1stDerivative(e,t,i,s,r){return this.Hermite1stDerivativeToRef(e,t,i,s,r,new de)}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n.x=6*(o-r)*e.x+(3*o-4*r+1)*t.x+6*(-o+r)*i.x+(3*o-2*r)*s.x,n.y=6*(o-r)*e.y+(3*o-4*r+1)*t.y+6*(-o+r)*i.y+(3*o-2*r)*s.y,n}static Lerp(e,t,i){const s=e.x+(t.x-e.x)*i,r=e.y+(t.y-e.y)*i;return new de(s,r)}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return de.NormalizeToRef(e,new de)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.xt.x?e.x:t.x,s=e.y>t.y?e.y:t.y;return new de(i,s)}static Transform(e,t){return de.TransformToRef(e,t,new de)}static TransformToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+s[12],n=e.x*s[1]+e.y*s[5]+s[13];return i.x=r,i.y=n,i}static PointInTriangle(e,t,i,s){const r=.5*(-i.y*s.x+t.y*(-i.x+s.x)+t.x*(i.y-s.y)+i.x*s.y),n=r<0?-1:1,o=(t.y*s.x-t.x*s.y+(s.y-t.y)*e.x+(t.x-s.x)*e.y)*n,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*n;return o>0&&a>0&&o+a<2*r*n}static Distance(e,t){return Math.sqrt(de.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y;return i*i+s*s}static Center(e,t){return de.CenterToRef(e,t,new de)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const s=de.DistanceSquared(t,i);if(0===s)return de.Distance(e,t);const r=i.subtract(t),n=Math.max(0,Math.min(1,de.Dot(e.subtract(t),r)/s)),o=t.add(r.multiplyByFloats(n,n));return de.Distance(e,o)}}de._ZeroReadOnly=de.Zero(),Object.defineProperties(de.prototype,{dimension:{value:[2]},rank:{value:1}});class _e{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=ue(this._x);return e=397*e^ue(this._y),e=397*e^ue(this._z),e}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return _e.FromArrayToRef(e,t,this),this}toQuaternion(){return fe.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new _e(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new _e(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new _e(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new _e(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new _e(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const s=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const r=t*Math.sin(i)*Math.cos(s),n=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(s);return e.set(r,n,o),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,r=this._z,n=e._x,o=e._y,a=e._z,l=e._w,h=2*(o*r-a*s),c=2*(a*i-n*r),u=2*(n*s-o*i);return t._x=i+l*h+o*u-a*c,t._y=s+l*c+a*h-n*u,t._z=r+l*u+n*c-o*h,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new _e)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new _e)}projectOnPlaneToRef(e,t,i){const s=e.normal,r=e.d,n=ge.Vector3[0];this.subtractToRef(t,n),n.normalize();const o=_e.Dot(n,s);if(Math.abs(o)<1e-10)i.setAll(1/0);else{const e=-(_e.Dot(t,s)+r)/o,a=n.scaleInPlace(e);t.addToRef(a,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=J){return e&&ne(this._x,e._x,t)&&ne(this._y,e._y,t)&&ne(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new _e(this._x*e,this._y*t,this._z*i)}divide(e){return new _e(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!ne(t,i,e))return!0;const s=Math.abs(this._z);return!ne(t,s,e)||!ne(i,s,e)}get isNonUniform(){const e=Math.abs(this._x);return e!==Math.abs(this._y)||e!==Math.abs(this._z)}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new _e(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))}fractToRef(e){return e._x=this.x-Math.floor(this._x),e._y=this.y-Math.floor(this._y),e._z=this.z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new _e(this.x-Math.floor(this._x),this.y-Math.floor(this._y),this.z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z==0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if("xyz"===(e=e.toLowerCase()))return this;const t=ge.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(ge.Matrix[0]),_e.TransformCoordinatesToRef(this,ge.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,ge.Vector3[0]),ge.Vector3[0].rotateByQuaternionToRef(e,ge.Vector3[0]),t.addToRef(ge.Vector3[0],i),i}cross(e){return _e.CrossToRef(this,e,new _e)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new _e)}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new _e(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,s){const r=_e.Dot(e,i);return(r-s)/(r-_e.Dot(t,i))}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(ge.Vector3[1]),r=t.normalizeToRef(ge.Vector3[2]);let n=_e.Dot(s,r);n=le(n,-1,1);const o=Math.acos(n),a=ge.Vector3[3];return _e.CrossToRef(s,r,a),_e.Dot(a,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){ge.Vector3[0].copyFrom(e);const s=ge.Vector3[0];ge.Vector3[1].copyFrom(t);const r=ge.Vector3[1];ge.Vector3[2].copyFrom(i);const n=ge.Vector3[2],o=ge.Vector3[3],a=ge.Vector3[4];return s.normalize(),r.normalize(),n.normalize(),_e.CrossToRef(n,s,o),_e.CrossToRef(o,n,a),he(Math.atan2(_e.Dot(r,o),_e.Dot(r,a)))}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=ve.Vector3[0];return t.subtractToRef(e,s),i._y=Math.atan2(s.x,s.z)||0,i._x=Math.atan2(Math.sqrt(s.x**2+s.z**2),s.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=_e.Zero();return _e.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=le(i,0,1);const r=ge.Vector3[0],n=ge.Vector3[1];r.copyFrom(e);const o=r.length();r.normalizeFromLength(o),n.copyFrom(t);const a=n.length();n.normalizeFromLength(a);const l=_e.Dot(r,n);let h,c;if(l<1-J){const e=Math.acos(l),t=1/Math.sin(e);h=Math.sin((1-i)*e)*t,c=Math.sin(i*e)*t}else h=1-i,c=i;return r.scaleInPlace(h),n.scaleInPlace(c),s.copyFrom(r).addInPlace(n),s.scaleInPlace(ae(o,a,i)),s}static SmoothToRef(e,t,i,s,r){return _e.SlerpToRef(e,t,0===s?1:i/s,r),r}static FromArray(e,t=0){return new _e(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return _e.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return _e.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new _e(0,0,0)}static One(){return new _e(1,1,1)}static Up(){return new _e(0,1,0)}static get UpReadOnly(){return _e._UpReadOnly}static get DownReadOnly(){return _e._DownReadOnly}static get RightReadOnly(){return _e._RightReadOnly}static get LeftReadOnly(){return _e._LeftReadOnly}static get LeftHandedForwardReadOnly(){return _e._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return _e._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return _e._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return _e._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return _e._ZeroReadOnly}static get OneReadOnly(){return _e._OneReadOnly}static Down(){return new _e(0,-1,0)}static Forward(e=!1){return new _e(0,0,e?-1:1)}static Backward(e=!1){return new _e(0,0,e?1:-1)}static Right(){return new _e(1,0,0)}static Left(){return new _e(-1,0,0)}static Random(e=0,t=1){return new _e(oe(e,t),oe(e,t),oe(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(oe(e,t),oe(e,t),oe(e,t))}static TransformCoordinates(e,t){const i=_e.Zero();return _e.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return _e.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=1/(e*n[3]+t*n[7]+i*n[11]+n[15]);return r._x=o*h,r._y=a*h,r._z=l*h,r._isDirty=!0,r}static TransformNormal(e,t){const i=_e.Zero();return _e.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,s,r){const n=s.m;return r._x=e*n[0]+t*n[4]+i*n[8],r._y=e*n[1]+t*n[5]+i*n[9],r._z=e*n[2]+t*n[6]+i*n[10],r._isDirty=!0,r}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,a=.5*(2*t._x+(-e._x+i._x)*r+(2*e._x-5*t._x+4*i._x-s._x)*n+(-e._x+3*t._x-3*i._x+s._x)*o),l=.5*(2*t._y+(-e._y+i._y)*r+(2*e._y-5*t._y+4*i._y-s._y)*n+(-e._y+3*t._y-3*i._y+s._y)*o),h=.5*(2*t._z+(-e._z+i._z)*r+(2*e._z-5*t._z+4*i._z-s._z)*n+(-e._z+3*t._z-3*i._z+s._z)*o);return new _e(a,l,h)}static Clamp(e,t,i){const s=new _e;return _e.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let r=e._x;r=r>i._x?i._x:r,r=ri._y?i._y:n,n=ni._z?i._z:o,o=o0&&E<0?(P.copyFrom(n),I=t,R=i):E>0&&A<0?(P.copyFrom(a),I=i,R=s):(P.copyFrom(o).scaleInPlace(-1),I=s,R=t);const M=ge.Vector3[9],O=ge.Vector3[4];if(I.subtractToRef(g,T),R.subtractToRef(g,M),_e.CrossToRef(T,M,O),!(_e.Dot(O,l)<0))return r.copyFrom(g),Math.abs(p*f);const D=ge.Vector3[5];_e.CrossToRef(P,O,D),D.normalize();const w=ge.Vector3[9];w.copyFrom(I).subtractInPlace(g);const N=w.length();if(Nthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,s){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(s,this.w),this}maximizeInPlaceFromFloats(e,t,i,s){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(s,this.w),this}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e}floor(){return new pe(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e.z=this.z-Math.floor(this.z),e.w=this.w-Math.floor(this.w),e}fract(){return new pe(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new pe)}normalizeToRef(e){const t=this.length();return 0===t||1===t?(e.x=this.x,e.y=this.y,e.z=this.z,e.w=this.w,e):this.scaleToRef(1/t,e)}toVector3(){return new _e(this.x,this.y,this.z)}clone(){return new pe(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}static FromArray(e,t){return t||(t=0),new pe(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return pe.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,s,r){return r.x=e,r.y=t,r.z=i,r.w=s,r}static Zero(){return new pe(0,0,0,0)}static One(){return new pe(1,1,1,1)}static Random(e=0,t=1){return new pe(oe(e,t),oe(e,t),oe(e,t),oe(e,t))}static RandomToRef(e=0,t=1,i){return i.x=oe(e,t),i.y=oe(e,t),i.z=oe(e,t),i.w=oe(e,t),i}static Clamp(e,t,i){return pe.ClampToRef(e,t,i,new pe)}static ClampToRef(e,t,i,s){return s.x=le(e.x,t.x,i.x),s.y=le(e.y,t.y,i.y),s.z=le(e.z,t.z,i.z),s.w=le(e.w,t.w,i.w),s}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return pe._ZeroReadOnly}static Normalize(e){return pe.NormalizeToRef(e,new pe)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new pe;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new pe;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(pe.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return pe.CenterToRef(e,t,new pe)}static CenterToRef(e,t,i){return i.x=(e.x+t.x)/2,i.y=(e.y+t.y)/2,i.z=(e.z+t.z)/2,i.w=(e.w+t.w)/2,i}static TransformCoordinates(e,t){return pe.TransformCoordinatesToRef(e,t,new pe)}static TransformCoordinatesToRef(e,t,i){return pe.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=e*n[3]+t*n[7]+i*n[11]+n[15];return r.x=o,r.y=a,r.z=l,r.w=h,r}static TransformNormal(e,t){return pe.TransformNormalToRef(e,t,new pe)}static TransformNormalToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+e.z*s[8],n=e.x*s[1]+e.y*s[5]+e.z*s[9],o=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=r,i.y=n,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,r,n){const o=r.m;return n.x=e*o[0]+t*o[4]+i*o[8],n.y=e*o[1]+t*o[5]+i*o[9],n.z=e*o[2]+t*o[6]+i*o[10],n.w=s,n}static FromVector3(e,t=0){return new pe(e._x,e._y,e._z,t)}static Dot(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w}}pe._ZeroReadOnly=pe.Zero(),Object.defineProperties(pe.prototype,{dimension:{value:[4]},rank:{value:1}});class fe{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,s=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=ue(this._x);return e=397*e^ue(this._y),e=397*e^ue(this._z),e=397*e^ue(this._w),e}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return fe.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=J){return e&&ne(this._x,e._x,t)&&ne(this._y,e._y,t)&&ne(this._z,e._z,t)&&ne(this._w,e._w,t)}clone(){return new fe(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._isDirty=!0,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new fe(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,s){return this._x+=e,this._y+=t,this._z+=i,this._w+=s,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,s){return this.subtractFromFloatsToRef(e,t,i,s,new fe)}subtractFromFloatsToRef(e,t,i,s,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._w=this._w-s,r._isDirty=!0,r}subtract(e){return new fe(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new fe(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){const t=new fe(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,s=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,n=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,s,r,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,s){return this._x*=e,this._y*=t,this._z*=i,this._w*=s,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new fe)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,s){return this._x===e&&this._y===t&&this._z===i&&this._w===s}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new fe(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return 0==e||1==e||this.scaleInPlace(1/e),this}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new fe(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=_e.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,s=this._y,r=this._w,n=s*t-i*r,o=.4999999;if(n<-o)e._y=2*Math.atan2(s,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>o)e._y=2*Math.atan2(s,r),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const o=r*r,a=t*t,l=i*i,h=s*s;e._z=Math.atan2(2*(i*s+t*r),-a-l+h+o),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*i+s*r),a-l-h+o),e._isDirty=!0}return e}toRotationMatrix(e){return me.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return fe.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}static FromRotationMatrix(e){const t=new fe;return fe.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[1],a=i[5],l=i[9],h=i[2],c=i[6],u=i[10],d=s+a+u;let _;return d>0?(_=.5/Math.sqrt(d+1),t._w=.25/_,t._x=(c-l)*_,t._y=(n-h)*_,t._z=(o-r)*_,t._isDirty=!0):s>a&&s>u?(_=2*Math.sqrt(1+s-a-u),t._w=(c-l)/_,t._x=.25*_,t._y=(r+o)/_,t._z=(n+h)/_,t._isDirty=!0):a>u?(_=2*Math.sqrt(1+a-s-u),t._w=(n-h)/_,t._x=(r+o)/_,t._y=.25*_,t._z=(l+c)/_,t._isDirty=!0):(_=2*Math.sqrt(1+u-s-a),t._w=(o-r)/_,t._x=(n+h)/_,t._y=(l+c)/_,t._z=.25*_,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const s=fe.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,r){let n=0===s?1:i/s;return n=le(n,0,1),fe.SlerpToRef(e,t,n,r),r}static Zero(){return new fe(0,0,0,0)}static Inverse(e){return new fe(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new fe(0,0,0,1)}static IsIdentity(e){return e&&0===e._x&&0===e._y&&0===e._z&&1===e._w}static RotationAxis(e,t){return fe.RotationAxisToRef(e,t,new fe)}static RotationAxisToRef(e,t,i){const s=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*s,i._y=e._y*s,i._z=e._z*s,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new fe(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,s,r){return r.copyFromFloats(e,t,i,s),r}static FromEulerAngles(e,t,i){const s=new fe;return fe.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return fe.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new fe;return fe.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return fe.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=J){const r=_e.Dot(e,t)+1;return rMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(_e.CrossToRef(e,t,ve.Vector3[0]),i.set(ve.Vector3[0].x,ve.Vector3[0].y,ve.Vector3[0].z,r)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new fe;return fe.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const r=.5*i,n=.5*t,o=.5*e,a=Math.sin(r),l=Math.cos(r),h=Math.sin(n),c=Math.cos(n),u=Math.sin(o),d=Math.cos(o);return s._x=d*h*l+u*c*a,s._y=u*c*l-d*h*a,s._z=d*c*a-u*h*l,s._w=d*c*l+u*h*a,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new fe;return fe.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const r=.5*(i+e),n=.5*(i-e),o=.5*t;return s._x=Math.cos(n)*Math.sin(o),s._y=Math.sin(n)*Math.sin(o),s._z=Math.sin(r)*Math.cos(o),s._w=Math.cos(r)*Math.cos(o),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new fe(0,0,0,0);return fe.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const r=ge.Matrix[0];return me.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),r),fe.FromRotationMatrixToRef(r,s),s}static FromLookDirectionLH(e,t){const i=new fe;return fe.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=ge.Matrix[0];return me.LookDirectionLHToRef(e,t,s),fe.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new fe;return fe.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=ge.Matrix[0];return me.LookDirectionRHToRef(e,t,s),fe.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=fe.Identity();return fe.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let r,n,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,a=!1;if(o<0&&(a=!0,o=-o),o>.999999)n=1-i,r=a?-i:i;else{const e=Math.acos(o),t=1/Math.sin(e);n=Math.sin((1-i)*e)*t,r=a?-Math.sin(i*e)*t:Math.sin(i*e)*t}return s._x=n*e._x+r*t._x,s._y=n*e._y+r*t._y,s._z=n*e._z+r*t._z,s._w=n*e._w+r*t._w,s._isDirty=!0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e._x*a+i._x*l+t._x*h+s._x*c,d=e._y*a+i._y*l+t._y*h+s._y*c,_=e._z*a+i._z*l+t._z*h+s._z*c,p=e._w*a+i._w*l+t._w*h+s._w*c;return new fe(u,d,_,p)}static Hermite1stDerivative(e,t,i,s,r){const n=new fe;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n._x=6*(o-r)*e._x+(3*o-4*r+1)*t._x+6*(-o+r)*i._x+(3*o-2*r)*s._x,n._y=6*(o-r)*e._y+(3*o-4*r+1)*t._y+6*(-o+r)*i._y+(3*o-2*r)*s._y,n._z=6*(o-r)*e._z+(3*o-4*r+1)*t._z+6*(-o+r)*i._z+(3*o-2*r)*s._z,n._w=6*(o-r)*e._w+(3*o-4*r+1)*t._w+6*(-o+r)*i._w+(3*o-2*r)*s._w,n._isDirty=!0,n}static Normalize(e){const t=fe.Zero();return fe.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const s=new fe;return fe.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(le(e.x,t.x,i.x),le(e.y,t.y,i.y),le(e.z,t.z,i.z),le(e.w,t.w,i.w))}static Random(e=0,t=1){return new fe(oe(e,t),oe(e,t),oe(e,t),oe(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(oe(e,t),oe(e,t),oe(e,t),oe(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(fe.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return fe.CenterToRef(e,t,fe.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}Object.defineProperties(fe.prototype,{dimension:{value:[4]},rank:{value:1}});class me{static get Use64Bits(){return se.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=me._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,s=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&s}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,se.MatrixTrackPrecisionChange&&se.MatrixTrackedMatrices.push(this),this._m=new se.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]||0!==this._m[1]||0!==this._m[2]||0!==this._m[3]||0!==this._m[4]||0!==this._m[6]||0!==this._m[7]||0!==this._m[8]||0!==this._m[9]||0!==this._m[10]||0!==this._m[11]||0!==this._m[12]||0!==this._m[13]||0!==this._m[14]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;const e=this._m,t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],o=e[5],a=e[6],l=e[7],h=e[8],c=e[9],u=e[10],d=e[11],_=e[12],p=e[13],f=e[14],m=e[15],g=u*m-f*d,v=c*m-p*d,x=c*f-p*u,b=h*m-_*d,T=h*f-u*_,y=h*p-_*c;return t*+(o*g-a*v+l*x)+i*-(n*g-a*b+l*T)+s*+(n*v-o*b+l*y)+r*-(n*x-o*T+a*y)}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}\n${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}\n${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}\n${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let s=0;s<16;s++)e[t+s]=i[s];return this}asArray(){return this._m}fromArray(e,t=0){return me.FromArrayToRef(e,t,this)}copyFromFloats(...e){return me.FromArrayToRef(e,0,this)}set(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){const t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return me.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){const t=new me;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,s=t._m,r=e.m;for(let e=0;e<16;e++)s[e]=i[e]+r[e];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]-s[e];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new me)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let e=0;e<16;e++)s[e]=i[e]-r[e];return t.markAsUpdated(),t}invertToRef(e){if(!0===this._isIdentity)return me.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],r=t[2],n=t[3],o=t[4],a=t[5],l=t[6],h=t[7],c=t[8],u=t[9],d=t[10],_=t[11],p=t[12],f=t[13],m=t[14],g=t[15],v=d*g-m*_,x=u*g-f*_,b=u*m-f*d,T=c*g-p*_,y=c*m-d*p,S=c*f-p*u,C=+(a*v-l*x+h*b),E=-(o*v-l*T+h*y),A=+(o*x-a*T+h*S),P=-(o*b-a*y+l*S),I=i*C+s*E+r*A+n*P;if(0===I)return e.copyFrom(this),e;const R=1/I,M=l*g-m*h,O=a*g-f*h,D=a*m-f*l,w=o*g-p*h,N=o*m-p*l,F=o*f-p*a,L=l*_-d*h,B=a*_-u*h,k=a*d-u*l,V=o*_-c*h,U=o*d-c*l,G=o*u-c*a,z=-(s*v-r*x+n*b),W=+(i*v-r*T+n*y),H=-(i*x-s*T+n*S),X=+(i*b-s*y+r*S),Y=+(s*M-r*O+n*D),Q=-(i*M-r*w+n*N),j=+(i*O-s*w+n*F),K=-(i*D-s*N+r*F),$=-(s*L-r*B+n*k),q=+(i*L-r*V+n*U),Z=-(i*B-s*V+n*G),J=+(i*k-s*U+r*G);return me.FromValuesToRef(C*R,z*R,Y*R,$*R,E*R,W*R,Q*R,q*R,A*R,H*R,j*R,Z*R,P*R,X*R,K*R,J*R,e),e}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new _e(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){const e=this.m;return me.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]),this}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){const i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiply(e){const t=new me;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]*=i[e];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let e=0;e<16;e++)s[e]=i[e]*r[e];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const s=this._m,r=e.m,n=s[0],o=s[1],a=s[2],l=s[3],h=s[4],c=s[5],u=s[6],d=s[7],_=s[8],p=s[9],f=s[10],m=s[11],g=s[12],v=s[13],x=s[14],b=s[15],T=r[0],y=r[1],S=r[2],C=r[3],E=r[4],A=r[5],P=r[6],I=r[7],R=r[8],M=r[9],O=r[10],D=r[11],w=r[12],N=r[13],F=r[14],L=r[15];return t[i]=n*T+o*E+a*R+l*w,t[i+1]=n*y+o*A+a*M+l*N,t[i+2]=n*S+o*P+a*O+l*F,t[i+3]=n*C+o*I+a*D+l*L,t[i+4]=h*T+c*E+u*R+d*w,t[i+5]=h*y+c*A+u*M+d*N,t[i+6]=h*S+c*P+u*O+d*F,t[i+7]=h*C+c*I+u*D+d*L,t[i+8]=_*T+p*E+f*R+m*w,t[i+9]=_*y+p*A+f*M+m*N,t[i+10]=_*S+p*P+f*O+m*F,t[i+11]=_*C+p*I+f*D+m*L,t[i+12]=g*T+v*E+x*R+b*w,t[i+13]=g*y+v*A+x*M+b*N,t[i+14]=g*S+v*P+x*O+b*F,t[i+15]=g*C+v*I+x*D+b*L,this}divide(e){return this.divideToRef(e,new me)}divideToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]/s[e];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]/=i[e];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new me)}negateInPlace(){const e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=-t[e];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,s=t.m;return i[0]===s[0]&&i[1]===s[1]&&i[2]===s[2]&&i[3]===s[3]&&i[4]===s[4]&&i[5]===s[5]&&i[6]===s[6]&&i[7]===s[7]&&i[8]===s[8]&&i[9]===s[9]&&i[10]===s[10]&&i[11]===s[11]&&i[12]===s[12]&&i[13]===s[13]&&i[14]===s[14]&&i[15]===s[15]}equalsWithEpsilon(e,t=0){const i=this._m,s=e.m;for(let e=0;e<16;e++)if(!ne(i[e],s[e],t))return!1;return!0}equalsToFloats(...e){const t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new me)}floorToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=Math.floor(t[e]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new me)}fractToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=t[e]-Math.floor(t[e]);return e.markAsUpdated(),e}clone(){const e=new me;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=ue(this._m[0]);for(let t=1;t<16;t++)e=397*e^ue(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new fe,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,s,r=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const n=this._m;if(i&&i.copyFromFloats(n[12],n[13],n[14]),(e=e||ge.Vector3[0]).x=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),e.y=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),e.z=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]),s){const t=(r?s.absoluteScaling.x:s.scaling.x)<0?-1:1,i=(r?s.absoluteScaling.y:s.scaling.y)<0?-1:1,n=(r?s.absoluteScaling.z:s.scaling.z)<0?-1:1;e.x*=t,e.y*=i,e.z*=n}else this.determinant()<=0&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const i=1/e._x,s=1/e._y,r=1/e._z;me.FromValuesToRef(n[0]*i,n[1]*i,n[2]*i,0,n[4]*s,n[5]*s,n[6]*s,0,n[8]*r,n[9]*r,n[10]*r,0,0,0,0,1,ge.Matrix[0]),fe.FromRotationMatrixToRef(ge.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new pe(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){const i=4*e;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){const e=new me;return me.TransposeToRef(this,e),e}transposeToRef(e){return me.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,s,r){if(e<0||e>3)return this;const n=4*e;return this._m[n+0]=t,this._m[n+1]=i,this._m[n+2]=s,this._m[n+3]=r,this.markAsUpdated(),this}scale(e){const t=new me;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){const t=ge.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return me.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){const e=new me;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=ge.Vector3[0];if(!this.decompose(t))return me.IdentityToRef(e),e;const i=this._m,s=1/t._x,r=1/t._y,n=1/t._z;return me.FromValuesToRef(i[0]*s,i[1]*s,i[2]*s,0,i[4]*r,i[5]*r,i[6]*r,0,i[8]*n,i[9]*n,i[10]*n,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){const i=new me;return me.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let s=0;s<16;s++)i._m[s]=e[s+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,s){for(let r=0;r<16;r++)s._m[r]=e[r+t]*i;return s.markAsUpdated(),s}static get IdentityReadOnly(){return me._IdentityReadOnly}static FromValuesToRef(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m){const g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=s,g[4]=r,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=p,g[15]=f,m.markAsUpdated()}static FromValues(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f){const m=new me,g=m._m;return g[0]=e,g[1]=t,g[2]=i,g[3]=s,g[4]=r,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=p,g[15]=f,m.markAsUpdated(),m}static Compose(e,t,i){const s=new me;return me.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const r=s._m,n=t._x,o=t._y,a=t._z,l=t._w,h=n+n,c=o+o,u=a+a,d=n*h,_=n*c,p=n*u,f=o*c,m=o*u,g=a*u,v=l*h,x=l*c,b=l*u,T=e._x,y=e._y,S=e._z;return r[0]=(1-(f+g))*T,r[1]=(_+b)*T,r[2]=(p-x)*T,r[3]=0,r[4]=(_-b)*y,r[5]=(1-(d+g))*y,r[6]=(m+v)*y,r[7]=0,r[8]=(p+x)*S,r[9]=(m-v)*S,r[10]=(1-(d+f))*S,r[11]=0,r[12]=i._x,r[13]=i._y,r[14]=i._z,r[15]=1,s.markAsUpdated(),s}static Identity(){const e=me.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return me.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){const e=me.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){const t=new me;return me.RotationXToRef(e,t),t}static Invert(e){const t=new me;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return me.FromValuesToRef(1,0,0,0,0,s,i,0,0,-i,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationY(e){const t=new me;return me.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return me.FromValuesToRef(s,0,-i,0,0,1,0,0,i,0,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationZ(e){const t=new me;return me.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return me.FromValuesToRef(s,i,0,0,-i,s,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationAxis(e,t){const i=new me;return me.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),r=Math.cos(-t),n=1-r;e.normalize();const o=i._m;return o[0]=e._x*e._x*n+r,o[1]=e._x*e._y*n-e._z*s,o[2]=e._x*e._z*n+e._y*s,o[3]=0,o[4]=e._y*e._x*n+e._z*s,o[5]=e._y*e._y*n+r,o[6]=e._y*e._z*n-e._x*s,o[7]=0,o[8]=e._z*e._x*n-e._y*s,o[9]=e._z*e._y*n+e._x*s,o[10]=e._z*e._z*n+r,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const r=_e.Dot(t,e),n=i._m;if(r<-1+J)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=s?1:-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=s?-1:1,n[11]=0;else{const i=_e.Cross(t,e),s=1/(1+r);n[0]=i._x*i._x*s+r,n[1]=i._y*i._x*s-i._z,n[2]=i._z*i._x*s+i._y,n[3]=0,n[4]=i._x*i._y*s+i._z,n[5]=i._y*i._y*s+r,n[6]=i._z*i._y*s-i._x,n[7]=0,n[8]=i._x*i._z*s-i._y,n[9]=i._y*i._z*s+i._x,n[10]=i._z*i._z*s+r,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const s=new me;return me.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return fe.RotationYawPitchRollToRef(e,t,i,ge.Quaternion[0]),ge.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new me;return me.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return me.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,s),s._updateIdentityStatus(1===e&&1===t&&1===i),s}static Translation(e,t,i){const s=new me;return me.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return me.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,s),s._updateIdentityStatus(0===e&&0===t&&0===i),s}static Lerp(e,t,i){const s=new me;return me.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const r=s._m,n=e.m,o=t.m;for(let e=0;e<16;e++)r[e]=n[e]*(1-i)+o[e]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new me;return me.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const r=ge.Vector3[0],n=ge.Quaternion[0],o=ge.Vector3[1];e.decompose(r,n,o);const a=ge.Vector3[2],l=ge.Quaternion[1],h=ge.Vector3[3];t.decompose(a,l,h);const c=ge.Vector3[4];_e.LerpToRef(r,a,i,c);const u=ge.Quaternion[2];fe.SlerpToRef(n,l,i,u);const d=ge.Vector3[5];return _e.LerpToRef(o,h,i,d),me.ComposeToRef(c,u,d,s),s}static LookAtLH(e,t,i){const s=new me;return me.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const r=ge.Vector3[0],n=ge.Vector3[1],o=ge.Vector3[2];t.subtractToRef(e,o),o.normalize(),_e.CrossToRef(i,o,r);const a=r.lengthSquared();0===a?r.x=1:r.normalizeFromLength(Math.sqrt(a)),_e.CrossToRef(o,r,n),n.normalize();const l=-_e.Dot(r,e),h=-_e.Dot(n,e),c=-_e.Dot(o,e);return me.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,l,h,c,1,s),s}static LookAtRH(e,t,i){const s=new me;return me.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const r=ge.Vector3[0],n=ge.Vector3[1],o=ge.Vector3[2];e.subtractToRef(t,o),o.normalize(),_e.CrossToRef(i,o,r);const a=r.lengthSquared();0===a?r.x=1:r.normalizeFromLength(Math.sqrt(a)),_e.CrossToRef(o,r,n),n.normalize();const l=-_e.Dot(r,e),h=-_e.Dot(n,e),c=-_e.Dot(o,e);return me.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,l,h,c,1,s),s}static LookDirectionLH(e,t){const i=new me;return me.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=ge.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const r=ge.Vector3[1];return _e.CrossToRef(t,s,r),me.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new me;return me.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=ge.Vector3[2];return _e.CrossToRef(t,e,s),me.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,s,r){const n=new me;return me.OrthoLHToRef(e,t,i,s,n,r),n}static OrthoLHToRef(e,t,i,s,r,n){const o=2/e,a=2/t,l=2/(s-i),h=-(s+i)/(s-i);return me.FromValuesToRef(o,0,0,0,0,a,0,0,0,0,l,0,0,0,h,1,r),n&&r.multiplyToRef(xe,r),r._updateIdentityStatus(1===o&&1===a&&1===l&&0===h),r}static OrthoOffCenterLH(e,t,i,s,r,n,o){const a=new me;return me.OrthoOffCenterLHToRef(e,t,i,s,r,n,a,o),a}static OrthoOffCenterLHToRef(e,t,i,s,r,n,o,a){const l=2/(t-e),h=2/(s-i),c=2/(n-r),u=-(n+r)/(n-r),d=(e+t)/(e-t),_=(s+i)/(i-s);return me.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,0,d,_,u,1,o),a&&o.multiplyToRef(xe,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,s,r,n,o,a,l,h,c){const u=-o*Math.cos(a),d=-o*Math.sin(a);return me.TranslationToRef(0,0,-l,ge.Matrix[1]),me.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,ge.Matrix[0]),ge.Matrix[1].multiplyToRef(ge.Matrix[0],ge.Matrix[0]),me.TranslationToRef(0,0,l,ge.Matrix[1]),ge.Matrix[0].multiplyToRef(ge.Matrix[1],ge.Matrix[0]),me.OrthoOffCenterLHToRef(e,t,i,s,r,n,h,c),ge.Matrix[0].multiplyToRef(h,h),h}static OrthoOffCenterRH(e,t,i,s,r,n,o){const a=new me;return me.OrthoOffCenterRHToRef(e,t,i,s,r,n,a,o),a}static OrthoOffCenterRHToRef(e,t,i,s,r,n,o,a){return me.OrthoOffCenterLHToRef(e,t,i,s,r,n,o,a),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,s,r,n,o,a,l,h,c){const u=o*Math.cos(a),d=o*Math.sin(a);return me.TranslationToRef(0,0,l,ge.Matrix[1]),me.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,ge.Matrix[0]),ge.Matrix[1].multiplyToRef(ge.Matrix[0],ge.Matrix[0]),me.TranslationToRef(0,0,-l,ge.Matrix[1]),ge.Matrix[0].multiplyToRef(ge.Matrix[1],ge.Matrix[0]),me.OrthoOffCenterRHToRef(e,t,i,s,r,n,h,c),ge.Matrix[0].multiplyToRef(h,h),h}static PerspectiveLH(e,t,i,s,r,n=0){const o=new me,a=2*i/e,l=2*i/t,h=(s+i)/(s-i),c=-2*s*i/(s-i),u=Math.tan(n);return me.FromValuesToRef(a,0,0,0,0,l,0,u,0,0,h,1,0,0,c,0,o),r&&o.multiplyToRef(xe,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,s,r,n=0,o=!1){const a=new me;return me.PerspectiveFovLHToRef(e,t,i,s,a,!0,r,n,o),a}static PerspectiveFovLHToRef(e,t,i,s,r,n=!0,o,a=0,l=!1){const h=i,c=s,u=1/Math.tan(.5*e),d=n?u/t:u,_=n?u:u*t,p=l&&0===h?-1:0!==c?(c+h)/(c-h):1,f=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,m=Math.tan(a);return me.FromValuesToRef(d,0,0,0,0,_,0,m,0,0,p,1,0,0,f,0,r),o&&r.multiplyToRef(xe,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,s,r,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return me.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,1,0,0,1,0,r),o&&r.multiplyToRef(xe,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,s,r,n=0,o=!1){const a=new me;return me.PerspectiveFovRHToRef(e,t,i,s,a,!0,r,n,o),a}static PerspectiveFovRHToRef(e,t,i,s,r,n=!0,o,a=0,l=!1){const h=i,c=s,u=1/Math.tan(.5*e),d=n?u/t:u,_=n?u:u*t,p=l&&0===h?1:0!==c?-(c+h)/(c-h):-1,f=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,m=Math.tan(a);return me.FromValuesToRef(d,0,0,0,0,_,0,m,0,0,p,-1,0,0,f,0,r),o&&r.multiplyToRef(xe,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,s,r,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return me.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,-1,0,0,-1,0,r),o&&r.multiplyToRef(xe,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,i,s,r,n){const o=e.width,a=e.height,l=e.x,h=e.y,c=me.FromValues(o/2,0,0,0,0,-a/2,0,0,0,0,n-r,0,l+o/2,a/2+h,r,1),u=new me;return t.multiplyToRef(i,u),u.multiplyToRef(s,u),u.multiplyToRef(c,u)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return se.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){const t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return se.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new me;return me.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[12],a=i[1],l=i[5],h=i[9],c=i[13],u=i[2],d=i[6],_=i[10],p=i[14],f=i[3],m=i[7],g=i[11],v=i[15],x=t._m;return x[0]=s,x[1]=r,x[2]=n,x[3]=o,x[4]=a,x[5]=l,x[6]=h,x[7]=c,x[8]=u,x[9]=d,x[10]=_,x[11]=p,x[12]=f,x[13]=m,x[14]=g,x[15]=v,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new me;return me.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,s=e.normal.y,r=e.normal.z,n=-2*i,o=-2*s,a=-2*r;return me.FromValuesToRef(n*i+1,o*i,a*i,0,n*s,o*s+1,a*s,0,n*r,o*r,a*r+1,0,n*e.d,o*e.d,a*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return me.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,s),s}static FromQuaternionToRef(e,t){const i=e._x*e._x,s=e._y*e._y,r=e._z*e._z,n=e._x*e._y,o=e._z*e._w,a=e._z*e._x,l=e._y*e._w,h=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(s+r),t._m[1]=2*(n+o),t._m[2]=2*(a-l),t._m[3]=0,t._m[4]=2*(n-o),t._m[5]=1-2*(r+i),t._m[6]=2*(h+c),t._m[7]=0,t._m[8]=2*(a+l),t._m[9]=2*(h-c),t._m[10]=1-2*(s+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}me._UpdateFlagSeed=0,me._IdentityReadOnly=me.Identity(),Object.defineProperties(me.prototype,{dimension:{value:[4,4]},rank:{value:2}});class ge{}ge.Vector3=ee.BuildTuple(11,_e.Zero),ge.Matrix=ee.BuildTuple(2,me.Identity),ge.Quaternion=ee.BuildTuple(3,fe.Zero);class ve{}ve.Vector2=ee.BuildTuple(3,de.Zero),ve.Vector3=ee.BuildTuple(13,_e.Zero),ve.Vector4=ee.BuildTuple(3,pe.Zero),ve.Quaternion=ee.BuildTuple(2,fe.Zero),ve.Matrix=ee.BuildTuple(8,me.Identity),z("BABYLON.Vector2",de),z("BABYLON.Vector3",_e),z("BABYLON.Vector4",pe),z("BABYLON.Matrix",me);const xe=me.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class be{static Sign(e){return 0==(e=+e)||isNaN(e)?e:e>0?1:-1}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(0===e)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e*=2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=be.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=be.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=be.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return s=Math.abs(t-e)<=i?t:e+be.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=be.DeltaAngle(e,t);let r=0;return-i180&&(s-=360),e+s*le(i)}static InverseLerp(e,t,i){let s=0;return s=e!=t?le((i-e)/(t-e)):0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n;return e*(2*o-3*n+1)+i*(-2*o+3*n)+t*(o-2*n+r)+s*(o-n)}static Hermite1stDerivative(e,t,i,s,r){const n=r*r;return 6*(n-r)*e+(3*n-4*r+1)*t+6*(-n+r)*i+(3*n-2*r)*s}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static HCF(e,t){const i=e%t;return 0===i?t:be.HCF(t,i)}}function Te(e){return Math.pow(e,q)}function ye(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function Se(e){return Math.pow(e,$)}function Ce(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}be.TwoPi=2*Math.PI,be.WithinEpsilon=ne,be.ToHex=ce,be.Clamp=le,be.Lerp=ae,be.RandomRange=oe,be.NormalizeRadians=he;class Ee{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return Ee.FromArrayToRef(e,t,this),this}toColor4(e=1){return new Ae(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return.3*this.r+.59*this.g+.11*this.b}multiply(e){return new Ee(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,i){return new Ee(this.r*e,this.g*t,this.b*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=J){return be.WithinEpsilon(this.r,e.r,t)&&be.WithinEpsilon(this.g,e.g,t)&&be.WithinEpsilon(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new Ee(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,i){return i.r=le(this.r,e,t),i.g=le(this.g,e,t),i.b=le(this.b,e,t),i}add(e){return new Ee(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new Ee(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,i){return new Ee(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,s){return s.r=this.r-e,s.g=this.g-t,s.b=this.b-i,s}clone(){return new Ee(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){const e=Math.round(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+ce(e)+ce(t)+ce(i)}toHSV(){return this.toHSVToRef(new Ee)}toHSVToRef(e){const t=this.r,i=this.g,s=this.b,r=Math.max(t,i,s),n=Math.min(t,i,s);let o=0,a=0;const l=r,h=r-n;return 0!==r&&(a=h/r),r!=n&&(r==t?(o=(i-s)/h,i=0&&n<=1?(a=r,l=o):n>=1&&n<=2?(a=o,l=r):n>=2&&n<=3?(l=r,h=o):n>=3&&n<=4?(l=o,h=r):n>=4&&n<=5?(a=o,h=r):n>=5&&n<=6&&(a=r,h=o);const c=i-r;return s.r=a+c,s.g=l+c,s.b=h+c,s}static FromHSV(e,t,i){const s=new Ee(0,0,0);return Ee.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new Ee(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16);return Ee.FromInts(t,i,s)}static FromArray(e,t=0){return new Ee(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new Ee(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new Ee(0,0,0);return Ee.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.r*a+i.r*l+t.r*h+s.r*c,d=e.g*a+i.g*l+t.g*h+s.g*c,_=e.b*a+i.b*l+t.b*h+s.b*c;return new Ee(u,d,_)}static Hermite1stDerivative(e,t,i,s,r){const n=Ee.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=6*(o-r)*e.r+(3*o-4*r+1)*t.r+6*(-o+r)*i.r+(3*o-2*r)*s.r,n.g=6*(o-r)*e.g+(3*o-4*r+1)*t.g+6*(-o+r)*i.g+(3*o-2*r)*s.g,n.b=6*(o-r)*e.b+(3*o-4*r+1)*t.b+6*(-o+r)*i.b+(3*o-2*r)*s.b}static Red(){return new Ee(1,0,0)}static Green(){return new Ee(0,1,0)}static Blue(){return new Ee(0,0,1)}static Black(){return new Ee(0,0,0)}static get BlackReadOnly(){return Ee._BlackReadOnly}static White(){return new Ee(1,1,1)}static Purple(){return new Ee(.5,0,.5)}static Magenta(){return new Ee(1,0,1)}static Yellow(){return new Ee(1,1,0)}static Gray(){return new Ee(.5,.5,.5)}static Teal(){return new Ee(0,1,1)}static Random(){return new Ee(Math.random(),Math.random(),Math.random())}}Ee._BlackReadOnly=Ee.Black(),Object.defineProperties(Ee.prototype,{dimension:{value:[3]},rank:{value:1}});class Ae{constructor(e=0,t=0,i=0,s=1){this.r=e,this.g=t,this.b=i,this.a=s}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new Ae(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,s){return this.r+=e,this.g+=t,this.b+=i,this.a+=s,this}subtract(e){return new Ae(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,s){return new Ae(this.r-e,this.g-t,this.b-i,this.a-s)}subtractFromFloatsToRef(e,t,i,s,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r.a=this.a-s,r}scale(e){return new Ae(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,i){return i.r=le(this.r,e,t),i.g=le(this.g,e,t),i.b=le(this.b,e,t),i.a=le(this.a,e,t),i}multiply(e){return new Ae(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,s){return new Ae(this.r*e,this.g*t,this.b*i,this.a*s)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,s){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(s,this.a),this}maximizeInPlaceFromFloats(e,t,i,s){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(s,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=J){return be.WithinEpsilon(this.r,e.r,t)&&be.WithinEpsilon(this.g,e.g,t)&&be.WithinEpsilon(this.b,e.b,t)&&be.WithinEpsilon(this.a,e.a,t)}equalsToFloats(e,t,i,s){return this.r===e&&this.g===t&&this.b===i&&this.a===s}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e=397*e^255*this.a,e}clone(){return(new Ae).copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,s){return this.r=e,this.g=t,this.b=i,this.a=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+ce(t)+ce(i)+ce(s);const r=Math.round(255*this.a);return"#"+ce(t)+ce(i)+ce(s)+ce(r)}toLinearSpace(e=!1){const t=new Ae;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=ye(this.r),e.g=ye(this.g),e.b=ye(this.b)):(e.r=Te(this.r),e.g=Te(this.g),e.b=Te(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new Ae;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=Ce(this.r),e.g=Ce(this.g),e.b=Ce(this.b)):(e.r=Se(this.r),e.g=Se(this.g),e.b=Se(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new Ae(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16),r=9===e.length?parseInt(e.substring(7,9),16):255;return Ae.FromInts(t,i,s,r)}static Lerp(e,t,i){return Ae.LerpToRef(e,t,i,new Ae)}static LerpToRef(e,t,i,s){return s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i,s.a=e.a+(t.a-e.a)*i,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.r*a+i.r*l+t.r*h+s.r*c,d=e.g*a+i.g*l+t.g*h+s.g*c,_=e.b*a+i.b*l+t.b*h+s.b*c,p=e.a*a+i.a*l+t.a*h+s.a*c;return new Ae(u,d,_,p)}static Hermite1stDerivative(e,t,i,s,r){const n=new Ae;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=6*(o-r)*e.r+(3*o-4*r+1)*t.r+6*(-o+r)*i.r+(3*o-2*r)*s.r,n.g=6*(o-r)*e.g+(3*o-4*r+1)*t.g+6*(-o+r)*i.g+(3*o-2*r)*s.g,n.b=6*(o-r)*e.b+(3*o-4*r+1)*t.b+6*(-o+r)*i.b+(3*o-2*r)*s.b,n.a=6*(o-r)*e.a+(3*o-4*r+1)*t.a+6*(-o+r)*i.a+(3*o-2*r)*s.a}static FromColor3(e,t=1){return new Ae(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new Ae(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,s){return new Ae(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;inew Ae(0,0,0,0))),z("BABYLON.Color3",Ee),z("BABYLON.Color4",Ae);class Ie{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new K,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}_prepare(){}getTriggerParameter(){return this._triggerParameter}setTriggerParameter(e){this._triggerParameter=e}_evaluateConditionForCurrentFrame(){const e=this._condition;if(!e)return!0;const t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){this._evaluateConditionForCurrentFrame()&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())}execute(e){}skipToNextActiveAction(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this}then(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(e){return null}_serialize(e,t){const i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){const e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}}Ie._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof de?e.x+", "+e.y:e instanceof _e?e.x+", "+e.y+", "+e.z:e instanceof Ee?e.r+", "+e.g+", "+e.b:e instanceof Ae?e.r+", "+e.g+", "+e.b+", "+e.a:e,Ie._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),z("BABYLON.Action",Ie);class Re{constructor(e,t,i,s,r,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=s,this.sourceEvent=r,this.additionalData=n}static CreateNew(e,t,i){const s=e.getScene();return new Re(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new Re(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new Re(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new Re(e,t.x,t.y,null,i,s)}}class Me{constructor(e){this._actionManager=e}isValid(){return!0}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(){}_serialize(e){return{type:2,children:[],name:e.name,properties:e.properties}}}class Oe extends Me{static get IsEqual(){return Oe._IsEqual}static get IsDifferent(){return Oe._IsDifferent}static get IsGreater(){return Oe._IsGreater}static get IsLesser(){return Oe._IsLesser}constructor(e,t,i,s,r=Oe.IsEqual){super(e),this.propertyPath=i,this.value=s,this.operator=r,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case Oe.IsGreater:return this._effectiveTarget[this._property]>this.value;case Oe.IsLesser:return this._effectiveTarget[this._property]e<10?"0"+e:""+e,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){const s=Array.isArray(t)?t[0]:t;if(void 0!==i&&!Ne._CheckLimit(s,i))return;const r=Ne._FormatMessage(s),n=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];n.logFunc&&n.logFunc("BJS - "+r,...o);const a=`
${r}

`;Ne._AddLogEntry(a),Ne._GenerateLimitMessage(s,e)}static get LogCache(){return Ne._LogCache}static ClearLogCache(){Ne._LogCache="",Ne._LogLimitOutputs={},Ne.errorsCount=0}static set LogLevels(e){Ne.Log=Ne._LogDisabled,Ne.Warn=Ne._LogDisabled,Ne.Error=Ne._LogDisabled,[Ne.MessageLogLevel,Ne.WarningLogLevel,Ne.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];Ne[e.name]=Ne._LogEnabled.bind(Ne,t)}}))}}Ne.NoneLogLevel=0,Ne.MessageLogLevel=1,Ne.WarningLogLevel=2,Ne.ErrorLogLevel=4,Ne.AllLogLevel=7,Ne.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",Ne._LogCache="",Ne._LogLimitOutputs={},Ne._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],Ne.errorsCount=0,Ne.Log=Ne._LogEnabled.bind(Ne,Ne.MessageLogLevel),Ne.Warn=Ne._LogEnabled.bind(Ne,Ne.WarningLogLevel),Ne.Error=Ne._LogEnabled.bind(Ne,Ne.ErrorLogLevel);class Fe extends Ie{constructor(e,t,i,s){super(e,s),this.propertyPath=i,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]}serialize(e){return super._serialize({name:"SwitchBooleanAction",properties:[Ie._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}class Le extends Ie{constructor(e,t,i,s){super(e,s),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[Ie._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}class Be extends Ie{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"SetValueAction",properties:[Ie._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Ie._SerializeValueAsString(this.value)}]},e)}}class ke extends Ie{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&Ne.Warn("Warning: IncrementValueAction can only be used with number values")}execute(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"IncrementValueAction",properties:[Ie._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Ie._SerializeValueAsString(this.value)}]},e)}}class Ve extends Ie{constructor(e,t,i,s,r,n){super(e,n),this.from=i,this.to=s,this.loop=r,this._target=t}_prepare(){}execute(){this._actionManager.getScene().beginAnimation(this._target,this.from,this.to,this.loop)}serialize(e){return super._serialize({name:"PlayAnimationAction",properties:[Ie._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:Ie._SerializeValueAsString(this.loop)||!1}]},e)}}class Ue extends Ie{constructor(e,t,i){super(e,i),this._target=t}_prepare(){}execute(){this._actionManager.getScene().stopAnimation(this._target)}serialize(e){return super._serialize({name:"StopAnimationAction",properties:[Ie._GetTargetProperty(this._target)]},e)}}class Ge extends Ie{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class ze extends Ie{constructor(e,t,i,s=!0){super(e,i),this.children=t,this.enableChildrenConditions=s}_prepare(){for(let e=0;ee?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?{...e}:null:e.clone(t):null;class Ye{static DeepCopy(e,t,i,s,r=!1){const n=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const o of n){if("_"===o[0]&&(!s||-1===s.indexOf(o)))continue;if(o.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(o))continue;const n=e[o],a=typeof n;if("function"!==a)try{if("object"===a)if(n instanceof Uint8Array)t[o]=Uint8Array.from(n);else if(n instanceof Array){if(t[o]=[],n.length>0)if("object"==typeof n[0])for(let e=0;e-1&&this._scene.actionManagers.splice(e,1);const t=this._scene.meshes.filter((e=>e.actionManager===this));for(const e of t)e.actionManager=null}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=Qe.OnPickTrigger&&t.trigger<=Qe.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=Qe.OnPickTrigger&&t.trigger<=Qe.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===Qe.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(Ne.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,Qe.Triggers[e.trigger]?Qe.Triggers[e.trigger]++:Qe.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){const t=this.actions.indexOf(e);return-1!==t&&(this.actions.splice(t,1),Qe.Triggers[e.trigger]-=1,0===Qe.Triggers[e.trigger]&&delete Qe.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i{if(null===s){const e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}const r=s.split("."),n=t.split(",");for(let e=0;e{if(e.detached)return;const h=[];let c=null,u=null;const d=e.combine&&e.combine.length>0;if(2===e.type?h.push(s):h.push(t),d){const t=[];for(let i=0;i{const i=W("BABYLON."+e);return i&&new i(...t)})(e.name,h);if(_ instanceof Me&&null!==o){const e=new Ge(t,o);a?a.then(e):s.registerAction(e),a=e}null===l?_ instanceof Me?(o=_,_=a):(o=null,a?a.then(_):s.registerAction(_)):l.push(_);for(let i=0;i0){const e=r.properties[0].value,t=null===r.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),s={trigger:Qe[r.name],parameter:t}}else s=Qe[r.name];for(let e=0;e=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o}Object.create,Object.create;const Je={},et={};function tt(e){const t=e.getClassName();if(Je[t])return Je[t];Je[t]={};const i=Je[t];let s=e,r=t;for(;r;){const e=et[r];for(const t in e)i[t]=e[t];let t,n=!1;do{if(t=Object.getPrototypeOf(s),!t.getClassName){n=!0;break}if(t.getClassName()!==r)break;s=t}while(t);if(n)break;r=t.getClassName(),s=t}return i}function it(e,t){return(i,s)=>{const r=function(e){const t=e.getClassName();return et[t]||(et[t]={}),et[t]}(i);r[s]||(r[s]={type:e,sourceName:t})}}function st(e,t=null){return function(e,t=null){return(i,s)=>{const r=t||"_"+s;Object.defineProperty(i,s,{get:function(){return this[r]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[r]!==t&&(this[r]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function rt(e){return it(0,e)}function nt(e){return it(1,e)}function ot(e){return it(2,e)}function at(e){return it(3,e)}function lt(e){return it(4,e)}function ht(e){return it(5,e)}function ct(e){return it(6,e)}function ut(e){return it(7,e)}function dt(e){return it(8,e)}function _t(e){return it(9,e)}function pt(e){return it(10,e)}function ft(e){return it(12,e)}function mt(e){return it(11,e)}function gt(e,t,i,s){const r=i.value;i.value=(...i)=>{let n=r;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];n=s?(...t)=>s(...t)?e(...t):r(...t):e}return e[t]=n,n(...i)}}gt.filter=function(e){return(t,i,s)=>gt(t,i,s,e)};const vt={};function xt(e,t=!1){if(!t||!vt[e])return vt[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}class bt{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),bt._HandleParenthesisContent(e,t)))):bt._HandleParenthesisContent(e,t))||"false"!==e&&bt.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const s=e.split("||");for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){let r=bt._SimplifyNegation(s[e].trim());const n=r.split("&&");if(n.length>1)for(let e=0;e(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}class Tt{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>Tt.HasTags(e),e.addTags=t=>Tt.AddTagsTo(e,t),e.removeTags=t=>Tt.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>Tt.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;const t=e._tags;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const t=[];for(const i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}return e._tags}static AddTagsTo(e,t){t&&"string"==typeof t&&t.split(" ").forEach((function(t){Tt._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(Tt.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!Tt.HasTags(e))return;const i=t.split(" ");for(const t in i)Tt._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?Tt.HasTags(e):bt.Eval(t,(t=>Tt.HasTags(e)&&e._tags[t])))}}const yt=function(e,t,i,s={}){const r=e();Tt&&Tt.HasTags(t)&&Tt.AddTagsTo(r,Tt.GetTags(t,!0));const n=tt(r),o={};for(const e in n){const a=n[e],l=t[e],h=a.type;if(null!=l&&("uniqueId"!==e||St.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:r[e]=l;break;case 1:s.cloneTexturesOnlyOnce&&o[l.uniqueId]?r[e]=o[l.uniqueId]:(r[e]=i||l.isRenderTarget?l:l.clone(),o[l.uniqueId]=r[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:r[e]=i?l:l.clone()}}return r};class St{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw xt("ImageProcessingConfiguration")},St._FresnelParametersParser=e=>{throw xt("FresnelParameters")},St._ColorCurvesParser=e=>{throw xt("ColorCurves")},St._TextureParser=(e,t,i)=>{throw xt("Texture")};class Ct{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new K,this._onClonedObservable=new K}}class Et{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,s){const r=this._NodeConstructors[e];return r?r(t,i,s):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;const t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){const t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){-1===this._nodeDataStorage._sceneRootNodesIndex&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(-1!==this._nodeDataStorage._sceneRootNodesIndex){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null,i=!0){this._isDirty=!1,this._nodeDataStorage=new Ct,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new K,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=me.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new K,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||re.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),i&&this._addToSceneRootNodes()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return-1!==this._behaviors.indexOf(e)||(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce((()=>{e.attach(this)})):e.attach(this),this._behaviors.push(e)),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),this}get behaviors(){return this._behaviors}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={}}updateCache(e){!e&&this.isSynchronized()||this._updateCache()}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return!this._parentNode||!this._parentNode._isDirty&&this._parentUpdateId===this._parentNode._childUpdateId&&this._parentNode.isSynchronized()}isSynchronized(){return!(this._parentNode&&!this.isSynchronizedWithParent())&&this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return!1===e?this._nodeDataStorage._isEnabled:!!this._nodeDataStorage._isEnabled&&this._nodeDataStorage._isParentEnabled}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),this._children&&this._children.forEach((e=>{e._syncParentEnabledState()}))}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return!!this.parent&&(this.parent===e||this.parent.isDescendantOf(e))}_getDescendants(e,t=!1,i){if(this._children)for(let s=0;s(!t||t(e))&&void 0!==e.cullingStrategy)),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)}getAnimationByName(e){for(let t=0;tnew Et(e,this.getScene())),this);if(t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i{throw xt("AnimationRange")},Et._NodeConstructors={},Ze([rt()],Et.prototype,"name",void 0),Ze([rt()],Et.prototype,"id",void 0),Ze([rt()],Et.prototype,"uniqueId",void 0),Ze([rt()],Et.prototype,"state",void 0),Ze([rt()],Et.prototype,"metadata",void 0);class At{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=0|this.width;return e=397*e^this.height,e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new At(this.width*e,this.height*t)}clone(){return new At(this.width,this.height)}equals(e){return!!e&&this.width===e.width&&this.height===e.height}get surface(){return this.width*this.height}static Zero(){return new At(0,0)}add(e){return new At(this.width+e.width,this.height+e.height)}subtract(e){return new At(this.width-e.width,this.height-e.height)}scale(e){return new At(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,r=e.height+(t.height-e.height)*i;return new At(s,r)}}class Pt{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(Pt.CustomRequestHeaders).length>0||Pt.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in Pt.CustomRequestHeaders){const t=Pt.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return Pt.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){Pt.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const e of Pt.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}t=(t=t.replace("file:http:","http:")).replace("file:https:","https:"),this._requestURL=t,this._xhr.open(e,t,!0)}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}Pt.CustomRequestHeaders={},Pt.CustomRequestModifiers=new Array,Pt.SkipRequestModificationForBabylonCDN=!0;const It=Object.freeze(new fe(0,0,0,0)),Rt=Object.freeze(_e.Zero()),Mt=Object.freeze(de.Zero()),Ot=Object.freeze(At.Zero()),Dt=Object.freeze(Ee.Black()),wt=Object.freeze(new Ae(0,0,0,0)),Nt={key:0,repeatCount:0,loopMode:2};class Ft{static _PrepareAnimation(e,t,i,s,r,n,o,a){let l;if(!isNaN(parseFloat(r))&&isFinite(r)?l=Ft.ANIMATIONTYPE_FLOAT:r instanceof fe?l=Ft.ANIMATIONTYPE_QUATERNION:r instanceof _e?l=Ft.ANIMATIONTYPE_VECTOR3:r instanceof de?l=Ft.ANIMATIONTYPE_VECTOR2:r instanceof Ee?l=Ft.ANIMATIONTYPE_COLOR3:r instanceof Ae?l=Ft.ANIMATIONTYPE_COLOR4:r instanceof At&&(l=Ft.ANIMATIONTYPE_SIZE),null==l)return null;const h=new Ft(e,t,i,l,o),c=[{frame:0,value:r},{frame:s,value:n}];return h.setKeys(c),void 0!==a&&h.setEasingFunction(a),h}static CreateAnimation(e,t,i,s){const r=new Ft(e+"Animation",e,i,t,Ft.ANIMATIONLOOPMODE_CONSTANT);return r.setEasingFunction(s),r}static CreateAndStartAnimation(e,t,i,s,r,n,o,a,l,h,c){const u=Ft._PrepareAnimation(e,i,s,r,n,o,a,l);return u?(t.getScene&&(c=t.getScene()),c?c.beginDirectAnimation(t,[u],0,r,1===u.loopMode,1,h):null):null}static CreateAndStartHierarchyAnimation(e,t,i,s,r,n,o,a,l,h,c){const u=Ft._PrepareAnimation(e,s,r,n,o,a,l,h);return u?t.getScene().beginDirectHierarchyAnimation(t,i,[u],0,n,1===u.loopMode,1,c):null}static CreateMergeAndStartAnimation(e,t,i,s,r,n,o,a,l,h){const c=Ft._PrepareAnimation(e,i,s,r,n,o,a,l);return c?(t.animations.push(c),t.getScene().beginAnimation(t,0,r,1===c.loopMode,1,h)):null}static MakeAnimationAdditive(e,t,i,s=!1,r){let n;n="object"==typeof t?t:{referenceFrame:t??0,range:i,cloneOriginalAnimation:s,clonedAnimationName:r};let o=e;if(n.cloneOriginalAnimation&&(o=e.clone(),o.name=n.clonedAnimationName||o.name),!o._keys.length)return o;const a=n.referenceFrame&&n.referenceFrame>=0?n.referenceFrame:0;let l=0;const h=o._keys[0];let c=o._keys.length-1;const u=o._keys[c],d={referenceValue:h.value,referencePosition:ve.Vector3[0],referenceQuaternion:ve.Quaternion[0],referenceScaling:ve.Vector3[1],keyPosition:ve.Vector3[2],keyQuaternion:ve.Quaternion[1],keyScaling:ve.Vector3[3]};let _=h.frame,p=u.frame;if(n.range){const e=o.getRange(n.range);e&&(_=e.from,p=e.to)}else _=n.fromFrame??_,p=n.toFrame??p;if(_!==h.frame&&(l=o.createKeyForFrame(_)),p!==u.frame&&(c=o.createKeyForFrame(p)),1===o._keys.length){const e=o._getKeyValue(o._keys[0]);d.referenceValue=e.clone?e.clone():e}else if(a<=h.frame){const e=o._getKeyValue(h.value);d.referenceValue=e.clone?e.clone():e}else if(a>=u.frame){const e=o._getKeyValue(u.value);d.referenceValue=e.clone?e.clone():e}else{Nt.key=0;const e=o._interpolate(a,Nt);d.referenceValue=e.clone?e.clone():e}o.dataType===Ft.ANIMATIONTYPE_QUATERNION?d.referenceValue.normalize().conjugateInPlace():o.dataType===Ft.ANIMATIONTYPE_MATRIX&&(d.referenceValue.decompose(d.referenceScaling,d.referenceQuaternion,d.referencePosition),d.referenceQuaternion.normalize().conjugateInPlace());let f=Number.MAX_VALUE;const m=n.clipKeys?[]:null;for(let e=l;e<=c;e++){let t=o._keys[e];if((m||n.cloneOriginalAnimation)&&(t={frame:t.frame,value:t.value.clone?t.value.clone():t.value,inTangent:t.inTangent,outTangent:t.outTangent,interpolation:t.interpolation,lockedTangent:t.lockedTangent},m&&(f===Number.MAX_VALUE&&(f=t.frame),t.frame-=f,m.push(t))),!e||o.dataType===Ft.ANIMATIONTYPE_FLOAT||t.value!==h.value)switch(o.dataType){case Ft.ANIMATIONTYPE_MATRIX:t.value.decompose(d.keyScaling,d.keyQuaternion,d.keyPosition),d.keyPosition.subtractInPlace(d.referencePosition),d.keyScaling.divideInPlace(d.referenceScaling),d.referenceQuaternion.multiplyToRef(d.keyQuaternion,d.keyQuaternion),me.ComposeToRef(d.keyScaling,d.keyQuaternion,d.keyPosition,t.value);break;case Ft.ANIMATIONTYPE_QUATERNION:d.referenceValue.multiplyToRef(t.value,t.value);break;case Ft.ANIMATIONTYPE_VECTOR2:case Ft.ANIMATIONTYPE_VECTOR3:case Ft.ANIMATIONTYPE_COLOR3:case Ft.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(d.referenceValue,t.value);break;case Ft.ANIMATIONTYPE_SIZE:t.value.width-=d.referenceValue.width,t.value.height-=d.referenceValue.height;break;default:t.value-=d.referenceValue}}return m&&o.setKeys(m,!0),o}static TransitionTo(e,t,i,s,r,n,o,a=null){if(o<=0)return i[e]=t,a&&a(),null;const l=r*(o/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);const h=s.beginAnimation(i,0,l,!1);return h.onAnimationEnd=a,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,s,r,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=s,this.loopMode=r,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=s,this.loopMode=void 0===r?Ft.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=Ft._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort(((e,t)=>e.frame-t.frame))}removeEvents(e){for(let t=0;t=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const s=this._keys,r=s.length;let n=t.key;for(;n>=0&&e=s[n+1].frame;)++n;if(t.key=n,n<0)return i?void 0:this._getKeyValue(s[0].value);if(n+1>r-1)return i?void 0:this._getKeyValue(s[r-1].value);const o=s[n],a=s[n+1];if(i&&(e===o.frame||e===a.frame))return;const l=this._getKeyValue(o.value),h=this._getKeyValue(a.value);if(o.interpolation===$e.STEP)return a.frame>e?l:h;const c=void 0!==o.outTangent&&void 0!==a.inTangent,u=a.frame-o.frame;let d=(e-o.frame)/u;const _=o.easingFunction||this.getEasingFunction();switch(null!==_&&(d=_.ease(d)),this.dataType){case Ft.ANIMATIONTYPE_FLOAT:{const e=c?this.floatInterpolateFunctionWithTangents(l,o.outTangent*u,h,a.inTangent*u,d):this.floatInterpolateFunction(l,h,d);switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return e;case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+e}break}case Ft.ANIMATIONTYPE_QUATERNION:{const e=c?this.quaternionInterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.quaternionInterpolateFunction(l,h,d);switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return e;case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||It).scale(t.repeatCount))}return e}case Ft.ANIMATIONTYPE_VECTOR3:{const e=c?this.vector3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.vector3InterpolateFunction(l,h,d);switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return e;case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Rt).scale(t.repeatCount))}break}case Ft.ANIMATIONTYPE_VECTOR2:{const e=c?this.vector2InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.vector2InterpolateFunction(l,h,d);switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return e;case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Mt).scale(t.repeatCount))}break}case Ft.ANIMATIONTYPE_SIZE:switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,h,d);case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(l,h,d).add((t.offsetValue||Ot).scale(t.repeatCount))}break;case Ft.ANIMATIONTYPE_COLOR3:{const e=c?this.color3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.color3InterpolateFunction(l,h,d);switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return e;case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Dt).scale(t.repeatCount))}break}case Ft.ANIMATIONTYPE_COLOR4:{const e=c?this.color4InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.color4InterpolateFunction(l,h,d);switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return e;case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||wt).scale(t.repeatCount))}break}case Ft.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return Ft.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,h,d,t.workValue):l;case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return l}}return 0}matrixInterpolateFunction(e,t,i,s){return Ft.AllowMatrixDecomposeForInterpolation?s?(me.DecomposeLerpToRef(e,t,i,s),s):me.DecomposeLerp(e,t,i):s?(me.LerpToRef(e,t,i,s),s):me.Lerp(e,t,i)}clone(){const e=new Ft(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(const t in this._ranges){const i=this._ranges[t];i&&(e._ranges[t]=i.clone())}}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){Nt.key=0;const t=this._interpolate(e,Nt,!0);if(!t)return this._keys[Nt.key].frame===e?Nt.key:Nt.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(Nt.key+1,0,i),Nt.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let s=0;s=2&&(o=t.values[1]),t.values.length>=3&&(a=t.values[2]),t.values.length>=4&&(l=t.values[3]);break;case Ft.ANIMATIONTYPE_QUATERNION:if(r=fe.FromArray(t.values),t.values.length>=8){const e=fe.FromArray(t.values.slice(4,8));e.equals(fe.Zero())||(o=e)}if(t.values.length>=12){const e=fe.FromArray(t.values.slice(8,12));e.equals(fe.Zero())||(a=e)}t.values.length>=13&&(l=t.values[12]);break;case Ft.ANIMATIONTYPE_MATRIX:r=me.FromArray(t.values),t.values.length>=17&&(l=t.values[16]);break;case Ft.ANIMATIONTYPE_COLOR3:r=Ee.FromArray(t.values),t.values[3]&&(o=Ee.FromArray(t.values[3])),t.values[4]&&(a=Ee.FromArray(t.values[4])),t.values[5]&&(l=t.values[5]);break;case Ft.ANIMATIONTYPE_COLOR4:r=Ae.FromArray(t.values),t.values[4]&&(o=Ae.FromArray(t.values[4])),t.values[5]&&(a=Ae.FromArray(t.values[5])),t.values[6]&&(l=Ae.FromArray(t.values[6]));break;case Ft.ANIMATIONTYPE_VECTOR3:default:r=_e.FromArray(t.values),t.values[3]&&(o=_e.FromArray(t.values[3])),t.values[4]&&(a=_e.FromArray(t.values[4])),t.values[5]&&(l=t.values[5])}const h={};h.frame=t.frame,h.value=r,null!=o&&(h.inTangent=o),null!=a&&(h.outTangent=a),null!=l&&(h.interpolation=l),s.push(h)}if(t.setKeys(s),e.ranges)for(n=0;n{const r=new Pt;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){let t=JSON.parse(r.responseText);if(t.animations&&(t=t.animations),t.length){const e=[];for(const i of t)e.push(this.Parse(i));i(e)}else{const s=this.Parse(t);e&&(s.name=e),i(s)}}else s("Unable to load the animation")})),r.open("GET",t),r.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const s=new Pt;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){const i=JSON.parse(JSON.parse(s.responseText).jsonPayload);if(i.animations){const s=JSON.parse(i.animations),r=[];for(const t of s.animations){const i=this.Parse(t);i.snippetId=e,r.push(i)}t(r)}else{const s=JSON.parse(i.animation),r=this.Parse(s);r.snippetId=e,t(r)}}else i("Unable to load the snippet "+e)})),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()}))}}Ft._UniqueIdGenerator=0,Ft.AllowMatricesInterpolation=!1,Ft.AllowMatrixDecomposeForInterpolation=!0,Ft.SnippetUrl="https://snippet.babylonjs.com",Ft.ANIMATIONTYPE_FLOAT=0,Ft.ANIMATIONTYPE_VECTOR3=1,Ft.ANIMATIONTYPE_QUATERNION=2,Ft.ANIMATIONTYPE_MATRIX=3,Ft.ANIMATIONTYPE_COLOR3=4,Ft.ANIMATIONTYPE_COLOR4=7,Ft.ANIMATIONTYPE_VECTOR2=5,Ft.ANIMATIONTYPE_SIZE=6,Ft.ANIMATIONLOOPMODE_RELATIVE=0,Ft.ANIMATIONLOOPMODE_CYCLE=1,Ft.ANIMATIONLOOPMODE_CONSTANT=2,Ft.ANIMATIONLOOPMODE_YOYO=4,Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,Ft.CreateFromSnippetAsync=Ft.ParseFromSnippetAsync,z("BABYLON.Animation",Ft),Et._AnimationRangeFactory=(e,t,i)=>new qe(e,t,i);class Lt extends Ie{constructor(e,t,i,s,r=1e3,n,o,a){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new K,this.propertyPath=i,this.value=s,this.duration=r,this.stopOtherAnimations=o,this.onInterpolationDone=a,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){const e=this._actionManager.getScene(),t=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];let i;if("number"==typeof this.value)i=Ft.ANIMATIONTYPE_FLOAT;else if(this.value instanceof Ee)i=Ft.ANIMATIONTYPE_COLOR3;else if(this.value instanceof _e)i=Ft.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof me)i=Ft.ANIMATIONTYPE_MATRIX;else{if(!(this.value instanceof fe))return void Ne.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");i=Ft.ANIMATIONTYPE_QUATERNION}const s=new Ft("InterpolateValueAction",this._property,1e3/this.duration*100,i,Ft.ANIMATIONLOOPMODE_CONSTANT);s.setKeys(t),this.stopOtherAnimations&&e.stopAnimation(this._effectiveTarget),e.beginDirectAnimation(this._effectiveTarget,[s],0,100,!1,1,(()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()}))}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[Ie._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Ie._SerializeValueAsString(this.value)},{name:"duration",value:Ie._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:Ie._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}z("BABYLON.InterpolateValueAction",Lt);class Bt{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,i,s){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._yoyoDirection=1,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=s,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===Ft.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=me.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,0!==this._minFrame){const e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(const t of this._target)this._preparePath(t,e),this._getOriginalValues(e),e++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const r=t.getEvents();r&&r.length>0&&r.forEach((e=>{this._events.push(e._clone())})),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){const i=this._animation.targetPropertyPath;if(i.length>1){let s=e;for(let e=0;e-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray)for(let i=0;ii[i.length-1].frame&&(e=i[i.length-1].frame);const s=this._events;if(s.length)for(let t=0;tthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const h=i-t;let c,u=e*(o.framePerSecond*r)/1e3+this._absoluteFrameOffset,d=0,_=!1;const p=s&&this._animationState.loopMode===Ft.ANIMATIONLOOPMODE_YOYO;if(p){const e=(u-t)/h,i=Math.sin(e*Math.PI);u=Math.abs(i)*h+t;const s=i>=0?1:-1;this._yoyoDirection!==s&&(_=!0),this._yoyoDirection=s}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=u,!s&&i>=t&&(u>=h&&r>0||u<=0&&r<0))l=!1,d=o._getKeyValue(this._maxValue);else if(!s&&t>=i&&(u<=h&&r<0||u>=0&&r>0))l=!1,d=o._getKeyValue(this._minValue);else if(this._animationState.loopMode!==Ft.ANIMATIONLOOPMODE_CYCLE){const e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=Ft.ANIMATIONLOOPMODE_CYCLE;const s=o._interpolate(t,this._animationState),r=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case Ft.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=r-s;break;case Ft.ANIMATIONTYPE_QUATERNION:case Ft.ANIMATIONTYPE_VECTOR3:case Ft.ANIMATIONTYPE_VECTOR2:case Ft.ANIMATIONTYPE_SIZE:case Ft.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=r.subtract(s)}this._highLimitsCache[e]=r}d=this._highLimitsCache[e],c=this._offsetsCache[e]}if(void 0===c)switch(o.dataType){case Ft.ANIMATIONTYPE_FLOAT:c=0;break;case Ft.ANIMATIONTYPE_QUATERNION:c=It;break;case Ft.ANIMATIONTYPE_VECTOR3:c=Rt;break;case Ft.ANIMATIONTYPE_VECTOR2:c=Mt;break;case Ft.ANIMATIONTYPE_SIZE:c=Ot;break;case Ft.ANIMATIONTYPE_COLOR3:c=Dt;break;case Ft.ANIMATIONTYPE_COLOR4:c=wt}let f;if(this._host&&this._host.syncRoot){const e=this._host.syncRoot;f=t+h*((e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame))}else f=u>0&&t>i||u<0&&t0&&this.currentFrame>f||r<0&&this.currentFrame0?0:o.getKeys().length-1}this._currentFrame=f,this._animationState.repeatCount=0===h?0:u/h|0,this._animationState.highLimitValue=d,this._animationState.offsetValue=c;const g=o._interpolate(f,this._animationState);if(this.setValue(g,n),m.length)for(let e=0;e=0&&f>=m[e].frame&&m[e].frame>=t||h<0&&f<=m[e].frame&&m[e].frame<=t){const t=m[e];t.isDone||(t.onlyOnce&&(m.splice(e,1),e--),t.isDone=!0,t.action(f))}return l||(this._stopped=!0),l}}function kt(){return"undefined"!=typeof window}function Vt(){return"undefined"!=typeof navigator}function Ut(){return"undefined"!=typeof document}function Gt(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}const zt={IsWindowObjectExist:kt,IsNavigatorAvailable:Vt,IsDocumentAvailable:Ut,GetDOMTextContent:Gt};class Wt{static get Now(){return kt()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class Ht{}Ht.FilesToLoad={};class Xt{static ExponentialBackoff(e=3,t=500){return(i,s,r)=>0!==s.status||r>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,r)*t}}class Yt extends Error{}Yt._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));const Qt={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class jt extends Yt{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",Yt._setPrototypeOf(this,jt.prototype)}}const Kt=(e,t)=>e.endsWith(t),$t=(e,t)=>!!e&&e.startsWith(t),qt=e=>{if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0;i{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,s,r,n,o,a,l,h="",c=0;const u=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c>2,o=(3&i)<<4|s>>4,a=(15&s)<<2|r>>6,l=63&r,isNaN(s)?a=l=64:isNaN(r)&&(l=64),h+=t.charAt(n)+t.charAt(o)+t.charAt(a)+t.charAt(l);return h},Jt=e=>atob(e),ei=e=>{const t=Jt(e),i=t.length,s=new Uint8Array(new ArrayBuffer(i));for(let e=0;e{let i=String(e);for(;i.length{i+=s.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class ri{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(e);else{const e=t.split(";");for(let t=0;t{h=h.trim(),""!==h&&(i.push(h),h="")},n=e=>{sai._Stack[s],a=()=>-1===s?"!!INVALID EXPRESSION!!":ai._Stack[s--];let l=0,h="";for(;l1){for(r();-1!==s&&ai._OperatorPriority[o()]>=ai._OperatorPriority[c];)i.push(a());n(c),l++}else h+=t;l++}for(r();-1!==s;)"("===o()?a():i.push(a());return ai._InfixToPostfixCache.size>=ai.InfixToPostfixCacheLimitSize&&ai.ClearCache(),ai._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(ai._InfixToPostfixCache.entries()).sort(((e,t)=>e[1].accessTime-t[1].accessTime));for(let t=0;t":i=s>r;break;case"<":i=s=":i=s>=r;break;case"==":i=s===r;break;case"!=":i=s!==r}return i}}var di;!function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(di||(di={}));const _i={};function pi(e,t,i=""){return i+(t?t+"\n":"")+e}function fi(e,t,i,s,r,n,o){const a=o||_i.loadFile;if(a)return a(e,t,i,s,r,n);throw xt("FileTools")}function mi(e,t,i,s){if(e)return t?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,i?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(s?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return t&&(e+="#define IS_NDC_HALF_ZRANGE"),i&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),s&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}const gi=/defined\s*?\((.+?)\)/g,vi=/defined\s*?\[(.+?)\]/g,xi=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,bi=/__decl__/,Ti=/light\{X\}.(\w*)/g,yi=/\{X\}/g,Si=[],Ci=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function Ei(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}function Ai(e,t,i,s){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),Ni(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const r=function(e,t,i){let s=function(e,t){if(t.processor?.noPrecision)return e;const i=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=i?"precision highp float;\n"+e:"precision mediump float;\n"+e:i||(e=e.replace("precision highp float","precision mediump float")),e}(e,t);if(!t.processor)return s;if(t.processor.shaderLanguage===di.GLSL&&-1!==s.indexOf("#version 3")&&(s=s.replace("#version 300 es",""),!t.processor.parseGLES3))return s;const r=t.defines,n=wi(t,i);return t.processor.preProcessor&&(s=t.processor.preProcessor(s,r,n,t.isFragment,t.processingContext)),s=Di(s,n,t),t.processor.postProcessor&&(s=t.processor.postProcessor(s,r,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),i?._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}(e,t,s);i(r,e)}))}function Pi(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}function Ii(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new li(t[1].trim(),"!"===e[0]);const i=["==","!=",">=","<=","<",">"];let s="",r=0;for(s of i)if(r=e.indexOf(s),r>-1)break;if(-1===r)return new li(e);const n=e.substring(0,r).trim(),o=e.substring(r+s.length).trim();return new ui(n,s,o)}function Ri(e,t){const i=new oi,s=e.substring(0,t);let r=e.substring(t);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),i.testExpression="#ifdef"===s?new li(r):"#ifndef"===s?new li(r,!0):function(e){e=e.replace(gi,"defined[$1]");const t=ai.infixToPostfix(e),i=[];for(const e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],s=i[i.length-2];i.length-=2;const r="&&"==e?new ci:new hi;"string"==typeof t&&(t=t.replace(vi,"defined($1)")),"string"==typeof s&&(s=s.replace(vi,"defined($1)")),r.leftOperand="string"==typeof s?Ii(s):s,r.rightOperand="string"==typeof t?Ii(t):t,i.push(r)}let s=i[i.length-1];return"string"==typeof s&&(s=s.replace(vi,"defined($1)")),"string"==typeof s?Ii(s):s}(r),i}function Mi(e,t,i){let s=e.currentLine;for(;Oi(e,i);){s=e.currentLine;const r=s.substring(0,5).toLowerCase();if("#else"===r){const i=new si;return t.children.push(i),void Oi(e,i)}if("#elif"===r){const e=Ri(s,5);t.children.push(e),i=e}}}function Oi(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const s=Ci.exec(i);if(s&&s.length){switch(s[0]){case"#ifdef":{const s=new ni;t.children.push(s);const r=Ri(i,6);s.children.push(r),Mi(e,s,r);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const s=new ni;t.children.push(s);const r=Ri(i,7);s.children.push(r),Mi(e,s,r);break}case"#if":{const s=new ni,r=Ri(i,3);t.children.push(s),s.children.push(r),Mi(e,s,r);break}}continue}}const s=new si;if(s.line=i,t.children.push(s),"#"===i[0]&&"d"===i[1]){const e=i.replace(";","").split(" ");s.additionalDefineKey=e[1],3===e.length&&(s.additionalDefineValue=e[2])}}return!1}function Di(e,t,i){const s=new si,r=new ri;return r.lineIndex=-1,r.lines=e.split("\n"),Oi(r,s),s.process(t,i)}function wi(e,t){const i=e.defines,s={};for(const e of i){const t=e.replace("#define","").replace(";","").trim().split(" ");s[t[0]]=t.length>1?t[1]:""}return e.processor?.shaderLanguage===di.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",mi(s,t?.isNDCHalfZRange,t?.useReverseDepthBuffer,t?.useExactSrgbConversions),s}function Ni(e,t,i){let s;for(Si.length=0;null!==(s=xi.exec(e));)Si.push(s);let r=String(e),n=[e],o=!1;for(const e of Si){let s=e[1];if(-1!==s.indexOf("__decl__")&&(s=s.replace(bi,""),t.supportsUniformBuffers&&(s=s.replace("Vertex","Ubo").replace("Fragment","Ubo")),s+="Declaration"),!t.includesShadersStore[s]){const e=t.shadersRepository+"ShadersInclude/"+s+".fx";return void Fi.loadFile(e,(e=>{t.includesShadersStore[s]=e,Ni(n.join(""),t,i)}))}{let i=t.includesShadersStore[s];if(e[2]){const t=e[3].split(",");for(let e=0;et+"{X}"))),i+=o.replace(yi,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(Ti,((e,t)=>t+"{X}"))),i=i.replace(yi,s)}const r=[];for(const t of n){const s=t.split(e[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}}Si.length=0,r=n.join(""),o?Ni(r.toString(),t,i):i(r)}const Fi={loadFile:(e,t,i,s,r,n)=>{throw xt("FileTools")}};class Li{static SetImmediate(e){kt()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}class Bi{static GetShadersRepository(e=di.GLSL){return e===di.GLSL?Bi.ShadersRepository:Bi.ShadersRepositoryWGSL}static GetShadersStore(e=di.GLSL){return e===di.GLSL?Bi.ShadersStore:Bi.ShadersStoreWGSL}static GetIncludesShadersStore(e=di.GLSL){return e===di.GLSL?Bi.IncludesShadersStore:Bi.IncludesShadersStoreWGSL}}Bi.ShadersRepository="src/Shaders/",Bi.ShadersStore={},Bi.IncludesShadersStore={},Bi.ShadersRepositoryWGSL="src/ShadersWGSL/",Bi.ShadersStoreWGSL={},Bi.IncludesShadersStoreWGSL={};class ki{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,i,s,r,n,o,a){const l=this.engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this.engine.getUniforms(this,i).forEach(((e,t)=>{s[i[t]]=e})),this._uniforms=s,h=0;h{n[e]=t}));for(const e of l.getAttributes(this,o))a.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s||2!==s.length)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r||3!==r.length)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}const Vi=new WeakMap,Ui={_webGLVersion:2,cachedPipelines:{}};function Gi(e){let t=Vi.get(e);if(!t){if(!e)return Ui;t={_webGLVersion:e.TEXTURE_BINDING_3D?2:1,_context:e,cachedPipelines:{}},Vi.set(e,t)}return t}function zi(e,t,i,s,r,n){const o=Gi(s);return n||(n=o._createShaderProgramInjection??Hi),n(e,Qi(t,"vertex",s,o._contextWasLost),Qi(i,"fragment",s,o._contextWasLost),s,r,o.validateShaderPrograms)}function Wi(e,t,i,s,r,n=null,o){const a=Gi(r);o||(o=a._createShaderProgramInjection??Hi);const l=a._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"";return o(e,Yi(t,"vertex",s,l,r,a._contextWasLost),Yi(i,"fragment",s,l,r,a._contextWasLost),r,n,a.validateShaderPrograms)}function Hi(e,t,i,s,r=null,n){const o=s.createProgram();if(e.program=o,!o)throw new Error("Unable to create program");return s.attachShader(o,t),s.attachShader(o,i),s.linkProgram(o),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||Xi(e,s,n),o}function Xi(e,t,i){const s=e.context,r=e.vertexShader,n=e.fragmentShader,o=e.program;if(!s.getProgramParameter(o,s.LINK_STATUS)){if(!t.getShaderParameter(r,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(r);if(i)throw e.vertexCompilationError=i,new Error("VERTEX SHADER "+i)}if(!t.getShaderParameter(n,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(n);if(i)throw e.fragmentCompilationError=i,new Error("FRAGMENT SHADER "+i)}const i=s.getProgramInfoLog(o);if(i)throw e.programLinkError=i,new Error(i)}if(i&&(s.validateProgram(o),!s.getProgramParameter(o,s.VALIDATE_STATUS))){const t=s.getProgramInfoLog(o);if(t)throw e.programValidationError=t,new Error(t)}s.deleteShader(r),s.deleteShader(n),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}function Yi(e,t,i,s,r,n){return Qi(pi(e,i,s),t,r,n)}function Qi(e,t,i,s){const r=i.createShader("vertex"===t?i.VERTEX_SHADER:i.FRAGMENT_SHADER);if(!r){let e=i.NO_ERROR,r=i.NO_ERROR;for(;(r=i.getError())!==i.NO_ERROR;)e=r;throw new Error(`Something went wrong while creating a gl ${t} shader object. gl error=${e}, gl isContextLost=${i.isContextLost()}, _contextWasLost=${s}`)}return i.shaderSource(r,e),i.compileShader(r),r}function ji(e){const t=e._name,i=e.context;if(t&&i){const e=Gi(i),s=e.cachedPipelines[t];s?.dispose(),delete e.cachedPipelines[t]}}function Ki(e,t,i,s,r,n){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void s(Gt(e));if("source:"===e.substr(0,7))return void s(e.substr(7));if("base64:"===e.substr(0,7))return void s(window.atob(e.substr(7)));const o=Bi.GetShadersStore(r);if(o[e+t+"Shader"])return void s(o[e+t+"Shader"]);if(i&&o[e+i+"Shader"])return void s(o[e+i+"Shader"]);let a;if(a="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:Bi.GetShadersRepository(r)+e,!(n=n||fi))throw new Error("loadFileInjection is not defined");n(a+"."+t.toLowerCase()+".fx",s)}class $i{static get ShadersRepository(){return Bi.ShadersRepository}static set ShadersRepository(e){Bi.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new K),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,s=null,r,n=null,o=null,a=null,l=null,h,c="",u=di.GLSL){this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new K,this.onErrorObservable=new K,this._onBindObservable=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=c;const d=this._key.replace(/\r/g,"").replace(/\n/g,"|");let _;if(t.attributes){const e=t;if(this._engine=i,this._attributesNames=e.attributes,this._uniformsNames=e.uniformsNames.concat(e.samplers),this._samplerList=e.samplers.slice(),this.defines=e.defines,this.onError=e.onError,this.onCompiled=e.onCompiled,this._fallbacks=e.fallbacks,this._indexParameters=e.indexParameters,this._transformFeedbackVaryings=e.transformFeedbackVaryings||null,this._multiTarget=!!e.multiTarget,this._shaderLanguage=e.shaderLanguage??di.GLSL,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t{if(c[0]&&c[1]){e.isFragment=!0;const[a,l]=c;Ai(l,e,((n,l)=>{o&&(o._fragmentSourceCodeBeforeMigration=l),i&&(n=i("fragment",n));const h=Pi(a,n,e);e=null;const c=function(e,t,i,s){if(i){const r=i.vertexElement||i.vertex||i.spectorName||i,n=i.fragmentElement||i.fragment||i.spectorName||i;return{vertexSourceCode:(s===di.WGSL?"//":"")+"#define SHADER_NAME vertex:"+r+"\n"+e,fragmentSourceCode:(s===di.WGSL?"//":"")+"#define SHADER_NAME fragment:"+n+"\n"+t}}return{vertexSourceCode:e,fragmentSourceCode:t}}(h.vertexCode,h.fragmentCode,t,r);s?.(c.vertexSourceCode,c.fragmentSourceCode)}),n)}};Ki(a,"Vertex","",(t=>{Ei(e),Ai(t,e,((e,s)=>{o&&(o._rawVertexSourceCode=t,o._vertexSourceCodeBeforeMigration=s),i&&(e=i("vertex",e)),c[0]=e,u()}),n)}),r),Ki(l,"Fragment","Pixel",(e=>{o&&(o._rawFragmentSourceCode=e),c[1]=e,u()}),r)}({defines:this.defines.split("\n"),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:e??this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Bi.GetShadersRepository(this._shaderLanguage),includesShadersStore:Bi.GetIncludesShadersStore(this._shaderLanguage),version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:this._processCodeAfterIncludes},this.name,this._processFinalCode,((e,i)=>{this._vertexSourceCode=e,this._fragmentSourceCode=i,this._prepareEffect(t)}),this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getAttributesNames(){return this._attributesNames}getAttributeLocation(e){return this._attributes[e]}getAttributeLocationByName(e){return this._attributeLocationByName[e]}getAttributesCount(){return this._attributes.length}getUniformIndex(e){return this._uniformsNames.indexOf(e)}getUniform(e){return this._uniforms[e]}getSamplers(){return this._samplerList}getUniformNames(){return this._uniformsNames}getUniformBuffersNames(){return this._uniformBuffersNamesList}getIndexParameters(){return this._indexParameters}getCompilationError(){return this._compilationError}allFallbacksProcessed(){return this._allFallbacksProcessed}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}this._isDisposed||setTimeout((()=>{this._checkIsReady(e)}),16)}get vertexSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:this._pipelineContext?._getVertexShaderCode()??this._vertexSourceCode}get fragmentSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:this._pipelineContext?._getFragmentShaderCode()??this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}getPipelineGenerationOptions(){return{platformName:this._engine.shaderPlatformName,shaderLanguage:this._shaderLanguage,shaderNameOrContent:this.name,key:this._key,defines:this.defines.split("\n"),addGlobalDefines:!1,extendedProcessingOptions:{indexParameters:this._indexParameters,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,supportsUniformBuffers:this._engine.supportsUniformBuffers},extendedCreatePipelineOptions:{transformFeedbackVaryings:this._transformFeedbackVaryings,createAsRaw:!(!this._vertexSourceCodeOverride||!this._fragmentSourceCodeOverride)}}}_rebuildProgram(e,t,i,s){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{s&&s(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;t{try{const r=e.existingPipelineContext||t(e.shaderProcessingContext);return r._name=e.name,e.name&&e.context&&(Gi(e.context).cachedPipelines[e.name]=r),i(r,e.vertex,e.fragment,!!e.createAsRaw,"","",e.rebuildRebind,e.defines,e.transformFeedbackVaryings,""),s(r,(()=>{e.onRenderingStateCompiled?.(r)})),r}catch(e){throw Ne.Error("Error compiling effect"),e}})({existingPipelineContext:e?t:null,vertex:r,fragment:n,context:"WEBGL2"===o.shaderPlatformName?o._gl:void 0,rebuildRebind:(e,t,i,s)=>this._rebuildProgram(e,t,i,s),defines:s,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:i,parallelShaderCompile:o._caps.parallelShaderCompile,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:i=>{t&&!e&&this._engine._deletePipelineContext(t),i&&this._onRenderingStateCompiled(i)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContext.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t,i){const s=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let r=null;if(t&&e){const n=t.match(s);if(n&&2===n.length){const t=parseInt(n[1]),s=e.split("\n",-1);s.length>=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${s[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){this._compilationError=e.message;const i=this._attributesNames,s=this._fallbacks;if(Ne.Error("Unable to compile effect:"),Ne.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),Ne.Error("Attributes: "+i.map((function(e){return" "+e}))),Ne.Error("Defines:\n"+this.defines),$i.LogShaderCodeOnCompilationError){let e=null,t=null,i=null;this._pipelineContext?._getVertexShaderCode()&&([i,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),i&&(Ne.Error("Vertex code:"),Ne.Error(i))),this._pipelineContext?._getFragmentShaderCode()&&([i,t]=this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(),this._compilationError,!0),i&&(Ne.Error("Fragment code:"),Ne.Error(i))),e&&Ne.Error(e),t&&Ne.Error(t)}Ne.Error("Error: "+this._compilationError);const r=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,r()),s?(this._pipelineContext=null,s.hasMoreFallbacks?(this._allFallbacksProcessed=!1,Ne.Error("Trying next fallback."),this.defines=s.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,r(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||r())}get isSupported(){return""===this._compilationError}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){const s=this._samplerList.indexOf(e);for(let e=1;e{t._swapAndDie(this,!1),this.isReady=e.isReady};return void(e.isAsync?e.proxy.then(t):t(e.proxy))}let e;switch(this.source){case is.Temp:break;case is.Url:return void(e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,(e=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer));case is.Raw:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case is.Raw3D:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case is.Raw2DArray:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case is.Dynamic:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case is.Cube:return void(e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,(()=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer));case is.CubeRaw:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case is.CubeRawRGBD:return;case is.CubePrefiltered:return e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,(e=>{e&&e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension),void(e._sphericalPolynomial=this._sphericalPolynomial);case is.DepthStencil:case is.Depth:}}_swapAndDie(e,t=!0){this._hardwareTexture?.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const i=this._engine.getLoadedTexturesCache();let s=i.indexOf(this);-1!==s&&i.splice(s,1),s=i.indexOf(e),-1===s&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}function rs(e,t){if(kt()){const{requestAnimationFrame:i}=t||window;if("function"==typeof i)return i(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}ss._Counter=0;class ns{get frameId(){return this._frameId}get isWebGPU(){return this._isWebGPU}_getShaderProcessor(e){return this._shaderProcessor}get shaderPlatformName(){return this._shaderPlatformName}_clearEmptyResources(){this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,this._depthCullingState.depthFunc=e?518:515)}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}_getGlobalDefines(e){if(e)return this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return this.isNDCHalfZRange&&(e+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}_rebuildInternalTextures(){const e=this._internalTexturesCache.slice();for(const t of e)t._rebuild()}_rebuildRenderTargetWrappers(){const e=this._renderTargetWrapperCache.slice();for(const t of e)t._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}$i.ResetCache()}_rebuildGraphicsResources(){this.wipeCaches(!0),this._rebuildEffects(),this._rebuildComputeEffects?.(),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){Ne.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout((async()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=r,this._flagContextRestored()}),0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return 0}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){const e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get activeRenderLoops(){return this._activeRenderLoops}stopRenderLoop(e){if(!e)return this._activeRenderLoops.length=0,void this._cancelFrame();const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(0!==this._frameHandler){const e=this._frameHandler;if(this._frameHandler=0,kt()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if("function"==typeof t)return t(e)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(e);return clearTimeout(e)}}beginFrame(){this.onBeginFrameObservable.notifyObservers(this)}endFrame(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e-1?e.substring(T).toLowerCase():""),S=null;y.indexOf("?")>-1&&(y=y.split("?")[0]);for(const e of ns._TextureLoaders)if(e.canLoad(y,_)){S=e;break}s&&s.addPendingData(x),x.url=e,x.generateMipMaps=!t,x.samplingMode=r,x.invertY=i,x._useSRGBBuffer=this._getUseSRGBBuffer(!!f,t),this._doNotHandleContextLost||(x._buffer=h);let C=null;n&&!c&&(C=x.onLoadedObservable.add(n)),c||this._internalTexturesCache.push(x);const E=(i,c)=>{s&&s.removePendingData(x),e===b?(C&&x.onLoadedObservable.remove(C),re.UseFallbackTexture&&e!==re.FallbackTexture&&this._createTextureBase(re.FallbackTexture,t,x.invertY,s,r,null,o,a,l,h,x),i=(i||"Unknown error")+(re.UseFallbackTexture?" - Fallback texture was used":""),x.onErrorObservable.notifyObservers({message:i,exception:c}),o&&o(i,c)):(Ne.Warn(`Failed to load ${e}, falling back to ${b}`),this._createTextureBase(b,t,x.invertY,s,r,n,o,a,l,h,x,u,d,_,p,f))};if(S){const t=e=>{S.loadData(e,x,((e,t,i,n,o,l)=>{l?E("TextureLoader failed to load data"):a(x,y,s,{width:e,height:t},x.invertY,!i,n,(()=>(o(),!1)),r)}),p)};h?h instanceof ArrayBuffer?t(new Uint8Array(h)):ArrayBuffer.isView(h)?t(h):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,s?s.offlineProvider:void 0,!0,((e,t)=>{E("Unable to load "+(e&&e.responseURL,t))}))}else{const i=e=>{g&&!this._doNotHandleContextLost&&(x._buffer=e),a(x,y,s,e,x.invertY,t,!1,l,r)};!m||v?h&&("string"==typeof h.decoding||h.close)?i(h):ns._FileToolsLoadImage(e||"",i,E,s?s.offlineProvider:null,_,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof h||h instanceof ArrayBuffer||ArrayBuffer.isView(h)||h instanceof Blob?ns._FileToolsLoadImage(h,i,E,s?s.offlineProvider:null,_,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):h&&i(h)}return x}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuildAfterContextLost()}get _shouldUseHighPrecisionShader(){return!(!this._caps.highPrecisionShaderSupported||!this._highPrecisionShadersAllowed)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:Ut()?document:null}getLoadedTexturesCache(){return this._internalTexturesCache}clearInternalTexturesCache(){this._internalTexturesCache.length=0}getCaps(){return this._caps}resetTextureCache(){for(const e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}get name(){return this._name}set name(e){this._name=e}static get NpmPackage(){return"babylonjs@7.9.0"}static get Version(){return"7.9.0"}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get isStencilEnable(){return this._isStencilEnable}getCreationOptions(){return this._creationOptions}constructor(e,t,i){this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new qi,this._stencilStateComposer=new Zi,this._stencilState=new Ji,this._alphaState=new es,this._alphaMode=1,this._alphaEquation=0,this._activeRequests=[],this._badOS=!1,this._badDesktopOS=!1,this._compatibilityMode=!0,this._internalTexturesCache=new Array,this._currentRenderTarget=null,this._boundTexturesCache={},this._activeChannel=0,this._currentTextureChannel=-1,this._viewportCached={x:0,y:0,z:0,w:0},this._isWebGPU=!1,this.onCanvasBlurObservable=new K,this.onCanvasFocusObservable=new K,this.onNewSceneAddedObservable=new K,this.onResizeObservable=new K,this.onCanvasPointerOutObservable=new K,this.disablePerformanceMonitorInBackground=!1,this.disableVertexArrayObjects=!1,this._frameId=0,this.hostInformation={isMobile:!1},this.isFullscreen=!1,this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.currentRenderPassId=0,this.isPointerLock=!1,this.postProcesses=[],this.canvasTabIndex=1,this._contextWasLost=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this._renderTargetWrapperCache=new Array,this._compiledEffects={},this._isDisposed=!1,this.scenes=[],this._virtualScenes=new Array,this.onBeforeTextureInitObservable=new K,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new K,this.onAfterShaderCompilationObservable=new K,this.onBeginFrameObservable=new K,this.onEndFrameObservable=new K,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new K,this.onContextRestoredObservable=new K,this._name="",this.premultipliedAlpha=!0,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._doNotHandleContextLost=!1,this.cullBackFaces=null,this._renderPassNames=["main"],this._fps=60,this._deltaTime=0,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this.onDisposeObservable=new K,re.Instances.push(this),this.startTime=Wt.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,se.SetMatrixPrecision(!!t.useHighPrecisionMatrix),Vt()&&navigator.userAgent&&(this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),this.adaptToDeviceRatio=i??!1,t.antialias=e??t.antialias,t.deterministicLockstep=t.deterministicLockstep??!1,t.lockstepMaxSteps=t.lockstepMaxSteps??4,t.timeStep=t.timeStep??1/60,t.audioEngine=t.audioEngine??!0,t.stencil=t.stencil??!0,this._audioContext=t.audioEngineOptions?.audioContext??null,this._audioDestination=t.audioEngineOptions?.audioDestination??null,this.premultipliedAlpha=t.premultipliedAlpha??!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=t.useExactSrgbConversions??!1;const s=kt()&&window.devicePixelRatio||1,r=t.limitDeviceRatio||s;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(r,s):1,this._lastDevicePixelRatio=s,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const e=kt()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if(kt()&&Ut())if(this._renderingCanvas){const e=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||e.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||e.height||this._renderingCanvas.height||100}else t=window.innerWidth,i=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){if(!this._renderingCanvas)return!1;if(e|=0,t|=0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t)return!1;if(this._renderingCanvas.width=e,this._renderingCanvas.height=t,this.scenes){for(let e=0;e{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&Ut()&&"ontouchend"in document},this._checkForMobile(),kt()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){this._drawCalls?.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}_createImageBitmapFromSource(e,t){throw new Error("createImageBitmapFromSource is not implemented")}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){throw new Error("resizeImageBitmap is not implemented")}getFontOffset(e){throw new Error("getFontOffset is not implemented")}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return ns._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,s,r,n){throw xt("FileTools")}_loadFile(e,t,i,s,r,n){const o=fi(e,t,i,s,r,n);return this._activeRequests.push(o),o.onCompleteObservable.add((()=>{const e=this._activeRequests.indexOf(o);-1!==e&&this._activeRequests.splice(e,1)})),o}static _FileToolsLoadFile(e,t,i,s,r,n){if(_i.loadFile)return _i.loadFile(e,t,i,s,r,n);throw xt("FileTools")}dispose(){for(this.hideLoadingUI(),this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();this.releaseComputeEffects?.(),$i.ResetCache();for(const e of this._activeRequests)e.abort();this._boundRenderFunction=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onNewSceneAddedObservable.clear(),kt()&&window.removeEventListener("resize",this._checkForMobile);const e=re.Instances.indexOf(this);e>=0&&re.Instances.splice(e,1),re.Instances.length||(re.OnEnginesDisposedObservable.notifyObservers(this),re.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw xt("LoadingScreen")}}ns._TextureLoaders=[],ns._RenderPassIdCounter=0,ns._RescalePostProcessFactory=null;const os=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class as extends jt{constructor(e,t){super(e,Qt.LoadFileError),this.name="LoadFileError",Yt._setPrototypeOf(this,as.prototype),t instanceof Pt?this.request=t:this.file=t}}class ls extends jt{constructor(e,t){super(e,Qt.RequestFileError),this.request=t,this.name="RequestFileError",Yt._setPrototypeOf(this,ls.prototype)}}class hs extends jt{constructor(e,t){super(e,Qt.ReadFileError),this.file=t,this.name="ReadFileError",Yt._setPrototypeOf(this,hs.prototype)}}const cs={DefaultRetryStrategy:Xt.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e,CleanUrl:e=>e.replace(/#/gm,"%23")},us=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&cs.CorsBehavior)if("string"==typeof cs.CorsBehavior||cs.CorsBehavior instanceof String)t.crossOrigin=cs.CorsBehavior;else{const i=cs.CorsBehavior(e);i&&(t.crossOrigin=i)}},ds=(e,t,i,s,r="",n)=>{const o=re.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!o?._features.forceBitmapOverHTMLImageElement)return i("LoadImage is only supported in web or BabylonNative environments."),null;let a,l=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(a=URL.createObjectURL(new Blob([e],{type:r})),l=!0):a=`data:${r};base64,`+Zt(e):e instanceof Blob?(a=URL.createObjectURL(e),l=!0):(a=cs.CleanUrl(e),a=cs.PreprocessUrl(e));const h=t=>{if(i){const s=a||e.toString();i(`Error while trying to load image: ${0===s.indexOf("http")||s.length<=128?s:s.slice(0,128)+"..."}`,t)}};if(o?._features.forceBitmapOverHTMLImageElement)return ps(a,(s=>{o.createImageBitmap(new Blob([s],{type:r}),{premultiplyAlpha:"none",...n}).then((e=>{t(e),l&&URL.revokeObjectURL(a)})).catch((t=>{i&&i("Error while trying to load image: "+e,t)}))}),void 0,s||void 0,!0,((e,t)=>{h(t)})),null;const c=new Image;us(a,c);const u=[],d=()=>{u.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),u.length=0};u.push({target:c,name:"load",handler:()=>{d(),t(c),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:c,name:"error",handler:e=>{d(),h(e),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==c.src)return;d();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);re.UseFallbackTexture=!1,h(t),l&&c.src&&URL.revokeObjectURL(c.src),c.src=""}}),u.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const _="blob:"===a.substring(0,5),p="data:"===a.substring(0,5),f=()=>{_||p||!Pt.IsCustomRequestAvailable?c.src=a:ps(a,((e,t,i)=>{const s=new Blob([e],{type:!r&&i?i:r}),n=URL.createObjectURL(s);l=!0,c.src=n}),void 0,s||void 0,!0,((e,t)=>{h(t)}))};if(!_&&!p&&s&&s.enableTexturesOffline)s.open((()=>{s&&s.loadImage(a,c)}),f);else{if(-1!==a.indexOf("file:")){const e=decodeURIComponent(a.substring(5).toLowerCase());if(Ht.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(Ht.FilesToLoad[e])}catch(i){t=URL.createObjectURL(Ht.FilesToLoad[e])}c.src=t,l=!0}catch(e){c.src=""}return c}}f()}return c},_s=(e,t,i,s,r)=>{const n=new FileReader,o={onCompleteObservable:new K,abort:()=>n.abort()};return n.onloadend=()=>o.onCompleteObservable.notifyObservers(o),r&&(n.onerror=()=>{r(new hs(`Unable to read ${e.name}`,e))}),n.onload=e=>{t(e.target.result)},i&&(n.onprogress=i),s?n.readAsArrayBuffer(e):n.readAsText(e),o},ps=(e,t,i,s,r,n,o)=>{if(e.name)return _s(e,t,i,r,n?e=>{n(void 0,e)}:void 0);const a=e;if(-1!==a.indexOf("file:")){let e=decodeURIComponent(a.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const s=Ht.FilesToLoad[e];if(s)return _s(s,t,i,r,n?e=>n(void 0,new as(e.message,e.file)):void 0)}const{match:l,type:h}=vs(a);if(l){const e={onCompleteObservable:new K,abort:()=>()=>{}};try{const e=r?xs(a):bs(a);t(e,void 0,h)}catch(e){n?n(void 0,e):Ne.Error(e.message||"Failed to parse the Data URL")}return Li.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return fs(a,((e,i)=>{t(e,i?.responseURL,i?.getResponseHeader("content-type"))}),i,s,r,n?e=>{n(e.request,new as(e.message,e.request))}:void 0,o)},fs=(e,t,i,s,r,n,o)=>{e=cs.CleanUrl(e),e=cs.PreprocessUrl(e);const a=cs.BaseUrl+e;let l=!1;const h={onCompleteObservable:new K,abort:()=>l=!0},c=()=>{let e,s=new Pt,c=null;const u=()=>{s&&(i&&s.removeEventListener("progress",i),e&&s.removeEventListener("readystatechange",e),s.removeEventListener("loadend",d))};let d=()=>{u(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),i=void 0,e=null,d=null,n=void 0,o=void 0,t=void 0};h.abort=()=>{l=!0,d&&d(),s&&s.readyState!==(XMLHttpRequest.DONE||4)&&s.abort(),null!==c&&(clearTimeout(c),c=null),s=null};const _=e=>{const t=e.message||"Unknown error";n&&s?n(new ls(t,s)):Ne.Error(t)},p=h=>{if(s){if(s.open("GET",a),o)try{o(s)}catch(e){return void _(e)}r&&(s.responseType="arraybuffer"),i&&s.addEventListener("progress",i),d&&s.addEventListener("loadend",d),e=()=>{if(!l&&s&&s.readyState===(XMLHttpRequest.DONE||4)){if(e&&s.removeEventListener("readystatechange",e),s.status>=200&&s.status<300||0===s.status&&(!kt()||ms())){try{t&&t(r?s.response:s.responseText,s)}catch(e){_(e)}return}const i=cs.DefaultRetryStrategy;if(i){const e=i(a,s,h);if(-1!==e)return u(),s=new Pt,void(c=setTimeout((()=>p(h+1)),e))}const o=new ls("Error status: "+s.status+" "+s.statusText+" - Unable to load "+a,s);n&&n(o)}},s.addEventListener("readystatechange",e),s.send()}};p(0)};if(s&&s.enableSceneOffline){const o=e=>{e&&e.status>400?n&&n(e):c()},a=()=>{s&&s.loadFile(cs.BaseUrl+e,(e=>{!l&&t&&t(e),h.onCompleteObservable.notifyObservers(h)}),i?e=>{!l&&i&&i(e)}:void 0,o,r)};s.open(a,o)}else c();return h},ms=()=>"undefined"!=typeof location&&"file:"===location.protocol,gs=e=>os.test(e),vs=e=>{const t=os.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function xs(e){return ei(e.split(",")[1])}const bs=e=>Jt(e.split(",")[1]);let Ts;ns._FileToolsLoadImage=ds,_i.loadFile=ps,Fi.loadFile=ps;const ys=(e,t,i,s,r,n,o,a,l,h)=>{Ts={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:s,IsFileURL:r,LoadFile:n,LoadImage:o,ReadFile:a,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(Ts,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(Ts,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(Ts,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(Ts,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})};ys(xs,bs,cs,gs,ms,ps,ds,_s,fs,us);class Ss{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=W(e);if(t)return t;Ne.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let e=0,t=i.length;e{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}Ss.RegisteredExternalClasses={};const Es={RandomId:Cs};function As(e){let t=1;do{t*=2}while(te-i?i:t}function Rs(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}function Ms(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}function Os(e,t,i=2){let s;switch(i){case 1:s=Ms(e);break;case 2:s=Is(e);break;default:s=Rs(e)}return Math.min(s,t)}class Ds{static get BaseUrl(){return cs.BaseUrl}static set BaseUrl(e){cs.BaseUrl=e}static get CleanUrl(){return cs.CleanUrl}static set CleanUrl(e){cs.CleanUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||-1!==e.indexOf("://")&&-1!==e.indexOf(".")&&-1!==e.indexOf("/")&&!(e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://"){ps(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{s(t)}))}))}static GetBabylonScriptURL(e,t){if(!e)return"";if(Ds.ScriptBaseUrl&&e.startsWith(Ds._DefaultCdnUrl)){const t="/"===Ds.ScriptBaseUrl[Ds.ScriptBaseUrl.length-1]?Ds.ScriptBaseUrl.substring(0,Ds.ScriptBaseUrl.length-1):Ds.ScriptBaseUrl;e=e.replace(Ds._DefaultCdnUrl,t)}return e=Ds.ScriptPreprocessUrl(e),t&&(e=Ds.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=Ds.GetBabylonScriptURL(e),Ds.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=Ds.GetBabylonScriptURL(e),Ds.LoadScriptAsync(e)}static LoadScript(e,t,i,s){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){i?.(`Unable to load script '${e}' in worker`,t)}return}if(!kt())return void i?.(`Cannot load script '${e}' outside of a window or a worker`);const r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("src",e),s&&(n.id=s),n.onload=()=>{t&&t()},n.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},r.appendChild(n)}static LoadScriptAsync(e,t){return new Promise(((i,s)=>{this.LoadScript(e,(()=>{i()}),((e,t)=>{s(t||new Error(e))}),t)}))}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new K,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,s,r){return _s(e,t,i,s,r)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,s){Ye.DeepCopy(e,t,i,s)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{const s=atob(this.toDataURL(t,i).split(",")[1]),r=s.length,n=new Uint8Array(r);for(let e=0;et(e))):e.toBlob((function(e){t(e)}),i,s)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const e=new Date;t="screenshot_"+(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2)+".png"}Ds.Download(e,t)}else if(e&&"undefined"!=typeof URL){const t=URL.createObjectURL(e),i=window.open("");if(!i)return;const s=i.document.createElement("img");s.onload=function(){URL.revokeObjectURL(t)},s.src=t,i.document.body.appendChild(s)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,r){if("string"!=typeof s&&t){if(t){if(Ds._IsOffScreenCanvas(e))return void e.convertToBlob({type:i,quality:r}).then((e=>{const i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{const e=i.result;t(e)}}));const s=e.toDataURL(i,r);t(s)}}else this.ToBlob(e,(function(e){e&&Ds.DownloadBlob(e,s),t&&t("")}),i,r)}static Download(e,t){if("undefined"==typeof URL)return;const i=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.style.display="none",s.href=i,s.download=t,s.addEventListener("click",(()=>{s.parentElement&&s.parentElement.removeChild(s)})),s.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,s,r="image/png",n=!1,o){throw xt("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",r){throw xt("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,o=!1,a,l=!1,h=!1,c=!0,u){throw xt("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,o,a=!1,l=!1,h=!0,c){throw xt("ScreenshotTools")}static RandomId(){return Cs()}static IsBase64(e){return gs(e)}static DecodeBase64(e){return xs(e)}static get errorsCount(){return Ne.errorsCount}static Log(e){Ne.Log(e)}static Warn(e){Ne.Warn(e)}static Error(e){Ne.Error(e)}static get LogCache(){return Ne.LogCache}static ClearLogCache(){Ne.ClearLogCache()}static set LogLevels(e){Ne.LogLevels=e}static set PerformanceLogLevel(e){return(e&Ds.PerformanceUserMarkLogLevel)===Ds.PerformanceUserMarkLogLevel?(Ds.StartPerformanceCounter=Ds._StartUserMark,void(Ds.EndPerformanceCounter=Ds._EndUserMark)):(e&Ds.PerformanceConsoleLogLevel)===Ds.PerformanceConsoleLogLevel?(Ds.StartPerformanceCounter=Ds._StartPerformanceConsole,void(Ds.EndPerformanceCounter=Ds._EndPerformanceConsole)):(Ds.StartPerformanceCounter=Ds._StartPerformanceCounterDisabled,void(Ds.EndPerformanceCounter=Ds._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Ds._Performance){if(!kt())return;Ds._Performance=window.performance}t&&Ds._Performance.mark&&Ds._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&Ds._Performance.mark&&(Ds._Performance.mark(e+"-End"),Ds._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Ds._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Ds._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return Wt.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,s=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,s=r.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=s?s+".":"")+i:null}static DelayAsync(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}static IsSafari(){return!!Vt()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}function ws(e,t){return i=>{i.__bjsclassName__=e,i.__bjsmoduleName__=null!=t?t:null}}Ds.UseCustomRequestHeaders=!1,Ds.CustomRequestHeaders=Pt.CustomRequestHeaders,Ds.GetDOMTextContent=Gt,Ds._DefaultCdnUrl="https://cdn.babylonjs.com",Ds.GetAbsoluteUrl="object"==typeof document?e=>{const t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},Ds.NoneLogLevel=Ne.NoneLogLevel,Ds.MessageLogLevel=Ne.MessageLogLevel,Ds.WarningLogLevel=Ne.WarningLogLevel,Ds.ErrorLogLevel=Ne.ErrorLogLevel,Ds.AllLogLevel=Ne.AllLogLevel,Ds.IsWindowObjectExist=kt,Ds.PerformanceNoneLogLevel=0,Ds.PerformanceUserMarkLogLevel=1,Ds.PerformanceConsoleLogLevel=2,Ds.StartPerformanceCounter=Ds._StartPerformanceCounterDisabled,Ds.EndPerformanceCounter=Ds._EndPerformanceCounterDisabled;class Ns{constructor(e,t,i,s=0){this.iterations=e,this.index=s-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{r&&r()?s.breakLoop():setTimeout((()=>{for(let n=0;n=e)break;if(i(o),r&&r()){s.breakLoop();break}}s.executeNext()}),n)}),s)}}Ds.Mix=Ps,Ds.IsExponentOfTwo=As,re.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";class Fs{constructor(e){this.length=0,this.data=new Array(e),this._id=Fs._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}Fs._GlobalId=0;class Ls extends Fs{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return!(e.__smartArrayFlags&&e.__smartArrayFlags[this._id]===this._duplicateId||(this.push(e),0))}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;tthis.add(e,t)))}get(e){const t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let i=this.get(e);return void 0!==i||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return void 0!==i?i:(this.add(e,t),t)}contains(e){return void 0!==this._data[e]}add(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)}set(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null}remove(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data)e(t,this._data[t])}first(e){for(const t in this._data){const i=e(t,this._data[t]);if(i)return i}return null}}function ks(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class Vs{constructor(){this._dirty=!0,this._tempColor=new Ae(0,0,0,0),this._globalCurve=new Ae(0,0,0,0),this._highlightsCurve=new Ae(0,0,0,0),this._midtonesCurve=new Ae(0,0,0,0),this._shadowsCurve=new Ae(0,0,0,0),this._positiveCurve=new Ae(0,0,0,0),this._negativeCurve=new Ae(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",s="vCameraColorCurveNeutral",r="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(s,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(r,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,s,r){null!=e&&(e=Vs._Clamp(e,0,360),t=Vs._Clamp(t,-100,100),i=Vs._Clamp(i,-100,100),s=Vs._Clamp(s,-100,100),t=Vs._ApplyColorGradingSliderNonlinear(t),t*=.5,s=Vs._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),Vs._FromHSBToRef(e,t,50+.25*s,r),r.scaleToRef(2,r),r.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,s){let r=Vs._Clamp(e,0,360);const n=Vs._Clamp(t/100,0,1),o=Vs._Clamp(i/100,0,1);if(0===n)s.r=o,s.g=o,s.b=o;else{r/=60;const e=Math.floor(r),t=r-e,i=o*(1-n),a=o*(1-n*t),l=o*(1-n*(1-t));switch(e){case 0:s.r=o,s.g=l,s.b=i;break;case 1:s.r=a,s.g=o,s.b=i;break;case 2:s.r=i,s.g=o,s.b=l;break;case 3:s.r=i,s.g=a,s.b=o;break;case 4:s.r=l,s.g=i,s.b=o;break;default:s.r=o,s.g=i,s.b=a}}s.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return St.Clone((()=>new Vs),this)}serialize(){return St.Serialize(this)}static Parse(e){return St.Parse((()=>new Vs),e,null,null)}}function Us(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&ks(e),t.DITHER&&e.push("ditherIntensity")}function Gs(e,t){t.COLORGRADING&&e.push("txColorTransform")}Vs.PrepareUniforms=ks,Ze([rt()],Vs.prototype,"_globalHue",void 0),Ze([rt()],Vs.prototype,"_globalDensity",void 0),Ze([rt()],Vs.prototype,"_globalSaturation",void 0),Ze([rt()],Vs.prototype,"_globalExposure",void 0),Ze([rt()],Vs.prototype,"_highlightsHue",void 0),Ze([rt()],Vs.prototype,"_highlightsDensity",void 0),Ze([rt()],Vs.prototype,"_highlightsSaturation",void 0),Ze([rt()],Vs.prototype,"_highlightsExposure",void 0),Ze([rt()],Vs.prototype,"_midtonesHue",void 0),Ze([rt()],Vs.prototype,"_midtonesDensity",void 0),Ze([rt()],Vs.prototype,"_midtonesSaturation",void 0),Ze([rt()],Vs.prototype,"_midtonesExposure",void 0),St._ColorCurvesParser=Vs.Parse;class zs{constructor(){this.colorCurves=new Vs,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=zs.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new Ae(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=zs.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new K}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled)return e.VIGNETTE=!1,e.TONEMAPPING=0,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,void(e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===zs._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,this._toneMappingEnabled)switch(this._toneMappingType){case zs.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case zs.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1}else e.TONEMAPPING=0;e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||!!e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&Vs.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),s=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,s),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=null!=t?t:s/i;let n=Math.tan(.5*this.vignetteCameraFov),o=n*r;const a=Math.sqrt(o*n);o=Ps(o,a,this.vignetteStretch),n=Ps(n,a,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,n,-o*this.vignetteCenterX,-n*this.vignetteCenterY);const l=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,l)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return St.Clone((()=>new zs),this)}serialize(){return St.Serialize(this)}static Parse(e){const t=St.Parse((()=>new zs),e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}function Ws(e){return void 0===e.getPipelineContext}zs.TONEMAPPING_STANDARD=0,zs.TONEMAPPING_ACES=1,zs.TONEMAPPING_KHR_PBR_NEUTRAL=2,zs.PrepareUniforms=Us,zs.PrepareSamplers=Gs,zs._VIGNETTEMODE_MULTIPLY=0,zs._VIGNETTEMODE_OPAQUE=1,Ze([ut()],zs.prototype,"colorCurves",void 0),Ze([rt()],zs.prototype,"_colorCurvesEnabled",void 0),Ze([nt("colorGradingTexture")],zs.prototype,"_colorGradingTexture",void 0),Ze([rt()],zs.prototype,"_colorGradingEnabled",void 0),Ze([rt()],zs.prototype,"_colorGradingWithGreenDepth",void 0),Ze([rt()],zs.prototype,"_colorGradingBGR",void 0),Ze([rt()],zs.prototype,"_exposure",void 0),Ze([rt()],zs.prototype,"_toneMappingEnabled",void 0),Ze([rt()],zs.prototype,"_toneMappingType",void 0),Ze([rt()],zs.prototype,"_contrast",void 0),Ze([rt()],zs.prototype,"vignetteStretch",void 0),Ze([rt()],zs.prototype,"vignetteCenterX",void 0),Ze([rt()],zs.prototype,"vignetteCenterY",void 0),Ze([rt()],zs.prototype,"vignetteWeight",void 0),Ze([dt()],zs.prototype,"vignetteColor",void 0),Ze([rt()],zs.prototype,"vignetteCameraFov",void 0),Ze([rt()],zs.prototype,"_vignetteBlendMode",void 0),Ze([rt()],zs.prototype,"_vignetteEnabled",void 0),Ze([rt()],zs.prototype,"_ditheringEnabled",void 0),Ze([rt()],zs.prototype,"_ditheringIntensity",void 0),Ze([rt()],zs.prototype,"_skipFinalColorClamp",void 0),Ze([rt()],zs.prototype,"_applyByPostProcess",void 0),Ze([rt()],zs.prototype,"_isEnabled",void 0),St._ImageProcessingConfigurationParser=zs.Parse,z("BABYLON.ImageProcessingConfiguration",zs);class Hs{constructor(){this.shaderLanguage=di.GLSL}postProcessor(e,t,i,s,r){if(r.drawBuffersExtensionDisabled){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}const Xs=/(flat\s)?\s*varying\s*.*/;class Ys{constructor(){this.shaderLanguage=di.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return Xs.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(s||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}class Qs{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=Qs._Counter++}}Qs._Counter=0;class js extends Qs{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class Ks{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){return this._MSAARenderBuffers?.[e]??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}class $s{}class qs extends ns{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return $i.ShadersRepository}static set ShadersRepository(e){$i.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}snapshotRenderingReset(){this.snapshotRendering=!1}constructor(e,t,i,s){if(i=i||{},super(t??i.antialias,i,s),this._name="WebGL",this.forcePOTTextures=!1,this.validateShaderPrograms=!1,this.disableUniformBuffers=!1,this._webGLVersion=1,this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},!e)return;let r=null;if(e.getContext){if(r=e,this._renderingCanvas=r,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();const e=navigator.userAgent;for(const t of qs.ExceptionList){const s=t.key,r=t.targets;if(new RegExp(s).test(e)){if(t.capture&&t.captureConstraint){const i=t.capture,s=t.captureConstraint,r=new RegExp(i).exec(e);if(r&&r.length>0&&parseInt(r[r.length-1])>=s)continue}for(const e of r)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,Ne.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost((()=>this._initGLContext()))},r.addEventListener("webglcontextlost",this._onContextLost,!1),r.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=r.getContext("webgl2",i)||r.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!r)throw new Error("The provided canvas is null or undefined.");try{this._gl=r.getContext("webgl",i)||r.getContext("experimental-webgl",i)}catch(e){throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";const t=this._gl.getContextAttributes();t&&(i.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==i.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e1?new Ys:new Hs;const n=`Babylon.js v${qs.Version}`;Ne.Log(n+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",n);const o=Gi(this._gl);o.validateShaderPrograms=this.validateShaderPrograms,o.parallelShaderCompile=this._caps.parallelShaderCompile}_clearEmptyResources(){this._dummyFramebuffer=null,super._clearEmptyResources()}_getShaderProcessingContext(e){return null}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_initGLContext(){this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||null!==this._gl.getExtension("OES_standard_derivatives"),maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:1!==this._webGLVersion,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=e&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)??0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!(!this._creationOptions||!this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);this._gl.uniformBlockBinding(s,r,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,s,r,n,o){const a=this._currentBufferPointers[t];if(!a)return;let l=!1;a.active?(a.buffer!==e&&(a.buffer=e,l=!0),a.size!==i&&(a.size=i,l=!0),a.type!==s&&(a.type=s,l=!0),a.normalized!==r&&(a.normalized=r,l=!0),a.stride!==n&&(a.stride=n,l=!0),a.offset!==o&&(a.offset=o,l=!0)):(l=!0,a.active=!0,a.index=t,a.size=i,a.type=s,a.normalized=r,a.stride=n,a.offset=o,a.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),s===this._gl.UNSIGNED_INT||s===this._gl.INT?this._gl.vertexAttribIPointer(t,i,s,n,o):this._gl.vertexAttribPointer(t,i,s,r,n,o))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const s=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let r=0;r=0){const t=s[r];let o=null;if(i&&(o=i[t]),o||(o=e[t]),!o)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const a=o.getBuffer();a&&(this._vertexAttribPointer(a,n,o.getSize(),o.type,o.normalized,o.byteStride,o.byteOffset),o.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,o.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(a))))}}}recordVertexArrayObject(e,t,i,s){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,s),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,s,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const t=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let o=0;o=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[o],this._gl.FLOAT,!1,s,n)),n+=4*i[o]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,s){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,s)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t{s?.(),t(e)}}(e,t)}getUniforms(e,t){const i=new Array,s=e;for(let e=0;e1||this.isWebGPU)),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(a=1),1!==o||this._caps.textureFloat||(o=0,Ne.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=this._gl,d=new ss(this,s),_=e.width||e,p=e.height||e,f=e.depth||0,m=e.layers||0,g=this._getSamplingParameters(a,n),v=0!==m?u.TEXTURE_2D_ARRAY:0!==f?u.TEXTURE_3D:u.TEXTURE_2D,x=this._getRGBABufferInternalSizedFormat(o,l,h),b=this._getInternalFormat(l),T=this._getWebGLTextureType(o);return this._bindTextureDirectly(v,d),0!==m?(d.is2DArray=!0,u.texImage3D(v,0,x,_,p,m,0,b,T,null)):0!==f?(d.is3D=!0,u.texImage3D(v,0,x,_,p,f,0,b,T,null)):u.texImage2D(v,0,x,_,p,0,b,T,null),u.texParameteri(v,u.TEXTURE_MAG_FILTER,g.mag),u.texParameteri(v,u.TEXTURE_MIN_FILTER,g.min),u.texParameteri(v,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(v,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(v),this._bindTextureDirectly(v,null),d._useSRGBBuffer=h,d.baseWidth=_,d.baseHeight=p,d.width=_,d.height=p,d.depth=m,d.isReady=!0,d.samples=c,d.generateMipMaps=n,d.samplingMode=a,d.type=o,d.format=l,d.label=r,this._internalTexturesCache.push(d),d}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,_,p){return this._createTextureBase(e,t,i,s,r,n,o,((...e)=>this._prepareWebGLTexture(...e,h)),((e,t,i,r,n,o)=>{const a=this._gl,l=i.width===e&&i.height===t;n._creationFlags=_??0;const h=this._getTexImageParametersForCreateTexture(n.format,n._useSRGBBuffer);if(l)return a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,i),!1;const c=this._caps.maxTextureSize;if(i.width>c||i.height>c||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!(!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,this._workingCanvas),n.width=e,n.height=t,1));{const e=new ss(this,is.Temp);this._bindTextureDirectly(a.TEXTURE_2D,e,!0),a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,i),this._rescaleTexture(e,n,s,h.format,(()=>{this._releaseTexture(e),this._bindTextureDirectly(a.TEXTURE_2D,n,!0),o()}))}return!0}),a,l,h,c,u,d,p)}_getTexImageParametersForCreateTexture(e,t){let i,s;return 1===this.webGLVersion?(i=this._getInternalFormat(e,t),s=i):(i=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(0,e,t)),{internalFormat:s,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,s,r){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const s=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,r.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),t.samplingMode=e}updateTextureDimensions(e,t,i,s=1){}updateTextureWrappingMode(e,t,i=null,s=null){const r=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==s&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(r,null)}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){const a=this._gl;let l=a.TEXTURE_2D;if(e.isCube&&(l=a.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=a.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(l,o,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const o=this._gl,a=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=void 0===r?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=o.TEXTURE_2D;e.isCube&&(c=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);const u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),_=n?e.width:Math.pow(2,Math.max(u-s,0)),p=n?e.height:Math.pow(2,Math.max(d-s,0));o.texImage2D(c,s,h,_,p,0,l,a,t)}updateTextureData(e,t,i,s,r,n,o=0,a=0,l=!1){const h=this._gl,c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,_=h.TEXTURE_2D;e.isCube&&(_=h.TEXTURE_CUBE_MAP_POSITIVE_X+o,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(_,a,i,s,r,n,u,c,t),l&&this._gl.generateMipmap(_),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const r=this._gl,n=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,r){const n=this._gl;if(!n)return;const o=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,o.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,o.min),i||s||n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,r,n,o,a,l,h){const c=this.getCaps().maxTextureSize,u=Math.min(c,this.needPOTTextures?Os(s.width,c):s.width),d=Math.min(c,this.needPOTTextures?Os(s.height,c):s.height),_=this._gl;_&&(e._hardwareTexture?(this._bindTextureDirectly(_.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),e.baseWidth=s.width,e.baseHeight=s.height,e.width=u,e.height=d,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:h??(".jpg"!==t||e._useSRGBBuffer?5:4),a(u,d,s,t,e,(()=>{this._prepareWebGLTextureContinuation(e,i,n,o,l)}))||this._prepareWebGLTextureContinuation(e,i,n,o,l)):i&&i.removePendingData(e))}_setupFramebufferDepthAttachments(e,t,i,s,r=1){const n=this._gl;if(e&&t)return this._createRenderBuffer(i,s,r,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let e=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=n.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,r,e,e,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,r,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,r,n,o=!0){const a=this._gl.createRenderbuffer();return this._updateRenderBuffer(a,e,t,i,s,r,n,o)}_updateRenderBuffer(e,t,i,s,r,n,o,a=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),s>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,s,n,t,i):l.renderbufferStorage(l.RENDERBUFFER,r,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,o,l.RENDERBUFFER,e),a&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture?.underlyingResource),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);-1!==t&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(function(e,t){t.useProgram(e)}(e,this._gl),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t-1;if(i&&n&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw Ne.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,t?._hardwareTexture?.underlyingResource??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(r=!0,this._activateCurrentTexture());return n&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),r}_bindTexture(e,t,i){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;const s=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(s,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,s=!1,r=""){if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;const i=t.getInternalTexture();i&&(i._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;n=s?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&n&&(n._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),o=!1),this._activeChannel=e;const a=this._getTextureTarget(n);if(o&&this._bindTextureDirectly(a,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(a,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,s){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},kt()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&this._gl.getExtension("WEBGL_lose_context")?.loseContext(),function(e){Vi.delete(e)}(this._gl)}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const s=t.createTexture();t.bindTexture(t.TEXTURE_2D,s),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const n=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&n===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);const e=t.RGBA,s=t.UNSIGNED_BYTE,r=new Uint8Array(4);t.readPixels(0,0,1,1,e,s,r),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(r),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:i=this._gl.RED;break;case 7:i=this._gl.RG;break;case 4:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,s,r=!0,n=!0){const o=r?4:3,a=r?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(s*i*o);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,a,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{const e=ns._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{const e=ns._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}}qs._TempClearColorUint32=new Uint32Array(4),qs._TempClearColorInt32=new Int32Array(4),qs.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],qs.CollisionsEpsilon=.001,qs._ConcatenateShader=pi,qs._IsSupported=null,qs._HasMajorPerformanceCaveat=null,qs.CeilingPOT=Rs,qs.FloorPOT=Ms,qs.NearestPOT=Is,qs.GetExponentOfTwo=Os,qs.QueueNewFrame=rs,qs.prototype.createUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create uniform buffer");const s=new js(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},qs.prototype.createDynamicUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create dynamic uniform buffer");const s=new js(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},qs.prototype.updateUniformBuffer=function(e,t,i,s){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===s?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+s)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+s)),this.bindUniformBuffer(null)},qs.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},qs.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},qs.prototype.bindUniformBlock=function(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);4294967295!==r&&this._gl.uniformBlockBinding(s,r,i)};class Zs{constructor(e,t,i,s,r=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,this._dynamic=i,this._name=s??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){const e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const i=this._uniformLocationPointer-e;for(let e=0;e0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t?t*=i:t=t*i+(4-t)*i,s=[];for(let e=0;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(Zs._UpdatedUbosInFrame[this._name]||(Zs._UpdatedUbosInFrame[this._name]=0),Zs._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.trackUbosInFrame;else this.create()}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let s=this._uniformLocations[e];if(void 0===s){if(this._buffer)return void Ne.Error("Cannot add an uniform after UBO has been created. uniformName="+e);this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e0)return void(this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label));Ne.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,s=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,s?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),this._data=0===t&&void 0===i?e:null)}_increaseReferences(){this._buffer&&(this._isAlreadyOwned?this._buffer.references++:this._isAlreadyOwned=!0)}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class er{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,s,r,n,o,a,l,h,c=!1,u=!1,d=1,_=!1){this._isDisposed=!1;let p=!1;if(this.engine=e,"object"==typeof s&&null!==s?(p=s.updatable??!1,r=s.postponeInternalCreation,n=s.stride,o=s.instanced,a=s.offset,l=s.size,h=s.type,c=s.normalized??!1,u=s.useBytes??!1,d=s.divisor??1,_=s.takeBufferOwnership??!1,this._label=s.label):p=!!s,t instanceof Js?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new Js(e,t,p,n,r,o,u,d,this._label),this._ownsBuffer=!0),this.uniqueId=er._Counter++,this._kind=i,void 0===h){const e=this.getData();this.type=e?er.GetDataType(e):er.FLOAT}else this.type=h;const f=er.GetTypeByteLength(this.type);u?(this._size=l||(n?n/f:er.DeduceStride(i)),this.byteStride=n||this._buffer.byteStride||this._size*f,this.byteOffset=a||0):(this._size=l||n||er.DeduceStride(i),this.byteStride=n?n*f:this._buffer.byteStride||this._size*f,this.byteOffset=(a||0)*f),this.normalized=c,this._instanced=void 0!==o&&o,this._instanceDivisor=o?d:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120|0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){this._buffer?._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?er.GetFloatData(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/er.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/er.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*er.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){er.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case er.UVKind:case er.UV2Kind:case er.UV3Kind:case er.UV4Kind:case er.UV5Kind:case er.UV6Kind:return 2;case er.NormalKind:case er.PositionKind:return 3;case er.ColorKind:case er.ColorInstanceKind:case er.MatricesIndicesKind:case er.MatricesIndicesExtraKind:case er.MatricesWeightsKind:case er.MatricesWeightsExtraKind:case er.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?er.BYTE:e instanceof Uint8Array?er.UNSIGNED_BYTE:e instanceof Int16Array?er.SHORT:e instanceof Uint16Array?er.UNSIGNED_SHORT:e instanceof Int32Array?er.INT:e instanceof Uint32Array?er.UNSIGNED_INT:er.FLOAT}static GetTypeByteLength(e){switch(e){case er.BYTE:case er.UNSIGNED_BYTE:return 1;case er.SHORT:case er.UNSIGNED_SHORT:return 2;case er.INT:case er.UNSIGNED_INT:case er.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,s,r,n,o,a){if(e instanceof Array){let r=t/4;const o=i/4;for(let t=0;to[t]=e)),o}if(!(e instanceof Array||e instanceof Float32Array)||0!==s||e.length!==h){if(e instanceof Array){const t=s/4;return e.slice(t,t+h)}if(e instanceof ArrayBuffer)return new Float32Array(e,s,h);{let t=e.byteOffset+s;if(a){const i=new Float32Array(h),s=new Float32Array(e.buffer,t,h);return i.set(s),i}const i=t%4;return i&&(t=Math.max(0,t-i)),new Float32Array(e.buffer,t,h)}}return a?e.slice():e}}er._Counter=0,er.BYTE=5120,er.UNSIGNED_BYTE=5121,er.SHORT=5122,er.UNSIGNED_SHORT=5123,er.INT=5124,er.UNSIGNED_INT=5125,er.FLOAT=5126,er.PositionKind="position",er.NormalKind="normal",er.TangentKind="tangent",er.UVKind="uv",er.UV2Kind="uv2",er.UV3Kind="uv3",er.UV4Kind="uv4",er.UV5Kind="uv5",er.UV6Kind="uv6",er.ColorKind="color",er.ColorInstanceKind="instanceColor",er.MatricesIndicesKind="matricesIndices",er.MatricesWeightsKind="matricesWeights",er.MatricesIndicesExtraKind="matricesIndicesExtra",er.MatricesWeightsExtraKind="matricesWeightsExtra";class tr{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(er.NormalKind))return null;let i,s=this.pickedMesh.getIndices();0===s?.length&&(s=null);const r=ve.Vector3[0],n=ve.Vector3[1],o=ve.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(er.NormalKind);let t=s?_e.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),a=s?_e.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=s?_e.FromArrayToRef(e,3*s[3*this.faceId+2],o):o.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]);t=t.scale(this.bu),a=a.scale(this.bv),l=l.scale(1-this.bu-this.bv),i=new _e(t.x+a.x+l.x,t.y+a.y+l.y,t.z+a.z+l.z)}else{const e=this.pickedMesh.getVerticesData(er.PositionKind),t=s?_e.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),a=s?_e.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=s?_e.FromArrayToRef(e,3*s[3*this.faceId+2],o):o.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),h=t.subtract(a),c=l.subtract(a);i=_e.Cross(h,c)}const a=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(ve.Matrix[0].copyFrom(i),i=ve.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(ve.Matrix[1]),i=ve.Matrix[1]),_e.TransformNormalToRef(t,i,t)};if(e&&a(this.pickedMesh,i),this.ray){const t=ve.Vector3[0].copyFrom(i);e||a(this.pickedMesh,t),_e.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=er.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const i=this.pickedMesh.getVerticesData(e);if(!i)return null;let s=de.FromArray(i,2*t[3*this.faceId]),r=de.FromArray(i,2*t[3*this.faceId+1]),n=de.FromArray(i,2*t[3*this.faceId+2]);return s=s.scale(this.bu),r=r.scale(this.bv),n=n.scale(1-this.bu-this.bv),new de(s.x+r.x+n.x,s.y+r.y+n.y)}}class ir{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[er.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[er.PositionKind]=new er(this._scene.getEngine(),e,er.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}_rebuild(){const e=this._vertexBuffers[er.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!(!i||!(t=t||i._postProcesses.filter((e=>null!=e)))||0===t.length||!this._scene.postProcessesEnabled||(t[0].activate(i,e,null!=t),0))}directRender(e,t=null,i=!1,s=0,r=0,n=!1){const o=this._scene.getEngine();for(let a=0;anull!=e))).length||!this._scene.postProcessesEnabled)return;const o=this._scene.getEngine();for(let a=0,l=s.length;at._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),s=t.getMesh();return i.material&&s.material?i.material.uniqueId-s.material.uniqueId:i.uniqueId-s.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t.isEnabled()&&t.isVisible&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(0===this._particleSystems.length)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i=mr.LeftClick&&i<=mr.RightClick&&(a.type=1===s?"pointerdown":"pointerup",a.button=i-2),a}static _CreateWheelEvent(e,t,i,s,r,n){const o=this._CreateMouseEvent(e,t,i,s,r,n);switch(o.pointerId=1,o.type="wheel",o.deltaMode=Sr.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case mr.MouseWheelX:o.deltaX=s;break;case mr.MouseWheelY:o.deltaY=s;break;case mr.MouseWheelZ:o.deltaZ=s}return o}static _CreateMouseEvent(e,t,i,s,r,n){const o=this._CreateEvent(n),a=r.pollInput(e,t,mr.Horizontal),l=r.pollInput(e,t,mr.Vertical);return n?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-n.getBoundingClientRect().x,o.offsetY=o.movementY-n.getBoundingClientRect().y):(o.movementX=r.pollInput(e,t,gr.DeltaHorizontal),o.movementY=r.pollInput(e,t,gr.DeltaVertical),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,r),o.clientX=a,o.clientY=l,o.x=a,o.y=l,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=fr.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=1===t?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(fr.Keyboard),s=i&&1===t.pollInput(fr.Keyboard,0,18),r=i&&1===t.pollInput(fr.Keyboard,0,17),n=i&&(1===t.pollInput(fr.Keyboard,0,91)||1===t.pollInput(fr.Keyboard,0,92)||1===t.pollInput(fr.Keyboard,0,93)),o=i&&1===t.pollInput(fr.Keyboard,0,16);e.altKey=s,e.ctrlKey=r,e.metaKey=n,e.shiftKey=o}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class Er{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,s,r)=>{const n=Cr.CreateDeviceEvent(e,t,s,r,this);i(e,t,n)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===fr.Mouse||e===fr.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const Ar=Object.keys(mr).length/2;class Pr{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Ds.IsSafari(),this._usingMacOS=Vt()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=e=>{},this._keyboardUpEvent=e=>{},this._keyboardBlurEvent=e=>{},this._pointerMoveEvent=e=>{},this._pointerDownEvent=e=>{},this._pointerUpEvent=e=>{},this._pointerCancelEvent=e=>{},this._pointerWheelEvent=e=>{},this._pointerBlurEvent=e=>{},this._pointerMacOSChromeOutEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=Vt()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=Vt()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=Ds.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=s,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){const s=this._inputs[e][t];if(!s)throw`Unable to find device ${fr[e]}`;e>=fr.DualShock&&e<=fr.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(void 0===r)throw`Unable to find input ${i} for device ${fr[e]} in slot ${t}`;return i===mr.Move&&Ds.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this?._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(const e of this._inputs)if(e)for(const t in e){const i=e[+t];if(i)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(fr.Keyboard,0,255));const t=this._inputs[fr.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(fr.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(fr.Keyboard,0,255));const t=this._inputs[fr.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const i=Cr.CreateDeviceEvent(fr.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(fr.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(fr.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[fr.Keyboard][0];for(let t=0;t{const t=this._getPointerType(e);let i=t===fr.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===fr.Touch&&-1===i){const s=this._activeTouchIds.indexOf(-1);if(!(s>=0))return void Ds.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=s,this._activeTouchIds[s]=e.pointerId,this._onDeviceConnected(t,i)}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=e;r.inputIndex=mr.Move,s[mr.Horizontal]=e.clientX,s[mr.Vertical]=e.clientY,t===fr.Touch&&0===s[mr.LeftClick]&&(s[mr.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,r),this._usingSafari||-1===e.button||(r.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,r))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===fr.Mouse?0:e.pointerId;if(t===fr.Touch){let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t&&(t=this._activeTouchIds.indexOf(-1)),!(t>=0))return void Ds.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=t,this._activeTouchIds[t]=e.pointerId}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===fr.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=s[mr.Horizontal],n=s[mr.Vertical];if(t===fr.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}s[mr.Horizontal]=e.clientX,s[mr.Vertical]=e.clientY,s[e.button+2]=1;const o=e;o.inputIndex=e.button+2,this._onInputChanged(t,i,o),r===e.clientX&&n===e.clientY||(o.inputIndex=mr.Move,this._onInputChanged(t,i,o))}},this._pointerUpEvent=e=>{const t=this._getPointerType(e),i=t===fr.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===fr.Touch){if(-1===i)return;this._activeTouchIds[i]=-1}const s=this._inputs[t]?.[i];if(s&&0!==s[e.button+2]){const r=s[mr.Horizontal],n=s[mr.Vertical];s[mr.Horizontal]=e.clientX,s[mr.Vertical]=e.clientY,s[e.button+2]=0;const o=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),r===e.clientX&&n===e.clientY||(o.inputIndex=mr.Move,this._onInputChanged(t,i,o)),o.inputIndex=e.button+2,t===fr.Mouse&&this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(t,i,o),t===fr.Touch&&this._onDeviceDisconnected(t,i)}},this._pointerCancelEvent=e=>{if("mouse"===e.pointerType){const e=this._inputs[fr.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=mr.LeftClick;t<=mr.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=Cr.CreateDeviceEvent(fr.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(fr.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[fr.Touch][t][mr.LeftClick]=0;const i=Cr.CreateDeviceEvent(fr.Touch,t,mr.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(fr.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(fr.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1;const t=function(){};try{const i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch(e){}this._pointerBlurEvent=()=>{if(this.isDeviceAvailable(fr.Mouse)){const e=this._inputs[fr.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=mr.LeftClick;t<=mr.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=Cr.CreateDeviceEvent(fr.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(fr.Mouse,0,i)}}if(this.isDeviceAvailable(fr.Touch)){const e=this._inputs[fr.Touch];for(let t=0;t{const t=fr.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,Ar));const i=this._inputs[t][0];if(i){i[mr.MouseWheelX]=e.deltaX||0,i[mr.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[mr.MouseWheelZ]=e.deltaZ||0;const s=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[mr.MouseWheelX]&&(s.inputIndex=mr.MouseWheelX,this._onInputChanged(t,0,s)),0!==i[mr.MouseWheelY]&&(s.inputIndex=mr.MouseWheelY,this._onInputChanged(t,0,s)),0!==i[mr.MouseWheelZ]&&(s.inputIndex=mr.MouseWheelZ,this._onInputChanged(t,0,s))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=e=>{e.buttons>1&&this._pointerCancelEvent(e)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,!!e&&{passive:!1}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add((()=>{if(this.isDeviceAvailable(fr.Mouse)){const e=this._inputs[fr.Mouse][0];e[mr.MouseWheelX]=0,e[mr.MouseWheelY]=0,e[mr.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const s=navigator.getGamepads()[t];if(s&&e===this._gamepads[t]){const r=this._inputs[e][t];i>=s.buttons.length?r[i]=s.axes[i-s.buttons.length].valueOf():r[i]=s.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?fr.DualSense:fr.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?fr.Xbox:-1!==e.indexOf("057e")?fr.Switch:fr.Generic}_getPointerType(e){let t=fr.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=fr.Touch),t}}class Ir{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new K,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class Rr{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(fr).length/2;this._devices=new Array(t);const i=(e,t)=>{this._devices[e]||(this._devices[e]=new Array),this._devices[e][t]||(this._devices[e][t]=t);for(const i of this._registeredManagers){const s=new Ir(this._deviceInputSystem,e,t);i._addDevice(s)}},s=(e,t)=>{this._devices[e]?.[t]&&delete this._devices[e][t];for(const i of this._registeredManagers)i._removeDevice(e,t)},r=(e,t,i)=>{if(i)for(const s of this._registeredManagers)s._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new Er(i,s,r):this._deviceInputSystem=new Pr(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class Mr{getDeviceSource(e,t){if(void 0===t){if(void 0===this._firstDevice[e])return null;t=this._firstDevice[e]}return this._devices[e]&&void 0!==this._devices[e][t]?this._devices[e][t]:null}getDeviceSources(e){return this._devices[e]?this._devices[e].filter((e=>!!e)):[]}constructor(e){const t=Object.keys(fr).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new Rr(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new K((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new K,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){const i=this._devices[e]?.[t];this.onDeviceDisconnectedObservable.notifyObservers(i),this._devices[e]?.[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){this._devices[e]?.[t]?.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case fr.Keyboard:case fr.Mouse:this._firstDevice[e]=0;break;case fr.Touch:case fr.DualSense:case fr.DualShock:case fr.Xbox:case fr.Switch:case fr.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i=mr.MouseWheelX&&t.inputIndex<=mr.MouseWheelZ?lr.POINTERWHEEL:lr.POINTERMOVE;let o;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n)),e?(o=new ur(n,t,e),this._setRayOnPointerInfo(e,t)):(o=new ur(n,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,me.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const s=this._scene,r=new cr(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,"xr-near"===t.pointerType&&e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const s=i.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(s.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=mr.Move,this._checkPrePointerObservable(e,i,lr.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,lr.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const s=e.pickedMesh._getActionManagerForTrigger();if(s){if(s.hasPickTriggers)switch(s.processTrigger(5,Re.CreateNew(e.pickedMesh,t,e)),t.button){case 0:s.processTrigger(2,Re.CreateNew(e.pickedMesh,t,e));break;case 1:s.processTrigger(4,Re.CreateNew(e.pickedMesh,t,e));break;case 2:s.processTrigger(3,Re.CreateNew(e.pickedMesh,t,e))}s.hasSpecificTrigger(8)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);e?.pickedMesh&&s&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>Dr.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,s.processTrigger(8,Re.CreateNew(e.pickedMesh,t)))}),Dr.LongPressDelay)}}else for(const s of i._pointerDownStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=lr.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new ur(r,t,e),this._setRayOnPointerInfo(e,t)):s=new ur(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=mr.Move;const r=new Or;i?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,s,lr.POINTERUP)||this._processPointerUp(e,s,r)}_processPointerUp(e,t,i){const s=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){const i=lr.POINTERPICK,r=new ur(i,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,i)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,Re.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,Re.CreateNew(e.pickedMesh,t,e));const s=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&s&&s.processTrigger(6,Re.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,Re.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new ur(lr.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,lr.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,lr.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(i.singleClick?r=lr.POINTERTAP:i.doubleClick&&(r=lr.POINTERDOUBLETAP),r){const i=new ur(r,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(r)&&s.onPointerObservable.notifyObservers(i,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const r=this._scene,n=r.getEngine();s||(s=n.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new Mr(n),this._initActionManager=e=>{if(!this._meshPickProceed){const t=r.skipPointerUpPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers,r.pointerUpTrianglePredicate);this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>Dr.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){const t=this._delayedClicks[e].evt,i=lr.POINTERTAP,s=new ur(i,t,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(i)&&r.onPointerObservable.notifyObservers(s,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,s)=>{const r=new Or;this._currentPickResult=null;let n=null,o=e.hasSpecificMask(lr.POINTERPICK)||t.hasSpecificMask(lr.POINTERPICK)||e.hasSpecificMask(lr.POINTERTAP)||t.hasSpecificMask(lr.POINTERTAP)||e.hasSpecificMask(lr.POINTERDOUBLETAP)||t.hasSpecificMask(lr.POINTERDOUBLETAP);!o&&Y&&(n=this._initActionManager(n,r),n&&(o=n.hasPickTriggers));let a=!1;if(o){const o=i.button;if(r.hasSwiped=this._isPointerSwiping(),!r.hasSwiped){let l=!Dr.ExclusiveDoubleClickMode;if(l||(l=!e.hasSpecificMask(lr.POINTERDOUBLETAP)&&!t.hasSpecificMask(lr.POINTERDOUBLETAP),l&&!Y.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(l=!n.hasSpecificTrigger(6)))),l)(Date.now()-this._previousStartingPointerTime>Dr.DoubleClickDelay||o!==this._previousButtonPressed)&&(r.singleClick=!0,s(r,this._currentPickResult),a=!0);else{const e={evt:i,clickInfo:r,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,o,r,s),Dr.DoubleClickDelay)};this._delayedClicks[o]=e}let h=e.hasSpecificMask(lr.POINTERDOUBLETAP)||t.hasSpecificMask(lr.POINTERDOUBLETAP);!h&&Y.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(h=n.hasSpecificTrigger(6))),h&&(o===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>Dr.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>Dr.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=mr.MouseWheelX&&e.inputIndex<=mr.MouseWheelZ?lr.POINTERWHEEL:lr.POINTERMOVE))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking)return void this._processPointerMove(new tr,e);r.pointerMovePredicate||(r.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask)));const t=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,Dr.ExclusiveDoubleClickMode)for(let t=0;te.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,t=r.skipPointerDownPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerDown?new tr:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers,r.pointerDownTrianglePredicate),this._processPointerDown(t,e)},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),r.preventDefaultOnPointerUp&&s&&(e.preventDefault(),s.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,e,((t,i)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,lr.POINTERUP))return this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),void(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1));t.hasSwiped||(t.singleClick&&r.onPrePointerObservable.hasSpecificMask(lr.POINTERTAP)&&this._checkPrePointerObservable(null,e,lr.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&r.onPrePointerObservable.hasSpecificMask(lr.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,lr.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(r.cameraToUseForPointers||r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(Y&&Y.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))):this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1)})))},this._onKeyDown=e=>{const t=dr.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const i=new pr(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new _r(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(14,Re.CreateNewFromScene(r,e))},this._onKeyUp=e=>{const t=dr.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const i=new pr(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new _r(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(15,Re.CreateNewFromScene(r,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((s=>{s.deviceType===fr.Mouse?s.onInputChangedObservable.add((r=>{this._originMouseEvent=r,r.inputIndex===mr.LeftClick||r.inputIndex===mr.MiddleClick||r.inputIndex===mr.RightClick||r.inputIndex===mr.BrowserBack||r.inputIndex===mr.BrowserForward?t&&1===s.getInput(r.inputIndex)?this._onPointerDown(r):e&&0===s.getInput(r.inputIndex)&&this._onPointerUp(r):i&&(r.inputIndex===mr.Move?this._onPointerMove(r):r.inputIndex!==mr.MouseWheelX&&r.inputIndex!==mr.MouseWheelY&&r.inputIndex!==mr.MouseWheelZ||this._onPointerMove(r))})):s.deviceType===fr.Touch?s.onInputChangedObservable.add((r=>{r.inputIndex===mr.LeftClick&&(t&&1===s.getInput(r.inputIndex)?(this._onPointerDown(r),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===s.getInput(r.inputIndex)&&(this._onPointerUp(r),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&r.inputIndex===mr.Move&&this._onPointerMove(r)})):s.deviceType===fr.Keyboard&&s.onInputChangedObservable.add((e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)}))})),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,s){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const r=this._meshUnderPointerId[t];let n;r&&(n=r._getActionManagerForTrigger(10),n&&n.processTrigger(10,Re.CreateNew(r,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,Re.CreateNew(e,s,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(const t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}Dr.DragMovementThreshold=10,Dr.LongPressDelay=500,Dr.DoubleClickDelay=300,Dr.ExclusiveDoubleClickMode=!1;class wr{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){wr.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){wr.Enabled&&(this._startMonitoringTime=Wt.Now)}endMonitoring(e=!0){if(!wr.Enabled)return;e&&this.fetchNewFrame();const t=Wt.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;const e=Wt.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}wr.Enabled=!0;class Nr{constructor(e,t,i,s){this.normal=new _e(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new Nr(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^this.d,e}normalize(){const e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z);let t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=Nr._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,o=this.d,a=s*i[0]+r*i[1]+n*i[2]+o*i[3],l=s*i[4]+r*i[5]+n*i[6]+o*i[7],h=s*i[8]+r*i[9]+n*i[10]+o*i[11],c=s*i[12]+r*i[13]+n*i[14]+o*i[15];return new Nr(a,l,h,c)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const s=t.x-e.x,r=t.y-e.y,n=t.z-e.z,o=i.x-e.x,a=i.y-e.y,l=i.z-e.z,h=r*l-n*a,c=n*o-s*l,u=s*a-r*o,d=Math.sqrt(h*h+c*c+u*u);let _;return _=0!==d?1/d:0,this.normal.x=h*_,this.normal.y=c*_,this.normal.z=u*_,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return _e.Dot(this.normal,e)<=t}signedDistanceTo(e){return _e.Dot(e,this.normal)+this.d}static FromArray(e){return new Nr(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new Nr(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new Nr(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return _e.Dot(i,t)+s}}Nr._TmpMatrix=me.Identity();class Fr{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new Nr(0,0,0,0));return Fr.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){Fr.GetNearPlaneToRef(e,t[0]),Fr.GetFarPlaneToRef(e,t[1]),Fr.GetLeftPlaneToRef(e,t[2]),Fr.GetRightPlaneToRef(e,t[3]),Fr.GetTopPlaneToRef(e,t[4]),Fr.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}class Lr{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}Lr._UniqueIdCounter=1;class Br{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}Br.FALLOFF_DEFAULT=0,Br.FALLOFF_PHYSICAL=1,Br.FALLOFF_GLTF=2,Br.FALLOFF_STANDARD=3,Br.LIGHTMAP_DEFAULT=0,Br.LIGHTMAP_SPECULAR=1,Br.LIGHTMAP_SHADOWSONLY=2,Br.INTENSITYMODE_AUTOMATIC=0,Br.INTENSITYMODE_LUMINOUSPOWER=1,Br.INTENSITYMODE_LUMINOUSINTENSITY=2,Br.INTENSITYMODE_ILLUMINANCE=3,Br.INTENSITYMODE_LUMINANCE=4,Br.LIGHTTYPEID_POINTLIGHT=0,Br.LIGHTTYPEID_DIRECTIONALLIGHT=1,Br.LIGHTTYPEID_SPOTLIGHT=2,Br.LIGHTTYPEID_HEMISPHERICLIGHT=3;class kr{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var Vr,Ur,Gr,zr,Wr;!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(Vr||(Vr={}));class Hr extends X{static DefaultMaterialFactory(e){throw xt("StandardMaterial")}static CollisionCoordinatorFactory(){throw xt("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case Vr.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case Vr.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case Vr.Aggressive:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return Dr.DragMovementThreshold}static set DragMovementThreshold(e){Dr.DragMovementThreshold=e}static get LongPressDelay(){return Dr.LongPressDelay}static set LongPressDelay(e){Dr.LongPressDelay=e}static get DoubleClickDelay(){return Dr.DoubleClickDelay}static set DoubleClickDelay(e){Dr.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return Dr.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){Dr.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const s=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return ve.Vector4[0].set(s.x,s.y,s.z,r?-1:1),e&&(i?e.setFloat3(t,ve.Vector4[0].x,ve.Vector4[0].y,ve.Vector4[0].z):e.setVector4(t,ve.Vector4[0])),ve.Vector4[0]}finalizeSceneUbo(){const e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=ie(e,(()=>{this.onActiveCamerasChanged.notifyObservers(this)}))),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=Hr.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=Hr.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new Dr(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new Ae(.2,.2,.3,1),this.ambientColor=new Ee(0,0,0),this.environmentIntensity=1,this._performancePriority=Vr.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new K,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new K,this._onDisposeObserver=null,this.onBeforeRenderObservable=new K,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new K,this.onAfterRenderCameraObservable=new K,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new K,this.onAfterAnimationsObservable=new K,this.onBeforeDrawPhaseObservable=new K,this.onAfterDrawPhaseObservable=new K,this.onReadyObservable=new K,this.onBeforeCameraRenderObservable=new K,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new K,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new K,this.onAfterActiveMeshesEvaluationObservable=new K,this.onBeforeParticlesRenderingObservable=new K,this.onAfterParticlesRenderingObservable=new K,this.onDataLoadedObservable=new K,this.onNewCameraAddedObservable=new K,this.onCameraRemovedObservable=new K,this.onNewLightAddedObservable=new K,this.onLightRemovedObservable=new K,this.onNewGeometryAddedObservable=new K,this.onGeometryRemovedObservable=new K,this.onNewTransformNodeAddedObservable=new K,this.onTransformNodeRemovedObservable=new K,this.onNewMeshAddedObservable=new K,this.onMeshRemovedObservable=new K,this.onNewSkeletonAddedObservable=new K,this.onSkeletonRemovedObservable=new K,this.onNewMaterialAddedObservable=new K,this.onNewMultiMaterialAddedObservable=new K,this.onMaterialRemovedObservable=new K,this.onMultiMaterialRemovedObservable=new K,this.onNewTextureAddedObservable=new K,this.onTextureRemovedObservable=new K,this.onBeforeRenderTargetsRenderObservable=new K,this.onAfterRenderTargetsRenderObservable=new K,this.onBeforeStepObservable=new K,this.onAfterStepObservable=new K,this.onActiveCameraChanged=new K,this.onActiveCamerasChanged=new K,this.onBeforeRenderingGroupObservable=new K,this.onAfterRenderingGroupObservable=new K,this.onMeshImportedObservable=new K,this.onAnimationFileImportedObservable=new K,this._registeredForLateAnimationBindings=new Ls(256),this._pointerPickingConfiguration=new kr,this.onPrePointerObservable=new K,this.onPointerObservable=new K,this.onPreKeyboardObservable=new K,this.onKeyboardObservable=new K,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=Hr.FOGMODE_NONE,this.fogColor=new Ee(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new _e(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new Ls(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new wr,this._activeIndices=new wr,this._activeParticles=new wr,this._activeBones=new wr,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=new Array(256),this._activeRequests=new Array,this._pendingData=new Array,this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new Fs(256),this._processedMaterials=new Fs(256),this._renderTargets=new Ls(256),this._materialsRenderTargets=new Ls(256),this._activeParticleSystems=new Fs(256),this._activeSkeletons=new Ls(32),this._softwareSkinnedMeshes=new Ls(32),this._activeAnimatables=new Array,this._transformMatrix=me.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=ar.Create(),this._beforeClearStage=ar.Create(),this._beforeRenderTargetClearStage=ar.Create(),this._gatherRenderTargetsStage=ar.Create(),this._gatherActiveCameraRenderTargetsStage=ar.Create(),this._isReadyForMeshStage=ar.Create(),this._beforeEvaluateActiveMeshStage=ar.Create(),this._evaluateSubMeshStage=ar.Create(),this._preActiveMeshStage=ar.Create(),this._cameraDrawRenderTargetStage=ar.Create(),this._beforeCameraDrawStage=ar.Create(),this._beforeRenderTargetDrawStage=ar.Create(),this._beforeRenderingGroupDrawStage=ar.Create(),this._beforeRenderingMeshStage=ar.Create(),this._afterRenderingMeshStage=ar.Create(),this._afterRenderingGroupDrawStage=ar.Create(),this._afterCameraDrawStage=ar.Create(),this._afterCameraPostProcessStage=ar.Create(),this._afterRenderTargetDrawStage=ar.Create(),this._afterRenderTargetPostProcessStage=ar.Create(),this._afterRenderStage=ar.Create(),this._pointerMoveStage=ar.Create(),this._pointerDownStage=ar.Create(),this._pointerUpStage=ar.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];const i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};e=this._engine=e||re.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(re._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new nr(this),ir&&(this.postProcessManager=new ir(this)),kt()&&this.attachControl(),this._createUbo(),zs&&(this._imageProcessingConfiguration=new zs),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,t&&t.virtual||e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return void 0!==this._animationRatio?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){if(this._isDisposed)return!1;let t;const i=this.getEngine(),s=i.currentRenderPassId;i.currentRenderPassId=this.activeCamera?.renderPassId??s;let r=!0;for(this._pendingData.length>0&&(r=!1),this.prePassRenderer?.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&r&&(r=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const e of this._isReadyForMeshStage)e.action(s,n)||(r=!1);if(!e)continue;const o=s.material||this.defaultMaterial;if(o)if(o._storeEffectOnSubMeshes)for(const e of s.subMeshes){const t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else o.hasRenderTargetTextures&&null!=o.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(o)&&(this._processedMaterials.push(o),this._materialsRenderTargets.concatWithNoDuplicate(o.getRenderTargetTextures()))}if(e)for(t=0;t0)for(const e of this.activeCameras)e.isReady(!0)||(r=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(r=!1));for(const e of this.particleSystems)e.isReady()||(r=!1);if(this.layers)for(const e of this.layers)e.isReady()||(r=!1);return i.areAllEffectsReady()||(r=!1),i.currentRenderPassId=s,r}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout((()=>{this.unregisterBeforeRender(t)}))};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){void 0!==t?setTimeout((()=>{this._executeOnceBeforeRender(e)}),t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){const t=this.isLoading,i=this._pendingData.indexOf(e);-1!==i&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise((t=>{this.executeWhenReady((()=>{t()}),e)}))}_checkIsReady(e=!1){return this._registerTransientComponents(),this.isReady(e)?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):void(this._executeWhenReadyTimeoutId=setTimeout((()=>{this.incrementRenderId(),this._checkIsReady(e)}),100))}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=Wt.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,s){i||s||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?Fr.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Fr.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,s):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new Zs(this._engine,void 0,!1,e??"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return Lr.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.addMesh(e)})))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return-1!==i&&(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.removeMesh(e)})),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){const e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){const t=this.skeletons.indexOf(e);return-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(-1!==t){for(const t of this.meshes)t._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t}removeCamera(e){const t=this.cameras.indexOf(e);if(-1!==t&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){const t=this.particleSystems.indexOf(e);return-1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(-1!==t&&tt.uniqueId===e))}getMaterialById(e,t=!1){return this._getMaterial(t,(t=>t.id===e))}getMaterialByName(e,t=!1){return this._getMaterial(t,(t=>t.name===e))}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t)for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t];return null}getTextureByUniqueId(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const s=this.getLightById(e);if(s)return s;const r=this.getCameraById(e);if(r)return r;return this.getBoneById(e)||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const s=this.getLightByName(e);if(s)return s;const r=this.getCameraByName(e);if(r)return r;return this.getBoneByName(e)||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(this.activeCamera){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,s)for(let e=0;ee.dispose()))}_evaluateActiveMeshes(){if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode)return void(this._activeMeshes.length>0&&(this.activeCamera?._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset()));if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const e=this._activeMeshes.length;for(let t=0;t0&&t.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||t.alwaysSelectAsActiveMesh||t.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(t),this.activeCamera._activeMeshes.push(t),s!==t&&s._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(t);t._activate(this._renderId,!1)&&(t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(s=t):s._internalAbstractMeshDataInfo._onlyForInstances=!1,s._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(t,s)),t._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e0){const s=this.getActiveSubMeshCandidates(t),r=s.length;i=i||1===r;for(let n=0;n0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const e of this._gatherActiveCameraRenderTargetsStage)e.action(this._renderTargets);let r=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Ds.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e0),this._renderId++}for(const e of this._cameraDrawRenderTargetStage)r=e.action(this.activeCamera)||r;this._intermediateRendering=!1}this._engine.currentRenderPassId=e.outputRenderTarget?.renderPassId??e.renderPassId??0,r&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame();for(const e of this._beforeCameraDrawStage)e.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),s.snapshotRendering&&1===s.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const e of this._afterCameraDrawStage)e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(const e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview)return e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t-1&&(13===i.trigger&&i._executeCurrent(Re.CreateNew(t,void 0,s)),t.actionManager.hasSpecificTrigger(13,(e=>{const t=e.mesh?e.mesh:e;return s===t}))&&13!==i.trigger||t._intersectionsInProgress.splice(n,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(Hr.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Hr.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&s0)for(let e=0;e0),this._intermediateRendering=!0;for(let e=0;e0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=s?.renderPassId??0,this.activeCamera=s,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const e of this._beforeClearStage)e.action();this._clearFrameBuffer(this.activeCamera);for(const e of this._gatherRenderTargetsStage)e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const e of this._afterRenderStage)e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e{e.onAnimationEndObservable.clear(),e.onAnimationEnd=null})),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;const e=this._activeRequests.slice();for(const t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){Ne.Error("An error occurred while calling onDisposeObservable!",e)}if(this.detachControl(),this._engine.getInputElement())for(let e=0;ee.dispose(!0))),this._disposeList(this.transformNodes,(e=>e.dispose(!0)));const t=this.cameras;this._disposeList(t),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),re._LastCreatedScene===this&&(this._engine.scenes.length>0?re._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:re._LastCreatedScene=null),i=this._engine._virtualScenes.indexOf(this),i>-1&&this._engine._virtualScenes.splice(i,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const i=e.slice(0);t=t??(e=>e.dispose());for(const e of i)t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach((e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;const s=e.getBoundingInfo(),r=s.boundingBox.minimumWorld,n=s.boundingBox.maximumWorld;_e.CheckExtends(r,t,i),_e.CheckExtends(n,t,i)})),{min:t,max:i}}createPickingRay(e,t,i,s,r=!1){throw xt("Ray")}createPickingRayToRef(e,t,i,s,r,n=!1,o=!1){throw xt("Ray")}createPickingRayInCameraSpace(e,t,i){throw xt("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw xt("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,r,n){const o=xt("Ray",!0);return o&&Ne.Warn(o),new tr}pickWithBoundingInfo(e,t,i,s,r){const n=xt("Ray",!0);return n&&Ne.Warn(n),new tr}pickWithRay(e,t,i,s){throw xt("Ray")}multiPick(e,t,i,s,r){throw xt("Ray")}multiPickWithRay(e,t,i){throw xt("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(void 0===t)return e;const s=[];for(const r in e){const n=e[r];Tt&&Tt.MatchesQuery(n,t)&&(!i||i(n))&&s.push(n)}return s}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,s)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,s,r,n,o){const a=ps(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_loadFileAsync(e,t,i,s,r){return new Promise(((n,o)=>{this._loadFile(e,(e=>{n(e)}),t,i,s,((e,t)=>{o(t)}),r)}))}_requestFile(e,t,i,s,r,n,o){const a=fs(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_requestFileAsync(e,t,i,s,r){return new Promise(((n,o)=>{this._requestFile(e,(e=>{n(e)}),t,i,s,(e=>{o(e)}),r)}))}_readFile(e,t,i,s,r){const n=_s(e,t,i,s,r);return this._activeRequests.push(n),n.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),n}_readFileAsync(e,t,i){return new Promise(((s,r)=>{this._readFile(e,(e=>{s(e)}),t,i,(e=>{r(e)}))}))}getPerfCollector(){throw xt("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}Hr.FOGMODE_NONE=0,Hr.FOGMODE_EXP=1,Hr.FOGMODE_EXP2=2,Hr.FOGMODE_LINEAR=3,Hr.MinDeltaTime=1,Hr.MaxDeltaTime=1e3,z("BABYLON.Scene",Hr),function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(Ur||(Ur={}));class Xr{}Xr.X=new _e(1,0,0),Xr.Y=new _e(0,1,0),Xr.Z=new _e(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Gr||(Gr={}));class Yr extends Et{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){(e.updateFlag!==this._localMatrix.updateFlag||this._needToCompose)&&(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,s=null,r=null,n=null,o=null){super(e,t.getScene(),!1),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=s?.clone()??me.Identity(),this._restMatrix=r??this._localMatrix.clone(),this._bindMatrix=n??this._localMatrix.clone(),this._index=o,this._absoluteMatrix=new me,this._absoluteBindMatrix=new me,this._absoluteInverseBindMatrix=new me,this._finalMatrix=new me,t.bones.push(this),this.setParent(i,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return null===this._index?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){const e=this.parent.children.indexOf(this);-1!==e&&this.parent.children.splice(e,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){if(this._linkedTransformNode){const e=ve.Vector3[0],t=ve.Quaternion[0],i=ve.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??fe.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(t),this._linkedTransformNode.scaling.copyFrom(e)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._absoluteMatrix}getAbsoluteTransform(){return this._absoluteMatrix}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=_e.Zero(),this._localRotation=fe.Zero(),this._localPosition=_e.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,me.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let e=0;e-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(r)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const r=this._runtimeAnimations;for(let i=r.length-1;i>=0;i--){const s=r[i];e&&s.animation.name!=e||t&&!t(s.target)||(s.dispose(),r.splice(i,1))}0==r.length&&(i||this._scene._activeAnimatables.splice(s,1),this._raiseOnAnimationEnd())}}else{const e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);const t=this._runtimeAnimations;for(let e=0;e{this.onAnimationEndObservable.add((()=>{e(this)}),void 0,void 0,this,!0)}))}_animate(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),null!==this._manualJumpDelay&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,0===this._weight)return!0;let t=!1;const i=this._runtimeAnimations;let s;for(s=0;s0)return;this._animationTimeLast=t}this.deltaTime=void 0!==e?e:this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=t;const i=this._activeAnimatables;if(0===i.length)return;this._animationTime+=this.deltaTime;const s=this._animationTime;for(let e=0;ee.playOrder-t.playOrder))},Hr.prototype.beginWeightedAnimation=function(e,t,i,s=1,r,n=1,o,a,l,h,c=!1){const u=this.beginAnimation(e,t,i,r,n,o,a,!1,l,h,c);return u.weight=s,u},Hr.prototype.beginAnimation=function(e,t,i,s,r=1,n,o,a=!0,l,h,c=!1){t>i&&r>0&&(r*=-1),a&&this.stopAnimation(e,void 0,l),o||(o=new Qr(this,e,t,i,s,r,n,void 0,h,c));const u=!l||l(e);if(e.animations&&u&&o.appendAnimations(e,e.animations),e.getAnimatables){const c=e.getAnimatables();for(let e=0;es&&n>0)n*=-1;else if(s>i&&n<0){const e=s;s=i,i=e}return new Qr(this,e,i,s,r,n,o,t,a,l)},Hr.prototype.beginDirectHierarchyAnimation=function(e,t,i,s,r,n,o,a,l,h=!1){const c=e.getDescendants(t),u=[];u.push(this.beginDirectAnimation(e,i,s,r,n,o,a,l,h));for(const e of c)u.push(this.beginDirectAnimation(e,i,s,r,n,o,a,l,h));return u},Hr.prototype.getAnimatableByTarget=function(e){for(let t=0;t0?l:-l,r),a.scaleAndAddToRef(l,i)}r.normalize()}for(let t=0;t0)r.copyFrom(s);else if(1===e.animations.length){if(fe.SlerpToRef(s,i.currentValue,Math.min(1,e.totalWeight),r),0===e.totalAdditiveWeight)return r}else if(e.animations.length>1){let i,n,o=1;if(e.totalWeight<1){const t=1-e.totalWeight;i=[],n=[],i.push(s),n.push(t)}else{if(2===e.animations.length&&(fe.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],n=[],o=e.totalWeight}for(let t=0;t=o&&m.frame<=a&&(s?(v=m.value.clone(),d?(g=v.getTranslation(),v.setTranslation(g.scaleInPlace(_))):p&&r?(g=v.getTranslation(),v.setTranslation(g.multiplyInPlace(r))):v=m.value):v=m.value,f.push({frame:m.frame+i,value:v}));return this.animations[0].createRange(t,o+i,a+i),!0};class jr{constructor(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=Ft.ANIMATIONLOOPMODE_CYCLE}}!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(zr||(zr={}));class Kr{static Interpolate(e,t,i,s,r){const n=1-3*s+3*t,o=3*s-6*t,a=3*t;let l=e;for(let t=0;t<5;t++){const t=l*l;l-=1/(3*n*t+2*o*l+a)*(n*(t*l)+o*t+a*l-e),l=Math.min(1,Math.max(0,l))}return 3*Math.pow(1-l,2)*l*i+3*(1-l)*Math.pow(l,2)*r+Math.pow(l,3)}}class $r{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return 180*this._radians/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),s=Math.atan2(i.y,i.x);return new $r(s)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(0===i)return new $r(Math.PI/2);i=Math.sqrt(i);let s=e.dot(t)/i;s=be.Clamp(s,-1,1);const r=Math.acos(s);return new $r(r)}static FromRadians(e){return new $r(e)}static FromDegrees(e){return new $r(e*Math.PI/180)}}class qr{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const s=Math.pow(t.x,2)+Math.pow(t.y,2),r=(Math.pow(e.x,2)+Math.pow(e.y,2)-s)/2,n=(s-Math.pow(i.x,2)-Math.pow(i.y,2))/2,o=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new de((r*(t.y-i.y)-n*(e.y-t.y))/o,((e.x-t.x)*n-(t.x-i.x)*r)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=$r.BetweenTwoPoints(this.centerPoint,this.startPoint);const a=this.startAngle.degrees();let l=$r.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=$r.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-a>180&&(l-=360),l-a<-180&&(l+=360),h-l>180&&(h-=360),h-l<-180&&(h+=360),this.orientation=l-a<0?zr.CW:zr.CCW,this.angle=$r.FromDegrees(this.orientation===zr.CW?a-h:h-a)}}class Zr{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new de(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new de(e,t),s=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(s).length(),this}addArcTo(e,t,i,s,r=36){if(this.closed)return this;const n=this._points[this._points.length-1],o=new de(e,t),a=new de(i,s),l=new qr(n,o,a);let h=l.angle.radians()/r;l.orientation===zr.CW&&(h*=-1);let c=l.startAngle.radians()+h;for(let e=0;e(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*s,o=this._points[this._points.length-1];for(let a=0;a<=r;a++){const l=a/r,h=n(l,o.x,e,i),c=n(l,o.y,t,s);this.addLineTo(h,c)}return this}addBezierCurveTo(e,t,i,s,r,n,o=36){if(this.closed)return this;const a=(e,t,i,s,r)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*s+e*e*e*r,l=this._points[this._points.length-1];for(let h=0;h<=o;h++){const c=h/o,u=a(c,l.x,e,i,r),d=a(c,l.y,t,s,n);this.addLineTo(u,d)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let s=i-1,r=0;rNumber.EPSILON){if(a<0&&(i=this._points[r],o=-o,n=this._points[s],a=-a),e.yn.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{const s=a*(e.x-i.x)-o*(e.y-i.y);if(0===s)return!0;if(s<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(n.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=n.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1];e+=this._points[0].subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,s=0;s1)return de.Zero();const t=e*this.length();let i=0;for(let e=0;e=i&&t<=o){const e=n.normalize(),s=t-i;return new de(r.x+e.x*s,r.y+e.y*s)}i=o}return de.Zero()}static StartingAt(e,t){return new Zr(e,t)}}class Jr{constructor(e,t=null,i,s=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:_e.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:me.Identity()};for(let t=0;tt){const i=e;e=t,t=i}const i=this.getCurve(),s=this.getPointAt(e);let r=this.getPreviousPointIndexAt(e);const n=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,a=[];return 0!==e&&(r++,a.push(s)),a.push(...i.slice(r,o)),1===t&&1!==e||a.push(n),new Jr(a,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;tt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,s=e.length();if(0===s&&(s=1),null==t){let t;t=be.WithinEpsilon(Math.abs(e.y)/s,1,J)?be.WithinEpsilon(Math.abs(e.x)/s,1,J)?be.WithinEpsilon(Math.abs(e.z)/s,1,J)?_e.Zero():new _e(0,0,1):new _e(1,0,0):new _e(0,-1,0),i=_e.Cross(e,t)}else i=_e.Cross(e,t),_e.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;const i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let s,r=i[0],n=0;const o=e*this.length();for(let a=1;ao){const i=(n-o)/l,h=r.subtract(s),c=s.add(h.scaleInPlace(i));return this._setPointAtData(e,1-i,c,a-1,t)}r=s}return this._pointAtData}_setPointAtData(e,t,i,s,r){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=s,this._pointAtData.interpolateReady=r,r&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=me.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),s=this._normals[e].clone(),r=this._binormals[e].clone(),n=this._tangents[t].clone(),o=this._normals[t].clone(),a=this._binormals[t].clone(),l=fe.RotationQuaternionFromAxis(s,r,i),h=fe.RotationQuaternionFromAxis(o,a,n);fe.Slerp(l,h,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class en{static CreateQuadraticBezier(e,t,i,s){s=s>2?s:3;const r=[],n=(e,t,i,s)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*s;for(let o=0;o<=s;o++)r.push(new _e(n(o/s,e.x,t.x,i.x),n(o/s,e.y,t.y,i.y),n(o/s,e.z,t.z,i.z)));return new en(r)}static CreateCubicBezier(e,t,i,s,r){r=r>3?r:4;const n=[],o=(e,t,i,s,r)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*s+e*e*e*r;for(let a=0;a<=r;a++)n.push(new _e(o(a/r,e.x,t.x,i.x,s.x),o(a/r,e.y,t.y,i.y,s.y),o(a/r,e.z,t.z,i.z,s.z)));return new en(n)}static CreateHermiteSpline(e,t,i,s,r){const n=[],o=1/r;for(let a=0;a<=r;a++)n.push(_e.Hermite(e,t,i,s,a*o));return new en(n)}static CreateCatmullRomSpline(e,t,i){const s=[],r=1/t;let n=0;if(i){const i=e.length;for(let o=0;o=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}tn.EASINGMODE_EASEIN=0,tn.EASINGMODE_EASEOUT=1,tn.EASINGMODE_EASEINOUT=2;class sn extends tn{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class rn extends tn{constructor(e=1){super(),this.amplitude=e}easeInCore(e){const t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}}class nn extends tn{constructor(e=3,t=2){super(),this.bounces=e,this.bounciness=t}easeInCore(e){const t=Math.max(0,this.bounces);let i=this.bounciness;i<=1&&(i=1.001);const s=Math.pow(i,t),r=1-i,n=(1-s)/r+.5*s,o=e*n,a=Math.log(-o*(1-i)+1)/Math.log(i),l=Math.floor(a),h=l+1,c=(1-Math.pow(i,l))/(r*n),u=.5*(c+(1-Math.pow(i,h))/(r*n)),d=e-u,_=u-c;return-Math.pow(1/i,t-l)/(_*_)*(d-_)*(d+_)}}class on extends tn{easeInCore(e){return e*e*e}}class an extends tn{constructor(e=3,t=3){super(),this.oscillations=e,this.springiness=t}easeInCore(e){let t;const i=Math.max(0,this.oscillations),s=Math.max(0,this.springiness);return t=0==s?e:(Math.exp(s*e)-1)/(Math.exp(s)-1),t*Math.sin((6.283185307179586*i+1.5707963267948966)*e)}}class ln extends tn{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}}class hn extends tn{constructor(e=2){super(),this.power=e}easeInCore(e){const t=Math.max(0,this.power);return Math.pow(e,t)}}class cn extends tn{easeInCore(e){return e*e}}class un extends tn{easeInCore(e){return e*e*e*e}}class dn extends tn{easeInCore(e){return e*e*e*e*e}}class _n extends tn{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class pn extends tn{constructor(e=0,t=0,i=1,s=1){super(),this.x1=e,this.y1=t,this.x2=i,this.y2=s}easeInCore(e){return Kr.Interpolate(e,this.x1,this.y1,this.x2,this.y2)}}class fn{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new fn(this.frame,this.action,this.onlyOnce)}}class mn{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class gn{get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this.syncWithMask(!0))}syncWithMask(e=!1){if(this.mask||e){this._numActiveAnimatables=0;for(let e=0;e0)){for(let e=0;en&&(n=t.to);const o=new gn(e[0].name+"_merged",e[0]._scene,s);for(const s of e){i&&s.normalize(r,n);for(const e of s.targetedAnimations)o.addTargetedAnimation(e.animation,e.target);t&&s.dispose()}return o}constructor(e,t=null,i=-1,s=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._parentContainer=null,this.onAnimationEndObservable=new K,this.onAnimationLoopObservable=new K,this.onAnimationGroupLoopObservable=new K,this.onAnimationGroupEndObservable=new K,this.onAnimationGroupPauseObservable=new K,this.onAnimationGroupPlayObservable=new K,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||re.LastCreatedScene,this._weight=i,this._playOrder=s,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new mn;i.animation=e,i.target=t;const s=e.getKeys();return this._from>s[0].frame&&(this._from=s[0].frame),this._to-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;ie){const t={frame:e,value:r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation};s.splice(0,0,t)}if(n.frame{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,s,r){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(a)},this._processLoop(a,o,n),this._animatables.push(a)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e0&&(this._scene._activeAnimatables[t++]=i)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const e=this._parentContainer.animationGroups.indexOf(this);e>-1&&this._parentContainer.animationGroups.splice(e,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e){const t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const s=new gn(e||this.name,this._scene,this._weight,this._playOrder);s._from=this.from,s._to=this.to,s._speedRatio=this.speedRatio,s._loopAnimation=this.loopAnimation,s._isAdditive=this.isAdditive,s._enableBlending=this.enableBlending,s._blendingSpeed=this.blendingSpeed,s.metadata=this.metadata,s.mask=this.mask;for(const e of this._targetedAnimations)s.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return s}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;tr[0].frame&&(e=r[0].frame),t=t&&e<=i||r&&s.frame>=t&&s.frame<=i){const e={frame:s.frame,value:s.value.clone?s.value.clone():s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation,lockedTangent:s.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,u.push(e)}}0!==u.length?(n>u[0].frame&&(n=u[0].frame),o1)throw"step size should be less than 1.";return this.value+=e,this._ensureLimits(),this._raiseOnChange(),this}_ensureLimits(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this}_raiseOnChange(){return this._onchange.forEach((e=>e(this))),this}onchange(e){return this._onchange.push(e),this}}!function(e){e[e.Include=0]="Include",e[e.Exclude=1]="Exclude"}(Wr||(Wr={}));class xn{constructor(e,t=Wr.Include){this.mode=t,this.disabled=!1,this._targetNames=new Set,e&&this.addTargetName(e)}addTargetName(e){if(Array.isArray(e))for(const t of e)this._targetNames.add(t);else this._targetNames.add(e)}removeTargetName(e){if(Array.isArray(e))for(const t of e)this._targetNames.delete(t);else this._targetNames.delete(e)}hasTarget(e){return this._targetNames.has(e)}retainsTarget(e){return this._targetNames.has(e)===(this.mode===Wr.Include)}}function bn(e,t,i){try{const s=e.next();s.done?t(s):s.value?s.value.then((()=>{s.value=void 0,t(s)}),i):t(s)}catch(e){i(e)}}function Tn(e=25){let t;return(i,s,r)=>{const n=performance.now();void 0===t||n-t>e?(t=n,setTimeout((()=>{bn(i,s,r)}),0)):bn(i,s,r)}}function yn(e,t,i,s,r){const n=()=>{let o;const a=e=>{e.done?i(e.value):void 0===o?o=!0:n()};do{o=void 0,r&&r.aborted?s(new Error("Aborted")):t(e,a,s),void 0===o&&(o=!1)}while(o)};n()}function Sn(e,t){let i;return yn(e,bn,(e=>i=e),(e=>{throw e}),t),i}function Cn(e,t,i){return new Promise(((s,r)=>{yn(e,t,s,r,i)}))}function En(e,t){return(...i)=>Sn(e(...i),t)}function An(e,t,i){return(...s)=>Cn(e(...s),t,i)}class Pn{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new Pn(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new Pn(this.x,this.y,this.width,this.height)}}class In extends Et{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){let e=0,t=0;if(this.mode===In.PERSPECTIVE_CAMERA)this.fovMode===In.FOVMODE_VERTICAL_FIXED?(t=2*this.minZ*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=2*this.minZ*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const i=this.getEngine().getRenderWidth()/2,s=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??s)-(this.orthoBottom??-s)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,s=!0){super(e,i,!1),this._position=_e.Zero(),this._upVector=_e.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=In.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new Pn(0,0,1,1),this.layerMask=268435455,this.fovMode=In.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=In.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new K,this.onProjectionMatrixChangedObservable=new K,this.onAfterCheckInputsObservable=new K,this.onRestoreStateObservable=new K,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new me,this._postProcesses=new Array,this._activeMeshes=new Fs(256),this._globalPosition=_e.Zero(),this._computedViewMatrix=me.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=me.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=fe.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),s&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i-1?(Ne.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))}detachPostProcess(e){const t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()||this.getViewMatrix(),this._worldMatrix}_getViewMatrix(){return me.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix)),this._computedViewMatrix}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const t=this.getEngine(),i=this.getScene(),s=t.useReverseDepthBuffer;if(this.mode===In.PERSPECTIVE_CAMERA){let e;this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=t.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),e=i.useRightHandedSystem?me.PerspectiveFovRHToRef:me.PerspectiveFovLHToRef,e(this.fov,t.getAspectRatio(this),s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===In.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{const e=t.getRenderWidth()/2,r=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?me.ObliqueOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):me.OrthoOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?me.ObliqueOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):me.OrthoOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=this.oblique?.angle,this._cache.obliqueLength=this.oblique?.length,this._cache.obliqueOffset=this.oblique?.offset,this._cache.renderWidth=t.getRenderWidth(),this._cache.renderHeight=t.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){return(this.radius||(this.target?_e.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?Fr.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Fr.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;return this.rigCameras.forEach((i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)})),t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw xt("Ray")}getForwardRayToRef(e,t=100,i,s){throw xt("Ray")}dispose(e,t=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){const e=this._parentContainer.cameras.indexOf(this);e>-1&&this._parentContainer.cameras.splice(e,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==In.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){const t=this._postProcesses[e];t&&t.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),super.dispose(e,t)}get isLeftCamera(){return this._isLeftCamera}get isRightCamera(){return this._isRightCamera}get leftCamera(){return this._rigCameras.length<1?null:this._rigCameras[0]}get rightCamera(){return this._rigCameras.length<2?null:this._rigCameras[1]}getLeftTarget(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()}getRightTarget(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()}setCameraRigMode(e,t){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=Ds.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==In.RIG_MODE_NONE){const e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);const t=this.createRigCamera(this.name+"_R",1);t&&(t._isRightCamera=!0),e&&t&&(this._rigCameras.push(e),this._rigCameras.push(t))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return me.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=Ds.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eIn._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=In.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=St.Parse(s,e,t);if(void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=_e.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(_e.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(_e.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t{throw xt("UniversalCamera")},In.PERSPECTIVE_CAMERA=0,In.ORTHOGRAPHIC_CAMERA=1,In.FOVMODE_VERTICAL_FIXED=0,In.FOVMODE_HORIZONTAL_FIXED=1,In.RIG_MODE_NONE=0,In.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,In.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,In.RIG_MODE_STEREOSCOPIC_INTERLACED=14,In.RIG_MODE_VR=20,In.RIG_MODE_CUSTOM=22,In.ForceAttachControlToAlwaysPreventDefault=!1,Ze([ht("position")],In.prototype,"_position",void 0),Ze([ht("upVector")],In.prototype,"_upVector",void 0),Ze([rt()],In.prototype,"orthoLeft",null),Ze([rt()],In.prototype,"orthoRight",null),Ze([rt()],In.prototype,"orthoBottom",null),Ze([rt()],In.prototype,"orthoTop",null),Ze([rt()],In.prototype,"fov",void 0),Ze([rt()],In.prototype,"projectionPlaneTilt",void 0),Ze([rt()],In.prototype,"minZ",void 0),Ze([rt()],In.prototype,"maxZ",void 0),Ze([rt()],In.prototype,"inertia",void 0),Ze([rt()],In.prototype,"mode",null),Ze([rt()],In.prototype,"layerMask",void 0),Ze([rt()],In.prototype,"fovMode",void 0),Ze([rt()],In.prototype,"cameraRigMode",void 0),Ze([rt()],In.prototype,"interaxialDistance",void 0),Ze([rt()],In.prototype,"isStereoscopicSideBySide",void 0);class Rn{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class Mn{constructor(e,t,i){this.vectors=ee.BuildArray(8,_e.Zero),this.center=_e.Zero(),this.centerWorld=_e.Zero(),this.extendSize=_e.Zero(),this.extendSizeWorld=_e.Zero(),this.directions=ee.BuildArray(3,_e.Zero),this.vectorsWorld=ee.BuildArray(8,_e.Zero),this.minimumWorld=_e.Zero(),this.maximumWorld=_e.Zero(),this.minimum=_e.Zero(),this.maximum=_e.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,r=e.y,n=e.z,o=t.x,a=t.y,l=t.z,h=this.vectors;this.minimum.copyFromFloats(s,r,n),this.maximum.copyFromFloats(o,a,l),h[0].copyFromFloats(s,r,n),h[1].copyFromFloats(o,a,l),h[2].copyFromFloats(o,r,n),h[3].copyFromFloats(s,a,n),h[4].copyFromFloats(s,r,l),h[5].copyFromFloats(o,a,n),h[6].copyFromFloats(s,a,l),h[7].copyFromFloats(o,r,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||me.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=Mn._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const r=s*e,n=i.scaleInPlace(.5*r),o=this.center.subtractToRef(n,t[1]),a=this.center.addToRef(n,t[2]);return this.reConstruct(o,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,s=this.directions,r=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)r[e].copyFrom(n[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let s=0;s<8;++s){const o=r[s];_e.TransformCoordinatesToRef(n[s],e,o),t.minimizeInPlace(o),i.maximizeInPlace(o)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}_e.FromArrayToRef(e.m,0,s[0]),_e.FromArrayToRef(e.m,4,s[1]),_e.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return Mn.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return Mn.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,r=t.y,n=t.z,o=i.x,a=i.y,l=i.z,h=e.x,c=e.y,u=e.z,d=-J;return!(o-hh-s||a-cc-r||l-uu-n)}intersectsSphere(e){return Mn.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,r=i.x,n=i.y,o=i.z,a=s.x,l=s.y,h=s.z,c=e.x,u=e.y,d=e.z,_=t.x,p=t.y,f=t.z;return!(a_||lp||hf)}dispose(){this._drawWrapperFront?.dispose(),this._drawWrapperBack?.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const r=Mn._TmpVector3[0];return _e.ClampToRef(i,e,t,r),_e.DistanceSquared(i,r)<=s*s}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let s=!0;const r=t[i];for(let t=0;t<8;++t)if(r.dotCoordinate(e[t])>=0){s=!1;break}if(s)return!1}return!0}}Mn._TmpVector3=ee.BuildArray(3,_e.Zero);class On{constructor(e,t,i){this.center=_e.Zero(),this.centerWorld=_e.Zero(),this.minimum=_e.Zero(),this.maximum=_e.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=_e.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*s,this._update(i||me.IdentityReadOnly)}scale(e){const t=this.radius*e,i=On._TmpVector3,s=i[0].setAll(t),r=this.center.subtractToRef(s,i[1]),n=this.center.addToRef(s,i[2]);return this.reConstruct(r,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{_e.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=On._TmpVector3[0];_e.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,i=this.radiusWorld;for(let s=0;s<6;s++)if(e[s].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=_e.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const s=_e.Dot(t.centerWorld,e),r=Math.abs(_e.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(_e.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(_e.Dot(t.directions[2],e))*t.extendSize.z;i.min=s-r,i.max=s+r},Fn=(e,t,i)=>(Nn(e,t,Dn),Nn(e,i,wn),!(Dn.min>wn.max||wn.min>Dn.max));class Ln{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new Mn(e,t,i),this.boundingSphere=new On(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}get minimum(){return this.boundingBox.minimum}get maximum(){return this.boundingBox.maximum}get isLocked(){return this._isLocked}set isLocked(e){this._isLocked=e}update(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))}centerOn(e,t){const i=Ln._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=Ln._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=_e.Minimize(this.minimum,e),i=_e.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=ve.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=ve.Vector3[0];return _e.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),_e.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return!(2!==t&&3!==t||!this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(!(1!==t&&3!==t)||this.boundingBox.isInFrustum(e))}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,Ln._TmpVector3[0]).length()}isCompletelyInFrustum(e){return this.boundingBox.isCompletelyInFrustum(e)}_checkCollision(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)}intersectsPoint(e){return!!this.boundingSphere.centerWorld&&!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e)}intersects(e,t){if(!On.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!Mn.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!!(Fn(i.directions[0],i,s)&&Fn(i.directions[1],i,s)&&Fn(i.directions[2],i,s)&&Fn(s.directions[0],i,s)&&Fn(s.directions[1],i,s)&&Fn(s.directions[2],i,s)&&Fn(_e.Cross(i.directions[0],s.directions[0]),i,s)&&Fn(_e.Cross(i.directions[0],s.directions[1]),i,s)&&Fn(_e.Cross(i.directions[0],s.directions[2]),i,s)&&Fn(_e.Cross(i.directions[1],s.directions[0]),i,s)&&Fn(_e.Cross(i.directions[1],s.directions[1]),i,s)&&Fn(_e.Cross(i.directions[1],s.directions[2]),i,s)&&Fn(_e.Cross(i.directions[2],s.directions[0]),i,s)&&Fn(_e.Cross(i.directions[2],s.directions[1]),i,s)&&Fn(_e.Cross(i.directions[2],s.directions[2]),i,s))}}Ln._TmpVector3=ee.BuildArray(2,_e.Zero);class Bn{static extractMinAndMaxIndexed(e,t,i,s,r,n){for(let o=i;o!Array.isArray(e)&&!Array.isArray(t)))],Bn,"extractMinAndMaxIndexed",null),Ze([gt.filter(((...[e])=>!Array.isArray(e)))],Bn,"extractMinAndMax",null);class Un{static GetEffect(e){return void 0===e.getPipelineContext?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){this.effect=e,void 0!==t&&(this.defines=t),i&&this.drawContext?.reset()}dispose(){this.drawContext?.dispose()}}class Gn{get materialDefines(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:this._getDrawWrapper()?.defines}set materialDefines(e){(this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new Un(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){t&&this._drawWrappers[e]?.dispose(),this._drawWrappers[e]=void 0}get effect(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:this._getDrawWrapper()?.effect??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,s=!0){const r=this._drawWrapper;r.setEffect(e,t,s),void 0!==i&&(r.materialContext=i),e||(r.defines=null,r.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)e?.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,s,r,n,o,a=!0){return new Gn(e,t,i,s,r,n,o,a)}constructor(e,t,i,s,r,n,o,a=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=s,this.indexCount=r,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=o||n,l&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,a&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){return(this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null)||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(!t)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(t)){const e=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return t}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(er.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();i={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else i=kn(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new Ln(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const i=[];for(let t=this.indexStart;ta&&(a=t)}return new Gn(e,o,a-o+1,t,i,s,r,n)}}class zn{}class Wn{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=En(this._applyToCoroutine.bind(this)),this.uniqueId=Wn._UniqueIDGenerator,Wn._UniqueIDGenerator++}set(e,t){switch(e.length||Ne.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case er.PositionKind:this.positions=e;break;case er.NormalKind:this.normals=e;break;case er.TangentKind:this.tangents=e;break;case er.UVKind:this.uvs=e;break;case er.UV2Kind:this.uvs2=e;break;case er.UV3Kind:this.uvs3=e;break;case er.UV4Kind:this.uvs4=e;break;case er.UV5Kind:this.uvs5=e;break;case er.UV6Kind:this.uvs6=e;break;case er.ColorKind:this.colors=e;break;case er.MatricesIndicesKind:this.matricesIndices=e;break;case er.MatricesWeightsKind:this.matricesWeights=e;break;case er.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case er.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){if(this.positions&&(e.setVerticesData(er.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(er.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(er.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(er.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(er.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(er.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(er.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(er.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(er.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(er.ColorKind,this.colors,t),this.hasVertexAlpha&&void 0!==e.hasVertexAlpha&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(er.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(er.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(er.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(er.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){const t=e;t.subMeshes=[];for(const e of this.materialInfos)new Gn(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,t)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(er.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(er.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(er.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(er.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(er.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(er.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(er.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(er.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(er.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(er.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(er.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(er.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(er.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(er.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const r=ve.Vector3[0],n=ve.Vector3[1];for(let o=i;o({vertexData:e}))):[{vertexData:e}];return Sn(this._mergeCoroutine(void 0,n,t,!1,i,s,r))}*_mergeCoroutine(e,t,i=!1,s,r,n=!1,o=!1){this._validate();let a=t.map((e=>e.vertexData)),l=this;if(o)for(const e of a)e&&(e._validate(),!this.normals&&e.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&e.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&e.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&e.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&e.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&e.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&e.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&e.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&e.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&e.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&e.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&e.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&e.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const e of a)if(e)if(o)this.normals&&!e.normals&&(e.normals=new Float32Array(e.positions.length)),this.tangents&&!e.tangents&&(e.tangents=new Float32Array(e.positions.length/3*4)),this.uvs&&!e.uvs&&(e.uvs=new Float32Array(e.positions.length/3*2)),this.uvs2&&!e.uvs2&&(e.uvs2=new Float32Array(e.positions.length/3*2)),this.uvs3&&!e.uvs3&&(e.uvs3=new Float32Array(e.positions.length/3*2)),this.uvs4&&!e.uvs4&&(e.uvs4=new Float32Array(e.positions.length/3*2)),this.uvs5&&!e.uvs5&&(e.uvs5=new Float32Array(e.positions.length/3*2)),this.uvs6&&!e.uvs6&&(e.uvs6=new Float32Array(e.positions.length/3*2)),this.colors&&!e.colors&&(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)),this.matricesIndices&&!e.matricesIndices&&(e.matricesIndices=new Float32Array(e.positions.length/3*4)),this.matricesWeights&&!e.matricesWeights&&(e.matricesWeights=new Float32Array(e.positions.length/3*4)),this.matricesIndicesExtra&&!e.matricesIndicesExtra&&(e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4)),this.matricesWeightsExtra&&!e.matricesWeightsExtra&&(e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4));else if(e._validate(),!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");if(n){let i=0,s=0,r=0;const n=[];let o=null;const h=[];for(const t of this.splitBasedOnMaterialID())h.push({vertexData:t,transform:e});for(const e of t)if(e.vertexData)for(const t of e.vertexData.splitBasedOnMaterialID())h.push({vertexData:t,transform:e.transform});h.sort(((e,t)=>{const i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,s=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>s?1:i===s?0:-1}));for(const e of h){const t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,o&&o.materialIndex===i)o.indexCount+=t.indices.length,o.verticesCount+=t.positions.length/3;else{const e=new zn;e.materialIndex=i,e.indexStart=s,e.indexCount=t.indices.length,e.verticesStart=r,e.verticesCount=t.positions.length/3,n.push(e),o=e}s+=t.indices.length,r+=t.positions.length/3}const c=h.splice(0,1)[0];l=c.vertexData,e=c.transform,a=h.map((e=>e.vertexData)),t=h,this.materialInfos=n}const h=a.reduce(((e,t)=>e+(t.indices?.length??0)),l.indices?.length??0);let c=r||a.some((e=>e.indices===l.indices))?l.indices?.slice():l.indices;if(h>0){let r=c?.length??0;if(c||(c=new Array(h)),c.length!==h){if(Array.isArray(c))c.length=h;else{const e=i||c instanceof Uint32Array?new Uint32Array(h):new Uint16Array(h);e.set(c),c=e}e&&e.determinant()<0&&Wn._FlipFaces(c,0,r)}let n=l.positions?l.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t[e.vertexData.positions,e.transform]))),s&&(yield),l.normals&&(this.normals=Wn._MergeElement(er.NormalKind,l.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),s&&(yield)),l.tangents&&(this.tangents=Wn._MergeElement(er.TangentKind,l.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),s&&(yield)),l.uvs&&(this.uvs=Wn._MergeElement(er.UVKind,l.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),s&&(yield)),l.uvs2&&(this.uvs2=Wn._MergeElement(er.UV2Kind,l.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),s&&(yield)),l.uvs3&&(this.uvs3=Wn._MergeElement(er.UV3Kind,l.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),s&&(yield)),l.uvs4&&(this.uvs4=Wn._MergeElement(er.UV4Kind,l.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),s&&(yield)),l.uvs5&&(this.uvs5=Wn._MergeElement(er.UV5Kind,l.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),s&&(yield)),l.uvs6&&(this.uvs6=Wn._MergeElement(er.UV6Kind,l.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),s&&(yield)),l.colors&&(this.colors=Wn._MergeElement(er.ColorKind,l.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),(void 0!==l.hasVertexAlpha||t.some((e=>void 0!==e.vertexData.hasVertexAlpha)))&&(this.hasVertexAlpha=l.hasVertexAlpha||t.some((e=>e.vertexData.hasVertexAlpha))),s&&(yield)),l.matricesIndices&&(this.matricesIndices=Wn._MergeElement(er.MatricesIndicesKind,l.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),s&&(yield)),l.matricesWeights&&(this.matricesWeights=Wn._MergeElement(er.MatricesWeightsKind,l.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),s&&(yield)),l.matricesIndicesExtra&&(this.matricesIndicesExtra=Wn._MergeElement(er.MatricesIndicesExtraKind,l.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),s&&(yield)),l.matricesWeightsExtra&&(this.matricesWeightsExtra=Wn._MergeElement(er.MatricesWeightsExtraKind,l.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform])))),this}static _MergeElement(e,t,i,s){const r=s.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==r.length)return t;if(!t)return this._MergeElement(e,r[0][0],r[0][1],r.slice(1));const n=r.reduce(((e,t)=>e+t[0].length),t.length),o=e===er.PositionKind?Wn._TransformVector3Coordinates:e===er.NormalKind?Wn._TransformVector3Normals:e===er.TangentKind?Wn._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(n);e.set(t),i&&o(e,i,0,t.length);let s=t.length;for(const[t,i]of r)e.set(t,s),i&&o(e,i,s,t.length),s+=t.length;return e}{const e=new Array(n);for(let i=0;i{const i=er.DeduceStride(e);if(t.length%i!=0)throw new Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(er.PositionKind,this.positions),i=(i,s)=>{const r=e(i,s);if(r!==t)throw new Error("The "+i+"s element count ("+r+") does not match the positions count ("+t+")")};this.normals&&i(er.NormalKind,this.normals),this.tangents&&i(er.TangentKind,this.tangents),this.uvs&&i(er.UVKind,this.uvs),this.uvs2&&i(er.UV2Kind,this.uvs2),this.uvs3&&i(er.UV3Kind,this.uvs3),this.uvs4&&i(er.UV4Kind,this.uvs4),this.uvs5&&i(er.UV5Kind,this.uvs5),this.uvs6&&i(er.UV6Kind,this.uvs6),this.colors&&i(er.ColorKind,this.colors),this.matricesIndices&&i(er.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(er.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(er.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(er.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return Wn.Parse(e)}serialize(){const e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos){e.materialInfos=[];for(const t of this.materialInfos){const i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return Wn._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return Wn._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new Wn;return e.isVerticesDataPresent(er.PositionKind)&&(s.positions=e.getVerticesData(er.PositionKind,t,i)),e.isVerticesDataPresent(er.NormalKind)&&(s.normals=e.getVerticesData(er.NormalKind,t,i)),e.isVerticesDataPresent(er.TangentKind)&&(s.tangents=e.getVerticesData(er.TangentKind,t,i)),e.isVerticesDataPresent(er.UVKind)&&(s.uvs=e.getVerticesData(er.UVKind,t,i)),e.isVerticesDataPresent(er.UV2Kind)&&(s.uvs2=e.getVerticesData(er.UV2Kind,t,i)),e.isVerticesDataPresent(er.UV3Kind)&&(s.uvs3=e.getVerticesData(er.UV3Kind,t,i)),e.isVerticesDataPresent(er.UV4Kind)&&(s.uvs4=e.getVerticesData(er.UV4Kind,t,i)),e.isVerticesDataPresent(er.UV5Kind)&&(s.uvs5=e.getVerticesData(er.UV5Kind,t,i)),e.isVerticesDataPresent(er.UV6Kind)&&(s.uvs6=e.getVerticesData(er.UV6Kind,t,i)),e.isVerticesDataPresent(er.ColorKind)&&(s.colors=e.getVerticesData(er.ColorKind,t,i)),e.isVerticesDataPresent(er.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(er.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(er.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(er.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(er.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(er.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(er.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(er.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw xt("ribbonBuilder")}static CreateBox(e){throw xt("boxBuilder")}static CreateTiledBox(e){throw xt("tiledBoxBuilder")}static CreateTiledPlane(e){throw xt("tiledPlaneBuilder")}static CreateSphere(e){throw xt("sphereBuilder")}static CreateCylinder(e){throw xt("cylinderBuilder")}static CreateTorus(e){throw xt("torusBuilder")}static CreateLineSystem(e){throw xt("linesBuilder")}static CreateDashedLines(e){throw xt("linesBuilder")}static CreateGround(e){throw xt("groundBuilder")}static CreateTiledGround(e){throw xt("groundBuilder")}static CreateGroundFromHeightMap(e){throw xt("groundBuilder")}static CreatePlane(e){throw xt("planeBuilder")}static CreateDisc(e){throw xt("discBuilder")}static CreatePolygon(e,t,i,s,r,n,o){throw xt("polygonBuilder")}static CreateIcoSphere(e){throw xt("icoSphereBuilder")}static CreatePolyhedron(e){throw xt("polyhedronBuilder")}static CreateCapsule(e={orientation:_e.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw xt("capsuleBuilder")}static CreateTorusKnot(e){throw xt("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let r=0,n=0,o=0,a=0,l=0,h=0,c=0,u=0,d=0,_=0,p=0,f=0,m=0,g=0,v=0,x=0,b=0,T=0,y=0,S=0,C=!1,E=!1,A=!1,P=!1,I=1,R=0,M=null;s&&(C=!!s.facetNormals,E=!!s.facetPositions,A=!!s.facetPartitioning,I=!0===s.useRightHandedSystem?-1:1,R=s.ratio||0,P=!!s.depthSort,M=s.distanceTo,P&&void 0===M&&(M=_e.Zero()));let O=0,D=0,w=0,N=0;for(A&&s&&s.bbSize&&(O=s.subDiv.X*R/s.bbSize.x,D=s.subDiv.Y*R/s.bbSize.y,w=s.subDiv.Z*R/s.bbSize.z,N=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),r=0;r!Array.isArray(e)))],Wn,"_TransformVector3Coordinates",null),Ze([gt.filter(((...[e])=>!Array.isArray(e)))],Wn,"_TransformVector3Normals",null),Ze([gt.filter(((...[e])=>!Array.isArray(e)))],Wn,"_TransformVector4Normals",null),Ze([gt.filter(((...[e])=>!Array.isArray(e)))],Wn,"_FlipFaces",null);class Hn{static get ForceFullSceneLoadingForIncremental(){return Hn._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Hn._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Hn._ShowLoadingScreen}static set ShowLoadingScreen(e){Hn._ShowLoadingScreen=e}static get loggingLevel(){return Hn._LoggingLevel}static set loggingLevel(e){Hn._LoggingLevel=e}static get CleanBoneMatrixWeights(){return Hn._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Hn._CleanBoneMatrixWeights=e}}Hn._ForceFullSceneLoadingForIncremental=!1,Hn._ShowLoadingScreen=!0,Hn._CleanBoneMatrixWeights=!1,Hn._LoggingLevel=0;class Xn{}Xn.UseOpenGLOrientationForUV=!1;class Yn{get boundingBias(){return this._boundingBias}set boundingBias(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)}static CreateGeometryForMesh(e){const t=new Yn(Yn.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,s=!1,r=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||re.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=s,i?this.setAllVerticesData(i,s):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e{e._rebuild()}))}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,s){i&&Array.isArray(t)&&(t=new Float32Array(t));const r=new er(this._engine,t,e,{updatable:i,postponeInternalCreation:0===this._meshes.length,stride:s,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(r)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const s=e.getKind();this._vertexBuffers[s]&&i&&this._vertexBuffers[s].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[s]=e;const r=this._meshes,n=r.length;if(s===er.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const i=this._extend&&this._extend.minimum||new _e(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),s=this._extend&&this._extend.maximum||new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e65535);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),null!=t&&(this._totalVertices=t);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?void 0!==this._totalIndices?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){e&&this._vertexArrayObjects&&this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const i=this._meshes,s=i.indexOf(e);-1!==s&&(i.splice(s,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;const t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();const i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&!(e=this.getVerticesData(er.PositionKind)))return;this._extend=Vn(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===er.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const e of this._meshes)e._markSubMeshesAsAttributesDirty()}load(e,t){2!==this.delayLoadState&&(this.isReady()?t&&t():(this.delayLoadState=2,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const s=this._meshes,r=s.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new Wn;t.indices=[];const i=this.getIndices();if(i)for(let e=0;e0){const s=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(er.PositionKind,s,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const s=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(er.NormalKind,s,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const s=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(er.TangentKind,s,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const s=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(Xn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(Xn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(Xn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(Xn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(Xn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(Xn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(er.ColorKind,s,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(er.MatricesIndicesKind,r,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(er.MatricesIndicesExtraKind,r,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const s=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(er.MatricesWeightsKind,s,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){const s=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(s,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){const s=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(er.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(er.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(er.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(Yn._CleanMatricesWeights(e,t),t.setVerticesData(er.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(er.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;s=i.bones.length}const r=t.getVerticesData(er.MatricesIndicesKind),n=t.getVerticesData(er.MatricesIndicesExtraKind),o=e.matricesWeights,a=e.matricesWeightsExtra,l=e.numBoneInfluencer,h=o.length;for(let e=0;el-1)&&(h=l-1),t>i){const i=1/t;for(let t=0;t<4;t++)o[e+t]*=i;if(a)for(let t=0;t<4;t++)a[e+t]*=i}else h>=4?(a[e+h-4]=1-t,n[e+h-4]=s):(o[e+h]=1-t,r[e+h]=s)}t.setVerticesData(er.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(er.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const s=new Yn(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,Tt&&Tt.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new Ln(_e.FromArray(e.boundingBoxMinimum),_e.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(er.UVKind),e.hasUVs2&&s._delayInfo.push(er.UV2Kind),e.hasUVs3&&s._delayInfo.push(er.UV3Kind),e.hasUVs4&&s._delayInfo.push(er.UV4Kind),e.hasUVs5&&s._delayInfo.push(er.UV5Kind),e.hasUVs6&&s._delayInfo.push(er.UV6Kind),e.hasColors&&s._delayInfo.push(er.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(er.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(er.MatricesWeightsKind),s._delayLoadingFunction=Wn.ImportVertexData):Wn.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}class Qn{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new jn(e)}sampleFrame(e=Wt.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){const t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}}get averageFrameTime(){return this._rollingFrameTime.average}get averageFrameTimeVariance(){return this._rollingFrameTime.variance}get instantaneousFrameTime(){return this._rollingFrameTime.history(0)}get averageFPS(){return 1e3/this._rollingFrameTime.average}get instantaneousFPS(){const e=this._rollingFrameTime.history(0);return 0===e?0:1e3/e}get isSaturated(){return this._rollingFrameTime.isSaturated()}enable(){this._enabled=!0}disable(){this._enabled=!1,this._lastFrameTimeMs=null}get isEnabled(){return this._enabled}reset(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()}}class jn{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const e=this._samples[this._pos];t=e-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(e-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length}history(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;const t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]}isSaturated(){return this._sampleCount>=this._samples.length}reset(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0}_wrapPosition(e){const t=this._samples.length;return(e%t+t)%t}}function Kn(e,t,i=!1,s){switch(e){case 3:{const e=(ArrayBuffer,new Int8Array(t));return s&&e.set(new Int8Array(s)),e}case 0:{const e=(ArrayBuffer,new Uint8Array(t));return s&&e.set(new Uint8Array(s)),e}case 4:{const e=t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);return s&&e.set(new Int16Array(s)),e}case 5:case 8:case 9:case 10:case 2:{const e=t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);return s&&e.set(new Uint16Array(s)),e}case 6:{const e=t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);return s&&e.set(new Int32Array(s)),e}case 7:case 11:case 12:case 13:case 14:case 15:{const e=t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);return s&&e.set(new Uint32Array(s)),e}case 1:{const e=t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t);return s&&e.set(new Float32Array(s)),e}}const r=(ArrayBuffer,new Uint8Array(t));return s&&r.set(new Uint8Array(s)),r}function $n(e,t,i){e._onCanvasFocus=()=>{e.onCanvasFocusObservable.notifyObservers(e)},e._onCanvasBlur=()=>{e.onCanvasBlurObservable.notifyObservers(e)},e._onCanvasContextMenu=t=>{e.disableContextMenu&&t.preventDefault()},t.addEventListener("focus",e._onCanvasFocus),t.addEventListener("blur",e._onCanvasBlur),t.addEventListener("contextmenu",e._onCanvasContextMenu),e._onBlur=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.disable(),e._windowIsBackground=!0},e._onFocus=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.enable(),e._windowIsBackground=!1},e._onCanvasPointerOut=i=>{document.elementFromPoint(i.clientX,i.clientY)!==t&&e.onCanvasPointerOutObservable.notifyObservers(i)};const s=e.getHostWindow();s&&"function"==typeof s.addEventListener&&(s.addEventListener("blur",e._onBlur),s.addEventListener("focus",e._onFocus)),t.addEventListener("pointerout",e._onCanvasPointerOut),i.doNotHandleTouchAction||function(e){e&&e.setAttribute&&(e.setAttribute("touch-action","none"),e.style.touchAction="none",e.style.webkitTapHighlightColor="transparent")}(t),!ns.audioEngine&&i.audioEngine&&ns.AudioEngineFactory&&(ns.audioEngine=ns.AudioEngineFactory(e.getRenderingCanvas(),e.getAudioContext(),e.getAudioDestination())),Ut()&&(e._onFullscreenChange=()=>{e.isFullscreen=!!document.fullscreenElement,e.isFullscreen&&e._pointerLockRequested&&t&&so(t)},document.addEventListener("fullscreenchange",e._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",e._onFullscreenChange,!1),e._onPointerLockChange=()=>{e.isPointerLock=document.pointerLockElement===t},document.addEventListener("pointerlockchange",e._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",e._onPointerLockChange,!1)),e.enableOfflineSupport=void 0!==ns.OfflineProviderFactory,e._deterministicLockstep=!!i.deterministicLockstep,e._lockstepMaxSteps=i.lockstepMaxSteps||0,e._timeStep=i.timeStep||1/60}function qn(e,t){1===re.Instances.length&&ns.audioEngine&&(ns.audioEngine.dispose(),ns.audioEngine=null);const i=e.getHostWindow();i&&"function"==typeof i.removeEventListener&&(i.removeEventListener("blur",e._onBlur),i.removeEventListener("focus",e._onFocus)),t&&(t.removeEventListener("focus",e._onCanvasFocus),t.removeEventListener("blur",e._onCanvasBlur),t.removeEventListener("pointerout",e._onCanvasPointerOut),t.removeEventListener("contextmenu",e._onCanvasContextMenu)),Ut()&&(document.removeEventListener("fullscreenchange",e._onFullscreenChange),document.removeEventListener("mozfullscreenchange",e._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",e._onFullscreenChange),document.removeEventListener("msfullscreenchange",e._onFullscreenChange),document.removeEventListener("pointerlockchange",e._onPointerLockChange),document.removeEventListener("mspointerlockchange",e._onPointerLockChange),document.removeEventListener("mozpointerlockchange",e._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",e._onPointerLockChange))}function Zn(e){const t=document.createElement("span");t.textContent="Hg",t.style.font=e;const i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";const s=document.createElement("div");s.style.whiteSpace="nowrap",s.appendChild(t),s.appendChild(i),document.body.appendChild(s);let r=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",r=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(s)}return{ascent:r,height:n,descent:n-r}}function Jn(e,t,i){return new Promise(((s,r)=>{const n=new Image;n.onload=()=>{n.decode().then((()=>{e.createImageBitmap(n,i).then((e=>{s(e)}))}))},n.onerror=()=>{r(`Error loading image ${n.src}`)},n.src=t}))}function eo(e,t,i,s){const r=e.createCanvas(i,s).getContext("2d");if(!r)throw new Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(t,0,0),r.getImageData(0,0,i,s).data}function to(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}function io(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}function so(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}function ro(){document.exitPointerLock&&document.exitPointerLock()}qs.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode!==e){switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0}t||(this.depthCullingState.depthMask=0===e),this._alphaMode=e}else if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}},qs.prototype._readTexturePixelsSync=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=c.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),s>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+s,e._hardwareTexture?.underlyingResource,r):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,e._hardwareTexture?.underlyingResource,r);let u=void 0!==e.type?this._getWebGLTextureType(e.type):c.UNSIGNED_BYTE;return a?n||(n=Kn(e.type,4*t*i)):u===c.UNSIGNED_BYTE?(n||(n=new Uint8Array(4*t*i)),u=c.UNSIGNED_BYTE):(n||(n=new Float32Array(4*t*i)),u=c.FLOAT),o&&this.flushFramebuffer(),c.readPixels(l,h,t,i,c.RGBA,u,n),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),n},qs.prototype._readTexturePixels=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,s,r,n,o,a,l,h))},qs.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let s;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),s=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,s,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},qs.prototype.updateDynamicVertexBuffer=function(e,t,i,s){this.bindArrayBuffer(e),void 0===i&&(i=0);const r=t.byteLength||t.length;void 0===s||s>=r&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+s)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,s):new Uint8Array(t.buffer,t.byteOffset+i,s),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()},ns.prototype.displayLoadingUI=function(){if(!kt())return;const e=this.loadingScreen;e&&e.displayLoadingUI()},ns.prototype.hideLoadingUI=function(){if(!kt())return;const e=this._loadingScreen;e&&e.hideLoadingUI()},Object.defineProperty(ns.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=ns.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(ns.prototype,"loadingUIText",{set:function(e){this.loadingScreen.loadingUIText=e},enumerable:!0,configurable:!0}),Object.defineProperty(ns.prototype,"loadingUIBackgroundColor",{set:function(e){this.loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),ns.prototype.getInputElement=function(){return this._renderingCanvas},ns.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null},ns.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null},ns.prototype.getAspectRatio=function(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)},ns.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)},ns.prototype._verifyPointerLock=function(){this._onPointerLockChange?.()},ns.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774)}this._alphaEquation=e}},ns.prototype.getInputElement=function(){return this._renderingCanvas},ns.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},ns.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},ns.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)},ns.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)},ns.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)},ns.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)},ns.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},ns.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},ns.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},ns.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},ns.prototype.getStencilMask=function(){return this._stencilState.stencilMask},ns.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},ns.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},ns.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},ns.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},ns.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},ns.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},ns.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},ns.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},ns.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},ns.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},ns.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},ns.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},ns.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},ns.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()},ns.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)},ns.prototype.setAlphaConstants=function(e,t,i,s){this._alphaState.setAlphaBlendConstants(e,t,i,s)},ns.prototype.getAlphaMode=function(){return this._alphaMode},ns.prototype.getAlphaEquation=function(){return this._alphaEquation},ns.prototype.getRenderPassNames=function(){return this._renderPassNames},ns.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]},ns.prototype.createRenderPassId=function(e){const t=++ns._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t},ns.prototype.releaseRenderPassId=function(e){this._renderPassNames[e]=void 0;for(let t=0;tnew no(e,t,i);class no{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new K,this.onAudioLockedObservable=new K,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!kt())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);const s=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{s&&s.canPlayType&&(s.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||s.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{s&&s.canPlayType&&s.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){if("running"===this._audioContext?.state)return this._hideMuteButton(),void(this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)));this._tryToRun?this._audioContext?.suspend().then((()=>{this._tryToRun=!1,this._triggerRunningState()})):this._triggerRunningState()}_resumeAudioContext(){return this._audioContext?.resume?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,Ne.Error("Web Audio: "+e.message)}}_triggerRunningState(){this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then((()=>{this._tryToRun=!1,this._muteButton&&this._hideMuteButton(),this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)})).catch((()=>{this._tryToRun=!1,this.unlocked=!1})))}_triggerSuspendedState(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()}_displayMuteButton(){if(this.useCustomUnlockedButton||this._muteButton)return;this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";const e=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",(()=>{this._triggerRunningState()}),!0),this._muteButton.addEventListener("click",(()=>{this.unlock()}),!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}}class oo extends qs{static get NpmPackage(){return ns.NpmPackage}static get Version(){return ns.Version}static get Instances(){return re.Instances}static get LastCreatedEngine(){return re.LastCreatedEngine}static get LastCreatedScene(){return re.LastCreatedScene}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{this._loadFile(e,(e=>{s(e)}),void 0,t,i,((e,t)=>{r(t)}))}))}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return Zn(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(0!==this._frameHandler){this._frameHandler=0;const{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}enterPointerlock(){this._renderingCanvas&&so(this._renderingCanvas)}exitPointerlock(){ro()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){const t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,s,r,n=null){r=r||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const o=super.createShaderProgram(e,t,i,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),o}_createShaderProgram(e,t,i,s,r=null){const n=s.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");if(s.attachShader(n,t),s.attachShader(n,i),this.webGLVersion>1&&r){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=t}return s.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach((t=>{t.postProcesses.forEach((t=>{t._outputTexture===e&&(t._outputTexture=null)})),t.cameras.forEach((t=>{t._postProcesses.forEach((t=>{t&&t._outputTexture===e&&(t._outputTexture=null)}))}))}))}_rescaleTexture(e,t,i,s,r){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);const n=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&oo._RescalePostProcessFactory&&(this._rescalePostProcess=oo._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled((()=>{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let o=i;o||(o=this.scenes[this.scenes.length-1]),o.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()})))}wrapWebGLTexture(e,t=!1,i=3,s=0,r=0){const n=new Ks(e,this._gl),o=new ss(this,is.Unknown,!0);return o._hardwareTexture=n,o.baseWidth=s,o.baseHeight=r,o.width=s,o.height=r,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,s=0){const r=this._gl,n=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,o),l=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=r.TEXTURE_2D;e.isCube&&(h=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(h,s,a,o,n,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void Ne.Error("WebGL 1 does not support texture comparison.");const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");const i=new js(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const s=this._gl;return new Promise(((r,n)=>{const o=()=>{const a=s.clientWaitSync(e,t,0);a!=s.WAIT_FAILED?a!=s.TIMEOUT_EXPIRED?r():setTimeout(o,i):n()};o()}))}_readPixelsAsync(e,t,i,s,r,n,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const a=this._gl,l=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.bufferData(a.PIXEL_PACK_BUFFER,o.byteLength,a.STREAM_READ),a.readPixels(e,t,i,s,r,n,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null);const h=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(a.flush(),this._clientWaitAsync(h,0,10).then((()=>(a.deleteSync(h),a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,o),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.deleteBuffer(l),o)))):null}dispose(){this._rescalePostProcess&&this._rescalePostProcess.dispose(),qn(this,this._renderingCanvas),super.dispose()}}oo.ALPHA_DISABLE=0,oo.ALPHA_ADD=1,oo.ALPHA_COMBINE=2,oo.ALPHA_SUBTRACT=3,oo.ALPHA_MULTIPLY=4,oo.ALPHA_MAXIMIZED=5,oo.ALPHA_ONEONE=6,oo.ALPHA_PREMULTIPLIED=7,oo.ALPHA_PREMULTIPLIED_PORTERDUFF=8,oo.ALPHA_INTERPOLATE=9,oo.ALPHA_SCREENMODE=10,oo.DELAYLOADSTATE_NONE=0,oo.DELAYLOADSTATE_LOADED=1,oo.DELAYLOADSTATE_LOADING=2,oo.DELAYLOADSTATE_NOTLOADED=4,oo.NEVER=512,oo.ALWAYS=519,oo.LESS=513,oo.EQUAL=514,oo.LEQUAL=515,oo.GREATER=516,oo.GEQUAL=518,oo.NOTEQUAL=517,oo.KEEP=7680,oo.REPLACE=7681,oo.INCR=7682,oo.DECR=7683,oo.INVERT=5386,oo.INCR_WRAP=34055,oo.DECR_WRAP=34056,oo.TEXTURE_CLAMP_ADDRESSMODE=0,oo.TEXTURE_WRAP_ADDRESSMODE=1,oo.TEXTURE_MIRROR_ADDRESSMODE=2,oo.TEXTUREFORMAT_ALPHA=0,oo.TEXTUREFORMAT_LUMINANCE=1,oo.TEXTUREFORMAT_LUMINANCE_ALPHA=2,oo.TEXTUREFORMAT_RGB=4,oo.TEXTUREFORMAT_RGBA=5,oo.TEXTUREFORMAT_RED=6,oo.TEXTUREFORMAT_R=6,oo.TEXTUREFORMAT_RG=7,oo.TEXTUREFORMAT_RED_INTEGER=8,oo.TEXTUREFORMAT_R_INTEGER=8,oo.TEXTUREFORMAT_RG_INTEGER=9,oo.TEXTUREFORMAT_RGB_INTEGER=10,oo.TEXTUREFORMAT_RGBA_INTEGER=11,oo.TEXTURETYPE_UNSIGNED_BYTE=0,oo.TEXTURETYPE_UNSIGNED_INT=0,oo.TEXTURETYPE_FLOAT=1,oo.TEXTURETYPE_HALF_FLOAT=2,oo.TEXTURETYPE_BYTE=3,oo.TEXTURETYPE_SHORT=4,oo.TEXTURETYPE_UNSIGNED_SHORT=5,oo.TEXTURETYPE_INT=6,oo.TEXTURETYPE_UNSIGNED_INTEGER=7,oo.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,oo.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,oo.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,oo.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,oo.TEXTURETYPE_UNSIGNED_INT_24_8=12,oo.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,oo.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,oo.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,oo.TEXTURE_NEAREST_SAMPLINGMODE=1,oo.TEXTURE_BILINEAR_SAMPLINGMODE=2,oo.TEXTURE_TRILINEAR_SAMPLINGMODE=3,oo.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,oo.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,oo.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,oo.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,oo.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,oo.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,oo.TEXTURE_NEAREST_LINEAR=7,oo.TEXTURE_NEAREST_NEAREST=1,oo.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,oo.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,oo.TEXTURE_LINEAR_LINEAR=2,oo.TEXTURE_LINEAR_NEAREST=12,oo.TEXTURE_EXPLICIT_MODE=0,oo.TEXTURE_SPHERICAL_MODE=1,oo.TEXTURE_PLANAR_MODE=2,oo.TEXTURE_CUBIC_MODE=3,oo.TEXTURE_PROJECTION_MODE=4,oo.TEXTURE_SKYBOX_MODE=5,oo.TEXTURE_INVCUBIC_MODE=6,oo.TEXTURE_EQUIRECTANGULAR_MODE=7,oo.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,oo.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,oo.SCALEMODE_FLOOR=1,oo.SCALEMODE_NEAREST=2,oo.SCALEMODE_CEILING=3;const ao=me.Compose(_e.One(),fe.FromEulerAngles(0,Math.PI,0),_e.Zero());class lo extends Et{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=!!(this._billboardMode&lo.BILLBOARDMODE_USE_POSITION),this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==lo.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t,!1),this._forward=new _e(0,0,1),this._up=new _e(0,1,0),this._right=new _e(1,0,0),this._position=_e.Zero(),this._rotation=_e.Zero(),this._rotationQuaternion=null,this._scaling=_e.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=lo.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=me.Zero(),this._usePivotMatrix=!1,this._absolutePosition=_e.Zero(),this._absoluteScaling=_e.Zero(),this._absoluteRotationQuaternion=fe.Identity(),this._pivotMatrix=me.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new K,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return _e.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return _e.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return _e.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()}updatePoseMatrix(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=me.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==lo.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this._infiniteDistance||this._position._isDirty||this._scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)}_initCache(){super._initCache();const e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1,e.useBillboardPath=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=me.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const s=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);s&&i&&i(this,s);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(s,t,i);return s}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||fe.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,s;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],s=arguments[2]}else t=e.x,i=e.y,s=e.z;if(this.parent){const e=ve.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),_e.TransformCoordinatesFromFloatsToRef(t,i,s,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=s;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=_e.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=ve.Matrix[0];return this._localMatrix.invertToRef(e),_e.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=_e.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,r=Ur.LOCAL){const n=lo._LookAtVectorCache,o=r===Ur.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,n),this.setDirection(n,t,i,s),r===Ur.WORLD&&this.parent)if(this.rotationQuaternion){const e=ve.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=ve.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=ve.Quaternion[0];fe.FromEulerVectorToRef(this.rotation,e);const t=ve.Matrix[0];e.toRotationMatrix(t);const i=ve.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=_e.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return _e.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,n);return this.rotationQuaternion?fe.RotationYawPitchRollToRef(r+t,o+i,s,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=r+t,this.rotation.z=s),this}setPivotPoint(e,t=Ur.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==Ur.WORLD){const t=ve.Matrix[0];i.invertToRef(t),e=_e.TransformCoordinates(e,t)}return this.setPivotMatrix(me.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=_e.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){const e=_e.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),_e.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;const s=ve.Quaternion[0],r=ve.Vector3[0],n=ve.Vector3[1],o=ve.Matrix[1];me.IdentityToRef(o);const a=ve.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=lo._TmpRotation,fe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),me.ComposeToRef(this.scaling,l,this.position,a),this.parent&&a.multiplyToRef(this.parent.computeWorldMatrix(!0),a),e&&(e.computeWorldMatrix(!0).invertToRef(o),a.multiplyToRef(o,a)),a.decompose(n,s,r,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(r),this.parent=e,i&&this.setPivotMatrix(me.Identity()),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=e?this._currentParentWhenAttachingToBone:null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){let s;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==Ur.LOCAL){if(this.parent){const i=this.parent.getWorldMatrix(),s=ve.Matrix[0];i.invertToRef(s),e=_e.TransformNormal(e,s),i.determinant()<0&&(t*=-1)}s=fe.RotationAxisToRef(e,t,lo._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else s=fe.RotationAxisToRef(e,t,lo._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=fe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=ve.Vector3[0],r=ve.Vector3[1],n=ve.Vector3[2],o=ve.Quaternion[0],a=ve.Matrix[0],l=ve.Matrix[1],h=ve.Matrix[2],c=ve.Matrix[3];return e.subtractToRef(this.position,s),me.TranslationToRef(s.x,s.y,s.z,a),me.TranslationToRef(-s.x,-s.y,-s.z,l),me.RotationAxisToRef(t,i,h),l.multiplyToRef(h,c),c.multiplyToRef(a,c),c.decompose(r,o,n),this.position.addInPlace(n),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(i&&i!==Ur.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(s));else{const e=this.getPositionExpressedInLocalSpace().add(s);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let s;this.rotationQuaternion?s=this.rotationQuaternion:(s=ve.Quaternion[1],fe.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const r=ve.Quaternion[0];return fe.RotationYawPitchRollToRef(t,e,i,r),s.multiplyInPlace(r),this.rotationQuaternion||s.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==lo.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const r=this._getEffectiveParent(),n=lo._TmpScaling;let o,a=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new _e(e.m[12],e.m[13],e.m[14]);a=lo._TmpTranslation,a.copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,o=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(fe.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(o=lo._TmpRotation,fe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,o)),this._usePivotMatrix){const e=ve.Matrix[1];me.ScalingToRef(n.x,n.y,n.z,e);const t=ve.Matrix[0];o.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,ve.Matrix[4]),ve.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(a.x,a.y,a.z)}else me.ComposeToRef(n,o,a,this._localMatrix);if(r&&r.getWorldMatrix){if(e&&r.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),ve.Matrix[7])}else ve.Matrix[7].copyFrom(r.getWorldMatrix());const e=ve.Vector3[5],t=ve.Vector3[6],i=ve.Quaternion[0];ve.Matrix[7].decompose(t,i,e),me.ScalingToRef(t.x,t.y,t.z,ve.Matrix[7]),ve.Matrix[7].setTranslation(e),lo.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(ve.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),ve.Matrix[6]),ve.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(r.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){const e=ve.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),ve.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&ve.Matrix[1].multiplyToRef(ao,ve.Matrix[1]),ve.Matrix[1].setTranslationFromFloats(0,0,0),ve.Matrix[1].invertToRef(ve.Matrix[0]),(this.billboardMode&lo.BILLBOARDMODE_ALL)!==lo.BILLBOARDMODE_ALL){ve.Matrix[0].decompose(void 0,ve.Quaternion[0],void 0);const e=ve.Vector3[1];ve.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&lo.BILLBOARDMODE_X)!==lo.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&lo.BILLBOARDMODE_Y)!==lo.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&lo.BILLBOARDMODE_Z)!==lo.BILLBOARDMODE_Z&&(e.z=0),me.RotationYawPitchRollToRef(e.y,e.x,e.z,ve.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ve.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ve.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const e=ve.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(ve.Matrix[1]);const s=ve.Vector3[1];_e.TransformCoordinatesToRef(i,ve.Matrix[1],s),s.normalize();const r=-Math.atan2(s.z,s.x)+Math.PI/2,n=Math.sqrt(s.x*s.x+s.z*s.z),o=-Math.atan2(s.y,n);if(fe.RotationYawPitchRollToRef(r,o,0,ve.Quaternion[0]),(this.billboardMode&lo.BILLBOARDMODE_ALL)!==lo.BILLBOARDMODE_ALL){const e=ve.Vector3[1];ve.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&lo.BILLBOARDMODE_X)!==lo.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&lo.BILLBOARDMODE_Y)!==lo.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&lo.BILLBOARDMODE_Z)!==lo.BILLBOARDMODE_Z&&(e.z=0),me.RotationYawPitchRollToRef(e.y,e.x,e.z,ve.Matrix[0])}else me.FromQuaternionToRef(ve.Quaternion[0],ve.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ve.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ve.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):r&&r._nonUniformScaling?this._updateNonUniformScalingState(r._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=me.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;tnew lo(e,this.getScene())),this);if(s.name=e,s.id=e,t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;inew lo(e.name,t)),e,t,i);if(e.localMatrix?s.setPreTransformMatrix(me.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(me.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let t=0;t(!t||t(e))&&e instanceof lo)),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const e=this.getChildTransformNodes(!0);for(const t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let s=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),o=n.max.subtract(n.min),a=Math.max(o.x,o.y,o.z);if(0===a)return this;const l=1/a;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&s&&this.rotation.copyFrom(s)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}lo.BILLBOARDMODE_NONE=0,lo.BILLBOARDMODE_X=1,lo.BILLBOARDMODE_Y=2,lo.BILLBOARDMODE_Z=4,lo.BILLBOARDMODE_ALL=7,lo.BILLBOARDMODE_USE_POSITION=128,lo.BillboardUseParentOrientation=!1,lo._TmpRotation=fe.Zero(),lo._TmpScaling=_e.Zero(),lo._TmpTranslation=_e.Zero(),lo._LookAtVectorCache=new _e(0,0,0),lo._RotationAxisCache=new fe,Ze([ht("position")],lo.prototype,"_position",void 0),Ze([ht("rotation")],lo.prototype,"_rotation",void 0),Ze([pt("rotationQuaternion")],lo.prototype,"_rotationQuaternion",void 0),Ze([ht("scaling")],lo.prototype,"_scaling",void 0),Ze([rt("billboardMode")],lo.prototype,"_billboardMode",void 0),Ze([rt()],lo.prototype,"scalingDeterminant",void 0),Ze([rt("infiniteDistance")],lo.prototype,"_infiniteDistance",void 0),Ze([rt()],lo.prototype,"ignoreNonUniformScaling",void 0),Ze([rt()],lo.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class ho{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new _e(0,0,0),this._diffPositionForCollisions=new _e(0,0,0),this._collisionResponse=!0}}class co{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=_e.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class uo{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new co,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=null,this._currentLODIsUpToDate=!1,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new ho,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class _o extends lo{static get BILLBOARDMODE_NONE(){return lo.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return lo.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return lo.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return lo.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return lo.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return lo.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return!!super._updateNonUniformScalingState(e)&&(this._markSubMeshesAsMiscDirty(),!0)}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;const t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty((e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()}))}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){return this._internalAbstractMeshDataInfo._materialForRenderPass?.[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}get _positions(){return null}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new uo,this._waitingMaterialId=null,this.cullingStrategy=_o.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new K,this.onCollisionPositionChangeObservable=new K,this.onMaterialChangedObservable=new K,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this.isVisible=!0,this.isPickable=!0,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=Ee.Red(),this.outlineWidth=.02,this.overlayColor=Ee.Red(),this.overlayAlpha=.5,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.alwaysSelectAsActiveMesh=!1,this.doNotSyncBoundingInfo=!1,this.actionManager=null,this.ellipsoid=new _e(.5,1,.5),this.ellipsoidOffset=new _e(0,0,0),this.edgesWidth=1,this.edgesColor=new Ae(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new K,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>oo.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new Zs(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case Vr.Aggressive:this.doNotSyncBoundingInfo=!0;case Vr.Intermediate:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){const t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()}getMeshUniformBuffer(){return this._uniformBuffer}getClassName(){return"AbstractMesh"}toString(e){let t="Name: "+this.name+", isInstance: "+("InstancedMesh"!==this.getClassName()?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);const i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==lo.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),null!==this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes){for(const e of this.subMeshes)e._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let s=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;s=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(s)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;it.markAsLightDirty(e)))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty((e=>e.markAsAttributesDirty()))}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty((e=>e.markAsMiscDirty()))}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,s){return this}updateVerticesData(e,t,i,s){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new Ln(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(er.MatricesIndicesKind)&&this.isVerticesDataPresent(er.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===lo.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){const s=new me;(this.rotationQuaternion?this.rotationQuaternion:fe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const r=_e.Zero(),n=this.definedFacingForward?-1:1;return _e.TransformCoordinatesFromFloatsToRef(e*n,t,i*n,s,r),r}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const s=this.definedFacingForward?1:-1;return new _e(e*s,t,i*s)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){const i=Vn(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new Ln(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t4,n=r?this.getVerticesData(er.MatricesIndicesExtraKind):null,o=r?this.getVerticesData(er.MatricesWeightsExtraKind):null,a=this.skeleton.getTransformMatrices(this),l=ve.Vector3[0],h=ve.Matrix[0],c=ve.Matrix[1];let u=0;for(let d=0;d0&&(me.FromFloat32ArrayToRefScaled(a,Math.floor(16*e[u+_]),p,c),h.addToSelf(c));if(r)for(_=0;_<4;_++)p=o[u+_],p>0&&(me.FromFloat32ArrayToRefScaled(a,Math.floor(16*n[u+_]),p,c),h.addToSelf(c));s===er.NormalKind?_e.TransformNormalFromFloatsToRef(i[d],i[d+1],i[d+2],h,l):_e.TransformCoordinatesFromFloatsToRef(i[d],i[d+1],i[d+2],h,l),l.toArray(i,d),s===er.PositionKind&&this._positions&&this._positions[d/3].copyFrom(l)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,er.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,er.PositionKind)}_getPositionData(e,t){let i=this.getVerticesData(er.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),i&&(e&&this.skeleton||t&&this.morphTargetManager)){if(i=i.slice(),this._generatePointsArray(),this._positions){const e=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(e.length);for(let t=0;t1||!s.IsGlobal)&&s.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const s=this.getBoundingInfo(),r=e.getBoundingInfo();if(s.intersects(r,t))return!0;if(i)for(const i of this.getChildMeshes())if(i.intersectsMesh(e,t,!0))return!0;return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);const t=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=t.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,t.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const i=e.verticesStart,s=e.verticesStart+e.verticesCount;for(let r=i;r1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=ve.Matrix[0],i=ve.Matrix[1];return me.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,s=!1,r,n=!1){const o=new tr,a=this.getClassName(),l="InstancedLinesMesh"===a||"LinesMesh"===a||"GreasedLineMesh"===a?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes)return o;if(!(n||e.intersectsSphere(h.boundingSphere,l)&&e.intersectsBox(h.boundingBox,l)))return o;if(s)return o.hit=!n,o.pickedMesh=n?null:this,o.distance=n?0:_e.Distance(e.origin,h.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let c=null;const u=this._scene.getIntersectingSubMeshCandidates(this,e),d=u.length;let _=!1;for(let e=0;e1&&!n&&!r.canIntersects(e))continue;const o=r.intersects(e,this._positions,this.getIndices(),t,i);if(o&&(t||!c||o.distancee!==this&&e.actionManager===this.actionManager))||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(this),-1!==t&&e.excludedMeshes.splice(t,1);const i=e.getShadowGenerators();if(i){const e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){const e=i.value.getShadowMap();e&&e.renderList&&(t=e.renderList.indexOf(this),-1!==t&&e.renderList.splice(t,1))}}})),"InstancedMesh"===this.getClassName()&&"InstancedLinesMesh"===this.getClassName()||this.releaseSubMeshes();const r=s.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,r.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),r.wipeCaches(),s.removeMesh(this),this._parentContainer){const e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:_e.Zero()}e.depthSortedFacets=[];for(let t=0;tJ?r.maximum.x-r.minimum.x:J,e.bbSize.y=r.maximum.y-r.minimum.y>J?r.maximum.y-r.minimum.y:J,e.bbSize.z=r.maximum.z-r.minimum.z>J?r.maximum.z-r.minimum.z:J;let n=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(n=n>e.bbSize.z?n:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/n),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/n),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/n),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=r,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),_e.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&Wn.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let s=0;sr.subDiv.max||o<0||o>r.subDiv.max||a<0||a>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*o+r.subDiv.max*r.subDiv.max*a]}getClosestFacetAtCoordinates(e,t,i,s,r=!1,n=!0){const o=this.getWorldMatrix(),a=ve.Matrix[5];o.invertToRef(a);const l=ve.Vector3[8];_e.TransformCoordinatesFromFloatsToRef(e,t,i,a,l);const h=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,s,r,n);return s&&_e.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,o,s),h}getClosestFacetAtLocalCoordinates(e,t,i,s,r=!1,n=!0){let o=null,a=0,l=0,h=0,c=0,u=0,d=0,_=0,p=0;const f=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;let v,x,b,T=Number.MAX_VALUE,y=T;for(let S=0;S=0||r&&!n&&c<=0)&&(c=x.x*b.x+x.y*b.y+x.z*b.z,u=-(x.x*e+x.y*t+x.z*i-c)/(x.x*x.x+x.y*x.y+x.z*x.z),d=e+x.x*u,_=t+x.y*u,p=i+x.z*u,a=d-e,l=_-t,h=p-i,y=a*a+l*l+h*h,ye.emitter===this))}}_o.OCCLUSION_TYPE_NONE=0,_o.OCCLUSION_TYPE_OPTIMISTIC=1,_o.OCCLUSION_TYPE_STRICT=2,_o.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,_o.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,_o.CULLINGSTRATEGY_STANDARD=0,_o.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,_o.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,_o.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,z("BABYLON.AbstractMesh",_o);class po{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681}get func(){return this._func}set func(e){this._func=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){St.Clone((()=>e),this)}serialize(){return St.Serialize(this)}parse(e,t,i){St.Parse((()=>this),e,t,i)}}var fo;function mo(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}function go(e,t,i){const s=!!(e.clipPlane??t.clipPlane),r=!!(e.clipPlane2??t.clipPlane2),n=!!(e.clipPlane3??t.clipPlane3),o=!!(e.clipPlane4??t.clipPlane4),a=!!(e.clipPlane5??t.clipPlane5),l=!!(e.clipPlane6??t.clipPlane6);s&&i.push("#define CLIPPLANE"),r&&i.push("#define CLIPPLANE2"),n&&i.push("#define CLIPPLANE3"),o&&i.push("#define CLIPPLANE4"),a&&i.push("#define CLIPPLANE5"),l&&i.push("#define CLIPPLANE6")}function vo(e,t,i){let s=!1;const r=!!(e.clipPlane??t.clipPlane),n=!!(e.clipPlane2??t.clipPlane2),o=!!(e.clipPlane3??t.clipPlane3),a=!!(e.clipPlane4??t.clipPlane4),l=!!(e.clipPlane5??t.clipPlane5),h=!!(e.clipPlane6??t.clipPlane6);return i.CLIPPLANE!==r&&(i.CLIPPLANE=r,s=!0),i.CLIPPLANE2!==n&&(i.CLIPPLANE2=n,s=!0),i.CLIPPLANE3!==o&&(i.CLIPPLANE3=o,s=!0),i.CLIPPLANE4!==a&&(i.CLIPPLANE4=a,s=!0),i.CLIPPLANE5!==l&&(i.CLIPPLANE5=l,s=!0),i.CLIPPLANE6!==h&&(i.CLIPPLANE6=h,s=!0),s}function xo(e,t,i){let s=t.clipPlane??i.clipPlane;bo(e,"vClipPlane",s),s=t.clipPlane2??i.clipPlane2,bo(e,"vClipPlane2",s),s=t.clipPlane3??i.clipPlane3,bo(e,"vClipPlane3",s),s=t.clipPlane4??i.clipPlane4,bo(e,"vClipPlane4",s),s=t.clipPlane5??i.clipPlane5,bo(e,"vClipPlane5",s),s=t.clipPlane6??i.clipPlane6,bo(e,"vClipPlane6",s)}function bo(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}Ze([rt()],po.prototype,"func",null),Ze([rt()],po.prototype,"funcRef",null),Ze([rt()],po.prototype,"funcMask",null),Ze([rt()],po.prototype,"opStencilFail",null),Ze([rt()],po.prototype,"opDepthFail",null),Ze([rt()],po.prototype,"opStencilDepthPass",null),Ze([rt()],po.prototype,"mask",null),Ze([rt()],po.prototype,"enabled",null),function(e){e[e.Created=1]="Created",e[e.Disposed=2]="Disposed",e[e.GetDefineNames=4]="GetDefineNames",e[e.PrepareUniformBuffer=8]="PrepareUniformBuffer",e[e.IsReadyForSubMesh=16]="IsReadyForSubMesh",e[e.PrepareDefines=32]="PrepareDefines",e[e.BindForSubMesh=64]="BindForSubMesh",e[e.PrepareEffect=128]="PrepareEffect",e[e.GetAnimatables=256]="GetAnimatables",e[e.GetActiveTextures=512]="GetActiveTextures",e[e.HasTexture=1024]="HasTexture",e[e.FillRenderTargetTextures=2048]="FillRenderTargetTextures",e[e.HasRenderTargetTextures=4096]="HasRenderTargetTextures",e[e.HardBindForSubMesh=8192]="HardBindForSubMesh"}(fo||(fo={}));const To=Ee.Black(),yo={NUM_MORPH_INFLUENCERS:0};function So(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=i.activeCamera;1===e.mode&&Ne.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}function Co(e,t,i,s=!1){i&&e.fogEnabled&&(!t||t.applyFog)&&0!==e.fogMode&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),s?(e.fogColor.toLinearSpaceToRef(To,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",To)):i.setColor3("vFogColor",e.fogColor))}function Eo(e,t,i){yo.NUM_MORPH_INFLUENCERS=i,Ao(e,t,yo)}function Ao(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&re.LastCreatedEngine){const r=re.LastCreatedEngine.getCaps().maxVertexAttribs,n=t.morphTargetManager;if(n?.isUsingTextureForTargets)return;const o=n&&n.supportsNormals&&i.NORMAL,a=n&&n.supportsTangents&&i.TANGENT,l=n&&n.supportsUVs&&i.UV1;for(let i=0;ir&&Ne.Error("Cannot add more vertex attributes for mesh "+t.name)}}function Po(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}function Io(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}function Ro(e,t){t.bindToEffect(e,"Scene")}function Mo(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}function Oo(e,t,i){const s=e.getTextureMatrix();t.updateMatrix(i+"Matrix",s)}function Do(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}function wo(e,t,i){var s;if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const r=e.skeleton;if(r.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){const i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{const n=r.getTransformMatrices(e);n&&(t.setMatrices("mBones",n),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=n.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),s=n,i.previousBones[e.uniqueId].set(s)))}}}function No(e,t,i){e.transferToEffect(t,i+"")}function Fo(e,t,i,s,r,n=!0){e._bindLight(t,i,s,r,n)}function Lo(e,t,i,s,r=4){const n=Math.min(t.lightSources.length,r);for(let r=0;r0&&(s.addCPUSkinningFallback(0,t),e.push("matricesIndices"),e.push("matricesWeights"),i.NUM_BONE_INFLUENCERS>4&&(e.push("matricesIndicesExtra"),e.push("matricesWeightsExtra")))}function ko(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&Po(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push("instanceColor")}function Vo(e,t,i=4,s=0){let r=0;for(let n=0;n0&&(r=s+n,t.addFallback(r,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(s,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(s,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(s,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(s,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(s,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(s,"SHADOWCLOSEESM"+n));return r++}function Uo(e,t){return t.fogEnabled&&e.applyFog&&0!==t.fogMode}function Go(e,t,i,s,r,n,o,a=!1){o._areMiscDirty&&(o.LOGARITHMICDEPTH=i,o.POINTSIZE=s,o.FOG=r&&Uo(e,t),o.NONUNIFORMSCALING=e.nonUniformScaling,o.ALPHATEST=n,o.DECAL_AFTER_DETAIL=a)}function zo(e,t,i,s,r=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let o=0;const a={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n)for(const n of t.lightSources)if(Wo(e,t,n,o,i,s,a),o++,o===r)break;i.SPECULARTERM=a.specularEnabled,i.SHADOWS=a.shadowEnabled;for(let e=o;e0&&(o.shadowEnabled=!0,t.prepareDefines(r,s))}}i.lightmapMode!=Br.LIGHTMAP_DEFAULT?(o.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+s]=!0,r["LIGHTMAPNOSPECULAR"+s]=i.lightmapMode==Br.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+s]=!1,r["LIGHTMAPNOSPECULAR"+s]=!1)}function Ho(e,t,i,s,r,n=null,o=!1){let a=Zo(e,s);!1!==n&&(a=vo(i,e,s)),s.DEPTHPREPASS!==!t.getColorWrite()&&(s.DEPTHPREPASS=!s.DEPTHPREPASS,a=!0),s.INSTANCES!==r&&(s.INSTANCES=r,a=!0),s.THIN_INSTANCES!==o&&(s.THIN_INSTANCES=o,a=!0),a&&s.markAsUnprocessed()}function Xo(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;const s=e.getScene().prePassRenderer;if(s&&s.enabled){const i=-1===s.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}function Yo(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.NUM_MORPH_INFLUENCERS=i.numMaxInfluencers||i.numInfluencers,t.MORPHTARGETS=t.NUM_MORPH_INFLUENCERS>0,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}function Qo(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}function jo(e,t,i,s,r=!1,n=!0,o=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent("normal"),t._needNormals&&e.isVerticesDataPresent("tangent")&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){const i=e.useVertexColors&&e.isVerticesDataPresent("color");t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&n}return e.isVerticesDataPresent("instanceColor")&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),s&&Xo(e,t),r&&Yo(e,t),o&&Qo(e,t),!0}function Ko(e,t){if(e.activeCamera){const i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}function $o(e,t,i){const s=t.ORDER_INDEPENDENT_TRANSPARENCY,r=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,s===t.ORDER_INDEPENDENT_TRANSPARENCY&&r===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}function qo(e,t,i){const s=t.PREPASS;if(!t._arePrePassDirty)return;const r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let i=0;i{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const s=t||re.LastCreatedScene;s&&(this._scene=s,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||Ds.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Un(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=ta.ClockWiseSideOrientation:this.sideOrientation=ta.CounterClockWiseSideOrientation,this._uniformBuffer=new Zs(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),ta.OnEventObservable.notifyObservers(this,fo.Created))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const s=t.materialDefines;return!!s&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===ta.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===ta.MATERIAL_OPAQUE||this._transparencyMode===ta.MATERIAL_ALPHATEST}needAlphaBlending(){return!this._disableAlphaBlending&&this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1||!this._disableAlphaBlending&&(e.hasVertexAlpha||this.needAlphaBlending())}needAlphaTesting(){return!!this._forceAlphaTest}_shouldTurnAlphaTestOn(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)if(t.getMaterial()===this)for(const i of t._drawWrappers)i&&this._materialContext===i.materialContext&&(i._wasPreviouslyReady=!1,i._wasPreviouslyUsingInstances=null,i._forceRebindOnNextCall=e);e&&this.markAsDirty(ta.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),s=(null==t?this.sideOrientation:t)===ta.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(fo.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const s=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),s._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,Ro(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),this._scene._cachedVisibility=e?e.visibility:1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){const e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){const e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(fo.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(fo.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(fo.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),ta._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const t of this.pluginManager._plugins){const i=e.pluginManager.getPlugin(t.name);i&&t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}return this._scene.meshes.filter((e=>e.material===this))}forceCompilation(e,t,i,s){const r={clipPlane:!1,useInstances:!1,...i},n=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const a=()=>{if(!this._scene||!this._scene.getEngine())return;const i=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new Nr(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,n=null;if(e.subMeshes){const t=new Gn(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,r.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?n=t.effect.getCompilationError():(i=!1,setTimeout(a,16)))}i&&(this.allowShaderHotSwapping=o,n&&s&&s(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(a,16);r.clipPlane&&(n.clipPlane=i)};a()}forceCompilationAsync(e,t){return new Promise(((i,s)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{s(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(ta._DirtyCallbackArray.length=0,e&ta.TextureDirtyFlag&&ta._DirtyCallbackArray.push(ta._TextureDirtyCallBack),e&ta.LightDirtyFlag&&ta._DirtyCallbackArray.push(ta._LightsDirtyCallBack),e&ta.FresnelDirtyFlag&&ta._DirtyCallbackArray.push(ta._FresnelDirtyCallBack),e&ta.AttributesDirtyFlag&&ta._DirtyCallbackArray.push(ta._AttributeDirtyCallBack),e&ta.MiscDirtyFlag&&ta._DirtyCallbackArray.push(ta._MiscDirtyCallBack),e&ta.PrePassDirtyFlag&&ta._DirtyCallbackArray.push(ta._PrePassDirtyCallBack),ta._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(ta._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const e of t.subMeshes)e.getMaterial()===this&&e.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)if(t.getMaterial(!1)===this)for(const i of t._drawWrappers)i&&i.defines&&i.defines.markAllAsDirty&&this._materialContext===i.materialContext&&e(i.defines)}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(ta._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(ta._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(ta._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(ta._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(ta._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(ta._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(ta._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(ta._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(ta._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(ta._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==Vr.BackwardCompatible){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce((()=>{this.checkReadyOnlyOnce=!1}));this.onDisposeObservable.add((()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)}))}}setPrePassRenderer(e){return!1}dispose(e,t,i){const s=this.getScene();if(s.stopAnimation(this),s.freeProcessedMaterials(),s.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(fo.Disposed,this._eventInfo),this._parentContainer){const e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i)if(this.meshMap)for(const t in this.meshMap){const i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{const t=s.meshes;for(const i of t)i.material!==this||i.sourceMesh||(i.material=null,this.releaseVertexArrayObject(i,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const s of e.subMeshes)i._releaseVertexArrayObject(s.effect),t&&s.effect&&s.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=St.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(const t of this.pluginManager._plugins)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,i){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return Ne.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else e.customType="BABYLON.StandardMaterial";const s=Ds.Instantiate(e.customType).Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _ParsePlugins(e,t,i,s){if(e.plugins)for(const r in e.plugins){const n=e.plugins[r];let o=t.pluginManager?.getPlugin(n.name);if(!o){const e=Ds.Instantiate("BABYLON."+r);e&&(o=new e(t))}o?.parse(n,i,s)}}}ta.TriangleFillMode=0,ta.WireFrameFillMode=1,ta.PointFillMode=2,ta.PointListDrawMode=3,ta.LineListDrawMode=4,ta.LineLoopDrawMode=5,ta.LineStripDrawMode=6,ta.TriangleStripDrawMode=7,ta.TriangleFanDrawMode=8,ta.ClockWiseSideOrientation=0,ta.CounterClockWiseSideOrientation=1,ta.TextureDirtyFlag=1,ta.LightDirtyFlag=2,ta.FresnelDirtyFlag=4,ta.AttributesDirtyFlag=8,ta.MiscDirtyFlag=16,ta.PrePassDirtyFlag=32,ta.AllDirtyFlag=63,ta.MATERIAL_OPAQUE=0,ta.MATERIAL_ALPHATEST=1,ta.MATERIAL_ALPHABLEND=2,ta.MATERIAL_ALPHATESTANDBLEND=3,ta.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,ta.MATERIAL_NORMALBLENDMETHOD_RNM=1,ta.OnEventObservable=new K,ta._AllDirtyCallBack=e=>e.markAllAsDirty(),ta._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),ta._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),ta._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),ta._MiscDirtyCallBack=e=>e.markAsMiscDirty(),ta._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),ta._LightsDirtyCallBack=e=>e.markAsLightDirty(),ta._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),ta._FresnelAndMiscDirtyCallBack=e=>{ta._FresnelDirtyCallBack(e),ta._MiscDirtyCallBack(e)},ta._TextureAndMiscDirtyCallBack=e=>{ta._TextureDirtyCallBack(e),ta._MiscDirtyCallBack(e)},ta._DirtyCallbackArray=[],ta._RunDirtyCallBacks=e=>{for(const t of ta._DirtyCallbackArray)t(e)},Ze([rt()],ta.prototype,"id",void 0),Ze([rt()],ta.prototype,"uniqueId",void 0),Ze([rt()],ta.prototype,"name",void 0),Ze([rt()],ta.prototype,"metadata",void 0),Ze([rt()],ta.prototype,"checkReadyOnEveryCall",void 0),Ze([rt()],ta.prototype,"checkReadyOnlyOnce",void 0),Ze([rt()],ta.prototype,"state",void 0),Ze([rt("alpha")],ta.prototype,"_alpha",void 0),Ze([rt("backFaceCulling")],ta.prototype,"_backFaceCulling",void 0),Ze([rt("cullBackFaces")],ta.prototype,"_cullBackFaces",void 0),Ze([rt()],ta.prototype,"sideOrientation",void 0),Ze([rt("alphaMode")],ta.prototype,"_alphaMode",void 0),Ze([rt()],ta.prototype,"_needDepthPrePass",void 0),Ze([rt()],ta.prototype,"disableDepthWrite",void 0),Ze([rt()],ta.prototype,"disableColorWrite",void 0),Ze([rt()],ta.prototype,"forceDepthWrite",void 0),Ze([rt()],ta.prototype,"depthFunction",void 0),Ze([rt()],ta.prototype,"separateCullingPass",void 0),Ze([rt("fogEnabled")],ta.prototype,"_fogEnabled",void 0),Ze([rt()],ta.prototype,"pointSize",void 0),Ze([rt()],ta.prototype,"zOffset",void 0),Ze([rt()],ta.prototype,"zOffsetUnits",void 0),Ze([rt()],ta.prototype,"pointsCloud",null),Ze([rt()],ta.prototype,"fillMode",null),Ze([rt()],ta.prototype,"useLogarithmicDepth",null),Ze([rt()],ta.prototype,"transparencyMode",null);class ia extends ta{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);return this._markAllSubMeshesAsTexturesDirty(),r}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map((e=>e?e.getActiveTextures():[])))}hasTexture(e){if(super.hasTexture(e))return!0;for(let t=0;t=0&&s.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new ia(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,Tt&&Tt.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}z("BABYLON.MultiMaterial",ia);class sa{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class ra{}class na{constructor(){this.visibleInstances={},this.batchCache=new oa,this.batchCacheReplacementModeInFrozenMode=new oa,this.instancesBufferSize=2048}}class oa{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class aa{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class la{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}}class ha extends _o{static _GetDefaultSideOrientation(e){return e||ha.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(er.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(er.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new K),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new K),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new K),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new K),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new K),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}constructor(e,t=null,i=null,s=null,r,n=!0){if(super(e,t),this._internalMeshDataInfo=new la,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new na,this._thinInstanceDataStorage=new aa,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=ha.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,i)=>{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},s){if(s._geometry&&s._geometry.applyToMesh(this),Ye.DeepCopy(s,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=s,t.useClonedMeshMap&&(s._internalMeshDataInfo.meshMap||(s._internalMeshDataInfo.meshMap={}),s._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=s._originalBuilderSideOrientation,this._creationDataStorage=s._creationDataStorage,s._ranges){const e=s._ranges;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,Tt&&Tt.HasTags(s)&&Tt.AddTagsTo(this,Tt.GetTags(s,!0)),this.setEnabled(s.isEnabled(!1)),this.parent=s.parent,this.setPivotMatrix(s.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=e+"."+s.id,this.material=s.material,!r){const t=s.getDescendants(!0);for(let i=0;i{e.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add((()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))})))},this.onMeshReadyObservable=new K(this._internalMeshDataInfo._onMeshReadyObserverAdded),s&&s.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const s=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));s.parent=e||this.parent,s.position=this.position.clone(),s.scaling=this.scaling.clone(),this.rotationQuaternion?s.rotationQuaternion=this.rotationQuaternion.clone():s.rotation=this.rotation.clone(),i&&i(this,s);for(const e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===s.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(s,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:s},i):e.instantiateHierarchy(s,t,i);return s}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort(((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0))}addLODLevel(e,t){if(t&&t._masterMesh)return Ne.Warn("You cannot use a mesh as LOD level twice"),this;const i=new sa(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let i=0;io*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let e=0;e0||this.hasThinInstances);this.computeWorldMatrix();const n=this.material||s.defaultMaterial;if(n)if(n._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,r))return!1}else if(!t.isReady(this,r))return!1}else if(!n.isReady(this,r))return!1;const o=i.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const s=t.values();for(let e=s.next();!0!==e.done;e=s.next()){const t=e.value;if(t&&(!t.getShadowMap()?.renderList||t.getShadowMap()?.renderList&&-1!==t.getShadowMap()?.renderList?.indexOf(this))){const e=t.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let s=0;s0){const i=this.getIndices();if(!i)return null;const s=i.length;let r=!1;if(e)r=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>s){r=!0;break}if(e.verticesStart+e.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new Gn(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,s=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let r=0;r=t);r++)Gn.CreateFromIndices(0,s,r===e-1?t-s:i,this,void 0,!1),s+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,s){if(this._geometry)this._geometry.setVerticesData(e,t,i,s);else{const s=new Wn;s.set(t,e);const r=this.getScene();new Yn(Yn.RandomId(),r,s,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=Yn.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,s){return this._geometry?(s?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(er.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(er.PositionKind,i,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(er.NormalKind);if(!t)return this;Wn.ComputeNormals(i,e,t),this.updateVerticesData(er.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(1===this._geometry.meshes.length)return this;const e=this._geometry,t=this._geometry.copy(Yn.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let s=this._geometry;s||(s=new Yn(Yn.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const t=new Wn;t.indices=e;const s=this.getScene();new Yn(Yn.RandomId(),s,t,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,s=!0){if(!this._geometry)return this;const r=this.getScene().getEngine();let n;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)n=null;else switch(this._getRenderingFillMode(i)){case ta.PointFillMode:n=null;break;case ta.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case ta.TriangleFillMode:n=this._geometry.getIndexBuffer()}return s&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,n,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,n),this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const s=this.getScene().getEngine();return this._unIndexed||t==ta.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==ta.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):s.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const i=this.getScene(),s=i._isInIntermediateRendering(),r=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,r=i.getRenderId(),o=s?t.intermediateDefaultRenderId:t.defaultRenderId;n.visibleInstances[e]=t[r],!n.visibleInstances[e]&&o&&(n.visibleInstances[e]=t[o])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==n.visibleInstances[e]&&void 0!==n.visibleInstances[e],this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,i,s,r){const n=i.visibleInstances[e._id],o=n?n.length:0,a=this._instanceDataStorage,l=a.instancesBufferSize;let h=a.instancesBuffer,c=a.instancesPreviousBuffer;const u=16*(o+1)*4;for(;a.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera1&&s.activeCamera===s.activeCameras[0]||r<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const n=this._getInstancesRenderList(e._id,!!i);if(n.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const o=s.getEngine();let a=0,l=null;this.ignoreCameraMaxZ&&s.activeCamera&&!s._isInIntermediateRendering()&&(a=s.activeCamera.maxZ,l=s.activeCamera,s.activeCamera.maxZ=0,s.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const h=e.getRenderingMesh(),c=n.hardwareInstancedRendering[e._id]||h.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,u=this._instanceDataStorage,d=e.getMaterial();if(!d)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;if(u.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===d){if(d._storeEffectOnSubMeshes&&!e._drawWrapper?._wasPreviouslyReady||!d._storeEffectOnSubMeshes&&!d._getDrawWrapper()._wasPreviouslyReady)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this}else{if(d._storeEffectOnSubMeshes){if(!d.isReadyForSubMesh(this,e,c))return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this}else if(!d.isReady(this,c))return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=d}let _;t&&o.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),_=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const p=_?.effect??null;for(const t of s._beforeRenderingMeshStage)t.action(this,e,n,p);if(!_||!p)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;const f=i||this;let m;if(u.isFrozen||!this._internalMeshDataInfo._effectiveMaterial.backFaceCulling&&null===this.overrideMaterialSideOrientation&&!this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)m=u.sideOrientation;else{const e=f._getWorldMatrixDeterminant();m=this.overrideMaterialSideOrientation,null==m&&(m=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(m=m===ta.ClockWiseSideOrientation?ta.CounterClockWiseSideOrientation:ta.ClockWiseSideOrientation),u.sideOrientation=m}const g=this._internalMeshDataInfo._effectiveMaterial._preBind(_,m);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&o.setDepthWrite(!0);const v=this._internalMeshDataInfo._effectiveMaterial,x=v.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),c||this._bind(e,p,x,!1);const b=f.getWorldMatrix();v._storeEffectOnSubMeshes?v.bindForSubMesh(b,this,e):v.bind(b,this),!v.backFaceCulling&&v.separateCullingPass&&(o.setState(!0,v.zOffset,!1,!g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._processRendering(this,e,p,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),o.setState(!0,v.zOffset,!1,g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,p,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const t of s._afterRenderingMeshStage)t.action(this,e,n,p);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),l&&(l.maxZ=a,s.updateTransformMatrix(!0)),s.performancePriority!==Vr.Aggressive||u.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(er.MatricesWeightsKind)&&(this.isVerticesDataPresent(er.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(er.MatricesWeightsKind),t=e.length;for(let i=0;ii&&s++,0!==n&&u++,c+=n,i=n}if(l[u]++,u>n&&(n=u),0===c)r++;else{const i=1/c;let s=0;for(let r=0;r.001&&o++}}const h=this.skeleton.bones.length,c=this.getVerticesData(er.MatricesIndicesKind),u=this.getVerticesData(er.MatricesIndicesExtraKind);let d=0;for(let e=0;e=h||i<0)&&d++}return{skinned:!0,valid:0===r&&0===o&&0===d,report:"Number of Weights = "+i/4+"\nMaximum influences = "+n+"\nMissing Weights = "+r+"\nNot Sorted = "+s+"\nNot Normalized = "+o+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+d}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return Ds.LoadFile(this.delayLoadingFile,(t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach((e=>{e.refreshBoundingInfo(),e._syncSubMeshes()})),this.delayLoadState=1,e.removePendingData(this)}),(()=>{}),e.offlineProvider,t),this}isInFrustum(e){return 2!==this.delayLoadState&&!!super.isInFrustum(e)&&(this._checkDelayState(),!0)}setMaterialById(e){const t=this.getScene().materials;let i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;const s=this.getScene().multiMaterials;for(i=s.length-1;i>-1;i--)if(s[i].id===e)return this.material=s[i],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(er.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(er.PositionKind);const s=_e.Zero();let r;for(r=0;r{const a=e.width,l=e.height,h=this.getEngine().createCanvas(a,l).getContext("2d");h.drawImage(e,0,0);const c=h.getImageData(0,0,a,l).data;this.applyDisplacementMapFromBuffer(c,a,l,t,i,r,n,o),s&&s(this)}),a||(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,r,n,o,a=!1){if(!this.isVerticesDataPresent(er.PositionKind)||!this.isVerticesDataPresent(er.NormalKind)||!this.isVerticesDataPresent(er.UVKind))return Ne.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(er.PositionKind,!0,!0),h=this.getVerticesData(er.NormalKind),c=this.getVerticesData(er.UVKind);let u=_e.Zero();const d=_e.Zero(),_=de.Zero();n=n||de.Zero(),o=o||new de(1,1);for(let a=0;a{const s=new Float32Array(i.length*t);let r=0;for(let n=0;n{const t=s.length-1-e,i=s[t];for(let e=0;e{for(let e=0;e-1&&(s.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(s.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(s.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t4,l=a?this.getVerticesData(er.MatricesIndicesExtraKind):null,h=a?this.getVerticesData(er.MatricesWeightsExtraKind):null,c=e.getTransformMatrices(this),u=_e.Zero(),d=new me,_=new me;let p,f=0;for(let e=0;e0&&(me.FromFloat32ArrayToRefScaled(c,Math.floor(16*n[f+p]),m,_),d.addToSelf(_));if(a)for(p=0;p<4;p++)m=h[f+p],m>0&&(me.FromFloat32ArrayToRefScaled(c,Math.floor(16*l[f+p]),m,_),d.addToSelf(_));_e.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],d,u),u.toArray(s,e),t&&(_e.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],d,u),u.toArray(r,e)),d.reset()}return this.updateVerticesData(er.PositionKind,s),t&&this.updateVerticesData(er.NormalKind,r),this}static MinMax(e){let t=null,i=null;return e.forEach((function(e){const s=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(s.minimumWorld),i.maximizeInPlace(s.maximumWorld)):(t=s.minimumWorld,i=s.maximumWorld)})),t&&i?{min:t,max:i}:{min:_e.Zero(),max:_e.Zero()}}static Center(e){const t=e instanceof Array?ha.MinMax(e):e;return _e.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,r,n){return Sn(ha._MergeMeshesCoroutine(e,t,i,s,r,n,!1))}static MergeMeshesAsync(e,t=!0,i,s,r,n){return Cn(ha._MergeMeshesCoroutine(e,t,i,s,r,n,!0),Tn())}static*_MergeMeshesCoroutine(e,t=!0,i,s,r,n,o){if(0===(e=e.filter(Boolean)).length)return null;let a;if(!i){let t=0;for(a=0;a=65536)return Ne.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(r=!1);const l=new Array,h=new Array,c=new Array,u=e[0].overrideMaterialSideOrientation;for(a=0;a{const t=e.computeWorldMatrix(!0);return{vertexData:Wn.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:p,transform:f}=_(d);o&&(yield);const m=new Array(e.length-1);for(let t=1;t{throw xt("GroundMesh")},ha._GoldbergMeshParser=(e,t)=>{throw xt("GoldbergMesh")},ha._LinesMeshParser=(e,t)=>{throw xt("LinesMesh")},ha._GreasedLineMeshParser=(e,t)=>{throw xt("GreasedLineMesh")},ha._GreasedLineRibbonMeshParser=(e,t)=>{throw xt("GreasedLineRibbonMesh")},ha._TrailMeshParser=(e,t)=>{throw xt("TrailMesh")},z("BABYLON.Mesh",ha),ha._instancedMeshFactory=(e,t)=>{const i=new ca(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class ca extends _o{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const e of t.getAnimationRanges())null!=e&&this.createAnimationRange(e.name,e.from,e.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){this._sourceMesh?.receiveShadows!==e&&Ds.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){this._sourceMesh?.material!==e&&Ds.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){this._sourceMesh?.visibility!==e&&Ds.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){this._sourceMesh?.skeleton!==e&&Ds.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){this._sourceMesh&&e!==this._sourceMesh.renderingGroupId&&Ne.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,s),this.sourceMesh}updateVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,s),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||Ne.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),t){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1}_postActivate(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)}getWorldMatrix(){if(this._currentLOD&&this._currentLOD.billboardMode!==lo.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new me);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,ve.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(ve.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;const t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){const t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e0&&-1===this.includedOnlyMeshes.indexOf(e)||this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)||!(0===this.includeOnlyWithLayerMask||this.includeOnlyWithLayerMask&e.layerMask)||0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(const e of this.getScene().meshes)e._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){const i=ua.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=St.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=St.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0&&(e.excludedMeshesIds=[],this.excludedMeshes.forEach((t=>{e.excludedMeshesIds.push(t.id)}))),this.includedOnlyMeshes.length>0&&(e.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((t=>{e.includedOnlyMeshesIds.push(t.id)}))),St.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){return Et.Construct("Light_Type_"+e,t,i)||null}static Parse(e,t){const i=ua.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=St.Parse(i,e,t);if(e.excludedMeshesIds&&(s._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(s._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(s.falloffType=e.falloffType),void 0!==e.lightmapMode&&(s.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t{const s=t.apply(e,i);for(const e of i)e._resyncLightSource(this);return s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);for(const e of r)e._resyncLightSource(this);return r};for(const t of e)t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);return this._resyncMeshes(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);return this._resyncMeshes(),r},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===ua.INTENSITYMODE_AUTOMATIC&&(i=t===ua.LIGHTTYPEID_DIRECTIONALLIGHT?ua.INTENSITYMODE_ILLUMINANCE:ua.INTENSITYMODE_LUMINOUSINTENSITY),t){case ua.LIGHTTYPEID_POINTLIGHT:case ua.LIGHTTYPEID_SPOTLIGHT:switch(i){case ua.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case ua.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case ua.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case ua.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case ua.INTENSITYMODE_ILLUMINANCE:e=1;break;case ua.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001),e=2*Math.PI*(1-Math.cos(t));break}}break;case ua.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}ua.FALLOFF_DEFAULT=Br.FALLOFF_DEFAULT,ua.FALLOFF_PHYSICAL=Br.FALLOFF_PHYSICAL,ua.FALLOFF_GLTF=Br.FALLOFF_GLTF,ua.FALLOFF_STANDARD=Br.FALLOFF_STANDARD,ua.LIGHTMAP_DEFAULT=Br.LIGHTMAP_DEFAULT,ua.LIGHTMAP_SPECULAR=Br.LIGHTMAP_SPECULAR,ua.LIGHTMAP_SHADOWSONLY=Br.LIGHTMAP_SHADOWSONLY,ua.INTENSITYMODE_AUTOMATIC=Br.INTENSITYMODE_AUTOMATIC,ua.INTENSITYMODE_LUMINOUSPOWER=Br.INTENSITYMODE_LUMINOUSPOWER,ua.INTENSITYMODE_LUMINOUSINTENSITY=Br.INTENSITYMODE_LUMINOUSINTENSITY,ua.INTENSITYMODE_ILLUMINANCE=Br.INTENSITYMODE_ILLUMINANCE,ua.INTENSITYMODE_LUMINANCE=Br.INTENSITYMODE_LUMINANCE,ua.LIGHTTYPEID_POINTLIGHT=Br.LIGHTTYPEID_POINTLIGHT,ua.LIGHTTYPEID_DIRECTIONALLIGHT=Br.LIGHTTYPEID_DIRECTIONALLIGHT,ua.LIGHTTYPEID_SPOTLIGHT=Br.LIGHTTYPEID_SPOTLIGHT,ua.LIGHTTYPEID_HEMISPHERICLIGHT=Br.LIGHTTYPEID_HEMISPHERICLIGHT,Ze([ot()],ua.prototype,"diffuse",void 0),Ze([ot()],ua.prototype,"specular",void 0),Ze([rt()],ua.prototype,"falloffType",void 0),Ze([rt()],ua.prototype,"intensity",void 0),Ze([rt()],ua.prototype,"range",null),Ze([rt()],ua.prototype,"intensityMode",null),Ze([rt()],ua.prototype,"radius",null),Ze([rt()],ua.prototype,"_renderPriority",void 0),Ze([st("_reorderLightsInScene")],ua.prototype,"renderPriority",void 0),Ze([rt("shadowEnabled")],ua.prototype,"_shadowEnabled",void 0),Ze([rt("excludeWithLayerMask")],ua.prototype,"_excludeWithLayerMask",void 0),Ze([rt("includeOnlyWithLayerMask")],ua.prototype,"_includeOnlyWithLayerMask",void 0),Ze([rt("lightmapMode")],ua.prototype,"_lightmapMode",void 0);class da extends X{}class _a{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){this.rootNodes.slice(0).forEach((e=>{e.dispose()})),this.rootNodes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0}}class pa extends X{constructor(e){super(),this._wasAddedToScene=!1,(e=e||re.LastCreatedScene)&&(this.scene=e,this.sounds=[],this.effectLayers=[],this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.reflectionProbes=[],e.onDisposeObservable.add((()=>{this._wasAddedToScene||this.dispose()})),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();for(const e of this.particleSystems)e.rebuild();for(const e of this.textures)e._rebuild()})))}_topologicalSort(e){const t=new Map;for(const i of e)t.set(i.uniqueId,i);const i={dependsOn:new Map,dependedBy:new Map};for(const t of e){const e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(const s of e){const e=s.uniqueId,r=i.dependsOn.get(e);if(s instanceof ca){const n=s.sourceMesh;t.has(n.uniqueId)&&(r.add(n.uniqueId),i.dependedBy.get(n.uniqueId).add(e))}const n=i.dependedBy.get(e);for(const r of s.getDescendants()){const s=r.uniqueId;t.has(s)&&(n.add(s),i.dependsOn.get(s).add(e))}}const s=[],r=[];for(const s of e){const e=s.uniqueId;0===i.dependsOn.get(e).size&&(r.push(s),t.delete(e))}const n=r;for(;n.length>0;){const e=n.shift();s.push(e);const r=i.dependedBy.get(e.uniqueId);for(const s of Array.from(r.values())){const r=i.dependsOn.get(s);r.delete(e.uniqueId),0===r.size&&t.get(s)&&(n.push(t.get(s)),t.delete(s))}}return t.size>0&&(Ne.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>Ne.Error(e.name)))),s}_addNodeAndDescendantsToList(e,t,i,s){if(i&&(!s||s(i))&&!t.has(i.uniqueId)){e.push(i),t.add(i.uniqueId);for(const r of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,r,s)}}_isNodeInContainer(e){return e instanceof _o&&-1!==this.meshes.indexOf(e)||e instanceof lo&&-1!==this.transformNodes.indexOf(e)||e instanceof ua&&-1!==this.lights.indexOf(e)||e instanceof In&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return Ne.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return Ne.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return Ne.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return Ne.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Ds.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},r={},n=new _a,o=[],a=[],l={doNotInstantiate:!0,...i},h=[],c=new Set;for(const e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);for(const e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);const u=this._topologicalSort(h),d=(i,o)=>{if(((t,i)=>{if(s[t.uniqueId]=i.uniqueId,r[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof ha){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;te&&r[s[e.uniqueId]]))}}"InstancedMesh"!==n.getClassName()&&(n.material=r[s[t.uniqueId]])}else"MultiMaterial"===n.material.getClassName()?-1===this.scene.multiMaterials.indexOf(n.material)&&this.scene.addMultiMaterial(n.material):-1===this.scene.materials.indexOf(n.material)&&this.scene.addMaterial(n.material)}null===o.parent&&n.rootNodes.push(o)};return u.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,n=s[i.uniqueId],o=("number"==typeof n?r[n]:i).createInstance(t.name);d(t,o)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);const i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw new Error(`Could not clone or instantiate node on Asset Container ${e.name}`);d(e,i)}})),this.skeletons.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name);for(const e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){const t=r[s[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=i,-1!==o.indexOf(i))continue;o.push(i);for(const e of i.bones)e._linkedTransformNode&&(e._linkedTransformNode=r[s[e._linkedTransformNode.uniqueId]])}n.skeletons.push(i)})),this.animationGroups.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name,(e=>r[s[e.uniqueId]]||e));n.animationGroups.push(i)})),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Ds.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(const e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){const t=[];this.cameras.forEach((i=>{e&&!e(i)||(this.scene.addCamera(i),t.push(i))})),this.lights.forEach((i=>{e&&!e(i)||(this.scene.addLight(i),t.push(i))})),this.meshes.forEach((i=>{e&&!e(i)||(this.scene.addMesh(i),t.push(i))})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.addSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.addAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.addAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.addMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.addMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.addMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.addGeometry(t)})),this.transformNodes.forEach((i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.addActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.addTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.addReflectionProbe(t)}));for(const e of t)e.parent&&-1===this.scene.getNodes().indexOf(e.parent)&&(e.setParent?e.setParent(null):e.parent=null)}removeAllFromScene(){this._isValidHierarchy()||Ds.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach((t=>{e&&!e(t)||this.scene.removeCamera(t)})),this.lights.forEach((t=>{e&&!e(t)||this.scene.removeLight(t)})),this.meshes.forEach((t=>{e&&!e(t)||this.scene.removeMesh(t,!0)})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.removeSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.removeAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.removeMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.removeGeometry(t)})),this.transformNodes.forEach((t=>{e&&!e(t)||this.scene.removeTransformNode(t)})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.removeActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.removeTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)}))}dispose(){this.cameras.slice(0).forEach((e=>{e.dispose()})),this.cameras.length=0,this.lights.slice(0).forEach((e=>{e.dispose()})),this.lights.length=0,this.meshes.slice(0).forEach((e=>{e.dispose()})),this.meshes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach((e=>{e.dispose()})),this.multiMaterials.length=0,this.materials.slice(0).forEach((e=>{e.dispose()})),this.materials.length=0,this.geometries.slice(0).forEach((e=>{e.dispose()})),this.geometries.length=0,this.transformNodes.slice(0).forEach((e=>{e.dispose()})),this.transformNodes.length=0,this.actionManagers.slice(0).forEach((e=>{e.dispose()})),this.actionManagers.length=0,this.textures.slice(0).forEach((e=>{e.dispose()})),this.textures.length=0,this.reflectionProbes.slice(0).forEach((e=>{e.dispose()})),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach((e=>{e.dispose()})),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(e&&t)for(const s of e){let e=!0;if(i)for(const t of i)if(s===t){e=!1;break}e&&(t.push(s),s._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,void 0===e&&(e=new da);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||("_environmentTexture"===t?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new ha("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=re.LastCreatedScene,t,i=null){if(!e)return Ne.Error("No scene available to merge animations to"),[];const s=i||(t=>{let i=null;const s=t.animations.length?t.animations[0].targetProperty:"",r=t.name.split(".").join("").split("_primitive")[0];switch(s){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(r);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(r);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(r)}return i});this.getNodes().forEach((e=>{const t=s(e);if(null!==t){for(const i of e.animations){const e=t.animations.filter((e=>e.targetProperty===i.targetProperty));for(const i of e){const e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}}));const r=[];return this.animationGroups.slice().forEach((e=>{r.push(e.clone(e.name,s)),e.animatables.forEach((e=>{e.stop()}))})),t.forEach((t=>{const i=s(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))})),r}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.transformNodes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.lights.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.cameras.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}))}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const e=t.pop();if(e instanceof ha?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof lo?this.transformNodes.push(e):e instanceof ua?this.lights.push(e):e instanceof In&&this.cameras.push(e),e instanceof _o){if(e.material&&-1===this.materials.indexOf(e.material)){this.materials.push(e.material);for(const t of e.material.getActiveTextures())-1===this.textures.indexOf(t)&&this.textures.push(t)}e.skeleton&&-1===this.skeletons.indexOf(e.skeleton)&&this.skeletons.push(e.skeleton),e.morphTargetManager&&-1===this.morphTargetManagers.indexOf(e.morphTargetManager)&&this.morphTargetManagers.push(e.morphTargetManager)}for(const s of e.getChildren())i.has(s)||t.push(s);i.add(e)}this.populateRootNodes()}}class fa{constructor(e){this.SMOOTHING=.75,this.FFT_SIZE=512,this.BARGRAPHAMPLITUDE=256,this.DEBUGCANVASPOS={x:20,y:20},this.DEBUGCANVASSIZE={width:320,height:200},(e=e||re.LastCreatedScene)&&(this._scene=e,oo.audioEngine?(this._audioEngine=oo.audioEngine,this._audioEngine.canUseWebAudio&&this._audioEngine.audioContext&&(this._webAudioAnalyser=this._audioEngine.audioContext.createAnalyser(),this._webAudioAnalyser.minDecibels=-140,this._webAudioAnalyser.maxDecibels=0,this._byteFreqs=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._byteTime=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._floatFreqs=new Float32Array(this._webAudioAnalyser.frequencyBinCount))):Ds.Warn("No audio engine initialized, failed to create an audio analyser"))}getFrequencyBinCount(){return this._audioEngine.canUseWebAudio?this._webAudioAnalyser.frequencyBinCount:0}getByteFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs)),this._byteFreqs}getByteTimeDomainData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteTimeDomainData(this._byteTime)),this._byteTime}getFloatFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs)),this._floatFreqs}drawDebugCanvas(){if(this._audioEngine.canUseWebAudio&&(this._debugCanvas||(this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=this.DEBUGCANVASSIZE.width,this._debugCanvas.height=this.DEBUGCANVASSIZE.height,this._debugCanvas.style.position="absolute",this._debugCanvas.style.top=this.DEBUGCANVASPOS.y+"px",this._debugCanvas.style.left=this.DEBUGCANVASPOS.x+"px",this._debugCanvasContext=this._debugCanvas.getContext("2d"),document.body.appendChild(this._debugCanvas),this._registerFunc=()=>{this.drawDebugCanvas()},this._scene.registerBeforeRender(this._registerFunc)),this._registerFunc&&this._debugCanvasContext)){const e=this.getByteFrequencyData();this._debugCanvasContext.fillStyle="rgb(0, 0, 0)",this._debugCanvasContext.fillRect(0,0,this.DEBUGCANVASSIZE.width,this.DEBUGCANVASSIZE.height);for(let t=0;tt0&&(s=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()})),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(t,(e=>{this._soundLoaded(e)}),void 0,!0,!0,(e=>{e&&Ne.Error("XHR "+e.status+" error on: "+t+"."),Ne.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}));break}}break;default:e=!1}e?s||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)):Ne.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){Ne.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),oo.audioEngine&&!oo.audioEngine.WarnedWebAudioUnsupported&&(Ne.Error("Web Audio is not supported by your browser."),oo.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)}dispose(){oo.audioEngine?.canUseWebAudio&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,-1===this.soundTrackId?this._scene.mainSoundTrack.removeSound(this):this._scene.soundTracks&&this._scene.soundTracks[this.soundTrackId].removeSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._streamingSource&&this._streamingSource.disconnect(),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){oo.audioEngine?.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){oo.audioEngine?.audioContext&&oo.audioEngine.audioContext.decodeAudioData(e,(e=>{this._audioBufferLoaded(e)}),(e=>{Ne.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)}))}setAudioBuffer(e){oo.audioEngine?.canUseWebAudio&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){e&&(this.loop=e.loop??this.loop,this.maxDistance=e.maxDistance??this.maxDistance,this.useCustomAttenuation=e.useCustomAttenuation??this.useCustomAttenuation,this.rolloffFactor=e.rolloffFactor??this.rolloffFactor,this.refDistance=e.refDistance??this.refDistance,this.distanceModel=e.distanceModel??this.distanceModel,this._playbackRate=e.playbackRate??this._playbackRate,this._length=e.length??void 0,this.spatialSound=e.spatialSound??this._spatialSound,this._setOffset(e.offset??void 0),this.setVolume(e.volume??this._volume),this._updateSpatialParameters(),this.isPlaying&&(this._streaming&&this._htmlAudioElement?(this._htmlAudioElement.playbackRate=this._playbackRate,this._htmlAudioElement.loop!==this.loop&&(this._htmlAudioElement.loop=this.loop)):this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.loop!==this.loop&&(this._soundSource.loop=this.loop),void 0!==this._offset&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),void 0!==this._length&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(0|this._offset)+this._length))))}_createSpatialParameters(){oo.audioEngine?.canUseWebAudio&&oo.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??oo.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){this._spatialSound&&(this._inputAudioNode=this._soundGain,this._soundPanner?.disconnect(),this._soundPanner=null,this._spatialSound=!1)}_updateSpatialParameters(){this._spatialSound&&(this._soundPanner?this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel):this._createSpatialParameters())}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){oo.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){oo.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const e=()=>{if(oo.audioEngine?.unlocked){const t=this._htmlAudioElement.play();void 0!==t&&t.catch((()=>{oo.audioEngine?.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=oo.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))}))}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=oo.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))};e()}}else{const r=()=>{if(oo.audioEngine?.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){const e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=oo.audioEngine?.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,void 0!==t&&(this._soundSource.loopStart=t),void 0!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},s=e?oo.audioEngine?.audioContext.currentTime+e:oo.audioEngine.audioContext.currentTime;const r=((this.isPaused?this.currentTime:0)+(this._offset??0))%this._soundSource.buffer.duration;this._soundSource.start(s,r,this.loop?void 0:i)}}};"suspended"===oo.audioEngine?.audioContext.state?this._tryToPlayTimeout=setTimeout((()=>{"suspended"===oo.audioEngine?.audioContext.state?(oo.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=oo.audioEngine.onAudioUnlockedObservable.addOnce((()=>{r()})))):r()}),500):r()}this._startTime=s,this.isPlaying=!0,this.isPaused=!1}catch(e){Ne.Error("Error while trying to play audio: "+this.name+", "+e.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){if(this.isPlaying)if(this._clearTimeoutsAndObservers(),this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if(oo.audioEngine?.audioContext&&this._soundSource){const t=e?oo.audioEngine.audioContext.currentTime+e:void 0;this._soundSource.onended=()=>{this.isPlaying=!1,this.isPaused=!1,this._startTime=0,this._currentTime=0,this._soundSource&&(this._soundSource.onended=()=>{}),this._onended()},this._soundSource.stop(t)}else this.isPlaying=!1;else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):oo.audioEngine?.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=oo.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){oo.audioEngine?.canUseWebAudio&&this._soundGain&&(t&&oo.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(oo.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,oo.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,oo.audioEngine.audioContext.currentTime+t)):this._soundGain.gain.value=e),this._volume=e}setPlaybackRate(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))}getPlaybackRate(){return this._playbackRate}getVolume(){return this._volume}attachToMesh(e){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=e,this._spatialSound||(this._spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=e=>this._onRegisterAfterWorldMatrixUpdate(e),this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)}detachFromMesh(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)}_onRegisterAfterWorldMatrixUpdate(e){if(e.getBoundingInfo){const t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);oo.audioEngine?.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{const e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},i=new ma(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){const e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,s){const r=e.name;let n;n=e.url?i+e.url:i+r;const o={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};let a;if(s){const e=()=>{s._isReadyToPlay?(a._audioBuffer=s.getAudioBuffer(),a._isReadyToPlay=!0,a.autoplay&&a.play(0,a._offset,a._length)):setTimeout(e,300)};a=new ma(r,new ArrayBuffer(0),t,null,o),e()}else a=new ma(r,n,t,(()=>{t.removePendingData(a)}),o),t.addPendingData(a);if(e.position){const t=_e.FromArray(e.position);a.setPosition(t)}if(e.isDirectional&&(a.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const t=_e.FromArray(e.localDirectionToMesh);a.setLocalDirectionToMesh(t)}if(e.connectedMeshId){const i=t.getMeshById(e.connectedMeshId);i&&a.attachToMesh(i)}return e.metadata&&(a.metadata=e.metadata),a}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(oo.audioEngine?.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}ma._SceneComponentInitialization=e=>{throw xt("AudioSceneComponent")},z("BABYLON.Sound",ma);class ga{constructor(e,t={}){this.id=-1,this._isInitialized=!1,(e=e||re.LastCreatedScene)&&(this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1))}_initializeSoundTrackAudioGraph(){oo.audioEngine?.canUseWebAudio&&oo.audioEngine.audioContext&&(this._outputAudioNode=oo.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(oo.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(oo.audioEngine&&oo.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(e){this._isInitialized||this._initializeSoundTrackAudioGraph(),oo.audioEngine?.canUseWebAudio&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){const t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){oo.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){if(oo.audioEngine?.canUseWebAudio)for(let e=0;e{let r,n=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let o=0,a=e.sounds.length;o{e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)}))}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach((e=>{e.stop(),e.autoplay=!1,this.scene.mainSoundTrack.removeSound(e),t&&e.dispose()}))}dispose(){const e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(s=t.activeCameras[0]),this.audioListenerPositionProvider){const e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else s?this._cachedCameraPosition.equals(s.globalPosition)||(this._cachedCameraPosition.copyFrom(s.globalPosition),i.audioContext.listener.setPosition(s.globalPosition.x,s.globalPosition.y,s.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else s?(s.rigCameras&&s.rigCameras.length>0&&(s=s.rigCameras[0]),s.getViewMatrix().invertToRef(this._invertMatrixTemp),_e.TransformNormalToRef(va._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),isNaN(this._cameraDirectionTemp.x)||isNaN(this._cameraDirectionTemp.y)||isNaN(this._cameraDirectionTemp.z)||this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);for(e=0;e{let t=e._getComponent(or.NAME_AUDIO);t||(t=new va(e),e._addComponent(t))};class xa{constructor(e,t,i){if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],t.length!==i.length)throw new Error("Sounds length does not equal weights length");this.loop=e,this._weights=i;let s=0;for(const e of i)s+=e;const r=s>0?1/s:0;for(let e=0;e{this._onended()}))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAnglee),this)}serialize(){return St.Serialize(this)}parse(e,t,i){St.Parse((()=>this),e,t,i)}}Ze([nt(),st("_markSubMeshesAsAttributesDirty")],ba.prototype,"texture",void 0),Ze([rt(),st("_markSubMeshesAsAttributesDirty")],ba.prototype,"isEnabled",void 0),Ze([rt()],ba.prototype,"animationParameters",void 0),Ze([rt()],ba.prototype,"time",void 0);class Ta{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return!!this._texture&&this._texture.isCube}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return void 0!==e?.shareDepth}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=At.Zero(),this._cachedBaseSize=At.Zero(),this._initialSamplingMode=2,this._texture=Ta._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return this.isReady()&&this._texture?this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}class ya extends Ta{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return!!this._texture&&this._texture._linearSpecularLOD}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=Cs()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=ya.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new K,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?ya._IsScene(e)?this._scene=e:this._engine=e:this._scene=re.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}getTextureMatrix(){return me.IdentityReadOnly}getReflectionTextureMatrix(){return me.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,s,r,n){const o=this._getEngine();if(!o)return null;const a=o._getUseSRGBBuffer(!!r,t),l=o.getLoadedTexturesCache();for(let o=0;o=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const e=this._parentContainer.textures.indexOf(this);e>-1&&this._parentContainer.textures.splice(e,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;const t=St.Serialize(this);return St.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let s=0;s{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}function Sa(e,t,i=!1){const s=t.width,r=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let s=e[t];s<0?s=0:s>1&&(s=1),i[t]=255*s}e=i}const n=document.createElement("canvas");n.width=s,n.height=r;const o=n.getContext("2d");if(!o)return null;const a=o.createImageData(s,r);if(a.data.set(e),o.putImageData(a,0,0),i){const e=document.createElement("canvas");e.width=s,e.height=r;const t=e.getContext("2d");return t?(t.translate(0,r),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}function Ca(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=e._readPixelsSync(t,i);return r?Sa(r,e.getSize(),s.invertY):null}async function Ea(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=await e.readPixels(t,i);return r?Sa(r,e.getSize(),s.invertY):null}ya.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,Ze([rt()],ya.prototype,"uniqueId",void 0),Ze([rt()],ya.prototype,"name",void 0),Ze([rt()],ya.prototype,"metadata",void 0),Ze([rt("hasAlpha")],ya.prototype,"_hasAlpha",void 0),Ze([rt("getAlphaFromRGB")],ya.prototype,"_getAlphaFromRGB",void 0),Ze([rt()],ya.prototype,"level",void 0),Ze([rt("coordinatesIndex")],ya.prototype,"_coordinatesIndex",void 0),Ze([rt()],ya.prototype,"optimizeUVAllocation",void 0),Ze([rt("coordinatesMode")],ya.prototype,"_coordinatesMode",void 0),Ze([rt()],ya.prototype,"wrapU",null),Ze([rt()],ya.prototype,"wrapV",null),Ze([rt()],ya.prototype,"wrapR",void 0),Ze([rt()],ya.prototype,"anisotropicFilteringLevel",void 0),Ze([rt()],ya.prototype,"isCube",null),Ze([rt()],ya.prototype,"is3D",null),Ze([rt()],ya.prototype,"is2DArray",null),Ze([rt()],ya.prototype,"gammaSpace",null),Ze([rt()],ya.prototype,"invertZ",void 0),Ze([rt()],ya.prototype,"lodLevelInAlpha",void 0),Ze([rt()],ya.prototype,"lodGenerationOffset",null),Ze([rt()],ya.prototype,"lodGenerationScale",null),Ze([rt()],ya.prototype,"linearSpecularLOD",null),Ze([nt()],ya.prototype,"irradianceTexture",null),Ze([rt()],ya.prototype,"isRenderTarget",void 0);const Aa={GenerateBase64StringFromPixelData:Sa,GenerateBase64StringFromTexture:Ca,GenerateBase64StringFromTextureAsync:Ea};class Pa extends ya{static _CreateVideoTexture(e,t,i,s=!1,r=!1,n=Pa.TRILINEAR_SAMPLINGMODE,o={},a,l=5){throw xt("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,s,r=Pa.TRILINEAR_SAMPLINGMODE,n=null,o=null,a=null,l=!1,h,c,u,d,_){let p;super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=null,this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedIdentity3x2=!0,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new K,this._isBlocking=!0,this.name=e||"",this.url=e;let f=!1,m=null,g=!0;"object"==typeof i&&null!==i?(p=i.noMipmap??!1,s=i.invertY??!Xn.UseOpenGLOrientationForUV,r=i.samplingMode??Pa.TRILINEAR_SAMPLINGMODE,n=i.onLoad??null,o=i.onError??null,a=i.buffer??null,l=i.deleteBuffer??!1,h=i.format,c=i.mimeType,u=i.loaderOptions,d=i.creationFlags,f=i.useSRGBBuffer??!1,m=i.internalTexture??null,g=i.gammaSpace??g):p=!!i,this._gammaSpace=g,this._noMipmap=p,this._invertY=void 0===s?!Xn.UseOpenGLOrientationForUV:s,this._initialSamplingMode=r,this._buffer=a,this._deleteBuffer=l,this._mimeType=c,this._loaderOptions=u,this._creationFlags=d,this._useSRGBBuffer=f,this._forcedExtension=_,h&&(this._format=h);const v=this.getScene(),x=this._getEngine();if(!x)return;x.onBeforeTextureInitObservable.notifyObservers(this);const b=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),n&&n(),!this.isBlocking&&v&&v.resetCachedMaterial()},T=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},o&&o(e,t),Pa.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!m)return this._delayedOnLoad=b,void(this._delayedOnError=T);if(this._texture=m??this._getFromCache(this.url,p,r,this._invertY,f,this.isCube),this._texture)if(this._texture.isReady)Li.SetImmediate((()=>b()));else{const e=this._texture.onLoadedObservable.add(b);this._texture.onErrorObservable.add((t=>{T(t.message,t.exception),this._texture?.onLoadedObservable.remove(e)}))}else if(v&&v.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=b,this._delayedOnError=T;else{try{this._texture=x.createTexture(this.url,p,this._invertY,v,r,b,T,this._buffer,void 0,this._format,this._forcedExtension,c,u,d,f)}catch(e){throw T("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,i,s){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=s,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;const e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?Li.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,s){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,_e.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,s),s.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,s.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,s.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,this._cachedTextureMatrix&&this._rowGenerationMatrix||(this._cachedTextureMatrix=me.Zero(),this._rowGenerationMatrix=new me,this._t0=_e.Zero(),this._t1=_e.Zero(),this._t2=_e.Zero()),me.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(me.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,ve.Matrix[0]),me.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,ve.Matrix[1]),me.ScalingToRef(this._cachedUScale,this._cachedVScale,0,ve.Matrix[2]),me.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,ve.Matrix[3]),ve.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ve.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ve.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ve.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),me.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));const t=this.getScene();if(!t)return this._cachedTextureMatrix;const i=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&i!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedTextureMatrix}getReflectionTextureMatrix(){const e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode){if(this.coordinatesMode!==Pa.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=me.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=me.Zero());const t=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case Pa.PLANAR_MODE:me.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break;case Pa.PROJECTION_MODE:{me.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:me.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedReflectionTextureMatrix}clone(){const e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return St.Clone((()=>new Pa(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){const e=this.name;Pa.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(Pa._SerializeInternalTextureUniqueId);return t?((Pa.SerializeBuffers||Pa.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(t.base64String=this._buffer,t.name=t.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?t.base64String="data:image/png;base64,"+Zt(this._buffer):(Pa.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?Ca(this):Ea(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,Pa._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=this._texture?.uniqueId??void 0),t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const s=Ss.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&s.updateSamplingMode&&s._samplingMode&&s._samplingMode!==e.samplingMode&&s.updateSamplingMode(e.samplingMode),s}if(e.isCube&&!e.isRenderTarget)return Pa._CubeTextureParser(e,t,i);const s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;let r;if(s){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}const n=t=>{if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){const i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i{let s=!0;if(e.noMipmap&&(s=!1),e.mirrorPlane){const i=Pa._CreateMirror(e.name,e.renderTargetSize,t,s);return i._waitingRenderList=e.renderList,i.mirrorPlane=Nr.FromArray(e.mirrorPlane),n(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{n(o)}),e._creationFlags??0,e._useSRGBBuffer??!1),o.name=e.name;else{let a;a=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||Pa.UseSerializedUrlIfAny)&&(a=e.url);const l={noMipmap:!s,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(o)},internalTexture:r};o=new Pa(a,t,l)}return o}}),e,t)}static CreateFromBase64String(e,t,i,s,r,n=Pa.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=5,h,c){return new Pa("data:"+t,i,s,r,n,o,a,e,!1,l,void 0,void 0,h,c)}static LoadFromDataString(e,t,i,s=!1,r,n=!0,o=Pa.TRILINEAR_SAMPLINGMODE,a=null,l=null,h=5,c,u){return"data:"!==e.substr(0,5)&&(e="data:"+e),new Pa(e,i,r,n,o,a,l,t,s,h,void 0,void 0,c,u)}}function Ia(e,t,i,s){let r,n=1;1===s?r=new Float32Array(t*i*4):2===s?(r=new Uint16Array(t*i*4),n=15360):r=7===s?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let s=0;s{throw xt("CubeTexture")},Pa._CreateMirror=(e,t,i,s)=>{throw xt("MirrorTexture")},Pa._CreateRenderTargetTexture=(e,t,i,s,r)=>{throw xt("RenderTargetTexture")},Pa.NEAREST_SAMPLINGMODE=1,Pa.NEAREST_NEAREST_MIPLINEAR=8,Pa.BILINEAR_SAMPLINGMODE=2,Pa.LINEAR_LINEAR_MIPNEAREST=11,Pa.TRILINEAR_SAMPLINGMODE=3,Pa.LINEAR_LINEAR_MIPLINEAR=3,Pa.NEAREST_NEAREST_MIPNEAREST=4,Pa.NEAREST_LINEAR_MIPNEAREST=5,Pa.NEAREST_LINEAR_MIPLINEAR=6,Pa.NEAREST_LINEAR=7,Pa.NEAREST_NEAREST=1,Pa.LINEAR_NEAREST_MIPNEAREST=9,Pa.LINEAR_NEAREST_MIPLINEAR=10,Pa.LINEAR_LINEAR=2,Pa.LINEAR_NEAREST=12,Pa.EXPLICIT_MODE=0,Pa.SPHERICAL_MODE=1,Pa.PLANAR_MODE=2,Pa.CUBIC_MODE=3,Pa.PROJECTION_MODE=4,Pa.SKYBOX_MODE=5,Pa.INVCUBIC_MODE=6,Pa.EQUIRECTANGULAR_MODE=7,Pa.FIXED_EQUIRECTANGULAR_MODE=8,Pa.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Pa.CLAMP_ADDRESSMODE=0,Pa.WRAP_ADDRESSMODE=1,Pa.MIRROR_ADDRESSMODE=2,Pa.UseSerializedUrlIfAny=!1,Ze([rt()],Pa.prototype,"url",void 0),Ze([rt()],Pa.prototype,"uOffset",void 0),Ze([rt()],Pa.prototype,"vOffset",void 0),Ze([rt()],Pa.prototype,"uScale",void 0),Ze([rt()],Pa.prototype,"vScale",void 0),Ze([rt()],Pa.prototype,"uAng",void 0),Ze([rt()],Pa.prototype,"vAng",void 0),Ze([rt()],Pa.prototype,"wAng",void 0),Ze([rt()],Pa.prototype,"uRotationCenter",void 0),Ze([rt()],Pa.prototype,"vRotationCenter",void 0),Ze([rt()],Pa.prototype,"wRotationCenter",void 0),Ze([rt()],Pa.prototype,"homogeneousRotationInUVTransform",void 0),Ze([rt()],Pa.prototype,"isBlocking",null),z("BABYLON.Texture",Pa),St._TextureParser=Pa.Parse,qs.prototype.updateRawTexture=function(e,t,i,s,r=null,n=0,o=!1){if(!e)return;const a=this._getRGBABufferInternalSizedFormat(n,i,o),l=this._getInternalFormat(i),h=this._getWebGLTextureType(n);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=n,e.invertY=s,e._compression=r),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[r],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,e.width,e.height,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0},qs.prototype.createRawTexture=function(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new ss(this,is.Raw);u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u._compression=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!r),this._doNotHandleContextLost||(u._bufferView=e),this.updateRawTexture(u,e,s,n,a,l,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);const d=this._getSamplingParameters(o,r);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),r&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u},qs.prototype.createRawCubeTexture=function(e,t,i,s,r,n,o,a=null){const l=this._gl,h=new ss(this,is.CubeRaw);h.isCube=!0,h.format=i,h.type=s,this._doNotHandleContextLost||(h._bufferViewArray=e);const c=this._getWebGLTextureType(s);let u=this._getInternalFormat(i);u===l.RGB&&(u=l.RGBA),c!==l.FLOAT||this._caps.textureFloatLinearFiltering?c!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?c!==l.FLOAT||this._caps.textureFloatRender?c!==l.HALF_FLOAT||this._caps.colorBufferFloat||(r=!1,Ne.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(r=!1,Ne.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(r=!1,o=1,Ne.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(r=!1,o=1,Ne.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."));const d=t,_=d;if(h.width=d,h.height=_,h.invertY=n,h._compression=a,!this.needPOTTextures||As(h.width)&&As(h.height)||(r=!1),e)this.updateRawCubeTexture(h,e,i,s,n,a);else{const e=this._getRGBABufferInternalSizedFormat(s),t=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let i=0;i<6;i++)a?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,this.getCaps().s3tc[a],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,e,h.width,h.height,0,u,c,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),e&&r&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const p=this._getSamplingParameters(o,r);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,p.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,p.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),h.generateMipMaps=r,h.samplingMode=o,h.isReady=!0,h},qs.prototype.updateRawCubeTexture=function(e,t,i,s,r,n=null,o=0){e._bufferViewArray=t,e.format=i,e.type=s,e.invertY=r,e._compression=n;const a=this._gl,l=this._getWebGLTextureType(s);let h=this._getInternalFormat(i);const c=this._getRGBABufferInternalSizedFormat(s);let u=!1;h===a.RGB&&(h=a.RGBA,u=!0),this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===r||!!r),e.width%4!=0&&a.pixelStorei(a.UNPACK_ALIGNMENT,1);for(let i=0;i<6;i++){let r=t[i];n?a.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+i,o,this.getCaps().s3tc[n],e.width,e.height,0,r):(u&&(r=Ia(r,e.width,e.height,s)),a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+i,o,c,e.width,e.height,0,h,l,r))}(!this.needPOTTextures||As(e.width)&&As(e.height))&&e.generateMipMaps&&0===o&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},qs.prototype.createRawCubeTextureFromUrl=function(e,t,i,s,r,n,o,a,l=null,h=null,c=3,u=!1){const d=this._gl,_=this.createRawCubeTexture(null,i,s,r,!n,u,c,null);t?.addPendingData(_),_.url=e,_.isReady=!1,this._internalTexturesCache.push(_);const p=e=>{const i=_.width,n=o(e);if(n){if(a){const e=this._getWebGLTextureType(r);let t=this._getInternalFormat(s);const o=this._getRGBABufferInternalSizedFormat(r);let l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,_,!0),this._unpackFlipY(!1);const h=a(n);for(let s=0;s>s;for(let i=0;i<6;i++){let a=h[s][i];l&&(a=Ia(a,n,n,r)),d.texImage2D(i,s,o,n,n,0,t,e,a)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(_,n,s,r,u);_.isReady=!0,t?.removePendingData(_),_.onLoadedObservable.notifyObservers(_),_.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,(e=>{p(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(_),h&&e&&h(e.status+" "+e.statusText,i)})),_},qs.prototype.createRawTexture2DArray=Ra(!1),qs.prototype.createRawTexture3D=Ra(!0),qs.prototype.updateRawTexture2DArray=Ma(!1),qs.prototype.updateRawTexture3D=Ma(!0);class Oa extends Pa{constructor(e,t,i,s,r,n=!0,o=!1,a=3,l=0,h,c){super(null,r,!n,o,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=s,this._engine&&(this._engine._caps.textureFloatLinearFiltering||1!==l||(a=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(a=1),this._texture=this._engine.createRawTexture(e,t,i,s,n,o,a,null,l,h??0,c??!1),this.wrapU=Pa.CLAMP_ADDRESSMODE,this.wrapV=Pa.CLAMP_ADDRESSMODE)}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}static CreateLuminanceTexture(e,t,i,s,r=!0,n=!1,o=3){return new Oa(e,t,i,1,s,r,n,o)}static CreateLuminanceAlphaTexture(e,t,i,s,r=!0,n=!1,o=3){return new Oa(e,t,i,2,s,r,n,o)}static CreateAlphaTexture(e,t,i,s,r=!0,n=!1,o=3){return new Oa(e,t,i,0,s,r,n,o)}static CreateRGBTexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=0,h=!1){return new Oa(e,t,i,4,s,r,n,o,a,l,h)}static CreateRGBATexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=0,h=!1){return new Oa(e,t,i,5,s,r,n,o,a,l,h)}static CreateRGBAStorageTexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=!1){return new Oa(e,t,i,5,s,r,n,o,a,1,l)}static CreateRTexture(e,t,i,s,r=!0,n=!1,o=Pa.TRILINEAR_SAMPLINGMODE,a=1){return new Oa(e,t,i,6,s,r,n,o,a)}static CreateRStorageTexture(e,t,i,s,r=!0,n=!1,o=Pa.TRILINEAR_SAMPLINGMODE,a=1){return new Oa(e,t,i,6,s,r,n,o,a,1)}}class Da{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=me.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new K,this.bones=[],this._scene=i||re.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const s=this._scene.getEngine().getCaps();this._canUseTextureForBones=s.textureFloat&&s.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter((e=>!e.getParent()))}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return this._transformMatrices&&!this._isDirty||this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0)for(const e of this.bones)if(e._linkedTransformNode){const t=e._linkedTransformNode;e.position=t.position,t.rotationQuaternion?e.rotationQuaternion=t.rotationQuaternion:e.rotation=t.rotation,e.scaling=t.scaling}if(this.needInitialSkinMatrix)for(const e of this._meshesWithPoseMatrix){const t=e.getPoseMatrix();let i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){this._synchronizedWithMesh=e;for(const e of this.bones)e.getParent()||(e.getBindMatrix().multiplyToRef(t,ve.Matrix[1]),e._updateAbsoluteBindMatrices(ve.Matrix[1]));if(this.isUsingTextureForMatrices){const t=4*(this.bones.length+1);e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=Oa.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(e._bonesTransformMatrices,t),this.isUsingTextureForMatrices&&e._transformMatrixTexture&&e._transformMatrixTexture.update(e._bonesTransformMatrices)}}else{if(!this._isDirty)return;this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=Oa.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e{t.animations.forEach((t=>{t.enableBlending=!0,t.blendingSpeed=e}))}))}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){const e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){const e={};e.name=this.name,e.id=this.id,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let t=0;t0&&(r.animation=i.animations[0].serialize()),e.ranges=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const s={};s.name=t,s.from=i.from,s.to=i.to,e.ranges.push(s)}}return e}static Parse(e,t){const i=new Da(e.name,e.id,t);let s;for(e.dimensionsAtRest&&(i.dimensionsAtRest=_e.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,s=0;s-1&&(n=i.bones[t.parentBoneIndex]);const o=t.rest?me.FromArray(t.rest):null,a=new Yr(t.name,i,n,me.FromArray(t.matrix),o,null,r);void 0!==t.id&&null!==t.id&&(a.id=t.id),t.length&&(a.length=t.length),t.metadata&&(a.metadata=t.metadata),t.animation&&a.animations.push(Ft.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,a._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(s=0;s0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()}))}}class wa{constructor(e,t){this._scene=e,t instanceof Da?(this._skeleton=t,this._mesh=null):(this._mesh=t,this._skeleton=t.skeleton)}async bakeVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=e.reduce(((e,t)=>e+t.to-t.from+1),0);if(isNaN(i))throw new Error("Invalid animation ranges.");let s=0;const r=new Float32Array(4*(t+1)*4*i);this._scene.stopAnimation(this._skeleton),this._skeleton.returnToRest();for(const t of e)for(let e=t.from;e<=t.to;e++)await this._executeAnimationFrame(r,e,s++);return r}async _executeAnimationFrame(e,t,i){return new Promise(((s,r)=>{this._scene.beginAnimation(this._skeleton,t,t,!1,1,(()=>{const t=this._skeleton.getTransformMatrices(this._mesh);e.set(t,i*t.length),s()}))}))}textureFromBakedVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=Oa.CreateRGBATexture(e,4*(t+1),e.length/(4*(t+1)*4),this._scene,!1,!1,Pa.NEAREST_NEAREST,1);return i.name="VAT"+this._skeleton.name,i}serializeBakedVertexDataToObject(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=4*(t+1),s=e.length/(4*(t+1)*4);return{vertexData:Zt(e),width:i,height:s}}loadBakedVertexDataFromObject(e){return new Float32Array(ei(e.vertexData))}serializeBakedVertexDataToJSON(e){return JSON.stringify(this.serializeBakedVertexDataToObject(e))}loadBakedVertexDataFromJSON(e){return this.loadBakedVertexDataFromObject(JSON.parse(e))}}class Na{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==lr.POINTERDOWN?e.type===lr.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=Wt.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const i=e-this._lastInteractionTime-this._idleRotationWaitTime,s=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*s,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=e??Wt.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(e&&(e.computeWorldMatrix(!0),e.getBoundingInfo)){const t=e.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=.05*t,this.upperRadiusTransitionRange=.05*t}})):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))}))}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return!!this._attachedCamera&&this._attachedCamera.radius===e&&!this._radiusIsAnimating}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(Fa.EasingFunction.setEasingMode(Fa.EasingMode),this._radiusBounceTransition=Ft.CreateAnimation("radius",Ft.ANIMATIONTYPE_FLOAT,60,Fa.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=Ft.TransitionTo("radius",this._attachedCamera.radius+e,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,(()=>this._clearAnimationLocks()));t&&this._animatables.push(t)}_clearAnimationLocks(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()}}Fa.EasingFunction=new rn(.3),Fa.EasingMode=tn.EASINGMODE_EASEOUT;class La{constructor(){this.onTargetFramingAnimationEndObservable=new K,this._mode=La.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}get name(){return"Framing"}set mode(e){this._mode=e}get mode(){return this._mode}set radiusScale(e){this._radiusScale=e}get radiusScale(){return this._radiusScale}set positionScale(e){this._positionScale=e}get positionScale(){return this._positionScale}set defaultElevation(e){this._defaultElevation=e}get defaultElevation(){return this._defaultElevation}set elevationReturnTime(e){this._elevationReturnTime=e}get elevationReturnTime(){return this._elevationReturnTime}set elevationReturnWaitTime(e){this._elevationReturnWaitTime=e}get elevationReturnWaitTime(){return this._elevationReturnWaitTime}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set framingTime(e){this._framingTime=e}get framingTime(){return this._framingTime}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();La.EasingFunction.setEasingMode(La.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==lr.POINTERDOWN?e.type===lr.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add((e=>{e&&e.getBoundingInfo&&this.zoomOnMesh(e,void 0,(()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()}))})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(s.minimumWorld,s.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(s.min,s.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const s=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new _e(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t{this.stopAllAnimations(),s&&s(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),l&&this._animatables.push(l),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let s=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===La.IgnoreBoundsSizeMode&&(s=si.upperRadiusLimit?i.upperRadiusLimit:s),s}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=Wt.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation,i=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=Ft.CreateAnimation("beta",Ft.ANIMATIONTYPE_FLOAT,60,La.EasingFunction));const e=Ft.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(()=>{this._clearAnimationLocks(),this.stopAllAnimations()}));e&&this._animatables.push(e)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=Wt.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}La.EasingFunction=new ln,La.EasingMode=tn.EASINGMODE_EASEINOUT,La.IgnoreBoundsSizeMode=0,La.FitFrustumSidesMode=1;class Ba{constructor(e,t=new _e,i=0,s=!1){this.direction=e,this.rotatedDirection=t,this.diff=i,this.ignore=s}}class ka{constructor(e){this._ui=e,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new Ba(_e.Up()),new Ba(_e.Down()),new Ba(_e.Left()),new Ba(_e.Right()),new Ba(_e.Forward()),new Ba(_e.Forward().scaleInPlace(-1))],this._tmpMatrix=new me,this._tmpVector=new _e,this._zeroVector=_e.Zero(),this._lookAtTmpMatrix=new me}init(){}_closestFace(e){return this._faceVectors.forEach((t=>{this._target.rotationQuaternion||(this._target.rotationQuaternion=fe.RotationYawPitchRoll(this._target.rotation.y,this._target.rotation.x,this._target.rotation.z)),this._target.rotationQuaternion.toRotationMatrix(this._tmpMatrix),_e.TransformCoordinatesToRef(t.direction,this._tmpMatrix,t.rotatedDirection),t.diff=_e.GetAngleBetweenVectors(t.rotatedDirection,e,_e.Cross(t.rotatedDirection,e))})),this._faceVectors.reduce(((e,t)=>e.ignore?t:t.ignore||e.diff{if(!this._scene.activeCamera)return;let t=this._scene.activeCamera.position;this._scene.activeCamera.devicePosition&&(t=this._scene.activeCamera.devicePosition);const i=this._closestFace(t.subtract(e.position));this._scene.activeCamera.leftCamera?this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix):this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix),_e.TransformCoordinatesToRef(_e.Up(),this._tmpMatrix,this._tmpVector),this._faceVectors.forEach((e=>{i.direction.x&&e.direction.x&&(e.ignore=!0),i.direction.y&&e.direction.y&&(e.ignore=!0),i.direction.z&&e.direction.z&&(e.ignore=!0)}));const s=this._closestFace(this._tmpVector);this._faceVectors.forEach((e=>{e.ignore=!1})),this._ui.position.copyFrom(e.position),i.direction.x&&(i.rotatedDirection.scaleToRef(e.scaling.x/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.y&&(i.rotatedDirection.scaleToRef(e.scaling.y/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.z&&(i.rotatedDirection.scaleToRef(e.scaling.z/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),this._ui.rotationQuaternion||(this._ui.rotationQuaternion=fe.RotationYawPitchRoll(this._ui.rotation.y,this._ui.rotation.x,this._ui.rotation.z)),i.rotatedDirection.scaleToRef(-1,this._tmpVector),this._lookAtToRef(this._tmpVector,s.rotatedDirection,this._ui.rotationQuaternion),s.direction.x&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.x/2,this._tmpVector),s.direction.y&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.y/2,this._tmpVector),s.direction.z&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.z/2,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)}))}detach(){this._scene.onBeforeRenderObservable.remove(this._onRenderObserver)}}class Va{get delay(){return this.fadeInDelay}set delay(e){this.fadeInDelay=e,this.fadeOutDelay=e}constructor(){this.fadeInDelay=0,this.fadeOutDelay=0,this.fadeInTime=300,this.fadeOutTime=300,this._millisecondsPerFrame=1e3/60,this._hovered=!1,this._hoverValue=0,this._ownerNode=null,this._delay=0,this._time=300,this._update=()=>{if(this._ownerNode){if(this._hoverValue+=this._hovered?this._millisecondsPerFrame:-this._millisecondsPerFrame,this._setAllVisibility(this._ownerNode,(this._hoverValue-this._delay)/this._time),this._ownerNode.visibility>1){if(this._setAllVisibility(this._ownerNode,1),this._hoverValue>this._time)return this._hoverValue=this._time,void this._detachObserver()}else if(this._ownerNode.visibility<0&&(this._setAllVisibility(this._ownerNode,0),this._hoverValue<0))return this._hoverValue=0,void this._detachObserver();this._attachObserver()}}}get name(){return"FadeInOut"}init(){}attach(e){this._ownerNode=e,this._setAllVisibility(this._ownerNode,0)}detach(){this._ownerNode=null}fadeIn(e=!0){this._delay=e?this.fadeInDelay:this.fadeOutDelay,this._time=e?this.fadeInTime:this.fadeOutTime,this._detachObserver(),this._ownerNode&&(e&&this._ownerNode.visibility>=1||!e&&this._ownerNode.visibility<=0)||(this._hovered=e,this._hovered||(this._delay*=-1),this._ownerNode.visibility>=1?this._hoverValue=this._time:this._ownerNode.visibility<=0&&(this._hoverValue=0),this._update())}fadeOut(){this.fadeIn(!1)}_setAllVisibility(e,t){e.visibility=t,e.getChildMeshes().forEach((e=>{this._setAllVisibility(e,t)}))}_attachObserver(){this._onBeforeRenderObserver||(this._onBeforeRenderObserver=this._ownerNode?.getScene().onBeforeRenderObservable.add(this._update))}_detachObserver(){this._onBeforeRenderObserver&&(this._ownerNode?.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=null)}}class Ua{constructor(e,t,i=Number.MAX_VALUE,s=J){this.origin=e,this.direction=t,this.length=i,this.epsilon=s}clone(){return new Ua(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const s=Ua._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),r=Ua._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let n,o,a,l,h=0,c=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xr.x)return!1}else if(n=1/this.direction.x,o=(s.x-this.origin.x)*n,a=(r.x-this.origin.x)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yr.y)return!1}else if(n=1/this.direction.y,o=(s.y-this.origin.y)*n,a=(r.y-this.origin.y)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zr.z)return!1}else if(n=1/this.direction.z,o=(s.z-this.origin.z)*n,a=(r.z-this.origin.z)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){const i=e.center.x-this.origin.x,s=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=i*i+s*s+r*r,o=e.radius+t,a=o*o;if(n<=a)return!0;const l=i*this.direction.x+s*this.direction.y+r*this.direction.z;return!(l<0)&&n-l*l<=a}intersectsTriangle(e,t,i){const s=Ua._TmpVector3[0],r=Ua._TmpVector3[1],n=Ua._TmpVector3[2],o=Ua._TmpVector3[3],a=Ua._TmpVector3[4];t.subtractToRef(e,s),i.subtractToRef(e,r),_e.CrossToRef(this.direction,r,n);const l=_e.Dot(s,n);if(0===l)return null;const h=1/l;this.origin.subtractToRef(e,o);const c=_e.Dot(o,n)*h;if(c<-this.epsilon||c>1+this.epsilon)return null;_e.CrossToRef(o,s,a);const u=_e.Dot(this.direction,a)*h;if(u<-this.epsilon||c+u>1+this.epsilon)return null;const d=_e.Dot(r,a)*h;return d>this.length?null:new Rn(1-c-u,c,d)}intersectsPlane(e){let t;const i=_e.Dot(e.normal,this.direction);if(Math.abs(i)<9.99999997475243e-7)return null;{const s=_e.Dot(e.normal,this.origin);return t=(-e.d-s)/i,t<0?t<-9.99999997475243e-7?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const e=(this.origin.y-t)/this.direction.y;return e>0?null:new _e(this.origin.x+this.direction.x*-e,t,this.origin.z+this.direction.z*-e)}case"x":{const e=(this.origin.x-t)/this.direction.x;return e>0?null:new _e(t,this.origin.y+this.direction.y*-e,this.origin.z+this.direction.z*-e)}case"z":{const e=(this.origin.z-t)/this.direction.z;return e>0?null:new _e(this.origin.x+this.direction.x*-e,this.origin.y+this.direction.y*-e,t)}default:return null}}intersectsMesh(e,t,i,s=!1,r,n=!1){const o=ve.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?Ua.TransformToRef(this,o,this._tmpRay):this._tmpRay=Ua.Transform(this,o),e.intersects(this._tmpRay,t,i,s,r,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let s=0;st.distance?1:0}intersectionSegment(e,t,i){const s=this.origin,r=ve.Vector3[0],n=ve.Vector3[1],o=ve.Vector3[2],a=ve.Vector3[3];t.subtractToRef(e,r),this.direction.scaleToRef(Ua._Rayl,o),s.addToRef(o,n),e.subtractToRef(s,a);const l=_e.Dot(r,r),h=_e.Dot(r,o),c=_e.Dot(o,o),u=_e.Dot(r,a),d=_e.Dot(o,a),_=l*c-h*h;let p,f,m=_,g=_;_m&&(p=m,f=d+h,g=c)),f<0?(f=0,-u<0?p=0:-u>l?p=m:(p=-u,m=l)):f>g&&(f=g,-u+h<0?p=0:-u+h>l?p=m:(p=-u+h,m=l));const v=Math.abs(p)0&&x<=this.length&&y.lengthSquared()=e.distance?null:h:null},Hr.prototype._internalPick=function(e,t,i,s,r){let n=null;const o=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),a=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),n=this.cameraToUseForPointers||this.activeCamera;for(let o=0;o(this._tempPickingRay||(this._tempPickingRay=Ua.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,r||null),this._tempPickingRay)),i,s,!0);return n&&(n.ray=this.createPickingRay(e,t,me.Identity(),r||null)),n},Object.defineProperty(Hr.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),Hr.prototype.pick=function(e,t,i,s,r,n,o=!1){const a=this._internalPick(((i,s)=>(this._tempPickingRay||(this._tempPickingRay=Ua.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,r||null,!1,s),this._tempPickingRay)),i,s,!1,n);return a&&(a.ray=this.createPickingRay(e,t,me.Identity(),r||null)),a},Hr.prototype.pickWithRay=function(e,t,i,s){const r=this._internalPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=me.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Ua.Zero()),Ua.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i,!1,s);return r&&(r.ray=e),r},Hr.prototype.multiPick=function(e,t,i,s,r){return this._internalMultiPick((i=>this.createPickingRay(e,t,i,s||null)),i,r)},Hr.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=me.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Ua.Zero()),Ua.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i)},In.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new Ua(_e.Zero(),_e.Zero(),e),e,t,i)},In.prototype.getForwardRayToRef=function(e,t=100,i,s){i||(i=this.getWorldMatrix()),e.length=t,s?e.origin.copyFrom(s):e.origin.copyFrom(this.position);const r=ve.Vector3[2];r.set(0,0,this._scene.useRightHandedSystem?-1:1);const n=ve.Vector3[3];return _e.TransformNormalToRef(r,i,n),_e.NormalizeToRef(n,e.direction),e};class Ga{static _RemoveAndStorePivotPoint(e){e&&0===Ga._PivotCached&&(e.getPivotPointToRef(Ga._OldPivotPoint),Ga._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,Ga._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(me.IdentityReadOnly),Ga._OldPivotPoint.subtractToRef(e.getPivotPoint(),Ga._PivotTranslation),Ga._PivotTmpVector.copyFromFloats(1,1,1),Ga._PivotTmpVector.subtractInPlace(e.scaling),Ga._PivotTmpVector.multiplyInPlace(Ga._PivotTranslation),e.position.addInPlace(Ga._PivotTmpVector))),Ga._PivotCached++}static _RestorePivotPoint(e){e&&!Ga._OldPivotPoint.equalsToFloats(0,0,0)&&1===Ga._PivotCached&&(e.setPivotPoint(Ga._OldPivotPoint),e._postMultiplyPivotMatrix=Ga._PivotPostMultiplyPivotMatrix,Ga._PivotTmpVector.copyFromFloats(1,1,1),Ga._PivotTmpVector.subtractInPlace(e.scaling),Ga._PivotTmpVector.multiplyInPlace(Ga._PivotTranslation),e.position.subtractInPlace(Ga._PivotTmpVector)),this._PivotCached--}}function za(e){const t=[],i=[],s=[],r=[],n=e.width||e.size||1,o=e.height||e.size||1,a=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,l=n/2,h=o/2;i.push(-l,-h,0),s.push(0,0,-1),r.push(0,Xn.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),s.push(0,0,-1),r.push(1,Xn.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),s.push(0,0,-1),r.push(1,Xn.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),s.push(0,0,-1),r.push(0,Xn.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),Wn._ComputeSides(a,i,t,s,r,e.frontUVs,e.backUVs);const c=new Wn;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function Wa(e,t={},i=null){const s=new ha(e,i);return t.sideOrientation=ha._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,za(t).applyToMesh(s,t.updatable),t.sourcePlane&&(s.translate(t.sourcePlane.normal,-t.sourcePlane.d),s.setDirection(t.sourcePlane.normal.scale(-1))),s}Ga._PivotCached=0,Ga._OldPivotPoint=new _e,Ga._PivotTranslation=new _e,Ga._PivotTmpVector=new _e,Ga._PivotPostMultiplyPivotMatrix=!1;const Ha={CreatePlane:Wa};Wn.CreatePlane=za,ha.CreatePlane=(e,t,i,s,r)=>Wa(e,{size:t,width:t,height:t,sideOrientation:r,updatable:s},i);class Xa{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new K,this.onDragStartObservable=new K,this.onDragEndObservable=new K,this.onEnabledObservable=new K,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new _e(0,0,0),this._alternatePickedPoint=new _e(0,0,0),this._worldDragAxis=new _e(0,0,0),this._targetPosition=new _e(0,0,0),this._attachedToElement=!1,this._startDragRay=new Ua(new _e,new _e),this._lastPointerRay={},this._dragDelta=new _e,this._pointA=new _e(0,0,0),this._pointC=new _e(0,0,0),this._localAxis=new _e(0,0,0),this._lookAt=new _e(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,Xa._PlaneScene||(this._debugMode?Xa._PlaneScene=this._scene:(Xa._PlaneScene=new Hr(this._scene.getEngine(),{virtual:!0}),Xa._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce((()=>{Xa._PlaneScene.dispose(),Xa._PlaneScene=null})))),this._dragPlane=Wa("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:ha.DOUBLESIDE},Xa._PlaneScene),this.lastDragPosition=new _e(0,0,0);const i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add((e=>{if(this.enabled){if(e.type==lr.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&i(e.pickInfo.pickedMesh)&&-1===this._activeDragButton&&-1!==this.dragButtons.indexOf(e.event.button)&&(this._activeDragButton=e.event.button,this._activePointerInfo=e,this._startDrag(e.event.pointerId,e.pickInfo.ray,e.pickInfo.pickedPoint));else if(e.type==lr.POINTERUP)!this.startAndReleaseDragOnPointerEvents||this.currentDraggingPointerId!=e.event.pointerId||this._activeDragButton!==e.event.button&&-1!==this._activeDragButton||this.releaseDrag();else if(e.type==lr.POINTERMOVE){const t=e.event.pointerId;if(this.currentDraggingPointerId===Xa._AnyMouseId&&t!==Xa._AnyMouseId){const i=e.event;("mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[t]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=t)}this._lastPointerRay[t]||(this._lastPointerRay[t]=new Ua(new _e,new _e)),e.pickInfo&&e.pickInfo.ray&&(this._lastPointerRay[t].origin.copyFrom(e.pickInfo.ray.origin),this._lastPointerRay[t].direction.copyFrom(e.pickInfo.ray.direction),this.currentDraggingPointerId==t&&this.dragging&&this._moveDrag(e.pickInfo.ray))}}else this._attachedToElement&&this.releaseDrag()})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{if(this._moving&&this.moveAttached){let e=!1;Ga._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),e=!0),Ga._RestorePivotPoint(this.attachedNode),e&&this.attachedNode.computeWorldMatrix()}}))}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){const e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}}startDrag(e=Xa._AnyMouseId,t,i){this._startDrag(e,t,i);let s=this._lastPointerRay[e];e===Xa._AnyMouseId&&(s=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),s&&this._moveDrag(s)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;Ga._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);const s=this._pickWithRayOnDragPlane(this._startDragRay);s?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(s),this.onDragStartObservable.notifyObservers({dragPlanePoint:s,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),Ga._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;const t=this._pickWithRayOnDragPlane(e);if(t){Ga._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?_e.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=_e.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),Ga._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(_e.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*_e.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);const t=_e.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-t,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}return null}const i=this._dragPlane.forward,s=this._dragPlane.position,r=e.direction.dot(i);if(Math.abs(r).999?Math.abs(_e.Dot(_e.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(_e.Right()):this._lookAt.copyFrom(_e.UpReadOnly):(_e.CrossToRef(this._localAxis,this._pointC,this._lookAt),_e.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?_e.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}}Xa._AnyMouseId=-2;class Ya{constructor(){this._startDistance=0,this._initialScale=new _e(0,0,0),this._targetScale=new _e(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new Xa({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new Xa({}),this._dragBehaviorB.moveAttached=!1}get name(){return"MultiPointerScale"}init(){}_getCurrentDistance(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()}attach(e){this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add((()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorA.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))})),this._dragBehaviorB.onDragStartObservable.add((()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorB.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))})),[this._dragBehaviorA,this._dragBehaviorB].forEach((e=>{e.onDragObservable.add((()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const e=this._getCurrentDistance()/this._startDistance;this._initialScale.scaleToRef(e,this._targetScale)}}))})),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const t=this._targetScale.subtract(e.scaling).scaleInPlace(.1);t.length()>.01&&e.scaling.addInPlace(t)}}))}detach(){this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach((e=>{e.onDragStartObservable.clear(),e.onDragObservable.clear(),this._ownerNode.removeBehavior(e)}))}}class Qa{constructor(){this._attachedToElement=!1,this._virtualMeshesInfo={},this._tmpVector=new _e,this._tmpQuaternion=new fe,this._dragType={NONE:0,DRAG:1,DRAG_WITH_CONTROLLER:2,NEAR_DRAG:3},this._moving=!1,this._dragging=this._dragType.NONE,this.draggableMeshes=null,this.zDragFactor=3,this.currentDraggingPointerIds=[],this.detachCameraControls=!0,this.onDragStartObservable=new K,this.onDragObservable=new K,this.onDragEndObservable=new K,this.allowMultiPointer=!0}get currentDraggingPointerId(){return void 0!==this.currentDraggingPointerIds[0]?this.currentDraggingPointerIds[0]:-1}set currentDraggingPointerId(e){this.currentDraggingPointerIds[0]=e}get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}get name(){return"BaseSixDofDrag"}get isMoving(){return this._moving}init(){}get _pointerCamera(){return this._scene.cameraToUseForPointers?this._scene.cameraToUseForPointers:this._scene.activeCamera}_createVirtualMeshInfo(){const e=new _o("",Qa._virtualScene);e.rotationQuaternion=new fe;const t=new _o("",Qa._virtualScene);t.rotationQuaternion=new fe;const i=new _o("",Qa._virtualScene);return i.rotationQuaternion=new fe,{dragging:!1,moving:!1,dragMesh:e,originMesh:t,pivotMesh:i,startingPivotPosition:new _e,startingPivotOrientation:new fe,startingPosition:new _e,startingOrientation:new fe,lastOriginPosition:new _e,lastDragPosition:new _e}}_resetVirtualMeshesPosition(){for(let e=0;el&&(l=Math.min(h-a,0)),o.scaleInPlace(l),o.addToRef(r.pivotMesh.absolutePosition,this._tmpVector),r.pivotMesh.setAbsolutePosition(this._tmpVector),o.addToRef(r.dragMesh.absolutePosition,this._tmpVector),r.dragMesh.setAbsolutePosition(this._tmpVector)}}attach(e){this._ownerNode=e,this._scene=this._ownerNode.getScene(),Qa._virtualScene||(Qa._virtualScene=new Hr(this._scene.getEngine(),{virtual:!0}),Qa._virtualScene.detachControl());const t=e=>this._ownerNode===e||e.isDescendantOf(this._ownerNode)&&(!this.draggableMeshes||-1!==this.draggableMeshes.indexOf(e));this._pointerObserver=this._scene.onPointerObservable.add((e=>{const i=e.event.pointerId;this._virtualMeshesInfo[i]||(this._virtualMeshesInfo[i]=this._createVirtualMeshInfo());const s=this._virtualMeshesInfo[i],r="xr-near"===e.event.pointerType||"xr"===e.event.pointerType;if(e.type==lr.POINTERDOWN){if(!s.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&(!r||e.pickInfo.aimTransform)&&t(e.pickInfo.pickedMesh)){if((!this.allowMultiPointer||r)&&this.currentDraggingPointerIds.length>0)return;!this._pointerCamera||this._pointerCamera.cameraRigMode!==In.RIG_MODE_NONE||this._pointerCamera._isLeftCamera||this._pointerCamera._isRightCamera||e.pickInfo.ray.origin.copyFrom(this._pointerCamera.globalPosition),this._ownerNode.computeWorldMatrix(!0);const t=this._virtualMeshesInfo[i];r?(this._dragging=e.pickInfo.originMesh?this._dragType.NEAR_DRAG:this._dragType.DRAG_WITH_CONTROLLER,t.originMesh.position.copyFrom(e.pickInfo.aimTransform.position),this._dragging===this._dragType.NEAR_DRAG&&e.pickInfo.gripTransform?t.originMesh.rotationQuaternion.copyFrom(e.pickInfo.gripTransform.rotationQuaternion):t.originMesh.rotationQuaternion.copyFrom(e.pickInfo.aimTransform.rotationQuaternion)):(this._dragging=this._dragType.DRAG,t.originMesh.position.copyFrom(e.pickInfo.ray.origin)),t.lastOriginPosition.copyFrom(t.originMesh.position),t.dragMesh.position.copyFrom(e.pickInfo.pickedPoint),t.lastDragPosition.copyFrom(e.pickInfo.pickedPoint),t.pivotMesh.position.copyFrom(this._ownerNode.getAbsolutePivotPoint()),t.pivotMesh.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),t.startingPosition.copyFrom(t.dragMesh.position),t.startingPivotPosition.copyFrom(t.pivotMesh.position),t.startingOrientation.copyFrom(t.dragMesh.rotationQuaternion),t.startingPivotOrientation.copyFrom(t.pivotMesh.rotationQuaternion),r?(t.originMesh.addChild(t.dragMesh),t.originMesh.addChild(t.pivotMesh)):t.originMesh.lookAt(t.dragMesh.position),t.dragging=!0,-1===this.currentDraggingPointerIds.indexOf(i)&&this.currentDraggingPointerIds.push(i),this.detachCameraControls&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._pointerCamera.inputs&&this._pointerCamera.inputs.attachedToElement?(this._pointerCamera.detachControl(),this._attachedToElement=!0):this.allowMultiPointer&&0!==this.currentDraggingPointerIds.length||(this._attachedToElement=!1)),this._targetDragStart(t.pivotMesh.position,t.pivotMesh.rotationQuaternion,i),this.onDragStartObservable.notifyObservers({position:t.pivotMesh.position})}}else if(e.type==lr.POINTERUP||e.type==lr.POINTERDOUBLETAP){const e=this.currentDraggingPointerIds.indexOf(i);s.dragging=!1,-1!==e&&(this.currentDraggingPointerIds.splice(e,1),0===this.currentDraggingPointerIds.length&&(this._moving=!1,this._dragging=this._dragType.NONE,this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1)),s.originMesh.removeChild(s.dragMesh),s.originMesh.removeChild(s.pivotMesh),this._targetDragEnd(i),this.onDragEndObservable.notifyObservers({}))}else if(e.type==lr.POINTERMOVE&&-1!==this.currentDraggingPointerIds.indexOf(i)&&s.dragging&&e.pickInfo&&(e.pickInfo.ray||e.pickInfo.aimTransform)){let t=this.zDragFactor;(this.currentDraggingPointerIds.length>1||e.pickInfo.originMesh)&&(t=0),this._ownerNode.computeWorldMatrix(!0),r?this._pointerUpdateXR(e.pickInfo.aimTransform,e.pickInfo.gripTransform,i,t):this._pointerUpdate2D(e.pickInfo.ray,i,t),this._tmpQuaternion.copyFrom(s.startingPivotOrientation),this._tmpQuaternion.x=-this._tmpQuaternion.x,this._tmpQuaternion.y=-this._tmpQuaternion.y,this._tmpQuaternion.z=-this._tmpQuaternion.z,s.pivotMesh.absoluteRotationQuaternion.multiplyToRef(this._tmpQuaternion,this._tmpQuaternion),s.pivotMesh.absolutePosition.subtractToRef(s.startingPivotPosition,this._tmpVector),this.onDragObservable.notifyObservers({delta:this._tmpVector,position:s.pivotMesh.position,pickInfo:e.pickInfo}),this._targetDrag(this._tmpVector,this._tmpQuaternion,i),s.lastDragPosition.copyFrom(s.dragMesh.absolutePosition),this._moving=!0}}))}_applyZOffset(e,t,i){e.position.z-=e.position.z<1?t*i:t*i*e.position.z,e.position.z<0&&(e.position.z=0)}_targetDragStart(e,t,i){}_targetDrag(e,t,i){}_targetDragEnd(e){}_reattachCameraControls(){if(this._pointerCamera)if("ArcRotateCamera"===this._pointerCamera.getClassName()){const e=this._pointerCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._pointerCamera.attachControl(!this._pointerCamera.inputs||this._pointerCamera.inputs.noPreventDefault)}detach(){this._scene&&(this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1),this._scene.onPointerObservable.remove(this._pointerObserver));for(const e in this._virtualMeshesInfo)this._virtualMeshesInfo[e].originMesh.dispose(),this._virtualMeshesInfo[e].dragMesh.dispose();this.onDragEndObservable.clear(),this.onDragObservable.clear(),this.onDragStartObservable.clear()}}class ja extends Qa{constructor(){super(...arguments),this._sceneRenderObserver=null,this._targetPosition=new _e(0,0,0),this._targetOrientation=new fe,this._targetScaling=new _e(1,1,1),this._startingPosition=new _e(0,0,0),this._startingOrientation=new fe,this._startingScaling=new _e(1,1,1),this.onPositionChangedObservable=new K,this.dragDeltaRatio=.2,this.rotateDraggedObject=!0,this.rotateAroundYOnly=!1,this.rotateWithMotionController=!0,this.disableMovement=!1,this.faceCameraOnDragStart=!1}get name(){return"SixDofDrag"}attach(e){super.attach(e),e.isNearGrabbable=!0,e.getChildMeshes().forEach((e=>{e.isNearGrabbable=!0})),this._virtualTransformNode=new lo("virtual_sixDof",Qa._virtualScene),this._virtualTransformNode.rotationQuaternion=fe.Identity(),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((()=>{if(1===this.currentDraggingPointerIds.length&&this._moving&&!this.disableMovement){const t=ve.Vector3[0];t.copyFrom(this._targetPosition).subtractInPlace(e.absolutePosition).scaleInPlace(this.dragDeltaRatio);const i=ve.Vector3[1];if(i.copyFrom(t),e.parent){const s=ve.Matrix[0];e.parent.absoluteRotationQuaternion.toRotationMatrix(s),s.invert(),_e.TransformNormalToRef(t,s,i)}if(e.position.addInPlace(i),this.onPositionChangedObservable.notifyObservers({position:e.absolutePosition}),!e.parent||e.parent.scaling&&!e.parent.scaling.isNonUniformWithinEpsilon(.001)){const t=ve.Quaternion[0];if(t.copyFrom(this._targetOrientation),e.parent){const i=ve.Quaternion[0];i.copyFrom(e.parent.absoluteRotationQuaternion),i.invertInPlace(),i.multiplyToRef(this._targetOrientation,t)}fe.SlerpToRef(e.rotationQuaternion,t,this.dragDeltaRatio,e.rotationQuaternion)}}}))}_getPositionOffsetAround(e,t,i){const s=ve.Matrix[0],r=ve.Matrix[1],n=ve.Matrix[2],o=ve.Matrix[3],a=ve.Matrix[4];return me.TranslationToRef(e.x,e.y,e.z,s),me.TranslationToRef(-e.x,-e.y,-e.z,r),me.FromQuaternionToRef(i,n),me.ScalingToRef(t,t,t,o),r.multiplyToRef(n,a),a.multiplyToRef(o,a),a.multiplyToRef(s,a),a.getTranslation()}_onePointerPositionUpdated(e,t){ve.Vector3[0].setAll(0),this._dragging===this._dragType.DRAG?this.rotateDraggedObject&&(this.rotateAroundYOnly?fe.RotationYawPitchRollToRef(t.toEulerAngles().y,0,0,ve.Quaternion[0]):ve.Quaternion[0].copyFrom(t),ve.Quaternion[0].multiplyToRef(this._startingOrientation,this._targetOrientation)):(this._dragging===this._dragType.NEAR_DRAG||this._dragging===this._dragType.DRAG_WITH_CONTROLLER&&this.rotateWithMotionController)&&t.multiplyToRef(this._startingOrientation,this._targetOrientation),this._targetPosition.copyFrom(this._startingPosition).addInPlace(e)}_twoPointersPositionUpdated(){const e=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].startingPosition,t=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].startingPosition,i=ve.Vector3[0];e.addToRef(t,i),i.scaleInPlace(.5);const s=ve.Vector3[1];t.subtractToRef(e,s);const r=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition,n=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition,o=ve.Vector3[2];r.addToRef(n,o),o.scaleInPlace(.5);const a=ve.Vector3[3];n.subtractToRef(r,a);const l=a.length()/s.length(),h=o.subtract(i),c=fe.FromEulerAngles(0,_e.GetAngleBetweenVectorsOnPlane(s.normalize(),a.normalize(),_e.UpReadOnly),0),u=this._ownerNode.parent;this._ownerNode.setParent(null);const d=this._getPositionOffsetAround(i.subtract(this._virtualTransformNode.getAbsolutePivotPoint()),l,c);this._virtualTransformNode.rotationQuaternion.multiplyToRef(c,this._ownerNode.rotationQuaternion),this._virtualTransformNode.scaling.scaleToRef(l,this._ownerNode.scaling),this._virtualTransformNode.position.addToRef(h.addInPlace(d),this._ownerNode.position),this.onPositionChangedObservable.notifyObservers({position:this._ownerNode.position}),this._ownerNode.setParent(u)}_targetDragStart(){const e=this.currentDraggingPointerIds.length;this._ownerNode.rotationQuaternion||(this._ownerNode.rotationQuaternion=fe.RotationYawPitchRoll(this._ownerNode.rotation.y,this._ownerNode.rotation.x,this._ownerNode.rotation.z));const t=this._ownerNode.getAbsolutePivotPoint();if(1===e){if(this._targetPosition.copyFrom(this._ownerNode.absolutePosition),this._targetOrientation.copyFrom(this._ownerNode.rotationQuaternion),this._targetScaling.copyFrom(this._ownerNode.absoluteScaling),this.faceCameraOnDragStart&&this._scene.activeCamera){const e=ve.Vector3[0];this._scene.activeCamera.position.subtractToRef(t,e),e.normalize();const i=ve.Quaternion[0];this._scene.useRightHandedSystem?fe.FromLookDirectionRHToRef(e,new _e(0,1,0),i):fe.FromLookDirectionLHToRef(e,new _e(0,1,0),i),i.normalize(),fe.RotationYawPitchRollToRef(i.toEulerAngles().y,0,0,ve.Quaternion[0]),this._targetOrientation.copyFrom(ve.Quaternion[0])}this._startingPosition.copyFrom(this._targetPosition),this._startingOrientation.copyFrom(this._targetOrientation),this._startingScaling.copyFrom(this._targetScaling)}else 2===e&&(this._virtualTransformNode.setPivotPoint(new _e(0,0,0),Ur.LOCAL),this._virtualTransformNode.position.copyFrom(this._ownerNode.absolutePosition),this._virtualTransformNode.scaling.copyFrom(this._ownerNode.absoluteScaling),this._virtualTransformNode.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),this._virtualTransformNode.setPivotPoint(t,Ur.WORLD),this._resetVirtualMeshesPosition())}_targetDrag(e,t){1===this.currentDraggingPointerIds.length?this._onePointerPositionUpdated(e,t):2===this.currentDraggingPointerIds.length&&this._twoPointersPositionUpdated()}_targetDragEnd(){if(1===this.currentDraggingPointerIds.length){this._resetVirtualMeshesPosition();const e=this.faceCameraOnDragStart;this.faceCameraOnDragStart=!1,this._targetDragStart(),this.faceCameraOnDragStart=e}}detach(){super.detach(),this._ownerNode&&this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),this._virtualTransformNode&&this._virtualTransformNode.dispose()}}class Ka{constructor(){this._attachPointLocalOffset=new _e,this._workingPosition=new _e,this._workingQuaternion=new fe,this._lastTick=-1,this._hit=!1,this.hitNormalOffset=.05,this.meshes=[],this.interpolatePose=!0,this.lerpTime=250,this.keepOrientationVertical=!0,this.enabled=!0,this.maxStickingDistance=.8}get name(){return"SurfaceMagnetism"}init(){}attach(e,t){this._attachedMesh=e,this._scene=t||e.getScene(),this._attachedMesh.rotationQuaternion||(this._attachedMesh.rotationQuaternion=fe.RotationYawPitchRoll(this._attachedMesh.rotation.y,this._attachedMesh.rotation.x,this._attachedMesh.rotation.z)),this.updateAttachPoint(),this._workingPosition.copyFrom(this._attachedMesh.position),this._workingQuaternion.copyFrom(this._attachedMesh.rotationQuaternion),this._addObservables()}detach(){this._attachedMesh=null,this._removeObservables()}_getTargetPose(e){if(!this._attachedMesh)return null;if(e&&e.hit){const t=e.getNormal(!0,!0),i=e.pickedPoint;if(!t||!i)return null;t.normalize();const s=ve.Vector3[0];return s.copyFrom(t),s.scaleInPlace(this.hitNormalOffset),s.addInPlace(i),this._attachedMesh.parent&&(ve.Matrix[0].copyFrom(this._attachedMesh.parent.getWorldMatrix()).invert(),_e.TransformNormalToRef(s,ve.Matrix[0],s)),{position:s,quaternion:fe.RotationYawPitchRoll(-Math.atan2(t.x,-t.z),this.keepOrientationVertical?0:Math.atan2(t.y,Math.sqrt(t.z*t.z+t.x*t.x)),0)}}return null}updateAttachPoint(){this._getAttachPointOffsetToRef(this._attachPointLocalOffset)}findAndUpdateTarget(e){if(this._hit=!1,!e.ray)return!1;const t=e.ray.intersectsMeshes(this.meshes)[0];if(this._attachedMesh&&t&&t.hit&&t.pickedMesh){const e=this._getTargetPose(t);e&&_e.Distance(this._attachedMesh.position,e.position){this.enabled&&e.type==lr.POINTERMOVE&&e.pickInfo&&this.findAndUpdateTarget(e.pickInfo)})),this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((()=>{const e=Date.now();this._updateTransformToGoal(e-this._lastTick),this._lastTick=e}))}_removeObservables(){this._scene.onPointerObservable.remove(this._pointerObserver),this._scene.onBeforeRenderObservable.remove(this._onBeforeRender),this._pointerObserver=null,this._onBeforeRender=null}}class $a{constructor(){this._tmpQuaternion=new fe,this._tmpVectors=[new _e,new _e,new _e,new _e,new _e,new _e,new _e],this._tmpMatrix=new me,this._tmpInvertView=new me,this._tmpForward=new _e,this._tmpNodeForward=new _e,this._tmpPosition=new _e,this._workingPosition=new _e,this._workingQuaternion=new fe,this._lastTick=-1,this._recenterNextUpdate=!0,this.interpolatePose=!0,this.lerpTime=500,this.ignoreCameraPitchAndRoll=!1,this.pitchOffset=15,this.maxViewVerticalDegrees=30,this.maxViewHorizontalDegrees=30,this.orientToCameraDeadzoneDegrees=60,this.ignoreDistanceClamp=!1,this.ignoreAngleClamp=!1,this.verticalMaxDistance=0,this.defaultDistance=.8,this.maximumDistance=2,this.minimumDistance=.3,this.useFixedVerticalOffset=!1,this.fixedVerticalOffset=0,this._enabled=!0}get followedCamera(){return this._followedCamera||this._scene.activeCamera}set followedCamera(e){this._followedCamera=e}get name(){return"Follow"}init(){}attach(e,t){this._scene=e.getScene(),this.attachedNode=e,t&&(this.followedCamera=t),this._addObservables()}detach(){this.attachedNode=null,this._removeObservables()}recenter(){this._recenterNextUpdate=!0}_angleBetweenVectorAndPlane(e,t){return this._tmpVectors[0].copyFrom(e),e=this._tmpVectors[0],this._tmpVectors[1].copyFrom(t),t=this._tmpVectors[1],e.normalize(),t.normalize(),Math.PI/2-Math.acos(_e.Dot(e,t))}_length2D(e){return Math.sqrt(e.x*e.x+e.z*e.z)}_distanceClamp(e,t=!1){let i=this.minimumDistance,s=this.maximumDistance;const r=this.defaultDistance,n=this._tmpVectors[0];n.copyFrom(e);let o=n.length();if(n.normalizeFromLength(o),this.ignoreCameraPitchAndRoll){i=this._length2D(n)*i,s=this._length2D(n)*s;const t=this._length2D(e);n.scaleInPlace(o/t),o=t}let a=o;return a=t?r:be.Clamp(o,i,s),e.copyFrom(n).scaleInPlace(a),o!==a}_applyVerticalClamp(e){0!==this.verticalMaxDistance&&(e.y=be.Clamp(e.y,-this.verticalMaxDistance,this.verticalMaxDistance))}_toOrientationQuatToRef(e,t){fe.RotationYawPitchRollToRef(Math.atan2(e.x,e.z),Math.atan2(e.y,Math.sqrt(e.z*e.z+e.x*e.x)),0,t)}_applyPitchOffset(e){const t=this._tmpVectors[0],i=this._tmpVectors[1];t.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),i.copyFromFloats(1,0,0),_e.TransformNormalToRef(t,e,t),t.y=0,t.normalize(),_e.TransformNormalToRef(i,e,i),fe.RotationAxisToRef(i,this.pitchOffset*Math.PI/180,this._tmpQuaternion),t.rotateByQuaternionToRef(this._tmpQuaternion,t),this._toOrientationQuatToRef(t,this._tmpQuaternion),this._tmpQuaternion.toRotationMatrix(this._tmpMatrix),e.copyFrom(this._tmpMatrix)}_angularClamp(e,t){const i=this._tmpVectors[5];i.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1);const s=this._tmpVectors[6];s.copyFromFloats(1,0,0),_e.TransformNormalToRef(i,e,i),_e.TransformNormalToRef(s,e,s);const r=_e.UpReadOnly;if(t.length()r&&(fe.RotationAxisToRef(s,-e+r,o),t.rotateByQuaternionToRef(o,t),n=!0)}const a=this._angleBetweenVectorAndPlane(t,s)*(this._scene.useRightHandedSystem?-1:1),l=this.maxViewHorizontalDegrees*Math.PI/180*.5;return a<-l?(fe.RotationAxisToRef(r,-a-l,o),t.rotateByQuaternionToRef(o,t),n=!0):a>l&&(fe.RotationAxisToRef(r,-a+l,o),t.rotateByQuaternionToRef(o,t),n=!0),n}_orientationClamp(e,t){const i=this._tmpVectors[0];i.copyFrom(e).scaleInPlace(-1).normalize();const s=this._tmpVectors[1],r=this._tmpVectors[2];s.copyFromFloats(0,1,0),_e.CrossToRef(i,s,r);const n=r.length();nthis.orientToCameraDeadzoneDegrees}_updateLeashing(e){if(this.attachedNode&&this._enabled){const t=this.attachedNode.parent;this.attachedNode.setParent(null);const i=this.attachedNode.getWorldMatrix(),s=this._workingPosition,r=this._workingQuaternion,n=this.attachedNode.getPivotPoint(),o=this._tmpInvertView;o.copyFrom(e.getViewMatrix()),o.invert(),_e.TransformCoordinatesToRef(n,i,s);const a=this._tmpPosition;a.copyFromFloats(0,0,0),_e.TransformCoordinatesToRef(a,i,a),a.scaleInPlace(-1).subtractInPlace(n),s.subtractInPlace(e.globalPosition),this.ignoreCameraPitchAndRoll&&this._applyPitchOffset(o);let l=!1;const h=this._tmpForward;h.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),_e.TransformNormalToRef(h,o,h);const c=this._tmpNodeForward;if(c.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),_e.TransformNormalToRef(c,i,c),this._recenterNextUpdate)s.copyFrom(h).scaleInPlace(this.defaultDistance);else if(this.ignoreAngleClamp){const e=s.length();s.copyFrom(h).scaleInPlace(e)}else l=this._angularClamp(o,s);let u=!1;this.ignoreDistanceClamp||(u=this._distanceClamp(s,l),this._applyVerticalClamp(s)),this.useFixedVerticalOffset&&(s.y=a.y-e.globalPosition.y+this.fixedVerticalOffset),(l||u||this._passedOrientationDeadzone(s,c)||this._recenterNextUpdate)&&this._orientationClamp(s,r),this._workingPosition.subtractInPlace(n),this._recenterNextUpdate=!1,this.attachedNode.setParent(t)}}_updateTransformToGoal(e){if(!this.attachedNode||!this.followedCamera||!this._enabled)return;this.attachedNode.rotationQuaternion||(this.attachedNode.rotationQuaternion=fe.Identity());const t=this.attachedNode.parent;if(this.attachedNode.setParent(null),!this.interpolatePose)return this.attachedNode.position.copyFrom(this.followedCamera.globalPosition).addInPlace(this._workingPosition),void this.attachedNode.rotationQuaternion.copyFrom(this._workingQuaternion);const i=new _e;i.copyFrom(this.attachedNode.position).subtractInPlace(this.followedCamera.globalPosition),_e.SmoothToRef(i,this._workingPosition,e,this.lerpTime,i),i.addInPlace(this.followedCamera.globalPosition),this.attachedNode.position.copyFrom(i);const s=new fe;s.copyFrom(this.attachedNode.rotationQuaternion),fe.SmoothToRef(s,this._workingQuaternion,e,this.lerpTime,this.attachedNode.rotationQuaternion),this.attachedNode.setParent(t)}_addObservables(){this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((()=>{if(!this.followedCamera)return;const e=Date.now();this._updateLeashing(this.followedCamera),this._updateTransformToGoal(e-this._lastTick),this._lastTick=e}))}_removeObservables(){this._onBeforeRender&&this._scene.onBeforeRenderObservable.remove(this._onBeforeRender)}}class qa{}qa.ANCHOR_SYSTEM="xr-anchor-system",qa.BACKGROUND_REMOVER="xr-background-remover",qa.HIT_TEST="xr-hit-test",qa.MESH_DETECTION="xr-mesh-detection",qa.PHYSICS_CONTROLLERS="xr-physics-controller",qa.PLANE_DETECTION="xr-plane-detection",qa.POINTER_SELECTION="xr-controller-pointer-selection",qa.TELEPORTATION="xr-controller-teleportation",qa.FEATURE_POINTS="xr-feature-points",qa.HAND_TRACKING="xr-hand-tracking",qa.IMAGE_TRACKING="xr-image-tracking",qa.NEAR_INTERACTION="xr-near-interaction",qa.DOM_OVERLAY="xr-dom-overlay",qa.MOVEMENT="xr-controller-movement",qa.LIGHT_ESTIMATION="xr-light-estimation",qa.EYE_TRACKING="xr-eye-tracking",qa.WALKING_LOCOMOTION="xr-walking-locomotion",qa.LAYERS="xr-layers",qa.DEPTH_SENSING="xr-depth-sensing",qa.SPACE_WARP="xr-space-warp",qa.RAW_CAMERA_ACCESS="xr-raw-camera-access";class Za{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)}))})),this._xrSessionManager.onXRSessionEnded.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)}))}))}static AddWebXRFeature(e,t,i=1,s=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),s&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,s){const r=this._AvailableFeatures[e][t];if(!r)throw new Error("feature not found");return r(i,s)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){const t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&(t.featureImplementation.attach()||Ds.Warn(`Feature ${e} failed to attach`))}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&(t.featureImplementation.detach()||Ds.Warn(`Feature ${e} failed to detach`))}disableFeature(e){const t="string"==typeof e?e:e.Name,i=this._features[t];return!(!i||!i.enabled||(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],0))}dispose(){this.getEnabledFeatures().forEach((e=>{this.disableFeature(e)}))}enableFeature(e,t="latest",i={},s=!0,r=!0){const n="string"==typeof e?e:e.Name;let o=0;if("string"==typeof t){if(!t)throw new Error(`Error in provided version - ${n} (${t})`);if(o="stable"===t?Za.GetStableVersionOfFeature(n):"latest"===t?Za.GetLatestVersionOfFeature(n):+t,-1===o||isNaN(o))throw new Error(`feature not found - ${n} (${t})`)}else o=t;const a=Za._ConflictingFeatures[n];if(void 0!==a&&-1!==this.getEnabledFeatures().indexOf(a))throw new Error(`Feature ${n} cannot be enabled while ${a} is enabled.`);const l=this._features[n],h=Za.ConstructFeature(n,o,this._xrSessionManager,i);if(!h)throw new Error(`feature not found - ${n}`);l&&this.disableFeature(n);const c=h();if(c.dependsOn){const e=c.dependsOn.every((e=>!!this._features[e]));if(!e)throw new Error(`Dependant features missing. Make sure the following features are enabled - ${c.dependsOn.join(", ")}`)}if(c.isCompatible())return this._features[n]={featureImplementation:c,enabled:!0,version:o,required:r},s?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(r)throw new Error("required feature not compatible");return Ds.Warn(`Feature ${n} not compatible with the current environment/browser and was not enabled.`),c}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){const t=this.getEnabledFeatures();for(const i of t){const t=this._features[i],s=t.featureImplementation.xrNativeFeatureName;if(s&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(s)&&e.requiredFeatures.push(s)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(s)&&e.optionalFeatures.push(s))),t.featureImplementation.getXRSessionInitExtension){const i=await t.featureImplementation.getXRSessionInitExtension();e={...e,...i}}}return e}}Za._AvailableFeatures={},Za._ConflictingFeatures={[qa.TELEPORTATION]:qa.MOVEMENT,[qa.MOVEMENT]:qa.TELEPORTATION};class Ja{get xrNativeFeatureName(){return this._xrNativeFeatureName}set xrNativeFeatureName(e){!this._xrSessionManager.isNative&&e&&this._xrSessionManager.inXRSession&&-1===this._xrSessionManager.enabledFeatures?.indexOf(e)&&Ne.Warn(`The feature ${e} needs to be enabled before starting the XR session. Note - It is still possible it is not supported.`),this._xrNativeFeatureName=e}constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this._xrNativeFeatureName="",this.onFeatureAttachObservable=new K,this.onFeatureDetachObservable=new K}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;if(this._xrSessionManager.enabledFeatures){if(!this._xrSessionManager.isNative&&this.xrNativeFeatureName&&-1===this._xrSessionManager.enabledFeatures.indexOf(this.xrNativeFeatureName))return!1}else Ne.Warn("session.enabledFeatures is not available on this device. It is possible that this feature is not supported.");return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,(e=>this._onXRFrame(e))),this.onFeatureAttachObservable.notifyObservers(this),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach((e=>{e.observable.remove(e.observer)})),this.onFeatureDetachObservable.notifyObservers(this),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0,this.onFeatureAttachObservable.clear(),this.onFeatureDetachObservable.clear()}isCompatible(){return!0}_addNewAttachObserver(e,t,i){this._removeOnDetach.push({observable:e,observer:e.add(t,void 0,i)})}}class el{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint,this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}el.DistanceJoint=0,el.HingeJoint=1,el.BallAndSocketJoint=2,el.WheelJoint=3,el.SliderJoint=4,el.PrismaticJoint=5,el.UniversalJoint=6,el.Hinge2Joint=el.WheelJoint,el.PointToPointJoint=8,el.SpringJoint=9,el.LockJoint=10;class tl extends el{constructor(e){super(el.DistanceJoint,e)}updateDistance(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)}}class il extends el{constructor(e,t){super(e,t)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class sl extends il{constructor(e){super(el.HingeJoint,e)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class rl extends il{constructor(e){super(el.Hinge2Joint,e)}setMotor(e,t,i=0){this._physicsPlugin.setMotor(this,e||0,t,i)}setLimit(e,t,i=0){this._physicsPlugin.setLimit(this,e,t,i)}}ha._PhysicsImpostorParser=function(e,t,i){return new nl(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};class nl{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},s){this.object=e,this.type=t,this._options=i,this._scene=s,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=_e.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new fe,this._tmpQuat2=new fe,this.beforeStep=()=>{this._physicsEngine&&(this.object.translate(this._deltaPosition,-1),this._deltaRotationConjugated&&this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated,this.object.rotationQuaternion),this.object.computeWorldMatrix(!1),this.object.parent&&this.object.rotationQuaternion?(this.getParentsRotation(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this._tmpQuat)):this._tmpQuat.copyFrom(this.object.rotationQuaternion||new fe),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach((e=>{e(this)})))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach((e=>{e(this)})),this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this),this.object.parent&&this.object.rotationQuaternion&&(this.getParentsRotation(),this._tmpQuat.conjugateInPlace(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this.object.rotationQuaternion)),this.object.setAbsolutePosition(this.object.position),this._deltaRotation?(this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotation,this.object.rotationQuaternion),this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation,nl._TmpVecs[0]),this.object.translate(nl._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=e=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent)return;if(!this._physicsEngine)return;const t=this._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(this.onCollideEvent&&this.onCollideEvent(this,t),this._onPhysicsCollideCallbacks.filter((e=>-1!==e.otherImpostors.indexOf(t))).forEach((i=>{i.callback(this,t,e.point,e.distance,e.impulse,e.normal)})))},this.object?(this.object.parent&&0!==i.mass&&Ne.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),this._scene&&(this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=fe.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new fe),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&Ne.Warn("You must affect impostors to children before affecting impostor to parent.")):Ne.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):Ne.Error("No object was provided. A physics object is obligatory")}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))}_getPhysicsParent(){return this.object.parent instanceof _o?this.object.parent.physicsImpostor:null}isBodyInitRequired(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)}setScalingUpdated(){this.forceUpdate()}forceUpdate(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()}get physicsBody(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody}get parent(){return!this._options.ignoreParent&&this._parent?this._parent:null}set parent(e){this._parent=e}set physicsBody(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()}resetUpdateFlags(){this._bodyUpdateRequired=!1}getObjectExtents(){if(this.object.getBoundingInfo){const e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=nl.IDENTITY_QUATERNION;const i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);const s=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return s.x=Math.abs(s.x),s.y=Math.abs(s.y),s.z=Math.abs(s.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),s}return nl.DEFAULT_OBJECT_SIZE}getObjectCenter(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.centerWorld:this.object.position}getParam(e){return this._options[e]}setParam(e,t){this._options[e]=t,this._bodyUpdateRequired=!0}setMass(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)}getLinearVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):_e.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):_e.Zero()}setAngularVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)}executeNativeFunction(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)}registerBeforePhysicsStep(e){this._onBeforePhysicsStepCallbacks.push(e)}unregisterBeforePhysicsStep(e){const t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):Ne.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){const t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):Ne.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];let s=-1;this._onPhysicsCollideCallbacks.some(((e,r)=>{if(e.callback===t&&e.otherImpostors.length===i.length){const t=e.otherImpostors.every((e=>i.indexOf(e)>-1));return t&&(s=r),t}return!1}))?this._onPhysicsCollideCallbacks.splice(s,1):Ne.Warn("Function to remove was not found")}getParentsRotation(){let e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):fe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){const s=new el(t,i);return this.addJoint(e,s),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,s,r){if(!this._physicsEngine)return this;const n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor?(this._physicsEngine&&n.appendAnchor(this,e,t,i,s,r),this):this}addHook(e,t,i,s){if(!this._physicsEngine)return this;const r=this._physicsEngine.getPhysicsPlugin();return r.appendAnchor?(this._physicsEngine&&r.appendHook(this,e,t,i,s),this):this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new nl(e,this.type,this._options,this._scene):null}dispose(){this._physicsEngine&&(this._joints.forEach((e=>{this._physicsEngine&&this._physicsEngine.removeJoint(this,e.otherImpostor,e.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)}setDeltaPosition(e){this._deltaPosition.copyFrom(e)}setDeltaRotation(e){this._deltaRotation||(this._deltaRotation=new fe),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,s,r){const n=nl._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(r){const i=nl._TmpQuat;o.rotationQuaternion.multiplyToRef(r,i),e.setRotationQuaternion(i,Ur.WORLD,t)}else e.setRotationQuaternion(o.rotationQuaternion,Ur.WORLD,t);n.x=0,n.y=0,n.z=0,i&&(n.x=i.x,n.y=i.y,n.z=i.z,e.getDirectionToRef(n,t,n),null==s&&(s=i.length()),n.x*=s,n.y*=s,n.z*=s),e.getParent()?(n.addInPlace(o.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(o.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,s,r,n){const o=this.object;if(o.rotationQuaternion)if(r){const i=nl._TmpQuat;e.getRotationQuaternionToRef(Ur.WORLD,t,i),i.multiplyToRef(r,o.rotationQuaternion)}else e.getRotationQuaternionToRef(Ur.WORLD,t,o.rotationQuaternion);const a=nl._TmpVecs[0],l=nl._TmpVecs[1];n||((n=nl._TmpVecs[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,a),null==s&&i&&(s=i.length()),null!=s&&(a.x+=l.x*s,a.y+=l.y*s,a.z+=l.z*s),o.setAbsolutePosition(a)}}var ol,al,ll,hl,cl,ul,dl,_l,pl;nl.DEFAULT_OBJECT_SIZE=new _e(1,1,1),nl.IDENTITY_QUATERNION=fe.Identity(),nl._TmpVecs=ee.BuildArray(3,_e.Zero),nl._TmpQuat=fe.Identity(),nl.NoImpostor=0,nl.SphereImpostor=1,nl.BoxImpostor=2,nl.PlaneImpostor=3,nl.MeshImpostor=4,nl.CapsuleImpostor=6,nl.CylinderImpostor=7,nl.ParticleImpostor=8,nl.HeightmapImpostor=9,nl.ConvexHullImpostor=10,nl.CustomImpostor=100,nl.RopeImpostor=101,nl.ClothImpostor=102,nl.SoftbodyImpostor=103,function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(ol||(ol={}));class fl{static get ForceFullSceneLoadingForIncremental(){return Hn.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Hn.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Hn.ShowLoadingScreen}static set ShowLoadingScreen(e){Hn.ShowLoadingScreen=e}static get loggingLevel(){return Hn.loggingLevel}static set loggingLevel(e){Hn.loggingLevel=e}static get CleanBoneMatrixWeights(){return Hn.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Hn.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return fl._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){return fl._RegisteredPlugins[e]||(Ne.Warn("Unable to find a plugin to load "+e+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),fl.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in fl._RegisteredPlugins){const i=fl._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return fl._RegisteredPlugins[t]}return fl.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const i=e.lastIndexOf("."),s=e.substring(i,e.length).toLowerCase();return fl._GetPluginForExtension(s)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let s="Unable to load from "+(e.rawData?"binary data":e.url);return t?s+=`: ${t}`:i&&(s+=`: ${i}`),s}static _LoadData(e,t,i,s,r,n,o,a){const l=fl._GetDirectLoad(e.url);if(e.rawData&&!o)throw"When using ArrayBufferView to load data the file extension must be provided.";const h=o?fl._GetPluginForExtension(o):l?fl._GetPluginForDirectLoad(e.url):fl._GetPluginForFilename(e.url);if(e.rawData&&!h.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";let c;if(c=void 0!==h.plugin.createPlugin?h.plugin.createPlugin():h.plugin,!c)throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(fl.OnPluginActivatedObservable.notifyObservers(c),l&&(c.canDirectLoad&&c.canDirectLoad(e.url)||!gs(e.url))){if(c.directLoad){const e=c.directLoad(t,l);e.then?e.then((e=>{i(c,e)})).catch((e=>{r("Error in directLoad of _loadData: "+e,e)})):i(c,e)}else i(c,l);return c}const u=h.isBinary,d=(e,s)=>{t.isDisposed?r("Scene has been disposed"):i(c,e,s)};let _=null,p=!1;const f=c.onDisposeObservable;f&&f.add((()=>{p=!0,_&&(_.abort(),_=null),n()}));const m=()=>{if(p)return;const i=(e,t)=>{r(e?.statusText,t)};if(!c.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";_=c.loadFile?c.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,d,s,u,i,a):t._loadFile(e.file||e.url,d,s,!0,u,i)},g=t.getEngine();let v=g.enableOfflineSupport;if(v){let i=!1;for(const s of t.disableOfflineSupportExceptionRules)if(s.test(e.url)){i=!0;break}v=!i}return v&&oo.OfflineProviderFactory?t.offlineProvider=oo.OfflineProviderFactory(e.url,m,g.disableManifestCheck):m(),c}static _GetFileInfo(e,t){let i,s,r=null,n=null;if(t)if(t.name){const e=t;i=`file:${e.name}`,s=e.name,r=e}else if(ArrayBuffer.isView(t))i="",s=Cs(),n=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,s="";else{const r=t;if("/"===r.substr(0,1))return Ds.Error("Wrong sceneFilename parameter"),null;i=e+r,s=r}else i=e,s=Ds.GetFilename(e),e=Ds.GetFolderPath(e);return{url:i,rootUrl:e,name:s,file:r,rawData:n}}static GetPluginForExtension(e){return fl._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!fl._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){const t=e.extensions;fl._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{fl._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}}))}}static ImportMesh(e,t,i="",s=re.LastCreatedScene,r=null,n=null,o=null,a=null,l=""){if(!s)return Ne.Error("No scene available to import mesh to"),null;const h=fl._GetFileInfo(t,i);if(!h)return null;const c={};s.addPendingData(c);const u=()=>{s.removePendingData(c)},d=(e,t)=>{const i=fl._FormatErrorMessage(h,e,t);o?o(s,i,new jt(i,Qt.SceneLoaderError,t)):Ne.Error(i),u()},_=n?e=>{try{n(e)}catch(e){d("Error in onProgress callback: "+e,e)}}:void 0,p=(e,t,i,n,o,a,l,u)=>{if(s.importedMeshesFiles.push(h.url),r)try{r(e,t,i,n,o,a,l,u)}catch(e){d("Error in onSuccess callback: "+e,e)}s.removePendingData(c)};return fl._LoadData(h,s,((t,i,r)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,r)),t.importMesh){const r=[],n=[],o=[];if(!t.importMesh(e,s,i,h.rootUrl,r,n,o,d))return;s.loadingPluginName=t.name,p(r,n,o,[],[],[],[],[])}else t.importMeshAsync(e,s,i,h.rootUrl,_,h.name).then((e=>{s.loadingPluginName=t.name,p(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights,e.spriteManagers)})).catch((e=>{d(e.message,e)}))}),_,d,u,a,l)}static ImportMeshAsync(e,t,i="",s=re.LastCreatedScene,r=null,n=null,o=""){return new Promise(((a,l)=>{fl.ImportMesh(e,t,i,s,((e,t,i,s,r,n,o,l)=>{a({meshes:e,particleSystems:t,skeletons:i,animationGroups:s,transformNodes:r,geometries:n,lights:o,spriteManagers:l})}),r,((e,t,i)=>{l(i||new Error(t))}),n,o)}))}static Load(e,t="",i=re.LastCreatedEngine,s=null,r=null,n=null,o=null,a=""){return i?fl.Append(e,t,new Hr(i),s,r,n,o,a):(Ds.Error("No engine available"),null)}static LoadAsync(e,t="",i=re.LastCreatedEngine,s=null,r=null,n=""){return new Promise(((o,a)=>{fl.Load(e,t,i,(e=>{o(e)}),s,((e,t,i)=>{a(i||new Error(t))}),r,n)}))}static Append(e,t="",i=re.LastCreatedScene,s=null,r=null,n=null,o=null,a=""){if(!i)return Ne.Error("No scene available to append to"),null;const l=fl._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)};fl.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1})));const u=(e,t)=>{const s=fl._FormatErrorMessage(l,e,t);n?n(i,s,new jt(s,Qt.SceneLoaderError,t)):Ne.Error(s),c()},d=r?e=>{try{r(e)}catch(e){u("Error in onProgress callback",e)}}:void 0,_=()=>{if(s)try{s(i)}catch(e){u("Error in onSuccess callback",e)}i.removePendingData(h)};return fl._LoadData(l,i,((e,t)=>{if(e.load){if(!e.load(i,t,l.rootUrl,u))return;i.loadingPluginName=e.name,_()}else e.loadAsync(i,t,l.rootUrl,d,l.name).then((()=>{i.loadingPluginName=e.name,_()})).catch((e=>{u(e.message,e)}))}),d,u,c,o,a)}static AppendAsync(e,t="",i=re.LastCreatedScene,s=null,r=null,n=""){return new Promise(((o,a)=>{fl.Append(e,t,i,(e=>{o(e)}),s,((e,t,i)=>{a(i||new Error(t))}),r,n)}))}static LoadAssetContainer(e,t="",i=re.LastCreatedScene,s=null,r=null,n=null,o=null,a=""){if(!i)return Ne.Error("No scene available to load asset container to"),null;const l=fl._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)},u=(e,t)=>{const s=fl._FormatErrorMessage(l,e,t);n?n(i,s,new jt(s,Qt.SceneLoaderError,t)):Ne.Error(s),c()},d=r?e=>{try{r(e)}catch(e){u("Error in onProgress callback",e)}}:void 0,_=e=>{if(s)try{s(e)}catch(e){u("Error in onSuccess callback",e)}i.removePendingData(h)};return fl._LoadData(l,i,((e,t)=>{if(e.loadAssetContainer){const s=e.loadAssetContainer(i,t,l.rootUrl,u);if(!s)return;s.populateRootNodes(),i.loadingPluginName=e.name,_(s)}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,l.rootUrl,d,l.name).then((t=>{t.populateRootNodes(),i.loadingPluginName=e.name,_(t)})).catch((e=>{u(e.message,e)})):u("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),d,u,c,o,a)}static LoadAssetContainerAsync(e,t="",i=re.LastCreatedScene,s=null,r=null){return new Promise(((n,o)=>{fl.LoadAssetContainer(e,t,i,(e=>{n(e)}),s,((e,t,i)=>{o(i||new Error(t))}),r)}))}static ImportAnimations(e,t="",i=re.LastCreatedScene,s=!0,r=ol.Clean,n=null,o=null,a=null,l=null,h=null){if(!i)return void Ne.Error("No scene available to load animations to");if(s){for(const e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach((e=>{e.dispose()})),i.getNodes().forEach((e=>{e.animations&&(e.animations=[])}))}else switch(r){case ol.Clean:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case ol.Stop:i.animationGroups.forEach((e=>{e.stop()}));break;case ol.Sync:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case ol.NoSync:break;default:return void Ne.Error("Unknown animation group loading mode value '"+r+"'")}const c=i.animatables.length;this.LoadAssetContainer(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(c),n),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)}),a,l,h)}static ImportAnimationsAsync(e,t="",i=re.LastCreatedScene,s=!0,r=ol.Clean,n=null,o=null,a=null,l=null,h=null){return new Promise(((o,l)=>{fl.ImportAnimations(e,t,i,s,r,n,(e=>{o(e)}),a,((e,t,i)=>{l(i||new Error(t))}),h)}))}}fl.NO_LOGGING=0,fl.MINIMAL_LOGGING=1,fl.SUMMARY_LOGGING=2,fl.DETAILED_LOGGING=3,fl.OnPluginActivatedObservable=new K,fl._RegisteredPlugins={},fl._ShowingLoadingScreen=!1;class ml extends ta{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new me,this._storeEffectOnSubMeshes=i}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return!!e&&(!this._storeEffectOnSubMeshes||!e.subMeshes||0===e.subMeshes.length||this.isReadyForSubMesh(e,e.subMeshes[0],t))}_isReadyForSubMesh(e){const t=e.materialDefines;return!(this.checkReadyOnEveryCall||!e.effect||!t||t._renderId!==this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,i){super._afterBind(e,t,i),this.getScene()._cachedEffect=t,i?i._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,i,s=1){return i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,s)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}!function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.Object=256]="Object",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.All=4095]="All"}(al||(al={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(ll||(ll={}));class gl{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}get shaderLanguage(){return this.sharedData.nodeMaterial.shaderLanguage}get fSuffix(){return this.shaderLanguage===di.WGSL?"f":""}finalize(e){const t=e.sharedData.emitComments,i=this.target===ll.Fragment;this.shaderLanguage===di.WGSL?this.compilationString=i?`\n${t?"//Entry point\n":""}@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${this.compilationString}`:`\n${t?"//Entry point\n":""}@vertex\nfn main(input: VertexInputs) -> FragmentInputs{\n${this.compilationString}`:this.compilationString=`\n${t?"//Entry point\n":""}void main(void) {\n${this.compilationString}`,this._constantDeclaration&&(this.compilationString=`\n${t?"//Constants\n":""}${this._constantDeclaration}\n${this.compilationString}`);let s="";for(const e in this.functions)s+=this.functions[e]+"\n";if(this.compilationString=`\n${s}\n${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString}\n${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString}\n${this._injectAtEnd}`),this.compilationString=`${this.compilationString}\n}`,this.sharedData.varyingDeclaration&&(this.compilationString=`\n${t?"//Varyings\n":""}${this.sharedData.varyingDeclaration}\n${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=`\n${t?"//Samplers\n":""}${this._samplerDeclaration}\n${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=`\n${t?"//Uniforms\n":""}${this._uniformDeclaration}\n${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=`\n${t?"//Attributes\n":""}${this._attributeDeclaration}\n${this.compilationString}`),this.shaderLanguage!==di.WGSL){this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defines(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,i&&(this.compilationString="#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n"+this.compilationString);for(const e in this.extensions){const t=this.extensions[e];this.compilationString=`\n${t}\n${this.compilationString}`}}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e]?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){this.samplers.indexOf(e)<0&&(this.shaderLanguage===di.WGSL?(this._samplerDeclaration+=`var ${e+"Sampler"}: sampler;\n`,this._samplerDeclaration+=`var ${e}: texture_2d;\n`):this._samplerDeclaration+=`uniform sampler2D ${e};\n`,this.samplers.push(e))}_emit2DArraySampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2DArray ${e};\n`,this.samplers.push(e))}_getGLType(e){switch(e){case al.Float:return"float";case al.Int:return"int";case al.Vector2:return"vec2";case al.Color3:case al.Vector3:return"vec3";case al.Color4:case al.Vector4:return"vec4";case al.Matrix:return"mat4"}return""}_getShaderType(e){const t=this.shaderLanguage===di.WGSL;switch(e){case al.Float:return t?"f32":"float";case al.Int:return t?"i32":"int";case al.Vector2:return t?"vec2f":"vec2";case al.Color3:case al.Vector3:return t?"vec3f":"vec3";case al.Color4:case al.Vector4:return t?"vec4f":"vec4";case al.Matrix:return t?"mat4x4f":"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i}\n${t}\n#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+"\n"+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`;let s=Bi.GetIncludesShadersStore(this.shaderLanguage)[e]+"\n";if(this.sharedData.emitComments&&(s=t+"\n"+s),!i)return s;if(i.replaceStrings)for(let e=0;e${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`:this.functions[r]=`#include<${e}>${i?.substitutionVars?"("+i?.substitutionVars+")":""}\n`,void(this.sharedData.emitComments&&(this.functions[r]=t+"\n"+this.functions[r]));const n=Bi.GetIncludesShadersStore(this.shaderLanguage);if(this.functions[r]=n[e],this.sharedData.emitComments&&(this.functions[r]=t+"\n"+this.functions[r]),i.removeIfDef&&(this.functions[r]=this.functions[r].replace(/^\s*?#ifdef.+$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#endif.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#else.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[r]=this.functions[r].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[r]=this.functions[r].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[r]=this.functions[r].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(let e=0;e")}_convertTernaryOperandsToWGSL(e){return e.replace(new RegExp("\\[(.*?)\\?(.*?):(.*)\\]","g"),((e,t,i,s)=>`select(${s}, ${i}, ${t})`))}_convertModOperatorsToWGSL(e){return e.replace(new RegExp("mod\\((.+?),\\s*(.+?)\\)","g"),((e,t,i)=>`((${t})%(${i}))`))}_convertConstToWGSL(e){return e.replace(new RegExp("const var","g"),"const")}_convertInnerFunctionsToWGSL(e){return e.replace(new RegExp("inversesqrt","g"),"inverseSqrt")}_convertFunctionsToWGSL(e){const t=/var\s+(\w+)\s*:\s*(\w+)\((.*)\)/g;let i;for(;null!==(i=t.exec(e));){const t=i[1],s=i[2],r=i[3].replace(/var\s/g,"");e=e.replace(i[0],`fn ${t}(${r}) -> ${s}`)}return e}_babylonSLtoWGSL(e){return e=this._convertVariableDeclarationToWGSL("void","voidnull",e),e=this._convertVariableDeclarationToWGSL("bool","bool",e),e=this._convertVariableDeclarationToWGSL("int","i32",e),e=this._convertVariableDeclarationToWGSL("uint","u32",e),e=this._convertVariableDeclarationToWGSL("float","f32",e),e=this._convertVariableDeclarationToWGSL("vec2","vec2f",e),e=this._convertVariableDeclarationToWGSL("vec3","vec3f",e),e=this._convertVariableDeclarationToWGSL("vec4","vec4f",e),e=this._convertVariableDeclarationToWGSL("mat2","mat2x2f",e),e=this._convertVariableDeclarationToWGSL("mat3","mat3x3f",e),e=this._convertVariableDeclarationToWGSL("mat4","mat4x4f",e),e=this._convertVariableConstructorsToWGSL("float","f32",e),e=this._convertVariableConstructorsToWGSL("vec2","vec2f",e),e=this._convertVariableConstructorsToWGSL("vec3","vec3f",e),e=this._convertVariableConstructorsToWGSL("vec4","vec4f",e),e=this._convertVariableConstructorsToWGSL("mat2","mat2x2f",e),e=this._convertVariableConstructorsToWGSL("mat3","mat3x3f",e),e=this._convertVariableConstructorsToWGSL("mat4","mat4x4f",e),e=this._convertTernaryOperandsToWGSL(e),e=this._convertModOperatorsToWGSL(e),e=this._convertConstToWGSL(e),e=this._convertInnerFunctionsToWGSL(e),e=(e=this._convertOutParametersToWGSL(e)).replace(/\[\*\]/g,"*"),(e=(e=(e=this._convertFunctionsToWGSL(e)).replace(/\s->\svoidnull/g,"")).replace(/dFdx/g,"dpdx")).replace(/dFdy/g,"dpdy")}_convertTernaryOperandsToGLSL(e){return e.replace(new RegExp("\\[(.+?)\\?(.+?):(.+)\\]","g"),((e,t,i,s)=>`${t} ? ${i} : ${s}`))}_babylonSLtoGLSL(e){return e=e.replace(/\[\*\]/g,""),this._convertTernaryOperandsToGLSL(e)}}class vl{constructor(){this.temps=[],this.varyings=[],this.varyingDeclaration="",this.inputBlocks=[],this.textureBlocks=[],this.bindableBlocks=[],this.forcedBindableBlocks=[],this.blocksWithFallbacks=[],this.blocksWithDefines=[],this.repeatableContentBlocks=[],this.dynamicUniformBlocks=[],this.blockingBlocks=[],this.animatedInputs=[],this.variableNames={},this.defineNames={},this.hints={needWorldViewMatrix:!1,needWorldViewProjectionMatrix:!1,needAlphaBlending:!1,needAlphaTesting:!1},this.checks={emitVertex:!1,emitFragment:!1,notConnectedNonOptionalInputs:new Array},this.allowEmptyVertexProgram=!1,this.variableNames.position=0,this.variableNames.normal=0,this.variableNames.tangent=0,this.variableNames.uv=0,this.variableNames.uv2=0,this.variableNames.uv3=0,this.variableNames.uv4=0,this.variableNames.uv5=0,this.variableNames.uv6=0,this.variableNames.color=0,this.variableNames.matricesIndices=0,this.variableNames.matricesWeights=0,this.variableNames.matricesIndicesExtra=0,this.variableNames.matricesWeightsExtra=0,this.variableNames.diffuseBase=0,this.variableNames.specularBase=0,this.variableNames.worldPos=0,this.variableNames.shadow=0,this.variableNames.view=0,this.variableNames.vTBN=0,this.defineNames.MAINUV0=0,this.defineNames.MAINUV1=0,this.defineNames.MAINUV2=0,this.defineNames.MAINUV3=0,this.defineNames.MAINUV4=0,this.defineNames.MAINUV5=0,this.defineNames.MAINUV6=0,this.defineNames.MAINUV7=0}emitErrors(){let e="";this.checks.emitVertex||this.allowEmptyVertexProgram||(e+="NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.\n"),this.checks.emitFragment||(e+="NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\n");for(const t of this.checks.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional.\n`;if(e)throw"Build of NodeMaterial failed:\n"+e}}class xl{constructor(e){if(this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!1,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)-1===this._keys.indexOf(e)&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;tthis._setDefaultValue(e)))}_setDefaultValue(e){const t=this._externalProperties?.[e]?.type??typeof this[e],i=this._externalProperties?.[e]?.default;switch(t){case"number":this[e]=i??0;break;case"string":this[e]=i??"";break;default:this[e]=i??!1}}toString(){let e="";for(let t=0;tthis._connectedPointBackingField=e)),this._connectedPointBackingField&&(this._connectedPointTypeChangedObserver=this._connectedPointBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get _typeConnectionSource(){return this._typeConnectionSourceBackingField}set _typeConnectionSource(e){this._typeConnectionSourceBackingField!==e&&(this._typeConnectionSourceTypeChangedObserver?.remove(),this._updateTypeDependentState((()=>this._typeConnectionSourceBackingField=e)),this._typeConnectionSourceBackingField&&(this._typeConnectionSourceTypeChangedObserver=this._typeConnectionSourceBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get _defaultConnectionPointType(){return this._defaultConnectionPointTypeBackingField}set _defaultConnectionPointType(e){this._updateTypeDependentState((()=>this._defaultConnectionPointTypeBackingField=e))}get _linkedConnectionSource(){return this._linkedConnectionSourceBackingField}set _linkedConnectionSource(e){this._linkedConnectionSourceBackingField!==e&&(this._linkedConnectionSourceTypeChangedObserver?.remove(),this._updateTypeDependentState((()=>this._linkedConnectionSourceBackingField=e)),this._linkedConnectionSourceBackingField&&(this._linkedConnectionSourceTypeChangedObserver=this._linkedConnectionSourceBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get direction(){return this._direction}get declarationVariableName(){return this._ownerBlock.isInput?this._ownerBlock.declarationVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.declarationVariableName}get associatedVariableName(){return this._ownerBlock.isInput?this._ownerBlock.associatedVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}get type(){if(this._type===al.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===al.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._updateTypeDependentState((()=>this._type=e))}get target(){return this._prioritizeVertex&&this._ownerBlock?this._target!==ll.VertexAndFragment?this._target:this._ownerBlock.target===ll.Fragment?ll.Fragment:ll.Vertex:this._target}set target(e){this._target=e}get isConnected(){return null!==this.connectedPoint||this.hasEndpoints}get isConnectedToInputBlock(){return null!==this.connectedPoint&&this.connectedPoint.ownerBlock.isInput}get connectInputBlock(){return this.isConnectedToInputBlock?this.connectedPoint.ownerBlock:null}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return 0===this._endpoints.length?[]:this._endpoints.map((e=>e.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===ll.Vertex)return!0;if((e.ownerBlock.target===ll.Neutral||e.ownerBlock.target===ll.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isDirectlyConnectedToVertexOutput)))return!0}return!1}get isConnectedInVertexShader(){if(this.target===ll.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===ll.Vertex)return!0;if(e.target===ll.Vertex)return!0;if((e.ownerBlock.target===ll.Neutral||e.ownerBlock.target===ll.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInVertexShader)))return!0}return!1}get isConnectedInFragmentShader(){if(this.target===ll.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===ll.Fragment)return!0;if((e.ownerBlock.target===ll.Neutral||e.ownerBlock.target===ll.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0}return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPointBackingField=null,this._endpoints=new Array,this._typeConnectionSourceBackingField=null,this._defaultConnectionPointTypeBackingField=null,this._linkedConnectionSourceBackingField=null,this._acceptedConnectionPointType=null,this._type=al.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new K,this.onDisconnectionObservable=new K,this.onTypeChangedObservable=new K,this._isTypeChangeObservableNotifying=!1,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=ll.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===hl.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===ll.Fragment){if(i.target===ll.Vertex)return hl.TargetIncompatible;for(const e of i.outputs)if(e.ownerBlock.target!=ll.Neutral&&e.isConnectedInVertexShader)return hl.TargetIncompatible}if(this.type!==e.type&&e.innerType!==al.AutoDetect)return bl.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&bl.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?hl.Compatible:hl.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return hl.TypeIncompatible;let s=i,r=t;return this.direction===cl.Input&&(s=t,r=i),s.isAnAncestorOf(r)?hl.HierarchyIssue:hl.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear(),this.onTypeChangedObservable.clear(),this._connectedPoint=null,this._typeConnectionSource=null,this._linkedConnectionSource=null}_updateTypeDependentState(e){const t=this.type;e(),this.type!==t&&this._notifyTypeChanged()}_notifyTypeChanged(){this._isTypeChangeObservableNotifying||(this._isTypeChangeObservableNotifying=!0,this.onTypeChangedObservable.notifyObservers(this.type),this._isTypeChangeObservableNotifying=!1)}}class Tl{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){this._target&e||(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}constructor(e,t=ll.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===ll.Neutral,this._isFinalMerger=i,this._isInput="InputBlock"===this.getClassName(),this._isTeleportOut="NodeMaterialTeleportOutBlock"===this.getClassName(),this._isTeleportIn="NodeMaterialTeleportInBlock"===this.getClassName(),this._name=e,this.uniqueId=Lr.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===ll.Neutral}initialize(e){}bind(e,t,i,s){}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return-1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some((e=>e.isConnectedInFragmentShader))}registerInput(e,t,i=!1,s,r){return(r=r??new bl(e,this,cl.Input)).type=t,r.isOptional=i,s&&(r.target=s),this._inputs.push(r),this}registerOutput(e,t,i,s){return(s=s??new bl(e,this,cl.Output)).type=t,i&&(s.target=i),this._outputs.push(s),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!(t.connectedPoint||e&&e.type!==t.type&&t.type!==al.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===ll.Neutral||e.target&t.target)return t;return null}getSiblingOutput(e){const t=this._outputs.indexOf(e);return-1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){if(i.ownerBlock===e)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),s=!0;for(;s;){const r=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&r&&i.canConnectTo(r))i.connectTo(r),s=!1;else{if(!i)throw"Unable to find a compatible match";i=this.getSiblingOutput(i)}}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,s){}provideFallbacks(e,t){}initializeDefines(e,t,i,s=!1){}prepareDefines(e,t,i,s=!1,r){}autoConfigure(e,t=(()=>!0)){}replaceRepeatableContent(e,t,i,s){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some((e=>e.isDirectlyConnectedToVertexOutput))||this.target===ll.Vertex||this.target!==ll.VertexAndFragment&&this.target!==ll.Neutral||!this._outputs.some((e=>e.isConnectedInVertexShader)))}isReady(e,t,i,s=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,s){e.build(t,s);const r=null!=t._vertexState,n=e._buildTarget===ll.Vertex&&e.target!==ll.VertexAndFragment;if(r&&(!(e.target&e._buildTarget)||!(e.target&i.target)||this.target!==ll.VertexAndFragment&&n)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){const e=i.connectedPoint;if(t._vertexState._emitVaryingFromString("v_"+e.declarationVariableName,e.type)){const i=t.shaderLanguage===di.WGSL?"vertexOutputs.":"";t._vertexState.compilationString+=`${i}${"v_"+e.declarationVariableName} = ${e.associatedVariableName};\n`}const s=t.shaderLanguage===di.WGSL?"fragmentInputs.":"";i.associatedVariableName=s+"v_"+e.declarationVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){const t=["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"];for(const i of t)if(e===i)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(const t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==ll.Neutral){if(!(i.target&this.target))continue;if(!(i.target&e.target))continue}const s=i.connectedPoint.ownerBlock;s&&s!==this&&this._processBuild(s,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&Ne.Log(`${e.target===ll.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case ll.Vertex:e.sharedData.checks.emitVertex=!0;break;case ll.Fragment:e.sharedData.checks.emitFragment=!0}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=`\n//${this.name}\n`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(const i of this._outputs)if(i.target&e.target)for(const s of i.endpoints){const i=s.ownerBlock;i&&i.target&e.target&&-1!==t.indexOf(i)&&this._processBuild(i,e,s,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector};\n${e}.visibleOnFrame = ${this.visibleOnFrame};\n${e}.target = ${this.target};\n`}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let s=`\n// ${this.getClassName()}\n`;this.comments&&(s+=`// ${this.comments}\n`),s+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\n`,s+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint.ownerBlock;-1===t.indexOf(r)&&(s+=r._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const r of i.endpoints){const i=r.ownerBlock;i&&-1===t.indexOf(i)&&(s+=i._dumpCode(e,t))}return s}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}return t}clone(e,t=""){const i=this.serialize(),s=W(i.customType);if(s){const r=new s;return r._deserialize(i,e,t),r}return null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i,s){this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=e.target??this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach(((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class yl extends Tl{constructor(e){super(e,ll.Neutral),this.complementW=1,this.complementZ=0,this.target=ll.Vertex,this.registerInput("vector",al.AutoDetect),this.registerInput("transform",al.Matrix),this.registerOutput("output",al.Vector4),this.registerOutput("xyz",al.Vector3),this._inputs[0].onConnectionObservable.add((e=>{if(e.ownerBlock.isInput){const t=e.ownerBlock;"normal"!==t.name&&"tangent"!==t.name||(this.complementW=0)}}))}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.transform,s=e._getShaderType(al.Vector4),r=e._getShaderType(al.Vector3);if(t.connectedPoint){if(0===this.complementW){const n=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",n),e.sharedData.blocksWithDefines.push(this);const o=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.shaderLanguage===di.WGSL?e.compilationString+=`var ${o}: mat3x3f = mat3x3f(${i.associatedVariableName}[0].xyz, ${i.associatedVariableName}[1].xyz, ${i.associatedVariableName}[2].xyz);\n`:e.compilationString+=`mat3 ${o} = mat3(${i.associatedVariableName});\n`,e.compilationString+="#ifdef NONUNIFORMSCALING\n",e.compilationString+=`${o} = transposeMat3(inverseMat3(${o}));\n`,e.compilationString+="#endif\n",t.connectedPoint.type){case al.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${s}(${o} * ${r}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\n`;break;case al.Vector3:case al.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${s}(${o} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${s}(${o} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\n`}}else{const r=i.associatedVariableName;switch(t.connectedPoint.type){case al.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${r} * ${s}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\n`;break;case al.Vector3:case al.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${r} * ${s}(${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${r} * ${t.associatedVariableName};\n`}}this.xyz.hasEndpoints&&(e.compilationString+=e._declareOutput(this.xyz)+` = ${this.output.associatedVariableName}.xyz;\n`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){const e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ};\n`;return e+=`${this._codeVariableName}.complementW = ${this.complementW};\n`,e}}z("BABYLON.TransformBlock",yl);class Sl extends Tl{constructor(e){super(e,ll.Vertex,!0),this.registerInput("vector",al.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e,t){if(t)return!0;for(const t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);const t=this.vector;return e.shaderLanguage===di.WGSL?e.compilationString+=`vertexOutputs.position = ${t.associatedVariableName};\n`:e.compilationString+=`gl_Position = ${t.associatedVariableName};\n`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes,e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant",al.Float),e._emitVaryingFromString("vFragmentDepth",al.Float),e.compilationString+="vFragmentDepth = 1.0 + gl_Position.w;\n",e.compilationString+="gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\n"),this}}function Cl(e,t=ul.Boolean,i="PROPERTIES",s){return(r,n)=>{let o=r._propStore;o||(o=[],r._propStore=o),o.push({propertyName:n,displayName:e,type:t,groupName:i,options:s??{}})}}z("BABYLON.VertexOutputBlock",Sl),function(e){e[e.Boolean=0]="Boolean",e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=3]="Vector2",e[e.List=4]="List"}(ul||(ul={}));class El extends Tl{constructor(e){super(e,ll.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",al.Color4,!0),this.registerInput("rgb",al.AutoDetect,!0),this.registerInput("a",al.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){(this.useLogarithmicDepth||t.useLogarithmicDepth)&&i&&So(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,s=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||s.isConnected,e.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant",al.Float),e._emitVaryingFromString("vFragmentDepth",al.Float),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r);let n="gl_FragColor";e.shaderLanguage===di.WGSL&&(n="fragmentOutputs.color");const o=e._getShaderType(al.Vector4);if(t.connectedPoint)s.isConnected?e.compilationString+=`${n} = ${o}(${t.associatedVariableName}.rgb, ${s.associatedVariableName});\n`:e.compilationString+=`${n} = ${t.associatedVariableName};\n`;else if(i.connectedPoint){let t="1.0";s.connectedPoint&&(t=s.associatedVariableName),i.connectedPoint.type===al.Float?e.compilationString+=`${n} = ${o}(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t});\n`:e.compilationString+=`${n} = ${o}(${i.associatedVariableName}, ${t});\n`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${n} = toLinearSpace(${n});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${n} = toGammaSpace(${n});\n`,e.compilationString+="#endif\n",(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e.compilationString+="gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\n"),e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+="gl_FragData[0] = gl_FragColor;\r\n",e.compilationString+="#endif\r\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\n`,e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.useLogarithmicDepth=e.useLogarithmicDepth??!1}}Ze([Cl("Convert to gamma space",ul.Boolean,"PROPERTIES",{notifiers:{update:!0}})],El.prototype,"convertToGammaSpace",void 0),Ze([Cl("Convert to linear space",ul.Boolean,"PROPERTIES",{notifiers:{update:!0}})],El.prototype,"convertToLinearSpace",void 0),Ze([Cl("Use logarithmic depth",ul.Boolean,"PROPERTIES")],El.prototype,"useLogarithmicDepth",void 0),z("BABYLON.FragmentOutputBlock",El),function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(dl||(dl={})),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime",e[e.CameraParameters=10]="CameraParameters",e[e.MaterialAlpha=11]="MaterialAlpha"}(_l||(_l={}));class Al{constructor(e=_e.Zero(),t=_e.Up()){this.position=e,this.normal=t}clone(){return new Al(this.position.clone(),this.normal.clone())}}class Pl{constructor(e=_e.Zero(),t=_e.Up(),i=de.Zero()){this.position=e,this.normal=t,this.uv=i}clone(){return new Pl(this.position.clone(),this.normal.clone(),this.uv.clone())}}!function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime",e[e.MouseInfo=3]="MouseInfo"}(pl||(pl={}));const Il={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},Rl={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},Ml={particle_texturemask:!0};class Ol extends Tl{get type(){if(this._type===al.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=al.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=al.Vector2,this._type;case"Vector3":return this._type=al.Vector3,this._type;case"Vector4":return this._type=al.Vector4,this._type;case"Color3":return this._type=al.Color3,this._type;case"Color4":return this._type=al.Color4,this._type;case"Matrix":return this._type=al.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=al.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=al.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=al.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=al.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case _l.World:case _l.WorldView:case _l.WorldViewProjection:case _l.View:case _l.ViewProjection:case _l.Projection:return this._type=al.Matrix,this._type;case _l.CameraPosition:return this._type=al.Vector3,this._type;case _l.FogColor:return this._type=al.Color3,this._type;case _l.DeltaTime:case _l.MaterialAlpha:return this._type=al.Float,this._type;case _l.CameraParameters:return this._type=al.Vector4,this._type}}return this._type}constructor(e,t=ll.Vertex,i=al.AutoDetect){super(e,t,!1),this._mode=dl.Undefined,this._animationType=pl.None,this._prefix="",this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new K,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=dl.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===al.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=dl.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=dl.Uniform}get declarationVariableName(){return this._associatedVariableName}get associatedVariableName(){return this._prefix+this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===dl.Undefined}get isUniform(){return this._mode===dl.Uniform}set isUniform(e){this._mode=e?dl.Uniform:dl.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===dl.Attribute}set isAttribute(e){this._mode=e?dl.Attribute:dl.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===dl.Varying}set isVarying(e){this._mode=e?dl.Varying:dl.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=dl.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case pl.Time:this.type===al.Float&&(this.value+=.01*e.getAnimationRatio());break;case pl.RealTime:this.type===al.Float&&(this.value=(Wt.Now-e.getEngine().startTime)/1e3);break;case pl.MouseInfo:if(this.type===al.Vector4){const t=e._inputManager._originMouseEvent;if(t){const e=t.offsetX,i=t.offsetY,s=1&t.buttons?1:0,r=2&t.buttons?1:0;this.value=new pe(e,i,s,r)}else this.value=new pe(0,0,0,0)}}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)}\n`:`#ifdef ${e}\n`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case al.Float:this.value=0;break;case al.Vector2:this.value=de.Zero();break;case al.Vector3:this.value=_e.Zero();break;case al.Vector4:this.value=pe.Zero();break;case al.Color3:this.value=Ee.White();break;case al.Color4:this.value=new Ae(1,1,1,1);break;case al.Matrix:this.value=me.Identity()}}_emitConstant(e){switch(this.type){case al.Float:return`${e._emitFloat(this.value)}`;case al.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case al.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case al.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case al.Color3:return Pe.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&Pe.Color3[0].toGammaSpaceToRef(Pe.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Pe.Color3[0].toLinearSpaceToRef(Pe.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${Pe.Color3[0].r}, ${Pe.Color3[0].g}, ${Pe.Color3[0].b})`;case al.Color4:return Pe.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&Pe.Color4[0].toGammaSpaceToRef(Pe.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Pe.Color4[0].toLinearSpaceToRef(Pe.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${Pe.Color4[0].r}, ${Pe.Color4[0].g}, ${Pe.Color4[0].b}, ${Pe.Color4[0].a})`}return""}get _noContextSwitch(){return Rl[this.name]}_emit(e,t){if(this.isUniform){if(this._associatedVariableName||(this._associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;return e.constants.push(this.associatedVariableName),void(e._constantDeclaration+=e._declareOutput(this.output,!0)+` = ${this._emitConstant(e)};\n`)}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t));const i=e._getShaderType(this.type);e.shaderLanguage===di.WGSL?(e._uniformDeclaration+=`uniform ${this._associatedVariableName}: ${i};\n`,this._prefix="uniforms."):e._uniformDeclaration+=`uniform ${i} ${this.associatedVariableName};\n`,t&&(e._uniformDeclaration+="#endif\n");const s=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case _l.WorldView:s.needWorldViewMatrix=!0;break;case _l.WorldViewProjection:s.needWorldViewProjectionMatrix=!0}else this._animationType!==pl.None&&e.sharedData.animatedInputs.push(this)}else if(this.isAttribute){if(this.associatedVariableName=Il[this.name]??this.name,this.target===ll.Vertex&&e._vertexState)return void(Rl[this.name]?Ml[this.name]?(e._emitUniformFromString(this.associatedVariableName,this.type,t),e.shaderLanguage===di.WGSL&&(this._prefix="vertexInputs.")):e._emitVaryingFromString(this.associatedVariableName,this.type,t):this._emit(e._vertexState,t));if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),Rl[this.name]?Ml[this.name]?e._emitUniformFromString(this.associatedVariableName,this.type,t):e._emitVaryingFromString(this.associatedVariableName,this.type,t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e.shaderLanguage===di.WGSL?(e._attributeDeclaration+=`attribute ${this.associatedVariableName}: ${e._getShaderType(this.type)};\n`,this._prefix="vertexInputs."):e._attributeDeclaration+=`attribute ${e._getShaderType(this.type)} ${this.associatedVariableName};\n`,t&&(e._attributeDeclaration+="#endif\n"))}}_transmitWorld(e,t,i,s){if(!this._systemValue)return;const r=this._associatedVariableName;switch(this._systemValue){case _l.World:e.setMatrix(r,t);break;case _l.WorldView:e.setMatrix(r,i);break;case _l.WorldViewProjection:e.setMatrix(r,s)}}_transmit(e,t,i){if(this.isAttribute)return;const s=this._associatedVariableName;if(this._systemValue){switch(this._systemValue){case _l.World:case _l.WorldView:case _l.WorldViewProjection:return;case _l.View:e.setMatrix(s,t.getViewMatrix());break;case _l.Projection:e.setMatrix(s,t.getProjectionMatrix());break;case _l.ViewProjection:e.setMatrix(s,t.getTransformMatrix());break;case _l.CameraPosition:t.bindEyePosition(e,s,!0);break;case _l.FogColor:e.setColor3(s,t.fogColor);break;case _l.DeltaTime:e.setFloat(s,t.deltaTime/1e3);break;case _l.CameraParameters:t.activeCamera&&e.setFloat4(s,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case _l.MaterialAlpha:e.setFloat(s,i.alpha)}return}const r=this._valueCallback?this._valueCallback():this._storedValue;if(null!==r)switch(this.type){case al.Float:e.setFloat(s,r);break;case al.Int:e.setInt(s,r);break;case al.Color3:Pe.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&Pe.Color3[0].toGammaSpaceToRef(Pe.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Pe.Color3[0].toLinearSpaceToRef(Pe.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(s,Pe.Color3[0]);break;case al.Color4:Pe.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&Pe.Color4[0].toGammaSpaceToRef(Pe.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Pe.Color4[0].toLinearSpaceToRef(Pe.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(s,Pe.Color4[0]);break;case al.Vector2:e.setVector2(s,r);break;case al.Vector3:e.setVector3(s,r);break;case al.Vector4:e.setVector4(s,r);break;case al.Matrix:e.setMatrix(s,r)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}");\n`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${_l[this._systemValue]});\n`;if(this.isUniform){const t=[];let i="";switch(this.type){case al.Float:i=`${this.value}`;break;case al.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case al.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case al.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case al.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case al.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case al.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===al.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${pl[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){const e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,null!=this._storedValue&&this._mode===dl.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,"tangent"===e.name&&e.mode===dl.Attribute&&e.type===al.Vector3&&(this._type=al.Vector4),e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=W(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}z("BABYLON.InputBlock",Ol);class Dl extends Tl{constructor(e){super(e,ll.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",al.AutoDetect,!1,ll.VertexAndFragment),this.registerOutput("rgba",al.Color4,ll.Neutral),this.registerOutput("rgb",al.Color3,ll.Neutral),this.registerOutput("r",al.Float,ll.Neutral),this.registerOutput("g",al.Float,ll.Neutral),this.registerOutput("b",al.Float,ll.Neutral),this.registerOutput("a",al.Float,ll.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Vector2|al.Vector3|al.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?ll.VertexAndFragment:ll.Fragment:ll.VertexAndFragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,al.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,al.Vector2),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===ll.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\n`}else this.uv.ownerBlock.target!==ll.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\n`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===ll.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target!==ll.Fragment?(e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"):e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.blockingBlocks.indexOf(this)<0&&e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.indexOf(this)<0&&e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.indexOf(this)<0&&e.sharedData.blocksWithDefines.push(this),e.target!==ll.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Pa.Parse(e.texture,t,i))}}z("BABYLON.CurrentScreenBlock",Dl);class wl extends Tl{constructor(e){super(e,ll.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",al.AutoDetect,!1,ll.VertexAndFragment),this.registerOutput("rgba",al.Color4,ll.Neutral),this.registerOutput("rgb",al.Color3,ll.Neutral),this.registerOutput("r",al.Float,ll.Neutral),this.registerOutput("g",al.Float,ll.Neutral),this.registerOutput("b",al.Float,ll.Neutral),this.registerOutput("a",al.Float,ll.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Vector2|al.Vector3|al.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"particle_uv"===e.name&&t(e)));i||(i=new Ol("uv"),i.setAsAttribute("particle_uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_writeOutput(e,t,i){e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"}_buildBlock(e){if(super._buildBlock(e),e.target===ll.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName});\n`;for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Pa.Parse(e.texture,t,i))}}z("BABYLON.ParticleTextureBlock",wl);class Nl extends Tl{constructor(e){super(e,ll.Fragment),this._isUnique=!0,this.registerInput("color",al.Color4,!1,ll.Fragment),this.registerOutput("rampColor",al.Color4,ll.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==ll.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges",al.Vector4,"RAMPGRADIENT"),e.compilationString+=`\n #ifdef RAMPGRADIENT\n vec4 baseColor = ${this.color.associatedVariableName};\n float alpha = ${this.color.associatedVariableName}.a;\n\n float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\n\n vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));\n baseColor.rgb *= rampColor.rgb;\n\n // Remapped alpha\n float finalAlpha = baseColor.a;\n baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);\n\n ${e._declareOutput(this.rampColor)} = baseColor;\n #else\n ${e._declareOutput(this.rampColor)} = ${this.color.associatedVariableName};\n #endif\n `,this}}z("BABYLON.ParticleRampGradientBlock",Nl);class Fl extends Tl{constructor(e){super(e,ll.Fragment),this._isUnique=!0,this.registerInput("color",al.Color4,!1,ll.Fragment),this.registerInput("alphaTexture",al.Float,!1,ll.Fragment),this.registerInput("alphaColor",al.Float,!1,ll.Fragment),this.registerOutput("blendColor",al.Color4,ll.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==ll.Vertex)return e.compilationString+=`\n #ifdef BLENDMULTIPLYMODE\n ${e._declareOutput(this.blendColor)};\n float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};\n ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);\n ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a;\n #else\n ${e._declareOutput(this.blendColor)} = ${this.color.associatedVariableName};\n #endif\n `,this}}z("BABYLON.ParticleBlendMultiplyBlock",Fl);class Ll{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let e=0;e0&&(s.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;i0}get is3D(){return this.depth>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){return this._textures?.[0]??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}constructor(e,t,i,s,r){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=s,this._depthStencilTexture=null,this.label=r}setTextures(e){Array.isArray(e)?this._textures=e:this._textures=e?[e]:null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){return this._depthStencilTexture?.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:s,depthTextureFormat:r,label:n},this),this._depthStencilTexture}_shareDepth(e){this.shareDepth(e)}shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){let e=null;if(this._isMulti){const t=this.textures;if(t&&t.length>0){let i=!1,s=t.length,r=-1;const n=t[t.length-1]._source;n!==is.Depth&&n!==is.DepthStencil||(i=!0,r=t[t.length-1].format,s--);const o=[],a=[],l=[],h=[],c=[],u=[],d=[],_={};for(let e=0;e1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e1){const r=this._context,n=r["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??this.layerIndices?.[t]??0,r.framebufferTextureLayer(r.FRAMEBUFFER,n,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=i??this.faceIndices?.[t]??0,r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const r=this._context,n=r["COLOR_ATTACHMENT"+t+"_WEBGL"],o=void 0!==i?r.TEXTURE_CUBE_MAP_POSITIVE_X+i:r.TEXTURE_2D;r.framebufferTexture2D(r.FRAMEBUFFER,n,o,e._hardwareTexture.underlyingResource,s)}n._bindUnboundFramebuffer(o)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=this._attachments?.length??this.textures.length;for(let e=0;e1&&(15===o.format?u=i.DEPTH_COMPONENT16:16===o.format?u=i.DEPTH_COMPONENT24:17===o.format||13===o.format?u=i.DEPTH24_STENCIL8:14===o.format?u=i.DEPTH_COMPONENT32F:18===o.format&&(u=i.DEPTH32F_STENCIL8)),o.is2DArray?i.texImage3D(n,0,u,o.width,o.height,s,0,c,h,null):o.is3D?i.texImage3D(n,0,u,o.width,o.height,r,0,c,h,null):i.texImage2D(n,0,u,o.width,o.height,0,c,h,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(o),o},qs.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);const s=e.texture._hardwareTexture;if(s.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){const r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBABufferInternalSizedFormat(e.texture.type,e.texture.format,e.texture._useSRGBBuffer),i.COLOR_ATTACHMENT0,!1);if(!n)throw new Error("Unable to create multi sampled framebuffer");s.addMSAARenderBuffer(n)}else this._bindUnboundFramebuffer(e._framebuffer);return e.texture.samples=t,e._samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t),this._bindUnboundFramebuffer(null),t},qs.prototype._setupDepthStencilTexture=function(e,t,i,s,r,n=1){const o=t.width||t,a=t.height||t,l=t.layers||0,h=t.depth||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.depth=l||h,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=0,e._comparisonFunction=r;const c=this._gl,u=this._getTextureTarget(e),d=this._getSamplingParameters(e.samplingMode,!1);c.texParameteri(u,c.TEXTURE_MAG_FILTER,d.mag),c.texParameteri(u,c.TEXTURE_MIN_FILTER,d.min),c.texParameteri(u,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(u,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===r?(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,515),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,r),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))},ns.prototype.setTextureFromPostProcess=function(e,t,i){let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,s?.texture??null,i)},ns.prototype.setTextureFromPostProcessOutput=function(e,t,i){this._bindTexture(e,t?._outputTexture?.texture??null,i)},$i.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)},$i.prototype.setTextureFromPostProcessOutput=function(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)};class Vl{static RegisterShaderCodeProcessing(e,t){t?Vl._CustomShaderCodeProcessing[e??""]=t:delete Vl._CustomShaderCodeProcessing[e??""]}static _GetShaderCodeProcessing(e){return Vl._CustomShaderCodeProcessing[e]??Vl._CustomShaderCodeProcessing[""]}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach((e=>{e.setSamples(this._samples)}))}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,s,r,n,o=1,a,l,h=null,c=0,u="postprocess",d,_=!1,p=5,f=di.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new Fs(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new de(1,1),this._texelSize=de.Zero(),this.onActivateObservable=new K,this.onSizeChangedObservable=new K,this.onApplyObservable=new K,this.onBeforeRenderObservable=new K,this.onAfterRenderObservable=new K,this.name=e;let m=1,g=null;if(i&&!Array.isArray(i)){const e=i;i=e.uniforms??null,s=e.samplers??null,m=e.size??1,n=e.camera??null,o=e.samplingMode??1,a=e.engine,l=e.reusable,h=e.defines??null,c=e.textureType??0,u=e.vertexUrl??"postprocess",d=e.indexParameters,_=e.blockCompilation??!1,p=e.textureFormat??5,f=e.shaderLanguage??di.GLSL,g=e.uniformBuffers??null}else r&&(m="number"==typeof r?r:{width:r.width,height:r.height});null!=n?(this._camera=n,this._scene=n.getScene(),n.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):a&&(this._engine=a,this._engine.postProcesses.push(this)),this._options=m,this.renderTargetSamplingMode=o||1,this._reusable=l||!1,this._textureType=c,this._textureFormat=p,this._shaderLanguage=f,this._samplers=s||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=u,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=g||[],this._indexParameters=d,this._drawWrapper=new Un(this._engine),_||this.updateEffect(h)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){0==this._textures.length&&(this._textures=new Fs(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,r,n,o,a){const l=Vl._GetShaderCodeProcessing(this.name);if(l?.defineCustomBindings){const s=t?.slice()??[];s.push(...this._parameters);const r=i?.slice()??[];r.push(...this._samplers),e=l.defineCustomBindings(this.name,e,s,r),t=s,i=r}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:o??this._vertexUrl,fragment:a??this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:r??null,onError:n??null,indexParameters:s||this._indexParameters,processCodeAfterIncludes:l?.processCodeAfterIncludes?(e,t)=>l.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:l?.processFinalCode?(e,t)=>l.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let s=0;s=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i)for(let e=0;e{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}return u||(u=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/l,a/h),this._engine.bindFramebuffer(u,0,o,a,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(u,0,void 0,void 0,this.forceFullscreenViewport)),this._engine._debugInsertMarker?.(`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:s.clearColor,s._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),u}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._drawWrapper.effect?.isReady()??!1}apply(){if(!this._drawWrapper.effect?.isReady())return null;let e;return this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),e=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e?.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),Vl._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name,this._drawWrapper.effect),this._drawWrapper.effect}_disposeTextures(){this._shareOutputWithPostProcess||this._forcedOutputTexture?this._disposeTextureCache():(this._disposeTextureCache(),this._textures.dispose())}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return!!this._prePassEffectConfiguration&&(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0)}dispose(e){let t;if(e=e||this._camera,this._disposeTextures(),this._scene&&(t=this._scene.postProcesses.indexOf(this),-1!==t&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),-1!==t&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),0===t&&e._postProcesses.length>0){const e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){const e=St.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const e=this.serialize();e._engine=this._engine,e.cameraId=null;const t=Vl.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const s=W(e.customType);if(!s||!s._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return s._Parse(e,r,t,i)}static _Parse(e,t,i,s){return St.Parse((()=>new Vl(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat)),e,i,s)}}Vl._CustomShaderCodeProcessing={},Ze([rt()],Vl.prototype,"uniqueId",void 0),Ze([rt()],Vl.prototype,"name",void 0),Ze([rt()],Vl.prototype,"width",void 0),Ze([rt()],Vl.prototype,"height",void 0),Ze([rt()],Vl.prototype,"renderTargetSamplingMode",void 0),Ze([dt()],Vl.prototype,"clearColor",void 0),Ze([rt()],Vl.prototype,"autoClear",void 0),Ze([rt()],Vl.prototype,"forceAutoClearInAlphaMode",void 0),Ze([rt()],Vl.prototype,"alphaMode",void 0),Ze([rt()],Vl.prototype,"alphaConstants",void 0),Ze([rt()],Vl.prototype,"enablePixelPerfectMode",void 0),Ze([rt()],Vl.prototype,"forceFullscreenViewport",void 0),Ze([rt()],Vl.prototype,"scaleMode",void 0),Ze([rt()],Vl.prototype,"alwaysForcePOT",void 0),Ze([rt("samples")],Vl.prototype,"_samples",void 0),Ze([rt()],Vl.prototype,"adaptScaleToCurrentViewport",void 0),z("BABYLON.PostProcess",Vl);class Ul extends Tl{constructor(e){super(e,ll.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",al.Vector4,!0),this.registerInput("xyz ",al.Vector3,!0),this.registerInput("xy ",al.Vector2,!0),this.registerInput("zw ",al.Vector2,!0),this.registerInput("x",al.Float,!0),this.registerInput("y",al.Float,!0),this.registerInput("z",al.Float,!0),this.registerInput("w",al.Float,!0),this.registerOutput("xyzw",al.Vector4),this.registerOutput("xyz",al.Vector3),this.registerOutput("xy",al.Vector2),this.registerOutput("zw",al.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.x,i=this.y,s=this.z,r=this.w,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],c=this._outputs[1],u=this._outputs[2],d=this._outputs[3],_=e._getShaderType(al.Vector4),p=e._getShaderType(al.Vector3),f=e._getShaderType(al.Vector2);return l.isConnected?(h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${l.associatedVariableName}${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${l.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${l.associatedVariableName}${this._buildSwizzle(2)};\n`)):a.isConnected?(h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${_}(${a.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${a.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${a.associatedVariableName}${this._buildSwizzle(2)};\n`)):n.isConnected?(h.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(h)+` = ${_}(${n.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=e._declareOutput(h)+` = ${_}(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${p}(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${n.associatedVariableName}${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(d)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=e._declareOutput(d)+` = ${f}(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};\n`)):(h.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(h)+` = ${_}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=e._declareOutput(h)+` = ${_}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${p}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${f}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(d)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=e._declareOutput(d)+` = ${f}(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};\n`)),this}serialize(){const e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.xSwizzle=e.xSwizzle??"x",this.ySwizzle=e.ySwizzle??"y",this.zSwizzle=e.zSwizzle??"z",this.wSwizzle=e.wSwizzle??"w"}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}";\n`,e+=`${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";\n`,e+=`${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";\n`,e+=`${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";\n`,e}}z("BABYLON.VectorMergerBlock",Ul);class Gl extends Tl{constructor(e){super(e,ll.Neutral),this.sourceRange=new de(-1,1),this.targetRange=new de(0,1),this.registerInput("input",al.AutoDetect),this.registerInput("sourceMin",al.Float,!0),this.registerInput("sourceMax",al.Float,!0),this.registerInput("targetMin",al.Float,!0),this.registerInput("targetMax",al.Float,!0),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),s=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),r=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),n=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=e._declareOutput(t)+` = ${r} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${r}) / (${s} - ${i});\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\n`;return e+=`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\n`,e}serialize(){const e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=de.FromArray(e.sourceRange),this.targetRange=de.FromArray(e.targetRange)}}Ze([Cl("From",ul.Vector2)],Gl.prototype,"sourceRange",void 0),Ze([Cl("To",ul.Vector2)],Gl.prototype,"targetRange",void 0),z("BABYLON.RemapBlock",Gl);class zl extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("left",al.AutoDetect),this.registerInput("right",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this.output._typeConnectionSource=this.left,this._linkConnectionTypes(0,1,!0),this.left.acceptedConnectionPointTypes.push(al.Float),this.right.acceptedConnectionPointTypes.push(al.Float),this._connectionObservers=[this.left.onTypeChangedObservable.add((()=>this._updateInputOutputTypes())),this.right.onTypeChangedObservable.add((()=>this._updateInputOutputTypes()))]}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===al.Int||this.left.type===al.Float&&this.right.type!==al.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(const[e,t]of[[this.left,this.right],[this.right,this.left]])e.acceptedConnectionPointTypes=[al.Int,al.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==al.Int&&t.type!==al.Float||e.acceptedConnectionPointTypes.push(al.Vector2,al.Vector3,al.Vector4,al.Color3,al.Color4,al.Matrix))}dispose(){super.dispose(),this._connectionObservers.forEach((e=>e.remove())),this._connectionObservers.length=0}}class Wl extends zl{constructor(e){super(e)}getClassName(){return"MultiplyBlock"}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};\n`,this}}var Hl;z("BABYLON.MultiplyBlock",Wl),function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture"}(Hl||(Hl={}));class Xl extends xl{constructor(){super(),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class Yl{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:_e.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:_e.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:_e.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:_e.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let s=0;for(const i of t){if(i.gradient===e){t.splice(s,1);break}s++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=_e.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this.applyFog=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new _e(10,10,10),this.onAnimationEnd=null,this.blendMode=Yl.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new de(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new _e(0,0,0),this._useLogarithmicDepth=!1,this.gravity=_e.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new Ae(1,1,1,1),this.color2=new Ae(1,1,1,1),this.colorDead=new Ae(0,0,0,1),this.textureMask=new Ae(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new Xl,this.id=e,this.name=e}createPointEmitter(e,t){throw new Error("Method not implemented.")}createHemisphericEmitter(e=1,t=1){throw new Error("Method not implemented.")}createSphereEmitter(e=1,t=1){throw new Error("Method not implemented.")}createDirectedSphereEmitter(e=1,t=new _e(0,1,0),i=new _e(0,1,0)){throw new Error("Method not implemented.")}createCylinderEmitter(e=1,t=1,i=1,s=0){throw new Error("Method not implemented.")}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new _e(0,1,0),r=new _e(0,1,0)){throw new Error("Method not implemented.")}createConeEmitter(e=1,t=Math.PI/4){throw new Error("Method not implemented.")}createBoxEmitter(e,t,i,s){throw new Error("Method not implemented.")}}Yl.BLENDMODE_ONEONE=0,Yl.BLENDMODE_STANDARD=1,Yl.BLENDMODE_ADD=2,Yl.BLENDMODE_MULTIPLY=3,Yl.BLENDMODE_MULTIPLYADD=4,z("BABYLON.BaseParticleSystem",Yl);class Ql extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("rgba",al.Color4,!0),this.registerInput("rgb ",al.Color3,!0),this.registerOutput("rgb",al.Color3),this.registerOutput("r",al.Float),this.registerOutput("g",al.Float),this.registerOutput("b",al.Float),this.registerOutput("a",al.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);const t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;const i=this._outputs[0],s=this._outputs[1],r=this._outputs[2],n=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${t.associatedVariableName}.rgb;\n`),s.hasEndpoints&&(e.compilationString+=e._declareOutput(s)+` = ${t.associatedVariableName}.r;\n`),r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = ${t.associatedVariableName}.g;\n`),n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = ${t.associatedVariableName}.b;\n`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = ${t.associatedVariableName}.a;\n`),this}}z("BABYLON.ColorSplitterBlock",Ql),qs.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,(1!==s.type||this._caps.textureFloatLinearFiltering)&&(2!==s.type||this._caps.textureHalfFloatLinearFiltering)||(s.samplingMode=1);const r=this._gl,n=new ss(this,is.RenderTarget);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,n,!0);const o=this._getSamplingParameters(s.samplingMode,s.generateMipMaps);1!==s.type||this._caps.textureFloat||(s.type=0,Ne.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,o.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,o.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let t=0;t<6;t++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(s.type,s.format),e,e,0,this._getInternalFormat(s.format),this._getWebGLTextureType(s.type),null);const a=r.createFramebuffer();return this._bindUnboundFramebuffer(a),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(s.generateStencilBuffer,s.generateDepthBuffer,e,e),s.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=a,i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=s.generateMipMaps,n.samplingMode=s.samplingMode,n.type=s.type,n.format=s.format,this._internalTexturesCache.push(n),i.setTextures(n),i},qs.prototype.setDepthStencilTexture=function(e,t,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,s):this._setTexture(e,null,void 0,void 0,s))};const jl={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class Kl{constructor(e,t=jl){this._fullscreenViewport=new Pn(0,0,1,1);const i=t.positions??jl.positions,s=t.indices??jl.indices;this.engine=e,this._vertexBuffers={[er.PositionKind]:new er(e,i,er.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(s),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(s);for(const e in this._vertexBuffers)this._vertexBuffers[e]._rebuild()}))}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=null===t?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){const e=this._vertexBuffers[er.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[er.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class $l{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new K;const i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add((()=>{this.effect.setFloat2("scale",1,1)})));const s=e.defines?e.defines.join("\n"):"";this._drawWrapper=new Un(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],i,e.samplerNames,s,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new $i(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,s,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add((()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const ql="passPixelShader",Zl="varying vec2 vUV;uniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);}";Bi.ShadersStore[ql]=Zl;const Jl=ql,eh=Zl;class th{static _CreateDumpRenderer(){if(!th._DumpToolsEngine){let e,t=null;const i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new qs(e,!1,i)}catch(s){e=document.createElement("canvas"),t=new qs(e,!1,i)}re.Instances.pop(),re.OnEnginesDisposedObservable.add((e=>{t&&e!==t&&!t.isDisposed&&0===re.Instances.length&&th.Dispose()})),t.getCaps().parallelShaderCompile=void 0;const s=new Kl(t),r=new $l({engine:t,name:Jl,fragmentShader:eh,samplerNames:["textureSampler"]});th._DumpToolsEngine={canvas:e,engine:t,renderer:s,wrapper:r}}return th._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,r="image/png",n,o){const a=await i.readPixels(0,0,e,t),l=new Uint8Array(a.buffer);th.DumpData(e,t,l,s,r,n,!0,void 0,o)}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,o=!1,a){return new Promise((l=>{th.DumpData(e,t,i,(e=>l(e)),s,r,n,o,a)}))}static DumpData(e,t,i,s,r="image/png",n,o=!1,a=!1,l){const h=th._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){const e=new Uint8Array(i.length);let t=i.length;for(;t--;){const s=i[t];e[t]=Math.round(255*be.Clamp(s))}i=e}const c=h.engine.createRawTexture(i,e,t,5,!1,!o,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",c),h.renderer.draw(),a?Ds.ToBlob(h.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;s&&s(t)},t.readAsArrayBuffer(e)}),r,l):Ds.EncodeScreenshotCanvasData(h.canvas,s,r,n,l),c.dispose()}static Dispose(){th._DumpToolsEngine&&(th._DumpToolsEngine.wrapper.dispose(),th._DumpToolsEngine.renderer.dispose(),th._DumpToolsEngine.engine.dispose()),th._DumpToolsEngine=null}}Ds.DumpData=th.DumpData,Ds.DumpDataAsync=th.DumpDataAsync,Ds.DumpFramebuffer=th.DumpFramebuffer,$i.prototype.setDepthStencilTexture=function(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)};class ih extends Pa{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=ie(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;i=Array.isArray(e)?e:[e];for(let e=0;e{const i=this._renderList?this._renderList.length:0;(0===t&&i>0||0===i)&&this.getScene()?.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new K,this.onAfterUnbindObservable=new K,this.onBeforeRenderObservable=new K,this.onAfterRenderObservable=new K,this.onClearObservable=new K,this.onResizeObservable=new K,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=_e.Zero(),!(i=this.getScene()))return;const x=this.getScene().getEngine();this._gammaSpace=v,this._coordinatesMode=Pa.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=o,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=x.onResizeObservable.add((()=>{})),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=r,this._renderingManager=new nr(i),this._renderingManager._useSceneAutoClearSetup=!0,c||(this._renderTargetOptions={generateMipMaps:s,type:n,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:h,samples:_,creationFlags:p,noColorAttachment:f,useSRGBBuffer:m,colorAttachment:g,label:this.name},this.samplingMode===Pa.NEAREST_SAMPLINGMODE&&(this.wrapU=Pa.CLAMP_ADDRESSMODE,this.wrapV=Pa.CLAMP_ADDRESSMODE),d||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=Pa.INVCUBIC_MODE,this._textureMatrix=me.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==_&&(this.samples=_)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){this._renderTarget?.createDepthStencilTexture(e,t,i,s,r,n)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;if(e)return e;return this._size.depth||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){const t=this.isCube;this._renderTarget?.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e,!1),this._renderTarget=t?i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==this._renderTargetOptions.samples&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){const s=this.getScene();if(!s)return i;const r=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let e=0;e{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):s&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0,r=null){const n=this.getScene();if(!n)return;const o=n.getEngine();if(o._debugPushGroup?.(`render to face #${e} layer #${s}`,1),this._prepareFrame(n,e,s,t),this.is2DArray||this.is3D?(o.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(o.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),o.snapshotRendering&&1===o.snapshotRenderingMode)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||n.clearColor,!0,!0,!0);else{let a=null;const l=this.renderList?this.renderList:n.getActiveMeshes().data,h=this.renderList?this.renderList.length:n.getActiveMeshes().length;this.getCustomRenderList&&(a=this.getCustomRenderList(this.is2DArray||this.is3D?s:e,l,h)),a?this._prepareRenderingManager(a,a.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(l,h,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),a=l);for(const t of n._beforeRenderTargetClearStage)t.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||n.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0);for(const t of n._beforeRenderTargetDrawStage)t.action(this,e,s);this._renderingManager.render(this.customRenderFunction,a,this.renderParticles,this.renderSprites);for(const t of n._afterRenderTargetDrawStage)t.action(this,e,s);const c=this._texture?.generateMipMaps??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&n.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e);for(const t of n._afterRenderTargetPostProcessStage)t.action(this,e,s);this._texture&&(this._texture.generateMipMaps=c),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0),i&&th.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),o)}this._unbindFrameBuffer(o,e),this._texture&&this.isCube&&5===e&&o.generateMipMapsForCubemap(this._texture,!0),o._debugPopGroup?.(1)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new ih(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&e.customRenderTargets.splice(t,1);for(const i of e.cameras)t=i.customRenderTargets.indexOf(this),t>=0&&i.customRenderTargets.splice(t,1);this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===ih.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=ih.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}ih.REFRESHRATE_RENDER_ONCE=0,ih.REFRESHRATE_RENDER_ONEVERYFRAME=1,ih.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,Pa._CreateRenderTargetTexture=(e,t,i,s,r)=>new ih(e,t,i,s);class sh{constructor(e){this.name=or.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(or.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){Ds.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}Bi.ShadersStore.proceduralVertexShader="attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class rh extends Pa{constructor(e,t,i,s,r=null,n=!0,o=!1,a=0){super(null,s,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new K,this.onBeforeGenerationObservable=new K,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._vectors4={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null,null===r||r instanceof Pa?(this._options={},this._fallbackTexture=r):(this._options=r,this._fallbackTexture=r.fallbackTexture??null);let l=(s=this.getScene()||re.LastCreatedScene)._getComponent(or.NAME_PROCEDURALTEXTURE);l||(l=new sh(s),s._addComponent(l)),s.proceduralTextures.push(this),this._fullEngine=s.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=a,this._generateMipMaps=n,this._drawWrapper=new Un(this._fullEngine),this.setFragment(i);const h=this._createRtWrapper(o,t,n,a);this._texture=h.texture;const c=[];c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1),this._vertexBuffers[er.PositionKind]=new er(this._fullEngine,c,er.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,s){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.then((e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId})):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId)),this._contentData}_createIndexBuffer(){const e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[er.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===ih.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=ih.REFRESHRATE_RENDER_ONCE)}reset(){this._drawWrapper.effect?.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}executeWhenReady(e){if(this.isReady())return void e(this);const t=this.getEffect();t&&t.executeWhenCompiled((()=>{e(this)}))}isReady(){const e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;const t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;const i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:"string"==typeof this._fragment?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[er.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,(()=>{this._rtWrapper?.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0}))),this._drawWrapper.effect.isReady()}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;const i=this._texture.isCube;this._rtWrapper.dispose();const s=this._createRtWrapper(i,e,t,this._textureType);this._texture=s.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){const t=this.getScene();if(!t)return;const i=this._fullEngine;if(i.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),i.setState(!1),!this.nodeMaterialSource){for(const e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(const e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(const e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(const e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(const e in this._colors4){const t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(const e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)this._drawWrapper.effect.setVector4(e,this._vectors4[e]);for(const e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;i._debugPushGroup?.(`procedural texture generation for ${this.name}`,1);const s=i.currentViewport;if(this.isCube)for(let e=0;e<6;e++)i.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(ta.TriangleFillMode,0,6);else{let e=1;this._rtWrapper.is3D?e=this._rtWrapper.depth:this._rtWrapper.is2DArray&&(e=this._rtWrapper.layers);for(let s=0;s=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[er.PositionKind];i&&(i.dispose(),this._vertexBuffers[er.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}var nh;Ze([rt()],rh.prototype,"isEnabled",void 0),Ze([rt()],rh.prototype,"autoClear",void 0),Ze([rt()],rh.prototype,"_generateMipMaps",void 0),Ze([rt()],rh.prototype,"_size",void 0),Ze([rt()],rh.prototype,"refreshRate",null),z("BABYLON.ProceduralTexture",rh),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees",e[e.Set=18]="Set"}(nh||(nh={}));class oh extends Tl{constructor(e){super(e,ll.Neutral),this.operation=nh.Cos,this.registerInput("input",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="";switch(this.operation){case nh.Cos:i="cos";break;case nh.Sin:i="sin";break;case nh.Abs:i="abs";break;case nh.Exp:i="exp";break;case nh.Exp2:i="exp2";break;case nh.Round:i="round";break;case nh.Floor:i="floor";break;case nh.Ceiling:i="ceil";break;case nh.Sqrt:i="sqrt";break;case nh.Log:i="log";break;case nh.Tan:i="tan";break;case nh.ArcTan:i="atan";break;case nh.ArcCos:i="acos";break;case nh.ArcSin:i="asin";break;case nh.Fract:i="fract";break;case nh.Sign:i="sign";break;case nh.Radians:i="radians";break;case nh.Degrees:i="degrees";break;case nh.Set:i=""}return e.compilationString+=e._declareOutput(t)+` = ${i}(${this.input.associatedVariableName});\n`,this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${nh[this.operation]};\n`}}z("BABYLON.TrigonometryBlock",oh);const ah={effect:null,subMesh:null};class lh extends xl{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class hh extends ml{static _BlockIsTextureBlock(e){return"TextureBlock"===e.getClassName()||"ReflectionTextureBaseBlock"===e.getClassName()||"ReflectionTextureBlock"===e.getClassName()||"ReflectionBlock"===e.getClassName()||"RefractionBlock"===e.getClassName()||"CurrentScreenBlock"===e.getClassName()||"ParticleTextureBlock"===e.getClassName()||"ImageSourceBlock"===e.getClassName()||"TriPlanarBlock"===e.getClassName()||"BiPlanarBlock"===e.getClassName()||"PrePassTextureBlock"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get shaderLanguage(){return this._options.shaderLanguage}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){if(super(e,t||re.LastCreatedScene),this._buildId=hh._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new me,this._cachedWorldViewProjectionMatrix=new me,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new K,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=[],this._mode=Hl.Material,this.forceAlphaBlending=!1,i&&i.shaderLanguage===di.WGSL&&!this.getScene().getEngine().isWebGPU)throw new Error("WebGPU shader language is only supported with WebGPU engine");this._options={emitComments:!1,shaderLanguage:hh.DefaultShaderLanguage,...i},this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return Ds.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(const t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){const t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return e.target&ll.Vertex&&this._addVertexOutputNode(e),e.target&ll.Fragment&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||(e.target&ll.Vertex&&this._removeVertexOutputNode(e),e.target&ll.Fragment&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=ll.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){const t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=ll.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){const t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,s=!0){(e.target===ll.VertexAndFragment||t.target===ll.Fragment&&e.target===ll.Vertex&&e._preparationId!==this._buildId)&&i.push(e),this._initializeBlock(e,t,i,s)}_initializeBlock(e,t,i,s=!0){if(e.initialize(t),s&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){const t=e.getClassName();for(const e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const r of e.inputs){r.associatedVariableName="";const n=r.connectedPoint;if(n){const r=n.ownerBlock;r!==e&&this._processInitializeOnLink(r,t,i,s)}}if(e.isTeleportOut){const r=e;r.entryPoint&&this._processInitializeOnLink(r.entryPoint,t,i,s)}for(const t of e.outputs)t.associatedVariableName=""}_resetDualBlocks(e,t){e.target===ll.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._resetDualBlocks(i.entryPoint,t)}}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){this._vertexCompilationState||i||(i=!0),this._buildWasSuccessful=!1;const s=this.getScene().getEngine(),r=this._mode===Hl.Particle;if(0===this._vertexOutputNodes.length&&!r)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new gl,this._vertexCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._vertexCompilationState.target=ll.Vertex,this._fragmentCompilationState=new gl,this._fragmentCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._fragmentCompilationState.target=ll.Fragment,this._sharedData=new vl,this._sharedData.nodeMaterial=this,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=r;const n=[],o=[];for(const e of this._vertexOutputNodes)n.push(e),this._initializeBlock(e,this._vertexCompilationState,o,i);for(const e of this._fragmentOutputNodes)o.push(e),this._initializeBlock(e,this._fragmentCompilationState,n,i);this.optimize();for(const e of n)e.build(this._vertexCompilationState,n);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(const e of o)this._resetDualBlocks(e,this._buildId-1);for(const e of o)e.build(this._fragmentCompilationState,o);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=hh._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(Ne.Log("Vertex shader:"),Ne.Log(this._vertexCompilationState.compilationString),Ne.Log("Fragment shader:"),Ne.Log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const a=this.getScene().meshes;for(const e of a)if(e.subMeshes)for(const t of e.subMeshes){if(t.getMaterial()!==this)continue;if(!t.materialDefines)continue;const e=t.materialDefines;e.markAllAsDirty(),e.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();const l=this.getScene().prePassRenderer;l&&l.markAsDirty()}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,s=t.TANGENT,r=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(er.NormalKind),t.TANGENT=e.isVerticesDataPresent(er.TangentKind);const n=e.useVertexColors&&e.isVerticesDataPresent(er.ColorKind);t.VERTEXCOLOR_NME=n;let o=!1;for(let i=1;i<=6;++i){const s=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),o=o||t["UV"+i]!==s}const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;qo(this.getScene(),t,!a),(i!==t.NORMAL||s!==t.TANGENT||r!==t.VERTEXCOLOR_NME||o)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){const e=this.getBlockByPredicate((e=>"PrePassOutputBlock"===e.getClassName())),t=[4];return e?(this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t):t}get prePassTextureInputs(){const e=this.getAllTextureBlocks().filter((e=>"PrePassTextureBlock"===e.getClassName())),t=[];for(const i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){const t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]}));for(const e of t)i.texturesRequired.includes(e)||i.texturesRequired.push(e);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,s,r,n=0,o=5){return this.mode!==Hl.PostProcess?(Ne.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,s,r,n,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,s=1,r,n,o=0,a=5){let l=this.name+this._buildId;const h=new lh,c=new _o(l+"PostProcess",this.getScene());let u=this._buildId;return this._processDefines(c,h),$i.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new Vl(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,s,r,n,h.toString(),o,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,a),e.nodeMaterialSource=this,e.onApplyObservable.add((t=>{u!==this._buildId&&(delete $i.ShadersStore[l+"VertexShader"],delete $i.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),u=this._buildId),this._processDefines(c,h)&&($i.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Li.SetImmediate((()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l)))),this._checkInternals(t)})),e}createProceduralTexture(e,t){if(this.mode!==Hl.ProceduralTexture)return Ne.Log("Incompatible material mode"),null;let i=this.name+this._buildId;const s=new rh(i,e,null,t),r=new _o(i+"Procedural",this.getScene());r.reservedDataStore={hidden:!0};const n=new lh,o=this._processDefines(r,n);$i.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[er.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),o?.fallbacks,void 0);s.nodeMaterialSource=this,s._setEffect(a);let l=this._buildId;return s.onBeforeGenerationObservable.add((()=>{l!==this._buildId&&(delete $i.ShadersStore[i+"VertexShader"],delete $i.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),l=this._buildId);const e=this._processDefines(r,n);e&&($i.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Li.SetImmediate((()=>{a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[er.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),e?.fallbacks,void 0),s._setEffect(a)}))),this._checkInternals(a)})),s}_createEffectForParticles(e,t,i,s,r,n,o,a=""){let l=this.name+this._buildId+"_"+t;n||(n=new lh),o||(o=this.getScene().getMeshByName(this.name+"Particle"))||((o=new _o(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId;const c=[];let u=a;if(!r){const a=this._processDefines(o,n);$i.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(c,t,!1),u=c.join("\n"),r=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,a?.fallbacks,i,s,e),e.setCustomEffect(r,t)}r.onBindObservable.add((r=>{h!==this._buildId&&(delete $i.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,n.markAllAsDirty(),h=this._buildId),c.length=0,e.fillDefines(c,t,!1);const d=c.join("\n");d!==u&&(n.markAllAsDirty(),u=d);const _=this._processDefines(o,n);if(_)return $i.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),r=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,_?.fallbacks,i,s,e),e.setCustomEffect(r,t),void this._createEffectForParticles(e,t,i,s,r,n,o,a);this._checkInternals(r)}))}_checkInternals(e){if(this._sharedData.animatedInputs){const e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(const t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(const t of this._sharedData.bindableBlocks)t.bind(e,this);for(const t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){this.mode===Hl.Particle?(this._createEffectForParticles(e,Yl.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,Yl.BLENDMODE_MULTIPLY,t,i)):Ne.Log("Incompatible material mode")}createAsShadowDepthWrapper(e){this.mode===Hl.Material?e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene()):Ne.Log("Incompatible material mode")}_processDefines(e,t,i=!1,s){let r=null;if(Zo(this.getScene(),t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach((s=>{s.initializeDefines(e,this,t,i)})),this._sharedData.blocksWithDefines.forEach((r=>{r.prepareDefines(e,this,t,i,s)})),t.isDirty){const i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach((i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)}));const s=[];this._sharedData.dynamicUniformBlocks.forEach((e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,s)}));const n=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach((e=>{-1===n.indexOf(e)&&n.push(e)}));const o=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach((e=>{-1===o.indexOf(e)&&o.push(e)}));const a=new Ll;this._sharedData.blocksWithFallbacks.forEach((t=>{t.provideFallbacks(e,a)})),r={lightDisposed:i,uniformBuffers:s,mergedUniforms:n,mergedSamplers:o,fallbacks:a}}return r}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const s=this.getScene();if(this._sharedData.animatedInputs){const e=s.getFrameId();if(this._animationFrame!==e){for(const e of this._sharedData.animatedInputs)e.animate(s);this._animationFrame=e}}const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new lh);const n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=s.getEngine();if(this._prepareDefinesForAttributes(e,n),this._sharedData.blockingBlocks.some((t=>!t.isReady(e,this,n,i))))return!1;const a=this._processDefines(e,n,i,t);if(a){const e=t.effect,i=n.toString();let r=o.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:i,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:n.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS},shaderLanguage:this.shaderLanguage},o);if(r)if(this._onEffectCreatedObservable&&(ah.effect=r,ah.subMesh=t,this._onEffectCreatedObservable.notifyObservers(ah)),this.allowShaderHotSwapping&&e&&!r.isReady()){if(r=e,n.markAsUnprocessed(),a.lightDisposed)return n._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(r,n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}get compiledShaders(){return`// Vertex shader\n${this._vertexCompilationState.compilationString}\n\n// Fragment shader\n${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){const t=this.getScene();if(!this._activeEffect)return;const i=this._sharedData.hints;i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(const t of this._sharedData.inputBlocks)t._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.effect;if(!r)return;this._activeEffect=r,this.bindOnlyWorldMatrix(e);const n=this._mustRebind(s,r,i,t.visibility),o=this._sharedData;if(n){for(const e of o.bindableBlocks)e.bind(r,this,t,i);for(const e of o.forcedBindableBlocks)e.bind(r,this,t,i);for(const e of o.inputBlocks)e._transmit(r,s,this)}else if(!this.isFrozen)for(const e of o.forcedBindableBlocks)e.bind(r,this,t,i);this._afterBind(t,this._activeEffect,i)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter((e=>e.texture)).map((e=>e.texture))),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)hh._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(const t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(const e of this.getTextureBlocks().filter((e=>e.texture)).map((e=>e.texture)))e.dispose();for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){const t={nodeMaterial:this,...e};this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise((t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),void 0===this.BJSNODEMATERIALEDITOR){const i=e&&e.editorURL?e.editorURL:hh.EditorURL;Ds.LoadBabylonScript(i,(()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(e?.nodeEditorConfig),t()}))}else this._createNodeEditor(e?.nodeEditorConfig),t()}))}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;const e=new Ol("Position");e.setAsAttribute("position");const t=new Ol("World");t.setAsSystemValue(_l.World);const i=new yl("WorldPos");e.connectTo(i),t.connectTo(i);const s=new Ol("ViewProjection");s.setAsSystemValue(_l.ViewProjection);const r=new yl("WorldPos * ViewProjectionTransform");i.connectTo(r),s.connectTo(r);const n=new Sl("VertexOutput");r.connectTo(n);const o=new Ol("color");o.value=new Ae(.8,.8,.8,1);const a=new El("FragmentOutput");o.connectTo(a),this.addOutputNode(n),this.addOutputNode(a),this._mode=Hl.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Ol("Position");e.setAsAttribute("position2d");const t=new Ol("Constant1");t.isConstant=!0,t.value=1;const i=new Ul("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new Sl("VertexOutput");i.connectTo(s);const r=new Ol("Scale");r.visibleInInspector=!0,r.value=new de(1,1);const n=new Gl("uv0");e.connectTo(n);const o=new Wl("UV scale");n.connectTo(o),r.connectTo(o);const a=new Dl("CurrentScreen");o.connectTo(a),a.texture=new Pa("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const l=new El("FragmentOutput");a.connectTo(l,{output:"rgba"}),this.addOutputNode(s),this.addOutputNode(l),this._mode=Hl.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Ol("Position");e.setAsAttribute("position2d");const t=new Ol("Constant1");t.isConstant=!0,t.value=1;const i=new Ul("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new Sl("VertexOutput");i.connectTo(s);const r=new Ol("Time");r.value=0,r.min=0,r.max=0,r.isBoolean=!1,r.matrixMode=0,r.animationType=pl.Time,r.isConstant=!1;const n=new Ol("Color3");n.value=new Ee(1,1,1),n.isConstant=!1;const o=new El("FragmentOutput"),a=new Ul("VectorMerger");a.visibleInInspector=!1;const l=new oh("Cos");l.operation=nh.Cos,e.connectTo(a),r.output.connectTo(l.input),l.output.connectTo(a.z),a.xyzOut.connectTo(o.rgb),this.addOutputNode(s),this.addOutputNode(o),this._mode=Hl.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Ol("uv");e.setAsAttribute("particle_uv");const t=new wl("ParticleTexture");e.connectTo(t);const i=new Ol("Color");i.setAsAttribute("particle_color");const s=new Wl("Texture * Color");t.connectTo(s),i.connectTo(s);const r=new Nl("ParticleRampGradient");s.connectTo(r);const n=new Ql("ColorSplitter");i.connectTo(n);const o=new Fl("ParticleBlendMultiply");r.connectTo(o),t.connectTo(o,{output:"a"}),n.connectTo(o,{output:"a"});const a=new El("FragmentOutput");o.connectTo(a),this.addOutputNode(a),this._mode=Hl.Particle}async loadAsync(e,t=""){return hh.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,t);const s=[];for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,s);let r=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}");\n`;r+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${Hl[this.mode]};\n`;for(const s of t)s.isInput&&-1===e.indexOf(s)&&(r+=s._dumpCode(i,e));for(const t of s)t.isInput&&-1===e.indexOf(t)&&(r+=t._dumpCode(i,e));e=[],r+="\n// Connections\n";for(const t of this._vertexOutputNodes)r+=t._dumpCodeForOutputConnections(e);for(const t of this._fragmentOutputNodes)r+=t._dumpCodeForOutputConnections(e);r+="\n// Output nodes\n";for(const e of this._vertexOutputNodes)r+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;for(const e of this._fragmentOutputNodes)r+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;return r+="nodeMaterial.build();\n",r}serialize(e){const t=e?{}:St.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{t.customType="BABYLON.NodeMaterial",t.outputNodes=[];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n)for(const o of r.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==s.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;s.connectTo(e,!0),this._restoreConnections(n,t,i)}}}parseSerializedObject(e,t="",i=!1,s){i||this.clear();const r={};for(const i of e.blocks){const e=W(i.customType);if(e){const n=new e;n._deserialize(i,this.getScene(),t,s),r[i.id]=n,this.attachedBlocks.push(n)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,i=t._tempEntryPointUniqueId;i&&r[i].attachToEndpoint(t)}for(let t=0;tnew hh(e,this.getScene(),this.options)),this);return s.id=e,s.name=e,s.parseSerializedObject(i),s._buildId=this._buildId,s.build(!1,!t),s}whenTexturesReadyAsync(){const e=[];return this.getActiveTextures().forEach((t=>{const i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise(((e,t)=>{i.onLoadedObservable.addOnce((()=>{e()})),i.onErrorObservable.addOnce((e=>{t(e)}))})))})),Promise.all(e)}static Parse(e,t,i="",s=di.GLSL){const r=St.Parse((()=>new hh(e.name,t,{shaderLanguage:s})),e,t,i);return r.parseSerializedObject(e,i),r.build(),r}static async ParseFromFileAsync(e,t,i,s="",r=!1,n,o){const a=n??new hh(e,i),l=await i._loadFileAsync(t),h=JSON.parse(l);return a.parseSerializedObject(h,s,void 0,o),r||a.build(),a}static ParseFromSnippetAsync(e,t=re.LastCreatedScene,i="",s,r=!1,n=!1,o){return"_BLANK"===e?Promise.resolve(hh.CreateDefault("blank",t)):new Promise(((a,l)=>{const h=new Pt;h.addEventListener("readystatechange",(()=>{if(4==h.readyState)if(200==h.status){const c=JSON.parse(JSON.parse(h.responseText).jsonPayload),u=JSON.parse(c.nodeMaterial);s||((s=St.Parse((()=>new hh(e,t)),u,t,i)).uniqueId=t.getUniqueId()),s.parseSerializedObject(u,void 0,void 0,o),s.snippetId=e;try{r||s.build()}catch(e){l(e)}n?s.whenTexturesReadyAsync().then((()=>{a(s)})).catch((e=>{l(e)})):a(s)}else l("Unable to load the snippet "+e)})),h.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),h.send()}))}static CreateDefault(e,t){const i=new hh(e,t);return i.setToDefault(),i.build(),i}}function ch(e){const t=e.sideOrientation||Wn.DEFAULTSIDE,i=e.radius||1,s=void 0===e.flat||e.flat,r=0|(e.subdivisions||4),n=e.radiusX||i,o=e.radiusY||i,a=e.radiusZ||i,l=(1+Math.sqrt(5))/2,h=[-1,l,-0,1,l,0,-1,-l,0,1,-l,0,0,-1,-l,0,1,-l,0,-1,l,0,1,l,l,0,1,l,0,-1,-l,0,1,-l,0,-1],c=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],u=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],d=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],_=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],p=[],f=[],m=[],g=[];let v=0;const x=new Array(3),b=new Array(3);let T;for(T=0;T<3;T++)x[T]=_e.Zero(),b[T]=de.Zero();for(let e=0;e<20;e++){for(T=0;T<3;T++){const t=c[3*e+T];x[T].copyFromFloats(h[3*u[t]],h[3*u[t]+1],h[3*u[t]+2]),x[T].normalize(),b[T].copyFromFloats(.134765625*d[2*t]+.05859375+-.0390625*_[e],.2333984375*d[2*t+1]+.025390625+.01953125*_[e])}const t=(e,t,i,l)=>{const h=_e.Lerp(x[0],x[2],t/r),c=_e.Lerp(x[1],x[2],t/r),u=r===t?x[2]:_e.Lerp(h,c,e/(r-t));let d;if(u.normalize(),s){const e=_e.Lerp(x[0],x[2],l/r),t=_e.Lerp(x[1],x[2],l/r);d=_e.Lerp(e,t,i/(r-l))}else d=new _e(u.x,u.y,u.z);d.x/=n,d.y/=o,d.z/=a,d.normalize();const _=de.Lerp(b[0],b[2],t/r),T=de.Lerp(b[1],b[2],t/r),y=r===t?b[2]:de.Lerp(_,T,e/(r-t));f.push(u.x*n,u.y*o,u.z*a),m.push(d.x,d.y,d.z),g.push(y.x,Xn.UseOpenGLOrientationForUV?1-y.y:y.y),p.push(v),v++};for(let e=0;euh(e,t,i),function(e){e.WRIST="wrist",e.THUMB="thumb",e.INDEX="index",e.MIDDLE="middle",e.RING="ring",e.LITTLE="little"}(_h||(_h={})),function(e){e.WRIST="wrist",e.THUMB_METACARPAL="thumb-metacarpal",e.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",e.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",e.THUMB_TIP="thumb-tip",e.INDEX_FINGER_METACARPAL="index-finger-metacarpal",e.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",e.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",e.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",e.INDEX_FINGER_TIP="index-finger-tip",e.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",e.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",e.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",e.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",e.MIDDLE_FINGER_TIP="middle-finger-tip",e.RING_FINGER_METACARPAL="ring-finger-metacarpal",e.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",e.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",e.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",e.RING_FINGER_TIP="ring-finger-tip",e.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",e.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",e.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",e.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",e.PINKY_FINGER_TIP="pinky-finger-tip"}(ph||(ph={}));const fh=[ph.WRIST,ph.THUMB_METACARPAL,ph.THUMB_PHALANX_PROXIMAL,ph.THUMB_PHALANX_DISTAL,ph.THUMB_TIP,ph.INDEX_FINGER_METACARPAL,ph.INDEX_FINGER_PHALANX_PROXIMAL,ph.INDEX_FINGER_PHALANX_INTERMEDIATE,ph.INDEX_FINGER_PHALANX_DISTAL,ph.INDEX_FINGER_TIP,ph.MIDDLE_FINGER_METACARPAL,ph.MIDDLE_FINGER_PHALANX_PROXIMAL,ph.MIDDLE_FINGER_PHALANX_INTERMEDIATE,ph.MIDDLE_FINGER_PHALANX_DISTAL,ph.MIDDLE_FINGER_TIP,ph.RING_FINGER_METACARPAL,ph.RING_FINGER_PHALANX_PROXIMAL,ph.RING_FINGER_PHALANX_INTERMEDIATE,ph.RING_FINGER_PHALANX_DISTAL,ph.RING_FINGER_TIP,ph.PINKY_FINGER_METACARPAL,ph.PINKY_FINGER_PHALANX_PROXIMAL,ph.PINKY_FINGER_PHALANX_INTERMEDIATE,ph.PINKY_FINGER_PHALANX_DISTAL,ph.PINKY_FINGER_TIP],mh={[_h.WRIST]:[ph.WRIST],[_h.THUMB]:[ph.THUMB_METACARPAL,ph.THUMB_PHALANX_PROXIMAL,ph.THUMB_PHALANX_DISTAL,ph.THUMB_TIP],[_h.INDEX]:[ph.INDEX_FINGER_METACARPAL,ph.INDEX_FINGER_PHALANX_PROXIMAL,ph.INDEX_FINGER_PHALANX_INTERMEDIATE,ph.INDEX_FINGER_PHALANX_DISTAL,ph.INDEX_FINGER_TIP],[_h.MIDDLE]:[ph.MIDDLE_FINGER_METACARPAL,ph.MIDDLE_FINGER_PHALANX_PROXIMAL,ph.MIDDLE_FINGER_PHALANX_INTERMEDIATE,ph.MIDDLE_FINGER_PHALANX_DISTAL,ph.MIDDLE_FINGER_TIP],[_h.RING]:[ph.RING_FINGER_METACARPAL,ph.RING_FINGER_PHALANX_PROXIMAL,ph.RING_FINGER_PHALANX_INTERMEDIATE,ph.RING_FINGER_PHALANX_DISTAL,ph.RING_FINGER_TIP],[_h.LITTLE]:[ph.PINKY_FINGER_METACARPAL,ph.PINKY_FINGER_PHALANX_PROXIMAL,ph.PINKY_FINGER_PHALANX_INTERMEDIATE,ph.PINKY_FINGER_PHALANX_DISTAL,ph.PINKY_FINGER_TIP]};class gh{get handMesh(){return this._handMesh}getHandPartMeshes(e){return mh[e].map((e=>this._jointMeshes[fh.indexOf(e)]))}getJointMesh(e){return this._jointMeshes[fh.indexOf(e)]}constructor(e,t,i,s,r=!1,n=!1,o=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=s,this._leftHandedMeshes=r,this._jointsInvisible=n,this._jointScaleFactor=o,this.onHandMeshSetObservable=new K,this._jointTransforms=new Array(fh.length),this._jointTransformMatrices=new Float32Array(16*fh.length),this._tempJointMatrix=new me,this._jointRadii=new Float32Array(fh.length),this._scene=t[0].getScene();for(let e=0;e{e._doNotLoadControllerMesh=!0}))}setHandMesh(e,t,i){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach((e=>{e.alwaysSelectAsActiveMesh=!0})),this._handMesh.skeleton){const e=this._handMesh.skeleton;fh.forEach(((i,s)=>{const r=e.getBoneIndexByName(t?t[i]:i);-1!==r&&e.bones[r].linkTransformNode(this._jointTransforms[s])}))}this.onHandMeshSetObservable.notifyObservers(this)}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const s=i,r=fh.map((e=>s[e]||i.get(e)));let n=!1;if(e.fillPoses&&e.fillJointRadii)n=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){n=!0;for(let i=0;i{const i=this._jointTransforms[t];me.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);const s=this._jointRadii[t]*this._jointScaleFactor,r=this._jointMeshes[t];r.isVisible=!this._handMesh&&!this._jointsInvisible,r.position.copyFrom(i.position),r.rotationQuaternion.copyFrom(i.rotationQuaternion),r.scaling.setAll(s),this._scene.useRightHandedSystem||(r.position.z*=-1,r.rotationQuaternion.z*=-1,r.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))})),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(e=!1){this._handMesh&&(e?(this._handMesh.skeleton?.dispose(),this._handMesh.dispose(!1,!0)):this._handMesh.isVisible=!1)}}class vh extends Ja{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map((i=>{const s=[],r=e.jointMeshes?.sourceMesh||uh("jointParent",vh._ICOSPHERE_PARAMS);r.isVisible=!!e.jointMeshes?.keepOriginalVisible;for(let t=0;t{const r={};vh._RightHandGLB?.meshes[1]?.isDisposed()&&(vh._RightHandGLB=null),vh._LeftHandGLB?.meshes[1]?.isDisposed()&&(vh._LeftHandGLB=null);const n=!(!vh._RightHandGLB||!vh._LeftHandGLB),o=await Promise.all([vh._RightHandGLB||fl.ImportMeshAsync("",vh.DEFAULT_HAND_MODEL_BASE_URL,vh.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),vh._LeftHandGLB||fl.ImportMeshAsync("",vh.DEFAULT_HAND_MODEL_BASE_URL,vh.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);vh._RightHandGLB=o[0],vh._LeftHandGLB=o[1];const a=await hh.ParseFromFileAsync("handShader",vh.DEFAULT_HAND_MODEL_SHADER_URL,e);a.needDepthPrePass=!0,a.transparencyMode=ta.MATERIAL_ALPHABLEND,a.alphaMode=2,a.build(!1);const l={base:Ee.FromInts(116,63,203),fresnel:Ee.FromInts(149,102,229),fingerColor:Ee.FromInts(177,130,255),tipFresnel:Ee.FromInts(220,200,255),...i?.handMeshes?.customColors},h={base:a.getBlockByName("baseColor"),fresnel:a.getBlockByName("fresnelColor"),fingerColor:a.getBlockByName("fingerColor"),tipFresnel:a.getBlockByName("tipFresnelColor")};h.base.value=l.base,h.fresnel.value=l.fresnel,h.fingerColor.value=l.fingerColor,h.tipFresnel.value=l.tipFresnel;const c=t._getBaseLayerWrapper()?.isMultiview;["left","right"].forEach((t=>{const i="left"==t?vh._LeftHandGLB:vh._RightHandGLB;if(!i)throw new Error("Could not load hand model");const s=i.meshes[1];s._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,c||(s.material=a.clone(`${t}HandShaderClone`,!0)),s.isVisible=!1,r[t]=s,n||e.useRightHandedSystem||i.meshes[1].rotate(Xr.Y,Math.PI)})),a.dispose(),s({left:r.left,right:r.right})}))}static _GenerateDefaultHandMeshRigMapping(e){const t="right"==e?"R":"L";return{[ph.WRIST]:`wrist_${t}`,[ph.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[ph.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[ph.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[ph.THUMB_TIP]:`thumb_tip_${t}`,[ph.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[ph.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[ph.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[ph.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[ph.INDEX_FINGER_TIP]:`index_tip_${t}`,[ph.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[ph.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[ph.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[ph.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[ph.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[ph.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[ph.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[ph.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[ph.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[ph.RING_FINGER_TIP]:`ring_tip_${t}`,[ph.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[ph.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[ph.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[ph.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[ph.PINKY_FINGER_TIP]:`little_tip_${t}`}}isCompatible(){return"undefined"!=typeof XRHand}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return"none"==e?null:this._trackingHands[e]}constructor(e,t){super(e),this.options=t,this._attachedHands={},this._trackingHands={left:null,right:null},this._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},this._worldScaleObserver=null,this.onHandAddedObservable=new K,this.onHandRemovedObservable=new K,this._attachHand=e=>{if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;const t=e.inputSource.handedness,i=new gh(e,this._handResources.jointMeshes[t],this._handResources.handMeshes&&this._handResources.handMeshes[t],this._handResources.rigMappings&&this._handResources.rigMappings[t],this.options.handMeshes?.meshesUseLeftHandedCoordinates,this.options.jointMeshes?.invisible,this.options.jointMeshes?.scaleFactor);this._attachedHands[e.uniqueId]=i,this._trackingHands[t]=i,this.onHandAddedObservable.notifyObservers(i)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";const i=t.jointMeshes;if(i&&(void 0!==i.disableDefaultHandMesh&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=i.disableDefaultHandMesh),void 0!==i.handMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=i.handMeshes),void 0!==i.leftHandedSystemMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=i.leftHandedSystemMeshes),void 0!==i.rigMapping)){t.handMeshes=t.handMeshes||{};const e={},s={};[[i.rigMapping.left,e],[i.rigMapping.right,s]].forEach((e=>{const t=e[0],i=e[1];t.forEach(((e,t)=>{i[fh[t]]=e}))})),t.handMeshes.customRigMappings={left:e,right:s}}}attach(){return!!super.attach()&&(this._handResources={jointMeshes:vh._GenerateTrackedJointMeshes(this.options),handMeshes:this.options.handMeshes?.customMeshes||null,rigMappings:this.options.handMeshes?.customRigMappings||null},this.options.handMeshes?.customMeshes||this.options.handMeshes?.disableDefaultMeshes||(vh._GenerateDefaultHandMeshesAsync(re.LastCreatedScene,this._xrSessionManager,this.options).then((e=>{this._handResources.handMeshes=e,this._handResources.rigMappings={left:vh._GenerateDefaultHandMeshRigMapping("left"),right:vh._GenerateDefaultHandMeshRigMapping("right")},this._trackingHands.left?.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left,this._xrSessionManager),this._trackingHands.right?.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right,this._xrSessionManager),this._handResources.handMeshes.left.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._handResources.handMeshes.right.scaling.setAll(this._xrSessionManager.worldScalingFactor)})),this._worldScaleObserver=this._xrSessionManager.onWorldScaleFactorChangedObservable.add((e=>{this._handResources.handMeshes&&(this._handResources.handMeshes.left.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor),this._handResources.handMeshes.right.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor))}))),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0)}_onXRFrame(e){this._trackingHands.left?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),this._trackingHands.right?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e,t){const i=this.getHandByControllerId(e);if(i){const s="left"==i.xrController.inputSource.handedness?"left":"right";this._trackingHands[s]?.xrController.uniqueId===e&&(this._trackingHands[s]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(t),delete this._attachedHands[e]}}detach(){return!!super.detach()&&(Object.keys(this._attachedHands).forEach((e=>this._detachHandById(e,this.options.handMeshes?.disposeOnSessionEnd))),this.options.handMeshes?.disposeOnSessionEnd&&this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose()))),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver),!0)}dispose(){super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!this.options.handMeshes?.customMeshes&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),vh._RightHandGLB=null,vh._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose())))}}var xh,bh,Th;vh.Name=qa.HAND_TRACKING,vh.Version=1,vh.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",vh.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",vh.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",vh.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",vh._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},vh._RightHandGLB=null,vh._LeftHandGLB=null,Za.AddWebXRFeature(vh.Name,((e,t)=>()=>new vh(e,t)),vh.Version,!1),function(e){e[e.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",e[e.RADIAL_SIDE=1]="RADIAL_SIDE",e[e.ULNAR_SIDE=2]="ULNAR_SIDE",e[e.BELOW_WRIST=3]="BELOW_WRIST"}(xh||(xh={})),function(e){e[e.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",e[e.HAND_ROTATION=1]="HAND_ROTATION"}(bh||(bh={})),function(e){e[e.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",e[e.PALM_UP=1]="PALM_UP",e[e.GAZE_FOCUS=2]="GAZE_FOCUS",e[e.PALM_AND_GAZE=3]="PALM_AND_GAZE"}(Th||(Th={}));class yh{constructor(){this._sceneRenderObserver=null,this._zoneAxis={},this.handConstraintVisibility=Th.PALM_AND_GAZE,this.palmUpStrictness=.95,this.gazeProximityRadius=.15,this.targetOffset=.1,this.targetZone=xh.ULNAR_SIDE,this.zoneOrientationMode=bh.HAND_ROTATION,this.nodeOrientationMode=bh.HAND_ROTATION,this.handedness="none",this.lerpTime=100,this._zoneAxis[xh.ABOVE_FINGER_TIPS]=new _e(0,1,0),this._zoneAxis[xh.RADIAL_SIDE]=new _e(-1,0,0),this._zoneAxis[xh.ULNAR_SIDE]=new _e(1,0,0),this._zoneAxis[xh.BELOW_WRIST]=new _e(0,-1,0)}get name(){return"HandConstraint"}enable(){this._node.setEnabled(!0)}disable(){this._node.setEnabled(!1)}_getHandPose(){if(!this._handTracking)return null;let e;if(e="none"===this.handedness?this._handTracking.getHandByHandedness("left")||this._handTracking.getHandByHandedness("right"):this._handTracking.getHandByHandedness(this.handedness),e){const t=e.getJointMesh(ph.PINKY_FINGER_METACARPAL),i=e.getJointMesh(ph.MIDDLE_FINGER_METACARPAL),s=e.getJointMesh(ph.WRIST);if(s&&i&&t){const r={position:i.absolutePosition,quaternion:new fe,id:e.xrController.uniqueId},n=ve.Vector3[0],o=ve.Vector3[1],a=ve.Vector3[2];return n.copyFrom(i.absolutePosition).subtractInPlace(s.absolutePosition).normalize(),o.copyFrom(t.absolutePosition).subtractInPlace(i.absolutePosition).normalize(),_e.CrossToRef(n,o,o),_e.CrossToRef(o,n,a),fe.FromLookDirectionLHToRef(o,n,r.quaternion),r}}return null}init(){}attach(e){this._node=e,this._scene=e.getScene(),this._node.rotationQuaternion||(this._node.rotationQuaternion=fe.RotationYawPitchRoll(this._node.rotation.y,this._node.rotation.x,this._node.rotation.z));let t=Date.now();this._sceneRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{const e=this._getHandPose();if(this._node.reservedDataStore=this._node.reservedDataStore||{},this._node.reservedDataStore.nearInteraction=this._node.reservedDataStore.nearInteraction||{},this._node.reservedDataStore.nearInteraction.excludedControllerId=null,e){const i=ve.Vector3[0],s=this._scene.activeCamera;i.copyFrom(this._zoneAxis[this.targetZone]);const r=ve.Quaternion[0];if(s&&(this.zoneOrientationMode===bh.LOOK_AT_CAMERA||this.nodeOrientationMode===bh.LOOK_AT_CAMERA)){const t=ve.Vector3[1];t.copyFrom(s.position).subtractInPlace(e.position).normalize(),this._scene.useRightHandedSystem?fe.FromLookDirectionRHToRef(t,_e.UpReadOnly,r):fe.FromLookDirectionLHToRef(t,_e.UpReadOnly,r)}this.zoneOrientationMode===bh.HAND_ROTATION?e.quaternion.toRotationMatrix(ve.Matrix[0]):r.toRotationMatrix(ve.Matrix[0]),_e.TransformNormalToRef(i,ve.Matrix[0],i),i.scaleInPlace(this.targetOffset);const n=ve.Vector3[2],o=ve.Quaternion[1];n.copyFrom(e.position).addInPlace(i),this.nodeOrientationMode===bh.HAND_ROTATION?o.copyFrom(e.quaternion):o.copyFrom(r);const a=Date.now()-t;_e.SmoothToRef(this._node.position,n,a,this.lerpTime,this._node.position),fe.SmoothToRef(this._node.rotationQuaternion,o,a,this.lerpTime,this._node.rotationQuaternion),this._node.reservedDataStore.nearInteraction.excludedControllerId=e.id}this._setVisibility(e),t=Date.now()}))}_setVisibility(e){let t=!0,i=!0;const s=this._scene.activeCamera;if(s){const r=s.getForwardRay();if(this.handConstraintVisibility===Th.GAZE_FOCUS||this.handConstraintVisibility===Th.PALM_AND_GAZE){let t;i=!1,this._eyeTracking&&(t=this._eyeTracking.getEyeGaze()),t=t||r;const s=ve.Vector3[0];e?e.position.subtractToRef(t.origin,s):this._node.getAbsolutePosition().subtractToRef(t.origin,s);const n=_e.Dot(s,t.direction),o=n*n;n>0&&s.lengthSquared()-o2*this.palmUpStrictness-1&&(t=!0)}}this._node.setEnabled(t&&i)}detach(){this._scene.onBeforeRenderObservable.remove(this._sceneRenderObserver)}linkToXRExperience(e){const t=e.featuresManager?e.featuresManager:e;if(t){try{this._eyeTracking=t.getEnabledFeature(qa.EYE_TRACKING)}catch{}try{this._handTracking=t.getEnabledFeature(qa.HAND_TRACKING)}catch{Ds.Error("Hand tracking must be enabled for the Hand Menu to work")}}else Ds.Error("XR features manager must be available or provided directly for the Hand Menu to work")}}class Sh{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=_e.Zero(),this.poleTargetPosition=_e.Zero(),this.poleTargetLocalOffset=_e.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=fe.Identity(),this._bone1Mat=me.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=_e.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;const s=t.getParent();if(!s)return this._notEnoughInformation=!0,void Ne.Error("BoneIKController: bone must have a parent for IK to work.");if(this._bone1=s,0===this._bone2.children.length&&!this._bone2.length)return this._notEnoughInformation=!0,void Ne.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();const r=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,r.x>r.y&&r.x>r.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){const e=this._bone1.getScale(),t=this._bone2.getScale();this._bone1Length=this._bone1.length*e.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);const t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),s=this._bone1.getAbsolutePosition(e);this._bone2Length=_e.Distance(t,i),this._bone1Length=_e.Distance(i,s)}else{e.computeWorldMatrix(!0);const t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;const i=this._bone2.getAbsolutePosition(e),s=this._bone1.getAbsolutePosition(e);this._bone1Length=_e.Distance(i,s)}this._bone1.getRotationMatrixToRef(Ur.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||null==e)&&(e=Math.PI),this._maxAngle=e;const t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;const e=this.targetPosition,t=this.poleTargetPosition,i=Sh._TmpMats[0],s=Sh._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&_e.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);const r=Sh._TmpVecs[0],n=Sh._TmpVecs[1],o=Sh._TmpVecs[2],a=Sh._TmpVecs[3],l=Sh._TmpVecs[4],h=Sh._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,r),t.subtractToRef(r,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),e.subtractToRef(r,a),a.normalize(),_e.CrossToRef(a,l,n),n.normalize(),_e.CrossToRef(a,n,o),o.normalize(),me.FromXYZAxesToRef(o,a,n,i);const c=this._bone1Length,u=this._bone2Length;let d=_e.Distance(r,e);this._maxReach>0&&(d=Math.min(this._maxReach,d));let _=(u*u+d*d-c*c)/(2*u*d),p=(d*d+c*c-u*u)/(2*d*c);_>1&&(_=1),p>1&&(p=1),_<-1&&(_=-1),p<-1&&(p=-1);const f=Math.acos(_),m=Math.acos(p);let g=-f-m;if(this._rightHandedSystem)me.RotationYawPitchRollToRef(0,0,this._adjustRoll,s),s.multiplyToRef(i,i),me.RotationAxisToRef(this._bendAxis,m,s),s.multiplyToRef(i,i);else{const e=Sh._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,me.RotationAxisToRef(e,-m,s),s.multiplyToRef(i,i)}this.poleAngle&&(me.RotationAxisToRef(a,this.poleAngle,s),i.multiplyToRef(s,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||fe.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),fe.FromRotationMatrixToRef(i,h),fe.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),g=this._bone2Ang*(1-this.slerpAmount)+g*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,Ur.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,Ur.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,g,Ur.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=g}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new fe),e.getRotationQuaternionToRef(Ur.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}Sh._TmpVecs=[_e.Zero(),_e.Zero(),_e.Zero(),_e.Zero(),_e.Zero(),_e.Zero()],Sh._TmpQuat=fe.Identity(),Sh._TmpMats=[me.Identity(),me.Identity()];class Ch{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,s){if(this.upAxis=_e.Up(),this.upAxisSpace=Ur.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=fe.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=_e.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,s){if(s.adjustYaw&&(this.adjustYaw=s.adjustYaw),s.adjustPitch&&(this.adjustPitch=s.adjustPitch),s.adjustRoll&&(this.adjustRoll=s.adjustRoll),null!=s.maxYaw?this.maxYaw=s.maxYaw:this.maxYaw=Math.PI,null!=s.minYaw?this.minYaw=s.minYaw:this.minYaw=-Math.PI,null!=s.maxPitch?this.maxPitch=s.maxPitch:this.maxPitch=Math.PI,null!=s.minPitch?this.minPitch=s.minPitch:this.minPitch=-Math.PI,null!=s.slerpAmount&&(this.slerpAmount=s.slerpAmount),null!=s.upAxis&&(this.upAxis=s.upAxis),null!=s.upAxisSpace&&(this.upAxisSpace=s.upAxisSpace),null!=s.yawAxis||null!=s.pitchAxis){let e=Xr.Y,t=Xr.X;null!=s.yawAxis&&(e=s.yawAxis.clone(),e.normalize()),null!=s.pitchAxis&&(t=s.pitchAxis.clone(),t.normalize());const i=_e.Cross(t,e);this._transformYawPitch=me.Identity(),me.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==s.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=s.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=Ur.BONE||(this.upAxisSpace=Ur.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped)return void(this._firstFrameSkipped=!0);const e=this.bone,t=Ch._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target;const s=Ch._TmpMats[0],r=Ch._TmpMats[1],n=this.mesh,o=e.getParent(),a=Ch._TmpVecs[1];a.copyFrom(this.upAxis),this.upAxisSpace==Ur.BONE&&o?(this._transformYawPitch&&_e.TransformCoordinatesToRef(a,this._transformYawPitchInv,a),o.getDirectionToRef(a,this.mesh,a)):this.upAxisSpace==Ur.LOCAL&&(n.getDirectionToRef(a,a),1==n.scaling.x&&1==n.scaling.y&&1==n.scaling.z||a.normalize());let l=!1,h=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(l=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(h=!0),l||h){const e=Ch._TmpMats[2],s=Ch._TmpMats[3];if(this.upAxisSpace==Ur.BONE&&1==a.y&&o)o.getRotationMatrixToRef(Ur.WORLD,this.mesh,e);else if(this.upAxisSpace!=Ur.LOCAL||1!=a.y||o){let t=Ch._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&_e.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),o?o.getDirectionToRef(t,this.mesh,t):n.getDirectionToRef(t,t);const i=_e.Cross(a,t);i.normalize(),t=_e.Cross(i,a),me.FromXYZAxesToRef(i,a,t,e)}else e.copyFrom(n.getWorldMatrix());e.invertToRef(s);let r=null;if(h){const n=Ch._TmpVecs[3];i.subtractToRef(t,n),_e.TransformCoordinatesToRef(n,s,n),r=Math.sqrt(n.x*n.x+n.z*n.z);const o=Math.atan2(n.y,r);let a=o;o>this._maxPitch?(n.y=this._maxPitchTan*r,a=this._maxPitch):othis._maxYaw||aMath.PI?this._isAngleBetween(o,this._maxYaw,this._midYawConstraint)?(n.z=this._maxYawCos*r,n.x=this._maxYawSin*r,l=this._maxYaw):this._isAngleBetween(o,this._midYawConstraint,this._minYaw)&&(n.z=this._minYawCos*r,n.x=this._minYawSin*r,l=this._minYaw):a>this._maxYaw?(n.z=this._maxYawCos*r,n.x=this._maxYawSin*r,o<0&&this.useAbsoluteValueForYaw&&(n.x*=-1),l=this._maxYaw):aMath.PI){const e=Ch._TmpVecs[8];e.copyFrom(Xr.Z),this._transformYawPitch&&_e.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);const t=Ch._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),_e.TransformCoordinatesToRef(e,t,e),_e.TransformCoordinatesToRef(e,s,e);const i=Math.atan2(e.x,e.z);if(this._getAngleBetween(i,o)>this._getAngleBetween(i,this._midYawConstraint)){null==r&&(r=Math.sqrt(n.x*n.x+n.z*n.z));const e=this._getAngleBetween(i,this._maxYaw);this._getAngleBetween(i,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){let i=0;return i=(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)<(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)?t-e:e-t,i>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e=(e%=2*Math.PI)<0?e+2*Math.PI:e,(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)<(i=(i%=2*Math.PI)<0?i+2*Math.PI:i)){if(e>t&&ei&&e{const e=new Uint8Array(4);return!!((new Uint32Array(e.buffer)[0]=1)&e[0])})();Object.defineProperty(er.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0}),Object.defineProperty(er.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0}),Object.defineProperty(er.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0}),er.prototype._rebuild=function(){this._buffer?._rebuild(),this._alignedBuffer?._rebuild()},er.prototype.dispose=function(){this._ownsBuffer&&this._buffer.dispose(),this._alignedBuffer?.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0},er.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer},er.prototype._alignBuffer=function(){const e=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes||this.byteStride%4==0&&this.byteOffset%4==0||!e)return;const t=er.GetTypeByteLength(this.type),i=this.byteStride+3&-4,s=i/t,r=this._maxVerticesCount,n=r*i/t;let o,a;if(Array.isArray(e)){const t=new Float32Array(e);o=new DataView(t.buffer,t.byteOffset,t.byteLength)}else o=e instanceof ArrayBuffer?new DataView(e,0,e.byteLength):new DataView(e.buffer,e.byteOffset,e.byteLength);a=this.type===er.BYTE?new Int8Array(n):this.type===er.UNSIGNED_BYTE?new Uint8Array(n):this.type===er.SHORT?new Int16Array(n):this.type===er.UNSIGNED_SHORT?new Uint16Array(n):this.type===er.INT?new Int32Array(n):this.type===er.UNSIGNED_INT?new Uint32Array(n):new Float32Array(n);const l=this.getSize();let h=this.byteOffset;for(let e=0;e{if(t.type!==lr.POINTERWHEEL)return;const i=t.event,s=i.deltaMode===Sr.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*s*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*s*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*s*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,lr.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}Ze([rt()],Ph.prototype,"wheelPrecisionX",void 0),Ze([rt()],Ph.prototype,"wheelPrecisionY",void 0),Ze([rt()],Ph.prototype,"wheelPrecisionZ",void 0);class Ih{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let s=0,r=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=n=>{const o=n.event,a="touch"===o.pointerType;if(n.type!==lr.POINTERMOVE&&-1===this.buttons.indexOf(o.button))return;const l=o.target;if(this._altKey=o.altKey,this._ctrlKey=o.ctrlKey,this._metaKey=o.metaKey,this._shiftKey=o.shiftKey,this._buttonsPressed=o.buttons,t.isPointerLock){const e=o.movementX,t=o.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(n.type!==lr.POINTERDOWN&&n.type!==lr.POINTERDOUBLETAP&&a&&this._pointA?.pointerId!==o.pointerId&&this._pointB?.pointerId!==o.pointerId)return;if(n.type!==lr.POINTERDOWN||-1!==this._currentActiveButton&&!a)if(n.type===lr.POINTERDOUBLETAP)this.onDoubleTap(o.pointerType);else if(n.type!==lr.POINTERUP||this._currentActiveButton!==o.button&&!a){if(n.type===lr.POINTERMOVE)if(e||o.preventDefault(),this._pointA&&null===this._pointB){const e=o.clientX-this._pointA.x,t=o.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=o.clientX,this._pointA.y=o.clientY}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===o.pointerId?this._pointA:this._pointB;e.x=o.clientX,e.y=o.clientY;const t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,a=t*t+i*i,l={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:o.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,s,a,r,l),r=l,s=a}}else{try{l?.releasePointerCapture(o.pointerId)}catch(e){}a||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==o.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==o.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==s||r)&&(this.onMultiTouch(this._pointA,this._pointB,s,0,r,null),s=0,r=null),this._currentActiveButton=-1,this.onButtonUp(o),e||o.preventDefault()}else{try{l?.setPointerCapture(o.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType};else{if(null!==this._pointB)return;this._pointB={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType}}-1!==this._currentActiveButton||a||(this._currentActiveButton=o.button),this.onButtonDown(o),e||(o.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,lr.POINTERDOWN|lr.POINTERUP|lr.POINTERMOVE|lr.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,r=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&Ds.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Ds.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,s,r,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}Ze([rt()],Ih.prototype,"buttons",void 0);var Rh,Mh,Oh,Dh,wh,Nh,Fh={};class Lh{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();this.attached[t]?Ne.Warn("camera input of type "+t+" already exists on camera"):(this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault))}remove(e){for(const t in this.attached){const i=this.attached[t];if(i===e)return i.detachControl(),i.camera=null,delete this.attached[t],void this.rebuildInputCheck()}}removeByType(e){for(const t in this.attached){const i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){const t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=!In.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e;for(const t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(const t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(const e in this.attached){const t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){const t={};for(const e in this.attached){const i=this.attached[e],s=St.Serialize(i);t[i.getClassName()]=s}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=Fh[e];if(i){const s=t[e],r=St.Parse((()=>new i),s,null);this.add(r)}}}else for(const t in this.attached){const i=Fh[this.attached[t].getClassName()];if(i){const s=St.Parse((()=>new i),e,null);this.remove(this.attached[t]),this.add(s)}}}}class Bh{constructor(e,t){this.x=e,this.y=t}}class kh{get isConnected(){return this._isConnected}constructor(e,t,i,s=0,r=1,n=2,o=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=kh.GAMEPAD,this._leftStickAxisX=s,this._leftStickAxisY=r,this._rightStickAxisX=n,this._rightStickAxisY=o,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}}kh.GAMEPAD=0,kh.GENERIC=1,kh.XBOX=2,kh.POSE_ENABLED=3,kh.DUALSHOCK=4;class Vh extends kh{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new K,this.onButtonUpObservable=new K,this.type=kh.GENERIC,this._buttons=new Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{e.type!==kh.POSE_ENABLED&&(this.gamepad&&e.type!==kh.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(kh.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){const e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){const i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){const i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}const i=this.gamepad.leftStick;if(i&&0!=i.y){const e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}Ze([rt()],Uh.prototype,"gamepadRotationSensibility",void 0),Ze([rt()],Uh.prototype,"gamepadMoveSensibility",void 0),Fh.ArcRotateCameraGamepadInput=Uh;class Gh{constructor(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===dr.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t0?s/(1+this.wheelDeltaPercentage):s*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==lr.POINTERWHEEL)return;const i=t.event;let s=0;const r=i.deltaMode===Sr.DOM_DELTA_LINE?40:1,n=-i.deltaY*r;if(this.customComputeDeltaFromMouseWheel)s=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if(s=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius),s>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+s;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=be.Clamp(e,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else s=n/(40*this.wheelPrecision);s&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(s)):this.camera.inertialRadiusOffset+=s),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,lr.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}checkInputs(){if(!this.zoomToMouseLocation)return;const e=this.camera;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){const e=this.camera,t=e.target.subtract(e.position);this._hitPlane=Nr.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,me.Identity(),e,!1);0===e.targetScreenOffset.x&&0===e.targetScreenOffset.y||(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=_e.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(s))}_zoomToMouse(e){const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const s=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/is&&(e=(t.radius-s)*i-t.inertialRadiusOffset)}const s=e/i/t.radius,r=this._getPosition(),n=ve.Vector3[6];r.subtractToRef(t.target,n),n.scaleInPlace(s),n.scaleInPlace(i),this._inertialPanning.addInPlace(n),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,s),this._isPinching=!0):this._computeMultiTouchPanning(r,n)):this.multiTouchPanning?this._computeMultiTouchPanning(r,n):this.pinchZoom&&this._computePinchZoom(i,s))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}Wh.MinimumRadiusForPinch=.001,Ze([rt()],Wh.prototype,"buttons",void 0),Ze([rt()],Wh.prototype,"angularSensibilityX",void 0),Ze([rt()],Wh.prototype,"angularSensibilityY",void 0),Ze([rt()],Wh.prototype,"pinchPrecision",void 0),Ze([rt()],Wh.prototype,"pinchDeltaPercentage",void 0),Ze([rt()],Wh.prototype,"useNaturalPinchZoom",void 0),Ze([rt()],Wh.prototype,"pinchZoom",void 0),Ze([rt()],Wh.prototype,"panningSensibility",void 0),Ze([rt()],Wh.prototype,"multiTouchPanning",void 0),Ze([rt()],Wh.prototype,"multiTouchPanAndZoom",void 0),Fh.ArcRotateCameraPointersInput=Wh;class Hh extends Lh{constructor(e){super(e)}addMouseWheel(){return this.add(new zh),this}addPointers(){return this.add(new Wh),this}addKeyboard(){return this.add(new Gh),this}}Hh.prototype.addVRDeviceOrientation=function(){return this.add(new Xh),this};class Xh{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=e=>this._onOrientationEvent(e)}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);const t=this.camera.getScene().getEngine().getHostWindow();t&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t.addEventListener("deviceorientation",this._deviceOrientationHandler):Ds.Warn("Permission not granted.")})).catch((e=>{Ds.Error(e)})):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*this.gammaCorrection),this._dirty=!0}checkInputs(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)}detachControl(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)}getClassName(){return"ArcRotateCameraVRDeviceOrientationInput"}getSimpleName(){return"VRDeviceOrientation"}}Fh.ArcRotateCameraVRDeviceOrientationInput=Xh;class Yh{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=new Array}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(t.type===dr.KEYDOWN)-1===this.keysForward.indexOf(i.keyCode)&&-1===this.keysBackward.indexOf(i.keyCode)&&-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{this._pointerInput(e)}),lr.POINTERDOWN|lr.POINTERUP|lr.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add((()=>{this.camera.rollCorrect&&this.camera.restoreRoll(this.camera.rollCorrect)}))}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)}getClassName(){return"FlyCameraMouseInput"}getSimpleName(){return"mouse"}_pointerInput(e){const t=e.event,i=this.camera.getEngine();if(!this.touchEnabled&&"touch"===t.pointerType)return;if(e.type!==lr.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;const s=t.target;if(e.type===lr.POINTERDOWN){try{s?.setPointerCapture(t.pointerId)}catch(t){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),i.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===lr.POINTERUP){try{s?.releasePointerCapture(t.pointerId)}catch(t){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===lr.POINTERMOVE){if(!this._previousPosition)return void(i.isPointerLock&&this._onMouseMove(e.event));const s=t.clientX-this._previousPosition.x,r=t.clientY-this._previousPosition.y;this._rotateCamera(s,r),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){if(!this.camera.getEngine().isPointerLock)return;const t=e.movementX,i=e.movementY;this._rotateCamera(t,i),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera,s=(e*=i._calculateHandednessMultiplier())/this.angularSensibility,r=t/this.angularSensibility,n=fe.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let o;if(this.buttonsPitch.some((e=>e===this.activeButton))&&(o=fe.RotationAxis(Xr.X,r),n.multiplyInPlace(o)),this.buttonsYaw.some((e=>e===this.activeButton))){o=fe.RotationAxis(Xr.Y,s),n.multiplyInPlace(o);const e=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-ee===this.activeButton))&&(o=fe.RotationAxis(Xr.Z,-s),i._trackRoll-=s,n.multiplyInPlace(o)),n.toEulerAnglesToRef(i.rotation)}}Ze([rt()],Qh.prototype,"buttons",void 0),Ze([rt()],Qh.prototype,"angularSensibility",void 0),Fh.FlyCameraMouseInput=Qh;class jh{constructor(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=new Array}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===dr.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){this._onKeyboardObserver&&this._keys.forEach((e=>{-1!==this.keysHeightOffsetIncr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:-1!==this.keysHeightOffsetDecr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:-1!==this.keysRotationOffsetIncr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRotationOffsetDecr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRadiusIncr.indexOf(e)&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:-1!==this.keysRadiusDecr.indexOf(e)&&this._modifierRadius()&&(this.camera.radius-=this.radiusSensibility)}))}getClassName(){return"FollowCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}_modifierHeightOffset(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed}_modifierRotationOffset(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed}_modifierRadius(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed}}Ze([rt()],jh.prototype,"keysHeightOffsetIncr",void 0),Ze([rt()],jh.prototype,"keysHeightOffsetDecr",void 0),Ze([rt()],jh.prototype,"keysHeightOffsetModifierAlt",void 0),Ze([rt()],jh.prototype,"keysHeightOffsetModifierCtrl",void 0),Ze([rt()],jh.prototype,"keysHeightOffsetModifierShift",void 0),Ze([rt()],jh.prototype,"keysRotationOffsetIncr",void 0),Ze([rt()],jh.prototype,"keysRotationOffsetDecr",void 0),Ze([rt()],jh.prototype,"keysRotationOffsetModifierAlt",void 0),Ze([rt()],jh.prototype,"keysRotationOffsetModifierCtrl",void 0),Ze([rt()],jh.prototype,"keysRotationOffsetModifierShift",void 0),Ze([rt()],jh.prototype,"keysRadiusIncr",void 0),Ze([rt()],jh.prototype,"keysRadiusDecr",void 0),Ze([rt()],jh.prototype,"keysRadiusModifierAlt",void 0),Ze([rt()],jh.prototype,"keysRadiusModifierCtrl",void 0),Ze([rt()],jh.prototype,"keysRadiusModifierShift",void 0),Ze([rt()],jh.prototype,"heightSensibility",void 0),Ze([rt()],jh.prototype,"rotationSensibility",void 0),Ze([rt()],jh.prototype,"radiusSensibility",void 0),Fh.FollowCameraKeyboardMoveInput=jh;class Kh{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==lr.POINTERWHEEL)return;const i=t.event;let s=0;const r=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(+this.axisControlRadius+ +this.axisControlHeight+ +this.axisControlRotation&&Ne.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?s=.01*r*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?s=.01*r*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(s=.01*r*this.wheelDeltaPercentage*this.camera.rotationOffset)):s=r*this.wheelPrecision,s&&(this.axisControlRadius?this.camera.radius+=s:this.axisControlHeight?this.camera.heightOffset-=s:this.axisControlRotation&&(this.camera.rotationOffset-=s)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,lr.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}Ze([rt()],Kh.prototype,"axisControlRadius",void 0),Ze([rt()],Kh.prototype,"axisControlHeight",void 0),Ze([rt()],Kh.prototype,"axisControlRotation",void 0),Ze([rt()],Kh.prototype,"wheelPrecision",void 0),Ze([rt()],Kh.prototype,"wheelDeltaPercentage",void 0),Fh.FollowCameraMouseWheelInput=Kh;class $h extends Ih{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,s,r,n){if(0===i&&null===r)return;if(0===s&&null===n)return;let o=(s-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(o*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=o*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=o*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=o*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=o),this.axisPinchControlHeight&&(this.camera.heightOffset+=o),this.axisPinchControlRadius&&(this.camera.radius-=o))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;const e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";+this.axisXControlRotation+ +this.axisXControlHeight+ +this.axisXControlRadius<=1&&Ne.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&Ne.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&Ne.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}Ze([rt()],$h.prototype,"angularSensibilityX",void 0),Ze([rt()],$h.prototype,"angularSensibilityY",void 0),Ze([rt()],$h.prototype,"pinchPrecision",void 0),Ze([rt()],$h.prototype,"pinchDeltaPercentage",void 0),Ze([rt()],$h.prototype,"axisXControlRadius",void 0),Ze([rt()],$h.prototype,"axisXControlHeight",void 0),Ze([rt()],$h.prototype,"axisXControlRotation",void 0),Ze([rt()],$h.prototype,"axisYControlRadius",void 0),Ze([rt()],$h.prototype,"axisYControlHeight",void 0),Ze([rt()],$h.prototype,"axisYControlRotation",void 0),Ze([rt()],$h.prototype,"axisPinchControlRadius",void 0),Ze([rt()],$h.prototype,"axisPinchControlHeight",void 0),Ze([rt()],$h.prototype,"axisPinchControlRotation",void 0),Fh.FollowCameraPointersInput=$h;class qh{constructor(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===dr.KEYDOWN)-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)&&-1===this.keysUpward.indexOf(i.keyCode)&&-1===this.keysDownward.indexOf(i.keyCode)&&-1===this.keysRotateLeft.indexOf(i.keyCode)&&-1===this.keysRotateRight.indexOf(i.keyCode)&&-1===this.keysRotateUp.indexOf(i.keyCode)&&-1===this.keysRotateDown.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysUpward.indexOf(i.keyCode)||-1!==this.keysDownward.indexOf(i.keyCode)||-1!==this.keysRotateLeft.indexOf(i.keyCode)||-1!==this.keysRotateRight.indexOf(i.keyCode)||-1!==this.keysRotateUp.indexOf(i.keyCode)||-1!==this.keysRotateDown.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{const r=s.event,n="touch"===r.pointerType;if(!this.touchEnabled&&n)return;if(s.type!==lr.POINTERMOVE&&-1===this.buttons.indexOf(r.button))return;const o=r.target;if(s.type===lr.POINTERDOWN){if(n&&-1!==this._activePointerId||!n&&-1!==this._currentActiveButton)return;this._activePointerId=r.pointerId;try{o?.setPointerCapture(r.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=r.button),this._previousPosition={x:r.clientX,y:r.clientY},e||(r.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(s.event)}else if(s.type===lr.POINTERUP){if(n&&this._activePointerId!==r.pointerId||!n&&this._currentActiveButton!==r.button)return;try{o?.releasePointerCapture(r.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||r.preventDefault(),this._activePointerId=-1}else if(s.type===lr.POINTERMOVE&&(this._activePointerId===r.pointerId||!n))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(s.event);else if(this._previousPosition){const t=this.camera._calculateHandednessMultiplier(),i=(r.clientX-this._previousPosition.x)*t,s=r.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=s/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:s}),this._previousPosition={x:r.clientX,y:r.clientY},e||r.preventDefault()}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;const s=this.camera._calculateHandednessMultiplier(),r=i.movementX*s;this.camera.cameraRotation.y+=r/this.angularSensibility;const n=i.movementY;this.camera.cameraRotation.x+=n/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,lr.POINTERDOWN|lr.POINTERUP|lr.POINTERMOVE),i&&(this._contextMenuBind=e=>this.onContextMenu(e),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}Ze([rt()],Zh.prototype,"buttons",void 0),Ze([rt()],Zh.prototype,"angularSensibility",void 0),Fh.FreeCameraMouseInput=Zh,function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(Rh||(Rh={}));class Jh extends Ph{constructor(){super(...arguments),this._moveRelative=_e.Zero(),this._rotateRelative=_e.Zero(),this._moveScene=_e.Zero(),this._wheelXAction=Rh.MoveRelative,this._wheelXActionCoordinate=Gr.X,this._wheelYAction=Rh.MoveRelative,this._wheelYActionCoordinate=Gr.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){null===e&&this._wheelXAction!==Rh.MoveRelative||(this._wheelXAction=Rh.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Rh.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){null===e&&this._wheelYAction!==Rh.MoveRelative||(this._wheelYAction=Rh.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Rh.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){null===e&&this._wheelZAction!==Rh.MoveRelative||(this._wheelZAction=Rh.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Rh.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){null===e&&this._wheelXAction!==Rh.RotateRelative||(this._wheelXAction=Rh.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Rh.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){null===e&&this._wheelYAction!==Rh.RotateRelative||(this._wheelYAction=Rh.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Rh.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){null===e&&this._wheelZAction!==Rh.RotateRelative||(this._wheelZAction=Rh.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Rh.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){null===e&&this._wheelXAction!==Rh.MoveScene||(this._wheelXAction=Rh.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Rh.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){null===e&&this._wheelYAction!==Rh.MoveScene||(this._wheelYAction=Rh.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Rh.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){null===e&&this._wheelZAction!==Rh.MoveScene||(this._wheelZAction=Rh.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Rh.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(0===this._wheelDeltaX&&0===this._wheelDeltaY&&0==this._wheelDeltaZ)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);const e=me.Zero();this.camera.getViewMatrix().invertToRef(e);const t=_e.Zero();_e.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,i){if(0===e)return;if(null===t||null===i)return;let s=null;switch(t){case Rh.MoveRelative:s=this._moveRelative;break;case Rh.RotateRelative:s=this._rotateRelative;break;case Rh.MoveScene:s=this._moveScene}switch(i){case Gr.X:s.set(e,0,0);break;case Gr.Y:s.set(0,e,0);break;case Gr.Z:s.set(0,0,e)}}}Ze([rt()],Jh.prototype,"wheelXMoveRelative",null),Ze([rt()],Jh.prototype,"wheelYMoveRelative",null),Ze([rt()],Jh.prototype,"wheelZMoveRelative",null),Ze([rt()],Jh.prototype,"wheelXRotateRelative",null),Ze([rt()],Jh.prototype,"wheelYRotateRelative",null),Ze([rt()],Jh.prototype,"wheelZRotateRelative",null),Ze([rt()],Jh.prototype,"wheelXMoveScene",null),Ze([rt()],Jh.prototype,"wheelYMoveScene",null),Ze([rt()],Jh.prototype,"wheelZMoveScene",null),Fh.FreeCameraMouseWheelInput=Jh;class ec{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=Ds.IsSafari()}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const s=i.event,r="mouse"===s.pointerType||this._isSafari&&void 0===s.pointerType;if(this.allowMouse||!r)if(i.type===lr.POINTERDOWN){if(e||s.preventDefault(),this._pointerPressed.push(s.pointerId),1!==this._pointerPressed.length)return;t={x:s.clientX,y:s.clientY}}else if(i.type===lr.POINTERUP){e||s.preventDefault();const i=this._pointerPressed.indexOf(s.pointerId);if(-1===i)return;if(this._pointerPressed.splice(i,1),0!=i)return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===lr.POINTERMOVE){if(e||s.preventDefault(),!t)return;if(0!=this._pointerPressed.indexOf(s.pointerId))return;this._offsetX=s.clientX-t.x,this._offsetY=-(s.clientY-t.y)}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,lr.POINTERDOWN|lr.POINTERUP|lr.POINTERMOVE),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(null===this._offsetX||null===this._offsetY)return;if(0===this._offsetX&&0===this._offsetY)return;const e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility,this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{const t=e._computeLocalCameraSpeed(),i=new _e(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);me.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(_e.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}Ze([rt()],ec.prototype,"touchAngularSensibility",void 0),Ze([rt()],ec.prototype,"touchMoveSensibility",void 0),Fh.FreeCameraTouchInput=ec;class tc extends Lh{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new qh),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new Zh(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new Jh,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new ec),this}clear(){super.clear(),this._mouseInput=null}}tc.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new ic,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};class ic{static WaitForOrientationChangeAsync(e){return new Promise(((t,i)=>{let s=!1;const r=()=>{window.removeEventListener("deviceorientation",r),s=!0,t()};e&&setTimeout((()=>{s||(window.removeEventListener("deviceorientation",r),i("WaitForOrientationChangeAsync timed out"))}),e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"==e?window.addEventListener("deviceorientation",r):Ds.Warn("Permission not granted.")})).catch((e=>{Ds.Error(e)})):window.addEventListener("deviceorientation",r)}))}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new fe,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new K,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-Ds.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?Ds.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?Ds.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?Ds.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new fe(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new fe),this._camera&&this._camera.onDisposeObservable.add((()=>{this._onDeviceOrientationChangedObservable.clear()}))}attachControl(){const e=this.camera.getScene().getEngine().getHostWindow();if(e){const t=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t():Ds.Warn("Permission not granted.")})).catch((e=>{Ds.Error(e)})):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(fe.RotationYawPitchRollToRef(Ds.ToRadians(this._alpha),Ds.ToRadians(this._beta),-Ds.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}Fh.FreeCameraDeviceOrientationInput=ic;class sc{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=me.Identity(),this._deltaTransform=_e.Zero(),this._vector3=_e.Zero(),this._vector2=de.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{e.type!==kh.POSE_ENABLED&&(this.gamepad&&e.type!==kh.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(kh.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){const e=this.camera,t=this.gamepad.leftStick;0!==this.gamepadMoveSensibility&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&0!==this.gamepadAngularSensibility?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):me.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const s=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*s,0,-t.y*s),_e.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}}Ze([rt()],sc.prototype,"gamepadAngularSensibility",void 0),Ze([rt()],sc.prototype,"gamepadMoveSensibility",void 0),Fh.FreeCameraGamepadInput=sc,function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Mh||(Mh={}));class rc{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;const i={...rc._GetDefaultOptions(),...t};if(this._leftJoystick=!!e,rc._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=Mh.X,this._axisTargetedByUpAndDown=Mh.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new Bs,this.deltaPosition=_e.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{rc._VJCanvasWidth=window.innerWidth,rc._VJCanvasHeight=window.innerHeight,rc.Canvas&&(rc.Canvas.width=rc._VJCanvasWidth,rc.Canvas.height=rc._VJCanvasHeight),rc._HalfWidth=rc._VJCanvasWidth/2},!rc.Canvas){window.addEventListener("resize",this._onResize,!1),rc.Canvas=document.createElement("canvas"),rc._VJCanvasWidth=window.innerWidth,rc._VJCanvasHeight=window.innerHeight,rc.Canvas.width=window.innerWidth,rc.Canvas.height=window.innerHeight,rc.Canvas.style.width="100%",rc.Canvas.style.height="100%",rc.Canvas.style.position="absolute",rc.Canvas.style.backgroundColor="transparent",rc.Canvas.style.top="0px",rc.Canvas.style.left="0px",rc.Canvas.style.zIndex="5",rc.Canvas.style.touchAction="none",rc.Canvas.setAttribute("touch-action","none");const e=rc.Canvas.getContext("2d");if(!e)throw new Error("Unable to create canvas for virtual joystick");rc._VJCanvasContext=e,rc._VJCanvasContext.strokeStyle="#ffffff",rc._VJCanvasContext.lineWidth=2,document.body.appendChild(rc.Canvas)}rc._HalfWidth=rc.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&rc._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new de(0,0),this._joystickPreviousPointerPos=new de(0,0),this._joystickPointerStartPos=new de(0,0),this._deltaJoystickVector=new de(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},rc.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),rc.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),rc.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),rc.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),rc.Canvas.addEventListener("contextmenu",(e=>{e.preventDefault()}),!1),requestAnimationFrame((()=>{this._drawVirtualJoystick()}))}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){let t;e.preventDefault(),t=!0===this._leftJoystick?e.clientXrc._HalfWidth,t&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):rc._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){const t=new de(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0this._containerImage=t}setPuckImage(e){const t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){const e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?rc._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(rc._VJCanvasContext.beginPath(),rc._VJCanvasContext.strokeStyle=this._joystickColor,rc._VJCanvasContext.lineWidth=2,rc._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),rc._VJCanvasContext.stroke(),rc._VJCanvasContext.closePath(),rc._VJCanvasContext.beginPath(),rc._VJCanvasContext.lineWidth=6,rc._VJCanvasContext.strokeStyle=this._joystickColor,rc._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),rc._VJCanvasContext.stroke(),rc._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?rc._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(rc._VJCanvasContext.beginPath(),rc._VJCanvasContext.strokeStyle=this._joystickColor,rc._VJCanvasContext.lineWidth=2,rc._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),rc._VJCanvasContext.stroke(),rc._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach(((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(rc._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),rc._VJCanvasContext.beginPath(),rc._VJCanvasContext.fillStyle="white",rc._VJCanvasContext.beginPath(),rc._VJCanvasContext.strokeStyle="red",rc._VJCanvasContext.lineWidth=6,rc._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),rc._VJCanvasContext.stroke(),rc._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)})),requestAnimationFrame((()=>{this._drawVirtualJoystick()})))}releaseCanvas(){rc.Canvas&&(rc.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),rc.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),rc.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),rc.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(rc.Canvas),rc.Canvas=null),this._released=!0}}rc._GlobalJoystickIndex=0,rc._AlwaysVisibleSticks=0,tc.prototype.addVirtualJoystick=function(){return this.add(new nc),this};class nc{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=50*e._computeLocalCameraSpeed(),i=me.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),s=_e.TransformCoordinates(new _e(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(s),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new rc(!0),this._leftjoystick.setAxisForUpDown(Mh.Z),this._leftjoystick.setAxisForLeftRight(Mh.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new rc(!1),this._rightjoystick.setAxisForUpDown(Mh.X),this._rightjoystick.setAxisForLeftRight(Mh.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}}Fh.FreeCameraVirtualJoystickInput=nc,Et.AddNodeConstructor("TargetCamera",((e,t)=>()=>new oc(e,_e.Zero(),t)));class oc extends In{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=_e.Zero(),this._tmpTargetVector=_e.Zero(),this.cameraDirection=new _e(0,0,0),this.cameraRotation=new de(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new fe,this.rotation=new _e(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=_e.Zero(),this._initialFocalDistance=1,this._viewMatrix=me.Zero(),this._camMatrix=me.Zero(),this._cameraTransformMatrix=me.Zero(),this._cameraRotationMatrix=me.Zero(),this._referencePoint=new _e(0,0,1),this._transformedReferencePoint=_e.Zero(),this._deferredPositionUpdate=new _e,this._deferredRotationQuaternionUpdate=new fe,this._deferredRotationUpdate=new _e,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=_e.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();const t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){const e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)}_initCache(){super._initCache(),this._cache.lockedTarget=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new fe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();const t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;const e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){const e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=J),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),me.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);const t=e.subtract(this.position);t.x>=0?this.rotation.y=-Math.atan(t.z/t.x)+Math.PI/2:this.rotation.y=-Math.atan(t.z/t.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&fe.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(ve.Matrix[0]),_e.TransformNormalToRef(this.cameraDirection,ve.Matrix[0],ve.Vector3[0]),this._deferredPositionUpdate.addInPlace(ve.Vector3[0]),void(this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate));this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint){const e=1.570796;this._deferredRotationUpdate.x>e&&(this._deferredRotationUpdate.x=e),this._deferredRotationUpdate.x<-e&&(this._deferredRotationUpdate.x=-e)}this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(fe.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))}t&&(Math.abs(this.cameraDirection.x){this._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>oo.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new tc(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ds.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new _e(0,0,0),this.cameraRotation=new de(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?_e.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=_e.Zero(),this._transformedDirection=_e.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}}Ze([ht()],ac.prototype,"ellipsoid",void 0),Ze([ht()],ac.prototype,"ellipsoidOffset",void 0),Ze([rt()],ac.prototype,"checkCollisions",void 0),Ze([rt()],ac.prototype,"applyGravity",void 0),z("BABYLON.FreeCamera",ac),Et.AddNodeConstructor("TouchCamera",((e,t)=>()=>new lc(e,_e.Zero(),t)));class lc extends ac{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!e:e.allowMouse=!t}}Et.AddNodeConstructor("ArcRotateCamera",((e,t)=>()=>new hc(e,0,0,1,_e.Zero(),t)));class hc extends oc{get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new me,this._upToYMatrix=new me,this._upVector=_e.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){me.RotationAlignToRef(_e.UpReadOnly,this._upVector,this._yToUpMatrix),me.RotationAlignToRef(this._upVector,_e.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){const e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){const t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){const e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){const t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){const e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){const t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){const e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){const t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){const e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){const e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){const t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){const e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return null!=this._bouncingBehavior}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Fa,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return null!=this._framingBehavior}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new La,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return null!=this._autoRotationBehavior}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new Na,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,r,n,o=!0){super(e,_e.Zero(),n,o),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=_e.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=de.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new me,this.panningAxis=new _e(1,1,0),this._transformedDirection=new _e,this.mapPanning=!1,this.onMeshTargetChangedObservable=new K,this.checkCollisions=!1,this.collisionRadius=new _e(.5,.5,.5),this._previousPosition=_e.Zero(),this._collisionVelocity=_e.Zero(),this._newPosition=_e.Zero(),this._computationVector=_e.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);const s=Math.cos(this.alpha),r=Math.sin(this.alpha),n=Math.cos(this.beta);let o=Math.sin(this.beta);0===o&&(o=1e-4);const a=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*s*o,this.radius*n,this.radius*r*o),a.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=l.clone(),l=l.negate()),this._computeViewMatrix(this._position,a,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=_e.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new Hh(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=de.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){const e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}return this._getLockedTargetPosition()||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)}_isSynchronizedViewMatrix(){return!!super._isSynchronizedViewMatrix()&&this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset)}attachControl(e,t,i=!0,s=2){const r=arguments;t=Ds.BackCompatCameraNoPreventDefault(r),this._useCtrlForPanning=i,this._panningMouseButton=s,"boolean"==typeof r[0]&&(r.length>1&&(this._useCtrlForPanning=r[1]),r.length>2&&(this._panningMouseButton=r[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){const e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier();let i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||_e.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);const e=this.alpha;0===this._computationVector.x&&0===this._computationVector.z?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,s=!1){if(s=this.overrideCloneAlphaBetaRadius??s,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const t=e,s=this._getTargetPosition();if(s&&!i&&s.equals(t))return;this._targetHost=null,this._target=t,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}s||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let s=Math.sin(this.beta);0===s&&(s=1e-4),0===this.radius&&(this.radius=1e-4);const r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*s,this.radius*i,this.radius*t*s),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||_e.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),r.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&s<0&&(e=e.negate()),this._computeViewMatrix(this._position,r,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=ha.MinMax(e);let s=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);s=Math.max(Math.min(s,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=s*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:s},t)}focusOn(e,t=!1){let i,s;if(void 0===e.min){const t=e||this.getScene().meshes;i=ha.MinMax(t),s=_e.Distance(i.min,i.max)}else i=e,s=e.distance;this._target=ha.Center(i),t||(this.maxZ=2*s)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case In.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case In.RIG_MODE_STEREOSCOPIC_OVERUNDER:case In.RIG_MODE_STEREOSCOPIC_INTERLACED:case In.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const s=new hc(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return s._cameraRigParams={},s.isRigCamera=!0,s.rigParent=this,s.upVector=this.upVector,s.mode=this.mode,s.orthoLeft=this.orthoLeft,s.orthoRight=this.orthoRight,s.orthoBottom=this.orthoBottom,s.orthoTop=this.orthoTop,s}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case In.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case In.RIG_MODE_STEREOSCOPIC_OVERUNDER:case In.RIG_MODE_STEREOSCOPIC_INTERLACED:case In.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const s=_e.Distance(e,t),r=this.getScene().getEngine().getAspectRatio(this),n=Math.tan(this.fov/2),o=n*r,a=.5*s*i,l=a*Math.sqrt(1+1/(o*o)),h=a*Math.sqrt(1+1/(n*n));return Math.max(l,h)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}Ze([rt()],hc.prototype,"alpha",void 0),Ze([rt()],hc.prototype,"beta",void 0),Ze([rt()],hc.prototype,"radius",void 0),Ze([rt()],hc.prototype,"overrideCloneAlphaBetaRadius",void 0),Ze([ht("target")],hc.prototype,"_target",void 0),Ze([ct("targetHost")],hc.prototype,"_targetHost",void 0),Ze([rt()],hc.prototype,"inertialAlphaOffset",void 0),Ze([rt()],hc.prototype,"inertialBetaOffset",void 0),Ze([rt()],hc.prototype,"inertialRadiusOffset",void 0),Ze([rt()],hc.prototype,"lowerAlphaLimit",void 0),Ze([rt()],hc.prototype,"upperAlphaLimit",void 0),Ze([rt()],hc.prototype,"lowerBetaLimit",void 0),Ze([rt()],hc.prototype,"upperBetaLimit",void 0),Ze([rt()],hc.prototype,"lowerRadiusLimit",void 0),Ze([rt()],hc.prototype,"upperRadiusLimit",void 0),Ze([rt()],hc.prototype,"inertialPanningX",void 0),Ze([rt()],hc.prototype,"inertialPanningY",void 0),Ze([rt()],hc.prototype,"pinchToPanMaxDistance",void 0),Ze([rt()],hc.prototype,"panningDistanceLimit",void 0),Ze([ht()],hc.prototype,"panningOriginTarget",void 0),Ze([rt()],hc.prototype,"panningInertia",void 0),Ze([rt()],hc.prototype,"zoomToMouseLocation",null),Ze([rt()],hc.prototype,"zoomOnFactor",void 0),Ze([lt()],hc.prototype,"targetScreenOffset",void 0),Ze([rt()],hc.prototype,"allowUpsideDown",void 0),Ze([rt()],hc.prototype,"useInputToRestoreState",void 0),z("BABYLON.ArcRotateCamera",hc),Et.AddNodeConstructor("DeviceOrientationCamera",((e,t)=>()=>new cc(e,_e.Zero(),t)));class cc extends ac{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new fe,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new fe,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce((()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add((e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new fe),fe.FromEulerAnglesToRef(0,e.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))})))}))}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=Xr.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new fe),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}}class uc extends Lh{constructor(e){super(e)}addKeyboard(){return this.add(new Yh),this}addMouse(){return this.add(new Qh),this}}class dc extends oc{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){const e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){const t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){const e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){const t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,s=!0){super(e,t,i,s),this.ellipsoid=new _e(1,1,1),this.ellipsoidOffset=new _e(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=_e.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=_e.Zero(),this._diffPosition=_e.Zero(),this._newPosition=_e.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>oo.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new uc(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ds.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new _e(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?_e.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=_e.Zero(),this._transformedDirection=_e.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}restoreRoll(e){const t=this._trackRoll,i=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,Math.abs(t-this.rotation.z)<=.001&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}Ze([ht()],dc.prototype,"ellipsoid",void 0),Ze([ht()],dc.prototype,"ellipsoidOffset",void 0),Ze([rt()],dc.prototype,"checkCollisions",void 0),Ze([rt()],dc.prototype,"applyGravity",void 0),z("BABYLON.FlyCamera",dc);class _c extends Lh{constructor(e){super(e)}addKeyboard(){return this.add(new jh),this}addMouseWheel(){return this.add(new Kh),this}addPointers(){return this.add(new $h),this}addVRDeviceOrientation(){return Ne.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}Et.AddNodeConstructor("FollowCamera",((e,t)=>()=>new pc(e,_e.Zero(),t))),Et.AddNodeConstructor("ArcFollowCamera",((e,t)=>()=>new fc(e,0,0,1,null,t)));class pc extends oc{constructor(e,t,i,s=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=s,this.inputs=new _c(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=ve.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),s=Ds.ToRadians(this.rotationOffset)+i,r=e.getAbsolutePosition(),n=r.x+Math.sin(s)*this.radius,o=r.z+Math.cos(s)*this.radius,a=n-this.position.x,l=r.y+this.heightOffset-this.position.y,h=o-this.position.z;let c=a*this.cameraAcceleration*2,u=l*this.cameraAcceleration,d=h*this.cameraAcceleration*2;(c>this.maxCameraSpeed||c<-this.maxCameraSpeed)&&(c=c<1?-this.maxCameraSpeed:this.maxCameraSpeed),(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new _e(this.position.x+c,this.position.y+u,this.position.z+d),this.setTarget(r)}attachControl(e,t){t=Ds.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=()=>{}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){this.inputs.checkInputs(),this._checkLimits(),super._checkInputs(),this.lockedTarget&&this._follow(this.lockedTarget)}_checkLimits(){null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}Ze([rt()],pc.prototype,"radius",void 0),Ze([rt()],pc.prototype,"lowerRadiusLimit",void 0),Ze([rt()],pc.prototype,"upperRadiusLimit",void 0),Ze([rt()],pc.prototype,"rotationOffset",void 0),Ze([rt()],pc.prototype,"lowerRotationOffsetLimit",void 0),Ze([rt()],pc.prototype,"upperRotationOffsetLimit",void 0),Ze([rt()],pc.prototype,"heightOffset",void 0),Ze([rt()],pc.prototype,"lowerHeightOffsetLimit",void 0),Ze([rt()],pc.prototype,"upperHeightOffsetLimit",void 0),Ze([rt()],pc.prototype,"cameraAcceleration",void 0),Ze([rt()],pc.prototype,"maxCameraSpeed",void 0),Ze([ct("lockedTargetId")],pc.prototype,"lockedTarget",void 0);class fc extends oc{constructor(e,t,i,s,r,n){super(e,_e.Zero(),n),this.alpha=t,this.beta=i,this.radius=s,this._cartesianCoordinates=_e.Zero(),this.setMeshTarget(r)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);const e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}z("BABYLON.FollowCamera",pc),z("BABYLON.ArcFollowCamera",fc),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Oh||(Oh={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Dh||(Dh={}));class mc extends kh{constructor(e,t,i,s=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new K,this.onButtonUpObservable=new K,this.onPadDownObservable=new K,this.onPadUpObservable=new K,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this.type=kh.XBOX,this._isXboxOnePad=s}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,Oh.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,Oh.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,Oh.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,Oh.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,Oh.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,Oh.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,Oh.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,Oh.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Oh.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Oh.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Dh.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Dh.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Dh.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Dh.Right)}update(){super.update(),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}!function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(wh||(wh={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Nh||(Nh={}));class gc extends kh{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new K,this.onButtonUpObservable=new K,this.onPadDownObservable=new K,this.onPadUpObservable=new K,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=kh.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,wh.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,wh.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,wh.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,wh.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,wh.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,wh.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,wh.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,wh.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,wh.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,wh.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Nh.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Nh.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Nh.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Nh.Right)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class vc{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new K,kt()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new K((e=>{for(const t in this._babylonGamepads){const i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}})),this._onGamepadConnectedEvent=e=>{const t=e.gamepad;if(t.index in this._babylonGamepads&&this._babylonGamepads[t.index].isConnected)return;let i;this._babylonGamepads[t.index]?(i=this._babylonGamepads[t.index],i.browserGamepad=t,i._isConnected=!0):i=this._addNewGamepad(t),this.onGamepadConnectedObservable.notifyObservers(i),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=e=>{const t=e.gamepad;for(const e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){const t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){const e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}get gamepads(){return this._babylonGamepads}getGamepadByType(e=kh.XBOX){for(const t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach((e=>{e.dispose()})),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);const i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),s=-1!==e.id.search("Xbox One");return t=s||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new mc(e.id,e.index,e,s):i?new gc(e.id,e.index,e):new Vh(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){this._updateGamepadObjects();for(const e in this._babylonGamepads){const t=this._babylonGamepads[e];if(t&&t.isConnected)try{t.update()}catch{-1===this._loggedErrors.indexOf(t.index)&&(Ds.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&oo.QueueNewFrame((()=>{this._checkGamepadsStatus()}))}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new bc(e,_e.Zero(),t)));class bc extends lc{get gamepadAngularSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}}In._CreateDefaultParsedCamera=(e,t)=>new bc(e,_e.Zero(),t),Et.AddNodeConstructor("GamepadCamera",((e,t)=>()=>new Tc(e,_e.Zero(),t)));class Tc extends bc{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}Bi.ShadersStore.passCubePixelShader="varying vec2 vUV;uniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";class yc extends Vl{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,r,n,o=0,a=!1){super(e,"pass",null,null,t,i,s,r,n,void 0,o,void 0,null,a)}static _Parse(e,t,i,s){return St.Parse((()=>new yc(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,s)}}z("BABYLON.PassPostProcess",yc);class Sc extends Vl{get face(){return this._face}set face(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ")}}getClassName(){return"PassCubePostProcess"}constructor(e,t,i=null,s,r,n,o=0,a=!1){super(e,"passCube",null,null,t,i,s,r,n,"#define POSITIVEX",o,void 0,null,a),this._face=0}static _Parse(e,t,i,s){return St.Parse((()=>new Sc(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,s)}}ns._RescalePostProcessFactory=e=>new yc("rescale",1,null,2,e,!1,0);Bi.ShadersStore.anaglyphPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}";class Cc extends Vl{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,s,r,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],s,r,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)}))}}function Ec(e){e._rigCameras[0]._rigPostProcess=new yc(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new Cc(e.name+"_anaglyph",1,e._rigCameras)}z("BABYLON.AnaglyphPostProcess",Cc),Et.AddNodeConstructor("AnaglyphArcRotateCamera",((e,t,i)=>()=>new Ac(e,0,0,1,_e.Zero(),i.interaxial_distance,t)));class Ac extends hc{constructor(e,t,i,s,r,n,o){super(e,t,i,s,r,o),this._setRigMode=()=>Ec(this),this.interaxialDistance=n,this.setCameraRigMode(In.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}Et.AddNodeConstructor("AnaglyphFreeCamera",((e,t,i)=>()=>new Pc(e,_e.Zero(),i.interaxial_distance,t)));class Pc extends ac{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Ec(this),this.interaxialDistance=i,this.setCameraRigMode(In.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}Et.AddNodeConstructor("AnaglyphGamepadCamera",((e,t,i)=>()=>new Ic(e,_e.Zero(),i.interaxial_distance,t)));class Ic extends Tc{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Ec(this),this.interaxialDistance=i,this.setCameraRigMode(In.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}Et.AddNodeConstructor("AnaglyphUniversalCamera",((e,t,i)=>()=>new Rc(e,_e.Zero(),i.interaxial_distance,t)));class Rc extends bc{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Ec(this),this.interaxialDistance=i,this.setCameraRigMode(In.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}Bi.ShadersStore.stereoscopicInterlacePixelShader="const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\n#ifdef IS_STEREOSCOPIC_INTERLACED\nfloat rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n#endif\nif (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);}\n";class Mc extends Vl{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,s,r,n,o){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],r,n,o,s?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new de(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new de(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}class Oc extends Vl{getClassName(){return"StereoscopicInterlacePostProcess"}constructor(e,t,i,s,r,n){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,r,n,i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new de(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new de(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}function Dc(e){const t=e.cameraRigMode===In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;e.cameraRigMode===In.RIG_MODE_STEREOSCOPIC_INTERLACED?(e._rigCameras[0]._rigPostProcess=new yc(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new Mc(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new Pn(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new Pn(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}Et.AddNodeConstructor("StereoscopicArcRotateCamera",((e,t,i)=>()=>new wc(e,0,0,1,_e.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class wc extends hc{constructor(e,t,i,s,r,n,o,a){super(e,t,i,s,r,a),this._setRigMode=()=>Dc(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:In.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}Et.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new Nc(e,_e.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Nc extends ac{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Dc(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:In.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}Et.AddNodeConstructor("StereoscopicGamepadCamera",((e,t,i)=>()=>new Fc(e,_e.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Fc extends Tc{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Dc(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:In.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}Et.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new Lc(e,_e.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Lc extends bc{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Dc(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:In.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}class Bc extends bc{set distanceBetweenEyes(e){this._distanceBetweenEyes=e}get distanceBetweenEyes(){return this._distanceBetweenEyes}set distanceToProjectionPlane(e){this._distanceToProjectionPlane=e}get distanceToProjectionPlane(){return this._distanceToProjectionPlane}constructor(e,t,i,s=1,r=.065){super(e,t,i),this._distanceBetweenEyes=r,this._distanceToProjectionPlane=s,this.setCameraRigMode(In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,{stereoHalfAngle:0}),this._cameraRigParams.stereoHalfAngle=0,this._cameraRigParams.interaxialDistance=r}getClassName(){return"StereoscopicUniversalCamera"}createRigCamera(e){const t=new oc(e,_e.Zero(),this.getScene()),i=new lo("tm_"+e,this.getScene());return t.parent=i,i.setPivotMatrix(me.Identity(),!1),t.isRigCamera=!0,t.rigParent=this,t}_updateRigCameras(){for(let e=0;e()=>new kc(e,_e.Zero(),t)));class kc extends ac{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class Vc{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return me.Translation(e,0,0)}get rightHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return me.Translation(-e,0,0)}get leftPreViewMatrix(){return me.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return me.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new Vc;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}Bi.ShadersStore.vrDistortionCorrectionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}";class Uc extends Vl{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,s){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,s.postProcessScaleFactor,t,Pa.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=s.distortionK,this._postProcessScaleFactor=s.postProcessScaleFactor,this._lensCenterOffset=s.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add((()=>{this._scaleIn=new de(2,2/this.aspectRatio),this._scaleFactor=new de(1/this._postProcessScaleFactor*.5,1/this._postProcessScaleFactor*.5*this.aspectRatio),this._lensCenter=new de(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)})),this.onApplyObservable.add((e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])}))}}Bi.ShadersStore.vrMultiviewToSingleviewPixelShader="precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}";class Gc extends ih{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}}function zc(e,t){const i=new Zs(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}oo.prototype.createMultiviewRenderTargetTexture=function(e,t,i,s){const r=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const n=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});n._framebuffer=r.createFramebuffer();const o=new ss(this,is.Unknown,!0);return o.width=e,o.height=t,o.isMultiview=!0,i||(i=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,i),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.RGBA8,e,t,2)),n._colorTextureArray=i,s||(s=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,s),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.DEPTH24_STENCIL8,e,t,2)),n._depthStencilTextureArray=s,o.isReady=!0,n.setTextures(o),n._depthStencilTexture=o,n},oo.prototype.bindMultiviewFramebuffer=function(e){const t=e,i=this._gl,s=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw"Invalid multiview frame buffer";this.getCaps().oculusMultiview?(s.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,t.samples,0,2),s.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,t.samples,0,2)):(s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,0,2))},oo.prototype.bindSpaceWarpFramebuffer=function(e){const t=e,i=this._gl,s=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw new Error("Invalid Space Warp framebuffer");s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_ATTACHMENT,t._depthStencilTextureArray,0,0,2)},In.prototype._useMultiviewToSingleView=!1,In.prototype._multiviewTexture=null,In.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==e&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new Gc(this.getScene(),{width:e,height:t})):this._multiviewTexture=new Gc(this.getScene(),{width:e,height:t})};const Wc=Hr.prototype.createSceneUniformBuffer;Hr.prototype._transformMatrixR=me.Zero(),Hr.prototype._multiviewSceneUbo=null,Hr.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=zc(this.getEngine(),"scene_multiview")},Hr.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?zc(this.getEngine(),e):Wc.bind(this)(e)},Hr.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,ve.Matrix[0]),Fr.GetRightPlaneToRef(ve.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))},Hr.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t{})),this.onApplyObservable.add((e=>{s._scene.activeCamera&&s._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",s._multiviewTexture)}))}}function Xc(e,t){const i=t.vrCameraMetrics||Vc.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new Pn(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new me,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new Pn(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new me,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new Hc("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(Ne.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new Uc("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new Uc("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}Et.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",((e,t)=>()=>new Yc(e,0,0,1,_e.Zero(),t)));class Yc extends hc{constructor(e,t,i,s,r,n,o=!0,a=Vc.GetDefault()){super(e,t,i,s,r,n),this._setRigMode=e=>Xc(this,e),a.compensateDistortion=o,this.setCameraRigMode(In.RIG_MODE_VR,{vrCameraMetrics:a}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}Et.AddNodeConstructor("VRDeviceOrientationFreeCamera",((e,t)=>()=>new Qc(e,_e.Zero(),t)));class Qc extends cc{constructor(e,t,i,s=!0,r=Vc.GetDefault()){super(e,t,i),this._setRigMode=e=>Xc(this,e),r.compensateDistortion=s,this.setCameraRigMode(In.RIG_MODE_VR,{vrCameraMetrics:r})}getClassName(){return"VRDeviceOrientationFreeCamera"}}Et.AddNodeConstructor("VRDeviceOrientationGamepadCamera",((e,t)=>()=>new jc(e,_e.Zero(),t)));class jc extends Qc{constructor(e,t,i,s=!0,r=Vc.GetDefault()){super(e,t,i,s,r),this._setRigMode=e=>Xc(this,e),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}class Kc{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,s,r){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(2)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=s.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const r=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==r.frameId&&(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=s.clone()}}}class $c{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,oo.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._TranslucencyIntensityTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get TranslucencyColorTextureEnabled(){return this._TranslucencyColorTextureEnabled}static set TranslucencyColorTextureEnabled(e){this._TranslucencyColorTextureEnabled!==e&&(this._TranslucencyColorTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}}$c._DiffuseTextureEnabled=!0,$c._DetailTextureEnabled=!0,$c._DecalMapEnabled=!0,$c._AmbientTextureEnabled=!0,$c._OpacityTextureEnabled=!0,$c._ReflectionTextureEnabled=!0,$c._EmissiveTextureEnabled=!0,$c._SpecularTextureEnabled=!0,$c._BumpTextureEnabled=!0,$c._LightmapTextureEnabled=!0,$c._RefractionTextureEnabled=!0,$c._ColorGradingTextureEnabled=!0,$c._FresnelEnabled=!0,$c._ClearCoatTextureEnabled=!0,$c._ClearCoatBumpTextureEnabled=!0,$c._ClearCoatTintTextureEnabled=!0,$c._SheenTextureEnabled=!0,$c._AnisotropicTextureEnabled=!0,$c._ThicknessTextureEnabled=!0,$c._RefractionIntensityTextureEnabled=!0,$c._TranslucencyIntensityTextureEnabled=!0,$c._TranslucencyColorTextureEnabled=!0,$c._IridescenceTextureEnabled=!0;Bi.IncludesShadersStore.decalFragmentDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;\n#endif\n";Bi.IncludesShadersStore.defaultFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;uniform vec4 refractionRightColor;\n#endif\n#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)\nuniform mat4 reflectionMatrix;\n#endif\n#ifndef REFLECTIONMAP_SKYBOX\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";Bi.IncludesShadersStore.sceneUboDeclaration="layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \nmat4 view;mat4 projection;vec4 vEyePosition;};\n";Bi.IncludesShadersStore.meshUboDeclaration="#ifdef WEBGL2\nuniform mat4 world;uniform float visibility;\n#else\nlayout(std140,column_major) uniform;uniform Mesh\n{mat4 world;float visibility;};\n#endif\n#define WORLD_UBO\n";Bi.IncludesShadersStore.defaultUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";Bi.IncludesShadersStore.prePassDeclaration="#ifdef PREPASS\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor;\n#ifdef PREPASS_DEPTH\nvarying highp vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nvarying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;\n#endif\n#endif\n";Bi.IncludesShadersStore.oitDeclaration="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out vec2 depth; \nlayout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor;\n#define MAX_DEPTH 99999.0\nhighp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler;\n#endif\n";Bi.IncludesShadersStore.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vec2 vMainUV{X};\n#endif\n";Bi.IncludesShadersStore.helperFunctions="const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; \nconst float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\n#define absEps(x) abs(x)+Epsilon\n#define maxEps(x) max(x,Epsilon)\n#define saturateEps(x) clamp(x,Epsilon,1.0)\nmat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nmat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;}\n#if USE_EXACT_SRGB_CONVERSIONS\nvec3 toLinearSpaceExact(vec3 color)\n{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));\n#else\nreturn\nvec3(\ncolor.r<=0.04045 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.04045 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.04045 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\nvec3 toGammaSpaceExact(vec3 color)\n{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));\n#else\nreturn\nvec3(\ncolor.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\n#endif\nfloat toLinearSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,LinearEncodePowerApprox);\n#endif\n}\nvec3 toLinearSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nvec4 toLinearSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfloat toGammaSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,GammaEncodePowerApprox);\n#endif\n}\nvec3 toGammaSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nvec4 toGammaSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfloat square(float value)\n{return value*value;}\nvec3 square(vec3 value)\n{return value*value;}\nfloat pow5(float value) {float sq=value*value;return sq*sq*value;}\nfloat getLuminance(vec3 color)\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfloat getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfloat dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;}\nconst float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); }\nvec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;}\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";Bi.IncludesShadersStore.lightFragmentDeclaration="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};\n#else\nuniform highp sampler2DArray shadowTexture{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowTexture{X};\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowTexture{X};\n#else\nuniform sampler2D shadowTexture{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};\n#endif\n#endif\n";Bi.IncludesShadersStore.lightUboDeclaration="#ifdef LIGHT{X}\nuniform Light{X}\n{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;vec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;vec2 depthValues;} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};\n#else\nuniform highp sampler2DArray shadowTexture{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowTexture{X}; \n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowTexture{X};\n#else\nuniform sampler2D shadowTexture{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";Bi.IncludesShadersStore.lightsFragmentFunctions="struct lightingInfo\n{vec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.)\n{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}";Bi.IncludesShadersStore.shadowsFragmentFunctions="#ifdef SHADOWS\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}\n#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\n#define inline\nfloat computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nreturn depth>shadow ? darkness : 1.0;}\n#define inline\nfloat computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}\n#endif\n#define inline\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}}\n#define inline\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#ifdef IS_NDC_HALF_ZRANGE\n#define ZINCLIP clipSpace.z\n#else\n#define ZINCLIP uvDepth.z\n#endif\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define GREATEST_LESS_THAN_ONE 0.99999994\n#define DISABLE_UNIFORMITY_ANALYSIS\n#define inline\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.)\n);const vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n#define inline\nfloat computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; ithis._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort(((e,t)=>e.priority-t.priority)),this._codeInjectionPoints={};const i={};i[Zc._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const e of this._plugins)e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t0&&e.uniforms.push(...this._uniformList),this._samplerList.length>0&&e.samplers.push(...this._samplerList),this._uboList.length>0&&e.uniformBuffersNames.push(...this._uboList),e.customCode=this._injectCustomCode(e,e.customCode);break}case fo.PrepareUniformBuffer:{const e=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const t of this._plugins){const i=t.getUniforms();if(i){if(i.ubo)for(const t of i.ubo){if(t.size&&t.type){const i=t.arraySize??0;e.ubo.addUniform(t.name,t.size,i),this._uboDeclaration+=`${t.type} ${t.name}${i>0?`[${i}]`:""};\n`}this._uniformList.push(t.name)}i.vertex&&(this._vertexDeclaration+=i.vertex+"\n"),i.fragment&&(this._fragmentDeclaration+=i.fragment+"\n")}t.getSamplers(this._samplerList),t.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,s)=>{t&&(s=t(i,s)),this._uboDeclaration&&(s=s.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(s=s.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(s=s.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const r=this._codeInjectionPoints?.[i];if(!r)return s;let n=null;for(let t in r){let r="";for(const s of this._activePlugins){let o=s.getCustomCode(i)?.[t];if(o){if(s.resolveIncludes){if(null===n){const t=di.GLSL;n={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Bi.GetShadersRepository(t),includesShadersStore:Bi.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}n.isFragment="fragment"===i,Ni(o,n,(e=>o=e))}r+=o+"\n"}}if(r.length>0)if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{const i=qc.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}e.indexOf("g")<0&&(e+="g");const i=s,n=new RegExp(t,e);let o=n.exec(i);for(;null!==o;){let e=r;for(let t=0;t{ru()}));const Jc=[];let eu=!1,tu=null;function iu(e,t){eu||(tu=ta.OnEventObservable.add((e=>{for(const[,t]of Jc)t(e)}),fo.Created),eu=!0);const i=Jc.filter((([t,i])=>t===e));i.length>0?i[0][1]=t:Jc.push([e,t])}function su(e){for(let t=0;t{e.pluginManager=void 0}))),this._pluginDefineNames=s,this._pluginManager=e.pluginManager,r&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,s){return!0}hardBindForSubMesh(e,t,i,s){}bindForSubMesh(e,t,i,s){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;const i=typeof this._pluginDefineNames[t];e[t]={type:"number"===i?"number":"string"===i?"string":"boolean"===i?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(){return{}}copyTo(e){St.Clone((()=>e),this)}serialize(){return St.Serialize(this)}parse(e,t,i){St.Parse((()=>this),e,t,i)}}Ze([rt()],nu.prototype,"name",void 0),Ze([rt()],nu.prototype,"priority",void 0),Ze([rt()],nu.prototype,"resolveIncludes",void 0),Ze([rt()],nu.prototype,"registerForExtraEvents",void 0),z("BABYLON.MaterialPluginBase",nu);class ou extends xl{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class au extends nu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new ou,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=ta.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&$c.DetailTextureEnabled&&!this._texture.isReady())}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&$c.DetailTextureEnabled&&this._isEnabled?(Mo(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||this._texture&&$c.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),Oo(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&$c.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture?.dispose()}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}Ze([nt("detailTexture"),st("_markAllSubMeshesAsTexturesDirty")],au.prototype,"texture",void 0),Ze([rt()],au.prototype,"diffuseBlendLevel",void 0),Ze([rt()],au.prototype,"roughnessBlendLevel",void 0),Ze([rt()],au.prototype,"bumpLevel",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],au.prototype,"normalBlendMethod",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],au.prototype,"isEnabled",void 0);const lu={effect:null,subMesh:null};class hu extends xl{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){const t=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];for(const i of t)this[i]=i===e}}class cu extends ml{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new Ee(0,0,0),this.diffuseColor=new Ee(1,1,1),this.specularColor=new Ee(1,1,1),this.emissiveColor=new Ee(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._renderTargets=new Fs(16),this._worldViewProjectionMatrix=me.Zero(),this._globalAmbientColor=new Ee(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new au(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new Kc,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),cu.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),cu.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return!!(cu.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||!!(cu.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===ta.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==ta.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(fo.GetDefineNames,this._eventInfo),t.materialDefines=new hu(this._eventInfo.defineNames));const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();n._needNormals=zo(r,e,n,!0,this._maxSimultaneousLights,this._disableLighting),Ko(r,n);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(qo(r,n,this.canRenderToMRT&&!a),$o(r,n,a),n._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n._needUVs=!1;for(let e=1;e<=6;++e)n["MAINUV"+e]=!1;if(r.texturesEnabled){if(n.DIFFUSEDIRECTUV=0,n.BUMPDIRECTUV=0,n.AMBIENTDIRECTUV=0,n.OPACITYDIRECTUV=0,n.EMISSIVEDIRECTUV=0,n.SPECULARDIRECTUV=0,n.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&cu.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;Mo(this._diffuseTexture,n,"DIFFUSE")}else n.DIFFUSE=!1;if(this._ambientTexture&&cu.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;Mo(this._ambientTexture,n,"AMBIENT")}else n.AMBIENT=!1;if(this._opacityTexture&&cu.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;Mo(this._opacityTexture,n,"OPACITY"),n.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else n.OPACITY=!1;if(this._reflectionTexture&&cu.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(n._needNormals=!0,n.REFLECTION=!0,n.ROUGHNESS=this._roughness>0,n.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,n.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===Pa.INVCUBIC_MODE,n.REFLECTIONMAP_3D=this._reflectionTexture.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,n.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case Pa.EXPLICIT_MODE:n.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case Pa.PLANAR_MODE:n.setReflectionMode("REFLECTIONMAP_PLANAR");break;case Pa.PROJECTION_MODE:n.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case Pa.SKYBOX_MODE:n.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case Pa.SPHERICAL_MODE:n.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case Pa.EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case Pa.FIXED_EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case Pa.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case Pa.CUBIC_MODE:case Pa.INVCUBIC_MODE:default:n.setReflectionMode("REFLECTIONMAP_CUBIC")}n.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else n.REFLECTION=!1,n.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&cu.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;Mo(this._emissiveTexture,n,"EMISSIVE")}else n.EMISSIVE=!1;if(this._lightmapTexture&&cu.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;Mo(this._lightmapTexture,n,"LIGHTMAP"),n.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,n.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else n.LIGHTMAP=!1;if(this._specularTexture&&cu.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;Mo(this._specularTexture,n,"SPECULAR"),n.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else n.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&cu.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;Mo(this._bumpTexture,n,"BUMP"),n.PARALLAX=this._useParallax,n.PARALLAX_RHS=r.useRightHandedSystem,n.PARALLAXOCCLUSION=this._useParallaxOcclusion,n.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else n.BUMP=!1,n.PARALLAX=!1,n.PARALLAX_RHS=!1,n.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&cu.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;n._needUVs=!0,n.REFRACTION=!0,n.REFRACTIONMAP_3D=this._refractionTexture.isCube,n.RGBDREFRACTION=this._refractionTexture.isRGBD,n.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else n.REFRACTION=!1;n.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else n.DIFFUSE=!1,n.AMBIENT=!1,n.OPACITY=!1,n.REFLECTION=!1,n.EMISSIVE=!1,n.LIGHTMAP=!1,n.BUMP=!1,n.REFRACTION=!1;n.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),n.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,n.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,n.SPECULAROVERALPHA=this._useSpecularOverAlpha,n.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,n.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,n.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n),n.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,n.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}n._areFresnelDirty&&(cu.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(n.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,n.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,n.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,n.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,n.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,n.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,n._needNormals=!0,n.FRESNEL=!0):n.FRESNEL=!1),Go(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,n,this._applyDecalMapAfterDetailMap),Ho(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=n,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),jo(e,n,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let l=!1;if(n.isDirty){const i=n._areLightsDisposed;n.markAsProcessed();const s=new Ll;n.REFLECTION&&s.addFallback(0,"REFLECTION"),n.SPECULAR&&s.addFallback(0,"SPECULAR"),n.BUMP&&s.addFallback(0,"BUMP"),n.PARALLAX&&s.addFallback(1,"PARALLAX"),n.PARALLAX_RHS&&s.addFallback(1,"PARALLAX_RHS"),n.PARALLAXOCCLUSION&&s.addFallback(0,"PARALLAXOCCLUSION"),n.SPECULAROVERALPHA&&s.addFallback(0,"SPECULAROVERALPHA"),n.FOG&&s.addFallback(1,"FOG"),n.POINTSIZE&&s.addFallback(0,"POINTSIZE"),n.LOGARITHMICDEPTH&&s.addFallback(0,"LOGARITHMICDEPTH"),Vo(n,s,this._maxSimultaneousLights),n.SPECULARTERM&&s.addFallback(0,"SPECULARTERM"),n.DIFFUSEFRESNEL&&s.addFallback(1,"DIFFUSEFRESNEL"),n.OPACITYFRESNEL&&s.addFallback(2,"OPACITYFRESNEL"),n.REFLECTIONFRESNEL&&s.addFallback(3,"REFLECTIONFRESNEL"),n.EMISSIVEFRESNEL&&s.addFallback(4,"EMISSIVEFRESNEL"),n.FRESNEL&&s.addFallback(4,"FRESNEL"),n.MULTIVIEW&&s.addFallback(0,"MULTIVIEW");const a=[er.PositionKind];n.NORMAL&&a.push(er.NormalKind),n.TANGENT&&a.push(er.TangentKind);for(let e=1;e<=6;++e)n["UV"+e]&&a.push(`uv${1===e?"":e}`);n.VERTEXCOLOR&&a.push(er.ColorKind),Bo(a,e,n,s),ko(a,n),Ao(a,e,n),Do(a,0,n);let h="default";const c=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],u=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],d=["Material","Scene","Mesh"],_={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=s,this._eventInfo.fallbackRank=0,this._eventInfo.defines=n,this._eventInfo.uniforms=c,this._eventInfo.attributes=a,this._eventInfo.samplers=u,this._eventInfo.uniformBuffersNames=d,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=_,this._callbackPluginEventGeneric(fo.PrepareEffect,this._eventInfo),Kc.AddUniforms(c),Kc.AddSamplers(u),zs&&(zs.PrepareUniforms(c,n),zs.PrepareSamplers(u,n)),ea({uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:n,maxSimultaneousLights:this._maxSimultaneousLights}),mo(c);const p={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,c,d,u,n,a,p));const f=n.toString(),m=t.effect;let g=r.getEngine().createEffect(h,{attributes:a,uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:f,fallbacks:s,onCompiled:this.onCompiled,onError:this.onError,indexParameters:_,processFinalCode:p.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:n.PREPASS},o);if(this._eventInfo.customCode=void 0,g)if(this._onEffectCreatedObservable&&(lu.effect=g,lu.subMesh=t,this._onEffectCreatedObservable.notifyObservers(lu)),this.allowShaderHotSwapping&&m&&!g.isReady()){if(g=m,n.markAsUnprocessed(),l=this.isFrozen,i)return n._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(g,n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!l,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(s,n,i,t.visibility);wo(t,n);const a=this._uniformBuffer;if(o){if(this.bindViewProjection(n),!a.useUbo||!this.isFrozen||!a.isSync||i._drawWrapper._forceRebindOnNextCall){if(cu.FresnelEnabled&&r.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(a.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),a.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&a.updateColor4("opacityParts",new Ee(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(a.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),a.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(a.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),a.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(a.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),a.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&cu.DiffuseTextureEnabled&&(a.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Oo(this._diffuseTexture,a,"diffuse")),this._ambientTexture&&cu.AmbientTextureEnabled&&(a.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),Oo(this._ambientTexture,a,"ambient")),this._opacityTexture&&cu.OpacityTextureEnabled&&(a.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Oo(this._opacityTexture,a,"opacity")),this._hasAlphaChannel()&&a.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&cu.ReflectionTextureEnabled&&(a.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),a.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const e=this._reflectionTexture;a.updateVector3("vReflectionPosition",e.boundingBoxPosition),a.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&cu.EmissiveTextureEnabled&&(a.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Oo(this._emissiveTexture,a,"emissive")),this._lightmapTexture&&cu.LightmapTextureEnabled&&(a.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Oo(this._lightmapTexture,a,"lightmap")),this._specularTexture&&cu.SpecularTextureEnabled&&(a.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),Oo(this._specularTexture,a,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&cu.BumpTextureEnabled&&(a.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),Oo(this._bumpTexture,a,"bump"),s._mirroredCameraPosition?a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&cu.RefractionTextureEnabled){let e=1;if(this._refractionTexture.isCube||(a.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),a.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const e=this._refractionTexture;a.updateVector3("vRefractionPosition",e.boundingBoxPosition),a.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&a.updateFloat("pointSize",this.pointSize),r.SPECULARTERM&&a.updateColor4("vSpecularColor",this.specularColor,this.specularPower),a.updateColor3("vEmissiveColor",cu.EmissiveTextureEnabled?this.emissiveColor:Ee.BlackReadOnly),a.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),a.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&cu.DiffuseTextureEnabled&&n.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&cu.AmbientTextureEnabled&&n.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&cu.OpacityTextureEnabled&&n.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&cu.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?n.setTexture("reflectionCubeSampler",this._reflectionTexture):n.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&cu.EmissiveTextureEnabled&&n.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&cu.LightmapTextureEnabled&&n.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&cu.SpecularTextureEnabled&&n.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&cu.BumpTextureEnabled&&n.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&cu.RefractionTextureEnabled&&(this._refractionTexture.isCube?n.setTexture("refractionCubeSampler",this._refractionTexture):n.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),xo(n,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!o&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&Lo(s,t,n,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),Co(s,t,n),r.NUM_MORPH_INFLUENCERS&&Io(t,n),r.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,r.INSTANCES),this.useLogarithmicDepth&&So(r,n,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),a.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e}dispose(e,t){t&&(this._diffuseTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._specularTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._refractionTexture?.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=St.Clone((()=>new cu(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return s.name=e,s.id=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}static Parse(e,t,i){const s=St.Parse((()=>new cu(e.name,t)),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),ta._ParsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return $c.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){$c.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return $c.DetailTextureEnabled}static set DetailTextureEnabled(e){$c.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return $c.AmbientTextureEnabled}static set AmbientTextureEnabled(e){$c.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return $c.OpacityTextureEnabled}static set OpacityTextureEnabled(e){$c.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return $c.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){$c.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return $c.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){$c.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return $c.SpecularTextureEnabled}static set SpecularTextureEnabled(e){$c.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return $c.BumpTextureEnabled}static set BumpTextureEnabled(e){$c.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return $c.LightmapTextureEnabled}static set LightmapTextureEnabled(e){$c.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return $c.RefractionTextureEnabled}static set RefractionTextureEnabled(e){$c.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return $c.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){$c.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return $c.FresnelEnabled}static set FresnelEnabled(e){$c.FresnelEnabled=e}}Ze([nt("diffuseTexture")],cu.prototype,"_diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesAndMiscDirty")],cu.prototype,"diffuseTexture",void 0),Ze([nt("ambientTexture")],cu.prototype,"_ambientTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"ambientTexture",void 0),Ze([nt("opacityTexture")],cu.prototype,"_opacityTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesAndMiscDirty")],cu.prototype,"opacityTexture",void 0),Ze([nt("reflectionTexture")],cu.prototype,"_reflectionTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"reflectionTexture",void 0),Ze([nt("emissiveTexture")],cu.prototype,"_emissiveTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"emissiveTexture",void 0),Ze([nt("specularTexture")],cu.prototype,"_specularTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"specularTexture",void 0),Ze([nt("bumpTexture")],cu.prototype,"_bumpTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"bumpTexture",void 0),Ze([nt("lightmapTexture")],cu.prototype,"_lightmapTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"lightmapTexture",void 0),Ze([nt("refractionTexture")],cu.prototype,"_refractionTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"refractionTexture",void 0),Ze([ot("ambient")],cu.prototype,"ambientColor",void 0),Ze([ot("diffuse")],cu.prototype,"diffuseColor",void 0),Ze([ot("specular")],cu.prototype,"specularColor",void 0),Ze([ot("emissive")],cu.prototype,"emissiveColor",void 0),Ze([rt()],cu.prototype,"specularPower",void 0),Ze([rt("useAlphaFromDiffuseTexture")],cu.prototype,"_useAlphaFromDiffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesAndMiscDirty")],cu.prototype,"useAlphaFromDiffuseTexture",void 0),Ze([rt("useEmissiveAsIllumination")],cu.prototype,"_useEmissiveAsIllumination",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useEmissiveAsIllumination",void 0),Ze([rt("linkEmissiveWithDiffuse")],cu.prototype,"_linkEmissiveWithDiffuse",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"linkEmissiveWithDiffuse",void 0),Ze([rt("useSpecularOverAlpha")],cu.prototype,"_useSpecularOverAlpha",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useSpecularOverAlpha",void 0),Ze([rt("useReflectionOverAlpha")],cu.prototype,"_useReflectionOverAlpha",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useReflectionOverAlpha",void 0),Ze([rt("disableLighting")],cu.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],cu.prototype,"disableLighting",void 0),Ze([rt("useObjectSpaceNormalMap")],cu.prototype,"_useObjectSpaceNormalMap",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useObjectSpaceNormalMap",void 0),Ze([rt("useParallax")],cu.prototype,"_useParallax",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useParallax",void 0),Ze([rt("useParallaxOcclusion")],cu.prototype,"_useParallaxOcclusion",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useParallaxOcclusion",void 0),Ze([rt()],cu.prototype,"parallaxScaleBias",void 0),Ze([rt("roughness")],cu.prototype,"_roughness",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"roughness",void 0),Ze([rt()],cu.prototype,"indexOfRefraction",void 0),Ze([rt()],cu.prototype,"invertRefractionY",void 0),Ze([rt()],cu.prototype,"alphaCutOff",void 0),Ze([rt("useLightmapAsShadowmap")],cu.prototype,"_useLightmapAsShadowmap",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useLightmapAsShadowmap",void 0),Ze([at("diffuseFresnelParameters")],cu.prototype,"_diffuseFresnelParameters",void 0),Ze([st("_markAllSubMeshesAsFresnelDirty")],cu.prototype,"diffuseFresnelParameters",void 0),Ze([at("opacityFresnelParameters")],cu.prototype,"_opacityFresnelParameters",void 0),Ze([st("_markAllSubMeshesAsFresnelAndMiscDirty")],cu.prototype,"opacityFresnelParameters",void 0),Ze([at("reflectionFresnelParameters")],cu.prototype,"_reflectionFresnelParameters",void 0),Ze([st("_markAllSubMeshesAsFresnelDirty")],cu.prototype,"reflectionFresnelParameters",void 0),Ze([at("refractionFresnelParameters")],cu.prototype,"_refractionFresnelParameters",void 0),Ze([st("_markAllSubMeshesAsFresnelDirty")],cu.prototype,"refractionFresnelParameters",void 0),Ze([at("emissiveFresnelParameters")],cu.prototype,"_emissiveFresnelParameters",void 0),Ze([st("_markAllSubMeshesAsFresnelDirty")],cu.prototype,"emissiveFresnelParameters",void 0),Ze([rt("useReflectionFresnelFromSpecular")],cu.prototype,"_useReflectionFresnelFromSpecular",void 0),Ze([st("_markAllSubMeshesAsFresnelDirty")],cu.prototype,"useReflectionFresnelFromSpecular",void 0),Ze([rt("useGlossinessFromSpecularMapAlpha")],cu.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useGlossinessFromSpecularMapAlpha",void 0),Ze([rt("maxSimultaneousLights")],cu.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],cu.prototype,"maxSimultaneousLights",void 0),Ze([rt("invertNormalMapX")],cu.prototype,"_invertNormalMapX",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"invertNormalMapX",void 0),Ze([rt("invertNormalMapY")],cu.prototype,"_invertNormalMapY",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"invertNormalMapY",void 0),Ze([rt("twoSidedLighting")],cu.prototype,"_twoSidedLighting",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"twoSidedLighting",void 0),Ze([rt("applyDecalMapAfterDetailMap")],cu.prototype,"_applyDecalMapAfterDetailMap",void 0),Ze([st("_markAllSubMeshesAsMiscDirty")],cu.prototype,"applyDecalMapAfterDetailMap",void 0),z("BABYLON.StandardMaterial",cu),Hr.DefaultMaterialFactory=e=>new cu("default material",e),qs.prototype.createDynamicTexture=function(e,t,i,s){const r=new ss(this,is.Dynamic);return r.baseWidth=e,r.baseHeight=t,i&&(e=this.needPOTTextures?Os(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?Os(t,this._caps.maxTextureSize):t),r.width=e,r.height=t,r.isReady=!1,r.generateMipMaps=i,r.samplingMode=s,this.updateTextureSamplingMode(s,r),this._internalTexturesCache.push(r),r},qs.prototype.updateDynamicTexture=function(e,t,i,s=!1,r,n=!1,o=!1){if(!e)return;const a=this._gl,l=a.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,n);this._unpackFlipY(void 0===i?e.invertY:i),s&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(r||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,u);a.texImage2D(l,0,d,u,c,t),e.generateMipMaps&&a.generateMipmap(l),h||this._bindTextureDirectly(l,null),s&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),r&&(e.format=r),e._dynamicTextureSource=t,e._premulAlpha=s,e.invertY=i||!1,e.isReady=!0};class uu extends Pa{constructor(e,t,i=null,s=!1,r=3,n=5,o){super(null,i,!s,o,r,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=Pa.CLAMP_ADDRESSMODE,this.wrapV=Pa.CLAMP_ADDRESSMODE,this._generateMipMaps=s;const a=this._getEngine();if(!a)return;t.getContext?(this._canvas=t,this._ownCanvas=!1,this._texture=a.createDynamicTexture(t.width,t.height,s,r)):(this._canvas=a.createCanvas(1,1),this._ownCanvas=!0,t.width||0===t.width?this._texture=a.createDynamicTexture(t.width,t.height,s,r):this._texture=a.createDynamicTexture(t,t,s,r));const l=this.getSize();this._canvas.width!==l.width&&(this._canvas.width=l.width),this._canvas.height!==l.height&&(this._canvas.height=l.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){const t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){const i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){const t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0,void 0,i)}drawText(e,t,i,s,r,n,o,a=!0){const l=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,l.width,l.height)),this._context.font=s,null==t){const i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){const e=parseInt(s.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=r||"",this._context.fillText(e,t,i),a&&this.update(o)}dispose(){super.dispose(),this._ownCanvas&&this._canvas?.remove?.(),this._canvas=null,this._context=null}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new uu(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){const e=this.getScene();e&&!e.isReady()&&Ne.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return uu._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return void 0!==e.toDataURL}_rebuild(){this.update()}}class du{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){if(this.isFixedFoveationSupported){const t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}}createRenderTargetTextureProvider(e){return this._rttWrapper=this._createRenderTargetTextureProvider(e),this._rttWrapper}dispose(){this._rttWrapper&&(this._rttWrapper.dispose(),this._rttWrapper=null)}constructor(e,t,i,s,r){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this._createRenderTargetTextureProvider=r,this._rttWrapper=null}}class _u{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new ss(this._engine,is.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new Ks(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,s,r,n){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},a=n?new Gc(this._scene,o):new ih("XR renderTargetTexture",o,this._scene),l=a.renderTarget;if(l._samples=a.samples,!i&&s||(l._framebuffer=i),s)if(n)l._colorTextureArray=s;else{const e=this._createInternalTexture(o,s);l.setTexture(e,0),a._texture=e}return r&&(n?l._depthStencilTextureArray=r:l._depthStencilTexture=this._createInternalTexture(o,r)),a.disableRescaling(),this._renderTargetTextures.push(a),a}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.length=0}}class pu extends du{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new fu(e.scene,this))),this.layer=e}}class fu extends _u{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){const i=this._layer.getViewport(t);if(!i)return!1;const s=this._framebufferDimensions.framebufferWidth,r=this._framebufferDimensions.framebufferHeight;return e.x=i.x/s,e.y=i.y/r,e.width=i.width/s,e.height=i.height/r,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,s=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&s===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,s),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=s),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class mu{static GetDefaults(e){const t=new mu;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class gu{constructor(e,t=mu.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new K,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{const e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add((()=>{this._addCanvas()})),e.onXRSessionEnded.add((()=>{this._removeCanvas()})),this._makeCanvasCompatibleAsync()}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}_makeCanvasCompatibleAsync(){this._canvasCompatiblePromise=new Promise((e=>{this.canvasContext&&this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then((()=>{e()})):e()}))}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new pu(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this._canvasCompatiblePromise.then((()=>{}),(()=>{Ds.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")})).then((()=>t()))}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce((()=>{this._setCanvasSize(!0)}))}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class vu extends du{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new xu(e,this))),this.layer=e}}class xu extends _u{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}}class bu{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}}class Tu{get worldScalingFactor(){return this._worldScalingFactor}set worldScalingFactor(e){const t=this._worldScalingFactor;this._worldScalingFactor=e,this.onWorldScaleFactorChangedObservable.notifyObservers({previousScaleFactor:t,newScaleFactor:e})}constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new K,this.onXRReferenceSpaceChanged=new K,this.onXRSessionEnded=new K,this.onXRSessionInit=new K,this.onXRReferenceSpaceInitialized=new K,this.onXRReady=new K,this.inXRFrameLoop=!1,this.inXRSession=!1,this._worldScalingFactor=1,this.onWorldScaleFactorChangedObservable=new K(void 0,!0),this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),this.onWorldScaleFactorChangedObservable.clear(),this._engine?.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}async exitXRAsync(){if(this.session&&this.inXRSession){this.inXRSession=!1;try{return await this.session.end()}catch{Ne.Warn("Could not end XR session.")}}return Promise.resolve()}trySetViewportForView(e,t){return this._baseLayerRTTProvider?.trySetViewportForView(e,t)||!1}getRenderTargetTextureForEye(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForEye(e)||null}getRenderTargetTextureForView(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForView(e)||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new bu(this):((e=e||mu.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new gu(this,e))}initializeAsync(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then((t=>(this.session=t,this._sessionMode=e,this.inXRSession=!0,this.onXRSessionInit.notifyObservers(t),this.session.addEventListener("end",(()=>{this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&this._baseLayerRTTProvider?.dispose(),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null}),{once:!0}),this.session)))}isSessionSupportedAsync(e){return Tu.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:e=>this.session.requestAnimationFrame(e),renderFunction:(e,t)=>{if(this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t)){this.inXRFrameLoop=!0;const e=this._baseLayerRTTProvider?.getFramebufferDimensions()||null;this._engine.framebufferDimensionsObject!==e&&(this._engine.framebufferDimensionsObject=e),this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1}}},this._engine.framebufferDimensionsObject=this._baseLayerRTTProvider?.getFramebufferDimensions()||null,this.onXRFrameObservable.addOnce((()=>{this.onXRReady.notifyObservers(this)})),"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then((e=>e),(e=>(Ne.Error("XR.requestReferenceSpace failed for the following reason: "),Ne.Error(e),Ne.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then((e=>{const t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)}),(e=>{throw Ne.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))))).then((e=>this.session.requestReferenceSpace("viewer").then((t=>(this.viewerReferenceSpace=t,e))))).then((e=>(this.referenceSpace=this.baseReferenceSpace=e,this.onXRReferenceSpaceInitialized.notifyObservers(e),this.referenceSpace)))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){this.isNative&&this._baseLayerRTTProvider?.dispose(),this._baseLayerWrapper=e,this._baseLayerRTTProvider=this._baseLayerWrapper?.createRenderTargetTextureProvider(this)||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new vu(e.baseLayer):new pu(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);const t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then((e=>{const t=void 0===e||e;return Promise.resolve(t)})).catch((e=>(Ne.Warn(e),Promise.resolve(!1)))):Promise.resolve(!1)}get isNative(){return this._xrNavigator.xr.native??!1}get currentFrameRate(){return this.session?.frameRate}get supportedFrameRates(){return this.session?.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():!this.inXRSession&&t||this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){return this._baseLayerWrapper?.isFixedFoveationSupported||!1}get fixedFoveation(){return this._baseLayerWrapper?.fixedFoveation||null}set fixedFoveation(e){const t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)}get enabledFeatures(){return this.session?.enabledFeatures??null}}var yu,Su;!function(e){e[e.ENTERING_XR=0]="ENTERING_XR",e[e.EXITING_XR=1]="EXITING_XR",e[e.IN_XR=2]="IN_XR",e[e.NOT_IN_XR=3]="NOT_IN_XR"}(yu||(yu={})),function(e){e[e.NOT_TRACKING=0]="NOT_TRACKING",e[e.TRACKING_LOST=1]="TRACKING_LOST",e[e.TRACKING=2]="TRACKING"}(Su||(Su={})),ha._GroundMeshParser=(e,t)=>Cu.Parse(e,t);class Cu extends ha{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),s=ve.Matrix[5];i.invertToRef(s);const r=ve.Vector3[8];if(_e.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const n=this._getFacetAt(e,t),o=-(n.x*e+n.z*t+n.w)/n.y;return _e.TransformCoordinatesFromFloatsToRef(0,o,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new _e(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),r=ve.Matrix[5];s.invertToRef(r);const n=ve.Vector3[8];if(_e.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t);return _e.TransformNormalFromFloatsToRef(o.x,o.y,o.z,s,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),s=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[s*this._subdivisionsX+i];let n;return n=te.maxHeight){h=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(n=0;n<=e.subdivisions;n++)for(o=0;o<=e.subdivisions;o++){const t=new _e(o*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-n)*e.height/e.subdivisions-e.height/2),c=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let u=e.buffer[c]/255,d=e.buffer[c+1]/255,_=e.buffer[c+2]/255;const p=e.buffer[c+3]/255;h&&(u=1-u,d=1-d,_=1-_);const f=u*a.r+d*a.g+_*a.b;t.y=p>=l?e.minHeight+(e.maxHeight-e.minHeight)*f:e.minHeight-J,e.heightBuffer&&(e.heightBuffer[n*(e.subdivisions+1)+o]=t.y),i.push(t.x,t.y,t.z),s.push(0,0,0),r.push(o/e.subdivisions,1-n/e.subdivisions)}for(n=0;n=e.minHeight,c=i[3*r+1]>=e.minHeight,u=i[3*a+1]>=e.minHeight;h&&c&&u&&(t.push(s),t.push(r),t.push(a)),i[3*l+1]>=e.minHeight&&h&&u&&(t.push(l),t.push(s),t.push(a))}Wn.ComputeNormals(i,t,s);const c=new Wn;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function Iu(e,t={},i){const s=new Cu(e,i);return s._setReady(!1),s._subdivisionsX=t.subdivisionsX||t.subdivisions||1,s._subdivisionsY=t.subdivisionsY||t.subdivisions||1,s._width=t.width||1,s._height=t.height||1,s._maxX=s._width/2,s._maxZ=s._height/2,s._minX=-s._maxX,s._minZ=-s._maxZ,Eu(t).applyToMesh(s,t.updatable),s._setReady(!0),s}function Ru(e,t,i=null){const s=new ha(e,i);return Au(t).applyToMesh(s,t.updatable),s}function Mu(e,t,i={},s=null){const r=i.width||10,n=i.height||10,o=i.subdivisions||1,a=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new Ee(.3,.59,.11),c=i.alphaFilter||0,u=i.updatable,d=i.onReady;s=s||re.LastCreatedScene;const _=new Cu(e,s);let p;_._subdivisionsX=o,_._subdivisionsY=o,_._width=r,_._height=n,_._maxX=_._width/2,_._maxZ=_._height/2,_._minX=-_._maxX,_._minZ=-_._maxZ,_._setReady(!1),i.passHeightBufferInCallback&&(p=new Float32Array((o+1)*(o+1)));const f=(e,t,i)=>{Pu({width:r,height:n,subdivisions:o,minHeight:a,maxHeight:l,colorFilter:h,buffer:e,bufferWidth:t,bufferHeight:i,alphaFilter:c,heightBuffer:p}).applyToMesh(_,u),d&&d(_,p),_._setReady(!0)};if("string"==typeof t){const e=e=>{const t=e.width,i=e.height;if(s.isDisposed)return;const r=s?.getEngine().resizeImageBitmap(e,t,i);f(r,t,i)};Ds.LoadImage(t,e,i.onError?i.onError:()=>{},s.offlineProvider)}else f(t.data,t.width,t.height);return _}const Ou={CreateGround:Iu,CreateGroundFromHeightMap:Mu,CreateTiledGround:Ru};function Du(e){const t=[],i=[],s=[],r=[],n=e.diameter||1,o=e.thickness||.5,a=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,h=a+1;for(let e=0;e<=a;e++){const l=e/a,c=e*Math.PI*2/a-Math.PI/2,u=me.Translation(n/2,0,0).multiply(me.RotationY(c));for(let n=0;n<=a;n++){const c=1-n/a,d=n*Math.PI*2/a+Math.PI,_=Math.cos(d),p=Math.sin(d);let f=new _e(_,p,0),m=f.scale(o/2);const g=new de(l,c);m=_e.TransformCoordinates(m,u),f=_e.TransformNormal(f,u),i.push(m.x,m.y,m.z),s.push(f.x,f.y,f.z),r.push(g.x,Xn.UseOpenGLOrientationForUV?1-g.y:g.y);const v=(e+1)%h,x=(n+1)%h;t.push(e*h+n),t.push(e*h+x),t.push(v*h+n),t.push(e*h+x),t.push(v*h+x),t.push(v*h+n)}}Wn._ComputeSides(l,i,t,s,r,e.frontUVs,e.backUVs);const c=new Wn;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function wu(e,t={},i){const s=new ha(e,i);return t.sideOrientation=ha._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,Du(t).applyToMesh(s,t.updatable),s}Wn.CreateGround=Eu,Wn.CreateTiledGround=Au,Wn.CreateGroundFromHeightMap=Pu,ha.CreateGround=(e,t,i,s,r,n)=>Iu(e,{width:t,height:i,subdivisions:s,updatable:n},r),ha.CreateTiledGround=(e,t,i,s,r,n,o,a,l)=>Ru(e,{xmin:t,zmin:i,xmax:s,zmax:r,subdivisions:n,precision:o,updatable:l},a),ha.CreateGroundFromHeightMap=(e,t,i,s,r,n,o,a,l,h,c)=>Mu(e,t,{width:i,height:s,subdivisions:r,minHeight:n,maxHeight:o,updatable:l,onReady:h,alphaFilter:c},a);const Nu={CreateTorus:wu};Wn.CreateTorus=Du,ha.CreateTorus=(e,t,i,s,r,n,o)=>wu(e,{diameter:t,thickness:i,tessellation:s,sideOrientation:o,updatable:n},r);class Fu{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=Fu._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=wu("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const t=new cu("targetMat",e);t.specularColor=Ee.Black(),t.emissiveColor=new Ee(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new Ua(_e.Zero(),new _e(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}}Fu._IdCounter=0;class Lu extends Fu{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new Ua(_e.Zero(),_e.Forward())}}class Bu{}class ku{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._scene.activeCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated}constructor(e,t={}){if(this.webVROptions=t,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new K,this.onAfterEnteringVRObservable=new K,this.onExitingVRObservable=new K,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=ku.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new _e(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new _e(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new Ee(.2,.2,1),this._pickedGazeColor=new Ee(0,0,1),this.onNewMeshSelected=new K,this.onNewMeshPicked=new K,this.onBeforeCameraTeleport=new K,this.onAfterCameraTeleport=new K,this.onSelectedMeshUnselected=new K,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock||(this._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=e=>{e.type!==kh.POSE_ENABLED&&(e.leftStick&&e.onleftstickchanged((e=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))})),e.rightStick&&e.onrightstickchanged((e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)})),e.type===kh.XBOX&&(e.onbuttondown((e=>{this._interactionsEnabled&&e===Oh.A&&this._cameraGazer._selectionPointerDown()})),e.onbuttonup((e=>{this._interactionsEnabled&&e===Oh.A&&this._cameraGazer._selectionPointerUp()}))))},this._workingVector=_e.Zero(),this._workingQuaternion=fe.Identity(),this._workingMatrix=me.Identity(),Ne.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement(),"getVRDisplays"in navigator||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new _e(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new cc("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof oc&&this._scene.activeCamera.rotation)){const e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(fe.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?Tu.IsSessionSupportedAsync("immersive-vr").then((i=>{i?(Ne.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then((t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new Lu((()=>this.xr.baseExperience.camera),e),this.xr.baseExperience.onStateChangedObservable.add((e=>{switch(e){case yu.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case yu.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case yu.IN_XR:this._hasEnteredVR=!0;break;case yu.NOT_IN_XR:this._hasEnteredVR=!1}}))}))):this._completeVRInit(e,t)})):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new Qc("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new Lu((()=>this.currentVRCamera),e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let e=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";e+=".babylonVRicon.vrdisplaypresenting { display: none; }";const t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",(()=>{this.isInVRMode||this.enterVR()}));const i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add((()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())}),lr.POINTERDOUBLETAP,!1),e.onDisposeObservable.add((()=>{this.dispose()})),this._updateButtonVisibility(),this._circleEase=new sn,this._circleEase.setEasingMode(tn.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add((t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===lr.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===lr.POINTERUP&&this._cameraGazer._selectionPointerUp())})),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===yu.IN_XR||this._fullscreenVRpresenting}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){const e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))}enterVR(){if(this.xr)this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);else{if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){Ne.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=fe.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce((()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})}))),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}}exitVR(){if(this.xr)this.xr.baseExperience.exitXRAsync();else if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){Ne.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this.xr)return void(this.xr.baseExperience.state===yu.IN_XR&&this.xr.pointerSelection.attach());this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>!!(this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}_isTeleportationFloor(e){for(let t=0;t-1||this._floorMeshesCollection.push(e))}removeFloorMesh(e){if(!this._floorMeshesCollection)return;const t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const t=e.floorMeshes||[];if(!t.length){const i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr)return t.forEach((e=>{this.xr.teleportation.addFloorMesh(e)})),void(this.xr.teleportation.attached||this.xr.teleportation.attach());if(!this.xrTestDone){const t=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(t),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};return void this._scene.registerBeforeRender(t)}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction);const t=new zs;t.vignetteColor=new Ae(0,0,0,0),t.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}}_checkTeleportWithRay(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;const e=fe.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,fe.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),_e.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const s=new Ua(i,this._workingVector),r=this._scene.pickWithRay(s,this._raySelectionPredicate);r&&r.pickedPoint&&r.pickedMesh&&this._isTeleportationFloor(r.pickedMesh)&&r.distance<5&&this.teleportCamera(r.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_createTeleportationCircles(){this._teleportationTarget=Iu("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=new uu("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;const t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();const i=new cu("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;const s=wu("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);s.isPickable=!1,s.parent=this._teleportationTarget;const r=new Ft("animationInnerCircle","position.y",30,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),r.setKeys(n);const o=new _n;o.setEasingMode(tn.EASINGMODE_EASEINOUT),r.setEasingFunction(o),s.animations=[],s.animations.push(r),this._scene.beginAnimation(s,0,60,!0),this._hideTeleportationTarget()}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof ac))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=fe.FromRotationMatrix(me.RotationY(Math.PI/4*this._rotationAngle)),i=new Ft("animationRotation","rotationQuaternion",90,Ft.ANIMATIONTYPE_QUATERNION,Ft.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),s.push({frame:6,value:t}),i.setKeys(s),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const r=new Ft("animationPP","vignetteWeight",90,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),r.setKeys(n),r.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(r);const o=new Ft("animationPP2","vignetteStretch",90,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:10}),a.push({frame:6,value:0}),o.setKeys(a),o.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(o),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}teleportCamera(e){if(!(this.currentVRCamera instanceof ac))return;let t,i;if(this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==ku.TELEPORTATIONMODE_CONSTANTSPEED){i=90;const e=_e.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];const s=new Ft("animationCameraTeleportation","position",90,Ft.ANIMATIONTYPE_VECTOR3,Ft.ANIMATIONLOOPMODE_CONSTANT),r=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];s.setKeys(r),s.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(s),this._postProcessMove.animations=[];const n=Math.round(i/2),o=new Ft("animationPP","vignetteWeight",90,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:n,value:8}),a.push({frame:i,value:0}),o.setKeys(a),this._postProcessMove.animations.push(o);const l=new Ft("animationPP2","vignetteStretch",90,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:n,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,(()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)})),this._hideTeleportationTarget()}setLaserColor(e,t=this._pickedLaserColor){this._pickedLaserColor=t}setLaserLightingState(e=!0){}setGazeColor(e,t=this._pickedGazeColor){this._pickedGazeColor=t}changeLaserColor(e){this.updateControllerLaserColor}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}}ku.TELEPORTATIONMODE_CONSTANTTIME=0,ku.TELEPORTATIONMODE_CONSTANTSPEED=1;const Vu=function(){const e={root:0,found:!1};return function(t,i,s,r){e.root=0,e.found=!1;const n=i*i-4*t*s;if(n<0)return e;const o=Math.sqrt(n);let a=(-i-o)/(2*t),l=(-i+o)/(2*t);if(a>l){const e=l;l=a,a=e}return a>0&&a0&&l=0))}_canDoCollision(e,t,i,s){const r=_e.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(r>this._velocityWorldLength+n+t||!((e,t,i,s)=>!(e.x>i.x+s||i.x-s>t.x||e.y>i.y+s||i.y-s>t.y||e.z>i.z+s||i.z-s>t.z))(i,s,this._basePointWorld,this._velocityWorldLength+n))}_testTriangle(e,t,i,s,r,n,o){let a,l=!1;t||(t=[]),t[e]||(t[e]=new Nr(0,0,0,0),t[e].copyFromPoints(i,s,r));const h=t[e];if(!n&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;const c=h.signedDistanceTo(this._basePoint),u=_e.Dot(h.normal,this._velocity);if(Uu.DoubleSidedCheck&&u>1e-4)return;if(0==u){if(Math.abs(c)>=1)return;l=!0,a=0}else{a=(-1-c)/u;let e=(1-c)/u;if(a>e){const t=e;e=a,a=t}if(a>1||e<0)return;a<0&&(a=0),a>1&&(a=1)}this._collisionPoint.copyFromFloats(0,0,0);let d=!1,_=1;if(l||(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(a,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,s,r,h.normal)&&(d=!0,_=a,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!d){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*_e.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=Vu(e,t,n,_);o.found&&(_=o.root,d=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(s,this._tempVector),t=2*_e.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=Vu(e,t,n,_),o.found&&(_=o.root,d=!0,this._collisionPoint.copyFrom(s)),this._basePoint.subtractToRef(r,this._tempVector),t=2*_e.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=Vu(e,t,n,_),o.found&&(_=o.root,d=!0,this._collisionPoint.copyFrom(r)),s.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let a=this._edge.lengthSquared(),l=_e.Dot(this._edge,this._velocity),h=_e.Dot(this._edge,this._baseToVertex);if(e=a*-this._velocitySquaredLength+l*l,t=2*(a*_e.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=Vu(e,t,n,_),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(_=o.root,d=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(r.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=_e.Dot(this._edge,this._velocity),h=_e.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*_e.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=Vu(e,t,n,_),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(_=o.root,d=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=_e.Dot(this._edge,this._velocity),h=_e.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*_e.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=Vu(e,t,n,_),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(_=o.root,d=!0,this._edge.scaleInPlace(e),r.addToRef(this._edge,this._collisionPoint))}}if(d){const e=_*_*this._velocitySquaredLength;(!this.collisionFound||e=s)return void r.copyFrom(e);const a=n?n.collisionMask:i.collisionMask;i._initialize(e,t,o);const l=n&&n.surroundingMeshes||this._scene.meshes;for(let e=0;enew Gu;class zu{constructor(e,t,i,s=""){let r;this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new K,this.onErrorObservable=new K,this.onBindObservable=new K,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=di.WGSL,this.name=e,this._key=s,this._engine=i,this.uniqueId=zu._UniqueIdSeed++,this.defines=t.defines??"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=t.entryPoint??"main",this._shaderStore=Bi.GetShadersStore(this._shaderLanguage),this._shaderRepository=Bi.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=Bi.GetIncludesShadersStore(this._shaderLanguage);const n=kt()?this._engine.getHostDocument():null;r="string"==typeof e?e:e.computeSource?"source:"+e.computeSource:e.computeElement?n?.getElementById(e.computeElement)||e.computeElement:e.compute||e;const o={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(r,"Compute","",(i=>{Ei(o),function(e,t,i,s){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),Ni(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const r=function(e,t,i){let s=e;const r=t.defines,n=wi(t,i);return t.processor?.preProcessor&&(s=t.processor.preProcessor(s,r,n,t.isFragment,t.processingContext)),s=Di(s,n,t),t.processor?.postProcessor&&(s=t.processor.postProcessor(s,r,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),i._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}(e,t,s);i(r,e)}))}(i,o,(s=>{this._rawComputeSourceCode=i,t.processFinalCode&&(s=t.processFinalCode(s));const r=Pi(s,"",o);this._useFinalCode(r.vertexCode,e)}),this._engine)}))}_useFinalCode(e,t){if(t){const i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}setTimeout((()=>{this._checkIsReady(e)}),16)}_loadShader(e,t,i,s){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void s(Gt(e));if("source:"===e.substr(0,7))return void s(e.substr(7));if("base64:"===e.substr(0,7))return void s(window.atob(e.substr(7)));if(this._shaderStore[e+t+"Shader"])return void s(this._shaderStore[e+t+"Shader"]);if(i&&this._shaderStore[e+i+"Shader"])return void s(this._shaderStore[e+i+"Shader"]);let r;r="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(r+"."+t.toLowerCase()+".fx",s)}get computeSourceCode(){return this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._pipelineContext?._getComputeShaderCode()??this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){const e=this.defines,t=this._pipelineContext;this._isReady=!1;try{const i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,(e=>{e&&e.numErrors>0?this._processCompilationErrors(e,t):(this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t))})),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_processCompilationErrors(e,t=null){if(this._compilationError="",Ne.Error("Unable to compile compute effect:"),this.defines&&Ne.Error("Defines:\n"+this.defines),zu.LogShaderCodeOnCompilationError){const e=this._pipelineContext?._getComputeShaderCode();e&&(Ne.Error("Compute code:"),Ne.Error(e))}if("string"==typeof e)this._compilationError=e,Ne.Error("Error: "+this._compilationError);else for(const t of e.messages){let e="";void 0!==t.line&&(e+="Line "+t.line+", "),void 0!==t.offset&&(e+="Offset "+t.offset+", "),void 0!==t.length&&(e+="Length "+t.length+", "),e+=t.type+": "+t.text,this._compilationError&&(this._compilationError+="\n"),this._compilationError+=e,Ne.Error(e)}t&&(this._pipelineContext=t,this._isReady=!0),this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){Bi.GetShadersStore(di.WGSL)[`${e}ComputeShader`]=t}}var Wu;zu._UniqueIdSeed=0,zu.LogShaderCodeOnCompilationError=!0,function(e){e[e.Texture=0]="Texture",e[e.StorageTexture=1]="StorageTexture",e[e.UniformBuffer=2]="UniformBuffer",e[e.StorageBuffer=3]="StorageBuffer",e[e.TextureWithoutSampler=4]="TextureWithoutSampler",e[e.Sampler=5]="Sampler",e[e.ExternalTexture=6]="ExternalTexture",e[e.DataBuffer=7]="DataBuffer"}(Wu||(Wu={})),qs.prototype.createComputeEffect=function(e,t){throw new Error("createComputeEffect: This engine does not support compute shaders!")},qs.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")},qs.prototype.createComputeContext=function(){},qs.prototype.computeDispatch=function(e,t,i,s,r,n,o){throw new Error("computeDispatch: This engine does not support compute shaders!")},qs.prototype.computeDispatchIndirect=function(e,t,i,s,r,n){throw new Error("computeDispatchIndirect: This engine does not support compute shaders!")},qs.prototype.areAllComputeEffectsReady=function(){return!0},qs.prototype.releaseComputeEffects=function(){},qs.prototype._prepareComputePipelineContext=function(e,t,i,s,r){},qs.prototype._rebuildComputeEffects=function(){},ns.prototype._executeWhenComputeStateIsCompiled=function(e,t){t(null)},qs.prototype._releaseComputeEffect=function(e){},qs.prototype._deleteComputePipelineContext=function(e){};class Hu{constructor(){this._gpuTimeInFrameId=-1,this.counter=new wr}_addDuration(e,t){e{const n=()=>{this.dispatch(e,t,i)?r():setTimeout(n,s)};n()}))}serialize(){const e=St.Serialize(this);e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={};for(const t in this._bindings){const i=this._bindings[t],s=i.object;switch(i.type){case Wu.Texture:case Wu.TextureWithoutSampler:case Wu.StorageTexture:{const r=s.serialize();r&&(e.textures[t]=r,e.bindings[t]={type:i.type});break}case Wu.UniformBuffer:}}return e}static Parse(e,t,i){const s=St.Parse((()=>new Xu(e.name,t.getEngine(),e.shaderPath,e.options)),e,t,i);for(const r in e.textures){const n=e.bindings[r],o=Pa.Parse(e.textures[r],t,i);n.type===Wu.Texture?s.setTexture(r,o):n.type===Wu.TextureWithoutSampler?s.setTexture(r,o,!1):s.setStorageTexture(r,o)}return s}static _BufferIsDataBuffer(e){return void 0!==e.underlyingResource}}Ze([rt()],Xu.prototype,"name",void 0),Ze([rt()],Xu.prototype,"fastMode",void 0),z("BABYLON.ComputeShader",Xu);class Yu{constructor(e,t,i,s,r,n){this.entries=[],this._boundingVectors=new Array,this._capacity=i,this._depth=s,this._maxDepth=r,this._creationFunc=n,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks)for(let t=0;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{const i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},Qu.CreationFuncForSubMeshes=(e,t)=>{e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},Hr.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(or.NAME_OCTREE);i||(i=new ju(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new Qu(Qu.CreationFuncForMeshes,e,t));const s=this.getWorldExtends();return this._selectionOctree.update(s.min,s.max,this.meshes),this._selectionOctree},Object.defineProperty(Hr.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),_o.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){const i=this.getScene();let s=i._getComponent(or.NAME_OCTREE);s||(s=new ju(i),i._addComponent(s)),this._submeshesOctree||(this._submeshesOctree=new Qu(Qu.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);const r=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(r.minimumWorld,r.maximumWorld,this.subMeshes),this._submeshesOctree};class ju{constructor(e){this.name=or.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new Ua(_e.Zero(),new _e(1,1,1)),(e=e||re.LastCreatedScene)&&(this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=e=>this.getActiveSubMeshCandidates(e),this.scene.getCollidingSubMeshCandidates=(e,t)=>this.getCollidingSubMeshCandidates(e,t),this.scene.getIntersectingSubMeshCandidates=(e,t)=>this.getIntersectingSubMeshCandidates(e,t))}register(){this.scene.onMeshRemovedObservable.add((e=>{const t=this.scene.selectionOctree;if(null!=t){const i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}})),this.scene.onMeshImportedObservable.add((e=>{const t=this.scene.selectionOctree;null!=t&&t.addMesh(e)}))}getActiveMeshCandidates(){return this.scene._selectionOctree?.select(this.scene.frustumPlanes)||this.scene._getDefaultMeshCandidates()}getActiveSubMeshCandidates(e){return e._submeshesOctree&&e.useOctreeForRenderingSelection?e._submeshesOctree.select(this.scene.frustumPlanes):this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){return e._submeshesOctree&&e.useOctreeForPicking?(Ua.TransformToRef(t,e.getWorldMatrix(),this._tempRay),e._submeshesOctree.intersectsRay(this._tempRay)):this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){const i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z);return e._submeshesOctree.intersects(t._basePointWorld,i)}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}}function Ku(e){const t=e.height||2;let i=0===e.diameterTop?0:e.diameterTop||e.diameter||1,s=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;i=i||1e-5,s=s||1e-5;const r=0|(e.tessellation||24),n=0|(e.subdivisions||1),o=!!e.hasRings,a=!!e.enclose,l=0===e.cap?0:e.cap||ha.CAP_ALL,h=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,c=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,u=e.faceUV||new Array(3),d=e.faceColors,_=2+(1+(1!==h&&a?2:0))*(o?n:1);let p;for(p=0;p<_;p++)d&&void 0===d[p]&&(d[p]=new Ae(1,1,1,1));for(p=0;p<_;p++)u&&void 0===u[p]&&(u[p]=new pe(0,0,1,1));const f=[],m=[],g=[],v=[],x=[],b=2*Math.PI*h/r;let T,y,S;const C=(s-i)/2/t,E=_e.Zero(),A=_e.Zero(),P=_e.Zero(),I=_e.Zero(),R=_e.Zero(),M=Xr.Y;let O,D,w,N=1,F=1,L=0,B=0;for(O=0;O<=n;O++)for(y=O/n,S=(y*(i-s)+s)/2,N=o&&0!==O&&O!==n?2:1,w=0;w{const n=e?i/2:s/2;if(0===n)return;let o,a,l;const c=e?u[_-1]:u[0];let p=null;d&&(p=e?d[_-1]:d[0]);const b=m.length/3,T=e?t/2:-t/2,y=new _e(0,T,0);m.push(y.x,y.y,y.z),g.push(0,e?1:-1,0);const S=c.y+.5*(c.w-c.y);v.push(c.x+.5*(c.z-c.x),Xn.UseOpenGLOrientationForUV?1-S:S),p&&x.push(p.r,p.g,p.b,p.a);const C=new de(.5,.5);for(l=0;l<=r;l++){o=2*Math.PI*l*h/r;const t=Math.cos(-o),i=Math.sin(-o);a=new _e(t*n,T,i*n);const s=new de(t*C.x+.5,i*C.y+.5);m.push(a.x,a.y,a.z),g.push(0,e?1:-1,0);const u=c.y+(c.w-c.y)*s.y;v.push(c.x+(c.z-c.x)*s.x,Xn.UseOpenGLOrientationForUV?1-u:u),p&&x.push(p.r,p.g,p.b,p.a)}for(l=0;l(void 0!==o&&o instanceof Hr||(void 0!==o&&(l=a||ha.DEFAULTSIDE,a=o),o=n,n=1),$u(e,{height:t,diameterTop:i,diameterBottom:s,tessellation:r,subdivisions:n,sideOrientation:l,updatable:a},o)),Et.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new Zu(e,_e.Zero(),t)));class Zu extends ua{constructor(e,t,i){super(e,i),this.groundColor=new Ee(0,0,0),this.direction=t||_e.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=_e.Normalize(e.subtract(_e.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=_e.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){const i=_e.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=me.Identity()),this._worldMatrix}getTypeID(){return ua.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}Ze([ot()],Zu.prototype,"groundColor",void 0),Ze([ht()],Zu.prototype,"direction",void 0),z("BABYLON.HemisphericLight",Zu);class Ju{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new Zu("shared gizmo light",new _e(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=Ee.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==Ju._DefaultUtilityLayer?Ju._CreateDefaultUtilityLayerFromScene(re.LastCreatedScene):Ju._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return Ju._DefaultUtilityLayer=new Ju(e),Ju._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{Ju._DefaultUtilityLayer=null})),Ju._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==Ju._DefaultKeepDepthUtilityLayer&&(Ju._DefaultKeepDepthUtilityLayer=new Ju(re.LastCreatedScene),Ju._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,Ju._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{Ju._DefaultKeepDepthUtilityLayer=null}))),Ju._DefaultKeepDepthUtilityLayer}constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new K,this.utilityLayerScene=new Hr(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add((t=>{if(!this.utilityLayerScene.activeCamera)return;if(!this.pickingEnabled)return;if(!this.processAllEvents&&t.type!==lr.POINTERMOVE&&t.type!==lr.POINTERUP&&t.type!==lr.POINTERDOWN&&t.type!==lr.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const i=t.event;if(e.isPointerCaptured(i.pointerId))return void(this._pointerCaptures[i.pointerId]=!1);const s=i=>{let s=null;if(t.nearInteractionPickingInfo)s=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new tr;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)s=t.originalPickingInfo;else{let r=null;this._renderCamera&&(r=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),s=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),r&&(i._activeCamera=r)}return s},r=s(this.utilityLayerScene);if(!t.ray&&r&&(t.ray=r.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=lr.POINTERDOWN)return t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new ur(t.type,t.event,r),t.type),void(t.type===lr.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1));if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)r&&r.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new ur(t.type,t.event,r),t.type),t.skipOnPointerObservable=!0);else{const i=s(e),n=t.event;i&&r&&(0===r.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):t.type===lr.POINTERDOWN?this._pointerCaptures[n.pointerId]=!0:t.type!==lr.POINTERMOVE&&t.type!==lr.POINTERUP||(this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,i,n)):!this._pointerCaptures[n.pointerId]&&(r.distance0)):!this._pointerCaptures[n.pointerId]&&r.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):(t.type!==lr.POINTERMOVE&&t.type!==lr.POINTERUP||this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,r,n))),t.type===lr.POINTERUP&&this._pointerCaptures[n.pointerId]&&(this._pointerCaptures[n.pointerId]=!1))}})),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add((e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add((()=>{this.dispose()})),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new ur(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){const e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}}var ed,td,id;Ju._DefaultUtilityLayer=null,Ju._DefaultKeepDepthUtilityLayer=null,function(e){e[e.Origin=0]="Origin",e[e.Pivot=1]="Pivot"}(ed||(ed={})),function(e){e[e.World=0]="World",e[e.Local=1]="Local"}(td||(td={}));class sd{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach((e=>{e.dispose()})),e.parent=this._rootMesh,this._customMeshSet=!0}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){this._additionalTransformNode=e}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;const t=e==td.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=Ju.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=ed.Origin,this._updateScale=!0,this._coordinatesMode=td.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=me.RotationY(Math.PI),this._rootMesh=new ha("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=fe.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add((()=>{this._update()}))}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh)if(this.anchorPoint==ed.Pivot&&e.getAbsolutePivotPoint){const t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{const t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new _e(0,0,0);this._rootMesh.position.copyFrom(i)}if(this.updateGizmoRotationToMatchAttachedMesh){const t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName()?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,sd.PreserveScaling?t:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){const t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,ve.Vector3[0]);let s=this.scaleRatio;if(t.mode==In.ORTHOGRAPHIC_CAMERA)t.orthoTop&&t.orthoBottom&&(s*=t.orthoTop-t.orthoBottom);else{const e=t.getScene().useRightHandedSystem?_e.RightHandedForwardReadOnly:_e.LeftHandedForwardReadOnly,i=t.getDirection(e);s*=_e.Dot(ve.Vector3[0],i)}this._rootMesh.scaling.setAll(s),e._getWorldMatrixDeterminant()<0&&!sd.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}this.additionalTransformNode&&(this._rootMesh.computeWorldMatrix(!0),this._rootMesh.getWorldMatrix().multiplyToRef(this.additionalTransformNode.getWorldMatrix(),ve.Matrix[0]),ve.Matrix[0].decompose(this._rootMesh.scaling,this._rootMesh.rotationQuaternion,this._rootMesh.position))}_handlePivotMatrixInverse(e,t,i){if(e.isUsingPivotMatrix()&&!e.isUsingPostMultiplyPivotMatrix())return e.getPivotMatrix().invertToRef(ve.Matrix[5]),void ve.Matrix[5].multiplyToRef(t,i);i.copyFrom(t)}_matrixChanged(){if(this._attachedNode)if(this._attachedNode._isCamera){const e=this._attachedNode;let t,i;if(e.parent){const i=ve.Matrix[1];e.parent._worldMatrix.invertToRef(i),this._attachedNode._worldMatrix.multiplyToRef(i,ve.Matrix[0]),t=ve.Matrix[0]}else t=this._attachedNode._worldMatrix;if(e.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(t,ve.Matrix[1]),i=ve.Matrix[1]):i=t,i.decompose(ve.Vector3[1],ve.Quaternion[0],ve.Vector3[0]),"FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName()){const e=this._attachedNode;e.rotation=ve.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(ve.Quaternion[0]),e.rotationQuaternion.normalize())}e.position.copyFrom(ve.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){const e=this._attachedNode;if(e.parent){const t=ve.Matrix[0],i=ve.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i);const s=ve.Matrix[4];if(this._handlePivotMatrixInverse(e,i,s),s.decompose(ve.Vector3[0],ve.Quaternion[0],e.position,sd.PreserveScaling?e:void 0,sd.UseAbsoluteScaling),ve.Quaternion[0].normalize(),e.isUsingPivotMatrix()){const t=ve.Quaternion[1];fe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,t);const i=ve.Matrix[2];me.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,i);const s=ve.Matrix[2];t.toRotationMatrix(s);const r=e.getPivotMatrix(),n=ve.Matrix[3];r.invertToRef(n),r.multiplyToRef(i,ve.Matrix[4]),ve.Matrix[4].multiplyToRef(s,ve.Matrix[5]),ve.Matrix[5].multiplyToRef(n,ve.Matrix[6]),ve.Matrix[6].getTranslationToRef(ve.Vector3[1]),e.position.subtractInPlace(ve.Vector3[1])}}else{const t=ve.Matrix[4];this._handlePivotMatrixInverse(e,this._attachedNode._worldMatrix,t),t.decompose(ve.Vector3[0],ve.Quaternion[0],e.position,sd.PreserveScaling?e:void 0,sd.UseAbsoluteScaling)}ve.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(ve.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(ve.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=ve.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){const e=this._attachedNode,t=e.getParent();if(t){const i=ve.Matrix[0],s=ve.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,s),e.getLocalMatrix().copyFrom(s)}else e.getLocalMatrix().copyFrom(e.getFinalMatrix());e.markAsDirty()}else{const e=this._attachedNode;if(e.getTypeID){const t=e.getTypeID();if(t===ua.LIGHTTYPEID_DIRECTIONALLIGHT||t===ua.LIGHTTYPEID_SPOTLIGHT||t===ua.LIGHTTYPEID_POINTLIGHT){const t=e.parent;if(t){const i=ve.Matrix[0],s=ve.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,s),s.decompose(void 0,ve.Quaternion[0],ve.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,ve.Quaternion[0],ve.Vector3[0]);e.position=new _e(ve.Vector3[0].x,ve.Vector3[0].y,ve.Vector3[0].z),e.direction&&(e.direction=new _e(e.direction.x,e.direction.y,e.direction.z))}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach((e=>{e.material=t,e.color&&(e.color=t.diffuseColor)}))}static GizmoAxisPointerObserver(e,t){let i=!1;return e.utilityLayerScene.onPointerObservable.add((e=>{if(e.pickInfo){if(e.type===lr.POINTERMOVE){if(i)return;t.forEach((t=>{if(t.colliderMeshes&&t.gizmoMeshes){const i=-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh),s=t.dragBehavior.enabled?i||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=s,e.color&&(e.color=s.diffuseColor)}))}}))}e.type===lr.POINTERDOWN&&t.has(e.pickInfo.pickedMesh?.parent)&&(i=!0,t.get(e.pickInfo.pickedMesh?.parent).active=!0,t.forEach((t=>{const i=(-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh)||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=i,e.color&&(e.color=i.diffuseColor)}))}))),e.type===lr.POINTERUP&&t.forEach((e=>{e.active=!1,i=!1,e.gizmoMeshes.forEach((t=>{t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)}))}))}}))}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}sd.PreserveScaling=!1,sd.UseAbsoluteScaling=!0;class rd extends sd{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreateArrow(e,t,i=1,s=!1){const r=new lo("arrow",e),n=$u("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375*(1+(i-1)/4),tessellation:96},e),o=$u("cylinder",{diameterTop:.005*i,height:.275,diameterBottom:.005*i,tessellation:96},e);return n.parent=r,n.material=t,n.rotation.x=Math.PI/2,n.position.z+=.3,o.parent=r,o.material=t,o.position.z+=.1375,o.rotation.x=Math.PI/2,s&&(o.visibility=0,n.visibility=0),r}static _CreateArrowInstance(e,t){const i=new lo("arrow",e);for(const e of t.getChildMeshes())e.createInstance(e.name).parent=i;return i}constructor(e,t=Ee.Gray(),i=Ju.DefaultUtilityLayer,s=null,r=1,n=Ee.Yellow(),o=Ee.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new K,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._parent=s,this._coloredMaterial=new cu("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ee(.1,.1,.1)),this._hoverMaterial=new cu("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new cu("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4;const a=rd._CreateArrow(i.utilityLayerScene,this._coloredMaterial,r),l=rd._CreateArrow(i.utilityLayerScene,this._coloredMaterial,r+4,!0);this._gizmoMesh=new ha("",i.utilityLayerScene),this._gizmoMesh.addChild(a),this._gizmoMesh.addChild(l),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let h=0;const c={snapDistance:0};this.dragBehavior=new Xa({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add((e=>{if(this.attachedNode){let t=!1;if(0==this.snapDistance)this.attachedNode.getWorldMatrix().getTranslationToRef(ve.Vector3[2]),ve.Vector3[2].addInPlace(e.delta),this.dragBehavior.validateDrag(ve.Vector3[2])&&(this.attachedNode.position&&this.attachedNode.position.addInPlaceFromFloats(e.delta.x,e.delta.y,e.delta.z),this.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z),this.attachedNode.updateCache(),t=!0);else if(h+=e.dragDistance,Math.abs(h)>this.snapDistance){const i=Math.floor(Math.abs(h)/this.snapDistance);h%=this.snapDistance,e.delta.normalizeToRef(ve.Vector3[1]),ve.Vector3[1].scaleInPlace(this.snapDistance*i),this.attachedNode.getWorldMatrix().getTranslationToRef(ve.Vector3[2]),ve.Vector3[2].addInPlace(ve.Vector3[1]),this.dragBehavior.validateDrag(ve.Vector3[2])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(ve.Vector3[1].x,ve.Vector3[1].y,ve.Vector3[1].z),this.attachedNode.updateCache(),c.snapDistance=this.snapDistance*i*Math.sign(h),this.onSnapObservable.notifyObservers(c),t=!0)}t&&this._matrixChanged()}})),this.dragBehavior.onDragStartObservable.add((()=>{this._dragging=!0})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1}));const u=i._getSharedGizmoLight();u.includedOnlyMeshes=u.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const d={gizmoMeshes:a.getChildMeshes(),colliderMeshes:l.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(l,d),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this._isHovered=!(-1==d.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(d.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(d.gizmoMeshes,e?d.material:d.disableMaterial)}))}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}class nd{get scaleLines(){return this._scaleLines}set scaleLines(e){this._scaleLines=e,this._xAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._yAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._zAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor)}get xAxis(){return this._xAxis}get yAxis(){return this._yAxis}get zAxis(){return this._zAxis}constructor(e,t=1,i=2,s,r,n,o=1){if(this._scaleLinesFactor=4,this._instanced=!1,this.scene=null,this._scaleLines=1,e=e||re.LastCreatedScene){if(!s){const t=new cu("xAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=Ee.Red().scale(.5),s=rd._CreateArrow(e,t,o)}if(!r){const t=new cu("yAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=Ee.Green().scale(.5),r=rd._CreateArrow(e,t,o)}if(!n){const t=new cu("zAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=Ee.Blue().scale(.5),n=rd._CreateArrow(e,t,o)}this._xAxis=s,this._yAxis=r,this._zAxis=n,this.scaleLines=t,null!=i&&(nd._SetRenderingGroupId(this._xAxis,i),nd._SetRenderingGroupId(this._yAxis,i),nd._SetRenderingGroupId(this._zAxis,i)),this.scene=e,this.update(new _e,_e.Right(),_e.Up(),_e.Forward())}}update(e,t,i,s){this._xAxis.position.copyFrom(e),this._xAxis.setDirection(t),this._yAxis.position.copyFrom(e),this._yAxis.setDirection(i),this._zAxis.position.copyFrom(e),this._zAxis.setDirection(s)}createInstance(){const e=rd._CreateArrowInstance(this.scene,this._xAxis),t=rd._CreateArrowInstance(this.scene,this._yAxis),i=rd._CreateArrowInstance(this.scene,this._zAxis),s=new nd(this.scene,this.scaleLines,null,e,t,i);return s._instanced=!0,s}dispose(){this._xAxis&&this._xAxis.dispose(!1,!this._instanced),this._yAxis&&this._yAxis.dispose(!1,!this._instanced),this._zAxis&&this._zAxis.dispose(!1,!this._instanced),this.scene=null}static _SetRenderingGroupId(e,t){e.getChildMeshes().forEach((e=>{e.renderingGroupId=t}))}}class od extends nd{constructor(e,t,i,s=1){super(e,s),this.pos=_e.Zero(),this.xaxis=_e.Zero(),this.yaxis=_e.Zero(),this.zaxis=_e.Zero(),this.mesh=i,this.bone=t}update(){if(!this.mesh||!this.bone)return;const e=this.bone;e.getAbsolutePositionToRef(this.mesh,this.pos),e.getDirectionToRef(Xr.X,this.mesh,this.xaxis),e.getDirectionToRef(Xr.Y,this.mesh,this.yaxis),e.getDirectionToRef(Xr.Z,this.mesh,this.zaxis),super.update(this.pos,this.xaxis,this.yaxis,this.zaxis)}dispose(){this.mesh&&(this.mesh=null,this.bone=null,super.dispose())}}Object.defineProperty(Hr.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new ad(this)),this._debugLayer},enumerable:!0,configurable:!0}),function(e){e[e.Properties=0]="Properties",e[e.Debug=1]="Debug",e[e.Statistics=2]="Statistics",e[e.Tools=3]="Tools",e[e.Settings=4]="Settings"}(id||(id={}));class ad{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new K),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new K),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||re.LastCreatedScene,this._scene&&this._scene.onDisposeObservable.add((()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()}))}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(const e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(const e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}const t={...ad.Config,...e};this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise((t=>{if(void 0===this.BJSINSPECTOR){const i=e&&e.inspectorURL?e.inspectorURL:ad.InspectorURL;Ds.LoadBabylonScript(i,(()=>{this._createInspector(e),t(this)}))}else this._createInspector(e),t(this)}))}}function ld(e){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],s=[];let r=[];const n=e.width||e.size||1,o=e.height||e.size||1,a=e.depth||e.size||1,l=e.wrap||!1;let h=void 0===e.topBaseAt?1:e.topBaseAt,c=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,c=(c+4)%4;let u=[2,0,3,1][h],d=[2,0,1,3][c],_=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(l){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],_=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let e=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],i=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const s=[17,18,19,16],r=[22,23,20,21];for(;u>0;)e.unshift(e.pop()),s.unshift(s.pop()),u--;for(;d>0;)i.unshift(i.pop()),r.unshift(r.pop()),d--;e=e.flat(),i=i.flat(),_=_.concat(e).concat(i),t.push(s[0],s[2],s[3],s[0],s[1],s[2]),t.push(r[0],r[2],r[3],r[0],r[1],r[2])}const p=[n/2,o/2,a/2];r=_.reduce(((e,t,i)=>e.concat(t*p[i%3])),[]);const f=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,m=e.faceUV||new Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new pe(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new Ae(1,1,1,1));for(let e=0;e<6;e++)if(s.push(m[e].z,Xn.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),s.push(m[e].x,Xn.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),s.push(m[e].x,Xn.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),s.push(m[e].z,Xn.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);Wn._ComputeSides(f,r,t,i,s,e.frontUVs,e.backUVs);const x=new Wn;if(x.indices=t,x.positions=r,x.normals=i,x.uvs=s,g){const e=f===Wn.DOUBLESIDE?v.concat(v):v;x.colors=e}return x}function hd(e){const t=e.width||e.size||1,i=e.height||e.size||1,s=e.depth||e.size||1,r=0|(e.widthSegments||e.segments||1),n=0|(e.heightSegments||e.segments||1),o=0|(e.depthSegments||e.segments||1),a=new me,l=new me,h=new me,c=Eu({width:t,height:s,subdivisionsX:r,subdivisionsY:o});me.TranslationToRef(0,-i/2,0,l),me.RotationZToRef(Math.PI,a),a.multiplyToRef(l,h),c.transform(h);const u=Eu({width:t,height:s,subdivisionsX:r,subdivisionsY:o});me.TranslationToRef(0,i/2,0,h),u.transform(h);const d=Eu({width:i,height:s,subdivisionsX:n,subdivisionsY:o});me.TranslationToRef(-t/2,0,0,l),me.RotationZToRef(Math.PI/2,a),a.multiplyToRef(l,h),d.transform(h);const _=Eu({width:i,height:s,subdivisionsX:n,subdivisionsY:o});me.TranslationToRef(t/2,0,0,l),me.RotationZToRef(-Math.PI/2,a),a.multiplyToRef(l,h),_.transform(h);const p=Eu({width:t,height:i,subdivisionsX:r,subdivisionsY:n});me.TranslationToRef(0,0,-s/2,l),me.RotationXToRef(-Math.PI/2,a),a.multiplyToRef(l,h),p.transform(h);const f=Eu({width:t,height:i,subdivisionsX:r,subdivisionsY:n});return me.TranslationToRef(0,0,s/2,l),me.RotationXToRef(Math.PI/2,a),a.multiplyToRef(l,h),f.transform(h),c.merge([u,_,d,p,f],!0),c}function cd(e,t={},i=null){const s=new ha(e,i);return t.sideOrientation=ha._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,ld(t).applyToMesh(s,t.updatable),s}ad.InspectorURL=`${Ds._DefaultCdnUrl}/v${oo.Version}/inspector/babylon.inspector.bundle.js`,ad.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0};const ud={CreateBox:cd};function dd(e){const t=0|(e.segments||32),i=e.diameterX||e.diameter||1,s=e.diameterY||e.diameter||1,r=e.diameterZ||e.diameter||1,n=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,o=e.slice&&e.slice<=0?1:e.slice||1,a=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new _e(i/2,s/2,r/2),c=2+t,u=2*c,d=[],_=[],p=[],f=[];for(let e=0;e<=c;e++){const t=e/c,i=t*Math.PI*o;for(let e=0;e<=u;e++){const s=e/u,r=s*Math.PI*2*n,o=me.RotationZ(-i),a=me.RotationY(r),l=_e.TransformCoordinates(_e.Up(),o),c=_e.TransformCoordinates(l,a),d=c.multiply(h),m=c.divide(h).normalize();_.push(d.x,d.y,d.z),p.push(m.x,m.y,m.z),f.push(s,Xn.UseOpenGLOrientationForUV?1-t:t)}if(e>0){const t=_.length/3;for(let i=t-2*(u+1);i+u+21&&(d.push(i),d.push(i+1),d.push(i+u+1)),(ecd(e,{size:t,sideOrientation:r,updatable:s},i);const pd={CreateSphere:_d};function fd(e={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const t=0|Math.max(e.subdivisions?e.subdivisions:2,1),i=0|Math.max(e.tessellation?e.tessellation:16,3),s=Math.max(e.height?e.height:1,0),r=Math.max(e.radius?e.radius:.25,0),n=0|Math.max(e.capSubdivisions?e.capSubdivisions:6,1),o=i,a=t,l=Math.max(e.radiusTop?e.radiusTop:r,0),h=Math.max(e.radiusBottom?e.radiusBottom:r,0),c=s-(l+h),u=2*Math.PI,d=Math.max(e.topCapSubdivisions?e.topCapSubdivisions:n,1),_=Math.max(e.bottomCapSubdivisions?e.bottomCapSubdivisions:n,1),p=Math.acos((h-l)/s);let f=[];const m=[],g=[],v=[];let x=0;const b=[],T=.5*c,y=.5*Math.PI;let S,C;const E=_e.Zero(),A=_e.Zero(),P=Math.cos(p),I=Math.sin(p),R=new de(l*I,T+l*P).subtract(new de(h*I,h*P-T)).length(),M=l*p+R+h*(y-p);let O=0;for(C=0;C<=d;C++){const e=[],t=y-p*(C/d);O+=l*p/d;const i=Math.cos(t),s=Math.sin(t),r=i*l;for(S=0;S<=o;S++){const t=S/o,n=t*u+0,a=Math.sin(n),h=Math.cos(n);A.x=r*a,A.y=T+s*l,A.z=r*h,m.push(A.x,A.y,A.z),E.set(i*a,s,i*h),g.push(E.x,E.y,E.z),v.push(t,Xn.UseOpenGLOrientationForUV?O/M:1-O/M),e.push(x),x++}b.push(e)}const D=s-l-h+P*l-P*h,w=I*(h-l)/D;for(C=1;C<=a;C++){const e=[];O+=R/a;const t=I*(C*(h-l)/a+l);for(S=0;S<=o;S++){const i=S/o,s=i*u+0,r=Math.sin(s),n=Math.cos(s);A.x=t*r,A.y=T+P*l-C*D/a,A.z=t*n,m.push(A.x,A.y,A.z),E.set(r,w,n).normalize(),g.push(E.x,E.y,E.z),v.push(i,Xn.UseOpenGLOrientationForUV?O/M:1-O/M),e.push(x),x++}b.push(e)}for(C=1;C<=_;C++){const e=[],t=y-p-(Math.PI-p)*(C/_);O+=h*p/_;const i=Math.cos(t),s=Math.sin(t),r=i*h;for(S=0;S<=o;S++){const t=S/o,n=t*u+0,a=Math.sin(n),l=Math.cos(n);A.x=r*a,A.y=s*h-T,A.z=r*l,m.push(A.x,A.y,A.z),E.set(i*a,s,i*l),g.push(E.x,E.y,E.z),v.push(t,Xn.UseOpenGLOrientationForUV?O/M:1-O/M),e.push(x),x++}b.push(e)}for(S=0;S_d(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:n,updatable:r},s);const gd={CreateCapsule:md};function vd(e){let t=e.pathArray;const i=e.closeArray||!1,s=e.closePath||!1,r=e.invertUV||!1,n=Math.floor(t[0].length/2);let o=e.offset||n;o=o>n?n:Math.floor(o);const a=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,l=e.uvs,h=e.colors,c=[],u=[],d=[],_=[],p=[],f=[],m=[],g=[];let v;const x=[],b=[];let T,y,S;if(t.length<2){const e=[],i=[];for(y=0;y0&&(R=P[S].subtract(P[S-1]).length(),M=R+m[T],p[T].push(M),m[T]=M),S++;s&&(S--,c.push(P[0].x,P[0].y,P[0].z),R=P[S].subtract(P[0]).length(),M=R+m[T],p[T].push(M),m[T]=M),x[T]=I+E,b[T]=C,C+=I+E}let w,N,F=null,L=null;for(y=0;y{let r=s[0].length;const n=a;let o=0;const l=n._originalBuilderSideOrientation===ha.DOUBLESIDE?2:1;for(let a=1;a<=l;++a)for(let a=0;amd(e,t,i),Wn.CreateCapsule=fd;const bd={CreateRibbon:xd};function Td(e){const t=[],i=[],s=[],r=[],n=e.radius||.5,o=e.tessellation||64,a=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE;t.push(0,0,0),r.push(.5,.5);const h=2*Math.PI*a,c=1===a?h/o:h/(o-1);let u=0;for(let e=0;exd(e,{pathArray:t,closeArray:i,closePath:s,offset:r,updatable:o,sideOrientation:a,instance:l},n);const Sd={CreateDisc:yd};function Cd(e){const t=e.pattern||ha.NO_FLIP,i=e.tileWidth||e.tileSize||1,s=e.tileHeight||e.tileSize||1,r=e.alignHorizontal||0,n=e.alignVertical||0,o=e.width||e.size||1,a=Math.floor(o/i);let l=o-a*i;const h=e.height||e.size||1,c=Math.floor(h/s);let u=h-c*s;const d=i*a/2,_=s*c/2;let p=0,f=0,m=0,g=0,v=0,x=0;if(l>0||u>0){switch(m=-d,g=-_,v=d,x=_,r){case ha.CENTER:l/=2,m-=l,v+=l;break;case ha.LEFT:v+=l,p=-l/2;break;case ha.RIGHT:m-=l,p=l/2}switch(n){case ha.CENTER:u/=2,g-=u,x+=u;break;case ha.BOTTOM:x+=u,f=-u/2;break;case ha.TOP:g-=u,f=u/2}}const b=[],T=[],y=[];y[0]=[0,0,1,0,1,1,0,1],y[1]=[0,0,1,0,1,1,0,1],t!==ha.ROTATE_TILE&&t!==ha.ROTATE_ROW||(y[1]=[1,1,0,1,0,0,1,0]),t!==ha.FLIP_TILE&&t!==ha.FLIP_ROW||(y[1]=[1,0,0,0,0,1,1,1]),t!==ha.FLIP_N_ROTATE_TILE&&t!==ha.FLIP_N_ROTATE_ROW||(y[1]=[0,1,1,1,1,0,0,0]);let S=[];const C=[],E=[];let A=0;for(let e=0;e0||u>0){const e=u>0&&(n===ha.CENTER||n===ha.TOP),o=u>0&&(n===ha.CENTER||n===ha.BOTTOM),h=l>0&&(r===ha.CENTER||r===ha.RIGHT),y=l>0&&(r===ha.CENTER||r===ha.LEFT);let P,I,R,M,O=[];if(e&&h&&(b.push(m+p,g+f,0),b.push(-d+p,g+f,0),b.push(-d+p,g+u+f,0),b.push(m+p,g+u+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=1-l/i,I=1-u/s,R=1,M=1,O=[P,I,R,I,R,M,P,M],t===ha.ROTATE_ROW&&(O=[1-P,1-I,1-R,1-I,1-R,1-M,1-P,1-M]),t===ha.FLIP_ROW&&(O=[1-P,I,1-R,I,1-R,M,1-P,M]),t===ha.FLIP_N_ROTATE_ROW&&(O=[P,1-I,R,1-I,R,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e&&y&&(b.push(d+p,g+f,0),b.push(v+p,g+f,0),b.push(v+p,g+u+f,0),b.push(d+p,g+u+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=0,I=1-u/s,R=l/i,M=1,O=[P,I,R,I,R,M,P,M],(t===ha.ROTATE_ROW||t===ha.ROTATE_TILE&&a%2==0)&&(O=[1-P,1-I,1-R,1-I,1-R,1-M,1-P,1-M]),(t===ha.FLIP_ROW||t===ha.FLIP_TILE&&a%2==0)&&(O=[1-P,I,1-R,I,1-R,M,1-P,M]),(t===ha.FLIP_N_ROTATE_ROW||t===ha.FLIP_N_ROTATE_TILE&&a%2==0)&&(O=[P,1-I,R,1-I,R,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&h&&(b.push(m+p,_+f,0),b.push(-d+p,_+f,0),b.push(-d+p,x+f,0),b.push(m+p,x+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=1-l/i,I=0,R=1,M=u/s,O=[P,I,R,I,R,M,P,M],(t===ha.ROTATE_ROW&&c%2==1||t===ha.ROTATE_TILE&&c%1==0)&&(O=[1-P,1-I,1-R,1-I,1-R,1-M,1-P,1-M]),(t===ha.FLIP_ROW&&c%2==1||t===ha.FLIP_TILE&&c%2==0)&&(O=[1-P,I,1-R,I,1-R,M,1-P,M]),(t===ha.FLIP_N_ROTATE_ROW&&c%2==1||t===ha.FLIP_N_ROTATE_TILE&&c%2==0)&&(O=[P,1-I,R,1-I,R,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&y&&(b.push(d+p,_+f,0),b.push(v+p,_+f,0),b.push(v+p,x+f,0),b.push(d+p,x+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=0,I=0,R=l/i,M=u/s,O=[P,I,R,I,R,M,P,M],(t===ha.ROTATE_ROW&&c%2==1||t===ha.ROTATE_TILE&&(c+a)%2==1)&&(O=[1-P,1-I,1-R,1-I,1-R,1-M,1-P,1-M]),(t===ha.FLIP_ROW&&c%2==1||t===ha.FLIP_TILE&&(c+a)%2==1)&&(O=[1-P,I,1-R,I,1-R,M,1-P,M]),(t===ha.FLIP_N_ROTATE_ROW&&c%2==1||t===ha.FLIP_N_ROTATE_TILE&&(c+a)%2==1)&&(O=[P,1-I,R,1-I,R,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e){const e=[];P=0,I=1-u/s,R=1,M=1,e[0]=[P,I,R,I,R,M,P,M],e[1]=[P,I,R,I,R,M,P,M],t!==ha.ROTATE_TILE&&t!==ha.ROTATE_ROW||(e[1]=[1-P,1-I,1-R,1-I,1-R,1-M,1-P,1-M]),t!==ha.FLIP_TILE&&t!==ha.FLIP_ROW||(e[1]=[1-P,I,1-R,I,1-R,M,1-P,M]),t!==ha.FLIP_N_ROTATE_TILE&&t!==ha.FLIP_N_ROTATE_ROW||(e[1]=[P,1-I,R,1-I,R,1-M,P,1-M]);for(let s=0;syd(e,{radius:t,tessellation:i,sideOrientation:n,updatable:r},s);const Ad={CreateTiledPlane:Ed};function Pd(e){const t=e.faceUV||new Array(6),i=e.faceColors,s=e.pattern||ha.NO_FLIP,r=e.width||e.size||1,n=e.height||e.size||1,o=e.depth||e.size||1,a=e.tileWidth||e.tileSize||1,l=e.tileHeight||e.tileSize||1,h=e.alignHorizontal||0,c=e.alignVertical||0,u=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE;for(let e=0;e<6;e++)void 0===t[e]&&(t[e]=new pe(0,0,1,1)),i&&void 0===i[e]&&(i[e]=new Ae(1,1,1,1));const d=r/2,_=n/2,p=o/2,f=[];for(let e=0;e<2;e++)f[e]=Cd({pattern:s,tileWidth:a,tileHeight:l,width:r,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});for(let e=2;e<4;e++)f[e]=Cd({pattern:s,tileWidth:a,tileHeight:l,width:o,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});let m=c;c===ha.BOTTOM?m=ha.TOP:c===ha.TOP&&(m=ha.BOTTOM);for(let e=4;e<6;e++)f[e]=Cd({pattern:s,tileWidth:a,tileHeight:l,width:r,height:o,alignVertical:m,alignHorizontal:h,sideOrientation:u});let g=[],v=[],x=[],b=[];const T=[],y=[],S=[],C=[];let E=0,A=0;for(let e=0;e<6;e++){const s=f[e].positions.length;y[e]=[],S[e]=[];for(let t=0;te+A))),A+=y[e].length,i)for(let t=0;t<4;t++)T.push(i[e].r,i[e].g,i[e].b,i[e].a)}const P=new _e(0,0,p),I=me.RotationY(Math.PI);g=y[0].map((e=>_e.TransformNormal(e,I).add(P))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),v=S[0].map((e=>_e.TransformNormal(e,I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),g=g.concat(y[1].map((e=>e.subtract(P))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[1].map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const R=new _e(d,0,0),M=me.RotationY(-Math.PI/2);g=g.concat(y[2].map((e=>_e.TransformNormal(e,M).add(R))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[2].map((e=>_e.TransformNormal(e,M))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const O=me.RotationY(Math.PI/2);g=g.concat(y[3].map((e=>_e.TransformNormal(e,O).subtract(R))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[3].map((e=>_e.TransformNormal(e,O))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const D=new _e(0,_,0),w=me.RotationX(Math.PI/2);g=g.concat(y[4].map((e=>_e.TransformNormal(e,w).add(D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[4].map((e=>_e.TransformNormal(e,w))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const N=me.RotationX(-Math.PI/2);g=g.concat(y[5].map((e=>_e.TransformNormal(e,N).subtract(D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[5].map((e=>_e.TransformNormal(e,N))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),Wn._ComputeSides(u,g,b,v,x);const F=new Wn;if(F.indices=b,F.positions=g,F.normals=v,F.uvs=x,i){const e=u===Wn.DOUBLESIDE?T.concat(T):T;F.colors=e}return F}function Id(e,t,i=null){const s=new ha(e,i);return t.sideOrientation=ha._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,Pd(t).applyToMesh(s,t.updatable),s}Wn.CreateTiledPlane=Cd;const Rd={CreateTiledBox:Id};function Md(e){const t=[],i=[],s=[],r=[],n=e.radius||2,o=e.tube||.5,a=e.radialSegments||32,l=e.tubularSegments||32,h=e.p||2,c=e.q||3,u=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,d=e=>{const t=Math.cos(e),i=Math.sin(e),s=c/h*e,r=Math.cos(s),o=n*(2+r)*.5*t,a=n*(2+r)*i*.5,l=n*Math.sin(s)*.5;return new _e(o,a,l)};let _,p;for(_=0;_<=a;_++){const e=_%a/a*2*h*Math.PI,t=d(e),s=d(e+.01),n=s.subtract(t);let c=s.add(t);const u=_e.Cross(n,c);for(c=_e.Cross(u,n),u.normalize(),c.normalize(),p=0;pOd(e,{radius:t,tube:i,radialSegments:s,tubularSegments:r,p:n,q:o,sideOrientation:h,updatable:l},a);const wd={effect:null,subMesh:null};class Nd extends ml{constructor(e,t,i,s={},r=!0){super(e,t,r),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new me,this._cachedWorldViewProjectionMatrix=new me,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...s}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return-1===this._options.externalTextures.indexOf(e)&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(16*t.length);for(let e=0;et===e||t.startsWith(i)));return s>=0&&this.options.defines.splice(s,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){const s=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const e=s?i._drawWrapper:this._drawWrapper;if(e.effect&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}const r=this.getScene(),n=r.getEngine(),o=[],a=[],l=new Ll;let h=this._shaderPath,c=this._options.uniforms,u=this._options.uniformBuffers,d=this._options.samplers;n.getCaps().multiview&&r.activeCamera&&r.activeCamera.outputRenderTarget&&r.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),-1!==c.indexOf("viewProjection")&&-1===c.indexOf("viewProjectionR")&&c.push("viewProjectionR"));for(let e=0;e4&&(a.push(er.MatricesIndicesExtraKind),a.push(er.MatricesWeightsExtraKind));const t=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),l.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),-1===c.indexOf("boneTextureWidth")&&c.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(t.bones.length+1)),-1===c.indexOf("mBones")&&c.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let _=0;const p=e?e.morphTargetManager:null;if(p){const e=p.supportsUVs&&-1!==o.indexOf("#define UV1"),t=p.supportsTangents&&-1!==o.indexOf("#define TANGENT"),i=p.supportsNormals&&-1!==o.indexOf("#define NORMAL");_=p.numMaxInfluencers||p.numInfluencers,e&&o.push("#define MORPHTARGETS_UV"),t&&o.push("#define MORPHTARGETS_TANGENT"),i&&o.push("#define MORPHTARGETS_NORMAL"),_>0&&o.push("#define MORPHTARGETS"),p.isUsingTextureForTargets&&(o.push("#define MORPHTARGETS_TEXTURE"),-1===c.indexOf("morphTargetTextureIndices")&&c.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),o.push("#define NUM_MORPH_INFLUENCERS "+_);for(let s=0;s<_;s++)a.push(er.PositionKind+s),i&&a.push(er.NormalKind+s),t&&a.push(er.TangentKind+s),e&&a.push(er.UVKind+"_"+s);_>0&&(c=c.slice(),c.push("morphTargetInfluences"),c.push("morphTargetCount"),c.push("morphTargetTextureInfo"),c.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===c.indexOf("bakedVertexAnimationSettings")&&c.push("bakedVertexAnimationSettings"),-1===c.indexOf("bakedVertexAnimationTextureSizeInverted")&&c.push("bakedVertexAnimationTextureSizeInverted"),-1===c.indexOf("bakedVertexAnimationTime")&&c.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),Do(a,0,o)}for(const e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&o.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&(mo(c),go(this,r,o)),r.fogEnabled&&e?.applyFog&&r.fogMode!==Hr.FOGMODE_NONE&&(o.push("#define FOG"),-1===c.indexOf("view")&&c.push("view"),-1===c.indexOf("vFogInfos")&&c.push("vFogInfos"),-1===c.indexOf("vFogColor")&&c.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),-1===c.indexOf("logarithmicDepthConstant")&&c.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(c=c.slice(),u=u.slice(),d=d.slice(),h=this.customShaderNameResolve(this.name,c,u,d,o,a));const f=s?i._getDrawWrapper(void 0,!0):this._drawWrapper,m=f?.effect??null,g=f?.defines??null,v=o.join("\n");let x=m;return g!==v&&(x=n.createEffect(h,{attributes:a,uniformsNames:c,uniformBuffersNames:u,samplers:d,defines:v,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:_},shaderLanguage:this._options.shaderLanguage},n),s?i.setEffect(x,v,this._materialContext):f&&f.setEffect(x,v),this._onEffectCreatedObservable&&(wd.effect=x,wd.subMesh=i??e?.subMeshes[0]??null,this._onEffectCreatedObservable.notifyObservers(wd))),f._wasPreviouslyUsingInstances=!!t,!(!x?.isReady()??1)&&(m!==x&&r.resetCachedMaterial(),f._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),s=t??this.getEffect();s&&(-1!==this._options.uniforms.indexOf("world")&&s.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),s.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),s.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),-1!==this._options.uniforms.indexOf("view")&&s.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){this.bind(e,t,i._drawWrapperOverride?.effect,i)}bind(e,t,i,s){const r=s&&this._storeEffectOnSubMeshes,n=i??(r?s.effect:this.getEffect());if(!n)return;const o=this.getScene();this._activeEffect=n,this.bindOnlyWorldMatrix(e,i);const a=this._options.uniformBuffers;let l=!1;if(n&&a&&a.length>0&&o.getEngine().supportsUniformBuffers)for(let i=0;i0&&Io(t,n);const i=t.bakedVertexAnimationManager;if(i&&i.isEnabled){const e=r?s._drawWrapper:this._drawWrapper;t.bakedVertexAnimationManager?.bind(n,!!e._wasPreviouslyUsingInstances)}}this._afterBind(t,n,s)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let t=0;tnew Nd(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes)),this);t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach((e=>{const t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))})),this.stencil.copyTo(t.stencil);for(const e in this._textures)t.setTexture(e,this._textures[e]);for(const e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(const e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(const e in this._ints)t.setInt(e,this._ints[e]);for(const e in this._uints)t.setUInt(e,this._uints[e]);for(const e in this._floats)t.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(const e in this._colors3)t.setColor3(e,this._colors3[e]);for(const e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(const e in this._colors4)t.setColor4(e,this._colors4[e]);for(const e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(const e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(const e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(const e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(const e in this._matrices)t.setMatrix(e,this._matrices[e]);for(const e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(const e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(const e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(const e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(const e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(const e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(const e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(const e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(const e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){const t=this._textureArrays[e];for(let e=0;enew Nd(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes)),e,t,i);let r;for(r in e.stencil&&s.stencil.parse(e.stencil,t,i),e.textures)s.setTexture(r,Pa.Parse(e.textures[r],t,i));for(r in e.textureArrays){const n=e.textureArrays[r],o=[];for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>Ee.FromArray(e)));s.setColor3Array(r,t)}for(r in e.colors4)s.setColor4(r,Ae.FromArray(e.colors4[r]));for(r in e.colors4Arrays){const t=e.colors4Arrays[r].reduce(((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>Ae.FromArray(e)));s.setColor4Array(r,t)}for(r in e.vectors2)s.setVector2(r,de.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,_e.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,pe.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,fe.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,me.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise(((r,n)=>{const o=new Pt;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=this.Parse(t,i||re.LastCreatedScene,s);e&&(n.name=e),r(n)}else n("Unable to load the ShaderMaterial")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return new Promise(((s,r)=>{const n=new Pt;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const r=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(r.shaderMaterial),a=this.Parse(o,t||re.LastCreatedScene,i);a.snippetId=e,s(a)}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}Nd.SnippetUrl="https://snippet.babylonjs.com",Nd.CreateFromSnippetAsync=Nd.ParseFromSnippetAsync,z("BABYLON.ShaderMaterial",Nd);Bi.ShadersStore.colorPixelShader="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n#include(color,gl_FragColor)\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.colorVertexShader="attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\n#ifdef FOG\nuniform mat4 view;\n#endif\n#include\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}",ha._LinesMeshParser=(e,t)=>Fd.Parse(e,t);class Fd extends ha{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,s=null,r,n,o,a){super(e,t,i,s,r),this.useVertexColor=n,this.useVertexAlpha=o,this.color=new Ee(1,1,1),this.alpha=1,s&&(this.color=s.color.clone(),this.alpha=s.alpha,this.useVertexColor=s.useVertexColor,this.useVertexAlpha=s.useVertexAlpha),this.intersectionThreshold=.1;const l={attributes:[er.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===o?l.needAlphaBlending=!1:l.defines.push("#define VERTEXALPHA"),n?(l.defines.push("#define VERTEXCOLOR"),l.attributes.push(er.ColorKind)):(l.uniforms.push("color"),this._color4=new Ae),a?this.material=a:(this.material=new Nd("colorShader",this.getScene(),"color",l,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=ta.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;const i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const s=this.getScene().getEngine();return this._unIndexed?s.drawArraysType(ta.LineListDrawMode,e.verticesStart,e.verticesCount,i):s.drawElementsType(ta.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new Fd(e,this.getScene(),t,this,i)}createInstance(e){const t=new Ld(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const e in this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new Fd(e.name,t);return i.color=Ee.FromArray(e.color),i.alpha=e.alpha,i}}class Ld extends ca{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function Bd(e){const t=[],i=[],s=e.lines,r=e.colors,n=[];let o=0;for(let e=0;e0&&(t.push(o-1),t.push(o)),o++}}const a=new Wn;return a.indices=t,a.positions=i,r&&(a.colors=n),a}function kd(e){const t=e.dashSize||3,i=e.gapSize||1,s=e.dashNb||200,r=e.points,n=[],o=[],a=_e.Zero();let l=0,h=0,c=0,u=0,d=0,_=0,p=0;for(p=0;p{const t=_e.Zero(),i=e.length/6;let n=0,o=0,a=0,l=0,h=0,c=0,u=0,d=0;for(u=0;uUd(e,{points:t,updatable:s,instance:r},i),ha.CreateDashedLines=(e,t,i,s,r,n=null,o,a)=>Gd(e,{points:t,dashSize:i,gapSize:s,dashNb:r,updatable:o,instance:a},n);class Wd extends de{constructor(e,t){super(e.x,e.y),this.index=t}}class Hd{constructor(){this.elements=[]}add(e){const t=[];return e.forEach((e=>{const i=new Wd(e,this.elements.length);t.push(i),this.elements.push(i)})),t}computeBounds(){const e=new de(this.elements[0].x,this.elements[0].y),t=new de(this.elements[0].x,this.elements[0].y);return this.elements.forEach((i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)})),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class Xd{static Rectangle(e,t,i,s){return[new de(e,t),new de(i,t),new de(i,s),new de(e,s)]}static Circle(e,t=0,i=0,s=32){const r=[];let n=0;const o=2*Math.PI/s;for(let a=0;a!isNaN(e)));let i;const s=[];for(i=0;i<(2147483646&t.length);i+=2)s.push(new de(t[i],t[i+1]));return s}static StartingAt(e,t){return Zr.StartingAt(e,t)}}class Yd{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,s=earcut){let r;this._points=new Hd,this._outlinepoints=new Hd,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=e,this._scene=i||re.LastCreatedScene,r=t instanceof Zr?t.getPoints():t,this._addToepoint(r),this._points.add(r),this._outlinepoints.add(r),void 0===this.bjsEarcut&&Ne.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new Hd;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){const s=new ha(this._name,this._scene),r=this.buildVertexData(t,i);return s.setVerticesData(er.PositionKind,r.positions,e),s.setVerticesData(er.NormalKind,r.normals,e),s.setVerticesData(er.UVKind,r.uvs,e),s.setIndices(r.indices),s}buildVertexData(e=0,t=2){const i=new Wn,s=[],r=[],n=[],o=this._points.computeBounds();this._points.elements.forEach((e=>{s.push(0,1,0),r.push(e.x,0,e.y),n.push((e.x-o.min.x)/o.width,(e.y-o.min.y)/o.height)}));const a=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e0){const i=r.length/3;this._points.elements.forEach((t=>{s.push(0,-1,0),r.push(t.x,-e,t.y),n.push(1-(t.x-o.min.x)/o.width,1-(t.y-o.min.y)/o.height)}));const l=a.length;for(let e=0;e{this._addSide(r,s,n,a,o,i,e,!0,t)}))}return i.indices=a,i.positions=r,i.normals=s,i.uvs=n,i}_addSide(e,t,i,s,r,n,o,a,l){let h=e.length/3,c=0;for(let u=0;ul?yl?S1),o=t.rotationFunction||(()=>0),a=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||ha.NO_CAP,c=t.updatable,u=t.firstNormal||null,d=t.adjustFrame||!1;return Jd(e,r,s,null,null,n,o,a,l,h,!0,i,!!c,ha._GetDefaultSideOrientation(t.sideOrientation),t.instance||null,t.invertUV||!1,t.frontUVs||null,t.backUVs||null,u,d)}function Jd(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v,x){const b=(e,t,i,s,r,n,o,a,l,h,c)=>{const u=i.getTangents(),d=i.getNormals(),_=i.getBinormals(),p=i.getDistances();if(c)for(let e=0;e0){let t=u[e-1];_e.Dot(t,u[e])<0&&u[e].scaleInPlace(-1),t=d[e-1],_e.Dot(t,d[e])<0&&d[e].scaleInPlace(-1),t=_[e-1],_e.Dot(t,_[e])<0&&_[e].scaleInPlace(-1)}let f=0;const m=h&&a?a:()=>null!==n?n:0,g=h&&o?o:()=>null!==r?r:1;let v=l===ha.NO_CAP||l===ha.CAP_END?0:2;const x=ve.Matrix[0];for(let i=0;i{const t=Array(),i=_e.Zero();let s;for(s=0;s3?0:h,c,x);const S=xd(e,{pathArray:y,closeArray:a,closePath:l,updatable:d,sideOrientation:_,invertUV:f,frontUVs:m||void 0,backUVs:g||void 0},u);return S._creationDataStorage.pathArray=y,S._creationDataStorage.path3D=T,S._creationDataStorage.cap=h,S}Wn.CreatePolygon=Qd,ha.CreatePolygon=(e,t,i,s,r,n,o=earcut)=>jd(e,{shape:t,holes:s,updatable:r,sideOrientation:n},i,o),ha.ExtrudePolygon=(e,t,i,s,r,n,o,a=earcut)=>Kd(e,{shape:t,holes:r,depth:i,updatable:n,sideOrientation:o},s,a);const e_={ExtrudeShape:qd,ExtrudeShapeCustom:Zd};function t_(e,t,i=null){const s=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,r=void 0===t.closed||t.closed,n=t.shape,o=t.radius||1,a=t.tessellation||64,l=t.clip||0,h=t.updatable,c=ha._GetDefaultSideOrientation(t.sideOrientation),u=t.cap||ha.NO_CAP,d=2*Math.PI,_=[],p=t.invertUV||!1;let f=0,m=0;const g=d/a*s;let v,x;for(f=0;f<=a-l;f++){for(x=[],u!=ha.CAP_START&&u!=ha.CAP_ALL||(x.push(new _e(0,n[0].y,0)),x.push(new _e(Math.cos(f*g)*n[0].x*o,n[0].y,Math.sin(f*g)*n[0].x*o))),m=0;mqd(e,{shape:t,path:i,scale:s,rotation:r,cap:0===n?0:n||ha.NO_CAP,sideOrientation:l,instance:h,updatable:a},o),ha.ExtrudeShapeCustom=(e,t,i,s,r,n,o,a,l,h,c,u)=>Zd(e,{shape:t,path:i,scaleFunction:s,rotationFunction:r,ribbonCloseArray:n,ribbonClosePath:o,cap:0===a?0:a||ha.NO_CAP,sideOrientation:c,instance:u,updatable:h},l);const i_={CreateLathe:t_};function s_(e,t,i=null){const s=t.path;let r=t.instance,n=1;void 0!==t.radius?n=t.radius:r&&(n=r._creationDataStorage.radius);const o=t.tessellation||64,a=t.radiusFunction||null;let l=t.cap||ha.NO_CAP;const h=t.invertUV||!1,c=t.updatable,u=ha._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;const d=(e,t,i,s,r,n,o,a)=>{const l=t.getTangents(),h=t.getNormals(),c=t.getDistances(),u=2*Math.PI/r*a,d=n||(()=>s);let _,p,f,m;const g=ve.Matrix[0];let v=o===ha.NO_CAP||o===ha.CAP_END?0:2;for(let t=0;t{const s=Array();for(let r=0;r3?0:l,p=d(s,_,new Array,n,o,a,l,t.arc);const f=xd(e,{pathArray:p,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:h,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return f._creationDataStorage.pathArray=p,f._creationDataStorage.path3D=_,f._creationDataStorage.tessellation=o,f._creationDataStorage.cap=l,f._creationDataStorage.arc=t.arc,f._creationDataStorage.radius=n,f}ha.CreateLathe=(e,t,i,s,r,n,o)=>t_(e,{shape:t,radius:i,tessellation:s,sideOrientation:o,updatable:n},r);const r_={CreateTube:s_};function n_(e){const t=[];t[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},t[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},t[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},t[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},t[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},t[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},t[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},t[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},t[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},t[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},t[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},t[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},t[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},t[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},t[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};const i=e.type&&(e.type<0||e.type>=t.length)?0:e.type||0,s=e.size,r=e.sizeX||s||1,n=e.sizeY||s||1,o=e.sizeZ||s||1,a=e.custom||t[i],l=a.face.length,h=e.faceUV||new Array(l),c=e.faceColors,u=void 0===e.flat||e.flat,d=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,_=[],p=[],f=[],m=[],g=[];let v=0,x=0;const b=[];let T,y,S,C,E,A,P=0,I=0;if(u)for(I=0;Is_(e,{path:t,radius:i,tessellation:s,radiusFunction:r,arc:1,cap:n,updatable:a,sideOrientation:l,instance:h},o);const a_={CreatePolyhedron:o_};Wn.CreatePolyhedron=n_,ha.CreatePolyhedron=(e,t,i)=>o_(e,t,i);const l_=new _e(1,0,0),h_=new _e(-1,0,0),c_=new _e(0,1,0),u_=new _e(0,-1,0),d_=new _e(0,0,1),__=new _e(0,0,-1);class p_{constructor(e=_e.Zero(),t=_e.Up(),i=de.Zero(),s=0,r=0,n=null,o=null,a=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=s,this.vertexIdxForBones=r,this.localPositionOverride=n,this.localNormalOverride=o,this.matrixIndicesOverride=a,this.matrixWeightsOverride=l}clone(){return new p_(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,this.localPositionOverride?.slice(),this.localNormalOverride?.slice(),this.matrixIndicesOverride?.slice(),this.matrixWeightsOverride?.slice())}}function f_(e,t,i){const s=!!t.skeleton,r=i.localMode||s,n=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,o=t.getIndices(),a=s?t.getPositionData(!0,!0):t.getVerticesData(er.PositionKind),l=s?t.getNormalsData(!0,!0):t.getVerticesData(er.NormalKind),h=r?s?t.getVerticesData(er.PositionKind):a:null,c=r?s?t.getVerticesData(er.NormalKind):l:null,u=t.getVerticesData(er.UVKind),d=s?t.getVerticesData(er.MatricesIndicesKind):null,_=s?t.getVerticesData(er.MatricesWeightsKind):null,p=s?t.getVerticesData(er.MatricesIndicesExtraKind):null,f=s?t.getVerticesData(er.MatricesWeightsExtraKind):null,m=i.position||_e.Zero();let g=i.normal||_e.Up();const v=i.size||_e.One(),x=i.angle||0;if(!g){const e=new _e(0,0,1),i=t.getScene().activeCamera,s=_e.TransformCoordinates(e,i.getWorldMatrix());g=i.globalPosition.subtract(s)}const b=-Math.atan2(g.z,g.x)-Math.PI/2,T=Math.sqrt(g.x*g.x+g.z*g.z),y=Math.atan2(g.y,T),S=new Wn;S.indices=[],S.positions=[],S.normals=[],S.uvs=[],S.matricesIndices=s?[]:null,S.matricesWeights=s?[]:null,S.matricesIndicesExtra=p?[]:null,S.matricesWeightsExtra=f?[]:null;let C=0;const E=(e,t)=>{const s=new p_;if(!o||!a||!l)return s;const r=o[e];if(s.vertexIdx=3*r,s.vertexIdxForBones=4*r,s.position=new _e(a[3*r],a[3*r+1],a[3*r+2]),_e.TransformCoordinatesToRef(s.position,t,s.position),s.normal=new _e(l[3*r],l[3*r+1],l[3*r+2]),_e.TransformNormalToRef(s.normal,t,s.normal),i.captureUVS&&u){const e=u[2*r+1];s.uv=new de(u[2*r],Xn.UseOpenGLOrientationForUV?1-e:e)}return s},A=[0,0,0,0],P=(e,t)=>{if(0===e.length)return e;const i=.5*Math.abs(_e.Dot(v,t)),s=(e,t,i,s)=>{for(let r=0;r{const n=_e.GetClipFactor(e.position,r.position,t,i);let o=A,a=A;if(d&&_){const t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=e.matrixIndicesOverride??d,l=e.matrixWeightsOverride??_,h=r.matrixIndicesOverride?0:r.vertexIdxForBones,c=r.matrixIndicesOverride??d,u=r.matrixWeightsOverride??_;o=[0,0,0,0],a=[0,0,0,0];let p=0;for(let e=0;e<4;++e)if(l[t+e]>0){const r=s(c,i[t+e],h,4);o[p]=i[t+e],a[p]=be.Lerp(l[t+e],r>=0?u[r]:0,n),p++}for(let e=0;e<4&&p<4;++e){const r=c[h+e];-1===s(i,r,t,4)&&(o[p]=r,a[p]=be.Lerp(0,u[h+e],n),p++)}const f=a[0]+a[1]+a[2]+a[3];a[0]/=f,a[1]/=f,a[2]/=f,a[3]/=f}const l=e.localPositionOverride?e.localPositionOverride[0]:h?.[e.vertexIdx]??0,u=e.localPositionOverride?e.localPositionOverride[1]:h?.[e.vertexIdx+1]??0,p=e.localPositionOverride?e.localPositionOverride[2]:h?.[e.vertexIdx+2]??0,f=r.localPositionOverride?r.localPositionOverride[0]:h?.[r.vertexIdx]??0,m=r.localPositionOverride?r.localPositionOverride[1]:h?.[r.vertexIdx+1]??0,g=r.localPositionOverride?r.localPositionOverride[2]:h?.[r.vertexIdx+2]??0,v=e.localNormalOverride?e.localNormalOverride[0]:c?.[e.vertexIdx]??0,x=e.localNormalOverride?e.localNormalOverride[1]:c?.[e.vertexIdx+1]??0,b=e.localNormalOverride?e.localNormalOverride[2]:c?.[e.vertexIdx+2]??0,T=v+((r.localNormalOverride?r.localNormalOverride[0]:c?.[r.vertexIdx]??0)-v)*n,y=x+((r.localNormalOverride?r.localNormalOverride[1]:c?.[r.vertexIdx+1]??0)-x)*n,S=b+((r.localNormalOverride?r.localNormalOverride[2]:c?.[r.vertexIdx+2]??0)-b)*n,C=Math.sqrt(T*T+y*y+S*S);return new p_(_e.Lerp(e.position,r.position,n),_e.Lerp(e.normal,r.normal,n).normalize(),de.Lerp(e.uv,r.uv,n),-1,-1,h?[l+(f-l)*n,u+(m-u)*n,p+(g-p)*n]:null,c?[T/C,y/C,S/C]:null,o,a)};let n=null;e.length>3&&(n=[]);for(let s=0;s0,d=_e.Dot(e[s+1].position,t)-i>0,_=_e.Dot(e[s+2].position,t)-i>0;switch(o=(u?1:0)+(d?1:0)+(_?1:0),o){case 0:e.length>3?(n.push(e[s]),n.push(e[s+1]),n.push(e[s+2])):n=e;break;case 1:if(n=n??new Array,u&&(a=e[s+1],l=e[s+2],h=r(e[s],a),c=r(e[s],l)),d){a=e[s],l=e[s+2],h=r(e[s+1],a),c=r(e[s+1],l),n.push(h),n.push(l.clone()),n.push(a.clone()),n.push(l.clone()),n.push(h.clone()),n.push(c);break}_&&(a=e[s],l=e[s+1],h=r(e[s+2],a),c=r(e[s+2],l)),a&&l&&h&&c&&(n.push(a.clone()),n.push(l.clone()),n.push(h),n.push(c),n.push(h.clone()),n.push(l.clone()));break;case 2:n=n??new Array,u||(a=e[s].clone(),l=r(a,e[s+1]),h=r(a,e[s+2]),n.push(a),n.push(l),n.push(h)),d||(a=e[s+1].clone(),l=r(a,e[s+2]),h=r(a,e[s]),n.push(a),n.push(l),n.push(h)),_||(a=e[s+2].clone(),l=r(a,e[s]),h=r(a,e[s+1]),n.push(a),n.push(l),n.push(h))}}return n},I=t instanceof ha?t:null,R=I?._thinInstanceDataStorage.matrixData,M=I?.thinInstanceCount||1,O=ve.Matrix[0];O.copyFrom(me.IdentityReadOnly);for(let e=0;ef_(e,t,{position:i,normal:s,size:r,angle:n});class g_{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(Math.floor(e),Ne.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(Math.floor(t),Ne.Warn("y is not an integer, floor(y) used"))}clone(){return new g_(this.x,this.y)}rotate60About(e){const t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){const t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&(Math.floor(e),Ne.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),Ne.Warn("n not an integer only floor(n) used"));const i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&(Math.floor(e),Ne.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),Ne.Warn("n is not an integer, floor(n) used"));const i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){const i=_e.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new g_(0,0)}}class v_{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new x_("icosahedron","Regular",[[0,Z,-1],[-Z,1,0],[-1,0,-Z],[1,0,-Z],[Z,1,0],[0,Z,1],[-1,0,Z],[-Z,-1,0],[0,-Z,-1],[Z,-1,0],[1,0,Z],[0,-Z,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12;const t={},i=this.m,s=this.n;let r,n,o,a,l,h=i,c=1,u=0;0!==s&&(h=be.HCF(i,s)),c=i/h,u=s/h;const d=g_.Zero(),_=new g_(i,s),p=new g_(-s,i+s),f=g_.Zero(),m=g_.Zero(),g=g_.Zero();let v,x,b,T,y=[];const S=[],C=this.vertByDist,E=(i,s,r,n)=>{v=i+"|"+r,x=s+"|"+n,v in t||x in t?v in t&&!(x in t)?t[x]=t[v]:x in t&&!(v in t)&&(t[v]=t[x]):(t[v]=e,t[x]=e,e++),C[r][0]>2?S[t[v]]=[-C[r][0],C[r][1],t[v]]:S[t[v]]=[y[C[r][0]],C[r][1],t[v]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let x=0;x<20;x++){if(y=this.IDATA.face[x],o=y[2],a=y[1],l=y[0],b=d.x+"|"+d.y,v=x+"|"+b,v in t||(t[v]=o,S[o]=[y[C[b][0]],C[b][1]]),b=_.x+"|"+_.y,v=x+"|"+b,v in t||(t[v]=a,S[a]=[y[C[b][0]],C[b][1]]),b=p.x+"|"+p.y,v=x+"|"+b,v in t||(t[v]=l,S[l]=[y[C[b][0]],C[b][1]]),r=this.IDATA.edgematch[x][0],n=this.IDATA.edgematch[x][1],"B"===n)for(let e=1;e2?S[t[v]]=[-C[b][0],C[b][1],t[v]]:S[t[v]]=[y[C[b][0]],C[b][1],t[v]])}this.closestTo=S,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,s=e*e+t*t+e*t;this.coau=(e+t)/s,this.cobu=-t/s,this.coav=-i*(e-t)/s,this.cobv=i*(2*e+t)/s}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i0&&e0){const s=be.HCF(e,t),r=e/s,n=t/s;for(let o=1;oe.x-t.x)),i.sort(((e,t)=>e.y-t.y));const o=new Array(e+t+1),a=new Array(e+t+1);for(let e=0;e{const r=i.clone();return"A"===s&&r.rotateNeg120(e,t),"B"===s&&r.rotate120(e,t),r.x<0?r.y:r.x+r.y},d=[],_=[],p=[],f=[],m={},g=[];let v=-1,x=-1;for(let e=0;ee[2]-t[2])),g.sort(((e,t)=>e[3]-t[3])),g.sort(((e,t)=>e[1]-t[1])),g.sort(((e,t)=>e[0]-t[0]));for(let e=0;et.vecToidx[e+i])))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let s=0;s-1?i[e][1]>0&&t[i[e][0]].push([e,i[e][1]]):t[12].push([e,i[e][0]]);const s=[];for(let e=0;e<12;e++)s[e]=e;let r=12;for(let e=0;e<12;e++){t[e].sort(((e,t)=>e[1]-t[1]));for(let i=0;ie[3]-t[3]));for(let e=0;e0;)r=t[a],this.face[r].indexOf(o)>-1?(n=(this.face[r].indexOf(o)+1)%3,o=this.face[r][n],i.push(o),s.push(r),t.splice(a,1),a=0):a++;return this.adjacentFaces.push(i),s}toGoldbergPolyhedronData(){const e=new x_("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let e=0;e{s=0,r=0,n=0,o=this.face[t];for(let e=0;e<3;e++)a=this.vertex[o[e]],s+=a[0],r+=a[1],n+=a[2];e.vertex[t]=[s/3,r/3,n/3]}));return e}static BuildGeodesicData(e){const t=new b_("Geodesic-m-n","Geodesic",[[0,Z,-1],[-Z,1,0],[-1,0,-Z],[1,0,-Z],[Z,1,0],[0,Z,1],[-1,0,Z],[-Z,-1,0],[0,-Z,-1],[Z,-1,0],[1,0,Z],[0,-Z,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let i=0;is){const e=r;r=s,s=e,Ne.Warn("n > m therefore m and n swapped")}const n=new v_;return n.build(s,r),o_(e,{custom:b_.BuildGeodesicData(n),size:t.size,sizeX:t.sizeX,sizeY:t.sizeY,sizeZ:t.sizeZ,faceUV:t.faceUV,faceColors:t.faceColors,flat:t.flat,updatable:t.updatable,sideOrientation:t.sideOrientation,frontUVs:t.frontUVs,backUVs:t.backUVs},i)}ha._GoldbergMeshParser=(e,t)=>y_.Parse(e,t);class y_ extends ha{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(Ne.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(Ne.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(Ne.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let t=0;t1&&(c=1),l.push(c,u);for(let e=0;e<6;e++)c=n.x+o*Math.cos(a+e*Math.PI/3),u=n.y+o*Math.sin(a+e*Math.PI/3),c<0&&(c=0),c>1&&(c=1),h.push(c,u);for(let e=s;eAe.FromArray(e))),i.faceCenters=i.faceCenters.map((e=>_e.FromArray(e))),i.faceZaxis=i.faceZaxis.map((e=>_e.FromArray(e))),i.faceXaxis=i.faceXaxis.map((e=>_e.FromArray(e))),i.faceYaxis=i.faceYaxis.map((e=>_e.FromArray(e)));const s=new y_(e.name,t);return s.goldbergData=i,s}}function S_(e,t){const i=e.size,s=e.sizeX||i||1,r=e.sizeY||i||1,n=e.sizeZ||i||1,o=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,a=[],l=[],h=[],c=[];let u=1/0,d=-1/0,_=1/0,p=-1/0;for(let e=0;ea){const e=l;l=a,a=e,Ne.Warn("n > m therefore m and n swapped")}const h=new v_;h.build(a,l);const c=b_.BuildGeodesicData(h),u=c.toGoldbergPolyhedronData(),d=new y_(e,i);t.sideOrientation=ha._GetDefaultSideOrientation(t.sideOrientation),d._originalBuilderSideOrientation=t.sideOrientation,S_(t,u).applyToMesh(d,t.updatable),d.goldbergData.nbSharedFaces=c.sharedNodes,d.goldbergData.nbUnsharedFaces=c.poleNodes,d.goldbergData.adjacentFaces=c.adjacentFaces,d.goldbergData.nbFaces=d.goldbergData.nbSharedFaces+d.goldbergData.nbUnsharedFaces,d.goldbergData.nbFacesAtPole=(d.goldbergData.nbUnsharedFaces-12)/12;for(let e=0;e0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function A_(e,t,i,s,r,n){const o=n.glyphs[e]||n.glyphs["?"];if(!o)return null;const a=new E_(r);if(o.o){const e=o.o.split(" ");for(let r=0,n=e.length;rJ&&(e.x=1*Math.sign(e.x)),Math.abs(e.y-1)>J&&(e.y=1*Math.sign(e.y)),Math.abs(e.z-1)>J&&(e.z=1*Math.sign(e.z))}_updateDebugConstraint(e,t){if(!e._initOptions)return;const{pivotA:i,pivotB:s,axisA:r,axisB:n,perpAxisA:o,perpAxisB:a}=e._initOptions;i&&s&&r&&n&&o&&a&&t.getDescendants(!0).forEach((e=>{const t=e.getDescendants(!0)[0],l=e.getDescendants(!0)[1],{parentBody:h,parentBodyIndex:c}=t.metadata,{childBody:u,childBodyIndex:d}=l.metadata,_=this._getTransformFromBodyToRef(h,ve.Matrix[0],c),p=this._getTransformFromBodyToRef(u,ve.Matrix[1],d);_.decomposeToTransformNode(t),this._makeScalingUnitInPlace(t.scaling),p.decomposeToTransformNode(l),this._makeScalingUnitInPlace(l.scaling);const f=t.getDescendants(!0)[0];f.position.copyFrom(i);const m=l.getDescendants(!0)[0];m.position.copyFrom(s),fe.FromRotationMatrixToRef(me.FromXYZAxesToRef(r,o,_e.CrossToRef(r,o,ve.Vector3[0]),ve.Matrix[0]),f.rotationQuaternion),fe.FromRotationMatrixToRef(me.FromXYZAxesToRef(n,a,_e.CrossToRef(n,a,ve.Vector3[1]),ve.Matrix[1]),m.rotationQuaternion)}))}showImpostor(e,t){if(!this._scene)return null;for(let t=0;tthis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numMeshes++),i}showBody(e){if(!this._scene)return null;for(let t=0;tthis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numBodies++),t}showInertia(e){if(!this._scene)return null;for(let t=0;tthis._updateInertiaMeshes(),this._scene.registerBeforeRender(this._inertiaRenderFunction)),this._numInertiaBodies++),t}showConstraint(e){if(!this._scene)return null;for(let t=0;tthis._updateDebugConstraints(),this._scene.registerBeforeRender(this._constraintRenderFunction)),this._numConstraints++),t}hideImpostor(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let s=0;s-1&&this._debugMeshMeshes.splice(r,1),this._numMeshes--,this._numMeshes>0?(this._meshes[s]=this._meshes[this._numMeshes],this._impostors[s]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&0===this._numMeshes&&this._scene.unregisterBeforeRender(this._renderFunction)}hideBody(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let s=0;s0?(this._bodyMeshes[s]=this._bodyMeshes[this._numBodies],this._bodies[s]=this._bodies[this._numBodies],this._bodyMeshes[this._numBodies]=null,this._bodies[this._numBodies]=null):(this._bodyMeshes[0]=null,this._bodies[0]=null),t=!0;break}t&&0===this._numBodies&&this._scene.unregisterBeforeRender(this._renderFunction)}hideInertia(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let s=0;s0?(this._constraints[s]=this._constraints[this._numConstraints],this._constraintMeshes[s]=this._constraintMeshes[this._numConstraints],this._constraints[this._numConstraints]=null,this._constraintMeshes[this._numConstraints]=null):(this._constraints[0]=null,this._constraintMeshes[0]=null),t=!0;break}t&&0===this._numConstraints&&this._scene.unregisterBeforeRender(this._constraintRenderFunction)}_getDebugMaterial(e){return this._debugMaterial||(this._debugMaterial=new cu("",e),this._debugMaterial.wireframe=!0,this._debugMaterial.emissiveColor=Ee.White(),this._debugMaterial.disableLighting=!0),this._debugMaterial}_getDebugInertiaMaterial(e){return this._debugInertiaMaterial||(this._debugInertiaMaterial=new cu("",e),this._debugInertiaMaterial.disableLighting=!0,this._debugInertiaMaterial.alpha=0),this._debugInertiaMaterial}_getDebugBoxMesh(e){return this._debugBoxMesh||(this._debugBoxMesh=cd("physicsBodyBoxViewMesh",{size:1},e),this._debugBoxMesh.rotationQuaternion=fe.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(e),this._debugBoxMesh.setEnabled(!1)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")}_getDebugSphereMesh(e){return this._debugSphereMesh||(this._debugSphereMesh=_d("physicsBodySphereViewMesh",{diameter:1},e),this._debugSphereMesh.rotationQuaternion=fe.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(e),this._debugSphereMesh.setEnabled(!1)),this._debugSphereMesh.createInstance("physicsBodySphereViewInstance")}_getDebugCapsuleMesh(e){return this._debugCapsuleMesh||(this._debugCapsuleMesh=md("physicsBodyCapsuleViewMesh",{height:1},e),this._debugCapsuleMesh.rotationQuaternion=fe.Identity(),this._debugCapsuleMesh.material=this._getDebugMaterial(e),this._debugCapsuleMesh.setEnabled(!1)),this._debugCapsuleMesh.createInstance("physicsBodyCapsuleViewInstance")}_getDebugCylinderMesh(e){return this._debugCylinderMesh||(this._debugCylinderMesh=$u("physicsBodyCylinderViewMesh",{diameterTop:1,diameterBottom:1,height:1},e),this._debugCylinderMesh.rotationQuaternion=fe.Identity(),this._debugCylinderMesh.material=this._getDebugMaterial(e),this._debugCylinderMesh.setEnabled(!1)),this._debugCylinderMesh.createInstance("physicsBodyCylinderViewInstance")}_getDebugMeshMesh(e,t){const i=new ha(e.name,t,null,e);return i.setParent(e),i.position=_e.Zero(),i.material=this._getDebugMaterial(t),this._debugMeshMeshes.push(i),i}_getDebugMesh(e,t){if(!this._utilityLayer)return null;if(t&&t.parent&&t.parent.physicsImpostor)return null;let i=null;const s=this._utilityLayer.utilityLayerScene;if(!e.physicsBody)return Ne.Warn("Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor."),null;switch(e.type){case nl.BoxImpostor:i=this._getDebugBoxMesh(s),e.getBoxSizeToRef(i.scaling);break;case nl.SphereImpostor:{i=this._getDebugSphereMesh(s);const t=e.getRadius();i.scaling.x=2*t,i.scaling.y=2*t,i.scaling.z=2*t;break}case nl.CapsuleImpostor:{i=this._getDebugCapsuleMesh(s);const t=e.object.getBoundingInfo();i.scaling.x=2*(t.boundingBox.maximum.x-t.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(t.boundingBox.maximum.y-t.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=2*(t.boundingBox.maximum.z-t.boundingBox.minimum.z)*e.object.scaling.z;break}case nl.MeshImpostor:t&&(i=this._getDebugMeshMesh(t,s));break;case nl.NoImpostor:t?t.getChildMeshes().filter((e=>e.physicsImpostor?1:0)).forEach((e=>{if(e.physicsImpostor&&"Mesh"===e.getClassName()){const t=e.getBoundingInfo(),r=t.boundingBox.minimum,n=t.boundingBox.maximum;switch(e.physicsImpostor.type){case nl.BoxImpostor:i=this._getDebugBoxMesh(s),i.position.copyFrom(r),i.position.addInPlace(n),i.position.scaleInPlace(.5);break;case nl.SphereImpostor:i=this._getDebugSphereMesh(s);break;case nl.CylinderImpostor:i=this._getDebugCylinderMesh(s);break;default:i=null}i&&(i.scaling.x=n.x-r.x,i.scaling.y=n.y-r.y,i.scaling.z=n.z-r.z,i.parent=e)}})):Ne.Warn("No target mesh parameter provided for NoImpostor. Skipping."),i=null;break;case nl.CylinderImpostor:{i=this._getDebugCylinderMesh(s);const t=e.object.getBoundingInfo();i.scaling.x=(t.boundingBox.maximum.x-t.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(t.boundingBox.maximum.y-t.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=(t.boundingBox.maximum.z-t.boundingBox.minimum.z)*e.object.scaling.z;break}}return i}_getDebugBodyMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=new ha("custom",t),s=new Wn,r=e.getGeometry();if(s.positions=r.positions,s.indices=r.indices,s.applyToMesh(i),e._pluginDataInstances){const t=new Float32Array(16*e._pluginDataInstances.length);i.thinInstanceSetBuffer("matrix",t,16,!1)}return i.material=this._getDebugMaterial(t),i}_getMeshDebugInertiaMatrixToRef(e,t){const i=e.inertiaOrientation??fe.Identity(),s=e.inertia??_e.Zero(),r=e.centerOfMass??_e.Zero(),n=6*(s.x-s.y+s.z),o=Math.sqrt(Math.max(n,0)),a=12*s.x-n,l=Math.sqrt(Math.max(a,0)),h=12*s.z-n,c=Math.sqrt(Math.max(h,0)),u=ve.Vector3[0];u.set(c,o,l);const d=me.ScalingToRef(u.x,u.y,u.z,ve.Matrix[0]),_=i.toRotationMatrix(ve.Matrix[1]),p=me.TranslationToRef(r.x,r.y,r.z,ve.Matrix[2]);return d.multiplyToRef(_,t),t.multiplyToRef(p,t),t}_getDebugInertiaMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=R_.CreateBox("custom",{size:1},t),s=me.Identity();if(e._pluginDataInstances.length){const t=new Float32Array(16*e._pluginDataInstances.length);for(let i=0;i=0?me.FromArrayToRef(s._thinInstanceDataStorage.matrixData,i,t):t.copyFrom(s.getWorldMatrix())}_getDebugConstraintMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene;if(!e._initOptions)return null;const{pivotA:i,pivotB:s,axisA:r,axisB:n,perpAxisA:o,perpAxisB:a}=e._initOptions;if(!(i&&s&&r&&n&&o&&a))return null;const l=new ha("parentingDebugConstraint",t),h=e.getBodiesUsingConstraint();for(const e of h){const h=new lo("parentOfPair",t);h.parent=l;const{parentBody:c,parentBodyIndex:u,childBody:d,childBodyIndex:_}=e,p=this._getTransformFromBodyToRef(c,ve.Matrix[0],u),f=this._getTransformFromBodyToRef(d,ve.Matrix[1],_),m=new lo("parentCoordSystem",t);m.parent=h,m.metadata={parentBody:c,parentBodyIndex:u},p.decomposeToTransformNode(m);const g=new lo("childCoordSystem",t);g.parent=h,g.metadata={childBody:d,childBodyIndex:_},f.decomposeToTransformNode(g);const v=fe.FromRotationMatrix(me.FromXYZAxesToRef(r,o,r.cross(o),ve.Matrix[0])),x=fe.FromRotationMatrix(me.FromXYZAxesToRef(n,a,n.cross(a),ve.Matrix[0])),b=i,T=s,y=new lo("constraint_parent",t);y.position.copyFrom(b),y.rotationQuaternion=v,y.parent=m;const S=new lo("constraint_child",t);S.parent=g,S.position.copyFrom(T),S.rotationQuaternion=x;const C=new nd(t,this._constraintAxesSize);C.xAxis.parent=y,C.yAxis.parent=y,C.zAxis.parent=y;const E=new nd(t,this._constraintAxesSize);E.xAxis.parent=S,E.yAxis.parent=S,E.zAxis.parent=S}return l}dispose(){for(let e=this._numMeshes-1;e>=0;e--)this.hideImpostor(this._impostors[0]);for(let e=this._numBodies-1;e>=0;e--)this.hideBody(this._bodies[0]);for(let e=this._numInertiaBodies-1;e>=0;e--)this.hideInertia(this._inertiaBodies[0]);this._debugBoxMesh&&this._debugBoxMesh.dispose(),this._debugSphereMesh&&this._debugSphereMesh.dispose(),this._debugCylinderMesh&&this._debugCylinderMesh.dispose(),this._debugMaterial&&this._debugMaterial.dispose(),this._impostors.length=0,this._scene=null,this._physicsEnginePlugin=null,this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null)}}class O_{static CreateAndShow(e,t,i){const s=new O_(e);return s.show(t,i),s}constructor(e){this.ray=e}show(e,t){if(!this._renderFunction&&this.ray){const t=this.ray;this._renderFunction=()=>this._render(),this._scene=e,this._renderPoints=[t.origin,t.origin.add(t.direction.scale(t.length))],this._renderLine=Ud("ray",{points:this._renderPoints,updatable:!0},e),this._renderLine.isPickable=!1,this._renderFunction&&this._scene.registerBeforeRender(this._renderFunction)}t&&this._renderLine&&this._renderLine.color.copyFrom(t)}hide(){this._renderFunction&&this._scene&&(this._scene.unregisterBeforeRender(this._renderFunction),this._scene=null,this._renderFunction=null,this._renderLine&&(this._renderLine.dispose(),this._renderLine=null),this._renderPoints=[])}_render(){const e=this.ray;if(!e)return;const t=this._renderPoints[1],i=Math.min(e.length,1e6);t.copyFrom(e.direction),t.scaleInPlace(i),t.addInPlace(e.origin),this._renderPoints[0].copyFrom(e.origin),Ud("ray",{points:this._renderPoints,updatable:!0,instance:this._renderLine},this._scene),this._renderLine?.refreshBoundingInfo()}attachToMesh(e,t,i,s){this._attachedToMesh=e;const r=this.ray;r&&(r.direction||(r.direction=_e.Zero()),r.origin||(r.origin=_e.Zero()),s&&(r.length=s),i||(i=_e.Zero()),t||(t=new _e(0,0,-1)),this._scene||(this._scene=e.getScene()),this._meshSpaceDirection?(this._meshSpaceDirection.copyFrom(t),this._meshSpaceOrigin.copyFrom(i)):(this._meshSpaceDirection=t.clone(),this._meshSpaceOrigin=i.clone()),this._onAfterRenderObserver||(this._onAfterRenderObserver=this._scene.onBeforeRenderObservable.add((()=>this._updateToMesh())),this._onAfterStepObserver=this._scene.onAfterStepObservable.add((()=>this._updateToMesh()))),this._attachedToMesh.computeWorldMatrix(!0),this._updateToMesh())}detachFromMesh(){this._attachedToMesh&&this._scene&&(this._onAfterRenderObserver&&(this._scene.onBeforeRenderObservable.remove(this._onAfterRenderObserver),this._scene.onAfterStepObservable.remove(this._onAfterStepObserver)),this._attachedToMesh=null,this._onAfterRenderObserver=null,this._onAfterStepObserver=null,this._scene=null)}_updateToMesh(){const e=this.ray;this._attachedToMesh&&e&&(this._attachedToMesh.isDisposed()?this.detachFromMesh():(this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection,e.direction),_e.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),e.origin)))}dispose(){this.hide(),this.detachFromMesh(),this.ray=null}}class D_{static CreateBoneWeightShader(e,t){const i=e.skeleton,s=e.colorBase??Ee.Black(),r=e.colorZero??Ee.Blue(),n=e.colorQuarter??Ee.Green(),o=e.colorHalf??Ee.Yellow(),a=e.colorFull??Ee.Red(),l=e.targetBoneIndex??0;$i.ShadersStore["boneWeights:"+i.name+"VertexShader"]="precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n\n #include\n\n varying vec3 vColor;\n\n uniform vec3 colorBase;\n uniform vec3 colorZero;\n uniform vec3 colorQuarter;\n uniform vec3 colorHalf;\n uniform vec3 colorFull;\n\n uniform float targetBoneIndex;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n vec3 color = colorBase;\n float totalWeight = 0.;\n if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){\n totalWeight += matricesWeights[0];\n }\n if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){\n totalWeight += matricesWeights[1];\n }\n if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){\n totalWeight += matricesWeights[2];\n }\n if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){\n totalWeight += matricesWeights[3];\n }\n\n color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));\n color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));\n color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));\n color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));\n vColor = color;\n\n gl_Position = projection * view * worldPos;\n }",$i.ShadersStore["boneWeights:"+i.name+"FragmentShader"]="\n precision highp float;\n varying vec3 vPosition;\n\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4(vColor, 1.0);\n gl_FragColor = color;\n }\n ";const h=new Nd("boneWeight:"+i.name,t,{vertex:"boneWeights:"+i.name,fragment:"boneWeights:"+i.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return h.setColor3("colorBase",s),h.setColor3("colorZero",r),h.setColor3("colorQuarter",n),h.setColor3("colorHalf",o),h.setColor3("colorFull",a),h.setFloat("targetBoneIndex",l),h.getClassName=()=>"BoneWeightShader",h.transparencyMode=ta.MATERIAL_OPAQUE,h}static CreateSkeletonMapShader(e,t){const i=e.skeleton,s=e.colorMap??[{color:new Ee(1,.38,.18),location:0},{color:new Ee(.59,.18,1),location:.2},{color:new Ee(.59,1,.18),location:.4},{color:new Ee(1,.87,.17),location:.6},{color:new Ee(1,.17,.42),location:.8},{color:new Ee(.17,.68,1),location:1}],r=i.bones.length+1,n=D_._CreateBoneMapColorBuffer(r,s,t),o=new Nd("boneWeights:"+i.name,t,{vertexSource:"precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n uniform float colorMap["+4*i.bones.length+"];\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n #include\n\n varying vec3 vColor;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec3 color = vec3(0.);\n bool first = true;\n\n for (int i = 0; i < 4; i++) {\n int boneIdx = int(matricesIndices[i]);\n float boneWgt = matricesWeights[i];\n\n vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);\n\n if (boneWgt > 0.) {\n if (first) {\n first = false;\n color = c;\n } else {\n color = mix(color, c, boneWgt);\n }\n }\n }\n\n vColor = color;\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n gl_Position = projection * view * worldPos;\n }",fragmentSource:"\n precision highp float;\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4( vColor, 1.0 );\n gl_FragColor = color;\n }\n "},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",n),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=ta.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){const s=new uu("temp",{width:e,height:1},i,!1),r=s.getContext(),n=r.createLinearGradient(0,0,e,0);t.forEach((e=>{n.addColorStop(e.location,e.color.toHexString())})),r.fillStyle=n,r.fillRect(0,0,e,1),s.update();const o=[],a=r.getImageData(0,0,e,1).data,l=1/255;for(let e=0;eD_.DISPLAY_SPHERE_AND_SPURS&&(e=D_.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,s=!0,r=3,n={}){if(this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=s,this.renderingGroupId=r,this.options=n,this.color=Ee.White(),this._debugLines=new Array,this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,n.pauseAnimations=n.pauseAnimations??!0,n.returnToRest=n.returnToRest??!1,n.displayMode=n.displayMode??D_.DISPLAY_LINES,n.displayOptions=n.displayOptions??{},n.displayOptions.midStep=n.displayOptions.midStep??.235,n.displayOptions.midStepFactor=n.displayOptions.midStepFactor??.155,n.displayOptions.sphereBaseSize=n.displayOptions.sphereBaseSize??.15,n.displayOptions.sphereScaleUnit=n.displayOptions.sphereScaleUnit??2,n.displayOptions.sphereFactor=n.displayOptions.sphereFactor??.865,n.displayOptions.spurFollowsChild=n.displayOptions.spurFollowsChild??!1,n.displayOptions.showLocalAxes=n.displayOptions.showLocalAxes??!1,n.displayOptions.localAxesSize=n.displayOptions.localAxesSize??.075,n.computeBonesUsingShaders=n.computeBonesUsingShaders??!0,n.useAllBones=n.useAllBones??!0,this._boneIndices=new Set,!n.useAllBones){const e=t?.getVerticesData(er.MatricesIndicesKind),i=t?.getVerticesData(er.MatricesWeightsKind);if(e&&i)for(let t=0;tD_.DISPLAY_SPHERE_AND_SPURS&&(o=D_.DISPLAY_LINES),this.displayMode=o,this.update(),this._bindObs()}_bindObs(){this.displayMode===D_.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add((()=>{this._displayLinesUpdate()})))}update(){switch(this.displayMode){case D_.DISPLAY_LINES:this._displayLinesUpdate();break;case D_.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case D_.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,s=0,r=0,n=0){const o=ve.Matrix[0],a=t.getParent();if(o.copyFrom(t.getLocalMatrix()),0!==s||0!==r||0!==n){const e=ve.Matrix[1];me.IdentityToRef(e),e.setTranslationFromFloats(s,r,n),e.multiplyToRef(o,o)}a&&o.multiplyToRef(a.getAbsoluteMatrix(),o),o.multiplyToRef(i,o),e.x=o.m[12],e.y=o.m[13],e.z=o.m[14]}_getLinesForBonesWithLength(e,t){const i=e.length;let s,r;t?(s=t.getWorldMatrix(),r=t.position):(s=new me,r=e[0].position);let n=0;for(let t=0;t=0;s--){const t=e[s],o=t.getParent();if(!o||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let a=this._debugLines[i];a||(a=[_e.Zero(),_e.Zero()],this._debugLines[i]=a),t.getAbsolutePositionToRef(r,a[0]),o.getAbsolutePositionToRef(r,a[1]),a[0].subtractInPlace(n),a[1].subtractInPlace(n),i++}s||r.dispose()}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){null!==e&&-1!==e._index?(this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)):t.copyFrom(me.Identity())}_createSpur(e,t,i,s,r,n){const o=i.subtract(e),a=o.length(),l=o.normalize().scale(a),h=r.midStep||.165,c=r.midStepFactor||.215,u=l.scale(h),d=Zd("skeletonViewer",{shape:[new _e(1,-1,0),new _e(1,1,0),new _e(-1,1,0),new _e(-1,-1,0),new _e(1,-1,0)],path:[_e.Zero(),u,l],scaleFunction:e=>{switch(e){case 0:case 2:return 0;case 1:return a*c}return 0},sideOrientation:ha.DEFAULTSIDE,updatable:!1},n),_=d.getTotalVertices(),p=[],f=[];for(let e=0;e<_;e++)p.push(1,0,0,0),s&&r.spurFollowsChild&&e>9?f.push(s.getIndex(),0,0,0):f.push(t.getIndex(),0,0,0);return d.position=e.clone(),d.setVerticesData(er.MatricesWeightsKind,p,!1),d.setVerticesData(er.MatricesIndicesKind,f,!1),d.convertToFlatShadedMesh(),d}_getBoundingSphereForBone(e){if(!this.mesh)return null;const t=this.mesh.getVerticesData(er.PositionKind),i=this.mesh.getIndices(),s=this.mesh.getVerticesData(er.MatricesWeightsKind),r=this.mesh.getVerticesData(er.MatricesIndicesKind);if(!(t&&i&&s&&r))return null;const n=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new _e(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);let a=0;for(let l=0;l1e-5){_e.FromArrayToRef(t,3*h,ve.Vector3[0]),n.minimizeInPlace(ve.Vector3[0]),o.maximizeInPlace(ve.Vector3[0]),a++;break}}}return a>1?{center:_e.Center(n,o),radius:_e.Distance(n,o)/2}:null}_buildSpheresAndSpurs(e=!0){this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;const t=this.utilityLayer?.utilityLayerScene,i=this.skeleton.bones,s=[],r=[],n=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,t.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let o=Number.NEGATIVE_INFINITY;const a=this.options.displayOptions||{};for(let n=0;n0)l.children.forEach((i=>{const s=new me;i.getLocalMatrix().multiplyToRef(h,s);const n=new _e;s.decompose(void 0,void 0,n);const u=_e.Distance(c,n);u>o&&(o=u),e||r.push(this._createSpur(c,l,n,i,a,t))}));else{const i=this._getBoundingSphereForBone(l.getIndex());if(i&&(i.radius>o&&(o=i.radius),!e)){let e;const s=l.getParent();s?(this._getAbsoluteBindPoseToRef(s,h),h.decompose(void 0,void 0,ve.Vector3[0]),e=c.subtract(ve.Vector3[0]).normalize().scale(i.radius).add(c)):e=i.center.subtract(c).normalize().scale(i.radius).add(c),r.push(this._createSpur(c,l,e,null,a,t))}}const u=_d("skeletonViewer",{segments:6,diameter:a.sphereBaseSize||.2,updatable:!0},t),d=u.getTotalVertices(),_=[],p=[];for(let e=0;e{e.setEnabled(t<6&&this._showLines||t>=6&&this._showPlanes)})),this._oldPosition.set(Number.NaN,Number.NaN,Number.NaN),this._visible=!0}hide(){this._lightHelperFrustumMeshes.forEach((e=>{e.setEnabled(!1)})),this._visible=!1}update(){if(!this._visible)return;if(this._oldPosition.equals(this._light.position)&&this._oldDirection.equals(this._light.direction)&&this._oldAutoCalc===this._light.autoCalcShadowZBounds&&this._oldMinZ===this._light.shadowMinZ&&this._oldMaxZ===this._light.shadowMaxZ)return;this._oldPosition.copyFrom(this._light.position),this._oldDirection.copyFrom(this._light.direction),this._oldAutoCalc=this._light.autoCalcShadowZBounds,this._oldMinZ=this._light.shadowMinZ,this._oldMaxZ=this._light.shadowMaxZ,ve.Vector3[0].set(this._light.orthoLeft,this._light.orthoBottom,void 0!==this._light.shadowMinZ?this._light.shadowMinZ:this._camera.minZ),ve.Vector3[1].set(this._light.orthoRight,this._light.orthoTop,void 0!==this._light.shadowMaxZ?this._light.shadowMaxZ:this._camera.maxZ);const e=this._getInvertViewMatrix();ve.Vector3[2].copyFromFloats(ve.Vector3[1].x,ve.Vector3[1].y,ve.Vector3[0].z),ve.Vector3[3].copyFromFloats(ve.Vector3[1].x,ve.Vector3[0].y,ve.Vector3[0].z),ve.Vector3[4].copyFromFloats(ve.Vector3[0].x,ve.Vector3[0].y,ve.Vector3[0].z),ve.Vector3[5].copyFromFloats(ve.Vector3[0].x,ve.Vector3[1].y,ve.Vector3[0].z),_e.TransformCoordinatesToRef(ve.Vector3[2],e,ve.Vector3[2]),_e.TransformCoordinatesToRef(ve.Vector3[3],e,ve.Vector3[3]),_e.TransformCoordinatesToRef(ve.Vector3[4],e,ve.Vector3[4]),_e.TransformCoordinatesToRef(ve.Vector3[5],e,ve.Vector3[5]),ve.Vector3[6].copyFromFloats(ve.Vector3[1].x,ve.Vector3[1].y,ve.Vector3[1].z),ve.Vector3[7].copyFromFloats(ve.Vector3[1].x,ve.Vector3[0].y,ve.Vector3[1].z),ve.Vector3[8].copyFromFloats(ve.Vector3[0].x,ve.Vector3[0].y,ve.Vector3[1].z),ve.Vector3[9].copyFromFloats(ve.Vector3[0].x,ve.Vector3[1].y,ve.Vector3[1].z),_e.TransformCoordinatesToRef(ve.Vector3[6],e,ve.Vector3[6]),_e.TransformCoordinatesToRef(ve.Vector3[7],e,ve.Vector3[7]),_e.TransformCoordinatesToRef(ve.Vector3[8],e,ve.Vector3[8]),_e.TransformCoordinatesToRef(ve.Vector3[9],e,ve.Vector3[9]),Ud("nearlines",{updatable:!0,points:this._nearLinesPoints,instance:this._lightHelperFrustumMeshes[0]},this._scene),Ud("farlines",{updatable:!0,points:this._farLinesPoints,instance:this._lightHelperFrustumMeshes[1]},this._scene),Ud("trlines",{updatable:!0,points:this._trLinesPoints,instance:this._lightHelperFrustumMeshes[2]},this._scene),Ud("brlines",{updatable:!0,points:this._brLinesPoints,instance:this._lightHelperFrustumMeshes[3]},this._scene),Ud("tllines",{updatable:!0,points:this._tlLinesPoints,instance:this._lightHelperFrustumMeshes[4]},this._scene),Ud("bllines",{updatable:!0,points:this._blLinesPoints,instance:this._lightHelperFrustumMeshes[5]},this._scene),ve.Vector3[2].toArray(this._nearPlaneVertices,0),ve.Vector3[3].toArray(this._nearPlaneVertices,3),ve.Vector3[4].toArray(this._nearPlaneVertices,6),ve.Vector3[5].toArray(this._nearPlaneVertices,9),this._lightHelperFrustumMeshes[6].geometry?.updateVerticesDataDirectly("position",this._nearPlaneVertices,0),ve.Vector3[6].toArray(this._farPlaneVertices,0),ve.Vector3[7].toArray(this._farPlaneVertices,3),ve.Vector3[8].toArray(this._farPlaneVertices,6),ve.Vector3[9].toArray(this._farPlaneVertices,9),this._lightHelperFrustumMeshes[7].geometry?.updateVerticesDataDirectly("position",this._farPlaneVertices,0),ve.Vector3[2].toArray(this._rightPlaneVertices,0),ve.Vector3[6].toArray(this._rightPlaneVertices,3),ve.Vector3[7].toArray(this._rightPlaneVertices,6),ve.Vector3[3].toArray(this._rightPlaneVertices,9),this._lightHelperFrustumMeshes[8].geometry?.updateVerticesDataDirectly("position",this._rightPlaneVertices,0),ve.Vector3[5].toArray(this._leftPlaneVertices,0),ve.Vector3[9].toArray(this._leftPlaneVertices,3),ve.Vector3[8].toArray(this._leftPlaneVertices,6),ve.Vector3[4].toArray(this._leftPlaneVertices,9),this._lightHelperFrustumMeshes[9].geometry?.updateVerticesDataDirectly("position",this._leftPlaneVertices,0),ve.Vector3[2].toArray(this._topPlaneVertices,0),ve.Vector3[6].toArray(this._topPlaneVertices,3),ve.Vector3[9].toArray(this._topPlaneVertices,6),ve.Vector3[5].toArray(this._topPlaneVertices,9),this._lightHelperFrustumMeshes[10].geometry?.updateVerticesDataDirectly("position",this._topPlaneVertices,0),ve.Vector3[3].toArray(this._bottomPlaneVertices,0),ve.Vector3[7].toArray(this._bottomPlaneVertices,3),ve.Vector3[8].toArray(this._bottomPlaneVertices,6),ve.Vector3[4].toArray(this._bottomPlaneVertices,9),this._lightHelperFrustumMeshes[11].geometry?.updateVerticesDataDirectly("position",this._bottomPlaneVertices,0)}dispose(){this._lightHelperFrustumMeshes.forEach((e=>{e.material?.dispose(),e.dispose()})),this._rootNode.dispose()}_createGeometry(){this._rootNode=new lo("directionalLightHelperRoot_"+this._light.name,this._scene),this._rootNode.parent=this._light.parent,this._nearLinesPoints=[ve.Vector3[0],ve.Vector3[1],ve.Vector3[2],ve.Vector3[3],ve.Vector3[4]];const e=Ud("nearlines",{updatable:!0,points:this._nearLinesPoints},this._scene);e.parent=this._rootNode,e.alwaysSelectAsActiveMesh=!0,this._farLinesPoints=[ve.Vector3[5],ve.Vector3[6],ve.Vector3[7],ve.Vector3[8],ve.Vector3[9]];const t=Ud("farlines",{updatable:!0,points:this._farLinesPoints},this._scene);t.parent=this._rootNode,t.alwaysSelectAsActiveMesh=!0,this._trLinesPoints=[ve.Vector3[10],ve.Vector3[11]];const i=Ud("trlines",{updatable:!0,points:this._trLinesPoints},this._scene);i.parent=this._rootNode,i.alwaysSelectAsActiveMesh=!0,this._brLinesPoints=[ve.Vector3[12],ve.Vector3[0]];const s=Ud("brlines",{updatable:!0,points:this._brLinesPoints},this._scene);s.parent=this._rootNode,s.alwaysSelectAsActiveMesh=!0,this._tlLinesPoints=[ve.Vector3[1],ve.Vector3[2]];const r=Ud("tllines",{updatable:!0,points:this._tlLinesPoints},this._scene);r.parent=this._rootNode,r.alwaysSelectAsActiveMesh=!0,this._blLinesPoints=[ve.Vector3[3],ve.Vector3[4]];const n=Ud("bllines",{updatable:!0,points:this._blLinesPoints},this._scene);n.parent=this._rootNode,n.alwaysSelectAsActiveMesh=!0,this._lightHelperFrustumMeshes.push(e,t,i,s,r,n);const o=(e,t,i)=>{const s=new ha(e+"plane",this._scene),r=new cu(e+"PlaneMat",this._scene);s.material=r,s.parent=this._rootNode,s.alwaysSelectAsActiveMesh=!0,r.emissiveColor=t,r.alpha=this.transparency,r.backFaceCulling=!1,r.disableLighting=!0;const n=new Wn;n.positions=i,n.indices=[0,1,2,0,2,3],n.applyToMesh(s,!0),this._lightHelperFrustumMeshes.push(s)};this._nearPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._farPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._rightPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._leftPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._topPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._bottomPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],o("near",new Ee(1,0,0),this._nearPlaneVertices),o("far",new Ee(.3,0,0),this._farPlaneVertices),o("right",new Ee(0,1,0),this._rightPlaneVertices),o("left",new Ee(0,.3,0),this._leftPlaneVertices),o("top",new Ee(0,0,1),this._topPlaneVertices),o("bottom",new Ee(0,0,.3),this._bottomPlaneVertices),this._nearLinesPoints[0]=ve.Vector3[2],this._nearLinesPoints[1]=ve.Vector3[3],this._nearLinesPoints[2]=ve.Vector3[4],this._nearLinesPoints[3]=ve.Vector3[5],this._nearLinesPoints[4]=ve.Vector3[2],this._farLinesPoints[0]=ve.Vector3[6],this._farLinesPoints[1]=ve.Vector3[7],this._farLinesPoints[2]=ve.Vector3[8],this._farLinesPoints[3]=ve.Vector3[9],this._farLinesPoints[4]=ve.Vector3[6],this._trLinesPoints[0]=ve.Vector3[2],this._trLinesPoints[1]=ve.Vector3[6],this._brLinesPoints[0]=ve.Vector3[3],this._brLinesPoints[1]=ve.Vector3[7],this._tlLinesPoints[0]=ve.Vector3[4],this._tlLinesPoints[1]=ve.Vector3[8],this._blLinesPoints[0]=ve.Vector3[5],this._blLinesPoints[1]=ve.Vector3[9]}_getInvertViewMatrix(){return me.LookAtLHToRef(this._light.position,this._light.position.add(this._light.direction),_e.UpReadOnly,this._inverseViewMatrix),this._inverseViewMatrix.invertToRef(this._inverseViewMatrix),this._inverseViewMatrix}}class N_{}N_.AUTOSAMPLERSUFFIX="Sampler",N_.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS",N_.ALPHA_DISABLE=0,N_.ALPHA_ADD=1,N_.ALPHA_COMBINE=2,N_.ALPHA_SUBTRACT=3,N_.ALPHA_MULTIPLY=4,N_.ALPHA_MAXIMIZED=5,N_.ALPHA_ONEONE=6,N_.ALPHA_PREMULTIPLIED=7,N_.ALPHA_PREMULTIPLIED_PORTERDUFF=8,N_.ALPHA_INTERPOLATE=9,N_.ALPHA_SCREENMODE=10,N_.ALPHA_ONEONE_ONEONE=11,N_.ALPHA_ALPHATOCOLOR=12,N_.ALPHA_REVERSEONEMINUS=13,N_.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,N_.ALPHA_ONEONE_ONEZERO=15,N_.ALPHA_EXCLUSION=16,N_.ALPHA_LAYER_ACCUMULATE=17,N_.ALPHA_EQUATION_ADD=0,N_.ALPHA_EQUATION_SUBSTRACT=1,N_.ALPHA_EQUATION_REVERSE_SUBTRACT=2,N_.ALPHA_EQUATION_MAX=3,N_.ALPHA_EQUATION_MIN=4,N_.ALPHA_EQUATION_DARKEN=5,N_.DELAYLOADSTATE_NONE=0,N_.DELAYLOADSTATE_LOADED=1,N_.DELAYLOADSTATE_LOADING=2,N_.DELAYLOADSTATE_NOTLOADED=4,N_.NEVER=512,N_.ALWAYS=519,N_.LESS=513,N_.EQUAL=514,N_.LEQUAL=515,N_.GREATER=516,N_.GEQUAL=518,N_.NOTEQUAL=517,N_.KEEP=7680,N_.ZERO=0,N_.REPLACE=7681,N_.INCR=7682,N_.DECR=7683,N_.INVERT=5386,N_.INCR_WRAP=34055,N_.DECR_WRAP=34056,N_.TEXTURE_CLAMP_ADDRESSMODE=0,N_.TEXTURE_WRAP_ADDRESSMODE=1,N_.TEXTURE_MIRROR_ADDRESSMODE=2,N_.TEXTURE_CREATIONFLAG_STORAGE=1,N_.TEXTUREFORMAT_ALPHA=0,N_.TEXTUREFORMAT_LUMINANCE=1,N_.TEXTUREFORMAT_LUMINANCE_ALPHA=2,N_.TEXTUREFORMAT_RGB=4,N_.TEXTUREFORMAT_RGBA=5,N_.TEXTUREFORMAT_RED=6,N_.TEXTUREFORMAT_R=6,N_.TEXTUREFORMAT_RG=7,N_.TEXTUREFORMAT_RED_INTEGER=8,N_.TEXTUREFORMAT_R_INTEGER=8,N_.TEXTUREFORMAT_RG_INTEGER=9,N_.TEXTUREFORMAT_RGB_INTEGER=10,N_.TEXTUREFORMAT_RGBA_INTEGER=11,N_.TEXTUREFORMAT_BGRA=12,N_.TEXTUREFORMAT_DEPTH24_STENCIL8=13,N_.TEXTUREFORMAT_DEPTH32_FLOAT=14,N_.TEXTUREFORMAT_DEPTH16=15,N_.TEXTUREFORMAT_DEPTH24=16,N_.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,N_.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,N_.TEXTUREFORMAT_STENCIL8=19,N_.TEXTUREFORMAT_UNDEFINED=4294967295,N_.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,N_.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,N_.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,N_.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,N_.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,N_.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,N_.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,N_.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,N_.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,N_.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,N_.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,N_.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,N_.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,N_.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,N_.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,N_.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,N_.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,N_.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,N_.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,N_.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,N_.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,N_.TEXTURETYPE_UNSIGNED_BYTE=0,N_.TEXTURETYPE_UNSIGNED_INT=0,N_.TEXTURETYPE_FLOAT=1,N_.TEXTURETYPE_HALF_FLOAT=2,N_.TEXTURETYPE_BYTE=3,N_.TEXTURETYPE_SHORT=4,N_.TEXTURETYPE_UNSIGNED_SHORT=5,N_.TEXTURETYPE_INT=6,N_.TEXTURETYPE_UNSIGNED_INTEGER=7,N_.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,N_.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,N_.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,N_.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,N_.TEXTURETYPE_UNSIGNED_INT_24_8=12,N_.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,N_.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,N_.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,N_.TEXTURETYPE_UNDEFINED=16,N_.TEXTURE_2D=3553,N_.TEXTURE_2D_ARRAY=35866,N_.TEXTURE_CUBE_MAP=34067,N_.TEXTURE_CUBE_MAP_ARRAY=3735928559,N_.TEXTURE_3D=32879,N_.TEXTURE_NEAREST_SAMPLINGMODE=1,N_.TEXTURE_NEAREST_NEAREST=1,N_.TEXTURE_BILINEAR_SAMPLINGMODE=2,N_.TEXTURE_LINEAR_LINEAR=2,N_.TEXTURE_TRILINEAR_SAMPLINGMODE=3,N_.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,N_.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,N_.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,N_.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,N_.TEXTURE_NEAREST_LINEAR=7,N_.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,N_.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,N_.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,N_.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,N_.TEXTURE_LINEAR_NEAREST=12,N_.TEXTURE_EXPLICIT_MODE=0,N_.TEXTURE_SPHERICAL_MODE=1,N_.TEXTURE_PLANAR_MODE=2,N_.TEXTURE_CUBIC_MODE=3,N_.TEXTURE_PROJECTION_MODE=4,N_.TEXTURE_SKYBOX_MODE=5,N_.TEXTURE_INVCUBIC_MODE=6,N_.TEXTURE_EQUIRECTANGULAR_MODE=7,N_.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,N_.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,N_.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,N_.TEXTURE_FILTERING_QUALITY_HIGH=64,N_.TEXTURE_FILTERING_QUALITY_MEDIUM=16,N_.TEXTURE_FILTERING_QUALITY_LOW=8,N_.SCALEMODE_FLOOR=1,N_.SCALEMODE_NEAREST=2,N_.SCALEMODE_CEILING=3,N_.MATERIAL_TextureDirtyFlag=1,N_.MATERIAL_LightDirtyFlag=2,N_.MATERIAL_FresnelDirtyFlag=4,N_.MATERIAL_AttributesDirtyFlag=8,N_.MATERIAL_MiscDirtyFlag=16,N_.MATERIAL_PrePassDirtyFlag=32,N_.MATERIAL_AllDirtyFlag=63,N_.MATERIAL_TriangleFillMode=0,N_.MATERIAL_WireFrameFillMode=1,N_.MATERIAL_PointFillMode=2,N_.MATERIAL_PointListDrawMode=3,N_.MATERIAL_LineListDrawMode=4,N_.MATERIAL_LineLoopDrawMode=5,N_.MATERIAL_LineStripDrawMode=6,N_.MATERIAL_TriangleStripDrawMode=7,N_.MATERIAL_TriangleFanDrawMode=8,N_.MATERIAL_ClockWiseSideOrientation=0,N_.MATERIAL_CounterClockWiseSideOrientation=1,N_.ACTION_NothingTrigger=0,N_.ACTION_OnPickTrigger=1,N_.ACTION_OnLeftPickTrigger=2,N_.ACTION_OnRightPickTrigger=3,N_.ACTION_OnCenterPickTrigger=4,N_.ACTION_OnPickDownTrigger=5,N_.ACTION_OnDoublePickTrigger=6,N_.ACTION_OnPickUpTrigger=7,N_.ACTION_OnPickOutTrigger=16,N_.ACTION_OnLongPressTrigger=8,N_.ACTION_OnPointerOverTrigger=9,N_.ACTION_OnPointerOutTrigger=10,N_.ACTION_OnEveryFrameTrigger=11,N_.ACTION_OnIntersectionEnterTrigger=12,N_.ACTION_OnIntersectionExitTrigger=13,N_.ACTION_OnKeyDownTrigger=14,N_.ACTION_OnKeyUpTrigger=15,N_.PARTICLES_BILLBOARDMODE_Y=2,N_.PARTICLES_BILLBOARDMODE_ALL=7,N_.PARTICLES_BILLBOARDMODE_STRETCHED=8,N_.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,N_.MESHES_CULLINGSTRATEGY_STANDARD=0,N_.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,N_.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,N_.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,N_.SCENELOADER_NO_LOGGING=0,N_.SCENELOADER_MINIMAL_LOGGING=1,N_.SCENELOADER_SUMMARY_LOGGING=2,N_.SCENELOADER_DETAILED_LOGGING=3,N_.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,N_.PREPASS_POSITION_TEXTURE_TYPE=1,N_.PREPASS_VELOCITY_TEXTURE_TYPE=2,N_.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,N_.PREPASS_COLOR_TEXTURE_TYPE=4,N_.PREPASS_DEPTH_TEXTURE_TYPE=5,N_.PREPASS_NORMAL_TEXTURE_TYPE=6,N_.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,N_.BUFFER_CREATIONFLAG_READ=1,N_.BUFFER_CREATIONFLAG_WRITE=2,N_.BUFFER_CREATIONFLAG_READWRITE=3,N_.BUFFER_CREATIONFLAG_UNIFORM=4,N_.BUFFER_CREATIONFLAG_VERTEX=8,N_.BUFFER_CREATIONFLAG_INDEX=16,N_.BUFFER_CREATIONFLAG_STORAGE=32,N_.BUFFER_CREATIONFLAG_INDIRECT=64,N_.RENDERPASS_MAIN=0,N_.INPUT_ALT_KEY=18,N_.INPUT_CTRL_KEY=17,N_.INPUT_META_KEY1=91,N_.INPUT_META_KEY2=92,N_.INPUT_META_KEY3=93,N_.INPUT_SHIFT_KEY=16,N_.SNAPSHOTRENDERING_STANDARD=0,N_.SNAPSHOTRENDERING_FAST=1,N_.PERSPECTIVE_CAMERA=0,N_.ORTHOGRAPHIC_CAMERA=1,N_.FOVMODE_VERTICAL_FIXED=0,N_.FOVMODE_HORIZONTAL_FIXED=1,N_.RIG_MODE_NONE=0,N_.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,N_.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,N_.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,N_.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,N_.RIG_MODE_STEREOSCOPIC_INTERLACED=14,N_.RIG_MODE_VR=20,N_.RIG_MODE_CUSTOM=22,N_.MAX_SUPPORTED_UV_SETS=6,N_.GL_ALPHA_EQUATION_ADD=32774,N_.GL_ALPHA_EQUATION_MIN=32775,N_.GL_ALPHA_EQUATION_MAX=32776,N_.GL_ALPHA_EQUATION_SUBTRACT=32778,N_.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,N_.GL_ALPHA_FUNCTION_SRC=768,N_.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,N_.GL_ALPHA_FUNCTION_SRC_ALPHA=770,N_.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,N_.GL_ALPHA_FUNCTION_DST_ALPHA=772,N_.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,N_.GL_ALPHA_FUNCTION_DST_COLOR=774,N_.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,N_.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,N_.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,N_.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,N_.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,N_.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,N_.SnippetUrl="https://snippet.babylonjs.com",N_.FOGMODE_NONE=0,N_.FOGMODE_EXP=1,N_.FOGMODE_EXP2=2,N_.FOGMODE_LINEAR=3,N_.BYTE=5120,N_.UNSIGNED_BYTE=5121,N_.SHORT=5122,N_.UNSIGNED_SHORT=5123,N_.INT=5124,N_.UNSIGNED_INT=5125,N_.FLOAT=5126,N_.PositionKind="position",N_.NormalKind="normal",N_.TangentKind="tangent",N_.UVKind="uv",N_.UV2Kind="uv2",N_.UV3Kind="uv3",N_.UV4Kind="uv4",N_.UV5Kind="uv5",N_.UV6Kind="uv6",N_.ColorKind="color",N_.ColorInstanceKind="instanceColor",N_.MatricesIndicesKind="matricesIndices",N_.MatricesWeightsKind="matricesWeights",N_.MatricesIndicesExtraKind="matricesIndicesExtra",N_.MatricesWeightsExtraKind="matricesWeightsExtra";class F_{constructor(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}}class L_ extends oo{isDeterministicLockStep(){return this._options.deterministicLockstep}getLockstepMaxSteps(){return this._options.lockstepMaxSteps}getHardwareScalingLevel(){return 1}constructor(e=new F_){super(null),void 0===e.deterministicLockstep&&(e.deterministicLockstep=!1),void 0!==e.timeStep&&(this._timeStep=e.timeStep),void 0===e.lockstepMaxSteps&&(e.lockstepMaxSteps=4),this._options=e,se.SetMatrixPrecision(!!e.useHighPrecisionMatrix),this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:512,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!1,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:0,uintIndices:!1,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!1,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!1,instancedArrays:!1,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,maxMSAASamples:1,blendMinMax:!1,canUseGLInstanceID:!1,canUseGLVertexID:!1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:128,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!1,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1},e.renderingCanvas&&(this._renderingCanvas=e.renderingCanvas),Ne.Log(`Babylon.js v${oo.Version} - Null engine`);const t="undefined"!=typeof self?self:void 0!==i.g?i.g:window;"undefined"==typeof URL&&(t.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(t.Blob=function(){})}createVertexBuffer(e){const t=new Qs;return t.references=1,t}createIndexBuffer(e){const t=new Qs;return t.references=1,t}clear(e,t,i,s=!1){}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight}setViewport(e,t,i){this._cachedViewport=e}createShaderProgram(e,t,i,s,r){return{__SPECTOR_rebuildProgram:null}}getUniforms(e,t){return[]}getAttributes(e,t){return[]}bindSamplers(e){this._currentEffect=null}enableEffect(e){e=null!==e&&Ws(e)?e.effect:e,this._currentEffect=e,e&&(e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setState(e,t=0,i,s=!1,r,n,o=0){}setIntArray(e,t){return!0}setIntArray2(e,t){return!0}setIntArray3(e,t){return!0}setIntArray4(e,t){return!0}setFloatArray(e,t){return!0}setFloatArray2(e,t){return!0}setFloatArray3(e,t){return!0}setFloatArray4(e,t){return!0}setArray(e,t){return!0}setArray2(e,t){return!0}setArray3(e,t){return!0}setArray4(e,t){return!0}setMatrices(e,t){return!0}setMatrix3x3(e,t){return!0}setMatrix2x2(e,t){return!0}setFloat(e,t){return!0}setFloat2(e,t,i){return!0}setFloat3(e,t,i,s){return!0}setBool(e,t){return!0}setFloat4(e,t,i,s,r){return!0}setAlphaMode(e,t=!1){this._alphaMode!==e&&(this.alphaState.alphaBlend=0!==e,t||this.setDepthWrite(0===e),this._alphaMode=e)}bindBuffers(e,t,i){}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this.depthCullingState.reset(),this.alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}draw(e,t,i,s){}drawElementsType(e,t,i,s){}drawArraysType(e,t,i,s){}_createTexture(){return{}}_releaseTexture(e){}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u){const d=new ss(this,is.Url),_=String(e);return d.url=_,d.generateMipMaps=!t,d.samplingMode=r,d.invertY=i,d.baseWidth=this._options.textureSize,d.baseHeight=this._options.textureSize,d.width=this._options.textureSize,d.height=this._options.textureSize,h&&(d.format=h),d.isReady=!0,n&&setTimeout((()=>{n(d)})),this._internalTexturesCache.push(d),d}_createHardwareRenderTargetWrapper(e,t,i){const s=new Bl(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),s={};void 0!==t&&"object"==typeof t?(s.generateMipMaps=t.generateMipMaps,s.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,s.generateStencilBuffer=s.generateDepthBuffer&&t.generateStencilBuffer,s.type=void 0===t.type?0:t.type,s.samplingMode=void 0===t.samplingMode?3:t.samplingMode):(s.generateMipMaps=t,s.generateDepthBuffer=!0,s.generateStencilBuffer=!1,s.type=0,s.samplingMode=3);const r=new ss(this,is.RenderTarget),n=e.width||e,o=e.height||e;return i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer,r.baseWidth=n,r.baseHeight=o,r.width=n,r.height=o,r.isReady=!0,r.samples=1,r.generateMipMaps=!!s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,this._internalTexturesCache.push(r),i}createRenderTargetCubeTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,(1!==s.type||this._caps.textureFloatLinearFiltering)&&(2!==s.type||this._caps.textureHalfFloatLinearFiltering)||(s.samplingMode=1),i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer;const r=new ss(this,is.RenderTarget);return r.baseWidth=e,r.baseHeight=e,r.width=e,r.height=e,r.isReady=!0,r.isCube=!0,r.samples=1,r.generateMipMaps=!!s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,this._internalTexturesCache.push(r),i}updateTextureSamplingMode(e,t){t.samplingMode=e}createRawTexture(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new ss(this,is.Raw);return u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u._compression=a,u.type=l,u._useSRGBBuffer=c,this._doNotHandleContextLost||(u._bufferView=e),u}updateRawTexture(e,t,i,s,r=null,n=0,o=!1){e&&(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r,e.type=n,e._useSRGBBuffer=o)}bindFramebuffer(e,t,i,s,r){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=null,this._cachedViewport&&!r&&this.setViewport(this._cachedViewport,i,s)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._currentFramebuffer=null}createDynamicVertexBuffer(e){const t=new Qs;return t.references=1,t.capacity=1,t}updateDynamicTexture(e,t,i,s=!1,r){}areAllEffectsReady(){return!0}getError(){return 0}_getUnpackAlignement(){return 1}_unpackFlipY(e){}updateDynamicIndexBuffer(e,t,i=0){}updateDynamicVertexBuffer(e,t,i,s){}_bindTextureDirectly(e,t){return this._boundTexturesCache[this._activeChannel]!==t&&(this._boundTexturesCache[this._activeChannel]=t,!0)}_bindTexture(e,t){e<0||this._bindTextureDirectly(0,t)}_deleteBuffer(e){}releaseEffects(){}displayLoadingUI(){}hideLoadingUI(){}set loadingUIText(e){}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){}_uploadDataToTextureDirectly(e,t,i=0,s=0){}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){}_uploadImageToTexture(e,t,i=0,s=0){}}ns.prototype._partialLoadFile=function(e,t,i,s,r=null){this._loadFile(e,(e=>{i[t]=e,i._internalCount++,6===i._internalCount&&s(i)}),void 0,void 0,!0,((e,t)=>{r&&e&&r(e.status+" "+e.statusText,t)}))},ns.prototype._cascadeLoadFiles=function(e,t,i,s=null){const r=[];r._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,r,t,s)},ns.prototype._cascadeLoadImgs=function(e,t,i,s,r=null,n){const o=[];o._internalCount=0;for(let a=0;a<6;a++)this._partialLoadImg(s[a],a,o,e,t,i,r,n)},ns.prototype._partialLoadImg=function(e,t,i,s,r,n,o=null,a){const l=Cs();ds(e,(e=>{i[t]=e,i._internalCount++,s&&s.removePendingData(l),6===i._internalCount&&n&&n(r,i)}),((e,t)=>{s&&s.removePendingData(l),o&&o(e,t)}),s?s.offlineProvider:null,a),s&&s.addPendingData(l)},ns.prototype.createCubeTextureBase=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d=null,_=null,p=!1){const f=u||new ss(this,is.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!s,f._lodGenerationScale=h,f._lodGenerationOffset=c,f._useSRGBBuffer=!!p&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!s),f!==u&&(f.label=e.substring(0,60)),this._doNotHandleContextLost||(f._extension=a,f._files=i);const m=e;this._transformTextureUrl&&!u&&(e=this._transformTextureUrl(e));const g=e.split("?")[0],v=g.lastIndexOf("."),x=a||(v>-1?g.substring(v).toLowerCase():"");let b=null;for(const e of ns._TextureLoaders)if(e.canLoad(x)){b=e;break}const T=(u,g)=>{e===m?n&&u&&n(u.status+" "+u.statusText,g):(Ne.Warn(`Failed to load ${e}, falling back to the ${m}`),this.createCubeTextureBase(m,t,i,!!s,r,n,o,a,l,h,c,f,d,_,p))};if(b){const s=e=>{d&&d(f,e),b.loadCubeData(e,f,l,r,n)};i&&6===i.length?b.supportCascades?this._cascadeLoadFiles(t,(e=>s(e.map((e=>new Uint8Array(e))))),i,n):n?n("Textures type does not support cascades."):Ne.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>s(new Uint8Array(e))),void 0,void 0,!0,T)}else{if(!i||0===i.length)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(t,f,((e,t)=>{_&&_(e,t)}),i,n)}return this._internalTexturesCache.push(f),f};class B_{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=_o.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=_o.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}ns.prototype.getGPUFrameTimeCounter=function(){return null},ns.prototype.captureGPUFrameTime=function(e){},ns.prototype.createQuery=function(){return null},ns.prototype.deleteQuery=function(e){return this},ns.prototype.isQueryResultAvailable=function(e){return!1},ns.prototype.getQueryResult=function(e){return 0},ns.prototype.beginOcclusionQuery=function(e,t){return!1},ns.prototype.endOcclusionQuery=function(e){return this},Object.defineProperty(_o.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(_o.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new B_),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(_o.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(_o.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(_o.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(_o.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(_o.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),_o.prototype._checkOcclusionQuery=function(){const e=this._occlusionDataStorage;if(e.occlusionType===_o.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;const t=this.getEngine();if(!t.getCaps().supportOcclusionQuery)return e.isOccluded=!1,!1;if(!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&null!==this._occlusionQuery&&void 0!==this._occlusionQuery)if(t.isQueryResultAvailable(this._occlusionQuery)){const i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,!(-1!==e.occlusionRetryCount&&e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==_o.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==_o.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}const i=this.getScene();if(i.getBoundingBoxRenderer){const s=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),this._occlusionQuery&&t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(s.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded};class k_{}const V_=new K,U_=new K;Object.defineProperty(ns.prototype,"onBeforeViewRenderObservable",{get:function(){return V_}}),Object.defineProperty(ns.prototype,"onAfterViewRenderObservable",{get:function(){return U_}}),Object.defineProperty(ns.prototype,"inputElement",{get:function(){return this._inputElement},set:function(e){this._inputElement!==e&&(this._inputElement=e,this._onEngineViewChanged?.())}}),ns.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},ns.prototype.registerView=function(e,t,i){this.views||(this.views=[]);for(const t of this.views)if(t.target===e)return t;const s=this.getRenderingCanvas();s&&(e.width=s.width,e.height=s.height);const r={target:e,camera:t,clearBeforeCopy:i,enabled:!0,id:(1e5*Math.random()).toFixed()};return this.views.push(r),t&&!Array.isArray(t)&&t.onDisposeObservable.add((()=>{this.unRegisterView(e)})),r},ns.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(const t of this.views)if(t.target===e){const e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},ns.prototype._renderViewStep=function(e){const t=e.target,i=t.getContext("2d");if(!i)return!0;const s=this.getRenderingCanvas();V_.notifyObservers(e);const r=e.camera;let n=null,o=null,a=null;if(r&&(a=Array.isArray(r)?r[0].getScene():r.getScene(),n=a.activeCamera,o=a.activeCameras,this.activeView=e,Array.isArray(r)?a.activeCameras=r:(a.activeCamera=r,a.activeCameras=null)),e.customResize)e.customResize(t);else{const e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),r=e!==t.width||s.width!==t.width||i!==t.height||s.height!==t.height;t.clientWidth&&t.clientHeight&&r&&(t.width=e,t.height=i,this.setSize(e,i))}return!(!s.width||!s.height||(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,s.width,s.height),i.drawImage(s,0,0),a&&(a.activeCameras=o,a.activeCamera=n),U_.notifyObservers(e),0))},ns.prototype._renderViews=function(){if(!this.views||0===this.views.length)return!1;if(!this.getRenderingCanvas())return!1;let e;for(const t of this.views)if(t.enabled)if(t.target!==this.inputElement){if(!this._renderViewStep(t))return!1}else e=t;return!(e&&!this._renderViewStep(e)||(this.activeView=null,0))},ns.prototype._debugPushGroup=function(e,t){},ns.prototype._debugPopGroup=function(e){},ns.prototype._debugInsertMarker=function(e,t){},ns.prototype._debugFlushPendingCommands=function(){};class G_{constructor(){this._timeElapsedQueryEnded=!1}}oo.prototype.createQuery=function(){const e=this._gl.createQuery();if(!e)throw new Error("Unable to create Occlusion Query");return e},oo.prototype.deleteQuery=function(e){return this._gl.deleteQuery(e),this},oo.prototype.isQueryResultAvailable=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT_AVAILABLE)},oo.prototype.getQueryResult=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT)},oo.prototype.beginOcclusionQuery=function(e,t){const i=this._getGlAlgorithmType(e);return this._gl.beginQuery(i,t),!0},oo.prototype.endOcclusionQuery=function(e){const t=this._getGlAlgorithmType(e);return this._gl.endQuery(t),this},oo.prototype._createTimeQuery=function(){const e=this.getCaps().timerQuery;return e.createQueryEXT?e.createQueryEXT():this.createQuery()},oo.prototype._deleteTimeQuery=function(e){const t=this.getCaps().timerQuery;t.deleteQueryEXT?t.deleteQueryEXT(e):this.deleteQuery(e)},oo.prototype._getTimeQueryResult=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT):this.getQueryResult(e)},oo.prototype._getTimeQueryAvailability=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(e)},oo.prototype.startTimeQuery=function(){const e=this.getCaps(),t=e.timerQuery;if(!t)return null;const i=new G_;if(this._gl.getParameter(t.GPU_DISJOINT_EXT),e.canUseTimestampForTimerQuery)i._startTimeQuery=this._createTimeQuery(),i._startTimeQuery&&t.queryCounterEXT(i._startTimeQuery,t.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;i._timeElapsedQuery=this._createTimeQuery(),i._timeElapsedQuery&&(t.beginQueryEXT?t.beginQueryEXT(t.TIME_ELAPSED_EXT,i._timeElapsedQuery):this._gl.beginQuery(t.TIME_ELAPSED_EXT,i._timeElapsedQuery)),this._currentNonTimestampToken=i}return i},oo.prototype.endTimeQuery=function(e){const t=this.getCaps(),i=t.timerQuery;if(!i||!e)return-1;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery)return-1;e._endTimeQuery||(e._endTimeQuery=this._createTimeQuery(),e._endTimeQuery&&i.queryCounterEXT(e._endTimeQuery,i.TIMESTAMP_EXT))}else if(!e._timeElapsedQueryEnded){if(!e._timeElapsedQuery)return-1;i.endQueryEXT?i.endQueryEXT(i.TIME_ELAPSED_EXT):(this._gl.endQuery(i.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),e._timeElapsedQueryEnded=!0}const s=this._gl.getParameter(i.GPU_DISJOINT_EXT);let r=!1;if(e._endTimeQuery?r=this._getTimeQueryAvailability(e._endTimeQuery):e._timeElapsedQuery&&(r=this._getTimeQueryAvailability(e._timeElapsedQuery)),r&&!s){let i=0;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery||!e._endTimeQuery)return-1;const t=this._getTimeQueryResult(e._startTimeQuery);i=this._getTimeQueryResult(e._endTimeQuery)-t,this._deleteTimeQuery(e._startTimeQuery),this._deleteTimeQuery(e._endTimeQuery),e._startTimeQuery=null,e._endTimeQuery=null}else{if(!e._timeElapsedQuery)return-1;i=this._getTimeQueryResult(e._timeElapsedQuery),this._deleteTimeQuery(e._timeElapsedQuery),e._timeElapsedQuery=null,e._timeElapsedQueryEnded=!1}return i}return-1},oo.prototype._captureGPUFrameTime=!1,oo.prototype._gpuFrameTime=new wr,oo.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime},oo.prototype.captureGPUFrameTime=function(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.onBeginFrameObservable.add((()=>{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())})),this._onEndFrameObserver=this.onEndFrameObservable.add((()=>{if(!this._gpuFrameTimeToken)return;const e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))}))):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},oo.prototype._getGlAlgorithmType=function(e){return e===_o.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED};var z_=!0;oo.prototype.createTransformFeedback=function(){const e=this._gl.createTransformFeedback();if(!e)throw new Error("Unable to create Transform Feedback");return e},oo.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},oo.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},oo.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},oo.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},oo.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},oo.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},qs.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;const s=this._getInternalFormat(e.format),r=this._getRGBABufferInternalSizedFormat(0,e.format),n=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);const t=e._workingCanvas.getContext("2d");if(!t)throw new Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},qs.prototype.restoreSingleAttachment=function(){const e=this._gl;this.bindAttachments([e.BACK])},qs.prototype.restoreSingleAttachmentForRenderTarget=function(){const e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},qs.prototype.buildTextureLayout=function(e){const t=this._gl,i=[];for(let s=0;s1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],s.readBuffer(r[t]),s.drawBuffers(r),s.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,s.COLOR_BUFFER_BIT,s.NEAREST)}for(let e=0;e1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];s.drawBuffers(r)}for(let i=0;i1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(a=t.depthTextureFormat)),g.label=t?.label??"MultiRenderTargetWrapper";const v=this._gl,x=v.createFramebuffer();this._bindUnboundFramebuffer(x);const b=e.width||e,T=e.height||e,y=[],S=[],C=this.webGLVersion>1&&o&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),E=this._setupFramebufferDepthAttachments(!C&&n,!o&&r,b,T);g._framebuffer=x,g._depthStencilBuffer=E,g._generateDepthBuffer=!o&&r,g._generateStencilBuffer=!C&&n,g._attachments=S;for(let e=0;e1||this.isWebGPU);const p=this.webGLVersion>1,f=v[p?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(S.push(f),-1===o)continue;const g=new ss(this,is.MultiRenderTarget);y[e]=g,v.activeTexture(v["TEXTURE"+e]),v.bindTexture(o,g._hardwareTexture.underlyingResource),v.texParameteri(o,v.TEXTURE_MAG_FILTER,l.mag),v.texParameteri(o,v.TEXTURE_MIN_FILTER,l.min),v.texParameteri(o,v.TEXTURE_WRAP_S,v.CLAMP_TO_EDGE),v.texParameteri(o,v.TEXTURE_WRAP_T,v.CLAMP_TO_EDGE);const x=this._getRGBABufferInternalSizedFormat(i,n,r),C=this._getInternalFormat(n),E=this._getWebGLTextureType(i);if(!p||35866!==o&&32879!==o)if(34067===o){for(let e=0;e<6;e++)v.texImage2D(v.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,x,b,T,0,C,E,null);g.isCube=!0}else v.texImage2D(v.TEXTURE_2D,0,x,b,T,0,C,E,null);else 35866===o?g.is2DArray=!0:g.is3D=!0,g.baseDepth=g.depth=a,v.texImage3D(o,0,x,b,T,a,0,C,E,null);s&&v.generateMipmap(o),this._bindTextureDirectly(o,null),g.baseWidth=b,g.baseHeight=T,g.width=b,g.height=T,g.isReady=!0,g.samples=1,g.generateMipMaps=s,g.samplingMode=t,g.type=i,g._useSRGBBuffer=r,g.format=n,this._internalTexturesCache.push(g)}if(o&&this._caps.depthTextureExtension){const e=new ss(this,is.Depth);let t=5,i=v.DEPTH_COMPONENT16,r=v.DEPTH_COMPONENT,n=v.UNSIGNED_SHORT,o=v.DEPTH_ATTACHMENT;this.webGLVersion<2?i=v.DEPTH_COMPONENT:14===a?(t=1,n=v.FLOAT,i=v.DEPTH_COMPONENT32F):18===a?(t=0,n=v.FLOAT_32_UNSIGNED_INT_24_8_REV,i=v.DEPTH32F_STENCIL8,r=v.DEPTH_STENCIL,o=v.DEPTH_STENCIL_ATTACHMENT):16===a?(t=0,n=v.UNSIGNED_INT,i=v.DEPTH_COMPONENT24,o=v.DEPTH_ATTACHMENT):13!==a&&17!==a||(t=12,n=v.UNSIGNED_INT_24_8,i=v.DEPTH24_STENCIL8,r=v.DEPTH_STENCIL,o=v.DEPTH_STENCIL_ATTACHMENT),v.activeTexture(v.TEXTURE0),v.bindTexture(v.TEXTURE_2D,e._hardwareTexture.underlyingResource),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_MAG_FILTER,v.NEAREST),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_MIN_FILTER,v.NEAREST),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_WRAP_S,v.CLAMP_TO_EDGE),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_WRAP_T,v.CLAMP_TO_EDGE),v.texImage2D(v.TEXTURE_2D,0,i,b,T,0,r,n,null),v.framebufferTexture2D(v.FRAMEBUFFER,o,v.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=b,e.baseHeight=T,e.width=b,e.height=T,e.isReady=!0,e.samples=1,e.generateMipMaps=s,e.samplingMode=1,e.format=a,e.type=t,y[l]=e,this._internalTexturesCache.push(e)}return g.setTextures(y),i&&v.drawBuffers(S),this._bindUnboundFramebuffer(null),g.setLayerAndFaceIndices(f,p),this.resetTextureCache(),g},qs.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const s=e._attachments.length;if(0===s)return 1;const r=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);const n=!!e._depthStencilBuffer;if(n&&(r.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(r.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof r.renderbufferStorageMultisample){const n=r.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);const o=[];for(let t=0;t1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(s.width,s.height,t,-1,this._getRGBABufferInternalSizedFormat(s.type,s.format,s._useSRGBBuffer),a);if(!l)throw new Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(l),s.samples=t,o.push(a)}i&&r.drawBuffers(o)}else this._bindUnboundFramebuffer(e._framebuffer);return n&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},qs.prototype._createDepthStencilCubeTexture=function(e,t){const i=new ss(this,is.DepthStencil);if(i.isCube=!0,1===this.webGLVersion)return Ne.Error("Depth cube texture is not supported by WebGL 1."),i;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t},r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction);for(let t=0;t<6;t++)s.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH24_STENCIL8,e,e,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH_COMPONENT24,e,e,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(i),i},qs.prototype._setCubeMapTextureParams=function(e,t,i){const s=this._gl;s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,t?s.LINEAR_MIPMAP_LINEAR:s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null)},qs.prototype.createCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,_=!1){const p=this._gl;return this.createCubeTextureBase(e,t,i,!!s,r,n,o,a,l,h,c,u,(e=>this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const i=this.needPOTTextures?Os(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,n=i,a=[p.TEXTURE_CUBE_MAP_POSITIVE_X,p.TEXTURE_CUBE_MAP_POSITIVE_Y,p.TEXTURE_CUBE_MAP_POSITIVE_Z,p.TEXTURE_CUBE_MAP_NEGATIVE_X,p.TEXTURE_CUBE_MAP_NEGATIVE_Y,p.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const l=o?this._getInternalFormat(o,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:p.RGBA;let h=o?this._getInternalFormat(o):p.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(h=l);for(let e=0;e1,e=>e.y,e=>e.z,e=>e.x,e=>e.x*e.y,e=>e.y*e.z,e=>3*e.z*e.z-1,e=>e.x*e.z,e=>e.x*e.x-e.y*e.y],X_=(e,t)=>W_[e]*H_[e](t),Y_=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4];class Q_{constructor(){this.preScaled=!1,this.l00=_e.Zero(),this.l1_1=_e.Zero(),this.l10=_e.Zero(),this.l11=_e.Zero(),this.l2_2=_e.Zero(),this.l2_1=_e.Zero(),this.l20=_e.Zero(),this.l21=_e.Zero(),this.l22=_e.Zero()}addLight(e,t,i){ve.Vector3[0].set(t.r,t.g,t.b);const s=ve.Vector3[0],r=ve.Vector3[1];s.scaleToRef(i,r),r.scaleToRef(X_(0,e),ve.Vector3[2]),this.l00.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(1,e),ve.Vector3[2]),this.l1_1.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(2,e),ve.Vector3[2]),this.l10.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(3,e),ve.Vector3[2]),this.l11.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(4,e),ve.Vector3[2]),this.l2_2.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(5,e),ve.Vector3[2]),this.l2_1.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(6,e),ve.Vector3[2]),this.l20.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(7,e),ve.Vector3[2]),this.l21.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(8,e),ve.Vector3[2]),this.l22.addInPlace(ve.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(Y_[0]),this.l1_1.scaleInPlace(Y_[1]),this.l10.scaleInPlace(Y_[2]),this.l11.scaleInPlace(Y_[3]),this.l2_2.scaleInPlace(Y_[4]),this.l2_1.scaleInPlace(Y_[5]),this.l20.scaleInPlace(Y_[6]),this.l21.scaleInPlace(Y_[7]),this.l22.scaleInPlace(Y_[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(W_[0]),this.l1_1.scaleInPlace(W_[1]),this.l10.scaleInPlace(W_[2]),this.l11.scaleInPlace(W_[3]),this.l2_2.scaleInPlace(W_[4]),this.l2_1.scaleInPlace(W_[5]),this.l20.scaleInPlace(W_[6]),this.l21.scaleInPlace(W_[7]),this.l22.scaleInPlace(W_[8])}updateFromArray(e){return _e.FromArrayToRef(e[0],0,this.l00),_e.FromArrayToRef(e[1],0,this.l1_1),_e.FromArrayToRef(e[2],0,this.l10),_e.FromArrayToRef(e[3],0,this.l11),_e.FromArrayToRef(e[4],0,this.l2_2),_e.FromArrayToRef(e[5],0,this.l2_1),_e.FromArrayToRef(e[6],0,this.l20),_e.FromArrayToRef(e[7],0,this.l21),_e.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return _e.FromFloatsToRef(e[0],e[1],e[2],this.l00),_e.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),_e.FromFloatsToRef(e[6],e[7],e[8],this.l10),_e.FromFloatsToRef(e[9],e[10],e[11],this.l11),_e.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),_e.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),_e.FromFloatsToRef(e[18],e[19],e[20],this.l20),_e.FromFloatsToRef(e[21],e[22],e[23],this.l21),_e.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new Q_).updateFromArray(e)}static FromPolynomial(e){const t=new Q_;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}}class j_{constructor(){this.x=_e.Zero(),this.y=_e.Zero(),this.z=_e.Zero(),this.xx=_e.Zero(),this.yy=_e.Zero(),this.zz=_e.Zero(),this.xy=_e.Zero(),this.yz=_e.Zero(),this.zx=_e.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=Q_.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){ve.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=ve.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),ve.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),ve.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(ve.Vector3[0]).addInPlace(ve.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(ve.Vector3[0]).subtractInPlace(ve.Vector3[1]),this.zz.copyFrom(e.l00),ve.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(ve.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return(new j_).updateFromHarmonics(e)}static FromArray(e){const t=new j_;return _e.FromArrayToRef(e[0],0,t.x),_e.FromArrayToRef(e[1],0,t.y),_e.FromArrayToRef(e[2],0,t.z),_e.FromArrayToRef(e[3],0,t.xx),_e.FromArrayToRef(e[4],0,t.yy),_e.FromArrayToRef(e[5],0,t.zz),_e.FromArrayToRef(e[6],0,t.yz),_e.FromArrayToRef(e[7],0,t.zx),_e.FromArrayToRef(e[8],0,t.xy),t}}class K_{constructor(e,t,i,s){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=s}}class $_{static ConvertCubeMapTextureToSphericalPolynomial(e){if(!e.isCube)return null;e.getScene()?.getEngine().flushFramebuffer();const t=e.getSize().width,i=e.readPixels(0,void 0,void 0,!1),s=e.readPixels(1,void 0,void 0,!1);let r,n;e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),n=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),n=e.readPixels(3,void 0,void 0,!1));const o=e.readPixels(4,void 0,void 0,!1),a=e.readPixels(5,void 0,void 0,!1),l=e.gammaSpace;let h=0;return 1!=e.textureType&&2!=e.textureType||(h=1),new Promise((e=>{Promise.all([s,i,r,n,o,a]).then((([i,s,r,n,o,a])=>{const c={size:t,right:s,left:i,up:r,down:n,front:o,back:a,format:5,type:h,gammaSpace:l};e(this.ConvertCubeMapToSphericalPolynomial(c))}))}))}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new Q_;let i=0;const s=2/e.size,r=s,n=.5*s,o=n-1;for(let a=0;a<6;a++){const l=this._FileFaces[a],h=e[l.name];let c=o;const u=5===e.format?4:3;for(let a=0;ag){const t=g/e;p*=t,f*=t,m*=t}}else p=be.Clamp(p,0,g),f=be.Clamp(f,0,g),m=be.Clamp(m,0,g);const v=new Ee(p,f,m);t.addLight(o,v,_),i+=_,d+=s}c+=r}}const a=4*Math.PI*6/6/i;return t.scaleInPlace(a),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),j_.FromHarmonics(t)}}$_._FileFaces=[new K_("right",new _e(1,0,0),new _e(0,0,-1),new _e(0,-1,0)),new K_("left",new _e(-1,0,0),new _e(0,0,1),new _e(0,-1,0)),new K_("up",new _e(0,1,0),new _e(1,0,0),new _e(0,0,1)),new K_("down",new _e(0,-1,0),new _e(1,0,0),new _e(0,0,-1)),new K_("front",new _e(0,0,1),new _e(1,0,0),new _e(0,-1,0)),new K_("back",new _e(0,0,-1),new _e(-1,0,0),new _e(0,-1,0))],$_.MAX_HDRI_VALUE=4096,$_.PRESERVE_CLAMPED_COLORS=!1;Bi.ShadersStore.lodPixelShader="#extension GL_EXT_shader_texture_lod : enable\nprecision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform sampler2D textureSampler;uniform float lod;uniform vec2 texSize;uniform bool gamma;void main(void)\n{gl_FragColor=textureLod(textureSampler,vUV,lod);if (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";function q_(e,t,i,s=!0){const r=e.getScene(),n=r.getEngine(),o=new ih("resized"+e.name,{width:t,height:i},r,!e.noMipmap,!0,e._texture.type,!1,e.samplingMode,!1);o.wrapU=e.wrapU,o.wrapV=e.wrapV,o.uOffset=e.uOffset,o.vOffset=e.vOffset,o.uScale=e.uScale,o.vScale=e.vScale,o.uAng=e.uAng,o.vAng=e.vAng,o.wAng=e.wAng,o.coordinatesIndex=e.coordinatesIndex,o.level=e.level,o.anisotropicFilteringLevel=e.anisotropicFilteringLevel,o._texture.isReady=!1,e.wrapU=Pa.CLAMP_ADDRESSMODE,e.wrapV=Pa.CLAMP_ADDRESSMODE;const a=new yc("pass",1,null,s?Pa.BILINEAR_SAMPLINGMODE:Pa.NEAREST_SAMPLINGMODE,n,!1,0);return a.externalTextureSamplerBinding=!0,a.getEffect().executeWhenCompiled((()=>{a.onApply=function(t){t.setTexture("textureSampler",e)};const t=o.renderTarget;t&&(r.postProcessManager.directRender([a],t),n.unBindFramebuffer(t),o.disposeFramebufferObjects(),a.dispose(),o.getInternalTexture().isReady=!0)})),o}function Z_(e,t,i,s,r,n,o,a){const l=t.getEngine();return t.isReady=!1,r=r??t.samplingMode,s=s??t.type,n=n??t.format,o=o??t.width,a=a??t.height,-1===s&&(s=0),new Promise((h=>{const c=new Vl("postprocess",e,null,null,1,null,r,l,!1,void 0,s,void 0,null,!1,n);c.externalTextureSamplerBinding=!0;const u=l.createRenderTargetTexture({width:o,height:a},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:r,type:s,format:n});c.getEffect().executeWhenCompiled((()=>{c.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([c],u,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),c&&c.dispose(),u._swapAndDie(t),t.type=s,t.format=5,t.isReady=!0,h(t)}))}))}let J_,ep;function tp(e){J_||(J_=new Float32Array(1),ep=new Int32Array(J_.buffer)),J_[0]=e;const t=ep[0];let i=t>>16&32768,s=t>>12&2047;const r=t>>23&255;return r<103?i:r>142?(i|=31744,i|=(255==r?0:1)&&8388607&t,i):r<113?(s|=2048,i|=(s>>114-r)+(s>>113-r&1),i):(i|=r-112<<10|s>>1,i+=1&s,i)}function ip(e){const t=(32768&e)>>15,i=(31744&e)>>10,s=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(s/Math.pow(2,10)):31==i?s?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+s/Math.pow(2,10))}Bi.ShadersStore.lodCubePixelShader="precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform samplerCube textureSampler;uniform float lod;uniform bool gamma;void main(void)\n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x),lod);\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x),lod);\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x),lod);\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x),lod);\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001),lod);\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001),lod);\n#endif\nif (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";const sp=async(e,t,i,s,r)=>{const n=e.getScene(),o=n.getEngine();let a;if(e.isCube){const e=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];a=new Vl("lodCube","lodCube",["lod","gamma"],null,1,null,Pa.NEAREST_NEAREST_MIPNEAREST,o,!1,e[s])}else a=new Vl("lod","lod",["lod","gamma"],null,1,null,Pa.NEAREST_NEAREST_MIPNEAREST,o);await new Promise((e=>{a.getEffect().executeWhenCompiled((()=>{e(0)}))}));const l=new ih("temp",{width:t,height:i},n,!1);a.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",r),t.setBool("gamma",e.gammaSpace)};const h=e.getInternalTexture();try{if(l.renderTarget&&h){const s=h.samplingMode;0!==r?e.updateSamplingMode(Pa.NEAREST_NEAREST_MIPNEAREST):e.updateSamplingMode(Pa.NEAREST_NEAREST),n.postProcessManager.directRender([a],l.renderTarget,!0),e.updateSamplingMode(s);const c=await o.readPixels(0,0,t,i),u=new Uint8Array(c.buffer,0,c.byteLength);return o.unBindFramebuffer(l.renderTarget),u}throw Error("Render to texture failed.")}finally{l.dispose(),a.dispose()}};async function rp(e,t,i,s=0,r=0){return!e.isReady()&&e._texture&&await new Promise(((t,i)=>{null!==e._texture?e._texture.onLoadedObservable.addOnce((()=>{t(0)})):i(0)})),await sp(e,t,i,s,r)}const np={CreateResizedCopy:q_,ApplyPostProcess:Z_,ToHalfFloat:tp,FromHalfFloat:ip,GetTextureDataAsync:rp},op=131072,ap=131072;function lp(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}const hp=lp("DXT1"),cp=lp("DXT3"),up=lp("DXT5"),dp=lp("DX10");class _p{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35);let s=1;t[2]&op&&(s=Math.max(1,t[7]));const r=t[21],n=r===dp?i[32]:0;let o=0;switch(r){case 113:o=2;break;case 116:o=1;break;case dp:if(10===n){o=2;break}if(2===n){o=1;break}}return{width:t[4],height:t[3],mipmapCount:s,isFourCC:!(4&~t[20]),isRGB:!(64&~t[20]),isLuminance:(t[20]&ap)===ap,isCube:!(512&~t[28]),isCompressed:r===hp||r===cp||r===up,dxgiFormat:n,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,s,r,n){const o=new Float32Array(s),a=new Uint16Array(r,i);let l=0;for(let i=0;i>8)}static _GetRGBArrayBuffer(e,t,i,s,r,n,o,a){const l=new Uint8Array(s),h=new Uint8Array(r,i);let c=0;for(let i=0;i>8&255,C>>16&255,C>>24&255))])}var C;const E=_p._ExtractLongWordOrder(u[23]),A=_p._ExtractLongWordOrder(u[24]),P=_p._ExtractLongWordOrder(u[25]),I=_p._ExtractLongWordOrder(u[26]);S&&(b=e._getRGBABufferInternalSizedFormat(s.textureType)),g=1,u[2]&op&&!1!==r&&(g=Math.max(1,u[7]));const R=a||0,M=e.getCaps();for(let r=R;r0?s.sphericalPolynomial=$_.ConvertCubeMapToSphericalPolynomial({size:u[4],right:h[0],left:h[1],up:h[2],down:h[3],front:h[4],back:h[5],format:5,type:1,gammaSpace:!1}):s.sphericalPolynomial=void 0}}function pp(e){if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some((t=>{const i="\\b"+t+"\\b";return e&&(e===t||e.match(new RegExp(i,"g")))})))return e;const t=e.lastIndexOf("."),i=e.lastIndexOf("?"),s=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+s}_p.StoreLODInAlphaChannel=!1,qs.prototype.createPrefilteredCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(r&&r(null));const n=e.texture;if(l?e.info.sphericalPolynomial&&(n._sphericalPolynomial=e.info.sphericalPolynomial):n._sphericalPolynomial=new j_,n._source=is.CubePrefiltered,this.getCaps().textureLOD)return void(r&&r(n));const o=this._gl,a=e.width;if(!a)return;const h=[];for(let r=0;r<3;r++){const l=1-r/2,c=s,u=be.Log2(a)*i+s,d=c+(u-c)*l,_=Math.round(Math.min(Math.max(d,0),u)),p=new ss(this,is.Temp);if(p.type=n.type,p.format=n.format,p.width=Math.pow(2,Math.max(be.Log2(a)-_,0)),p.height=p.width,p.isCube=!0,p._cachedWrapU=0,p._cachedWrapV=0,this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,p,!0),p.samplingMode=2,o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),e.isDDS){const t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),_p.UploadDDSLevels(this,p,i,t,!0,6,_)}else Ne.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null);const f=new ya(t);f._isCube=!0,f._texture=p,p.isReady=!0,h.push(f)}n._lodTextureHigh=h[2],n._lodTextureMid=h[1],n._lodTextureLow=h[0],r&&r(n)}),n,o,a,l,i,s)},Object.defineProperty(oo.prototype,"texturesSupported",{get:function(){const e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(oo.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),oo.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},oo.prototype.setTextureFormatToUse=function(e){const t=this.texturesSupported;for(let i=0,s=t.length;i{this._flush()}))}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}}fp.DEFAULT_BUFFER_SIZE=65536;Bi.ShadersStore.rgbdDecodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}";class mp{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),s=i.getCaps(),r=t.isReady;let n=!1;s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?(n=!0,t.type=2):s.textureFloatRender&&s.textureFloatLinearFiltering&&(n=!0,t.type=1),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const o=()=>{const s=new Vl("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);s.externalTextureSamplerBinding=!0;const r=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});s.getEffect().executeWhenCompiled((()=>{s.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([s],r,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),s&&s.dispose(),r._swapAndDie(t),t.isReady=!0}))};n&&(r?o():e.onLoadObservable.addOnce(o))}static EncodeTextureToRGBD(e,t,i=0){return Z_("rgbdEncode",e,t,i,1,5)}}ya.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(ya.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=$_.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then((e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))),null}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});Bi.ShadersStore.rgbdEncodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}";const gp="image/png",vp=2,xp=[134,22,135,150,246,214,150,54];function bp(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;for(let e=0;evp)throw new Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "${vp}".`);return 2===e.version?e:e={...e,version:2,imageType:gp}}async function yp(e,t={}){const i=e.getInternalTexture();if(!i)return Promise.reject("The cube texture is invalid.");const s=t.imageType??gp,r=i.getEngine();if(2!==e.textureType&&1!==e.textureType&&0!==e.textureType&&0!==e.textureType&&7!==e.textureType&&-1!==e.textureType)return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");let n=1;if(!r.getCaps().textureFloatRender&&(n=2,!r.getCaps().textureHalfFloatRender))return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");e.sphericalPolynomial;const o=e.getInternalTexture()?._sphericalPolynomialPromise,a=i.width,l=new Hr(r),h={};r.flushFramebuffer();const c=be.ILog2(i.width);for(let i=0;i<=c;i++){const o=Math.pow(2,c-i);for(let a=0;a<6;a++){let c=await e.readPixels(a,i,void 0,!1);if(c&&c.byteLength===c.length){const e=new Float32Array(4*c.byteLength);for(let t=0;t{if(i){const i=t.createTexture(null,!0,!0,null,1,null,(e=>{d(e)}),e);s.getEffect().executeWhenCompiled((()=>{s.externalTextureSamplerBinding=!0,s.onApply=s=>{s._bindTexture("textureSampler",i),s.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([s],h,!0,n,o),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(r),u())}))}else{if(t._uploadImageToTexture(c,e,n,o),a){const i=l[o];i&&t._uploadImageToTexture(i._texture,e,n,0)}u()}}))}function Pp(e,t,i=gp){if(!Ds.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");const s=be.ILog2(e.width)+1,r=e.getEngine();let n=!1,o=!1,a=null,l=null,h=null;const c=r.getCaps();if(e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,r.updateTextureSamplingMode(3,e),c.textureLOD?r._features.supportRenderAndCopyToLodForFloatTextures?c.textureHalfFloatRender&&c.textureHalfFloatLinearFiltering?(n=!0,e.type=2):c.textureFloatRender&&c.textureFloatLinearFiltering&&(n=!0,e.type=1):n=!1:(n=!1,o=!0,h={}),n)a=new Vl("rgbdDecode","rgbdDecode",null,null,1,null,3,r,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,l=r.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:e.type,format:5});else if(e._isRGBD=!0,e.invertY=!0,o){const t=3,i=e._lodGenerationScale,n=e._lodGenerationOffset;for(let o=0;oAp(t,r,n,a,p,c,s,o,h,l,e)));else{const t=new Image;t.src=p,f=new Promise(((i,u)=>{t.onload=()=>{Ap(t,r,n,a,p,c,s,o,h,l,e).then((()=>i())).catch((e=>{u(e)}))},t.onerror=e=>{u(e)}}))}u.push(f)}if(t.length{l&&(r._releaseTexture(e),l._swapAndDie(e)),a&&a.dispose(),o&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))}))}function Ip(e,t){const i=(t=Tp(t)).irradiance;if(!i)return;const s=new j_;_e.FromArrayToRef(i.x,0,s.x),_e.FromArrayToRef(i.y,0,s.y),_e.FromArrayToRef(i.z,0,s.z),_e.FromArrayToRef(i.xx,0,s.xx),_e.FromArrayToRef(i.yy,0,s.yy),_e.FromArrayToRef(i.zz,0,s.zz),_e.FromArrayToRef(i.yz,0,s.yz),_e.FromArrayToRef(i.zx,0,s.zx),_e.FromArrayToRef(i.xy,0,s.xy),e._sphericalPolynomial=s}function Rp(e,t,i,s,r){const n=Pp(e.getEngine().createRawCubeTexture(null,e.width,e.format,e.type,e.generateMipMaps,e.invertY,e.samplingMode,e._compression),t).then((()=>e));return e.onRebuildCallback=e=>({proxy:n,isReady:!0,isAsync:!0}),e._source=is.CubeRawRGBD,e._bufferViewArrayArray=t,e._lodGenerationScale=s,e._lodGenerationOffset=r,e._sphericalPolynomial=i,Pp(e,t).then((()=>(e.isReady=!0,e)))}const Mp={GetEnvInfo:bp,CreateEnvTextureAsync:yp,CreateImageDataArrayBufferViews:Cp,UploadEnvLevelsAsync:Ep,UploadLevelsAsync:Pp,UploadEnvSpherical:Ip};function Op(e,t,i,s){let r=s,n=0,o="";for(;r=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function Np(e){let t=0,i="",s=!1;const r=[];for(;t=0&&e.charAt(t)!==i&&(!s||e.charAt(t)!==s);)t--;return t}function Lp(e,t,i,s){let r=e.indexOf(t);if(r<0)return e;if(i){for(;r++=0&&d.push(t.substring(i+1))}"void"!==r&&d.push("return"),this._functionDescr.push({name:n,type:r,parameters:d,body:c,callIndex:0}),e=h+1;const _=t>0?this._sourceCode.substring(0,t):"",p=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&Ne.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:s,parameters:r,body:n}=t;let o=0;for(;o{const t=[];let i=0,s=0;for(;i0?this._sourceCode.substring(0,a):"";const g=h+1{const a=r[0];return wp(e.charAt(a-1))||wp(e.charAt(a+n))?t[s]:o}))}return e}}Bp._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;const kp=/(flat\s)?\s*varying\s*.*/;class Vp{constructor(){this.shaderLanguage=di.GLSL}initializeShaders(e){this._nativeProcessingContext=e,this._nativeProcessingContext&&(this._nativeProcessingContext.remappedAttributeNames={},this._nativeProcessingContext.injectInVertexMain="")}attributeProcessor(e){if(!this._nativeProcessingContext)return e.replace("attribute","in");const t=/\s*(?:attribute|in)\s+(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==t){const i=t[1],s=t[2],r=this._nativeProcessingContext.vertexBufferKindToNumberOfComponents[s];if(void 0!==r){const n=r<0?-1===r?"int":"ivec"+-r:1===r?"uint":"uvec"+r,o=`_int_${s}_`;e=e.replace(t[0],`in ${n} ${o}; ${i} ${s};`),this._nativeProcessingContext.injectInVertexMain+=`${s} = ${i}(${o});\n`,this._nativeProcessingContext.remappedAttributeNames[s]=o}else e=e.replace(t[0],`in ${i} ${s};`)}return e}varyingCheck(e,t){return kp.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(s||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(this._nativeProcessingContext?.injectInVertexMain&&(e=Lp(e,"void main",this._nativeProcessingContext.injectInVertexMain)),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}class Up{get isReady(){if(this.compilationError){const e=this.compilationError.message;throw new Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}constructor(e,t,i){this.isCompiled=!1,this.vertexBufferKindToType={},this._valueCache={},this._engine=e,this.isAsync=t,this.shaderProcessingContext=i}_fillEffectInformation(e,t,i,s,r,n,o,a){const l=this._engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this._engine.getUniforms(this,i).forEach(((e,t)=>{s[i[t]]=e})),this._uniforms=s,h=0;h{n[e]=t})),a.push(...l.getAttributes(this,o))}setEngine(e){this._engine=e}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this._engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this._engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this._engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this._engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}}class Gp extends Bl{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,s){super(e,t,i,s),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=s}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class zp{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}}function Wp(e,t){switch(e){case 15:return _native.Engine.TEXTURE_FORMAT_D16;case 16:return _native.Engine.TEXTURE_FORMAT_D24;case 13:return _native.Engine.TEXTURE_FORMAT_D24S8;case 14:return _native.Engine.TEXTURE_FORMAT_D32F;case 36492:return _native.Engine.TEXTURE_FORMAT_BC7;case 36494:return _native.Engine.TEXTURE_FORMAT_BC6H;case 33779:return _native.Engine.TEXTURE_FORMAT_BC3;case 33778:return _native.Engine.TEXTURE_FORMAT_BC2;case 33777:case 33776:return _native.Engine.TEXTURE_FORMAT_BC1;case 37808:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case 36196:return _native.Engine.TEXTURE_FORMAT_ETC1;case 37492:return _native.Engine.TEXTURE_FORMAT_ETC2;case 37496:return _native.Engine.TEXTURE_FORMAT_ETC2A;case 4:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGB8;case 3:return _native.Engine.TEXTURE_FORMAT_RGB8S;case 6:return _native.Engine.TEXTURE_FORMAT_RGB8I;case 7:return _native.Engine.TEXTURE_FORMAT_RGB8U}break;case 5:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGBA8;case 1:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case 2:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case 3:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case 4:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case 5:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case 6:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case 7:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break;case 6:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_R8;case 1:return _native.Engine.TEXTURE_FORMAT_R32F;case 2:return _native.Engine.TEXTURE_FORMAT_R16F;case 3:return _native.Engine.TEXTURE_FORMAT_R8S;case 4:return _native.Engine.TEXTURE_FORMAT_R16S;case 5:return _native.Engine.TEXTURE_FORMAT_R16U;case 6:return _native.Engine.TEXTURE_FORMAT_R32I;case 7:return _native.Engine.TEXTURE_FORMAT_R32U}break;case 7:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RG8;case 1:return _native.Engine.TEXTURE_FORMAT_RG32F;case 2:return _native.Engine.TEXTURE_FORMAT_RG16F;case 3:return _native.Engine.TEXTURE_FORMAT_RG8S;case 4:return _native.Engine.TEXTURE_FORMAT_RG16S;case 5:return _native.Engine.TEXTURE_FORMAT_RG16U;case 6:return _native.Engine.TEXTURE_FORMAT_RG32I;case 7:return _native.Engine.TEXTURE_FORMAT_RG32U}break;case 12:if(0===t)return _native.Engine.TEXTURE_FORMAT_BGRA8}throw new jt(`Unsupported texture format or type: format ${e}, type ${t}.`,Qt.UnsupportedTextureError)}function Hp(e){switch(e){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw new Error(`Unsupported sampling mode: ${e}.`)}}function Xp(e){switch(e){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw new Error("Unexpected wrap mode: "+e+".")}}function Yp(e){switch(e){case er.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case er.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case er.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case er.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case er.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${e}.`)}}const Qp={[er.PositionKind]:!0,[er.NormalKind]:!0,[er.TangentKind]:!0,[er.UVKind]:!0,[er.UV2Kind]:!0,[er.UV3Kind]:!0,[er.UV4Kind]:!0,[er.UV5Kind]:!0,[er.UV6Kind]:!0,[er.ColorKind]:!0,[er.ColorInstanceKind]:!0,[er.MatricesIndicesKind]:!0,[er.MatricesWeightsKind]:!0,[er.MatricesIndicesExtraKind]:!0,[er.MatricesWeightsExtraKind]:!0};function jp(e){switch(e){case er.BYTE:case er.SHORT:case er.INT:case er.FLOAT:return!0;case er.UNSIGNED_BYTE:case er.UNSIGNED_SHORT:case er.UNSIGNED_INT:return!1;default:throw new Error(`Invalid type '${e}'`)}}function Kp(e,t){const i=t.getEngine(),s=t._pipelineContext;if(!s?.vertexBufferKindToType)return;let r=null;for(const n in e){const o=e[n];if(!o||!Qp[n])continue;const a=o.normalized?er.FLOAT:o.type,l=s.vertexBufferKindToType[n];(a!==er.FLOAT&&void 0===l||void 0!==l&&l!==a)&&(r||(r=i._getShaderProcessingContext(t.shaderLanguage)),s.vertexBufferKindToType[n]=a,a!==er.FLOAT&&(r.vertexBufferKindToNumberOfComponents[n]=er.DeduceStride(n),jp(a)&&(r.vertexBufferKindToNumberOfComponents[n]*=-1)))}if(r){const e=i._caps.parallelShaderCompile;i._caps.parallelShaderCompile=void 0,t._processShaderCode(null,i._features._checkNonFloatVertexBuffersDontRecreatePipelineContext,r),i._caps.parallelShaderCompile=e}}class $p{constructor(){this.vertexBufferKindToNumberOfComponents={},this.remappedAttributeNames={},this.injectInVertexMain=""}}const qp=new K;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{e=t,e&&qp.notifyObservers(e)}})}function Zp(){return new Promise((e=>{"undefined"==typeof _native?qp.addOnce((t=>e(t))):e(_native)}))}async function Jp(e,t){(await Zp())[e]=t}class ef extends Qs{}class tf{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=rf._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw new Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw new Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}}const sf=[];class rf extends oo{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine({version:oo.Version,nonFloatVertexBuffers:!0}),this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new tf(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==rf.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${rf.PROTOCOL_VERSION} (JS)`);this._engine.setDeviceLostCallback&&this._engine.setDeviceLostCallback((()=>{this.onContextLostObservable.notifyObservers(this),this._contextWasLost=!0,this._restoreEngineAfterContextLost()})),this._webGLVersion=2,this.disableUniformBuffers=!0,this._shaderPlatformName="NATIVE",this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!0,textureFloatLinearFiltering:!0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1,parallelShaderCompile:{COMPLETION_STATUS_KHR:0}},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1},Ds.Log("Babylon Native (v"+oo.Version+") launched"),Ds.LoadScript=function(e,t,i,s){Ds.LoadFile(e,(e=>{Function(e).apply(null),t&&t()}),void 0,void 0,!1,((e,t)=>{i&&i("LoadScript Error",t)}))},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(){const t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,(function(i,s){return Array.isArray(s)?i.push.apply(i,e.call(s,t-1)):i.push(s),i}),[]):Array.prototype.slice.call(this)},writable:!0});const t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();const i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new Vp,this.onNewSceneAddedObservable.add((e=>{const t=e.render;e.render=(...i)=>{this._commandBufferEncoder.beginCommandScope(),t.apply(e,i),this._commandBufferEncoder.endCommandScope()}}))}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new fp}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_restoreEngineAfterContextLost(){this._clearEmptyResources();const e=this._depthCullingState.depthTest,t=this._depthCullingState.depthFunc,i=this._depthCullingState.depthMask,s=this._stencilState.stencilTest;this._rebuildGraphicsResources(),this._depthCullingState.depthTest=e,this._depthCullingState.depthFunc=t,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=s,this._flagContextRestored()}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,s=!1){if(this.useReverseDepthBuffer)throw new Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(s?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){const s=this._normalizeIndexData(e),r=new ef;return r.references=1,r.is32Bits=4===s.BYTES_PER_ELEMENT,s.byteLength&&(r.nativeIndexBuffer=this._engine.createIndexBuffer(s.buffer,s.byteOffset,s.byteLength,r.is32Bits,t??!1)),r}createVertexBuffer(e,t,i){const s=ArrayBuffer.isView(e)?e:new Float32Array(e),r=new ef;return r.references=1,s.byteLength&&(r.nativeVertexBuffer=this._engine.createVertexBuffer(s.buffer,s.byteOffset,s.byteLength,t??!1)),r}_recordVertexArrayObject(e,t,i,s,r){Kp(t,s),i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const n=s.getAttributesNames();for(let i=0;i=0){const s=n[i];let a=null;if(r&&(a=r[s]),a||(a=t[s]),a){const t=a.effectiveBuffer;t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,o,a.effectiveByteOffset,a.effectiveByteStride,a.getSize(),Yp(a.type),a.normalized,a.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,s){const r=this._engine.createVertexArray();return this._recordVertexArrayObject(r,e,t,i,s),r}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){const i=e,s=i.shaderProcessingContext;sf.length=0;for(let e=0;e{e(),t()}}else i.onCompiled=t;else t()}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,s){const r=e;this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=new Bp(t);n.processCode(),t=n.code;const o=new Bp(i);o.processCode(),i=o.code,t=qs._ConcatenateShader(t,s),i=qs._ConcatenateShader(i,s);const a=()=>{r.isCompiled=!0,r.onCompiled?.(),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(e.isAsync)r.program=this._engine.createProgramAsync(t,i,a,(e=>{r.compilationError=e}));else try{r.program=this._engine.createProgram(t,i),a()}catch(e){const t=e?.message;throw new Error("SHADER ERROR"+("string"==typeof t?"\n"+t:""))}return r.program}inlineShaderCode(e){const t=new Bp(e);return t.debug=!1,t.processCode(),t.code}_setProgram(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)}_deletePipelineContext(e){const t=e;t&&t.program&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(t.program),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){const i=e;return this._engine.getUniforms(i.program,t)}bindUniformBlock(e,t,i){throw new Error("Not Implemented")}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t{}}}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()}setDepthWrite(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}setColorWrite(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}getColorWrite(){return this._colorWrite}applyStencil(){this._setStencil(this._stencilMask,function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw new Error(`Unsupported stencil OpFail mode: ${e}.`)}}(this._stencilOpStencilFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw new Error(`Unsupported stencil depthFail mode: ${e}.`)}}(this._stencilOpDepthFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw new Error(`Unsupported stencil opPass mode: ${e}.`)}}(this._stencilOpStencilDepthPass),function(e){switch(e){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw new Error(`Unsupported stencil func mode: ${e}.`)}}(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,s,r,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,s){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=function(e){switch(e){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw new Error(`Unsupported alpha mode: ${e}.`)}}(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(0===e),this._alphaMode=e}setInt(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setArray(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))}setArray2(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))}setArray3(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))}setArray4(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))}setMatrices(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix3x3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix2x2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat2(e,t,i){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat3(e,t,i,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,s,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,s=!1,r){if(void 0===s&&(s=!1),e&&e._hardwareTexture){const i=t.getCanvasTexture(),s=e._hardwareTexture.underlyingResource;this._engine.copyTexture(s,i),e.isReady=!0}}createDynamicTexture(e,t,i,s){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,s)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const s=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(s,t,i)}}createRawTexture(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new ss(this,is.Raw);if(u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u.baseWidth=t,u.baseHeight=i,u.width=u.baseWidth,u.height=u.baseHeight,u._compression=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!r),this.updateRawTexture(u,e,s,n,a,l,u._useSRGBBuffer),u._hardwareTexture){const e=u._hardwareTexture.underlyingResource,t=Hp(o);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(u),u}createRawTexture2DArray(e,t,i,s,r,n,o,a,l=null,h=0){const c=new ss(this,is.Raw2DArray);if(c.baseWidth=t,c.baseHeight=i,c.baseDepth=s,c.width=t,c.height=i,c.depth=s,c.format=r,c.type=h,c.generateMipMaps=n,c.samplingMode=a,c.is2DArray=!0,c._hardwareTexture){const l=c._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,s,Wp(r,h),n,o);const u=Hp(a);this._setTextureSampling(l,u)}return c.isReady=!0,this._internalTexturesCache.push(c),c}updateRawTexture(e,t,i,s,r=null,n=0,o=!1){if(e){if(t&&e._hardwareTexture){const s=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(s,t,e.width,e.height,Wp(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,_,p=!1){const f="data:"===(e=e||"").substr(0,5),m=f&&-1!==e.indexOf(";base64,"),g=l||new ss(this,is.Url),v=e;!this._transformTextureUrl||m||l||a||(e=this._transformTextureUrl(e));const x=e.lastIndexOf("."),b=c||(x>-1?e.substring(x).toLowerCase():"");let T=null;for(const e of ns._TextureLoaders)if(e.canLoad(b)){T=e;break}s&&s.addPendingData(g),g.url=e,g.generateMipMaps=!t,g.samplingMode=r,g.invertY=i,g._useSRGBBuffer=this._getUseSRGBBuffer(p,t),this.doNotHandleContextLost||(g._buffer=a);let y=null;n&&!l&&(y=g.onLoadedObservable.add(n)),l||this._internalTexturesCache.push(g);const S=(i,l)=>{s&&s.removePendingData(g),e===v?(y&&g.onLoadedObservable.remove(y),re.UseFallbackTexture&&this.createTexture(re.FallbackTexture,t,g.invertY,s,r,null,o,a,g),o&&o((i||"Unknown error")+(re.UseFallbackTexture?" - Fallback texture was used":""),l)):(Ne.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,g.invertY,s,r,n,o,a,g,h,c,u,d))};if(T)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const n=e=>{if(!g._hardwareTexture)return void(s&&s.removePendingData(g));const n=g._hardwareTexture.underlyingResource;this._engine.loadTexture(n,e,!t,i,g._useSRGBBuffer,(()=>{g.baseWidth=this._engine.getTextureWidth(n),g.baseHeight=this._engine.getTextureHeight(n),g.width=g.baseWidth,g.height=g.baseHeight,g.isReady=!0;const e=Hp(r);this._setTextureSampling(n,e),s&&s.removePendingData(g),g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()}),(()=>{throw new Error("Could not load a native texture.")}))};if(f&&a)if(a instanceof ArrayBuffer)n(new Uint8Array(a));else if(ArrayBuffer.isView(a))n(a);else{if("string"!=typeof a)throw new Error("Unsupported buffer type");n(new Uint8Array(Ds.DecodeBase64(a)))}else m?n(new Uint8Array(Ds.DecodeBase64(e))):this._loadFile(e,(e=>n(new Uint8Array(e))),void 0,void 0,!0,((e,t)=>{S("Unable to load "+(e&&e.responseURL,t))}))}return g}wrapNativeTexture(e,t=!1,i=3){const s=new zp(e,this._engine),r=new ss(this,is.Unknown,!0);return r._hardwareTexture=s,r.baseWidth=this._engine.getTextureWidth(e),r.baseHeight=this._engine.getTextureHeight(e),r.width=r.baseWidth,r.height=r.baseHeight,r.isReady=!0,r.useMipMaps=t,this.updateTextureSamplingMode(i,r),r}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const s=t.generateStencil||!1,r=t.samples||1,n=i,o=new ss(this,is.DepthStencil),a=e.width??e,l=e.height??e,h=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,a,l,s,!0,r);return n._framebufferDepthStencil=h,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){return new Promise(((t,i)=>{const s=this.createCanvasImage();s.onload=()=>{try{const e=this._engine.createImageBitmap(s);t(e)}catch(e){i(`Error loading image ${s.src} with exception: ${e}`)}},s.onerror=e=>{i(`Error loading image ${s.src} with exception: ${e}`)},s.src=e}))}createImageBitmap(e,t){return new Promise(((t,i)=>{if(Array.isArray(e)){const i=e;if(i.length){const e=this._engine.createImageBitmap(i[0]);if(e)return void t(e)}}i("Unsupported data for createImageBitmap.")}))}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,_=!1){const p=u||new ss(this,is.Cube);p.isCube=!0,p.url=e,p.generateMipMaps=!s,p._lodGenerationScale=h,p._lodGenerationOffset=c,p._useSRGBBuffer=this._getUseSRGBBuffer(_,!!s),this._doNotHandleContextLost||(p._extension=a,p._files=i);const f=e.lastIndexOf(".");if(".env"===(a||(f>-1?e.substring(f).toLowerCase():""))){const t=e=>{const t=bp(e);p.width=t.width,p.height=t.width,Ip(p,t);const i=t.specular;if(!i)throw new Error("Nothing else parsed so far");p._lodGenerationScale=i.lodGenerationScale;const s=Cp(e,t);p.format=5,p.type=0,p.generateMipMaps=!0,p.getEngine().updateTextureSamplingMode(Pa.TRILINEAR_SAMPLINGMODE,p),p._isRGBD=!0,p.invertY=!0,this._engine.loadCubeTextureWithMips(p._hardwareTexture.underlyingResource,s,!1,p._useSRGBBuffer,(()=>{p.isReady=!0,r&&r()}),(()=>{throw new Error("Could not load a native cube texture.")}))};if(i&&6===i.length)throw new Error("Multi-file loading not allowed on env files.");{const i=(e,t)=>{n&&e&&n(e.status+" "+e.statusText,t)};this._loadFile(e,(e=>{t(new Uint8Array(e,0,e.byteLength))}),void 0,void 0,!0,i)}}else{if(!i||6!==i.length)throw new Error("Cannot load cubemap because 6 files were not defined");const e=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(e.map((e=>this._loadFileAsync(e,void 0,!0).then((e=>new Uint8Array(e,0,e.byteLength)))))).then((e=>new Promise(((t,i)=>{this._engine.loadCubeTexture(p._hardwareTexture.underlyingResource,e,!s,!0,p._useSRGBBuffer,t,i)})))).then((()=>{p.isReady=!0,r&&r()}),(e=>{n&&n(`Failed to load cubemap: ${e.message}`,e)}))}return this._internalTexturesCache.push(p),p}_createHardwareTexture(){return new zp(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const s=new Gp(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}_createInternalTexture(e,t,i=!0,s=is.Unknown){let r,n=!1,o=0,a=3,l=5,h=!1,c=1;void 0!==t&&"object"==typeof t?(n=!!t.generateMipMaps,o=void 0===t.type?0:t.type,a=void 0===t.samplingMode?3:t.samplingMode,l=void 0===t.format?5:t.format,h=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,c=t.samples??1,r=t.label):n=!!t,h=this._getUseSRGBBuffer(h,!n),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(a=1),1!==o||this._caps.textureFloat||(o=0,Ne.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=new ss(this,s),d=e.width??e,_=e.height??e,p=e.layers||0;if(0!==p)throw new Error("Texture layers are not supported in Babylon Native");const f=u._hardwareTexture.underlyingResource,m=Wp(l,o);return this._engine.initializeTexture(f,d,_,n,m,!0,h,c),this._setTextureSampling(f,Hp(a)),u._useSRGBBuffer=h,u.baseWidth=d,u.baseHeight=_,u.width=d,u.height=_,u.depth=p,u.isReady=!0,u.samples=c,u.generateMipMaps=n,u.samplingMode=a,u.type=o,u.format=l,u.label=r,this._internalTexturesCache.push(u),u}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e);let s,r=!0,n=!1,o=!1,a=1;void 0!==t&&"object"==typeof t&&(r=t.generateDepthBuffer??!0,n=!!t.generateStencilBuffer,o=!!t.noColorAttachment,s=t.colorAttachment,a=t.samples??1);const l=s||(o?null:this._createInternalTexture(e,t,!0,is.RenderTarget)),h=e.width??e,c=e.height??e,u=this._engine.createFrameBuffer(l?l._hardwareTexture.underlyingResource:null,h,c,n,r,a);return i._framebuffer=u,i._generateDepthBuffer=r,i._generateStencilBuffer=n,i._samples=a,i.setTextures(l),i}updateRenderTargetTextureSampleCount(e,t){return Ne.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=Hp(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,s,r){const n=e;if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||s)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");n._framebufferDepthStencil?this._bindUnboundFramebuffer(n._framebufferDepthStencil):this._bindUnboundFramebuffer(n._framebuffer)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e,!0)}updateDynamicIndexBuffer(e,t,i=0){const s=e,r=this._normalizeIndexData(t);s.is32Bits=4===r.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(s.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i=0,s){const r=e,n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,o=new Uint8Array(n.buffer,n.byteOffset,s??n.byteLength);this._engine.updateDynamicVertexBuffer(r.nativeVertexBuffer,o.buffer,o.byteOffset,o.byteLength,i)}_setTexture(e,t,i=!1,s=!1){const r=this._boundUniforms[e];if(!r)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null,this._unsetNativeTexture(r)),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;return n=s?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!(!n||!n._hardwareTexture||(this._setTextureWrapMode(n._hardwareTexture.underlyingResource,Xp(t.wrapU),Xp(t.wrapV),Xp(t.wrapR)),this._updateAnisotropicLevel(t),this._setNativeTexture(r,n._hardwareTexture.underlyingResource),0))}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,s){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.finishEncodingCommand()}_setNativeTexture(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_unsetNativeTexture(e){_native.Engine.COMMAND_UNSETTEXTURE&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNSETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_updateAnisotropicLevel(e){const t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){const i=this._boundUniforms[e];if(i)if(t&&t._hardwareTexture){const e=t._hardwareTexture.underlyingResource;this._setNativeTexture(i,e)}else this._unsetNativeTexture(i)}unbindAllTextures(){_native.Engine.COMMAND_DISCARDALLTEXTURES&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DISCARDALLTEXTURES),this._commandBufferEncoder.finishEncodingCommand())}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");const i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");return new _native.Image}updateTextureData(e,t,i,s,r,n,o=0,a=0,l=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,s=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}flushFramebuffer(){}_readTexturePixels(e,t,i,s,r,n,o,a,l,h){if(void 0!==s&&-1!==s)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${s}.`);return this._engine.readTexture(e._hardwareTexture?.underlyingResource,r??0,l??0,h??0,t,i,n?.buffer??null,n?.byteOffset??0,n?.byteLength??0).then((e=>(n||(n=new Uint8Array(e)),n)))}}rf.PROTOCOL_VERSION=8,rf._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new nf:new fp};class nf extends fp{constructor(){super()}writeUint32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32),super.writeUint32(e)}writeInt32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32),super.writeInt32(e)}writeFloat32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32),super.writeFloat32(e)}writeUint32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),super.writeUint32Array(e)}writeInt32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY),super.writeInt32Array(e)}writeFloat32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),super.writeFloat32Array(e)}writeNativeData(e){super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA),super.writeNativeData(e)}writeBoolean(e){super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN),super.writeBoolean(e)}}var of,af,lf,hf,cf,uf,df,_f,pf,ff,mf,gf,vf,xf,bf,Tf,yf,Sf,Cf,Ef,Af,Pf,If,Rf,Mf,Of,Df,wf,Nf,Ff,Lf,Bf,kf,Vf,Uf,Gf,zf,Wf,Hf,Xf;!function(e){e.LowPower="low-power",e.HighPerformance="high-performance"}(of||(of={})),function(e){e.DepthClipControl="depth-clip-control",e.Depth32FloatStencil8="depth32float-stencil8",e.TextureCompressionBC="texture-compression-bc",e.TextureCompressionETC2="texture-compression-etc2",e.TextureCompressionASTC="texture-compression-astc",e.TimestampQuery="timestamp-query",e.IndirectFirstInstance="indirect-first-instance",e.ShaderF16="shader-f16",e.RG11B10UFloatRenderable="rg11b10ufloat-renderable",e.BGRA8UnormStorage="bgra8unorm-storage",e.Float32Filterable="float32-filterable"}(af||(af={})),function(e){e.Unmapped="unmapped",e.Pending="pending",e.Mapped="mapped"}(lf||(lf={})),function(e){e[e.MapRead=1]="MapRead",e[e.MapWrite=2]="MapWrite",e[e.CopySrc=4]="CopySrc",e[e.CopyDst=8]="CopyDst",e[e.Index=16]="Index",e[e.Vertex=32]="Vertex",e[e.Uniform=64]="Uniform",e[e.Storage=128]="Storage",e[e.Indirect=256]="Indirect",e[e.QueryResolve=512]="QueryResolve"}(hf||(hf={})),function(e){e[e.Read=1]="Read",e[e.Write=2]="Write"}(cf||(cf={})),function(e){e.E1d="1d",e.E2d="2d",e.E3d="3d"}(uf||(uf={})),function(e){e[e.CopySrc=1]="CopySrc",e[e.CopyDst=2]="CopyDst",e[e.TextureBinding=4]="TextureBinding",e[e.StorageBinding=8]="StorageBinding",e[e.RenderAttachment=16]="RenderAttachment"}(df||(df={})),function(e){e.E1d="1d",e.E2d="2d",e.E2dArray="2d-array",e.Cube="cube",e.CubeArray="cube-array",e.E3d="3d"}(_f||(_f={})),function(e){e.All="all",e.StencilOnly="stencil-only",e.DepthOnly="depth-only"}(pf||(pf={})),function(e){e.R8Unorm="r8unorm",e.R8Snorm="r8snorm",e.R8Uint="r8uint",e.R8Sint="r8sint",e.R16Uint="r16uint",e.R16Sint="r16sint",e.R16Float="r16float",e.RG8Unorm="rg8unorm",e.RG8Snorm="rg8snorm",e.RG8Uint="rg8uint",e.RG8Sint="rg8sint",e.R32Uint="r32uint",e.R32Sint="r32sint",e.R32Float="r32float",e.RG16Uint="rg16uint",e.RG16Sint="rg16sint",e.RG16Float="rg16float",e.RGBA8Unorm="rgba8unorm",e.RGBA8UnormSRGB="rgba8unorm-srgb",e.RGBA8Snorm="rgba8snorm",e.RGBA8Uint="rgba8uint",e.RGBA8Sint="rgba8sint",e.BGRA8Unorm="bgra8unorm",e.BGRA8UnormSRGB="bgra8unorm-srgb",e.RGB9E5UFloat="rgb9e5ufloat",e.RGB10A2UINT="rgb10a2uint",e.RGB10A2Unorm="rgb10a2unorm",e.RG11B10UFloat="rg11b10ufloat",e.RG32Uint="rg32uint",e.RG32Sint="rg32sint",e.RG32Float="rg32float",e.RGBA16Uint="rgba16uint",e.RGBA16Sint="rgba16sint",e.RGBA16Float="rgba16float",e.RGBA32Uint="rgba32uint",e.RGBA32Sint="rgba32sint",e.RGBA32Float="rgba32float",e.Stencil8="stencil8",e.Depth16Unorm="depth16unorm",e.Depth24Plus="depth24plus",e.Depth24PlusStencil8="depth24plus-stencil8",e.Depth32Float="depth32float",e.BC1RGBAUnorm="bc1-rgba-unorm",e.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",e.BC2RGBAUnorm="bc2-rgba-unorm",e.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",e.BC3RGBAUnorm="bc3-rgba-unorm",e.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",e.BC4RUnorm="bc4-r-unorm",e.BC4RSnorm="bc4-r-snorm",e.BC5RGUnorm="bc5-rg-unorm",e.BC5RGSnorm="bc5-rg-snorm",e.BC6HRGBUFloat="bc6h-rgb-ufloat",e.BC6HRGBFloat="bc6h-rgb-float",e.BC7RGBAUnorm="bc7-rgba-unorm",e.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",e.ETC2RGB8Unorm="etc2-rgb8unorm",e.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",e.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",e.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",e.ETC2RGBA8Unorm="etc2-rgba8unorm",e.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",e.EACR11Unorm="eac-r11unorm",e.EACR11Snorm="eac-r11snorm",e.EACRG11Unorm="eac-rg11unorm",e.EACRG11Snorm="eac-rg11snorm",e.ASTC4x4Unorm="astc-4x4-unorm",e.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",e.ASTC5x4Unorm="astc-5x4-unorm",e.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",e.ASTC5x5Unorm="astc-5x5-unorm",e.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",e.ASTC6x5Unorm="astc-6x5-unorm",e.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",e.ASTC6x6Unorm="astc-6x6-unorm",e.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",e.ASTC8x5Unorm="astc-8x5-unorm",e.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",e.ASTC8x6Unorm="astc-8x6-unorm",e.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",e.ASTC8x8Unorm="astc-8x8-unorm",e.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",e.ASTC10x5Unorm="astc-10x5-unorm",e.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",e.ASTC10x6Unorm="astc-10x6-unorm",e.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",e.ASTC10x8Unorm="astc-10x8-unorm",e.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",e.ASTC10x10Unorm="astc-10x10-unorm",e.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",e.ASTC12x10Unorm="astc-12x10-unorm",e.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",e.ASTC12x12Unorm="astc-12x12-unorm",e.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",e.Depth32FloatStencil8="depth32float-stencil8"}(ff||(ff={})),function(e){e.ClampToEdge="clamp-to-edge",e.Repeat="repeat",e.MirrorRepeat="mirror-repeat"}(mf||(mf={})),function(e){e.Nearest="nearest",e.Linear="linear"}(gf||(gf={})),function(e){e.Nearest="nearest",e.Linear="linear"}(vf||(vf={})),function(e){e.Never="never",e.Less="less",e.Equal="equal",e.LessEqual="less-equal",e.Greater="greater",e.NotEqual="not-equal",e.GreaterEqual="greater-equal",e.Always="always"}(xf||(xf={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Compute=4]="Compute"}(bf||(bf={})),function(e){e.Uniform="uniform",e.Storage="storage",e.ReadOnlyStorage="read-only-storage"}(Tf||(Tf={})),function(e){e.Filtering="filtering",e.NonFiltering="non-filtering",e.Comparison="comparison"}(yf||(yf={})),function(e){e.Float="float",e.UnfilterableFloat="unfilterable-float",e.Depth="depth",e.Sint="sint",e.Uint="uint"}(Sf||(Sf={})),function(e){e.WriteOnly="write-only",e.ReadOnly="read-only",e.ReadWrite="read-write"}(Cf||(Cf={})),function(e){e.Error="error",e.Warning="warning",e.Info="info"}(Ef||(Ef={})),function(e){e.Validation="validation",e.Internal="internal"}(Af||(Af={})),function(e){e.Auto="auto"}(Pf||(Pf={})),function(e){e.PointList="point-list",e.LineList="line-list",e.LineStrip="line-strip",e.TriangleList="triangle-list",e.TriangleStrip="triangle-strip"}(If||(If={})),function(e){e.CCW="ccw",e.CW="cw"}(Rf||(Rf={})),function(e){e.None="none",e.Front="front",e.Back="back"}(Mf||(Mf={})),function(e){e[e.Red=1]="Red",e[e.Green=2]="Green",e[e.Blue=4]="Blue",e[e.Alpha=8]="Alpha",e[e.All=15]="All"}(Of||(Of={})),function(e){e.Zero="zero",e.One="one",e.Src="src",e.OneMinusSrc="one-minus-src",e.SrcAlpha="src-alpha",e.OneMinusSrcAlpha="one-minus-src-alpha",e.Dst="dst",e.OneMinusDst="one-minus-dst",e.DstAlpha="dst-alpha",e.OneMinusDstAlpha="one-minus-dst-alpha",e.SrcAlphaSaturated="src-alpha-saturated",e.Constant="constant",e.OneMinusConstant="one-minus-constant"}(Df||(Df={})),function(e){e.Add="add",e.Subtract="subtract",e.ReverseSubtract="reverse-subtract",e.Min="min",e.Max="max"}(wf||(wf={})),function(e){e.Keep="keep",e.Zero="zero",e.Replace="replace",e.Invert="invert",e.IncrementClamp="increment-clamp",e.DecrementClamp="decrement-clamp",e.IncrementWrap="increment-wrap",e.DecrementWrap="decrement-wrap"}(Nf||(Nf={})),function(e){e.Uint16="uint16",e.Uint32="uint32"}(Ff||(Ff={})),function(e){e.Uint8x2="uint8x2",e.Uint8x4="uint8x4",e.Sint8x2="sint8x2",e.Sint8x4="sint8x4",e.Unorm8x2="unorm8x2",e.Unorm8x4="unorm8x4",e.Snorm8x2="snorm8x2",e.Snorm8x4="snorm8x4",e.Uint16x2="uint16x2",e.Uint16x4="uint16x4",e.Sint16x2="sint16x2",e.Sint16x4="sint16x4",e.Unorm16x2="unorm16x2",e.Unorm16x4="unorm16x4",e.Snorm16x2="snorm16x2",e.Snorm16x4="snorm16x4",e.Float16x2="float16x2",e.Float16x4="float16x4",e.Float32="float32",e.Float32x2="float32x2",e.Float32x3="float32x3",e.Float32x4="float32x4",e.Uint32="uint32",e.Uint32x2="uint32x2",e.Uint32x3="uint32x3",e.Uint32x4="uint32x4",e.Sint32="sint32",e.Sint32x2="sint32x2",e.Sint32x3="sint32x3",e.Sint32x4="sint32x4",e.UNORM10x10x10x2="unorm10-10-10-2"}(Lf||(Lf={})),function(e){e.Vertex="vertex",e.Instance="instance"}(Bf||(Bf={})),function(e){e.Beginning="beginning",e.End="end"}(kf||(kf={})),function(e){e.Beginning="beginning",e.End="end"}(Vf||(Vf={})),function(e){e.Load="load",e.Clear="clear"}(Uf||(Uf={})),function(e){e.Store="store",e.Discard="discard"}(Gf||(Gf={})),function(e){e.Occlusion="occlusion",e.Timestamp="timestamp"}(zf||(zf={})),function(e){e.Opaque="opaque",e.Premultiplied="premultiplied"}(Wf||(Wf={})),function(e){e.Unknown="unknown",e.Destroyed="destroyed"}(Hf||(Hf={})),function(e){e.Validation="validation",e.OutOfMemory="out-of-memory",e.Internal="internal"}(Xf||(Xf={}));class Yf{constructor(){this.shaderLanguage=di.GLSL}_addUniformToLeftOverUBO(e,t,i){let s=0;[e,t,s]=this._getArraySize(e,t,i);for(let t=0;t=0&&(u.push(o[c]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=u,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new Zs(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=Yf.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}setEngine(e){this.engine=e}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,s)}setInt4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,s,r)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,s)}setUInt4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,s,r)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,s)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,s,r)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){return this.sources?.vertex}_getFragmentShaderCode(){return this.sources?.fragment}}const jf={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class Kf{static get KnownUBOs(){return Kf._SimplifiedKnownBindings?Kf._SimplifiedKnownUBOs:Kf._KnownUBOs}constructor(e){this.vertexBufferKindToNumberOfComponents={},this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=Kf.KnownUBOs,t=[];for(const i in e){const s=e[i].binding;-1!==s.groupIndex&&(void 0===t[s.groupIndex]?t[s.groupIndex]=s.bindingIndex:t[s.groupIndex]=Math.max(t[s.groupIndex],s.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){const i=this._attributeNextLocation;return this._attributeNextLocation+=(jf[e]??1)*(t||1),i}getVaryingNextLocation(e,t=0){const i=this._varyingNextLocation;return this._varyingNextLocation+=(jf[e]??1)*(t||1),i}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";const t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}Kf._SimplifiedKnownBindings=!0,Kf._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}},Kf._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};class $f extends Yf{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=di.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let s=0;const r=e.indexOf("["),n=e.indexOf("]");if(r>0&&n>0){const t=e.substring(r+1,n);s=+t,isNaN(s)&&(s=+i[t.trim()]),e=e.substr(0,r)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){const i=`// Internals UBO\nuniform ${Yf.InternalsUBOName} {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n`,s=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),s?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),s?e:i+e)}varyingCheck(e,t){return(t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/).test(e)}varyingProcessor(e,t,i){this._preProcessors=i;const s=(t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==s){const r=s[1]??"",n=s[2],o=s[3];let a;t?(a=this._webgpuProcessingContext.availableVaryings[o],this._missingVaryings[a]="",void 0===a&&Ne.Warn(`Invalid fragment shader: The varying named "${o}" is not declared in the vertex shader! This declaration will be ignored.`)):(a=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(o,n,i)[2]),this._webgpuProcessingContext.availableVaryings[o]=a,this._missingVaryings[a]=`layout(location = ${a}) ${r} in ${n} ${o};`),e=e.replace(s[0],void 0===a?"":`layout(location = ${a}) ${r} ${t?"in":"out"} ${n} ${o};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=(this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==i){const s=i[1],r=i[2],n=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(r,s,t)[2]);this._webgpuProcessingContext.availableAttributes[r]=n,this._webgpuProcessingContext.orderedAttributes[n]=r;const o=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[r];if(void 0!==o){const t=o<0?-1===o?"int":"ivec"+-o:1===o?"uint":"uvec"+o,a=`_int_${r}_`;e=e.replace(i[0],`layout(location = ${n}) in ${t} ${a}; ${s} ${r} = ${s}(${a});`)}else e=e.replace(i[0],`layout(location = ${n}) in ${s} ${r};`)}return e}uniformProcessor(e,t,i){this._preProcessors=i;const s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let r=s[1],n=s[2];if(0===r.indexOf("sampler")||1===r.indexOf("sampler")){let s=0;[n,r,s]=this._getArraySize(n,r,i);let o=this._webgpuProcessingContext.availableTextures[n];if(!o){o={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:Sf.Float};for(let e=0;e<(s||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const a=Yf._SamplerTypeByWebGLSamplerType[r]??"sampler",l=!!Yf._IsComparisonSamplerByWebGPUSamplerType[a],h=l?yf.Comparison:yf.Filtering,c=n+"Sampler";let u=this._webgpuProcessingContext.availableSamplers[c];u||(u={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:h});const d="u"===r.charAt(0)?"u":"i"===r.charAt(0)?"i":"";d&&(r=r.substr(1));const _=l?Sf.Depth:"u"===d?Sf.Uint:"i"===d?Sf.Sint:Sf.Float;o.sampleType=_;const p=s>0,f=u.binding.groupIndex,m=u.binding.bindingIndex,g=Yf._SamplerFunctionByWebGLSamplerType[r],v=Yf._TextureTypeByWebGLSamplerType[r],x=Yf._GpuTextureViewDimensionByWebGPUTextureType[v];if(p){const t=[];t.push(`layout(set = ${f}, binding = ${m}) uniform ${d}${a} ${c};`),e="\n";for(let i=0;i0?"\n":""}#define ${n}${i} ${d}${g}(${n}Texture${i}, ${c})`}e=t.join("\n")+e,this._textureArrayProcessing.push(n)}else s=1,e=`layout(set = ${f}, binding = ${m}) uniform ${a} ${c};\n layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${d}${v} ${n}Texture;\n #define ${n} ${d}${g}(${n}Texture, ${c})`;this._webgpuProcessingContext.availableTextures[n]=o,this._webgpuProcessingContext.availableSamplers[c]=u,this._addSamplerBindingDescription(c,u,!t);for(let e=0;e=0,i="\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n ",s=t?"vec4 glFragCoord_;\n":"",r=-1!==e.search(/layout *\(location *= *0\) *out/g);if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){const t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(n||r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",s),t&&(e=Lp(e,"void main",i))}else if(e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex"),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;if(!i){const t=e.lastIndexOf("}");e=e.substring(0,t),e+="gl_Position.y *= yFactor_;\n",e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let s=i.exec(e);for(;null!==s;){const r=s[1];let n=+r;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[r.trim()]),e=e.replace(s[0],t+n),s=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} {\n `;for(const e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}];\n`:i+=` ${e.type} ${e.name};\n`;return i+="};\n\n",i}finalizeShaders(e,t){for(let i=0;i0&&(t=i+"\n"+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}Bi.IncludesShadersStoreWGSL.bonesDeclaration="#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4;attribute matricesWeights : vec4;\n#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d;uniform boneTextureWidth : f32;\n#else\nuniform mBones : array;\n#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array;\n#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\n{let offset=i32(index) *4; \nlet m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);}\n#endif\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.bonesVertex="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\n#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\n#endif \n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4\n{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);}\n#endif\n";Bi.IncludesShadersStoreWGSL.bakedVertexAnimation="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\n#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\n#endif\nlet totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;}\n#endif\n";Bi.IncludesShadersStoreWGSL.clipPlaneFragment="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fragmentInputs.fClipDistance>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\n{discard;}\n#endif\n";Bi.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration="#ifdef CLIPPLANE\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nvarying fClipDistance6: f32;\n#endif\n";Bi.IncludesShadersStoreWGSL.clipPlaneVertex="#ifdef CLIPPLANE\nvertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nvertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nvertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nvertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nvertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nvertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);\n#endif\n";Bi.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration="#ifdef CLIPPLANE\nuniform vClipPlane: vec4;varying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4;varying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4;varying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4;varying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4;varying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4;varying fClipDistance6: f32;\n#endif\n";Bi.IncludesShadersStoreWGSL.instancesDeclaration="#ifdef INSTANCES\nattribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4;\n#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4;\n#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform previousWorld : mat4x4;\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.instancesVertex="#ifdef INSTANCES\nvar finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\n#if !defined(WORLD_UBO)\nfinalWorld=uniforms.world*finalWorld;\n#else\nfinalWorld=mesh.world*finalWorld;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nvar finalWorld=uniforms.world;\n#else\nvar finalWorld=mesh.world;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=previousWorld;\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.helperFunctions="const PI: f32=3.1415926535897932384626433832795;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const HALF_MIN: f32=5.96046448e-08; \nconst LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3=vec3 (0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\nfn transposeMat3(inMatrix: mat3x3f)->mat3x3f {let i0: vec3=inMatrix[0];let i1: vec3=inMatrix[1];let i2: vec3=inMatrix[2];let outMatrix:mat3x3f=mat3x3f(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nfn inverseMat3(inMatrix: mat3x3f)->mat3x3f {let a00: f32=inMatrix[0][0];let a01: f32=inMatrix[0][1];let a02: f32=inMatrix[0][2];let a10: f32=inMatrix[1][0];let a11: f32=inMatrix[1][1];let a12: f32=inMatrix[1][2];let a20: f32=inMatrix[2][0];let a21: f32=inMatrix[2][1];let a22: f32=inMatrix[2][2];let b01: f32=a22*a11-a12*a21;let b11: f32=-a22*a10+a12*a20;let b21: f32=a21*a10-a11*a20;let det: f32=a00*b01+a01*b11+a02*b21;return mat3x3f(b01/det,(-a22*a01+a02*a21)/det,(a12*a01-a02*a11)/det,\nb11/det,(a22*a00-a02*a20)/det,(-a12*a00+a02*a10)/det,\nb21/det,(-a21*a00+a01*a20)/det,(a11*a00-a01*a10)/det);}\n#if USE_EXACT_SRGB_CONVERSIONS\nfn toLinearSpaceExact(color: vec3)->vec3\n{let nearZeroSection: vec3=0.0773993808*color;let remainingSection: vec3=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));}\nfn toGammaSpaceExact(color: vec3)->vec3\n{let nearZeroSection: vec3=12.92*color;let remainingSection: vec3=1.055*pow(color,vec3(0.41666))-vec3(0.055);return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));}\n#endif\nfn toLinearSpace(color: vec4)->vec4\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfn toLinearSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nfn toGammaSpace(color: vec4)->vec4\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfn toGammaSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nfn square(value: vec3)->vec3\n{return value*value;}\nfn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;}\nfn getLuminance(color: vec3)->f32\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfn getRand(seed: vec2)->f32 {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfn dither(seed: vec2,varianceAmount: f32)->f32 {let rand: f32=getRand(seed);let normVariance: f32=varianceAmount/255.0;let dither: f32=mix(-normVariance,normVariance,rand);return dither;}\nconst rgbdMaxRange: f32=255.0;fn toRGBD(color: vec3)->vec4 {let maxRGB: f32=max(max(color.r,max(color.g,color.b)),Epsilon);var D: f32 =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);var rgb: vec3 =color.rgb*D;rgb=toGammaSpaceVec3(rgb);return vec4(clamp(rgb,vec3(0.,0.,0.),vec3(1.,1.,1.)),D); }\nfn fromRGBD(rgbd: vec4)->vec3 {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;}\nfn parallaxCorrectNormal(vertexPos: vec3,origVec: vec3,cubeSize: vec3,cubePos: vec3)->vec3 {let invOrigVec: vec3=vec3(1.0,1.0,1.0)/origVec;let halfSize: vec3=cubeSize*0.5;let intersecAtMaxPlane: vec3=(cubePos+halfSize-vertexPos)*invOrigVec;let intersecAtMinPlane: vec3=(cubePos-halfSize-vertexPos)*invOrigVec;let largestIntersec: vec3=max(intersecAtMaxPlane,intersecAtMinPlane);let distance: f32=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);let intersectPositionWS: vec3=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";Bi.IncludesShadersStoreWGSL.fresnelFunction="#ifdef FRESNEL\nfn computeFresnelTerm(viewDirection: vec3f,worldNormal: vec3f,bias: f32,power: f32)->f32\n{let fresnelTerm: f32=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}\n#endif\n";Bi.IncludesShadersStoreWGSL.meshUboDeclaration="struct Mesh {world : mat4x4,\nvisibility : f32,};var mesh : Mesh;\n#define WORLD_UBO\n";Bi.IncludesShadersStoreWGSL.morphTargetsVertex="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (var i=0; i=uniforms.morphTargetCount) {break;}\nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n}\n#endif\n#else\npositionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3;\n#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2;\n#endif\n#elif {X}==0\nuniform morphTargetCount: i32;\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.morphTargetsVertexGlobal="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration="#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array;\n#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3\n{ \nlet y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;}\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.sceneUboDeclaration="struct Scene {viewProjection : mat4x4,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4,\n#endif \nview : mat4x4,\nprojection : mat4x4,\nvEyePosition : vec4,};var scene : Scene;\n";Bi.IncludesShadersStoreWGSL.lightsFragmentFunctions="struct lightingInfo\n{diffuse: vec3f,\n#ifdef SPECULARTERM\nspecular: vec3f,\n#endif\n#ifdef NDOTL\nndl: f32,\n#endif\n};fn computeLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var lightVectorW: vec3f;var attenuation: f32=1.0;if (lightData.w==0.)\n{var direction: vec3f=lightData.xyz-vPositionW;var attenuation: f32=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nvar ndl: f32=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nfn computeSpotLighting(viewDirectionW: vec3f,vNormal: vec3f ,lightData: vec4f,lightDirection: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var direction: vec3f=lightData.xyz-vPositionW;var lightVectorW: vec3f=normalize(direction);var attenuation: f32=max(0.,1.0-length(direction)/range);var cosAngle: f32=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;var ndl: f32=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3f(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3f(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nfn computeHemisphericLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,groundColor: vec3f,glossiness: f32)->lightingInfo {var result: lightingInfo;var ndl: f32=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightData.xyz);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\nfn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f)->vec3f {var strq: vec4f=textureProjectionMatrix*vec4f(vPositionW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return textureColor;}";Bi.IncludesShadersStoreWGSL.lightFragment="#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(POINTLIGHT{X})\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(HEMILIGHT{X})\npreInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(DIRLIGHT{X})\npreInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#endif\npreInfo.NdotV=NdotV;\n#ifdef SPOTLIGHT{X}\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\n#elif defined(POINTLIGHT{X})\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\n#else\npreInfo.attenuation=1.0;\n#endif\n#ifdef HEMILIGHT{X}\npreInfo.roughness=roughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#ifdef IRIDESCENCE\npreInfo.iridescenceIntensity=iridescenceIntensity;\n#endif\n#ifdef HEMILIGHT{X}\ninfo.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround);\n#elif defined(SS_TRANSLUCENCY)\ninfo.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance);\n#else\ninfo.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef SPECULARTERM\n#ifdef ANISOTROPIC\ninfo.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#else\ninfo.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#endif\n#ifdef SHEEN\n#ifdef SHEEN_LINKWITHALBEDO\npreInfo.roughness=sheenOut.sheenIntensity;\n#else\n#ifdef HEMILIGHT{X}\npreInfo.roughness=sheenOut.sheenRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#endif\ninfo.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef CLEARCOAT\n#ifdef HEMILIGHT{X}\npreInfo.roughness=clearcoatOut.clearCoatRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\ninfo.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb);\n#ifdef CLEARCOAT_TINT\nabsorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;\n#ifdef SPECULARTERM\ninfo.specular*=absorption;\n#endif\n#endif\ninfo.diffuse*=info.clearCoat.w;\n#ifdef SPECULARTERM\ninfo.specular*=info.clearCoat.w;\n#endif\n#ifdef SHEEN\ninfo.sheen*=info.clearCoat.w;\n#endif\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},projectionLightTexture{X}Sampler,textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSMDEBUG{X} \nvar shadowDebug{X}: vec3f;\n#endif\n#ifdef SHADOWCSM{X}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nvar index{X}: i32=-1;\n#else\nvar index{X}: i32=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nvar diff{X}: f32=0.;vPositionFromLight{X}[0]=fragmentInputs.vPositionFromLight{X}_0;vPositionFromLight{X}[1]=fragmentInputs.vPositionFromLight{X}_1;vPositionFromLight{X}[2]=fragmentInputs.vPositionFromLight{X}_2;vPositionFromLight{X}[3]=fragmentInputs.vPositionFromLight{X}_3;vDepthMetric{X}[0]=fragmentInputs.vDepthMetric{X}_0;vDepthMetric{X}[1]=fragmentInputs.vDepthMetric{X}_1;vDepthMetric{X}[2]=fragmentInputs.vDepthMetric{X}_2;vDepthMetric{X}[3]=fragmentInputs.vDepthMetric{X}_3;for (var i:i32=0; i=0.) {index{X}=i;break;}}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nif (index{X}>=0)\n#endif\n{\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#else\nshadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#endif\n#else\nshadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=vec3f(shadow)*vCascadeColorsMultiplier{X}[index{X}];\n#endif\n#ifndef SHADOWCSMNOBLEND{X}\nvar frustumLength:f32=uniforms.frustumLengths{X}[index{X}];var diffRatio:f32=clamp(diff{X}/frustumLength,0.,1.)*uniforms.cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)\n{index{X}+=1;var nextShadow: f32=0.;\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nnextShadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#else\nnextShadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#endif\n#else\nnextShadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\nshadow=mix(nextShadow,shadow,diffRatio);\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);\n#endif\n}\n#endif\n}\n#elif defined(SHADOWCLOSEESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;shadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\naggShadow+=shadow;numLights+=1.0;\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor.rgb*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifndef LIGHTMAPNOSPECULAR{X}\nclearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef SHEEN\n#ifndef LIGHTMAPNOSPECULAR{X}\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#else\n#ifdef SHADOWCSMDEBUG{X}\ndiffuseBase+=info.diffuse*shadowDebug{X};\n#else \ndiffuseBase+=info.diffuse*shadow;\n#endif\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#ifdef CLEARCOAT\nclearCoatBase+=info.clearCoat.rgb*shadow;\n#endif\n#ifdef SHEEN\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.lightUboDeclaration="#ifdef LIGHT{X}\nstruct Light{X}\n{vLightData: vec4f,\nvLightDiffuse: vec4f,\nvLightSpecular: vec4f,\n#ifdef SPOTLIGHT{X}\nvLightDirection: vec4f,\nvLightFalloff: vec4f,\n#elif defined(POINTLIGHT{X})\nvLightFalloff: vec4f,\n#elif defined(HEMILIGHT{X})\nvLightGround: vec3f,\n#endif\nshadowsInfo: vec4f,\ndepthValues: vec2f} ;var light{X} : Light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform textureProjectionMatrix{X}: mat4x4f;var projectionLightTexture{X}sampler: sampler;var projectionLightTexture{X}: texture_2d;\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array;uniform viewFrustumZ{X}: array;uniform frustumLengths{X}: array;uniform cascadeBlendFactor{X}: f32;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;var vPositionFromLight{X}: array;var vDepthMetric{X} : array;\n#if defined(SHADOWPCSS{X})\nvar shadowTexture{X}Sampler: sampler_comparison; \nvar shadowTexture{X}: texture_depth_2d_array;var depthTexture{X}Sampler: sampler;var depthTexture{X}: texture_2d_array;uniform lightSizeUVCorrection{X}: array;uniform depthCorrection{X}: array;uniform penumbraDarkness{X}: f32;\n#elif defined(SHADOWPCF{X})\nvar shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d_array;\n#else \nvar shadowTexture{X}Sampler: sampler; \nvar shadowTexture{X}: texture_2d_array;\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vCascadeColorsMultiplier{X}: array=array\n(\nvec3f ( 1.5,0.0,0.0 ),\nvec3f ( 0.0,1.5,0.0 ),\nvec3f ( 0.0,0.0,5.5 ),\nvec3f ( 1.5,0.0,5.5 ),\nvec3f ( 1.5,1.5,0.0 ),\nvec3f ( 1.0,1.0,1.0 ),\nvec3f ( 0.0,1.0,5.5 ),\nvec3f ( 0.5,3.5,0.75 )\n);\n#endif\n#elif defined(SHADOWCUBE{X})\nvar shadowTexture{X}Sampler: sampler;var shadowTexture{X}: texture_cube;\n#else\nvarying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;\n#if defined(SHADOWPCSS{X})\nvar shadowTexture{X}Sampler: sampler_comparison; \nvar shadowTexture{X}: texture_depth_2d;var depthTexture{X}Sampler: sampler; \nvar depthTexture{X}: texture_2d;\n#elif defined(SHADOWPCF{X})\nvar shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d;\n#else\nvar shadowTexture{X}Sampler: sampler; \nvar shadowTexture{X}: texture_2d;\n#endif\nuniform lightMatrix{X}: mat4x4f;\n#endif\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.lightVxUboDeclaration="#ifdef LIGHT{X}\nstruct Light{X}\n{vLightData: vec4f,\nvLightDiffuse: vec4f,\nvLightSpecular: vec4f,\n#ifdef SPOTLIGHT{X}\nvLightDirection: vec4f,\nvLightFalloff: vec4f,\n#elif defined(POINTLIGHT{X})\nvLightFalloff: vec4f,\n#elif defined(HEMILIGHT{X})\nvLightGround: vec3f,\n#endif\nshadowsInfo: vec4f,\ndepthValues: vec2f} ;var light{X} : Light{X};\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f;\n#endif\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.shadowsFragmentFunctions="#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfn unpack(color: vec4f)->f32\n{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}\n#endif\nfn computeFallOff(value: f32,clipSpace: vec2f,frustumEdgeFalloff: f32)->f32\n{var mask: f32=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\nfn computeShadowCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadow: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nreturn select(darkness,1.0,depth>shadow);}\nfn computeShadowWithPoissonSamplingCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,mapSize: f32,darkness: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec3f(-1.0,1.0,-1.0);poissonDisk[1]= vec3f(1.0,-1.0,-1.0);poissonDisk[2]= vec3f(-1.0,-1.0,-1.0);poissonDisk[3]= vec3f(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[0]*mapSize)),shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nvar esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;}\nfn computeShadowWithCloseESMCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nvar esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;}\nfn computeShadowCSM(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d_array,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,uv,layer));\n#else\nvar shadow: f32=textureSample(shadowTexture,shadowSampler,uv,layer).x;\n#endif\nreturn select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}\nfn computeShadow(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadow: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nreturn select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}}\nfn computeShadowWithPoissonSampling(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,mapSize: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec2f(-0.94201624,-0.39906216);poissonDisk[1]= vec2f(0.94558609,-0.76890725);poissonDisk[2]= vec2f(-0.094184101,-0.92938870);poissonDisk[3]= vec2f(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[0]*mapSize,0.)),shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nvar esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithCloseESM(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nvar esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\nfn getZInClip(clipSpace: vec3f,uvDepth: vec3f)->f32\n{\n#ifdef IS_NDC_HALF_ZRANGE\nreturn clipSpace.z;\n#else\nreturn uvDepth.z;\n#endif\n}\nconst GREATEST_LESS_THAN_ONE: f32=0.99999994;\n#define DIAGNOSTIC_OFF\nfn computeShadowWithCSMPCF1(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var shadow: f32=textureSampleCompare(shadowTexture,shadowSampler,uvDepth.xy,layer,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithCSMPCF3(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithCSMPCF5(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),layer,uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),layer,uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),layer,uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),layer,uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithPCF1(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var shadow: f32=textureSampleCompareLevel(shadowTexture,shadowSampler,uvDepth.xy,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithPCF3(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithPCF5(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nconst PoissonSamplers32: array=array (\nvec3f(0.06407013,0.05409927,0.),\nvec3f(0.7366577,0.5789394,0.),\nvec3f(-0.6270542,-0.5320278,0.),\nvec3f(-0.4096107,0.8411095,0.),\nvec3f(0.6849564,-0.4990818,0.),\nvec3f(-0.874181,-0.04579735,0.),\nvec3f(0.9989998,0.0009880066,0.),\nvec3f(-0.004920578,-0.9151649,0.),\nvec3f(0.1805763,0.9747483,0.),\nvec3f(-0.2138451,0.2635818,0.),\nvec3f(0.109845,0.3884785,0.),\nvec3f(0.06876755,-0.3581074,0.),\nvec3f(0.374073,-0.7661266,0.),\nvec3f(0.3079132,-0.1216763,0.),\nvec3f(-0.3794335,-0.8271583,0.),\nvec3f(-0.203878,-0.07715034,0.),\nvec3f(0.5912697,0.1469799,0.),\nvec3f(-0.88069,0.3031784,0.),\nvec3f(0.5040108,0.8283722,0.),\nvec3f(-0.5844124,0.5494877,0.),\nvec3f(0.6017799,-0.1726654,0.),\nvec3f(-0.5554981,0.1559997,0.),\nvec3f(-0.3016369,-0.3900928,0.),\nvec3f(-0.5550632,-0.1723762,0.),\nvec3f(0.925029,0.2995041,0.),\nvec3f(-0.2473137,0.5538505,0.),\nvec3f(0.9183037,-0.2862392,0.),\nvec3f(0.2469421,0.6718712,0.),\nvec3f(0.3916397,-0.4328209,0.),\nvec3f(-0.03576927,-0.6220032,0.),\nvec3f(-0.04661255,0.7995201,0.),\nvec3f(0.4402924,0.3640312,0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.)\n);const PoissonSamplers64: array=array (\nvec3f(-0.613392,0.617481,0.),\nvec3f(0.170019,-0.040254,0.),\nvec3f(-0.299417,0.791925,0.),\nvec3f(0.645680,0.493210,0.),\nvec3f(-0.651784,0.717887,0.),\nvec3f(0.421003,0.027070,0.),\nvec3f(-0.817194,-0.271096,0.),\nvec3f(-0.705374,-0.668203,0.),\nvec3f(0.977050,-0.108615,0.),\nvec3f(0.063326,0.142369,0.),\nvec3f(0.203528,0.214331,0.),\nvec3f(-0.667531,0.326090,0.),\nvec3f(-0.098422,-0.295755,0.),\nvec3f(-0.885922,0.215369,0.),\nvec3f(0.566637,0.605213,0.),\nvec3f(0.039766,-0.396100,0.),\nvec3f(0.751946,0.453352,0.),\nvec3f(0.078707,-0.715323,0.),\nvec3f(-0.075838,-0.529344,0.),\nvec3f(0.724479,-0.580798,0.),\nvec3f(0.222999,-0.215125,0.),\nvec3f(-0.467574,-0.405438,0.),\nvec3f(-0.248268,-0.814753,0.),\nvec3f(0.354411,-0.887570,0.),\nvec3f(0.175817,0.382366,0.),\nvec3f(0.487472,-0.063082,0.),\nvec3f(-0.084078,0.898312,0.),\nvec3f(0.488876,-0.783441,0.),\nvec3f(0.470016,0.217933,0.),\nvec3f(-0.696890,-0.549791,0.),\nvec3f(-0.149693,0.605762,0.),\nvec3f(0.034211,0.979980,0.),\nvec3f(0.503098,-0.308878,0.),\nvec3f(-0.016205,-0.872921,0.),\nvec3f(0.385784,-0.393902,0.),\nvec3f(-0.146886,-0.859249,0.),\nvec3f(0.643361,0.164098,0.),\nvec3f(0.634388,-0.049471,0.),\nvec3f(-0.688894,0.007843,0.),\nvec3f(0.464034,-0.188818,0.),\nvec3f(-0.440840,0.137486,0.),\nvec3f(0.364483,0.511704,0.),\nvec3f(0.034028,0.325968,0.),\nvec3f(0.099094,-0.308023,0.),\nvec3f(0.693960,-0.366253,0.),\nvec3f(0.678884,-0.204688,0.),\nvec3f(0.001801,0.780328,0.),\nvec3f(0.145177,-0.898984,0.),\nvec3f(0.062655,-0.611866,0.),\nvec3f(0.315226,-0.604297,0.),\nvec3f(-0.780145,0.486251,0.),\nvec3f(-0.371868,0.882138,0.),\nvec3f(0.200476,0.494430,0.),\nvec3f(-0.494552,-0.711051,0.),\nvec3f(0.612476,0.705252,0.),\nvec3f(-0.578845,-0.768792,0.),\nvec3f(-0.772454,-0.090976,0.),\nvec3f(0.504440,0.372295,0.),\nvec3f(0.155736,0.065157,0.),\nvec3f(0.391522,0.849605,0.),\nvec3f(-0.620106,-0.328104,0.),\nvec3f(0.789239,-0.419965,0.),\nvec3f(-0.545396,0.538133,0.),\nvec3f(-0.178564,-0.596057,0.)\n);fn computeShadowWithCSMPCSS(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uvDepthLayer: vec4f= vec4f(uvDepth.x,uvDepth.y,f32(layer),uvDepth.z);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;var exitCondition: bool=depthMetric>1.0 || depthMetric<0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);}\nfn computeShadowWithPCSS32(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);}\nfn computeShadowWithPCSS64(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);}\nfn computeShadowWithCSMPCSS16(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\nfn computeShadowWithCSMPCSS32(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\nfn computeShadowWithCSMPCSS64(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#endif\n";Bi.IncludesShadersStoreWGSL.shadowsVertex="#ifdef SHADOWS\n#if defined(SHADOWCSM{X})\nvertexOutputs.vPositionFromCamera{X}=view*worldPos;\n#if SHADOWCSMNUM_CASCADES{X}>0\nvertexOutputs.vPositionFromLight{X}_0=uniforms.lightMatrix{X}[0]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_0=(-vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_0= (vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#if SHADOWCSMNUM_CASCADES{X}>1\nvertexOutputs.vPositionFromLight{X}_1=uniforms.lightMatrix{X}[1]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_1=(-vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_1= (vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#if SHADOWCSMNUM_CASCADES{X}>2\nvertexOutputs.vPositionFromLight{X}_2=uniforms.lightMatrix{X}[2]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_2=(-vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_2= (vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#if SHADOWCSMNUM_CASCADES{X}>3\nvertexOutputs.vPositionFromLight{X}_3=uniforms.lightMatrix{X}[3]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_3=(-vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_3= (vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvertexOutputs.vPositionFromLight{X}=uniforms.lightMatrix{X}*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}=(-vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}=(vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.fogFragmentDeclaration="#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vFogInfos: vec4f;uniform vFogColor: vec3f;varying vFogDistance: vec3f;fn CalcFogFactor()->f32\n{var fogCoeff: f32=1.0;var fogStart: f32=uniforms.vFogInfos.y;var fogEnd: f32=uniforms.vFogInfos.z;var fogDensity: f32=uniforms.vFogInfos.w;var fogDistance: f32=length(fragmentInputs.vFogDistance);if (FOGMODE_LINEAR==uniforms.vFogInfos.x)\n{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);}\nelse if (FOGMODE_EXP==uniforms.vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDensity);}\nelse if (FOGMODE_EXP2==uniforms.vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);}\nreturn clamp(fogCoeff,0.0,1.0);}\n#endif\n";Bi.IncludesShadersStoreWGSL.bumpFragment="var uvOffset: vec2f= vec2f(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)\n#ifdef NORMALXYSCALE\nvar normalScale: f32=1.0;\n#elif defined(BUMP)\nvar normalScale: f32=vBumpInfos.y;\n#else\nvar normalScale: f32=1.0;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nvar TBN: mat3x3f=vTBN;\n#elif defined(BUMP)\nvar TBNUV: vec2f=select(-vBumpUV,vBumpUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);\n#else\nvar TBNUV: vec2f=select(-vDetailUV,vDetailUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,vPositionW,TBNUV, vec2f(1.,1.));\n#endif\n#elif defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvar TBN: mat3x3f=vTBN;\n#else\nvar TBNUV: vec2f=select( -vMainUV1,vMainUV1,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW,vPositionW,TBNUV, vec2f(1.,1.));\n#endif\n#endif\n#ifdef PARALLAX\nvar invTBN: mat3x3f=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef DETAIL\nvar detailColor: vec4f=textureSample(detail,detailSampler,vDetailUV+uvOffset);var detailNormalRG: vec2f=detailColor.wy*2.0-1.0;var detailNormalB: f32=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));var detailNormal: vec3f= vec3f(detailNormalRG,detailNormalB);\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\n#define CUSTOM_FRAGMENT_BUMP_FRAGMENT\nnormalW=normalize(textureSample(bump,bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize( mat3x3f(normalMatrix)*normalW);\n#elif !defined(DETAIL)\nnormalW=perturbNormal(TBN,textureSample(bump,bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);\n#else\nvar bumpNormal: vec3f=textureSample(bump,bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;\n#if DETAIL_NORMALBLENDMETHOD==0 \ndetailNormal.xy*=vDetailInfos.z;var blendedNormal: vec3f=normalize( vec3f(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));\n#elif DETAIL_NORMALBLENDMETHOD==1 \ndetailNormal.xy*=vDetailInfos.z;bumpNormal+= vec3f(0.0,0.0,1.0);detailNormal*= vec3f(-1.0,-1.0,1.0);var blendedNormal: vec3f=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;\n#endif\nnormalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);\n#endif\n#elif defined(DETAIL)\ndetailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);\n#endif\n";Bi.IncludesShadersStoreWGSL.bumpFragmentMainFunctions="#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)\n#if defined(TANGENT) && defined(NORMAL) \nvarying vTBN: mat3x3f;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform normalMatrix: mat4x4f;\n#if defined(WEBGL2) || defined(WEBGPU)\nfn toNormalMatrix(wMatrix: mat4x4f)->mat4x4f\n{var ret: mat4x4f=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]= vec4f(0.,0.,0.,1.);return ret;}\n#else\nfn toNormalMatrix(m: mat4x4f)->mat4x4f\n{var a00: f32=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3],\na10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3],\na20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3],\na30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3],\nb00=a00*a11-a01*a10,\nb01=a00*a12-a02*a10,\nb02=a00*a13-a03*a10,\nb03=a01*a12-a02*a11,\nb04=a01*a13-a03*a11,\nb05=a02*a13-a03*a12,\nb06=a20*a31-a21*a30,\nb07=a20*a32-a22*a30,\nb08=a20*a33-a23*a30,\nb09=a21*a32-a22*a31,\nb10=a21*a33-a23*a31,\nb11=a22*a33-a23*a32,\ndet=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;var mi: mat4x4f= mat4x4f(\na11*b11-a12*b10+a13*b09,\na02*b10-a01*b11-a03*b09,\na31*b05-a32*b04+a33*b03,\na22*b04-a21*b05-a23*b03,\na12*b08-a10*b11-a13*b07,\na00*b11-a02*b08+a03*b07,\na32*b02-a30*b05-a33*b01,\na20*b05-a22*b02+a23*b01,\na10*b10-a11*b08+a13*b06,\na01*b08-a00*b10-a03*b06,\na30*b04-a31*b02+a33*b00,\na21*b02-a20*b04-a23*b00,\na11*b07-a10*b09-a12*b06,\na00*b09-a01*b07+a02*b06,\na31*b01-a30*b03-a32*b00,\na20*b03-a21*b01+a22*b00)/det;return mat4x4f(mi[0][0],mi[1][0],mi[2][0],mi[3][0],\nmi[0][1],mi[1][1],mi[2][1],mi[3][1],\nmi[0][2],mi[1][2],mi[2][2],mi[3][2],\nmi[0][3],mi[1][3],mi[2][3],mi[3][3]);}\n#endif\n#endif\nfn perturbNormalBase(cotangentFrame: mat3x3f,normal: vec3f,scale: f32)->vec3f\n{\n#ifdef NORMALXYSCALE\nnormal=normalize(normal* vec3f(scale,scale,1.0));\n#endif\nreturn normalize(cotangentFrame*normal);}\nfn perturbNormal(cotangentFrame: mat3x3f,textureSample: vec3f,scale: f32)->vec3f\n{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}\nfn cotangent_frame(normal: vec3f,p: vec3f,uv: vec2f,tangentSpaceParams: vec2f)->mat3x3f\n{var dp1: vec3f=dpdx(p);var dp2: vec3f=dpdy(p);var duv1: vec2f=dpdx(uv);var duv2: vec2f=dpdy(uv);var dp2perp: vec3f=cross(dp2,normal);var dp1perp: vec3f=cross(normal,dp1);var tangent: vec3f=dp2perp*duv1.x+dp1perp*duv2.x;var bitangent: vec3f=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;var det: f32=max(dot(tangent,tangent),dot(bitangent,bitangent));var invmax: f32=select(inverseSqrt(det),0.0,det==0.0);return mat3x3f(tangent*invmax,bitangent*invmax,normal);}\n#endif\n";Bi.IncludesShadersStoreWGSL.samplerFragmentDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying v_VARYINGNAME_UV: vec2f;\n#endif\nuniform _SAMPLERNAME_Sampler: sampler;uniform _SAMPLERNAME_: texture_2d;\n#endif\n";Bi.IncludesShadersStoreWGSL.bumpFragmentFunctions="#if defined(BUMP)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)\n#endif\n#if defined(DETAIL)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)\n#endif\n#if defined(BUMP) && defined(PARALLAX)\nconst minSamples: f32=4.;const maxSamples: f32=15.;const iMaxSamples: i32=15;fn parallaxOcclusion(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32)->vec2f {var parallaxLimit: f32=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;var vOffsetDir: vec2f=normalize(vViewDirCoT.xy);var vMaxOffset: vec2f=vOffsetDir*parallaxLimit;var numSamples: f32=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));var stepSize: f32=1.0/numSamples;var currRayHeight: f32=1.0;var vCurrOffset: vec2f= vec2f(0,0);var vLastOffset: vec2f= vec2f(0,0);var lastSampledHeight: f32=1.0;var currSampledHeight: f32=1.0;var keepWorking: bool=true;for (var i: i32=0; icurrRayHeight)\n{var delta1: f32=currSampledHeight-currRayHeight;var delta2: f32=(currRayHeight+stepSize)-lastSampledHeight;var ratio: f32=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}\nelse\n{currRayHeight-=stepSize;vLastOffset=vCurrOffset;\n#ifdef PARALLAX_RHS\nvCurrOffset-=stepSize*vMaxOffset;\n#else\nvCurrOffset+=stepSize*vMaxOffset;\n#endif\nlastSampledHeight=currSampledHeight;}}\nreturn vCurrOffset;}\nfn parallaxOffset(viewDir: vec3f,heightScale: f32)->vec2f\n{var height: f32=textureSample(bump,bumpSampler,vBumpUV).w;var texCoordOffset: vec2f=heightScale*viewDir.xy*height;\n#ifdef PARALLAX_RHS\nreturn texCoordOffset;\n#else\nreturn -texCoordOffset;\n#endif\n}\n#endif\n";const qf={texture_1d:_f.E1d,texture_2d:_f.E2d,texture_2d_array:_f.E2dArray,texture_3d:_f.E3d,texture_cube:_f.Cube,texture_cube_array:_f.CubeArray,texture_multisampled_2d:_f.E2d,texture_depth_2d:_f.E2d,texture_depth_2d_array:_f.E2dArray,texture_depth_cube:_f.Cube,texture_depth_cube_array:_f.CubeArray,texture_depth_multisampled_2d:_f.E2d,texture_storage_1d:_f.E1d,texture_storage_2d:_f.E2d,texture_storage_2d_array:_f.E2dArray,texture_storage_3d:_f.E3d,texture_external:null};class Zf extends Yf{constructor(){super(...arguments),this.shaderLanguage=di.WGSL,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0}preProcessor(e,t,i,s,r){for(const t in i){if("__VERSION__"===t)continue;const s=i[t];isNaN(parseInt(s))&&isNaN(parseFloat(s))||(e=`const ${t} = ${s};\n`+e)}return e}_getArraySize(e,t,i){let s=0;const r=t.lastIndexOf(">");if(t.indexOf("array")>=0&&r>0){let e=r;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;const n=t.substring(e+1,r);for(s=+n,isNaN(s)&&(s=+i[n.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){const t=`struct ${Yf.InternalsUBOName} {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar internals : ${Yf.InternalsUBOName};\n`;return-1!==e.indexOf(t)?e:t+Np(e)}varyingCheck(e,t){return/(flat|linear|perspective)?\s*(center|centroid|sample)?\s*\bvarying\b/.test(e)}varyingProcessor(e,t,i){const s=/\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==s){const r=s[1]??"perspective",n=s[2]??"center",o=s[4],a=s[3],l="flat"===r?`@interpolate(${r})`:`@interpolate(${r}, ${n})`;let h;t?(h=this._webgpuProcessingContext.availableVaryings[a],void 0===h&&Ne.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`)):(h=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(a,o,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=h,this._varyingsWGSL.push(` @location(${h}) ${l} ${a} : ${o},`),this._varyingNamesWGSL.push(a)),e=""}return e}attributeProcessor(e,t){const i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){const s=i[2],r=i[1],n=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(r,s,t)[2]);this._webgpuProcessingContext.availableAttributes[r]=n,this._webgpuProcessingContext.orderedAttributes[n]=r;const o=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[r];if(void 0!==o){const e=o<0?-1===o?"i32":"vec"+-o+"":1===o?"u32":"vec"+o+"",t=`_int_${r}_`;this._attributesInputWGSL.push(`@location(${n}) ${t} : ${e},`),this._attributesWGSL.push(`${r} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${r} = ${s}(vertexInputs_.${t});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${n}) ${r} : ${s},`),this._attributesWGSL.push(`${r} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${r} = vertexInputs_.${r};`);e=""}return e}uniformProcessor(e,t,i){const s=this.uniformRegexp.exec(e);if(null!==s){const t=s[2],r=s[1];this._addUniformToLeftOverUBO(r,t,i),e=""}return e}textureProcessor(e,t,i){const s=this.textureRegexp.exec(e);if(null!==s){const r=s[1],n=s[2],o=!!s[3],a=s[4],l=a.indexOf("storage")>0,h=s[6],c=l?h.substring(0,h.indexOf(",")).trim():null;let u=o?this._getArraySize(r,n,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[r];if(d)u=d.textures.length;else{d={isTextureArray:u>0,isStorageTexture:l,textures:[],sampleType:Sf.Float},u=u||1;for(let e=0;e0,p=qf[a],f=_?Sf.Depth:"u32"===h?Sf.Uint:"i32"===h?Sf.Sint:Sf.Float;if(d.sampleType=f,void 0===p)throw`Can't get the texture dimension corresponding to the texture function "${a}"!`;for(let i=0;i=0?"\n if (internals.yFactor_ == 1.) {\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\n }\n ":"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);const s=this._buildLeftOverUBO();t=s+t,e=(e=(e=s+e).replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;")).replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let r="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesInputWGSL.length>0&&(r+=this._attributesInputWGSL.join("\n")),r+="\n};\nvar vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(r+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n",r+=this._attributesWGSL.join("\n"),r+="\n};\nvar vertexInputs : VertexInputs_;\n");let n="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join("\n")),n+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=r+n+e;let o=`\n vertexInputs${this._hasNonFloatAttribute?"_":""} = input;\n`;this._hasNonFloatAttribute&&(o+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n",o+=this._attributesConversionCodeWGSL.join("\n"),o+="\n");let a=-1!==e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS");e=(a?"diagnostic(off, derivative_uniformity);\n":"")+Lp(e,"fn main",o," vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;"),t=(t=t.replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;")).replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let l="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(l+=this._varyingsWGSL.join("\n")),l+="\n};\nvar fragmentInputs : FragmentInputs;\n";let h="struct FragmentOutputs {\n @location(0) color : vec4,\n",c=!1,u=0;for(;!(c||(u=t.indexOf("fragmentOutputs.fragDepth",u),u<0));){const e=u;for(c=!0;u>1&&"\n"!==t.charAt(u);){if("/"===t.charAt(u)&&"/"===t.charAt(u-1)){c=!1;break}u--}u=e+25}c&&(h+=" @builtin(frag_depth) fragDepth: f32,\n"),h+="};\nvar fragmentOutputs : FragmentOutputs;\n";const d=" fragmentInputs = input;\n "+i;return a=-1!==(t=l+h+t).indexOf("#define DISABLE_UNIFORMITY_ANALYSIS"),t=(a?"diagnostic(off, derivative_uniformity);\n":"")+Lp(t,"fn main",d," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",s=`struct ${e} {\n`;for(const t of this._webgpuProcessingContext.leftOverUniforms){const r=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),n=Yf.UniformSizes[r];if(t.length>0)if(n<=2){const n=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${n} {\n @size(16)\n el: ${r},\n }`,this._stridedUniformArrays.push(t.name),s+=` @align(16) ${t.name} : array<${n}, ${t.length}>,\n`}else s+=` ${t.name} : array<${t.type}, ${t.length}>,\n`;else s+=` ${t.name} : ${t.type},\n`}return s+="};\n",s=`${i}\n${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var uniforms : ${e};\n`,s}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const s=i.exec(e);if(null===s)break;const r=s[1],n=s[2],o=r.indexOf("Sampler")===r.length-7?r.substring(0,r.indexOf("Sampler")):null,a="sampler_comparison"===n?yf.Comparison:yf.Filtering;if(o){const e=this._webgpuProcessingContext.availableTextures[o];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[r];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:a},this._webgpuProcessingContext.availableSamplers[r]=l),this._addSamplerBindingDescription(r,l,t);const h=e.substring(0,s.index),c=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `,u=e.substring(s.index);e=h+c+u,i.lastIndex+=c.length}return e}_processCustomBuffers(e,t){const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const s=i.exec(e);if(null===s)break;const r=s[1],n=s[3];let o=s[4];const a=s[5];let l=this._webgpuProcessingContext.availableBuffers[o];if(!l){const e="uniform"===r?Kf.KnownUBOs[a]:null;let t;e?(o=a,t=e.binding,-1===t.groupIndex&&(t=this._webgpuProcessingContext.availableBuffers[o]?.binding,t||(t=this._webgpuProcessingContext.getNextFreeUBOBinding()))):t=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:t},this._webgpuProcessingContext.availableBuffers[o]=l}this._addBufferBindingDescription(o,this._webgpuProcessingContext.availableBuffers[o],"read_write"===n?Tf.Storage:"storage"===r?Tf.ReadOnlyStorage:Tf.Uniform,t);const h=l.binding.groupIndex,c=l.binding.bindingIndex,u=e.substring(0,s.index),d=`@group(${h}) @binding(${c}) `,_=e.substring(s.index);e=u+d+_,i.lastIndex+=d.length}return e}_processStridedUniformArrays(e){for(const t of this._stridedUniformArrays)e=e.replace(new RegExp(`${t}\\s*\\[(.*?)\\]`,"g"),`${t}[$1].el`);return e}}class Jf{static ComputeNumMipmapLevels(e,t){return be.ILog2(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case ff.R8Unorm:case ff.R8Snorm:case ff.R8Uint:case ff.R8Sint:case ff.RG8Unorm:case ff.RG8Snorm:case ff.RG8Uint:case ff.RG8Sint:case ff.RGBA8Unorm:case ff.RGBA8UnormSRGB:case ff.RGBA8Snorm:case ff.RGBA8Uint:case ff.RGBA8Sint:case ff.BGRA8Unorm:case ff.BGRA8UnormSRGB:case ff.RGB10A2UINT:case ff.RGB10A2Unorm:case ff.RGB9E5UFloat:case ff.RG11B10UFloat:case ff.BC7RGBAUnorm:case ff.BC7RGBAUnormSRGB:case ff.BC6HRGBUFloat:case ff.BC6HRGBFloat:case ff.BC5RGUnorm:case ff.BC5RGSnorm:case ff.BC3RGBAUnorm:case ff.BC3RGBAUnormSRGB:case ff.BC2RGBAUnorm:case ff.BC2RGBAUnormSRGB:case ff.BC4RUnorm:case ff.BC4RSnorm:case ff.BC1RGBAUnorm:case ff.BC1RGBAUnormSRGB:case ff.ETC2RGB8Unorm:case ff.ETC2RGB8UnormSRGB:case ff.ETC2RGB8A1Unorm:case ff.ETC2RGB8A1UnormSRGB:case ff.ETC2RGBA8Unorm:case ff.ETC2RGBA8UnormSRGB:case ff.EACR11Unorm:case ff.EACR11Snorm:case ff.EACRG11Unorm:case ff.EACRG11Snorm:case ff.ASTC4x4Unorm:case ff.ASTC4x4UnormSRGB:case ff.ASTC5x4Unorm:case ff.ASTC5x4UnormSRGB:case ff.ASTC5x5Unorm:case ff.ASTC5x5UnormSRGB:case ff.ASTC6x5Unorm:case ff.ASTC6x5UnormSRGB:case ff.ASTC6x6Unorm:case ff.ASTC6x6UnormSRGB:case ff.ASTC8x5Unorm:case ff.ASTC8x5UnormSRGB:case ff.ASTC8x6Unorm:case ff.ASTC8x6UnormSRGB:case ff.ASTC8x8Unorm:case ff.ASTC8x8UnormSRGB:case ff.ASTC10x5Unorm:case ff.ASTC10x5UnormSRGB:case ff.ASTC10x6Unorm:case ff.ASTC10x6UnormSRGB:case ff.ASTC10x8Unorm:case ff.ASTC10x8UnormSRGB:case ff.ASTC10x10Unorm:case ff.ASTC10x10UnormSRGB:case ff.ASTC12x10Unorm:case ff.ASTC12x10UnormSRGB:case ff.ASTC12x12Unorm:case ff.ASTC12x12UnormSRGB:case ff.Stencil8:return 0;case ff.R16Uint:case ff.R16Sint:case ff.RG16Uint:case ff.RG16Sint:case ff.RGBA16Uint:case ff.RGBA16Sint:case ff.Depth16Unorm:return 5;case ff.R16Float:case ff.RG16Float:case ff.RGBA16Float:return 2;case ff.R32Uint:case ff.R32Sint:case ff.RG32Uint:case ff.RG32Sint:case ff.RGBA32Uint:case ff.RGBA32Sint:return 7;case ff.R32Float:case ff.RG32Float:case ff.RGBA32Float:case ff.Depth32Float:case ff.Depth32FloatStencil8:case ff.Depth24Plus:case ff.Depth24PlusStencil8:return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case ff.R8Unorm:case ff.R8Snorm:case ff.R8Uint:case ff.R8Sint:return{width:1,height:1,length:1};case ff.R16Uint:case ff.R16Sint:case ff.R16Float:case ff.RG8Unorm:case ff.RG8Snorm:case ff.RG8Uint:case ff.RG8Sint:return{width:1,height:1,length:2};case ff.R32Uint:case ff.R32Sint:case ff.R32Float:case ff.RG16Uint:case ff.RG16Sint:case ff.RG16Float:case ff.RGBA8Unorm:case ff.RGBA8UnormSRGB:case ff.RGBA8Snorm:case ff.RGBA8Uint:case ff.RGBA8Sint:case ff.BGRA8Unorm:case ff.BGRA8UnormSRGB:case ff.RGB9E5UFloat:case ff.RGB10A2UINT:case ff.RGB10A2Unorm:case ff.RG11B10UFloat:return{width:1,height:1,length:4};case ff.RG32Uint:case ff.RG32Sint:case ff.RG32Float:case ff.RGBA16Uint:case ff.RGBA16Sint:case ff.RGBA16Float:return{width:1,height:1,length:8};case ff.RGBA32Uint:case ff.RGBA32Sint:case ff.RGBA32Float:return{width:1,height:1,length:16};case ff.Stencil8:throw"No fixed size for Stencil8 format!";case ff.Depth16Unorm:return{width:1,height:1,length:2};case ff.Depth24Plus:throw"No fixed size for Depth24Plus format!";case ff.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case ff.Depth32Float:return{width:1,height:1,length:4};case ff.Depth32FloatStencil8:return{width:1,height:1,length:5};case ff.BC7RGBAUnorm:case ff.BC7RGBAUnormSRGB:case ff.BC6HRGBUFloat:case ff.BC6HRGBFloat:case ff.BC5RGUnorm:case ff.BC5RGSnorm:case ff.BC3RGBAUnorm:case ff.BC3RGBAUnormSRGB:case ff.BC2RGBAUnorm:case ff.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case ff.BC4RUnorm:case ff.BC4RSnorm:case ff.BC1RGBAUnorm:case ff.BC1RGBAUnormSRGB:case ff.ETC2RGB8Unorm:case ff.ETC2RGB8UnormSRGB:case ff.ETC2RGB8A1Unorm:case ff.ETC2RGB8A1UnormSRGB:case ff.EACR11Unorm:case ff.EACR11Snorm:return{width:4,height:4,length:8};case ff.ETC2RGBA8Unorm:case ff.ETC2RGBA8UnormSRGB:case ff.EACRG11Unorm:case ff.EACRG11Snorm:case ff.ASTC4x4Unorm:case ff.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case ff.ASTC5x4Unorm:case ff.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case ff.ASTC5x5Unorm:case ff.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case ff.ASTC6x5Unorm:case ff.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case ff.ASTC6x6Unorm:case ff.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case ff.ASTC8x5Unorm:case ff.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case ff.ASTC8x6Unorm:case ff.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case ff.ASTC8x8Unorm:case ff.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case ff.ASTC10x5Unorm:case ff.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case ff.ASTC10x6Unorm:case ff.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case ff.ASTC10x8Unorm:case ff.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case ff.ASTC10x10Unorm:case ff.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case ff.ASTC12x10Unorm:case ff.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case ff.ASTC12x12Unorm:case ff.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}static IsCompressedFormat(e){switch(e){case ff.BC7RGBAUnormSRGB:case ff.BC7RGBAUnorm:case ff.BC6HRGBFloat:case ff.BC6HRGBUFloat:case ff.BC5RGSnorm:case ff.BC5RGUnorm:case ff.BC4RSnorm:case ff.BC4RUnorm:case ff.BC3RGBAUnormSRGB:case ff.BC3RGBAUnorm:case ff.BC2RGBAUnormSRGB:case ff.BC2RGBAUnorm:case ff.BC1RGBAUnormSRGB:case ff.BC1RGBAUnorm:case ff.ETC2RGB8Unorm:case ff.ETC2RGB8UnormSRGB:case ff.ETC2RGB8A1Unorm:case ff.ETC2RGB8A1UnormSRGB:case ff.ETC2RGBA8Unorm:case ff.ETC2RGBA8UnormSRGB:case ff.EACR11Unorm:case ff.EACR11Snorm:case ff.EACRG11Unorm:case ff.EACRG11Snorm:case ff.ASTC4x4Unorm:case ff.ASTC4x4UnormSRGB:case ff.ASTC5x4Unorm:case ff.ASTC5x4UnormSRGB:case ff.ASTC5x5Unorm:case ff.ASTC5x5UnormSRGB:case ff.ASTC6x5Unorm:case ff.ASTC6x5UnormSRGB:case ff.ASTC6x6Unorm:case ff.ASTC6x6UnormSRGB:case ff.ASTC8x5Unorm:case ff.ASTC8x5UnormSRGB:case ff.ASTC8x6Unorm:case ff.ASTC8x6UnormSRGB:case ff.ASTC8x8Unorm:case ff.ASTC8x8UnormSRGB:case ff.ASTC10x5Unorm:case ff.ASTC10x5UnormSRGB:case ff.ASTC10x6Unorm:case ff.ASTC10x6UnormSRGB:case ff.ASTC10x8Unorm:case ff.ASTC10x8UnormSRGB:case ff.ASTC10x10Unorm:case ff.ASTC10x10UnormSRGB:case ff.ASTC12x10Unorm:case ff.ASTC12x10UnormSRGB:case ff.ASTC12x12Unorm:case ff.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return ff.Depth16Unorm;case 16:return ff.Depth24Plus;case 13:return ff.Depth24PlusStencil8;case 14:return ff.Depth32Float;case 18:return ff.Depth32FloatStencil8;case 19:return ff.Stencil8;case 36492:return i?ff.BC7RGBAUnormSRGB:ff.BC7RGBAUnorm;case 36495:return ff.BC6HRGBUFloat;case 36494:return ff.BC6HRGBFloat;case 33779:return i?ff.BC3RGBAUnormSRGB:ff.BC3RGBAUnorm;case 33778:return i?ff.BC2RGBAUnormSRGB:ff.BC2RGBAUnorm;case 33777:case 33776:return i?ff.BC1RGBAUnormSRGB:ff.BC1RGBAUnorm;case 37808:return i?ff.ASTC4x4UnormSRGB:ff.ASTC4x4Unorm;case 36196:case 37492:return i?ff.ETC2RGB8UnormSRGB:ff.ETC2RGB8Unorm;case 37496:return i?ff.ETC2RGBA8UnormSRGB:ff.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return ff.R8Snorm;case 7:return ff.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return ff.R8Sint;case 9:return ff.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return ff.RGBA8Sint;default:return ff.RGBA8Snorm}case 0:switch(t){case 6:return ff.R8Unorm;case 7:return ff.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?ff.RGBA8UnormSRGB:ff.RGBA8Unorm;case 12:return i?ff.BGRA8UnormSRGB:ff.BGRA8Unorm;case 8:return ff.R8Uint;case 9:return ff.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return ff.RGBA8Uint;case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return ff.RGBA8Unorm}case 4:switch(t){case 8:return ff.R16Sint;case 9:return ff.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ff.RGBA16Sint}case 5:switch(t){case 8:return ff.R16Uint;case 9:return ff.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ff.RGBA16Uint}case 6:switch(t){case 8:return ff.R32Sint;case 9:return ff.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ff.RGBA32Sint}case 7:switch(t){case 8:return ff.R32Uint;case 9:return ff.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ff.RGBA32Uint}case 1:switch(t){case 6:return ff.R32Float;case 7:return ff.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return ff.RGBA32Float}case 2:switch(t){case 6:return ff.R16Float;case 7:return ff.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return ff.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return ff.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"}case 14:switch(t){case 5:default:return ff.RGB9E5UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:default:return ff.RGB10A2Unorm;case 11:return ff.RGB10A2UINT}}return i?ff.RGBA8UnormSRGB:ff.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case ff.R8Unorm:case ff.R8Snorm:case ff.R8Uint:case ff.R8Sint:case ff.BC4RUnorm:case ff.BC4RSnorm:case ff.R16Uint:case ff.R16Sint:case ff.Depth16Unorm:case ff.R16Float:case ff.R32Uint:case ff.R32Sint:case ff.R32Float:case ff.Depth32Float:case ff.Stencil8:case ff.Depth24Plus:case ff.EACR11Unorm:case ff.EACR11Snorm:return 1;case ff.RG8Unorm:case ff.RG8Snorm:case ff.RG8Uint:case ff.RG8Sint:case ff.Depth32FloatStencil8:case ff.BC5RGUnorm:case ff.BC5RGSnorm:case ff.RG16Uint:case ff.RG16Sint:case ff.RG16Float:case ff.RG32Uint:case ff.RG32Sint:case ff.RG32Float:case ff.Depth24PlusStencil8:case ff.EACRG11Unorm:case ff.EACRG11Snorm:return 2;case ff.RGB9E5UFloat:case ff.RG11B10UFloat:case ff.BC6HRGBUFloat:case ff.BC6HRGBFloat:case ff.ETC2RGB8Unorm:case ff.ETC2RGB8UnormSRGB:return 3;case ff.RGBA8Unorm:case ff.RGBA8UnormSRGB:case ff.RGBA8Snorm:case ff.RGBA8Uint:case ff.RGBA8Sint:case ff.BGRA8Unorm:case ff.BGRA8UnormSRGB:case ff.RGB10A2UINT:case ff.RGB10A2Unorm:case ff.BC7RGBAUnorm:case ff.BC7RGBAUnormSRGB:case ff.BC3RGBAUnorm:case ff.BC3RGBAUnormSRGB:case ff.BC2RGBAUnorm:case ff.BC2RGBAUnormSRGB:case ff.BC1RGBAUnorm:case ff.BC1RGBAUnormSRGB:case ff.RGBA16Uint:case ff.RGBA16Sint:case ff.RGBA16Float:case ff.RGBA32Uint:case ff.RGBA32Sint:case ff.RGBA32Float:case ff.ETC2RGB8A1Unorm:case ff.ETC2RGB8A1UnormSRGB:case ff.ETC2RGBA8Unorm:case ff.ETC2RGBA8UnormSRGB:case ff.ASTC4x4Unorm:case ff.ASTC4x4UnormSRGB:case ff.ASTC5x4Unorm:case ff.ASTC5x4UnormSRGB:case ff.ASTC5x5Unorm:case ff.ASTC5x5UnormSRGB:case ff.ASTC6x5Unorm:case ff.ASTC6x5UnormSRGB:case ff.ASTC6x6Unorm:case ff.ASTC6x6UnormSRGB:case ff.ASTC8x5Unorm:case ff.ASTC8x5UnormSRGB:case ff.ASTC8x6Unorm:case ff.ASTC8x6UnormSRGB:case ff.ASTC8x8Unorm:case ff.ASTC8x8UnormSRGB:case ff.ASTC10x5Unorm:case ff.ASTC10x5UnormSRGB:case ff.ASTC10x6Unorm:case ff.ASTC10x6UnormSRGB:case ff.ASTC10x8Unorm:case ff.ASTC10x8UnormSRGB:case ff.ASTC10x10Unorm:case ff.ASTC10x10UnormSRGB:case ff.ASTC12x10Unorm:case ff.ASTC12x10UnormSRGB:case ff.ASTC12x12Unorm:case ff.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case ff.Stencil8:case ff.Depth32FloatStencil8:case ff.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case ff.Depth32FloatStencil8:case ff.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case ff.Depth16Unorm:return ff.Depth16Unorm;case ff.Depth24Plus:case ff.Depth24PlusStencil8:return ff.Depth24Plus;case ff.Depth32Float:case ff.Depth32FloatStencil8:return ff.Depth32Float}return e}static GetSample(e){return e>1?4:1}}class em{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){return this._webgpuMSAATexture?.[e]??null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),-1===t&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(const e of this._webgpuMSAATexture)e?.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this._originalFormatIsRGB=!1,this.format=ff.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,s,r,n,o,a){let l=_f.E2d,h=1;s?(l=i?_f.CubeArray:_f.Cube,h=6*(a||1)):r?(l=_f.E3d,h=1):i&&(l=_f.E2dArray,h=a);const c=Jf.GetDepthFormatOnly(this.format),u=Jf.HasDepthAndStencilAspects(this.format)?pf.DepthOnly:pf.All;this.createView({label:`TextureView${r?"3D":s?"Cube":"2D"}${i?"_Array"+h:""}_${n}x${o}_${t?"wmips":"womips"}_${this.format}_${l}`,format:c,dimension:l,mipLevelCount:t?be.ILog2(Math.max(n,o))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:h,aspect:u})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){this._webgpuTexture?.destroy(),this.releaseMSAATexture(),this._copyInvertYTempTexture?.destroy(),this.reset()}}const tm="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) out flat ivec2 vTextureSize;\n #endif\n\n void main() {\n #ifdef INVERTY\n vTextureSize = textureSize(img, 0);\n #endif\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",im=tm;var sm,rm;!function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"}(sm||(sm={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(rm||(rm={}));const nm=[{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(location = 0) out vec2 vTex;\n\n void main() {\n vTex = tex[gl_VertexIndex];\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform sampler imgSampler;\n layout(set = 0, binding = 1) uniform texture2D img;\n\n layout(location = 0) in vec2 vTex;\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = texture(sampler2D(img, imgSampler), vTex);\n }\n "},{vertex:tm,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "},{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n\n void main() {\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform Uniforms {\n uniform vec4 color;\n };\n\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = color;\n }\n "},{vertex:im,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n layout(set = 0, binding = 1) uniform Params {\n float ofstX;\n float ofstY;\n float width;\n float height;\n };\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) {\n discard;\n }\n if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) {\n discard;\n }\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "}],om={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};class am{constructor(e,t,i,s,r,n){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._glslang=i,this._tintWASM=s,this._bufferManager=r,-1!==n.indexOf(af.RG11B10UFloatRenderable)){const e=Object.keys(om);om[ff.RG11B10UFloat]=om[e[e.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:gf.Linear}),this._videoSampler=t.createSampler({minFilter:gf.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,hf.Uniform|hf.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(ff.RGBA8Unorm),this._getVideoPipeline(ff.RGBA8Unorm)}_getPipeline(e,t=sm.MipMap,i){const s=t===sm.MipMap?1:t===sm.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===sm.Clear?8:t===sm.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let r=this._pipelines[e][s];if(!r){let n="#version 450\n";t!==sm.InvertYPremultiplyAlpha&&t!==sm.InvertYPremultiplyAlphaWithOfst||(i.invertY&&(n+="#define INVERTY\n"),i.premultiplyAlpha&&(n+="#define PREMULTIPLYALPHA\n"));let o=this._compiledShaders[s];if(!o){let e=this._glslang.compileGLSL(n+nm[t].vertex,"vertex"),i=this._glslang.compileGLSL(n+nm[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));const r=this._device.createShaderModule({code:e}),a=this._device.createShaderModule({code:i});o=this._compiledShaders[s]=[r,a]}const a=this._device.createRenderPipeline({layout:Pf.Auto,vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:If.TriangleStrip,stripIndexFormat:Ff.Uint16}});r=this._pipelines[e][s]=[a,a.getBindGroupLayout(0)]}return r}_getVideoPipeline(e,t=rm.DontInvertY){const i=t===rm.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let s=this._videoPipelines[e][i];if(!s){let t=this._videoCompiledShaders[i];if(!t){const e=this._device.createShaderModule({code:"\n struct VertexOutput {\n @builtin(position) Position : vec4,\n @location(0) fragUV : vec2\n }\n\n @vertex\n fn main(\n @builtin(vertex_index) VertexIndex : u32\n ) -> VertexOutput {\n var pos = array, 4>(\n vec2(-1.0, 1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, -1.0)\n );\n var tex = array, 4>(\n vec2(0.0, 0.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(1.0, 1.0)\n );\n\n var output: VertexOutput;\n\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = tex[VertexIndex];\n\n return output;\n }\n "}),s=this._device.createShaderModule({code:0===i?"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\n }\n ":"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y));\n }\n "});t=this._videoCompiledShaders[i]=[e,s]}const r=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:Pf.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:If.TriangleStrip,stripIndexFormat:Ff.Uint16}});s=this._videoPipelines[e][i]=[r,r.getBindGroupLayout(0)]}return s}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,s=!1,r){const n=void 0===r,[o,a]=this._getVideoPipeline(i,s?rm.InvertY:rm.DontInvertY);n&&(r=this._device.createCommandEncoder({})),r.pushDebugGroup?.(`copy video to texture - invertY=${s}`);const l=t._hardwareTexture,h={label:`BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${i}_${s?"InvertY":"DontInvertY"}${t.label?"_"+t.label:""}`,colorAttachments:[{view:l.underlyingResource.createView({format:i,dimension:_f.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:pf.All}),loadOp:Uf.Load,storeOp:Gf.Store}]},c=r.beginRenderPass(h),u={layout:a,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},d=this._device.createBindGroup(u);c.setPipeline(o),c.setBindGroup(0,d),c.draw(4,1,0,0),c.end(),r.popDebugGroup?.(),n&&(this._device.queue.submit([r.finish()]),r=null)}invertYPreMultiplyAlpha(e,t,i,s,r=!1,n=!1,o=0,a=0,l=1,h=0,c=0,u=0,d=0,_,p){const f=0!==u,m=void 0===_,[g,v]=this._getPipeline(s,f?sm.InvertYPremultiplyAlphaWithOfst:sm.InvertYPremultiplyAlpha,{invertY:r,premultiplyAlpha:n});let x;if(o=Math.max(o,0),m&&(_=this._device.createCommandEncoder({})),_.pushDebugGroup?.(`internal process texture - invertY=${r} premultiplyAlpha=${n}`),Jf.IsHardwareTexture(e)?(x=e.underlyingResource,r&&!n&&1===l&&0===o||(e=void 0)):(x=e,e=void 0),!x)return;f&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,c,u,d]),0,16);const b=e,T=b?._copyInvertYTempTexture??this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,s,1,_,df.CopySrc|df.RenderAttachment|df.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),y=b?._copyInvertYRenderPassDescr??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${s}_${r?"InvertY":"DontInvertY"}_${n?"PremultiplyAlpha":"DontPremultiplyAlpha"}`,colorAttachments:[{view:T.createView({format:s,dimension:_f.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:Uf.Load,storeOp:Gf.Store}]},S=_.beginRenderPass(y);let C=f?b?._copyInvertYBindGroupWithOfst:b?._copyInvertYBindGroup;if(!C){const e={layout:v,entries:[{binding:0,resource:x.createView({format:s,dimension:_f.E2d,baseMipLevel:a,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:o})}]};f&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),C=this._device.createBindGroup(e)}S.setPipeline(g),S.setBindGroup(0,C),S.draw(4,1,0,0),S.end(),_.copyTextureToTexture({texture:T},{texture:x,mipLevel:a,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),b?(b._copyInvertYTempTexture=T,b._copyInvertYRenderPassDescr=y,f?b._copyInvertYBindGroupWithOfst=C:b._copyInvertYBindGroup=C):this._deferredReleaseTextures.push([T,null]),_.popDebugGroup?.(),m&&(this._device.queue.submit([_.finish()]),_=null)}copyWithInvertY(e,t,i,s){const r=void 0===s,[n,o]=this._getPipeline(t,sm.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});r&&(s=this._device.createCommandEncoder({})),s.pushDebugGroup?.("internal copy texture with invertY");const a=s.beginRenderPass(i),l=this._device.createBindGroup({layout:o,entries:[{binding:0,resource:e}]});a.setPipeline(n),a.setBindGroup(0,l),a.draw(4,1,0,0),a.end(),s.popDebugGroup?.(),r&&(this._device.queue.submit([s.finish()]),s=null)}createTexture(e,t=!1,i=!1,s=!1,r=!1,n=!1,o=ff.RGBA8Unorm,a=1,l,h=-1,c=0,u){a=Jf.GetSample(a);const d=e.layers||1,_={width:e.width,height:e.height,depthOrArrayLayers:d},p=om[o]?df.RenderAttachment:0,f=Jf.IsCompressedFormat(o),m=t?Jf.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:df.CopySrc|df.CopyDst|df.TextureBinding;c|=t&&!f?df.CopySrc|p:0,f||n||(c|=p|df.CopyDst);const v=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_Texture${n?"3D":"2D"}_${u?u+"_":""}${_.width}x${_.height}x${_.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${a}`,size:_,dimension:n?uf.E3d:uf.E2d,format:o,usage:g|c,sampleCount:a,mipLevelCount:m});return Jf.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,o,0,0,s,r,0,0),t&&i&&this.generateMipmaps(v,o,m,0,n,l)),v}createCubeTexture(e,t=!1,i=!1,s=!1,r=!1,n=ff.RGBA8Unorm,o=1,a,l=-1,h=0,c){o=Jf.GetSample(o);const u=Jf.IsImageBitmapArray(e)?e[0].width:e.width,d=Jf.IsImageBitmapArray(e)?e[0].height:e.height,_=om[n]?df.RenderAttachment:0,p=Jf.IsCompressedFormat(n),f=t?Jf.ComputeNumMipmapLevels(u,d):1,m=l>=0?l:df.CopySrc|df.CopyDst|df.TextureBinding;h|=t&&!p?df.CopySrc|_:0,p||(h|=_|df.CopyDst);const g=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${c?c+"_":""}${u}x${d}x6_${t?"wmips":"womips"}_${n}_samples${o}`,size:{width:u,height:d,depthOrArrayLayers:6},dimension:uf.E2d,format:n,usage:m|h,sampleCount:o,mipLevelCount:f});return Jf.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,u,d,n,s,r,0,0),t&&i&&this.generateCubeMipmaps(g,n,f,a)),g}generateCubeMipmaps(e,t,i,s){const r=void 0===s;r&&(s=this._device.createCommandEncoder({})),s.pushDebugGroup?.(`create cube mipmaps - ${i} levels`);for(let r=0;r<6;++r)this.generateMipmaps(e,t,i,r,!1,s);s.popDebugGroup?.(),r&&(this._device.queue.submit([s.finish()]),s=null)}generateMipmaps(e,t,i,s=0,r=!1,n){const o=void 0===n,[a,l]=this._getPipeline(t);let h;if(s=Math.max(s,0),o&&(n=this._device.createCommandEncoder({})),n.pushDebugGroup?.(`create mipmaps for face #${s} - ${i} levels`),Jf.IsHardwareTexture(e)?(h=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(h=e,e=void 0),!h)return;const c=e;for(let e=1;eh;)this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,h),c+=h;this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,r-c)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const s=new Uint16Array(t);for(;e--;)i[e]=ip(s[e]);return i}readDataFromBuffer(e,t,i,s,r,n,o=0,a=0,l=null,h=!0,c=!1){const u=1===o?2:2===o?1:0,d=this._engine.uniqueId;return new Promise(((i,_)=>{e.mapAsync(cf.Read,a,t).then((()=>{const d=e.getMappedRange(a,t);let _=l;if(c)_=null===_?Kn(o,t,!0,d):Kn(o,_.buffer,void 0,d);else if(null===_)switch(u){case 0:_=new Uint8Array(t),_.set(new Uint8Array(d));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:_=new Float32Array(t/4),_.set(new Float32Array(d))}else switch(u){case 0:_=new Uint8Array(_.buffer),_.set(new Uint8Array(d));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:_=new Float32Array(_.buffer),_.set(new Float32Array(d))}if(r!==n){1!==u||c||(r*=2,n*=2);const e=new Uint8Array(_.buffer);let t=r,i=0;for(let o=1;o{this._engine.isDisposed||this._engine.uniqueId!==d?i(new Uint8Array):_(e)}))}))}releaseBuffer(e){return hm._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e1?4:1;return cm[e.samplingMode]+um[(e._comparisonFunction||514)-512+1]+dm[e.samplingMode]+((e._cachedWrapU??1)<<8)+((e._cachedWrapV??1)<<10)+((e._cachedWrapR??1)<<12)+((e.useMipMaps?1:0)<<14)+(t<<15)}static _GetSamplerFilterDescriptor(e,t){let i,s,r,n,o;const a=e.useMipMaps;switch(e.samplingMode){case 11:i=gf.Linear,s=gf.Linear,r=gf.Nearest,a||(n=o=0);break;case 3:case 3:i=gf.Linear,s=gf.Linear,a?r=gf.Linear:(r=gf.Nearest,n=o=0);break;case 8:i=gf.Nearest,s=gf.Nearest,a?r=gf.Linear:(r=gf.Nearest,n=o=0);break;case 4:i=gf.Nearest,s=gf.Nearest,r=gf.Nearest,a||(n=o=0);break;case 5:i=gf.Nearest,s=gf.Linear,r=gf.Nearest,a||(n=o=0);break;case 6:i=gf.Nearest,s=gf.Linear,a?r=gf.Linear:(r=gf.Nearest,n=o=0);break;case 7:i=gf.Nearest,s=gf.Linear,r=gf.Nearest,n=o=0;break;case 1:case 1:default:i=gf.Nearest,s=gf.Nearest,r=gf.Nearest,n=o=0;break;case 9:i=gf.Linear,s=gf.Nearest,r=gf.Nearest,a||(n=o=0);break;case 10:i=gf.Linear,s=gf.Nearest,a?r=gf.Linear:(r=gf.Nearest,n=o=0);break;case 2:case 2:i=gf.Linear,s=gf.Linear,r=gf.Nearest,n=o=0;break;case 12:i=gf.Linear,s=gf.Nearest,r=gf.Nearest,n=o=0}return t>1&&(0!==n||0!==o)&&r!==gf.Nearest?{magFilter:gf.Linear,minFilter:gf.Linear,mipmapFilter:gf.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:s,mipmapFilter:r,lodMinClamp:n,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return mf.Repeat;case 0:return mf.ClampToEdge;case 2:return mf.MirrorRepeat}return mf.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,t){const i=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,s=this._GetSamplerFilterDescriptor(e,i);return{label:t,...s,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?_m.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:s.anisotropyEnabled?i:1}}static GetCompareFunction(e){switch(e){case 519:return xf.Always;case 514:return xf.Equal;case 516:return xf.Greater;case 518:return xf.GreaterEqual;case 513:default:return xf.Less;case 515:return xf.LessEqual;case 512:return xf.Never;case 517:return xf.NotEqual}}getSampler(e,t=!1,i=0,s){if(this.disabled)return this._device.createSampler(_m._GetSamplerDescriptor(e,s));t?i=0:0===i&&(i=_m.GetSamplerHashCode(e));let r=t?void 0:this._samplers[i];return r||(r=this._device.createSampler(_m._GetSamplerDescriptor(e,s)),t||(this._samplers[i]=r)),r}}var pm;!function(e){e[e.StencilReadMask=0]="StencilReadMask",e[e.StencilWriteMask=1]="StencilWriteMask",e[e.DepthBias=2]="DepthBias",e[e.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",e[e.DepthStencilState=4]="DepthStencilState",e[e.MRTAttachments1=5]="MRTAttachments1",e[e.MRTAttachments2=6]="MRTAttachments2",e[e.RasterizationState=7]="RasterizationState",e[e.ColorStates=8]="ColorStates",e[e.ShaderStage=9]="ShaderStage",e[e.TextureStage=10]="TextureStage",e[e.VertexState=11]="VertexState",e[e.NumStates=12]="NumStates"}(pm||(pm={}));const fm={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},mm={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class gm{constructor(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[ff.BGRA8Unorm],this.setColorFormat(ff.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(ff.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,s=0){if(i=Jf.GetSample(i),this.disabled){const r=gm._GetTopology(e);return this._setVertexState(t),this._setTextureState(s),this._parameter.pipeline=this._createRenderPipeline(t,r,i),gm.NumCacheMiss++,gm._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(s),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,gm.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return gm.NumCacheHitWithHash++,this._parameter.pipeline;const r=gm._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,r,i),this._setRenderPipeline(this._parameter),gm.NumCacheMiss++,gm._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){gm.NumPipelineCreationLastFrame=gm._NumPipelineCreationCurrentFrame,gm._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,s,r,n,o,a){this._depthWriteEnabled=o,this._depthTestEnabled=n,this._depthCompare=(a??519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(s),this.setDepthBias(r)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[pm.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[pm.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=om[e??""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const i=[0,0];let s=0,r=0,n=0;for(let o=0;o=32&&(r=0,s++)}this._mrtFormats.length=n,this._mrtAttachments1===i[0]&&this._mrtAttachments2===i[1]||(this._mrtAttachments1=i[0],this._mrtAttachments2=i[1],this._states[pm.MRTAttachments1]=i[0],this._states[pm.MRTAttachments2]=i[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=void 0===e?0:om[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(e??519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(e??519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=null===e?1:mm[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:mm[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:mm[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[pm.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[pm.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,s,r,n,o){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=null===i?1:mm[i],this._stencilFrontPassOp=null===s?2:mm[s],this._stencilFrontFailOp=null===r?1:mm[r],this.setStencilReadMask(n),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return If.TriangleList;case 2:case 3:return If.PointList;case 1:case 4:return If.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return If.LineStrip;case 7:return If.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return wf.Add;case 32778:return wf.Subtract;case 32779:return wf.ReverseSubtract;case 32775:return wf.Min;case 32776:return wf.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return Df.Zero;case 1:default:return Df.One;case 768:return Df.Src;case 769:return Df.OneMinusSrc;case 770:return Df.SrcAlpha;case 771:return Df.OneMinusSrcAlpha;case 772:return Df.DstAlpha;case 773:return Df.OneMinusDstAlpha;case 774:return Df.Dst;case 775:return Df.OneMinusDst;case 776:return Df.SrcAlphaSaturated;case 32769:case 32771:return Df.Constant;case 32770:case 32772:return Df.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:return xf.Never;case 1:return xf.Less;case 2:return xf.Equal;case 3:return xf.LessEqual;case 4:return xf.Greater;case 5:return xf.NotEqual;case 6:return xf.GreaterEqual;case 7:return xf.Always}return xf.Never}static _GetStencilOpFunction(e){switch(e){case 0:return Nf.Zero;case 1:return Nf.Keep;case 2:return Nf.Replace;case 3:return Nf.IncrementClamp;case 4:return Nf.DecrementClamp;case 5:return Nf.Invert;case 6:return Nf.IncrementWrap;case 7:return Nf.DecrementWrap}return Nf.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,s=e.getSize();switch(t){case er.BYTE:switch(s){case 1:case 2:return i?Lf.Snorm8x2:Lf.Sint8x2;case 3:case 4:return i?Lf.Snorm8x4:Lf.Sint8x4}break;case er.UNSIGNED_BYTE:switch(s){case 1:case 2:return i?Lf.Unorm8x2:Lf.Uint8x2;case 3:case 4:return i?Lf.Unorm8x4:Lf.Uint8x4}break;case er.SHORT:switch(s){case 1:case 2:return i?Lf.Snorm16x2:Lf.Sint16x2;case 3:case 4:return i?Lf.Snorm16x4:Lf.Sint16x4}break;case er.UNSIGNED_SHORT:switch(s){case 1:case 2:return i?Lf.Unorm16x2:Lf.Uint16x2;case 3:case 4:return i?Lf.Unorm16x4:Lf.Uint16x4}break;case er.INT:switch(s){case 1:return Lf.Sint32;case 2:return Lf.Sint32x2;case 3:return Lf.Sint32x3;case 4:return Lf.Sint32x4}break;case er.UNSIGNED_INT:switch(s){case 1:return Lf.Uint32;case 2:return Lf.Uint32x2;case 3:return Lf.Uint32x3;case 4:return Lf.Uint32x4}break;case er.FLOAT:switch(s){case 1:return Lf.Float32;case 2:return Lf.Float32x2;case 3:return Lf.Float32x3;case 4:return Lf.Float32x4}}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${s}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:gm._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:gm._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:gm._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:gm._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:gm._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:gm._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[pm.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace-1+((this._cullEnabled?this._cullFace:0)<<1)+((this._clampDepth?1:0)<<3)+((this._alphaToCoverageEnabled?1:0)<<4)+(e<<5)+(t<<8);this._rasterizationState!==i&&(this._rasterizationState=i,this._states[pm.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=(0|(null===this._alphaBlendFuncParams[0]?2:fm[this._alphaBlendFuncParams[0]]))+((null===this._alphaBlendFuncParams[1]?2:fm[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:fm[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:fm[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[pm.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.ColorStates))}_setDepthStencilState(){const e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[pm.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.DepthStencilState))}_setVertexState(e){const t=this._statesLength;let i=pm.VertexState;const s=e._pipelineContext,r=s.shaderProcessingContext.attributeNamesFromEffect,n=s.shaderProcessingContext.attributeLocationsFromEffect;let o,a=0;for(let e=0;e0)for(let e=0;e=this._video.HAVE_CURRENT_DATA}dispose(){}}class Sm{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=Sm._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],s=-1;i?s=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?_m.GetSamplerHashCode(t):0;const r=s!==i.hashCode;r&&this.updateId++,this.isDirty||(this.isDirty=r)}setTexture(e,t){let i=this.textures[e],s=-1;i?s=i.texture?.uniqueId??-1:this.textures[e]=i={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},i.isExternalTexture&&this._numExternalTextures--,i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(i.isFloatOrDepthTexture=1===t.type||t.format>=13&&t.format<=18,i.isExternalTexture=ym.IsExternalTexture(t),i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,i.isExternalTexture&&this._numExternalTextures++):(i.isFloatOrDepthTexture=!1,i.isExternalTexture=!1),i.texture=t;const r=s!==(t?.uniqueId??-1);r&&this.updateId++,this.isDirty||(this.isDirty=r)}}Sm._Counter=0;class Cm{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,hf.CopyDst|hf.Indirect|hf.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=Cm._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){this._isDirty||(this._isDirty=t?.uniqueId!==this.buffers[e]?.uniqueId),this.buffers[e]=t}setIndirectData(e,t,i){t!==this._currentInstanceCount&&this.indirectDrawBuffer&&this._indirectDrawData&&(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}}Cm._Counter=0;class Em{constructor(){this.values={}}}class Am{static get Statistics(){return{totalCreated:Am.NumBindGroupsCreatedTotal,lastFrameCreated:Am.NumBindGroupsCreatedLastFrame,lookupLastFrame:Am.NumBindGroupsLookupLastFrame,noLookupLastFrame:Am.NumBindGroupsNoLookupLastFrame}}static ResetCache(){Am._Cache=new Em,Am.NumBindGroupsCreatedTotal=0,Am.NumBindGroupsCreatedLastFrame=0,Am.NumBindGroupsLookupLastFrame=0,Am.NumBindGroupsNoLookupLastFrame=0,Am._NumBindGroupsCreatedCurrentFrame=0,Am._NumBindGroupsLookupCurrentFrame=0,Am._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){Am.NumBindGroupsCreatedLastFrame=Am._NumBindGroupsCreatedCurrentFrame,Am.NumBindGroupsLookupLastFrame=Am._NumBindGroupsLookupCurrentFrame,Am.NumBindGroupsNoLookupLastFrame=Am._NumBindGroupsNoLookupCurrentFrame,Am._NumBindGroupsCreatedCurrentFrame=0,Am._NumBindGroupsLookupCurrentFrame=0,Am._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){let s,r=Am._Cache;const n=this.disabled||i.forceBindGroupCreation;if(!n){if(!t.isDirty(i.updateId)&&!i.isDirty)return Am._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const i of e.shaderProcessingContext.bufferNames){const e=t.buffers[i]?.uniqueId??0;let s=r.values[e];s||(s=new Em,r.values[e]=s),r=s}for(const t of e.shaderProcessingContext.samplerNames){const e=i.samplers[t]?.hashCode??0;let s=r.values[e];s||(s=new Em,r.values[e]=s),r=s}for(const t of e.shaderProcessingContext.textureNames){const e=i.textures[t]?.texture?.uniqueId??0;let s=r.values[e];s||(s=new Em,r.values[e]=s),r=s}s=r.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,s)return t.bindGroups=s,Am._NumBindGroupsLookupCurrentFrame++,s;s=[],t.bindGroups=s,n||(r.bindGroups=s),Am.NumBindGroupsCreatedTotal++,Am._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[i.textureState];for(let r=0;r"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=this._cacheSampler.getSampler(t,!1,e.hashCode,t.label)}else Ne.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.texture||n.storageTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){Ne.Error(`Trying to bind a null texture! entry=${JSON.stringify(n)}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||n.texture&&!t.view||n.storageTexture&&!t.viewForWriting)){Ne.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=n.storageTexture?t.viewForWriting:t.view}else Ne.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.externalTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){Ne.Error(`Trying to bind a null external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){Ne.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=this._device.importExternalTexture({source:t})}else Ne.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.buffer){const e=t.buffers[l];if(e){const t=e.underlyingResource;a[s].resource.buffer=t,a[s].resource.size=e.capacity}else Ne.Error(`Can't find buffer "${l}". entry=${JSON.stringify(n)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const l=o[r];s[r]=this._device.createBindGroup({layout:l,entries:a})}return s}}Am.NumBindGroupsCreatedTotal=0,Am.NumBindGroupsCreatedLastFrame=0,Am.NumBindGroupsLookupLastFrame=0,Am.NumBindGroupsNoLookupLastFrame=0,Am._Cache=new Em,Am._NumBindGroupsCreatedCurrentFrame=0,Am._NumBindGroupsLookupCurrentFrame=0,Am._NumBindGroupsNoLookupCurrentFrame=0;Bi.ShadersStoreWGSL.clearQuadVertexShader="uniform depthValue: f32;const pos=array(\nvec2f(-1.0,1.0),\nvec2f(1.0,1.0),\nvec2f(-1.0,-1.0),\nvec2f(1.0,-1.0)\n);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.position=vec4f(pos[input.vertexIndex],uniforms.depthValue,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";Bi.ShadersStoreWGSL.clearQuadPixelShader="uniform color: vec4f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;}\n";class Pm{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new xm(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"],void 0,void 0,void 0,void 0,void 0,void 0,di.WGSL)}clear(e,t,i,s,r=1){let n,o,a=null;const l=!!this._engine._currentRenderTarget;if(e)n=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t1?2**36:0)+h*2**37,o=this._keyTemp.join("_"),a=this._bundleCache[o],a)return a;n=this._device.createRenderBundleEncoder({label:"clearQuadRenderBundle",colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:Jf.GetSample(r)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!s&&!!this._depthTextureFormat&&Jf.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(s?255:0),this._cacheRenderPipeline.setStencilCompare(s?519:512),this._cacheRenderPipeline.setStencilPassOp(s?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const h=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,r),c=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),c.uniformBuffer.update();const u=l?this._engine._ubInvertY:this._engine._ubDontInvertY,d=c.uniformBuffer.getBuffer(),_=d.uniqueId+"-"+u.uniqueId;let p=this._bindGroups[_];if(!p){const e=c.bindGroupLayouts[0];p=this._bindGroups[_]=[],p.push(this._device.createBindGroup({label:`clearQuadBindGroup0-${_}`,layout:e[0],entries:[]})),Kf._SimplifiedKnownBindings||p.push(this._device.createBindGroup({label:`clearQuadBindGroup1-${_}`,layout:e[1],entries:[]})),p.push(this._device.createBindGroup({label:`clearQuadBindGroup${Kf._SimplifiedKnownBindings?1:2}-${_}`,layout:e[Kf._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:u.underlyingResource,size:u.capacity}},{binding:1,resource:{buffer:d.underlyingResource,size:d.capacity}}]}))}n.setPipeline(h);for(let e=0;e{const e=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,e}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==s)return null;throw e}))}async readValue(e=0){const t=this._getBuffer(e,1);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(cf.Read).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(cf.Read).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[1]-e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0})))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;const i=this._engine.frameId;this._measureDuration.stopPass(e).then((e=>{t._addDuration(i,null!==e&&e>0?e:0)}))}dispose(){this._measureDuration?.dispose()}}class km{constructor(e,t,i,s=2,r){this._count=s,this._querySet=new Lm(e,s,zf.Timestamp,t,i,!0,r)}start(e){e.writeTimestamp?.(this._querySet.querySet,0)}async stop(e){return e.writeTimestamp?.(this._querySet.querySet,1),e.writeTimestamp?this._querySet.readTwoValuesAndSubtract(0):0}startPass(e,t){if(t+3>this._count)throw new Error("WebGPUDurationMeasure: index out of range ("+t+")");e.timestampWrites={querySet:this._querySet.querySet,beginningOfPassWriteIndex:t+2,endOfPassWriteIndex:t+3}}async stopPass(e){return this._querySet.readTwoValuesAndSubtract(e+2)}dispose(){this._querySet.dispose()}}class Vm{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;const t=void 0!==this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,s=50,r=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=r,this._allocateNewIndices(s)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();const e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e})))}_allocateNewIndices(e){e=e??this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose),1e3)}dispose(){this._querySet?.dispose(),this._availableIndices.length=0}}class Um{async initTwgsl(e){if(!Um._Twgsl)return e=e||{},(e={...Um._TWgslDefaultOptions,...e}).twgsl?(Um._Twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await Ds.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(Um._Twgsl=await self.twgsl(Ds.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=Um._Twgsl.convertSpirV2WGSL(e,Um.DisableUniformityAnalysis||t);return Um.ShowWGSLShaderCode&&(Ne.Log(i),Ne.Log("***********************************************")),Um.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}Um._TWgslDefaultOptions={jsPath:`${Ds._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${Ds._DefaultCdnUrl}/twgsl/twgsl.wasm`},Um.ShowWGSLShaderCode=!1,Um.DisableUniformityAnalysis=!1,Um._Twgsl=null;class Gm{constructor(e,t,i){this._record=!1,this._play=!1,this._playBundleListIndex=0,this._allBundleLists=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._allBundleLists.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endRenderPass(e){if(!this._record&&!this._play)return!1;let t;if(this._record)t=this._bundleList.clone(),this._allBundleLists.push(t),this._bundleList.reset();else{if(this._playBundleListIndex>=this._allBundleLists.length)throw new Error(`Invalid playBundleListIndex! Your snapshot is no longer valid for the current frame, you should recreate a new one. playBundleListIndex=${this._playBundleListIndex}, allBundleLists.length=${this._allBundleLists.length}}`);t=this._allBundleLists[this._playBundleListIndex++]}return t.run(e),1===this._mode&&this._engine._reportDrawCall(t.numDrawCalls),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0}reset(){this.enabled=!1,this.enabled=!0}}Bi.ShadersStoreWGSL.postprocessVertexShader="attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class zm extends ym{constructor(e){super(e)}}const Wm={label:"TextureView_SwapChain_ResolveTarget",dimension:uf.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Hm={label:"TextureView_SwapChain",dimension:uf.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Xm=new Ae;class Ym extends ns{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return!!this._cacheSampler&&this._cacheSampler.disabled}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}areAllEffectsReady(){return!0}getFontOffset(e){return Zn(e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then((e=>!!e),(()=>!1)).catch((()=>!1)):Promise.resolve(!1)}static get IsSupported(){return Ne.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){return this.name+this.version}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get enableGPUTimingMeasurements(){return this._timestampQuery.enable}set enableGPUTimingMeasurements(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new Hu:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new Ym(e,t);return new Promise((e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then((()=>e(i)))}))}constructor(e,t={}){super(t.antialias??!0,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._timestampIndex=0,this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this.scenes=[],this._virtualScenes=new Array,this._commandBuffers=[null,null],this._currentRenderPass=null,this._mainRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._rttRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._pendingDebugCommands=[],this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this._snapshotRenderingMode=0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._performanceMonitor=new Qn,this._name="WebGPU",this._drawCalls=new wr,t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=t.enableGPUDebugMarkers??!1,Ne.Log(`Babylon.js v${oo.Version} - ${this.description} engine`),navigator.gpu?(t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,navigator&&navigator.userAgent&&this._setupMobileChecks(),this._sharedInit(this._renderingCanvas),this._shaderProcessor=new $f,this._shaderProcessorWGSL=new Zf):Ne.Error("WebGPU is not supported by your browser.")}initAsync(e,t){return this.uniqueId=Ym._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,this._initGlslang(e??this._options?.glslangOptions).then((e=>(this._glslang=e,this._tintWASM=Ym.UseTWGSL?new Um:null,this._tintWASM?this._tintWASM.initTwgsl(t??this._options?.twgslOptions).then((()=>navigator.gpu.requestAdapter(this._options))):navigator.gpu.requestAdapter(this._options)))).then((e=>{if(e){this._adapter=e,this._adapterSupportedExtensions=[],this._adapter.features?.forEach((e=>this._adapterSupportedExtensions.push(e))),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then((e=>{this._adapterInfo=e}));const t=this._options.deviceDescriptor??{},i=t?.requiredFeatures??(this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0);if(i){const e=i,s=[];for(const t of e)-1!==this._adapterSupportedExtensions.indexOf(t)&&s.push(t);t.requiredFeatures=s}if(this._options.setMaximumLimits&&!t.requiredLimits){t.requiredLimits={};for(const e in this._adapterSupportedLimits)"minSubgroupSize"!==e&&"maxSubgroupSize"!==e&&(t.requiredLimits[e]=this._adapterSupportedLimits[e])}return t.label=`BabylonWebGPUDevice${this.uniqueId}`,this._adapter.requestDevice(t)}throw"Could not retrieve a WebGPU adapter (adapter is null)."})).then((e=>{this._device=e,this._deviceEnabledExtensions=[],this._device.features?.forEach((e=>this._deviceEnabledExtensions.push(e))),this._deviceLimits=e.limits;let t=-1;this._device.addEventListener("uncapturederror",(e=>{++t{this._isDisposed||(this._contextWasLost=!0,Ne.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost((async()=>{const e=this.snapshotRenderingMode,t=this.snapshotRendering,i=this.disableCacheSamplers,s=this.disableCacheRenderPipelines,r=this.disableCacheBindGroups,n=this.enableGPUTimingMeasurements;await this.initAsync(this._glslangOptions??this._options?.glslangOptions,this._twgslOptions??this._options?.twgslOptions),this.snapshotRenderingMode=e,this.snapshotRendering=t,this.disableCacheSamplers=i,this.disableCacheRenderPipelines=s,this.disableCacheBindGroups=r,this.enableGPUTimingMeasurements=n,this._currentRenderPass=null})))}))})).then((()=>{this._bufferManager=new hm(this,this._device),this._textureHelper=new am(this,this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new _m(this._device),this._cacheBindGroups=new Am(this._device,this._cacheSampler,this),this._timestampQuery=new Bm(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new Vm(this,this._device,this._bufferManager):void 0,this._bundleList=new Fm(this._device),this._snapshotRendering=new Gm(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),hf.Uniform|hf.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),hf.Uniform|hf.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&void 0===this._count&&(this._count=0,Ne.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._initializeLimits(),this._emptyVertexBuffer=new er(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new xm(this._device,this._emptyVertexBuffer),this._depthCullingState=new Tm(this._cacheRenderPipeline),this._stencilStateComposer=new bm(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new Pm(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()})).catch((e=>{throw Ne.Error("A fatal error occurred during WebGPU creation/initialization."),e}))}_initGlslang(e){return e=e||{},(e={...Ym._GLSLslangDefaultOptions,...e}).glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?Ds.LoadBabylonScriptAsync(e.jsPath).then((()=>self.glslang(Ds.GetBabylonScriptURL(e.wasmPath)))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(af.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(af.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(af.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(af.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf(af.RG11B10UFloatRenderable)>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(af.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf(af.TimestampQuery)||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new em],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._setColorFormat(this._mainRenderPassWrapper)}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};const e=new Float32Array([this.getRenderHeight(!0)]);let t;if(this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e),this._options.antialias){const e={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:uf.E2d,format:this._options.swapChainFormat,usage:df.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(e),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:uf.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new Ae(0,0,0,1),loadOp:Uf.Clear,storeOp:Gf.Store}]}else t=[{view:void 0,clearValue:new Ae(0,0,0,1),loadOp:Uf.Clear,storeOp:Gf.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?ff.Depth24PlusStencil8:ff.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);const i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:uf.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:df.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const s={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:uf.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:Uf.Clear,depthStoreOp:Gf.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?Uf.Clear:void 0,stencilStoreOp:this.isStencilEnable?Gf.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:s}}_sharedInit(e){super._sharedInit(e),$n(this,e,this._creationOptions)}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:df.RenderAttachment|df.CopySrc,alphaMode:this.premultipliedAlpha?Wf.Premultiplied:Wf.Opaque})}resizeImageBitmap(e,t,i){return eo(this,e,t,i)}_createImageBitmapFromSource(e,t){return Jn(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&to(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&io()}enterPointerlock(){this._renderingCanvas&&so(this._renderingCanvas)}exitPointerlock(){ro()}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){xm.ResetCache(),Am.ResetCache();const t=e=>{for(const t of e){for(const e of t.meshes){const t=e.subMeshes;if(t)for(const e of t)e._drawWrappers=[]}for(const e of t.materials)e._materialContext?.reset()}};t(this.scenes),t(this._virtualScenes);const i=[];for(const e of this._uniformBuffers)e.name.indexOf("leftOver")<0&&i.push(e);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setSize(e,t,i=!1){return!!super.setSize(e,t,i)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0,r=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,n=i===di.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===di.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,o,i,s,r)}_compilePipelineStageDescriptor(e,t,i,s){this.onBeforeShaderCompilationObservable.notifyObservers(this);const r=e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,n=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,o="#version 450\n",a=s===di.GLSL?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),l=s===di.GLSL?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(a,l,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new Bp(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new Qf(e,this)}createMaterialContext(){return new Sm}createDrawContext(){return new Cm(this._bufferManager)}_preparePipelineContext(e,t,i,s,r,n,o,a){const l=e,h=l.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(Ne.Log(["defines",a]),Ne.Log(t),Ne.Log(i),Ne.Log("***********************************************")),l.sources={fragment:i,vertex:t,rawVertex:r,rawFragment:n},l.stages=s?this._compileRawPipelineStageDescriptor(t,i,h):this._compilePipelineStageDescriptor(t,i,a,h)}getAttributes(e,t){const i=new Array(t.length),s=e;for(let e=0;e0,n.is3D=l>0,n._cachedWrapU=0,n._cachedWrapV=0,n._useSRGBBuffer=r.useSRGBBuffer,n.label=r.label,this._internalTexturesCache.push(n),i||this._textureHelper.createGPUTextureForInternalTexture(n,o,a,h||1,r.creationFlags),n}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,_,p){return this._createTextureBase(e,t,i,s,r,n,o,((e,t,i,s,r,n,o,a)=>{const l=s;if(e.baseWidth=l.width,e.baseHeight=l.height,e.width=l.width,e.height=l.height,e.format=-1!==e.format?e.format:h??5,e.type=-1!==e.type?e.type:0,e._creationFlags=_??0,a(e.width,e.height,l,t,e,(()=>{})),e._hardwareTexture?.underlyingResource)n||o||this._generateMipmaps(e,this._uploadEncoder);else{const t=this._textureHelper.createGPUTextureForInternalTexture(e,l.width,l.height,void 0,_);Jf.IsImageBitmap(l)&&(this._textureHelper.updateTexture(l,e,l.width,l.height,e.depth,t.format,0,0,r,!1,0,0),n||o||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}),(()=>!1),a,l,h,c,u,d,p)}wrapWebGPUTexture(e){const t=new em(e),i=new ss(this,is.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers}_unpackFlipY(e){}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,s=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==s&&(e._cachedWrapR=s)}updateTextureDimensions(e,t,i,s=1){if(!e._hardwareTexture)return;if(e.width===t&&e.height===i&&e.depth===s)return;const r=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,s,r)}_setInternalTexture(e,t,i){if(i=i??e,this._currentEffect){const s=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),s&&s.autoBindSampler){const e=i+"Sampler";this._currentMaterialContext.setSampler(e,t)}}}createPrefilteredCubeTexture(e,t,i,s,r=null,n=null,o,a=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(r&&r(null));const t=e.texture;l?e.info.sphericalPolynomial&&(t._sphericalPolynomial=e.info.sphericalPolynomial):t._sphericalPolynomial=new j_,t._source=is.CubePrefiltered,r&&r(t)}),n,o,a,l,i,s)}setTexture(e,t,i,s){this._setTexture(e,i,!1,!1,s,s)}setTextureArray(e,t,i,s){for(let e=0;e{const o=()=>{n.mapAsync(cf.Read,0,i).then((()=>{const t=n.getMappedRange(0,i);let r=s;if(void 0===r)r=new Uint8Array(i),r.set(new Uint8Array(t));else{const e=r.constructor;r=new e(r.buffer),r.set(new e(t))}n.unmap(),this._bufferManager.releaseBuffer(n),e(r)}),(i=>{this.isDisposed?e(new Uint8Array):t(i)}))};r?(this.flushFramebuffer(),o()):this.onEndFrameObservable.addOnce((()=>{o()}))}))}setStorageBuffer(e,t){this._currentDrawContext?.setBuffer(e,t?.getBuffer()??null)}}Ym._GLSLslangDefaultOptions={jsPath:`${Ds._DefaultCdnUrl}/glslang/glslang.js`,wasmPath:`${Ds._DefaultCdnUrl}/glslang/glslang.wasm`},Ym._InstanceId=0,Ym.UseTWGSL=!0,Ym.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode===e&&(0===e&&!this._alphaState.alphaBlend||0!==e&&this._alphaState.alphaBlend)){if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.setDepthWrite(t),this._cacheRenderPipeline.setDepthWriteEnabled(t))}}else{switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,1),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,1),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(1,1,0,1),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(770,1,0,1),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(0,769,1,1),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(774,0,1,1),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(770,769,1,1),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(32769,32770,32771,32772),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(1,769,1,771),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,1),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(772,1,0,0),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(775,769,773,771),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,0),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(775,769,0,1),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,771),this._alphaState.alphaBlend=!0}t||(this.setDepthWrite(0===e),this._cacheRenderPipeline.setDepthWriteEnabled(0===e)),this._alphaMode=e,this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)}},Ym.prototype.setAlphaEquation=function(e){ns.prototype.setAlphaEquation.call(this,e),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};class Qm{getBindGroups(e,t,i){if(!i)throw new Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");if(0===this._bindGroups.length){const s=this._bindGroupEntries.length>0;for(const t in e){const r=e[t],n=i[t],o=n.group,a=n.binding,l=r.type,h=r.object;let c=r.indexInGroupEntries,u=this._bindGroupEntries[o];switch(u||(u=this._bindGroupEntries[o]=[]),l){case Wu.Sampler:{const e=h;void 0!==c&&s?u[c].resource=this._cacheSampler.getSampler(e):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:this._cacheSampler.getSampler(e)}));break}case Wu.Texture:case Wu.TextureWithoutSampler:{const e=h,t=e._texture._hardwareTexture;void 0!==c&&s?(l===Wu.Texture&&(u[c++].resource=this._cacheSampler.getSampler(e._texture)),u[c].resource=t.view):(r.indexInGroupEntries=u.length,l===Wu.Texture&&u.push({binding:a-1,resource:this._cacheSampler.getSampler(e._texture)}),u.push({binding:a,resource:t.view}));break}case Wu.StorageTexture:{const e=h,t=e._texture._hardwareTexture;t.textureAdditionalUsages&df.StorageBinding||Ne.Error(`computeDispatch: The texture (name=${e.name}, uniqueId=${e.uniqueId}) is not a storage texture!`,50),void 0!==c&&s?u[c].resource=t.viewForWriting:(r.indexInGroupEntries=u.length,u.push({binding:a,resource:t.viewForWriting}));break}case Wu.ExternalTexture:{const e=h.underlyingResource;void 0!==c&&s?u[c].resource=this._device.importExternalTexture({source:e}):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:this._device.importExternalTexture({source:e})}));break}case Wu.UniformBuffer:case Wu.StorageBuffer:case Wu.DataBuffer:{const e=l===Wu.DataBuffer?h:(Wu.UniformBuffer,h.getBuffer()),t=e.underlyingResource;void 0!==c&&s?(u[c].resource.buffer=t,u[c].resource.size=e.capacity):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:{buffer:t,offset:0,size:e.capacity}}));break}}}for(let e=0;e0&&d.dispatchWorkgroups(s,r,n),d.end(),h&&(this._timestampQuery.endPass(this._timestampIndex,h),this._timestampIndex+=2)},Ym.prototype.releaseComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e].getPipelineContext();this._deleteComputePipelineContext(t)}this._compiledComputeEffects={}},Ym.prototype._prepareComputePipelineContext=function(e,t,i,s,r){const n=e;this.dbgShowShaderCode&&(Ne.Log(s),Ne.Log(t)),n.sources={compute:t,rawCompute:i},n.stage=this._createComputePipelineStageDescriptor(t,s,r)},Ym.prototype._releaseComputeEffect=function(e){this._compiledComputeEffects[e._key]&&(delete this._compiledComputeEffects[e._key],this._deleteComputePipelineContext(e.getPipelineContext()))},Ym.prototype._rebuildComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}},Ym.prototype._executeWhenComputeStateIsCompiled=function(e,t){e.stage.module.getCompilationInfo().then((e=>{const i={numErrors:0,messages:[]};for(const t of e.messages)"error"===t.type&&i.numErrors++,i.messages.push({type:t.type,text:t.message,line:t.lineNum,column:t.linePos,length:t.length,offset:t.offset});t(i)}))},Ym.prototype._deleteComputePipelineContext=function(e){e&&e.dispose()},Ym.prototype._createComputePipelineStageDescriptor=function(e,t,i){return t=t?"//"+t.split("\n").join("\n//")+"\n":"",{module:this._device.createShaderModule({code:t+e}),entryPoint:i}},Ym.prototype._createDepthStencilCubeTexture=function(e,t){const i=new ss(this,t.generateStencil?is.DepthStencil:is.Depth);i.isCube=!0,i.label=t.label;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t};i.format=s.depthTextureFormat,this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction,s.samples),this._textureHelper.createGPUTextureForInternalTexture(i);const r=i._hardwareTexture;return i.type=Jf.GetTextureTypeFromFormat(r.format),this._internalTexturesCache.push(i),i},Ym.prototype.createCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d=!1){return this.createCubeTextureBase(e,t,i,!!s,r,n,o,a,l,h,c,u,null,((e,t)=>{const i=t,n=i[0].width,a=n;this._setCubeMapTextureParams(e,!s),e.format=o??-1;const l=this._textureHelper.createGPUTextureForInternalTexture(e,n,a);this._textureHelper.updateCubeTextures(i,l.underlyingResource,n,a,l.format,!1,!1,0,0),s||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),r&&r()}),!!d)},Ym.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},Ym.prototype.generateMipMapsForCubemap=function(e){if(e.generateMipMaps){const t=e._hardwareTexture?.underlyingResource;t||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e)}},Ym.prototype._debugPushGroup=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.pushDebugGroup(e):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e]))},Ym.prototype._debugPopGroup=function(e){this._options.enableGPUDebugMarkers&&(0===e||1===e?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))},Ym.prototype._debugInsertMarker=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.insertDebugMarker(e):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e]))},Ym.prototype._debugFlushPendingCommands=function(){for(let e=0;e{const i=d.width,n=o(e);if(n){if(a){const e=4===s,t=a(n),o=d._hardwareTexture,l=[0,1,2,3,4,5];for(let s=0;s>s,a=[];for(let i=0;i<6;i++){let o=t[s][l[i]];e&&(o=$m(o,n,n,r)),a.push(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}this._textureHelper.updateCubeTextures(a,o.underlyingResource,n,n,o.format,u,!1,0,0)}}else this.updateRawCubeTexture(d,n,s,r,u);d.isReady=!0,t?.removePendingData(d),l&&l()}};return this._loadFile(e,(e=>{_(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)})),d},Ym.prototype.createRawTexture3D=function(e,t,i,s,r,n,o,a,l=null,h=0,c=0){const u=is.Raw3D,d=new ss(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=s,d.width=t,d.height=i,d.depth=s,d.format=r,d.type=h,d.generateMipMaps=n,d.samplingMode=a,d.is3D=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,void 0,c),this.updateRawTexture3D(d,e,r,o,l,h),this._internalTexturesCache.push(d),d},Ym.prototype.updateRawTexture3D=function(e,t,i,s,r=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r),t){const r=e._hardwareTexture;4===i&&(t=$m(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,r.format,0,0,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Ym.prototype.createRawTexture2DArray=function(e,t,i,s,r,n,o,a,l=null,h=0,c=0){const u=is.Raw2DArray,d=new ss(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=s,d.width=t,d.height=i,d.depth=s,d.format=r,d.type=h,d.generateMipMaps=n,d.samplingMode=a,d.is2DArray=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,s,c),this.updateRawTexture2DArray(d,e,r,o,l,h),this._internalTexturesCache.push(d),d},Ym.prototype.updateRawTexture2DArray=function(e,t,i,s,r=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r),t){const r=e._hardwareTexture;4===i&&(t=$m(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,r.format,0,0,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Ym.prototype._readTexturePixels=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){const c=e._hardwareTexture;return o&&this.flushFramebuffer(),this._textureHelper.readPixels(c.underlyingResource,l,h,t,i,c.format,s,r,n,a)},Ym.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};class qm extends Bl{constructor(e,t,i,s,r){super(e,t,i,s,r),s.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new Hu)}}Ym.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const s=new qm(e,t,i,this);return this._renderTargetWrapperCache.push(s),s},Ym.prototype.createRenderTargetTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),s={};void 0!==t&&"object"==typeof t?(s.generateMipMaps=t.generateMipMaps,s.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,s.generateStencilBuffer=s.generateDepthBuffer&&t.generateStencilBuffer,s.samplingMode=void 0===t.samplingMode?3:t.samplingMode,s.creationFlags=t.creationFlags??0,s.noColorAttachment=!!t.noColorAttachment,s.samples=t.samples,s.label=t.label):(s.generateMipMaps=t,s.generateDepthBuffer=!0,s.generateStencilBuffer=!1,s.samplingMode=3,s.creationFlags=0,s.noColorAttachment=!1);const r=s.noColorAttachment?null:this._createInternalTexture(e,t,!0,is.RenderTarget);return i.label=s.label??"RenderTargetWrapper",i._samples=s.samples??1,i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer,i.setTextures(r),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,!1,i._generateStencilBuffer,i.samples,s.generateStencilBuffer?13:14,s.label?s.label+"-DepthStencil":void 0),r&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r,void 0,void 0,void 0,s.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!1)),i},Ym.prototype._createDepthStencilTexture=function(e,t){const i=new ss(this,t.generateStencil?is.DepthStencil:is.Depth);i.label=t.label;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t};i.format=s.depthTextureFormat,this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction,s.samples),this._textureHelper.createGPUTextureForInternalTexture(i);const r=i._hardwareTexture;return i.type=Jf.GetTextureTypeFromFormat(r.format),this._internalTexturesCache.push(i),i},Ym.prototype._setupDepthStencilTexture=function(e,t,i,s,r,n=1){const o=t.width||t,a=t.height||t,l=t.layers||0,h=t.depth||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.is3D=h>0,e.depth=l||h,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=1,e._comparisonFunction=r,e._cachedWrapU=0,e._cachedWrapV=0},Ym.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t?(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t,t):t},Ym.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,i.label=s.label??"RenderTargetWrapper",i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer;const r=new ss(this,is.RenderTarget);return r.width=e,r.height=e,r.depth=0,r.isReady=!0,r.isCube=!0,r.samples=s.samples,r.generateMipMaps=s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,r.format=s.format,this._internalTexturesCache.push(r),i.setTextures(r),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,void 0===s.samplingMode||2===s.samplingMode||2===s.samplingMode||3===s.samplingMode||3===s.samplingMode||5===s.samplingMode||6===s.samplingMode||7===s.samplingMode||11===s.samplingMode,i._generateStencilBuffer,i.samples),t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r),t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!1),i},Ym.prototype.setDepthStencilTexture=function(e,t,i,s){i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,s):this._setTexture(e,null,void 0,void 0,s)},Ym.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;e._hardwareTexture?.underlyingResource||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),function(e){return!(!e||void 0===e.underlyingResource)}(t)?(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0):t&&this.createImageBitmap(t).then((t=>{this._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,s.format,0,0,!i,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0})).catch((()=>{e.isReady=!0}))};class Zm{static async CreateAsync(e,t){return await Ym.IsSupportedAsync?Ym.CreateAsync(e,t):oo.IsSupported?new oo(e,void 0,t):new L_(t)}}class Jm{}Jm.COPY=1,Jm.CUT=2,Jm.PASTE=3;class eg{constructor(e,t){this.type=e,this.event=t}static GetTypeFromCharacter(e){switch(e){case 67:return Jm.COPY;case 86:return Jm.PASTE;case 88:return Jm.CUT;default:return-1}}}class tg extends sd{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=Ee.Gray(),i=Ju.DefaultUtilityLayer,s=null,r=1,n=Ee.Yellow(),o=Ee.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new K,this.uniformScaling=!1,this.sensitivity=1,this.dragScale=1,this.incrementalSnap=!1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._tmpVector=new _e(0,0,0),this._incrementalStartupValue=_e.Zero(),this._parent=s,this._coloredMaterial=new cu("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ee(.1,.1,.1)),this._hoverMaterial=new cu("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new cu("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4,this._gizmoMesh=new ha("axis",i.utilityLayerScene);const{arrowMesh:a,arrowTail:l}=this._createGizmoMesh(this._gizmoMesh,r),h=this._createGizmoMesh(this._gizmoMesh,r+4,!0);this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,sd.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3);const c=a.position.clone(),u=l.position.clone(),d=l.scaling.clone(),_=e=>{const t=e*(3/this._rootMesh.scaling.length())*6;a.position.z+=t/3.5,l.scaling.y+=t,this.dragScale=l.scaling.y,l.position.z=a.position.z/2},p=()=>{a.position.set(c.x,c.y,c.z),l.position.set(u.x,u.y,u.z),l.scaling.set(d.x,d.y,d.z),this.dragScale=l.scaling.y,this._dragging=!1};this.dragBehavior=new Xa({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior);let f=0,m=0;const g={snapDistance:0};this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const i=this.sensitivity*t.dragDistance*(3*this.scaleRatio/this._rootMesh.scaling.length()),s=this._tmpVector;let r=!1,n=0;if(this.uniformScaling?s.setAll(.57735):s.copyFrom(e),0==this.snapDistance)s.scaleToRef(i,s);else{f+=i,m+=i;const e=this.incrementalSnap?m:f;Math.abs(e)>this.snapDistance?(n=Math.floor(Math.abs(e)/this.snapDistance),e<0&&(n*=-1),f%=this.snapDistance,s.scaleToRef(this.snapDistance*n,s),r=!0):s.scaleInPlace(0)}s.addInPlaceFromFloats(1,1,1),s.x=Math.abs(s.x)0&&this.incrementalSnap?(this.attachedNode.getWorldMatrix().decompose(void 0,ve.Quaternion[0],ve.Vector3[2],sd.PreserveScaling?o:void 0),s.addInPlace(this._incrementalStartupValue),s.addInPlaceFromFloats(-1,-1,-1),s.x=Math.abs(s.x)*(this._incrementalStartupValue.x>0?1:-1),s.y=Math.abs(s.y)*(this._incrementalStartupValue.y>0?1:-1),s.z=Math.abs(s.z)*(this._incrementalStartupValue.z>0?1:-1),me.ComposeToRef(s,ve.Quaternion[0],ve.Vector3[2],ve.Matrix[1])):(me.ScalingToRef(s.x,s.y,s.z,ve.Matrix[2]),ve.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(),ve.Matrix[1])),ve.Matrix[1].decompose(ve.Vector3[1],void 0,void 0,sd.PreserveScaling?o:void 0);const a=1e5;Math.abs(ve.Vector3[1].x){this._dragging=!0;const e=this.attachedNode._isMesh?this.attachedNode:void 0;this.attachedNode?.getWorldMatrix().decompose(this._incrementalStartupValue,void 0,void 0,sd.PreserveScaling?e:void 0),f=0,m=0})),this.dragBehavior.onDragObservable.add((e=>_(e.dragDistance))),this.dragBehavior.onDragEndObservable.add(p),s?.uniformScaleGizmo?.dragBehavior?.onDragObservable?.add((e=>_(e.delta.y))),s?.uniformScaleGizmo?.dragBehavior?.onDragEndObservable?.add(p);const v={gizmoMeshes:[a,l],colliderMeshes:[h.arrowMesh,h.arrowTail],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,v),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(this._customMeshSet)return;let t=this._parent?.getAxisCache(this._gizmoMesh);if(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),t=this._parent?.getAxisCache(this._rootMesh),this._isHovered||(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh))),!this._parent){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(v.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(v.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}));const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes())}_createGizmoMesh(e,t,i=!1){const s=cd("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),r=$u("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return s.scaling.scaleInPlace(.1),s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,s.position.z+=.3,r.material=this._coloredMaterial,r.position.z+=.1375,r.rotation.x=Math.PI/2,i&&(s.visibility=0,r.visibility=0),e.addChild(s),e.addChild(r),{arrowMesh:s,arrowTail:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}setCustomMesh(e,t=!1){super.setCustomMesh(e),t&&(this._rootMesh.getChildMeshes().forEach((e=>{e.material=this._coloredMaterial,e.color&&(e.color=this._coloredMaterial.diffuseColor)})),this._customMeshSet=!1)}}tg.MinimumAbsoluteScale=J;class ig extends sd{set axisFactor(e){this._axisFactor=e;const t=this._scaleBoxesParent.getChildMeshes();let i=0;for(let e=0;e<3;e++)for(let s=0;s<3;s++)for(let r=0;r<3;r++){const n=(1===e?1:0)+(1===s?1:0)+(1===r?1:0);if(1!==n&&3!==n){if(t[i]){const n=new _e(e-1,s-1,r-1);n.multiplyInPlace(this._axisFactor),t[i].setEnabled(n.lengthSquared()>J)}i++}}}get axisFactor(){return this._axisFactor}set scaleDragSpeed(e){this._scaleDragSpeed=e}get scaleDragSpeed(){return this._scaleDragSpeed}get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverColoredMaterial}get pointerDragBehavior(){return this._pointerDragBehavior}get isDragging(){return this._dragging||this._pointerDragBehavior.dragging}setColor(e){this._coloredMaterial.emissiveColor=e,this._hoverColoredMaterial.emissiveColor=e.clone().add(new Ee(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach((t=>{t.color&&(t.color=e)}))}constructor(e=Ee.Gray(),t=Ju.DefaultKeepDepthUtilityLayer){super(t),this._boundingDimensions=new _e(1,1,1),this._renderObserver=null,this._pointerObserver=null,this._scaleDragSpeed=.2,this._rotateSpheresDragBehaviors=[],this._scaleBoxesDragBehaviors=[],this._dragging=!1,this._tmpQuaternion=new fe,this._tmpVector=new _e(0,0,0),this._tmpRotationMatrix=new me,this._incrementalStartupValue=_e.Zero(),this._incrementalAnchorStartupValue=_e.Zero(),this.ignoreChildren=!1,this.includeChildPredicate=null,this.rotationSphereSize=.1,this.scaleBoxSize=.1,this.fixedDragMeshScreenSize=!1,this.fixedDragMeshBoundsSize=!1,this.fixedDragMeshScreenSizeDistanceFactor=10,this.scalingSnapDistance=0,this.rotationSnapDistance=0,this.onDragStartObservable=new K,this.onScaleBoxDragObservable=new K,this.onScaleBoxDragEndObservable=new K,this.onRotationSphereDragObservable=new K,this.onRotationSphereDragEndObservable=new K,this.scalePivot=null,this._axisFactor=new _e(1,1,1),this.incrementalSnap=!1,this._existingMeshScale=new _e,this._dragMesh=null,this._pointerDragBehavior=new Xa,this.updateScale=!1,this._anchorMesh=new _o("anchor",t.utilityLayerScene),this._coloredMaterial=new cu("",t.utilityLayerScene),this._coloredMaterial.disableLighting=!0,this._hoverColoredMaterial=new cu("",t.utilityLayerScene),this._hoverColoredMaterial.disableLighting=!0,this._lineBoundingBox=new _o("",t.utilityLayerScene),this._lineBoundingBox.rotationQuaternion=new fe;const i=[];i.push(Ud("lines",{points:[new _e(0,0,0),new _e(this._boundingDimensions.x,0,0)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(0,0,0),new _e(0,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(0,0,0),new _e(0,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(this._boundingDimensions.x,0,0),new _e(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(this._boundingDimensions.x,0,0),new _e(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(0,this._boundingDimensions.y,0),new _e(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(0,this._boundingDimensions.y,0),new _e(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(0,0,this._boundingDimensions.z),new _e(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(0,0,this._boundingDimensions.z),new _e(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new _e(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new _e(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new _e(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.forEach((t=>{t.color=e,t.position.addInPlace(new _e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),t.isPickable=!1,this._lineBoundingBox.addChild(t)})),this._rootMesh.addChild(this._lineBoundingBox),this.setColor(e),this._rotateSpheresParent=new _o("",t.utilityLayerScene),this._rotateSpheresParent.rotationQuaternion=new fe;for(let e=0;e<12;e++){const i=_d("",{diameter:1},t.utilityLayerScene);i.rotationQuaternion=new fe,i.material=this._coloredMaterial,i.isNearGrabbable=!0;const s=new Xa({});s.moveAttached=!1,s.updateDragPlane=!1,i.addBehavior(s);const r=new _e(1,0,0);let n=0,o=0;s.onDragStartObservable.add((()=>{r.copyFrom(i.forward),n=0,o=0})),s.onDragObservable.add((t=>{if(this.onRotationSphereDragObservable.notifyObservers({}),this.attachedMesh){const i=this.attachedMesh.parent;if(i&&i.scaling&&i.scaling.isNonUniformWithinEpsilon(.001))return void Ne.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");Ga._RemoveAndStorePivotPoint(this.attachedMesh);const s=r,a=t.dragPlaneNormal.scale(_e.Dot(t.dragPlaneNormal,s)),l=s.subtract(a).normalizeToNew();let h=_e.Dot(l,t.delta)<0?Math.abs(t.delta.length()):-Math.abs(t.delta.length());if(h=h/this._boundingDimensions.length()*this._anchorMesh.scaling.length(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=fe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=fe.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),n+=h,Math.abs(n)<=2*Math.PI){if(this.rotationSnapDistance>0){const e=Math.floor(Math.abs(n)/this.rotationSnapDistance)*(n<0?-1:1),t=this.rotationSnapDistance*e;h=t-o,o=t}e>=8?fe.RotationYawPitchRollToRef(0,0,h,this._tmpQuaternion):e>=4?fe.RotationYawPitchRollToRef(h,0,0,this._tmpQuaternion):fe.RotationYawPitchRollToRef(0,h,0,this._tmpQuaternion),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.copyFrom(this.attachedMesh.position),this._anchorMesh.addChild(this.attachedMesh),this._anchorMesh.getScene().useRightHandedSystem&&this._tmpQuaternion.conjugateInPlace(),this._tmpQuaternion.normalize(),this._anchorMesh.rotationQuaternion.multiplyToRef(this._tmpQuaternion,this._anchorMesh.rotationQuaternion),this._anchorMesh.rotationQuaternion.normalize(),this._anchorMesh.removeChild(this.attachedMesh),this.attachedMesh.setParent(i)}this.updateBoundingBox(),Ga._RestorePivotPoint(this.attachedMesh)}this._updateDummy()})),s.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({}),this._dragging=!0,this._selectNode(i)})),s.onDragEndObservable.add((e=>{this.onRotationSphereDragEndObservable.notifyObservers({}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(e.pointerInfo,i)})),this._rotateSpheresDragBehaviors.push(s),this._rotateSpheresParent.addChild(i)}this._rootMesh.addChild(this._rotateSpheresParent),this._scaleBoxesParent=new _o("",t.utilityLayerScene),this._scaleBoxesParent.rotationQuaternion=new fe;for(let e=0;e<3;e++)for(let i=0;i<3;i++)for(let s=0;s<3;s++){const r=(1===e?1:0)+(1===i?1:0)+(1===s?1:0);if(1===r||3===r)continue;const n=cd("",{size:1},t.utilityLayerScene);n.material=this._coloredMaterial,n._internalMetadata=2===r,n.isNearGrabbable=!0;const o=new _e(e-1,i-1,s-1).normalize(),a=new Xa({dragAxis:o});a.updateDragPlane=!1,a.moveAttached=!1;let l=0,h=0;n.addBehavior(a),a.onDragObservable.add((e=>{if(this.onScaleBoxDragObservable.notifyObservers({}),this.attachedMesh){const t=this.attachedMesh.parent;if(t&&t.scaling&&t.scaling.isNonUniformWithinEpsilon(.001))return void Ne.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");Ga._RemoveAndStorePivotPoint(this.attachedMesh);let i=e.dragDistance/this._boundingDimensions.length()*this._anchorMesh.scaling.length();if(l+=i,this.scalingSnapDistance>0){const e=Math.floor(Math.abs(l)/this.scalingSnapDistance)*(l<0?-1:1),t=this.scalingSnapDistance*e;i=t-h,h=t}const s=new _e(i,i,i),a=new _e(h,h,h);2===r&&(s.x*=Math.abs(o.x),s.y*=Math.abs(o.y),s.z*=Math.abs(o.z)),s.scaleInPlace(this._scaleDragSpeed),s.multiplyInPlace(this._axisFactor),a.scaleInPlace(this._scaleDragSpeed),a.multiplyInPlace(this._axisFactor),a.addInPlace(this._incrementalStartupValue),this.updateBoundingBox(),this.scalePivot?(this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(this._tmpRotationMatrix),this._boundingDimensions.scaleToRef(.5,this._tmpVector),_e.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this._boundingDimensions.multiplyToRef(this.scalePivot,this._tmpVector),_e.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.addInPlace(this._tmpVector)):(n.absolutePosition.subtractToRef(this._anchorMesh.position,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.subtractInPlace(this.attachedMesh.getPivotPoint())),this._anchorMesh.addChild(this.attachedMesh),this.incrementalSnap?(a.x/=Math.abs(this._incrementalStartupValue.x){this.onDragStartObservable.notifyObservers({}),this._dragging=!0,this._selectNode(n),l=0,h=0,this._incrementalStartupValue.copyFrom(this.attachedMesh.scaling),this._incrementalAnchorStartupValue.copyFrom(this._anchorMesh.scaling)})),a.onDragEndObservable.add((e=>{this.onScaleBoxDragEndObservable.notifyObservers({}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(e.pointerInfo,n)})),this._scaleBoxesParent.addChild(n),this._scaleBoxesDragBehaviors.push(a)}this._rootMesh.addChild(this._scaleBoxesParent);const s=[];this._pointerObserver=t.utilityLayerScene.onPointerObservable.add((e=>{s[e.event.pointerId]?e.pickInfo&&e.pickInfo.pickedMesh!=s[e.event.pointerId]&&(s[e.event.pointerId].material=this._coloredMaterial,delete s[e.event.pointerId],this._isHovered=!1):this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((t=>{e.pickInfo&&e.pickInfo.pickedMesh==t&&(s[e.event.pointerId]=t,t.material=this._hoverColoredMaterial,this._isHovered=!0)}))})),this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add((()=>{this.attachedMesh&&!this._existingMeshScale.equals(this.attachedMesh.scaling)?this.updateBoundingBox():(this.fixedDragMeshScreenSize||this.fixedDragMeshBoundsSize)&&(this._updateRotationSpheres(),this._updateScaleBoxes()),this._dragMesh&&this.attachedMesh&&this._pointerDragBehavior.dragging&&(this._lineBoundingBox.position.rotateByQuaternionToRef(this._rootMesh.rotationQuaternion,this._tmpVector),this.attachedMesh.setAbsolutePosition(this._dragMesh.position.add(this._tmpVector.scale(-1))))})),this.updateBoundingBox()}_attachedNodeChanged(e){if(e){this._anchorMesh.scaling.setAll(1),Ga._RemoveAndStorePivotPoint(e);const t=e.parent;this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),e.setParent(t),Ga._RestorePivotPoint(e),this.updateBoundingBox(),e.getChildMeshes(!1).forEach((e=>{e.markAsDirty("scaling")})),this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce((()=>{this._updateDummy()}))}}_selectNode(e){this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((t=>{t.isVisible=!e||t==e}))}_unhoverMeshOnTouchUp(e,t){e?.event instanceof PointerEvent&&"touch"===e?.event.pointerType&&(t.material=this._coloredMaterial)}getScaleBoxes(){return this._scaleBoxesParent.getChildMeshes()}updateBoundingBox(){if(this.attachedMesh){Ga._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=fe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=fe.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);const t=this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren,this.includeChildPredicate);t.max.subtractToRef(t.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((t.max.x+t.min.x)/2,(t.max.y+t.min.y)/2,(t.max.z+t.min.z)/2),this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this.attachedMesh.setParent(e)}this._updateRotationSpheres(),this._updateScaleBoxes(),this.attachedMesh&&(this._existingMeshScale.copyFrom(this.attachedMesh.scaling),Ga._RestorePivotPoint(this.attachedMesh))}_updateRotationSpheres(){const e=this._rotateSpheresParent.getChildMeshes();for(let t=0;t<3;t++)for(let i=0;i<2;i++)for(let s=0;s<2;s++){const r=4*t+2*i+s;if(0==t&&(e[r].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*i,this._boundingDimensions.z*s),e[r].position.addInPlace(new _e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(_e.Cross(e[r].position.normalizeToNew(),_e.Right()).normalizeToNew().add(e[r].position))),1==t&&(e[r].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y/2,this._boundingDimensions.z*s),e[r].position.addInPlace(new _e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(_e.Cross(e[r].position.normalizeToNew(),_e.Up()).normalizeToNew().add(e[r].position))),2==t&&(e[r].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y*s,this._boundingDimensions.z/2),e[r].position.addInPlace(new _e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(_e.Cross(e[r].position.normalizeToNew(),_e.Forward()).normalizeToNew().add(e[r].position))),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[r].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);const t=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[r].scaling.set(t,t,t)}else this.fixedDragMeshBoundsSize?e[r].scaling.set(this.rotationSphereSize*this._boundingDimensions.x,this.rotationSphereSize*this._boundingDimensions.y,this.rotationSphereSize*this._boundingDimensions.z):e[r].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}}_updateScaleBoxes(){const e=this._scaleBoxesParent.getChildMeshes();let t=0;for(let i=0;i<3;i++)for(let s=0;s<3;s++)for(let r=0;r<3;r++){const n=(1===i?1:0)+(1===s?1:0)+(1===r?1:0);if(1!==n&&3!==n){if(e[t])if(e[t].position.set(this._boundingDimensions.x*(i/2),this._boundingDimensions.y*(s/2),this._boundingDimensions.z*(r/2)),e[t].position.addInPlace(new _e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[t].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.globalPosition,this._tmpVector);const i=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[t].scaling.set(i,i,i)}else this.fixedDragMeshBoundsSize?e[t].scaling.set(this.scaleBoxSize*this._boundingDimensions.x,this.scaleBoxSize*this._boundingDimensions.y,this.scaleBoxSize*this._boundingDimensions.z):e[t].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize);t++}}}setEnabledRotationAxis(e){this._rotateSpheresParent.getChildMeshes().forEach(((t,i)=>{i<4?t.setEnabled(-1!=e.indexOf("x")):i<8?t.setEnabled(-1!=e.indexOf("y")):t.setEnabled(-1!=e.indexOf("z"))}))}setEnabledScaling(e,t=!1){this._scaleBoxesParent.getChildMeshes().forEach((i=>{let s=e;t&&!0===i._internalMetadata&&(s=!1),i.setEnabled(s)}))}_updateDummy(){this._dragMesh&&(this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()),this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling),this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion))}enableDragBehavior(){this._dragMesh=cd("dummy",{size:1},this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new fe,this._pointerDragBehavior.useObjectOrientationForDragging=!1,this._dragMesh.addBehavior(this._pointerDragBehavior)}releaseDrag(){this._scaleBoxesDragBehaviors.forEach((e=>{e.releaseDrag()})),this._rotateSpheresDragBehaviors.forEach((e=>{e.releaseDrag()})),this._pointerDragBehavior.releaseDrag()}dispose(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateSpheresParent.dispose(),this._scaleBoxesParent.dispose(),this._dragMesh&&this._dragMesh.dispose(),this._scaleBoxesDragBehaviors.length=0,this._rotateSpheresDragBehaviors.length=0,super.dispose()}static MakeNotPickableAndWrapInBoundingBox(e){const t=e=>{e.isPickable=!1,e.getChildMeshes().forEach((e=>{t(e)}))};t(e),e.rotationQuaternion||(e.rotationQuaternion=fe.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));const i=e.position.clone(),s=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);const r=cd("box",{size:1},e.getScene()),n=e.getHierarchyBoundingVectors();return n.max.subtractToRef(n.min,r.scaling),0===r.scaling.y&&(r.scaling.y=J),0===r.scaling.x&&(r.scaling.x=J),0===r.scaling.z&&(r.scaling.z=J),r.position.set((n.max.x+n.min.x)/2,(n.max.y+n.min.y)/2,(n.max.z+n.min.z)/2),e.addChild(r),e.rotationQuaternion.copyFrom(s),e.position.copyFrom(i),e.removeChild(r),r.addChild(e),r.visibility=0,r}setCustomMesh(){Ne.Error("Custom meshes are not supported on this gizmo")}}class sg extends sd{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}set rotationColor(e){this._rotationShaderMaterial.setColor3("rotationColor",e)}get disableMaterial(){return this._disableMaterial}constructor(e,t=Ee.Gray(),i=Ju.DefaultUtilityLayer,s=32,r=null,n=!1,o=1,a=Ee.Yellow(),l=Ee.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new K,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new _e,this._parent=r,this._coloredMaterial=new cu("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ee(.1,.1,.1)),this._hoverMaterial=new cu("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a,this._hoverMaterial.specularColor=a,this._disableMaterial=new cu("",i.utilityLayerScene),this._disableMaterial.diffuseColor=l,this._disableMaterial.alpha=.4,this._gizmoMesh=new ha("",i.utilityLayerScene);const{rotationMesh:h,collider:c}=this._createGizmoMesh(this._gizmoMesh,o,s);this._rotationDisplayPlane=Wa("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),$i.ShadersStore.rotationGizmoVertexShader=sg._RotationGizmoVertexShader,$i.ShadersStore.rotationGizmoFragmentShader=sg._RotationGizmoFragmentShader,this._rotationShaderMaterial=new Nd("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles","rotationColor"]}),this._rotationShaderMaterial.backFaceCulling=!1,this.rotationColor=a,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,sd.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new Xa({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=sg.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);const u=new _e,d=new me,_=new _e;let p=new _e;this.dragBehavior.onDragStartObservable.add((e=>{this.attachedNode&&(u.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(d),_e.TransformCoordinatesToRef(e.dragPlanePoint,d,u),this._angles.x=Math.atan2(u.y,u.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,u.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)}));const f={snapDistance:0};let m=0;const g=new me,v=new fe;this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const s=new _e(1,1,1),r=new fe(0,0,0,1),n=new _e(0,0,0);if(this.attachedNode.getWorldMatrix().decompose(s,r,n),!(Math.abs(Math.abs(s.x)-Math.abs(s.y))<=J&&Math.abs(Math.abs(s.x)-Math.abs(s.z))<=J)&&this.updateGizmoRotationToMatchAttachedMesh)return void Ne.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");r.normalize();const o=this.updateGizmoPositionToMatchAttachedMesh?n:this._rootMesh.absolutePosition,a=t.dragPlanePoint.subtract(o).normalize(),l=u.subtract(o).normalize(),h=_e.Cross(a,l),c=_e.Dot(a,l);let x=Math.atan2(h.length(),c)*this.sensitivity;_.copyFrom(e),p.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(r.toRotationMatrix(d),p=_e.TransformCoordinates(_,d));let b=!1;if(i.utilityLayerScene.activeCamera){const e=i.utilityLayerScene.activeCamera.position.subtract(o).normalize();_e.Dot(e,p)>0&&(_.scaleInPlace(-1),p.scaleInPlace(-1),b=!0)}_e.Dot(p,h)>0&&(x=-x),ve.Vector3[0].set(x,0,0),this.dragBehavior.validateDrag(ve.Vector3[0])||(x=0);let T=!1;if(0!=this.snapDistance)if(m+=x,Math.abs(m)>this.snapDistance){let e=Math.floor(Math.abs(m)/this.snapDistance);m<0&&(e*=-1),m%=this.snapDistance,x=this.snapDistance*e,T=!0}else x=0;const y=Math.sin(x/2);if(v.set(_.x*y,_.y*y,_.z*y,Math.cos(x/2)),g.determinant()>0){const e=new _e;v.toEulerAnglesToRef(e),fe.RotationYawPitchRollToRef(e.y,-e.x,-e.z,v)}if(this.updateGizmoRotationToMatchAttachedMesh)r.multiplyToRef(v,r),r.normalize(),me.ComposeToRef(s,r,n,this.attachedNode.getWorldMatrix());else{v.toRotationMatrix(ve.Matrix[0]);const e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(ve.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}u.copyFrom(t.dragPlanePoint),T&&(f.snapDistance=x,this.onSnapObservable.notifyObservers(f)),this._angles.y+=x,this.angle+=b?-x:x,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}}));const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const b={colliderMeshes:[c],gizmoMeshes:[h],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,b),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=sg.MaxDragAngle,this._isHovered=!(-1==b.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=b.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(b.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(b.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_createGizmoMesh(e,t,i){const s=wu("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);s.visibility=0;const r=wu("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return r.material=this._coloredMaterial,r.rotation.x=Math.PI/2,s.rotation.x=Math.PI/2,e.addChild(r,sd.PreserveScaling),e.addChild(s,sd.PreserveScaling),{rotationMesh:r,collider:s}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}sg.MaxDragAngle=9*Math.PI/20,sg._RotationGizmoVertexShader="\n precision highp float;\n attribute vec3 position;\n attribute vec2 uv;\n uniform mat4 worldViewProjection;\n varying vec3 vPosition;\n varying vec2 vUV;\n\n void main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n vUV = uv;\n }",sg._RotationGizmoFragmentShader="\n precision highp float;\n varying vec2 vUV;\n varying vec3 vPosition;\n uniform vec3 angles;\n uniform vec3 rotationColor;\n\n #define twopi 6.283185307\n\n void main(void) {\n vec2 uv = vUV - vec2(0.5);\n float angle = atan(uv.y, uv.x) + 3.141592;\n float delta = gl_FrontFacing ? angles.y : -angles.y;\n float begin = angles.x - delta * angles.z;\n float start = (begin < (begin + delta)) ? begin : (begin + delta);\n float end = (begin > (begin + delta)) ? begin : (begin + delta);\n float len = sqrt(dot(uv,uv));\n float opacity = 1. - step(0.5, len);\n\n float base = abs(floor(start / twopi)) * twopi;\n start += base;\n end += base;\n\n float intensity = 0.;\n for (int i = 0; i < 5; i++)\n {\n intensity += max(step(start, angle) - step(end, angle), 0.);\n angle += twopi;\n }\n gl_FragColor = vec4(rotationColor, min(intensity * 0.25, 0.8)) * opacity;\n }\n ";class rg extends sd{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}_checkBillboardTransform(){this._nodeAttached&&this._nodeAttached.billboardMode&&Ne.Log("Rotation Gizmo will not work with transforms in billboard mode.")}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t&&(t.sensitivity=e)}))}get sensitivity(){return this._sensitivity}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=Ju.DefaultUtilityLayer,t=32,i=!1,s=1,r,n){super(e),this.onDragStartObservable=new K,this.onDragObservable=new K,this.onDragEndObservable=new K,this._observables=[],this._sensitivity=1,this._gizmoAxisCache=new Map;const o=n&&n.xOptions&&n.xOptions.color?n.xOptions.color:Ee.Red().scale(.5),a=n&&n.yOptions&&n.yOptions.color?n.yOptions.color:Ee.Green().scale(.5),l=n&&n.zOptions&&n.zOptions.color?n.zOptions.color:Ee.Blue().scale(.5);this.xGizmo=new sg(new _e(1,0,0),o,e,t,this,i,s),this.yGizmo=new sg(new _e(0,1,0),a,e,t,this,i,s),this.zGizmo=new sg(new _e(0,0,1),l,e,t,this,i,s),this.additionalTransformNode=n?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((e=>{n&&null!=n.updateScale&&(e.updateScale=n.updateScale),e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,this.attachedNode=null,r?r.addToAxisCache(this._gizmoAxisCache):sd.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set updateGizmoRotationToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)}get updateGizmoRotationToMatchAttachedMesh(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.yGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.zGizmo.updateGizmoPositionToMatchAttachedMesh=e)}get updateGizmoPositionToMatchAttachedMesh(){return this.xGizmo.updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.anchorPoint=e}))}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.coordinatesMode=e}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this.xGizmo&&(this.xGizmo.snapDistance=e,this.yGizmo.snapDistance=e,this.zGizmo.snapDistance=e)}get snapDistance(){return this.xGizmo.snapDistance}set scaleRatio(e){this.xGizmo&&(this.xGizmo.scaleRatio=e,this.yGizmo.scaleRatio=e,this.zGizmo.scaleRatio=e)}get scaleRatio(){return this.xGizmo.scaleRatio}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag()}dispose(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose(),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)}))}setCustomMesh(){Ne.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")}}class ng extends sd{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreatePlane(e,t){const i=new lo("plane",e),s=Wa("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return s.material=t,s.parent=i,i}constructor(e,t=Ee.Gray(),i=Ju.DefaultUtilityLayer,s=null,r=Ee.Yellow(),n=Ee.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new K,this._isEnabled=!1,this._parent=null,this._dragging=!1,this._parent=s,this._coloredMaterial=new cu("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ee(.1,.1,.1)),this._hoverMaterial=new cu("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=r,this._disableMaterial=new cu("",i.utilityLayerScene),this._disableMaterial.diffuseColor=n,this._disableMaterial.alpha=.4,this._gizmoMesh=ng._CreatePlane(i.utilityLayerScene,this._coloredMaterial),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let o=0;const a=new _e,l={snapDistance:0};this.dragBehavior=new Xa({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add((e=>{if(this.attachedNode){if(0==this.snapDistance)this.attachedNode.getWorldMatrix().getTranslationToRef(ve.Vector3[0]),ve.Vector3[0].addToRef(e.delta,ve.Vector3[0]),this.dragBehavior.validateDrag(ve.Vector3[0])&&this.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z);else if(o+=e.dragDistance,Math.abs(o)>this.snapDistance){const t=Math.floor(Math.abs(o)/this.snapDistance);o%=this.snapDistance,e.delta.normalizeToRef(a),a.scaleInPlace(this.snapDistance*t),this.attachedNode.getWorldMatrix().getTranslationToRef(ve.Vector3[0]),ve.Vector3[0].addToRef(a,ve.Vector3[0]),this.dragBehavior.validateDrag(ve.Vector3[0])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(a.x,a.y,a.z),l.snapDistance=this.snapDistance*t,this.onSnapObservable.notifyObservers(l))}this._matrixChanged()}})),this.dragBehavior.onDragStartObservable.add((()=>{this._dragging=!0})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1}));const h=i._getSharedGizmoLight();h.includedOnlyMeshes=h.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const c={gizmoMeshes:this._gizmoMesh.getChildMeshes(),colliderMeshes:this._gizmoMesh.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,c),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this._isHovered=!(-1==c.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=c.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(c.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(c.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedNode=this._parent.attachedNode):this.attachedNode=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),super.dispose(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()}))}}class og extends sd{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.xPlaneGizmo.isHovered||this.yPlaneGizmo.isHovered||this.zPlaneGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.xPlaneGizmo.dragBehavior.dragging||this.yPlaneGizmo.dragBehavior.dragging||this.zPlaneGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=Ju.DefaultUtilityLayer,t=1,i,s){super(e),this._meshAttached=null,this._nodeAttached=null,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new K,this.onDragObservable=new K,this.onDragEndObservable=new K,this._planarGizmoEnabled=!1,this.xGizmo=new rd(new _e(1,0,0),Ee.Red().scale(.5),e,this,t),this.yGizmo=new rd(new _e(0,1,0),Ee.Green().scale(.5),e,this,t),this.zGizmo=new rd(new _e(0,0,1),Ee.Blue().scale(.5),e,this,t),this.xPlaneGizmo=new ng(new _e(1,0,0),Ee.Red().scale(.5),this.gizmoLayer,this),this.yPlaneGizmo=new ng(new _e(0,1,0),Ee.Green().scale(.5),this.gizmoLayer,this),this.zPlaneGizmo=new ng(new _e(0,0,1),Ee.Blue().scale(.5),this.gizmoLayer,this),this.additionalTransformNode=s?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((e=>{e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,i?i.addToAxisCache(this._gizmoAxisCache):sd.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set planarGizmoEnabled(e){this._planarGizmoEnabled=e,[this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.isEnabled=e,e&&(t.attachedMesh?t.attachedMesh=this.attachedMesh:t.attachedNode=this.attachedNode))}),this)}get planarGizmoEnabled(){return this._planarGizmoEnabled}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.updateGizmoPositionToMatchAttachedMesh=e)}))}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.anchorPoint=e}))}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.coordinatesMode=e}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.snapDistance=e)}))}get snapDistance(){return this._snapDistance}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.xPlaneGizmo.dragBehavior.releaseDrag(),this.yPlaneGizmo.dragBehavior.releaseDrag(),this.zPlaneGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((e=>{e&&e.dispose()})),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear()}setCustomMesh(){Ne.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)")}}class ag extends sd{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.uniformScaleGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.uniformScaleGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=Ju.DefaultUtilityLayer,t=1,i,s){super(e),this._meshAttached=null,this._nodeAttached=null,this._incrementalSnap=!1,this._sensitivity=1,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new K,this.onDragObservable=new K,this.onDragEndObservable=new K,this.uniformScaleGizmo=this._createUniformScaleMesh(),this.xGizmo=new tg(new _e(1,0,0),Ee.Red().scale(.5),e,this,t),this.yGizmo=new tg(new _e(0,1,0),Ee.Green().scale(.5),e,this,t),this.zGizmo=new tg(new _e(0,0,1),Ee.Blue().scale(.5),e,this,t),this.additionalTransformNode=s?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,this.attachedNode=null,i?i.addToAxisCache(this._gizmoAxisCache):sd.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}_createUniformScaleMesh(){this._coloredMaterial=new cu("",this.gizmoLayer.utilityLayerScene),this._coloredMaterial.diffuseColor=Ee.Gray(),this._hoverMaterial=new cu("",this.gizmoLayer.utilityLayerScene),this._hoverMaterial.diffuseColor=Ee.Yellow(),this._disableMaterial=new cu("",this.gizmoLayer.utilityLayerScene),this._disableMaterial.diffuseColor=Ee.Gray(),this._disableMaterial.alpha=.4;const e=new tg(new _e(0,1,0),Ee.Gray().scale(.5),this.gizmoLayer,this);e.updateGizmoRotationToMatchAttachedMesh=!1,e.uniformScaling=!0,this._uniformScalingMesh=o_("uniform",{type:1},e.gizmoLayer.utilityLayerScene),this._uniformScalingMesh.scaling.scaleInPlace(.01),this._uniformScalingMesh.visibility=0,this._octahedron=o_("",{type:1},e.gizmoLayer.utilityLayerScene),this._octahedron.scaling.scaleInPlace(.007),this._uniformScalingMesh.addChild(this._octahedron),e.setCustomMesh(this._uniformScalingMesh,!0);const t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._octahedron);const i={gizmoMeshes:[this._octahedron,this._uniformScalingMesh],colliderMeshes:[this._octahedron,this._uniformScalingMesh],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:e.dragBehavior};return this.addToAxisCache(e._rootMesh,i),e}set updateGizmoRotationToMatchAttachedMesh(e){e?(this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))):Ne.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.")}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.anchorPoint=e)}))}get anchorPoint(){return this._anchorPoint}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}set coordinatesMode(e){e==td.World&&Ne.Warn("Setting coordinates Mode to world on scaling gizmo is not supported."),[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e.coordinatesMode=td.Local}))}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.snapDistance=e)}))}get snapDistance(){return this._snapDistance}set incrementalSnap(e){this._incrementalSnap=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.incrementalSnap=e)}))}get incrementalSnap(){return this._incrementalSnap}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.sensitivity=e)}))}get sensitivity(){return this._sensitivity}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}getAxisCache(e){return this._gizmoAxisCache.get(e)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.uniformScaleGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e&&e.dispose()})),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),[this._uniformScalingMesh,this._octahedron].forEach((e=>{e&&e.dispose()})),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()}))}}class lg{get keepDepthUtilityLayer(){return this._defaultKeepDepthUtilityLayer}get utilityLayer(){return this._defaultUtilityLayer}get isHovered(){let e=!1;for(const t in this.gizmos){const i=this.gizmos[t];if(i&&i.isHovered){e=!0;break}}return e}get isDragging(){let e=!1;return[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach((t=>{t&&t.isDragging&&(e=!0)})),e}set scaleRatio(e){this._scaleRatio=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}set coordinatesMode(e){this._coordinatesMode=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach((t=>{t&&(t.coordinatesMode=e)}))}get coordinatesMode(){return this._coordinatesMode}get attachedMesh(){return this._attachedMesh}get attachedNode(){return this._attachedNode}get additionalTransformNode(){return this._additionalTransformNode}constructor(e,t=1,i=Ju.DefaultUtilityLayer,s=Ju.DefaultKeepDepthUtilityLayer){this._scene=e,this.clearGizmoOnEmptyPointerEvent=!1,this.enableAutoPicking=!0,this.onAttachedToMeshObservable=new K,this.onAttachedToNodeObservable=new K,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObservers=[],this._attachedMesh=null,this._attachedNode=null,this._boundingBoxColor=Ee.FromHexString("#0984e3"),this._thickness=1,this._scaleRatio=1,this._coordinatesMode=td.Local,this._gizmoAxisCache=new Map,this.boundingBoxDragBehavior=new ja,this.attachableMeshes=null,this.attachableNodes=null,this.usePointerToAttachGizmos=!0,this._defaultUtilityLayer=i,this._defaultKeepDepthUtilityLayer=s,this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,this._thickness=t,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};const r=this._attachToMeshPointerObserver(e),n=sd.GizmoAxisPointerObserver(this._defaultUtilityLayer,this._gizmoAxisCache);this._pointerObservers=[r,n]}_attachToMeshPointerObserver(e){return e.onPointerObservable.add((e=>{if(this.usePointerToAttachGizmos&&e.type==lr.POINTERDOWN)if(e.pickInfo&&e.pickInfo.pickedMesh){if(this.enableAutoPicking){let t=e.pickInfo.pickedMesh;if(null==this.attachableMeshes)for(;t&&null!=t.parent;)t=t.parent;else{let e=!1;this.attachableMeshes.forEach((i=>{t&&(t==i||t.isDescendantOf(i))&&(t=i,e=!0)})),e||(t=null)}t instanceof _o?this._attachedMesh!=t&&this.attachToMesh(t):this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}}else this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}))}attachToMesh(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=e,this._attachedNode=null;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedMesh=e)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToMeshObservable.notifyObservers(e)}attachToNode(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=null,this._attachedNode=e;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedNode=e)}this.boundingBoxGizmoEnabled&&this._attachedNode&&this._attachedNode.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToNodeObservable.notifyObservers(e)}set positionGizmoEnabled(e){e?(this.gizmos.positionGizmo||(this.gizmos.positionGizmo=new og(this._defaultUtilityLayer,this._thickness,this)),this._attachedNode?this.gizmos.positionGizmo.attachedNode=this._attachedNode:this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedNode=null),this._gizmosEnabled.positionGizmo=e,this._setAdditionalTransformNode()}get positionGizmoEnabled(){return this._gizmosEnabled.positionGizmo}set rotationGizmoEnabled(e){e?(this.gizmos.rotationGizmo||(this.gizmos.rotationGizmo=new rg(this._defaultUtilityLayer,32,!1,this._thickness,this)),this._attachedNode?this.gizmos.rotationGizmo.attachedNode=this._attachedNode:this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedNode=null),this._gizmosEnabled.rotationGizmo=e,this._setAdditionalTransformNode()}get rotationGizmoEnabled(){return this._gizmosEnabled.rotationGizmo}set scaleGizmoEnabled(e){e?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new ag(this._defaultUtilityLayer,this._thickness,this),this._attachedNode?this.gizmos.scaleGizmo.attachedNode=this._attachedNode:this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedNode=null),this._gizmosEnabled.scaleGizmo=e,this._setAdditionalTransformNode()}get scaleGizmoEnabled(){return this._gizmosEnabled.scaleGizmo}set boundingBoxGizmoEnabled(e){e?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new ig(this._boundingBoxColor,this._defaultKeepDepthUtilityLayer),this._attachedMesh?this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh:this.gizmos.boundingBoxGizmo.attachedNode=this._attachedNode,this._attachedMesh?(this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh.addBehavior(this.boundingBoxDragBehavior)):this._attachedNode&&(this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode.addBehavior(this.boundingBoxDragBehavior))):this.gizmos.boundingBoxGizmo&&(this._attachedMesh?this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior):this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this.gizmos.boundingBoxGizmo.attachedNode=null),this._gizmosEnabled.boundingBoxGizmo=e,this._setAdditionalTransformNode()}get boundingBoxGizmoEnabled(){return this._gizmosEnabled.boundingBoxGizmo}set additionalTransformNode(e){this._additionalTransformNode=e,this._setAdditionalTransformNode()}_setAdditionalTransformNode(){for(const e in this.gizmos){const t=this.gizmos[e];t&&this._gizmosEnabled[e]&&(t.additionalTransformNode=this._additionalTransformNode)}}addToAxisCache(e){e.size>0&&e.forEach(((e,t)=>{this._gizmoAxisCache.set(t,e)}))}releaseDrag(){[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach((e=>{e?.releaseDrag()}))}dispose(){this._pointerObservers.forEach((e=>{this._scene.onPointerObservable.remove(e)}));for(const e in this.gizmos){const t=this.gizmos[e];t&&t.dispose()}this._defaultKeepDepthUtilityLayer!==Ju._DefaultKeepDepthUtilityLayer&&this._defaultKeepDepthUtilityLayer?.dispose(),this._defaultUtilityLayer!==Ju._DefaultUtilityLayer&&this._defaultUtilityLayer?.dispose(),this.boundingBoxDragBehavior.detach(),this.onAttachedToMeshObservable.clear()}}class hg extends ua{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=me.Identity(),this._projectionMatrix=me.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return!(!this.parent||!this.parent.getWorldMatrix||(this.transformedPosition||(this.transformedPosition=_e.Zero()),_e.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=_e.Zero()),_e.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),0))}getDepthScale(){return 50}getShadowDirection(e){return this.transformedDirection?this.transformedDirection:this.direction}getAbsolutePosition(){return this.transformedPosition?this.transformedPosition:this.position}setDirectionToTarget(e){return this.direction=_e.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=_e.Cross(this.direction,Xr.Y),t=_e.Cross(e,this.direction);return _e.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=_e.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=me.Identity()),me.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),this.parent&&this.parent.getWorldMatrix||(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){const t=ve.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),_e.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(_e.Dot(t,_e.Up()))&&(t.z=1e-13);const s=ve.Vector3[1];return i.addToRef(t,s),me.LookAtLHToRef(i,s,_e.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}Ze([ht()],hg.prototype,"position",null),Ze([ht()],hg.prototype,"direction",null),Ze([rt()],hg.prototype,"shadowMinZ",null),Ze([rt()],hg.prototype,"shadowMaxZ",null),Et.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new cg(e,_e.Zero(),t)));class cg extends hg{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,i){super(e,i),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return ua.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){const t=this.getScene().activeCamera;t&&me.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=_e.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let s=Number.MAX_VALUE,r=-Number.MAX_VALUE;for(let n=0;nthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zr&&(r=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=s,this._shadowMaxZ=r)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,o=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;me.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,l?a:o,l?o:a,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}function ug(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);const s=_d("",{slice:.5,diameter:t.diameter,segments:t.segments},i),r=yd("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);r.rotation.x=-Math.PI/2,r.parent=s;const n=ha.MergeMeshes([r,s],!0);return n.name=e,n}Ze([rt()],cg.prototype,"shadowFrustumSize",null),Ze([rt()],cg.prototype,"shadowOrthoScale",null),Ze([rt()],cg.prototype,"autoUpdateExtends",void 0),Ze([rt()],cg.prototype,"autoCalcShadowZBounds",void 0),Ze([rt("orthoLeft")],cg.prototype,"_orthoLeft",void 0),Ze([rt("orthoRight")],cg.prototype,"_orthoRight",void 0),Ze([rt("orthoTop")],cg.prototype,"_orthoTop",void 0),Ze([rt("orthoBottom")],cg.prototype,"_orthoBottom",void 0),z("BABYLON.DirectionalLight",cg);const dg={CreateHemisphere:ug};ha.CreateHemisphere=(e,t,i,s)=>ug(e,{segments:t,diameter:i},s),Et.AddNodeConstructor("Light_Type_2",((e,t)=>()=>new _g(e,_e.Zero(),_e.Zero(),0,0,t)));class _g extends hg{get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(.5*e),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()}get innerAngle(){return this._innerAngle}set innerAngle(e){this._innerAngle=e,this._computeAngleValues()}get shadowAngleScale(){return this._shadowAngleScale}set shadowAngleScale(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()}get projectionTextureMatrix(){return this._projectionTextureMatrix}get projectionTextureLightNear(){return this._projectionTextureLightNear}set projectionTextureLightNear(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureLightFar(){return this._projectionTextureLightFar}set projectionTextureLightFar(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureUpDirection(){return this._projectionTextureUpDirection}set projectionTextureUpDirection(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0}get projectionTexture(){return this._projectionTexture}set projectionTexture(e){this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(_g._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((()=>{this._markMeshesAsLightDirty()})):_g._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce((()=>{this._markMeshesAsLightDirty()}))))}static _IsProceduralTexture(e){return void 0!==e.onGeneratedObservable}static _IsTexture(e){return void 0!==e.onLoadObservable}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,s,r,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=me.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=_e.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=_e.Zero(),this._projectionTextureViewLightMatrix=me.Zero(),this._projectionTextureProjectionLightMatrix=me.Zero(),this._projectionTextureScalingMatrix=me.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=s,this.exponent=r}getClassName(){return"SpotLight"}getTypeID(){return ua.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;this._shadowAngleScale=this._shadowAngleScale||1;const r=this._shadowAngleScale*this._angle,n=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;me.PerspectiveFovLHToRef(r,1,a?o:n,a?n:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,a)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),me.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),s=-i*t,r=1/Math.tan(this._angle/2);me.FromValuesToRef(r/1,0,0,0,0,r,0,0,0,0,i,1,0,0,s,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof Pa){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;me.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}_computeAngleValues(){this._lightAngleScale=1/Math.max(.001,Math.cos(.5*this._innerAngle)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightTexture"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=_e.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=_e.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return i=this.computeTransformedInformation()?_e.Normalize(this.transformedDirection):_e.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!(!this.projectionTexture||!this.projectionTexture.isReady())}}Ze([rt()],_g.prototype,"angle",null),Ze([rt()],_g.prototype,"innerAngle",null),Ze([rt()],_g.prototype,"shadowAngleScale",null),Ze([rt()],_g.prototype,"exponent",void 0),Ze([rt()],_g.prototype,"projectionTextureLightNear",null),Ze([rt()],_g.prototype,"projectionTextureLightFar",null),Ze([rt()],_g.prototype,"projectionTextureUpDirection",null),Ze([nt("projectedLightTexture")],_g.prototype,"_projectionTexture",void 0),z("BABYLON.SpotLight",_g);class pg extends sd{constructor(e=Ju.DefaultUtilityLayer){super(e),this._cachedPosition=new _e,this._cachedForward=new _e(0,0,1),this._pointerObserver=null,this.onClickedObservable=new K,this._light=null,this.attachedMesh=new _o("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new lo("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new cu("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new Ee(.5,.5,.5),this._material.specularColor=new Ee(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._light&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._light))}),lr.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){Ne.Warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),this._lightMesh=e instanceof Zu?pg._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof cg?pg._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof _g?pg._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):pg._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._lightMesh.parent=this._rootMesh;const t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new fe,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction){this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0);const t=this._getMeshForward();this._cachedForward.copyFrom(t)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(ve.Vector3[0]),e=ve.Vector3[0]),e}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position)if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{const e=this.attachedMesh.position;this._light.position=new _e(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction){const e=this._getMeshForward();if(_e.DistanceSquared(e,this._cachedForward)>1e-4){const t=e;this._light.direction=new _e(t.x,t.y,t.z),this._cachedForward.copyFrom(e)}else _e.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){const t=new ha("hemisphereLight",e),i=ug(t.name,{segments:10,diameter:1},e);return i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(3,e).parent=t,t.scaling.scaleInPlace(pg._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){const t=new ha("pointLight",e),i=_d(t.name,{segments:10,diameter:1},e);return i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(5,e).parent=t,t.scaling.scaleInPlace(pg._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){const t=new ha("spotLight",e);_d(t.name,{segments:10,diameter:1},e).parent=t;const i=ug(t.name,{segments:10,diameter:2},e);return i.parent=t,i.rotation.x=-Math.PI/2,this._CreateLightLines(2,e).parent=t,t.scaling.scaleInPlace(pg._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){const t=new ha("directionalLight",e),i=new ha(t.name,e);i.parent=t,_d(t.name,{diameter:1.2,segments:10},e).parent=i;const s=$u(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);s.parent=i;let r=s.clone(t.name);r.scaling.y=.5,r.position.x+=1.25;let n=s.clone(t.name);n.scaling.y=.5,n.position.x+=-1.25;const o=$u(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,r=o.clone(t.name),r.position.y=1.5,r.position.x+=1.25,n=o.clone(t.name),n.position.y=1.5,n.position.x+=-1.25,i.scaling.scaleInPlace(pg._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}pg._Scale=.007,pg._CreateLightLines=(e,t)=>{const i=new ha("root",t);i.rotation.x=Math.PI/2;const s=new ha("linePivot",t);s.parent=i;const r=$u("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(r.position.y=r.scaling.y/2+1.2,r.parent=s,e<2)return s;for(let e=0;e<4;e++){const t=s.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){const t=s.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){const t=s.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}return e<5||(s.clone("linePivotClone").rotation.z=Math.PI),i};class fg extends sd{constructor(e=Ju.DefaultUtilityLayer,t,i){super(e),this._pointerObserver=null,this.onClickedObservable=new K,this._camera=null,this._invProjection=new me,this._material=new cu("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._frustumLinesColor=i,this._material.diffuseColor=t??new Ee(.5,.5,.5),this._material.specularColor=new Ee(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._camera&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._camera))}),lr.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){if(this._camera=e,this.attachedNode=e,e){this._customMeshSet||(this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=fg._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._cameraMesh.parent=this._rootMesh),this._cameraLinesMesh&&this._cameraLinesMesh.dispose();const t=this._frustumLinesColor?.toColor4(1)??new Ae(1,1,1,1);this._cameraLinesMesh=fg._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene,t),this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;const i=this.gizmoLayer._getSharedGizmoLight();i.includedOnlyMeshes=i.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}}get camera(){return this._camera}get material(){return this._material}_update(){super._update(),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=e,this._cameraMesh.parent=this._rootMesh,this._customMeshSet=!0}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),super.dispose()}static _CreateCameraMesh(e){const t=new ha("rootCameraGizmo",e),i=new ha(t.name,e);i.parent=t,cd(t.name,{width:1,height:.8,depth:.5},e).parent=i;const s=$u(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);s.parent=i,s.position.y=.3,s.position.x=-.6,s.rotation.x=.5*Math.PI;const r=$u(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);r.parent=i,r.position.y=.5,r.position.x=.4,r.rotation.x=.5*Math.PI;const n=$u(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return n.parent=i,n.position.y=0,n.position.x=.6,n.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(fg._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e,t){const i=new ha("rootCameraGizmo",e),s=new ha(i.name,e);s.parent=i;for(let i=0;i<4;i+=2)for(let r=0;r<4;r+=2){let n=Ud("lines",{points:[new _e(-1+r,-1+i,-1),new _e(-1+r,-1+i,1)],colors:[t,t]},e);n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Ud("lines",{points:[new _e(-1,-1+r,-1+i),new _e(1,-1+r,-1+i)],colors:[t,t]},e),n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Ud("lines",{points:[new _e(-1+r,-1,-1+i),new _e(-1+r,1,-1+i)],colors:[t,t]},e),n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1}return i}}fg._Scale=.05;Bi.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";Bi.IncludesShadersStore.packingFunctions="vec4 pack(float depth)\n{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}";Bi.IncludesShadersStore.kernelBlurFragment="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif\n";Bi.IncludesShadersStore.kernelBlurFragment2="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";Bi.ShadersStore.kernelBlurPixelShader="uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";Bi.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";Bi.ShadersStore.kernelBlurVertexShader="attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class mg extends Vl{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,s,r,n=Pa.BILINEAR_SAMPLINGMODE,o,a,l=0,h="",c=!1,u=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],s,r,n,o,a,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,u),this._blockCompilation=c,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add((e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)})),this.kernel=i}updateEffect(e=null,t=null,i=null,s,r,n){this._updateParameters(r,n)}_updateParameters(e,t){const i=this._kernel,s=(i-1)/2;let r=[],n=[],o=0;for(let e=0;e0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){const t=1/3,i=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(i)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,s){return St.Parse((()=>new mg(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)),e,i,s)}}Ze([rt("kernel")],mg.prototype,"_kernel",void 0),Ze([rt("packedFloat")],mg.prototype,"_packedFloat",void 0),Ze([lt()],mg.prototype,"direction",void 0),z("BABYLON.BlurPostProcess",mg);class gg extends ih{set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){const e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){const e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,s,r=0,n=Pa.BILINEAR_SAMPLINGMODE,o=!0){if(super(e,t,i,s,!0,r,!1,n,o),this.mirrorPlane=new Nr(0,1,0,1),this._transformMatrix=me.Zero(),this._mirrorMatrix=me.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateGammaSpace()}));const a=i.getEngine();let l;a.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add((()=>{a._debugPushGroup?.(`mirror generation for ${e}`,1)})),this.onAfterUnbindObservable.add((()=>{a._debugPopGroup?.(1)})),this.onBeforeRenderObservable.add((()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),me.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),l=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=_e.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)})),this.onAfterRenderObservable.add((()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=l}))}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){const e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new mg("horizontal blur",new de(1,0),this._blurKernelX,this._blurRatio,null,Pa.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new mg("vertical blur",new de(0,1),this._blurKernelY,this._blurRatio,null,Pa.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new gg(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){super.dispose();const e=this.getScene();e&&e.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),this._sceneUBO?.dispose()}}Pa._CreateMirror=(e,t,i,s)=>new gg(e,t,i,s);class vg extends ya{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(me.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let s="";return e.forEach((e=>s+=e)),new vg(s,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,s=!0){const r=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const n=new vg(e,t,null,!1,null,null,null,void 0,!0,i,s);return t.useDelayedTextureLoading=r,n}constructor(e,t,i=null,s=!1,r=null,n=null,o=null,a=5,l=!1,h=null,c=!1,u=.8,d=0,_,p){super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new K,this.boundingBoxPosition=_e.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new me,this.name=e,this.url=e,this._noMipmap=s,this.hasAlpha=!1,this._format=a,this.isCube=!0,this._textureMatrix=me.Identity(),this._createPolynomials=c,this.coordinatesMode=Pa.CUBIC_MODE,this._extensions=i,this._files=r,this._forcedExtension=h,this._loaderOptions=_,this._useSRGBBuffer=p,this._lodScale=u,this._lodOffset=d,(e||r)&&this.updateURL(e,h,n,l,o,i,this.getScene()?.useDelayedTextureLoading,r)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,s=!1,r=null,n=null,o=!1,a=null){this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,t&&(this._forcedExtension=t);const l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),c=0===h.indexOf(".dds"),u=0===h.indexOf(".env"),d=0===h.indexOf(".basis");if(u?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=s,s&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),a)this._files=a;else if(d||u||c||n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,n){for(let t=0;t-1!==e.getActiveTextures().indexOf(this))),this._textureMatrix=e,!this.getScene()?.useRightHandedSystem)return;const t=ve.Vector3[0],i=ve.Quaternion[0],s=ve.Vector3[1];this._textureMatrix.decompose(t,i,s),i.z*=-1,i.w*=-1,me.ComposeToRef(t,i,s,this._textureMatrixRefraction)}getRefractionTextureMatrix(){return this.getScene()?.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){const i=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const r=()=>{this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),this.getScene()?.markAllMaterialsAsDirty(1)),e&&e()},n=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),Pa.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Ds.SetImmediate((()=>r())):this._texture.onLoadedObservable.add((()=>r())):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,i,this._lodScale,this._lodOffset,e,n,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,i,this._files,this._noMipmap,e,n,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),this._texture?.onLoadedObservable.add((()=>this.onLoadObservable.notifyObservers(this))))}static Parse(e,t,i){const s=St.Parse((()=>{let s=!1;return e.prefiltered&&(s=e.prefiltered),new vg(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(s.boundingBoxPosition=_e.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=_e.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t{const t=new vg(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}Ze([rt()],vg.prototype,"url",void 0),Ze([ht()],vg.prototype,"boundingBoxPosition",void 0),Ze([ht()],vg.prototype,"boundingBoxSize",null),Ze([rt("rotationY")],vg.prototype,"rotationY",null),Ze([rt("files")],vg.prototype,"_files",void 0),Ze([rt("forcedExtension")],vg.prototype,"_forcedExtension",void 0),Ze([rt("extensions")],vg.prototype,"_extensions",void 0),Ze([ft("textureMatrix")],vg.prototype,"_textureMatrix",void 0),Ze([ft("textureMatrixRefraction")],vg.prototype,"_textureMatrixRefraction",void 0),Pa._CubeTextureParser=vg.Parse,z("BABYLON.CubeTexture",vg);Bi.IncludesShadersStore.backgroundFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;uniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef PROJECTED_GROUND\nuniform vec2 projectedGroundInfos;\n#endif\n";Bi.IncludesShadersStore.backgroundUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;};\n#include\n";Bi.ShadersStore.backgroundPixelShader="#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#include\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#ifdef PROJECTED_GROUND\nfloat diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; }\nvec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q)\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\nfloat shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.;\n#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n#ifndef BACKMAT_SHADOWONLY\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\n#ifdef PROJECTED_GROUND\nvec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.));\n#else\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);} else {reflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\nvec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor;\n#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\nvec4 color=vec4(finalColor,finalAlpha);\n#else\nvec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);\n#endif\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#endif\n#else\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Bi.IncludesShadersStore.backgroundVertexDeclaration="uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";Bi.ShadersStore.backgroundVertexShader="precision highp float;\n#include<__decl__backgroundVertex>\n#include\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vec2 vDiffuseUV;\n#endif\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif\n#include\n#include\n#include\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);}\n#else\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#endif\nvec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class xg extends xl{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.PROJECTED_GROUND=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}}class bg extends ml{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t*=2,this.reflectionReflectance0=bg.StandardReflectance0*t,this.reflectionReflectance90=bg.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=bg.StandardReflectance0+(1-bg.StandardReflectance0)*t,this.reflectionReflectance90=bg.StandardReflectance90+(1-bg.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()}))))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.primaryColor=Ee.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=_e.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._enableGroundProjection=!1,this.enableGroundProjection=!1,this.projectedGroundRadius=1e3,this.projectedGroundHeight=10,this._renderTargets=new Fs(16),this._reflectionControls=pe.Zero(),this._white=Ee.White(),this._primaryShadowColor=Ee.Black(),this._primaryHighlightColor=Ee.Black(),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!(!this._diffuseTexture||!this._diffuseTexture.isRenderTarget)||!(!this._reflectionTexture||!this._reflectionTexture.isRenderTarget)}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new xg);const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(zo(r,e,n,!1,this._maxSimultaneousLights),n._needNormals=!0,Ko(r,n),n._areTexturesDirty){if(n._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(n.TEXTURELODSUPPORT=!0),this._diffuseTexture&&$c.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;Mo(this._diffuseTexture,n,"DIFFUSE"),n.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,n.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,n.OPACITYFRESNEL=this._opacityFresnel}else n.DIFFUSE=!1,n.DIFFUSEDIRECTUV=0,n.DIFFUSEHASALPHA=!1,n.GAMMADIFFUSE=!1,n.OPACITYFRESNEL=!1;const e=this._reflectionTexture;if(e&&$c.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(n.REFLECTION=!0,n.GAMMAREFLECTION=e.gammaSpace,n.RGBDREFLECTION=e.isRGBD,n.REFLECTIONBLUR=this._reflectionBlur>0,n.LODINREFLECTIONALPHA=e.lodLevelInAlpha,n.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,n.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===Pa.INVCUBIC_MODE&&(n.INVERTCUBICMAP=!0),n.REFLECTIONMAP_3D=e.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case Pa.EXPLICIT_MODE:n.REFLECTIONMAP_EXPLICIT=!0;break;case Pa.PLANAR_MODE:n.REFLECTIONMAP_PLANAR=!0;break;case Pa.PROJECTION_MODE:n.REFLECTIONMAP_PROJECTION=!0;break;case Pa.SKYBOX_MODE:n.REFLECTIONMAP_SKYBOX=!0;break;case Pa.SPHERICAL_MODE:n.REFLECTIONMAP_SPHERICAL=!0;break;case Pa.EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Pa.FIXED_EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Pa.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Pa.CUBIC_MODE:case Pa.INVCUBIC_MODE:default:n.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(n.REFLECTIONFRESNEL=!0,n.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1)}else n.REFLECTION=!1,n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1,n.REFLECTIONBLUR=!1,n.REFLECTIONMAP_3D=!1,n.REFLECTIONMAP_SPHERICAL=!1,n.REFLECTIONMAP_PLANAR=!1,n.REFLECTIONMAP_CUBIC=!1,n.REFLECTIONMAP_PROJECTION=!1,n.REFLECTIONMAP_SKYBOX=!1,n.REFLECTIONMAP_EXPLICIT=!1,n.REFLECTIONMAP_EQUIRECTANGULAR=!1,n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,n.INVERTCUBICMAP=!1,n.REFLECTIONMAP_OPPOSITEZ=!1,n.LODINREFLECTIONALPHA=!1,n.GAMMAREFLECTION=!1,n.RGBDREFLECTION=!1}n.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,n.USERGBCOLOR=this._useRGBColor,n.NOISE=this._enableNoise}if(n._areLightsDirty&&(n.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),n.BACKMAT_SHADOWONLY=this._shadowOnly),n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n)}if(n._areMiscDirty&&(n.REFLECTIONMAP_3D&&this._enableGroundProjection?(n.PROJECTED_GROUND=!0,n.REFLECTIONMAP_SKYBOX=!0):n.PROJECTED_GROUND=!1),Go(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),Ho(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),jo(e,n,!1,!0,!1)&&e&&(r.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(er.NormalKind)||(e.createNormals(!0),Ne.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),n.isDirty){n.markAsProcessed(),r.resetCachedMaterial();const i=new Ll;n.FOG&&i.addFallback(0,"FOG"),n.POINTSIZE&&i.addFallback(1,"POINTSIZE"),n.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),Vo(n,i,this._maxSimultaneousLights);const s=[er.PositionKind];n.NORMAL&&s.push(er.NormalKind),n.UV1&&s.push(er.UVKind),n.UV2&&s.push(er.UV2Kind),Bo(s,e,n,i),ko(s,n);const a=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];mo(a);const l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];zs&&(zs.PrepareUniforms(a,n),zs.PrepareSamplers(l,n)),ea({uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:n,maxSimultaneousLights:this._maxSimultaneousLights});const c=n.toString(),u=r.getEngine().createEffect("background",{attributes:s,uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:c,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o);t.setEffect(u,n,this._materialContext),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady()||(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),wo(t,this._activeEffect);const o=this._mustRebind(s,n,i,t.visibility);if(o){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);const e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync&&!i._drawWrapper._forceRebindOnNextCall||(s.texturesEnabled&&(this._diffuseTexture&&$c.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Oo(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&$c.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),r.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),s.texturesEnabled&&(this._diffuseTexture&&$c.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&$c.ReflectionTextureEnabled&&(r.REFLECTIONBLUR&&r.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):r.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),r.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),r.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),xo(this._activeEffect,this,s),s.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);!o&&this.isFrozen||(s.lightsEnabled&&Lo(s,t,this._activeEffect,r,this._maxSimultaneousLights),this.bindView(n),Co(s,t,this._activeEffect,!0),this._useLogarithmicDepth&&So(r,n,s),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return St.Clone((()=>new bg(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return St.Parse((()=>new bg(e.name,t)),e,t,i)}}bg.StandardReflectance0=.05,bg.StandardReflectance90=.5,Ze([ot()],bg.prototype,"_primaryColor",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],bg.prototype,"primaryColor",void 0),Ze([ot()],bg.prototype,"__perceptualColor",void 0),Ze([rt()],bg.prototype,"_primaryColorShadowLevel",void 0),Ze([rt()],bg.prototype,"_primaryColorHighlightLevel",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],bg.prototype,"primaryColorHighlightLevel",null),Ze([nt()],bg.prototype,"_reflectionTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"reflectionTexture",void 0),Ze([rt()],bg.prototype,"_reflectionBlur",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"reflectionBlur",void 0),Ze([nt()],bg.prototype,"_diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"shadowLights",void 0),Ze([rt()],bg.prototype,"_shadowLevel",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"shadowLevel",void 0),Ze([ht()],bg.prototype,"_sceneCenter",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"sceneCenter",void 0),Ze([rt()],bg.prototype,"_opacityFresnel",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"opacityFresnel",void 0),Ze([rt()],bg.prototype,"_reflectionFresnel",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"reflectionFresnel",void 0),Ze([rt()],bg.prototype,"_reflectionFalloffDistance",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"reflectionFalloffDistance",void 0),Ze([rt()],bg.prototype,"_reflectionAmount",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"reflectionAmount",void 0),Ze([rt()],bg.prototype,"_reflectionReflectance0",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"reflectionReflectance0",void 0),Ze([rt()],bg.prototype,"_reflectionReflectance90",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"reflectionReflectance90",void 0),Ze([rt()],bg.prototype,"_useRGBColor",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"useRGBColor",void 0),Ze([rt()],bg.prototype,"_enableNoise",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"enableNoise",void 0),Ze([rt()],bg.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"maxSimultaneousLights",void 0),Ze([rt()],bg.prototype,"_shadowOnly",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],bg.prototype,"shadowOnly",void 0),Ze([_t()],bg.prototype,"_imageProcessingConfiguration",void 0),Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],bg.prototype,"enableGroundProjection",void 0),Ze([rt()],bg.prototype,"projectedGroundRadius",void 0),Ze([rt()],bg.prototype,"projectedGroundHeight",void 0),z("BABYLON.BackgroundMaterial",bg);class Tg{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new Ee(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new Ee(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:_e.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}constructor(e,t){this._errorHandler=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options={...Tg._GetDefaultOptions(t),...e},this._scene=t,this.onErrorObservable=new K,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){const t={...this._options,...e};this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new Ae(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof ya)return void(this._scene.environmentTexture=this._options.environmentTexture);const e=vg.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new ha("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;const e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};const s=this._scene.getWorldExtends((e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox)),r=s.max.subtract(s.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof hc&&this._scene.activeCamera.upperRadiusLimit&&(e=2*this._scene.activeCamera.upperRadiusLimit,t=e);const n=r.length();n>e&&(e=2*n,t=e),e*=1.1,t*=1.5,i=s.min.add(r.scale(.5)),i.y=s.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){this._ground&&!this._ground.isDisposed()||(this._ground=Wa("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((()=>{this._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new bg("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){this._groundMaterial&&(this._groundTexture||(this._options.groundTexture instanceof ya?this._groundMaterial.diffuseTexture=this._options.groundTexture:(this._groundTexture=new Pa(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture)))}_setupGroundMirrorTexture(e){const t=Pa.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new gg("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,Pa.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new Nr(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e{this._skybox=null}))),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new bg("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){this._skyboxMaterial&&(this._skyboxTexture||(this._options.skyboxTexture instanceof ya?this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture:(this._skyboxTexture=new vg(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=Pa.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture)))}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}}Tg._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",Tg._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",Tg._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class yg extends lo{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=Pa.CLAMP_ADDRESSMODE,this._texture.wrapV=Pa.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=Pa.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=Pa.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,s,r=null){super(e,s),this.onError=r,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=yg.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new K,this.onLoadObservable=new K,s=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=Boolean(i.clickToPlay),i.autoPlay=void 0===i.autoPlay||Boolean(i.autoPlay),i.loop=void 0===i.loop||Boolean(i.loop),i.size=Math.abs(i.size)||(s.activeCamera?.48*s.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=_d(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:ha.BACKSIDE},s);const n=this._material=new bg(e+"_material",s);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;const o=this._initTexture(t,s,i);if(this.texture=o,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=_d("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:ha.BACKSIDE},s),this._halfDomeMask.rotate(Xr.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce((()=>{this._setReady(!0)})),i.faceForward&&s.activeCamera){const e=s.activeCamera,t=_e.Forward(),i=_e.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(_e.Dot(t,i))}this._changeTextureMode(this._textureMode)}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case yg.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case yg.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;const e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((i=>{let s=i.isRightCamera;this._crossEye&&(s=!s),this._texture.uOffset=s?e:t}));break}case yg.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0}))}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}}yg.MODE_MONOSCOPIC=0,yg.MODE_TOPBOTTOM=1,yg.MODE_SIDEBYSIDE=2;class Sg extends yg{get photoTexture(){return this.texture}set photoTexture(e){this.texture=e}get imageMode(){return this.textureMode}set imageMode(e){this.textureMode=e}_initTexture(e,t,i){return new Pa(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,(()=>{this.onLoadObservable.notifyObservers()}),((e,t)=>{this.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),this.onError&&this.onError(e,t)}))}}Sg.MODE_MONOSCOPIC=yg.MODE_MONOSCOPIC,Sg.MODE_TOPBOTTOM=yg.MODE_TOPBOTTOM,Sg.MODE_SIDEBYSIDE=yg.MODE_SIDEBYSIDE;let Cg=0;const Eg=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const i=e._blockEntityCollection;e._blockEntityCollection=!1;const s=Pa.CreateFromBase64String("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==","EnvironmentBRDFTexture"+Cg++,e,!0,!1,Pa.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;const r=e.getEngine().getLoadedTexturesCache(),n=r.indexOf(s.getInternalTexture());-1!==n&&r.splice(n,1),s.isRGBD=!0,s.wrapU=Pa.CLAMP_ADDRESSMODE,s.wrapV=Pa.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=s,e.useDelayedTextureLoading=t,mp.ExpandRGBDTexture(s);const o=e.getEngine().onContextRestoredObservable.add((()=>{s.isRGBD=!0;const t=e.onBeforeRenderObservable.add((()=>{s.isReady()&&(e.onBeforeRenderObservable.remove(t),mp.ExpandRGBDTexture(s))}))}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(o)}))}return e.environmentBRDFTexture},Ag={GetEnvironmentBRDFTexture:Eg};class Pg extends xl{constructor(){super(...arguments),this.BRDF_V_HEIGHT_CORRELATED=!1,this.MS_BRDF_ENERGY_CONSERVATION=!1,this.SPHERICAL_HARMONICS=!1,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1}}class Ig extends nu{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new Pg,t),this._useEnergyConservation=Ig.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=Ig.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=Ig.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=Ig.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=Ig.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=Ig.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=Ig.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=Ig.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation}getClassName(){return"PBRBRDFConfiguration"}}Ig.DEFAULT_USE_ENERGY_CONSERVATION=!0,Ig.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,Ig.DEFAULT_USE_SPHERICAL_HARMONICS=!0,Ig.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],Ig.prototype,"useEnergyConservation",void 0),Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],Ig.prototype,"useSmithVisibilityHeightCorrelated",void 0),Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],Ig.prototype,"useSphericalHarmonics",void 0),Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],Ig.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);Bi.IncludesShadersStore.pbrFragmentDeclaration="uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor;\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REALTIME_FILTERING\nuniform vec2 vReflectionFilteringInfo;\n#endif\nuniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams;\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#endif\n#ifdef IRIDESCENCE\nuniform vec4 vIridescenceParams;\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\nuniform vec4 vSheenColor;\n#ifdef SHEEN_ROUGHNESS\nuniform float vSheenRoughness;\n#endif\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;\n#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\n#endif\n#ifdef SS_DISPERSION\nuniform float dispersion;\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;\n#endif\nuniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity;uniform vec4 vTranslucencyColor;\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nuniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;\n#endif\n#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\n#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;\n#else\nuniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;\n#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";Bi.IncludesShadersStore.pbrUboDeclaration="layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";Bi.IncludesShadersStore.pbrFragmentExtraDeclaration="varying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#include[1..7]\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n";Bi.IncludesShadersStore.samplerFragmentAlternateDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n#endif\n";Bi.IncludesShadersStore.pbrFragmentSamplersDeclaration="#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform sampler2D clearCoatRoughnessSampler;\n#endif\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform sampler2D sheenRoughnessSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh;\n#endif\n#endif\n#endif\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)\n#endif\n";Bi.IncludesShadersStore.subSurfaceScatteringFunctions="bool testLightingForSSS(float diffusionProfile)\n{return diffusionProfile<1.;}";Bi.IncludesShadersStore.importanceSampling="vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { \nfloat phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}";Bi.IncludesShadersStore.pbrHelperFunctions="#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{return square(roughness)+MINIMUMVARIANCE;}\nfloat fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}\n#else\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;}\n#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);}\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);return clearCoatAbsorption;}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;}\n#endif\n";Bi.IncludesShadersStore.harmonicsFunctions="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nvec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00\n+ vSphericalL1_1*(normal.y)\n+ vSphericalL10*(normal.z)\n+ vSphericalL11*(normal.x)\n+ vSphericalL2_2*(normal.y*normal.x)\n+ vSphericalL2_1*(normal.y*normal.z)\n+ vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+ vSphericalL21*(normal.z*normal.x)\n+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}\n#else\nvec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;}\n#endif\n#endif\n";Bi.IncludesShadersStore.pbrDirectLightingSetupFunctions="struct preLightingInfo\n{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness;\n#ifdef IRIDESCENCE\nfloat iridescenceIntensity;\n#endif\n};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;}";Bi.IncludesShadersStore.pbrDirectLightingFalloffFunctions="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{return max(0.,1.0-length(lightOffset)/range);}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{return 1.0/maxEps(lightDistanceSquared);}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)\n{falloff=max(0.,pow(cosAngle,exponent));}\nreturn falloff;}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}";Bi.IncludesShadersStore.pbrBRDFFunctions="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;\n#endif\nreturn reflectance;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#endif\nreturn reflectance;}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfloat getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)\n{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\n/**\n* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.\n* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table\n*/\nvec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}\n#endif\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\n#ifdef CLEARCOAT\nvec3 getR0RemappedForClearCoat(vec3 f0) {\n#ifdef CLEARCOAT_DEFAULTIOR\n#ifdef MOBILE\nreturn saturate(f0*(f0*0.526868+0.529324)-0.0482256);\n#else\nreturn saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);\n#endif\n#else\nvec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t);\n#endif\n}\n#endif\n#ifdef IRIDESCENCE\nconst mat3 XYZ_TO_REC709=mat3(\n3.2404542,-0.9692660, 0.0556434,\n-1.5371385, 1.8760108,-0.2040259,\n-0.4985314, 0.0415560, 1.0572252\n);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}\nvec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));}\nfloat getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));}\nvec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;}\nvec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;}\nfloat cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose(),this._bumpTexture?.dispose(),this._tintTexture?.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}}Mg._DefaultIndexOfRefraction=1.5,Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"isEnabled",void 0),Ze([rt()],Mg.prototype,"intensity",void 0),Ze([rt()],Mg.prototype,"roughness",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"indexOfRefraction",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"texture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"useRoughnessFromMainTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"textureRoughness",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"remapF0OnInterfaceChange",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"bumpTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"isTintEnabled",void 0),Ze([ot()],Mg.prototype,"tintColor",void 0),Ze([rt()],Mg.prototype,"tintColorAtDistance",void 0),Ze([rt()],Mg.prototype,"tintThickness",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"tintTexture",void 0);class Og extends xl{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0}}class Dg extends nu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new Og,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=Dg._DefaultMinimumThickness,this.maximumThickness=Dg._DefaultMaximumThickness,this.indexOfRefraction=Dg._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&$c.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&$c.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&$c.IridescenceTextureEnabled?Mo(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&$c.IridescenceTextureEnabled?Mo(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||((this._texture||this._thicknessTexture)&&$c.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._thicknessTexture?.coordinatesIndex??0,this._thicknessTexture?.level??0),this._texture&&Oo(this._texture,e,"iridescence"),this._thicknessTexture&&Oo(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&$c.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&$c.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){e&&(this._texture?.dispose(),this._thicknessTexture?.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}}Dg._DefaultMinimumThickness=100,Dg._DefaultMaximumThickness=400,Dg._DefaultIndexOfRefraction=1.3,Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Dg.prototype,"isEnabled",void 0),Ze([rt()],Dg.prototype,"intensity",void 0),Ze([rt()],Dg.prototype,"minimumThickness",void 0),Ze([rt()],Dg.prototype,"maximumThickness",void 0),Ze([rt()],Dg.prototype,"indexOfRefraction",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Dg.prototype,"texture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Dg.prototype,"thicknessTexture",void 0);class wg extends xl{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class Ng extends nu{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new wg,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new de(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&$c.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(er.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&$c.AnisotropicTextureEnabled?Mo(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1),e._areMiscDirty&&(e.ANISOTROPIC_LEGACY=this._legacy)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.ANISOTROPIC_LEGACY=!1)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&$c.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),Oo(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&$c.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,i){super.parse(e,t,i),void 0===e.legacy&&(this.legacy=!0)}}Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Ng.prototype,"isEnabled",void 0),Ze([rt()],Ng.prototype,"intensity",void 0),Ze([lt()],Ng.prototype,"direction",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Ng.prototype,"texture",void 0),Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],Ng.prototype,"legacy",void 0);class Fg extends xl{constructor(){super(...arguments),this.SHEEN=!1,this.SHEEN_TEXTURE=!1,this.SHEEN_GAMMATEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS=!1,this.SHEEN_TEXTUREDIRECTUV=0,this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,this.SHEEN_LINKWITHALBEDO=!1,this.SHEEN_ROUGHNESS=!1,this.SHEEN_ALBEDOSCALING=!1,this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1}}class Lg extends nu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new Fg,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=Ee.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&$c.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&$c.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=null!==this._roughness,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&$c.SheenTextureEnabled?(Mo(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&$c.SheenTextureEnabled?Mo(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,s){if(!this._isEnabled)return;const r=s.materialDefines,n=this._material.isFrozen;e.useUbo&&n&&e.isSync||((this._texture||this._textureRoughness)&&$c.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&Oo(this._texture,e,"sheen"),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Oo(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),null!==this._roughness&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&$c.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&$c.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}}Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Lg.prototype,"isEnabled",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Lg.prototype,"linkSheenWithAlbedo",void 0),Ze([rt()],Lg.prototype,"intensity",void 0),Ze([ot()],Lg.prototype,"color",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Lg.prototype,"texture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Lg.prototype,"useRoughnessFromMainTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Lg.prototype,"roughness",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Lg.prototype,"textureRoughness",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Lg.prototype,"albedoScaling",void 0);class Bg extends xl{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_SCATTERING=!1,this.SS_DISPERSION=!1,this.SS_THICKNESSANDMASK_TEXTURE=!1,this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,this.SS_HAS_THICKNESS=!1,this.SS_REFRACTIONINTENSITY_TEXTURE=!1,this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,this.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0,this.SS_REFRACTIONMAP_3D=!1,this.SS_REFRACTIONMAP_OPPOSITEZ=!1,this.SS_LODINREFRACTIONALPHA=!1,this.SS_GAMMAREFRACTION=!1,this.SS_RGBDREFRACTION=!1,this.SS_LINEARSPECULARREFRACTION=!1,this.SS_LINKREFRACTIONTOTRANSPARENCY=!1,this.SS_ALBEDOFORREFRACTIONTINT=!1,this.SS_ALBEDOFORTRANSLUCENCYTINT=!1,this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.SS_USE_THICKNESS_AS_DEPTH=!1,this.SS_USE_GLTF_TEXTURES=!1}}class kg extends nu{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){this._volumeIndexOfRefraction=e>=1?e:-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new Bg,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isDispersionEnabled=!1,this.isDispersionEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this.useAlbedoToTintRefraction=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=Ee.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=Ee.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this.translucencyColor=null,this._translucencyColorTexture=null,this.translucencyColorTexture=null,this._useGltfStyleTextures=!0,this.useGltfStyleTextures=!0,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&$c.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;if(this._translucencyColorTexture&&$c.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&$c.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return e.SUBSURFACE=!1,e.SS_DISPERSION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,void(e.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0);if(e._areTexturesDirty){if(e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&$c.ThicknessTextureEnabled&&Mo(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&$c.RefractionIntensityTextureEnabled&&Mo(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&$c.TranslucencyIntensityTextureEnabled&&Mo(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&&$c.TranslucencyColorTextureEnabled&&Mo(this._translucencyColorTexture,e,"SS_TRANSLUCENCYCOLOR_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._refractionIntensityTexture,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._translucencyIntensityTexture,this._isRefractionEnabled&&t.texturesEnabled){const i=this._getRefractionTexture(t);i&&$c.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;s.getRenderingMesh().getWorldMatrix().decompose(ve.Vector3[0]);const r=Math.max(Math.abs(ve.Vector3[0].x),Math.abs(ve.Vector3[0].y),Math.abs(ve.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*r,(this.maximumThickness-this.minimumThickness)*r)}bindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const r=s.materialDefines,n=this._material.isFrozen,o=this._material.realTimeFiltering,a=r.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&$c.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),Oo(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&$c.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),Oo(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&&$c.TranslucencyColorTextureEnabled&&r.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),Oo(this._translucencyColorTexture,e,"translucencyColor")),l&&$c.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;l.isCube||l.depth&&(t=l.depth);const i=l.getSize().width,s=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",l.level,1/s,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",i,be.Log2(i)),l.boundingBoxSize){const t=l;e.updateVector3("vRefractionPosition",t.boundingBoxPosition),e.updateVector3("vRefractionSize",t.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateColor4("vTranslucencyColor",this.translucencyColor??this.tintColor,0),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&$c.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&$c.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&$c.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&&$c.TranslucencyColorTextureEnabled&&r.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),l&&$c.RefractionTextureEnabled&&(a?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){$c.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e||this._refractionIntensityTexture===e||this._translucencyIntensityTexture===e||this._translucencyColorTexture===e}hasRenderTargetTextures(){return!!($c.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture),this._translucencyColorTexture&&e.push(this._translucencyColorTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),this._translucencyColorTexture&&this._translucencyColorTexture.animations&&this._translucencyColorTexture.animations.length>0&&e.push(this._translucencyColorTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose(),this._translucencyColorTexture&&this._translucencyColorTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","translucencyColorSampler")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"},{name:"vTranslucencyColor",size:4,type:"vec4"},{name:"vTranslucencyColorInfos",size:2,type:"vec2"},{name:"translucencyColorMatrix",size:16,type:"mat4"}]}}}Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"isRefractionEnabled",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"isTranslucencyEnabled",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"isDispersionEnabled",void 0),Ze([rt(),st("_markScenePrePassDirty")],kg.prototype,"isScatteringEnabled",void 0),Ze([rt()],kg.prototype,"_scatteringDiffusionProfileIndex",void 0),Ze([rt()],kg.prototype,"refractionIntensity",void 0),Ze([rt()],kg.prototype,"translucencyIntensity",void 0),Ze([rt()],kg.prototype,"useAlbedoToTintRefraction",void 0),Ze([rt()],kg.prototype,"useAlbedoToTintTranslucency",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"thicknessTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"refractionTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"indexOfRefraction",void 0),Ze([rt()],kg.prototype,"_volumeIndexOfRefraction",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"volumeIndexOfRefraction",null),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"invertRefractionY",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"linkRefractionWithTransparency",void 0),Ze([rt()],kg.prototype,"minimumThickness",void 0),Ze([rt()],kg.prototype,"maximumThickness",void 0),Ze([rt()],kg.prototype,"useThicknessAsDepth",void 0),Ze([ot()],kg.prototype,"tintColor",void 0),Ze([rt()],kg.prototype,"tintColorAtDistance",void 0),Ze([rt()],kg.prototype,"dispersion",void 0),Ze([ot()],kg.prototype,"diffusionDistance",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"useMaskFromThicknessTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"refractionIntensityTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"translucencyIntensityTexture",void 0),Ze([ot()],kg.prototype,"translucencyColor",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"translucencyColorTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"useGltfStyleTextures",void 0);const Vg={effect:null,subMesh:null};class Ug extends xl{constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class Gg extends ml{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new pe(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=Gg.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._reflectivityTexture=null,this._metallicTexture=null,this._metallic=null,this._roughness=null,this._metallicF0Factor=1,this._metallicReflectanceColor=Ee.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new Ee(0,0,0),this._albedoColor=new Ee(1,1,1),this._reflectivityColor=new Ee(1,1,1),this._reflectionColor=new Ee(1,1,1),this._emissiveColor=new Ee(0,0,0),this._microSurface=.9,this._useLightmapAsShadowmap=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromAlbedoTexture=!1,this._useSpecularOverAlpha=!0,this._useMicroSurfaceFromReflectivityMapAlpha=!1,this._useRoughnessFromMetallicTextureAlpha=!0,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallnessFromMetallicTextureBlue=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useAmbientInGrayScale=!1,this._useAutoMicroSurfaceFromReflectivityMap=!1,this._lightFalloff=Gg.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._forceAlphaTest=!1,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new Fs(16),this._globalAmbientColor=new Ee(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new Ig(this),this.clearCoat=new Mg(this),this.iridescence=new Dg(this),this.anisotropy=new Ng(this),this.sheen=new Lg(this),this.subSurface=new kg(this),this.detailMap=new au(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),$c.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=Eg(this.getScene()),this.prePassConfiguration=new Kc}get hasRenderTargetTextures(){return!!($c.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){return this._transparencyMode===Gg.PBRMATERIAL_OPAQUE||this._transparencyMode===Gg.PBRMATERIAL_ALPHATEST||this.subSurface?.disableAlphaBlending}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){return!!this._forceAlphaTest||!this.subSurface?.disableAlphaBlending&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Gg.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==Gg.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(fo.GetDefineNames,this._eventInfo),t.materialDefines=new Ug(this._eventInfo.defineNames));const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=this.getScene(),o=n.getEngine();if(r._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&$c.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&$c.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&$c.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&$c.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&e.getInternalTexture()?._sphericalPolynomialPromise)return!1}if(this._lightmapTexture&&$c.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&$c.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if($c.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking())return!1;if(this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&$c.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&$c.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(r._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;o.getCaps().standardDerivatives||e.isVerticesDataPresent(er.NormalKind)||(e.createNormals(!0),Ne.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const a=t.effect,l=r._areLightsDisposed;let h=this._prepareEffect(e,r,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),c=!1;if(h)if(this._onEffectCreatedObservable&&(Vg.effect=h,Vg.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Vg)),this.allowShaderHotSwapping&&a&&!h.isReady()){if(h=a,r.markAsUnprocessed(),c=this.isFrozen,l)return r._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(h,r,this._materialContext);return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!c,s._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),0))}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,i=null,s=null,r=null,n=null,o){if(this._prepareDefines(e,t,r,n,o),!t.isDirty)return null;t.markAsProcessed();const a=this.getScene().getEngine(),l=new Ll;let h=0;t.USESPHERICALINVERTEX&&l.addFallback(h++,"USESPHERICALINVERTEX"),t.FOG&&l.addFallback(h,"FOG"),t.SPECULARAA&&l.addFallback(h,"SPECULARAA"),t.POINTSIZE&&l.addFallback(h,"POINTSIZE"),t.LOGARITHMICDEPTH&&l.addFallback(h,"LOGARITHMICDEPTH"),t.PARALLAX&&l.addFallback(h,"PARALLAX"),t.PARALLAX_RHS&&l.addFallback(h,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&l.addFallback(h++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&l.addFallback(h++,"ENVIRONMENTBRDF"),t.TANGENT&&l.addFallback(h++,"TANGENT"),t.BUMP&&l.addFallback(h++,"BUMP"),h=Vo(t,l,this._maxSimultaneousLights,h++),t.SPECULARTERM&&l.addFallback(h++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&l.addFallback(h++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&l.addFallback(h++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&l.addFallback(h++,"LIGHTMAP"),t.NORMAL&&l.addFallback(h++,"NORMAL"),t.AMBIENT&&l.addFallback(h++,"AMBIENT"),t.EMISSIVE&&l.addFallback(h++,"EMISSIVE"),t.VERTEXCOLOR&&l.addFallback(h++,"VERTEXCOLOR"),t.MORPHTARGETS&&l.addFallback(h++,"MORPHTARGETS"),t.MULTIVIEW&&l.addFallback(0,"MULTIVIEW");const c=[er.PositionKind];t.NORMAL&&c.push(er.NormalKind),t.TANGENT&&c.push(er.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&c.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&c.push(er.ColorKind),Bo(c,e,t,l),ko(c,t),Ao(c,e,t),Do(c,0,t);let u="pbr";const d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],_=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],p=["Material","Scene","Mesh"],f={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=l,this._eventInfo.fallbackRank=h,this._eventInfo.defines=t,this._eventInfo.uniforms=d,this._eventInfo.attributes=c,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=p,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=f,this._callbackPluginEventGeneric(fo.PrepareEffect,this._eventInfo),Kc.AddUniforms(d),Kc.AddSamplers(_),mo(d),zs&&(zs.PrepareUniforms(d,t),zs.PrepareSamplers(_,t)),ea({uniformsNames:d,uniformBuffersNames:p,samplers:_,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const m={};this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,d,p,_,t,c,m));const g=t.toString(),v=a.createEffect(u,{attributes:c,uniformsNames:d,uniformBuffersNames:p,samplers:_,defines:g,fallbacks:l,onCompiled:i,onError:s,indexParameters:f,processFinalCode:m.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},a);return this._eventInfo.customCode=void 0,v}_prepareDefines(e,t,i=null,s=null,r=!1){const n=this.getScene(),o=n.getEngine();zo(n,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,Ko(n,t);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(qo(n,t,this.canRenderToMRT&&!a),$o(n,t,a),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!1;if(n.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&$c.DiffuseTextureEnabled?(Mo(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&$c.AmbientTextureEnabled?(Mo(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&$c.OpacityTextureEnabled?(Mo(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&$c.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(t.NUM_SAMPLES=""+this.realTimeFilteringQuality,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===Pa.INVCUBIC_MODE,t.REFLECTIONMAP_3D=e.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.coordinatesMode){case Pa.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case Pa.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case Pa.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case Pa.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case Pa.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case Pa.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Pa.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Pa.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Pa.CUBIC_MODE:case Pa.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==Pa.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||o.getCaps().maxVaryingVectors<=8?t.USESPHERICALINVERTEX=!1:t.USESPHERICALINVERTEX=!0))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;this._lightmapTexture&&$c.LightmapTextureEnabled?(Mo(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&$c.EmissiveTextureEnabled?(Mo(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,$c.SpecularTextureEnabled?(this._metallicTexture?(Mo(this._metallicTexture,t,"REFLECTIVITY"),t.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,t.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,t.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,t.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,t.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(Mo(this._reflectivityTexture,t,"REFLECTIVITY"),t.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,t.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,t.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):t.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture?(t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture,this._metallicReflectanceTexture?(Mo(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(Mo(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1):(t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1),this._microSurfaceTexture?Mo(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1):(t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1),o.getCaps().standardDerivatives&&this._bumpTexture&&$c.BumpTextureEnabled&&!this._disableBumpMap?(Mo(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&$c.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=n.useRightHandedSystem,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAX_RHS=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&$c.ReflectionTextureEnabled?(t.ENVIRONMENTBRDF=!0,t.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(t.ENVIRONMENTBRDF=!1,t.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?t.ALPHAFROMALBEDO=!0:t.ALPHAFROMALBEDO=!1}t.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===Gg.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Gg.LIGHTFALLOFF_GLTF?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!0):(t.USEPHYSICALLIGHTFALLOFF=!0,t.USEGLTFLIGHTFALLOFF=!1),t.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?t.TWOSIDEDLIGHTING=!0:t.TWOSIDEDLIGHTING=!1,t.SPECULARAA=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(er.NormalKind),t.DEBUGMODE=this._debugMode),Ho(n,o,this,t,!!i,s,r),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),jo(e,t,!0,!0,!0,this._transparencyMode!==Gg.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const s={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(fo.GetDefineNames,this._eventInfo);const r=new Ug(this._eventInfo.defineNames),n=this._prepareEffect(e,r,void 0,void 0,s.useInstances,s.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(Vg.effect=n,Vg.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Vg)),n.isReady()?t&&t(this):n.onCompileObservable.add((()=>{t&&t(this)}))}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionFilteringInfo",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("reflectionMatrix",16),e.addUniform("vReflectionColor",3),e.addUniform("vAlbedoColor",4),e.addUniform("vLightingIntensity",4),e.addUniform("vReflectionMicrosurfaceInfos",3),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),e.addUniform("vSphericalL00",3),e.addUniform("vSphericalL1_1",3),e.addUniform("vSphericalL10",3),e.addUniform("vSphericalL11",3),e.addUniform("vSphericalL2_2",3),e.addUniform("vSphericalL2_1",3),e.addUniform("vSphericalL20",3),e.addUniform("vSphericalL21",3),e.addUniform("vSphericalL22",3),e.addUniform("vSphericalX",3),e.addUniform("vSphericalY",3),e.addUniform("vSphericalZ",3),e.addUniform("vSphericalXX_ZZ",3),e.addUniform("vSphericalYY_ZZ",3),e.addUniform("vSphericalZZ",3),e.addUniform("vSphericalXY",3),e.addUniform("vSphericalYZ",3),e.addUniform("vSphericalZX",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e);const o=s.getEngine();this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const a=this._mustRebind(s,n,i,t.visibility);wo(t,this._activeEffect,this.prePassConfiguration);let l=null;const h=this._uniformBuffer;if(a){if(this.bindViewProjection(n),l=this._getReflectionTexture(),!h.useUbo||!this.isFrozen||!h.isSync||i._drawWrapper._forceRebindOnNextCall){if(s.texturesEnabled){if(this._albedoTexture&&$c.DiffuseTextureEnabled&&(h.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),Oo(this._albedoTexture,h,"albedo")),this._ambientTexture&&$c.AmbientTextureEnabled&&(h.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),Oo(this._ambientTexture,h,"ambient")),this._opacityTexture&&$c.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Oo(this._opacityTexture,h,"opacity")),l&&$c.ReflectionTextureEnabled){if(h.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),h.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){const e=l;h.updateVector3("vReflectionPosition",e.boundingBoxPosition),h.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=l.getSize().width;h.updateFloat2("vReflectionFilteringInfo",e,be.Log2(e))}if(!r.USEIRRADIANCEMAP){const e=l.sphericalPolynomial;if(r.USESPHERICALFROMREFLECTIONMAP&&e)if(r.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;h.updateVector3("vSphericalL00",t.l00),h.updateVector3("vSphericalL1_1",t.l1_1),h.updateVector3("vSphericalL10",t.l10),h.updateVector3("vSphericalL11",t.l11),h.updateVector3("vSphericalL2_2",t.l2_2),h.updateVector3("vSphericalL2_1",t.l2_1),h.updateVector3("vSphericalL20",t.l20),h.updateVector3("vSphericalL21",t.l21),h.updateVector3("vSphericalL22",t.l22)}else h.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),h.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),h.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),h.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),h.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),h.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),h.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),h.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),h.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}h.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}this._emissiveTexture&&$c.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Oo(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&$c.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Oo(this._lightmapTexture,h,"lightmap")),$c.SpecularTextureEnabled&&(this._metallicTexture?(h.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),Oo(this._metallicTexture,h,"reflectivity")):this._reflectivityTexture&&(h.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),Oo(this._reflectivityTexture,h,"reflectivity")),this._metallicReflectanceTexture&&(h.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),Oo(this._metallicReflectanceTexture,h,"metallicReflectance")),this._reflectanceTexture&&r.REFLECTANCE&&(h.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),Oo(this._reflectanceTexture,h,"reflectance")),this._microSurfaceTexture&&(h.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),Oo(this._microSurfaceTexture,h,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&&$c.BumpTextureEnabled&&!this._disableBumpMap&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),Oo(this._bumpTexture,h,"bump"),s._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),r.METALLICWORKFLOW){Pe.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,Pe.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,h.updateColor4("vReflectivityColor",Pe.Color3[0],1);const e=this.subSurface?._indexOfRefraction??1.5,t=1,i=Math.pow((e-t)/(e+t),2);this._metallicReflectanceColor.scaleToRef(i*this._metallicF0Factor,Pe.Color3[0]);const s=this._metallicF0Factor;h.updateColor4("vMetallicReflectanceFactors",Pe.Color3[0],s)}else h.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);h.updateColor3("vEmissiveColor",$c.EmissiveTextureEnabled?this._emissiveColor:Ee.BlackReadOnly),h.updateColor3("vReflectionColor",this._reflectionColor),!r.SS_REFRACTION&&this.subSurface?._linkRefractionWithTransparency?h.updateColor4("vAlbedoColor",this._albedoColor,1):h.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*s.environmentIntensity,this._lightingInfos.w=this._specularIntensity,h.updateVector4("vLightingIntensity",this._lightingInfos),s.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor),h.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}s.texturesEnabled&&(this._albedoTexture&&$c.DiffuseTextureEnabled&&h.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&$c.AmbientTextureEnabled&&h.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&$c.OpacityTextureEnabled&&h.setTexture("opacitySampler",this._opacityTexture),l&&$c.ReflectionTextureEnabled&&(r.LODBASEDMICROSFURACE?h.setTexture("reflectionSampler",l):(h.setTexture("reflectionSampler",l._lodTextureMid||l),h.setTexture("reflectionSamplerLow",l._lodTextureLow||l),h.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)),r.USEIRRADIANCEMAP&&h.setTexture("irradianceSampler",l.irradianceTexture)),r.ENVIRONMENTBRDF&&h.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&$c.EmissiveTextureEnabled&&h.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&$c.LightmapTextureEnabled&&h.setTexture("lightmapSampler",this._lightmapTexture),$c.SpecularTextureEnabled&&(this._metallicTexture?h.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&h.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&h.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&r.REFLECTANCE&&h.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&h.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&&$c.BumpTextureEnabled&&!this._disableBumpMap&&h.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),xo(this._activeEffect,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!a&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&Lo(s,t,this._activeEffect,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE||l||this.subSurface.refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),Co(s,t,this._activeEffect,!0),r.NUM_MORPH_INFLUENCERS&&Io(t,this._activeEffect),r.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,r.INSTANCES),this._imageProcessingConfiguration.bind(this._activeEffect),So(r,this._activeEffect,s)),this._afterBind(t,this._activeEffect,i),h.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._albedoTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e}setPrePassRenderer(){if(!this.subSurface?.isScatteringEnabled)return!1;const e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._albedoTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._metallicTexture?.dispose(),this._reflectivityTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._metallicReflectanceTexture?.dispose(),this._reflectanceTexture?.dispose(),this._microSurfaceTexture?.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}Gg.PBRMATERIAL_OPAQUE=ta.MATERIAL_OPAQUE,Gg.PBRMATERIAL_ALPHATEST=ta.MATERIAL_ALPHATEST,Gg.PBRMATERIAL_ALPHABLEND=ta.MATERIAL_ALPHABLEND,Gg.PBRMATERIAL_ALPHATESTANDBLEND=ta.MATERIAL_ALPHATESTANDBLEND,Gg.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,Gg.LIGHTFALLOFF_PHYSICAL=0,Gg.LIGHTFALLOFF_GLTF=1,Gg.LIGHTFALLOFF_STANDARD=2,Ze([_t()],Gg.prototype,"_imageProcessingConfiguration",void 0),Ze([st("_markAllSubMeshesAsMiscDirty")],Gg.prototype,"debugMode",void 0);class zg extends Gg{get refractionTexture(){return this.subSurface.refractionTexture}set refractionTexture(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)}get indexOfRefraction(){return this.subSurface.indexOfRefraction}set indexOfRefraction(e){this.subSurface.indexOfRefraction=e}get invertRefractionY(){return this.subSurface.invertRefractionY}set invertRefractionY(e){this.subSurface.invertRefractionY=e}get linkRefractionWithTransparency(){return this.subSurface.linkRefractionWithTransparency}set linkRefractionWithTransparency(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)}get usePhysicalLightFalloff(){return this._lightFalloff===Gg.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Gg.LIGHTFALLOFF_PHYSICAL:Gg.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Gg.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Gg.LIGHTFALLOFF_GLTF:Gg.LIGHTFALLOFF_STANDARD)}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=zg.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=Ee.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new Ee(0,0,0),this.albedoColor=new Ee(1,1,1),this.reflectivityColor=new Ee(1,1,1),this.reflectionColor=new Ee(1,1,1),this.emissiveColor=new Ee(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=Eg(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const s=St.Clone((()=>new zg(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return s.id=e,s.name=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const s=St.Parse((()=>new zg(e.name,t)),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),ta._ParsePlugins(e,s,t,i),e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}zg.PBRMATERIAL_OPAQUE=Gg.PBRMATERIAL_OPAQUE,zg.PBRMATERIAL_ALPHATEST=Gg.PBRMATERIAL_ALPHATEST,zg.PBRMATERIAL_ALPHABLEND=Gg.PBRMATERIAL_ALPHABLEND,zg.PBRMATERIAL_ALPHATESTANDBLEND=Gg.PBRMATERIAL_ALPHATESTANDBLEND,zg.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Gg.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"directIntensity",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"emissiveIntensity",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"environmentIntensity",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"specularIntensity",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"disableBumpMap",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"albedoTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"ambientTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"ambientTextureStrength",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesAndMiscDirty")],zg.prototype,"opacityTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"reflectionTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"emissiveTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"reflectivityTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"metallicTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"metallic",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"roughness",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"metallicF0Factor",void 0),Ze([ot(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"metallicReflectanceColor",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"metallicReflectanceTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"reflectanceTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"microSurfaceTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"bumpTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty",null)],zg.prototype,"lightmapTexture",void 0),Ze([ot("ambient"),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"ambientColor",void 0),Ze([ot("albedo"),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"albedoColor",void 0),Ze([ot("reflectivity"),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"reflectivityColor",void 0),Ze([ot("reflection"),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"reflectionColor",void 0),Ze([ot("emissive"),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"emissiveColor",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"microSurface",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useLightmapAsShadowmap",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesAndMiscDirty")],zg.prototype,"useAlphaFromAlbedoTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesAndMiscDirty")],zg.prototype,"forceAlphaTest",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesAndMiscDirty")],zg.prototype,"alphaCutOff",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useSpecularOverAlpha",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useRoughnessFromMetallicTextureGreen",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useMetallnessFromMetallicTextureBlue",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useAmbientInGrayScale",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),Ze([rt()],zg.prototype,"usePhysicalLightFalloff",null),Ze([rt()],zg.prototype,"useGLTFLightFalloff",null),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useRadianceOverAlpha",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useObjectSpaceNormalMap",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useParallax",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useParallaxOcclusion",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"parallaxScaleBias",void 0),Ze([rt(),st("_markAllSubMeshesAsLightsDirty")],zg.prototype,"disableLighting",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"forceIrradianceInFragment",void 0),Ze([rt(),st("_markAllSubMeshesAsLightsDirty")],zg.prototype,"maxSimultaneousLights",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"invertNormalMapX",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"invertNormalMapY",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"twoSidedLighting",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useAlphaFresnel",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useLinearAlphaFresnel",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"environmentBRDFTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"forceNormalForward",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"enableSpecularAntiAliasing",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useHorizonOcclusion",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useRadianceOcclusion",void 0),Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],zg.prototype,"unlit",void 0),Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],zg.prototype,"applyDecalMapAfterDetailMap",void 0),z("BABYLON.PBRMaterial",zg);class Wg{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,s){const r=t.getEngine();let n,o=!1,a=1e3;if(Array.isArray(e))for(let i=0;i1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),_p.UploadDDSLevels(r,t,s,n,o,6,-1,i),n.isFourCC||1!==n.mipmapCount?a=n.mipmapCount-1:r.generateMipMapsForCubemap(t)}else{const s=e;n=_p.GetDDSInfo(s),t.width=n.width,t.height=n.height,i&&(n.sphericalPolynomial=new j_),o=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),_p.UploadDDSLevels(r,t,s,n,o,6),n.isFourCC||1!==n.mipmapCount?a=n.mipmapCount-1:r.generateMipMapsForCubemap(t,!1)}r._setCubeMapTextureParams(t,o,a),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s({isDDS:!0,width:t.width,info:n,data:e,texture:t})}loadData(e,t,i){const s=_p.GetDDSInfo(e),r=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps&&s.width>>s.mipmapCount-1==1;i(s.width,s.height,r,s.isFourCC,(()=>{_p.UploadDDSLevels(t.getEngine(),t,e,s,r,1)}))}}oo._TextureLoaders.push(new Wg);class Hg{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=bp(e);if(n){t.width=n.width,t.height=n.width;try{Ip(t,n),Ep(t,e,n).then((()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}),(e=>{r?.("Can not upload environment levels",e)}))}catch(e){r?.("Can not upload environment file",e)}}else r&&r("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}oo._TextureLoaders.push(new Hg);class Xg{constructor(e,t){if(this.data=e,this.isInvalid=!1,!Xg.IsValid(e))return this.isInvalid=!0,void Ne.Error("texture missing KTX identifier");const i=Uint32Array.BYTES_PER_ELEMENT,s=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),r=67305985===s.getUint32(0,!0);return this.glType=s.getUint32(1*i,r),this.glTypeSize=s.getUint32(2*i,r),this.glFormat=s.getUint32(3*i,r),this.glInternalFormat=s.getUint32(4*i,r),this.glBaseInternalFormat=s.getUint32(5*i,r),this.pixelWidth=s.getUint32(6*i,r),this.pixelHeight=s.getUint32(7*i,r),this.pixelDepth=s.getUint32(8*i,r),this.numberOfArrayElements=s.getUint32(9*i,r),this.numberOfFaces=s.getUint32(10*i,r),this.numberOfMipmapLevels=s.getUint32(11*i,r),this.bytesOfKeyValueData=s.getUint32(12*i,r),0!==this.glType?(Ne.Error("only compressed formats currently supported"),void(this.isInvalid=!0)):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?(Ne.Error("only 2D textures currently supported"),void(this.isInvalid=!0)):0!==this.numberOfArrayElements?(Ne.Error("texture arrays not currently supported"),void(this.isInvalid=!0)):this.numberOfFaces!==t?(Ne.Error("number of faces expected"+t+", but found "+this.numberOfFaces),void(this.isInvalid=!0)):void(this.loadType=Xg.COMPRESSED_2D))}uploadLevels(e,t){switch(this.loadType){case Xg.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case Xg.TEX_2D:case Xg.COMPRESSED_3D:case Xg.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=Xg.HEADER_LEN+this.bytesOfKeyValueData,s=this.pixelWidth,r=this.pixelHeight;const n=t?this.numberOfMipmapLevels:1;for(let t=0;t=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}Xg.HEADER_LEN=64,Xg.COMPRESSED_2D=0,Xg.COMPRESSED_3D=1,Xg.TEX_2D=2,Xg.TEX_3D=3;class Yg{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map((e=>({workerPromise:Promise.resolve(e),idle:!0})))}dispose(){for(const e of this._workerInfos)e.workerPromise.then((e=>{e.terminate()}));this._workerInfos.length=0,this._pendingActions.length=0}push(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)}_executeOnIdleWorker(e){for(const t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then((i=>{t(i,(()=>{const t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0}))}))}}class Qg extends Yg{constructor(e,t,i=Qg.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,(()=>{s(),e.idle&&(e.timeoutId=setTimeout((()=>{e.workerPromise.then((e=>{e.terminate()}));const t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)}),this._options.idleTimeElapsedBeforeRelease))}))}))}}var jg,Kg,$g;function qg(e,t){const i=t?.jsDecoderModule||KTX2DECODER;e&&(e.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(i.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(i.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)),t&&(t.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmBinary=t.wasmUASTCToASTC),t.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmBinary=t.wasmUASTCToBC7),t.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary=t.wasmUASTCToRGBA_UNORM),t.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary=t.wasmUASTCToRGBA_SRGB),t.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmBinary=t.wasmUASTCToR8_UNORM),t.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary=t.wasmUASTCToRG8_UNORM),t.jsMSCTranscoder&&(i.MSCTranscoder.JSModule=t.jsMSCTranscoder),t.wasmMSCTranscoder&&(i.MSCTranscoder.WasmBinary=t.wasmMSCTranscoder),t.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmBinary=t.wasmZSTDDecoder))}function Zg(e){let t;void 0===e&&"undefined"!=typeof KTX2DECODER&&(e=KTX2DECODER),onmessage=i=>{if(i.data)switch(i.data.action){case"init":{const s=i.data.urls;s&&(s.jsDecoderModule&&void 0===e&&(importScripts(s.jsDecoderModule),e=KTX2DECODER),qg(s)),i.data.wasmBinaries&&qg(void 0,{...i.data.wasmBinaries,jsDecoderModule:e}),t=new e.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":e.KTX2Decoder.DefaultDecoderOptions=i.data.options;break;case"decode":t.decode(i.data.data,i.data.caps,i.data.options).then((e=>{const t=[];for(let i=0;i{postMessage({action:"decoded",success:!1,msg:e})}))}}}Qg.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(jg||(jg={})),function(e){e[e.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",e[e.BC7_RGBA=1]="BC7_RGBA",e[e.BC3_RGBA=2]="BC3_RGBA",e[e.BC1_RGB=3]="BC1_RGB",e[e.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",e[e.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",e[e.ETC2_RGBA=6]="ETC2_RGBA",e[e.ETC1_RGB=7]="ETC1_RGB",e[e.RGBA32=8]="RGBA32",e[e.R8=9]="R8",e[e.RG8=10]="RG8"}(Kg||(Kg={})),function(e){e[e.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",e[e.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",e[e.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",e[e.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",e[e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",e[e.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",e[e.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",e[e.RGBA8Format=32856]="RGBA8Format",e[e.R8Format=33321]="R8Format",e[e.RG8Format=33323]="RG8Format"}($g||($g={}));class Jg{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;const e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[Kg.BC1_RGB,Kg.BC3_RGBA],yes:{transcodeFormat:Kg.RGBA32,engineFormat:$g.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class ev{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(ev._WorkerPoolPromise||ev._DecoderModulePromise)return;const t={jsDecoderModule:Ds.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:Ds.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:Ds.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:Ds.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:Ds.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:Ds.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:Ds.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:Ds.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:Ds.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:Ds.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?ev._WorkerPoolPromise=new Promise((i=>{const s=`${qg}(${Zg})()`,r=URL.createObjectURL(new Blob([s],{type:"application/javascript"}));i(new Qg(e,(()=>function(e,t,i){return new Promise(((t,s)=>{const r=t=>{e.removeEventListener("error",r),e.removeEventListener("message",n),s(t)},n=i=>{"init"===i.data.action&&(e.removeEventListener("error",r),e.removeEventListener("message",n),t(e))};e.addEventListener("error",r),e.addEventListener("message",n),e.postMessage({action:"init",urls:i,wasmBinaries:undefined})}))}(new Worker(r),0,t))))})):void 0===ev._KTX2DecoderModule?ev._DecoderModulePromise=Ds.LoadBabylonScriptAsync(t.jsDecoderModule).then((()=>(ev._KTX2DecoderModule=KTX2DECODER,ev._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,ev._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,qg(t,ev._KTX2DecoderModule),new ev._KTX2DecoderModule.KTX2Decoder))):(ev._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,ev._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,ev._DecoderModulePromise=Promise.resolve(new ev._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=ev.DefaultNumWorkers){this._engine=e;const i="object"==typeof t&&t.workerPool||ev.WorkerPool;if(i)ev._WorkerPoolPromise=Promise.resolve(i);else{"object"==typeof t?ev._KTX2DecoderModule=t?.binariesAndModulesContainer?.jsDecoderModule:"undefined"!=typeof KTX2DECODER&&(ev._KTX2DecoderModule=KTX2DECODER);const e="number"==typeof t?t:t.numWorkers??ev.DefaultNumWorkers;ev._Initialize(e)}}_uploadAsync(e,t,i){const s=this._engine.getCaps(),r={astc:!!s.astc,bptc:!!s.bptc,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,etc1:!!s.etc1};if(ev._WorkerPoolPromise)return ev._WorkerPoolPromise.then((s=>new Promise(((n,o)=>{s.push(((s,a)=>{const l=e=>{s.removeEventListener("error",l),s.removeEventListener("message",h),o(e),a()},h=e=>{if("decoded"===e.data.action){if(s.removeEventListener("error",l),s.removeEventListener("message",h),e.data.success)try{this._createTexture(e.data.decodedData,t,i),n()}catch(e){o({message:e})}else o({message:e.data.msg});a()}};s.addEventListener("error",l),s.addEventListener("message",h),s.postMessage({action:"setDefaultDecoderOptions",options:ev.DefaultDecoderOptions._getKTX2DecoderOptions()});const c=new Uint8Array(e.byteLength);c.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),s.postMessage({action:"decode",data:c,caps:r,options:i},[c.buffer])}))}))));if(ev._DecoderModulePromise)return ev._DecoderModulePromise.then((i=>(ev.DefaultDecoderOptions.isDirty&&(ev._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=ev.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise(((r,n)=>{i.decode(e,s).then((e=>{this._createTexture(e,t),r()})).catch((e=>{n({message:e})}))})))));throw new Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let s=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,s=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw new Error("KTX2 container - could not transcode the data. "+e.errors);for(let i=0;i=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}ev.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null},ev.DefaultNumWorkers=ev.GetDefaultNumWorkers(),ev.DefaultDecoderOptions=new Jg;class tv{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,s){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const r=t.getEngine(),n=new Xg(e,6),o=n.numberOfMipmapLevels>1&&t.generateMipMaps;r._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,r._setCubeMapTextureParams(t,o,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}loadData(e,t,i,s){if(Xg.IsValid(e)){t._invertVScale=!t.invertY;const s=new Xg(e,1),r=function(e){switch(e){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}(s.glInternalFormat);r?(t.format=r,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=s.glInternalFormat,i(s.pixelWidth,s.pixelHeight,t.generateMipMaps,!0,(()=>{s.uploadLevels(t,t.generateMipMaps)}),s.isInvalid)}else ev.IsValid(e)?new ev(t.getEngine())._uploadAsync(e,t,s).then((()=>{i(t.width,t.height,t.generateMipMaps,!0,(()=>{}),!1)}),(e=>{Ne.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,(()=>{}),!0)})):(Ne.Error("texture missing KTX identifier"),i(0,0,!1,!1,(()=>{}),!0))}}oo._TextureLoaders.push(new tv);class iv extends ac{constructor(e,t,i){super(e,_e.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=fe.Identity(),this._referencedPosition=new _e,this._trackingState=Su.NOT_TRACKING,this.onXRCameraInitializedObservable=new K,this.onBeforeCameraTeleport=new K,this.onAfterCameraTeleport=new K,this.onTrackingStateChanged=new K,this.compensateOnFirstFrame=!0,this._rotate180=new fe(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new fe,this.cameraRigMode=In.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add((()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame,this._xrSessionManager.onWorldScaleFactorChangedObservable.add((()=>{this._xrSessionManager.currentFrame&&this._updateDepthNearFar()}))})),this._xrSessionManager.onXRFrameObservable.add((()=>{this._firstFrame&&this._updateFromXRSession(),this.onXRCameraInitializedObservable.hasObservers()&&(this.onXRCameraInitializedObservable.notifyObservers(this),this.onXRCameraInitializedObservable.clear()),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()}),void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y*this._xrSessionManager.worldScalingFactor:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new Pn(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new Pn(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){e&&e!==this&&(e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,fe.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace())}getClassName(){return"WebXRCamera"}setTarget(e){const t=ve.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),fe.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateDepthNearFar(){const e=(this.maxZ||1e4)*this._xrSessionManager.worldScalingFactor,t={depthFar:e,depthNear:this.minZ};this._xrSessionManager.updateRenderState(t),this._cache.minZ=this.minZ,this._cache.maxZ=e}_updateFromXRSession(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e)return void this._setTrackingState(Su.NOT_TRACKING);const t=e.emulatedPosition?Su.TRACKING_LOST:Su.TRACKING;if(this._setTrackingState(t),this.minZ===this._cache.minZ&&this.maxZ===this._cache.maxZ||this._updateDepthNearFar(),e.transform){const t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;const i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._referenceQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach(((e,t)=>{const i=this.rigCameras[t];i.isLeftCamera||i.isRightCamera||("right"===e.eye?i._isRightCamera=!0:"left"===e.eye&&(i._isLeftCamera=!0));const s=this.getScene().customRenderTargets;for(let e=0;ee;){const e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=ve.Matrix[0],t=ve.Matrix[1],i=ve.Matrix[2];me.ComposeToRef(iv._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),me.ComposeToRef(iv._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);const s=new XRRigidTransform({x:this._referencedPosition.x/this._xrSessionManager.worldScalingFactor,y:this._referencedPosition.y/this._xrSessionManager.worldScalingFactor,z:this._referencedPosition.z/this._xrSessionManager.worldScalingFactor},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(s)}}}iv._ScaleReadOnly=_e.One();class sv{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new K,this.onStateChangedObservable=new K,this.state=yu.NOT_IN_XR,this.sessionManager=new Tu(e),this.camera=new iv("webxr",e,this.sessionManager),this.featuresManager=new Za(this.sessionManager),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}static CreateAsync(e){const t=new sv(e);return t.sessionManager.initializeAsync().then((()=>(t._supported=!0,t))).catch((e=>{throw t._setState(yu.NOT_IN_XR),t.dispose(),e}))}dispose(){this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),this._spectatorCamera?.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),s={}){if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(yu.ENTERING_XR),"viewer"!==t&&"local"!==t&&(s.optionalFeatures=s.optionalFeatures||[],s.optionalFeatures.push(t)),s=await this.featuresManager._extendXRSessionInitObject(s),"immersive-ar"===e&&"unbounded"!==t&&Ne.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,s),await this.sessionManager.setReferenceSpaceTypeAsync(t);const r={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};if(!this.featuresManager.getEnabledFeature(qa.LAYERS)){const e=await i.initializeXRLayerAsync(this.sessionManager.session);r.baseLayer=e}return this.sessionManager.updateRenderState(r),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!this._nonVRCamera?.inputs?.attachedToElement,this._nonVRCamera?.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),this.sessionManager.onXRSessionEnded.addOnce((()=>{this.state!==yu.EXITING_XR&&this._setState(yu.EXITING_XR),this.camera.rigCameras.forEach((e=>{e.outputRenderTarget=null})),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(yu.NOT_IN_XR)})),this.sessionManager.onXRFrameObservable.addOnce((()=>{this._setState(yu.IN_XR)})),this.sessionManager}catch(e){throw Ne.Log(e),Ne.Log(e.message),this._setState(yu.NOT_IN_XR),e}}exitXRAsync(){return this.state!==yu.IN_XR?Promise.resolve():(this._setState(yu.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){const t=1/(e?.fps?e.fps:1e3)*1e3,i=e?.preferredCameraIndex?e?.preferredCameraIndex:0,s=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=t&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[i].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[i].absoluteRotation))};if(this._spectatorMode){if(i>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const e=()=>{this.state===yu.IN_XR?(this._spectatorCamera=new bc("webxr-spectator",_e.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new fe,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(s),this._scene.onAfterRenderCameraObservable.add((e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)}))):this.state===yu.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=null)};this.onStateChangedObservable.add(e),e()}else this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class rv{constructor(e,t,i=-1,s=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=s,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new K,this.onButtonStateChangedObservable=new K}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return 0!==this._axesIndices.length}isButton(){return-1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){const i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}}rv.BUTTON_TYPE="button",rv.SQUEEZE_TYPE="squeeze",rv.THUMBSTICK_TYPE="thumbstick",rv.TOUCHPAD_TYPE="touchpad",rv.TRIGGER_TYPE="trigger";class nv{constructor(e,t,i,s,r=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=s,this._doNotLoadControllerMesh=r,this._controllerCache=n,this._initComponent=e=>{if(!e)return;const t=this.layout.components[e],i=t.type,s=t.gamepadIndices.button,r=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&r.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new rv(e,i,s,r)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new K,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach((e=>this.getComponent(e).dispose())),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach((e=>{e.setEnabled(!1)})),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map((e=>this.components[e])).filter((t=>t.type===e))}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){const e=!this._getModelLoadingConstraints();let t=this._getGenericFilenameAndPath();return e?Ne.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise(((i,s)=>{const r=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const e=this._controllerCache.filter((e=>e.filename===t.filename&&e.path===t.path));if(e[0])return e[0].meshes.forEach((e=>e.setEnabled(!0))),void r(e[0].meshes)}fl.ImportMesh("",t.path,t.filename,this.scene,(e=>{this._controllerCache&&this._controllerCache.push({...t,meshes:e}),r(e)}),null,((e,i)=>{Ne.Log(i),Ne.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),s(i)}))}))}updateFromXRFrame(e){this.getComponentIds().forEach((e=>this.getComponent(e).update(this.gamepadObject))),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren((e=>e.name===t),!1)[0]}_getImmediateChildByName(e,t){return e.getChildren((e=>e.name==t),!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh)return;if(!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;const s=i?.5*t+.5:t;fe.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,s,e.valueMesh.rotationQuaternion),_e.LerpToRef(e.minMesh.position,e.maxMesh.position,s,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new ha(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))})),this.rootMesh.rotationQuaternion=fe.FromEulerAngles(0,Math.PI,0)}}class ov extends nv{constructor(e,t,i){super(e,av[i],t,i),this.profileId=ov.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new ha(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)})),this.rootMesh.rotationQuaternion=fe.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}ov.ProfileId="generic-trigger";const av={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};class lv extends nv{constructor(e,t,i,s,r){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,r),this._repositoryUrl=s,this.controllerCache=r,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach((e=>{this._touchDots[e].dispose()}))}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){const e=fl.IsPluginForExtensionAvailable(".glb");return e||Ne.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach((i=>{const s=t.visualResponses[i];if("transform"===s.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s.valueNodeName),minMesh:this._getChildByName(this.rootMesh,s.minNodeName),maxMesh:this._getChildByName(this.rootMesh,s.maxNodeName)};else{const r=t.type===rv.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:s.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r)},t.type===rv.TOUCHPAD_TYPE&&!this._touchDots[i]){const t=_d(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new cu(i+"mat",this.scene),t.material.diffuseColor=Ee.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}}))}))}_setRootMesh(e){let t;this.rootMesh=new ha(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i{const t=this.getComponent(e);if(!t.hasChanges)return;const i=this._buttonMeshMapping[e],s=this.layout.components[e];Object.keys(s.visualResponses).forEach((e=>{const r=s.visualResponses[e];let n=t.value;if("xAxis"===r.componentProperty?n=t.axes.x:"yAxis"===r.componentProperty&&(n=t.axes.y),"transform"===r.valueNodeProperty)this._lerpTransform(i.states[e],n,"button"!==r.componentProperty);else{const s=i.states[e].valueMesh;s&&(s.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}}))}))}}const hv=[];class cv{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){const t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){const s=[];i&&s.push(i),s.push(...e.profiles||[]),s.length&&!s[0]&&s.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&s.push("oculus-touch-v2");const r=s.indexOf("windows-mixed-reality");if(-1!==r&&s.splice(r,0,"microsoft-mixed-reality"),s.length||s.push("generic-trigger"),this.UseOnlineRepository){const i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,r=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,s,e,t).catch((()=>r.call(this,s,e,t)))}return this._LoadProfilesFromAvailableControllers(s,e,t)}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=Ds.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then((e=>JSON.parse(e))),this._ProfilesList}static ClearControllerCache(){hv.forEach((e=>{e.meshes.forEach((e=>{e.dispose(!1,!0)}))})),hv.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then((()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList())).then((t=>{for(let i=0;i(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=Ds.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then((e=>JSON.parse(e)))),this._ProfileLoadingPromises[e]))).then((e=>new lv(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:hv)))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let s=0;snew ov(t,e.gamepad,e.handedness))),cv.DefaultFallbacks();let uv=0;class dv{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new _e,this._disposed=!1,this.onDisposeObservable=new K,this.onMeshLoadedObservable=new K,this.onMotionControllerInitObservable=new K,this._uniqueId=`controller-${uv++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new _o(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new fe,this.inputSource.gripSpace&&(this.grip=new _o(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new fe),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&cv.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then((e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then((e=>{e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach((e=>e.renderingGroupId=this._options.renderingGroupId))),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&this.motionController?.dispose()}))}),(()=>{Ds.Warn("Could not find a matching motion controller for the registered input source")}))}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){const i=t&&this.grip?this.grip:this.pointer;_e.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i,s){const r=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=r,r){const e=r.transform.position;this.pointer.position.set(e.x,e.y,e.z).scaleInPlace(s.worldScalingFactor);const t=r.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent,this.pointer.scaling.setAll(s.worldScalingFactor)}if(this.inputSource.gripSpace&&this.grip){const r=e.getPose(this.inputSource.gripSpace,t);if(r){const e=r.transform.position,t=r.transform.orientation;this.grip.position.set(e.x,e.y,e.z).scaleInPlace(s.worldScalingFactor),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent,this.grip.scaling.setAll(s.worldScalingFactor)}this.motionController&&this.motionController.updateFromXRFrame(e)}}class _v{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new K,this.onControllerRemovedObservable=new K,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add((()=>{this._addAndRemoveControllers([],this.controllers.map((e=>e.inputSource)))})),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add((e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)})),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add((e=>{this.controllers.forEach((t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera,this.xrSessionManager)}))})),this._options.customControllersRepositoryURL&&(cv.BaseRepositoryUrl=this._options.customControllersRepositoryURL),cv.UseOnlineRepository=!this._options.disableOnlineControllerRepository,cv.UseOnlineRepository)try{cv.UpdateProfilesList().catch((()=>{cv.UseOnlineRepository=!1}))}catch(e){cv.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map((e=>e.inputSource));for(const t of e)if(-1===i.indexOf(t)){const e=new dv(this.xrSessionManager.scene,t,{...this._options.controllerOptions||{},forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation});this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}const s=[],r=[];this.controllers.forEach((e=>{-1===t.indexOf(e.inputSource)?s.push(e):r.push(e)})),this.controllers=s,r.forEach((e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()}))}dispose(){this.controllers.forEach((e=>{e.dispose()})),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),cv.ClearControllerCache()}}class pv extends Ja{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;const{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(this._options.forceGripIfAvailable&&e.grip?e.grip:e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new Ua(new _e,new _e),disabledByNearInteraction:!1,id:pv._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":case"transient-pointer":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new _e,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new Ee(.9,.9,.9),this.laserPointerDefaultColor=new Ee(.7,.7,.7),this.selectionMeshDefaultColor=new Ee(.8,.8,.8),this.selectionMeshPickedColor=new Ee(.3,.3,1),this._identityMatrix=me.Identity(),this._screenCoordinatesRef=_e.Zero(),this._viewportRef=new Pn(0,0,0,0),this._scene=this._xrSessionManager.scene,void 0===this._options.lookAndPickMode&&(this._scene.getEngine()._badDesktopOS||this._scene.getEngine()._badOS)&&(this._options.lookAndPickMode=!0),this._options.lookAndPickMode&&(this._options.enablePointerSelectionOnAllControllers=!0,this.displayLaserPointer=!1)}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController,!0),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)}),!0),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){const e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new Ua(new _e,new _e),disabledByNearInteraction:!1,id:pv._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i{const t=this._controllers[e];if(this._options.lookAndPickMode&&"transient-pointer"!==t.xrController?.inputSource.targetRayMode)return;if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||t.disabledByNearInteraction)return t.selectionMesh.isVisible=!1,t.laserPointer.isVisible=!1,void(t.pick=null);let i;if(t.laserPointer.isVisible=this.displayLaserPointer,t.xrController)i=this._options.forceGripIfAvailable&&t.xrController.grip?t.xrController.grip.position:t.xrController.pointer.position,t.xrController.getWorldPointerRayToRef(t.tmpRay,this._options.forceGripIfAvailable);else{if(!t.webXRCamera)return;i=t.webXRCamera.position,t.webXRCamera.getForwardRayToRef(t.tmpRay)}if(this._options.maxPointerDistance&&(t.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&i){const e=this._xrSessionManager.scene,s=this._options.xrInput.xrCamera;s&&(s.viewport.toGlobalToRef(e.getEngine().getRenderWidth()/s.rigCameras.length,e.getEngine().getRenderHeight(),this._viewportRef),_e.ProjectToRef(i,this._identityMatrix,s.getTransformationMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||this._screenCoordinatesRef.x===1/0||this._screenCoordinatesRef.y===1/0||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,t.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let s=null;this._utilityLayerScene&&(s=this._utilityLayerScene.pickWithRay(t.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const r=this._scene.pickWithRay(t.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);s&&s.hit?r&&r.hit?s.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit)if(this._pickingMoved(r,t.pick))a&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,l)),a=!1,o=0;else if(o>i/10&&(n.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,l),a=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),n.isVisible=!1;else{const e=1-o/i;n.scaling.set(e,e,e)}else a=!1,o=0;this._scene.simulatePointerMove(t.pick,l),r=t.pick}})),void 0!==this._options.renderingGroupId&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce((()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&a&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),n.dispose()}))}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const s={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),!t.pick||this._options.disablePointerUpOnTouchOut&&i||(i?this._scene.simulatePointerMove(t.pick,s):(this._scene.simulatePointerDown(t.pick,s),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,s)))})),e.onDisposeObservable.addOnce((()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame((()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,s),t.finalPointerUpTriggered=!0)}))}))}_attachTrackedPointerRayMode(e){const t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);const i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))})),e.inputSource.gamepad){const s=s=>{this._options.overrideButtonId&&(t.selectionComponent=s.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=s.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((s=>{if(s.changes.pressed){const r=s.changes.pressed.current;if(t.pick)(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),r?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor));else if(r&&!this._options.enablePointerSelectionOnAllControllers&&!this._options.disableSwitchOnClick){const t=this._controllers[this._attachedController];t&&t.pointerDownTriggered&&!t.finalPointerUpTriggered&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerUp(new tr,{pointerId:t.id,pointerType:"xr"}),t.finalPointerUpTriggered=!0),this._attachedController=e.uniqueId}}}))};e.motionController?s(e.motionController):e.onMotionControllerInitObservable.add(s)}else{const e=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)}))},s=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)}))};t.eventListeners={selectend:s,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",s)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(_e.Dot(e,t.direction)){const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),!t.finalPointerUpTriggered&&t.pointerDownTriggered){const e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame((()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new tr,e),t.finalPointerUpTriggered=!0}))}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce((()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){Ds.Warn("controller already detached.")}}))}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Ju.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():$u("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const s=new cu("laserPointerMat",t);s.emissiveColor=this.laserPointerDefaultColor,s.alpha=.7,i.material=s,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const r=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():wu("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);r.bakeCurrentTransformIntoVertices(),r.isPickable=!1,r.isVisible=!1;const n=new cu("targetMat",t);return n.specularColor=Ee.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,r.material=n,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:r}}_pickingMoved(e,t){if(!e.hit||!t.hit)return!0;if(!(e.pickedMesh&&e.pickedPoint&&t.pickedMesh&&t.pickedPoint))return!0;if(e.pickedMesh!==t.pickedMesh)return!0;e.pickedPoint?.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const i=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance;return this._tmpVectorForPickCompare.length()>i}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}}var fv,mv,gv;pv._IdCounter=200,pv.Name=qa.POINTER_SELECTION,pv.Version=1,Za.AddWebXRFeature(pv.Name,((e,t)=>()=>new pv(e,t)),pv.Version,!0),Gn.prototype._projectOnTrianglesToRef=function(e,t,i,s,r,n){const o=ve.Vector3[0],a=ve.Vector3[1];let l=1/0;for(let n=this.indexStart;n{if(this._controllers[e.uniqueId])return;const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s}=this._generateNewTouchPointMesh(),r=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s,currentAnimationState:fv.DEHYDRATED,grabRay:new Ua(new _e,new _e),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,downTriggered:!1,id:vv._IdCounter++,pickedPointVisualCue:r},this._controllers[e.uniqueId]._worldScaleObserver=this._controllers[e.uniqueId]._worldScaleObserver||this._xrSessionManager.onWorldScaleFactorChangedObservable.add((t=>{if(t.newScaleFactor!==t.previousScaleFactor){this._controllers[e.uniqueId].touchCollisionMesh.dispose(),this._controllers[e.uniqueId].pickedPointVisualCue.dispose();const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s}=this._generateNewTouchPointMesh();this._controllers[e.uniqueId].touchCollisionMesh=t,this._controllers[e.uniqueId].touchCollisionMeshFunction=i,this._controllers[e.uniqueId].hydrateCollisionMeshFunction=s,this._controllers[e.uniqueId].pickedPointVisualCue=this._generateVisualCue()}})),this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new Ee(.8,.8,.8),this.selectionMeshPickedColor=new Ee(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=mv.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;ie.currentAnimationState)switch(e.currentAnimationState){case fv.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===fv.HOVER)break;case fv.HOVER:if(e.touchCollisionMeshFunction(!0),t===fv.TOUCH)break}else switch(e.currentAnimationState){case fv.TOUCH:if(e.touchCollisionMeshFunction(!1),t===fv.HOVER)break;case fv.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===fv.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){const s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(ve.Vector3[0]),s.grabRay.direction.copyFrom(ve.Vector3[0]),this._options.nearInteractionControllerMode!==mv.CENTERED_IN_FRONT||s.xrController?.inputSource.hand||(s.xrController.getWorldPointerRayToRef(this._tmpRay),s.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),s.grabRay.length=this._nearGrabLengthScale*this._hoverRadius*this._xrSessionManager.worldScalingFactor,s.touchCollisionMesh.position.copyFrom(s.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor)}_onXRFrame(e){Object.keys(this._controllers).forEach((t=>{const i=this._controllers[t],s=i.xrController?.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!i.xrController||!s&&(!this._options.nearInteractionControllerMode||!i.xrController.inputSource.gamepad))return void(i.pick=null);if(i.hoverInteraction=!1,i.nearInteraction=!1,!i.xrController)return;if(s){const i=s.get("index-finger-tip");if(i){const s=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(s&&s.transform){const e=this._scene.useRightHandedSystem?1:-1;ve.Vector3[0].set(s.transform.position.x,s.transform.position.y,s.transform.position.z*e),ve.Quaternion[0].set(s.transform.orientation.x,s.transform.orientation.y,s.transform.orientation.z*e,s.transform.orientation.w*e),this._processTouchPoint(t,ve.Vector3[0],ve.Quaternion[0])}}}else if(i.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==mv.DISABLED){let e=i.xrController.pointer;i.xrController.grip&&this._options.nearInteractionControllerMode===mv.CENTERED_ON_CONTROLLER&&(e=i.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}const r=(e,t)=>{let i=null;return i=t&&t.hit?e&&e.hit?t.distance{let t=new tr,i=!1;const s=e&&e.pickedPoint&&e.hit;return e?.pickedPoint&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),s&&!i&&(t=e),t};if(!i.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._utilityLayerScene,(e=>this._nearInteractionPredicate(e))));const o=r(this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._scene,(e=>this._nearInteractionPredicate(e))),t);if(o&&o.hit&&(e=n(o),e.hit&&(i.hoverInteraction=!0)),i.hoverInteraction){let t=null;const o=(s?this._pickRadius:this._controllerPickRadius)*this._xrSessionManager.worldScalingFactor;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,o,this._utilityLayerScene,(e=>this._nearPickPredicate(e))));const a=n(r(this._pickWithSphere(i,o,this._scene,(e=>this._nearPickPredicate(e))),t));a.hit&&(e=a,i.nearInteraction=!0)}i.stalePick=i.pick,i.pick=e,i.pick&&i.pick.pickedPoint&&i.pick.hit?(i.meshUnderPointer=i.pick.pickedMesh,i.pickedPointVisualCue.position.copyFrom(i.pick.pickedPoint),i.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!0)):(i.meshUnderPointer=null,i.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!1))}let o=fv.DEHYDRATED;i.grabInteraction||i.nearInteraction?o=fv.TOUCH:i.hoverInteraction&&(o=fv.HOVER),this._handleTransitionAnimation(i,o)}))}get _utilityLayerScene(){return this._options.customUtilityLayerScene||Ju.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Ju.DefaultUtilityLayer.utilityLayerScene:this._scene,t=_d("nearInteraction",{diameter:.0105*this._xrSessionManager.worldScalingFactor},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=fe.Identity();const i=new cu("targetMat",e);return i.specularColor=Ee.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer,t.downTriggered=!0):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.downTriggered=!1,t.nearInteractionTargetMesh=null))}));const s=s=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),s&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0):!s&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.downTriggered=!1,t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!s||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const i=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;s(t)}})):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;s(t)}})))};e.motionController?i(e.motionController):e.onMotionControllerInitObservable.add(i)}else{const e=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0)},s=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0,t.downTriggered=!1)};t.eventListeners={selectend:s,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",s)}}_detachController(e){const t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach((e=>{const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame((()=>{if(!t.downTriggered)return;const e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new tr,e)})),t._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(t._worldScaleObserver),delete this._controllers[e],this._attachedController===e)){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){const e=this._xrSessionManager.worldScalingFactor,t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Ju.DefaultUtilityLayer.utilityLayerScene:this._scene,i=_d("PickSphere",{diameter:1*e},t);if(i.isVisible=!1,this._options.motionControllerOrbMaterial)i.material=this._options.motionControllerOrbMaterial;else{let e;e=this._options.motionControllerTouchMaterialSnippetUrl?hh.ParseFromFileAsync("motionControllerTouchMaterial",this._options.motionControllerTouchMaterialSnippetUrl,t):hh.ParseFromSnippetAsync("8RUNKL#3",t),e.then((e=>{i.material=e})).catch((e=>{Ne.Warn(`Error creating touch material in WebXRNearInteraction: ${e}`)}))}const s=new cn;s.setEasingMode(tn.EASINGMODE_EASEINOUT);const r=new _e(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius).scaleInPlace(e),n=this._controllerPickRadius*(4/3),o=new _e(n,n,n).scaleInPlace(e),a=this._controllerPickRadius*(7/6),l=new _e(a,a,a).scaleInPlace(e),h=.8*this._controllerPickRadius,c=new _e(h,h,h).scaleInPlace(e),u=1.5*this._controllerPickRadius,d=[{frame:0,value:r},{frame:10,value:new _e(u,u,u).scaleInPlace(e)},{frame:18,value:o}],_=[{frame:0,value:o},{frame:10,value:c},{frame:18,value:r}],p=[{frame:0,value:_e.ZeroReadOnly},{frame:12,value:l},{frame:15,value:r}],f=[{frame:0,value:r},{frame:10,value:_e.ZeroReadOnly},{frame:15,value:_e.ZeroReadOnly}],m=new Ft("touch","scaling",60,Ft.ANIMATIONTYPE_VECTOR3,Ft.ANIMATIONLOOPMODE_CONSTANT),g=new Ft("release","scaling",60,Ft.ANIMATIONTYPE_VECTOR3,Ft.ANIMATIONLOOPMODE_CONSTANT),v=new Ft("hydrate","scaling",60,Ft.ANIMATIONTYPE_VECTOR3,Ft.ANIMATIONLOOPMODE_CONSTANT),x=new Ft("dehydrate","scaling",60,Ft.ANIMATIONTYPE_VECTOR3,Ft.ANIMATIONLOOPMODE_CONSTANT);return m.setEasingFunction(s),g.setEasingFunction(s),v.setEasingFunction(s),x.setEasingFunction(s),m.setKeys(d),g.setKeys(_),v.setKeys(p),x.setKeys(f),{touchCollisionMesh:i,touchCollisionMeshFunction:e=>{const s=e?m:g;t.beginDirectAnimation(i,[s],0,18,!1,1)},hydrateCollisionMeshFunction:e=>{const s=e?v:x;e&&(i.isVisible=!0),t.beginDirectAnimation(i,[s],0,15,!1,1,(()=>{e||(i.isVisible=!1)}))}}}_pickWithSphere(e,t,i,s){const r=new tr;if(r.distance=1/0,e.touchCollisionMesh&&e.xrController){const n=e.touchCollisionMesh.position,o=On.CreateFromCenterAndRadius(n,t);for(let t=0;tc&&(h=0,a.copyFrom(t.center)),-1!==h&&h<_&&(_=h,Ua.CreateFromToToRef(t.center,a,l),l.length=2*_,d=l.intersectsMesh(e),o.copyFrom(a));return _()=>new vv(e,t)),vv.Version,!0);class xv{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class bv{}class Tv{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new K,this._onSessionGranted=e=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw Ds.Warn("WebXR can only be served over HTTPS"),new Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";const e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor";let s=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+("undefined"==typeof SVGSVGElement?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";s+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const r=document.createElement("style");r.appendChild(document.createTextNode(s)),document.getElementsByTagName("head")[0].appendChild(r);const n=document.createElement("button");n.className="babylonVRicon",n.title=`${e} - ${i}`,this._buttons.push(new xv(n,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",n.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}const i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce((()=>{this.dispose()})))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;const i=this._buttons.map((t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode)));e.onStateChangedObservable.add((e=>{e==yu.NOT_IN_XR&&this._updateButtons(null)})),(await Promise.all(i)).forEach(((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):Ds.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)}))}static async CreateAsync(e,t,i){const s=new Tv(e,i);return await s.setHelperAsync(t,i.renderTarget||void 0),s}async _enterXRWithButtonIndex(e=0){if(this._helper.state==yu.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==yu.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(t){this._updateButtons(null);const i=this._buttons[e].element,s=i.title;i.title="Error entering XR session : "+s,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t)}}dispose(){const e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach((e=>{e.update(this._activeButton)})),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}function yv(e){let t=0;const i=Date.now();e.observableParameters=e.observableParameters??{};const s=e.contextObservable.add((r=>{const n=Date.now();t=n-i;const o={startTime:i,currentTime:n,deltaTime:t,completeRate:t/e.timeout,payload:r};e.onTick&&e.onTick(o),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(o)),t>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(o))}),e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return s}!function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(gv||(gv={}));class Sv{constructor(e){this.onEachCountObservable=new K,this.onTimerAbortedObservable=new K,this.onTimerEndedObservable=new K,this.onStateChangedObservable=new K,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{const t=Date.now();this._timer=t-this._startTime;const i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},s=this._breakOnNextTick||this._breakCondition(i);s||this._timer>=this._timeToEnd?this._stop(i,s):this.onEachCountObservable.notifyObservers(i)},this._setState(gv.INIT),this._contextObservable=e.contextObservable,this._observableParameters=e.observableParameters??{},this._breakCondition=e.breakCondition??(()=>!1),this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}set breakCondition(e){this._breakCondition=e}clearObservables(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()}start(e=this._timeToEnd){if(this._state===gv.STARTED)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(gv.STARTED)}stop(){this._state===gv.STARTED&&(this._breakOnNextTick=!0)}dispose(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()}_setState(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)}_stop(e,t=!1){this._contextObservable.remove(this._observer),this._setState(gv.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class Cv extends Ja{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){const t=this._options.teleportationTargetMesh.getChildMeshes(!1,(e=>"rotationCone"===e.name));t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new Ae(1,1,1,1),this._tmpRay=new Ua(new _e,new _e),this._tmpVector=new _e,this._tmpQuaternion=new fe,this._worldScaleObserver=null,this.skipNextTeleportation=!1,this.backwardsMovementEnabled=!0,this.backwardsTeleportationDistance=.7,this.parabolicCheckRadius=5,this.parabolicRayEnabled=!0,this.straightRayEnabled=!0,this.rotationAngle=Math.PI/8,this.onTargetMeshPositionUpdatedObservable=new K,this.teleportationEnabled=!0,this._rotationEnabled=!0,this.onBeforeCameraTeleportRotation=new K,this.onAfterCameraTeleportRotation=new K,this._attachController=e=>{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1,initialHit:!1,mainComponentUsed:!1}};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController){const i=e.motionController.getComponentOfType(rv.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(rv.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){const i=e.motionController.getMainComponent();if(!i)return;t.teleportationState.mainComponentUsed=!0,t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add((()=>{if(!this.teleportationEnabled)return;const s=()=>{t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,yv({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};i.changes.pressed&&(i.changes.pressed.current?this._options.timeToTeleportStart?yv({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{i.pressed&&s()}}):s():(t.teleportationState.forward=!1,this._currentTeleportationControllerId=""))}))}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add((i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,fe.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);const e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,(e=>-1!==this._floorMeshes.indexOf(e)));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout((()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))})):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;const e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this.onBeforeCameraTeleportRotation.notifyObservers(e),fe.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),t.teleportationState.forward&&this._teleportForward(e.uniqueId))}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}else{t.teleportationState.mainComponentUsed=!0;let i=!1;const s=()=>{this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,yv({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};this._xrSessionManager.scene.onPointerObservable.add((e=>{e.type===lr.POINTERDOWN?(i=!1,this._options.timeToTeleportStart?yv({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&s()},breakCondition:()=>!!i&&(i=!1,!0)}):s()):e.type===lr.POINTERUP&&(i=!0,t.teleportationState.forward=!1,this._currentTeleportationControllerId="")}))}},this._colorArray=Array(24).fill(this._cachedColor4White),this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new Ae(1,0,0,.75),this._setTargetMeshVisibility(!1),this.onBeforeCameraTeleport=t.xrInput.xrCamera.onBeforeCameraTeleport,this.onAfterCameraTeleport=t.xrInput.xrCamera.onAfterCameraTeleport,this.parabolicCheckRadius*=this._xrSessionManager.worldScalingFactor,this._worldScaleObserver=e.onWorldScaleFactorChangedObservable.add((e=>{this.parabolicCheckRadius=this.parabolicCheckRadius/e.previousScaleFactor*e.newScaleFactor,this._options.teleportationTargetMesh?.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor)}))}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return!!super.attach()&&(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver)}removeFloorMesh(e){const t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];const t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){const t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(-1===t)for(let i=0;i{if(this._options.blockerMeshesPredicate&&this._options.blockerMeshesPredicate(e))return!0;if(this._options.blockAllPickableMeshes&&e.isPickable)return!0;if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;const t=this._floorMeshes.indexOf(e);return-1!==t&&this._floorMeshes[t].absolutePosition.y!(!this._options.blockerMeshesPredicate||!this._options.blockerMeshesPredicate(e))||!(!this._options.blockAllPickableMeshes||!e.isPickable)||!(!this._options.pickBlockerMeshes||-1===this._options.pickBlockerMeshes.indexOf(e))||-1!==this._floorMeshes.indexOf(e))),l=a&&a.pickedMesh&&-1!==this._floorMeshes.indexOf(a.pickedMesh);if(a&&a.pickedMesh&&!l)return e.teleportationState.mainComponentUsed&&!e.teleportationState.initialHit?void(e.teleportationState.forward=!1):(e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,r),void this._showParabolicPath(a));a&&a.pickedPoint&&(e.teleportationState.initialHit=!0,e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(a),this._setTargetMeshVisibility(!0,!1,r),this._showParabolicPath(a))}this._setTargetMeshVisibility(t,!1,r)}else this._setTargetMeshVisibility(!1,!1,!0)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1,!1,!0)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Ju.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=Iu("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const i=512,s=new uu("teleportationPlaneDynamicTexture",i,e,!0);s.hasAlpha=!0;const r=s.getContext(),n=i/2,o=i/2,a=200;r.beginPath(),r.arc(n,o,a,0,2*Math.PI,!1),r.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",r.fill(),r.lineWidth=10,r.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",r.stroke(),r.closePath(),s.update();const l=new cu("teleportationPlaneMaterial",e);l.diffuseTexture=s,t.material=l}const i=wu("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const t=new Ft("animationInnerCircle","position.y",30,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CYCLE),s=[];s.push({frame:0,value:0}),s.push({frame:30,value:.4}),s.push({frame:60,value:0}),t.setKeys(s);const r=new _n;r.setEasingMode(tn.EASINGMODE_EASEINOUT),t.setEasingFunction(r),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}const s=$u("rotationCone",{diameterTop:0,tessellation:4},e);if(s.isPickable=!1,s.scaling.set(.5,.12,.2),s.rotate(Xr.X,Math.PI/2),s.position.z=.6,s.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,s.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const t=new cu("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new Ee(.3,.3,1):t.diffuseColor=new Ee(.3,.3,1),t.alpha=.9,i.material=t,s.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._options.teleportationTargetMesh.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._setTargetMeshVisibility(!1)}_detachController(e){const t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,s=Number.MAX_VALUE;if(this._snapToPositions.length){const r=t*t;this._snapToPositions.forEach((t=>{const n=_e.DistanceSquared(t,e);n<=r&&n{t.isVisible=e})),e?this._selectionFeature&&i&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&i&&this._selectionFeature.attach()))}_disposeBezierCurve(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Ju.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],s=en.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),r=i.teleportationState.blocked?this._blockedRayColor:void 0,n=this._colorArray.fill(r||this._cachedColor4White),o=s.getPoints();o.shift(),o.shift(),this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(s.getPoints(),e):this._quadraticBezierCurve=Ud("teleportation path line",{points:o,instance:this._quadraticBezierCurve,updatable:!0,colors:n},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){const t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint))if(this.skipNextTeleportation)this.skipNextTeleportation=!1;else if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){const e=this._options.xrInput.xrCamera.realWorldHeight;this.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=e,fe.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}Cv.Name=qa.TELEPORTATION,Cv.Version=1,Za.AddWebXRFeature(Cv.Name,((e,t)=>()=>new Cv(e,t)),Cv.Version,!0);class Ev{}class Av{constructor(){}static CreateAsync(e,t={}){const i=new Av;if(e.onDisposeObservable.addOnce((()=>{i.dispose()})),!t.disableDefaultUI){const s={renderTarget:i.renderTarget,...t.uiOptions||{}};t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?s.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:s.optionalFeatures=t.optionalFeatures),i.enterExitUI=new Tv(e,s)}return sv.CreateAsync(e).then((e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new _v(e.sessionManager,e.camera,{controllerOptions:{renderingGroupId:t.renderingGroupId},...t.inputOptions||{}}),!t.disablePointerSelection){const e={...t.pointerSelectionOptions,xrInput:i.input,renderingGroupId:t.renderingGroupId};i.pointerSelection=i.baseExperience.featuresManager.enableFeature(pv.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(Cv.Name,t.useStablePlugins?"stable":"latest",{floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId,...t.teleportationOptions}),i.teleportation.setSelectionFeature(i.pointerSelection))}return t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(vv.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0,...t.nearInteractionOptions})),t.disableHandTracking||i.baseExperience.featuresManager.enableFeature(vh.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,...t.handSupportOptions},void 0,!1),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)})).then((()=>i)).catch((e=>(Ne.Error("Error initializing XR"),Ne.Error(e),i)))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}var Pv=!0;function Iv(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}Hr.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;ee.isVisible&&e.isEnabled())),s=t.max.subtract(t.min),r=t.min.add(s.scale(.5));let n,o=1.5*s.length();if(isFinite(o)||(o=1,r.copyFromFloats(0,0,0)),e){const e=new hc("default camera",-Math.PI/2,Math.PI/2,o,r,this);e.lowerRadiusLimit=.01*o,e.wheelPrecision=100/o,n=e}else{const e=new ac("default camera",new _e(r.x,r.y,-o),this);e.setTarget(r),n=e}n.minZ=.01*o,n.maxZ=1e3*o,n.speed=.2*o,this.activeCamera=n,i&&n.attachControl()}},Hr.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},Hr.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,s=0,r=!0){if(!e)return Ne.Warn("Can not create default skybox without environment texture."),null;r&&e&&(this.environmentTexture=e);const n=cd("hdrSkyBox",{size:i},this);if(t){const t=new zg("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Pa.SKYBOX_MODE),t.microSurface=1-s,t.disableLighting=!0,t.twoSidedLighting=!0,n.material=t}else{const t=new cu("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Pa.SKYBOX_MODE),t.disableLighting=!0,n.material=t}return n.isPickable=!1,n.infiniteDistance=!0,n.ignoreCameraMaxZ=!0,n},Hr.prototype.createDefaultEnvironment=function(e){return Tg?new Tg(e,this):null},Hr.prototype.createDefaultVRExperience=function(e={}){return new ku(this,e)},Hr.prototype.createDefaultXRExperienceAsync=function(e={}){return Av.CreateAsync(this,e).then((e=>e))};class Rv extends Pa{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new K),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e?.message):Ne.Error(e?.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch((e=>{if("NotAllowedError"===e?.name){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers())return void this._onUserActionRequestedObservable.notifyObservers(this);if(!this.video.muted)return Ne.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,void this.video.play().catch((e=>{this._processError(e)}))}this._processError(e)}))}constructor(e,t,i,s=!1,r=!1,n=Pa.TRILINEAR_SAMPLINGMODE,o={},a,l=5){super(null,i,!s,r),this._externalTexture=null,this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||Ds.IsExponentOfTwo(this.video.videoWidth)&&Ds.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=Pa.WRAP_ADDRESSMODE,this.wrapV=Pa.WRAP_ADDRESSMODE):(this.wrapU=Pa.CLAMP_ADDRESSMODE,this.wrapV=Pa.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=this._format??5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(null!=this._texture){if(!this._displayingPosterTexture)return;this._displayingPosterTexture=!1}if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{const e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture)return;if(this.video.readyState=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&u?u&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return Ds.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return"string"==typeof e?(Ds.SetCorsBehavior(e,t),t.src=e):(Ds.SetCorsBehavior(e[0],t),e.forEach((e=>{const i=document.createElement("source");i.src=e,t.appendChild(i)}))),this.onDisposeObservable.addOnce((()=>{Iv(t)})),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))}get externalTexture(){return this._externalTexture}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new Rv(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("loadeddata",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),this._externalTexture?.dispose()}static CreateFromStreamAsync(e,t,i,s=!0){const r=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(r),r.style.transform="scale(0.0001, 0.0001)",r.style.opacity="0",r.style.position="fixed",r.style.bottom="0px",r.style.right="0px"),r.setAttribute("autoplay",""),r.setAttribute("muted","true"),r.setAttribute("playsinline",""),r.muted=!0,r.isNative||(void 0!==r.mozSrcObject?r.mozSrcObject=t:"object"==typeof r.srcObject?r.srcObject=t:r.src=window.URL&&window.URL.createObjectURL(t)),new Promise((t=>{const i=()=>{const n=new Rv("video",r,e,!0,s,void 0,void 0,void 0,4);e.getEngine()._badOS&&n.onDisposeObservable.addOnce((()=>{r.remove()})),n.onDisposeObservable.addOnce((()=>{Iv(r)})),t(n),r.removeEventListener("playing",i)};r.addEventListener("playing",i),r.play()}))}static async CreateFromWebCamAsync(e,t,i=!1,s=!0){if(navigator.mediaDevices){const r=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,r,t,s);return n.onDisposeObservable.addOnce((()=>{r.getTracks().forEach((e=>{e.stop()}))})),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,s=!1,r=!0){this.CreateFromWebCamAsync(e,i,s,r).then((function(e){t&&t(e)})).catch((function(e){Ne.Error(e.name)}))}}Ze([rt("settings")],Rv.prototype,"_settings",void 0),Ze([rt("src")],Rv.prototype,"_currentSrc",void 0),Ze([rt()],Rv.prototype,"isVideo",void 0),Pa._CreateVideoTexture=(e,t,i,s=!1,r=!1,n=Pa.TRILINEAR_SAMPLINGMODE,o={},a,l=5)=>new Rv(e,t,i,s,r,n,o,a,l),z("BABYLON.VideoTexture",Rv);class Mv extends yg{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const s={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},r=new Rv((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,Pa.TRILINEAR_SAMPLINGMODE,s);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add((e=>{e.pickInfo?.pickedMesh===this.mesh&&this._texture.video.play()}),lr.POINTERDOWN)),this._textureObserver=r.onLoadObservable.add((()=>{this.onLoadObservable.notifyObservers()})),r}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}Mv.MODE_MONOSCOPIC=yg.MODE_MONOSCOPIC,Mv.MODE_TOPBOTTOM=yg.MODE_TOPBOTTOM,Mv.MODE_SIDEBYSIDE=yg.MODE_SIDEBYSIDE;class Ov{get gpuFrameTimeCounter(){return this.engine.getGPUFrameTimeCounter()}get captureGPUFrameTime(){return this._captureGPUFrameTime}set captureGPUFrameTime(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,this.engine.captureGPUFrameTime(e))}get shaderCompilationTimeCounter(){return this._shaderCompilationTime}get captureShaderCompilationTime(){return this._captureShaderCompilationTime}set captureShaderCompilationTime(e){e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add((()=>{this._shaderCompilationTime.fetchNewFrame(),this._shaderCompilationTime.beginMonitoring()})),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add((()=>{this._shaderCompilationTime.endMonitoring()}))):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))}constructor(e){this.engine=e,this._captureGPUFrameTime=!1,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new wr,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}dispose(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null}}class Dv{get activeMeshesEvaluationTimeCounter(){return this._activeMeshesEvaluationTime}get captureActiveMeshesEvaluationTime(){return this._captureActiveMeshesEvaluationTime}set captureActiveMeshesEvaluationTime(e){e!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=e,e?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add((()=>{Ds.StartPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.beginMonitoring()})),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add((()=>{Ds.EndPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.endMonitoring(!1)}))):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))}get renderTargetsRenderTimeCounter(){return this._renderTargetsRenderTime}get captureRenderTargetsRenderTime(){return this._captureRenderTargetsRenderTime}set captureRenderTargetsRenderTime(e){e!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=e,e?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add((()=>{Ds.StartPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.beginMonitoring()})),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add((()=>{Ds.EndPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))}get particlesRenderTimeCounter(){return this._particlesRenderTime}get captureParticlesRenderTime(){return this._captureParticlesRenderTime}set captureParticlesRenderTime(e){e!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=e,e?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add((()=>{Ds.StartPerformanceCounter("Particles"),this._particlesRenderTime.beginMonitoring()})),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add((()=>{Ds.EndPerformanceCounter("Particles"),this._particlesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))}get spritesRenderTimeCounter(){return this._spritesRenderTime}get captureSpritesRenderTime(){return this._captureSpritesRenderTime}set captureSpritesRenderTime(e){e!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=e,this.scene.spriteManagers&&(e?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add((()=>{Ds.StartPerformanceCounter("Sprites"),this._spritesRenderTime.beginMonitoring()})),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add((()=>{Ds.EndPerformanceCounter("Sprites"),this._spritesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null)))}get physicsTimeCounter(){return this._physicsTime}get capturePhysicsTime(){return this._capturePhysicsTime}set capturePhysicsTime(e){e!==this._capturePhysicsTime&&this.scene.onBeforePhysicsObservable&&(this._capturePhysicsTime=e,e?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add((()=>{Ds.StartPerformanceCounter("Physics"),this._physicsTime.beginMonitoring()})),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add((()=>{Ds.EndPerformanceCounter("Physics"),this._physicsTime.endMonitoring()}))):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))}get animationsTimeCounter(){return this._animationsTime}get captureAnimationsTime(){return this._captureAnimationsTime}set captureAnimationsTime(e){e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add((()=>{this._animationsTime.endMonitoring()})):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))}get frameTimeCounter(){return this._frameTime}get captureFrameTime(){return this._captureFrameTime}set captureFrameTime(e){this._captureFrameTime=e}get interFrameTimeCounter(){return this._interFrameTime}get captureInterFrameTime(){return this._captureInterFrameTime}set captureInterFrameTime(e){this._captureInterFrameTime=e}get renderTimeCounter(){return this._renderTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add((()=>{this._renderTime.beginMonitoring(),Ds.StartPerformanceCounter("Main render")})),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add((()=>{this._renderTime.endMonitoring(!1),Ds.EndPerformanceCounter("Main render")}))):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))}get cameraRenderTimeCounter(){return this._cameraRenderTime}get captureCameraRenderTime(){return this._captureCameraRenderTime}set captureCameraRenderTime(e){e!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=e,e?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add((e=>{this._cameraRenderTime.beginMonitoring(),Ds.StartPerformanceCounter(`Rendering camera ${e.name}`)})),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add((e=>{this._cameraRenderTime.endMonitoring(!1),Ds.EndPerformanceCounter(`Rendering camera ${e.name}`)}))):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))}get drawCallsCounter(){return this.scene.getEngine()._drawCalls}constructor(e){this.scene=e,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new wr,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new wr,this._captureFrameTime=!1,this._frameTime=new wr,this._captureRenderTime=!1,this._renderTime=new wr,this._captureInterFrameTime=!1,this._interFrameTime=new wr,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new wr,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new wr,this._capturePhysicsTime=!1,this._physicsTime=new wr,this._captureAnimationsTime=!1,this._animationsTime=new wr,this._captureCameraRenderTime=!1,this._cameraRenderTime=new wr,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=e.onBeforeAnimationsObservable.add((()=>{this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.fetchNewFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.fetchNewFrame(),this._captureFrameTime&&(Ds.StartPerformanceCounter("Scene rendering"),this._frameTime.beginMonitoring()),this._captureInterFrameTime&&this._interFrameTime.endMonitoring(),this._captureParticlesRenderTime&&this._particlesRenderTime.fetchNewFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.fetchNewFrame(),this._captureAnimationsTime&&this._animationsTime.beginMonitoring(),this._captureRenderTime&&this._renderTime.fetchNewFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.fetchNewFrame(),this.scene.getEngine()._drawCalls.fetchNewFrame()})),this._onAfterRenderObserver=e.onAfterRenderObservable.add((()=>{this._captureFrameTime&&(Ds.EndPerformanceCounter("Scene rendering"),this._frameTime.endMonitoring()),this._captureRenderTime&&this._renderTime.endMonitoring(!1),this._captureInterFrameTime&&this._interFrameTime.beginMonitoring(),this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.endFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.endFrame(),this._captureParticlesRenderTime&&this._particlesRenderTime.endFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.endFrame(),this._captureRenderTime&&this._renderTime.endFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.endFrame()}))}dispose(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver&&(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null),this._onAfterSpritesRenderingObserver&&(this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null),this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this._onBeforePhysicsObserver&&(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null),this._onAfterPhysicsObserver&&(this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null),this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null}}Bi.ShadersStore.glowMapGenerationPixelShader="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;uniform float glowIntensity;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;varying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform mat4 diffuseMatrix;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform mat4 opacityMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform mat4 emissiveMatrix;\n#endif\n#ifdef VERTEXALPHA\nattribute vec4 color;varying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef CUBEMAP\nvPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*worldPos;gl_Position=vPosition;\n#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef OPACITYUV2\nvUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef VERTEXALPHA\nvColor=color;\n#endif\n#include\n}";class wv{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||0===t)&&e.subMeshes)for(let t=0;t{let r;this.onBeforeRenderMainTextureObservable.notifyObservers(this);const n=this._scene.getEngine();if(s.length){for(n.setColorWrite(!1),r=0;r{e.clear(this.neutralColor,!0,!0,!0)})),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e})),this._mainTexture.onAfterUnbindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=e}))}}_addCustomEffectDefines(e){}_isReady(e,t,i){const s=this._scene.getEngine(),r=e.getMesh(),n=r._internalAbstractMeshDataInfo._materialForRenderPass?.[s.currentRenderPassId];if(n)return n.isReadyForSubMesh(r,e,t);const o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);const a=[],l=[er.PositionKind];let h=!1,c=!1;if(o){const e=o.needAlphaTesting(),t=o.getAlphaTestTexture(),i=t&&t.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);t&&(e||i)&&(a.push("#define DIFFUSE"),r.isVerticesDataPresent(er.UV2Kind)&&1===t.coordinatesIndex?(a.push("#define DIFFUSEUV2"),c=!0):r.isVerticesDataPresent(er.UVKind)&&(a.push("#define DIFFUSEUV1"),h=!0),e&&(a.push("#define ALPHATEST"),a.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||a.push("#define DIFFUSE_ISLINEAR"));const s=o.opacityTexture;s&&(a.push("#define OPACITY"),r.isVerticesDataPresent(er.UV2Kind)&&1===s.coordinatesIndex?(a.push("#define OPACITYUV2"),c=!0):r.isVerticesDataPresent(er.UVKind)&&(a.push("#define OPACITYUV1"),h=!0))}i&&(a.push("#define EMISSIVE"),r.isVerticesDataPresent(er.UV2Kind)&&1===i.coordinatesIndex?(a.push("#define EMISSIVEUV2"),c=!0):r.isVerticesDataPresent(er.UVKind)&&(a.push("#define EMISSIVEUV1"),h=!0),i.gammaSpace||a.push("#define EMISSIVE_ISLINEAR")),r.useVertexColors&&r.isVerticesDataPresent(er.ColorKind)&&r.hasVertexAlpha&&o.transparencyMode!==ta.MATERIAL_OPAQUE&&(l.push(er.ColorKind),a.push("#define VERTEXALPHA")),h&&(l.push(er.UVKind),a.push("#define UV1")),c&&(l.push(er.UV2Kind),a.push("#define UV2"));const u=new Ll;if(r.useBones&&r.computeBonesUsingShaders){l.push(er.MatricesIndicesKind),l.push(er.MatricesWeightsKind),r.numBoneInfluencers>4&&(l.push(er.MatricesIndicesExtraKind),l.push(er.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers);const e=r.skeleton;e&&e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),r.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,r)}else a.push("#define NUM_BONE_INFLUENCERS 0");const d=r.morphTargetManager;let _=0;d&&(_=d.numMaxInfluencers||d.numInfluencers,_>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+_),d.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),Eo(l,r,_))),t&&(a.push("#define INSTANCES"),Po(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),go(o,this._scene,a),this._addCustomEffectDefines(a);const p=e._getDrawWrapper(void 0,!0),f=p.defines,m=a.join("\n");if(f!==m){const e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];mo(e),p.setEffect(this._engine.createEffect("glowMapGeneration",l,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],m,u,void 0,void 0,{maxSimultaneousMorphTargets:_}),m)}return p.effect.isReady()}render(){for(let e=0;eh.setMatrix("world",t)))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(s)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[er.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return Ds.Instantiate(e.customType).Parse(e,t,i)}}wv._SceneComponentInitialization=e=>{throw xt("EffectLayerSceneComponent")},Ze([rt()],wv.prototype,"name",void 0),Ze([dt()],wv.prototype,"neutralColor",void 0),Ze([rt()],wv.prototype,"isEnabled",void 0),Ze([mt()],wv.prototype,"camera",null),Ze([rt()],wv.prototype,"renderingGroupId",null),Ze([rt()],wv.prototype,"disableBoundingBoxesFromEffectLayer",void 0),X.AddParser(or.NAME_EFFECTLAYER,((e,t,i,s)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let r=0;r{this.scene.addEffectLayer(e)}))}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach((e=>{this.scene.removeEffectLayer(e),t&&e.dispose()}))}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,s=this.scene.effectLayers;for(const r of s){if(!r.hasMesh(e))continue;const s=r._mainTexture;this._engine.currentRenderPassId=s.renderPassId;for(const s of e.subMeshes)if(!r.isReady(s,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const s of i)if(s.shouldRender()&&(!s.camera||s.camera.cameraRigMode===In.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==In.RIG_MODE_NONE&&s.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||s.needStencil();const e=s._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i{let t=e._getComponent(or.NAME_EFFECTLAYER);t||(t=new Nv(e),e._addComponent(t))};Bi.ShadersStore.glowMapMergePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);baseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.glowMapMergeVertexShader="attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}",X.prototype.getGlowLayerByName=function(e){for(let t=0;t{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess1=new mg("GlowLayerVBP1",new de(0,1),n,{width:e,height:t},null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new mg("GlowLayerHBP2",new de(1,0),n,{width:s,height:r},null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=s,this._horizontalBlurPostprocess2.height=r,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._blurTexture1)})),this._verticalBlurPostprocess2=new mg("GlowLayerVBP2",new de(0,1),n,{width:s,height:r},null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add((()=>{const e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);const t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(t??e,!0)}})),this._postProcesses.map((e=>{e.autoClear=!1}))}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s)return!1;const r=i.emissiveTexture;return super._isReady(e,t,r)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(ta.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let s=1;this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector?this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color):i.emissiveColor?(s*=i.emissiveIntensity??1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){const e=St.Serialize(this);let t;if(e.customType="BABYLON.GlowLayer",e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew Fv(e.name,t,e.options)),e,t,i);let r;for(r=0;r{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)}))}}class Bv extends wv{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new K,this.onAfterBlurObservable=new K,this._instanceGlowingMeshStencilReference=Bv.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=Bv.NeutralColor,this._engine.isStencilEnable||Ne.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return Bv.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[er.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?Os(e,this._maxSize):e,t=this._engine.needPOTTextures?Os(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new ih("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=Pa.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=Pa.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(Pa.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new yc("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._horizontalBlurPostprocess=new Lv("HighlightLayerHBP",new de(1,0),this._options.blurHorizontalSize,1,null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._verticalBlurPostprocess=new Lv("HighlightLayerVBP",new de(0,1),this._options.blurVerticalSize,1,null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new mg("HighlightLayerHBP",new de(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess=new mg("HighlightLayerVBP",new de(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add((()=>{this.onBeforeBlurObservable.notifyObservers(this);const e=this._blurTexture.renderTarget;e&&(this._scene.postProcessManager.directRender(this._postProcesses,e,!0),this._engine.unBindFramebuffer(e,!0)),this.onAfterBlurObservable.notifyObservers(this)})),this._postProcesses.map((e=>{e.autoClear=!1}))}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s||!this._meshes)return!1;let r=null;const n=this._meshes[s.uniqueId];return n&&n.glowEmissiveOnly&&i&&(r=i.emissiveTexture),super._isReady(e,t,r)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);const i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(ta.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(ta.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return!!super.shouldRender()&&!!this._meshes}_shouldRenderMesh(e){return!(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]||!super.hasMesh(e))}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){const s=this._meshes[e.uniqueId];s?this._emissiveTextureAndColor.color.set(s.color.r,s.color.g,s.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),s&&s.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(this._excludedMeshes&&!this._excludedMeshes[e.uniqueId]){const t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add((e=>{t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)})),t.afterRender=e.onAfterRenderObservable.add((e=>{e.getEngine().setStencilBuffer(t.stencilState)})),this._excludedMeshes[e.uniqueId]=t}}removeExcludedMesh(e){if(!this._excludedMeshes)return;const t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!!this._meshes&&!!super.hasMesh(e)&&void 0!==this._meshes[e.uniqueId]&&null!==this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;const s=this._meshes[e.uniqueId];s?s.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add((e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))})),observerDefault:e.onAfterRenderObservable.add((e=>{this.isEnabled&&this._defaultStencilReference(e)})),glowEmissiveOnly:i},e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;const t=this._meshes[e.uniqueId];t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(const e in this._meshes)if(this._meshes[e]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes)for(const e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){const t=this._meshes[e];t&&this.removeMesh(t.mesh)}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(Bv.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(const e in this._meshes){const t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(const e in this._excludedMeshes){const t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){const e=St.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(const t in this._meshes){const i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(const t in this._excludedMeshes){const i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){const s=St.Parse((()=>new Bv(e.name,t,e.options)),e,t,i);let r;for(r=0;rthis._drawCameraPredicate(t,!0,!0,e.layerMask)))}_drawCameraForegroundWithPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!0,e.layerMask)))}_drawCameraForegroundWithoutPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!1,e.layerMask)))}_drawRenderTargetPredicate(e,t,i,s,r){return e.renderTargetTextures.length>0&&e.isBackground===t&&e.applyPostProcess===i&&e.renderTargetTextures.indexOf(r)>-1&&!!(e.layerMask&s)}_drawRenderTargetBackground(e){this._draw((t=>this._drawRenderTargetPredicate(t,!0,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithoutPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!1,this.scene.activeCamera.layerMask,e)))}addFromContainer(e){e.layers&&e.layers.forEach((e=>{this.scene.layers.push(e)}))}removeFromContainer(e,t=!1){e.layers&&e.layers.forEach((e=>{const i=this.scene.layers.indexOf(e);-1!==i&&this.scene.layers.splice(i,1),t&&e.dispose()}))}}Bi.ShadersStore.layerPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef LINEAR\nbaseColor.rgb=toGammaSpace(baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.layerVertexShader="attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class Vv{set applyPostProcess(e){this._applyPostProcess=e}get applyPostProcess(){return this.isBackground||this._applyPostProcess}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}constructor(e,t,i,s,r){this.name=e,this._applyPostProcess=!0,this.scale=new de(1,1),this.offset=new de(0,0),this.alphaBlendingMode=2,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this.isEnabled=!0,this._vertexBuffers={},this.onDisposeObservable=new K,this.onBeforeRenderObservable=new K,this.onAfterRenderObservable=new K,this.texture=t?new Pa(t,i,!0):null,this.isBackground=void 0===s||s,this.color=void 0===r?new Ae(1,1,1,1):r,this._scene=i||re.LastCreatedScene;let n=this._scene._getComponent(or.NAME_LAYER);n||(n=new kv(this._scene),this._scene._addComponent(n)),this._scene.layers.push(this);const o=this._scene.getEngine();this._drawWrapper=new Un(o);const a=[];a.push(1,1),a.push(-1,1),a.push(-1,-1),a.push(1,-1);const l=new er(o,a,er.PositionKind,!1,!1,2);this._vertexBuffers[er.PositionKind]=l,this._createIndexBuffer()}_createIndexBuffer(){const e=this._scene.getEngine(),t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[er.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}isReady(){const e=this._scene.getEngine();let t="";this.alphaTest&&(t="#define ALPHATEST"),this.texture&&!this.texture.gammaSpace&&(t+="\n#define LINEAR"),this._previousDefines!==t&&(this._previousDefines=t,this._drawWrapper.effect=e.createEffect("layer",[er.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],t));const i=this._drawWrapper.effect;return i?.isReady()&&this.texture?.isReady()}render(){if(!this.isEnabled)return;const e=this._scene.getEngine();if(!this.isReady())return;const t=this._drawWrapper.effect;this.onBeforeRenderObservable.notifyObservers(this),e.enableEffect(this._drawWrapper),e.setState(!1),t.setTexture("textureSampler",this.texture),t.setMatrix("textureMatrix",this.texture.getTextureMatrix()),t.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),t.setVector2("offset",this.offset),t.setVector2("scale",this.scale),e.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.alphaTest?e.drawElementsType(ta.TriangleFillMode,0,6):(e.setAlphaMode(this.alphaBlendingMode),e.drawElementsType(ta.TriangleFillMode,0,6),e.setAlphaMode(0)),this.onAfterRenderObservable.notifyObservers(this)}dispose(){const e=this._vertexBuffers[er.PositionKind];e&&(e.dispose(),this._vertexBuffers[er.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null),this.renderTargetTextures=[];const t=this._scene.layers.indexOf(this);this._scene.layers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()}}class Uv{static AddFlare(e,t,i,s,r){return new Uv(e,t,i,s,r)}constructor(e,t,i,s,r){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new Ee(1,1,1),this.texture=s?new Pa(s,r.getScene(),!0):null,this._system=r;const n=r.scene.getEngine();this._drawWrapper=new Un(n),this._drawWrapper.effect=n.createEffect("lensFlare",[er.PositionKind],["color","viewportMatrix"],["textureSampler"],""),r.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();const e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}Bi.ShadersStore.lensFlarePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.lensFlareVertexShader="attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class Gv{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||re.LastCreatedScene,Gv._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&!!(e.layerMask&i.activeCamera.layerMask);const s=i.getEngine(),r=[];r.push(1,1),r.push(-1,1),r.push(-1,-1),r.push(1,-1),this._vertexBuffers[er.PositionKind]=new er(s,r,er.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=_e.Project(t,me.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=_e.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);const i=this._scene.useRightHandedSystem;return!!(t.z>0&&!i||t.z<0&&i)&&(this._positionX>e.x&&this._positionXe.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;const e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();const i=new Ua(this._scene.activeCamera.globalPosition,e),s=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!s||!s.hit||s.distance>t}render(){if(!this._scene.activeCamera)return!1;const e=this._scene.getEngine(),t=this._scene.activeCamera.viewport.toGlobal(e.getRenderWidth(!0),e.getRenderHeight(!0));if(!this.computeEffectivePosition(t))return!1;if(!this._isVisible())return!1;let i,s;i=this._positionXt.x+t.width-this.borderLimit?this._positionX-t.x-t.width+this.borderLimit:0,s=this._positionYt.y+t.height-this.borderLimit?this._positionY-t.y-t.height+this.borderLimit:0;let r=i>s?i:s;r-=this.viewportBorder,r>this.borderLimit&&(r=this.borderLimit);let n=1-be.Clamp(r/this.borderLimit,0,1);if(n<0)return!1;n>1&&(n=1),this.viewportBorder>0&&(t.x+=this.viewportBorder,t.y+=this.viewportBorder,t.width-=2*this.viewportBorder,t.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);const o=t.x+t.width/2,a=t.y+t.height/2,l=o-this._positionX,h=a-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let i=0;i{throw xt("LensFlareSystemSceneComponent")},X.AddParser(or.NAME_LENSFLARESYSTEM,((e,t,i,s)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(let r=0,n=e.lensFlareSystems.length;r{this.scene.addLensFlareSystem(e)}))}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach((e=>{this.scene.removeLensFlareSystem(e),t&&e.dispose()}))}serialize(e){e.lensFlareSystems=[];const t=this.scene.lensFlareSystems;for(const i of t)e.lensFlareSystems.push(i.serialize())}dispose(){const e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){const t=this.scene.lensFlareSystems;Ds.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)e.layerMask&i.layerMask&&i.render();Ds.EndPerformanceCounter("Lens flares",t.length>0)}}}Gv._SceneComponentInitialization=e=>{let t=e._getComponent(or.NAME_LENSFLARESYSTEM);t||(t=new zv(e),e._addComponent(t))};Bi.IncludesShadersStore.bayerDitherFunctions="float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);}\nfloat bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5*mod(_P,4.0)); \nreturn 4.0*bayerDither2(P1)+bayerDither2(P2);}\nfloat bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5 *mod(_P,4.0)); \nvec2 P4=floor(0.25*mod(_P,8.0)); \nreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}\n";Bi.IncludesShadersStore.shadowMapFragmentExtraDeclaration="#if SM_FLOAT==0\n#include\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include\nuniform float softTransparentShadowSM;\n#endif\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nuniform vec3 lightDataSM;varying vec3 vPositionWSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";Bi.IncludesShadersStore.shadowMapFragment="float depthSM=vDepthMetricSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\ndepthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_FragDepth=clamp(1.0-depthSM,0.0,1.0);\n#else\ngl_FragDepth=clamp(depthSM,0.0,1.0); \n#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);\n#endif\n#if SM_FLOAT==1\ngl_FragColor=vec4(depthSM,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depthSM);\n#endif\nreturn;";Bi.ShadersStore.shadowMapPixelShader="#include\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEXTURE\nfloat alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;\n#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard;\n#else\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;\n#endif\n#endif\n#include\n}";Bi.IncludesShadersStore.sceneVertexDeclaration="uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\nuniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition;\n";Bi.IncludesShadersStore.meshVertexDeclaration="uniform mat4 world;uniform float visibility;\n";Bi.IncludesShadersStore.shadowMapVertexDeclaration="#include\n#include\n";Bi.IncludesShadersStore.shadowMapUboDeclaration="layout(std140,column_major) uniform;\n#include\n#include\n";Bi.IncludesShadersStore.shadowMapVertexExtraDeclaration="#if SM_NORMALBIAS==1\nuniform vec3 lightDataSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nvarying vec3 vPositionWSM;\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";Bi.IncludesShadersStore.shadowMapVertexNormalBias="#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvec3 worldLightDirSM=normalize(-lightDataSM.xyz);\n#else\nvec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM);\n#endif\nfloat ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM;\n#endif\n";Bi.IncludesShadersStore.shadowMapVertexMetric="#if SM_USEDISTANCE==1\nvPositionWSM=worldPos.xyz;\n#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#else\ngl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nzSM=gl_Position.z;gl_Position.z=0.0;\n#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\nvDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n";Bi.ShadersStore.shadowMapVertexShader="attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;\n#endif\n#include\n#include<__decl__shadowMapVertex>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normWorldSM=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvec3 vNormalW=normalize(normWorldSM*normalUpdated);\n#endif\n#endif\n#include\ngl_Position=viewProjection*worldPos;\n#include\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}";Bi.ShadersStore.depthBoxBlurPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}";Bi.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow="#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;\n#endif\n";class Wv{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===Wv.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(e===Wv.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(e===Wv.FILTER_PCF||e===Wv.FILTER_PCSS)return void(this.usePoissonSampling=!0)}e!==Wv.FILTER_PCF&&e!==Wv.FILTER_PCSS||this._scene.getEngine()._features.supportShadowSamplers?this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0}get usePoissonSampling(){return this.filter===Wv.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(Wv.FILTER_POISSONSAMPLING);(e||this.filter===Wv.FILTER_POISSONSAMPLING)&&(this.filter=e?t:Wv.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===Wv.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(Wv.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===Wv.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:Wv.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===Wv.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(Wv.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===Wv.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:Wv.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===Wv.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(Wv.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===Wv.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:Wv.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===Wv.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(Wv.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===Wv.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:Wv.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===Wv.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(Wv.FILTER_PCF);(e||this.filter===Wv.FILTER_PCF)&&(this.filter=e?t:Wv.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===Wv.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(Wv.FILTER_PCSS);(e||this.filter===Wv.FILTER_PCSS)&&(this.filter=e?t:Wv.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return this._darkness=e>=1?1:e<=0?0:e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return Wv.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(const t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(const t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}_getCamera(){return this._camera??this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,s,r){this.onBeforeShadowMapRenderObservable=new K,this.onAfterShadowMapRenderObservable=new K,this.onBeforeShadowMapRenderMeshObservable=new K,this.onAfterShadowMapRenderMeshObservable=new K,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=Wv.FILTER_NONE,this._filteringQuality=Wv.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=_e.Zero(),this._viewMatrix=me.Zero(),this._projectionMatrix=me.Zero(),this._transformMatrix=me.Zero(),this._cachedPosition=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=me.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=s??null,this._useRedTextureType=!!r;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),Wv._SceneComponentInitialization(this._scene);const o=this._scene.getEngine().getCaps();i?o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new ih(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForShadowGenerator-${this._light.name}`)):this._shadowMap=new ih(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=Pa.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=Pa.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(Pa.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,s)=>this._renderForShadowMap(e,t,i,s),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`shadow map generation for pass id ${e.currentRenderPassId}`,1)})),this._shadowMap.onBeforeRenderObservable.add((t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===Wv.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onAfterUnbindObservable.add((()=>{if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===Wv.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap)return void e._debugPopGroup?.(1);const t=this.getShadowMapForRendering();t&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,t.renderTarget,!0),e.unBindFramebuffer(t.renderTarget,!0),e._debugPopGroup?.(1))}));const t=new Ae(0,0,0,0),i=new Ae(1,1,1,1);this._shadowMap.onClearObservable.add((e=>{this._filter===Wv.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)})),this._shadowMap.onResizeObservable.add((e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}));for(let e=nr.MIN_RENDERINGGROUPS;e{e.setTexture("textureSampler",this._shadowMap)})),this._kernelBlurYPostprocess=new mg(this._light.name+"KernelBlurY",new de(0,1),this.blurKernel,1,null,Pa.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new Vl(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,Pa.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add((e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,s){let r;if(s.length)for(r=0;r{s===i||e?(s.getMeshUniformBuffer().bindToEffect(h,"Mesh"),s.transferToEffect(e?t:_)):(i.getMeshUniformBuffer().bindToEffect(h,"Mesh"),i.transferToEffect(t))})),this.forceBackFacesOnly&&n.setState(!0,0,!1,!1,o.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(h),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===Wv.FILTER_NONE||this.filter===Wv.FILTER_PCSS?this._shadowMap.updateSamplingMode(Pa.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(Pa.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},s=this.getShadowMap();if(!s)return void(e&&e(this));const r=s.renderList;if(!r)return void(e&&e(this));const n=[];for(const e of r)n.push(...e.subMeshes);if(0===n.length)return void(e&&e(this));let o=0;const a=()=>{if(this._scene&&this._scene.getEngine()){for(;this.isReady(n[o],i.useInstances,n[o].getMaterial()?.needAlphaBlendingForMesh(n[o].getMesh())??!1);)if(o++,o>=n.length)return void(e&&e(this));setTimeout(a,16)}};a()}forceCompilationAsync(e){return new Promise((t=>{this.forceCompilation((()=>{t()}),e)}))}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,s){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const r=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&r.isVerticesDataPresent(er.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===ua.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&s?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){const s=e.getMaterial(),r=s?.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;const n=[];if(this._prepareShadowDefines(e,t,n,i),r){if(!r.isReadyForSubMesh(e,n,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const i=e._getDrawWrapper(void 0,!0);let r=i.effect,o=i.defines;const a=[er.PositionKind],l=e.getMesh();this.normalBias&&l.isVerticesDataPresent(er.NormalKind)&&(a.push(er.NormalKind),n.push("#define NORMAL"),l.nonUniformScaling&&n.push("#define NONUNIFORMSCALING"));const h=s.needAlphaTesting();if((h||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const e=s.alphaCutOff??Wv.DEFAULT_ALPHA_CUTOFF;n.push("#define ALPHATEXTURE"),h&&n.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),l.isVerticesDataPresent(er.UVKind)&&(a.push(er.UVKind),n.push("#define UV1")),l.isVerticesDataPresent(er.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(a.push(er.UV2Kind),n.push("#define UV2"))}const c=new Ll;if(l.useBones&&l.computeBonesUsingShaders&&l.skeleton){a.push(er.MatricesIndicesKind),a.push(er.MatricesWeightsKind),l.numBoneInfluencers>4&&(a.push(er.MatricesIndicesExtraKind),a.push(er.MatricesWeightsExtraKind));const e=l.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+l.numBoneInfluencers),l.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,l),e.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(e.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");const u=l.morphTargetManager;let d=0;if(u&&(d=u.numMaxInfluencers||u.numInfluencers,d>0&&(n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+d),u.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),Eo(a,l,d))),go(s,this._scene,n),t&&(n.push("#define INSTANCES"),Po(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const e of this.customShaderOptions.defines)-1===n.indexOf(e)&&n.push(e);const _=l.bakedVertexAnimationManager;t&&_&&_.isEnabled&&(n.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),a.push("bakedVertexAnimationSettingsInstanced"));const p=n.join("\n");if(o!==p){o=p;let e="shadowMap";const t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],s=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],n=["Scene","Mesh"];if(mo(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const e of this.customShaderOptions.attributes)-1===a.indexOf(e)&&a.push(e);if(this.customShaderOptions.uniforms)for(const e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(const e of this.customShaderOptions.samplers)-1===s.indexOf(e)&&s.push(e)}const l=this._scene.getEngine();r=l.createEffect(e,{attributes:a,uniformsNames:t,uniformBuffersNames:n,samplers:s,defines:p,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:d}},l),i.setEffect(r,o)}if(!r.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){const i=this._scene,s=this._light;i.shadowsEnabled&&s.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===Wv.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Wv.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===Wv.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Wv.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),s.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();if(!r)return;i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix());const n=this.getShadowMapForRendering();this._filter===Wv.FILTER_PCF?(t.setDepthStencilTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),r.getSize().width,1/r.getSize().width,this.frustumEdgeFalloff,e)):this._filter===Wv.FILTER_PCSS?(t.setDepthStencilTexture("shadowTexture"+e,n),t.setTexture("depthTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/r.getSize().width,this._contactHardeningLightSizeUVRatio*r.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/r.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e)}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){const e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),_e.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(_e.Dot(this._lightDirection,_e.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),me.LookAtLHToRef(t,t.add(this._lightDirection),_e.Up(),this._viewMatrix);const e=this.getShadowMap();if(e){const t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){const e=this._shadowMap;if(!e)return;const t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(const e of t)this._shadowMap.renderList.push(e)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){const e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){const e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=this._camera?.id,e.id=this.id,e.mapSize=t.getRenderSize(),e.forceBackFacesOnly=this.forceBackFacesOnly,e.darkness=this.getDarkness(),e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.filteringQuality=this.filteringQuality,e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.depthScale=this.depthScale,e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.renderList=[],t.renderList)for(let i=0;i{throw xt("ShadowGeneratorSceneComponent")};Bi.ShadersStore.depthPixelShader="#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\nvarying float vDepthMetric;\n#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\n#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\n#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\n#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";Bi.IncludesShadersStore.pointCloudVertexDeclaration="#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";Bi.ShadersStore.depthVertexShader="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;uniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;varying vec4 vViewPos;\n#endif\n#include\nvarying float vDepthMetric;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#include\ngl_Position=viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\n#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}\n";class Hv{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,s=!1,r=Pa.TRILINEAR_SAMPLINGMODE,n=!1,o){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=s,this._storeCameraSpaceZ=n,this.isPacked=0===t,this.isPacked?this.clearColor=new Ae(1,1,1,1):this.clearColor=new Ae(n?1e8:1,0,0,1),Hv._SceneComponentInitialization(this._scene);const a=e.getEngine();this._camera=i,r!==Pa.NEAREST_SAMPLINGMODE&&(1!==t||a._caps.textureFloatLinearFiltering||(r=Pa.NEAREST_SAMPLINGMODE),2!==t||a._caps.textureHalfFloatLinearFiltering||(r=Pa.NEAREST_SAMPLINGMODE));const l=this.isPacked||!a._features.supportExtendedTextureFormats?5:6;this._depthMap=new ih(o??"DepthRenderer",{width:a.getRenderWidth(),height:a.getRenderHeight()},this._scene,!1,!0,t,!1,r,void 0,void 0,void 0,l),this._depthMap.wrapU=Pa.CLAMP_ADDRESSMODE,this._depthMap.wrapV=Pa.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((e=>{e.clear(this.clearColor,!0,!0,!0)})),this._depthMap.onBeforeBindObservable.add((()=>{a._debugPushGroup?.("depth renderer",1)})),this._depthMap.onAfterUnbindObservable.add((()=>{a._debugPopGroup?.(1)})),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),s=this._scene,r=s.getEngine(),n=e.getMaterial();if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!n||i.infiniteDistance||n.disableDepthWrite||0===e.verticesCount||e._renderId===s.getRenderId())return;const o=i._getWorldMatrixDeterminant()<0;let a=t.overrideMaterialSideOrientation??n.sideOrientation;o&&(a=0===a?1:0);const l=0===a;r.setState(n.backFaceCulling,0,!1,l,this.reverseCulling?!n.cullBackFaces:n.cullBackFaces);const h=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(h.mustReturn)return;const c=r.getCaps().instancedArrays&&(null!==h.visibleInstances[e._id]&&void 0!==h.visibleInstances[e._id]||t.hasThinInstances),u=this._camera||s.activeCamera;if(this.isReady(e,c)&&u){e._renderId=s.getRenderId();const o=i._internalAbstractMeshDataInfo._materialForRenderPass?.[r.currentRenderPassId];let a=e._getDrawWrapper();!a&&o&&(a=o._getDrawWrapper());const l=u.mode===In.ORTHOGRAPHIC_CAMERA;if(!a)return;const d=a.effect;let _,p;if(r.enableEffect(a),c||t._bind(e,d,n.fillMode),o?o.bindForSubMesh(i.getWorldMatrix(),i,e):(d.setMatrix("viewProjection",s.getTransformMatrix()),d.setMatrix("world",i.getWorldMatrix()),this._storeCameraSpaceZ&&d.setMatrix("view",s.getViewMatrix())),l?(_=!r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1,p=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1):(_=r.useReverseDepthBuffer&&r.isNDCHalfZRange?u.minZ:r.isNDCHalfZRange?0:u.minZ,p=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:u.maxZ),d.setFloat2("depthValues",_,_+p),!o){if(n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(d.setTexture("diffuseSampler",e),d.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices){const i=e.getTransformMatrixTexture(t);if(!i)return;d.setTexture("boneSampler",i),d.setFloat("boneTextureWidth",4*(e.bones.length+1))}else d.setMatrices("mBones",e.getTransformMatrices(t))}xo(d,n,s),Io(t,d),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(d),n.pointsCloud&&d.setFloat("pointSize",n.pointSize)}t._processRendering(i,e,d,n.fillMode,h,c,((e,t)=>d.setMatrix("world",t)))}};this._depthMap.customRenderFunction=(e,t,i,s)=>{let r;if(s.length)for(r=0;r4&&(l.push(er.MatricesIndicesExtraKind),l.push(er.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),a.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));const t=e.getRenderingMesh().skeleton;t?.isUsingTextureForMatrices&&a.push("#define BONETEXTURE")}else a.push("#define NUM_BONE_INFLUENCERS 0");const h=s.morphTargetManager;let c=0;h&&(c=h.numMaxInfluencers||h.numInfluencers,c>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+c),h.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),Eo(l,s,c))),o.pointsCloud&&a.push("#define POINTSIZE"),t&&(a.push("#define INSTANCES"),Po(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&a.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&a.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&a.push("#define PACKED"),go(o,r,a);const u=e._getDrawWrapper(void 0,!0),d=u.defines,_=a.join("\n");if(d!==_){const e=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];mo(e),u.setEffect(i.createEffect("depth",l,e,["diffuseSampler","morphTargets","boneSampler"],_,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),_)}return u.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}Hv._SceneComponentInitialization=e=>{throw xt("DepthRendererSceneComponent")};Bi.ShadersStore.minmaxReduxPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#if defined(INITIAL)\nuniform sampler2D sourceTexture;uniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4);\n#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\n#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\n#endif\nglFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(MAIN)\nuniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(LAST)\nvoid main(void)\n{glFragColor=vec4(0.);if (true) { \ndiscard;}}\n#endif\n";class Xv{constructor(e){this.onAfterReductionPerformed=new K,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new ir(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{this._postProcessManager._rebuild()}))}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,s=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=s;const r=this._camera.getScene(),n=new Vl("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,r.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);n.autoClear=!1,n.forceFullscreenViewport=s;let o=this._sourceTexture.getRenderWidth(),a=this._sourceTexture.getRenderHeight();n.onApply=((e,t)=>i=>{i.setTexture("sourceTexture",this._sourceTexture),i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(n);let l=1;for(;o>1||a>1;){o=Math.max(Math.round(o/2),1),a=Math.max(Math.round(a/2),1);const e=new Vl("Reduction phase "+l,"minmaxRedux",["texSize"],null,{width:o,height:a},null,1,r.getEngine(),!1,"#define "+(1==o&&1==a?"LAST":1==o||1==a?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=s,e.onApply=((e,t)=>i=>{1==e||1==t?i.setInt2("texSize",e,t):i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(e),l++,1==o&&1==a){const t=(e,t,i)=>{const s=new Float32Array(4*e*t),n={min:0,max:0};return()=>{r.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,s,!1),n.min=s[0],n.max=s[1],this.onAfterReductionPerformed.notifyObservers(n)}};e.onAfterRenderObservable.add(t(o,a,e))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add((()=>{const e=this._camera.getScene().getEngine();e._debugPushGroup?.("min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),e.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),e._debugPopGroup?.(1)})),this._activated=!0)}deactivate(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let e=0;ethis._computeShadowCastersBoundingInfo()))),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){const e=this._shadowMap.renderList;for(let t=0;tt&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return Zv.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let t=e.min,i=e.max;t>=i&&(t=0,i=1),t==this._minDistance&&i==this._maxDistance||this.setMinMaxDistance(t,i)})),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate??-1}set autoCalcDepthBoundsRefreshRate(e){this._depthReducer?.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,s=i-t,r=this._minDistance,n=t+r*s,o=t+(this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance)*s,a=o-n,l=o/n;for(let e=0;e{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===Wv.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()})),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==Wv.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,s=this._light;if(!i.shadowsEnabled||!s.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const r=this._getCamera();r&&this._shadowMaxZ<=(r.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();if(!r)return;const n=r.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===Wv.FILTER_PCF)t.setDepthStencilTexture("shadowTexture"+e,r),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n,1/n,this.frustumEdgeFalloff,e);else if(this._filter===Wv.FILTER_PCSS){for(let e=0;enew Zv(e,t,void 0,i)));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}Zv._FrustumCornersNDCSpace=[new _e(-1,1,-1),new _e(1,1,-1),new _e(1,-1,-1),new _e(-1,-1,-1),new _e(-1,1,1),new _e(1,1,1),new _e(1,-1,1),new _e(-1,-1,1)],Zv.CLASSNAME="CascadedShadowGenerator",Zv.DEFAULT_CASCADES_COUNT=4,Zv.MIN_CASCADES_COUNT=2,Zv.MAX_CASCADES_COUNT=4,Zv._SceneComponentInitialization=e=>{throw xt("ShadowGeneratorSceneComponent")},X.AddParser(or.NAME_SHADOWGENERATOR,((e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,s=e.shadowGenerators.length;i{let t=e._getComponent(or.NAME_SHADOWGENERATOR);t||(t=new Jv(e),e._addComponent(t))},Et.AddNodeConstructor("Light_Type_0",((e,t)=>()=>new ex(e,_e.Zero(),t)));class ex extends hg{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){const t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return ua.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new _e(1,0,0);case 1:return new _e(-1,0,0);case 2:return new _e(0,-1,0);case 3:return new _e(0,1,0);case 4:return new _e(0,0,1);case 5:return new _e(0,0,-1)}return _e.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;const r=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;me.PerspectiveFovLHToRef(this.shadowAngle,1,o?n:r,o?r:n,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}}Ze([rt()],ex.prototype,"shadowAngle",null),z("BABYLON.PointLight",ex);class tx{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css",this._style.innerHTML="@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }",document.getElementsByTagName("head")[0].appendChild(this._style);const e=!!window.SVGSVGElement,t=new Image;tx.DefaultLogoUrl?t.src=tx.DefaultLogoUrl:t.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",t.style.width="150px",t.style.gridColumn="1",t.style.gridRow="1",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.position="absolute";const i=document.createElement("div");i.style.width="300px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const s=new Image;if(tx.DefaultSpinnerUrl?s.src=tx.DefaultSpinnerUrl:s.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!e){const e={w:16,h:18.5},i={w:30,h:30};t.style.width=`${e.w}vh`,t.style.height=`${e.h}vh`,t.style.left=`calc(50% - ${e.w/2}vh)`,t.style.top=`calc(50% - ${e.h/2}vh)`,s.style.width=`${i.w}vh`,s.style.height=`${i.h}vh`,s.style.left=`calc(50% - ${i.w/2}vh)`,s.style.top=`calc(50% - ${i.h/2}vh)`}i.appendChild(s),this._loadingDiv.appendChild(t),this._loadingDiv.appendChild(i),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",(()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)})))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}tx.DefaultLogoUrl="",tx.DefaultSpinnerUrl="",ns.DefaultLoadingScreenFactory=e=>new tx(e);class ix{static ConvertPanoramaToCubemap(e,t,i,s,r=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(s,this.FACE_FRONT,e,t,i,r),back:this.CreateCubemapTexture(s,this.FACE_BACK,e,t,i,r),left:this.CreateCubemapTexture(s,this.FACE_LEFT,e,t,i,r),right:this.CreateCubemapTexture(s,this.FACE_RIGHT,e,t,i,r),up:this.CreateCubemapTexture(s,this.FACE_UP,e,t,i,r),down:this.CreateCubemapTexture(s,this.FACE_DOWN,e,t,i,r),size:s,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,s,r,n=!1){const o=new ArrayBuffer(e*e*4*3),a=new Float32Array(o),l=n?Math.max(1,Math.round(s/4/e)):1,h=1/l,c=h*h,u=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),_=1/e;let p=0;for(let n=0;nMath.PI;)r-=2*Math.PI;let o=r/Math.PI;const a=n/Math.PI;o=.5*o+.5;let l=Math.round(o*i);l<0?l=0:l>=i&&(l=i-1);let h=Math.round(a*s);h<0?h=0:h>=s&&(h=s-1);const c=s-h-1;return{r:t[c*i*3+3*l+0],g:t[c*i*3+3*l+1],b:t[c*i*3+3*l+2]}}}ix.FACE_LEFT=[new _e(-1,-1,-1),new _e(1,-1,-1),new _e(-1,1,-1),new _e(1,1,-1)],ix.FACE_RIGHT=[new _e(1,-1,1),new _e(-1,-1,1),new _e(1,1,1),new _e(-1,1,1)],ix.FACE_FRONT=[new _e(1,-1,-1),new _e(1,-1,1),new _e(1,1,-1),new _e(1,1,1)],ix.FACE_BACK=[new _e(-1,-1,1),new _e(-1,-1,-1),new _e(-1,1,1),new _e(-1,1,-1)],ix.FACE_DOWN=[new _e(1,1,-1),new _e(1,1,1),new _e(-1,1,-1),new _e(-1,1,1)],ix.FACE_UP=[new _e(-1,-1,-1),new _e(-1,-1,1),new _e(1,-1,-1),new _e(1,-1,1)];class sx{static _Ldexp(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,s,r,n){r>0?(r=this._Ldexp(1,r-136),e[n+0]=t*r,e[n+1]=i*r,e[n+2]=s*r):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}static _ReadStringLine(e,t){let i="",s="";for(let r=t;r32767)throw"HDR Bad header format, unsupported size";return o+=s.length+1,{height:t,width:i,dataPosition:o}}static GetCubeMapTextureData(e,t,i=!1){const s=new Uint8Array(e),r=this.RGBE_ReadHeader(s),n=this.RGBE_ReadPixels(s,r);return ix.ConvertPanoramaToCubemap(n,r.width,r.height,t,i)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i=t.height;const s=t.width;let r,n,o,a,l,h=t.dataPosition,c=0,u=0,d=0;const _=new ArrayBuffer(4*s),p=new Uint8Array(_),f=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(f);for(;i>0;){if(r=e[h++],n=e[h++],o=e[h++],a=e[h++],2!=r||2!=n||128&o||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((o<<8|a)!=s)throw"HDR Bad header format, wrong scan line width";for(c=0,d=0;d<4;d++)for(u=(d+1)*s;c128){if(l=r-128,0==l||l>u-c)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)p[c++]=n}else{if(l=r,0==l||l>u-c)throw"HDR Bad Format, bad scanline data (non-run)";if(p[c++]=n,--l>0)for(let t=0;t0;){for(l=0;l{this._effectRenderer=new Kl(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled((()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()}))})):(Ne.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}}class nx extends ya{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(me.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,s=!1,r=!0,n=!1,o=!1,a=null,l=null,h=!1){super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=_e.Zero(),this.onLoadObservable=new K,e&&(this._coordinatesMode=Pa.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=me.Identity(),this._prefilterOnLoad=o,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),a&&a()},this._onError=l,this.gammaSpace=n,this._noMipmap=s,this._size=i,this._supersample=h,this._generateHarmonics=r,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?Ds.SetImmediate((()=>this._onLoad())):this._texture.onLoadedObservable.add(this._onLoad):this.getScene()?.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture())}getClassName(){return"HDRCubeTexture"}_loadTexture(){const e=this._getEngine(),t=e.getCaps();let i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const t=this._onLoad,i=new rx(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,(e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const t=sx.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){const e=$_.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}const s=[];let r=null,n=null;for(let e=0;e<6;e++){2===i?n=new Uint16Array(this._size*this._size*3):0===i&&(r=new Uint8Array(this._size*this._size*3));const o=t[nx._FacesMapping[e]];if(this.gammaSpace||n||r)for(let e=0;e255){const e=255/n;t*=e,i*=e,s*=e}r[3*e+0]=t,r[3*e+1]=i,r[3*e+2]=s}n?s.push(n):r?s.push(r):s.push(o)}return s}),null,this._onLoad,this._onError)}clone(){const e=new nx(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&this.getScene()?.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(this)))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let s=null;return e.name&&!e.isRenderTarget&&(s=new nx(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),s.name=e.name,s.hasAlpha=e.hasAlpha,s.level=e.level,s.coordinatesMode=e.coordinatesMode,s.isBlocking=e.isBlocking),s&&(e.boundingBoxPosition&&(s.boundingBoxPosition=_e.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=_e.FromArray(e.boundingBoxSize)),e.rotationY&&(s.rotationY=e.rotationY)),s}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}nx._FacesMapping=["right","left","up","down","front","back"],z("BABYLON.HDRCubeTexture",nx);class ox{get influence(){return this._influence}set influence(e){if(this._influence===e)return;const t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new K,this._onDataLayoutChanged=new K,this._animationPropertiesOverride=null,this._scene=i||re.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}setPositions(e){const t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){const t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){const t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){const t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){const e=St.Clone((()=>new ox(this.name,this.influence,this._scene)),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e}serialize(){const e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),null!=this.id&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),St.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new ox(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Fs(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=re.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._syncActiveTargets(!0))}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get numTargets(){return this._targets.length}get numInfluencers(){return this._activeTargets.length}get influences(){return this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets=e}get isUsingTextureForTargets(){return lx.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!this._scene?.getEngine().getCaps().disableMorphTargetTexture}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}getTargetByName(e){for(const t of this._targets)if(t.name===e)return t;return null}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add((e=>{this._syncActiveTargets(e)}))),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add((()=>{this._syncActiveTargets(!0)}))),this._syncActiveTargets(!0)}removeTarget(e){const t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0)),this._scene&&this._scene.stopAnimation(e)}_bind(e){e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setInt("morphTargetCount",this.numInfluencers)}clone(){const e=new lx(this._scene);for(const t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){const e={};e.id=this.uniqueId,e.targets=[];for(const t of this._targets)e.targets.push(t.serialize());return e}_syncActiveTargets(e){if(this.areUpdatesFrozen)return;let t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),this._morphTargetTextureIndices&&this._morphTargetTextureIndices.length===this._targets.length||(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let i=-1;for(const e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=lx.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;const s=e.getPositions();if(s){const e=s.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e)return void Ne.Error("Incompatible target. Targets must all have the same vertices count.")}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e0)){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;const e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){const e=this._targetStoreTexture.getSize();e.width===this._textureWidth&&e.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4);let i=0;for(let s=0;s-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(const e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){const i=new lx(t);i._uniqueId=e.id;for(const s of e.targets)i.addTarget(ox.Parse(s,t));return i}}lx.EnableTextureStorage=!0,lx.MaxActiveMorphTargetsInVertexAttributeMode=8;class hx{constructor(){this._hasHit=!1,this._hitNormal=_e.Zero(),this._hitPoint=_e.Zero(),this._triangleIndex=-1}get hitPoint(){return this._hitPoint}get hitNormal(){return this._hitNormal}get hasHit(){return this._hasHit}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormal.set(e.x,e.y,e.z),this._hitPoint.set(t.x,t.y,t.z),this._triangleIndex=i??-1}reset(){this._hasHit=!1,this._hitNormal.setAll(0),this._hitPoint.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0,this.shape=void 0}}class cx extends hx{constructor(){super(...arguments),this._hitDistance=0,this._rayFromWorld=_e.Zero(),this._rayToWorld=_e.Zero()}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormal}get hitPointWorld(){return this._hitPoint}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=_e.Distance(this._rayFromWorld,this._hitPoint)}reset(e=_e.Zero(),t=_e.Zero()){super.reset(),this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hitDistance=0}}class ux{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw xt("CannonJSPlugin")}constructor(e,t=ux.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new _e(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){const t=this._impostors.indexOf(e);t>-1&&this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)}addJoint(e,t,i){const s={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(s),this._physicsPlugin.generateJoint(s)}removeJoint(e,t,i){const s=this._joints.filter((function(s){return s.connectedImpostor===t&&s.joint===i&&s.mainImpostor===e}));s.length&&this._physicsPlugin.removeJoint(s[0])}_step(e){this._impostors.forEach((e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t0&&(this._physicsBodiesToRemoveAfterStep.forEach((e=>{"function"==typeof this.world.removeBody?this.world.removeBody(e):this.world.remove(e)})),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(r,s)}applyForce(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(r,s)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const t=this._createShape(e);if(!t)return void Ne.Warn("It was not possible to create a physics body for this object.");const i=e.physicsBody;i&&this.removePhysicsBody(e);const s=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),r={mass:e.getParam("mass"),material:s},n=e.getParam("nativeOptions");for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(r[e]=n[e]);e.physicsBody=new this.BJSCANNON.Body(r),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){const s=i[t];e.physicsBody[t].set(s.x,s.y,s.z)})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}}_processChildMeshes(e){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],i=e.object.rotationQuaternion;if(i?i.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),t.length){const i=t=>{if(!t.rotationQuaternion)return;const s=t.getPhysicsImpostor();if(s&&s.parent!==e&&t.parent){const i=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),r=t.rotationQuaternion.multiply(this._tmpQuaternion);s.physicsBody&&(this.removePhysicsBody(s),s.physicsBody=null),s.parent=e,s.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(s),new this.BJSCANNON.Vec3(i.x,i.y,i.z),new this.BJSCANNON.Quaternion(r.x,r.y,r.z,r.w)),e.physicsBody.mass+=s.getParam("mass")}t.getChildMeshes(!0).filter((e=>!!e.physicsImpostor)).forEach(i)};t.filter((e=>!!e.physicsImpostor)).forEach(i)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;let s;const r=e.joint.jointData,n={pivotA:r.mainPivot?(new this.BJSCANNON.Vec3).set(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z):null,pivotB:r.connectedPivot?(new this.BJSCANNON.Vec3).set(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z):null,axisA:r.mainAxis?(new this.BJSCANNON.Vec3).set(r.mainAxis.x,r.mainAxis.y,r.mainAxis.z):null,axisB:r.connectedAxis?(new this.BJSCANNON.Vec3).set(r.connectedAxis.x,r.connectedAxis.y,r.connectedAxis.z):null,maxForce:r.nativeParams.maxForce,collideConnected:!!r.collision};switch(e.joint.type){case el.HingeJoint:case el.Hinge2Joint:s=new this.BJSCANNON.HingeConstraint(t,i,n);break;case el.DistanceJoint:s=new this.BJSCANNON.DistanceConstraint(t,i,r.maxDistance||2);break;case el.SpringJoint:{const e=r;s=new this.BJSCANNON.Spring(t,i,{restLength:e.length,stiffness:e.stiffness,damping:e.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break}case el.LockJoint:s=new this.BJSCANNON.LockConstraint(t,i,n);break;case el.PointToPointJoint:case el.BallAndSocketJoint:default:s=new this.BJSCANNON.PointToPointConstraint(t,n.pivotA,i,n.pivotB,n.maxForce)}s.collideConnected=!!r.collision,e.joint.physicsJoint=s,e.joint.type!==el.SpringJoint?this.world.addConstraint(s):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){s.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==el.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let s,r;for(s=0;s1e3*i));e++);this.time+=s;const a=this.time%i/i,l=e,h=this.bodies;for(let e=0;e!==h.length;e++){const i=h[e];i.type!==t.Body.STATIC&&i.sleepState!==t.Body.SLEEPING?(i.position.vsub(i.previousPosition,l),l.scale(a,l),i.position.vadd(l,i.interpolatedPosition)):(i.interpolatedPosition.set(i.position.x,i.position.y,i.position.z),i.interpolatedQuaternion.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w))}}}}raycast(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))}}ux.DefaultPluginFactory=()=>new dx;class _x{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=_e.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new cx}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this.world.timeStep=e}getTimeStep(){return this.world.timeStep}executeStep(e,t){t.forEach((function(e){e.beforeStep()})),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach((e=>{e.afterStep(),this._tmpImpostorsArray[e.uniqueId]=e}));let i=this.world.contacts;for(;null!==i;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];e&&t?(e.onCollide({body:t.physicsBody,point:null,distance:0,impulse:0,normal:null}),t.onCollide({body:e.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next):i=i.next}}applyImpulse(e,t,i){const s=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*s))}applyForce(e,t,i){Ne.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},s=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach((function(e){e.physicsImpostor&&s.push(e.physicsImpostor)}));const r=e=>Math.max(e,J),n=new fe;s.forEach((t=>{if(!t.object.rotationQuaternion)return;const s=t.object.rotationQuaternion;n.copyFrom(s),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);const o=n.toEulerAngles(),a=t.getObjectExtents(),l=57.29577951308232;if(t===e){const t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{const e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(o.x*l,o.y*l,o.z*l)}switch(t.object.rotationQuaternion.copyFrom(n),t.type){case nl.ParticleImpostor:Ne.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case nl.SphereImpostor:{const e=a.x,t=a.y,s=a.z,n=Math.max(r(e),r(t),r(s))/2;i.type.push("sphere"),i.size.push(n),i.size.push(n),i.size.push(n);break}case nl.CylinderImpostor:{const e=r(a.x)/2,t=r(a.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case nl.PlaneImpostor:case nl.BoxImpostor:default:{const e=r(a.x),t=r(a.y),s=r(a.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(s);break}}t.object.rotationQuaternion=s})),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(n),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}var t}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const s=e.joint.jointData,r=s.nativeParams||{};let n;const o={body1:t,body2:i,axe1:r.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:r.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:r.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:r.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:r.min,max:r.max,collision:r.collision||s.collision,spring:r.spring,world:this.world};switch(e.joint.type){case el.BallAndSocketJoint:n="jointBall";break;case el.SpringJoint:{Ne.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const e=s;o.min=e.length||o.min,o.max=Math.max(o.min,o.max)}case el.DistanceJoint:n="jointDistance",o.max=s.maxDistance;break;case el.PrismaticJoint:n="jointPrisme";break;case el.SliderJoint:n="jointSlide";break;case el.WheelJoint:n="jointWheel";break;case el.HingeJoint:default:n="jointHinge"}o.type=n,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){Ne.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{const t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){const t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){const s=e.physicsBody;e.physicsBody.shapes.next||(s.position.set(t.x,t.y,t.z),s.orientation.set(i.x,i.y,i.z,i.w),s.syncShapes(),s.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){const t=e.physicsBody.linearVelocity;return t?new _e(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new _e(t.x,t.y,t.z):null}setBodyMass(e,t){const i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,s){void 0!==i?Ne.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setMotor(t,i)}setLimit(e,t,i,s){const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setLimit(t,void 0===i?-t:i)}syncMeshWithImpostor(e,t){const i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)}getRadius(e){return e.physicsBody.shapes.radius}getBoxSizeToRef(e,t){const i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth}dispose(){this.world.clear()}raycast(e,t){return Ne.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){Ne.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class px{constructor(e=!0,t=Ammo,i=null){this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new fe,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new _e,this._tmpContactNormal=new _e,this._tmpVec3=new _e,this._tmpMatrix=new me,"function"!=typeof t?(this.bjsAMMO=t,this.isSupported()?(this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=e=>{const t=(e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint)).getPositionWorldOnA(),i=e.m_normalWorldOnB;this._tmpContactPoint.x=t.x(),this._tmpContactPoint.y=t.y(),this._tmpContactPoint.z=t.z(),this._tmpContactNormal.x=i.x(),this._tmpContactNormal.y=i.y(),this._tmpContactNormal.z=i.z(),this._tmpContactImpulse=e.getAppliedImpulse(),this._tmpContactDistance=e.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new cx,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)):Ne.Error("AmmoJS is not available. Please make sure you included the js file.")):Ne.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.")}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(e))for(const t of e._onPhysicsCollideCallbacks)for(const i of t.otherImpostors)(e.physicsBody.isActive()||i.physicsBody.isActive())&&this._isImpostorPairInContact(e,i)&&(e.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),i.onCollide({body:e.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===nl.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let s,r,n,o,a;const l=new Array;for(let e=0;e{this.bjsAMMO.destroy(e)})),e._pluginData.toDispose=[]))}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;if(e.joint.physicsJoint)return;const s=e.joint.jointData;let r;switch(s.mainPivot||(s.mainPivot=new _e(0,0,0)),s.connectedPivot||(s.connectedPivot=new _e(0,0,0)),e.joint.type){case el.DistanceJoint:{const e=s.maxDistance;e&&(s.mainPivot=new _e(0,-e/2,0),s.connectedPivot=new _e(0,e/2,0));const n=this._tmpAmmoVectorA;n.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const o=this._tmpAmmoVectorB;o.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,n,o);break}case el.HingeJoint:{s.mainAxis||(s.mainAxis=new _e(0,0,0)),s.connectedAxis||(s.connectedAxis=new _e(0,0,0));const e=this._tmpAmmoVectorA;e.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z);const o=this._tmpAmmoVectorC;o.setValue(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z);const a=this._tmpAmmoVectorD;a.setValue(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z),r=new this.bjsAMMO.btHingeConstraint(t,i,e,n,o,a);break}case el.BallAndSocketJoint:{const e=this._tmpAmmoVectorA;e.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,e,n);break}default:{Ne.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint");const e=this._tmpAmmoVectorA;e.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,e,n);break}}this.world.addConstraint(r,!e.joint.jointData.collision),e.joint.physicsJoint=r}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint),this.bjsAMMO.destroy(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n,o=i.getVerticesData(er.PositionKind);if(o||(o=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?fe.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):fe.Identity(),me.Compose(_e.One(),e,t.position).invertToRef(this._tmpMatrix),n=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else me.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),n=this._tmpMatrix;const a=r.length/3;for(let t=0;t{s+=this._addMeshVerts(e,t,i)}))}return s}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(er.PositionKind);i||(i=[]);let s=t.getVerticesData(er.NormalKind);s||(s=[]),t.computeWorldMatrix(!1);const r=[],n=[];for(let e=0;ee*e)).reduce(((e,t)=>e+t)))t=r.length,i=t/3-1,this._tmpAmmoVectorA.setValue(r[0],r[1],r[2]),this._tmpAmmoVectorB.setValue(r[t-3],r[t-2],r[t-1]);else{e._isFromLine=!1;const s=e.getParam("path");if(null===e.getParam("shape"))return Ne.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;t=s.length,i=t-1,this._tmpAmmoVectorA.setValue(s[0].x,s[0].y,s[0].z),this._tmpAmmoVectorB.setValue(s[t-1].x,s[t-1].y,s[t-1].z)}e.segments=i;let o=e.getParam("fixedPoints");o=o>3?3:o;const a=(new this.bjsAMMO.btSoftBodyHelpers).CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,o);return a.get_m_cfg().set_collisions(17),a}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n=i.getVerticesData(er.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);const o=r.length/3;for(let t=0;t{s+=this._addHullVerts(e,t,i)}))}return s}_createShape(e,t=!1){const i=e.object;let s;const r=e.getObjectExtents();if(!t){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];s=new this.bjsAMMO.btCompoundShape;let i=0;if(t.forEach((e=>{const t=e.getPhysicsImpostor();if(t){if(t.type==nl.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const r=this._createShape(t),n=e.parent.getWorldMatrix().clone(),o=new _e;n.decompose(o),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*o.x,e.position.y*o.y,e.position.z*o.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,r),t.dispose(),i++}})),i>0){if(e.type!=nl.NoImpostor){const t=this._createShape(e,!0);t&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,t))}return s}this.bjsAMMO.destroy(s),s=null}switch(e.type){case nl.SphereImpostor:if(be.WithinEpsilon(r.x,r.y,1e-4)&&be.WithinEpsilon(r.x,r.z,1e-4))s=new this.bjsAMMO.btSphereShape(r.x/2);else{this._tmpAmmoVectorA.setValue(0,0,0);const e=[this._tmpAmmoVectorA],t=[1];s=new this.bjsAMMO.btMultiSphereShape(e,t,1),this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s.setLocalScaling(this._tmpAmmoVectorA)}break;case nl.CapsuleImpostor:{const e=r.x/2;s=new this.bjsAMMO.btCapsuleShape(e,r.y-2*e)}break;case nl.CylinderImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case nl.PlaneImpostor:case nl.BoxImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case nl.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)s=this.onCreateCustomMeshImpostor(e);else{const t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);const r=this._addMeshVerts(t,i,i);s=0==r?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case nl.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)s=this.onCreateCustomConvexHullImpostor(e);else{const t=new this.bjsAMMO.btConvexHullShape;0==this._addHullVerts(t,i,i)?(e._pluginData.toDispose.push(t),s=new this.bjsAMMO.btCompoundShape):s=t}break;case nl.NoImpostor:s=new this.bjsAMMO.btSphereShape(r.x/2);break;case nl.CustomImpostor:s=this._createCustom(e);break;case nl.SoftbodyImpostor:s=this._createSoftbody(e);break;case nl.ClothImpostor:s=this._createCloth(e);break;case nl.RopeImpostor:s=this._createRope(e);break;default:Ne.Warn("The impostor type is not currently supported by the ammo plugin.")}return s}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){const s=e.physicsBody.getWorldTransform();if(Math.abs(s.getOrigin().x()-t.x)>J||Math.abs(s.getOrigin().y()-t.y)>J||Math.abs(s.getOrigin().z()-t.z)>J||Math.abs(s.getRotation().x()-i.x)>J||Math.abs(s.getRotation().y()-i.y)>J||Math.abs(s.getRotation().z()-i.z)>J||Math.abs(s.getRotation().w()-i.w)>J)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),s.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),s.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(s),0==e.mass){const t=e.physicsBody.getMotionState();t&&t.setWorldTransform(s)}else e.physicsBody.activate()}isSupported(){return void 0!==this.bjsAMMO}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity(),!t)return null;const i=new _e(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity(),!t)return null;const i=new _e(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}setBodyMass(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t}getBodyMass(e){return e._pluginData.mass||0}getBodyFriction(e){return e._pluginData.friction||0}setBodyFriction(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t}getBodyRestitution(e){return e._pluginData.restitution||0}setBodyRestitution(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t}getBodyPressure(e){return e.soft?e._pluginData.pressure||0:(Ne.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===nl.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):Ne.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(Ne.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):Ne.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(Ne.Warn("Velocity iterations is not a property of a rigid body"),0)}setBodyVelocityIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):Ne.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(Ne.Warn("Position iterations is not a property of a rigid body"),0)}setBodyPositionIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):Ne.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,s,r=1,n=!1){const o=e.segments,a=Math.round((o-1)*i)+o*(o-1-Math.round((o-1)*s));e.physicsBody.appendAnchor(a,t.physicsBody,n,r)}appendHook(e,t,i,s=1,r=!1){const n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,r,s)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){Ne.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){Ne.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){return e.getObjectExtents().x/2}getBoxSizeToRef(e,t){const i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._softBodySolver),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoVectorD),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);const s=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,s),i.reset(e,t),s.hasHit()&&(i.setHitData({x:s.get_m_hitNormalWorld().x(),y:s.get_m_hitNormalWorld().y(),z:s.get_m_hitNormalWorld().z()},{x:s.get_m_hitPointWorld().x(),y:s.get_m_hitPointWorld().y(),z:s.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(s),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}px._DISABLE_COLLISION_FLAG=4,px._KINEMATIC_FLAG=2,px._DISABLE_DEACTIVATION_FLAG=4,X.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return-1;const t=this.reflectionProbes.indexOf(e);return-1!==t&&this.reflectionProbes.splice(t,1),t},X.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};class fx{constructor(e,t,i,s=!0,r=!1,n=!1){if(this.name=e,this._viewMatrix=me.Identity(),this._target=_e.Zero(),this._add=_e.Zero(),this._invertYAxis=!1,this.position=_e.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(r){const e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?o=2:e.textureFloatRender&&(o=1)}this._renderTargetTexture=new ih(e,t,i,s,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const a=i.getEngine().useReverseDepthBuffer;let l;this._renderTargetTexture.onBeforeRenderObservable.add((e=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){case 0:this._add.copyFromFloats(1,0,0);break;case 1:this._add.copyFromFloats(-1,0,0);break;case 2:this._add.copyFromFloats(0,this._invertYAxis?1:-1,0);break;case 3:this._add.copyFromFloats(0,this._invertYAxis?-1:1,0);break;case 4:this._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:this._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1)}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);const t=i.useRightHandedSystem?me.LookAtRHToRef:me.LookAtLHToRef,s=i.useRightHandedSystem?me.PerspectiveFovRH:me.PerspectiveFovLH;t(this.position,this._target,_e.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=s(Math.PI/2,1,a?i.activeCamera.maxZ:i.activeCamera.minZ,a?i.activeCamera.minZ:i.activeCamera.maxZ,this._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(this._viewMatrix,this._projectionMatrix),i.activeCamera.isRigCamera&&!this._renderTargetTexture.activeCamera&&(this._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=this.position})),this._renderTargetTexture.onBeforeBindObservable.add((()=>{this._currentSceneUBO=i.getSceneUniformBuffer(),i.getEngine()._debugPushGroup?.(`reflection probe generation for ${e}`,1),l=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)})),this._renderTargetTexture.onAfterUnbindObservable.add((()=>{i.imageProcessingConfiguration.applyByPostProcess=l,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),i.getEngine()._debugPopGroup?.(1)}))}get samples(){return this._renderTargetTexture.samples}set samples(e){this._renderTargetTexture.samples=e}get refreshRate(){return this._renderTargetTexture.refreshRate}set refreshRate(e){this._renderTargetTexture.refreshRate=e}getScene(){return this._scene}get cubeTexture(){return this._renderTargetTexture}get renderList(){return this._renderTargetTexture.renderList}set renderList(e){this._renderTargetTexture.renderList=e}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){const e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){const e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}toString(e){let t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t}getClassName(){return"ReflectionProbe"}serialize(){const e=St.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let s=null;if(t.reflectionProbes)for(let i=0;is||new fx(e.name,e.renderTargetSize,t,e._generateMipMaps)),e,t,i),s.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&s.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(s.metadata=e.metadata),s}}Ze([ct()],fx.prototype,"_attachedMesh",void 0),Ze([ht()],fx.prototype,"position",void 0);class mx{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,s,r){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=s||1,this._animationStarted=!0,this._onBaseAnimationEnd=r,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class gx extends mx{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=new Array,this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new K,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new Ae(1,1,1,1),this.position=_e.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,s,r=null){this._onAnimationEnd=r,super.playAnimation(e,t,i,s,this._endAnimation)}dispose(){for(let e=0;e0)for(let n=0;n=r.distance))&&(r=a,i))break}return r||new tr},Hr.prototype._internalMultiPickSprites=function(e,t,i){if(!tr)return null;let s=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let r=0;r!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(or.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(or.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(or.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();const e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,s,r){const n=this.scene.pickSprite(t,i,this._spritePredicate,s,r);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,s,r){const n=this.scene;return s?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&r&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?r.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:r.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null),i}_pointerDown(e,t,i,s){const r=this.scene;if(r._pickedDownSprite=null,r.spriteManagers&&r.spriteManagers.length>0&&(i=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(r._pickedDownSprite=i.pickedSprite,s.button){case 0:i.pickedSprite.actionManager.processTrigger(2,Re.CreateNewFromSprite(i.pickedSprite,r,s));break;case 1:i.pickedSprite.actionManager.processTrigger(4,Re.CreateNewFromSprite(i.pickedSprite,r,s));break;case 2:i.pickedSprite.actionManager.processTrigger(3,Re.CreateNewFromSprite(i.pickedSprite,r,s))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,Re.CreateNewFromSprite(i.pickedSprite,r,s))}return i}_pointerUp(e,t,i,s,r){const n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){const i=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,Re.CreateNewFromSprite(i.pickedSprite,n,s)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,Re.CreateNewFromSprite(i.pickedSprite,n,s)),r&&i.pickedSprite.actionManager.processTrigger(6,Re.CreateNewFromSprite(i.pickedSprite,n,s)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==i.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,Re.CreateNewFromSprite(n._pickedDownSprite,n,s)))}return i}}Bi.IncludesShadersStore.imageProcessingCompatibility="#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));\n#endif\n";Bi.ShadersStore.spritesPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler;\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nvec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;}\n#endif\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvec2 uv=uvPixelPerfect(vUV);\n#else\nvec2 uv=vUV;\n#endif\nvec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.)\n{if (color.a<0.95)\ndiscard;}\ncolor*=vColor;\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.spritesVertexShader="attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor;\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); \nvColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y;\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";class xx{get fogEnabled(){return this._fogEnabled}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this._createEffects())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=!!this._scene?.getEngine().getCaps().fragmentDepthSupported;e&&!t&&Ne.Warn("Logarithmic depth has been requested for a sprite renderer on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._createEffects()}get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,s=null){this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this._fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=s,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new Js(e,this._vertexData,!0,this._vertexBufferSize);const r=this._buffer.createVertexBuffer(er.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),n=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing);let o,a=6;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Js(e,t,!1,2),o=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else o=this._buffer.createVertexBuffer("offsets",a,2,this._vertexBufferSize,this._useInstancing),a+=2;const l=this._buffer.createVertexBuffer("inverts",a,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",a+2,4,this._vertexBufferSize,this._useInstancing),c=this._buffer.createVertexBuffer(er.ColorKind,a+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[er.PositionKind]=r,this._vertexBuffers.options=n,this._vertexBuffers.offsets=o,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[er.ColorKind]=c,this._createEffects()}_createEffects(){this._drawWrapperBase?.dispose(),this._drawWrapperDepth?.dispose(),this._drawWrapperBase=new Un(this._engine),this._drawWrapperDepth=new Un(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing);let e="";this._pixelPerfect&&(e+="#define PIXEL_PERFECT\n"),this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&this._fogEnabled&&(e+="#define FOG\n"),this._useLogarithmicDepth&&(e+="#define LOGARITHMICDEPTH\n"),this._drawWrapperBase.effect=this._engine.createEffect("sprites",[er.PositionKind,"options","offsets","inverts","cellInfo",er.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor","logarithmicDepthConstant"],["diffuseSampler"],e),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext}render(e,t,i,s,r=null){if(!this.texture||!this.texture.isReady()||!e.length)return;const n=this._drawWrapperBase,o=this._drawWrapperDepth,a=this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode,l=n.effect;if(!l.isReady())return;const h=this._engine,c=!(!this._scene||!this._scene.useRightHandedSystem),u=this.texture.getBaseSize(),d=Math.min(this._capacity,e.length);let _=0,p=!0;for(let i=0;i{e.cellRef||(e.cellIndex=0);const i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=this._spriteMap[e.cellIndex]),e._xOffset=this._cellData[e.cellRef].frame.x/t.width,e._yOffset=this._cellData[e.cellRef].frame.y/t.height,e._xSize=this._cellData[e.cellRef].frame.w,e._ySize=this._cellData[e.cellRef].frame.h},r||(r=re.LastCreatedScene),r._getComponent(or.NAME_SPRITE)||r._addComponent(new vx(r)),this._fromPacked=a,this._scene=r;const h=this._scene.getEngine();if(this._spriteRenderer=new xx(h,i,n,r),s.width&&s.height)this.cellWidth=s.width,this.cellHeight=s.height;else{if(void 0===s)return void(this._spriteRenderer=null);this.cellWidth=s,this.cellHeight=s}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new Pa(t,r,!0,!1,o)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if(e="string"==typeof t?JSON.parse(t):t,e.frames.length){const t={};for(let i=0;i0);const s=e.substring(0,i-1)+".json",r=()=>{Ne.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},n=e=>{try{const t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};Ds.LoadFile(s,n,void 0,void 0,!1,r)}}_checkTextureAlpha(e,t,i,s,r){if(!e.useAlphaForPicking||!this.texture)return!0;const n=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(n.width*n.height*4),this.texture.readPixels(0,0,this._textureContent));const o=ve.Vector3[0];o.copyFrom(t.direction),o.normalize(),o.scaleInPlace(i),o.addInPlace(t.origin);const a=(o.x-s.x)/(r.x-s.x),l=1-(o.y-s.y)/(r.y-s.y),h=e._xOffset*n.width+a*e._xSize|0,c=e._yOffset*n.height+l*e._ySize|0;return this._textureContent[4*(h+c*n.width)+3]>.5}intersects(e,t,i,s){const r=Math.min(this.capacity,this.sprites.length),n=_e.Zero(),o=_e.Zero();let a=Number.MAX_VALUE,l=null;const h=ve.Vector3[0],c=ve.Vector3[1],u=t.getViewMatrix();let d=e,_=e;for(let t=0;te){if(!this._checkTextureAlpha(r,d,e,n,o))continue;if(_=d,a=e,l=r,s)break}}}}if(l){const e=new tr;u.invertToRef(ve.Matrix[0]),e.hit=!0,e.pickedSprite=l,e.distance=a;const t=ve.Vector3[2];return t.copyFrom(_.direction),t.normalize(),t.scaleInPlace(a),_.origin.addToRef(t,h),e.pickedPoint=_e.TransformCoordinates(h,ve.Matrix[0]),e}return null}multiIntersects(e,t,i){const s=Math.min(this.capacity,this.sprites.length),r=_e.Zero(),n=_e.Zero();let o;const a=[],l=ve.Vector3[0].copyFromFloats(0,0,0),h=ve.Vector3[1].copyFromFloats(0,0,0),c=t.getViewMatrix();for(let t=0;t{const o=new Pt;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=bx.Parse(t,i||re.LastCreatedScene,s);e&&(n.name=e),r(n)}else n("Unable to load the sprite manager")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new bx("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise(((s,r)=>{const n=new Pt;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const r=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(r.spriteManager),a=bx.Parse(o,t||re.LastCreatedScene,i);a.snippetId=e,s(a)}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}bx.SnippetUrl="https://snippet.babylonjs.com",bx.CreateFromSnippetAsync=bx.ParseFromSnippetAsync;var Tx=!0;class yx{}yx.LoaderInjectedPhysicsEngine=void 0;let Sx={},Cx={};const Ex=(e,t,i,s)=>{if(!t.materials)return null;for(let r=0,n=t.materials.length;r{for(const s in t)if(e.name===t[s])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},Px=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),Ix=(e,t)=>{const i=t;if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){const s=t._waitingData.lods.ids,r=i.isEnabled(!1);if(t._waitingData.lods.distances){const n=t._waitingData.lods.distances;if(n.length>=s.length){const t=n.length>s.length?n[n.length-1]:0;i.setEnabled(!1);for(let t=0;t0&&i.addLODLevel(t,null),!0===r&&i.setEnabled(!0)}else Ds.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},Rx=(e,t,i)=>{if("number"!=typeof e){const s=i.getLastEntryById(e);return s&&null!=t?s.instances[parseInt(t)]:s}const s=Sx[e];return s&&null!=t?s.instances[parseInt(t)]:s},Mx=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):Cx[e],Ox=(e,t,i,s,r=!1)=>{const n=new pa(e);let o="importScene has failed JSON parse";try{var a=JSON.parse(t);o="";const s=fl.loggingLevel===fl.DETAILED_LOGGING;let r,l;if(void 0!==a.environmentTexture&&null!==a.environmentTexture){const t=void 0===a.isPBR||a.isPBR;if(a.environmentTextureType&&"BABYLON.HDRCubeTexture"===a.environmentTextureType){const s=a.environmentTextureSize?a.environmentTextureSize:128,r=new nx((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,s,!0,!t,void 0,a.environmentTexturePrefilterOnLoad);a.environmentTextureRotationY&&(r.rotationY=a.environmentTextureRotationY),e.environmentTexture=r}else if("object"==typeof a.environmentTexture){const t=vg.Parse(a.environmentTexture,e,i);e.environmentTexture=t}else if(a.environmentTexture.endsWith(".env")){const t=new vg((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}else{const t=vg.CreateFromPrefilteredData((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}if(!0===a.createDefaultSkybox){const i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,s=a.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,s)}n.environmentTexture=e.environmentTexture}if(void 0!==a.environmentIntensity&&null!==a.environmentIntensity&&(e.environmentIntensity=a.environmentIntensity),void 0!==a.lights&&null!==a.lights)for(r=0,l=a.lights.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})))}if(void 0!==a.multiMaterials&&null!==a.multiMaterials)for(r=0,l=a.multiMaterials.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)}))}if(void 0!==a.morphTargetManagers&&null!==a.morphTargetManagers)for(const t of a.morphTargetManagers){const i=lx.Parse(t,e);n.morphTargetManagers.push(i),i._parentContainer=n}if(void 0!==a.skeletons&&null!==a.skeletons)for(r=0,l=a.skeletons.length;r{e&&(n.geometries.push(e),e._parentContainer=n)}))}if(void 0!==a.transformNodes&&null!==a.transformNodes)for(r=0,l=a.transformNodes.length;r{t._waitingSubMaterialsUniqueIds.forEach((i=>{t.subMaterials.push(Mx(i,e))})),t._waitingSubMaterialsUniqueIds=[]})),e.meshes.forEach((t=>{null!==t._waitingMaterialId&&(t.material=Mx(t._waitingMaterialId,e),t._waitingMaterialId=null)})),r=0,l=e.skeletons.length;r{if(t._waitingTransformNodeId){const i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}})),t._hasWaitingData=null)}for(r=0,l=e.meshes.length;r0){for(let i=0;i0){for(let i=0;i{e._loadedUniqueId=""})),X.Parse(a,e,n,i),r=0,l=e.meshes.length;r-1!==e.indexOf("babylon"),importMesh:(e,t,i,s,r,n,o,a)=>{let l="importMesh has failed JSON parse";try{var h=JSON.parse(i);l="";const a=fl.loggingLevel===fl.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;const c=[],u=new Map,d=[];if(void 0!==h.transformNodes&&null!==h.transformNodes)for(let e=0,i=h.transformNodes.length;e{!0!==e&&h.geometries[i]&&Array.isArray(h.geometries[i])&&h.geometries[i].forEach((r=>{r.id===f.geometryId&&("vertexData"===i&&Yn.Parse(r,t,s),e=!0)}))})),!1===e&&Ne.Warn("Geometry not found for mesh "+f.id)}if(f.materialUniqueId||f.materialId){const e=f.materialUniqueId?_:n;let i=-1!==e.indexOf(f.materialUniqueId||f.materialId);if(!1===i&&void 0!==h.multiMaterials&&null!==h.multiMaterials){const r=(i,r)=>{e.push(i);const n=Ex(r,h,t,s);n&&n.material&&(Cx[n.parsedMaterial.uniqueId||n.parsedMaterial.id]=n.material,l+="\n\tMaterial "+n.material.toString(a))};for(let s=0,n=h.multiMaterials.length;sr(e,(t=>t.uniqueId===e)))):n.materials.forEach((e=>r(e,(t=>t.id===e)))),e.push(n.uniqueId||n.id);const s=ia.ParseMultiMaterial(n,t);Cx[n.uniqueId||n.id]=s,s&&(i=!0,l+="\n\tMulti-Material "+s.toString(a));break}}}if(!1===i){e.push(f.materialUniqueId||f.materialId);const i=Ex((e=>f.materialUniqueId&&e.uniqueId===f.materialUniqueId||e.id===f.materialId),h,t,s);i&&i.material?(Cx[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,l+="\n\tMaterial "+i.material.toString(a)):Ne.Warn("Material not found for mesh "+f.id)}}if(null!==f.skeletonId&&void 0!==f.skeletonId&&-1!==h.skeletonId&&void 0!==h.skeletons&&null!==h.skeletons&&!(i.indexOf(f.skeletonId)>-1))for(let e=0,s=h.skeletons.length;e-1&&void 0!==h.morphTargetManagers&&null!==h.morphTargetManagers&&!(p.indexOf(f.morphTargetManagerId)>-1))for(let e=0,i=h.morphTargetManagers.length;e{e._waitingSubMaterialsUniqueIds.forEach((i=>{e.subMaterials.push(Mx(i,t))})),e._waitingSubMaterialsUniqueIds=[]})),t.meshes.forEach((e=>{null!==e._waitingMaterialId&&(e.material=Mx(e._waitingMaterialId,t),e._waitingMaterialId=null)}));for(let e=0,i=t.transformNodes.length;e-1&&d.splice(e,1)}f._waitingParentId=null}f._waitingData.lods&&Ix(t,f)}for(const e of d)e.dispose();for(let e=0,i=t.skeletons.length;e{if(e._waitingTransformNodeId){const i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}})),i._hasWaitingData=null)}for(let e=0,i=t.meshes.length;e{e._loadedUniqueId=""})),!0}catch(e){const t=Px("importMesh",h?h.producer:"Unknown")+l;if(!a)throw Ne.Log(t),e;a(t,e)}finally{null!==l&&fl.loggingLevel!==fl.NO_LOGGING&&Ne.Log(Px("importMesh",h?h.producer:"Unknown")+(fl.loggingLevel!==fl.MINIMAL_LOGGING?l:"")),Cx={}}return!1},load:(e,t,i,s)=>{let r="importScene has failed JSON parse";try{var n=JSON.parse(t);switch(r="",void 0!==n.useDelayedTextureLoading&&null!==n.useDelayedTextureLoading&&(e.useDelayedTextureLoading=n.useDelayedTextureLoading&&!fl.ForceFullSceneLoadingForIncremental),void 0!==n.autoClear&&null!==n.autoClear&&(e.autoClear=n.autoClear),void 0!==n.clearColor&&null!==n.clearColor&&(e.clearColor=Ae.FromArray(n.clearColor)),void 0!==n.ambientColor&&null!==n.ambientColor&&(e.ambientColor=Ee.FromArray(n.ambientColor)),void 0!==n.gravity&&null!==n.gravity&&(e.gravity=_e.FromArray(n.gravity)),void 0!==n.useRightHandedSystem&&(e.useRightHandedSystem=!!n.useRightHandedSystem),void 0!==n.fogMode&&null!==n.fogMode&&(e.fogMode=n.fogMode),void 0!==n.fogColor&&null!==n.fogColor&&(e.fogColor=Ee.FromArray(n.fogColor)),void 0!==n.fogStart&&null!==n.fogStart&&(e.fogStart=n.fogStart),void 0!==n.fogEnd&&null!==n.fogEnd&&(e.fogEnd=n.fogEnd),void 0!==n.fogDensity&&null!==n.fogDensity&&(e.fogDensity=n.fogDensity),r+="\tFog mode for scene: ",e.fogMode){case 0:r+="none\n";break;case 1:r+="exp\n";break;case 2:r+="exp2\n";break;case 3:r+="linear\n"}if(n.physicsEnabled){let t;"cannon"===n.physicsEngine||n.physicsEngine===dx.name?t=new dx(void 0,void 0,yx.LoaderInjectedPhysicsEngine):"oimo"===n.physicsEngine||n.physicsEngine===_x.name?t=new _x(void 0,yx.LoaderInjectedPhysicsEngine):"ammo"!==n.physicsEngine&&n.physicsEngine!==px.name||(t=new px(void 0,yx.LoaderInjectedPhysicsEngine,void 0)),r="\tPhysics engine "+(n.physicsEngine?n.physicsEngine:"oimo")+" enabled\n";const i=n.physicsGravity?_e.FromArray(n.physicsGravity):null;e.enablePhysics(i,t)}return void 0!==n.metadata&&null!==n.metadata&&(e.metadata=n.metadata),void 0!==n.collisionsEnabled&&null!==n.collisionsEnabled&&(e.collisionsEnabled=n.collisionsEnabled),!!Ox(e,t,i,s,!0)&&(n.autoAnimate&&e.beginAnimation(e,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1),void 0!==n.activeCameraID&&null!==n.activeCameraID&&e.setActiveCameraById(n.activeCameraID),!0)}catch(e){const t=Px("importScene",n?n.producer:"Unknown")+r;if(!s)throw Ne.Log(t),e;s(t,e)}finally{null!==r&&fl.loggingLevel!==fl.NO_LOGGING&&Ne.Log(Px("importScene",n?n.producer:"Unknown")+(fl.loggingLevel!==fl.MINIMAL_LOGGING?r:""))}return!1},loadAssetContainer:(e,t,i,s)=>Ox(e,t,i,s)});class Dx{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,oo.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||Ee.White(),this.rightColor=e.rightColor||Ee.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){const e=new Dx;return Ye.DeepCopy(this,e),e}equals(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled}serialize(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}}static Parse(e){return new Dx({isEnabled:e.isEnabled,leftColor:Ee.FromArray(e.leftColor),rightColor:Ee.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}St._FresnelParametersParser=Dx.Parse;class wx{}wx.BindSceneUniformBuffer=Ro,wx.PrepareDefinesForMergedUV=Mo,wx.BindTextureMatrix=Oo,wx.GetFogState=Uo,wx.PrepareDefinesForMisc=Go,wx.PrepareDefinesForCamera=Zo,wx.PrepareDefinesForFrameBoundValues=Ho,wx.PrepareDefinesForBones=Xo,wx.PrepareDefinesForMorphTargets=Yo,wx.PrepareDefinesForBakedVertexAnimation=Qo,wx.PrepareDefinesForAttributes=jo,wx.PrepareDefinesForMultiview=Ko,wx.PrepareDefinesForOIT=$o,wx.PrepareDefinesForPrePass=qo,wx.PrepareDefinesForLight=Wo,wx.PrepareDefinesForLights=zo,wx.PrepareUniformsAndSamplersForLight=Jo,wx.PrepareUniformsAndSamplersList=ea,wx.HandleFallbacksForShadows=Vo,wx.PrepareAttributesForMorphTargetsInfluencers=Eo,wx.PrepareAttributesForMorphTargets=Ao,wx.PrepareAttributesForBakedVertexAnimation=Do,wx.PrepareAttributesForBones=Bo,wx.PrepareAttributesForInstances=ko,wx.PushAttributesForInstances=Po,wx.BindLightProperties=No,wx.BindLight=Fo,wx.BindLights=Lo,wx.BindFogParameters=Co,wx.BindBonesParameters=wo,wx.BindMorphTargetParameters=Io,wx.BindLogDepth=So;class Nx extends Nd{constructor(e,t){super(e,t,"color",{attributes:["position"],uniforms:["world","viewProjection","color"]}),this.disableColorWrite=!0,this.forceDepthWrite=!0,this.setColor4("color",new Ae(0,0,0,1))}}class Fx extends Gg{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new Ee(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}Ze([rt(),st("_markAllSubMeshesAsLightsDirty")],Fx.prototype,"maxSimultaneousLights",void 0),Ze([rt(),st("_markAllSubMeshesAsLightsDirty")],Fx.prototype,"disableLighting",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],Fx.prototype,"environmentTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Fx.prototype,"invertNormalMapX",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Fx.prototype,"invertNormalMapY",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],Fx.prototype,"normalTexture",void 0),Ze([ot("emissive"),st("_markAllSubMeshesAsTexturesDirty")],Fx.prototype,"emissiveColor",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Fx.prototype,"emissiveTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],Fx.prototype,"occlusionStrength",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],Fx.prototype,"occlusionTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],Fx.prototype,"alphaCutOff",void 0),Ze([rt()],Fx.prototype,"doubleSided",null),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty",null)],Fx.prototype,"lightmapTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Fx.prototype,"useLightmapAsShadowmap",void 0);class Lx extends Fx{constructor(e,t){super(e,t),this._useRoughnessFromMetallicTextureAlpha=!1,this._useRoughnessFromMetallicTextureGreen=!0,this._useMetallnessFromMetallicTextureBlue=!0,this.metallic=1,this.roughness=1}getClassName(){return"PBRMetallicRoughnessMaterial"}clone(e){const t=St.Clone((()=>new Lx(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=St.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const s=St.Parse((()=>new Lx(e.name,t)),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}Ze([ot(),st("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Lx.prototype,"baseColor",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Lx.prototype,"baseTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Lx.prototype,"metallic",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Lx.prototype,"roughness",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],Lx.prototype,"metallicRoughnessTexture",void 0),z("BABYLON.PBRMetallicRoughnessMaterial",Lx);class Bx extends Fx{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=St.Clone((()=>new Bx(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=St.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const s=St.Parse((()=>new Bx(e.name,t)),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}Ze([ot("diffuse"),st("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Bx.prototype,"diffuseColor",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Bx.prototype,"diffuseTexture",void 0),Ze([ot("specular"),st("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],Bx.prototype,"specularColor",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty","_microSurface")],Bx.prototype,"glossiness",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],Bx.prototype,"specularGlossinessTexture",void 0),z("BABYLON.PBRSpecularGlossinessMaterial",Bx);class kx extends ya{constructor(e,t,i=null){if(super(t),e)if(this._textureMatrix=me.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){const e=this._getEngine();let t;t=e._features.support3DTextures?e.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):e.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=t,this._texture.isReady=!1,this.isCube=!1,this.is3D=e._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;const i=i=>{if("string"!=typeof i)return;let s,r=null,n=null;const o=i.split("\n");let a=0,l=0,h=0,c=0,u=0;for(let e=0;e0&&(e+1)%4==0)r[e]=255;else{const t=n[e];r[e]=t/u*255}t.is3D?(t.updateSize(a,a,a),e.updateRawTexture3D(t,r,5,!1)):(t.updateSize(a*a,a),e.updateRawTexture(t,r,5,!1)),t.isReady=!0,this._triggerOnLoad()},s=this.getScene();return s?s._loadFile(this.url,i):e._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){const e=new kx(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())}static Parse(e,t){let i=null;return e.name&&!e.isRenderTarget&&(i=new kx(e.name,t),i.name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}}kx._NoneEmptyLineRegex=/\S+/,z("BABYLON.ColorGradingTexture",kx);class Vx extends ya{constructor(e,t,i,s=!1,r=!0,n=null,o=null,a=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=Pa.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=a,this._noMipmap=s,this.gammaSpace=r,this._onLoad=n,this._onError=o,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?n&&(this._texture.isReady?Ds.SetImmediate((()=>n())):this._texture.onLoadedObservable.add(n)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage((()=>this._loadTexture()),this._onError)}_loadImage(e,t){const i=this.getScene();if(!i)return;const s=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,!this._noMipmap,!1,3);s.generateMipMaps=!this._noMipmap,i.addPendingData(s),s.url=this.url,s.isReady=!1,i.getEngine()._internalTexturesCache.push(s),this._texture=s;const r=document.createElement("canvas");ds(this.url,(t=>{this._width=t.width,this._height=t.height,r.width=this._width,r.height=this._height;const i=r.getContext("2d");i.drawImage(t,0,0);const s=i.getImageData(0,0,t.width,t.height);this._buffer=s.data.buffer,r.remove(),e()}),((e,r)=>{i.removePendingData(s),t&&t(`${this.getClassName()} could not be loaded`,r)}),i?i.offlineProvider:null)}_loadTexture(){const e=this.getScene();if(!e)return;const t=(()=>{const e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=ix.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){const s=t[Vx._FacesMapping[e]];i.push(s)}return i})(),i=this._texture;e.getEngine().updateRawCubeTexture(i,t,i.format,i.type,i.invertY),i.isReady=!0,e.removePendingData(i),i.onLoadedObservable.notifyObservers(i),i.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(3*e.byteLength/4);let s=0;for(let r=0;rt.length)return void Ne.Error("Unable to load TGA file - Not enough data");i+=s.id_length;let r,n=!1,o=!1,a=!1;switch(s.image_type){case Hx:n=!0;case Gx:o=!0;break;case Xx:n=!0;case zx:break;case Yx:n=!0;case Wx:a=!0}const l=s.pixel_size>>3,h=s.width*s.height*l;let c,u,d,_,p,f,m;if(o&&(c=t.subarray(i,i+=s.colormap_length*(s.colormap_size>>3))),n){let e,s,n;r=new Uint8Array(h);let o=0;const a=new Uint8Array(l);for(;i>jx){default:case qx:u=0,_=1,m=s.width,d=0,p=1,f=s.height;break;case Kx:u=0,_=1,m=s.width,d=s.height-1,p=-1,f=-1;break;case Zx:u=s.width-1,_=-1,m=-1,d=0,p=1,f=s.height;break;case $x:u=s.width-1,_=-1,m=-1,d=s.height-1,p=-1,f=-1}const g="_getImageData"+(a?"Grey":"")+s.pixel_size+"bits",v=tb[g](s,c,r,d,p,f,u,_,m);e.getEngine()._uploadDataToTextureDirectly(e,v)}const tb={GetTGAHeader:Jx,UploadContent:eb,_getImageData8bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=t,u=e.width,d=e.height;let _,p,f,m=0;const g=new Uint8Array(u*d*4);for(f=s;f!==n;f+=r)for(p=o;p!==l;p+=a,m++)_=h[m],g[4*(p+u*f)+3]=255,g[4*(p+u*f)+2]=c[3*_+0],g[4*(p+u*f)+1]=c[3*_+1],g[4*(p+u*f)+0]=c[3*_+2];return g},_getImageData16bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p,f=0;const m=new Uint8Array(c*u*4);for(p=s;p!==n;p+=r)for(_=o;_!==l;_+=a,f+=2){d=h[f+0]+(h[f+1]<<8);const e=255*((31744&d)>>10)/31|0,t=255*((992&d)>>5)/31|0,i=255*(31&d)/31|0;m[4*(_+c*p)+0]=e,m[4*(_+c*p)+1]=t,m[4*(_+c*p)+2]=i,m[4*(_+c*p)+3]=32768&d?0:255}return m},_getImageData24bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p=0;const f=new Uint8Array(c*u*4);for(_=s;_!==n;_+=r)for(d=o;d!==l;d+=a,p+=3)f[4*(d+c*_)+3]=255,f[4*(d+c*_)+2]=h[p+0],f[4*(d+c*_)+1]=h[p+1],f[4*(d+c*_)+0]=h[p+2];return f},_getImageData32bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p=0;const f=new Uint8Array(c*u*4);for(_=s;_!==n;_+=r)for(d=o;d!==l;d+=a,p+=4)f[4*(d+c*_)+2]=h[p+0],f[4*(d+c*_)+1]=h[p+1],f[4*(d+c*_)+0]=h[p+2],f[4*(d+c*_)+3]=h[p+3];return f},_getImageDataGrey8bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p,f=0;const m=new Uint8Array(c*u*4);for(p=s;p!==n;p+=r)for(_=o;_!==l;_+=a,f++)d=h[f],m[4*(_+c*p)+0]=d,m[4*(_+c*p)+1]=d,m[4*(_+c*p)+2]=d,m[4*(_+c*p)+3]=255;return m},_getImageDataGrey16bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p=0;const f=new Uint8Array(c*u*4);for(_=s;_!==n;_+=r)for(d=o;d!==l;d+=a,p+=2)f[4*(d+c*_)+0]=h[p+0],f[4*(d+c*_)+1]=h[p+0],f[4*(d+c*_)+2]=h[p+0],f[4*(d+c*_)+3]=h[p+1];return f}};class ib{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=Jx(s);i(r.width,r.height,t.generateMipMaps,!1,(()=>{eb(t,s)}))}}oo._TextureLoaders.push(new ib);class sb{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=sx.RGBE_ReadHeader(s),n=sx.RGBE_ReadPixels(s,r),o=r.width*r.height,a=new Float32Array(4*o);for(let e=0;e{const e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,a)}))}}function rb(){let e=null;function t(e,t,i,s,r){const n=e.getImageTranscodedSizeInBytes(t,i,s);let o=new Uint8Array(n);return e.transcodeImage(o,t,i,s,1,0)?(r&&(o=function(e,t,i,s){const r=new Uint16Array(4),n=new Uint16Array(i*s),o=i/4,a=s/4;for(let t=0;t>2&3],n[h++]=r[l>>4&3],n[h++]=r[l>>6&3]}}return n}(o,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)),o):null}onmessage=i=>{if("init"===i.data.action){if(i.data.url)try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}e||(e=BASIS({wasmBinary:i.data.wasmBinary})),null!==e&&e.then((e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})}))}else if("transcode"===i.data.action){const e=i.data.config,s=i.data.imageData,r=new BASIS.BasisFile(s),n=function(e){const t=e.getHasAlpha(),i=e.getNumImages(),s=[];for(let t=0;t{let i;switch(e){case ab.cTFETC1:i=36196;break;case ab.cTFBC1:i=33776;break;case ab.cTFBC4:i=33779;break;case ab.cTFASTC_4x4:i=37808;break;case ab.cTFETC2:i=37496;break;case ab.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i};let cb=null,ub=null,db=0;const _b=e=>{ub=e},pb=(e,t)=>{const i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise(((e,s)=>{(cb||(cb=new Promise(((e,t)=>{ub?e(ub):Ds.LoadFileAsync(Ds.GetBabylonScriptURL(lb.WasmModuleURL)).then((i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");const s=URL.createObjectURL(new Blob([`(${rb})()`],{type:"application/javascript"}));ub=new Worker(s),function(e,t,i){return new Promise(((s,r)=>{const n=t=>{"init"===t.data.action?(e.removeEventListener("message",n),s(e)):"error"===t.data.action&&r(t.data.error||"error initializing worker")};e.addEventListener("message",n),e.postMessage({action:"init",url:i?Ds.GetBabylonScriptURL(i):void 0,wasmBinary:t},[t])}))}(ub,i,lb.JSModuleURL).then(e,t)})).catch(t)}))),cb).then((()=>{const r=db++,n=t=>{"transcode"===t.data.action&&t.data.id===r&&(ub.removeEventListener("message",n),t.data.success?e(t.data):s("Transcode is not supported on this device"))};ub.addEventListener("message",n);const o=new Uint8Array(i.byteLength);o.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),ub.postMessage({action:"transcode",id:r,imageData:o,config:t,ignoreSupportedFormats:!1},[o.buffer])}),(e=>{s(e)}))}))},fb=(e,t)=>{let i=t._gl?.TEXTURE_2D;e.isCube&&(i=t._gl?.TEXTURE_CUBE_MAP),t._bindTextureDirectly(i,e,!0)},mb=(e,t)=>{const i=e.getEngine();for(let s=0;s{i._releaseTexture(t),fb(e,i)}))}else{e.width=r.width,e.height=r.height,e.generateMipMaps=t.fileInfo.images[s].levels.length>1;const n=gb.GetInternalFormatFromBasisFormat(t.format,i);e.format=n,fb(e,i),t.fileInfo.images[s].levels.forEach(((t,r)=>{i._uploadCompressedDataToTextureDirectly(e,n,t.width,t.height,t.transcodedPixels,s,r)})),!i._features.basisNeedsPOT||be.Log2(e.width)%1==0&&be.Log2(e.height)%1==0||(Ds.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),e._cachedWrapU=Pa.CLAMP_ADDRESSMODE,e._cachedWrapV=Pa.CLAMP_ADDRESSMODE)}}},gb={JSModuleURL:lb.JSModuleURL,WasmModuleURL:lb.WasmModuleURL,GetInternalFormatFromBasisFormat:hb,TranscodeAsync:pb,LoadTextureFromTranscodeResult:mb};Object.defineProperty(gb,"JSModuleURL",{get:function(){return lb.JSModuleURL},set:function(e){lb.JSModuleURL=e}}),Object.defineProperty(gb,"WasmModuleURL",{get:function(){return lb.WasmModuleURL},set:function(e){lb.WasmModuleURL=e}});class vb{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=t.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};pb(e,o).then((e=>{const i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;mb(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()})).catch((e=>{Ds.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,r&&r(e)}))}loadData(e,t,i){const s=t.getEngine().getCaps(),r={supportedCompressionFormats:{etc1:!!s.etc1,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,astc:!!s.astc,bc7:!!s.bptc}};pb(e,r).then((e=>{const s=e.fileInfo.images[0].levels[0],r=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(s.width,s.height,r,-1!==e.format,(()=>{mb(t,e)}))})).catch((e=>{Ds.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),Ds.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,(()=>{}),!0)}))}}ns._TextureLoaders.push(new vb);class xb extends ih{get isSupported(){return this._engine?.getCaps().drawBuffersExtension??!1}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,s,r,n,o,a,l,h){for(let c=0;c{this.onAfterRenderObservable.notifyObservers(t)}))}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){const e=this._renderTarget?.textures;if(e){for(let t=e.length-1;t>=0;t--)this._textures[t]._texture=null;this._renderTarget?.dispose(),this._renderTarget=null}}}class bb{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class Tb{constructor(e,t,i,s){return this.name=e,this.meshes=t,this.scene=s,this.options=i,this.options.map=this.options.map??["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=this.options.uvsIn??er.UVKind,this.options.uvsOut=this.options.uvsOut??er.UVKind,this.options.layout=this.options.layout??Tb.LAYOUT_STRIP,this.options.layout===Tb.LAYOUT_COLNUM&&(this.options.colnum=this.options.colnum??8),this.options.updateInputMeshes=this.options.updateInputMeshes??!0,this.options.disposeSources=this.options.disposeSources??!0,this._expecting=0,this.options.fillBlanks=this.options.fillBlanks??!0,!0===this.options.fillBlanks&&(this.options.customFillColor=this.options.customFillColor??"black"),this.options.frameSize=this.options.frameSize??256,this.options.paddingRatio=this.options.paddingRatio??.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=this.options.paddingMode??Tb.SUBUV_WRAP,this.options.paddingMode===Tb.SUBUV_COLOR&&(this.options.paddingColor=this.options.paddingColor??new Ae(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){const t=this._calculateSize(),i=new de(1,1).divide(t);let s=0;const r=this._expecting,n=this.meshes.length,o=Object.keys(this.sets);for(let e=0;e{this._calculateMeshUVFrames(a,l,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i{s++,d.update(!1);const i=_.getImageData(0,0,h,h),n=this.sets[m];if(n.getContext().putImageData(i,t.x*p.x,t.y*p.y),d.dispose(),n.update(!1),s==r)return c(),void e()},m=o[u]||"_blank";if(n&&null!==n[m]){const e=n[m],t=new Image;t.src=e instanceof uu?e.getContext().canvas.toDataURL("image/png"):e.url,Ds.SetCorsBehavior(t.src,t),t.onload=()=>{_.fillStyle="rgba(0,0,0,0)",_.fillRect(0,0,h,h),d.update(!1),_.setTransform(1,0,0,-1,0,0);const e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let i=0;i<9;i++)_.drawImage(t,0,0,t.width,t.height,l+a*e[i],l+a*e[i+1]-h,a,a);break;case 1:for(let i=0;i{e.dispose&&e.dispose()};for(let e=0;e{try{if(0===this.meshes.length)return void e();let t=0;const i=i=>{if(t++,this.options.map){for(let e=0;e{i(n)}));else if(t++,t===this.meshes.length)return this._createFrames(e)}}catch(e){return t(e)}}))}dispose(){const e=Object.keys(this.sets);for(let t=0;t{const i={name:this.name,sets:{},options:{},frames:[]},s=Object.keys(this.sets),r=Object.keys(this.options);try{for(let r=0;r{try{this.setFragment(this._texturePath)}catch(e){Ne.Log("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},i=e+"/config.json",s=new Pt;s.open("GET",i),s.addEventListener("load",(()=>{if(200===s.status||s.responseText&&s.responseText.length>0)try{this._config=JSON.parse(s.response),this.updateShaderUniforms(),this.updateTextures(),this.setFragment(this._texturePath+"/custom"),this._animate=this._config.animate,this.refreshRate=this._config.refreshrate}catch(e){t()}else t()}),!1),s.addEventListener("error",(()=>{t()}),!1);try{s.send()}catch(e){Ne.Error("CustomProceduralTexture: Error on XHR send request.")}}isReady(){if(!super.isReady())return!1;for(const e in this._textures)if(!this._textures[e].isReady())return!1;return!0}render(e){const t=this.getScene();this._animate&&t&&(this._time+=.03*t.getAnimationRatio(),this.updateShaderUniforms()),super.render(e)}updateTextures(){for(let e=0;e{}))}clone(){return St.Clone((()=>{const e=this.getScene(),t=this._texture,i=new Cb(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return t.source===is.CubeRawRGBD&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i}),this)}}class Eb extends Pa{constructor(e,t,i,s,r,n,o=!0,a=!1,l=Pa.TRILINEAR_SAMPLINGMODE,h=0,c){super(null,n,!o,a),this.format=r,this._texture=n.getEngine().createRawTexture3D(e,t,i,s,r,o,a,l,null,h,c),this.is3D=!0}update(e){this._texture&&this._getEngine().updateRawTexture3D(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}}class Ab extends ih{constructor(e,t,i,s){super(e,t,i,s,!0),this.refractionPlane=new Nr(0,1,0,1),this.depth=2,this.onBeforeRenderObservable.add((()=>{this.getScene().clipPlane=this.refractionPlane})),this.onAfterRenderObservable.add((()=>{this.getScene().clipPlane=null}))}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Ab(this.name,t.width,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.refractionPlane=this.refractionPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i.depth=this.depth,i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e}}class Pb extends Ta{get renderTarget(){return this._renderTarget}constructor(e,t,i){super(null),this._renderTarget=null,this._engine=e,this._renderTargetOptions=i,this.resize(t)}resize(e){this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,this._size=e,this._engine&&(this._renderTarget=this._engine.createRenderTargetTexture(this._size,this._renderTargetOptions)),this._texture=this.renderTarget.texture}getInternalTexture(){return this._texture}getClassName(){return"ThinRenderTargetTexture"}dispose(e=!1){this._renderTarget?.dispose(!0),this._renderTarget=null,e||super.dispose()}}class Ib extends bl{constructor(e,t,i,s,r){super(e,t,i),this._blockType=s,this._blockName=r,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof Ib&&e._blockName===this._blockName?hl.Compatible:hl.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}class Rb extends Tl{constructor(e){super(e,ll.Vertex),this.registerInput("matricesIndices",al.Vector4),this.registerInput("matricesWeights",al.Vector4),this.registerInput("matricesIndicesExtra",al.Vector4,!0),this.registerInput("matricesWeightsExtra",al.Vector4,!0),this.registerInput("world",al.Matrix),this.registerOutput("output",al.Matrix)}initialize(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh")}getClassName(){return"BonesBlock"}get matricesIndices(){return this._inputs[0]}get matricesWeights(){return this._inputs[1]}get matricesIndicesExtra(){return this._inputs[2]}get matricesWeightsExtra(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}autoConfigure(e,t=(()=>!0)){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesIndices"===e.name&&t(e)));i||(i=new Ol("matricesIndices"),i.setAsAttribute("matricesIndices")),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesWeights"===e.name&&t(e)));i||(i=new Ol("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.World&&t(e)));i||(i=new Ol("world"),i.setAsSystemValue(_l.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){wo(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&Xo(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");const t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});const i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});const s=this._outputs[0],r=this.world;return e.compilationString+="#if NUM_BONE_INFLUENCERS>0\n",e.compilationString+=e._declareOutput(s)+` = ${r.associatedVariableName} * ${i};\n`,e.compilationString+="#else\n",e.compilationString+=e._declareOutput(s)+` = ${r.associatedVariableName};\n`,e.compilationString+="#endif\n",this}}z("BABYLON.BonesBlock",Rb);class Mb extends Tl{constructor(e){super(e,ll.Vertex),this.registerInput("world0",al.Vector4),this.registerInput("world1",al.Vector4),this.registerInput("world2",al.Vector4),this.registerInput("world3",al.Vector4),this.registerInput("world",al.Matrix,!0),this.registerOutput("output",al.Matrix),this.registerOutput("instanceID",al.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e,t=(()=>!0)){if(!this.world0.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world0"===e.name&&t(e)));i||(i=new Ol("world0"),i.setAsAttribute("world0")),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world1"===e.name&&t(e)));i||(i=new Ol("world1"),i.setAsAttribute("world1")),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world2"===e.name&&t(e)));i||(i=new Ol("world2"),i.setAsAttribute("world2")),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world3"===e.name&&t(e)));i||(i=new Ol("world3"),i.setAsAttribute("world3")),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world"===e.name&&t(e)));i||(i=new Ol("world"),i.setAsSystemValue(_l.World)),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,s=!1,r){let n=!1;i.INSTANCES!==s&&(i.setValue("INSTANCES",s),n=!0),r&&i.THIN_INSTANCES!==!!r?.getRenderingMesh().hasThinInstances&&(i.setValue("THIN_INSTANCES",!!r?.getRenderingMesh().hasThinInstances),n=!0),n&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);const t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);const i=this._outputs[0],s=this._outputs[1],r=this.world0,n=this.world1,o=this.world2,a=this.world3;let l="mat4",h="gl_InstanceID",c="float";return e.shaderLanguage===di.WGSL&&(l="mat4x4f",h="vertexInputs.instanceIndex",c="f32"),e.compilationString+="#ifdef INSTANCES\n",e.compilationString+=e._declareOutput(i)+` = ${l}(${r.associatedVariableName}, ${n.associatedVariableName}, ${o.associatedVariableName}, ${a.associatedVariableName});\n`,e.compilationString+="#ifdef THIN_INSTANCES\n",e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName};\n`,e.compilationString+="#endif\n",t._caps.canUseGLInstanceID?e.compilationString+=e._declareOutput(s)+` = ${c}(${h});\n`:e.compilationString+=e._declareOutput(s)+" = 0.0;\n",e.compilationString+="#else\n",e.compilationString+=e._declareOutput(i)+` = ${this.world.associatedVariableName};\n`,e.compilationString+=e._declareOutput(s)+" = 0.0;\n",e.compilationString+="#endif\n",this}}z("BABYLON.InstancesBlock",Mb);class Ob extends Tl{constructor(e){super(e,ll.Vertex),this.registerInput("position",al.Vector3),this.registerInput("normal",al.Vector3),this.registerInput("tangent",al.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(al.Color4|al.Vector4|al.Vector3),this.registerInput("uv",al.Vector2),this.registerOutput("positionOutput",al.Vector3),this.registerOutput("normalOutput",al.Vector3),this.registerOutput("tangentOutput",al.Vector4),this.registerOutput("uvOutput",al.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Ol("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Ol("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&t(e)));i||(i=new Ol("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Ol("uv"),i.setAsAttribute("uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const t=e.morphTargetManager;t?.isUsingTextureForTargets&&(t.numMaxInfluencers||t.numInfluencers)!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&Yo(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(Io(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,s){const r=this.position,n=this.normal,o=this.tangent,a=this.uv,l=this.positionOutput,h=this.normalOutput,c=this.tangentOutput,u=this.uvOutput,d=e,_=s.NUM_MORPH_INFLUENCERS,p=i.morphTargetManager,f=p&&p.supportsNormals&&s.NORMAL,m=p&&p.supportsTangents&&s.TANGENT,g=p&&p.supportsUVs&&s.UV1;let v="";p?.isUsingTextureForTargets&&_>0&&(v+=`${d._declareLocalVar("vertexID",al.Float)};\n`),v+="#ifdef MORPHTARGETS\n";const x=d.shaderLanguage===di.WGSL,b=x?"uniforms.":"";if(p?.isUsingTextureForTargets)v+=`for (${x?"var":"int"} i = 0; i < NUM_MORPH_INFLUENCERS; i++) {\n`,v+=`if (i >= ${b}morphTargetCount) { break; }\n`,v+=`vertexID = ${x?"f32(vertexInputs.vertexIndex":"float(gl_VertexID"}) * ${b}morphTargetTextureInfo.x;\n`,v+=`${l.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${r.associatedVariableName}) * ${b}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",f&&(v+="#ifdef MORPHTARGETS_NORMAL\n",v+=`${h.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${n.associatedVariableName}) * ${b}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),g&&(v+="#ifdef MORPHTARGETS_UV\n",v+=`${u.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${a.associatedVariableName}) * ${b}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\n",v+=`${c.associatedVariableName}.xyz += (readVector3FromRawSampler(i, vertexID) - ${o.associatedVariableName}.xyz) * ${b}morphTargetInfluences[i];\n`,o.type===al.Vector4?v+=`${c.associatedVariableName}.w = ${o.associatedVariableName}.w;\n`:v+=`${c.associatedVariableName}.w = 1.;\n`,v+="#endif\n"),v+="}\n";else for(let e=0;e<_;e++)v+=`${l.associatedVariableName} += (position${e} - ${r.associatedVariableName}) * ${b}morphTargetInfluences[${e}];\n`,f&&(v+="#ifdef MORPHTARGETS_NORMAL\n",v+=`${h.associatedVariableName} += (normal${e} - ${n.associatedVariableName}) * ${b}morphTargetInfluences[${e}];\n`,v+="#endif\n"),g&&(v+="#ifdef MORPHTARGETS_UV\n",v+=`${u.associatedVariableName}.xy += (uv_${e} - ${a.associatedVariableName}.xy) * ${b}morphTargetInfluences[${e}];\n`,v+="#endif\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\n",v+=`${c.associatedVariableName}.xyz += (tangent${e} - ${o.associatedVariableName}.xyz) * ${b}morphTargetInfluences[${e}];\n`,o.type===al.Vector4?v+=`${c.associatedVariableName}.w = ${o.associatedVariableName}.w;\n`:v+=`${c.associatedVariableName}.w = 1.;\n`,v+="#endif\n");if(v+="#endif\n",d.compilationString=d.compilationString.replace(this._repeatableContentAnchor,v),_>0)for(let e=0;e<_;e++)d.attributes.push(er.PositionKind+e),f&&d.attributes.push(er.NormalKind+e),m&&d.attributes.push(er.TangentKind+e),g&&d.attributes.push(er.UVKind+"_"+e)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e.sharedData.repeatableContentBlocks.push(this);const t=this.position,i=this.normal,s=this.tangent,r=this.uv,n=this.positionOutput,o=this.normalOutput,a=this.tangentOutput,l=this.uvOutput,h=`//${this.name}`;return e.uniforms.push("morphTargetInfluences"),e.uniforms.push("morphTargetCount"),e.uniforms.push("morphTargetTextureInfo"),e.uniforms.push("morphTargetTextureIndices"),e.samplers.push("morphTargets"),e._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration",h),e._emitFunctionFromInclude("morphTargetsVertexDeclaration",h,{repeatKey:"maxSimultaneousMorphTargets"}),e.compilationString+=`${e._declareOutput(n)} = ${t.associatedVariableName};\n`,e.compilationString+="#ifdef NORMAL\n",e.compilationString+=`${e._declareOutput(o)} = ${i.associatedVariableName};\n`,e.compilationString+="#else\n",e.compilationString+=`${e._declareOutput(o)} = vec3(0., 0., 0.);\n`,e.compilationString+="#endif\n",e.compilationString+="#ifdef TANGENT\n",e.compilationString+=`${e._declareOutput(a)} = ${s.associatedVariableName};\n`,e.compilationString+="#else\n",e.compilationString+=`${e._declareOutput(a)} = vec4(0., 0., 0., 0.);\n`,e.compilationString+="#endif\n",e.compilationString+="#ifdef UV1\n",e.compilationString+=`${e._declareOutput(l)} = ${r.associatedVariableName};\n`,e.compilationString+="#else\n",e.compilationString+=`${e._declareOutput(l)} = vec2(0., 0.);\n`,e.compilationString+="#endif\n",this._repeatableContentAnchor=e._repeatableContentAnchor,e.compilationString+=this._repeatableContentAnchor,this}}z("BABYLON.MorphTargetsBlock",Ob);class Db extends Tl{constructor(e){super(e,ll.Vertex),this.registerInput("worldPosition",al.Vector4,!1,ll.Vertex),this.registerOutput("direction",al.Vector3),this.registerOutput("color",al.Color3),this.registerOutput("intensity",al.Float),this.registerOutput("shadowBias",al.Float),this.registerOutput("shadowNormalBias",al.Float),this.registerOutput("shadowDepthScale",al.Float),this.registerOutput("shadowDepthRange",al.Vector2)}getClassName(){return"LightInformationBlock"}get worldPosition(){return this._inputs[0]}get direction(){return this._outputs[0]}get color(){return this._outputs[1]}get intensity(){return this._outputs[2]}get shadowBias(){return this._outputs[3]}get shadowNormalBias(){return this._outputs[4]}get shadowDepthScale(){return this._outputs[5]}get shadowDepthRange(){return this._outputs[6]}bind(e,t,i){if(!i)return;this.light&&this.light.isDisposed()&&(this.light=null);let s=this.light;const r=t.getScene();if(!s&&r.lights.length&&(s=this.light=r.lights[0],this._forcePrepareDefines=!0),!s||!s.isEnabled)return e.setFloat3(this._lightDataUniformName,0,0,0),void e.setFloat4(this._lightColorUniformName,0,0,0,0);s.transferToNodeMaterialEffect(e,this._lightDataUniformName),e.setColor4(this._lightColorUniformName,s.diffuse,s.intensity);const n=s.getShadowGenerator();if((this.shadowBias.hasEndpoints||this.shadowNormalBias.hasEndpoints||this.shadowDepthScale.hasEndpoints)&&(n?e.setFloat3(this._lightShadowUniformName,n.bias,n.normalBias,n.depthScale):e.setFloat3(this._lightShadowUniformName,0,0,0)),this.shadowDepthRange)if(n&&r.activeCamera){const t=s;e.setFloat2(this._lightShadowExtraUniformName,t.getDepthMinZ(r.activeCamera),t.getDepthMinZ(r.activeCamera)+t.getDepthMaxZ(r.activeCamera))}else e.setFloat2(this._lightShadowExtraUniformName,0,0)}prepareDefines(e,t,i){if(!i._areLightsDirty&&!this._forcePrepareDefines)return;this._forcePrepareDefines=!1;const s=this.light;i.setValue(this._lightTypeDefineName,!!(s&&s instanceof ex),!0)}_buildBlock(e){super._buildBlock(e),e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const t=this.direction,i=this.color,s=this.intensity,r=this.shadowBias,n=this.shadowNormalBias,o=this.shadowDepthScale,a=this.shadowDepthRange;this._lightDataUniformName=e._getFreeVariableName("lightData"),this._lightColorUniformName=e._getFreeVariableName("lightColor"),this._lightShadowUniformName=e._getFreeVariableName("shadowData"),this._lightShadowExtraUniformName=e._getFreeVariableName("shadowExtraData"),this._lightTypeDefineName=e._getFreeDefineName("LIGHTPOINTTYPE");const l=e.shaderLanguage===di.WGSL?"uniforms.":"";return e._emitUniformFromString(this._lightDataUniformName,al.Vector3),e._emitUniformFromString(this._lightColorUniformName,al.Vector4),e.compilationString+=`#ifdef ${this._lightTypeDefineName}\n`,e.compilationString+=e._declareOutput(t)+` = normalize(${this.worldPosition.associatedVariableName}.xyz - ${this._lightDataUniformName});\n`,e.compilationString+="#else\n",e.compilationString+=e._declareOutput(t)+` = ${l}${this._lightDataUniformName};\n`,e.compilationString+="#endif\n",e.compilationString+=e._declareOutput(i)+` = ${l}${this._lightColorUniformName}.rgb;\n`,e.compilationString+=e._declareOutput(s)+` = ${l}${this._lightColorUniformName}.a;\n`,(r.hasEndpoints||n.hasEndpoints||o.hasEndpoints)&&(e._emitUniformFromString(this._lightShadowUniformName,al.Vector3),r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = ${l}${this._lightShadowUniformName}.x;\n`),n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = ${l}${this._lightShadowUniformName}.y;\n`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = ${l}${this._lightShadowUniformName}.z;\n`)),a.hasEndpoints&&(e._emitUniformFromString(this._lightShadowExtraUniformName,al.Vector2),e.compilationString+=e._declareOutput(a)+` = ${this._lightShadowUniformName};\n`),this}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId))}}z("BABYLON.LightInformationBlock",Db);class wb extends Tl{constructor(e){super(e,ll.Fragment),this.convertInputToLinearSpace=!0,this.registerInput("color",al.AutoDetect),this.registerOutput("output",al.Color4),this.registerOutput("rgb",al.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Color4|al.Vector3|al.Vector4)}getClassName(){return"ImageProcessingBlock"}get color(){return this._inputs[0]}get output(){return this._outputs[0]}get rgb(){return this._outputs[1]}initialize(e){e._excludeVariableName("exposureLinear"),e._excludeVariableName("contrast"),e._excludeVariableName("vInverseScreenSize"),e._excludeVariableName("vignetteSettings1"),e._excludeVariableName("vignetteSettings2"),e._excludeVariableName("vCameraColorCurveNegative"),e._excludeVariableName("vCameraColorCurveNeutral"),e._excludeVariableName("vCameraColorCurvePositive"),e._excludeVariableName("txColorTransform"),e._excludeVariableName("colorTransformSettings"),e._excludeVariableName("ditherIntensity")}isReady(e,t,i){return!(i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}prepareDefines(e,t,i){i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i)}bind(e,t,i){i&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),e.sharedData.bindableBlocks.push(this),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity");const t=this.color,i=this._outputs[0],s=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",s),e._emitFunctionFromInclude("imageProcessingDeclaration",s),e._emitFunctionFromInclude("imageProcessingFunctions",s),t.connectedPoint?.isConnected&&(t.connectedPoint.type===al.Color4||t.connectedPoint.type===al.Vector4?e.compilationString+=`${e._declareOutput(i)} = ${t.associatedVariableName};\n`:e.compilationString+=`${e._declareOutput(i)} = vec4(${t.associatedVariableName}, 1.0);\n`,e.compilationString+="#ifdef IMAGEPROCESSINGPOSTPROCESS\n",this.convertInputToLinearSpace&&(e.compilationString+=`${i.associatedVariableName}.rgb = toLinearSpace(${t.associatedVariableName}.rgb);\n`),e.compilationString+="#else\n",e.compilationString+="#ifdef IMAGEPROCESSING\n",this.convertInputToLinearSpace&&(e.compilationString+=`${i.associatedVariableName}.rgb = toLinearSpace(${t.associatedVariableName}.rgb);\n`),e.compilationString+=`${i.associatedVariableName} = applyImageProcessing(${i.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+="#endif\n",this.rgb.hasEndpoints&&(e.compilationString+=e._declareOutput(this.rgb)+` = ${this.output.associatedVariableName}.xyz;\n`)),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace};\n`,e}serialize(){const e=super.serialize();return e.convertInputToLinearSpace=this.convertInputToLinearSpace,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertInputToLinearSpace=e.convertInputToLinearSpace??!0}}Ze([Cl("Convert input to linear space",ul.Boolean,"ADVANCED")],wb.prototype,"convertInputToLinearSpace",void 0),z("BABYLON.ImageProcessingBlock",wb);class Nb extends Tl{constructor(e){super(e,ll.Fragment,!0),this.registerInput("normal",al.AutoDetect,!1),this.normal.addExcludedConnectionPointFromAllowedTypes(al.Color4|al.Vector4|al.Vector3),this.registerInput("tangent",al.Vector4,!1),this.registerInput("world",al.Matrix,!1),this.registerOutput("TBN",al.Object,ll.Fragment,new Ib("TBN",this,cl.Output,Nb,"TBNBlock")),this.registerOutput("row0",al.Vector3,ll.Fragment),this.registerOutput("row1",al.Vector3,ll.Fragment),this.registerOutput("row2",al.Vector3,ll.Fragment)}getClassName(){return"TBNBlock"}initialize(e){e._excludeVariableName("tbnNormal"),e._excludeVariableName("tbnTangent"),e._excludeVariableName("tbnBitangent"),e._excludeVariableName("TBN")}get normal(){return this._inputs[0]}get tangent(){return this._inputs[1]}get world(){return this._inputs[2]}get TBN(){return this._outputs[0]}get row0(){return this._outputs[1]}get row1(){return this._outputs[2]}get row2(){return this._outputs[3]}get target(){return ll.Fragment}set target(e){}autoConfigure(e,t=(()=>!0)){if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.isSystemValue&&e.systemValue===_l.World&&t(e)));i||(i=new Ol("world"),i.setAsSystemValue(_l.World)),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Ol("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&e.type===al.Vector4&&t(e)));i||(i=new Ol("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){const s=this.normal,r=this.tangent;let n=s.isConnected;s.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(s.connectInputBlock?.name)&&(n=!1);let o=r.isConnected;r.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(r.connectInputBlock?.name)&&(o=!1);const a=n&&o;i.setValue("TBNBLOCK",a,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,s=this.world,r=this.TBN,n=this.row0,o=this.row1,a=this.row2,l=e.shaderLanguage===di.WGSL,h=l?"mat3x3f":"mat3",c=l?"f":"";return e.target===ll.Fragment&&(e.compilationString+=`\n // ${this.name}\n ${e._declareLocalVar("tbnNormal",al.Vector3)} = normalize(${t.associatedVariableName}).xyz;\n ${e._declareLocalVar("tbnTangent",al.Vector3)} = normalize(${i.associatedVariableName}.xyz);\n ${e._declareLocalVar("tbnBitangent",al.Vector3)} = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w;\n ${l?"var":"mat3"} ${r.associatedVariableName} = ${h}(${s.associatedVariableName}[0].xyz, ${s.associatedVariableName}[1].xyz, ${s.associatedVariableName}[2].xyz) * ${h}(tbnTangent, tbnBitangent, tbnNormal);\n `,n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = vec3${c}(${r.associatedVariableName}[0][0], ${r.associatedVariableName}[0][1], ${r.associatedVariableName}[0][2]);\n`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = vec3${c}(${r.associatedVariableName}[1[0], ${r.associatedVariableName}[1][1], ${r.associatedVariableName}[1][2]);\n`),a.hasEndpoints&&(e.compilationString+=e._declareOutput(a)+` = vec3${c}(${r.associatedVariableName}[2][0], ${r.associatedVariableName}[2][1], ${r.associatedVariableName}[2][2]);\n`),e.sharedData.blocksWithDefines.push(this)),this}}z("BABYLON.TBNBlock",Nb);class Fb extends Tl{constructor(e){super(e,ll.Fragment),this._tangentSpaceParameterName="",this._tangentCorrectionFactorName="",this._worldMatrixName="",this.invertX=!1,this.invertY=!1,this.useParallaxOcclusion=!1,this.useObjectSpaceNormalMap=!1,this._isUnique=!0,this.registerInput("worldPosition",al.Vector4,!1),this.registerInput("worldNormal",al.Vector4,!1),this.registerInput("worldTangent",al.Vector4,!0),this.registerInput("uv",al.Vector2,!1),this.registerInput("normalMapColor",al.Color3,!1),this.registerInput("strength",al.Float,!1),this.registerInput("viewDirection",al.Vector3,!0),this.registerInput("parallaxScale",al.Float,!0),this.registerInput("parallaxHeight",al.Float,!0),this.registerInput("TBN",al.Object,!0,ll.VertexAndFragment,new Ib("TBN",this,cl.Input,Nb,"TBNBlock")),this.registerInput("world",al.Matrix,!0),this.registerOutput("output",al.Vector4),this.registerOutput("uvOffset",al.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}prepareDefines(e,t,i){const s=this.normalMapColor.connectedPoint._ownerBlock.samplerName,r=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&s||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",r,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Ol("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const e=new Ol("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,s=this.worldPosition,r=this.worldNormal,n=this.worldTangent,o=e.shaderLanguage===di.WGSL,a=o?"mat3x3f":"mat3",l=o?"f":"",h=o?"uniforms.":"";e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,al.Vector2),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,al.Float),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,al.Matrix);let c=null;this.normalMapColor.connectedPoint&&(c=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const u=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&c||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),d=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",_=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${e._emitFloat(this.strength.connectInputBlock.value)}`:`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${this.strength.associatedVariableName}`;o||e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const p={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},f=this.TBN;f.isConnected?e.compilationString+=`\n #ifdef TBNBLOCK\n ${o?"var":"mat3"} vTBN = ${f.associatedVariableName};\n #endif\n `:n.isConnected&&(e.compilationString+=`${e._declareLocalVar("tbnNormal",al.Vector3)} = normalize(${r.associatedVariableName}.xyz);\n`,e.compilationString+=`${e._declareLocalVar("tbnTangent",al.Vector3)} = normalize(${n.associatedVariableName}.xyz);\n`,e.compilationString+=`${e._declareLocalVar("tbnBitangent",al.Vector3)} = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\n`,e.compilationString+=`${o?"var":"mat3"} vTBN = ${a}(tbnTangent, tbnBitangent, tbnNormal);\n`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[p,{search:/varying mat3 vTBN;/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]});const m=o?"fn parallaxOcclusion(vViewDirCoT: vec3f, vNormalCoT: vec3f, texCoord: vec2f, parallaxScale:f32, bump: texture_2d, bumpSampler: sampler)":"#define inline\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)",g=o?/fn parallaxOcclusion\(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32\)/g:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,v=o?"fn parallaxOffset(viewDir: vec3f, heightScale: f32, height_: f32)":"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)",x=o?/fn parallaxOffset\(viewDir: vec3f,heightScale: f32\)/g:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g;e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:g,replace:m},{search:x,replace:v},{search:/texture.+?bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const b=u&&c?`${o?`textureSample(${c}, ${c+"Sampler"}`:`texture2D(${c}`}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName,T=e._getFreeVariableName("tempOutput");return e.compilationString+=e._declareLocalVar(T,al.Vector3)+` = vec3${l}(0.);\n`,e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture.+?bumpSampler,vBumpUV\)/g,replace:`${b}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`${e._declareLocalVar("normalMatrix",al.Matrix)} = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture.+?bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${b}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${o?u&&this.useParallaxOcclusion?`${c}, ${c+"Sampler"}`:"bump, bumpSampler":u&&this.useParallaxOcclusion?c:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${u?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:h+this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:_},{search:/vBumpInfos.z/g,replace:d},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:s.associatedVariableName+".xyz"},{search:/normalW=/g,replace:T+" = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:`${a}(normalMatrix) * `+T},{search:/normalW/g,replace:r.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:u?this.viewDirection.associatedVariableName:`vec3${l}(0.)`},p]}),e.compilationString+=e._declareOutput(this.output)+` = vec4${l}(${T}, 0.);\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX};\n`;return e+=`${this._codeVariableName}.invertY = ${this.invertY};\n`,e+=`${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};\n`,e+=`${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};\n`,e}serialize(){const e=super.serialize();return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!e.useObjectSpaceNormalMap}}Ze([Cl("Invert X axis",ul.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Fb.prototype,"invertX",void 0),Ze([Cl("Invert Y axis",ul.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Fb.prototype,"invertY",void 0),Ze([Cl("Use parallax occlusion",ul.Boolean)],Fb.prototype,"useParallaxOcclusion",void 0),Ze([Cl("Object Space Mode",ul.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Fb.prototype,"useObjectSpaceNormalMap",void 0),z("BABYLON.PerturbNormalBlock",Fb);class Lb extends Tl{constructor(e){super(e,ll.Fragment,!0),this.registerInput("value",al.Float,!0),this.registerInput("cutoff",al.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) { discard; }\n`,this}}z("BABYLON.DiscardBlock",Lb);class Bb extends Tl{constructor(e){super(e,ll.Fragment),this.registerOutput("output",al.Float,ll.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===ll.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary("1.0","0.0",e.shaderLanguage===di.GLSL?"gl_FrontFacing":"fragmentInputs.frontFacing")};\n`,this}}z("BABYLON.FrontFacingBlock",Bb);class kb extends Tl{constructor(e){super(e,ll.Fragment),this.registerInput("input",al.AutoDetect,!1),this.registerOutput("dx",al.BasedOnInput),this.registerOutput("dy",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._outputs[1];e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let s="dFdx",r="dFdy";return e.shaderLanguage===di.WGSL&&(s="dpdx",r="dpdy"),t.hasEndpoints&&(e.compilationString+=e._declareOutput(t)+` = ${s}(${this.input.associatedVariableName});\n`),i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${r}(${this.input.associatedVariableName});\n`),this}}z("BABYLON.DerivativeBlock",kb);class Vb extends Tl{constructor(e){super(e,ll.Fragment),this.registerOutput("xy",al.Vector2,ll.Fragment),this.registerOutput("xyz",al.Vector3,ll.Fragment),this.registerOutput("xyzw",al.Vector4,ll.Fragment),this.registerOutput("x",al.Float,ll.Fragment),this.registerOutput("y",al.Float,ll.Fragment),this.registerOutput("z",al.Float,ll.Fragment),this.registerOutput("w",al.Float,ll.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";const i=e.shaderLanguage===di.WGSL?"fragmentInputs.position":"gl_FragCoord";for(const s of this._outputs)s.hasEndpoints&&(t+=`${e._declareOutput(s)} = ${i}.${s.name};\n`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===ll.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}z("BABYLON.FragCoordBlock",Vb);class Ub extends Tl{constructor(e){super(e,ll.Fragment),this.registerOutput("xy",al.Vector2,ll.Fragment),this.registerOutput("x",al.Float,ll.Fragment),this.registerOutput("y",al.Float,ll.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){const t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(const s of this._outputs)s.hasEndpoints&&(i+=`${e._declareOutput(s)} = ${t}.${s.name};\n`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===ll.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,al.Vector2);const t=e.shaderLanguage===di.WGSL?"uniforms.":"";return e.compilationString+=this.writeOutputs(e,t+this._varName),this}}z("BABYLON.ScreenSizeBlock",Ub);class Gb extends Tl{constructor(e){super(e,ll.Fragment),this.registerInput("vector",al.AutoDetect),this.registerInput("worldViewProjection",al.Matrix),this.registerOutput("output",al.Vector2),this.registerOutput("x",al.Float),this.registerOutput("y",al.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e,t=(()=>!0)){if(!this.worldViewProjection.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.WorldViewProjection&&t(e)));i||(i=new Ol("worldViewProjection"),i.setAsSystemValue(_l.WorldViewProjection)),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const s=i.associatedVariableName,r=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case al.Vector3:e.compilationString+=`${e._declareLocalVar(r,al.Vector4)} = ${s} * vec4${e.fSuffix}(${t.associatedVariableName}, 1.0);\n`;break;case al.Vector4:e.compilationString+=`${e._declareLocalVar(r,al.Vector4)} = ${s} * ${t.associatedVariableName};\n`}return e.compilationString+=`${r} = vec4${e.fSuffix}(${r}.xy / ${r}.w, ${r}.zw);`,e.compilationString+=`${r} = vec4${e.fSuffix}(${r}.xy * 0.5 + vec2${e.fSuffix}(0.5, 0.5), ${r}.zw);`,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${r}.xy;\n`),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${r}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${r}.y;\n`),this}}z("BABYLON.ScreenSpaceBlock",Gb);class zb extends Tl{constructor(e){super(e,ll.Fragment),this.registerInput("input",al.Vector2),this.registerInput("strength",al.Float),this.registerInput("center",al.Vector2),this.registerInput("offset",al.Vector2),this.registerOutput("output",al.Vector2),this.registerOutput("x",al.Float),this.registerOutput("y",al.Float)}getClassName(){return"TwirlBlock"}get input(){return this._inputs[0]}get strength(){return this._inputs[1]}get center(){return this._inputs[2]}get offset(){return this._inputs[3]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(){if(!this.center.isConnected){const e=new Ol("center");e.value=new de(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new Ol("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new Ol("offset");e.value=new de(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),s=e._getFreeVariableName("x"),r=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=` \n ${e._declareLocalVar(t,al.Vector2)} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName};\n ${e._declareLocalVar(i,al.Float)} = ${this.strength.associatedVariableName} * length(${t});\n ${e._declareLocalVar(s,al.Float)} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y;\n ${e._declareLocalVar(r,al.Float)} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y;\n ${e._declareLocalVar(n,al.Vector2)} = vec2(${s} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${r} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y);\n `,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${n};\n`),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${n}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${n}.y;\n`),this}}z("BABYLON.TwirlBlock",zb);class Wb extends Tl{constructor(e){super(e,ll.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",al.Float),this.registerInput("worldPosition",al.Vector3),this.registerInput("worldNormal",al.Vector3),this.registerInput("worldTangent",al.AutoDetect,!0),this.registerOutput("output",al.Vector4),this.registerOutput("xyz",al.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e.shaderLanguage===di.WGSL,s=e.fSuffix;this.generateInWorldSpace||this.worldTangent.isConnected||Ne.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const r=this.generateInWorldSpace?"":"\n vec3 biTangent = cross(norm, tgt);\n mat3 TBN = mat3(tgt, biTangent, norm);\n ",n=this.generateInWorldSpace?"":"\n result = TBN * result;\n result = result * vec3(0.5) + vec3(0.5);\n ";let o=`\n vec4 heightToNormal(float height, vec3 position, vec3 tangent, vec3 normal) {\n vec3 tgt = ${this.automaticNormalizationTangent?"normalize(tangent);":"tangent;"}\n vec3 norm = ${this.automaticNormalizationNormal?"normalize(normal);":"normal;"}\n ${r}\n vec3 worlddX = dFdx(position);\n vec3 worlddY = dFdy(position);\n vec3 crossX = cross(norm, worlddX);\n vec3 crossY = cross(norm, worlddY);\n float d = abs(dot(crossY, worlddX));\n vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));\n inToNormal.y *= -1.0;\n vec3 result = normalize((d * norm) - inToNormal);\n ${n}\n return vec4(result, 0.);\n }`;return i?o=e._babylonSLtoWGSL(o):e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",o,"// heightToNormal"),e.compilationString+=e._declareOutput(t)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:`vec3${s}(0.)`}.xyz, ${this.worldNormal.associatedVariableName});\n`,this.xyz.hasEndpoints&&(e.compilationString+=e._declareOutput(this.xyz)+` = ${this.output.associatedVariableName}.xyz;\n`),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};\n`,e+=`${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};\n`,e+=`${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};\n`,e}serialize(){const e=super.serialize();return e.generateInWorldSpace=this.generateInWorldSpace,e.automaticNormalizationNormal=this.automaticNormalizationNormal,e.automaticNormalizationTangent=this.automaticNormalizationTangent,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.generateInWorldSpace=e.generateInWorldSpace,this.automaticNormalizationNormal=e.automaticNormalizationNormal,this.automaticNormalizationTangent=e.automaticNormalizationTangent}}Ze([Cl("Generate in world space instead of tangent space",ul.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Wb.prototype,"generateInWorldSpace",void 0),Ze([Cl("Force normalization for the worldNormal input",ul.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Wb.prototype,"automaticNormalizationNormal",void 0),Ze([Cl("Force normalization for the worldTangent input",ul.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Wb.prototype,"automaticNormalizationTangent",void 0),z("BABYLON.HeightToNormalBlock",Wb);class Hb extends Tl{constructor(e){super(e,ll.Fragment,!0),this.registerInput("depth",al.Float,!0),this.registerInput("worldPos",al.Vector4,!0),this.registerInput("viewProjection",al.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){super._buildBlock(e);const t=e.shaderLanguage===di.GLSL?"gl_FragDepth":"fragmentOutputs.fragDepth";return this.depth.isConnected?e.compilationString+=`${t} = ${this.depth.associatedVariableName};\n`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=`\n ${e._declareLocalVar("p",al.Vector4)} = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName};\n ${e._declareLocalVar("v",al.Vector4)} = p.z / p.w;\n #ifndef IS_NDC_HALF_ZRANGE\n v = v * 0.5 + 0.5;\n #endif\n ${t} = v;\n \n `:Ne.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}z("BABYLON.FragDepthBlock",Hb);class Xb extends Tl{constructor(e){super(e,ll.Fragment),this.registerInput("worldPosition",al.Vector4,!1),this.registerInput("viewProjection",al.Matrix,!1),this.registerInput("worldNormal",al.AutoDetect,!0),this.registerOutput("depth",al.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM")}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitUniformFromString("biasAndScaleSM",al.Vector3),e._emitUniformFromString("lightDataSM",al.Vector3),e._emitUniformFromString("depthValuesSM",al.Vector3),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`vec4 worldPos = ${this.worldPosition.associatedVariableName};\n`,e.compilationString+="vec3 vPositionWSM;\n",e.compilationString+="float vDepthMetricSM = 0.0;\n",e.compilationString+="float zSM;\n",this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+="\n #if SM_DEPTHTEXTURE == 1\n #ifdef IS_NDC_HALF_ZRANGE\n gl_FragDepth = (clipPos.z / clipPos.w);\n #else\n gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5;\n #endif\n #endif\n ",e.compilationString+=`${e._declareOutput(this.depth)} = vec3(depthSM, 1., 1.);\n`,this}}z("BABYLON.ShadowMapBlock",Xb);class Yb extends Tl{constructor(e){super(e,ll.Fragment,!0),this.registerInput("viewDepth",al.Float,!0),this.registerInput("worldPosition",al.AutoDetect,!0),this.registerInput("viewNormal",al.AutoDetect,!0),this.registerInput("reflectivity",al.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(al.Vector3|al.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(al.Vector3|al.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(al.Vector3|al.Vector4|al.Color3|al.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}get reflectivity(){return this._inputs[3]}_buildBlock(e){super._buildBlock(e);const t=this.worldPosition,i=this.viewNormal,s=this.viewDepth,r=this.reflectivity;e.sharedData.blocksWithDefines.push(this);const n=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",n),e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+="#ifdef PREPASS_DEPTH\r\n",s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${s.associatedVariableName}, 0.0, 0.0, 1.0);\r\n`:e.compilationString+=" gl_FragData[PREPASS_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_POSITION\r\n",t.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===al.Vector4?t.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_NORMAL\r\n",i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===al.Vector4?i.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_REFLECTIVITY\r\n",r.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(${r.associatedVariableName}.rgb, ${r.connectedPoint.type===al.Vector4?r.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#endif\r\n",this}}z("BABYLON.PrePassOutputBlock",Yb);class Qb extends Tl{constructor(e){super(e,ll.VertexAndFragment,!1),this.registerInput("worldPosition",al.Vector4,!1,ll.Vertex),this.registerInput("view",al.Matrix,!1,ll.Vertex),this.registerInput("input",al.AutoDetect,!1,ll.Fragment),this.registerInput("fogColor",al.AutoDetect,!1,ll.Fragment),this.registerOutput("output",al.Color3,ll.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e,t=(()=>!0)){if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.View&&t(e)));i||(i=new Ol("view"),i.setAsSystemValue(_l.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.FogColor&&t(e)));i||(i=new Ol("fogColor",void 0,al.Color3),i.setAsSystemValue(_l.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const s=e.getScene();i.setValue("FOG",t.fogEnabled&&Uo(e,s))}bind(e,t,i){if(!i)return;const s=i.getScene();e.setFloat4(this._fogParameters,s.fogMode,s.fogStart,s.fogEnd,s.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===ll.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=[],i="",s="";e.shaderLanguage===di.WGSL?(t=[{search:/fn CalcFogFactor\(\)/,replace:"fn CalcFogFactor(vFogDistance: vec3f, vFogInfos: vec4f)"},{search:/uniforms.vFogInfos/g,replace:"vFogInfos"},{search:/fragmentInputs.vFogDistance/g,replace:"vFogDistance"}],i="fragmentInputs.",s="uniforms."):t=[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}],e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:t});const r=e._getFreeVariableName("fog"),n=this.input,o=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const a=this._outputs[0];e._emitUniformFromString(this._fogParameters,al.Vector4),e.compilationString+="#ifdef FOG\n",e.compilationString+=`${e._declareLocalVar(r,al.Float)} = CalcFogFactor(${i}${this._fogDistanceName}, ${s}${this._fogParameters});\n`,e.compilationString+=e._declareOutput(a)+` = ${r} * ${n.associatedVariableName}.rgb + (1.0 - ${r}) * ${o.associatedVariableName}.rgb;\n`,e.compilationString+=`#else\n${e._declareOutput(a)} = ${n.associatedVariableName}.rgb;\n`,e.compilationString+="#endif\n"}else{const t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,al.Vector3);const s=e.shaderLanguage===di.WGSL?"vertexOutputs.":"";e.compilationString+=`${s}${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz;\n`}return this}}z("BABYLON.FogBlock",Qb);class jb extends Tl{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,Ne.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?ll.Fragment:ll.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?ll.Fragment:ll.Vertex}constructor(e){super(e,ll.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",al.Vector4,!1,ll.Vertex),this.registerInput("worldNormal",al.Vector4,!1,ll.Fragment),this.registerInput("cameraPosition",al.Vector3,!1,ll.Fragment),this.registerInput("glossiness",al.Float,!0,ll.Fragment),this.registerInput("glossPower",al.Float,!0,ll.Fragment),this.registerInput("diffuseColor",al.Color3,!0,ll.Fragment),this.registerInput("specularColor",al.Color3,!0,ll.Fragment),this.registerInput("view",al.Matrix,!0),this.registerOutput("diffuseOutput",al.Color3,ll.Fragment),this.registerOutput("specularOutput",al.Color3,ll.Fragment),this.registerOutput("shadow",al.Float,ll.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.CameraPosition&&t(e)));i||(i=new Ol("cameraPosition"),i.setAsSystemValue(_l.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const s=e.getScene();if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};Wo(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else zo(s,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;Jo(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,t)}}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?Fo(this.light,this._lightId,s,e,!0):Lo(s,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,al.Vector4)&&(e.compilationString+=(e.shaderLanguage===di.WGSL?"vertexOutputs.":"")+`${s} = ${t.associatedVariableName};\n`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`${e._declareLocalVar("worldPos",al.Vector4)} = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`${e._declareLocalVar("view",al.Matrix)} = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_injectUBODeclaration(e){const t=`//${this.name}`;this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0})}_buildBlock(e){super._buildBlock(e);const t=e.shaderLanguage===di.WGSL,i=t?"f":"",s=`//${this.name}`;if(e.target!==ll.Fragment)return void this._injectVertexCode(e);this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const r=e.shaderLanguage===di.WGSL?"fragmentInputs.":"";e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const n=this.worldPosition;let o=n.associatedVariableName;this.generateOnlyFragmentCode?(o=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`${e._declareLocalVar(o,al.Vector3)};\n`,s),e.compilationString+=`${o} = ${n.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${n.associatedVariableName}`:void 0})):o=r+"v_"+o+".xyz",e._emitFunctionFromInclude("helperFunctions",s),e._emitFunctionFromInclude("lightsFragmentFunctions",s,{replaceStrings:[{search:/vPositionW/g,replace:o}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",s,{replaceStrings:[{search:/vPositionW/g,replace:o}]}),this._injectUBODeclaration(e),0===this._lightId&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`${e._declareLocalVar("viewDirectionW",al.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${o});\n`),e.compilationString+=t?"var info: lightingInfo;\n":"lightingInfo info;\n",e.compilationString+=`${e._declareLocalVar("shadow",al.Float)} = 1.;\n`,e.compilationString+=`${e._declareLocalVar("aggShadow",al.Float)} = 0.;\n`,e.compilationString+=`${e._declareLocalVar("numLights",al.Float)} = 0.;\n`,e.compilationString+=`${e._declareLocalVar("glossiness",al.Float)} = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"};\n`,e.compilationString+=`${e._declareLocalVar("diffuseBase",al.Vector3)} = vec3${i}(0., 0., 0.);\n`,e.compilationString+=`${e._declareLocalVar("specularBase",al.Vector3)} = vec3${i}(0., 0., 0.);\n`,e.compilationString+=`${e._declareLocalVar("normalW",al.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz;\n`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:o+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",s,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${o}.xyz`}),0===this._lightId&&(e.compilationString+="aggShadow = aggShadow / numLights;\n");const a=this.diffuseOutput,l=this.specularOutput;return e.compilationString+=e._declareOutput(a)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""};\n`,l.hasEndpoints&&(e.compilationString+=e._declareOutput(l)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""};\n`),this.shadow.hasEndpoints&&(e.compilationString+=e._declareOutput(this.shadow)+" = aggShadow;\n"),this}serialize(){const e=super.serialize();return e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}Ze([Cl("Generate only fragment code",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:jb._OnGenerateOnlyFragmentCodeChanged}})],jb.prototype,"generateOnlyFragmentCode",void 0),z("BABYLON.LightBlock",jb);class Kb extends Tl{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??re.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get samplerName(){return this._samplerName}constructor(e){super(e,ll.VertexAndFragment),this.registerOutput("source",al.Object,ll.VertexAndFragment,new Ib("source",this,cl.Output,Kb,"ImageSourceBlock"))}bind(e){this.texture&&e.setTexture(this._samplerName,this.texture)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}getClassName(){return"ImageSourceBlock"}get source(){return this._outputs[0]}_buildBlock(e){return super._buildBlock(e),e.target===ll.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Texture"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i,s){super._deserialize(e,t,i,s),e.texture&&!hh.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(0===e.texture.url.indexOf("data:")?i="":s&&(e.texture.url=s(e.texture.url),e.texture.name=e.texture.url),this.texture=Pa.Parse(e.texture,t,i))}}z("BABYLON.ImageSourceBlock",Kb);class $b extends Tl{get texture(){return this.source.isConnected?(this.source.connectedPoint?.ownerBlock).texture:this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??re.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _IsPrePassTextureBlock(e){return"PrePassTextureBlock"===e?.getClassName()}get _isSourcePrePass(){return $b._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!$b._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=this.texture.getScene()??re.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??re.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?ll.Fragment:ll.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",al.AutoDetect,!1,ll.VertexAndFragment),this.registerInput("source",al.Object,!0,ll.VertexAndFragment,new Ib("source",this,cl.Input,Kb,"ImageSourceBlock")),this.registerInput("layer",al.Float,!0),this.registerInput("lod",al.Float,!0),this.registerOutput("rgba",al.Color4,ll.Neutral),this.registerOutput("rgb",al.Color3,ll.Neutral),this.registerOutput("r",al.Float,ll.Neutral),this.registerOutput("g",al.Float,ll.Neutral),this.registerOutput("b",al.Float,ll.Neutral),this.registerOutput("a",al.Float,ll.Neutral),this.registerOutput("level",al.Float,ll.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Vector2|al.Vector3|al.Vector4),this._inputs[0]._prioritizeVertex=!t}getClassName(){return"TextureBlock"}get uv(){return this._inputs[0]}get source(){return this._inputs[1]}get layer(){return this._inputs[2]}get lod(){return this._inputs[3]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}get target(){if(this._fragmentOnly)return ll.Fragment;if(!this.uv.isConnected)return ll.VertexAndFragment;if(this.uv.sourceBlock.isInput)return ll.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===ll.Fragment)return ll.Fragment;if(e.target===ll.Vertex)return ll.VertexAndFragment;if(e.target===ll.Neutral||e.target===ll.VertexAndFragment){const t=e.ownerBlock;if(t.target===ll.Fragment)return ll.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return ll.VertexAndFragment}set target(e){}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected)if(e.mode===Hl.PostProcess){const i=e.getBlockByPredicate((e=>"uv"===e.name&&t(e)));i&&i.connectTo(this)}else{const i=e.mode===Hl.Particle?"particle_uv":"uv";let s=e.getInputBlockByPredicate((e=>e.isAttribute&&e.name===i&&t(e)));s||(s=new Ol("uv"),s.setAsAttribute(i)),s.output.connectTo(this.uv)}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix)return void(this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)));const s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),null==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!!this._isSourcePrePass||!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==ll.Fragment}_injectVertexCode(e){const t=this.uv;this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.declarationVariableName.toUpperCase(),this._mainUVName="vMain"+t.declarationVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,al.Vector2,this._defineName),e._emitVaryingFromString(this._mainUVName,al.Vector2,this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,al.Matrix,this._defineName);const i=e._getShaderType(al.Vector4),s=e._getShaderType(al.Vector2);if(e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`${e._getVaryingName(this._transformedUVName)} = ${s}(${this._textureTransformName} * ${i}(${t.associatedVariableName}.xy, 1.0, 0.0));\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`,e.compilationString+=`${e._getVaryingName(this._mainUVName)} = ${t.associatedVariableName}.xy;\n`,e.compilationString+="#endif\n",this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}}_getUVW(e){let t=e;const i=this._texture?._texture?.is2DArray??!1,s=this._texture?._texture?.is3D??!1;return(i||s)&&(t=`vec3(${e}, ${this.layer.isConnected?this.layer.associatedVariableName:"0"})`),t}_samplerFunc(e){return e.shaderLanguage===di.WGSL?e.target===ll.Vertex?"textureSampleLevel":"textureSample":this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureSample(e,t){if(t.shaderLanguage===di.WGSL){const i=t.target===ll.Vertex;return`${this._samplerFunc(t)}(${this.samplerName},${this.samplerName+"Sampler"}, ${this._getUVW(e)}${this._samplerLodSuffix}${i?", 0":""})`}return`${this._samplerFunc(t)}(${this.samplerName}, ${this._getUVW(e)}${this._samplerLodSuffix})`}_generateTextureLookup(e){e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,al.Vector4)} = ${this._generateTextureSample(e._getVaryingName(this._transformedUVName),e)};\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,al.Vector4)} = ${this._generateTextureSample(this._mainUVName?e._getVaryingName(this._mainUVName):this.uv.associatedVariableName,e)}${this._samplerLodSuffix};\n`,e.compilationString+="#endif\n"}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===ll.Fragment)return;this._generateTextureLookup(e)}else this.uv.ownerBlock.target!==ll.Fragment?this._generateTextureLookup(e):e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,al.Vector4)} = ${this._generateTextureSample(i.associatedVariableName,e)}${this._samplerLodSuffix};\n`}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i,s=!1){if(s){if(e.target===ll.Fragment)return;return e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i)}if(this.uv.ownerBlock.target===ll.Fragment)return e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i);let r="";this.disableLevelMultiplication||(r=" * "+(e.shaderLanguage===di.WGSL?"uniforms.":"")+this._textureInfoName),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${r};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===ll.Vertex||this._fragmentOnly||e.target===ll.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),!this._isMixed&&e.target===ll.Fragment||this._isMixed&&e.target===ll.Vertex){if(!this._imageSource){const t=e._getFreeVariableName(this.name);this._samplerName=t+"Texture",this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)}e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)}if(e.target!==ll.Fragment)return void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;this._isMixed&&!this._imageSource&&(this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._isMixed&&e._emitUniformFromString(this._textureInfoName,al.Float),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i,s){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!hh.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(0===e.texture.url.indexOf("data:")?i="":s&&(e.texture.url=s(e.texture.url),e.texture.name=e.texture.url),this.texture=Pa.Parse(e.texture,t,i))}}z("BABYLON.TextureBlock",$b);class qb extends Tl{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??re.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?ll.Fragment:ll.VertexAndFragment)}constructor(e){super(e,ll.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Ol("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.World&&t(e)));i||(i=new Ol("world"),i.setAsSystemValue(_l.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.View&&t(e)));i||(i=new Ol("view"),i.setAsSystemValue(_l.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this._getTexture();s&&s.getTextureMatrix&&(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLocalCubicName,!!s.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===s.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===s.coordinatesMode,!0),i.setValue(this._defineCubicName,3===s.coordinatesMode||6===s.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===s.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===s.coordinatesMode,!0),i.setValue(this._definePlanarName,2===s.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===s.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===s.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===s.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===s.coordinatesMode,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i,s){const r=this._getTexture();if(i&&r&&(e.setMatrix(this._reflectionMatrixName,r.getReflectionTextureMatrix()),r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),r.boundingBoxSize)){const t=r;e.setVector3(this._reflectionPositionName,t.boundingBoxPosition),e.setVector3(this._reflectionSizeName,t.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===ll.Vertex)return"";this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,al.Matrix);let t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");const i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,al.Vector4))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName};\n`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,al.Vector3,this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName}\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\n`,t+="#endif\n"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,al.Vector3,`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0)));\n`,t+="#endif\n"),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\n`,e._samplerDeclaration+="#else\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\n`,e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,al.Vector3),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,al.Vector3)}handleFragmentSideCodeReflectionCoords(e,t,i=!1,s=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const r=this._reflectionMatrixName,n=`normalize(${this._directionWName})`,o=`${this._positionUVWName}`,a=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=`\n #ifdef ${this._defineMirroredEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${n});\n #endif\n\n #ifdef ${this._defineEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${n});\n #endif\n\n #ifdef ${this._defineEquirectangularName}\n vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n\n #ifdef ${this._defineSphericalName}\n vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${r});\n #endif\n\n #ifdef ${this._definePlanarName}\n vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n\n #ifdef ${this._defineCubicName}\n #ifdef ${this._defineLocalCubicName}\n vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${a}.xyz, ${r}, ${this._reflectionSizeName}, ${this._reflectionPositionName});\n #else\n vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n #endif\n\n #ifdef ${this._defineProjectionName}\n vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${r});\n #endif\n\n #ifdef ${this._defineSkyboxName}\n vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${o}, ${r});\n #endif\n\n #ifdef ${this._defineExplicitName}\n vec3 ${this._reflectionVectorName} = vec3(0, 0, 0);\n #endif\n`;return s||(h+=`#ifdef ${this._defineOppositeZ}\n ${this._reflectionVectorName}.z *= -1.0;\n #endif\n`),i||(h+=`\n #ifdef ${this._define3DName}\n vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName};\n #else\n vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy;\n #ifdef ${this._defineProjectionName}\n ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;\n #endif\n ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;\n #endif\n`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i=`${"vec"+(0===t.length?"4":t.length-1)} ${this._reflectionColorName};\n #ifdef ${this._define3DName}\n`;return i+=e?`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t};\n`:`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t};\n`,i+="\n #else\n",i+=e?`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t};\n`:`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t};\n`,i+="#endif\n",i}writeOutputs(e,t){let i="";if(e.target===ll.Fragment)for(const s of this._outputs)s.hasEndpoints&&(i+=`${e._declareOutput(s)} = ${t}.${s.name};\n`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){const t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"});\n`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);\n`;return e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!hh.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=vg.Parse(e.texture,t,i):this.texture=Pa.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}Ze([Cl("Generate only fragment code",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:qb._OnGenerateOnlyFragmentCodeChanged}})],qb.prototype,"generateOnlyFragmentCode",void 0),z("BABYLON.ReflectionTextureBaseBlock",qb);class Zb extends qb{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,Ne.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,Ne.Error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?ll.Fragment:ll.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?ll.Fragment:ll.Vertex}constructor(e){super(e),this.registerInput("position",al.AutoDetect,!1,ll.Vertex),this.registerInput("worldPosition",al.Vector4,!1,ll.Vertex),this.registerInput("worldNormal",al.Vector4,!1,ll.Fragment),this.registerInput("world",al.Matrix,!1,ll.Vertex),this.registerInput("cameraPosition",al.Vector3,!1,ll.Fragment),this.registerInput("view",al.Matrix,!1,ll.Fragment),this.registerOutput("rgb",al.Color3,ll.Fragment),this.registerOutput("rgba",al.Color4,ll.Fragment),this.registerOutput("r",al.Float,ll.Fragment),this.registerOutput("g",al.Float,ll.Fragment),this.registerOutput("b",al.Float,ll.Fragment),this.registerOutput("a",al.Float,ll.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e,t=(()=>!0)){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.CameraPosition&&t(e)));i||(i=new Ol("cameraPosition"),i.setAsSystemValue(_l.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==ll.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);const t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName});\n`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}}z("BABYLON.ReflectionTextureBlock",Zb);class Jb extends Tl{constructor(e){super(e,ll.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",al.AutoDetect,!1,ll.VertexAndFragment),this.registerOutput("depth",al.Float,ll.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Vector2|al.Vector3|al.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"SceneDepthBlock"}get uv(){return this._inputs[0]}get depth(){return this._outputs[0]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?ll.VertexAndFragment:ll.Fragment:ll.VertexAndFragment}_getTexture(e){return e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ).getDepthMap()}bind(e,t){const i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,t.type===al.Vector3?al.Vector3:t.type===al.Vector4?al.Vector4:al.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,al.Vector2),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===ll.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\n`}else this.uv.ownerBlock.target!==ll.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\n`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===ll.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target,ll.Fragment,e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.bindableBlocks.indexOf(this)<0&&e.sharedData.bindableBlocks.push(this),e.target!==ll.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(this._outputs.some((e=>e.isConnectedInFragmentShader))){e._emit2DSampler(this._samplerName),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){const e=super.serialize();return e.useNonLinearDepth=this.useNonLinearDepth,e.storeCameraSpaceZ=this.storeCameraSpaceZ,e.force32itsFloat=this.force32itsFloat,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useNonLinearDepth=e.useNonLinearDepth,this.storeCameraSpaceZ=!!e.storeCameraSpaceZ,this.force32itsFloat=e.force32itsFloat}}Ze([Cl("Use non linear depth",ul.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let s=!1;return i.useNonLinearDepth&&(i.storeCameraSpaceZ=!1,s=!0),e&&e.disableDepthRenderer(),s}}})],Jb.prototype,"useNonLinearDepth",void 0),Ze([Cl("Store Camera space Z",ul.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let s=!1;return i.storeCameraSpaceZ&&(i.useNonLinearDepth=!1,s=!0),e&&e.disableDepthRenderer(),s}}})],Jb.prototype,"storeCameraSpaceZ",void 0),Ze([Cl("Force 32 bits float",ul.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>e?.disableDepthRenderer()}})],Jb.prototype,"force32itsFloat",void 0),z("BABYLON.SceneDepthBlock",Jb);class eT extends Tl{constructor(e){super(e,ll.VertexAndFragment,!0),this.registerInput("worldPosition",al.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6")}get worldPosition(){return this._inputs[0]}get target(){return ll.VertexAndFragment}set target(e){}prepareDefines(e,t,i){const s=e.getScene(),r=!!(t.clipPlane??s.clipPlane),n=!!(t.clipPlane2??s.clipPlane2),o=!!(t.clipPlane3??s.clipPlane3),a=!!(t.clipPlane4??s.clipPlane4),l=!!(t.clipPlane5??s.clipPlane5),h=!!(t.clipPlane6??s.clipPlane6);i.setValue("CLIPPLANE",r,!0),i.setValue("CLIPPLANE2",n,!0),i.setValue("CLIPPLANE3",o,!0),i.setValue("CLIPPLANE4",a,!0),i.setValue("CLIPPLANE5",l,!0),i.setValue("CLIPPLANE6",h,!0)}bind(e,t,i){i&&xo(e,t,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==ll.Fragment){const i=this.worldPosition;return e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane",al.Vector4),e._emitUniformFromString("vClipPlane2",al.Vector4),e._emitUniformFromString("vClipPlane3",al.Vector4),e._emitUniformFromString("vClipPlane4",al.Vector4),e._emitUniformFromString("vClipPlane5",al.Vector4),void e._emitUniformFromString("vClipPlane6",al.Vector4)}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}z("BABYLON.ClipPlanesBlock",eT);class tT extends Tl{get texture(){return null}set texture(e){}constructor(e,t=ll.VertexAndFragment){super(e,t,!1),this.registerOutput("position",al.Object,ll.VertexAndFragment,new Ib("position",this,cl.Output,Kb,"ImageSourceBlock")),this.registerOutput("depth",al.Object,ll.VertexAndFragment,new Ib("depth",this,cl.Output,Kb,"ImageSourceBlock")),this.registerOutput("normal",al.Object,ll.VertexAndFragment,new Ib("normal",this,cl.Output,Kb,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==ll.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){const i=t.getScene().enablePrePassRenderer();if(!i)return;const s=i.defaultRT;s.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,s.textures[i.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,s.textures[i.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,s.textures[i.getIndex(6)]))}}z("BABYLON.PrePassTextureBlock",tT);class iT extends Tl{get endpoints(){return this._endpoints}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==ll.VertexAndFragment)return t.target;if(e.connectedPoint.target!==ll.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}constructor(e){super(e,ll.Neutral),this._endpoints=[],this.registerInput("input",al.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some((e=>e.output.isConnectedInFragmentShader))}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)-1===t.indexOf(s)&&(i+=s._dumpCode(e,t));return i}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(t.isAnAncestorOf(e))return!0}return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){super.dispose();for(const e of this._endpoints)this.detachFromEndpoint(e);this._endpoints=[]}}z("BABYLON.NodeMaterialTeleportInBlock",iT);class sT extends Tl{constructor(e){super(e,ll.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",al.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){this._target&e||(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=e._declareOutput(this.output)+` = ${this.entryPoint.input.associatedVariableName};\n`)}clone(e,t=""){const i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}z("BABYLON.NodeMaterialTeleportOutBlock",sT);class rT extends zl{constructor(e){super(e)}getClassName(){return"AddBlock"}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName};\n`,this}}z("BABYLON.AddBlock",rT);class nT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("input",al.AutoDetect),this.registerInput("factor",al.Float),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ScaleBlock"}get input(){return this._inputs[0]}get factor(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName};\n`,this}}z("BABYLON.ScaleBlock",nT);class oT extends Tl{constructor(e){super(e,ll.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e.shaderLanguage===di.WGSL?e._getShaderType(this.value.type):"";return e.compilationString+=e._declareOutput(t)+` = clamp(${this.value.associatedVariableName}, ${i}(${this._writeFloat(this.minimum)}), ${i}(${this._writeFloat(this.maximum)}));\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.minimum=e.minimum,this.maximum=e.maximum}}Ze([Cl("Minimum",ul.Float)],oT.prototype,"minimum",void 0),Ze([Cl("Maximum",ul.Float)],oT.prototype,"maximum",void 0),z("BABYLON.ClampBlock",oT);class aT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("left",al.AutoDetect),this.registerInput("right",al.AutoDetect),this.registerOutput("output",al.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(al.Float),this._inputs[0].excludedConnectionPointTypes.push(al.Matrix),this._inputs[0].excludedConnectionPointTypes.push(al.Vector2),this._inputs[1].excludedConnectionPointTypes.push(al.Float),this._inputs[1].excludedConnectionPointTypes.push(al.Matrix),this._inputs[1].excludedConnectionPointTypes.push(al.Vector2)}getClassName(){return"CrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz);\n`,this}}z("BABYLON.CrossBlock",aT);class lT extends Tl{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach((s=>{const r=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),n=e._getGLType(s.type);t=t.replace(r,n),i=i.replace(r,n)})),this._outputs.forEach((s=>{const r=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),n=e._getGLType(s.type);t=t.replace(r,n),i=i.replace(r,n)})),e._emitFunction(i,t,""),this._outputs.forEach((t=>{e.compilationString+=e._declareOutput(t)+";\n"})),e.compilationString+=i+"(";let s=!1;return this._inputs.forEach(((t,i)=>{i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=t.connectedPoint?.ownerBlock?.samplerName??t.associatedVariableName:e.compilationString+=t.associatedVariableName,s=!0})),this._outputs.forEach(((t,i)=>{(i>0||s)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName})),e.compilationString+=");\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.options = ${JSON.stringify(this._options)};\n`,e}serialize(){const e=super.serialize();return e.options=this._options,e}_deserialize(e,t,i){this._deserializeOptions(e.options),super._deserialize(e,t,i)}_deserializeOptions(e){this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=ll[e.target],e.inParameters?.forEach(((e,t)=>{const i=al[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,al.Object,!0,ll.VertexAndFragment,new Ib(e.name,this,cl.Input,Kb,"ImageSourceBlock"))):this.registerInput(e.name,i),Object.defineProperty(this,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})})),e.outParameters?.forEach(((e,t)=>{this.registerOutput(e.name,al[e.type]),Object.defineProperty(this,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(this._outputs[t]._typeConnectionSource=this._findInputByName(e.typeFromInput)[0])})),e.inLinkedConnectionTypes?.forEach((e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])}))}_findInputByName(e){if(!e)return null;for(let t=0;t!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.CameraPosition&&t(e)));i||(i=new Ol("cameraPosition"),i.setAsSystemValue(_l.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz);\n`,this}}z("BABYLON.ViewDirectionBlock",vT);class xT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("worldNormal",al.Vector4),this.registerInput("viewDirection",al.Vector3),this.registerInput("bias",al.Float),this.registerInput("power",al.Float),this.registerOutput("fresnel",al.Float)}getClassName(){return"FresnelBlock"}get worldNormal(){return this._inputs[0]}get viewDirection(){return this._inputs[1]}get bias(){return this._inputs[2]}get power(){return this._inputs[3]}get fresnel(){return this._outputs[0]}autoConfigure(e){if(!this.viewDirection.isConnected){const t=new vT("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const e=new Ol("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){const e=new Ol("power");e.value=1,e.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitFunctionFromInclude("fresnelFunction",t,{removeIfDef:!0}),e.compilationString+=e._declareOutput(this.fresnel)+` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName});\n`,this}}z("BABYLON.FresnelBlock",xT);class bT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("left",al.AutoDetect),this.registerInput("right",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MaxBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`,this}}z("BABYLON.MaxBlock",bT);class TT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("left",al.AutoDetect),this.registerInput("right",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MinBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`,this}}z("BABYLON.MinBlock",TT);class yT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("left",al.AutoDetect),this.registerInput("right",al.AutoDetect),this.registerOutput("output",al.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(al.Float),this._inputs[0].excludedConnectionPointTypes.push(al.Matrix),this._inputs[1].excludedConnectionPointTypes.push(al.Float),this._inputs[1].excludedConnectionPointTypes.push(al.Matrix)}getClassName(){return"DistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName});\n`,this}}z("BABYLON.DistanceBlock",yT);class ST extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("value",al.AutoDetect),this.registerOutput("output",al.Float),this._inputs[0].excludedConnectionPointTypes.push(al.Float),this._inputs[0].excludedConnectionPointTypes.push(al.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = length(${this.value.associatedVariableName});\n`,this}}z("BABYLON.LengthBlock",ST);class CT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("value",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NegateBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = -1.0 * ${this.value.associatedVariableName};\n`,this}}z("BABYLON.NegateBlock",CT);class ET extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("value",al.AutoDetect),this.registerInput("power",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"PowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName});\n`,this}}z("BABYLON.PowBlock",ET);class AT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("seed",al.AutoDetect),this.registerOutput("output",al.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Vector2|al.Vector3|al.Vector4|al.Color3|al.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=e._declareOutput(t)+` = getRand(${this.seed.associatedVariableName}.xy);\n`,this}}z("BABYLON.RandomNumberBlock",AT);class PT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("x",al.Float),this.registerInput("y",al.Float),this.registerOutput("output",al.Float)}getClassName(){return"ArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e.shaderLanguage===di.WGSL?"atan2":"atan";return e.compilationString+=e._declareOutput(t)+` = ${i}(${this.x.associatedVariableName}, ${this.y.associatedVariableName});\n`,this}}z("BABYLON.ArcTan2Block",PT);class IT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("value",al.AutoDetect),this.registerInput("edge0",al.Float),this.registerInput("edge1",al.Float),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"SmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e._getShaderType(this.value.type);return e.compilationString+=e._declareOutput(t)+` = smoothstep(${i}(${this.edge0.associatedVariableName}), ${i}(${this.edge1.associatedVariableName}), ${this.value.associatedVariableName});\n`,this}}z("BABYLON.SmoothStepBlock",IT);class RT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("input",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ReciprocalBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return this.input.type===al.Matrix?e.compilationString+=e._declareOutput(t)+` = inverse(${this.input.associatedVariableName});\n`:e.compilationString+=e._declareOutput(t)+` = 1. / ${this.input.associatedVariableName};\n`,this}}z("BABYLON.ReciprocalBlock",RT);class MT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("value",al.AutoDetect),this.registerInput("reference",al.AutoDetect),this.registerInput("distance",al.Float),this.registerInput("replacement",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(al.Float),this._inputs[0].excludedConnectionPointTypes.push(al.Matrix),this._inputs[1].excludedConnectionPointTypes.push(al.Float),this._inputs[1].excludedConnectionPointTypes.push(al.Matrix),this._inputs[3].excludedConnectionPointTypes.push(al.Float),this._inputs[3].excludedConnectionPointTypes.push(al.Matrix)}getClassName(){return"ReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+";\n",e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {\n`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName};\n`,e.compilationString+="} else {\n",e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName};\n`,e.compilationString+="}\n",this}}z("BABYLON.ReplaceColorBlock",MT);class OT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("value",al.AutoDetect),this.registerInput("steps",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(al.Matrix),this._inputs[1].excludedConnectionPointTypes.push(al.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(al.Float)}getClassName(){return"PosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName});\n`,this}}var DT;z("BABYLON.PosterizeBlock",OT),function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(DT||(DT={}));class wT extends Tl{constructor(e){super(e,ll.Neutral),this.kind=DT.SawTooth,this.registerInput("input",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(al.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];switch(this.kind){case DT.SawTooth:e.compilationString+=e._declareOutput(t)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\n`;break;case DT.Square:e.compilationString+=e._declareOutput(t)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\n`;break;case DT.Triangle:e.compilationString+=e._declareOutput(t)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\n`}return this}serialize(){const e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}}z("BABYLON.WaveBlock",wT);class NT{get step(){return this._step}set step(e){this._step=e}get color(){return this._color}set color(e){this._color=e}constructor(e,t){this.step=e,this.color=t}}class FT extends Tl{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,ll.Neutral),this.colorSteps=[new NT(0,Ee.Black()),new NT(1,Ee.White())],this.onValueChangedObservable=new K,this.registerInput("gradient",al.AutoDetect),this.registerOutput("output",al.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Float|al.Vector2|al.Vector3|al.Vector4|al.Color3|al.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e,t){const i=this.colorSteps[e];return`${t}(${i.color.r}, ${i.color.g}, ${i.color.b})`}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e._getShaderType(al.Vector3);if(!this.colorSteps.length||!this.gradient.connectedPoint)return void(e.compilationString+=e._declareOutput(t)+` = ${i}(0., 0., 0.);\n`);const s=e._getFreeVariableName("gradientTempColor"),r=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`${e._declareLocalVar(s,al.Vector3)} = ${this._writeColorConstant(0,i)};\n`,e.compilationString+=`${e._declareLocalVar(r,al.Float)};\n`;let n=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==al.Float&&(n+=".x");for(let t=1;t!0)){if(!this.intensity.isConnected){const e=new Ol("Refraction intensity",ll.Fragment,al.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.View&&t(e)));i||(i=new Ol("view"),i.setAsSystemValue(_l.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this._getTexture(),r=s&&s.getTextureMatrix;i.setValue("SS_REFRACTION",r,!0),r&&(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLODRefractionAlpha,s.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,s.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&s.isCube?!s.invertZ:s.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",s.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",s.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!s.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){super.bind(e,t,i);const s=this._getTexture();if(!s)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s),e.setMatrix(this._refractionMatrixName,s.getRefractionTextureMatrix());let r=1;s.isCube||s.depth&&(r=s.depth);const n=this.volumeIndexOfRefraction.connectInputBlock?.value??this.indexOfRefractionConnectionPoint.connectInputBlock?.value??1.5;e.setFloat4(this._vRefractionInfosName,s.level,1/n,r,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,s.getSize().width,s.lodGenerationScale,s.lodGenerationOffset,1/n);const o=s.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,o,be.Log2(o)),s.boundingBoxSize){const t=s;e.setVector3("vRefractionPosition",t.boundingBoxPosition),e.setVector3("vRefractionSize",t.boundingBoxSize)}}getCode(e){return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\n`,e._samplerDeclaration+="#else\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\n`,e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,al.Matrix),e._emitFunction("sampleRefraction",`\n #ifdef ${this._define3DName}\n #define sampleRefraction(s, c) textureCube(s, c)\n #else\n #define sampleRefraction(s, c) texture2D(s, c)\n #endif\n`,`//${this.name}`),e._emitFunction("sampleRefractionLod",`\n #ifdef ${this._define3DName}\n #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\n`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,al.Vector4),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,al.Vector4),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,al.Vector2),e._emitUniformFromString("vRefractionPosition",al.Vector3),e._emitUniformFromString("vRefractionSize",al.Vector3),""}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e=this.texture.isCube?`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\n`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\n`,e+=`${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\n`,e+=`${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=vg.Parse(e.texture,t,i):this.texture=Pa.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}Ze([Cl("Link refraction to transparency",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],KT.prototype,"linkRefractionWithTransparency",void 0),Ze([Cl("Invert refraction Y",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],KT.prototype,"invertRefractionY",void 0),Ze([Cl("Use thickness as depth",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],KT.prototype,"useThicknessAsDepth",void 0),z("BABYLON.RefractionBlock",KT);class $T extends Tl{constructor(e){super(e,ll.Fragment),this._isUnique=!0,this.registerInput("thickness",al.Float,!1,ll.Fragment),this.registerInput("tintColor",al.Color3,!0,ll.Fragment),this.registerInput("translucencyIntensity",al.Float,!0,ll.Fragment),this.registerInput("translucencyDiffusionDist",al.Color3,!0,ll.Fragment),this.registerInput("refraction",al.Object,!0,ll.Fragment,new Ib("refraction",this,cl.Input,KT,"RefractionBlock")),this.registerInput("dispersion",al.Float,!0,ll.Fragment),this.registerOutput("subsurface",al.Object,ll.Fragment,new Ib("subsurface",this,cl.Output,$T,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vTranslucencyColor"),e._excludeVariableName("vSubSurfaceIntensity"),e._excludeVariableName("dispersion")}getClassName(){return"SubSurfaceBlock"}get thickness(){return this._inputs[0]}get tintColor(){return this._inputs[1]}get translucencyIntensity(){return this._inputs[2]}get translucencyDiffusionDist(){return this._inputs[3]}get refraction(){return this._inputs[4]}get dispersion(){return this._inputs[5]}get subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){const e=new Ol("SubSurface thickness",ll.Fragment,al.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",s||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",s,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0),i.setValue("SS_DISPERSION",this.dispersion.isConnected,!0)}static GetCode(e,t,i,s){let r="";const n=t?.thickness.isConnected?t.thickness.associatedVariableName:"0.",o=t?.tintColor.isConnected?t.tintColor.associatedVariableName:"vec3(1.)",a=t?.translucencyIntensity.isConnected?t?.translucencyIntensity.associatedVariableName:"1.",l=t?.translucencyDiffusionDist.isConnected?t?.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",h=t?.refraction.isConnected?t?.refraction.connectedPoint?.ownerBlock:null,c=h?.tintAtDistance.isConnected?h.tintAtDistance.associatedVariableName:"1.",u=h?.intensity.isConnected?h.intensity.associatedVariableName:"1.",d=h?.view.isConnected?h.view.associatedVariableName:"",_=t?.dispersion.isConnected?t?.dispersion.associatedVariableName:"0.0";return r+=h?.getCode(e)??"",r+=`subSurfaceOutParams subSurfaceOut;\n\n #ifdef SUBSURFACE\n vec2 vThicknessParam = vec2(0., ${n});\n vec4 vTintColor = vec4(${o}, ${c});\n vec3 vSubSurfaceIntensity = vec3(${u}, ${a}, 0.);\n float dispersion = ${_};\n subSurfaceBlock(\n vSubSurfaceIntensity,\n vThicknessParam,\n vTintColor,\n normalW,\n specularEnvironmentReflectance,\n #ifdef SS_THICKNESSANDMASK_TEXTURE\n vec4(0.),\n #endif\n #ifdef REFLECTION\n #ifdef SS_TRANSLUCENCY\n ${i?._reflectionMatrixName},\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n reflectionOut.irradianceVector,\n #endif\n #if defined(REALTIME_FILTERING)\n ${i?._cubeSamplerName},\n ${i?._vReflectionFilteringInfoName},\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n irradianceSampler,\n #endif\n #endif\n #endif\n #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n surfaceAlbedo,\n #endif\n #ifdef SS_REFRACTION\n ${s}.xyz,\n viewDirectionW,\n ${d},\n ${h?._vRefractionInfosName??""},\n ${h?._refractionMatrixName??""},\n ${h?._vRefractionMicrosurfaceInfosName??""},\n vLightingIntensity,\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha,\n #endif\n #ifdef ${h?._defineLODRefractionAlpha??"IGNORE"}\n NdotVUnclamped,\n #endif\n #ifdef ${h?._defineLinearSpecularRefraction??"IGNORE"}\n roughness,\n #endif\n alphaG,\n #ifdef ${h?._define3DName??"IGNORE"}\n ${h?._cubeSamplerName??""},\n #else\n ${h?._2DSamplerName??""},\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${h?._define3DName??"IGNORE"}\n ${h?._cubeSamplerName??""},\n ${h?._cubeSamplerName??""},\n #else\n ${h?._2DSamplerName??""},\n ${h?._2DSamplerName??""},\n #endif\n #endif\n #ifdef ANISOTROPIC\n anisotropicOut,\n #endif\n #ifdef REALTIME_FILTERING\n ${h?._vRefractionFilteringInfoName??""},\n #endif\n #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n vRefractionPosition,\n vRefractionSize,\n #endif\n #ifdef SS_DISPERSION\n dispersion,\n #endif\n #endif\n #ifdef SS_TRANSLUCENCY\n ${l},\n vTintColor,\n #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\n vec4(0.),\n #endif\n #endif\n subSurfaceOut\n );\n\n #ifdef SS_REFRACTION\n surfaceAlbedo = subSurfaceOut.surfaceAlbedo;\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha = subSurfaceOut.alpha;\n #endif\n #endif\n #else\n subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;\n #endif\n`,r}_buildBlock(e){return e.target===ll.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}z("BABYLON.SubSurfaceBlock",$T);const qT={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]};class ZT extends Tl{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,Ne.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?ll.Fragment:ll.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?ll.Fragment:ll.Vertex}constructor(e){super(e,ll.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=Ee.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",al.Vector4,!1,ll.Vertex),this.registerInput("worldNormal",al.Vector4,!1,ll.Fragment),this.registerInput("view",al.Matrix,!1),this.registerInput("cameraPosition",al.Vector3,!1,ll.Fragment),this.registerInput("perturbedNormal",al.Vector4,!0,ll.Fragment),this.registerInput("baseColor",al.Color3,!0,ll.Fragment),this.registerInput("metallic",al.Float,!1,ll.Fragment),this.registerInput("roughness",al.Float,!1,ll.Fragment),this.registerInput("ambientOcc",al.Float,!0,ll.Fragment),this.registerInput("opacity",al.Float,!0,ll.Fragment),this.registerInput("indexOfRefraction",al.Float,!0,ll.Fragment),this.registerInput("ambientColor",al.Color3,!0,ll.Fragment),this.registerInput("reflection",al.Object,!0,ll.Fragment,new Ib("reflection",this,cl.Input,YT,"ReflectionBlock")),this.registerInput("clearcoat",al.Object,!0,ll.Fragment,new Ib("clearcoat",this,cl.Input,QT,"ClearCoatBlock")),this.registerInput("sheen",al.Object,!0,ll.Fragment,new Ib("sheen",this,cl.Input,HT,"SheenBlock")),this.registerInput("subsurface",al.Object,!0,ll.Fragment,new Ib("subsurface",this,cl.Input,$T,"SubSurfaceBlock")),this.registerInput("anisotropy",al.Object,!0,ll.Fragment,new Ib("anisotropy",this,cl.Input,XT,"AnisotropyBlock")),this.registerInput("iridescence",al.Object,!0,ll.Fragment,new Ib("iridescence",this,cl.Input,jT,"IridescenceBlock")),this.registerOutput("ambientClr",al.Color3,ll.Fragment),this.registerOutput("diffuseDir",al.Color3,ll.Fragment),this.registerOutput("specularDir",al.Color3,ll.Fragment),this.registerOutput("clearcoatDir",al.Color3,ll.Fragment),this.registerOutput("sheenDir",al.Color3,ll.Fragment),this.registerOutput("diffuseInd",al.Color3,ll.Fragment),this.registerOutput("specularInd",al.Color3,ll.Fragment),this.registerOutput("clearcoatInd",al.Color3,ll.Fragment),this.registerOutput("sheenInd",al.Color3,ll.Fragment),this.registerOutput("refraction",al.Color3,ll.Fragment),this.registerOutput("lighting",al.Color3,ll.Fragment),this.registerOutput("shadow",al.Float,ll.Fragment),this.registerOutput("alpha",al.Float,ll.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.CameraPosition&&t(e)));i||(i=new Ol("cameraPosition"),i.setAsSystemValue(_l.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.View&&t(e)));i||(i=new Ol("view"),i.setAsSystemValue(_l.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===Gg.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===Gg.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const s=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",s.indexOf(".")<0?s+".":s,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);const r=e.getScene();if(r.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&$c.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),i._areLightsDirty)if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};Wo(r,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else zo(r,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,Ko(r,i)}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;Jo(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,t)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?Fo(this.light,this._lightId,s,e,!0):Lo(s,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const r=this._scene.ambientColor;r&&e.setColor3("ambientFromScene",r);const n=s.useRightHandedSystem===(null!=s._mirroredCameraPosition);e.setFloat(this._invertNormalName,n?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const o=this.indexOfRefraction.connectInputBlock?.value??1.5,a=Math.pow((o-1)/(o+1),2);this._metallicReflectanceColor.scaleToRef(a*this._metallicF0Factor,Pe.Color3[0]);const l=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,Pe.Color3[0],l),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,al.Vector4)&&(e.compilationString+=`${s} = ${t.associatedVariableName};\n`);const r=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;r&&(r.viewConnectionPoint=this.view),e.compilationString+=r?.handleVertexSide(e)??"",e._emitVaryingFromString("vClipSpacePosition",al.Vector4,"defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+="#if DEBUGMODE > 0\n",e._injectAtEnd+="vClipSpacePosition = gl_Position;\n",e._injectAtEnd+="#endif\n"),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e="albedoOpacityOutParams albedoOpacityOut;\n";return e+=`albedoOpacityBlock(\n vec4(${this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)"}, 1.),\n #ifdef ALBEDO\n vec4(1.),\n vec2(1., 1.),\n #endif\n #ifdef OPACITY\n vec4(${this.opacity.isConnected?this.opacity.associatedVariableName:"1."}),\n vec2(1., 1.),\n #endif\n albedoOpacityOut\n );\n\n vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;\n float alpha = albedoOpacityOut.alpha;\n`,e}_getAmbientOcclusionCode(){let e="ambientOcclusionOutParams aoOut;\n";return e+=`ambientOcclusionBlock(\n #ifdef AMBIENT\n vec3(${this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1."}),\n vec4(0., 1.0, 1.0, 0.),\n #endif\n aoOut\n );\n`,e}_getReflectivityCode(e){let t="reflectivityOutParams reflectivityOut;\n";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,al.Vector4),t+=`vec3 baseColor = surfaceAlbedo;\n\n reflectivityBlock(\n vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.),\n #ifdef METALLICWORKFLOW\n surfaceAlbedo,\n ${this._vMetallicReflectanceFactorsName},\n #endif\n #ifdef REFLECTIVITY\n vec3(0., 0., 1.),\n vec4(1.),\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor,\n #endif\n #ifdef MICROSURFACEMAP\n microSurfaceTexel, <== not handled!\n #endif\n reflectivityOut\n );\n\n float microSurface = reflectivityOut.microSurface;\n float roughness = reflectivityOut.roughness;\n\n #ifdef METALLICWORKFLOW\n surfaceAlbedo = reflectivityOut.surfaceAlbedo;\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;\n #endif\n`,t}_buildBlock(e){super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=Eg(this._scene));const t=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;if(t&&(t.worldPositionConnectionPoint=this.worldPosition,t.cameraPositionConnectionPoint=this.cameraPosition,t.worldNormalConnectionPoint=this.worldNormal,t.viewConnectionPoint=this.view),e.target!==ll.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const i=`//${this.name}`,s=this.perturbedNormal;let r=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${r};\n`,i),e.compilationString+=`${r} = ${this.worldPosition.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+="#if DEBUGMODE > 0\n",e.compilationString+="vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0);\n",e.compilationString+="#endif\n"):r="v_"+r,this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode",al.Vector2,"defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene",al.Vector3),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",i),e._emitFunctionFromInclude("importanceSampling",i),e._emitFunctionFromInclude("pbrHelperFunctions",i),e._emitFunctionFromInclude("imageProcessingDeclaration",i),e._emitFunctionFromInclude("imageProcessingFunctions",i),e._emitFunctionFromInclude("shadowsFragmentFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",i),e._emitFunctionFromInclude("pbrBRDFFunctions",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",i),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",i),e._emitFunctionFromInclude("pbrBlockReflectivity",i),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",i),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",i),e._emitFunctionFromInclude("pbrBlockAnisotropic",i),e._emitUniformFromString("vLightingIntensity",al.Vector4),t?.generateOnlyFragmentCode&&(e.compilationString+=t.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName});\n`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${r}.xyz);\n`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz;\n`,e.compilationString+=`vec3 normalW = ${s.isConnected?"normalize("+s.associatedVariableName+".xyz)":"geometricNormalW"};\n`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,al.Float),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",i),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",i),e.compilationString+="#ifdef UNLIT\n vec3 diffuseBase = vec3(1., 1., 1.);\n #else\n",e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"}]});const n=this.anisotropy.isConnected?this.anisotropy.connectedPoint?.ownerBlock:null;n&&(n.worldPositionConnectionPoint=this.worldPosition,n.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=n.getCode(e,!this.perturbedNormal.isConnected)),t&&t.hasTexture&&(e.compilationString+=t.getCode(e,n?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:t?._vReflectionFilteringInfoName??"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",i,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});const o=this.sheen.isConnected?this.sheen.connectedPoint?.ownerBlock:null;o&&(e.compilationString+=o.getCode(t)),e._emitFunctionFromInclude("pbrBlockSheen",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"}]});const a=this.iridescence.isConnected?this.iridescence.connectedPoint?.ownerBlock:null;e.compilationString+=jT.GetCode(a),e._emitFunctionFromInclude("pbrBlockIridescence",i,{replaceStrings:[]});const l=this.clearcoat.isConnected?this.clearcoat.connectedPoint?.ownerBlock:null,h=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,c=this.perturbedNormal.isConnected&&(this.perturbedNormal.connectedPoint?.ownerBlock).worldTangent?.isConnected,u=this.anisotropy.isConnected&&(this.anisotropy.connectedPoint?.ownerBlock).worldTangent.isConnected;let d=c||!this.perturbedNormal.isConnected&&u;e.compilationString+=QT.GetCode(e,l,t,r,h,d,this.worldNormal.associatedVariableName),h&&(d=l?.worldTangent.isConnected??!1),e._emitFunctionFromInclude("pbrBlockClearcoat",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:d?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"}]});const _=this.subsurface.isConnected?this.subsurface.connectedPoint?.ownerBlock:null,p=this.subsurface.isConnected?(this.subsurface.connectedPoint?.ownerBlock).refraction.connectedPoint?.ownerBlock:null;p&&(p.viewConnectionPoint=this.view,p.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=$T.GetCode(e,_,t,r),e._emitFunctionFromInclude("pbrBlockSubSurface",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:p?._define3DName??"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:p?._defineLODRefractionAlpha??"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:p?._defineLinearSpecularRefraction??"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:p?._defineOppositeZ??"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",i),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:r+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${r}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",i),e.compilationString+="#endif\n";const f=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)";let m=Gg.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();-1===m.indexOf(".")&&(m+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",i,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:f+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:m}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",i,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",i,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",i,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:r},{search:/albedoTexture\.rgb;/g,replace:"vec3(1.);\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\n"}]});for(const t of this._outputs)if(t.hasEndpoints){const i=qT[t.name];if(i){const[s,r]=i;r&&(e.compilationString+=`#if ${r}\n`),e.compilationString+=`${e._declareOutput(t)} = ${s};\n`,r&&(e.compilationString+="#else\n",e.compilationString+=`${e._declareOutput(t)} = vec3(0.);\n`,e.compilationString+="#endif\n")}else Ne.Error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.lightFalloff = ${this.lightFalloff};\n`,e+=`${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};\n`,e+=`${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};\n`,e+=`${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};\n`,e+=`${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};\n`,e+=`${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};\n`,e+=`${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};\n`,e+=`${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};\n`,e+=`${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};\n`,e+=`${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};\n`,e+=`${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};\n`,e+=`${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};\n`,e+=`${this._codeVariableName}.unlit = ${this.unlit};\n`,e+=`${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};\n`,e+=`${this._codeVariableName}.debugMode = ${this.debugMode};\n`,e+=`${this._codeVariableName}.debugLimit = ${this.debugLimit};\n`,e+=`${this._codeVariableName}.debugFactor = ${this.debugFactor};\n`,e}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=e.lightFalloff??0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=e.realTimeFilteringQuality??8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor,this.generateOnlyFragmentCode=!!e.generateOnlyFragmentCode,this._setTarget()}}Ze([Cl("Direct lights",ul.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],ZT.prototype,"directIntensity",void 0),Ze([Cl("Environment lights",ul.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],ZT.prototype,"environmentIntensity",void 0),Ze([Cl("Specular highlights",ul.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],ZT.prototype,"specularIntensity",void 0),Ze([Cl("Light falloff",ul.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:Gg.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:Gg.LIGHTFALLOFF_GLTF},{label:"Standard",value:Gg.LIGHTFALLOFF_STANDARD}]})],ZT.prototype,"lightFalloff",void 0),Ze([Cl("Alpha Testing",ul.Boolean,"OPACITY")],ZT.prototype,"useAlphaTest",void 0),Ze([Cl("Alpha CutOff",ul.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],ZT.prototype,"alphaTestCutoff",void 0),Ze([Cl("Alpha blending",ul.Boolean,"OPACITY")],ZT.prototype,"useAlphaBlending",void 0),Ze([Cl("Radiance over alpha",ul.Boolean,"RENDERING",{notifiers:{update:!0}})],ZT.prototype,"useRadianceOverAlpha",void 0),Ze([Cl("Specular over alpha",ul.Boolean,"RENDERING",{notifiers:{update:!0}})],ZT.prototype,"useSpecularOverAlpha",void 0),Ze([Cl("Specular anti-aliasing",ul.Boolean,"RENDERING",{notifiers:{update:!0}})],ZT.prototype,"enableSpecularAntiAliasing",void 0),Ze([Cl("Realtime filtering",ul.Boolean,"RENDERING",{notifiers:{update:!0}})],ZT.prototype,"realTimeFiltering",void 0),Ze([Cl("Realtime filtering quality",ul.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],ZT.prototype,"realTimeFilteringQuality",void 0),Ze([Cl("Energy Conservation",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],ZT.prototype,"useEnergyConservation",void 0),Ze([Cl("Radiance occlusion",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],ZT.prototype,"useRadianceOcclusion",void 0),Ze([Cl("Horizon occlusion",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],ZT.prototype,"useHorizonOcclusion",void 0),Ze([Cl("Unlit",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],ZT.prototype,"unlit",void 0),Ze([Cl("Force normal forward",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],ZT.prototype,"forceNormalForward",void 0),Ze([Cl("Generate only fragment code",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:ZT._OnGenerateOnlyFragmentCodeChanged}})],ZT.prototype,"generateOnlyFragmentCode",void 0),Ze([Cl("Debug mode",ul.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87},{label:"Albedo color",value:88},{label:"Ambient occlusion color",value:89}]})],ZT.prototype,"debugMode",void 0),Ze([Cl("Split position",ul.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],ZT.prototype,"debugLimit",void 0),Ze([Cl("Output factor",ul.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],ZT.prototype,"debugFactor",void 0),z("BABYLON.PBRMetallicRoughnessBlock",ZT);class JT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("left",al.AutoDetect),this.registerInput("right",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[1].acceptedConnectionPointTypes.push(al.Float)}getClassName(){return"ModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.shaderLanguage===di.GLSL?e.compilationString+=e._declareOutput(t)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`:e.compilationString+=e._declareOutput(t)+` = (${this.left.associatedVariableName} % ${this.right.associatedVariableName});\n`,this}}z("BABYLON.ModBlock",JT);class ey extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("row0",al.Vector4),this.registerInput("row1",al.Vector4),this.registerInput("row2",al.Vector4),this.registerInput("row3",al.Vector4),this.registerOutput("output",al.Matrix)}getClassName(){return"MatrixBuilder"}get row0(){return this._inputs[0]}get row1(){return this._inputs[1]}get row2(){return this._inputs[2]}get row3(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(){if(!this.row0.isConnected){const e=new Ol("row0");e.value=new pe(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new Ol("row1");e.value=new pe(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new Ol("row2");e.value=new pe(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new Ol("row3");e.value=new pe(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,s=this.row1,r=this.row2,n=this.row3,o=e.shaderLanguage===di.WGSL?"mat4x4f":"mat4";return e.compilationString+=e._declareOutput(t)+` = ${o}(${i.associatedVariableName}, ${s.associatedVariableName}, ${r.associatedVariableName}, ${n.associatedVariableName});\n`,this}}var ty,iy,sy,ry,ny,oy;z("BABYLON.MatrixBuilder",ey),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(ty||(ty={}));class ay extends Tl{constructor(e){super(e,ll.Neutral),this.condition=ty.LessThan,this.registerInput("a",al.Float),this.registerInput("b",al.Float),this.registerInput("true",al.AutoDetect,!0),this.registerInput("false",al.AutoDetect,!0),this.registerOutput("output",al.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=al.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",s=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case ty.Equal:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} == ${this.b.associatedVariableName}`)};\n`;break;case ty.NotEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} != ${this.b.associatedVariableName}`)};\n`;break;case ty.LessThan:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} < ${this.b.associatedVariableName}`)};\n`;break;case ty.LessOrEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} <= ${this.b.associatedVariableName}`)};\n`;break;case ty.GreaterThan:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} > ${this.b.associatedVariableName}`)};\n`;break;case ty.GreaterOrEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} >= ${this.b.associatedVariableName}`)};\n`;break;case ty.Xor:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`(((${this.a.associatedVariableName} + ${this.b.associatedVariableName}) % 2.0) > 0.0)`)};\n`;break;case ty.Or:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`(min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0)`)};\n`;break;case ty.And:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`(${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0)`)};\n`}return this}serialize(){const e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${ty[this.condition]};\n`}}z("BABYLON.ConditionalBlock",ay);class ly extends Tl{constructor(e){super(e,ll.Neutral),this.octaves=6,this.registerInput("seed",al.AutoDetect),this.registerInput("chaos",al.AutoDetect,!0),this.registerInput("offsetX",al.Float,!0),this.registerInput("offsetY",al.Float,!0),this.registerInput("offsetZ",al.Float,!0),this.registerOutput("output",al.Float),this._inputs[0].acceptedConnectionPointTypes.push(al.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(al.Vector3),this._linkConnectionTypes(0,1)}getClassName(){return"CloudBlock"}get seed(){return this._inputs[0]}get chaos(){return this._inputs[1]}get offsetX(){return this._inputs[2]}get offsetY(){return this._inputs[3]}get offsetZ(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;if(!this._outputs[0].hasEndpoints)return;let t="\n\n float cloudRandom(float p) { \n float temp = fract(p * 0.011); \n temp *= temp + 7.5; \n temp *= temp + temp; \n return fract(temp); \n }\n\n // Based on Morgan McGuire @morgan3d\n // https://www.shadertoy.com/view/4dS3Wd\n float cloudNoise2(vec2 x, vec2 chaos) {\n vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);\n\n vec2 i = floor(x);\n vec2 f = fract(x);\n\n float n = dot(i, step);\n\n vec2 u = f * f * (3.0 - 2.0 * f);\n return mix(\n mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),\n mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),\n u.y\n );\n }\n\n float cloudNoise3(vec3 x, vec3 chaos) {\n vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);\n\n vec3 i = floor(x);\n vec3 f = fract(x);\n\n float n = dot(i, step);\n\n vec3 u = f * f * (3.0 - 2.0 * f);\n return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),\n mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);\n }",i="\n float fbm2(vec2 st, vec2 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = .5;\n float frequency = 0.;\n\n // Loop of octaves\n vec2 tempST = st;\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise2(tempST, chaos);\n tempST *= 2.0;\n amplitude *= 0.5;\n }\n return value;\n }\n\n float fbm3(vec3 x, vec3 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = 0.5;\n vec3 tempX = x;\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise3(tempX, chaos);\n tempX = tempX * 2.0;\n amplitude *= 0.5;\n }\n return value;\n }";e.shaderLanguage===di.WGSL&&(t=e._babylonSLtoWGSL(t),i=e._babylonSLtoWGSL(i));const s=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",t,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,i.replace(/fbm/gi,s).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");const r=e._getFreeVariableName("st"),n=this.seed.connectedPoint?.type||al.Vector3;e.compilationString+=`${e._declareLocalVar(r,n)} = ${this.seed.associatedVariableName};\n`,this.offsetX.isConnected&&(e.compilationString+=`${r}.x += 0.1 * ${this.offsetX.associatedVariableName};\n`),this.offsetY.isConnected&&(e.compilationString+=`${r}.y += 0.1 * ${this.offsetY.associatedVariableName};\n`),this.offsetZ.isConnected&&n===al.Vector3&&(e.compilationString+=`${r}.z += 0.1 * ${this.offsetZ.associatedVariableName};\n`);let o="";if(this.chaos.isConnected)o=this.chaos.associatedVariableName;else{const t=e.fSuffix;o=this.seed.connectedPoint?.type===al.Vector2?`vec2${t}(0., 0.)`:`vec3${t}(0., 0., 0.)`}return e.compilationString+=e._declareOutput(this._outputs[0])+` = ${s}${this.seed.connectedPoint?.type===al.Vector2?"2":"3"}(${r}, ${o});\n`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves};\n`}serialize(){const e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}Ze([Cl("Octaves",ul.Int)],ly.prototype,"octaves",void 0),z("BABYLON.CloudBlock",ly);class hy extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("seed",al.Vector2),this.registerInput("offset",al.Float),this.registerInput("density",al.Float),this.registerOutput("output",al.Float),this.registerOutput("cells",al.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t="vec2 voronoiRandom(vec2 p){\n p = vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3)));\n return fract(sin(p)*18.5453);\n }\n ";e.shaderLanguage===di.WGSL&&(t=e._babylonSLtoWGSL(t)),e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t="void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){\n vec2 n = floor(seed * density);\n vec2 f = fract(seed * density);\n vec3 m = vec3( 8.0 );\n for( int j=-1; j<=1; j++ ){\n for( int i=-1; i<=1; i++ ){\n vec2 g = vec2( float(i), float(j) );\n vec2 o = voronoiRandom( n + g);\n vec2 r = g - f + (0.5+0.5*sin(offset+6.2831*o));\n float d = dot( r, r );\n if( de.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get textureY(){return this.sourceY.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}get textureZ(){return this.sourceZ?.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}_getImageSourceBlock(e){return e?.isConnected?e.connectedPoint.ownerBlock:null}get samplerName(){const e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){return this._getImageSourceBlock(this.sourceY)?.samplerName??null}get samplerZName(){return this._getImageSourceBlock(this.sourceZ)?.samplerName??null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=this.texture.getScene()??re.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??re.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,ll.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",al.AutoDetect,!1),this.registerInput("normal",al.AutoDetect,!1),this.registerInput("sharpness",al.Float,!0),this.registerInput("source",al.Object,!0,ll.VertexAndFragment,new Ib("source",this,cl.Input,Kb,"ImageSourceBlock")),this.registerInput("sourceY",al.Object,!0,ll.VertexAndFragment,new Ib("sourceY",this,cl.Input,Kb,"ImageSourceBlock")),t||this.registerInput("sourceZ",al.Object,!0,ll.VertexAndFragment,new Ib("sourceZ",this,cl.Input,Kb,"ImageSourceBlock")),this.registerOutput("rgba",al.Color4,ll.Neutral),this.registerOutput("rgb",al.Color3,ll.Neutral),this.registerOutput("r",al.Float,ll.Neutral),this.registerOutput("g",al.Float,ll.Neutral),this.registerOutput("b",al.Float,ll.Neutral),this.registerOutput("a",al.Float,ll.Neutral),this.registerOutput("level",al.Float,ll.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_samplerFunc(e){return e.shaderLanguage===di.WGSL?"textureSample":"texture2D"}_generateTextureSample(e,t,i){return i.shaderLanguage===di.WGSL?`${this._samplerFunc(i)}(${e},${e+"Sampler"}, ${t})`:`${this._samplerFunc(i)}(${e}, ${t})`}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??t,s=this.samplerZName??t,r=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("x"),o=e._getFreeVariableName("y"),a=e._getFreeVariableName("z"),l=e._getFreeVariableName("w"),h=e._getFreeVariableName("n"),c=e._getFreeVariableName("uvx"),u=e._getFreeVariableName("uvy"),d=e._getFreeVariableName("uvz");e.compilationString+=`\n ${e._declareLocalVar(h,al.Vector3)} = ${this.normal.associatedVariableName}.xyz;\n\n ${e._declareLocalVar(c,al.Vector2)} = ${this.position.associatedVariableName}.yz;\n ${e._declareLocalVar(u,al.Vector2)} = ${this.position.associatedVariableName}.zx;\n ${e._declareLocalVar(d,al.Vector2)} = ${this.position.associatedVariableName}.xy;\n `,this.projectAsCube&&(e.compilationString+=`\n ${c}.xy = ${c}.yx;\n\n if (${h}.x >= 0.0) {\n ${c}.x = -${c}.x;\n }\n if (${h}.y < 0.0) {\n ${u}.y = -${u}.y;\n }\n if (${h}.z < 0.0) {\n ${d}.x = -${d}.x;\n }\n `);const _=e.fSuffix;e.compilationString+=`\n ${e._declareLocalVar(n,al.Vector4)} = ${this._generateTextureSample(t,c,e)};\n ${e._declareLocalVar(o,al.Vector4)} = ${this._generateTextureSample(i,u,e)};\n ${e._declareLocalVar(a,al.Vector4)} = ${this._generateTextureSample(s,d,e)};\n \n // blend weights\n ${e._declareLocalVar(l,al.Vector3)} = pow(abs(${h}), vec3${_}(${r}));\n\n // blend and return\n ${e._declareLocalVar(this._tempTextureRead,al.Vector4)} = (${n}*${l}.x + ${o}*${l}.y + ${a}*${l}.z) / (${l}.x + ${l}.y + ${l}.z); \n `}_generateConversionCode(e,t,i){let s="";e.shaderLanguage!==di.WGSL||t.type!==al.Vector3&&t.type!==al.Color3||(s="Vec3"),"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace${s}(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace${s}(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i){let s="";this.disableLevelMultiplication||(s=` * ${e.shaderLanguage===di.WGSL?"uniforms.":""}${this._textureInfoName}`),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${s};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=(e.shaderLanguage===di.WGSL?"uniforms.":"")+this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Texture"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,al.Float),this._generateTextureLookup(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,e+=`${this._codeVariableName}.projectAsCube = ${this.projectAsCube};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!hh.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Pa.Parse(e.texture,t,i))}}Ze([Cl("Project as cube",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],uy.prototype,"projectAsCube",void 0),z("BABYLON.TriPlanarBlock",uy);class dy extends uy{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_declareLocalVarAsVec3I(e,t){return t.shaderLanguage===di.WGSL?`var ${e}: vec3`:`ivec3 ${e}`}_getTextureGrad(e,t){return e.shaderLanguage===di.WGSL?`textureSampleGrad(${t},${t+"Sampler"}`:`textureGrad(${t}`}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",r=e._getFreeVariableName("dxValue"),n=e._getFreeVariableName("dyValue"),o=e._getFreeVariableName("n"),a=e._getFreeVariableName("ma"),l=e._getFreeVariableName("mi"),h=e._getFreeVariableName("me"),c=e._getFreeVariableName("x"),u=e._getFreeVariableName("y"),d=e._getFreeVariableName("w");let _="ivec3",p="dFdx",f="dFdy";const m=e.fSuffix;e.shaderLanguage===di.WGSL&&(_="vec3",p="dpdx",f="dpdy"),e.compilationString+=`\n // grab coord derivatives for texturing\n ${e._declareLocalVar(r,al.Vector3)} = ${p}(${this.position.associatedVariableName}.xyz);\n ${e._declareLocalVar(n,al.Vector3)} = ${f}(${this.position.associatedVariableName}.xyz);\n ${e._declareLocalVar(o,al.Vector3)} = abs(${this.normal.associatedVariableName}.xyz);\n \n // determine major axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(a,e)} = ${e._generateTernary(`${_}(0,1,2)`,`${e._generateTernary(`${_}(1,2,0)`,`${_}(2,0,1)`,`(${o}.y>${o}.z)`)}`,`(${o}.x>${o}.y && ${o}.x>${o}.z)`)}; \n\n // determine minor axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(l,e)} = ${e._generateTernary(`${_}(0,1,2)`,`${e._generateTernary(`${_}(1,2,0)`,`${_}(2,0,1)`,`(${o}.y<${o}.z)`)}`,`(${o}.x<${o}.y && ${o}.x<${o}.z)`)}; \n \n // determine median axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(h,e)} = ${_}(3) - ${l} - ${a};\n \n // project+fetch\n ${e._declareLocalVar(c,al.Vector4)} = ${this._getTextureGrad(e,t)}, vec2${m}(${this.position.associatedVariableName}[${a}.y], ${this.position.associatedVariableName}[${a}.z]), \n vec2${m}(${r}[${a}.y],${r}[${a}.z]), \n vec2${m}(${n}[${a}.y],${n}[${a}.z]));\n ${e._declareLocalVar(u,al.Vector4)} = ${this._getTextureGrad(e,i)}, vec2${m}(${this.position.associatedVariableName}[${h}.y], ${this.position.associatedVariableName}[${h}.z]), \n vec2${m}(${r}[${h}.y],${r}[${h}.z]),\n vec2${m}(${n}[${h}.y],${n}[${h}.z]));\n \n // blend factors\n ${e._declareLocalVar(d,al.Vector2)} = vec2${m}(${o}[${a}.x],${o}[${h}.x]);\n // make local support\n ${d} = clamp( (${d}-0.5773)/(1.0-0.5773), vec2${m}(0.0), vec2${m}(1.0) );\n // shape transition\n ${d} = pow( ${d}, vec2${m}(${s}/8.0) );\n // blend and return\n ${e._declareLocalVar(this._tempTextureRead,al.Vector4)} = (${c}*${d}.x + ${u}*${d}.y) / (${d}.x + ${d}.y);\n `}}z("BABYLON.BiPlanarBlock",dy);class _y extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("input",al.Matrix),this.registerOutput("output",al.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=e._declareOutput(t)+` = determinant(${i.associatedVariableName});\n`,this}}z("BABYLON.MatrixDeterminantBlock",_y);class py extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("input",al.Matrix),this.registerOutput("output",al.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=e._declareOutput(t)+` = transpose(${i.associatedVariableName});\n`,this}}z("BABYLON.MatrixTransposeBlock",py),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Tangent=2]="Tangent",e[e.VertexColor=3]="VertexColor",e[e.UV1=4]="UV1",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6"}(iy||(iy={}));class fy extends Tl{constructor(e){super(e,ll.Neutral),this.attributeType=iy.None,this.registerInput("input",al.AutoDetect),this.registerInput("fallback",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add((e=>{if(this.attributeType)return;const t=e.ownerBlock;if(t instanceof Ol&&t.isAttribute)switch(t.name){case"color":this.attributeType=iy.VertexColor;break;case"normal":this.attributeType=iy.Normal;break;case"tangent":this.attributeType=iy.Tangent;break;case"uv":this.attributeType=iy.UV1;break;case"uv2":this.attributeType=iy.UV2;break;case"uv3":this.attributeType=iy.UV3;break;case"uv4":this.attributeType=iy.UV4;break;case"uv5":this.attributeType=iy.UV5;break;case"uv6":this.attributeType=iy.UV6}else if(t instanceof Ob)switch(this.input.connectedPoint?.name){case"normalOutput":this.attributeType=iy.Normal;break;case"tangentOutput":this.attributeType=iy.Tangent;break;case"uvOutput":this.attributeType=iy.UV1}}))}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case iy.VertexColor:t="VERTEXCOLOR_NME";break;case iy.Normal:t="NORMAL";break;case iy.Tangent:t="TANGENT";break;case iy.UV1:t="UV1";break;case iy.UV2:t="UV2";break;case iy.UV3:t="UV3";break;case iy.UV4:t="UV4";break;case iy.UV5:t="UV5";break;case iy.UV6:t="UV6"}const i=e._declareOutput(this.output);return t&&(e.compilationString+=`#ifdef ${t}\n`),e.compilationString+=`${i} = ${this.input.associatedVariableName};\n`,t&&(e.compilationString+="#else\n",e.compilationString+=`${i} = ${this.fallback.associatedVariableName};\n`,e.compilationString+="#endif\n"),this}serialize(){const e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.attributeType=e.attributeType??iy.None}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType};\n`,e}}Ze([Cl("Attribute lookup",ul.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:iy.None},{label:"Normal",value:iy.Normal},{label:"Tangent",value:iy.Tangent},{label:"Vertex Color",value:iy.VertexColor},{label:"UV1",value:iy.UV1},{label:"UV2",value:iy.UV2},{label:"UV3",value:iy.UV3},{label:"UV4",value:iy.UV4},{label:"UV5",value:iy.UV5},{label:"UV6",value:iy.UV6}]})],fy.prototype,"attributeType",void 0),z("BABYLON.MeshAttributeExistsBlock",fy),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(sy||(sy={}));class my extends Tl{constructor(e){super(e,ll.Neutral),this.type=sy.EaseInOutSine,this.registerInput("input",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(al.Matrix),this._inputs[0].excludedConnectionPointTypes.push(al.Object),this._inputs[0].excludedConnectionPointTypes.push(al.Int)}getClassName(){return"CurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_duplicateEntry(e,t){return`ret.${t} = ${e.replace(/VAL/g,"v."+t)}`}_duplicateEntryDirect(e){return`return ${e.replace(/VAL/g,"v")}`}_duplicateVector(e,t,i){if("float"===t||"f32"===t)return this._duplicateEntryDirect(e);const s=parseInt(t.replace("vec",""));let r=i?`\n var ret: vec${s}f = vec${s}f(0.0);\n `:`\n vec${s} ret = vec${s}(0.0);\n `;for(let t=1;t<=s;t++)r+=this._duplicateEntry(e,1===t?"x":2===t?"y":3===t?"z":"w")+";\n";return r+="return ret;\n",r}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",s="";const r=e._getShaderType(this.input.type),n=e.shaderLanguage===di.WGSL;switch(s=sy[this.type]+"_"+r.replace("<","").replace(">",""),this.type){case sy.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case sy.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case sy.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case sy.EaseInQuad:i="return v * v";break;case sy.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case sy.EaseInOutQuad:{const t=e._generateTernary("2.0 * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case sy.EaseInCubic:i="return v * v * v";break;case sy.EaseOutCubic:{const e="1.0 - pow(1.0 - VAL, 3.0)";i=this._duplicateVector(e,r,n);break}case sy.EaseInOutCubic:{const t=e._generateTernary("4.0 * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case sy.EaseInQuart:i="return v * v * v * v";break;case sy.EaseOutQuart:{const e="1.0 - pow(1.0 - VAL, 4.0)";i=this._duplicateVector(e,r,n);break}case sy.EaseInOutQuart:{const t=e._generateTernary("8.0 * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case sy.EaseInQuint:i="return v * v * v * v * v";break;case sy.EaseOutQuint:{const e="1.0 - pow(1.0 - VAL, 5.0)";i=this._duplicateVector(e,r,n);break}case sy.EaseInOutQuint:{const t=e._generateTernary("16.0 * VAL * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case sy.EaseInExpo:{const t=e._generateTernary("0.0","pow(2.0, 10.0 * VAL - 10.0)","VAL == 0.0");i=this._duplicateVector(t,r,n);break}case sy.EaseOutExpo:{const t=e._generateTernary("1.0","1.0 - pow(2.0, -10.0 * VAL)","VAL == 1.0");i=this._duplicateVector(t,r,n);break}case sy.EaseInOutExpo:{const t=e._generateTernary("0.0",e._generateTernary("1.0",e._generateTernary("pow(2.0, 20.0 * VAL - 10.0) / 2.0","(2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}case sy.EaseInCirc:{const e="1.0 - sqrt(1.0 - pow(VAL, 2.0))";i=this._duplicateVector(e,r,n);break}case sy.EaseOutCirc:{const e="sqrt(1.0 - pow(VAL - 1.0, 2.0))";i=this._duplicateVector(e,r,n);break}case sy.EaseInOutCirc:{const t=e._generateTernary("(1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0","(sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case sy.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case sy.EaseOutBack:{const e="2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)";i=this._duplicateVector(e,r,n);break}case sy.EaseInOutBack:{const t=e._generateTernary("(pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0","(pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case sy.EaseInElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0","-pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))","VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}case sy.EaseOutElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0","pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0","VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}case sy.EaseInOutElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0",e._generateTernary("-(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0","(pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}}return n?e._emitFunction(s,`fn ${s}(v: ${r}) -> ${r} {${i};}\n`,""):e._emitFunction(s,`${r} ${s}(${r} v) {${i};}\n`,""),e.compilationString+=e._declareOutput(t)+` = ${s}(${this.input.associatedVariableName});\n`,this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${sy[this.type]};\n`}}z("BABYLON.CurveBlock",my);class gy{optimize(e,t){}}class vy{constructor(){this.mm=new Map}get(e,t){const i=this.mm.get(e);if(void 0!==i)return i.get(t)}set(e,t,i){let s=this.mm.get(e);void 0===s&&this.mm.set(e,s=new Map),s.set(t,i)}}class xy{get standalone(){return this._options?.standalone??!1}get baseMaterial(){return this._baseMaterial}get doNotInjectCode(){return this._options?.doNotInjectCode??!1}constructor(e,t,i){this._baseMaterial=e,this._scene=t??re.LastCreatedScene,this._options=i,this._subMeshToEffect=new Map,this._subMeshToDepthWrapper=new vy,this._meshes=new Map,this._onEffectCreatedObserver=this._baseMaterial.onEffectCreatedObservable.add((e=>{const t=e.subMesh?.getMesh();t&&!this._meshes.has(t)&&this._meshes.set(t,t.onDisposeObservable.add((e=>{const t=this._subMeshToEffect.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value;t?.getMesh()===e&&(this._subMeshToEffect.delete(t),this._deleteDepthWrapperEffect(t))}}))),this._subMeshToEffect.get(e.subMesh)?.[0]!==e.effect&&(this._subMeshToEffect.set(e.subMesh,[e.effect,this._scene.getEngine().currentRenderPassId]),this._deleteDepthWrapperEffect(e.subMesh))}))}_deleteDepthWrapperEffect(e){const t=this._subMeshToDepthWrapper.mm.get(e);t&&(t.forEach((e=>{e.mainDrawWrapper.effect?.dispose()})),this._subMeshToDepthWrapper.mm.delete(e))}getEffect(e,t,i){const s=this._subMeshToDepthWrapper.mm.get(e)?.get(t);if(!s)return null;let r=s.drawWrapper[i];return r||(r=s.drawWrapper[i]=new Un(this._scene.getEngine()),r.setEffect(s.mainDrawWrapper.effect,s.mainDrawWrapper.defines)),r}isReadyForSubMesh(e,t,i,s,r){return!(this.standalone&&!this._baseMaterial.isReadyForSubMesh(e.getMesh(),e,s))&&(this._makeEffect(e,t,i,r)?.isReady()??!1)}dispose(){this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver),this._onEffectCreatedObserver=null;const e=this._meshes.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;e.onDisposeObservable.remove(i)}}_makeEffect(e,t,i,s){const r=this._scene.getEngine(),n=this._subMeshToEffect.get(e);if(!n)return null;const[o,a]=n;let l=this._subMeshToDepthWrapper.get(e,i);if(!l){const t=new Un(r);t.defines=e._getDrawWrapper(a)?.defines??null,l={drawWrapper:[],mainDrawWrapper:t,depthDefines:"",token:Cs()},l.drawWrapper[s]=t,this._subMeshToDepthWrapper.set(e,i,l)}const h=t.join("\n");if(l.mainDrawWrapper.effect&&h===l.depthDefines)return l.mainDrawWrapper.effect;l.depthDefines=h;const c=o.getUniformNames().slice();let u=o.vertexSourceCodeBeforeMigration,d=o.fragmentSourceCodeBeforeMigration;if(!this.doNotInjectCode){const e=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",t=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",i=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",s="#include",r="#include";u=o.shaderLanguage===di.GLSL?u.replace(/void\s+?main/g,`\n${r}\nvoid main`):u.replace(/@vertex/g,`\n${r}\n@vertex`),u=u.replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g,e),u=-1!==u.indexOf("#define SHADOWDEPTH_METRIC")?u.replace(/#define SHADOWDEPTH_METRIC/g,t):u.replace(/}\s*$/g,t+"\n}"),u=u.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g,"");const n=d.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW")>=0||d.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG")>=0,a=-1!==d.indexOf("#define SHADOWDEPTH_FRAGMENT");let l="";n?d=d.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g,i):l=i+"\n",d=d.replace(/void\s+?main/g,$i.IncludesShadersStore.shadowMapFragmentExtraDeclaration+"\nvoid main"),a?d=d.replace(/#define SHADOWDEPTH_FRAGMENT/g,s):l+=s+"\n",l&&(d=d.replace(/}\s*$/g,l+"}")),c.push("biasAndScaleSM","depthValuesSM","lightDataSM","softTransparentShadowSM")}l.mainDrawWrapper.effect=r.createEffect({vertexSource:u,fragmentSource:d,vertexToken:l.token,fragmentToken:l.token},{attributes:o.getAttributesNames(),uniformsNames:c,uniformBuffersNames:o.getUniformBuffersNames(),samplers:o.getSamplers(),defines:h+"\n"+o.defines.replace("#define SHADOWS","").replace(/#define SHADOW\d/g,""),indexParameters:o.getIndexParameters(),shaderLanguage:o.shaderLanguage},r);for(let e=0;e0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof _e){const t=[];return e.forEach((e=>{t.push(e.flatMap((e=>[e.x,e.y,e.z])))})),t}if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){const t=[];return e.forEach((e=>{t.push(Array.from(e))})),t}return[]}static OmitZeroLengthPredicate(e,t,i){const s=[];return t.subtract(e).lengthSquared()>0&&s.push([e,t]),i.subtract(t).lengthSquared()>0&&s.push([t,i]),e.subtract(i).lengthSquared()>0&&s.push([i,e]),0===s.length?null:s}static OmitDuplicatesPredicate(e,t,i,s){const r=[];return My._SearchInPoints(e,t,s)||r.push([e,t]),My._SearchInPoints(t,i,s)||r.push([t,i]),My._SearchInPoints(i,e,s)||r.push([i,e]),0===r.length?null:r}static _SearchInPoints(e,t,i){for(const s of i)for(let i=0;i{const r=e.getVerticesData(er.PositionKind),n=e.getIndices();if(r&&n)for(let o=0,a=0;o[e.x,e.y,e.z]))}static GetPointsCountInfo(e){const t=new Array(e.length);let i=0;for(let s=e.length;s--;)t[s]=e[s].length/3,i+=t[s];return{total:i,counts:t}}static GetLineLength(e){if(0===e.length)return 0;let t;t="number"==typeof e[0]?My.ToVector3Array(e):e;const i=ve.Vector3[0];let s=0;for(let e=0;e{e.length>t?My.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t)).forEach((e=>{s.push(e)})):(s.push(e.point1),s.push(e.point2))})),s}static SegmentizeLineBySegmentCount(e,t){const i="number"==typeof e[0]?My.ToVector3Array(e):e,s=My.GetLineLength(i)/t;return My.SegmentizeLineBySegmentLength(i,s)}static GetLineSegments(e){const t=[];for(let i=0;ie.length));return{min:t[0].length,max:t[t.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,s=!1){const r=t*i;let n=0,o=0;const a=e.length;for(let t=0;t[e.x,e.y,e.z]))}static GetArrowCap(e,t,i,s,r,n=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[s,r,n,o]}}static GetPointsFromText(e,t,i,s,r=0,n=!0){const o=[],a=P_(e,t,i,s);for(const e of a){for(const t of e.paths){const e=[],i=t.getPoints();for(const t of i)e.push(t.x,t.y,r);o.push(e)}if(n)for(const t of e.holes){const e=[],i=t.getPoints();for(const t of i)e.push(t.x,t.y,r);o.push(e)}}return o}static Color3toRGBAUint8(e){const t=new Uint8Array(4*e.length);for(let i=0,s=0;ir?r:t.length,o=Math.ceil(t.length/r);o>1&&(t=[...t,...Array(n*o-t.length).fill(t[0])]);const a=My.Color3toRGBAUint8(t),l=new Oa(a,n,o,oo.TEXTUREFORMAT_RGBA,s,!1,!0,i);return l.name=e,l}static PrepareEmptyColorsTexture(e){if(!Ry.EmptyColorsTexture){const t=new Uint8Array(4);Ry.EmptyColorsTexture=new Oa(t,1,1,oo.TEXTUREFORMAT_RGBA,e,!1,!1,Oa.NEAREST_NEAREST),Ry.EmptyColorsTexture.name="grlEmptyColorsTexture"}return Ry.EmptyColorsTexture}static DisposeEmptyColorsTexture(){Ry.EmptyColorsTexture?.dispose(),Ry.EmptyColorsTexture=null}static BooleanToNumber(e){return e?1:0}}class Oy extends xl{constructor(){super(...arguments),this.GREASED_LINE_HAS_COLOR=!1,this.GREASED_LINE_SIZE_ATTENUATION=!1,this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=!1,this.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=!1,this.GREASED_LINE_CAMERA_FACING=!0}}class Dy extends nu{constructor(e,t,i){i=i||{color:Ry.DEFAULT_COLOR};const s=new Oy;s.GREASED_LINE_HAS_COLOR=!!i.color&&!i.useColors,s.GREASED_LINE_SIZE_ATTENUATION=i.sizeAttenuation??!1,s.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=i.colorDistributionType===oy.COLOR_DISTRIBUTION_TYPE_LINE,s.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=(t??e.getScene()).useRightHandedSystem,s.GREASED_LINE_CAMERA_FACING=i.cameraFacing??!0,super(e,Dy.GREASED_LINE_MATERIAL_NAME,200,s),this.colorsTexture=null,this._scene=t??e.getScene(),this._engine=this._scene.getEngine(),this._cameraFacing=i.cameraFacing??!0,this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.width=i.width?i.width:i.sizeAttenuation?Ry.DEFAULT_WIDTH_ATTENUATED:Ry.DEFAULT_WIDTH,this._sizeAttenuation=i.sizeAttenuation??!1,this.colorMode=i.colorMode??ny.COLOR_MODE_SET,this._color=i.color??null,this.useColors=i.useColors??!1,this._colorsDistributionType=i.colorDistributionType??oy.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=i.colorsSampling??Oa.NEAREST_NEAREST,this._colors=i.colors??null,this.dashCount=i.dashCount??1,this.resolution=i.resolution??new de(this._engine.getRenderWidth(),this._engine.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this._colors?this.colorsTexture=My.CreateColorsTexture(`${e.name}-colors-texture`,this._colors,this.colorsSampling,this._scene):(this._color=this._color??Ry.DEFAULT_COLOR,My.PrepareEmptyColorsTexture(this._scene)),this._engine.onDisposeObservable.add((()=>{My.DisposeEmptyColorsTexture()})),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this.colorsTexture&&e.push(this.colorsTexture)}getUniforms(){const e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_textureSize",size:2,type:"vec2"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?"\n uniform vec4 grl_aspect_resolution_lineWidth;\n uniform mat4 grl_projection;\n ":"",fragment:"\n uniform vec4 grl_dashOptions;\n uniform vec2 grl_textureSize;\n uniform vec4 grl_colorMode_visibility_colorsWidth_useColors;\n uniform vec3 grl_singleColor;\n "}}get isEnabled(){return!0}bindForSubMesh(e){if(this._cameraFacing){const t=this._scene.activeCamera;if(!t)throw Error("GreasedLinePluginMaterial requires an active camera.");{const i=t.getProjectionMatrix();e.updateMatrix("grl_projection",i)}const i=ve.Vector4[0];i.x=this._aspect,i.y=this._resolution.x,i.z=this._resolution.y,i.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",i)}const t=ve.Vector4[0];t.x=My.BooleanToNumber(this.useDash),t.y=this._dashArray,t.z=this.dashOffset,t.w=this.dashRatio,e.updateVector4("grl_dashOptions",t);const i=ve.Vector4[1];i.x=this.colorMode,i.y=this.visibility,i.z=this.colorsTexture?this.colorsTexture.getSize().width:0,i.w=My.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",i),this._color&&e.updateColor3("grl_singleColor",this._color);const s=this.colorsTexture??Ry.EmptyColorsTexture;e.setTexture("grl_colors",s),e.updateFloat2("grl_textureSize",s?.getSize().width??1,s?.getSize().height??1)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===oy.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return Dy.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if("vertex"===e){const e={CUSTOM_VERTEX_DEFINITIONS:"\n attribute float grl_widths;\n attribute vec3 grl_offsets;\n attribute float grl_colorPointers;\n varying float grlCounters;\n varying float grlColorPointer;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n attribute vec4 grl_previousAndSide;\n attribute vec4 grl_nextAndCounters;\n\n vec2 grlFix( vec4 i, float aspect ) {\n vec2 res = i.xy / i.w;\n res.x *= aspect;\n return res;\n }\n #else\n attribute vec3 grl_slopes;\n attribute float grl_counters;\n #endif\n ",CUSTOM_VERTEX_UPDATE_POSITION:"\n #ifdef GREASED_LINE_CAMERA_FACING\n vec3 grlPositionOffset = grl_offsets;\n positionUpdated += grlPositionOffset;\n #else\n positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths);\n #endif\n ",CUSTOM_VERTEX_MAIN_END:"\n grlColorPointer = grl_colorPointers;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n\n float grlAspect = grl_aspect_resolution_lineWidth.x;\n float grlBaseWidth = grl_aspect_resolution_lineWidth.w;\n\n\n vec3 grlPrevious = grl_previousAndSide.xyz;\n float grlSide = grl_previousAndSide.w;\n\n vec3 grlNext = grl_nextAndCounters.xyz;\n grlCounters = grl_nextAndCounters.w;\n\n mat4 grlMatrix = viewProjection * finalWorld;\n vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 );\n vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 );\n vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 );\n\n vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect );\n vec2 grlPrevP = grlFix( grlPrevPos, grlAspect );\n vec2 grlNextP = grlFix( grlNextPos, grlAspect );\n\n float grlWidth = grlBaseWidth * grl_widths;\n\n vec2 grlDir;\n if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP );\n else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP );\n else {\n vec2 grlDir1 = normalize( grlCurrentP - grlPrevP );\n vec2 grlDir2 = normalize( grlNextP - grlCurrentP );\n grlDir = normalize( grlDir1 + grlDir2 );\n }\n vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. );\n #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\n grlNormal.xy *= -.5 * grlWidth;\n #else\n grlNormal.xy *= .5 * grlWidth;\n #endif\n\n grlNormal *= grl_projection;\n\n #ifdef GREASED_LINE_SIZE_ATTENUATION\n grlNormal.xy *= grlFinalPosition.w;\n grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy;\n #endif\n\n grlFinalPosition.xy += grlNormal.xy * grlSide;\n gl_Position = grlFinalPosition;\n\n vPositionW = vec3(grlFinalPosition);\n #else\n grlCounters = grl_counters;\n #endif\n "};return this._cameraFacing&&(e["!gl_Position\\=viewProjection\\*worldPos;"]="//"),e}return"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:"\n varying float grlCounters;\n varying float grlColorPointer;\n uniform sampler2D grl_colors;\n ",CUSTOM_FRAGMENT_MAIN_END:`\n float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x;\n float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y;\n float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z;\n float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w;\n\n float grlUseDash = grl_dashOptions.x;\n float grlDashArray = grl_dashOptions.y;\n float grlDashOffset = grl_dashOptions.z;\n float grlDashRatio = grl_dashOptions.w;\n\n gl_FragColor.a *= step(grlCounters, grlVisibility);\n if( gl_FragColor.a == 0. ) discard;\n\n if(grlUseDash == 1.){\n gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio));\n if (gl_FragColor.a == 0.) discard;\n }\n\n #ifdef GREASED_LINE_HAS_COLOR\n if (grlColorMode == ${ny.COLOR_MODE_SET}.) {\n gl_FragColor.rgb = grl_singleColor;\n } else if (grlColorMode == ${ny.COLOR_MODE_ADD}.) {\n gl_FragColor.rgb += grl_singleColor;\n } else if (grlColorMode == ${ny.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor.rgb *= grl_singleColor;\n }\n #else\n if (grlUseColors == 1.) {\n #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE\n vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.);\n #else\n vec2 lookup = vec2(fract(grlColorPointer / grl_textureSize.x), 1.0 - floor(grlColorPointer / grl_textureSize.x) / max(grl_textureSize.y - 1.0, 1.0));\n vec4 grlColor = texture2D(grl_colors, lookup, 0.0);\n #endif\n if (grlColorMode == ${ny.COLOR_MODE_SET}.) {\n gl_FragColor = grlColor;\n } else if (grlColorMode == ${ny.COLOR_MODE_ADD}.) {\n gl_FragColor += grlColor;\n } else if (grlColorMode == ${ny.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor *= grlColor;\n }\n }\n #endif\n\n `}:null}dispose(){this.colorsTexture?.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){const s=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this.colorsTexture&&s===e.length&&!i){const t=My.Color3toRGBAUint8(e);this.colorsTexture.update(t)}else this.colorsTexture?.dispose(),this.colorsTexture=My.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}else this.colorsTexture?.dispose()}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){null===this._color&&null!==e||null!==this._color&&null===e?(this._color=e,!t&&this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){super.parse(e,t,i);const s=e.greasedLineMaterialOptions;this.colorsTexture?.dispose(),s.color&&this.setColor(s.color,!0),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colors&&(this.colors=s.colors),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),this.colors?this.colorsTexture=My.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):My.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){const t=e;t.colorsTexture?.dispose(),this._colors&&(t.colorsTexture=My.CreateColorsTexture(`${t._material.name}-colors-texture`,this._colors,t.colorsSampling,this._scene)),t.setColor(this.color,!0),t.colorsDistributionType=this.colorsDistributionType,t.colorsSampling=this.colorsSampling,t.colorMode=this.colorMode,t.useColors=this.useColors,t.visibility=this.visibility,t.useDash=this.useDash,t.dashCount=this.dashCount,t.dashRatio=this.dashRatio,t.dashOffset=this.dashOffset,t.width=this.width,t.sizeAttenuation=this.sizeAttenuation,t.resolution=this.resolution,t.markAllDefinesAsDirty()}}Dy.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",z(`BABYLON.${Dy.GREASED_LINE_MATERIAL_NAME}`,Dy);Bi.ShadersStore.greasedLinePixelShader="precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;}\nif (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { \ntextureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);}\nif (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}}\n";Bi.ShadersStore.greasedLineVertexShader="precision highp float;\n#include\nattribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer;\n#ifdef GREASED_LINE_CAMERA_FACING\nattribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;}\n#else\nattribute vec3 grl_slopes;attribute float grl_counters;\n#endif\nvoid main() {\n#include\ngrlColorPointer=grl_colorPointers;mat4 grlMatrix=viewProjection*finalWorld ;\n#ifdef GREASED_LINE_CAMERA_FACING\nfloat grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );}\nvec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. );\n#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\ngrlNormal.xy*=-.5*grlWidth;\n#else\ngrlNormal.xy*=.5*grlWidth;\n#endif\ngrlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;}\ngrlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition;\n#else\ngrlCounters=grl_counters;vec4 grlFinalPosition=grlMatrix*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition;\n#endif\n}\n";class wy extends Nd{constructor(e,t,i){const s=[`COLOR_DISTRIBUTION_TYPE_LINE ${oy.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${oy.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${ny.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${ny.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${ny.COLOR_MODE_MULTIPLY}.`],r=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&s.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(s.push("GREASED_LINE_CAMERA_FACING"),r.push("grl_previousAndSide","grl_nextAndCounters")):(r.push("grl_slopes"),r.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:r,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:s}),this._color=Ee.White(),this._colorsDistributionType=oy.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:Ry.DEFAULT_COLOR};const n=t.getEngine();this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.dashCount=i.dashCount??1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?Ry.DEFAULT_WIDTH_ATTENUATED:Ry.DEFAULT_WIDTH,this.sizeAttenuation=i.sizeAttenuation??!1,this.color=i.color??Ee.White(),this.useColors=i.useColors??!1,this.colorsDistributionType=i.colorDistributionType??oy.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=i.colorsSampling??Oa.NEAREST_NEAREST,this.colorMode=i.colorMode??ny.COLOR_MODE_SET,this._colors=i.colors??null,this._cameraFacing=i.cameraFacing??!0,this.resolution=i.resolution??new de(n.getRenderWidth(),n.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=My.PrepareEmptyColorsTexture(t),this._colors&&this.setColors(this._colors),n.onDisposeObservable.add((()=>{My.DisposeEmptyColorsTexture()}))}dispose(){this._colorsTexture?.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new de(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){const s=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this._colorsTexture&&s===e.length&&!i){const t=My.Color3toRGBAUint8(e);this._colorsTexture.update(t)}else this._colorsTexture?.dispose(),this.colorsTexture=My.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}else this._colorsTexture?.dispose()}get colorsTexture(){return this._colorsTexture??null}set colorsTexture(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",My.BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",My.BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",My.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=e??Ry.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){const s=e.greasedLineMaterialOptions;this._colorsTexture?.dispose(),s.color&&(this.color=s.color),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),s.colors?this.colorsTexture=My.CreateColorsTexture(`${this.name}-colors-texture`,s.colors,this.colorsSampling,this.getScene()):this.colorsTexture=My.PrepareEmptyColorsTexture(t),this._cameraFacing=s.cameraFacing??!0,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}const Ny=[new Ee(.98,.26,.38),new Ee(.47,.75,.3),new Ee(0,.26,.77),new Ee(.97,.6,.76),new Ee(.19,.63,.78),new Ee(.98,.8,.6),new Ee(.65,.43,.15),new Ee(.15,.47,.22),new Ee(.67,.71,.86),new Ee(.09,.46,.56),new Ee(.8,.98,.02),new Ee(.39,.29,.13),new Ee(.53,.63,.06),new Ee(.95,.96,.41),new Ee(1,.72,.94),new Ee(.63,.08,.31),new Ee(.66,.96,.95),new Ee(.22,.14,.19),new Ee(.14,.65,.59),new Ee(.93,1,.68),new Ee(.93,.14,.44),new Ee(.47,.86,.67),new Ee(.85,.07,.78),new Ee(.53,.64,.98),new Ee(.43,.37,.56),new Ee(.71,.65,.25),new Ee(.66,.19,.01),new Ee(.94,.53,.12),new Ee(.41,.44,.44),new Ee(.24,.71,.96),new Ee(.57,.28,.56),new Ee(.44,.98,.42)];var Fy;!function(e){e[e.NONE=0]="NONE",e[e.TRIANGLES=1]="TRIANGLES",e[e.VERTICES=2]="VERTICES",e[e.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",e[e.UV0=4]="UV0",e[e.UV1=5]="UV1",e[e.VERTEXCOLORS=6]="VERTEXCOLORS",e[e.MATERIALIDS=7]="MATERIALIDS"}(Fy||(Fy={}));class Ly extends xl{constructor(){super(...arguments),this.DBG_MODE=Fy.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class By extends nu{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){const i=new Ly;i.DBG_MODE=t.mode??i.DBG_MODE,i.DBG_MULTIPLY=t.multiply??i.DBG_MULTIPLY,super(e,"MeshDebug",200,i,!0,!0),this._mode=i.DBG_MODE,this._multiply=i.DBG_MULTIPLY,this.shadedDiffuseColor=t.shadedDiffuseColor??new Ee(1,1,1),this.shadedSpecularColor=t.shadedSpecularColor??new Ee(.8,.8,.8),this.shadedSpecularPower=t.shadedSpecularPower??10,this.wireframeThickness=t.wireframeThickness??.7,this.wireframeTrianglesColor=t.wireframeTrianglesColor??new Ee(0,0,0),this.wireframeVerticesColor=t.wireframeVerticesColor??new Ee(.8,.8,.8),this.vertexColor=t.vertexColor??new Ee(0,0,0),this.vertexRadius=t.vertexRadius??1.2,this.uvScale=t.uvScale??20,this.uvPrimaryColor=t.uvPrimaryColor??new Ee(1,1,1),this.uvSecondaryColor=t.uvSecondaryColor??new Ee(.5,.5,.5),this._materialColor=By.MaterialColors[By._PluginCount++%By.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&1==this._material.getScene().getEngine().version)return Ne.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),void(this._isEnabled=!1);this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){this._mode!=Fy.VERTICES&&this._mode!=Fy.TRIANGLES&&this._mode!=Fy.TRIANGLES_VERTICES||i.isVerticesDataPresent("dbg_initialPass")||Ne.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:"#if defined(DBG_ENABLED)\nuniform vec3 dbg_shadedDiffuseColor;\nuniform vec4 dbg_shadedSpecularColorPower;\nuniform vec3 dbg_thicknessRadiusScale;\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n uniform vec3 dbg_vertexColor;\n#endif\n\n#if DBG_MODE == 1\n uniform vec3 dbg_wireframeTrianglesColor;\n#elif DBG_MODE == 3\n uniform vec3 dbg_wireframeVerticesColor;\n#elif DBG_MODE == 4 || DBG_MODE == 5\n uniform vec3 dbg_uvPrimaryColor;\n uniform vec3 dbg_uvSecondaryColor;\n#elif DBG_MODE == 7\n uniform vec3 dbg_materialColor;\n#endif\n#endif"}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:"#if defined(DBG_ENABLED)\nattribute float dbg_initialPass;\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n#endif",CUSTOM_VERTEX_MAIN_END:"#if defined(DBG_ENABLED)\nfloat dbg_vertexIndex = mod(float(gl_VertexID), 3.);\nif (dbg_vertexIndex == 0.0) { \n dbg_vBarycentric = vec3(1.,0.,0.); \n}\nelse if (dbg_vertexIndex == 1.0) { \n dbg_vBarycentric = vec3(0.,1.,0.); \n}\nelse { \n dbg_vBarycentric = vec3(0.,0.,1.); \n}\n\ndbg_vVertexWorldPos = vPositionW;\ndbg_vPass = dbg_initialPass;\n#endif"}:{CUSTOM_FRAGMENT_DEFINITIONS:"#if defined(DBG_ENABLED)\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n\n#if !defined(DBG_MULTIPLY)\n vec3 dbg_applyShading(vec3 color) {\n vec3 N = vNormalW.xyz;\n vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz);\n vec3 H = normalize(L + L);\n float LdotN = clamp(dot(L,N), 0., 1.);\n float HdotN = clamp(dot(H,N), 0., 1.);\n float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w);\n color *= (LdotN / PI);\n color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI);\n return color;\n }\n#endif\n\n#if DBG_MODE == 1 || DBG_MODE == 3\n float dbg_edgeFactor() {\n vec3 d = fwidth(dbg_vBarycentric);\n vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric);\n return min(min(a3.x, a3.y), a3.z);\n }\n#endif\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor() {\n vec3 worldPos = vPositionW;\n float dist = length(worldPos - dbg_vVertexWorldPos);\n float camDist = length(worldPos - vEyePosition.xyz);\n float d = sqrt(camDist) * .001;\n return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist);\n }\n#endif\n\n#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2))\n float dbg_checkerboardFactor(vec2 uv) {\n vec2 f = fract(uv * dbg_thicknessRadiusScale.z);\n f -= .5;\n return (f.x * f.y) > 0. ? 1. : 0.;\n }\n#endif\n#endif",CUSTOM_FRAGMENT_MAIN_END:"#if defined(DBG_ENABLED)\nvec3 dbg_color = vec3(1.);\n#if DBG_MODE == 1\n dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor());\n#elif DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor = dbg_cornerFactor();\n if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard;\n dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor);\n #if DBG_MODE == 3\n dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor());\n #endif\n#elif DBG_MODE == 4 && defined(MAINUV1)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1));\n#elif DBG_MODE == 5 && defined(MAINUV2)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2));\n#elif DBG_MODE == 6 && defined(VERTEXCOLOR)\n dbg_color = vColor.rgb;\n#elif DBG_MODE == 7\n dbg_color = dbg_materialColor;\n#endif\n\n#if defined(DBG_MULTIPLY)\n gl_FragColor *= vec4(dbg_color, 1.);\n#else\n #if DBG_MODE != 6\n gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.);\n #else\n gl_FragColor = vec4(dbg_color, 1.);\n #endif\n#endif\n#endif"}}static Reset(){this._PluginCount=0,this.MaterialColors=Ny}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(0==e.getTotalIndices())return i;if(t){const t=e.getVerticesDataKinds(),s=e.getIndices(),r={};for(const i of t)r[i]=e.getVerticesData(i);i=function(){e.setIndices(s);for(const i of t){const t=e.getVertexBuffer(i).getStrideSize();e.setVerticesData(i,r[i],void 0,t)}e.removeVerticesData("dbg_initialPass")}}let s=Array.from(e.getIndices());const r=[];for(let e=0;enew Vy(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GaussianSplattingMaterial",e}getClassName(){return"GaussianSplattingMaterial"}static Parse(e,t,i){return St.Parse((()=>new Vy(e.name,t)),e,t,i)}}z("BABYLON.GaussianSplattingMaterial",Vy),Object.defineProperty(cu.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new Ty(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(Gg.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new Ty(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(_o.prototype,"decalMap",{get:function(){return this._decalMap},set:function(e){this._decalMap=e},enumerable:!0,configurable:!0});class Uy{constructor(e,t){this.radius=e,this.theta=t,this.radius=e,this.theta=t}getClassName(){return"Polar"}toString(){return JSON.stringify(this)}asArray(){return[this.radius,this.theta]}addToRef(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t}add(e){const t=new Uy(0,0);return this.addToRef(e,t),t}addInPlace(e){return this.addToRef(e,this),this}addInPlaceFromFloats(e,t){return this.radius+=e,this.theta+=t,this}subtractToRef(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t}subtract(e){const t=new Uy(0,0);return this.subtractToRef(e,t),t}subtractInPlace(e){return this.subtractToRef(e,this),this}subtractFromFloatsToRef(e,t,i){return i.radius=this.radius-e,i.theta=this.theta-t,i}subtractFromFloats(e,t){const i=new Uy(0,0);return this.subtractFromFloatsToRef(e,t,i),i}multiplyToRef(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t}multiply(e){const t=new Uy(0,0);return this.multiplyToRef(e,t),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}divideToRef(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t}divide(e){const t=new Uy(0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new Uy(this.radius,this.theta)}copyFrom(e){return this.radius=e.radius,this.theta=e.theta,this}copyFromFloats(e,t){return this.radius=e,this.theta=t,this}scaleToRef(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t}scale(e){const t=new Uy(0,0);return this.scaleToRef(e,t),t}scaleInPlace(e){return this.scaleToRef(e,this),this}set(e,t){return this.radius=e,this.theta=t,this}setAll(e){return this.set(e,e),this}toVector2ToRef(e){const t=this.radius*Math.cos(this.theta),i=this.radius*Math.sin(this.theta);return e.set(t,i),e}toVector2(){const e=new de(0,0);return this.toVector2ToRef(e)}static FromVector2ToRef(e,t){const i=Math.sign(e.y)*Math.acos(e.x/e.length());return t.radius=e.length(),t.theta=i,t}static FromVector2(e){const t=new Uy(0,0);return Uy.FromVector2ToRef(e,t),t}static FromArray(e){return new Uy(e[0],e[1])}}class Gy{constructor(e,t,i){this.radius=e,this.theta=t,this.phi=i,this.radius=e,this.theta=t,this.phi=i}getClassName(){return"Spherical"}toString(){return JSON.stringify(this)}asArray(){return[this.radius,this.theta,this.phi]}addToRef(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t.phi=this.phi+e.phi,t}add(e){const t=new Gy(0,0,0);return this.addToRef(e,t),t}addInPlace(e){return this.addToRef(e,this),this}addInPlaceFromFloats(e,t,i){return this.radius+=e,this.theta+=t,this.phi+=i,this}subtractToRef(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t.phi=this.phi-e.phi,t}subtract(e){const t=new Gy(0,0,0);return this.subtractToRef(e,t),t}subtractInPlace(e){return this.subtractToRef(e,this),this}subtractFromFloatsToRef(e,t,i,s){return s.radius=this.radius-e,s.theta=this.theta-t,s.phi=this.phi-i,s}subtractFromFloats(e,t,i){const s=new Gy(0,0,0);return this.subtractFromFloatsToRef(e,t,i,s),s}multiplyToRef(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t.phi=this.phi*e.phi,t}multiply(e){const t=new Gy(0,0,0);return this.multiplyToRef(e,t),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}divideToRef(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t.phi=this.phi/e.phi,t}divide(e){const t=new Gy(0,0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new Gy(this.radius,this.theta,this.phi)}copyFrom(e){return this.radius=e.radius,this.theta=e.theta,this.phi=e.phi,this}copyFromFloats(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this}scaleToRef(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t.phi=this.phi*e,t}scale(e){const t=new Gy(0,0,0);return this.scaleToRef(e,t),t}scaleInPlace(e){return this.scaleToRef(e,this),this}set(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this}setAll(e){return this.set(e,e,e),this}toVector3ToRef(e){const t=this.radius*Math.sin(this.theta)*Math.cos(this.phi),i=this.radius*Math.cos(this.theta),s=this.radius*Math.sin(this.theta)*Math.sin(this.phi);return e.set(t,i,s),e}toVector3(){const e=new _e(0,0,0);return this.toVector3ToRef(e)}static FromVector3ToRef(e,t){return t.radius=e.length(),t.theta=Math.acos(e.y/t.radius),t.phi=Math.atan2(e.z,e.x),t}static FromVector3(e){const t=new Gy(0,0,0);return Gy.FromVector3ToRef(e,t),t}static FromArray(e){return new Gy(e[0],e[1],e[2])}}class zy{constructor(e,t=2,i=3,s=1,r=1){this._curIndex=0,this._sequence=[],this._numSamples=0,this.x=0,this.y=0,this._width=s,this._height=r,this._baseX=t,this._baseY=i,this._generateSequence(e),this.next()}regenerate(e){this._generateSequence(e),this.next()}setDimensions(e,t){this._width=e,this._height=t}next(){this.x=this._sequence[this._curIndex]/this._width,this.y=this._sequence[this._curIndex+1]/this._height,this._curIndex+=2,this._curIndex>=2*this._numSamples&&(this._curIndex=0)}_generateSequence(e){this._sequence=[],this._curIndex=0,this._numSamples=e;for(let t=1;t<=e;++t)this._sequence.push(this._halton(t,this._baseX)-.5,this._halton(t,this._baseY)-.5)}_halton(e,t){let i=1,s=0;for(;e>0;)i/=t,s+=i*(e%t),e=~~(e/t);return s}}function Wy(e,t){return`{X: ${e.x.toFixed(t)} Y: ${e.y.toFixed(t)}}`}function Hy(e,t){return`{X: ${e._x.toFixed(t)} Y: ${e._y.toFixed(t)} Z: ${e._z.toFixed(t)}}`}function Xy(e,t){return`{X: ${e.x.toFixed(t)} Y: ${e.y.toFixed(t)} Z: ${e.z.toFixed(t)} W: ${e.w.toFixed(t)}}`}function Yy(e,t,i,s,r){let n=null,o=null,a=null;try{let l;n=new e.Decoder,o=new e.DecoderBuffer,o.Init(t,t.byteLength);const h=n.GetEncodedGeometryType(o);switch(h){case e.TRIANGULAR_MESH:{const t=new e.Mesh;if(l=n.DecodeBufferToMesh(o,t),!l.ok()||0===t.ptr)throw new Error(l.error_msg());const i=3*t.num_faces(),r=4*i,h=e._malloc(r);try{n.GetTrianglesUInt32Array(t,r,h);const o=new Uint32Array(i);o.set(new Uint32Array(e.HEAPF32.buffer,h,i)),s(o)}finally{e._free(h)}a=t;break}case e.POINT_CLOUD:{const t=new e.PointCloud;if(l=n.DecodeBufferToPointCloud(o,t),!l.ok()||!t.ptr)throw new Error(l.error_msg());a=t;break}default:throw new Error(`Invalid geometry type ${h}`)}const c=a.num_points(),u=(t,i,s,n)=>{const o=n.data_type(),a=n.num_components(),l=n.normalized(),h=n.byte_stride(),u=n.byte_offset(),d={[e.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:e.HEAPF32},[e.DT_INT8]:{typedArrayConstructor:Int8Array,heap:e.HEAP8},[e.DT_INT16]:{typedArrayConstructor:Int16Array,heap:e.HEAP16},[e.DT_INT32]:{typedArrayConstructor:Int32Array,heap:e.HEAP32},[e.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:e.HEAPU8},[e.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:e.HEAPU16},[e.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:e.HEAPU32}}[o];if(!d)throw new Error(`Invalid data type ${o}`);const _=c*a,p=_*d.typedArrayConstructor.BYTES_PER_ELEMENT,f=e._malloc(p);try{t.GetAttributeDataArrayForAllPoints(i,n,o,p,f);const e=new d.typedArrayConstructor(d.heap.buffer,f,_);r(s,e.slice(),a,u,h,l)}finally{e._free(f)}};if(i)for(const e in i){const t=i[e],s=n.GetAttributeByUniqueId(a,t);u(n,a,e,s)}else{const t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(const e in t){const i=n.GetAttributeId(a,t[e]);if(-1!==i){const t=n.GetAttribute(a,i);u(n,a,e,t)}}}return c}finally{a&&e.destroy(a),o&&e.destroy(o),n&&e.destroy(n)}}function Qy(){let e;onmessage=t=>{const i=t.data;switch(i.id){case"init":{const t=i.decoder;t.url&&importScripts(t.url);const s=t.wasmBinary?{wasmBinary:t.wasmBinary}:{};e=DracoDecoderModule(s),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((e=>{const t=Yy(e,i.dataView,i.attributes,(e=>{postMessage({id:"indices",data:e},[e.buffer])}),((e,t,i,s,r,n)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:s,byteStride:r,normalized:n},[t.buffer])}));postMessage({id:"decodeMeshDone",totalVertices:t})}))}}}class jy{static get DecoderAvailable(){const e=jy.Configuration.decoder;return!!(e.wasmUrl&&e.wasmBinaryUrl&&"object"==typeof WebAssembly||e.fallbackUrl)}static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static get Default(){return jy._Default||(jy._Default=new jy),jy._Default}static ResetDefault(e){jy._Default&&(e||jy._Default.dispose(),jy._Default=null)}constructor(e=jy.DefaultNumWorkers){const t=jy.Configuration.decoder;if(t.workerPool||"object"==typeof e&&e.workerPool)this._workerPoolPromise=Promise.resolve(t.workerPool||e.workerPool);else{const i=t.wasmBinary||"object"==typeof e&&e.wasmBinary,s="number"==typeof e?e:e.numWorkers,r=s&&"function"==typeof Worker&&"function"==typeof URL,n=r||!r&&!t.jsModule,o=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:n?Ds.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:i?Promise.resolve(i):Ds.LoadFileAsync(Ds.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:n?Ds.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};r?this._workerPoolPromise=o.wasmBinaryPromise.then((e=>{const t=`${Yy}(${Qy})()`,i=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));return new Qg(s,(()=>function(e,t,i){return new Promise(((s,r)=>{const n=t=>{e.removeEventListener("error",n),e.removeEventListener("message",o),r(t)},o=t=>{"initDone"===t.data.id&&(e.removeEventListener("error",n),e.removeEventListener("message",o),s(e))};if(e.addEventListener("error",n),e.addEventListener("message",o),t){const s=t.slice(0);e.postMessage({id:"init",decoder:{url:i,wasmBinary:s}},[s])}else e.postMessage({id:"init",decoder:{url:i}})}))}(new Worker(i),e,o.url)))})):this._decoderModulePromise=o.wasmBinaryPromise.then((async e=>{if("undefined"==typeof DracoDecoderModule&&!t.jsModule){if(!o.url)throw new Error("Draco decoder module is not available");await Ds.LoadBabylonScriptAsync(o.url)}return await(i=e,s=t.jsModule,new Promise((e=>{(s||DracoDecoderModule)({wasmBinary:i}).then((t=>{e({module:t})}))})));var i,s}))}}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then((e=>{e.dispose()})),delete this._workerPoolPromise,delete this._decoderModulePromise}async whenReadyAsync(){this._workerPoolPromise?await this._workerPoolPromise:this._decoderModulePromise&&await this._decoderModulePromise}decodeMeshToMeshDataAsync(e,t,i){const s=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength);if(this._workerPoolPromise)return this._workerPoolPromise.then((e=>new Promise(((r,n)=>{e.push(((e,o)=>{let a=null;const l=[],h=t=>{e.removeEventListener("error",h),e.removeEventListener("message",c),n(t),o()},c=t=>{const s=t.data;switch(s.id){case"decodeMeshDone":e.removeEventListener("error",h),e.removeEventListener("message",c),r({indices:a,attributes:l,totalVertices:s.totalVertices}),o();break;case"indices":a=s.data;break;case"attribute":l.push({kind:s.kind,data:s.data,size:s.size,byteOffset:s.byteOffset,byteStride:s.byteStride,normalized:(n=s.kind,u=s.normalized,i&&void 0!==i[n]?(u!==i[n]&&Ne.Warn(`Normalized flag from Draco data (${u}) does not match normalized flag from glTF accessor (${i[n]}). Using flag from glTF accessor.`),i[n]):u)})}var n,u};e.addEventListener("error",h),e.addEventListener("message",c);const u=s.slice();e.postMessage({id:"decodeMesh",dataView:u,attributes:t},[u.buffer])}))}))));if(this._decoderModulePromise)return this._decoderModulePromise.then((e=>{let i=null;const r=[],n=Yy(e.module,s,t,(e=>{i=e}),((e,t,i,s,n,o)=>{r.push({kind:e,data:t,size:i,byteOffset:s,byteStride:n,normalized:o})}));return{indices:i,attributes:r,totalVertices:n}}));throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,i,s){const r=await this.decodeMeshToMeshDataAsync(i,s),n=new Yn(e,t);r.indices&&n.setIndices(r.indices);for(const e of r.attributes)n.setVerticesBuffer(new er(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),r.totalVertices);return n}async _decodeMeshToGeometryForGltfAsync(e,t,i,s,r){const n=await this.decodeMeshToMeshDataAsync(i,s,r),o=new Yn(e,t);n.indices&&o.setIndices(n.indices);for(const e of n.attributes)o.setVerticesBuffer(new er(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),n.totalVertices);return o}async decodeMeshAsync(e,t){const i=await this.decodeMeshToMeshDataAsync(e,t),s=new Wn;i.indices&&(s.indices=i.indices);for(const e of i.attributes){const t=er.GetFloatData(e.data,e.size,er.GetDataType(e.data),e.byteOffset,e.byteStride,e.normalized,i.totalVertices);s.set(t,e.kind)}return s}}jy.Configuration={decoder:{wasmUrl:`${Ds._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${Ds._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${Ds._DefaultCdnUrl}/draco_decoder_gltf.js`}},jy.DefaultNumWorkers=jy.GetDefaultNumWorkers(),jy._Default=null;class Ky{static get Default(){return Ky._Default||(Ky._Default=new Ky),Ky._Default}constructor(){const e=Ky.Configuration.decoder;this._decoderModulePromise=Ds.LoadBabylonScriptAsync(e.url).then((()=>MeshoptDecoder.ready))}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,s,r){return this._decoderModulePromise.then((async()=>{MeshoptDecoder.useWorkers(1);const n=await MeshoptDecoder.decodeGltfBufferAsync(t,i,e,s,r);return MeshoptDecoder.useWorkers(0),n}))}}Ky.Configuration={decoder:{url:`${Ds._DefaultCdnUrl}/meshopt_decoder.js`}},Ky._Default=null;let $y=0;class qy{constructor(e,t,i,s){this.pos=e,this.normal=t,this.uv=i,this.vertColor=s}clone(){return new qy(this.pos.clone(),this.normal.clone(),this.uv?.clone(),this.vertColor?.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new qy(_e.Lerp(this.pos,e.pos,t),_e.Lerp(this.normal,e.normal,t),this.uv&&e.uv?de.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?Ae.Lerp(this.vertColor,e.vertColor,t):void 0)}}class Zy{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const s=i.subtract(e),r=t.subtract(e);if(0===s.lengthSquared()||0===r.lengthSquared())return null;const n=_e.Normalize(_e.Cross(s,r));return new Zy(n,_e.Dot(n,e))}clone(){return new Zy(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,s,r){let n=0;const o=[];let a,l;for(a=0;aZy.EPSILON?1:0;n|=t,o.push(t)}switch(n){case 0:(_e.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:s.push(e);break;case 2:r.push(e);break;case 3:{const t=[],i=[];for(a=0;a=3&&(n=new Jy(t,e.shared),n.plane&&s.push(n)),i.length>=3&&(n=new Jy(i,e.shared),n.plane&&r.push(n));break}}}}Zy.EPSILON=1e-5;class Jy{constructor(e,t){this.vertices=e,this.shared=t,this.plane=Zy.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map((e=>e.clone()));return new Jy(e,this.shared)}flip(){this.vertices.reverse().map((e=>{e.flip()})),this.plane.flip()}}class eS{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new eS;return e._plane=this._plane&&this._plane.clone(),e._front=this._front&&this._front.clone(),e._back=this._back&&this._back.clone(),e._polygons=this._polygons.map((e=>e.clone())),e}invert(){for(let e=0;ee.clone())),e.copyTransformAttributes(this),e}union(e){const t=new eS(this.clone()._polygons),i=new eS(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),tS._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new eS(this._polygons),i=new eS(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()}subtract(e){const t=new eS(this.clone()._polygons),i=new eS(e.clone()._polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),tS._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new eS(this._polygons),i=new eS(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}intersect(e){const t=new eS(this.clone()._polygons),i=new eS(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),tS._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new eS(this._polygons),i=new eS(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){const e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map((e=>{e.flip()}))}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){const i=this.matrix.clone();i.invert();const s=this._polygons,r=[],n=[],o=[];let a=null,l=null;const h=_e.Zero(),c=_e.Zero(),u=de.Zero(),d=new Ae(0,0,0,0),_=[0,0,0],p={};let f;for(let m=0,g=s.length;me.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId)),this.toVertexData((e=>{o[e.shared.meshId]||(o[e.shared.meshId]={}),o[e.shared.meshId][e.shared.subMeshId]||(o[e.shared.meshId][e.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:e.shared.materialIndex}),a=o[e.shared.meshId][e.shared.subMeshId]}),(()=>{a.indexStart=Math.min(n,a.indexStart),a.indexEnd=Math.max(n,a.indexEnd),n++})).applyToMesh(s),i){let e,t=0;s.subMeshes=[];for(const i in o){e=-1;for(const r in o[i])a=o[i][r],Gn.CreateFromIndices(a.materialIndex+t,a.indexStart,a.indexEnd-a.indexStart+1,s),e=Math.max(a.materialIndex,e);t+=++e}}return s}toMesh(e,t=null,i,s){const r=this.buildMeshGeometry(e,i,s);return r.material=t,r.position.copyFrom(this.position),r.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(r.rotationQuaternion=this.rotationQuaternion.clone()),r.scaling.copyFrom(this.scaling),r.computeWorldMatrix(!0),r}}Bi.ShadersStore.meshUVSpaceRendererVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nvoid main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW;\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\n#endif\nvec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);}";Bi.ShadersStore.meshUVSpaceRendererPixelShader="precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;}\ngl_FragColor=texture2D(textureSampler,vDecalTC);}\n";Bi.ShadersStore.meshUVSpaceRendererMaskerVertexShader="attribute vec2 uv;varying vec2 vUV;void main(void) {gl_Position=vec4(vec2(uv.x,uv.y)*2.0-1.0,0.,1.0);vUV=uv;}";Bi.ShadersStore.meshUVSpaceRendererMaskerPixelShader="varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);}\n";Bi.ShadersStore.meshUVSpaceRendererFinaliserPixelShader="precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D maskTextureSampler;uniform vec2 textureSize;void main() {vec4 mask=texture2D(maskTextureSampler,vUV).rgba;if (mask.r>0.5) {gl_FragColor=texture2D(textureSampler,vUV);} else {vec2 texelSize=4.0/textureSize;vec2 uv_p01=vUV+vec2(-1.0,0.0)*texelSize;vec2 uv_p21=vUV+vec2(1.0,0.0)*texelSize;vec2 uv_p10=vUV+vec2(0.0,-1.0)*texelSize;vec2 uv_p12=vUV+vec2(0.0,1.0)*texelSize;float mask_p01=texture2D(maskTextureSampler,uv_p01).r;float mask_p21=texture2D(maskTextureSampler,uv_p21).r;float mask_p10=texture2D(maskTextureSampler,uv_p10).r;float mask_p12=texture2D(maskTextureSampler,uv_p12).r;vec4 col=vec4(0.0,0.0,0.0,0.0);float total_weight=0.0;if (mask_p01>0.5) {col+=texture2D(textureSampler,uv_p01);total_weight+=1.0;}\nif (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;}\nif (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;}\nif (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;}\nif (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}}\n";Bi.ShadersStore.meshUVSpaceRendererFinaliserVertexShader="precision highp float;attribute vec3 position;attribute vec2 uv;uniform mat4 worldViewProjection;varying vec2 vUV;void main() {gl_Position=worldViewProjection*vec4(position,1.0);vUV=uv;}\n";class iS{static _GetShader(e){if(!e._meshUVSpaceRendererShader){const t=new Nd("meshUVSpaceRendererShader",e,{vertex:"meshUVSpaceRenderer",fragment:"meshUVSpaceRenderer"},{attributes:["position","normal","uv"],uniforms:["world","projMatrix"],samplers:["textureSampler"],needAlphaBlending:!0});t.backFaceCulling=!1,t.alphaMode=2,e.onDisposeObservable.add((()=>{e._meshUVSpaceRendererShader?.dispose(),e._meshUVSpaceRendererShader=null})),e._meshUVSpaceRendererShader=t}return e._meshUVSpaceRendererShader}static _GetMaskShader(e){if(!e._meshUVSpaceRendererMaskShader){const t=new Nd("meshUVSpaceRendererMaskShader",e,{vertex:"meshUVSpaceRendererMasker",fragment:"meshUVSpaceRendererMasker"},{attributes:["position","uv"],uniforms:["worldViewProjection"]});t.backFaceCulling=!1,t.alphaMode=2,e.onDisposeObservable.add((()=>{e._meshUVSpaceRendererMaskShader?.dispose(),e._meshUVSpaceRendererMaskShader=null})),e._meshUVSpaceRendererMaskShader=t}return e._meshUVSpaceRendererMaskShader}static _IsRenderTargetTexture(e){return void 0!==e.renderList}constructor(e,t,i){this._textureCreatedInternally=!1,this._configureUserCreatedTexture=!0,this._maskTexture=null,this._finalPostProcess=null,this.clearColor=new Ae(0,0,0,0),this._mesh=e,this._scene=t,this._options={width:1024,height:1024,textureType:0,generateMipMaps:!0,optimizeUVAllocation:!0,uvEdgeBlending:!1,...i}}isReady(){this.texture||this._createDiffuseRTT();const e=iS._IsRenderTargetTexture(this.texture)?this.texture.isReadyForRendering():this.texture.isReady(),t=this._maskTexture?.isReadyForRendering()??!0,i=this._finalPostProcess?.isReady()??!0;return e&&t&&i}renderTexture(e,t,i,s,r=0){if(this.texture?this._configureUserCreatedTexture&&this._configureUserCreatedRTT():this._createDiffuseRTT(),iS._IsRenderTargetTexture(this.texture)){const n=this._createProjectionMatrix(t,i,s,r),o=iS._GetShader(this._scene);o.setTexture("textureSampler",e),o.setMatrix("projMatrix",n),this.texture.render()}}clear(){if(iS._IsRenderTargetTexture(this.texture)&&this.texture.renderTarget){const e=this._scene.getEngine();e.bindFramebuffer(this.texture.renderTarget),e.clear(this.clearColor,!0,!0,!0),e.unBindFramebuffer(this.texture.renderTarget)}if(this._finalPostProcess?.inputTexture){const e=this._scene.getEngine();e.bindFramebuffer(this._finalPostProcess?.inputTexture),e.clear(this.clearColor,!0,!0,!0),e.unBindFramebuffer(this._finalPostProcess?.inputTexture)}}dispose(){this._textureCreatedInternally&&(this.texture.dispose(),this._textureCreatedInternally=!1),this._configureUserCreatedTexture=!0,this._maskTexture?.dispose(),this._maskTexture=null,this._finalPostProcess?.dispose(),this._finalPostProcess=null}_configureUserCreatedRTT(){this._configureUserCreatedTexture=!1,iS._IsRenderTargetTexture(this.texture)&&(this.texture.setMaterialForRendering(this._mesh,iS._GetShader(this._scene)),this.texture.onClearObservable.add((()=>{})),this.texture.renderList=[this._mesh],this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),this.texture.addPostProcess(this._finalPostProcess)))}_createDiffuseRTT(){this._textureCreatedInternally=!0;const e=this._createRenderTargetTexture(this._options.width,this._options.height);e.setMaterialForRendering(this._mesh,iS._GetShader(this._scene)),this.texture=e,this._configureUserCreatedTexture=!1,this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),e.addPostProcess(this._finalPostProcess))}_createMaskTexture(){this._maskTexture||(this._maskTexture=new ih(this._mesh.name+"_maskTexture",{width:this._options.width,height:this._options.height},this._scene,!1,!0,0,!1,2,void 0,void 0,void 0,6),this._maskTexture.clearColor=new Ae(0,0,0,0),this._maskTexture.renderList.push(this._mesh),this._maskTexture.setMaterialForRendering(this._mesh,iS._GetMaskShader(this._scene)),this._maskTexture.refreshRate=ih.REFRESHRATE_RENDER_ONCE,this._scene.customRenderTargets.push(this._maskTexture))}_createPostProcess(){this._finalPostProcess||(this._finalPostProcess=new Vl(this._mesh.name+"_fixSeamsPostProcess","meshUVSpaceRendererFinaliser",["textureSize"],["textureSampler","maskTextureSampler"],1,null,1,this._scene.getEngine(),!1,null,this._options.textureType),this._finalPostProcess.onApplyObservable.add((e=>{e.setTexture("maskTextureSampler",this._maskTexture),e.setFloat2("textureSize",this._options.width,this._options.height)})))}_createRenderTargetTexture(e,t){const i=new ih(this._mesh.name+"_uvspaceTexture",{width:e,height:t},this._scene,this._options.generateMipMaps,!0,this._options.textureType,!1,this._options.generateMipMaps?3:2,!1,!1,!1,5);return i.renderParticles=!1,i.optimizeUVAllocation=!!this._options.optimizeUVAllocation,i.onClearObservable.addOnce((()=>{this._scene.getEngine().clear(this.clearColor,!0,!0,!0),i.onClearObservable.add((()=>{}))})),i.renderList=[this._mesh],i}_createProjectionMatrix(e,t,i,s=0){const r=-Math.atan2(t.z,t.x)-Math.PI/2,n=Math.sqrt(t.x*t.x+t.z*t.z),o=Math.atan2(t.y,n),a=e.add(t.scale(.5*i.z)),l=me.RotationYawPitchRoll(r,o,s).multiply(me.Translation(a.x,a.y,a.z)),h=me.Invert(l),c=me.FromArray([2/i.x,0,0,0,0,2/i.y,0,0,0,0,1/i.z,0,0,0,0,1]),u=me.FromArray([.5,0,0,0,0,.5,0,0,0,0,1,0,.5,.5,0,1]);return h.multiply(c).multiply(u)}}ha._TrailMeshParser=(e,t)=>sS.Parse(e,t);class sS extends ha{constructor(e,t,i,s,r=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._generator=t,"object"==typeof s&&null!==s?(this.diameter=s.diameter||1,this._length=s.length||60,this._segments=s.segments?s.segments>this._length?this._length:s.segments:this._length,this._sectionPolygonPointsCount=s.sections||4,this._doNotTaper=s.doNotTaper||!1,this._autoStart=s.autoStart||!0):(this.diameter=s||1,this._length=r,this._segments=this._length,this._doNotTaper=!1,this._autoStart=n),this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e<=this._sectionPolygonPointsCount;e++)this._sectionVectors[e]=_e.Zero(),this._sectionNormalVectors[e]=_e.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){const e=new Wn,t=[],i=[],s=[],r=[];let n=_e.Zero();n=this._generator instanceof _o&&this._generator.hasBoundingInfo?this._generator.getBoundingInfo().boundingBox.centerWorld:this._generator.absolutePosition;const o=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<=this._sectionPolygonPointsCount;e++){const i=e!==this._sectionPolygonPointsCount?e*o:0;t.push(n.x+Math.cos(i)*this.diameter,n.y+Math.sin(i)*this.diameter,n.z),r.push(e/this._sectionPolygonPointsCount,0)}for(let e=1;e<=this._segments;e++){for(let i=0;i<=this._sectionPolygonPointsCount;i++){const s=i!==this._sectionPolygonPointsCount?i*o:0;t.push(n.x+Math.cos(s)*this.diameter,n.y+Math.sin(s)*this.diameter,n.z),r.push(i/this._sectionPolygonPointsCount,e/this._segments)}const i=t.length/3-2*(this._sectionPolygonPointsCount+1);for(let e=0;e<=this._sectionPolygonPointsCount;e++)s.push(i+e,i+e+this._sectionPolygonPointsCount,i+e+this._sectionPolygonPointsCount+1),s.push(i+e,i+e+this._sectionPolygonPointsCount+1,i+e+1)}Wn.ComputeNormals(t,s,i),e.positions=t,e.normals=i,e.indices=s,e.uvs=r,e.applyToMesh(this,!0),this._autoStart&&this.start()}start(){this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add((()=>{this.update()})))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){const e=this.getVerticesData(er.PositionKind),t=this.getVerticesData(er.NormalKind),i=this._generator.getWorldMatrix(),s=3*(this._sectionPolygonPointsCount+1);if(e&&t){if(this._doNotTaper)for(let t=s;t{this._getSimplifier(e).simplify(t,(i=>{void 0!==t.distance&&e.mesh.addLODLevel(t.distance,i),i.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()}))}));else{const t=this._getSimplifier(e),i=(i,s)=>{t.simplify(i,(t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,s()}))};Ns.Run(e.settings.length,(t=>{i(e.settings[t.index],(()=>{t.executeNext()}))}),(()=>{e.successCallback&&e.successCallback(),this.executeNext()}))}}_getSimplifier(e){return e.simplificationType,oS.QUADRATIC,new PS(e.mesh)}}var oS,aS,lS,hS,cS,uS,dS,_S,pS,fS,mS,gS,vS,xS,bS,TS,yS;!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(oS||(oS={}));class SS{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class CS{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new ES,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class ES{constructor(e){this.data=new Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,s,r,n,o,a,l){return this.data[e]*this.data[r]*this.data[l]+this.data[i]*this.data[s]*this.data[a]+this.data[t]*this.data[n]*this.data[o]-this.data[i]*this.data[r]*this.data[o]-this.data[e]*this.data[n]*this.data[a]-this.data[t]*this.data[s]*this.data[l]}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){const t=new ES;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,s){return new ES(ES.DataFromNumbers(e,t,i,s))}static DataFromNumbers(e,t,i,s){return[e*e,e*t,e*i,e*s,t*t,t*i,t*s,i*i,i*s,s*s]}}class AS{constructor(e,t){this.vertexId=e,this.triangleId=t}}class PS{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=J}simplify(e,t){this._initDecimatedMesh(),Ns.Run(this._mesh.subMeshes.length,(t=>{this._initWithMesh(t.index,(()=>{this._runDecimation(e,t.index,(()=>{t.executeNext()}))}),e.optimizeMesh)}),(()=>{setTimeout((()=>{t(this._reconstructedMesh)}),0)}))}_runDecimation(e,t,i){const s=~~(this._triangles.length*e.quality);let r=0;const n=this._triangles.length,o=(e,t)=>{setTimeout((()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e{const t=~~((this._triangles.length/2+e)%this._triangles.length),s=this._triangles[t];if(s&&!(s.error[3]>i||s.deleted||s.isDirty))for(let e=0;e<3;++e)if(s.error[e]{-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))})),h.length%2!=0)continue;n.q=o.q.add(n.q),n.updatePosition(a);const c=this._references.length;r=this._updateTriangles(n,n,t,r),r=this._updateTriangles(n,o,i,r);const u=this._references.length-c;if(u<=n.triangleCount){if(u)for(let e=0;en-r<=s))}),0)};Ns.Run(this.decimationIterations,(e=>{n-r<=s?e.breakLoop():o(e.index,(()=>{e.executeNext()}))}),(()=>{setTimeout((()=>{this._reconstructMesh(t),i()}),0)}))}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const s=this._mesh.getVerticesData(er.PositionKind),r=this._mesh.getIndices(),n=this._mesh.subMeshes[e],o=e=>{if(i)for(let t=0;t{if(!s)return;const t=e+n.verticesStart,i=_e.FromArray(s,3*t),r=o(i)||new CS(i,this._vertices.length);r.originalOffsets.push(t),r.id===this._vertices.length&&this._vertices.push(r),a.push(r.id)}),(()=>{Ns.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,(e=>{if(!r)return;const t=3*(n.indexStart/3+e),i=r[t+0],s=r[t+1],o=r[t+2],l=this._vertices[a[i-n.verticesStart]],h=this._vertices[a[s-n.verticesStart]],c=this._vertices[a[o-n.verticesStart]],u=new SS([l,h,c]);u.originalOffset=t,this._triangles.push(u)}),(()=>{this._init(t)}))}))}_init(e){Ns.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];t.normal=_e.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(ES.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-_e.Dot(t.normal,t._vertices[0].position)))}),(()=>{Ns.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])}),(()=>{e()}))}))}_reconstructMesh(e){const t=[];let i,s,r;for(i=0;i{n.push(e.position.x),n.push(e.position.y),n.push(e.position.z),h&&h.length&&(o.push(h[3*t]),o.push(h[3*t+1]),o.push(h[3*t+2])),c&&c.length&&(a.push(c[2*t]),a.push(c[2*t+1])),u&&u.length&&(l.push(u[4*t]),l.push(u[4*t+1]),l.push(u[4*t+2]),l.push(u[4*t+3])),++d}))}const _=this._reconstructedMesh.getTotalIndices(),p=this._reconstructedMesh.getTotalVertices(),f=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(i=0;i{const t=g[s.originalOffset+e];let i=s._vertices[e].originalOffsets.indexOf(t);i<0&&(i=0),m.push(s._vertices[e].id+i+p)}));this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(er.PositionKind,n),o.length>0&&this._reconstructedMesh.setVerticesData(er.NormalKind,o),a.length>0&&this._reconstructedMesh.setVerticesData(er.UVKind,a),l.length>0&&this._reconstructedMesh.setVerticesData(er.ColorKind,l);const v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],f.forEach((e=>{Gn.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())})),Gn.AddToMesh(v.materialIndex,p,d,_,3*t.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new ha(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,s,r){for(let n=0;n.999)return!0;const d=_e.Cross(c,u).normalize();if(s[n]=!1,_e.Dot(d,o.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,s){let r=s;for(let s=0;sMS.Parse(e,t);class MS extends RS{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(My.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[],this._points.forEach((t=>{for(let i=0;i{i+=2*e.length,s+=2*(e.length-3),r+=4*e.length/3,n+=8*e.length/3}));const o=new Float32Array(i),a=i>65535?new Uint32Array(s):new Uint16Array(s),l=new Float32Array(r),h=new Float32Array(n),c=new Float32Array(n);let u=0,d=0,_=0,p=0,f=0;e.forEach((e=>{const i=My.GetLineLengthArray(e),s=i[i.length-1];for(let i=0,s=0;s>1]/s;if(this._options.uvs)for(let e=0;eOS.Parse(e,t);class OS extends RS{constructor(e,t,i,s){if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=i.widths??[],this._ribbonWidths=[],this._pathsOptions=s??[],i.points&&this.addPoints(My.ConvertPoints(i.points),i,!!s)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t{const r=OS._ConvertToRibbonPath(e,n.ribbonOptions,this._scene.useRightHandedSystem,i?i[t]:i);s=this._preprocess(r,s,n)}))}}this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:new Array(e).fill(t)}static _CreateRibbonVertexData(e,t){const i=e.length;if(i<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";const s=[],r=[],n=e[0];for(let t=0;t2)for(let e=0;e0&&(o[0]+=1,o[1]+=1),r.push(o[1]+(e%2!=0?i:0),o[0],o[2]),a&&r.push(o[0],o[1]+(e%2!=0?i:0),o[2])}else for(let e=0;ee.y&&e.x>e.z?i?OS._RightHandedForwardReadOnlyQuaternion:OS._LeftHandedForwardReadOnlyQuaternion:OS._LeftReadOnlyQuaternion),l=e.normalize()}h=l.multiplyByFloats(o,o,o),r.push(c.add(h)),n.push(c.subtract(h))}s||(r.push(a[a.length-1].add(h)),n.push(a[a.length-1].subtract(h)))}return[r,n]}static _GetDirectionFromPoints(e,t,i){return e.x!==t.x||i&&1!==i?.x?e.y===t.y?OS.DIRECTION_XZ:e.z===t.z?OS.DIRECTION_XY:OS.DIRECTION_XZ:OS.DIRECTION_YZ}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),s={},r=[];Ye.DeepCopy(this._pathsOptions,r,void 0,void 0,!0),Ye.DeepCopy(i,s,["instance"],void 0,!0);const n=new OS(e,this._scene,s,r);return t&&(n.parent=t),n.material=this.material,n}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions(),e.pathsOptions=this._pathsOptions}static Parse(e,t){const i=e.lineOptions,s=e.name,r=e.pathOptions;return new OS(s,t,i,r)}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){const t=e.length;this._vSegmentLengths=new Array(t),this._vTotalLengths=new Array(t);let i=0;for(let s=0;s0){if(t.length%2!=0&&t.push(s),i===uS.WIDTH_DISTRIBUTION_START_END){const e=Math.floor(t.length/2);for(let i=0,s=0;i0){if(i===cS.COLOR_DISTRIBUTION_START_END){const e=Math.floor(t.length/2);for(let i=0;i=this._thinInstanceDataStorage.instancesCount)return!1;const s=this._thinInstanceDataStorage.matrixData;return t.copyToArray(s,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},ha.prototype.thinInstanceSetAttributeAt=function(e,t,i,s=!0){return e===er.ColorKind&&(e=er.ColorInstanceKind),!(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[e]||t>=this._thinInstanceDataStorage.instancesCount||(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),s&&this.thinInstanceBufferUpdated(e),0))},Object.defineProperty(ha.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){const t=this._thinInstanceDataStorage.matrixData??this.source?._thinInstanceDataStorage.matrixData;e<=(t?t.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),ha.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!0){const s=new Js(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(s.createVertexBuffer(e+t,4*t,4));return s},ha.prototype.thinInstanceSetBuffer=function(e,t,i=0,s=!0){i=i||16,"matrix"===e?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*i,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/i,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,s),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,s))):(e===er.ColorKind&&(e=er.ColorInstanceKind),null===t?this._userThinInstanceBuffersStorage?.data[e]&&(this.removeVerticesData(e),delete this._userThinInstanceBuffersStorage.data[e],delete this._userThinInstanceBuffersStorage.strides[e],delete this._userThinInstanceBuffersStorage.sizes[e],delete this._userThinInstanceBuffersStorage.vertexBuffers[e]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[e]=t,this._userThinInstanceBuffersStorage.strides[e]=i,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new er(this.getEngine(),t,e,!s,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},ha.prototype.thinInstanceBufferUpdated=function(e){"matrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.matrixBuffer?.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):"previousMatrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.previousMatrixBuffer?.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(e===er.ColorKind&&(e=er.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[e].isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0)))},ha.prototype.thinInstancePartialBufferUpdate=function(e,t,i){"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===er.ColorKind&&(e=er.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},ha.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;te.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}_resetCounters(){this._callCount=0,this._executionCount=0}get callCount(){return this._callCount}get executionCount(){return this._executionCount}getConnectedValue(e){return this.isConnected?this._connectedPoint?._storedFunction?(this._connectedPoint._callCount++,this._connectedPoint._executionCount++,this._connectedPoint._storedFunction(e)):(this._connectedPoint._callCount++,this._connectedPoint._executionCount=1,this._connectedPoint._storedValue):(this._callCount++,this._executionCount=1,this.value)}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=new Array,this._type=dS.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new K,this.onDisconnectionObservable=new K,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._callCount=0,this._executionCount=0,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===_S.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==dS.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?_S.Compatible:_S.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return _S.TypeIncompatible;let s=i,r=t;return this.direction===pS.Input&&(s=t,r=i),s.isAnAncestorOf(r)?_S.HierarchyIssue:_S.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear()}}class kS{get buildExecutionTime(){return this._buildExecutionTime}get inputs(){return this._inputs}get outputs(){return this._outputs}get name(){return this._name}set name(e){this._name=e}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get isDebug(){return this._isDebug}get isUnique(){return this._isUnique}getClassName(){return"NodeGeometryBlock"}_inputRename(e){return e}_outputRename(e){return e}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){if(i.ownerBlock===e)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints)if(i.ownerBlock.isAnAncestorOfType(e))return!0;return!1}getDescendantOfPredicate(e){if(e(this))return this;for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){const t=i.ownerBlock.getDescendantOfPredicate(e);if(t)return t}return null}constructor(e){this._name="",this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._isDebug=!1,this._isUnique=!1,this._buildExecutionTime=0,this.onBuildObservable=new K,this._inputs=new Array,this._outputs=new Array,this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this.uniqueId=Lr.UniqueId}registerInput(e,t,i=!1,s,r,n){const o=new BS(e,this,pS.Input);return o.type=t,o.isOptional=i,o.defaultValue=s,o.value=s,o.valueMin=r,o.valueMax=n,this._inputs.push(o),this}registerOutput(e,t,i){return(i=i??new BS(e,this,pS.Output)).type=t,this._outputs.push(i),this}_buildBlock(e){}_customBuildStep(e){}build(e){if(this._buildId===e.buildId)return!0;if(this._outputs.length>0){if(!this._outputs.some((e=>e.hasEndpoints))&&!this.isDebug)return!1;this.outputs.forEach((e=>e._resetCounters()))}this._buildId=e.buildId;for(const t of this._inputs){if(!t.connectedPoint){t.isOptional||e.notConnectedNonOptionalInputs.push(t);continue}const i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}this._customBuildStep(e),e.verbose&&Ne.Log(`Building ${this.name} [${this.getClassName()}]`);const t=Wt.Now;this._buildBlock(e),this._buildExecutionTime=Wt.Now-t;for(const t of this._outputs)for(const i of t.endpoints){const t=i.ownerBlock;t&&t.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.visibleOnFrame=this.visibleOnFrame,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach((e=>{const t=this.inputs.find((t=>t.name===e.name));if(t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value))if("number"===e.valueType)t.value=e.value;else{const i=W(e.valueType);i&&(t.value=i.FromArray(e.value))}})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}_dumpPropertiesCode(){return`${this._codeVariableName}.visibleOnFrame = ${this.visibleOnFrame};\n`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}return t}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let s=`\n// ${this.getClassName()}\n`;this.comments&&(s+=`// ${this.comments}\n`);const r=this.getClassName();if("GeometryInputBlock"===r){const e=this.type;s+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${e});\n`}else s+=`var ${this._codeVariableName} = new BABYLON.${r}("${this.name}");\n`;s+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint.ownerBlock;-1===t.indexOf(r)&&(s+=r._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const r of i.endpoints){const i=r.ownerBlock;i&&-1===t.indexOf(i)&&(s+=i._dumpCode(e,t))}return s}clone(){const e=this.serialize(),t=W(e.customType);if(t){const i=new t;return i._deserialize(e),i}return null}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose();this.onBuildObservable.clear()}}Ze([rt("comment")],kS.prototype,"comments",void 0);class VS extends kS{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",dS.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}z("BABYLON.GeometryOutputBlock",VS),function(e){e[e.None=0]="None",e[e.Positions=1]="Positions",e[e.Normals=2]="Normals",e[e.Tangents=3]="Tangents",e[e.UV=4]="UV",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6",e[e.Colors=10]="Colors",e[e.VertexID=11]="VertexID",e[e.FaceID=12]="FaceID",e[e.GeometryID=13]="GeometryID",e[e.CollectionID=14]="CollectionID",e[e.LoopID=15]="LoopID",e[e.InstanceID=16]="InstanceID"}(fS||(fS={}));class US{constructor(){this._rotationMatrix=new me,this._scalingMatrix=new me,this._positionMatrix=new me,this._scalingRotationMatrix=new me,this._transformMatrix=new me,this._tempVector3=new _e,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}get geometryContext(){return this._geometryContext}get executionContext(){return this._executionContext}get instancingContext(){return this._instancingContext}pushGeometryContext(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)}pushExecutionContext(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)}pushInstancingContext(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)}restoreGeometryContext(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null}restoreExecutionContext(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null}restoreInstancingContext(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null}getContextualValue(e,t=!1){if(!this.executionContext)return t||this.noContextualData.push(e),null;const i=this.executionContext.getExecutionIndex();switch(e){case fS.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():this.geometryContext&&this.geometryContext.positions?_e.FromArray(this.geometryContext.positions,3*i):_e.Zero();case fS.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():this.geometryContext&&this.geometryContext.normals?_e.FromArray(this.geometryContext.normals,3*i):_e.Zero();case fS.Colors:return this.geometryContext&&this.geometryContext.colors?pe.FromArray(this.geometryContext.colors,4*i):pe.Zero();case fS.Tangents:return this.geometryContext&&this.geometryContext.tangents?pe.FromArray(this.geometryContext.tangents,4*i):pe.Zero();case fS.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():this.geometryContext&&this.geometryContext.uvs?de.FromArray(this.geometryContext.uvs,2*i):de.Zero();case fS.UV2:return this.geometryContext&&this.geometryContext.uvs2?de.FromArray(this.geometryContext.uvs2,2*i):de.Zero();case fS.UV3:return this.geometryContext&&this.geometryContext.uvs3?de.FromArray(this.geometryContext.uvs3,2*i):de.Zero();case fS.UV4:return this.geometryContext&&this.geometryContext.uvs4?de.FromArray(this.geometryContext.uvs4,2*i):de.Zero();case fS.UV5:return this.geometryContext&&this.geometryContext.uvs5?de.FromArray(this.geometryContext.uvs5,2*i):de.Zero();case fS.UV6:return this.geometryContext&&this.geometryContext.uvs6?de.FromArray(this.geometryContext.uvs6,2*i):de.Zero();case fS.VertexID:return i;case fS.FaceID:return this.executionContext.getExecutionFaceIndex();case fS.LoopID:return this.executionContext.getExecutionLoopIndex();case fS.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case fS.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case fS.CollectionID:return this.geometryContext&&this.geometryContext.metadata&&this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){const i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case dS.Vector2:return new de(i,i);case dS.Vector3:return new _e(i,i,i);case dS.Vector4:return new pe(i,i,i,i)}return null}adaptInput(e,t,i){if(!e.isConnected)return e.value||i;const s=e.getConnectedValue(this);if(e._connectedPoint?.type===t)return s;switch(t){case dS.Vector2:return new de(s,s);case dS.Vector3:return new _e(s,s,s);case dS.Vector4:return new pe(s,s,s,s)}return null}emitErrors(){let e="";for(const t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional.\n`;for(const t of this.noContextualData)e+=`Contextual input ${fS[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block).\n`;if(e)throw"Build of NodeGeometry failed:\n"+e}_instantiate(e,t,i,s,r){me.ScalingToRef(s.x,s.y,s.z,this._scalingMatrix),me.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),me.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let t=0;te.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${fS[this._contextualSource]};\n`;const t=[];let i="";switch(this.type){case dS.Float:case dS.Int:i=`${this.value}`;break;case dS.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case dS.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case dS.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`}return t.push(`${e}.value = ${i}`),this.type!==dS.Float&&this.type!==dS.Int||t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}serialize(){const e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,null===this._storedValue||this.isContextual||(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=W(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}z("BABYLON.GeometryInputBlock",GS);class zS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",dS.Float,!0,1),this.registerInput("width",dS.Float,!0,0),this.registerInput("height",dS.Float,!0,0),this.registerInput("depth",dS.Float,!0,0),this.registerInput("subdivisions",dS.Int,!0,1),this.registerInput("subdivisionsX",dS.Int,!0,0),this.registerInput("subdivisionsY",dS.Int,!0,0),this.registerInput("subdivisionsZ",dS.Int,!0,0),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){const e=new GS("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){const e=new GS("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new GS("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new GS("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){const t={},i=e=>{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.depth=this.depth.getConnectedValue(e);const i=this.subdivisions.getConnectedValue(e),s=this.subdivisionsX.getConnectedValue(e),r=this.subdivisionsY.getConnectedValue(e),n=this.subdivisionsZ.getConnectedValue(e);return i&&(t.segments=i),s&&(t.widthSegments=s),r&&(t.heightSegments=r),n&&(t.depthSegments=n),hd(t)};if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],zS.prototype,"evaluateContext",void 0),z("BABYLON.BoxBlock",zS);class WS{_getGlobalNodeGeometryEditor(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=WS._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new K,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return Ds.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise((t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),void 0===this.BJSNODEGEOMETRYEDITOR){const i=e&&e.editorURL?e.editorURL:WS.EditorURL;Ds.LoadBabylonScript(i,(()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}else this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}_createNodeEditor(e){const t={nodeGeometry:this,...e};this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";const s=Wt.Now;this._initializeBlock(this.outputBlock,i);const r=new US;r.buildId=this._buildId,r.verbose=e,this.outputBlock.build(r),t&&(this._buildId=WS._BuildIdGenerator++),this._buildExecutionTime=Wt.Now-s,r.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=r.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;const i=new ha(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),!!this._vertexData&&(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e)}_initializeBlock(e,t=!0){e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._initializeBlock(i,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();const i={};for(const t of e.blocks){const e=W(t.customType);if(e){const s=new e;s._deserialize(t),i[t.id]=s,this.attachedBlocks.push(s)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,s=t._tempEntryPointUniqueId;if(s){const e=i[s];e&&e.attachToEndpoint(t)}}for(let s=0;se.targetConnectionName))&&!t||this._restoreConnections(n,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const s=e.locations||e.editorData.locations;for(const e of s)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&s.concat(this.editorData.locations),e.locations?this.editorData={locations:s}:(this.editorData=e.editorData,this.editorData.locations=s);const r=[];for(const e in i)r[e]=i[e].uniqueId;this.editorData.map=r}this.comment=e.comment}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n)for(const o of r.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==s.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;s.connectTo(e,!0),this._restoreConnections(n,t,i)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let s=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}");\n`;for(const r of t)r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));return this.outputBlock&&(e=[],s+="// Connections\n",s+=this.outputBlock._dumpCodeForOutputConnections(e),s+="// Output nodes\n",s+=`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName};\n`,s+="nodeGeometry.build();\n"),s}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new zS("Box");e.autoConfigure();const t=new VS("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=St.Clone((()=>new WS(e)),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){const t=e?{}:St.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}dispose(){for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){const t=new WS(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=St.Parse((()=>new WS(e.name)),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return"_BLANK"===e?Promise.resolve(WS.CreateDefault("blank")):new Promise(((s,r)=>{const n=new Pt;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(o.nodeGeometry);t||(t=St.Parse((()=>new WS(e)),a,null)),t.parseSerializedObject(a),t.snippetId=e;try{i||t.build(),s(t)}catch(e){r(e)}}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}WS._BuildIdGenerator=0,WS.EditorURL=`${Ds._DefaultCdnUrl}/v${oo.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`,WS.SnippetUrl="https://snippet.babylonjs.com",Ze([rt()],WS.prototype,"name",void 0),Ze([rt("comment")],WS.prototype,"comment",void 0);class HS extends kS{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=J,this.registerInput("geometry",dS.Geometry),this.registerOutput("output",dS.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e),i=[],s={};for(let e=0;es[e])),r};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`;return e+=`${this._codeVariableName}.epsilon = ${this.epsilon};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],HS.prototype,"evaluateContext",void 0),Ze([Cl("Epsilon",ul.Float,"ADVANCED",{notifiers:{rebuild:!0}})],HS.prototype,"epsilon",void 0),z("BABYLON.GeometryOptimizeBlock",HS);class XS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",dS.Float,!0,1),this.registerInput("width",dS.Float,!0,0),this.registerInput("height",dS.Float,!0,0),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){const e=new GS("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){const e=new GS("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new GS("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){const t={},i=e=>(t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),za(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],XS.prototype,"evaluateContext",void 0),z("BABYLON.PlaneBlock",XS);class YS extends kS{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.reverseWindingOrder=!1,this.serializedCachedData=!1,this.registerOutput("geometry",dS.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}cleanData(){this._mesh=null,this._cachedVertexData=null}_buildBlock(){if(!this._mesh)return void(this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null);const e=Wn.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;te.clone()}serialize(){const e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=Wn.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(e.cachedVertexData=this._cachedVertexData.serialize())),e.reverseWindingOrder=this.reverseWindingOrder,e}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=Wn.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}Ze([Cl("Serialize cached data",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],YS.prototype,"serializedCachedData",void 0),z("BABYLON.MeshBlock",YS);class QS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",dS.Float,!0,1),this.registerInput("radiusX",dS.Float,!0,0),this.registerInput("radiusY",dS.Float,!0,0),this.registerInput("radiusZ",dS.Float,!0,0),this.registerInput("subdivisions",dS.Int,!0,4),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new GS("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.radiusX=this.radiusX.getConnectedValue(e),t.radiusY=this.radiusY.getConnectedValue(e),t.radiusZ=this.radiusZ.getConnectedValue(e),ch(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],QS.prototype,"evaluateContext",void 0),z("BABYLON.IcoSphereBlock",QS);class jS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",dS.Int,!0,32),this.registerInput("diameter",dS.Float,!0,1),this.registerInput("diameterX",dS.Float,!0,0),this.registerInput("diameterY",dS.Float,!0,0),this.registerInput("diameterZ",dS.Float,!0,0),this.registerInput("arc",dS.Float,!0,1),this.registerInput("slice",dS.Float,!0,1),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new GS("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.segments=this.segments.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterX=this.diameterX.getConnectedValue(e),t.diameterY=this.diameterY.getConnectedValue(e),t.diameterZ=this.diameterZ.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),t.slice=this.slice.getConnectedValue(e),dd(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],jS.prototype,"evaluateContext",void 0),z("BABYLON.SphereBlock",jS);class KS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",dS.Float,!0,1),this.registerInput("height",dS.Float,!0,1),this.registerInput("subdivisions",dS.Int,!0,1),this.registerInput("subdivisionsX",dS.Int,!0,0),this.registerInput("subdivisionsY",dS.Int,!0,0),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){const e=new GS("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new GS("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.subdivisionsX=this.subdivisionsX.getConnectedValue(e),t.subdivisionsY=this.subdivisionsY.getConnectedValue(e),Eu(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],KS.prototype,"evaluateContext",void 0),z("BABYLON.GridBlock",KS);class $S extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",dS.Float,!0,1),this.registerInput("thickness",dS.Float,!0,.5),this.registerInput("tessellation",dS.Int,!0,16),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new GS("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.thickness=this.thickness.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),Du(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],$S.prototype,"evaluateContext",void 0),z("BABYLON.TorusBlock",$S);class qS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",dS.Float,!0,25),this.registerInput("diameter",dS.Float,!0,1),this.registerInput("diameterTop",dS.Float,!0,-1),this.registerInput("diameterBottom",dS.Float,!0,-1),this.registerInput("subdivisions",dS.Int,!0,1),this.registerInput("tessellation",dS.Int,!0,24),this.registerInput("arc",dS.Float,!0,1),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new GS("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new GS("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterTop=this.diameterTop.getConnectedValue(e),t.diameterBottom=this.diameterBottom.getConnectedValue(e),-1===t.diameterTop&&(t.diameterTop=t.diameter),-1===t.diameterBottom&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),Ku(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],qS.prototype,"evaluateContext",void 0),z("BABYLON.CylinderBlock",qS);class ZS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",dS.Float,!0,1),this.registerInput("radius",dS.Float,!0,.25),this.registerInput("tessellation",dS.Int,!0,16),this.registerInput("subdivisions",dS.Int,!0,2),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){const e=new GS("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new GS("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),fd(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],ZS.prototype,"evaluateContext",void 0),z("BABYLON.CapsuleBlock",ZS);class JS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",dS.Float,!0,.5),this.registerInput("tessellation",dS.Int,!0,64),this.registerInput("arc",dS.Float,!0,1),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new GS("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),Td(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],JS.prototype,"evaluateContext",void 0),z("BABYLON.DiscBlock",JS);class eC extends kS{constructor(e){super(e),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}}z("BABYLON.NullBlock",eC);class tC extends kS{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",dS.Geometry),this.registerInput("positions",dS.Vector3),this.registerOutput("output",dS.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.normals.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.normals||(this._vertexData.normals=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.uvs.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);const t=[],i=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.colors.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.colors||(this._vertexData.colors=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.tangents.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.tangents||(this._vertexData.tangents=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndexthis._updateInputOutputTypes())),this.left.onDisconnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onConnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onDisconnectionObservable.add((()=>this._updateInputOutputTypes()))]}getClassName(){return"MathBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){let e;const t=this.left,i=this.right;if(!t.isConnected||!i.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const s=t.type===dS.Float||t.type===dS.Int,r=i.type===dS.Float||i.type===dS.Int,n=s&&r;switch(this.operation){case mS.Add:e=n?e=>t.getConnectedValue(e)+i.getConnectedValue(e):s?e=>e.adapt(t,i.type).add(i.getConnectedValue(e)):e=>t.getConnectedValue(e).add(e.adapt(i,t.type));break;case mS.Subtract:e=n?e=>t.getConnectedValue(e)-i.getConnectedValue(e):s?e=>e.adapt(t,i.type).subtract(i.getConnectedValue(e)):e=>t.getConnectedValue(e).subtract(e.adapt(i,t.type));break;case mS.Multiply:e=n?e=>t.getConnectedValue(e)*i.getConnectedValue(e):s?e=>e.adapt(t,i.type).multiply(i.getConnectedValue(e)):e=>t.getConnectedValue(e).multiply(e.adapt(i,t.type));break;case mS.Divide:e=n?e=>t.getConnectedValue(e)/i.getConnectedValue(e):s?e=>e.adapt(t,i.type).divide(i.getConnectedValue(e)):e=>t.getConnectedValue(e).divide(e.adapt(i,t.type));break;case mS.Min:if(n)e=e=>Math.min(t.getConnectedValue(e),i.getConnectedValue(e));else{const[r,n]=s?[i,t]:[t,i];switch(r.type){case dS.Vector2:e=e=>de.Minimize(r.getConnectedValue(e),e.adapt(n,r.type));break;case dS.Vector3:e=e=>_e.Minimize(r.getConnectedValue(e),e.adapt(n,r.type));break;case dS.Vector4:e=e=>pe.Minimize(r.getConnectedValue(e),e.adapt(n,r.type))}}break;case mS.Max:if(!n){const[r,n]=s?[i,t]:[t,i];switch(r.type){case dS.Vector2:e=e=>de.Maximize(r.getConnectedValue(e),e.adapt(n,r.type));break;case dS.Vector3:e=e=>_e.Maximize(r.getConnectedValue(e),e.adapt(n,r.type));break;case dS.Vector4:e=e=>pe.Maximize(r.getConnectedValue(e),e.adapt(n,r.type))}break}e=e=>Math.max(t.getConnectedValue(e),i.getConnectedValue(e))}this.output._storedFunction=i=>t.type===dS.Int?0|e(i):e(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${mS[this.operation]};\n`}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===dS.Int||this.left.type===dS.Float&&this.right.type!==dS.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(const[e,t]of[[this.left,this.right],[this.right,this.left]])e.acceptedConnectionPointTypes=[dS.Int,dS.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==dS.Int&&t.type!==dS.Float||e.acceptedConnectionPointTypes.push(dS.Vector2,dS.Vector3,dS.Vector4))}dispose(){super.dispose(),this._connectionObservers.forEach((e=>e.remove())),this._connectionObservers.length=0}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}}Ze([Cl("Operation",ul.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:mS.Add},{label:"Subtract",value:mS.Subtract},{label:"Multiply",value:mS.Multiply},{label:"Divide",value:mS.Divide},{label:"Max",value:mS.Max},{label:"Min",value:mS.Min}]})],oC.prototype,"operation",void 0),z("BABYLON.MathBlock",oC);class aC extends kS{constructor(e){super(e),this.registerInput("value",dS.AutoDetect),this.registerInput("fromMin",dS.Float,!0,0),this.registerInput("fromMax",dS.Float,!0,1),this.registerInput("toMin",dS.Float,!0,0),this.registerInput("toMax",dS.Float,!0,1),this.registerOutput("output",dS.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(dS.Vector2),this._inputs[0].excludedConnectionPointTypes.push(dS.Vector3),this._inputs[0].excludedConnectionPointTypes.push(dS.Vector4),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),s=this.fromMax.getConnectedValue(e),r=this.toMin.getConnectedValue(e),n=(t-i)/(s-i)*(this.toMax.getConnectedValue(e)-r)+r;return this.output.type===dS.Int?Math.floor(n):n}}}z("BABYLON.MapRangeBlock",aC),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(gS||(gS={}));class lC extends kS{constructor(e){super(e),this.test=gS.Equal,this.registerInput("left",dS.Float),this.registerInput("right",dS.Float,!0,0),this.registerInput("ifTrue",dS.AutoDetect,!0,1),this.registerInput("ifFalse",dS.AutoDetect,!0,0),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=dS.Float,this._inputs[0].acceptedConnectionPointTypes.push(dS.Int),this._inputs[1].acceptedConnectionPointTypes.push(dS.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);let s=!1;switch(this.test){case gS.Equal:s=be.WithinEpsilon(t,i,J);break;case gS.NotEqual:s=t!==i;break;case gS.LessThan:s=ti;break;case gS.LessOrEqual:s=t<=i;break;case gS.GreaterOrEqual:s=t>=i;break;case gS.Xor:s=!!t&&!i||!t&&!!i;break;case gS.Or:s=!!t||!!i;break;case gS.And:s=!!t&&!!i}return s};this.output._storedFunction=t=>e(t)?this.ifTrue.getConnectedValue(t):this.ifFalse.getConnectedValue(t)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${gS[this.test]};\n`}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}Ze([Cl("Test",ul.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:gS.Equal},{label:"NotEqual",value:gS.NotEqual},{label:"LessThan",value:gS.LessThan},{label:"GreaterThan",value:gS.GreaterThan},{label:"LessOrEqual",value:gS.LessOrEqual},{label:"GreaterOrEqual",value:gS.GreaterOrEqual},{label:"Xor",value:gS.Xor},{label:"Or",value:gS.Or},{label:"And",value:gS.And}]})],lC.prototype,"test",void 0),z("BABYLON.ConditionBlock",lC),function(e){e[e.None=0]="None",e[e.LoopID=1]="LoopID",e[e.InstanceID=2]="InstanceID"}(vS||(vS={}));class hC extends kS{constructor(e){super(e),this._currentLockId=-1,this.lockMode=vS.None,this.registerInput("min",dS.AutoDetect),this.registerInput("max",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture),this._inputs[1].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[1].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[1].excludedConnectionPointTypes.push(dS.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){const e=new GS("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new GS("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case dS.Int:case dS.Float:e=e=>{const t=this.min.getConnectedValue(e)||0,i=this.max.getConnectedValue(e)||0;return t+Math.random()*(i-t)};break;case dS.Vector2:e=e=>{const t=this.min.getConnectedValue(e)||de.Zero(),i=this.max.getConnectedValue(e)||de.Zero();return new de(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y))};break;case dS.Vector3:e=e=>{const t=this.min.getConnectedValue(e)||_e.Zero(),i=this.max.getConnectedValue(e)||_e.Zero();return new _e(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z))};break;case dS.Vector4:e=e=>{const t=this.min.getConnectedValue(e)||pe.Zero(),i=this.max.getConnectedValue(e)||pe.Zero();return new pe(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z),t.w+Math.random()*(i.w-t.w))}}this.lockMode!==vS.None&&e?this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case vS.InstanceID:i=t.getContextualValue(fS.InstanceID,!0)||0;break;case vS.LoopID:i=t.getContextualValue(fS.LoopID,!0)||0}return this._currentLockId===i&&this.lockMode!==vS.None||(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}:this.output._storedFunction=e}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${vS[this.lockMode]};\n`}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}Ze([Cl("LockMode",ul.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:vS.None},{label:"LoopID",value:vS.LoopID},{label:"InstanceID",value:vS.InstanceID}]})],hC.prototype,"lockMode",void 0),z("BABYLON.RandomBlock",hC);class cC extends kS{constructor(e){super(e),this.registerInput("offset",dS.Vector3,!0,_e.Zero()),this.registerInput("scale",dS.Float,!0,1),this.registerInput("octaves",dS.Float,!0,2,0,16),this.registerInput("roughness",dS.Float,!0,.5,0,1),this.registerOutput("output",dS.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return 0!==t?-e:e}_noiseGrad(e,t,i,s){const r=15&e,n=r<8?t:i,o=r<4?i:12===r||14==r?t:s;return this._negateIf(n,r&n)+this._negateIf(o,2&r)}_fade(e){return e*e*e*(e*(6*e-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let s,r,n;return s=r=n=3735928584,n+=i,r+=t,s+=e,n^=r,n-=this._hashBitRotate(r,14),s^=n,s-=this._hashBitRotate(n,11),r^=s,r-=this._hashBitRotate(s,25),n^=r,n-=this._hashBitRotate(r,16),s^=n,s-=this._hashBitRotate(n,4),r^=s,r-=this._hashBitRotate(s,14),n^=r,n-=this._hashBitRotate(r,24),n}_mix(e,t,i,s,r,n,o,a,l,h,c){const u=1-l,d=1-h;return(1-c)*(d*(e*u+t*l)+h*(i*u+s*l))+c*(d*(r*u+n*l)+h*(o*u+a*l))}_perlinNoise(e){const t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),s=(0|e.z)-(e.z<0?1:0),r=e.x-t,n=e.y-i,o=e.z-s,a=this._fade(r),l=this._fade(n),h=this._fade(o);return this._mix(this._noiseGrad(this._hash(t,i,s),r,n,o),this._noiseGrad(this._hash(t+1,i,s),r-1,n,o),this._noiseGrad(this._hash(t,i+1,s),r,n-1,o),this._noiseGrad(this._hash(t+1,i+1,s),r-1,n-1,o),this._noiseGrad(this._hash(t,i,s+1),r,n,o-1),this._noiseGrad(this._hash(t+1,i,s+1),r-1,n,o-1),this._noiseGrad(this._hash(t,i+1,s+1),r,n-1,o-1),this._noiseGrad(this._hash(t+1,i+1,s+1),r-1,n-1,o-1),a,l,h)}_perlinSigned(e){return.982*this._perlinNoise(e)}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,s,r){const n=new _e(i.x*r+s.x,i.y*r+s.y,i.z*r+s.z);let o=1,a=1,l=0,h=0;const c=0|(e=be.Clamp(e,0,15));for(let e=0;e<=c;e++)h+=this._perlin(n.scale(o))*a,l+=a,a*=be.Clamp(t,0,1),o*=2;const u=e-Math.floor(e);if(0==u)return h/l;let d=h+this._perlin(n.scale(o))*a;return h/=l,d/=l+a,(1-u)*h+u*d}_buildBlock(){this.output._storedFunction=e=>{const t=e.getContextualValue(fS.Positions),i=this.octaves.getConnectedValue(e),s=this.roughness.getConnectedValue(e),r=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,s,t,r,n)}}}z("BABYLON.NoiseBlock",cC);class uC extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",dS.Geometry),this.registerInput("geometry1",dS.Geometry,!0),this.registerInput("geometry2",dS.Geometry,!0),this.registerInput("geometry3",dS.Geometry,!0),this.registerInput("geometry4",dS.Geometry,!0),this.registerOutput("output",dS.Geometry)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{let t=this.geometry0.getConnectedValue(e);const i=[];if(!t)return null;if(t=t.clone(),this.geometry1.isConnected){const t=this.geometry1.getConnectedValue(e);t&&i.push(t)}if(this.geometry2.isConnected){const t=this.geometry2.getConnectedValue(e);t&&i.push(t)}if(this.geometry3.isConnected){const t=this.geometry3.getConnectedValue(e);t&&i.push(t)}if(this.geometry4.isConnected){const t=this.geometry4.getConnectedValue(e);t&&i.push(t)}return i.length&&t&&(t=t.merge(i,!0,!1,!0,!0)),t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],uC.prototype,"evaluateContext",void 0),z("BABYLON.MergeGeometryBlock",uC);class dC extends kS{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",dS.Geometry,!0),this.registerInput("geometry1",dS.Geometry,!0),this.registerInput("geometry2",dS.Geometry,!0),this.registerInput("geometry3",dS.Geometry,!0),this.registerInput("geometry4",dS.Geometry,!0),this.registerInput("geometry5",dS.Geometry,!0),this.registerInput("geometry6",dS.Geometry,!0),this.registerInput("geometry7",dS.Geometry,!0),this.registerInput("geometry8",dS.Geometry,!0),this.registerInput("geometry9",dS.Geometry,!0),this.registerOutput("output",dS.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,s){if(e.isConnected){const r=e.getConnectedValue(t);if(!r)return;r.metadata=r.metadata||{},r.metadata.collectionId=i,s.push(r)}}_buildBlock(e){const t=e=>{const t=[];return this._storeGeometry(this.geometry0,e,0,t),this._storeGeometry(this.geometry1,e,1,t),this._storeGeometry(this.geometry2,e,2,t),this._storeGeometry(this.geometry3,e,3,t),this._storeGeometry(this.geometry4,e,4,t),this._storeGeometry(this.geometry5,e,5,t),this._storeGeometry(this.geometry6,e,6,t),this._storeGeometry(this.geometry7,e,7,t),this._storeGeometry(this.geometry8,e,8,t),this._storeGeometry(this.geometry9,e,9,t),t.length?t[Math.round(Math.random()*(t.length-1))]:null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],dC.prototype,"evaluateContext",void 0),z("BABYLON.GeometryCollectionBlock",dC);class _C extends kS{constructor(e){super(e),this.registerInput("input",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];t._storedFunction=e=>i.getConnectedValue(e)}}z("BABYLON.GeometryElbowBlock",_C);class pC extends kS{constructor(e){super(e),this.registerInput("geometry",dS.Geometry),this.registerOutput("output",dS.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),Wn.ComputeNormals(t.positions,t.indices,t.normals),t}}}z("BABYLON.ComputeNormalsBlock",pC);class fC extends kS{constructor(e){super(e),this.registerInput("xyzw ",dS.Vector4,!0),this.registerInput("xyz ",dS.Vector3,!0),this.registerInput("xy ",dS.Vector2,!0),this.registerInput("zw ",dS.Vector2,!0),this.registerInput("x ",dS.Float,!0),this.registerInput("y ",dS.Float,!0),this.registerInput("z ",dS.Float,!0),this.registerInput("w ",dS.Float,!0),this.registerOutput("xyzw",dS.Vector4),this.registerOutput("xyz",dS.Vector3),this.registerOutput("xy",dS.Vector2),this.registerOutput("zw",dS.Vector2),this.registerOutput("x",dS.Float),this.registerOutput("y",dS.Float),this.registerOutput("z",dS.Float),this.registerOutput("w",dS.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);const t=this.xIn,i=this.yIn,s=this.zIn,r=this.wIn,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,c=this.xyzOut,u=this.xyOut,d=this.zwOut,_=this.xOut,p=this.yOut,f=this.zOut,m=this.wOut,g=e=>{if(l.isConnected)return l.getConnectedValue(e);let h=0,c=0,u=0,d=0;if(t.isConnected&&(h=t.getConnectedValue(e)),i.isConnected&&(c=i.getConnectedValue(e)),s.isConnected&&(u=s.getConnectedValue(e)),r.isConnected&&(d=r.getConnectedValue(e)),n.isConnected){const t=n.getConnectedValue(e);t&&(h=t.x,c=t.y)}if(o.isConnected){const t=o.getConnectedValue(e);t&&(u=t.x,d=t.y)}if(a.isConnected){const t=a.getConnectedValue(e);t&&(h=t.x,c=t.y,u=t.z)}return new pe(h,c,u,d)};h._storedFunction=e=>g(e),c._storedFunction=e=>{const t=g(e);return new _e(t.x,t.y,t.z)},u._storedFunction=e=>{const t=g(e);return new de(t.x,t.y)},d._storedFunction=e=>{const t=g(e);return new de(t.z,t.w)},_._storedFunction=e=>g(e).x,p._storedFunction=e=>g(e).y,f._storedFunction=e=>g(e).z,m._storedFunction=e=>g(e).w}}z("BABYLON.VectorConverterBlock",fC);class mC extends kS{constructor(e){super(e),this.registerInput("input",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(dS.Float),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.output._storedFunction=null,this.input.isConnected?this.output._storedFunction=e=>this.input.getConnectedValue(e).normalize():this.output._storedValue=null}}z("BABYLON.NormalizeVectorBlock",mC);class gC extends kS{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",dS.Geometry),this.registerInput("id",dS.Int,!0,0),this.registerOutput("output",dS.Geometry),this.id.acceptedConnectionPointTypes.push(dS.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.geometry.getConnectedValue(e);if(!t||!t.indices||!t.positions)return t;const i=new zn;return i.materialIndex=0|this.id.getConnectedValue(e),i.indexStart=0,i.indexCount=t.indices.length,i.verticesStart=0,i.verticesCount=t.positions.length/3,t.materialInfos=[i],t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],gC.prototype,"evaluateContext",void 0),z("BABYLON.SetMaterialIDBlock",gC),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Round=4]="Round",e[e.Floor=5]="Floor",e[e.Ceiling=6]="Ceiling",e[e.Sqrt=7]="Sqrt",e[e.Log=8]="Log",e[e.Tan=9]="Tan",e[e.ArcTan=10]="ArcTan",e[e.ArcCos=11]="ArcCos",e[e.ArcSin=12]="ArcSin",e[e.Sign=13]="Sign",e[e.Negate=14]="Negate",e[e.OneMinus=15]="OneMinus",e[e.Reciprocal=16]="Reciprocal",e[e.ToDegrees=17]="ToDegrees",e[e.ToRadians=18]="ToRadians",e[e.Fract=19]="Fract",e[e.Exp2=20]="Exp2"}(xS||(xS={}));class vC extends kS{constructor(e){super(e),this.operation=xS.Cos,this.registerInput("input",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case xS.Cos:t=e=>Math.cos(e);break;case xS.Sin:t=e=>Math.sin(e);break;case xS.Abs:t=e=>Math.abs(e);break;case xS.Exp:t=e=>Math.exp(e);break;case xS.Exp2:t=e=>Math.pow(2,e);break;case xS.Round:t=e=>Math.round(e);break;case xS.Floor:t=e=>Math.floor(e);break;case xS.Ceiling:t=e=>Math.ceil(e);break;case xS.Sqrt:t=e=>Math.sqrt(e);break;case xS.Log:t=e=>Math.log(e);break;case xS.Tan:t=e=>Math.tan(e);break;case xS.ArcTan:t=e=>Math.atan(e);break;case xS.ArcCos:t=e=>Math.acos(e);break;case xS.ArcSin:t=e=>Math.asin(e);break;case xS.Sign:t=e=>Math.sign(e);break;case xS.Negate:t=e=>-e;break;case xS.OneMinus:t=e=>1-e;break;case xS.Reciprocal:t=e=>1/e;break;case xS.ToRadians:t=e=>e*Math.PI/180;break;case xS.ToDegrees:t=e=>180*e/Math.PI;break;case xS.Fract:t=e=>e>=0?e-Math.floor(e):e-Math.ceil(e)}if(!t)return this.output._storedFunction=null,void(this.output._storedValue=null);switch(this.input.type){case dS.Int:case dS.Float:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return t(i)};break;case dS.Vector2:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new de(t(i.x),t(i.y))};break;case dS.Vector3:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new _e(t(i.x),t(i.y),t(i.z))};break;case dS.Vector4:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new pe(t(i.x),t(i.y),t(i.z),t(i.w))}}return this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${xS[this.operation]};\n`}}Ze([Cl("Operation",ul.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:xS.Cos},{label:"Sin",value:xS.Sin},{label:"Abs",value:xS.Abs},{label:"Exp",value:xS.Exp},{label:"Exp2",value:xS.Exp2},{label:"Round",value:xS.Round},{label:"Floor",value:xS.Floor},{label:"Ceiling",value:xS.Ceiling},{label:"Sqrt",value:xS.Sqrt},{label:"Log",value:xS.Log},{label:"Tan",value:xS.Tan},{label:"ArcTan",value:xS.ArcTan},{label:"ArcCos",value:xS.ArcCos},{label:"ArcSin",value:xS.ArcSin},{label:"Sign",value:xS.Sign},{label:"Negate",value:xS.Negate},{label:"OneMinus",value:xS.OneMinus},{label:"Reciprocal",value:xS.Reciprocal},{label:"ToDegrees",value:xS.ToDegrees},{label:"ToRadians",value:xS.ToRadians},{label:"Fract",value:xS.Fract}]})],vC.prototype,"operation",void 0),z("BABYLON.GeometryTrigonometryBlock",vC);class xC extends kS{constructor(e){super(e),this._rotationMatrix=new me,this._scalingMatrix=new me,this._translationMatrix=new me,this._scalingRotationMatrix=new me,this._transformMatrix=new me,this.evaluateContext=!0,this.registerInput("value",dS.AutoDetect),this.registerInput("matrix",dS.Matrix,!0),this.registerInput("translation",dS.Vector3,!0,_e.Zero()),this.registerInput("rotation",dS.Vector3,!0,_e.Zero()),this.registerInput("scaling",dS.Vector3,!0,_e.One()),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(dS.Float),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.value.getConnectedValue(e);if(!t)return null;let i;if(this.matrix.isConnected)i=this.matrix.getConnectedValue(e);else{const t=this.scaling.getConnectedValue(e),s=this.rotation.getConnectedValue(e),r=this.translation.getConnectedValue(e);me.ScalingToRef(t.x,t.y,t.z,this._scalingMatrix),me.RotationYawPitchRollToRef(s.y,s.x,s.z,this._rotationMatrix),me.TranslationToRef(r.x,r.y,r.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),i=this._transformMatrix}switch(this.value.type){case dS.Geometry:{const e=t.clone();return e.transform(i),e}case dS.Vector2:return de.Transform(t,i);case dS.Vector3:return _e.TransformCoordinates(t,i);case dS.Vector4:return pe.TransformCoordinates(t,i)}return null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],xC.prototype,"evaluateContext",void 0),z("BABYLON.GeometryTransformBlock",xC);class bC extends kS{constructor(e){super(e),this.registerInput("angle",dS.Float,!1,0),this.registerOutput("matrix",dS.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new GS("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>me.RotationX(this.angle.getConnectedValue(e))}}z("BABYLON.RotationXBlock",bC);class TC extends kS{constructor(e){super(e),this.registerInput("angle",dS.Float,!1,0),this.registerOutput("matrix",dS.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new GS("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>me.RotationY(this.angle.getConnectedValue(e))}}z("BABYLON.RotationYBlock",TC);class yC extends kS{constructor(e){super(e),this.registerInput("angle",dS.Float,!1,0),this.registerOutput("matrix",dS.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new GS("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>me.RotationZ(this.angle.getConnectedValue(e))}}z("BABYLON.RotationZBlock",yC);class SC extends kS{constructor(e){super(e),this.registerInput("scale",dS.Vector3,!1,_e.One()),this.registerOutput("matrix",dS.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new GS("Scale");e.value=new _e(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.scale.getConnectedValue(e);return me.Scaling(t.x,t.y,t.z)}}}z("BABYLON.ScalingBlock",SC);class CC extends kS{constructor(e){super(e),this.registerInput("source",dS.Vector3,!0,_e.Up()),this.registerInput("target",dS.Vector3,!0,_e.Left()),this.registerOutput("matrix",dS.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.source.getConnectedValue(e).clone(),i=this.target.getConnectedValue(e).clone(),s=new me;return t.normalize(),i.normalize(),me.RotationAlignToRef(t,i,s,!0),s}}}z("BABYLON.AlignBlock",CC);class EC extends kS{constructor(e){super(e),this.registerInput("translation",dS.Vector3,!1,_e.Zero()),this.registerOutput("matrix",dS.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new GS("Translation");e.value=new _e(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.translation.getConnectedValue(e);return me.Translation(t.x,t.y,t.z)}}}z("BABYLON.TranslationBlock",EC);class AC extends kS{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",dS.Geometry),this.registerInput("instance",dS.Geometry,!0),this.registerInput("density",dS.Float,!0,1,0,1),this.registerInput("matrix",dS.Matrix,!0),this.registerInput("rotation",dS.Vector3,!0,_e.Zero()),this.registerInput("scaling",dS.Vector3,!0,_e.One()),this.scaling.acceptedConnectionPointTypes.push(dS.Float),this.registerOutput("output",dS.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get density(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected)return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=this._vertexData.positions.length/3;const i=[],s=new _e,r=[];let n=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexr)continue;s.fromArray(n,3*this._currentIndex);const o=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(o,s,t,i)}else{const t=e.adaptInput(this.scaling,dS.Vector3,_e.OneReadOnly),r=this.rotation.getConnectedValue(e)||_e.ZeroReadOnly;e._instantiate(o,s,r,t,i)}this._currentLoopIndex++}if(e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),!i.length)return null;if(1===i.length)this._vertexData=i[0];else{const e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}return this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"};\n`;return e+=`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`,e}serialize(){const e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],AC.prototype,"evaluateContext",void 0),Ze([Cl("Remove duplicated positions",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],AC.prototype,"removeDuplicatedPositions",void 0),z("BABYLON.InstantiateOnVerticesBlock",AC);class PC extends kS{constructor(e){super(e),this._currentPosition=new _e,this._currentUV=new de,this._vertex0=new _e,this._vertex1=new _e,this._vertex2=new _e,this._tempVector0=new _e,this._tempVector1=new _e,this._uv0=new de,this._uv1=new de,this._uv2=new de,this.evaluateContext=!0,this.registerInput("geometry",dS.Geometry),this.registerInput("instance",dS.Geometry,!0),this.registerInput("count",dS.Int,!0,256),this.registerInput("matrix",dS.Matrix,!0),this.registerInput("rotation",dS.Vector3,!0,_e.Zero()),this.registerInput("scaling",dS.Vector3,!0,_e.One()),this.scaling.acceptedConnectionPointTypes.push(dS.Float),this.registerOutput("output",dS.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),_e.Cross(this._tempVector1,this._tempVector0)}getOverrideUVs1ContextualValue(){return this._currentUV}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),s=this._vertexData.indices.length/3,r=i/s;let n=0;const o=[];let a=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=i);l++){let i=Math.random(),s=Math.random();if(i>s){const e=i;i=s,s=e}const l=i,h=s-i,c=1-l-h;if(this._currentPosition.set(l*this._vertex0.x+h*this._vertex1.x+c*this._vertex2.x,l*this._vertex0.y+h*this._vertex1.y+c*this._vertex2.y,l*this._vertex0.z+h*this._vertex1.z+c*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(l*this._uv0.x+h*this._uv1.x+c*this._uv2.x,l*this._uv0.y+h*this._uv1.y+c*this._uv2.y),t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length){n-=r;continue}const u=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(u,this._currentPosition,t,o)}else{const t=e.adaptInput(this.scaling,dS.Vector3,_e.OneReadOnly),i=this.rotation.getConnectedValue(e)||_e.ZeroReadOnly;e._instantiate(u,this._currentPosition,i,t,o)}a++,this._currentLoopIndex++}}if(o.length)if(1===o.length)this._vertexData=o[0];else{const e=o.splice(0,1)[0];this._vertexData=e.merge(o,!0,!1,!0,!0)}return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],PC.prototype,"evaluateContext",void 0),z("BABYLON.InstantiateOnFacesBlock",PC);class IC extends kS{constructor(e){super(e),this._currentPosition=new _e,this._vertex0=new _e,this._vertex1=new _e,this._vertex2=new _e,this.evaluateContext=!0,this.registerInput("geometry",dS.Geometry),this.registerInput("instance",dS.Geometry,!0),this.registerInput("count",dS.Int,!0,256),this.registerInput("matrix",dS.Matrix,!0),this.registerInput("rotation",dS.Vector3,!0,_e.Zero()),this.registerInput("scaling",dS.Vector3,!0,_e.One()),this.scaling.acceptedConnectionPointTypes.push(dS.Float),this.registerOutput("output",dS.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),s=[],r=Vn(this._vertexData.positions,0,this._vertexData.positions.length/3),n=r.minimum,o=r.maximum,a=new _e(1,0,0),l=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let r=0;r0&&h++}if(h%2==0){r--;continue}if(t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length)continue;const c=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(c,this._currentPosition,t,s)}else{const t=e.adaptInput(this.scaling,dS.Vector3,_e.OneReadOnly),i=this.rotation.getConnectedValue(e)||_e.ZeroReadOnly;e._instantiate(c,this._currentPosition,i,t,s)}this._currentLoopIndex++}if(s.length)if(1===s.length)this._vertexData=s[0];else{const e=s.splice(0,1)[0];this._vertexData=e.merge(s,!0,!1,!0,!0)}return e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],IC.prototype,"evaluateContext",void 0),z("BABYLON.InstantiateOnVolumeBlock",IC);class RC extends kS{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",dS.Geometry,!0),this.registerInput("count",dS.Int,!0,1),this.registerOutput("output",dS.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBaseBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get output(){return this._outputs[0]}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],RC.prototype,"evaluateContext",void 0);class MC extends RC{constructor(e){super(e),this.registerInput("matrix",dS.Matrix,!0),this.registerInput("position",dS.Vector3,!0,_e.Zero()),this.registerInput("rotation",dS.Vector3,!0,_e.Zero()),this.registerInput("scaling",dS.Vector3,!0,_e.One()),this.scaling.acceptedConnectionPointTypes.push(dS.Float)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get matrix(){return this._inputs[2]}get position(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}_buildBlock(e){const t=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[];for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],s=me.Identity(),r=_e.Zero(),n=_e.Zero(),o=_e.Zero();for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],s=me.Identity(),r=me.Identity(),n=me.Identity(),o=_e.Zero(),a=_e.Zero(),l=_e.Zero();for(this._currentIndex=0;this._currentIndexthis.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?Math.floor(this.floatIn.getConnectedValue(e)):this.intIn.isConnected?Math.floor(this.intIn.getConnectedValue(e)):0}}z("BABYLON.IntFloatConverterBlock",wC);class NC extends kS{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.log=[];const t=e=>{const t=this.input.getConnectedValue(e);if(null==t)return this.log.push(["null",""]),t;switch(this.input.type){case dS.Vector2:this.log.push([Wy(t,4),t.toString()]);break;case dS.Vector3:this.log.push([Hy(t,4),t.toString()]);break;case dS.Vector4:this.log.push([Xy(t,4),t.toString()]);break;default:this.log.push([t.toString(),t.toString()])}return t};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}z("BABYLON.DebugBlock",NC);class FC extends kS{constructor(e){super(e),this.registerInput("geometry",dS.Geometry),this.registerOutput("output",dS.Geometry),this.registerOutput("id",dS.Int),this.registerOutput("collectionId",dS.Int),this.registerOutput("verticesCount",dS.Int),this.registerOutput("facesCount",dS.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected)return this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,void(this.output._storedFunction=null);this.output._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData),this.id._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}}z("BABYLON.GeometryInfoBlock",FC),function(e){e[e.Spherical=0]="Spherical",e[e.Cylindrical=1]="Cylindrical",e[e.Cubic=2]="Cubic"}(bS||(bS={}));class LC extends kS{constructor(e){super(e),this.mapping=bS.Spherical,this.registerInput("position",dS.Vector3),this.registerInput("normal",dS.Vector3),this.registerInput("center",dS.Vector3,!0,_e.Zero()),this.registerOutput("uv",dS.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get center(){return this._inputs[2]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected)return this.uv._storedFunction=null,void(this.uv._storedValue=null);const e=_e.Zero(),t=t=>{const i=this.position.getConnectedValue(t)||_e.Zero(),s=this.normal.getConnectedValue(t)||_e.Zero(),r=this.center.getConnectedValue(t),n=de.Zero();switch(this.mapping){case bS.Spherical:{i.subtractToRef(r,e);const t=e.length();t>0&&(n.x=Math.acos(e.y/t)/Math.PI,0===e.x&&0===e.z||(n.y=Math.atan2(e.x,e.z)/(2*Math.PI)));break}case bS.Cylindrical:{i.subtractToRef(r,e);const t=e.length();t>0&&(n.x=Math.atan2(e.x/t,e.z/t)/(2*Math.PI),n.y=(e.y+1)/2);break}case bS.Cubic:{const e=Math.abs(s.x),t=Math.abs(s.y),o=Math.abs(s.z),a=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z));let l=0,h=0;e>=t&&e>=o?(l=i.y/a-r.y,h=i.z/a-r.z):t>=e&&t>=o?(l=i.x/a-r.x,h=i.z/a-r.z):(l=i.x/a-r.x,h=i.y/a-r.y),n.x=(l+1)/2,n.y=(h+1)/2}}return n};this.uv._storedFunction=e=>t(e)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${bS[this.mapping]};\n`}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}Ze([Cl("Mapping",ul.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:bS.Spherical},{label:"Cylindrical",value:bS.Cylindrical},{label:"Cubic",value:bS.Cubic}]})],LC.prototype,"mapping",void 0),z("BABYLON.MappingBlock",LC);class BC extends kS{constructor(e){super(e),this.registerInput("matrix0",dS.Matrix),this.registerInput("matrix1",dS.Matrix),this.registerOutput("output",dS.Matrix)}getClassName(){return"MatrixComposeBlock"}get matrix0(){return this._inputs[0]}get matrix1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.matrix0.isConnected||!this.matrix1.isConnected)return null;const t=this.matrix0.getConnectedValue(e),i=this.matrix1.getConnectedValue(e);return t&&i?t.multiply(i):null}}}z("BABYLON.MatrixComposeBlock",BC);class kC extends kS{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",dS.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)-1===t.indexOf(s)&&(i+=s._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(t.isAnAncestorOf(e))return!0}return!1}getDescendantOfPredicate(e){if(e(this))return this;for(const t of this.endpoints){const i=t.getDescendantOfPredicate(e);if(i)return i}return null}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(const e of this._endpoints)e.output._storedFunction=e=>this.input.getConnectedValue(e)}}z("BABYLON.TeleportInBlock",kC);class VC extends kS{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",dS.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){const e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}z("BABYLON.TeleportOutBlock",VC);class UC extends kS{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.serializedCachedData=!1,this.registerOutput("texture",dS.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise(((t,i)=>{const s=new Image,r=document.createElement("canvas"),n=r.getContext("2d");s.onload=()=>{r.width=s.width,r.height=s.height,n.drawImage(s,0,0);const e=n.getImageData(0,0,s.width,s.height).data,i=new Float32Array(e.length);for(let t=0;t{this._data=null,i()},s.src=e}))}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise(((t,i)=>{if(!e.isReady())return void e.onLoadObservable.addOnce((()=>this.extractFromTextureAsync(e).then(t).catch(i)));const s=e.getSize();np.GetTextureDataAsync(e,s.width,s.height).then((async e=>{const i=new Float32Array(e.length);for(let t=0;t=0?e%1:1-Math.abs(e)%1}_buildBlock(){const e=e=>{const t=this.texture.getConnectedValue(e);if(!t||!t.data)return null;const i=this.coordinates.getConnectedValue(e);if(!i)return null;const s=this.clampCoordinates?Math.max(0,Math.min(i.x,1)):this._repeatClamp(i.x),r=this.clampCoordinates?Math.max(0,Math.min(i.y,1)):this._repeatClamp(i.y),n=Math.floor(s*(t.width-1)),o=Math.floor(r*(t.height-1)),a=n+t.width*o;return pe.FromArray(t.data,4*a)};this.rgba._storedFunction=t=>e(t),this.rgb._storedFunction=t=>{const i=e(t);return i?i.toVector3():null},this.r._storedFunction=t=>{const i=e(t);return i?i.x:null},this.g._storedFunction=t=>{const i=e(t);return i?i.y:null},this.b._storedFunction=t=>{const i=e(t);return i?i.z:null},this.a._storedFunction=t=>{const i=e(t);return i?i.w:null}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates};\n`}serialize(){const e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}}Ze([Cl("Clamp Coordinates",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GC.prototype,"clampCoordinates",void 0),z("BABYLON.GeometryTextureFetchBlock",GC);class zC extends kS{constructor(e){super(e),this.registerInput("geometry",dS.Geometry),this.registerOutput("min",dS.Vector3),this.registerOutput("max",dS.Vector3)}getClassName(){return"BoundingBlock"}get geometry(){return this._inputs[0]}get min(){return this._outputs[0]}get max(){return this._outputs[1]}_buildBlock(){this.min._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?Vn(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?Vn(t.positions,0,t.positions.length/3).maximum:null}}}z("BABYLON.BoundingBlock",zC),function(e){e[e.Intersect=0]="Intersect",e[e.Subtract=1]="Subtract",e[e.Union=2]="Union"}(TS||(TS={}));class WC extends kS{constructor(e){super(e),this.evaluateContext=!1,this.operation=TS.Intersect,this.registerInput("geometry0",dS.Geometry),this.registerInput("geometry1",dS.Geometry),this.registerOutput("output",dS.Geometry)}getClassName(){return"BooleanGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{const t=this.geometry0.getConnectedValue(e),i=this.geometry1.getConnectedValue(e);if(!t||!i)return null;const s=t.positions.length/3;!t.normals&&i.normals&&(t.normals=new Array(t.positions.length)),!i.normals&&t.normals&&(i.normals=new Array(i.positions.length)),!t.uvs&&i.uvs&&(t.uvs=new Array(2*s)),!i.uvs&&t.uvs&&(i.uvs=new Array(2*s)),!t.colors&&i.colors&&(t.colors=new Array(4*s)),!i.colors&&t.colors&&(i.colors=new Array(4*s));const r=tS.FromVertexData(t),n=tS.FromVertexData(i);let o;switch(this.operation){case TS.Intersect:o=r.intersect(n);break;case TS.Subtract:o=r.subtract(n);break;case TS.Union:o=r.union(n)}return o.toVertexData()};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`;return e+=`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${TS[this.operation]};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation)}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],WC.prototype,"evaluateContext",void 0),Ze([Cl("Operation",ul.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:TS.Intersect},{label:"Subtract",value:TS.Subtract},{label:"Union",value:TS.Union}]})],WC.prototype,"operation",void 0),z("BABYLON.BooleanGeometryBlock",WC);class HC extends kS{constructor(e){super(e),this.registerInput("x",dS.AutoDetect),this.registerInput("y",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.x.isConnected||!this.y.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.atan2(e,t);this.output._storedFunction=t=>{const i=this.x.getConnectedValue(t),s=this.y.getConnectedValue(t);switch(this.x.type){case dS.Int:case dS.Float:return e(i,s);case dS.Vector2:return new de(e(i.x,s.x),e(i.y,s.y));case dS.Vector3:return new _e(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case dS.Vector4:return new pe(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0}}}z("BABYLON.GeometryArcTan2Block",HC);class XC extends kS{constructor(e){super(e),this.registerInput("left",dS.AutoDetect),this.registerInput("right",dS.AutoDetect),this.registerInput("gradient",dS.Float),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case dS.Int:case dS.Float:return e(r,i,s);case dS.Vector2:return new de(e(r,i.x,s.x),e(r,i.y,s.y));case dS.Vector3:return new _e(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));case dS.Vector4:return new pe(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w))}return 0},this}}z("BABYLON.GeometryLerpBlock",XC);class YC extends kS{constructor(e){super(e),this.registerInput("left",dS.AutoDetect),this.registerInput("right",dS.AutoDetect),this.registerInput("gradient",dS.Float),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryNLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case dS.Int:case dS.Float:return e(r,i,s);case dS.Vector2:{const t=new de(e(r,i.x,s.x),e(r,i.y,s.y));return t.normalize(),t}case dS.Vector3:{const t=new _e(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));return t.normalize(),t}case dS.Vector4:{const t=new pe(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w));return t.normalize(),t}}return 0},this}}z("BABYLON.GeometryNLerpBlock",YC);class QC extends kS{constructor(e){super(e),this.registerInput("value",dS.AutoDetect),this.registerInput("edge",dS.Float),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryStepBlock"}get value(){return this._inputs[0]}get edge(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e{const i=this.value.getConnectedValue(t),s=this.edge.getConnectedValue(t);switch(this.value.type){case dS.Int:case dS.Float:return e(i,s);case dS.Vector2:return new de(e(i.x,s),e(i.y,s));case dS.Vector3:return new _e(e(i.x,s),e(i.y,s),e(i.z,s));case dS.Vector4:return new pe(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}}z("BABYLON.GeometryStepBlock",QC);class jC extends kS{constructor(e){super(e),this.registerInput("value",dS.AutoDetect),this.registerInput("edge0",dS.Float),this.registerInput("edge1",dS.Float),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometrySmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge0.isConnected||!this.edge1.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>{const s=Math.max(0,Math.min((e-t)/(i-t),1));return s*s*(3-2*s)};return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.edge0.getConnectedValue(t),r=this.edge1.getConnectedValue(t);switch(this.value.type){case dS.Int:case dS.Float:return e(i,s,r);case dS.Vector2:return new de(e(i.x,s,r),e(i.y,s,r));case dS.Vector3:return new _e(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r));case dS.Vector4:return new pe(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r),e(i.w,s,r))}return 0},this}}z("BABYLON.GeometrySmoothStepBlock",jC);class KC extends kS{constructor(e){super(e),this.registerInput("left",dS.AutoDetect),this.registerInput("right",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e-Math.floor(e/t)*t;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t);switch(this.left.type){case dS.Int:case dS.Float:return e(i,s);case dS.Vector2:return new de(e(i.x,s.x),e(i.y,s.y));case dS.Vector3:return new _e(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case dS.Vector4:return new pe(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0},this}}z("BABYLON.GeometryModBlock",KC);class $C extends kS{constructor(e){super(e),this.registerInput("value",dS.AutoDetect),this.registerInput("power",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryPowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.power.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.pow(e,t);return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.power.getConnectedValue(t);switch(this.value.type){case dS.Int:case dS.Float:return e(i,s);case dS.Vector2:return new de(e(i.x,s),e(i.y,s));case dS.Vector3:return new _e(e(i.x,s),e(i.y,s),e(i.z,s));case dS.Vector4:return new pe(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}}z("BABYLON.GeometryPowBlock",$C);class qC extends kS{constructor(e){super(e),this.minimum=0,this.maximum=1,this.registerInput("value",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=e=>Math.max(this.minimum,Math.min(e,this.maximum));return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t);switch(this.value.type){case dS.Int:case dS.Float:return e(i);case dS.Vector2:return new de(e(i.x),e(i.y));case dS.Vector3:return new _e(e(i.x),e(i.y),e(i.z));case dS.Vector4:return new pe(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e){super._deserialize(e),this.minimum=e.minimum,this.maximum=e.maximum}}Ze([Cl("Minimum",ul.Float)],qC.prototype,"minimum",void 0),Ze([Cl("Maximum",ul.Float)],qC.prototype,"maximum",void 0),z("BABYLON.GeometryClampBlock",qC);class ZC extends kS{constructor(e){super(e),this.registerInput("left",dS.AutoDetect),this.registerInput("right",dS.AutoDetect),this.registerOutput("output",dS.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Int),this._inputs[0].excludedConnectionPointTypes.push(dS.Float),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Vector2),this._inputs[1].excludedConnectionPointTypes.push(dS.Int),this._inputs[1].excludedConnectionPointTypes.push(dS.Float),this._inputs[1].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[1].excludedConnectionPointTypes.push(dS.Vector2)}getClassName(){return"GeometryCrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);switch(this.left.type){case dS.Vector3:return _e.Cross(t,i);case dS.Vector4:return _e.Cross(t.toVector3(),i.toVector3())}return 0},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}z("BABYLON.GeometryCrossBlock",ZC),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(yS||(yS={}));class JC extends kS{constructor(e){super(e),this.type=yS.EaseInOutSine,this.registerInput("input",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Int)}getClassName(){return"GeometryCurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);let e;switch(this.type){case yS.EaseInSine:e=e=>1-Math.cos(3.1415*e/2);break;case yS.EaseOutSine:e=e=>Math.sin(3.1415*e/2);break;case yS.EaseInOutSine:e=e=>-(Math.cos(3.1415*e)-1)/2;break;case yS.EaseInQuad:e=e=>e*e;break;case yS.EaseOutQuad:e=e=>(1-e)*(1-e);break;case yS.EaseInOutQuad:e=e=>e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;break;case yS.EaseInCubic:e=e=>e*e*e;break;case yS.EaseOutCubic:e=e=>1-Math.pow(1-e,3);break;case yS.EaseInOutCubic:e=e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;break;case yS.EaseInQuart:e=e=>e*e*e*e;break;case yS.EaseOutQuart:e=e=>1-Math.pow(1-e,4);break;case yS.EaseInOutQuart:e=e=>e<.5?8*e*e*e*e:1-Math.pow(-2*e+2,4)/2;break;case yS.EaseInQuint:e=e=>e*e*e*e*e;break;case yS.EaseOutQuint:e=e=>1-Math.pow(1-e,5);break;case yS.EaseInOutQuint:e=e=>e<.5?16*e*e*e*e*e:1-Math.pow(-2*e+2,5)/2;break;case yS.EaseInExpo:e=e=>0===e?0:Math.pow(2,10*e-10);break;case yS.EaseOutExpo:e=e=>1===e?1:1-Math.pow(2,-10*e);break;case yS.EaseInOutExpo:e=e=>0===e?0:1===e?1:e<.5?Math.pow(2,20*e-10)/2:(2-Math.pow(2,-20*e+10))/2;break;case yS.EaseInCirc:e=e=>1-Math.sqrt(1-Math.pow(e,2));break;case yS.EaseOutCirc:e=e=>Math.sqrt(1-Math.pow(e-1,2));break;case yS.EaseInOutCirc:e=e=>e<.5?(1-Math.sqrt(1-Math.pow(2*e,2)))/2:(Math.sqrt(1-Math.pow(-2*e+2,2))+1)/2;break;case yS.EaseInBack:e=e=>2.70158*e*e*e-1.70158*e*e;break;case yS.EaseOutBack:e=e=>2.70158*Math.pow(e-1,3)+1.70158*Math.pow(e-1,2);break;case yS.EaseInOutBack:e=e=>e<.5?Math.pow(2*e,2)*(7.189819*e-2.5949095)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+3.5949095)+2)/2;break;case yS.EaseInElastic:e=e=>0===e?0:1===e?1:-Math.pow(2,10*e-10)*Math.sin(6.283/3*(10*e-10.75));break;case yS.EaseOutElastic:e=e=>0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(6.283/3*(10*e-.75))+1;break;case yS.EaseInOutElastic:e=e=>0===e?0:1==e?1:e<.5?-Math.pow(2,20*e-10)*Math.sin(6.283/4.5*(20*e-11.125))/2:Math.pow(2,-20*e+10)*Math.sin(6.283/4.5*(20*e-11.125))/2+1}return this.output._storedFunction=t=>{const i=this.input.getConnectedValue(t);switch(this.input.type){case dS.Float:return e(i);case dS.Vector2:return new de(e(i.x),e(i.y));case dS.Vector3:return new _e(e(i.x),e(i.y),e(i.z));case dS.Vector4:return new pe(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e){super._deserialize(e),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.GeometryCurveBlockTypes.${yS[this.type]};\n`}}Ze([Cl("Type",ul.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"EaseInSine",value:yS.EaseInSine},{label:"EaseOutSine",value:yS.EaseOutSine},{label:"EaseInOutSine",value:yS.EaseInOutSine},{label:"EaseInQuad",value:yS.EaseInQuad},{label:"EaseOutQuad",value:yS.EaseOutQuad},{label:"EaseInOutQuad",value:yS.EaseInOutQuad},{label:"EaseInCubic",value:yS.EaseInCubic},{label:"EaseOutCubic",value:yS.EaseOutCubic},{label:"EaseInOutCubic",value:yS.EaseInOutCubic},{label:"EaseInQuart",value:yS.EaseInQuart},{label:"EaseOutQuart",value:yS.EaseOutQuart},{label:"EaseInOutQuart",value:yS.EaseInOutQuart},{label:"EaseInQuint",value:yS.EaseInQuint},{label:"EaseOutQuint",value:yS.EaseOutQuint},{label:"EaseInOutQuint",value:yS.EaseInOutQuint},{label:"EaseInExpo",value:yS.EaseInExpo},{label:"EaseOutExpo",value:yS.EaseOutExpo},{label:"EaseInOutExpo",value:yS.EaseInOutExpo},{label:"EaseInCirc",value:yS.EaseInCirc},{label:"EaseOutCirc",value:yS.EaseOutCirc},{label:"EaseInOutCirc",value:yS.EaseInOutCirc},{label:"EaseInBack",value:yS.EaseInBack},{label:"EaseOutBack",value:yS.EaseOutBack},{label:"EaseInOutBack",value:yS.EaseInOutBack},{label:"EaseInElastic",value:yS.EaseInElastic},{label:"EaseOutElastic",value:yS.EaseOutElastic},{label:"EaseInOutElastic",value:yS.EaseInOutElastic}]})],JC.prototype,"type",void 0),z("BABYLON.GeometryCurveBlock",JC);class eE extends kS{constructor(e){super(e),this.registerInput("color",dS.Vector3),this.registerInput("level",dS.Float,!0,0),this.registerOutput("output",dS.Vector3)}getClassName(){return"GeometryDesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.color.isConnected?(this.output._storedFunction=e=>{const t=this.color.getConnectedValue(e),i=this.level.getConnectedValue(e),s=.5*(Math.min(t.x,t.y,t.z)+Math.max(t.x,t.y,t.z));return new _e(t.x*(1-i)+s*i,t.y*(1-i)+s*i,t.z*(1-i)+s*i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}z("BABYLON.GeometryDesaturateBlock",eE);class tE extends kS{constructor(e){super(e),this.registerInput("value",dS.AutoDetect),this.registerInput("steps",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[1].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(dS.Float)}getClassName(){return"GeometryPosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected&&this.steps.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.steps.getConnectedValue(e);let s=i;if(this.steps.type===dS.Float)switch(this.value.type){case dS.Vector2:s=new de(i,i);break;case dS.Vector3:s=new _e(i,i,i);break;case dS.Vector4:s=new pe(i,i,i,i)}switch(this.value.type){case dS.Vector2:return new de(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y));case dS.Vector3:return new _e(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z));case dS.Vector4:return new pe(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z),t.w/(1/s.w)*(1/s.w));default:return Math.floor(t/(1/i)*(1/i))}},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}z("BABYLON.GeometryPosterizeBlock",tE);class iE extends kS{constructor(e){super(e),this.registerInput("value",dS.AutoDetect),this.registerInput("reference",dS.AutoDetect),this.registerInput("distance",dS.Float),this.registerInput("replacement",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(dS.Float),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[1].excludedConnectionPointTypes.push(dS.Float),this._inputs[1].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[3].excludedConnectionPointTypes.push(dS.Float),this._inputs[3].excludedConnectionPointTypes.push(dS.Matrix)}getClassName(){return"GeometryReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected&&this.reference.isConnected&&this.distance.isConnected&&this.replacement.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.reference.getConnectedValue(e),s=this.distance.getConnectedValue(e),r=this.replacement.getConnectedValue(e);return t.subtract(i).length(){const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.subtract(i).length()},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}z("BABYLON.GeometryDistanceBlock",sE);class rE extends kS{constructor(e){super(e),this.registerInput("left",dS.AutoDetect),this.registerInput("right",dS.AutoDetect),this.registerOutput("output",dS.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Int),this._inputs[0].excludedConnectionPointTypes.push(dS.Float),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[1].excludedConnectionPointTypes.push(dS.Float),this._inputs[1].excludedConnectionPointTypes.push(dS.Matrix)}getClassName(){return"GeometryDotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.dot(i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}z("BABYLON.GeometryDotBlock",rE);class nE extends kS{constructor(e){super(e),this.registerInput("value",dS.AutoDetect),this.registerOutput("output",dS.Float),this._inputs[0].excludedConnectionPointTypes.push(dS.Int),this._inputs[0].excludedConnectionPointTypes.push(dS.Float),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix)}getClassName(){return"GeometryLengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected?(this.output._storedFunction=e=>this.value.getConnectedValue(e).length(),this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}z("BABYLON.GeometryLengthBlock",nE);class oE extends kS{constructor(e){super(e),this.registerInput("input",dS.Vector2),this.registerInput("angle",dS.Float),this.registerOutput("output",dS.Vector2)}getClassName(){return"GeometryRotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.angle.isConnected&&this.input.isConnected?(this.output._storedFunction=e=>{const t=this.input.getConnectedValue(e),i=this.angle.getConnectedValue(e);return new de(Math.cos(i)*t.x-Math.sin(i)*t.y,Math.sin(i)*t.x+Math.cos(i)*t.y)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}z("BABYLON.GeometryRotate2dBlock",oE);class aE extends ha{get covariancesATexture(){return this._covariancesATexture}get covariancesBTexture(){return this._covariancesBTexture}get centersTexture(){return this._centersTexture}get colorsTexture(){return this._colorsTexture}constructor(e,t=null,i=null){super(e,i),this._vertexCount=0,this._worker=null,this._frameIdLastUpdate=-1,this._modelViewMatrix=me.Identity(),this._material=null,this._canPostToWorker=!0,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null;const s=new Wn;s.positions=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],s.indices=[0,1,2,0,2,3],s.applyToMesh(this),this.subMeshes=[],new Gn(0,0,4,0,6,this),this.doNotSyncBoundingInfo=!0,this.setEnabled(!1),this._lastProj=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t&&this.loadFileAsync(t)}getClassName(){return"GaussianSplattingMesh"}getTotalVertices(){return this._vertexCount}render(e,t,i){this.material||(this._material=new Vy(this.name+"_material",this._scene),this.material=this._material);const s=this.getScene().getFrameId();if(s!==this._frameIdLastUpdate&&this._worker&&this._scene.activeCamera&&this._canPostToWorker){this.getWorldMatrix().multiplyToRef(this._scene.activeCamera.getViewMatrix(),this._modelViewMatrix);const e=this._lastProj[2]*this._modelViewMatrix.m[2]+this._lastProj[6]*this._modelViewMatrix.m[6]+this._lastProj[10]*this._modelViewMatrix.m[10];Math.abs(e-1)>=.01&&(this._frameIdLastUpdate=s,this._canPostToWorker=!1,this._lastProj=this._modelViewMatrix.m.slice(0),this._worker.postMessage({view:this._modelViewMatrix.m,depthMix:this._depthMix,useRightHandedSystem:this._scene.useRightHandedSystem},[this._depthMix.buffer]))}return super.render(e,t,i)}static ConvertPLYToSplat(e){const t=new Uint8Array(e),i=(new TextDecoder).decode(t.slice(0,10240)),s=i.indexOf("end_header\n");if(s<0||!i)return e;const r=parseInt(/element vertex (\d+)\n/.exec(i)[1]);let n=0;const o={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1},a=[],l=i.slice(0,s).split("\n").filter((e=>e.startsWith("property ")));for(const e of l){const[,t,i]=e.split(" ");if(a.push({name:i,type:t,offset:n}),!o[t])return Ne.Error(`Unsupported property type: ${t}. Are you sure it's a valid Gaussian Splatting file?`),new ArrayBuffer(0);n+=o[t]}const h=.28209479177387814,c=new DataView(e,s+11),u=new ArrayBuffer(32*r),d=new fe;for(let e=0;e{this._loadData(aE.ConvertPLYToSplat(e))}))}dispose(e){this._covariancesATexture?.dispose(),this._covariancesBTexture?.dispose(),this._centersTexture?.dispose(),this._colorsTexture?.dispose(),this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._material?.dispose(!1,!0),this._material=null,this._worker?.terminate(),this._worker=null,super.dispose(e)}_loadData(e){if(!e.byteLength)return;const t=new Uint8Array(e),i=new Float32Array(t.buffer),s=t.length/32;this._vertexCount=s;const r=this._getTextureSize(s),n=r.x*r.y,o=new Float32Array(3*n),a=new Float32Array(3*n),l=new Float32Array(3*n),h=ve.Matrix[0],c=ve.Matrix[1],u=ve.Quaternion[0],d=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),_=new _e(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let e=0;enew Oa(e,t,i,s,this._scene,!1,!1,2,1),g=e=>{const t=e.length/3,i=new Float32Array(4*t);for(let s=0;s{this._depthMix=e.data.depthMix;const t=new Uint32Array(e.data.depthMix.buffer);for(let e=0;ei&&(Ne.Error("GaussianSplatting texture size: ("+i+", "+s+"), maxTextureSize: "+i),s=i),new de(i,s)}}aE._CreateWorker=function(e){let t,i,s,r,n=0;e.onmessage=o=>{if(o.data.positions)t=o.data.positions,n=o.data.vertexCount;else{const a=o.data.view;if(!t||!a)throw new Error("positions or view is not defined!");i=o.data.depthMix,s=new Uint32Array(i.buffer),r=new Float32Array(i.buffer);for(let e=0;e{this.update(.001*s.getEngine().getDeltaTime()*e.timeFactor)}))}addAgent(e,t,i){const s=new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams;s.radius=t.radius,s.height=t.height,s.maxAcceleration=t.maxAcceleration,s.maxSpeed=t.maxSpeed,s.collisionQueryRange=t.collisionQueryRange,s.pathOptimizationRange=t.pathOptimizationRange,s.separationWeight=t.separationWeight,s.updateFlags=7,s.obstacleAvoidanceType=0,s.queryFilterType=0,s.userData=0;const r=this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z),s);return this.transforms.push(i),this.agents.push(r),this.reachRadii.push(t.reachRadius?t.reachRadius:t.radius),this._agentDestinationArmed.push(!1),this._agentDestination.push(new _e(0,0,0)),r}getAgentPosition(e){const t=this.recastCrowd.getAgentPosition(e);return new _e(t.x,t.y,t.z)}getAgentPositionToRef(e,t){const i=this.recastCrowd.getAgentPosition(e);t.set(i.x,i.y,i.z)}getAgentVelocity(e){const t=this.recastCrowd.getAgentVelocity(e);return new _e(t.x,t.y,t.z)}getAgentVelocityToRef(e,t){const i=this.recastCrowd.getAgentVelocity(e);t.set(i.x,i.y,i.z)}getAgentNextTargetPath(e){const t=this.recastCrowd.getAgentNextTargetPath(e);return new _e(t.x,t.y,t.z)}getAgentNextTargetPathToRef(e,t){const i=this.recastCrowd.getAgentNextTargetPath(e);t.set(i.x,i.y,i.z)}getAgentState(e){return this.recastCrowd.getAgentState(e)}overOffmeshConnection(e){return this.recastCrowd.overOffmeshConnection(e)}agentGoto(e,t){this.recastCrowd.agentGoto(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z));const i=this.agents.indexOf(e);i>-1&&(this._agentDestinationArmed[i]=!0,this._agentDestination[i].set(t.x,t.y,t.z))}agentTeleport(e,t){this.recastCrowd.agentTeleport(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z))}updateAgentParameters(e,t){const i=this.recastCrowd.getAgentParameters(e);void 0!==t.radius&&(i.radius=t.radius),void 0!==t.height&&(i.height=t.height),void 0!==t.maxAcceleration&&(i.maxAcceleration=t.maxAcceleration),void 0!==t.maxSpeed&&(i.maxSpeed=t.maxSpeed),void 0!==t.collisionQueryRange&&(i.collisionQueryRange=t.collisionQueryRange),void 0!==t.pathOptimizationRange&&(i.pathOptimizationRange=t.pathOptimizationRange),void 0!==t.separationWeight&&(i.separationWeight=t.separationWeight),this.recastCrowd.setAgentParameters(e,i)}removeAgent(e){this.recastCrowd.removeAgent(e);const t=this.agents.indexOf(e);t>-1&&(this.agents.splice(t,1),this.transforms.splice(t,1),this.reachRadii.splice(t,1),this._agentDestinationArmed.splice(t,1),this._agentDestination.splice(t,1))}getAgents(){return this.agents}update(e){if(this.bjsRECASTPlugin.navMesh.update(),e<=J)return;const t=this.bjsRECASTPlugin.getTimeStep(),i=this.bjsRECASTPlugin.getMaximumSubStepCount();if(t<=J)this.recastCrowd.update(e);else{let s=Math.floor(e/t);i&&s>i&&(s=i),s<1&&(s=1);const r=e/s;for(let e=0;eo&&i.ynew cE(e,t,i);class cE{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=cE._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,cE.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,Ds.SetImmediate((()=>{t(!0)}))):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){const t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){const e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`};let s=!1,r=i();const n=new Pt;navigator.onLine&&(s=!0,r=r+(null==r.match(/\?/)?"?":"&")+Date.now()),n.open("GET",r),n.addEventListener("load",(()=>{if(200===n.status||cE._ValidateXHRData(n,1))try{const t=JSON.parse(n.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&cE._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){t()}else t()}),!1),n.addEventListener("error",(()=>{if(s){s=!1;const e=i();n.open("GET",e),n.send()}else t()}),!1);try{n.send()}catch(t){Ne.Error("Error on XHR send request."),e(!1)}}open(e,t){const i=()=>{this._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline))if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;const t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{i()},t.onblocked=()=>{Ne.Error("IDB request blocked. Please reload the page."),i()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){Ne.Error("Error while creating object stores. Exception: "+e.message),i()}}}else this._isSupported=!1,t&&t()}loadImage(e,t){const i=cE._ReturnFullUrlLocation(e),s=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?s():this._loadImageFromDBAsync(i,t,s)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let s;const r=this._db.transaction(["textures"]);r.onabort=()=>{t.src=e},r.oncomplete=()=>{let r;s&&"function"==typeof URL?(r=URL.createObjectURL(s.data),t.onerror=()=>{Ne.Error("Error loading image from blob URL: "+r+" switching back to web url: "+e),t.src=e},t.src=r):i()};const n=r.objectStore("textures").get(e);n.onsuccess=e=>{s=e.target.result},n.onerror=()=>{Ne.Error("Error loading texture "+e+" from DB."),t.src=e}}else Ne.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){const s=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(cE._IsUASupportingBlobStorage){const r=new Pt;r.open("GET",e),r.responseType="blob",r.addEventListener("load",(()=>{if(200===r.status&&this._db){i=r.response;const n=this._db.transaction(["textures"],"readwrite");n.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}s()},n.oncomplete=()=>{s()};const o={textureUrl:e,data:i};try{const e=n.objectStore("textures").put(o);e.onsuccess=()=>{},e.onerror=()=>{s()}}catch(i){25===i.code&&(cE._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e}),!1),r.addEventListener("error",(()=>{Ne.Error("Error in XHR request in BABYLON.Database."),t.src=e}),!1),r.send()}else t.src=e}else Ne.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,(()=>{this._saveVersionIntoDBAsync(e,t)}))}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let s;try{const r=this._db.transaction(["versions"]);r.oncomplete=()=>{s?this._manifestVersionFound!==s.data?(this._mustUpdateRessources=!0,i()):t(s.data):(this._mustUpdateRessources=!0,i())},r.onabort=()=>{t(-1)};const n=r.objectStore("versions").get(e);n.onsuccess=e=>{s=e.target.result},n.onerror=()=>{Ne.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){Ne.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else Ne.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)}_saveVersionIntoDBAsync(e,t){if(this._isSupported&&!this._hasReachedQuota&&this._db)try{const i=this._db.transaction(["versions"],"readwrite");i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const s={sceneUrl:e,data:this._manifestVersionFound},r=i.objectStore("versions").put(s);r.onsuccess=()=>{},r.onerror=()=>{Ne.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){Ne.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,s,r){const n=cE._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(n,t,i,r,s)};this._checkVersionFromDB(n,(e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(n,t,i,r,s):this._loadFileAsync(n,t,o):s&&s()}))}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let s,r;s=-1!==e.indexOf(".babylon")?"scenes":"textures";const n=this._db.transaction([s]);n.oncomplete=()=>{r?t(r.data):i()},n.onabort=()=>{i()};const o=n.objectStore(s).get(e);o.onsuccess=e=>{r=e.target.result},o.onerror=()=>{Ne.Error("Error loading file "+e+" from DB."),i()}}else Ne.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,s,r){if(this._isSupported){let n;n=-1!==e.indexOf(".babylon")?"scenes":"textures";const o=new Pt;let a;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),s&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",(()=>{if(200===o.status||o.status<400&&cE._ValidateXHRData(o,s?6:1))if(a=s?o.response:o.responseText,!this._hasReachedQuota&&this._db){const i=this._db.transaction([n],"readwrite");let s;i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(a)},i.oncomplete=()=>{t(a)},s="scenes"===n?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{const e=i.objectStore(n).put(s);e.onsuccess=()=>{},e.onerror=()=>{Ne.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(a)}}else t(a);else o.status>=400&&r?r(o):t()}),!1),o.addEventListener("error",(()=>{Ne.Error("error on XHR request."),r&&r()}),!1),o.send()}else Ne.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),r&&r()}static _ValidateXHRData(e,t=7){try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){const i=Jx(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){const t=new Uint8Array(e.response,0,3);return 68===t[0]&&68===t[1]&&83===t[2]}}catch(e){}return!1}}cE._IsUASupportingBlobStorage=!0,cE.IDBStorageEnabled=!1,cE._ParseURL=e=>{document.createElement("a").href=e;const t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},cE._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?cE._ParseURL(window.location.href)+e:e;class uE{constructor(){this.direction1=new _e(0,1,0),this.direction2=new _e(0,1,0),this.minEmitBox=new _e(-.5,-.5,-.5),this.maxEmitBox=new _e(.5,.5,.5)}startDirectionFunction(e,t,i,s){const r=oe(this.direction1.x,this.direction2.x),n=oe(this.direction1.y,this.direction2.y),o=oe(this.direction1.z,this.direction2.z);if(s)return t.x=r,t.y=n,void(t.z=o);_e.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){const r=oe(this.minEmitBox.x,this.maxEmitBox.x),n=oe(this.minEmitBox.y,this.maxEmitBox.y),o=oe(this.minEmitBox.z,this.maxEmitBox.z);if(s)return t.x=r,t.y=n,void(t.z=o);_e.TransformCoordinatesFromFloatsToRef(r,n,o,e,t)}clone(){const e=new uE;return Ye.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){_e.FromArrayToRef(e.direction1,0,this.direction1),_e.FromArrayToRef(e.direction2,0,this.direction2),_e.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),_e.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class dE{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,s){s?ve.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),ve.Vector3[0]).normalize();const r=be.RandomRange(0,this.directionRandomizer),n=be.RandomRange(0,this.directionRandomizer),o=be.RandomRange(0,this.directionRandomizer);t.x=ve.Vector3[0].x+r,t.y=ve.Vector3[0].y+n,t.z=ve.Vector3[0].z+o,t.normalize()}startPositionFunction(e,t,i,s){const r=be.RandomRange(0,2*Math.PI);let n;this.emitFromSpawnPointOnly?n=1e-4:(n=be.RandomRange(0,this.heightRange),n=1-n*n);let o=this._radius-be.RandomRange(0,this._radius*this.radiusRange);o*=n;const a=o*Math.sin(r),l=o*Math.cos(r),h=n*this._height;if(s)return t.x=a,t.y=h,void(t.z=l);_e.TransformCoordinatesFromFloatsToRef(a,h,l,e,t)}clone(){const e=new dE(this._radius,this._angle,this.directionRandomizer);return Ye.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e}getClassName(){return"ConeParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}}class _E{constructor(e=1,t=1,i=1,s=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=s,this._tempVector=_e.Zero()}startDirectionFunction(e,t,i,s,r){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),_e.TransformNormalToRef(this._tempVector,r,this._tempVector);const n=be.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let o=Math.atan2(this._tempVector.x,this._tempVector.z);o+=be.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=n,this._tempVector.x=Math.sin(o),this._tempVector.z=Math.cos(o),this._tempVector.normalize(),s?t.copyFrom(this._tempVector):_e.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,s){const r=be.RandomRange(-this.height/2,this.height/2),n=be.RandomRange(0,2*Math.PI),o=be.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),a=Math.sqrt(o)*this.radius,l=a*Math.cos(n),h=a*Math.sin(n);s?t.copyFromFloats(l,r,h):_e.TransformCoordinatesFromFloatsToRef(l,r,h,e,t)}clone(){const e=new _E(this.radius,this.directionRandomizer);return Ye.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class pE extends _E{constructor(e=1,t=1,i=1,s=new _e(0,1,0),r=new _e(0,1,0)){super(e,t,i),this.direction1=s,this.direction2=r}startDirectionFunction(e,t,i,s){const r=be.RandomRange(this.direction1.x,this.direction2.x),n=be.RandomRange(this.direction1.y,this.direction2.y),o=be.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):_e.TransformNormalFromFloatsToRef(r,n,o,e,t)}clone(){const e=new pE(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return Ye.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),_e.FromArrayToRef(e.direction1,0,this.direction1),_e.FromArrayToRef(e.direction2,0,this.direction2)}}class fE{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=be.RandomRange(0,this.directionRandomizer),o=be.RandomRange(0,this.directionRandomizer),a=be.RandomRange(0,this.directionRandomizer);r.x+=n,r.y+=o,r.z+=a,r.normalize(),s?t.copyFrom(r):_e.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-be.RandomRange(0,this.radius*this.radiusRange),n=be.RandomRange(0,1),o=be.RandomRange(0,2*Math.PI),a=Math.acos(2*n-1),l=r*Math.cos(o)*Math.sin(a),h=r*Math.cos(a),c=r*Math.sin(o)*Math.sin(a);s?t.copyFromFloats(l,Math.abs(h),c):_e.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),c,e,t)}clone(){const e=new fE(this.radius,this.directionRandomizer);return Ye.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class mE{constructor(){this.direction1=new _e(0,1,0),this.direction2=new _e(0,1,0)}startDirectionFunction(e,t,i,s){const r=be.RandomRange(this.direction1.x,this.direction2.x),n=be.RandomRange(this.direction1.y,this.direction2.y),o=be.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):_e.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){s?t.copyFromFloats(0,0,0):_e.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new mE;return Ye.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){_e.FromArrayToRef(e.direction1,0,this.direction1),_e.FromArrayToRef(e.direction2,0,this.direction2)}}class gE{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=be.RandomRange(0,this.directionRandomizer),o=be.RandomRange(0,this.directionRandomizer),a=be.RandomRange(0,this.directionRandomizer);r.x+=n,r.y+=o,r.z+=a,r.normalize(),s?t.copyFrom(r):_e.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-be.RandomRange(0,this.radius*this.radiusRange),n=be.RandomRange(0,1),o=be.RandomRange(0,2*Math.PI),a=Math.acos(2*n-1),l=r*Math.cos(o)*Math.sin(a),h=r*Math.cos(a),c=r*Math.sin(o)*Math.sin(a);s?t.copyFromFloats(l,h,c):_e.TransformCoordinatesFromFloatsToRef(l,h,c,e,t)}clone(){const e=new gE(this.radius,this.directionRandomizer);return Ye.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class vE extends gE{constructor(e=1,t=new _e(0,1,0),i=new _e(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=be.RandomRange(this.direction1.x,this.direction2.x),s=be.RandomRange(this.direction1.y,this.direction2.y),r=be.RandomRange(this.direction1.z,this.direction2.z);_e.TransformNormalFromFloatsToRef(i,s,r,e,t)}clone(){const e=new vE(this.radius,this.direction1,this.direction2);return Ye.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class xE{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,s){const r=ve.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,r);const e=ve.Vector3[1];r.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,r)}else r.set(0,0,0);s?t.copyFrom(r):_e.TransformNormalToRef(r,e,t)}startPositionFunction(e,t,i,s){const r=ve.Vector3[0];this.particlePositionGenerator?this.particlePositionGenerator(-1,i,r):r.set(0,0,0),s?t.copyFrom(r):_e.TransformCoordinatesToRef(r,e,t)}clone(){const e=new xE;return Ye.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.particlePositionGenerator=this.particlePositionGenerator,e.particleDestinationGenerator=this.particleDestinationGenerator,e}parse(e){e.particlePositionGenerator&&(this.particlePositionGenerator=e.particlePositionGenerator),e.particleDestinationGenerator&&(this.particleDestinationGenerator=e.particleDestinationGenerator)}}class bE{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(er.PositionKind),this._normals=e.getVerticesData(er.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=_e.Zero(),this._mesh=null,this.direction1=new _e(0,1,0),this.direction2=new _e(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,s){if(this.useMeshNormalsForDirection&&this._normals)return void _e.TransformNormalToRef(this._storedNormal,e,t);const r=be.RandomRange(this.direction1.x,this.direction2.x),n=be.RandomRange(this.direction1.y,this.direction2.y),o=be.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):_e.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){if(!this._indices||!this._positions)return;const r=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),o=Math.random()*(1-n),a=1-n-o,l=this._indices[r],h=this._indices[r+1],c=this._indices[r+2],u=ve.Vector3[0],d=ve.Vector3[1],_=ve.Vector3[2],p=ve.Vector3[3];_e.FromArrayToRef(this._positions,3*l,u),_e.FromArrayToRef(this._positions,3*h,d),_e.FromArrayToRef(this._positions,3*c,_),p.x=n*u.x+o*d.x+a*_.x,p.y=n*u.y+o*d.y+a*_.y,p.z=n*u.z+o*d.z+a*_.z,s?t.copyFromFloats(p.x,p.y,p.z):_e.TransformCoordinatesFromFloatsToRef(p.x,p.y,p.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(_e.FromArrayToRef(this._normals,3*l,u),_e.FromArrayToRef(this._normals,3*h,d),_e.FromArrayToRef(this._normals,3*c,_),this._storedNormal.x=n*u.x+o*d.x+a*_.x,this._storedNormal.y=n*u.y+o*d.y+a*_.y,this._storedNormal.z=n*u.z+o*d.z+a*_.z)}clone(){const e=new bE(this.mesh);return Ye.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.meshId=this.mesh?.id,e.useMeshNormalsForDirection=this.useMeshNormalsForDirection,e}parse(e,t){_e.FromArrayToRef(e.direction1,0,this.direction1),_e.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class TE{_isUbo(e){return void 0!==e.addUniform}constructor(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}}Bi.ShadersStore.gpuUpdateParticlesPixelShader="#version 300 es\nvoid main() {discard;}\n";Bi.ShadersStore.gpuUpdateParticlesVertexShader="#version 300 es\n#define PI 3.14159\nuniform float currentCount;uniform float timeDelta;uniform float stopFactor;\n#ifndef LOCAL\nuniform mat4 emitterWM;\n#endif\nuniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;uniform vec4 color2;\n#endif\nuniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;uniform float radiusRange;uniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;uniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;uniform float height;uniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer;\n#endif\nin vec3 position;\n#ifdef CUSTOMEMITTER\nin vec3 initialPosition;\n#endif\nin float age;in float life;in vec4 seed;in vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;in vec3 noiseCoordinates2;\n#endif\nout vec3 outPosition;\n#ifdef CUSTOMEMITTER\nout vec3 outInitialPosition;\n#endif\nout float outAge;out float outLife;out vec4 outSeed;out vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;uniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec4 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;}\nvec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));}\nvoid main() {float newAge=age+timeDelta; \nif (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed;\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(direction1+(direction2-direction1)*randoms3);\n#else\nnewDirection=normalize(newPosition+directionRandomizer*randoms3);\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\nangle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.0001;\n#else\nfloat h=randoms2.y*height.y;h=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); \nif (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); }\n#elif defined(CUSTOMEMITTER)\nnewPosition=initialPosition;outInitialPosition=initialPosition;\n#else \nnewPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\n#ifdef LOCAL\noutPosition=newPosition;\n#else\noutPosition=(emitterWM*vec4(newPosition,1.)).xyz;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#ifndef BILLBOARD \noutInitialDirection=direction;\n#endif\n#else\n#ifdef LOCAL\nvec3 initial=newDirection;\n#else \nvec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;\n#endif\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#if defined(CUSTOMEMITTER)\noutPosition=position+(direction-position)*ageGradient; \noutInitialPosition=initialPosition;\n#else\noutPosition=position+direction*directionScale;\n#endif\noutLife=life;outSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#else\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;float dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset;\n#else\nfloat cellStartOffset=0.;\n#endif \nfloat ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);}\nelse {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);}\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}}";class yE{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){return this._updateEffect?.isReady()??!1}createUpdateBuffer(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof xE&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new $i("gpuUpdateParticles",this._updateEffectOptions,this._engine),new TE(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){const e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);const s=this._engine;s.bindTransformFeedbackBuffer(t.getBuffer()),s.setRasterizerState(!1),s.beginTransformFeedback(!0),s.drawArraysType(3,0,i),s.endTransformFeedback(),s.setRasterizerState(!0),s.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;ee)return void i(t[0],t[0],1);for(let s=0;s=r.gradient&&e<=n.gradient)return void i(r,n,(e-r.gradient)/(n.gradient-r.gradient))}const s=t.length-1;i(t[s],t[s],1)}}class IE{constructor(e){this.particleSystem=e,this.position=_e.Zero(),this.direction=_e.Zero(),this.color=new Ae(0,0,0,0),this.colorStep=new Ae(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new de(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new Ae(0,0,0,0),this._currentColor2=new Ae(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=IE._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===t?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);const i=this._initialEndSpriteCellID-this._initialStartSpriteCellID+1;let s;s=this._initialSpriteCellLoop?le(e*t%this.lifeTime/this.lifeTime):le(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+s*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const e=ve.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,ve.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(ve.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach((e=>{this._inheritParticleInfoToSubEmitter(e)}))}_reset(){this.age=0,this.id=IE._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new pe(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}}IE._Count=0;Bi.ShadersStore.particlesPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler;\n#include\n#include\n#include\n#include\n#include\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;uniform sampler2D rampSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n#include\n#include(color,baseColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.particlesVertexShader="attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos; \n#endif\nvarying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#include\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvec3 row1=direction;\n#else\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nmat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size;\n#ifdef BILLBOARD\nvec3 rotatedCorner;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\ngl_Position=projection*vec4(viewPos,1.0);\n#else\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0);\n#endif\nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";class RE extends Yl{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Un(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new K),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,s=null,r=!1,n=.01){super(e),this._emitterInverseWorldMatrix=me.Identity(),this._inheritedVelocityOffset=new _e,this.onDisposeObservable=new K,this.onStoppedObservable=new K,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new Ae(0,0,0,0),this._colorDiff=new Ae(0,0,0,0),this._scaledDirection=_e.Zero(),this._scaledGravity=_e.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this._emitFromParticle=e=>{},this.recycleParticle=e=>{const t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;return 0!==this._stockParticles.length?(e=this._stockParticles.pop(),e._reset()):e=new IE(this),this._prepareParticle(e),e},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=r,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=me.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||re.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new Un(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new uE;let o=null;this.updateFunction=e=>{let t=null;this.noiseTexture&&(t=this.noiseTexture.getSize(),this.noiseTexture.getContent()?.then((e=>{o=e})));const i=e===this._particles;for(let s=0;sr.lifeTime){const e=r.age-a;n=(r.lifeTime-a)*n/e,r.age=r.lifeTime}const l=r.age/r.lifeTime;this._colorGradients&&this._colorGradients.length>0?PE.GetCurrentGradient(l,this._colorGradients,((e,t,i)=>{e!==r._currentColorGradient&&(r._currentColor1.copyFrom(r._currentColor2),t.getColorToRef(r._currentColor2),r._currentColorGradient=e),Ae.LerpToRef(r._currentColor1,r._currentColor2,i,r.color)})):(r.colorStep.scaleToRef(n,this._scaledColorStep),r.color.addInPlace(this._scaledColorStep),r.color.a<0&&(r.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&PE.GetCurrentGradient(l,this._angularSpeedGradients,((e,t,i)=>{e!==r._currentAngularSpeedGradient&&(r._currentAngularSpeed1=r._currentAngularSpeed2,r._currentAngularSpeed2=t.getFactor(),r._currentAngularSpeedGradient=e),r.angularSpeed=ae(r._currentAngularSpeed1,r._currentAngularSpeed2,i)})),r.angle+=r.angularSpeed*n;let h=n;if(this._velocityGradients&&this._velocityGradients.length>0&&PE.GetCurrentGradient(l,this._velocityGradients,((e,t,i)=>{e!==r._currentVelocityGradient&&(r._currentVelocity1=r._currentVelocity2,r._currentVelocity2=t.getFactor(),r._currentVelocityGradient=e),h*=ae(r._currentVelocity1,r._currentVelocity2,i)})),r.direction.scaleToRef(h,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&PE.GetCurrentGradient(l,this._limitVelocityGradients,((e,t,i)=>{e!==r._currentLimitVelocityGradient&&(r._currentLimitVelocity1=r._currentLimitVelocity2,r._currentLimitVelocity2=t.getFactor(),r._currentLimitVelocityGradient=e);const s=ae(r._currentLimitVelocity1,r._currentLimitVelocity2,i);r.direction.length()>s&&r.direction.scaleInPlace(this.limitVelocityDamping)})),this._dragGradients&&this._dragGradients.length>0&&PE.GetCurrentGradient(l,this._dragGradients,((e,t,i)=>{e!==r._currentDragGradient&&(r._currentDrag1=r._currentDrag2,r._currentDrag2=t.getFactor(),r._currentDragGradient=e);const s=ae(r._currentDrag1,r._currentDrag2,i);this._scaledDirection.scaleInPlace(1-s)})),this.isLocal&&r._localPosition?(r._localPosition.addInPlace(this._scaledDirection),_e.TransformCoordinatesToRef(r._localPosition,this._emitterWorldMatrix,r.position)):r.position.addInPlace(this._scaledDirection),o&&t&&r._randomNoiseCoordinates1){const e=this._fetchR(r._randomNoiseCoordinates1.x,r._randomNoiseCoordinates1.y,t.width,t.height,o),i=this._fetchR(r._randomNoiseCoordinates1.z,r._randomNoiseCoordinates2.x,t.width,t.height,o),s=this._fetchR(r._randomNoiseCoordinates2.y,r._randomNoiseCoordinates2.z,t.width,t.height,o),a=ve.Vector3[0],l=ve.Vector3[1];a.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*i-1)*this.noiseStrength.y,(2*s-1)*this.noiseStrength.z),a.scaleToRef(n,l),r.direction.addInPlace(l)}this.gravity.scaleToRef(n,this._scaledGravity),r.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&PE.GetCurrentGradient(l,this._sizeGradients,((e,t,i)=>{e!==r._currentSizeGradient&&(r._currentSize1=r._currentSize2,r._currentSize2=t.getFactor(),r._currentSizeGradient=e),r.size=ae(r._currentSize1,r._currentSize2,i)})),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&PE.GetCurrentGradient(l,this._colorRemapGradients,((e,t,i)=>{const s=ae(e.factor1,t.factor1,i),n=ae(e.factor2,t.factor2,i);r.remapData.x=s,r.remapData.y=n-s})),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&PE.GetCurrentGradient(l,this._alphaRemapGradients,((e,t,i)=>{const s=ae(e.factor1,t.factor1,i),n=ae(e.factor2,t.factor2,i);r.remapData.z=s,r.remapData.w=n-s}))),this._isAnimationSheetEnabled&&r.updateCellIndex(),r._inheritParticleInfoToSubEmitters(),r.age>=r.lifeTime&&(this._emitFromParticle(r),r._attachedSubEmitters&&(r._attachedSubEmitters.forEach((e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()})),r._attachedSubEmitters=null),this.recycleParticle(r),i&&s--)}}}serialize(e){throw new Error("Method not implemented.")}clone(e,t,i=!1){throw new Error("Method not implemented.")}_addFactorGradient(e,t,i,s){const r=new AE(t,i,s);e.push(r),e.sort(((e,t)=>e.gradientt.gradient?1:0))}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const s of e){if(s.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;const e=new Uint8Array(4*this._rawTextureWidth),t=Pe.Color3[0];for(let i=0;i{Ee.LerpToRef(s.color,r.color,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255}))}this._rampGradientsTexture=Oa.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);const i=new EE(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);const s=new CE(e,t,i);return this._colorGradients.push(s),this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(const i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(const e of this._drawWrappers)if(e)for(const t of e)t?.dispose();this._drawWrappers=[]}_fetchR(e,t,i,s,r){return r[4*(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*s%s|0)*i)]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&8!==this.billboardMode&&9!==this.billboardMode||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);const e=this._engine,t=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*t),this._vertexBuffer=new Js(e,this._vertexData,!0,t);let i=0;const s=this._vertexBuffer.createVertexBuffer(er.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[er.PositionKind]=s,i+=3;const r=this._vertexBuffer.createVertexBuffer(er.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[er.ColorKind]=r,i+=4;const n=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=n,i+=1;const o=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,i+=2,this._isAnimationSheetEnabled){const e=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,i+=1}if(!this._isBillboardBased||8===this.billboardMode||9===this.billboardMode){const e=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,i+=3}if(this._useRampGradients){const e=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,i+=4}let a;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Js(e,t,!1,2),a=this._spriteBuffer.createVertexBuffer("offset",0,2)}else a=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=a,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing)return void(this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3])));const e=[],t=[];let i=0;for(let s=0;s{this.start(0)}),e);else{if(this._started=!0,this._stopped=!1,this._actualFrame=0,this._preStart(),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){-1!==this.emitter?.getClassName().indexOf("Mesh")&&this.emitter.computeWorldMatrix(!0);const e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce((()=>{setTimeout((()=>{for(let t=0;t0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,this._postStop(e))}_postStop(e){}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,s){let r=e*this._vertexBufferSize;if(this._vertexData[r++]=t.position.x+this.worldOffset.x,this._vertexData[r++]=t.position.y+this.worldOffset.y,this._vertexData[r++]=t.position.z+this.worldOffset.z,this._vertexData[r++]=t.color.r,this._vertexData[r++]=t.color.g,this._vertexData[r++]=t.color.b,this._vertexData[r++]=t.color.a,this._vertexData[r++]=t.angle,this._vertexData[r++]=t.scale.x*t.size,this._vertexData[r++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[r++]=t.cellIndex),this._isBillboardBased)8!==this.billboardMode&&9!==this.billboardMode||(this._vertexData[r++]=t.direction.x,this._vertexData[r++]=t.direction.y,this._vertexData[r++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(_e.TransformNormalToRef(e,this._emitterWorldMatrix,ve.Vector3[0]),e=ve.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[r++]=e.x,this._vertexData[r++]=e.y,this._vertexData[r++]=e.z}else{let e=t.direction;this.isLocal&&(_e.TransformNormalToRef(e,this._emitterWorldMatrix,ve.Vector3[0]),e=ve.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[r++]=e.x,this._vertexData[r++]=e.y,this._vertexData[r++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[r++]=t.remapData.x,this._vertexData[r++]=t.remapData.y,this._vertexData[r++]=t.remapData.z,this._vertexData[r++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===s?s=this._epsilon:1===s&&(s=1-this._epsilon)),this._vertexData[r++]=i,this._vertexData[r++]=s)}_prepareParticle(e){}_update(e){if(this._alive=this._particles.length>0,this.emitter.position){const e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{const e=this.emitter;this._emitterWorldMatrix=me.Translation(e.x,e.y,e.z)}let t;this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i0){const e=le(this._actualFrame/this.targetStopDuration);PE.GetCurrentGradient(e,this._lifeTimeGradients,((i,s)=>{const r=i,n=s,o=r.getFactor(),a=n.getFactor(),l=(e-r.gradient)/(n.gradient-r.gradient);t.lifeTime=ae(o,a,l)}))}else t.lifeTime=oe(this.minLifeTime,this.maxLifeTime);const e=oe(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),_e.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=oe(this.minSize,this.maxSize),t.scale.copyFromFloats(oe(this.minScaleX,this.maxScaleX),oe(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const e=this._actualFrame/this.targetStopDuration;PE.GetCurrentGradient(e,this._startSizeGradients,((e,i,s)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);const r=ae(this._currentStartSize1,this._currentStartSize2,s);t.scale.scaleInPlace(r)}))}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=oe(this.minAngularSpeed,this.maxAngularSpeed),t.angle=oe(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),this._colorGradients&&0!==this._colorGradients.length)t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);else{const e=oe(0,1);Ae.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new pe(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new _e(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new _e(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const s=[er.PositionKind,er.ColorKind,"angle","offset","size"];return e&&s.push("cellIndex"),t||s.push("direction"),i&&s.push("remapData"),s}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["invView","view","projection","textureMask","translationPivot","eyePosition"];return mo(s),e&&s.push("particlesInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t,i=!0){if(this._scene&&(go(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&0!==this._scene.fogMode&&e.push("#define FOG")),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===Yl.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case 2:e.push("#define BILLBOARDY");break;case 8:case 9:e.push("#define BILLBOARDSTRETCHED"),9===this.billboardMode&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case 7:e.push("#define BILLBOARDMODE_ALL")}i&&this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...RE._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&8!==this.billboardMode&&9!==this.billboardMode,this._useRampGradients)),e.push(...RE._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(Us(e,this._imageProcessingConfigurationDefines),Gs(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);const s=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let r=this._drawWrappers[s];r||(r=this._drawWrappers[s]=[]);let n=r[e];n||(n=new Un(this._engine),n.drawContext&&(n.drawContext.useInstancing=this._useInstancing),r[e]=n);const o=i.join("\n");if(n.defines!==o){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("particles",e,t,i,o),o)}return n}animate(e=!1){if(!this._started)return;if(!e&&this._scene){if(!this.isReady())return;if(this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}let t;if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this.manualEmitCount>-1)t=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const t=this._actualFrame/this.targetStopDuration;PE.GetCurrentGradient(t,this._emitRateGradients,((t,i,s)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=ae(this._currentEmitRate1,this._currentEmitRate2,s)}))}t=e*this._scaledUpdateSpeed|0,this._newPartsExcess+=e*this._scaledUpdateSpeed-t}if(this._newPartsExcess>1&&(t+=0|this._newPartsExcess,this._newPartsExcess-=0|this._newPartsExcess),this._alive=!1,this._stopped?t=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(t),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){let e=0;for(let t=0;t=0&&(r.invertToRef(ve.Matrix[0]),i.setMatrix("invView",ve.Matrix[0])),void 0!==this._vertexArrayObject?this._scene?.forceWireframe?s.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,i):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,i)),this._engine.bindVertexArrayObject(this._vertexArrayObject,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?s.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBuffer:this._indexBuffer,i):s.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null,i),this.useLogarithmicDepth&&this._scene&&So(n,i,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(i),e){case Yl.BLENDMODE_ADD:s.setAlphaMode(1);break;case Yl.BLENDMODE_ONEONE:s.setAlphaMode(6);break;case Yl.BLENDMODE_STANDARD:s.setAlphaMode(2);break;case Yl.BLENDMODE_MULTIPLY:s.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(i),this._useInstancing?this._scene?.forceWireframe?s.drawElementsType(6,0,10,this._particles.length):s.drawArraysType(7,0,4,this._particles.length):this._scene?.forceWireframe?s.drawElementsType(1,0,10*this._particles.length):s.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;const e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===Yl.BLENDMODE_MULTIPLYADD?this._render(Yl.BLENDMODE_MULTIPLY)+this._render(Yl.BLENDMODE_ADD):this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}_onDispose(e=!1,t=!1){}dispose(e=!0,t=!1,i=!1){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._onDispose(t,i),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.clear(),this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}}var ME;!function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(ME||(ME={}));class OE{constructor(e){if(this.particleSystem=e,this.type=ME.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=W("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;e?e instanceof _e?e=e.clone():-1!==e.getClassName().indexOf("Mesh")&&(e=new(W("BABYLON.Mesh"))("",e.getScene()),e.isVisible=!1):e=new _e;const t=new OE(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){const t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,s=!1){throw xt("ParseParticle")}static Parse(e,t,i){const s=e.particleSystem,r=new OE(OE._ParseParticleSystem(s,t,i,!0));return r.type=e.type,r.inheritDirection=e.inheritDirection,r.inheritedVelocityAmount=e.inheritedVelocityAmount,r.particleSystem._isSubEmitter=!0,r}dispose(){this.particleSystem.dispose()}}function DE(e,t){const i=new mE;return i.direction1=e,i.direction2=t,i}function wE(e=1,t=1){return new fE(e,t)}function NE(e=1,t=1){return new gE(e,t)}function FE(e=1,t=new _e(0,1,0),i=new _e(0,1,0)){return new vE(e,t,i)}function LE(e=1,t=1,i=1,s=0){return new _E(e,t,i,s)}function BE(e=1,t=1,i=1,s=new _e(0,1,0),r=new _e(0,1,0)){return new pE(e,t,i,s,r)}function kE(e=1,t=Math.PI/4){return new dE(e,t)}class VE extends RE{constructor(){super(...arguments),this._disposeEmitterOnDispose=!1,this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;const t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach((t=>{if(t.type===ME.END){const i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}}))}}createPointEmitter(e,t){const i=DE(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=wE(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=NE(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new _e(0,1,0),i=new _e(0,1,0)){const s=FE(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=LE(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new _e(0,1,0),r=new _e(0,1,0)){const n=BE(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=kE(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new uE;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}_prepareSubEmitterInternalArray(){this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach((e=>{e instanceof VE?this._subEmitters.push([new OE(e)]):e instanceof OE?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)}))}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach((e=>{e.stop(!0)})),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;const e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_preStart(){this._prepareSubEmitterInternalArray(),this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=[])}_postStop(e){e&&this._stopSubEmitters()}_prepareParticle(e){if(this._subEmitters&&this._subEmitters.length>0){const t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach((t=>{if(t.type===ME.ATTACHED){const i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}}))}}_onDispose(e=!1,t=!1){if(this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),e&&this.particles?.forEach((e=>{if(e._attachedSubEmitters)for(let t=e._attachedSubEmitters.length-1;t>=0;t-=1)e._attachedSubEmitters[t].dispose()})),t&&this.activeSubSystems)for(let e=this.activeSubSystems.length-1;e>=0;e-=1)this.activeSubSystems[e].dispose();if(this._subEmitters&&this._subEmitters.length){for(let e=0;e0?h.shaderOptions.defines.join("\n"):"";l=o.createEffectForParticles(h.shaderPath.fragmentElement,h.shaderOptions.uniforms,h.shaderOptions.samplers,t)}const c=new VE(n,r||e.capacity,t,l,e.isAnimationSheetEnabled);if(c.customShader=h,c._rootUrl=i,e.id&&(c.id=e.id),e.subEmitters){c.subEmitters=[];for(const s of e.subEmitters){const e=[];for(const r of s)e.push(OE.Parse(r,t,i));c.subEmitters.push(e)}}return VE._Parse(e,c,t,i),e.textureMask&&(c.textureMask=Ae.FromArray(e.textureMask)),e.worldOffset&&(c.worldOffset=_e.FromArray(e.worldOffset)),e.preventAutoStart&&(c.preventAutoStart=e.preventAutoStart),s||c.preventAutoStart||c.start(),c}serialize(e=!1){const t={};if(VE._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,t.worldOffset=this.worldOffset.asArray(),this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const s=[];for(const t of i)s.push(t.serialize(e));t.subEmitters.push(s)}}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){const i=t.emitter;e.emitterId=i.id}else{const i=t.emitter;e.emitter=i.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,St.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;const s=t.getColorGradients();if(s){e.colorGradients=[];for(const t of s){const i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}}const r=t.getRampGradients();if(r){e.rampGradients=[];for(const t of r){const i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}const n=t.getColorRemapGradients();if(n){e.colorRemapGradients=[];for(const t of n){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const t of o){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}}const a=t.getSizeGradients();if(a){e.sizeGradients=[];for(const t of a){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}}const l=t.getAngularSpeedGradients();if(l){e.angularSpeedGradients=[];for(const t of l){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}}const h=t.getVelocityGradients();if(h){e.velocityGradients=[];for(const t of h){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}}const c=t.getDragGradients();if(c){e.dragGradients=[];for(const t of c){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}}const u=t.getEmitRateGradients();if(u){e.emitRateGradients=[];for(const t of u){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}}const d=t.getStartSizeGradients();if(d){e.startSizeGradients=[];for(const t of d){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}}const _=t.getLifeTimeGradients();if(_){e.lifeTimeGradients=[];for(const t of _){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}}const p=t.getLimitVelocityGradients();if(p){e.limitVelocityGradients=[];for(const t of p){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}clone(e,t,i=!1){const s={...this._customWrappers};let r=null;const n=this._engine;if(n.createEffectForParticles&&null!=this.customShader){r=this.customShader;const e=r.shaderOptions.defines.length>0?r.shaderOptions.defines.join("\n"):"",t=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,e);s[0]?s[0].effect=t:this.setCustomEffect(t,0)}const o=this.serialize(i),a=VE.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=r,a._customWrappers=s,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,this.preventAutoStart||a.start(),a}}VE.BILLBOARDMODE_Y=2,VE.BILLBOARDMODE_ALL=7,VE.BILLBOARDMODE_STRETCHED=8,VE.BILLBOARDMODE_STRETCHED_LOCAL=9,OE._ParseParticleSystem=VE.Parse;Bi.IncludesShadersStore.clipPlaneFragmentDeclaration2="#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nin float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nin float fClipDistance6;\n#endif\n";Bi.ShadersStore.gpuRenderParticlesPixelShader="precision highp float;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor;\n#include \n#include\n#include\n#include\n#include\n#include\nvoid main() {\n#include \nvec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha);\n#endif \n#include\n#include(color,gl_FragColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor);\n#endif\n#endif\n}\n";Bi.IncludesShadersStore.clipPlaneVertexDeclaration2="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;out float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;out float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;out float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;out float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;out float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;out float fClipDistance6;\n#endif\n";Bi.ShadersStore.gpuRenderParticlesVertexShader="precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset;\n#ifdef LOCAL\nuniform mat4 emitterWM;\n#endif\nattribute vec3 position;attribute float age;attribute float life;attribute vec3 size;\n#ifndef BILLBOARD\nattribute vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\nattribute float angle;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\nattribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#include\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;attribute vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture2D(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x;\n#ifdef BILLBOARD\nvec4 rotatedCorner;rotatedCorner.w=0.;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;\n#ifdef LOCAL\nvec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner;\n#else\nvec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner;\n#endif\nvPositionW=(invView*viewPosition).xyz;\n#endif\n#else\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0);\n#endif\ngl_Position=projection*viewPosition;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#include\n}";class UE extends Yl{static get IsSupported(){if(!re.LastCreatedEngine)return!1;const e=re.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]),void 0,"GPUParticleSystemLinesIndexBuffer")}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}createPointEmitter(e,t){const i=DE(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=wE(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=NE(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new _e(0,1,0),i=new _e(0,1,0)){const s=FE(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=LE(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new _e(0,1,0),r=new _e(0,1,0)){const n=BE(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=kE(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new uE;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady()||this._rebuildingAfterContextLost)return!1;if(this.blendMode!==VE.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else{if(!this._getWrapper(VE.BLENDMODE_MULTIPLY).effect.isReady())return!1;if(!this._getWrapper(VE.BLENDMODE_ADD).effect.isReady())return!1}return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";e?setTimeout((()=>{this.start(0)}),e):(this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop))}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Un(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new K),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[1^this._targetIndex]}get indexBuffer(){return null}_removeGradientAndTexture(e,t,i){return super._removeGradientAndTexture(e,t,i),this._releaseBuffers(),this}addColorGradient(e,t){this._colorGradients||(this._colorGradients=[]);const i=new CE(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))}forceRefreshGradients(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()}removeColorGradient(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this}resetDrawCache(){for(const e in this._drawWrappers){const t=this._drawWrappers[e];t.drawContext?.reset()}}_addFactorGradient(e,t,i){const s=new AE(t,i);e.push(s),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){if(!e)return;i&&e.sort(((e,t)=>e.gradientt.gradient?1:0));const s=this;s[t]&&(s[t].dispose(),s[t]=null)}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,s=null,r=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this._rebuildingAfterContextLost=!1,this.onDisposeObservable=new K,this.onStoppedObservable=new K,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=me.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||re.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!W("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new(W("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!W("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new(W("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new Un(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers={0:new Un(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),(t=t??{}).randomTextureSize||delete t.randomTextureSize;const n={capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize,...t},o=t;isFinite(o)&&(n.capacity=o),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=r,this.particleEmitterType=new uE;const a=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize);let l=[];for(let e=0;e0;)i.push(0)}const o=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),a=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new Js(t,a,!1,this._attributesStrideSize),this._buffer1=new Js(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new Js(t,o,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}_recreateUpdateEffect(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();let e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e)),this._platform.isUpdateBufferReady()}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);let s=this._drawWrappers[e];s||(s=new Un(this._engine),s.drawContext&&(s.drawContext.useInstancing=!0),this._drawWrappers[e]=s);const r=i.join("\n");if(s.defines!==r){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),s.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,r),r)}return s}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,s=!1){const r=[er.PositionKind,"age","life","size","angle"];return e||r.push(er.ColorKind),t&&r.push("cellIndex"),i||r.push("initialDirection"),s&&r.push("direction"),r.push("offset",er.UVKind),r}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return mo(s),e&&s.push("sheetInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t=0,i=!0){if(this._scene&&(go(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==Hr.FOGMODE_NONE&&e.push("#define FOG")),t===VE.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case VE.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case VE.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case VE.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),i&&this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...UE._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===VE.BILLBOARDMODE_STRETCHED)),e.push(...UE._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(zs.PrepareUniforms(e,this._imageProcessingConfigurationDefines),zs.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){const i=this[t];if(!e||!e.length||i)return;const s=new Float32Array(this._rawTextureWidth);for(let t=0;t{s[t]=be.Lerp(e.factor1,i.factor1,r)}))}this[t]=Oa.CreateRTexture(s,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;const e=new Uint8Array(4*this._rawTextureWidth),t=Pe.Color4[0];for(let i=0;i{Ae.LerpToRef(s.color1,r.color1,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a}))}this._colorGradientsTexture=Oa.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){const i=this._getWrapper(e),s=i.effect;this._engine.enableEffect(i);const r=this._scene?.getViewMatrix()||me.IdentityReadOnly;if(s.setMatrix("view",r),s.setMatrix("projection",this.defaultProjectionMatrix??this._scene.getProjectionMatrix()),s.setTexture("diffuseSampler",this.particleTexture),s.setVector2("translationPivot",this.translationPivot),s.setVector3("worldOffset",this.worldOffset),this.isLocal&&s.setMatrix("emitterWM",t),this._colorGradientsTexture?s.setTexture("colorGradientSampler",this._colorGradientsTexture):s.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const e=this.particleTexture.getBaseSize();s.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const e=this._scene.activeCamera;s.setVector3("eyePosition",e.globalPosition)}const n=s.defines;if(this._scene&&(xo(s,this,this._scene),this.applyFog&&Co(this._scene,void 0,s)),n.indexOf("#define BILLBOARDMODE_ALL")>=0){const e=r.clone();e.invert(),s.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&So(n,s,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(s),e){case VE.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case VE.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case VE.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case VE.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,s,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(s),this._scene?.forceWireframe?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),this._scene?.forceWireframe&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer)return;if(!this._recreateUpdateEffect()||this._rebuildingAfterContextLost)return;if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{const t=this.emitter;e=ve.Matrix[0],me.TranslationToRef(t.x,t.y,t.z,e)}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,2===this._targetIndex&&(this._targetIndex=0);const t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){if(!this._started)return 0;if(!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e1){const e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount+=e}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;let i;if(this.emitter.position)i=this.emitter.getWorldMatrix();else{const e=this.emitter;i=ve.Matrix[0],me.TranslationToRef(e.x,e.y,e.z,i)}const s=this._engine;this.updateInAnimate||this._update(i);let r=0;return e||t||(s.setState(!1),this.forceDepthWrite&&s.setDepthWrite(!0),r=this.blendMode===VE.BLENDMODE_MULTIPLYADD?this._render(VE.BLENDMODE_MULTIPLY,i)+this._render(VE.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),r}rebuild(){const e=()=>{this._recreateUpdateEffect()&&this._platform.isUpdateBufferReady()?(this._initialize(!0),this._rebuildingAfterContextLost=!1):setTimeout(e,10)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),this._rebuildingAfterContextLost=!0,e()}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(const e in this._drawWrappers)this._drawWrappers[e].dispose();if(this._drawWrappers={},this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e0?r.shaderOptions.defines.join("\n"):"";s[0]=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,e,void 0,void 0,void 0,this)}const o=this.serialize(i),a=UE.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=r,a._customWrappers=s,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,a}serialize(e=!1){const t={};return VE._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,s=!1,r){const n=e.name;let o,a;t instanceof ns?o=t:(a=t,o=a.getEngine());const l=new UE(n,{capacity:r||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(l._rootUrl=i,e.customShader&&o.createEffectForParticles){const t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",s=o.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,l);l.setCustomEffect(s,0),l.customShader=t}return e.id&&(l.id=e.id),e.activeParticleCount&&(l.activeParticleCount=e.activeParticleCount),VE._Parse(e,l,t,i),e.preventAutoStart&&(l.preventAutoStart=e.preventAutoStart),s||l.preventAutoStart||l.start(),l}}class GE{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1);for(const t of this.systems)t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};const s=_d("emitterSphere",{diameter:e.diameter,segments:e.segments},i);s.renderingGroupId=t;const r=new cu("emitterSphereMaterial",i);r.emissiveColor=e.color,s.material=r;for(const e of this.systems)e.emitter=s;this._emitterNode=s}start(e){for(const t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(const e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){const t={systems:[]};for(const i of this.systems)t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,s){const r=new GE,n=this.BaseAssetsUrl+"/textures/";t=t||re.LastCreatedScene;for(const o of e.systems)r.systems.push(i?UE.Parse(o,t,n,!0,s):VE.Parse(o,t,n,!0,s));if(e.emitter){const i=e.emitter.options;"Sphere"===e.emitter.kind&&r.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:Ee.FromArray(i.color)},e.emitter.renderingGroupId,t)}return r}}GE.BaseAssetsUrl="https://assets.babylonjs.com/particles";class zE{static CreateDefault(e,t=500,i,s=!1){let r;return r=s?new UE("default system",{capacity:t},i):new VE("default system",t,i),r.emitter=e,r.particleTexture=new Pa("https://assets.babylonjs.com/textures/flare.png",r.getScene()),r.createConeEmitter(.1,Math.PI/4),r.color1=new Ae(1,1,1,1),r.color2=new Ae(1,1,1,1),r.colorDead=new Ae(1,1,1,0),r.minSize=.1,r.maxSize=.1,r.minEmitPower=2,r.maxEmitPower=2,r.updateSpeed=1/60,r.emitRate=30,r}static CreateAsync(e,t,i=!1,s){t||(t=re.LastCreatedScene);const r={};return t.addPendingData(r),new Promise(((n,o)=>{if(i&&!UE.IsSupported)return t.removePendingData(r),o("Particle system with GPU is not supported.");Ds.LoadFile(`${zE.BaseAssetsUrl}/systems/${e}.json`,(e=>{t.removePendingData(r);const o=JSON.parse(e.toString());return n(GE.Parse(o,t,i,s))}),void 0,void 0,void 0,(()=>(t.removePendingData(r),o(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`))))}))}static ExportSet(e){const t=new GE;for(const i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,s=!1,r="",n){return new Promise(((o,a)=>{const l=new Pt;l.addEventListener("readystatechange",(()=>{if(4==l.readyState)if(200==l.status){const t=JSON.parse(l.responseText);let a;a=s?UE.Parse(t,i,r,!1,n):VE.Parse(t,i,r,!1,n),e&&(a.name=e),o(a)}else a("Unable to load the particle system")})),l.open("GET",t),l.send()}))}static ParseFromSnippetAsync(e,t,i=!1,s="",r){if("_BLANK"===e){const e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise(((n,o)=>{const a=new Pt;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.particleSystem);let h;h=i?UE.Parse(l,t,s,!1,r):VE.Parse(l,t,s,!1,r),h.snippetId=e,n(h)}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}}zE.BaseAssetsUrl=GE.BaseAssetsUrl,zE.SnippetUrl="https://snippet.babylonjs.com",zE.CreateFromSnippetAsync=zE.ParseFromSnippetAsync,X.AddParser(or.NAME_PARTICLESYSTEM,((e,t,i,s)=>{const r=X.GetIndividualParser(or.NAME_PARTICLESYSTEM);if(r&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,o=e.particleSystems.length;ne.activeParticleCount?UE.Parse(e,t,i):VE.Parse(e,t,i))),ns.prototype.createEffectForParticles=function(e,t=[],i=[],s="",r,n,o,a){let l=[],h=[];const c=[];return a?a.fillUniformsAttributesAndSamplerNames(h,l,c):(l=VE._GetAttributeNamesOrOptions(),h=VE._GetEffectCreationOptions()),-1===s.indexOf(" BILLBOARD")&&(s+="\n#define BILLBOARD\n"),a?.isAnimationSheetEnabled&&-1===s.indexOf(" ANIMATESHEET")&&(s+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:a?.vertexShaderName??"particles",fragmentElement:e},l,h.concat(t),c.concat(i),s,r,n,o)},ha.prototype.getEmittedParticleSystems=function(){const e=[];for(let t=0;tt.sqDistance-e.sqDistance,this._materialSortFunction=(e,t)=>e.materialIndex-t.materialIndex,this._autoUpdateSubMeshes=!1,this._recomputeInvisibles=!1,this.name=e,this._scene=t||re.LastCreatedScene,this._camera=t.activeCamera,this._pickable=!!i&&i.isPickable,this._depthSort=!!i&&i.enableDepthSort,this._multimaterialEnabled=!!i&&i.enableMultiMaterial,this._useModelMaterial=!!i&&i.useModelMaterial,this._multimaterialEnabled=!!this._useModelMaterial||this._multimaterialEnabled,this._expandable=!!i&&i.expandable,this._particlesIntersect=!!i&&i.particleIntersection,this._bSphereOnly=!!i&&i.boundingSphereOnly,this._bSphereRadiusFactor=i&&i.bSphereRadiusFactor?i.bSphereRadiusFactor:1,this._computeBoundingBox=!!i?.computeBoundingBox&&i.computeBoundingBox,this._autoFixFaceOrientation=!!i?.autoFixFaceOrientation&&i.autoFixFaceOrientation,i&&void 0!==i.updatable?this._updatable=i.updatable:this._updatable=!0,this._pickable&&(this.pickedBySubMesh=[[]],this.pickedParticles=this.pickedBySubMesh[0]),(this._depthSort||this._multimaterialEnabled)&&(this.depthSortedParticles=[]),this._multimaterialEnabled&&(this._multimaterial=new ia(this.name+"MultiMaterial",this._scene),this._materials=[],this._materialIndexesById={}),this._tmpVertex=new YE}buildMesh(){if(!this._isNotBuilt&&this.mesh)return this.mesh;if(0===this.nbParticles&&!this.mesh){const e=yd("",{radius:1,tessellation:3},this._scene);this.addShape(e,1),e.dispose()}if(this._indices32=this._needs32Bits?new Uint32Array(this._indices):new Uint16Array(this._indices),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),!this.mesh){const e=new ha(this.name,this._scene);this.mesh=e}!this._updatable&&this._multimaterialEnabled&&this._sortParticlesByMaterial(),this.recomputeNormals&&Wn.ComputeNormals(this._positions32,this._indices32,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals),this._mustUnrotateFixedNormals&&this._unrotateFixedNormals();const e=new Wn;if(e.indices=this._depthSort?this._indices:this._indices32,e.set(this._positions32,er.PositionKind),e.set(this._normals32,er.NormalKind),this._uvs32.length>0&&e.set(this._uvs32,er.UVKind),this._colors32.length>0&&e.set(this._colors32,er.ColorKind),e.applyToMesh(this.mesh,this._updatable),this.mesh.isPickable=this._pickable,this._pickable){let e=0;for(let t=0;td?d:s,i=Math.round(d/s),r=0):i=i>d?d:i;const _=[],p=[],f=[],m=[],g=[],v=_e.Zero(),x=i;for(;ud-i&&(i=d-u),_.length=0,p.length=0,f.length=0,m.length=0,g.length=0;let t=0;for(let e=3*u;e<3*(u+i);e++){f.push(t);const i=o[e],s=3*i;if(_.push(n[s],n[s+1],n[s+2]),p.push(h[s],h[s+1],h[s+2]),a){const e=2*i;m.push(a[e],a[e+1])}if(l){const e=4*i;g.push(l[e],l[e+1],l[e+2],l[e+3])}t++}let s=this.nbParticles;const b=this._posToShape(_),T=this._uvsToShapeUV(m),y=f.slice(),S=g.slice(),C=p.slice();let E;for(v.copyFromFloats(0,0,0),E=0;E65535&&(this._needs32Bits=!0)}if(this._depthSort||this._multimaterialEnabled){const e=null!==b.materialIndex?b.materialIndex:0;this.depthSortedParticles.push(new XE(d,t,r.length,e))}return b}_posToShape(e){const t=[];for(let i=0;i=this.nbParticles||!this._updatable)return[];const s=this.particles,r=this.nbParticles;if(t=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){const e=this.mesh.getBoundingInfo();e&&(v.copyFrom(e.minimum),x.copyFrom(e.maximum))}A=this.particles[e]._pos;const D=A/3|0;I=4*D,M=2*D;for(let i=e;i<=t;i++){const e=this.particles[i];this.updateParticle(e);const t=e._model._shape,r=e._model._shapeUV,c=e._rotationMatrix,u=e.position,D=e.rotation,w=e.scaling,N=e._globalPosition;if(_){const t=this.depthSortedParticles[i];t.idx=e.idx,t.ind=e._ind,t.indicesLength=e._model._indicesLength,t.sqDistance=_e.DistanceSquared(e.position,b)}if(e.alive&&(!e._stillInvisible||e.isVisible||this._recomputeInvisibles)){if(e.isVisible){e._stillInvisible=!1;const i=p[12];if(e.pivot.multiplyToRef(w,i),this.billboard&&(D.x=0,D.y=0),(this._computeParticleRotation||this.billboard)&&e.getRotationMatrix(s),null!==e.parentId){const t=this.getParticleById(e.parentId);if(t){const e=t._rotationMatrix,i=t._globalPosition,r=u.x*e[1]+u.y*e[4]+u.z*e[7],n=u.x*e[0]+u.y*e[3]+u.z*e[6],o=u.x*e[2]+u.y*e[5]+u.z*e[8];if(N.x=i.x+n,N.y=i.y+r,N.z=i.z+o,this._computeParticleRotation||this.billboard){const t=s.m;c[0]=t[0]*e[0]+t[1]*e[3]+t[2]*e[6],c[1]=t[0]*e[1]+t[1]*e[4]+t[2]*e[7],c[2]=t[0]*e[2]+t[1]*e[5]+t[2]*e[8],c[3]=t[4]*e[0]+t[5]*e[3]+t[6]*e[6],c[4]=t[4]*e[1]+t[5]*e[4]+t[6]*e[7],c[5]=t[4]*e[2]+t[5]*e[5]+t[6]*e[8],c[6]=t[8]*e[0]+t[9]*e[3]+t[10]*e[6],c[7]=t[8]*e[1]+t[9]*e[4]+t[10]*e[7],c[8]=t[8]*e[2]+t[9]*e[5]+t[10]*e[8]}}else e.parentId=null}else if(N.x=u.x,N.y=u.y,N.z=u.z,this._computeParticleRotation||this.billboard){const e=s.m;c[0]=e[0],c[1]=e[1],c[2]=e[2],c[3]=e[4],c[4]=e[5],c[5]=e[6],c[6]=e[8],c[7]=e[9],c[8]=e[10]}const n=p[11];for(e.translateFromPivot?n.setAll(0):n.copyFrom(i),O=0;O0)for(let t=0;t(this._isReady=!0,this._buildMesh(e))))}_buildMesh(e){0===this.nbParticles&&this.addPoints(1),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors);const t=new Wn;t.set(this._positions32,er.PositionKind),this._uvs32.length>0&&t.set(this._uvs32,er.UVKind);let i=0;this._colors32.length>0&&(i=1,t.set(this._colors32,er.ColorKind));const s=new ha(this.name,this._scene);t.applyToMesh(s,this._updatable),this.mesh=s,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);let r=e;return r||(r=new cu("point cloud material",this._scene),r.emissiveColor=new Ee(i,i,i),r.disableLighting=!0,r.pointsCloud=!0,r.pointSize=this._size),s.material=r,new Promise((e=>e(s)))}_addParticle(e,t,i,s){const r=new jE(e,t,i,s,this);return this.particles.push(r),r}_randomUnitVector(e){e.position=new _e(Math.random(),Math.random(),Math.random()),e.color=new Ae(1,1,1,1)}_getColorIndicesForCoord(e,t,i,s){const r=e._groupImageData,n=i*(4*s)+4*t,o=[n,n+1,n+2,n+3],a=o[1],l=o[2],h=o[3],c=r[o[0]],u=r[a],d=r[l],_=r[h];return new Ae(c/255,u/255,d/255,_)}_setPointsColorOrUV(e,t,i,s,r,n,o,a){a=a??0,i&&e.updateFacetData();const l=2*e.getBoundingInfo().boundingSphere.radius;let h=e.getVerticesData(er.PositionKind);const c=e.getIndices(),u=e.getVerticesData(er.UVKind+(a?a+1:"")),d=e.getVerticesData(er.ColorKind),_=_e.Zero();e.computeWorldMatrix();const p=e.getWorldMatrix();if(!p.isIdentity()){h=h.slice(0);for(let e=0;e1&&(Re=1),Me<0&&(Me=0),Me>1&&(Me=1),Ee.HSVtoRGBToRef(Ie,Re,Me,we),ue.set(we.r,we.g,we.b,1)):ue=ie.set(Math.random(),Math.random(),Math.random(),1),Fe.color=new Ae(ue.x,ue.y,ue.z,ue.w),this._colors.push(ue.x,ue.y,ue.z,ue.w))}}_colorFromTexture(e,t,i){if(null===e.material)return Ne.Warn(e.name+"has no material."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);const s=e.material.getActiveTextures();if(0===s.length)return Ne.Warn(e.name+"has no usable texture."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);const r=e.clone();r.setEnabled(!1),this._promises.push(new Promise((e=>{ya.WhenAllReady(s,(()=>{let n=t._textureNb;n<0&&(n=0),n>s.length-1&&(n=s.length-1);const o=()=>{t._groupImgWidth=s[n].getSize().width,t._groupImgHeight=s[n].getSize().height,this._setPointsColorOrUV(r,t,i,!0,!0,void 0,void 0,s[n].coordinatesIndex),r.dispose(),e()};t._groupImageData=null;const a=s[n].readPixels();a?a.then((e=>{t._groupImageData=e,o()})):o()}))})))}_calculateDensity(e,t,i){let s,r,n,o,a,l,h,c,u,d,_,p;const f=_e.Zero(),m=_e.Zero(),g=_e.Zero(),v=_e.Zero(),x=_e.Zero(),b=_e.Zero();let T;const y=[];let S=0;const C=i.length/3;for(let e=0;e0;e--){const t=y[e];if(0===t)E[e]=0;else{const i=(t-y[e-1])/t*A,s=Math.floor(i),r=i-s,n=s+Number(Math.random()3)&&(n=$E.Random);const o=e.getVerticesData(er.PositionKind),a=e.getIndices();this._groups.push(this._groupCounter);const l=new KE(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,a),n===$E.Color?l._textureNb=s||0:s=s||new Ae(1,1,1,1),n){case $E.Color:this._colorFromTexture(e,l,!1);break;case $E.UV:this._setPointsColorOrUV(e,l,!1,!1,!1);break;case $E.Random:this._setPointsColorOrUV(e,l,!1);break;case $E.Stated:this._setPointsColorOrUV(e,l,!1,void 0,void 0,s,r)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}addVolumePoints(e,t,i,s,r){let n=i||$E.Random;(isNaN(n)||n<0||n>3)&&(n=$E.Random);const o=e.getVerticesData(er.PositionKind),a=e.getIndices();this._groups.push(this._groupCounter);const l=new KE(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,a),n===$E.Color?l._textureNb=s||0:s=s||new Ae(1,1,1,1),n){case $E.Color:this._colorFromTexture(e,l,!0);break;case $E.UV:this._setPointsColorOrUV(e,l,!0,!1,!1);break;case $E.Random:this._setPointsColorOrUV(e,l,!0);break;case $E.Stated:this._setPointsColorOrUV(e,l,!0,void 0,void 0,s,r)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}setParticles(e=0,t=this.nbParticles-1,i=!0){if(!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(e,t,i);const s=ve.Matrix[0],r=this.mesh,n=this._colors32,o=this._positions32,a=this._uvs32,l=ve.Vector3,h=l[5].copyFromFloats(1,0,0),c=l[6].copyFromFloats(0,1,0),u=l[7].copyFromFloats(0,0,1),d=l[8].setAll(Number.MAX_VALUE),_=l[9].setAll(-Number.MAX_VALUE);me.IdentityToRef(s);let p=0;if(this.mesh?.isFacetDataEnabled&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){const e=this.mesh?.getBoundingInfo();e&&(d.copyFrom(e.minimum),_.copyFrom(e.maximum))}p=0;let f=0,m=0,g=0;for(let i=e;i<=t;i++){const e=this.particles[i];p=e.idx,f=3*p,m=4*p,g=2*p,this.updateParticle(e);const t=e._rotationMatrix,r=e.position,n=e._globalPosition;if(this._computeParticleRotation&&e.getRotationMatrix(s),null!==e.parentId){const i=this.particles[e.parentId],o=i._rotationMatrix,a=i._globalPosition,l=r.x*o[1]+r.y*o[4]+r.z*o[7],h=r.x*o[0]+r.y*o[3]+r.z*o[6],c=r.x*o[2]+r.y*o[5]+r.z*o[8];if(n.x=a.x+h,n.y=a.y+l,n.z=a.z+c,this._computeParticleRotation){const e=s.m;t[0]=e[0]*o[0]+e[1]*o[3]+e[2]*o[6],t[1]=e[0]*o[1]+e[1]*o[4]+e[2]*o[7],t[2]=e[0]*o[2]+e[1]*o[5]+e[2]*o[8],t[3]=e[4]*o[0]+e[5]*o[3]+e[6]*o[6],t[4]=e[4]*o[1]+e[5]*o[4]+e[6]*o[7],t[5]=e[4]*o[2]+e[5]*o[5]+e[6]*o[8],t[6]=e[8]*o[0]+e[9]*o[3]+e[10]*o[6],t[7]=e[8]*o[1]+e[9]*o[4]+e[10]*o[7],t[8]=e[8]*o[2]+e[9]*o[5]+e[10]*o[8]}}else if(n.x=0,n.y=0,n.z=0,this._computeParticleRotation){const e=s.m;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10]}const a=l[11];e.translateFromPivot?a.setAll(0):a.copyFrom(e.pivot);const v=l[0];v.copyFrom(e.position);const x=v.x-e.pivot.x,b=v.y-e.pivot.y,T=v.z-e.pivot.z;let y=x*t[0]+b*t[3]+T*t[6],S=x*t[1]+b*t[4]+T*t[7],C=x*t[2]+b*t[5]+T*t[8];y+=a.x,S+=a.y,C+=a.z;const E=o[f]=n.x+h.x*y+c.x*S+u.x*C,A=o[f+1]=n.y+h.y*y+c.y*S+u.y*C,P=o[f+2]=n.z+h.z*y+c.z*S+u.z*C;if(this._computeBoundingBox&&(d.minimizeInPlaceFromFloats(E,A,P),_.maximizeInPlaceFromFloats(E,A,P)),this._computeParticleColor&&e.color){const t=e.color,i=this._colors32;i[m]=t.r,i[m+1]=t.g,i[m+2]=t.b,i[m+3]=t.a}if(this._computeParticleTexture&&e.uv){const t=e.uv,i=this._uvs32;i[g]=t.x,i[g+1]=t.y}}return r&&(i&&(this._computeParticleColor&&r.updateVerticesData(er.ColorKind,n,!1,!1),this._computeParticleTexture&&r.updateVerticesData(er.UVKind,a,!1,!1),r.updateVerticesData(er.PositionKind,o,!1,!1)),this._computeBoundingBox&&(r.hasBoundingInfo?r.getBoundingInfo().reConstruct(d,_,r._worldMatrix):r.buildBoundingInfo(d,_,r._worldMatrix))),this.afterUpdateParticles(e,t,i),this}dispose(){this.mesh?.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._indices32=null,this._positions32=null,this._uvs32=null,this._colors32=null}refreshVisibleSize(){return this._isVisibilityBoxLocked||this.mesh?.refreshBoundingInfo(),this}setVisibilityBox(e){if(!this.mesh)return;const t=e/2;this.mesh.buildBoundingInfo(new _e(-t,-t,-t),new _e(t,t,t))}get isAlwaysVisible(){return this._alwaysVisible}set isAlwaysVisible(e){this.mesh&&(this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e)}set computeParticleRotation(e){this._computeParticleRotation=e}set computeParticleColor(e){this._computeParticleColor=e}set computeParticleTexture(e){this._computeParticleTexture=e}get computeParticleColor(){return this._computeParticleColor}get computeParticleTexture(){return this._computeParticleTexture}set computeBoundingBox(e){this._computeBoundingBox=e}get computeBoundingBox(){return this._computeBoundingBox}initParticles(){}recycleParticle(e){return e}updateParticle(e){return e}beforeUpdateParticles(e,t,i){}afterUpdateParticles(e,t,i){}}Object.defineProperty(_o.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(e){this._physicsImpostor!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)}))))},enumerable:!0,configurable:!0}),_o.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},_o.prototype.applyImpulse=function(e,t){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(e,t),this):this},_o.prototype.setPhysicsLinkWith=function(e,t,i,s){return this.physicsImpostor&&e.physicsImpostor?(this.physicsImpostor.createJoint(e.physicsImpostor,el.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:s}),this):this};class hA{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw xt("")}constructor(e,t=hA.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new _e(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){const t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,s){this._physicsPlugin.raycast(e,t,i,s)}raycast(e,t,i){const s=new cx;return this._physicsPlugin.raycast(e,t,s,i),s}}!function(e){e[e.FREE=0]="FREE",e[e.LIMITED=1]="LIMITED",e[e.LOCKED=2]="LOCKED"}(qE||(qE={})),function(e){e[e.LINEAR_X=0]="LINEAR_X",e[e.LINEAR_Y=1]="LINEAR_Y",e[e.LINEAR_Z=2]="LINEAR_Z",e[e.ANGULAR_X=3]="ANGULAR_X",e[e.ANGULAR_Y=4]="ANGULAR_Y",e[e.ANGULAR_Z=5]="ANGULAR_Z",e[e.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"}(ZE||(ZE={})),function(e){e[e.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",e[e.DISTANCE=2]="DISTANCE",e[e.HINGE=3]="HINGE",e[e.SLIDER=4]="SLIDER",e[e.LOCK=5]="LOCK",e[e.PRISMATIC=6]="PRISMATIC",e[e.SIX_DOF=7]="SIX_DOF"}(JE||(JE={})),function(e){e[e.SPHERE=0]="SPHERE",e[e.CAPSULE=1]="CAPSULE",e[e.CYLINDER=2]="CYLINDER",e[e.BOX=3]="BOX",e[e.CONVEX_HULL=4]="CONVEX_HULL",e[e.CONTAINER=5]="CONTAINER",e[e.MESH=6]="MESH",e[e.HEIGHTFIELD=7]="HEIGHTFIELD"}(eA||(eA={})),function(e){e[e.NONE=0]="NONE",e[e.VELOCITY=1]="VELOCITY",e[e.POSITION=2]="POSITION"}(tA||(tA={})),function(e){e.COLLISION_STARTED="COLLISION_STARTED",e.COLLISION_CONTINUED="COLLISION_CONTINUED",e.COLLISION_FINISHED="COLLISION_FINISHED",e.TRIGGER_ENTERED="TRIGGER_ENTERED",e.TRIGGER_EXITED="TRIGGER_EXITED"}(iA||(iA={})),function(e){e[e.STATIC=0]="STATIC",e[e.ANIMATED=1]="ANIMATED",e[e.DYNAMIC=2]="DYNAMIC"}(sA||(sA={})),function(e){e[e.SIMULATION_CONTROLLED=0]="SIMULATION_CONTROLLED",e[e.ALWAYS_ACTIVE=1]="ALWAYS_ACTIVE",e[e.ALWAYS_INACTIVE=2]="ALWAYS_INACTIVE"}(rA||(rA={}));class cA{constructor(e,t,i,s){if(this._pluginData=void 0,this._pluginDataInstances=[],this._collisionCBEnabled=!1,this._collisionEndedCBEnabled=!1,this.disablePreStep=!0,this.disableSync=!1,this._isDisposed=!1,this._shape=null,!s)return;const r=s.getPhysicsEngine();if(!r)throw new Error("No Physics Engine available.");if(this._physicsEngine=r,2!=r.getPluginVersion())throw new Error("Plugin version is incorrect. Expected version 2.");const n=r.getPhysicsPlugin();if(!n)throw new Error("No Physics Plugin available.");this._physicsPlugin=n,e.rotationQuaternion||(e.rotationQuaternion=fe.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z)),this.startAsleep=i,this._motionType=t,this.disableSync=t==sA.STATIC;const o=e;o.hasThinInstances?this._physicsPlugin.initBodyInstances(this,t,o):(e.parent&&e.computeWorldMatrix(!0),this._physicsPlugin.initBody(this,t,e.absolutePosition,e.absoluteRotationQuaternion)),this.transformNode=e,e.physicsBody=this,r.addBody(this),this._nodeDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}getClassName(){return"PhysicsBody"}clone(e){const t=new cA(e,this.getMotionType(),this.startAsleep,this.transformNode.getScene());return t.shape=this.shape,t.setMassProperties(this.getMassProperties()),t.setLinearDamping(this.getLinearDamping()),t.setAngularDamping(this.getAngularDamping()),t}updateBodyInstances(){const e=this.transformNode;e.hasThinInstances&&this._physicsPlugin.updateBodyInstances(this,e)}get numInstances(){return this._pluginDataInstances.length}get motionType(){return this._motionType}set shape(e){this._shape=e,e&&this._physicsPlugin.setShape(this,e)}get shape(){return this._shape}getBoundingBox(){return this._physicsPlugin.getBodyBoundingBox(this)}setEventMask(e,t){this._physicsPlugin.setEventMask(this,e,t)}getEventMask(e){return this._physicsPlugin.getEventMask(this,e)}setMotionType(e,t){this.disableSync=e==sA.STATIC,this._physicsPlugin.setMotionType(this,e,t)}getMotionType(e){return this._physicsPlugin.getMotionType(this,e)}computeMassProperties(e){return this._physicsPlugin.computeMassProperties(this,e)}setMassProperties(e,t){this._physicsPlugin.setMassProperties(this,e,t)}getMassProperties(e){return this._physicsPlugin.getMassProperties(this,e)}setLinearDamping(e,t){this._physicsPlugin.setLinearDamping(this,e,t)}getLinearDamping(e){return this._physicsPlugin.getLinearDamping(this,e)}setAngularDamping(e,t){this._physicsPlugin.setAngularDamping(this,e,t)}getAngularDamping(e){return this._physicsPlugin.getAngularDamping(this,e)}setLinearVelocity(e,t){this._physicsPlugin.setLinearVelocity(this,e,t)}getLinearVelocityToRef(e,t){this._physicsPlugin.getLinearVelocityToRef(this,e,t)}getLinearVelocity(e){const t=new _e;return this.getLinearVelocityToRef(t,e),t}setAngularVelocity(e,t){this._physicsPlugin.setAngularVelocity(this,e,t)}getAngularVelocityToRef(e,t){this._physicsPlugin.getAngularVelocityToRef(this,e,t)}getAngularVelocity(e){const t=new _e;return this.getAngularVelocityToRef(t,e),t}applyImpulse(e,t,i){this._physicsPlugin.applyImpulse(this,e,t,i)}applyAngularImpulse(e,t){this._physicsPlugin.applyAngularImpulse(this,e,t)}applyForce(e,t,i){this._physicsPlugin.applyForce(this,e,t,i)}getGeometry(){return this._physicsPlugin.getBodyGeometry(this)}getCollisionObservable(){return this._physicsPlugin.getCollisionObservable(this)}getCollisionEndedObservable(){return this._physicsPlugin.getCollisionEndedObservable(this)}setCollisionCallbackEnabled(e){this._collisionCBEnabled=e,this._physicsPlugin.setCollisionCallbackEnabled(this,e)}setCollisionEndedCallbackEnabled(e){this._collisionEndedCBEnabled=e,this._physicsPlugin.setCollisionEndedCallbackEnabled(this,e)}getObjectCenterWorld(e){const t=new _e;return this.getObjectCenterWorldToRef(t,e)}getObjectCenterWorldToRef(e,t){if(this._pluginDataInstances?.length>0){const i=t||0,s=this.transformNode._thinInstanceDataStorage.matrixData;s&&e.set(s[16*i+12],s[16*i+13],s[16*i+14])}else e.copyFrom(this.transformNode.position);return e}addConstraint(e,t,i,s){this._physicsPlugin.addConstraint(this,e,t,i,s)}syncWithBone(e,t,i,s,r,n){const o=this.transformNode;if(o.rotationQuaternion)if(r){const i=ve.Quaternion[0];e.getRotationQuaternionToRef(Ur.WORLD,t,i),i.multiplyToRef(r,o.rotationQuaternion)}else e.getRotationQuaternionToRef(Ur.WORLD,t,o.rotationQuaternion);const a=ve.Vector3[0],l=ve.Vector3[1];n||((n=ve.Vector3[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,a),null==s&&i&&(s=i.length()),null!=s&&(a.x+=l.x*s,a.y+=l.y*s,a.z+=l.z*s),o.setAbsolutePosition(a)}iterateOverAllInstances(e){if(this._pluginDataInstances?.length>0)for(let t=0;t{this.dispose()}))}_getObjectBoundingBox(){return this.transformNode.getRawBoundingInfo?this.transformNode.getRawBoundingInfo().boundingBox:new Mn(new _e(-.5,-.5,-.5),new _e(.5,.5,.5))}_hasVertices(e){return e?.getTotalVertices()>0}_addSizeOptions(){this.transformNode.computeWorldMatrix(!0);const e=this._getObjectBoundingBox(),t=ve.Vector3[0];t.copyFrom(e.extendSize),t.scaleInPlace(2),t.multiplyInPlace(this.transformNode.absoluteScaling),t.x=Math.abs(t.x),t.y=Math.abs(t.y),t.z=Math.abs(t.z);const i=ve.Vector3[1];if(i.copyFrom(e.minimum),i.multiplyInPlace(this.transformNode.absoluteScaling),!this._options.center){const t=new _e;t.copyFrom(e.center),t.multiplyInPlace(this.transformNode.absoluteScaling),this._options.center=t}switch(this.type){case eA.SPHERE:!this._options.radius&&be.WithinEpsilon(t.x,t.y,1e-4)&&be.WithinEpsilon(t.x,t.z,1e-4)?this._options.radius=t.x/2:this._options.radius||(Ne.Warn("Non uniform scaling is unsupported for sphere shapes. Setting the radius to the biggest bounding box extent."),this._options.radius=Math.max(t.x,t.y,t.z)/2);break;case eA.CAPSULE:{const e=t.x/2;this._options.radius=this._options.radius??e,this._options.pointA=this._options.pointA??new _e(0,i.y+e,0),this._options.pointB=this._options.pointB??new _e(0,i.y+t.y-e,0)}break;case eA.CYLINDER:{const e=t.x/2;this._options.radius=this._options.radius??e,this._options.pointA=this._options.pointA??new _e(0,i.y,0),this._options.pointB=this._options.pointB??new _e(0,i.y+t.y,0)}break;case eA.MESH:case eA.CONVEX_HULL:if(!this._options.mesh&&this._hasVertices(this.transformNode))this._options.mesh=this.transformNode;else if(!this._options.mesh||!this._hasVertices(this._options.mesh))throw new Error("No valid mesh was provided for mesh or convex hull shape parameter. Please provide a mesh with valid geometry (number of vertices greater than 0).");break;case eA.BOX:this._options.extents=this._options.extents??new _e(t.x,t.y,t.z),this._options.rotation=this._options.rotation??fe.Identity()}}dispose(){this._nodeDisposeObserver&&(this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver),this._nodeDisposeObserver=null),this.body.dispose(),this._disposeShapeWhenDisposed&&this.shape.dispose()}}class MA{}class OA{constructor(e,t,i){this._boxConfigs=new Array,this._joints=new Array,this._bones=new Array,this._initialRotation=new Array,this._initialRotation2=new Array,this._boneNames=[],this._transforms=new Array,this._aggregates=new Array,this._ragdollMode=!1,this._rootBoneName="",this._rootBoneIndex=-1,this._mass=10,this._restitution=0,this.pauseSync=!1,this._defaultJoint=JE.HINGE,this._defaultJointMin=-90,this._defaultJointMax=90,this._skeleton=e,this._scene=e.getScene(),this._rootTransformNode=t,this._config=i,this._boxConfigs=[],this._putBoxesInBoneCenter=!1,this._defaultJoint=JE.HINGE,this._init()}getAggregate(e){return e<0||e>=this._aggregates.length?this._aggregates[this._rootBoneIndex]:this._aggregates[e]}_createColliders(){this._rootTransformNode.computeWorldMatrix(),this._skeleton.computeAbsoluteMatrices(!0),this._skeleton.prepare(!0);const e=this._config;for(let t=0;t{this._syncBonesAndBoxes()})),this._syncBonesToPhysics())}ragdoll(){this._ragdollMode=!0,this._skeleton.bones.forEach((e=>{e.linkTransformNode(null)}));for(let e=0;e{e.dispose()}))}}class DA{constructor(e,t,i){this._vertices=[],this._indices=[],this._isRightHanded=i.useRightHandedSystem,this._collectIndices=t}addNodeMeshes(e,t){e.computeWorldMatrix(!0);const i=ve.Matrix[0];if(me.ScalingToRef(e.absoluteScaling.x,e.absoluteScaling.y,e.absoluteScaling.z,i),e instanceof ha?this._addMesh(e,i):e instanceof ca&&this._addMesh(e.sourceMesh,i),t){const t=ve.Matrix[1];e.computeWorldMatrix().invertToRef(t);const s=ve.Matrix[2];t.multiplyToRef(i,s),e.getChildMeshes(!1).filter((e=>!e.physicsBody)).forEach((e=>{const t=e.computeWorldMatrix(),i=ve.Matrix[3];t.multiplyToRef(s,i),e instanceof ha?this._addMesh(e,i):e instanceof ca&&this._addMesh(e.sourceMesh,i)}))}}_addMesh(e,t){const i=e.getVerticesData(er.PositionKind)||[],s=i.length/3,r=this._vertices.length;for(let e=0;e0)for(const t of e._pluginDataInstances)this._bodyCollisionObservable.delete(t.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,t.hpBodyId),this._bodies.delete(t.hpBodyId[0]);e._pluginData&&(this._bodyCollisionObservable.delete(e._pluginData.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,e._pluginData.hpBodyId),this._bodies.delete(e._pluginData.hpBodyId[0]))}initBodyInstances(e,t,i){const s=i._thinInstanceDataStorage?.instancesCount??0,r=i._thinInstanceDataStorage.matrixData;r&&(this._createOrUpdateBodyInstances(e,t,r,0,s,!1),e._pluginDataInstances.forEach(((t,i)=>{this._bodies.set(t.hpBodyId[0],{body:e,index:i})})))}_createOrUpdateBodyInstances(e,t,i,s,r,n){const o=ve.Quaternion[0],a=me.Identity();for(let l=s;lr){this._createOrUpdateBodyInstances(e,n,s,r,i,!1);const t=this._hknp.HP_Body_GetShape(e._pluginDataInstances[0].hpBodyId)[1];t[0]||(t[0]=e.shape?._pluginData[0]);for(let s=r;s{this._hknp.HP_Body_SetEventMask(e.hpBodyId,t)}),i)}getEventMask(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1]}_fromMassPropertiesTuple(e){return{centerOfMass:_e.FromArray(e[0]),mass:e[1],inertia:_e.FromArray(e[2]),inertiaOrientation:fe.FromArray(e[3])}}_internalUpdateMassProperties(e){const t=this._internalComputeMassProperties(e),i=e.userMassProps;i.centerOfMass&&(t[0]=i.centerOfMass.asArray()),null!=i.mass&&(t[1]=i.mass),i.inertia&&(t[2]=i.inertia.asArray()),i.inertiaOrientation&&(t[3]=i.inertiaOrientation.asArray()),this._hknp.HP_Body_SetMassProperties(e.hpBodyId,t)}_internalSetMotionType(e,t){switch(t){case sA.STATIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.STATIC);break;case sA.ANIMATED:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.KINEMATIC);break;case sA.DYNAMIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.DYNAMIC)}}setMotionType(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._internalSetMotionType(e,t)}),i)}getMotionType(e,t){const i=this._getPluginReference(e,t),s=this._hknp.HP_Body_GetMotionType(i.hpBodyId)[1];switch(s){case this._hknp.MotionType.STATIC:return sA.STATIC;case this._hknp.MotionType.KINEMATIC:return sA.ANIMATED;case this._hknp.MotionType.DYNAMIC:return sA.DYNAMIC}throw new Error("Unknown motion type: "+s)}setActivationControl(e,t){switch(t){case rA.ALWAYS_ACTIVE:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_ACTIVE);break;case rA.ALWAYS_INACTIVE:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_INACTIVE);break;case rA.SIMULATION_CONTROLLED:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.SIMULATION_CONTROLLED)}}_internalComputeMassProperties(e){const t=this._hknp.HP_Body_GetShape(e.hpBodyId);if(t[0]==this._hknp.Result.RESULT_OK){const e=this._hknp.HP_Shape_BuildMassProperties(t[1]);if(e[0]==this._hknp.Result.RESULT_OK)return e[1]}return[[0,0,0],1,[1,1,1],[0,0,0,1]]}computeMassProperties(e,t){const i=this._getPluginReference(e,t),s=this._internalComputeMassProperties(i);return this._fromMassPropertiesTuple(s)}setMassProperties(e,t,i){this._applyToBodyOrInstances(e,(e=>{e.userMassProps=t,this._internalUpdateMassProperties(e)}),i)}getMassProperties(e,t){const i=this._getPluginReference(e,t),s=this._hknp.HP_Body_GetMassProperties(i.hpBodyId)[1];return this._fromMassPropertiesTuple(s)}setLinearDamping(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetLinearDamping(e.hpBodyId,t)}),i)}getLinearDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetLinearDamping(i.hpBodyId)[1]}setAngularDamping(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetAngularDamping(e.hpBodyId,t)}),i)}getAngularDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetAngularDamping(i.hpBodyId)[1]}setLinearVelocity(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetLinearVelocity(e.hpBodyId,this._bVecToV3(t))}),i)}getLinearVelocityToRef(e,t,i){const s=this._getPluginReference(e,i),r=this._hknp.HP_Body_GetLinearVelocity(s.hpBodyId)[1];this._v3ToBvecRef(r,t)}_applyToBodyOrInstances(e,t,i){if(e._pluginDataInstances?.length>0&&void 0===i)for(let i=0;i{this._hknp.HP_Body_ApplyImpulse(e.hpBodyId,this._bVecToV3(i),this._bVecToV3(t))}),s)}applyAngularImpulse(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_ApplyAngularImpulse(e.hpBodyId,this._bVecToV3(t))}),i)}applyForce(e,t,i,s){t.scaleToRef(this.getTimeStep(),this._tmpVec3[0]),this.applyImpulse(e,this._tmpVec3[0],i,s)}setAngularVelocity(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetAngularVelocity(e.hpBodyId,this._bVecToV3(t))}),i)}getAngularVelocityToRef(e,t,i){const s=this._getPluginReference(e,i),r=this._hknp.HP_Body_GetAngularVelocity(s.hpBodyId)[1];this._v3ToBvecRef(r,t)}setPhysicsBodyTransformation(e,t){const i=e.transformNode;if(e.numInstances>0){const t=i._thinInstanceDataStorage.matrixData;if(!t)return;const s=e.numInstances;this._createOrUpdateBodyInstances(e,e.getMotionType(),t,0,s,!0)}else this._hknp.HP_Body_SetQTransform(e._pluginData.hpBodyId,this._getTransformInfos(t))}setTargetTransform(e,t,i,s){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetTargetQTransform(e.hpBodyId,[this._bVecToV3(t),this._bQuatToV4(i)])}),s)}setGravityFactor(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetGravityFactor(e.hpBodyId,t)}),i)}getGravityFactor(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetGravityFactor(i.hpBodyId)[1]}disposeBody(e){if(e._pluginDataInstances&&e._pluginDataInstances.length>0)for(const t of e._pluginDataInstances)this._hknp.HP_Body_Release(t.hpBodyId),t.hpBodyId=void 0;e._pluginData&&(this._hknp.HP_Body_Release(e._pluginData.hpBodyId),e._pluginData.hpBodyId=void 0)}initShape(e,t,i){switch(t){case eA.SPHERE:{const t=i.radius||1,s=i.center?this._bVecToV3(i.center):[0,0,0];e._pluginData=this._hknp.HP_Shape_CreateSphere(s,t)[1]}break;case eA.BOX:{const t=i.rotation?this._bQuatToV4(i.rotation):[0,0,0,1],s=i.extents?this._bVecToV3(i.extents):[1,1,1],r=i.center?this._bVecToV3(i.center):[0,0,0];e._pluginData=this._hknp.HP_Shape_CreateBox(r,t,s)[1]}break;case eA.CAPSULE:{const t=i.pointA?this._bVecToV3(i.pointA):[0,0,0],s=i.pointB?this._bVecToV3(i.pointB):[0,1,0],r=i.radius||0;e._pluginData=this._hknp.HP_Shape_CreateCapsule(t,s,r)[1]}break;case eA.CONTAINER:e._pluginData=this._hknp.HP_Shape_CreateContainer()[1];break;case eA.CYLINDER:{const t=i.pointA?this._bVecToV3(i.pointA):[0,0,0],s=i.pointB?this._bVecToV3(i.pointB):[0,1,0],r=i.radius||0;e._pluginData=this._hknp.HP_Shape_CreateCylinder(t,s,r)[1]}break;case eA.CONVEX_HULL:case eA.MESH:{const s=i.mesh;if(!s)throw new Error("No mesh provided to create physics shape.");{const r=!!i.includeChildMeshes,n=t!=eA.CONVEX_HULL,o=new DA(s,n,s?.getScene());o.addNodeMeshes(s,r);const a=o.getVertices(this._hknp),l=a.numObjects/3;if(t==eA.CONVEX_HULL)e._pluginData=this._hknp.HP_Shape_CreateConvexHull(a.offset,l)[1];else{const t=o.getTriangles(this._hknp),i=t.numObjects/3;e._pluginData=this._hknp.HP_Shape_CreateMesh(a.offset,l,t.offset,i)[1],o.freeBuffer(this._hknp,t)}o.freeBuffer(this._hknp,a)}}break;case eA.HEIGHTFIELD:if(!(i.numHeightFieldSamplesX&&i.numHeightFieldSamplesZ&&i.heightFieldSizeX&&i.heightFieldSizeZ&&i.heightFieldData))throw new Error("Missing required heightfield parameters");{const t=i.numHeightFieldSamplesX*i.numHeightFieldSamplesZ,s=4*t,r=this._hknp._malloc(s),n=new Float32Array(this._hknp.HEAPU8.buffer,r,t);for(let e=0;e0?e._pluginDataInstances[0]:e._pluginData,i=this._hknp.HP_Body_GetShape(t.hpBodyId)[1],s=this._hknp.HP_Shape_CreateDebugDisplayGeometry(i);if(s[0]!=this._hknp.Result.RESULT_OK)return{positions:[],indices:[]};const r=this._hknp.HP_DebugGeometry_GetInfo(s[1])[1],n=new Float32Array(this._hknp.HEAPU8.buffer,r[0],3*r[1]),o=new Uint32Array(this._hknp.HEAPU8.buffer,r[2],3*r[3]),a=n.slice(0),l=o.slice(0);return this._hknp.HP_DebugGeometry_Release(s[1]),{positions:a,indices:l}}disposeShape(e){this._hknp.HP_Shape_Release(e._pluginData),e._pluginData=void 0}initConstraint(e,t,i,s,r){const n=e.type,o=e.options;if(!n||!o)return void Ne.Warn("No constraint type or options. Constraint is invalid.");if(t._pluginDataInstances.length>0&&void 0===s||i._pluginDataInstances.length>0&&void 0===r)return void Ne.Warn("Body is instanced but no instance index was specified. Constraint will not be applied.");e._pluginData=e._pluginData??[];const a=this._hknp.HP_Constraint_Create()[1];e._pluginData.push(a);const l=this._getPluginReference(t,s).hpBodyId,h=this._getPluginReference(i,r).hpBodyId;this._hknp.HP_Constraint_SetParentBody(a,l),this._hknp.HP_Constraint_SetChildBody(a,h),this._constraintToBodyIdPair.set(a[0],[l[0],h[0]]);const c=o.pivotA?this._bVecToV3(o.pivotA):this._bVecToV3(_e.Zero()),u=o.axisA??new _e(1,0,0),d=this._tmpVec3[0];o.perpAxisA?d.copyFrom(o.perpAxisA):u.getNormalToRef(d),this._hknp.HP_Constraint_SetAnchorInParent(a,c,this._bVecToV3(u),this._bVecToV3(d));const _=o.pivotB?this._bVecToV3(o.pivotB):this._bVecToV3(_e.Zero()),p=o.axisB??new _e(1,0,0),f=this._tmpVec3[0];if(o.perpAxisB?f.copyFrom(o.perpAxisB):p.getNormalToRef(f),this._hknp.HP_Constraint_SetAnchorInChild(a,_,this._bVecToV3(p),this._bVecToV3(f)),e._initOptions||(e._initOptions={axisA:u.clone(),axisB:p.clone(),perpAxisA:d.clone(),perpAxisB:f.clone(),pivotA:new _e(c[0],c[1],c[2]),pivotB:new _e(_[0],_[1],_[2])}),n==JE.LOCK)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==JE.DISTANCE){const e=o.maxDistance||0,t=this._hknp.ConstraintAxis.LINEAR_DISTANCE;this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(a,t,e),this._hknp.HP_Constraint_SetAxisMaxLimit(a,t,e)}else if(n==JE.HINGE)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==JE.PRISMATIC)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==JE.SLIDER)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==JE.BALL_AND_SOCKET)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else{if(n!=JE.SIX_DOF)throw new Error("Unsupported Constraint Type.");{const t=e;for(const e of t.limits){const t=this._constraintAxisToNative(e.axis);0==(e.minLimit??-1)&&0==(e.maxLimit??-1)?this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LOCKED):(null!=e.minLimit&&(this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(a,t,e.minLimit)),null!=e.maxLimit&&(this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMaxLimit(a,t,e.maxLimit))),e.stiffness&&this._hknp.HP_Constraint_SetAxisStiffness(a,t,e.stiffness),e.damping&&this._hknp.HP_Constraint_SetAxisDamping(a,t,e.damping)}}}const m=!!o.collision;this._hknp.HP_Constraint_SetCollisionsEnabled(a,m),this._hknp.HP_Constraint_SetEnabled(a,!0)}getBodiesUsingConstraint(e){const t=[];for(const i of e._pluginData){const e=this._constraintToBodyIdPair.get(i[0]);if(e){const i=this._bodies.get(e[0]),s=this._bodies.get(e[1]);i&&s&&t.push({parentBody:i.body,parentBodyIndex:i.index,childBody:s.body,childBodyIndex:s.index})}}return t}addConstraint(e,t,i,s,r){this.initConstraint(i,e,t,s,r)}setEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetEnabled(i,t)}getEnabled(e){const t=e._pluginData&&e._pluginData[0];return!!t&&this._hknp.HP_Constraint_GetEnabled(t)[1]}setCollisionsEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetCollisionsEnabled(i,t)}getCollisionsEnabled(e){const t=e._pluginData&&e._pluginData[0];return!!t&&this._hknp.HP_Constraint_GetCollisionsEnabled(t)[1]}setAxisFriction(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisFriction(s,this._constraintAxisToNative(t),i)}getAxisFriction(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisFriction(i,this._constraintAxisToNative(t))[1]:null}setAxisMode(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMode(s,this._constraintAxisToNative(t),this._limitModeToNative(i))}getAxisMode(e,t){const i=e._pluginData&&e._pluginData[0];if(i){const e=this._hknp.HP_Constraint_GetAxisMode(i,this._constraintAxisToNative(t))[1];return this._nativeToLimitMode(e)}return null}setAxisMinLimit(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMinLimit(s,this._constraintAxisToNative(t),i)}getAxisMinLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMinLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMaxLimit(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMaxLimit(s,this._constraintAxisToNative(t),i)}getAxisMaxLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMaxLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMotorType(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorType(s,this._constraintAxisToNative(t),this._constraintMotorTypeToNative(i))}getAxisMotorType(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._nativeToMotorType(this._hknp.HP_Constraint_GetAxisMotorType(i,this._constraintAxisToNative(t))[1]):null}setAxisMotorTarget(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorTarget(s,this._constraintAxisToNative(t),i)}getAxisMotorTarget(e,t){return e._pluginData&&e._pluginData[0]?this._hknp.HP_Constraint_GetAxisMotorTarget(e._pluginData,this._constraintAxisToNative(t))[1]:null}setAxisMotorMaxForce(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorMaxForce(s,this._constraintAxisToNative(t),i)}getAxisMotorMaxForce(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMotorMaxForce(i,this._constraintAxisToNative(t))[1]:null}disposeConstraint(e){for(const t of e._pluginData)this._hknp.HP_Constraint_SetEnabled(t,!1),this._hknp.HP_Constraint_Release(t);e._pluginData.length=0}_populateHitData(e,t){const i=this._bodies.get(e[0][0]);t.body=i?.body,t.bodyIndex=i?.index;const s=this._shapes.get(e[1][0]);t.shape=s;const r=e[3],n=e[4],o=e[5];t.setHitData({x:n[0],y:n[1],z:n[2]},{x:r[0],y:r[1],z:r[2]},o)}raycast(e,t,i,s){const r=s?.membership??-1,n=s?.collideWith??-1;i.reset(e,t);const o=[BigInt(0)],a=[this._bVecToV3(e),this._bVecToV3(t),[r,n],!1,o];if(this._hknp.HP_World_CastRayWithCollector(this.world,this._queryCollector,a),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[,e]=this._hknp.HP_QueryCollector_GetCastRayResult(this._queryCollector,0)[1];this._populateHitData(e,i),i.calculateHitDistance()}}pointProximity(e,t){const i=e?.collisionFilter?.membership??-1,s=e?.collisionFilter?.collideWith??-1;t.reset();const r=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[this._bVecToV3(e.position),e.maxDistance,[i,s],e.shouldHitTriggers,r];if(this._hknp.HP_World_PointProximityWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,i]=this._hknp.HP_QueryCollector_GetPointProximityResult(this._queryCollector,0)[1];this._populateHitData(i,t),t.setHitDistance(e)}}shapeProximity(e,t,i){t.reset(),i.reset();const s=e.shape._pluginData,r=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[s,this._bVecToV3(e.position),this._bQuatToV4(e.rotation),e.maxDistance,e.shouldHitTriggers,r];if(this._hknp.HP_World_ShapeProximityWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,s,r]=this._hknp.HP_QueryCollector_GetShapeProximityResult(this._queryCollector,0)[1];this._populateHitData(s,t),this._populateHitData(r,i),t.setHitDistance(e),i.setHitDistance(e)}}shapeCast(e,t,i){t.reset(),i.reset();const s=e.shape._pluginData,r=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[s,this._bQuatToV4(e.rotation),this._bVecToV3(e.startPosition),this._bVecToV3(e.endPosition),e.shouldHitTriggers,r];if(this._hknp.HP_World_ShapeCastWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,s,r]=this._hknp.HP_QueryCollector_GetShapeCastResult(this._queryCollector,0)[1];this._populateHitData(s,t),this._populateHitData(r,i),t.setHitFraction(e),i.setHitFraction(e)}}getCollisionObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionObservable.get(t);return i||(i=new K,this._bodyCollisionObservable.set(t,i)),i}getCollisionEndedObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionEndedObservable.get(t);return i||(i=new K,this._bodyCollisionEndedObservable.set(t,i)),i}setCollisionCallbackEnabled(e,t){const i=this._hknp.EventType.COLLISION_STARTED.value|this._hknp.EventType.COLLISION_CONTINUED.value|this._hknp.EventType.COLLISION_FINISHED.value;e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach((e=>{this._hknp.HP_Body_SetEventMask(e.hpBodyId,t?i:0)})):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,t?i:0)}setCollisionEndedCallbackEnabled(e,t){const i=this._getPluginReference(e);let s=this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1];s=t?s|this._hknp.EventType.COLLISION_FINISHED.value:s&~this._hknp.EventType.COLLISION_FINISHED.value,e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach((e=>{this._hknp.HP_Body_SetEventMask(e.hpBodyId,s)})):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,s)}_notifyTriggers(){let e=this._hknp.HP_World_GetTriggerEvents(this.world)[1];const t=new LA;for(;e;){LA.readToRef(this._hknp.HEAPU8.buffer,e,t);const i=this._bodies.get(t.bodyIdA),s=this._bodies.get(t.bodyIdB);if(i&&s){const e={collider:i.body,colliderIndex:i.index,collidedAgainst:s.body,collidedAgainstIndex:s.index,type:this._nativeTriggerCollisionValueToCollisionType(t.type)};this.onTriggerCollisionObservable.notifyObservers(e)}e=this._hknp.HP_World_GetNextTriggerEvent(this.world,e)}}_notifyCollisions(){let e=this._hknp.HP_World_GetCollisionEvents(this.world)[1];const t=new FA,i=Number(this.world);for(;e;){FA.readToRef(this._hknp.HEAPU8.buffer,e,t);const s=this._bodies.get(t.contactOnA.bodyId),r=this._bodies.get(t.contactOnB.bodyId);if(s&&r){const e={collider:s.body,colliderIndex:s.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,type:this._nativeCollisionValueToCollisionType(t.type)};if(e.type===iA.COLLISION_FINISHED)this.onCollisionEndedObservable.notifyObservers(e);else{t.contactOnB.position.subtractToRef(t.contactOnA.position,this._tmpVec3[0]);const i=_e.Dot(this._tmpVec3[0],t.contactOnA.normal);e.point=t.contactOnA.position,e.distance=i,e.impulse=t.impulseApplied,e.normal=t.contactOnA.normal,this.onCollisionObservable.notifyObservers(e)}if(this._bodyCollisionObservable.size&&e.type!==iA.COLLISION_FINISHED){const i=this._bodyCollisionObservable.get(t.contactOnA.bodyId),n=this._bodyCollisionObservable.get(t.contactOnB.bodyId);i?i.notifyObservers(e):n&&(e.collider=r.body,e.colliderIndex=r.index,e.collidedAgainst=s.body,e.collidedAgainstIndex=s.index,e.normal=t.contactOnB.normal,n.notifyObservers(e))}else if(this._bodyCollisionEndedObservable.size){const i=this._bodyCollisionEndedObservable.get(t.contactOnA.bodyId),n=this._bodyCollisionEndedObservable.get(t.contactOnB.bodyId);i?i.notifyObservers(e):n&&(e.collider=r.body,e.colliderIndex=r.index,e.collidedAgainst=s.body,e.collidedAgainstIndex=s.index,e.normal=t.contactOnB.normal,n.notifyObservers(e))}}e=this._hknp.HP_World_GetNextCollisionEvent(i,e)}}get numBodies(){return this._hknp.HP_World_GetNumBodies(this.world)[1]}dispose(){this._queryCollector&&(this._hknp.HP_QueryCollector_Release(this._queryCollector),this._queryCollector=void 0),this.world&&(this._hknp.HP_World_Release(this.world),this.world=void 0)}_v3ToBvecRef(e,t){t.set(e[0],e[1],e[2])}_bVecToV3(e){return[e._x,e._y,e._z]}_bQuatToV4(e){return[e._x,e._y,e._z,e._w]}_constraintMotorTypeToNative(e){switch(e){case tA.POSITION:return this._hknp.ConstraintMotorType.POSITION;case tA.VELOCITY:return this._hknp.ConstraintMotorType.VELOCITY}return this._hknp.ConstraintMotorType.NONE}_nativeToMotorType(e){switch(e){case this._hknp.ConstraintMotorType.POSITION:return tA.POSITION;case this._hknp.ConstraintMotorType.VELOCITY:return tA.VELOCITY}return tA.NONE}_materialCombineToNative(e){switch(e){case nA.GEOMETRIC_MEAN:return this._hknp.MaterialCombine.GEOMETRIC_MEAN;case nA.MINIMUM:return this._hknp.MaterialCombine.MINIMUM;case nA.MAXIMUM:return this._hknp.MaterialCombine.MAXIMUM;case nA.ARITHMETIC_MEAN:return this._hknp.MaterialCombine.ARITHMETIC_MEAN;case nA.MULTIPLY:return this._hknp.MaterialCombine.MULTIPLY}}_nativeToMaterialCombine(e){switch(e){case this._hknp.MaterialCombine.GEOMETRIC_MEAN:return nA.GEOMETRIC_MEAN;case this._hknp.MaterialCombine.MINIMUM:return nA.MINIMUM;case this._hknp.MaterialCombine.MAXIMUM:return nA.MAXIMUM;case this._hknp.MaterialCombine.ARITHMETIC_MEAN:return nA.ARITHMETIC_MEAN;case this._hknp.MaterialCombine.MULTIPLY:return nA.MULTIPLY;default:return}}_constraintAxisToNative(e){switch(e){case ZE.LINEAR_X:return this._hknp.ConstraintAxis.LINEAR_X;case ZE.LINEAR_Y:return this._hknp.ConstraintAxis.LINEAR_Y;case ZE.LINEAR_Z:return this._hknp.ConstraintAxis.LINEAR_Z;case ZE.ANGULAR_X:return this._hknp.ConstraintAxis.ANGULAR_X;case ZE.ANGULAR_Y:return this._hknp.ConstraintAxis.ANGULAR_Y;case ZE.ANGULAR_Z:return this._hknp.ConstraintAxis.ANGULAR_Z;case ZE.LINEAR_DISTANCE:return this._hknp.ConstraintAxis.LINEAR_DISTANCE}}_nativeToLimitMode(e){switch(e){case this._hknp.ConstraintAxisLimitMode.FREE:return qE.FREE;case this._hknp.ConstraintAxisLimitMode.LIMITED:return qE.LIMITED;case this._hknp.ConstraintAxisLimitMode.LOCKED:return qE.LOCKED}return qE.FREE}_limitModeToNative(e){switch(e){case qE.FREE:return this._hknp.ConstraintAxisLimitMode.FREE;case qE.LIMITED:return this._hknp.ConstraintAxisLimitMode.LIMITED;case qE.LOCKED:return this._hknp.ConstraintAxisLimitMode.LOCKED}}_nativeCollisionValueToCollisionType(e){switch(e){case this._hknp.EventType.COLLISION_STARTED.value:return iA.COLLISION_STARTED;case this._hknp.EventType.COLLISION_FINISHED.value:return iA.COLLISION_FINISHED;case this._hknp.EventType.COLLISION_CONTINUED.value:return iA.COLLISION_CONTINUED}return iA.COLLISION_STARTED}_nativeTriggerCollisionValueToCollisionType(e){switch(e){case 8:return iA.TRIGGER_ENTERED;case 16:return iA.TRIGGER_EXITED}return iA.TRIGGER_ENTERED}}Hr.prototype.getPhysicsEngine=function(){return this._physicsEngine},Hr.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(or.NAME_PHYSICSENGINE);i||(i=new kA(this),this._addComponent(i));try{if(t&&1!==t?.getPluginVersion()){if(2!==t?.getPluginVersion())throw new Error("Unsupported Physics plugin version.");this._physicsEngine=new hA(e,t)}else this._physicsEngine=new ux(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return Ne.Error(e.message),!1}},Hr.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},Hr.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},Hr.prototype.deleteCompoundImpostor=function(e){const t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},Hr.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){const t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class kA{constructor(e){this.name=or.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new K,this.scene.onAfterPhysicsObservable=new K,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?1e3*this.scene._physicsEngine.getTimeStep():1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(lo.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)}))))},enumerable:!0,configurable:!0}),lo.prototype.getPhysicsBody=function(){return this.physicsBody},lo.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this},lo.prototype.applyAngularImpulse=function(e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyAngularImpulse(e),this};class VA{static GetContactPointToRef(e,t,i,s,r){const n=e.getScene().getPhysicsEngine(),o=n?.getPluginVersion();if(1===o){const r=new Ua(t,i).intersectsMesh(e);if(r.hit&&r.pickedPoint)return s.copyFrom(r.pickedPoint),!0}else if(2===o)return e.physicsBody.getObjectCenterWorldToRef(s,r),!0;return!1}static HasAppliedForces(e,t){return e.getMotionType(t)===sA.STATIC||0===(e.getMassProperties(t)?.mass??0)||0===e.transformNode?.getTotalVertices()}static IsInsideCylinder(e,t,i,s){const r=ve.Vector3[0];return e.subtractToRef(t,r),Math.abs(r.x)<=i&&Math.abs(r.z)<=i&&r.y>=0&&r.y<=s}}class UA{constructor(e){this._hitData={force:new _e,contactPoint:new _e,distanceFromOrigin:0},this._scene=e,this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine||Ne.Warn("Physics engine not enabled. Please enable the physics before you can use the methods.")}applyRadialExplosionImpulse(e,t,i,s){if(!this._physicsEngine)return Ne.Warn("Physics engine not enabled. Please enable the physics before you call this method."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;let r=!1;if("number"==typeof t){const e=t;(t=new XA).radius=e,t.strength=i??t.strength,t.falloff=s??t.falloff}else r=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);const n=new GA(this._scene,t),o=this._hitData;if(1===this._physicsEngine.getPluginVersion()){const t=Array();this._physicsEngine.getImpostors().forEach((i=>{n.getImpostorHitData(i,e,o)&&(i.applyImpulse(o.force,o.contactPoint),r&&t.push({impostor:i,hitData:this._copyPhysicsHitData(o)}))})),n.triggerAffectedImpostorsCallback(t)}else this._applicationForBodies(n,e,o,r,((e,t)=>{e.applyImpulse(t.force,t.contactPoint,t.instanceIndex)}));return n.dispose(!1),n}applyRadialExplosionForce(e,t,i,s){if(!this._physicsEngine)return Ne.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;let r=!1;if("number"==typeof t){const e=t;(t=new XA).radius=e,t.strength=i??t.strength,t.falloff=s??t.falloff}else r=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);const n=new GA(this._scene,t),o=this._hitData;if(1===this._physicsEngine.getPluginVersion()){const t=Array();this._physicsEngine.getImpostors().forEach((i=>{n.getImpostorHitData(i,e,o)&&(i.applyForce(o.force,o.contactPoint),r&&t.push({impostor:i,hitData:this._copyPhysicsHitData(o)}))})),n.triggerAffectedImpostorsCallback(t)}else this._applicationForBodies(n,e,o,r,((e,t)=>{e.applyForce(t.force,t.contactPoint,t.instanceIndex)}));return n.dispose(!1),n}_applicationForBodies(e,t,i,s,r){const n=Array(),o=this._physicsEngine.getBodies();for(const a of o)a.iterateOverAllInstances(((o,a)=>{e.getBodyHitData(o,t,i,a)&&(r(o,i),s&&n.push({body:o,hitData:this._copyPhysicsHitData(i)}))}));e.triggerAffectedBodiesCallback(n)}gravitationalField(e,t,i,s){if(!this._physicsEngine)return Ne.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new XA).radius=e,t.strength=i??t.strength,t.falloff=s??t.falloff}const r=new zA(this,this._scene,e,t);return r.dispose(!1),r}updraft(e,t,i,s,r){if(!this._physicsEngine)return Ne.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new YA).radius=e,t.strength=i??t.strength,t.height=s??t.height,t.updraftMode=r??t.updraftMode}const n=new WA(this._scene,e,t);return n.dispose(!1),n}vortex(e,t,i,s){if(!this._physicsEngine)return Ne.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new QA).radius=e,t.strength=i??t.strength,t.height=s??t.height}const r=new HA(this._scene,e,t);return r.dispose(!1),r}_copyPhysicsHitData(e){return{force:e.force.clone(),contactPoint:e.contactPoint.clone(),distanceFromOrigin:e.distanceFromOrigin,instanceIndex:e.instanceIndex}}}class GA{constructor(e,t){this._scene=e,this._options=t,this._dataFetched=!1,this._options={...new XA,...this._options}}getData(){return this._dataFetched=!0,{sphere:this._sphere}}_getHitData(e,t,i,s){const r=ve.Vector3[0];r.copyFrom(t).subtractInPlace(i);const n=ve.Vector3[1];if(!VA.GetContactPointToRef(e,i,r,n,s.instanceIndex))return!1;const o=_e.Distance(i,n);if(o>this._options.radius)return!1;const a=this._options.falloff===oA.Constant?this._options.strength:this._options.strength*(1-o/this._options.radius);return r.scaleInPlace(a),s.force.copyFrom(r),s.contactPoint.copyFrom(n),s.distanceFromOrigin=o,!0}getBodyHitData(e,t,i,s){if(VA.HasAppliedForces(e,s))return!1;const r=e.transformNode,n=e.getObjectCenterWorld(s);return i.instanceIndex=s,this._getHitData(r,n,t,i)}getImpostorHitData(e,t,i){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const s=e.object;if(!this._intersectsWithSphere(s,t,this._options.radius))return!1;const r=e.getObjectCenter();return this._getHitData(s,r,t,i),!0}triggerAffectedImpostorsCallback(e){this._options.affectedImpostorsCallback&&this._options.affectedImpostorsCallback(e)}triggerAffectedBodiesCallback(e){this._options.affectedBodiesCallback&&this._options.affectedBodiesCallback(e)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout((()=>{this._dataFetched||this._sphere.dispose()}),0))}_prepareSphere(){this._sphere||(this._sphere=_d("radialExplosionEventSphere",this._options.sphere,this._scene),this._sphere.isVisible=!1)}_intersectsWithSphere(e,t,i){return this._prepareSphere(),this._sphere.position=t,this._sphere.scaling.setAll(2*i),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(e,!0)}}class zA{constructor(e,t,i,s){this._physicsHelper=e,this._scene=t,this._origin=i,this._options=s,this._dataFetched=!1,this._options={...new XA,...this._options},this._tickCallback=()=>this._tick(),this._options.strength=-1*this._options.strength}getData(){return this._dataFetched=!0,{sphere:this._sphere}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout((()=>{this._dataFetched||this._sphere.dispose()}),0))}_tick(){if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);else{const e=this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);e&&(this._sphere=e.getData().sphere?.clone("radialExplosionEventSphereClone"))}}}class WA{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=_e.Zero(),this._originDirection=_e.Zero(),this._cylinderPosition=_e.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new YA,...this._options},this._origin.addToRef(new _e(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new _e(0,this._options.height,0),this._originTop),this._options.updraftMode===aA.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout((()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)}),0))}_getHitData(e,t){let i;i=this._options.updraftMode===aA.Perpendicular?this._originDirection:e.subtract(this._originTop);const s=_e.Distance(this._origin,e),r=-1*this._options.strength,n=i.multiplyByFloats(r,r,r);t.force.copyFrom(n),t.contactPoint.copyFrom(e),t.distanceFromOrigin=s}_getBodyHitData(e,t,i){if(VA.HasAppliedForces(e))return!1;const s=e.getObjectCenterWorld(i);return!!VA.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(s,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const s=e.getObjectCenter();return this._getHitData(s,t),!0}_tick(){const e=WA._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=$u("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))}}WA._HitData={force:new _e,contactPoint:new _e,distanceFromOrigin:0};class HA{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=_e.Zero(),this._cylinderPosition=_e.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new QA,...this._options},this._origin.addToRef(new _e(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new _e(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout((()=>{this._dataFetched||this._cylinder.dispose()}),0))}_getHitData(e,t,i){const s=HA._OriginOnPlane;s.set(this._origin.x,t.y,this._origin.z);const r=ve.Vector3[0];t.subtractToRef(s,r);const n=ve.Vector3[1];if(!VA.GetContactPointToRef(e,s,r,n,i.instanceIndex))return!1;const o=_e.Distance(n,s)/this._options.radius,a=ve.Vector3[2];let l,h,c;if(n.normalizeToRef(a),o>this._options.centripetalForceThreshold&&a.negateInPlace(),o>this._options.centripetalForceThreshold)l=a.x*this._options.centripetalForceMultiplier,h=a.y*this._options.updraftForceMultiplier,c=a.z*this._options.centripetalForceMultiplier;else{const e=_e.Cross(s,t).normalize();l=(e.x+a.x)*this._options.centrifugalForceMultiplier,h=this._originTop.y*this._options.updraftForceMultiplier,c=(e.z+a.z)*this._options.centrifugalForceMultiplier}const u=ve.Vector3[3];return u.set(l,h,c),u.scaleInPlace(this._options.strength),i.force.copyFrom(u),i.contactPoint.copyFrom(t),i.distanceFromOrigin=o,!0}_getBodyHitData(e,t,i){if(VA.HasAppliedForces(e,i))return!1;const s=e.transformNode,r=e.getObjectCenterWorld(i);return!!VA.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(s,r,t))}_getImpostorHitData(e,t){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const s=e.getObjectCenter();return this._getHitData(i,s,t),!0}_tick(){const e=HA._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=$u("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}}HA._OriginOnPlane=_e.Zero(),HA._HitData={force:new _e,contactPoint:new _e,distanceFromOrigin:0};class XA{constructor(){this.radius=5,this.strength=10,this.falloff=oA.Constant,this.sphere={segments:32,diameter:1}}}class YA{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=aA.Center}}class QA{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}!function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"}(oA||(oA={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(aA||(aA={}));class jA extends hx{constructor(){super(...arguments),this._hitDistance=0}get hitDistance(){return this._hitDistance}setHitDistance(e){this._hitDistance=e}reset(){super.reset(),this._hitDistance=0}}class KA extends hx{constructor(){super(...arguments),this._hitFraction=0}get hitFraction(){return this._hitFraction}setHitFraction(e){this._hitFraction=e}}Bi.ShadersStore.blackAndWhitePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}";class $A extends Vl{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,s,r,n){super(e,"blackAndWhite",["degree"],null,t,i,s,r,n),this.degree=1,this.onApplyObservable.add((e=>{e.setFloat("degree",this.degree)}))}static _Parse(e,t,i,s){return St.Parse((()=>new $A(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}Ze([rt()],$A.prototype,"degree",void 0),z("BABYLON.BlackAndWhitePostProcess",$A);class qA{constructor(e,t,i,s){this._name=t,this._singleInstance=s||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let e=0;e{const t=s.attachPostProcess(e);this._indicesForCamera[r].push(t)})),this._cameras[r]||(this._cameras[r]=s)}}_detachCameras(e){const t=Ds.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)})),this._cameras[s]&&(this._cameras[s]=null),delete this._indicesForCamera[s]}}_enable(e){const t=Ds.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)}))}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}Bi.ShadersStore.extractHighlightsPixelShader="#include\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}";class ZA extends Vl{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,s,r,n,null,o,void 0,null,a),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add((e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess),e.setFloat("threshold",Math.pow(this.threshold,$)),e.setFloat("exposure",this._exposure)}))}}Ze([rt()],ZA.prototype,"threshold",void 0),z("BABYLON.ExtractHighlightsPostProcess",ZA);Bi.ShadersStore.bloomMergePixelShader="uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); }\n";class JA extends Vl{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,s,r,n,o,a,l,h=0,c=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],r,n,o,a,l,null,h,void 0,null,!0),this.weight=1,this.weight=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)})),c||this.updateEffect()}}Ze([rt()],JA.prototype,"weight",void 0),z("BABYLON.BloomMergePostProcess",JA);class eP extends qA{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,s,r=0,n=!1){super(e.getEngine(),"bloom",(()=>this._effects),!0),this._bloomScale=t,this._effects=[],this._downscale=new ZA("highlights",1,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._blurX=new mg("horizontal blur",new de(1,0),10,t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new mg("vertical blur",new de(0,1),10,t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=s,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new JA("bloomMerge",this._downscale,this._blurY,i,t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)}))}static _Parse(e,t,i,s){return St.Parse((()=>new tP(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,s)}}Ze([rt()],tP.prototype,"aberrationAmount",void 0),Ze([rt()],tP.prototype,"radialIntensity",void 0),Ze([rt()],tP.prototype,"direction",void 0),Ze([rt()],tP.prototype,"centerPosition",void 0),Ze([rt()],tP.prototype,"screenWidth",void 0),Ze([rt()],tP.prototype,"screenHeight",void 0),z("BABYLON.ChromaticAberrationPostProcess",tP);Bi.ShadersStore.circleOfConfusionPixelShader="uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float depth=texture2D(depthSampler,vUV).r;\n#define CUSTOM_COC_DEPTH\nfloat pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; \n#define CUSTOM_COC_PIXELDISTANCE\nfloat coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);}\n";class iP extends Vl{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,s,r,n,o,a=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,s,r,n,o,null,a,void 0,null,l),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add((e=>{if(!this._depthTexture)return void Ne.Warn("No depth texture set on CircleOfConfusionPostProcess");e.setTexture("depthSampler",this._depthTexture);const t=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",t);const i=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",i.minZ,i.maxZ-i.minZ)}))}set depthTexture(e){this._depthTexture=e}}Ze([rt()],iP.prototype,"lensSize",void 0),Ze([rt()],iP.prototype,"fStop",void 0),Ze([rt()],iP.prototype,"focusDistance",void 0),Ze([rt()],iP.prototype,"focalLength",void 0),z("BABYLON.CircleOfConfusionPostProcess",iP);Bi.ShadersStore.colorCorrectionPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D colorTable; \nvarying vec2 vUV;const float SLICE_COUNT=16.0; \nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}";class sP extends Vl{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"colorCorrection",null,["colorTable"],i,s,r,n,o);const a=s?.getScene()||null;this._colorTableTexture=new Pa(t,a,!0,!1,Pa.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=Pa.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=Pa.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,s){return St.Parse((()=>new sP(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}Ze([rt()],sP.prototype,"colorTableUrl",void 0),z("BABYLON.ColorCorrectionPostProcess",sP);Bi.ShadersStore.convolutionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9];\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}";class rP extends Vl{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,s,r,n,o,a=0){super(e,"convolution",["kernel","screenSize"],null,i,s,r,n,o,null,a),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,s){return St.Parse((()=>new rP(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType)),e,i,s)}}rP.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],rP.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],rP.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],rP.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],rP.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],rP.GaussianKernel=[0,1,0,1,1,1,0,1,0],Ze([rt()],rP.prototype,"kernel",void 0),z("BABYLON.ConvolutionPostProcess",rP);class nP extends mg{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,s,r,n,o,a=null,l=Pa.BILINEAR_SAMPLINGMODE,h,c,u=0,d=!1,_=5){super(e,i,s,r,n,2,h,c,u,"#define DOF 1\n",d,_),this.direction=i,this.externalTextureSamplerBinding=!!a,this.onApplyObservable.add((e=>{null!=a&&e.setTextureFromPostProcess("textureSampler",a),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)}))}}Ze([rt()],nP.prototype,"direction",void 0),z("BABYLON.DepthOfFieldBlurPostProcess",nP);Bi.ShadersStore.depthOfFieldMergePixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;\n#if BLUR_LEVEL==0\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);}\n#endif\n#if BLUR_LEVEL==2\nif(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);}\n#endif\n}\n";class oP extends Vl{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,s,r,n,o,a,l,h=0,c=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],r,n,o,a,l,null,h,void 0,null,!0),this._blurSteps=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),s.forEach(((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(s.length-i-1),t)}))})),c||this.updateEffect()}updateEffect(e=null,t=null,i=null,s,r,n){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,s,r,n)}}var aP;!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(aP||(aP={}));class lP extends qA{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=aP.Low,s=0,r=!1){super(e.getEngine(),"depth of field",(()=>this._effects),!0),this._effects=[];const n=e.getEngine(),o=n.isWebGPU||n.version>1?6:5;this._circleOfConfusion=new iP("circleOfConfusion",t,1,null,Pa.BILINEAR_SAMPLINGMODE,n,!1,s,r),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let a=1,l=15;switch(i){case aP.High:a=3,l=51;break;case aP.Medium:a=2,l=31;break;default:l=15,a=1}const h=l/Math.pow(2,a-1);let c=1;for(let t=0;tnew hP(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}z("BABYLON.DisplayPassPostProcess",hP);Bi.ShadersStore.filterPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}";class cP extends Vl{getClassName(){return"FilterPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"filter",["kernelMatrix"],null,i,s,r,n,o),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,s){return St.Parse((()=>new cP(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}Ze([ft()],cP.prototype,"kernelMatrix",void 0),z("BABYLON.FilterPostProcess",cP);Bi.ShadersStore.fxaaPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)\n{lumaN=lumaW;}\nif (!horzSpan) \n{lumaS=lumaE;}\nif (horzSpan) \n{lengthSign=texelSize.y;}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN)\n{lengthSign=-lengthSign;}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) \n{posB.x+=lengthSign*0.5;}\nif (horzSpan)\n{posB.y+=lengthSign*0.5;}\nvec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) \n{lumaNN=lumaSS;}\nfloat gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) \n{posN.x-=offNP.x*3.0;}\nif (!doneN) \n{posN.y-=offNP.y*3.0;}\nbool doneNP=(!doneN) || (!doneP);if (!doneP) \n{posP.x+=offNP.x*3.0;}\nif (!doneP)\n{posP.y+=offNP.y*3.0;}\nif (doneNP)\n{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;}\nfloat dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan)\n{dstN=posM.y-posN.y;}\nif (!horzSpan) \n{dstP=posP.y-posM.y;}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{const t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)}))}_getDefines(){const e=this.getEngine();return e&&e.extractDriverInfo().toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,s){return St.Parse((()=>new uP(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}z("BABYLON.FxaaPostProcess",uP);Bi.ShadersStore.grainPixelShader="#include\nuniform sampler2D textureSampler; \nuniform float intensity;uniform float animatedSeed;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}";class dP extends Vl{getClassName(){return"GrainPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,s,r,n,null,o,void 0,null,a),this.intensity=30,this.animated=!1,this.onApplyObservable.add((e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)}))}static _Parse(e,t,i,s){return St.Parse((()=>new dP(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}Ze([rt()],dP.prototype,"intensity",void 0),Ze([rt()],dP.prototype,"animated",void 0),z("BABYLON.GrainPostProcess",dP);Bi.ShadersStore.highlightsPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }";class _P extends Vl{getClassName(){return"HighlightsPostProcess"}constructor(e,t,i,s,r,n,o=0){super(e,"highlights",null,null,t,i,s,r,n,null,o)}}Bi.ShadersStore.imageProcessingPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;}";class pP extends Vl{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null;const t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){const i=t.scenes;e=i[i.length-1]}else e=re.LastCreatedScene;this._imageProcessingConfiguration=e?e.imageProcessingConfiguration:new zs}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateParameters()}))),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,s,r,n,o=0,a){super(e,"imageProcessing",[],[],t,i,s,r,n,null,o,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:0,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},a?(a.applyByPostProcess=!0,this._attachImageProcessingConfiguration(a,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const t in this._defines){const i=this._defines[t];switch(typeof i){case"number":case"string":e+=`#define ${t} ${i};\n`;break;default:i&&(e+=`#define ${t};\n`)}}const t=["textureSampler"],i=["scale"];zs&&(zs.PrepareSamplers(t,this._defines),zs.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}Ze([rt()],pP.prototype,"_fromLinearSpace",void 0);Bi.IncludesShadersStore.mrtFragmentDeclaration="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n";Bi.ShadersStore.geometryPixelShader="#extension GL_EXT_draw_buffers : require\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\nprecision highp float;\n#ifdef BUMP\nvarying mat4 vWorldView;varying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nvarying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#ifdef NEED_UV\nvarying vec2 vUV;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIVITY)\n#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nuniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV;\n#endif\n#ifdef ALBEDOTEXTURE\nvarying vec2 vAlbedoUV;uniform sampler2D albedoSampler;\n#endif\n#ifdef REFLECTIVITYCOLOR\nuniform vec3 reflectivityColor;\n#endif\n#ifdef ALBEDOCOLOR\nuniform vec3 albedoColor;\n#endif\n#ifdef METALLIC\nuniform float metallic;\n#endif\n#if defined(ROUGHNESS) || defined(GLOSSINESS)\nuniform float glossiness;\n#endif\n#endif\n#if defined(ALPHATEST) && defined(NEED_UV)\nuniform sampler2D diffuseSampler;\n#endif\n#include\n#include[RENDER_TARGET_COUNT]\n#include\n#include\n#include\nvoid main() {\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nvec3 normalOutput;\n#ifdef BUMP\nvec3 normalW=normalize(vNormalW);\n#include\n#ifdef NORMAL_WORLDSPACE\nnormalOutput=normalW;\n#else\nnormalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0)));\n#endif\n#else\nnormalOutput=normalize(vNormalV);\n#endif\n#ifdef ENCODE_NORMAL\nnormalOutput=normalOutput*0.5+0.5;\n#endif\n#ifdef PREPASS\n#ifdef PREPASS_DEPTH\ngl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n#endif\n#ifdef PREPASS_NORMAL\ngl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0);\n#endif\n#else\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0);\n#endif\n#ifdef POSITION\ngl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);\n#endif\n#ifdef REFLECTIVITY\nvec4 reflectivity=vec4(0.0,0.0,0.0,1.0);\n#ifdef METALLICWORKFLOW\nfloat metal=1.0;float roughness=1.0;\n#ifdef ORMTEXTURE\nmetal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g;\n#endif\n#ifdef METALLIC\nmetal*=metallic;\n#endif\n#ifdef ROUGHNESS\nroughness*=(1.0-glossiness); \n#endif\nreflectivity.a-=roughness;vec3 color=vec3(1.0);\n#ifdef ALBEDOTEXTURE\ncolor=texture2D(albedoSampler,vAlbedoUV).rgb;\n#ifdef GAMMAALBEDO\ncolor=toLinearSpace(color);\n#endif\n#endif\n#ifdef ALBEDOCOLOR\ncolor*=albedoColor.xyz;\n#endif\nreflectivity.rgb=mix(vec3(0.04),color,metal);\n#else\n#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nreflectivity=texture2D(reflectivitySampler,vReflectivityUV);\n#ifdef GAMMAREFLECTIVITYTEXTURE\nreflectivity.rgb=toLinearSpace(reflectivity.rgb);\n#endif\n#else \n#ifdef REFLECTIVITYCOLOR\nreflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0;\n#endif\n#endif\n#ifdef GLOSSINESSS\nreflectivity.a*=glossiness; \n#endif\n#endif\ngl_FragData[REFLECTIVITY_INDEX]=reflectivity;\n#endif\n}\n";Bi.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;";Bi.IncludesShadersStore.geometryUboDeclaration="#include\n";Bi.ShadersStore.geometryVertexShader="precision highp float;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include<__decl__geometryVertex>\n#include\nattribute vec3 position;attribute vec3 normal;\n#ifdef NEED_UV\nvarying vec2 vUV;\n#ifdef ALPHATEST\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef BUMP\nuniform mat4 bumpMatrix;varying vec2 vBumpUV;\n#endif\n#ifdef REFLECTIVITY\nuniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef BUMP\nvarying mat4 vWorldView;\n#endif\n#ifdef BUMP\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nuniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include\n#include\nvec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0));\n#ifdef BUMP\nvWorldView=view*finalWorld;vNormalW=normalUpdated;\n#else\n#ifdef NORMAL_WORLDSPACE\nvNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#else\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));\n#endif\n#endif\nvViewPos=view*worldPos;\n#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n#if defined(POSITION) || defined(BUMP)\nvPositionW=worldPos.xyz/worldPos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#include\n#ifdef NEED_UV\n#ifdef UV1\n#if defined(ALPHATEST) && defined(ALPHATEST_UV1)\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#else\nvUV=uv;\n#endif\n#ifdef BUMP_UV1\nvBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV1\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV1\nvAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#endif\n#ifdef UV2\n#if defined(ALPHATEST) && defined(ALPHATEST_UV2)\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#else\nvUV=uv2;\n#endif\n#ifdef BUMP_UV2\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV2\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV2\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#endif\n#include\n}\n";const fP=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];mo(fP);class mP{get normalsAreUnsigned(){return this._normalsAreUnsigned}_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add((()=>{})))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===mP.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===mP.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===mP.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===mP.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===mP.NORMAL_TEXTURE_TYPE&&(this._normalIndex=t)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case mP.POSITION_TEXTURE_TYPE:return this._positionIndex;case mP.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case mP.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case mP.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case mP.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return-1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return"object"==typeof this._ratioOrDimensions?1:this._ratioOrDimensions}constructor(e,t=1,i=15,s){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new Ae(0,0,0,0),this._clearDepthColor=new Ae(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=s||{},mP._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const s=[],r=[er.PositionKind,er.NormalKind],n=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(s.push("#define ALPHATEST"),s.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&$c.BumpTextureEnabled&&(s.push("#define BUMP"),s.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(i.metallicRoughnessTexture&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!=i.metallic&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),t=!0),null!=i.roughness&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),t=!0),t&&(i.baseTexture&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),e=!0),i.baseColor&&s.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(i.specularGlossinessTexture?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor&&s.push("#define REFLECTIVITYCOLOR"),null!=i.glossiness&&s.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(i.metallicTexture&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!=i.metallic&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),t=!0),null!=i.roughness&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),t=!0),t?(i.albedoTexture&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),e=!0),i.albedoColor&&s.push("#define ALBEDOCOLOR")):(i.reflectivityTexture?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):i.reflectivityColor&&s.push("#define REFLECTIVITYCOLOR"),null!=i.microSurface&&s.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(i.specularTexture&&(s.push("#define REFLECTIVITYTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),i.specularColor&&s.push("#define REFLECTIVITYCOLOR"))}e&&(s.push("#define NEED_UV"),n.isVerticesDataPresent(er.UVKind)&&(r.push(er.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(er.UV2Kind)&&(r.push(er.UV2Kind),s.push("#define UV2")))}this._linkedWithPrePass&&(s.push("#define PREPASS"),-1!==this._depthIndex&&(s.push("#define DEPTH_INDEX "+this._depthIndex),s.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(s.push("#define NORMAL_INDEX "+this._normalIndex),s.push("#define PREPASS_NORMAL"))),this._enablePosition&&(s.push("#define POSITION"),s.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(s.push("#define VELOCITY"),s.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(n)&&s.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(s.push("#define REFLECTIVITY"),s.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&s.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&s.push("#define ENCODE_NORMAL"),n.useBones&&n.computeBonesUsingShaders&&n.skeleton?(r.push(er.MatricesIndicesKind),r.push(er.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(er.MatricesIndicesExtraKind),r.push(er.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BONETEXTURE "+n.skeleton.isUsingTextureForMatrices),s.push("#define BonesPerMesh "+(n.skeleton.bones.length+1))):(s.push("#define NUM_BONE_INFLUENCERS 0"),s.push("#define BONETEXTURE false"),s.push("#define BonesPerMesh 0"));const o=n.morphTargetManager;let a=0;o&&(a=o.numMaxInfluencers||o.numInfluencers,a>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+a),o.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),Eo(r,n,a))),t&&(s.push("#define INSTANCES"),Po(r,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES")),this._linkedWithPrePass?s.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):s.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),go(i,this._scene,s);const l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),c=h.defines,u=s.join("\n");return c!==u&&h.setEffect(l.createEffect("geometry",{attributes:r,uniformsNames:fP,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler"],defines:u,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:a}},l),u),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.getGBuffer().dispose()}_assignRenderTargetIndices(){const e=[],t=[];let i=2;return e.push("gBuffer_Depth","gBuffer_Normal"),t.push(this._textureTypesAndFormats[mP.DEPTH_TEXTURE_TYPE]),t.push(this._textureTypesAndFormats[mP.NORMAL_TEXTURE_TYPE]),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[mP.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[mP.VELOCITY_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[mP.REFLECTIVITY_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i,s]=this._assignRenderTargetIndices();let r=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?r=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(r=2);const n=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],a=[];for(const e of s)e?(o.push(e.textureType),a.push(e.textureFormat)):(o.push(r),a.push(5));if(this._normalsAreUnsigned=11===o[mP.NORMAL_TEXTURE_TYPE]||13===o[mP.NORMAL_TEXTURE_TYPE],this._multiRenderTarget=new xb("gBuffer",n,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:o,formats:a,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=Pa.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=Pa.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const l=[!0],h=[!1],c=[!0];for(let e=1;e{e.bindAttachments(this.useSpecificClearForDepthTexture?d:u),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(_),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(u)})),this._resizeObserver=e.onResizeObservable.add((()=>{if(this._multiRenderTarget){const t=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(t)}}));const p=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),s=this._scene,r=s.getEngine(),n=e.getMaterial();if(!n)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:me.Identity(),viewProjection:s.getTransformMatrix()},t.skeleton)){const e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=r.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances),l=i.getWorldMatrix();if(this.isReady(e,a)){const h=e._getDrawWrapper();if(!h)return;const c=h.effect;let u;r.enableEffect(h),a||t._bind(e,c,n.fillMode),this._useUbo?(Ro(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",s.getTransformMatrix()),c.setMatrix("view",s.getViewMatrix()));const d=t._instanceDataStorage;if(d.isFrozen||!n.backFaceCulling&&null===t.overrideMaterialSideOrientation)u=d.sideOrientation;else{const e=i._getWorldMatrixDeterminant();u=t.overrideMaterialSideOrientation,null===u&&(u=n.sideOrientation),e<0&&(u=u===ta.ClockWiseSideOrientation?ta.CounterClockWiseSideOrientation:ta.ClockWiseSideOrientation)}if(n._preBind(h,u),n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(n.bumpTexture&&s.getEngine().getCaps().standardDerivatives&&$c.BumpTextureEnabled&&(c.setFloat3("vBumpInfos",n.bumpTexture.coordinatesIndex,1/n.bumpTexture.level,n.parallaxScaleBias),c.setMatrix("bumpMatrix",n.bumpTexture.getTextureMatrix()),c.setTexture("bumpSampler",n.bumpTexture),c.setFloat2("vTangentSpaceParams",n.invertNormalMapX?-1:1,n.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===n.getClassName()?(null!==n.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",n.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",n.metallicRoughnessTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.baseTexture&&(c.setTexture("albedoSampler",n.baseTexture),c.setMatrix("albedoMatrix",n.baseTexture.getTextureMatrix())),null!==n.baseColor&&c.setColor3("albedoColor",n.baseColor)):"PBRSpecularGlossinessMaterial"===n.getClassName()?(null!==n.specularGlossinessTexture?(c.setTexture("reflectivitySampler",n.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",n.specularGlossinessTexture.getTextureMatrix())):null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor),null!==n.glossiness&&c.setFloat("glossiness",n.glossiness)):"PBRMaterial"===n.getClassName()?(null!==n.metallicTexture&&(c.setTexture("reflectivitySampler",n.metallicTexture),c.setMatrix("reflectivityMatrix",n.metallicTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.roughness||null!==n.metallic||null!==n.metallicTexture?(null!==n.albedoTexture&&(c.setTexture("albedoSampler",n.albedoTexture),c.setMatrix("albedoMatrix",n.albedoTexture.getTextureMatrix())),null!==n.albedoColor&&c.setColor3("albedoColor",n.albedoColor)):(null!==n.reflectivityTexture?(c.setTexture("reflectivitySampler",n.reflectivityTexture),c.setMatrix("reflectivityMatrix",n.reflectivityTexture.getTextureMatrix())):null!==n.reflectivityColor&&c.setColor3("reflectivityColor",n.reflectivityColor),null!==n.microSurface&&c.setFloat("glossiness",n.microSurface))):"StandardMaterial"===n.getClassName()&&(null!==n.specularTexture&&(c.setTexture("reflectivitySampler",n.specularTexture),c.setMatrix("reflectivityMatrix",n.specularTexture.getTextureMatrix())),null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor))),xo(c,n,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices&&c.getUniformIndex("boneTextureWidth")>-1){const i=e.getTransformMatrixTexture(t);c.setTexture("boneSampler",i),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",t.skeleton.getTransformMatrices(t));this._enableVelocity&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])}Io(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c),this._enableVelocity&&(c.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),c.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),a&&t.hasThinInstances&&c.setMatrix("world",l),t._processRendering(i,e,c,n.fillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=l.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,s)=>{if((s||0===i)&&t.subMeshes)for(let i=0;i{let n;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(r.length){for(e.setColorWrite(!1),n=0;n{throw xt("GeometryBufferRendererSceneComponent")};class gP{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(Hr.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),Hr.prototype.enableGeometryBufferRenderer=function(e=1,t=15,i){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new mP(this,e,t,i),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},Hr.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class vP{constructor(e){this.name=or.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(or.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}mP._SceneComponentInitialization=e=>{let t=e._getComponent(or.NAME_GEOMETRYBUFFERRENDERER);t||(t=new vP(e),e._addComponent(t))};Bi.ShadersStore.motionBlurPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize;\n#ifdef OBJECT_BASED\nuniform sampler2D velocitySampler;\n#else\nuniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\n#ifdef OBJECT_BASED\nvec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=samplesCount)\nbreak;vec2 offset=vUV+velocity*(hlim+float(i));\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset,0.0);\n#else\nresult+=texture2D(textureSampler,offset);\n#endif\n}\ngl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0;\n#else\nvec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; \nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=nSamples)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset1,0.0);\n#else\nresult+=texture2D(textureSampler,offset1);\n#endif\n}\ngl_FragColor=result/float(nSamples);\n#endif\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";class xP extends Vl{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,s,r,n,o,a=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,s,r,n,o,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",a,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new gP)),this._applyMode()}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}const i=t.indexOf(e);-1!==i&&t.splice(i,1)}}dispose(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),super.dispose(e)}_applyMode(){if(!this._geometryBufferRenderer&&!this._prePassRenderer)return Ne.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=me.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=5),this.onApply=e=>this._onApplyScreenBased(e))}_onApplyObjectBased(e){if(e.setVector2("screenSize",new de(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(mP.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){const t=ve.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new de(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(mP.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){const e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}}static _Parse(e,t,i,s){return St.Parse((()=>new xP(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,s)}}Ze([rt()],xP.prototype,"motionStrength",void 0),Ze([rt()],xP.prototype,"motionBlurSamples",null),Ze([rt()],xP.prototype,"isObjectBased",null),z("BABYLON.MotionBlurPostProcess",xP);Bi.ShadersStore.refractionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";class bP extends Vl{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,s,r,n,o,a,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,o,a,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=s,this.colorLevel=r,this.refractionTextureUrl=t,this.onActivateObservable.add((e=>{this._refTexture=this._refTexture||new Pa(t,e.getScene())})),this.onApplyObservable.add((e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)}))}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,s){return St.Parse((()=>new bP(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}Ze([rt()],bP.prototype,"color",void 0),Ze([rt()],bP.prototype,"depth",void 0),Ze([rt()],bP.prototype,"colorLevel",void 0),Ze([rt()],bP.prototype,"refractionTextureUrl",void 0),z("BABYLON.RefractionPostProcess",bP);Bi.ShadersStore.sharpenPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}";class TP extends Vl{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,s,r,n,null,o,void 0,null,a),this.colorAmount=1,this.edgeAmount=.3,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,s){return St.Parse((()=>new TP(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}Ze([rt()],TP.prototype,"colorAmount",void 0),Ze([rt()],TP.prototype,"edgeAmount",void 0),z("BABYLON.SharpenPostProcess",TP);class yP{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(const e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){const i=this._renderEffects[e];i&&i._enable(Ds.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(Ds.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=Ds.MakeArray(e||this._cameras);if(!i)return;const s=[];let r;for(r=0;r0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){const e=Object.keys(this._renderEffects);for(const t of e){const e=this._renderEffects[t].getPostProcesses();if(e)for(const t of e)t.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}Ze([rt()],yP.prototype,"_name",void 0);class SP{constructor(){this._renderPipelines={}}get supportedPipelines(){const e=[];for(const t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){const i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){const s=this._renderPipelines[e];s&&s._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._disableEffect(t,i)}update(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){const t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e]._rebuild()}dispose(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e].dispose()}}Object.defineProperty(Hr.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(or.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new CP(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new SP}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class CP{constructor(e){this.name=or.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(or.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}}class EP extends yP{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){const e=this.bloom;this.bloom=new eP(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen),!0),this.depthOfField=new lP(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=o.getHardwareScalingLevel(),this._resizeObserver=o.onResizeObservable.add((()=>{this._hardwareScaleLevel=o.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel})),this.bloom=new eP(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new tP("ChromaticAberration",o.getRenderWidth(),o.getRenderHeight(),1,null,Pa.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new qA(o,this.ChromaticAberrationPostProcessId,(()=>this.chromaticAberration),!0),this.grain=new dP("Grain",1,null,Pa.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new qA(o,this.GrainPostProcessId,(()=>this.grain),!0);let a=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add((()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,a?Ds.SetImmediate((()=>{this._buildPipeline()})):this._buildPipeline())})),this._buildPipeline(),a=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){const e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;const e=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(const e of this._cameras)this._scene.enableDepthRenderer(e).useOnlyInActiveCamera=!0;this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add((e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())}))}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new pP("imageProcessing",1,null,Pa.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new qA(e,this.ImageProcessingPostProcessId,(()=>this.imageProcessing),!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new uP("fxaa",1,null,Pa.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new qA(e,this.FxaaPostProcessId,(()=>this.fxaa),!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add((()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)}))),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add((()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)}))),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&Ne.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew EP(e._name,e._name._hdr,t)),e,t,i)}}Ze([rt()],EP.prototype,"sharpenEnabled",null),Ze([rt()],EP.prototype,"bloomKernel",null),Ze([rt()],EP.prototype,"_bloomWeight",void 0),Ze([rt()],EP.prototype,"_bloomThreshold",void 0),Ze([rt()],EP.prototype,"_hdr",void 0),Ze([rt()],EP.prototype,"bloomWeight",null),Ze([rt()],EP.prototype,"bloomThreshold",null),Ze([rt()],EP.prototype,"bloomScale",null),Ze([rt()],EP.prototype,"bloomEnabled",null),Ze([rt()],EP.prototype,"depthOfFieldEnabled",null),Ze([rt()],EP.prototype,"depthOfFieldBlurLevel",null),Ze([rt()],EP.prototype,"fxaaEnabled",null),Ze([rt()],EP.prototype,"samples",null),Ze([rt()],EP.prototype,"imageProcessingEnabled",null),Ze([rt()],EP.prototype,"glowLayerEnabled",null),Ze([rt()],EP.prototype,"chromaticAberrationEnabled",null),Ze([rt()],EP.prototype,"grainEnabled",null),z("BABYLON.DefaultRenderingPipeline",EP);Bi.ShadersStore.lensHighlightsPixelShader="uniform sampler2D textureSampler; \nuniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;}\nfloat w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;gl_FragColor=blurred;}";Bi.ShadersStore.depthOfFieldPixelShader="uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; \nuniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV;\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \nvec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co)\n{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);}\nvec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;}\nfloat sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;}\nfloat getBlurLevel(float size) {return min(3.0,ceil(size/1.0));}\nvec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);}\nif (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);}\ncol/=total_weight; \nif (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);}\nreturn col;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; }\nfloat edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;}\nfloat blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);}\nelse {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;}\nif (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}}\nif (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}}\n";class AP extends yP{constructor(e,t,i,s=1,r){super(i.getEngine(),e),this.LensChromaticAberrationEffect="LensChromaticAberrationEffect",this.HighlightsEnhancingEffect="HighlightsEnhancingEffect",this.LensDepthOfFieldEffect="LensDepthOfFieldEffect",this._pentagonBokehIsEnabled=!1,this._scene=i,this._depthTexture=i.enableDepthRenderer().getDepthMap(),t.grain_texture?this._grainTexture=t.grain_texture:this._createGrainTexture(),this._edgeBlur=t.edge_blur?t.edge_blur:0,this._grainAmount=t.grain_amount?t.grain_amount:0,this._chromaticAberration=t.chromatic_aberration?t.chromatic_aberration:0,this._distortion=t.distortion?t.distortion:0,this._highlightsGain=void 0!==t.dof_gain?t.dof_gain:-1,this._highlightsThreshold=t.dof_threshold?t.dof_threshold:1,this._dofDistance=void 0!==t.dof_focus_distance?t.dof_focus_distance:-1,this._dofAperture=t.dof_aperture?t.dof_aperture:1,this._dofDarken=t.dof_darken?t.dof_darken:0,this._dofPentagon=void 0===t.dof_pentagon||t.dof_pentagon,this._blurNoise=void 0===t.blur_noise||t.blur_noise,this._createChromaticAberrationPostProcess(s),this._createHighlightsPostProcess(s),this._createDepthOfFieldPostProcess(s/4),this.addEffect(new qA(i.getEngine(),this.LensChromaticAberrationEffect,(()=>this._chromaticAberrationPostProcess),!0)),this.addEffect(new qA(i.getEngine(),this.HighlightsEnhancingEffect,(()=>this._highlightsPostProcess),!0)),this.addEffect(new qA(i.getEngine(),this.LensDepthOfFieldEffect,(()=>this._depthOfFieldPostProcess),!0)),-1===this._highlightsGain&&this._disableEffect(this.HighlightsEnhancingEffect,null),i.postProcessRenderPipelineManager.addPipeline(this),r&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}getClassName(){return"LensRenderingPipeline"}get scene(){return this._scene}get edgeBlur(){return this._edgeBlur}set edgeBlur(e){this.setEdgeBlur(e)}get grainAmount(){return this._grainAmount}set grainAmount(e){this.setGrainAmount(e)}get chromaticAberration(){return this._chromaticAberration}set chromaticAberration(e){this.setChromaticAberration(e)}get dofAperture(){return this._dofAperture}set dofAperture(e){this.setAperture(e)}get edgeDistortion(){return this._distortion}set edgeDistortion(e){this.setEdgeDistortion(e)}get dofDistortion(){return this._dofDistance}set dofDistortion(e){this.setFocusDistance(e)}get darkenOutOfFocus(){return this._dofDarken}set darkenOutOfFocus(e){this.setDarkenOutOfFocus(e)}get blurNoise(){return this._blurNoise}set blurNoise(e){this._blurNoise=e}get pentagonBokeh(){return this._pentagonBokehIsEnabled}set pentagonBokeh(e){e?this.enablePentagonBokeh():this.disablePentagonBokeh()}get highlightsGain(){return this._highlightsGain}set highlightsGain(e){this.setHighlightsGain(e)}get highlightsThreshold(){return this._highlightsThreshold}set highlightsThreshold(e){this.setHighlightsThreshold(e)}setEdgeBlur(e){this._edgeBlur=e}disableEdgeBlur(){this._edgeBlur=0}setGrainAmount(e){this._grainAmount=e}disableGrain(){this._grainAmount=0}setChromaticAberration(e){this._chromaticAberration=e}disableChromaticAberration(){this._chromaticAberration=0}setEdgeDistortion(e){this._distortion=e}disableEdgeDistortion(){this._distortion=0}setFocusDistance(e){this._dofDistance=e}disableDepthOfField(){this._dofDistance=-1}setAperture(e){this._dofAperture=e}setDarkenOutOfFocus(e){this._dofDarken=e}enablePentagonBokeh(){this._highlightsPostProcess.updateEffect("#define PENTAGON\n"),this._pentagonBokehIsEnabled=!0}disablePentagonBokeh(){this._pentagonBokehIsEnabled=!1,this._highlightsPostProcess.updateEffect()}enableNoiseBlur(){this._blurNoise=!0}disableNoiseBlur(){this._blurNoise=!1}setHighlightsGain(e){this._highlightsGain=e}setHighlightsThreshold(e){-1===this._highlightsGain&&(this._highlightsGain=1),this._highlightsThreshold=e}disableHighlights(){this._highlightsGain=-1}dispose(e=!1){this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),this._chromaticAberrationPostProcess=null,this._highlightsPostProcess=null,this._depthOfFieldPostProcess=null,this._grainTexture.dispose(),e&&this._scene.disableDepthRenderer()}_createChromaticAberrationPostProcess(e){this._chromaticAberrationPostProcess=new Vl("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],e,null,Pa.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._chromaticAberrationPostProcess.onApply=e=>{e.setFloat("chromatic_aberration",this._chromaticAberration),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),e.setFloat("radialIntensity",1),e.setFloat2("direction",17,17),e.setFloat2("centerPosition",.5,.5)}}_createHighlightsPostProcess(e){this._highlightsPostProcess=new Vl("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],e,null,Pa.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,this._dofPentagon?"#define PENTAGON\n":""),this._highlightsPostProcess.externalTextureSamplerBinding=!0,this._highlightsPostProcess.onApply=e=>{e.setFloat("gain",this._highlightsGain),e.setFloat("threshold",this._highlightsThreshold),e.setTextureFromPostProcess("textureSampler",this._chromaticAberrationPostProcess),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight())}}_createDepthOfFieldPostProcess(e){this._depthOfFieldPostProcess=new Vl("LensDepthOfField","depthOfField",["grain_amount","blur_noise","screen_width","screen_height","distortion","dof_enabled","screen_distance","aperture","darken","edge_blur","highlights","near","far"],["depthSampler","grainSampler","highlightsSampler"],e,null,Pa.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._depthOfFieldPostProcess.externalTextureSamplerBinding=!0,this._depthOfFieldPostProcess.onApply=e=>{e.setTexture("depthSampler",this._depthTexture),e.setTexture("grainSampler",this._grainTexture),e.setTextureFromPostProcess("textureSampler",this._highlightsPostProcess),e.setTextureFromPostProcess("highlightsSampler",this._depthOfFieldPostProcess),e.setFloat("grain_amount",this._grainAmount),e.setBool("blur_noise",this._blurNoise),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),e.setFloat("distortion",this._distortion),e.setBool("dof_enabled",-1!==this._dofDistance),e.setFloat("screen_distance",1/(.1-1/this._dofDistance)),e.setFloat("aperture",this._dofAperture),e.setFloat("darken",this._dofDarken),e.setFloat("edge_blur",this._edgeBlur),e.setBool("highlights",-1!==this._highlightsGain),this._scene.activeCamera&&(e.setFloat("near",this._scene.activeCamera.minZ),e.setFloat("far",this._scene.activeCamera.maxZ))}}_createGrainTexture(){const e=new Uint8Array(1048576);for(let t=0;t1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;}\nfloat sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);}\n#endif\n#ifdef BLUR\nuniform float outSize;uniform float soften;uniform float tolerance;uniform int samples;\n#ifndef BLUR_BYPASS\nuniform sampler2D depthSampler;\n#ifdef BLUR_LEGACY\n#define inline\nfloat blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;}\n#endif\n#endif\nvoid main()\n{float result=0.0;\n#ifdef BLUR_BYPASS\nresult=textureLod(textureSampler,vUV,0.0).r;\n#else\n#ifdef BLUR_H\nvec2 step=vec2(1.0/outSize,0.0);\n#else\nvec2 step=vec2(0.0,1.0/outSize);\n#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,vUV,step);\n#else\nfloat compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; ithis._originalColorPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e{if(!this._scene.activeCamera)return;const t=n?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=n?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},o.samples=this.textureSamples,o.autoClear=!1,o}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,2.3283064365386963e-10*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){const i=2*t*Math.PI,s=1-.85*e,r=Math.sqrt(1-s*s);return new _e(Math.cos(i)*r,Math.sin(i)*r,s)}_generateHemisphere(){const e=this.samples,t=[];let i,s=0;for(;s{if(this._scene.activeCamera){if(e.setArray3("sampleSphere",this._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/this.samples),e.setFloat("totalStrength",this.totalStrength),e.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),e.setFloat("radius",this.radius),e.setFloat("maxZ",this.maxZ),e.setFloat("minZAspect",this.minZAspect),e.setFloat("base",this.base),e.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===In.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",IP.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const t=this._scene.getEngine().getRenderWidth()/2,i=this._scene.getEngine().getRenderHeight()/2,s=this._scene.activeCamera.orthoLeft??-t,r=this._scene.activeCamera.orthoRight??t,n=this._scene.activeCamera.orthoBottom??-i,o=this._scene.activeCamera.orthoTop??i;e.setMatrix3x3("depthProjection",IP.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",.5*(r-s)),e.setFloat("yViewport",.5*(o-n))}e.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),e.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),e.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new PP)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new Vl("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{const t=this._scene.activeCamera.viewport;e.setVector4("viewport",ve.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.autoClear=!1,this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){const e=new Uint8Array(65536),t=de.Zero();for(let i=0;inew IP(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType)),e,t,i)}}IP.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],IP.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],Ze([rt()],IP.prototype,"totalStrength",void 0),Ze([rt()],IP.prototype,"maxZ",void 0),Ze([rt()],IP.prototype,"minZAspect",void 0),Ze([rt("epsilon")],IP.prototype,"_epsilon",void 0),Ze([rt("samples")],IP.prototype,"_samples",void 0),Ze([rt("textureSamples")],IP.prototype,"_textureSamples",void 0),Ze([rt()],IP.prototype,"_forceGeometryBuffer",void 0),Ze([rt()],IP.prototype,"_ratio",void 0),Ze([rt()],IP.prototype,"_textureType",void 0),Ze([rt()],IP.prototype,"radius",void 0),Ze([rt()],IP.prototype,"base",void 0),Ze([rt("bypassBlur")],IP.prototype,"_bypassBlur",void 0),Ze([rt("expensiveBlur")],IP.prototype,"_expensiveBlur",void 0),Ze([rt()],IP.prototype,"bilateralSamples",void 0),Ze([rt()],IP.prototype,"bilateralSoften",void 0),Ze([rt()],IP.prototype,"bilateralTolerance",void 0),z("BABYLON.SSAO2RenderingPipeline",IP);Bi.ShadersStore.ssaoPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords)\n{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);}\nvoid main()\n{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; ithis._originalColorPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}_attachCameras(e,t){super._attachCameras(e,t);for(const e of this._cameras)this._scene.enableDepthRenderer(e).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e{const e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e})),this._blurVPostProcess.onActivateObservable.add((()=>{const e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e}))}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){const t=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271];this._ssaoPostProcess=new Vl("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=e=>{this._firstUpdate&&(e.setArray3("sampleSphere",t),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",this.totalStrength),e.setFloat("radius",this.radius),e.setFloat("area",this.area),e.setFloat("fallOff",this.fallOff),e.setFloat("base",this.base),e.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new Vl("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",ve.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const e=new Uint8Array(1048576);for(let t=0;t0.0)\nhitCoord-=dir;else\nhitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;}\nprojectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;}\n/**\n* Tests the given world position (hitCoord) according to the given reflection vector (dir)\n* until it finds a collision (means that depth is enough close to say \"it's the pixel to sample!\").\n*/\nReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)\n{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i{const i=this._geometryBufferRenderer,s=this._prePassRenderer;if(!s&&!i)return;if(i){const t=i.getTextureIndex(mP.POSITION_TEXTURE_TYPE),s=i.getTextureIndex(mP.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[s])}else if(s){const t=s.getIndex(1),i=s.getIndex(3),r=s.getIndex(6);e.setTexture("normalSampler",s.getRenderTarget().textures[r]),e.setTexture("positionSampler",s.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",s.getRenderTarget().textures[i])}const r=t.activeCamera;if(!r)return;const n=r.getViewMatrix(!0),o=r.getProjectionMatrix(!0);e.setMatrix("projection",o),e.setMatrix("view",n),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(0|this._reflectionSamples)),e.push("#define SMOOTH_STEPS "+(0|this._smoothSteps)),this.updateEffect(e.join("\n"))}static _Parse(e,t,i,s){return St.Parse((()=>new OP(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}Ze([rt()],OP.prototype,"threshold",void 0),Ze([rt()],OP.prototype,"strength",void 0),Ze([rt()],OP.prototype,"reflectionSpecularFalloffExponent",void 0),Ze([rt()],OP.prototype,"step",void 0),Ze([rt()],OP.prototype,"roughnessFactor",void 0),Ze([rt()],OP.prototype,"enableSmoothReflections",null),Ze([rt()],OP.prototype,"reflectionSamples",null),Ze([rt()],OP.prototype,"smoothSteps",null),z("BABYLON.ScreenSpaceReflectionPostProcess",OP);Bi.ShadersStore.standardPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];void main(void)\n{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void)\n{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminanceshadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;}\naccumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;void main(void)\n{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];void main()\n{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++)\n{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));}\naverage=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];uniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\n#include\n#endif\nvoid main()\n{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++)\n{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;uniform float averageLuminance;void main()\n{vec4 color=texture2D(textureAdderSampler,vUV);\n#ifndef AUTO_EXPOSURE\nvec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0;\n#endif\ngl_FragColor=color;}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p)\n{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);}\nfloat noise(in vec2 p)\n{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);}\nfloat fbm(vec2 p)\n{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;}\nvec3 pattern(vec2 uv)\n{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);}\nfloat luminance(vec3 color)\n{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{return vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);}\nvoid main(void)\n{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i=nSamples)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);}\ngl_FragColor=result/float(nSamples);}\n#endif\n";class DP extends yP{get exposure(){return this._fixedExposure}set exposure(e){this._fixedExposure=e,this._currentExposure=e}get hdrAutoExposure(){return this._hdrAutoExposure}set hdrAutoExposure(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){const t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join("\n"))}}get motionStrength(){return this._motionStrength}set motionStrength(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)}get objectBasedMotionBlur(){return this._isObjectBasedMotionBlur}set objectBasedMotionBlur(e){const t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()}get BloomEnabled(){return this._bloomEnabled}set BloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get DepthOfFieldEnabled(){return this._depthOfFieldEnabled}set DepthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get LensFlareEnabled(){return this._lensFlareEnabled}set LensFlareEnabled(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())}get HDREnabled(){return this._hdrEnabled}set HDREnabled(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())}get VLSEnabled(){return this._vlsEnabled}set VLSEnabled(e){if(this._vlsEnabled!==e){if(e&&!this._scene.enableGeometryBufferRenderer())return void Ne.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,s=null,r){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=r||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=s,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){const e=this._ratio,t=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new OP("HDRPass",t,e,null,Pa.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess})),this.addEffect(new qA(t.getEngine(),"HDRScreenSpaceReflections",(()=>this.screenSpaceReflectionPostProcess),!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new Vl("HDRPass","standard",[],[],e,null,Pa.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.originalPostProcess})),this.addEffect(new qA(t.getEngine(),"HDRPassPostProcess",(()=>this.originalPostProcess),!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(t,e/4),this._createBrightPassPostProcess(t,e/4),this._createBlurPostProcesses(t,e/4,1),this._createTextureAdderPostProcess(t,e),this.textureAdderFinalPostProcess=new Vl("HDRDepthOfFieldSource","standard",[],[],e,null,Pa.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new qA(t.getEngine(),"HDRBaseDepthOfFieldSource",(()=>this.textureAdderFinalPostProcess),!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new Vl("HDRVLSFinal","standard",[],[],e,null,Pa.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new qA(t.getEngine(),"HDRVLSFinal",(()=>this.volumetricLightFinalPostProcess),!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new Vl("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,Pa.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new qA(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",(()=>this.lensFlareFinalPostProcess),!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new Vl("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,Pa.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new qA(t.getEngine(),"HDRPostHDReDepthOfFieldSource",(()=>this.hdrFinalPostProcess),!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(t,e/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(t,e)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(t,e),this._fxaaEnabled&&(this.fxaaPostProcess=new uP("fxaa",1,null,Pa.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new qA(t.getEngine(),"HDRFxaa",(()=>this.fxaaPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&Ne.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){const i=new Array(32);this.downSampleX4PostProcess=new Vl("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0;const s=this.downSampleX4PostProcess.width,r=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let n=-2;n<2;n++)i[t]=(e+.5)*(1/s),i[t+1]=(n+.5)*(1/r),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new qA(e.getEngine(),"HDRDownSampleX4",(()=>this.downSampleX4PostProcess),!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new Vl("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{const t=1/this.brightPassPostProcess.width,s=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*s,i[2]=.5*t,i[3]=.5*s,i[4]=-.5*t,i[5]=-.5*s,i[6]=.5*t,i[7]=-.5*s,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new qA(e.getEngine(),"HDRBrightPass",(()=>this.brightPassPostProcess),!0))}_createBlurPostProcesses(e,t,i,s="blurWidth"){const r=e.getEngine(),n=new mg("HDRBlurH_"+i,new de(1,0),this[s],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),o=new mg("HDRBlurV_"+i,new de(0,1),this[s],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add((()=>{const e=n.width/r.getRenderWidth();n.kernel=this[s]*e})),o.onActivateObservable.add((()=>{const e=o.height/r.getRenderHeight();o.kernel=this.horizontalBlur?64*e:this[s]*e})),this.addEffect(new qA(e.getEngine(),"HDRBlurH"+i,(()=>n),!0)),this.addEffect(new qA(e.getEngine(),"HDRBlurV"+i,(()=>o),!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(o)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new Vl("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),e.setTexture("lensSampler",this.lensTexture),e.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new qA(e.getEngine(),"HDRTextureAdder",(()=>this.textureAdderPostProcess),!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const s=i.getGBuffer();this.volumetricLightPostProcess=new Vl("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));const r=de.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",s.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),r.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),r.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",r)}},this.addEffect(new qA(e.getEngine(),"HDRVLS",(()=>this.volumetricLightPostProcess),!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new Vl("HDRVLSMerge","standard",[],["originalSampler"],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=e=>{e.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new qA(e.getEngine(),"HDRVLSMerge",(()=>this.volumetricLightMergePostProces),!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,DP.LuminanceSteps);this.luminancePostProcess=new Vl("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const s=[];this.luminancePostProcess.onApply=e=>{const t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;s[0]=-.5*t,s[1]=.5*i,s[2]=.5*t,s[3]=.5*i,s[4]=-.5*t,s[5]=-.5*i,s[6]=.5*t,s[7]=-.5*i,e.setArray2("lumOffsets",s)},this.addEffect(new qA(e.getEngine(),"HDRLuminance",(()=>this.luminancePostProcess),!0));for(let s=DP.LuminanceSteps-1;s>=0;s--){i=Math.pow(3,s);let r="#define LUMINANCE_DOWN_SAMPLE\n";0===s&&(r+="#define FINAL_DOWN_SAMPLER");const n=new Vl("HDRLuminanceDownSample"+s,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,t);this.luminanceDownSamplePostProcesses.push(n)}let r=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach(((t,i)=>{const s=new Array(18);t.onApply=e=>{if(!r)return;let n=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)s[n]=e/r.width,s[n+1]=t/r.height,n+=2;e.setArray2("dsOffsets",s),e.setFloat("halfDestPixelSize",.5/r.width),r=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{const t=e.getEngine().readPixels(0,0,1,1),i=new pe(1/16581375,1/65025,1/255,1);t.then((e=>{const t=new Uint8Array(e.buffer);this._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100}))}),this.addEffect(new qA(e.getEngine(),"HDRLuminanceDownSample"+i,(()=>t),!0))}))}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new Vl("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let s=1,r=0,n=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),r+=e.getEngine().getDeltaTime(),s<0)s=this._hdrCurrentLuminance;else{const e=(n-r)/1e3;this._hdrCurrentLuminances-this.hdrIncreaseRate*e?s-=this.hdrIncreaseRate*e:s=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/s:(s=be.Clamp(s,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",s)),n=r,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new qA(e.getEngine(),"HDR",(()=>this.hdrPostProcess),!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new Vl("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new qA(e.getEngine(),"HDRLensFlare",(()=>this.lensFlarePostProcess),!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new Vl("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new qA(e.getEngine(),"HDRLensFlareCompose",(()=>this.lensFlareComposePostProcess),!0));const i=new de(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=e=>{e.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),e.setTexture("lensColorSampler",this.lensColorTexture),e.setFloat("strength",this.lensFlareStrength),e.setFloat("ghostDispersal",this.lensFlareGhostDispersal),e.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,e.setVector2("resolution",i),e.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const s=me.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),r=me.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=e=>{if(!this._scene.activeCamera)return;e.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),e.setTexture("lensDirtSampler",this.lensFlareDirtTexture),e.setTexture("lensStarSampler",this.lensStarTexture);const t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2);let n=_e.Dot(t.toVector3(),new _e(1,0,0))+_e.Dot(i.toVector3(),new _e(0,0,1));n*=4;const o=me.FromValues(.5*Math.cos(n),-Math.sin(n),0,0,Math.sin(n),.5*Math.cos(n),0,0,0,0,1,0,0,0,0,1),a=r.multiply(o).multiply(s);e.setMatrix("lensStarMatrix",a),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new Vl("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),e.setTexture("depthSampler",this._getDepthTexture()),e.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new qA(e.getEngine(),"HDRDepthOfField",(()=>this.depthOfFieldPostProcess),!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new xP("HDRMotionBlur",e,t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new Vl("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,s=me.Identity();const r=me.Identity();let n=me.Identity();const o=de.Zero();this.motionBlurPostProcess.onApply=t=>{n=e.getProjectionMatrix().multiply(e.getViewMatrix()),n.invertToRef(r),t.setMatrix("inverseViewProjection",r),t.setMatrix("prevViewProjection",s),s=n,o.x=this.motionBlurPostProcess.width,o.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",o),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new qA(e.getEngine(),"HDRMotionBlur",(()=>this.motionBlurPostProcess),!0))}_getDepthTexture(){return this._scene.getEngine().getCaps().drawBuffersExtension?this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]:this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;enew DP(e._name,t,e._ratio)),e,t,i);return e.sourceLightId&&(s.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&St.Parse((()=>s.screenSpaceReflectionPostProcess),e.screenSpaceReflectionPostProcess,t,i),s}}DP.LuminanceSteps=6,Ze([rt()],DP.prototype,"brightThreshold",void 0),Ze([rt()],DP.prototype,"blurWidth",void 0),Ze([rt()],DP.prototype,"horizontalBlur",void 0),Ze([rt()],DP.prototype,"exposure",null),Ze([nt("lensTexture")],DP.prototype,"lensTexture",void 0),Ze([rt()],DP.prototype,"volumetricLightCoefficient",void 0),Ze([rt()],DP.prototype,"volumetricLightPower",void 0),Ze([rt()],DP.prototype,"volumetricLightBlurScale",void 0),Ze([rt()],DP.prototype,"hdrMinimumLuminance",void 0),Ze([rt()],DP.prototype,"hdrDecreaseRate",void 0),Ze([rt()],DP.prototype,"hdrIncreaseRate",void 0),Ze([rt()],DP.prototype,"hdrAutoExposure",null),Ze([nt("lensColorTexture")],DP.prototype,"lensColorTexture",void 0),Ze([rt()],DP.prototype,"lensFlareStrength",void 0),Ze([rt()],DP.prototype,"lensFlareGhostDispersal",void 0),Ze([rt()],DP.prototype,"lensFlareHaloWidth",void 0),Ze([rt()],DP.prototype,"lensFlareDistortionStrength",void 0),Ze([rt()],DP.prototype,"lensFlareBlurWidth",void 0),Ze([nt("lensStarTexture")],DP.prototype,"lensStarTexture",void 0),Ze([nt("lensFlareDirtTexture")],DP.prototype,"lensFlareDirtTexture",void 0),Ze([rt()],DP.prototype,"depthOfFieldDistance",void 0),Ze([rt()],DP.prototype,"depthOfFieldBlurWidth",void 0),Ze([rt()],DP.prototype,"motionStrength",null),Ze([rt()],DP.prototype,"objectBasedMotionBlur",null),Ze([rt()],DP.prototype,"_ratio",void 0),Ze([rt()],DP.prototype,"BloomEnabled",null),Ze([rt()],DP.prototype,"DepthOfFieldEnabled",null),Ze([rt()],DP.prototype,"LensFlareEnabled",null),Ze([rt()],DP.prototype,"HDREnabled",null),Ze([rt()],DP.prototype,"VLSEnabled",null),Ze([rt()],DP.prototype,"MotionBlurEnabled",null),Ze([rt()],DP.prototype,"fxaaEnabled",null),Ze([rt()],DP.prototype,"screenSpaceReflectionsEnabled",null),Ze([rt()],DP.prototype,"volumetricLightStepsCount",null),Ze([rt()],DP.prototype,"motionBlurSamples",null),Ze([rt()],DP.prototype,"samples",null),z("BABYLON.StandardRenderingPipeline",DP);class wP{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}Bi.IncludesShadersStore.screenSpaceRayTrace="float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }\n/**\nparam csOrigin Camera-space ray origin,which must be \nwithin the view volume and must have z>0.01 and project within the valid screen rectangle\nparam csDirection Unit length camera-space ray direction\nparam projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \n(**not** [-1,+1] normalized device coordinates).\nparam csZBuffer The camera-space Z buffer\nparam csZBufferSize Dimensions of csZBuffer\nparam csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\nparam nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\nfor clipping rays headed towards the camera\nparam stride Step in horizontal or vertical pixels between samples. This is a float\nbecause integer math is slow on GPUs,but should be set to an integer>=1\nparam jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\nto conceal banding artifacts,plus the stride ray offset.\nparam maxSteps Maximum number of iterations. Higher gives better images but may be slow\nparam maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\nparam selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.\n1 is a reasonable value,depending on the scene you may need to set this value to 2\nparam hitPixel Pixel coordinates of the first intersection with the scene\nparam numIterations number of iterations performed\nparam csHitPoint Camera space location of the ray hit\n*/\n#define inline\nbool traceScreenSpaceRay1(\nvec3 csOrigin,\nvec3 csDirection,\nmat4 projectToPixelMatrix,\nsampler2D csZBuffer,\nvec2 csZBufferSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nsampler2D csZBackBuffer,\nfloat csZBackSizeFactor,\n#endif\nfloat csZThickness,\nfloat nearPlaneZ,\nfloat stride,\nfloat jitterFraction,\nfloat maxSteps,\nfloat maxRayTraceDistance,\nfloat selfCollisionNumSkip,\nout vec2 startPixel,\nout vec2 hitPixel,\nout vec3 csHitPoint,\nout float numIterations\n#ifdef SSRAYTRACE_DEBUG\n,out vec3 debugColor\n#endif\n)\n{\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\n#else\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);}\nif ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));}\nP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\n#endif\nP1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { \nfloat t=rayZMin; rayZMin=rayZMax; rayZMax=t;}\nsceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\n#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\n#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\n#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\n#endif\n#endif\n}\npqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;}\n#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 ||\n(refinementStepCount<=stride*1.4) &&\n(rayZMaxend) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);}\n#endif\nreturn hit;}\n/**\ntexCoord: in the [0,1] range\ndepth: depth in view space (range [znear,zfar]])\n*/\nvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef ORTHOGRAPHIC_CAMERA\nndc.z=-projection[2].z*depth+projection[3].z;\n#else\nndc.z=-projection[2].z-projection[3].z/depth;\n#endif\n#else\n#ifdef ORTHOGRAPHIC_CAMERA\nndc.z=projection[2].z*depth+projection[3].z;\n#else\nndc.z=projection[2].z+projection[3].z/depth;\n#endif\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\n";Bi.ShadersStore.screenSpaceReflection2PixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nuniform sampler2D backDepthSampler;uniform float backSizeFactor;\n#endif\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nuniform samplerCube envCubeSampler;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize;\n#endif\n#endif\nuniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold;\n#include\n#include\n#include\nvec3 hash(vec3 a)\n{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);}\nfloat computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0;\n#ifdef SSR_ATTENUATE_SCREEN_BORDERS\nvec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE\nattenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\nattenuation*=1.0-(numIterations/maxSteps);\n#endif\n#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION\nvec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation;\n#endif\nreturn attenuation;}\n#endif\nvoid main()\n{\n#ifdef SSR_SUPPORTED\nvec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {\n#ifdef SSR_USE_BLUR\ngl_FragColor=vec4(0.);\n#else\ngl_FragColor=colorFull;\n#endif\nreturn;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; \n#ifdef SSR_DECODE_NORMAL\ncsNormal=csNormal*2.0-1.0;\n#endif\n#ifdef SSR_NORMAL_IS_IN_WORLDSPACE\ncsNormal=(view*vec4(csNormal,0.0)).xyz;\n#endif\nfloat depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);\n#ifdef ORTHOGRAPHIC_CAMERA\nvec3 csViewDirection=vec3(0.,0.,1.);\n#else\nvec3 csViewDirection=normalize(csPosition);\n#endif\nvec3 csReflectedVector=reflect(csViewDirection,csNormal);\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0));\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nvec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition);\n#endif\n#ifdef SSR_INVERTCUBICMAP\nwReflectedVector.y*=-1.0;\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nwReflectedVector.z*=-1.0;\n#endif\nvec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz;\n#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\nenvColor=toLinearSpace(envColor);\n#endif\n#else\nvec3 envColor=color;\n#endif\nfloat reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations;\n#ifdef SSRAYTRACE_DEBUG\nvec3 debugColor;\n#endif\n#ifdef SSR_ATTENUATE_FACING_CAMERA\nreflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));\n#endif\nif (reflectionAttenuation>0.0) {\n#ifdef SSR_USE_BLUR\nvec3 jitt=vec3(0.);\n#else\nfloat roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; \n#endif\nvec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); \nrayHasHit=traceScreenSpaceRay1(\ncsPosition,\nnormalize(csReflectedVector+jitt),\nprojectionPixel,\ndepthSampler,\ntexSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nbackDepthSampler,\nbackSizeFactor,\n#endif\nthickness,\nnearPlaneZ,\nstepSize,\njitter,\nmaxSteps,\nmaxDistance,\nselfCollisionNumSkip,\nstartPixel,\nhitPixel,\nhitPoint,\nnumIterations\n#ifdef SSRAYTRACE_DEBUG\n,debugColor\n#endif\n);}\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=vec4(debugColor,1.);return;\n#endif\nvec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb;\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\nreflectedColor=toLinearSpace(reflectedColor);\n#endif\nreflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;}\n#ifndef SSR_BLEND_WITH_FRESNEL\nSSR*=fresnel;\n#endif\n#ifdef SSR_USE_BLUR\nfloat blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; \nfloat a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);}\ngl_FragColor=vec4(SSR,blur_radius/255.0); \n#else\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,colorFull.a);\n#endif\n#else\ngl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0);\n#endif\n}\n";Bi.ShadersStore.screenSpaceReflection2BlurPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator)\n{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;}\nvoid main()\n{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;}\nfloat blurRadius=colorFull.a*255.0; \nvec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);}\n";Bi.ShadersStore.screenSpaceReflection2BlurCombinerPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV;\n#include\n#ifdef SSR_BLEND_WITH_FRESNEL\n#include\n#include\nuniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#endif\nvoid main()\n{\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=texture2D(textureSampler,vUV);\n#else\nvec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,color.a);\n#endif\n}\n";const NP=me.Compose(new _e(.5,.5,.5),fe.Identity(),new _e(.5,.5,.5)),FP=me.Compose(new _e(.5,.5,1),fe.Identity(),new _e(.5,.5,0));class LP extends yP{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}get reflectivityThreshold(){return this._reflectivityThreshold}set reflectivityThreshold(e){e!==this._reflectivityThreshold&&(0===e&&0!==this._reflectivityThreshold||0!==e&&0===this._reflectivityThreshold?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)}get ssrDownsample(){return this._ssrDownsample}set ssrDownsample(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())}get blurDispersionStrength(){return this._blurDispersionStrength}set blurDispersionStrength(e){if(e===this._blurDispersionStrength)return;const t=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;this._blurDispersionStrength=e,t&&this._buildPipeline()}_useBlur(){return this._blurDispersionStrength>0}get blurDownsample(){return this._blurDownsample}set blurDownsample(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e,this._updateEffectDefines()}get environmentTextureIsProbe(){return this._environmentTextureIsProbe}set environmentTextureIsProbe(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()}get attenuateScreenBorders(){return this._attenuateScreenBorders}set attenuateScreenBorders(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())}get attenuateIntersectionDistance(){return this._attenuateIntersectionDistance}set attenuateIntersectionDistance(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())}get attenuateIntersectionIterations(){return this._attenuateIntersectionIterations}set attenuateIntersectionIterations(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())}get attenuateFacingCamera(){return this._attenuateFacingCamera}set attenuateFacingCamera(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())}get attenuateBackfaceReflection(){return this._attenuateBackfaceReflection}set attenuateBackfaceReflection(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())}get clipToFrustum(){return this._clipToFrustum}set clipToFrustum(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())}get useFresnel(){return this._useFresnel}set useFresnel(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())}get enableAutomaticThicknessComputation(){return this._enableAutomaticThicknessComputation}set enableAutomaticThicknessComputation(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())}get backfaceDepthRenderer(){return this._depthRenderer}get backfaceDepthTextureDownsample(){return this._backfaceDepthTextureDownsample}set backfaceDepthTextureDownsample(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())}get backfaceForceDepthWriteTransparentMeshes(){return this._backfaceForceDepthWriteTransparentMeshes}set backfaceForceDepthWriteTransparentMeshes(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){const e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,s=!1,r=0){if(super(t.getEngine(),e),this.SSRRenderEffect="SSRRenderEffect",this.SSRBlurRenderEffect="SSRBlurRenderEffect",this.SSRCombineRenderEffect="SSRCombineRenderEffect",this._samples=1,this.maxDistance=1e3,this.step=1,this.thickness=.5,this.strength=1,this.reflectionSpecularFalloffExponent=1,this.maxSteps=1e3,this.roughnessFactor=.2,this.selfCollisionNumSkip=1,this._reflectivityThreshold=.04,this._ssrDownsample=0,this._blurDispersionStrength=.03,this._blurDownsample=0,this._enableSmoothReflections=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=r,this._forceGeometryBuffer=s,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0)}else{const e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty())}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){const e=this._scene.getEngine(),t=this._prePassRenderer;let i={width:e.getRenderWidth(),height:e.getRenderHeight()};if(t&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const e=t.getRenderTarget();e&&e.textures&&(i=e.textures[t.getIndex(4)].getSize())}else this._ssrPostProcess?.inputTexture&&(i.width=this._ssrPostProcess.inputTexture.width,i.height=this._ssrPostProcess.inputTexture.height);return i}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&e.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(e.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&e.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&e.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&e.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&e.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&e.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&e.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&e.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&e.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&e.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&e.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&e.push("#define SSR_USE_BLUR"),this._debug&&e.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&e.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&e.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&e.push("#define SSR_BLEND_WITH_FRESNEL"),0===this._reflectivityThreshold&&e.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(this._geometryBufferRenderer?.generateNormalsInWorldSpace??this._prePassRenderer?.generateNormalsInWorldSpace)&&e.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),this._geometryBufferRenderer?.normalsAreUnsigned&&e.push("#define SSR_DECODE_NORMAL");const t=this._cameras?.[0];t&&1===t.mode&&e.push("#define ORTHOGRAPHIC_CAMERA"),this._ssrPostProcess?.updateEffect(e.join("\n"))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){const e=this._cameras?.[0];e&&(this._depthRendererCamera=e,this._depthRenderer=new Hv(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),e.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new qA(e,this.SSRRenderEffect,(()=>this._ssrPostProcess),!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new qA(e,this.SSRBlurRenderEffect,(()=>[this._blurPostProcessX,this._blurPostProcessY]),!0)),this.addEffect(new qA(e,this.SSRCombineRenderEffect,(()=>this._blurCombinerPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;const e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),s=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));t.width===i&&t.height===s||this._depthRenderer.getDepthMap().resize({width:i,height:s})}_disposeDepthRenderer(){if(this._depthRenderer){if(this._depthRendererCamera){const e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap())??-1;-1!==e&&this._depthRendererCamera.customRenderTargets.splice(e,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){for(let e=0;e{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const i=t.getTextureIndex(mP.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){const t=i.getIndex(5),s=i.getIndex(3),r=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[r]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[s])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const s=this._scene.activeCamera;if(!s)return;const r=s.getViewMatrix(),n=s.getProjectionMatrix();n.invertToRef(ve.Matrix[0]),r.invertToRef(ve.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",r),e.setMatrix("invView",ve.Matrix[1]),e.setMatrix("invProjectionMatrix",ve.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",s.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const o=this._getTextureSize();me.ScalingToRef(o.width,o.height,1,ve.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?FP:NP,ve.Matrix[3]),ve.Matrix[3].multiplyToRef(ve.Matrix[2],ve.Matrix[4]),e.setMatrix("projectionPixel",ve.Matrix[4]),this._environmentTexture&&(e.setTexture("envCubeSampler",this._environmentTexture),this._environmentTexture.boundingBoxSize&&(e.setVector3("vReflectionPosition",this._environmentTexture.boundingBoxPosition),e.setVector3("vReflectionSize",this._environmentTexture.boundingBoxSize)))},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new wP)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new Vl("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add((e=>{const t=this._blurPostProcessX?.inputTexture.width??this._scene.getEngine().getRenderWidth();e.setFloat2("texelOffsetScale",this._blurDispersionStrength/t,0)})),this._blurPostProcessY=new Vl("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add((e=>{const t=this._blurPostProcessY?.inputTexture.height??this._scene.getEngine().getRenderHeight();e.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/t)}));const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"];let s="";this._debug&&(s+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(s+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(s+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(s+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(s+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new Vl("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,s,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add((e=>{const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(i||t){if(i&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const t=i.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[i.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(t){const i=t.getTextureIndex(mP.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),this.useFresnel&&(e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("depthSampler",t.getGBuffer().textures[0]))}else if(i){const t=i.getIndex(3);if(e.setTexture("reflectivitySampler",i.getRenderTarget().textures[t]),this.useFresnel){const t=i.getIndex(5),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const t=this._scene.activeCamera;if(t){const i=t.getProjectionMatrix();i.invertToRef(ve.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",ve.Matrix[0])}}}}))}serialize(){const e=St.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return St.Parse((()=>new LP(e._name,t,e._ratio)),e,t,i)}}Ze([rt()],LP.prototype,"samples",null),Ze([rt()],LP.prototype,"maxDistance",void 0),Ze([rt()],LP.prototype,"step",void 0),Ze([rt()],LP.prototype,"thickness",void 0),Ze([rt()],LP.prototype,"strength",void 0),Ze([rt()],LP.prototype,"reflectionSpecularFalloffExponent",void 0),Ze([rt()],LP.prototype,"maxSteps",void 0),Ze([rt()],LP.prototype,"roughnessFactor",void 0),Ze([rt()],LP.prototype,"selfCollisionNumSkip",void 0),Ze([rt()],LP.prototype,"_reflectivityThreshold",void 0),Ze([rt("_ssrDownsample")],LP.prototype,"_ssrDownsample",void 0),Ze([rt()],LP.prototype,"ssrDownsample",null),Ze([rt("blurDispersionStrength")],LP.prototype,"_blurDispersionStrength",void 0),Ze([rt("blurDownsample")],LP.prototype,"_blurDownsample",void 0),Ze([rt("enableSmoothReflections")],LP.prototype,"_enableSmoothReflections",void 0),Ze([rt("environmentTexture")],LP.prototype,"_environmentTexture",void 0),Ze([rt("environmentTextureIsProbe")],LP.prototype,"_environmentTextureIsProbe",void 0),Ze([rt("attenuateScreenBorders")],LP.prototype,"_attenuateScreenBorders",void 0),Ze([rt("attenuateIntersectionDistance")],LP.prototype,"_attenuateIntersectionDistance",void 0),Ze([rt("attenuateIntersectionIterations")],LP.prototype,"_attenuateIntersectionIterations",void 0),Ze([rt("attenuateFacingCamera")],LP.prototype,"_attenuateFacingCamera",void 0),Ze([rt("attenuateBackfaceReflection")],LP.prototype,"_attenuateBackfaceReflection",void 0),Ze([rt("clipToFrustum")],LP.prototype,"_clipToFrustum",void 0),Ze([rt("useFresnel")],LP.prototype,"_useFresnel",void 0),Ze([rt("enableAutomaticThicknessComputation")],LP.prototype,"_enableAutomaticThicknessComputation",void 0),Ze([rt("backfaceDepthTextureDownsample")],LP.prototype,"_backfaceDepthTextureDownsample",void 0),Ze([rt("backfaceForceDepthWriteTransparentMeshes")],LP.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),Ze([rt("isEnabled")],LP.prototype,"_isEnabled",void 0),Ze([rt("inputTextureColorIsInGammaSpace")],LP.prototype,"_inputTextureColorIsInGammaSpace",void 0),Ze([rt("generateOutputInGammaSpace")],LP.prototype,"_generateOutputInGammaSpace",void 0),Ze([rt("debug")],LP.prototype,"_debug",void 0),z("BABYLON.SSRRenderingPipeline",LP);Bi.ShadersStore.taaPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D historySampler;uniform float factor;void main() {vec4 c=texelFetch(textureSampler,ivec2(gl_FragCoord.xy),0);vec4 h=texelFetch(historySampler,ivec2(gl_FragCoord.xy),0);gl_FragColor=mix(h,c,factor);}\n";class BP extends yP{set samples(e){this._samples!==e&&(this._samples=e,this._hs.regenerate(e))}get samples(){return this._samples}set msaaSamples(e){this._msaaSamples!==e&&(this._msaaSamples=e,this._taaPostProcess&&(this._taaPostProcess.samples=e))}get msaaSamples(){return this._msaaSamples}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&(this._firstUpdate=!0,this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras))):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get scene(){return this._scene}get isSupported(){return this._scene.getEngine().getCaps().texelFetch}constructor(e,t,i,s=0){const r=t.getEngine();super(r,e),this.TAARenderEffect="TAARenderEffect",this.TAAPassEffect="TAAPassEffect",this._samples=8,this._msaaSamples=1,this.factor=.05,this.disableOnCameraMove=!0,this._isEnabled=!0,this._isDirty=!1,this._camerasToBeAttached=[],this._pingpong=0,this._firstUpdate=!0,this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._hs=new zy(this.samples),this.isSupported&&(this._createPingPongTextures(r.getRenderWidth(),r.getRenderHeight()),t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline())}getClassName(){return"TAARenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._ping.dispose(),this._pong.dispose(),super.dispose()}_createPingPongTextures(e,t){const i=this._scene.getEngine();this._ping?.dispose(),this._pong?.dispose(),this._ping=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._pong=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._hs.setDimensions(e/2,t/2),this._firstUpdate=!0}_updateEffectDefines(){this._taaPostProcess?.updateEffect([].join("\n"))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._createTAAPostProcess(),this.addEffect(new qA(e,this.TAARenderEffect,(()=>this._taaPostProcess),!0)),this._createPassPostProcess(),this.addEffect(new qA(e,this.TAAPassEffect,(()=>this._passPostProcess),!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_disposePostProcesses(){for(let e=0;e{const e=this._scene.activeCamera;if(this._taaPostProcess?.width!==this._ping.width||this._taaPostProcess?.height!==this._ping.height){const e=this._scene.getEngine();this._createPingPongTextures(e.getRenderWidth(),e.getRenderHeight())}if(e&&!e.hasMoved)if(e.mode===In.PERSPECTIVE_CAMERA){const t=e.getProjectionMatrix();t.setRowFromFloats(2,this._hs.x,this._hs.y,t.m[10],t.m[11])}else{const t=e.getProjectionMatrix(!0);t.setRowFromFloats(3,this._hs.x+t.m[12],this._hs.y+t.m[13],t.m[14],t.m[15])}this._passPostProcess&&(this._passPostProcess.inputTexture=this._pingpong?this._ping:this._pong),this._pingpong=1^this._pingpong,this._hs.next()})),this._taaPostProcess.onApplyObservable.add((e=>{const t=this._scene.activeCamera;e._bindTexture("historySampler",this._pingpong?this._ping.texture:this._pong.texture),e.setFloat("factor",t?.hasMoved&&this.disableOnCameraMove||this._firstUpdate?1:this.factor),this._firstUpdate=!1}))}_createPassPostProcess(){const e=this._scene.getEngine();this._passPostProcess=new yc("TAAPass",1,null,1,e),this._passPostProcess.inputTexture=this._ping,this._passPostProcess.autoClear=!1}serialize(){const e=St.Serialize(this);return e.customType="TAARenderingPipeline",e}static Parse(e,t,i){return St.Parse((()=>new BP(e._name,t,e._ratio)),e,t,i)}}Ze([rt("samples")],BP.prototype,"_samples",void 0),Ze([rt("msaaSamples")],BP.prototype,"_msaaSamples",void 0),Ze([rt()],BP.prototype,"factor",void 0),Ze([rt()],BP.prototype,"disableOnCameraMove",void 0),Ze([rt("isEnabled")],BP.prototype,"_isEnabled",void 0),z("BABYLON.TAARenderingPipeline",BP);var kP;Bi.ShadersStore.tonemapPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{return dot(c,vec3(0.22,0.707,0.071));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);}",function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(kP||(kP={}));class VP extends Vl{getClassName(){return"TonemapPostProcess"}constructor(e,t,i,s,r=2,n,o=0,a){super(e,"tonemap",["_ExposureAdjustment"],null,1,s,r,n,a,null,o),this._operator=t,this.exposureAdjustment=i;let l="#define ";this._operator===kP.Hable?l+="HABLE_TONEMAPPING":this._operator===kP.Reinhard?l+="REINHARD_TONEMAPPING":this._operator===kP.HejiDawson?l+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":this._operator===kP.Photographic&&(l+="PHOTOGRAPHIC_TONEMAPPING"),this.updateEffect(l),this.onApply=e=>{e.setFloat("_ExposureAdjustment",this.exposureAdjustment)}}}Bi.ShadersStore.volumetricLightScatteringPixelShader="uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add((e=>{this._updateMeshScreenCoordinates(l),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)}))}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){const i=e.getMesh();if(i===this.mesh&&i.material)return i.material.isReady(i);const s=i._internalAbstractMeshDataInfo._materialForRenderPass?.[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(i,e,t);const r=[],n=[er.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&r.push("#define ALPHATEST"),i.isVerticesDataPresent(er.UVKind)&&(n.push(er.UVKind),r.push("#define UV1")),i.isVerticesDataPresent(er.UV2Kind)&&(n.push(er.UV2Kind),r.push("#define UV2"))),i.useBones&&i.computeBonesUsingShaders?(n.push(er.MatricesIndicesKind),n.push(er.MatricesWeightsKind),r.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),r.push("#define BonesPerMesh "+(i.skeleton?i.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0"),t&&(r.push("#define INSTANCES"),Po(n),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));const a=e._getDrawWrapper(void 0,!0),l=a.defines,h=r.join("\n");return l!==h&&a.setEffect(i.getScene().getEngine().createEffect("volumetricLightScatteringPass",n,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],h,void 0,void 0,void 0,{maxSimultaneousMorphTargets:i.numBoneInfluencers}),h),a.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){const t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==t&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)}_createPass(e,t){const i=e.getEngine();this._volumetricLightScatteringRTT=new ih("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=Pa.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=Pa.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const r=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh();if(this._meshExcluded(t))return;i._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const s=e.getMaterial();if(!s)return;const r=t.getScene(),n=r.getEngine();n.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=n.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances);if(this._isReady(e,a)){const l=i._internalAbstractMeshDataInfo._materialForRenderPass?.[n.currentRenderPassId];let h=e._getDrawWrapper();if(t!==this.mesh||h||(h=s._getDrawWrapper()),!h)return;const c=h.effect;if(n.enableEffect(h),a||t._bind(e,c,s.fillMode),t===this.mesh)s.bind(i.getWorldMatrix(),t);else if(l)l.bindForSubMesh(i.getWorldMatrix(),i,e);else{if(c.setMatrix("viewProjection",r.getTransformMatrix()),s&&s.needAlphaTesting()){const e=s.getAlphaTestTexture();c.setTexture("diffuseSampler",e),e&&c.setMatrix("diffuseMatrix",e.getTextureMatrix())}t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&c.setMatrices("mBones",t.skeleton.getTransformMatrices(t))}a&&t.hasThinInstances&&c.setMatrix("world",i.getWorldMatrix()),t._processRendering(i,e,c,ta.TriangleFillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}};let n;const o=new Ae(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((()=>{n=e.clearColor,e.clearColor=o})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((()=>{e.clearColor=n})),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,s)=>{if((s||0===t)&&e.subMeshes)for(let t=0;t{const o=e.getEngine();let a;if(n.length){for(o.setColorWrite(!1),a=0;ae._alphaIndex>t._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0)),o.setAlphaMode(2),a=0;a{e.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));const t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}):Ne.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=re.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,s){return St.Parse((()=>new GP(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}Ze([rt()],GP.prototype,"ridge",void 0),Ze([rt()],GP.prototype,"valley",void 0),z("BABYLON.ScreenSpaceCurvaturePostProcess",GP);Bi.IncludesShadersStore.boundingBoxRendererFragmentDeclaration="uniform vec4 color;\n";Bi.IncludesShadersStore.boundingBoxRendererUboDeclaration="#ifdef WEBGL2\nuniform vec4 color;uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#else\nlayout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;};\n#endif\n";Bi.ShadersStore.boundingBoxRendererPixelShader="#include<__decl__boundingBoxRendererFragment>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.IncludesShadersStore.boundingBoxRendererVertexDeclaration="uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n";Bi.ShadersStore.boundingBoxRendererVertexShader="attribute vec3 position;\n#include<__decl__boundingBoxRendererVertex>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec4 worldPos=world*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n",Object.defineProperty(Hr.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),Hr.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new zP(this)),this._boundingBoxRenderer},Object.defineProperty(_o.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class zP{constructor(e){this.name=or.NAME_BOUNDINGBOXRENDERER,this.frontColor=new Ee(1,1,1),this.backColor=new Ee(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new K,this.onAfterBoxRenderingObservable=new K,this.onResourcesReadyObservable=new K,this.enabled=!0,this.renderList=new Fs(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new Zs(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new Zs(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(or.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(or.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(or.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(or.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){const i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){const t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new Nd("colorShader",this.scene,"boundingBoxRenderer",{attributes:[er.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new Nd("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[er.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=ld({size:1});this._vertexBuffers[er.PositionKind]=new er(e,t.positions,er.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){const e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){const e=this._vertexBuffers[er.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){if(0===this.renderList.length||!this.enabled)return;if(this._prepareResources(),!this._colorShader.isReady())return;const t=this.scene.getEngine();t.setDepthWrite(!1);const i=this.scene.getTransformMatrix();for(let s=0;s{let t=e._getComponent(or.NAME_DEPTHRENDERER);t||(t=new WP(e),e._addComponent(t))};Bi.ShadersStore.oitFinalPixelShader="precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4(\nfrontColor.rgb+alphaMultiplier*backColor.rgb,\nfrontColor.a+backColor.a\n);}";Bi.ShadersStore.oitBackBlendPixelShader="precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { \ndiscard;}}";class HP{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class XP{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new Fs(10),this._excludedSubMeshes=new Fs(10),this._excludedMeshes=[],this._colorCache=[new Ae(XP._DEPTH_CLEAR_VALUE,XP._DEPTH_CLEAR_VALUE,0,0),new Ae(-XP._MIN_DEPTH,XP._MAX_DEPTH,0,0),new Ae(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,e.enablePrePassRenderer()){for(let e=0;e\nuniform vec4 color;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.lineVertexShader="#include\n#include\nattribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio;\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nmat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}",_o.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},_o.prototype.enableEdgesRendering=function(e=.95,t=!1,i){return this.disableEdgesRendering(),this._edgesRenderer=new jP(this,e,t,!0,i),this},Object.defineProperty(_o.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),Fd.prototype.enableEdgesRendering=function(e=.95,t=!1){return this.disableEdgesRendering(),this._edgesRenderer=new KP(this,e,t),this},Ld.prototype.enableEdgesRendering=function(e=.95,t=!1){return Fd.prototype.enableEdgesRendering.apply(this,arguments),this};class QP{constructor(){this.edges=[],this.edgesConnectedCount=0}}class jP{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){const t=new Nd("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,s=!0,r){this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new Fs(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=r??null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new Un(e.getEngine())),this._prepareRessources(),s&&(r?.useAlternateEdgeFinder??1?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add((()=>{this._rebuild()})),this._meshDisposeObserver=this._source.onDisposeObservable.add((()=>{this.dispose()}))}_prepareRessources(){this._lineShader||(this._lineShader=jP._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[er.PositionKind];e&&e._rebuild(),e=this._buffers[er.NormalKind],e&&e._rebuild();const t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)}dispose(){this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let e=this._buffers[er.PositionKind];e&&(e.dispose(),this._buffers[er.PositionKind]=null),e=this._buffers[er.NormalKind],e&&(e.dispose(),this._buffers[er.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),this._drawWrapper?.dispose()}_processEdgeForAdjacencies(e,t,i,s,r){return e===i&&t===s||e===s&&t===i?0:e===s&&t===r||e===r&&t===s?1:e===r&&t===i||e===i&&t===r?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,s,r){const n=1e-10;return e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(s,n)||e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(i,n)?0:e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(r,n)||e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(s,n)?1:e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(i,n)||e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(r,n)?2:-1}_checkEdge(e,t,i,s,r){let n;n=void 0===t||_e.Dot(i[e],i[t]){i>=0&&t.push(i);for(let i=0;i=e[0].length&&e[1].length>=e[2].length?n=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(n=2);for(let t=0;t<3;++t)t===n?e[t].sort(((e,t)=>e[1]t[1]?1:0)):e[t].sort(((e,t)=>e[1]>t[1]?-1:e[1]=n+1;--o)r(e[o%3],a,o!==n+2?s[i[t+(o+1)%3]]:-1);const h=a.length;i.push(s[i[t+n]],o[0],a[0]),i.push(s[i[t+(n+1)%3]],a[h-1],o[l-1]);const c=l<=h,u=c?l:h,d=c?h:l,_=c?l-1:h-1,p=c?0:1;let f=l+h-2,m=0,g=0;const v=c?o:a,x=c?a:o;let b=0;for(;f-- >0;){let e;p?i.push(v[m],x[g]):i.push(x[g],v[m]),b+=u,b>=d&&m<_?(e=v[++m],b-=d):e=x[++g],i.push(e)}i[t+0]=i[i.length-3],i[t+1]=i[i.length-2],i[t+2]=i[i.length-1],i.length=i.length-3}_generateEdgesLinesAlternate(){const e=this._source.getVerticesData(er.PositionKind);let t=this._source.getIndices();if(!t||!e)return;Array.isArray(t)||(t=Array.from(t));const i=this._options?.useFastVertexMerger??!0,s=i?Math.round(-Math.log(this._options?.epsilonVertexMerge??1e-6)/Math.log(10)):this._options?.epsilonVertexMerge??1e-6,r=[],n=[];if(i){const t={};for(let i=0;il){const e=a;a=l,l=e}const c=a+"_"+l,u=o[c];u?u.done||(_e.Dot(s,u.normal)0||this._source.hasThinInstances)}render(){const e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera)return void this._lineShader._setDrawWrapper(t);const i=this._source.hasInstances&&this.customInstances.length>0,s=i||this._source.hasThinInstances;let r=0;if(s)if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){const e=this._source._instanceDataStorage;if(r=this.customInstances.length,!e.instancesData)return void(this._source.getScene()._activeMeshesFrozen||this.customInstances.reset());if(!e.isFrozen){let t=0;for(let i=0;i0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[r]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),s.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(s)}_resetLayout(){for(let e=0;enull!=e)),this._scene.autoClear=!0;const s=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!s&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const r=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||s,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?o=n:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:r&&(o=r),this._bindFrameBuffer(),this._linkInternalTexture(e,o)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;enull!=e)),e)){for(let s=0;s=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw xt("PrePassRendererSceneComponent")},qP.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}],Object.defineProperty(Hr.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),Hr.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new qP(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,Ne.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},Hr.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class ZP{constructor(e){this.name=or.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(or.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(or.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(or.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(or.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(or.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(or.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(or.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(or.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,s){if(!s)return;const r=e.getScene();r.prePassRenderer&&r.prePassRenderer.bindAttachmentsForEffect(s,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){}dispose(){this.scene.disablePrePassRenderer()}}qP._SceneComponentInitialization=e=>{let t=e._getComponent(or.NAME_PREPASSRENDERER);t||(t=new ZP(e),e._addComponent(t))};Bi.IncludesShadersStore.fibonacci="#define rcp(x) 1./x\n#define GOLDEN_RATIO 1.618033988749895\n#define TWO_PI 6.2831855\nvec2 Golden2dSeq(int i,float n)\n{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));}\nvec2 SampleDiskGolden(int i,int sampleCount)\n{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}";Bi.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";Bi.ShadersStore.subSurfaceScatteringPixelShader="#include\n#include\n#include\n#include\nvarying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40;\n#define rcp(x) 1./x\n#define Sq(x) x*x\n#define SSS_BILATERAL_FILTER true\nvec3 EvalBurleyDiffusionProfile(float r,vec3 S)\n{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); \nvec3 expSum=exp_13*(1.+exp_13*exp_13); \nreturn (S*rcp(8.*PI))*expSum; }\nvec2 SampleBurleyDiffusionProfile(float u,float rcpS)\n{u=1.-u; \nfloat g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); \nfloat p=(g*n)*n; \nfloat c=1.+p+n; \nfloat d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); \nfloat x=(3./LOG2_E)*log2(c)-d; \nfloat rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; \nreturn vec2(r,rcpPdf);}\nvec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)\n{\n#ifndef SSS_BILATERAL_FILTER\nz=0.;\n#endif\nfloat r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf;\n#if SSS_CLAMP_ARTIFACT\nreturn clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);\n#else\nreturn EvalBurleyDiffusionProfile(r,S)*area;\n#endif\n}\nvoid EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,\nfloat phase,inout vec3 totalIrradiance,inout vec3 totalWeight)\n{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; \nfloat cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; \nvec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; \nfloat xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a))\n{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;}\nelse\n{}}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest)\n{centerDepth=texture2D(depthSampler,vUV).r;}\nif (!passedStencilTest) { \ngl_FragColor=inputColor;return;}\nfloat distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; \nvec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; \nfloat mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1)\n{\n#ifdef DEBUG_SSS_SAMPLES\nvec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return;\n#endif\ngl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;}\n#ifdef DEBUG_SSS_SAMPLES\nvec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return;\n#endif\nfloat phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); \nvec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration)return void Ne.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");const i=this.texelSize;e.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",i.x,i.y),e.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),e.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),e.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),e.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),e.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)}))}}class eI{get ssDiffusionS(){return this._ssDiffusionS}get ssDiffusionD(){return this._ssDiffusionD}get ssFilterRadii(){return this._ssFilterRadii}constructor(e){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=or.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new Ee(1,1,1)),this._scene=e,eI._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return Ne.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw xt("SubSurfaceSceneComponent")},X.AddParser(or.NAME_SUBSURFACE,((e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,s=e.ssDiffusionProfileColors.length;i{let t=e._getComponent(or.NAME_SUBSURFACE);t||(t=new tI(e),e._addComponent(t))};Bi.ShadersStore.outlinePixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.outlineVertexShader="attribute vec3 position;attribute vec3 normal;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n#include\n}\n",Hr.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new iI(this)),this._outlineRenderer},Object.defineProperty(ha.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(ha.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});class iI{constructor(e){this.name=or.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(or.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(or.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{_.setMatrix("world",t)})),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=i??this._passIdForDrawWrapper[0];const s=[],r=[er.PositionKind,er.NormalKind],n=e.getMesh(),o=e.getMaterial();if(!o)return!1;const a=n.getScene();o.needAlphaTesting()&&(s.push("#define ALPHATEST"),n.isVerticesDataPresent(er.UVKind)&&(r.push(er.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(er.UV2Kind)&&(r.push(er.UV2Kind),s.push("#define UV2"))),o.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),go(o,a,s),n.useBones&&n.computeBonesUsingShaders?(r.push(er.MatricesIndicesKind),r.push(er.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(er.MatricesIndicesExtraKind),r.push(er.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):s.push("#define NUM_BONE_INFLUENCERS 0");const l=n.morphTargetManager;let h=0;l&&(h=l.numMaxInfluencers||l.numInfluencers,h>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),Eo(r,n,h))),t&&(s.push("#define INSTANCES"),Po(r),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const c=e._getDrawWrapper(i,!0),u=c.defines,d=s.join("\n");if(u!==d){const e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];mo(e),c.setEffect(this.scene.getEngine().createEffect("outline",r,e,["diffuseSampler","morphTargets"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),d)}return c.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const s=t.getMaterial();s&&s.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(iI._StencilReference),this._engine.setStencilFunctionReference(iI._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),s&&s.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const e=this._engine.getAlphaMode(),s=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=s}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}iI._StencilReference=4;class sI{get particleSize(){return this._particleSize}set particleSize(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))}get useInstancing(){return!this.indexBuffer}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&this._hasVelocity()&&(this._useVelocity=e,this._effectsAreDirty=!0)}_hasVelocity(){return!!this.vertexBuffers?.velocity}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new K,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){const e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new $l({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new $l({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})}isReady(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;const e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){const e=this.numParticles;if(!this._depthEffectWrapper||0===e)return;const t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}renderThicknessTexture(){const e=this.numParticles;if(!this._thicknessEffectWrapper||0===e)return;const t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(6),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0)}renderDiffuseTexture(){}dispose(){this._depthEffectWrapper?.dispose(),this._thicknessEffectWrapper?.dispose()}}class rI extends sI{get particleSystem(){return this._particleSystem}getClassName(){return"FluidRenderingObjectParticleSystem"}get useTrueRenderingForDiffuseTexture(){return this._useTrueRenderingForDiffuseTexture}set useTrueRenderingForDiffuseTexture(e){this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add((()=>{this._engine.setAlphaMode(2)}))))}get vertexBuffers(){return this._particleSystem.vertexBuffers}get indexBuffer(){return this._particleSystem.indexBuffer}constructor(e,t){super(e),this._useTrueRenderingForDiffuseTexture=!0,this._particleSystem=t,this._originalRender=t.render.bind(t),this._blendMode=t.blendMode,this._onBeforeDrawParticleObserver=null,this._updateInAnimate=this._particleSystem.updateInAnimate,this._particleSystem.updateInAnimate=!0,this._particleSystem.render=()=>0,this.particleSize=(t.minSize+t.maxSize)/2,this.useTrueRenderingForDiffuseTexture=!1}isReady(){return super.isReady()&&this._particleSystem.isReady()}get numParticles(){return this._particleSystem.getActiveCount()}renderDiffuseTexture(){this._originalRender()}dispose(){super.dispose(),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate}}class nI{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){const e=this._blurPostProcesses[0],t=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let i=0;i<2*this._blurNumIterations;++i)this._blurPostProcesses[i]=1&i?t:e}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}constructor(e,t,i,s,r,n,o=1,a=6,l=1,h=6,c=!1,u=null,d=!0,_=1){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new K,this._name=e,this._scene=t,this._camera=u,this._engine=t.getEngine(),this._width=i,this._height=s,this._blurTextureSizeX=r,this._blurTextureSizeY=n,this._textureType=o,this._textureFormat=a,this._blurTextureType=l,this._blurTextureFormat=h,this._useStandardBlur=c,this._generateDepthBuffer=d,this._samples=_,this._postProcessRunningIndex=0,this.enableBlur=0!==r&&0!==n,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){const[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});const e=this._rt.texture;e.incrementReferences(),this._texture=new Pa(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=Pa.CLAMP_ADDRESSMODE,this._texture.wrapV=Pa.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,s,r,n=!1){const o=this._scene.getEngine(),a=new de(Math.floor(this._blurTextureSizeX/s),Math.floor(this._blurTextureSizeY/s)),l=1===t&&o.getCaps().textureFloatLinearFiltering||2===t&&o.getCaps().textureHalfFloatLinearFiltering,h=this._engine.createRenderTargetTexture({width:a.x,height:a.y},{generateMipMaps:!1,type:t,format:i,samplingMode:l?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${r}`}),c=h.texture;c.incrementReferences();const u=new Pa(null,this._scene);if(u.name="rttBlurred"+r,u._texture=c,u.wrapU=Pa.CLAMP_ADDRESSMODE,u.wrapV=Pa.CLAMP_ADDRESSMODE,u.anisotropicFilteringLevel=1,n){const s=new Vl("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",s.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++})),s.onSizeChangedObservable.add((()=>{s._textures.forEach((e=>{e.texture.wrapU=Pa.CLAMP_ADDRESSMODE,e.texture.wrapV=Pa.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(s);const r=new Vl("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.onApplyObservable.add((e=>{e.setInt("filterSize",this.blurFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++})),r.onSizeChangedObservable.add((()=>{r._textures.forEach((e=>{e.texture.wrapU=Pa.CLAMP_ADDRESSMODE,e.texture.wrapV=Pa.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(r),s.autoClear=!1,r.autoClear=!1;const n=[];for(let e=0;e<2*this._blurNumIterations;++e)n[e]=1&e?r:s;return[h,u,n]}{const s=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],r=new Vl("BilateralBlurX","fluidRenderingBilateralBlur",s,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",r.inputTexture.texture),t.setInt("maxFilterSize",this.blurMaxFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),t.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),r.onSizeChangedObservable.add((()=>{r._textures.forEach((e=>{e.texture.wrapU=Pa.CLAMP_ADDRESSMODE,e.texture.wrapV=Pa.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(r);const n=new Vl("BilateralBlurY","fluidRenderingBilateralBlur",s,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);n.samples=this._samples,n.onApplyObservable.add((e=>{e.setInt("maxFilterSize",this.blurMaxFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),e.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),e.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),n.onSizeChangedObservable.add((()=>{n._textures.forEach((e=>{e.texture.wrapU=Pa.CLAMP_ADDRESSMODE,e.texture.wrapV=Pa.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(n),r.autoClear=!1,n.autoClear=!1;const a=[];for(let e=0;e<2*this._blurNumIterations;++e)a[e]=1&e?n:r;return[h,u,a]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})),e.onApplyObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})))}_getProjectedParticleConstant(){return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((this._camera?.fov??45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),this._rt?.dispose(),this._rt=null,this._texture?.dispose(),this._texture=null,this._rtBlur?.dispose(),this._rtBlur=null,this._textureBlurred?.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}var oI;!function(e){e[e.DepthTexture=0]="DepthTexture",e[e.DepthBlurredTexture=1]="DepthBlurredTexture",e[e.ThicknessTexture=2]="ThicknessTexture",e[e.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",e[e.DiffuseTexture=4]="DiffuseTexture",e[e.Normals=5]="Normals",e[e.DiffuseRendering=6]="DiffuseRendering"}(oI||(oI={}));class aI{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get compositeMode(){return this._compositeMode}set compositeMode(e){this._compositeMode!==e&&(this._compositeMode=e,this._needInitialization=!0)}get camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new Ee(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new _e(-2,-1,1).normalize(),this._debugFeature=oI.DepthBlurredTexture,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new K,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._compositeMode=!1,this._scene=e,this._engine=e.getEngine(),this._camera=t??e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new me,this._depthClearColor=new Ae(1e6,1e6,1e6,1),this._thicknessClearColor=new Ae(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){this.dispose(),this._needInitialization=!1;const e=this._depthMapSize??this._engine.getRenderWidth(),t=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new nI("Depth",this._scene,e,t,e,t,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const e=this._diffuseMapSize??this._engine.getRenderWidth(),t=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new nI("Diffuse",this._scene,e,t,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const i=this._thicknessMapSize??this._engine.getRenderWidth(),s=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new nI("Thickness",this._scene,i,s,i,s,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){null!==e&&e!==this._depthRenderTarget||this._setBlurDepthParameters(),null!==e&&e!==this._thicknessRenderTarget||this._setBlurThicknessParameters()}_setBlurDepthParameters(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)}_setBlurThicknessParameters(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)}_initializeRenderTarget(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()}_createLiquidRenderingPostProcess(){const e=this._scene.getEngine(),t=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],i=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;const r=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,n=new de(1/r.getSize().width,1/r.getSize().height);this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap&&(this._environmentMap??this._scene.environmentTexture)&&(i.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(i.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):t.push("diffuseColor"),this._useVelocity&&(i.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(t.push("thickness"),i.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(t.push("minimumThickness"),i.push("thicknessSampler")),this._compositeMode&&s.push("#define FLUIDRENDERING_COMPOSITE_MODE"),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===oI.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===oI.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),i.push("debugSampler"),this._debugFeature!==oI.DepthTexture&&this._debugFeature!==oI.DepthBlurredTexture||s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new Vl("FluidRendering","fluidRenderingRender",t,i,1,null,2,e,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(s.join("\n")),this._renderPostProcess.samples=this._samples;const o=e,a=o.setTextureSampler;this._renderPostProcess.onApplyObservable.add((e=>{if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),a&&a.call(o,"textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(e.setTexture("depthSampler",this._depthRenderTarget.textureBlur),a&&a.call(o,"depthSamplerSampler",this._depthRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),a&&a.call(o,"depthSamplerSampler",this._depthRenderTarget.texture?.getInternalTexture()??null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),a&&a.call(o,"diffuseSamplerSampler",this._diffuseRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),a&&a.call(o,"diffuseSamplerSampler",this._diffuseRenderTarget.texture?.getInternalTexture()??null)):e.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(e.setFloat("thickness",this.minimumThickness),e._bindTexture("bgDepthSampler",this._bgDepthTexture),a&&a.call(o,"bgDepthSamplerSampler",this._bgDepthTexture??null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),a&&a.call(o,"thicknessSamplerSampler",this._thicknessRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),a&&a.call(o,"thicknessSamplerSampler",this._thicknessRenderTarget.texture?.getInternalTexture()??null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){const t=this._environmentMap??this._scene.environmentTexture;t&&(e.setTexture("reflectionSampler",t),a&&a.call(o,"reflectionSamplerSampler",t?.getInternalTexture()??null))}if(e.setMatrix("viewMatrix",this._scene.getViewMatrix()),e.setMatrix("invProjectionMatrix",this._invProjectionMatrix),e.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),e.setVector2("texelSize",n),e.setFloat("density",this.density),e.setFloat("refractionStrength",this.refractionStrength),e.setFloat("fresnelClamp",this.fresnelClamp),e.setFloat("specularPower",this.specularPower),e.setVector3("dirLight",this.dirLight),e.setFloat("cameraFar",this._camera.maxZ),this._debug){let t=null;switch(this._debugFeature){case oI.DepthTexture:t=this._depthRenderTarget.texture;break;case oI.DepthBlurredTexture:t=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case oI.ThicknessTexture:t=this._thicknessRenderTarget?.texture??null;break;case oI.ThicknessBlurredTexture:t=this._thicknessRenderTarget?.enableBlur?this._thicknessRenderTarget?.textureBlur??null:this._thicknessRenderTarget?.texture??null;break;case oI.DiffuseTexture:this._diffuseRenderTarget&&(t=this._diffuseRenderTarget.texture)}this._debugFeature!==oI.Normals&&(e.setTexture("debugSampler",t),a&&a.call(o,"debugSamplerSampler",t?.getInternalTexture()??null))}}))}_clearTargets(){this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){if(this._needInitialization||!e.isReady())return;const t=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0),this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),this._depthRenderTarget?.applyBlurPostProcesses(),this._diffuseRenderTarget?.applyBlurPostProcesses(),this._thicknessRenderTarget?.applyBlurPostProcesses(),t&&this._engine.bindFramebuffer(t)}dispose(e=!1){e||(this._depthRenderTarget?.dispose(),this._depthRenderTarget=null,this._diffuseRenderTarget?.dispose(),this._diffuseRenderTarget=null,this._thicknessRenderTarget?.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),this._renderPostProcess?.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class lI extends sI{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i){super(e),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(const t in e){let i,s=!0;switch(t){case"velocity":i=3;break;case"offset":s=!1}this._vertexBuffers[t]=new er(this._engine,e[t],t,!0,!1,i,s)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new $l({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[]})}isReady(){return this._vertexBuffers.offset||(this._vertexBuffers.offset=new er(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&(this._diffuseEffectWrapper?.effect.isReady()??!1)}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){const e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)return;const t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),null!==this._particleSize&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){super.dispose(),this._diffuseEffectWrapper?.dispose();for(const e in this._vertexBuffers)this._vertexBuffers[e].dispose();this._vertexBuffers={}}}var hI;Bi.ShadersStore.copyTextureToTexturePixelShader="uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV;\n#include\nvoid main(void) \n{vec4 color=texture2D(textureSampler,vUV);\n#ifdef DEPTH_TEXTURE\ngl_FragDepth=color.r;\n#else\nif (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);}\ngl_FragColor=color;\n#endif\n}\n",function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(hI||(hI={}));class cI{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new Kl(e),this._effectWrapper=new $l({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add((()=>{t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.depthCullingState.depthFunc=519),this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)}))}isReady(){return this._effectWrapper.effect.isReady()}copy(e,t,i=hI.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;const s=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&s&&(this._engine.depthCullingState.depthFunc=s),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class uI{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,s=1){this._engine=e,this._copyTextureToTexture=new cI(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:s,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil").label=`FluidDepthTextureCopy${t}x${i}x${s}`}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}Bi.ShadersStore.fluidRenderingParticleDepthVertexShader="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nattribute vec3 velocity;varying float velocityNorm;\n#endif\nvoid main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0;\n#ifdef FLUIDRENDERING_VELOCITY\nvelocityNorm=length(velocity);\n#endif\n}\n";Bi.ShadersStore.fluidRenderingParticleDepthPixelShader="uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nvarying float velocityNorm;\n#endif\nvoid main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2);\n#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\n#endif\nvec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos;\n#ifdef WEBGPU\ngl_FragDepth=clipSpacePos.z/clipSpacePos.w;\n#else\ngl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;\n#endif\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nglFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);\n#else\nglFragColor=vec4(realViewPos.z,0.,0.,1.);\n#endif\n}\n";Bi.ShadersStore.fluidRenderingParticleThicknessVertexShader="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;}\n";Bi.ShadersStore.fluidRenderingParticleThicknessPixelShader="uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);}\n";Bi.ShadersStore.fluidRenderingParticleDiffuseVertexShader="attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;}\n";Bi.ShadersStore.fluidRenderingParticleDiffusePixelShader="uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);}\n";Bi.ShadersStore.fluidRenderingBilateralBlurPixelShader="uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;}\nint filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;}\nglFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);}\n";Bi.ShadersStore.fluidRenderingStandardBlurPixelShader="uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;}\nfloat sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;}\nsum/=wsum;glFragColor=vec4(sum.rgb,1.);}\n";function dI(e){return!!e.particleSystem}function _I(e){return!!e.addBuffers}Bi.ShadersStore.fluidRenderingRenderPixelShader="#define DISABLE_UNIFORMITY_ANALYSIS\n#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nuniform sampler2D textureSampler;uniform sampler2D depthSampler;\n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nuniform sampler2D diffuseSampler;\n#else\nuniform vec3 diffuseColor;\n#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform float thickness;uniform sampler2D bgDepthSampler;\n#else\nuniform float minimumThickness;uniform sampler2D thicknessSampler;\n#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nuniform samplerCube reflectionSampler;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nuniform sampler2D debugSampler;\n#endif\nuniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef FLUIDRENDERING_RHS\nndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#else\nndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\nvec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);}\nvoid main(void) {vec2 texCoord=vUV;\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvec4 color=texture2D(debugSampler,texCoord);\n#ifdef FLUIDRENDERING_DEBUG_DEPTH\nglFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);}\n#else\nglFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);}\n#endif\nreturn;\n#endif\nvec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r;\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nfloat thickness=texture2D(thicknessSampler,texCoord).x;\n#else\nfloat bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5;\n#endif\nvec4 backColor=texture2D(textureSampler,texCoord);\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {\n#else\nif (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\n#endif\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nglFragColor.rgb=backColor.rgb*backColor.a;glFragColor.a=backColor.a;\n#else\nglFragColor=backColor;\n#endif\nreturn;}\nvec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;}\nvec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;}\nvec3 normal=normalize(cross(ddy,ddx));\n#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\n#endif\n#ifndef WEBGPU\nif(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);}\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nglFragColor=vec4(normal*0.5+0.5,1.0);return;\n#endif\nvec3 rayDir=normalize(viewPos); \n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;\n#endif\nvec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower);\n#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nfloat diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return;\n#endif\nvec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nif (transmitted.a==0.) transmitted.a=thickness;\n#endif\nvec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); \nvec3 refractionColor=transmitted.rgb*transmittance;\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular;\n#else\nvec3 finalColor=refractionColor+specular;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfloat velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));\n#endif\nglFragColor=vec4(finalColor,transmitted.a);}\n",Object.defineProperty(Hr.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),Hr.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new fI(this)),this._fluidRenderer},Hr.prototype.disableFluidRenderer=function(){this._fluidRenderer?.dispose(),this._fluidRenderer=null};class pI{constructor(e){this.name=or.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(or.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(or.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){this.scene.fluidRenderer?._prepareRendering()}_afterCameraDraw(e){this.scene.fluidRenderer?._render(e)}rebuild(){const e=this.scene.fluidRenderer;if(!e)return;const t=new Set;for(let i=0;i{e._rebuild()}))}dispose(){this.scene.disableFluidRenderer()}}class fI{static _SceneComponentInitialization(e){let t=e._getComponent(or.NAME_FLUIDRENDERER);t||(t=new pI(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,fI._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add((()=>{this._initialize()}))}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){const t=this._getParticleSystemIndex(e);return-1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,s){const r=new rI(this._scene,e);r.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),i||(i=new aI(this._scene,s),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==t&&(i.generateDiffuseTexture=t);const n={object:r,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,s,r){const n=new lI(this._scene,e,t);n.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),s||(s=new aI(this._scene,r),this.targetRenderers.push(s)),s._onUseVelocityChanged.hasObservers()||s._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==i&&(s.generateDiffuseTexture=i);const o={object:n,targetRenderer:s};return this.renderObjects.push(o),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),o}removeRenderObject(e,t=!0){const i=this.renderObjects.indexOf(e);return-1!==i&&(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort(((e,t)=>e.object.priorityt.object.priority?1:0))}_removeUnusedTargetRenderers(){const e={};for(let t=0;t{r.inputTexture.depthStencilTexture||r.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,n[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${r.name}`);for(const e of n){const t=e._thicknessRenderTarget?.renderTarget,i=t?.texture;if(t&&i){const e=i.width+"_"+i.height;let s=o[e];s||(s=o[e]=new uI(this._engine,i.width,i.height)),s.depthRTWrapper.shareDepth(t)}}}))}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value,s=this._cameras.get(t)[1],r=e.get(t);if(r)for(const e in s)r[1][e]||s[e].dispose();else for(const e in s)s[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){const e=new Map;for(let t=0;t{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)}))}_setUseVelocityForRenderObject(){for(const e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(const e of this.targetRenderers)if(e.needInitialization)return void this._initialize()}_render(e){for(let t=0;t{const t=e[1];for(const e in t)t[e].dispose()})),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class mI{get enable(){return this._enable}set enable(e){this._enable!==e&&(this._enable=e,this._customRenderTarget(e))}get positionWorldTexture(){return this._mrt.textures[0]}get normalWorldTexture(){return this._mrt.textures[1]}get fluxTexture(){return this._mrt.textures[2]}get renderList(){return this._mrt.renderList}get light(){return this._light}constructor(e,t,i={width:512,height:512}){this._lightTransformMatrix=me.Identity(),this._enable=!1,this.forceUpdateLightParameters=!1,this._scene=e,this._light=t,this._textureDimensions=i,this._regularMatToMatWithPlugin=new Map,this._counters=[{name:"RSM Generation "+t.name,value:0}],this._createMultiRenderTarget(),this._recomputeLightTransformationMatrix(),this.enable=!0}setTextureDimensions(e){const t=this._mrt.renderList;this._textureDimensions=e,this._disposeMultiRenderTarget(),this._createMultiRenderTarget(),t?.forEach((e=>{this._addMeshToMRT(e)}))}addMesh(e){e?this._addMeshToMRT(e):this._scene.meshes.forEach((e=>{this._addMeshToMRT(e)})),this._recomputeLightTransformationMatrix()}updateLightParameters(){this._recomputeLightTransformationMatrix()}get lightTransformationMatrix(){return this.forceUpdateLightParameters&&this.updateLightParameters(),this._lightTransformMatrix}get countersGPU(){return this._counters}dispose(){this._disposeMultiRenderTarget()}_createMultiRenderTarget(){const e=this._light.name,t=this._scene.getEngine().getCaps(),i=t.rg11b10ufColorRenderable?13:2,s=t.rg11b10ufColorRenderable?4:5;let r,n;this._mrt=new xb("RSMmrt_"+e,this._textureDimensions,3,this._scene,{types:[2,11,i],samplingModes:[2,2,2],generateMipMaps:!1,targetTypes:[3553,3553,3553],formats:[5,5,s]},["RSMPosition_"+e,"RSMNormal_"+e,"RSMFlux_"+e]),this._mrt.renderList=[],this._mrt.clearColor=new Ae(0,0,0,1),this._mrt.noPrePassRenderer=!0;const o=this._scene.getEngine().supportsUniformBuffers;let a;o&&(r=this._scene.createSceneUniformBuffer(`Scene for RSM (light "${e}")`)),this._mrt.onBeforeBindObservable.add((()=>{n=this._scene.getSceneUniformBuffer(),a=this._light.shadowEnabled,this._light.shadowEnabled=!1})),this._mrt.onBeforeRenderObservable.add((e=>{r&&this._scene.setSceneUniformBuffer(r);const t=this._light.getViewMatrix(e),i=this._light.getProjectionMatrix(t||void 0,this._mrt.renderList||void 0);t&&i&&this._scene.setTransformMatrix(t,i),o&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._mrt.onAfterUnbindObservable.add((()=>{r&&this._scene.setSceneUniformBuffer(n),this._scene.updateTransformMatrix(),this._light.shadowEnabled=a,this._counters[0].value=this._mrt.renderTarget.gpuTimeInFrame?.counter.lastSecAverage??0})),this._customRenderTarget(!0)}_customRenderTarget(e){const t=this._scene.customRenderTargets.indexOf(this._mrt);e?-1===t&&this._scene.customRenderTargets.push(this._mrt):-1!==t&&this._scene.customRenderTargets.splice(t,1)}_recomputeLightTransformationMatrix(){const e=this._light.getViewMatrix(),t=this._light.getProjectionMatrix(e||void 0,this._mrt.renderList||void 0);e&&t&&e.multiplyToRef(t,this._lightTransformMatrix)}_addMeshToMRT(e){this._mrt.renderList?.push(e);const t=e.material;if(0===e.getTotalVertices()||!t)return;let i=this._regularMatToMatWithPlugin.get(t);if(!i&&(i=t.clone("RSMCreate_"+t.name)||void 0,i)){Object.defineProperty(i,"canRenderToMRT",{get:function(){return!1},enumerable:!0,configurable:!0}),i.disableLighting=!0;const e=new vI(i);e.isEnabled=!0,e.light=this._light,this._regularMatToMatWithPlugin.set(t,i)}this._mrt.setMaterialForRendering(e,i)}_disposeMultiRenderTarget(){this._customRenderTarget(!1),this._mrt.dispose()}}class gI extends xl{constructor(){super(...arguments),this.RSMCREATE=!1,this.RSMCREATE_PROJTEXTURE=!1,this.RSMCREATE_LIGHT_IS_SPOT=!1}}class vI extends nu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,vI.Name,300,new gI),this._lightColor=new Ee,this._hasProjectionTexture=!1,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._varAlbedoName=e instanceof Gg?"surfaceAlbedo":"baseColor.rgb"}prepareDefines(e){e.RSMCREATE=this._isEnabled,this._hasProjectionTexture=!1;const t=this.light.getTypeID()===ua.LIGHTTYPEID_SPOTLIGHT;if(t){const e=this.light;this._hasProjectionTexture=!!e.projectionTexture&&e.projectionTexture.isReady()}e.RSMCREATE_PROJTEXTURE=this._hasProjectionTexture,e.RSMCREATE_LIGHT_IS_SPOT=t}getClassName(){return"RSMCreatePluginMaterial"}getUniforms(){return{ubo:[{name:"rsmTextureProjectionMatrix",size:16,type:"mat4"},{name:"rsmSpotInfo",size:4,type:"vec4"},{name:"rsmLightColor",size:3,type:"vec3"},{name:"rsmLightPosition",size:3,type:"vec3"}],fragment:"#ifdef RSMCREATE\n uniform mat4 rsmTextureProjectionMatrix;\n uniform vec4 rsmSpotInfo;\n uniform vec3 rsmLightColor;\n uniform vec3 rsmLightPosition;\n #endif"}}getSamplers(e){e.push("rsmTextureProjectionSampler")}bindForSubMesh(e){if(this._isEnabled&&(this.light.diffuse.scaleToRef(this.light.getScaledIntensity(),this._lightColor),e.updateColor3("rsmLightColor",this._lightColor),this.light.getTypeID()===ua.LIGHTTYPEID_SPOTLIGHT)){const t=this.light;this._hasProjectionTexture&&(e.updateMatrix("rsmTextureProjectionMatrix",t.projectionTextureMatrix),e.setTexture("rsmTextureProjectionSampler",t.projectionTexture));const i=ve.Vector3[0];t.computeTransformedInformation()?(e.updateFloat3("rsmLightPosition",this.light.transformedPosition.x,this.light.transformedPosition.y,this.light.transformedPosition.z),t.transformedDirection.normalizeToRef(i)):(e.updateFloat3("rsmLightPosition",this.light.position.x,this.light.position.y,this.light.position.z),t.direction.normalizeToRef(i)),e.updateFloat4("rsmSpotInfo",i.x,i.y,i.z,Math.cos(.5*t.angle))}}getCustomCode(e){return"vertex"===e?null:{CUSTOM_FRAGMENT_BEGIN:"\n #ifdef RSMCREATE\n #extension GL_EXT_draw_buffers : require\n #endif\n ",CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RSMCREATE\n #ifdef RSMCREATE_PROJTEXTURE\n uniform highp sampler2D rsmTextureProjectionSampler; \n #endif\n layout(location = 0) out highp vec4 glFragData[3];\n vec4 glFragColor;\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:`\n #ifdef RSMCREATE\n vec3 rsmColor = ${this._varAlbedoName} * rsmLightColor;\n #ifdef RSMCREATE_PROJTEXTURE\n {\n vec4 strq = rsmTextureProjectionMatrix * vec4(vPositionW, 1.0);\n strq /= strq.w;\n rsmColor *= texture2D(rsmTextureProjectionSampler, strq.xy).rgb;\n }\n #endif\n #ifdef RSMCREATE_LIGHT_IS_SPOT\n {\n float cosAngle = max(0., dot(rsmSpotInfo.xyz, normalize(vPositionW - rsmLightPosition)));\n rsmColor = sign(cosAngle - rsmSpotInfo.w) * rsmColor;\n }\n #endif\n glFragData[0] = vec4(vPositionW, 1.);\n glFragData[1] = vec4(normalize(normalW) * 0.5 + 0.5, 1.);\n glFragData[2] = vec4(rsmColor, 1.);\n #endif\n `}}}vI.Name="RSMCreate",Ze([rt()],vI.prototype,"light",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],vI.prototype,"isEnabled",void 0),z("BABYLON.RSMCreatePluginMaterial",vI);class xI{constructor(e){this.numSamples=400,this.radius=.1,this.intensity=.1,this.edgeArtifactCorrection=.1,this.rotateSample=!0,this.noiseFactor=100,this.useFullTexture=!1,this.rsm=e}dispose(){this.rsm.dispose()}}Bi.ShadersStore.bilateralBlurPixelShader="uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec3 sampleColor=textureLod(textureSampler,vUV+coords*blurDir,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords*blurDir,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords*blurDir,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat r=dot(coords,coords);float w=exp(-r/two_sigma2);float depthDelta=abs(sampleDepth-depth);float wd=step(depthDelta,depthThreshold);vec3 normalDelta=abs(sampleNormal-normal);float wn=step(normalDelta.x+normalDelta.y+normalDelta.z,normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}\nglFragColor=vec4(sum/wsum,1.);}\n";Bi.ShadersStore.bilateralBlurQualityPixelShader="uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {for (int y=-filterSize; y<=filterSize; ++y) {vec2 coords=vec2(x,y)*blurDir;vec3 sampleColor=textureLod(textureSampler,vUV+coords,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepth-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);float rNormal=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);float wn=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}}\nglFragColor=vec4(sum/wsum,1.);}\n";Bi.ShadersStore.rsmGlobalIlluminationPixelShader="/**\n* The implementation is an application of the formula found in http:\n* For better results,it also adds a random (noise) rotation to the RSM samples (the noise artifacts are easier to remove than the banding artifacts).\n*/\nprecision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform vec4 rsmInfo2;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;uniform sampler2D rsmSamples;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nfloat mod289(float x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 perm(vec4 x){return mod289(((x*34.0)+1.0)*x);}\nfloat noise(vec3 p){vec3 a=floor(p);vec3 d=p-a;d=d*d*(3.0-2.0*d);vec4 b=a.xxyy+vec4(0.0,1.0,0.0,1.0);vec4 k1=perm(b.xyxy);vec4 k2=perm(k1.xyxy+b.zzww);vec4 c=k2+a.zzzz;vec4 k3=perm(c);vec4 k4=perm(c+1.0);vec4 o1=fract(k3*(1.0/41.0));vec4 o2=fract(k4*(1.0/41.0));vec4 o3=o2*d.z+o1*(1.0-d.z);vec2 o4=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);}\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);int numSamples=int(rsmInfo.x);float radius=rsmInfo.y;float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;float angle=noise(p*rsmInfo2.x);float c=cos(angle);float s=sin(angle);for (int i=0; i1. || uv.y<0. || uv.y>1.) continue;vec3 vplPositionW=textureLod(rsmPositionW,uv,0.).xyz;vec3 vplNormalW=textureLod(rsmNormalW,uv,0.).xyz*2.0-1.0;vec3 vplFlux=textureLod(rsmFlux,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; \nfloat dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}\nreturn clamp(indirectDiffuse*intensity,0.0,1.0);}\nvoid main(void) \n{vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz;\n#ifdef DECODE_NORMAL\nnormalW=normalW*2.0-1.0;\n#endif\n#ifdef TRANSFORM_NORMAL\nnormalW=(invView*vec4(normalW,0.)).xyz;\n#endif\ngl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;}\n";Bi.ShadersStore.rsmFullGlobalIlluminationPixelShader="/**\n* The implementation is a direct application of the formula found in http:\n*/\nprecision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;int width=int(rsmInfo.x);int height=int(rsmInfo.y);for (int j=0; j{t.pluginManager&&(t.pluginManager.getPlugin(yI.Name).isEnabled=e)})),this.recreateResources(!e))}get enableBlur(){return this._enableBlur}set enableBlur(e){e!==this._enableBlur&&(this._enableBlur=e,this.recreateResources())}get useQualityBlur(){return this._useQualityBlur}set useQualityBlur(e){e!==this._useQualityBlur&&(this._useQualityBlur=e,this.recreateResources())}get fullSizeBlur(){return this._forceFullSizeBlur}set fullSizeBlur(e){this._forceFullSizeBlur!==e&&(this._forceFullSizeBlur=e,this.recreateResources())}get useQualityUpsampling(){return this._useQualityUpsampling}set useQualityUpsampling(e){e!==this._useQualityUpsampling&&(this._useQualityUpsampling=e,this.recreateResources())}get showOnlyGI(){return this._showOnlyGI}set showOnlyGI(e){this._showOnlyGI!==e&&(this._showOnlyGI=e,this._debugLayer.isEnabled=e)}get use32BitsDepthBuffer(){return this._use32BitsDepthBuffer}set use32BitsDepthBuffer(e){this._use32BitsDepthBuffer!==e&&(this._use32BitsDepthBuffer=e,this.recreateResources())}setOutputDimensions(e){this._outputDimensions=e,this.recreateResources()}setGITextureDimensions(e){this._giTextureDimensions=e,this.recreateResources()}get giTextureType(){return this._giTextureType}set giTextureType(e){this._giTextureType!==e&&(this._giTextureType=e,this.recreateResources())}get giRSM(){return this._giRSM}addGIRSM(e){Array.isArray(e)?this._giRSM.push(...e):this._giRSM.push(e),this.recreateResources()}removeGIRSM(e){if(Array.isArray(e))for(let t=0;t{e.getTotalVertices()>0&&e.isEnabled()&&e.material&&this._addGISupportToMaterial(e.material)}))}get countersGPU(){return this._counters}recreateResources(e=!1){this._disposePostProcesses(e),this._createPostProcesses(),this._setPluginParameters()}generateSampleTexture(e){this._sampleTexture?.dispose(),this._maxSamples=e;const t=new Float32Array(4*this._maxSamples);for(let e=0;e{const e=this._engine._currentRenderTarget;let t=!1;if(this._enable){this.pause||(this._scene.postProcessManager.directRender(this._ppGlobalIllumination,this._ppGlobalIllumination[0].inputTexture),this._engine.unBindFramebuffer(this._ppGlobalIllumination[0].inputTexture,!0),this._engine.setAlphaMode(0),t=!0,this.enableBlur&&this._blurPostProcesses&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,this._blurRTT.renderTarget,!0),this._engine.unBindFramebuffer(this._blurRTT.renderTarget,!0)));for(let e=0;e{if(e.pluginManager){const t=e.pluginManager.getPlugin(yI.Name);t.textureGIContrib=this.enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height}}))}_createPostProcesses(){if(!this._enable)return;const e=13===this._giTextureType?4:5;this._firstActivation&&(this._firstActivation=!1,this._geomBufferEnabled=!!this._scene.geometryBufferRenderer,this._geomBufferEnablePosition=this._scene.geometryBufferRenderer?.enablePosition??!1),this._geomBufferEnabled||this._scene.disableGeometryBufferRenderer();const t=this._scene.enableGeometryBufferRenderer(this._enableBlur?this._outputDimensions:this._giTextureDimensions,this._use32BitsDepthBuffer?14:15,bI.GeometryBufferTextureTypesAndFormats);if(!t)throw new Error("Geometry buffer renderer is not supported but is required for GIRSMManager.");t.enablePosition=!0,this._geomBufferEnabled||(t.generateNormalsInWorldSpace=!0);const i=t.normalsAreUnsigned,s=t.generateNormalsInWorldSpace;this._counters.push({name:"Geometry buffer renderer",value:0}),this._countersRTW.push([this._scene.geometryBufferRenderer.getGBuffer().renderTarget]);let r="";i&&(r+="#define DECODE_NORMAL\n"),s||(r+="#define TRANSFORM_NORMAL\n");for(let i=0;i{e.setTexture("textureSampler",t.getGBuffer().textures[t.getTextureIndex(mP.POSITION_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(mP.NORMAL_TEXTURE_TYPE)]),e.setTexture("rsmPositionW",o.positionWorldTexture),e.setTexture("rsmNormalW",o.normalWorldTexture),e.setTexture("rsmFlux",o.fluxTexture),e.setMatrix("rsmLightMatrix",o.lightTransformationMatrix),n.useFullTexture?e.setFloat4("rsmInfo",o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height,n.intensity,n.edgeArtifactCorrection):(e.setTexture("rsmSamples",this._sampleTexture),e.setFloat4("rsmInfo",n.numSamples,n.radius,n.intensity,n.edgeArtifactCorrection),e.setFloat4("rsmInfo2",n.noiseFactor,n.rotateSample?1:0,o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height)),s||(this._tempMatrix.copyFrom(this._scene.activeCamera.getViewMatrix()),this._tempMatrix.invert(),e.setMatrix("invView",this._tempMatrix))}))}for(const e of this._ppGlobalIllumination)e.inputTexture||e.resize(this._giTextureDimensions.width,this._giTextureDimensions.height);if(this._counters.push({name:"GI generation",value:0}),this._countersRTW.push([this._ppGlobalIllumination[0].inputTexture]),this._enableBlur){const s=this._forceFullSizeBlur?this._outputDimensions:this._giTextureDimensions;this._blurRTT=new ih("GIRSMContribution",this._outputDimensions,this._scene,{type:this._giTextureType,format:e,generateDepthBuffer:!1}),this._blurRTT.wrapU=0,this._blurRTT.wrapV=0,this._blurRTT.updateSamplingMode(1),this._blurRTT.skipInitialClear=!0;const r=[];if(this._counters.push({name:"GI blur",value:0}),this._countersRTW.push(r),this._blurXPostprocess=new Vl(this._useQualityBlur?"BilateralBlur":"BilateralBlurX",this._useQualityBlur?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._blurXPostprocess.onApplyObservable.add((e=>{e._bindTexture("textureSampler",this._ppGlobalIllumination[0].inputTexture.texture),e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(mP.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(mP.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",1/this._giTextureDimensions.width,this._useQualityBlur?1/this._giTextureDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurXPostprocess.externalTextureSamplerBinding=!0,this._blurXPostprocess.autoClear=!1,this._useQualityBlur||(this._blurYPostprocess=new Vl("BilateralBlurY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._blurYPostprocess.autoClear=!1,this._blurYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(mP.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(mP.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",0,1/this._giTextureDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurYPostprocess.resize(s.width,s.height),r.push(this._blurYPostprocess.inputTexture)),this._blurPostProcesses=[this._blurXPostprocess],this._blurYPostprocess&&this._blurPostProcesses.push(this._blurYPostprocess),this._giTextureDimensions.width>=this._outputDimensions.width&&this._giTextureDimensions.height>=this._outputDimensions.height||this._forceFullSizeBlur)r.push(this._blurRTT.renderTarget);else{const n=[];this._counters.push({name:"GI upsampling",value:0}),this._countersRTW.push(n),this._upsamplingXPostprocess=new Vl(this._useQualityUpsampling?"BilateralUpsampling":"BilateralUpsamplingX",this._useQualityUpsampling?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._upsamplingXPostprocess.autoClear=!1,this._upsamplingXPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(mP.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(mP.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",1/this._outputDimensions.width,this._useQualityUpsampling?1/this._outputDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingXPostprocess.resize(s.width,s.height),r.push(this._upsamplingXPostprocess.inputTexture),this.useQualityUpsampling||(this._upsamplingYPostprocess=new Vl("BilateralUpsamplingY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:this._outputDimensions,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._upsamplingYPostprocess.autoClear=!1,this._upsamplingYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(mP.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(mP.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",0,1/this._outputDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingYPostprocess.resize(this._outputDimensions.width,this._outputDimensions.height),n.push(this._upsamplingYPostprocess.inputTexture)),n.push(this._blurRTT.renderTarget),this._blurPostProcesses.push(this._upsamplingXPostprocess),this._upsamplingYPostprocess&&this._blurPostProcesses.push(this._upsamplingYPostprocess)}}this._debugLayer.texture?.dispose(),this._debugLayer.texture=new ya(this._scene,this._enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture)}_addGISupportToMaterial(e){if(e.pluginManager?.getPlugin(yI.Name))return;const t=new yI(e);this._enable&&this._ppGlobalIllumination.length>0&&(t.textureGIContrib=this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height),t.isEnabled=this._enable,this._materialsWithRenderPlugin.push(e)}}bI.GeometryBufferTextureTypesAndFormats={0:{textureType:2,textureFormat:6},1:{textureType:11,textureFormat:5},2:{textureType:2,textureFormat:5}};class TI extends xl{constructor(){super(...arguments),this.RENDER_WITH_GIRSM=!1,this.RSMCREATE_PROJTEXTURE=!1}}class yI extends nu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,yI.Name,310,new TI),this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._isPBR=e instanceof Gg}prepareDefines(e){e.RENDER_WITH_GIRSM=this._isEnabled}getClassName(){return"GIRSMRenderPluginMaterial"}getUniforms(){return{ubo:[{name:"girsmTextureOutputSize",size:2,type:"vec2"}],fragment:"#ifdef RENDER_WITH_GIRSM\n uniform vec2 girsmTextureOutputSize;\n #endif"}}getSamplers(e){e.push("girsmTextureGIContrib")}bindForSubMesh(e){this._isEnabled&&(e.bindTexture("girsmTextureGIContrib",this.textureGIContrib),e.updateFloat2("girsmTextureOutputSize",this.outputTextureWidth,this.outputTextureHeight))}getCustomCode(e){const t={CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RENDER_WITH_GIRSM\n uniform sampler2D girsmTextureGIContrib;\n\n vec3 computeIndirect() {\n vec2 uv = gl_FragCoord.xy / girsmTextureOutputSize;\n return texture2D(girsmTextureGIContrib, uv).rgb;\n }\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:"\n #ifdef RENDER_WITH_GIRSM\n finalDiffuse += computeIndirect() * surfaceAlbedo.rgb;\n #endif\n "};return this._isPBR||(t.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR="\n #ifdef RENDER_WITH_GIRSM\n color.rgb += computeIndirect() * baseColor.rgb;\n #endif\n "),"vertex"===e?null:t}}yI.Name="GIRSMRender",Ze([rt()],yI.prototype,"textureGIContrib",void 0),Ze([rt()],yI.prototype,"outputTextureWidth",void 0),Ze([rt()],yI.prototype,"outputTextureHeight",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],yI.prototype,"isEnabled",void 0),z("BABYLON.GIRSMRenderPluginMaterial",yI);Bi.ShadersStore.spriteMapPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nprecision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4(\ntexture2D(frameMap,vec2(fX,0.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*1.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*2.),0.),\nvec4(0.)\n);}\nvoid main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV);\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\nvec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; fmt){frameID=animationData.x;break;}\nanimationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}}\nmat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;}\nvec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}}\ncolor.xyz*=colorMul;gl_FragColor=color;}";Bi.ShadersStore.spriteMapVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; \ngl_Position=worldViewProjection*p;}";class SI{get spriteCount(){return this.sprites.length}get position(){return this._output.position}set position(e){this._output.position=e}get rotation(){return this._output.rotation}set rotation(e){this._output.rotation=e}get animationMap(){return this._animationMap}set animationMap(e){const t=e._texture._bufferView,i=this._createTileAnimationBuffer(t);this._animationMap.dispose(),this._animationMap=i,this._material.setTexture("animationMap",this._animationMap)}constructor(e,t,i,s,r){this.name=e,this.sprites=[],this.atlasJSON=t,this.sprites=this.atlasJSON.frames,this.spriteSheet=i,this.options=s,s.stageSize=s.stageSize||new de(1,1),s.outputSize=s.outputSize||s.stageSize,s.outputPosition=s.outputPosition||_e.Zero(),s.outputRotation=s.outputRotation||_e.Zero(),s.layerCount=s.layerCount||1,s.maxAnimationFrames=s.maxAnimationFrames||0,s.baseTile=s.baseTile||0,s.flipU=s.flipU||!1,s.colorMultiply=s.colorMultiply||new _e(1,1,1),this._scene=r,this._frameMap=this._createFrameBuffer(),this._tileMaps=new Array;for(let e=0;e{this.spriteSheet&&this.spriteSheet.isReady()&&this.spriteSheet._texture?this._material.setVector2("spriteMapSize",new de(this.spriteSheet._texture.baseWidth||1,this.spriteSheet._texture.baseHeight||1)):l<100&&setTimeout((()=>{l++,h()}),100)};h(),this._material.setVector3("colorMul",s.colorMultiply),this._material.setTexture("frameMap",this._frameMap),this._material.setTextureArray("tileMaps",this._tileMaps),this._material.setTexture("animationMap",this._animationMap),this._material.setFloat("time",this._time),this._output=Wa(e+":output",{size:1,updatable:!0},r),this._output.scaling.x=s.outputSize.x,this._output.scaling.y=s.outputSize.y,this.position=s.outputPosition,this.rotation=s.outputRotation,this._scene.onBeforeRenderObservable.add((()=>{this._time+=this._scene.getEngine().getDeltaTime(),this._material.setFloat("time",this._time)})),this._output.material=this._material}getTileID(){const e=this.getMousePosition();return e.multiplyInPlace(this.options.stageSize||de.Zero()),e.x=Math.floor(e.x),e.y=Math.floor(e.y),e}getMousePosition(){const e=this._output,t=this._scene.pick(this._scene.pointerX,this._scene.pointerY,(t=>t===e));if(!t||!t.hit||!t.getTextureCoordinates)return new de(-1,-1);return t.getTextureCoordinates()||new de(-1,-1)}_createFrameBuffer(){const e=[];for(let t=0;t0&&(e+="\n\r"),e+=this._tileMaps[t]._texture._bufferView.toString();const t=document.createElement("a");t.href="data:octet/stream;charset=utf-8,"+encodeURI(e),t.target="_blank",t.download=this.name+".tilemaps",t.click(),t.remove()}loadTileMaps(e){const t=new XMLHttpRequest;t.open("GET",e);const i=this.options.layerCount||0;t.onload=()=>{const e=t.response.split("\n\r");for(let t=0;t{e.dispose()})),this._frameMap.dispose()}}class CI extends bx{constructor(e,t,i,s,r=null,n=.01,o=Pa.TRILINEAR_SAMPLINGMODE){super(e,t,i,64,s,n,o,!0,r),this.name=e}}var EI;!function(e){e[e.INIT=0]="INIT",e[e.RUNNING=1]="RUNNING",e[e.DONE=2]="DONE",e[e.ERROR=3]="ERROR"}(EI||(EI={}));class AI{constructor(e){this.name=e,this._isCompleted=!1,this._taskState=EI.INIT}get isCompleted(){return this._isCompleted}get taskState(){return this._taskState}get errorObject(){return this._errorObject}_setErrorObject(e,t){this._errorObject||(this._errorObject={message:e,exception:t})}run(e,t,i){this._taskState=EI.RUNNING,this.runTask(e,(()=>{this._onDoneCallback(t,i)}),((e,t)=>{this._onErrorCallback(i,e,t)}))}runTask(e,t,i){throw new Error("runTask is not implemented")}reset(){this._taskState=EI.INIT}_onErrorCallback(e,t,i){this._taskState=EI.ERROR,this._errorObject={message:t,exception:i},this.onError&&this.onError(this,t,i),e()}_onDoneCallback(e,t){try{this._taskState=EI.DONE,this._isCompleted=!0,this.onSuccess&&this.onSuccess(this),e()}catch(e){this._onErrorCallback(t,"Task is done, error executing success callback(s)",e)}}}class PI{constructor(e,t,i){this.remainingCount=e,this.totalCount=t,this.task=i}}class II extends AI{constructor(e,t,i,s,r){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=s,this.extension=r}runTask(e,t,i){fl.LoadAssetContainer(this.rootUrl,this.sceneFilename,e,(e=>{this.loadedContainer=e,this.loadedMeshes=e.meshes,this.loadedTransformNodes=e.transformNodes,this.loadedParticleSystems=e.particleSystems,this.loadedSkeletons=e.skeletons,this.loadedAnimationGroups=e.animationGroups,t()}),null,((e,t,s)=>{i(t,s)}),this.extension)}}class RI extends AI{constructor(e,t,i,s,r){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=s,this.extension=r}runTask(e,t,i){fl.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,e,((e,i,s,r,n)=>{this.loadedMeshes=e,this.loadedTransformNodes=n,this.loadedParticleSystems=i,this.loadedSkeletons=s,this.loadedAnimationGroups=r,t()}),null,((e,t,s)=>{i(t,s)}),this.extension)}}class MI extends AI{constructor(e,t,i,s,r){super(e),this.name=e,this.rootUrl=t,this.filename=i,this.targetConverter=s,this.extension=r}runTask(e,t,i){const s=e.animatables.length,r=e.animationGroups.length;this.loadedAnimatables=[],this.loadedAnimationGroups=[],fl.ImportAnimations(this.rootUrl,this.filename,e,!1,ol.NoSync,this.targetConverter,(()=>{this.loadedAnimatables=e.animatables.slice(s),this.loadedAnimationGroups=e.animationGroups.slice(r),t()}),null,((e,t,s)=>{i(t,s)}),this.extension)}}class OI extends AI{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.text=e,t()}),void 0,!1,!1,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class DI extends AI{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.data=e,t()}),void 0,!0,!0,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class wI extends AI{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){const s=new Image;Ds.SetCorsBehavior(this.url,s),s.onload=()=>{this.image=s,t()},s.onerror=e=>{i("Error loading image",e)},s.src=this.url}}class NI extends AI{constructor(e,t,i,s=!0,r=Pa.TRILINEAR_SAMPLINGMODE){super(e),this.name=e,this.url=t,this.noMipmap=i,this.invertY=s,this.samplingMode=r}runTask(e,t,i){this.texture=new Pa(this.url,e,this.noMipmap,this.invertY,this.samplingMode,(()=>{t()}),((e,t)=>{i(e,t)}))}}class FI extends AI{constructor(e,t,i,s,r,n){super(e),this.name=e,this.url=t,this.extensions=i,this.noMipmap=s,this.files=r,this.prefiltered=n}runTask(e,t,i){this.texture=new vg(this.url,e,this.extensions,this.noMipmap,this.files,(()=>{t()}),((e,t)=>{i(e,t)}),void 0,this.prefiltered)}}class LI extends AI{constructor(e,t,i,s=!1,r=!0,n=!1,o=!1){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=s,this.generateHarmonics=r,this.gammaSpace=n,this.reserved=o}runTask(e,t,i){this.texture=new nx(this.url,e,this.size,this.noMipmap,this.generateHarmonics,this.gammaSpace,this.reserved,(()=>{t()}),((e,t)=>{i(e,t)}))}}class BI extends AI{constructor(e,t,i,s=!1,r=!0){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=s,this.gammaSpace=r}runTask(e,t,i){this.texture=new Vx(this.url,e,this.size,this.noMipmap,this.gammaSpace,(()=>{t()}),((e,t)=>{i(e,t)}))}}class kI{constructor(e){this._isLoading=!1,this._tasks=new Array,this._waitingTasksCount=0,this._totalTasksCount=0,this.onTaskSuccessObservable=new K,this.onTaskErrorObservable=new K,this.onTasksDoneObservable=new K,this.onProgressObservable=new K,this.useDefaultLoadingScreen=!0,this.autoHideLoadingUI=!0,this._scene=e||re.LastCreatedScene}addContainerTask(e,t,i,s,r){const n=new II(e,t,i,s,r);return this._tasks.push(n),n}addMeshTask(e,t,i,s,r){const n=new RI(e,t,i,s,r);return this._tasks.push(n),n}addTextFileTask(e,t){const i=new OI(e,t);return this._tasks.push(i),i}addBinaryFileTask(e,t){const i=new DI(e,t);return this._tasks.push(i),i}addImageTask(e,t){const i=new wI(e,t);return this._tasks.push(i),i}addTextureTask(e,t,i,s,r=Pa.TRILINEAR_SAMPLINGMODE){const n=new NI(e,t,i,s,r);return this._tasks.push(n),n}addCubeTextureTask(e,t,i,s,r,n){const o=new FI(e,t,i,s,r,n);return this._tasks.push(o),o}addHDRCubeTextureTask(e,t,i,s=!1,r=!0,n=!1,o=!1){const a=new LI(e,t,i,s,r,n,o);return this._tasks.push(a),a}addEquiRectangularCubeTextureAssetTask(e,t,i,s=!1,r=!0){const n=new BI(e,t,i,s,r);return this._tasks.push(n),n}removeTask(e){const t=this._tasks.indexOf(e);t>-1&&this._tasks.splice(t,1)}_decreaseWaitingTasksCount(e){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,e),this.onProgressObservable.notifyObservers(new PI(this._waitingTasksCount,this._totalTasksCount,e))}catch(e){Ne.Error("Error running progress callbacks."),Ne.Log(e)}if(0===this._waitingTasksCount){try{const e=this._tasks.slice();this.onFinish&&this.onFinish(e);for(const t of e)if(t.taskState===EI.DONE){const e=this._tasks.indexOf(t);e>-1&&this._tasks.splice(e,1)}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(e){Ne.Error("Error running tasks-done callbacks."),Ne.Log(e)}this._isLoading=!1,this.autoHideLoadingUI&&this._scene.getEngine().hideLoadingUI()}}_runTask(e){const t=(t,i)=>{e._setErrorObject(t,i),this.onTaskError?this.onTaskError(e):e.onError||Ne.Error(this._formatTaskErrorMessage(e)),this.onTaskErrorObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)};e.run(this._scene,(()=>{try{this.onTaskSuccess&&this.onTaskSuccess(e),this.onTaskSuccessObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)}catch(e){t("Error executing task success callbacks",e)}}),t)}_formatTaskErrorMessage(e){let t="Unable to complete task "+e.name;return e.errorObject.message&&(t+=`: ${e.errorObject.message}`),e.errorObject.exception&&(t+=`: ${e.errorObject.exception}`),t}reset(){return this._isLoading=!1,this._tasks=new Array,this}load(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,0===this._waitingTasksCount)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(let e=0;e{this._isLoading?e():(this.onTasksDoneObservable.addOnce((i=>{i&&i.length?t(i):e()})),this.load())}))}}class VI{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}}class UI{constructor(e,t){this._meshesOrigins=[],this._toCenterVectors=[],this._scaledDirection=new _e(1,1,1),this._newPosition=_e.Zero(),this._centerPosition=_e.Zero(),this._meshes=e.slice(),t?this._centerMesh=t:this._setCenterMesh(),this._centerMesh.computeWorldMatrix(!0);const i=this._meshes.indexOf(this._centerMesh);i>=0&&this._meshes.splice(i,1),this._centerPosition=this._centerMesh.getAbsolutePosition().clone();for(let e=0;e!0,this.displayLoadingUI=!0,this.loadAsync=(e,t)=>this.useAppend?fl.AppendAsync("file:",e,this._currentScene,t):fl.LoadAsync("file:",e,this._engine,t),this._engine=e,this._currentScene=t,this._sceneLoadedCallback=i,this._progressCallback=s,this._additionalRenderLoopLogicCallback=r,this._textureLoadingCallback=n,this._startingProcessingFilesCallback=o,this._onReloadCallback=a,this._errorCallback=l}monitorElementForDragNDrop(e){e&&(this._elementToMonitor=e,this._dragEnterHandler=e=>{this._drag(e)},this._dragOverHandler=e=>{this._drag(e)},this._dropHandler=e=>{this._drop(e)},this._elementToMonitor.addEventListener("dragenter",this._dragEnterHandler,!1),this._elementToMonitor.addEventListener("dragover",this._dragOverHandler,!1),this._elementToMonitor.addEventListener("drop",this._dropHandler,!1))}get filesToLoad(){return this._filesToLoad}dispose(){this._elementToMonitor&&(this._elementToMonitor.removeEventListener("dragenter",this._dragEnterHandler),this._elementToMonitor.removeEventListener("dragover",this._dragOverHandler),this._elementToMonitor.removeEventListener("drop",this._dropHandler))}_renderFunction(){if(this._additionalRenderLoopLogicCallback&&this._additionalRenderLoopLogicCallback(),this._currentScene){if(this._textureLoadingCallback){const e=this._currentScene.getWaitingItemsCount();e>0&&this._textureLoadingCallback(e)}this._currentScene.render()}}_drag(e){e.stopPropagation(),e.preventDefault()}_drop(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)}_traverseFolder(e,t,i,s){const r=e.createReader(),n=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");r.readEntries((e=>{i.count+=e.length;for(const r of e)r.isFile?r.file((e=>{e.correctName=n+e.name,t.push(e),0==--i.count&&s()})):r.isDirectory&&this._traverseFolder(r,t,i,s);0==--i.count&&s()}))}_processFiles(e){for(let t=0;tthis._sceneFileToLoad=e))&&(fl.IsPluginForExtensionAvailable("."+s)&&(this._sceneFileToLoad=e[t]),GI.FilesToLoad[i]=e[t])}}loadFiles(e){if(e&&e.dataTransfer&&e.dataTransfer.files&&(this._filesToLoad=e.dataTransfer.files),e&&e.target&&e.target.files&&(this._filesToLoad=e.target.files),this._filesToLoad&&0!==this._filesToLoad.length&&(this._startingProcessingFilesCallback&&this._startingProcessingFilesCallback(this._filesToLoad),this._filesToLoad&&this._filesToLoad.length>0)){const t=[],i=[],s=e.dataTransfer?e.dataTransfer.items:null;for(let e=0;e{this._processFiles(t),0===e.count&&this._processReload()}))}}}_processReload(){this._onReloadCallback?this._onReloadCallback(this._sceneFileToLoad):this.reload()}reload(){this._sceneFileToLoad?(this.useAppend||this._currentScene&&(Ne.errorsCount>0&&Ne.ClearLogCache(),this._engine.stopRenderLoop()),fl.ShowLoadingScreen=!1,this.displayLoadingUI&&this._engine.displayLoadingUI(),this.loadAsync(this._sceneFileToLoad,this._progressCallback).then((e=>{this.useAppend?this.displayLoadingUI&&this._engine.hideLoadingUI():(this._currentScene&&this._currentScene.dispose(),this._currentScene=e,this._currentScene.executeWhenReady((()=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._engine.runRenderLoop((()=>{this._renderFunction()}))}))),this._sceneLoadedCallback&&this._currentScene&&this._sceneLoadedCallback(this._sceneFileToLoad,this._currentScene)})).catch((e=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._errorCallback&&this._errorCallback(this._sceneFileToLoad,this._currentScene,e.message)}))):Ne.Error("Please provide a valid .babylon file.")}}class zI{dispose(){if(this._observers&&this._observables)for(let e=0;e{o.skipNextObservers||i._willBeUnregistered||i.mask&t&&(n=i.scope?n.then((t=>(o.lastReturnValue=t,i.callback.apply(i.scope,[e,o])))):n.then((t=>(o.lastReturnValue=t,i.callback(e,o)))),i.unregisterOnNextCall&&this._deferUnregister(i))})),await n,e};class WI{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class HI extends WI{getDescription(){return"Reducing render target texture size to "+this.maximumSize}constructor(e=0,t=1024,i=.5){super(e),this.priority=e,this.maximumSize=t,this.step=i}apply(e,t){let i=!0;for(let t=0;tthis.maximumSize&&(s.scale(this.step),i=!1)}return i}}class XI extends WI{getDescription(){return"Setting hardware scaling level to "+this._currentScale}constructor(e=0,t=2,i=.25){super(e),this.priority=e,this.maximumScale=t,this.step=i,this._currentScale=-1,this._directionOffset=1}apply(e,t){return-1===this._currentScale&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,e.getEngine().setHardwareScalingLevel(this._currentScale),1===this._directionOffset?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale}}class YI extends WI{getDescription(){return"Turning shadows on/off"}apply(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0}}class QI extends WI{getDescription(){return"Turning post-processes on/off"}apply(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0}}class jI extends WI{getDescription(){return"Turning lens flares on/off"}apply(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0}}class KI extends WI{getDescription(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"}apply(e,t){return!this.onApply||this.onApply(e,t)}}class $I extends WI{getDescription(){return"Turning particles on/off"}apply(e,t){return e.particlesEnabled=t.isInImprovementMode,!0}}class qI extends WI{getDescription(){return"Turning render targets off"}apply(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0}}class ZI extends WI{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof ha))return!1;const t=e;return!(t.isDisposed()||!t.isVisible||!t.isEnabled()||t.instances.length>0||t.skeleton||t.hasLODLevels||0===t.getTotalVertices())}}static get UpdateSelectionTree(){return ZI._UpdateSelectionTree}static set UpdateSelectionTree(e){ZI._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const s=e.meshes.slice(0);let r=s.length;for(let e=0;e{this._sceneDisposeObserver=null,this.dispose()}))}stop(){this._isRunning=!1}reset(){this._currentPriorityLevel=0}start(){this._isRunning||(this._isRunning=!0,this._scene.executeWhenReady((()=>{setTimeout((()=>{this._checkCurrentState()}),this._trackerDuration)})))}_checkCurrentState(){if(!this._isRunning)return;const e=this._scene,t=this._options;if(this._currentFrameRate=Math.round(e.getEngine().getFps()),this._improvementMode&&this._currentFrameRate<=this._targetFrameRate||!this._improvementMode&&this._currentFrameRate>=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);let i=!0,s=!0;for(let r=0;r{setTimeout((()=>{this._checkCurrentState()}),this._trackerDuration)}))}dispose(){this.stop(),this.onSuccessObservable.clear(),this.onFailureObservable.clear(),this.onNewOptimizationAppliedObservable.clear(),this._sceneDisposeObserver&&this._scene.onDisposeObservable.remove(this._sceneDisposeObserver)}static OptimizeAsync(e,t,i,s){const r=new eR(e,t||JI.ModerateDegradationAllowed(),!1);return i&&r.onSuccessObservable.add((()=>{i()})),s&&r.onFailureObservable.add((()=>{s()})),r.start(),r}}let tR=[];const iR=(e,t)=>{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),tR[e.id]=!0)},sR=(e,t)=>{const i={},s=e._geometry;return s&&(e.getScene().getGeometryById(s.id)||iR(s,t.geometries)),e.serialize&&e.serialize(i),i};class rR{static ClearCache(){tR=[]}static Serialize(e){return rR._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&Pa.ForceSerializeBuffers&&Ne.Warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),rR.ClearCache(),i.useDelayedTextureLoading=e.useDelayedTextureLoading,i.autoClear=e.autoClear,i.clearColor=e.clearColor.asArray(),i.ambientColor=e.ambientColor.asArray(),i.gravity=e.gravity.asArray(),i.collisionsEnabled=e.collisionsEnabled,i.useRightHandedSystem=e.useRightHandedSystem,void 0!==e.fogMode&&null!==e.fogMode&&(i.fogMode=e.fogMode),void 0!==e.fogColor&&null!==e.fogColor&&(i.fogColor=e.fogColor.asArray()),void 0!==e.fogStart&&null!==e.fogStart&&(i.fogStart=e.fogStart),void 0!==e.fogEnd&&null!==e.fogEnd&&(i.fogEnd=e.fogEnd),void 0!==e.fogDensity&&null!==e.fogDensity&&(i.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){const t=e.getPhysicsEngine();t&&(i.physicsEnabled=!0,i.physicsGravity=t.gravity.asArray(),i.physicsEngine=t.getPhysicsPluginName())}e.metadata&&(i.metadata=e.metadata),i.morphTargetManagers=[];for(const t of e.meshes){const e=t.morphTargetManager;e&&i.morphTargetManagers.push(e.serialize())}let s,r,n;for(i.lights=[],s=0;s0){i.animationGroups=[];for(let t=0;t0)for(i.reflectionProbes=[],s=0;st))}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=t))):(s instanceof Object||Array.isArray(s))&&this._CollectPromises(s,t)}else if(e instanceof Object)for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const s=e[i];s instanceof Promise?t.push(s.then((t=>e[i]=t))):(s instanceof Object||Array.isArray(s))&&this._CollectPromises(s,t)}}static SerializeMesh(e,t=!1,i=!1){const s={meshes:[],transformNodes:[],cameras:[],lights:[]};if(rR.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let s=0;s{e.indexOf(t)<0&&!t.doNotSerialize&&e.push(t)})),t&&e[s].parent&&e.indexOf(e[s].parent)<0&&!e[s].parent.doNotSerialize&&e.push(e[s].parent);return e.forEach((e=>{((e,t)=>{if(e._isMesh){const i=e;if(1===i.delayLoadState||0===i.delayLoadState){const e=e=>{t.materials=t.materials||[],i.material&&!t.materials.some((e=>e.id===i.material.id))&&t.materials.push(e.serialize())};if(i.material&&!i.material.doNotSerialize)if(i.material instanceof ia){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some((e=>e.id===i.material.id))){t.multiMaterials.push(i.material.serialize());for(const t of i.material.subMaterials)t&&e(t)}}else e(i.material);else i.material||e(i.getScene().defaultMaterial);const s=i._geometry;s&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),iR(s,t.geometries)),i.skeleton&&!i.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(i.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(sR(i,t))}}else if("TransformNode"===e.getClassName()){const i=e;t.transformNodes.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Camera")){const i=e;t.cameras.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Light")){const i=e;t.lights.push(i.serialize())}})(e,s)})),s}}class nR{static IsSupported(e,t){const i=t??e.getRenderingCanvas();return!!i&&"function"==typeof i.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!nR.IsSupported(e,t.canvas))throw"Your browser does not support recording so far.";const i=t.canvas??e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options={...nR._DefaultOptions,...t};const s=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const e of this._options.audioTracks)s.addTrack(e);this._mediaRecorder=new MediaRecorder(s,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=e=>this._handleDataAvailable(e),this._mediaRecorder.onerror=e=>this._handleError(e),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout((()=>{this.stopRecording()}),1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),!this._reject)throw new e.error;this._reject(e.error)}_handleStop(){this.stopRecording();const e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&Ds.Download(e,this._fileName)}}nR._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let oR=null;function aR(e,t,i,s,r="image/png",n=!1,o){const{height:a,width:l}=dR(e,t,i);if(!a||!l)return void Ne.Error("Invalid 'size' parameter !");oR||(oR=document.createElement("canvas")),oR.width=l,oR.height=a;const h=oR.getContext("2d"),c=e.getRenderWidth()/e.getRenderHeight();let u=l,d=u/c;d>a&&(d=a,u=d*c);const _=Math.max(0,l-u)/2,p=Math.max(0,a-d)/2;t.getScene().activeCamera!==t?cR(e,t,i,(e=>{if(n){const t=new Blob([e]);Ds.DownloadBlob(t),s&&s("")}else s&&s(e)}),r,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,o):e.onEndFrameObservable.addOnce((()=>{const t=e.getRenderingCanvas();h&&t&&h.drawImage(t,_,p,u,d),oR&&(n?(Ds.EncodeScreenshotCanvasData(oR,void 0,r,void 0,o),s&&s("")):Ds.EncodeScreenshotCanvasData(oR,s,r,void 0,o))}))}function lR(e,t,i,s="image/png",r){return new Promise(((n,o)=>{aR(e,t,i,(e=>{void 0!==e?n(e):o(new Error("Data is undefined"))}),s,void 0,r)}))}function hR(e,t,i,s,r="image/png",n){return new Promise((o=>{aR(e,t,{width:i,height:s},(()=>{o()}),r,!0,n)}))}function cR(e,t,i,s,r="image/png",n=1,o=!1,a,l=!1,h=!1,c=!0,u,d){const{height:_,width:p,finalWidth:f,finalHeight:m}=dR(e,t,i),g={width:p,height:_};if(!_||!p)return void Ne.Error("Invalid 'size' parameter !");const v={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(p,_);const x=t.getScene(),b=new ih("screenShot",g,x,!1,!1,0,!1,Pa.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,n);b.renderList=x.meshes.slice(),b.samples=n,b.renderSprites=l,b.activeCamera=t,b.forceLayerMaskCheck=c,d?.(b);const T=()=>{b.isReadyForRendering()&&t.isReady(!0)?(e.onEndFrameObservable.addOnce((()=>{f===p&&m===_?b.readPixels(void 0,void 0,void 0,!1).then((e=>{th.DumpData(p,_,e,s,r,a,!0,void 0,u),b.dispose()})):Z_("pass",b.getInternalTexture(),x,void 0,void 0,void 0,f,m).then((t=>{e._readTexturePixels(t,f,m,-1,0,null,!0,!1,0,0).then((e=>{th.DumpData(f,m,e,s,r,a,!0,void 0,u),t.dispose()}))}))})),b.render(!0),x.incrementRenderId(),x.resetCachedMaterial(),e.setSize(v.width,v.height),t.getProjectionMatrix(!0),x.render()):setTimeout(T,16)},y=()=>{x.incrementRenderId(),x.resetCachedMaterial(),T()};if(o){const e=new uP("antialiasing",1,x.activeCamera);b.addPostProcess(e),e.getEffect().isReady()?y():e.getEffect().onCompiled=()=>{y()}}else y()}function uR(e,t,i,s="image/png",r=1,n=!1,o,a=!1,l=!1,h=!0,c){return new Promise(((u,d)=>{cR(e,t,i,(e=>{void 0!==e?u(e):d(new Error("Data is undefined"))}),s,r,n,o,a,l,h,c)}))}function dR(e,t,i){let s=0,r=0,n=0,o=0;if("object"==typeof i){const a=i.precision?Math.abs(i.precision):1;i.width&&i.height?(s=i.height*a,r=i.width*a):i.width&&!i.height?(r=i.width*a,s=Math.round(r/e.getAspectRatio(t))):i.height&&!i.width?(s=i.height*a,r=Math.round(s*e.getAspectRatio(t))):(r=Math.round(e.getRenderWidth()*a),s=Math.round(r/e.getAspectRatio(t))),i.finalWidth&&i.finalHeight?(o=i.finalHeight,n=i.finalWidth):i.finalWidth&&!i.finalHeight?(n=i.finalWidth,o=Math.round(n/e.getAspectRatio(t))):i.finalHeight&&!i.finalWidth?(o=i.finalHeight,n=Math.round(o*e.getAspectRatio(t))):(n=r,o=s)}else isNaN(i)||(s=i,r=i,n=i,o=i);return r&&(r=Math.floor(r)),s&&(s=Math.floor(s)),n&&(n=Math.floor(n)),o&&(o=Math.floor(o)),{height:0|s,width:0|r,finalWidth:0|n,finalHeight:0|o}}const _R={CreateScreenshot:aR,CreateScreenshotAsync:lR,CreateScreenshotWithResizeAsync:hR,CreateScreenshotUsingRenderTarget:cR,CreateScreenshotUsingRenderTargetAsync:uR};var pR,fR;Ds.CreateScreenshot=aR,Ds.CreateScreenshotAsync=lR,Ds.CreateScreenshotUsingRenderTarget=cR,Ds.CreateScreenshotUsingRenderTargetAsync=uR,function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String",e[e.Button=6]="Button",e[e.Options=7]="Options",e[e.Tab=8]="Tab",e[e.FileButton=9]="FileButton",e[e.Vector2=10]="Vector2"}(pR||(pR={}));class mR{constructor(e){this.byteOffset=0,this.buffer=e}loadAsync(e){return this.buffer.readAsync(this.byteOffset,e).then((e=>{this._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),this._dataByteOffset=0}))}readUint32(){const e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e}readUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t}readString(e){return qt(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}class gR{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{const e={};return{getItem:t=>{const i=e[t];return void 0===i?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){const i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){const i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){const i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}gR._Storage=gR._GetStorage();class vR{constructor(){this._trackedScene=null}track(e){this._trackedScene=e,St.AllowLoadingUniqueId=!0,this._savedJSON=rR.Serialize(e),St.AllowLoadingUniqueId=!1}getDelta(){if(!this._trackedScene)return null;const e=Pa.ForceSerializeBuffers;Pa.ForceSerializeBuffers=!1,St.AllowLoadingUniqueId=!0;const t=rR.Serialize(this._trackedScene);St.AllowLoadingUniqueId=!1;const i={};for(const e in t)this._compareCollections(e,this._savedJSON[e],t[e],i);return Pa.ForceSerializeBuffers=e,i}_compareArray(e,t,i,s){if(0===t.length&&0===i.length)return!0;if(t.length&&!isNaN(t[0])||i.length&&!isNaN(i[0])){if(t.length!==i.length)return!1;if(0===t.length)return!0;for(let r=0;re.uniqueId===a));if(l.length){const t=l[0],i={};this._compareObjects(o,t,i)||(s[e]||(s[e]=[]),i.__state={id:t.id||t.name},s[e].push(i))}else{const t={__state:{deleteId:o.id||o.name}};s[e]||(s[e]=[]),s[e].push(t)}}for(let t=0;te.getShadowGenerators()));for(const e of i)if(e){const i=e.values();for(let e=i.next();!0!==e.done;e=i.next()){const i=e.value;if(i&&i.id===t)return i}}return null}static ApplyDelta(e,t){"string"==typeof e&&(e=JSON.parse(e));const i=t;for(const s in e){const r=e[s],n=i[s];if(Array.isArray(n)||"shadowGenerators"===s)switch(s){case"cameras":this._ApplyDeltaForEntity(r,t,t.getCameraById.bind(t),(e=>In.Parse(e,t)));break;case"lights":this._ApplyDeltaForEntity(r,t,t.getLightById.bind(t),(e=>ua.Parse(e,t)));break;case"shadowGenerators":this._ApplyDeltaForEntity(r,t,(e=>this.GetShadowGeneratorById(t,e)),(e=>Wv.Parse(e,t)));break;case"meshes":this._ApplyDeltaForEntity(r,t,t.getMeshById.bind(t),(e=>ha.Parse(e,t,"")));break;case"skeletons":this._ApplyDeltaForEntity(r,t,t.getSkeletonById.bind(t),(e=>Da.Parse(e,t)));break;case"materials":this._ApplyDeltaForEntity(r,t,t.getMaterialById.bind(t),(e=>ta.Parse(e,t,"")));break;case"multiMaterials":this._ApplyDeltaForEntity(r,t,t.getMaterialById.bind(t),(e=>ia.Parse(e,t,"")));break;case"transformNodes":this._ApplyDeltaForEntity(r,t,t.getTransformNodeById.bind(t),(e=>lo.Parse(e,t,"")));break;case"particleSystems":this._ApplyDeltaForEntity(r,t,t.getParticleSystemById.bind(t),(e=>VE.Parse(e,t,"")));break;case"morphTargetManagers":this._ApplyDeltaForEntity(r,t,t.getMorphTargetById.bind(t),(e=>lx.Parse(e,t)));break;case"postProcesses":this._ApplyDeltaForEntity(r,t,t.getPostProcessByName.bind(t),(e=>Vl.Parse(e,t,"")))}else isNaN(n)?n.fromArray&&n.fromArray(r):i[s]=r}}static _ApplyPropertiesToEntity(e,t){for(const i in e){const s=e[i],r=t[i];void 0!==r&&(!isNaN(r)||Array.isArray(r)?t[i]=s:r.fromArray?r.fromArray(s):"object"==typeof r&&null!==r&&this._ApplyPropertiesToEntity(s,r))}}static _ApplyDeltaForEntity(e,t,i,s){for(const r of e)if(r.__state&&void 0!==r.__state.id){const e=i(r.__state.id);e&&(this._ApplyPropertiesToEntity(r,e),St.ParseProperties(r,e,t,null))}else if(r.__state&&void 0!==r.__state.deleteId){const e=i(r.__state.deleteId);e?.dispose()}else s(r)}}!function(e){class t{serialize(){const e={},t=new Array(this._characterToIdx.size);return this._characterToIdx.forEach(((e,i)=>{t[e]=i})),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){const i=JSON.parse(e),s=new t(i.characters);return s._insertionCosts=i.insertionCosts,s._deletionCosts=i.deletionCosts,s._substitutionCosts=i.substitutionCosts,s}constructor(e,t=null,i=null,s=null){let r;t=t??(()=>1),i=i??(()=>1),s=s??((e,t)=>e===t?0:1),this._characterToIdx=new Map,this._insertionCosts=new Array(e.length),this._deletionCosts=new Array(e.length),this._substitutionCosts=new Array(e.length);for(let n=0;ni._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+i._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map((e=>this._alphabet.getCharacterIdx(e)))}distance(e){return i._Distance(this,e)}static _Distance(e,t){const s=e._alphabet;if(s!==t._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const r=e._characters,n=t._characters,o=r.length,a=n.length,l=i._CostMatrix;l[0][0]=0;for(let e=0;enew Array(i._MAX_SEQUENCE_LENGTH+1))),e.Sequence=i}(fR||(fR={}));class xR{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new xR(t._segmentLength);return i._points=t._points.map((e=>new _e(e._x,e._y,e._z))),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{const i=()=>this._segmentLength/_e.Distance(this._points[t-1],e);for(let s=i();s<=1;s=i()){const i=this._points[t-1].scale(1-s);e.scaleAndAddToRef(s,i),this._points.push(i),++t}}}resampleAtTargetResolution(e){const t=new xR(this.getLength()/e);return this._points.forEach((e=>{t.add(e)})),t}tokenize(e){const t=[],i=new _e;for(let s=2;s.98||(_e.CrossToRef(xR._ForwardDir,xR._InverseFromVec,xR._UpDir),xR._UpDir.normalize(),me.LookAtLHToRef(e,t,xR._UpDir,xR._LookMatrix),i.subtractToRef(t,xR._FromToVec),xR._FromToVec.normalize(),_e.TransformNormalToRef(xR._FromToVec,xR._LookMatrix,s),0))}static _TokenizeSegment(e,t){xR._BestMatch=0,xR._Score=_e.Dot(e,t[0]),xR._BestScore=xR._Score;for(let i=1;ixR._BestScore&&(xR._BestMatch=i,xR._BestScore=xR._Score);return xR._BestMatch}}xR._ForwardDir=new _e,xR._InverseFromVec=new _e,xR._UpDir=new _e,xR._FromToVec=new _e,xR._LookMatrix=new me;class bR{static Generate(e=64,t=256,i=.1,s=.001,r=[]){const n=new bR(e);for(let t=0;t{n.chars[e].subtractToRef(t,h),a=h.lengthSquared(),a>1e-6&&h.scaleAndAddToRef(1/(h.lengthSquared()*a),l)})),l.scaleInPlace(o),n.chars[e].addInPlace(l),n.chars[e].normalize()}var c;return n}serialize(){return JSON.stringify(this.chars)}static Deserialize(e){const t=JSON.parse(e),i=new bR(t.length);for(let e=0;ee.serialize())))}static Deserialize(e,t){const i=new TR;return i._sequences=JSON.parse(e).map((e=>fR.Sequence.Deserialize(e,t))),i}static CreateFromTrajectory(e,t,i){return TR.CreateFromTokenizationPyramid(TR._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new TR;return i._sequences=e.map((e=>new fR.Sequence(e,t))),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=TR._FINEST_DESCRIPTOR_RESOLUTION){const s=[];for(let r=i;r>4;r=Math.floor(r/2))s.push(e.resampleAtTargetResolution(r).tokenize(t.chars));return s}distance(e){let t,i=0;for(let s=0;se.serialize())),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),s=new yR;return s._descriptors=i.descriptors.map((e=>TR.Deserialize(e,t))),s._centroidIdx=i.centroidIdx,s._averageDistance=i.averageDistance,s}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map((t=>t.distance(e))))}_refreshDescription(){let e;this._centroidIdx=-1;const t=this._descriptors.map((t=>(e=0,this._descriptors.forEach((i=>{e+=t.distance(i)})),e)));for(let e=0;e{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])})),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,yR._MIN_AVERAGE_DISTANCE))}}yR._MIN_AVERAGE_DISTANCE=1;class SR{serialize(){const e={};return e.maximumAllowableMatchCost=this._maximumAllowableMatchCost,e.vector3Alphabet=this._vector3Alphabet.serialize(),e.levenshteinAlphabet=this._levenshteinAlphabet.serialize(),e.nameToDescribedTrajectory=[],this._nameToDescribedTrajectory.forEach(((t,i)=>{e.nameToDescribedTrajectory.push(i),e.nameToDescribedTrajectory.push(t.serialize())})),JSON.stringify(e)}static Deserialize(e){const t=JSON.parse(e),i=new SR;i._maximumAllowableMatchCost=t.maximumAllowableMatchCost,i._vector3Alphabet=bR.Deserialize(t.vector3Alphabet),i._levenshteinAlphabet=fR.Alphabet.Deserialize(t.levenshteinAlphabet);for(let e=0;e0===e?0:1),(e=>0===e?0:1),((t,i)=>Math.min(1-_e.Dot(e.chars[t],e.chars[i]),1))),s=new SR;return s._vector3Alphabet=e,s._levenshteinAlphabet=i,s}constructor(){this._maximumAllowableMatchCost=4,this._nameToDescribedTrajectory=new Map}addTrajectoryToClassification(e,t){this._nameToDescribedTrajectory.has(t)||this._nameToDescribedTrajectory.set(t,new yR),this._nameToDescribedTrajectory.get(t).add(TR.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet))}deleteClassification(e){return this._nameToDescribedTrajectory.delete(e)}classifyTrajectory(e){const t=TR.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet),i=[];if(this._nameToDescribedTrajectory.forEach(((e,s)=>{e.getMatchCost(t){const t=e.data;if(t.startsWith(CR._SERVER_PREFIX)){const e=t.substr(CR._SERVER_PREFIX.length);return Ne.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),void this._handleServerMessage(e)}Ne.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{Ne.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&rR.SerializeAsync(this._scene).then((e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)}))}_handleClientMessage(){}}CR._SERVER_PREFIX="$$";class ER{constructor(e){this._observer=null,this._currentState=[],this.onPressureChanged=new K,ER.IsAvailable&&(this._observer=new PressureObserver((e=>{this._currentState=e,this.onPressureChanged.notifyObservers(e)}),e))}static get IsAvailable(){return"undefined"!=typeof PressureObserver&&PressureObserver.knownSources&&PressureObserver.knownSources.includes("cpu")}observe(e){try{this._observer?.observe(e),this.onPressureChanged.notifyObservers(this._currentState)}catch{}}unobserve(e){try{this._observer?.unobserve(e)}catch{}}dispose(){this._observer?.disconnect(),this._observer=null,this.onPressureChanged.clear()}}class AR{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){const e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}}const PR=1800,IR="timestamp",RR="numPoints",MR=/\r/g;class OR{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const e=Wt.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength;let s=0;if(i>0){const e=this.datasets.startingIndices.at(i-1);s=e+this.datasets.data.at(e+OR.NumberOfPointsOffset)+OR.SliceDataOffset}if(this.datasets.startingIndices.push(s),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach((e=>{const t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())})),this.datasetObservable.hasObservers()){const i=[e,t];for(let e=0;ee.callback(this._datasetMeta,new Q(0)))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&(this._strategies.get(e)?.dispose(),this._strategies.delete(e));const s={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,s=0;const r=t.onAfterRenderObservable.add((()=>{s=i,i=0})),n=this._customEventObservable.add((t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)}));return{id:e,getData:()=>s,dispose:()=>{t.onAfterRenderObservable.remove(r),this._customEventObservable.remove(n)}}},category:i}),s}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach((e=>{this.registerEvent(e,!0)}))}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:s}of e){const e=t(this._scene);this._strategies.has(e.id)?e.dispose():(this.datasets.ids.push(e.id),i&&(i=i.replace(new RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:s}),this._strategies.set(e.id,e))}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i>e&255).toString(16)).substr(-2);return i}getCurrentSlice(){const e=[Wt.Now-this._startingTimestamp,this.datasets.ids.length];this.datasets.ids.forEach((t=>{const i=this._strategies.get(t);i&&this.datasetObservable.hasObservers()&&e.push(i.getData())})),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(e)}updateMetadata(e,t,i){const s=this._datasetMeta.get(e);s&&(s[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new AR(PR),this.datasets.ids.length=0,this.datasets.startingIndices=new AR(PR),this._datasetMeta.clear(),this._strategies.forEach((e=>e.dispose())),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){const i=e.replace(MR,"").split("\n").map((e=>e.split(",").filter((e=>e.length>0)))).filter((e=>e.length>0)),s=OR.NumberOfPointsOffset;if(i.length<2)return!1;const r={ids:[],data:new AR(PR),startingIndices:new AR(PR)},[n,...o]=i;if(n.length<2||n[0]!==IR||n[s]!==RR)return!1;const a=new Map;for(let e=OR.SliceDataOffset;ee.dispose())),this._strategies.clear(),!t)for(const e of this.datasets.ids){const t=a.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${IR},${RR}`;for(let t=0;t{e.dispose()})),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}const DR=()=>{};class wR{static FpsStrategy(){return e=>{const t=e.getEngine();return{id:"FPS",getData:()=>t.getFps(),dispose:DR}}}static ThermalStrategy(){return this._PressureStrategy("Thermal utilization","thermal")}static PowerSupplyStrategy(){return this._PressureStrategy("Power supply utilization","power-supply")}static PressureStrategy(){return this._PressureStrategy("Pressure")}static _PressureStrategy(e,t=null){return()=>{let i=0;const s=new ER;return s.observe("cpu"),s.onPressureChanged.add((e=>{for(const s of e)if(t&&s.factors.includes(t)||!t&&0===(s.factors?.length??0))switch(s.state){case"nominal":i=0;break;case"fair":i=.25;break;case"serious":i=.5;break;case"critical":i=1}})),{id:e,getData:()=>i,dispose:()=>s.dispose()}}}static TotalMeshesStrategy(){return e=>({id:"Total meshes",getData:()=>e.meshes.length,dispose:DR})}static ActiveMeshesStrategy(){return e=>({id:"Active meshes",getData:()=>e.getActiveMeshes().length,dispose:DR})}static ActiveIndicesStrategy(){return e=>({id:"Active indices",getData:()=>e.getActiveIndices(),dispose:DR})}static ActiveFacesStrategy(){return e=>({id:"Active faces",getData:()=>e.getActiveIndices()/3,dispose:DR})}static ActiveBonesStrategy(){return e=>({id:"Active bones",getData:()=>e.getActiveBones(),dispose:DR})}static ActiveParticlesStrategy(){return e=>({id:"Active particles",getData:()=>e.getActiveParticles(),dispose:DR})}static DrawCallsStrategy(){return e=>{let t=0;const i=e.onBeforeAnimationsObservable.add((()=>{e.getEngine()._drawCalls.fetchNewFrame()})),s=e.onAfterRenderObservable.add((()=>{t=e.getEngine()._drawCalls.current}));return{id:"Draw calls",getData:()=>t,dispose:()=>{e.onBeforeAnimationsObservable.remove(i),e.onAfterRenderObservable.remove(s)}}}}static TotalLightsStrategy(){return e=>({id:"Total lights",getData:()=>e.lights.length,dispose:DR})}static TotalVerticesStrategy(){return e=>({id:"Total vertices",getData:()=>e.getTotalVertices(),dispose:DR})}static TotalMaterialsStrategy(){return e=>({id:"Total materials",getData:()=>e.materials.length,dispose:DR})}static TotalTexturesStrategy(){return e=>({id:"Total textures",getData:()=>e.textures.length,dispose:DR})}static AbsoluteFpsStrategy(){return e=>{const t=new Dv(e);return t.captureFrameTime=!0,{id:"Absolute FPS",getData:()=>1e3/t.frameTimeCounter.lastSecAverage,dispose:DR}}}static MeshesSelectionStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeActiveMeshesEvaluationObservable.add((()=>{t=Wt.Now})),r=e.onAfterActiveMeshesEvaluationObservable.add((()=>{i=Wt.Now-t}));return{id:"Meshes Selection",getData:()=>i,dispose:()=>{e.onBeforeActiveMeshesEvaluationObservable.remove(s),e.onAfterActiveMeshesEvaluationObservable.remove(r)}}}}static RenderTargetsStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeRenderTargetsRenderObservable.add((()=>{t=Wt.Now})),r=e.onAfterRenderTargetsRenderObservable.add((()=>{i=Wt.Now-t}));return{id:"Render Targets",getData:()=>i,dispose:()=>{e.onBeforeRenderTargetsRenderObservable.remove(s),e.onAfterRenderTargetsRenderObservable.remove(r)}}}}static ParticlesStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeParticlesRenderingObservable.add((()=>{t=Wt.Now})),r=e.onAfterParticlesRenderingObservable.add((()=>{i=Wt.Now-t}));return{id:"Particles",getData:()=>i,dispose:()=>{e.onBeforeParticlesRenderingObservable.remove(s),e.onAfterParticlesRenderingObservable.remove(r)}}}}static SpritesStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeSpritesRenderingObservable?.add((()=>{t=Wt.Now})),r=e.onAfterSpritesRenderingObservable?.add((()=>{i=Wt.Now-t}));return{id:"Sprites",getData:()=>i,dispose:()=>{e.onBeforeSpritesRenderingObservable?.remove(s),e.onAfterSpritesRenderingObservable?.remove(r)}}}}static AnimationsStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeAnimationsObservable.add((()=>{t=Wt.Now})),r=e.onAfterAnimationsObservable.add((()=>{i=Wt.Now-t}));return{id:"Animations",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(s),e.onAfterAnimationsObservable.remove(r)}}}}static PhysicsStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforePhysicsObservable?.add((()=>{t=Wt.Now})),r=e.onAfterPhysicsObservable?.add((()=>{i=Wt.Now-t}));return{id:"Physics",getData:()=>i,dispose:()=>{e.onBeforePhysicsObservable?.remove(s),e.onAfterPhysicsObservable?.remove(r)}}}}static RenderStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeDrawPhaseObservable.add((()=>{t=Wt.Now})),r=e.onAfterDrawPhaseObservable.add((()=>{i=Wt.Now-t}));return{id:"Render",getData:()=>i,dispose:()=>{e.onBeforeDrawPhaseObservable.remove(s),e.onAfterDrawPhaseObservable.remove(r)}}}}static FrameTotalStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeAnimationsObservable.add((()=>{t=Wt.Now})),r=e.onAfterRenderObservable.add((()=>{i=Wt.Now-t}));return{id:"Frame Total",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(s),e.onAfterRenderObservable.remove(r)}}}}static InterFrameStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeAnimationsObservable.add((()=>{i=Wt.Now-t})),r=e.onAfterRenderObservable.add((()=>{t=Wt.Now}));return{id:"Inter-frame",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(s),e.onAfterRenderObservable.remove(r)}}}}static GpuFrameTimeStrategy(){return e=>{const t=new Ov(e.getEngine());return t.captureGPUFrameTime=!0,{id:"GPU frame time",getData:()=>Math.max(1e-6*t.gpuFrameTimeCounter.current,0),dispose:()=>{t.dispose()}}}}}Hr.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new OR(this)),this._perfCollector},K.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){const e=function(e){const t=new Array,i=new Array,s=new Array,r=e.add((()=>{const e=t.length;for(let r=0;r{t.push(e),i.push(r),s.push(n)},dispose:()=>{e.remove(r)}}}(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return Cn(e,this._coroutineScheduler)},K.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};async function NR(e,t){const i=t.probe??new fx("tempProbe",t.size,e),s=!!t.probe;s||(t.position?i.position=t.position.clone():e.activeCamera&&(i.position=e.activeCamera.position.clone()));const r=t.meshesFilter?e.meshes.filter(t.meshesFilter):e.meshes;i.renderList?.push(...r),i.refreshRate=ih.REFRESHRATE_RENDER_ONCE,i.cubeTexture.render();const n=new yb("tempProceduralTexture","equirectangularPanorama",{width:2*t.size,height:t.size},e);return n.setTexture("cubeMap",i.cubeTexture),new Promise(((e,r)=>{n.onGeneratedObservable.addOnce((()=>{const o=n.readPixels();if(!o)return r(new Error("No Pixel Data found on procedural texture")),n.dispose(),void(s||i.dispose());o.then((r=>{n.dispose(),s||i.dispose(),t.filename?(th.DumpData(2*t.size,t.size,r,void 0,"image/png",t.filename),e(null)):e(r)}))}))}))}Bi.ShadersStore.equirectangularPanoramaPixelShader="#ifdef GL_ES\nprecision highp float;\n#endif\n#define M_PI 3.1415926535897932384626433832795\nvarying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3(\n- sin( longitude )*sin( latitude ),\ncos( latitude ),\n- cos( longitude )*sin( latitude )\n);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}";class FR extends Ja{constructor(e,t={}){super(e),this.options=t,this._direction=new _e(0,0,-1),this._mat=new me,this._onSelectEnabled=!1,this._origin=new _e(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new K,this._onHitTestResults=e=>{const t=e.map((e=>{const t=me.FromArray(e.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&t.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}}));this.lastNativeXRHitResults=e,this.onHitTestResultObservable.notifyObservers(t)},this._onSelect=e=>{this._onSelectEnabled&&FR.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",Ds.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,s){return e.requestHitTest(t,i).then((e=>{const t=s||(e=>!!e.hitMatrix);return e.filter(t)}))}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const s=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,s,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;me.FromArrayToRef(t.transform.matrix,0,this._mat),_e.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),_e.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();const i=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});FR.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}FR.Name=qa.HIT_TEST,FR.Version=1,Za.AddWebXRFeature(FR.Name,((e,t)=>()=>new FR(e,t)),FR.Version,!1);let LR=0;class BR extends Ja{set referenceSpaceForFrameAnchors(e){this._referenceSpaceForFrameAnchors=e}constructor(e,t={}){super(e),this._options=t,this._lastFrameDetected=new Set,this._trackedAnchors=[],this._futureAnchors=[],this.onAnchorAddedObservable=new K,this.onAnchorRemovedObservable=new K,this.onAnchorUpdatedObservable=new K,this._tmpVector=new _e,this._tmpQuaternion=new fe,this.xrNativeFeatureName="anchors"}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new _e,i=new fe){this._populateTmpTransformation(t,i);const s=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(!e.xrHitResult.createAnchor)throw this.detach(),new Error("Anchors not enabled in this environment/browser");try{const t=await e.xrHitResult.createAnchor(s);return new Promise(((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:s,resolve:e,reject:i})}))}catch(e){throw new Error(e)}}async addAnchorAtPositionAndRotationAsync(e,t=new fe,i=!1){this._populateTmpTransformation(e,t);const s=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),r=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(s,this._xrSessionManager.currentFrame):void 0;return new Promise(((e,t)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!1,xrTransformation:s,resolve:e,reject:t})}))}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){const e=this._trackedAnchors.pop();if(e){try{e.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(e)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;const t=e.trackedAnchors;if(t){const i=this._trackedAnchors.filter((e=>!t.has(e.xrAnchor))).map((e=>this._trackedAnchors.indexOf(e)));let s=0;i.forEach((e=>{const t=this._trackedAnchors.splice(e-s,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),s++})),t.forEach((t=>{if(this._lastFrameDetected.has(t)){const i=this._findIndexInAnchorArray(t),s=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,s,e),s.attachedNode&&(s.attachedNode.rotationQuaternion=s.attachedNode.rotationQuaternion||new fe,s.transformationMatrix.decompose(s.attachedNode.scaling,s.attachedNode.rotationQuaternion,s.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(s)}catch(e){Ds.Warn("Anchor could not be updated")}}else{const i={id:LR++,xrAnchor:t,remove:()=>t.delete()},s=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(s),this.onAnchorAddedObservable.notifyObservers(s);const r=this._futureAnchors.filter((e=>e.nativeAnchor===t))[0];r&&(r.resolve(s),r.resolved=!0)}})),this._lastFrameDetected=t}this._futureAnchors.forEach((t=>{t.resolved||t.submitted||(this._createAnchorAtTransformation(t.xrTransformation,e).then((e=>{t.nativeAnchor=e}),(e=>{t.resolved=!0,t.reject(e)})),t.submitted=!0)}))}_findIndexInAnchorArray(e){for(let t=0;t()=>new BR(e,t)),BR.Version);let kR=0;class VR extends Ja{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new K,this.onPlaneRemovedObservable=new K,this.onPlaneUpdatedObservable=new K,this.xrNativeFeatureName="plane-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){if(!super.detach())return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){const e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return"undefined"!=typeof XRPlane}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.detectedPlanes||e.worldInformation?.detectedPlanes;if(t){for(let e=0;e{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._findIndexInPlaneArray(t),s=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,s,e),this.onPlaneUpdatedObservable.notifyObservers(s)}}else{const i={id:kR++,xrPlane:t,polygonDefinition:[]},s=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(s),this.onPlaneAddedObservable.notifyObservers(s)}})),this._lastFrameDetected=t}}_init(){const e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),this._xrSessionManager.session.updateWorldTrackingState?(this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()):e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map((e=>{const t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new _e(e.x,e.y,e.z*t)}));const s=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(s){const e=t.transformationMatrix||new me;me.FromArrayToRef(s.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new VR(e,t)),VR.Version);class UR extends Ja{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new K}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){const t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper)if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){const i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){const i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{const i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach((t=>t.setEnabled(e))),this.onBackgroundStateChangedObservable.notifyObservers(e)}}UR.Name=qa.BACKGROUND_REMOVER,UR.Version=1,Za.AddWebXRFeature(UR.Name,((e,t)=>()=>new UR(e,t)),UR.Version,!0);class GR{}class zR extends Ja{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||nl.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,s=_d("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});s.isVisible=this._debugMode,s.isPickable=!1,s.rotationQuaternion=new fe;const r=e.grip||e.pointer;s.position.copyFrom(r.position),s.rotationQuaternion.copyFrom(r.rotationQuaternion);const n=new nl(s,t,{mass:0,...this._options.physicsProperties});this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:s}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||Ne.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce((t=>{t._doNotLoadControllerMesh?this._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce((()=>{const i=new nl(t.rootMesh,nl.MeshImpostor,{mass:0,...this._options.physicsProperties}),s=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:s.position.clone(),oldRotation:s.rotationQuaternion.clone()}}))})):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new fe,this._tmpVector=new _e,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e];t.impostorMesh&&(t.impostorMesh.isVisible=!0)}))}addController(e){this._attachController(e)}attach(){if(!super.attach())return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._options.enableHeadsetImpostor){const e=this._options.headsetImpostorParams||{impostorType:nl.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=_d("headset-mesh",{diameterX:"number"==typeof t?t:t.width,diameterY:"number"==typeof t?t:t.height,diameterZ:"number"==typeof t?t:t.depth}),this._headsetMesh.rotationQuaternion=new fe,this._headsetMesh.isVisible=!1,this._headsetImpostor=new nl(this._headsetMesh,e.impostorType,{mass:0,...e})}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._headsetMesh&&this._headsetMesh.dispose(),!0)}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){const t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties={...this._options.physicsProperties,...e}}_onXRFrame(e){if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),this._options.xrInput.xrCamera._lastXRViewerPose?.linearVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(this._options.xrInput.xrCamera._lastXRViewerPose?.angularVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e],i=t.xrController.grip||t.xrController.pointer,s=t.oldPos||t.impostorMesh.position;if(t.xrController._lastXRPose?.linearVelocity){const e=t.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setLinearVelocity(this._tmpVector)}else i.position.subtractToRef(s,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),t.impostor.setLinearVelocity(this._tmpVector);s.copyFrom(i.position),this._debugMode&&Ne.Log([this._tmpVector,"linear"]);const r=t.oldRotation||t.impostorMesh.rotationQuaternion;if(t.xrController._lastXRPose?.angularVelocity){const e=t.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setAngularVelocity(this._tmpVector)}else if(!r.equalsWithEpsilon(i.rotationQuaternion)){r.conjugateInPlace().multiplyToRef(i.rotationQuaternion,this._tmpQuaternion);const e=Math.sqrt(this._tmpQuaternion.x*this._tmpQuaternion.x+this._tmpQuaternion.y*this._tmpQuaternion.y+this._tmpQuaternion.z*this._tmpQuaternion.z);if(this._tmpVector.set(this._tmpQuaternion.x,this._tmpQuaternion.y,this._tmpQuaternion.z),e<.001)this._tmpVector.scaleInPlace(2);else{const t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}t.impostor.setAngularVelocity(this._tmpVector)}r.copyFrom(i.rotationQuaternion),this._debugMode&&Ne.Log([this._tmpVector,this._tmpQuaternion,"angular"])}))}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}zR.Name=qa.PHYSICS_CONTROLLERS,zR.Version=1,Za.AddWebXRFeature(zR.Name,((e,t)=>()=>new zR(e,t)),zR.Version,!0);class WR extends Ja{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new me,this._tmpPos=new _e,this._tmpQuat=new fe,this._initHitTestSource=e=>{if(!e)return;const t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),i.space?this._xrSessionManager.session.requestHitTestSource(i).then((e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})):Ds.Warn("waiting for viewer reference space to initialize")},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new K,this.paused=!1,this.xrNativeFeatureName="hit-test",Ds.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach())return!1;if(!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){const e=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:e,entityTypes:this.options.entityTypes}).then((e=>{this._transientXrHitTestSource=e}))}return!0}detach(){return!!super.detach()&&(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(this.attached&&!this.paused){if(this._xrHitTestSource){const t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}this._transientXrHitTestSource&&e.getHitTestResultsForTransientInput(this._transientXrHitTestSource).forEach((e=>{this._processWebXRHitTestResult(e.results,e.inputSource)}))}}_processWebXRHitTestResult(e,t){const i=[];e.forEach((e=>{const s=e.getPose(this._xrSessionManager.referenceSpace);if(!s)return;const r=s.transform.position,n=s.transform.orientation;this._tmpPos.set(r.x,r.y,r.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._tmpQuat.set(n.x,n.y,n.z,n.w),me.FromFloat32ArrayToRefScaled(s.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());const o={position:this.autoCloneTransformation?this._tmpPos.clone():this._tmpPos,rotationQuaternion:this.autoCloneTransformation?this._tmpQuat.clone():this._tmpQuat,transformationMatrix:this.autoCloneTransformation?this._tmpMat.clone():this._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:e};i.push(o)})),this.onHitTestResultObservable.notifyObservers(i)}}WR.Name=qa.HIT_TEST,WR.Version=2,Za.AddWebXRFeature(WR.Name,((e,t)=>()=>new WR(e,t)),WR.Version,!1);class HR extends Ja{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new K,this.onFeaturePointsUpdatedObservable=new K,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this.featurePointCloud.length=0,!0)}dispose(){super.dispose(),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw new Error("Received malformed feature point cloud of length: "+t.length);const e=t.length/5,i=[],s=[];for(let r=0;r0&&this.onFeaturePointsAddedObservable.notifyObservers(s),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}}HR.Name=qa.FEATURE_POINTS,HR.Version=1,Za.AddWebXRFeature(HR.Name,(e=>()=>new HR(e)),HR.Version);let XR=0;class YR extends Ja{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new K,this.onMeshRemovedObservable=new K,this.onMeshUpdatedObservable=new K,this.xrNativeFeatureName="mesh-detection",this._options.generateMeshes&&(this._options.convertCoordinateSystems=!0),this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach((e=>{this.onMeshRemovedObservable.notifyObservers(e)})),this._detectedMeshes.clear()),!0)}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){try{if(!this.attached||!e)return;const t=e.detectedMeshes||e.worldInformation?.detectedMeshes;if(t){const i=new Set;this._detectedMeshes.forEach(((e,s)=>{t.has(s)||i.add(s)})),i.forEach((e=>{const t=this._detectedMeshes.get(e);t&&(this.onMeshRemovedObservable.notifyObservers(t),this._detectedMeshes.delete(e))})),t.forEach((t=>{if(this._detectedMeshes.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{const i={id:XR++,xrMesh:t},s=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,s),this.onMeshAddedObservable.notifyObservers(s)}}))}}catch(e){Ne.Log(e.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;const s=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=s,t.normals=e.normals;else{t.positions=new Float32Array(s.length);for(let e=0;e()=>new YR(e,t)),YR.Version,!1),function(e){e[e.NotReceived=0]="NotReceived",e[e.Waiting=1]="Waiting",e[e.Received=2]="Received"}(QR||(QR={}));class jR extends Ja{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new K,this.onTrackableImageFoundObservable=new K,this.onTrackedImageUpdatedObservable=new K,this._trackableScoreStatus=QR.NotReceived,this._trackedImages=[],this.xrNativeFeatureName="image-tracking"}attach(){return super.attach()}detach(){return super.detach()}getTrackedImageById(e){return this._trackedImages[e]||null}dispose(){super.dispose(),this._trackedImages.forEach((e=>{e.originalBitmap.close()})),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()}async getXRSessionInitExtension(){if(!this.options.images||!this.options.images.length)return{};const e=this.options.images.map((e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src)));try{const t=await Promise.all(e);return this._originalTrackingRequest=t.map(((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth}))),{trackedImages:this._originalTrackingRequest}}catch(e){return Ds.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===QR.Waiting)return;if(this._trackableScoreStatus===QR.NotReceived)return void this._checkScoresAsync();const t=e.getImageTrackingResults();for(const i of t){let t=!1;const s=i.index,r=this._trackedImages[s];if(!r)continue;r.xrTrackingResult=i,r.realWorldWidth!==i.measuredWidthInMeters&&(r.realWorldWidth=i.measuredWidthInMeters,t=!0);const n=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(n){const e=r.transformationMatrix;me.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}const o="emulated"===i.trackingState;r.emulated!==o&&(r.emulated=o,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(r)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==QR.NotReceived)return;this._trackableScoreStatus=QR.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(e&&0!==e.length){for(let t=0;t0?QR.Received:QR.NotReceived}else this._trackableScoreStatus=QR.NotReceived}}jR.Name=qa.IMAGE_TRACKING,jR.Version=1,Za.AddWebXRFeature(jR.Name,((e,t)=>()=>new jR(e,t)),jR.Version,!1);class KR extends Ja{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",Ds.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!(!super.attach()||!this._xrSessionManager.session.domOverlayState||null===this._xrSessionManager.session.domOverlayState.type||(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),0))}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(void 0===this.options.element)return Ds.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){const e=document.querySelector(this.options.element);if(null===e)return Ds.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`),{};this._element=e}else this._element=this.options.element;return{domOverlay:{root:this._element}}}}KR.Name=qa.DOM_OVERLAY,KR.Version=1,Za.AddWebXRFeature(KR.Name,((e,t)=>()=>new KR(e,t)),KR.Version,!1);class $R extends Ja{get movementDirection(){return this._movementDirection}get movementEnabled(){return this._featureContext.movementEnabled}set movementEnabled(e){this._featureContext.movementEnabled=e}get movementOrientationFollowsViewerPose(){return this._featureContext.movementOrientationFollowsViewerPose}set movementOrientationFollowsViewerPose(e){this._featureContext.movementOrientationFollowsViewerPose=e}get movementSpeed(){return this._featureContext.movementSpeed}set movementSpeed(e){this._featureContext.movementSpeed=e}get movementThreshold(){return this._featureContext.movementThreshold}set movementThreshold(e){this._featureContext.movementThreshold=e}get rotationEnabled(){return this._featureContext.rotationEnabled}set rotationEnabled(e){this._featureContext.rotationEnabled=e}get rotationSpeed(){return this._featureContext.rotationSpeed}set rotationSpeed(e){this._featureContext.rotationSpeed=e}get rotationThreshold(){return this._featureContext.rotationThreshold}set rotationThreshold(e){this._featureContext.rotationThreshold=e}constructor(e,t){super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new fe,this._tmpRotationMatrix=me.Identity(),this._tmpTranslationDirection=new _e,this._tmpMovementTranslation=new _e,this._tempCacheQuaternion=new fe,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController)for(const i of this._currentRegistrationConfigurations){let s=null;if(i.allowedComponentTypes)for(const t of i.allowedComponentTypes){const i=e.motionController.getComponentOfType(t);if(null!==i){s=i;break}}if(i.mainComponentOnly){const t=e.motionController.getMainComponent();if(null===t)continue;s=t}if("function"==typeof i.componentSelectionPredicate&&(s=i.componentSelectionPredicate(e)),s&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness)continue;if(null===s)continue;const r={registrationConfiguration:i,component:s};t.registeredComponents.push(r),"axisChangedHandler"in i&&(r.onAxisChangedObserver=s.onAxisValueChangedObservable.add((e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)}))),"buttonChangedhandler"in i&&(r.onButtonChangedObserver=s.onButtonStateChangedObservable.add((()=>{s.changes.pressed&&i.buttonChangedhandler(s.changes.pressed,this._movementState,this._featureContext,this._xrInput)})))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}},t&&void 0!==t.xrInput?(Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=$R.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:t.movementOrientationFollowsViewerPose??!0,movementSpeed:t.movementSpeed??1,movementThreshold:t.movementThreshold??.25,rotationEnabled:t.rotationEnabled??!0,rotationSpeed:t.rotationSpeed??1,rotationThreshold:t.rotationThreshold??.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput):Ds.Error('WebXRControllerMovement feature requires "xrInput" option.')}attach(){return!!super.attach()&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._controllers={},!0)}_onXRFrame(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){const e=.001*this._xrSessionManager.scene.getEngine().getDeltaTime()*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=e,fe.RotationYawPitchRollToRef(e,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(fe.RotationYawPitchRollToRef(3*e,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(me.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),_e.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}}_detachController(e){const t=this._controllers[e];if(t){for(const e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}}$R.Name=qa.MOVEMENT,$R.REGISTRATIONS={default:[{allowedComponentTypes:[rv.THUMBSTICK_TYPE,rv.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(e,t,i)=>{t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[rv.THUMBSTICK_TYPE,rv.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(e,t,i)=>{t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},$R.Version=1,Za.AddWebXRFeature($R.Name,((e,t)=>()=>new $R(e,t)),$R.Version,!0);class qR extends Ja{constructor(e,t){super(e),this.options=t,this._canvasContext=null,this._reflectionCubeMap=null,this._xrLightEstimate=null,this._xrLightProbe=null,this._xrWebGLBinding=null,this._lightDirection=_e.Up().negateInPlace(),this._lightColor=Ee.White(),this._intensity=1,this._sphericalHarmonics=new Q_,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new K,this._updateReflectionCubeMap=()=>{if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const e=Date.now();if(e-this._cubeMapPollTime{this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap)})))}},this.xrNativeFeatureName="light-estimation",this.options.createDirectionalLightSource&&(this.directionalLight=new cg("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new _e(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=Br.FALLOFF_GLTF),this._hdrFilter=new rx(this._xrSessionManager.scene.getEngine()),Ds.Warn("light-estimation is an experimental and unstable feature.")}get reflectionCubeMapTexture(){return this._reflectionCubeMap}get xrLightingEstimate(){return this._xrLightEstimate?{lightColor:this._lightColor,lightDirection:this._lightDirection,lightIntensity:this._intensity,sphericalHarmonics:this._sphericalHarmonics}:this._xrLightEstimate}_getCanvasContext(){return null===this._canvasContext&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(null===this._xrWebGLBinding){const e=this._getCanvasContext();this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,e)}return this._xrWebGLBinding}attach(){if(!super.attach())return!1;const e=this.options.reflectionFormat??(this._xrSessionManager.session.preferredReflectionFormat||"srgba8");return this.options.reflectionFormat=e,this._xrSessionManager.session.requestLightProbe({reflectionFormat:e}).then((e=>{this._xrLightProbe=e,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new ya(this._xrSessionManager.scene),this._reflectionCubeMap._isCube=!0,this._reflectionCubeMap.coordinatesMode=3,this.options.setSceneEnvironmentTexture&&(this._xrSessionManager.scene.environmentTexture=this._reflectionCubeMap)),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap))})),!0}detach(){const e=super.detach();return null===this._xrLightProbe||this.options.disableCubeMapReflection||(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,e}dispose(){super.dispose(),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){const e=Date.now();if(e-this._lightEstimationPollTime()=>new qR(e,t)),qR.Version,!1);class ZR extends Ja{constructor(e){super(e),this.onEyeTrackingStartedObservable=new K,this.onEyeTrackingEndedObservable=new K,this.onEyeTrackingFrameUpdateObservable=new K,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new Ua(_e.Zero(),_e.Forward()),this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay)},this._eyeTrackingEndListener=()=>{this._latestEyeSpace=null,this._gazeRay=null,this.onEyeTrackingEndedObservable.notifyObservers()},this.xrNativeFeatureName="eye-tracking",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}dispose(){super.dispose(),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()}get isEyeGazeValid(){return!!this._gazeRay}getEyeGaze(){return this._gazeRay}_onXRFrame(e){if(this.attached&&e&&this._latestEyeSpace&&this._gazeRay){const t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z).scaleInPlace(this._xrSessionManager.worldScalingFactor);const e=t.transform.orientation;ve.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?_e.RightHandedForwardReadOnly.rotateByQuaternionToRef(ve.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,ve.Quaternion[0].z*=-1,ve.Quaternion[0].w*=-1,_e.LeftHandedForwardReadOnly.rotateByQuaternionToRef(ve.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))}}ZR.Name=qa.EYE_TRACKING,ZR.Version=1,Za.AddWebXRFeature(ZR.Name,(e=>()=>new ZR(e)),ZR.Version,!1);class JR{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw new Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class eM{constructor(){this._samples=new JR(20),this._entropy=0,this.onFirstStepDetected=new K}update(e,t,i,s){this._samples.push(e,t);const r=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=de.Distance(r,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let n;for(n=this._samePointCheckStartIdx;no&&(a=t,o=e);if(on*this._squaredProjectionDistanceThreshold)return;const p=ve.Vector3[0];p.set(i,s,0);const f=ve.Vector3[1];f.set(h.x,h.y,0);const m=_e.Cross(p,f).z>0,g=r.clone(),v=r.clone();l.subtractToRef(r,h),m?(h.scaleAndAddToRef(this._axisToApexShrinkFactor,g),h.scaleAndAddToRef(this._axisToApexExtendFactor,v)):(h.scaleAndAddToRef(this._axisToApexExtendFactor,g),h.scaleAndAddToRef(this._axisToApexShrinkFactor,v)),this.onFirstStepDetected.notifyObservers({leftApex:g,rightApex:v,currentPosition:r,currentStepDirection:m?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),this._axisLength<.03))}get _vitalityThreshold(){return.1}get forward(){return this._forward}}class iM{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new eM,this._walker=null,this._movement=new de,this._millisecondsSinceLastUpdate=iM._MillisecondsPerUpdate,this.movementThisFrame=_e.Zero(),this._engine=e,this._detector.onFirstStepDetected.add((e=>{this._walker||(this._walker=new tM(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),this._walker.onFootfall.add((()=>{Ne.Log("Footfall!")})),this._walker.onMovement.add((e=>{this._walker.forward.scaleAndAddToRef(.024*e.deltaT,this._movement)})))}))}update(e,t){t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=iM._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=iM._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker&&(this._walker.update(e.x,e.z)||(this._walker=null)),this._movement.scaleInPlace(.85)),this.movementThisFrame.set(this._movement.x,0,this._movement.y)}}class sM extends Ja{static get Name(){return qa.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()}constructor(e,t){super(e),this._up=new _e,this._forward=new _e,this._position=new _e,this._movement=new _e,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&Ne.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended")}isCompatible(){return void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!(!this.isCompatible||!super.attach()||(this._walker=new iM(this._sessionManager.scene.getEngine()),0))}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){const t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;const i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,s=t.transform.matrix;this._up.copyFromFloats(s[4],s[5],i*s[6]),this._forward.copyFromFloats(s[8],s[9],i*s[10]),this._position.copyFromFloats(s[12],s[13],i*s[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||_e.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}Za.AddWebXRFeature(sM.Name,((e,t)=>()=>new sM(e,t)),sM.Version,!1);class rM extends du{constructor(e,t,i,s,r,n,o=null){super(e,t,i,s,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this.isMultiview=r,this.createRTTProvider=n,this._originalInternalTexture=o}}class nM extends _u{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this.onRenderTargetTextureCreatedObservable=new K,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t="none"){const i=this._lastSubImages.get(t),s="right"==t?1:0,r=e.colorTextureWidth??e.textureWidth,n=e.colorTextureHeight??e.textureHeight;if(!this._renderTargetTextures[s]||i?.textureWidth!==r||i?.textureHeight!==n){let i;const o=e.depthStencilTextureWidth??r,a=e.depthStencilTextureHeight??n;r!==o&&n!==a||(i=e.depthStencilTexture),this._renderTargetTextures[s]=this._createRenderTargetTexture(r,n,null,e.colorTexture,i,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n},this.onRenderTargetTextureCreatedObservable.notifyObservers({texture:this._renderTargetTextures[s],eye:t})}return this._lastSubImages.set(t,e),this._renderTargetTextures[s]}_getSubImageForEye(e){const t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){const t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e?.eye)}_setViewportForSubImage(e,t){const i=t.colorTextureWidth??t.textureWidth,s=t.colorTextureHeight??t.textureHeight,r=t.viewport;e.x=r.x/i,e.y=r.y/s,e.width=r.width/i,e.height=r.height/s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}}class oM extends rM{constructor(e,t,i){super((()=>e.textureWidth),(()=>e.textureHeight),e,"XRProjectionLayer",t,(e=>new aM(e,i,this))),this.layer=e}}class aM extends nM{constructor(e,t,i){super(e,t,i),this.layerWrapper=i,this._projectionLayer=i.layer}_getSubImageForView(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)}getRenderTargetTextureForView(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)}getRenderTargetTextureForEye(e){const t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}}const lM={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1,clearOnAccess:!1},hM={};class cM extends Ja{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this._isMultiviewEnabled=!1,this._projectionLayerInitialized=!1,this._compositionLayerTextureMapping=new WeakMap,this._layerToRTTProviderMapping=new WeakMap,this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;const t={...lM,...this._options.projectionLayerInit};return this._isMultiviewEnabled=this._options.preferMultiviewOnInit&&e.getCaps().multiview,this.createProjectionLayer(t),this._projectionLayerInitialized=!0,!0}detach(){return!!super.detach()&&(this._existingLayers.forEach((e=>{e.dispose()})),this._existingLayers.length=0,this._projectionLayerInitialized=!1,!0)}createXRWebGLLayer(e=hM){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new pu(t)}_validateLayerInit(e,t=this._isMultiviewEnabled){if(!this._xrSessionManager.inXRSession)throw new Error("Cannot create a layer outside of a WebXR session. Make sure the session has started before creating layers.");if(t&&"texture-array"!==e.textureType)throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)throw new Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.")}_extendXRLayerInit(e,t=this._isMultiviewEnabled){return t&&(e.textureType="texture-array"),e}createProjectionLayer(e=lM,t=this._isMultiviewEnabled){this._extendXRLayerInit(e,t),this._validateLayerInit(e,t);const i=this._xrWebGLBinding.createProjectionLayer(e),s=new oM(i,t,this._xrWebGLBinding);return this.addXRSessionLayer(s),s}_createQuadLayer(e={params:{}},t){this._extendXRLayerInit(e.params,!1);const i=this._existingLayers[0].layer.textureWidth,s=this._existingLayers[0].layer.textureHeight,r={space:this._xrSessionManager.referenceSpace,viewPixelWidth:i,viewPixelHeight:s,clearOnAccess:!0,...e.params};this._validateLayerInit(r,!1);const n=this._xrWebGLBinding.createQuadLayer(r);n.width=this._isMultiviewEnabled?1:2,n.height=1;const o=new rM((()=>n.width),(()=>n.height),n,"XRQuadLayer",!1,(e=>new nM(e,this._xrWebGLBinding,o)));t&&this._compositionLayerTextureMapping.set(n,t);const a=o.createRenderTargetTextureProvider(this._xrSessionManager);return this._layerToRTTProviderMapping.set(n,a),this.addXRSessionLayer(o),o}addFullscreenAdvancedDynamicTexture(e,t={distanceFromHeadset:1.5}){const i=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}},e),s=i.layer,r={x:0,y:0,z:-Math.max(.1,t.distanceFromHeadset)};s.transform=new XRRigidTransform(r,{x:0,y:0,z:0,w:1});const n=this._layerToRTTProviderMapping.get(s);if(!n)throw new Error("Could not find the RTT provider for the layer");const o=this._xrSessionManager.scene.layers.find((t=>t.texture===e));if(!o)throw new Error("Could not find the babylon layer for the texture");return n.onRenderTargetTextureCreatedObservable.add((e=>{e.eye&&"right"===e.eye||(e.texture.clearColor=new Ae(0,0,0,0),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.scene.onBeforeRenderObservable.add((()=>{e.texture.render()})),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.onXRSessionEnded.addOnce((()=>{o.renderTargetTextures.splice(o.renderTargetTextures.indexOf(e.texture),1),o.renderOnlyInRenderTargetTextures=!1})))})),i}_addLensFlareSystem(e){const t=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}}),i=t.layer;i.width=2,i.height=1;i.transform=new XRRigidTransform({x:0,y:0,z:-10},{x:0,y:0,z:0,w:1});const s=this._layerToRTTProviderMapping.get(i);if(!s)throw new Error("Could not find the RTT provider for the layer");return s.onRenderTargetTextureCreatedObservable.add((t=>{t.texture.clearColor=new Ae(0,0,0,0),t.texture.customRenderFunction=()=>{e.render()}})),this._xrSessionManager.onXRSessionInit.add((()=>{this._xrSessionManager.scene.lensFlareSystems.splice(this._xrSessionManager.scene.lensFlareSystems.indexOf(e),1)})),this._xrSessionManager.onXRSessionEnded.add((()=>{this._xrSessionManager.scene.lensFlareSystems.push(e)})),t}addXRSessionLayer(e){this._existingLayers.push(e),this.setXRSessionLayers(this._existingLayers)}setXRSessionLayers(e=this._existingLayers){const t={...this._xrSessionManager.session.renderState};t.baseLayer=void 0,t.layers=e.map((e=>e.layer)),this._xrSessionManager.updateRenderState(t),this._projectionLayerInitialized||this._xrSessionManager._setBaseLayerWrapper(e.length>0?e.at(0):null)}isCompatible(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){const t=this._existingLayers;for(let i=0;i()=>new cM(e,t)),cM.Version,!1);class uM extends Ja{get width(){return this._width}get height(){return this._height}get rawValueToMeters(){return this._rawValueToMeters}get normDepthBufferFromNormView(){return this._normDepthBufferFromNormView}get depthUsage(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}}get depthDataFormat(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}}get latestInternalTexture(){if(!this._cachedWebGLTexture)return null;const e=this._xrSessionManager.scene.getEngine(),t=new ss(e,is.Unknown);return t.isCube=!1,t.invertY=!1,t._useSRGBBuffer=!1,t.format="ushort"===this.depthDataFormat?2:5,t.generateMipMaps=!1,t.type="ushort"===this.depthDataFormat?5:1,t.samplingMode=7,t.width=this.width??0,t.height=this.height??0,t._cachedWrapU=1,t._cachedWrapV=1,t._hardwareTexture=new Ks(this._cachedWebGLTexture,e._gl),t}get latestDepthBuffer(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null}get latestDepthImageTexture(){return this._cachedDepthImageTexture}constructor(e,t){super(e),this.options=t,this._width=null,this._height=null,this._rawValueToMeters=null,this._normDepthBufferFromNormView=null,this._cachedDepthBuffer=null,this._cachedWebGLTexture=null,this._cachedDepthImageTexture=null,this.onGetDepthInMetersAvailable=new K,this.xrNativeFeatureName="depth-sensing",Ds.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){return!!super.attach(e)&&(null!=this._xrSessionManager.session.depthDataFormat&&null!=this._xrSessionManager.session.depthUsage&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0))}dispose(){this._cachedDepthImageTexture?.dispose()}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(const t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:Ds.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(null===s)return;const{data:r,width:n,height:o,rawValueToMeters:a,getDepthInMeters:l}=s;switch(this._width=n,this._height=o,this._rawValueToMeters=a,this._cachedDepthBuffer=r,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(s)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Oa.CreateRTexture(null,n,o,this._xrSessionManager.scene,!1,!0,Pa.NEAREST_SAMPLINGMODE,oo.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(r)).map((e=>e*a)));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(r).map((e=>e*a)))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(null===s)return;const{texture:r,width:n,height:o}=s;this._width=n,this._height=o,this._cachedWebGLTexture=r;const a=this._xrSessionManager.scene,l=a.getEngine().wrapWebGLTexture(r);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Oa.CreateRTexture(null,n,o,a,!1,!0,Pa.NEAREST_SAMPLINGMODE,"ushort"===i?oo.TEXTURETYPE_UNSIGNED_BYTE:oo.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=l}getXRSessionInitExtension(){const e=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,t=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise((i=>{i(e&&t?{depthSensing:{usagePreference:this.options.usagePreference.map((e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}})),dataFormatPreference:this.options.dataFormatPreference.map((e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}}))}}:{})}))}}uM.Name=qa.DEPTH_SENSING,uM.Version=1,Za.AddWebXRFeature(uM.Name,((e,t)=>()=>new uM(e,t)),uM.Version,!1);Bi.ShadersStore.velocityPixelShader="precision highp float;\n#define CUSTOM_FRAGMENT_BEGIN\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nhighp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.velocityVertexShader="#define CUSTOM_VERTEX_BEGIN\n#define VELOCITY\nattribute vec3 position;\n#include\nuniform mat4 viewProjection;uniform mat4 previousViewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR;\n#endif\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;}\n#elif\nclipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class dM extends ih{constructor(e,t,i,s=512){super("spacewarp rtt",s,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[me.Identity(),me.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new Nd("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add((e=>{this._previousWorldMatrices[e.uniqueId]=this._previousWorldMatrices[e.uniqueId]||e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[e.uniqueId]),this._previousWorldMatrices[e.uniqueId]=e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)})),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;const i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach((e=>{this._originalPairing.push([e,e.material]),e.material=this._velocityMaterial})),super.render(e,t),this._originalPairing.forEach((e=>{e[0].material=e[1]}))}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}}class _M{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){const t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');const i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,s,r){if(!this._engine)throw new Error("Engine is disposed");const n={width:e,height:t},o=new dM(s,r,this._scene,n),a=o.renderTarget;return i&&(a._framebuffer=i),a._colorTextureArray=s,a._depthStencilTextureArray=r,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let s=this._renderTargetTextures.get(t.eye);const r=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return s&&i?.textureWidth===r&&i?.textureHeight==n||(s=this._createRenderTargetTexture(r,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,s),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n}),this._lastSubImages.set(t,e),s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}accessMotionVector(e){const t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){const t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.clear()}}class pM extends Ja{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[qa.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new _M(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add((()=>this._onAfterRender())),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;const i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}}pM.Name=qa.SPACE_WARP,pM.Version=1,Za.AddWebXRFeature(pM.Name,(e=>()=>new pM(e)),pM.Version,!1);class fM extends Ja{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new K,this.xrNativeFeatureName="camera-access"}attach(e){return!!super.attach(e)&&(this._glContext=this._xrSessionManager.scene.getEngine()._gl,this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),!0)}detach(){return!!super.detach()&&(this._glBinding=void 0,this.options.doNotDisposeOnDetach||(this._cachedInternalTextures.forEach((e=>e.dispose())),this.texturesData.forEach((e=>e.dispose())),this._cachedInternalTextures.length=0,this.texturesData.length=0,this.cameraIntrinsics.length=0),!0)}dispose(){super.dispose(),this.onTexturesUpdatedObservable.clear()}_updateCameraIntrinsics(e,t){const i={width:e.camera.width,height:e.camera.height,x:0,y:0},s=e.projectionMatrix,r=(1-s[8])*i.width/2+i.x,n=(1-s[9])*i.height/2+i.y,o=i.width/2*s[0],a=i.height/2*s[5],l=i.width/2*s[4];this.cameraIntrinsics[t]={u0:r,v0:n,ax:o,ay:a,gamma:l,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){if(!e.camera)return!1;this.viewIndex[t]=e.eye;const i=this._glBinding?.getCameraImage(e.camera);if(this._cachedInternalTextures[t])this._cachedInternalTextures[t]._hardwareTexture?.set(i);else{const s=new ss(this._xrSessionManager.scene.getEngine(),is.Unknown,!0);s.isCube=!0,s.invertY=!1,s.format=5,s.generateMipMaps=!0,s.type=1,s.samplingMode=3,s.width=e.camera.width,s.height=e.camera.height,s._cachedWrapU=1,s._cachedWrapV=1,s._hardwareTexture=new Ks(i,this._glContext),this._cachedInternalTextures[t]=s;const r=new ya(this._xrSessionManager.scene);r.name=`WebXR Raw Camera Access (${t})`,r._texture=this._cachedInternalTextures[t],this.texturesData[t]=r,this._updateCameraIntrinsics(e,t)}return this._cachedInternalTextures[t].isReady=!0,!0}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(!i||!i.views)return;let s=!0;i.views.forEach(((e,t)=>{s=s&&this._updateInternalTextures(e,t)})),s&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}fM.Name=qa.RAW_CAMERA_ACCESS,fM.Version=1,Za.AddWebXRFeature(fM.Name,((e,t)=>()=>new fM(e,t)),fM.Version,!1);class mM extends nv{constructor(e,t,i){super(e,gM[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}}cv.RegisterController("generic-hand-select-grasp",((e,t)=>new mM(t,e.gamepad,e.handedness)));const gM={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};class vM extends nv{constructor(e,t,i){super(e,xM["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";return e="left"===this.handedness?vM.MODEL_LEFT_FILENAME:vM.MODEL_RIGHT_FILENAME,{filename:e,path:vM.MODEL_BASE_URL+"default/"}}_getModelLoadingConstraints(){const e=fl.IsPluginForExtensionAvailable(".glb");return e||Ne.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach(((e,t)=>{if(!this.disableAnimation&&e&&this.rootMesh){const i=this._mapping.buttons[e],s=i.rootNodeName;if(!s)return void Ne.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);const r=this._getChildByName(this.rootMesh,s);if(!r)return void Ne.Warn("Missing button mesh with name: "+s);if(i.valueMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.valueNodeName),i.pressedMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.pressedNodeName),i.unpressedMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.unpressedNodeName),i.valueMesh&&i.pressedMesh&&i.unpressedMesh){const t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add((e=>{this._lerpTransform(i,e.value)}),void 0,!0)}else Ne.Warn("Missing button submesh under mesh with name: "+s)}})),this.getComponentIds().forEach((e=>{const t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach((i=>{if(!this.rootMesh)return;const s=this._mapping.axes[e][i],r=this._getChildByName(this.rootMesh,s.rootNodeName);r?(s.valueMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.valueNodeName),s.minMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.minNodeName),s.maxMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.maxNodeName),s.valueMesh&&s.minMesh&&s.maxMesh?t&&t.onAxisValueChangedObservable.add((e=>{const t="x-axis"===i?e.x:e.y;this._lerpTransform(s,t,!0)}),void 0,!0):Ne.Warn("Missing axis submesh under mesh with name: "+s.rootNodeName)):Ne.Warn("Missing axis mesh with name: "+s.rootNodeName)}))})))}_setRootMesh(e){let t;this.rootMesh=new ha(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;inew vM(t,e.gamepad,e.handedness)));const xM={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};class bM extends nv{constructor(e,t,i,s=!1,r=!1){super(e,TM[i],t,i),this._forceLegacyControllers=r,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";return e="left"===this.handedness?bM.MODEL_LEFT_FILENAME:bM.MODEL_RIGHT_FILENAME,{filename:e,path:this._isQuest()?bM.QUEST_MODEL_BASE_URL:bM.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){const t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach((e=>{const s=e&&this.getComponent(e);s&&s.onButtonStateChangedObservable.add((s=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(t||(this._modelRootNode.getChildren()[3].rotation.x=.2*-s.value,this._modelRootNode.getChildren()[3].position.y=.005*-s.value,this._modelRootNode.getChildren()[3].position.z=.005*-s.value));case"xr-standard-squeeze":return void(t||(this._modelRootNode.getChildren()[4].position.x=i*s.value*.0035));case"xr-standard-thumbstick":return;case"a-button":case"x-button":return void(t||(s.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0));case"b-button":case"y-button":return void(t||(s.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0))}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new ha(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=fe.FromEulerAngles(0,Math.PI,0)),e.forEach((e=>{e.isPickable=!1})),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}}bM.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",bM.MODEL_LEFT_FILENAME="left.babylon",bM.MODEL_RIGHT_FILENAME="right.babylon",bM.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",cv.RegisterController("oculus-touch",((e,t)=>new bM(t,e.gamepad,e.handedness))),cv.RegisterController("oculus-touch-legacy",((e,t)=>new bM(t,e.gamepad,e.handedness,!0)));const TM={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};class yM extends nv{constructor(e,t,i){super(e,SM[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){return{filename:yM.MODEL_FILENAME,path:yM.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add((t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(this._modelRootNode.getChildren()[6].rotation.x=.15*-t.value);case"xr-standard-touchpad":case"xr-standard-squeeze":return}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new ha(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1})),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=fe.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}yM.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",yM.MODEL_FILENAME="wand.babylon",cv.RegisterController("htc-vive",((e,t)=>new yM(t,e.gamepad,e.handedness)));const SM={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};class CM{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw new Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>this._nativeImpl._imageTrackingResults??[]}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;const i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];const s=this._xrTransform.orientation;return s.x=this._xrPoseVectorData[4],s.y=this._xrPoseVectorData[5],s.z=this._xrPoseVectorData[6],s.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw new Error("This function is not available in Babylon Native")}}var EM;Jp("NativeXRFrame",CM),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(EM||(EM={}));class AM{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=Cs(),this.connectedPointIds=[],this.name=e,this._connectionType=t}get connectionType(){return this._connectionType}_isSingularConnection(){return!0}isConnected(){return this._connectedPoint.length>0}connectTo(e){if(this._connectionType===e._connectionType)throw new Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw new Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName();for(const t of this._connectedPoint)e.connectedPointIds.push(t.uniqueId)}getClassName(){return"FGConnection"}deserialize(e){this.uniqueId=e.uniqueId,this.name=e.name,this._connectionType=e._connectionType,this.connectedPointIds=e.connectedPointIds}static Parse(e={},t){const i=new(Ds.Instantiate(e.className))(e.name,e._connectionType,t);return i.deserialize(e),i}}class PM{constructor(e){this.value=this._toInt(e)}_toInt(e){return 0|e}add(e){return new PM(this.value+e.value)}subtract(e){return new PM(this.value-e.value)}multiply(e){return new PM(Math.imul(this.value,e.value))}divide(e){return new PM(this.value/e.value)}getClassName(){return PM.ClassName}equals(e){return this.value===e.value}static Parse(e){return new PM(e.value)}}PM.ClassName="FlowGraphInteger",z("FlowGraphInteger",PM);class IM{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new IM(e.typeName,e.defaultValue)}}const RM=new IM("any",void 0),MM=new IM("string",""),OM=new IM("number",0),DM=new IM("boolean",!1),wM=new IM("Vector2",de.Zero()),NM=new IM("Vector3",_e.Zero()),FM=new IM("Vector4",pe.Zero()),LM=new IM("Matrix",me.Identity()),BM=new IM("Color3",Ee.Black()),kM=new IM("Color4",new Ae(0,0,0,0)),VM=new IM("Quaternion",fe.Identity()),UM=new IM("FlowGraphInteger",new PM(0));function GM(e){switch(typeof e){case"string":return MM;case"number":return OM;case"boolean":return DM;case"object":return e instanceof de?wM:e instanceof _e?NM:e instanceof pe?FM:e instanceof Ee?BM:e instanceof Ae?kM:e instanceof fe?VM:e instanceof PM?UM:RM;default:return RM}}class zM extends AM{constructor(e,t,i,s){super(e,t,i),this.richType=s}_isSingularConnection(){return this.connectionType===EM.Input}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===EM.Output?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){const i=AM.Parse(e,t);return i.richType=IM.Parse(e.richType),i}}function WM(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function HM(e){return"Vector2"===e||"Vector3"===e||"Vector4"===e||"Quaternion"===e||"Color3"===e||"Color4"===e}function XM(e,t,i){const s=t?.getClassName?.()??"";WM(s)?i[e]={name:t.name,className:s}:HM(s)?i[e]={value:t.asArray(),className:s}:i[e]=t}function YM(e,t,i){const s=t[e];let r;const n=s?.className;return r=WM(n)?i.getMeshByName(s.name):HM(n)?function(e,t){if("Vector2"===e)return de.FromArray(t);if("Vector3"===e)return _e.FromArray(t);if("Vector4"===e)return pe.FromArray(t);if("Quaternion"===e)return fe.FromArray(t);if("Color3"===e)return new Ee(t[0],t[1],t[2]);if("Color4"===e)return new Ae(t[0],t[1],t[2],t[3]);throw new Error(`Unknown vector class name ${e}`)}(n,s.value):"Matrix"===n?me.FromArray(s.value):n===PM.ClassName?PM.Parse(s):s&&void 0!==s.value?s.value:s,r}z("FGDataConnection",zM);class QM{constructor(e){this.config=e,this.uniqueId=Cs(),this.name=this.config?.name??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new zM(e,EM.Input,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new zM(e,EM.Output,this,t);return this.dataOutputs.push(i),i}getDataInput(e){return this.dataInputs.find((t=>t.name===e))}getDataOutput(e){return this.dataOutputs.find((t=>t.name===e))}serialize(e={},t=XM){e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName();for(const t of this.dataInputs){const i={};t.serialize(i),e.dataInputs.push(i)}for(const t of this.dataOutputs){const i={};t.serialize(i),e.dataOutputs.push(i)}}getClassName(){return"FGBlock"}static Parse(e,t){const i=Ds.Instantiate(e.className),s={},r=t.valueParseFunction??YM;if(e.config)for(const i in e.config)s[i]=r(i,e.config,t.scene);(function(e){return"FGSetPropertyBlock"===e||"FGGetPropertyBlock"===e||"FGPlayAnimationBlock"===e||"FGMeshPickEventBlock"===e})(e.className)&&(s.pathConverter=t.pathConverter);const n=new i(s);n.uniqueId=e.uniqueId;for(let t=0;tt.name===e))}getSignalOutput(e){return this.signalOutputs.find((t=>t.name===e))}serialize(e={}){super.serialize(e),e.signalInputs=[],e.signalOutputs=[];for(const t of this.signalInputs){const i={};t.serialize(i),e.signalInputs.push(i)}for(const t of this.signalOutputs){const i={};t.serialize(i),e.signalOutputs.push(i)}}deserialize(e){for(let t=0;t{t.type===lr.POINTERPICK&&t.pickInfo?.pickedMesh&&(t.pickInfo?.pickedMesh===i||JM(t.pickInfo?.pickedMesh,i))&&this._execute(e)}));const s=i.onDisposeObservable.add((()=>this._onDispose));e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",s)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),s=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(s),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return eO.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}var tO;eO.ClassName="FGMeshPickEventBlock",z(eO.ClassName,eO),function(e){e[e.Stopped=0]="Stopped",e[e.Started=1]="Started"}(tO||(tO={}));class iO{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=tO.Stopped,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>this.dispose()))}createContext(){const e=new ZM({scene:this._scene,coordinator:this._coordinator});return this._executionContexts.push(e),e}getContext(e){return this._executionContexts[e]}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==tO.Started){this.state=tO.Started,0===this._executionContexts.length&&this.createContext();for(const e of this._executionContexts){const t=this._getContextualOrder();for(const i of t)i._startPendingTasks(e)}}}_getContextualOrder(){const e=[];for(const t of this._eventBlocks)if(t.getClassName()===eO.ClassName){const i=t._getReferencedMesh();let s=0;for(;s0;){const s=t.pop();e(s);for(const e of s.dataInputs)for(const s of e._connectedPoint)i.has(s._ownerBlock.uniqueId)||(t.push(s._ownerBlock),i.add(s._ownerBlock.uniqueId));if(s instanceof KM)for(const e of s.signalOutputs)for(const s of e._connectedPoint)i.has(s._ownerBlock.uniqueId)||(t.push(s._ownerBlock),i.add(s._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks((t=>{const i={};t.serialize(i),e.allBlocks.push(i)})),e.executionContexts=[];for(const i of this._executionContexts){const s={};i.serialize(s,t),e.executionContexts.push(s)}}static GetDataOutConnectionByUniqueId(e,t){for(const i of e)for(const e of i.dataOutputs)if(e.uniqueId===t)return e;throw new Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(const i of e)if(i instanceof KM)for(const e of i.signalInputs)if(e.uniqueId===t)return e;throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const i=t.coordinator.createGraph(),s=[],r=t.valueParseFunction??YM;for(const n of e.allBlocks){const e=QM.Parse(n,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:r});s.push(e),e instanceof qM&&i.addEventBlock(e)}for(const e of s){for(const t of e.dataInputs)for(const e of t.connectedPointIds){const i=iO.GetDataOutConnectionByUniqueId(s,e);t.connectTo(i)}if(e instanceof KM)for(const t of e.signalOutputs)for(const e of t.connectedPointIds){const i=iO.GetSignalInConnectionByUniqueId(s,e);t.connectTo(i)}}for(const t of e.executionContexts)ZM.Parse(t,{graph:i,valueParseFunction:r});return i}}class sO{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add((()=>{this.dispose()})),(sO.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new iO({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){const t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach((e=>e.start()))}dispose(){this._flowGraphs.forEach((e=>e.dispose())),this._flowGraphs.length=0;const e=sO.SceneCoordinators.get(this.config.scene)??[],t=e.indexOf(this);-1!==t&&e.splice(t,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach((i=>{const s={};i.serialize(s,t),e._flowGraphs.push(s)}))}static Parse(e,t){const i=t.valueParseFunction??YM,s=new sO({scene:t.scene});return e._flowGraphs?.forEach((e=>{iO.Parse(e,{coordinator:s,valueParseFunction:i,pathConverter:t.pathConverter})})),s}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new K,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}sO.SceneCoordinators=new Map;class rO{constructor(e){this._context=e,this._context.onNodeExecutedObservable.add((e=>{Ds.Log(`Node executed: ${e.getClassName()}`)}))}}class nO extends KM{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class oO extends nO{constructor(e){super(e),this.message=this.registerDataInput("message",RM)}_execute(e){const t=this.message.getValue(e);Ne.Log(t),this.out._activateSignal(e)}getClassName(){return oO.ClassName}}oO.ClassName="FGConsoleLogBlock",z(oO.ClassName,oO);class aO extends nO{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,RM)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return aO.ClassName}}aO.ClassName="FGSetVariableBlock",z(aO.ClassName,aO);const lO=new RegExp(/\{(\w+)\}/g);class hO{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=lO.exec(e);for(;i;){const[,s]=i;this.templatedInputs.push(t.registerDataInput(s,UM)),i=lO.exec(e)}}getAccessor(e,t){let i=this.path;for(const e of this.templatedInputs){const s=e.getValue(t).value;i=i.replace(`{${e.name}}`,s.toString())}return e.convert(i)}}class cO extends nO{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",RM),this.templateComponent=new hO(e.path,this)}_execute(e){const t=this.a.getValue(e),i=this.templateComponent.getAccessor(this.config.pathConverter,e);i.info.set(t,i.object),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path}getClassName(){return cO.ClassName}}cO.ClassName="FGSetPropertyBlock",z("FGSetPropertyBlock",cO);class uO extends nO{constructor(e){super(e),this.config=e;for(let e=0;et.getValue(e)));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return uO.ClassName}}uO.ClassName="FGSendCustomEventBlock",z("FGSendCustomEventBlock",uO);class dO extends KM{constructor(e){super(e),this.condition=this.registerDataInput("condition",DM),this.onTrue=this._registerSignalOutput("onTrue"),this.onFalse=this._registerSignalOutput("onFalse")}_execute(e){this.condition.getValue(e)?this.onTrue._activateSignal(e):this.onFalse._activateSignal(e)}getClassName(){return"FGBranchBlock"}}z("FGBranchBlock",dO);class _O extends nO{constructor(e={startIndex:new PM(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",UM),this.value=this.registerDataOutput("value",UM)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const t=this.value.getValue(e);t.values)this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",r);else{const t=s-(r-i);this.timeRemaining.setValue(t,e)}}getClassName(){return"FGThrottleBlock"}}z("FGThrottleBlock",fO);class mO extends $M{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",OM)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(void 0!==t&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],s=e.configuration.scene,r=new Sv({timeout:t,contextObservable:s.onBeforeRenderObservable,onEnded:()=>this._onEnded(r,e)});r.start(),i.push(r),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],s=i.indexOf(e);-1!==s?i.splice(s,1):Ds.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningTimers")||[];for(const e of t)e.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return mO.ClassName}}mO.ClassName="FGTimerBlock",z("FGTimerBlock",mO);class gO extends KM{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",OM),this.config.startIndex=void 0!==this.config.startIndex?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let e=0;e=this.config.numberOutputFlows&&this.config.loop)r=0;else if(r>=this.config.numberOutputFlows&&!this.config.loop)return;if(s=s.filter((e=>e!==r)),0===s.length)for(let e=0;e=0&&(i[e+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every((e=>e))){this.out._activateSignal(e);for(let e=0;e=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}z("FGDebounceBlock",yO);class SO extends KM{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",DM)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}}z("FGFlipFlopBlock",SO);class CO extends KM{constructor(e){super(e),this.config=e,this.outFlows=[];for(let e=0;ethis._onAnimationEnd(t,e)));this.runningAnimatable.setValue(t,e),n.push(t)}e._setExecutionVariable(this,"runningAnimatables",n)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){const i=t._getExecutionVariable(this,"runningAnimatables")??[],s=i.indexOf(e);-1!==s&&i.splice(s,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningAnimatables")??[];for(const e of t)e.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return EO.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}EO.ClassName="FGPlayAnimationBlock",z(EO.ClassName,EO);class AO extends nO{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",RM)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}z("FGStopAnimationBlock",AO);class PO extends nO{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",RM)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}z("FGPauseAnimationBlock",PO);class IO extends QM{constructor(e){super(e),this.condition=this.registerDataInput("condition",DM),this.trueValue=this.registerDataInput("trueValue",RM),this.falseValue=this.registerDataInput("falseValue",RM),this.output=this.registerDataOutput("output",RM)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}z("FGConditionalDataBlock",IO);class RO extends QM{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,RM)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return RO.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}RO.ClassName="FGGetVariableBlock",z(RO.ClassName,RO);class MO extends QM{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",RM),this.destinationSystem=this.registerDataInput("destinationSystem",RM),this.inputCoordinates=this.registerDataInput("inputCoordinates",NM),this.outputCoordinates=this.registerDataOutput("outputCoordinates",NM)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),s=this.inputCoordinates.getValue(e),r=t.getWorldMatrix(),n=i.getWorldMatrix(),o=ve.Matrix[0].copyFrom(n);o.invert();const a=ve.Matrix[1];o.multiplyToRef(r,a);const l=this.outputCoordinates.getValue(e);_e.TransformCoordinatesToRef(s,a,l)}getClassName(){return"FGCoordinateTransformBlock"}}z("FGCoordinateTransformBlock",MO);class OO extends QM{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",GM(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=XM){super.serialize(e),t("value",this.config.value,e.config)}}z("FGConstantBlock",OO);class DO extends QM{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",RM),this.templateComponent=new hO(e.path,this)}_updateOutputs(e){const t=this.templateComponent.getAccessor(this.config.pathConverter,e),i=t.info.get(t.object);this.value.setValue(i,e)}getClassName(){return DO.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}DO.ClassName="FGGetPropertyBlock",z(DO.ClassName,DO);const wO="cachedOperationValue",NO="cachedExecutionId";class FO extends QM{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,NO),i=e._getExecutionVariable(this,wO);if(void 0!==i&&t===e.executionId)this.value.setValue(i,e);else{const t=this._doOperation(e);e._setExecutionVariable(this,wO,t),e._setExecutionVariable(this,NO,e.executionId),this.value.setValue(t,e)}}}class LO extends FO{constructor(e,t,i,s,r,n){super(i,n),this._operation=s,this._className=r,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e))}getClassName(){return this._className}}class BO extends FO{constructor(e,t,i,s,r){super(t,r),this._operation=i,this._className=s,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}const kO="FGLogic",VO="AndBlock",UO="OrBlock",GO="NotBlock";class zO extends LO{constructor(e){super(DM,DM,DM,((e,t)=>e&&t),`${kO}${VO}`,e)}}z(`${kO}${VO}`,zO);class WO extends LO{constructor(e){super(DM,DM,DM,((e,t)=>e||t),`${kO}${UO}`,e)}}z(`${kO}${UO}`,WO);class HO extends BO{constructor(e){super(DM,DM,(e=>!e),`${kO}${GO}`,e)}}z(`${kO}${GO}`,HO);class XO extends FO{constructor(e,t,i,s){super(e,s),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class YO extends FO{constructor(e,t,i,s,r,n,o){super(s,o),this._operation=r,this._className=n,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t),this.c=this.registerDataInput("c",i)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e),this.c.getValue(e))}getClassName(){return this._className}}function QO(e){return e.getClassName?e.getClassName():""}function jO(e,t){return"Vector2"===e&&"Vector2"===t||"Vector3"===e&&"Vector3"===t||"Vector4"===e&&"Vector4"===t}function KO(e,t){return"Matrix"===e&&"Matrix"===t}function $O(e,t){return"FlowGraphInteger"===e&&"FlowGraphInteger"===t}class qO extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicAdd(e,t)),qO.ClassName,e)}_polymorphicAdd(e,t){const i=QO(e),s=QO(t);return jO(i,s)||KO(i,s)||$O(i,s)?e.add(t):e+t}}qO.ClassName="FGAddBlock",z(qO.ClassName,qO);class ZO extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicAdd(e,t)),ZO.ClassName,e)}_polymorphicAdd(e,t){const i=QO(e),s=QO(t);return jO(i,s)||$O(i,s)?e.subtract(t):KO(i,s)?e.add(t.scale(-1)):e-t}}ZO.ClassName="FGSubBlock",z(ZO.ClassName,ZO);class JO extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicMultiply(e,t)),JO.ClassName,e)}_polymorphicMultiply(e,t){const i=QO(e),s=QO(t);return jO(i,s)||$O(i,s)?e.multiply(t):KO(i,s)?me.FromValues(e.m[0]*t.m[0],e.m[4]*t.m[4],e.m[8]*t.m[8],e.m[12]*t.m[12],e.m[1]*t.m[1],e.m[5]*t.m[5],e.m[9]*t.m[9],e.m[13]*t.m[13],e.m[2]*t.m[2],e.m[6]*t.m[6],e.m[10]*t.m[10],e.m[14]*t.m[14],e.m[3]*t.m[3],e.m[7]*t.m[7],e.m[11]*t.m[11],e.m[15]*t.m[15]):e*t}}JO.ClassName="FGMultiplyBlock",z(JO.ClassName,JO);class eD extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicDivide(e,t)),eD.ClassName,e)}_polymorphicDivide(e,t){const i=QO(e),s=QO(t);return jO(i,s)||$O(i,s)?e.divide(t):KO(i,s)?me.FromValues(e.m[0]/t.m[0],e.m[4]/t.m[4],e.m[8]/t.m[8],e.m[12]/t.m[12],e.m[1]/t.m[1],e.m[5]/t.m[5],e.m[9]/t.m[9],e.m[13]/t.m[13],e.m[2]/t.m[2],e.m[6]/t.m[6],e.m[10]/t.m[10],e.m[14]/t.m[14],e.m[3]/t.m[3],e.m[7]/t.m[7],e.m[11]/t.m[11],e.m[15]/t.m[15]):e/t}}eD.ClassName="FGDivideBlock",z(eD.ClassName,eD);class tD extends XO{constructor(e){super(OM,(()=>Math.random()),tD.ClassName,e)}}tD.ClassName="FGRandomBlock",z(tD.ClassName,tD);class iD extends LO{constructor(e){super(RM,RM,OM,((e,t)=>this._polymorphicDot(e,t)),iD.ClassName,e)}_polymorphicDot(e,t){switch(QO(e)){case"Vector2":return de.Dot(e,t);case"Vector3":return _e.Dot(e,t);case"Vector4":return pe.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}iD.ClassName="FGDotBlock",z(iD.ClassName,iD);class sD extends XO{constructor(e){super(OM,(()=>Math.E),sD.ClassName,e)}}sD.ClassName="FGEBlock",z(sD.ClassName,sD);class rD extends XO{constructor(e){super(OM,(()=>Math.PI),rD.ClassName,e)}}rD.ClassName="FGPIBlock",z(rD.ClassName,rD);class nD extends XO{constructor(e){super(OM,(()=>Number.POSITIVE_INFINITY),nD.ClassName,e)}}nD.ClassName="FGInfBlock",z(nD.ClassName,nD);class oD extends XO{constructor(e){super(OM,(()=>Number.NaN),oD.ClassName,e)}}function aD(e,t){switch(QO(e)){case"FlowGraphInteger":return new PM(t(e.value));case"Vector2":return new de(t(e.x),t(e.y));case"Vector3":return new _e(t(e.x),t(e.y),t(e.z));case"Vector4":return new pe(t(e.x),t(e.y),t(e.z),t(e.w));case"Matrix":return me.FromValues(t(e.m[0]),t(e.m[4]),t(e.m[8]),t(e.m[12]),t(e.m[1]),t(e.m[5]),t(e.m[9]),t(e.m[13]),t(e.m[2]),t(e.m[6]),t(e.m[10]),t(e.m[14]),t(e.m[3]),t(e.m[7]),t(e.m[11]),t(e.m[15]));default:return t(e)}}oD.ClassName="FGNaNBlock",z(oD.ClassName,oD);class lD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicAbs(e)),lD.ClassName,e)}_polymorphicAbs(e){return aD(e,Math.abs)}}lD.ClassName="FGAbsBlock",z(lD.ClassName,lD);class hD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicSign(e)),hD.ClassName,e)}_polymorphicSign(e){return aD(e,Math.sign)}}hD.ClassName="FGSignBlock",z(hD.ClassName,hD);class cD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicTrunc(e)),cD.ClassName,e)}_polymorphicTrunc(e){return aD(e,Math.trunc)}}cD.ClassName="FGTruncBlock",z(cD.ClassName,cD);class uD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicFloor(e)),uD.ClassName,e)}_polymorphicFloor(e){return aD(e,Math.floor)}}uD.ClassName="FGFloorBlock",z(uD.ClassName,uD);class dD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicCeiling(e)),dD.ClassName,e)}_polymorphicCeiling(e){return aD(e,Math.ceil)}}dD.ClassName="FGCeilBlock",z(dD.ClassName,dD);class _D extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicFract(e)),_D.ClassName,e)}_polymorphicFract(e){return aD(e,(e=>e-Math.floor(e)))}}_D.ClassName="FGFractBlock",z(_D.ClassName,_D);class pD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicNeg(e)),pD.ClassName,e)}_polymorphicNeg(e){return aD(e,(e=>-e))}}function fD(e,t,i){switch(QO(e)){case"FlowGraphInteger":return new PM(i(e.value,t.value));case"Vector2":return new de(i(e.x,t.x),i(e.y,t.y));case"Vector3":return new _e(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z));case"Vector4":return new pe(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z),i(e.w,t.w));case"Matrix":return me.FromValues(i(e.m[0],t.m[0]),i(e.m[4],t.m[4]),i(e.m[8],t.m[8]),i(e.m[12],t.m[12]),i(e.m[1],t.m[1]),i(e.m[5],t.m[5]),i(e.m[9],t.m[9]),i(e.m[13],t.m[13]),i(e.m[2],t.m[2]),i(e.m[6],t.m[6]),i(e.m[10],t.m[10]),i(e.m[14],t.m[14]),i(e.m[3],t.m[3]),i(e.m[7],t.m[7]),i(e.m[11],t.m[11]),i(e.m[15],t.m[15]));default:return i(e,t)}}pD.ClassName="FGNegBlock",z(pD.ClassName,pD);class mD extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicRemainder(e,t)),mD.ClassName,e)}_polymorphicRemainder(e,t){return fD(e,t,((e,t)=>e%t))}}mD.ClassName="FGRemainderBlock",z(mD.ClassName,mD);class gD extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicMin(e,t)),gD.ClassName,e)}_polymorphicMin(e,t){return fD(e,t,Math.min)}}gD.ClassName="FGMinBlock",z(gD.ClassName,gD);class vD extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicMax(e,t)),vD.ClassName,e)}_polymorphicMax(e,t){return fD(e,t,Math.max)}}function xD(e,t,i){return Math.min(Math.max(e,Math.min(t,i)),Math.max(t,i))}function bD(e,t,i,s){switch(QO(e)){case"FlowGraphInteger":return new PM(s(e.value,t.value,i.value));case"Vector2":return new de(s(e.x,t.x,i.x),s(e.y,t.y,i.y));case"Vector3":return new _e(s(e.x,t.x,i.x),s(e.y,t.y,i.y),s(e.z,t.z,i.z));case"Vector4":return new pe(s(e.x,t.x,i.x),s(e.y,t.y,i.y),s(e.z,t.z,i.z),s(e.w,t.w,i.w));case"Matrix":return me.FromValues(s(e.m[0],t.m[0],i.m[0]),s(e.m[4],t.m[4],i.m[4]),s(e.m[8],t.m[8],i.m[8]),s(e.m[12],t.m[12],i.m[12]),s(e.m[1],t.m[1],i.m[1]),s(e.m[5],t.m[5],i.m[5]),s(e.m[9],t.m[9],i.m[9]),s(e.m[13],t.m[13],i.m[13]),s(e.m[2],t.m[2],i.m[2]),s(e.m[6],t.m[6],i.m[6]),s(e.m[10],t.m[10],i.m[10]),s(e.m[14],t.m[14],i.m[14]),s(e.m[3],t.m[3],i.m[3]),s(e.m[7],t.m[7],i.m[7]),s(e.m[11],t.m[11],i.m[11]),s(e.m[15],t.m[15],i.m[15]));default:return s(e,t,i)}}vD.ClassName="FGMaxBlock",z(vD.ClassName,vD);class TD extends YO{constructor(e){super(RM,RM,RM,RM,((e,t,i)=>this._polymorphicClamp(e,t,i)),TD.ClassName,e)}_polymorphicClamp(e,t,i){return bD(e,t,i,xD)}}function yD(e){return Math.min(Math.max(e,0),1)}TD.ClassName="FGClampBlock",z(TD.ClassName,TD);class SD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicSaturate(e)),SD.ClassName,e)}_polymorphicSaturate(e){return aD(e,yD)}}SD.ClassName="FGSaturateBlock",z(SD.ClassName,SD);class CD extends YO{constructor(e){super(RM,RM,RM,RM,((e,t,i)=>this._polymorphicInterpolate(e,t,i)),CD.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return bD(e,t,i,this._interpolate)}}CD.ClassName="FGInterpolateBlock",z(CD.ClassName,CD);class ED extends LO{constructor(e){super(RM,RM,DM,((e,t)=>this._polymorphicEq(e,t)),ED.ClassName,e)}_polymorphicEq(e,t){const i=QO(e),s=QO(t);return jO(i,s)||KO(i,s)||$O(i,s)?e.equals(t):e===t}}function AD(e,t,i){const s=QO(e);if(s===QO(t)){if(""===s)return i(e,t);if("FlowGraphInteger"===s)return i(e.value,t.value);throw new Error(`Cannot compare ${e} and ${t}`)}throw new Error(`${e} and ${t} are of different types.`)}ED.ClassName="FGEqBlock",z(ED.ClassName,ED);class PD extends LO{constructor(e){super(RM,RM,DM,((e,t)=>this._polymorphicLessThan(e,t)),PD.ClassName,e)}_polymorphicLessThan(e,t){return AD(e,t,((e,t)=>ethis._polymorphicLessThanOrEqual(e,t)),ID.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return AD(e,t,((e,t)=>e<=t))}}ID.ClassName="FGLessThanOrEqualBlock";class RD extends LO{constructor(e){super(RM,RM,DM,((e,t)=>this._polymorphicGreaterThan(e,t)),RD.ClassName,e)}_polymorphicGreaterThan(e,t){return AD(e,t,((e,t)=>e>t))}}RD.ClassName="FGGreaterThanBlock",z(RD.ClassName,RD);class MD extends LO{constructor(e){super(RM,RM,DM,((e,t)=>this._polymorphicGreaterThanOrEqual(e,t)),MD.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return AD(e,t,((e,t)=>e>=t))}}MD.ClassName="FGGreaterThanOrEqualBlock",z(MD.ClassName,MD);class OD extends BO{constructor(e){super(RM,DM,(e=>this._polymorphicIsNan(e)),OD.ClassName,e)}_polymorphicIsNan(e){const t=QO(e);if(""===t)return isNaN(e);if("FlowGraphInteger"===t)return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}OD.ClassName="FGIsNanBlock",z(OD.ClassName,OD);class DD extends BO{constructor(e){super(RM,DM,(e=>this._polymorphicIsInf(e)),DD.ClassName,e)}_polymorphicIsInf(e){const t=QO(e);if(""===t)return!isFinite(e);if("FlowGraphInteger"===t)return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}DD.ClassName="FGIsInfBlock";class wD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicDegToRad(e)),wD.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return aD(e,this._degToRad)}}wD.ClassName="FGDegToRadBlock",z(wD.ClassName,wD);class ND extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicRadToDeg(e)),ND.ClassName,e)}_radToDeg(e){return 180*e/Math.PI}_polymorphicRadToDeg(e){return aD(e,this._radToDeg)}}ND.ClassName="FGRadToDegBlock",z(ND.ClassName,ND);class FD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicSin(e)),FD.ClassName,e)}_polymorphicSin(e){return aD(e,Math.sin)}}FD.ClassName="FGSinBlock",z(FD.ClassName,FD);class LD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicCos(e)),LD.ClassName,e)}_polymorphicCos(e){return aD(e,Math.cos)}}LD.ClassName="FGCosBlock",z(LD.ClassName,LD);class BD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicTan(e)),BD.ClassName,e)}_polymorphicTan(e){return aD(e,Math.tan)}}BD.ClassName="FGTanBlock",z(BD.ClassName,BD);class kD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicAsin(e)),kD.ClassName,e)}_polymorphicAsin(e){return aD(e,Math.asin)}}kD.ClassName="FGAsinBlock",z(kD.ClassName,kD);class VD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicAcos(e)),VD.ClassName,e)}_polymorphicAcos(e){return aD(e,Math.acos)}}VD.ClassName="FGAcosBlock",z(VD.ClassName,VD);class UD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicAtan(e)),UD.ClassName,e)}_polymorphicAtan(e){return aD(e,Math.atan)}}UD.ClassName="FGAtanBlock",z(UD.ClassName,UD);class GD extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicAtan2(e,t)),GD.ClassName,e)}_polymorphicAtan2(e,t){return fD(e,t,Math.atan2)}}GD.ClassName="FGAtan2Block",z(GD.ClassName,GD);class zD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicSinh(e)),zD.ClassName,e)}_polymorphicSinh(e){return aD(e,Math.sinh)}}zD.ClassName="FGSinhBlock",z(zD.ClassName,zD);class WD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicCosh(e)),WD.ClassName,e)}_polymorphicCosh(e){return aD(e,Math.cosh)}}WD.ClassName="FGCoshBlock",z(WD.ClassName,WD);class HD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicTanh(e)),HD.ClassName,e)}_polymorphicTanh(e){return aD(e,Math.tanh)}}HD.ClassName="FGTanhBlock",z(HD.ClassName,HD);class XD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicAsinh(e)),XD.ClassName,e)}_polymorphicAsinh(e){return aD(e,Math.asinh)}}XD.ClassName="FGAsinhBlock",z(XD.ClassName,XD);class YD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicAcosh(e)),YD.ClassName,e)}_polymorphicAcosh(e){return aD(e,Math.acosh)}}YD.ClassName="FGAcoshBlock",z(YD.ClassName,YD);class QD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicAtanh(e)),QD.ClassName,e)}_polymorphicAtanh(e){return aD(e,Math.atanh)}}QD.ClassName="FGAtanhBlock",z(QD.ClassName,QD);class jD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicExp(e)),jD.ClassName,e)}_polymorphicExp(e){return aD(e,Math.exp)}}jD.ClassName="FGExpBlock",z(jD.ClassName,jD);class KD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicLog(e)),KD.ClassName,e)}_polymorphicLog(e){return aD(e,Math.log)}}KD.ClassName="FGLogBlock",z(KD.ClassName,KD);class $D extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicLog2(e)),$D.ClassName,e)}_polymorphicLog2(e){return aD(e,Math.log2)}}$D.ClassName="FGLog2Block",z($D.ClassName,$D);class qD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicLog10(e)),qD.ClassName,e)}_polymorphicLog10(e){return aD(e,Math.log10)}}qD.ClassName="FGLog10Block",z(qD.ClassName,qD);class ZD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicSqrt(e)),ZD.ClassName,e)}_polymorphicSqrt(e){return aD(e,Math.sqrt)}}ZD.ClassName="FGSqrtBlock",z(ZD.ClassName,ZD);class JD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicCubeRoot(e)),JD.ClassName,e)}_polymorphicCubeRoot(e){return aD(e,Math.cbrt)}}JD.ClassName="FGCubeRootBlock",z(JD.ClassName,JD);class ew extends LO{constructor(e){super(RM,OM,OM,((e,t)=>this._polymorphicPow(e,t)),ew.ClassName,e)}_polymorphicPow(e,t){return fD(e,t,Math.pow)}}ew.ClassName="FGPowBlock",z(ew.ClassName,ew);class tw extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicLength(e)),tw.ClassName,e)}_polymorphicLength(e){switch(QO(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}tw.ClassName="FGLengthBlock",z(tw.ClassName,tw);class iw extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicNormalize(e)),iw.ClassName,e)}_polymorphicNormalize(e){switch(QO(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}iw.ClassName="FGNormalizeBlock",z(iw.ClassName,iw);class sw extends LO{constructor(e){super(NM,NM,NM,((e,t)=>_e.Cross(e,t)),sw.ClassName,e)}}sw.ClassName="FGCrossBlock",z(sw.ClassName,sw);class rw extends LO{constructor(e){super(wM,OM,wM,((e,t)=>de.Transform(e,me.RotationZ(t))),rw.ClassName,e)}}rw.ClassName="FGRotate2DBlock",z(rw.ClassName,rw);class nw extends YO{constructor(e){super(NM,NM,OM,NM,((e,t,i)=>_e.TransformCoordinates(e,me.RotationAxis(t,i))),nw.ClassName,e)}}nw.ClassName="FGRotate3DBlock",z(nw.ClassName,nw);class ow extends BO{constructor(e){super(LM,LM,(e=>me.Transpose(e)),ow.ClassName,e)}}ow.ClassName="FGTransposeBlock",z(ow.ClassName,ow);class aw extends BO{constructor(e){super(LM,OM,(e=>e.determinant()),aw.ClassName,e)}}aw.ClassName="FGDeterminantBlock",z(aw.ClassName,aw);class lw extends BO{constructor(e){super(LM,LM,(e=>me.Invert(e)),lw.ClassName,e)}}lw.ClassName="FGInvertMatrixBlock",z(lw.ClassName,lw);class hw extends LO{constructor(e){super(LM,LM,LM,((e,t)=>t.multiply(e)),hw.ClassName,e)}}hw.ClassName="FGMatMulBlock",z(hw.ClassName,hw);class cw extends BO{constructor(e){super(UM,UM,(e=>new PM(~e.value)),cw.ClassName,e)}}cw.ClassName="FGBitwiseNotBlock",z(cw.ClassName,cw);class uw extends LO{constructor(e){super(UM,UM,UM,((e,t)=>new PM(e.value&t.value)),uw.ClassName,e)}}uw.ClassName="FGBitwiseAndBlock",z(uw.ClassName,uw);class dw extends LO{constructor(e){super(UM,UM,UM,((e,t)=>new PM(e.value|t.value)),dw.ClassName,e)}}dw.ClassName="FGBitwiseOrBlock",z(dw.ClassName,dw);class _w extends LO{constructor(e){super(UM,UM,UM,((e,t)=>new PM(e.value^t.value)),_w.ClassName,e)}}_w.ClassName="FGBitwiseXorBlock",z(_w.ClassName,_w);class pw extends LO{constructor(e){super(UM,UM,UM,((e,t)=>new PM(e.value<new PM(e.value>>t.value)),fw.ClassName,e)}}fw.ClassName="FGBitwiseRightShiftBlock",z(fw.ClassName,fw);class mw extends BO{constructor(e){super(UM,UM,(e=>new PM(Math.clz32(e.value))),mw.ClassName,e)}}mw.ClassName="FGCountLeadingZerosBlock",z(mw.ClassName,mw);class gw extends BO{constructor(e){super(UM,UM,(e=>new PM(e.value?31-Math.clz32(e.value&-e.value):32)),gw.ClassName,e)}}gw.ClassName="FGCountTrailingZerosBlock",z(gw.ClassName,gw);class vw extends BO{constructor(e){super(UM,UM,(e=>new PM(function(e){let t=0;for(;e;)t+=1&e,e>>=1;return t}(e.value))),vw.ClassName,e)}}vw.ClassName="FGCountOneBitsBlock",z(vw.ClassName,vw);class xw extends qM{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const t=e.configuration.scene.onReadyObservable.add((()=>{this._execute(e)}));e._setExecutionVariable(this,"sceneReadyObserver",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return xw.ClassName}}xw.ClassName="FGSceneReadyEventBlock",z("FGSceneReadyEventBlock",xw);class bw extends qM{constructor(e){super(e),this.config=e;for(let e=0;e{for(let i=0;i{this._execute(e)}));e._setExecutionVariable(this,"sceneBeforeRender",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return Tw.ClassName}}Tw.ClassName="FGSceneTickEventBlock",z(Tw.ClassName,Tw);class yw{constructor(e,t=yw.UNITMODE_PIXEL,i=!0){this.negativeValueAllowed=i,this._value=1,this._unit=yw.UNITMODE_PIXEL,this.ignoreAdaptiveScaling=!1,this.onChangedObservable=new K,this._value=e,this._unit=t,this._originalUnit=t}get isPercentage(){return this._unit===yw.UNITMODE_PERCENTAGE}get isPixel(){return this._unit===yw.UNITMODE_PIXEL}get internalValue(){return this._value}get value(){return this._value}set value(e){e!==this._value&&(this._value=e,this.onChangedObservable.notifyObservers())}get unit(){return this._unit}set unit(e){e!==this._unit&&(this._unit=e,this.onChangedObservable.notifyObservers())}getValueInPixel(e,t){return this.isPixel?this.getValue(e):this.getValue(e)*t}updateInPlace(e,t=yw.UNITMODE_PIXEL){return this.value===e&&this.unit===t||(this._value=e,this._unit=t,this.onChangedObservable.notifyObservers()),this}getValue(e){if(e&&!this.ignoreAdaptiveScaling&&this.unit!==yw.UNITMODE_PERCENTAGE){let t=0,i=0;if(e.idealWidth&&(t=Math.ceil(this._value*e.getSize().width/e.idealWidth)),e.idealHeight&&(i=Math.ceil(this._value*e.getSize().height/e.idealHeight)),e.useSmallestIdeal&&e.idealWidth&&e.idealHeight)return window.innerWidth{this._markAsDirty(),this._resetFontCache()}))),this._markAsDirty(),this._resetFontCache()}get _isFontSizeInPercentage(){return this._fontSize.isPercentage}get fontSizeInPixels(){const e=this._style?this._style._fontSize:this._fontSize;return e.isPixel?e.getValue(this._host):e.getValueInPixel(this._host,this._tempParentMeasure.height||this._cachedParentMeasure.height)}set fontSizeInPixels(e){isNaN(e)||(this.fontSize=e+"px")}get fontSize(){return this._fontSize.toString(this._host)}set fontSize(e){this._fontSize.toString(this._host)!==e&&this._fontSize.fromString(e)&&(this._markAsDirty(),this._resetFontCache())}get color(){return this._color}set color(e){this._color!==e&&(this._color=e,this._markAsDirty())}get gradient(){return this._gradient}set gradient(e){this._gradient!==e&&(this._gradient=e,this._markAsDirty())}get zIndex(){return this._zIndex}set zIndex(e){this.zIndex!==e&&(this._zIndex=e,this.parent&&this.parent._reOrderControl(this))}get notRenderable(){return this._doNotRender}set notRenderable(e){this._doNotRender!==e&&(this._doNotRender=e,this._markAsDirty())}get isVisible(){return this._isVisible}set isVisible(e){this._isVisible!==e&&(this._isVisible=e,this._markAsDirty(!0),this.onIsVisibleChangedObservable.notifyObservers(e))}get isDirty(){return this._isDirty}get linkedMesh(){return this._linkedMesh}get descendantsOnlyPadding(){return this._descendantsOnlyPadding}set descendantsOnlyPadding(e){this._descendantsOnlyPadding!==e&&(this._descendantsOnlyPadding=e,this._markAsDirty())}get paddingLeft(){return this._paddingLeft.toString(this._host)}set paddingLeft(e){this._paddingLeft.fromString(e)&&this._markAsDirty()}get paddingLeftInPixels(){return this._paddingLeft.getValueInPixel(this._host,this._cachedParentMeasure.width)}set paddingLeftInPixels(e){isNaN(e)||(this.paddingLeft=e+"px")}get _paddingLeftInPixels(){return this._descendantsOnlyPadding?0:this.paddingLeftInPixels}get paddingRight(){return this._paddingRight.toString(this._host)}set paddingRight(e){this._paddingRight.fromString(e)&&this._markAsDirty()}get paddingRightInPixels(){return this._paddingRight.getValueInPixel(this._host,this._cachedParentMeasure.width)}set paddingRightInPixels(e){isNaN(e)||(this.paddingRight=e+"px")}get _paddingRightInPixels(){return this._descendantsOnlyPadding?0:this.paddingRightInPixels}get paddingTop(){return this._paddingTop.toString(this._host)}set paddingTop(e){this._paddingTop.fromString(e)&&this._markAsDirty()}get paddingTopInPixels(){return this._paddingTop.getValueInPixel(this._host,this._cachedParentMeasure.height)}set paddingTopInPixels(e){isNaN(e)||(this.paddingTop=e+"px")}get _paddingTopInPixels(){return this._descendantsOnlyPadding?0:this.paddingTopInPixels}get paddingBottom(){return this._paddingBottom.toString(this._host)}set paddingBottom(e){this._paddingBottom.fromString(e)&&this._markAsDirty()}get paddingBottomInPixels(){return this._paddingBottom.getValueInPixel(this._host,this._cachedParentMeasure.height)}set paddingBottomInPixels(e){isNaN(e)||(this.paddingBottom=e+"px")}get _paddingBottomInPixels(){return this._descendantsOnlyPadding?0:this.paddingBottomInPixels}get left(){return this._left.toString(this._host)}set left(e){this._left.fromString(e)&&this._markAsDirty()}get leftInPixels(){return this._left.getValueInPixel(this._host,this._cachedParentMeasure.width)}set leftInPixels(e){isNaN(e)||(this.left=e+"px")}get top(){return this._top.toString(this._host)}set top(e){this._top.fromString(e)&&this._markAsDirty()}get topInPixels(){return this._top.getValueInPixel(this._host,this._cachedParentMeasure.height)}set topInPixels(e){isNaN(e)||(this.top=e+"px")}get linkOffsetX(){return this._linkOffsetX.toString(this._host)}set linkOffsetX(e){this._linkOffsetX.fromString(e)&&this._markAsDirty()}get linkOffsetXInPixels(){return this._linkOffsetX.getValueInPixel(this._host,this._cachedParentMeasure.width)}set linkOffsetXInPixels(e){isNaN(e)||(this.linkOffsetX=e+"px")}get linkOffsetY(){return this._linkOffsetY.toString(this._host)}set linkOffsetY(e){this._linkOffsetY.fromString(e)&&this._markAsDirty()}get linkOffsetYInPixels(){return this._linkOffsetY.getValueInPixel(this._host,this._cachedParentMeasure.height)}set linkOffsetYInPixels(e){isNaN(e)||(this.linkOffsetY=e+"px")}get centerX(){return this._currentMeasure.left+this._currentMeasure.width/2}get centerY(){return this._currentMeasure.top+this._currentMeasure.height/2}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled===e)return;this._isEnabled=e,this._markAsDirty();const t=e=>{if(e.host){for(const t in e.host._lastControlOver)e===this.host._lastControlOver[t]&&(e._onPointerOut(e,null,!0),delete e.host._lastControlOver[t]);void 0!==e.children&&e.children.forEach(t)}};t(this),this.onEnabledStateChangedObservable.notifyObservers(e)}get disabledColor(){return this._disabledColor}set disabledColor(e){this._disabledColor!==e&&(this._disabledColor=e,this._markAsDirty())}get disabledColorItem(){return this._disabledColorItem}set disabledColorItem(e){this._disabledColorItem!==e&&(this._disabledColorItem=e,this._markAsDirty())}constructor(e){this.name=e,this._alpha=1,this._alphaSet=!1,this._zIndex=0,this._currentMeasure=Pw.Empty(),this._tempPaddingMeasure=Pw.Empty(),this._fontFamily="",this._fontStyle="",this._fontWeight="",this._fontSize=new yw(18,yw.UNITMODE_PIXEL,!1),this._width=new yw(1,yw.UNITMODE_PERCENTAGE,!1),this._height=new yw(1,yw.UNITMODE_PERCENTAGE,!1),this._color="",this._style=null,this._horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_CENTER,this._verticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,this._isDirty=!0,this._wasDirty=!1,this._tempParentMeasure=Pw.Empty(),this._prevCurrentMeasureTransformedIntoGlobalSpace=Pw.Empty(),this._cachedParentMeasure=Pw.Empty(),this._descendantsOnlyPadding=!1,this._paddingLeft=new yw(0),this._paddingRight=new yw(0),this._paddingTop=new yw(0),this._paddingBottom=new yw(0),this._left=new yw(0),this._top=new yw(0),this._scaleX=1,this._scaleY=1,this._rotation=0,this._transformCenterX=.5,this._transformCenterY=.5,this._transformMatrix=Rw.Identity(),this._invertTransformMatrix=Rw.Identity(),this._transformedPosition=de.Zero(),this._isMatrixDirty=!0,this._isVisible=!0,this._isHighlighted=!1,this._highlightColor="#4affff",this._highlightLineWidth=2,this._fontSet=!1,this._dummyVector2=de.Zero(),this._downCount=0,this._enterCount=-1,this._doNotRender=!1,this._downPointerIds={},this._evaluatedMeasure=new Pw(0,0,0,0),this._evaluatedParentMeasure=new Pw(0,0,0,0),this._isEnabled=!0,this._disabledColor="#9a9a9a",this._disabledColorItem="#6a6a6a",this._isReadOnly=!1,this._gradient=null,this._rebuildLayout=!1,this.onEnabledStateChangedObservable=new K,this._customData={},this._isClipped=!1,this._automaticSize=!1,this.metadata=null,this.isHitTestVisible=!0,this.isPointerBlocker=!1,this.isFocusInvisible=!1,this._clipChildren=!0,this._clipContent=!0,this.useBitmapCache=!1,this._shadowOffsetX=0,this._shadowOffsetY=0,this._shadowBlur=0,this._previousShadowBlur=0,this._shadowColor="black",this.hoverCursor="",this._linkOffsetX=new yw(0),this._linkOffsetY=new yw(0),this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new K,this.onWheelObservable=new K,this.onPointerMoveObservable=new K,this.onPointerOutObservable=new K,this.onPointerDownObservable=new K,this.onPointerUpObservable=new K,this.onPointerClickObservable=new K,this.onPointerEnterObservable=new K,this.onDirtyObservable=new K,this.onBeforeDrawObservable=new K,this.onAfterDrawObservable=new K,this.onDisposeObservable=new K,this.onIsVisibleChangedObservable=new K,this.isSerializable=!0,this._fixedRatio=0,this._fixedRatioMasterIsWidth=!0,this.animations=null,this._tmpMeasureA=new Pw(0,0,0,0)}_getTypeName(){return"Control"}getAscendantOfClass(e){return this.parent?this.parent.getClassName()===e?this.parent:this.parent.getAscendantOfClass(e):null}markAsDirty(e=!1){this._markAsDirty(e)}markAllAsDirty(){this._markAllAsDirty()}_resetFontCache(){this._fontSet=!0,this._markAsDirty()}isAscendant(e){return!!this.parent&&(this.parent===e||this.parent.isAscendant(e))}getLocalCoordinates(e){const t=de.Zero();return this.getLocalCoordinatesToRef(e,t),t}getLocalCoordinatesToRef(e,t){return t.x=e.x-this._currentMeasure.left,t.y=e.y-this._currentMeasure.top,this}getParentLocalCoordinates(e){const t=de.Zero();return t.x=e.x-this._cachedParentMeasure.left,t.y=e.y-this._cachedParentMeasure.top,t}moveToVector3(e,t){if(!this._host||this.parent!==this._host._rootContainer)return void Ds.Error("Cannot move a control to a vector3 if the control is not at root level");this.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP;const i=this._host._getGlobalViewport(),s=_e.Project(e,me.IdentityReadOnly,t.getTransformMatrix(),i);this._moveToProjectedPosition(s),s.z<0||s.z>1?this.notRenderable=!0:this.notRenderable=!1}getDescendantsToRef(e,t=!1,i){}getDescendants(e,t){const i=[];return this.getDescendantsToRef(i,e,t),i}linkWithMesh(e){if(!this._host||this.parent&&this.parent!==this._host._rootContainer)return void(e&&Ds.Error("Cannot link a control to a mesh if the control is not at root level"));const t=this._host._linkedControls.indexOf(this);if(-1!==t)return this._linkedMesh=e,void(e||this._host._linkedControls.splice(t,1));e&&(this.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,this._linkedMesh=e,this._host._linkedControls.push(this))}setPadding(e,t,i,s){const r=e,n=t??r,o=i??r,a=s??n;this.paddingTop=r,this.paddingRight=n,this.paddingBottom=o,this.paddingLeft=a}setPaddingInPixels(e,t,i,s){const r=e,n=t??r,o=i??r,a=s??n;this.paddingTopInPixels=r,this.paddingRightInPixels=n,this.paddingBottomInPixels=o,this.paddingLeftInPixels=a}_moveToProjectedPosition(e){const t=this._left.getValue(this._host),i=this._top.getValue(this._host),s=this.parent?._currentMeasure;s&&this._processMeasures(s,this._host.getContext());let r=e.x+this._linkOffsetX.getValue(this._host)-this._currentMeasure.width/2,n=e.y+this._linkOffsetY.getValue(this._host)-this._currentMeasure.height/2;const o=this._left.ignoreAdaptiveScaling&&this._top.ignoreAdaptiveScaling;o&&(Math.abs(r-t)<.5&&(r=t),Math.abs(n-i)<.5&&(n=i)),(o||t!==r||i!==n)&&(this.left=r+"px",this.top=n+"px",this._left.ignoreAdaptiveScaling=!0,this._top.ignoreAdaptiveScaling=!0,this._markAsDirty())}_offsetLeft(e){this._isDirty=!0,this._currentMeasure.left+=e}_offsetTop(e){this._isDirty=!0,this._currentMeasure.top+=e}_markMatrixAsDirty(){this._isMatrixDirty=!0,this._flagDescendantsAsMatrixDirty()}_flagDescendantsAsMatrixDirty(){}_intersectsRect(e,t){return this._transform(t),!(this._evaluatedMeasure.left>=e.left+e.width||this._evaluatedMeasure.top>=e.top+e.height||this._evaluatedMeasure.left+this._evaluatedMeasure.width<=e.left||this._evaluatedMeasure.top+this._evaluatedMeasure.height<=e.top)}_computeAdditionalOffsetX(){return 0}_computeAdditionalOffsetY(){return 0}invalidateRect(){if(this._transform(),this.host&&this.host.useInvalidateRectOptimization){this._currentMeasure.transformToRef(this._transformMatrix,this._tmpMeasureA),Pw.CombineToRef(this._tmpMeasureA,this._prevCurrentMeasureTransformedIntoGlobalSpace,this._tmpMeasureA);const e=this.shadowOffsetX,t=this.shadowOffsetY,i=Math.max(this._previousShadowBlur,this.shadowBlur),s=Math.min(Math.min(e,0)-2*i,0),r=Math.max(Math.max(e,0)+2*i,0),n=Math.min(Math.min(t,0)-2*i,0),o=Math.max(Math.max(t,0)+2*i,0),a=this._computeAdditionalOffsetX(),l=this._computeAdditionalOffsetY();this.host.invalidateRect(Math.floor(this._tmpMeasureA.left+s-a),Math.floor(this._tmpMeasureA.top+n-l),Math.ceil(this._tmpMeasureA.left+this._tmpMeasureA.width+r+a),Math.ceil(this._tmpMeasureA.top+this._tmpMeasureA.height+o+l))}}_markAsDirty(e=!1){(this._isVisible||e)&&(this._isDirty=!0,this._markMatrixAsDirty(),this._host&&this._host.markAsDirty())}_markAllAsDirty(){this._markAsDirty(),this._font&&this._prepareFont()}_link(e){this._host=e,this._host&&(this.uniqueId=this._host.getScene().getUniqueId())}_transform(e){if(!this._isMatrixDirty&&1===this._scaleX&&1===this._scaleY&&0===this._rotation)return;const t=this._currentMeasure.width*this._transformCenterX+this._currentMeasure.left,i=this._currentMeasure.height*this._transformCenterY+this._currentMeasure.top;e&&(e.translate(t,i),e.rotate(this._rotation),e.scale(this._scaleX,this._scaleY),e.translate(-t,-i)),(this._isMatrixDirty||this._cachedOffsetX!==t||this._cachedOffsetY!==i)&&(this._cachedOffsetX=t,this._cachedOffsetY=i,this._isMatrixDirty=!1,this._flagDescendantsAsMatrixDirty(),Rw.ComposeToRef(-t,-i,this._rotation,this._scaleX,this._scaleY,this.parent?this.parent._transformMatrix:null,this._transformMatrix),this._transformMatrix.invertToRef(this._invertTransformMatrix),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure))}_renderHighlight(e){this.isHighlighted&&(e.save(),e.strokeStyle=this._highlightColor,e.lineWidth=this._highlightLineWidth,this._renderHighlightSpecific(e),e.restore())}_renderHighlightSpecific(e){e.strokeRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)}_getColor(e){return this.gradient?this.gradient.getCanvasGradient(e):this.color}_applyStates(e){this._isFontSizeInPercentage&&(this._fontSet=!0),this._host&&this._host.useSmallestIdeal&&!this._font&&(this._fontSet=!0),this._fontSet&&(this._prepareFont(),this._fontSet=!1),this._font&&(e.font=this._font),(this._color||this.gradient)&&(e.fillStyle=this._getColor(e)),Ow.AllowAlphaInheritance?e.globalAlpha*=this._alpha:this._alphaSet&&(e.globalAlpha=this.parent&&!this.parent.renderToIntermediateTexture?this.parent.alpha*this._alpha:this._alpha)}_layout(e,t){if(!this.isDirty&&(!this.isVisible||this.notRenderable))return!1;if(this._isDirty||!this._cachedParentMeasure.isEqualsTo(e)){this.host._numLayoutCalls++,this._currentMeasure.addAndTransformToRef(this._transformMatrix,0|-this._paddingLeftInPixels,0|-this._paddingTopInPixels,0|this._paddingRightInPixels,0|this._paddingBottomInPixels,this._prevCurrentMeasureTransformedIntoGlobalSpace),t.save(),this._applyStates(t);let i=0;do{this._rebuildLayout=!1,this._processMeasures(e,t),i++}while(this._rebuildLayout&&i<3);i>=3&&Ne.Error(`Layout cycle detected in GUI (Control name=${this.name}, uniqueId=${this.uniqueId})`),t.restore(),this.invalidateRect(),this._evaluateClippingState(e)}return this._wasDirty=this._isDirty,this._isDirty=!1,!0}_processMeasures(e,t){this._tempPaddingMeasure.copyFrom(e),this.parent&&this.parent.descendantsOnlyPadding&&(this._tempPaddingMeasure.left+=this.parent.paddingLeftInPixels,this._tempPaddingMeasure.top+=this.parent.paddingTopInPixels,this._tempPaddingMeasure.width-=this.parent.paddingLeftInPixels+this.parent.paddingRightInPixels,this._tempPaddingMeasure.height-=this.parent.paddingTopInPixels+this.parent.paddingBottomInPixels),this._currentMeasure.copyFrom(this._tempPaddingMeasure),this._preMeasure(this._tempPaddingMeasure,t),this._measure(),this._postMeasure(this._tempPaddingMeasure,t),this._computeAlignment(this._tempPaddingMeasure,t),this._currentMeasure.left=0|this._currentMeasure.left,this._currentMeasure.top=0|this._currentMeasure.top,this._currentMeasure.width=0|this._currentMeasure.width,this._currentMeasure.height=0|this._currentMeasure.height,this._additionalProcessing(this._tempPaddingMeasure,t),this._cachedParentMeasure.copyFrom(this._tempPaddingMeasure),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure),this.onDirtyObservable.hasObservers()&&this.onDirtyObservable.notifyObservers(this)}_evaluateClippingState(e){if(this._transform(),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure),this.parent&&this.parent.clipChildren){if(e.transformToRef(this.parent._transformMatrix,this._evaluatedParentMeasure),this._evaluatedMeasure.left>this._evaluatedParentMeasure.left+this._evaluatedParentMeasure.width)return void(this._isClipped=!0);if(this._evaluatedMeasure.left+this._evaluatedMeasure.widththis._evaluatedParentMeasure.top+this._evaluatedParentMeasure.height)return void(this._isClipped=!0);if(this._evaluatedMeasure.top+this._evaluatedMeasure.heightthis._currentMeasure.left+this._currentMeasure.width||tthis._currentMeasure.top+this._currentMeasure.height||(this.isPointerBlocker&&(this._host._shouldBlockPointer=!0),0))}_processPicking(e,t,i,s,r,n,o,a){return!(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this._doNotRender||!this.contains(e,t)||(this._processObservables(s,e,t,i,r,n,o,a),0))}_onPointerMove(e,t,i,s){this.onPointerMoveObservable.notifyObservers(t,-1,e,this,s)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerMove(e,t,i,s)}_onPointerEnter(e,t){return!!this._isEnabled&&(!(this._enterCount>0)&&(-1===this._enterCount&&(this._enterCount=0),this._enterCount++,this.onPointerEnterObservable.notifyObservers(this,-1,e,this,t)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerEnter(e,t),!0))}_onPointerOut(e,t,i=!1){if(!(i||this._isEnabled&&e!==this))return;this._enterCount=0;let s=!0;e.isAscendant(this)||(s=this.onPointerOutObservable.notifyObservers(this,-1,e,this,t)),s&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerOut(e,t,i)}_onPointerDown(e,t,i,s,r){return this._onPointerEnter(this,r),0===this._downCount&&(this._downCount++,this._downPointerIds[i]=!0,this.onPointerDownObservable.notifyObservers(new Iw(t,s),-1,e,this,r)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerDown(e,t,i,s,r),r&&this.uniqueId!==this._host.rootContainer.uniqueId&&this._host._capturedPointerIds.add(r.event.pointerId),!0)}_onPointerUp(e,t,i,s,r,n){if(!this._isEnabled)return;this._downCount=0,delete this._downPointerIds[i];let o=r;r&&(this._enterCount>0||-1===this._enterCount)&&(o=this.onPointerClickObservable.notifyObservers(new Iw(t,s),-1,e,this,n)),this.onPointerUpObservable.notifyObservers(new Iw(t,s),-1,e,this,n)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerUp(e,t,i,s,o,n),n&&this.uniqueId!==this._host.rootContainer.uniqueId&&this._host._capturedPointerIds.delete(n.event.pointerId)}_forcePointerUp(e=null){if(null!==e)this._onPointerUp(this,de.Zero(),e,0,!0);else for(const e in this._downPointerIds)this._onPointerUp(this,de.Zero(),+e,0,!0)}_onWheelScroll(e,t){this._isEnabled&&this.onWheelObservable.notifyObservers(new de(e,t))&&null!=this.parent&&this.parent._onWheelScroll(e,t)}_onCanvasBlur(){}_processObservables(e,t,i,s,r,n,o,a){if(!this._isEnabled)return!1;if(this._dummyVector2.copyFromFloats(t,i),e===lr.POINTERMOVE){this._onPointerMove(this,this._dummyVector2,r,s);const e=this._host._lastControlOver[r];return e&&e!==this&&e._onPointerOut(this,s),e!==this&&this._onPointerEnter(this,s),this._host._lastControlOver[r]=this,!0}return e===lr.POINTERDOWN?(this._onPointerDown(this,this._dummyVector2,r,n,s),this._host._registerLastControlDown(this,r),this._host._lastPickedControl=this,!0):e===lr.POINTERUP?(this._host._lastControlDown[r]&&this._host._lastControlDown[r]._onPointerUp(this,this._dummyVector2,r,n,!0,s),delete this._host._lastControlDown[r],!0):!(e!==lr.POINTERWHEEL||!this._host._lastControlOver[r]||(this._host._lastControlOver[r]._onWheelScroll(o,a),0))}_getStyleProperty(e,t){const i=(this._style&&this._style[e])??this[e];return!i&&this.parent?this.parent._getStyleProperty(e,t):this.parent?i:t}_prepareFont(){(this._font||this._fontSet)&&(this._font=this._getStyleProperty("fontStyle","")+" "+this._getStyleProperty("fontWeight","")+" "+this.fontSizeInPixels+"px "+this._getStyleProperty("fontFamily","Arial"),this._fontOffset=Ow._GetFontOffset(this._font,this._host?.getScene()?.getEngine()),this.getDescendants().forEach((e=>e._markAllAsDirty())))}isDimensionFullyDefined(e){return this.getDimension(e).isPixel}getDimension(e){return"width"===e?this._width:this._height}clone(e){const t={};this.serialize(t,!0);const i=new(Ds.Instantiate("BABYLON.GUI."+t.className));return i.parse(t,e),i}parse(e,t,i){return this._urlRewriter=i,St.Parse((()=>this),e,null),this.name=e.name,this._parseFromContent(e,t??this._host),this}serialize(e,t=!1,i=!0){(this.isSerializable||t)&&(St.Serialize(this,e),e.name=this.name,e.className=this.getClassName(),i&&this._prepareFont(),this._fontFamily&&(e.fontFamily=this._fontFamily),this.fontSize&&(e.fontSize=this.fontSize),this.fontWeight&&(e.fontWeight=this.fontWeight),this.fontStyle&&(e.fontStyle=this.fontStyle),this._gradient&&(e.gradient={},this._gradient.serialize(e.gradient)),St.AppendSerializedAnimations(this,e))}_parseFromContent(e,t,i){if(e.fontFamily&&(this.fontFamily=e.fontFamily),e.fontSize&&(this.fontSize=e.fontSize),e.fontWeight&&(this.fontWeight=e.fontWeight),e.fontStyle&&(this.fontStyle=e.fontStyle),e.gradient){const t=Ds.Instantiate("BABYLON.GUI."+e.gradient.className);this._gradient=new t,this._gradient?.parse(e.gradient)}if(e.animations){this.animations=[];for(let t=0;t-1&&this.linkWithMesh(null),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}static get HORIZONTAL_ALIGNMENT_LEFT(){return Ow._HORIZONTAL_ALIGNMENT_LEFT}static get HORIZONTAL_ALIGNMENT_RIGHT(){return Ow._HORIZONTAL_ALIGNMENT_RIGHT}static get HORIZONTAL_ALIGNMENT_CENTER(){return Ow._HORIZONTAL_ALIGNMENT_CENTER}static get VERTICAL_ALIGNMENT_TOP(){return Ow._VERTICAL_ALIGNMENT_TOP}static get VERTICAL_ALIGNMENT_BOTTOM(){return Ow._VERTICAL_ALIGNMENT_BOTTOM}static get VERTICAL_ALIGNMENT_CENTER(){return Ow._VERTICAL_ALIGNMENT_CENTER}static _GetFontOffset(e,t){if(Ow._FontHeightSizes[e])return Ow._FontHeightSizes[e];const i=t||re.LastCreatedEngine;if(!i)throw new Error("Invalid engine. Unable to create a canvas.");const s=i.getFontOffset(e);return Ow._FontHeightSizes[e]=s,s}static Parse(e,t,i){const s=Ds.Instantiate("BABYLON.GUI."+e.className),r=St.Parse((()=>{const e=new s;return e._urlRewriter=i,e}),e,null);return r.name=e.name,r._parseFromContent(e,t,i),r}static drawEllipse(e,t,i,s,r){r.translate(e,t),r.scale(i,s),r.beginPath(),r.arc(0,0,1,0,2*Math.PI),r.closePath(),r.scale(1/i,1/s),r.translate(-e,-t)}isReady(){return!0}}Ow.AllowAlphaInheritance=!1,Ow._ClipMeasure=new Pw(0,0,0,0),Ow._HORIZONTAL_ALIGNMENT_LEFT=0,Ow._HORIZONTAL_ALIGNMENT_RIGHT=1,Ow._HORIZONTAL_ALIGNMENT_CENTER=2,Ow._VERTICAL_ALIGNMENT_TOP=0,Ow._VERTICAL_ALIGNMENT_BOTTOM=1,Ow._VERTICAL_ALIGNMENT_CENTER=2,Ow._FontHeightSizes={},Ow.AddHeader=()=>{},Ze([rt()],Ow.prototype,"metadata",void 0),Ze([rt()],Ow.prototype,"isHitTestVisible",void 0),Ze([rt()],Ow.prototype,"isPointerBlocker",void 0),Ze([rt()],Ow.prototype,"isFocusInvisible",void 0),Ze([rt()],Ow.prototype,"clipChildren",null),Ze([rt()],Ow.prototype,"clipContent",null),Ze([rt()],Ow.prototype,"useBitmapCache",void 0),Ze([rt()],Ow.prototype,"shadowOffsetX",null),Ze([rt()],Ow.prototype,"shadowOffsetY",null),Ze([rt()],Ow.prototype,"shadowBlur",null),Ze([rt()],Ow.prototype,"shadowColor",null),Ze([rt()],Ow.prototype,"hoverCursor",void 0),Ze([rt()],Ow.prototype,"fontOffset",null),Ze([rt()],Ow.prototype,"alpha",null),Ze([rt()],Ow.prototype,"isSerializable",void 0),Ze([rt()],Ow.prototype,"scaleX",null),Ze([rt()],Ow.prototype,"scaleY",null),Ze([rt()],Ow.prototype,"rotation",null),Ze([rt()],Ow.prototype,"transformCenterY",null),Ze([rt()],Ow.prototype,"transformCenterX",null),Ze([rt()],Ow.prototype,"horizontalAlignment",null),Ze([rt()],Ow.prototype,"verticalAlignment",null),Ze([rt()],Ow.prototype,"fixedRatio",null),Ze([rt()],Ow.prototype,"fixedRatioMasterIsWidth",null),Ze([rt()],Ow.prototype,"width",null),Ze([rt()],Ow.prototype,"height",null),Ze([rt()],Ow.prototype,"style",null),Ze([rt()],Ow.prototype,"color",null),Ze([rt()],Ow.prototype,"gradient",null),Ze([rt()],Ow.prototype,"zIndex",null),Ze([rt()],Ow.prototype,"notRenderable",null),Ze([rt()],Ow.prototype,"isVisible",null),Ze([rt()],Ow.prototype,"descendantsOnlyPadding",null),Ze([rt()],Ow.prototype,"paddingLeft",null),Ze([rt()],Ow.prototype,"paddingRight",null),Ze([rt()],Ow.prototype,"paddingTop",null),Ze([rt()],Ow.prototype,"paddingBottom",null),Ze([rt()],Ow.prototype,"left",null),Ze([rt()],Ow.prototype,"top",null),Ze([rt()],Ow.prototype,"linkOffsetX",null),Ze([rt()],Ow.prototype,"linkOffsetY",null),Ze([rt()],Ow.prototype,"isEnabled",null),Ze([rt()],Ow.prototype,"disabledColor",null),Ze([rt()],Ow.prototype,"disabledColorItem",null),Ze([rt()],Ow.prototype,"overlapGroup",void 0),Ze([rt()],Ow.prototype,"overlapDeltaMultiplier",void 0),z("BABYLON.GUI.Control",Ow);class Dw extends Ow{get renderToIntermediateTexture(){return this._renderToIntermediateTexture}set renderToIntermediateTexture(e){this._renderToIntermediateTexture!==e&&(this._renderToIntermediateTexture=e,this._markAsDirty())}get adaptHeightToChildren(){return this._adaptHeightToChildren}set adaptHeightToChildren(e){this._adaptHeightToChildren!==e&&(this._adaptHeightToChildren=e,e&&(this.height="100%"),this._markAsDirty())}get adaptWidthToChildren(){return this._adaptWidthToChildren}set adaptWidthToChildren(e){this._adaptWidthToChildren!==e&&(this._adaptWidthToChildren=e,e&&(this.width="100%"),this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get backgroundGradient(){return this._backgroundGradient}set backgroundGradient(e){this._backgroundGradient!==e&&(this._backgroundGradient=e,this._markAsDirty())}get children(){return this._children}get isReadOnly(){return this._isReadOnly}set isReadOnly(e){this._isReadOnly=e;for(const t of this._children)t.isReadOnly=e}constructor(e){super(e),this.name=e,this._children=new Array,this._measureForChildren=Pw.Empty(),this._background="",this._backgroundGradient=null,this._adaptWidthToChildren=!1,this._adaptHeightToChildren=!1,this._renderToIntermediateTexture=!1,this._intermediateTexture=null,this.delegatePickingToChildren=!1,this.logLayoutCycleErrors=!1,this.maxLayoutCycle=3,this.onControlAddedObservable=new K,this.onControlRemovedObservable=new K,this._inverseTransformMatrix=Rw.Identity(),this._inverseMeasure=new Pw(0,0,0,0)}_getTypeName(){return"Container"}_flagDescendantsAsMatrixDirty(){for(const e of this.children)e._isClipped=!1,e._markMatrixAsDirty()}getChildByName(e){for(const t of this.children)if(t.name===e)return t;return null}getChildByType(e,t){for(const e of this.children)if(e.typeName===t)return e;return null}containsControl(e){return-1!==this.children.indexOf(e)}addControl(e){return e?(-1!==this._children.indexOf(e)||(e._link(this._host),e._markAllAsDirty(),this._reOrderControl(e),this._markAsDirty(),this.onControlAddedObservable.notifyObservers(e)),this):this}clearControls(){const e=this.children.slice();for(const t of e)this.removeControl(t);return this}removeControl(e){const t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e.parent=null),e.linkWithMesh(null),this._host&&this._host._cleanControlAfterRemoval(e),this._markAsDirty(),this.onControlRemovedObservable.notifyObservers(e),this}_reOrderControl(e){const t=e.linkedMesh;this.removeControl(e);let i=!1;for(let t=0;te.zIndex){this._children.splice(t,0,e),i=!0;break}i||this._children.push(e),e.parent=this,t&&e.linkWithMesh(t),this._markAsDirty()}_offsetLeft(e){super._offsetLeft(e);for(const t of this._children)t._offsetLeft(e)}_offsetTop(e){super._offsetTop(e);for(const t of this._children)t._offsetTop(e)}_markAllAsDirty(){super._markAllAsDirty();for(let e=0;e=0&&(s+=this.paddingLeftInPixels+this.paddingRightInPixels,this.width!==s+"px"&&(this.parent?._markAsDirty(),this.width=s+"px",this._width.ignoreAdaptiveScaling=!0,this._rebuildLayout=!0)),this.adaptHeightToChildren&&r>=0&&(r+=this.paddingTopInPixels+this.paddingBottomInPixels,this.height!==r+"px"&&(this.parent?._markAsDirty(),this.height=r+"px",this._height.ignoreAdaptiveScaling=!0,this._rebuildLayout=!0)),this._postMeasure()}i++}while(this._rebuildLayout&&i=3&&this.logLayoutCycleErrors&&Ne.Error(`Layout cycle detected in GUI (Container name=${this.name}, uniqueId=${this.uniqueId})`),t.restore(),this._isDirty&&(this.invalidateRect(),this._isDirty=!1),!0}_postMeasure(){}_draw(e,t){const i=this._renderToIntermediateTexture&&this._intermediateTexture,s=i?this._intermediateTexture.getContext():e;i&&(s.save(),s.translate(-this._currentMeasure.left,-this._currentMeasure.top),t?(this._transformMatrix.invertToRef(this._inverseTransformMatrix),t.transformToRef(this._inverseTransformMatrix,this._inverseMeasure),s.clearRect(this._inverseMeasure.left,this._inverseMeasure.top,this._inverseMeasure.width,this._inverseMeasure.height)):s.clearRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),this._localDraw(s),e.save(),this.clipChildren&&this._clipForChildren(s);for(const e of this._children)t&&!e._intersectsRect(t)||e._render(s,t);i&&(s.restore(),e.save(),e.globalAlpha=this.alpha,e.drawImage(s.canvas,this._currentMeasure.left,this._currentMeasure.top),e.restore()),e.restore()}getDescendantsToRef(e,t=!1,i){if(this.children)for(let s=0;s=0;s--){const r=this._children[s];if(r.isEnabled&&r.isHitTestVisible&&r.isVisible&&!r.notRenderable&&r.contains(e,t)){i=!0;break}}if(!i)return!1}for(let l=this._children.length-1;l>=0;l--){const h=this._children[l];if(h._processPicking(e,t,i,s,r,n,o,a))return h.hoverCursor&&this._host._changeCursor(h.hoverCursor),!0}return!!l&&!!this.isHitTestVisible&&this._processObservables(s,e,t,i,r,n,o,a)}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.copyFrom(this._currentMeasure)}_getAdaptDimTo(e){return"width"===e?this.adaptWidthToChildren:this.adaptHeightToChildren}isDimensionFullyDefined(e){if(this._getAdaptDimTo(e)){for(const t of this.children)if(!t.isDimensionFullyDefined(e))return!1;return!0}return super.isDimensionFullyDefined(e)}serialize(e,t=!1,i=!0){if(super.serialize(e,t,i),(this.isSerializable||t)&&(this.backgroundGradient&&(e.backgroundGradient={},this.backgroundGradient.serialize(e.backgroundGradient)),this.children.length)){e.children=[];for(const s of this.children)if(s.isSerializable||t){const r={};s.serialize(r,t,i),e.children.push(r)}}}dispose(){super.dispose();for(let e=this.children.length-1;e>=0;e--)this.children[e].dispose();this._intermediateTexture?.dispose()}_parseFromContent(e,t,i){if(super._parseFromContent(e,t,i),this._link(t),e.backgroundGradient){const t=Ds.Instantiate("BABYLON.GUI."+e.backgroundGradient.className);this._backgroundGradient=new t,this._backgroundGradient?.parse(e.backgroundGradient)}if(e.children)for(const s of e.children)this.addControl(Ow.Parse(s,t,i))}isReady(){for(const e of this.children)if(!e.isReady())return!1;return!0}}Ze([rt()],Dw.prototype,"delegatePickingToChildren",void 0),Ze([rt()],Dw.prototype,"renderToIntermediateTexture",null),Ze([rt()],Dw.prototype,"maxLayoutCycle",void 0),Ze([rt()],Dw.prototype,"adaptHeightToChildren",null),Ze([rt()],Dw.prototype,"adaptWidthToChildren",null),Ze([rt()],Dw.prototype,"background",null),Ze([rt()],Dw.prototype,"backgroundGradient",null),z("BABYLON.GUI.Container",Dw);class ww extends Dw{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get cornerRadius(){return this._cornerRadius[0]}set cornerRadius(e){e<0&&(e=0),this._cornerRadius[0]===e&&this._cornerRadius[1]===e&&this._cornerRadius[2]===e&&this._cornerRadius[3]===e||(this._cornerRadius[0]=this._cornerRadius[1]=this._cornerRadius[2]=this._cornerRadius[3]=e,this._markAsDirty())}get cornerRadiusX(){return this._cornerRadius[0]}set cornerRadiusX(e){this._cornerRadius[0]!==e&&(this._cornerRadius[0]=e)}get cornerRadiusY(){return this._cornerRadius[1]}set cornerRadiusY(e){this._cornerRadius[1]!==e&&(this._cornerRadius[1]=e)}get cornerRadiusZ(){return this._cornerRadius[2]}set cornerRadiusZ(e){this._cornerRadius[2]!==e&&(this._cornerRadius[2]=e)}get cornerRadiusW(){return this._cornerRadius[3]}set cornerRadiusW(e){this._cornerRadius[3]!==e&&(this._cornerRadius[3]=e)}constructor(e){super(e),this.name=e,this._thickness=1,this._cornerRadius=[0,0,0,0],this._cachedRadius=[0,0,0,0]}_getTypeName(){return"Rectangle"}_computeAdditionalOffsetX(){let e=0;return 0===this._cornerRadius[0]&&0===this._cornerRadius[1]&&0===this._cornerRadius[2]&&0===this._cornerRadius[3]||(e+=1),this.thickness&&(e+=this.thickness/2),e}_computeAdditionalOffsetY(){let e=0;return 0===this._cornerRadius[0]&&0===this._cornerRadius[1]&&0===this._cornerRadius[2]&&0===this._cornerRadius[3]||(e+=1),this.thickness&&(e+=this.thickness/2),e}_getRectangleFill(e){return this._getBackgroundColor(e)}_localDraw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),(this._background||this._backgroundGradient)&&(e.fillStyle=this._getRectangleFill(e),0!==this._cornerRadius[0]||0!==this._cornerRadius[1]||0!==this._cornerRadius[2]||0!==this._cornerRadius[3]?(this._drawRoundedRect(e,this._thickness/2),e.fill()):e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),this._thickness&&((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),(this.color||this.gradient)&&(e.strokeStyle=this.gradient?this.gradient.getCanvasGradient(e):this.color),e.lineWidth=this._thickness,0!==this._cornerRadius[0]||0!==this._cornerRadius[1]||0!==this._cornerRadius[2]||0!==this._cornerRadius[3]?(this._drawRoundedRect(e,this._thickness/2),e.stroke()):e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness)),e.restore()}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.width-=2*this._thickness,this._measureForChildren.height-=2*this._thickness,this._measureForChildren.left+=this._thickness,this._measureForChildren.top+=this._thickness}_drawRoundedRect(e,t=0){const i=this._currentMeasure.left+t,s=this._currentMeasure.top+t,r=this._currentMeasure.width-2*t,n=this._currentMeasure.height-2*t;for(let e=0;ei&&(i=t.width)}if(this._resizeToFit){if(this._textWrapping===Nw.Clip||this._forceResizeWidth){const e=Math.ceil(this._paddingLeftInPixels)+Math.ceil(this._paddingRightInPixels)+Math.ceil(i);e!==this._width.getValueInPixel(this._host,this._tempParentMeasure.width)&&(this._width.updateInPlace(e,yw.UNITMODE_PIXEL),this._rebuildLayout=!0)}let e=this._paddingTopInPixels+this._paddingBottomInPixels+this._fontOffset.height*this._lines.length|0;if(this._lines.length>0&&0!==this._lineSpacing.internalValue){let t=0;t=this._lineSpacing.isPixel?this._lineSpacing.getValue(this._host):this._lineSpacing.getValue(this._host)*this._height.getValueInPixel(this._host,this._cachedParentMeasure.height),e+=(this._lines.length-1)*t}e!==this._height.internalValue&&(this._height.updateInPlace(e,yw.UNITMODE_PIXEL),this._rebuildLayout=!0)}}_drawText(e,t,i,s){const r=this._currentMeasure.width;let n=0;switch(this._textHorizontalAlignment){case Ow.HORIZONTAL_ALIGNMENT_LEFT:n=0;break;case Ow.HORIZONTAL_ALIGNMENT_RIGHT:n=r-t;break;case Ow.HORIZONTAL_ALIGNMENT_CENTER:n=(r-t)/2}(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(s.shadowColor=this.shadowColor,s.shadowBlur=this.shadowBlur,s.shadowOffsetX=this.shadowOffsetX,s.shadowOffsetY=this.shadowOffsetY),this.outlineWidth&&s.strokeText(e,this._currentMeasure.left+n,i),s.fillText(e,this._currentMeasure.left+n,i),this._underline&&this._drawLine(this._currentMeasure.left+n,i+3,this._currentMeasure.left+n+t,i+3,s),this._lineThrough&&this._drawLine(this._currentMeasure.left+n,i-this.fontSizeInPixels/3,this._currentMeasure.left+n+t,i-this.fontSizeInPixels/3,s)}_drawLine(e,t,i,s,r){if(r.beginPath(),r.lineWidth=Math.round(.05*this.fontSizeInPixels),r.moveTo(e,t),r.lineTo(i,s),this.outlineWidth&&this.applyOutlineToUnderline)r.stroke(),r.fill();else{const e=r.strokeStyle;r.strokeStyle=r.fillStyle,r.stroke(),r.strokeStyle=e}r.closePath()}_draw(e){e.save(),this._applyStates(e),this._renderLines(e),e.restore()}_applyStates(e){super._applyStates(e),this.outlineWidth&&(e.lineWidth=this.outlineWidth,e.strokeStyle=this.outlineColor,e.lineJoin="miter",e.miterLimit=2)}_breakLines(e,t,i){this._linesTemp.length=0;const s=this.text.split("\n");if(this._textWrapping===Nw.Ellipsis)for(const t of s)this._linesTemp.push(this._parseLineEllipsis(t,e,i));else if(this._textWrapping===Nw.WordWrap)for(const t of s)this._linesTemp.push(...this._parseLineWordWrap(t,e,i));else if(this._textWrapping===Nw.WordWrapEllipsis)for(const r of s)this._linesTemp.push(...this._parseLineWordWrapEllipsis(r,e,t,i));else for(const e of s)this._linesTemp.push(this._parseLine(e,i));return this._linesTemp}_parseLine(e="",t){return{text:e,width:this._getTextMetricsWidth(t.measureText(e))}}_getCharsToRemove(e,t,i){const s=e>t?e-t:0,r=e/i;return Math.max(Math.floor(s/r),1)}_parseLineEllipsis(e="",t,i){let s=this._getTextMetricsWidth(i.measureText(e)),r=this._getCharsToRemove(s,t,e.length);const n=Array.from&&Array.from(e);if(n)for(;n.length&&s>t;)n.splice(n.length-r,r),e=`${n.join("")}…`,s=this._getTextMetricsWidth(i.measureText(e)),r=this._getCharsToRemove(s,t,e.length);else{for(;e.length>2&&s>t;)e=e.slice(0,-r),s=this._getTextMetricsWidth(i.measureText(e+"…")),r=this._getCharsToRemove(s,t,e.length);e+="…"}return{text:e,width:s}}_getTextMetricsWidth(e){return void 0!==e.actualBoundingBoxLeft?Math.abs(e.actualBoundingBoxLeft)+Math.abs(e.actualBoundingBoxRight):e.width}_parseLineWordWrap(e="",t,i){const s=[],r=this.wordSplittingFunction?this.wordSplittingFunction(e):e.split(this._wordDivider);let n=this._getTextMetricsWidth(i.measureText(e));for(let o=0;o0?e+this._wordDivider+r[o]:r[0],l=this._getTextMetricsWidth(i.measureText(a));l>t&&o>0?(s.push({text:e,width:n}),e=r[o],n=this._getTextMetricsWidth(i.measureText(e))):(n=l,e=a)}return s.push({text:e,width:n}),s}_parseLineWordWrapEllipsis(e="",t,i,s){const r=this._parseLineWordWrap(e,t,s);for(let e=1;e<=r.length;e++)if(this._computeHeightForLinesOf(e)>i&&e>1){const i=r[e-2],n=r[e-1];r[e-2]=this._parseLineEllipsis(i.text+this._wordDivider+n.text,t,s);const o=r.length-e+1;for(let e=0;e0&&0!==this._lineSpacing.internalValue){let i=0;i=this._lineSpacing.isPixel?this._lineSpacing.getValue(this._host):this._lineSpacing.getValue(this._host)*this._height.getValueInPixel(this._host,this._cachedParentMeasure.height),t+=(e-1)*i}return t}isDimensionFullyDefined(e){return!!this.resizeToFit||super.isDimensionFullyDefined(e)}computeExpectedHeight(){if(this.text&&this.widthInPixels){const e=re.LastCreatedEngine?.createCanvas(0,0).getContext("2d");if(e){this._applyStates(e),this._fontOffset||(this._fontOffset=Ow._GetFontOffset(e.font,this._host.getScene()?.getEngine()));const t=this._lines?this._lines:this._breakLines(this.widthInPixels-this._paddingLeftInPixels-this._paddingRightInPixels,this.heightInPixels-this._paddingTopInPixels-this._paddingBottomInPixels,e);return this._computeHeightForLinesOf(t.length)}}return 0}dispose(){super.dispose(),this.onTextChangedObservable.clear()}}Ze([rt()],Fw.prototype,"resizeToFit",null),Ze([rt()],Fw.prototype,"textWrapping",null),Ze([rt()],Fw.prototype,"text",null),Ze([rt()],Fw.prototype,"textHorizontalAlignment",null),Ze([rt()],Fw.prototype,"textVerticalAlignment",null),Ze([rt()],Fw.prototype,"lineSpacing",null),Ze([rt()],Fw.prototype,"outlineWidth",null),Ze([rt()],Fw.prototype,"underline",null),Ze([rt()],Fw.prototype,"lineThrough",null),Ze([rt()],Fw.prototype,"applyOutlineToUnderline",null),Ze([rt()],Fw.prototype,"outlineColor",null),Ze([rt()],Fw.prototype,"wordDivider",null),Ze([rt()],Fw.prototype,"forceResizeWidth",null),z("BABYLON.GUI.TextBlock",Fw);class Lw extends Ow{get isLoaded(){return this._loaded}isReady(){return this.isLoaded}get detectPointerOnOpaqueOnly(){return this._detectPointerOnOpaqueOnly}set detectPointerOnOpaqueOnly(e){this._detectPointerOnOpaqueOnly!==e&&(this._detectPointerOnOpaqueOnly=e)}get sliceLeft(){return this._sliceLeft}set sliceLeft(e){this._sliceLeft!==e&&(this._sliceLeft=e,this._markAsDirty())}get sliceRight(){return this._sliceRight}set sliceRight(e){this._sliceRight!==e&&(this._sliceRight=e,this._markAsDirty())}get sliceTop(){return this._sliceTop}set sliceTop(e){this._sliceTop!==e&&(this._sliceTop=e,this._markAsDirty())}get sliceBottom(){return this._sliceBottom}set sliceBottom(e){this._sliceBottom!==e&&(this._sliceBottom=e,this._markAsDirty())}get sourceLeft(){return this._sourceLeft}set sourceLeft(e){this._sourceLeft!==e&&(this._sourceLeft=e,this._markAsDirty())}get sourceTop(){return this._sourceTop}set sourceTop(e){this._sourceTop!==e&&(this._sourceTop=e,this._markAsDirty())}get sourceWidth(){return this._sourceWidth}set sourceWidth(e){this._sourceWidth!==e&&(this._sourceWidth=e,this._markAsDirty())}get sourceHeight(){return this._sourceHeight}set sourceHeight(e){this._sourceHeight!==e&&(this._sourceHeight=e,this._markAsDirty())}get imageWidth(){return this._imageWidth}get imageHeight(){return this._imageHeight}get populateNinePatchSlicesFromImage(){return this._populateNinePatchSlicesFromImage}set populateNinePatchSlicesFromImage(e){this._populateNinePatchSlicesFromImage!==e&&(this._populateNinePatchSlicesFromImage=e,this._populateNinePatchSlicesFromImage&&this._loaded&&this._extractNinePatchSliceDataFromImage())}get isSVG(){return this._isSVG}get svgAttributesComputationCompleted(){return this._svgAttributesComputationCompleted}get autoScale(){return this._autoScale}set autoScale(e){this._autoScale!==e&&(this._autoScale=e,e&&this._loaded&&this.synchronizeSizeWithContent())}get stretch(){return this._stretch}set stretch(e){this._stretch!==e&&(this._stretch=e,this._markAsDirty())}_rotate90(e,t=!1){const i=this._domImage.width,s=this._domImage.height,r=this._host?.getScene()?.getEngine()||re.LastCreatedEngine;if(!r)throw new Error("Invalid engine. Unable to create a canvas.");const n=r.createCanvas(s,i),o=n.getContext("2d");o.translate(n.width/2,n.height/2),o.rotate(e*Math.PI/2),o.drawImage(this._domImage,0,0,i,s,-i/2,-s/2,i,s);const a=n.toDataURL("image/jpg"),l=new Lw(this.name+"rotated",a);return t&&(l._stretch=this._stretch,l._autoScale=this._autoScale,l._cellId=this._cellId,l._cellWidth=e%1?this._cellHeight:this._cellWidth,l._cellHeight=e%1?this._cellWidth:this._cellHeight),this._handleRotationForSVGImage(this,l,e),this._imageDataCache.data=null,l}_handleRotationForSVGImage(e,t,i){e._isSVG&&(e._svgAttributesComputationCompleted?(this._rotate90SourceProperties(e,t,i),this._markAsDirty()):e.onSVGAttributesComputedObservable.addOnce((()=>{this._rotate90SourceProperties(e,t,i),this._markAsDirty()})))}_rotate90SourceProperties(e,t,i){let s=e.sourceLeft,r=e.sourceTop,n=e.domImage.width,o=e.domImage.height,a=s,l=r,h=e.sourceWidth,c=e.sourceHeight;if(0!=i){const e=i<0?-1:1;i%=4;for(let t=0;t127&&-1===this._sliceLeft)this._sliceLeft=t;else if(e<127&&this._sliceLeft>-1){this._sliceRight=t;break}}this._sliceTop=-1,this._sliceBottom=-1;for(let i=0;i127&&-1===this._sliceTop)this._sliceTop=i;else if(t<127&&this._sliceTop>-1){this._sliceBottom=i;break}}}set domImage(e){this._domImage=e,this._loaded=!1,this._imageDataCache.data=null,this._domImage.width?this._onImageLoaded():this._domImage.onload=()=>{this._onImageLoaded()}}get domImage(){return this._domImage}_onImageLoaded(){this._imageDataCache.data=null,this._imageWidth=this._domImage.width,this._imageHeight=this._domImage.height,this._loaded=!0,this._populateNinePatchSlicesFromImage&&this._extractNinePatchSliceDataFromImage(),this._autoScale&&this.synchronizeSizeWithContent(),this.onImageLoadedObservable.notifyObservers(this),this._markAsDirty()}get source(){return this._source}static ResetImageCache(){Lw.SourceImgCache.clear()}_removeCacheUsage(e){const t=e&&Lw.SourceImgCache.get(e);t&&(t.timesUsed-=1,0===t.timesUsed&&Lw.SourceImgCache.delete(e))}set source(e){if(this._urlRewriter&&e&&(e=this._urlRewriter(e)),this._source===e)return;this._removeCacheUsage(this._source),this._loaded=!1,this._source=e,this._imageDataCache.data=null,e&&(e=this._svgCheck(e));const t=this._host?.getScene()?.getEngine()||re.LastCreatedEngine;if(!t)throw new Error("Invalid engine. Unable to create a canvas.");if(e&&Lw.SourceImgCache.has(e)){const t=Lw.SourceImgCache.get(e);return this._domImage=t.img,t.timesUsed+=1,void(t.loaded?this._onImageLoaded():t.waitingForLoadCallback.push(this._onImageLoaded.bind(this)))}this._domImage=t.createCanvasImage(),e&&Lw.SourceImgCache.set(e,{img:this._domImage,timesUsed:1,loaded:!1,waitingForLoadCallback:[this._onImageLoaded.bind(this)]}),this._domImage.onload=()=>{if(e){const t=Lw.SourceImgCache.get(e);if(t){t.loaded=!0;for(const e of t.waitingForLoadCallback)e();return void(t.waitingForLoadCallback.length=0)}}this._onImageLoaded()},e&&(Ds.SetCorsBehavior(e,this._domImage),Ds.SetReferrerPolicyBehavior(this.referrerPolicy,this._domImage),this._domImage.src=e)}_svgCheck(e){if(window.SVGSVGElement&&-1!==e.search(/.svg#/gi)&&e.indexOf("#")===e.lastIndexOf("#")){this._isSVG=!0;const t=e.split("#")[0],i=e.split("#")[1],s=document.body.querySelector('object[data="'+t+'"]');if(s){const t=s.contentDocument;if(t&&t.documentElement){const r=t.documentElement.getAttribute("viewBox"),n=Number(t.documentElement.getAttribute("width")),o=Number(t.documentElement.getAttribute("height"));if(t.getElementById(i)&&r&&n&&o)return this._getSVGAttribs(s,i),e}s.addEventListener("load",(()=>{this._getSVGAttribs(s,i)}))}else{const e=document.createElement("object");e.data=t,e.type="image/svg+xml",e.width="0%",e.height="0%",document.body.appendChild(e),e.onload=()=>{const e=document.body.querySelector('object[data="'+t+'"]');e&&this._getSVGAttribs(e,i)}}return t}return e}_getSVGAttribs(e,t){const i=e.contentDocument;if(i&&i.documentElement){const e=i.documentElement.getAttribute("viewBox"),s=Number(i.documentElement.getAttribute("width")),r=Number(i.documentElement.getAttribute("height")),n=i.getElementById(t);if(e&&s&&r&&n){const t=Number(e.split(" ")[2]),i=Number(e.split(" ")[3]),o=n.getBBox();let a=1,l=1,h=0,c=0;const u=n.transform.baseVal.consolidate().matrix;n.transform&&n.transform.baseVal.consolidate()&&(a=u.a,l=u.d,h=u.e,c=u.f),this.sourceLeft=(a*o.x+h)*s/t,this.sourceTop=(l*o.y+c)*r/i,this.sourceWidth=o.width*a*(s/t),this.sourceHeight=o.height*l*(r/i),this._svgAttributesComputationCompleted=!0,this.onSVGAttributesComputedObservable.notifyObservers(this)}}}get cellWidth(){return this._cellWidth}set cellWidth(e){this._cellWidth!==e&&(this._cellWidth=e,this._markAsDirty())}get cellHeight(){return this._cellHeight}set cellHeight(e){this._cellHeight!==e&&(this._cellHeight=e,this._markAsDirty())}get cellId(){return this._cellId}set cellId(e){this._cellId!==e&&(this._cellId=e,this._markAsDirty())}constructor(e,t=null){super(e),this.name=e,this._workingCanvas=null,this._loaded=!1,this._stretch=Lw.STRETCH_FILL,this._autoScale=!1,this._sourceLeft=0,this._sourceTop=0,this._sourceWidth=0,this._sourceHeight=0,this._svgAttributesComputationCompleted=!1,this._isSVG=!1,this._cellWidth=0,this._cellHeight=0,this._cellId=-1,this._populateNinePatchSlicesFromImage=!1,this._imageDataCache={data:null,key:""},this.onImageLoadedObservable=new K,this.onSVGAttributesComputedObservable=new K,this.source=t}contains(e,t){if(!super.contains(e,t))return!1;if(!this._detectPointerOnOpaqueOnly||!this._workingCanvas)return!0;const i=0|this._currentMeasure.width,s=0|this._currentMeasure.height,r=i+"_"+s;let n=this._imageDataCache.data;if(!n||this._imageDataCache.key!==r){const e=this._workingCanvas.getContext("2d");this._imageDataCache.data=n=e.getImageData(0,0,i,s).data,this._imageDataCache.key=r}return n[4*((e=e-this._currentMeasure.left|0)+(t=t-this._currentMeasure.top|0)*i)+3]>0}_getTypeName(){return"Image"}synchronizeSizeWithContent(){this._loaded&&(this.width=this._domImage.width+"px",this.height=this._domImage.height+"px")}_processMeasures(e,t){if(this._loaded)switch(this._stretch){case Lw.STRETCH_NONE:case Lw.STRETCH_FILL:case Lw.STRETCH_UNIFORM:case Lw.STRETCH_NINE_PATCH:break;case Lw.STRETCH_EXTEND:this._autoScale&&this.synchronizeSizeWithContent(),this.parent&&this.parent.parent&&(this.parent.adaptWidthToChildren=!0,this.parent.adaptHeightToChildren=!0)}super._processMeasures(e,t)}_prepareWorkingCanvasForOpaqueDetection(){if(!this._detectPointerOnOpaqueOnly)return;const e=this._currentMeasure.width,t=this._currentMeasure.height;if(!this._workingCanvas){const i=this._host?.getScene()?.getEngine()||re.LastCreatedEngine;if(!i)throw new Error("Invalid engine. Unable to create a canvas.");this._workingCanvas=i.createCanvas(e,t)}this._workingCanvas.getContext("2d").clearRect(0,0,e,t)}_drawImage(e,t,i,s,r,n,o,a,l){if(e.drawImage(this._domImage,t,i,s,r,n,o,a,l),!this._detectPointerOnOpaqueOnly)return;const h=e.getTransform(),c=this._workingCanvas.getContext("2d");c.save();const u=n-this._currentMeasure.left,d=o-this._currentMeasure.top;c.setTransform(h.a,h.b,h.c,h.d,(u+a)/2,(d+l)/2),c.translate(-(u+a)/2,-(d+l)/2),c.drawImage(this._domImage,t,i,s,r,u,d,a,l),c.restore()}_draw(e){let t,i,s,r;if(e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),-1==this.cellId)t=this._sourceLeft,i=this._sourceTop,s=this._sourceWidth?this._sourceWidth:this._imageWidth,r=this._sourceHeight?this._sourceHeight:this._imageHeight;else{const e=this._domImage.naturalWidth/this.cellWidth,n=this.cellId/e|0,o=this.cellId%e;t=this.cellWidth*o,i=this.cellHeight*n,s=this.cellWidth,r=this.cellHeight}if(this._prepareWorkingCanvasForOpaqueDetection(),this._applyStates(e),this._loaded)switch(this._stretch){case Lw.STRETCH_NONE:case Lw.STRETCH_FILL:this._drawImage(e,t,i,s,r,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case Lw.STRETCH_UNIFORM:{const n=this._currentMeasure.width/s,o=this._currentMeasure.height/r,a=Math.min(n,o),l=(this._currentMeasure.width-s*a)/2,h=(this._currentMeasure.height-r*a)/2;this._drawImage(e,t,i,s,r,this._currentMeasure.left+l,this._currentMeasure.top+h,s*a,r*a);break}case Lw.STRETCH_EXTEND:this._drawImage(e,t,i,s,r,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case Lw.STRETCH_NINE_PATCH:this._renderNinePatch(e,t,i,s,r)}e.restore()}_renderNinePatch(e,t,i,s,r){const n=this.host.idealWidth?this._width.getValue(this.host)/this.host.idealWidth:this.host.idealHeight?this._height.getValue(this.host)/this.host.idealHeight:1,o=this._sliceLeft,a=this._sliceTop,l=r-this._sliceBottom,h=s-this._sliceRight,c=this._sliceRight-this._sliceLeft,u=this._sliceBottom-this._sliceTop,d=Math.round(o*n),_=Math.round(a*n),p=Math.round(l*n),f=Math.round(h*n),m=Math.round(this._currentMeasure.width)-f-d+2,g=Math.round(this._currentMeasure.height)-p-_+2,v=Math.round(this._currentMeasure.left)+d-1,x=Math.round(this._currentMeasure.top)+_-1,b=Math.round(this._currentMeasure.left+this._currentMeasure.width)-f,T=Math.round(this._currentMeasure.top+this._currentMeasure.height)-p;this._drawImage(e,t,i,o,a,this._currentMeasure.left,this._currentMeasure.top,d,_),this._drawImage(e,t+this._sliceLeft,i,c,a,v+1,this._currentMeasure.top,m-2,_),this._drawImage(e,t+this._sliceRight,i,h,a,b,this._currentMeasure.top,f,_),this._drawImage(e,t,i+this._sliceTop,o,u,this._currentMeasure.left,x+1,d,g-2),this._drawImage(e,t+this._sliceLeft,i+this._sliceTop,c,u,v+1,x+1,m-2,g-2),this._drawImage(e,t+this._sliceRight,i+this._sliceTop,h,u,b,x+1,f,g-2),this._drawImage(e,t,i+this._sliceBottom,o,l,this._currentMeasure.left,T,d,p),this._drawImage(e,t+this.sliceLeft,i+this._sliceBottom,c,l,v+1,T,m-2,p),this._drawImage(e,t+this._sliceRight,i+this._sliceBottom,h,l,b,T,f,p)}dispose(){super.dispose(),this.onImageLoadedObservable.clear(),this.onSVGAttributesComputedObservable.clear(),this._removeCacheUsage(this._source)}}Lw.SourceImgCache=new Map,Lw.STRETCH_NONE=0,Lw.STRETCH_FILL=1,Lw.STRETCH_UNIFORM=2,Lw.STRETCH_EXTEND=3,Lw.STRETCH_NINE_PATCH=4,Ze([rt()],Lw.prototype,"detectPointerOnOpaqueOnly",null),Ze([rt()],Lw.prototype,"sliceLeft",null),Ze([rt()],Lw.prototype,"sliceRight",null),Ze([rt()],Lw.prototype,"sliceTop",null),Ze([rt()],Lw.prototype,"sliceBottom",null),Ze([rt()],Lw.prototype,"sourceLeft",null),Ze([rt()],Lw.prototype,"sourceTop",null),Ze([rt()],Lw.prototype,"sourceWidth",null),Ze([rt()],Lw.prototype,"sourceHeight",null),Ze([rt()],Lw.prototype,"populateNinePatchSlicesFromImage",null),Ze([rt()],Lw.prototype,"autoScale",null),Ze([rt()],Lw.prototype,"stretch",null),Ze([rt()],Lw.prototype,"source",null),Ze([rt()],Lw.prototype,"cellWidth",null),Ze([rt()],Lw.prototype,"cellHeight",null),Ze([rt()],Lw.prototype,"cellId",null),z("BABYLON.GUI.Image",Lw);class Bw extends ww{get image(){return this._image}get textBlock(){return this._textBlock}constructor(e){super(e),this.name=e,this.thickness=1,this.isPointerBlocker=!0;let t=null;this.pointerEnterAnimation=()=>{t=this.alpha,this.alpha-=.1},this.pointerOutAnimation=()=>{null!==t&&(this.alpha=t)},this.pointerDownAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05}}_getTypeName(){return"Button"}_processPicking(e,t,i,s,r,n,o,a){if(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this.notRenderable)return!1;if(!super.contains(e,t))return!1;if(this.delegatePickingToChildren){let i=!1;for(let s=this._children.length-1;s>=0;s--){const r=this._children[s];if(r.isEnabled&&r.isHitTestVisible&&r.isVisible&&!r.notRenderable&&r.contains(e,t)){i=!0;break}}if(!i)return!1}return this._processObservables(s,e,t,i,r,n,o,a),!0}_onPointerEnter(e,t){return!!super._onPointerEnter(e,t)&&(!this.isReadOnly&&this.pointerEnterAnimation&&this.pointerEnterAnimation(),!0)}_onPointerOut(e,t,i=!1){!this.isReadOnly&&this.pointerOutAnimation&&this.pointerOutAnimation(),super._onPointerOut(e,t,i)}_onPointerDown(e,t,i,s,r){return!!super._onPointerDown(e,t,i,s,r)&&(!this.isReadOnly&&this.pointerDownAnimation&&this.pointerDownAnimation(),!0)}_getRectangleFill(e){return this.isEnabled?this._getBackgroundColor(e):this._disabledColor}_onPointerUp(e,t,i,s,r,n){!this.isReadOnly&&this.pointerUpAnimation&&this.pointerUpAnimation(),super._onPointerUp(e,t,i,s,r,n)}serialize(e,t){super.serialize(e,t),(this.isSerializable||t)&&(this._textBlock&&(e.textBlockName=this._textBlock.name),this._image&&(e.imageName=this._image.name))}_parseFromContent(e,t){super._parseFromContent(e,t),e.textBlockName&&(this._textBlock=this.getChildByName(e.textBlockName)),e.imageName&&(this._image=this.getChildByName(e.imageName))}static CreateImageButton(e,t,i){const s=new this(e),r=new Fw(e+"_button",t);r.textWrapping=!0,r.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_CENTER,r.paddingLeft="20%",s.addControl(r);const n=new Lw(e+"_icon",i);return n.width="20%",n.stretch=Lw.STRETCH_UNIFORM,n.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,s.addControl(n),s._image=n,s._textBlock=r,s}static CreateImageOnlyButton(e,t){const i=new this(e),s=new Lw(e+"_icon",t);return s.stretch=Lw.STRETCH_FILL,s.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,i.addControl(s),i._image=s,i}static CreateSimpleButton(e,t){const i=new this(e),s=new Fw(e+"_button",t);return s.textWrapping=!0,s.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_CENTER,i.addControl(s),i._textBlock=s,i}static CreateImageWithCenterTextButton(e,t,i){const s=new this(e),r=new Lw(e+"_icon",i);r.stretch=Lw.STRETCH_FILL,s.addControl(r);const n=new Fw(e+"_button",t);return n.textWrapping=!0,n.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_CENTER,s.addControl(n),s._image=r,s._textBlock=n,s}}z("BABYLON.GUI.Button",Bw);class kw extends Dw{get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,this._markAsDirty())}get spacing(){return this._spacing}set spacing(e){this._spacing!==e&&(this._spacing=e,this._markAsDirty())}set width(e){this._doNotTrackManualChanges||(this._manualWidth=!0),this._width.toString(this._host)!==e&&this._width.fromString(e)&&this._markAsDirty()}get width(){return this._width.toString(this._host)}set height(e){this._doNotTrackManualChanges||(this._manualHeight=!0),this._height.toString(this._host)!==e&&this._height.fromString(e)&&this._markAsDirty()}get height(){return this._height.toString(this._host)}constructor(e){super(e),this.name=e,this._isVertical=!0,this._manualWidth=!1,this._manualHeight=!1,this._doNotTrackManualChanges=!1,this._spacing=0,this.ignoreLayoutWarnings=!1}_getTypeName(){return"StackPanel"}_preMeasure(e,t){for(const e of this._children)this._isVertical?e.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP:e.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT;super._preMeasure(e,t)}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.copyFrom(e),this._measureForChildren.left=this._currentMeasure.left,this._measureForChildren.top=this._currentMeasure.top,this.isVertical&&!this._manualWidth||(this._measureForChildren.width=this._currentMeasure.width),(this.isVertical||this._manualHeight)&&(this._measureForChildren.height=this._currentMeasure.height)}_postMeasure(){let e=0,t=0;const i=this._children.length;for(let s=0;s=0?Math.min(e,this._characters.length):this._characters.length+Math.max(e,-this._characters.length),void 0===t?t=this._characters.length-e:(isNaN(t)||t<0)&&(t=0);const i=[];for(;--t>=0;)i[t]=this._characters[e+t];return i.join("")}return this._text.substr(e,t)}substring(e,t){if(this._characters){isNaN(e)?e=0:e>this._characters.length?e=this._characters.length:e<0&&(e=0),void 0===t?t=this._characters.length:isNaN(t)?t=0:t>this._characters.length?t=this._characters.length:t<0&&(t=0);const i=[];let s=0;for(;e{switch(e.type){case Jm.COPY:this._onCopyText(e.event),this.onTextCopyObservable.notifyObservers(this);break;case Jm.CUT:this._onCutText(e.event),this.onTextCutObservable.notifyObservers(this);break;case Jm.PASTE:this._onPasteText(e.event),this.onTextPasteObservable.notifyObservers(this);break;default:return}}));const e=this._host.getScene();e&&(this._onPointerDblTapObserver=e.onPointerObservable.add((e=>{this._isFocused&&e.type===lr.POINTERDOUBLETAP&&this._processDblClick(e)}))),this._onFocusSelectAll&&this._selectAllText()}focus(){this._host.moveFocusToControl(this)}blur(){this._host.focusedControl=null}_getTypeName(){return"InputText"}keepsFocusWith(){return this._connectedVirtualKeyboard?[this._connectedVirtualKeyboard]:null}processKey(e,t,i){if(!this.isReadOnly&&(!i||!i.ctrlKey&&!i.metaKey||67!==e&&86!==e&&88!==e)){if(i&&(i.ctrlKey||i.metaKey)&&65===e)return this._selectAllText(),void i.preventDefault();switch(e){case 32:t=" ";break;case 191:i&&i.preventDefault();break;case 8:if(this._textWrapper.text&&this._textWrapper.length>0){if(this.isTextHighlightOn)return this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this._blinkIsEven=!1,void(i&&i.preventDefault());if(0===this._cursorOffset)this.text=this._textWrapper.substr(0,this._textWrapper.length-1);else{const e=this._textWrapper.length-this._cursorOffset;e>0&&(this._textWrapper.removePart(e-1,e),this._textHasChanged())}}return void(i&&i.preventDefault());case 46:if(this.isTextHighlightOn)return this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,void(i&&i.preventDefault());if(this._textWrapper.text&&this._textWrapper.length>0&&this._cursorOffset>0){const e=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(e,e+1),this._textHasChanged(),this._cursorOffset--}return void(i&&i.preventDefault());case 13:return this._host.focusedControl=null,void(this.isTextHighlightOn=!1);case 35:return this._cursorOffset=0,this._blinkIsEven=!1,this.isTextHighlightOn=!1,void this._markAsDirty();case 36:return this._cursorOffset=this._textWrapper.length,this._blinkIsEven=!1,this.isTextHighlightOn=!1,void this._markAsDirty();case 37:if(this._cursorOffset++,this._cursorOffset>this._textWrapper.length&&(this._cursorOffset=this._textWrapper.length),i&&i.shiftKey){if(this._blinkIsEven=!1,i.ctrlKey||i.metaKey){if(!this.isTextHighlightOn){if(this._textWrapper.length===this._cursorOffset)return;this._endHighlightIndex=this._textWrapper.length-this._cursorOffset+1}return this._startHighlightIndex=0,this._cursorIndex=this._textWrapper.length-this._endHighlightIndex,this._cursorOffset=this._textWrapper.length,this.isTextHighlightOn=!0,void this._markAsDirty()}return this.isTextHighlightOn?-1===this._cursorIndex&&(this._cursorIndex=this._textWrapper.length-this._endHighlightIndex,this._cursorOffset=0===this._startHighlightIndex?this._textWrapper.length:this._textWrapper.length-this._startHighlightIndex+1):(this.isTextHighlightOn=!0,this._cursorIndex=this._cursorOffset>=this._textWrapper.length?this._textWrapper.length:this._cursorOffset-1),this._cursorIndexthis._cursorOffset?(this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex):this.isTextHighlightOn=!1,void this._markAsDirty()}return this.isTextHighlightOn&&(this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this.isTextHighlightOn=!1),i&&(i.ctrlKey||i.metaKey)&&(this._cursorOffset=this._textWrapper.length,i.preventDefault()),this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._cursorIndex=-1,void this._markAsDirty();case 39:if(this._cursorOffset--,this._cursorOffset<0&&(this._cursorOffset=0),i&&i.shiftKey){if(this._blinkIsEven=!1,i.ctrlKey||i.metaKey){if(!this.isTextHighlightOn){if(0===this._cursorOffset)return;this._startHighlightIndex=this._textWrapper.length-this._cursorOffset-1}return this._endHighlightIndex=this._textWrapper.length,this.isTextHighlightOn=!0,this._cursorIndex=this._textWrapper.length-this._startHighlightIndex,this._cursorOffset=0,void this._markAsDirty()}return this.isTextHighlightOn?-1===this._cursorIndex&&(this._cursorIndex=this._textWrapper.length-this._startHighlightIndex,this._cursorOffset=this._textWrapper.length===this._endHighlightIndex?0:this._textWrapper.length-this._endHighlightIndex-1):(this.isTextHighlightOn=!0,this._cursorIndex=this._cursorOffset<=0?0:this._cursorOffset+1),this._cursorIndexthis._cursorOffset?(this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex):this.isTextHighlightOn=!1,void this._markAsDirty()}return this.isTextHighlightOn&&(this._cursorOffset=this._textWrapper.length-this._endHighlightIndex,this.isTextHighlightOn=!1),i&&(i.ctrlKey||i.metaKey)&&(this._cursorOffset=0,i.preventDefault()),this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._cursorIndex=-1,void this._markAsDirty()}if(32===e&&(t=i?.key??" "),this._deadKey="Dead"===t,t&&(-1===e||32===e||34===e||39===e||e>47&&e<64||e>64&&e<91||e>159&&e<193||e>218&&e<223||e>95&&e<112)&&(this._currentKey=t,this.onBeforeKeyAddObservable.notifyObservers(this),t=this._currentKey,this._addKey&&!this._deadKey))if(this.isTextHighlightOn)this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex,t),this._textHasChanged(),this._cursorOffset=this._textWrapper.length-(this._startHighlightIndex+1),this.isTextHighlightOn=!1,this._blinkIsEven=!1,this._markAsDirty();else if(0===this._cursorOffset)this.text+=this._deadKey&&i?.key?i.key:t;else{const e=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(e,e,t),this._textHasChanged()}}}_updateValueFromCursorIndex(e){if(this._blinkIsEven=!1,-1===this._cursorIndex)this._cursorIndex=e;else if(this._cursorIndexthis._cursorOffset))return this.isTextHighlightOn=!1,void this._markAsDirty();this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex}this.isTextHighlightOn=!0,this._markAsDirty()}_processDblClick(e){let t,i;this._startHighlightIndex=this._textWrapper.length-this._cursorOffset,this._endHighlightIndex=this._startHighlightIndex;do{i=this._endHighlightIndex0&&this._textWrapper.isWord(this._startHighlightIndex-1)?--this._startHighlightIndex:0}while(t||i);this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this.isTextHighlightOn=!0,this._clickedCoordinate=null,this._blinkIsEven=!0,this._cursorIndex=-1,this._markAsDirty()}_selectAllText(){this._blinkIsEven=!0,this.isTextHighlightOn=!0,this._startHighlightIndex=0,this._endHighlightIndex=this._textWrapper.length,this._cursorOffset=this._textWrapper.length,this._cursorIndex=-1,this._markAsDirty()}processKeyboard(e){this.processKey(e.keyCode,e.key,e),this.onKeyboardEventProcessedObservable.notifyObservers(e)}_onCopyText(e){this.isTextHighlightOn=!1;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText}_onCutText(e){if(this._highlightedText){this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText,this._highlightedText=""}}_onPasteText(e){let t="";t=e.clipboardData&&-1!==e.clipboardData.types.indexOf("text/plain")?e.clipboardData.getData("text/plain"):this._host.clipboardData;const i=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(i,i,t),this._textHasChanged()}_draw(e){e.save(),this._applyStates(e),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._isEnabled?this._focusedBackground:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._fontOffset&&!this._wasDirty||(this._fontOffset=Ow._GetFontOffset(e.font,this._host.getScene()?.getEngine()));const t=this._currentMeasure.left+this._margin.getValueInPixel(this._host,this._tempParentMeasure.width);this.color&&(e.fillStyle=this.color);let i=this._beforeRenderText(this._textWrapper);this._isFocused||this._textWrapper.text||!this._placeholderText||(i=new Uw,i.text=this._placeholderText,this._placeholderColor&&(e.fillStyle=this._placeholderColor)),this._textWidth=e.measureText(i.text).width;const s=2*this._margin.getValueInPixel(this._host,this._tempParentMeasure.width);this._autoStretchWidth&&(this.width=Math.min(this._maxWidth.getValueInPixel(this._host,this._tempParentMeasure.width),this._textWidth+s)+"px",this._autoStretchWidth=!0);const r=this._fontOffset.ascent+(this._currentMeasure.height-this._fontOffset.height)/2,n=this._width.getValueInPixel(this._host,this._tempParentMeasure.width)-s;if(e.save(),e.beginPath(),e.rect(t,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,n+2,this._currentMeasure.height),e.clip(),this._isFocused&&this._textWidth>n){const e=t-this._textWidth+n;this._scrollLeft||(this._scrollLeft=e)}else this._scrollLeft=t;if(this.outlineWidth&&e.strokeText(i.text,this._scrollLeft,this._currentMeasure.top+r),e.fillText(i.text,this._scrollLeft,this._currentMeasure.top+r),this._isFocused){if(this._clickedCoordinate){const t=this._scrollLeft+this._textWidth-this._clickedCoordinate;let s=0;this._cursorOffset=0;let r=0;do{this._cursorOffset&&(r=Math.abs(t-s)),this._cursorOffset++,s=e.measureText(i.substr(i.length-this._cursorOffset,this._cursorOffset)).width}while(s=this._cursorOffset);Math.abs(t-s)>r&&this._cursorOffset--,this._blinkIsEven=!1,this._clickedCoordinate=null}if(!this._blinkIsEven){const s=i.substr(i.length-this._cursorOffset),r=e.measureText(s).width;let o=this._scrollLeft+this._textWidth-r;ot+n&&(this._scrollLeft+=t+n-o,o=t+n,this._markAsDirty()),this.isTextHighlightOn||e.fillRect(o,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,2,this._fontOffset.height)}if(clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout((()=>{this._blinkIsEven=!this._blinkIsEven,this._markAsDirty()}),500),this.isTextHighlightOn){clearTimeout(this._blinkTimeout);const s=e.measureText(i.substring(this._startHighlightIndex)).width;let r=this._scrollLeft+this._textWidth-s;this._highlightedText=i.substring(this._startHighlightIndex,this._endHighlightIndex);let n=e.measureText(i.substring(this._startHighlightIndex,this._endHighlightIndex)).width;r=this._rowDefinitions.length?null:this._rowDefinitions[e]}getColumnDefinition(e){return e<0||e>=this._columnDefinitions.length?null:this._columnDefinitions[e]}addRowDefinition(e,t=!1){return this._rowDefinitions.push(new yw(e,t?yw.UNITMODE_PIXEL:yw.UNITMODE_PERCENTAGE)),this._rowDefinitionObservers.push(this._rowDefinitions[this.rowCount-1].onChangedObservable.add((()=>this._markAsDirty()))),this._markAsDirty(),this}addColumnDefinition(e,t=!1){return this._columnDefinitions.push(new yw(e,t?yw.UNITMODE_PIXEL:yw.UNITMODE_PERCENTAGE)),this._columnDefinitionObservers.push(this._columnDefinitions[this.columnCount-1].onChangedObservable.add((()=>this._markAsDirty()))),this._markAsDirty(),this}setRowDefinition(e,t,i=!1){if(e<0||e>=this._rowDefinitions.length)return this;const s=this._rowDefinitions[e];return s&&s.isPixel===i&&s.value===t||(this._rowDefinitions[e].onChangedObservable.remove(this._rowDefinitionObservers[e]),this._rowDefinitions[e]=new yw(t,i?yw.UNITMODE_PIXEL:yw.UNITMODE_PERCENTAGE),this._rowDefinitionObservers[e]=this._rowDefinitions[e].onChangedObservable.add((()=>this._markAsDirty())),this._markAsDirty()),this}setColumnDefinition(e,t,i=!1){if(e<0||e>=this._columnDefinitions.length)return this;const s=this._columnDefinitions[e];return s&&s.isPixel===i&&s.value===t||(this._columnDefinitions[e].onChangedObservable.remove(this._columnDefinitionObservers[e]),this._columnDefinitions[e]=new yw(t,i?yw.UNITMODE_PIXEL:yw.UNITMODE_PERCENTAGE),this._columnDefinitionObservers[e]=this._columnDefinitions[e].onChangedObservable.add((()=>this._markAsDirty())),this._markAsDirty()),this}getChildrenAt(e,t){const i=this._cells[`${e}:${t}`];return i?i.children:null}getChildCellInfo(e){return e._tag}_removeCell(e,t){if(e){super.removeControl(e);for(const t of e.children){const e=this._childControls.indexOf(t);-1!==e&&this._childControls.splice(e,1)}delete this._cells[t]}}_offsetCell(e,t){if(this._cells[t]){this._cells[e]=this._cells[t];for(const t of this._cells[e].children)t._tag=e;delete this._cells[t]}}removeColumnDefinition(e){if(e<0||e>=this._columnDefinitions.length)return this;for(let t=0;t=this._rowDefinitions.length)return this;for(let t=0;t{for(const r in this._cells){if(!Object.prototype.hasOwnProperty.call(this._cells,r))continue;const n=r.split(":"),o=parseInt(n[0]),a=parseInt(n[1]),l=this._cells[r];l.leftInPixels=e[a],l.topInPixels=t[o],l.widthInPixels=i[a],l.heightInPixels=s[o],l._left.ignoreAdaptiveScaling=!0,l._top.ignoreAdaptiveScaling=!0,l._width.ignoreAdaptiveScaling=!0,l._height.ignoreAdaptiveScaling=!0}})),super._additionalProcessing(e,t)}_flagDescendantsAsMatrixDirty(){for(const e in this._cells)Object.prototype.hasOwnProperty.call(this._cells,e)&&this._cells[e]._markMatrixAsDirty()}_renderHighlightSpecific(e){super._renderHighlightSpecific(e),this._getGridDefinitions(((t,i,s,r)=>{for(let i=0;i{e.tags.push(t._tag)}))}}_parseFromContent(e,t){super._parseFromContent(e,t);const i=[];this.children.forEach((e=>{i.push(e)})),this.removeRowDefinition(0),this.removeColumnDefinition(0);for(let t=0;t=1-Ww._Epsilon&&(this._value.r=1),this._value.g>=1-Ww._Epsilon&&(this._value.g=1),this._value.b>=1-Ww._Epsilon&&(this._value.b=1),this.onValueChangedObservable.notifyObservers(this._value))}get width(){return this._width.toString(this._host)}set width(e){this._width.toString(this._host)!==e&&this._width.fromString(e)&&(0===this._width.getValue(this._host)&&(e="1px",this._width.fromString(e)),this._height.fromString(e),this._markAsDirty())}get height(){return this._height.toString(this._host)}set height(e){this._height.toString(this._host)!==e&&this._height.fromString(e)&&(0===this._height.getValue(this._host)&&(e="1px",this._height.fromString(e)),this._width.fromString(e),this._markAsDirty())}get size(){return this.width}set size(e){this.width=e}constructor(e){super(e),this.name=e,this._value=Ee.Red(),this._tmpColor=new Ee,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._squareLeft=0,this._squareTop=0,this._squareSize=0,this._h=360,this._s=1,this._v=1,this._lastPointerDownId=-1,this.onValueChangedObservable=new K,this._pointerIsDown=!1,this.value=new Ee(.88,.1,.1),this.size="200px",this.isPointerBlocker=!0}_getTypeName(){return"ColorPicker"}_preMeasure(e){e.widthl||sg?f:(f-p)*(e-m)/(g-m)+p,d=(r-h)/(e-h),o[u+3]=d<_?d/_*255:d>1-_?255*(1-(d-(1-_))/_):255}return r.putImageData(n,0,0),s}_draw(e){e.save(),this._applyStates(e);const t=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),i=.2*t,s=this._currentMeasure.left,r=this._currentMeasure.top;this._colorWheelCanvas&&this._colorWheelCanvas.width==2*t||(this._colorWheelCanvas=this._createColorWheelCanvas(t,i)),this._updateSquareProps(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY,e.fillRect(this._squareLeft,this._squareTop,this._squareSize,this._squareSize)),e.drawImage(this._colorWheelCanvas,s,r),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._drawGradientSquare(this._h,this._squareLeft,this._squareTop,this._squareSize,this._squareSize,e);let n=this._squareLeft+this._squareSize*this._s,o=this._squareTop+this._squareSize*(1-this._v);this._drawCircle(n,o,.04*t,e);const a=t-.5*i;n=s+t+Math.cos((this._h-180)*Math.PI/180)*a,o=r+t+Math.sin((this._h-180)*Math.PI/180)*a,this._drawCircle(n,o,.35*i,e),e.restore()}_updateValueFromPointer(e,t){if(this._pointerStartedOnWheel){const i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),s=i+this._currentMeasure.left,r=i+this._currentMeasure.top;this._h=180*Math.atan2(t-r,e-s)/Math.PI+180}else this._pointerStartedOnSquare&&(this._updateSquareProps(),this._s=(e-this._squareLeft)/this._squareSize,this._v=1-(t-this._squareTop)/this._squareSize,this._s=Math.min(this._s,1),this._s=Math.max(this._s,Ww._Epsilon),this._v=Math.min(this._v,1),this._v=Math.max(this._v,Ww._Epsilon));Ee.HSVtoRGBToRef(this._h,this._s,this._v,this._tmpColor),this.value=this._tmpColor}_isPointOnSquare(e,t){this._updateSquareProps();const i=this._squareLeft,s=this._squareTop,r=this._squareSize;return e>=i&&e<=i+r&&t>=s&&t<=s+r}_isPointOnWheel(e,t){const i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),s=i-.2*i,r=e-(i+this._currentMeasure.left),n=t-(i+this._currentMeasure.top),o=r*r+n*n;return o<=i*i&&o>=s*s}_onPointerDown(e,t,i,s,r){if(!super._onPointerDown(e,t,i,s,r))return!1;if(this.isReadOnly)return!0;this._pointerIsDown=!0,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._invertTransformMatrix.transformCoordinates(t.x,t.y,this._transformedPosition);const n=this._transformedPosition.x,o=this._transformedPosition.y;return this._isPointOnSquare(n,o)?this._pointerStartedOnSquare=!0:this._isPointOnWheel(n,o)&&(this._pointerStartedOnWheel=!0),this._updateValueFromPointer(n,o),this._host._capturingControl[i]=this,this._lastPointerDownId=i,!0}_onPointerMove(e,t,i,s){if(i==this._lastPointerDownId){if(!this.isReadOnly){this._invertTransformMatrix.transformCoordinates(t.x,t.y,this._transformedPosition);const e=this._transformedPosition.x,i=this._transformedPosition.y;this._pointerIsDown&&this._updateValueFromPointer(e,i)}super._onPointerMove(e,t,i,s)}}_onPointerUp(e,t,i,s,r,n){this._pointerIsDown=!1,delete this._host._capturingControl[i],super._onPointerUp(e,t,i,s,r,n)}_onCanvasBlur(){this._forcePointerUp(),super._onCanvasBlur()}static ShowPickerDialogAsync(e,t){return new Promise((i=>{t.pickerWidth=t.pickerWidth||"640px",t.pickerHeight=t.pickerHeight||"400px",t.headerHeight=t.headerHeight||"35px",t.lastColor=t.lastColor||"#000000",t.swatchLimit=t.swatchLimit||20,t.numSwatchesPerLine=t.numSwatchesPerLine||10;const s=t.swatchLimit/t.numSwatchesPerLine,r=parseFloat(t.pickerWidth)/t.numSwatchesPerLine,n=Math.floor(.25*r),o=n*(t.numSwatchesPerLine+1),a=Math.floor((parseFloat(t.pickerWidth)-o)/t.numSwatchesPerLine),l=a*s+n*(s+1),h=(parseInt(t.pickerHeight)+l+Math.floor(.25*a)).toString()+"px",c="#c0c0c0",u="#535353",d="#414141",_="515151",p="#555555",f="#454545",m=Ee.FromHexString("#dddddd"),g=m.r+m.g+m.b,v="#aaaaaa",x="#ffffff";let b,T;const y=["R","G","B"],S="#454545",C="#f0f0f0";let E,A,P,I,R,M=!1;const O=new zw;if(O.name="Dialog Container",O.width=t.pickerWidth,t.savedColors){O.height=h;const e=parseInt(t.pickerHeight)/parseInt(h);O.addRowDefinition(e,!1),O.addRowDefinition(1-e,!1)}else O.height=t.pickerHeight,O.addRowDefinition(1,!1);if(e.addControl(O),t.savedColors){A=new zw,A.name="Swatch Drawer",A.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,A.background=u,A.width=t.pickerWidth;const e=t.savedColors.length/t.numSwatchesPerLine;let i;i=0==e?0:e+1,A.height=(a*e+i*n).toString()+"px",A.top=Math.floor(.25*a).toString()+"px";for(let e=0;e<2*Math.ceil(t.savedColors.length/t.numSwatchesPerLine)+1;e++)e%2!=0?A.addRowDefinition(a,!0):A.addRowDefinition(n,!0);for(let e=0;e<2*t.numSwatchesPerLine+1;e++)e%2!=0?A.addColumnDefinition(a,!0):A.addColumnDefinition(n,!0);O.addControl(A,1,0)}const D=new zw;D.name="Picker Panel",D.height=t.pickerHeight;const w=parseInt(t.headerHeight)/parseInt(t.pickerHeight),N=[w,1-w];D.addRowDefinition(N[0],!1),D.addRowDefinition(N[1],!1),O.addControl(D,0,0);const F=new ww;F.name="Dialogue Header Bar",F.background="#cccccc",F.thickness=0,D.addControl(F,0,0);const L=Bw.CreateSimpleButton("closeButton","a");L.fontFamily="coreglyphs";const B=Ee.FromHexString(F.background),k=new Ee(1-B.r,1-B.g,1-B.b);L.color=k.toHexString(),L.fontSize=Math.floor(.6*parseInt(t.headerHeight)),L.textBlock.textVerticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,L.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_RIGHT,L.height=L.width=t.headerHeight,L.background=F.background,L.thickness=0,L.pointerDownAnimation=()=>{},L.pointerUpAnimation=()=>{L.background=F.background},L.pointerEnterAnimation=()=>{L.color=F.background,L.background="red"},L.pointerOutAnimation=()=>{L.color=k.toHexString(),L.background=F.background},L.onPointerClickObservable.add((()=>{De(te.background)})),D.addControl(L,0,0);const V=new zw;V.name="Dialogue Body",V.background=u;const U=[.4375,.5625];V.addRowDefinition(1,!1),V.addColumnDefinition(U[0],!1),V.addColumnDefinition(U[1],!1),D.addControl(V,1,0);const G=new zw;G.name="Picker Grid",G.addRowDefinition(.85,!1),G.addRowDefinition(.15,!1),V.addControl(G,0,0);const z=new Ww;z.name="GUI Color Picker",t.pickerHeight{R=z.name,I="",Ie(!1)})),z.onValueChangedObservable.add((function(e){R==z.name&&Se(e,z.name)})),G.addControl(z,0,0);const W=new zw;W.name="Dialogue Right Half",W.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT;const H=[.514,.486];W.addRowDefinition(H[0],!1),W.addRowDefinition(H[1],!1),V.addControl(W,1,1);const X=new zw;X.name="Swatches and Buttons";const Y=[.417,.583];X.addRowDefinition(1,!1),X.addColumnDefinition(Y[0],!1),X.addColumnDefinition(Y[1],!1),W.addControl(X,0,0);const Q=new zw;Q.name="New and Current Swatches";const j=[.04,.16,.64,.16];Q.addRowDefinition(j[0],!1),Q.addRowDefinition(j[1],!1),Q.addRowDefinition(j[2],!1),Q.addRowDefinition(j[3],!1),X.addControl(Q,0,0);const K=new zw;K.name="Active Swatches",K.width=.67,K.addRowDefinition(.5,!1),K.addRowDefinition(.5,!1),Q.addControl(K,2,0);const $=Math.floor(parseInt(t.pickerWidth)*U[1]*Y[0]*.11),q=Math.floor(parseInt(t.pickerHeight)*N[1]*H[0]*j[1]*.5);let Z;Z=t.pickerWidth>t.pickerHeight?q:$;const J=new Fw;J.text="new",J.name="New Color Label",J.color=c,J.fontSize=Z,Q.addControl(J,1,0);const ee=new ww;ee.name="New Color Swatch",ee.background=t.lastColor,ee.thickness=0,K.addControl(ee,0,0);const te=Bw.CreateSimpleButton("currentSwatch","");te.background=t.lastColor,te.thickness=0,te.onPointerClickObservable.add((()=>{Se(Ee.FromHexString(te.background),te.name),Ie(!1)})),te.pointerDownAnimation=()=>{},te.pointerUpAnimation=()=>{},te.pointerEnterAnimation=()=>{},te.pointerOutAnimation=()=>{},K.addControl(te,1,0);const ie=new ww;ie.name="Swatch Outline",ie.width=.67,ie.thickness=2,ie.color="#404040",ie.isHitTestVisible=!1,Q.addControl(ie,2,0);const se=new Fw;se.name="Current Color Label",se.text="current",se.color=c,se.fontSize=Z,Q.addControl(se,3,0);const re=new zw;re.name="Button Grid",re.height=.8;const ne=1/3;re.addRowDefinition(ne,!1),re.addRowDefinition(ne,!1),re.addRowDefinition(ne,!1),X.addControl(re,0,1);const oe=Math.floor(parseInt(t.pickerWidth)*U[1]*Y[1]*.67).toString()+"px",ae=Math.floor(parseInt(t.pickerHeight)*N[1]*H[0]*(parseFloat(re.height.toString())/100)*ne*.7).toString()+"px";b=parseFloat(oe)>parseFloat(ae)?Math.floor(.45*parseFloat(ae)):Math.floor(.11*parseFloat(oe));const le=Bw.CreateSimpleButton("butOK","OK");le.width=oe,le.height=ae,le.verticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,le.thickness=2,le.color=c,le.fontSize=b,le.background=u,le.onPointerEnterObservable.add((()=>{le.background=d})),le.onPointerOutObservable.add((()=>{le.background=u})),le.pointerDownAnimation=()=>{le.background=_},le.pointerUpAnimation=()=>{le.background=d},le.onPointerClickObservable.add((()=>{Ie(!1),De(ee.background)})),re.addControl(le,0,0);const he=Bw.CreateSimpleButton("butCancel","Cancel");he.width=oe,he.height=ae,he.verticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,he.thickness=2,he.color=c,he.fontSize=b,he.background=u,he.onPointerEnterObservable.add((()=>{he.background=d})),he.onPointerOutObservable.add((()=>{he.background=u})),he.pointerDownAnimation=()=>{he.background=_},he.pointerUpAnimation=()=>{he.background=d},he.onPointerClickObservable.add((()=>{Ie(!1),De(te.background)})),re.addControl(he,1,0),t.savedColors&&(P=Bw.CreateSimpleButton("butSave","Save"),P.width=oe,P.height=ae,P.verticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,P.thickness=2,P.fontSize=b,t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&(0==t.savedColors.length&&Me(!0),t.savedColors.length0&&Me(!0),re.addControl(P,2,0));const ce=new zw;ce.name="Dialog Lower Right",ce.addRowDefinition(.02,!1),ce.addRowDefinition(.63,!1),ce.addRowDefinition(.21,!1),ce.addRowDefinition(.14,!1),W.addControl(ce,1,0);const ue=Ee.FromHexString(t.lastColor),de=new zw;de.name="RGB Values",de.width=.82,de.verticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,de.addRowDefinition(1/3,!1),de.addRowDefinition(1/3,!1),de.addRowDefinition(1/3,!1),de.addColumnDefinition(.1,!1),de.addColumnDefinition(.2,!1),de.addColumnDefinition(.7,!1),ce.addControl(de,1,0);for(let e=0;e{R=_e.name,I=_e.text,Ie(!1)})),_e.onBlurObservable.add((()=>{""==_e.text&&(_e.text="0"),Ce(_e,"r"),R==_e.name&&(R="")})),_e.onTextChangedObservable.add((()=>{R==_e.name&&Ce(_e,"r")})),de.addControl(_e,0,1);const pe=new Gw;pe.width=.83,pe.height=.72,pe.name="gIntField",pe.fontSize=b,pe.text=(255*ue.g).toString(),pe.color=C,pe.background=S,pe.onFocusObservable.add((()=>{R=pe.name,I=pe.text,Ie(!1)})),pe.onBlurObservable.add((()=>{""==pe.text&&(pe.text="0"),Ce(pe,"g"),R==pe.name&&(R="")})),pe.onTextChangedObservable.add((()=>{R==pe.name&&Ce(pe,"g")})),de.addControl(pe,1,1);const fe=new Gw;fe.width=.83,fe.height=.72,fe.name="bIntField",fe.fontSize=b,fe.text=(255*ue.b).toString(),fe.color=C,fe.background=S,fe.onFocusObservable.add((()=>{R=fe.name,I=fe.text,Ie(!1)})),fe.onBlurObservable.add((()=>{""==fe.text&&(fe.text="0"),Ce(fe,"b"),R==fe.name&&(R="")})),fe.onTextChangedObservable.add((()=>{R==fe.name&&Ce(fe,"b")})),de.addControl(fe,2,1);const me=new Gw;me.width=.95,me.height=.72,me.name="rDecField",me.fontSize=b,me.text=ue.r.toString(),me.color=C,me.background=S,me.onFocusObservable.add((()=>{R=me.name,I=me.text,Ie(!1)})),me.onBlurObservable.add((()=>{0!=parseFloat(me.text)&&""!=me.text||(me.text="0",Ae(me,"r")),R==me.name&&(R="")})),me.onTextChangedObservable.add((()=>{R==me.name&&Ae(me,"r")})),de.addControl(me,0,2);const ge=new Gw;ge.width=.95,ge.height=.72,ge.name="gDecField",ge.fontSize=b,ge.text=ue.g.toString(),ge.color=C,ge.background=S,ge.onFocusObservable.add((()=>{R=ge.name,I=ge.text,Ie(!1)})),ge.onBlurObservable.add((()=>{0!=parseFloat(ge.text)&&""!=ge.text||(ge.text="0",Ae(ge,"g")),R==ge.name&&(R="")})),ge.onTextChangedObservable.add((()=>{R==ge.name&&Ae(ge,"g")})),de.addControl(ge,1,2);const ve=new Gw;ve.width=.95,ve.height=.72,ve.name="bDecField",ve.fontSize=b,ve.text=ue.b.toString(),ve.color=C,ve.background=S,ve.onFocusObservable.add((()=>{R=ve.name,I=ve.text,Ie(!1)})),ve.onBlurObservable.add((()=>{0!=parseFloat(ve.text)&&""!=ve.text||(ve.text="0",Ae(ve,"b")),R==ve.name&&(R="")})),ve.onTextChangedObservable.add((()=>{R==ve.name&&Ae(ve,"b")})),de.addControl(ve,2,2);const xe=new zw;xe.name="Hex Value",xe.width=.82,xe.addRowDefinition(1,!1),xe.addColumnDefinition(.1,!1),xe.addColumnDefinition(.9,!1),ce.addControl(xe,2,0);const be=new Fw;be.text="#",be.color=c,be.fontSize=b,xe.addControl(be,0,0);const Te=new Gw;Te.width=.96,Te.height=.72,Te.name="hexField",Te.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_CENTER,Te.fontSize=b;const ye=t.lastColor.split("#");function Se(e,t){R=t;const i=e.toHexString();if(ee.background=i,_e.name!=R&&(_e.text=Math.floor(255*e.r).toString()),pe.name!=R&&(pe.text=Math.floor(255*e.g).toString()),fe.name!=R&&(fe.text=Math.floor(255*e.b).toString()),me.name!=R&&(me.text=e.r.toString()),ge.name!=R&&(ge.text=e.g.toString()),ve.name!=R&&(ve.text=e.b.toString()),Te.name!=R){const e=i.split("#");Te.text=e[1]}z.name!=R&&(z.value=e)}function Ce(e,t){let i=e.text;if(/[^0-9]/g.test(i))e.text=I;else if(""!=i&&(Math.floor(parseInt(i))<0?i="0":Math.floor(parseInt(i))>255?i="255":isNaN(parseInt(i))&&(i="0")),R==e.name&&(I=i),""!=i){i=parseInt(i).toString(),e.text=i;const s=Ee.FromHexString(ee.background);R==e.name&&Se("r"==t?new Ee(parseInt(i)/255,s.g,s.b):"g"==t?new Ee(s.r,parseInt(i)/255,s.b):new Ee(s.r,s.g,parseInt(i)/255),e.name)}}function Ae(e,t){let i=e.text;if(/[^0-9.]/g.test(i))return void(e.text=I);""!=i&&"."!=i&&0!=parseFloat(i)&&(parseFloat(i)<0?i="0.0":parseFloat(i)>1?i="1.0":isNaN(parseFloat(i))&&(i="0.0")),R==e.name&&(I=i),""!=i&&"."!=i&&0!=parseFloat(i)?(i=parseFloat(i).toString(),e.text=i):i="0.0";const s=Ee.FromHexString(ee.background);R==e.name&&Se("r"==t?new Ee(parseFloat(i),s.g,s.b):"g"==t?new Ee(s.r,parseFloat(i),s.b):new Ee(s.r,s.g,parseFloat(i)),e.name)}function Pe(){if(t.savedColors&&t.savedColors[E]){let e;e=M?"b":"";const i=Bw.CreateSimpleButton("Swatch_"+E,e);i.fontFamily="coreglyphs";const s=Ee.FromHexString(t.savedColors[E]),r=s.r+s.g+s.b;i.color=r>g?v:x,i.fontSize=Math.floor(.7*a),i.textBlock.verticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,i.height=i.width=a.toString()+"px",i.background=t.savedColors[E],i.thickness=2;const n=E;return i.pointerDownAnimation=()=>{i.thickness=4},i.pointerUpAnimation=()=>{i.thickness=3},i.pointerEnterAnimation=()=>{i.thickness=3},i.pointerOutAnimation=()=>{i.thickness=2},i.onPointerClickObservable.add((()=>{var e;M?(e=n,t.savedColors&&t.savedColors.splice(e,1),t.savedColors&&0==t.savedColors.length&&(Me(!1),M=!1),Re("",P)):t.savedColors&&Se(Ee.FromHexString(t.savedColors[n]),i.name)})),i}return null}function Ie(e){let t;if(void 0!==e&&(M=e),M){for(let e=0;ei*t.numSwatchesPerLine?t.numSwatchesPerLine:t.savedColors.length-(i-1)*t.numSwatchesPerLine;const r=Math.min(Math.max(s,0),t.numSwatchesPerLine);for(let i=0,s=1;it.numSwatchesPerLine)continue;const r=Pe();null!=r&&(A.addControl(r,e,s),s+=2,E++)}}t.savedColors.length>=t.swatchLimit?Oe(i,!0):Oe(i,!1)}}function Me(e){e?(T=Bw.CreateSimpleButton("butEdit","Edit"),T.width=oe,T.height=ae,T.left=Math.floor(.1*parseInt(oe)).toString()+"px",T.top=(-1*parseFloat(T.left)).toString()+"px",T.verticalAlignment=Ow.VERTICAL_ALIGNMENT_BOTTOM,T.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,T.thickness=2,T.color=c,T.fontSize=b,T.background=u,T.onPointerEnterObservable.add((()=>{T.background=d})),T.onPointerOutObservable.add((()=>{T.background=u})),T.pointerDownAnimation=()=>{T.background=_},T.pointerUpAnimation=()=>{T.background=d},T.onPointerClickObservable.add((()=>{M=!M,Ie()})),G.addControl(T,1,0)):G.removeControl(T)}function Oe(e,t){t?(e.color=p,e.background=f):(e.color=c,e.background=u)}function De(s){t.savedColors&&t.savedColors.length>0?i({savedColors:t.savedColors,pickedColor:s}):i({pickedColor:s}),e.removeControl(O)}Te.text=ye[1],Te.color=C,Te.background=S,Te.onFocusObservable.add((()=>{R=Te.name,I=Te.text,Ie(!1)})),Te.onBlurObservable.add((()=>{if(3==Te.text.length){const e=Te.text.split("");Te.text=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]}""==Te.text&&(Te.text="000000",Se(Ee.FromHexString(Te.text),"b")),R==Te.name&&(R="")})),Te.onTextChangedObservable.add((()=>{let e=Te.text;const t=/[^0-9A-F]/i.test(e);if((Te.text.length>6||t)&&R==Te.name)Te.text=I;else{if(Te.text.length<6){const t=6-Te.text.length;for(let i=0;i0&&Re("",P)}))}}Ww._Epsilon=1e-6,Ze([rt()],Ww.prototype,"value",null),Ze([rt()],Ww.prototype,"width",null),Ze([rt()],Ww.prototype,"height",null),Ze([rt()],Ww.prototype,"size",null),z("BABYLON.GUI.ColorPicker",Ww);class Hw extends Dw{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thickness=1}_getTypeName(){return"Ellipse"}_localDraw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),Ow.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,e),(this._backgroundGradient||this._background)&&(e.fillStyle=this._getBackgroundColor(e),e.fill()),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._thickness&&(this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.stroke()),e.restore()}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.width-=2*this._thickness,this._measureForChildren.height-=2*this._thickness,this._measureForChildren.left+=this._thickness,this._measureForChildren.top+=this._thickness}_clipForChildren(e){Ow.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2,this._currentMeasure.height/2,e),e.clip()}_renderHighlightSpecific(e){Ow.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._highlightLineWidth/2,this._currentMeasure.height/2-this._highlightLineWidth/2,e),e.stroke()}}Ze([rt()],Hw.prototype,"thickness",null),z("BABYLON.GUI.Ellipse",Hw);class Xw extends Bw{constructor(e){super(e),this.name=e,this.focusedColor=null,this._isFocused=!1,this._unfocusedColor=null,this.onFocusObservable=new K,this.onBlurObservable=new K,this.onKeyboardEventProcessedObservable=new K,this._unfocusedColor=this.color}onBlur(){this._isFocused&&(this._isFocused=!1,this.focusedColor&&null!=this._unfocusedColor&&(this.color=this._unfocusedColor),this.onBlurObservable.notifyObservers(this))}onFocus(){this._isFocused=!0,this.focusedColor&&(this._unfocusedColor=this.color,this.color=this.focusedColor),this.onFocusObservable.notifyObservers(this)}keepsFocusWith(){return null}focus(){this._host.moveFocusToControl(this)}blur(){this._host.focusedControl=null}processKeyboard(e){this.onKeyboardEventProcessedObservable.notifyObservers(e,-1,this)}_onPointerDown(e,t,i,s,r){return this.isReadOnly||this.focus(),super._onPointerDown(e,t,i,s,r)}dispose(){super.dispose(),this.onBlurObservable.clear(),this.onFocusObservable.clear(),this.onKeyboardEventProcessedObservable.clear()}}z("BABYLON.GUI.FocusableButton",Xw);class Yw extends Gw{get autoStretchHeight(){return this._autoStretchHeight}set autoStretchHeight(e){this._autoStretchHeight!==e&&(this._autoStretchHeight=e,this._markAsDirty())}set height(e){this.fixedRatioMasterIsWidth=!1,this._height.toString(this._host)!==e&&(this._height.fromString(e)&&this._markAsDirty(),this._autoStretchHeight=!1)}get maxHeight(){return this._maxHeight.toString(this._host)}get maxHeightInPixels(){return this._maxHeight.getValueInPixel(this._host,this._cachedParentMeasure.height)}set maxHeight(e){this._maxHeight.toString(this._host)!==e&&this._maxHeight.fromString(e)&&this._markAsDirty()}constructor(e,t=""){super(e),this.name=e,this._textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._textVerticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,this._prevText=this.text,this._lineSpacing=new yw(0),this._maxHeight=new yw(1,yw.UNITMODE_PERCENTAGE,!1),this.onLinesReadyObservable=new K,this.text=t,this.isPointerBlocker=!0,this.onLinesReadyObservable.add((()=>this._updateCursorPosition())),this._highlightCursorInfo={initialStartIndex:-1,initialRelativeStartIndex:-1,initialLineIndex:-1},this._cursorInfo={globalStartIndex:0,globalEndIndex:0,relativeEndIndex:0,relativeStartIndex:0,currentLineIndex:0}}_getTypeName(){return"InputTextArea"}processKeyboard(e){this.isReadOnly||(this.alternativeProcessKey(e.code,e.key,e),this.onKeyboardEventProcessedObservable.notifyObservers(e))}alternativeProcessKey(e,t,i){if(!i||!i.ctrlKey&&!i.metaKey||"KeyC"!==e&&"KeyV"!==e&&"KeyX"!==e){switch(e){case"KeyA":if(i&&(i.ctrlKey||i.metaKey))return this._selectAllText(),void i.preventDefault();break;case"Period":i&&i.shiftKey&&i.preventDefault();break;case"Backspace":!this._isTextHighlightOn&&this._cursorInfo.globalStartIndex>0&&(this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex--),this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,i&&i.preventDefault(),this._blinkIsEven=!1,this._isTextHighlightOn=!1,this._textHasChanged();break;case"Delete":!this._isTextHighlightOn&&this._cursorInfo.globalEndIndexthis._highlightCursorInfo.initialStartIndex?this._cursorInfo.globalEndIndex--:this._cursorInfo.globalStartIndex--:(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex--,this._isTextHighlightOn=!0),this._blinkIsEven=!0,void i.preventDefault()):(this._isTextHighlightOn?this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex:i&&(i.ctrlKey||i.metaKey)?(this._cursorInfo.globalStartIndex-=this._cursorInfo.relativeStartIndex,i.preventDefault()):this._cursorInfo.globalStartIndex>0&&this._cursorInfo.globalStartIndex--,this._blinkIsEven=!1,void(this._isTextHighlightOn=!1));case"ArrowRight":if(this._markAsDirty(),i&&i.shiftKey){if(i.ctrlKey||i.metaKey){const e=this._lines[this._cursorInfo.currentLineIndex].text.length-this._cursorInfo.relativeEndIndex-1;this._cursorInfo.globalEndIndex+=e,this._cursorInfo.globalStartIndex=this._highlightCursorInfo.initialStartIndex}return this._isTextHighlightOn?this._cursorInfo.globalStartIndexa&&l>0&&i--,this._isTextHighlightOn?this._cursorInfo.currentLineIndex<=this._highlightCursorInfo.initialLineIndex?(this._cursorInfo.globalStartIndex=i,this._cursorInfo.globalEndIndex=this._highlightCursorInfo.initialStartIndex,this._cursorInfo.relativeEndIndex=this._highlightCursorInfo.initialRelativeStartIndex):this._cursorInfo.globalEndIndex=i:this._cursorInfo.globalStartIndex=i}return void this._markAsDirty();case"ArrowDown":if(this._blinkIsEven=!1,i&&(i.shiftKey?(this._isTextHighlightOn||(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex),this._isTextHighlightOn=!0,this._blinkIsEven=!0):this._isTextHighlightOn=!1,i.preventDefault()),this._cursorInfo.currentLineIndex===this._lines.length-1)this._cursorInfo.globalStartIndex=this.text.length;else{const e=this._lines[this._cursorInfo.currentLineIndex],t=this._lines[this._cursorInfo.currentLineIndex+1];let i=0,s=0;!this._isTextHighlightOn||this._cursorInfo.currentLineIndexa&&l>0&&i--,this._isTextHighlightOn?this._cursorInfo.currentLineIndexthis._cursorInfo.globalEndIndex&&(this._cursorInfo.globalEndIndex+=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex=this._cursorInfo.globalEndIndex-this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex-=this._cursorInfo.globalStartIndex)):(this._cursorInfo.globalEndIndex=i,this._cursorInfo.globalStartIndex=this._highlightCursorInfo.initialStartIndex):this._cursorInfo.globalStartIndex=i}return void this._markAsDirty()}1===t?.length&&(i?.preventDefault(),this._currentKey=t,this.onBeforeKeyAddObservable.notifyObservers(this),t=this._currentKey,this._addKey&&(this._isTextHighlightOn=!1,this._blinkIsEven=!1,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex,t),this._cursorInfo.globalStartIndex+=t.length,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._textHasChanged()))}}_parseLineWordWrap(e="",t,i){const s=[],r=e.split(" ");let n=0;for(let o=0;o0?e+" "+r[o]:r[0],l=i.measureText(a).width;if(l>t){o>0&&(n=i.measureText(e).width,s.push({text:e,width:n,lineEnding:" "})),e=r[o];let a="";e.split("").map((e=>{i.measureText(a+e).width>t&&(s.push({text:a,width:i.measureText(a).width,lineEnding:""}),a=""),a+=e})),e=a,n=i.measureText(e).width}else n=l,e=a}return s.push({text:e,width:n,lineEnding:" "}),s}_breakLines(e,t){const i=[],s=(this.text||this.placeholderText).split("\n");if(this.clipContent)for(const r of s)i.push(...this._parseLineWordWrap(r,e,t));else for(const e of s)i.push(this._parseLine(e,t));return i[i.length-1].lineEnding="\n",i}_parseLine(e="",t){return{text:e,width:t.measureText(e).width,lineEnding:" "}}_preMeasure(e,t){this._fontOffset&&!this._wasDirty||(this._fontOffset=Ow._GetFontOffset(t.font,this._host.getScene()?.getEngine()));let i=this._beforeRenderText(this._textWrapper).text;!this.text&&this._placeholderText&&(i=this._placeholderText),this._textWidth=t.measureText(i).width;const s=2*this._margin.getValueInPixel(this._host,e.width);if(this._autoStretchWidth){const r=i.split("\n").reduce(((e,i)=>t.measureText(i).width>t.measureText(e).width?i:e),""),n=t.measureText(r).width;this.width=Math.min(this._maxWidth.getValueInPixel(this._host,e.width),n+s)+"px",this.autoStretchWidth=!0}if(this._availableWidth=this._width.getValueInPixel(this._host,e.width)-s,this._lines=this._breakLines(this._availableWidth,t),this._contextForBreakLines=t,this._autoStretchHeight){const t=this._lines.length*this._fontOffset.height+2*this._margin.getValueInPixel(this._host,e.height);this.height=Math.min(this._maxHeight.getValueInPixel(this._host,e.height),t)+"px",this._autoStretchHeight=!0}if(this._availableHeight=this._height.getValueInPixel(this._host,e.height)-s,this._isFocused){this._cursorInfo.currentLineIndex=0;let e=this._lines[this._cursorInfo.currentLineIndex].text.length+this._lines[this._cursorInfo.currentLineIndex].lineEnding.length,t=0;for(;t+e<=this._cursorInfo.globalStartIndex;)t+=e,this._cursorInfo.currentLineIndexthis._availableWidth){const e=this._clipTextLeft-this._lines[this._cursorInfo.currentLineIndex].width+this._availableWidth;this._scrollLeft||(this._scrollLeft=e)}else this._scrollLeft=this._clipTextLeft;if(this._isFocused&&!this._autoStretchHeight){const e=(this._cursorInfo.currentLineIndex+1)*this._fontOffset.height,t=this._clipTextTop-e;this._scrollTop||(this._scrollTop=t)}else this._scrollTop=this._clipTextTop}_additionalProcessing(){this.highlightedText="",this.onLinesReadyObservable.notifyObservers(this)}_drawText(e,t,i,s){const r=this._currentMeasure.width;let n=this._scrollLeft;switch(this._textHorizontalAlignment){case Ow.HORIZONTAL_ALIGNMENT_LEFT:n+=0;break;case Ow.HORIZONTAL_ALIGNMENT_RIGHT:n+=r-t;break;case Ow.HORIZONTAL_ALIGNMENT_CENTER:n+=(r-t)/2}(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(s.shadowColor=this.shadowColor,s.shadowBlur=this.shadowBlur,s.shadowOffsetX=this.shadowOffsetX,s.shadowOffsetY=this.shadowOffsetY),this.outlineWidth&&s.strokeText(e,this._currentMeasure.left+n,i),s.fillText(e,n,i)}_onCopyText(e){this._isTextHighlightOn=!1;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText}_onCutText(e){if(this._highlightedText){try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),this._textHasChanged()}}_onPasteText(e){let t="";t=e.clipboardData&&-1!==e.clipboardData.types.indexOf("text/plain")?e.clipboardData.getData("text/plain"):this._host.clipboardData,this._isTextHighlightOn=!1,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex,t);const i=t.length-(this._cursorInfo.globalEndIndex-this._cursorInfo.globalStartIndex);this._cursorInfo.globalStartIndex+=i,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._textHasChanged()}_draw(e){this._computeScroll(),this._scrollLeft=this._scrollLeft??0,this._scrollTop=this._scrollTop??0,e.save(),this._applyStates(e),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._isEnabled?this._focusedBackground:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this.color&&(e.fillStyle=this.color);const t=this._currentMeasure.height,i=this._currentMeasure.width;let s=0;switch(this._textVerticalAlignment){case Ow.VERTICAL_ALIGNMENT_TOP:s=this._fontOffset.ascent;break;case Ow.VERTICAL_ALIGNMENT_BOTTOM:s=t-this._fontOffset.height*(this._lines.length-1)-this._fontOffset.descent;break;case Ow.VERTICAL_ALIGNMENT_CENTER:s=this._fontOffset.ascent+(t-this._fontOffset.height*this._lines.length)/2}e.save(),e.beginPath(),e.fillStyle=this.fontStyle,!this._textWrapper.text&&this.placeholderText&&(e.fillStyle=this._placeholderColor),e.rect(this._clipTextLeft,this._clipTextTop,this._availableWidth+2,this._availableHeight+2),e.clip(),s+=this._scrollTop;for(let t=0;tthis._clipTextLeft+this._availableWidth&&(this._scrollLeft+=this._clipTextLeft+this._availableWidth-t,t=this._clipTextLeft+this._availableWidth,this._markAsDirty());let i=this._scrollTop+this._cursorInfo.currentLineIndex*this._fontOffset.height;ithis._clipTextTop+this._availableHeight&&(this._scrollTop+=this._clipTextTop+this._availableHeight-i-this._fontOffset.height,i=this._clipTextTop+this._availableHeight-this._fontOffset.height,this._markAsDirty()),this._isTextHighlightOn||e.fillRect(t,i,2,this._fontOffset.height)}if(this._resetBlinking(),this._isTextHighlightOn){clearTimeout(this._blinkTimeout),this._highlightedText=this.text.substring(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),e.globalAlpha=this._highligherOpacity,e.fillStyle=this._textHighlightColor;const t=Math.min(this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialLineIndex),s=Math.max(this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialLineIndex);let r=this._scrollTop+t*this._fontOffset.height;for(let n=t;n<=s;n++){const o=this._lines[n];let a=this._scrollLeft;switch(this._textHorizontalAlignment){case Ow.HORIZONTAL_ALIGNMENT_LEFT:a+=0;break;case Ow.HORIZONTAL_ALIGNMENT_RIGHT:a+=i-o.width;break;case Ow.HORIZONTAL_ALIGNMENT_CENTER:a+=(i-o.width)/2}const l=n===t?this._cursorInfo.relativeStartIndex:0,h=n===s?this._cursorInfo.relativeEndIndex:o.text.length,c=e.measureText(o.text.substr(0,l)).width,u=o.text.substring(l,h),d=e.measureText(u).width;e.fillRect(a+c,r,d,this._fontOffset.height),r+=this._fontOffset.height}this._cursorInfo.globalEndIndex===this._cursorInfo.globalStartIndex&&this._resetBlinking()}}e.restore(),this._thickness&&(this._isFocused?this.focusedColor&&(e.strokeStyle=this.focusedColor):this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness))}_resetBlinking(){clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout((()=>{this._blinkIsEven=!this._blinkIsEven,this._markAsDirty()}),500)}_onPointerDown(e,t,i,s,r){return!(!super._onPointerDown(e,t,i,s,r)||!this.isReadOnly&&(this._clickedCoordinateX=t.x,this._clickedCoordinateY=t.y,this._isTextHighlightOn=!1,this._highlightedText="",this._isPointerDown=!0,this._host._capturingControl[i]=this,this._host.focusedControl===this?(clearTimeout(this._blinkTimeout),this._markAsDirty(),0):!this._isEnabled||(this._host.focusedControl=this,0)))}_onPointerMove(e,t,i,s){0===s.event.movementX&&0===s.event.movementY||(this._host.focusedControl===this&&this._isPointerDown&&!this.isReadOnly&&(this._clickedCoordinateX=t.x,this._clickedCoordinateY=t.y,this._isTextHighlightOn||(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex,this._isTextHighlightOn=!0),this._markAsDirty()),super._onPointerMove(e,t,i,s))}_updateCursorPosition(){if(this._isFocused)if(!this._textWrapper.text&&this.placeholderText)this._cursorInfo.currentLineIndex=0,this._cursorInfo.globalStartIndex=0,this._cursorInfo.globalEndIndex=0,this._cursorInfo.relativeStartIndex=0,this._cursorInfo.relativeEndIndex=0;else if(this._clickedCoordinateX&&this._clickedCoordinateY){this._isTextHighlightOn||(this._cursorInfo={globalStartIndex:0,globalEndIndex:0,relativeStartIndex:0,relativeEndIndex:0,currentLineIndex:0});let e=0,t=0;const i=this._clickedCoordinateY-this._scrollTop,s=Math.floor(i/this._fontOffset.height);this._cursorInfo.currentLineIndex=Math.min(Math.max(s,0),this._lines.length-1);let r=0;const n=this._clickedCoordinateX-(this._scrollLeft??0);let o=0;for(let t=0;tt;)t++,o=Math.abs(n-r),r=this._contextForBreakLines.measureText(this._lines[this._cursorInfo.currentLineIndex].text.substr(0,t)).width;Math.abs(n-r)>o&&t>0&&t--,e+=t,this._isTextHighlightOn?e=this._highlightCursorInfo.initialStartIndex){for(;t+e<=this._cursorInfo.globalEndIndex;)t+=e,this._cursorInfo.currentLineIndex0&&this._textWrapper.isWord(this._cursorInfo.globalStartIndex-1)?--this._cursorInfo.globalStartIndex:0,i=this._cursorInfo.globalEndIndexthis._markAsDirty()))),this._connectedControl=e,this._markAsDirty())}get x1(){return this._x1.toString(this._host)}set x1(e){this._x1.toString(this._host)!==e&&this._x1.fromString(e)&&this._markAsDirty()}get y1(){return this._y1.toString(this._host)}set y1(e){this._y1.toString(this._host)!==e&&this._y1.fromString(e)&&this._markAsDirty()}get x2(){return this._x2.toString(this._host)}set x2(e){this._x2.toString(this._host)!==e&&this._x2.fromString(e)&&this._markAsDirty()}get y2(){return this._y2.toString(this._host)}set y2(e){this._y2.toString(this._host)!==e&&this._y2.fromString(e)&&this._markAsDirty()}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth!==e&&(this._lineWidth=e,this._markAsDirty())}set horizontalAlignment(e){}set verticalAlignment(e){}get _effectiveX2(){return(this._connectedControl?this._connectedControl.centerX:0)+this._x2.getValue(this._host)}get _effectiveY2(){return(this._connectedControl?this._connectedControl.centerY:0)+this._y2.getValue(this._host)}constructor(e){super(e),this.name=e,this._lineWidth=1,this._x1=new yw(0),this._y1=new yw(0),this._x2=new yw(0),this._y2=new yw(0),this._dash=new Array,this._automaticSize=!0,this.isHitTestVisible=!1,this._horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP}_getTypeName(){return"Line"}_draw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._applyStates(e),e.strokeStyle=this._getColor(e),e.lineWidth=this._lineWidth,e.setLineDash(this._dash),e.beginPath(),e.moveTo(this._cachedParentMeasure.left+this._x1.getValue(this._host),this._cachedParentMeasure.top+this._y1.getValue(this._host)),e.lineTo(this._cachedParentMeasure.left+this._effectiveX2,this._cachedParentMeasure.top+this._effectiveY2),e.stroke(),e.restore()}_measure(){this._currentMeasure.width=Math.abs(this._x1.getValue(this._host)-this._effectiveX2)+this._lineWidth,this._currentMeasure.height=Math.abs(this._y1.getValue(this._host)-this._effectiveY2)+this._lineWidth}_computeAlignment(e){this._currentMeasure.left=e.left+Math.min(this._x1.getValue(this._host),this._effectiveX2)-this._lineWidth/2,this._currentMeasure.top=e.top+Math.min(this._y1.getValue(this._host),this._effectiveY2)-this._lineWidth/2}moveToVector3(e,t,i=!1){if(!this._host||this.parent!==this._host._rootContainer)return void Ds.Error("Cannot move a control to a vector3 if the control is not at root level");const s=this._host._getGlobalViewport(),r=_e.Project(e,me.IdentityReadOnly,t.getTransformMatrix(),s);this._moveToProjectedPosition(r,i),r.z<0||r.z>1?this.notRenderable=!0:this.notRenderable=!1}_moveToProjectedPosition(e,t=!1){const i=e.x+this._linkOffsetX.getValue(this._host)+"px",s=e.y+this._linkOffsetY.getValue(this._host)+"px";t?(this.x2=i,this.y2=s,this._x2.ignoreAdaptiveScaling=!0,this._y2.ignoreAdaptiveScaling=!0):(this.x1=i,this.y1=s,this._x1.ignoreAdaptiveScaling=!0,this._y1.ignoreAdaptiveScaling=!0)}}Ze([rt()],jw.prototype,"dash",null),Ze([rt()],jw.prototype,"x1",null),Ze([rt()],jw.prototype,"y1",null),Ze([rt()],jw.prototype,"x2",null),Ze([rt()],jw.prototype,"y2",null),Ze([rt()],jw.prototype,"lineWidth",null),z("BABYLON.GUI.Line",jw);class Kw{constructor(e){this._multiLine=e,this._x=new yw(0),this._y=new yw(0),this._point=new _e(0,0,0)}get x(){return this._x.toString(this._multiLine._host)}set x(e){this._x.toString(this._multiLine._host)!==e&&this._x.fromString(e)&&this._multiLine._markAsDirty()}get y(){return this._y.toString(this._multiLine._host)}set y(e){this._y.toString(this._multiLine._host)!==e&&this._y.fromString(e)&&this._multiLine._markAsDirty()}get control(){return this._control}set control(e){this._control!==e&&(this._control&&this._controlObserver&&(this._control.onDirtyObservable.remove(this._controlObserver),this._controlObserver=null),this._control=e,this._control&&(this._controlObserver=this._control.onDirtyObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())}get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh&&this._meshObserver&&this._mesh.getScene().onAfterCameraRenderObservable.remove(this._meshObserver),this._mesh=e,this._mesh&&(this._meshObserver=this._mesh.getScene().onAfterCameraRenderObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())}resetLinks(){this.control=null,this.mesh=null}translate(){return this._point=this._translatePoint(),this._point}_translatePoint(){if(null!=this._mesh)return this._multiLine._host.getProjectedPositionWithZ(this._mesh.getBoundingInfo().boundingSphere.center,this._mesh.getWorldMatrix());if(null!=this._control)return new _e(this._control.centerX,this._control.centerY,1-J);{const e=this._multiLine._host,t=this._x.getValueInPixel(e,Number(e._canvas.width)),i=this._y.getValueInPixel(e,Number(e._canvas.height));return new _e(t,i,1-J)}}dispose(){this.resetLinks()}}class $w extends Ow{constructor(e){super(e),this.name=e,this._lineWidth=1,this.onPointUpdate=()=>{this._markAsDirty()},this._automaticSize=!0,this.isHitTestVisible=!1,this._horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,this._dash=[],this._points=[]}get dash(){return this._dash}set dash(e){this._dash!==e&&(this._dash=e,this._markAsDirty())}getAt(e){return this._points[e]||(this._points[e]=new Kw(this)),this._points[e]}add(...e){return e.map((e=>this.push(e)))}push(e){const t=this.getAt(this._points.length);return null==e||(e instanceof _o?t.mesh=e:e instanceof Ow?t.control=e:null!=e.x&&null!=e.y&&(t.x=e.x,t.y=e.y)),t}remove(e){let t;if(e instanceof Kw){if(t=this._points.indexOf(e),-1===t)return}else t=e;const i=this._points[t];i&&(i.dispose(),this._points.splice(t,1))}reset(){for(;this._points.length>0;)this.remove(this._points.length-1)}resetLinks(){this._points.forEach((e=>{null!=e&&e.resetLinks()}))}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth!==e&&(this._lineWidth=e,this._markAsDirty())}set horizontalAlignment(e){}set verticalAlignment(e){}_getTypeName(){return"MultiLine"}_draw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._applyStates(e),e.strokeStyle=this.color,e.lineWidth=this._lineWidth,e.setLineDash(this._dash),e.beginPath();let t,i=!0;this._points.forEach((s=>{s&&(i?(e.moveTo(s._point.x,s._point.y),i=!1):s._point.z<1&&t.z<1?e.lineTo(s._point.x,s._point.y):e.moveTo(s._point.x,s._point.y),t=s._point)})),e.stroke(),e.restore()}_additionalProcessing(){this._minX=null,this._minY=null,this._maxX=null,this._maxY=null,this._points.forEach((e=>{e&&(e.translate(),(null==this._minX||e._point.xthis._maxX)&&(this._maxX=e._point.x),(null==this._maxY||e._point.y>this._maxY)&&(this._maxY=e._point.y))})),null==this._minX&&(this._minX=0),null==this._minY&&(this._minY=0),null==this._maxX&&(this._maxX=0),null==this._maxY&&(this._maxY=0)}_measure(){null!=this._minX&&null!=this._maxX&&null!=this._minY&&null!=this._maxY&&(this._currentMeasure.width=Math.abs(this._maxX-this._minX)+this._lineWidth,this._currentMeasure.height=Math.abs(this._maxY-this._minY)+this._lineWidth)}_computeAlignment(){null!=this._minX&&null!=this._minY&&(this._currentMeasure.left=this._minX-this._lineWidth/2,this._currentMeasure.top=this._minY-this._lineWidth/2)}dispose(){this.reset(),super.dispose()}}Ze([rt()],$w.prototype,"dash",null),z("BABYLON.GUI.MultiLine",$w);class qw extends Ow{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get checkSizeRatio(){return this._checkSizeRatio}set checkSizeRatio(e){e=Math.max(Math.min(1,e),0),this._checkSizeRatio!==e&&(this._checkSizeRatio=e,this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get isChecked(){return this._isChecked}set isChecked(e){this._isChecked!==e&&(this._isChecked=e,this._markAsDirty(),this.onIsCheckedChangedObservable.notifyObservers(e),this._isChecked&&this._host&&this._host.executeOnAllControls((e=>{if(e===this)return;if(void 0===e.group)return;const t=e;t.group===this.group&&(t.isChecked=!1)})))}constructor(e){super(e),this.name=e,this._isChecked=!1,this._background="black",this._checkSizeRatio=.8,this._thickness=1,this.group="",this.onIsCheckedChangedObservable=new K,this.isPointerBlocker=!0}_getTypeName(){return"RadioButton"}_draw(e){e.save(),this._applyStates(e);const t=this._currentMeasure.width-this._thickness,i=this._currentMeasure.height-this._thickness;if((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),Ow.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,e),e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fill(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),e.strokeStyle=this.color,e.lineWidth=this._thickness,e.stroke(),this._isChecked){e.fillStyle=this._isEnabled?this.color:this._disabledColor;const s=t*this._checkSizeRatio,r=i*this._checkSizeRatio;Ow.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,s/2-this._thickness/2,r/2-this._thickness/2,e),e.fill()}e.restore()}_onPointerDown(e,t,i,s,r){return!!super._onPointerDown(e,t,i,s,r)&&(this.isReadOnly||this.isChecked||(this.isChecked=!0),!0)}static AddRadioButtonWithHeader(e,t,i,s){const r=new kw;r.isVertical=!1,r.height="30px";const n=new qw;n.width="20px",n.height="20px",n.isChecked=i,n.color="green",n.group=t,n.onIsCheckedChangedObservable.add((e=>s(n,e))),r.addControl(n);const o=new Fw;return o.text=e,o.width="180px",o.paddingLeft="5px",o.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,o.color="white",r.addControl(o),r}}Ze([rt()],qw.prototype,"thickness",null),Ze([rt()],qw.prototype,"group",void 0),Ze([rt()],qw.prototype,"checkSizeRatio",null),Ze([rt()],qw.prototype,"background",null),Ze([rt()],qw.prototype,"isChecked",null),z("BABYLON.GUI.RadioButton",qw);class Zw extends Ow{get displayThumb(){return this._displayThumb}set displayThumb(e){this._displayThumb!==e&&(this._displayThumb=e,this._markAsDirty())}get step(){return this._step}set step(e){this._step!==e&&(this._step=e,this._markAsDirty())}get barOffset(){return this._barOffset.toString(this._host)}get barOffsetInPixels(){return this._barOffset.getValueInPixel(this._host,this._cachedParentMeasure.width)}set barOffset(e){this._barOffset.toString(this._host)!==e&&this._barOffset.fromString(e)&&this._markAsDirty()}get thumbWidth(){return this._thumbWidth.toString(this._host)}get thumbWidthInPixels(){return this._thumbWidth.getValueInPixel(this._host,this._cachedParentMeasure.width)}set thumbWidth(e){this._thumbWidth.toString(this._host)!==e&&this._thumbWidth.fromString(e)&&this._markAsDirty()}get minimum(){return this._minimum}set minimum(e){this._minimum!==e&&(this._minimum=e,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))}get maximum(){return this._maximum}set maximum(e){this._maximum!==e&&(this._maximum=e,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))}get value(){return this._value}set value(e){e=Math.max(Math.min(e,this._maximum),this._minimum),this._value!==e&&(this._value=e,this._markAsDirty(),this.onValueChangedObservable.notifyObservers(this._value))}get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,this._markAsDirty())}get isThumbClamped(){return this._isThumbClamped}set isThumbClamped(e){this._isThumbClamped!==e&&(this._isThumbClamped=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thumbWidth=new yw(20,yw.UNITMODE_PIXEL,!1),this._minimum=0,this._maximum=100,this._value=50,this._isVertical=!1,this._barOffset=new yw(5,yw.UNITMODE_PIXEL,!1),this._isThumbClamped=!1,this._displayThumb=!0,this._step=0,this._lastPointerDownId=-1,this._effectiveBarOffset=0,this.onValueChangedObservable=new K,this._pointerIsDown=!1,this.isPointerBlocker=!0}_getTypeName(){return"BaseSlider"}_getThumbPosition(){return this.isVertical?(this.maximum-this.value)/(this.maximum-this.minimum)*this._backgroundBoxLength:(this.value-this.minimum)/(this.maximum-this.minimum)*this._backgroundBoxLength}_getThumbThickness(e){let t=0;switch(e){case"circle":t=this._thumbWidth.isPixel?Math.max(this._thumbWidth.getValue(this._host),this._backgroundBoxThickness):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host);break;case"rectangle":t=this._thumbWidth.isPixel?Math.min(this._thumbWidth.getValue(this._host),this._backgroundBoxThickness):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host)}return t}_prepareRenderingData(e){this._effectiveBarOffset=0,this._renderLeft=this._currentMeasure.left,this._renderTop=this._currentMeasure.top,this._renderWidth=this._currentMeasure.width,this._renderHeight=this._currentMeasure.height,this._backgroundBoxLength=Math.max(this._currentMeasure.width,this._currentMeasure.height),this._backgroundBoxThickness=Math.min(this._currentMeasure.width,this._currentMeasure.height),this._effectiveThumbThickness=this._getThumbThickness(e),this.displayThumb&&(this._backgroundBoxLength-=this._effectiveThumbThickness),this.isVertical&&this._currentMeasure.height=this._selectors.length))return this._selectors[e]}removeSelector(e){e<0||e>=this._selectors.length||(this._groupPanel.removeControl(this._selectors[e]),this._selectors.splice(e,1))}}class tN extends eN{addCheckbox(e,t=(e=>{}),i=!1){i=i||!1;const s=new Vw;s.width="20px",s.height="20px",s.color="#364249",s.background="#CCCCCC",s.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,s.onIsCheckedChangedObservable.add((function(e){t(e)}));const r=Ow.AddHeader(s,e,"200px",{isHorizontal:!0,controlFirst:!0});r.height="30px",r.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,r.left="4px",this.groupPanel.addControl(r),this.selectors.push(r),s.isChecked=i,this.groupPanel.parent&&this.groupPanel.parent.parent&&(s.color=this.groupPanel.parent.parent.buttonColor,s.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[1].text=t}_setSelectorLabelColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[0].background=t}}class iN extends eN{constructor(){super(...arguments),this._selectNb=0}addRadio(e,t=(e=>{}),i=!1){const s=this._selectNb++,r=new qw;r.name=e,r.width="20px",r.height="20px",r.color="#364249",r.background="#CCCCCC",r.group=this.name,r.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,r.onIsCheckedChangedObservable.add((function(e){e&&t(s)}));const n=Ow.AddHeader(r,e,"200px",{isHorizontal:!0,controlFirst:!0});n.height="30px",n.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,n.left="4px",this.groupPanel.addControl(n),this.selectors.push(n),r.isChecked=i,this.groupPanel.parent&&this.groupPanel.parent.parent&&(r.color=this.groupPanel.parent.parent.buttonColor,r.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[1].text=t}_setSelectorLabelColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[0].background=t}}class sN extends eN{addSlider(e,t=(e=>{}),i="Units",s=0,r=0,n=0,o=(e=>0|e)){const a=new Jw;a.name=i,a.value=n,a.minimum=s,a.maximum=r,a.width=.9,a.height="20px",a.color="#364249",a.background="#CCCCCC",a.borderColor="black",a.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,a.left="4px",a.paddingBottom="4px",a.onValueChangedObservable.add((function(e){a.parent.children[0].text=a.parent.children[0].name+": "+o(e)+" "+a.name,t(e)}));const l=Ow.AddHeader(a,e+": "+o(n)+" "+i,"30px",{isHorizontal:!1,controlFirst:!1});l.height="60px",l.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,l.left="4px",l.children[0].name=e,this.groupPanel.addControl(l),this.selectors.push(l),this.groupPanel.parent&&this.groupPanel.parent.parent&&(a.color=this.groupPanel.parent.parent.buttonColor,a.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[0].name=t,this.selectors[e].children[0].text=t+": "+this.selectors[e].children[1].value+" "+this.selectors[e].children[1].name}_setSelectorLabelColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[1].background=t}}class rN extends ww{constructor(e,t=[]){if(super(e),this.name=e,this.groups=t,this._buttonColor="#364249",this._buttonBackground="#CCCCCC",this._headerColor="black",this._barColor="white",this._barHeight="2px",this._spacerHeight="20px",this._bars=new Array,this._groups=t,this.thickness=2,this._panel=new kw,this._panel.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,this._panel.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._panel.top=5,this._panel.left=5,this._panel.width=.95,t.length>0){for(let e=0;e0&&this._addSpacer(),this._panel.addControl(e.groupPanel),this._groups.push(e),e.groupPanel.children[0].color=this._headerColor;for(let t=0;t=this._groups.length)return;const t=this._groups[e];this._panel.removeControl(t.groupPanel),this._groups.splice(e,1),e=this._groups.length||(this._groups[t].groupPanel.children[0].text=e)}relabel(e,t,i){if(t<0||t>=this._groups.length)return;const s=this._groups[t];i<0||i>=s.selectors.length||s._setSelectorLabel(i,e)}removeFromGroupSelector(e,t){if(e<0||e>=this._groups.length)return;const i=this._groups[e];t<0||t>=i.selectors.length||i.removeSelector(t)}addToGroupCheckbox(e,t,i=(()=>{}),s=!1){e<0||e>=this._groups.length||this._groups[e].addCheckbox(t,i,s)}addToGroupRadio(e,t,i=(()=>{}),s=!1){e<0||e>=this._groups.length||this._groups[e].addRadio(t,i,s)}addToGroupSlider(e,t,i=(()=>{}),s="Units",r=0,n=0,o=0,a=(e=>0|e)){e<0||e>=this._groups.length||this._groups[e].addSlider(t,i,s,r,n,o,a)}}class nN extends Dw{get freezeControls(){return this._freezeControls}set freezeControls(e){if(this._freezeControls===e)return;e||this._restoreMeasures(),this._freezeControls=!1;const t=this.host.getSize(),i=t.width,s=t.height,r=this.host.getContext(),n=new Pw(0,0,i,s);this.host._numLayoutCalls=0,this.host._rootContainer._layout(n,r),e&&(this._updateMeasures(),this._useBuckets()&&this._makeBuckets()),this._freezeControls=e,this.host.markAsDirty()}get bucketWidth(){return this._bucketWidth}get bucketHeight(){return this._bucketHeight}setBucketSizes(e,t){this._bucketWidth=e,this._bucketHeight=t,this._useBuckets()?this._freezeControls&&this._makeBuckets():this._buckets={}}_useBuckets(){return this._bucketWidth>0&&this._bucketHeight>0}_makeBuckets(){this._buckets={},this._bucketLen=Math.ceil(this.widthInPixels/this._bucketWidth),this._dispatchInBuckets(this._children),this._oldLeft=null,this._oldTop=null}_dispatchInBuckets(e){for(let t=0;t0&&this._dispatchInBuckets(i._children)}}_updateMeasures(){const e=0|this.leftInPixels,t=0|this.topInPixels;this._measureForChildren.left-=e,this._measureForChildren.top-=t,this._currentMeasure.left-=e,this._currentMeasure.top-=t,this._customData.origLeftForChildren=this._measureForChildren.left,this._customData.origTopForChildren=this._measureForChildren.top,this._customData.origLeft=this._currentMeasure.left,this._customData.origTop=this._currentMeasure.top,this._updateChildrenMeasures(this._children,e,t)}_updateChildrenMeasures(e,t,i){for(let s=0;s0&&this._updateChildrenMeasures(r._children,t,i)}}_restoreMeasures(){const e=0|this.leftInPixels,t=0|this.topInPixels;this._measureForChildren.left=this._customData.origLeftForChildren+e,this._measureForChildren.top=this._customData.origTopForChildren+t,this._currentMeasure.left=this._customData.origLeft+e,this._currentMeasure.top=this._customData.origTop+t}constructor(e){super(e),this._freezeControls=!1,this._bucketWidth=0,this._bucketHeight=0,this._buckets={}}_getTypeName(){return"ScrollViewerWindow"}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._parentMeasure=e,this._measureForChildren.left=this._currentMeasure.left,this._measureForChildren.top=this._currentMeasure.top,this._measureForChildren.width=e.width,this._measureForChildren.height=e.height}_layout(e,t){return this._freezeControls?(this.invalidateRect(),!1):super._layout(e,t)}_scrollChildren(e,t,i){for(let s=0;s0&&this._scrollChildren(r._children,t,i)}}_scrollChildrenWithBuckets(e,t,i,s){const r=Math.max(0,Math.floor(-e/this._bucketWidth)),n=Math.floor((-e+this._parentMeasure.width-1)/this._bucketWidth),o=Math.floor((-t+this._parentMeasure.height-1)/this._bucketHeight);let a=Math.max(0,Math.floor(-t/this._bucketHeight));for(;a<=o;){for(let e=r;e<=n;++e){const t=a*this._bucketLen+e,r=this._buckets[t];if(r)for(let e=0;ethis._tempMeasure.left+this._tempMeasure.width||tthis._tempMeasure.top+this._tempMeasure.height)&&(this.isVertical?this.value=this.minimum+(1-(t-this._currentMeasure.top)/this._currentMeasure.height)*(this.maximum-this.minimum):this.value=this.minimum+(e-this._currentMeasure.left)/this._currentMeasure.width*(this.maximum-this.minimum)));let s=0;s=this.isVertical?-(t-this._originY)/(this._currentMeasure.height-this._effectiveThumbThickness):(e-this._originX)/(this._currentMeasure.width-this._effectiveThumbThickness),this.value+=i*s*(this.maximum-this.minimum),this._originX=e,this._originY=t}_onPointerDown(e,t,i,s,r){return this._first=!0,super._onPointerDown(e,t,i,s,r)}serialize(e){super.serialize(e),this.backgroundGradient&&(e.backgroundGradient={},this.backgroundGradient.serialize(e.backgroundGradient))}_parseFromContent(e,t){if(super._parseFromContent(e,t),e.backgroundGradient){const t=Ds.Instantiate("BABYLON.GUI."+e.backgroundGradient.className);this.backgroundGradient=new t,this.backgroundGradient.parse(e.backgroundGradient)}}}Ze([rt()],oN.prototype,"borderColor",null),Ze([rt()],oN.prototype,"background",null),Ze([rt()],oN.prototype,"invertScrollDirection",null),z("BABYLON.GUI.Scrollbar",oN);class aN extends Zw{get invertScrollDirection(){return this._invertScrollDirection}set invertScrollDirection(e){this._invertScrollDirection=e}get backgroundImage(){return this._backgroundBaseImage}set backgroundImage(e){this._backgroundBaseImage!==e&&(this._backgroundBaseImage=e,this.isVertical&&0!==this.num90RotationInVerticalMode?e.isLoaded?(this._backgroundImage=e._rotate90(this.num90RotationInVerticalMode,!0),this._markAsDirty()):e.onImageLoadedObservable.addOnce((()=>{const t=e._rotate90(this.num90RotationInVerticalMode,!0);this._backgroundImage=t,t.isLoaded||t.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()})):(this._backgroundImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()))}get thumbImage(){return this._thumbBaseImage}set thumbImage(e){this._thumbBaseImage!==e&&(this._thumbBaseImage=e,this.isVertical&&0!==this.num90RotationInVerticalMode?e.isLoaded?(this._thumbImage=e._rotate90(-this.num90RotationInVerticalMode,!0),this._markAsDirty()):e.onImageLoadedObservable.addOnce((()=>{const t=e._rotate90(-this.num90RotationInVerticalMode,!0);this._thumbImage=t,t.isLoaded||t.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()})):(this._thumbImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()))}get thumbLength(){return this._thumbLength}set thumbLength(e){this._thumbLength!==e&&(this._thumbLength=e,this._markAsDirty())}get thumbHeight(){return this._thumbHeight}set thumbHeight(e){this._thumbLength!==e&&(this._thumbHeight=e,this._markAsDirty())}get barImageHeight(){return this._barImageHeight}set barImageHeight(e){this._barImageHeight!==e&&(this._barImageHeight=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thumbLength=.5,this._thumbHeight=1,this._barImageHeight=1,this._tempMeasure=new Pw(0,0,0,0),this._invertScrollDirection=!1,this.num90RotationInVerticalMode=1}_getTypeName(){return"ImageScrollBar"}_getThumbThickness(){let e=0;return e=this._thumbWidth.isPixel?this._thumbWidth.getValue(this._host):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host),e}_draw(e){e.save(),this._applyStates(e),this._prepareRenderingData("rectangle");const t=this._getThumbPosition(),i=this._renderLeft,s=this._renderTop,r=this._renderWidth,n=this._renderHeight;this._backgroundImage&&(this._tempMeasure.copyFromFloats(i,s,r,n),this.isVertical?(this._tempMeasure.copyFromFloats(i+r*(1-this._barImageHeight)*.5,this._currentMeasure.top,r*this._barImageHeight,n),this._tempMeasure.height+=this._effectiveThumbThickness,this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure)):(this._tempMeasure.copyFromFloats(this._currentMeasure.left,s+n*(1-this._barImageHeight)*.5,r,n*this._barImageHeight),this._tempMeasure.width+=this._effectiveThumbThickness,this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure)),this._backgroundImage._draw(e)),this.isVertical?this._tempMeasure.copyFromFloats(i-this._effectiveBarOffset+this._currentMeasure.width*(1-this._thumbHeight)*.5,this._currentMeasure.top+t,this._currentMeasure.width*this._thumbHeight,this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(this._currentMeasure.left+t,this._currentMeasure.top+this._currentMeasure.height*(1-this._thumbHeight)*.5,this._effectiveThumbThickness,this._currentMeasure.height*this._thumbHeight),this._thumbImage&&(this._thumbImage._currentMeasure.copyFrom(this._tempMeasure),this._thumbImage._draw(e)),e.restore()}_updateValueFromPointer(e,t){0!=this.rotation&&(this._invertTransformMatrix.transformCoordinates(e,t,this._transformedPosition),e=this._transformedPosition.x,t=this._transformedPosition.y);const i=this._invertScrollDirection?-1:1;this._first&&(this._first=!1,this._originX=e,this._originY=t,(ethis._tempMeasure.left+this._tempMeasure.width||tthis._tempMeasure.top+this._tempMeasure.height)&&(this.isVertical?this.value=this.minimum+(1-(t-this._currentMeasure.top)/this._currentMeasure.height)*(this.maximum-this.minimum):this.value=this.minimum+(e-this._currentMeasure.left)/this._currentMeasure.width*(this.maximum-this.minimum)));let s=0;s=this.isVertical?-(t-this._originY)/(this._currentMeasure.height-this._effectiveThumbThickness):(e-this._originX)/(this._currentMeasure.width-this._effectiveThumbThickness),this.value+=i*s*(this.maximum-this.minimum),this._originX=e,this._originY=t}_onPointerDown(e,t,i,s,r){return this._first=!0,super._onPointerDown(e,t,i,s,r)}}Ze([rt()],aN.prototype,"num90RotationInVerticalMode",void 0),Ze([rt()],aN.prototype,"invertScrollDirection",null);class lN extends ww{get horizontalBar(){return this._horizontalBar}get verticalBar(){return this._verticalBar}addControl(e){return e?(this._window.addControl(e),this):this}removeControl(e){return this._window.removeControl(e),this}get children(){return this._window.children}_flagDescendantsAsMatrixDirty(){for(const e of this._children)e._markMatrixAsDirty()}get freezeControls(){return this._window.freezeControls}set freezeControls(e){this._window.freezeControls=e}get bucketWidth(){return this._window.bucketWidth}get bucketHeight(){return this._window.bucketHeight}setBucketSizes(e,t){this._window.setBucketSizes(e,t)}get forceHorizontalBar(){return this._forceHorizontalBar}set forceHorizontalBar(e){this._grid.setRowDefinition(1,e?this._barSize:0,!0),this._horizontalBar.isVisible=e,this._forceHorizontalBar=e}get forceVerticalBar(){return this._forceVerticalBar}set forceVerticalBar(e){this._grid.setColumnDefinition(1,e?this._barSize:0,!0),this._verticalBar.isVisible=e,this._forceVerticalBar=e}constructor(e,t){super(e),this._barSize=20,this._pointerIsOver=!1,this._wheelPrecision=.05,this._thumbLength=.5,this._thumbHeight=1,this._barImageHeight=1,this._horizontalBarImageHeight=1,this._verticalBarImageHeight=1,this._oldWindowContentsWidth=0,this._oldWindowContentsHeight=0,this._forceHorizontalBar=!1,this._forceVerticalBar=!1,this._useImageBar=t||!1,this.onDirtyObservable.add((()=>{this._horizontalBarSpace.color=this.color,this._verticalBarSpace.color=this.color,this._dragSpace.color=this.color})),this.onPointerEnterObservable.add((()=>{this._pointerIsOver=!0})),this.onPointerOutObservable.add((()=>{this._pointerIsOver=!1})),this._grid=new zw,this._useImageBar?(this._horizontalBar=new aN,this._verticalBar=new aN):(this._horizontalBar=new oN,this._verticalBar=new oN),this._window=new nN("scrollViewer_window"),this._window.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._window.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,this._grid.addColumnDefinition(1),this._grid.addColumnDefinition(0,!0),this._grid.addRowDefinition(1),this._grid.addRowDefinition(0,!0),super.addControl(this._grid),this._grid.addControl(this._window,0,0),this._verticalBarSpace=new ww,this._verticalBarSpace.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._verticalBarSpace.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,this._verticalBarSpace.thickness=1,this._grid.addControl(this._verticalBarSpace,0,1),this._addBar(this._verticalBar,this._verticalBarSpace,!0,Math.PI),this._horizontalBarSpace=new ww,this._horizontalBarSpace.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._horizontalBarSpace.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,this._horizontalBarSpace.thickness=1,this._grid.addControl(this._horizontalBarSpace,1,0),this._addBar(this._horizontalBar,this._horizontalBarSpace,!1,0),this._dragSpace=new ww,this._dragSpace.thickness=1,this._grid.addControl(this._dragSpace,1,1),this._grid.clipChildren=!1,this._useImageBar||(this.barColor="grey",this.barBackground="transparent")}resetWindow(){this._window.width="100%",this._window.height="100%"}_getTypeName(){return"ScrollViewer"}_buildClientSizes(){const e=this.host.idealRatio;this._window.parentClientWidth=this._currentMeasure.width-(this._verticalBar.isVisible||this.forceVerticalBar?this._barSize*e:0)-2*this.thickness,this._window.parentClientHeight=this._currentMeasure.height-(this._horizontalBar.isVisible||this.forceHorizontalBar?this._barSize*e:0)-2*this.thickness,this._clientWidth=this._window.parentClientWidth,this._clientHeight=this._window.parentClientHeight}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._buildClientSizes()}_postMeasure(){super._postMeasure(),this._updateScroller(),this._setWindowPosition(!1)}get wheelPrecision(){return this._wheelPrecision}set wheelPrecision(e){this._wheelPrecision!==e&&(e<0&&(e=0),e>1&&(e=1),this._wheelPrecision=e)}get scrollBackground(){return this._horizontalBarSpace.background}set scrollBackground(e){this._horizontalBarSpace.background!==e&&(this._horizontalBarSpace.background=e,this._verticalBarSpace.background=e)}get barColor(){return this._barColor}set barColor(e){this._barColor!==e&&(this._barColor=e,this._horizontalBar.color=e,this._verticalBar.color=e)}get thumbImage(){return this._barImage}set thumbImage(e){if(this._barImage===e)return;this._barImage=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbImage=e,i.thumbImage=e}get horizontalThumbImage(){return this._horizontalBarImage}set horizontalThumbImage(e){this._horizontalBarImage!==e&&(this._horizontalBarImage=e,this._horizontalBar.thumbImage=e)}get verticalThumbImage(){return this._verticalBarImage}set verticalThumbImage(e){this._verticalBarImage!==e&&(this._verticalBarImage=e,this._verticalBar.thumbImage=e)}get barSize(){return this._barSize}set barSize(e){this._barSize!==e&&(this._barSize=e,this._markAsDirty(),this._horizontalBar.isVisible&&this._grid.setRowDefinition(1,this._barSize,!0),this._verticalBar.isVisible&&this._grid.setColumnDefinition(1,this._barSize,!0))}get thumbLength(){return this._thumbLength}set thumbLength(e){if(this._thumbLength===e)return;e<=0&&(e=.1),e>1&&(e=1),this._thumbLength=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbLength=e,i.thumbLength=e,this._markAsDirty()}get thumbHeight(){return this._thumbHeight}set thumbHeight(e){if(this._thumbHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._thumbHeight=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbHeight=e,i.thumbHeight=e,this._markAsDirty()}get barImageHeight(){return this._barImageHeight}set barImageHeight(e){if(this._barImageHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._barImageHeight=e;const t=this._horizontalBar,i=this._verticalBar;t.barImageHeight=e,i.barImageHeight=e,this._markAsDirty()}get horizontalBarImageHeight(){return this._horizontalBarImageHeight}set horizontalBarImageHeight(e){this._horizontalBarImageHeight!==e&&(e<=0&&(e=.1),e>1&&(e=1),this._horizontalBarImageHeight=e,this._horizontalBar.barImageHeight=e,this._markAsDirty())}get verticalBarImageHeight(){return this._verticalBarImageHeight}set verticalBarImageHeight(e){this._verticalBarImageHeight!==e&&(e<=0&&(e=.1),e>1&&(e=1),this._verticalBarImageHeight=e,this._verticalBar.barImageHeight=e,this._markAsDirty())}get barBackground(){return this._barBackground}set barBackground(e){if(this._barBackground===e)return;this._barBackground=e;const t=this._horizontalBar,i=this._verticalBar;t.background=e,i.background=e,this._dragSpace.background=e}get barImage(){return this._barBackgroundImage}set barImage(e){this._barBackgroundImage=e;const t=this._horizontalBar,i=this._verticalBar;t.backgroundImage=e,i.backgroundImage=e}get horizontalBarImage(){return this._horizontalBarBackgroundImage}set horizontalBarImage(e){this._horizontalBarBackgroundImage=e,this._horizontalBar.backgroundImage=e}get verticalBarImage(){return this._verticalBarBackgroundImage}set verticalBarImage(e){this._verticalBarBackgroundImage=e,this._verticalBar.backgroundImage=e}_setWindowPosition(e=!0){const t=this.host.idealRatio,i=this._window._currentMeasure.width,s=this._window._currentMeasure.height;if(!e&&this._oldWindowContentsWidth===i&&this._oldWindowContentsHeight===s)return;this._oldWindowContentsWidth=i,this._oldWindowContentsHeight=s;const r=this._clientWidth-i,n=this._clientHeight-s,o=this._horizontalBar.value/t*r+"px",a=this._verticalBar.value/t*n+"px";o!==this._window.left&&(this._window.left=o,this.freezeControls||(this._rebuildLayout=!0)),a!==this._window.top&&(this._window.top=a,this.freezeControls||(this._rebuildLayout=!0))}_updateScroller(){const e=this._window._currentMeasure.width,t=this._window._currentMeasure.height;this._horizontalBar.isVisible&&e<=this._clientWidth&&!this.forceHorizontalBar?(this._grid.setRowDefinition(1,0,!0),this._horizontalBar.isVisible=!1,this._horizontalBar.value=0,this._rebuildLayout=!0):!this._horizontalBar.isVisible&&(e>this._clientWidth||this.forceHorizontalBar)&&(this._grid.setRowDefinition(1,this._barSize,!0),this._horizontalBar.isVisible=!0,this._rebuildLayout=!0),this._verticalBar.isVisible&&t<=this._clientHeight&&!this.forceVerticalBar?(this._grid.setColumnDefinition(1,0,!0),this._verticalBar.isVisible=!1,this._verticalBar.value=0,this._rebuildLayout=!0):!this._verticalBar.isVisible&&(t>this._clientHeight||this.forceVerticalBar)&&(this._grid.setColumnDefinition(1,this._barSize,!0),this._verticalBar.isVisible=!0,this._rebuildLayout=!0),this._buildClientSizes();const i=this.host.idealRatio;this._horizontalBar.thumbWidth=.9*this._thumbLength*(this._clientWidth/i)+"px",this._verticalBar.thumbWidth=.9*this._thumbLength*(this._clientHeight/i)+"px"}_link(e){super._link(e),this._attachWheel()}_addBar(e,t,i,s){e.paddingLeft=0,e.width="100%",e.height="100%",e.barOffset=0,e.value=0,e.maximum=1,e.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_CENTER,e.verticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,e.isVertical=i,e.rotation=s,e.isVisible=!1,t.addControl(e),e.onValueChangedObservable.add((()=>{this._setWindowPosition()}))}_attachWheel(){this._host&&!this._onWheelObserver&&(this._onWheelObserver=this.onWheelObservable.add((e=>{this._pointerIsOver&&!this.isReadOnly&&(1==this._verticalBar.isVisible&&(e.y<0&&this._verticalBar.value>0?this._verticalBar.value-=this._wheelPrecision:e.y>0&&this._verticalBar.value0&&this._horizontalBar.value>0&&(this._horizontalBar.value-=this._wheelPrecision)))})))}_renderHighlightSpecific(e){this.isHighlighted&&(super._renderHighlightSpecific(e),this._grid._renderHighlightSpecific(e),e.restore())}dispose(){this.onWheelObservable.remove(this._onWheelObserver),this._onWheelObserver=null,super.dispose()}}Ze([rt()],lN.prototype,"wheelPrecision",null),Ze([rt()],lN.prototype,"scrollBackground",null),Ze([rt()],lN.prototype,"barColor",null),Ze([rt()],lN.prototype,"barSize",null),Ze([rt()],lN.prototype,"barBackground",null),z("BABYLON.GUI.ScrollViewer",lN);class hN extends ww{get group(){return this._group}set group(e){this._group!==e&&(this._group=e)}get isActive(){return this._isActive}set isActive(e){this._isActive!==e&&(this._isActive=e,this._isActive?this.toActiveAnimation?.():this.toInactiveAnimation?.(),this._markAsDirty(),this.onIsActiveChangedObservable.notifyObservers(e),this._isActive&&this._host&&this._group&&this._host.executeOnAllControls((e=>{if("ToggleButton"===e.typeName){if(e===this)return;const t=e;t.group===this.group&&(t.isActive=!1)}})))}constructor(e,t){super(e),this.name=e,this.onIsActiveChangedObservable=new K,this.delegatePickingToChildren=!1,this._isActive=!1,this.group=t??"",this.thickness=0,this.isPointerBlocker=!0;let i=null;this.toActiveAnimation=()=>{this.thickness=1},this.toInactiveAnimation=()=>{this.thickness=0},this.pointerEnterActiveAnimation=()=>{i=this.alpha,this.alpha-=.1},this.pointerOutActiveAnimation=()=>{null!==i&&(this.alpha=i)},this.pointerDownActiveAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpActiveAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05},this.pointerEnterInactiveAnimation=()=>{i=this.alpha,this.alpha-=.1},this.pointerOutInactiveAnimation=()=>{null!==i&&(this.alpha=i)},this.pointerDownInactiveAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpInactiveAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05}}_getTypeName(){return"ToggleButton"}_processPicking(e,t,i,s,r,n,o,a){if(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this.notRenderable)return!1;if(!super.contains(e,t))return!1;if(this.delegatePickingToChildren){let i=!1;for(let s=this._children.length-1;s>=0;s--){const r=this._children[s];if(r.isEnabled&&r.isHitTestVisible&&r.isVisible&&!r.notRenderable&&r.contains(e,t)){i=!0;break}}if(!i)return!1}return this._processObservables(s,e,t,i,r,n,o,a),!0}_onPointerEnter(e,t){return!!super._onPointerEnter(e,t)&&(this.isReadOnly||(this._isActive?this.pointerEnterActiveAnimation&&this.pointerEnterActiveAnimation():this.pointerEnterInactiveAnimation&&this.pointerEnterInactiveAnimation()),!0)}_onPointerOut(e,t,i=!1){this.isReadOnly||(this._isActive?this.pointerOutActiveAnimation&&this.pointerOutActiveAnimation():this.pointerOutInactiveAnimation&&this.pointerOutInactiveAnimation()),super._onPointerOut(e,t,i)}_onPointerDown(e,t,i,s,r){return!!super._onPointerDown(e,t,i,s,r)&&(this.isReadOnly||(this._isActive?this.pointerDownActiveAnimation&&this.pointerDownActiveAnimation():this.pointerDownInactiveAnimation&&this.pointerDownInactiveAnimation()),!0)}_onPointerUp(e,t,i,s,r,n){this.isReadOnly||(this._isActive?this.pointerUpActiveAnimation&&this.pointerUpActiveAnimation():this.pointerUpInactiveAnimation&&this.pointerUpInactiveAnimation()),super._onPointerUp(e,t,i,s,r,n)}}z("BABYLON.GUI.ToggleButton",hN);class cN{}class uN extends kw{constructor(){super(...arguments),this.onKeyPressObservable=new K,this.defaultButtonWidth="40px",this.defaultButtonHeight="40px",this.defaultButtonPaddingLeft="2px",this.defaultButtonPaddingRight="2px",this.defaultButtonPaddingTop="2px",this.defaultButtonPaddingBottom="2px",this.defaultButtonColor="#DDD",this.defaultButtonBackground="#070707",this.shiftButtonColor="#7799FF",this.selectedShiftThickness=1,this.shiftState=0,this._currentlyConnectedInputText=null,this._connectedInputTexts=[],this._onKeyPressObserver=null}_getTypeName(){return"VirtualKeyboard"}_createKey(e,t){const i=Bw.CreateSimpleButton(e,e);return i.width=t&&t.width?t.width:this.defaultButtonWidth,i.height=t&&t.height?t.height:this.defaultButtonHeight,i.color=t&&t.color?t.color:this.defaultButtonColor,i.background=t&&t.background?t.background:this.defaultButtonBackground,i.paddingLeft=t&&t.paddingLeft?t.paddingLeft:this.defaultButtonPaddingLeft,i.paddingRight=t&&t.paddingRight?t.paddingRight:this.defaultButtonPaddingRight,i.paddingTop=t&&t.paddingTop?t.paddingTop:this.defaultButtonPaddingTop,i.paddingBottom=t&&t.paddingBottom?t.paddingBottom:this.defaultButtonPaddingBottom,i.thickness=0,i.isFocusInvisible=!0,i.shadowColor=this.shadowColor,i.shadowBlur=this.shadowBlur,i.shadowOffsetX=this.shadowOffsetX,i.shadowOffsetY=this.shadowOffsetY,i.onPointerUpObservable.add((()=>{this.onKeyPressObservable.notifyObservers(e)})),i}addKeysRow(e,t){const i=new kw;i.isVertical=!1,i.isFocusInvisible=!0;let s=null;for(let r=0;rs.heightInPixels)&&(s=o),i.addControl(o)}i.height=s?s.height:this.defaultButtonHeight,this.addControl(i)}applyShiftState(e){if(this.children)for(let t=0;t1?this.selectedShiftThickness:0),r.text=e>0?r.text.toUpperCase():r.text.toLowerCase()}}}get connectedInputText(){return this._currentlyConnectedInputText}connect(e){if(this._connectedInputTexts.some((t=>t.input===e)))return;null===this._onKeyPressObserver&&(this._onKeyPressObserver=this.onKeyPressObservable.add((e=>{if(this._currentlyConnectedInputText){switch(this._currentlyConnectedInputText._host.focusedControl=this._currentlyConnectedInputText,e){case"⇧":return this.shiftState++,this.shiftState>2&&(this.shiftState=0),void this.applyShiftState(this.shiftState);case"←":return void(this._currentlyConnectedInputText instanceof Yw?this._currentlyConnectedInputText.alternativeProcessKey("Backspace"):this._currentlyConnectedInputText.processKey(8));case"↵":return void(this._currentlyConnectedInputText instanceof Yw?this._currentlyConnectedInputText.alternativeProcessKey("Enter"):this._currentlyConnectedInputText.processKey(13))}this._currentlyConnectedInputText instanceof Yw?this._currentlyConnectedInputText.alternativeProcessKey("",this.shiftState?e.toUpperCase():e):this._currentlyConnectedInputText.processKey(-1,this.shiftState?e.toUpperCase():e),1===this.shiftState&&(this.shiftState=0,this.applyShiftState(this.shiftState))}}))),this.isVisible=!1,this._currentlyConnectedInputText=e,e._connectedVirtualKeyboard=this;const t=e.onFocusObservable.add((()=>{this._currentlyConnectedInputText=e,e._connectedVirtualKeyboard=this,this.isVisible=!0})),i=e.onBlurObservable.add((()=>{e._connectedVirtualKeyboard=null,this._currentlyConnectedInputText=null,this.isVisible=!1}));this._connectedInputTexts.push({input:e,onBlurObserver:i,onFocusObserver:t})}disconnect(e){if(e){const t=this._connectedInputTexts.filter((t=>t.input===e));1===t.length&&(this._removeConnectedInputObservables(t[0]),this._connectedInputTexts=this._connectedInputTexts.filter((t=>t.input!==e)),this._currentlyConnectedInputText===e&&(this._currentlyConnectedInputText=null))}else this._connectedInputTexts.forEach((e=>{this._removeConnectedInputObservables(e)})),this._connectedInputTexts.length=0;0===this._connectedInputTexts.length&&(this._currentlyConnectedInputText=null,this.onKeyPressObservable.remove(this._onKeyPressObserver),this._onKeyPressObserver=null)}_removeConnectedInputObservables(e){e.input._connectedVirtualKeyboard=null,e.input.onFocusObservable.remove(e.onFocusObserver),e.input.onBlurObservable.remove(e.onBlurObserver)}dispose(){super.dispose(),this.disconnect()}static CreateDefaultLayout(e){const t=new uN(e);return t.addKeysRow(["1","2","3","4","5","6","7","8","9","0","←"]),t.addKeysRow(["q","w","e","r","t","y","u","i","o","p"]),t.addKeysRow(["a","s","d","f","g","h","j","k","l",";","'","↵"]),t.addKeysRow(["⇧","z","x","c","v","b","n","m",",",".","/"]),t.addKeysRow([" "],[{width:"200px"}]),t}_parseFromContent(e,t){super._parseFromContent(e,t);for(const e of this.children)if("StackPanel"===e.getClassName()){const t=e;for(const e of t.children)"Button"===e.getClassName()&&e.name&&e.onPointerUpObservable.add((()=>{this.onKeyPressObservable.notifyObservers(e.name)}))}}}z("BABYLON.GUI.VirtualKeyboard",uN);class dN extends Ow{get displayMinorLines(){return this._displayMinorLines}set displayMinorLines(e){this._displayMinorLines!==e&&(this._displayMinorLines=e,this._markAsDirty())}get displayMajorLines(){return this._displayMajorLines}set displayMajorLines(e){this._displayMajorLines!==e&&(this._displayMajorLines=e,this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get cellWidth(){return this._cellWidth}set cellWidth(e){this._cellWidth=e,this._markAsDirty()}get cellHeight(){return this._cellHeight}set cellHeight(e){this._cellHeight=e,this._markAsDirty()}get minorLineTickness(){return this._minorLineTickness}set minorLineTickness(e){this._minorLineTickness=e,this._markAsDirty()}get minorLineColor(){return this._minorLineColor}set minorLineColor(e){this._minorLineColor=e,this._markAsDirty()}get majorLineTickness(){return this._majorLineTickness}set majorLineTickness(e){this._majorLineTickness=e,this._markAsDirty()}get majorLineColor(){return this._majorLineColor}set majorLineColor(e){this._majorLineColor=e,this._markAsDirty()}get majorLineFrequency(){return this._majorLineFrequency}set majorLineFrequency(e){this._majorLineFrequency=e,this._markAsDirty()}constructor(e){super(e),this.name=e,this._cellWidth=20,this._cellHeight=20,this._minorLineTickness=1,this._minorLineColor="DarkGray",this._majorLineTickness=2,this._majorLineColor="White",this._majorLineFrequency=5,this._background="Black",this._displayMajorLines=!0,this._displayMinorLines=!0}_draw(e){if(e.save(),this._applyStates(e),this._isEnabled){this._background&&(e.fillStyle=this._background,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height));const t=this._currentMeasure.width/this._cellWidth,i=this._currentMeasure.height/this._cellHeight,s=this._currentMeasure.left+this._currentMeasure.width/2,r=this._currentMeasure.top+this._currentMeasure.height/2;if(this._displayMinorLines){e.strokeStyle=this._minorLineColor,e.lineWidth=this._minorLineTickness;for(let i=-t/2+1;ithis._markAsDirty())),this._markAsDirty())}get valueBarImage(){return this._valueBarImage}set valueBarImage(e){this._valueBarImage!==e&&(this._valueBarImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>this._markAsDirty())),this._markAsDirty())}get thumbImage(){return this._thumbImage}set thumbImage(e){this._thumbImage!==e&&(this._thumbImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>this._markAsDirty())),this._markAsDirty())}constructor(e){super(e),this.name=e,this._tempMeasure=new Pw(0,0,0,0)}_getTypeName(){return"ImageBasedSlider"}_draw(e){e.save(),this._applyStates(e),this._prepareRenderingData("rectangle");const t=this._getThumbPosition(),i=this._renderLeft,s=this._renderTop,r=this._renderWidth,n=this._renderHeight;this._backgroundImage&&(this._tempMeasure.copyFromFloats(i,s,r,n),this.isThumbClamped&&this.displayThumb&&(this.isVertical?this._tempMeasure.height+=this._effectiveThumbThickness:this._tempMeasure.width+=this._effectiveThumbThickness),this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure),this._backgroundImage._draw(e)),this._valueBarImage&&(this.isVertical?this.isThumbClamped&&this.displayThumb?this._tempMeasure.copyFromFloats(i,s+t,r,n-t+this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(i,s+t,r,n-t):this.isThumbClamped&&this.displayThumb?this._tempMeasure.copyFromFloats(i,s,t+this._effectiveThumbThickness/2,n):this._tempMeasure.copyFromFloats(i,s,t,n),this._valueBarImage._currentMeasure.copyFrom(this._tempMeasure),this._valueBarImage._draw(e)),this.displayThumb&&(this.isVertical?this._tempMeasure.copyFromFloats(i-this._effectiveBarOffset,this._currentMeasure.top+t,this._currentMeasure.width,this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(this._currentMeasure.left+t,this._currentMeasure.top,this._effectiveThumbThickness,this._currentMeasure.height),this._thumbImage._currentMeasure.copyFrom(this._tempMeasure),this._thumbImage._draw(e)),e.restore()}serialize(e){super.serialize(e);const t={},i={},s={};this.backgroundImage.serialize(t),this.thumbImage.serialize(i),this.valueBarImage.serialize(s),e.backgroundImage=t,e.thumbImage=i,e.valueBarImage=s}_parseFromContent(e,t){super._parseFromContent(e,t),this.backgroundImage=Lw.Parse(e.backgroundImage,t),this.thumbImage=Lw.Parse(e.thumbImage,t),this.valueBarImage=Lw.Parse(e.valueBarImage,t)}}Ze([rt()],_N.prototype,"displayThumb",null),z("BABYLON.GUI.ImageBasedSlider",_N);const pN="Statics";Ow.AddHeader=function(e,t,i,s){const r=new kw("panel"),n=!s||s.isHorizontal,o=!s||s.controlFirst;r.isVertical=!n;const a=new Fw("header");return a.text=t,a.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,n?a.width=i:a.height=i,o?(r.addControl(e),r.addControl(a),a.paddingLeft="5px"):(r.addControl(a),r.addControl(e),a.paddingRight="5px"),a.shadowBlur=e.shadowBlur,a.shadowColor=e.shadowColor,a.shadowOffsetX=e.shadowOffsetX,a.shadowOffsetY=e.shadowOffsetY,r};class fN{constructor(){this._colorStops=[],this._gradientDirty=!0}_addColorStopsToCanvasGradient(){for(const e of this._colorStops)this._canvasGradient.addColorStop(e.offset,e.color)}getCanvasGradient(e){return(this._gradientDirty||this._context!==e)&&(this._context=e,this._canvasGradient=this._createCanvasGradient(e),this._addColorStopsToCanvasGradient(),this._gradientDirty=!1),this._canvasGradient}addColorStop(e,t){this._colorStops.push({offset:e,color:t}),this._gradientDirty=!0}removeColorStop(e){this._colorStops=this._colorStops.filter((t=>t.offset!==e)),this._gradientDirty=!0}clearColorStops(){this._colorStops=[],this._gradientDirty=!0}get colorStops(){return this._colorStops}getClassName(){return"BaseGradient"}serialize(e){e.colorStops=this._colorStops,e.className=this.getClassName()}parse(e){this._colorStops=e.colorStops}}class mN extends fN{constructor(e,t,i,s){super(),this._x0=e??0,this._y0=t??0,this._x1=i??0,this._y1=s??0}_createCanvasGradient(e){return e.createLinearGradient(this._x0,this._y0,this._x1,this._y1)}get x0(){return this._x0}get x1(){return this._x1}get y0(){return this._y0}get y1(){return this._y1}getClassName(){return"LinearGradient"}serialize(e){super.serialize(e),e.x0=this._x0,e.y0=this._y0,e.x1=this._x1,e.y1=this._y1}parse(e){super.parse(e),this._x0=e.x0,this._y0=e.y0,this._x1=e.x1,this._y1=e.y1}}z("BABYLON.GUI.LinearGradient",mN);class gN extends fN{constructor(e,t,i,s,r,n){super(),this._x0=e??0,this._y0=t??0,this._r0=i??0,this._x1=s??0,this._y1=r??0,this._r1=n??0}_createCanvasGradient(e){return e.createRadialGradient(this._x0,this._y0,this._r0,this._x1,this._y1,this._r1)}get x0(){return this._x0}get x1(){return this._x1}get y0(){return this._y0}get y1(){return this._y1}get r0(){return this._r0}get r1(){return this._r1}getClassName(){return"RadialGradient"}serialize(e){super.serialize(e),e.x0=this._x0,e.y0=this._y0,e.r0=this._r0,e.x1=this._x1,e.y1=this._y1,e.r1=this._r1}parse(e){super.parse(e),this._x0=e.x0,this._y0=e.y0,this._r0=e.r0,this._x1=e.x1,this._y1=e.y1,this._r1=e.r1}}z("BABYLON.GUI.RadialGradient",gN);class vN{constructor(e){this._fontFamily="Arial",this._fontStyle="",this._fontWeight="",this._fontSize=new yw(18,yw.UNITMODE_PIXEL,!1),this.onChangedObservable=new K,this._host=e}get fontSize(){return this._fontSize.toString(this._host)}set fontSize(e){this._fontSize.toString(this._host)!==e&&this._fontSize.fromString(e)&&this.onChangedObservable.notifyObservers(this)}get fontFamily(){return this._fontFamily}set fontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.onChangedObservable.notifyObservers(this))}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.onChangedObservable.notifyObservers(this))}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.onChangedObservable.notifyObservers(this))}dispose(){this.onChangedObservable.clear()}}class xN extends uu{get numLayoutCalls(){return this._numLayoutCalls}get numRenderCalls(){return this._numRenderCalls}get renderScale(){return this._renderScale}set renderScale(e){e!==this._renderScale&&(this._renderScale=e,this._onResize())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this.markAsDirty())}get idealWidth(){return this._idealWidth}set idealWidth(e){this._idealWidth!==e&&(this._idealWidth=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get idealHeight(){return this._idealHeight}set idealHeight(e){this._idealHeight!==e&&(this._idealHeight=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get useSmallestIdeal(){return this._useSmallestIdeal}set useSmallestIdeal(e){this._useSmallestIdeal!==e&&(this._useSmallestIdeal=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get renderAtIdealSize(){return this._renderAtIdealSize}set renderAtIdealSize(e){this._renderAtIdealSize!==e&&(this._renderAtIdealSize=e,this._onResize())}get idealRatio(){let e=0,t=0;return this._idealWidth&&(e=this.getSize().width/this._idealWidth),this._idealHeight&&(t=this.getSize().height/this._idealHeight),this._useSmallestIdeal&&this._idealWidth&&this._idealHeight?window.innerWidtht.typeName===e))}getControlByName(e){return this._getControlByKey("name",e)}_getControlByKey(e,t){return this._rootContainer.getDescendants().find((i=>i[e]===t))||null}get focusedControl(){return this._focusedControl}set focusedControl(e){this._focusedControl!=e&&(this._focusedControl&&this._focusedControl.onBlur(),e&&e.onFocus(),this._focusedControl=e)}get isForeground(){return!this.layer||!this.layer.isBackground}set isForeground(e){this.layer&&this.layer.isBackground!==!e&&(this.layer.isBackground=!e)}get clipboardData(){return this._clipboardData}set clipboardData(e){this._clipboardData=e}constructor(e,t=0,i=0,s,r=!1,n=Pa.NEAREST_SAMPLINGMODE,o=!0){super(e,{width:t,height:i},s,r,n,N_.TEXTUREFORMAT_RGBA,o),this.onGuiReadyObservable=new K,this._isDirty=!1,this._rootContainer=new Dw("root"),this._lastControlOver={},this._lastControlDown={},this._capturingControl={},this._linkedControls=new Array,this._isFullscreen=!1,this._fullscreenViewport=new Pn(0,0,1,1),this._idealWidth=0,this._idealHeight=0,this._useSmallestIdeal=!1,this._renderAtIdealSize=!1,this._blockNextFocusCheck=!1,this._renderScale=1,this._cursorChanged=!1,this._defaultMousePointerId=0,this._rootChildrenHaveChanged=!1,this._capturedPointerIds=new Set,this._numLayoutCalls=0,this._numRenderCalls=0,this._clipboardData="",this.onClipboardObservable=new K,this.onControlPickedObservable=new K,this.onBeginLayoutObservable=new K,this.onEndLayoutObservable=new K,this.onBeginRenderObservable=new K,this.onEndRenderObservable=new K,this.premulAlpha=!1,this.applyYInversionOnUpdate=!0,this.skipBlockEvents=0,this.checkPointerEveryFrame=!1,this._useInvalidateRectOptimization=!0,this._invalidatedRectangle=null,this._clearMeasure=new Pw(0,0,0,0),this._onClipboardCopy=e=>{const t=e,i=new eg(Jm.COPY,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this._onClipboardCut=e=>{const t=e,i=new eg(Jm.CUT,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this._onClipboardPaste=e=>{const t=e,i=new eg(Jm.PASTE,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this.parseContent=this.parseSerializedObject,(s=this.getScene())&&this._texture&&(this.applyYInversionOnUpdate=o,this._rootElement=s.getEngine().getInputElement(),this._renderObserver=s.onBeforeCameraRenderObservable.add((e=>this._checkUpdate(e))),this._controlAddedObserver=this._rootContainer.onControlAddedObservable.add((e=>{e&&(this._rootChildrenHaveChanged=!0)})),this._controlRemovedObserver=this._rootContainer.onControlRemovedObservable.add((e=>{e&&(this._rootChildrenHaveChanged=!0)})),this._preKeyboardObserver=s.onPreKeyboardObservable.add((e=>{this._focusedControl&&(e.type===dr.KEYDOWN&&this._focusedControl.processKeyboard(e.event),e.skipOnPointerObservable=!0)})),this._rootContainer._link(this),this.hasAlpha=!0,t&&i||(this._resizeObserver=s.getEngine().onResizeObservable.add((()=>this._onResize())),this._onResize()),this._texture.isReady=!0)}getClassName(){return"AdvancedDynamicTexture"}executeOnAllControls(e,t){t||(t=this._rootContainer),e(t);for(const i of t.children)i.children?this.executeOnAllControls(e,i):e(i)}get useInvalidateRectOptimization(){return this._useInvalidateRectOptimization}set useInvalidateRectOptimization(e){this._useInvalidateRectOptimization=e}invalidateRect(e,t,i,s){if(this._useInvalidateRectOptimization)if(this._invalidatedRectangle){const r=Math.ceil(Math.max(this._invalidatedRectangle.left+this._invalidatedRectangle.width-1,i)),n=Math.ceil(Math.max(this._invalidatedRectangle.top+this._invalidatedRectangle.height-1,s));this._invalidatedRectangle.left=Math.floor(Math.min(this._invalidatedRectangle.left,e)),this._invalidatedRectangle.top=Math.floor(Math.min(this._invalidatedRectangle.top,t)),this._invalidatedRectangle.width=r-this._invalidatedRectangle.left+1,this._invalidatedRectangle.height=n-this._invalidatedRectangle.top+1}else this._invalidatedRectangle=new Pw(e,t,i-e+1,s-t+1)}markAsDirty(){this._isDirty=!0}createStyle(){return new vN(this)}addControl(e){return this._rootContainer.addControl(e),this}removeControl(e){return this._rootContainer.removeControl(e),this}moveToNonOverlappedPosition(e,t=1,i=1){let s;if(Array.isArray(e))s=e;else{const t=this.getDescendants(!0);s=void 0===e?t.filter((e=>void 0!==e.overlapGroup)):t.filter((t=>t.overlapGroup===e))}s.forEach((e=>{let r=de.Zero();const n=new de(e.centerX,e.centerY);s.forEach((t=>{if(e!==t&&xN._Overlaps(e,t)){const e=n.subtract(new de(t.centerX,t.centerY)),s=e.length();s>0&&(r=r.add(e.normalize().scale(i/s)))}})),r.length()>0&&(r=r.normalize().scale(t*(e.overlapDeltaMultiplier??1)),e.linkOffsetXInPixels+=r.x,e.linkOffsetYInPixels+=r.y)}))}dispose(){const e=this.getScene();e&&(this._rootElement=null,e.onBeforeCameraRenderObservable.remove(this._renderObserver),this._resizeObserver&&e.getEngine().onResizeObservable.remove(this._resizeObserver),this._prePointerObserver&&e.onPrePointerObservable.remove(this._prePointerObserver),this._sceneRenderObserver&&e.onBeforeRenderObservable.remove(this._sceneRenderObserver),this._pointerObserver&&e.onPointerObservable.remove(this._pointerObserver),this._preKeyboardObserver&&e.onPreKeyboardObservable.remove(this._preKeyboardObserver),this._canvasPointerOutObserver&&e.getEngine().onCanvasPointerOutObservable.remove(this._canvasPointerOutObserver),this._canvasBlurObserver&&e.getEngine().onCanvasBlurObservable.remove(this._canvasBlurObserver),this._controlAddedObserver&&this._rootContainer.onControlAddedObservable.remove(this._controlAddedObserver),this._controlRemovedObserver&&this._rootContainer.onControlRemovedObservable.remove(this._controlRemovedObserver),this._layerToDispose&&(this._layerToDispose.texture=null,this._layerToDispose.dispose(),this._layerToDispose=null),this._rootContainer.dispose(),this.onClipboardObservable.clear(),this.onControlPickedObservable.clear(),this.onBeginRenderObservable.clear(),this.onEndRenderObservable.clear(),this.onBeginLayoutObservable.clear(),this.onEndLayoutObservable.clear(),this.onGuiReadyObservable.clear(),super.dispose())}_onResize(){const e=this.getScene();if(!e)return;const t=e.getEngine(),i=this.getSize();let s=t.getRenderWidth()*this._renderScale,r=t.getRenderHeight()*this._renderScale;this._renderAtIdealSize&&(this._idealWidth?(r=r*this._idealWidth/s,s=this._idealWidth):this._idealHeight&&(s=s*this._idealHeight/r,r=this._idealHeight)),i.width===s&&i.height===r||(this.scaleTo(s,r),this.markAsDirty(),(this._idealWidth||this._idealHeight)&&this._rootContainer._markAllAsDirty()),this.invalidateRect(0,0,i.width-1,i.height-1)}_getGlobalViewport(){const e=this.getSize(),t=this._fullscreenViewport.toGlobal(e.width,e.height),i=Math.round(t.width*(1/this.rootContainer.scaleX)),s=Math.round(t.height*(1/this.rootContainer.scaleY));return t.x+=(t.width-i)/2,t.y+=(t.height-s)/2,t.width=i,t.height=s,t}getProjectedPosition(e,t){const i=this.getProjectedPositionWithZ(e,t);return new de(i.x,i.y)}getProjectedPositionWithZ(e,t){const i=this.getScene();if(!i)return _e.Zero();const s=this._getGlobalViewport(),r=_e.Project(e,t,i.getTransformMatrix(),s);return new _e(r.x,r.y,r.z)}_checkUpdate(e,t){if(!this._layerToDispose||e.layerMask&this._layerToDispose.layerMask){if(this._isFullscreen&&this._linkedControls.length){const e=this.getScene();if(!e)return;const t=this._getGlobalViewport();for(const i of this._linkedControls){if(!i.isVisible)continue;const s=i._linkedMesh;if(!s||s.isDisposed()){Ds.SetImmediate((()=>{i.linkWithMesh(null)}));continue}const r=s.getBoundingInfo?s.getBoundingInfo().boundingSphere.center:_e.ZeroReadOnly,n=_e.Project(r,s.getWorldMatrix(),e.getTransformMatrix(),t);n.z<0||n.z>1?i.notRenderable=!0:(i.notRenderable=!1,this.useInvalidateRectOptimization&&i.invalidateRect(),i._moveToProjectedPosition(n))}}(this._isDirty||this._rootContainer.isDirty)&&(this._isDirty=!1,this._render(t),t||this.update(this.applyYInversionOnUpdate,this.premulAlpha,xN.AllowGPUOptimizations))}}_render(e){const t=this.getSize(),i=t.width,s=t.height,r=this.getContext();if(r.font="18px Arial",r.strokeStyle="white",this.onGuiReadyObservable.hasObservers()&&this._checkGuiIsReady(),this._rootChildrenHaveChanged){const e=this.getScene()?.activeCamera;e&&(this._rootChildrenHaveChanged=!1,this._checkUpdate(e,!0))}this.onBeginLayoutObservable.notifyObservers(this);const n=new Pw(0,0,i,s);this._numLayoutCalls=0,this._rootContainer._layout(n,r),this.onEndLayoutObservable.notifyObservers(this),this._isDirty=!1,e||(this._invalidatedRectangle?this._clearMeasure.copyFrom(this._invalidatedRectangle):this._clearMeasure.copyFromFloats(0,0,i,s),r.clearRect(this._clearMeasure.left,this._clearMeasure.top,this._clearMeasure.width,this._clearMeasure.height),this._background&&(r.save(),r.fillStyle=this._background,r.fillRect(this._clearMeasure.left,this._clearMeasure.top,this._clearMeasure.width,this._clearMeasure.height),r.restore()),this.onBeginRenderObservable.notifyObservers(this),this._numRenderCalls=0,this._rootContainer._render(r,this._invalidatedRectangle),this.onEndRenderObservable.notifyObservers(this),this._invalidatedRectangle=null)}_changeCursor(e){this._rootElement&&(this._rootElement.style.cursor=e,this._cursorChanged=!0)}_registerLastControlDown(e,t){this._lastControlDown[t]=e,this.onControlPickedObservable.notifyObservers(e)}_doPicking(e,t,i,s,r,n,o,a){const l=this.getScene();if(!l)return;const h=l.getEngine(),c=this.getSize();if(this._isFullscreen){const i=l.cameraToUseForPointers||l.activeCamera;if(!i)return;const s=i.viewport;e*=c.width/(h.getRenderWidth()*s.width),t*=c.height/(h.getRenderHeight()*s.height)}if(this._capturingControl[r])return this._capturingControl[r].isPointerBlocker&&(this._shouldBlockPointer=!0),void this._capturingControl[r]._processObservables(s,e,t,i,r,n);this._cursorChanged=!1,this._rootContainer._processPicking(e,t,i,s,r,n,o,a)||(l.doNotHandleCursors||this._changeCursor(""),s===lr.POINTERMOVE&&this._lastControlOver[r]&&(this._lastControlOver[r]._onPointerOut(this._lastControlOver[r],i),delete this._lastControlOver[r])),this._cursorChanged||l.doNotHandleCursors||this._changeCursor(""),this._manageFocus()}_cleanControlAfterRemovalFromList(e,t){for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&e[i]===t&&delete e[i]}_cleanControlAfterRemoval(e){this._cleanControlAfterRemovalFromList(this._lastControlDown,e),this._cleanControlAfterRemovalFromList(this._lastControlOver,e)}pick(e,t,i=null){this._isFullscreen&&this._scene&&this._translateToPicking(this._scene,new Pn(0,0,0,0),i,e,t)}_translateToPicking(e,t,i,s=e.pointerX,r=e.pointerY){const n=e.cameraToUseForPointers||e.activeCamera,o=e.getEngine(),a=e.cameraToUseForPointers;if(n)if(n.rigCameras.length){const i=new Pn(0,0,1,1);n.rigCameras.forEach((n=>{n.viewport.toGlobalToRef(o.getRenderWidth(),o.getRenderHeight(),i);const a=s/o.getHardwareScalingLevel()-i.x,l=r/o.getHardwareScalingLevel()-(o.getRenderHeight()-i.y-i.height);a<0||l<0||s>i.width||r>i.height||(e.cameraToUseForPointers=n,t.x=i.x,t.y=i.y,t.width=i.width,t.height=i.height)}))}else n.viewport.toGlobalToRef(o.getRenderWidth(),o.getRenderHeight(),t);else t.x=0,t.y=0,t.width=o.getRenderWidth(),t.height=o.getRenderHeight();const l=s/o.getHardwareScalingLevel()-t.x,h=r/o.getHardwareScalingLevel()-(o.getRenderHeight()-t.y-t.height);if(this._shouldBlockPointer=!1,i){const e=i.event.pointerId||this._defaultMousePointerId;this._doPicking(l,h,i,i.type,e,i.event.button,i.event.deltaX,i.event.deltaY),(this._shouldBlockPointer&&!(i.type&this.skipBlockEvents)||this._capturingControl[e])&&(i.skipOnPointerObservable=!0)}else this._doPicking(l,h,null,lr.POINTERMOVE,this._defaultMousePointerId,0);e.cameraToUseForPointers=a}attach(){const e=this.getScene();if(!e)return;const t=new Pn(0,0,0,0);this._prePointerObserver=e.onPrePointerObservable.add((i=>{if((!e.isPointerCaptured(i.event.pointerId)||i.type!==lr.POINTERUP||this._capturedPointerIds.has(i.event.pointerId))&&(i.type===lr.POINTERMOVE||i.type===lr.POINTERUP||i.type===lr.POINTERDOWN||i.type===lr.POINTERWHEEL)){if(i.type===lr.POINTERMOVE){if(e.isPointerCaptured(i.event.pointerId))return;i.event.pointerId&&(this._defaultMousePointerId=i.event.pointerId)}this._translateToPicking(e,t,i)}})),this._attachPickingToSceneRender(e,(()=>this._translateToPicking(e,t,null)),!1),this._attachToOnPointerOut(e),this._attachToOnBlur(e)}registerClipboardEvents(){self.addEventListener("copy",this._onClipboardCopy,!1),self.addEventListener("cut",this._onClipboardCut,!1),self.addEventListener("paste",this._onClipboardPaste,!1)}unRegisterClipboardEvents(){self.removeEventListener("copy",this._onClipboardCopy),self.removeEventListener("cut",this._onClipboardCut),self.removeEventListener("paste",this._onClipboardPaste)}_transformUvs(e){const t=this.getTextureMatrix();let i;if(t.isIdentityAs3x2())i=e;else{const s=ve.Matrix[0];t.getRowToRef(0,ve.Vector4[0]),t.getRowToRef(1,ve.Vector4[1]),t.getRowToRef(2,ve.Vector4[2]);const r=ve.Vector4[0],n=ve.Vector4[1],o=ve.Vector4[2];s.setRowFromFloats(0,r.x,r.y,0,0),s.setRowFromFloats(1,n.x,n.y,0,0),s.setRowFromFloats(2,0,0,1,0),s.setRowFromFloats(3,o.x,o.y,0,1),i=ve.Vector2[0],de.TransformToRef(e,s,i)}if((this.wrapU===Pa.WRAP_ADDRESSMODE||this.wrapU===Pa.MIRROR_ADDRESSMODE)&&i.x>1){let e=i.x-Math.trunc(i.x);this.wrapU===Pa.MIRROR_ADDRESSMODE&&Math.trunc(i.x)%2==1&&(e=1-e),i.x=e}if((this.wrapV===Pa.WRAP_ADDRESSMODE||this.wrapV===Pa.MIRROR_ADDRESSMODE)&&i.y>1){let e=i.y-Math.trunc(i.y);this.wrapV===Pa.MIRROR_ADDRESSMODE&&Math.trunc(i.x)%2==1&&(e=1-e),i.y=e}return i}attachToMesh(e,t=!0){const i=this.getScene();i&&(this._pointerObserver&&i.onPointerObservable.remove(this._pointerObserver),this._pointerObserver=i.onPointerObservable.add((t=>{if(t.type!==lr.POINTERMOVE&&t.type!==lr.POINTERUP&&t.type!==lr.POINTERDOWN&&t.type!==lr.POINTERWHEEL)return;t.type===lr.POINTERMOVE&&t.event.pointerId&&(this._defaultMousePointerId=t.event.pointerId);const i=t.event.pointerId||this._defaultMousePointerId;if(t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh===e){let e=t.pickInfo.getTextureCoordinates();if(e){e=this._transformUvs(e);const s=this.getSize();this._doPicking(e.x*s.width,(this.applyYInversionOnUpdate?1-e.y:e.y)*s.height,t,t.type,i,t.event.button,t.event.deltaX,t.event.deltaY)}}else if(t.type===lr.POINTERUP){if(this._lastControlDown[i]&&this._lastControlDown[i]._forcePointerUp(i),delete this._lastControlDown[i],this.focusedControl){const e=this.focusedControl.keepsFocusWith();let t=!0;if(e)for(const s of e){if(this===s._host)continue;const e=s._host;if(e._lastControlOver[i]&&e._lastControlOver[i].isAscendant(s)){t=!1;break}}t&&(this.focusedControl=null)}}else t.type===lr.POINTERMOVE&&(this._lastControlOver[i]&&this._lastControlOver[i]._onPointerOut(this._lastControlOver[i],t,!0),delete this._lastControlOver[i])})),e.enablePointerMoveEvents=t,this._attachPickingToSceneRender(i,(()=>{const t=this._defaultMousePointerId,s=i?.pick(i.pointerX,i.pointerY);if(s&&s.hit&&s.pickedMesh===e){let e=s.getTextureCoordinates();if(e){e=this._transformUvs(e);const i=this.getSize();this._doPicking(e.x*i.width,(this.applyYInversionOnUpdate?1-e.y:e.y)*i.height,null,lr.POINTERMOVE,t,0)}}else this._lastControlOver[t]&&this._lastControlOver[t]._onPointerOut(this._lastControlOver[t],null,!0),delete this._lastControlOver[t]}),!0),this._attachToOnPointerOut(i),this._attachToOnBlur(i))}moveFocusToControl(e){this.focusedControl=e,this._lastPickedControl=e,this._blockNextFocusCheck=!0}_manageFocus(){if(this._blockNextFocusCheck)return this._blockNextFocusCheck=!1,void(this._lastPickedControl=this._focusedControl);if(this._focusedControl&&this._focusedControl!==this._lastPickedControl){if(this._lastPickedControl.isFocusInvisible)return;this.focusedControl=null}}_attachPickingToSceneRender(e,t,i){this._sceneRenderObserver=e.onBeforeRenderObservable.add((()=>{this.checkPointerEveryFrame&&(this._linkedControls.length>0||i)&&t()}))}_attachToOnPointerOut(e){this._canvasPointerOutObserver=e.getEngine().onCanvasPointerOutObservable.add((e=>{this._lastControlOver[e.pointerId]&&this._lastControlOver[e.pointerId]._onPointerOut(this._lastControlOver[e.pointerId],null),delete this._lastControlOver[e.pointerId],this._lastControlDown[e.pointerId]&&this._lastControlDown[e.pointerId]!==this._capturingControl[e.pointerId]&&(this._lastControlDown[e.pointerId]._forcePointerUp(e.pointerId),delete this._lastControlDown[e.pointerId])}))}_attachToOnBlur(e){this._canvasBlurObserver=e.getEngine().onCanvasBlurObservable.add((()=>{Object.entries(this._lastControlDown).forEach((([,e])=>{e._onCanvasBlur()})),this.focusedControl=null,this._lastControlDown={}}))}serializeContent(){const e=this.getSize(),t={root:{},width:e.width,height:e.height};return this._rootContainer.serialize(t.root),t}parseSerializedObject(e,t,i){if(this._rootContainer=Ow.Parse(e.root,this,i),t){const t=e.width,i=e.height;"number"==typeof t&&"number"==typeof i&&t>=0&&i>=0?this.scaleTo(t,i):this.scaleTo(1920,1080)}}clone(e,t){const i=this.getScene();if(!i)return this;const s=this.getSize(),r=this.serializeContent();let n;return n=this._isFullscreen?xN.CreateFullscreenUI(e??"Clone of "+this.name):t?xN.CreateForMesh(t,s.width,s.height):new xN(e??"Clone of "+this.name,s.width,s.height,i,!this.noMipmap,this.samplingMode),n.parseSerializedObject(r),n}static async ParseFromSnippetAsync(e,t,i,s){const r=i??xN.CreateFullscreenUI("ADT from snippet");if("_BLANK"===e)return r;const n=await xN._LoadURLContentAsync(xN.SnippetUrl+"/"+e.replace(/#/g,"/"),!0);return r.parseSerializedObject(n,t,s),r}parseFromSnippetAsync(e,t,i){return xN.ParseFromSnippetAsync(e,t,this,i)}static async ParseFromFileAsync(e,t,i,s){const r=i??xN.CreateFullscreenUI("ADT from URL"),n=await xN._LoadURLContentAsync(e);return r.parseSerializedObject(n,t,s),r}parseFromURLAsync(e,t,i){return xN.ParseFromFileAsync(e,t,this,i)}static _LoadURLContentAsync(e,t=!1){return""===e?Promise.reject("No URL provided"):new Promise(((i,s)=>{const r=new Pt;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){let e;if(t){const t=JSON.parse(JSON.parse(r.responseText).jsonPayload);e=t.encodedGui?new TextDecoder("utf-8").decode(ei(t.encodedGui)):t.gui}else e=r.responseText;const s=JSON.parse(e);i(s)}else s("Unable to load")})),r.open("GET",e),r.send()}))}static _Overlaps(e,t){return!(e.centerX>t.centerX+t.widthInPixels||e.centerX+e.widthInPixelst.centerY+t.heightInPixels)}static CreateForMesh(e,t=1024,i=1024,s=!0,r=!1,n,o=this._CreateMaterial,a=Pa.TRILINEAR_SAMPLINGMODE){const l=Cs(),h=new xN(`AdvancedDynamicTexture for ${e.name} [${l}]`,t,i,e.getScene(),!0,a,n);return o(e,l,h,r),h.attachToMesh(e,s),h}static _CreateMaterial(e,t,i,s){const r=W("BABYLON.StandardMaterial");if(!r)throw"StandardMaterial needs to be imported before as it contains a side-effect required by your code.";const n=new r(`AdvancedDynamicTextureMaterial for ${e.name} [${t}]`,e.getScene());n.backFaceCulling=!1,n.diffuseColor=Ee.Black(),n.specularColor=Ee.Black(),s?(n.diffuseTexture=i,n.emissiveTexture=i,i.hasAlpha=!0):(n.emissiveTexture=i,n.opacityTexture=i),e.material=n}static CreateForMeshTexture(e,t=1024,i=1024,s=!0,r,n=Pa.TRILINEAR_SAMPLINGMODE){const o=new xN(e.name+" AdvancedDynamicTexture",t,i,e.getScene(),!0,n,r);return o.attachToMesh(e,s),o}static CreateFullscreenUI(e,t=!0,i=null,s=Pa.BILINEAR_SAMPLINGMODE,r=!1){const n=new xN(e,0,0,i,!1,s),o=n.getScene(),a=new Vv(e+"_layer",null,o,!t);if(a.texture=n,n._layerToDispose=a,n._isFullscreen=!0,r&&o){const e=1/o.getEngine().getHardwareScalingLevel();n._rootContainer.scaleX=e,n._rootContainer.scaleY=e}return n.attach(),n}scale(e){super.scale(e),this.markAsDirty()}scaleTo(e,t){super.scaleTo(e,t),this.markAsDirty()}_checkGuiIsReady(){this.guiIsReady()&&(this.onGuiReadyObservable.notifyObservers(this),this.onGuiReadyObservable.clear())}guiIsReady(){return this._rootContainer.isReady()}}xN.SnippetUrl=N_.SnippetUrl,xN.AllowGPUOptimizations=!0;class bN{get renderTimeCounter(){return this._renderTime}get layoutTimeCounter(){return this._layoutTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeginRenderObserver=this.texture.onBeginRenderObservable.add((()=>{this._renderTime.beginMonitoring()})),this._onEndRenderObserver=this.texture.onEndRenderObservable.add((()=>{this._renderTime.endMonitoring(!0)}))):(this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver),this._onBeginRenderObserver=null,this.texture.onEndRenderObservable.remove(this._onEndRenderObserver),this._onEndRenderObserver=null))}get captureLayoutTime(){return this._captureLayoutTime}set captureLayoutTime(e){e!==this._captureLayoutTime&&(this._captureLayoutTime=e,e?(this._onBeginLayoutObserver=this.texture.onBeginLayoutObservable.add((()=>{this._layoutTime.beginMonitoring()})),this._onEndLayoutObserver=this.texture.onEndLayoutObservable.add((()=>{this._layoutTime.endMonitoring(!0)}))):(this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver),this._onBeginLayoutObserver=null,this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver),this._onEndLayoutObserver=null))}constructor(e){this.texture=e,this._captureRenderTime=!1,this._renderTime=new wr,this._captureLayoutTime=!1,this._layoutTime=new wr,this._onBeginRenderObserver=null,this._onEndRenderObserver=null,this._onBeginLayoutObserver=null,this._onEndLayoutObserver=null}dispose(){this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver),this._onBeginRenderObserver=null,this.texture.onEndRenderObservable.remove(this._onEndRenderObserver),this._onEndRenderObserver=null,this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver),this._onBeginLayoutObserver=null,this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver),this._onEndLayoutObserver=null,this.texture=null}}const TN="XmlLoader Exception : XML file is malformed or corrupted.";class yN{constructor(e=null){this._nodes={},this._nodeTypes={element:1,attribute:2,text:3},this._isLoaded=!1,this._objectAttributes={textHorizontalAlignment:1,textVerticalAlignment:2,horizontalAlignment:3,verticalAlignment:4,stretch:5},e&&(this._parentClass=e)}_getChainElement(e){let t=window;this._parentClass&&(t=this._parentClass);let i=e;i=i.split(".");for(let e=0;e0&&u>d)throw"XmlLoader Exception : In the Grid element, the number of columns is defined in the first row, do not add more columns in the subsequent rows.";if(0==c){if(!n[e].attributes.getNamedItem("width"))throw"XmlLoader Exception : Width must be defined for all the grid columns in the first row";s=Number(n[e].attributes.getNamedItem("width").nodeValue),h=!!n[e].attributes.getNamedItem("isPixel")&&JSON.parse(n[e].attributes.getNamedItem("isPixel").nodeValue),t.addColumnDefinition(s,h)}a=n[e].children;for(let e=0;e{if(4===r.readyState&&200===r.status){if(!r.responseXML){if(s)return void s(TN);throw TN}const e=r.responseXML.documentElement;this._parseXml(e.firstChild,t),this._isLoaded=!0,i&&i()}},r.onerror=function(){s&&s("an error occurred during loading the layout")},r.open("GET",e,!0),r.send()}async loadLayoutAsync(e,t){return new Promise(((i,s)=>{this.loadLayout(e,t,i,s)}))}}class SN extends _e{constructor(e,t=0){super(e.x,e.y,e.z),this.buttonIndex=t}}class CN{get position(){return this._node?this._node.position:_e.Zero()}set position(e){this._node&&(this._node.position=e)}get scaling(){return this._node?this._node.scaling:new _e(1,1,1)}set scaling(e){this._node&&(this._isScaledByManager=!1,this._node.scaling=e)}get behaviors(){return this._behaviors}addBehavior(e){if(-1!==this._behaviors.indexOf(e))return this;e.init();const t=this._host.scene;return t.isLoading?t.onDataLoadedObservable.addOnce((()=>{e.attach(this)})):e.attach(this),this._behaviors.push(e),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),this}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}get isVisible(){return this._isVisible}set isVisible(e){if(this._isVisible===e)return;this._isVisible=e;const t=this.mesh;t&&t.setEnabled(e)}constructor(e){this.name=e,this._downCount=0,this._enterCount=-1,this._downPointerIds={},this._isVisible=!0,this._isScaledByManager=!1,this.onPointerMoveObservable=new K,this.onPointerOutObservable=new K,this.onPointerDownObservable=new K,this.onPointerUpObservable=new K,this.onPointerClickObservable=new K,this.onPointerEnterObservable=new K,this._behaviors=new Array}get typeName(){return this._getTypeName()}getClassName(){return this._getTypeName()}_getTypeName(){return"Control3D"}get node(){return this._node}get mesh(){return this._node instanceof _o?this._node:null}linkToTransformNode(e){return this._node&&(this._node.parent=e),this}_prepareNode(e){if(!this._node){if(this._node=this._createNode(e),!this.node)return;this._injectGUI3DReservedDataStore(this.node).control=this;const t=this.mesh;t&&(t.isPickable=!0,this._affectMaterial(t))}}_injectGUI3DReservedDataStore(e){return e.reservedDataStore=e.reservedDataStore??{},e.reservedDataStore.GUI3D=e.reservedDataStore.GUI3D??{},e.reservedDataStore.GUI3D}_createNode(e){return null}_affectMaterial(e){e.material=null}_isTouchButton3D(e){return void 0!==e._generatePointerEventType}_onPointerMove(e,t){this.onPointerMoveObservable.notifyObservers(t,-1,e,this)}_onPointerEnter(e){return-1===this._enterCount&&(this._enterCount=0),this._enterCount++,!(this._enterCount>1||(this.onPointerEnterObservable.notifyObservers(this,-1,e,this),this.pointerEnterAnimation&&this.pointerEnterAnimation(),0))}_onPointerOut(e){this._enterCount--,this._enterCount>0||(this._enterCount=0,this.onPointerOutObservable.notifyObservers(this,-1,e,this),this.pointerOutAnimation&&this.pointerOutAnimation())}_onPointerDown(e,t,i,s){return this._downCount++,this._downPointerIds[i]=this._downPointerIds[i]+1||1,1===this._downCount&&(this.onPointerDownObservable.notifyObservers(new SN(t,s),-1,e,this),this.pointerDownAnimation&&this.pointerDownAnimation(),!0)}_onPointerUp(e,t,i,s,r){this._downCount--,this._downPointerIds[i]--,this._downPointerIds[i]<=0&&delete this._downPointerIds[i],this._downCount<0?this._downCount=0:0==this._downCount&&(r&&(this._enterCount>0||-1===this._enterCount)&&this.onPointerClickObservable.notifyObservers(new SN(t,s),-1,e,this),this.onPointerUpObservable.notifyObservers(new SN(t,s),-1,e,this),this.pointerUpAnimation&&this.pointerUpAnimation())}forcePointerUp(e=null){if(null!==e)this._onPointerUp(this,_e.Zero(),e,0,!0);else{for(const e in this._downPointerIds)this._onPointerUp(this,_e.Zero(),+e,0,!0);this._downCount>0&&(this._downCount=1,this._onPointerUp(this,_e.Zero(),0,0,!0))}}_processObservables(e,t,i,s,r){if(this._isTouchButton3D(this)&&i&&(e=this._generatePointerEventType(e,i,this._downCount)),e===lr.POINTERMOVE){this._onPointerMove(this,t);const e=this._host._lastControlOver[s];return e&&e!==this&&e._onPointerOut(this),e!==this&&this._onPointerEnter(this),this._host._lastControlOver[s]=this,!0}return e===lr.POINTERDOWN?(this._onPointerDown(this,t,s,r),this._host._lastControlDown[s]=this,this._host._lastPickedControl=this,!0):(e===lr.POINTERUP||e===lr.POINTERDOUBLETAP)&&(this._host._lastControlDown[s]&&this._host._lastControlDown[s]._onPointerUp(this,t,s,r,!0),delete this._host._lastControlDown[s],!0)}_disposeNode(){this._node&&(this._node.dispose(),this._node=null)}dispose(){this.onPointerDownObservable.clear(),this.onPointerEnterObservable.clear(),this.onPointerMoveObservable.clear(),this.onPointerOutObservable.clear(),this.onPointerUpObservable.clear(),this.onPointerClickObservable.clear(),this._disposeNode();for(const e of this._behaviors)e.detach()}}class EN extends CN{constructor(){super(...arguments),this._contentResolution=512,this._contentScaleRatio=2}get content(){return this._content}set content(e){this._content=e,e&&this._host&&this._host.utilityLayer&&(this._facadeTexture?this._facadeTexture.rootContainer.clearControls():(this._facadeTexture=new xN("Facade",this._contentResolution,this._contentResolution,this._host.utilityLayer.utilityLayerScene,!0,Pa.TRILINEAR_SAMPLINGMODE),this._setFacadeTextureScaling(),this._facadeTexture.premulAlpha=!0),this._facadeTexture.addControl(e),this._applyFacade(this._facadeTexture))}_setFacadeTextureScaling(){this._facadeTexture&&(this._facadeTexture.rootContainer.scaleX=this._contentScaleRatio,this._facadeTexture.rootContainer.scaleY=this._contentScaleRatioY??this._contentScaleRatio)}get contentResolution(){return this._contentResolution}set contentResolution(e){this._contentResolution!==e&&(this._contentResolution=e,this._resetContent())}_disposeFacadeTexture(){this._facadeTexture&&(this._facadeTexture.dispose(),this._facadeTexture=null)}_resetContent(){this._disposeFacadeTexture(),this.content=this._content}_applyFacade(e){}}class AN extends EN{constructor(e){super(e)}_getTypeName(){return"AbstractButton3D"}_createNode(e){return new lo("button"+this.name,e)}}class PN extends AN{constructor(e,t){super(e),this._options={width:1,height:1,depth:.08,...t},this.pointerEnterAnimation=()=>{this.mesh&&(this._currentMaterial.emissiveColor=Ee.Red())},this.pointerOutAnimation=()=>{this._currentMaterial.emissiveColor=Ee.Black()},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_applyFacade(e){this._currentMaterial.emissiveTexture=e}_getTypeName(){return"Button3D"}_createNode(e){const t=new Array(6);for(let e=0;e<6;e++)t[e]=new pe(0,0,0,0);e.useRightHandedSystem?t[0].copyFromFloats(1,0,0,1):t[1].copyFromFloats(0,0,1,1);const i=cd(this.name+"_rootMesh",{width:this._options.width,height:this._options.height,depth:this._options.depth,faceUV:t,wrap:!0},e);return this._contentScaleRatioY=this._contentScaleRatio*this._options.width/this._options.height,this._setFacadeTextureScaling(),i}_affectMaterial(e){const t=new cu(this.name+"Material",e.getScene());t.specularColor=Ee.Black(),e.material=t,this._currentMaterial=t,this._resetContent()}dispose(){super.dispose(),this._disposeFacadeTexture(),this._currentMaterial&&this._currentMaterial.dispose()}}class IN extends CN{get children(){return this._children}get blockLayout(){return this._blockLayout}set blockLayout(e){this._blockLayout!==e&&(this._blockLayout=e,this._blockLayout||this._arrangeChildren())}constructor(e){super(e),this._blockLayout=!1,this._children=new Array}updateLayout(){return this._arrangeChildren(),this}containsControl(e){return-1!==this._children.indexOf(e)}addControl(e){return-1!==this._children.indexOf(e)||(e.parent=this,e._host=this._host,this._children.push(e),this._host.utilityLayer&&(e._prepareNode(this._host.utilityLayer.utilityLayerScene),e.node&&(e.node.parent=this.node),this.blockLayout||this._arrangeChildren())),this}_arrangeChildren(){}_createNode(e){return new lo("ContainerNode",e)}removeControl(e){const t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e.parent=null,e._disposeNode()),this}_getTypeName(){return"Container3D"}dispose(){for(const e of this._children)e.dispose();this._children.length=0,super.dispose()}}IN.UNSET_ORIENTATION=0,IN.FACEORIGIN_ORIENTATION=1,IN.FACEORIGINREVERSED_ORIENTATION=2,IN.FACEFORWARD_ORIENTATION=3,IN.FACEFORWARDREVERSED_ORIENTATION=4;class RN extends IN{get orientation(){return this._orientation}set orientation(e){this._orientation!==e&&(this._orientation=e,Ds.SetImmediate((()=>{this._arrangeChildren()})))}get columns(){return this._columns}set columns(e){this._columns!==e&&(this._columns=e,this._rowThenColum=!0,Ds.SetImmediate((()=>{this._arrangeChildren()})))}get rows(){return this._rows}set rows(e){this._rows!==e&&(this._rows=e,this._rowThenColum=!1,Ds.SetImmediate((()=>{this._arrangeChildren()})))}constructor(e){super(e),this._columns=10,this._rows=0,this._rowThenColum=!0,this._orientation=IN.FACEORIGIN_ORIENTATION,this.margin=0}_arrangeChildren(){this._cellWidth=0,this._cellHeight=0;let e=0,t=0,i=0;const s=me.Invert(this.node.computeWorldMatrix(!0));for(const e of this._children){if(!e.mesh)continue;i++,e.mesh.computeWorldMatrix(!0);const t=e.mesh.getHierarchyBoundingVectors(),r=ve.Vector3[0],n=ve.Vector3[1];t.max.subtractToRef(t.min,n),n.scaleInPlace(.5),_e.TransformNormalToRef(n,s,r),this._cellWidth=Math.max(this._cellWidth,2*r.x),this._cellHeight=Math.max(this._cellHeight,2*r.y)}this._cellWidth+=2*this.margin,this._cellHeight+=2*this.margin,this._rowThenColum?(t=this._columns,e=Math.ceil(i/this._columns)):(e=this._rows,t=Math.ceil(i/this._rows));const r=.5*t*this._cellWidth,n=.5*e*this._cellHeight,o=[];let a=0;if(this._rowThenColum)for(let s=0;si));e++);else for(let s=0;si));t++);a=0;for(const e of this._children)e.mesh&&(this._mapGridNode(e,o[a]),a++);this._finalProcessing()}_finalProcessing(){}}class MN extends RN{constructor(){super(...arguments),this._radius=5}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,Ds.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh;if(!i)return;const s=this._cylindricalMapping(t);switch(e.position=s,this.orientation){case IN.FACEORIGIN_ORIENTATION:i.lookAt(new _e(2*s.x,s.y,2*s.z));break;case IN.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new _e(-s.x,s.y,-s.z));break;case IN.FACEFORWARD_ORIENTATION:break;case IN.FACEFORWARDREVERSED_ORIENTATION:i.rotate(Xr.Y,Math.PI,Ur.LOCAL)}}_cylindricalMapping(e){const t=new _e(0,e.y,this._radius),i=e.x/this._radius;return me.RotationYawPitchRollToRef(i,0,0,ve.Matrix[0]),_e.TransformNormal(t,ve.Matrix[0])}}Bi.ShadersStore.fluentVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 world;uniform mat4 viewProjection;varying vec2 vUV;\n#ifdef BORDER\nvarying vec2 scaleInfo;uniform float borderWidth;uniform vec3 scaleFactor;\n#endif\n#ifdef HOVERLIGHT\nvarying vec3 worldPosition;\n#endif\nvoid main(void) {vUV=uv;\n#ifdef BORDER\nvec3 scale=scaleFactor;float minScale=min(min(scale.x,scale.y),scale.z);float maxScale=max(max(scale.x,scale.y),scale.z);float minOverMiddleScale=minScale/(scale.x+scale.y+scale.z-minScale-maxScale);float areaYZ=scale.y*scale.z;float areaXZ=scale.x*scale.z;float areaXY=scale.x*scale.y;float scaledBorderWidth=borderWidth; \nif (abs(normal.x)==1.0) \n{scale.x=scale.y;scale.y=scale.z;if (areaYZ>areaXZ && areaYZ>areaXY)\n{scaledBorderWidth*=minOverMiddleScale;}}\nelse if (abs(normal.y)==1.0) \n{scale.x=scale.z;if (areaXZ>areaXY && areaXZ>areaYZ)\n{scaledBorderWidth*=minOverMiddleScale;}}\nelse \n{if (areaXY>areaYZ && areaXY>areaXZ)\n{scaledBorderWidth*=minOverMiddleScale;}}\nfloat scaleRatio=min(scale.x,scale.y)/max(scale.x,scale.y);if (scale.x>scale.y)\n{scaleInfo.x=1.0-(scaledBorderWidth*scaleRatio);scaleInfo.y=1.0-scaledBorderWidth;}\nelse\n{scaleInfo.x=1.0-scaledBorderWidth;scaleInfo.y=1.0-(scaledBorderWidth*scaleRatio);} \n#endif \nvec4 worldPos=world*vec4(position,1.0);\n#ifdef HOVERLIGHT\nworldPosition=worldPos.xyz;\n#endif\ngl_Position=viewProjection*worldPos;}\n";Bi.ShadersStore.fluentPixelShader="precision highp float;varying vec2 vUV;uniform vec4 albedoColor;\n#ifdef INNERGLOW\nuniform vec4 innerGlowColor;\n#endif\n#ifdef BORDER\nvarying vec2 scaleInfo;uniform float edgeSmoothingValue;uniform float borderMinValue;\n#endif\n#ifdef HOVERLIGHT\nvarying vec3 worldPosition;uniform vec3 hoverPosition;uniform vec4 hoverColor;uniform float hoverRadius;\n#endif\n#ifdef TEXTURE\nuniform sampler2D albedoSampler;uniform mat4 textureMatrix;vec2 finalUV;\n#endif\nvoid main(void) {vec3 albedo=albedoColor.rgb;float alpha=albedoColor.a;\n#ifdef TEXTURE\nfinalUV=vec2(textureMatrix*vec4(vUV,1.0,0.0));albedo=texture2D(albedoSampler,finalUV).rgb;\n#endif\n#ifdef HOVERLIGHT\nfloat pointToHover=(1.0-clamp(length(hoverPosition-worldPosition)/hoverRadius,0.,1.))*hoverColor.a;albedo=clamp(albedo+hoverColor.rgb*pointToHover,0.,1.);\n#else\nfloat pointToHover=1.0;\n#endif\n#ifdef BORDER \nfloat borderPower=10.0;float inverseBorderPower=1.0/borderPower;vec3 borderColor=albedo*borderPower;vec2 distanceToEdge;distanceToEdge.x=abs(vUV.x-0.5)*2.0;distanceToEdge.y=abs(vUV.y-0.5)*2.0;float borderValue=max(smoothstep(scaleInfo.x-edgeSmoothingValue,scaleInfo.x+edgeSmoothingValue,distanceToEdge.x),\nsmoothstep(scaleInfo.y-edgeSmoothingValue,scaleInfo.y+edgeSmoothingValue,distanceToEdge.y));borderColor=borderColor*borderValue*max(borderMinValue*inverseBorderPower,pointToHover); \nalbedo+=borderColor;alpha=max(alpha,borderValue);\n#endif\n#ifdef INNERGLOW\nvec2 uvGlow=(vUV-vec2(0.5,0.5))*(innerGlowColor.a*2.0);uvGlow=uvGlow*uvGlow;uvGlow=uvGlow*uvGlow;albedo+=mix(vec3(0.0,0.0,0.0),innerGlowColor.rgb,uvGlow.x+uvGlow.y); \n#endif\ngl_FragColor=vec4(albedo,alpha);}";class ON extends xl{constructor(){super(),this.INNERGLOW=!1,this.BORDER=!1,this.HOVERLIGHT=!1,this.TEXTURE=!1,this.rebuild()}}class DN extends ml{constructor(e,t){super(e,t),this.innerGlowColorIntensity=.5,this.innerGlowColor=new Ee(1,1,1),this.albedoColor=new Ee(.3,.35,.4),this.renderBorders=!1,this.borderWidth=.5,this.edgeSmoothingValue=.02,this.borderMinValue=.1,this.renderHoverLight=!1,this.hoverRadius=.01,this.hoverColor=new Ae(.3,.3,.3,1),this.hoverPosition=_e.Zero()}needAlphaBlending(){return 1!==this.alpha}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new ON);const s=this.getScene(),r=t.materialDefines;if(!this.checkReadyOnEveryCall&&t.effect&&r._renderId===s.getRenderId())return!0;if(r._areTexturesDirty)if(r.INNERGLOW=this.innerGlowColorIntensity>0,r.BORDER=this.renderBorders,r.HOVERLIGHT=this.renderHoverLight,this._albedoTexture){if(!this._albedoTexture.isReadyOrNotBlocking())return!1;r.TEXTURE=!0}else r.TEXTURE=!1;const n=s.getEngine();if(r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=[er.PositionKind];e.push(er.NormalKind),e.push(er.UVKind);const i="fluent",o=["world","viewProjection","innerGlowColor","albedoColor","borderWidth","edgeSmoothingValue","scaleFactor","borderMinValue","hoverColor","hoverPosition","hoverRadius","textureMatrix"],a=["albedoSampler"],l=[];ea({uniformsNames:o,uniformBuffersNames:l,samplers:a,defines:r,maxSimultaneousLights:4});const h=r.toString();t.setEffect(s.getEngine().createEffect(i,{attributes:e,uniformsNames:o,uniformBuffersNames:l,samplers:a,defines:h,fallbacks:null,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(n){if(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._mustRebind(s,n,i)&&(this._activeEffect.setColor4("albedoColor",this.albedoColor,this.alpha),r.INNERGLOW&&this._activeEffect.setColor4("innerGlowColor",this.innerGlowColor,this.innerGlowColorIntensity),r.BORDER&&(this._activeEffect.setFloat("borderWidth",this.borderWidth),this._activeEffect.setFloat("edgeSmoothingValue",this.edgeSmoothingValue),this._activeEffect.setFloat("borderMinValue",this.borderMinValue),t.getBoundingInfo().boundingBox.extendSize.multiplyToRef(t.scaling,ve.Vector3[0]),this._activeEffect.setVector3("scaleFactor",ve.Vector3[0])),r.HOVERLIGHT&&(this._activeEffect.setDirectColor4("hoverColor",this.hoverColor),this._activeEffect.setFloat("hoverRadius",this.hoverRadius),this._activeEffect.setVector3("hoverPosition",this.hoverPosition)),r.TEXTURE&&this._albedoTexture)){this._activeEffect.setTexture("albedoSampler",this._albedoTexture);const e=this._albedoTexture.getTextureMatrix();this._activeEffect.setMatrix("textureMatrix",e)}this._afterBind(t,this._activeEffect,i)}}getActiveTextures(){return super.getActiveTextures()}hasTexture(e){return!!super.hasTexture(e)}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new DN(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GUI.FluentMaterial",e}getClassName(){return"FluentMaterial"}static Parse(e,t,i){return St.Parse((()=>new DN(e.name,t)),e,t,i)}}Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],DN.prototype,"innerGlowColorIntensity",void 0),Ze([ot()],DN.prototype,"innerGlowColor",void 0),Ze([ot()],DN.prototype,"albedoColor",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],DN.prototype,"renderBorders",void 0),Ze([rt()],DN.prototype,"borderWidth",void 0),Ze([rt()],DN.prototype,"edgeSmoothingValue",void 0),Ze([rt()],DN.prototype,"borderMinValue",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],DN.prototype,"renderHoverLight",void 0),Ze([rt()],DN.prototype,"hoverRadius",void 0),Ze([dt()],DN.prototype,"hoverColor",void 0),Ze([ht()],DN.prototype,"hoverPosition",void 0),Ze([nt("albedoTexture")],DN.prototype,"_albedoTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesAndMiscDirty")],DN.prototype,"albedoTexture",void 0),z("BABYLON.GUI.FluentMaterial",DN);class wN extends RN{get backPlateMargin(){return this._backPlateMargin}set backPlateMargin(e){this._backPlateMargin=e,this._children.length>=1&&(this.children.forEach((e=>{this._updateCurrentMinMax(e.position)})),this._updateMargins())}_createNode(e){const t=new ha(`menu_${this.name}`,e);return this._backPlate=cd("backPlate"+this.name,{size:1},e),this._backPlate.parent=t,t}_affectMaterial(e){this._backPlateMaterial=new DN(this.name+"backPlateMaterial",e.getScene()),this._backPlateMaterial.albedoColor=new Ee(.08,.15,.55),this._backPlateMaterial.renderBorders=!0,this._backPlateMaterial.renderHoverLight=!0,this._pickedPointObserver=this._host.onPickedPointChangedObservable.add((e=>{e?(this._backPlateMaterial.hoverPosition=e,this._backPlateMaterial.hoverColor.a=1):this._backPlateMaterial.hoverColor.a=0})),this._backPlate.material=this._backPlateMaterial}_mapGridNode(e,t){e.mesh&&(e.position=t.clone(),this._updateCurrentMinMax(t))}_finalProcessing(){this._updateMargins()}_updateCurrentMinMax(e){this._currentMin||(this._currentMin=e.clone(),this._currentMax=e.clone()),this._currentMin.minimizeInPlace(e),this._currentMax.maximizeInPlace(e)}_updateMargins(){if(this._children.length>0){this._currentMin.addInPlaceFromFloats(-this._cellWidth/2,-this._cellHeight/2,0),this._currentMax.addInPlaceFromFloats(this._cellWidth/2,this._cellHeight/2,0);const e=this._currentMax.subtract(this._currentMin);this._backPlate.scaling.x=e.x+this._cellWidth*this.backPlateMargin,this._backPlate.scaling.y=e.y+this._cellHeight*this.backPlateMargin,this._backPlate.scaling.z=.001;for(let t=0;t0.0 ? g : 1.0;Gradient2=Position_Object.z>0.0 ? 1.0 : g;} else {Gradient1=g+(1.0-g)*(Radial_Gradient);Gradient2=1.0;}}\nvoid Pick_Radius_B144(\nfloat Radius,\nfloat Radius_Top_Left,\nfloat Radius_Top_Right,\nfloat Radius_Bottom_Left,\nfloat Radius_Bottom_Right,\nvec3 Position,\nout float Result)\n{bool whichY=Position.y>0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid main()\n{vec3 Nrm_World_Q128;Nrm_World_Q128=normalize((world*vec4(normal,0.0)).xyz);vec3 Tangent_World_Q131;vec3 Tangent_World_N_Q131;float Tangent_Length_Q131;Tangent_World_Q131=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q131=length(Tangent_World_Q131);Tangent_World_N_Q131=Tangent_World_Q131/Tangent_Length_Q131;vec3 Binormal_World_Q132;vec3 Binormal_World_N_Q132;float Binormal_Length_Q132;Object_To_World_Dir_B132(vec3(0,1,0),Binormal_World_Q132,Binormal_World_N_Q132,Binormal_Length_Q132);float Anisotropy_Q133=Tangent_Length_Q131/Binormal_Length_Q132;vec3 Result_Q177;Result_Q177=mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(_Use_Global_Left_Index_));vec3 Result_Q178;Result_Q178=mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(_Use_Global_Right_Index_));float Result_Q144;Pick_Radius_B144(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q144);vec3 Dir_Q140;PickDir_B140(_Angle_,Tangent_World_N_Q131,Binormal_World_N_Q132,Dir_Q140);float Radius_Q147;float Line_Width_Q147;RelativeOrAbsoluteDetail_B147(Result_Q144,_Line_Width_,_Absolute_Sizes_,Binormal_Length_Q132,Radius_Q147,Line_Width_Q147);vec4 Out_Color_Q145=vec4(Radius_Q147,Line_Width_Q147,0,1);vec3 New_P_Q129;vec2 New_UV_Q129;float Radial_Gradient_Q129;vec3 Radial_Dir_Q129;Move_Verts_B129(Anisotropy_Q133,position,Radius_Q147,New_P_Q129,New_UV_Q129,Radial_Gradient_Q129,Radial_Dir_Q129);vec3 Pos_World_Q115;Object_To_World_Pos_B115(New_P_Q129,Pos_World_Q115);vec4 Blob_Info_Q180;\n#if BLOB_ENABLE\nBlob_Vertex_B180(Pos_World_Q115,Nrm_World_Q128,Tangent_World_N_Q131,Binormal_World_N_Q132,Result_Q177,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q180);\n#else\nBlob_Info_Q180=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q181;\n#if BLOB_ENABLE_2\nBlob_Vertex_B180(Pos_World_Q115,Nrm_World_Q128,Tangent_World_N_Q131,Binormal_World_N_Q132,Result_Q178,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q181);\n#else\nBlob_Info_Q181=vec4(0,0,0,0);\n#endif\nfloat Gradient1_Q130;float Gradient2_Q130;\n#if SMOOTH_EDGES\nEdge_AA_Vertex_B130(Pos_World_Q115,position,normal,cameraPosition,Radial_Gradient_Q129,Radial_Dir_Q129,tangent,Gradient1_Q130,Gradient2_Q130);\n#else\nGradient1_Q130=1.0;Gradient2_Q130=1.0;\n#endif\nvec2 Rect_UV_Q139;vec4 Rect_Parms_Q139;vec2 Scale_XY_Q139;vec2 Line_UV_Q139;Round_Rect_Vertex_B139(New_UV_Q129,Radius_Q147,0.0,Anisotropy_Q133,Gradient1_Q130,Gradient2_Q130,Rect_UV_Q139,Rect_Parms_Q139,Scale_XY_Q139,Line_UV_Q139);vec3 Line_Vertex_Q135;Line_Vertex_B135(Scale_XY_Q139,Line_UV_Q139,0.0,_Rate_,_Highlight_Transform_,Line_Vertex_Q135);vec3 Position=Pos_World_Q115;vec3 Normal=Dir_Q140;vec2 UV=Rect_UV_Q139;vec3 Tangent=Line_Vertex_Q135;vec3 Binormal=Nrm_World_Q128;vec4 Color=Out_Color_Q145;vec4 Extra1=Rect_Parms_Q139;vec4 Extra2=Blob_Info_Q180;vec4 Extra3=Blob_Info_Q181;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class FN extends xl{constructor(){super(),this.BLOB_ENABLE=!0,this.BLOB_ENABLE_2=!0,this.SMOOTH_EDGES=!0,this.IRIDESCENT_MAP_ENABLE=!0,this._needNormals=!0,this.rebuild()}}class LN extends ml{constructor(e,t){super(e,t),this.radius=.03,this.lineWidth=.01,this.absoluteSizes=!1,this._filterWidth=1,this.baseColor=new Ae(.0392157,.0666667,.207843,1),this.lineColor=new Ae(.14902,.133333,.384314,1),this.blobIntensity=.98,this.blobFarSize=.04,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.08,this.blobNearSize=.22,this.blobPulse=0,this.blobFade=0,this.blobNearSize2=.22,this.blobPulse2=0,this.blobFade2=0,this._rate=.135,this.highlightColor=new Ae(.98,.98,.98,1),this.highlightWidth=.25,this._highlightTransform=new pe(1,1,0,0),this._highlight=1,this.iridescenceIntensity=0,this.iridescenceEdgeIntensity=1,this._angle=-45,this.fadeOut=1,this._reflected=!0,this._frequency=1,this._verticalOffset=0,this.globalLeftIndexTipPosition=_e.Zero(),this._globalLeftIndexTipPosition4=pe.Zero(),this.globalRightIndexTipPosition=_e.Zero(),this._globalRightIndexTipPosition4=pe.Zero(),this.alphaMode=N_.ALPHA_DISABLE,this.backFaceCulling=!1,this._blobTexture=new Pa(LN.BLOB_TEXTURE_URL,this.getScene(),!0,!1,Pa.NEAREST_SAMPLINGMODE),this._iridescentMap=new Pa(LN.IM_TEXTURE_URL,this.getScene(),!0,!1,Pa.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new FN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="fluentBackplate",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Absolute_Sizes_","_Filter_Width_","_Base_Color_","_Line_Color_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Rate_","_Highlight_Color_","_Highlight_Width_","_Highlight_Transform_","_Highlight_","_Iridescence_Intensity_","_Iridescence_Edge_Intensity_","_Angle_","_Fade_Out_","_Reflected_","_Frequency_","_Vertical_Offset_","_Iridescent_Map_","_Use_Global_Left_Index_","_Use_Global_Right_Index_","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position"],h=["_Blob_Texture_","_Iridescent_Map_"],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera?.position??_e.ZeroReadOnly),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Base_Color_",this.baseColor),this._activeEffect.setDirectColor4("_Line_Color_",this.lineColor),this._activeEffect.setFloat("_Radius_Top_Left_",1),this._activeEffect.setFloat("_Radius_Top_Right_",1),this._activeEffect.setFloat("_Radius_Bottom_Left_",1),this._activeEffect.setFloat("_Radius_Bottom_Right_",1),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setFloat("_Rate_",this._rate),this._activeEffect.setDirectColor4("_Highlight_Color_",this.highlightColor),this._activeEffect.setFloat("_Highlight_Width_",this.highlightWidth),this._activeEffect.setVector4("_Highlight_Transform_",this._highlightTransform),this._activeEffect.setFloat("_Highlight_",this._highlight),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setFloat("_Iridescence_Edge_Intensity_",this.iridescenceEdgeIntensity),this._activeEffect.setFloat("_Angle_",this._angle),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._activeEffect.setFloat("_Reflected_",this._reflected?1:0),this._activeEffect.setFloat("_Frequency_",this._frequency),this._activeEffect.setFloat("_Vertical_Offset_",this._verticalOffset),this._activeEffect.setTexture("_Iridescent_Map_",this._iridescentMap),this._activeEffect.setFloat("_Use_Global_Left_Index_",1),this._activeEffect.setFloat("_Use_Global_Right_Index_",1),this._globalLeftIndexTipPosition4.set(this.globalLeftIndexTipPosition.x,this.globalLeftIndexTipPosition.y,this.globalLeftIndexTipPosition.z,1),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this._globalLeftIndexTipPosition4),this._globalRightIndexTipPosition4.set(this.globalRightIndexTipPosition.x,this.globalRightIndexTipPosition.y,this.globalRightIndexTipPosition.z,1),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this._globalRightIndexTipPosition4),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._blobTexture.dispose(),this._iridescentMap.dispose()}clone(e){return St.Clone((()=>new LN(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FluentBackplateMaterial",e}getClassName(){return"FluentBackplateMaterial"}static Parse(e,t,i){return St.Parse((()=>new LN(e.name,t)),e,t,i)}}LN.BLOB_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-backplate-blob.png",LN.IM_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-backplate-iridescence.png",Ze([rt()],LN.prototype,"radius",void 0),Ze([rt()],LN.prototype,"lineWidth",void 0),Ze([rt()],LN.prototype,"absoluteSizes",void 0),Ze([rt()],LN.prototype,"baseColor",void 0),Ze([rt()],LN.prototype,"lineColor",void 0),Ze([rt()],LN.prototype,"blobIntensity",void 0),Ze([rt()],LN.prototype,"blobFarSize",void 0),Ze([rt()],LN.prototype,"blobNearDistance",void 0),Ze([rt()],LN.prototype,"blobFarDistance",void 0),Ze([rt()],LN.prototype,"blobFadeLength",void 0),Ze([rt()],LN.prototype,"blobNearSize",void 0),Ze([rt()],LN.prototype,"blobPulse",void 0),Ze([rt()],LN.prototype,"blobFade",void 0),Ze([rt()],LN.prototype,"blobNearSize2",void 0),Ze([rt()],LN.prototype,"blobPulse2",void 0),Ze([rt()],LN.prototype,"blobFade2",void 0),Ze([rt()],LN.prototype,"highlightColor",void 0),Ze([rt()],LN.prototype,"highlightWidth",void 0),Ze([rt()],LN.prototype,"iridescenceIntensity",void 0),Ze([rt()],LN.prototype,"iridescenceEdgeIntensity",void 0),Ze([rt()],LN.prototype,"fadeOut",void 0),Ze([ht()],LN.prototype,"globalLeftIndexTipPosition",void 0),Ze([ht()],LN.prototype,"globalRightIndexTipPosition",void 0),z("BABYLON.GUI.FluentBackplateMaterial",LN);class BN extends CN{set renderingGroupId(e){this._model.renderingGroupId=e}get renderingGroupId(){return this._model.renderingGroupId}get material(){return this._material}get shareMaterials(){return this._shareMaterials}constructor(e,t=!0){super(e),this._shareMaterials=t}_getTypeName(){return"HolographicBackplate"}_createNode(e){const t=cd((this.name??"HolographicBackplate")+"_CollisionMesh",{width:1,height:1,depth:1},e);return t.isPickable=!0,t.visibility=0,fl.ImportMeshAsync(void 0,BN.MODEL_BASE_URL,BN.MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_frontPlate`,i.isPickable=!1,i.parent=t,this._material&&(i.material=this._material),this._model=i})),t}_createMaterial(e){this._material=new LN(this.name+" Material",e.getScene())}_affectMaterial(e){this._shareMaterials?this._host._touchSharedMaterials.fluentBackplateMaterial?this._material=this._host._touchSharedMaterials.fluentBackplateMaterial:(this._createMaterial(e),this._host._touchSharedMaterials.fluentBackplateMaterial=this._material):this._createMaterial(e)}dispose(){super.dispose(),this.shareMaterials||this._material.dispose(),this._model.dispose()}}BN.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",BN.MODEL_FILENAME="mrtk-fluent-backplate.glb";class kN extends PN{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=Wa("",{size:1},this._backPlate._scene);const t=Wa("",{size:1,sideOrientation:ha.DOUBLESIDE},this._backPlate._scene),i=new cu("",this._backPlate._scene);i.diffuseColor=Ee.FromHexString("#212121"),t.material=i,t.isPickable=!1,this._tooltipMesh.addChild(t),t.position=_e.Forward(e).scale(.05),this._tooltipMesh.scaling.y=1/3,this._tooltipMesh.position=_e.Up().scale(.7).add(_e.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._backPlate,this._tooltipTexture=xN.CreateForMesh(this._tooltipMesh),this._tooltipTextBlock=new Fw,this._tooltipTextBlock.scaleY=3,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=130,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new Va,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?this._tooltipTextBlock.text:null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}constructor(e,t=!0){super(e),this._shareMaterials=!0,this._shareMaterials=t,this.pointerEnterAnimation=()=>{this.mesh&&this._frontPlate.setEnabled(!0)},this.pointerOutAnimation=()=>{this.mesh&&this._frontPlate.setEnabled(!1)}}_getTypeName(){return"HolographicButton"}_rebuildContent(){this._disposeFacadeTexture();const e=new kw;if(e.isVertical=!0,Ut()&&document.createElement&&this._imageUrl){const t=new Lw;t.source=this._imageUrl,t.paddingTop="40px",t.height="180px",t.width="100px",t.paddingBottom="40px",e.addControl(t)}if(this._text){const t=new Fw;t.text=this._text,t.color="white",t.height="30px",t.fontSize=24,e.addControl(t)}this._frontPlate&&(this.content=e)}_createNode(e){return this._backPlate=cd(this.name+"BackMesh",{width:1,height:1,depth:.08},e),this._frontPlate=cd(this.name+"FrontMesh",{width:1,height:1,depth:.08},e),this._frontPlate.parent=this._backPlate,this._frontPlate.position=_e.Forward(e.useRightHandedSystem).scale(-.08),this._frontPlate.isPickable=!1,this._frontPlate.setEnabled(!1),this._textPlate=super._createNode(e),this._textPlate.parent=this._backPlate,this._textPlate.position=_e.Forward(e.useRightHandedSystem).scale(-.08),this._textPlate.isPickable=!1,this._backPlate}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e}_createBackMaterial(e){this._backMaterial=new DN(this.name+"Back Material",e.getScene()),this._backMaterial.renderHoverLight=!0,this._pickedPointObserver=this._host.onPickedPointChangedObservable.add((e=>{e?(this._backMaterial.hoverPosition=e,this._backMaterial.hoverColor.a=1):this._backMaterial.hoverColor.a=0}))}_createFrontMaterial(e){this._frontMaterial=new DN(this.name+"Front Material",e.getScene()),this._frontMaterial.innerGlowColorIntensity=0,this._frontMaterial.alpha=.5,this._frontMaterial.renderBorders=!0}_createPlateMaterial(e){this._plateMaterial=new cu(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=Ee.Black()}_affectMaterial(e){this._shareMaterials?(this._host._sharedMaterials.backFluentMaterial?this._backMaterial=this._host._sharedMaterials.backFluentMaterial:(this._createBackMaterial(e),this._host._sharedMaterials.backFluentMaterial=this._backMaterial),this._host._sharedMaterials.frontFluentMaterial?this._frontMaterial=this._host._sharedMaterials.frontFluentMaterial:(this._createFrontMaterial(e),this._host._sharedMaterials.frontFluentMaterial=this._frontMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._frontPlate.material=this._frontMaterial,this._textPlate.material=this._plateMaterial,this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}Bi.ShadersStore.fluentButtonPixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;uniform float _Edge_Width_;uniform vec4 _Edge_Color_;uniform bool _Relative_Width_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Active_Face_Dir_;uniform vec3 _Active_Face_Up_;uniform bool Enable_Fade;uniform float _Fade_Width_;uniform bool _Smooth_Active_Face_;uniform bool _Show_Frame_;uniform bool _Use_Blob_Texture_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;void Holo_Edge_Fragment_B35(\nvec4 Edges,\nfloat Edge_Width,\nout float NotEdge)\n{vec2 c=vec2(min(Edges.r,Edges.g),min(Edges.b,Edges.a));vec2 df=fwidth(c)*Edge_Width;vec2 g=clamp(c/df,0.0,1.0);NotEdge=g.x*g.y;}\nvoid Blob_Fragment_B39(\nvec2 UV,\nvec3 Blob_Info,\nsampler2D Blob_Texture,\nout vec4 Blob_Color)\n{float k=dot(UV,UV);Blob_Color=Blob_Info.y*texture(Blob_Texture,vec2(vec2(sqrt(k),Blob_Info.x).x,1.0-vec2(sqrt(k),Blob_Info.x).y))*(1.0-clamp(k,0.0,1.0));}\nvec2 FilterStep(vec2 Edge,vec2 X)\n{vec2 dX=max(fwidth(X),vec2(0.00001,0.00001));return clamp( (X+dX-max(Edge,X-dX))/(dX*2.0),0.0,1.0);}\nvoid Wireframe_Fragment_B59(\nvec3 Widths,\nvec2 UV,\nfloat Proximity,\nvec4 Edge_Color,\nout vec4 Wireframe)\n{vec2 c=min(UV,vec2(1.0,1.0)-UV);vec2 g=FilterStep(Widths.xy*0.5,c); \nWireframe=(1.0-min(g.x,g.y))*Proximity*Edge_Color;}\nvoid Proximity_B53(\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Proximity_Max_Intensity,\nfloat Proximity_Near_Radius,\nvec3 Position,\nvec3 Show_Selection,\nvec4 Extra1,\nfloat Dist_To_Face,\nfloat Intensity,\nout float Proximity)\n{vec2 delta1=Extra1.xy;vec2 delta2=Extra1.zw;float d2=sqrt(min(dot(delta1,delta1),dot(delta2,delta2))+Dist_To_Face*Dist_To_Face);Proximity=Intensity*Proximity_Max_Intensity*(1.0-clamp(d2/Proximity_Near_Radius,0.0,1.0))*(1.0-Show_Selection.x)+Show_Selection.x;}\nvoid To_XYZ_B46(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid main()\n{float NotEdge_Q35;\n#if ENABLE_FADE\nHolo_Edge_Fragment_B35(vColor,_Fade_Width_,NotEdge_Q35);\n#else\nNotEdge_Q35=1.0;\n#endif\nvec4 Blob_Color_Q39;float k=dot(vUV,vUV);vec2 blobTextureCoord=vec2(vec2(sqrt(k),vTangent.x).x,1.0-vec2(sqrt(k),vTangent.x).y);vec4 blobColor=mix(vec4(1.0,1.0,1.0,1.0)*step(1.0-vTangent.x,clamp(sqrt(k)+0.1,0.0,1.0)),texture(_Blob_Texture_,blobTextureCoord),float(_Use_Blob_Texture_));Blob_Color_Q39=vTangent.y*blobColor*(1.0-clamp(k,0.0,1.0));float Is_Quad_Q24;Is_Quad_Q24=vNormal.z;vec3 Blob_Position_Q41= mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(Use_Global_Left_Index));vec3 Blob_Position_Q42= mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(Use_Global_Right_Index));float X_Q46;float Y_Q46;float Z_Q46;To_XYZ_B46(vBinormal,X_Q46,Y_Q46,Z_Q46);float Proximity_Q53;Proximity_B53(Blob_Position_Q41,Blob_Position_Q42,_Proximity_Max_Intensity_,_Proximity_Near_Radius_,vPosition,vBinormal,vExtra1,Y_Q46,Z_Q46,Proximity_Q53);vec4 Wireframe_Q59;Wireframe_Fragment_B59(vNormal,vUV,Proximity_Q53,_Edge_Color_,Wireframe_Q59);vec4 Wire_Or_Blob_Q23=mix(Wireframe_Q59,Blob_Color_Q39,Is_Quad_Q24);vec4 Result_Q22;Result_Q22=mix(Wire_Or_Blob_Q23,vec4(0.3,0.3,0.3,0.3),float(_Show_Frame_));vec4 Final_Color_Q37=NotEdge_Q35*Result_Q22;vec4 Out_Color=Final_Color_Q37;float Clip_Threshold=0.0;bool To_sRGB=false;gl_FragColor=Out_Color;}";Bi.ShadersStore.fluentButtonVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform float _Edge_Width_;uniform vec4 _Edge_Color_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Active_Face_Dir_;uniform vec3 _Active_Face_Up_;uniform bool _Enable_Fade_;uniform float _Fade_Width_;uniform bool _Smooth_Active_Face_;uniform bool _Show_Frame_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;void Blob_Vertex_B47(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nvec3 Blob_Position,\nfloat Intensity,\nfloat Blob_Near_Size,\nfloat Blob_Far_Size,\nfloat Blob_Near_Distance,\nfloat Blob_Far_Distance,\nvec4 Vx_Color,\nvec2 UV,\nvec3 Face_Center,\nvec2 Face_Size,\nvec2 In_UV,\nfloat Blob_Fade_Length,\nfloat Selection_Fade,\nfloat Selection_Fade_Size,\nfloat Inner_Fade,\nvec3 Active_Face_Center,\nfloat Blob_Pulse,\nfloat Blob_Fade,\nfloat Blob_Enabled,\nout vec3 Out_Position,\nout vec2 Out_UV,\nout vec3 Blob_Info)\n{float blobSize,fadeIn;vec3 Hit_Position;Blob_Info=vec3(0.0,0.0,0.0);float Hit_Distance=dot(Blob_Position-Face_Center,Normal);Hit_Position=Blob_Position-Hit_Distance*Normal;float absD=abs(Hit_Distance);float lerpVal=clamp((absD-Blob_Near_Distance)/(Blob_Far_Distance-Blob_Near_Distance),0.0,1.0);fadeIn=1.0-clamp((absD-Blob_Far_Distance)/Blob_Fade_Length,0.0,1.0);float innerFade=1.0-clamp(-Hit_Distance/Inner_Fade,0.0,1.0);float farClip=clamp(1.0-step(Blob_Far_Distance+Blob_Fade_Length,absD),0.0,1.0);float size=mix(Blob_Near_Size,Blob_Far_Size,lerpVal)*farClip;blobSize=mix(size,Selection_Fade_Size,Selection_Fade)*innerFade*Blob_Enabled;Blob_Info.x=lerpVal*0.5+0.5;Blob_Info.y=fadeIn*Intensity*(1.0-Selection_Fade)*Blob_Fade;Blob_Info.x*=(1.0-Blob_Pulse);vec3 delta=Hit_Position-Face_Center;vec2 blobCenterXY=vec2(dot(delta,Tangent),dot(delta,Bitangent));vec2 quadUVin=2.0*UV-1.0; \nvec2 blobXY=blobCenterXY+quadUVin*blobSize;vec2 blobClipped=clamp(blobXY,-Face_Size*0.5,Face_Size*0.5);vec2 blobUV=(blobClipped-blobCenterXY)/max(blobSize,0.0001)*2.0;vec3 blobCorner=Face_Center+blobClipped.x*Tangent+blobClipped.y*Bitangent;Out_Position=mix(Position,blobCorner,Vx_Color.rrr);Out_UV=mix(In_UV,blobUV,Vx_Color.rr);}\nvec2 ProjectProximity(\nvec3 blobPosition,\nvec3 position,\nvec3 center,\nvec3 dir,\nvec3 xdir,\nvec3 ydir,\nout float vdistance\n)\n{vec3 delta=blobPosition-position;vec2 xy=vec2(dot(delta,xdir),dot(delta,ydir));vdistance=abs(dot(delta,dir));return xy;}\nvoid Proximity_Vertex_B66(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Active_Face_Center,\nvec3 Active_Face_Dir,\nvec3 Position,\nfloat Proximity_Far_Distance,\nfloat Relative_Scale,\nfloat Proximity_Anisotropy,\nvec3 Up,\nout vec4 Extra1,\nout float Distance_To_Face,\nout float Intensity)\n{vec3 Active_Face_Dir_X=normalize(cross(Active_Face_Dir,Up));vec3 Active_Face_Dir_Y=cross(Active_Face_Dir,Active_Face_Dir_X);float distz1,distz2;Extra1.xy=ProjectProximity(Blob_Position,Position,Active_Face_Center,Active_Face_Dir,Active_Face_Dir_X*Proximity_Anisotropy,Active_Face_Dir_Y,distz1)/Relative_Scale;Extra1.zw=ProjectProximity(Blob_Position_2,Position,Active_Face_Center,Active_Face_Dir,Active_Face_Dir_X*Proximity_Anisotropy,Active_Face_Dir_Y,distz2)/Relative_Scale;Distance_To_Face=dot(Active_Face_Dir,Position-Active_Face_Center);Intensity=1.0-clamp(min(distz1,distz2)/Proximity_Far_Distance,0.0,1.0);}\nvoid Holo_Edge_Vertex_B44(\nvec3 Incident,\nvec3 Normal,\nvec2 UV,\nvec3 Tangent,\nvec3 Bitangent,\nbool Smooth_Active_Face,\nfloat Active,\nout vec4 Holo_Edges)\n{float NdotI=dot(Incident,Normal);vec2 flip=(UV-vec2(0.5,0.5));float udot=dot(Incident,Tangent)*flip.x*NdotI;float uval=1.0-float(udot>0.0);float vdot=-dot(Incident,Bitangent)*flip.y*NdotI;float vval=1.0-float(vdot>0.0);float Smooth_And_Active=step(1.0,float(Smooth_Active_Face && Active>0.0));uval=mix(uval,max(1.0,uval),Smooth_And_Active); \nvval=mix(vval,max(1.0,vval),Smooth_And_Active);Holo_Edges=vec4(1.0,1.0,1.0,1.0)-vec4(uval*UV.x,uval*(1.0-UV.x),vval*UV.y,vval*(1.0-UV.y));}\nvoid Object_To_World_Pos_B13(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Choose_Blob_B38(\nvec4 Vx_Color,\nvec3 Position1,\nvec3 Position2,\nbool Blob_Enable_1,\nbool Blob_Enable_2,\nfloat Near_Size_1,\nfloat Near_Size_2,\nfloat Blob_Inner_Fade_1,\nfloat Blob_Inner_Fade_2,\nfloat Blob_Pulse_1,\nfloat Blob_Pulse_2,\nfloat Blob_Fade_1,\nfloat Blob_Fade_2,\nout vec3 Position,\nout float Near_Size,\nout float Inner_Fade,\nout float Blob_Enable,\nout float Fade,\nout float Pulse)\n{Position=Position1*(1.0-Vx_Color.g)+Vx_Color.g*Position2;float b1=float(Blob_Enable_1);float b2=float(Blob_Enable_2);Blob_Enable=b1+(b2-b1)*Vx_Color.g;Pulse=Blob_Pulse_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Pulse_2;Fade=Blob_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Fade_2;Near_Size=Near_Size_1*(1.0-Vx_Color.g)+Vx_Color.g*Near_Size_2;Inner_Fade=Blob_Inner_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Inner_Fade_2;}\nvoid Wireframe_Vertex_B51(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Edge_Width,\nvec2 Face_Size,\nout vec3 Wire_Vx_Pos,\nout vec2 UV,\nout vec2 Widths)\n{Widths.xy=Edge_Width/Face_Size;float x=dot(Position,Tangent);float y=dot(Position,Bitangent);float dx=0.5-abs(x);float newx=(0.5-dx*Widths.x*2.0)*sign(x);float dy=0.5-abs(y);float newy=(0.5-dy*Widths.y*2.0)*sign(y);Wire_Vx_Pos=Normal*0.5+newx*Tangent+newy*Bitangent;UV.x=dot(Wire_Vx_Pos,Tangent)+0.5;UV.y=dot(Wire_Vx_Pos,Bitangent)+0.5;}\nvec2 ramp2(vec2 start,vec2 end,vec2 x)\n{return clamp((x-start)/(end-start),vec2(0.0,0.0),vec2(1.0,1.0));}\nfloat computeSelection(\nvec3 blobPosition,\nvec3 normal,\nvec3 tangent,\nvec3 bitangent,\nvec3 faceCenter,\nvec2 faceSize,\nfloat selectionFuzz,\nfloat farDistance,\nfloat fadeLength\n)\n{vec3 delta=blobPosition-faceCenter;float absD=abs(dot(delta,normal));float fadeIn=1.0-clamp((absD-farDistance)/fadeLength,0.0,1.0);vec2 blobCenterXY=vec2(dot(delta,tangent),dot(delta,bitangent));vec2 innerFace=faceSize*(1.0-selectionFuzz)*0.5;vec2 selectPulse=ramp2(-faceSize*0.5,-innerFace,blobCenterXY)-ramp2(innerFace,faceSize*0.5,blobCenterXY);return selectPulse.x*selectPulse.y*fadeIn;}\nvoid Selection_Vertex_B48(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec2 Face_Size,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Selection_Fuzz,\nfloat Selected,\nfloat Far_Distance,\nfloat Fade_Length,\nvec3 Active_Face_Dir,\nout float Show_Selection)\n{float select1=computeSelection(Blob_Position,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float select2=computeSelection(Blob_Position_2,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float Active=max(0.0,dot(Active_Face_Dir,Normal));Show_Selection=mix(max(select1,select2),1.0,Selected)*Active;}\nvoid Proximity_Visibility_B54(\nfloat Selection,\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Input_Width,\nfloat Proximity_Far_Distance,\nfloat Proximity_Radius,\nvec3 Active_Face_Center,\nvec3 Active_Face_Dir,\nout float Width)\n{vec3 boxEdges=(world*vec4(vec3(0.5,0.5,0.5),0.0)).xyz;float boxMaxSize=length(boxEdges);float d1=dot(Proximity_Center-Active_Face_Center,Active_Face_Dir);vec3 blob1=Proximity_Center-d1*Active_Face_Dir;float d2=dot(Proximity_Center_2-Active_Face_Center,Active_Face_Dir);vec3 blob2=Proximity_Center_2-d2*Active_Face_Dir;vec3 delta1=blob1-Active_Face_Center;vec3 delta2=blob2-Active_Face_Center;float dist1=dot(delta1,delta1);float dist2=dot(delta2,delta2);float nearestProxDist=sqrt(min(dist1,dist2));Width=Input_Width*(1.0-step(boxMaxSize+Proximity_Radius,nearestProxDist))*(1.0-step(Proximity_Far_Distance,min(d1,d2))*(1.0-step(0.0001,Selection)));}\nvoid Object_To_World_Dir_B67(\nvec3 Dir_Object,\nout vec3 Dir_World)\n{Dir_World=(world*vec4(Dir_Object,0.0)).xyz;}\nvoid main()\n{vec3 Active_Face_Center_Q49;Active_Face_Center_Q49=(world*vec4(_Active_Face_Dir_*0.5,1.0)).xyz;vec3 Blob_Position_Q41= mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(Use_Global_Left_Index));vec3 Blob_Position_Q42= mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(Use_Global_Right_Index));vec3 Active_Face_Dir_Q64=normalize((world*vec4(_Active_Face_Dir_,0.0)).xyz);float Relative_Scale_Q57;\n#if RELATIVE_WIDTH\nRelative_Scale_Q57=length((world*vec4(vec3(0,1,0),0.0)).xyz);\n#else\nRelative_Scale_Q57=1.0;\n#endif\nvec3 Tangent_World_Q30;Tangent_World_Q30=(world*vec4(tangent,0.0)).xyz;vec3 Binormal_World_Q31;Binormal_World_Q31=(world*vec4((cross(normal,tangent)),0.0)).xyz;vec3 Normal_World_Q60;Normal_World_Q60=(world*vec4(normal,0.0)).xyz;vec3 Result_Q18=0.5*normal;vec3 Dir_World_Q67;Object_To_World_Dir_B67(_Active_Face_Up_,Dir_World_Q67);float Product_Q56=_Edge_Width_*Relative_Scale_Q57;vec3 Normal_World_N_Q29=normalize(Normal_World_Q60);vec3 Tangent_World_N_Q28=normalize(Tangent_World_Q30);vec3 Binormal_World_N_Q32=normalize(Binormal_World_Q31);vec3 Position_Q38;float Near_Size_Q38;float Inner_Fade_Q38;float Blob_Enable_Q38;float Fade_Q38;float Pulse_Q38;Choose_Blob_B38(color,Blob_Position_Q41,Blob_Position_Q42,_Blob_Enable_,_Blob_Enable_2_,_Blob_Near_Size_,_Blob_Near_Size_2_,_Blob_Inner_Fade_,_Blob_Inner_Fade_2_,_Blob_Pulse_,_Blob_Pulse_2_,_Blob_Fade_,_Blob_Fade_2_,Position_Q38,Near_Size_Q38,Inner_Fade_Q38,Blob_Enable_Q38,Fade_Q38,Pulse_Q38);vec3 Face_Center_Q33;Face_Center_Q33=(world*vec4(Result_Q18,1.0)).xyz;vec2 Face_Size_Q50=vec2(length(Tangent_World_Q30),length(Binormal_World_Q31));float Show_Selection_Q48;Selection_Vertex_B48(Blob_Position_Q41,Blob_Position_Q42,Face_Center_Q33,Face_Size_Q50,Normal_World_N_Q29,Tangent_World_N_Q28,Binormal_World_N_Q32,_Selection_Fuzz_,_Selected_,_Selected_Distance_,_Selected_Fade_Length_,Active_Face_Dir_Q64,Show_Selection_Q48);vec3 Normalized_Q72=normalize(Dir_World_Q67);float Active_Q34=max(0.0,dot(Active_Face_Dir_Q64,Normal_World_N_Q29));float Width_Q54;Proximity_Visibility_B54(Show_Selection_Q48,Blob_Position_Q41,Blob_Position_Q42,Product_Q56,_Proximity_Far_Distance_,_Proximity_Near_Radius_,Active_Face_Center_Q49,Active_Face_Dir_Q64,Width_Q54);vec3 Wire_Vx_Pos_Q51;vec2 UV_Q51;vec2 Widths_Q51;Wireframe_Vertex_B51(position,normal,tangent,(cross(normal,tangent)),Width_Q54,Face_Size_Q50,Wire_Vx_Pos_Q51,UV_Q51,Widths_Q51);vec3 Vec3_Q27=vec3(Widths_Q51.x,Widths_Q51.y,color.r);vec3 Pos_World_Q13;Object_To_World_Pos_B13(Wire_Vx_Pos_Q51,Pos_World_Q13);vec3 Incident_Q36=normalize(Pos_World_Q13-cameraPosition);vec3 Out_Position_Q47;vec2 Out_UV_Q47;vec3 Blob_Info_Q47;Blob_Vertex_B47(Pos_World_Q13,Normal_World_N_Q29,Tangent_World_N_Q28,Binormal_World_N_Q32,Position_Q38,_Blob_Intensity_,Near_Size_Q38,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,color,uv,Face_Center_Q33,Face_Size_Q50,UV_Q51,_Blob_Fade_Length_,_Selection_Fade_,_Selection_Fade_Size_,Inner_Fade_Q38,Active_Face_Center_Q49,Pulse_Q38,Fade_Q38,Blob_Enable_Q38,Out_Position_Q47,Out_UV_Q47,Blob_Info_Q47);vec4 Extra1_Q66;float Distance_To_Face_Q66;float Intensity_Q66;Proximity_Vertex_B66(Blob_Position_Q41,Blob_Position_Q42,Active_Face_Center_Q49,Active_Face_Dir_Q64,Pos_World_Q13,_Proximity_Far_Distance_,Relative_Scale_Q57,_Proximity_Anisotropy_,Normalized_Q72,Extra1_Q66,Distance_To_Face_Q66,Intensity_Q66);vec4 Holo_Edges_Q44;Holo_Edge_Vertex_B44(Incident_Q36,Normal_World_N_Q29,uv,Tangent_World_Q30,Binormal_World_Q31,_Smooth_Active_Face_,Active_Q34,Holo_Edges_Q44);vec3 Vec3_Q19=vec3(Show_Selection_Q48,Distance_To_Face_Q66,Intensity_Q66);vec3 Position=Out_Position_Q47;vec2 UV=Out_UV_Q47;vec3 Tangent=Blob_Info_Q47;vec3 Binormal=Vec3_Q19;vec3 Normal=Vec3_Q27;vec4 Extra1=Extra1_Q66;vec4 Color=Holo_Edges_Q44;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;}";class VN extends xl{constructor(){super(),this.RELATIVE_WIDTH=!0,this.ENABLE_FADE=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class UN extends ml{constructor(e,t){super(e,t),this.edgeWidth=.04,this.edgeColor=new Ae(.592157,.592157,.592157,1),this.proximityMaxIntensity=.45,this.proximityFarDistance=.16,this.proximityNearRadius=1.5,this.proximityAnisotropy=1,this.selectionFuzz=.5,this.selected=0,this.selectionFade=0,this.selectionFadeSize=.3,this.selectedDistance=.08,this.selectedFadeLength=.08,this.blobIntensity=.5,this.blobFarSize=.05,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.08,this.leftBlobEnable=!0,this.leftBlobNearSize=.025,this.leftBlobPulse=0,this.leftBlobFade=1,this.leftBlobInnerFade=.01,this.rightBlobEnable=!0,this.rightBlobNearSize=.025,this.rightBlobPulse=0,this.rightBlobFade=1,this.rightBlobInnerFade=.01,this.activeFaceDir=new _e(0,0,-1),this.activeFaceUp=new _e(0,1,0),this.enableFade=!0,this.fadeWidth=1.5,this.smoothActiveFace=!0,this.showFrame=!1,this.useBlobTexture=!0,this.globalLeftIndexTipPosition=_e.Zero(),this.globalRightIndexTipPosition=_e.Zero(),this.alphaMode=N_.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1,this._blobTexture=new Pa(UN.BLOB_TEXTURE_URL,this.getScene(),!0,!1,Pa.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!0}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new VN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!0,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="fluentButton",a=s.toString(),l=["world","viewProjection","cameraPosition","_Edge_Width_","_Edge_Color_","_Relative_Width_","_Proximity_Max_Intensity_","_Proximity_Far_Distance_","_Proximity_Near_Radius_","_Proximity_Anisotropy_","_Selection_Fuzz_","_Selected_","_Selection_Fade_","_Selection_Fade_Size_","_Selected_Distance_","_Selected_Fade_Length_","_Blob_Enable_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Inner_Fade_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Enable_2_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Inner_Fade_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Active_Face_Dir_","_Active_Face_Up_","_Enable_Fade_","_Fade_Width_","_Smooth_Active_Face_","_Show_Frame_","_Use_Blob_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Blob_Texture_"],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Edge_Width_",this.edgeWidth),this._activeEffect.setColor4("_Edge_Color_",new Ee(this.edgeColor.r,this.edgeColor.g,this.edgeColor.b),this.edgeColor.a),this._activeEffect.setFloat("_Proximity_Max_Intensity_",this.proximityMaxIntensity),this._activeEffect.setFloat("_Proximity_Far_Distance_",this.proximityFarDistance),this._activeEffect.setFloat("_Proximity_Near_Radius_",this.proximityNearRadius),this._activeEffect.setFloat("_Proximity_Anisotropy_",this.proximityAnisotropy),this._activeEffect.setFloat("_Selection_Fuzz_",this.selectionFuzz),this._activeEffect.setFloat("_Selected_",this.selected),this._activeEffect.setFloat("_Selection_Fade_",this.selectionFade),this._activeEffect.setFloat("_Selection_Fade_Size_",this.selectionFadeSize),this._activeEffect.setFloat("_Selected_Distance_",this.selectedDistance),this._activeEffect.setFloat("_Selected_Fade_Length_",this.selectedFadeLength),this._activeEffect.setFloat("_Blob_Enable_",this.leftBlobEnable?1:0),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.leftBlobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Inner_Fade_",this.leftBlobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_",this.leftBlobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.leftBlobFade),this._activeEffect.setFloat("_Blob_Enable_2_",this.rightBlobEnable?1:0),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.rightBlobNearSize),this._activeEffect.setFloat("_Blob_Inner_Fade_2_",this.rightBlobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_2_",this.rightBlobPulse),this._activeEffect.setFloat("_Blob_Fade_2_",this.rightBlobFade),this._activeEffect.setVector3("_Active_Face_Dir_",this.activeFaceDir),this._activeEffect.setVector3("_Active_Face_Up_",this.activeFaceUp),this._activeEffect.setFloat("_Fade_Width_",this.fadeWidth),this._activeEffect.setFloat("_Smooth_Active_Face_",this.smoothActiveFace?1:0),this._activeEffect.setFloat("_Show_Frame_",this.showFrame?1:0),this._activeEffect.setFloat("_Use_Blob_Texture_",this.useBlobTexture?1:0),this._activeEffect.setFloat("Use_Global_Left_Index",1),this._activeEffect.setFloat("Use_Global_Right_Index",1),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",new pe(this.globalLeftIndexTipPosition.x,this.globalLeftIndexTipPosition.y,this.globalLeftIndexTipPosition.z,1)),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",new pe(this.globalRightIndexTipPosition.x,this.globalRightIndexTipPosition.y,this.globalRightIndexTipPosition.z,1)),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new UN(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FluentButtonMaterial",e}getClassName(){return"FluentButtonMaterial"}static Parse(e,t,i){return St.Parse((()=>new UN(e.name,t)),e,t,i)}}UN.BLOB_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-button-blob.png",Ze([rt()],UN.prototype,"edgeWidth",void 0),Ze([dt()],UN.prototype,"edgeColor",void 0),Ze([rt()],UN.prototype,"proximityMaxIntensity",void 0),Ze([rt()],UN.prototype,"proximityFarDistance",void 0),Ze([rt()],UN.prototype,"proximityNearRadius",void 0),Ze([rt()],UN.prototype,"proximityAnisotropy",void 0),Ze([rt()],UN.prototype,"selectionFuzz",void 0),Ze([rt()],UN.prototype,"selected",void 0),Ze([rt()],UN.prototype,"selectionFade",void 0),Ze([rt()],UN.prototype,"selectionFadeSize",void 0),Ze([rt()],UN.prototype,"selectedDistance",void 0),Ze([rt()],UN.prototype,"selectedFadeLength",void 0),Ze([rt()],UN.prototype,"blobIntensity",void 0),Ze([rt()],UN.prototype,"blobFarSize",void 0),Ze([rt()],UN.prototype,"blobNearDistance",void 0),Ze([rt()],UN.prototype,"blobFarDistance",void 0),Ze([rt()],UN.prototype,"blobFadeLength",void 0),Ze([rt()],UN.prototype,"leftBlobEnable",void 0),Ze([rt()],UN.prototype,"leftBlobNearSize",void 0),Ze([rt()],UN.prototype,"leftBlobPulse",void 0),Ze([rt()],UN.prototype,"leftBlobFade",void 0),Ze([rt()],UN.prototype,"leftBlobInnerFade",void 0),Ze([rt()],UN.prototype,"rightBlobEnable",void 0),Ze([rt()],UN.prototype,"rightBlobNearSize",void 0),Ze([rt()],UN.prototype,"rightBlobPulse",void 0),Ze([rt()],UN.prototype,"rightBlobFade",void 0),Ze([rt()],UN.prototype,"rightBlobInnerFade",void 0),Ze([ht()],UN.prototype,"activeFaceDir",void 0),Ze([ht()],UN.prototype,"activeFaceUp",void 0),Ze([rt()],UN.prototype,"enableFade",void 0),Ze([rt()],UN.prototype,"fadeWidth",void 0),Ze([rt()],UN.prototype,"smoothActiveFace",void 0),Ze([rt()],UN.prototype,"showFrame",void 0),Ze([rt()],UN.prototype,"useBlobTexture",void 0),Ze([ht()],UN.prototype,"globalLeftIndexTipPosition",void 0),Ze([ht()],UN.prototype,"globalRightIndexTipPosition",void 0),z("BABYLON.GUI.FluentButtonMaterial",UN);class GN extends PN{constructor(e,t){super(e),this._isNearPressed=!1,this._interactionSurfaceHeight=0,this._isToggleButton=!1,this._toggleState=!1,this._toggleButtonCallback=()=>{this._onToggle(!this._toggleState)},this.onToggleObservable=new K,this.collidableFrontDirection=_e.Zero(),t&&(this.collisionMesh=t)}get isActiveNearInteraction(){return this._isNearPressed}set collidableFrontDirection(e){if(this._collidableFrontDirection=e.normalize(),this._collisionMesh){const e=ve.Matrix[0];e.copyFrom(this._collisionMesh.getWorldMatrix()),e.invert(),_e.TransformNormalToRef(this._collidableFrontDirection,e,this._collidableFrontDirection),this._collidableFrontDirection.normalize()}}get collidableFrontDirection(){if(this._collisionMesh){const e=ve.Vector3[0];return _e.TransformNormalToRef(this._collidableFrontDirection,this._collisionMesh.getWorldMatrix(),e),e.normalize()}return this._collidableFrontDirection}set collisionMesh(e){this._collisionMesh&&(this._collisionMesh.isNearPickable=!1,this._collisionMesh.reservedDataStore?.GUI3D&&(this._collisionMesh.reservedDataStore.GUI3D={}),this._collisionMesh.getChildMeshes().forEach((e=>{e.isNearPickable=!1,e.reservedDataStore?.GUI3D&&(e.reservedDataStore.GUI3D={})}))),this._collisionMesh=e,this._injectGUI3DReservedDataStore(this._collisionMesh).control=this,this._collisionMesh.isNearPickable=!0,this._collisionMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this,e.isNearPickable=!0})),this.collidableFrontDirection=e.forward}set isToggleButton(e){e!==this._isToggleButton&&(this._isToggleButton=e,e?this.onPointerUpObservable.add(this._toggleButtonCallback):(this.onPointerUpObservable.removeCallback(this._toggleButtonCallback),this._toggleState&&this._onToggle(!1)))}get isToggleButton(){return this._isToggleButton}set isToggled(e){this._isToggleButton&&this._toggleState!==e&&this._onToggle(e)}get isToggled(){return this._toggleState}_onToggle(e){this._toggleState=e,this.onToggleObservable.notifyObservers(e)}_isInteractionInFrontOfButton(e){return this._getInteractionHeight(e,this._collisionMesh.getAbsolutePosition())>0}getPressDepth(e){if(!this._isNearPressed)return 0;const t=this._getInteractionHeight(e,this._collisionMesh.getAbsolutePosition());return this._interactionSurfaceHeight-t}_getInteractionHeight(e,t){const i=this.collidableFrontDirection;if(0===i.length())return _e.Distance(e,t);const s=_e.Dot(t,i);return _e.Dot(e,i)-s}_generatePointerEventType(e,t,i){if(e===lr.POINTERDOWN||e===lr.POINTERMOVE){if(!this._isInteractionInFrontOfButton(t))return lr.POINTERMOVE;this._isNearPressed=!0,this._interactionSurfaceHeight=this._getInteractionHeight(t,this._collisionMesh.getAbsolutePosition())}if(e===lr.POINTERUP){if(0==i)return lr.POINTERMOVE;this._isNearPressed=!1}return e}_getTypeName(){return"TouchButton3D"}_createNode(e){return super._createNode(e)}dispose(){super.dispose(),this.onPointerUpObservable.removeCallback(this._toggleButtonCallback),this.onToggleObservable.clear(),this._collisionMesh&&this._collisionMesh.dispose()}}class zN extends GN{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}get mesh(){return this._backPlate}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=Wa("",{size:1},this._backPlate._scene);const t=Wa("",{size:1,sideOrientation:ha.DOUBLESIDE},this._backPlate._scene),i=new cu("",this._backPlate._scene);i.diffuseColor=Ee.FromHexString("#212121"),t.material=i,t.isPickable=!1,this._tooltipMesh.addChild(t),t.position=_e.Forward(e).scale(.05),this._tooltipMesh.scaling.y=1/3,this._tooltipMesh.position=_e.Up().scale(.7).add(_e.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._backPlate,this._tooltipTexture=xN.CreateForMesh(this._tooltipMesh),this._tooltipTextBlock=new Fw,this._tooltipTextBlock.scaleY=3,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=130,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new Va,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?this._tooltipTextBlock.text:null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}set isBackplateVisible(e){this.mesh&&this._backMaterial&&(e&&!this._isBackplateVisible?this._backPlate.visibility=1:!e&&this._isBackplateVisible&&(this._backPlate.visibility=0)),this._isBackplateVisible=e}constructor(e,t=!0){super(e),this._shareMaterials=!0,this._isBackplateVisible=!0,this._frontPlateDepth=.5,this._backPlateDepth=.04,this._backplateColor=new Ee(.08,.15,.55),this._backplateToggledColor=new Ee(.25,.4,.95),this._shareMaterials=t,this.pointerEnterAnimation=()=>{this._frontMaterial.leftBlobEnable=!0,this._frontMaterial.rightBlobEnable=!0},this.pointerOutAnimation=()=>{this._frontMaterial.leftBlobEnable=!1,this._frontMaterial.rightBlobEnable=!1},this.pointerDownAnimation=()=>{this._frontPlate&&!this.isActiveNearInteraction&&(this._frontPlate.scaling.z=.2*this._frontPlateDepth,this._frontPlate.position=_e.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-.2*this._frontPlateDepth)/2),this._textPlate.position=_e.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+.2*this._frontPlateDepth)/2))},this.pointerUpAnimation=()=>{this._frontPlate&&(this._frontPlate.scaling.z=this._frontPlateDepth,this._frontPlate.position=_e.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-this._frontPlateDepth)/2),this._textPlate.position=_e.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+this._frontPlateDepth)/2))},this.onPointerMoveObservable.add((e=>{if(this._frontPlate&&this.isActiveNearInteraction){const t=_e.Zero();if(this._backPlate.getWorldMatrix().decompose(t,void 0,void 0)){let i=this._getInteractionHeight(e,this._backPlate.getAbsolutePosition())/t.z;i=be.Clamp(i-this._backPlateDepth/2,.2*this._frontPlateDepth,this._frontPlateDepth),this._frontPlate.scaling.z=i,this._frontPlate.position=_e.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-i)/2),this._textPlate.position=_e.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+i)/2)}}})),this._pointerHoverObserver=this.onPointerMoveObservable.add((e=>{this._frontMaterial.globalLeftIndexTipPosition=e}))}_getTypeName(){return"TouchHolographicButton"}_rebuildContent(){this._disposeFacadeTexture();const e=new kw;if(e.isVertical=!0,Ut()&&document.createElement&&this._imageUrl){const t=new Lw;t.source=this._imageUrl,t.paddingTop="40px",t.height="180px",t.width="100px",t.paddingBottom="40px",e.addControl(t)}if(this._text){const t=new Fw;t.text=this._text,t.color="white",t.height="30px",t.fontSize=24,e.addControl(t)}this.content=e}_createNode(e){this.name=this.name??"TouchHolographicButton";const t=cd(`${this.name}_collisionMesh`,{width:1,height:1,depth:this._frontPlateDepth},e);t.isPickable=!0,t.isNearPickable=!0,t.visibility=0,t.position=_e.Forward(e.useRightHandedSystem).scale(-this._frontPlateDepth/2),fl.ImportMeshAsync(void 0,zN.MODEL_BASE_URL,zN.MODEL_FILENAME,e).then((i=>{const s=cd("${this.name}_alphaMesh",{width:1,height:1,depth:1},e);s.isPickable=!1,s.material=new cu("${this.name}_alphaMesh_material",e),s.material.alpha=.15;const r=i.meshes[1];r.name=`${this.name}_frontPlate`,r.isPickable=!1,r.scaling.z=this._frontPlateDepth,s.parent=r,r.parent=t,this._frontMaterial&&(r.material=this._frontMaterial),this._frontPlate=r})),this._backPlate=cd(`${this.name}_backPlate`,{width:1,height:1,depth:this._backPlateDepth},e),this._backPlate.position=_e.Forward(e.useRightHandedSystem).scale(this._backPlateDepth/2),this._backPlate.isPickable=!1,this._textPlate=super._createNode(e),this._textPlate.name=`${this.name}_textPlate`,this._textPlate.isPickable=!1,this._textPlate.position=_e.Forward(e.useRightHandedSystem).scale(-this._frontPlateDepth/2),this._backPlate.addChild(t),this._backPlate.addChild(this._textPlate);const i=new lo("{this.name}_root",e);return this._backPlate.setParent(i),this.collisionMesh=t,this.collidableFrontDirection=this._backPlate.forward.negate(),i}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e,this._plateMaterial.diffuseColor=new Ee(.4,.4,.4)}_createBackMaterial(e){this._backMaterial=new DN(this.name+"backPlateMaterial",e.getScene()),this._backMaterial.albedoColor=this._backplateColor,this._backMaterial.renderBorders=!0,this._backMaterial.renderHoverLight=!1}_createFrontMaterial(e){this._frontMaterial=new UN(this.name+"Front Material",e.getScene())}_createPlateMaterial(e){this._plateMaterial=new cu(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=Ee.Black()}_onToggle(e){this._backMaterial&&(this._backMaterial.albedoColor=e?this._backplateToggledColor:this._backplateColor),super._onToggle(e)}_affectMaterial(e){this._shareMaterials?(this._host._touchSharedMaterials.backFluentMaterial?this._backMaterial=this._host._touchSharedMaterials.backFluentMaterial:(this._createBackMaterial(e),this._host._touchSharedMaterials.backFluentMaterial=this._backMaterial),this._host._touchSharedMaterials.frontFluentMaterial?this._frontMaterial=this._host._touchSharedMaterials.frontFluentMaterial:(this._createFrontMaterial(e),this._host._touchSharedMaterials.frontFluentMaterial=this._frontMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._textPlate.material=this._plateMaterial,this._isBackplateVisible||(this._backPlate.visibility=0),this._frontPlate&&(this._frontPlate.material=this._frontMaterial),this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.onPointerMoveObservable.remove(this._pointerHoverObserver),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}zN.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",zN.MODEL_FILENAME="mrtk-fluent-button.glb";class WN{constructor(){this.followBehaviorEnabled=!1,this.sixDofDragBehaviorEnabled=!0,this.surfaceMagnetismBehaviorEnabled=!0,this._followBehavior=new $a,this._sixDofDragBehavior=new ja,this._surfaceMagnetismBehavior=new Ka}get name(){return"Default"}get followBehavior(){return this._followBehavior}get sixDofDragBehavior(){return this._sixDofDragBehavior}get surfaceMagnetismBehavior(){return this._surfaceMagnetismBehavior}init(){}attach(e,t,i){this._scene=e.getScene(),this.attachedNode=e,this._addObservables(),this._followBehavior.attach(e),this._sixDofDragBehavior.attach(e),this._sixDofDragBehavior.draggableMeshes=t||null,this._sixDofDragBehavior.faceCameraOnDragStart=!0,this._surfaceMagnetismBehavior.attach(e,this._scene),i&&(this._surfaceMagnetismBehavior.meshes=i),this._surfaceMagnetismBehavior.enabled=!1}detach(){this.attachedNode=null,this._removeObservables(),this._followBehavior.detach(),this._sixDofDragBehavior.detach(),this._surfaceMagnetismBehavior.detach()}_addObservables(){this._onBeforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{this._followBehavior._enabled=!this._sixDofDragBehavior.isMoving&&this.followBehaviorEnabled})),this._onDragObserver=this._sixDofDragBehavior.onDragObservable.add((e=>{this._sixDofDragBehavior.disableMovement=this._surfaceMagnetismBehavior.findAndUpdateTarget(e.pickInfo)}))}_removeObservables(){this._scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._sixDofDragBehavior.onDragObservable.remove(this._onDragObserver)}}Bi.ShadersStore.handleVertexShader="precision highp float;attribute vec3 position;uniform vec3 positionOffset;uniform mat4 worldViewProjection;uniform float scale;void main(void) {vec4 vPos=vec4((vec3(position)+positionOffset)*scale,1.0);gl_Position=worldViewProjection*vPos;}";Bi.ShadersStore.handlePixelShader="uniform vec3 color;void main(void) {gl_FragColor=vec4(color,1.0);}";class HN extends Nd{get hover(){return this._hover}set hover(e){this._hover=e,this._updateInterpolationTarget()}get drag(){return this._drag}set drag(e){this._drag=e,this._updateInterpolationTarget()}constructor(e,t){super(e,t,"handle",{attributes:["position"],uniforms:["worldViewProjection","color","scale","positionOffset"],needAlphaBlending:!1,needAlphaTesting:!1}),this._hover=!1,this._drag=!1,this._color=new Ee,this._scale=1,this._lastTick=-1,this.animationLength=100,this.hoverColor=new Ee(0,.467,.84),this.baseColor=new Ee(1,1,1),this.hoverScale=.75,this.baseScale=.35,this.dragScale=.55,this._positionOffset=_e.Zero(),this._updateInterpolationTarget(),this._lastTick=Date.now(),this._onBeforeRender=this.getScene().onBeforeRenderObservable.add((()=>{const e=Date.now(),t=e-this._lastTick,i=this._targetScale-this._scale,s=Pe.Color3[0].copyFrom(this._targetColor).subtractToRef(this._color,Pe.Color3[0]);this._scale=this._scale+i*t/this.animationLength,s.scaleToRef(t/this.animationLength,s),this._color.addToRef(s,this._color),this.setColor3("color",this._color),this.setFloat("scale",this._scale),this.setVector3("positionOffset",this._positionOffset),this._lastTick=e}))}_updateInterpolationTarget(){this.drag?(this._targetColor=this.hoverColor,this._targetScale=this.dragScale):this.hover?(this._targetColor=this.hoverColor,this._targetScale=this.hoverScale):(this._targetColor=this.baseColor,this._targetScale=this.baseScale)}dispose(){super.dispose(),this.getScene().onBeforeRenderObservable.remove(this._onBeforeRender)}}var XN;!function(e){e[e.IDLE=0]="IDLE",e[e.HOVER=1]="HOVER",e[e.DRAG=2]="DRAG"}(XN||(XN={}));class YN{get state(){return this._state}get gizmo(){return this._gizmo}set hover(e){e?this._state|=XN.HOVER:this._state&=~XN.HOVER,this._updateMaterial()}set drag(e){e?this._state|=XN.DRAG:this._state&=~XN.DRAG,this._updateMaterial()}constructor(e,t){this._state=XN.IDLE,this._materials=[],this._scene=t,this._gizmo=e,this.node=this.createNode(),this.node.reservedDataStore={handle:this}}_createMaterial(e){const t=new HN("handle",this._scene);return e&&(t._positionOffset=e),t}_updateMaterial(){const e=this._state;for(const e of this._materials)e.hover=!1,e.drag=!1;if(e&XN.DRAG)for(const e of this._materials)e.drag=!0;else if(e&XN.HOVER)for(const e of this._materials)e.hover=!0}setDragBehavior(e,t,i){const s=new Qa;this._dragBehavior=s,this._dragStartObserver=s.onDragStartObservable.add(e),this._draggingObserver=s.onDragObservable.add(t),this._dragEndObserver=s.onDragEndObservable.add(i),this._dragBehavior.attach(this.node)}dispose(){this._dragBehavior.onDragStartObservable.remove(this._dragStartObserver),this._dragBehavior.onDragObservable.remove(this._draggingObserver),this._dragBehavior.onDragEndObservable.remove(this._dragEndObserver),this._dragBehavior.detach();for(const e of this._materials)e.dispose();this.node.dispose()}}class QN extends YN{createNode(){const e=cd("sideVert",{width:1,height:10,depth:.1},this._scene),t=new lo("side",this._scene);e.parent=t;const i=this._createMaterial();return e.material=i,e.isNearGrabbable=!0,this._materials.push(i),t}}class jN extends YN{createNode(){const e=cd("angleHor",{width:3,height:1,depth:.1},this._scene),t=cd("angleVert",{width:1,height:3,depth:.1},this._scene),i=new lo("angle",this._scene);return e.parent=i,t.parent=i,e.material=this._createMaterial(new _e(1,0,0)),t.material=this._createMaterial(new _e(0,1,0)),t.isNearGrabbable=!0,e.isNearGrabbable=!0,this._materials.push(e.material),this._materials.push(t.material),i}}class KN extends sd{set attachedSlate(e){e?(this.attachedMesh=e.mesh,this.updateBoundingBox(),this._pickedPointObserver=e._host.onPickingObservable.add((e=>{if(!this._handleHovered||e&&e.parent===this._handleHovered.node||(this._handleHovered.hover=!1,this._handleHovered=null),e&&e.parent&&e.parent.reservedDataStore&&e.parent.reservedDataStore.handle){const t=e.parent.reservedDataStore.handle;t.gizmo===this&&(this._handleHovered=t,this._handleHovered.hover=!0)}}))):this._attachedSlate&&this._attachedSlate._host.onPickingObservable.remove(this._pickedPointObserver),this._attachedSlate=e}get attachedSlate(){return this._attachedSlate}constructor(e){super(e),this._boundingDimensions=new _e(0,0,0),this._renderObserver=null,this._tmpQuaternion=new fe,this._tmpVector=new _e(0,0,0),this._corners=[],this._sides=[],this._boundingBoxGizmo={min:new _e,max:new _e},this._margin=.35,this._handleSize=.075,this._attachedSlate=null,this._existingSlateScale=new _e,this.fixedScreenSize=!1,this.fixedScreenSizeDistanceFactor=10,this._createNode(),this.updateScale=!1,this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add((()=>{this.attachedMesh&&!this._existingSlateScale.equals(this.attachedMesh.scaling)&&this.updateBoundingBox()}))}_createNode(){this._handlesParent=new lo("handlesParent",this.gizmoLayer.utilityLayerScene),this._handlesParent.rotationQuaternion=fe.Identity();const e=[{dimensions:new _e(-1,-1,0),origin:new _e(1,0,0)},{dimensions:new _e(1,-1,0),origin:new _e(0,0,0)},{dimensions:new _e(1,1,0),origin:new _e(0,1,0)},{dimensions:new _e(-1,1,0),origin:new _e(1,1,0)}];for(let t=0;t<4;t++){const i=new jN(this,this.gizmoLayer.utilityLayerScene);this._corners.push(i),i.node.rotation.z=Math.PI/2*t,i.node.parent=this._handlesParent,this._assignDragBehaviorCorners(i,((e,t,i,s)=>this._moveHandle(e,t,i,s,!0)),e[t])}for(let e=0;e<4;e++){const t=new QN(this,this.gizmoLayer.utilityLayerScene);this._sides.push(t),t.node.rotation.z=Math.PI/2*e,t.node.parent=this._handlesParent,this._assignDragBehaviorSides(t,e%2==0?new _e(0,1,0):new _e(1,0,0))}this._handlesParent.parent=this._rootMesh}_keepAspectRatio(e,t,i=!1){const s=ve.Vector3[0];s.copyFromFloats(t,1,0).normalize(),i&&(s.y*=-1);const r=_e.Dot(e,s);e.copyFrom(s).scaleInPlace(r)}_clampDimensions(e,t,i,s=!1){const r=ve.Vector3[0];r.copyFrom(e).multiplyInPlace(i);const n=ve.Vector3[1];if(n.copyFromFloats(Math.max(this._attachedSlate.minDimensions.x,r.x+t.x),Math.max(this._attachedSlate.minDimensions.y,r.y+t.y),0),s){const e=t.x/t.y;n.x=Math.max(n.x,n.y*e),n.y=Math.max(n.y,n.x/e)}r.copyFrom(n).subtractInPlace(t),e.x=Math.sign(e.x)*Math.abs(r.x),e.y=Math.sign(e.y)*Math.abs(r.y)}_moveHandle(e,t,i,s,r){if(!this._attachedSlate)return;if(r){const e=t.x/t.y;this._keepAspectRatio(i,e,s.dimensions.x*s.dimensions.y<0)}this._clampDimensions(i,t,s.dimensions,r);const n=ve.Vector3[0],o=ve.Vector3[1];n.copyFrom(i).multiplyInPlace(s.origin),o.copyFrom(i).multiplyInPlace(s.dimensions),this._attachedSlate.origin.copyFrom(e).addInPlace(n),this._attachedSlate.dimensions.set(t.x+o.x,t.y+o.y)}_assignDragBehaviorCorners(e,t,i){const s=new _e,r=new _e,n=new _e,o=new me,a=new _e;e.setDragBehavior((e=>{this.attachedSlate&&this.attachedMesh&&(s.set(this.attachedSlate.dimensions.x,this.attachedSlate.dimensions.y,J),r.copyFrom(this.attachedSlate.origin),n.copyFrom(e.position),o.copyFrom(this.attachedMesh.computeWorldMatrix(!0)),o.invert(),this.attachedSlate._followButton.isToggled=!1,_e.TransformNormalToRef(_e.Forward(),this.attachedMesh.getWorldMatrix(),a),a.normalize(),this._handleHovered&&(this._handleDragged=this._handleHovered,this._handleDragged.drag=!0))}),(e=>{this.attachedSlate&&this.attachedMesh&&(((e,t,i,s)=>{e.subtractToRef(i,ve.Vector3[0]);const r=_e.Dot(ve.Vector3[0],t);ve.Vector3[1].copyFrom(t).scaleInPlace(r),ve.Vector3[0].subtractInPlace(ve.Vector3[1]),ve.Vector3[0].addToRef(i,s)})(e.position,a,n,this._tmpVector),this._tmpVector.subtractInPlace(n),_e.TransformNormalToRef(this._tmpVector,o,this._tmpVector),t(r,s,this._tmpVector,i),this.attachedSlate._positionElements(),this.updateBoundingBox())}),(()=>{this.attachedSlate&&this.attachedNode&&(this.attachedSlate._updatePivot(),this._handleDragged&&(this._handleDragged.drag=!1,this._handleDragged=null))}))}_assignDragBehaviorSides(e,t){const i=new fe,s=new _e,r=new _e,n=new _e,o=new _e;e.setDragBehavior((e=>{this.attachedSlate&&this.attachedMesh&&(i.copyFrom(this.attachedMesh.rotationQuaternion),s.copyFrom(e.position),n.copyFrom(this.attachedMesh.getAbsolutePivotPoint()),r.copyFrom(s).subtractInPlace(n).normalize(),this.attachedSlate._followButton.isToggled=!1,_e.TransformNormalToRef(t,this.attachedMesh.getWorldMatrix(),o),o.normalize(),this._handleHovered&&(this._handleDragged=this._handleHovered,this._handleDragged.drag=!0))}),(e=>{if(this.attachedSlate&&this.attachedMesh){this._tmpVector.copyFrom(e.position),this._tmpVector.subtractInPlace(n),this._tmpVector.normalize();const s=-_e.GetAngleBetweenVectorsOnPlane(this._tmpVector,r,o);fe.RotationAxisToRef(t,s,this._tmpQuaternion),i.multiplyToRef(this._tmpQuaternion,this.attachedMesh.rotationQuaternion)}}),(()=>{this.attachedSlate&&this.attachedNode&&(this.attachedSlate._updatePivot(),this._handleDragged&&(this._handleDragged.drag=!1,this._handleDragged=null))}))}_attachedNodeChanged(e){e&&this.updateBoundingBox()}updateBoundingBox(){if(this.attachedMesh){Ga._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=fe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);const t=this.attachedMesh.getHierarchyBoundingVectors();t.max.subtractToRef(t.min,this._boundingDimensions),this._boundingBoxGizmo.min=t.min,this._boundingBoxGizmo.max=t.max,this._updateHandlesPosition(),this._updateHandlesScaling(),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),Ga._RestorePivotPoint(this.attachedMesh),this.attachedMesh.setParent(e),this.attachedMesh.computeWorldMatrix(!0),this._existingSlateScale.copyFrom(this.attachedMesh.scaling)}}_updateHandlesPosition(){const e=this._boundingBoxGizmo.min.clone(),t=this._boundingBoxGizmo.max.clone(),i=this._corners[0].node.scaling.length();e.x-=this._margin*i,e.y-=this._margin*i,t.x+=this._margin*i,t.y+=this._margin*i;const s=e.add(t).scaleInPlace(.5);this._corners[0].node.position.copyFromFloats(e.x,e.y,0),this._corners[1].node.position.copyFromFloats(t.x,e.y,0),this._corners[2].node.position.copyFromFloats(t.x,t.y,0),this._corners[3].node.position.copyFromFloats(e.x,t.y,0),this._sides[0].node.position.copyFromFloats(e.x,s.y,0),this._sides[1].node.position.copyFromFloats(s.x,e.y,0),this._sides[2].node.position.copyFromFloats(t.x,s.y,0),this._sides[3].node.position.copyFromFloats(s.x,t.y,0)}_updateHandlesScaling(){if(this._attachedSlate&&this._attachedSlate.mesh){const e=this._attachedSlate.mesh.scaling.x*this._attachedSlate.dimensions.x,t=this._attachedSlate.mesh.scaling.y*this._attachedSlate.dimensions.y,i=Math.min(e,t)*this._handleSize;for(let e=0;ei?this.minDimensions.x/e.x:this.minDimensions.y/e.y}this._dimensions.copyFrom(e).scaleInPlace(t),this._updatePivot(),this._positionElements()}get titleBarHeight(){return this._titleBarHeight}set titleBarHeight(e){this._titleBarHeight=e}set renderingGroupId(e){this._titleBar.renderingGroupId=e,this._titleBarTitle.renderingGroupId=e,this._contentPlate.renderingGroupId=e,this._backPlate.renderingGroupId=e}get renderingGroupId(){return this._titleBar.renderingGroupId}set title(e){this._titleText=e,this._titleTextComponent&&(this._titleTextComponent.text=e)}get title(){return this._titleText}constructor(e){super(e),this.titleBarMargin=.005,this.origin=new _e(0,0,0),this._dimensions=new de(21.875,12.5),this._titleBarHeight=.625,this._titleText="",this._contentScaleRatio=1,this.minDimensions=new de(15.625,6.25),this.defaultDimensions=this._dimensions.clone(),this._followButton=new zN("followButton"+this.name),this._followButton.isToggleButton=!0,this._closeButton=new zN("closeButton"+this.name),this._contentViewport=new Pn(0,0,1,1),this._contentDragBehavior=new Xa({dragPlaneNormal:new _e(0,0,-1)})}_applyFacade(e){this._contentMaterial.albedoTexture=e,this._resetContentPositionAndZoom(),this._applyContentViewport(),e.attachToMesh(this._contentPlate,!0)}_addControl(e){e._host=this._host,this._host.utilityLayer&&e._prepareNode(this._host.utilityLayer.utilityLayerScene)}_getTypeName(){return"HolographicSlate"}_positionElements(){const e=this._followButton,t=this._closeButton,i=this._titleBar,s=this._titleBarTitle,r=this._contentPlate,n=this._backPlate;if(e&&t&&i){t.scaling.setAll(this.titleBarHeight),e.scaling.setAll(this.titleBarHeight),t.position.copyFromFloats(this.dimensions.x-this.titleBarHeight/2,-this.titleBarHeight/2,0).addInPlace(this.origin),e.position.copyFromFloats(this.dimensions.x-3*this.titleBarHeight/2,-this.titleBarHeight/2,0).addInPlace(this.origin);const o=this.dimensions.y-this.titleBarHeight-this.titleBarMargin,a=r.getScene().useRightHandedSystem;i.scaling.set(this.dimensions.x,this.titleBarHeight,J),s.scaling.set(this.dimensions.x-2*this.titleBarHeight,this.titleBarHeight,J),r.scaling.copyFromFloats(this.dimensions.x,o,J),n.scaling.copyFromFloats(this.dimensions.x,o,J),i.position.copyFromFloats(this.dimensions.x/2,-this.titleBarHeight/2,0).addInPlace(this.origin),s.position.copyFromFloats(this.dimensions.x/2-this.titleBarHeight,-this.titleBarHeight/2,a?J:-J).addInPlace(this.origin),r.position.copyFromFloats(this.dimensions.x/2,-(this.titleBarHeight+this.titleBarMargin+o/2),0).addInPlace(this.origin),n.position.copyFromFloats(this.dimensions.x/2,-(this.titleBarHeight+this.titleBarMargin+o/2),a?-J:J).addInPlace(this.origin),this._titleTextComponent.host.scaleTo($N._DEFAULT_TEXT_RESOLUTION_Y*s.scaling.x/s.scaling.y,$N._DEFAULT_TEXT_RESOLUTION_Y);const l=this.dimensions.x/o;this._contentViewport.width=this._contentScaleRatio,this._contentViewport.height=this._contentScaleRatio/l,this._applyContentViewport(),this._gizmo&&this._gizmo.updateBoundingBox()}}_applyContentViewport(){if(this._contentPlate?.material&&this._contentPlate.material.albedoTexture){const e=this._contentPlate.material.albedoTexture;e.uScale=this._contentScaleRatio,e.vScale=this._contentScaleRatio/this._contentViewport.width*this._contentViewport.height,e.uOffset=this._contentViewport.x,e.vOffset=this._contentViewport.y}}_resetContentPositionAndZoom(){this._contentViewport.x=0,this._contentViewport.y=1-this._contentViewport.height/this._contentViewport.width,this._contentScaleRatio=1}_updatePivot(){if(!this.mesh)return;const e=new _e(.5*this.dimensions.x,.5*-this.dimensions.y,J);e.addInPlace(this.origin),e.z=0;const t=new _e(0,0,0);_e.TransformCoordinatesToRef(t,this.mesh.computeWorldMatrix(!0),t),this.mesh.setPivotPoint(e);const i=new _e(0,0,0);_e.TransformCoordinatesToRef(i,this.mesh.computeWorldMatrix(!0),i),this.mesh.position.addInPlace(t).subtractInPlace(i)}_createNode(e){const t=new ha("slate_"+this.name,e);this._titleBar=cd("titleBar_"+this.name,{size:1},e),this._titleBarTitle=Wa("titleText_"+this.name,{size:1},e),this._titleBarTitle.parent=t,this._titleBarTitle.isPickable=!1;const i=xN.CreateForMesh(this._titleBarTitle);if(this._titleTextComponent=new Fw("titleText_"+this.name,this._titleText),this._titleTextComponent.textWrapping=Nw.Ellipsis,this._titleTextComponent.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._titleTextComponent.color="white",this._titleTextComponent.fontSize=$N._DEFAULT_TEXT_RESOLUTION_Y/2,this._titleTextComponent.paddingLeft=$N._DEFAULT_TEXT_RESOLUTION_Y/4,i.addControl(this._titleTextComponent),e.useRightHandedSystem){const t=new pe(0,0,1,1);this._contentPlate=Wa("contentPlate_"+this.name,{size:1,sideOrientation:Wn.BACKSIDE,frontUVs:t},e),this._backPlate=Wa("backPlate_"+this.name,{size:1,sideOrientation:Wn.FRONTSIDE},e)}else{const t=new pe(0,0,1,1);this._contentPlate=Wa("contentPlate_"+this.name,{size:1,sideOrientation:Wn.FRONTSIDE,frontUVs:t},e),this._backPlate=Wa("backPlate_"+this.name,{size:1,sideOrientation:Wn.BACKSIDE},e)}this._titleBar.parent=t,this._titleBar.isNearGrabbable=!0,this._contentPlate.parent=t,this._backPlate.parent=t,this._attachContentPlateBehavior(),this._addControl(this._followButton),this._addControl(this._closeButton);const s=this._followButton,r=this._closeButton;return s.node.parent=t,r.node.parent=t,this._positionElements(),this._followButton.imageUrl=$N.ASSETS_BASE_URL+$N.FOLLOW_ICON_FILENAME,this._closeButton.imageUrl=$N.ASSETS_BASE_URL+$N.CLOSE_ICON_FILENAME,this._followButton.isBackplateVisible=!1,this._closeButton.isBackplateVisible=!1,this._followButton.onToggleObservable.add((e=>{this._defaultBehavior.followBehaviorEnabled=e,this._defaultBehavior.followBehaviorEnabled&&this._defaultBehavior.followBehavior.recenter()})),this._closeButton.onPointerClickObservable.add((()=>{this.dispose()})),t.rotationQuaternion=fe.Identity(),t.isVisible=!1,t}_attachContentPlateBehavior(){this._contentDragBehavior.attach(this._contentPlate),this._contentDragBehavior.moveAttached=!1,this._contentDragBehavior.useObjectOrientationForDragging=!0,this._contentDragBehavior.updateDragPlane=!1;const e=new _e,t=new _e,i=new _e,s=new _e,r=new de;let n,o;this._contentDragBehavior.onDragStartObservable.add((r=>{this.node&&(n=this._contentViewport.clone(),o=this.node.computeWorldMatrix(!0),e.copyFrom(r.dragPlanePoint),t.set(this.dimensions.x,this.dimensions.y,J),t.y-=this.titleBarHeight+this.titleBarMargin,_e.TransformNormalToRef(t,o,t),i.copyFromFloats(0,1,0),_e.TransformNormalToRef(i,o,i),s.copyFromFloats(1,0,0),_e.TransformNormalToRef(s,o,s),i.normalize(),i.scaleInPlace(1/_e.Dot(i,t)),s.normalize(),s.scaleInPlace(1/_e.Dot(s,t)))}));const a=new _e;this._contentDragBehavior.onDragObservable.add((t=>{a.copyFrom(t.dragPlanePoint),a.subtractInPlace(e),r.copyFromFloats(_e.Dot(a,s),_e.Dot(a,i)),this._contentViewport.x=be.Clamp(n.x-a.x,0,1-this._contentViewport.width*this._contentScaleRatio),this._contentViewport.y=be.Clamp(n.y-a.y,0,1-this._contentViewport.height*this._contentScaleRatio),this._applyContentViewport()}))}_affectMaterial(e){this._titleBarMaterial=new LN(`${this.name} plateMaterial`,e.getScene()),this._contentMaterial=new DN(`${this.name} contentMaterial`,e.getScene()),this._contentMaterial.renderBorders=!0,this._backMaterial=new LN(`${this.name} backPlate`,e.getScene()),this._backMaterial.lineWidth=J,this._backMaterial.radius=.005,this._backMaterial.backFaceCulling=!0,this._titleBar.material=this._titleBarMaterial,this._contentPlate.material=this._contentMaterial,this._backPlate.material=this._backMaterial,this._resetContent(),this._applyContentViewport()}_prepareNode(e){super._prepareNode(e),this._gizmo=new KN(this._host.utilityLayer),this._gizmo.attachedSlate=this,this._defaultBehavior=new WN,this._defaultBehavior.attach(this.node,[this._titleBar]),this._defaultBehavior.sixDofDragBehavior.onDragStartObservable.add((()=>{this._followButton.isToggled=!1})),this._positionChangedObserver=this._defaultBehavior.sixDofDragBehavior.onPositionChangedObservable.add((()=>{this._gizmo.updateBoundingBox()})),this._updatePivot(),this.resetDefaultAspectAndPose(!1)}resetDefaultAspectAndPose(e=!0){if(!this._host||!this._host.utilityLayer||!this.node)return;const t=this._host.utilityLayer.utilityLayerScene,i=t.activeCamera;if(i){const s=i.getWorldMatrix(),r=_e.TransformNormal(_e.Backward(t.useRightHandedSystem),s);this.origin.setAll(0),this._gizmo.updateBoundingBox();const n=this.node.getAbsolutePivotPoint();this.node.position.copyFrom(i.position).subtractInPlace(r).subtractInPlace(n),this.node.rotationQuaternion=fe.FromLookDirectionLH(r,new _e(0,1,0)),e&&(this.dimensions=this.defaultDimensions)}}dispose(){super.dispose(),this._titleBarMaterial.dispose(),this._contentMaterial.dispose(),this._titleBar.dispose(),this._titleBarTitle.dispose(),this._contentPlate.dispose(),this._backPlate.dispose(),this._followButton.dispose(),this._closeButton.dispose(),this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._defaultBehavior.sixDofDragBehavior.onPositionChangedObservable.remove(this._positionChangedObserver),this._defaultBehavior.detach(),this._gizmo.dispose(),this._contentDragBehavior.detach()}}$N.ASSETS_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",$N.CLOSE_ICON_FILENAME="IconClose.png",$N.FOLLOW_ICON_FILENAME="IconFollowMe.png",$N._DEFAULT_TEXT_RESOLUTION_Y=102.4;class qN extends PN{constructor(e,t){super(t),this._currentMesh=e,this.pointerEnterAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1.1)},this.pointerOutAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/1.1)},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_getTypeName(){return"MeshButton3D"}_createNode(e){return this._currentMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this})),this._currentMesh}_affectMaterial(e){}}class ZN extends wN{get defaultBehavior(){return this._defaultBehavior}get isPinned(){return this._isPinned}set isPinned(e){this._pinButton.isToggled===e?(this._isPinned=e,this._defaultBehavior.followBehaviorEnabled=!e):this._pinButton.isToggled=e}_createPinButton(e){const t=new zN("pin"+this.name,!1);return t.imageUrl=ZN._ASSETS_BASE_URL+ZN._PIN_ICON_FILENAME,t.parent=this,t._host=this._host,t.isToggleButton=!0,t.onToggleObservable.add((e=>{this.isPinned=e})),this._host.utilityLayer&&(t._prepareNode(this._host.utilityLayer.utilityLayerScene),t.scaling.scaleInPlace(wN.MENU_BUTTON_SCALE),t.node&&(t.node.parent=e)),t}_createNode(e){const t=super._createNode(e);return this._pinButton=this._createPinButton(t),this.isPinned=!1,this._defaultBehavior.attach(t,[this._backPlate]),this._defaultBehavior.followBehavior.ignoreCameraPitchAndRoll=!0,this._defaultBehavior.followBehavior.pitchOffset=-15,this._defaultBehavior.followBehavior.minimumDistance=.3,this._defaultBehavior.followBehavior.defaultDistance=.4,this._defaultBehavior.followBehavior.maximumDistance=.6,this._backPlate.isNearGrabbable=!0,t.isVisible=!1,t}_finalProcessing(){super._finalProcessing(),this._pinButton.position.copyFromFloats((this._backPlate.scaling.x+wN.MENU_BUTTON_SCALE)/2,this._backPlate.scaling.y/2,0)}constructor(e){super(e),this._isPinned=!1,this._defaultBehavior=new WN,this._dragObserver=this._defaultBehavior.sixDofDragBehavior.onDragObservable.add((()=>{this.isPinned=!0})),this.backPlateMargin=1}dispose(){super.dispose(),this._defaultBehavior.sixDofDragBehavior.onDragObservable.remove(this._dragObserver),this._defaultBehavior.detach()}}ZN._ASSETS_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",ZN._PIN_ICON_FILENAME="IconPin.png";class JN extends RN{_mapGridNode(e,t){const i=e.mesh;if(!i)return;e.position=t.clone();const s=ve.Vector3[0];switch(s.copyFrom(t),this.orientation){case IN.FACEORIGIN_ORIENTATION:case IN.FACEFORWARD_ORIENTATION:s.addInPlace(new _e(0,0,1)),i.lookAt(s);break;case IN.FACEFORWARDREVERSED_ORIENTATION:case IN.FACEORIGINREVERSED_ORIENTATION:s.addInPlace(new _e(0,0,-1)),i.lookAt(s)}}}class eF extends RN{constructor(){super(...arguments),this._iteration=100}get iteration(){return this._iteration}set iteration(e){this._iteration!==e&&(this._iteration=e,Ds.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh,s=this._scatterMapping(t);if(i){switch(this.orientation){case IN.FACEORIGIN_ORIENTATION:case IN.FACEFORWARD_ORIENTATION:i.lookAt(new _e(0,0,1));break;case IN.FACEFORWARDREVERSED_ORIENTATION:case IN.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new _e(0,0,-1))}e.position=s}}_scatterMapping(e){return e.x=(1-2*Math.random())*this._cellWidth,e.y=(1-2*Math.random())*this._cellHeight,e}_finalProcessing(){const e=[];for(const t of this._children)t.mesh&&e.push(t.mesh);for(let t=0;t{const i=e.position.lengthSquared(),s=t.position.lengthSquared();return is?-1:0}));const t=Math.pow(this.margin,2),i=Math.max(this._cellWidth,this._cellHeight),s=ve.Vector2[0],r=ve.Vector3[0];for(let n=0;n0.0) {C=mix(H,S,k);} else {C=mix(H,G,k); }\nreturn C;}\nvoid Sky_Environment_B50(\nvec3 Normal,\nvec3 Reflected,\nvec4 Sky_Color,\nvec4 Horizon_Color,\nvec4 Ground_Color,\nfloat Horizon_Power,\nout vec4 Reflected_Color,\nout vec4 Indirect_Color)\n{Reflected_Color=SampleEnv_Bid50(Reflected,Sky_Color,Horizon_Color,Ground_Color,Horizon_Power);Indirect_Color=mix(Ground_Color,Sky_Color,Normal.y*0.5+0.5);}\nvoid Min_Segment_Distance_B65(\nvec3 P0,\nvec3 P1,\nvec3 Q0,\nvec3 Q1,\nout vec3 NearP,\nout vec3 NearQ,\nout float Distance)\n{vec3 u=P1-P0;vec3 v=Q1-Q0;vec3 w=P0-Q0;float a=dot(u,u);float b=dot(u,v);float c=dot(v,v);float d=dot(u,w);float e=dot(v,w);float D=a*c-b*b;float sD=D;float tD=D;float sc,sN,tc,tN;if (D<0.00001) {sN=0.0;sD=1.0;tN=e;tD=c;} else {sN=(b*e-c*d);tN=(a*e-b*d);if (sN<0.0) {sN=0.0;tN=e;tD=c;} else if (sN>sD) {sN=sD;tN=e+b;tD=c;}}\nif (tN<0.0) {tN=0.0;if (-d<0.0) {sN=0.0;} else if (-d>a) {sN=sD;} else {sN=-d;sD=a;}} else if (tN>tD) {tN=tD;if ((-d+b)<0.0) {sN=0.0;} else if ((-d+b)>a) {sN=sD;} else {sN=(-d+b);sD=a;}}\nsc=abs(sN)<0.000001 ? 0.0 : sN/sD;tc=abs(tN)<0.000001 ? 0.0 : tN/tD;NearP=P0+sc*u;NearQ=Q0+tc*v;Distance=distance(NearP,NearQ);}\nvoid To_XYZ_B74(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid Finger_Positions_B64(\nvec3 Left_Index_Pos,\nvec3 Right_Index_Pos,\nvec3 Left_Index_Middle_Pos,\nvec3 Right_Index_Middle_Pos,\nout vec3 Left_Index,\nout vec3 Right_Index,\nout vec3 Left_Index_Middle,\nout vec3 Right_Index_Middle)\n{Left_Index= (Use_Global_Left_Index ? Global_Left_Index_Tip_Position.xyz : Left_Index_Pos);Right_Index= (Use_Global_Right_Index ? Global_Right_Index_Tip_Position.xyz : Right_Index_Pos);Left_Index_Middle= (Use_Global_Left_Index ? Global_Left_Index_Middle_Position.xyz : Left_Index_Middle_Pos);Right_Index_Middle= (Use_Global_Right_Index ? Global_Right_Index_Middle_Position.xyz : Right_Index_Middle_Pos);}\nvoid VaryHSV_B108(\nvec3 HSV_In,\nfloat Hue_Shift,\nfloat Saturation_Shift,\nfloat Value_Shift,\nout vec3 HSV_Out)\n{HSV_Out=vec3(fract(HSV_In.x+Hue_Shift),clamp(HSV_In.y+Saturation_Shift,0.0,1.0),clamp(HSV_In.z+Value_Shift,0.0,1.0));}\nvoid Remap_Range_B114(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid To_HSV_B75(\nvec4 Color,\nout float Hue,\nout float Saturation,\nout float Value,\nout float Alpha,\nout vec3 HSV)\n{vec4 K=vec4(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4 p=Color.g0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Conditional_Float_B36(\nbool Which,\nfloat If_True,\nfloat If_False,\nout float Result)\n{Result=Which ? If_True : If_False;}\nvoid Greater_Than_B37(\nfloat Left,\nfloat Right,\nout bool Not_Greater_Than,\nout bool Greater_Than)\n{Greater_Than=Left>Right;Not_Greater_Than=!Greater_Than;}\nvoid Remap_Range_B105(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid main()\n{vec2 XY_Q85;XY_Q85=(uv-vec2(0.5,0.5))*_Decal_Scale_XY_+vec2(0.5,0.5);vec3 Tangent_World_Q27;vec3 Tangent_World_N_Q27;float Tangent_Length_Q27;Tangent_World_Q27=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q27=length(Tangent_World_Q27);Tangent_World_N_Q27=Tangent_World_Q27/Tangent_Length_Q27;vec3 Normal_World_Q60;vec3 Normal_World_N_Q60;float Normal_Length_Q60;Object_To_World_Dir_B60(vec3(0,0,1),Normal_World_Q60,Normal_World_N_Q60,Normal_Length_Q60);float X_Q78;float Y_Q78;float Z_Q78;To_XYZ_B78(position,X_Q78,Y_Q78,Z_Q78);vec3 Nrm_World_Q26;Nrm_World_Q26=normalize((world*vec4(normal,0.0)).xyz);vec3 Binormal_World_Q28;vec3 Binormal_World_N_Q28;float Binormal_Length_Q28;Object_To_World_Dir_B28(vec3(0,1,0),Binormal_World_Q28,Binormal_World_N_Q28,Binormal_Length_Q28);float Anisotropy_Q29=Tangent_Length_Q27/Binormal_Length_Q28;float Result_Q69;Pick_Radius_B69(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q69);float Anisotropy_Q53=Binormal_Length_Q28/Normal_Length_Q60;bool Not_Greater_Than_Q37;bool Greater_Than_Q37;Greater_Than_B37(Z_Q78,0.0,Not_Greater_Than_Q37,Greater_Than_Q37);vec4 Linear_Q101;Linear_Q101.rgb=clamp(_Left_Color_.rgb*_Left_Color_.rgb,0.0,1.0);Linear_Q101.a=_Left_Color_.a;vec4 Linear_Q102;Linear_Q102.rgb=clamp(_Right_Color_.rgb*_Right_Color_.rgb,0.0,1.0);Linear_Q102.a=_Right_Color_.a;vec3 Difference_Q61=vec3(0,0,0)-Normal_World_N_Q60;vec4 Out_Color_Q34=vec4(X_Q78,Y_Q78,Z_Q78,1);float Result_Q36;Conditional_Float_B36(Greater_Than_Q37,_Bevel_Back_,_Bevel_Front_,Result_Q36);float Result_Q94;Conditional_Float_B36(Greater_Than_Q37,_Bevel_Back_Stretch_,_Bevel_Front_Stretch_,Result_Q94);vec3 New_P_Q130;vec2 New_UV_Q130;float Radial_Gradient_Q130;vec3 Radial_Dir_Q130;vec3 New_Normal_Q130;Move_Verts_B130(Anisotropy_Q29,position,Result_Q69,Result_Q36,normal,Anisotropy_Q53,Result_Q94,New_P_Q130,New_UV_Q130,Radial_Gradient_Q130,Radial_Dir_Q130,New_Normal_Q130);float X_Q98;float Y_Q98;X_Q98=New_UV_Q130.x;Y_Q98=New_UV_Q130.y;vec3 Pos_World_Q12;Object_To_World_Pos_B12(New_P_Q130,Pos_World_Q12);vec3 Nrm_World_Q32;Object_To_World_Normal_B32(New_Normal_Q130,Nrm_World_Q32);vec4 Blob_Info_Q23;\n#if BLOB_ENABLE\nBlob_Vertex_B23(Pos_World_Q12,Nrm_World_Q26,Tangent_World_N_Q27,Binormal_World_N_Q28,_Blob_Position_,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q23);\n#else\nBlob_Info_Q23=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q24;\n#if BLOB_ENABLE_2\nBlob_Vertex_B24(Pos_World_Q12,Nrm_World_Q26,Tangent_World_N_Q27,Binormal_World_N_Q28,_Blob_Position_2_,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q24);\n#else\nBlob_Info_Q24=vec4(0,0,0,0);\n#endif\nfloat Out_Q105;Remap_Range_B105(0.0,1.0,0.0,1.0,X_Q98,Out_Q105);float X_Q86;float Y_Q86;float Z_Q86;To_XYZ_B78(Nrm_World_Q32,X_Q86,Y_Q86,Z_Q86);vec4 Color_At_T_Q97=mix(Linear_Q101,Linear_Q102,Out_Q105);float Minus_F_Q87=-Z_Q86;float R_Q99;float G_Q99;float B_Q99;float A_Q99;R_Q99=Color_At_T_Q97.r; G_Q99=Color_At_T_Q97.g; B_Q99=Color_At_T_Q97.b; A_Q99=Color_At_T_Q97.a;float ClampF_Q88=clamp(0.0,Minus_F_Q87,1.0);float Result_Q93;Conditional_Float_B93(_Decal_Front_Only_,ClampF_Q88,1.0,Result_Q93);vec4 Vec4_Q89=vec4(Result_Q93,Radial_Gradient_Q130,G_Q99,B_Q99);vec3 Position=Pos_World_Q12;vec3 Normal=Nrm_World_Q32;vec2 UV=XY_Q85;vec3 Tangent=Tangent_World_N_Q27;vec3 Binormal=Difference_Q61;vec4 Color=Out_Color_Q34;vec4 Extra1=Vec4_Q89;vec4 Extra2=Blob_Info_Q23;vec4 Extra3=Blob_Info_Q24;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class tF extends xl{constructor(){super(),this.SKY_ENABLED=!0,this.BLOB_ENABLE_2=!0,this.IRIDESCENCE_ENABLED=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class iF extends ml{constructor(e,t){super(e,t),this.radius=.6,this.bevelFront=.6,this.bevelFrontStretch=.077,this.bevelBack=0,this.bevelBackStretch=0,this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this.bulgeEnabled=!1,this.bulgeHeight=-.323,this.bulgeRadius=.73,this.sunIntensity=1.102,this.sunTheta=.76,this.sunPhi=.526,this.indirectDiffuse=.658,this.albedo=new Ae(.0117647,.505882,.996078,1),this.specular=0,this.shininess=10,this.sharpness=0,this.subsurface=0,this.leftGradientColor=new Ae(.0117647,.505882,.996078,1),this.rightGradientColor=new Ae(.0117647,.505882,.996078,1),this.reflection=.749,this.frontReflect=0,this.edgeReflect=.09,this.power=8.13,this.skyColor=new Ae(.0117647,.964706,.996078,1),this.horizonColor=new Ae(.0117647,.333333,.996078,1),this.groundColor=new Ae(0,.254902,.996078,1),this.horizonPower=1,this.width=.02,this.fuzz=.5,this.minFuzz=.001,this.clipFade=.01,this.hueShift=0,this.saturationShift=0,this.valueShift=0,this.blobPosition=new _e(0,0,.1),this.blobIntensity=.5,this.blobNearSize=.01,this.blobFarSize=.03,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.576,this.blobPulse=0,this.blobFade=1,this.blobPosition2=new _e(.2,0,.1),this.blobNearSize2=.01,this.blobPulse2=0,this.blobFade2=1,this.blobTexture=new Pa("",this.getScene()),this.leftIndexPosition=new _e(0,0,1),this.rightIndexPosition=new _e(-1,-1,-1),this.leftIndexMiddlePosition=new _e(0,0,0),this.rightIndexMiddlePosition=new _e(0,0,0),this.decalScaleXY=new de(1.5,1.5),this.decalFrontOnly=!0,this.rimIntensity=.287,this.rimHueShift=0,this.rimSaturationShift=0,this.rimValueShift=-1,this.iridescenceIntensity=0,this.useGlobalLeftIndex=1,this.useGlobalRightIndex=1,this.globalLeftIndexTipProximity=0,this.globalRightIndexTipProximity=0,this.globalLeftIndexTipPosition=new pe(.5,0,-.55,1),this.globaRightIndexTipPosition=new pe(0,0,0,1),this.globalLeftThumbTipPosition=new pe(.5,0,-.55,1),this.globalRightThumbTipPosition=new pe(0,0,0,1),this.globalLeftIndexMiddlePosition=new pe(.5,0,-.55,1),this.globalRightIndexMiddlePosition=new pe(0,0,0,1),this.alphaMode=N_.ALPHA_DISABLE,this.backFaceCulling=!1,this._blueGradientTexture=new Pa(iF.BLUE_GRADIENT_TEXTURE_URL,this.getScene(),!0,!1,Pa.NEAREST_SAMPLINGMODE),this._decalTexture=new Pa("",this.getScene()),this._reflectionMapTexture=new Pa("",this.getScene()),this._indirectEnvTexture=new Pa("",this.getScene())}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new tF);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="mrdlSliderBar",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Bevel_Front_","_Bevel_Front_Stretch_","_Bevel_Back_","_Bevel_Back_Stretch_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Bulge_Enabled_","_Bulge_Height_","_Bulge_Radius_","_Sun_Intensity_","_Sun_Theta_","_Sun_Phi_","_Indirect_Diffuse_","_Albedo_","_Specular_","_Shininess_","_Sharpness_","_Subsurface_","_Left_Color_","_Right_Color_","_Reflection_","_Front_Reflect_","_Edge_Reflect_","_Power_","_Sky_Color_","_Horizon_Color_","_Ground_Color_","_Horizon_Power_","_Reflection_Map_","_Indirect_Environment_","_Width_","_Fuzz_","_Min_Fuzz_","_Clip_Fade_","_Hue_Shift_","_Saturation_Shift_","_Value_Shift_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Left_Index_Pos_","_Right_Index_Pos_","_Left_Index_Middle_Pos_","_Right_Index_Middle_Pos_","_Decal_","_Decal_Scale_XY_","_Decal_Front_Only_","_Rim_Intensity_","_Rim_Texture_","_Rim_Hue_Shift_","_Rim_Saturation_Shift_","_Rim_Value_Shift_","_Iridescence_Intensity_","_Iridescence_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Middle_Position;","Global_Right_Index_Middle_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Rim_Texture_","_Iridescence_Texture_"],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Bevel_Front_",this.bevelFront),this._activeEffect.setFloat("_Bevel_Front_Stretch_",this.bevelFrontStretch),this._activeEffect.setFloat("_Bevel_Back_",this.bevelBack),this._activeEffect.setFloat("_Bevel_Back_Stretch_",this.bevelBackStretch),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Bulge_Enabled_",this.bulgeEnabled?1:0),this._activeEffect.setFloat("_Bulge_Height_",this.bulgeHeight),this._activeEffect.setFloat("_Bulge_Radius_",this.bulgeRadius),this._activeEffect.setFloat("_Sun_Intensity_",this.sunIntensity),this._activeEffect.setFloat("_Sun_Theta_",this.sunTheta),this._activeEffect.setFloat("_Sun_Phi_",this.sunPhi),this._activeEffect.setFloat("_Indirect_Diffuse_",this.indirectDiffuse),this._activeEffect.setDirectColor4("_Albedo_",this.albedo),this._activeEffect.setFloat("_Specular_",this.specular),this._activeEffect.setFloat("_Shininess_",this.shininess),this._activeEffect.setFloat("_Sharpness_",this.sharpness),this._activeEffect.setFloat("_Subsurface_",this.subsurface),this._activeEffect.setDirectColor4("_Left_Color_",this.leftGradientColor),this._activeEffect.setDirectColor4("_Right_Color_",this.rightGradientColor),this._activeEffect.setFloat("_Reflection_",this.reflection),this._activeEffect.setFloat("_Front_Reflect_",this.frontReflect),this._activeEffect.setFloat("_Edge_Reflect_",this.edgeReflect),this._activeEffect.setFloat("_Power_",this.power),this._activeEffect.setDirectColor4("_Sky_Color_",this.skyColor),this._activeEffect.setDirectColor4("_Horizon_Color_",this.horizonColor),this._activeEffect.setDirectColor4("_Ground_Color_",this.groundColor),this._activeEffect.setFloat("_Horizon_Power_",this.horizonPower),this._activeEffect.setTexture("_Reflection_Map_",this._reflectionMapTexture),this._activeEffect.setTexture("_Indirect_Environment_",this._indirectEnvTexture),this._activeEffect.setFloat("_Width_",this.width),this._activeEffect.setFloat("_Fuzz_",this.fuzz),this._activeEffect.setFloat("_Min_Fuzz_",this.minFuzz),this._activeEffect.setFloat("_Clip_Fade_",this.clipFade),this._activeEffect.setFloat("_Hue_Shift_",this.hueShift),this._activeEffect.setFloat("_Saturation_Shift_",this.saturationShift),this._activeEffect.setFloat("_Value_Shift_",this.valueShift),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this.blobTexture),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setVector3("_Left_Index_Pos_",this.leftIndexPosition),this._activeEffect.setVector3("_Right_Index_Pos_",this.rightIndexPosition),this._activeEffect.setVector3("_Left_Index_Middle_Pos_",this.leftIndexMiddlePosition),this._activeEffect.setVector3("_Right_Index_Middle_Pos_",this.rightIndexMiddlePosition),this._activeEffect.setTexture("_Decal_",this._decalTexture),this._activeEffect.setVector2("_Decal_Scale_XY_",this.decalScaleXY),this._activeEffect.setFloat("_Decal_Front_Only_",this.decalFrontOnly?1:0),this._activeEffect.setFloat("_Rim_Intensity_",this.rimIntensity),this._activeEffect.setTexture("_Rim_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("_Rim_Hue_Shift_",this.rimHueShift),this._activeEffect.setFloat("_Rim_Saturation_Shift_",this.rimSaturationShift),this._activeEffect.setFloat("_Rim_Value_Shift_",this.rimValueShift),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setTexture("_Iridescence_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("Use_Global_Left_Index",this.useGlobalLeftIndex),this._activeEffect.setFloat("Use_Global_Right_Index",this.useGlobalRightIndex),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this.globalLeftIndexTipPosition),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this.globaRightIndexTipPosition),this._activeEffect.setVector4("Global_Left_Thumb_Tip_Position",this.globalLeftThumbTipPosition),this._activeEffect.setVector4("Global_Right_Thumb_Tip_Position",this.globalRightThumbTipPosition),this._activeEffect.setVector4("Global_Left_Index_Middle_Position",this.globalLeftIndexMiddlePosition),this._activeEffect.setVector4("Global_Right_Index_Middle_Position",this.globalRightIndexMiddlePosition),this._activeEffect.setFloat("Global_Left_Index_Tip_Proximity",this.globalLeftIndexTipProximity),this._activeEffect.setFloat("Global_Right_Index_Tip_Proximity",this.globalRightIndexTipProximity),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._reflectionMapTexture.dispose(),this._indirectEnvTexture.dispose(),this._blueGradientTexture.dispose(),this._decalTexture.dispose()}clone(e){return St.Clone((()=>new iF(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLSliderBarMaterial",e}getClassName(){return"MRDLSliderBarMaterial"}static Parse(e,t,i){return St.Parse((()=>new iF(e.name,t)),e,t,i)}}iF.BLUE_GRADIENT_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-blue-gradient.png",Ze([rt()],iF.prototype,"radius",void 0),Ze([rt()],iF.prototype,"bevelFront",void 0),Ze([rt()],iF.prototype,"bevelFrontStretch",void 0),Ze([rt()],iF.prototype,"bevelBack",void 0),Ze([rt()],iF.prototype,"bevelBackStretch",void 0),Ze([rt()],iF.prototype,"radiusTopLeft",void 0),Ze([rt()],iF.prototype,"radiusTopRight",void 0),Ze([rt()],iF.prototype,"radiusBottomLeft",void 0),Ze([rt()],iF.prototype,"radiusBottomRight",void 0),Ze([rt()],iF.prototype,"bulgeEnabled",void 0),Ze([rt()],iF.prototype,"bulgeHeight",void 0),Ze([rt()],iF.prototype,"bulgeRadius",void 0),Ze([rt()],iF.prototype,"sunIntensity",void 0),Ze([rt()],iF.prototype,"sunTheta",void 0),Ze([rt()],iF.prototype,"sunPhi",void 0),Ze([rt()],iF.prototype,"indirectDiffuse",void 0),Ze([rt()],iF.prototype,"albedo",void 0),Ze([rt()],iF.prototype,"specular",void 0),Ze([rt()],iF.prototype,"shininess",void 0),Ze([rt()],iF.prototype,"sharpness",void 0),Ze([rt()],iF.prototype,"subsurface",void 0),Ze([rt()],iF.prototype,"leftGradientColor",void 0),Ze([rt()],iF.prototype,"rightGradientColor",void 0),Ze([rt()],iF.prototype,"reflection",void 0),Ze([rt()],iF.prototype,"frontReflect",void 0),Ze([rt()],iF.prototype,"edgeReflect",void 0),Ze([rt()],iF.prototype,"power",void 0),Ze([rt()],iF.prototype,"skyColor",void 0),Ze([rt()],iF.prototype,"horizonColor",void 0),Ze([rt()],iF.prototype,"groundColor",void 0),Ze([rt()],iF.prototype,"horizonPower",void 0),Ze([rt()],iF.prototype,"width",void 0),Ze([rt()],iF.prototype,"fuzz",void 0),Ze([rt()],iF.prototype,"minFuzz",void 0),Ze([rt()],iF.prototype,"clipFade",void 0),Ze([rt()],iF.prototype,"hueShift",void 0),Ze([rt()],iF.prototype,"saturationShift",void 0),Ze([rt()],iF.prototype,"valueShift",void 0),Ze([rt()],iF.prototype,"blobPosition",void 0),Ze([rt()],iF.prototype,"blobIntensity",void 0),Ze([rt()],iF.prototype,"blobNearSize",void 0),Ze([rt()],iF.prototype,"blobFarSize",void 0),Ze([rt()],iF.prototype,"blobNearDistance",void 0),Ze([rt()],iF.prototype,"blobFarDistance",void 0),Ze([rt()],iF.prototype,"blobFadeLength",void 0),Ze([rt()],iF.prototype,"blobPulse",void 0),Ze([rt()],iF.prototype,"blobFade",void 0),Ze([rt()],iF.prototype,"blobPosition2",void 0),Ze([rt()],iF.prototype,"blobNearSize2",void 0),Ze([rt()],iF.prototype,"blobPulse2",void 0),Ze([rt()],iF.prototype,"blobFade2",void 0),Ze([rt()],iF.prototype,"blobTexture",void 0),Ze([rt()],iF.prototype,"leftIndexPosition",void 0),Ze([rt()],iF.prototype,"rightIndexPosition",void 0),Ze([rt()],iF.prototype,"leftIndexMiddlePosition",void 0),Ze([rt()],iF.prototype,"rightIndexMiddlePosition",void 0),Ze([rt()],iF.prototype,"decalScaleXY",void 0),Ze([rt()],iF.prototype,"decalFrontOnly",void 0),Ze([rt()],iF.prototype,"rimIntensity",void 0),Ze([rt()],iF.prototype,"rimHueShift",void 0),Ze([rt()],iF.prototype,"rimSaturationShift",void 0),Ze([rt()],iF.prototype,"rimValueShift",void 0),Ze([rt()],iF.prototype,"iridescenceIntensity",void 0),z("BABYLON.GUI.MRDLSliderBarMaterial",iF);Bi.ShadersStore.mrdlSliderThumbPixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;uniform float _Radius_;uniform float _Bevel_Front_;uniform float _Bevel_Front_Stretch_;uniform float _Bevel_Back_;uniform float _Bevel_Back_Stretch_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform bool _Bulge_Enabled_;uniform float _Bulge_Height_;uniform float _Bulge_Radius_;uniform float _Sun_Intensity_;uniform float _Sun_Theta_;uniform float _Sun_Phi_;uniform float _Indirect_Diffuse_;uniform vec4 _Albedo_;uniform float _Specular_;uniform float _Shininess_;uniform float _Sharpness_;uniform float _Subsurface_;uniform vec4 _Left_Color_;uniform vec4 _Right_Color_;uniform float _Reflection_;uniform float _Front_Reflect_;uniform float _Edge_Reflect_;uniform float _Power_;uniform vec4 _Sky_Color_;uniform vec4 _Horizon_Color_;uniform vec4 _Ground_Color_;uniform float _Horizon_Power_;uniform sampler2D _Reflection_Map_;uniform sampler2D _Indirect_Environment_;uniform float _Width_;uniform float _Fuzz_;uniform float _Min_Fuzz_;uniform float _Clip_Fade_;uniform float _Hue_Shift_;uniform float _Saturation_Shift_;uniform float _Value_Shift_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Left_Index_Pos_;uniform vec3 _Right_Index_Pos_;uniform vec3 _Left_Index_Middle_Pos_;uniform vec3 _Right_Index_Middle_Pos_;uniform sampler2D _Decal_;uniform vec2 _Decal_Scale_XY_;uniform bool _Decal_Front_Only_;uniform float _Rim_Intensity_;uniform sampler2D _Rim_Texture_;uniform float _Rim_Hue_Shift_;uniform float _Rim_Saturation_Shift_;uniform float _Rim_Value_Shift_;uniform float _Iridescence_Intensity_;uniform sampler2D _Iridescence_Texture_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform vec4 Global_Left_Index_Middle_Position;uniform vec4 Global_Right_Index_Middle_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;void Blob_Fragment_B180(\nsampler2D Blob_Texture,\nvec4 Blob_Info1,\nvec4 Blob_Info2,\nout vec4 Blob_Color)\n{float k1=dot(Blob_Info1.xy,Blob_Info1.xy);float k2=dot(Blob_Info2.xy,Blob_Info2.xy);vec3 closer=k10.0) {C=mix(H,S,k);} else {C=mix(H,G,k); }\nreturn C;}\nvoid Sky_Environment_B200(\nvec3 Normal,\nvec3 Reflected,\nvec4 Sky_Color,\nvec4 Horizon_Color,\nvec4 Ground_Color,\nfloat Horizon_Power,\nout vec4 Reflected_Color,\nout vec4 Indirect_Color)\n{Reflected_Color=SampleEnv_Bid200(Reflected,Sky_Color,Horizon_Color,Ground_Color,Horizon_Power);Indirect_Color=mix(Ground_Color,Sky_Color,Normal.y*0.5+0.5);}\nvoid Min_Segment_Distance_B215(\nvec3 P0,\nvec3 P1,\nvec3 Q0,\nvec3 Q1,\nout vec3 NearP,\nout vec3 NearQ,\nout float Distance)\n{vec3 u=P1-P0;vec3 v=Q1-Q0;vec3 w=P0-Q0;float a=dot(u,u);float b=dot(u,v);float c=dot(v,v);float d=dot(u,w);float e=dot(v,w);float D=a*c-b*b;float sD=D;float tD=D;float sc,sN,tc,tN;if (D<0.00001) {sN=0.0;sD=1.0;tN=e;tD=c;} else {sN=(b*e-c*d);tN=(a*e-b*d);if (sN<0.0) {sN=0.0;tN=e;tD=c;} else if (sN>sD) {sN=sD;tN=e+b;tD=c;}}\nif (tN<0.0) {tN=0.0;if (-d<0.0) {sN=0.0;} else if (-d>a) {sN=sD;} else {sN=-d;sD=a;}} else if (tN>tD) {tN=tD;if ((-d+b)<0.0) {sN=0.0;} else if ((-d+b)>a) {sN=sD;} else {sN=(-d+b);sD=a;}}\nsc=abs(sN)<0.000001 ? 0.0 : sN/sD;tc=abs(tN)<0.000001 ? 0.0 : tN/tD;NearP=P0+sc*u;NearQ=Q0+tc*v;Distance=distance(NearP,NearQ);}\nvoid To_XYZ_B224(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid Finger_Positions_B214(\nvec3 Left_Index_Pos,\nvec3 Right_Index_Pos,\nvec3 Left_Index_Middle_Pos,\nvec3 Right_Index_Middle_Pos,\nout vec3 Left_Index,\nout vec3 Right_Index,\nout vec3 Left_Index_Middle,\nout vec3 Right_Index_Middle)\n{Left_Index= (Use_Global_Left_Index ? Global_Left_Index_Tip_Position.xyz : Left_Index_Pos);Right_Index= (Use_Global_Right_Index ? Global_Right_Index_Tip_Position.xyz : Right_Index_Pos);Left_Index_Middle= (Use_Global_Left_Index ? Global_Left_Index_Middle_Position.xyz : Left_Index_Middle_Pos);Right_Index_Middle= (Use_Global_Right_Index ? Global_Right_Index_Middle_Position.xyz : Right_Index_Middle_Pos);}\nvoid VaryHSV_B258(\nvec3 HSV_In,\nfloat Hue_Shift,\nfloat Saturation_Shift,\nfloat Value_Shift,\nout vec3 HSV_Out)\n{HSV_Out=vec3(fract(HSV_In.x+Hue_Shift),clamp(HSV_In.y+Saturation_Shift,0.0,1.0),clamp(HSV_In.z+Value_Shift,0.0,1.0));}\nvoid Remap_Range_B264(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid To_HSV_B225(\nvec4 Color,\nout float Hue,\nout float Saturation,\nout float Value,\nout float Alpha,\nout vec3 HSV)\n{vec4 K=vec4(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4 p=Color.g0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Conditional_Float_B186(\nbool Which,\nfloat If_True,\nfloat If_False,\nout float Result)\n{Result=Which ? If_True : If_False;}\nvoid Greater_Than_B187(\nfloat Left,\nfloat Right,\nout bool Not_Greater_Than,\nout bool Greater_Than)\n{Greater_Than=Left>Right;Not_Greater_Than=!Greater_Than;}\nvoid Remap_Range_B255(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid main()\n{vec2 XY_Q235;XY_Q235=(uv-vec2(0.5,0.5))*_Decal_Scale_XY_+vec2(0.5,0.5);vec3 Tangent_World_Q177;vec3 Tangent_World_N_Q177;float Tangent_Length_Q177;Tangent_World_Q177=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q177=length(Tangent_World_Q177);Tangent_World_N_Q177=Tangent_World_Q177/Tangent_Length_Q177;vec3 Normal_World_Q210;vec3 Normal_World_N_Q210;float Normal_Length_Q210;Object_To_World_Dir_B210(vec3(0,0,1),Normal_World_Q210,Normal_World_N_Q210,Normal_Length_Q210);float X_Q228;float Y_Q228;float Z_Q228;To_XYZ_B228(position,X_Q228,Y_Q228,Z_Q228);vec3 Nrm_World_Q176;Nrm_World_Q176=normalize((world*vec4(normal,0.0)).xyz);vec3 Binormal_World_Q178;vec3 Binormal_World_N_Q178;float Binormal_Length_Q178;Object_To_World_Dir_B178(vec3(0,1,0),Binormal_World_Q178,Binormal_World_N_Q178,Binormal_Length_Q178);float Anisotropy_Q179=Tangent_Length_Q177/Binormal_Length_Q178;float Result_Q219;Pick_Radius_B219(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q219);float Anisotropy_Q203=Binormal_Length_Q178/Normal_Length_Q210;bool Not_Greater_Than_Q187;bool Greater_Than_Q187;Greater_Than_B187(Z_Q228,0.0,Not_Greater_Than_Q187,Greater_Than_Q187);vec4 Linear_Q251;Linear_Q251.rgb=clamp(_Left_Color_.rgb*_Left_Color_.rgb,0.0,1.0);Linear_Q251.a=_Left_Color_.a;vec4 Linear_Q252;Linear_Q252.rgb=clamp(_Right_Color_.rgb*_Right_Color_.rgb,0.0,1.0);Linear_Q252.a=_Right_Color_.a;vec3 Difference_Q211=vec3(0,0,0)-Normal_World_N_Q210;vec4 Out_Color_Q184=vec4(X_Q228,Y_Q228,Z_Q228,1);float Result_Q186;Conditional_Float_B186(Greater_Than_Q187,_Bevel_Back_,_Bevel_Front_,Result_Q186);float Result_Q244;Conditional_Float_B186(Greater_Than_Q187,_Bevel_Back_Stretch_,_Bevel_Front_Stretch_,Result_Q244);vec3 New_P_Q280;vec2 New_UV_Q280;float Radial_Gradient_Q280;vec3 Radial_Dir_Q280;vec3 New_Normal_Q280;Move_Verts_B280(Anisotropy_Q179,position,Result_Q219,Result_Q186,normal,Anisotropy_Q203,Result_Q244,New_P_Q280,New_UV_Q280,Radial_Gradient_Q280,Radial_Dir_Q280,New_Normal_Q280);float X_Q248;float Y_Q248;X_Q248=New_UV_Q280.x;Y_Q248=New_UV_Q280.y;vec3 Pos_World_Q162;Object_To_World_Pos_B162(New_P_Q280,Pos_World_Q162);vec3 Nrm_World_Q182;Object_To_World_Normal_B182(New_Normal_Q280,Nrm_World_Q182);vec4 Blob_Info_Q173;\n#if BLOB_ENABLE\nBlob_Vertex_B173(Pos_World_Q162,Nrm_World_Q176,Tangent_World_N_Q177,Binormal_World_N_Q178,_Blob_Position_,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q173);\n#else\nBlob_Info_Q173=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q174;\n#if BLOB_ENABLE_2\nBlob_Vertex_B174(Pos_World_Q162,Nrm_World_Q176,Tangent_World_N_Q177,Binormal_World_N_Q178,_Blob_Position_2_,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q174);\n#else\nBlob_Info_Q174=vec4(0,0,0,0);\n#endif\nfloat Out_Q255;Remap_Range_B255(0.0,1.0,0.0,1.0,X_Q248,Out_Q255);float X_Q236;float Y_Q236;float Z_Q236;To_XYZ_B228(Nrm_World_Q182,X_Q236,Y_Q236,Z_Q236);vec4 Color_At_T_Q247=mix(Linear_Q251,Linear_Q252,Out_Q255);float Minus_F_Q237=-Z_Q236;float R_Q249;float G_Q249;float B_Q249;float A_Q249;R_Q249=Color_At_T_Q247.r; G_Q249=Color_At_T_Q247.g; B_Q249=Color_At_T_Q247.b; A_Q249=Color_At_T_Q247.a;float ClampF_Q238=clamp(0.0,Minus_F_Q237,1.0);float Result_Q243;Conditional_Float_B243(_Decal_Front_Only_,ClampF_Q238,1.0,Result_Q243);vec4 Vec4_Q239=vec4(Result_Q243,Radial_Gradient_Q280,G_Q249,B_Q249);vec3 Position=Pos_World_Q162;vec3 Normal=Nrm_World_Q182;vec2 UV=XY_Q235;vec3 Tangent=Tangent_World_N_Q177;vec3 Binormal=Difference_Q211;vec4 Color=Out_Color_Q184;vec4 Extra1=Vec4_Q239;vec4 Extra2=Blob_Info_Q173;vec4 Extra3=Blob_Info_Q174;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class sF extends xl{constructor(){super(),this.SKY_ENABLED=!0,this.BLOB_ENABLE_2=!0,this.IRIDESCENCE_ENABLED=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class rF extends ml{constructor(e,t){super(e,t),this.radius=.157,this.bevelFront=.065,this.bevelFrontStretch=.077,this.bevelBack=.031,this.bevelBackStretch=0,this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this.bulgeEnabled=!1,this.bulgeHeight=-.323,this.bulgeRadius=.73,this.sunIntensity=2,this.sunTheta=.937,this.sunPhi=.555,this.indirectDiffuse=1,this.albedo=new Ae(.0117647,.505882,.996078,1),this.specular=0,this.shininess=10,this.sharpness=0,this.subsurface=.31,this.leftGradientColor=new Ae(.0117647,.505882,.996078,1),this.rightGradientColor=new Ae(.0117647,.505882,.996078,1),this.reflection=.749,this.frontReflect=0,this.edgeReflect=.09,this.power=8.1,this.skyColor=new Ae(.0117647,.960784,.996078,1),this.horizonColor=new Ae(.0117647,.333333,.996078,1),this.groundColor=new Ae(0,.254902,.996078,1),this.horizonPower=1,this.width=.02,this.fuzz=.5,this.minFuzz=.001,this.clipFade=.01,this.hueShift=0,this.saturationShift=0,this.valueShift=0,this.blobPosition=new _e(0,0,.1),this.blobIntensity=.5,this.blobNearSize=.01,this.blobFarSize=.03,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.576,this.blobPulse=0,this.blobFade=1,this.blobPosition2=new _e(.2,0,.1),this.blobNearSize2=.01,this.blobPulse2=0,this.blobFade2=1,this.blobTexture=new Pa("",this.getScene()),this.leftIndexPosition=new _e(0,0,1),this.rightIndexPosition=new _e(-1,-1,-1),this.leftIndexMiddlePosition=new _e(0,0,0),this.rightIndexMiddlePosition=new _e(0,0,0),this.decalScaleXY=new de(1.5,1.5),this.decalFrontOnly=!0,this.rimIntensity=.287,this.rimHueShift=0,this.rimSaturationShift=0,this.rimValueShift=-1,this.iridescenceIntensity=0,this.useGlobalLeftIndex=1,this.useGlobalRightIndex=1,this.globalLeftIndexTipProximity=0,this.globalRightIndexTipProximity=0,this.globalLeftIndexTipPosition=new pe(.5,0,-.55,1),this.globaRightIndexTipPosition=new pe(0,0,0,1),this.globalLeftThumbTipPosition=new pe(.5,0,-.55,1),this.globalRightThumbTipPosition=new pe(0,0,0,1),this.globalLeftIndexMiddlePosition=new pe(.5,0,-.55,1),this.globalRightIndexMiddlePosition=new pe(0,0,0,1),this.alphaMode=N_.ALPHA_DISABLE,this.backFaceCulling=!1,this._blueGradientTexture=new Pa(rF.BLUE_GRADIENT_TEXTURE_URL,t,!0,!1,Pa.NEAREST_SAMPLINGMODE),this._decalTexture=new Pa("",this.getScene()),this._reflectionMapTexture=new Pa("",this.getScene()),this._indirectEnvTexture=new Pa("",this.getScene())}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new sF);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="mrdlSliderThumb",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Bevel_Front_","_Bevel_Front_Stretch_","_Bevel_Back_","_Bevel_Back_Stretch_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Bulge_Enabled_","_Bulge_Height_","_Bulge_Radius_","_Sun_Intensity_","_Sun_Theta_","_Sun_Phi_","_Indirect_Diffuse_","_Albedo_","_Specular_","_Shininess_","_Sharpness_","_Subsurface_","_Left_Color_","_Right_Color_","_Reflection_","_Front_Reflect_","_Edge_Reflect_","_Power_","_Sky_Color_","_Horizon_Color_","_Ground_Color_","_Horizon_Power_","_Reflection_Map_","_Indirect_Environment_","_Width_","_Fuzz_","_Min_Fuzz_","_Clip_Fade_","_Hue_Shift_","_Saturation_Shift_","_Value_Shift_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Left_Index_Pos_","_Right_Index_Pos_","_Left_Index_Middle_Pos_","_Right_Index_Middle_Pos_","_Decal_","_Decal_Scale_XY_","_Decal_Front_Only_","_Rim_Intensity_","_Rim_Texture_","_Rim_Hue_Shift_","_Rim_Saturation_Shift_","_Rim_Value_Shift_","_Iridescence_Intensity_","_Iridescence_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Middle_Position;","Global_Right_Index_Middle_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Rim_Texture_","_Iridescence_Texture_"],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Bevel_Front_",this.bevelFront),this._activeEffect.setFloat("_Bevel_Front_Stretch_",this.bevelFrontStretch),this._activeEffect.setFloat("_Bevel_Back_",this.bevelBack),this._activeEffect.setFloat("_Bevel_Back_Stretch_",this.bevelBackStretch),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Bulge_Enabled_",this.bulgeEnabled?1:0),this._activeEffect.setFloat("_Bulge_Height_",this.bulgeHeight),this._activeEffect.setFloat("_Bulge_Radius_",this.bulgeRadius),this._activeEffect.setFloat("_Sun_Intensity_",this.sunIntensity),this._activeEffect.setFloat("_Sun_Theta_",this.sunTheta),this._activeEffect.setFloat("_Sun_Phi_",this.sunPhi),this._activeEffect.setFloat("_Indirect_Diffuse_",this.indirectDiffuse),this._activeEffect.setDirectColor4("_Albedo_",this.albedo),this._activeEffect.setFloat("_Specular_",this.specular),this._activeEffect.setFloat("_Shininess_",this.shininess),this._activeEffect.setFloat("_Sharpness_",this.sharpness),this._activeEffect.setFloat("_Subsurface_",this.subsurface),this._activeEffect.setDirectColor4("_Left_Color_",this.leftGradientColor),this._activeEffect.setDirectColor4("_Right_Color_",this.rightGradientColor),this._activeEffect.setFloat("_Reflection_",this.reflection),this._activeEffect.setFloat("_Front_Reflect_",this.frontReflect),this._activeEffect.setFloat("_Edge_Reflect_",this.edgeReflect),this._activeEffect.setFloat("_Power_",this.power),this._activeEffect.setDirectColor4("_Sky_Color_",this.skyColor),this._activeEffect.setDirectColor4("_Horizon_Color_",this.horizonColor),this._activeEffect.setDirectColor4("_Ground_Color_",this.groundColor),this._activeEffect.setFloat("_Horizon_Power_",this.horizonPower),this._activeEffect.setTexture("_Reflection_Map_",this._reflectionMapTexture),this._activeEffect.setTexture("_Indirect_Environment_",this._indirectEnvTexture),this._activeEffect.setFloat("_Width_",this.width),this._activeEffect.setFloat("_Fuzz_",this.fuzz),this._activeEffect.setFloat("_Min_Fuzz_",this.minFuzz),this._activeEffect.setFloat("_Clip_Fade_",this.clipFade),this._activeEffect.setFloat("_Hue_Shift_",this.hueShift),this._activeEffect.setFloat("_Saturation_Shift_",this.saturationShift),this._activeEffect.setFloat("_Value_Shift_",this.valueShift),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this.blobTexture),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setVector3("_Left_Index_Pos_",this.leftIndexPosition),this._activeEffect.setVector3("_Right_Index_Pos_",this.rightIndexPosition),this._activeEffect.setVector3("_Left_Index_Middle_Pos_",this.leftIndexMiddlePosition),this._activeEffect.setVector3("_Right_Index_Middle_Pos_",this.rightIndexMiddlePosition),this._activeEffect.setTexture("_Decal_",this._decalTexture),this._activeEffect.setVector2("_Decal_Scale_XY_",this.decalScaleXY),this._activeEffect.setFloat("_Decal_Front_Only_",this.decalFrontOnly?1:0),this._activeEffect.setFloat("_Rim_Intensity_",this.rimIntensity),this._activeEffect.setTexture("_Rim_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("_Rim_Hue_Shift_",this.rimHueShift),this._activeEffect.setFloat("_Rim_Saturation_Shift_",this.rimSaturationShift),this._activeEffect.setFloat("_Rim_Value_Shift_",this.rimValueShift),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setTexture("_Iridescence_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("Use_Global_Left_Index",this.useGlobalLeftIndex),this._activeEffect.setFloat("Use_Global_Right_Index",this.useGlobalRightIndex),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this.globalLeftIndexTipPosition),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this.globaRightIndexTipPosition),this._activeEffect.setVector4("Global_Left_Thumb_Tip_Position",this.globalLeftThumbTipPosition),this._activeEffect.setVector4("Global_Right_Thumb_Tip_Position",this.globalRightThumbTipPosition),this._activeEffect.setVector4("Global_Left_Index_Middle_Position",this.globalLeftIndexMiddlePosition),this._activeEffect.setVector4("Global_Right_Index_Middle_Position",this.globalRightIndexMiddlePosition),this._activeEffect.setFloat("Global_Left_Index_Tip_Proximity",this.globalLeftIndexTipProximity),this._activeEffect.setFloat("Global_Right_Index_Tip_Proximity",this.globalRightIndexTipProximity),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._reflectionMapTexture.dispose(),this._indirectEnvTexture.dispose(),this._blueGradientTexture.dispose(),this._decalTexture.dispose()}clone(e){return St.Clone((()=>new rF(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLSliderThumbMaterial",e}getClassName(){return"MRDLSliderThumbMaterial"}static Parse(e,t,i){return St.Parse((()=>new rF(e.name,t)),e,t,i)}}rF.BLUE_GRADIENT_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-blue-gradient.png",Ze([rt()],rF.prototype,"radius",void 0),Ze([rt()],rF.prototype,"bevelFront",void 0),Ze([rt()],rF.prototype,"bevelFrontStretch",void 0),Ze([rt()],rF.prototype,"bevelBack",void 0),Ze([rt()],rF.prototype,"bevelBackStretch",void 0),Ze([rt()],rF.prototype,"radiusTopLeft",void 0),Ze([rt()],rF.prototype,"radiusTopRight",void 0),Ze([rt()],rF.prototype,"radiusBottomLeft",void 0),Ze([rt()],rF.prototype,"radiusBottomRight",void 0),Ze([rt()],rF.prototype,"bulgeEnabled",void 0),Ze([rt()],rF.prototype,"bulgeHeight",void 0),Ze([rt()],rF.prototype,"bulgeRadius",void 0),Ze([rt()],rF.prototype,"sunIntensity",void 0),Ze([rt()],rF.prototype,"sunTheta",void 0),Ze([rt()],rF.prototype,"sunPhi",void 0),Ze([rt()],rF.prototype,"indirectDiffuse",void 0),Ze([rt()],rF.prototype,"albedo",void 0),Ze([rt()],rF.prototype,"specular",void 0),Ze([rt()],rF.prototype,"shininess",void 0),Ze([rt()],rF.prototype,"sharpness",void 0),Ze([rt()],rF.prototype,"subsurface",void 0),Ze([rt()],rF.prototype,"leftGradientColor",void 0),Ze([rt()],rF.prototype,"rightGradientColor",void 0),Ze([rt()],rF.prototype,"reflection",void 0),Ze([rt()],rF.prototype,"frontReflect",void 0),Ze([rt()],rF.prototype,"edgeReflect",void 0),Ze([rt()],rF.prototype,"power",void 0),Ze([rt()],rF.prototype,"skyColor",void 0),Ze([rt()],rF.prototype,"horizonColor",void 0),Ze([rt()],rF.prototype,"groundColor",void 0),Ze([rt()],rF.prototype,"horizonPower",void 0),Ze([rt()],rF.prototype,"width",void 0),Ze([rt()],rF.prototype,"fuzz",void 0),Ze([rt()],rF.prototype,"minFuzz",void 0),Ze([rt()],rF.prototype,"clipFade",void 0),Ze([rt()],rF.prototype,"hueShift",void 0),Ze([rt()],rF.prototype,"saturationShift",void 0),Ze([rt()],rF.prototype,"valueShift",void 0),Ze([rt()],rF.prototype,"blobPosition",void 0),Ze([rt()],rF.prototype,"blobIntensity",void 0),Ze([rt()],rF.prototype,"blobNearSize",void 0),Ze([rt()],rF.prototype,"blobFarSize",void 0),Ze([rt()],rF.prototype,"blobNearDistance",void 0),Ze([rt()],rF.prototype,"blobFarDistance",void 0),Ze([rt()],rF.prototype,"blobFadeLength",void 0),Ze([rt()],rF.prototype,"blobPulse",void 0),Ze([rt()],rF.prototype,"blobFade",void 0),Ze([rt()],rF.prototype,"blobPosition2",void 0),Ze([rt()],rF.prototype,"blobNearSize2",void 0),Ze([rt()],rF.prototype,"blobPulse2",void 0),Ze([rt()],rF.prototype,"blobFade2",void 0),Ze([rt()],rF.prototype,"blobTexture",void 0),Ze([rt()],rF.prototype,"leftIndexPosition",void 0),Ze([rt()],rF.prototype,"rightIndexPosition",void 0),Ze([rt()],rF.prototype,"leftIndexMiddlePosition",void 0),Ze([rt()],rF.prototype,"rightIndexMiddlePosition",void 0),Ze([rt()],rF.prototype,"decalScaleXY",void 0),Ze([rt()],rF.prototype,"decalFrontOnly",void 0),Ze([rt()],rF.prototype,"rimIntensity",void 0),Ze([rt()],rF.prototype,"rimHueShift",void 0),Ze([rt()],rF.prototype,"rimSaturationShift",void 0),Ze([rt()],rF.prototype,"rimValueShift",void 0),Ze([rt()],rF.prototype,"iridescenceIntensity",void 0),z("BABYLON.GUI.MRDLSliderThumbMaterial",rF);Bi.ShadersStore.mrdlBackplatePixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vExtra1;varying vec4 vExtra2;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Filter_Width_;uniform vec4 _Base_Color_;uniform vec4 _Line_Color_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform float _Rate_;uniform vec4 _Highlight_Color_;uniform float _Highlight_Width_;uniform vec4 _Highlight_Transform_;uniform float _Highlight_;uniform float _Iridescence_Intensity_;uniform float _Iridescence_Edge_Intensity_;uniform vec4 _Iridescence_Tint_;uniform sampler2D _Iridescent_Map_;uniform float _Angle_;uniform bool _Reflected_;uniform float _Frequency_;uniform float _Vertical_Offset_;uniform vec4 _Gradient_Color_;uniform vec4 _Top_Left_;uniform vec4 _Top_Right_;uniform vec4 _Bottom_Left_;uniform vec4 _Bottom_Right_;uniform float _Edge_Width_;uniform float _Edge_Power_;uniform float _Line_Gradient_Blend_;uniform float _Fade_Out_;void FastLinearTosRGB_B353(\nvec4 Linear,\nout vec4 sRGB)\n{sRGB.rgb=sqrt(clamp(Linear.rgb,0.0,1.0));sRGB.a=Linear.a;}\nvoid Round_Rect_Fragment_B332(\nfloat Radius,\nfloat Line_Width,\nvec4 Line_Color,\nfloat Filter_Width,\nvec2 UV,\nfloat Line_Visibility,\nvec4 Rect_Parms,\nvec4 Fill_Color,\nout vec4 Color)\n{float d=length(max(abs(UV)-Rect_Parms.xy,0.0));float dx=max(fwidth(d)*Filter_Width,0.00001);float g=min(Rect_Parms.z,Rect_Parms.w);float dgrad=max(fwidth(g)*Filter_Width,0.00001);float Inside_Rect=clamp(g/dgrad,0.0,1.0);float inner=clamp((d+dx*0.5-max(Radius-Line_Width,d-dx*0.5))/dx,0.0,1.0);Color=clamp(mix(Fill_Color,Line_Color,inner),0.0,1.0)*Inside_Rect;}\nvoid Iridescence_B343(\nvec3 Position,\nvec3 Normal,\nvec2 UV,\nvec3 Axis,\nvec3 Eye,\nvec4 Tint,\nsampler2D Texture,\nbool Reflected,\nfloat Frequency,\nfloat Vertical_Offset,\nout vec4 Color)\n{vec3 i=normalize(Position-Eye);vec3 r=reflect(i,Normal);float idota=dot(i,Axis);float idotr=dot(i,r);float x=Reflected ? idotr : idota;vec2 xy;xy.x=fract((x*Frequency+1.0)*0.5+UV.y*Vertical_Offset);xy.y=0.5;Color=texture(Texture,xy);Color.rgb*=Tint.rgb;}\nvoid Scale_RGB_B346(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Scale_RGB_B344(\nfloat Scalar,\nvec4 Color,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Line_Fragment_B362(\nvec4 Base_Color,\nvec4 Highlight_Color,\nfloat Highlight_Width,\nvec3 Line_Vertex,\nfloat Highlight,\nout vec4 Line_Color)\n{float k2=1.0-clamp(abs(Line_Vertex.y/Highlight_Width),0.0,1.0);Line_Color=mix(Base_Color,Highlight_Color,Highlight*k2);}\nvoid Edge_B356(\nvec4 RectParms,\nfloat Radius,\nfloat Line_Width,\nvec2 UV,\nfloat Edge_Width,\nfloat Edge_Power,\nout float Result)\n{float d=length(max(abs(UV)-RectParms.xy,0.0));float edge=1.0-clamp((1.0-d/(Radius-Line_Width))/Edge_Width,0.0,1.0);Result=pow(edge,Edge_Power);}\nvoid Gradient_B355(\nvec4 Gradient_Color,\nvec4 Top_Left,\nvec4 Top_Right,\nvec4 Bottom_Left,\nvec4 Bottom_Right,\nvec2 UV,\nout vec4 Result)\n{vec3 top=Top_Left.rgb+(Top_Right.rgb-Top_Left.rgb)*UV.x;vec3 bottom=Bottom_Left.rgb+(Bottom_Right.rgb-Bottom_Left.rgb)*UV.x;Result.rgb=Gradient_Color.rgb*(bottom+(top-bottom)*UV.y);Result.a=1.0;}\nvoid main()\n{float X_Q338;float Y_Q338;float Z_Q338;float W_Q338;X_Q338=vExtra2.x;Y_Q338=vExtra2.y;Z_Q338=vExtra2.z;W_Q338=vExtra2.w;vec4 Color_Q343;\n#if IRIDESCENCE_ENABLE\nIridescence_B343(vPosition,vNormal,vUV,vBinormal,cameraPosition,_Iridescence_Tint_,_Iridescent_Map_,_Reflected_,_Frequency_,_Vertical_Offset_,Color_Q343);\n#else\nColor_Q343=vec4(0,0,0,0);\n#endif\nvec4 Result_Q344;Scale_RGB_B344(_Iridescence_Intensity_,Color_Q343,Result_Q344);vec4 Line_Color_Q362;Line_Fragment_B362(_Line_Color_,_Highlight_Color_,_Highlight_Width_,vTangent,_Highlight_,Line_Color_Q362);float Result_Q356;\n#if EDGE_ONLY\nEdge_B356(vExtra1,Z_Q338,W_Q338,vUV,_Edge_Width_,_Edge_Power_,Result_Q356);\n#else\nResult_Q356=1.0;\n#endif\nvec2 Vec2_Q339=vec2(X_Q338,Y_Q338);vec4 Result_Q355;Gradient_B355(_Gradient_Color_,_Top_Left_,_Top_Right_,_Bottom_Left_,_Bottom_Right_,Vec2_Q339,Result_Q355);vec4 Linear_Q348;Linear_Q348.rgb=clamp(Result_Q355.rgb*Result_Q355.rgb,0.0,1.0);Linear_Q348.a=Result_Q355.a;vec4 Result_Q346;Scale_RGB_B346(Linear_Q348,Result_Q356,Result_Q346);vec4 Sum_Q345=Result_Q346+Result_Q344;vec4 Color_At_T_Q347=mix(Line_Color_Q362,Result_Q346,_Line_Gradient_Blend_);vec4 Base_And_Iridescent_Q350;Base_And_Iridescent_Q350=_Base_Color_+vec4(Sum_Q345.rgb,0.0);vec4 Sum_Q349=Color_At_T_Q347+_Iridescence_Edge_Intensity_*Color_Q343;vec4 Result_Q351=Sum_Q349; Result_Q351.a=1.0;vec4 Color_Q332;Round_Rect_Fragment_B332(Z_Q338,W_Q338,Result_Q351,_Filter_Width_,vUV,1.0,vExtra1,Base_And_Iridescent_Q350,Color_Q332);vec4 Result_Q354=_Fade_Out_*Color_Q332;vec4 sRGB_Q353;FastLinearTosRGB_B353(Result_Q354,sRGB_Q353);vec4 Out_Color=sRGB_Q353;float Clip_Threshold=0.001;bool To_sRGB=false;gl_FragColor=Out_Color;}";Bi.ShadersStore.mrdlBackplateVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec3 tangent;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Filter_Width_;uniform vec4 _Base_Color_;uniform vec4 _Line_Color_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform float _Rate_;uniform vec4 _Highlight_Color_;uniform float _Highlight_Width_;uniform vec4 _Highlight_Transform_;uniform float _Highlight_;uniform float _Iridescence_Intensity_;uniform float _Iridescence_Edge_Intensity_;uniform vec4 _Iridescence_Tint_;uniform sampler2D _Iridescent_Map_;uniform float _Angle_;uniform bool _Reflected_;uniform float _Frequency_;uniform float _Vertical_Offset_;uniform vec4 _Gradient_Color_;uniform vec4 _Top_Left_;uniform vec4 _Top_Right_;uniform vec4 _Bottom_Left_;uniform vec4 _Bottom_Right_;uniform float _Edge_Width_;uniform float _Edge_Power_;uniform float _Line_Gradient_Blend_;uniform float _Fade_Out_;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vExtra1;varying vec4 vExtra2;void Object_To_World_Pos_B314(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Round_Rect_Vertex_B357(\nvec2 UV,\nfloat Radius,\nfloat Margin,\nfloat Anisotropy,\nfloat Gradient1,\nfloat Gradient2,\nvec3 Normal,\nvec4 Color_Scale_Translate,\nout vec2 Rect_UV,\nout vec4 Rect_Parms,\nout vec2 Scale_XY,\nout vec2 Line_UV,\nout vec2 Color_UV_Info)\n{Scale_XY=vec2(Anisotropy,1.0);Line_UV=(UV-vec2(0.5,0.5));Rect_UV=Line_UV*Scale_XY;Rect_Parms.xy=Scale_XY*0.5-vec2(Radius,Radius)-vec2(Margin,Margin);Rect_Parms.z=Gradient1; \nRect_Parms.w=Gradient2;Color_UV_Info=(Line_UV+vec2(0.5,0.5))*Color_Scale_Translate.xy+Color_Scale_Translate.zw;}\nvoid Line_Vertex_B333(\nvec2 Scale_XY,\nvec2 UV,\nfloat Time,\nfloat Rate,\nvec4 Highlight_Transform,\nout vec3 Line_Vertex)\n{float angle2=(Rate*Time)*2.0*3.1416;float sinAngle2=sin(angle2);float cosAngle2=cos(angle2);vec2 xformUV=UV*Highlight_Transform.xy+Highlight_Transform.zw;Line_Vertex.x=0.0;Line_Vertex.y=cosAngle2*xformUV.x-sinAngle2*xformUV.y;Line_Vertex.z=0.0; }\nvoid PickDir_B334(\nfloat Degrees,\nvec3 DirX,\nvec3 DirY,\nout vec3 Dir)\n{float a=Degrees*3.14159/180.0;Dir=cos(a)*DirX+sin(a)*DirY;}\nvoid Move_Verts_B327(\nfloat Anisotropy,\nvec3 P,\nfloat Radius,\nout vec3 New_P,\nout vec2 New_UV,\nout float Radial_Gradient,\nout vec3 Radial_Dir)\n{vec2 UV=P.xy*2.0+0.5;vec2 center=clamp(UV,0.0,1.0);vec2 delta=UV-center;vec2 r2=2.0*vec2(Radius/Anisotropy,Radius);New_UV=center+r2*(UV-2.0*center+0.5);New_P=vec3(New_UV-0.5,P.z);Radial_Gradient=1.0-length(delta)*2.0;Radial_Dir=vec3(delta*r2,0.0);}\nvoid Pick_Radius_B336(\nfloat Radius,\nfloat Radius_Top_Left,\nfloat Radius_Top_Right,\nfloat Radius_Bottom_Left,\nfloat Radius_Bottom_Right,\nvec3 Position,\nout float Result)\n{bool whichY=Position.y>0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Edge_AA_Vertex_B328(\nvec3 Position_World,\nvec3 Position_Object,\nvec3 Normal_Object,\nvec3 Eye,\nfloat Radial_Gradient,\nvec3 Radial_Dir,\nvec3 Tangent,\nout float Gradient1,\nout float Gradient2)\n{vec3 I=(Eye-Position_World);vec3 T=(vec4(Tangent,0.0)).xyz;float g=(dot(T,I)<0.0) ? 0.0 : 1.0;if (Normal_Object.z==0.0) { \nGradient1=Position_Object.z>0.0 ? g : 1.0;Gradient2=Position_Object.z>0.0 ? 1.0 : g;} else {Gradient1=g+(1.0-g)*(Radial_Gradient);Gradient2=1.0;}}\nvoid Object_To_World_Dir_B330(\nvec3 Dir_Object,\nout vec3 Binormal_World,\nout vec3 Binormal_World_N,\nout float Binormal_Length)\n{Binormal_World=(world*vec4(Dir_Object,0.0)).xyz;Binormal_Length=length(Binormal_World);Binormal_World_N=Binormal_World/Binormal_Length;}\nvoid RelativeOrAbsoluteDetail_B341(\nfloat Nominal_Radius,\nfloat Nominal_LineWidth,\nbool Absolute_Measurements,\nfloat Height,\nout float Radius,\nout float Line_Width)\n{float scale=Absolute_Measurements ? 1.0/Height : 1.0;Radius=Nominal_Radius*scale;Line_Width=Nominal_LineWidth*scale;}\nvoid main()\n{vec3 Nrm_World_Q326;Nrm_World_Q326=normalize((world*vec4(normal,0.0)).xyz);vec3 Tangent_World_Q329;vec3 Tangent_World_N_Q329;float Tangent_Length_Q329;Tangent_World_Q329=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q329=length(Tangent_World_Q329);Tangent_World_N_Q329=Tangent_World_Q329/Tangent_Length_Q329;vec3 Binormal_World_Q330;vec3 Binormal_World_N_Q330;float Binormal_Length_Q330;Object_To_World_Dir_B330(vec3(0,1,0),Binormal_World_Q330,Binormal_World_N_Q330,Binormal_Length_Q330);float Radius_Q341;float Line_Width_Q341;RelativeOrAbsoluteDetail_B341(_Radius_,_Line_Width_,_Absolute_Sizes_,Binormal_Length_Q330,Radius_Q341,Line_Width_Q341);vec3 Dir_Q334;PickDir_B334(_Angle_,Tangent_World_N_Q329,Binormal_World_N_Q330,Dir_Q334);float Result_Q336;Pick_Radius_B336(Radius_Q341,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q336);float Anisotropy_Q331=Tangent_Length_Q329/Binormal_Length_Q330;vec4 Out_Color_Q337=vec4(Result_Q336,Line_Width_Q341,0,1);vec3 New_P_Q327;vec2 New_UV_Q327;float Radial_Gradient_Q327;vec3 Radial_Dir_Q327;Move_Verts_B327(Anisotropy_Q331,position,Result_Q336,New_P_Q327,New_UV_Q327,Radial_Gradient_Q327,Radial_Dir_Q327);vec3 Pos_World_Q314;Object_To_World_Pos_B314(New_P_Q327,Pos_World_Q314);float Gradient1_Q328;float Gradient2_Q328;\n#if SMOOTH_EDGES\nEdge_AA_Vertex_B328(Pos_World_Q314,position,normal,cameraPosition,Radial_Gradient_Q327,Radial_Dir_Q327,tangent,Gradient1_Q328,Gradient2_Q328);\n#else\nGradient1_Q328=1.0;Gradient2_Q328=1.0;\n#endif\nvec2 Rect_UV_Q357;vec4 Rect_Parms_Q357;vec2 Scale_XY_Q357;vec2 Line_UV_Q357;vec2 Color_UV_Info_Q357;Round_Rect_Vertex_B357(New_UV_Q327,Result_Q336,0.0,Anisotropy_Q331,Gradient1_Q328,Gradient2_Q328,normal,vec4(1,1,0,0),Rect_UV_Q357,Rect_Parms_Q357,Scale_XY_Q357,Line_UV_Q357,Color_UV_Info_Q357);vec3 Line_Vertex_Q333;Line_Vertex_B333(Scale_XY_Q357,Line_UV_Q357,(20.0),_Rate_,_Highlight_Transform_,Line_Vertex_Q333);float X_Q359;float Y_Q359;X_Q359=Color_UV_Info_Q357.x;Y_Q359=Color_UV_Info_Q357.y;vec4 Vec4_Q358=vec4(X_Q359,Y_Q359,Result_Q336,Line_Width_Q341);vec3 Position=Pos_World_Q314;vec3 Normal=Nrm_World_Q326;vec2 UV=Rect_UV_Q357;vec3 Tangent=Line_Vertex_Q333;vec3 Binormal=Dir_Q334;vec4 Color=Out_Color_Q337;vec4 Extra1=Rect_Parms_Q357;vec4 Extra2=Vec4_Q358;vec4 Extra3=vec4(0,0,0,0);gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vExtra1=Extra1;vExtra2=Extra2;}";class nF extends xl{constructor(){super(),this.IRIDESCENCE_ENABLE=!0,this.SMOOTH_EDGES=!0,this._needNormals=!0,this.rebuild()}}class oF extends ml{constructor(e,t){super(e,t),this.radius=.3,this.lineWidth=.003,this.absoluteSizes=!1,this._filterWidth=1,this.baseColor=new Ae(0,0,0,1),this.lineColor=new Ae(.2,.262745,.4,1),this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this._rate=0,this.highlightColor=new Ae(.239216,.435294,.827451,1),this.highlightWidth=0,this._highlightTransform=new pe(1,1,0,0),this._highlight=1,this.iridescenceIntensity=.45,this.iridescenceEdgeIntensity=1,this.iridescenceTint=new Ae(1,1,1,1),this._angle=-45,this.fadeOut=1,this._reflected=!0,this._frequency=1,this._verticalOffset=0,this.gradientColor=new Ae(.74902,.74902,.74902,1),this.topLeftGradientColor=new Ae(.00784314,.294118,.580392,1),this.topRightGradientColor=new Ae(.305882,0,1,1),this.bottomLeftGradientColor=new Ae(.133333,.258824,.992157,1),this.bottomRightGradientColor=new Ae(.176471,.176471,.619608,1),this.edgeWidth=.5,this.edgePower=1,this.edgeLineGradientBlend=.5,this.alphaMode=N_.ALPHA_DISABLE,this.backFaceCulling=!1,this._iridescentMapTexture=new Pa(oF.IRIDESCENT_MAP_TEXTURE_URL,this.getScene(),!0,!1,Pa.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new nF);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="mrdlBackplate",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Absolute_Sizes_","_Filter_Width_","_Base_Color_","_Line_Color_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Rate_","_Highlight_Color_","_Highlight_Width_","_Highlight_Transform_","_Highlight_","_Iridescence_Intensity_","_Iridescence_Edge_Intensity_","_Iridescence_Tint_","_Iridescent_Map_","_Angle_","_Reflected_","_Frequency_","_Vertical_Offset_","_Gradient_Color_","_Top_Left_","_Top_Right_","_Bottom_Left_","_Bottom_Right_","_Edge_Width_","_Edge_Power_","_Line_Gradient_Blend_","_Fade_Out_"],h=["_Iridescent_Map_"],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Base_Color_",this.baseColor),this._activeEffect.setDirectColor4("_Line_Color_",this.lineColor),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Rate_",this._rate),this._activeEffect.setDirectColor4("_Highlight_Color_",this.highlightColor),this._activeEffect.setFloat("_Highlight_Width_",this.highlightWidth),this._activeEffect.setVector4("_Highlight_Transform_",this._highlightTransform),this._activeEffect.setFloat("_Highlight_",this._highlight),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setFloat("_Iridescence_Edge_Intensity_",this.iridescenceEdgeIntensity),this._activeEffect.setDirectColor4("_Iridescence_Tint_",this.iridescenceTint),this._activeEffect.setTexture("_Iridescent_Map_",this._iridescentMapTexture),this._activeEffect.setFloat("_Angle_",this._angle),this._activeEffect.setFloat("_Reflected_",this._reflected?1:0),this._activeEffect.setFloat("_Frequency_",this._frequency),this._activeEffect.setFloat("_Vertical_Offset_",this._verticalOffset),this._activeEffect.setDirectColor4("_Gradient_Color_",this.gradientColor),this._activeEffect.setDirectColor4("_Top_Left_",this.topLeftGradientColor),this._activeEffect.setDirectColor4("_Top_Right_",this.topRightGradientColor),this._activeEffect.setDirectColor4("_Bottom_Left_",this.bottomLeftGradientColor),this._activeEffect.setDirectColor4("_Bottom_Right_",this.bottomRightGradientColor),this._activeEffect.setFloat("_Edge_Width_",this.edgeWidth),this._activeEffect.setFloat("_Edge_Power_",this.edgePower),this._activeEffect.setFloat("_Line_Gradient_Blend_",this.edgeLineGradientBlend),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new oF(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLBackplateMaterial",e}getClassName(){return"MRDLBackplateMaterial"}static Parse(e,t,i){return St.Parse((()=>new oF(e.name,t)),e,t,i)}}oF.IRIDESCENT_MAP_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-backplate-iridescence.png",Ze([rt()],oF.prototype,"radius",void 0),Ze([rt()],oF.prototype,"lineWidth",void 0),Ze([rt()],oF.prototype,"absoluteSizes",void 0),Ze([rt()],oF.prototype,"baseColor",void 0),Ze([rt()],oF.prototype,"lineColor",void 0),Ze([rt()],oF.prototype,"radiusTopLeft",void 0),Ze([rt()],oF.prototype,"radiusTopRight",void 0),Ze([rt()],oF.prototype,"radiusBottomLeft",void 0),Ze([rt()],oF.prototype,"radiusBottomRight",void 0),Ze([rt()],oF.prototype,"highlightColor",void 0),Ze([rt()],oF.prototype,"highlightWidth",void 0),Ze([rt()],oF.prototype,"iridescenceIntensity",void 0),Ze([rt()],oF.prototype,"iridescenceEdgeIntensity",void 0),Ze([rt()],oF.prototype,"iridescenceTint",void 0),Ze([rt()],oF.prototype,"fadeOut",void 0),Ze([rt()],oF.prototype,"gradientColor",void 0),Ze([rt()],oF.prototype,"topLeftGradientColor",void 0),Ze([rt()],oF.prototype,"topRightGradientColor",void 0),Ze([rt()],oF.prototype,"bottomLeftGradientColor",void 0),Ze([rt()],oF.prototype,"bottomRightGradientColor",void 0),Ze([rt()],oF.prototype,"edgeWidth",void 0),Ze([rt()],oF.prototype,"edgePower",void 0),Ze([rt()],oF.prototype,"edgeLineGradientBlend",void 0),z("BABYLON.GUI.MRDLBackplateMaterial",oF);class aF extends CN{constructor(e,t){super(e),this.onValueChangedObservable=new K,this._sliderBackplateVisible=t||!1,this._minimum=0,this._maximum=100,this._step=0,this._value=50}get mesh(){return this.node?this._sliderThumb:null}get minimum(){return this._minimum}set minimum(e){this._minimum!==e&&(this._minimum=Math.max(e,0),this._value=Math.max(Math.min(this._value,this._maximum),this._minimum))}get maximum(){return this._maximum}set maximum(e){this._maximum!==e&&(this._maximum=Math.max(e,this._minimum),this._value=Math.max(Math.min(this._value,this._maximum),this._minimum))}get step(){return this._step}set step(e){this._step!==e&&(this._step=Math.max(Math.min(e,this._maximum-this._minimum),0))}get value(){return this._value}set value(e){this._value!==e&&(this._value=Math.max(Math.min(e,this._maximum),this._minimum),this._sliderThumb&&(this._sliderThumb.position.x=this._convertToPosition(this.value)),this.onValueChangedObservable.notifyObservers(this._value))}get start(){return this.node?this._sliderBar.position.x-this._sliderBar.scaling.x/2:-.5}get end(){return this.node?this._sliderBar.position.x+this._sliderBar.scaling.x/2:.5}get sliderBarMaterial(){return this._sliderBarMaterial}get sliderThumbMaterial(){return this._sliderThumbMaterial}get sliderBackplateMaterial(){return this._sliderBackplateMaterial}get sliderBar(){return this._sliderBar}get sliderThumb(){return this._sliderThumb}get sliderBackplate(){return this._sliderBackplate}set isVisible(e){this._isVisible!==e&&(this._isVisible=e,this.node?.setEnabled(e))}_createNode(e){const t=cd(`${this.name}_sliderbackplate`,{width:1,height:1,depth:1},e);return t.isPickable=!1,t.visibility=0,t.scaling=new _e(1,.5,.8),fl.ImportMeshAsync(void 0,aF.MODEL_BASE_URL,aF.MODEL_FILENAME,e).then((e=>{e.meshes.forEach((e=>{e.isPickable=!1}));const i=e.meshes[1],s=e.meshes[1].clone(`${this.name}_sliderbar`,t),r=e.meshes[1].clone(`${this.name}_sliderthumb`,t);i.visibility=0,this._sliderBackplateVisible&&(i.visibility=1,i.name=`${this.name}_sliderbackplate`,i.scaling.x=1,i.scaling.z=.2,i.parent=t,this._sliderBackplateMaterial&&(i.material=this._sliderBackplateMaterial),this._sliderBackplate=i),s&&(s.parent=t,s.position.z=-.1,s.scaling=new _e(.8,.04,.3),this._sliderBarMaterial&&(s.material=this._sliderBarMaterial),this._sliderBar=s),r&&(r.parent=t,r.isPickable=!0,r.position.z=-.115,r.scaling=new _e(.025,.3,.6),r.position.x=this._convertToPosition(this.value),r.addBehavior(this._createBehavior()),this._sliderThumbMaterial&&(r.material=this._sliderThumbMaterial),this._sliderThumb=r),this._injectGUI3DReservedDataStore(t).control=this,t.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this}))})),this._affectMaterial(t),t}_affectMaterial(e){this._sliderBackplateMaterial=this._sliderBackplateMaterial??new oF(`${this.name}_sliderbackplate_material`,e.getScene()),this._sliderBarMaterial=this._sliderBarMaterial??new iF(`${this.name}_sliderbar_material`,e.getScene()),this._sliderThumbMaterial=this._sliderThumbMaterial??new rF(`${this.name}_sliderthumb_material`,e.getScene())}_createBehavior(){const e=new Xa({dragAxis:_e.Right()});return e.moveAttached=!1,e.onDragStartObservable.add((()=>{this._draggedPosition=this._sliderThumb.position.x})),e.onDragObservable.add((e=>{this._draggedPosition+=e.dragDistance/this.scaling.x,this.value=this._convertToValue(this._draggedPosition)})),e}_convertToPosition(e){const t=(e-this.minimum)/(this.maximum-this.minimum)*(this.end-this.start)+this.start;return Math.min(Math.max(t,this.start),this.end)}_convertToValue(e){let t=(e-this.start)/(this.end-this.start)*(this.maximum-this.minimum);return t=this.step?Math.round(t/this.step)*this.step:t,Math.max(Math.min(this.minimum+t,this._maximum),this._minimum)}dispose(){super.dispose(),this._sliderBar?.dispose(),this._sliderThumb?.dispose(),this._sliderBarMaterial?.dispose(),this._sliderThumbMaterial?.dispose(),this._sliderBackplate?.dispose(),this._sliderBackplateMaterial?.dispose()}}aF.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",aF.MODEL_FILENAME="mrtk-fluent-backplate.glb";class lF extends RN{constructor(){super(...arguments),this._radius=5}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,Ds.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh;if(!i)return;const s=this._sphericalMapping(t);switch(e.position=s,this.orientation){case IN.FACEORIGIN_ORIENTATION:i.lookAt(new _e(2*s.x,2*s.y,2*s.z));break;case IN.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new _e(-s.x,-s.y,-s.z));break;case IN.FACEFORWARD_ORIENTATION:break;case IN.FACEFORWARDREVERSED_ORIENTATION:i.rotate(Xr.Y,Math.PI,Ur.LOCAL)}}_sphericalMapping(e){const t=new _e(0,0,this._radius),i=e.y/this._radius,s=-e.x/this._radius;return me.RotationYawPitchRollToRef(s,i,0,ve.Matrix[0]),_e.TransformNormal(t,ve.Matrix[0])}}class hF extends IN{get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,Ds.SetImmediate((()=>{this._arrangeChildren()})))}constructor(e=!1){super(),this._isVertical=!1,this.margin=.1,this._isVertical=e}_arrangeChildren(){let e=0,t=0,i=0;const s=[],r=me.Invert(this.node.computeWorldMatrix(!0));for(const n of this._children){if(!n.mesh)continue;i++,n.mesh.computeWorldMatrix(!0),n.mesh.getWorldMatrix().multiplyToRef(r,ve.Matrix[0]);const o=n.mesh.getBoundingInfo().boundingBox,a=_e.TransformNormal(o.extendSize,ve.Matrix[0]);s.push(a),this._isVertical?t+=a.y:e+=a.x}let n;this._isVertical?t+=(i-1)*this.margin/2:e+=(i-1)*this.margin/2,n=this._isVertical?-t:-e;let o=0;for(const e of this._children){if(!e.mesh)continue;i--;const t=s[o++];this._isVertical?(e.position.y=n+t.y,e.position.x=0,n+=2*t.y):(e.position.x=n+t.x,e.position.y=0,n+=2*t.x),n+=i>0?this.margin:0}}}class cF extends GN{constructor(e,t){super(t,e),this._currentMesh=e,this.pointerEnterAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1.1)},this.pointerOutAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/1.1)},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_getTypeName(){return"TouchMeshButton3D"}_createNode(){return this._currentMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this})),this._currentMesh}_affectMaterial(e){}}Bi.ShadersStore.mrdlBackglowPixelShader="uniform vec3 cameraPosition;varying vec3 vNormal;varying vec2 vUV;uniform float _Bevel_Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Tuning_Motion_;uniform float _Motion_;uniform float _Max_Intensity_;uniform float _Intensity_Fade_In_Exponent_;uniform float _Outer_Fuzz_Start_;uniform float _Outer_Fuzz_End_;uniform vec4 _Color_;uniform vec4 _Inner_Color_;uniform float _Blend_Exponent_;uniform float _Falloff_;uniform float _Bias_;float BiasFunc(float b,float v) {return pow(v,log(clamp(b,0.001,0.999))/log(0.5));}\nvoid Fuzzy_Round_Rect_B33(\nfloat Size_X,\nfloat Size_Y,\nfloat Radius_X,\nfloat Radius_Y,\nfloat Line_Width,\nvec2 UV,\nfloat Outer_Fuzz,\nfloat Max_Outer_Fuzz,\nout float Rect_Distance,\nout float Inner_Distance)\n{vec2 halfSize=vec2(Size_X,Size_Y)*0.5;vec2 r=max(min(vec2(Radius_X,Radius_Y),halfSize),vec2(0.001,0.001));float radius=min(r.x,r.y)-Max_Outer_Fuzz;vec2 v=abs(UV);vec2 nearestp=min(v,halfSize-r);float d=distance(nearestp,v);Inner_Distance=clamp(1.0-(radius-d)/Line_Width,0.0,1.0);Rect_Distance=clamp(1.0-(d-radius)/Outer_Fuzz,0.0,1.0)*Inner_Distance;}\nvoid main()\n{float X_Q42;float Y_Q42;X_Q42=vNormal.x;Y_Q42=vNormal.y;float MaxAB_Q24=max(_Tuning_Motion_,_Motion_);float Sqrt_F_Q27=sqrt(MaxAB_Q24);float Power_Q43=pow(MaxAB_Q24,_Intensity_Fade_In_Exponent_);float Value_At_T_Q26=mix(_Outer_Fuzz_Start_,_Outer_Fuzz_End_,Sqrt_F_Q27);float Product_Q23=_Max_Intensity_*Power_Q43;float Rect_Distance_Q33;float Inner_Distance_Q33;Fuzzy_Round_Rect_B33(X_Q42,Y_Q42,_Bevel_Radius_,_Bevel_Radius_,_Line_Width_,vUV,Value_At_T_Q26,_Outer_Fuzz_Start_,Rect_Distance_Q33,Inner_Distance_Q33);float Power_Q44=pow(Inner_Distance_Q33,_Blend_Exponent_);float Result_Q45=pow(BiasFunc(_Bias_,Rect_Distance_Q33),_Falloff_);vec4 Color_At_T_Q25=mix(_Inner_Color_,_Color_,Power_Q44);float Product_Q22=Result_Q45*Product_Q23;vec4 Result_Q28=Product_Q22*Color_At_T_Q25;vec4 Out_Color=Result_Q28;float Clip_Threshold=0.0;gl_FragColor=Out_Color;}";Bi.ShadersStore.mrdlBackglowVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;uniform float _Bevel_Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Tuning_Motion_;uniform float _Motion_;uniform float _Max_Intensity_;uniform float _Intensity_Fade_In_Exponent_;uniform float _Outer_Fuzz_Start_;uniform float _Outer_Fuzz_End_;uniform vec4 _Color_;uniform vec4 _Inner_Color_;uniform float _Blend_Exponent_;uniform float _Falloff_;uniform float _Bias_;varying vec3 vNormal;varying vec2 vUV;void main()\n{vec3 Dir_World_Q41=(world*vec4(tangent,0.0)).xyz;vec3 Dir_World_Q40=(world*vec4((cross(normal,tangent)),0.0)).xyz;float MaxAB_Q24=max(_Tuning_Motion_,_Motion_);float Length_Q16=length(Dir_World_Q41);float Length_Q17=length(Dir_World_Q40);bool Greater_Than_Q37=MaxAB_Q24>0.0;vec3 Sizes_Q35;vec2 XY_Q35;Sizes_Q35=(_Absolute_Sizes_ ? vec3(Length_Q16,Length_Q17,0) : vec3(Length_Q16/Length_Q17,1,0));XY_Q35=(uv-vec2(0.5,0.5))*Sizes_Q35.xy;vec3 Result_Q38=Greater_Than_Q37 ? position : vec3(0,0,0);vec3 Pos_World_Q39=(world*vec4(Result_Q38,1.0)).xyz;vec3 Position=Pos_World_Q39;vec3 Normal=Sizes_Q35;vec2 UV=XY_Q35;vec3 Tangent=vec3(0,0,0);vec3 Binormal=vec3(0,0,0);vec4 Color=vec4(1,1,1,1);gl_Position=viewProjection*vec4(Position,1);vNormal=Normal;vUV=UV;}";class uF extends xl{constructor(){super(),this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class dF extends ml{constructor(e,t){super(e,t),this.bevelRadius=.16,this.lineWidth=.16,this.absoluteSizes=!1,this.tuningMotion=0,this.motion=1,this.maxIntensity=.7,this.intensityFadeInExponent=2,this.outerFuzzStart=.04,this.outerFuzzEnd=.04,this.color=new Ae(.682353,.698039,1,1),this.innerColor=new Ae(.356863,.392157,.796078,1),this.blendExponent=1.5,this.falloff=2,this.bias=.5,this.alphaMode=N_.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new uF);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="mrdlBackglow",a=s.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Bevel_Radius_","_Line_Width_","_Absolute_Sizes_","_Tuning_Motion_","_Motion_","_Max_Intensity_","_Intensity_Fade_In_Exponent_","_Outer_Fuzz_Start_","_Outer_Fuzz_End_","_Color_","_Inner_Color_","_Blend_Exponent_","_Falloff_","_Bias_"],h=[],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setFloat("_Bevel_Radius_",this.bevelRadius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Tuning_Motion_",this.tuningMotion),this._activeEffect.setFloat("_Motion_",this.motion),this._activeEffect.setFloat("_Max_Intensity_",this.maxIntensity),this._activeEffect.setFloat("_Intensity_Fade_In_Exponent_",this.intensityFadeInExponent),this._activeEffect.setFloat("_Outer_Fuzz_Start_",this.outerFuzzStart),this._activeEffect.setFloat("_Outer_Fuzz_End_",this.outerFuzzEnd),this._activeEffect.setDirectColor4("_Color_",this.color),this._activeEffect.setDirectColor4("_Inner_Color_",this.innerColor),this._activeEffect.setFloat("_Blend_Exponent_",this.blendExponent),this._activeEffect.setFloat("_Falloff_",this.falloff),this._activeEffect.setFloat("_Bias_",this.bias),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new dF(e,this.getScene())),this)}serialize(){const e=St.Serialize(this);return e.customType="BABYLON.MRDLBackglowMaterial",e}getClassName(){return"MRDLBackglowMaterial"}static Parse(e,t,i){return St.Parse((()=>new dF(e.name,t)),e,t,i)}}Ze([rt()],dF.prototype,"bevelRadius",void 0),Ze([rt()],dF.prototype,"lineWidth",void 0),Ze([rt()],dF.prototype,"absoluteSizes",void 0),Ze([rt()],dF.prototype,"tuningMotion",void 0),Ze([rt()],dF.prototype,"motion",void 0),Ze([rt()],dF.prototype,"maxIntensity",void 0),Ze([rt()],dF.prototype,"intensityFadeInExponent",void 0),Ze([rt()],dF.prototype,"outerFuzzStart",void 0),Ze([rt()],dF.prototype,"outerFuzzEnd",void 0),Ze([rt()],dF.prototype,"color",void 0),Ze([rt()],dF.prototype,"innerColor",void 0),Ze([rt()],dF.prototype,"blendExponent",void 0),Ze([rt()],dF.prototype,"falloff",void 0),Ze([rt()],dF.prototype,"bias",void 0),z("BABYLON.GUI.MRDLBackglowMaterial",dF);Bi.ShadersStore.mrdlFrontplatePixelShader="uniform vec3 cameraPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Relative_To_Height_;uniform float _Filter_Width_;uniform vec4 _Edge_Color_;uniform float _Fade_Out_;uniform bool _Smooth_Edges_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform float _Blob_Pulse_Max_Size_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform float _Gaze_Intensity_;uniform float _Gaze_Focus_;uniform sampler2D _Blob_Texture_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform bool _Use_Global_Left_Index_;uniform bool _Use_Global_Right_Index_;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;void Scale_Color_B54(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=Scalar*Color;}\nvoid Scale_RGB_B50(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Proximity_Fragment_B51(\nfloat Proximity_Max_Intensity,\nfloat Proximity_Near_Radius,\nvec4 Deltas,\nfloat Show_Selection,\nfloat Distance_Fade1,\nfloat Distance_Fade2,\nfloat Strength,\nout float Proximity)\n{float proximity1=(1.0-clamp(length(Deltas.xy)/Proximity_Near_Radius,0.0,1.0))*Distance_Fade1;float proximity2=(1.0-clamp(length(Deltas.zw)/Proximity_Near_Radius,0.0,1.0))*Distance_Fade2;Proximity=Strength*(Proximity_Max_Intensity*max(proximity1,proximity2) *(1.0-Show_Selection)+Show_Selection);}\nvoid Blob_Fragment_B56(\nvec2 UV,\nvec3 Blob_Info,\nsampler2D Blob_Texture,\nout vec4 Blob_Color)\n{float k=dot(UV,UV);Blob_Color=Blob_Info.y*texture(Blob_Texture,vec2(vec2(sqrt(k),Blob_Info.x).x,1.0-vec2(sqrt(k),Blob_Info.x).y))*(1.0-clamp(k,0.0,1.0));}\nvoid Round_Rect_Fragment_B61(\nfloat Radius,\nvec4 Line_Color,\nfloat Filter_Width,\nfloat Line_Visibility,\nvec4 Fill_Color,\nbool Smooth_Edges,\nvec4 Rect_Parms,\nout float Inside_Rect)\n{float d=length(max(abs(Rect_Parms.zw)-Rect_Parms.xy,0.0));float dx=max(fwidth(d)*Filter_Width,0.00001);Inside_Rect=Smooth_Edges ? clamp((Radius-d)/dx,0.0,1.0) : 1.0-step(Radius,d);}\nvoid main()\n{float Is_Quad_Q53;Is_Quad_Q53=vNormal.z;vec4 Blob_Color_Q56;Blob_Fragment_B56(vUV,vTangent,_Blob_Texture_,Blob_Color_Q56);float X_Q52;float Y_Q52;float Z_Q52;float W_Q52;X_Q52=vExtra3.x;Y_Q52=vExtra3.y;Z_Q52=vExtra3.z;W_Q52=vExtra3.w;float Proximity_Q51;Proximity_Fragment_B51(_Proximity_Max_Intensity_,_Proximity_Near_Radius_,vExtra2,X_Q52,Y_Q52,Z_Q52,1.0,Proximity_Q51);float Inside_Rect_Q61;Round_Rect_Fragment_B61(W_Q52,vec4(1,1,1,1),_Filter_Width_,1.0,vec4(0,0,0,0),_Smooth_Edges_,vExtra1,Inside_Rect_Q61);vec4 Result_Q50;Scale_RGB_B50(_Edge_Color_,Proximity_Q51,Result_Q50);vec4 Result_Q47=Inside_Rect_Q61*Blob_Color_Q56;vec4 Color_At_T_Q48=mix(Result_Q50,Result_Q47,Is_Quad_Q53);vec4 Result_Q54;Scale_Color_B54(Color_At_T_Q48,_Fade_Out_,Result_Q54);vec4 Out_Color=Result_Q54;float Clip_Threshold=0.001;bool To_sRGB=false;gl_FragColor=Out_Color;}";Bi.ShadersStore.mrdlFrontplateVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Relative_To_Height_;uniform float _Filter_Width_;uniform vec4 _Edge_Color_;uniform float _Fade_Out_;uniform bool _Smooth_Edges_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform float _Blob_Pulse_Max_Size_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform float _Gaze_Intensity_;uniform float _Gaze_Focus_;uniform sampler2D _Blob_Texture_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform bool _Use_Global_Left_Index_;uniform bool _Use_Global_Right_Index_;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;void Blob_Vertex_B40(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nvec3 Blob_Position,\nfloat Intensity,\nfloat Blob_Near_Size,\nfloat Blob_Far_Size,\nfloat Blob_Near_Distance,\nfloat Blob_Far_Distance,\nvec4 Vx_Color,\nvec2 UV,\nvec3 Face_Center,\nvec2 Face_Size,\nvec2 In_UV,\nfloat Blob_Fade_Length,\nfloat Selection_Fade,\nfloat Selection_Fade_Size,\nfloat Inner_Fade,\nfloat Blob_Pulse,\nfloat Blob_Fade,\nfloat Blob_Enabled,\nfloat DistanceOffset,\nout vec3 Out_Position,\nout vec2 Out_UV,\nout vec3 Blob_Info,\nout vec2 Blob_Relative_UV)\n{float blobSize,fadeIn;vec3 Hit_Position;Blob_Info=vec3(0.0,0.0,0.0);float Hit_Distance=dot(Blob_Position-Face_Center,Normal)+DistanceOffset*Blob_Far_Distance;Hit_Position=Blob_Position-Hit_Distance*Normal;float absD=abs(Hit_Distance);float lerpVal=clamp((absD-Blob_Near_Distance)/(Blob_Far_Distance-Blob_Near_Distance),0.0,1.0);fadeIn=1.0-clamp((absD-Blob_Far_Distance)/Blob_Fade_Length,0.0,1.0);float innerFade=1.0-clamp(-Hit_Distance/Inner_Fade,0.0,1.0);float farClip=clamp(1.0-step(Blob_Far_Distance+Blob_Fade_Length,absD),0.0,1.0);float size=mix(Blob_Near_Size,Blob_Far_Size,lerpVal)*farClip;blobSize=mix(size,Selection_Fade_Size,Selection_Fade)*innerFade*Blob_Enabled;Blob_Info.x=lerpVal*0.5+0.5;Blob_Info.y=fadeIn*Intensity*(1.0-Selection_Fade)*Blob_Fade;Blob_Info.x*=(1.0-Blob_Pulse);vec3 delta=Hit_Position-Face_Center;vec2 blobCenterXY=vec2(dot(delta,Tangent),dot(delta,Bitangent));vec2 quadUVin=2.0*UV-1.0; \nvec2 blobXY=blobCenterXY+quadUVin*blobSize;vec2 blobClipped=clamp(blobXY,-Face_Size*0.5,Face_Size*0.5);vec2 blobUV=(blobClipped-blobCenterXY)/max(blobSize,0.0001)*2.0;vec3 blobCorner=Face_Center+blobClipped.x*Tangent+blobClipped.y*Bitangent;Out_Position=mix(Position,blobCorner,Vx_Color.rrr);Out_UV=mix(In_UV,blobUV,Vx_Color.rr);Blob_Relative_UV=blobClipped/Face_Size.y;}\nvoid Round_Rect_Vertex_B36(\nvec2 UV,\nvec3 Tangent,\nvec3 Binormal,\nfloat Radius,\nfloat Anisotropy,\nvec2 Blob_Center_UV,\nout vec2 Rect_UV,\nout vec2 Scale_XY,\nout vec4 Rect_Parms)\n{Scale_XY=vec2(Anisotropy,1.0);Rect_UV=(UV-vec2(0.5,0.5))*Scale_XY;Rect_Parms.xy=Scale_XY*0.5-vec2(Radius,Radius);Rect_Parms.zw=Blob_Center_UV;}\nvec2 ProjectProximity(\nvec3 blobPosition,\nvec3 position,\nvec3 center,\nvec3 dir,\nvec3 xdir,\nvec3 ydir,\nout float vdistance\n)\n{vec3 delta=blobPosition-position;vec2 xy=vec2(dot(delta,xdir),dot(delta,ydir));vdistance=abs(dot(delta,dir));return xy;}\nvoid Proximity_Vertex_B33(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec3 Position,\nfloat Proximity_Far_Distance,\nfloat Relative_Scale,\nfloat Proximity_Anisotropy,\nvec3 Normal,\nvec3 Tangent,\nvec3 Binormal,\nout vec4 Extra,\nout float Distance_To_Face,\nout float Distance_Fade1,\nout float Distance_Fade2)\n{float distz1,distz2;Extra.xy=ProjectProximity(Blob_Position,Position,Face_Center,Normal,Tangent*Proximity_Anisotropy,Binormal,distz1)/Relative_Scale;Extra.zw=ProjectProximity(Blob_Position_2,Position,Face_Center,Normal,Tangent*Proximity_Anisotropy,Binormal,distz2)/Relative_Scale;Distance_To_Face=dot(Normal,Position-Face_Center);Distance_Fade1=1.0-clamp(distz1/Proximity_Far_Distance,0.0,1.0);Distance_Fade2=1.0-clamp(distz2/Proximity_Far_Distance,0.0,1.0);}\nvoid Object_To_World_Pos_B12(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Choose_Blob_B27(\nvec4 Vx_Color,\nvec3 Position1,\nvec3 Position2,\nbool Blob_Enable_1,\nbool Blob_Enable_2,\nfloat Near_Size_1,\nfloat Near_Size_2,\nfloat Blob_Inner_Fade_1,\nfloat Blob_Inner_Fade_2,\nfloat Blob_Pulse_1,\nfloat Blob_Pulse_2,\nfloat Blob_Fade_1,\nfloat Blob_Fade_2,\nout vec3 Position,\nout float Near_Size,\nout float Inner_Fade,\nout float Blob_Enable,\nout float Fade,\nout float Pulse)\n{Position=Position1*(1.0-Vx_Color.g)+Vx_Color.g*Position2;float b1=Blob_Enable_1 ? 1.0 : 0.0;float b2=Blob_Enable_2 ? 1.0 : 0.0;Blob_Enable=b1+(b2-b1)*Vx_Color.g;Pulse=Blob_Pulse_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Pulse_2;Fade=Blob_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Fade_2;Near_Size=Near_Size_1*(1.0-Vx_Color.g)+Vx_Color.g*Near_Size_2;Inner_Fade=Blob_Inner_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Inner_Fade_2;}\nvoid Move_Verts_B32(\nvec2 UV,\nfloat Radius,\nfloat Anisotropy,\nfloat Line_Width,\nfloat Visible,\nout vec3 New_P,\nout vec2 New_UV)\n{vec2 xy=2.0*UV-vec2(0.5,0.5);vec2 center=clamp(xy,0.0,1.0);vec2 delta=2.0*(xy-center);float deltaLength=length(delta);vec2 aniso=vec2(1.0/Anisotropy,1.0);center=(center-vec2(0.5,0.5))*(1.0-2.0*Radius*aniso);New_UV=vec2((2.0-2.0*deltaLength)*Visible,0.0);float deltaRadius= (Radius-Line_Width*New_UV.x);New_P.xy=(center+deltaRadius/deltaLength *aniso*delta);New_P.z=0.0;}\nvoid Object_To_World_Dir_B14(\nvec3 Dir_Object,\nout vec3 Binormal_World)\n{Binormal_World=(world*vec4(Dir_Object,0.0)).xyz;}\nvoid Proximity_Visibility_B55(\nfloat Selection,\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Proximity_Far_Distance,\nfloat Proximity_Radius,\nvec3 Face_Center,\nvec3 Normal,\nvec2 Face_Size,\nfloat Gaze,\nout float Width)\n{float boxMaxSize=length(Face_Size)*0.5;float d1=dot(Proximity_Center-Face_Center,Normal);vec3 blob1=Proximity_Center-d1*Normal;float d2=dot(Proximity_Center_2-Face_Center,Normal);vec3 blob2=Proximity_Center_2-d2*Normal;vec3 delta1=blob1-Face_Center;vec3 delta2=blob2-Face_Center;float dist1=dot(delta1,delta1);float dist2=dot(delta2,delta2);float nearestProxDist=sqrt(min(dist1,dist2));Width=(1.0-step(boxMaxSize+Proximity_Radius,nearestProxDist))*(1.0-step(Proximity_Far_Distance,min(d1,d2))*(1.0-step(0.0001,Selection)));Width=max(Gaze,Width);}\nvec2 ramp2(vec2 start,vec2 end,vec2 x)\n{return clamp((x-start)/(end-start),vec2(0.0,0.0),vec2(1.0,1.0));}\nfloat computeSelection(\nvec3 blobPosition,\nvec3 normal,\nvec3 tangent,\nvec3 bitangent,\nvec3 faceCenter,\nvec2 faceSize,\nfloat selectionFuzz,\nfloat farDistance,\nfloat fadeLength\n)\n{vec3 delta=blobPosition-faceCenter;float absD=abs(dot(delta,normal));float fadeIn=1.0-clamp((absD-farDistance)/fadeLength,0.0,1.0);vec2 blobCenterXY=vec2(dot(delta,tangent),dot(delta,bitangent));vec2 innerFace=faceSize*(1.0-selectionFuzz)*0.5;vec2 selectPulse=ramp2(-faceSize*0.5,-innerFace,blobCenterXY)-ramp2(innerFace,faceSize*0.5,blobCenterXY);return selectPulse.x*selectPulse.y*fadeIn;}\nvoid Selection_Vertex_B31(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec2 Face_Size,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Selection_Fuzz,\nfloat Selected,\nfloat Far_Distance,\nfloat Fade_Length,\nvec3 Active_Face_Dir,\nout float Show_Selection)\n{float select1=computeSelection(Blob_Position,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float select2=computeSelection(Blob_Position_2,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);Show_Selection=mix(max(select1,select2),1.0,Selected);}\nvoid main()\n{vec3 Vec3_Q29=vec3(vec2(0,0).x,vec2(0,0).y,color.r);vec3 Nrm_World_Q24;Nrm_World_Q24=normalize((world*vec4(normal,0.0)).xyz);vec3 Face_Center_Q30;Face_Center_Q30=(world*vec4(vec3(0,0,0),1.0)).xyz;vec3 Tangent_World_Q13;Tangent_World_Q13=(world*vec4(tangent,0.0)).xyz;vec3 Result_Q42;Result_Q42=_Use_Global_Left_Index_ ? Global_Left_Index_Tip_Position.xyz : _Blob_Position_;vec3 Result_Q43;Result_Q43=_Use_Global_Right_Index_ ? Global_Right_Index_Tip_Position.xyz : _Blob_Position_2_;float Value_At_T_Q58=mix(_Blob_Near_Size_,_Blob_Pulse_Max_Size_,_Blob_Pulse_);float Value_At_T_Q59=mix(_Blob_Near_Size_2_,_Blob_Pulse_Max_Size_,_Blob_Pulse_2_);vec3 Cross_Q70=cross(normal,tangent);float Product_Q45=_Gaze_Intensity_*_Gaze_Focus_;float Step_Q46=step(0.0001,Product_Q45);vec3 Tangent_World_N_Q15=normalize(Tangent_World_Q13);vec3 Position_Q27;float Near_Size_Q27;float Inner_Fade_Q27;float Blob_Enable_Q27;float Fade_Q27;float Pulse_Q27;Choose_Blob_B27(color,Result_Q42,Result_Q43,_Blob_Enable_,_Blob_Enable_2_,Value_At_T_Q58,Value_At_T_Q59,_Blob_Inner_Fade_,_Blob_Inner_Fade_2_,_Blob_Pulse_,_Blob_Pulse_2_,_Blob_Fade_,_Blob_Fade_2_,Position_Q27,Near_Size_Q27,Inner_Fade_Q27,Blob_Enable_Q27,Fade_Q27,Pulse_Q27);vec3 Binormal_World_Q14;Object_To_World_Dir_B14(Cross_Q70,Binormal_World_Q14);float Anisotropy_Q21=length(Tangent_World_Q13)/length(Binormal_World_Q14);vec3 Binormal_World_N_Q16=normalize(Binormal_World_Q14);vec2 Face_Size_Q35;float ScaleY_Q35;Face_Size_Q35=vec2(length(Tangent_World_Q13),length(Binormal_World_Q14));ScaleY_Q35=Face_Size_Q35.y;float Out_Radius_Q38;float Out_Line_Width_Q38;Out_Radius_Q38=_Relative_To_Height_ ? _Radius_ : _Radius_/ScaleY_Q35;Out_Line_Width_Q38=_Relative_To_Height_ ? _Line_Width_ : _Line_Width_/ScaleY_Q35;float Show_Selection_Q31;Selection_Vertex_B31(Result_Q42,Result_Q43,Face_Center_Q30,Face_Size_Q35,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,_Selection_Fuzz_,_Selected_,_Selected_Distance_,_Selected_Fade_Length_,vec3(0,0,-1),Show_Selection_Q31);float MaxAB_Q41=max(Show_Selection_Q31,Product_Q45);float Width_Q55;Proximity_Visibility_B55(Show_Selection_Q31,Result_Q42,Result_Q43,_Proximity_Far_Distance_,_Proximity_Near_Radius_,Face_Center_Q30,Nrm_World_Q24,Face_Size_Q35,Step_Q46,Width_Q55);vec3 New_P_Q32;vec2 New_UV_Q32;Move_Verts_B32(uv,Out_Radius_Q38,Anisotropy_Q21,Out_Line_Width_Q38,Width_Q55,New_P_Q32,New_UV_Q32);vec3 Pos_World_Q12;Object_To_World_Pos_B12(New_P_Q32,Pos_World_Q12);vec3 Out_Position_Q40;vec2 Out_UV_Q40;vec3 Blob_Info_Q40;vec2 Blob_Relative_UV_Q40;Blob_Vertex_B40(Pos_World_Q12,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,Position_Q27,_Blob_Intensity_,Near_Size_Q27,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,color,uv,Face_Center_Q30,Face_Size_Q35,New_UV_Q32,_Blob_Fade_Length_,_Selection_Fade_,_Selection_Fade_Size_,Inner_Fade_Q27,Pulse_Q27,Fade_Q27,Blob_Enable_Q27,0.0,Out_Position_Q40,Out_UV_Q40,Blob_Info_Q40,Blob_Relative_UV_Q40);vec2 Rect_UV_Q36;vec2 Scale_XY_Q36;vec4 Rect_Parms_Q36;Round_Rect_Vertex_B36(New_UV_Q32,Tangent_World_Q13,Binormal_World_Q14,Out_Radius_Q38,Anisotropy_Q21,Blob_Relative_UV_Q40,Rect_UV_Q36,Scale_XY_Q36,Rect_Parms_Q36);vec4 Extra_Q33;float Distance_To_Face_Q33;float Distance_Fade1_Q33;float Distance_Fade2_Q33;Proximity_Vertex_B33(Result_Q42,Result_Q43,Face_Center_Q30,Pos_World_Q12,_Proximity_Far_Distance_,1.0,_Proximity_Anisotropy_,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,Extra_Q33,Distance_To_Face_Q33,Distance_Fade1_Q33,Distance_Fade2_Q33);vec4 Vec4_Q37=vec4(MaxAB_Q41,Distance_Fade1_Q33,Distance_Fade2_Q33,Out_Radius_Q38);vec3 Position=Out_Position_Q40;vec3 Normal=Vec3_Q29;vec2 UV=Out_UV_Q40;vec3 Tangent=Blob_Info_Q40;vec3 Binormal=vec3(0,0,0);vec4 Color=vec4(1,1,1,1);vec4 Extra1=Rect_Parms_Q36;vec4 Extra2=Extra_Q33;vec4 Extra3=Vec4_Q37;gl_Position=viewProjection*vec4(Position,1);vNormal=Normal;vUV=UV;vTangent=Tangent;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class _F extends xl{constructor(){super(),this.SMOOTH_EDGES=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class pF extends ml{constructor(e,t){super(e,t),this.radius=.12,this.lineWidth=.01,this.relativeToHeight=!1,this._filterWidth=1,this.edgeColor=new Ae(.53,.53,.53,1),this.blobEnable=!0,this.blobPosition=new _e(100,100,100),this.blobIntensity=.5,this.blobNearSize=.032,this.blobFarSize=.048,this.blobNearDistance=.008,this.blobFarDistance=.064,this.blobFadeLength=.04,this.blobInnerFade=.01,this.blobPulse=0,this.blobFade=1,this.blobPulseMaxSize=.05,this.blobEnable2=!0,this.blobPosition2=new _e(10,10.1,-.6),this.blobNearSize2=.008,this.blobInnerFade2=.1,this.blobPulse2=0,this.blobFade2=1,this.gazeIntensity=.8,this.gazeFocus=0,this.selectionFuzz=.5,this.selected=1,this.selectionFade=.2,this.selectionFadeSize=0,this.selectedDistance=.08,this.selectedFadeLength=.08,this.proximityMaxIntensity=.45,this.proximityFarDistance=.16,this.proximityNearRadius=.016,this.proximityAnisotropy=1,this.useGlobalLeftIndex=!0,this.useGlobalRightIndex=!0,this.fadeOut=1,this.alphaMode=N_.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1,this._blobTexture=new Pa(pF.BLOB_TEXTURE_URL,t,!0,!1,Pa.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new _F);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="mrdlFrontplate",a=s.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Relative_To_Height_","_Filter_Width_","_Edge_Color_","_Fade_Out_","_Smooth_Edges_","_Blob_Enable_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Inner_Fade_","_Blob_Pulse_","_Blob_Fade_","_Blob_Pulse_Max_Size_","_Blob_Enable_2_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Inner_Fade_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Gaze_Intensity_","_Gaze_Focus_","_Blob_Texture_","_Selection_Fuzz_","_Selected_","_Selection_Fade_","_Selection_Fade_Size_","_Selected_Distance_","_Selected_Fade_Length_","_Proximity_Max_Intensity_","_Proximity_Far_Distance_","_Proximity_Near_Radius_","_Proximity_Anisotropy_","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","_Use_Global_Left_Index_","_Use_Global_Right_Index_"],h=[],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Relative_To_Height_",this.relativeToHeight?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Edge_Color_",this.edgeColor),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._activeEffect.setFloat("_Blob_Enable_",this.blobEnable?1:0),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Inner_Fade_",this.blobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setFloat("_Blob_Pulse_Max_Size_",this.blobPulseMaxSize),this._activeEffect.setFloat("_Blob_Enable_2_",this.blobEnable2?1:0),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Inner_Fade_2_",this.blobInnerFade2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setFloat("_Gaze_Intensity_",this.gazeIntensity),this._activeEffect.setFloat("_Gaze_Focus_",this.gazeFocus),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Selection_Fuzz_",this.selectionFuzz),this._activeEffect.setFloat("_Selected_",this.selected),this._activeEffect.setFloat("_Selection_Fade_",this.selectionFade),this._activeEffect.setFloat("_Selection_Fade_Size_",this.selectionFadeSize),this._activeEffect.setFloat("_Selected_Distance_",this.selectedDistance),this._activeEffect.setFloat("_Selected_Fade_Length_",this.selectedFadeLength),this._activeEffect.setFloat("_Proximity_Max_Intensity_",this.proximityMaxIntensity),this._activeEffect.setFloat("_Proximity_Far_Distance_",this.proximityFarDistance),this._activeEffect.setFloat("_Proximity_Near_Radius_",this.proximityNearRadius),this._activeEffect.setFloat("_Proximity_Anisotropy_",this.proximityAnisotropy),this._activeEffect.setFloat("_Use_Global_Left_Index_",this.useGlobalLeftIndex?1:0),this._activeEffect.setFloat("_Use_Global_Right_Index_",this.useGlobalRightIndex?1:0),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new pF(e,this.getScene())),this)}serialize(){const e=St.Serialize(this);return e.customType="BABYLON.MRDLFrontplateMaterial",e}getClassName(){return"MRDLFrontplateMaterial"}static Parse(e,t,i){return St.Parse((()=>new pF(e.name,t)),e,t,i)}}pF.BLOB_TEXTURE_URL="",Ze([rt()],pF.prototype,"radius",void 0),Ze([rt()],pF.prototype,"lineWidth",void 0),Ze([rt()],pF.prototype,"relativeToHeight",void 0),Ze([rt()],pF.prototype,"edgeColor",void 0),Ze([rt()],pF.prototype,"blobEnable",void 0),Ze([rt()],pF.prototype,"blobPosition",void 0),Ze([rt()],pF.prototype,"blobIntensity",void 0),Ze([rt()],pF.prototype,"blobNearSize",void 0),Ze([rt()],pF.prototype,"blobFarSize",void 0),Ze([rt()],pF.prototype,"blobNearDistance",void 0),Ze([rt()],pF.prototype,"blobFarDistance",void 0),Ze([rt()],pF.prototype,"blobFadeLength",void 0),Ze([rt()],pF.prototype,"blobInnerFade",void 0),Ze([rt()],pF.prototype,"blobPulse",void 0),Ze([rt()],pF.prototype,"blobFade",void 0),Ze([rt()],pF.prototype,"blobPulseMaxSize",void 0),Ze([rt()],pF.prototype,"blobEnable2",void 0),Ze([rt()],pF.prototype,"blobPosition2",void 0),Ze([rt()],pF.prototype,"blobNearSize2",void 0),Ze([rt()],pF.prototype,"blobInnerFade2",void 0),Ze([rt()],pF.prototype,"blobPulse2",void 0),Ze([rt()],pF.prototype,"blobFade2",void 0),Ze([rt()],pF.prototype,"gazeIntensity",void 0),Ze([rt()],pF.prototype,"gazeFocus",void 0),Ze([rt()],pF.prototype,"selectionFuzz",void 0),Ze([rt()],pF.prototype,"selected",void 0),Ze([rt()],pF.prototype,"selectionFade",void 0),Ze([rt()],pF.prototype,"selectionFadeSize",void 0),Ze([rt()],pF.prototype,"selectedDistance",void 0),Ze([rt()],pF.prototype,"selectedFadeLength",void 0),Ze([rt()],pF.prototype,"proximityMaxIntensity",void 0),Ze([rt()],pF.prototype,"proximityFarDistance",void 0),Ze([rt()],pF.prototype,"proximityNearRadius",void 0),Ze([rt()],pF.prototype,"proximityAnisotropy",void 0),Ze([rt()],pF.prototype,"useGlobalLeftIndex",void 0),Ze([rt()],pF.prototype,"useGlobalRightIndex",void 0),z("BABYLON.GUI.MRDLFrontplateMaterial",pF);Bi.ShadersStore.mrdlInnerquadPixelShader="uniform vec3 cameraPosition;varying vec2 vUV;varying vec3 vTangent;uniform vec4 _Color_;uniform float _Radius_;uniform bool _Fixed_Radius_;uniform float _Filter_Width_;uniform float _Glow_Fraction_;uniform float _Glow_Max_;uniform float _Glow_Falloff_;float FilterStep_Bid194(float edge,float x,float filterWidth)\n{float dx=max(1.0E-5,fwidth(x)*filterWidth);return max((x+dx*0.5-max(edge,x-dx*0.5))/dx,0.0);}\nvoid Round_Rect_B194(\nfloat Size_X,\nfloat Size_Y,\nfloat Radius,\nvec4 Rect_Color,\nfloat Filter_Width,\nvec2 UV,\nfloat Glow_Fraction,\nfloat Glow_Max,\nfloat Glow_Falloff,\nout vec4 Color)\n{vec2 halfSize=vec2(Size_X,Size_Y)*0.5;vec2 r=max(min(vec2(Radius,Radius),halfSize),vec2(0.01,0.01));vec2 v=abs(UV);vec2 nearestp=min(v,halfSize-r);vec2 delta=(v-nearestp)/max(vec2(0.01,0.01),r);float Distance=length(delta);float insideRect=1.0-FilterStep_Bid194(1.0-Glow_Fraction,Distance,Filter_Width);float glow=clamp((1.0-Distance)/Glow_Fraction,0.0,1.0);glow=pow(glow,Glow_Falloff);Color=Rect_Color*max(insideRect,glow*Glow_Max);}\nvoid main()\n{float X_Q192;float Y_Q192;float Z_Q192;X_Q192=vTangent.x;Y_Q192=vTangent.y;Z_Q192=vTangent.z;vec4 Color_Q194;Round_Rect_B194(X_Q192,1.0,Y_Q192,_Color_,_Filter_Width_,vUV,_Glow_Fraction_,_Glow_Max_,_Glow_Falloff_,Color_Q194);vec4 Out_Color=Color_Q194;float Clip_Threshold=0.0;gl_FragColor=Out_Color;}\n";Bi.ShadersStore.mrdlInnerquadVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform vec4 _Color_;uniform float _Radius_;uniform bool _Fixed_Radius_;uniform float _Filter_Width_;uniform float _Glow_Fraction_;uniform float _Glow_Max_;uniform float _Glow_Falloff_;varying vec2 vUV;varying vec3 vTangent;void main()\n{vec3 Pos_World_Q189;Pos_World_Q189=(world*vec4(position,1.0)).xyz;vec3 Dir_World_Q190;Dir_World_Q190=(world*vec4(tangent,0.0)).xyz;vec3 Dir_World_Q191;Dir_World_Q191=(world*vec4((cross(normal,tangent)),0.0)).xyz;float Length_Q180=length(Dir_World_Q190);float Length_Q181=length(Dir_World_Q191);float Quotient_Q184=Length_Q180/Length_Q181;float Quotient_Q195=_Radius_/Length_Q181;vec2 Result_Q193;Result_Q193=vec2((uv.x-0.5)*Length_Q180/Length_Q181,(uv.y-0.5));float Result_Q198=_Fixed_Radius_ ? Quotient_Q195 : _Radius_;vec3 Vec3_Q183=vec3(Quotient_Q184,Result_Q198,0);vec3 Position=Pos_World_Q189;vec3 Normal=vec3(0,0,0);vec2 UV=Result_Q193;vec3 Tangent=Vec3_Q183;vec3 Binormal=vec3(0,0,0);vec4 Color=color;gl_Position=viewProjection*vec4(Position,1);vUV=UV;vTangent=Tangent;}\n";class fF extends xl{constructor(){super(),this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class mF extends ml{constructor(e,t){super(e,t),this.color=new Ae(1,1,1,.05),this.radius=.12,this.fixedRadius=!0,this._filterWidth=1,this.glowFraction=0,this.glowMax=.5,this.glowFalloff=2,this.alphaMode=N_.ALPHA_COMBINE,this.backFaceCulling=!1}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new fF);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!0,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="mrdlInnerquad",a=s.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Color_","_Radius_","_Fixed_Radius_","_Filter_Width_","_Glow_Fraction_","_Glow_Max_","_Glow_Falloff_"],h=[],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setDirectColor4("_Color_",this.color),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Fixed_Radius_",this.fixedRadius?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setFloat("_Glow_Fraction_",this.glowFraction),this._activeEffect.setFloat("_Glow_Max_",this.glowMax),this._activeEffect.setFloat("_Glow_Falloff_",this.glowFalloff),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new mF(e,this.getScene())),this)}serialize(){const e=St.Serialize(this);return e.customType="BABYLON.MRDLInnerquadMaterial",e}getClassName(){return"MRDLInnerquadMaterial"}static Parse(e,t,i){return St.Parse((()=>new mF(e.name,t)),e,t,i)}}Ze([rt()],mF.prototype,"color",void 0),Ze([rt()],mF.prototype,"radius",void 0),Ze([rt()],mF.prototype,"fixedRadius",void 0),Ze([rt()],mF.prototype,"glowFraction",void 0),Ze([rt()],mF.prototype,"glowMax",void 0),Ze([rt()],mF.prototype,"glowFalloff",void 0),z("BABYLON.GUI.MRDLInnerquadMaterial",mF);class gF extends GN{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._backGlow.renderingGroupId=e,this._innerQuad.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}get mesh(){return this._backPlate}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=Wa("",{size:1},this._backPlate._scene),this._tooltipMesh.position=_e.Down().scale(.7).add(_e.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._frontPlateCollisionMesh,this._tooltipTexture=xN.CreateForMesh(this._tooltipMesh);const t=new ww;t.height=.25,t.width=.8,t.cornerRadius=25,t.color="#ffffff",t.thickness=20,t.background="#060668",this._tooltipTexture.addControl(t),this._tooltipTextBlock=new Fw,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=100,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new Va,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?.text||null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get subtext(){return this._subtext}set subtext(e){this._subtext!==e&&(this._subtext=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get backGlowMaterial(){return this._backGlowMaterial}get innerQuadMaterial(){return this._innerQuadMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}set isBackplateVisible(e){this.mesh&&this._backMaterial&&(e&&!this._isBackplateVisible?this._backPlate.visibility=1:!e&&this._isBackplateVisible&&(this._backPlate.visibility=0)),this._isBackplateVisible=e}constructor(e,t=!0){super(e),this.width=1,this.height=1,this.radius=.14,this.textSizeInPixels=18,this.imageSizeInPixels=40,this.plateMaterialColor=new Ee(.4,.4,.4),this.frontPlateDepth=.2,this.backPlateDepth=.04,this.backGlowOffset=.1,this.flatPlaneDepth=.001,this.innerQuadRadius=this.radius-.04,this.innerQuadColor=new Ae(0,0,0,0),this.innerQuadToggledColor=new Ae(.5197843,.6485234,.9607843,.6),this.innerQuadHoverColor=new Ae(1,1,1,.05),this.innerQuadToggledHoverColor=new Ae(.5197843,.6485234,.9607843,1),this._isBackplateVisible=!0,this._shareMaterials=!0,this._shareMaterials=t,this.pointerEnterAnimation=()=>{this._frontPlate&&this._textPlate&&!this.isToggleButton&&this._performEnterExitAnimation(1),this.isToggleButton&&this._innerQuadMaterial&&(this.isToggled?this._innerQuadMaterial.color=this.innerQuadToggledHoverColor:this._innerQuadMaterial.color=this.innerQuadHoverColor)},this.pointerOutAnimation=()=>{this._frontPlate&&this._textPlate&&!this.isToggleButton&&this._performEnterExitAnimation(-.8),this.isToggleButton&&this._innerQuadMaterial&&this._onToggle(this.isToggled)},this.pointerDownAnimation=()=>{},this.pointerUpAnimation=()=>{},this._pointerClickObserver=this.onPointerClickObservable.add((()=>{this._frontPlate&&this._backGlow&&!this.isActiveNearInteraction&&this._performClickAnimation(),this.isToggleButton&&this._innerQuadMaterial&&this._onToggle(this.isToggled)})),this._pointerEnterObserver=this.onPointerEnterObservable.add((()=>{this.pointerEnterAnimation()})),this._pointerOutObserver=this.onPointerOutObservable.add((()=>{this.pointerOutAnimation()})),this._toggleObserver=this.onToggleObservable.add((e=>{this._innerQuadMaterial.color=e?this.innerQuadToggledColor:this.innerQuadColor}))}_getTypeName(){return"TouchHolographicButton"}_rebuildContent(){let e;e=this._getAspectRatio()<=1?this._alignContentVertically():this._alignContentHorizontally(),this.content=e}_getAspectRatio(){return this.width/this.height}_alignContentVertically(){const e=new kw;if(e.isVertical=!0,Ut()&&document.createElement&&this._imageUrl){const t=new Lw;t.source=this._imageUrl,t.heightInPixels=180,t.widthInPixels=100,t.paddingTopInPixels=40,t.paddingBottomInPixels=40,e.addControl(t)}if(this._text){const t=new Fw;t.text=this._text,t.color="white",t.heightInPixels=30,t.fontSize=24,e.addControl(t)}return e}_alignContentHorizontally(){let e=240;const t=15,i=new ww;i.widthInPixels=e,i.heightInPixels=e,i.color="transparent",i.setPaddingInPixels(t,t,t,t),e-=30;const s=new kw;if(s.isVertical=!1,s.scaleY=this._getAspectRatio(),Ut()&&document.createElement&&this._imageUrl){const t=new ww(`${this.name}_image`);t.widthInPixels=this.imageSizeInPixels,t.heightInPixels=this.imageSizeInPixels,t.color="transparent",e-=this.imageSizeInPixels;const i=new Lw;i.source=this._imageUrl,t.addControl(i),s.addControl(t)}if(this._text){const i=new Fw(`${this.name}_text`);if(i.text=this._text,i.color="white",i.fontSize=this.textSizeInPixels,i.widthInPixels=e,this._imageUrl&&(i.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,i.paddingLeftInPixels=t),this._subtext){const r=new zw;r.addColumnDefinition(1),r.addRowDefinition(.5),r.addRowDefinition(.5),r.widthInPixels=e,r.heightInPixels=45;const n=new Fw(`${this.name}_subtext`);n.text=this._subtext,n.color="#EEEEEEAB",n.fontSize=.75*this.textSizeInPixels,n.fontWeight="600",this._imageUrl&&(n.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,n.paddingLeftInPixels=t),r.addControl(i,0),r.addControl(n,1),s.addControl(r)}else s.addControl(i)}return i.addControl(s),i}_createNode(e){this.name=this.name??"TouchHolographicButton";const t=this._createBackPlate(e),i=this._createFrontPlate(e),s=this._createInnerQuad(e),r=this._createBackGlow(e);this._frontPlateCollisionMesh=i,this._textPlate=super._createNode(e),this._textPlate.name=`${this.name}_textPlate`,this._textPlate.isPickable=!1,this._textPlate.scaling.x=this.width,this._textPlate.parent=i,this._backPlate=t,this._backPlate.position=_e.Forward(e.useRightHandedSystem).scale(this.backPlateDepth/2),this._backPlate.isPickable=!1,this._backPlate.addChild(i),this._backPlate.addChild(s),r&&this._backPlate.addChild(r);const n=new lo(`${this.name}_root`,e);return this._backPlate.setParent(n),this.collisionMesh=i,this.collidableFrontDirection=this._backPlate.forward.negate(),n}_createBackPlate(e){const t=cd(`${this.name}_backPlate`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=.2,fl.ImportMeshAsync(void 0,gF.MRTK_ASSET_BASE_URL,gF.BACKPLATE_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.visibility=0,this._isBackplateVisible&&(i.visibility=1,i.name=`${this.name}_backPlate`,i.isPickable=!1,i.scaling.x=this.width,i.scaling.y=this.height,i.parent=t),this._backMaterial&&(i.material=this._backMaterial),this._backPlate=i})),t}_createFrontPlate(e){const t=cd(`${this.name}_frontPlate`,{width:this.width,height:this.height,depth:this.frontPlateDepth},e);return t.isPickable=!0,t.isNearPickable=!0,t.visibility=0,t.position=_e.Forward(e.useRightHandedSystem).scale((this.backPlateDepth-this.frontPlateDepth)/2),fl.ImportMeshAsync(void 0,gF.MRTK_ASSET_BASE_URL,gF.FRONTPLATE_MODEL_FILENAME,e).then((i=>{const s=cd(`${this.name}_collisionPlate`,{width:this.width,height:this.height},e);s.isPickable=!1,s.scaling.z=this.frontPlateDepth,s.visibility=0,s.parent=t,this._collisionPlate=s;const r=i.meshes[1];r.name=`${this.name}_frontPlate`,r.isPickable=!1,r.scaling.x=this.width-this.backGlowOffset,r.scaling.y=this.height-this.backGlowOffset,r.position=_e.Forward(e.useRightHandedSystem).scale(-.5),r.parent=s,this.isToggleButton&&(r.visibility=0),this._frontMaterial&&(r.material=this._frontMaterial),this._textPlate.scaling.x=1,this._textPlate.parent=r,this._frontPlate=r})),t}_createInnerQuad(e){const t=cd(`${this.name}_innerQuad`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=this.flatPlaneDepth,t.position.z+=this.backPlateDepth/2-this.flatPlaneDepth,fl.ImportMeshAsync(void 0,gF.MRTK_ASSET_BASE_URL,gF.INNERQUAD_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_innerQuad`,i.isPickable=!1,i.scaling.x=this.width-this.backGlowOffset,i.scaling.y=this.height-this.backGlowOffset,i.parent=t,this._innerQuadMaterial&&(i.material=this._innerQuadMaterial),this._innerQuad=i})),t}_createBackGlow(e){if(this.isToggleButton)return;const t=cd(`${this.name}_backGlow`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=this.flatPlaneDepth,t.position.z+=this.backPlateDepth/2-2*this.flatPlaneDepth,fl.ImportMeshAsync(void 0,gF.MRTK_ASSET_BASE_URL,gF.BACKGLOW_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_backGlow`,i.isPickable=!1,i.scaling.x=this.width-this.backGlowOffset,i.scaling.y=this.height-this.backGlowOffset,i.parent=t,this._backGlowMaterial&&(i.material=this._backGlowMaterial),this._backGlow=i})),t}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e,this._plateMaterial.diffuseColor=this.plateMaterialColor}_performClickAnimation(){const e=new gn("Click Animation Group"),t=[{name:"backGlowMotion",mesh:this._backGlow,property:"material.motion",keys:[{frame:0,values:[0,0,0]},{frame:20,values:[1,.0144,.0144]},{frame:40,values:[.0027713229489760476,0,0]},{frame:45,values:[.0027713229489760476]}]},{name:"_collisionPlateZSlide",mesh:this._collisionPlate,property:"position.z",keys:[{frame:0,values:[0,0,0]},{frame:20,values:[_e.Forward(this._collisionPlate._scene.useRightHandedSystem).scale(this.frontPlateDepth/2).z,0,0]},{frame:40,values:[0,.005403332496794331]},{frame:45,values:[0]}]},{name:"_collisionPlateZScale",mesh:this._collisionPlate,property:"scaling.z",keys:[{frame:0,values:[this.frontPlateDepth,0,0]},{frame:20,values:[this.backPlateDepth,0,0]},{frame:40,values:[this.frontPlateDepth,.0054]},{frame:45,values:[this.frontPlateDepth]}]}];for(const i of t){const t=new Ft(i.name,i.property,60,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CYCLE),s=[];for(const e of i.keys)s.push({frame:e.frame,value:e.values[0],inTangent:e.values[1],outTangent:e.values[2],interpolation:e.values[3]});t.setKeys(s),i.mesh&&e.addTargetedAnimation(t,i.mesh)}e.normalize(0,45),e.speedRatio=1,e.play()}_performEnterExitAnimation(e){const t=new gn("Enter Exit Animation Group"),i=[{name:"frontPlateFadeOut",mesh:this._frontPlate,property:"material.fadeOut",keys:[{frame:0,values:[0,0,.025045314830017686,0]},{frame:40,values:[1.00205599570012,.025045314830017686,0,0]}]},{name:"textPlateZSlide",mesh:this._textPlate,property:"position.z",keys:[{frame:0,values:[0,0,0]},{frame:40,values:[_e.Forward(this._textPlate._scene.useRightHandedSystem).scale(-.15).z,0,0]}]}];for(const e of i){const i=new Ft(e.name,e.property,60,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CYCLE),s=[];for(const t of e.keys)s.push({frame:t.frame,value:t.values[0],inTangent:t.values[1],outTangent:t.values[2],interpolation:t.values[3]});i.setKeys(s),e.mesh&&t.addTargetedAnimation(i,e.mesh)}t.normalize(0,45),t.speedRatio=e,t.play()}_createBackMaterial(e){this._backMaterial=this._backMaterial??new oF(this.name+"backPlateMaterial",e.getScene()),this._backMaterial.absoluteSizes=!0,this._backMaterial.radius=this.radius,this._backMaterial.lineWidth=.02}_createFrontMaterial(e){this._frontMaterial=this._frontMaterial??new pF(this.name+"Front Material",e.getScene()),this.frontMaterial.radius=this.innerQuadRadius,this.frontMaterial.fadeOut=0}_createBackGlowMaterial(e){const t=this.radius+.04;this._backGlowMaterial=this._backGlowMaterial??new dF(this.name+"Back Glow Material",e.getScene()),this._backGlowMaterial.bevelRadius=t,this._backGlowMaterial.lineWidth=t,this._backGlowMaterial.motion=0}_createInnerQuadMaterial(e){this._innerQuadMaterial=this._innerQuadMaterial??new mF("inner_quad",e.getScene()),this._innerQuadMaterial.radius=this.innerQuadRadius,this.isToggleButton&&(this._innerQuadMaterial.color=this.innerQuadColor)}_createPlateMaterial(e){this._plateMaterial=this._plateMaterial??new cu(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=Ee.Black()}_onToggle(e){super._onToggle(e)}_affectMaterial(e){this._shareMaterials?(this._host._touchSharedMaterials.mrdlBackplateMaterial?this._backMaterial=this._host._touchSharedMaterials.mrdlBackplateMaterial:(this._createBackMaterial(e),this._host._touchSharedMaterials.mrdlBackplateMaterial=this._backMaterial),this._host._touchSharedMaterials.mrdlFrontplateMaterial?this._frontMaterial=this._host._touchSharedMaterials.mrdlFrontplateMaterial:(this._createFrontMaterial(e),this._host._touchSharedMaterials.mrdlFrontplateMaterial=this._frontMaterial),this._host._touchSharedMaterials.mrdlBackglowMaterial?this._backGlowMaterial=this._host._touchSharedMaterials.mrdlBackglowMaterial:(this._createBackGlowMaterial(e),this._host._touchSharedMaterials.mrdlBackglowMaterial=this._backGlowMaterial),this._host._touchSharedMaterials.mrdlInnerQuadMaterial?this._innerQuadMaterial=this._host._touchSharedMaterials.mrdlInnerQuadMaterial:(this._createInnerQuadMaterial(e),this._host._touchSharedMaterials.mrdlInnerQuadMaterial=this._innerQuadMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e),this._createBackGlowMaterial(e),this._createInnerQuadMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._textPlate.material=this._plateMaterial,this._isBackplateVisible||(this._backPlate.visibility=0),this._frontPlate&&(this._frontPlate.material=this._frontMaterial),this._backGlow&&(this._backGlow.material=this._backGlowMaterial),this._innerQuad&&(this._innerQuad.material=this._innerQuadMaterial),this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.onPointerClickObservable.remove(this._pointerClickObserver),this.onPointerEnterObservable.remove(this._pointerEnterObserver),this.onPointerOutObservable.remove(this._pointerOutObserver),this.onToggleObservable.remove(this._toggleObserver),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._backGlowMaterial.dispose(),this._innerQuadMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}gF.MRTK_ASSET_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",gF.FRONTPLATE_MODEL_FILENAME="mrtk-fluent-frontplate.glb",gF.BACKPLATE_MODEL_FILENAME="mrtk-fluent-backplate.glb",gF.BACKGLOW_MODEL_FILENAME="mrtk-fluent-button.glb",gF.INNERQUAD_MODEL_FILENAME="SlateProximity.glb";class vF{get scene(){return this._scene}get utilityLayer(){return this._utilityLayer}get controlScaling(){return this._customControlScaling}set controlScaling(e){if(this._customControlScaling!==e&&e>0){const t=e/this._customControlScaling;this._customControlScaling=e,this._rootContainer.children.forEach((i=>{i.scaling.scaleInPlace(t),1!==e&&(i._isScaledByManager=!0)}))}}get useRealisticScaling(){return this.controlScaling===vF.MRTK_REALISTIC_SCALING}set useRealisticScaling(e){this.controlScaling=e?vF.MRTK_REALISTIC_SCALING:1}constructor(e){this._customControlScaling=1,this._lastControlOver={},this._lastControlDown={},this.onPickedPointChangedObservable=new K,this.onPickingObservable=new K,this._sharedMaterials={},this._touchSharedMaterials={},this._scene=e||re.LastCreatedScene,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>{this._sceneDisposeObserver=null,this._utilityLayer=null,this.dispose()})),this._utilityLayer=Ju._CreateDefaultUtilityLayerFromScene(this._scene),this._utilityLayer.onlyCheckPointerDownEvents=!1,this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.mainSceneTrackerPredicate=e=>e&&e.reservedDataStore?.GUI3D?.control?._node,this._rootContainer=new IN("RootContainer"),this._rootContainer._host=this;const t=this._utilityLayer.utilityLayerScene;this._pointerOutObserver=this._utilityLayer.onPointerOutObservable.add((e=>{this._handlePointerOut(e,!0)})),this._pointerObserver=t.onPointerObservable.add((e=>{this._doPicking(e)})),this._utilityLayer.utilityLayerScene.autoClear=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,new Zu("hemi",_e.Up(),this._utilityLayer.utilityLayerScene)}_handlePointerOut(e,t){const i=this._lastControlOver[e];i&&(i._onPointerOut(i),delete this._lastControlOver[e]),t&&this._lastControlDown[e]&&(this._lastControlDown[e].forcePointerUp(),delete this._lastControlDown[e]),this.onPickedPointChangedObservable.notifyObservers(null)}_doPicking(e){if(!this._utilityLayer||!this._utilityLayer.shouldRender||!this._utilityLayer.utilityLayerScene.activeCamera)return!1;const t=e.event,i=t.pointerId||0,s=t.button,r=e.pickInfo;if(r&&this.onPickingObservable.notifyObservers(r.pickedMesh),!r||!r.hit)return this._handlePointerOut(i,e.type===lr.POINTERUP),!1;r.pickedPoint&&this.onPickedPointChangedObservable.notifyObservers(r.pickedPoint);const n=r.pickedMesh.reservedDataStore?.GUI3D?.control;return n&&!n._processObservables(e.type,r.pickedPoint,r.originMesh?.position||null,i,s)&&e.type===lr.POINTERMOVE&&(this._lastControlOver[i]&&this._lastControlOver[i]._onPointerOut(this._lastControlOver[i]),delete this._lastControlOver[i]),e.type===lr.POINTERUP&&(this._lastControlDown[t.pointerId]&&(this._lastControlDown[t.pointerId].forcePointerUp(),delete this._lastControlDown[t.pointerId]),("touch"===t.pointerType||"xr"===t.pointerType&&this._scene.getEngine().hostInformation.isMobile)&&this._handlePointerOut(i,!1)),!0}get rootContainer(){return this._rootContainer}containsControl(e){return this._rootContainer.containsControl(e)}addControl(e){return this._rootContainer.addControl(e),1!==this._customControlScaling&&(e.scaling.scaleInPlace(this._customControlScaling),e._isScaledByManager=!0),this}removeControl(e){return this._rootContainer.removeControl(e),e._isScaledByManager&&(e.scaling.scaleInPlace(1/this._customControlScaling),e._isScaledByManager=!1),this}dispose(){this._rootContainer.dispose();for(const e in this._sharedMaterials)Object.prototype.hasOwnProperty.call(this._sharedMaterials,e)&&this._sharedMaterials[e].dispose();this._sharedMaterials={};for(const e in this._touchSharedMaterials)Object.prototype.hasOwnProperty.call(this._touchSharedMaterials,e)&&this._touchSharedMaterials[e].dispose();this._touchSharedMaterials={},this._pointerOutObserver&&this._utilityLayer&&(this._utilityLayer.onPointerOutObservable.remove(this._pointerOutObserver),this._pointerOutObserver=null),this.onPickedPointChangedObservable.clear(),this.onPickingObservable.clear();const e=this._utilityLayer?this._utilityLayer.utilityLayerScene:null;e&&this._pointerObserver&&(e.onPointerObservable.remove(this._pointerObserver),this._pointerObserver=null),this._scene&&this._sceneDisposeObserver&&(this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null),this._utilityLayer&&this._utilityLayer.dispose()}}function xF(e,t,i,s){const r={externalResourceFunction:s};return i&&(r.uri="file:"===t?i:t+i),ArrayBuffer.isView(e)?GLTFValidator.validateBytes(e,r):GLTFValidator.validateString(e,r)}function bF(){const e=[];onmessage=t=>{const i=t.data;switch(i.id){case"init":importScripts(i.url);break;case"validate":xF(i.data,i.rootUrl,i.fileName,(t=>new Promise(((i,s)=>{const r=e.length;e.push({resolve:i,reject:s}),postMessage({id:"getExternalResource",index:r,uri:t})})))).then((e=>{postMessage({id:"validate.resolve",value:e})}),(e=>{postMessage({id:"validate.reject",reason:e})}));break;case"getExternalResource.resolve":e[i.index].resolve(i.value);break;case"getExternalResource.reject":e[i.index].reject(i.reason)}}}vF.MRTK_REALISTIC_SCALING=.032;class TF{static ValidateAsync(e,t,i,s){return"function"==typeof Worker?new Promise(((r,n)=>{const o=`${xF}(${bF})()`,a=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),l=new Worker(a),h=e=>{l.removeEventListener("error",h),l.removeEventListener("message",c),n(e)},c=e=>{const t=e.data;switch(t.id){case"getExternalResource":s(t.uri).then((e=>{l.postMessage({id:"getExternalResource.resolve",index:t.index,value:e},[e.buffer])}),(e=>{l.postMessage({id:"getExternalResource.reject",index:t.index,reason:e})}));break;case"validate.resolve":l.removeEventListener("error",h),l.removeEventListener("message",c),r(t.value),l.terminate();break;case"validate.reject":l.removeEventListener("error",h),l.removeEventListener("message",c),n(t.reason),l.terminate()}};if(l.addEventListener("error",h),l.addEventListener("message",c),l.postMessage({id:"init",url:Ds.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const s=e.slice();l.postMessage({id:"validate",data:s,rootUrl:t,fileName:i},[s.buffer])}else l.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})})):(this._LoadScriptPromise||(this._LoadScriptPromise=Ds.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then((()=>xF(e,t,i,s))))}}function yF(e,t,i){try{return Promise.resolve(new Uint8Array(e,t,i))}catch(e){return Promise.reject(e)}}var SF,CF,EF,AF,PF,IF,RF,MF,OF,DF,wF,NF;TF.Configuration={url:`${Ds._DefaultCdnUrl}/gltf_validator.js`},function(e){e[e.AUTO=0]="AUTO",e[e.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"}(SF||(SF={})),function(e){e[e.NONE=0]="NONE",e[e.FIRST=1]="FIRST",e[e.ALL=2]="ALL"}(CF||(CF={})),function(e){e[e.LOADING=0]="LOADING",e[e.READY=1]="READY",e[e.COMPLETE=2]="COMPLETE"}(EF||(EF={}));class FF{constructor(){this.onParsedObservable=new K,this.coordinateSystemMode=SF.AUTO,this.animationStartMode=CF.FIRST,this.compileMaterials=!1,this.useClipPlane=!1,this.compileShadowGenerators=!1,this.transparencyAsCoverage=!1,this.useRangeRequests=!1,this.createInstances=!0,this.alwaysComputeBoundingBox=!1,this.loadAllMaterials=!1,this.loadOnlyMaterials=!1,this.skipMaterials=!1,this.useSRGBBuffers=!0,this.targetFps=60,this.alwaysComputeSkeletonRootNode=!1,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable=new K,this.onSkinLoadedObservable=new K,this.onTextureLoadedObservable=new K,this.onMaterialLoadedObservable=new K,this.onCameraLoadedObservable=new K,this.onCompleteObservable=new K,this.onErrorObservable=new K,this.onDisposeObservable=new K,this.onExtensionLoadedObservable=new K,this.validate=!1,this.onValidatedObservable=new K,this._loader=null,this._state=null,this._requests=new Array,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new K,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),this._onParsedObserver=this.onParsedObservable.add(e)}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e)}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e)}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e)}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e)}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,i,s,r,n,o,a){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,s,o,a),null;this._progressCallback=r;const l=t.name||Ds.GetFilename(t);if(n){if(this.useRangeRequests){this.validate&&Ne.Warn("glTF validation is not supported when range requests are enabled");const i={abort:()=>{},onCompleteObservable:new K},r={readAsync:(i,s)=>new Promise(((r,n)=>{this._loadFile(e,t,(e=>{r(new Uint8Array(e))}),!0,(e=>{n(e)}),(e=>{e.setRequestHeader("Range",`bytes=${i}-${i+s-1}`)}))})),byteLength:0};return this._unpackBinaryAsync(new mR(r)).then((e=>{i.onCompleteObservable.notifyObservers(i),s(e)}),o?e=>o(void 0,e):void 0),i}return this._loadFile(e,t,(t=>{this._validate(e,new Uint8Array(t,0,t.byteLength),i,l),this._unpackBinaryAsync(new mR({readAsync:(e,i)=>yF(t,e,i),byteLength:t.byteLength})).then((e=>{s(e)}),o?e=>o(void 0,e):void 0)}),!0,o)}return this._loadFile(e,t,(t=>{this._validate(e,t,i,l),s({json:this._parseJson(t)})}),!1,o)}_loadBinary(e,t,i,s,r,n){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i,n),this._unpackBinaryAsync(new mR({readAsync:(e,i)=>function(e,t,i){try{if(t<0||t>=e.byteLength)throw new RangeError("Offset is out of range.");if(t+i>e.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(e.buffer,e.byteOffset+t,i))}catch(e){return Promise.reject(e)}}(t,e,i),byteLength:t.byteLength})).then((e=>{s(e)}),r?e=>r(void 0,e):void 0)}importMeshAsync(e,t,i,s,r,n){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${n||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,s,r,n))))}loadAsync(e,t,i,s,r){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,s,r))))}loadAssetContainerAsync(e,t,i,s,r){return Promise.resolve().then((()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t);const n=new pa(e),o=[];this.onMaterialLoadedObservable.add((e=>{o.push(e)}));const a=[];this.onTextureLoadedObservable.add((e=>{a.push(e)}));const l=[];this.onCameraLoadedObservable.add((e=>{l.push(e)}));const h=[];return this.onMeshLoadedObservable.add((e=>{e.morphTargetManager&&h.push(e.morphTargetManager)})),this._loader.importMeshAsync(null,e,n,t,i,s,r).then((e=>(Array.prototype.push.apply(n.geometries,e.geometries),Array.prototype.push.apply(n.meshes,e.meshes),Array.prototype.push.apply(n.particleSystems,e.particleSystems),Array.prototype.push.apply(n.skeletons,e.skeletons),Array.prototype.push.apply(n.animationGroups,e.animationGroups),Array.prototype.push.apply(n.materials,o),Array.prototype.push.apply(n.textures,a),Array.prototype.push.apply(n.lights,e.lights),Array.prototype.push.apply(n.transformNodes,e.transformNodes),Array.prototype.push.apply(n.cameras,l),Array.prototype.push.apply(n.morphTargetManagers,h),n)))}))}canDirectLoad(e){return-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+FF._MagicBase64Encoded)||e.startsWith("data:;base64,"+FF._MagicBase64Encoded)||e.startsWith("data:application/octet-stream;base64,"+FF._MagicBase64Encoded)||e.startsWith("data:model/gltf-binary;base64,"+FF._MagicBase64Encoded)}directLoad(e,t){if(t.startsWith("base64,"+FF._MagicBase64Encoded)||t.startsWith(";base64,"+FF._MagicBase64Encoded)||t.startsWith("application/octet-stream;base64,"+FF._MagicBase64Encoded)||t.startsWith("model/gltf-binary;base64,"+FF._MagicBase64Encoded)){const i=xs(t);return this._validate(e,new Uint8Array(i,0,i.byteLength)),this._unpackBinaryAsync(new mR({readAsync:(e,t)=>yF(i,e,t),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(){return new FF}get loaderState(){return this._state}whenCompleteAsync(){return new Promise(((e,t)=>{this.onCompleteObservable.addOnce((()=>{e()})),this.onErrorObservable.addOnce((e=>{t(e)}))}))}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(EF[this._state]))}_loadFile(e,t,i,s,r,n){const o=e._loadFile(t,i,(e=>{this._onProgress(e,o)}),!0,s,r,n);return o.onCompleteObservable.add((()=>{o._lengthComputable=!0,o._total=o._loaded})),this._requests.push(o),o}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,s=0,r=0;for(const e of this._requests){if(void 0===e._lengthComputable||void 0===e._loaded||void 0===e._total)return;i=i&&e._lengthComputable,s+=e._loaded,r+=e._total}this._progressCallback({lengthComputable:i,loaded:s,total:i?r:0})}_validate(e,t,i="",s=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),TF.ValidateAsync(t,i,s,(t=>this.preprocessUrlAsync(i+t).then((t=>e._loadFileAsync(t,void 0,!0,!0).then((e=>new Uint8Array(e,0,e.byteLength))))))).then((e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()}),(e=>{this._endPerformanceCounter("Validate JSON"),Ds.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 i=FF._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=FF._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(FF._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const s={1:FF._CreateGLTF1Loader,2:FF._CreateGLTF2Loader}[i.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 t=e.readUint32();if(1179937895!==t)throw new jt("Unexpected magic: "+t,Qt.GLTFLoaderUnexpectedMagicError);const i=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${i}`);const s=e.readUint32();let r;switch(this.useRangeRequests||s===e.buffer.byteLength||Ne.Warn(`Length in header does not match actual data length: ${s} != ${e.buffer.byteLength}`),i){case 1:r=this._unpackBinaryV1Async(e,s);break;case 2:r=this._unpackBinaryV2Async(e,s);break;default:throw new Error("Unsupported version: "+i)}return this._endPerformanceCounter("Unpack Binary"),r}))}_unpackBinaryV1Async(e,t){const i=e.readUint32(),s=e.readUint32();if(0!==s)throw new Error(`Unexpected content format: ${s}`);const r=t-e.byteOffset,n={json:this._parseJson(e.readString(i)),bin:null};if(0!==r){const t=e.byteOffset;n.bin={readAsync:(i,s)=>e.buffer.readAsync(t+i,s),byteLength:r}}return Promise.resolve(n)}_unpackBinaryV2Async(e,t){const i=1313821514,s=e.readUint32();if(e.readUint32()!==i)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 r={json:this._parseJson(e.readString(s)),bin:null},n=()=>{const s=e.readUint32();switch(e.readUint32()){case i:throw new Error("Unexpected JSON chunk");case 5130562:{const t=e.byteOffset;r.bin={readAsync:(i,s)=>e.buffer.readAsync(t+i,s),byteLength:s},e.skipBytes(s);break}default:e.skipBytes(s)}return e.byteOffset!==t?e.loadAsync(8).then(n):Promise.resolve(r)};return n()}))}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.majort.minor?1:e.minorn.byteLength)throw new Error("Buffer access is out of range");const o=n.buffer;switch(i+=n.byteOffset,r){case AF.BYTE:return new Int8Array(o,i,s);case AF.UNSIGNED_BYTE:return new Uint8Array(o,i,s);case AF.SHORT:return new Int16Array(o,i,s);case AF.UNSIGNED_SHORT:return new Uint16Array(o,i,s);default:return new Float32Array(o,i,s)}}static GetBufferFromAccessor(e,t){const i=e.bufferViews[t.bufferView],s=t.count*LF.GetByteStrideFromType(t);return LF.GetBufferFromBufferView(e,i,t.byteOffset,s,t.componentType)}static DecodeBufferToText(e){let t="";const i=e.byteLength;for(let s=0;s=this._maxPos}}const kF=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],VF=["world","view","projection","worldView","worldViewProjection","mBones"],UF=["translation","rotation","scale"],GF=["position","rotationQuaternion","scaling"],zF=(e,t,i)=>{for(const s in e){const r=e[s];i[t][s]=r}},WF=e=>{if(e)for(let t=0;t{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},XF=e=>{let t=null;if(e.translation||e.rotation||e.scale){const i=_e.FromArray(e.scale||[1,1,1]),s=fe.FromArray(e.rotation||[0,0,0,1]),r=_e.FromArray(e.translation||[0,0,0]);t=me.Compose(i,s,r)}else t=me.FromArray(e.matrix);return t},YF=(e,t,i,s)=>{for(let e=0;e{for(let i=0;i{const i=e.nodes;let s=i[t];if(s)return{node:s,id:t};for(const e in i)if(s=i[e],s.jointName===t)return{node:s,id:e};return null},KF=(e,t)=>{for(let i=0;i{if(r||(e.scene._blockEntityCollection=!!e.assetContainer,(r=new ha(t.name||"",e.scene))._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,r.id=s),!t.babylonNode)return r;const n=[];let o=null;const a=[],l=[],h=[],c=[];for(let t=0;t1?(u=new ia("multimat"+s,e.scene),u.subMaterials=n):u=new cu("multimat"+s,e.scene),1===n.length&&(u=n[0]),u._parentContainer=e.assetContainer,r.material||(r.material=u),new Yn(s,e.scene,o,!1,r),r.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,r.subMeshes=[];let d=0;for(let t=0;t{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=i),e.scaling&&(e.scaling=s)},ZF=(e,t,i)=>{let s=null;if(e.importOnlyMeshes&&(t.skin||t.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&-1===e.importMeshesNames.indexOf(t.name||""))return null;if(t.skin){if(t.meshes){const r=e.skins[t.skin],n=$F(e,t,t.meshes,i,t.babylonNode);n.skeleton=e.scene.getLastSkeletonById(t.skin),null===n.skeleton&&(n.skeleton=((e,t,i,s)=>{if(s||(s=new Da(t.name||"","",e.scene)),!t.babylonSkeleton)return s;const r=[],n=[];((e,t,i,s)=>{for(const r in e.nodes){const n=e.nodes[r],o=r;if(!n.jointName||KF(i,n.jointName))continue;const a=XF(n),l=new Yr(n.name||"",t,null,a);l.id=o,s.push({bone:l,node:n,id:o})}for(let e=0;e0&&(u=QF(r,l),u&&-1===n.indexOf(u)&&n.push(u)),new Yr(a.jointName||"",s,u,d).id=l}const o=s.bones;s.bones=[];for(let i=0;i{if(t.matrix){const i=new _e(0,0,0),s=new fe,r=new _e(0,0,0);me.FromArray(t.matrix).decompose(r,s,i),qF(e,i,s,r)}else t.translation&&t.rotation&&t.scale&&qF(e,_e.FromArray(t.translation),fe.FromArray(t.rotation),_e.FromArray(t.scale));e.computeWorldMatrix(!0)})(s,t);else{const e=t.translation||[0,0,0],i=t.rotation||[0,0,0,1],r=t.scale||[1,1,1];qF(s,_e.FromArray(e),fe.FromArray(i),_e.FromArray(r))}s.updateCache(!0),t.babylonNode=s}return s},JF=(e,t,i,s=!1)=>{const r=e.nodes[t];let n=null;if(s=!(e.importOnlyMeshes&&!s&&e.importMeshesNames)||-1!==e.importMeshesNames.indexOf(r.name||"")||0===e.importMeshesNames.length,!r.jointName&&s&&(n=ZF(e,r,t),null!==n&&(n.id=t,n.parent=i)),r.children)for(let t=0;t{let t=e.currentScene;if(t)for(let i=0;i{for(const t in e.animations){const i=e.animations[t];if(!i.channels||!i.samplers)continue;let s=null;for(let r=0;r{for(const s in t.uniforms){const r=t.uniforms[s],n=t.parameters[r];if(e.currentIdentifier===s&&n.semantic&&!n.source&&!n.node){const e=kF.indexOf(n.semantic);if(-1!==e)return delete i[s],VF[e]}}return e.currentIdentifier},iL=e=>{for(const t in e.materials)nL.LoadMaterialAsync(e,t,(()=>{}),(()=>{}))};class sL{static CreateRuntime(e,t,i){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:i,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&zF(e.extensions,"extensions",s),e.extensionsUsed&&zF(e.extensionsUsed,"extensionsUsed",s),e.buffers&&((e,t)=>{for(const i in e){const s=e[i];t.buffers[i]=s,t.buffersCount++}})(e.buffers,s),e.bufferViews&&zF(e.bufferViews,"bufferViews",s),e.accessors&&zF(e.accessors,"accessors",s),e.meshes&&zF(e.meshes,"meshes",s),e.lights&&zF(e.lights,"lights",s),e.cameras&&zF(e.cameras,"cameras",s),e.nodes&&zF(e.nodes,"nodes",s),e.images&&zF(e.images,"images",s),e.textures&&zF(e.textures,"textures",s),e.shaders&&((e,t)=>{for(const i in e){const s=e[i];t.shaders[i]=s,t.shaderscount++}})(e.shaders,s),e.programs&&zF(e.programs,"programs",s),e.samplers&&zF(e.samplers,"samplers",s),e.techniques&&zF(e.techniques,"techniques",s),e.materials&&zF(e.materials,"materials",s),e.animations&&zF(e.animations,"animations",s),e.skins&&zF(e.skins,"skins",s),e.scenes&&(s.scenes=e.scenes),e.scene&&e.scenes&&(s.currentScene=e.scenes[e.scene]),s}static LoadBufferAsync(e,t,i,s,r){const n=e.buffers[t];Ds.IsBase64(n.uri)?setTimeout((()=>i(new Uint8Array(Ds.DecodeBase64(n.uri))))):Ds.LoadFile(e.rootUrl+n.uri,(e=>i(new Uint8Array(e))),r,void 0,!0,(e=>{e&&s(e.status+" "+e.statusText)}))}static LoadTextureBufferAsync(e,t,i,s){const r=e.textures[t];if(!r||!r.source)return void s("");if(r.babylonTexture)return void i(null);const n=e.images[r.source];Ds.IsBase64(n.uri)?setTimeout((()=>i(new Uint8Array(Ds.DecodeBase64(n.uri))))):Ds.LoadFile(e.rootUrl+n.uri,(e=>i(new Uint8Array(e))),void 0,void 0,!0,(e=>{e&&s(e.status+" "+e.statusText)}))}static CreateTextureAsync(e,t,i,s){const r=e.textures[t];if(r.babylonTexture)return void s(r.babylonTexture);const n=e.samplers[r.sampler],o=n.minFilter===MF.NEAREST_MIPMAP_NEAREST||n.minFilter===MF.NEAREST_MIPMAP_LINEAR||n.minFilter===MF.LINEAR_MIPMAP_NEAREST||n.minFilter===MF.LINEAR_MIPMAP_LINEAR,a=Pa.BILINEAR_SAMPLINGMODE,l=null==i?new Blob:new Blob([i]),h=URL.createObjectURL(l),c=()=>URL.revokeObjectURL(h),u=new Pa(h,e.scene,!o,!0,a,c,c);void 0!==n.wrapS&&(u.wrapU=LF.GetWrapMode(n.wrapS)),void 0!==n.wrapT&&(u.wrapV=LF.GetWrapMode(n.wrapT)),u.name=t,r.babylonTexture=u,s(u)}static LoadShaderStringAsync(e,t,i,s){const r=e.shaders[t];if(Ds.IsBase64(r.uri)){const e=atob(r.uri.split(",")[1]);i&&i(e)}else Ds.LoadFile(e.rootUrl+r.uri,i,void 0,void 0,!1,(e=>{e&&s&&s(e.status+" "+e.statusText)}))}static LoadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r.technique)return void(s&&s("No technique found."));const n=e.techniques[r.technique];if(!n){e.scene._blockEntityCollection=!!e.assetContainer;const s=new cu(t,e.scene);return s._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,s.diffuseColor=new Ee(.5,.5,.5),s.sideOrientation=ta.CounterClockWiseSideOrientation,void i(s)}const o=e.programs[n.program],a=n.states,l=$i.ShadersStore[o.vertexShader+"VertexShader"],h=$i.ShadersStore[o.fragmentShader+"PixelShader"];let c="",u="";const d=new BF(l),_=new BF(h),p={},f=[],m=[],g=[];for(const e in n.uniforms){const t=n.uniforms[e],i=n.parameters[t];if(p[e]=i,!i.semantic||i.node||i.source)i.type===IF.SAMPLER_2D?g.push(e):f.push(e);else{const t=kF.indexOf(i.semantic);-1!==t?(f.push(VF[t]),delete p[e]):f.push(e)}}for(const e in n.attributes){const t=n.attributes[e],i=n.parameters[t];if(i.semantic){const e=HF(i);e&&m.push(e)}}for(;!d.isEnd()&&d.getNextToken();){if(d.currentToken!==NF.IDENTIFIER){c+=d.currentString;continue}let e=!1;for(const t in n.attributes){const i=n.attributes[t],s=n.parameters[i];if(d.currentIdentifier===t&&s.semantic){c+=HF(s),e=!0;break}}e||(c+=tL(d,n,p))}for(;!_.isEnd()&&_.getNextToken();)_.currentToken===NF.IDENTIFIER?u+=tL(_,n,p):u+=_.currentString;const v={vertex:o.vertexShader+t,fragment:o.fragmentShader+t},x={attributes:m,uniforms:f,samplers:g,needAlphaBlending:a&&a.enable&&-1!==a.enable.indexOf(3042)};$i.ShadersStore[o.vertexShader+t+"VertexShader"]=c,$i.ShadersStore[o.fragmentShader+t+"PixelShader"]=u;const b=new Nd(t,e.scene,v,x);if(b.onError=((e,t,i)=>(s,r)=>{t.dispose(!0),i("Cannot compile program named "+e.name+". Error: "+r+". Default material will be applied")})(o,b,s),b.onCompiled=((e,t,i,s,r,n)=>o=>{((e,t,i,s,r)=>{const n=s.values||i.parameters,o=i.uniforms;for(const i in r){const a=r[i],l=a.type;let h=n[o[i]];if(void 0===h&&(h=a.value),!h)continue;const c=e=>i=>{a.value&&e&&(t.setTexture(e,i),delete r[e])};l===IF.SAMPLER_2D?nL.LoadTextureAsync(e,s.values?h:a.value,c(i),(()=>c(null))):a.value&&LF.SetUniform(t,i,s.values?h:a.value,l)&&delete r[i]}})(e,t,i,s,r),t.onBind=o=>{((e,t,i,s,r,n,o)=>{const a=n.values||r.parameters;for(const o in i){const l=i[o],h=l.type;if(h===IF.FLOAT_MAT2||h===IF.FLOAT_MAT3||h===IF.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;LF.SetMatrix(t.scene,e,l,o,s.getEffect())}}else LF.SetMatrix(t.scene,e,l,o,s.getEffect());else{const e=a[r.uniforms[o]];if(!e)continue;if(h===IF.SAMPLER_2D){const i=t.textures[n.values?e:l.value].babylonTexture;if(null==i)continue;s.getEffect().setTexture(o,i)}else LF.SetUniform(s.getEffect(),o,e,h)}}o(s)})(o,e,r,t,i,s,n)}})(e,b,n,r,p,i),b.sideOrientation=ta.CounterClockWiseSideOrientation,a&&a.functions){const e=a.functions;e.cullFace&&e.cullFace[0]!==DF.BACK&&(b.backFaceCulling=!1);const t=e.blendFuncSeparate;t&&(t[0]===wF.SRC_ALPHA&&t[1]===wF.ONE_MINUS_SRC_ALPHA&&t[2]===wF.ONE&&t[3]===wF.ONE?b.alphaMode=N_.ALPHA_COMBINE:t[0]===wF.ONE&&t[1]===wF.ONE&&t[2]===wF.ZERO&&t[3]===wF.ONE?b.alphaMode=N_.ALPHA_ONEONE:t[0]===wF.SRC_ALPHA&&t[1]===wF.ONE&&t[2]===wF.ZERO&&t[3]===wF.ONE?b.alphaMode=N_.ALPHA_ADD:t[0]===wF.ZERO&&t[1]===wF.ONE_MINUS_SRC_COLOR&&t[2]===wF.ONE&&t[3]===wF.ONE?b.alphaMode=N_.ALPHA_SUBTRACT:t[0]===wF.DST_COLOR&&t[1]===wF.ZERO&&t[2]===wF.ONE&&t[3]===wF.ONE?b.alphaMode=N_.ALPHA_MULTIPLY:t[0]===wF.SRC_ALPHA&&t[1]===wF.ONE_MINUS_SRC_COLOR&&t[2]===wF.ONE&&t[3]===wF.ONE&&(b.alphaMode=N_.ALPHA_MAXIMIZED))}}}class rL{static RegisterExtension(e){rL.Extensions[e.name]?Ds.Error('Tool with the same name "'+e.name+'" already exists'):rL.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,s,r,n,o,a){return t.useRightHandedSystem=!0,nL.LoadRuntimeAsync(t,i,s,(t=>{t.assetContainer=r,t.importOnlyMeshes=!0,""===e?t.importMeshesNames=[]:"string"==typeof e?t.importMeshesNames=[e]:!e||e instanceof Array?(t.importMeshesNames=[],Ds.Warn("Argument meshesNames must be of type string or string[]")):t.importMeshesNames=[e],this._createNodes(t);const i=[],s=[];for(const e in t.nodes){const s=t.nodes[e];s.babylonNode instanceof _o&&i.push(s.babylonNode)}for(const e in t.skins){const i=t.skins[e];i.babylonSkeleton instanceof Da&&s.push(i.babylonSkeleton)}this._loadBuffersAsync(t,(()=>{this._loadShadersAsync(t,(()=>{iL(t),eL(t),!FF.IncrementalLoading&&n&&n(i,s)}))})),FF.IncrementalLoading&&n&&n(i,s)}),a),!0}importMeshAsync(e,t,i,s,r,n){return new Promise(((o,a)=>{this._importMeshAsync(e,t,s,r,i,((e,t)=>{o({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})}),n,(e=>{a(new Error(e))}))}))}_loadAsync(e,t,i,s,r,n){e.useRightHandedSystem=!0,nL.LoadRuntimeAsync(e,t,i,(e=>{nL.LoadRuntimeExtensionsAsync(e,(()=>{this._createNodes(e),this._loadBuffersAsync(e,(()=>{this._loadShadersAsync(e,(()=>{iL(e),eL(e),FF.IncrementalLoading||s()}))})),FF.IncrementalLoading&&s()}),n)}),n)}loadAsync(e,t,i,s){return new Promise(((r,n)=>{this._loadAsync(e,t,i,(()=>{r()}),s,(e=>{n(new Error(e))}))}))}_loadShadersAsync(e,t){let i=!1;const s=(i,s)=>{nL.LoadShaderStringAsync(e,i,(r=>{r instanceof ArrayBuffer||(e.loadedShaderCount++,r&&($i.ShadersStore[i+(s.type===PF.VERTEX?"VertexShader":"PixelShader")]=r),e.loadedShaderCount===e.shaderscount&&t())}),(()=>{Ds.Error("Error when loading shader program named "+i+" located at "+s.uri)}))};for(const t in e.shaders){i=!0;const r=e.shaders[t];r?s.bind(this,t,r)():Ds.Error("No shader named: "+t)}i||t()}_loadBuffersAsync(e,t){let i=!1;const s=(i,s)=>{nL.LoadBufferAsync(e,i,(r=>{e.loadedBufferCount++,r&&(r.byteLength!=e.buffers[i].byteLength&&Ds.Error("Buffer named "+i+" is length "+r.byteLength+". Expected: "+s.byteLength),e.loadedBufferViews[i]=r),e.loadedBufferCount===e.buffersCount&&t()}),(()=>{Ds.Error("Error when loading buffer named "+i+" located at "+s.uri)}))};for(const t in e.buffers){i=!0;const r=e.buffers[t];r?s.bind(this,t,r)():Ds.Error("No buffer named: "+t)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;in.loadRuntimeAsync(e,t,i,s,r)),(()=>{setTimeout((()=>{s&&s(sL.CreateRuntime(t.json,e,i))}))}))}static LoadRuntimeExtensionsAsync(e,t,i){nL._ApplyExtensions((s=>s.loadRuntimeExtensionsAsync(e,t,i)),(()=>{setTimeout((()=>{t()}))}))}static LoadBufferAsync(e,t,i,s,r){nL._ApplyExtensions((n=>n.loadBufferAsync(e,t,i,s,r)),(()=>{sL.LoadBufferAsync(e,t,i,s,r)}))}static LoadTextureAsync(e,t,i,s){nL._LoadTextureBufferAsync(e,t,(r=>{r&&nL._CreateTextureAsync(e,t,r,i,s)}),s)}static LoadShaderStringAsync(e,t,i,s){nL._ApplyExtensions((r=>r.loadShaderStringAsync(e,t,i,s)),(()=>{sL.LoadShaderStringAsync(e,t,i,s)}))}static LoadMaterialAsync(e,t,i,s){nL._ApplyExtensions((r=>r.loadMaterialAsync(e,t,i,s)),(()=>{sL.LoadMaterialAsync(e,t,i,s)}))}static _LoadTextureBufferAsync(e,t,i,s){nL._ApplyExtensions((r=>r.loadTextureBufferAsync(e,t,i,s)),(()=>{sL.LoadTextureBufferAsync(e,t,i,s)}))}static _CreateTextureAsync(e,t,i,s,r){nL._ApplyExtensions((n=>n.createTextureAsync(e,t,i,s,r)),(()=>{sL.CreateTextureAsync(e,t,i,s)}))}static _ApplyExtensions(e,t){for(const t in rL.Extensions)if(e(rL.Extensions[t]))return;t()}}function oL(e,t,i,s){return _e.FromArray(t,i).scaleInPlace(s)}FF._CreateGLTF1Loader=()=>new rL,rL.RegisterExtension(new class extends nL{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,s){const r=t.json.extensionsUsed;return!(!r||-1===r.indexOf(this.name)||!t.bin||(this._bin=t.bin,s(sL.CreateRuntime(t.json,e,i)),0))}loadBufferAsync(e,t,i,s){return-1!==e.extensionsUsed.indexOf(this.name)&&"binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(i,(e=>s(e.message))),!0)}loadTextureBufferAsync(e,t,i){const s=e.textures[t],r=e.images[s.source];if(!r.extensions||!(this.name in r.extensions))return!1;const n=r.extensions[this.name],o=e.bufferViews[n.bufferView];return i(LF.GetBufferFromBufferView(e,o,0,o.byteLength,AF.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,i){const s=e.shaders[t];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],n=e.bufferViews[r.bufferView],o=LF.GetBufferFromBufferView(e,n,0,n.byteLength,AF.UNSIGNED_BYTE);return setTimeout((()=>{const e=LF.DecodeBufferToText(o);i(e)})),!0}}),rL.RegisterExtension(new class extends nL{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const t=e.extensions[this.name];if(!t)return!1;const i=t.lights;if(i)for(const t in i){const s=i[t];switch(s.type){case"ambient":{const t=new Zu(s.name,new _e(0,1,0),e.scene),i=s.ambient;i&&(t.diffuse=Ee.FromArray(i.color||[1,1,1]));break}case"point":{const t=new ex(s.name,new _e(10,10,10),e.scene),i=s.point;i&&(t.diffuse=Ee.FromArray(i.color||[1,1,1]));break}case"directional":{const t=new cg(s.name,new _e(0,-1,0),e.scene),i=s.directional;i&&(t.diffuse=Ee.FromArray(i.color||[1,1,1]));break}case"spot":{const t=s.spot;t&&(new _g(s.name,new _e(0,10,0),new _e(0,-1,0),t.fallOffAngle||Math.PI,t.fallOffExponent||0,e.scene).diffuse=Ee.FromArray(t.color||[1,1,1]));break}default:Ds.Warn('GLTF Material Common extension: light type "'+s.type+"” not supported")}}return!1}loadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r||!r.extensions)return!1;const n=r.extensions[this.name];if(!n)return!1;const o=new cu(t,e.scene);return o.sideOrientation=ta.CounterClockWiseSideOrientation,"CONSTANT"===n.technique&&(o.disableLighting=!0),o.backFaceCulling=void 0!==n.doubleSided&&!n.doubleSided,o.alpha=void 0===n.values.transparency?1:n.values.transparency,o.specularPower=void 0===n.values.shininess?0:n.values.shininess,"string"==typeof n.values.ambient?this._loadTexture(e,n.values.ambient,o,"ambientTexture",s):o.ambientColor=Ee.FromArray(n.values.ambient||[0,0,0]),"string"==typeof n.values.diffuse?this._loadTexture(e,n.values.diffuse,o,"diffuseTexture",s):o.diffuseColor=Ee.FromArray(n.values.diffuse||[0,0,0]),"string"==typeof n.values.emission?this._loadTexture(e,n.values.emission,o,"emissiveTexture",s):o.emissiveColor=Ee.FromArray(n.values.emission||[0,0,0]),"string"==typeof n.values.specular?this._loadTexture(e,n.values.specular,o,"specularTexture",s):o.specularColor=Ee.FromArray(n.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,s,r){sL.LoadTextureBufferAsync(e,t,(r=>{sL.CreateTextureAsync(e,t,r,(e=>i[s]=e))}),r)}});class aL{constructor(e,t,i,s){this.type=e,this.name=t,this.getValue=i,this.getStride=s}_buildAnimation(e,t,i){const s=new Ft(e,this.name,t,this.type);return s.setKeys(i),s}}class lL extends aL{buildAnimations(e,t,i,s,r){r(e._babylonTransformNode,this._buildAnimation(t,i,s))}}const hL={translation:[new lL(Ft.ANIMATIONTYPE_VECTOR3,"position",oL,(()=>3))],rotation:[new lL(Ft.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",(function(e,t,i,s){return fe.FromArray(t,i).scaleInPlace(s)}),(()=>4))],scale:[new lL(Ft.ANIMATIONTYPE_VECTOR3,"scaling",oL,(()=>3))],weights:[new class extends aL{buildAnimations(e,t,i,s,r){if(e._numMorphTargets)for(let n=0;n({frame:e.frame,inTangent:e.inTangent?e.inTangent[n]:void 0,value:e.value[n],outTangent:e.outTangent?e.outTangent[n]:void 0,interpolation:e.interpolation})))),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(n),i=o.clone();e.animations.push(i),r(e,i)}}}}(Ft.ANIMATIONTYPE_FLOAT,"influence",(function(e,t,i,s){const r=new Array(e._numMorphTargets);for(let e=0;ee._numMorphTargets))]};function cL(...e){const t=e=>e&&"object"==typeof e;return e.reduce(((e,i)=>(Object.keys(i).forEach((s=>{const r=e[s],n=i[s];Array.isArray(r)&&Array.isArray(n)?e[s]=r.concat(...n):t(r)&&t(n)?e[s]=cL(r,n):e[s]=n})),e)),{})}class uL{static Get(e,t,i){if(!t||null==i||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static TryGet(e,t){return e&&null!=t&&e[t]?e[t]:null}static Assign(e){if(e)for(let t=0;te.dispose&&e.dispose())),this._extensions.length=0,this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,i,s,r,n,o=""){return Promise.resolve().then((()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(s);let n=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);n=(e instanceof Array?e:[e]).map((e=>{const i=t[e];if(void 0===i)throw new Error(`Failed to find node '${e}'`);return i}))}return this._loadAsync(r,o,n,(()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]})))}))}loadAsync(e,t,i,s,r=""){return Promise.resolve().then((()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,r,null,(()=>{})))))}_loadAsync(e,t,i,s){return Promise.resolve().then((()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,this._loadExtensions(),this._checkExtensions();const r=`${EF[EF.LOADING]} => ${EF[EF.READY]}`,n=`${EF[EF.LOADING]} => ${EF[EF.COMPLETE]}`;this._parent._startPerformanceCounter(r),this._parent._startPerformanceCounter(n),this._parent._setState(EF.LOADING),this._extensionsOnLoading();const o=new Array,a=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=uL.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${e.index}`,e))}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let e=0;e{})))}return this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=a:this._babylonScene._forceBlockMaterialDirtyMechanism(a),this._parent.compileMaterials&&o.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&o.push(this._compileShadowGeneratorsAsync()),Promise.all(o).then((()=>(this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(EF.READY),this._startAnimations(),s()))).then((e=>(this._parent._endPerformanceCounter(r),Ds.SetImmediate((()=>{this._disposed||Promise.all(this._completePromises).then((()=>{this._parent._endPerformanceCounter(n),this._parent._setState(EF.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()}),(e=>{this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()}))})),e)))})).catch((e=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()),e}))}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){const i=t[0];(i.byteLengthe.bin.byteLength)&&Ne.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else Ne.Warn("Unexpected BIN chunk")}}_setupData(){if(uL.Assign(this._gltf.accessors),uL.Assign(this._gltf.animations),uL.Assign(this._gltf.buffers),uL.Assign(this._gltf.bufferViews),uL.Assign(this._gltf.cameras),uL.Assign(this._gltf.images),uL.Assign(this._gltf.materials),uL.Assign(this._gltf.meshes),uL.Assign(this._gltf.nodes),uL.Assign(this._gltf.samplers),uL.Assign(this._gltf.scenes),uL.Assign(this._gltf.skins),uL.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const t of this._gltf.nodes)if(t.children)for(const i of t.children)e[i]=t.index;const t=this._createRootNode();for(const i of this._gltf.nodes){const s=e[i.index];i.parent=void 0===s?t:this._gltf.nodes[s]}}}_loadExtensions(){for(const e in dL._RegisteredExtensions){const t=dL._RegisteredExtensions[e].factory(this);t.name!==e&&Ne.Warn(`The name of the glTF loader extension instance does not match the registered name: ${t.name} !== ${e}`),this._extensions.push(t),this._parent.onExtensionLoadedObservable.notifyObservers(t)}this._extensions.sort(((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE))),this._parent.onExtensionLoadedObservable.clear()}_checkExtensions(){if(this._gltf.extensionsRequired)for(const e of this._gltf.extensionsRequired)if(!this._extensions.some((t=>t.name===e&&t.enabled)))throw new Error(`Required extension ${e} 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 e=new ha("__root__",this._babylonScene);this._rootBabylonMesh=e,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const t={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case SF.AUTO:this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],dL._LoadTransform(t,this._rootBabylonMesh));break;case SF.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(e),t}loadSceneAsync(e,t){const i=this._extensionsLoadSceneAsync(e,t);if(i)return i;const s=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const i of t.nodes){const t=uL.Get(`${e}/nodes/${i}`,this._gltf.nodes,i);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 i of e._primitiveBabylonMeshes)t(i)}_getGeometries(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,(t=>{const i=t.geometry;i&&-1===e.indexOf(i)&&e.push(i)}));return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof _o&&e.push(this._rootBabylonMesh);const t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,(t=>{e.push(t)}));return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)i._babylonTransformNode&&"TransformNode"===i._babylonTransformNode.getClassName()&&e.push(i._babylonTransformNode),i._babylonTransformNodeForSkin&&e.push(i._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=[],t=this._gltf.skins;if(t)for(const i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){const e=[],t=this._gltf.animations;if(t)for(const i of t)i._babylonAnimationGroup&&e.push(i._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case CF.NONE:break;case CF.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case CF.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void Ne.Error(`Invalid animation start mode (${this._parent.animationStartMode})`)}}loadNodeAsync(e,t,i=(()=>{})){const s=this._extensionsLoadNodeAsync(e,t,i);if(s)return s;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const r=new Array;this.logOpen(`${e} ${t.name||""}`);const n=s=>{if(dL.AddPointerMetadata(s,e),dL._LoadTransform(t,s),null!=t.camera){const i=uL.Get(`${e}/camera`,this._gltf.cameras,t.camera);r.push(this.loadCameraAsync(`/cameras/${i.index}`,i,(e=>{e.parent=s})))}if(t.children)for(const i of t.children){const t=uL.Get(`${e}/children/${i}`,this._gltf.nodes,i);r.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=s})))}i(s)};if(null==t.mesh||null!=t.skin){const e=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new lo(e,this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==t.mesh?t._babylonTransformNode=i:t._babylonTransformNodeForSkin=i,n(i)}if(null!=t.mesh)if(null==t.skin){const i=uL.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,n))}else{const i=uL.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,(i=>{const s=t._babylonTransformNodeForSkin;i.metadata=cL(s.metadata,i.metadata||{});const n=uL.Get(`${e}/skin`,this._gltf.skins,t.skin);r.push(this._loadSkinAsync(`/skins/${n.index}`,t,n,(e=>{this._forEachPrimitive(t,(t=>{t.skeleton=e})),this._postSceneLoadActions.push((()=>{if(null!=n.skeleton){const e=uL.Get(`/skins/${n.index}/skeleton`,this._gltf.nodes,n.skeleton).parent;t.index===e.index?i.parent=s.parent:i.parent=e._babylonTransformNode}else i.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:s,skinnedNode:i})}))})))})))}return this.logClose(),Promise.all(r).then((()=>(this._forEachPrimitive(t,(e=>{e.geometry&&e.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0,!0)})),t._babylonTransformNode)))}_loadMeshAsync(e,t,i,s){const r=i.primitives;if(!r||!r.length)throw new Error(`${e}: Primitives are missing`);null==r[0].index&&uL.Assign(r);const n=new Array;this.logOpen(`${e} ${i.name||""}`);const o=t.name||`node${t.index}`;if(1===r.length){const s=i.primitives[0];n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${s.index}`,o,t,i,s,(e=>{t._babylonTransformNode=e,t._primitiveBabylonMeshes=[e]})))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new lo(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const s of r)n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${s.index}`,`${o}_primitive${s.index}`,t,i,s,(e=>{e.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(e)})))}return s(t._babylonTransformNode),this.logClose(),Promise.all(n).then((()=>t._babylonTransformNode))}_loadMeshPrimitiveAsync(e,t,i,s,r,n){const o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n);if(o)return o;this.logOpen(`${e}`);const a=0===this._disableInstancedMesh&&this._parent.createInstances&&null==i.skin&&!s.primitives[0].targets;let l,h;if(a&&r._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,l=r._instanceData.babylonSourceMesh.createInstance(t),l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,h=r._instanceData.promise;else{const n=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new ha(t,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.overrideMaterialSideOrientation=this._babylonScene.useRightHandedSystem?ta.CounterClockWiseSideOrientation:ta.ClockWiseSideOrientation,this._createMorphTargets(e,i,s,r,o),n.push(this._loadVertexDataAsync(e,r,o).then((t=>this._loadMorphTargetsAsync(e,r,o,t).then((()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(o),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})))));const c=dL._GetDrawMode(e,r.mode);if(null==r.material){let e=this._defaultBabylonMaterialData[c];e||(e=this._createDefaultMaterial("__GLTFLoader._default",c),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[c]=e),o.material=e}else if(!this.parent.skipMaterials){const t=uL.Get(`${e}/material`,this._gltf.materials,r.material);n.push(this._loadMaterialAsync(`/materials/${t.index}`,t,o,c,(e=>{o.material=e})))}h=Promise.all(n),a&&(r._instanceData={babylonSourceMesh:o,promise:h}),l=o}return dL.AddPointerMetadata(l,e),this._parent.onMeshLoadedObservable.notifyObservers(l),n(l),this.logClose(),h.then((()=>l))}_loadVertexDataAsync(e,t,i){const s=this._extensionsLoadVertexDataAsync(e,t,i);if(s)return s;const r=t.attributes;if(!r)throw new Error(`${e}: Attributes are missing`);const n=new Array,o=new Yn(i.name,this._babylonScene);if(null==t.indices)i.isUnIndexed=!0;else{const i=uL.Get(`${e}/indices`,this._gltf.accessors,t.indices);n.push(this._loadIndicesAccessorAsync(`/accessors/${i.index}`,i).then((e=>{o.setIndices(e)})))}const a=(t,s,a)=>{if(null==r[t])return;i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(s)&&i._delayInfo.push(s);const l=uL.Get(`${e}/attributes/${t}`,this._gltf.accessors,r[t]);n.push(this._loadVertexAccessorAsync(`/accessors/${l.index}`,l,s).then((e=>{if(e.getKind()===er.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&l.min&&l.max){const e=ve.Vector3[0].copyFromFloats(...l.min),t=ve.Vector3[1].copyFromFloats(...l.max);if(l.normalized&&5126!==l.componentType){let i=1;switch(l.componentType){case 5120:i=127;break;case 5121:i=255;break;case 5122:i=32767;break;case 5123:i=65535}const s=1/i;e.scaleInPlace(s),t.scaleInPlace(s)}o._boundingInfo=new Ln(e,t),o.useBoundingInfoFromGeometry=!0}o.setVerticesBuffer(e,l.count)}))),s==er.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),a&&a(l)};return a("POSITION",er.PositionKind),a("NORMAL",er.NormalKind),a("TANGENT",er.TangentKind),a("TEXCOORD_0",er.UVKind),a("TEXCOORD_1",er.UV2Kind),a("TEXCOORD_2",er.UV3Kind),a("TEXCOORD_3",er.UV4Kind),a("TEXCOORD_4",er.UV5Kind),a("TEXCOORD_5",er.UV6Kind),a("JOINTS_0",er.MatricesIndicesKind),a("WEIGHTS_0",er.MatricesWeightsKind),a("JOINTS_1",er.MatricesIndicesExtraKind),a("WEIGHTS_1",er.MatricesWeightsExtraKind),a("COLOR_0",er.ColorKind,(e=>{"VEC4"===e.type&&(i.hasVertexAlpha=!0)})),Promise.all(n).then((()=>o))}_createMorphTargets(e,t,i,s,r){if(!s.targets)return;if(null==t._numMorphTargets)t._numMorphTargets=s.targets.length;else if(s.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const n=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,r.morphTargetManager=new lx(this._babylonScene),r.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e{n.areUpdatesFrozen=!1}))}_loadMorphTargetVertexDataAsync(e,t,i,s){const r=new Array,n=(s,n,o)=>{if(null==i[s])return;const a=t.getVertexBuffer(n);if(!a)return;const l=uL.Get(`${e}/${s}`,this._gltf.accessors,i[s]);r.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then((e=>{o(a,e)})))};return n("POSITION",er.PositionKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(t.length,((e,s)=>{i[s]=t[s]+e})),s.setPositions(i)})),n("NORMAL",er.NormalKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(i.length,((e,s)=>{i[s]=t[s]+e})),s.setNormals(i)})),n("TANGENT",er.TangentKind,((e,t)=>{const i=new Float32Array(t.length/3*4);let r=0;e.forEach(t.length/3*4,((e,s)=>{(s+1)%4!=0&&(i[r]=t[r]+e,r++)})),s.setTangents(i)})),Promise.all(r).then((()=>{}))}static _LoadTransform(e,t){if(null!=e.skin)return;let i=_e.Zero(),s=fe.Identity(),r=_e.One();e.matrix?me.FromArray(e.matrix).decompose(r,s,i):(e.translation&&(i=_e.FromArray(e.translation)),e.rotation&&(s=fe.FromArray(e.rotation)),e.scale&&(r=_e.FromArray(e.scale))),t.position=i,t.rotationQuaternion=s,t.scaling=r}_loadSkinAsync(e,t,i,s){const r=this._extensionsLoadSkinAsync(e,t,i);if(r)return r;if(i._data)return s(i._data.babylonSkeleton),i._data.promise;const n=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new Da(i.name||n,n,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);const a=this._loadSkinInverseBindMatricesDataAsync(e,i).then((e=>{this._updateBoneMatrices(o,e)}));return i._data={babylonSkeleton:o,promise:a},s(o),a}_loadBones(e,t,i){if(null==t.skeleton||this._parent.alwaysComputeSkeletonRootNode){const i=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(i)if(void 0===t.skeleton)t.skeleton=i.index;else{const s=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},r=uL.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);r===i||s(r,i)||(Ne.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=i.index)}else Ne.Warn(`${e}: Failed to find common root`)}const s={};for(const r of t.joints){const n=uL.Get(`${e}/joints/${r}`,this._gltf.nodes,r);this._loadBone(n,t,i,s)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const i={};for(const s of t){const t=[];let r=uL.Get(`${e}/${s}`,this._gltf.nodes,s);for(;-1!==r.index;)t.unshift(r),r=r.parent;i[s]=t}let s=null;for(let e=0;;++e){let r=i[t[0]];if(e>=r.length)return s;const n=r[e];for(let o=1;o=r.length||n!==r[e])return s;s=n}}_loadBone(e,t,i,s){let r=s[e.index];if(r)return r;let n=null;e.index!==t.skeleton&&(e.parent&&-1!==e.parent.index?n=this._loadBone(e.parent,t,i,s):void 0!==t.skeleton&&Ne.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const o=t.joints.indexOf(e.index);return r=new Yr(e.name||`joint${e.index}`,i,n,this._getNodeMatrix(e),null,null,o),s[e.index]=r,this._postSceneLoadActions.push((()=>{r.linkTransformNode(e._babylonTransformNode)})),r}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const i=uL.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${i.index}`,i)}_updateBoneMatrices(e,t){for(const i of e.bones){const e=me.Identity(),s=i._index;t&&-1!==s&&(me.FromArrayToRef(t,16*s,e),e.invertToRef(e));const r=i.getParent();r&&e.multiplyToRef(r.getAbsoluteInverseBindMatrix(),e),i.updateMatrix(e,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?me.FromArray(e.matrix):me.Compose(e.scale?_e.FromArray(e.scale):_e.One(),e.rotation?fe.FromArray(e.rotation):fe.Identity(),e.translation?_e.FromArray(e.translation):_e.Zero())}loadCameraAsync(e,t,i=(()=>{})){const s=this._extensionsLoadCameraAsync(e,t,i);if(s)return s;const r=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new ac(t.name||`camera${t.index}`,_e.Zero(),this._babylonScene,!1);switch(n._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n.ignoreParentScaling=!0,t._babylonCamera=n,n.rotation.set(0,Math.PI,0),t.type){case"perspective":{const i=t.perspective;if(!i)throw new Error(`${e}: Camera perspective properties are missing`);n.fov=i.yfov,n.minZ=i.znear,n.maxZ=i.zfar||0;break}case"orthographic":if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);n.mode=In.ORTHOGRAPHIC_CAMERA,n.orthoLeft=-t.orthographic.xmag,n.orthoRight=t.orthographic.xmag,n.orthoBottom=-t.orthographic.ymag,n.orthoTop=t.orthographic.ymag,n.minZ=t.orthographic.znear,n.maxZ=t.orthographic.zfar;break;default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return dL.AddPointerMetadata(n,e),this._parent.onCameraLoadedObservable.notifyObservers(n),i(n),this.logClose(),Promise.all(r).then((()=>n))}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i{0===e.targetedAnimations.length&&e.dispose()})))}return Promise.all(t).then((()=>{}))}loadAnimationAsync(e,t){const i=this._extensionsLoadAnimationAsync(e,t);if(i)return i;this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new gn(t.name||`animation${t.index}`,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=s;const r=new Array;uL.Assign(t.channels),uL.Assign(t.samplers);for(const i of t.channels)r.push(this._loadAnimationChannelAsync(`${e}/channels/${i.index}`,e,t,i,((e,t)=>{e.animations=e.animations||[],e.animations.push(t),s.addTargetedAnimation(t,e)})));return Promise.all(r).then((()=>(s.normalize(0),s)))}_loadAnimationChannelAsync(e,t,i,s,r){const n=this._extensionsLoadAnimationChannelAsync(e,t,i,s,r);if(n)return n;if(null==s.target.node)return Promise.resolve();const o=uL.Get(`${e}/target/node`,this._gltf.nodes,s.target.node);if("weights"===s.target.path&&!o._numMorphTargets||"weights"!==s.target.path&&!o._babylonTransformNode)return Promise.resolve();let a;switch(s.target.path){case"translation":a=hL.translation;break;case"rotation":a=hL.rotation;break;case"scale":a=hL.scale;break;case"weights":a=hL.weights;break;default:throw new Error(`${e}/target/path: Invalid value (${s.target.path})`)}const l={object:o,info:a};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,l,r)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,s,r,n){const o=this.parent.targetFps,a=1/o,l=uL.Get(`${e}/sampler`,i.samplers,s.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${s.sampler}`,l).then((e=>{let t=0;const l=r.object,h=r.info;for(const r of h){const h=r.getStride(l),c=e.input,u=e.output,d=new Array(c.length);let _=0;switch(e.interpolation){case"STEP":for(let e=0;e0){const e=`${i.name||`animation${i.index}`}_channel${s.index}_${t}`;r.buildAnimations(l,e,o,d,((e,i)=>{++t,n(e,i)}))}}}))}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const i=t.interpolation||"LINEAR";switch(i){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const s=uL.Get(`${e}/input`,this._gltf.accessors,t.input),r=uL.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${s.index}`,s),this._loadFloatAccessorAsync(`/accessors/${r.index}`,r)]).then((([e,t])=>({input:e,interpolation:i,output:t}))),t._data}loadBufferAsync(e,t,i,s){const r=this._extensionsLoadBufferAsync(e,t,i,s);if(r)return r;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+i,s)}catch(t){throw new Error(`${e}: ${t.message}`)}}))}loadBufferViewAsync(e,t){const i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;const s=uL.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,t,i){if(t._data)return t._data;const s=dL._GetNumComponents(e,t.type),r=s*er.GetTypeByteLength(t.componentType),n=s*t.count;if(null==t.bufferView)t._data=Promise.resolve(new i(n));else{const o=uL.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then((a=>{if(5126!==t.componentType||t.normalized||o.byteStride&&o.byteStride!==r){const e=new i(n);return er.ForEach(a,t.byteOffset||0,o.byteStride||r,s,t.componentType,e.length,t.normalized||!1,((t,i)=>{e[i]=t})),e}return dL._GetTypedArray(e,t.componentType,a,t.byteOffset,n)}))}if(t.sparse){const n=t.sparse;t._data=t._data.then((o=>{const a=o,l=uL.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,n.indices.bufferView),h=uL.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,n.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${l.index}`,l),this.loadBufferViewAsync(`/bufferViews/${h.index}`,h)]).then((([o,l])=>{const h=dL._GetTypedArray(`${e}/sparse/indices`,n.indices.componentType,o,n.indices.byteOffset,n.count),c=s*n.count;let u;if(5126!==t.componentType||t.normalized){const o=dL._GetTypedArray(`${e}/sparse/values`,t.componentType,l,n.values.byteOffset,c);u=new i(c),er.ForEach(o,0,r,s,t.componentType,u.length,t.normalized||!1,((e,t)=>{u[t]=e}))}else u=dL._GetTypedArray(`${e}/sparse/values`,t.componentType,l,n.values.byteOffset,c);let d=0;for(let e=0;edL._GetTypedArray(e,t.componentType,i,t.byteOffset,t.count)))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then((e=>new Js(t,e,!1))),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){if(t._babylonVertexBuffer?.[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const s=this._babylonScene.getEngine();if(t.sparse||null==t.bufferView)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new er(s,e,i,!1)));else{const r=uL.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(r).then((n=>{const o=dL._GetNumComponents(e,t.type);return new er(s,n,i,!1,void 0,r.byteStride,void 0,t.byteOffset,o,t.componentType,t.normalized,!0,void 0,!0)}))}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return t&&(t.baseColorFactor?(i.albedoColor=Ee.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=Ee.White(),i.metallic=null==t.metallicFactor?1:t.metallicFactor,i.roughness=null==t.roughnessFactor?1:t.roughnessFactor,t.baseColorTexture&&s.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e}))),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,(e=>{e.name=`${i.name} (Metallic Roughness)`,i.metallicTexture=e}))),i.useMetallnessFromMetallicTextureBlue=!0,i.useRoughnessFromMetallicTextureGreen=!0,i.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(s).then((()=>{}))}_loadMaterialAsync(e,t,i,s,r=(()=>{})){const n=this._extensionsLoadMaterialAsync(e,t,i,s,r);if(n)return n;t._data=t._data||{};let o=t._data[s];if(!o){this.logOpen(`${e} ${t.name||""}`);const i=this.createMaterial(e,t,s);o={babylonMaterial:i,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,i)},t._data[s]=o,dL.AddPointerMetadata(i,e),this._parent.onMaterialLoadedObservable.notifyObservers(i),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce((()=>{const e=o.babylonMeshes.indexOf(i);-1!==e&&o.babylonMeshes.splice(e,1)}))),r(o.babylonMaterial),o.promise.then((()=>o.babylonMaterial))}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new zg(e,this._babylonScene);return i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,i.fillMode=t,i.enableSpecularAntiAliasing=!0,i.useRadianceOverAlpha=!this._parent.transparencyAsCoverage,i.useSpecularOverAlpha=!this._parent.transparencyAsCoverage,i.transparencyMode=zg.PBRMATERIAL_OPAQUE,i.metallic=1,i.roughness=1,i}createMaterial(e,t,i){const s=this._extensionsCreateMaterial(e,t,i);if(s)return s;const r=t.name||`material${t.index}`;return this._createDefaultMaterial(r,i)}loadMaterialPropertiesAsync(e,t,i){const s=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(s)return s;const r=new Array;return r.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&r.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then((()=>{}))}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.emissiveColor=t.emissiveFactor?Ee.FromArray(t.emissiveFactor):new Ee(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,(e=>{e.name=`${i.name} (Normal)`,i.bumpTexture=e}))),i.invertNormalMapX=!this._babylonScene.useRightHandedSystem,i.invertNormalMapY=this._babylonScene.useRightHandedSystem,null!=t.normalTexture.scale&&i.bumpTexture&&(i.bumpTexture.level=t.normalTexture.scale),i.forceIrradianceInFragment=!0),t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,(e=>{e.name=`${i.name} (Occlusion)`,i.ambientTexture=e}))),i.useAmbientInGrayScale=!0,null!=t.occlusionTexture.strength&&(i.ambientTextureStrength=t.occlusionTexture.strength)),t.emissiveTexture&&s.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,(e=>{e.name=`${i.name} (Emissive)`,i.emissiveTexture=e}))),Promise.all(s).then((()=>{}))}loadMaterialAlphaProperties(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":i.transparencyMode=zg.PBRMATERIAL_OPAQUE,i.alpha=1;break;case"MASK":i.transparencyMode=zg.PBRMATERIAL_ALPHATEST,i.alphaCutOff=null==t.alphaCutoff?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break;case"BLEND":i.transparencyMode=zg.PBRMATERIAL_ALPHABLEND,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0,i.useAlphaFromAlbedoTexture=!0);break;default:throw new Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(e,t,i=(()=>{})){const s=this._extensionsLoadTextureInfoAsync(e,t,i);if(s)return s;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const r=uL.Get(`${e}/index`,this._gltf.textures,t.index);r._textureInfo=t;const n=this._loadTextureAsync(`/textures/${t.index}`,r,(s=>{s.coordinatesIndex=t.texCoord||0,dL.AddPointerMetadata(s,e),this._parent.onTextureLoadedObservable.notifyObservers(s),i(s)}));return this.logClose(),n}_loadTextureAsync(e,t,i=(()=>{})){const s=this._extensionsLoadTextureAsync(e,t,i);if(s)return s;this.logOpen(`${e} ${t.name||""}`);const r=null==t.sampler?dL.DefaultSampler:uL.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),n=uL.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,r,n,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,s=(()=>{}),r,n){const o=this._loadSampler(`/samplers/${t.index}`,t),a=new Array,l=new VI;this._babylonScene._blockEntityCollection=!!this._assetContainer;const h={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||l.resolve()},onError:(t,i)=>{this._disposed||l.reject(new Error(`${e}: ${i&&i.message?i.message:t||"Failed to load texture"}`))},mimeType:i.mimeType,loaderOptions:r,useSRGBBuffer:!!n&&this._parent.useSRGBBuffers},c=new Pa(null,this._babylonScene,h);return c._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.push(l.promise),a.push(this.loadImageAsync(`/images/${i.index}`,i).then((e=>{const t=i.uri||`${this._fileName}#image${i.index}`,s=`data:${this._uniqueRootUrl}${t}`;c.updateURL(s,e)}))),c.wrapU=o.wrapU,c.wrapV=o.wrapV,s(c),Promise.all(a).then((()=>c))}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:dL._GetTextureSamplingMode(e,t),wrapU:dL._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:dL._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 i=uL.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}this.logClose()}return t._data}loadUriAsync(e,t,i){const s=this._extensionsLoadUriAsync(e,t,i);if(s)return s;if(!dL._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if(gs(i)){const t=new Uint8Array(xs(i));return this.log(`${e}: Decoded ${i.substr(0,64)}... (${t.length} bytes)`),Promise.resolve(t)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then((t=>new Promise(((s,r)=>{this._parent._loadFile(this._babylonScene,t,(t=>{this._disposed||(this.log(`${e}: Loaded ${i} (${t.byteLength} bytes)`),s(new Uint8Array(t)))}),!0,(t=>{r(new as(`${e}: Failed to load '${i}'${t?": "+t.status+" "+t.statusText:""}`,t))}))}))))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const i=e._internalMetadata=e._internalMetadata||{},s=i.gltf=i.gltf||{};(s.pointers=s.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=null==t?10497:t){case 33071:return Pa.CLAMP_ADDRESSMODE;case 33648:return Pa.MIRROR_ADDRESSMODE;case 10497:return Pa.WRAP_ADDRESSMODE;default:return Ne.Warn(`${e}: Invalid value (${t})`),Pa.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const i=null==t.magFilter?9729:t.magFilter,s=null==t.minFilter?9987:t.minFilter;if(9729===i)switch(s){case 9728:return Pa.LINEAR_NEAREST;case 9729:return Pa.LINEAR_LINEAR;case 9984:return Pa.LINEAR_NEAREST_MIPNEAREST;case 9985:return Pa.LINEAR_LINEAR_MIPNEAREST;case 9986:return Pa.LINEAR_NEAREST_MIPLINEAR;case 9987:return Pa.LINEAR_LINEAR_MIPLINEAR;default:return Ne.Warn(`${e}/minFilter: Invalid value (${s})`),Pa.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==i&&Ne.Warn(`${e}/magFilter: Invalid value (${i})`),s){case 9728:return Pa.NEAREST_NEAREST;case 9729:return Pa.NEAREST_LINEAR;case 9984:return Pa.NEAREST_NEAREST_MIPNEAREST;case 9985:return Pa.NEAREST_LINEAR_MIPNEAREST;case 9986:return Pa.NEAREST_NEAREST_MIPLINEAR;case 9987:return Pa.NEAREST_LINEAR_MIPLINEAR;default:return Ne.Warn(`${e}/minFilter: Invalid value (${s})`),Pa.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){switch(t){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`${e}: Invalid component type ${t}`)}}static _GetTypedArray(e,t,i,s,r){const n=i.buffer;s=i.byteOffset+(s||0);const o=dL._GetTypedArrayConstructor(`${e}/componentType`,t),a=er.GetTypeByteLength(t);return s%a!=0?(Ne.Warn(`${e}: Copying buffer as byte offset (${s}) is not a multiple of component type byte length (${a})`),new o(n.slice(s,s+r*a),0)):new o(n,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 Ds.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,t){switch(null==t&&(t=4),t){case 0:return ta.PointListDrawMode;case 1:return ta.LineListDrawMode;case 2:return ta.LineLoopDrawMode;case 3:return ta.LineStripDrawMode;case 4:return ta.TriangleFillMode;case 5:return ta.TriangleStripDrawMode;case 6:return ta.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${t})`)}_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 i in t._data){const s=t._data[i];for(const t of s.babylonMeshes){t.computeWorldMatrix(!0);const i=s.babylonMaterial;e.push(i.forceCompilationAsync(t)),e.push(i.forceCompilationAsync(t,{useInstances:!0})),this._parent.useClipPlane&&(e.push(i.forceCompilationAsync(t,{clipPlane:!0})),e.push(i.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 i of t){const t=i.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,i){for(const s of this._extensions)if(s.enabled){const r=`${s.name}.${t}`,n=e;n._activeLoaderExtensionFunctions=n._activeLoaderExtensionFunctions||{};const o=n._activeLoaderExtensionFunctions;if(!o[r]){o[r]=!0;try{const e=i(s);if(e)return e}finally{delete o[r]}}}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",(i=>i.loadSceneAsync&&i.loadSceneAsync(e,t)))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",(s=>s.loadNodeAsync&&s.loadNodeAsync(e,t,i)))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",(s=>s.loadCameraAsync&&s.loadCameraAsync(e,t,i)))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",(s=>s._loadVertexDataAsync&&s._loadVertexDataAsync(e,t,i)))}_extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n){return this._applyExtensions(r,"loadMeshPrimitive",(o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,s,r,n)))}_extensionsLoadMaterialAsync(e,t,i,s,r){return this._applyExtensions(t,"loadMaterial",(n=>n._loadMaterialAsync&&n._loadMaterialAsync(e,t,i,s,r)))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",(s=>s.createMaterial&&s.createMaterial(e,t,i)))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",(s=>s.loadMaterialPropertiesAsync&&s.loadMaterialPropertiesAsync(e,t,i)))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",(s=>s.loadTextureInfoAsync&&s.loadTextureInfoAsync(e,t,i)))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",(s=>s._loadTextureAsync&&s._loadTextureAsync(e,t,i)))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",(i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t)))}_extensionsLoadAnimationChannelAsync(e,t,i,s,r){return this._applyExtensions(i,"loadAnimationChannel",(n=>n._loadAnimationChannelAsync&&n._loadAnimationChannelAsync(e,t,i,s,r)))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",(s=>s._loadSkinAsync&&s._loadSkinAsync(e,t,i)))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",(s=>s._loadUriAsync&&s._loadUriAsync(e,t,i)))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",(i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t)))}_extensionsLoadBufferAsync(e,t,i,s){return this._applyExtensions(t,"loadBuffer",(r=>r.loadBufferAsync&&r.loadBufferAsync(e,t,i,s)))}static LoadExtensionAsync(e,t,i,s){if(!t.extensions)return null;const r=t.extensions[i];return r?s(`${e}/extensions/${i}`,r):null}static LoadExtraAsync(e,t,i,s){if(!t.extras)return null;const r=t.extras[i];return r?s(`${e}/extras/${i}`,r):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)}}dL._RegisteredExtensions={},dL.DefaultSampler={index:-1},FF._CreateGLTF2Loader=e=>new dL(e);const _L="EXT_lights_image_based";class pL{constructor(e){this.name=_L,this._loader=e,this.enabled=this._loader.isExtensionUsed(_L)}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 dL.LoadExtensionAsync(e,t,this.name,((i,s)=>{this._loader._allMaterialsDirtyRequired=!0;const r=new Array;r.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const n=uL.Get(`${i}/light`,this._lights,s.light);return r.push(this._loadLightAsync(`/extensions/${this.name}/lights/${s.light}`,n).then((e=>{this._loader.babylonScene.environmentTexture=e}))),this._loader.logClose(),Promise.all(r).then((()=>{}))}))}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const s=new Array(t.specularImages.length);for(let r=0;r{s[r][t]=e}))),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then((()=>{const i=new Cb(this._loader.babylonScene,null,t.specularImageSize);if(i.name=t.name||"environment",t._babylonTexture=i,null!=t.intensity&&(i.level=t.intensity),t.rotation){let e=fe.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(e=fe.Inverse(e)),me.FromQuaternionToRef(e,i.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const r=Q_.FromArray(t.irradianceCoefficients);r.scaleInPlace(t.intensity),r.convertIrradianceToLambertianRadiance();const n=j_.FromHarmonics(r),o=(s.length-1)/be.Log2(t.specularImageSize);return i.updateRGBDAsync(s,n,o)}))}return t._loaded.then((()=>t._babylonTexture))}}dL.RegisterExtension(_L,(e=>new pL(e)));const fL="EXT_mesh_gpu_instancing";class mL{constructor(e){this.name=fL,this._loader=e,this.enabled=this._loader.isExtensionUsed(fL)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((e,s)=>{this._loader._disableInstancedMesh++;const r=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return r;const n=new Array;let o=0;const a=t=>{if(null==s.attributes[t])return void n.push(Promise.resolve(null));const i=uL.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,s.attributes[t]);if(n.push(this._loader._loadFloatAccessorAsync(`/accessors/${i.bufferView}`,i)),0===o)o=i.count;else if(o!==i.count)throw new Error(`${e}/attributes: Instance buffer accessors do not have the same count.`)};return a("TRANSLATION"),a("ROTATION"),a("SCALE"),r.then((e=>Promise.all(n).then((([i,s,r])=>{const n=new Float32Array(16*o);ve.Vector3[0].copyFromFloats(0,0,0),ve.Quaternion[0].copyFromFloats(0,0,0,1),ve.Vector3[1].copyFromFloats(1,1,1);for(let e=0;enew mL(e)));const gL="EXT_meshopt_compression";class vL{constructor(e){this.name=gL,this.enabled=e.isExtensionUsed(gL),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return dL.LoadExtensionAsync(e,t,this.name,((i,s)=>{const r=t;if(r._meshOptData)return r._meshOptData;const n=uL.Get(`${e}/buffer`,this._loader.gltf.buffers,s.buffer);return r._meshOptData=this._loader.loadBufferAsync(`/buffers/${n.index}`,n,s.byteOffset||0,s.byteLength).then((e=>Ky.Default.decodeGltfBufferAsync(e,s.count,s.byteStride,s.mode,s.filter))),r._meshOptData}))}}dL.RegisterExtension(gL,(e=>new vL(e)));const xL="EXT_texture_webp";class bL{constructor(e){this.name=xL,this._loader=e,this.enabled=e.isExtensionUsed(xL)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=null==t.sampler?dL.DefaultSampler:uL.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=uL.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}dL.RegisterExtension(xL,(e=>new bL(e)));const TL="EXT_texture_avif";class yL{constructor(e){this.name=TL,this._loader=e,this.enabled=e.isExtensionUsed(TL)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=null==t.sampler?dL.DefaultSampler:uL.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=uL.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}dL.RegisterExtension(TL,(e=>new yL(e)));const SL="KHR_draco_mesh_compression";class CL{constructor(e){this.name=SL,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=jy.DecoderAvailable&&this._loader.isExtensionUsed(SL)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{if(null!=t.mode&&4!==t.mode&&5!==t.mode)throw new Error(`${e}: Unsupported mode ${t.mode}`);const n={},o={},a=(e,s)=>{const a=r.attributes[e];if(null!=a&&(i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(s)&&i._delayInfo.push(s),n[s]=a,this.useNormalizedFlagFromAccessor)){const i=uL.TryGet(this._loader.gltf.accessors,t.attributes[e]);i&&(o[s]=i.normalized||!1)}};a("POSITION",er.PositionKind),a("NORMAL",er.NormalKind),a("TANGENT",er.TangentKind),a("TEXCOORD_0",er.UVKind),a("TEXCOORD_1",er.UV2Kind),a("TEXCOORD_2",er.UV3Kind),a("TEXCOORD_3",er.UV4Kind),a("TEXCOORD_4",er.UV5Kind),a("TEXCOORD_5",er.UV6Kind),a("JOINTS_0",er.MatricesIndicesKind),a("WEIGHTS_0",er.MatricesWeightsKind),a("COLOR_0",er.ColorKind);const l=uL.Get(s,this._loader.gltf.bufferViews,r.bufferView);return l._dracoBabylonGeometry||(l._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${l.index}`,l).then((t=>(this.dracoCompression||jy.Default)._decodeMeshToGeometryForGltfAsync(i.name,this._loader.babylonScene,t,n,o).catch((t=>{throw new Error(`${e}: ${t.message}`)}))))),l._dracoBabylonGeometry}))}}dL.RegisterExtension(SL,(e=>new CL(e)));const EL="KHR_lights_punctual";class AL{constructor(e){this.name=EL,this._loader=e,this.enabled=this._loader.isExtensionUsed(EL)}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,uL.Assign(this._lights)}}loadNodeAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>(this._loader._allMaterialsDirtyRequired=!0,this._loader.loadNodeAsync(e,t,(e=>{let t;const n=uL.Get(s,this._lights,r.light),o=n.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,n.type){case"directional":{const e=new cg(o,_e.Backward(),this._loader.babylonScene);e.position.setAll(0),t=e;break}case"point":t=new ex(o,_e.Zero(),this._loader.babylonScene);break;case"spot":{const e=new _g(o,_e.Zero(),_e.Backward(),0,1,this._loader.babylonScene);e.angle=2*(n.spot&&n.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(n.spot&&n.spot.innerConeAngle||0),t=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${s}: Invalid light type (${n.type})`)}t._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,n._babylonLight=t,t.falloffType=ua.FALLOFF_GLTF,t.diffuse=n.color?Ee.FromArray(n.color):Ee.White(),t.intensity=null==n.intensity?1:n.intensity,t.range=null==n.range?Number.MAX_VALUE:n.range,t.parent=e,this._loader._babylonLights.push(t),dL.AddPointerMetadata(t,s),i(e)})))))}}dL.RegisterExtension(EL,(e=>new AL(e)));const PL="KHR_materials_pbrSpecularGlossiness";class IL{constructor(e){this.name=PL,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(PL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loadSpecularGlossinessPropertiesAsync(s,r,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(n).then((()=>{}))}))}_loadSpecularGlossinessPropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.metallic=null,i.roughness=null,t.diffuseFactor?(i.albedoColor=Ee.FromArray(t.diffuseFactor),i.alpha=t.diffuseFactor[3]):i.albedoColor=Ee.White(),i.reflectivityColor=t.specularFactor?Ee.FromArray(t.specularFactor):Ee.White(),i.microSurface=null==t.glossinessFactor?1:t.glossinessFactor,t.diffuseTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,t.diffuseTexture,(e=>{e.name=`${i.name} (Diffuse)`,i.albedoTexture=e}))),t.specularGlossinessTexture&&(s.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,t.specularGlossinessTexture,(e=>{e.name=`${i.name} (Specular Glossiness)`,i.reflectivityTexture=e,i.reflectivityTexture.hasAlpha=!0}))),i.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(s).then((()=>{}))}}dL.RegisterExtension(PL,(e=>new IL(e)));const RL="KHR_materials_unlit";class ML{constructor(e){this.name=RL,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(RL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,(()=>this._loadUnlitPropertiesAsync(e,t,i)))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;i.unlit=!0;const r=t.pbrMetallicRoughness;return r&&(r.baseColorFactor?(i.albedoColor=Ee.FromArray(r.baseColorFactor),i.alpha=r.baseColorFactor[3]):i.albedoColor=Ee.White(),r.baseColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,r.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e})))),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then((()=>{}))}}dL.RegisterExtension(RL,(e=>new ML(e)));const OL="KHR_materials_clearcoat";class DL{constructor(e){this.name=OL,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(OL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadClearCoatPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.clearCoat.isEnabled=!0,i.clearCoat.useRoughnessFromMainTexture=!1,i.clearCoat.remapF0OnInterfaceChange=!1,null!=t.clearcoatFactor?i.clearCoat.intensity=t.clearcoatFactor:i.clearCoat.intensity=0,t.clearcoatTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,(e=>{e.name=`${i.name} (ClearCoat Intensity)`,i.clearCoat.texture=e}))),null!=t.clearcoatRoughnessFactor?i.clearCoat.roughness=t.clearcoatRoughnessFactor:i.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,(e=>{e.name=`${i.name} (ClearCoat Roughness)`,i.clearCoat.textureRoughness=e})))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,(e=>{e.name=`${i.name} (ClearCoat Normal)`,i.clearCoat.bumpTexture=e}))),i.invertNormalMapX=!i.getScene().useRightHandedSystem,i.invertNormalMapY=i.getScene().useRightHandedSystem,null!=t.clearcoatNormalTexture.scale&&(i.clearCoat.bumpTexture.level=t.clearcoatNormalTexture.scale)),Promise.all(s).then((()=>{}))}}dL.RegisterExtension(OL,(e=>new DL(e)));const wL="KHR_materials_iridescence";class NL{constructor(e){this.name=wL,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(wL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.iridescence.isEnabled=!0,i.iridescence.intensity=t.iridescenceFactor??0,i.iridescence.indexOfRefraction=t.iridescenceIor??t.iridescenceIOR??1.3,i.iridescence.minimumThickness=t.iridescenceThicknessMinimum??100,i.iridescence.maximumThickness=t.iridescenceThicknessMaximum??400,t.iridescenceTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,(e=>{e.name=`${i.name} (Iridescence Intensity)`,i.iridescence.texture=e}))),t.iridescenceThicknessTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,(e=>{e.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=e}))),Promise.all(s).then((()=>{}))}}dL.RegisterExtension(wL,(e=>new NL(e)));const FL="KHR_materials_anisotropy";class LL{constructor(e){this.name=FL,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(FL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.anisotropy.isEnabled=!0,i.anisotropy.intensity=t.anisotropyStrength??0,i.anisotropy.angle=t.anisotropyRotation??0,t.anisotropyTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,(e=>{e.name=`${i.name} (Anisotropy Intensity)`,i.anisotropy.texture=e}))),Promise.all(s).then((()=>{}))}}dL.RegisterExtension(FL,(e=>new LL(e)));const BL="KHR_materials_emissive_strength";class kL{constructor(e){this.name=BL,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(BL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then((()=>{this._loadEmissiveProperties(s,r,i)}))))}_loadEmissiveProperties(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);void 0!==t.emissiveStrength&&(i.emissiveIntensity=t.emissiveStrength)}}dL.RegisterExtension(BL,(e=>new kL(e)));const VL="KHR_materials_sheen";class UL{constructor(e){this.name=VL,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(VL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSheenPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.sheen.isEnabled=!0,i.sheen.intensity=1,null!=t.sheenColorFactor?i.sheen.color=Ee.FromArray(t.sheenColorFactor):i.sheen.color=Ee.Black(),t.sheenColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,t.sheenColorTexture,(e=>{e.name=`${i.name} (Sheen Color)`,i.sheen.texture=e}))),void 0!==t.sheenRoughnessFactor?i.sheen.roughness=t.sheenRoughnessFactor:i.sheen.roughness=0,t.sheenRoughnessTexture&&(t.sheenRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,t.sheenRoughnessTexture,(e=>{e.name=`${i.name} (Sheen Roughness)`,i.sheen.textureRoughness=e})))),i.sheen.albedoScaling=!0,i.sheen.useRoughnessFromMainTexture=!1,Promise.all(s).then((()=>{}))}}dL.RegisterExtension(VL,(e=>new UL(e)));const GL="KHR_materials_specular";class zL{constructor(e){this.name=GL,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(GL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSpecularPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return void 0!==t.specularFactor&&(i.metallicF0Factor=t.specularFactor),void 0!==t.specularColorFactor&&(i.metallicReflectanceColor=Ee.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,(e=>{e.name=`${i.name} (Specular F0 Strength)`,i.metallicReflectanceTexture=e,i.useOnlyMetallicFromMetallicReflectanceTexture=!0})))),t.specularColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,(e=>{e.name=`${i.name} (Specular F0 Color)`,i.reflectanceTexture=e}))),Promise.all(s).then((()=>{}))}}dL.RegisterExtension(GL,(e=>new zL(e)));const WL="KHR_materials_ior";class HL{constructor(e){this.name=WL,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(WL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIorPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);return void 0!==t.ior?i.indexOfRefraction=t.ior:i.indexOfRefraction=HL._DEFAULT_IOR,Promise.resolve()}}HL._DEFAULT_IOR=1.5,dL.RegisterExtension(WL,(e=>new HL(e)));const XL="KHR_materials_variants";class YL{constructor(e){this.name=XL,this._loader=e,this.enabled=this._loader.isExtensionUsed(XL)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return YL.GetAvailableVariants(e)}static SelectVariant(e,t){const i=this._GetExtensionMetadata(e);if(!i)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${XL} extension`);const s=e=>{const t=i.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);i.lastSelected=t}selectVariant(e,t){YL.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 ${XL} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(e){YL.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 ${XL} extension`);return t.lastSelected}getLastSelectedVariant(e){return YL.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){return e?._internalMetadata?.gltf?.[XL]||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}_loadMeshPrimitiveAsync(e,t,i,s,r,n){return dL.LoadExtensionAsync(e,r,this.name,((o,a)=>{const l=new Array;return l.push(this._loader._loadMeshPrimitiveAsync(e,t,i,s,r,(t=>{if(n(t),t instanceof ha){const i=dL._GetDrawMode(e,r.mode),s=this._loader.rootBabylonMesh,n=s?s._internalMetadata=s._internalMetadata||{}:{},h=n.gltf=n.gltf||{},c=h[XL]=h[XL]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:t,material:t.material});for(let e=0;e{for(let i=0;i{const i=e;let r=null,n=i;do{if(n=n.parent,!n)return;r=YL._GetExtensionMetadata(n)}while(null===r);if(s&&r===YL._GetExtensionMetadata(s)){n._internalMetadata={};for(const e in s._internalMetadata)n._internalMetadata[e]=s._internalMetadata[e];n._internalMetadata.gltf=[];for(const e in s._internalMetadata.gltf)n._internalMetadata.gltf[e]=s._internalMetadata.gltf[e];n._internalMetadata.gltf[XL]={lastSelected:null,original:[],variants:{}};for(const e of r.original)n._internalMetadata.gltf[XL].original.push({mesh:e.mesh,material:e.material});for(const e in r.variants)if(Object.prototype.hasOwnProperty.call(r.variants,e)){n._internalMetadata.gltf[XL].variants[e]=[];for(const t of r.variants[e])n._internalMetadata.gltf[XL].variants[e].push({mesh:t.mesh,material:t.material})}r=n._internalMetadata.gltf[XL]}for(const e of r.original)e.mesh===t&&(e.mesh=i);for(const e of r.variants[o.name])e.mesh===t&&(e.mesh=i)}))}})))}}}))),Promise.all(l).then((([e])=>e))}))}}dL.RegisterExtension(XL,(e=>new YL(e)));class QL{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:N_.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...QL._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new K,this._scene.onDisposeObservable.addOnce((()=>{this.dispose()})),this._parseScene(),this._setupRenderTargets()}updateOptions(e){if(!Object.keys(e).filter((t=>this._options[t]!==e[t])).length)return;const t={...this._options,...e},i=this._options;this._options=t,t.renderSize===i.renderSize&&t.renderTargetTextureType===i.renderTargetTextureType&&t.generateMipmaps===i.generateMipmaps&&this._opaqueRenderTarget?(this._opaqueRenderTarget.samples=t.samples,this._opaqueRenderTarget.lodGenerationScale=t.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=t.lodGenerationOffset):this._setupRenderTargets()}getOpaqueTarget(){return this._opaqueRenderTarget}_shouldRenderAsTransmission(e){return!!e&&!!(e instanceof zg&&e.subSurface.isRefractionEnabled)}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),Ds.SetImmediate((()=>{this._shouldRenderAsTransmission(e.material)?(e.material.refractionTexture=this._opaqueRenderTarget,-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)}_parseScene(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))}_onMeshMaterialChanged(e){const t=this._transparentMeshesCache.indexOf(e),i=this._opaqueMeshesCache.indexOf(e);this._shouldRenderAsTransmission(e.material)?(e.material instanceof zg&&(e.material.subSurface.refractionTexture=this._opaqueRenderTarget),-1!==i?(this._opaqueMeshesCache.splice(i,1),this._transparentMeshesCache.push(e)):-1===t&&this._transparentMeshesCache.push(e)):-1!==t?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):-1===i&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){return null!==this._opaqueRenderTarget?.getInternalTexture()}_setupRenderTargets(){let e,t;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new ih("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.clearColor=this._options.clearColor?.clone()??this._scene.clearColor.clone(),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.onBeforeBindObservable.add((i=>{t=this._scene.environmentIntensity,this._scene.environmentIntensity=1,e=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?i.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(i.clearColor,this._scene.getEngine().useExactSrgbConversions),this._scene.imageProcessingConfiguration._applyByPostProcess=!0})),this._opaqueRenderTarget.onAfterUnbindObservable.add((()=>{this._scene.environmentIntensity=t,this._scene.imageProcessingConfiguration._applyByPostProcess=e})),this._transparentMeshesCache.forEach((e=>{this._shouldRenderAsTransmission(e.material)&&(e.material.refractionTexture=this._opaqueRenderTarget)}))}dispose(){this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[]}}const jL="KHR_materials_transmission";class KL{constructor(e){this.name=jL,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(jL),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTransparentPropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadTransparentPropertiesAsync(e,t,i,s){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isRefractionEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.useAlbedoToTintRefraction=!0,void 0===s.transmissionFactor)return r.subSurface.refractionIntensity=0,r.subSurface.isRefractionEnabled=!1,Promise.resolve();{r.subSurface.refractionIntensity=s.transmissionFactor;const e=r.getScene();r.subSurface.refractionIntensity&&!e._transmissionHelper?new QL({},r.getScene()):r.subSurface.refractionIntensity&&!e._transmissionHelper?._isRenderTargetValid()&&e._transmissionHelper?._setupRenderTargets()}return r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,s.transmissionTexture?(s.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,s.transmissionTexture,void 0).then((e=>{r.subSurface.refractionIntensityTexture=e,r.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}dL.RegisterExtension(jL,(e=>new KL(e)));const $L="KHR_materials_diffuse_transmission";class qL{constructor(e){this.name=$L,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed($L),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTranslucentPropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadTranslucentPropertiesAsync(e,t,i,s){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isTranslucencyEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,r.subSurface.useAlbedoToTintTranslucency=!1,void 0===s.diffuseTransmissionFactor)return r.subSurface.translucencyIntensity=0,r.subSurface.isTranslucencyEnabled=!1,Promise.resolve();r.subSurface.translucencyIntensity=s.diffuseTransmissionFactor;const n=new Array;return r.subSurface.useGltfStyleTextures=!0,s.diffuseTransmissionTexture&&(s.diffuseTransmissionTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,s.diffuseTransmissionTexture).then((e=>{r.subSurface.translucencyIntensityTexture=e})))),void 0!==s.diffuseTransmissionColorFactor?r.subSurface.translucencyColor=Ee.FromArray(s.diffuseTransmissionColorFactor):r.subSurface.translucencyColor=Ee.White(),s.diffuseTransmissionColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,s.diffuseTransmissionColorTexture).then((e=>{r.subSurface.translucencyColorTexture=e}))),Promise.all(n).then((()=>{}))}}dL.RegisterExtension($L,(e=>new qL(e)));const ZL="KHR_materials_volume";class JL{constructor(e){this.name=ZL,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(ZL),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadVolumePropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadVolumePropertiesAsync(e,t,i,s){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);if(!i.subSurface.isRefractionEnabled&&!i.subSurface.isTranslucencyEnabled||!s.thicknessFactor)return Promise.resolve();i.subSurface.volumeIndexOfRefraction=i.indexOfRefraction;const r=void 0!==s.attenuationDistance?s.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=r,void 0!==s.attenuationColor&&3==s.attenuationColor.length&&i.subSurface.tintColor.copyFromFloats(s.attenuationColor[0],s.attenuationColor[1],s.attenuationColor[2]),i.subSurface.minimumThickness=0,i.subSurface.maximumThickness=s.thicknessFactor,i.subSurface.useThicknessAsDepth=!0,s.thicknessTexture?(s.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,s.thicknessTexture).then((e=>{i.subSurface.thicknessTexture=e,i.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}dL.RegisterExtension(ZL,(e=>new JL(e)));const eB="KHR_materials_dispersion";class tB{constructor(e){this.name=eB,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(eB)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadDispersionPropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadDispersionPropertiesAsync(e,t,i,s){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);return i.subSurface.isRefractionEnabled&&s.dispersion?(i.subSurface.isDispersionEnabled=!0,i.subSurface.dispersion=s.dispersion,Promise.resolve()):Promise.resolve()}}dL.RegisterExtension(eB,(e=>new tB(e)));const iB="KHR_mesh_quantization";class sB{constructor(e){this.name=iB,this.enabled=e.isExtensionUsed(iB)}dispose(){}}dL.RegisterExtension(iB,(e=>new sB(e)));const rB="KHR_texture_basisu";class nB{constructor(e){this.name=rB,this._loader=e,this.enabled=e.isExtensionUsed(rB)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=null==t.sampler?dL.DefaultSampler:uL.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=uL.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}}dL.RegisterExtension(rB,(e=>new nB(e)));const oB="KHR_texture_transform";class aB{constructor(e){this.name=oB,this._loader=e,this.enabled=this._loader.isExtensionUsed(oB)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>this._loader.loadTextureInfoAsync(e,t,(e=>{if(!(e instanceof Pa))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),i(e)}))))}}dL.RegisterExtension(oB,(e=>new aB(e)));const lB="KHR_xmp_json_ld";class hB{constructor(e){this.name=lB,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(lB)}dispose(){this._loader=null}onLoading(){if(null===this._loader.rootBabylonMesh)return;const e=this._loader.gltf.extensions?.KHR_xmp_json_ld,t=this._loader.gltf.asset?.extensions?.KHR_xmp_json_ld;if(e&&t){const i=+t.packet;e.packets&&i2)),new gB(Ft.ANIMATIONTYPE_FLOAT,`${e}.vScale`,_B,(()=>2))],offset:[new gB(Ft.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,uB,(()=>2)),new gB(Ft.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,_B,(()=>2))],rotation:[new gB(Ft.ANIMATIONTYPE_FLOAT,`${e}.wAng`,dB,(()=>1))]}}dL.RegisterExtension(lB,(e=>new hB(e)));class mB extends aL{buildAnimations(e,t,i,s,r){r(e._babylonCamera,this._buildAnimation(t,i,s))}}class gB extends aL{buildAnimations(e,t,i,s,r){for(const n in e._data)r(e._data[n].babylonMaterial,this._buildAnimation(t,i,s))}}class vB extends aL{buildAnimations(e,t,i,s,r){r(e._babylonLight,this._buildAnimation(t,i,s))}}const xB={__array__:{__target__:!0,...hL}},bB={__array__:{__target__:!0,orthographic:{xmag:[new mB(Ft.ANIMATIONTYPE_FLOAT,"orthoLeft",dB,(()=>1)),new mB(Ft.ANIMATIONTYPE_FLOAT,"orthoRight",_B,(()=>1))],ymag:[new mB(Ft.ANIMATIONTYPE_FLOAT,"orthoBottom",dB,(()=>1)),new mB(Ft.ANIMATIONTYPE_FLOAT,"orthoTop",_B,(()=>1))],zfar:[new mB(Ft.ANIMATIONTYPE_FLOAT,"maxZ",uB,(()=>1))],znear:[new mB(Ft.ANIMATIONTYPE_FLOAT,"minZ",uB,(()=>1))]},perspective:{yfov:[new mB(Ft.ANIMATIONTYPE_FLOAT,"fov",uB,(()=>1))],zfar:[new mB(Ft.ANIMATIONTYPE_FLOAT,"maxZ",uB,(()=>1))],znear:[new mB(Ft.ANIMATIONTYPE_FLOAT,"minZ",uB,(()=>1))]}}},TB={nodes:xB,materials:{__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new gB(Ft.ANIMATIONTYPE_COLOR3,"albedoColor",cB,(()=>4)),new gB(Ft.ANIMATIONTYPE_FLOAT,"alpha",(function(e,t,i,s){return t[i+3]*s}),(()=>4))],metallicFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"metallic",uB,(()=>1))],roughnessFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"roughness",uB,(()=>1))],baseColorTexture:{extensions:{KHR_texture_transform:fB("albedoTexture")}},metallicRoughnessTexture:{extensions:{KHR_texture_transform:fB("metallicTexture")}}},emissiveFactor:[new gB(Ft.ANIMATIONTYPE_COLOR3,"emissiveColor",cB,(()=>3))],normalTexture:{scale:[new gB(Ft.ANIMATIONTYPE_FLOAT,"bumpTexture.level",uB,(()=>1))],extensions:{KHR_texture_transform:fB("bumpTexture")}},occlusionTexture:{strength:[new gB(Ft.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",uB,(()=>1))],extensions:{KHR_texture_transform:fB("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:fB("emissiveTexture")}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:[new gB(Ft.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",uB,(()=>1))],anisotropyRotation:[new gB(Ft.ANIMATIONTYPE_FLOAT,"anisotropy.angle",uB,(()=>1))],anisotropyTexture:{extensions:{KHR_texture_transform:fB("anisotropy.texture")}}},KHR_materials_clearcoat:{clearcoatFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",uB,(()=>1))],clearcoatRoughnessFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",uB,(()=>1))],clearcoatTexture:{extensions:{KHR_texture_transform:fB("clearCoat.texture")}},clearcoatNormalTexture:{scale:[new gB(Ft.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",uB,(()=>1))],extensions:{KHR_texture_transform:fB("clearCoat.bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:fB("clearCoat.textureRoughness")}}},KHR_materials_dispersion:{dispersion:[new gB(Ft.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",uB,(()=>1))]},KHR_materials_emissive_strength:{emissiveStrength:[new gB(Ft.ANIMATIONTYPE_FLOAT,"emissiveIntensity",uB,(()=>1))]},KHR_materials_ior:{ior:[new gB(Ft.ANIMATIONTYPE_FLOAT,"indexOfRefraction",uB,(()=>1))]},KHR_materials_iridescence:{iridescenceFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"iridescence.intensity",uB,(()=>1))],iridescenceIor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",uB,(()=>1))],iridescenceThicknessMinimum:[new gB(Ft.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",uB,(()=>1))],iridescenceThicknessMaximum:[new gB(Ft.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",uB,(()=>1))],iridescenceTexture:{extensions:{KHR_texture_transform:fB("iridescence.texture")}},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:fB("iridescence.thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:[new gB(Ft.ANIMATIONTYPE_COLOR3,"sheen.color",cB,(()=>3))],sheenRoughnessFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"sheen.roughness",uB,(()=>1))],sheenColorTexture:{extensions:{KHR_texture_transform:fB("sheen.texture")}},sheenRoughnessTexture:{extensions:{KHR_texture_transform:fB("sheen.textureRoughness")}}},KHR_materials_specular:{specularFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"metallicF0Factor",uB,(()=>1))],specularColorFactor:[new gB(Ft.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",cB,(()=>3))],specularTexture:{extensions:{KHR_texture_transform:fB("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:fB("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",uB,(()=>1))],transmissionTexture:{extensions:{KHR_texture_transform:fB("subSurface.refractionIntensityTexture")}}},KHR_materials_volume:{attenuationColor:[new gB(Ft.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",cB,(()=>3))],attenuationDistance:[new gB(Ft.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",uB,(()=>1))],thicknessFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",uB,(()=>1))],thicknessTexture:{extensions:{KHR_texture_transform:fB("subSurface.thicknessTexture")}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",uB,(()=>1))],diffuseTransmissionTexture:{extensions:{KHR_texture_transform:fB("subSurface.translucencyIntensityTexture")}},diffuseTransmissionColorFactor:[new gB(Ft.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",cB,(()=>3))],diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:fB("subSurface.translucencyColorTexture")}}}}}},cameras:bB,extensions:{KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new vB(Ft.ANIMATIONTYPE_COLOR3,"diffuse",cB,(()=>3))],intensity:[new vB(Ft.ANIMATIONTYPE_FLOAT,"intensity",uB,(()=>1))],range:[new vB(Ft.ANIMATIONTYPE_FLOAT,"range",uB,(()=>1))],spot:{innerConeAngle:[new vB(Ft.ANIMATIONTYPE_FLOAT,"innerAngle",pB,(()=>1))],outerConeAngle:[new vB(Ft.ANIMATIONTYPE_FLOAT,"angle",pB,(()=>1))]}}}}}};class yB{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t,i=this._gltf,s=this._infoTree;if(!e.startsWith("/"))throw new Error("Path must start with a /");const r=e.split("/");r.shift();for(const n of r){if(s.__array__)s=s.__array__;else if(s=s[n],!s)throw new Error(`Path ${e} is invalid`);if(void 0===i)throw new Error(`Path ${e} is invalid`);i=i[n],s.__target__&&(t=i)}return{object:t,info:s}}}const SB="KHR_animation_pointer";class CB extends yB{constructor(e){super(e,TB)}}class EB{constructor(e){this.name=SB,this._loader=e,this._pathToObjectConverter=new CB(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(SB)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,t,i,s,r){const n=s.target.extensions?.KHR_animation_pointer;if(!n||!this._pathToObjectConverter)return null;"pointer"!==s.target.path&&Ne.Warn(`${e}/target/path: Value (${s.target.path}) must be (pointer) when using the ${this.name} extension`),null!=s.target.node&&Ne.Warn(`${e}/target/node: Value (${s.target.node}) must not be present when using the ${this.name} extension`);const o=`${e}/extensions/${this.name}`,a=n.pointer;if(!a)throw new Error(`${o}: Pointer is missing`);try{const n=this._pathToObjectConverter.convert(a);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,n,r)}catch(e){return Ne.Warn(`${o}/pointer: Invalid pointer (${a}) skipped`),null}}}dL.RegisterExtension(SB,(e=>new EB(e)));const AB="MSFT_audio_emitter";class PB{constructor(e){this.name=AB,this._loader=e,this.enabled=this._loader.isExtensionUsed(AB)}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,uL.Assign(this._clips),uL.Assign(this._emitters)}}loadSceneAsync(e,t){return dL.LoadExtensionAsync(e,t,this.name,((i,s)=>{const r=new Array;r.push(this._loader.loadSceneAsync(e,t));for(const e of s.emitters){const t=uL.Get(`${i}/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(`${i}: Direction or Distance properties are not allowed on emitters attached to a scene`);r.push(this._loadEmitterAsync(`${i}/emitters/${t.index}`,t))}return Promise.all(r).then((()=>{}))}))}loadNodeAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((e,s)=>{const r=new Array;return this._loader.loadNodeAsync(e,t,(t=>{for(const i of s.emitters){const s=uL.Get(`${e}/emitters`,this._emitters,i);r.push(this._loadEmitterAsync(`${e}/emitters/${s.index}`,s).then((()=>{for(const e of s._babylonSounds)e.attachToMesh(t),null==s.innerAngle&&null==s.outerAngle||(e.setLocalDirectionToMesh(_e.Forward()),e.setDirectionalCone(2*Ds.ToDegrees(null==s.innerAngle?Math.PI:s.innerAngle),2*Ds.ToDegrees(null==s.outerAngle?Math.PI:s.outerAngle),0))})))}i(t)})).then((e=>Promise.all(r).then((()=>e))))}))}loadAnimationAsync(e,t){return dL.LoadExtensionAsync(e,t,this.name,((i,s)=>this._loader.loadAnimationAsync(e,t).then((r=>{const n=new Array;uL.Assign(s.events);for(const o of s.events)n.push(this._loadAnimationEventAsync(`${i}/events/${o.index}`,e,t,o,r));return Promise.all(n).then((()=>r))}))))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const s=uL.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);i=this._loader.loadBufferViewAsync(`/bufferViews/${s.index}`,s)}return t._objectURL=i.then((e=>URL.createObjectURL(new Blob([e],{type:t.mimeType})))),t._objectURL}_loadEmitterAsync(e,t){if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){const e=new Array,i=t.name||`emitter${t.index}`,s={loop:!1,autoplay:!1,volume:null==t.volume?1:t.volume};for(let r=0;r{const n=t._babylonSounds[r]=new ma(i,e,this._loader.babylonScene,null,s);n.refDistance=t.refDistance||1,n.maxDistance=t.maxDistance||256,n.rolloffFactor=t.rolloffFactor||1,n.distanceModel=t.distanceModel||"exponential"})))}const r=Promise.all(e).then((()=>{const e=t.clips.map((e=>e.weight||1)),i=new xa(t.loop||!1,t._babylonSounds,e);t.innerAngle&&(i.directionalConeInnerAngle=2*Ds.ToDegrees(t.innerAngle)),t.outerAngle&&(i.directionalConeOuterAngle=2*Ds.ToDegrees(t.outerAngle)),t.volume&&(i.volume=t.volume),t._babylonData.sound=i}));t._babylonData={loaded:r}}return t._babylonData.loaded}_getEventAction(e,t,i,s,r){switch(i){case"play":return e=>{const i=(r||0)+(e-s);t.play(i)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${i}`)}}_loadAnimationEventAsync(e,t,i,s,r){if(0==r.targetedAnimations.length)return Promise.resolve();const n=r.targetedAnimations[0],o=s.emitter,a=uL.Get(`/extensions/${this.name}/emitters`,this._emitters,o);return this._loadEmitterAsync(e,a).then((()=>{const t=a._babylonData.sound;if(t){const i=new fn(s.time,this._getEventAction(e,t,s.action,s.time,s.startOffset));n.animation.addEvent(i),r.onAnimationGroupEndObservable.add((()=>{t.stop()})),r.onAnimationGroupPauseObservable.add((()=>{t.pause()}))}}))}}dL.RegisterExtension(AB,(e=>new PB(e)));const IB="MSFT_lod";class RB{constructor(e){this.name=IB,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new K,this.onMaterialLODsLoadedObservable=new K,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.enabled=this._loader.isExtensionUsed(IB)}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{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{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 i=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),i}loadNodeAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((e,s)=>{let r;const n=this._getLODs(e,t,this._loader.gltf.nodes,s.ids);this._loader.logOpen(`${e}`);for(let e=0;e{i(e),e.setEnabled(!1)},o=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,s).then((t=>{if(0!==e){const t=n[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=o:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(o))}return this._loader.logClose(),r}))}_loadMaterialAsync(e,t,i,s,r){return this._nodeIndexLOD?null:dL.LoadExtensionAsync(e,t,this.name,((e,n)=>{let o;const a=this._getLODs(e,t,this._loader.gltf.materials,n.ids);this._loader.logOpen(`${e}`);for(let e=0;e{0===e&&r(t)})).then((t=>{if(0!==e){r(t);const i=a[e-1]._data;i[s]&&(this._disposeMaterials([i[s].babylonMaterial]),delete i[s])}return t}));this._materialPromiseLODs[e]=this._materialPromiseLODs[e]||[],0===e?o=n:(this._materialIndexLOD=null,this._materialPromiseLODs[e].push(n))}return this._loader.logClose(),o}))}_loadUriAsync(e,t,i){if(null!==this._nodeIndexLOD){this._loader.log("deferred");const s=this._nodeIndexLOD-1;return this._nodeSignalLODs[s]=this._nodeSignalLODs[s]||new VI,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const s=this._materialIndexLOD-1;return this._materialSignalLODs[s]=this._materialSignalLODs[s]||new VI,this._materialSignalLODs[s].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}return null}loadBufferAsync(e,t,i,s){if(this._loader.parent.useRangeRequests&&!t.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const t=(e,t)=>{const r=i,n=r+s-1;let o=e[t];return o?(o.start=Math.min(o.start,r),o.end=Math.max(o.end,n)):(o={start:r,end:n,loaded:new VI},e[t]=o),o.loaded.promise.then((e=>new Uint8Array(e.buffer,e.byteOffset+i-o.start,s)))};return this._loader.log("deferred"),null!==this._nodeIndexLOD?t(this._nodeBufferLODs,this._nodeIndexLOD):null!==this._materialIndexLOD?t(this._materialBufferLODs,this._materialIndexLOD):t(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const i=e[t];i&&(this._loader.log(`Loading buffer range [${i.start}-${i.end}]`),this._loader.bin.readAsync(i.start,i.end-i.start+1).then((e=>{i.loaded.resolve(e)}),(e=>{i.loaded.reject(e)})))}_getLODs(e,t,i,s){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const r=[];for(let t=s.length-1;t>=0;t--)if(r.push(uL.Get(`${e}/ids/${s[t]}`,i,s[t])),r.length===this.maxLODsToLoad)return r;return r.push(t),r}_disposeTransformNode(e){const t=[],i=e.material;i&&t.push(i);for(const i of e.getChildMeshes())i.material&&t.push(i.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 i of e){for(const e of i.getActiveTextures())t[e.uniqueId]=e;i.dispose()}for(const e in t)for(const i of this._loader.babylonScene.materials)i.hasTexture(t[e])&&delete t[e];for(const e in t)t[e].dispose()}}dL.RegisterExtension(IB,(e=>new RB(e)));const MB="MSFT_minecraftMesh";class OB{constructor(e){this.name=MB,this._loader=e,this.enabled=this._loader.isExtensionUsed(MB)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtraAsync(e,t,this.name,((s,r)=>{if(r){if(!(i instanceof zg))throw new Error(`${s}: Material type not supported`);const r=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,r}return null}))}}dL.RegisterExtension(MB,(e=>new OB(e)));const DB="MSFT_sRGBFactors";class wB{constructor(e){this.name=DB,this._loader=e,this.enabled=this._loader.isExtensionUsed(DB)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtraAsync(e,t,this.name,((s,r)=>{if(r){if(!(i instanceof zg))throw new Error(`${s}: Material type not supported`);const r=this._loader.loadMaterialPropertiesAsync(e,t,i),n=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,n),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,n),r}return null}))}}dL.RegisterExtension(DB,(e=>new wB(e)));const NB={"lifecycle/onStart":xw.ClassName,"lifecycle/onTick":Tw.ClassName,log:oO.ClassName,"flow/delay":mO.ClassName,"customEvent/send":uO.ClassName,"customEvent/receive":bw.ClassName,"flow/sequence":CO.ClassName,"world/get":DO.ClassName,"world/set":cO.ClassName,"flow/doN":_O.ClassName,"variable/get":RO.ClassName,"variable/set":aO.ClassName,"flow/whileLoop":TO.ClassName,"math/random":tD.ClassName,"math/e":sD.ClassName,"math/pi":rD.ClassName,"math/inf":nD.ClassName,"math/nan":oD.ClassName,"math/abs":lD.ClassName,"math/sign":hD.ClassName,"math/trunc":cD.ClassName,"math/floor":uD.ClassName,"math/ceil":dD.ClassName,"math/fract":_D.ClassName,"math/neg":pD.ClassName,"math/add":qO.ClassName,"math/sub":ZO.ClassName,"math/mul":JO.ClassName,"math/div":eD.ClassName,"math/rem":mD.ClassName,"math/min":gD.ClassName,"math/max":vD.ClassName,"math/clamp":TD.ClassName,"math/saturate":SD.ClassName,"math/mix":CD.ClassName,"math/eq":ED.ClassName,"math/lt":PD.ClassName,"math/le":ID.ClassName,"math/gt":RD.ClassName,"math/ge":MD.ClassName,"math/isnan":OD.ClassName,"math/isinf":DD.ClassName,"math/rad":wD.ClassName,"math/deg":ND.ClassName,"math/sin":FD.ClassName,"math/cos":LD.ClassName,"math/tan":BD.ClassName,"math/asin":kD.ClassName,"math/acos":VD.ClassName,"math/atan":UD.ClassName,"math/atan2":GD.ClassName,"math/sinh":zD.ClassName,"math/cosh":WD.ClassName,"math/tanh":HD.ClassName,"math/asinh":XD.ClassName,"math/acosh":YD.ClassName,"math/atanh":QD.ClassName,"math/exp":jD.ClassName,"math/log":KD.ClassName,"math/log2":$D.ClassName,"math/log10":qD.ClassName,"math/sqrt":ZD.ClassName,"math/cbrt":JD.ClassName,"math/pow":ew.ClassName,"math/length":tw.ClassName,"math/normalize":iw.ClassName,"math/dot":iD.ClassName,"math/cross":sw.ClassName,"math/rotate2d":rw.ClassName,"math/rotate3d":nw.ClassName,"math/transpose":ow.ClassName,"math/determinant":aw.ClassName,"math/inverse":lw.ClassName,"math/matmul":hw.ClassName,"math/not":cw.ClassName,"math/and":uw.ClassName,"math/or":dw.ClassName,"math/xor":_w.ClassName,"math/asr":fw.ClassName,"math/lsl":pw.ClassName,"math/clz":mw.ClassName,"math/ctz":gw.ClassName,"math/popcnt":vw.ClassName},FB={float2:"Vector2",float3:"Vector3",float4:"Vector4",float4x4:"Matrix",int:"FlowGraphInteger"};function LB(e,t,i){if(void 0!==e.type){const s=t.types&&t.types[e.type];if(!s)throw new Error(`${i}: Unknown type: ${e.type}`);const r=s.signature;if(!r)throw new Error(`${i}: Type ${e.type} has no signature`);const n=FB[r];return{value:e.value,className:n}}return e.value}function BB(e,t,i){const s=NB[t.type];if(!s)throw new Error(`/extensions/KHR_interactivity/nodes/${e}: Unknown block type: ${t.type}`);const r=e.toString(),n=function(e,t,i){const s={},r=e.configuration??[];for(const e of r)if("customEvent"===e.id){const r=t.customEvents&&t.customEvents[e.value];if(!r)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown custom event: ${e.value}`);s.eventId=r.id,s.eventData=r.values.map((e=>e.id))}else if("variable"===e.id){const r=t.variables&&t.variables[e.value];if(!r)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown variable: ${e.value}`);s.variableName=r.id}else if("path"===e.id){const t=e.value;s.path=t}else s[e.id]=LB(e,t,`/extensions/KHR_interactivity/nodes/${i}`);return s}(t,i,r);return{className:s,config:n,uniqueId:r,metadata:t.metadata,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[]}}class kB extends yB{constructor(e){super(e,VB)}}const VB={nodes:{__array__:{__target__:!0,translation:{type:"Vector3",get:e=>e._babylonTransformNode.position,set:(e,t)=>{t._babylonTransformNode.position=e},getObject:e=>e._babylonTransformNode}}}},UB="KHR_interactivity";class GB{constructor(e){this._loader=e,this.name=UB,this.enabled=this._loader.isExtensionUsed(UB),this._pathConverter=new kB(this._loader.gltf)}dispose(){this._loader=null,delete this._pathConverter}onReady(){if(!this._loader.babylonScene||!this._pathConverter)return;const e=this._loader.babylonScene,t=this._loader.gltf.extensions?.KHR_interactivity,i=function(e){const t={uniqueId:Cs(),_userVariables:{},_connectionValues:{}},i=[t],s=[];for(let t=0;te.name===a));h||(h={uniqueId:Cs(),name:a,_connectionType:EM.Input,connectedPointIds:[]},l.signalInputs.push(h)),h.connectedPointIds.push(r.uniqueId),r.connectedPointIds.push(h.uniqueId)}const a=r.values??[];for(const r of a){const o=r.id,a={uniqueId:Cs(),name:o,_connectionType:EM.Input,connectedPointIds:[]};if(n.dataInputs.push(a),void 0!==r.value){const s=LB(r,e,`/extensions/KHR_interactivity/nodes/${i}`);t._connectionValues[a.uniqueId]=s}else{if(void 0===r.node||void 0===r.socket)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Invalid socket ${o} in node ${i}`);{const e=r.node,t=r.socket,n=s[e];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Could not find node with id ${e} that connects its output with node${i}'s input ${o}`);let l=n.dataOutputs.find((e=>e.name===t));l||(l={uniqueId:Cs(),name:t,_connectionType:EM.Output,connectedPointIds:[]},n.dataOutputs.push(l)),a.connectedPointIds.push(l.uniqueId),l.connectedPointIds.push(a.uniqueId)}}}}const r=e.variables??[];for(let i=0;inew GB(e)));const zB="ExtrasAsMetadata";class WB{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const i=e.metadata=e.metadata||{};(i.gltf=i.gltf||{}).extras=t.extras}}constructor(e){this.name=zB,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}createMaterial(e,t,i){const s=this._loader.createMaterial(e,t,i);return this._assignExtras(s,t),s}}dL.RegisterExtension(zB,(e=>new WB(e)));class HB{constructor(){this.materials=[]}parseMTL(e,t,i,s){if(t instanceof ArrayBuffer)return;const r=t.split("\n"),n=/\s+/;let o,a=null;for(let t=0;t=0?l.substring(0,h):l;c=c.toLowerCase();const u=h>=0?l.substring(h+1).trim():"";if("newmtl"===c)a&&this.materials.push(a),e._blockEntityCollection=!!s,a=new cu(u,e),a._parentContainer=s,e._blockEntityCollection=!1;else if("kd"===c&&a)o=u.split(n,3).map(parseFloat),a.diffuseColor=Ee.FromArray(o);else if("ka"===c&&a)o=u.split(n,3).map(parseFloat),a.ambientColor=Ee.FromArray(o);else if("ks"===c&&a)o=u.split(n,3).map(parseFloat),a.specularColor=Ee.FromArray(o);else if("ke"===c&&a)o=u.split(n,3).map(parseFloat),a.emissiveColor=Ee.FromArray(o);else if("ns"===c&&a)a.specularPower=parseFloat(u);else if("d"===c&&a)a.alpha=parseFloat(u);else if("map_ka"===c&&a)a.ambientTexture=HB._GetTexture(i,u,e);else if("map_kd"===c&&a)a.diffuseTexture=HB._GetTexture(i,u,e);else if("map_ks"===c&&a)a.specularTexture=HB._GetTexture(i,u,e);else if("map_ns"===c);else if("map_bump"===c&&a){const t=u.split(n),s=t.indexOf("-bm");let r=null;s>=0&&(r=t[s+1],t.splice(s,2)),a.bumpTexture=HB._GetTexture(i,t.join(" "),e),a.bumpTexture&&null!==r&&(a.bumpTexture.level=parseFloat(r))}else"map_d"===c&&a&&(a.opacityTexture=HB._GetTexture(i,u,e))}a&&this.materials.push(a)}static _GetTexture(e,t,i){if(!t)return null;let s=e;if("file:"===e){let e=t.lastIndexOf("\\");-1===e&&(e=t.lastIndexOf("/")),s+=e>-1?t.substr(e+1):t}else s+=t;return new Pa(s,i,!1,HB.INVERT_TEXTURE_Y)}}HB.INVERT_TEXTURE_Y=!0;class XB{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],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 Ae(.5,.5,.5,1),this._materialToUse=e,this._babylonMeshesArray=t,this._loadingOptions=i}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});const i=e[t[0]].normals.indexOf(t[1]);return-1===i?-1:e[t[0]].idx[i]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});const i=e[t[0]].normals.indexOf(t[1]);return 1!=i&&t[2]===e[t[0]].uv[i]?e[t[0]].idx[i]:-1}_setData(e,t,i,s,r,n,o){let a;a=this._loadingOptions.optimizeWithUV?this._isInArrayUV(this._tuplePosNorm,[e,i,t]):this._isInArray(this._tuplePosNorm,[e,i]),-1===a?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(s),this._wrappedUvsForBabylon.push(r),this._wrappedNormalsForBabylon.push(n),void 0!==o&&this._wrappedColorsForBabylon.push(o),this._tuplePosNorm[e].normals.push(i),this._tuplePosNorm[e].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e].uv.push(t)):this._indicesForBabylon.push(a)}_unwrapData(){for(let e=0;e0&&(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._handledMesh.normals=this._unwrappedNormalsForBabylon.slice(),this._handledMesh.uvs=this._unwrappedUVForBabylon.slice(),this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0)}_optimizeNormals(e){const t=e.getVerticesData(er.PositionKind),i=e.getVerticesData(er.NormalKind),s={};if(!t||!i)return;for(let e=0;ethis._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=1):i.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 n=t.split("\n");for(let e=0;e=7){const e=parseFloat(i[4]),t=parseFloat(i[5]),s=parseFloat(i[6]);this._colors.push(new Ae(e>1?e/255:e,t>1?t/255:t,s>1?s/255:s,7===i.length||void 0===i[7]?1:parseFloat(i[7])))}else this._colors.push(this._grayColor)}else if(null!==(i=XB.NormalPattern.exec(t)))this._normals.push(new _e(parseFloat(i[1]),parseFloat(i[2]),parseFloat(i[3])));else if(null!==(i=XB.UVPattern.exec(t)))this._uvs.push(new de(parseFloat(i[1])*this._loadingOptions.UVScaling.x,parseFloat(i[2])*this._loadingOptions.UVScaling.y));else if(null!==(i=XB.FacePattern3.exec(t)))this._setDataForCurrentFaceWithPattern3(i[1].trim().split(" "),1);else if(null!==(i=XB.FacePattern4.exec(t)))this._setDataForCurrentFaceWithPattern4(i[1].trim().split(" "),1);else if(null!==(i=XB.FacePattern5.exec(t)))this._setDataForCurrentFaceWithPattern5(i[1].trim().split(" "),1);else if(null!==(i=XB.FacePattern2.exec(t)))this._setDataForCurrentFaceWithPattern2(i[1].trim().split(" "),1);else if(null!==(i=XB.FacePattern1.exec(t)))this._setDataForCurrentFaceWithPattern1(i[1].trim().split(" "),1);else if(null!==(i=XB.LinePattern1.exec(t)))this._setDataForCurrentFaceWithPattern1(i[1].trim().split(" "),0);else if(null!==(i=XB.LinePattern2.exec(t)))this._setDataForCurrentFaceWithPattern2(i[1].trim().split(" "),0);else if(null!==(i=XB.LinePattern3.exec(t)))this._setDataForCurrentFaceWithPattern3(i[1].trim().split(" "),0);else if(XB.GroupDescriptor.test(t)||XB.ObjectDescriptor.test(t)){const e={name:t.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:XB.ObjectDescriptor.test(t)};this._addPreviousObjMesh(),this._meshesFromObj.push(e),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(XB.UseMtlDescriptor.test(t)){if(this._materialNameFromObj=t.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 XB.MtlLibGroupDescriptor.test(t)?r(t.substring(7).trim()):XB.SmoothDescriptor.test(t)||Ne.Log("Unhandled expression at line : "+t)}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._handledMesh.normals=this._unwrappedNormalsForBabylon,this._handledMesh.uvs=this._unwrappedUVForBabylon,this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon)),!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._colors.length)for(const e of this._colors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);this._materialNameFromObj||(e=new cu(Yn.RandomId(),i),e.pointsCloud=!0,this._materialNameFromObj=e.name,this._normals.length||(e.disableLighting=!0,e.emissiveColor=Ee.White()))}this._meshesFromObj.push({name:Yn.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:e,isObject:!0})}for(let t=0;t=0;--e)if(this._meshesFromObj[e].isObject&&this._meshesFromObj[e]._babylonMesh){r.parent=this._meshesFromObj[e]._babylonMesh;break}if(this._materialToUse.push(this._meshesFromObj[t].materialName),0===this._handledMesh.positions?.length){this._babylonMeshesArray.push(r);continue}const n=new Wn;if(n.uvs=this._handledMesh.uvs,n.indices=this._handledMesh.indices,n.positions=this._handledMesh.positions,this._loadingOptions.computeNormals){const e=new Array;Wn.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,e),n.normals=e}else n.normals=this._handledMesh.normals;this._loadingOptions.importVertexColors&&(n.colors=this._handledMesh.colors),n.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)}}}XB.ObjectDescriptor=/^o/,XB.GroupDescriptor=/^g/,XB.MtlLibGroupDescriptor=/^mtllib /,XB.UseMtlDescriptor=/^usemtl /,XB.SmoothDescriptor=/^s /,XB.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/,XB.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,XB.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,XB.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/,XB.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,XB.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,XB.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,XB.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,XB.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/,XB.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/,XB.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;class YB{static get INVERT_TEXTURE_Y(){return HB.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){HB.INVERT_TEXTURE_Y=e}constructor(e){this.name="obj",this.extensions=".obj",this._assetContainer=null,this._loadingOptions=e||YB._DefaultLoadingOptions}static get _DefaultLoadingOptions(){return{computeNormals:YB.COMPUTE_NORMALS,optimizeNormals:YB.OPTIMIZE_NORMALS,importVertexColors:YB.IMPORT_VERTEX_COLORS,invertY:YB.INVERT_Y,invertTextureY:YB.INVERT_TEXTURE_Y,UVScaling:YB.UV_SCALING,materialLoadingFailsSilently:YB.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:YB.OPTIMIZE_WITH_UV,skipMaterials:YB.SKIP_MATERIALS,useLegacyBehavior:YB.USE_LEGACY_BEHAVIOR}}_loadMTL(e,t,i,s){const r=t+e;Ds.LoadFile(r,i,void 0,void 0,!1,((e,t)=>{s(r,t)}))}createPlugin(){return new YB(YB._DefaultLoadingOptions)}canDirectLoad(){return!1}importMeshAsync(e,t,i,s){return this._parseSolid(e,t,i,s).then((e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]})))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then((()=>{}))}loadAssetContainerAsync(e,t,i){const s=new pa(e);return this._assetContainer=s,this.importMeshAsync(null,e,t,i).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}))}_parseSolid(e,t,i,s){let r="";const n=new HB,o=[],a=[];new XB(o,a,this._loadingOptions).parse(e,i,t,this._assetContainer,(e=>{r=e}));const l=[];return""===r||this._loadingOptions.skipMaterials||l.push(new Promise(((e,i)=>{this._loadMTL(r,s,(l=>{try{n.parseMTL(t,l,s,this._assetContainer);for(let e=0;e-1;)i.push(s),t=s+1;if(-1===s&&0===i.length)n.materials[e].dispose();else for(let t=0;t{Ds.Warn(`Error downloading MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?e():i(s)}))}))),Promise.all(l).then((()=>a))}}YB.OPTIMIZE_WITH_UV=!0,YB.INVERT_Y=!1,YB.IMPORT_VERTEX_COLORS=!1,YB.COMPUTE_NORMALS=!1,YB.OPTIMIZE_NORMALS=!1,YB.UV_SCALING=new de(1,1),YB.SKIP_MATERIALS=!1,YB.MATERIAL_LOADING_FAILS_SILENTLY=!0,YB.USE_LEGACY_BEHAVIOR=!1,fl&&fl.RegisterPlugin(new YB);class QB{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="stl",this.extensions={".stl":{isBinary:!0}}}importMesh(e,t,i,s,r){let n;if("string"!=typeof i){if(this._isBinary(i)){const e=new ha("stlmesh",t);return this._parseBinary(e,i),r&&r.push(e),!0}i=(new TextDecoder).decode(new Uint8Array(i))}for(;n=this.solidPattern.exec(i);){let i=n[1];const s=n[3];if(s&&i!=s)return Ds.Error("Error in STL, solid name != endsolid name"),!1;if(e&&i)if(e instanceof Array){if(!e.indexOf(i))continue}else if(i!==e)continue;i=i||"stlmesh";const o=new ha(i,t);this._parseASCII(o,n[2]),r&&r.push(o)}return!0}load(e,t,i){return this.importMesh(null,e,t,i,null)}loadAssetContainer(e,t,i){const s=new pa(e);return e._blockEntityCollection=!0,this.importMesh(null,e,t,i,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 i=[115,111,108,105,100];for(let e=0;e<5;e++)if(t.getUint8(e)!==i[e])return!0;return!1}_parseBinary(e,t){const i=new DataView(t),s=i.getUint32(80,!0);let r=0;const n=new Float32Array(3*s*3),o=new Float32Array(3*s*3),a=new Uint32Array(3*s);let l=0;for(let e=0;e{if(e.tryDownload&&document){const i=new Blob([t],{type:"text/plain"}),s=URL.createObjectURL(i),r=e.fileName?e.fileName:"bitbybit-dev.step",n=document.createElement("a");n.href=s,n.target="_self",n.download=r,n.click(),n.remove()}return t}))}}class qB{constructor(e){this.occWorkerManager=e}makeCompound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.compound.makeCompound",e)}}class ZB{constructor(e){this.occWorkerManager=e}line(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.line",e)}arcThroughThreePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcThroughThreePoints",e)}arcThroughTwoPointsAndTangent(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcThroughTwoPointsAndTangent",e)}arcFromCircleAndTwoPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCircleAndTwoPoints",e)}arcFromCircleAndTwoAngles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCircleAndTwoAngles",e)}arcFromCirclePointAndAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCirclePointAndAngle",e)}createCircleEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.createCircleEdge",e)}createEllipseEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.createEllipseEdge",e)}removeInternalEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.removeInternalEdges",e)}makeEdgeFromGeom2dCurveAndSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.makeEdgeFromGeom2dCurveAndSurface",e)}getEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdge",e)}getEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdges",e)}getEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesAlongWire",e)}getCircularEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgesAlongWire",e)}getLinearEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getLinearEdgesAlongWire",e)}getCornerPointsOfEdgesForShape(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCornerPointsOfEdgesForShape",e)}getEdgeLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgeLength",e)}getEdgesLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesLengths",e)}getEdgeCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgeCenterOfMass",e)}getEdgesCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesCentersOfMass",e)}getCircularEdgeCenterPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgeCenterPoint",e)}getCircularEdgeRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgeRadius",e)}getCircularEdgePlaneDirection(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgePlaneDirection",e)}pointOnEdgeAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.pointOnEdgeAtParam",e)}edgesToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.edgesToPoints",e)}reversedEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.reversedEdge",e)}tangentOnEdgeAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.tangentOnEdgeAtParam",e)}pointOnEdgeAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.pointOnEdgeAtLength",e)}tangentOnEdgeAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.tangentOnEdgeAtLength",e)}startPointOnEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.startPointOnEdge",e)}endPointOnEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.endPointOnEdge",e)}divideEdgeByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.divideEdgeByParamsToPoints",e)}divideEdgeByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.divideEdgeByEqualDistanceToPoints",e)}constraintTanLinesFromTwoPtsToCircle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesFromTwoPtsToCircle",e)}constraintTanLinesFromPtToCircle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesFromPtToCircle",e)}constraintTanLinesOnTwoCircles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesOnTwoCircles",e)}constraintTanCirclesOnTwoCircles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanCirclesOnTwoCircles",e)}constraintTanCirclesOnCircleAndPnt(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanCirclesOnCircleAndPnt",e)}}class JB{constructor(e){this.occWorkerManager=e}createFaceFromWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWire",e)}createFaceFromWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWires",e)}createFacesFromWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFacesFromWires",e)}createFaceFromMultipleCircleTanWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromMultipleCircleTanWires",e)}createFaceFromMultipleCircleTanWireCollections(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromMultipleCircleTanWireCollections",e)}faceFromSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.faceFromSurface",e)}faceFromSurfaceAndWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.faceFromSurfaceAndWire",e)}createPolygonFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createPolygonFace",e)}createCircleFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createCircleFace",e)}createEllipseFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createEllipseFace",e)}createSquareFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createSquareFace",e)}createRectangleFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createRectangleFace",e)}getFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFace",e)}getFaces(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaces",e)}reversedFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.reversedFace",e)}subdivideToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPoints",e)}subdivideToPointsControlled(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPointsControlled",e)}subdivideToNormals(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToNormals",e)}subdivideToUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToUV",e)}pointOnUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.pointOnUV",e)}normalOnUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.normalOnUV",e)}pointsOnUVs(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.pointsOnUVs",e)}normalsOnUVs(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.normalsOnUVs",e)}subdivideToPointsOnParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPointsOnParam",e)}getUMinBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getUMinBound",e)}getUMaxBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getUMaxBound",e)}getVMinBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getVMinBound",e)}getVMaxBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getVMaxBound",e)}getFaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaceArea",e)}getFacesAreas(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFacesAreas",e)}getFaceCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaceCenterOfMass",e)}getFacesCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFacesCentersOfMass",e)}filterFacePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.filterFacePoints",e)}}class ek{constructor(e){this.occWorkerManager=e}fromClosedShell(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.fromClosedShell",e)}createBox(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createBox",e)}createCube(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCube",e)}createBoxFromCorner(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createBoxFromCorner",e)}createCylinder(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCylinder",e)}createCylindersOnLines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCylindersOnLines",e)}createSphere(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createSphere",e)}createCone(e){return e.angle=e.angle*(Math.PI/180),this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCone",e)}getSolidSurfaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidSurfaceArea",e)}getSolidVolume(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidVolume",e)}getSolidsVolumes(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidsVolumes",e)}getSolidCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidCenterOfMass",e)}getSolidsCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidsCentersOfMass",e)}getSolids(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolids",e)}filterSolidPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.filterSolidPoints",e)}}class tk{constructor(e){this.occWorkerManager=e}createPolygonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolygonWire",e)}createPolygons(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolygons",e)}createLineWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLineWire",e)}createLines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLines",e)}splitOnPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.splitOnPoints",e)}wiresToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.wiresToPoints",e)}createPolylineWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolylineWire",e)}createZigZagBetweenTwoWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createZigZagBetweenTwoWires",e)}createWireFromTwoCirclesTan(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createWireFromTwoCirclesTan",e)}createPolylines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolylines",e)}createBezier(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBezier",e)}createBezierWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBezierWires",e)}interpolatePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.interpolatePoints",e)}interpolateWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.interpolateWires",e)}createBSpline(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBSpline",e)}createBSplines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBSplines",e)}combineEdgesAndWiresIntoAWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.combineEdgesAndWiresIntoAWire",e)}createWireFromEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createWireFromEdge",e)}addEdgesAndWiresToWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.addEdgesAndWiresToWire",e)}divideWireByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWireByParamsToPoints",e)}divideWiresByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWiresByParamsToPoints",e)}divideWireByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWireByEqualDistanceToPoints",e)}divideWiresByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWiresByEqualDistanceToPoints",e)}pointOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointOnWireAtParam",e)}pointOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointOnWireAtLength",e)}tangentOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.tangentOnWireAtParam",e)}tangentOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.tangentOnWireAtLength",e)}derivativesOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.derivativesOnWireAtLength",e)}derivativesOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.derivativesOnWireAtParam",e)}startPointOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.startPointOnWire",e)}endPointOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.endPointOnWire",e)}createCircleWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createCircleWire",e)}createSquareWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createSquareWire",e)}createStarWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createStarWire",e)}createChristmasTreeWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createChristmasTreeWire",e)}createNGonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createNGonWire",e)}createParallelogramWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createParallelogramWire",e)}createHeartWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createHeartWire",e)}createRectangleWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createRectangleWire",e)}createLPolygonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLPolygonWire",e)}createEllipseWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createEllipseWire",e)}getWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWire",e)}getWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWires",e)}getWireCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWireCenterOfMass",e)}getWiresCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWiresCentersOfMass",e)}reversedWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.reversedWire",e)}reversedWireFromReversedEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.reversedWireFromReversedEdges",e)}getWireLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWireLength",e)}getWiresLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWiresLengths",e)}placeWireOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.placeWireOnFace",e)}placeWiresOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.placeWiresOnFace",e)}closeOpenWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.closeOpenWire",e)}project(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.project",e)}projectWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.projectWires",e)}}class ik{constructor(e){this.occWorkerManager=e}sewFaces(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shell.sewFaces",e)}getShellSurfaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shell.getShellSurfaceArea",e)}}class sk{constructor(e){this.occWorkerManager=e}purgeInternalEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.purgeInternalEdges",e)}unifySameDomain(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.unifySameDomain",e)}isClosed(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isClosed",e)}isConvex(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isConvex",e)}isChecked(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isChecked",e)}isFree(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isFree",e)}isInfinite(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isInfinite",e)}isModified(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isModified",e)}isLocked(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isLocked",e)}isNull(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isNull",e)}isEqual(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isEqual",e)}isNotEqual(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isNotEqual",e)}isPartner(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isPartner",e)}isSame(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isSame",e)}getOrientation(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.getOrientation",e)}getShapeType(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.getShapeType",e)}}class rk{constructor(e){this.occWorkerManager=e}vertexFromPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.vertexFromPoint",e)}verticesFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesFromPoints",e)}verticesCompoundFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesCompoundFromPoints",e)}getVertices(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.getVertices",e)}getVerticesAsPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.getVerticesAsPoints",e)}verticesToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesToPoints",e)}vertexToPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.vertexToPoint",e)}}class nk{constructor(e){this.vertex=new rk(e),this.edge=new ZB(e),this.wire=new tk(e),this.face=new JB(e),this.shell=new ik(e),this.solid=new ek(e),this.compound=new qB(e),this.shape=new sk(e)}}class ok{constructor(e){this.occWorkerManager=e}transform(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.transform",e)}rotate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotate",e)}rotateAroundCenter(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateAroundCenter",e)}align(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.align",e)}alignAndTranslate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignAndTranslate",e)}translate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.translate",e)}scale(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale",e)}scale3d(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale3d",e)}mirror(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirror",e)}mirrorAlongNormal(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorAlongNormal",e)}transformShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.transformShapes",e)}rotateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateShapes",e)}rotateAroundCenterShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateAroundCenterShapes",e)}alignShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignShapes",e)}alignAndTranslateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignAndTranslateShapes",e)}translateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.translateShapes",e)}scaleShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scaleShapes",e)}scale3dShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale3dShapes",e)}mirrorShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorShapes",e)}mirrorAlongNormalShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorAlongNormalShapes",e)}}class ak{constructor(e){this.occWorkerManager=e}loft(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.loft",e)}loftAdvanced(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.loftAdvanced",e)}closestPointsBetweenTwoShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsBetweenTwoShapes",e)}closestPointsOnShapeFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsOnShapeFromPoints",e)}closestPointsOnShapesFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsOnShapesFromPoints",e)}distancesToShapeFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.distancesToShapeFromPoints",e)}extrude(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.extrude",e)}extrudeShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.extrudeShapes",e)}splitShapeWithShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.splitShapeWithShapes",e)}revolve(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.revolve",e)}rotatedExtrude(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.rotatedExtrude",e)}pipe(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipe",e)}pipePolylineWireNGon(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipePolylineWireNGon",e)}pipeWiresCylindrical(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipeWiresCylindrical",e)}pipeWireCylindrical(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipeWireCylindrical",e)}offset(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offset",e)}offsetAdv(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offsetAdv",e)}makeThickSolidSimple(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.makeThickSolidSimple",e)}makeThickSolidByJoin(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.makeThickSolidByJoin",e)}slice(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.slice",e)}sliceInStepPattern(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.sliceInStepPattern",e)}offset3DWire(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offset3DWire",e)}}class lk{constructor(e){this.occWorkerManager=e}union(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.union",e)}difference(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.difference",e)}intersection(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.intersection",e)}}class hk{constructor(e){this.occWorkerManager=e}geom2dEllipse(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dEllipse",e)}geom2dTrimmedCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dTrimmedCurve",e)}geom2dSegment(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dSegment",e)}get2dPointFrom2dCurveOnParam(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.get2dPointFrom2dCurveOnParam",e)}geomCircleCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geomCircleCurve",e)}geomEllipseCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geomEllipseCurve",e)}}class ck{constructor(e){this.occWorkerManager=e}cylindricalSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.surfaces.cylindricalSurface",e)}surfaceFromFace(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.surfaces.surfaceFromFace",e)}}class uk{constructor(e){this.curves=new hk(e),this.surfaces=new ck(e)}}class dk{constructor(e){this.occWorkerManager=e}filletEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdges",e)}filletEdgesList(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesList",e)}filletEdgesListOneRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesListOneRadius",e)}filletEdgeVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgeVariableRadius",e)}filletEdgesSameVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesSameVariableRadius",e)}filletEdgesVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesVariableRadius",e)}fillet3DWire(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.fillet3DWire",e)}chamferEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdges",e)}chamferEdgesList(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesList",e)}chamferEdgeTwoDistances(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgeTwoDistances",e)}chamferEdgesTwoDistances(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesTwoDistances",e)}chamferEdgesTwoDistancesLists(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesTwoDistancesLists",e)}chamferEdgeDistAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgeDistAngle",e)}chamferEdgesDistAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesDistAngle",e)}chamferEdgesDistsAngles(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesDistsAngles",e)}fillet2d(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.fillet2d",e)}filletTwoEdgesInPlaneIntoAWire(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletTwoEdgesInPlaneIntoAWire",e)}}class _k{constructor(e){this.occWorkerManager=e}basicShapeRepair(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.basicShapeRepair",e)}fixSmallEdgeOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.fixSmallEdgeOnWire",e)}fixEdgeOrientationsAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.fixEdgeOrientationsAlongWire",e)}}var pk=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class fk{constructor(e){this.occWorkerManager=e,this.shapes=new nk(e),this.geom=new uk(e),this.transforms=new ok(e),this.operations=new ak(e),this.booleans=new lk(e),this.fillets=new dk(e),this.shapeFix=new _k(e),this.io=new $B(e)}shapeToMesh(e){return pk(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",e)}))}shapesToMeshes(e){return pk(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e)}))}deleteShape(e){return pk(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("deleteShape",e)}))}deleteShapes(e){return pk(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("deleteShapes",e)}))}cleanAllCache(){return pk(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("cleanAllCache",{})}))}}var mk=function(e,t){return mk=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},mk(e,t)};function gk(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}mk(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function vk(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],s=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function xk(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var s,r,n=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return o}function bk(e,t,i){if(i||2===arguments.length)for(var s,r=0,n=t.length;r0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,i=this,s=i.hasError,r=i.isStopped,n=i.observers;return s||r?Ak:(this.currentObservers=null,n.push(e),new Ek((function(){t.currentObservers=null,Ck(n,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,i=t.hasError,s=t.thrownError,r=t.isStopped;i?e.error(s):r&&e.complete()},t.prototype.asObservable=function(){var e=new $k;return e.source=this,e},t.create=function(e,t){return new sV(e,t)},t}($k),sV=function(e){function t(t,i){var s=e.call(this)||this;return s.destination=t,s.source=i,s}return gk(t,e),t.prototype.next=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===i||i.call(t,e)},t.prototype.error=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===i||i.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,i;return null!==(i=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==i?i:Ak},t}(iV);!function(e){e.loading="loading",e.loaded="loaded",e.initialised="initialised",e.computing="computing"}(Zk||(Zk={}));class rV{constructor(){this.occWorkerState$=new iV,this.promisesMade=[]}occWorkerAlreadyInitialised(){return!!this.occWorker}setOccWorker(e){this.occWorker=e,this.occWorker.onmessage=({data:e})=>{if("occ-initialised"===e)this.occWorkerState$.next({state:Zk.initialised});else if("busy"===e)this.occWorkerState$.next({state:Zk.computing});else{const t=this.promisesMade.find((t=>t.uid===e.uid));t&&void 0!==e.result&&!e.error?t.resolve(e.result):e.error&&(this.errorCallback&&this.errorCallback(e.error),t.reject(e.error)),this.promisesMade=this.promisesMade.filter((t=>t.uid!==e.uid)),0===this.promisesMade.length?this.occWorkerState$.next({state:Zk.loaded}):this.occWorkerState$.next({state:Zk.computing})}}}cleanPromisesMade(){this.promisesMade=[]}genericCallToWorkerPromise(e,t){const i=`call${Math.random()}${Date.now()}`,s={uid:i},r=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return s.promise=r,this.promisesMade.push(s),this.occWorker.postMessage({action:{functionName:e,inputs:t},uid:i}),r}startedTheRun(){return this.genericCallToWorkerPromise("startedTheRun",{})}cleanAllCache(){return this.genericCallToWorkerPromise("cleanAllCache",{})}}!function(e){let t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m;!function(e){e.arc="arc",e.intersection="intersection",e.tangent="tangent"}(t=e.joinTypeEnum||(e.joinTypeEnum={})),function(e){e.skin="skin",e.pipe="pipe",e.rectoVerso="rectoVerso"}(i=e.bRepOffsetModeEnum||(e.bRepOffsetModeEnum={})),function(e){e.approxChordLength="approxChordLength",e.approxCentripetal="approxCentripetal",e.approxIsoParametric="approxIsoParametric"}(s=e.approxParametrizationTypeEnum||(e.approxParametrizationTypeEnum={})),function(e){e.outside="outside",e.inside="inside",e.middle="middle"}(r=e.directionEnum||(e.directionEnum={})),function(e){e.iges="iges",e.step="step"}(n=e.fileTypeEnum||(e.fileTypeEnum={})),function(e){e.forward="forward",e.reversed="reversed",e.internal="internal",e.external="external"}(o=e.topAbsOrientationEnum||(e.topAbsOrientationEnum={})),function(e){e.in="in",e.out="out",e.on="on",e.unknown="unknown"}(a=e.topAbsStateEnum||(e.topAbsStateEnum={})),function(e){e.unknown="unknown",e.vertex="vertex",e.edge="edge",e.wire="wire",e.face="face",e.shell="shell",e.solid="solid",e.compSolid="compSolid",e.compound="compound",e.shape="shape"}(l=e.shapeTypeEnum||(e.shapeTypeEnum={})),function(e){e.unqualified="unqualified",e.enclosing="enclosing",e.enclosed="enclosed",e.outside="outside",e.noqualifier="noqualifier"}(h=e.gccEntPositionEnum||(e.gccEntPositionEnum={})),function(e){e.keepSide1="keepSide1",e.keepSide2="keepSide2",e.all="all"}(c=e.positionResultEnum||(e.positionResultEnum={})),function(e){e.none="none",e.keepSide1="keepSide1",e.keepSide2="keepSide2"}(u=e.circleInclusionEnum||(e.circleInclusionEnum={})),function(e){e.none="none",e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(d=e.twoCircleInclusionEnum||(e.twoCircleInclusionEnum={})),function(e){e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(_=e.fourSidesStrictEnum||(e.fourSidesStrictEnum={})),function(e){e.outside="outside",e.inside="inside"}(p=e.twoSidesStrictEnum||(e.twoSidesStrictEnum={})),function(e){e.allWithAll="allWithAll",e.inOrder="inOrder",e.inOrderClosed="inOrderClosed"}(f=e.combinationCirclesForFaceEnum||(e.combinationCirclesForFaceEnum={})),function(e){e[e.curve=0]="curve",e[e.edge=1]="edge",e[e.wire=2]="wire",e[e.face=3]="face"}(m=e.typeSpecificityEnum||(e.typeSpecificityEnum={})),e.DecomposedMeshDto=class{constructor(e,t){void 0!==e&&(this.faceList=e),void 0!==t&&(this.edgeList=t)}},e.DecomposedFaceDto=class{},e.DecomposedEdgeDto=class{},e.ShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.PointDto=class{constructor(e){this.point=[0,0,0],void 0!==e&&(this.point=e)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.ConstraintTanLinesFromPtToCircleDto=class{constructor(e,t,i,s,r){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.positionResult=s),void 0!==r&&(this.circleRemainder=r)}},e.ConstraintTanLinesFromTwoPtsToCircleDto=class{constructor(e,t,i,s,r,n){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point1=t),void 0!==i&&(this.point1=i),void 0!==s&&(this.tolerance=s),void 0!==r&&(this.positionResult=r),void 0!==n&&(this.circleRemainder=n)}},e.ConstraintTanLinesOnTwoCirclesDto=class{constructor(e,t,i,s,r){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainders=d.none,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.positionResult=s),void 0!==r&&(this.circleRemainders=r)}},e.ConstraintTanCirclesOnTwoCirclesDto=class{constructor(e,t,i,s){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.radius=s)}},e.ConstraintTanCirclesOnCircleAndPntDto=class{constructor(e,t,i,s){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.radius=s)}},e.CurveAndSurfaceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t)}},e.FilletTwoEdgesInPlaneDto=class{constructor(e,t,i,s,r,n){this.planeOrigin=[0,0,0],this.planeDirection=[0,1,0],this.radius=.3,this.solution=-1,void 0!==e&&(this.edge1=e),void 0!==t&&(this.edge2=t),void 0!==i&&(this.planeOrigin=i),void 0!==s&&(this.planeDirection=s),void 0!==r&&(this.radius=r),void 0!==n&&(this.solution=n)}},e.ClosestPointsOnShapeFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.SplitWireOnPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.ClosestPointsOnShapesFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shapes=e),void 0!==t&&(this.points=t)}},e.ClosestPointsBetweenTwoShapesDto=class{constructor(e,t){void 0!==e&&(this.shape1=e),void 0!==t&&(this.shape2=t)}},e.FaceFromSurfaceAndWireDto=class{constructor(e,t,i){this.inside=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.wire=t),void 0!==i&&(this.inside=i)}},e.WireOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wire=e),void 0!==t&&(this.face=t)}},e.DrawShapeDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shape=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdgeIndexes=_),void 0!==p&&(this.edgeIndexHeight=p),void 0!==f&&(this.edgeIndexColour=f),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.DrawShapesDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shapes=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdgeIndexes=_),void 0!==p&&(this.edgeIndexHeight=p),void 0!==f&&(this.edgeIndexColour=f),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.FaceSubdivisionDto=class{constructor(e,t,i,s,r,n,o,a,l){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepU=!1,this.removeStartEdgeU=!1,this.removeEndEdgeU=!1,this.shiftHalfStepV=!1,this.removeStartEdgeV=!1,this.removeEndEdgeV=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==s&&(this.shiftHalfStepU=s),void 0!==r&&(this.removeStartEdgeU=r),void 0!==n&&(this.removeEndEdgeU=n),void 0!==o&&(this.shiftHalfStepV=o),void 0!==a&&(this.removeStartEdgeV=a),void 0!==l&&(this.removeEndEdgeV=l)}},e.FaceSubdivisionControlledDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepNthU=0,this.shiftHalfStepUOffsetN=0,this.removeStartEdgeNthU=0,this.removeStartEdgeUOffsetN=0,this.removeEndEdgeNthU=0,this.removeEndEdgeUOffsetN=0,this.shiftHalfStepNthV=0,this.shiftHalfStepVOffsetN=0,this.removeStartEdgeNthV=0,this.removeStartEdgeVOffsetN=0,this.removeEndEdgeNthV=0,this.removeEndEdgeVOffsetN=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==s&&(this.shiftHalfStepNthU=s),void 0!==r&&(this.shiftHalfStepUOffsetN=r),void 0!==n&&(this.removeStartEdgeNthU=n),void 0!==o&&(this.removeStartEdgeUOffsetN=o),void 0!==a&&(this.removeEndEdgeNthU=a),void 0!==l&&(this.removeEndEdgeUOffsetN=l),void 0!==h&&(this.shiftHalfStepNthV=h),void 0!==c&&(this.shiftHalfStepVOffsetN=c),void 0!==u&&(this.removeStartEdgeNthV=u),void 0!==d&&(this.removeStartEdgeVOffsetN=d),void 0!==_&&(this.removeEndEdgeNthV=_),void 0!==p&&(this.removeEndEdgeVOffsetN=p)}},e.FaceLinearSubdivisionDto=class{constructor(e,t,i,s,r,n,o){this.isU=!0,this.param=.5,this.nrPoints=10,this.shiftHalfStep=!1,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==i&&(this.param=i),void 0!==s&&(this.nrPoints=s),void 0!==r&&(this.shiftHalfStep=r),void 0!==n&&(this.removeStartPoint=n),void 0!==o&&(this.removeEndPoint=o)}},e.DataOnUVDto=class{constructor(e,t,i){this.paramU=.5,this.paramV=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.paramU=t),void 0!==i&&(this.paramV=i)}},e.DataOnUVsDto=class{constructor(e,t){this.paramsUV=[[.5,.5]],void 0!==e&&(this.shape=e),void 0!==t&&(this.paramsUV=t)}},e.PolygonDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolygonsDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polygons=e),void 0!==t&&(this.returnCompound=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolylinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.returnCompound=t)}},e.SquareDto=class{constructor(e,t,i){this.size=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.RectangleDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.center=i),void 0!==s&&(this.direction=s)}},e.LPolygonDto=class{constructor(e,t,i,s,n,o,a,l){this.widthFirst=1,this.lengthFirst=2,this.widthSecond=.5,this.lengthSecond=2,this.align=r.outside,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.widthFirst=e),void 0!==t&&(this.lengthFirst=t),void 0!==i&&(this.widthSecond=i),void 0!==s&&(this.lengthSecond=s),void 0!==n&&(this.align=n),void 0!==o&&(this.rotation=o),void 0!==a&&(this.center=a),void 0!==l&&(this.direction=l)}},e.BoxDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.height=3,this.center=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==s&&(this.center=s)}},e.CubeDto=class{constructor(e,t){this.size=1,this.center=[0,0,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t)}},e.BoxFromCornerDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.height=3,this.corner=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==s&&(this.corner=s)}},e.SphereDto=class{constructor(e,t){this.radius=1,this.center=[0,0,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.ConeDto=class{constructor(e,t,i,s,r,n){this.radius1=2,this.radius2=1,this.height=2,this.angle=360,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius1=e),void 0!==t&&(this.radius2=t),void 0!==i&&(this.height=i),void 0!==s&&(this.angle=s),void 0!==r&&(this.center=r),void 0!==n&&(this.direction=n)}},e.LineDto=class{constructor(e,t){this.start=[0,0,0],this.end=[0,1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.returnCompound=t)}},e.ArcEdgeTwoPointsTangentDto=class{constructor(e,t,i){this.start=[0,0,0],this.tangentVec=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.tangentVec=t),void 0!==i&&(this.end=i)}},e.ArcEdgeCircleTwoPointsDto=class{constructor(e,t,i,s){this.start=[0,0,0],this.end=[0,0,1],this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.start=t),void 0!==i&&(this.end=i),void 0!==s&&(this.sense=s)}},e.ArcEdgeCircleTwoAnglesDto=class{constructor(e,t,i,s){this.alphaAngle1=0,this.alphaAngle2=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle1=t),void 0!==i&&(this.alphaAngle2=i),void 0!==s&&(this.sense=s)}},e.ArcEdgeCirclePointAngleDto=class{constructor(e,t,i,s){this.alphaAngle=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle=t),void 0!==s&&(this.sense=s)}},e.ArcEdgeThreePointsDto=class{constructor(e,t,i){this.start=[0,0,0],this.middle=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.middle=t),void 0!==i&&(this.end=i)}},e.CylinderDto=class{constructor(e,t,i,s){this.radius=1,this.height=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.height=t),void 0!==i&&(this.center=i),void 0!==s&&(this.direction=s)}},e.CylindersOnLinesDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.lines=t)}},e.FilletDto=class{constructor(e,t,i,s){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.indexes=s)}},e.FilletEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i)}},e.FilletEdgesListOneRadiusDto=class{constructor(e,t,i){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radius=i)}},e.FilletEdgeVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.paramsU=s)}},e.FilletEdgesVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusLists=i),void 0!==s&&(this.paramsULists=s)}},e.FilletEdgesSameVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.paramsU=s)}},e.Fillet3DWireDto=class{constructor(e,t,i,s,r){this.radius=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.direction=i),void 0!==s&&(this.radiusList=s),void 0!==r&&(this.indexes=r)}},e.ChamferDto=class{constructor(e,t,i,s){this.distance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.distance=t),void 0!==i&&(this.distanceList=i),void 0!==s&&(this.indexes=s)}},e.ChamferEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.distanceList=i)}},e.ChamferEdgeDistAngleDto=class{constructor(e,t,i,s,r){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.angle=r)}},e.ChamferEdgeTwoDistancesDto=class{constructor(e,t,i,s,r){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==s&&(this.distance1=s),void 0!==r&&(this.distance2=r)}},e.ChamferEdgesTwoDistancesListsDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distances1=s),void 0!==r&&(this.distances2=r)}},e.ChamferEdgesTwoDistancesDto=class{constructor(e,t,i,s,r){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distance1=s),void 0!==r&&(this.distance2=r)}},e.ChamferEdgesDistsAnglesDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distances=s),void 0!==r&&(this.angles=r)}},e.ChamferEdgesDistAngleDto=class{constructor(e,t,i,s,r){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.angle=r)}},e.BSplineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BSplinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bSplines=e),void 0!==t&&(this.returnCompound=t)}},e.WireFromTwoCirclesTanDto=class{constructor(e,t,i,s,r){this.keepLines=p.outside,this.circleRemainders=_.outside,this.tolerance=1e-7,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.keepLines=i),void 0!==s&&(this.circleRemainders=s),void 0!==r&&(this.tolerance=r)}},e.FaceFromMultipleCircleTanWiresDto=class{constructor(e,t,i,s){this.combination=f.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.circles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==s&&(this.tolerance=s)}},e.FaceFromMultipleCircleTanWireCollectionsDto=class{constructor(e,t,i,s){this.combination=f.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.listsOfCircles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==s&&(this.tolerance=s)}},e.ZigZagBetweenTwoWiresDto=class{constructor(e,t,i,s,r,n){this.nrZigZags=20,this.divideByEqualDistance=!1,this.zigZagsPerEdge=!0,void 0!==e&&(this.wire1=e),void 0!==t&&(this.wire2=t),void 0!==i&&(this.nrZigZags=i),void 0!==s&&(this.inverse=s),void 0!==r&&(this.divideByEqualDistance=r),void 0!==n&&(this.zigZagsPerEdge=n)}},e.InterpolationDto=class{constructor(e,t,i){this.periodic=!1,this.tolerance=1e-7,void 0!==e&&(this.points=e),void 0!==t&&(this.periodic=t),void 0!==i&&(this.tolerance=i)}},e.InterpolateWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.interpolations=e),void 0!==t&&(this.returnCompound=t)}},e.BezierDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BezierWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bezierWires=e),void 0!==t&&(this.returnCompound=t)}},e.DivideDto=class{constructor(e,t,i,s){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==s&&(this.removeEndPoint=s)}},e.ProjectWireDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wire=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.WiresToPointsDto=class{constructor(e,t,i,s,r,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==s&&(this.minimumOfPoints=s),void 0!==r&&(this.uTolerance=r),void 0!==n&&(this.minimumLength=n)}},e.EdgesToPointsDto=class{constructor(e,t,i,s,r,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==s&&(this.minimumOfPoints=s),void 0!==r&&(this.uTolerance=r),void 0!==n&&(this.minimumLength=n)}},e.ProjectWiresDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wires=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.DivideShapesDto=class{constructor(e,t,i,s){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==s&&(this.removeEndPoint=s)}},e.DataOnGeometryAtParamDto=class{constructor(e,t){this.param=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t)}},e.PointInFaceDto=class{constructor(e,t,i,s){this.tEdgeParam=.5,this.distance2DParam=.5,void 0!==e&&(this.face=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.tEdgeParam=i),void 0!==s&&(this.distance2DParam=s)}},e.DataOnGeometryAtLengthDto=class{constructor(e,t){this.length=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.length=t)}},e.CircleDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.LoftDto=class{constructor(e,t){this.makeSolid=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t)}},e.LoftAdvancedDto=class{constructor(e,t,i,r,n,o,a,l,h,c,u,d){this.makeSolid=!1,this.closed=!1,this.periodic=!1,this.straight=!1,this.nrPeriodicSections=10,this.useSmoothing=!1,this.maxUDegree=3,this.tolerance=1e-7,this.parType=s.approxCentripetal,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t),void 0!==i&&(this.closed=i),void 0!==r&&(this.periodic=r),void 0!==n&&(this.straight=n),void 0!==o&&(this.nrPeriodicSections=o),void 0!==a&&(this.useSmoothing=a),void 0!==l&&(this.maxUDegree=l),void 0!==h&&(this.tolerance=h),void 0!==c&&(this.parType=c),void 0!==u&&(this.startVertex=u),void 0!==d&&(this.endVertex=d)}},e.OffsetDto=class{constructor(e,t,i,s){this.distance=.2,this.tolerance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.face=t),void 0!==i&&(this.distance=i),void 0!==s&&(this.tolerance=s)}},e.OffsetAdvancedDto=class{constructor(e,i,s,r,n,o){this.distance=.2,this.tolerance=.1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.face=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.tolerance=r),void 0!==n&&(this.joinType=n),void 0!==o&&(this.removeIntEdges=o)}},e.RevolveDto=class{constructor(e,t,i,s){this.angle=360,this.direction=[0,1,0],this.copy=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.direction=i),void 0!==s&&(this.copy=s)}},e.ShapeShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.WiresOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t)}},e.PipeWiresCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.radius=t)}},e.PipeWireCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t)}},e.PipePolygonWireNGonDto=class{constructor(e,t,i){this.radius=.1,this.nrCorners=6,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.nrCorners=i)}},e.ExtrudeDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t)}},e.ExtrudeShapesDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.direction=t)}},e.SplitDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.UnionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.DifferenceDto=class{constructor(e,t,i){this.keepEdges=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t),void 0!==i&&(this.keepEdges=i)}},e.IntersectionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.ShapeDto=class{constructor(e){void 0!==e&&(this.shape=e)}},e.CompareShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.otherShape=t)}},e.FixSmallEdgesInWireDto=class{constructor(e,t,i){this.lockvtx=!1,this.precsmall=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.lockvtx=t),void 0!==i&&(this.precsmall=i)}},e.BasicShapeRepairDto=class{constructor(e,t,i,s){this.precision=.001,this.maxTolerance=.01,this.minTolerance=1e-4,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.maxTolerance=i),void 0!==s&&(this.minTolerance=s)}},e.FixClosedDto=class{constructor(e,t){this.precision=-.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t)}},e.ShapesWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.ShapeWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.tolerance=t)}},e.ShapeIndexDto=class{constructor(e,t){this.index=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.EdgeIndexDto=class{constructor(e,t){this.index=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.RotationExtrudeDto=class{constructor(e,t,i){this.height=1,this.angle=360,void 0!==e&&(this.shape=e),void 0!==t&&(this.height=t),void 0!==i&&(this.angle=i)}},e.ThickSolidByJoinDto=class{constructor(e,i,s,r,n,o,a,l){this.offset=1,this.tolerance=.001,this.intersection=!1,this.selfIntersection=!1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.shapes=i),void 0!==s&&(this.offset=s),void 0!==r&&(this.tolerance=r),void 0!==n&&(this.intersection=n),void 0!==o&&(this.selfIntersection=o),void 0!==a&&(this.joinType=a),void 0!==l&&(this.removeIntEdges=l)}},e.TransformDto=class{constructor(e,t,i,s,r){this.translation=[0,0,0],this.rotationAxis=[0,1,0],this.rotationAngle=0,this.scaleFactor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t),void 0!==i&&(this.rotationAxis=i),void 0!==s&&(this.rotationAngle=s),void 0!==r&&(this.scaleFactor=r)}},e.TransformShapesDto=class{constructor(e,t,i,s,r){this.translations=[[0,0,0]],this.rotationAxes=[[0,1,0]],this.rotationAngles=[0],this.scaleFactors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t),void 0!==i&&(this.rotationAxes=i),void 0!==s&&(this.rotationAngles=s),void 0!==r&&(this.scaleFactors=r)}},e.TranslateDto=class{constructor(e,t){this.translation=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t)}},e.TranslateShapesDto=class{constructor(e,t){this.translations=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t)}},e.AlignDto=class{constructor(e,t,i,s,r){this.fromOrigin=[0,0,0],this.fromDirection=[0,0,1],this.toOrigin=[0,1,0],this.toDirection=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.fromOrigin=t),void 0!==i&&(this.fromDirection=i),void 0!==s&&(this.toOrigin=s),void 0!==r&&(this.toDirection=r)}},e.AlignShapesDto=class{constructor(e,t,i,s,r){this.fromOrigins=[[0,0,0]],this.fromDirections=[[0,0,1]],this.toOrigins=[[0,1,0]],this.toDirections=[[0,1,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.fromOrigins=t),void 0!==i&&(this.fromDirections=i),void 0!==s&&(this.toOrigins=s),void 0!==r&&(this.toDirections=r)}},e.MirrorDto=class{constructor(e,t,i){this.origin=[0,0,0],this.direction=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.direction=i)}},e.MirrorShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.directions=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.directions=i)}},e.MirrorAlongNormalDto=class{constructor(e,t,i){this.origin=[0,0,0],this.normal=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.normal=i)}},e.MirrorAlongNormalShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.normals=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.normals=i)}},e.AlignAndTranslateDto=class{constructor(e,t,i){this.direction=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.center=i)}},e.UnifySameDomainDto=class{constructor(e,t,i,s){this.unifyEdges=!0,this.unifyFaces=!0,this.concatBSplines=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.unifyEdges=t),void 0!==i&&(this.unifyFaces=i),void 0!==s&&(this.concatBSplines=s)}},e.FilterFacePointsDto=class{constructor(e,t,i,s,r,n,o,a,l){this.tolerance=1e-4,this.useBndBox=!1,this.gapTolerance=.1,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.useBndBox=s),void 0!==r&&(this.gapTolerance=r),void 0!==n&&(this.keepIn=n),void 0!==o&&(this.keepOn=o),void 0!==a&&(this.keepOut=a),void 0!==l&&(this.keepUnknown=l)}},e.FilterSolidPointsDto=class{constructor(e,t,i,s,r,n,o){this.tolerance=1e-4,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.keepIn=s),void 0!==r&&(this.keepOn=r),void 0!==n&&(this.keepOut=n),void 0!==o&&(this.keepUnknown=o)}},e.AlignAndTranslateShapesDto=class{constructor(e,t,i){this.directions=[[0,1,0]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.directions=t),void 0!==i&&(this.centers=i)}},e.RotateDto=class{constructor(e,t,i){this.axis=[0,0,1],this.angle=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.angle=i)}},e.RotateAroundCenterDto=class{constructor(e,t,i,s){this.angle=0,this.center=[0,0,0],this.axis=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.center=i),void 0!==s&&(this.axis=s)}},e.RotateShapesDto=class{constructor(e,t,i){this.angles=[0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.axes=t),void 0!==i&&(this.angles=i)}},e.RotateAroundCenterShapesDto=class{constructor(e,t,i,s){this.angles=[0],this.centers=[[0,0,0]],this.axes=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.angles=t),void 0!==i&&(this.centers=i),void 0!==s&&(this.axes=s)}},e.ScaleDto=class{constructor(e,t){this.factor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.factor=t)}},e.ScaleShapesDto=class{constructor(e,t){this.factors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.factors=t)}},e.Scale3DDto=class{constructor(e,t,i){this.scale=[1,1,1],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.scale=t),void 0!==i&&(this.center=i)}},e.Scale3DShapesDto=class{constructor(e,t,i){this.scales=[[1,1,1]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.scales=t),void 0!==i&&(this.centers=i)}},e.ShapeToMeshDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.ShapesToMeshesDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.SaveStepDto=class{constructor(e,t,i,s){this.fileName="shape.step",this.adjustYtoZ=!1,this.tryDownload=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustYtoZ=i),void 0!==s&&(this.tryDownload=s)}},e.SaveStlDto=class{constructor(e,t,i,s,r,n){this.fileName="shape.stl",this.precision=.01,this.adjustYtoZ=!1,this.tryDownload=!0,this.binary=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.precision=i),void 0!==s&&(this.adjustYtoZ=s),void 0!==r&&(this.tryDownload=r),void 0!==n&&(this.binary=n)}},e.ImportStepIgesFromTextDto=class{constructor(e,t,i){this.fileType=n.step,this.adjustZtoY=!0,void 0!==e&&(this.text=e),void 0!==t&&(this.fileType=t),void 0!==i&&(this.adjustZtoY=i)}},e.ImportStepIgesDto=class{constructor(e,t){this.adjustZtoY=!0,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.adjustZtoY=t)}},e.LoadStepOrIgesDto=class{constructor(e,t,i){this.fileName="shape.igs",this.adjustZtoY=!0,void 0!==e&&(this.filetext=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustZtoY=i)}},e.CompoundShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.ThisckSolidSimpleDto=class{constructor(e,t){this.offset=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t)}},e.Offset3DWireDto=class{constructor(e,t,i){this.offset=1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t),void 0!==i&&(this.direction=i)}},e.FaceFromWireDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.planar=t)}},e.FaceFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.FacesFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.SewDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.FaceIsoCurveAtParamDto=class{constructor(e,t,i){this.dir="u",void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t),void 0!==i&&(this.dir=i)}},e.DivideFaceToUVPointsDto=class{constructor(e,t,i,s){this.nrOfPointsU=10,this.nrOfPointsV=10,this.flat=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfPointsU=t),void 0!==i&&(this.nrOfPointsV=i),void 0!==s&&(this.flat=s)}},e.Geom2dEllipseDto=class{constructor(e,t,i,s,r){this.center=[0,0],this.direction=[1,0],this.radiusMinor=1,this.radiusMajor=2,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==s&&(this.radiusMajor=s),void 0!==r&&(this.sense=r)}},e.Geom2dCircleDto=class{constructor(e,t,i,s){this.center=[0,0],this.direction=[1,0],this.radius=1,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.sense=s)}},e.ChristmasTreeDto=class{constructor(e,t,i,s,r,n,o,a,l,h){this.height=6,this.innerDist=1.5,this.outerDist=3,this.nrSkirts=5,this.trunkHeight=1,this.trunkWidth=1,this.half=!1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.innerDist=t),void 0!==i&&(this.outerDist=i),void 0!==s&&(this.nrSkirts=s),void 0!==r&&(this.trunkHeight=r),void 0!==n&&(this.trunkWidth=n),void 0!==o&&(this.half=o),void 0!==a&&(this.rotation=a),void 0!==l&&(this.origin=l),void 0!==h&&(this.direction=h)}},e.StarDto=class{constructor(e,t,i,s,r,n,o){this.center=[0,0,0],this.direction=[0,1,0],this.numRays=7,this.half=!1,void 0!==e&&(this.outerRadius=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.numRays=i),void 0!==s&&(this.center=s),void 0!==r&&(this.direction=r),void 0!==n&&(this.offsetOuterEdges=n),void 0!==o&&(this.half=o)}},e.ParallelogramDto=class{constructor(e,t,i,s,r,n){this.center=[0,0,0],this.direction=[0,1,0],this.aroundCenter=!0,this.width=2,this.height=1,this.angle=15,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.aroundCenter=i),void 0!==s&&(this.width=s),void 0!==r&&(this.height=r),void 0!==n&&(this.angle=n)}},e.Heart2DDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.rotation=0,this.sizeApprox=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.rotation=i),void 0!==s&&(this.sizeApprox=s)}},e.NGonWireDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.nrCorners=6,this.radius=1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.nrCorners=i),void 0!==s&&(this.radius=s)}},e.EllipseDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.radiusMinor=1,this.radiusMajor=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==s&&(this.radiusMajor=s)}},e.GeomCylindricalSurfaceDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.Geom2dTrimmedCurveDto=class{constructor(e,t,i,s,r){this.u1=0,this.u2=1,this.sense=!0,this.adjustPeriodic=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.u1=t),void 0!==i&&(this.u2=i),void 0!==s&&(this.sense=s),void 0!==r&&(this.adjustPeriodic=r)}},e.Geom2dSegmentDto=class{constructor(e,t){this.start=[0,0],this.end=[1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.SliceDto=class{constructor(e,t,i){this.step=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.step=t),void 0!==i&&(this.direction=i)}},e.SliceInStepPatternDto=class{constructor(e,t,i){this.steps=[.1,.2],this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.steps=t),void 0!==i&&(this.direction=i)}}}(Jk||(Jk={})),function(e){let t;!function(e){e.default="default",e.clearSky="clearSky",e.city="city"}(t=e.skyboxEnum||(e.skyboxEnum={}))}(eV||(eV={})),"undefined"!=typeof document&&document.currentScript&&document.currentScript.src;class nV{constructor(e){this.context=e}create(e){const t=new _e(e.target[0],e.target[1],e.target[2]),i=new hc(`arcRotateCamera${Math.random()}`,this.getRadians(e.alpha),this.getRadians(e.beta),e.radius,t,this.context.scene);void 0!==e.angularSensibilityX&&(i.angularSensibilityX=e.angularSensibilityX),void 0!==e.angularSensibilityY&&(i.angularSensibilityY=e.angularSensibilityY),void 0!==e.lowerBetaLimit&&(i.lowerBetaLimit=this.getRadians(e.lowerBetaLimit)),void 0!==e.upperBetaLimit&&(i.upperBetaLimit=this.getRadians(e.upperBetaLimit)),void 0!==e.panningSensibility&&(i.panningSensibility=e.panningSensibility),void 0!==e.wheelPrecision&&(i.wheelPrecision=e.wheelPrecision),void 0!==e.maxZ&&(i.maxZ=e.maxZ),i.minZ=0;const s=document.getElementById("renderCanvas");return i.attachControl(s,!0),i}getRadians(e){let t=$r.FromDegrees(e).radians();return e<0&&(t=-t),t}}class oV{constructor(e){this.context=e}create(e){const t=new _e(e.position[0],e.position[1],e.position[2]),i=new ac(`freeCamera${Math.random()}`,t,this.context.scene),s=new _e(e.target[0],e.target[1],e.target[2]);i.setTarget(s);const r=document.getElementById("renderCanvas");return i.attachControl(r,!0),i.minZ=0,i.maxZ=1e3,i}}class aV{constructor(e){this.context=e}create(e){const t=new _e(e.position[0],e.position[1],e.position[2]),i=new oc(`freeCamera${Math.random()}`,t,this.context.scene),s=new _e(e.target[0],e.target[1],e.target[2]);i.setTarget(s);const r=document.getElementById("renderCanvas");return i.attachControl(r,!0),i.minZ=0,i.maxZ=1e3,i}}class lV{constructor(e){this.context=e,this.free=new oV(this.context),this.arcRotate=new nV(this.context),this.target=new aV(this.context)}freezeProjectionMatrix(e){e.camera.freezeProjectionMatrix()}unfreezeProjectionMatrix(e){e.camera.unfreezeProjectionMatrix()}setPosition(e){const t=new _e(e.position[0],e.position[1],e.position[2]);e.camera.position=t}getPosition(e){return[e.camera.position.x,e.camera.position.y,e.camera.position.z]}setTarget(e){const t=new _e(e.target[0],e.target[1],e.target[2]);e.camera.setTarget(t)}getTarget(e){return[e.camera.target.x,e.camera.target.y,e.camera.target.z]}setSpeed(e){e.camera.speed=e.speed}getSpeed(e){return[e.camera.target.x,e.camera.target.y,e.camera.target.z]}setMinZ(e){e.camera.minZ=e.minZ}setMaxZ(e){e.camera.maxZ=e.maxZ}makeCameraOrthographic(e){e.camera.mode=In.ORTHOGRAPHIC_CAMERA,e.camera.orthoBottom=e.orthoBottom||-1,e.camera.orthoTop=e.orthoTop||1,e.camera.orthoLeft=e.orthoLeft||-1,e.camera.orthoRight=e.orthoRight||1}makeCameraPerspective(e){e.camera.mode=In.PERSPECTIVE_CAMERA}}class hV{constructor(e,t){this.context=e,this.color=t}create(e){const t=new Lx(e.name,this.context.scene);return t.baseColor=Ee.FromHexString(e.baseColor),t.metallic=e.metallic,t.roughness=e.roughness,t.alpha=e.alpha,t.backFaceCulling=e.backFaceCulling,t.zOffset=e.zOffset,t.alphaMode=1,e.emissiveColor&&(t.emissiveColor=Ee.FromHexString(e.emissiveColor)),t}setBaseColor(e){e.material.baseColor=Ee.FromHexString(e.baseColor)}setMetallic(e){e.material.metallic=e.metallic}setRoughness(e){e.material.roughness=e.roughness}setAlpha(e){e.material.alpha=e.alpha}setBackFaceCulling(e){e.material.backFaceCulling=e.backFaceCulling}setBaseTexture(e){e.material.baseTexture=e.baseTexture}getBaseColor(e){const t=e.material,i=this.context.remap(t.baseColor.r,0,1,0,255),s=this.context.remap(t.baseColor.g,0,1,0,255),r=this.context.remap(t.baseColor.b,0,1,0,255);return this.color.rgbToHex({r:i,g:s,b:r})}getMetallic(e){return e.material.metallic}getRoughness(e){return e.material.roughness}getAlpha(e){return e.material.alpha}getBackFaceCulling(e){return e.material.backFaceCulling}getBaseTexture(e){return e.material.baseTexture}}class cV{constructor(e,t){this.context=e,this.color=t,this.pbrMetallicRoughness=new hV(e,t)}}var uV=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class dV{constructor(e){this.context=e}createDefaultXRExperienceWithTeleportation(e){return uV(this,void 0,void 0,(function*(){const t=yield this.context.scene.createDefaultXRExperienceAsync();this.context.scene.metadata?this.context.scene.metadata.xr=t:this.context.scene.metadata={xr:t};const i=[];e.groundMeshes.forEach((e=>{e.getChildMeshes&&(null==e||e.getChildMeshes().forEach((e=>{e.isPickable=!0,i.push(e)}))),i.push(e),e.isPickable=!0}));const s=t.baseExperience.featuresManager,r=new Lx("teleportation");r.baseColor=new Ee(0,0,1),r.metallic=0,r.roughness=1,s.enableFeature(qa.TELEPORTATION,"stable",{xrInput:t.input,floorMeshes:i,defaultTargetMeshOptions:{torusArrowMaterial:r,disableLighting:!1}});const n=new vF(this.context.scene);this.context.scene.metadata.guiManager=n,n.useRealisticScaling=!0;const o=new ZN("near");n.addControl(o);const a=new zN("button1"),l=new Fw;l.text="Exit VR",l.color="white",l.fontSize="48px",a.onPointerClickObservable.add((()=>uV(this,void 0,void 0,(function*(){yield t.baseExperience.exitXRAsync()})))),o.addButton(a),a.content=l}))}}class _V{constructor(e){this.context=e}getEngine(){return this.context.engine}getRenderingCanvas(){return this.context.engine.getRenderingCanvas()}}var pV;class fV{constructor(e){this.context=e}create(e){return t=this,i=void 0,r=function*(){const t=new aE(`gaussian-splatting-${Math.random()}`,void 0,this.context.scene);return yield t.loadFileAsync(e.url),t},new((s=void 0)||(s=Promise))((function(e,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,a)}l((r=r.apply(t,i||[])).next())}));var t,i,s,r}}class mV{static _CreateBufferView(e,t,i,s,r){const n={buffer:e,byteLength:i};return t&&(n.byteOffset=t),r&&(n.name=r),s&&(n.byteStride=s),n}static _CreateAccessor(e,t,i,s,r,n,o,a){const l={name:t,bufferView:e,componentType:s,count:r,type:i};return null!=o&&(l.min=o),null!=a&&(l.max=a),null!=n&&(l.byteOffset=n),l}static _CalculateMinMaxPositions(e,t,i){const s=[1/0,1/0,1/0],r=[-1/0,-1/0,-1/0];let n,o,a;if(i)for(let l=t,h=t+i;lr[e]&&(r[e]=t),++n}}return{min:s,max:r}}static _NormalizeTangentFromRef(e){const t=Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z);t>0&&(e.x/=t,e.y/=t,e.z/=t)}static _GetDataAccessorElementCount(e){switch(e){case"MAT2":case"VEC4":return 4;case"MAT3":return 9;case"MAT4":return 16;case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3}}}!function(e){e[e.INTANGENT=0]="INTANGENT",e[e.OUTTANGENT=1]="OUTTANGENT"}(pV||(pV={}));class gV{static _IsTransformable(e){return e&&(e instanceof lo||e instanceof In||e instanceof ua)}static _CreateNodeAnimation(e,t,i,s,r){if(this._IsTransformable(e)){const n=[],o=[],a=t.getKeys(),l=gV._CalculateMinMaxKeyFrames(a),h=gV._DeduceInterpolation(a,i,s),c=h.interpolationType,u=h.shouldBakeAnimation;if(u?gV._CreateBakedAnimation(e,t,i,l.min,l.max,t.framePerSecond,r,n,o,l,s):"LINEAR"===c||"STEP"===c?gV._CreateLinearOrStepAnimation(e,t,i,n,o,s):"CUBICSPLINE"===c?gV._CreateCubicSplineAnimation(e,t,i,n,o,s):gV._CreateBakedAnimation(e,t,i,l.min,l.max,t.framePerSecond,r,n,o,l,s),n.length&&o.length)return{inputs:n,outputs:o,samplerInterpolation:c,inputsMin:u?l.min:Ds.FloatRound(l.min/t.framePerSecond),inputsMax:u?l.max:Ds.FloatRound(l.max/t.framePerSecond)}}return null}static _DeduceAnimationInfo(e){let t=null,i="VEC3",s=!1;const r=e.targetProperty.split(".");switch(r[0]){case"scaling":t="scale";break;case"position":t="translation";break;case"rotation":i="VEC4",t="rotation";break;case"rotationQuaternion":i="VEC4",s=!0,t="rotation";break;case"influence":i="SCALAR",t="weights";break;default:Ds.Error(`Unsupported animatable property ${r[0]}`)}return t?{animationChannelTargetPath:t,dataAccessorType:i,useQuaternion:s}:(Ds.Error("animation channel target path and data accessor type could be deduced"),null)}static _CreateNodeAnimationFromNodeAnimations(e,t,i,s,r,n,o,a,l,h){let c;if(gV._IsTransformable(e)&&e.animations)for(const r of e.animations){if(h&&!h(r))continue;const u=gV._DeduceAnimationInfo(r);u&&(c={name:r.name,samplers:[],channels:[]},gV._AddAnimation(`${r.name}`,r.hasRunningRuntimeAnimations?t:c,e,r,u.dataAccessorType,u.animationChannelTargetPath,s,n,o,a,u.useQuaternion,l),c.samplers.length&&c.channels.length&&i.push(c))}}static _CreateMorphTargetAnimationFromMorphTargetAnimations(e,t,i,s,r,n,o,a,l,h){let c;if(e instanceof ha){const r=e.morphTargetManager;if(r)for(let u=0;u{for(let i=0;ie.morphTargetManager===i));s&&(h.has(s)||h.set(s,new Map),h.get(s)?.set(t,f),d.add(s),u.set(s,f))}}}}d.forEach((e=>{const t=e.morphTargetManager;let a=null;const d=[],p=u.get(e).getKeys(),f=p.length;for(let i=0;i0;)t=_.inputs.shift(),e%d==0&&i.push(t),e++;_.inputs=i}const s=o[i.uniqueId];let c=4*_.inputs.length;p=mV._CreateBufferView(0,a.getByteOffset(),c,void 0,`${e} keyframe data view`),l.push(p),_.inputs.forEach((function(e){a.setFloat32(e)})),f=mV._CreateAccessor(l.length-1,`${e} keyframes`,"SCALAR",5126,_.inputs.length,null,[_.inputsMin],[_.inputsMax]),h.push(f),m=h.length-1,v=_.outputs.length,c=4*mV._GetDataAccessorElementCount(r)*_.outputs.length,p=mV._CreateBufferView(0,a.getByteOffset(),c,void 0,`${e} data view`),l.push(p),_.outputs.forEach((function(e){e.forEach((function(e){a.setFloat32(e)}))})),f=mV._CreateAccessor(l.length-1,`${e} data`,r,5126,v,null,null,null),h.push(f),g=h.length-1,x={interpolation:_.samplerInterpolation,input:m,output:g},t.samplers.push(x),b={sampler:t.samplers.length-1,target:{node:s,path:n}},t.channels.push(b)}}static _CreateBakedAnimation(e,t,i,s,r,n,o,a,l,h,c){let u;const d=fe.Identity();let _,p=null,f=null,m=null,g=null,v=null,x=null;h.min=Ds.FloatRound(s/n);const b=t.getKeys();for(let s=0,h=b.length;s{"StandardMaterial"===e.getClassName()?s.push(this._convertStandardMaterialAsync(e,t,i)):-1!==e.getClassName().indexOf("PBR")?s.push(this._convertPBRMaterialAsync(e,t,i)):Ds.Warn(`Unsupported material type: ${e.name}`)})),Promise.all(s).then((()=>{}))}_stripTexturesFromMaterial(e){const t={};if(e){t.name=e.name,t.doubleSided=e.doubleSided,t.alphaMode=e.alphaMode,t.alphaCutoff=e.alphaCutoff,t.emissiveFactor=e.emissiveFactor;const i=e.pbrMetallicRoughness;i&&(t.pbrMetallicRoughness={},t.pbrMetallicRoughness.baseColorFactor=i.baseColorFactor,t.pbrMetallicRoughness.metallicFactor=i.metallicFactor,t.pbrMetallicRoughness.roughnessFactor=i.roughnessFactor)}return t}_hasTexturesPresent(e){if(e.emissiveTexture||e.normalTexture||e.occlusionTexture)return!0;const t=e.pbrMetallicRoughness;if(t&&(t.baseColorTexture||t.metallicRoughnessTexture))return!0;if(e.extensions)for(const t in e.extensions){const i=e.extensions[t];if(i)return i.hasTextures?.()}return!1}_getTextureInfo(e){if(e){const t=e.uid;if(t in this._textureMap)return this._textureMap[t]}return null}_convertToGLTFPBRMetallicRoughness(e){const t=new de(0,1),i=new de(0,.1),s=new de(0,.1),r=new de(1300,.1),n=e.diffuseColor.toLinearSpace(e.getScene().getEngine().useExactSrgbConversions).scale(.5),o=e.alpha,a=(l=be.Clamp(e.specularPower,0,xV._MaxSpecularPower),h=Math.pow(l/r.x,.333333),c=t.y,u=i.y,d=s.y,_=r.y,(1-h)*(1-h)*(1-h)*c+3*(1-h)*(1-h)*h*u+3*(1-h)*h*h*d+h*h*h*_);var l,h,c,u,d,_;return{baseColorFactor:[n.r,n.g,n.b,o],metallicFactor:0,roughnessFactor:a}}static _SolveMetallic(e,t,i){if(t{e&&(o.baseColorTexture=e)})));const i=e.bumpTexture;i&&n.push(this._exportTextureAsync(i,t).then((e=>{e&&(a.normalTexture=e,1!==i.level&&(a.normalTexture.scale=i.level))}))),e.emissiveTexture&&(a.emissiveFactor=[1,1,1],n.push(this._exportTextureAsync(e.emissiveTexture,t).then((e=>{e&&(a.emissiveTexture=e)})))),e.ambientTexture&&n.push(this._exportTextureAsync(e.ambientTexture,t).then((e=>{if(e){const t={index:e.index};a.occlusionTexture=t}})))}return(e.alpha<1||e.opacityTexture)&&(e.alphaMode===N_.ALPHA_COMBINE?a.alphaMode="BLEND":Ds.Warn(e.name+": glTF 2.0 does not support alpha mode: "+e.alphaMode.toString())),e.emissiveColor&&!xV._FuzzyEquals(e.emissiveColor,Ee.Black(),xV._Epsilon)&&(a.emissiveFactor=e.emissiveColor.asArray()),a.pbrMetallicRoughness=o,xV._SetAlphaMode(a,e),r.push(a),s[e.uniqueId]=r.length-1,this._finishMaterial(n,a,e,t)}_finishMaterial(e,t,i,s){return Promise.all(e).then((()=>{const e=this._exporter._extensionsPostExportMaterialAdditionalTextures("exportMaterial",t,i);let r=null;for(const t of e)r||(r=[]),r.push(this._exportTextureAsync(t,s));return r||(r=[Promise.resolve(null)]),Promise.all(r).then((()=>{const e=this._exporter._extensionsPostExportMaterialAsync("exportMaterial",t,i);return e?e.then((()=>t)):t}))}))}async _getImageDataAsync(e,t,i,s){const r=N_.TEXTURETYPE_UNSIGNED_INT,n=this._exporter._babylonScene,o=n.getEngine(),a=o.createRawTexture(e,t,i,N_.TEXTUREFORMAT_RGBA,!1,!0,Pa.NEAREST_SAMPLINGMODE,null,r);await np.ApplyPostProcess("pass",a,n,r,N_.TEXTURE_NEAREST_SAMPLINGMODE,N_.TEXTUREFORMAT_RGBA);const l=await o._readTexturePixels(a,t,i);return await th.DumpDataAsync(t,i,l,s,void 0,!0,!0)}_createWhiteTexture(e,t,i){const s=new Uint8Array(e*t*4);for(let e=0;er.width?(o=t&&t instanceof Pa?np.CreateResizedCopy(t,s.width,s.height,!0):this._createWhiteTexture(s.width,s.height,i),n=e):(n=e,o=t),{texture1:n,texture2:o}}_convertPixelArrayToFloat32(e){if(e instanceof Uint8Array){const t=e.length,i=new Float32Array(e.length);for(let s=0;sxV._Epsilon?T.baseColor.r:1,m[i+1]/=T.baseColor.g>xV._Epsilon?T.baseColor.g:1,m[i+2]/=T.baseColor.b>xV._Epsilon?T.baseColor.b:1;const s=Ee.FromInts(m[i],m[i+1],m[i+2]).toGammaSpace(n.getEngine().useExactSrgbConversions);m[i]=255*s.r,m[i+1]=255*s.g,m[i+2]=255*s.b,xV._FuzzyEquals(s,Ee.White(),xV._Epsilon)||(S=!0),f[i+1]/=T.roughness>xV._Epsilon?T.roughness:1,f[i+2]/=T.metallic>xV._Epsilon?T.metallic:1;const r=Ee.FromInts(255,f[i+1],f[i+2]);xV._FuzzyEquals(r,Ee.White(),xV._Epsilon)||(y=!0)}return y&&r.push(this._getImageDataAsync(f,c,u,s).then((e=>{T.metallicRoughnessTextureData=e}))),S&&r.push(this._getImageDataAsync(m,c,u,s).then((e=>{T.baseColorTextureData=e}))),Promise.all(r).then((()=>T))}return Promise.reject("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!")}_convertSpecularGlossinessToMetallicRoughness(e){const t=this._getPerceivedBrightness(e.diffuseColor),i=this._getPerceivedBrightness(e.specularColor),s=1-this._getMaxComponent(e.specularColor),r=xV._SolveMetallic(t,i,s),n=e.diffuseColor.scale(s/(1-xV._DielectricSpecular.r)/Math.max(1-r,xV._Epsilon)),o=e.specularColor.subtract(xV._DielectricSpecular.scale(1-r)).scale(1/Math.max(r,xV._Epsilon));let a=Ee.Lerp(n,o,r*r);return a=a.clampToRef(0,1,a),{baseColor:a,metallic:r,roughness:1-e.glossiness}}_getPerceivedBrightness(e){return e?Math.sqrt(.299*e.r*e.r+.587*e.g*e.g+.114*e.b*e.b):0}_getMaxComponent(e){return e?Math.max(e.r,Math.max(e.g,e.b)):0}_convertMetalRoughFactorsToMetallicRoughnessAsync(e,t,i,s){const r=[],n={baseColor:e._albedoColor,metallic:e._metallic,roughness:e._roughness};if(s){e._albedoTexture&&r.push(this._exportTextureAsync(e._albedoTexture,t).then((e=>{e&&(i.baseColorTexture=e)})));const s=e._metallicTexture;s&&r.push(this._exportTextureAsync(s,t).then((e=>{e&&(i.metallicRoughnessTexture=e)})))}return Promise.all(r).then((()=>n))}_getTextureSampler(e){const t={};if(!(e&&e instanceof Pa))return t;const i=this._getGLTFTextureWrapMode(e.wrapU);10497!==i&&(t.wrapS=i);const s=this._getGLTFTextureWrapMode(e.wrapV);switch(10497!==s&&(t.wrapT=s),e.samplingMode){case Pa.LINEAR_LINEAR:t.magFilter=9729,t.minFilter=9729;break;case Pa.LINEAR_NEAREST:t.magFilter=9729,t.minFilter=9728;break;case Pa.NEAREST_LINEAR:t.magFilter=9728,t.minFilter=9729;break;case Pa.NEAREST_LINEAR_MIPLINEAR:t.magFilter=9728,t.minFilter=9987;break;case Pa.NEAREST_NEAREST:t.magFilter=9728,t.minFilter=9728;break;case Pa.NEAREST_LINEAR_MIPNEAREST:t.magFilter=9728,t.minFilter=9985;break;case Pa.LINEAR_NEAREST_MIPNEAREST:t.magFilter=9729,t.minFilter=9984;break;case Pa.LINEAR_NEAREST_MIPLINEAR:t.magFilter=9729,t.minFilter=9986;break;case Pa.NEAREST_NEAREST_MIPLINEAR:t.magFilter=9728,t.minFilter=9986;break;case Pa.LINEAR_LINEAR_MIPLINEAR:t.magFilter=9729,t.minFilter=9987;break;case Pa.LINEAR_LINEAR_MIPNEAREST:t.magFilter=9729,t.minFilter=9985;break;case Pa.NEAREST_NEAREST_MIPNEAREST:t.magFilter=9728,t.minFilter=9984}return t}_getGLTFTextureWrapMode(e){switch(e){case Pa.WRAP_ADDRESSMODE:return 10497;case Pa.CLAMP_ADDRESSMODE:return 33071;case Pa.MIRROR_ADDRESSMODE:return 33648;default:return Ds.Error(`Unsupported Texture Wrap Mode ${e}!`),10497}}_convertSpecGlossFactorsToMetallicRoughnessAsync(e,t,i,s){return Promise.resolve().then((()=>{const r={diffuseColor:e._albedoColor,specularColor:e._reflectivityColor,glossiness:e._microSurface},n=e._albedoTexture,o=e._reflectivityTexture,a=e._useMicroSurfaceFromReflectivityMapAlpha;if(o&&!a)return Promise.reject("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture are currently not supported");if((n||o)&&s){const e=this._exportTextureSampler(n||o);return this._convertSpecularGlossinessTexturesToMetallicRoughnessAsync(n,o,r,t).then((s=>{const r=this._exporter._textures;if(s.baseColorTextureData){const o=this._exportImage(`baseColor${r.length}`,t,s.baseColorTextureData);i.baseColorTexture=this._exportTextureInfo(o,e,n?.coordinatesIndex)}if(s.metallicRoughnessTextureData){const n=this._exportImage(`metallicRoughness${r.length}`,t,s.metallicRoughnessTextureData);i.metallicRoughnessTexture=this._exportTextureInfo(n,e,o?.coordinatesIndex)}return s}))}return this._convertSpecularGlossinessToMetallicRoughness(r)}))}_convertPBRMaterialAsync(e,t,i){const s={},r={name:e.name};if(e.isMetallicWorkflow()){const n=e._albedoColor,o=e.alpha;return n&&(s.baseColorFactor=[n.r,n.g,n.b,o]),this._convertMetalRoughFactorsToMetallicRoughnessAsync(e,t,s,i).then((n=>this._setMetallicRoughnessPbrMaterial(n,e,r,s,t,i)))}return this._convertSpecGlossFactorsToMetallicRoughnessAsync(e,t,s,i).then((n=>this._setMetallicRoughnessPbrMaterial(n,e,r,s,t,i)))}_setMetallicRoughnessPbrMaterial(e,t,i,s,r,n){const o=this._exporter._materialMap,a=this._exporter._materials,l=[];if(e){if(xV._SetAlphaMode(i,t),xV._FuzzyEquals(e.baseColor,Ee.White(),xV._Epsilon)&&t.alpha>=xV._Epsilon||(s.baseColorFactor=[e.baseColor.r,e.baseColor.g,e.baseColor.b,t.alpha]),null!=e.metallic&&1!==e.metallic&&(s.metallicFactor=e.metallic),null!=e.roughness&&1!==e.roughness&&(s.roughnessFactor=e.roughness),null==t.backFaceCulling||t.backFaceCulling||(t._twoSidedLighting||Ds.Warn(t.name+": Back-face culling disabled and two-sided lighting disabled is not supported in glTF."),i.doubleSided=!0),n){const e=t._bumpTexture;if(e){const t=this._exportTextureAsync(e,r).then((t=>{t&&(i.normalTexture=t,1!==e.level&&(i.normalTexture.scale=e.level))}));l.push(t)}const s=t._ambientTexture;if(s){const e=this._exportTextureAsync(s,r).then((e=>{if(e){const s={index:e.index,texCoord:e.texCoord,extensions:e.extensions};i.occlusionTexture=s;const r=t._ambientTextureStrength;r&&(s.strength=r)}}));l.push(e)}const n=t._emissiveTexture;if(n){const e=this._exportTextureAsync(n,r).then((e=>{e&&(i.emissiveTexture=e)}));l.push(e)}}const h=t._emissiveColor;xV._FuzzyEquals(h,Ee.Black(),xV._Epsilon)||(i.emissiveFactor=h.asArray()),i.pbrMetallicRoughness=s,a.push(i),o[t.uniqueId]=a.length-1}return this._finishMaterial(l,i,t,r)}_getPixelsFromTexture(e){return e.textureType,N_.TEXTURETYPE_UNSIGNED_INT,e.readPixels()}_exportTextureAsync(e,t){const i=this._exporter._extensionsPreExportTextureAsync("exporter",e,t);return i?i.then((i=>i?this._exportTextureInfoAsync(i,t):this._exportTextureInfoAsync(e,t))):this._exportTextureInfoAsync(e,t)}async _exportTextureInfoAsync(e,t){const i=e.uid;if(!(i in this._textureMap)){const s=await this._getPixelsFromTexture(e);if(!s)return null;const r=this._exportTextureSampler(e),n=e.mimeType;if(n)switch(n){case"image/jpeg":case"image/png":case"image/webp":t=n;break;default:Ds.Warn(`Unsupported media type: ${n}`)}const o=this._internalTextureToImage,a=e.getInternalTexture().uniqueId;o[a]||(o[a]={});let l=o[a][t];if(void 0===l){const i=e.getSize();l=(async()=>{const r=await this._getImageDataAsync(s,i.width,i.height,t);return this._exportImage(e.name,t,r)})(),o[a][t]=l}const h=this._exportTextureInfo(await l,r,e.coordinatesIndex);this._textureMap[i]=h,this._exporter._extensionsPostExportTextures("exporter",this._textureMap[i],e)}return this._textureMap[i]}_exportImage(e,t,i){const s=this._exporter._imageData,r=e.replace(/\.\/|\/|\.\\|\\/g,"_"),n=function(e){switch(e){case"image/jpeg":return".jpg";case"image/png":return".png";case"image/webp":return".webp";case"image/avif":return".avif"}}(t);let o=r+n;o in s&&(o=`${r}_${Ds.RandomId()}${n}`),s[o]={data:i,mimeType:t};const a=this._exporter._images;return a.push({name:e,uri:o}),a.length-1}_exportTextureInfo(e,t,i){const s=this._exporter._textures;let r=s.findIndex((i=>i.sampler==t&&i.source===e));-1===r&&(r=s.length,s.push({source:e,sampler:t}));const n={index:r};return i&&(n.texCoord=i),n}_exportTextureSampler(e){const t=this._getTextureSampler(e),i=this._exporter._samplers,s=i.findIndex((e=>e.minFilter===t.minFilter&&e.magFilter===t.magFilter&&e.wrapS===t.wrapS&&e.wrapT===t.wrapT));return-1!==s?s:(i.push(t),i.length-1)}}xV._DielectricSpecular=new Ee(.04,.04,.04),xV._MaxSpecularPower=1024,xV._Epsilon=1e-6;const bV=me.Compose(new _e(-1,1,1),fe.Identity(),_e.Zero()),TV=new fe(0,1,0,0);function yV(e,t){if(!(e instanceof lo))return!1;if(t){if(!e.getWorldMatrix().isIdentity())return!1}else if(!e.getWorldMatrix().multiplyToRef(bV,ve.Matrix[0]).isIdentity())return!1;return!(e instanceof ha&&e.geometry||e instanceof ca&&e.sourceMesh.geometry)}function SV(e){const t=_e.FromArrayToRef(e.translation||[0,0,0],0,ve.Vector3[0]),i=fe.FromArrayToRef(e.rotation||[0,0,0,1],0,ve.Quaternion[0]),s=_e.FromArrayToRef(e.scale||[1,1,1],0,ve.Vector3[1]);me.ComposeToRef(s,i,t,ve.Matrix[0]).multiplyToRef(bV,ve.Matrix[0]).decompose(s,i,t),t.equalsToFloats(0,0,0)?delete e.translation:e.translation=t.asArray(),fe.IsIdentity(i)?delete e.rotation:e.rotation=i.asArray(),s.equalsToFloats(1,1,1)?delete e.scale:e.scale=s.asArray()}class CV{_applyExtension(e,t,i,s){if(i>=t.length)return Promise.resolve(e);const r=s(t[i],e);return r?r.then((e=>this._applyExtension(e,t,i+1,s))):this._applyExtension(e,t,i+1,s)}_applyExtensions(e,t){const i=[];for(const e of CV._ExtensionNames)i.push(this._extensions[e]);return this._applyExtension(e,i,0,t)}_extensionsPreExportTextureAsync(e,t,i){return this._applyExtensions(t,((t,s)=>t.preExportTextureAsync&&t.preExportTextureAsync(e,s,i)))}_extensionsPostExportMeshPrimitiveAsync(e,t,i,s){return this._applyExtensions(t,((t,r)=>t.postExportMeshPrimitiveAsync&&t.postExportMeshPrimitiveAsync(e,r,i,s)))}_extensionsPostExportNodeAsync(e,t,i,s,r){return this._applyExtensions(t,((t,n)=>t.postExportNodeAsync&&t.postExportNodeAsync(e,n,i,s,r)))}_extensionsPostExportMaterialAsync(e,t,i){return this._applyExtensions(t,((t,s)=>t.postExportMaterialAsync&&t.postExportMaterialAsync(e,s,i)))}_extensionsPostExportMaterialAdditionalTextures(e,t,i){const s=[];for(const r of CV._ExtensionNames){const n=this._extensions[r];n.postExportMaterialAdditionalTextures&&s.push(...n.postExportMaterialAdditionalTextures(e,t,i))}return s}_extensionsPostExportTextures(e,t,i){for(const s of CV._ExtensionNames){const r=this._extensions[s];r.postExportTexture&&r.postExportTexture(e,t,i)}}_forEachExtensions(e){for(const t of CV._ExtensionNames){const i=this._extensions[t];i.enabled&&e(i)}}_extensionsOnExporting(){this._forEachExtensions((e=>{e.wasUsed&&(null==this._glTF.extensionsUsed&&(this._glTF.extensionsUsed=[]),-1===this._glTF.extensionsUsed.indexOf(e.name)&&this._glTF.extensionsUsed.push(e.name),e.required&&(null==this._glTF.extensionsRequired&&(this._glTF.extensionsRequired=[]),-1===this._glTF.extensionsRequired.indexOf(e.name)&&this._glTF.extensionsRequired.push(e.name)),null==this._glTF.extensions&&(this._glTF.extensions={}),e.onExporting&&e.onExporting())}))}_loadExtensions(){for(const e of CV._ExtensionNames){const t=CV._ExtensionFactories[e](this);this._extensions[e]=t}}constructor(e,t){this._extensions={},this._glTF={asset:{generator:`Babylon.js v${oo.Version}`,version:"2.0"}},(e=e||re.LastCreatedScene)&&(this._babylonScene=e,this._bufferViews=[],this._accessors=[],this._meshes=[],this._scenes=[],this._cameras=[],this._nodes=[],this._images=[],this._materials=[],this._materialMap=[],this._textures=[],this._samplers=[],this._skins=[],this._animations=[],this._imageData={},this._orderedImageData=[],this._options=t||{},this._animationSampleRate=this._options.animationSampleRate||1/60,this._glTFMaterialExporter=new xV(this),this._loadExtensions())}dispose(){for(const e in this._extensions)this._extensions[e].dispose()}get options(){return this._options}static RegisterExtension(e,t){CV.UnregisterExtension(e)&&Ds.Warn(`Extension with the name ${e} already exists`),CV._ExtensionFactories[e]=t,CV._ExtensionNames.push(e)}static UnregisterExtension(e){if(!CV._ExtensionFactories[e])return!1;delete CV._ExtensionFactories[e];const t=CV._ExtensionNames.indexOf(e);return-1!==t&&CV._ExtensionNames.splice(t,1),!0}_reorderIndicesBasedOnPrimitiveMode(e,t,i,s,r){switch(t){case ta.TriangleFillMode:s||(s=0);for(let t=e.indexStart,i=e.indexStart+e.indexCount;t=n;--t)r.setUInt32(i[t],s),s+=4;break;case ta.TriangleStripDrawMode:e.indexCount>=3&&(r.setUInt32(i[e.indexStart+2],s+4),r.setUInt32(i[e.indexStart+1],s+8))}}_reorderVertexAttributeDataBasedOnPrimitiveMode(e,t,i,s,r,n){switch(t){case ta.TriangleFillMode:this._reorderTriangleFillMode(e,i,s,r,n);break;case ta.TriangleStripDrawMode:this._reorderTriangleStripDrawMode(e,i,s,r,n);break;case ta.TriangleFanDrawMode:this._reorderTriangleFanMode(e,i,s,r,n)}}_reorderTriangleFillMode(e,t,i,s,r){const n=this._getVertexBufferFromMesh(t,e.getMesh());if(n){const o=n.byteStride/er.GetTypeByteLength(n.type);if(e.verticesCount%3!=0)Ds.Error("The submesh vertices for the triangle fill mode is not divisible by 3!");else{const a=[];let l=0;switch(t){case er.PositionKind:case er.NormalKind:for(let t=e.verticesStart;t=e.verticesStart;--t)l=t*o,a.push(pe.FromArray(i,l));break;case er.ColorKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,4===n.getSize()?a.push(pe.FromArray(i,l)):a.push(_e.FromArray(i,l));break;case er.UVKind:case er.UV2Kind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(de.FromArray(i,l));break;default:Ds.Error(`Unsupported Vertex Buffer type: ${t}`)}this._writeVertexAttributeData(a,s+12,t,r)}else Ds.Warn(`reorderTriangleStripDrawMode: Vertex buffer kind ${t} not present!`)}_reorderTriangleFanMode(e,t,i,s,r){const n=this._getVertexBufferFromMesh(t,e.getMesh());if(n){const o=n.byteStride/er.GetTypeByteLength(n.type),a=[];let l=0;switch(t){case er.PositionKind:case er.NormalKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(_e.FromArray(i,l));break;case er.TangentKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(pe.FromArray(i,l));break;case er.ColorKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(pe.FromArray(i,l)),4===n.getSize()?a.push(pe.FromArray(i,l)):a.push(_e.FromArray(i,l));break;case er.UVKind:case er.UV2Kind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(de.FromArray(i,l));break;default:Ds.Error(`Unsupported Vertex Buffer type: ${t}`)}this._writeVertexAttributeData(a,s,t,r)}else Ds.Warn(`reorderTriangleFanMode: Vertex buffer kind ${t} not present!`)}_writeVertexAttributeData(e,t,i,s){for(const r of e){i===er.NormalKind?r.normalize():i===er.TangentKind&&r instanceof pe&&mV._NormalizeTangentFromRef(r);for(const e of r.asArray())s.setFloat32(e,t),t+=4}}_writeAttributeData(e,t,i,s,r,n){let o,a,l=[];switch(e){case er.PositionKind:for(let e=0,t=i.length/s;e{e.uri&&(n=this._imageData[e.uri],this._orderedImageData.push(n),r=e.uri.split(".")[0]+" image",o=mV._CreateBufferView(0,a,n.data.byteLength,void 0,r),a+=n.data.byteLength,this._bufferViews.push(o),e.bufferView=this._bufferViews.length-1,e.name=r,e.mimeType=n.mimeType,e.uri=void 0,this._glTF.images||(this._glTF.images=[]),this._glTF.images.push(e))})),s.byteLength=a):this._glTF.images=this._images),e||(s.uri=t+".bin"),i?JSON.stringify(this._glTF,null,2):JSON.stringify(this._glTF)}_generateGLTFAsync(e,t=!0){return this._generateBinaryAsync().then((i=>{this._extensionsOnExporting();const s=this._generateJSON(!1,e,!0),r=new Blob([i],{type:"application/octet-stream"}),n=e+".gltf",o=e+".bin",a=new vV;if(a.glTFFiles[n]=s,a.glTFFiles[o]=r,this._imageData)for(const e in this._imageData)a.glTFFiles[e]=new Blob([this._imageData[e].data],{type:this._imageData[e].mimeType});return t&&this.dispose(),a}))}_generateBinaryAsync(){const e=new EV(4);return this._createSceneAsync(e).then((()=>(this._localEngine&&this._localEngine.dispose(),e.getArrayBuffer())))}_getPadding(e){const t=e%4;return 0===t?t:4-t}_generateGLBAsync(e,t=!0){return this._generateBinaryAsync().then((i=>{this._extensionsOnExporting();const s=this._generateJSON(!0),r=e+".glb";let n,o=s.length,a=0;"undefined"!=typeof TextEncoder&&(n=(new TextEncoder).encode(s),o=n.length);for(let e=0;e0){if((null!==o.overrideMaterialSideOrientation?o.overrideMaterialSideOrientation:d.sideOrientation)===(this._babylonScene.useRightHandedSystem?ta.ClockWiseSideOrientation:ta.CounterClockWiseSideOrientation)){let e=null!=l?this._bufferViews[l].byteOffset:null;null==e&&(e=0);let t=null;if(null!=l&&(t=o.getIndices()),t)this._reorderIndicesBasedOnPrimitiveMode(r,h,t,e,i);else for(const e of a){const t=o.getVerticesData(e.kind,void 0,void 0,!0);if(t){const s=this._bufferViews[c[e.kind]].byteOffset||0;this._reorderVertexAttributeDataBasedOnPrimitiveMode(r,h,e.kind,t,s,i)}}}null!=_&&(f.material=_)}if(u){e.extras||(e.extras={}),e.extras.targetNames=[];for(let t=0;t{}))}_createSceneAsync(e){const t={nodes:[]};let i,s,r;const n=[...this._babylonScene.transformNodes,...this._babylonScene.meshes,...this._babylonScene.lights,...this._babylonScene.cameras],o=new Set;if(this._babylonScene.metadata&&(this._options.metadataSelector?t.extras=this._options.metadataSelector(this._babylonScene.metadata):this._babylonScene.metadata.gltf&&(t.extras=this._babylonScene.metadata.gltf.extras)),(this._options.removeNoopRootNodes??1)&&!this._options.includeCoordinateSystemConversionNodes)for(const e of this._babylonScene.rootNodes)yV(e,this._babylonScene.useRightHandedSystem)&&(o.add(e),n.splice(n.indexOf(e),1));const a=new Map;this._babylonScene.cameras.forEach((e=>{if(this._options.shouldExportNode&&!this._options.shouldExportNode(e))return;const t={type:e.mode===In.PERSPECTIVE_CAMERA?"perspective":"orthographic"};if(e.name&&(t.name=e.name),"perspective"===t.type)t.perspective={aspectRatio:e.getEngine().getAspectRatio(e),yfov:e.fovMode===In.FOVMODE_VERTICAL_FIXED?e.fov:e.fov*e.getEngine().getAspectRatio(e),znear:e.minZ,zfar:e.maxZ};else if("orthographic"===t.type){const i=e.orthoLeft&&e.orthoRight?.5*(e.orthoRight-e.orthoLeft):.5*e.getEngine().getRenderWidth(),s=e.orthoBottom&&e.orthoTop?.5*(e.orthoTop-e.orthoBottom):.5*e.getEngine().getRenderHeight();t.orthographic={xmag:i,ymag:s,znear:e.minZ,zfar:e.maxZ}}a.set(e,this._cameras.length),this._cameras.push(t)}));const[l,h]=this._getExportNodes(n);return this._glTFMaterialExporter._convertMaterialsToGLTFAsync(h,"image/png",!0).then((()=>this._createNodeMapAndAnimationsAsync(l,e).then((l=>this._createSkinsAsync(l,e).then((h=>{if(this._nodeMap=l,this._totalByteLength=e.getByteOffset(),null==this._totalByteLength)throw new Error("undefined byte length!");for(const e of n)if(i=this._nodeMap[e.uniqueId],void 0!==i&&(s=this._nodes[i],e.metadata&&(this._options.metadataSelector?s.extras=this._options.metadataSelector(e.metadata):e.metadata.gltf&&(s.extras=e.metadata.gltf.extras)),e instanceof In&&(s.camera=a.get(e)),this._options.shouldExportNode&&!this._options.shouldExportNode(e)?Ds.Log("Omitting "+e.name+" from scene."):(e.parent||this._babylonScene.useRightHandedSystem||SV(s),e.parent&&!o.has(e.parent)||t.nodes.push(i)),e instanceof ha&&e.skeleton&&(s.skin=h[e.skeleton.uniqueId]),r=e.getDescendants(!0),!s.children&&r&&r.length)){const e=[];for(const t of r)null!=this._nodeMap[t.uniqueId]&&e.push(this._nodeMap[t.uniqueId]);e.length&&(s.children=e)}t.nodes.length&&this._scenes.push(t)}))))))}_getExportNodes(e){const t=[],i=new Set;for(const s of e)if(!this._options.shouldExportNode||this._options.shouldExportNode(s)){t.push(s);const e=s;if(e.subMeshes&&e.subMeshes.length>0){const t=e.material||e.getScene().defaultMaterial;if(t instanceof ia)for(const e of t.subMaterials)e&&i.add(e);else i.add(t)}}else s.name;return[t,i]}_createNodeMapAndAnimationsAsync(e,t){let i=Promise.resolve();const s={};let r;const n={name:"runtime animations",channels:[],samplers:[]},o=[];for(const a of e)i=i.then((()=>this._createNodeAsync(a,t).then((e=>{const i=this._extensionsPostExportNodeAsync("createNodeAsync",e,a,s,t);return null==i?(Ds.Warn(`Not exporting node ${a.name}`),Promise.resolve()):i.then((e=>{e&&(this._nodes.push(e),r=this._nodes.length-1,s[a.uniqueId]=r,this._babylonScene.animationGroups.length||(gV._CreateMorphTargetAnimationFromMorphTargetAnimations(a,n,o,s,this._nodes,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation),a.animations.length&&gV._CreateNodeAnimationFromNodeAnimations(a,n,o,s,this._nodes,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation)))}))}))));return i.then((()=>(n.channels.length&&n.samplers.length&&this._animations.push(n),o.forEach((e=>{e.channels.length&&e.samplers.length&&this._animations.push(e)})),this._babylonScene.animationGroups.length&&gV._CreateNodeAndMorphAnimationFromAnimationGroups(this._babylonScene,this._animations,s,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation),s)))}_createNodeAsync(e,t){return Promise.resolve().then((()=>{const i={},s={primitives:[]};if(e.name&&(i.name=e.name),e instanceof lo){if(this._setNodeTransformation(i,e),e instanceof ha){const t=e.morphTargetManager;if(t&&t.numTargets>0){s.weights=[];for(let e=0;e(s.primitives.length&&(this._meshes.push(s),i.mesh=this._meshes.length-1),i)))}return e instanceof In?(this._setCameraTransformation(i,e),i):i}))}_createSkinsAsync(e,t){const i=Promise.resolve(),s={};for(const i of this._babylonScene.skeletons){if(i.bones.length<=0)continue;const r={joints:[]},n=[],o={};let a=-1;for(let e=0;ea&&(a=s))}for(let t=0;t<=a;++t){const i=o[t];n.push(i.getInvertedAbsoluteTransform());const s=i.getTransformNode();s&&null!==e[s.uniqueId]&&void 0!==e[s.uniqueId]?r.joints.push(e[s.uniqueId]):Ds.Warn("Exporting a bone without a linked transform node is currently unsupported")}if(r.joints.length>0){const e=64,o=n.length*e,a=t.getByteOffset(),l=mV._CreateBufferView(0,a,o,void 0,"InverseBindMatrices - "+i.name);this._bufferViews.push(l);const h=this._bufferViews.length-1,c=mV._CreateAccessor(h,"InverseBindMatrices - "+i.name,"MAT4",5126,n.length,null,null,null),u=this._accessors.push(c)-1;r.inverseBindMatrices=u,this._skins.push(r),s[i.uniqueId]=this._skins.length-1,n.forEach((e=>{e.m.forEach((e=>{t.setFloat32(e)}))}))}}return i.then((()=>s))}}CV._ExtensionNames=new Array,CV._ExtensionFactories={};class EV{constructor(e){this._arrayBuffer=new ArrayBuffer(e),this._dataView=new DataView(this._arrayBuffer),this._byteOffset=0}_resizeBuffer(e){const t=new ArrayBuffer(e),i=Math.min(this._arrayBuffer.byteLength,e),s=new Uint8Array(this._arrayBuffer,0,i);return new Uint8Array(t).set(s,0),this._arrayBuffer=t,this._dataView=new DataView(this._arrayBuffer),t}getArrayBuffer(){return this._resizeBuffer(this.getByteOffset())}getByteOffset(){if(null==this._byteOffset)throw new Error("Byte offset is undefined!");return this._byteOffset}setUInt8(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint8(this._byteOffset,e),this._byteOffset+=1)}setUInt16(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint16(this._byteOffset,e,!0),this._byteOffset+=2)}getUInt32(e){if(ethis._byteOffset?Ds.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(e.x=this._dataView.getFloat32(t,!0),e.y=this._dataView.getFloat32(t+4,!0),e.z=this._dataView.getFloat32(t+8,!0))}setVector3Float32FromRef(e,t){t+8>this._byteOffset?Ds.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._dataView.setFloat32(t,e.x,!0),this._dataView.setFloat32(t+4,e.y,!0),this._dataView.setFloat32(t+8,e.z,!0))}getVector4Float32FromRef(e,t){t+12>this._byteOffset?Ds.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(e.x=this._dataView.getFloat32(t,!0),e.y=this._dataView.getFloat32(t+4,!0),e.z=this._dataView.getFloat32(t+8,!0),e.w=this._dataView.getFloat32(t+12,!0))}setVector4Float32FromRef(e,t){t+12>this._byteOffset?Ds.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._dataView.setFloat32(t,e.x,!0),this._dataView.setFloat32(t+4,e.y,!0),this._dataView.setFloat32(t+8,e.z,!0),this._dataView.setFloat32(t+12,e.w,!0))}setFloat32(e,t){isNaN(e)&&Ds.Error("Invalid data being written!"),null!=t&&(tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setFloat32(this._byteOffset,e,!0),this._byteOffset+=4}setUInt32(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint32(this._byteOffset,e,!0),this._byteOffset+=4)}setInt16(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setInt16(this._byteOffset,e,!0),this._byteOffset+=2)}setByte(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setInt8(this._byteOffset,e),this._byteOffset++)}}class AV{static GLTFAsync(e,t,i){return e.whenReadyAsync().then((()=>{const s=t.replace(/\.[^/.]+$/,"");return new CV(e,i)._generateGLTFAsync(s)}))}static _PreExportAsync(e,t){return Promise.resolve().then((()=>t&&t.exportWithoutWaitingForScene?Promise.resolve():e.whenReadyAsync()))}static _PostExportAsync(e,t,i){return Promise.resolve().then((()=>(i&&i.exportWithoutWaitingForScene,t)))}static GLBAsync(e,t,i){return this._PreExportAsync(e,i).then((()=>{const s=t.replace(/\.[^/.]+$/,"");return new CV(e,i)._generateGLBAsync(s).then((t=>this._PostExportAsync(e,t,i)))}))}}const PV="KHR_texture_transform";class IV{constructor(){this.name=PV,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}postExportTexture(e,t,i){if(i&&(0===i.uAng&&0===i.wAng&&0===i.vAng||0===i.uRotationCenter&&0===i.vRotationCenter)){const e={};let s=!1;if(0===i.uOffset&&0===i.vOffset||(e.offset=[i.uOffset,i.vOffset],s=!0),1===i.uScale&&1===i.vScale||(e.scale=[i.uScale,i.vScale],s=!0),0!==i.wAng&&(e.rotation=-i.wAng,s=!0),0!==i.coordinatesIndex&&(e.texCoord=i.coordinatesIndex,s=!0),!s)return;this._wasUsed=!0,t.extensions||(t.extensions={}),t.extensions[PV]=e}}preExportTextureAsync(e,t){return new Promise(((i,s)=>{t.getScene()?0!==t.uAng||0!==t.vAng?(Ds.Warn(`${e}: Texture ${t.name} with rotation in the u or v axis is not supported in glTF.`),i(null)):0===t.wAng||0===t.uRotationCenter&&0===t.vRotationCenter?i(t):(Ds.Warn(`${e}: Texture ${t.name} with rotation not centered at the origin cannot be exported with ${PV}`),i(null)):s(`${e}: "scene" is not defined for Babylon texture ${t.name}!`)}))}}CV.RegisterExtension(PV,(()=>new IV));const RV="KHR_lights_punctual";class MV{constructor(e){this.name=RV,this.enabled=!0,this.required=!1,this._exporter=e}dispose(){this._lights=null}get wasUsed(){return!!this._lights}onExporting(){this._exporter._glTF.extensions[RV]=this._lights}postExportNodeAsync(e,t,i,s){return new Promise((r=>{if(t&&i instanceof hg){let n;const o=i.getTypeID()==ua.LIGHTTYPEID_POINTLIGHT?"point":i.getTypeID()==ua.LIGHTTYPEID_DIRECTIONALLIGHT?"directional":i.getTypeID()==ua.LIGHTTYPEID_SPOTLIGHT?"spot":null;if(null==o)Ne.Warn(`${e}: Light ${i.name} is not supported in ${RV}`);else{if(i.position.equalsToFloats(0,0,0)||(t.translation=i.position.asArray()),"point"!==o){const e=i.direction,s=-Math.atan2(e.z,e.x)+Math.PI/2,r=Math.sqrt(e.x*e.x+e.z*e.z),n=-Math.atan2(e.y,r),o=fe.RotationYawPitchRoll(s+Math.PI,n,0);fe.IsIdentity(o)||(t.rotation=o.asArray())}if(i.falloffType!==ua.FALLOFF_GLTF&&Ne.Warn(`${e}: Light falloff for ${i.name} does not match the ${RV} specification!`),n={type:o},i.diffuse.equals(Ee.White())||(n.color=i.diffuse.asArray()),1!==i.intensity&&(n.intensity=i.intensity),i.range!==Number.MAX_VALUE&&(n.range=i.range),"spot"===o){const e=i;e.angle!==Math.PI/2&&(null==n.spot&&(n.spot={}),n.spot.outerConeAngle=e.angle/2),0!==e.innerAngle&&(null==n.spot&&(n.spot={}),n.spot.innerConeAngle=e.innerAngle/2)}this._lights||(this._lights={lights:[]}),this._lights.lights.push(n);const a={light:this._lights.lights.length-1},l=i.parent;if(l&&1==l.getChildren().length){const e=this._exporter._nodes[s[l.uniqueId]];if(e){const i=_e.FromArrayToRef(e.translation||[0,0,0],0,ve.Vector3[0]),s=fe.FromArrayToRef(e.rotation||[0,0,0,1],0,ve.Quaternion[0]),n=_e.FromArrayToRef(e.scale||[1,1,1],0,ve.Vector3[1]),o=me.ComposeToRef(n,s,i,ve.Matrix[0]),l=_e.FromArrayToRef(t.translation||[0,0,0],0,ve.Vector3[2]),h=fe.FromArrayToRef(t.rotation||[0,0,0,1],0,ve.Quaternion[1]),c=me.ComposeToRef(_e.OneReadOnly,h,l,ve.Matrix[1]);return o.multiplyToRef(c,c),c.decompose(n,s,i),i.equalsToFloats(0,0,0)?delete e.translation:e.translation=i.asArray(),fe.IsIdentity(s)?delete e.rotation:e.rotation=s.asArray(),n.equalsToFloats(1,1,1)?delete e.scale:e.scale=n.asArray(),e.extensions||(e.extensions={}),e.extensions[RV]=a,void r(null)}}t.extensions||(t.extensions={}),t.extensions[RV]=a}}r(t)}))}}CV.RegisterExtension(RV,(e=>new MV(e)));const OV="KHR_materials_clearcoat";class DV{constructor(e){this.name=OV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Gg&&i.clearCoat.isEnabled?(i.clearCoat.texture&&s.push(i.clearCoat.texture),!i.clearCoat.useRoughnessFromMainTexture&&i.clearCoat.textureRoughness&&s.push(i.clearCoat.textureRoughness),i.clearCoat.bumpTexture&&s.push(i.clearCoat.bumpTexture),s):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Gg){if(!i.clearCoat.isEnabled)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const s=this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.texture);let r;r=i.clearCoat.useRoughnessFromMainTexture?this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.texture):this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.textureRoughness),i.clearCoat.isTintEnabled&&Ds.Warn(`Clear Color tint is not supported for glTF export. Ignoring for: ${i.name}`),i.clearCoat.remapF0OnInterfaceChange&&Ds.Warn(`Clear Color F0 remapping is not supported for glTF export. Ignoring for: ${i.name}`);const n=this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.bumpTexture),o={clearcoatFactor:i.clearCoat.intensity,clearcoatTexture:s??void 0,clearcoatRoughnessFactor:i.clearCoat.roughness,clearcoatRoughnessTexture:r??void 0,clearcoatNormalTexture:n??void 0,hasTextures:()=>null!==o.clearcoatTexture||null!==o.clearcoatRoughnessTexture||null!==o.clearcoatRoughnessTexture};t.extensions[OV]=o}e(t)}))}}CV.RegisterExtension(OV,(e=>new DV(e)));const wV="KHR_materials_iridescence";class NV{constructor(e){this.name=wV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Gg&&i.iridescence.isEnabled?(i.iridescence.texture&&s.push(i.iridescence.texture),i.iridescence.thicknessTexture&&i.iridescence.thicknessTexture!==i.iridescence.texture&&s.push(i.iridescence.thicknessTexture),s):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Gg){if(!i.iridescence.isEnabled)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const s=this._exporter._glTFMaterialExporter._getTextureInfo(i.iridescence.texture),r=this._exporter._glTFMaterialExporter._getTextureInfo(i.iridescence.thicknessTexture),n={iridescenceFactor:i.iridescence.intensity,iridescenceIor:i.iridescence.indexOfRefraction,iridescenceThicknessMinimum:i.iridescence.minimumThickness,iridescenceThicknessMaximum:i.iridescence.maximumThickness,iridescenceTexture:s??void 0,iridescenceThicknessTexture:r??void 0,hasTextures:()=>null!==n.iridescenceTexture||null!==n.iridescenceThicknessTexture};t.extensions[wV]=n}e(t)}))}}CV.RegisterExtension(wV,(e=>new NV(e)));const FV="KHR_materials_anisotropy";class LV{constructor(e){this.name=FV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Gg&&i.anisotropy.isEnabled&&!i.anisotropy.legacy?(i.anisotropy.texture&&s.push(i.anisotropy.texture),s):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Gg){if(!i.anisotropy.isEnabled||i.anisotropy.legacy)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const s=this._exporter._glTFMaterialExporter._getTextureInfo(i.anisotropy.texture),r={anisotropyStrength:i.anisotropy.intensity,anisotropyRotation:i.anisotropy.angle,anisotropyTexture:s??void 0,hasTextures:()=>null!==r.anisotropyTexture};t.extensions[FV]=r}e(t)}))}}CV.RegisterExtension(FV,(e=>new LV(e)));const BV="KHR_materials_sheen";class kV{constructor(e){this.name=BV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){return i instanceof zg&&i.sheen.isEnabled&&i.sheen.texture?[i.sheen.texture]:[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zg){if(!i.sheen.isEnabled)return void e(t);this._wasUsed=!0,null==t.extensions&&(t.extensions={});const s={sheenColorFactor:i.sheen.color.asArray(),sheenRoughnessFactor:i.sheen.roughness??0,hasTextures:()=>null!==s.sheenColorTexture||null!==s.sheenRoughnessTexture};i.sheen.texture&&(s.sheenColorTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.texture)??void 0),i.sheen.textureRoughness&&!i.sheen.useRoughnessFromMainTexture?s.sheenRoughnessTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.textureRoughness)??void 0:i.sheen.texture&&i.sheen.useRoughnessFromMainTexture&&(s.sheenRoughnessTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.texture)??void 0),t.extensions[BV]=s}e(t)}))}}CV.RegisterExtension(BV,(e=>new kV(e)));const VV="KHR_materials_unlit";class UV{constructor(){this.name=VV,this.enabled=!0,this.required=!1,this._wasUsed=!1}get wasUsed(){return this._wasUsed}dispose(){}postExportMaterialAsync(e,t,i){return new Promise((e=>{let s=!1;i instanceof zg?s=i.unlit:i instanceof cu&&(s=i.disableLighting),s&&(this._wasUsed=!0,null==t.extensions&&(t.extensions={}),t.extensions[VV]={}),e(t)}))}}CV.RegisterExtension(VV,(()=>new UV));const GV="KHR_materials_ior";class zV{constructor(){this.name=GV,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}_isExtensionEnabled(e){return!e.unlit&&null!=e.indexOfRefraction&&1.5!=e.indexOfRefraction}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zg&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e={ior:i.indexOfRefraction};t.extensions=t.extensions||{},t.extensions[GV]=e}e(t)}))}}CV.RegisterExtension(GV,(e=>new zV));const WV="KHR_materials_specular";class HV{constructor(e){this.name=WV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof zg&&this._isExtensionEnabled(i)?(i.metallicReflectanceTexture&&s.push(i.metallicReflectanceTexture),i.reflectanceTexture&&s.push(i.reflectanceTexture),s):s}_isExtensionEnabled(e){return!e.unlit&&(null!=e.metallicF0Factor&&1!=e.metallicF0Factor||null!=e.metallicReflectanceColor&&!e.metallicReflectanceColor.equalsFloats(1,1,1)||this._hasTexturesExtension(e))}_hasTexturesExtension(e){return null!=e.metallicReflectanceTexture||null!=e.reflectanceTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zg&&this._isExtensionEnabled(i)){this._wasUsed=!0,t.extensions=t.extensions||{};const e=this._exporter._glTFMaterialExporter._getTextureInfo(i.metallicReflectanceTexture)??void 0,s=this._exporter._glTFMaterialExporter._getTextureInfo(i.reflectanceTexture)??void 0,r={specularFactor:1==i.metallicF0Factor?void 0:i.metallicF0Factor,specularTexture:e,specularColorFactor:i.metallicReflectanceColor.equalsFloats(1,1,1)?void 0:i.metallicReflectanceColor.asArray(),specularColorTexture:s,hasTextures:()=>this._hasTexturesExtension(i)};t.extensions[WV]=r}e(t)}))}}CV.RegisterExtension(WV,(e=>new HV(e)));const XV="KHR_materials_volume";class YV{constructor(e){this.name=XV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof zg&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&s.push(i.subSurface.thicknessTexture),s):s}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!(!t.isRefractionEnabled&&!t.isTranslucencyEnabled)&&(null!=t.maximumThickness&&0!=t.maximumThickness||null!=t.tintColorAtDistance&&t.tintColorAtDistance!=Number.POSITIVE_INFINITY||null!=t.tintColor&&t.tintColor!=Ee.White()||this._hasTexturesExtension(e))}_hasTexturesExtension(e){return null!=e.subSurface.thicknessTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zg&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e=i.subSurface,s={thicknessFactor:0==e.maximumThickness?void 0:e.maximumThickness,thicknessTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.thicknessTexture)??void 0,attenuationDistance:e.tintColorAtDistance==Number.POSITIVE_INFINITY?void 0:e.tintColorAtDistance,attenuationColor:e.tintColor.equalsFloats(1,1,1)?void 0:e.tintColor.asArray(),hasTextures:()=>this._hasTexturesExtension(i)};t.extensions=t.extensions||{},t.extensions[XV]=s}e(t)}))}}CV.RegisterExtension(XV,(e=>new YV(e)));const QV="KHR_materials_dispersion";class jV{constructor(){this.name=QV,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!(!t.isRefractionEnabled&&!t.isDispersionEnabled)}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zg&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e={dispersion:i.subSurface.dispersion};t.extensions=t.extensions||{},t.extensions[QV]=e}e(t)}))}}CV.RegisterExtension(QV,(()=>new jV));const KV="KHR_materials_transmission";class $V{constructor(e){this.name=KV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof zg&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&s.push(i.subSurface.thicknessTexture),s):s}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return t.isRefractionEnabled&&null!=t.refractionIntensity&&0!=t.refractionIntensity||this._hasTexturesExtension(e)}_hasTexturesExtension(e){return null!=e.subSurface.refractionIntensityTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zg&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e=i.subSurface,s={transmissionFactor:0===e.refractionIntensity?void 0:e.refractionIntensity,transmissionTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.refractionIntensityTexture)??void 0,hasTextures:()=>this._hasTexturesExtension(i)};t.extensions=t.extensions||{},t.extensions[KV]=s}e(t)}))}}CV.RegisterExtension(KV,(e=>new $V(e)));const qV="EXT_mesh_gpu_instancing";class ZV{constructor(e){this.name=qV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportNodeAsync(e,t,i,s,r){return new Promise((e=>{if(t&&i instanceof ha&&i.hasThinInstances&&r){this._wasUsed=!0;const e=_e.Zero(),s=fe.Identity(),n=_e.One(),o=i.thinInstanceGetWorldMatrices(),a=ve.Vector3[2],l=ve.Quaternion[1],h=ve.Vector3[3];let c=!1,u=!1,d=!1;const _=new Float32Array(3*i.thinInstanceCount),p=new Float32Array(4*i.thinInstanceCount),f=new Float32Array(3*i.thinInstanceCount);let m=0;for(const t of o)t.decompose(h,l,a),_.set(a.asArray(),3*m),p.set(l.normalize().asArray(),4*m),f.set(h.asArray(),3*m),c=c||!a.equalsWithEpsilon(e),u=u||!l.equalsWithEpsilon(s),d=d||!h.equalsWithEpsilon(n),m++;const g={attributes:{}};if(c&&(g.attributes.TRANSLATION=this._buildAccessor(_,"VEC3",i.thinInstanceCount,r,5126)),u){const e=5126;g.attributes.ROTATION=this._buildAccessor(p,"VEC4",i.thinInstanceCount,r,e)}d&&(g.attributes.SCALE=this._buildAccessor(f,"VEC3",i.thinInstanceCount,r,5126)),t.extensions=t.extensions||{},t.extensions[qV]=g}e(t)}))}_buildAccessor(e,t,i,s,r){const n=s.getByteOffset();switch(r){case 5126:for(let t=0;t!=e.length;t++)s.setFloat32(e[t]);break;case 5120:for(let t=0;t!=e.length;t++)s.setByte(127*e[t]);break;case 5122:for(let t=0;t!=e.length;t++)s.setInt16(32767*e[t])}const o={buffer:0,byteOffset:n,byteLength:e.length*er.GetTypeByteLength(r)},a=this._exporter._bufferViews.length;this._exporter._bufferViews.push(o);const l=this._exporter._accessors.length,h={bufferView:a,componentType:r,count:i,type:t,normalized:5120==r||5122==r};return this._exporter._accessors.push(h),l}}CV.RegisterExtension(qV,(e=>new ZV(e)));const JV="KHR_materials_emissive_strength";class eU{constructor(){this.name=JV,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(!(i instanceof zg))return e(t);const s=i.emissiveColor.asArray(),r=Math.max(...s);if(r>1){this._wasUsed=!0,t.extensions||(t.extensions={});const e={emissiveStrength:r},s=i.emissiveColor.scale(1/e.emissiveStrength);t.emissiveFactor=s.asArray(),t.extensions[JV]=e}return e(t)}))}}CV.RegisterExtension(JV,(e=>new eU));const tU="KHR_materials_diffuse_transmission";class iU{constructor(e){this.name=tU,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof zg&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&s.push(i.subSurface.thicknessTexture),s):s}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!!t.isTranslucencyEnabled&&!e.unlit&&!t.useAlbedoToTintTranslucency&&t.useGltfStyleTextures&&1===t.volumeIndexOfRefraction&&0===t.minimumThickness&&0===t.maximumThickness}_hasTexturesExtension(e){return null!=e.subSurface.translucencyIntensityTexture||null!=e.subSurface.translucencyColorTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zg&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e=i.subSurface,s={diffuseTransmissionFactor:1==e.translucencyIntensity?void 0:e.translucencyIntensity,diffuseTransmissionTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.translucencyIntensityTexture)??void 0,diffuseTransmissionColorFactor:!e.translucencyColor||e.translucencyColor.equalsFloats(1,1,1)?void 0:e.translucencyColor.asArray(),diffuseTransmissionColorTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.translucencyColorTexture)??void 0,hasTextures:()=>this._hasTexturesExtension(i)};t.extensions=t.extensions||{},t.extensions[tU]=s}e(t)}))}}CV.RegisterExtension(tU,(e=>new iU(e)));class sU{static CreateSTL(e,t=!0,i="stlmesh",s=!1,r=!0,n=!1,o=!1,a=!1){const l=function(e,t,i){const s=[3*e[i],3*e[i+1],3*e[i+2]],r=[new _e(t[s[0]],t[s[0]+2],t[s[0]+1]),new _e(t[s[1]],t[s[1]+2],t[s[1]+1]),new _e(t[s[2]],t[s[2]+2],t[s[2]+1])],n=r[0].subtract(r[1]),o=r[2].subtract(r[1]);return{v:r,n:_e.Cross(o,n).normalize()}},h=function(e,t,i,s){return t=c(e,t,i.x,s),t=c(e,t,i.y,s),c(e,t,i.z,s)},c=function(e,t,i,s){return e.setFloat32(t,i,s),t+4},u=function(e){if(o){let t=e;e instanceof ca&&(t=e.sourceMesh);const i=t.getVerticesData(er.PositionKind,!0,!0);if(!i)return[];const s=_e.Zero();let r;for(r=0;r"bitbybit-hdrSkyBox"!==e.name&&!e.name.includes("bitbybit-ground")}),AV.GLBAsync(this.context.scene,e.fileName,t).then((e=>{e.downloadFiles()}))}exportMeshToStl(e){return NU(this,void 0,void 0,(function*(){const t=e.mesh.getChildMeshes();let i=[];t&&t.length>0&&(i=t.filter((e=>!(e instanceof Fd||e instanceof MS))));let s=[e.mesh,...i];return s=s.filter((e=>e.isVisible)),sU.CreateSTL(s,!0,e.fileName,!0,!0,!0),Promise.resolve({})}))}exportMeshesToStl(e){return NU(this,void 0,void 0,(function*(){let t;return e.meshes.forEach((e=>{const i=e.getChildMeshes();let s=[];i&&i.length>0&&(s=i.filter((e=>!(e instanceof Fd||e instanceof MS)))),t.push(e),s.length>0&&t.push(...s)})),sU.CreateSTL(t,!0,e.fileName,!0,!0,!0),Promise.resolve({})}))}loadAsset(e,t,i,s){return NU(this,void 0,void 0,(function*(){const e=yield fl.ImportMeshAsync("",t,i,this.context.scene),r=this.context.scene.metadata.shadowGenerators,n=new ha("ImportedMeshContainer"+Math.random(),this.context.scene);return r.length>0&&e.meshes.forEach((e=>{if(e.isPickable=!1,s&&(e.isVisible=!1),e.getChildMeshes().forEach((e=>{e.isPickable=!1,s&&(e.isVisible=!1)})),this.context.scene.metadata.shadowGenerators.length>0){try{e.receiveShadows=!0}catch(e){}r.forEach((t=>{t.addShadowCaster(e)})),e.getChildMeshes().forEach((e=>{try{e.receiveShadows=!0}catch(e){}r.forEach((t=>{t.addShadowCaster(e)}))}))}})),e.meshes.forEach((e=>{e.parent=n})),n}))}}!function(e){e.GetAssetDto=class{constructor(e){void 0!==e&&(this.fileName=e)}},e.FileDto=class{constructor(e){void 0!==e&&(this.file=e)}},e.FetchDto=class{constructor(e,t){void 0!==e&&(this.url=e),void 0!==t&&(this.options=t)}},e.FilesDto=class{constructor(e){void 0!==e&&(this.files=e)}},e.AssetFileDto=class{constructor(e,t){this.hidden=!1,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.hidden=t)}},e.AssetFileByUrlDto=class{constructor(e,t,i){this.hidden=!1,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.rootUrl=t),void 0!==i&&(this.hidden=i)}}}(rU||(rU={})),function(e){e.ArcRotateCameraDto=class{constructor(e,t,i,s,r,n,o,a,l,h){this.radius=20,this.target=[0,0,0],this.alpha=45,this.beta=70,this.lowerBetaLimit=1,this.upperBetaLimit=179,this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.panningSensibility=1e3,this.wheelPrecision=3,this.maxZ=1e3,void 0!==e&&(this.radius=e),void 0!==t&&(this.alpha=t),void 0!==i&&(this.beta=i),void 0!==s&&(this.lowerBetaLimit=s),void 0!==r&&(this.upperBetaLimit=r),void 0!==n&&(this.angularSensibilityX=n),void 0!==o&&(this.angularSensibilityY=o),void 0!==a&&(this.panningSensibility=a),void 0!==l&&(this.wheelPrecision=l),void 0!==h&&(this.maxZ=h)}},e.FreeCameraDto=class{constructor(e,t){this.position=[20,20,20],this.target=[0,0,0],void 0!==e&&(this.position=e),void 0!==t&&(this.target=t)}},e.TargetCameraDto=class{constructor(e,t){this.position=[20,20,20],this.target=[0,0,0],void 0!==e&&(this.position=e),void 0!==t&&(this.target=t)}},e.PositionDto=class{constructor(e,t){this.position=[20,20,20],void 0!==e&&(this.camera=e),void 0!==t&&(this.position=t)}},e.SpeedDto=class{constructor(e,t){this.speed=1,void 0!==e&&(this.camera=e),void 0!==t&&(this.speed=t)}},e.TargetDto=class{constructor(e,t){this.target=[0,0,0],void 0!==e&&(this.camera=e),void 0!==t&&(this.target=t)}},e.MinZDto=class{constructor(e,t){this.minZ=0,void 0!==e&&(this.camera=e),void 0!==t&&(this.minZ=t)}},e.MaxZDto=class{constructor(e,t){this.maxZ=1e3,void 0!==e&&(this.camera=e),void 0!==t&&(this.maxZ=t)}},e.OrthographicDto=class{constructor(e,t,i,s,r){this.orthoLeft=-1,this.orthoRight=1,this.orthoBottom=-1,this.orthoTop=1,void 0!==e&&(this.camera=e),void 0!==t&&(this.orthoLeft=t),void 0!==i&&(this.orthoRight=i),void 0!==s&&(this.orthoTop=s),void 0!==r&&(this.orthoBottom=r)}},e.CameraDto=class{constructor(e){void 0!==e&&(this.camera=e)}}}(nU||(nU={})),function(e){e.ExportSceneGlbDto=class{constructor(e,t){this.fileName="bitbybit-scene",this.discardSkyboxAndGrid=!1,void 0!==e&&(this.fileName=e),void 0!==t&&(this.discardSkyboxAndGrid=t)}},e.ExportSceneDto=class{constructor(e){this.fileName="bitbybit-scene",void 0!==e&&(this.fileName=e)}},e.ExportMeshToStlDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.fileName=t)}},e.ExportMeshesToStlDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.fileName=t)}}}(oU||(oU={})),function(e){e.PBRMetallicRoughnessDto=class{constructor(e,t,i,s,r,n,o,a){this.name="Custom Material",this.baseColor="#0000ff",this.emissiveColor="#000000",this.metallic=.6,this.roughness=.5,this.alpha=1,this.backFaceCulling=!1,this.zOffset=0,void 0!==e&&(this.name=e),void 0!==t&&(this.baseColor=t),void 0!==i&&(this.emissiveColor=i),void 0!==s&&(this.metallic=s),void 0!==r&&(this.roughness=r),void 0!==n&&(this.alpha=n),void 0!==o&&(this.backFaceCulling=o),void 0!==a&&(this.zOffset=a)}},e.BaseColorDto=class{constructor(e,t){this.baseColor="#0000ff",void 0!==e&&(this.material=e),void 0!==t&&(this.baseColor=t)}},e.MaterialPropDto=class{constructor(e){void 0!==e&&(this.material=e)}},e.MetallicDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.metallic=t)}},e.RoughnessDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.roughness=t)}},e.AlphaDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.alpha=t)}},e.BackFaceCullingDto=class{constructor(e,t){this.backFaceCulling=!0,void 0!==e&&(this.material=e),void 0!==t&&(this.backFaceCulling=t)}},e.BaseTextureDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.baseTexture=t)}}}(aU||(aU={})),function(e){e.CreateGaussianSplattingMeshDto=class{constructor(e){void 0!==e&&(this.url=e)}}}(lU||(lU={})),function(e){let t;!function(e){e.frontside="frontside",e.backside="backside",e.doubleside="doubleside"}(t=e.sideOrientationEnum||(e.sideOrientationEnum={})),e.UpdateDrawnBabylonMesh=class{constructor(e,t,i,s,r){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.rotation=i),void 0!==s&&(this.scaling=s),void 0!==r&&(this.colours=r)}},e.SetParentDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.parentMesh=t)}},e.UpdateDrawnBabylonMeshPositionDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.position=t)}},e.UpdateDrawnBabylonMeshRotationDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.rotation=t)}},e.UpdateDrawnBabylonMeshScaleDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.scale=t)}},e.IntersectsMeshDto=class{constructor(e,t,i,s){this.precise=!1,this.includeDescendants=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.babylonMesh2=t),void 0!==i&&(this.precise=i),void 0!==s&&(this.includeDescendants=s)}},e.IntersectsPointDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.point=t)}},e.BabylonMeshDto=class{constructor(e){void 0!==e&&(this.babylonMesh=e)}},e.ShowHideMeshDto=class{constructor(e,t){this.includeChildren=!0,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.includeChildren=t)}},e.CloneBabylonMeshDto=class{constructor(e){void 0!==e&&(this.babylonMesh=e)}},e.ChildMeshesBabylonMeshDto=class{constructor(e,t){this.directDescendantsOnly=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.directDescendantsOnly=t)}},e.TranslateBabylonMeshDto=class{constructor(e,t){this.distance=0,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.distance=t)}},e.NameBabylonMeshDto=class{constructor(e,t,i){this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.name=t),void 0!==i&&(this.includeChildren=i)}},e.ByNameBabylonMeshDto=class{constructor(e){void 0!==e&&(this.name=e)}},e.MaterialBabylonMeshDto=class{constructor(e,t,i){this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.material=t),void 0!==i&&(this.includeChildren=i)}},e.IdBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.id=t)}},e.ByIdBabylonMeshDto=class{constructor(e){void 0!==e&&(this.id=e)}},e.UniqueIdBabylonMeshDto=class{constructor(e){void 0!==e&&(this.uniqueId=e)}},e.PickableBabylonMeshDto=class{constructor(e,t,i){this.pickable=!1,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.pickable=t),void 0!==i&&(this.includeChildren=i)}},e.CheckCollisionsBabylonMeshDto=class{constructor(e,t,i){this.checkCollisions=!1,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.checkCollisions=t),void 0!==i&&(this.includeChildren=i)}},e.RotateBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.rotate=t)}},e.SetMeshVisibilityDto=class{constructor(e,t,i){this.visibility=0,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.visibility=t),void 0!==i&&(this.includeChildren=i)}},e.MeshInstanceAndTransformDto=class{constructor(e,t,i,s){void 0!==e&&(this.mesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.rotation=i),void 0!==s&&(this.scaling=s)}},e.MeshInstanceDto=class{constructor(e){void 0!==e&&(this.mesh=e)}},e.RotateAroundAxisNodeDto=class{constructor(e,t,i,s){this.position=[0,0,0],this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.mesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.axis=i),void 0!==s&&(this.angle=s)}}}(hU||(hU={})),function(e){e.RayDto=class{constructor(e){void 0!==e&&(this.ray=e)}},e.PickInfo=class{constructor(e){void 0!==e&&(this.pickInfo=e)}}}(cU||(cU={})),function(e){e.BaseRayDto=class{constructor(e,t,i){void 0!==e&&(this.origin=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.length=i)}},e.RayDto=class{constructor(e){void 0!==e&&(this.ray=e)}},e.FromToDto=class{constructor(e,t){void 0!==e&&(this.from=e),void 0!==t&&(this.to=t)}}}(uU||(uU={})),function(e){e.CreateBoxDto=class{constructor(e,t,i,s){this.width=1,this.depth=1,this.height=1,this.sideOrientation=hU.sideOrientationEnum.frontside,void 0!==e&&(this.width=e),void 0!==t&&(this.depth=t),void 0!==i&&(this.height=i),void 0!==s&&(this.sideOrientation=s)}},e.CreateCubeDto=class{constructor(e,t){this.size=1,this.sideOrientation=hU.sideOrientationEnum.frontside,void 0!==e&&(this.size=e),void 0!==t&&(this.sideOrientation=t)}},e.CreateSquarePlaneDto=class{constructor(e,t){this.size=1,this.sideOrientation=hU.sideOrientationEnum.frontside,void 0!==e&&(this.size=e),void 0!==t&&(this.sideOrientation=t)}},e.CreateRectanglePlaneDto=class{constructor(e,t,i){this.width=1,this.height=1,this.sideOrientation=hU.sideOrientationEnum.frontside,void 0!==e&&(this.width=e),void 0!==t&&(this.height=t),void 0!==i&&(this.sideOrientation=i)}}}(dU||(dU={})),function(e){let t;!function(e){e.nearest="nearest",e.bilinear="bilinear",e.trilinear="trilinear"}(t=e.samplingModeEnum||(e.samplingModeEnum={})),e.TextureSimpleDto=class{constructor(t,i,s,r,n,o,a,l,h,c){this.name="Custom Texture",this.invertY=!1,this.invertZ=!1,this.wAng=0,this.uScale=1,this.vScale=1,this.uOffset=0,this.vOffset=0,this.samplingMode=e.samplingModeEnum.nearest,void 0!==t&&(this.name=t),void 0!==i&&(this.url=i),void 0!==s&&(this.invertY=s),void 0!==r&&(this.invertZ=r),void 0!==n&&(this.wAng=n),void 0!==o&&(this.uScale=o),void 0!==a&&(this.vScale=a),void 0!==l&&(this.uOffset=l),void 0!==h&&(this.vOffset=h),void 0!==c&&(this.samplingMode=c)}}}(_U||(_U={})),function(e){e.DefaultWebXRWithTeleportationDto=class{constructor(e){void 0!==e&&(this.groundMeshes=e)}}}(pU||(pU={})),function(e){e.HexDto=class{constructor(e){this.color="#0000ff",void 0!==e&&(this.color=e)}},e.HexDtoMapped=class{constructor(e,t,i){this.color="#0000ff",this.from=0,this.to=255,void 0!==e&&(this.color=e),void 0!==t&&(this.from=t),void 0!==i&&(this.to=i)}},e.RGBDto=class{constructor(e,t,i){this.r=255,this.g=255,this.b=255,void 0!==e&&(this.r=e),void 0!==t&&(this.g=t),void 0!==i&&(this.b=i)}},e.RGBObjectDto=class{constructor(e){void 0!==e&&(this.rgb=e)}}}(fU||(fU={})),function(e){let t;e.DrawAny=class{constructor(e,t,i){void 0!==e&&(this.entity=e),void 0!==t&&(this.options=t),void 0!==i&&(this.babylonMesh=i)}},e.SceneDrawGridMeshDto=class{constructor(e,t,i,s,r,n,o,a,l,h){this.width=400,this.height=400,this.subdivisions=10,this.majorUnitFrequency=10,this.minorUnitVisibility=.45,this.gridRatio=.5,this.opacity=.5,this.backFaceCulling=!1,this.mainColor="#ffffff",this.secondaryColor="#ffffff",void 0!==e&&(this.width=e),void 0!==t&&(this.height=t),void 0!==i&&(this.subdivisions=i),void 0!==s&&(this.majorUnitFrequency=s),void 0!==r&&(this.minorUnitVisibility=r),void 0!==n&&(this.gridRatio=n),void 0!==o&&(this.opacity=o),void 0!==a&&(this.backFaceCulling=a),void 0!==l&&(this.mainColor=l),void 0!==h&&(this.secondaryColor=h)}},e.DrawBasicGeometryOptions=class{constructor(e,t,i,s,r){this.colours="#ff0000",this.size=.1,this.opacity=1,this.updatable=!1,this.hidden=!1,void 0!==e&&(this.colours=e),void 0!==t&&(this.size=t),void 0!==i&&(this.opacity=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r)}},e.DrawNodeOptions=class{constructor(e,t,i,s){this.colorX="#0000ff",this.colorY="#00ff00",this.colorZ="#ff0000",this.size=2,void 0!==e&&(this.colorX=e),void 0!==t&&(this.colorY=t),void 0!==i&&(this.colorZ=i),void 0!==s&&(this.size=s)}},e.DrawOcctShapeOptions=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.vertexColour="#ffaaff",this.edgeWidth=2,this.vertexSize=.03,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.faceOpacity=e),void 0!==t&&(this.edgeOpacity=t),void 0!==i&&(this.edgeColour=i),void 0!==s&&(this.faceMaterial=s),void 0!==r&&(this.faceColour=r),void 0!==h&&(this.vertexColour=h),void 0!==c&&(this.vertexSize=c),void 0!==n&&(this.edgeWidth=n),void 0!==o&&(this.drawEdges=o),void 0!==a&&(this.drawFaces=a),void 0!==l&&(this.drawVertices=l),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdgeIndexes=d),void 0!==_&&(this.edgeIndexHeight=_),void 0!==p&&(this.edgeIndexColour=p),void 0!==f&&(this.drawFaceIndexes=f),void 0!==m&&(this.faceIndexHeight=m),void 0!==g&&(this.faceIndexColour=g)}},e.DrawOcctShapeSimpleOptions=class{constructor(e,t,i,s,r,n){this.precision=.01,this.drawFaces=!0,this.faceColour="#ff0000",this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=2,void 0!==e&&(this.precision=e),void 0!==t&&(this.drawFaces=t),void 0!==i&&(this.faceColour=i),void 0!==s&&(this.drawEdges=s),void 0!==r&&(this.edgeColour=r),void 0!==n&&(this.edgeWidth=n)}},e.DrawOcctShapeMaterialOptions=class{constructor(e,t,i,s,r){this.precision=.01,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=2,void 0!==e&&(this.precision=e),void 0!==t&&(this.faceMaterial=t),void 0!==i&&(this.drawEdges=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.edgeWidth=r)}},function(e){e[e.point=0]="point",e[e.points=1]="points",e[e.line=2]="line",e[e.lines=3]="lines",e[e.node=4]="node",e[e.nodes=5]="nodes",e[e.polyline=6]="polyline",e[e.polylines=7]="polylines",e[e.verbCurve=8]="verbCurve",e[e.verbCurves=9]="verbCurves",e[e.verbSurface=10]="verbSurface",e[e.verbSurfaces=11]="verbSurfaces",e[e.jscadMesh=12]="jscadMesh",e[e.jscadMeshes=13]="jscadMeshes",e[e.occt=14]="occt",e[e.tag=15]="tag",e[e.tags=16]="tags"}(t=e.drawingTypes||(e.drawingTypes={}))}(mU||(mU={})),function(e){let t,i;!function(e){e.edge="edge",e.round="round",e.chamfer="chamfer"}(t=e.solidCornerTypeEnum||(e.solidCornerTypeEnum={})),function(e){e.left="left",e.center="center",e.right="right"}(i=e.jscadTextAlignEnum||(e.jscadTextAlignEnum={})),e.DrawSolidMeshDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.mesh=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.jscadMesh=n)}},e.DrawSolidMeshesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.meshes=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.jscadMesh=n)}},e.DrawPathDto=class{constructor(e,t,i,s,r,n){this.colour="#444444",this.opacity=1,this.width=10,this.updatable=!1,void 0!==e&&(this.path=e),void 0!==t&&(this.colour=t),void 0!==i&&(this.opacity=i),void 0!==s&&(this.width=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.pathMesh=n)}},e.TransformSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.transformation=t)}},e.TransformSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.transformation=t)}},e.DownloadSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.fileName=t)}},e.DownloadGeometryDto=class{constructor(e,t){void 0!==e&&(this.geometry=e),void 0!==t&&(this.fileName=t)}},e.DownloadSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.fileName=t)}},e.ColorizeDto=class{constructor(e,t){this.color="#0000ff",void 0!==e&&(this.geometry=e),void 0!==t&&(this.color=t)}},e.BooleanObjectsDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.BooleanTwoObjectsDto=class{constructor(e,t){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.BooleanObjectsFromDto=class{constructor(e,t){void 0!==e&&(this.from=e),void 0!==t&&(this.meshes=t)}},e.ExpansionDto=class{constructor(e,i,s,r){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==s&&(this.corners=s),void 0!==r&&(this.segments=r)}},e.OffsetDto=class{constructor(e,i,s,r){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==s&&(this.corners=s),void 0!==r&&(this.segments=r)}},e.ExtrudeLinearDto=class{constructor(e,t,i,s){this.height=1,this.twistAngle=90,this.twistSteps=15,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.twistAngle=i),void 0!==s&&(this.twistSteps=s)}},e.HullDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.ExtrudeRectangularDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRectangularPointsDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.points=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRotateDto=class{constructor(e,t,i,s){this.angle=90,this.startAngle=0,this.segments=24,void 0!==e&&(this.polygon=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.startAngle=i),void 0!==s&&(this.segments=s)}},e.PathDto=class{constructor(e){void 0!==e&&(this.path=e)}},e.PathFromPointsDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.PathsFromPointsDto=class{constructor(e){void 0!==e&&(this.pointsLists=e)}},e.PathFromPolylineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.polyline=e),void 0!==t&&(this.closed=t)}},e.PathAppendCurveDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.path=t)}},e.PathAppendPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.path=t)}},e.PathAppendPolylineDto=class{constructor(e,t){void 0!==e&&(this.polyline=e),void 0!==t&&(this.path=t)}},e.PathAppendArcDto=class{constructor(e,t,i,s,r,n,o,a){this.endPoint=[1,1],this.xAxisRotation=90,this.clockwise=!0,this.large=!1,this.segments=24,this.radiusX=1,this.radiusY=1,void 0!==e&&(this.path=e),void 0!==t&&(this.endPoint=t),void 0!==i&&(this.xAxisRotation=i),void 0!==s&&(this.clockwise=s),void 0!==r&&(this.large=r),void 0!==n&&(this.segments=n),void 0!==o&&(this.radiusX=o),void 0!==a&&(this.radiusY=a)}},e.CircleDto=class{constructor(e,t,i){this.center=[0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipseDto=class{constructor(e,t,i){this.center=[0,0],this.radius=[1,2],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SquareDto=class{constructor(e,t){this.center=[0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.RectangleDto=class{constructor(e,t,i){this.center=[0,0],this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i)}},e.RoundedRectangleDto=class{constructor(e,t,i,s,r){this.center=[0,0],this.roundRadius=.2,this.segments=24,this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.segments=i),void 0!==s&&(this.width=s),void 0!==r&&(this.length=r)}},e.StarDto=class{constructor(e,t,i,s,r,n){this.center=[0,0],this.vertices=10,this.density=1,this.outerRadius=2,this.innerRadius=1,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.vertices=t),void 0!==i&&(this.density=i),void 0!==s&&(this.outerRadius=s),void 0!==r&&(this.innerRadius=r),void 0!==n&&(this.startAngle=n)}},e.CubeDto=class{constructor(e,t){this.center=[0,0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.CubeCentersDto=class{constructor(e,t){this.size=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.size=t)}},e.CuboidDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.width=1,this.length=1,this.height=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.height=s)}},e.CuboidCentersDto=class{constructor(e,t,i,s){this.width=1,this.length=1,this.height=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.height=s)}},e.RoundedCuboidDto=class{constructor(e,t,i,s,r,n){this.center=[0,0,0],this.roundRadius=1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==s&&(this.length=s),void 0!==r&&(this.height=r),void 0!==n&&(this.segments=n)}},e.RoundedCuboidCentersDto=class{constructor(e,t,i,s,r,n){this.roundRadius=.1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==s&&(this.length=s),void 0!==r&&(this.height=r),void 0!==n&&(this.segments=n)}},e.CylidnerEllipticDto=class{constructor(e,t,i,s,r){this.center=[0,0,0],this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==s&&(this.endRadius=s),void 0!==r&&(this.segments=r)}},e.CylidnerCentersEllipticDto=class{constructor(e,t,i,s,r){this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==s&&(this.endRadius=s),void 0!==r&&(this.segments=r)}},e.CylidnerDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.segments=s)}},e.RoundedCylidnerDto=class{constructor(e,t,i,s,r){this.center=[0,0,0],this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==s&&(this.radius=s),void 0!==r&&(this.segments=r)}},e.EllipsoidDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipsoidCentersDto=class{constructor(e,t,i){this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.GeodesicSphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.frequency=12,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.GeodesicSphereCentersDto=class{constructor(e,t,i){this.radius=1,this.frequency=12,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.CylidnerCentersDto=class{constructor(e,t,i,s){this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.segments=s)}},e.RoundedCylidnerCentersDto=class{constructor(e,t,i,s,r){this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==s&&(this.radius=s),void 0!==r&&(this.segments=r)}},e.SphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SphereCentersDto=class{constructor(e,t,i){this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.TorusDto=class{constructor(e,t,i,s,r,n,o,a){this.center=[0,0,0],this.innerRadius=1,this.outerRadius=2,this.innerSegments=24,this.outerSegments=24,this.innerRotation=0,this.outerRotation=360,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.outerRadius=i),void 0!==s&&(this.innerSegments=s),void 0!==r&&(this.outerSegments=r),void 0!==n&&(this.innerRotation=n),void 0!==o&&(this.outerRotation=o),void 0!==a&&(this.startAngle=a)}},e.TextDto=class{constructor(e,t,s,r,n,o,a,l,h){this.text="Hello World",this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.segments=t),void 0!==s&&(this.xOffset=s),void 0!==r&&(this.yOffset=r),void 0!==n&&(this.height=n),void 0!==o&&(this.lineSpacing=o),void 0!==a&&(this.letterSpacing=a),void 0!==l&&(this.align=l),void 0!==h&&(this.extrudeOffset=h)}},e.CylinderTextDto=class{constructor(e,t,s,r,n,o,a,l,h,c,u){this.text="Hello World",this.extrusionHeight=.5,this.extrusionSize=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.extrusionHeight=t),void 0!==s&&(this.extrusionSize=s),void 0!==r&&(this.segments=r),void 0!==n&&(this.xOffset=n),void 0!==o&&(this.yOffset=o),void 0!==a&&(this.height=a),void 0!==l&&(this.lineSpacing=l),void 0!==h&&(this.letterSpacing=h),void 0!==c&&(this.align=c),void 0!==u&&(this.extrudeOffset=u)}},e.SphereTextDto=class{constructor(e,t,s,r,n,o,a,l,h,c){this.text="Hello World",this.radius=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.radius=t),void 0!==s&&(this.segments=s),void 0!==r&&(this.xOffset=r),void 0!==n&&(this.yOffset=n),void 0!==o&&(this.height=o),void 0!==a&&(this.lineSpacing=a),void 0!==l&&(this.letterSpacing=l),void 0!==h&&(this.align=h),void 0!==c&&(this.extrudeOffset=c)}},e.FromPolygonPoints=class{constructor(e){void 0!==e&&(this.polygonPoints=e)}}}(gU||(gU={})),function(e){e.StringifyDto=class{constructor(e){void 0!==e&&(this.json=e)}},e.ParseDto=class{constructor(e){void 0!==e&&(this.text=e)}},e.QueryDto=class{constructor(e,t){void 0!==e&&(this.json=e),void 0!==t&&(this.query=t)}},e.SetValueDto=class{constructor(e,t,i){void 0!==e&&(this.json=e),void 0!==t&&(this.value=t),void 0!==i&&(this.path=i)}},e.SetValuesOnPathsDto=class{constructor(e,t,i){void 0!==e&&(this.json=e),void 0!==t&&(this.values=t),void 0!==i&&(this.paths=i)}},e.PathsDto=class{constructor(e,t){void 0!==e&&(this.json=e),void 0!==t&&(this.query=t)}},e.JsonDto=class{constructor(e){void 0!==e&&(this.json=e)}}}(vU||(vU={})),function(e){e.LinePointsDto=class{constructor(e,t){void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LineStartEndPointsDto=class{constructor(e,t){void 0!==e&&(this.startPoints=e),void 0!==t&&(this.endPoints=t)}},e.DrawLineDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.line=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.lineMesh=n)}},e.DrawLinesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.linesMesh=n)}},e.PointsLinesDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.LineDto=class{constructor(e){void 0!==e&&(this.line=e)}},e.LinesDto=class{constructor(e){void 0!==e&&(this.lines=e)}},e.PointOnLineDto=class{constructor(e,t){void 0!==e&&(this.line=e),void 0!==t&&(this.param=t)}},e.TransformLineDto=class{constructor(e,t){void 0!==e&&(this.line=e),void 0!==t&&(this.transformation=t)}},e.TransformsLinesDto=class{constructor(e,t){void 0!==e&&(this.lines=e),void 0!==t&&(this.transformation=t)}},e.TransformLinesDto=class{constructor(e,t){void 0!==e&&(this.lines=e),void 0!==t&&(this.transformation=t)}}}(xU||(xU={})),function(e){let t;!function(e){e.first="first",e.last="last"}(t=e.firstLastEnum||(e.firstLastEnum={})),e.ListItemDto=class{constructor(e,t,i){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.index=t),void 0!==i&&(this.clone=i)}},e.SubListDto=class{constructor(e,t,i,s){this.indexStart=0,this.indexEnd=1,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.indexStart=t),void 0!==i&&(this.indexEnd=i),void 0!==s&&(this.clone=s)}},e.ListDto=class{constructor(e,t){this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.clone=t)}},e.GroupListDto=class{constructor(e,t,i){this.nrElements=2,this.keepRemainder=!1,void 0!==e&&(this.list=e),void 0!==t&&(this.nrElements=t),void 0!==i&&(this.keepRemainder=i)}},e.MultiplyItemDto=class{constructor(e,t){void 0!==e&&(this.item=e),void 0!==t&&(this.times=t)}},e.AddItemAtIndexDto=class{constructor(e,t,i,s){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.item=t),void 0!==i&&(this.index=i),void 0!==s&&(this.clone=s)}},e.AddItemAtIndexesDto=class{constructor(e,t,i,s){this.indexes=[0],this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.item=t),void 0!==i&&(this.indexes=i),void 0!==s&&(this.clone=s)}},e.AddItemsAtIndexesDto=class{constructor(e,t,i,s){this.indexes=[0],this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.items=t),void 0!==i&&(this.indexes=i),void 0!==s&&(this.clone=s)}},e.RemoveItemAtIndexDto=class{constructor(e,t,i){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.index=t),void 0!==i&&(this.clone=i)}},e.RemoveNthItemDto=class{constructor(e,t,i,s){this.nth=2,this.offset=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.nth=t),void 0!==i&&(this.offset=i),void 0!==s&&(this.clone=s)}},e.GetByPatternDto=class{constructor(e,t){this.pattern=[!0,!0,!1],void 0!==e&&(this.list=e),void 0!==t&&(this.pattern=t)}},e.GetNthItemDto=class{constructor(e,t,i,s){this.nth=2,this.offset=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.nth=t),void 0!==i&&(this.offset=i),void 0!==s&&(this.clone=s)}},e.GetLongestListLength=class{constructor(e){void 0!==e&&(this.lists=e)}},e.MergeElementsOfLists=class{constructor(e,t){this.level=0,void 0!==e&&(this.lists=e),void 0!==t&&(this.level=t)}},e.AddItemFirstLastDto=class{constructor(e,i,s,r){this.position=t.last,this.clone=!0,void 0!==e&&(this.list=e),void 0!==i&&(this.item=i),void 0!==s&&(this.position=s),void 0!==r&&(this.clone=r)}}}(bU||(bU={})),function(e){let t;!function(e){e.less="<",e.lessOrEqual="<=",e.greater=">",e.greaterOrEqual=">=",e.tripleEqual="===",e.tripleNotEqual="!==",e.equal="==",e.notEqual="!="}(t=e.BooleanOperatorsEnum||(e.BooleanOperatorsEnum={})),e.ComparisonDto=class{constructor(e,t,i){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t),void 0!==i&&(this.operator=i)}},e.BooleanDto=class{constructor(e){this.boolean=!1,void 0!==e&&(this.boolean=e)}},e.BooleanListDto=class{constructor(e){void 0!==e&&(this.booleans=e)}},e.ValueGateDto=class{constructor(e,t){this.boolean=!1,void 0!==e&&(this.value=e),void 0!==t&&(this.boolean=t)}},e.TwoValueGateDto=class{constructor(e,t){void 0!==e&&(this.value1=e),void 0!==t&&(this.value2=t)}},e.RandomBooleansDto=class{constructor(e){this.length=10,void 0!==e&&(this.length=e)}},e.TwoThresholdRandomGradientDto=class{},e.ThresholdBooleanListDto=class{},e.ThresholdGapsBooleanListDto=class{}}(TU||(TU={})),function(e){let t,i;!function(e){e.add="add",e.subtract="subtract",e.multiply="multiply",e.divide="divide",e.power="power",e.modulus="modulus"}(t=e.mathTwoNrOperatorEnum||(e.mathTwoNrOperatorEnum={})),function(e){e.absolute="absolute",e.negate="negate",e.ln="ln",e.log10="log10",e.tenPow="tenPow",e.round="round",e.floor="floor",e.ceil="ceil",e.sqrt="sqrt",e.sin="sin",e.cos="cos",e.tan="tan",e.asin="asin",e.acos="acos",e.atan="atan",e.log="log",e.exp="exp",e.radToDeg="radToDeg",e.degToRad="degToRad"}(i=e.mathOneNrOperatorEnum||(e.mathOneNrOperatorEnum={})),e.NumberDto=class{constructor(e){this.number=0,void 0!==e&&(this.number=e)}},e.ModulusDto=class{constructor(e,t){this.number=1,this.modulus=2,void 0!==e&&(this.number=e),void 0!==t&&(this.modulus=t)}},e.RoundToDecimalsDto=class{constructor(e,t){this.number=1.123456,this.decimalPlaces=2,void 0!==e&&(this.number=e),void 0!==t&&(this.decimalPlaces=t)}},e.ActionOnTwoNumbersDto=class{constructor(e,t,i){this.first=1,this.second=1,void 0!==e&&(this.first=e),void 0!==t&&(this.second=t),void 0!==i&&(this.operation=i)}},e.ActionOnOneNumberDto=class{constructor(e,t){this.number=1,void 0!==e&&(this.number=e),void 0!==t&&(this.operation=t)}},e.RemapNumberDto=class{constructor(e,t,i,s,r){this.number=.5,this.fromLow=0,this.fromHigh=1,this.toLow=1,this.toHigh=2,void 0!==e&&(this.number=e),void 0!==t&&(this.fromLow=t),void 0!==i&&(this.fromHigh=i),void 0!==s&&(this.toLow=s),void 0!==r&&(this.toHigh=r)}},e.RandomNumberDto=class{constructor(e,t){this.low=0,this.high=1,void 0!==e&&(this.low=e),void 0!==t&&(this.high=t)}},e.RandomNumbersDto=class{constructor(e,t,i){this.low=0,this.high=1,this.count=10,void 0!==e&&(this.low=e),void 0!==t&&(this.high=t),void 0!==i&&(this.count=i)}}}(yU||(yU={})),function(e){e.NodeDto=class{constructor(e){void 0!==e&&(this.node=e)}},e.NodeTranslationDto=class{constructor(e,t,i){void 0!==e&&(this.node=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.distance=i)}},e.NodeParentDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.parentNode=t)}},e.NodeDirectionDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.direction=t)}},e.NodePositionDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.position=t)}},e.RotateNodeDto=class{constructor(e,t,i){this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.node=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.angle=i)}},e.RotateAroundAxisNodeDto=class{constructor(e,t,i,s){this.position=[0,0,0],this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.node=e),void 0!==t&&(this.position=t),void 0!==i&&(this.axis=i),void 0!==s&&(this.angle=s)}},e.CreateNodeFromRotationDto=class{constructor(e,t,i){this.origin=[0,0,0],this.rotation=[0,0,0],void 0!==e&&(this.parent=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.rotation=i)}},e.DrawNodeDto=class{constructor(e,t,i,s,r){this.colorX="#ff0000",this.colorY="#00ff00",this.colorZ="#0000ff",this.size=2,void 0!==e&&(this.node=e),void 0!==t&&(this.colorX=t),void 0!==i&&(this.colorY=i),void 0!==s&&(this.colorZ=s),void 0!==r&&(this.size=r)}},e.DrawNodesDto=class{constructor(e,t,i,s,r){this.colorX="#ff0000",this.colorY="#00ff00",this.colorZ="#0000ff",this.size=2,void 0!==e&&(this.nodes=e),void 0!==t&&(this.colorX=t),void 0!==i&&(this.colorY=i),void 0!==s&&(this.colorZ=s),void 0!==r&&(this.size=r)}}}(SU||(SU={})),function(e){e.PointDto=class{constructor(e){void 0!==e&&(this.point=e)}},e.PointXYZDto=class{constructor(e,t,i){this.x=0,this.y=0,this.z=0,void 0!==e&&(this.x=e),void 0!==t&&(this.y=t),void 0!==i&&(this.z=i)}},e.PointXYDto=class{constructor(e,t){this.x=0,this.y=0,void 0!==e&&(this.x=e),void 0!==t&&(this.y=t)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.DrawPointDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.size=3,this.colours="#444444",this.updatable=!1,void 0!==e&&(this.point=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.size=i),void 0!==s&&(this.colours=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.pointMesh=n)}},e.DrawPointsDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.size=.1,this.colours="#444444",this.updatable=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.size=i),void 0!==s&&(this.colours=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.pointsMesh=n)}},e.TransformPointDto=class{constructor(e,t){void 0!==e&&(this.point=e),void 0!==t&&(this.transformation=t)}},e.TransformPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.transformation=t)}},e.TransformsForPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.transformation=t)}},e.ClosestPointFromPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.point=t)}},e.StartEndPointsDto=class{constructor(e,t){void 0!==e&&(this.startPoint=e),void 0!==t&&(this.endPoint=t)}},e.StartEndPointsListDto=class{constructor(e,t){void 0!==e&&(this.startPoint=e),void 0!==t&&(this.endPoints=t)}},e.MultiplyPointDto=class{constructor(e,t){void 0!==e&&(this.point=e),void 0!==t&&(this.amountOfPoints=t)}},e.SpiralDto=class{constructor(e,t,i,s,r){this.phi=.9,this.numberPoints=200,this.widening=3,this.radius=6,this.factor=1,void 0!==e&&(this.radius=e),void 0!==t&&(this.numberPoints=t),void 0!==i&&(this.widening=i),void 0!==s&&(this.factor=s),void 0!==r&&(this.phi=r)}},e.HexGridCentersDto=class{constructor(e,t,i,s,r){this.nrHexagonsY=21,this.nrHexagonsX=21,this.orientOnCenter=!1,this.pointsOnGround=!1,void 0!==e&&(this.nrHexagonsX=e),void 0!==t&&(this.nrHexagonsY=t),void 0!==i&&(this.radiusHexagon=i),void 0!==s&&(this.orientOnCenter=s),void 0!==r&&(this.pointsOnGround=r)}}}(CU||(CU={})),function(e){e.PolylinePropertiesDto=class{constructor(e,t){this.isClosed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.isClosed=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.polyline=e)}},e.PolylinesDto=class{constructor(e){void 0!==e&&(this.polylines=e)}},e.TransformPolylineDto=class{constructor(e,t){void 0!==e&&(this.polyline=e),void 0!==t&&(this.transformation=t)}},e.DrawPolylineDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.polyline=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.polylineMesh=n)}},e.DrawPolylinesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.polylinesMesh=n)}}}(EU||(EU={})),function(e){let t,i;!function(e){e.default="default",e.clearSky="clearSky",e.city="city"}(t=e.skyboxEnum||(e.skyboxEnum={})),function(e){e.none="none",e.exponential="exponential",e.exponentialSquared="exponentialSquared",e.linear="linear"}(i=e.fogModeEnum||(e.fogModeEnum={}))}(AU||(AU={})),function(e){e.SceneBackgroundColourDto=class{constructor(e){this.colour="#ffffff",void 0!==e&&(this.colour=e)}},e.SceneDto=class{constructor(e){void 0!==e&&(this.scene=e)}},e.EnablePhysicsDto=class{constructor(e){this.vector=[0,-9.81,0],void 0!==e&&(this.vector=e)}},e.PointLightDto=class{constructor(e,t,i,s,r,n,o,a){this.position=[0,0,0],this.intensity=2e3,this.diffuse="#ffffff",this.specular="#ffffff",this.radius=.1,this.shadowGeneratorMapSize=1024,this.enableShadows=!0,this.shadowDarkness=0,void 0!==e&&(this.position=e),void 0!==t&&(this.intensity=t),void 0!==i&&(this.diffuse=i),void 0!==s&&(this.specular=s),void 0!==r&&(this.radius=r),void 0!==n&&(this.shadowGeneratorMapSize=n),void 0!==o&&(this.enableShadows=o),void 0!==a&&(this.shadowDarkness=a)}},e.ActiveCameraDto=class{constructor(e){void 0!==e&&(this.camera=e)}},e.UseRightHandedSystemDto=class{constructor(e){this.use=!0,void 0!==e&&(this.use=e)}},e.DirectionalLightDto=class{constructor(e,t,i,s,r,n,o){this.direction=[-100,-100,-100],this.intensity=.5,this.diffuse="#ffffff",this.specular="#ffffff",this.shadowGeneratorMapSize=1024,this.enableShadows=!0,this.shadowDarkness=0,void 0!==e&&(this.direction=e),void 0!==t&&(this.intensity=t),void 0!==i&&(this.diffuse=i),void 0!==s&&(this.specular=s),void 0!==r&&(this.shadowGeneratorMapSize=r),void 0!==n&&(this.enableShadows=n),void 0!==o&&(this.shadowDarkness=o)}},e.CameraConfigurationDto=class{constructor(e,t,i,s,r,n,o,a,l){this.position=[10,10,10],this.lookAt=[0,0,0],this.lowerBetaLimit=1,this.upperBetaLimit=179,this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.maxZ=1e3,this.panningSensibility=1e3,this.wheelPrecision=3,void 0!==e&&(this.position=e),void 0!==t&&(this.lookAt=t),void 0!==i&&(this.lowerBetaLimit=i),void 0!==s&&(this.upperBetaLimit=s),void 0!==r&&(this.angularSensibilityX=r),void 0!==n&&(this.angularSensibilityY=n),void 0!==o&&(this.maxZ=o),void 0!==a&&(this.panningSensibility=a),void 0!==l&&(this.wheelPrecision=l)}},e.SkyboxDto=class{constructor(e,t,i,s){this.skybox=AU.skyboxEnum.clearSky,this.size=1e3,this.blur=.1,this.environmentIntensity=.7,void 0!==e&&(this.skybox=e),void 0!==t&&(this.size=t),void 0!==i&&(this.blur=i),void 0!==s&&(this.environmentIntensity=s)}},e.PointerDto=class{},e.FogDto=class{constructor(e,t,i,s,r){this.color="#ffffff",this.density=.1,void 0!==e&&(this.mode=e),void 0!==t&&(this.color=t),void 0!==i&&(this.density=i),void 0!==s&&(this.start=s),void 0!==r&&(this.end=r)}}}(PU||(PU={})),function(e){e.DrawTagDto=class{constructor(e,t,i){this.updatable=!1,void 0!==e&&(this.tag=e),void 0!==t&&(this.updatable=t),void 0!==i&&(this.tagVariable=i)}},e.DrawTagsDto=class{constructor(e,t,i){this.updatable=!1,void 0!==e&&(this.tags=e),void 0!==t&&(this.updatable=t),void 0!==i&&(this.tagsVariable=i)}},e.TagDto=class{constructor(e,t,i,s,r,n,o){this.position=[0,0,0],this.colour="#444444",this.size=12,this.adaptDepth=!1,void 0!==e&&(this.text=e),void 0!==t&&(this.position=t),void 0!==i&&(this.colour=i),void 0!==s&&(this.size=s),void 0!==r&&(this.adaptDepth=r),void 0!==n&&(this.needsUpdate=n),void 0!==o&&(this.id=o)}}}(IU||(IU={})),function(e){e.TextDto=class{constructor(e){this.text="Hello World",void 0!==e&&(this.text=e)}},e.TextSplitDto=class{constructor(e,t){this.text="a,b,c",this.separator=",",void 0!==e&&(this.text=e),void 0!==t&&(this.separator=t)}},e.TextReplaceDto=class{constructor(e,t,i){this.text="a-c",this.search="-",this.replaceWith="b",void 0!==e&&(this.text=e),void 0!==t&&(this.search=t),void 0!==i&&(this.replaceWith=i)}},e.TextJoinDto=class{constructor(e,t){this.separator=",",void 0!==e&&(this.list=e),void 0!==t&&(this.separator=t)}},e.ToStringDto=class{constructor(e){void 0!==e&&(this.item=e)}},e.ToStringEachDto=class{constructor(e){void 0!==e&&(this.list=e)}}}(RU||(RU={})),function(e){e.PostFromIframe=class{constructor(e,t){void 0!==e&&(this.data=e),void 0!==t&&(this.targetOrigin=t)}}}(MU||(MU={})),function(e){e.RotationCenterAxisDto=class{constructor(e,t,i){this.angle=90,this.axis=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.center=i)}},e.TransformBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.transformation=t)}},e.RotationCenterDto=class{constructor(e,t){this.angle=90,this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.center=t)}},e.RotationCenterYawPitchRollDto=class{constructor(e,t,i,s){this.yaw=0,this.pitch=0,this.roll=0,this.center=[0,0,0],void 0!==e&&(this.yaw=e),void 0!==t&&(this.pitch=t),void 0!==i&&(this.roll=i),void 0!==s&&(this.center=s)}},e.ScaleXYZDto=class{constructor(e){this.scaleXyz=[1,1,1],void 0!==e&&(this.scaleXyz=e)}},e.ScaleCenterXYZDto=class{constructor(e,t){this.center=[0,0,0],this.scaleXyz=[1,1,1],void 0!==e&&(this.center=e),void 0!==t&&(this.scaleXyz=t)}},e.UniformScaleDto=class{constructor(e){this.scale=1,void 0!==e&&(this.scale=e)}},e.UniformScaleFromCenterDto=class{constructor(e,t){this.scale=1,this.center=[0,0,0],void 0!==e&&(this.scale=e),void 0!==t&&(this.center=t)}},e.TranslationXYZDto=class{constructor(e){this.translation=[0,0,0],void 0!==e&&(this.translation=e)}},e.TranslationsXYZDto=class{constructor(e){void 0!==e&&(this.translations=e)}}}(OU||(OU={})),function(e){e.TwoVectorsDto=class{constructor(e,t){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.VectorBoolDto=class{constructor(e){void 0!==e&&(this.vector=e)}},e.VectorDto=class{constructor(e){void 0!==e&&(this.vector=e)}},e.RangeMaxDto=class{constructor(e){void 0!==e&&(this.max=e)}},e.VectorXYZDto=class{constructor(e,t,i){void 0!==e&&(this.x=e),void 0!==t&&(this.y=t),void 0!==i&&(this.z=i)}},e.VectorXYDto=class{constructor(e,t){void 0!==e&&(this.x=e),void 0!==t&&(this.y=t)}},e.SpanDto=class{constructor(e,t,i){this.step=.1,this.min=0,this.max=1,void 0!==e&&(this.step=e),void 0!==t&&(this.min=t),void 0!==i&&(this.max=i)}},e.RayPointDto=class{constructor(e,t,i){void 0!==e&&(this.point=e),void 0!==t&&(this.distance=t),void 0!==i&&(this.vector=i)}},e.VectorsDto=class{constructor(e){void 0!==e&&(this.vectors=e)}},e.FractionTwoVectorsDto=class{constructor(e,t,i){this.fraction=.5,void 0!==e&&(this.fraction=e),void 0!==t&&(this.first=t),void 0!==i&&(this.second=i)}},e.VectorScalarDto=class{constructor(e,t){void 0!==e&&(this.scalar=e),void 0!==t&&(this.vector=t)}},e.TwoVectorsReferenceDto=class{constructor(e,t,i){void 0!==e&&(this.reference=e),void 0!==t&&(this.first=t),void 0!==i&&(this.second=i)}}}(DU||(DU={})),function(e){e.CurveDto=class{constructor(e){void 0!==e&&(this.curve=e)}},e.CurvesDto=class{constructor(e){void 0!==e&&(this.curves=e)}},e.ClosestPointDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.point=t)}},e.ClosestPointsDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.points=t)}},e.BezierCurveDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.weights=t)}},e.DrawCurveDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.curve=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.curveMesh=n)}},e.CurveParameterDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.parameter=t)}},e.CurvesParameterDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.parameter=t)}},e.CurveTransformDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.transformation=t)}},e.CurvesTransformDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.transformation=t)}},e.CurveToleranceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.tolerance=t)}},e.CurveLengthToleranceDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.length=t),void 0!==i&&(this.tolerance=i)}},e.CurveDerivativesDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.parameter=t),void 0!==i&&(this.numDerivatives=i)}},e.CurveSubdivisionsDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.subdivision=t)}},e.CurvesSubdivisionsDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.subdivision=t)}},e.CurvesDivideLengthDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.length=t)}},e.CurveDivideLengthDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.length=t)}},e.DrawCurvesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.curves=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.curvesMesh=n)}},e.CurveNurbsDataDto=class{constructor(e,t,i,s){void 0!==e&&(this.degree=e),void 0!==t&&(this.weights=t),void 0!==i&&(this.knots=i),void 0!==s&&(this.points=s)}},e.CurvePathDataDto=class{constructor(e,t){void 0!==e&&(this.degree=e),void 0!==t&&(this.points=t)}},e.EllipseDto=class{constructor(e){void 0!==e&&(this.ellipse=e)}},e.CircleDto=class{constructor(e){void 0!==e&&(this.circle=e)}},e.ArcDto=class{constructor(e){void 0!==e&&(this.arc=e)}},e.EllipseParametersDto=class{constructor(e,t,i){void 0!==e&&(this.xAxis=e),void 0!==t&&(this.yAxis=t),void 0!==i&&(this.center=i)}},e.CircleParametersDto=class{constructor(e,t,i,s){void 0!==e&&(this.xAxis=e),void 0!==t&&(this.yAxis=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.center=s)}},e.ArcParametersDto=class{constructor(e,t,i,s,r,n){void 0!==e&&(this.minAngle=e),void 0!==t&&(this.maxAngle=t),void 0!==i&&(this.xAxis=i),void 0!==s&&(this.yAxis=s),void 0!==r&&(this.radius=r),void 0!==n&&(this.center=n)}},e.EllipseArcParametersDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.minAngle=e),void 0!==t&&(this.maxAngle=t),void 0!==i&&(this.xAxis=i),void 0!==s&&(this.yAxis=s),void 0!==r&&(this.center=r)}},e.SurfaceDto=class{constructor(e){void 0!==e&&(this.surface=e)}},e.SurfaceTransformDto=class{constructor(e,t){void 0!==e&&(this.surface=e),void 0!==t&&(this.transformation=t)}},e.SurfaceParameterDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.parameter=t),void 0!==i&&(this.useV=i)}},e.IsocurvesParametersDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.parameters=t),void 0!==i&&(this.useV=i)}},e.IsocurveSubdivisionDto=class{constructor(e,t,i,s,r){this.useV=!1,this.includeLast=!0,this.includeFirst=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.useV=t),void 0!==i&&(this.includeLast=i),void 0!==s&&(this.includeFirst=s),void 0!==r&&(this.isocurveSegments=r)}},e.DerivativesDto=class{constructor(e,t,i,s){void 0!==e&&(this.surface=e),void 0!==t&&(this.u=t),void 0!==i&&(this.v=i),void 0!==s&&(this.numDerivatives=s)}},e.SurfaceLocationDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.u=t),void 0!==i&&(this.v=i)}},e.CornersDto=class{constructor(e,t,i,s){void 0!==e&&(this.point1=e),void 0!==t&&(this.point2=t),void 0!==i&&(this.point3=i),void 0!==s&&(this.point4=s)}},e.SurfaceParamDto=class{constructor(e,t){void 0!==e&&(this.surface=e),void 0!==t&&(this.point=t)}},e.KnotsControlPointsWeightsDto=class{constructor(e,t,i,s,r,n){void 0!==e&&(this.degreeU=e),void 0!==t&&(this.degreeV=t),void 0!==i&&(this.knotsU=i),void 0!==s&&(this.knotsV=s),void 0!==r&&(this.points=r),void 0!==n&&(this.weights=n)}},e.LoftCurvesDto=class{constructor(e,t){void 0!==e&&(this.degreeV=e),void 0!==t&&(this.curves=t)}},e.DrawSurfaceDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surface=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.surfaceMesh=n)}},e.DrawSurfacesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surfaces=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.surfacesMesh=n)}},e.DrawSurfacesColoursDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surfaces=e),void 0!==t&&(this.colours=t),void 0!==i&&(this.opacity=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.surfacesMesh=n)}},e.ConeAndCylinderParametersDto=class{constructor(e,t,i,s,r){this.axis=[0,1,0],this.xAxis=[1,0,0],this.base=[0,0,0],this.height=2,this.radius=1,void 0!==e&&(this.axis=e),void 0!==t&&(this.xAxis=t),void 0!==i&&(this.base=i),void 0!==s&&(this.height=s),void 0!==r&&(this.radius=r)}},e.ConeDto=class{constructor(e){void 0!==e&&(this.cone=e)}},e.CylinderDto=class{constructor(e){void 0!==e&&(this.cylinder=e)}},e.ExtrusionParametersDto=class{constructor(e,t){void 0!==e&&(this.profile=e),void 0!==t&&(this.direction=t)}},e.ExtrusionDto=class{constructor(e){void 0!==e&&(this.extrusion=e)}},e.SphericalParametersDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.SphereDto=class{constructor(e){void 0!==e&&(this.sphere=e)}},e.RevolutionParametersDto=class{constructor(e,t,i,s){void 0!==e&&(this.profile=e),void 0!==t&&(this.center=t),void 0!==i&&(this.axis=i),void 0!==s&&(this.angle=s)}},e.RevolutionDto=class{constructor(e){void 0!==e&&(this.revolution=e)}},e.SweepParametersDto=class{constructor(e,t){void 0!==e&&(this.profile=e),void 0!==t&&(this.rail=t)}},e.SweepDto=class{constructor(e){void 0!==e&&(this.sweep=e)}},e.CurveCurveDto=class{constructor(e,t,i){void 0!==e&&(this.firstCurve=e),void 0!==t&&(this.secondCurve=t),void 0!==i&&(this.tolerance=i)}},e.CurveSurfaceDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t),void 0!==i&&(this.tolerance=i)}},e.SurfaceSurfaceDto=class{constructor(e,t,i){void 0!==e&&(this.firstSurface=e),void 0!==t&&(this.secondSurface=t),void 0!==i&&(this.tolerance=i)}},e.CurveCurveIntersectionsDto=class{constructor(e){void 0!==e&&(this.intersections=e)}},e.CurveSurfaceIntersectionsDto=class{constructor(e){void 0!==e&&(this.intersections=e)}}}(wU||(wU={}));class LU{constructor(e){this.context=e}dispose(e){e.babylonMesh&&(e.babylonMesh.getScene().removeMesh(e.babylonMesh,!0),e.babylonMesh.dispose())}updateDrawn(e){const t=e.babylonMesh.metadata.type;e.babylonMesh.position=new _e(e.position[0],e.position[1],e.position[2]),e.babylonMesh.rotation=new _e(e.rotation[0],e.rotation[1],e.rotation[2]),e.babylonMesh.scaling=new _e(e.scaling[0],e.scaling[1],e.scaling[2]);const i=Array.isArray(e.colours);let s;if(e.babylonMesh.getChildMeshes&&(s=e.babylonMesh.getChildMeshes()),s&&s.length>0)i&&e.colours.length===s.length?s.forEach(((t,i)=>{const s=Ee.FromHexString(e.colours[i]);this.assignColorToMesh(t,s)})):i?s.forEach((t=>{const i=Ee.FromHexString(e.colours[0]);this.assignColorToMesh(t,i)})):s.forEach((t=>{const i=Ee.FromHexString(e.colours);this.assignColorToMesh(t,i)}));else{const t=i?Ee.FromHexString(e.colours[0]):Ee.FromHexString(e.colours);this.assignColorToMesh(e.babylonMesh,t)}if(null!==e.babylonMesh.edgesRenderer){const t=i?Ee.FromHexString(e.colours[0]):Ee.FromHexString(e.colours);e.babylonMesh.edgesColor=Ae.FromColor3(t)}if([mU.drawingTypes.point,mU.drawingTypes.points,mU.drawingTypes.line,mU.drawingTypes.lines,mU.drawingTypes.polyline,mU.drawingTypes.polylines].includes(t)){const t=e.babylonMesh.getVerticesData(er.ColorKind).length/4,s=[];if(i&&t===e.colours.length)for(let i=0;i{t.visibility=e.visibility}))}hide(e){e.babylonMesh.isVisible=!1,e.includeChildren&&e.babylonMesh.getChildMeshes&&e.babylonMesh.getChildMeshes().forEach((e=>{e.isVisible=!1}))}show(e){e.babylonMesh.isVisible=!0,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((e=>{e.isVisible=!0}))}setParent(e){e.babylonMesh.parent=e.parentMesh}getParent(e){return e.babylonMesh.parent}setCheckCollisions(e){e.babylonMesh.checkCollisions=e.checkCollisions,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.checkCollisions=e.checkCollisions}))}getCheckCollisions(e){return e.babylonMesh.checkCollisions}setPickable(e){e.babylonMesh.isPickable=e.pickable,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.isPickable=e.pickable}))}getPickable(e){return e.babylonMesh.isPickable}getMeshesWhereNameContains(e){return this.context.scene.meshes.filter((t=>t.name.includes(e.name)))}getChildMeshes(e){return e.babylonMesh.getChildMeshes(e.directDescendantsOnly)}getMeshesOfId(e){return this.context.scene.getMeshesById(e.id)}getMeshOfId(e){return this.context.scene.getMeshById(e.id)}getMeshOfUniqueId(e){return this.context.scene.getMeshByUniqueId(e.uniqueId)}clone(e){var t,i;const s=e.babylonMesh.clone(),r=null===(i=null===(t=this.context.scene)||void 0===t?void 0:t.metadata)||void 0===i?void 0:i.shadowGenerators;return r.length>0&&(s.getChildMeshes().forEach((e=>{e.receiveShadows=!0,r.forEach((t=>t.addShadowCaster(e)))})),s.receiveShadows=!0,r.forEach((e=>e.addShadowCaster(s)))),s}setId(e){e.babylonMesh.id=e.id}getId(e){return e.babylonMesh.id}getUniqueId(e){return e.babylonMesh.uniqueId}setName(e){e.babylonMesh.name=e.name,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.name=e.name}))}getVerticesAsPolygonPoints(e){const t=e.babylonMesh.getVerticesData(er.PositionKind),i=e.babylonMesh.getIndices(),s=[];for(let e=0;e{t.material=e.material}))}getMaterial(e){return e.babylonMesh.material}getPosition(e){const t=e.babylonMesh;return[t.position.x,t.position.y,t.position.z]}getAbsolutePosition(e){const t=e.babylonMesh;return[t.absolutePosition.x,t.absolutePosition.y,t.absolutePosition.z]}getRotation(e){const t=e.babylonMesh;return[t.rotation.x,t.rotation.y,t.rotation.z]}getScale(e){const t=e.babylonMesh;return[t.scaling.x,t.scaling.y,t.scaling.z]}moveForward(e){const t=e.babylonMesh;t.translate(t.forward,e.distance,Ur.WORLD)}moveBackward(e){const t=e.babylonMesh;t.translate(t.forward.negate(),e.distance,Ur.WORLD)}moveUp(e){const t=e.babylonMesh;t.translate(t.up,e.distance,Ur.WORLD)}moveDown(e){const t=e.babylonMesh;t.translate(t.up.negate(),e.distance,Ur.WORLD)}moveRight(e){const t=e.babylonMesh;t.translate(t.right,e.distance,Ur.WORLD)}moveLeft(e){const t=e.babylonMesh;t.translate(t.right.negate(),e.distance,Ur.WORLD)}yaw(e){const t=e.babylonMesh,i=$r.FromDegrees(e.rotate).radians();t.rotate(Xr.Y,i,Ur.LOCAL)}pitch(e){const t=e.babylonMesh,i=$r.FromDegrees(e.rotate).radians();t.rotate(Xr.X,i,Ur.LOCAL)}roll(e){const t=e.babylonMesh,i=$r.FromDegrees(e.rotate).radians();t.rotate(Xr.Z,i,Ur.LOCAL)}rotateAroundAxisWithPosition(e){e.mesh.rotateAround(new _e(e.position[0],e.position[1],e.position[2]),new _e(e.axis[0],e.axis[1],e.axis[2]),$r.FromDegrees(e.angle).radians())}setPosition(e){e.babylonMesh.position=new _e(e.position[0],e.position[1],e.position[2])}setRotation(e){const t=$r.FromDegrees(e.rotation[0]).radians(),i=$r.FromDegrees(e.rotation[1]).radians(),s=$r.FromDegrees(e.rotation[2]).radians();e.babylonMesh.rotation=new _e(t,i,s)}setScale(e){e.babylonMesh.scaling=new _e(e.scale[0],e.scale[1],e.scale[2])}intersectsMesh(e){return e.babylonMesh.intersectsMesh(e.babylonMesh2,e.precise,e.includeDescendants)}intersectsPoint(e){const t=new _e(e.point[0],e.point[1],e.point[2]);return e.babylonMesh.intersectsPoint(t)}createMeshInstanceAndTransformNoReturn(e){this.createMeshInstanceAndTransform(e)}createMeshInstanceAndTransform(e){var t,i;const s=new ha("instanceContainer"+Math.random(),this.context.scene),r=null===(i=null===(t=this.context.scene)||void 0===t?void 0:t.metadata)||void 0===i?void 0:i.shadowGenerators;if(e.mesh&&e.mesh.getChildMeshes&&e.mesh.getChildMeshes().length>0)e.mesh.getChildMeshes(!1).forEach((t=>{const i=t.getTotalVertices();if(t.createInstance&&i>0){t.disableEdgesRendering();const i=t.createInstance(`InstanceMesh${Math.random()}`);i.position=new _e(e.position[0],e.position[1],e.position[2]),i.rotation=new _e(e.rotation[0],e.rotation[1],e.rotation[2]),i.scaling=new _e(e.scaling[0],e.scaling[1],e.scaling[2]),r.length>0&&r.forEach((e=>{e.addShadowCaster(i)})),i.parent=s}})),e.mesh.isVisible=!1;else if(e.mesh){e.mesh.isVisible=!1;const t=e.mesh.createInstance(`InstanceMesh${Math.random()}`);t.position=new _e(e.position[0],e.position[1],e.position[2]),t.rotation=new _e($r.FromDegrees(e.rotation[0]).radians(),$r.FromDegrees(e.rotation[1]).radians(),$r.FromDegrees(e.rotation[2]).radians()),t.scaling=new _e(e.scaling[0],e.scaling[1],e.scaling[2]),t.parent=s,r.length>0&&r.forEach((e=>{e.addShadowCaster(t)}))}return s}createMeshInstance(e){let t;if(e.mesh&&e.mesh.getChildMeshes&&e.mesh.getChildMeshes().length>0){e.mesh.setParent(null);const i=new ha("meshCloneContainer"+Math.random());e.mesh.getChildMeshes(!1).forEach((e=>{e.createInstance&&e.getTotalVertices()>0&&e.getTotalIndices()>0&&(e.createInstance(`InstanceMesh${Math.random()}`).parent=i)})),t=i;const s=this.context.scene.metadata.shadowGenerators;s.length>0&&(t.getChildMeshes().forEach((e=>{s.forEach((t=>t.addShadowCaster(e)))})),s.forEach((e=>e.addShadowCaster(t))))}else if(e.mesh&&(e.mesh.setParent(null),e.mesh.getTotalVertices()>0)){const i=new ha("meshCloneContainer"+Math.random());e.mesh.createInstance(`InstanceMesh${Math.random()}`).parent=i,t=i}return t}getSideOrientation(e){switch(e){case hU.sideOrientationEnum.frontside:return ha.FRONTSIDE;case hU.sideOrientationEnum.backside:return ha.BACKSIDE;case hU.sideOrientationEnum.doubleside:return ha.DOUBLESIDE;default:return ha.FRONTSIDE}}assignColorToMesh(e,t){const i=e.material;i instanceof Lx?i.baseColor=t:i instanceof cu&&(i.diffuseColor=t)}}class BU{constructor(e,t){this.context=e,this.mesh=t}createBox(e){const t=R_.CreateBox("BabylonMesh"+Math.random(),{width:e.width,height:e.height,depth:e.depth,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}createCube(e){const t=R_.CreateBox("BabylonMesh"+Math.random(),{size:e.size,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}createSquarePlane(e){const t=R_.CreatePlane("BabylonMesh"+Math.random(),{size:e.size,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}createRectanglePlane(e){const t=R_.CreatePlane("BabylonMesh"+Math.random(),{width:e.width,height:e.height,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}enableShadows(e){this.context.scene.metadata.shadowGenerators&&(e.receiveShadows=!0,this.context.scene.metadata.shadowGenerators.forEach((t=>{t.addShadowCaster(e)})))}}class kU{constructor(e,t){this.context=e,this.geometryHelper=t}drawNode(e){this.geometryHelper.localAxes(e.size,this.context.scene,e.colorX,e.colorY,e.colorZ).parent=e.node}drawNodes(e){e.nodes.forEach((t=>{this.geometryHelper.localAxes(e.size,this.context.scene,e.colorX,e.colorY,e.colorZ).parent=t}))}createNodeFromRotation(e){const t=new lo(`node${Math.random()}`,this.context.scene);return e.parent&&(t.parent=e.parent),t.position=new _e(e.origin[0],e.origin[1],e.origin[2]),t.rotation=new _e($r.FromDegrees(e.rotation[0]).radians(),$r.FromDegrees(e.rotation[1]).radians(),$r.FromDegrees(e.rotation[2]).radians()),t}createWorldNode(){const e=new lo(`root${Math.random()}`,this.context.scene);return e.parent=this.context.scene.getTransformNodeByID("root"),e}getAbsoluteForwardVector(e){const t=e.node.forward;return[t.x,t.y,t.z]}getAbsoluteRightVector(e){const t=e.node.right;return[t.x,t.y,t.z]}getAbsoluteUpVector(e){const t=e.node.up;return[t.x,t.y,t.z]}getAbsolutePosition(e){const t=e.node.getAbsolutePosition();return[t.x,t.y,t.z]}getAbsoluteRotationTransformation(e){const t=new me;return e.node.absoluteRotationQuaternion.toRotationMatrix(t),[...t.toArray()]}getRotationTransformation(e){const t=new me;return e.node.rotationQuaternion.toRotationMatrix(t),[...t.toArray()]}getChildren(e){return e.node.getChildren()}getParent(e){return e.node.parent}getPositionExpressedInLocalSpace(e){const t=e.node.getPositionExpressedInLocalSpace();return[t.x,t.y,t.z]}getRootNode(){return this.context.scene.getTransformNodeByID("root")}getRotation(e){const t=e.node.rotation;return[$r.FromRadians(t.x).degrees(),$r.FromRadians(t.y).degrees(),$r.FromRadians(t.z).degrees()]}rotateAroundAxisWithPosition(e){e.node.rotateAround(new _e(e.position[0],e.position[1],e.position[2]),new _e(e.axis[0],e.axis[1],e.axis[2]),$r.FromDegrees(e.angle).radians())}rotate(e){e.node.rotate(new _e(e.axis[0],e.axis[1],e.axis[2]),$r.FromDegrees(e.angle).radians())}setAbsolutePosition(e){e.node.setAbsolutePosition(new _e(e.position[0],e.position[1],e.position[2]))}setDirection(e){e.node.setDirection(new _e(e.direction[0],e.direction[1],e.direction[2]))}setParent(e){e.node.setParent(e.parentNode)}translate(e){e.node.translate(new _e(e.direction[0],e.direction[1],e.direction[2]),e.distance)}}class VU{constructor(e){this.context=e}pickWithRay(e){return this.context.scene.pickWithRay(e.ray)}pickWithPickingRay(){const e=this.context.scene,t=e.createPickingRay(e.pointerX,e.pointerY,me.Identity(),this.context.scene.activeCamera,!1);return e.pickWithRay(t)}getDistance(e){return e.pickInfo.distance}getPickedMesh(e){return e.pickInfo.pickedMesh}getPickedPoint(e){const t=e.pickInfo.pickedPoint;return[t.x,t.y,t.z]}hit(e){return e.pickInfo.hit}getSubMeshId(e){return e.pickInfo.subMeshId}getSubMeshFaceId(e){return e.pickInfo.subMeshFaceId}getBU(e){return e.pickInfo.bu}getBV(e){return e.pickInfo.bv}getPickedSprite(e){return e.pickInfo.pickedSprite}}class UU{constructor(e){this.context=e}createPickingRay(){const e=this.context.scene;return e.createPickingRay(e.pointerX,e.pointerY,me.Identity(),this.context.scene.activeCamera,!1)}createRay(e){const t=new _e(e.origin[0],e.origin[1],e.origin[2]),i=new _e(e.direction[0],e.direction[1],e.direction[2]);let s;return 0!==e.length&&(s=e.length),new Ua(t,i,s)}createRayFromTo(e){const t=new _e(e.from[0],e.from[1],e.from[2]),i=new _e(e.to[0],e.to[1],e.to[2]);return Ua.CreateNewFromTo(t,i)}getOrigin(e){const t=e.ray.origin;return[t.x,t.y,t.z]}getDirection(e){const t=e.ray.direction;return[t.x,t.y,t.z]}getLength(e){return e.ray.length}}class GU{constructor(e){this.context=e}getScene(){return this.context.scene}setAndAttachScene(e){return e.scene.metadata={shadowGenerators:[]},new lo("root",this.context.scene),this.context.scene=e.scene}backgroundColour(e){this.context.scene.clearColor=Ae.FromColor3(Ee.FromHexString(e.colour))}activateCamera(e){this.context.scene.activeCamera.detachControl(),this.context.scene.activeCamera=e.camera}useRightHandedSystem(e){this.context.scene.useRightHandedSystem=e.use,this.context.scene.activeCamera.getViewMatrix(!0),this.context.scene.activeCamera.getProjectionMatrix(!0)}drawPointLightNoReturn(e){this.drawPointLight(e)}getShadowGenerators(){return this.context.scene.metadata&&this.context.scene.metadata.shadowGenerators?this.context.scene.metadata.shadowGenerators:[]}drawPointLight(e){const t=new _e(e.position[0],e.position[1],e.position[2]),i=new ex(`pointLight${Math.random()}`,t,this.context.scene);if(e.enableShadows){i.shadowEnabled=!0;const t=new Wv(e.shadowGeneratorMapSize,i);t.darkness=e.shadowDarkness,t.usePercentageCloserFiltering=!0,t.contactHardeningLightSizeUVRatio=.2,t.bias=1e-4,t.normalBias=.002,i.shadowMaxZ=1e3,i.shadowMinZ=.01,this.context.scene.metadata.shadowGenerators.push(t),this.context.scene.meshes.forEach((e=>{"bitbybit-hdrSkyBox"===e.name||e.name.includes("bitbybit-ground")||(t.addShadowCaster(e,!0),e.receiveShadows=!0)}))}if(i.diffuse=Ee.FromHexString(e.diffuse),i.specular=Ee.FromHexString(e.specular),i.intensityMode=ua.INTENSITYMODE_LUMINOUSPOWER,i.intensity=e.intensity,e.radius>0){const t=R_.CreateSphere(`PointLightSphere${Math.random()}`,{diameter:2*e.radius},this.context.scene),s=new cu(`LightMaterial${Math.random()}`,this.context.scene);s.diffuseColor=i.diffuse,s.specularColor=i.diffuse,s.emissiveColor=i.diffuse,t.material=s,t.parent=i}return i}drawDirectionalLightNoReturn(e){this.drawDirectionalLight(e)}drawDirectionalLight(e){const t=new _e(e.direction[0],e.direction[1],e.direction[2]),i=new cg(`directionalLight${Math.random()}`,t,this.context.scene);if(e.enableShadows){i.shadowEnabled=!0;const t=new Wv(e.shadowGeneratorMapSize,i);t.darkness=e.shadowDarkness,t.usePercentageCloserFiltering=!0,t.contactHardeningLightSizeUVRatio=.2,t.bias=1e-4,t.normalBias=.002,i.shadowMaxZ=1e3,i.shadowMinZ=0,this.context.scene.metadata.shadowGenerators.push(t),this.context.scene.meshes.forEach((e=>{"bitbybit-hdrSkyBox"===e.name||e.name.includes("bitbybit-ground")||(t.addShadowCaster(e,!0),e.receiveShadows=!0)}))}return i.diffuse=Ee.FromHexString(e.diffuse),i.specular=Ee.FromHexString(e.specular),i.intensity=e.intensity,i.shadowMaxZ=1e3,i}getActiveCamera(){return this.context.scene.activeCamera}adjustActiveArcRotateCamera(e){const t=this.context.scene.getCameraByName("Camera");t.position=new _e(e.position[0],e.position[1],e.position[2]),t.target=new _e(e.lookAt[0],e.lookAt[1],e.lookAt[2]);const i=_e.Distance(t.position,t.target);t.radius=i,void 0!==e.lowerBetaLimit&&(t.lowerBetaLimit=this.getRadians(e.lowerBetaLimit)),void 0!==e.upperBetaLimit&&(t.upperBetaLimit=this.getRadians(e.upperBetaLimit)),void 0!==e.angularSensibilityX&&(t.angularSensibilityX=e.angularSensibilityX),void 0!==e.angularSensibilityY&&(t.angularSensibilityY=e.angularSensibilityY),void 0!==e.panningSensibility&&(t.panningSensibility=e.panningSensibility),void 0!==e.wheelPrecision&&(t.wheelPrecision=e.wheelPrecision),void 0!==e.maxZ&&(t.maxZ=e.maxZ)}clearAllDrawn(){const e=this.context.scene;if(e&&(e.environmentTexture&&e.environmentTexture.dispose(),e.environmentTexture=null,e.fogMode=Hr.FOGMODE_NONE,e.meshes.forEach((e=>e.dispose())),e.meshes=[],e.materials.forEach((e=>e.dispose())),e.textures.forEach((e=>e.dispose())),e.materials=[],e.textures=[],e.useRightHandedSystem=!1,e.geometries.forEach((e=>{e.meshes&&e.meshes.forEach((e=>e.dispose())),e.dispose&&e.dispose()})),e.geometries=[],e.lights.forEach((e=>{"HemiLight"!==e.name&&e.dispose()})),e.lights=e.lights.filter((e=>"HemiLight"===e.name)),e.transformNodes&&e.transformNodes.forEach((e=>{e&&"root"!==e.name&&e.dispose()})),e.metadata&&(e.metadata.shadowGenerators.length>0&&(e.metadata.shadowGenerators.forEach((e=>e.dispose())),e.metadata.shadowGenerators=[]),e.metadata.xr&&e.metadata.xr.dispose(),e.metadata.guiManager&&e.metadata.guiManager.dispose()),e.transformNodes=[e.getTransformNodeByName("root")],e.activeCamera&&"Camera"!==e.activeCamera.name)){e.cameras.forEach((e=>e.dispose()));const t=new hc("Camera",0,10,10,new _e(0,0,0),e);t.lowerRadiusLimit=0,e.setActiveCameraByName(t.name),t.setPosition(new _e(0,10,20));const i=document.getElementById("renderCanvas");t.attachControl(i,!0),t.minZ=0}}enableSkybox(e){let t;e.skybox===AU.skyboxEnum.default?t=new vg("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.15.12/textures/skybox/default_skybox/skybox",this.context.scene):e.skybox===AU.skyboxEnum.clearSky?t=vg.CreateFromPrefilteredData("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.15.12/textures/skybox/clear_sky/environment.env",this.context.scene,!1,!1):e.skybox===AU.skyboxEnum.city&&(t=vg.CreateFromPrefilteredData("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.15.12/textures/skybox/city/environmentSpecular.env",this.context.scene,!1,!1)),this.context.scene.createDefaultSkybox(t,!0,e.size,e.blur,!0).name="bitbybit-hdrSkyBox",this.context.scene.environmentIntensity=e.environmentIntensity}onPointerDown(e){this.context.scene.onPointerDown=e.statement_update}onPointerUp(e){this.context.scene.onPointerUp=e.statement_update}onPointerMove(e){this.context.scene.onPointerMove=e.statement_update}fog(e){switch(e.mode){case AU.fogModeEnum.none:this.context.scene.fogMode=0;break;case AU.fogModeEnum.exponential:this.context.scene.fogMode=1;break;case AU.fogModeEnum.exponentialSquared:this.context.scene.fogMode=2;break;case AU.fogModeEnum.linear:this.context.scene.fogMode=3}this.context.scene.fogDensity=e.density,this.context.scene.fogStart=e.start,this.context.scene.fogEnd=e.end,this.context.scene.fogColor=Ee.FromHexString(e.color)}enablePhysics(e){this.context.scene.enablePhysics(new _e(e.vector[0],e.vector[1],e.vector[2]),this.context.havokPlugin)}getRadians(e){let t=$r.FromDegrees(e).radians();return e<0&&(t=-t),t}}class zU{constructor(e){this.context=e}createSimple(e){const t=new Pa(e.url,this.context.scene,void 0,e.invertY,this.getSamplingMode(e.samplingMode));return t.uScale=e.uScale,t.vScale=e.vScale,t.wAng=e.wAng,t.invertZ=e.invertZ,t.uOffset=e.uOffset,t.vOffset=e.vOffset,t}getSamplingMode(e){switch(e){case _U.samplingModeEnum.nearest:return Pa.NEAREST_SAMPLINGMODE;case _U.samplingModeEnum.bilinear:return Pa.BILINEAR_SAMPLINGMODE;case _U.samplingModeEnum.trilinear:return Pa.TRILINEAR_SAMPLINGMODE;default:return Pa.NEAREST_SAMPLINGMODE}}}class WU{rotationCenterAxis(e){return[[...me.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...me.RotationAxis(new _e(e.axis[0],e.axis[1],e.axis[2]),$r.FromDegrees(e.angle).radians()).toArray()],[...me.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterX(e){return[[...me.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...me.RotationX($r.FromDegrees(e.angle).radians()).toArray()],[...me.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterY(e){return[[...me.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...me.RotationY($r.FromDegrees(e.angle).radians()).toArray()],[...me.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterZ(e){return[[...me.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...me.RotationZ($r.FromDegrees(e.angle).radians()).toArray()],[...me.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterYawPitchRoll(e){return[[...me.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...me.RotationYawPitchRoll($r.FromDegrees(e.yaw).radians(),$r.FromDegrees(e.pitch).radians(),$r.FromDegrees(e.roll).radians()).toArray()],[...me.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}scaleCenterXYZ(e){return[[...me.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...me.Scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2]).toArray()],[...me.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}scaleXYZ(e){return[[...me.Scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2]).toArray()]]}uniformScale(e){return[[...me.Scaling(e.scale,e.scale,e.scale).toArray()]]}uniformScaleFromCenter(e){return[[...me.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...me.Scaling(e.scale,e.scale,e.scale).toArray()],[...me.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}translationXYZ(e){return[[...me.Translation(e.translation[0],e.translation[1],e.translation[2]).toArray()]]}translationsXYZ(e){return e.translations.map((e=>[[...me.Translation(e[0],e[1],e[2]).toArray()]]))}}class HU{constructor(e,t,i){this.mesh=new LU(e),this.camera=new lV(e),this.gaussianSplatting=new fV(e),this.node=new kU(e,t),this.scene=new GU(e),this.webxr=new dV(e),this.transforms=new WU,this.io=new FU(e),this.ray=new UU(e),this.pick=new VU(e),this.material=new cV(e,i),this.texture=new zU(e),this.meshBuilder=new BU(e,this.mesh),this.engine=new _V(e)}}var XU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class YU{constructor(e){this.jscadWorkerManager=e}intersect(e){return XU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.intersect",e)}))}subtract(e){return XU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.subtract",e)}))}union(e){return XU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.union",e)}))}intersectTwo(e){return XU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.intersectTwo",e)}))}subtractTwo(e){return XU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.subtractTwo",e)}))}unionTwo(e){return XU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.unionTwo",e)}))}subtractFrom(e){return XU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.subtractFrom",e)}))}}var QU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class jU{constructor(e){this.jscadWorkerManager=e}expand(e){return QU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("expansions.expand",e)}))}offset(e){return QU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("expansions.offset",e)}))}}var KU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class $U{constructor(e){this.jscadWorkerManager=e}extrudeLinear(e){return KU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeLinear",e)}))}extrudeRectangular(e){return KU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeRectangular",e)}))}extrudeRectangularPoints(e){return KU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeRectangularPoints",e)}))}extrudeRotate(e){return KU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeRotate",e)}))}}var qU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class ZU{constructor(e){this.jscadWorkerManager=e}hullChain(e){return qU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("hulls.hullChain",e)}))}hull(e){return qU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("hulls.hullChain",e)}))}}var JU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class eG{constructor(e){this.jscadWorkerManager=e}createFromPoints(e){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createFromPoints",e)}))}createPathsFromPoints(e){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createPathsFromPoints",e)}))}createFromPolyline(e){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createFromPolyline",e)}))}createEmpty(){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createEmpty",{})}))}close(e){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.close",e)}))}appendPoints(e){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.appendPoints",e)}))}appendPolyline(e){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.appendPolyline",e)}))}appendArc(e){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.appendArc",e)}))}}var tG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class iG{constructor(e){this.jscadWorkerManager=e}createFromPoints(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromPoints",e)}))}createFromPolyline(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromPolyline",e)}))}createFromCurve(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromCurve",e)}))}createFromPath(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromPath",e)}))}circle(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.circle",e)}))}ellipse(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.ellipse",e)}))}rectangle(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.rectangle",e)}))}roundedRectangle(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.roundedRectangle",e)}))}square(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.square",e)}))}star(e){return tG(this,void 0,void 0,(function*(){return yield this.jscadWorkerManager.genericCallToWorkerPromise("polygon.star",e)}))}}var sG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class rG{constructor(e){this.jscadWorkerManager=e}cube(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cube",e)}))}cubesOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cubesOnCenterPoints",e)}))}cuboid(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cuboid",e)}))}cuboidsOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cuboidsOnCenterPoints",e)}))}cylinderElliptic(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylinderElliptic",e)}))}cylinderEllipticOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylinderEllipticOnCenterPoints",e)}))}cylinder(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylinder",e)}))}cylindersOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylindersOnCenterPoints",e)}))}ellipsoid(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.ellipsoid",e)}))}ellipsoidsOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.ellipsoidsOnCenterPoints",e)}))}geodesicSphere(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.geodesicSphere",e)}))}geodesicSpheresOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.geodesicSpheresOnCenterPoints",e)}))}roundedCuboid(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCuboid",e)}))}roundedCuboidsOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCuboidsOnCenterPoints",e)}))}roundedCylinder(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCylinder",e)}))}roundedCylindersOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCylindersOnCenterPoints",e)}))}sphere(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.sphere",e)}))}spheresOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.spheresOnCenterPoints",e)}))}torus(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.torus",e)}))}fromPolygonPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.fromPolygonPoints",e)}))}}var nG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class oG{constructor(e){this.jscadWorkerManager=e}cylindricalText(e){return nG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("text.cylindricalText",e)}))}sphericalText(e){return nG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("text.sphericalText",e)}))}createVectorText(e){return nG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("text.createVectorText",e)}))}}class aG{constructor(e){this.jscadWorkerManager=e}colorize(e){return t=this,i=void 0,r=function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("colors.colorize",e)},new((s=void 0)||(s=Promise))((function(e,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,a)}l((r=r.apply(t,i||[])).next())}));var t,i,s,r}}var lG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class hG{constructor(e,t,i){this.jscadWorkerManager=e,this.context=t,this.geometryHelper=i,this.booleans=new YU(e),this.expansions=new jU(e),this.extrusions=new $U(e),this.hulls=new ZU(e),this.path=new eG(e),this.polygon=new iG(e),this.shapes=new rG(e),this.text=new oG(e),this.colors=new aG(e)}drawSolidOrPolygonMesh(e){return lG(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("shapeToMesh",e);let i,s;i=e.jscadMesh&&e.updatable?e.jscadMesh:new ha(`jscadMesh${Math.random()}`,this.context.scene),s=e.mesh.color&&e.mesh.color.length>0?Ee.FromArray(e.mesh.color).toHexString():Array.isArray(e.colours)?e.colours[0]:e.colours;const r=this.makeMesh(Object.assign(Object.assign({},e),{colour:s}),i,t);return e.jscadMesh=r,r}))}makeMesh(e,t,i){this.createMesh(i.positions,i.indices,i.normals,t,i.transforms,e.updatable),t.material=new Lx(`jscadMaterial${Math.random()}`,this.context.scene),t.flipFaces(!1);const s=t.material;return s.baseColor=Ee.FromHexString(e.colour),s.metallic=1,s.roughness=.6,s.alpha=e.opacity,s.alphaMode=1,s.backFaceCulling=!0,s.zOffset=0,t.isPickable=!1,e.hidden&&(t.isVisible=!1),t}drawSolidOrPolygonMeshes(e){return lG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e).then((t=>{let i;e.jscadMesh&&e.updatable?(i=e.jscadMesh,i.getChildMeshes().forEach((e=>{e.dispose(),i.removeChild(e)}))):i=new ha("local_origin"+Math.random(),this.context.scene),i.isVisible=!1;const s=Array.isArray(e.colours)&&e.colours.length===t.length,r=Array.isArray(e.colours);return t.map(((t,n)=>{const o=new ha(`jscadMesh${Math.random()}`,this.context.scene);let a;a=t.color?Ee.FromArray(t.color).toHexString():s?e.colours[n]:r?e.colours[0]:e.colours,this.makeMesh(Object.assign(Object.assign({},e),{colour:a}),o,t).parent=i})),e.jscadMesh=i,i}))}))}drawPath(e){return lG(this,void 0,void 0,(function*(){return new Promise((t=>{if(e.path.points&&e.path.isClosed){const t=e.path.points[0];e.path.points.push([t[0],0,t[1]])}let i=e.colour;e.path.color&&(i=Ee.FromArray(e.path.color).toHexString()),t(this.geometryHelper.drawPolyline(e.pathMesh,e.path.points,e.updatable,e.width,e.opacity,i))}))}))}transformSolids(e){return lG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("transformSolids",e)}))}transformSolid(e){return lG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("transformSolid",e)}))}downloadSolidSTL(e){return lG(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("downloadSolidSTL",e);this.downloadFile(t.blob,e.fileName,"stl")}))}downloadSolidsSTL(e){return lG(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("downloadSolidsSTL",e);this.downloadFile(t.blob,e.fileName,"stl")}))}downloadGeometryDxf(e){return lG(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("downloadGeometryDxf",e);this.downloadFile(t.blob,e.fileName,"dxf")}))}downloadFile(e,t,i){const s=URL.createObjectURL(e),r=document.createElement("a");r.href=s,r.target="_self",r.download=t+"."+i,r.click(),r.remove()}createMesh(e,t,i,s,r,n){const o=new Wn;o.positions=e,o.indices=t,Wn.ComputeNormals(e,t,i,{useRightHandedSystem:!0}),o.normals=i,o.applyToMesh(s,n),s.setPreTransformMatrix(me.FromArray(r))}}var cG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class uG extends $B{constructor(e,t,i){super(e),this.occWorkerManager=e,this.context=t,this.geometryHelper=i}loadSTEPorIGES(e){return this.context.getFile(e.assetFile).then((t=>this.occWorkerManager.genericCallToWorkerPromise("io.loadSTEPorIGES",new Jk.LoadStepOrIgesDto(t,e.assetFile.name,e.adjustZtoY))))}loadSTEPorIGESFromText(e){return this.occWorkerManager.genericCallToWorkerPromise("io.loadSTEPorIGES",new Jk.LoadStepOrIgesDto(e.text,`fake.${e.fileType}`,e.adjustZtoY))}saveShapeStl(e){return cG(this,void 0,void 0,(function*(){this.saveStl(e)}))}saveShapeStlAndReturn(e){return cG(this,void 0,void 0,(function*(){return this.saveStl(e)}))}saveStl(e){return cG(this,void 0,void 0,(function*(){const t=new Jk.DrawShapeDto;t.drawEdges=!1,t.shape=e.shape,t.precision=e.precision;const i=(yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",t)).faceList.map((e=>this.geometryHelper.createOrUpdateSurfaceMesh({positions:e.vertex_coord,normals:e.normal_coord,indices:e.tri_indexes},void 0,!1,void 0,!0,!1)));let s;return e.fileName.includes(".stl")&&(e.fileName=e.fileName.replace(".stl","")),s=document&&e.tryDownload?sU.CreateSTL(i,!0,e.fileName,e.binary,!0,!0):sU.CreateSTL(i,!1,e.fileName,e.binary,!0,!0),i.forEach((e=>e.dispose())),s}))}}var dG,_G=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class pG extends fk{constructor(e,t,i,s,r){super(t),this.context=e,this.occWorkerManager=t,this.geometryHelper=i,this.solidText=s,this.vector=r,this.usedMaterials=[],this.io=new uG(t,e,i)}drawShape(e){return _G(this,void 0,void 0,(function*(){const t=Object.assign({},e);e.faceMaterial&&delete e.faceMaterial;const i=yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",e);return this.handleDecomposedMesh(e,i,t)}))}drawShapes(e){return _G(this,void 0,void 0,(function*(){const t=Object.assign({},e);e.faceMaterial&&delete e.faceMaterial;const i=yield this.occWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e),s=yield Promise.all(i.map((i=>_G(this,void 0,void 0,(function*(){return this.handleDecomposedMesh(e,i,t)}))))),r=new ha("shapesMeshContainer"+Math.random(),this.context.scene);return s.forEach((e=>{e.parent=r})),r}))}handleDecomposedMesh(e,t,i){return _G(this,void 0,void 0,(function*(){const s=new ha("brepMesh"+Math.random(),this.context.scene);let r;if(s.isVisible=!1,e.drawFaces&&t&&t.faceList&&t.faceList.length){let n;if(i.faceMaterial)n=i.faceMaterial;else{const t=Array.isArray(e.faceColour)?e.faceColour[0]:e.faceColour,i=e.faceOpacity,s=e.drawEdges?2:0,r=this.usedMaterials.find((e=>e.sceneId===this.context.scene.uid&&e.hex===t&&e.alpha===i&&e.zOffset===s));if(this.usedMaterials=this.usedMaterials.filter((e=>e.sceneId===this.context.scene.uid)),r)n=r.material;else{const e=new Lx("pbr"+Math.random(),this.context.scene);e.baseColor=Ee.FromHexString(t),e.metallic=1,e.roughness=.6,e.alpha=i,e.alphaMode=1,e.backFaceCulling=!0,e.doubleSided=!1,e.zOffset=s,this.usedMaterials.push({sceneId:this.context.scene.uid,hex:t,alpha:i,zOffset:s,material:e}),n=e}}const o=t.faceList.map((e=>({positions:e.vertex_coord,normals:e.normal_coord,indices:e.tri_indexes,uvs:e.uvs})));this.geometryHelper.createOrUpdateSurfacesMesh(o,r,!1,n,!0,!1).parent=s}if(e.drawEdges&&t&&t.edgeList&&t.edgeList.length){const i=[];t.edgeList.forEach((e=>{const t=e.vertex_coord.filter((e=>void 0!==e));i.push(t)})),this.geometryHelper.drawPolylines(r,i,!1,e.edgeWidth,e.edgeOpacity,e.edgeColour).parent=s}if(e.drawVertices&&t&&t.pointsList&&t.pointsList.length&&(this.geometryHelper.drawPoints({pointsMesh:r,points:t.pointsList,opacity:1,size:e.vertexSize,colours:e.vertexColour,updatable:!1}).parent=s),e.drawEdgeIndexes){const i=t.edgeList.map((t=>_G(this,void 0,void 0,(function*(){const i=this.computeEdgeMiddlePos(t),s=new gU.TextDto;return s.text=`${t.edge_index+1}`,s.height=e.edgeIndexHeight,s.lineSpacing=1.5,(yield this.solidText.createVectorText(s)).map((e=>e.map((e=>[e[0],e[1]+.05,0])).map((e=>this.vector.add({first:e,second:i})))))})))),r=yield Promise.all(i),n=this.geometryHelper.drawPolylines(null,r.flat(),!1,.2,1,e.edgeIndexColour);n.parent=s,n.material.zOffset=-2}if(e.drawFaceIndexes){const i=t.faceList.map((t=>_G(this,void 0,void 0,(function*(){const i=this.computeFaceMiddlePos(t.vertex_coord_vec),s=new gU.TextDto;return s.text=`${t.face_index}`,s.height=e.faceIndexHeight,s.lineSpacing=1.5,(yield this.solidText.createVectorText(s)).map((e=>e.map((e=>[e[0],e[1]+.05,0])).map((e=>this.vector.add({first:e,second:i})))))})))),r=yield Promise.all(i),n=this.geometryHelper.drawPolylines(null,r.flat(),!1,.2,1,e.faceIndexColour);n.parent=s,e.drawEdges&&(n.material.zOffset=-2)}return s}))}computeFaceMiddlePos(e){let t=0,i=0,s=0,r=0;return e.forEach((e=>{t+=e[0],i+=e[1],s+=e[2],r++})),[t/r,i/r,s/r]}computeEdgeMiddlePos(e){let t;if(2===e.vertex_coord.length){const i=e.vertex_coord[0],s=e.vertex_coord[1];t=this.vector.lerp({first:i,second:s,fraction:.5})}else if(3===e.vertex_coord.length)t=e.vertex_coord[1];else{const i=e.vertex_coord[Math.floor(e.vertex_coord.length/2)],s=e.vertex_coord[Math.floor(e.vertex_coord.length/2+1)];t=this.vector.lerp({first:i,second:s,fraction:.5})}return t}}class fG{constructor(e){this.context=e}createCircle(e){return new this.context.verb.geom.Circle(e.center,e.xAxis,e.yAxis,e.radius)}createArc(e){return new this.context.verb.geom.Arc(e.center,e.xAxis,e.yAxis,e.radius,$r.FromDegrees(e.minAngle).radians(),$r.FromDegrees(e.maxAngle).radians())}center(e){return e.circle.center()}radius(e){return e.circle.radius()}maxAngle(e){return $r.FromRadians(e.circle.maxAngle()).degrees()}minAngle(e){return $r.FromRadians(e.circle.minAngle()).degrees()}xAxis(e){return e.circle.xaxis()}yAxis(e){return e.circle.yaxis()}}class mG{constructor(e){this.context=e}createEllipse(e){return new this.context.verb.geom.Ellipse(e.center,e.xAxis,e.yAxis)}createArc(e){return new this.context.verb.geom.EllipseArc(e.center,e.xAxis,e.yAxis,$r.FromDegrees(e.minAngle).radians(),$r.FromDegrees(e.maxAngle).radians())}center(e){return e.ellipse.center()}maxAngle(e){return $r.FromRadians(e.ellipse.maxAngle()).degrees()}minAngle(e){return $r.FromRadians(e.ellipse.minAngle()).degrees()}xAxis(e){return e.ellipse.xaxis()}yAxis(e){return e.ellipse.yaxis()}}class gG{constructor(e,t){this.context=e,this.geometryHelper=t,this.circle=new fG(e),this.ellipse=new mG(e)}drawCurve(e){const t=e.curve.tessellate();return this.geometryHelper.drawPolyline(e.curveMesh,t,e.updatable,e.size,e.opacity,e.colours)}drawCurves(e){const t=e.curves.map((e=>e.tessellate()));return this.geometryHelper.drawPolylines(e.curvesMesh,t,e.updatable,e.size,e.opacity,e.colours)}createCurveByKnotsControlPointsWeights(e){return this.context.verb.geom.NurbsCurve.byKnotsControlPointsWeights(e.degree,e.knots,e.points,e.weights)}createCurveByPoints(e){return this.context.verb.geom.NurbsCurve.byPoints(e.points,e.degree)}createBezierCurve(e){return new this.context.verb.geom.BezierCurve(e.points,e.weights)}clone(e){return e.curve.clone()}closestParam(e){return e.curve.closestParam(e.point)}closestParams(e){return e.points.map((t=>e.curve.closestParam(t)))}closestPoint(e){return e.curve.closestPoint(e.point)}closestPoints(e){return e.points.map((t=>e.curve.closestPoint(t)))}controlPoints(e){return e.curve.controlPoints()}degree(e){return e.curve.degree()}derivatives(e){return e.curve.derivatives(e.parameter,e.numDerivatives)}divideByEqualArcLengthToParams(e){return e.curve.divideByEqualArcLength(e.subdivision).map((e=>e.u))}divideByEqualArcLengthToPoints(e){return e.curve.divideByEqualArcLength(e.subdivision).map((t=>e.curve.point(t.u)))}divideByArcLengthToParams(e){return e.curve.divideByArcLength(e.length).map((e=>e.u))}divideByArcLengthToPoints(e){return e.curve.divideByArcLength(e.length).map((t=>e.curve.point(t.u)))}divideCurvesByEqualArcLengthToPoints(e){return e.curves.map((t=>this.divideByEqualArcLengthToPoints({curve:t,subdivision:e.subdivision})))}divideCurvesByArcLengthToPoints(e){return e.curves.map((t=>this.divideByArcLengthToPoints({curve:t,length:e.length})))}domain(e){return e.curve.domain()}startPoint(e){return e.curve.point(e.curve.domain().min)}endPoint(e){return e.curve.point(e.curve.domain().max)}startPoints(e){return e.curves.map((e=>this.startPoint({curve:e})))}endPoints(e){return e.curves.map((e=>this.endPoint({curve:e})))}knots(e){return e.curve.knots()}lengthAtParam(e){return e.curve.lengthAtParam(e.parameter)}length(e){return e.curve.length()}paramAtLength(e){return e.curve.paramAtLength(e.length,e.tolerance)}pointAtParam(e){return e.curve.point(e.parameter)}pointsAtParam(e){return e.curves.map((t=>this.pointAtParam({curve:t,parameter:e.parameter})))}reverse(e){return e.curve.reverse()}split(e){return e.curve.split(e.parameter)}tangent(e){return e.curve.tangent(e.parameter)}tessellate(e){return e.curve.tessellate(e.tolerance)}transform(e){const t=e.curve.controlPoints(),i=this.geometryHelper.transformControlPoints(e.transformation,t);return this.context.verb.geom.NurbsCurve.byKnotsControlPointsWeights(e.curve.degree(),e.curve.knots(),i,e.curve.weights())}transformCurves(e){return e.curves.map((t=>this.transform({curve:t,transformation:e.transformation})))}weights(e){return e.curve.weights()}}class vG{constructor(e){this.context=e}create(e){return new this.context.verb.geom.RevolvedSurface(e.profile,e.center,e.axis,$r.FromDegrees(e.angle).radians())}profile(e){return e.revolution.profile()}center(e){return e.revolution.center()}axis(e){return e.revolution.axis()}angle(e){return $r.FromRadians(e.revolution.angle()).degrees()}}class xG{constructor(e){this.context=e}create(e){return new this.context.verb.geom.ConicalSurface(e.axis,e.xAxis,e.base,e.height,e.radius)}axis(e){return e.cone.axis()}base(e){return e.cone.base()}height(e){return e.cone.height()}radius(e){return e.cone.radius()}xAxis(e){return e.cone.xaxis()}}class bG{constructor(e){this.context=e}create(e){return new this.context.verb.geom.CylindricalSurface(e.axis,e.xAxis,e.base,e.height,e.radius)}axis(e){return e.cylinder.axis()}base(e){return e.cylinder.base()}height(e){return e.cylinder.height()}radius(e){return e.cylinder.radius()}xAxis(e){return e.cylinder.xaxis()}}class TG{constructor(e){this.context=e}create(e){return new this.context.verb.geom.ExtrudedSurface(e.profile,e.direction)}direction(e){return e.extrusion.direction()}profile(e){return e.extrusion.profile()}}class yG{constructor(e){this.context=e}create(e){return new this.context.verb.geom.SphericalSurface(e.center,e.radius)}radius(e){return e.sphere.radius()}center(e){return e.sphere.center()}}class SG{constructor(e){this.context=e}create(e){return new this.context.verb.geom.SweptSurface(e.profile,e.rail)}profile(e){return e.sweep.profile()}rail(e){return e.sweep.rail()}}class CG{constructor(e,t){this.context=e,this.geometryHelper=t,this.cone=new xG(e),this.cylinder=new bG(e),this.extrusion=new TG(e),this.sphere=new yG(e),this.revolved=new vG(e),this.sweep=new SG(e)}drawSurface(e){const t=e.surface.tessellate(),i={positions:[],indices:[],normals:[]};let s=0;t.faces.forEach((e=>{s=this.parseFaces(e,t,i,s)}));const r=new Lx("pbr"+Math.random(),this.context.scene);return r.baseColor=Ee.FromHexString(Array.isArray(e.colours)?e.colours[0]:e.colours),r.metallic=1,r.roughness=.6,r.alpha=e.opacity,r.alphaMode=1,r.backFaceCulling=!1,r.doubleSided=!0,this.geometryHelper.createOrUpdateSurfaceMesh(i,e.surfaceMesh,e.updatable,r,!0,e.hidden)}drawSurfaces(e){const t=[];e.surfaces.forEach((e=>{t.push(e.tessellate())}));const i={positions:[],indices:[],normals:[]};let s=0;t.forEach((e=>{e.faces.forEach((t=>{s=this.parseFaces(t,e,i,s)}))}));const r=new Lx("pbr"+Math.random(),this.context.scene);return r.baseColor=Ee.FromHexString(Array.isArray(e.colours)?e.colours[0]:e.colours),r.metallic=1,r.roughness=.6,r.alpha=e.opacity,r.alphaMode=1,r.backFaceCulling=!0,r.doubleSided=!1,this.geometryHelper.createOrUpdateSurfaceMesh(i,e.surfacesMesh,e.updatable,r,!0,e.hidden)}drawSurfacesMultiColour(e){return e.surfacesMesh&&e.updatable&&e.surfacesMesh.getChildren().forEach((e=>e.dispose())),e.surfacesMesh=new ha(`ColouredSurfaces${Math.random()}`,this.context.scene),Array.isArray(e.colours)?e.surfaces.forEach(((t,i)=>{const s=this.drawSurface({surface:t,colours:e.colours[i]?e.colours[i]:e.colours[0],updatable:e.updatable,opacity:e.opacity,hidden:e.hidden});e.surfacesMesh.addChild(s)})):e.surfaces.forEach(((t,i)=>{const s=this.drawSurface({surface:t,colours:e.colours,updatable:e.updatable,opacity:e.opacity,hidden:e.hidden});e.surfacesMesh.addChild(s)})),e.surfacesMesh}boundaries(e){return e.surface.boundaries()}createSurfaceByCorners(e){return this.context.verb.geom.NurbsSurface.byCorners(e.point1,e.point2,e.point3,e.point4)}createSurfaceByKnotsControlPointsWeights(e){return this.context.verb.geom.NurbsSurface.byKnotsControlPointsWeights(e.degreeU,e.degreeV,e.knotsU,e.knotsV,e.points,e.weights)}createSurfaceByLoftingCurves(e){return this.context.verb.geom.NurbsSurface.byLoftingCurves(e.curves,e.degreeV)}clone(e){return e.surface.clone()}closestParam(e){return e.surface.closestParam(e.point)}closestPoint(e){return e.surface.closestPoint(e.point)}controlPoints(e){return e.surface.controlPoints()}degreeU(e){return e.surface.degreeU()}degreeV(e){return e.surface.degreeV()}derivatives(e){return e.surface.derivatives(e.u,e.v,e.numDerivatives)}domainU(e){return e.surface.domainU()}domainV(e){return e.surface.domainV()}isocurve(e){return e.surface.isocurve(e.parameter,e.useV)}isocurvesSubdivision(e){const t=.999999/e.isocurveSegments,i=this.context.verb.core.Vec.span(1e-7,.9999999,t);return e.includeLast||i.pop(),e.includeFirst||i.shift(),i.map((t=>e.surface.isocurve(t,e.useV)))}isocurvesAtParams(e){return e.parameters.map((t=>e.surface.isocurve(t,e.useV)))}knotsU(e){return e.surface.knotsU()}knotsV(e){return e.surface.knotsV()}normal(e){return e.surface.normal(e.u,e.v)}point(e){return e.surface.point(e.u,e.v)}reverse(e){return e.surface.reverse()}split(e){return e.surface.split(e.parameter,e.useV)}transformSurface(e){const t=e.surface.controlPoints(),i=e.transformation,s=[];return t.forEach((e=>{let t=e;t=this.geometryHelper.transformControlPoints(i,t),s.push(t)})),this.context.verb.geom.NurbsSurface.byKnotsControlPointsWeights(e.surface.degreeU(),e.surface.degreeV(),e.surface.knotsU(),e.surface.knotsV(),s,e.surface.weights())}weights(e){return e.surface.weights()}parseFaces(e,t,i,s){return e.reverse().forEach((e=>{const r=t.normals[e];i.normals.push(r[0],r[1],r[2]);const n=t.points[e];i.positions.push(n[0],n[1],n[2]),i.indices.push(s),s++})),s}}class EG{constructor(e,t){this.context=e,this.geometryHelper=t}curves(e){return this.context.verb.geom.Intersect.curves(e.firstCurve,e.secondCurve,e.tolerance)}curveAndSurface(e){return this.context.verb.geom.Intersect.curveAndSurface(e.curve,e.surface,e.tolerance)}surfaces(e){return this.context.verb.geom.Intersect.surfaces(e.firstSurface,e.secondSurface)}curveCurveFirstParams(e){return e.intersections.filter((e=>e.u0>=0&&e.u0<=1)).map((e=>e.u0))}curveCurveSecondParams(e){return e.intersections.filter((e=>e.u1>=0&&e.u1<=1)).map((e=>e.u1))}curveCurveFirstPoints(e){return e.intersections.filter((e=>e.u0>=0&&e.u0<=1)).map((e=>e.point0))}curveCurveSecondPoints(e){return e.intersections.filter((e=>e.u1>=0&&e.u1<=1)).map((e=>e.point1))}curveSurfaceCurveParams(e){return e.intersections.filter((e=>e.u>=0&&e.u<=1)).map((e=>e.u))}curveSurfaceSurfaceParams(e){return e.intersections.map((e=>e.uv))}curveSurfaceCurvePoints(e){return e.intersections.filter((e=>e.u>=0&&e.u<=1)).map((e=>e.curvePoint))}curveSurfaceSurfacePoints(e){return e.intersections.map((e=>e.surfacePoint))}}class AG{constructor(e,t){this.curve=new gG(e,t),this.surface=new CG(e,t),this.intersect=new EG(e,t)}}!function(e){e.IntervalDto=class{constructor(){this.min=0,this.max=1}},e.UVDto=class{constructor(){this.u=0,this.v=0}},e.CurveCurveIntersection=class{},e.CurveSurfaceIntersection=class{},e.SurfaceSurfaceIntersectionPoint=class{}}(dG||(dG={}));Bi.ShadersStore.cellPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nvec3 computeCustomDiffuseLighting(lightingInfo info,vec3 diffuseBase,float shadow)\n{diffuseBase=info.diffuse*shadow;\n#ifdef CELLBASIC\nfloat level=1.0;if (info.ndl<0.5)\nlevel=0.5;diffuseBase.rgb*vec3(level,level,level);\n#else\nfloat ToonThresholds[4];ToonThresholds[0]=0.95;ToonThresholds[1]=0.5;ToonThresholds[2]=0.2;ToonThresholds[3]=0.03;float ToonBrightnessLevels[5];ToonBrightnessLevels[0]=1.0;ToonBrightnessLevels[1]=0.8;ToonBrightnessLevels[2]=0.6;ToonBrightnessLevels[3]=0.35;ToonBrightnessLevels[4]=0.2;if (info.ndl>ToonThresholds[0])\n{diffuseBase.rgb*=ToonBrightnessLevels[0];}\nelse if (info.ndl>ToonThresholds[1])\n{diffuseBase.rgb*=ToonBrightnessLevels[1];}\nelse if (info.ndl>ToonThresholds[2])\n{diffuseBase.rgb*=ToonBrightnessLevels[2];}\nelse if (info.ndl>ToonThresholds[3])\n{diffuseBase.rgb*=ToonBrightnessLevels[3];}\nelse\n{diffuseBase.rgb*=ToonBrightnessLevels[4];}\n#endif\nreturn max(diffuseBase,vec3(0.2));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nlightingInfo info;vec3 diffuseBase=vec3(0.,0.,0.);float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.cellVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class PG extends xl{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.NDOTL=!0,this.CUSTOMUSERLIGHTING=!0,this.CELLBASIC=!0,this.DEPTHPREPASS=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class IG extends ml{constructor(e,t){super(e,t),this.diffuseColor=new Ee(1,1,1),this._computeHighLevel=!1,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new PG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&$c.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(r.CELLBASIC=!this.computeHighLevel,Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=zo(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),Ho(n,o,this,r,!!i),jo(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),Vo(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="cell",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights-1}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&$c.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),xo(this._activeEffect,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this._maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}getClassName(){return"CellMaterial"}clone(e){return St.Clone((()=>new IG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.CellMaterial",e}static Parse(e,t,i){return St.Parse((()=>new IG(e.name,t)),e,t,i)}}Ze([nt("diffuseTexture")],IG.prototype,"_diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],IG.prototype,"diffuseTexture",void 0),Ze([ot("diffuse")],IG.prototype,"diffuseColor",void 0),Ze([rt("computeHighLevel")],IG.prototype,"_computeHighLevel",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],IG.prototype,"computeHighLevel",void 0),Ze([rt("disableLighting")],IG.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],IG.prototype,"disableLighting",void 0),Ze([rt("maxSimultaneousLights")],IG.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],IG.prototype,"maxSimultaneousLights",void 0),z("BABYLON.CellMaterial",IG);class RG{constructor(){}}class MG extends cu{AttachAfterBind(e,t){if(this._newUniformInstances)for(const e in this._newUniformInstances){const i=e.toString().split("-");"vec2"==i[0]?t.setVector2(i[1],this._newUniformInstances[e]):"vec3"==i[0]?this._newUniformInstances[e]instanceof Ee?t.setColor3(i[1],this._newUniformInstances[e]):t.setVector3(i[1],this._newUniformInstances[e]):"vec4"==i[0]?(this._newUniformInstances[e]instanceof Ae?t.setDirectColor4(i[1],this._newUniformInstances[e]):t.setVector4(i[1],this._newUniformInstances[e]),t.setVector4(i[1],this._newUniformInstances[e])):"mat4"==i[0]?t.setMatrix(i[1],this._newUniformInstances[e]):"float"==i[0]&&t.setFloat(i[1],this._newUniformInstances[e])}if(this._newSamplerInstances)for(const e in this._newSamplerInstances){const i=e.toString().split("-");"sampler2D"==i[0]&&this._newSamplerInstances[e].isReady&&this._newSamplerInstances[e].isReady()&&t.setTexture(i[1],this._newSamplerInstances[e])}}ReviewUniform(e,t){if("uniform"==e&&this._newUniforms)for(let e=0;e0&&n.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",s);const o=this._createdShaderName;return $i.ShadersStore[o+"VertexShader"]&&$i.ShadersStore[o+"PixelShader"]||($i.ShadersStore[o+"VertexShader"]=this._injectCustomCode(this.VertexShader,"vertex"),$i.ShadersStore[o+"PixelShader"]=this._injectCustomCode(this.FragmentShader,"fragment")),o}_injectCustomCode(e,t){const i=this._getCustomCode(t);for(const t in i){const s=i[t];if(s&&s.length>0){const i="#define "+t;e=e.replace(i,"\n"+s+"\n"+i)}}return e}_getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_BEGIN:this.CustomParts.Vertex_Begin,CUSTOM_VERTEX_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Vertex_Definitions||""),CUSTOM_VERTEX_MAIN_BEGIN:this.CustomParts.Vertex_MainBegin,CUSTOM_VERTEX_UPDATE_POSITION:this.CustomParts.Vertex_Before_PositionUpdated,CUSTOM_VERTEX_UPDATE_NORMAL:this.CustomParts.Vertex_Before_NormalUpdated,CUSTOM_VERTEX_MAIN_END:this.CustomParts.Vertex_MainEnd,CUSTOM_VERTEX_UPDATE_WORLDPOS:this.CustomParts.Vertex_After_WorldPosComputed}:{CUSTOM_FRAGMENT_BEGIN:this.CustomParts.Fragment_Begin,CUSTOM_FRAGMENT_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Fragment_Definitions||""),CUSTOM_FRAGMENT_MAIN_BEGIN:this.CustomParts.Fragment_MainBegin,CUSTOM_FRAGMENT_UPDATE_DIFFUSE:this.CustomParts.Fragment_Custom_Diffuse,CUSTOM_FRAGMENT_UPDATE_ALPHA:this.CustomParts.Fragment_Custom_Alpha,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.CustomParts.Fragment_Before_Lights,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:this.CustomParts.Fragment_Before_FragColor,CUSTOM_FRAGMENT_MAIN_END:this.CustomParts.Fragment_MainEnd,CUSTOM_FRAGMENT_BEFORE_FOG:this.CustomParts.Fragment_Before_Fog}}constructor(e,t){super(e,t),this.CustomParts=new RG,this.customShaderNameResolve=this.Builder,this.FragmentShader=$i.ShadersStore.defaultPixelShader,this.VertexShader=$i.ShadersStore.defaultVertexShader,MG.ShaderIndexer++,this._createdShaderName="custom_"+MG.ShaderIndexer}_afterBind(e,t=null,i){if(t){this.AttachAfterBind(e,t);try{super._afterBind(e,t,i)}catch(e){}}}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(-1!=t.indexOf("sampler")?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Fragment_Custom_Diffuse(e){return this.CustomParts.Fragment_Custom_Diffuse=e.replace("result","diffuseColor"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}MG.ShaderIndexer=1,z("BABYLON.CustomMaterial",MG);class OG{constructor(){}}class DG extends zg{AttachAfterBind(e,t){if(this._newUniformInstances)for(const e in this._newUniformInstances){const i=e.toString().split("-");"vec2"==i[0]?t.setVector2(i[1],this._newUniformInstances[e]):"vec3"==i[0]?this._newUniformInstances[e]instanceof Ee?t.setColor3(i[1],this._newUniformInstances[e]):t.setVector3(i[1],this._newUniformInstances[e]):"vec4"==i[0]?(this._newUniformInstances[e]instanceof Ae?t.setDirectColor4(i[1],this._newUniformInstances[e]):t.setVector4(i[1],this._newUniformInstances[e]),t.setVector4(i[1],this._newUniformInstances[e])):"mat4"==i[0]?t.setMatrix(i[1],this._newUniformInstances[e]):"float"==i[0]&&t.setFloat(i[1],this._newUniformInstances[e])}if(this._newSamplerInstances)for(const e in this._newSamplerInstances){const i=e.toString().split("-");"sampler2D"==i[0]&&this._newSamplerInstances[e].isReady&&this._newSamplerInstances[e].isReady()&&t.setTexture(i[1],this._newSamplerInstances[e])}}ReviewUniform(e,t){if("uniform"==e&&this._newUniforms)for(let e=0;e{if("vertex"===t)return e?e(t,i):i;const s=new Bp(i);return s.inlineToken="#define pbr_inline",s.processCode(),e?e(t,s.code):s.code}}n&&this._customAttributes&&this._customAttributes.length>0&&n.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",s);const a=this._createdShaderName;return $i.ShadersStore[a+"VertexShader"]&&$i.ShadersStore[a+"PixelShader"]||($i.ShadersStore[a+"VertexShader"]=this._injectCustomCode(this.VertexShader,"vertex"),$i.ShadersStore[a+"PixelShader"]=this._injectCustomCode(this.FragmentShader,"fragment")),a}_injectCustomCode(e,t){const i=this._getCustomCode(t);for(const t in i){const s=i[t];if(s&&s.length>0){const i="#define "+t;e=e.replace(i,"\n"+s+"\n"+i)}}return e}_getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_BEGIN:this.CustomParts.Vertex_Begin,CUSTOM_VERTEX_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Vertex_Definitions||""),CUSTOM_VERTEX_MAIN_BEGIN:this.CustomParts.Vertex_MainBegin,CUSTOM_VERTEX_UPDATE_POSITION:this.CustomParts.Vertex_Before_PositionUpdated,CUSTOM_VERTEX_UPDATE_NORMAL:this.CustomParts.Vertex_Before_NormalUpdated,CUSTOM_VERTEX_MAIN_END:this.CustomParts.Vertex_MainEnd,CUSTOM_VERTEX_UPDATE_WORLDPOS:this.CustomParts.Vertex_After_WorldPosComputed}:{CUSTOM_FRAGMENT_BEGIN:this.CustomParts.Fragment_Begin,CUSTOM_FRAGMENT_MAIN_BEGIN:this.CustomParts.Fragment_MainBegin,CUSTOM_FRAGMENT_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Fragment_Definitions||""),CUSTOM_FRAGMENT_UPDATE_ALBEDO:this.CustomParts.Fragment_Custom_Albedo,CUSTOM_FRAGMENT_UPDATE_ALPHA:this.CustomParts.Fragment_Custom_Alpha,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.CustomParts.Fragment_Before_Lights,CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS:this.CustomParts.Fragment_Custom_MetallicRoughness,CUSTOM_FRAGMENT_UPDATE_MICROSURFACE:this.CustomParts.Fragment_Custom_MicroSurface,CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:this.CustomParts.Fragment_Before_FinalColorComposition,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:this.CustomParts.Fragment_Before_FragColor,CUSTOM_FRAGMENT_MAIN_END:this.CustomParts.Fragment_MainEnd,CUSTOM_FRAGMENT_BEFORE_FOG:this.CustomParts.Fragment_Before_Fog}}constructor(e,t){super(e,t),this.CustomParts=new OG,this.customShaderNameResolve=this.Builder,this.FragmentShader=$i.ShadersStore.pbrPixelShader,this.VertexShader=$i.ShadersStore.pbrVertexShader,this.FragmentShader=this.FragmentShader.replace(/#include/g,$i.IncludesShadersStore.pbrBlockAlbedoOpacity),this.FragmentShader=this.FragmentShader.replace(/#include/g,$i.IncludesShadersStore.pbrBlockReflectivity),this.FragmentShader=this.FragmentShader.replace(/#include/g,$i.IncludesShadersStore.pbrBlockFinalColorComposition),DG.ShaderIndexer++,this._createdShaderName="custompbr_"+DG.ShaderIndexer}_afterBind(e,t=null,i){if(t){this.AttachAfterBind(e,t);try{super._afterBind(e,t,i)}catch(e){}}}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(-1!=t.indexOf("sampler")?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_Custom_Albedo(e){return this.CustomParts.Fragment_Custom_Albedo=e.replace("result","surfaceAlbedo"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Custom_MetallicRoughness(e){return this.CustomParts.Fragment_Custom_MetallicRoughness=e,this}Fragment_Custom_MicroSurface(e){return this.CustomParts.Fragment_Custom_MicroSurface=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FinalColorComposition(e){return this.CustomParts.Fragment_Before_FinalColorComposition=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}DG.ShaderIndexer=1,z("BABYLON.PBRCustomMaterial",DG);Bi.ShadersStore.firePixelShader="precision highp float;uniform vec4 vEyePosition;varying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\nuniform sampler2D distortionSampler;uniform sampler2D opacitySampler;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nvec4 bx2(vec4 x)\n{return vec4(2.0)*x-vec4(1.0);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);float alpha=1.0;\n#ifdef DIFFUSE\nconst float distortionAmount0 =0.092;const float distortionAmount1 =0.092;const float distortionAmount2 =0.092;vec2 heightAttenuation=vec2(0.3,0.39);vec4 noise0=texture2D(distortionSampler,vDistortionCoords1);vec4 noise1=texture2D(distortionSampler,vDistortionCoords2);vec4 noise2=texture2D(distortionSampler,vDistortionCoords3);vec4 noiseSum=bx2(noise0)*distortionAmount0+bx2(noise1)*distortionAmount1+bx2(noise2)*distortionAmount2;vec4 perturbedBaseCoords=vec4(vDiffuseUV,0.0,1.0)+noiseSum*(vDiffuseUV.y*heightAttenuation.x+heightAttenuation.y);vec4 opacityColor=texture2D(opacitySampler,perturbedBaseCoords.xy);\n#ifdef ALPHATEST\nif (opacityColor.r<0.1)\ndiscard;\n#endif\n#include\nbaseColor=texture2D(diffuseSampler,perturbedBaseCoords.xy)*2.0;baseColor*=opacityColor;baseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(1.0,1.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec4 color=vec4(baseColor.rgb,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.fireVertexShader="precision highp float;attribute vec3 position;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\nuniform float time;uniform float speed;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef DIFFUSE\nvDiffuseUV=uv;vDiffuseUV.y-=0.2;\n#endif\n#include\n#include\n#include\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#ifdef DIFFUSE\nvec3 layerSpeed=vec3(-0.2,-0.52,-0.1)*speed;vDistortionCoords1.x=uv.x;vDistortionCoords1.y=uv.y+layerSpeed.x*time/1000.0;vDistortionCoords2.x=uv.x;vDistortionCoords2.y=uv.y+layerSpeed.y*time/1000.0;vDistortionCoords3.x=uv.x;vDistortionCoords3.y=uv.y+layerSpeed.z*time/1000.0;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class wG extends xl{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.UV1=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.BonesPerMesh=0,this.NUM_BONE_INFLUENCERS=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class NG extends ml{constructor(e,t){super(e,t),this.diffuseColor=new Ee(1,1,1),this.speed=1,this._scaledDiffuse=new Ee,this._lastTime=0}needAlphaBlending(){return!1}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new wG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,this._diffuseTexture&&$c.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(r.ALPHATEST=!!this._opacityTexture,r._areMiscDirty&&(r.POINTSIZE=this.pointsCloud||n.forcePointsCloud,r.FOG=n.fogEnabled&&e.applyFog&&n.fogMode!==Hr.FOGMODE_NONE&&this.fogEnabled,r.LOGARITHMICDEPTH=this._useLogarithmicDepth),Ho(n,o,this,r,!!i),jo(e,r,!1,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.UV1&&s.push(er.UVKind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="fire",l=["world","view","viewProjection","vEyePosition","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","time","speed"];mo(l);const h=r.toString();t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:l,uniformBuffersNames:[],samplers:["diffuseSampler","distortionSampler","opacitySampler"],defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:null,maxSimultaneousLights:4,transformFeedbackVaryings:null},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&$c.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix()),this._activeEffect.setTexture("distortionSampler",this._distortionTexture),this._activeEffect.setTexture("opacitySampler",this._opacityTexture)),xo(this._activeEffect,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._lastTime+=s.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime),this._activeEffect.setFloat("speed",this.speed),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._distortionTexture&&this._distortionTexture.animations&&this._distortionTexture.animations.length>0&&e.push(this._distortionTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._distortionTexture&&e.push(this._distortionTexture),this._opacityTexture&&e.push(this._opacityTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._distortionTexture===e||this._opacityTexture===e}getClassName(){return"FireMaterial"}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),this._distortionTexture&&this._distortionTexture.dispose(),super.dispose(e)}clone(e){return St.Clone((()=>new NG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FireMaterial",e.diffuseColor=this.diffuseColor.asArray(),e.speed=this.speed,this._diffuseTexture&&(e._diffuseTexture=this._diffuseTexture.serialize()),this._distortionTexture&&(e._distortionTexture=this._distortionTexture.serialize()),this._opacityTexture&&(e._opacityTexture=this._opacityTexture.serialize()),e}static Parse(e,t,i){const s=new NG(e.name,t);return s.diffuseColor=Ee.FromArray(e.diffuseColor),s.speed=e.speed,s.alpha=e.alpha,s.id=e.id,Tt.AddTagsTo(s,e.tags),s.backFaceCulling=e.backFaceCulling,s.wireframe=e.wireframe,e._diffuseTexture&&(s._diffuseTexture=Pa.Parse(e._diffuseTexture,t,i)),e._distortionTexture&&(s._distortionTexture=Pa.Parse(e._distortionTexture,t,i)),e._opacityTexture&&(s._opacityTexture=Pa.Parse(e._opacityTexture,t,i)),s}}Ze([nt("diffuseTexture")],NG.prototype,"_diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],NG.prototype,"diffuseTexture",void 0),Ze([nt("distortionTexture")],NG.prototype,"_distortionTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],NG.prototype,"distortionTexture",void 0),Ze([nt("opacityTexture")],NG.prototype,"_opacityTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],NG.prototype,"opacityTexture",void 0),Ze([ot("diffuse")],NG.prototype,"diffuseColor",void 0),Ze([rt()],NG.prototype,"speed",void 0),z("BABYLON.FireMaterial",NG);Bi.ShadersStore.furPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 furColor;uniform float furLength;varying vec3 vPositionW;varying float vfur_length;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef HIGHLEVEL\nuniform float furOffset;uniform float furOcclusion;uniform sampler2D furTexture;varying vec2 vFurUV;\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#include\n#include\nfloat Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=furColor;vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor*=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef HIGHLEVEL\nvec4 furTextureColor=texture2D(furTexture,vec2(vFurUV.x,vFurUV.y));if (furTextureColor.a<=0.0 || furTextureColor.g[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase.rgb*baseColor.rgb,0.0,1.0);\n#ifdef HIGHLEVEL\nvec4 color=vec4(finalDiffuse,alpha);\n#else\nfloat r=vfur_length/furLength*0.5;vec4 color=vec4(finalDiffuse*(0.5+r),alpha);\n#endif\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.furVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\nuniform float furLength;uniform float furAngle;\n#ifdef HIGHLEVEL\nuniform float furOffset;uniform vec3 furGravity;uniform float furTime;uniform float furSpacing;uniform float furDensity;\n#endif\n#ifdef HEIGHTMAP\nuniform sampler2D heightTexture;\n#endif\n#ifdef HIGHLEVEL\nvarying vec2 vFurUV;\n#endif\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\nvarying float vfur_length;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nfloat Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);}\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nfloat r=Rand(position);\n#ifdef HEIGHTMAP\n#if __VERSION__>100\nvfur_length=furLength*texture(heightTexture,uv).x;\n#else\nvfur_length=furLength*texture2D(heightTexture,uv).r;\n#endif\n#else \nvfur_length=(furLength*r);\n#endif\nvec3 tangent1=vec3(normal.y,-normal.x,0);vec3 tangent2=vec3(-normal.z,0,normal.x);r=Rand(tangent1*r);float J=(2.0+4.0*r);r=Rand(tangent2*r);float K=(2.0+2.0*r);tangent1=tangent1*J+tangent2*K;tangent1=normalize(tangent1);vec3 newPosition=position+normal*vfur_length*cos(furAngle)+tangent1*vfur_length*sin(furAngle);\n#ifdef HIGHLEVEL\nvec3 forceDirection=vec3(0.0,0.0,0.0);forceDirection.x=sin(furTime+position.x*0.05)*0.2;forceDirection.y=cos(furTime*0.7+position.y*0.04)*0.2;forceDirection.z=sin(furTime*0.7+position.z*0.04)*0.2;vec3 displacement=vec3(0.0,0.0,0.0);displacement=furGravity+forceDirection;float displacementFactor=pow(furOffset,3.0);vec3 aNormal=normal;aNormal.xyz+=displacement*displacementFactor;newPosition=vec3(newPosition.x,newPosition.y,newPosition.z)+(normalize(aNormal)*furOffset*furSpacing);\n#endif\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\ngl_Position=viewProjection*finalWorld*vec4(newPosition,1.0);vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos);\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#ifdef HIGHLEVEL\nvFurUV=vDiffuseUV*furDensity;\n#endif\n#else\n#ifdef HIGHLEVEL\nvFurUV=uv*furDensity;\n#endif\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class FG extends xl{constructor(){super(),this.DIFFUSE=!1,this.HEIGHTMAP=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.HIGHLEVEL=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class LG extends ml{constructor(e,t){super(e,t),this.diffuseColor=new Ee(1,1,1),this.furLength=1,this.furAngle=0,this.furColor=new Ee(.44,.21,.02),this.furOffset=0,this.furSpacing=12,this.furGravity=new _e(0,0,0),this.furSpeed=100,this.furDensity=20,this.furOcclusion=0,this._disableLighting=!1,this._maxSimultaneousLights=4,this.highLevelFur=!0,this._furTime=0}get furTime(){return this._furTime}set furTime(e){this._furTime=e}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}updateFur(){for(let e=1;e0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="fur",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","furLength","furAngle","furColor","furOffset","furGravity","furTime","furSpacing","furDensity","furOcclusion"];mo(h);const c=["diffuseSampler","heightTexture","furTexture"],u=[];ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&$c.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),this._heightTexture&&this._activeEffect.setTexture("heightTexture",this._heightTexture),xo(this._activeEffect,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._activeEffect.setFloat("furLength",this.furLength),this._activeEffect.setFloat("furAngle",this.furAngle),this._activeEffect.setColor4("furColor",this.furColor,1),this.highLevelFur&&(this._activeEffect.setVector3("furGravity",this.furGravity),this._activeEffect.setFloat("furOffset",this.furOffset),this._activeEffect.setFloat("furSpacing",this.furSpacing),this._activeEffect.setFloat("furDensity",this.furDensity),this._activeEffect.setFloat("furOcclusion",this.furOcclusion),this._furTime+=this.getScene().getEngine().getDeltaTime()/this.furSpeed,this._activeEffect.setFloat("furTime",this._furTime),this._activeEffect.setTexture("furTexture",this.furTexture)),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.heightTexture&&this.heightTexture.animations&&this.heightTexture.animations.length>0&&e.push(this.heightTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._heightTexture&&e.push(this._heightTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e||this._heightTexture===e}dispose(e){if(this.diffuseTexture&&this.diffuseTexture.dispose(),this._meshes)for(let t=1;tnew LG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FurMaterial",this._meshes&&(e.sourceMeshName=this._meshes[0].name,e.quality=this._meshes.length),e}getClassName(){return"FurMaterial"}static Parse(e,t,i){const s=St.Parse((()=>new LG(e.name,t)),e,t,i);return e.sourceMeshName&&s.highLevelFur&&t.executeWhenReady((()=>{const i=t.getMeshByName(e.sourceMeshName);if(i){const r=LG.GenerateTexture("Fur Texture",t);s.furTexture=r,LG.FurifyMesh(i,e.quality)}})),s}static GenerateTexture(e,t){const i=new uu("FurTexture "+e,256,t,!0),s=i.getContext();for(let e=0;e<2e4;++e)s.fillStyle="rgba(255, "+Math.floor(255*Math.random())+", "+Math.floor(255*Math.random())+", 1)",s.fillRect(Math.random()*i.getSize().width,Math.random()*i.getSize().height,2,2);return i.update(!1),i.wrapU=Pa.WRAP_ADDRESSMODE,i.wrapV=Pa.WRAP_ADDRESSMODE,i}static FurifyMesh(e,t){const i=[e],s=e.material;let r;if(!(s instanceof LG))throw"The material of the source mesh must be a Fur Material";for(r=1;r0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="gradient",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","logarithmicDepthConstant","topColor","bottomColor","offset","smoothness","scale"];mo(h);const c=[],u=[];ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:4}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,n),this._mustRebind(s,n,i)&&(xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._activeEffect.setColor4("topColor",this.topColor,this.topColorAlpha),this._activeEffect.setColor4("bottomColor",this.bottomColor,this.bottomColorAlpha),this._activeEffect.setFloat("offset",this.offset),this._activeEffect.setFloat("scale",this.scale),this._activeEffect.setFloat("smoothness",this.smoothness),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new kG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GradientMaterial",e}getClassName(){return"GradientMaterial"}static Parse(e,t,i){return St.Parse((()=>new kG(e.name,t)),e,t,i)}}Ze([rt("maxSimultaneousLights")],kG.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],kG.prototype,"maxSimultaneousLights",void 0),Ze([ot()],kG.prototype,"topColor",void 0),Ze([rt()],kG.prototype,"topColorAlpha",void 0),Ze([ot()],kG.prototype,"bottomColor",void 0),Ze([rt()],kG.prototype,"bottomColorAlpha",void 0),Ze([rt()],kG.prototype,"offset",void 0),Ze([rt()],kG.prototype,"scale",void 0),Ze([rt()],kG.prototype,"smoothness",void 0),Ze([rt("disableLighting")],kG.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],kG.prototype,"disableLighting",void 0),z("BABYLON.GradientMaterial",kG);Bi.ShadersStore.gridPixelShader="#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;uniform float visibility;uniform vec3 mainColor;uniform vec3 lineColor;uniform vec4 gridControl;uniform vec3 gridOffset;varying vec3 vPosition;varying vec3 vNormal;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#ifdef OPACITY\nvarying vec2 vOpacityUV;uniform sampler2D opacitySampler;uniform vec2 vOpacityInfos;\n#endif\nfloat getDynamicVisibility(float position) {float majorGridFrequency=gridControl.y;if (floor(position+0.5)==floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{return 1.0;}\nreturn gridControl.z;}\nfloat getAnisotropicAttenuation(float differentialLength) {const float maxNumberOfLines=10.0;return clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);}\nfloat isPointOnLine(float position,float differentialLength) {float fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \n#ifdef ANTIALIAS\nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);float result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result;\n#else\nreturn abs(fractionPartOfPosition)\n#endif\nfloat opacity=1.0;\n#ifdef TRANSPARENT\nopacity=clamp(grid,0.08,gridControl.w*grid);\n#endif\n#ifdef OPACITY\nopacity*=texture2D(opacitySampler,vOpacityUV).a;\n#endif\ngl_FragColor=vec4(color.rgb,opacity*visibility);\n#ifdef TRANSPARENT\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Bi.ShadersStore.gridVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#include\nuniform mat4 projection;uniform mat4 view;varying vec3 vPosition;varying vec3 vNormal;\n#include\n#include\n#ifdef OPACITY\nvarying vec2 vOpacityUV;uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\nvec4 cameraSpacePosition=view*worldPos;gl_Position=projection*cameraSpacePosition;\n#ifdef OPACITY\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\nif (vOpacityInfos.x==0.)\n{vOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));}\nelse\n{vOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));}\n#endif \n#include\nvPosition=position;vNormal=normal;\n#define CUSTOM_VERTEX_MAIN_END\n}";class VG extends xl{constructor(){super(),this.OPACITY=!1,this.ANTIALIAS=!1,this.TRANSPARENT=!1,this.FOG=!1,this.PREMULTIPLYALPHA=!1,this.MAX_LINE=!1,this.UV1=!1,this.UV2=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class UG extends ml{constructor(e,t){super(e,t),this.mainColor=Ee.Black(),this.lineColor=Ee.Teal(),this.gridRatio=1,this.gridOffset=_e.Zero(),this.majorUnitFrequency=10,this.minorUnitVisibility=.33,this.opacity=1,this.antialias=!0,this.preMultiplyAlpha=!1,this.useMaxLine=!1,this._gridControl=new pe(this.gridRatio,this.majorUnitFrequency,this.minorUnitVisibility,this.opacity)}needAlphaBlending(){return this.opacity<1||this._opacityTexture&&this._opacityTexture.isReady()}needAlphaBlendingForMesh(e){return e.visibility<1||this.needAlphaBlending()}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new VG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;if(r.TRANSPARENT!==this.opacity<1&&(r.TRANSPARENT=!r.TRANSPARENT,r.markAsUnprocessed()),r.PREMULTIPLYALPHA!=this.preMultiplyAlpha&&(r.PREMULTIPLYALPHA=!r.PREMULTIPLYALPHA,r.markAsUnprocessed()),r.MAX_LINE!==this.useMaxLine&&(r.MAX_LINE=!r.MAX_LINE,r.markAsUnprocessed()),r.ANTIALIAS!==this.antialias&&(r.ANTIALIAS=!r.ANTIALIAS,r.markAsUnprocessed()),r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._opacityTexture&&$c.OpacityTextureEnabled)){if(!this._opacityTexture.isReady())return!1;r._needUVs=!0,r.OPACITY=!0}if(Go(e,n,this._useLogarithmicDepth,!1,this.fogEnabled,!1,r),Ho(n,n.getEngine(),this,r,!!i),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial(),jo(e,r,!1,!1);const i=[er.PositionKind,er.NormalKind];r.UV1&&i.push(er.UVKind),r.UV2&&i.push(er.UV2Kind),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess,ko(i,r);const s=r.toString();t.setEffect(n.getEngine().createEffect("grid",i,["projection","mainColor","lineColor","gridControl","gridOffset","vFogInfos","vFogColor","world","view","opacityMatrix","vOpacityInfos","visibility","logarithmicDepthConstant"],["opacitySampler"],s,void 0,this.onCompiled,this.onError),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this._activeEffect.setFloat("visibility",t.visibility),r.INSTANCES&&!r.THIN_INSTANCE||this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("view",s.getViewMatrix()),this._activeEffect.setMatrix("projection",s.getProjectionMatrix()),this._mustRebind(s,n,i)&&(this._activeEffect.setColor3("mainColor",this.mainColor),this._activeEffect.setColor3("lineColor",this.lineColor),this._activeEffect.setVector3("gridOffset",this.gridOffset),this._gridControl.x=this.gridRatio,this._gridControl.y=Math.round(this.majorUnitFrequency),this._gridControl.z=this.minorUnitVisibility,this._gridControl.w=this.opacity,this._activeEffect.setVector4("gridControl",this._gridControl),this._opacityTexture&&$c.OpacityTextureEnabled&&(this._activeEffect.setTexture("opacitySampler",this._opacityTexture),this._activeEffect.setFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),this._activeEffect.setMatrix("opacityMatrix",this._opacityTexture.getTextureMatrix())),this._useLogarithmicDepth&&So(r,n,s)),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new UG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GridMaterial",e}getClassName(){return"GridMaterial"}static Parse(e,t,i){return St.Parse((()=>new UG(e.name,t)),e,t,i)}}Ze([ot()],UG.prototype,"mainColor",void 0),Ze([ot()],UG.prototype,"lineColor",void 0),Ze([rt()],UG.prototype,"gridRatio",void 0),Ze([ht()],UG.prototype,"gridOffset",void 0),Ze([rt()],UG.prototype,"majorUnitFrequency",void 0),Ze([rt()],UG.prototype,"minorUnitVisibility",void 0),Ze([rt()],UG.prototype,"opacity",void 0),Ze([rt()],UG.prototype,"antialias",void 0),Ze([rt()],UG.prototype,"preMultiplyAlpha",void 0),Ze([rt()],UG.prototype,"useMaxLine",void 0),Ze([nt("opacityTexture")],UG.prototype,"_opacityTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],UG.prototype,"opacityTexture",void 0),z("BABYLON.GridMaterial",UG);Bi.ShadersStore.lavaPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;uniform float time;uniform float speed;uniform float movingSpeed;uniform vec3 fogColor;uniform sampler2D noiseTexture;uniform float fogDensity;varying float noise;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nfloat random( vec3 scale,float seed ){return fract( sin( dot( gl_FragCoord.xyz+seed,scale ) )*43758.5453+seed ) ;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nvec4 noiseTex=texture2D( noiseTexture,vDiffuseUV );vec2 T1=vDiffuseUV+vec2( 1.5,-1.5 )*time *0.02;vec2 T2=vDiffuseUV+vec2( -0.5,2.0 )*time*0.01*speed;T1.x+=noiseTex.x*2.0;T1.y+=noiseTex.y*2.0;T2.x-=noiseTex.y*0.2+time*0.001*movingSpeed;T2.y+=noiseTex.z*0.2+time*0.002*movingSpeed;float p=texture2D( noiseTexture,T1*3.0 ).a;vec4 lavaColor=texture2D( diffuseSampler,T2*4.0);vec4 temp=lavaColor*( vec4( p,p,p,p )*2. )+( lavaColor*lavaColor-0.1 );baseColor=temp;float depth=gl_FragCoord.z*4.0;const float LOG2=1.442695;float fogFactor=exp2(-fogDensity*fogDensity*depth*depth*LOG2 );fogFactor=1.0-clamp( fogFactor,0.0,1.0 );baseColor=mix( baseColor,vec4( fogColor,baseColor.w ),fogFactor );diffuseColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0]\n#include[1]\n#include[2]\n#include[3]\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.lavaVertexShader="precision highp float;uniform float time;uniform float lowFrequencySpeed;varying float noise;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n/* NOISE FUNCTIONS */\nvec3 mod289(vec3 x)\n{return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x)\n{return x-floor(x*(1.0/289.0))*289.0;}\nvec4 permute(vec4 x)\n{return mod289(((x*34.0)+1.0)*x);}\nvec4 taylorInvSqrt(vec4 r)\n{return 1.79284291400159-0.85373472095314*r;}\nvec3 fade(vec3 t) {return t*t*t*(t*(t*6.0-15.0)+10.0);}\nfloat pnoise(vec3 P,vec3 rep)\n{vec3 Pi0=mod(floor(P),rep); \nvec3 Pi1=mod(Pi0+vec3(1.0),rep); \nPi0=mod289(Pi0);Pi1=mod289(Pi1);vec3 Pf0=fract(P); \nvec3 Pf1=Pf0-vec3(1.0); \nvec4 ix=vec4(Pi0.x,Pi1.x,Pi0.x,Pi1.x);vec4 iy=vec4(Pi0.yy,Pi1.yy);vec4 iz0=Pi0.zzzz;vec4 iz1=Pi1.zzzz;vec4 ixy=permute(permute(ix)+iy);vec4 ixy0=permute(ixy+iz0);vec4 ixy1=permute(ixy+iz1);vec4 gx0=ixy0*(1.0/7.0);vec4 gy0=fract(floor(gx0)*(1.0/7.0))-0.5;gx0=fract(gx0);vec4 gz0=vec4(0.5)-abs(gx0)-abs(gy0);vec4 sz0=step(gz0,vec4(0.0));gx0-=sz0*(step(0.0,gx0)-0.5);gy0-=sz0*(step(0.0,gy0)-0.5);vec4 gx1=ixy1*(1.0/7.0);vec4 gy1=fract(floor(gx1)*(1.0/7.0))-0.5;gx1=fract(gx1);vec4 gz1=vec4(0.5)-abs(gx1)-abs(gy1);vec4 sz1=step(gz1,vec4(0.0));gx1-=sz1*(step(0.0,gx1)-0.5);gy1-=sz1*(step(0.0,gy1)-0.5);vec3 g000=vec3(gx0.x,gy0.x,gz0.x);vec3 g100=vec3(gx0.y,gy0.y,gz0.y);vec3 g010=vec3(gx0.z,gy0.z,gz0.z);vec3 g110=vec3(gx0.w,gy0.w,gz0.w);vec3 g001=vec3(gx1.x,gy1.x,gz1.x);vec3 g101=vec3(gx1.y,gy1.y,gz1.y);vec3 g011=vec3(gx1.z,gy1.z,gz1.z);vec3 g111=vec3(gx1.w,gy1.w,gz1.w);vec4 norm0=taylorInvSqrt(vec4(dot(g000,g000),dot(g010,g010),dot(g100,g100),dot(g110,g110)));g000*=norm0.x;g010*=norm0.y;g100*=norm0.z;g110*=norm0.w;vec4 norm1=taylorInvSqrt(vec4(dot(g001,g001),dot(g011,g011),dot(g101,g101),dot(g111,g111)));g001*=norm1.x;g011*=norm1.y;g101*=norm1.z;g111*=norm1.w;float n000=dot(g000,Pf0);float n100=dot(g100,vec3(Pf1.x,Pf0.yz));float n010=dot(g010,vec3(Pf0.x,Pf1.y,Pf0.z));float n110=dot(g110,vec3(Pf1.xy,Pf0.z));float n001=dot(g001,vec3(Pf0.xy,Pf1.z));float n101=dot(g101,vec3(Pf1.x,Pf0.y,Pf1.z));float n011=dot(g011,vec3(Pf0.x,Pf1.yz));float n111=dot(g111,Pf1);vec3 fade_xyz=fade(Pf0);vec4 n_z=mix(vec4(n000,n100,n010,n110),vec4(n001,n101,n011,n111),fade_xyz.z);vec2 n_yz=mix(n_z.xy,n_z.zw,fade_xyz.y);float n_xyz=mix(n_yz.x,n_yz.y,fade_xyz.x);return 2.2*n_xyz;}\n/* END FUNCTION */\nfloat turbulence( vec3 p ) {float w=100.0;float t=-.5;for (float f=1.0 ; f<=10.0 ; f++ ){float power=pow( 2.0,f );t+=abs( pnoise( vec3( power*p ),vec3( 10.0,10.0,10.0 ) )/power );}\nreturn t;}\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\n#ifdef NORMAL\nnoise=10.0* -.10*turbulence( .5*normal+time*1.15 );float b=lowFrequencySpeed*5.0*pnoise( 0.05*position +vec3(time*1.025),vec3( 100.0 ) );float displacement=- 1.5*noise+b;vec3 newPosition=position+normal*displacement;gl_Position=viewProjection*finalWorld*vec4( newPosition,1.0 );vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos);vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class GG extends xl{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.UNLIT=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class zG extends ml{constructor(e,t){super(e,t),this.speed=1,this.movingSpeed=1,this.lowFrequencySpeed=1,this.fogDensity=.15,this._lastTime=0,this.diffuseColor=new Ee(1,1,1),this._disableLighting=!1,this._unlit=!1,this._maxSimultaneousLights=4,this._scaledDiffuse=new Ee}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new GG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&$c.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=!0,zo(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),Ho(n,o,this,r,!!i),jo(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),Vo(r,i),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="lava",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","time","speed","movingSpeed","fogColor","fogDensity","lowFrequencySpeed"];mo(h);const c=["diffuseSampler","noiseTexture"],u=[];ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,r.UNLIT=this._unlit,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.diffuseTexture&&$c.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),this.noiseTexture&&this._activeEffect.setTexture("noiseTexture",this.noiseTexture),xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._lastTime+=s.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime*this.speed/1e3),this.fogColor||(this.fogColor=Ee.Black()),this._activeEffect.setColor3("fogColor",this.fogColor),this._activeEffect.setFloat("fogDensity",this.fogDensity),this._activeEffect.setFloat("lowFrequencySpeed",this.lowFrequencySpeed),this._activeEffect.setFloat("movingSpeed",this.movingSpeed),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.noiseTexture&&this.noiseTexture.animations&&this.noiseTexture.animations.length>0&&e.push(this.noiseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),this.noiseTexture&&this.noiseTexture.dispose(),super.dispose(e)}clone(e){return St.Clone((()=>new zG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.LavaMaterial",e}getClassName(){return"LavaMaterial"}static Parse(e,t,i){return St.Parse((()=>new zG(e.name,t)),e,t,i)}}Ze([nt("diffuseTexture")],zG.prototype,"_diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],zG.prototype,"diffuseTexture",void 0),Ze([nt()],zG.prototype,"noiseTexture",void 0),Ze([ot()],zG.prototype,"fogColor",void 0),Ze([rt()],zG.prototype,"speed",void 0),Ze([rt()],zG.prototype,"movingSpeed",void 0),Ze([rt()],zG.prototype,"lowFrequencySpeed",void 0),Ze([rt()],zG.prototype,"fogDensity",void 0),Ze([ot()],zG.prototype,"diffuseColor",void 0),Ze([rt("disableLighting")],zG.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],zG.prototype,"disableLighting",void 0),Ze([rt("unlit")],zG.prototype,"_unlit",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],zG.prototype,"unlit",void 0),Ze([rt("maxSimultaneousLights")],zG.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],zG.prototype,"maxSimultaneousLights",void 0),z("BABYLON.LavaMaterial",zG);Bi.ShadersStore.mixPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform sampler2D mixMap1Sampler;uniform vec2 vTextureInfos;\n#ifdef MIXMAP2\nuniform sampler2D mixMap2Sampler;\n#endif\nuniform sampler2D diffuse1Sampler;uniform sampler2D diffuse2Sampler;uniform sampler2D diffuse3Sampler;uniform sampler2D diffuse4Sampler;uniform vec2 diffuse1Infos;uniform vec2 diffuse2Infos;uniform vec2 diffuse3Infos;uniform vec2 diffuse4Infos;\n#ifdef MIXMAP2\nuniform sampler2D diffuse5Sampler;uniform sampler2D diffuse6Sampler;uniform sampler2D diffuse7Sampler;uniform sampler2D diffuse8Sampler;uniform vec2 diffuse5Infos;uniform vec2 diffuse6Infos;uniform vec2 diffuse7Infos;uniform vec2 diffuse8Infos;\n#endif\n#endif\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 finalMixColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef MIXMAP2\nvec4 mixColor2=vec4(1.,1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec4 mixColor=texture2D(mixMap1Sampler,vTextureUV);\n#include\nmixColor.rgb*=vTextureInfos.y;vec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);vec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);vec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);vec4 diffuse4Color=texture2D(diffuse4Sampler,vTextureUV*diffuse4Infos);diffuse1Color.rgb*=mixColor.r;diffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,mixColor.g);diffuse3Color.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,mixColor.b);finalMixColor.rgb=mix(diffuse3Color.rgb,diffuse4Color.rgb,1.0-mixColor.a);\n#ifdef MIXMAP2\nmixColor=texture2D(mixMap2Sampler,vTextureUV);mixColor.rgb*=vTextureInfos.y;vec4 diffuse5Color=texture2D(diffuse5Sampler,vTextureUV*diffuse5Infos);vec4 diffuse6Color=texture2D(diffuse6Sampler,vTextureUV*diffuse6Infos);vec4 diffuse7Color=texture2D(diffuse7Sampler,vTextureUV*diffuse7Infos);vec4 diffuse8Color=texture2D(diffuse8Sampler,vTextureUV*diffuse8Infos);diffuse5Color.rgb=mix(finalMixColor.rgb,diffuse5Color.rgb,mixColor.r);diffuse6Color.rgb=mix(diffuse5Color.rgb,diffuse6Color.rgb,mixColor.g);diffuse7Color.rgb=mix(diffuse6Color.rgb,diffuse7Color.rgb,mixColor.b);finalMixColor.rgb=mix(diffuse7Color.rgb,diffuse8Color.rgb,1.0-mixColor.a);\n#endif\n#endif\n#ifdef VERTEXCOLOR\nfinalMixColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*finalMixColor.rgb,0.0,1.0);vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Bi.ShadersStore.mixVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x==0.)\n{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));}\nelse\n{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class WG extends xl{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.MIXMAP2=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class HG extends ml{constructor(e,t){super(e,t),this.diffuseColor=new Ee(1,1,1),this.specularColor=new Ee(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new WG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(n.texturesEnabled){if(!this._mixTexture1||!this._mixTexture1.isReady())return!1;if(r._needUVs=!0,$c.DiffuseTextureEnabled){if(!this._diffuseTexture1||!this._diffuseTexture1.isReady())return!1;if(r.DIFFUSE=!0,!this._diffuseTexture2||!this._diffuseTexture2.isReady())return!1;if(!this._diffuseTexture3||!this._diffuseTexture3.isReady())return!1;if(!this._diffuseTexture4||!this._diffuseTexture4.isReady())return!1;if(this._mixTexture2){if(!this._mixTexture2.isReady())return!1;if(r.MIXMAP2=!0,!this._diffuseTexture5||!this._diffuseTexture5.isReady())return!1;if(!this._diffuseTexture6||!this._diffuseTexture6.isReady())return!1;if(!this._diffuseTexture7||!this._diffuseTexture7.isReady())return!1;if(!this._diffuseTexture8||!this._diffuseTexture8.isReady())return!1}}}if(Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=zo(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),Ho(n,o,this,r,!!i),jo(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),Vo(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="mix",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","logarithmicDepthConstant","diffuse1Infos","diffuse2Infos","diffuse3Infos","diffuse4Infos","diffuse5Infos","diffuse6Infos","diffuse7Infos","diffuse8Infos"],c=["mixMap1Sampler","mixMap2Sampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","diffuse4Sampler","diffuse5Sampler","diffuse6Sampler","diffuse7Sampler","diffuse8Sampler"],u=[];mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._mixTexture1&&(this._activeEffect.setTexture("mixMap1Sampler",this._mixTexture1),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture1.coordinatesIndex,this._mixTexture1.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture1.getTextureMatrix()),$c.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale)),this._diffuseTexture4&&(this._activeEffect.setTexture("diffuse4Sampler",this._diffuseTexture4),this._activeEffect.setFloat2("diffuse4Infos",this._diffuseTexture4.uScale,this._diffuseTexture4.vScale)))),this._mixTexture2&&(this._activeEffect.setTexture("mixMap2Sampler",this._mixTexture2),$c.DiffuseTextureEnabled&&(this._diffuseTexture5&&(this._activeEffect.setTexture("diffuse5Sampler",this._diffuseTexture5),this._activeEffect.setFloat2("diffuse5Infos",this._diffuseTexture5.uScale,this._diffuseTexture5.vScale)),this._diffuseTexture6&&(this._activeEffect.setTexture("diffuse6Sampler",this._diffuseTexture6),this._activeEffect.setFloat2("diffuse6Infos",this._diffuseTexture6.uScale,this._diffuseTexture6.vScale)),this._diffuseTexture7&&(this._activeEffect.setTexture("diffuse7Sampler",this._diffuseTexture7),this._activeEffect.setFloat2("diffuse7Infos",this._diffuseTexture7.uScale,this._diffuseTexture7.vScale)),this._diffuseTexture8&&(this._activeEffect.setTexture("diffuse8Sampler",this._diffuseTexture8),this._activeEffect.setFloat2("diffuse8Infos",this._diffuseTexture8.uScale,this._diffuseTexture8.vScale)))),xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._mixTexture1&&this._mixTexture1.animations&&this._mixTexture1.animations.length>0&&e.push(this._mixTexture1),this._mixTexture2&&this._mixTexture2.animations&&this._mixTexture2.animations.length>0&&e.push(this._mixTexture2),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture1&&e.push(this._mixTexture1),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._diffuseTexture4&&e.push(this._diffuseTexture4),this._mixTexture2&&e.push(this._mixTexture2),this._diffuseTexture5&&e.push(this._diffuseTexture5),this._diffuseTexture6&&e.push(this._diffuseTexture6),this._diffuseTexture7&&e.push(this._diffuseTexture7),this._diffuseTexture8&&e.push(this._diffuseTexture8),e}hasTexture(e){return!!super.hasTexture(e)||this._mixTexture1===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._diffuseTexture4===e||this._mixTexture2===e||this._diffuseTexture5===e||this._diffuseTexture6===e||this._diffuseTexture7===e||this._diffuseTexture8===e}dispose(e){this._mixTexture1&&this._mixTexture1.dispose(),super.dispose(e)}clone(e){return St.Clone((()=>new HG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MixMaterial",e}getClassName(){return"MixMaterial"}static Parse(e,t,i){return St.Parse((()=>new HG(e.name,t)),e,t,i)}}Ze([nt("mixTexture1")],HG.prototype,"_mixTexture1",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"mixTexture1",void 0),Ze([nt("mixTexture2")],HG.prototype,"_mixTexture2",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"mixTexture2",void 0),Ze([nt("diffuseTexture1")],HG.prototype,"_diffuseTexture1",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture1",void 0),Ze([nt("diffuseTexture2")],HG.prototype,"_diffuseTexture2",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture2",void 0),Ze([nt("diffuseTexture3")],HG.prototype,"_diffuseTexture3",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture3",void 0),Ze([nt("diffuseTexture4")],HG.prototype,"_diffuseTexture4",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture4",void 0),Ze([nt("diffuseTexture1")],HG.prototype,"_diffuseTexture5",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture5",void 0),Ze([nt("diffuseTexture2")],HG.prototype,"_diffuseTexture6",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture6",void 0),Ze([nt("diffuseTexture3")],HG.prototype,"_diffuseTexture7",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture7",void 0),Ze([nt("diffuseTexture4")],HG.prototype,"_diffuseTexture8",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture8",void 0),Ze([ot()],HG.prototype,"diffuseColor",void 0),Ze([ot()],HG.prototype,"specularColor",void 0),Ze([rt()],HG.prototype,"specularPower",void 0),Ze([rt("disableLighting")],HG.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],HG.prototype,"disableLighting",void 0),Ze([rt("maxSimultaneousLights")],HG.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],HG.prototype,"maxSimultaneousLights",void 0),z("BABYLON.MixMaterial",HG);Bi.ShadersStore.normalPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef LIGHTING\n#include\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef NORMAL\nbaseColor=mix(baseColor,vec4(vNormalW,1.0),0.5);\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef LIGHTING\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0]\n#include[1]\n#include[2]\n#include[3]\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse= baseColor.rgb;\n#endif\nvec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.normalVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class XG extends xl{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.LIGHTING=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class YG extends ml{constructor(e,t){super(e,t),this.diffuseColor=new Ee(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaBlendingForMesh(e){return this.needAlphaBlending()||e.visibility<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new XG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&$c.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=!0,zo(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),Ho(n,o,this,r,!!i),r.LIGHTING=!this._disableLighting,jo(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),Vo(r,i),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),Bo(s,e,r,i),ko(s,r);const a="normal",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:4}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.diffuseTexture&&$c.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),super.dispose(e)}clone(e){return St.Clone((()=>new YG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.NormalMaterial",e}getClassName(){return"NormalMaterial"}static Parse(e,t,i){return St.Parse((()=>new YG(e.name,t)),e,t,i)}}Ze([nt("diffuseTexture")],YG.prototype,"_diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],YG.prototype,"diffuseTexture",void 0),Ze([ot()],YG.prototype,"diffuseColor",void 0),Ze([rt("disableLighting")],YG.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],YG.prototype,"disableLighting",void 0),Ze([rt("maxSimultaneousLights")],YG.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],YG.prototype,"maxSimultaneousLights",void 0),z("BABYLON.NormalMaterial",YG);Bi.ShadersStore.shadowOnlyPixelShader="precision highp float;uniform vec4 vEyePosition;uniform float alpha;uniform vec3 shadowColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0..1]\nvec4 color=vec4(shadowColor,(1.0-clamp(shadow,0.,1.))*alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.shadowOnlyVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class QG extends xl{constructor(){super(),this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class jG extends ml{constructor(e,t){super(e,t),this._needAlphaBlending=!0,this.shadowColor=Ee.Black()}needAlphaBlending(){return this._needAlphaBlending}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}get activeLight(){return this._activeLight}set activeLight(e){this._activeLight=e}_getFirstShadowLightForMesh(e){for(const t of e.lightSources)if(t.shadowEnabled)return t;return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new QG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(this._activeLight)for(const t of e.lightSources)if(t.shadowEnabled){if(this._activeLight===t)break;const i=e.lightSources.indexOf(this._activeLight);-1!==i&&(e.lightSources.splice(i,1),e.lightSources.splice(0,0,this._activeLight));break}Ho(n,o,this,r,!!i),Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=zo(n,e,r,!1,1);const a=this._getFirstShadowLightForMesh(e)?.getShadowGenerator();if(this._needAlphaBlending=!0,a&&a.getClassName&&"CascadedShadowGenerator"===a.getClassName()){const e=a;this._needAlphaBlending=!e.autoCalcDepthBounds}if(jo(e,r,!1,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),Vo(r,i,1),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),Bo(s,e,r,i),ko(s,r);const a="shadowOnly",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","alpha","shadowColor","mBones","logarithmicDepthConstant"],c=[],u=[];mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:1}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:1}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(n){if(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setFloat("alpha",this.alpha),this._activeEffect.setColor3("shadowColor",this.shadowColor),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),s.lightsEnabled){Lo(s,t,this._activeEffect,r,1);const e=this._getFirstShadowLightForMesh(t);e&&(e._renderId=-1)}(s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE||r.SHADOWCSM0)&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i)}}clone(e){return St.Clone((()=>new jG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.ShadowOnlyMaterial",e}getClassName(){return"ShadowOnlyMaterial"}static Parse(e,t,i){return St.Parse((()=>new jG(e.name,t)),e,t,i)}}z("BABYLON.ShadowOnlyMaterial",jG);Bi.ShadersStore.simplePixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.simpleVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class KG extends xl{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class $G extends ml{constructor(e,t){super(e,t),this.diffuseColor=new Ee(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new KG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&$c.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=zo(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),Ho(n,o,this,r,!!i),jo(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),Vo(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="simple",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights-1}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&$c.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}clone(e){return St.Clone((()=>new $G(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SimpleMaterial",e}getClassName(){return"SimpleMaterial"}static Parse(e,t,i){return St.Parse((()=>new $G(e.name,t)),e,t,i)}}Ze([nt("diffuseTexture")],$G.prototype,"_diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],$G.prototype,"diffuseTexture",void 0),Ze([ot("diffuse")],$G.prototype,"diffuseColor",void 0),Ze([rt("disableLighting")],$G.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],$G.prototype,"disableLighting",void 0),Ze([rt("maxSimultaneousLights")],$G.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],$G.prototype,"maxSimultaneousLights",void 0),z("BABYLON.SimpleMaterial",$G);Bi.ShadersStore.skyPixelShader="precision highp float;varying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\nuniform vec3 cameraPosition;uniform vec3 cameraOffset;uniform vec3 up;uniform float luminance;uniform float turbidity;uniform float rayleigh;uniform float mieCoefficient;uniform float mieDirectionalG;uniform vec3 sunPosition;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nconst float e=2.71828182845904523536028747135266249775724709369995957;const float pi=3.141592653589793238462643383279502884197169;const float n=1.0003;const float N=2.545E25;const float pn=0.035;const vec3 lambda=vec3(680E-9,550E-9,450E-9);const vec3 K=vec3(0.686,0.678,0.666);const float v=4.0;const float rayleighZenithLength=8.4E3;const float mieZenithLength=1.25E3;const float EE=1000.0;const float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;const float cutoffAngle=pi/1.95;const float steepness=1.5;vec3 totalRayleigh(vec3 lambda)\n{return (8.0*pow(pi,3.0)*pow(pow(n,2.0)-1.0,2.0)*(6.0+3.0*pn))/(3.0*N*pow(lambda,vec3(4.0))*(6.0-7.0*pn));}\nvec3 simplifiedRayleigh()\n{return 0.0005/vec3(94,40,18);}\nfloat rayleighPhase(float cosTheta)\n{ \nreturn (3.0/(16.0*pi))*(1.0+pow(cosTheta,2.0));}\nvec3 totalMie(vec3 lambda,vec3 K,float T)\n{float c=(0.2*T )*10E-18;return 0.434*c*pi*pow((2.0*pi)/lambda,vec3(v-2.0))*K;}\nfloat hgPhase(float cosTheta,float g)\n{return (1.0/(4.0*pi))*((1.0-pow(g,2.0))/pow(1.0-2.0*g*cosTheta+pow(g,2.0),1.5));}\nfloat sunIntensity(float zenithAngleCos)\n{return EE*max(0.0,1.0-exp((-(cutoffAngle-acos(zenithAngleCos))/steepness)));}\nfloat A=0.15;float B=0.50;float C=0.10;float D=0.20;float EEE=0.02;float F=0.30;float W=1000.0;vec3 Uncharted2Tonemap(vec3 x)\n{return ((x*(A*x+C*B)+D*EEE)/(x*(A*x+B)+D*F))-EEE/F;}\n#if DITHER\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n/**\n*--------------------------------------------------------------------------------------------------\n* Sky Color\n*--------------------------------------------------------------------------------------------------\n*/\nfloat sunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);float rayleighCoefficient=rayleigh-(1.0*(1.0-sunfade));vec3 sunDirection=normalize(sunPosition);float sunE=sunIntensity(dot(sunDirection,up));vec3 betaR=simplifiedRayleigh()*rayleighCoefficient;vec3 betaM=totalMie(lambda,K,turbidity)*mieCoefficient;float zenithAngle=acos(max(0.0,dot(up,normalize(vPositionW-cameraPosition+cameraOffset))));float sR=rayleighZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));float sM=mieZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));vec3 Fex=exp(-(betaR*sR+betaM*sM));float cosTheta=dot(normalize(vPositionW-cameraPosition),sunDirection);float rPhase=rayleighPhase(cosTheta*0.5+0.5);vec3 betaRTheta=betaR*rPhase;float mPhase=hgPhase(cosTheta,mieDirectionalG);vec3 betaMTheta=betaM*mPhase;vec3 Lin=pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*(1.0-Fex),vec3(1.5));Lin*=mix(vec3(1.0),pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,sunDirection),5.0),0.0,1.0));vec3 direction=normalize(vPositionW-cameraPosition);float theta=acos(direction.y);float phi=atan(direction.z,direction.x);vec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);vec3 L0=vec3(0.1)*Fex;float sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);L0+=(sunE*19000.0*Fex)*sundisk;vec3 whiteScale=1.0/Uncharted2Tonemap(vec3(W));vec3 texColor=(Lin+L0);texColor*=0.04 ;texColor+=vec3(0.0,0.001,0.0025)*0.3;float g_fMaxLuminance=1.0;float fLumScaled=0.1/luminance; \nfloat fLumCompressed=(fLumScaled*(1.0+(fLumScaled/(g_fMaxLuminance*g_fMaxLuminance))))/(1.0+fLumScaled); \nfloat ExposureBias=fLumCompressed;vec3 curr=Uncharted2Tonemap((log2(2.0/pow(luminance,4.0)))*texColor);vec3 retColor=curr*whiteScale;/**\n*--------------------------------------------------------------------------------------------------\n* Sky Color\n*--------------------------------------------------------------------------------------------------\n*/\nfloat alpha=1.0;\n#ifdef VERTEXCOLOR\nretColor.rgb*=vColor.rgb;\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#if DITHER\nretColor.rgb+=dither(gl_FragCoord.xy,0.5);\n#endif\nvec4 color=clamp(vec4(retColor.rgb,alpha),0.0,1.0);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Bi.ShadersStore.skyVertexShader="precision highp float;attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\nuniform mat4 world;uniform mat4 view;uniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\ngl_Position=viewProjection*world*vec4(position,1.0);vec4 worldPos=world*vec4(position,1.0);vPositionW=vec3(worldPos);\n#include\n#include\n#include\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class qG extends xl{constructor(){super(),this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.DITHER=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class ZG extends ml{constructor(e,t){super(e,t),this.luminance=1,this.turbidity=10,this.rayleigh=2,this.mieCoefficient=.005,this.mieDirectionalG=.8,this.distance=500,this.inclination=.49,this.azimuth=.25,this.sunPosition=new _e(0,100,0),this.useSunPosition=!1,this.cameraOffset=_e.Zero(),this.up=_e.Up(),this.dithering=!1,this._cameraPosition=_e.Zero(),this._skyOrientation=new fe}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new qG);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;if(Go(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,s),jo(e,s,!0,!1),s.IMAGEPROCESSINGPOSTPROCESS!==r.imageProcessingConfiguration.applyByPostProcess&&s.markAsMiscDirty(),s.DITHER!==this.dithering&&s.markAsMiscDirty(),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess,s.DITHER=this.dithering;const i=[er.PositionKind];s.VERTEXCOLOR&&i.push(er.ColorKind);const n="sky",o=["world","viewProjection","view","vFogInfos","vFogColor","logarithmicDepthConstant","pointSize","luminance","turbidity","rayleigh","mieCoefficient","mieDirectionalG","sunPosition","cameraPosition","cameraOffset","up"];mo(o);const a=s.toString();t.setEffect(r.getEngine().createEffect(n,i,o,[],a,e,this.onCompiled,this.onError),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._mustRebind(s,n,i)&&(xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s)),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect);const o=s.activeCamera;if(o){const e=o.getWorldMatrix();this._cameraPosition.x=e.m[12],this._cameraPosition.y=e.m[13],this._cameraPosition.z=e.m[14],this._activeEffect.setVector3("cameraPosition",this._cameraPosition)}if(this._activeEffect.setVector3("cameraOffset",this.cameraOffset),this._activeEffect.setVector3("up",this.up),this.luminance>0&&this._activeEffect.setFloat("luminance",this.luminance),this._activeEffect.setFloat("turbidity",this.turbidity),this._activeEffect.setFloat("rayleigh",this.rayleigh),this._activeEffect.setFloat("mieCoefficient",this.mieCoefficient),this._activeEffect.setFloat("mieDirectionalG",this.mieDirectionalG),!this.useSunPosition){const e=Math.PI*(this.inclination-.5),t=2*Math.PI*(this.azimuth-.5);this.sunPosition.x=this.distance*Math.cos(t)*Math.cos(e),this.sunPosition.y=this.distance*Math.sin(-e),this.sunPosition.z=this.distance*Math.sin(t)*Math.cos(e),fe.FromUnitVectorsToRef(_e.UpReadOnly,this.up,this._skyOrientation),this.sunPosition.rotateByQuaternionToRef(this._skyOrientation,this.sunPosition)}this._activeEffect.setVector3("sunPosition",this.sunPosition),this._afterBind(t,this._activeEffect,i)}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new ZG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SkyMaterial",e}getClassName(){return"SkyMaterial"}static Parse(e,t,i){return St.Parse((()=>new ZG(e.name,t)),e,t,i)}}Ze([rt()],ZG.prototype,"luminance",void 0),Ze([rt()],ZG.prototype,"turbidity",void 0),Ze([rt()],ZG.prototype,"rayleigh",void 0),Ze([rt()],ZG.prototype,"mieCoefficient",void 0),Ze([rt()],ZG.prototype,"mieDirectionalG",void 0),Ze([rt()],ZG.prototype,"distance",void 0),Ze([rt()],ZG.prototype,"inclination",void 0),Ze([rt()],ZG.prototype,"azimuth",void 0),Ze([ht()],ZG.prototype,"sunPosition",void 0),Ze([rt()],ZG.prototype,"useSunPosition",void 0),Ze([ht()],ZG.prototype,"cameraOffset",void 0),Ze([ht()],ZG.prototype,"up",void 0),Ze([rt()],ZG.prototype,"dithering",void 0),z("BABYLON.SkyMaterial",ZG);Bi.ShadersStore.terrainPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform sampler2D textureSampler;uniform vec2 vTextureInfos;uniform sampler2D diffuse1Sampler;uniform sampler2D diffuse2Sampler;uniform sampler2D diffuse3Sampler;uniform vec2 diffuse1Infos;uniform vec2 diffuse2Infos;uniform vec2 diffuse3Infos;\n#endif\n#ifdef BUMP\nuniform sampler2D bump1Sampler;uniform sampler2D bump2Sampler;uniform sampler2D bump3Sampler;\n#endif\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;float invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));return mat3(tangent*invmax,binormal*invmax,normal);}\nvec3 perturbNormal(vec3 viewDir,vec3 mixColor)\n{vec3 bump1Color=texture2D(bump1Sampler,vTextureUV*diffuse1Infos).xyz;vec3 bump2Color=texture2D(bump2Sampler,vTextureUV*diffuse2Infos).xyz;vec3 bump3Color=texture2D(bump3Sampler,vTextureUV*diffuse3Infos).xyz;bump1Color.rgb*=mixColor.r;bump2Color.rgb=mix(bump1Color.rgb,bump2Color.rgb,mixColor.g);vec3 map=mix(bump2Color.rgb,bump3Color.rgb,mixColor.b);map=map*255./127.-128./127.;mat3 TBN=cotangent_frame(vNormalW*vTextureInfos.y,-viewDir,vTextureUV);return normalize(TBN*map);}\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(textureSampler,vTextureUV);\n#if defined(BUMP) && defined(DIFFUSE)\nnormalW=perturbNormal(viewDirectionW,baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vTextureInfos.y;vec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);vec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);vec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);diffuse1Color.rgb*=baseColor.r;diffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,baseColor.g);baseColor.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,baseColor.b);\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*baseColor.rgb,0.0,1.0);vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Bi.ShadersStore.terrainVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x==0.)\n{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));}\nelse\n{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class JG extends xl{constructor(){super(),this.DIFFUSE=!1,this.BUMP=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class ez extends ml{constructor(e,t){super(e,t),this.diffuseColor=new Ee(1,1,1),this.specularColor=new Ee(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new JG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(n.texturesEnabled){if(!this.mixTexture||!this.mixTexture.isReady())return!1;if(r._needUVs=!0,$c.DiffuseTextureEnabled){if(!this.diffuseTexture1||!this.diffuseTexture1.isReady())return!1;if(!this.diffuseTexture2||!this.diffuseTexture2.isReady())return!1;if(!this.diffuseTexture3||!this.diffuseTexture3.isReady())return!1;r.DIFFUSE=!0}if(this.bumpTexture1&&this.bumpTexture2&&this.bumpTexture3&&$c.BumpTextureEnabled){if(!this.bumpTexture1.isReady())return!1;if(!this.bumpTexture2.isReady())return!1;if(!this.bumpTexture3.isReady())return!1;r._needNormals=!0,r.BUMP=!0}}if(Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=zo(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),Ho(n,o,this,r,!!i),jo(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),Vo(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="terrain",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","diffuse1Infos","diffuse2Infos","diffuse3Infos"],c=["textureSampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","bump1Sampler","bump2Sampler","bump3Sampler","logarithmicDepthConstant"],u=[];mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.mixTexture&&(this._activeEffect.setTexture("textureSampler",this._mixTexture),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture.coordinatesIndex,this._mixTexture.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture.getTextureMatrix()),$c.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale))),$c.BumpTextureEnabled&&s.getEngine().getCaps().standardDerivatives&&(this._bumpTexture1&&this._activeEffect.setTexture("bump1Sampler",this._bumpTexture1),this._bumpTexture2&&this._activeEffect.setTexture("bump2Sampler",this._bumpTexture2),this._bumpTexture3&&this._activeEffect.setTexture("bump3Sampler",this._bumpTexture3))),xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture&&e.push(this._mixTexture),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._bumpTexture1&&e.push(this._bumpTexture1),this._bumpTexture2&&e.push(this._bumpTexture2),this._bumpTexture3&&e.push(this._bumpTexture3),e}hasTexture(e){return!!super.hasTexture(e)||this._mixTexture===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._bumpTexture1===e||this._bumpTexture2===e||this._bumpTexture3===e}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return St.Clone((()=>new ez(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TerrainMaterial",e}getClassName(){return"TerrainMaterial"}static Parse(e,t,i){return St.Parse((()=>new ez(e.name,t)),e,t,i)}}Ze([nt("mixTexture")],ez.prototype,"_mixTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],ez.prototype,"mixTexture",void 0),Ze([nt("diffuseTexture1")],ez.prototype,"_diffuseTexture1",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],ez.prototype,"diffuseTexture1",void 0),Ze([nt("diffuseTexture2")],ez.prototype,"_diffuseTexture2",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],ez.prototype,"diffuseTexture2",void 0),Ze([nt("diffuseTexture3")],ez.prototype,"_diffuseTexture3",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],ez.prototype,"diffuseTexture3",void 0),Ze([nt("bumpTexture1")],ez.prototype,"_bumpTexture1",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],ez.prototype,"bumpTexture1",void 0),Ze([nt("bumpTexture2")],ez.prototype,"_bumpTexture2",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],ez.prototype,"bumpTexture2",void 0),Ze([nt("bumpTexture3")],ez.prototype,"_bumpTexture3",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],ez.prototype,"bumpTexture3",void 0),Ze([ot()],ez.prototype,"diffuseColor",void 0),Ze([ot()],ez.prototype,"specularColor",void 0),Ze([rt()],ez.prototype,"specularPower",void 0),Ze([rt("disableLighting")],ez.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],ez.prototype,"disableLighting",void 0),Ze([rt("maxSimultaneousLights")],ez.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],ez.prototype,"maxSimultaneousLights",void 0),z("BABYLON.TerrainMaterial",ez);Bi.ShadersStore.triplanarPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;uniform sampler2D diffuseSamplerX;\n#ifdef BUMPX\nuniform sampler2D normalSamplerX;\n#endif\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;uniform sampler2D diffuseSamplerY;\n#ifdef BUMPY\nuniform sampler2D normalSamplerY;\n#endif\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;uniform sampler2D diffuseSamplerZ;\n#ifdef BUMPZ\nuniform sampler2D normalSamplerZ;\n#endif\n#endif\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(0.,0.,0.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=tangentSpace[2];\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec4 baseNormal=vec4(0.0,0.0,0.0,1.0);normalW*=normalW;\n#ifdef DIFFUSEX\nbaseColor+=texture2D(diffuseSamplerX,vTextureUVX)*normalW.x;\n#ifdef BUMPX\nbaseNormal+=texture2D(normalSamplerX,vTextureUVX)*normalW.x;\n#endif\n#endif\n#ifdef DIFFUSEY\nbaseColor+=texture2D(diffuseSamplerY,vTextureUVY)*normalW.y;\n#ifdef BUMPY\nbaseNormal+=texture2D(normalSamplerY,vTextureUVY)*normalW.y;\n#endif\n#endif\n#ifdef DIFFUSEZ\nbaseColor+=texture2D(diffuseSamplerZ,vTextureUVZ)*normalW.z;\n#ifdef BUMPZ\nbaseNormal+=texture2D(normalSamplerZ,vTextureUVZ)*normalW.z;\n#endif\n#endif\n#ifdef NORMAL\nnormalW=normalize((2.0*baseNormal.xyz-1.0)*tangentSpace);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Bi.ShadersStore.triplanarVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\n#endif\nuniform float tileSize;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef DIFFUSEX\nvTextureUVX=worldPos.zy/tileSize;\n#endif\n#ifdef DIFFUSEY\nvTextureUVY=worldPos.xz/tileSize;\n#endif\n#ifdef DIFFUSEZ\nvTextureUVZ=worldPos.xy/tileSize;\n#endif\n#ifdef NORMAL\nvec3 xtan=vec3(0,0,1);vec3 xbin=vec3(0,1,0);vec3 ytan=vec3(1,0,0);vec3 ybin=vec3(0,0,1);vec3 ztan=vec3(1,0,0);vec3 zbin=vec3(0,1,0);vec3 normalizedNormal=normalize(normal);normalizedNormal*=normalizedNormal;vec3 worldBinormal=normalize(xbin*normalizedNormal.x+ybin*normalizedNormal.y+zbin*normalizedNormal.z);vec3 worldTangent=normalize(xtan*normalizedNormal.x+ytan*normalizedNormal.y+ztan*normalizedNormal.z);mat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nworldTangent=normalize((normalWorld*worldTangent).xyz);worldBinormal=normalize((normalWorld*worldBinormal).xyz);vec3 worldNormal=normalize((normalWorld*normalize(normal)).xyz);tangentSpace[0]=worldTangent;tangentSpace[1]=worldBinormal;tangentSpace[2]=worldNormal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class tz extends xl{constructor(){super(),this.DIFFUSEX=!1,this.DIFFUSEY=!1,this.DIFFUSEZ=!1,this.BUMPX=!1,this.BUMPY=!1,this.BUMPZ=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.NONUNIFORMSCALING=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class iz extends ml{constructor(e,t){super(e,t),this.tileSize=1,this.diffuseColor=new Ee(1,1,1),this.specularColor=new Ee(.2,.2,.2),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new tz);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&n.texturesEnabled){if($c.DiffuseTextureEnabled){const e=[this.diffuseTextureX,this.diffuseTextureY,this.diffuseTextureZ],t=["DIFFUSEX","DIFFUSEY","DIFFUSEZ"];for(let i=0;i0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="triplanar",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","mBones","tileSize"],c=["diffuseSamplerX","diffuseSamplerY","diffuseSamplerZ","normalSamplerX","normalSamplerY","normalSamplerZ","logarithmicDepthConstant"],u=[];mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._activeEffect.setFloat("tileSize",this.tileSize),this._mustRebind(s,n,i)&&(this.diffuseTextureX&&this._activeEffect.setTexture("diffuseSamplerX",this.diffuseTextureX),this.diffuseTextureY&&this._activeEffect.setTexture("diffuseSamplerY",this.diffuseTextureY),this.diffuseTextureZ&&this._activeEffect.setTexture("diffuseSamplerZ",this.diffuseTextureZ),this.normalTextureX&&this._activeEffect.setTexture("normalSamplerX",this.normalTextureX),this.normalTextureY&&this._activeEffect.setTexture("normalSamplerY",this.normalTextureY),this.normalTextureZ&&this._activeEffect.setTexture("normalSamplerZ",this.normalTextureZ),xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTextureX&&e.push(this._diffuseTextureX),this._diffuseTextureY&&e.push(this._diffuseTextureY),this._diffuseTextureZ&&e.push(this._diffuseTextureZ),this._normalTextureX&&e.push(this._normalTextureX),this._normalTextureY&&e.push(this._normalTextureY),this._normalTextureZ&&e.push(this._normalTextureZ),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTextureX===e||this._diffuseTextureY===e||this._diffuseTextureZ===e||this._normalTextureX===e||this._normalTextureY===e||this._normalTextureZ===e}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return St.Clone((()=>new iz(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TriPlanarMaterial",e}getClassName(){return"TriPlanarMaterial"}static Parse(e,t,i){return St.Parse((()=>new iz(e.name,t)),e,t,i)}}Ze([nt()],iz.prototype,"mixTexture",void 0),Ze([nt("diffuseTextureX")],iz.prototype,"_diffuseTextureX",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],iz.prototype,"diffuseTextureX",void 0),Ze([nt("diffuseTexturY")],iz.prototype,"_diffuseTextureY",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],iz.prototype,"diffuseTextureY",void 0),Ze([nt("diffuseTextureZ")],iz.prototype,"_diffuseTextureZ",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],iz.prototype,"diffuseTextureZ",void 0),Ze([nt("normalTextureX")],iz.prototype,"_normalTextureX",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],iz.prototype,"normalTextureX",void 0),Ze([nt("normalTextureY")],iz.prototype,"_normalTextureY",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],iz.prototype,"normalTextureY",void 0),Ze([nt("normalTextureZ")],iz.prototype,"_normalTextureZ",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],iz.prototype,"normalTextureZ",void 0),Ze([rt()],iz.prototype,"tileSize",void 0),Ze([ot()],iz.prototype,"diffuseColor",void 0),Ze([ot()],iz.prototype,"specularColor",void 0),Ze([rt()],iz.prototype,"specularPower",void 0),Ze([rt("disableLighting")],iz.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],iz.prototype,"disableLighting",void 0),Ze([rt("maxSimultaneousLights")],iz.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],iz.prototype,"maxSimultaneousLights",void 0),z("BABYLON.TriPlanarMaterial",iz);Bi.ShadersStore.waterPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform sampler2D normalSampler;uniform vec2 vNormalInfos;\n#endif\nuniform sampler2D refractionSampler;uniform sampler2D reflectionSampler;const float LOG2=1.442695;uniform vec3 cameraPosition;uniform vec4 waterColor;uniform float colorBlendFactor;uniform vec4 waterColor2;uniform float colorBlendFactor2;uniform float bumpHeight;uniform float time;varying vec3 vRefractionMapTexCoord;varying vec3 vReflectionMapTexCoord;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef BUMP\n#ifdef BUMPSUPERIMPOSE\nbaseColor=0.6*texture2D(normalSampler,vNormalUV)+0.4*texture2D(normalSampler,vec2(vNormalUV2.x,vNormalUV2.y));\n#else\nbaseColor=texture2D(normalSampler,vNormalUV);\n#endif\nvec3 bumpColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vNormalInfos.y;\n#else\nvec3 bumpColor=vec3(1.0);\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec2 perturbation=bumpHeight*(baseColor.rg-0.5);\n#ifdef BUMPAFFECTSREFLECTION\nvec3 normalW=normalize(vNormalW+vec3(perturbation.x*8.0,0.0,perturbation.y*8.0));if (normalW.y<0.0) {normalW.y=-normalW.y;}\n#else\nvec3 normalW=normalize(vNormalW);\n#endif\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);vec2 perturbation=bumpHeight*(vec2(1.0,1.0)-0.5);\n#endif\n#ifdef FRESNELSEPARATE\n#ifdef REFLECTION\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation*0.5,0.0,1.0);vec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vec2(\nvReflectionMapTexCoord.x/vReflectionMapTexCoord.z+perturbation.x*0.3,\nvReflectionMapTexCoord.y/vReflectionMapTexCoord.z+perturbation.y\n),0.0,1.0);vec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);float fresnelTerm=clamp(abs(pow(dot(viewDirectionW,upVector),3.0)),0.05,0.65);float IfresnelTerm=1.0-fresnelTerm;refractiveColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*refractiveColor;reflectiveColor=IfresnelTerm*colorBlendFactor2*waterColor+(1.0-colorBlendFactor2*IfresnelTerm)*reflectiveColor;vec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*IfresnelTerm;baseColor=combinedColor;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#else \n#ifdef REFLECTION\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation,0.0,1.0);vec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vReflectionMapTexCoord.xy/vReflectionMapTexCoord.z+perturbation,0.0,1.0);vec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);float fresnelTerm=max(dot(viewDirectionW,upVector),0.0);vec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*(1.0-fresnelTerm);baseColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*combinedColor;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#endif\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#elif defined(IMAGEPROCESSING)\ncolor.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Bi.ShadersStore.waterVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform mat4 normalMatrix;uniform vec2 vNormalInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\nuniform mat4 reflectionViewProjection;uniform vec2 windDirection;uniform float waveLength;uniform float time;uniform float windForce;uniform float waveHeight;uniform float waveSpeed;uniform float waveCount;varying vec3 vRefractionMapTexCoord;varying vec3 vReflectionMapTexCoord;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef BUMP\nif (vNormalInfos.x==0.)\n{vNormalUV=vec2(normalMatrix*vec4((uv*1.0)/waveLength+time*windForce*windDirection,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv*0.721)/waveLength+time*1.2*windForce*windDirection,1.0,0.0));\n#endif\n}\nelse\n{vNormalUV=vec2(normalMatrix*vec4((uv2*1.0)/waveLength+time*windForce*windDirection ,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv2*0.721)/waveLength+time*1.2*windForce*windDirection ,1.0,0.0));\n#endif\n}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\nfloat finalWaveCount=1.0/(waveCount*0.5);\n#ifdef USE_WORLD_COORDINATES\nvec3 p=worldPos.xyz;\n#else\nvec3 p=position;\n#endif\nfloat newY=(sin(((p.x/finalWaveCount)+time*waveSpeed))*waveHeight*windDirection.x*5.0)\n+ (cos(((p.z/finalWaveCount)+ time*waveSpeed))*waveHeight*windDirection.y*5.0);p.y+=abs(newY);\n#ifdef USE_WORLD_COORDINATES\ngl_Position=viewProjection*vec4(p,1.0);\n#else\ngl_Position=viewProjection*finalWorld*vec4(p,1.0);\n#endif\n#ifdef REFLECTION\nvRefractionMapTexCoord.x=0.5*(gl_Position.w+gl_Position.x);vRefractionMapTexCoord.y=0.5*(gl_Position.w+gl_Position.y);vRefractionMapTexCoord.z=gl_Position.w;worldPos=reflectionViewProjection*finalWorld*vec4(position,1.0);vReflectionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);vReflectionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);vReflectionMapTexCoord.z=worldPos.w;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class sz extends xl{constructor(){super(),this.BUMP=!1,this.REFLECTION=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.SPECULARTERM=!1,this.LOGARITHMICDEPTH=!1,this.USE_REVERSE_DEPTHBUFFER=!1,this.FRESNELSEPARATE=!1,this.BUMPSUPERIMPOSE=!1,this.BUMPAFFECTSREFLECTION=!1,this.USE_WORLD_COORDINATES=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class rz extends ml{get hasRenderTargetTextures(){return!0}constructor(e,t,i=new de(512,512)){super(e,t),this.renderTargetSize=i,this.diffuseColor=new Ee(1,1,1),this.specularColor=new Ee(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4,this.windForce=6,this.windDirection=new de(0,1),this.waveHeight=.4,this.bumpHeight=.4,this._bumpSuperimpose=!1,this._fresnelSeparate=!1,this._bumpAffectsReflection=!1,this.waterColor=new Ee(.1,.1,.6),this.colorBlendFactor=.2,this.waterColor2=new Ee(.1,.1,.6),this.colorBlendFactor2=.2,this.waveLength=.1,this.waveSpeed=1,this.waveCount=20,this.disableClipPlane=!1,this._useWorldCoordinatesForWaveDeformation=!1,this._renderTargets=new Fs(16),this._mesh=null,this._reflectionTransform=me.Zero(),this._lastTime=0,this._lastDeltaTime=0,this._createRenderTargets(this.getScene(),i),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._renderTargets.push(this._reflectionRTT),this._renderTargets.push(this._refractionRTT),this._renderTargets),this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get refractionTexture(){return this._refractionRTT}get reflectionTexture(){return this._reflectionRTT}addToRenderList(e){this._refractionRTT&&this._refractionRTT.renderList&&this._refractionRTT.renderList.push(e),this._reflectionRTT&&this._reflectionRTT.renderList&&this._reflectionRTT.renderList.push(e)}removeFromRenderList(e){if(this._refractionRTT&&this._refractionRTT.renderList){const t=this._refractionRTT.renderList.indexOf(e);-1!==t&&this._refractionRTT.renderList.splice(t,1)}if(this._reflectionRTT&&this._reflectionRTT.renderList){const t=this._reflectionRTT.renderList.indexOf(e);-1!==t&&this._reflectionRTT.renderList.splice(t,1)}}enableRenderTargets(e){const t=e?1:0;this._refractionRTT&&(this._refractionRTT.refreshRate=t),this._reflectionRTT&&(this._reflectionRTT.refreshRate=t)}getRenderList(){return this._refractionRTT?this._refractionRTT.renderList:[]}get renderTargetsEnabled(){return!(this._refractionRTT&&0===this._refractionRTT.refreshRate)}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new sz);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled)){if(this.bumpTexture&&$c.BumpTextureEnabled){if(!this.bumpTexture.isReady())return!1;r._needUVs=!0,r.BUMP=!0}$c.ReflectionTextureEnabled&&(r.REFLECTION=!0)}if(Ho(n,o,this,r,!!i),Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._areMiscDirty&&(r.FRESNELSEPARATE=this._fresnelSeparate,r.BUMPSUPERIMPOSE=this._bumpSuperimpose,r.BUMPAFFECTSREFLECTION=this._bumpAffectsReflection,r.USE_WORLD_COORDINATES=this._useWorldCoordinatesForWaveDeformation),r._needNormals=zo(n,e,r,!0,this._maxSimultaneousLights,this._disableLighting),r._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(r),r.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,r.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}if(jo(e,r,!0,!0),this._mesh=e,this._waitingRenderList){for(let e=0;e0&&i.addCPUSkinningFallback(0,e);const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="water",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vNormalInfos","mBones","normalMatrix","logarithmicDepthConstant","reflectionViewProjection","windDirection","waveLength","time","windForce","cameraPosition","bumpHeight","waveHeight","waterColor","waterColor2","colorBlendFactor","colorBlendFactor2","waveSpeed","waveCount"],c=["normalSampler","refractionSampler","reflectionSampler"],u=[];zs&&(zs.PrepareUniforms(h,r),zs.PrepareSamplers(c,r)),mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n||!this._mesh)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.bumpTexture&&$c.BumpTextureEnabled&&(this._activeEffect.setTexture("normalSampler",this.bumpTexture),this._activeEffect.setFloat2("vNormalInfos",this.bumpTexture.coordinatesIndex,this.bumpTexture.level),this._activeEffect.setMatrix("normalMatrix",this.bumpTexture.getTextureMatrix())),xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),So(r,this._activeEffect,s),$c.ReflectionTextureEnabled&&(this._activeEffect.setTexture("refractionSampler",this._refractionRTT),this._activeEffect.setTexture("reflectionSampler",this._reflectionRTT));const o=this._reflectionTransform.multiply(s.getProjectionMatrix()),a=s.getEngine().getDeltaTime();a!==this._lastDeltaTime&&(this._lastDeltaTime=a,this._lastTime+=this._lastDeltaTime),this._activeEffect.setMatrix("reflectionViewProjection",o),this._activeEffect.setVector2("windDirection",this.windDirection),this._activeEffect.setFloat("waveLength",this.waveLength),this._activeEffect.setFloat("time",this._lastTime/1e5),this._activeEffect.setFloat("windForce",this.windForce),this._activeEffect.setFloat("waveHeight",this.waveHeight),this._activeEffect.setFloat("bumpHeight",this.bumpHeight),this._activeEffect.setColor4("waterColor",this.waterColor,1),this._activeEffect.setFloat("colorBlendFactor",this.colorBlendFactor),this._activeEffect.setColor4("waterColor2",this.waterColor2,1),this._activeEffect.setFloat("colorBlendFactor2",this.colorBlendFactor2),this._activeEffect.setFloat("waveSpeed",this.waveSpeed),this._activeEffect.setFloat("waveCount",this.waveCount),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect),this._afterBind(t,this._activeEffect,i)}_createRenderTargets(e,t){this._refractionRTT=new ih(name+"_refraction",{width:t.x,height:t.y},e,!1,!0),this._refractionRTT.wrapU=N_.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.wrapV=N_.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.ignoreCameraViewport=!0;let i,s=!1;this._refractionRTT.onBeforeRenderObservable.add((()=>{s=e.getBoundingBoxRenderer().enabled,e.getBoundingBoxRenderer().enabled=!1})),this._refractionRTT.onAfterRenderObservable.add((()=>{e.getBoundingBoxRenderer().enabled=s})),this._reflectionRTT=new ih(name+"_reflection",{width:t.x,height:t.y},e,!1,!0),this._reflectionRTT.wrapU=N_.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.wrapV=N_.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.ignoreCameraViewport=!0;let r,n=null;const o=me.Zero();this._refractionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){n=e.clipPlane;const t=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=Nr.FromPositionAndNormal(new _e(0,t+.05,0),new _e(0,1,0))}},this._refractionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),this.disableClipPlane||(e.clipPlane=n)},this._reflectionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){n=e.clipPlane;const t=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=Nr.FromPositionAndNormal(new _e(0,t-.05,0),new _e(0,-1,0)),me.ReflectionToRef(e.clipPlane,o)}r=e.getViewMatrix(),o.multiplyToRef(r,this._reflectionTransform),e.setTransformMatrix(this._reflectionTransform,e.getProjectionMatrix()),e._mirroredCameraPosition=_e.TransformCoordinates(e.activeCamera.position,o)},this._reflectionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),e.clipPlane=n,e.setTransformMatrix(r,e.getProjectionMatrix()),e._mirroredCameraPosition=null}}getAnimatables(){const e=[];return this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this._reflectionRTT&&this._reflectionRTT.animations&&this._reflectionRTT.animations.length>0&&e.push(this._reflectionRTT),this._refractionRTT&&this._refractionRTT.animations&&this._refractionRTT.animations.length>0&&e.push(this._refractionRTT),e}getActiveTextures(){const e=super.getActiveTextures();return this._bumpTexture&&e.push(this._bumpTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._bumpTexture===e}dispose(e){this.bumpTexture&&this.bumpTexture.dispose();let t=this.getScene().customRenderTargets.indexOf(this._refractionRTT);-1!=t&&this.getScene().customRenderTargets.splice(t,1),t=-1,t=this.getScene().customRenderTargets.indexOf(this._reflectionRTT),-1!=t&&this.getScene().customRenderTargets.splice(t,1),this._reflectionRTT&&this._reflectionRTT.dispose(),this._refractionRTT&&this._refractionRTT.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return St.Clone((()=>new rz(e,this.getScene())),this)}serialize(){const e=super.serialize();if(e.customType="BABYLON.WaterMaterial",e.renderList=[],this._refractionRTT&&this._refractionRTT.renderList)for(let t=0;tnew rz(e.name,t)),e,t,i);return s._waitingRenderList=e.renderList,s}static CreateDefaultMesh(e,t){return Iu(e,{width:512,height:512,subdivisions:32,updatable:!1},t)}}Ze([nt("bumpTexture")],rz.prototype,"_bumpTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],rz.prototype,"bumpTexture",void 0),Ze([ot()],rz.prototype,"diffuseColor",void 0),Ze([ot()],rz.prototype,"specularColor",void 0),Ze([rt()],rz.prototype,"specularPower",void 0),Ze([rt("disableLighting")],rz.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],rz.prototype,"disableLighting",void 0),Ze([rt("maxSimultaneousLights")],rz.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],rz.prototype,"maxSimultaneousLights",void 0),Ze([rt()],rz.prototype,"windForce",void 0),Ze([lt()],rz.prototype,"windDirection",void 0),Ze([rt()],rz.prototype,"waveHeight",void 0),Ze([rt()],rz.prototype,"bumpHeight",void 0),Ze([rt("bumpSuperimpose")],rz.prototype,"_bumpSuperimpose",void 0),Ze([st("_markAllSubMeshesAsMiscDirty")],rz.prototype,"bumpSuperimpose",void 0),Ze([rt("fresnelSeparate")],rz.prototype,"_fresnelSeparate",void 0),Ze([st("_markAllSubMeshesAsMiscDirty")],rz.prototype,"fresnelSeparate",void 0),Ze([rt("bumpAffectsReflection")],rz.prototype,"_bumpAffectsReflection",void 0),Ze([st("_markAllSubMeshesAsMiscDirty")],rz.prototype,"bumpAffectsReflection",void 0),Ze([ot()],rz.prototype,"waterColor",void 0),Ze([rt()],rz.prototype,"colorBlendFactor",void 0),Ze([ot()],rz.prototype,"waterColor2",void 0),Ze([rt()],rz.prototype,"colorBlendFactor2",void 0),Ze([rt()],rz.prototype,"waveLength",void 0),Ze([rt()],rz.prototype,"waveSpeed",void 0),Ze([rt()],rz.prototype,"waveCount",void 0),Ze([rt()],rz.prototype,"disableClipPlane",void 0),Ze([rt("useWorldCoordinatesForWaveDeformation")],rz.prototype,"_useWorldCoordinatesForWaveDeformation",void 0),Ze([st("_markAllSubMeshesAsMiscDirty")],rz.prototype,"useWorldCoordinatesForWaveDeformation",void 0),z("BABYLON.WaterMaterial",rz);var nz,oz=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class az{constructor(e,t,i,s,r,n,o,a,l,h){this.point=e,this.line=t,this.polyline=i,this.node=s,this.verbCurve=r,this.verbSurface=n,this.jscad=o,this.occt=a,this.tag=l,this.context=h,this.defaultBasicOptions=new mU.DrawBasicGeometryOptions,this.defaultNodeOptions={colorX:"#ff0000",colorY:"#00ff00",colorZ:"#0000ff",size:2}}drawAnyAsyncNoReturn(e){return oz(this,void 0,void 0,(function*(){this.drawAnyAsync(e)}))}drawAnyAsync(e){return oz(this,void 0,void 0,(function*(){const t=e.entity;return void 0===t||Array.isArray(t)&&0===t.length?Promise.resolve(void 0):this.detectJscadMesh(t)?this.handleJscadMesh(e):this.detectOcctShape(t)?this.handleOcctShape(e):this.detectOcctShapes(t)?this.handleOcctShapes(e):this.detectJscadMeshes(t)?this.handleJscadMeshes(e):Promise.resolve(this.drawAny(e))}))}updateAny(e){let t;if(e.babylonMesh&&e.babylonMesh.metadata)switch(e.babylonMesh.metadata.type){case mU.drawingTypes.point:t=this.handlePoint(e);break;case mU.drawingTypes.points:t=this.handlePoints(e);break;case mU.drawingTypes.line:t=this.handleLine(e);break;case mU.drawingTypes.lines:t=this.handleLines(e);break;case mU.drawingTypes.polyline:t=this.handlePolyline(e);break;case mU.drawingTypes.polylines:t=this.handlePolylines(e);break;case mU.drawingTypes.verbCurve:t=this.handleVerbCurve(e);break;case mU.drawingTypes.verbCurves:t=this.handleVerbCurves(e);break;case mU.drawingTypes.verbSurface:t=this.handleVerbSurface(e);break;case mU.drawingTypes.verbSurfaces:t=this.handleVerbSurfaces(e);break;case mU.drawingTypes.tag:t=this.handleTag(e);break;case mU.drawingTypes.tags:t=this.handleTags(e);break;case mU.drawingTypes.node:t=this.handleNode(e);break;case mU.drawingTypes.nodes:t=this.handleNodes(e)}return t}drawAnyNoReturn(e){this.drawAny(e)}drawAny(e){let t;const i=e.entity;return e.babylonMesh?t=this.updateAny(e):this.detectLine(i)?t=this.handleLine(e):this.detectPoint(i)?t=this.handlePoint(e):this.detectPolyline(i)?t=this.handlePolyline(e):this.detectNode(i)?t=this.handleNode(e):this.detectVerbCurve(i)?t=this.handleVerbCurve(e):this.detectVerbSurface(i)?t=this.handleVerbSurface(e):this.detectPolylines(i)?t=this.handlePolylines(e):this.detectLines(i)?t=this.handleLines(e):this.detectPoints(i)?t=this.handlePoints(e):this.detectNodes(i)?t=this.handleNodes(e):this.detectVerbCurves(i)?t=this.handleVerbCurves(e):this.detectVerbSurfaces(i)?t=this.handleVerbSurfaces(e):this.detectTag(i)?t=this.handleTag(e):this.detectTags(i)&&(t=this.handleTags(e)),t}drawGridMeshNoReturn(e){this.drawGridMesh(e)}drawGridMesh(e){try{const t=new UG(`groundMaterial${Math.random()}`,this.context.scene);t.majorUnitFrequency=e.majorUnitFrequency,t.minorUnitVisibility=e.minorUnitVisibility,t.gridRatio=e.gridRatio,t.backFaceCulling=e.backFaceCulling,t.mainColor=Ee.FromHexString(e.mainColor),t.lineColor=Ee.FromHexString(e.secondaryColor),t.opacity=e.opacity;const i=R_.CreateGround(`bitbybit-ground${Math.random()}`,{width:e.width,height:e.height,subdivisions:e.subdivisions,updatable:!1},this.context.scene);return i.material=t,i}catch(e){return console.log("Error happened: ",e),new ha("error-ground",this.context.scene)}}optionsSimple(e){return e}optionsOcctShape(e){return e}optionsOcctShapeSimple(e){return e}optionsOcctShapeMaterial(e){return e}optionsBabylonNode(e){return e}handleTags(e){const t=e.options?e.options:{updatable:!1},i=this.tag.drawTags(Object.assign({tagsVariable:e.babylonMesh,tags:e.entity},t));return i.metadata={type:mU.drawingTypes.tags,options:t},i}handleTag(e){let t=e.options?e.options:{updatable:!1};!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.tag.drawTag(Object.assign({tagVariable:e.babylonMesh,tag:e.entity},t));return i.metadata={type:mU.drawingTypes.tag,options:t},i}handleVerbSurfaces(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbSurface.drawSurfacesMultiColour(Object.assign({surfacesMesh:e.babylonMesh,surfaces:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.verbSurfaces,t,i),i}handleVerbCurves(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbCurve.drawCurves(Object.assign({curvesMesh:e.babylonMesh,curves:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.verbCurves,t,i),i}handleNodes(e){let t=e.options?e.options:this.defaultNodeOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity;return this.node.drawNodes(Object.assign({nodes:e.entity},t)),this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.nodes,t,i),i}handlePoints(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.point.drawPoints(Object.assign({pointsMesh:e.babylonMesh,points:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.points,t,i),i}handleLines(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolylines(Object.assign({polylinesMesh:e.babylonMesh,polylines:e.entity.map((e=>({points:[e.start,e.end]})))},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.lines,t,i),i}handlePolylines(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolylines(Object.assign({polylinesMesh:e.babylonMesh,polylines:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.polylines,t,i),i}handleVerbSurface(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbSurface.drawSurface(Object.assign({surfaceMesh:e.babylonMesh,surface:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.verbSurface,t,i),i}handleVerbCurve(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbCurve.drawCurve(Object.assign({curveMesh:e.babylonMesh,curve:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.verbCurve,t,i),i}handleNode(e){let t=e.options?e.options:this.defaultNodeOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity;return this.node.drawNode(Object.assign({node:e.entity},t)),this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.node,t,i),i}handlePolyline(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolyline(Object.assign({polylineMesh:e.babylonMesh,polyline:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.polyline,t,i),i}handlePoint(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.point.drawPoint(Object.assign({pointMesh:e.babylonMesh,point:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.point,t,i),i}handleLine(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolylines(Object.assign({polylinesMesh:e.babylonMesh,polylines:[{points:[e.entity.start,e.entity.end]}]},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.line,t,i),i}handleJscadMeshes(e){let t=e.options?e.options:this.defaultBasicOptions;return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.jscad.drawSolidOrPolygonMeshes(Object.assign({jscadMesh:e.babylonMesh,meshes:e.entity},t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.jscadMeshes,t,e),e)))}handleOcctShape(e){let t=e.options?e.options:new Jk.DrawShapeDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.occt.drawShape(Object.assign(Object.assign({shape:e.entity},new mU.DrawOcctShapeOptions),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.occt,t,e),e)))}handleOcctShapes(e){let t=e.options?e.options:new Jk.DrawShapeDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.occt.drawShapes(Object.assign(Object.assign({shapes:e.entity},new mU.DrawOcctShapeOptions),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.occt,t,e),e)))}handleJscadMesh(e){let t=e.options?e.options:this.defaultBasicOptions;return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.jscad.drawSolidOrPolygonMesh(Object.assign({jscadMesh:e.babylonMesh,mesh:e.entity},t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.jscadMesh,t,e),e)))}applyGlobalSettingsAndMetadataAndShadowCasting(e,t,i){const s={type:e,options:t},r=this.context.scene.metadata.shadowGenerators;i.isPickable=!1,i.getChildMeshes().forEach((e=>{e.isPickable=!1})),r.length>0&&(i.receiveShadows=!0,r.forEach((e=>e.addShadowCaster(i))),i.getChildMeshes().forEach((e=>{e.receiveShadows=!0,r.forEach((t=>t.addShadowCaster(e)))}))),i.metadata=i.metadata?Object.assign(Object.assign({},i.metadata),s):s}detectPoint(e){return Array.isArray(e)&&3===e.length&&this.checkIfElementsInArrayAreNumbers(e)}detectPoints(e){return Array.isArray(e)&&this.checkIfElementsInArrayAreArrays(e)&&this.arraysInChildrenArraysContainNumbers(e)&&this.arraysInChildrenArraysAreOfLength3(e)}detectLine(e){return e.start&&e.end&&Array.isArray(e.start)&&Array.isArray(e.end)}detectLines(e){return Array.isArray(e)&&!e.some((e=>!this.detectLine(e)))}detectPolyline(e){return e.points&&Array.isArray(e.points)}detectPolylines(e){return Array.isArray(e)&&!e.some((e=>!this.detectPolyline(e)))}detectNode(e){return!Array.isArray(e)&&e.id&&e.id.includes("node")}detectNodes(e){return Array.isArray(e)&&!e.some((e=>!this.detectNode(e)))}detectVerbCurve(e){return!Array.isArray(e)&&e._data&&e._data.controlPoints&&e._data.knots&&e._data.degree}detectVerbSurface(e){return!Array.isArray(e)&&e._data&&e._data.controlPoints&&e._data.degreeU&&e._data.degreeV&&e._data.knotsU&&e._data.knotsV}detectVerbCurves(e){return Array.isArray(e)&&!e.some((e=>!this.detectVerbCurve(e)))}detectVerbSurfaces(e){return Array.isArray(e)&&!e.some((e=>!this.detectVerbSurface(e)))}detectJscadMesh(e){return!Array.isArray(e)&&(e.sides||e.polygons)}detectJscadMeshes(e){return Array.isArray(e)&&!e.some((e=>!this.detectJscadMesh(e)))}detectOcctShape(e){return"occ-shape"===(null==e?void 0:e.type)}detectOcctShapes(e){return Array.isArray(e)&&!e.some((e=>!this.detectOcctShape(e)))}detectTag(e){return!Array.isArray(e)&&e.text}detectTags(e){return Array.isArray(e)&&!e.some((e=>!this.detectTag(e)))}checkIfElementsInArrayAreNumbers(e){return!e.some((e=>isNaN(e)))}checkIfElementsInArrayAreArrays(e){return!e.some((e=>!Array.isArray(e)))}arraysInChildrenArraysContainNumbers(e){return!e.some((e=>!this.checkIfElementsInArrayAreNumbers(e)))}arraysInChildrenArraysAreOfLength3(e){return!e.some((e=>3!==e.length))}}class lz{constructor(e,t){this.context=e,this.geometryHelper=t}drawLines(e){const t=[],i=[];return e.lines.forEach(((s,r)=>{let n;t.push([new _e(s.start[0],s.start[1],s.start[2]),new _e(s.end[0],s.end[1],s.end[2])]),n=Array.isArray(e.colours)&&e.colours.length===e.lines.length?Ee.FromHexString(e.colours[r]):Array.isArray(e.colours)?Ee.FromHexString(e.colours[0]):Ee.FromHexString(e.colours),i.push([new Ae(n.r,n.g,n.b,e.opacity),new Ae(n.r,n.g,n.b,e.opacity)])})),e.linesMesh&&e.updatable?e.linesMesh.getTotalVertices()/2===t.length?e.linesMesh=R_.CreateLineSystem(null,{lines:t,instance:e.linesMesh,colors:i,useVertexAlpha:!0,updatable:e.updatable},null):(e.linesMesh.dispose(),e.linesMesh=this.createLineSystemMesh(e.updatable,t,i)):e.linesMesh=this.createLineSystemMesh(e.updatable,t,i),this.geometryHelper.edgesRendering(e.linesMesh,e.size,e.opacity,e.colours),e.linesMesh}convertToNurbsCurve(e){return new this.context.verb.geom.Line(e.line.start,e.line.end)}convertLinesToNurbsCurves(e){return e.lines.map((e=>new this.context.verb.geom.Line(e.start,e.end)))}getStartPoint(e){return e.line.start}getEndPoint(e){return e.line.end}length(e){return this.context.verb.core.Vec.dist(e.line.start,e.line.end)}reverse(e){return{start:e.line.end,end:e.line.start}}transformLine(e){const t=e.transformation;let i=[e.line.start,e.line.end];return i=this.geometryHelper.transformControlPoints(t,i),{start:i[0],end:i[1]}}transformsForLines(e){return e.lines.map(((t,i)=>{const s=e.transformation[i];let r=[t.start,t.end];return r=this.geometryHelper.transformControlPoints(s,r),{start:r[0],end:r[1]}}))}create(e){return{start:e.start,end:e.end}}createAsync(e){return Promise.resolve({start:e.start,end:e.end})}getPointOnLine(e){const t=e.line.start,i=e.line.end,s=e.param,r=[i[0]-t[0],i[1]-t[1],i[2]-t[2]];return[t[0]+s*r[0],t[1]+s*r[1],t[2]+s*r[2]]}linesBetweenPoints(e){const t=[];for(let i=1;i({start:t,end:e.endPoints[i]}))).filter((e=>0!==this.context.verb.core.Vec.dist(e.start,e.end)))}linesBetweenStartAndEndPointsAsync(e){return Promise.resolve(this.linesBetweenStartAndEndPoints(e))}createLineSystemMesh(e,t,i){return R_.CreateLineSystem(`lines${Math.random()}`,{lines:t,colors:i,useVertexAlpha:!0,updatable:e},this.context.scene)}}class hz{getItem(e){if(e.index<0||e.index>=e.list.length)throw new Error("Index out of bounds");let t;return t=e.clone?structuredClone(e.list[e.index]):e.list[e.index],t}getSubList(e){let t;return t=e.clone?structuredClone(e.list.slice(e.indexStart,e.indexEnd)):e.list.slice(e.indexStart,e.indexEnd),t}getNthItem(e){let t=e.list;e.clone&&(t=structuredClone(e.list));const i=[];for(let s=0;s=r)t.forEach(((e,t)=>{!0===i[t]&&n.push(e)}));else{const e=[],o=Math.ceil(r/s);for(let t=0;t{!0===e[i]&&n.push(t)}))}return n}mergeElementsOfLists(e){const t=e.lists,i=e.level,s=[],r=[];t.forEach((e=>{const t=e.flat(i);s.push(t)}));const n=this.getLongestListLength({lists:s});for(let e=0;e0&&r.push(t)}let o=[];if(i>0)for(let e=0;e{e.length>t&&(t=e.length)})),t):void 0}reverse(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),t.reverse()}flipLists(e){if(e.list.length>0){const t=e.list[0].length;let i=!0;if(e.list.forEach((e=>{e.length!==t&&(i=!1)})),i){const i=[];for(let s=0;s{t.push(e[s])})),i.push(t)}return i}throw new Error("Lists are not of the same length")}throw new Error("List is empty")}groupNth(e){return(e=>{const{nrElements:t,list:i,keepRemainder:s}=e,r=t,n=[];let o=[];return i.forEach(((e,t)=>{o.push(e),(t+1)%r==0&&(n.push(o),o=[]),s&&t===i.length-1&&n.push(o)})),n})(e)}getListDepth(e){let t=0,i=!0,s=e.list;for(;i;){let e=!1;for(let t=0;t=0&&e.index<=t.length&&t.splice(e.index,0,e.item),t}addItemAtIndexes(e){let t=e.list;e.clone&&(t=structuredClone(e.list));let i=[...e.indexes];return i=i.filter((e=>e>=0&&e<=t.length)),i.sort(((e,t)=>e-t)),i.forEach(((i,s)=>{i>=0&&i+s<=t.length&&t.splice(i+s,0,e.item)})),t}addItemsAtIndexes(e){if(e.items.length!==e.indexes.length)throw new Error("Items and indexes must have the same length");for(let t=0;t0&&e.indexes[t-1]>e.indexes[t])throw new Error("Indexes must be in ascending order");let t=e.list;return e.clone&&(t=structuredClone(e.list)),[...e.indexes].forEach(((i,s)=>{i>=0&&i+s<=t.length&&t.splice(i+s,0,e.items[s])})),t}removeItemAtIndex(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),e.index>=0&&e.index<=t.length&&t.splice(e.index,1),t}removeNthItem(e){let t=e.list;e.clone&&(t=structuredClone(e.list));const i=[];for(let s=0;s{const s=e.points;return e.isClosed&&s.push(s[0]),e.color&&(Array.isArray(t)||(t=[]),Array.isArray(e.color)?t[i]=Ee.FromArray(e.color).toHexString():t[i]=e.color),s}));return this.geometryHelper.drawPolylines(e.polylinesMesh,i,e.updatable,e.size,e.opacity,t)}convertToNurbsCurve(e){return this.context.verb.geom.NurbsCurve.byPoints(e.polyline.points,1)}length(e){let t=0;for(let i=1;it.id===e.tagVariable.id));Object.keys(e.tag).forEach((i=>{t[i]=e.tag[i]})),t.needsUpdate=!0}else{const t=document.createElement("span"),i="_tag"+(new Date).getTime()+this.context.tagBag.length;e.tag.id=i,t.id=i,t.textContent=e.tag.text,document.querySelector("."+this.context.canvasZoneClass).appendChild(t),e.tag.needsUpdate=!0,this.context.tagBag.push(e.tag)}return e.tag}drawTags(e){if(e.tagsVariable&&e.updatable){if(e.tagsVariable.length{const s=this.context.tagBag.find((e=>e.id===t.id)),r=e.tags[i];if(r)Object.keys(r).forEach((e=>{s[e]=r[e]})),s.needsUpdate=!0;else{this.context.tagBag=this.context.tagBag.filter((e=>e.id!==s.id));const e=document.getElementById(s.id);e.parentNode.removeChild(e)}}))}else{const t=[];e.tags.forEach(((i,s)=>{const r=document.createElement("span"),n="_tag"+(new Date).getTime()+this.context.tagBag.length;i.id=n,r.id=n,r.textContent=i.text,document.querySelector("."+this.context.canvasZoneClass).appendChild(r),i.needsUpdate=!0,this.context.tagBag.push(i),t.push(i),e.tagsVariable=t}))}return e.tagsVariable}}class _z{constructor(e){this.context=e}angleBetween(e){return $r.FromRadians(this.context.verb.core.Vec.angleBetween(e.first,e.second)).degrees()}angleBetweenNormalized2d(e){return $r.FromRadians(this.context.verb.core.Vec.angleBetweenNormalized2d(e.first,e.second)).degrees()}positiveAngleBetween(e){return $r.FromRadians(this.context.verb.core.Vec.positiveAngleBetween(e.first,e.second,e.reference)).degrees()}addAll(e){return this.context.verb.core.Vec.addAll(e.vectors)}add(e){return this.context.verb.core.Vec.add(e.first,e.second)}all(e){return this.context.verb.core.Vec.all(e.vector)}cross(e){return this.context.verb.core.Vec.cross(e.first,e.second)}distSquared(e){return this.context.verb.core.Vec.distSquared(e.first,e.second)}dist(e){return this.context.verb.core.Vec.dist(e.first,e.second)}div(e){return this.context.verb.core.Vec.div(e.vector,e.scalar)}domain(e){return this.context.verb.core.Vec.domain(e.vector)}dot(e){return this.context.verb.core.Vec.dot(e.first,e.second)}finite(e){return this.context.verb.core.Vec.finite(e.vector)}isZero(e){return this.context.verb.core.Vec.isZero(e.vector)}lerp(e){return this.context.verb.core.Vec.lerp(e.fraction,e.first,e.second)}max(e){return this.context.verb.core.Vec.max(e.vector)}min(e){return this.context.verb.core.Vec.min(e.vector)}mul(e){return e.vector.map((t=>t*e.scalar))}neg(e){return this.context.verb.core.Vec.neg(e.vector)}normSquared(e){return this.context.verb.core.Vec.normSquared(e.vector)}norm(e){return this.context.verb.core.Vec.norm(e.vector)}normalized(e){return this.context.verb.core.Vec.normalized(e.vector)}onRay(e){return this.context.verb.core.Vec.onRay(e.point,e.vector,e.distance)}vectorXYZ(e){return[e.x,e.y,e.z]}vectorXY(e){return[e.x,e.y]}range(e){return this.context.verb.core.Vec.range(e.max)}signedAngleBetween(e){return $r.FromRadians(this.context.verb.core.Vec.signedAngleBetween(e.first,e.second,e.reference)).degrees()}span(e){return this.context.verb.core.Vec.span(e.min,e.max,e.step)}sub(e){return this.context.verb.core.Vec.sub(e.first,e.second)}sum(e){return this.context.verb.core.Vec.sum(e.vector)}}class pz{constructor(e){this.context=e,this.tolerance=1e-5,this.getArrayDepth=e=>Array.isArray(e)?1+Math.max(...e.map(this.getArrayDepth)):0}createOrUpdateSurfaceMesh(e,t,i,s,r,n){const o=()=>{const s=new Wn;s.positions=e.positions,s.indices=e.indices,s.normals=e.normals,s.applyToMesh(t,i)};if(t&&i)t.dispose(),o(),t.flipFaces(!1);else{let e=null;r&&(e=this.context.scene),t=new ha(`surface${Math.random()}`,e),o(),t.flipFaces(!1),s&&(t.material=s)}return s&&(t.material=s),n&&(t.isVisible=!1),t.isPickable=!1,t}createOrUpdateSurfacesMesh(e,t,i,s,r,n){const o=()=>{const s=e.pop(),r=new Wn;r.positions=s.positions,r.indices=s.indices,r.normals=s.normals,r.uvs=s.uvs;const n=[];e.forEach((e=>{const t=new Wn;t.positions=e.positions,t.indices=e.indices,t.normals=e.normals,t.uvs=e.uvs,n.push(t)})),r.merge(n),r.applyToMesh(t,i)};if(t&&i)t.dispose(),o(),t.flipFaces(!1);else{let e=null;r&&(e=this.context.scene),t=new ha(`surface${Math.random()}`,e),o(),t.flipFaces(!1),s&&(t.material=s)}return s&&(t.material=s),n&&(t.isVisible=!1),t.isPickable=!1,t}transformControlPoints(e,t){return this.getFlatTransformations(e).forEach((e=>{t=this.transformPointsByMatrixArray(t,e)})),t}getFlatTransformations(e){let t=[];return 3===this.getArrayDepth(e)?e.forEach((e=>{t.push(...e)})):t=e,t}transformPointsByMatrixArray(e,t){const i=me.FromArray(t);return this.transformPointsByMatrix(e,i)}transformPointsByMatrix(e,t){const i=[];for(const s of e){const e=new _e(s[0],s[1],s[2]),r=_e.TransformCoordinates(e,t);i.push([r.x,r.y,r.z])}return i}edgesRendering(e,t,i,s){e.enableEdgesRendering(),e.edgesWidth=t;const r=Array.isArray(s)?Ee.FromHexString(s[0]):Ee.FromHexString(s);e.color=r,e.edgesColor=new Ae(r.r,r.g,r.b,i)}drawPolyline(e,t,i,s,r,n){return this.drawPolylines(e,[t],i,s,r,n)}drawPolylines(e,t,i,s,r,n){var o;const a=[];if(t&&t.length>0){t.forEach((e=>{const t=e.map((e=>2===e.length?[e[0],e[1],0]:e));a.push(t.flat())}));const l=s/100,h=Array.isArray(n)?Ee.FromHexString(n[0]):Ee.FromHexString(n);if(e&&i){if(!(null===(o=null==e?void 0:e.metadata)||void 0===o?void 0:o.linesForRenderLengths.some(((e,t)=>e!==a[t].length))))return e.setPoints(a),e;e.dispose(),(e=this.createGreasedPolylines(i,a,l,h,r)).metadata={linesForRenderLengths:a.map((e=>e.length))}}else(e=this.createGreasedPolylines(i,a,l,h,r)).metadata={linesForRenderLengths:a.map((e=>e.length))};return e}}createGreasedPolylines(e,t,i,s,r){const n=wS(`lineSystem${Math.random()}`,{points:t,updatable:e},{width:i,color:s},this.context.scene);return n.material.alpha=r,n}removeConsecutiveDuplicates(e,t=!0){const i=[];if(e.length>1){for(let t=1;ti[0])))):i=e.points.map((()=>e.colours)),e.pointsMesh&&e.updatable?e.pointsMesh.getChildMeshes().length===t.length?this.updatePointsInstances(e.pointsMesh,t):(e.pointsMesh.dispose(),e.pointsMesh=this.createPointSpheresMesh(`pointsMesh${Math.random()}`,t,i,e.opacity,e.size,e.updatable)):e.pointsMesh=this.createPointSpheresMesh(`pointsMesh${Math.random()}`,t,i,e.opacity,e.size,e.updatable),e.pointsMesh}updatePointsInstances(e,t){const i=e.getChildMeshes(),s={};t.forEach(((e,t)=>{s[t]=new _e(e[0],e[1],e[2])})),i.forEach((e=>{e.position=s[e.metadata.index]}))}setUpPositionsAndColours(e,t){const i=[],s=[];return t.length===e.length?e.forEach(((e,r)=>{i.push(...e),s.push(t[r].r,t[r].g,t[r].b,1)})):e.forEach(((e,r)=>{i.push(...e),s.push(t[0].r,t[0].g,t[0].b,1)})),{positions:i,colors:s}}createPointSpheresMesh(e,t,i,s,r,n){const o=t.map(((e,t)=>({position:e,color:i[t],index:t}))),a=Array.from(new Set(i)),l=a.map(((e,t)=>{const i=new cu(`mat${Math.random()}`,this.context.scene);i.disableLighting=!0,i.emissiveColor=Ee.FromHexString(e),i.alpha=s;const r=o.filter((t=>t.color===e));return{hex:a,material:i,positions:r}})),h=new ha(e,this.context.scene);return l.forEach((e=>{const t=R_.CreateSphere(`sphere${Math.random()}`,{diameter:r,segments:6,updatable:n},this.context.scene);t.material=e.material,t.isVisible=!1,e.positions.forEach(((e,i)=>{const s=t.createInstance(`sphere-${i}-${Math.random()}`);s.position=new _e(e.position[0],e.position[1],e.position[2]),s.metadata={index:e.index},s.parent=h,s.isVisible=!0}))})),h}}class fz{constructor(e,t,i){this.context=e,this.geometryHelper=t,this.line=i}drawPoint(e){return this.geometryHelper.drawPoint(e)}drawPoints(e){return this.geometryHelper.drawPoints(e)}drawPointsAsync(e){return Promise.resolve(this.drawPoints(e))}transformPoint(e){const t=e.transformation;let i=[e.point];return i=this.geometryHelper.transformControlPoints(t,i),i[0]}transformPoints(e){return this.geometryHelper.transformControlPoints(e.transformation,e.points)}transformsForPoints(e){if(e.points.length!==e.transformation.length)throw new Error("You must provide equal nr of points and transformations");return e.points.map(((t,i)=>this.geometryHelper.transformControlPoints(e.transformation[i],[t])[0]))}closestPointFromPointsDistance(e){return this.closestPointFromPointData(e).distance}closestPointFromPointsIndex(e){return this.closestPointFromPointData(e).index}closestPointFromPoints(e){return this.closestPointFromPointData(e).point}distance(e){const t=e.endPoint[0]-e.startPoint[0],i=e.endPoint[1]-e.startPoint[1],s=e.endPoint[2]-e.startPoint[2];return Math.sqrt(t*t+i*i+s*s)}distancesToPoints(e){return e.endPoints.map((t=>this.distance({startPoint:e.startPoint,endPoint:t})))}multiplyPoint(e){const t=[];for(let i=0;i{t.push(e[0]),i.push(e[1]),s.push(e[2])})),[t.reduce(((e,t)=>e+t),0)/e.points.length,i.reduce(((e,t)=>e+t),0)/e.points.length,s.reduce(((e,t)=>e+t),0)/e.points.length]}pointXYZ(e){return[e.x,e.y,e.z]}pointXY(e){return[e.x,e.y]}spiral(e){const t=e.phi,i=Math.log(t)/(Math.PI/e.widening),s=[],r=e.radius/e.numberPoints;for(let t=0;t{i[r]=[s[0]-e,s[1]-t,0]}))}return e.pointsOnGround&&i.forEach(((e,t)=>{i[t]=[e[0],0,e[1]]})),i}closestPointFromPointData(e){let t,i,s=Number.MAX_SAFE_INTEGER;for(let r=0;r{e(t)}))}}class gz{create(e){return e.text}split(e){return e.text.split(e.separator)}replaceAll(e){return e.text.split(e.search).join(e.replaceWith)}join(e){return e.list.join(e.separator)}toString(e){return e.item.toString()}toStringEach(e){return e.list.map((e=>e.toString()))}}class vz{constructor(){}}class xz{constructor(){this.assetManager=new vz}getFile(e){return this.assetManager.getAsset(e.fileName)}getLocalFile(e){return this.assetManager.getLocalAsset(e.fileName)}createObjectURL(e){return URL.createObjectURL(e.file)}createObjectURLs(e){return e.files.map((e=>URL.createObjectURL(e)))}}class bz{constructor(e){this.context=e}hexColor(e){return e.color}hexToRgb(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e.color);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:void 0}rgbToHex(e){const t=e.r,i=e.g,s=e.b;return`#${Number(16777216+65536*t+256*i+s).toString(16).substring(1,7)}`}hexToRgbMapped(e){const t=this.hexToRgb(e);return{r:this.context.remap(t.r,0,255,e.from,e.to),g:this.context.remap(t.g,0,255,e.from,e.to),b:this.context.remap(t.b,0,255,e.from,e.to)}}getRedParam(e){return this.hexToRgbMapped(e).r}getGreenParam(e){return this.hexToRgbMapped(e).g}getBlueParam(e){return this.hexToRgbMapped(e).b}rgbToRed(e){return e.rgb.r}rgbToGreen(e){return e.rgb.g}rgbToBlue(e){return e.rgb.b}}class Tz{constructor(){this.canvasZoneClass="canvasZone",this.tolerance=1e-5,this.snapTolerance=1e-5,this.tagBag=[],this.timeoutBag=[],this.intervalBag=[],this.renderLoopBag=[],this.keyDownBag=[],this.keyUpBag=[],this.keyPressBag=[],this.currentlyPressedKeys=[]}getFile(e){return new Promise(((t,i)=>{if(e){const s=new FileReader;s.readAsText(e,"UTF-8"),s.onload=e=>{const i=e.target.result;t(i)},s.onerror=e=>{i()}}else i()}))}remap(e,t,i,s,r){return(e-t)/(i-t)*(r-s)+s}}!function(e){e[e.loading=0]="loading",e[e.loaded=1]="loaded",e[e.initialised=2]="initialised",e[e.computing=3]="computing"}(nz||(nz={}));class yz{constructor(){this.jscadWorkerState=new iV,this.promisesMade=[]}jscadWorkerAlreadyInitialised(){return!!this.jscadWorker}setJscadWorker(e){this.jscadWorker=e,this.jscadWorker.onmessage=({data:e})=>{if("jscad-initialised"===e)this.jscadWorkerState.next({state:nz.initialised});else if("busy"===e)this.jscadWorkerState.next({state:nz.computing});else{const t=this.promisesMade.find((t=>t.uid===e.uid));t&&e.result&&!e.error?t.resolve(e.result):e.error&&(this.errorCallback&&this.errorCallback(e.error),t.reject(e.error)),this.promisesMade=this.promisesMade.filter((t=>t.uid!==e.uid)),0===this.promisesMade.length?this.jscadWorkerState.next({state:nz.loaded}):this.jscadWorkerState.next({state:nz.computing})}}}cleanPromisesMade(){this.promisesMade=[]}genericCallToWorkerPromise(e,t){const i=`call${Math.random()}${Date.now()}`,s={uid:i},r=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return s.promise=r,this.promisesMade.push(s),this.jscadWorker.postMessage({action:{functionName:e,inputs:t},uid:i}),r}startedTheRun(){return this.genericCallToWorkerPromise("startedTheRun",{})}cleanAllCache(){return this.genericCallToWorkerPromise("cleanAllCache",{})}}var Sz=i(258);class Cz{constructor(e){this.context=e}stringify(e){return JSON.stringify(e.json)}parse(e){return JSON.parse(e.text)}query(e){return this.context.jsonpath.query(e.json,e.query)}setValue(e){const t=Object.assign({},structuredClone(e.json));return this.context.jsonpath.value(t,e.path,e.value),t}setValuesOnPaths(e){const t=Object.assign({},structuredClone(e.json));return e.paths.forEach(((i,s)=>{this.context.jsonpath.value(t,i,e.values[s])})),t}paths(e){return this.context.jsonpath.paths(e.json,e.query)}pathsAsStrings(e){return this.context.jsonpath.paths(e.json,e.query).map((e=>this.context.jsonpath.stringify(e)))}createEmpty(){return{}}previewAndSaveJson(e){e.json&&this.context.promptPrintSave({text:e.json,isJson:!0,hidden:!1})}previewJson(e){e.json&&this.context.promptPrint({text:e.json,isJson:!0,hidden:!1})}}var Ez=i(615);class Az{boolean(e){return e.boolean}randomBooleans(e){const t=[];for(let i=0;i{if(ie.thresholdTotalFalse)t.push(!1);else{const s=i-e.thresholdTotalTrue,r=(e.thresholdTotalFalse-e.thresholdTotalTrue)/e.nrLevels,n=Math.ceil(s/r)/e.nrLevels;Math.random()>n?t.push(!0):t.push(!1)}})),t}thresholdBooleanList(e){const t=[];return e.numbers.forEach((i=>{i!e)):t}thresholdGapsBooleanList(e){const t=[];return e.numbers.forEach((i=>{let s=!1;e.gapThresholds.forEach((e=>{const r=e[0],n=e[1];i>=r&&i<=n&&(t.push(!0),s=!0)})),s||t.push(!1)})),e.inverse?t.map((e=>!e)):t}not(e){return!e.boolean}notList(e){return e.booleans.map((e=>!e))}compare(e){switch(e.operator){case"==":return e.first==e.second;case"!=":return e.first!=e.second;case"===":return e.first===e.second;case"!==":return e.first!==e.second;case"<":return e.first":return e.first>e.second;case">=":return e.first>=e.second;default:return!1}}valueGate(e){return e.boolean?e.value:void 0}firstDefinedValueGate(e){let t;return t=void 0!==e.value1?e.value1:void 0!==e.value2?e.value2:void 0,t}}class Pz{constructor(){this.context=new Tz,this.jscadWorkerManager=new yz,this.occtWorkerManager=new rV;const e=new pz(this.context);this.color=new bz(this.context),this.babylon=new HU(this.context,e,this.color),this.vector=new _z(this.context),this.line=new lz(this.context,e),this.point=new fz(this.context,e,this.line),this.polyline=new uz(this.context,e),this.verb=new AG(this.context,e),this.jscad=new hG(this.jscadWorkerManager,this.context,e),this.tag=new dz(this.context),this.time=new mz(this.context),this.occt=new pG(this.context,this.occtWorkerManager,e,this.jscad.text,this.vector),this.asset=new xz,this.math=new cz,this.logic=new Az,this.json=new Cz(this.context),this.text=new gz,this.lists=new hz,this.draw=new az(this.point,this.line,this.polyline,this.babylon.node,this.verb.curve,this.verb.surface,this.jscad,this.occt,this.tag,this.context)}init(e,t,i,s){this.context.scene=e,s&&(this.context.havokPlugin=s);const r={geom:Sz.geom,core:Sz.core};this.context.verb=r,this.context.jsonpath=Ez,t&&this.occtWorkerManager.setOccWorker(t),i&&this.jscadWorkerManager.setJscadWorker(i)}}const Iz="assets/textures";class Rz{constructor(e){this.name="",this.scene=void 0,this.wAng=0,this.uScale=1,this.vScale=1,this.color=void 0,this.albedoTextureUrl=void 0,this.microSurfaceTextureUrl=void 0,this.bumpTextureUrl=void 0,this.metallic=.1,this.roughness=.9,this.zOffset=2,Object.keys(this).forEach((t=>this[t]=e[t]))}}class Mz{static simpleBlackMaterial(e){const t=new zg("blackMaterial"+Math.random(),e);return t.albedoColor=new Ee(0,0,0),t.metallic=0,t.roughness=.7,t.zOffset=2,t}static rock1Material(e,t,i){const s=new Rz({name:"wood1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.rock1.default.albedo,bumpTextureUrl:Mz.textures.rock1.microSurfaceTexture,microSurfaceTextureUrl:Mz.textures.rock1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(s)}static wood1Material(e,t,i){const s=new Rz({name:"wood1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.wood1.light.albedo,bumpTextureUrl:Mz.textures.wood1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(s)}static wood2Material(e,t,i){const s=new Rz({name:"wood2",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.wood2.light.albedo,microSurfaceTextureUrl:Mz.textures.wood2.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(s)}static wood3Material(e,t,i){const s=new Rz({name:"wood3",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.wood1.dark.albedo,microSurfaceTextureUrl:Mz.textures.wood1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(s)}static brownPlanks(e,t,i){const s=new Rz({name:"brownPlanks",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.brownPlanks.light.albedo,microSurfaceTextureUrl:Mz.textures.brownPlanks.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(s)}static woodenPlanks(e,t,i){const s=new Rz({name:"woodenPlanks",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.woodenPlanks.light.albedo,microSurfaceTextureUrl:Mz.textures.woodenPlanks.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(s)}static glass(e,t){const i=new zg("faceGlassMaterial"+Math.random(),e);return i.albedoColor=Ee.FromHexString(t),i.ambientColor=Ee.FromHexString("#ffffff"),i.metallic=.8,i.roughness=.1,i.zOffset=1,i.alpha=.5,i}static brushedConcrete(e,t,i){const s=new Rz({name:"brushedConcrete",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.brushedConcrete.grey.albedo,microSurfaceTextureUrl:Mz.textures.brushedConcrete.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(s)}static metal1(e,t,i){const s=new Rz({name:"metal1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.metal1.light.albedo,microSurfaceTextureUrl:Mz.textures.metal1.microSurfaceTexture,bumpTextureUrl:Mz.textures.metal1.light.roughness,metallic:.3,roughness:.6,zOffset:2});return Mz.createMaterial(s)}static roughPlastic(e,t){const i=new Rz({name:"roughPlastic-"+t,color:t,scene:e,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(i)}static createMaterial(e){const t=new zg(e.name,e.scene);return e.color&&(t.albedoColor=Ee.FromHexString(e.color)),e.albedoTextureUrl&&(t.albedoTexture=Mz.createTexture(e.albedoTextureUrl,e)),e.microSurfaceTextureUrl&&(t.microSurfaceTexture=Mz.createTexture(e.microSurfaceTextureUrl,e)),e.bumpTextureUrl&&(t.bumpTexture=Mz.createTexture(e.bumpTextureUrl,e)),t.metallic=e.metallic,t.roughness=e.roughness,t.zOffset=e.zOffset,t}static createTexture(e,t){const i=new Pa(e,t.scene);return i.uScale=t.uScale,i.vScale=t.vScale,i.wAng=t.wAng,i}}Mz.textures={wood1:{microSurfaceTexture:`${Iz}/Wood048_1K/Wood048_1K_NormalGL.jpg`,light:{albedo:`${Iz}/Wood048_1K/Wood048_1K_Light.jpg`},dark:{albedo:`${Iz}/Wood048_1K/Wood048_1K_Color_Dark.jpg`}},wood2:{microSurfaceTexture:`${Iz}/Wood084_1K/Wood084A_1K_NormalGL.jpg`,light:{albedo:`${Iz}/Wood084_1K/Wood084A_1K_Color.jpg`}},metal1:{microSurfaceTexture:`${Iz}/metal_1/Metal029_1K_Displacement.jpg`,light:{albedo:`${Iz}/metal_1/Metal029_1K_Color.jpg`,normalGL:`${Iz}/metal_1/Metal029_1K_NormalGL.jpg`,roughness:`${Iz}/metal_1/Metal029_1K_Roughness.jpg`,metalness:`${Iz}/metal_1/Metal029_1K_Metalness.jpg`}},brownPlanks:{microSurfaceTexture:`${Iz}/brown_planks/brown_planks_05_nor_gl_1k.jpg`,light:{albedo:`${Iz}/brown_planks/brown_planks_05_diff_1k.jpg`}},woodenPlanks:{microSurfaceTexture:`${Iz}/wooden_planks/wooden_planks_nor_gl_1k.jpg`,light:{albedo:`${Iz}/wooden_planks/wooden_planks_diff_1k.jpg`}},brushedConcrete:{microSurfaceTexture:`${Iz}/brushed_concrete/brushed_concrete_03_nor_gl_1k.jpg`,sand:{albedo:`${Iz}/brushed_concrete/brushed_concrete_03_diff_1k.jpg`},grey:{albedo:`${Iz}/brushed_concrete/brushed_concrete_03_diff_grey_1k.jpg`}},rock1:{microSurfaceTexture:`${Iz}/Rock044_1K/Rock044_1K_NormalGL.jpg`,default:{albedo:`${Iz}/Rock044_1K/Rock044_1K_Color.jpg`,roughness:`${Iz}/Rock044_1K/Rock044_1K_Roughness.jpg`}}};var Oz=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class Dz{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return Oz(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.wingtipVilla",e);if(t){const e=t.shapes.find((e=>e.id===t.data.roof.compound)),i=t.shapes.find((e=>e.id===t.data.walls.compound));return{type:t.data.type,name:t.data.name,compound:t.compound,roof:{compound:e.shape,shapes:t.shapes.filter((e=>t.data.roof.shapes.includes(e.id))).map((e=>e.shape))},walls:{compound:i.shape,shapes:t.shapes.filter((e=>t.data.walls.shapes.includes(e.id))).map((e=>e.shape))},stick:{shape:t.shapes.find((e=>e.id===t.data.stick.shape)).shape},floor:{shape:t.shapes.find((e=>e.id===t.data.floor.shape)).shape},chimney:{shape:t.shapes.find((e=>e.id===t.data.chimney.shape)).shape},basicPoints:t.data.basicPoints}}}))}drawModel(e){return Oz(this,void 0,void 0,(function*(){const t=new ha("brepMesh"+Math.random(),this.context.scene),i=new mU.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#ffffff";const s=yield this.draw.drawAnyAsync({entity:e.roof.compound,options:i}),r=s.getChildMeshes(),n=r[0],o=r[1],a=yield this.draw.drawAnyAsync({entity:e.walls.compound,options:i}),l=a.getChildMeshes(),h=l[0],c=l[1],u=yield this.draw.drawAnyAsync({entity:e.floor.shape,options:i}),d=u.getChildMeshes(),_=d[0],p=d[1],f=yield this.draw.drawAnyAsync({entity:e.stick.shape,options:i}),m=f.getChildMeshes(),g=m[0],v=m[1],x=yield this.draw.drawAnyAsync({entity:e.chimney.shape,options:i}),b=x.getChildMeshes(),T=b[0],y=b[1],S=new Pa("assets/textures/Wood048_1K/Wood048_1K_Red.jpg",this.context.scene),C=new Pa("assets/textures/Wood048_1K/Wood048_1K_Color_Dark.jpg",this.context.scene),E=new Pa("assets/textures/Wood048_1K/Wood048_1K_NormalGL.jpg",this.context.scene);S.uScale=.3,S.vScale=.3,S.wAng=Math.PI/2,C.uScale=.3,C.vScale=.3,C.wAng=Math.PI/2,E.uScale=.3,E.vScale=.3,E.wAng=Math.PI/2;const A=new zg("wood-red",this.context.scene);A.albedoTexture=S,A.microSurfaceTexture=E,A.metallic=0,A.roughness=1,A.zOffset=2;const P=new zg("wood-dark",this.context.scene);return P.albedoTexture=C,P.microSurfaceTexture=E,P.metallic=0,P.roughness=1,P.zOffset=2,n.material=A,h.material=Mz.wood1Material(this.context.scene,Math.PI/2,.3),_.material=A,g.material=A,T.material=P,n.parent=t,h.parent=t,_.parent=t,g.parent=t,T.parent=t,o.parent=t,c.parent=t,p.parent=t,v.parent=t,y.parent=t,s.dispose(),u.dispose(),a.dispose(),f.dispose(),x.dispose(),t}))}dispose(e){return Oz(this,void 0,void 0,(function*(){const t=[e.compound,e.chimney.shape,e.floor.shape,...e.roof.shapes,...e.walls.shapes,e.stick.shape];yield this.occt.deleteShapes({shapes:t})}))}}var wz=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class Nz{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}dispose(e){return wz(this,void 0,void 0,(function*(){const t=[e.compound,e.floor.shape,...e.roof.shapes,...e.walls.shapes,e.stick.shape];yield this.occt.deleteShapes({shapes:t})}))}create(e){return wz(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.chirpyChalet",e);if(t){const e=t.shapes.find((e=>e.id===t.data.roof.compound)),i=t.shapes.find((e=>e.id===t.data.walls.compound));return{type:t.data.type,name:t.data.name,compound:t.compound,roof:{compound:e.shape,shapes:t.shapes.filter((e=>t.data.roof.shapes.includes(e.id))).map((e=>e.shape))},walls:{compound:i.shape,shapes:t.shapes.filter((e=>t.data.walls.shapes.includes(e.id))).map((e=>e.shape))},stick:{shape:t.shapes.find((e=>e.id===t.data.stick.shape)).shape},floor:{shape:t.shapes.find((e=>e.id===t.data.floor.shape)).shape},basicPoints:t.data.basicPoints}}}))}drawModel(e){return wz(this,void 0,void 0,(function*(){const t=new ha("brepMesh"+Math.random(),this.context.scene),i=new mU.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#ffffff";const s=yield this.draw.drawAnyAsync({entity:e.roof.compound,options:i}),r=s.getChildMeshes()[0],n=yield this.draw.drawAnyAsync({entity:e.walls.compound,options:i}),o=n.getChildMeshes()[0],a=yield this.draw.drawAnyAsync({entity:e.floor.shape,options:i}),l=a.getChildMeshes()[0],h=yield this.draw.drawAnyAsync({entity:e.stick.shape,options:i}),c=h.getChildMeshes()[0],u=new Pa("assets/textures/Wood048_1K/Wood048_1K_Color.jpg",this.context.scene),d=new Pa("assets/textures/Wood048_1K/Wood048_1K_Light.jpg",this.context.scene),_=new Pa("assets/textures/Wood048_1K/Wood048_1K_NormalGL.jpg",this.context.scene);d.uScale=.3,d.vScale=.3,d.wAng=Math.PI/2,u.uScale=.3,u.vScale=.3,u.wAng=Math.PI/2,_.uScale=.3,_.vScale=.3,_.wAng=Math.PI/2;const p=new zg("roof",this.context.scene);p.albedoTexture=u,p.microSurfaceTexture=_,p.metallic=0,p.roughness=1,p.zOffset=2;const f=new zg("walls",this.context.scene);return f.albedoTexture=d,f.microSurfaceTexture=_,f.metallic=0,f.roughness=1,f.zOffset=2,r.material=p,o.material=f,l.material=p,c.material=p,s.setParent(t),a.setParent(t),n.setParent(t),h.setParent(t),t}))}}class Fz{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.wingtipVilla=new Dz(this.occWorkerManager,this.context,this.draw,this.occt),this.chirpyChalet=new Nz(this.occWorkerManager,this.context,this.draw,this.occt)}}class Lz{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.birdhouses=new Fz(this.occWorkerManager,this.context,this.draw,this.occt)}}var Bz,kz,Vz,Uz,Gz,zz,Wz=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class Hz{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return Wz(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.serenitySwirl",e);return t?{type:t.data.type,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e,t=.003){return Wz(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s}),n=new zg("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new Ee(1,1,1),n.ambientColor=Ee.FromHexString("#ffffff"),n.metallic=0,n.roughness=.7,n.zOffset=1,r.getChildMeshes()[0].material=n,r.material=n,r.parent=i,i}))}dispose(e){return Wz(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}!function(e){e.low="low",e.middle="middle",e.high="high"}(Bz||(Bz={}));class Xz{constructor(){this.lod=Bz.low}}class Yz{}class Qz{constructor(e,t,i,s,r,n,o,a,l){this.swirl=.6,this.nrOfDivisions=10,this.addRadiusNarrow=.4,this.addRadiusWide=.2,this.addMiddleHeight=1.6,this.addTopHeight=1.5,this.thickness=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.swirl=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.addRadiusNarrow=i),void 0!==s&&(this.addRadiusWide=s),void 0!==r&&(this.addMiddleHeight=r),void 0!==n&&(this.addTopHeight=n),void 0!==o&&(this.thickness=o),void 0!==a&&(this.rotation=a),void 0!==l&&(this.origin=l)}}class jz{constructor(){this.type="parametric-model",this.name="serenitySwirl"}}class Kz{}class $z{constructor(e,t,i,s,r,n,o,a,l,h,c,u){this.profilePoints=[[2,0,0],[4,5,0],[1.5,10,0],[3,14,0]],this.nrOfSides=6,this.nrOfVerticalArches=4,this.archCenterThickness=.8,this.edgesThickness=.2,this.thickness=1,this.baseHeight=.4,this.patchHoles=!0,this.lod=Bz.high,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],this.scale=[1,1,1],void 0!==e&&(this.nrOfSides=e),void 0!==t&&(this.nrOfVerticalArches=t),void 0!==i&&(this.archCenterThickness=i),void 0!==s&&(this.edgesThickness=s),void 0!==r&&(this.thickness=r),void 0!==n&&(this.baseHeight=n),void 0!==o&&(this.patchHoles=o),void 0!==a&&(this.lod=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.origin=h),void 0!==c&&(this.direction=c),void 0!==u&&(this.scale=u)}}class qz{constructor(){this.type="parametric-model",this.name="arabicArchway"}}class Zz{}class Jz{}class eW{}class tW{constructor(e,t,i,s,r,n,o,a){this.textHeading="LOVE YOU",this.textName="NORA",this.fullModel=!0,this.thickness=6,this.decorationThickness=1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textHeading=e),void 0!==t&&(this.textName=t),void 0!==i&&(this.fullModel=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.decorationThickness=r),void 0!==n&&(this.rotation=n),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a)}}class iW{constructor(){this.type="parametric-model",this.name="eternalLove"}}class sW{}class rW{constructor(e,t,i,s,r,n,o,a,l,h,c,u){this.height=6,this.radiusBottom=4,this.radiusTopOffset=2,this.thickness=.6,this.fillet=.2,this.nrOfHandles=1,this.handleDist=2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==i&&(this.radiusTopOffset=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.fillet=r),void 0!==n&&(this.nrOfHandles=n),void 0!==o&&(this.handleDist=o),void 0!==a&&(this.precision=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.scale=h),void 0!==c&&(this.origin=c),void 0!==u&&(this.direction=u)}}class nW{constructor(){this.type="parametric-model",this.name="calmCup"}}class oW{}class aW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v,x,b){this.height=8,this.radiusBottom=4,this.radiusTopOffset=2,this.radiusMidOffset=2,this.rotationTopAngle=20,this.rotationMidAngle=20,this.nrSkinCellsVertical=5,this.nrSkinCellsHorizontal=10,this.nrSkinCellDivisionsTop=1,this.nrSkinCellDivisionsBottom=3,this.skinCellOuterHeight=.4,this.skinCellInnerHeight=.3,this.skinCellBottomHeight=.4,this.skinCellTopHeight=.4,this.thickness=.6,this.bottomThickness=1,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==i&&(this.radiusTopOffset=i),void 0!==s&&(this.radiusMidOffset=s),void 0!==r&&(this.rotationTopAngle=r),void 0!==n&&(this.rotationMidAngle=n),void 0!==o&&(this.nrSkinCellsVertical=o),void 0!==a&&(this.nrSkinCellsHorizontal=a),void 0!==l&&(this.nrSkinCellDivisionsTop=l),void 0!==h&&(this.nrSkinCellDivisionsBottom=h),void 0!==c&&(this.skinCellOuterHeight=c),void 0!==u&&(this.skinCellInnerHeight=u),void 0!==d&&(this.skinCellBottomHeight=d),void 0!==_&&(this.skinCellTopHeight=_),void 0!==p&&(this.thickness=p),void 0!==f&&(this.bottomThickness=f),void 0!==m&&(this.precision=m),void 0!==g&&(this.rotation=g),void 0!==v&&(this.scale=v),void 0!==x&&(this.origin=x),void 0!==b&&(this.direction=b)}}class lW{constructor(){this.type="parametric-model",this.name="dragonCup"}}class hW{}class cW{}class uW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g){this.heightBottom=5,this.heightTop=16,this.widthBack=25,this.widthFront=10,this.length=16,this.backOffset=6,this.thickness=.4,this.applyOrnaments=!1,this.filletRadius=2,this.phoneHeight=16.8,this.phoneWidth=7.8,this.phoneThickness=.7,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.heightBottom=e),void 0!==t&&(this.heightTop=t),void 0!==i&&(this.widthBack=i),void 0!==s&&(this.widthFront=s),void 0!==r&&(this.length=r),void 0!==n&&(this.backOffset=n),void 0!==o&&(this.thickness=o),void 0!==a&&(this.applyOrnaments=a),void 0!==l&&(this.filletRadius=l),void 0!==h&&(this.phoneHeight=h),void 0!==c&&(this.phoneWidth=c),void 0!==u&&(this.phoneThickness=u),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdges=_),void 0!==p&&(this.rotation=p),void 0!==f&&(this.scale=f),void 0!==m&&(this.origin=m),void 0!==g&&(this.direction=g)}}class dW{constructor(){this.type="parametric-model",this.name="phoneNest"}}class _W extends Yz{}class pW{}class fW extends Yz{}class mW{}class gW{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class vW{}class xW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v){this.textTop="Pepper",this.textFront="For Your Spicy Needs",this.nrSides=4,this.nrOffsets=1,this.height=6,this.radiusBase=4,this.radiusOffset=2,this.coverHeight=1,this.baseHeight=1,this.thickness=.6,this.ornamentalThickness=.1,this.nrOrnamnetsPerSide=10,this.invertOrnaments=!1,this.fillet=.2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textTop=e),void 0!==t&&(this.textFront=t),void 0!==i&&(this.nrSides=i),void 0!==s&&(this.nrOffsets=s),void 0!==r&&(this.height=r),void 0!==n&&(this.coverHeight=n),void 0!==o&&(this.baseHeight=o),void 0!==a&&(this.radiusBase=a),void 0!==l&&(this.radiusOffset=l),void 0!==h&&(this.thickness=h),void 0!==c&&(this.ornamentalThickness=c),void 0!==u&&(this.nrOrnamnetsPerSide=u),void 0!==d&&(this.invertOrnaments=d),void 0!==_&&(this.fillet=_),void 0!==p&&(this.precision=p),void 0!==f&&(this.rotation=f),void 0!==m&&(this.scale=m),void 0!==g&&(this.origin=g),void 0!==v&&(this.direction=v)}}class bW{constructor(){this.type="parametric-model",this.name="spicyBox"}}class TW{}class yW{}class SW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v,x,b,T,y,S,C,E,A,P,I,R){this.widthFirstWing=4,this.lengthFirstWing=10,this.terraceWidth=3,this.widthSecondWing=5,this.lengthSecondWing=10,this.heightWalls=3,this.roofAngleFirstWing=15,this.roofAngleSecondWing=25,this.roofOffset=.5,this.roofInsideOverhang=.5,this.roofMaxDistAttachmentBeams=.8,this.roofAttachmentBeamWidth=.2,this.roofAttachmentBeamHeight=.05,this.roofOutsideOverhang=.5,this.columnSize=.3,this.ceilingBeamHeight=.25,this.ceilingBeamWidth=.1,this.nrCeilingBeamsBetweenColumns=3,this.distBetweenColumns=2,this.floorHeight=.1,this.groundLevel=.6,this.facadePanelThickness=.05,this.windowWidthOffset=.1,this.windowHeightOffset=.2,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05,this.lod=Bz.high,this.skinOpacity=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.widthFirstWing=e),void 0!==t&&(this.lengthFirstWing=t),void 0!==i&&(this.terraceWidth=i),void 0!==s&&(this.widthSecondWing=s),void 0!==r&&(this.lengthSecondWing=r),void 0!==n&&(this.heightWalls=n),void 0!==o&&(this.roofAngleFirstWing=o),void 0!==a&&(this.roofAngleSecondWing=a),void 0!==l&&(this.roofOffset=l),void 0!==h&&(this.roofInsideOverhang=h),void 0!==c&&(this.roofMaxDistAttachmentBeams=c),void 0!==u&&(this.roofAttachmentBeamWidth=u),void 0!==d&&(this.roofAttachmentBeamHeight=d),void 0!==_&&(this.roofOutsideOverhang=_),void 0!==p&&(this.columnSize=p),void 0!==f&&(this.ceilingBeamHeight=f),void 0!==m&&(this.ceilingBeamWidth=m),void 0!==g&&(this.nrCeilingBeamsBetweenColumns=g),void 0!==v&&(this.distBetweenColumns=v),void 0!==x&&(this.floorHeight=x),void 0!==b&&(this.groundLevel=b),void 0!==T&&(this.facadePanelThickness=T),void 0!==y&&(this.windowWidthOffset=y),void 0!==S&&(this.windowHeightOffset=S),void 0!==C&&(this.windowFrameThickness=C),void 0!==E&&(this.windowGlassFrameThickness=E),void 0!==A&&(this.lod=A),void 0!==P&&(this.skinOpacity=P),void 0!==I&&(this.rotation=I),void 0!==R&&(this.origin=R)}}class CW{constructor(){this.type="parametric-model",this.name="zenHideout"}}class EW{}class AW{}class PW{constructor(){this.wallThickness=.4,this.facadePanelThickness=.05,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThckness=.05,this.height=3,this.lengthFirst=1,this.lengthSecond=2,this.rotation=0}}class IW{constructor(){this.thickness=.3,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThickness=.05,this.height=3,this.width=1,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0]}}class RW extends IW{}class MW extends PW{}class OW{constructor(){this.name="sandwitch-panel",this.createWindow=!0,this.createInnerPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelWidth=.4,this.exteriorPanelHeight=3,this.exteriorPanelThickness=.05,this.exteriorPanelBottomOffset=0,this.interiorPanelWidth=.4,this.interiorPanelHeight=3,this.interiorPanelThickness=.05,this.interiorPanelBottomOffset=0,this.windowWidthOffset=0,this.windowHeightOffset=0,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05}}class DW{constructor(){this.name="sandwitch-panel-flex",this.createInteriorPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelThickness=.05,this.interiorPanelThickness=.05,this.interiorPanelPolygonPoints=[],this.exteriorPanelPolygonPoints=[]}}class wW extends OW{}class NW extends DW{}class FW{}class LW{}class BW{}class kW{}class VW{}class UW{}class GW{constructor(){this.invert=!1,this.widthFirstLanding=1,this.widthSecondLanding=1,this.lengthFirstWing=2,this.lengthSecondWing=1,this.maxWishedStepHeight=.25,this.stepHeightWidthProportion=1.35,this.totalHeight=1,this.rotation=0,this.origin=[0,0,0]}}class zW extends GW{}class WW{}class HW{constructor(){this.name="roof-cover",this.roofAngle=15,this.roofLength=3,this.roofWidth=3,this.roofOutsideOverhang=.5,this.roofInsideOverhang=1,this.roofOverhangFacade=.1,this.roofThickness=.05,this.roofCoverHeight=.3,this.rotation=0,this.lod=Bz.high,this.center=[0,0,0],this.direction=[0,1,0]}}class XW extends HW{}class YW{}class QW{}class jW{constructor(){this.widthFirstWing=1,this.widthSecondWing=2,this.lengthStairFirstWing=2,this.lengthStairSecondWing=1,this.lengthWallFirstWing=2,this.lengthWallSecondWing=1,this.facadePanelThickness=.05,this.wallThickness=3,this.wallHeightExterior=3,this.wallHeightInterior=3,this.windowFrameOffsetTop=.3,this.windowFrameThickness=.1,this.glassFrameThickness=.05,this.doorWidth=1,this.windowWidthOffset=.3,this.stairTotalHeight=1,this.createStair=!1,this.flipDirection=!1,this.rotation=0,this.origin=[0,0,0]}}class KW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.5,this.holeDiameter=1.5,this.holeDistToBottom=2.5,this.stickLength=1.2,this.stickDiameter=.5,this.baseAttachmentHeight=2,this.roofOverhang=1,this.rotation=0,this.chimneyHeight=1,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==i&&(this.interiorHeight=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.holeDiameter=r),void 0!==n&&(this.holeDistToBottom=n),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==l&&(this.baseAttachmentHeight=l),void 0!==h&&(this.roofOverhang=h),void 0!==c&&(this.rotation=c),void 0!==u&&(this.chimneyHeight=u),void 0!==d&&(this.origin=d)}}class $W{constructor(){this.type="parametric-model",this.name="wingtipVilla"}}class qW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.3,this.holeDiameter=1.2,this.holeDistToBottom=2.5,this.stickLength=.9,this.stickDiameter=.3,this.baseAttachmentHeight=2,this.roofOverhang=.5,this.roofAngle=20,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==i&&(this.interiorHeight=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.holeDiameter=r),void 0!==n&&(this.holeDistToBottom=n),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==l&&(this.baseAttachmentHeight=l),void 0!==h&&(this.roofOverhang=h),void 0!==c&&(this.roofAngle=c),void 0!==u&&(this.rotation=u),void 0!==d&&(this.origin=d)}}class ZW{constructor(){this.type="parametric-model",this.name="chirpyChalet"}}class JW{}class eH{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p){this.sittingHeight=.45,this.backRestOffset=.1,this.backRestHeight=.7,this.width=.45,this.length=.45,this.thickness=.05,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.sittingHeight=e),void 0!==t&&(this.backRestOffset=t),void 0!==i&&(this.backRestHeight=i),void 0!==s&&(this.width=s),void 0!==r&&(this.length=r),void 0!==n&&(this.thickness=n),void 0!==o&&(this.nrOrnamentPlanks=o),void 0!==a&&(this.ornamentDepth=a),void 0!==l&&(this.filletRadius=l),void 0!==h&&(this.precision=h),void 0!==c&&(this.drawEdges=c),void 0!==u&&(this.rotation=u),void 0!==d&&(this.scale=d),void 0!==_&&(this.origin=_),void 0!==p&&(this.direction=p)}}class tH{constructor(){this.type="parametric-model",this.name="snakeChair"}}class iH extends Yz{}class sH{}class rH extends Yz{}class nH{}class oH{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class aH{}class lH{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f){this.height=.74,this.width=1,this.length=2,this.topThickness=.02,this.topOffset=.03,this.bottomThickness=.05,this.minFillet=.2,this.radiusLegTop=.03,this.radiusLegBottom=.01,this.nrLegPairs=2,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.topThickness=s),void 0!==r&&(this.topOffset=r),void 0!==n&&(this.bottomThickness=n),void 0!==o&&(this.minFillet=o),void 0!==a&&(this.radiusLegTop=a),void 0!==l&&(this.radiusLegBottom=l),void 0!==h&&(this.nrLegPairs=h),void 0!==c&&(this.precision=c),void 0!==u&&(this.drawEdges=u),void 0!==d&&(this.rotation=d),void 0!==_&&(this.scale=_),void 0!==p&&(this.origin=p),void 0!==f&&(this.direction=f)}}class hH{constructor(){this.type="parametric-model",this.name="elegantTable"}}class cH extends Yz{}class uH{}class dH extends Yz{}class _H extends Yz{}class pH{constructor(){this.index=0}}class fH{}class mH{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class gH{}class vH{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g){this.height=.4,this.width=1,this.length=1.2,this.chamfer=.01,this.topThickness=.05,this.topGlassOffset=.2,this.glassThickness=.005,this.glassHolderLength=.02,this.shelfTopOffset=.15,this.shelfThickness=.03,this.legWidth=.1,this.legDepth=.05,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.chamfer=s),void 0!==r&&(this.topThickness=r),void 0!==n&&(this.topGlassOffset=n),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassHolderLength=a),void 0!==l&&(this.shelfTopOffset=l),void 0!==h&&(this.shelfThickness=h),void 0!==c&&(this.legWidth=c),void 0!==u&&(this.legDepth=u),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdges=_),void 0!==p&&(this.rotation=p),void 0!==f&&(this.scale=f),void 0!==m&&(this.origin=m),void 0!==g&&(this.direction=g)}}class xH{constructor(){this.type="parametric-model",this.name="goodCoffeeTable"}}class bH extends Yz{}class TH{}class yH extends Yz{}class SH extends Yz{}class CH extends Yz{}class EH{constructor(){this.index=0}}class AH{}class PH{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class IH{}class RH{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m){this.height=.74,this.width=1,this.length=2,this.supportLength=.5,this.shelfHeight=.2,this.thickness=.05,this.glassThickness=.005,this.glassOffset=0,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.supportLength=s),void 0!==r&&(this.shelfHeight=r),void 0!==n&&(this.thickness=n),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassOffset=a),void 0!==l&&(this.nrOrnamentPlanks=l),void 0!==h&&(this.ornamentDepth=h),void 0!==c&&(this.filletRadius=c),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdges=d),void 0!==_&&(this.rotation=_),void 0!==p&&(this.scale=p),void 0!==f&&(this.origin=f),void 0!==m&&(this.direction=m)}}class MH{constructor(){this.type="parametric-model",this.name="snakeTable"}}class OH extends Yz{}class DH{}class wH extends Yz{}class NH{}class FH{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}!function(e){e.Aboreto="Aboreto",e.Bungee="Bungee",e.IndieFlower="IndieFlower",e.Lugrasimo="Lugrasimo",e.Orbitron="Orbitron",e.Roboto="Roboto",e.RobotoSlab="RobotoSlab",e.Silkscreen="Silkscreen",e.Tektur="Tektur",e.Workbench="Workbench"}(kz||(kz={})),function(e){e.Regular="Regular",e.Black="Black",e.Bold="Bold",e.ExtraBold="ExtraBold",e.Medium="Medium",e.SemiBold="SemiBold",e.BlackItalic="BlackItalic",e.BoldItalic="BoldItalic",e.Italic="Italic",e.Light="Light",e.LightItalic="LightItalic",e.MediumItalic="MediumItalic",e.Thin="Thin",e.ThinItalic="ThinItalic",e.ExtraLight="ExtraLight"}(Vz||(Vz={})),function(e){e.separatedExtrusion="separatedExtrusion",e.integratedExtrusion="integratedExtrusion",e.cutout="cutout"}(Uz||(Uz={})),function(e){e.compound="compound",e.cutout="originalCutout",e.cutoutInsideCharacter="cutoutInsideCharacter"}(Gz||(Gz={})),function(e){e.leftTop="leftTop",e.leftMiddle="leftMiddle",e.leftBottom="leftBottom",e.centerTop="centerTop",e.centerMiddle="centerMiddle",e.centerBottom="centerBottom",e.rightTop="rightTop",e.rightMiddle="rightMiddle",e.rightBottom="rightBottom"}(zz||(zz={}));const LH=[{key:"Aboreto",variants:["Regular"]},{key:"Bungee",variants:["Regular"]},{key:"IndieFlower",variants:["Regular"]},{key:"Lugrasimo",variants:["Regular"]},{key:"Orbitron",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Roboto",variants:["Black","BlackItalic","Bold","BoldItalic","Italic","Light","LightItalic","Medium","MediumItalic","Regular","Thin","ThinItalic"]},{key:"RobotoSlab",variants:["Black","Bold","ExtraBold","ExtraLight","Light","Medium","Regular","SemiBold","Thin"]},{key:"Silkscreen",variants:["Bold","Regular"]},{key:"Tektur",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Workbench",variants:["Regular"]}];class BH{constructor(e,t,i,s,r,n,o,a,l){this.text="bitbybit.dev",this.fontType=kz.Roboto,this.fontVariant=Vz.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.origin=[0,0,0],this.direction=[0,1,0],this.originAlignment=zz.centerMiddle,void 0!==e&&(this.text=e),void 0!==t&&(this.fontType=t),void 0!==i&&(this.fontVariant=i),void 0!==s&&(this.fontSize=s),void 0!==r&&(this.height=r),void 0!==n&&(this.rotation=n),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a),void 0!==l&&(this.originAlignment=l)}}class kH{constructor(e,t,i,s,r,n,o,a,l,h,c,u){this.facePlanar=!1,this.faceTextVar=Uz.separatedExtrusion,this.text="bitbybit.dev",this.fontType=kz.Roboto,this.fontVariant=Vz.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=zz.centerMiddle,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==i&&(this.faceTextVar=i),void 0!==s&&(this.text=s),void 0!==r&&(this.fontType=r),void 0!==n&&(this.fontVariant=n),void 0!==o&&(this.fontSize=o),void 0!==a&&(this.height=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.originParamU=h),void 0!==c&&(this.originParamV=c),void 0!==u&&(this.originAlignment=u)}}class VH{constructor(){this.type="parametric-model",this.name="text3d"}}class UH{constructor(){this.index=0}}class GH{}class zH{}class WH{constructor(e,t,i,s,r,n,o,a,l,h){this.faceTextVar=Uz.separatedExtrusion,this.text="bitbybit.dev",this.fontType=kz.Roboto,this.fontVariant=Vz.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=zz.centerMiddle,void 0!==e&&(this.faceTextVar=e),void 0!==t&&(this.text=t),void 0!==i&&(this.fontType=i),void 0!==s&&(this.fontVariant=s),void 0!==r&&(this.fontSize=r),void 0!==n&&(this.height=n),void 0!==o&&(this.rotation=o),void 0!==a&&(this.originParamU=a),void 0!==l&&(this.originParamV=l),void 0!==h&&(this.originAlignment=h)}}class HH{constructor(e,t,i){this.facePlanar=!1,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==i&&(this.definitions=i)}}class XH{constructor(e,t,i,s){this.uNumber=10,this.vNumber=10,this.height=.2,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==s&&(this.height=s)}}class YH{constructor(e,t,i,s,r,n,o){this.uNumber=10,this.vNumber=5,this.defaultHeight=.2,this.affectMinHeight=0,this.affectMaxHeight=1,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==t&&(this.affectorPoints=t),void 0!==i&&(this.uNumber=i),void 0!==s&&(this.vNumber=s),void 0!==r&&(this.affectMinHeight=r),void 0!==n&&(this.affectMaxHeight=n),void 0!==o&&(this.precision=o)}}class QH{constructor(){this.type="parametric-model",this.name="patternsFacePatternPyramidSimple"}}class jH{constructor(){this.index=0}}class KH{}class $H{}class qH{}class ZH{}class JH{constructor(){this.faceIndex=0}}class eX{constructor(){this.faceIndex=0,this.uIndex=0,this.vIndex=0}}class tX{constructor(){this.faceIndex=0,this.uIndex=0}}class iX{constructor(){this.faceIndex=0,this.vIndex=0}}class sX{}class rX{}var nX;!function(e){e.wire="wire",e.face="face",e.solid="solid"}(nX||(nX={}));class oX{static parse(e,t){var i;const s=[e],r=new Set;for(;s.length>0;){const e=s.pop();if("object"==typeof e&&null!==e&&!r.has(e))if(r.add(e),Array.isArray(e))for(let t=0;tt.id===e.shapes[r])))||void 0===i?void 0:i.shape)}for(const t in e)s.push(e[t])}}return e}}var aX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class lX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return aX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.arabicArchway",e);if(t){const e=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},e),{type:t.data.type,name:t.data.name,compound:t.compound,shapes:t.shapes,originalInputs:t.data.originalInputs})}}))}drawModel(e,t=.003){return aX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;this.materials||(this.materials=this.createMaterials(e.originalInputs.lod)),s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?e.originalInputs.lod===Bz.high&&"compound"===t?i(void 0):this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,t)=>{const s=o[t];if(s){if(s.parent=i,void 0!==this.materials[e]){const t=s.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}s.name=e,s.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=s}})),i}))}dispose(e){return aX(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}disposeMaterials(){this.materials&&Object.keys(this.materials).forEach((e=>{const t=this.materials[e];t&&t.dispose()}))}createMaterials(e){const t=new Jz;return e===Bz.high?t.compound=this.createBaseMaterial():t.compound=this.createOpaqueMaterial(),t.vasePartsCompound=this.createBaseMaterial(),t.glassPartsCompound=this.createGlassMaterial(),t.vaseBaseCompound=this.createBaseMaterial(),t}createOpaqueMaterial(){const e=new zg("opaqueMat"+Math.random(),this.context.scene);return e.albedoColor=new Ee(1,1,1),e.ambientColor=Ee.FromHexString("#ffffff"),e.metallic=0,e.roughness=.7,e.zOffset=1,e.backFaceCulling=!1,e.alpha=.3,e}createBaseMaterial(){const e=new zg("faceMaterial"+Math.random(),this.context.scene);return e.albedoColor=new Ee(1,1,1),e.ambientColor=Ee.FromHexString("#ffffff"),e.metallic=0,e.roughness=.7,e.zOffset=1,e}createGlassMaterial(){const e=new zg("faceGlassMaterial"+Math.random(),this.context.scene);return e.albedoColor=new Ee(0,0,.05),e.ambientColor=Ee.FromHexString("#ffffff"),e.metallic=.8,e.roughness=.1,e.zOffset=1,e.alpha=.5,e}}class hX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.serenitySwirl=new Hz(this.occWorkerManager,this.context,this.draw,this.occt),this.arabicArchway=new lX(this.occWorkerManager,this.context,this.draw,this.occt)}}var cX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class uX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return cX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.eternalLove",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e,t=.003){return cX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s}),n=new zg("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new Ee(1,.9,1),n.ambientColor=Ee.FromHexString("#ff00ff"),n.metallic=.8,n.roughness=.7,n.zOffset=1,r.getChildMeshes()[0].material=n,r.material=n,r.parent=i,i}))}dispose(e){return cX(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}class dX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.eternalLove=new uX(this.occWorkerManager,this.context,this.draw,this.occt)}}var _X=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class pX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return _X(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.calmCup",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e){return _X(this,void 0,void 0,(function*(){const t=new ha("brepMesh"+Math.random(),this.context.scene),i=new mU.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#bc7e5b",i.edgeWidth=.6*e.originalInputs.scale,i.precision=e.originalInputs.precision*e.originalInputs.scale;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),r=new zg("brepMaterial"+Math.random(),this.context.scene);return r.albedoColor=new Ee(1,1,1),r.ambientColor=Ee.FromHexString("#ffffff"),r.metallic=.8,r.roughness=.7,r.zOffset=2,s.getChildMeshes()[0].material=r,s.material=r,s.parent=t,t}))}dispose(e){return _X(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}var fX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class mX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return fX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.dragonCup",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}getCompoundShape(e){return e.model.compound}drawModel(e){return fX(this,void 0,void 0,(function*(){const t=new ha("brepMesh"+Math.random(),this.context.scene),i=new mU.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#617bff",i.edgeWidth=.6*e.originalInputs.scale,i.precision=e.originalInputs.precision*e.originalInputs.scale;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),r=new zg("brepMaterial"+Math.random(),this.context.scene);return r.albedoColor=Ee.FromHexString("#2b00ff"),r.ambientColor=Ee.FromHexString("#ffffff"),r.metallic=.9,r.roughness=.3,r.zOffset=2,s.getChildMeshes()[0].material=r,s.material=r,s.parent=t,t}))}}class gX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.calmCup=new pX(this.occWorkerManager,this.context,this.draw,this.occt),this.dragonCup=new mX(this.occWorkerManager,this.context,this.draw,this.occt)}}var vX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class xX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return vX(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.phoneNest",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}drawOptions(e){return e}drawModel(e,t){return vX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#ffffff",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?("phone"===t&&(s.edgeColour="#000000"),this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)}))):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return vX(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="phone-nest-",t=new pW,i=Mz.wood3Material(this.context.scene,Math.PI/2,1);i.name=e+i.name,t.main=i;const s=Mz.glass(this.context.scene,"#000000");return s.name=e+s.name,t.phone=s,t}}class bX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.phoneNest=new xX(this.occWorkerManager,this.context,this.draw,this.occt)}}class TX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.vases=new hX(this.occWorkerManager,this.context,this.draw,this.occt),this.cups=new gX(this.occWorkerManager,this.context,this.draw,this.occt),this.medals=new dX(this.occWorkerManager,this.context,this.draw,this.occt),this.desktop=new bX(this.occWorkerManager,this.context,this.draw,this.occt)}}var yX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class SX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return yX(this,void 0,void 0,(function*(){void 0===this.materials&&(this.materials=this.createMaterials()),void 0===this.skin&&(this.skin=this.createSkin());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.zenHideout",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}drawModel(e,t=.003){return yX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;if(s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.06,s.precision=t,e.originalInputs.lod===Bz.high&&e.drawingPart){const t={},r=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((s=>{s.isVisible=!1,s.getChildMeshes().forEach((e=>e.isVisible=!1)),!0===this.skin[t]&&(s.visibility=e.originalInputs.skinOpacity,s.getChildMeshes().forEach((t=>t.visibility=e.originalInputs.skinOpacity))),i(s)}),(()=>{i(void 0)})):i(void 0)})))),n=yield Promise.all(r);Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const r=n[s];if(r){if(r.parent=i,void 0!==this.materials[e]){const t=r.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}r.name=e,r.isVisible=!0,r.getChildMeshes().forEach((e=>e.isVisible=!0)),t[e]=r}}))}else if(e.originalInputs.lod===Bz.middle){const t=new zg("brepMaterial"+Math.random(),this.context.scene);t.albedoColor=new Ee(0,0,0),t.metallic=0,t.roughness=.7,t.zOffset=2;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s});r.getChildMeshes()[0].material=t,r.material=t,r.parent=i}else e.originalInputs.lod===Bz.low&&(s.edgeColour="#e89668",s.edgeWidth=10,(yield this.draw.drawAnyAsync({entity:e.compound,options:s})).parent=i);return i}))}dispose(e){return yX(this,void 0,void 0,(function*(){const t=e.shapes.map((e=>e.shape));yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="zen-hideout-",t=new AW,i=new Lx(e+"windowGlassCompound",this.context.scene);i.alpha=.2,i.metallic=.9,i.roughness=.1,i.baseColor=new Ee(.9,.9,1),i.zOffset=2,t.windowGlassCompound=i;const s=new Lx(e+"windowGlassCompound",this.context.scene);s.metallic=.1,s.roughness=.8,s.baseColor=new Ee(.05,.05,.05),s.zOffset=2,t.windowFrameCompound=s;const r=new Lx(e+"glassFramesCompound",this.context.scene);r.metallic=.1,r.roughness=.8,r.baseColor=new Ee(0,0,0),r.zOffset=2,t.glassFramesCompound=r;const n=Mz.metal1(this.context.scene,0,.3);t.roofCoverFirstCompound=n,t.roofCoverSecondCompound=n;const o=Mz.wood1Material(this.context.scene,0,1);t.beamsCompound=o,t.columnsCompound=o;const a=Mz.woodenPlanks(this.context.scene,0,1);t.firstFloorExteriorPanelsCompound=a;const l=new Lx(e+"firstFloorInteriorPanelsCompound",this.context.scene);l.metallic=.1,l.roughness=.8,l.baseColor=new Ee(.1,.1,.1),l.zOffset=2,t.firstFloorInteriorPanelsCompound=l;const h=Mz.wood3Material(this.context.scene,Math.PI/2,1);t.roofExteriorPanelsCompound=h;const c=new Lx(e+"roofInteriorPanelsCompound",this.context.scene);c.metallic=.1,c.roughness=.8,c.baseColor=new Ee(.3,.3,.3),c.zOffset=2,t.roofInteriorPanelsCompound=c;const u=Mz.wood2Material(this.context.scene,0,.5);t.floorCompound=u;const d=new Lx(e+"ceilingCompound",this.context.scene);d.metallic=.3,d.roughness=.7,d.baseColor=new Ee(1,1,1),d.zOffset=2,t.ceilingCompound=d;const _=Mz.brushedConcrete(this.context.scene,0,1);return t.stairsCompound=_,t}createSkin(){return{windowGlassCompound:!0,glassFramesCompound:!1,windowFrameCompound:!1,beamsCompound:!1,columnsCompound:!1,firstFloorExteriorPanelsCompound:!0,firstFloorInteriorPanelsCompound:!0,roofExteriorPanelsCompound:!0,roofInteriorPanelsCompound:!0,roofCoverFirstCompound:!0,roofCoverSecondCompound:!0,floorCompound:!0,ceilingCompound:!0,stairsCompound:!1}}}class CX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.zenHideout=new SX(this.occWorkerManager,this.context,this.draw,this.occt)}}class EX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.houses=new CX(this.occWorkerManager,this.context,this.draw,this.occt)}}class AX{lodEnum(e){return e.lod}}var PX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class IX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return PX(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.top.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.elegantTable",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getLegShapes(e){return e.model.legParts.map((e=>e.shapes.leg))}getLegShapeByIndex(e){return e.index>=0&&e.indexe.bottomCenter))}getLegTopPoints(e){return e.model.legParts.map((e=>e.topCenter))}drawOptions(e){return e}drawModel(e,t){return PX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#bc7e5b",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return PX(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="elegant-table-",t=new uH,i=Mz.wood3Material(this.context.scene,Math.PI/2,2);i.name=e+i.name,t.top=i;const s=Mz.wood1Material(this.context.scene,Math.PI/2,2);s.name=e+i.name,t.topBase=s;const r=Mz.wood1Material(this.context.scene,0,1);return r.name=e+i.name,t.legs=r,t}}var RX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class MX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return RX(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.top.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.goodCoffeeTable",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getLegShapes(e){return e.model.legParts.map((e=>e.shapes.leg))}getLegShapeByIndex(e){return e.index>=0&&e.indexe.bottomCenter))}getLegTopPoints(e){return e.model.legParts.map((e=>e.topCenter))}drawOptions(e){return e}drawModel(e,t){return RX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#bc7e5b",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return RX(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="good-coffee-table-",t=new TH,i=Mz.wood3Material(this.context.scene,Math.PI/2,2);i.name=e+i.name,t.top=i,t.legs=i,t.shelf=i;const s=Mz.glass(this.context.scene,"#000000");return s.name=e+i.name,t.topGlass=s,t}}var OX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class DX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return OX(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.snakeTable",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getGlassShape(e){return e.model.mainPart.shapes.glass}getMainShape(e){return e.model.mainPart.shapes.main}getTopCenterPoint(e){return e.model.mainPart.topCenter}drawOptions(e){return e}drawModel(e,t){return OX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#000000",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return OX(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="snake-table-",t=new DH,i=Mz.roughPlastic(this.context.scene,"#ffffff");i.name=e+i.name,t.main=i;const s=Mz.glass(this.context.scene,"#000000");return s.name=e+s.name,t.glass=s,t}}class wX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.elegantTable=new IX(this.occWorkerManager,this.context,this.draw,this.occt),this.goodCoffeeTable=new MX(this.occWorkerManager,this.context,this.draw,this.occt),this.snakeTable=new DX(this.occWorkerManager,this.context,this.draw,this.occt)}}var NX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class FX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return NX(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.snakeChair",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getSittingWireShape(e){return e.model.mainPart.shapes.sittingWire}getSittingAreaCenterPoint(e){return e.model.mainPart.sittingCenter}drawOptions(e){return e}drawModel(e,t){return NX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#000000",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return NX(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e=new sH,t=Mz.roughPlastic(this.context.scene,"#ffffff");return t.name="snake-chair-"+t.name,e.main=t,e}}class LX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.snakeChair=new FX(this.occWorkerManager,this.context,this.draw,this.occt)}}class BX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.chairs=new LX(this.occWorkerManager,this.context,this.draw,this.occt),this.tables=new wX(this.occWorkerManager,this.context,this.draw,this.occt)}}class kX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.kidsCorner=new Lz(this.occWorkerManager,this.context,this.draw,this.occt),this.threeDPrinting=new TX(this.occWorkerManager,this.context,this.draw,this.occt),this.architecture=new EX(this.occWorkerManager,this.context,this.draw,this.occt),this.furniture=new BX(this.occWorkerManager,this.context,this.draw,this.occt),this.enums=new AX}}var VX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class UX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return VX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.text3d",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createTextOnFace(e){return VX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.text3dFace",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createTextsOnFace(e){return VX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.texts3dFace",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}definition3dTextOnFace(e){return e}drawModel(e,t=.003){return VX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s}),n=new zg("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new Ee(1,1,1),n.ambientColor=Ee.FromHexString("#ffffff"),n.metallic=0,n.roughness=.7,n.zOffset=1,r.getChildMeshes()[0].material=n,r.material=n,r.parent=i,i}))}getCompoundShape(e){return e.model.compound}getCharacterShape(e){if(e.index<0||e.index>=e.model.characterParts.length)throw new Error("Index is out of bounds.");return e.model.characterParts[e.index].shapes.compound}getCharacterShapes(e){return e.model.characterParts.map((e=>e.shapes.compound))}getCharacterCenterCoordinates(e){return e.model.characterCenterCoordinates}getFaceCutout(e){if(e.model.faceParts){const t=e.model.faceParts.filter((e=>e.type===Gz.cutout)).map((e=>e.shapes.face));if(t.length>0)return t[0];throw new Error("No cutout was found.")}throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getAllFacesOfCutout(e){if(e.model.faceParts)return e.model.faceParts.filter((e=>e.type===Gz.cutout||e.type===Gz.cutoutInsideCharacter)).map((e=>e.shapes.face));throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getCutoutsInsideCharacters(e){if(e.model.faceParts)return e.model.faceParts.filter((e=>e.type===Gz.cutoutInsideCharacter)).map((e=>e.shapes.face));throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getAdvanceWidth(e){return e.model.advanceWidth}}var GX,zX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class WX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}createPyramidSimple(e){return zX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.pyramidSimple",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createPyramidSimpleAffectors(e){return zX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.pyramidSimpleAffectors",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}drawModel(e){return zX(this,void 0,void 0,(function*(){const t=new ha("brepMesh"+Math.random(),this.context.scene),i=new mU.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#bc7e5b",i.edgeWidth=1,i.precision=e.originalInputs.precision;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),r=new zg("brepMaterial"+Math.random(),this.context.scene);return r.albedoColor=new Ee(1,1,1),r.ambientColor=Ee.FromHexString("#ffffff"),r.metallic=.3,r.roughness=.6,r.zOffset=2,s.getChildMeshes()[0].material=r,s.material=r,s.parent=t,t}))}getCompoundShape(e){return e.model.compound}getCompoundShapeOnFace(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex&&t.vIndex===e.vIndex));if(t)return t.shapes.compound;throw new Error("Cell does not exist on the face")}throw new Error("Cell u or v index is out of range")}throw new Error("Face index is out of range")}getAllPyramidCells(e){return e.model.faceParts.map((e=>e.cells)).flat()}getAllPyramidCellsOnFace(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex));throw new Error("Face index is out of range")}getAllPyramidUCellsOnFaceAtV(e){if(e.model.faceParts&&e.faceIndext.vIndex===e.vIndex));throw new Error("Face index is out of range")}getCellOnIndex(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex&&t.vIndex===e.vIndex));if(t)return t;throw new Error("Cell does not exist on the face")}throw new Error("Cell u or v index is out of range")}throw new Error("Face index is out of range")}getTopPointsOfCells(e){return e.cells.map((e=>e.topPoint))}getCenterPointsOfCells(e){return e.cells.map((e=>e.centerPoint))}getCornerPointsOfCells(e){return e.cells.map((e=>[e.cornerPoint1,e.cornerPoint2,e.cornerPoint3,e.cornerPoint4].filter((e=>void 0!==e))))}getCornerPointOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.cornerPoint1:1===e.index?t.cornerPoint2:2===e.index?t.cornerPoint3:3===e.index?t.cornerPoint4:void 0));throw new Error("Corner index is out of range")}getCornerNormalOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.cornerNormal1:1===e.index?t.cornerNormal2:2===e.index?t.cornerNormal3:3===e.index?t.cornerNormal4:void 0));throw new Error("Corner index is out of range")}getCornerNormalsOfCells(e){return e.cells.map((e=>[e.cornerNormal1,e.cornerNormal2,e.cornerNormal3,e.cornerNormal4].filter((e=>void 0!==e))))}getCompoundShapesOfCells(e){return e.cells.map((e=>e.shapes.compound))}getFaceShapesOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.shapes.face1:1===e.index?t.shapes.face2:2===e.index?t.shapes.face3:3===e.index?t.shapes.face4:void 0));throw new Error("Face index is out of range")}getWireShapesOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.shapes.wire1:1===e.index?t.shapes.wire2:2===e.index?t.shapes.wire3:3===e.index?t.shapes.wire4:void 0));throw new Error("Wire index is out of range")}getStartPolylineWireU(e){if(e.faceIndex>=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex0&&r[r.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]0&&"string"!=typeof t[e])for(var i=function(i){var s=t[e][i];"object"==typeof s&&null!==s&&s.then&&(s.then((function(s){return t[e][i]=s,s})),n.push(t[e][i]))},s=0;s0&&e.startedAsyncTask(i,s,"#eeeeff"),n.length>0?[2,Promise.all(n).then((function(t){return e.finishedAsyncTask(i,s),t}))]:[2,null]}))}))},e.finishedAsyncTask=function(e,t){},e.startedAsyncTask=function(e,t,i){},e.runtimeValidation=function(e,t){},e.validate=function(e,t,i){},e.handleBlockException=function(e,t){},e.errorHappened=function(e,t,i){},e.updateListInputs=function(e){Object.keys(e).forEach((function(t){if(Array.isArray(e[t])){var i=[];e[t].forEach((function(e){if(e&&e.result){var t=e.result;e.transformers&&e.transformers.length&&e.transformers.forEach((function(e){e.type===KX.flat&&(t=t.flat())})),t instanceof Array?i.push.apply(i,t):i.push(t)}})),e[t]=i}}))},e.executeBasedOnTypeAsync=function(e,t,i){return qX(this,void 0,void 0,(function(){var s,r,n,o,a,l,h,c,u;return ZX(this,(function(d){switch(d.label){case 0:if(t)return[3,5];l=this.performActionOnAllVariationsSimplified(e,i),d.label=1;case 1:return d.trys.push([1,3,,4]),[4,Promise.all(l)];case 2:return s=d.sent(),[3,4];case 3:throw r=d.sent(),new Error(r);case 4:return[3,9];case 5:if(!t)return[3,9];for(n=Object.keys(e),o=n.map((function(t){return e[t]})),a=this.normalizeListsToEqualLength(o),l=[],h=function(e){var t={};n.forEach((function(i,s){t[i]=o[s][e]})),l.push(i(t))},c=0;ct&&(t=e.length)})),t},e.drawNodeMeshes=function(e,t){return qX(this,void 0,void 0,(function(){var i,s=this;return ZX(this,(function(r){switch(r.label){case 0:return i=e.map((function(e){return qX(s,void 0,void 0,(function(){var i,s,r;return ZX(this,(function(n){switch(n.label){case 0:return i=e.result,s=[],i instanceof Array&&i.length>0&&i[0]&&i[0].hash?i.forEach((function(e){var i=t.draw.drawAnyAsync({entity:e,options:void 0});s.push(i)})):(r=t.draw.drawAnyAsync({entity:i,options:void 0}),s.push(r)),[4,Promise.all(s)];case 1:return[2,n.sent()]}}))}))})),[4,Promise.all(i)];case 1:return r.sent(),[2]}}))}))},e}(),iY=function(){function e(e){this.context=e}return e.prototype.handleTags=function(e,t,i,s){var r=this;!t&&this.context.tagBag.length>0&&this.context.tagBag.find((function(e){return e.needsUpdate}))&&(t=!0),t&&this.context.tagBag.length>0&&this.context.tagBag.forEach((function(t){var n=document.querySelector("#"+t.id),o=new _e(t.position[0],t.position[1],t.position[2]);n.textContent=t.text;var a=i.getRenderWidth()/2,l=i.getRenderHeight()/2,h=_e.Project(o,me.IdentityReadOnly,s.getTransformMatrix(),e.viewport.toGlobal(a,l)),c=_e.Distance(e.position,o),u=t.adaptDepth?Math.ceil(r.context.remap(c,0,100,t.size,3)):t.size;h.x>0&&h.x0&&h.y0&&h.z<1&&u>3?n.style="".concat("position: absolute; transform: translate(-50%, -50%); font-weight: 400;"," font-size: ").concat(u,"px; color: ").concat(t.colour,"; left: ").concat(h.x,"px; top: ").concat(h.y,"px; display: inline;"):n.style="display: none;"}))},e.prototype.removeTagsIfNeeded=function(){this.tagsExist()&&this.context.tagBag.forEach((function(e){var t=document.getElementById(e.id);t.parentNode.removeChild(t)})),this.context.tagBag=[]},e.prototype.tagsExist=function(){return this.context.tagBag.length>0},e}(),sY=function(){return sY=Object.assign||function(e){for(var t,i=1,s=arguments.length;i0&&r[r.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]0?JSON.stringify(s):"{}",';\n let bitbybitRunnerResult = {};\n const runContext = "runner";\n const mockBitbybitRunnerInputs = (inputs) => {\n }\n const getBitbybitRunnerInputs = () => {\n return bitbybitRunnerInputs;\n }\n const setBitbybitRunnerResult = (result) => {\n bitbybitRunnerResult = result;\n }\n const setBitbybitRunnerResultValue = (prop, value) => {\n bitbybitRunnerResult[prop] = value;\n }\n \n const bitbybit = this.bitbybit;\n const Bit = this.Bit;\n Bit.mockBitbybitRunnerInputs = mockBitbybitRunnerInputs;\n Bit.getBitbybitRunnerInputs = getBitbybitRunnerInputs;\n Bit.setBitbybitRunnerResult = setBitbybitRunnerResult;\n Bit.setBitbybitRunnerResultValue = setBitbybitRunnerResultValue;\n \n const BitByBit = this.BitByBit;\n const errorHandle = this.errorHandle;\n const BABYLON = this.BABYLON;\n BABYLON.GUI = this.GUI;\n const resolve = this.resolve;\n \n await ').concat(r.script,"\n if(bitbybitRunnerResult !== undefined){\n resolve(bitbybitRunnerResult);\n } else {\n resolve(undefined);\n }\n }\n \n bitbybitRunnerStart();\n "),a={HS:tY,BitByBitContextHelperService:this.bitbybit.context},l={bitbybit:this.bitbybit,BABYLON:e,GUI:t,Bit:aY,BitByBit:a,errorHandle:n},[2,new Promise((function(e){return l.resolve=e,new Function(o).apply(l)}))]}))}))},i.prototype.resetRunnerContext=function(){if(this.bitbybit.context.scene.dispose(),this.options.enablePhysics){var e=new BA(!0,this.havok);this.bitbybit.context.havokPlugin=e}var t=document.getElementById(this.options.canvasId),i=this.bitbybit.context.engine;this.initScene(i,t),this.tagService.removeTagsIfNeeded(),this.bitbybit.context.intervalBag.forEach((function(e){return clearInterval(e)})),this.bitbybit.context.timeoutBag.forEach((function(e){return clearTimeout(e)})),this.bitbybit.context.intervalBag.length=0,this.bitbybit.context.timeoutBag.length=0,this.bitbybit.context.renderLoopBag.length=0,this.bitbybit.context.keyPressBag.length=0,this.bitbybit.context.keyDownBag.length=0,this.bitbybit.context.keyUpBag.length=0},i.prototype.cleanOCCTCache=function(){return rY(this,void 0,void 0,(function(){return nY(this,(function(e){return[2,this.bitbybit.occtWorkerManager.cleanAllCache()]}))}))},i.prototype.cleanJSCADCache=function(){return rY(this,void 0,void 0,(function(){return nY(this,(function(e){return[2,this.bitbybit.jscadWorkerManager.cleanAllCache()]}))}))},i}()})(),s})())); \ No newline at end of file +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.bitbybitRunner=t():e.bitbybitRunner=t()}(this,(()=>(()=>{var e={615:(e,t,i)=>{e.exports=function e(t,i,s){function r(o,a){if(!i[o]){if(!t[o]){if(n)return n(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var h=i[o]={exports:{}};t[o][0].call(h.exports,(function(e){return r(t[o][1][e]||e)}),h,h.exports,e,t,i,s)}return i[o].exports}for(var n=void 0,o=0;o=48&&e<=57}function T(e){return"0123456789abcdefABCDEF".indexOf(e)>=0}function y(e){return"01234567".indexOf(e)>=0}function S(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279].indexOf(e)>=0}function C(e){return 10===e||13===e||8232===e||8233===e}function E(e){return 64==e||36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||92===e||e>=128&&a.NonAsciiIdentifierStart.test(String.fromCharCode(e))}function A(e){return 36===e||95===e||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||92===e||e>=128&&a.NonAsciiIdentifierPart.test(String.fromCharCode(e))}function P(e){switch(e){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"yield":case"let":return!0;default:return!1}}function I(e){return"eval"===e||"arguments"===e}function R(e){if(c&&P(e))return!0;switch(e.length){case 2:return"if"===e||"in"===e||"do"===e;case 3:return"var"===e||"for"===e||"new"===e||"try"===e||"let"===e;case 4:return"this"===e||"else"===e||"case"===e||"void"===e||"with"===e||"enum"===e;case 5:return"while"===e||"break"===e||"catch"===e||"throw"===e||"const"===e||"yield"===e||"class"===e||"super"===e;case 6:return"return"===e||"typeof"===e||"delete"===e||"switch"===e||"export"===e||"import"===e;case 7:return"default"===e||"finally"===e||"extends"===e;case 8:return"function"===e||"continue"===e||"debugger"===e;case 10:return"instanceof"===e;default:return!1}}function M(e,t,i,s,r){var n;x("number"==typeof i,"Comment must have valid position"),g.lastCommentStart>=i||(g.lastCommentStart=i,n={type:e,value:t},v.range&&(n.range=[i,s]),v.loc&&(n.loc=r),v.comments.push(n),v.attachComment&&(v.leadingComments.push(n),v.trailingComments.push(n)))}function O(e){var t,i,s,r;for(t=u-e,i={start:{line:d,column:u-_-e}};u=p&&j({},o.UnexpectedToken,"ILLEGAL");else if(42===i){if(47===h.charCodeAt(u+1))return++u,++u,void(v.comments&&(s=h.slice(e+2,u-2),t.end={line:d,column:u-_},M("Block",s,e,u,t)));++u}else++u;j({},o.UnexpectedToken,"ILLEGAL")}function w(){var e,t;for(t=0===u;u>>="===(r=h.substr(u,4))?(u+=4,{type:t.Punctuator,value:r,lineNumber:d,lineStart:_,start:n,end:u}):">>>"===(s=r.substr(0,3))||"<<="===s||">>="===s?(u+=3,{type:t.Punctuator,value:s,lineNumber:d,lineStart:_,start:n,end:u}):l===(i=s.substr(0,2))[1]&&"+-<>&|".indexOf(l)>=0||"=>"===i?(u+=2,{type:t.Punctuator,value:i,lineNumber:d,lineStart:_,start:n,end:u}):"<>=!+-*%&|^/".indexOf(l)>=0?(++u,{type:t.Punctuator,value:l,lineNumber:d,lineStart:_,start:n,end:u}):void j({},o.UnexpectedToken,"ILLEGAL")}function k(){var e,i,s;if(x(b((s=h[u]).charCodeAt(0))||"."===s,"Numeric literal must start with a decimal digit or a decimal point"),i=u,e="","."!==s){if(e=h[u++],s=h[u],"0"===e){if("x"===s||"X"===s)return++u,function(e){for(var i="";u0&&(s=v.tokens[v.tokens.length-1]).range[0]===e&&"Punctuator"===s.type&&("/"!==s.value&&"/="!==s.value||v.tokens.pop()),v.tokens.push({type:"RegularExpression",value:i.literal,range:[e,u],loc:t})),i}function G(){var e,i,r;return w(),u>=p?{type:t.EOF,lineNumber:d,lineStart:_,start:u,end:u}:E(e=h.charCodeAt(u))?(i=u,{type:1===(r=92===h.charCodeAt(u)?F():L()).length?t.Identifier:R(r)?t.Keyword:"null"===r?t.NullLiteral:"true"===r||"false"===r?t.BooleanLiteral:t.Identifier,value:r,lineNumber:d,lineStart:_,start:i,end:u}):40===e||41===e||59===e?B():39===e||34===e?function(){var e,i,s,r,n,a,l,c,f="",m=!1;for(l=d,c=_,x("'"===(e=h[u])||'"'===e,"String literal must starts with a quote"),i=u,++u;u=0&&u=0?B():U()}return U()}return"Keyword"===e.type?U():B()}():B()}function z(){var e,s,r;return w(),e={start:{line:d,column:u-_}},s=G(),e.end={line:d,column:u-_},s.type!==t.EOF&&(r=h.slice(s.start,s.end),v.tokens.push({type:i[s.type],value:r,range:[s.start,s.end],loc:e})),s}function W(){var e;return u=(e=m).end,d=e.lineNumber,_=e.lineStart,m=void 0!==v.tokens?z():G(),u=e.end,d=e.lineNumber,_=e.lineStart,e}function H(){var e,t,i;e=u,t=d,i=_,m=void 0!==v.tokens?z():G(),u=e,d=t,_=i}function X(e,t){this.line=e,this.column=t}function Y(e,t,i,s){this.start=new X(e,t),this.end=new X(i,s)}function Q(){var e,t,i,s;return e=u,t=d,i=_,w(),s=d!==t,u=e,d=t,_=i,s}function j(e,t){var i,s=Array.prototype.slice.call(arguments,2),r=t.replace(/%(\d)/g,(function(e,t){return x(t":case"<=":case">=":case"instanceof":s=7;break;case"in":s=i?7:0;break;case"<<":case">>":case">>>":s=8;break;case"+":case"-":s=9;break;case"*":case"/":case"%":s=11}return s}function fe(){var e,t,i,s,r;return r=m,e=function(){var e,t,i,s,r,n,o,a,l,h;if(e=m,l=_e(),0===(r=pe(s=m,g.allowIn)))return l;for(s.prec=r,W(),t=[e,m],n=[l,s,o=_e()];(r=pe(m,g.allowIn))>0;){for(;n.length>2&&r<=n[n.length-2].prec;)o=n.pop(),a=n.pop().value,l=n.pop(),i=f.createBinaryExpression(a,l,o),t.pop(),e=t[t.length-1],f.markEnd(i,e),n.push(i);(s=W()).prec=r,n.push(s),t.push(m),i=_e(),n.push(i)}for(i=n[h=n.length-1],t.pop();h>1;)i=f.createBinaryExpression(n[h-1].value,n[h-2],i),h-=2,e=t.pop(),f.markEnd(i,e);return i}(),J("?")&&(W(),t=g.allowIn,g.allowIn=!0,i=me(),g.allowIn=t,q(":"),s=me(),e=f.createConditionalExpression(e,i,s),f.markEnd(e,r)),e}function me(){var e,i,s,n,a,l;return e=m,a=m,n=i=fe(),m.type===t.Punctuator&&("="===(l=m.value)||"*="===l||"/="===l||"%="===l||"+="===l||"-="===l||"<<="===l||">>="===l||">>>="===l||"&="===l||"^="===l||"|="===l)&&(ie(i)||K({},o.InvalidLHSInAssignment),c&&i.type===r.Identifier&&I(i.name)&&K(e,o.StrictLHSAssignment),e=W(),s=me(),n=f.markEnd(f.createAssignmentExpression(e.value,i,s),a)),n}function ge(){var e,t=m;if(e=me(),J(",")){for(e=f.createSequenceExpression([e]);u",i[t.Identifier]="Identifier",i[t.Keyword]="Keyword",i[t.NullLiteral]="Null",i[t.NumericLiteral]="Numeric",i[t.Punctuator]="Punctuator",i[t.StringLiteral]="String",i[t.RegularExpression]="RegularExpression",s=["(","{","[","in","typeof","instanceof","new","return","case","delete","throw","void","=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","&=","|=","^=",",","+","-","*","/","%","++","--","<<",">>",">>>","&","|","^","!","~","&&","||","?",":","===","==",">=","<=","<",">","!=","!=="],r={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DoWhileStatement:"DoWhileStatement",DebuggerStatement:"DebuggerStatement",EmptyStatement:"EmptyStatement",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",Identifier:"Identifier",IfStatement:"IfStatement",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement"},n={Data:1,Get:2,Set:4},o={UnexpectedToken:"Unexpected token %0",UnexpectedNumber:"Unexpected number",UnexpectedString:"Unexpected string",UnexpectedIdentifier:"Unexpected identifier",UnexpectedReserved:"Unexpected reserved word",UnexpectedEOS:"Unexpected end of input",NewlineAfterThrow:"Illegal newline after throw",InvalidRegExp:"Invalid regular expression",UnterminatedRegExp:"Invalid regular expression: missing /",InvalidLHSInAssignment:"Invalid left-hand side in assignment",InvalidLHSInForIn:"Invalid left-hand side in for-in",MultipleDefaultsInSwitch:"More than one default clause in switch statement",NoCatchOrFinally:"Missing catch or finally after try",UnknownLabel:"Undefined label '%0'",Redeclaration:"%0 '%1' has already been declared",IllegalContinue:"Illegal continue statement",IllegalBreak:"Illegal break statement",IllegalReturn:"Illegal return statement",StrictModeWith:"Strict mode code may not include a with statement",StrictCatchVariable:"Catch variable may not be eval or arguments in strict mode",StrictVarName:"Variable name may not be eval or arguments in strict mode",StrictParamName:"Parameter name eval or arguments is not allowed in strict mode",StrictParamDupe:"Strict mode function may not have duplicate parameter names",StrictFunctionName:"Function name may not be eval or arguments in strict mode",StrictOctalLiteral:"Octal literals are not allowed in strict mode.",StrictDelete:"Delete of an unqualified identifier in strict mode.",StrictDuplicateProperty:"Duplicate data property in object literal not allowed in strict mode",AccessorDataProperty:"Object literal may not have data and accessor property with the same name",AccessorGetSet:"Object literal may not have multiple get/set accessors with the same name",StrictLHSAssignment:"Assignment to eval or arguments is not allowed in strict mode",StrictLHSPostfix:"Postfix increment/decrement may not have eval or arguments operand in strict mode",StrictLHSPrefix:"Prefix increment/decrement may not have eval or arguments operand in strict mode",StrictReservedWord:"Use of future reserved word in strict mode"},a={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")},l={name:"SyntaxTree",processComment:function(e){var t,i;if(!(e.type===r.Program&&e.body.length>0)){for(v.trailingComments.length>0?v.trailingComments[0].range[0]>=e.range[1]?(i=v.trailingComments,v.trailingComments=[]):v.trailingComments.length=0:v.bottomRightStack.length>0&&v.bottomRightStack[v.bottomRightStack.length-1].trailingComments&&v.bottomRightStack[v.bottomRightStack.length-1].trailingComments[0].range[0]>=e.range[1]&&(i=v.bottomRightStack[v.bottomRightStack.length-1].trailingComments,delete v.bottomRightStack[v.bottomRightStack.length-1].trailingComments);v.bottomRightStack.length>0&&v.bottomRightStack[v.bottomRightStack.length-1].range[0]>=e.range[0];)t=v.bottomRightStack.pop();t?t.leadingComments&&t.leadingComments[t.leadingComments.length-1].range[1]<=e.range[0]&&(e.leadingComments=t.leadingComments,delete t.leadingComments):v.leadingComments.length>0&&v.leadingComments[v.leadingComments.length-1].range[1]<=e.range[0]&&(e.leadingComments=v.leadingComments,v.leadingComments=[]),i&&(e.trailingComments=i),v.bottomRightStack.push(e)}},markEnd:function(e,t){return v.range&&(e.range=[t.start,u]),v.loc&&(e.loc=new Y(void 0===t.startLineNumber?t.lineNumber:t.startLineNumber,t.start-(void 0===t.startLineStart?t.lineStart:t.startLineStart),d,u-_),this.postProcess(e)),v.attachComment&&this.processComment(e),e},postProcess:function(e){return v.source&&(e.loc.source=v.source),e},createArrayExpression:function(e){return{type:r.ArrayExpression,elements:e}},createAssignmentExpression:function(e,t,i){return{type:r.AssignmentExpression,operator:e,left:t,right:i}},createBinaryExpression:function(e,t,i){return{type:"||"===e||"&&"===e?r.LogicalExpression:r.BinaryExpression,operator:e,left:t,right:i}},createBlockStatement:function(e){return{type:r.BlockStatement,body:e}},createBreakStatement:function(e){return{type:r.BreakStatement,label:e}},createCallExpression:function(e,t){return{type:r.CallExpression,callee:e,arguments:t}},createCatchClause:function(e,t){return{type:r.CatchClause,param:e,body:t}},createConditionalExpression:function(e,t,i){return{type:r.ConditionalExpression,test:e,consequent:t,alternate:i}},createContinueStatement:function(e){return{type:r.ContinueStatement,label:e}},createDebuggerStatement:function(){return{type:r.DebuggerStatement}},createDoWhileStatement:function(e,t){return{type:r.DoWhileStatement,body:e,test:t}},createEmptyStatement:function(){return{type:r.EmptyStatement}},createExpressionStatement:function(e){return{type:r.ExpressionStatement,expression:e}},createForStatement:function(e,t,i,s){return{type:r.ForStatement,init:e,test:t,update:i,body:s}},createForInStatement:function(e,t,i){return{type:r.ForInStatement,left:e,right:t,body:i,each:!1}},createFunctionDeclaration:function(e,t,i,s){return{type:r.FunctionDeclaration,id:e,params:t,defaults:i,body:s,rest:null,generator:!1,expression:!1}},createFunctionExpression:function(e,t,i,s){return{type:r.FunctionExpression,id:e,params:t,defaults:i,body:s,rest:null,generator:!1,expression:!1}},createIdentifier:function(e){return{type:r.Identifier,name:e}},createIfStatement:function(e,t,i){return{type:r.IfStatement,test:e,consequent:t,alternate:i}},createLabeledStatement:function(e,t){return{type:r.LabeledStatement,label:e,body:t}},createLiteral:function(e){return{type:r.Literal,value:e.value,raw:h.slice(e.start,e.end)}},createMemberExpression:function(e,t,i){return{type:r.MemberExpression,computed:"["===e,object:t,property:i}},createNewExpression:function(e,t){return{type:r.NewExpression,callee:e,arguments:t}},createObjectExpression:function(e){return{type:r.ObjectExpression,properties:e}},createPostfixExpression:function(e,t){return{type:r.UpdateExpression,operator:e,argument:t,prefix:!1}},createProgram:function(e){return{type:r.Program,body:e}},createProperty:function(e,t,i){return{type:r.Property,key:t,value:i,kind:e}},createReturnStatement:function(e){return{type:r.ReturnStatement,argument:e}},createSequenceExpression:function(e){return{type:r.SequenceExpression,expressions:e}},createSwitchCase:function(e,t){return{type:r.SwitchCase,test:e,consequent:t}},createSwitchStatement:function(e,t){return{type:r.SwitchStatement,discriminant:e,cases:t}},createThisExpression:function(){return{type:r.ThisExpression}},createThrowStatement:function(e){return{type:r.ThrowStatement,argument:e}},createTryStatement:function(e,t,i,s){return{type:r.TryStatement,block:e,guardedHandlers:t,handlers:i,finalizer:s}},createUnaryExpression:function(e,t){return"++"===e||"--"===e?{type:r.UpdateExpression,operator:e,argument:t,prefix:!0}:{type:r.UnaryExpression,operator:e,argument:t,prefix:!0}},createVariableDeclaration:function(e,t){return{type:r.VariableDeclaration,declarations:e,kind:t}},createVariableDeclarator:function(e,t){return{type:r.VariableDeclarator,id:e,init:t}},createWhileStatement:function(e,t){return{type:r.WhileStatement,test:e,body:t}},createWithStatement:function(e,t){return{type:r.WithStatement,object:e,body:t}}},e.version="1.2.2",e.tokenize=function(e,i){var s;"string"==typeof e||e instanceof String||(e=String(e)),f=l,u=0,d=(h=e).length>0?1:0,_=0,p=h.length,m=null,g={allowIn:!0,labelSet:{},inFunctionBody:!1,inIteration:!1,inSwitch:!1,lastCommentStart:-1},v={},(i=i||{}).tokens=!0,v.tokens=[],v.tokenize=!0,v.openParenToken=-1,v.openCurlyToken=-1,v.range="boolean"==typeof i.range&&i.range,v.loc="boolean"==typeof i.loc&&i.loc,"boolean"==typeof i.comment&&i.comment&&(v.comments=[]),"boolean"==typeof i.tolerant&&i.tolerant&&(v.errors=[]);try{if(H(),m.type===t.EOF)return v.tokens;for(W();m.type!==t.EOF;)try{W()}catch(e){if(v.errors){v.errors.push(e);break}throw e}Oe(),s=v.tokens,void 0!==v.comments&&(s.comments=v.comments),void 0!==v.errors&&(s.errors=v.errors)}catch(e){throw e}finally{v={}}return s},e.parse=function(e,t){var i,s;s=String,"string"==typeof e||e instanceof String||(e=s(e)),f=l,u=0,d=(h=e).length>0?1:0,_=0,p=h.length,m=null,g={allowIn:!0,labelSet:{},inFunctionBody:!1,inIteration:!1,inSwitch:!1,lastCommentStart:-1},v={},void 0!==t&&(v.range="boolean"==typeof t.range&&t.range,v.loc="boolean"==typeof t.loc&&t.loc,v.attachComment="boolean"==typeof t.attachComment&&t.attachComment,v.loc&&null!==t.source&&void 0!==t.source&&(v.source=s(t.source)),"boolean"==typeof t.tokens&&t.tokens&&(v.tokens=[]),"boolean"==typeof t.comment&&t.comment&&(v.comments=[]),"boolean"==typeof t.tolerant&&t.tolerant&&(v.errors=[]),v.attachComment&&(v.range=!0,v.comments=[],v.bottomRightStack=[],v.trailingComments=[],v.leadingComments=[]));try{i=Me(),void 0!==v.comments&&(i.comments=v.comments),void 0!==v.tokens&&(Oe(),i.tokens=v.tokens),void 0!==v.errors&&(i.errors=v.errors)}catch(e){throw e}finally{v={}}return i},e.Syntax=function(){var e,t={};for(e in"function"==typeof Object.create&&(t=Object.create(null)),r)r.hasOwnProperty(e)&&(t[e]=r[e]);return"function"==typeof Object.freeze&&Object.freeze(t),t}()}))},{}],1:[function(e,t,i){(function(s){var r=function(){var e={trace:function(){},yy:{},symbols_:{error:2,JSON_PATH:3,DOLLAR:4,PATH_COMPONENTS:5,LEADING_CHILD_MEMBER_EXPRESSION:6,PATH_COMPONENT:7,MEMBER_COMPONENT:8,SUBSCRIPT_COMPONENT:9,CHILD_MEMBER_COMPONENT:10,DESCENDANT_MEMBER_COMPONENT:11,DOT:12,MEMBER_EXPRESSION:13,DOT_DOT:14,STAR:15,IDENTIFIER:16,SCRIPT_EXPRESSION:17,INTEGER:18,END:19,CHILD_SUBSCRIPT_COMPONENT:20,DESCENDANT_SUBSCRIPT_COMPONENT:21,"[":22,SUBSCRIPT:23,"]":24,SUBSCRIPT_EXPRESSION:25,SUBSCRIPT_EXPRESSION_LIST:26,SUBSCRIPT_EXPRESSION_LISTABLE:27,",":28,STRING_LITERAL:29,ARRAY_SLICE:30,FILTER_EXPRESSION:31,QQ_STRING:32,Q_STRING:33,$accept:0,$end:1},terminals_:{2:"error",4:"DOLLAR",12:"DOT",14:"DOT_DOT",15:"STAR",16:"IDENTIFIER",17:"SCRIPT_EXPRESSION",18:"INTEGER",19:"END",22:"[",24:"]",28:",",30:"ARRAY_SLICE",31:"FILTER_EXPRESSION",32:"QQ_STRING",33:"Q_STRING"},productions_:[0,[3,1],[3,2],[3,1],[3,2],[5,1],[5,2],[7,1],[7,1],[8,1],[8,1],[10,2],[6,1],[11,2],[13,1],[13,1],[13,1],[13,1],[13,1],[9,1],[9,1],[20,3],[21,4],[23,1],[23,1],[26,1],[26,3],[27,1],[27,1],[27,1],[25,1],[25,1],[25,1],[29,1],[29,1]],performAction:function(e,i,s,r,n,o,a){r.ast||(r.ast=t,t.initialize());var l=o.length-1;switch(n){case 1:return r.ast.set({expression:{type:"root",value:o[l]}}),r.ast.unshift(),r.ast.yield();case 2:return r.ast.set({expression:{type:"root",value:o[l-1]}}),r.ast.unshift(),r.ast.yield();case 3:return r.ast.unshift(),r.ast.yield();case 4:return r.ast.set({operation:"member",scope:"child",expression:{type:"identifier",value:o[l-1]}}),r.ast.unshift(),r.ast.yield();case 5:case 6:case 11:case 13:case 18:case 21:case 22:case 23:break;case 7:r.ast.set({operation:"member"}),r.ast.push();break;case 8:r.ast.set({operation:"subscript"}),r.ast.push();break;case 9:case 19:r.ast.set({scope:"child"});break;case 10:case 20:r.ast.set({scope:"descendant"});break;case 12:r.ast.set({scope:"child",operation:"member"});break;case 14:r.ast.set({expression:{type:"wildcard",value:o[l]}});break;case 15:r.ast.set({expression:{type:"identifier",value:o[l]}});break;case 16:r.ast.set({expression:{type:"script_expression",value:o[l]}});break;case 17:r.ast.set({expression:{type:"numeric_literal",value:parseInt(o[l])}});break;case 24:o[l].length>1?r.ast.set({expression:{type:"union",value:o[l]}}):this.$=o[l];break;case 25:this.$=[o[l]];break;case 26:this.$=o[l-2].concat(o[l]);break;case 27:this.$={expression:{type:"numeric_literal",value:parseInt(o[l])}},r.ast.set(this.$);break;case 28:this.$={expression:{type:"string_literal",value:o[l]}},r.ast.set(this.$);break;case 29:this.$={expression:{type:"slice",value:o[l]}},r.ast.set(this.$);break;case 30:this.$={expression:{type:"wildcard",value:o[l]}},r.ast.set(this.$);break;case 31:this.$={expression:{type:"script_expression",value:o[l]}},r.ast.set(this.$);break;case 32:this.$={expression:{type:"filter_expression",value:o[l]}},r.ast.set(this.$);break;case 33:case 34:this.$=o[l]}},table:[{3:1,4:[1,2],6:3,13:4,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9]},{1:[3]},{1:[2,1],5:10,7:11,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,3],5:21,7:11,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,12],12:[2,12],14:[2,12],22:[2,12]},{1:[2,14],12:[2,14],14:[2,14],22:[2,14]},{1:[2,15],12:[2,15],14:[2,15],22:[2,15]},{1:[2,16],12:[2,16],14:[2,16],22:[2,16]},{1:[2,17],12:[2,17],14:[2,17],22:[2,17]},{1:[2,18],12:[2,18],14:[2,18],22:[2,18]},{1:[2,2],7:22,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,5],12:[2,5],14:[2,5],22:[2,5]},{1:[2,7],12:[2,7],14:[2,7],22:[2,7]},{1:[2,8],12:[2,8],14:[2,8],22:[2,8]},{1:[2,9],12:[2,9],14:[2,9],22:[2,9]},{1:[2,10],12:[2,10],14:[2,10],22:[2,10]},{1:[2,19],12:[2,19],14:[2,19],22:[2,19]},{1:[2,20],12:[2,20],14:[2,20],22:[2,20]},{13:23,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9]},{13:24,15:[1,5],16:[1,6],17:[1,7],18:[1,8],19:[1,9],22:[1,25]},{15:[1,29],17:[1,30],18:[1,33],23:26,25:27,26:28,27:32,29:34,30:[1,35],31:[1,31],32:[1,36],33:[1,37]},{1:[2,4],7:22,8:12,9:13,10:14,11:15,12:[1,18],14:[1,19],20:16,21:17,22:[1,20]},{1:[2,6],12:[2,6],14:[2,6],22:[2,6]},{1:[2,11],12:[2,11],14:[2,11],22:[2,11]},{1:[2,13],12:[2,13],14:[2,13],22:[2,13]},{15:[1,29],17:[1,30],18:[1,33],23:38,25:27,26:28,27:32,29:34,30:[1,35],31:[1,31],32:[1,36],33:[1,37]},{24:[1,39]},{24:[2,23]},{24:[2,24],28:[1,40]},{24:[2,30]},{24:[2,31]},{24:[2,32]},{24:[2,25],28:[2,25]},{24:[2,27],28:[2,27]},{24:[2,28],28:[2,28]},{24:[2,29],28:[2,29]},{24:[2,33],28:[2,33]},{24:[2,34],28:[2,34]},{24:[1,41]},{1:[2,21],12:[2,21],14:[2,21],22:[2,21]},{18:[1,33],27:42,29:34,30:[1,35],32:[1,36],33:[1,37]},{1:[2,22],12:[2,22],14:[2,22],22:[2,22]},{24:[2,26],28:[2,26]}],defaultActions:{27:[2,23],29:[2,30],30:[2,31],31:[2,32]},parseError:function(e,t){if(!t.recoverable)throw new Error(e);this.trace(e)},parse:function(e){var t=this,i=[0],s=[null],r=[],n=this.table,o="",a=0,l=0,h=0,c=r.slice.call(arguments,1);this.lexer.setInput(e),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,void 0===this.lexer.yylloc&&(this.lexer.yylloc={});var u=this.lexer.yylloc;r.push(u);var d,_=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError?this.parseError=this.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;for(var p,f,m,g,v,x,b,T,y,S={};;){if(m=i[i.length-1],this.defaultActions[m]?g=this.defaultActions[m]:(null==p&&(d=void 0,"number"!=typeof(d=t.lexer.lex()||1)&&(d=t.symbols_[d]||d),p=d),g=n[m]&&n[m][p]),void 0===g||!g.length||!g[0]){var C;for(x in y=[],n[m])this.terminals_[x]&&x>2&&y.push("'"+this.terminals_[x]+"'");C=this.lexer.showPosition?"Parse error on line "+(a+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+y.join(", ")+", got '"+(this.terminals_[p]||p)+"'":"Parse error on line "+(a+1)+": Unexpected "+(1==p?"end of input":"'"+(this.terminals_[p]||p)+"'"),this.parseError(C,{text:this.lexer.match,token:this.terminals_[p]||p,line:this.lexer.yylineno,loc:u,expected:y})}if(g[0]instanceof Array&&g.length>1)throw new Error("Parse Error: multiple actions possible at state: "+m+", token: "+p);switch(g[0]){case 1:i.push(p),s.push(this.lexer.yytext),r.push(this.lexer.yylloc),i.push(g[1]),p=null,f?(p=f,f=null):(l=this.lexer.yyleng,o=this.lexer.yytext,a=this.lexer.yylineno,u=this.lexer.yylloc,h>0&&h--);break;case 2:if(b=this.productions_[g[1]][1],S.$=s[s.length-b],S._$={first_line:r[r.length-(b||1)].first_line,last_line:r[r.length-1].last_line,first_column:r[r.length-(b||1)].first_column,last_column:r[r.length-1].last_column},_&&(S._$.range=[r[r.length-(b||1)].range[0],r[r.length-1].range[1]]),void 0!==(v=this.performAction.apply(S,[o,l,a,this.yy,g[1],s,r].concat(c))))return v;b&&(i=i.slice(0,-1*b*2),s=s.slice(0,-1*b),r=r.slice(0,-1*b)),i.push(this.productions_[g[1]][0]),s.push(S.$),r.push(S._$),T=n[i[i.length-2]][i[i.length-1]],i.push(T);break;case 3:return!0}}return!0}},t={initialize:function(){this._nodes=[],this._node={},this._stash=[]},set:function(e){for(var t in e)this._node[t]=e[t];return this._node},node:function(e){return arguments.length&&(this._node=e),this._node},push:function(){this._nodes.push(this._node),this._node={}},unshift:function(){this._nodes.unshift(this._node),this._node={}},yield:function(){var e=this._nodes;return this.initialize(),e}},i={EOF:1,parseError:function(e,t){if(!this.yy.parser)throw new Error(e);this.yy.parser.parseError(e,t)},setInput:function(e){return this._input=e,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var e=this._input[0];return this.yytext+=e,this.yyleng++,this.offset++,this.match+=e,this.matched+=e,e.match(/(?:\r\n?|\n).*/g)?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),e},unput:function(e){var t=e.length,i=e.split(/(?:\r\n?|\n)/g);this._input=e+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-t-1),this.offset-=t;var s=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),i.length-1&&(this.yylineno-=i.length-1);var r=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:i?(i.length===s.length?this.yylloc.first_column:0)+s[s.length-i.length].length-i[0].length:this.yylloc.first_column-t},this.options.ranges&&(this.yylloc.range=[r[0],r[0]+this.yyleng-t]),this.yyleng=this.yytext.length,this},more:function(){return this._more=!0,this},reject:function(){return this.options.backtrack_lexer?(this._backtrack=!0,this):this.parseError("Lexical error on line "+(this.yylineno+1)+". You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},less:function(e){this.unput(this.match.slice(e))},pastInput:function(){var e=this.matched.substr(0,this.matched.length-this.match.length);return(e.length>20?"...":"")+e.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var e=this.match;return e.length<20&&(e+=this._input.substr(0,20-e.length)),(e.substr(0,20)+(e.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var e=this.pastInput(),t=new Array(e.length+1).join("-");return e+this.upcomingInput()+"\n"+t+"^"},test_match:function(e,t){var i,s,r;if(this.options.backtrack_lexer&&(r={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(r.yylloc.range=this.yylloc.range.slice(0))),(s=e[0].match(/(?:\r\n?|\n).*/g))&&(this.yylineno+=s.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:s?s[s.length-1].length-s[s.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+e[0].length},this.yytext+=e[0],this.match+=e[0],this.matches=e,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(e[0].length),this.matched+=e[0],i=this.performAction.call(this,this.yy,this,t,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),i)return i;if(this._backtrack){for(var n in r)this[n]=r[n];return!1}return!1},next:function(){if(this.done)return this.EOF;var e,t,i,s;this._input||(this.done=!0),this._more||(this.yytext="",this.match="");for(var r=this._currentRules(),n=0;nt[0].length)){if(t=i,s=n,this.options.backtrack_lexer){if(!1!==(e=this.test_match(i,r[n])))return e;if(this._backtrack){t=!1;continue}return!1}if(!this.options.flex)break}return t?!1!==(e=this.test_match(t,r[s]))&&e:""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){return this.next()||this.lex()},begin:function(e){this.conditionStack.push(e)},popState:function(){return this.conditionStack.length-1>0?this.conditionStack.pop():this.conditionStack[0]},_currentRules:function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},topState:function(e){return(e=this.conditionStack.length-1-Math.abs(e||0))>=0?this.conditionStack[e]:"INITIAL"},pushState:function(e){this.begin(e)},stateStackSize:function(){return this.conditionStack.length},options:{},performAction:function(e,t,i,s){switch(i){case 0:return 4;case 1:return 14;case 2:return 12;case 3:return 15;case 4:return 16;case 5:return 22;case 6:return 24;case 7:return 28;case 8:return 30;case 9:return 18;case 10:return t.yytext=t.yytext.substr(1,t.yyleng-2),32;case 11:return t.yytext=t.yytext.substr(1,t.yyleng-2),33;case 12:return 17;case 13:return 31}},rules:[/^(?:\$)/,/^(?:\.\.)/,/^(?:\.)/,/^(?:\*)/,/^(?:[a-zA-Z_]+[a-zA-Z0-9_]*)/,/^(?:\[)/,/^(?:\])/,/^(?:,)/,/^(?:((-?(?:0|[1-9][0-9]*)))?\:((-?(?:0|[1-9][0-9]*)))?(\:((-?(?:0|[1-9][0-9]*)))?)?)/,/^(?:(-?(?:0|[1-9][0-9]*)))/,/^(?:"(?:\\["bfnrt/\\]|\\u[a-fA-F0-9]{4}|[^"\\])*")/,/^(?:'(?:\\['bfnrt/\\]|\\u[a-fA-F0-9]{4}|[^'\\])*')/,/^(?:\(.+?\)(?=\]))/,/^(?:\?\(.+?\)(?=\]))/],conditions:{INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,12,13],inclusive:!0}}};function s(){this.yy={}}return e.lexer=i,s.prototype=e,e.Parser=s,new s}();void 0!==e&&void 0!==i&&(i.parser=r,i.Parser=r.Parser,i.parse=function(){return r.parse.apply(r,arguments)},i.main=function(t){t[1]||(console.log("Usage: "+t[0]+" FILE"),s.exit(1));var r=e("fs").readFileSync(e("path").normalize(t[1]),"utf8");return i.parser.parse(r)},void 0!==t&&e.main===t&&i.main(s.argv.slice(1)))}).call(this,e("_process"))},{_process:14,fs:12,path:13}],2:[function(e,t,i){t.exports={identifier:"[a-zA-Z_]+[a-zA-Z0-9_]*",integer:"-?(?:0|[1-9][0-9]*)",qq_string:'"(?:\\\\["bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4}|[^"\\\\])*"',q_string:"'(?:\\\\['bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4}|[^'\\\\])*'"}},{}],3:[function(e,t,i){var s=e("./dict"),r=e("fs"),n={lex:{macros:{esc:"\\\\",int:s.integer},rules:[["\\$","return 'DOLLAR'"],["\\.\\.","return 'DOT_DOT'"],["\\.","return 'DOT'"],["\\*","return 'STAR'"],[s.identifier,"return 'IDENTIFIER'"],["\\[","return '['"],["\\]","return ']'"],[",","return ','"],["({int})?\\:({int})?(\\:({int})?)?","return 'ARRAY_SLICE'"],["{int}","return 'INTEGER'"],[s.qq_string,"yytext = yytext.substr(1,yyleng-2); return 'QQ_STRING';"],[s.q_string,"yytext = yytext.substr(1,yyleng-2); return 'Q_STRING';"],["\\(.+?\\)(?=\\])","return 'SCRIPT_EXPRESSION'"],["\\?\\(.+?\\)(?=\\])","return 'FILTER_EXPRESSION'"]]},start:"JSON_PATH",bnf:{JSON_PATH:[["DOLLAR",'yy.ast.set({ expression: { type: "root", value: $1 } }); yy.ast.unshift(); return yy.ast.yield()'],["DOLLAR PATH_COMPONENTS",'yy.ast.set({ expression: { type: "root", value: $1 } }); yy.ast.unshift(); return yy.ast.yield()'],["LEADING_CHILD_MEMBER_EXPRESSION","yy.ast.unshift(); return yy.ast.yield()"],["LEADING_CHILD_MEMBER_EXPRESSION PATH_COMPONENTS",'yy.ast.set({ operation: "member", scope: "child", expression: { type: "identifier", value: $1 }}); yy.ast.unshift(); return yy.ast.yield()']],PATH_COMPONENTS:[["PATH_COMPONENT",""],["PATH_COMPONENTS PATH_COMPONENT",""]],PATH_COMPONENT:[["MEMBER_COMPONENT",'yy.ast.set({ operation: "member" }); yy.ast.push()'],["SUBSCRIPT_COMPONENT",'yy.ast.set({ operation: "subscript" }); yy.ast.push() ']],MEMBER_COMPONENT:[["CHILD_MEMBER_COMPONENT",'yy.ast.set({ scope: "child" })'],["DESCENDANT_MEMBER_COMPONENT",'yy.ast.set({ scope: "descendant" })']],CHILD_MEMBER_COMPONENT:[["DOT MEMBER_EXPRESSION",""]],LEADING_CHILD_MEMBER_EXPRESSION:[["MEMBER_EXPRESSION",'yy.ast.set({ scope: "child", operation: "member" })']],DESCENDANT_MEMBER_COMPONENT:[["DOT_DOT MEMBER_EXPRESSION",""]],MEMBER_EXPRESSION:[["STAR",'yy.ast.set({ expression: { type: "wildcard", value: $1 } })'],["IDENTIFIER",'yy.ast.set({ expression: { type: "identifier", value: $1 } })'],["SCRIPT_EXPRESSION",'yy.ast.set({ expression: { type: "script_expression", value: $1 } })'],["INTEGER",'yy.ast.set({ expression: { type: "numeric_literal", value: parseInt($1) } })'],["END",""]],SUBSCRIPT_COMPONENT:[["CHILD_SUBSCRIPT_COMPONENT",'yy.ast.set({ scope: "child" })'],["DESCENDANT_SUBSCRIPT_COMPONENT",'yy.ast.set({ scope: "descendant" })']],CHILD_SUBSCRIPT_COMPONENT:[["[ SUBSCRIPT ]",""]],DESCENDANT_SUBSCRIPT_COMPONENT:[["DOT_DOT [ SUBSCRIPT ]",""]],SUBSCRIPT:[["SUBSCRIPT_EXPRESSION",""],["SUBSCRIPT_EXPRESSION_LIST",'$1.length > 1? yy.ast.set({ expression: { type: "union", value: $1 } }) : $$ = $1']],SUBSCRIPT_EXPRESSION_LIST:[["SUBSCRIPT_EXPRESSION_LISTABLE","$$ = [$1]"],["SUBSCRIPT_EXPRESSION_LIST , SUBSCRIPT_EXPRESSION_LISTABLE","$$ = $1.concat($3)"]],SUBSCRIPT_EXPRESSION_LISTABLE:[["INTEGER",'$$ = { expression: { type: "numeric_literal", value: parseInt($1) } }; yy.ast.set($$)'],["STRING_LITERAL",'$$ = { expression: { type: "string_literal", value: $1 } }; yy.ast.set($$)'],["ARRAY_SLICE",'$$ = { expression: { type: "slice", value: $1 } }; yy.ast.set($$)']],SUBSCRIPT_EXPRESSION:[["STAR",'$$ = { expression: { type: "wildcard", value: $1 } }; yy.ast.set($$)'],["SCRIPT_EXPRESSION",'$$ = { expression: { type: "script_expression", value: $1 } }; yy.ast.set($$)'],["FILTER_EXPRESSION",'$$ = { expression: { type: "filter_expression", value: $1 } }; yy.ast.set($$)']],STRING_LITERAL:[["QQ_STRING","$$ = $1"],["Q_STRING","$$ = $1"]]}};r.readFileSync&&(n.moduleInclude=r.readFileSync(e.resolve("../include/module.js")),n.actionInclude=r.readFileSync(e.resolve("../include/action.js"))),t.exports=n},{"./dict":2,fs:12}],4:[function(e,t,i){var s=e("./aesprim"),r=e("./slice"),n=e("static-eval"),o=e("underscore").uniq,a=function(){return this.initialize.apply(this,arguments)};function l(t,i,r){var n=e("./index"),o=_(s.parse(i).body[0].expression,{"@":t.value}),a=r.replace(/\{\{\s*value\s*\}\}/g,o),l=n.nodes(t.value,a);return l.forEach((function(e){e.path=t.path.concat(e.path.slice(1))})),l}function h(e){return Array.isArray(e)}function c(e){return function(t,i,s,r){var n=t.value,o=t.path,a=[],l=function(t,n){var o;h(t)?(t.forEach((function(e,t){a.length>=r||s(t,e,i)&&a.push({path:n.concat(t),value:e})})),t.forEach((function(t,i){a.length>=r||e&&l(t,n.concat(i))}))):(o=t)&&!(o instanceof Array)&&o instanceof Object&&(this.keys(t).forEach((function(e){a.length>=r||s(e,t[e],i)&&a.push({path:n.concat(e),value:t[e]})})),this.keys(t).forEach((function(i){a.length>=r||e&&l(t[i],n.concat(i))})))}.bind(this);return l(n,o),a}}function u(e){return function(t,i,s){return this.descend(i,t.expression.value,e,s)}}function d(e){return function(t,i,s){return this.traverse(i,t.expression.value,e,s)}}function _(){try{return n.apply(this,arguments)}catch(e){}}function p(e){return e=e.filter((function(e){return e})),o(e,(function(e){return e.path.map((function(e){return String(e).replace("-","--")})).join("-")}))}function f(e){var t=String(e);return t.match(/^-?[0-9]+$/)?parseInt(t):null}a.prototype.initialize=function(){this.traverse=c(!0),this.descend=c()},a.prototype.keys=Object.keys,a.prototype.resolve=function(e){var t=[e.operation,e.scope,e.expression.type].join("-"),i=this._fns[t];if(!i)throw new Error("couldn't resolve key: "+t);return i.bind(this)},a.prototype.register=function(e,t){if(!t instanceof Function)throw new Error("handler must be a function");this._fns[e]=t},a.prototype._fns={"member-child-identifier":function(e,t){var i=e.expression.value,s=t.value;if(s instanceof Object&&i in s)return[{value:s[i],path:t.path.concat(i)}]},"member-descendant-identifier":d((function(e,t,i){return e==i})),"subscript-child-numeric_literal":u((function(e,t,i){return e===i})),"member-child-numeric_literal":u((function(e,t,i){return String(e)===String(i)})),"subscript-descendant-numeric_literal":d((function(e,t,i){return e===i})),"member-child-wildcard":u((function(){return!0})),"member-descendant-wildcard":d((function(){return!0})),"subscript-descendant-wildcard":d((function(){return!0})),"subscript-child-wildcard":u((function(){return!0})),"subscript-child-slice":function(e,t){if(h(t.value)){var i=e.expression.value.split(":").map(f),s=t.value.map((function(e,i){return{value:e,path:t.path.concat(i)}}));return r.apply(null,[s].concat(i))}},"subscript-child-union":function(e,t){var i=[];return e.expression.value.forEach((function(e){var s={operation:"subscript",scope:"child",expression:e.expression},r=this.resolve(s)(s,t);r&&(i=i.concat(r))}),this),p(i)},"subscript-descendant-union":function(t,i,s){var r=e(".."),n=this,o=[];return r.nodes(i,"$..*").slice(1).forEach((function(e){o.length>=s||t.expression.value.forEach((function(t){var i={operation:"subscript",scope:"child",expression:t.expression},s=n.resolve(i)(i,e);o=o.concat(s)}))})),p(o)},"subscript-child-filter_expression":function(e,t,i){var r=e.expression.value.slice(2,-1),n=s.parse(r).body[0].expression;return this.descend(t,null,(function(e,t){return _(n,{"@":t})}),i)},"subscript-descendant-filter_expression":function(e,t,i){var r=e.expression.value.slice(2,-1),n=s.parse(r).body[0].expression;return this.traverse(t,null,(function(e,t){return _(n,{"@":t})}),i)},"subscript-child-script_expression":function(e,t){return l(t,e.expression.value.slice(1,-1),"$[{{value}}]")},"member-child-script_expression":function(e,t){return l(t,e.expression.value.slice(1,-1),"$.{{value}}")},"member-descendant-script_expression":function(e,t){return l(t,e.expression.value.slice(1,-1),"$..value")}},a.prototype._fns["subscript-child-string_literal"]=a.prototype._fns["member-child-identifier"],a.prototype._fns["member-descendant-numeric_literal"]=a.prototype._fns["subscript-descendant-string_literal"]=a.prototype._fns["member-descendant-identifier"],t.exports=a},{"..":"jsonpath","./aesprim":"./aesprim","./index":5,"./slice":7,"static-eval":15,underscore:12}],5:[function(e,t,i){var s=e("assert"),r=e("./dict"),n=e("./parser"),o=e("./handlers"),a=function(){this.initialize.apply(this,arguments)};function l(e){return"[object String]"==Object.prototype.toString.call(e)}a.prototype.initialize=function(){this.parser=new n,this.handlers=new o},a.prototype.parse=function(e){return s.ok(l(e),"we need a path"),this.parser.parse(e)},a.prototype.parent=function(e,t){s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path");var i=this.nodes(e,t)[0];return i.path.pop(),this.value(e,i.path)},a.prototype.apply=function(e,t,i){s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),s.equal(typeof i,"function","fn needs to be function");var r=this.nodes(e,t).sort((function(e,t){return t.path.length-e.path.length}));return r.forEach((function(t){var s=t.path.pop(),r=this.value(e,this.stringify(t.path)),n=t.value=i.call(e,r[s]);r[s]=n}),this),r},a.prototype.value=function(e,t,i){if(s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),arguments.length>=3){var r=this.nodes(e,t).shift();if(!r)return this._vivify(e,t,i);var n=r.path.slice(-1).shift();this.parent(e,this.stringify(r.path))[n]=i}return this.query(e,this.stringify(t),1).shift()},a.prototype._vivify=function(e,t,i){var r=this;s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path");var n=this.parser.parse(t).map((function(e){return e.expression.value})),o=function(t,i){var s=t.pop(),n=r.value(e,t);n||(o(t.concat(),"string"==typeof s?{}:[]),n=r.value(e,t)),n[s]=i};return o(n,i),this.query(e,t)[0]},a.prototype.query=function(e,t,i){return s.ok(e instanceof Object,"obj needs to be an object"),s.ok(l(t),"we need a path"),this.nodes(e,t,i).map((function(e){return e.value}))},a.prototype.paths=function(e,t,i){return s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),this.nodes(e,t,i).map((function(e){return e.path}))},a.prototype.nodes=function(e,t,i){if(s.ok(e instanceof Object,"obj needs to be an object"),s.ok(t,"we need a path"),0===i)return[];var r=this.parser.parse(t),n=this.handlers,o=[{path:["$"],value:e}],a=[];return r.length&&"root"==r[0].expression.type&&r.shift(),r.length?(r.forEach((function(e,t){if(!(a.length>=i)){var s=n.resolve(e),l=[];o.forEach((function(n){if(!(a.length>=i)){var o=s(e,n,i);t==r.length-1?a=a.concat(o||[]):l=l.concat(o||[])}})),o=l}})),i?a.slice(0,i):a):o},a.prototype.stringify=function(e){s.ok(e,"we need a path");var t="$",i={"descendant-member":"..{{value}}","child-member":".{{value}}","descendant-subscript":"..[{{value}}]","child-subscript":"[{{value}}]"};return(e=this._normalize(e)).forEach((function(e){if("root"!=e.expression.type){var s,r=[e.scope,e.operation].join("-"),n=i[r];if(s="string_literal"==e.expression.type?JSON.stringify(e.expression.value):e.expression.value,!n)throw new Error("couldn't find template "+r);t+=n.replace(/{{value}}/,s)}})),t},a.prototype._normalize=function(e){if(s.ok(e,"we need a path"),"string"==typeof e)return this.parser.parse(e);if(Array.isArray(e)&&"string"==typeof e[0]){var t=[{expression:{type:"root",value:"$"}}];return e.forEach((function(e,i){if("$"!=e||0!==i)if("string"==typeof e&&e.match("^"+r.identifier+"$"))t.push({operation:"member",scope:"child",expression:{value:e,type:"identifier"}});else{var s="number"==typeof e?"numeric_literal":"string_literal";t.push({operation:"subscript",scope:"child",expression:{value:e,type:s}})}})),t}if(Array.isArray(e)&&"object"==typeof e[0])return e;throw new Error("couldn't understand path "+e)},a.Handlers=o,a.Parser=n;var h=new a;h.JSONPath=a,t.exports=h},{"./dict":2,"./handlers":4,"./parser":6,assert:8}],6:[function(e,t,i){var s=e("./grammar"),r=e("../generated/parser"),n=function(){var e=new r.Parser,t=e.parseError;return e.yy.parseError=function(){e.yy.ast&&e.yy.ast.initialize(),t.apply(e,arguments)},e};n.grammar=s,t.exports=n},{"../generated/parser":1,"./grammar":3}],7:[function(e,t,i){function s(e){return String(e).match(/^[0-9]+$/)?parseInt(e):Number.isFinite(e)?parseInt(e,10):0}t.exports=function(e,t,i,r){if("string"==typeof t)throw new Error("start cannot be a string");if("string"==typeof i)throw new Error("end cannot be a string");if("string"==typeof r)throw new Error("step cannot be a string");var n=e.length;if(0===r)throw new Error("step cannot be zero");if(r=r?s(r):1,i=i<0?n+i:i,t=s(0===(t=t<0?n+t:t)?0:t||(r>0?0:n-1)),i=s(0===i?0:i||(r>0?n:-1)),t=r>0?Math.max(0,t):Math.min(n,t),i=r>0?Math.min(i,n):Math.max(-1,i),r>0&&i<=t)return[];if(r<0&&t<=i)return[];for(var o=[],a=t;a!=i&&!(r<0&&a<=i||r>0&&a>=i);a+=r)o.push(e[a]);return o}},{}],8:[function(e,t,i){var s=e("util/"),r=Array.prototype.slice,n=Object.prototype.hasOwnProperty,o=t.exports=c;function a(e,t){return s.isUndefined(t)?""+t:s.isNumber(t)&&!isFinite(t)||s.isFunction(t)||s.isRegExp(t)?t.toString():t}function l(e,t){return s.isString(e)?e.length=0;a--)if(l[a]!=h[a])return!1;for(a=l.length-1;a>=0;a--)if(!u(e[o=l[a]],t[o]))return!1;return!0}(e,t):e==t}function d(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function _(e,t){return!(!e||!t)&&("[object RegExp]"==Object.prototype.toString.call(t)?t.test(e):e instanceof t||!0===t.call({},e))}function p(e,t,i,r){var n;s.isString(i)&&(r=i,i=null);try{t()}catch(e){n=e}if(r=(i&&i.name?" ("+i.name+").":".")+(r?" "+r:"."),e&&!n&&h(n,i,"Missing expected exception"+r),!e&&_(n,i)&&h(n,i,"Got unwanted exception"+r),e&&n&&i&&!_(n,i)||!e&&n)throw n}o.AssertionError=function(e){this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=function(e){return l(JSON.stringify(e.actual,a),128)+" "+e.operator+" "+l(JSON.stringify(e.expected,a),128)}(this),this.generatedMessage=!0);var t=e.stackStartFunction||h;if(Error.captureStackTrace)Error.captureStackTrace(this,t);else{var i=new Error;if(i.stack){var s=i.stack,r=t.name,n=s.indexOf("\n"+r);if(n>=0){var o=s.indexOf("\n",n+1);s=s.substring(o+1)}this.stack=s}}},s.inherits(o.AssertionError,Error),o.fail=h,o.ok=c,o.equal=function(e,t,i){e!=t&&h(e,t,i,"==",o.equal)},o.notEqual=function(e,t,i){e==t&&h(e,t,i,"!=",o.notEqual)},o.deepEqual=function(e,t,i){u(e,t)||h(e,t,i,"deepEqual",o.deepEqual)},o.notDeepEqual=function(e,t,i){u(e,t)&&h(e,t,i,"notDeepEqual",o.notDeepEqual)},o.strictEqual=function(e,t,i){e!==t&&h(e,t,i,"===",o.strictEqual)},o.notStrictEqual=function(e,t,i){e===t&&h(e,t,i,"!==",o.notStrictEqual)},o.throws=function(e,t,i){p.apply(this,[!0].concat(r.call(arguments)))},o.doesNotThrow=function(e,t){p.apply(this,[!1].concat(r.call(arguments)))},o.ifError=function(e){if(e)throw e};var f=Object.keys||function(e){var t=[];for(var i in e)n.call(e,i)&&t.push(i);return t}},{"util/":11}],9:[function(e,t,i){"function"==typeof Object.create?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var i=function(){};i.prototype=t.prototype,e.prototype=new i,e.prototype.constructor=e}},{}],10:[function(e,t,i){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],11:[function(e,t,s){(function(t,i){var r=/%[sdj%]/g;s.format=function(e){if(!g(e)){for(var t=[],i=0;i=n)return e;switch(e){case"%s":return String(s[i++]);case"%d":return Number(s[i++]);case"%j":try{return JSON.stringify(s[i++])}catch(e){return"[Circular]"}default:return e}})),l=s[i];i=3&&(i.depth=arguments[2]),arguments.length>=4&&(i.colors=arguments[3]),p(t)?i.showHidden=t:t&&s._extend(i,t),v(i.showHidden)&&(i.showHidden=!1),v(i.depth)&&(i.depth=2),v(i.colors)&&(i.colors=!1),v(i.customInspect)&&(i.customInspect=!0),i.colors&&(i.stylize=l),c(i,e,i.depth)}function l(e,t){var i=a.styles[t];return i?"["+a.colors[i][0]+"m"+e+"["+a.colors[i][1]+"m":e}function h(e,t){return e}function c(e,t,i){if(e.customInspect&&t&&S(t.inspect)&&t.inspect!==s.inspect&&(!t.constructor||t.constructor.prototype!==t)){var r=t.inspect(i,e);return g(r)||(r=c(e,r,i)),r}var n=function(e,t){if(v(t))return e.stylize("undefined","undefined");if(g(t)){var i="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(i,"string")}return m(t)?e.stylize(""+t,"number"):p(t)?e.stylize(""+t,"boolean"):f(t)?e.stylize("null","null"):void 0}(e,t);if(n)return n;var o=Object.keys(t),a=function(e){var t={};return e.forEach((function(e,i){t[e]=!0})),t}(o);if(e.showHidden&&(o=Object.getOwnPropertyNames(t)),y(t)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return u(t);if(0===o.length){if(S(t)){var l=t.name?": "+t.name:"";return e.stylize("[Function"+l+"]","special")}if(x(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(T(t))return e.stylize(Date.prototype.toString.call(t),"date");if(y(t))return u(t)}var h,b="",C=!1,E=["{","}"];return _(t)&&(C=!0,E=["[","]"]),S(t)&&(b=" [Function"+(t.name?": "+t.name:"")+"]"),x(t)&&(b=" "+RegExp.prototype.toString.call(t)),T(t)&&(b=" "+Date.prototype.toUTCString.call(t)),y(t)&&(b=" "+u(t)),0!==o.length||C&&0!=t.length?i<0?x(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),h=C?function(e,t,i,s,r){for(var n=[],o=0,a=t.length;o60?i[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+i[1]:i[0]+t+" "+e.join(", ")+" "+i[1]}(h,b,E)):E[0]+b+E[1]}function u(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,i,s,r,n){var o,a,l;if((l=Object.getOwnPropertyDescriptor(t,r)||{value:t[r]}).get?a=l.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):l.set&&(a=e.stylize("[Setter]","special")),P(s,r)||(o="["+r+"]"),a||(e.seen.indexOf(l.value)<0?(a=f(i)?c(e,l.value,null):c(e,l.value,i-1)).indexOf("\n")>-1&&(a=n?a.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+a.split("\n").map((function(e){return" "+e})).join("\n")):a=e.stylize("[Circular]","special")),v(o)){if(n&&r.match(/^\d+$/))return a;(o=JSON.stringify(""+r)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+a}function _(e){return Array.isArray(e)}function p(e){return"boolean"==typeof e}function f(e){return null===e}function m(e){return"number"==typeof e}function g(e){return"string"==typeof e}function v(e){return void 0===e}function x(e){return b(e)&&"[object RegExp]"===C(e)}function b(e){return"object"==typeof e&&null!==e}function T(e){return b(e)&&"[object Date]"===C(e)}function y(e){return b(e)&&("[object Error]"===C(e)||e instanceof Error)}function S(e){return"function"==typeof e}function C(e){return Object.prototype.toString.call(e)}function E(e){return e<10?"0"+e.toString(10):e.toString(10)}s.debuglog=function(e){if(v(n)&&(n=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!o[e])if(new RegExp("\\b"+e+"\\b","i").test(n)){var i=t.pid;o[e]=function(){var t=s.format.apply(s,arguments);console.error("%s %d: %s",e,i,t)}}else o[e]=function(){};return o[e]},s.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},s.isArray=_,s.isBoolean=p,s.isNull=f,s.isNullOrUndefined=function(e){return null==e},s.isNumber=m,s.isString=g,s.isSymbol=function(e){return"symbol"==typeof e},s.isUndefined=v,s.isRegExp=x,s.isObject=b,s.isDate=T,s.isError=y,s.isFunction=S,s.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},s.isBuffer=e("./support/isBuffer");var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function P(e,t){return Object.prototype.hasOwnProperty.call(e,t)}s.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[E(e.getHours()),E(e.getMinutes()),E(e.getSeconds())].join(":"),[e.getDate(),A[e.getMonth()],t].join(" ")),s.format.apply(s,arguments))},s.inherits=e("inherits"),s._extend=function(e,t){if(!t||!b(t))return e;for(var i=Object.keys(t),s=i.length;s--;)e[i[s]]=t[i[s]];return e}}).call(this,e("_process"),void 0!==i.g?i.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":10,_process:14,inherits:9}],12:[function(e,t,i){},{}],13:[function(e,t,i){(function(e){function t(e,t){for(var i=0,s=e.length-1;s>=0;s--){var r=e[s];"."===r?e.splice(s,1):".."===r?(e.splice(s,1),i++):i&&(e.splice(s,1),i--)}if(t)for(;i--;i)e.unshift("..");return e}function s(e,t){if(e.filter)return e.filter(t);for(var i=[],s=0;s=-1&&!r;n--){var o=n>=0?arguments[n]:e.cwd();if("string"!=typeof o)throw new TypeError("Arguments to path.resolve must be strings");o&&(i=o+"/"+i,r="/"===o.charAt(0))}return(r?"/":"")+(i=t(s(i.split("/"),(function(e){return!!e})),!r).join("/"))||"."},i.normalize=function(e){var n=i.isAbsolute(e),o="/"===r(e,-1);return(e=t(s(e.split("/"),(function(e){return!!e})),!n).join("/"))||n||(e="."),e&&o&&(e+="/"),(n?"/":"")+e},i.isAbsolute=function(e){return"/"===e.charAt(0)},i.join=function(){var e=Array.prototype.slice.call(arguments,0);return i.normalize(s(e,(function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e})).join("/"))},i.relative=function(e,t){function s(e){for(var t=0;t=0&&""===e[i];i--);return t>i?[]:e.slice(t,i-t+1)}e=i.resolve(e).substr(1),t=i.resolve(t).substr(1);for(var r=s(e.split("/")),n=s(t.split("/")),o=Math.min(r.length,n.length),a=o,l=0;l=1;--n)if(47===(t=e.charCodeAt(n))){if(!r){s=n;break}}else r=!1;return-1===s?i?"/":".":i&&1===s?"/":e.slice(0,s)},i.basename=function(e,t){var i=function(e){"string"!=typeof e&&(e+="");var t,i=0,s=-1,r=!0;for(t=e.length-1;t>=0;--t)if(47===e.charCodeAt(t)){if(!r){i=t+1;break}}else-1===s&&(r=!1,s=t+1);return-1===s?"":e.slice(i,s)}(e);return t&&i.substr(-1*t.length)===t&&(i=i.substr(0,i.length-t.length)),i},i.extname=function(e){"string"!=typeof e&&(e+="");for(var t=-1,i=0,s=-1,r=!0,n=0,o=e.length-1;o>=0;--o){var a=e.charCodeAt(o);if(47!==a)-1===s&&(r=!1,s=o+1),46===a?-1===t?t=o:1!==n&&(n=1):-1!==t&&(n=-1);else if(!r){i=o+1;break}}return-1===t||-1===s||0===n||1===n&&t===s-1&&t===i+1?"":e.slice(t,s)};var r=function(e,t,i){return e.substr(t,i)}}).call(this,e("_process"))},{_process:14}],14:[function(e,t,i){var s,r,n=t.exports={};function o(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function l(e){if(s===setTimeout)return setTimeout(e,0);if((s===o||!s)&&setTimeout)return s=setTimeout,setTimeout(e,0);try{return s(e,0)}catch(t){try{return s.call(null,e,0)}catch(t){return s.call(this,e,0)}}}!function(){try{s="function"==typeof setTimeout?setTimeout:o}catch(e){s=o}try{r="function"==typeof clearTimeout?clearTimeout:a}catch(e){r=a}}();var h,c=[],u=!1,d=-1;function _(){u&&h&&(u=!1,h.length?c=h.concat(c):d=-1,c.length&&p())}function p(){if(!u){var e=l(_);u=!0;for(var t=c.length;t;){for(h=c,c=[];++d1)for(var i=1;i"===_?h>d:">="===_?h>=d:"|"===_?h|d:"&"===_?h&d:"^"===_?h^d:"&&"===_?h&&d:"||"===_?h||d:i}if("Identifier"===r.type)return{}.hasOwnProperty.call(t,r.name)?t[r.name]:i;if("ThisExpression"===r.type)return{}.hasOwnProperty.call(t,"this")?t.this:i;if("CallExpression"===r.type){var p=e(r.callee);if(p===i)return i;if("function"!=typeof p)return i;var f=r.callee.object?e(r.callee.object):i;f===i&&(f=null);var m=[];for(l=0,h=r.arguments.length;l{e.exports=function(){var e={},t=this,i=(new Function("try {return this===window;}catch(e){ return false;}"),new Function("try {return this===global;}catch(e){return false;}")),s=new Function("try {return typeof importScripts === 'function';}catch(e){return false;}");if(i()&&s(),i()||s()){var r=t;if(s()){onmessage=function(e){if(e.data.className&&e.data.methodName){var i=(s=e.data.className,r=e.data.methodName,n=t,s.split(".").forEach((function(e){n&&(n=n[e])})),n?n[r]:null);if(!i)return console.error("could not find "+e.data.className+"."+e.data.methodName);postMessage({result:i.apply(null,e.data.args),id:e.data.id})}var s,r,n}}}return function(e,t,i){"use strict";t.geom=t.geom||{},t.exe=t.exe||{},t.eval=t.eval||{},t.core=t.core||{},t.promhx=t.promhx||{};var s={},r=function(){return P.__string_rec(this,"")};function n(e,t){function i(){}i.prototype=e;var s=new i;for(var r in t)s[r]=t[r];return t.toString!==Object.prototype.toString&&(s.toString=t.toString),s}var o=function(){};s.HxOverrides=o,o.__name__=["HxOverrides"],o.strDate=function(e){switch(e.length){case 8:var t=e.split(":"),i=new Date;return i.setTime(0),i.setUTCHours(t[0]),i.setUTCMinutes(t[1]),i.setUTCSeconds(t[2]),i;case 10:var s=e.split("-");return new Date(s[0],s[1]-1,s[2],0,0,0);case 19:var r=e.split(" "),n=r[0].split("-"),o=r[1].split(":");return new Date(n[0],n[1]-1,n[2],o[0],o[1],o[2]);default:throw new A("Invalid date format : "+e)}},o.cca=function(e,t){var i=e.charCodeAt(t);if(i==i)return i},o.substr=function(e,t,i){return null!=t&&0!=t&&null!=i&&i<0?"":(null==i&&(i=e.length),t<0?(t=e.length+t)<0&&(t=0):i<0&&(i=e.length+i-t),e.substr(t,i))},o.iter=function(e){return{cur:0,arr:e,hasNext:function(){return this.cur0&&(1==n?this.buf.b+="n":(this.buf.b+="u",this.buf.b+=null==n?"null":""+n),n=0),this.serialize(e[d]))}n>0&&(1==n?this.buf.b+="n":(this.buf.b+="u",this.buf.b+=null==n?"null":""+n)),this.buf.b+="h";break;case l:this.buf.b+="l";for(var _=e.h,f=null;null!=_;){var m;f=_[0],_=_[1],m=f,this.serialize(m)}this.buf.b+="h";break;case Date:var v=e;this.buf.b+="v",this.buf.add(v.getTime());break;case y:this.buf.b+="b";for(var T=e,C=T.keys();C.hasNext();){var E=C.next();this.serializeString(E),this.serialize(null!=ft[E]?T.getReserved(E):T.h[E])}this.buf.b+="h";break;case x:this.buf.b+="q";for(var I=e,R=I.keys();R.hasNext();){var M=R.next();this.buf.b+=":",this.buf.b+=null==M?"null":""+M,this.serialize(I.h[M])}this.buf.b+="h";break;case b:this.buf.b+="M";for(var O=e,D=O.keys();D.hasNext();){var w=D.next(),N=h.field(w,"__id__");h.deleteField(w,"__id__"),this.serialize(w),w.__id__=N,this.serialize(O.h[w.__id__])}this.buf.b+="h";break;case S:for(var F=e,L=0,B=F.length-2,k=new u,V=g.BASE64;L>2)),k.add(V.charAt(63&(U<<4|G>>4))),k.add(V.charAt(63&(G<<2|z>>6))),k.add(V.charAt(63&z))}if(L==B){var W=F.get(L++),H=F.get(L++);k.add(V.charAt(W>>2)),k.add(V.charAt(63&(W<<4|H>>4))),k.add(V.charAt(H<<2&63))}else if(L==B+1){var X=F.get(L++);k.add(V.charAt(X>>2)),k.add(V.charAt(X<<4&63))}var Y=k.b;this.buf.b+="s",null==Y.length?this.buf.b+="null":this.buf.b+=""+Y.length,this.buf.b+=":",this.buf.b+=null==Y?"null":""+Y;break;default:this.useCache&&this.cache.pop(),null!=e.hxSerialize?(this.buf.b+="C",this.serializeString(p.getClassName(r)),this.useCache&&this.cache.push(e),e.hxSerialize(this),this.buf.b+="g"):(this.buf.b+="c",this.serializeString(p.getClassName(r)),this.useCache&&this.cache.push(e),this.serializeFields(e))}break;case 4:if(P.__instanceof(e,_t)){var Q=p.getClassName(e);this.buf.b+="A",this.serializeString(Q)}else if(P.__instanceof(e,pt))this.buf.b+="B",this.serializeString(p.getEnumName(e));else{if(this.useCache&&this.serializeRef(e))return;this.buf.b+="o",this.serializeFields(e)}break;case 7:var j=t[2];if(this.useCache){if(this.serializeRef(e))return;this.cache.pop()}this.useEnumIndex?this.buf.b+="j":this.buf.b+="w",this.serializeString(p.getEnumName(j)),this.useEnumIndex?(this.buf.b+=":",this.buf.b+=c.string(e[1])):this.serializeString(e[0]),this.buf.b+=":";var K=e.length;this.buf.b+=c.string(K-2);for(var $=2;$57)break;e=10*e+(s-48),this.pos++}else{if(this.pos!=i)break;t=!0,this.pos++}}return t&&(e*=-1),e},readFloat:function(){for(var e=this.pos;;){var t=this.buf.charCodeAt(this.pos);if(!(t>=43&&t<58||101==t||69==t))break;this.pos++}return c.parseFloat(o.substr(this.buf,e,this.pos-e))},unserializeObject:function(e){for(;;){if(this.pos>=this.length)throw new A("Invalid object");if(103==this.buf.charCodeAt(this.pos))break;var t=this.unserialize();if("string"!=typeof t)throw new A("Invalid object key");var i=this.unserialize();e[t]=i}this.pos++},unserializeEnum:function(e,t){if(58!=this.get(this.pos++))throw new A("Invalid enum format");var i=this.readDigits();if(0==i)return p.createEnum(e,t);for(var s=[];i-- >0;)s.push(this.unserialize());return p.createEnum(e,t,s)},unserialize:function(){switch(this.get(this.pos++)){case 110:return null;case 116:return!0;case 102:return!1;case 122:return 0;case 105:return this.readDigits();case 100:return this.readFloat();case 121:var e=this.readDigits();if(58!=this.get(this.pos++)||this.length-this.pos=this.cache.length)throw new A("Invalid reference");return this.cache[a];case 82:var h=this.readDigits();if(h<0||h>=this.scache.length)throw new A("Invalid string reference");return this.scache[h];case 120:throw new A(this.unserialize());case 99:var c=this.unserialize(),u=this.resolver.resolveClass(c);if(null==u)throw new A("Class not found "+c);var _=p.createEmptyInstance(u);return this.cache.push(_),this.unserializeObject(_),_;case 119:var f=this.unserialize(),m=this.resolver.resolveEnum(f);if(null==m)throw new A("Enum not found "+f);var g=this.unserializeEnum(m,this.unserialize());return this.cache.push(g),g;case 106:var T=this.unserialize(),C=this.resolver.resolveEnum(T);if(null==C)throw new A("Enum not found "+T);this.pos++;var E=this.readDigits(),P=p.getEnumConstructs(C)[E];if(null==P)throw new A("Unknown enum index "+T+"@"+E);var I=this.unserializeEnum(C,P);return this.cache.push(I),I;case 108:var R=new l;for(this.cache.push(R),this.buf;104!=this.buf.charCodeAt(this.pos);)R.add(this.unserialize());return this.pos++,R;case 98:var M=new y;for(this.cache.push(M),this.buf;104!=this.buf.charCodeAt(this.pos);){var O=this.unserialize();M.set(O,this.unserialize())}return this.pos++,M;case 113:var D=new x;this.cache.push(D),this.buf;for(var w=this.get(this.pos++);58==w;){var N=this.readDigits();D.set(N,this.unserialize()),w=this.get(this.pos++)}if(104!=w)throw new A("Invalid IntMap format");return D;case 77:var F=new b;for(this.cache.push(F),this.buf;104!=this.buf.charCodeAt(this.pos);){var L=this.unserialize();F.set(L,this.unserialize())}return this.pos++,F;case 118:var B;if(this.buf.charCodeAt(this.pos)>=48&&this.buf.charCodeAt(this.pos)<=57&&this.buf.charCodeAt(this.pos+1)>=48&&this.buf.charCodeAt(this.pos+1)<=57&&this.buf.charCodeAt(this.pos+2)>=48&&this.buf.charCodeAt(this.pos+2)<=57&&this.buf.charCodeAt(this.pos+3)>=48&&this.buf.charCodeAt(this.pos+3)<=57&&45==this.buf.charCodeAt(this.pos+4)){var k=o.substr(this.buf,this.pos,19);B=o.strDate(k),this.pos+=19}else{var V=this.readFloat(),U=new Date;U.setTime(V),B=U}return this.cache.push(B),B;case 115:var G=this.readDigits(),z=this.buf;if(58!=this.get(this.pos++)||this.length-this.pos>2)+(Y>=2?Y-1:0);for(var Q=X+(G-Y),j=S.alloc(H),K=0;X>4);var Z=W[d.fastCodeAt(z,X++)];j.set(K++,q<<4|Z>>2);var J=W[d.fastCodeAt(z,X++)];j.set(K++,Z<<6|J)}if(Y>=2){var ee=W[d.fastCodeAt(z,X++)],te=W[d.fastCodeAt(z,X++)];if(j.set(K++,ee<<2|te>>4),3==Y){var ie=W[d.fastCodeAt(z,X++)];j.set(K++,te<<4|ie>>2)}}return this.pos+=G,this.cache.push(j),j;case 67:var se=this.unserialize(),re=this.resolver.resolveClass(se);if(null==re)throw new A("Class not found "+se);var ne=p.createEmptyInstance(re);if(this.cache.push(ne),ne.hxUnserialize(this),103!=this.get(this.pos++))throw new A("Invalid custom data");return ne;case 65:var oe=this.unserialize(),ae=this.resolver.resolveClass(oe);if(null==ae)throw new A("Class not found "+oe);return ae;case 66:var le=this.unserialize(),he=this.resolver.resolveEnum(le);if(null==he)throw new A("Enum not found "+le);return he}throw this.pos--,new A("Invalid char "+this.buf.charAt(this.pos)+" at position "+this.pos)},__class__:v};var x=function(){this.h={}};s["haxe.ds.IntMap"]=x,x.__name__=["haxe","ds","IntMap"],x.__interfaces__=[f],x.prototype={set:function(e,t){this.h[e]=t},remove:function(e){return!!this.h.hasOwnProperty(e)&&(delete this.h[e],!0)},keys:function(){var e=[];for(var t in this.h)this.h.hasOwnProperty(t)&&e.push(0|t);return o.iter(e)},__class__:x};var b=function(){this.h={},this.h.__keys__={}};s["haxe.ds.ObjectMap"]=b,b.__name__=["haxe","ds","ObjectMap"],b.__interfaces__=[f],b.prototype={set:function(e,t){var i=e.__id__||(e.__id__=++b.count);this.h[i]=t,this.h.__keys__[i]=e},keys:function(){var e=[];for(var t in this.h.__keys__)this.h.hasOwnProperty(t)&&e.push(this.h.__keys__[t]);return o.iter(e)},__class__:b};var T=s["haxe.ds.Option"]={__ename__:["haxe","ds","Option"],__constructs__:["Some","None"]};T.Some=function(e){var t=["Some",0,e];return t.__enum__=T,t.toString=r,t},T.None=["None",1],T.None.toString=r,T.None.__enum__=T;var y=function(){this.h={}};s["haxe.ds.StringMap"]=y,y.__name__=["haxe","ds","StringMap"],y.__interfaces__=[f],y.prototype={set:function(e,t){null!=ft[e]?this.setReserved(e,t):this.h[e]=t},get:function(e){return null!=ft[e]?this.getReserved(e):this.h[e]},setReserved:function(e,t){null==this.rh&&(this.rh={}),this.rh["$"+e]=t},getReserved:function(e){return null==this.rh?null:this.rh["$"+e]},keys:function(){var e=this.arrayKeys();return o.iter(e)},arrayKeys:function(){var e=[];for(var t in this.h)this.h.hasOwnProperty(t)&&e.push(t);if(null!=this.rh)for(var t in this.rh)36==t.charCodeAt(0)&&e.push(t.substr(1));return e},__class__:y};var S=function(e){this.length=e.byteLength,this.b=new gt(e),this.b.bufferValue=e,e.hxBytes=this,e.bytes=this.b};s["haxe.io.Bytes"]=S,S.__name__=["haxe","io","Bytes"],S.alloc=function(e){return new S(new mt(e))},S.prototype={get:function(e){return this.b[e]},set:function(e,t){this.b[e]=255&t},__class__:S};var C=s["haxe.io.Error"]={__ename__:["haxe","io","Error"],__constructs__:["Blocked","Overflow","OutsideBounds","Custom"]};C.Blocked=["Blocked",0],C.Blocked.toString=r,C.Blocked.__enum__=C,C.Overflow=["Overflow",1],C.Overflow.toString=r,C.Overflow.__enum__=C,C.OutsideBounds=["OutsideBounds",2],C.OutsideBounds.toString=r,C.OutsideBounds.__enum__=C,C.Custom=function(e){var t=["Custom",3,e];return t.__enum__=C,t.toString=r,t};var E=function(){};s["haxe.io.FPHelper"]=E,E.__name__=["haxe","io","FPHelper"],E.i32ToFloat=function(e){var t=e>>>23&255,i=8388607&e;return 0==i&&0==t?0:(1-(e>>>31<<1))*(1+Math.pow(2,-23)*i)*Math.pow(2,t-127)},E.floatToI32=function(e){if(0==e)return 0;var t;t=e<0?-e:e;var i=Math.floor(Math.log(t)/.6931471805599453);return i<-127?i=-127:i>128&&(i=128),(e<0?-2147483648:0)|i+127<<23|8388607&Math.round(8388608*(t/Math.pow(2,i)-1))},E.i64ToDouble=function(e,t){var i=(t>>20&2047)-1023,s=4294967296*(1048575&t)+2147483648*(e>>>31)+(2147483647&e);return 0==s&&-1023==i?0:(1-(t>>>31<<1))*(1+Math.pow(2,-52)*s)*Math.pow(2,i)},E.doubleToI64=function(e){var t=E.i64tmp;if(0==e)t.low=0,t.high=0;else{var i;i=e<0?-e:e;var s,r=Math.floor(Math.log(i)/.6931471805599453),n=4503599627370496*(i/Math.pow(2,r)-1),o=0|(s=Math.round(n)),a=s/4294967296|0;t.low=o,t.high=(e<0?-2147483648:0)|r+1023<<20|a}return t};var A=function(e){Error.call(this),this.val=e,this.message=String(e),Error.captureStackTrace&&Error.captureStackTrace(this,A)};s["js._Boot.HaxeError"]=A,A.__name__=["js","_Boot","HaxeError"],A.__super__=Error,A.prototype=n(Error.prototype,{__class__:A});var P=function(){};s["js.Boot"]=P,P.__name__=["js","Boot"],P.getClass=function(e){if(e instanceof Array&&null==e.__enum__)return Array;var t=e.__class__;if(null!=t)return t;var i=P.__nativeClassName(e);return null!=i?P.__resolveNativeClass(i):null},P.__string_rec=function(e,t){if(null==e)return"null";if(t.length>=5)return"<...>";var i=typeof e;switch("function"==i&&(e.__name__||e.__ename__)&&(i="object"),i){case"object":if(e instanceof Array){if(e.__enum__){if(2==e.length)return e[0];var s=e[0]+"(";t+="\t";for(var r=2,n=e.length;r0?",":"")+P.__string_rec(e[c],t)}return l+"]"}var u;try{u=e.toString}catch(e){return e instanceof A&&(e=e.val),"???"}if(null!=u&&u!=Object.toString&&"function"==typeof u){var d=e.toString();if("[object Object]"!=d)return d}var _=null,p="{\n";t+="\t";var f=null!=e.hasOwnProperty;for(var _ in e)f&&!e.hasOwnProperty(_)||"prototype"!=_&&"__class__"!=_&&"__super__"!=_&&"__interfaces__"!=_&&"__properties__"!=_&&(2!=p.length&&(p+=", \n"),p+=t+_+" : "+P.__string_rec(e[_],t));return p+"\n"+(t=t.substring(1))+"}";case"function":return"";case"string":return e;default:return String(e)}},P.__interfLoop=function(e,t){if(null==e)return!1;if(e==t)return!0;var i=e.__interfaces__;if(null!=i)for(var s=0,r=i.length;se.byteLength)throw new A(C.OutsideBounds)};s["js.html.compat.DataView"]=R,R.__name__=["js","html","compat","DataView"],R.prototype={getInt8:function(e){var t=this.buf.a[this.offset+e];return t>=128?t-256:t},getUint8:function(e){return this.buf.a[this.offset+e]},getInt16:function(e,t){var i=this.getUint16(e,t);return i>=32768?i-65536:i},getUint16:function(e,t){return t?this.buf.a[this.offset+e]|this.buf.a[this.offset+e+1]<<8:this.buf.a[this.offset+e]<<8|this.buf.a[this.offset+e+1]},getInt32:function(e,t){var i=this.offset+e,s=this.buf.a[i++],r=this.buf.a[i++],n=this.buf.a[i++],o=this.buf.a[i++];return t?s|r<<8|n<<16|o<<24:o|n<<8|r<<16|s<<24},getUint32:function(e,t){var i=this.getInt32(e,t);return i<0?i+4294967296:i},getFloat32:function(e,t){return E.i32ToFloat(this.getInt32(e,t))},getFloat64:function(e,t){var i=this.getInt32(e,t),s=this.getInt32(e+4,t);return E.i64ToDouble(t?i:s,t?s:i)},setInt8:function(e,t){this.buf.a[e+this.offset]=t<0?t+128&255:255&t},setUint8:function(e,t){this.buf.a[e+this.offset]=255&t},setInt16:function(e,t,i){this.setUint16(e,t<0?t+65536:t,i)},setUint16:function(e,t,i){var s=e+this.offset;i?(this.buf.a[s]=255&t,this.buf.a[s++]=t>>8&255):(this.buf.a[s++]=t>>8&255,this.buf.a[s]=255&t)},setInt32:function(e,t,i){this.setUint32(e,t,i)},setUint32:function(e,t,i){var s=e+this.offset;i?(this.buf.a[s++]=255&t,this.buf.a[s++]=t>>8&255,this.buf.a[s++]=t>>16&255,this.buf.a[s++]=t>>>24):(this.buf.a[s++]=t>>>24,this.buf.a[s++]=t>>16&255,this.buf.a[s++]=t>>8&255,this.buf.a[s++]=255&t)},setFloat32:function(e,t,i){this.setUint32(e,E.floatToI32(t),i)},setFloat64:function(e,t,i){var s=E.doubleToI64(t);i?(this.setUint32(e,s.low),this.setUint32(e,s.high)):(this.setUint32(e,s.high),this.setUint32(e,s.low))},__class__:R};var M=function(){};s["js.html.compat.Uint8Array"]=M,M.__name__=["js","html","compat","Uint8Array"],M._new=function(e,t,i){var s;if("number"==typeof e){s=[];for(var r=0;ri.byteLength)throw new A("set() outside of range");for(var r=0,n=e.byteLength;ri.byteLength)throw new A("set() outside of range");for(var l=0,h=a.length;l0||t.handleError(e._errorVal),e._resolved&&!e._pending)try{t.handleResolve(i(e._val))}catch(e){e instanceof A&&(e=e.val),t.handleError(e)}},O.linkAll=function(e,t){for(var i=function(i,s,r){if(0==i.length||O.allFulfilled(i)){for(var n,o=[],a=nt(e)();a.hasNext();){var l=a.next();o.push(l==s?r:l._val)}n=o,t.handleResolve(n)}},s=nt(e)();s.hasNext();){var r=s.next();r._update.push({async:t,linkf:function(e,t,i){return function(s){e(t,i,s)}}(i,function(t){for(var i=[],s=nt(e)();s.hasNext();){var n=s.next();n!=r&&i.push(n)}return i}(),r)})}O.allFulfilled(e)&&t.handleResolve(function(t){for(var i=[],s=nt(e)();s.hasNext();){var r=s.next();i.push(r._val)}return i}())},O.pipeLink=function(e,t,i){var s=!1,r=function(e){if(!s){s=!0;var r=i(e);r._update.push({async:t,linkf:lt(t,t.handleResolve)}),O.immediateLinkUpdate(r,t,(function(e){return e}))}};if(e._update.push({async:t,linkf:r}),e._resolved&&!e._pending)try{r(e._val)}catch(e){e instanceof A&&(e=e.val),t.handleError(e)}},O.allResolved=function(e){for(var t=nt(e)();t.hasNext();)if(!t.next()._resolved)return!1;return!0},O.allFulfilled=function(e){for(var t=nt(e)();t.hasNext();)if(!t.next()._fulfilled)return!1;return!0},O.prototype={catchError:function(e){return this._error.push(e),this},errorThen:function(e){return this._errorMap=e,this},isResolved:function(){return this._resolved},isErrored:function(){return this._errored},isErrorHandled:function(){return this._error.length>0},isErrorPending:function(){return this._errorPending},isFulfilled:function(){return this._fulfilled},isPending:function(){return this._pending},handleResolve:function(e){this._resolve(e)},_resolve:function(e){var t,i,s=this;this._pending?L.enqueue((t=lt(this,this._resolve),i=e,function(){t(i)})):(this._resolved=!0,this._pending=!0,L.queue.add((function(){s._val=e;for(var t=0,i=s._update;t0)for(var i=0,s=t._error;i0))throw new A(e);for(var n=0,o=t._update;n0&&null!=(t=L.queue.pop());)t();return L.queue.isEmpty()},L.clear=function(){L.queue=new l},L.f=function(){var e=L.queue.pop();null!=e&&e(),L.queue.isEmpty()||L.continueOnNextLoop()},L.continueOnNextLoop=function(){null!=L.nextLoop?L.nextLoop(L.f):setImmediate(L.f)};var B=s["promhx.error.PromiseError"]={__ename__:["promhx","error","PromiseError"],__constructs__:["AlreadyResolved","DownstreamNotFullfilled"]};B.AlreadyResolved=function(e){var t=["AlreadyResolved",0,e];return t.__enum__=B,t.toString=r,t},B.DownstreamNotFullfilled=function(e){var t=["DownstreamNotFullfilled",1,e];return t.__enum__=B,t.toString=r,t};var k=function(){};s["verb.Verb"]=k,k.__name__=["verb","Verb"],k.main=function(){e.log("verb 2.1.0")};var V=function(){};s["verb.core.ArrayExtensions"]=V,V.__name__=["verb","core","ArrayExtensions"],V.alloc=function(e,t){if(!(t<0))for(;e.length0;){for(var s=e.pop(),r=!0,n=0;ne)return 0;if(t>e-t&&(t=e-t),U.memo_exists(e,t))return U.get_memo(e,t);for(var i=1,s=e,r=1,n=t+1;re)return 0;t>e-t&&(t=e-t);for(var i=1,s=1,r=t+1;s=l&&o<=h||a>=l&&a<=h||l>=o&&l<=a||h>=o&&h<=a},G.prototype={fromPoint:function(e){return new G([e])},add:function(e){if(!this.initialized)return this.dim=e.length,this.min=e.slice(0),this.max=e.slice(0),this.initialized=!0,this;for(var t=0,i=this.dim;tthis.max[s]&&(this.max[s]=e[s]),e[s]e&&(e=n,t=r)}return t},getAxisLength:function(e){return e<0||e>this.dim-1?0:Math.abs(this.min[e]-this.max[e])},intersect:function(e,t){if(!this.initialized)return null;var i=this.min,s=this.max,r=e.min,n=e.max;if(!this.intersects(e,t))return null;for(var o=[],a=[],l=0,h=this.dim;l0?1:-1})),s=Math.floor(e.length/2),(r=new ue(e[s],n,i)).left=this.buildTree(e.slice(0,s),t+1,r),r.right=this.buildTree(e.slice(s+1),t+1,r),r)},nearest:function(e,t,i){var s,r=this,n=new he((function(e){return-e.item1})),o=null;s=o=function(i){for(var s,a,l,h,c=i.dimension,u=r.distanceFunction(e,i.kdPoint.point),d=[],_=0,p=r.dim;_t&&n.pop()},m=0,g=r.dim;m0&&(this.content[0]=t,this.sinkDown(0)),e},peek:function(){return this.content[0]},remove:function(e){for(var t=this.content.length,i=0;i0;){var i=Math.floor((e+1)/2)-1,s=this.content[i];if(!(this.scoreFunction(t)=0;){for(o=[],a=e[c],d=r-1;d>=0;){for(l=a[s-1]*t[s-1][d],u=s-2;u>=1;)h=u-1,l+=a[u]*t[u][d]+a[h]*t[h][d],u-=2;0==u&&(l+=a[0]*t[0][d]),o[d]=l,d--}n[c]=o,c--}return n},ge.add=function(e,t){for(var i=[],s=0,r=e.length;s=0;){for(n=a[i],s=i+1;ss?1:-1}));for(var l=[],h=0,c=r.length;h=.1*m*n||isNaN(u));)m*=.5,++x;if(m*g20)throw new A("Numerical gradient fails");if(d[m]=t[m]+g,r=e(d),d[m]=t[m]-g,n=e(d),d[m]=t[m],isNaN(r)||isNaN(n))g/=16;else{if(_[m]=(r-n)/(2*g),o=t[m]-g,a=t[m],l=t[m]+g,h=(r-s)/g,c=(s-n)/g,u=Ae.max([Math.abs(_[m]),Math.abs(s),Math.abs(r),Math.abs(n),Math.abs(o),Math.abs(a),Math.abs(l),1e-8]),!(Math.min(Ae.max([Math.abs(h-_[m]),Math.abs(c-_[m]),Math.abs(h-c)])/u,g/u)>.001))break;g/=16}}return _},Te.tensor=function(e,t){for(var i,s,r=e.length,n=t.length,o=[],a=r-1;a>=0;){i=[],s=e[a];for(var l=n-1;l>=3;)i[l]=s*t[l],i[--l]=s*t[l],i[--l]=s*t[l],i[--l]=s*t[l],--l;for(;l>=0;)i[l]=s*t[l],--l;o[a]=i,a--}return o};var ye=function(e,t,i,s,r,n){this.solution=e,this.value=t,this.gradient=i,this.invHessian=s,this.iterations=r,this.message=n};s["verb.core.MinimizationResult"]=ye,ye.__name__=["verb","core","MinimizationResult"],ye.prototype={__class__:ye};var Se=function(){};s["verb.core.ISerializable"]=Se,Se.__name__=["verb","core","ISerializable"],Se.prototype={__class__:Se};var Ce=t.core.Deserializer=function(){};s["verb.core.Deserializer"]=Ce,Ce.__name__=["verb","core","Deserializer"],Ce.deserialize=function(e){return new v(e).unserialize()};var Ee=t.core.Trig=function(){};s["verb.core.Trig"]=Ee,Ee.__name__=["verb","core","Trig"],Ee.isPointInPlane=function(e,t,i){return Math.abs(Ae.dot(Ae.sub(e,t.origin),t.normal))o?{u:r,pt:i}:{u:s+(r-s)*c/o,pt:Ae.add(a,Ae.mul(c,l))}};var Ae=t.core.Vec=function(){};s["verb.core.Vec"]=Ae,Ae.__name__=["verb","core","Vec"],Ae.angleBetween=function(e,t){return Math.acos(Ae.dot(e,t)/(Ae.norm(e)*Ae.norm(t)))},Ae.positiveAngleBetween=function(e,t,i){var s=Ae.cross(e,t),r=Ae.norm(e)*Ae.norm(t),n=Ae.dot(e,t),o=Ae.norm(s)/r,a=n/r,l=Math.atan2(o,a),h=Ae.dot(i,s);return Math.abs(h)0?l:-l},Ae.signedAngleBetween=function(e,t,i){var s=Ae.cross(e,t),r=Ae.norm(e)*Ae.norm(t),n=Ae.dot(e,t),o=Ae.norm(s)/r,a=n/r,l=Math.atan2(o,a);return Ae.dot(i,s)>0?l:2*Math.PI-l},Ae.angleBetweenNormalized2d=function(e,t){var i=e[0]*t[1]-e[1]*t[0];return Math.atan2(i,Ae.dot(e,t))},Ae.domain=function(e){return V.last(e)-V.first(e)},Ae.range=function(e){for(var t=[],i=0,s=0;st&&i>0)return[];if(t>e&&i<0)return[];for(var s=[],r=e;r<=t;)s.push(r),r+=i;return s},Ae.neg=function(e){return e.map((function(e){return-e}))},Ae.min=function(e){return a.fold(e,(function(e,t){return Math.min(e,t)}),1/0)},Ae.max=function(e){return a.fold(e,(function(e,t){return Math.max(e,t)}),-1/0)},Ae.all=function(e){return a.fold(e,(function(e,t){return t&&e}),!0)},Ae.finite=function(e){return e.map((function(e){return isFinite(e)}))},Ae.onRay=function(e,t,i){return Ae.add(e,Ae.mul(i,t))},Ae.lerp=function(e,t,i){return Ae.add(Ae.mul(e,t),Ae.mul(1-e,i))},Ae.normalized=function(e){return Ae.div(e,Ae.norm(e))},Ae.cross=function(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]},Ae.dist=function(e,t){return Ae.norm(Ae.sub(e,t))},Ae.distSquared=function(e,t){return Ae.normSquared(Ae.sub(e,t))},Ae.sum=function(e){return a.fold(e,(function(e,t){return t+e}),0)},Ae.addAll=function(e){var t=nt(e)();if(!t.hasNext())return null;var i=t.next().length;return a.fold(e,(function(e,t){return Ae.add(t,e)}),Ae.rep(i,0))},Ae.addAllMutate=function(e){for(var t=e[0],i=1,s=e.length;iz.TOLERANCE)return!1}return!0},Ae.sortedSetUnion=function(e,t){for(var i=[],s=0,r=0;s=e.length)i.push(t[r]),r++;else if(r>=t.length)i.push(e[s]),s++;else{var n=e[s]-t[r];Math.abs(n)0?(i.push(t[r]),r++):(i.push(e[s]),s++)}return i},Ae.sortedSetSub=function(e,t){for(var i=[],s=0,r=0;s=t.length?(i.push(e[s]),s++):Math.abs(e[s]-t[r])z.EPSILON&&(i=new Ie(r,0),t.push(i)),i.inc()}return t},Pe.isRationalSurfaceClosed=function(e,t){var i;null==t&&(t=!0);for(var s=0,r=(i=t?e.controlPoints:ge.transpose(e.controlPoints))[0].length;sh&&(A=d?[l+(A[0]-h),A[1]]:[h-z.EPSILON,A[1]]),A[1]u&&(A=_?[A[0],c+(A[0]-u)]:[A[0],u-z.EPSILON]),Ae.norm(Ae.mul(A[0]-r[0],i[1][0]))+Ae.norm(Ae.mul(A[1]-r[1],i[0][1]))x&&(A=b?v+(A-x):x),Ae.norm(Ae.mul(A-T,p[1]))(r=null!=s?s:Pe.rationalBezierCurveArcLength(e)))return V.last(e.knots);var n,o=e.knots[0],a=0,l=V.last(e.knots),h=r,c=0,u=0;for(n=null!=i?i:2*z.TOLERANCE;h-a>n;)c=(o+l)/2,(u=Pe.rationalBezierCurveArcLength(e,c))>t?(l=c,h=u):(o=c,a=u);return(o+l)/2},Pe.rationalCurveArcLength=function(e,t,i){null==i&&(i=16),null==t&&(t=V.last(e.knots));for(var s=Fe.decomposeCurveIntoBeziers(e),r=0,n=s[0],o=0;rz.EPSILON)return!1}i=V.last(e);for(var o=e.length-t-1,a=e.length;oz.EPSILON)return!1}return Re.isNonDecreasing(e)},Re.isNonDecreasing=function(e){for(var t=V.first(e),i=0,s=e.length;ir)return n;for(var o,a=t,l=0,h=a,c=0,u=0;l=t[l+1];)l++;o.push(l),n.push(De.basisFunctionsGivenKnotSpanIndex(l,a,e,t)),a+=r}return new q(o,n)},De.regularlySpacedDerivativeBasisFunctions=function(e,t,i){for(var s=t.length-e-2,r=(V.last(t)-t[0])/i,n=[],o=[],a=t[0],l=De.knotSpanGivenN(s,e,a,t),h=i+1,c=0;c=t[l+1];)l++;o.push(l),n.push(De.derivativeBasisFunctionsGivenNI(l,a,e,s,t)),a+=r}return new q(o,n)},De.surfacePointGivenBasesKnotSpans=function(e,t,i,s,r,n,o,a){for(var l,h=Ae.zeros1d(a),c=s-e,u=r-t,d=0,_=t+1;d<_;){var p=d++;l=Ae.zeros1d(a);for(var f=0,m=e+1;f=M&&(m[v][0]=m[g][0]/n[T+1][b],x=m[v][0]*n[b][T]);for(var O=b>=-1?1:-b,D=1+(P-1<=T?M-1:i-P);Os[e+1]-z.EPSILON)return e;if(i=s[o+1];)iz.EPSILON})),(function(e,t){var i=Ae.sub(e.min.uv0,t.min.uv0),s=Ae.dot(i,i),r=Ae.sub(e.max.uv0,t.max.uv0),n=Ae.dot(r,r),o=Ae.sub(e.min.uv0,t.max.uv0),a=Ae.dot(o,o),l=Ae.sub(e.max.uv0,t.min.uv0),h=Ae.dot(l,l);return s0&&(f.push(f[f.length-1].opp),u.push(f))}if(0==c.length&&r.length>0&&(_||d0;){var o=s.pop(),a=r.pop();if(!o.empty()&&!a.empty()&&o.boundingBox().intersects(a.boundingBox(),i)){var l=o.indivisible(i),h=a.indivisible(i);if(l&&h)n.push(new q(o.yield(),a.yield()));else if(!l||h)if(l||!h){var c=o.split(),u=a.split();s.push(c.item1),r.push(u.item1),s.push(c.item1),r.push(u.item0),s.push(c.item0),r.push(u.item1),s.push(c.item0),r.push(u.item0)}else{var d=o.split();s.push(d.item1),r.push(a),s.push(d.item0),r.push(a)}else{var _=a.split();s.push(o),r.push(_.item1),s.push(o),r.push(_.item0)}}}return n},we.curves=function(e,t,i){var s=we.boundingBoxTrees(new _e(e),new _e(t),0);return V.unique(s.map((function(s){return we.curvesWithEstimate(e,t,V.first(s.item0.knots),V.first(s.item1.knots),i)})).filter((function(e){return Ae.distSquared(e.point0,e.point1)h[_]+z.EPSILON||((null==c||vu.u)&&(u=new ne(v,Ae.onRay(e.origin,e.dir,v),Ae.onRay(n[_],o[_],g/h[_]))))}}return null==u||null==c?null:new Z(c,u)},we.mergeTriangleClipIntervals=function(e,t,i,s,r,n){if(t.min.u>e.max.u+z.EPSILON||e.min.u>t.max.u+z.EPSILON)return null;var o,a;o=e.min.u>t.min.u?new q(e.min,0):new q(t.min,1),a=e.max.uc&&(h=1,c=u),d>c&&(h=2,c=d),0==h?(n=t[1],o=t[2],a=s[1],l=s[2]):1==h?(n=t[0],o=t[2],a=s[0],l=s[2]):(n=t[0],o=t[1],a=s[0],l=s[1]);var _=-Ae.dot(e,t),p=-Ae.dot(i,s),f=n*l-o*a,m=(o*p-_*l)/f,g=(_*a-n*p)/f;return new X(0==h?[0,m,g]:1==h?[m,0,g]:[m,g,0],Ae.normalized(r))},we.threePlanes=function(e,t,i,s,r,n){var o=Ae.cross(i,r),a=Ae.dot(e,o);if(Math.abs(a)1)return null;var f=Ae.add(e,Ae.mul(p,c)),m=Ae.dot(a,l),g=Ae.dot(a,a),v=Ae.dot(l,l),x=Ae.sub(f,r),b=Ae.dot(x,a),T=Ae.dot(x,l),y=m*m-g*v;if(Math.abs(y)1+z.EPSILON||C>1+z.EPSILON||C<-z.EPSILON||S<-z.EPSILON||S+C>1+z.EPSILON?null:new re(f,S,C,p)},we.segmentAndPlane=function(e,t,i,s){var r=Ae.dot(s,Ae.sub(t,e));if(Math.abs(r)1+z.EPSILON||n<-z.EPSILON?null:{p:n}};var Ne=t.eval.Make=function(){};s["verb.eval.Make"]=Ne,Ne.__name__=["verb","eval","Make"],Ne.rationalTranslationalSurface=function(e,t){for(var i=De.rationalCurvePoint(t,V.first(t.knots)),s=V.first(t.knots),r=V.last(t.knots),n=2*t.controlPoints.length,o=(r-s)/(n-1),a=[],l=0;l=0&&(u-=n[o].mult),c=u>0?Fe.surfaceKnotRefine(e,Ae.rep(u,t),i):e;var d=De.knotSpan(r,t,s);return Math.abs(t-V.first(s))e.length-1&&(t=e.length-1);for(var s=e[0].knots,r=[],n=[],o=0,a=e[0].controlPoints.length;oz.EPSILON&&(E=Ae.mul(1/A,E),P=Ae.mul(1/A,P)),m[0][S]=o[S];var I=o[S];g[0][S]=a[S];for(var R=P,M=0,O=1,D=r+1;Ot?e:t},Fe.curveElevateDegree=function(e,t){if(t<=e.degree)return e;var i=e.knots.length-e.degree-2,s=e.degree,r=e.knots,n=e.controlPoints,o=t-e.degree,a=e.controlPoints[0].length,l=Ae.zeros2d(s+o+1,s+1),h=[],c=[],u=[],d=i+s+1,_=t,p=Math.floor(_/2),f=[],m=[];l[0][0]=1,l[_][s]=1;for(var g=1,v=p+1;g0?Math.floor((K+2)/2):1,X=D>0?Math.floor(_-(D+1)/2):_,D>0){for(var $=j-L,q=[],Z=s;Z>Q;)q[Z-Q-1]=$/(r[w+Z]-L),Z--;for(var J=1,ee=D+1;J=se;)h[re]=Ae.add(Ae.mul(q[re-se],h[re]),Ae.mul(1-q[re-se],h[re-1])),re--;u[ie]=h[s]}}for(var ne=H,oe=_+1;ne1)for(var de=O-2,_e=O,pe=j-L,fe=(j-m[O-1])/pe,me=1;mege;){if(ve=H){if(xe-ge<=O-_+K){var ye=(j-m[xe-ge])/pe;c[be]=Ae.lerp(ye,c[be],c[be+1])}}else c[be]=Ae.lerp(fe,c[be],c[be+1]);ve+=1,xe-=1,be-=1}de-=1,_e+=1}if(w!=s)for(var Se=0,Ce=_-K;Se=0;){for(;t[A]<=r[C]&&C>l;)c[E-i-1]=s[C-i-1],u[E]=r[C],E-=1,C-=1;c[E-i-1]=c[E-i];for(var P=1,I=i+1;Ps||!Ee.threePointsAreFlat(n,l,o,s)){var u=t+.5*(i-t),d=Le.rationalCurveAdaptiveSampleRange(e,t,u,s,r),_=Le.rationalCurveAdaptiveSampleRange(e,u,i,s,r);return d.slice(0,-1).concat(_)}return r?[[t].concat(n),[i].concat(o)]:[n,o]},Le.rationalSurfaceNaive=function(e,t,i){t<1&&(t=1),i<1&&(i=1),e.degreeU,e.degreeV,e.controlPoints;for(var s=e.knotsU,r=e.knotsV,n=(V.last(s)-s[0])/t,o=(V.last(r)-r[0])/i,a=[],l=[],h=[],c=0,u=t+1;cr?t.minDivsU=t.minDivsU:t.minDivsU=r,s=t.minDivsV>n?t.minDivsV=t.minDivsV:t.minDivsV=n;for(var o=V.last(e.knotsU),a=e.knotsU[0],l=V.last(e.knotsV),h=e.knotsV[0],c=(o-a)/i,u=(l-h)/s,d=[],_=[],p=0,f=s+1;pn.corners[0].uv[0]+r&&e.uv[0]n.corners[0].uv[1]+r&&e.uv[1]=e.maxDepth)return!1;if(this.hasBadNormals())return this.fixNormals(),!1;if(this.splitVert=Ae.normSquared(Ae.sub(this.corners[0].normal,this.corners[1].normal))>e.normTol||Ae.normSquared(Ae.sub(this.corners[2].normal,this.corners[3].normal))>e.normTol,this.splitHoriz=Ae.normSquared(Ae.sub(this.corners[1].normal,this.corners[2].normal))>e.normTol||Ae.normSquared(Ae.sub(this.corners[3].normal,this.corners[0].normal))>e.normTol,this.splitVert||this.splitHoriz)return!0;var i=this.center();return Ae.normSquared(Ae.sub(i.normal,this.corners[0].normal))>e.normTol||Ae.normSquared(Ae.sub(i.normal,this.corners[1].normal))>e.normTol||Ae.normSquared(Ae.sub(i.normal,this.corners[2].normal))>e.normTol||Ae.normSquared(Ae.sub(i.normal,this.corners[3].normal))>e.normTol},divide:function(e){null==e&&(e=new Be),null==e.normTol&&(e.normTol=.085),null==e.minDepth&&(e.minDepth=0),null==e.maxDepth&&(e.maxDepth=10),this._divide(e,0,!0)},_divide:function(e,t,i){if(this.evalCorners(),this.shouldDivide(e,t)){if(t++,this.splitVert&&!this.splitHoriz?i=!1:!this.splitVert&&this.splitHoriz&&(i=!0),this.horizontal=i,this.horizontal){var s=[this.corners[0],this.corners[1],this.midpoint(1),this.midpoint(3)],r=[this.midpoint(3),this.midpoint(1),this.corners[2],this.corners[3]];this.children=[new ke(this.srf,s),new ke(this.srf,r)],this.children[0].neighbors=[this.neighbors[0],this.neighbors[1],this.children[1],this.neighbors[3]],this.children[1].neighbors=[this.children[0],this.neighbors[1],this.neighbors[2],this.neighbors[3]]}else{var n=[this.corners[0],this.midpoint(0),this.midpoint(2),this.corners[3]],o=[this.midpoint(0),this.corners[1],this.corners[2],this.midpoint(2)];this.children=[new ke(this.srf,n),new ke(this.srf,o)],this.children[0].neighbors=[this.neighbors[0],this.children[1],this.neighbors[2],this.neighbors[3]],this.children[1].neighbors=[this.neighbors[0],this.neighbors[1],this.neighbors[2],this.children[0]]}for(var a=0,l=this.children;a0&&this._pool.length>0;){var i=this._queue.shift(),s=[i.id],r=[this._pool.shift()];this._working.h[s[0]]=r[0],r[0].onmessage=function(i,s){return function(r){t._working.remove(s[0]),t._pool.push(i[0]);try{t._callbacks.h.hasOwnProperty(s[0])&&(t._callbacks.h[s[0]](r.data.result),t._callbacks.remove(s[0]))}catch(t){t instanceof A&&(t=t.val),e.log(t)}t.processQueue()}}(r,s),r[0].postMessage(i)}},__class__:Ue};var Ge=function(e,t,i){this.className=e,this.methodName=t,this.args=i,this.id=Ge.uuid++};s["verb.exe._WorkerPool.Work"]=Ge,Ge.__name__=["verb","exe","_WorkerPool","Work"],Ge.prototype={__class__:Ge};var ze=function(){};s["verb.geom.ICurve"]=ze,ze.__name__=["verb","geom","ICurve"],ze.__interfaces__=[Se],ze.prototype={__class__:ze};var We=t.geom.NurbsCurve=function(e){this._data=Re.isValidNurbsCurveData(e)};s["verb.geom.NurbsCurve"]=We,We.__name__=["verb","geom","NurbsCurve"],We.__interfaces__=[ze],We.byKnotsControlPointsWeights=function(e,t,i,s){return new We(new Y(e,t.slice(),De.homogenize1d(i,s)))},We.byPoints=function(e,t){return null==t&&(t=3),new We(Ne.rationalInterpCurve(e,t))},We.__super__=W,We.prototype=n(W.prototype,{degree:function(){return this._data.degree},knots:function(){return this._data.knots.slice(0)},controlPoints:function(){return De.dehomogenize1d(this._data.controlPoints)},weights:function(){return De.weight1d(this._data.controlPoints)},asNurbs:function(){return new Y(this.degree(),this.knots(),De.homogenize1d(this.controlPoints(),this.weights()))},clone:function(){return new We(this._data)},domain:function(){return new Z(V.first(this._data.knots),V.last(this._data.knots))},transform:function(e){return new We(Fe.rationalCurveTransform(this._data,e))},transformAsync:function(e){return Ve.dispatchMethod(Fe,"rationalCurveTransform",[this._data,e]).then((function(e){return new We(e)}))},point:function(e){return De.rationalCurvePoint(this._data,e)},pointAsync:function(e){return Ve.dispatchMethod(De,"rationalCurvePoint",[this._data,e])},tangent:function(e){return De.rationalCurveTangent(this._data,e)},tangentAsync:function(e){return Ve.dispatchMethod(De,"rationalCurveTangent",[this._data,e])},derivatives:function(e,t){return null==t&&(t=1),De.rationalCurveDerivatives(this._data,e,t)},derivativesAsync:function(e,t){return null==t&&(t=1),Ve.dispatchMethod(De,"rationalCurveDerivatives",[this._data,e,t])},closestPoint:function(e){return Pe.rationalCurveClosestPoint(this._data,e)},closestPointAsync:function(e){return Ve.dispatchMethod(Pe,"rationalCurveClosestPoint",[this._data,e])},closestParam:function(e){return Pe.rationalCurveClosestParam(this._data,e)},closestParamAsync:function(e){return Ve.dispatchMethod(Pe,"rationalCurveClosestParam",[this._data,e])},length:function(){return Pe.rationalCurveArcLength(this._data)},lengthAsync:function(){return Ve.dispatchMethod(Pe,"rationalCurveArcLength",[this._data])},lengthAtParam:function(e){return Pe.rationalCurveArcLength(this._data,e)},lengthAtParamAsync:function(){return Ve.dispatchMethod(Pe,"rationalCurveArcLength",[this._data])},paramAtLength:function(e,t){return Pe.rationalCurveParamAtArcLength(this._data,e,t)},paramAtLengthAsync:function(e,t){return Ve.dispatchMethod(Pe,"rationalCurveParamAtArcLength",[this._data,e,t])},divideByEqualArcLength:function(e){return Me.rationalCurveByEqualArcLength(this._data,e)},divideByEqualArcLengthAsync:function(e){return Ve.dispatchMethod(Me,"rationalCurveByEqualArcLength",[this._data,e])},divideByArcLength:function(e){return Me.rationalCurveByArcLength(this._data,e)},divideByArcLengthAsync:function(e){return Ve.dispatchMethod(Me,"rationalCurveByArcLength",[this._data,e])},split:function(e){return Me.curveSplit(this._data,e).map((function(e){return new We(e)}))},splitAsync:function(e){return Ve.dispatchMethod(Me,"curveSplit",[this._data,e]).then((function(e){return e.map((function(e){return new We(e)}))}))},reverse:function(){return new We(Fe.curveReverse(this._data))},reverseAsync:function(){return Ve.dispatchMethod(Fe,"curveReverse",[this._data]).then((function(e){return new We(e)}))},tessellate:function(e){return Le.rationalCurveAdaptiveSample(this._data,e,!1)},tessellateAsync:function(e){return Ve.dispatchMethod(Le,"rationalCurveAdaptiveSample",[this._data,e,!1])},__class__:We});var He=t.geom.Arc=function(e,t,i,s,r,n){We.call(this,Ne.arc(e,t,i,s,r,n)),this._center=e,this._xaxis=t,this._yaxis=i,this._radius=s,this._minAngle=r,this._maxAngle=n};s["verb.geom.Arc"]=He,He.__name__=["verb","geom","Arc"],He.__super__=We,He.prototype=n(We.prototype,{center:function(){return this._center},xaxis:function(){return this._xaxis},yaxis:function(){return this._yaxis},radius:function(){return this._radius},minAngle:function(){return this._minAngle},maxAngle:function(){return this._maxAngle},__class__:He});var Xe=t.geom.BezierCurve=function(e,t){We.call(this,Ne.rationalBezierCurve(e,t))};s["verb.geom.BezierCurve"]=Xe,Xe.__name__=["verb","geom","BezierCurve"],Xe.__super__=We,Xe.prototype=n(We.prototype,{__class__:Xe});var Ye=t.geom.Circle=function(e,t,i,s){He.call(this,e,t,i,s,0,2*Math.PI)};s["verb.geom.Circle"]=Ye,Ye.__name__=["verb","geom","Circle"],Ye.__super__=He,Ye.prototype=n(He.prototype,{__class__:Ye});var Qe=function(){};s["verb.geom.ISurface"]=Qe,Qe.__name__=["verb","geom","ISurface"],Qe.__interfaces__=[Se],Qe.prototype={__class__:Qe};var je=t.geom.NurbsSurface=function(e){this._data=Re.isValidNurbsSurfaceData(e)};s["verb.geom.NurbsSurface"]=je,je.__name__=["verb","geom","NurbsSurface"],je.__interfaces__=[Qe],je.byKnotsControlPointsWeights=function(e,t,i,s,r,n){return new je(new Q(e,t,i,s,De.homogenize2d(r,n)))},je.byCorners=function(e,t,i,s){return new je(Ne.fourPointSurface(e,t,i,s))},je.byLoftingCurves=function(e,t){return new je(Ne.loftedSurface(function(t){for(var i=[],s=0;s{},439:()=>{},699:()=>{}},t={};function i(s){var r=t[s];if(void 0!==r)return r.exports;var n=t[s]={exports:{}};return e[s](n,n.exports,i),n.exports}i.d=(e,t)=>{for(var s in t)i.o(t,s)&&!i.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};return(()=>{"use strict";i.r(s),i.d(s,{Runner:()=>hY,fontsEnum:()=>eY,getRunnerInstance:()=>lY});var e={};i.r(e),i.d(e,{AbstractActionManager:()=>Y,AbstractAssetTask:()=>AI,AbstractEngine:()=>ns,AbstractMesh:()=>_o,AbstractScene:()=>X,AcquireNativeObjectAsync:()=>Zp,Action:()=>Ie,ActionEvent:()=>Re,ActionManager:()=>Qe,AddBlock:()=>rT,AddressMode:()=>mf,AdvancedTimer:()=>Sv,AlignBlock:()=>CC,AlphaState:()=>es,AmmoJSPlugin:()=>px,AnaglyphArcRotateCamera:()=>Ac,AnaglyphFreeCamera:()=>Pc,AnaglyphGamepadCamera:()=>Ic,AnaglyphPostProcess:()=>Cc,AnaglyphUniversalCamera:()=>Rc,Analyser:()=>fa,AndOrNotEvaluator:()=>bt,Angle:()=>$r,Animatable:()=>Qr,AnimatedInputBlockTypes:()=>pl,Animation:()=>Ft,AnimationAssetTask:()=>MI,AnimationEvent:()=>fn,AnimationGroup:()=>gn,AnimationGroupMask:()=>xn,AnimationGroupMaskMode:()=>Wr,AnimationKeyInterpolation:()=>$e,AnimationPropertiesOverride:()=>jr,AnimationRange:()=>qe,AnisotropyBlock:()=>XT,ApplyPostProcess:()=>Z_,Arc2:()=>qr,ArcFollowCamera:()=>fc,ArcRotateCamera:()=>hc,ArcRotateCameraGamepadInput:()=>Uh,ArcRotateCameraInputsManager:()=>Hh,ArcRotateCameraKeyboardMoveInput:()=>Gh,ArcRotateCameraMouseWheelInput:()=>zh,ArcRotateCameraPointersInput:()=>Wh,ArcRotateCameraVRDeviceOrientationInput:()=>Xh,ArcTan2Block:()=>PT,AssetContainer:()=>pa,AssetTaskState:()=>EI,AssetsManager:()=>kI,AssetsProgressEvent:()=>PI,AsyncLoop:()=>Ns,AttachToBoxBehavior:()=>ka,AudioEngine:()=>no,AudioSceneComponent:()=>va,AutoLayoutMode:()=>Pf,AutoReleaseWorkerPool:()=>Qg,AutoRotationBehavior:()=>Na,AxesViewer:()=>nd,Axis:()=>Xr,AxisDragGizmo:()=>rd,AxisScaleGizmo:()=>tg,BRDFTextureTools:()=>Ag,BabylonFileLoaderConfiguration:()=>yx,BackEase:()=>rn,BackgroundMaterial:()=>bg,BakedVertexAnimationManager:()=>ba,BallAndSocketConstraint:()=>yA,BaseCameraMouseWheelInput:()=>Ph,BaseCameraPointersInput:()=>Ih,BaseError:()=>Yt,BaseParticleSystem:()=>Yl,BaseSixDofDragBehavior:()=>Qa,BaseTexture:()=>ya,BasisFileInfo:()=>nb,BasisTools:()=>gb,BasisToolsOptions:()=>lb,BasisTranscodeConfiguration:()=>ob,BezierCurve:()=>Kr,BezierCurveEase:()=>pn,BiPlanarBlock:()=>dy,BinaryFileAssetTask:()=>DI,BindBonesParameters:()=>wo,BindFogParameters:()=>Co,BindLight:()=>Fo,BindLightProperties:()=>No,BindLights:()=>Lo,BindLogDepth:()=>So,BindMorphTargetParameters:()=>Io,BindSceneUniformBuffer:()=>Ro,BindTextureMatrix:()=>Oo,BlackAndWhitePostProcess:()=>$A,BlendFactor:()=>Df,BlendOperation:()=>wf,BloomEffect:()=>eP,BloomMergePostProcess:()=>JA,BlurPostProcess:()=>mg,Bone:()=>Yr,BoneAxesViewer:()=>od,BoneIKController:()=>Sh,BoneLookController:()=>Ch,BonesBlock:()=>Rb,BooleanGeometryBlock:()=>WC,BooleanGeometryOperations:()=>TS,BounceEase:()=>nn,BouncingBehavior:()=>Fa,BoundingBlock:()=>zC,BoundingBox:()=>Mn,BoundingBoxGizmo:()=>ig,BoundingBoxRenderer:()=>zP,BoundingInfo:()=>Ln,BoundingSphere:()=>On,BoxBlock:()=>zS,BoxBuilder:()=>ud,BoxParticleEmitter:()=>uE,Buffer:()=>Js,BufferBindingType:()=>Tf,BufferMapState:()=>lf,BufferUsage:()=>hf,CSG:()=>tS,Camera:()=>In,CameraGizmo:()=>fg,CameraInputTypes:()=>Fh,CameraInputsManager:()=>Lh,CannonJSPlugin:()=>dx,CanvasAlphaMode:()=>Wf,CapsuleBlock:()=>ZS,CapsuleBuilder:()=>gd,CascadedShadowGenerator:()=>Zv,ChromaticAberrationPostProcess:()=>tP,CircleEase:()=>sn,CircleOfConfusionPostProcess:()=>iP,ClampBlock:()=>oT,ClearCoatBlock:()=>QT,ClipPlanesBlock:()=>eT,ClipboardEventTypes:()=>Jm,ClipboardInfo:()=>eg,CloudBlock:()=>ly,CloudPoint:()=>jE,Collider:()=>Uu,Color3:()=>Ee,Color3Gradient:()=>EE,Color4:()=>Ae,ColorCorrectionPostProcess:()=>sP,ColorCurves:()=>Vs,ColorGradient:()=>CE,ColorGradingTexture:()=>kx,ColorMergerBlock:()=>uT,ColorSplitterBlock:()=>Ql,ColorWrite:()=>Of,CombineAction:()=>ze,CompareFunction:()=>xf,CompatibilityOptions:()=>Xn,CompilationMessageType:()=>Ef,CompleteGreasedLineColorTable:()=>LS,CompleteGreasedLineWidthTable:()=>FS,ComputeBindingType:()=>Wu,ComputeEffect:()=>zu,ComputeNormalsBlock:()=>pC,ComputePassTimestampLocation:()=>kf,ComputeShader:()=>Xu,ComputeShaderParticleSystem:()=>SE,Condition:()=>Me,ConditionBlock:()=>lC,ConditionBlockTests:()=>gS,ConditionalBlock:()=>ay,ConditionalBlockConditions:()=>ty,ConeParticleEmitter:()=>dE,Constants:()=>N_,ContainerAssetTask:()=>II,ConversionMode:()=>hI,ConvolutionPostProcess:()=>rP,Coordinate:()=>Gr,CopyTextureToTexture:()=>cI,CopyTools:()=>Aa,CreateBox:()=>cd,CreateBoxVertexData:()=>ld,CreateCapsule:()=>md,CreateCapsuleVertexData:()=>fd,CreateCylinder:()=>$u,CreateCylinderVertexData:()=>Ku,CreateDashedLines:()=>Gd,CreateDashedLinesVertexData:()=>kd,CreateDecal:()=>f_,CreateDisc:()=>yd,CreateDiscVertexData:()=>Td,CreateEnvTextureAsync:()=>yp,CreateGeodesic:()=>T_,CreateGoldberg:()=>C_,CreateGoldbergVertexData:()=>S_,CreateGreasedLine:()=>wS,CreateGreasedLineMaterial:()=>DS,CreateGround:()=>Iu,CreateGroundFromHeightMap:()=>Mu,CreateGroundFromHeightMapVertexData:()=>Pu,CreateGroundVertexData:()=>Eu,CreateHemisphere:()=>ug,CreateIcoSphere:()=>uh,CreateIcoSphereVertexData:()=>ch,CreateImageBitmapFromSource:()=>Jn,CreateImageDataArrayBufferViews:()=>Cp,CreateLathe:()=>t_,CreateLineSystem:()=>Vd,CreateLineSystemVertexData:()=>Bd,CreateLines:()=>Ud,CreatePlane:()=>Wa,CreatePlaneVertexData:()=>za,CreatePolygon:()=>jd,CreatePolygonVertexData:()=>Qd,CreatePolyhedron:()=>o_,CreatePolyhedronVertexData:()=>n_,CreateResizedCopy:()=>q_,CreateRibbon:()=>xd,CreateRibbonVertexData:()=>vd,CreateScreenshot:()=>aR,CreateScreenshotAsync:()=>lR,CreateScreenshotUsingRenderTarget:()=>cR,CreateScreenshotUsingRenderTargetAsync:()=>uR,CreateScreenshotWithResizeAsync:()=>hR,CreateSegmentedBoxVertexData:()=>hd,CreateSphere:()=>_d,CreateSphereVertexData:()=>dd,CreateText:()=>I_,CreateTextShapePaths:()=>P_,CreateTiledBox:()=>Id,CreateTiledBoxVertexData:()=>Pd,CreateTiledGround:()=>Ru,CreateTiledGroundVertexData:()=>Au,CreateTiledPlane:()=>Ed,CreateTiledPlaneVertexData:()=>Cd,CreateTorus:()=>wu,CreateTorusKnot:()=>Od,CreateTorusKnotVertexData:()=>Md,CreateTorusVertexData:()=>Du,CreateTube:()=>s_,CrossBlock:()=>aT,CubeMapToSphericalPolynomialTools:()=>$_,CubeTexture:()=>vg,CubeTextureAssetTask:()=>FI,CubicEase:()=>on,CullMode:()=>Mf,CurrentScreenBlock:()=>Dl,Curve3:()=>en,CurveBlock:()=>my,CurveBlockTypes:()=>sy,CustomBlock:()=>lT,CustomOptimization:()=>KI,CustomParticleEmitter:()=>xE,CustomProceduralTexture:()=>yb,CylinderBlock:()=>qS,CylinderBuilder:()=>qu,CylinderDirectedParticleEmitter:()=>pE,CylinderParticleEmitter:()=>_E,DDSTools:()=>_p,DataBuffer:()=>Qs,DataReader:()=>mR,DataStorage:()=>gR,Database:()=>cE,DebugBlock:()=>NC,DebugLayer:()=>ad,DebugLayerTab:()=>id,DecalBuilder:()=>m_,DecalMapConfiguration:()=>Ty,DecalMapDefines:()=>by,Decode:()=>qt,DecodeBase64ToBinary:()=>ei,DecodeBase64ToString:()=>Jt,DecodeBase64UrlToBinary:()=>xs,DecodeBase64UrlToString:()=>bs,DeepCopier:()=>Ye,DefaultCollisionCoordinator:()=>Gu,DefaultKTX2DecoderOptions:()=>Jg,DefaultLoadingScreen:()=>tx,DefaultRenderingPipeline:()=>EP,Deferred:()=>VI,DepthCullingState:()=>qi,DepthOfFieldBlurPostProcess:()=>nP,DepthOfFieldEffect:()=>lP,DepthOfFieldEffectBlurLevel:()=>aP,DepthOfFieldMergePostProcess:()=>oP,DepthPeelingRenderer:()=>XP,DepthPeelingSceneComponent:()=>YP,DepthReducer:()=>Yv,DepthRenderer:()=>Hv,DepthRendererSceneComponent:()=>WP,DepthSortedParticle:()=>XE,DerivativeBlock:()=>kb,DesaturateBlock:()=>WT,DetailMapConfiguration:()=>au,DeviceInputEventType:()=>yr,DeviceLostReason:()=>Hf,DeviceOrientationCamera:()=>cc,DeviceSource:()=>Ir,DeviceSourceManager:()=>Mr,DeviceType:()=>fr,DirectionalLight:()=>cg,DirectionalLightFrustumViewer:()=>w_,DiscBlock:()=>JS,DiscBuilder:()=>Sd,DiscardBlock:()=>Lb,DisplayPassPostProcess:()=>hP,DistanceBlock:()=>yT,DistanceConstraint:()=>SA,DistanceJoint:()=>tl,DivideBlock:()=>pT,DoNothingAction:()=>Ge,DomManagement:()=>zt,DotBlock:()=>hT,DracoCompression:()=>jy,DrawWrapper:()=>Un,DualSenseInput:()=>xr,DualShockButton:()=>wh,DualShockDpad:()=>Nh,DualShockInput:()=>vr,DualShockPad:()=>gc,DumpTools:()=>th,DynamicFloat32Array:()=>AR,DynamicTexture:()=>uu,EasingFunction:()=>tn,EdgesRenderer:()=>jP,Effect:()=>$i,EffectFallbacks:()=>Ll,EffectLayer:()=>wv,EffectLayerSceneComponent:()=>Nv,EffectRenderer:()=>Kl,EffectWrapper:()=>$l,ElasticEase:()=>an,ElbowBlock:()=>cy,EncodeArrayBufferToBase64:()=>Zt,EndsWith:()=>Kt,Engine:()=>oo,EngineFactory:()=>Zm,EngineFormat:()=>$g,EngineInstrumentation:()=>Ov,EngineStore:()=>re,EngineView:()=>k_,EnvironmentHelper:()=>Tg,EnvironmentTextureTools:()=>Mp,Epsilon:()=>J,EquiRectangularCubeTexture:()=>Vx,EquiRectangularCubeTextureAssetTask:()=>BI,ErrorCodes:()=>Qt,ErrorFilter:()=>Xf,EventConstants:()=>Sr,EventState:()=>Q,ExecuteCodeAction:()=>We,ExitFullscreen:()=>io,ExitPointerlock:()=>ro,ExponentialEase:()=>ln,ExternalTexture:()=>ym,ExtractHighlightsPostProcess:()=>ZA,ExtrudePolygon:()=>Kd,ExtrudeShape:()=>qd,ExtrudeShapeCustom:()=>Zd,FactorGradient:()=>AE,FadeInOutBehavior:()=>Va,FeatureName:()=>af,FileTools:()=>Ts,FileToolsOptions:()=>cs,FilesInput:()=>GI,FilesInputStore:()=>Ht,FilterMode:()=>gf,FilterPostProcess:()=>cP,FlowGraph:()=>iO,FlowGraphAbsBlock:()=>lD,FlowGraphAcosBlock:()=>VD,FlowGraphAcoshBlock:()=>YD,FlowGraphAddBlock:()=>qO,FlowGraphAsinBlock:()=>kD,FlowGraphAsinhBlock:()=>XD,FlowGraphAtan2Block:()=>GD,FlowGraphAtanBlock:()=>UD,FlowGraphAtanhBlock:()=>QD,FlowGraphBitwiseAndBlock:()=>uw,FlowGraphBitwiseLeftShiftBlock:()=>pw,FlowGraphBitwiseNotBlock:()=>cw,FlowGraphBitwiseOrBlock:()=>dw,FlowGraphBitwiseRightShiftBlock:()=>fw,FlowGraphBitwiseXorBlock:()=>_w,FlowGraphBlock:()=>QM,FlowGraphBranchBlock:()=>dO,FlowGraphCeilBlock:()=>dD,FlowGraphClampBlock:()=>TD,FlowGraphConditionalDataBlock:()=>IO,FlowGraphConnection:()=>AM,FlowGraphConnectionType:()=>EM,FlowGraphConsoleLogBlock:()=>oO,FlowGraphConstantBlock:()=>OO,FlowGraphContext:()=>ZM,FlowGraphContextLogger:()=>rO,FlowGraphCoordinateTransformBlock:()=>MO,FlowGraphCoordinator:()=>sO,FlowGraphCosBlock:()=>LD,FlowGraphCoshBlock:()=>WD,FlowGraphCountLeadingZerosBlock:()=>mw,FlowGraphCountOneBitsBlock:()=>vw,FlowGraphCountTrailingZerosBlock:()=>gw,FlowGraphCounterBlock:()=>bO,FlowGraphCrossBlock:()=>sw,FlowGraphCubeRootBlock:()=>JD,FlowGraphDataConnection:()=>zM,FlowGraphDebounceBlock:()=>yO,FlowGraphDegToRadBlock:()=>wD,FlowGraphDeterminantBlock:()=>aw,FlowGraphDivideBlock:()=>eD,FlowGraphDoNBlock:()=>_O,FlowGraphDotBlock:()=>iD,FlowGraphEBlock:()=>sD,FlowGraphEqBlock:()=>ED,FlowGraphEventBlock:()=>qM,FlowGraphExecutionBlock:()=>KM,FlowGraphExpBlock:()=>jD,FlowGraphFlipFlopBlock:()=>SO,FlowGraphFloorBlock:()=>uD,FlowGraphForLoopBlock:()=>pO,FlowGraphFractBlock:()=>_D,FlowGraphGetPropertyBlock:()=>DO,FlowGraphGetVariableBlock:()=>RO,FlowGraphGreaterThanBlock:()=>RD,FlowGraphGreaterThanOrEqualBlock:()=>MD,FlowGraphInfBlock:()=>nD,FlowGraphInterpolateBlock:()=>CD,FlowGraphInvertMatrixBlock:()=>lw,FlowGraphIsInfBlock:()=>DD,FlowGraphIsNanBlock:()=>OD,FlowGraphLengthBlock:()=>tw,FlowGraphLessThanBlock:()=>PD,FlowGraphLessThanOrEqualBlock:()=>ID,FlowGraphLog10Block:()=>qD,FlowGraphLog2Block:()=>$D,FlowGraphLogBlock:()=>KD,FlowGraphLogicAndBlock:()=>zO,FlowGraphLogicNotBlock:()=>HO,FlowGraphLogicOrBlock:()=>WO,FlowGraphMatMulBlock:()=>hw,FlowGraphMaxBlock:()=>vD,FlowGraphMeshPickEventBlock:()=>eO,FlowGraphMinBlock:()=>gD,FlowGraphMultiGateBlock:()=>gO,FlowGraphMultiplyBlock:()=>JO,FlowGraphNaNBlock:()=>oD,FlowGraphNegBlock:()=>pD,FlowGraphNormalizeBlock:()=>iw,FlowGraphPauseAnimationBlock:()=>PO,FlowGraphPiBlock:()=>rD,FlowGraphPlayAnimationBlock:()=>EO,FlowGraphPowBlock:()=>ew,FlowGraphRadToDegBlock:()=>ND,FlowGraphRandomBlock:()=>tD,FlowGraphReceiveCustomEventBlock:()=>bw,FlowGraphRemainderBlock:()=>mD,FlowGraphRotate2DBlock:()=>rw,FlowGraphRotate3DBlock:()=>nw,FlowGraphSaturateBlock:()=>SD,FlowGraphSceneReadyEventBlock:()=>xw,FlowGraphSceneTickEventBlock:()=>Tw,FlowGraphSendCustomEventBlock:()=>uO,FlowGraphSequenceBlock:()=>CO,FlowGraphSetPropertyBlock:()=>cO,FlowGraphSetVariableBlock:()=>aO,FlowGraphSignBlock:()=>hD,FlowGraphSignalConnection:()=>jM,FlowGraphSinBlock:()=>FD,FlowGraphSinhBlock:()=>zD,FlowGraphSqrtBlock:()=>ZD,FlowGraphState:()=>tO,FlowGraphStopAnimationBlock:()=>AO,FlowGraphSubtractBlock:()=>ZO,FlowGraphSwitchBlock:()=>vO,FlowGraphTanBlock:()=>BD,FlowGraphTanhBlock:()=>HD,FlowGraphThrottleBlock:()=>fO,FlowGraphTimerBlock:()=>mO,FlowGraphTransposeBlock:()=>ow,FlowGraphTruncBlock:()=>cD,FlowGraphWaitAllBlock:()=>xO,FlowGraphWhileLoopBlock:()=>TO,FluidRenderer:()=>fI,FluidRendererSceneComponent:()=>pI,FluidRenderingDebug:()=>oI,FluidRenderingObject:()=>sI,FluidRenderingObjectCustomParticles:()=>lI,FluidRenderingObjectParticleSystem:()=>rI,FluidRenderingTargetRenderer:()=>aI,FlyCamera:()=>dc,FlyCameraInputsManager:()=>uc,FlyCameraKeyboardInput:()=>Yh,FlyCameraMouseInput:()=>Qh,FogBlock:()=>Qb,FollowBehavior:()=>$a,FollowCamera:()=>pc,FollowCameraInputsManager:()=>_c,FollowCameraKeyboardMoveInput:()=>jh,FollowCameraMouseWheelInput:()=>Kh,FollowCameraPointersInput:()=>$h,FragCoordBlock:()=>Vb,FragDepthBlock:()=>Hb,FragmentOutputBlock:()=>El,FramingBehavior:()=>La,FreeCamera:()=>ac,FreeCameraDeviceOrientationInput:()=>ic,FreeCameraGamepadInput:()=>sc,FreeCameraInputsManager:()=>tc,FreeCameraKeyboardMoveInput:()=>qh,FreeCameraMouseInput:()=>Zh,FreeCameraMouseWheelInput:()=>Jh,FreeCameraTouchInput:()=>ec,FreeCameraVirtualJoystickInput:()=>nc,FresnelBlock:()=>xT,FresnelParameters:()=>Dx,FromHalfFloat:()=>ip,FrontFace:()=>Rf,FrontFacingBlock:()=>Bb,Frustum:()=>Fr,FxaaPostProcess:()=>uP,GIRSM:()=>xI,GIRSMManager:()=>bI,GIRSMRenderPluginMaterial:()=>yI,GPUParticleSystem:()=>UE,GUID:()=>Es,Gamepad:()=>kh,GamepadCamera:()=>Tc,GamepadManager:()=>vc,GamepadSystemSceneComponent:()=>xc,GaussianSplattingMaterial:()=>Vy,GaussianSplattingMesh:()=>aE,GenerateBase64StringFromPixelData:()=>Sa,GenerateBase64StringFromTexture:()=>Ca,GenerateBase64StringFromTextureAsync:()=>Ea,GenericPad:()=>Vh,GeodesicData:()=>b_,Geometry:()=>Yn,GeometryArcTan2Block:()=>HC,GeometryBufferRenderer:()=>mP,GeometryBufferRendererSceneComponent:()=>vP,GeometryClampBlock:()=>qC,GeometryCollectionBlock:()=>dC,GeometryCrossBlock:()=>ZC,GeometryCurveBlock:()=>JC,GeometryCurveBlockTypes:()=>yS,GeometryDesaturateBlock:()=>eE,GeometryDistanceBlock:()=>sE,GeometryDotBlock:()=>rE,GeometryElbowBlock:()=>_C,GeometryInfoBlock:()=>FC,GeometryInputBlock:()=>GS,GeometryLengthBlock:()=>nE,GeometryLerpBlock:()=>XC,GeometryModBlock:()=>KC,GeometryNLerpBlock:()=>YC,GeometryOptimizeBlock:()=>HS,GeometryOutputBlock:()=>VS,GeometryPosterizeBlock:()=>tE,GeometryPowBlock:()=>$C,GeometryReplaceColorBlock:()=>iE,GeometryRotate2dBlock:()=>oE,GeometrySmoothStepBlock:()=>jC,GeometryStepBlock:()=>QC,GeometryTextureBlock:()=>UC,GeometryTextureFetchBlock:()=>GC,GeometryTransformBlock:()=>xC,GeometryTrigonometryBlock:()=>vC,GeometryTrigonometryBlockOperations:()=>xS,GetClass:()=>W,GetClassName:()=>H,GetDOMTextContent:()=>Gt,GetEnvInfo:()=>bp,GetEnvironmentBRDFTexture:()=>Eg,GetFogState:()=>Uo,GetFontOffset:()=>Zn,GetInternalFormatFromBasisFormat:()=>hb,GetPointsCount:()=>NS,GetTGAHeader:()=>Jx,GetTextureDataAsync:()=>rp,Gizmo:()=>sd,GizmoAnchorPoint:()=>ed,GizmoCoordinatesMode:()=>td,GizmoManager:()=>lg,GlowLayer:()=>Fv,GoldbergMesh:()=>y_,GradientBlock:()=>FT,GradientBlockColorStep:()=>NT,GradientHelper:()=>PE,GrainPostProcess:()=>dP,GreasedLineBaseMesh:()=>RS,GreasedLineMaterialDefaults:()=>Ry,GreasedLineMesh:()=>MS,GreasedLineMeshColorDistribution:()=>cS,GreasedLineMeshColorDistributionType:()=>oy,GreasedLineMeshColorMode:()=>ny,GreasedLineMeshMaterialType:()=>ry,GreasedLineMeshWidthDistribution:()=>uS,GreasedLinePluginMaterial:()=>Dy,GreasedLineRibbonAutoDirectionMode:()=>hS,GreasedLineRibbonFacesMode:()=>lS,GreasedLineRibbonMesh:()=>OS,GreasedLineRibbonPointsMode:()=>aS,GreasedLineSimpleMaterial:()=>wy,GreasedLineTools:()=>My,GridBlock:()=>KS,GroundBuilder:()=>Ou,GroundMesh:()=>Cu,HDRCubeTexture:()=>nx,HDRCubeTextureAssetTask:()=>LI,HDRFiltering:()=>rx,HDRTools:()=>sx,Halton2DSequence:()=>zy,HandConstraintBehavior:()=>yh,HandConstraintOrientation:()=>bh,HandConstraintVisibility:()=>Th,HandConstraintZone:()=>xh,HandPart:()=>_h,HandleFallbacksForShadows:()=>Vo,HardwareScalingOptimization:()=>XI,HavokPlugin:()=>BA,HeightToNormalBlock:()=>Wb,HemisphereBuilder:()=>dg,HemisphericLight:()=>Zu,HemisphericParticleEmitter:()=>fE,HighlightLayer:()=>Bv,HighlightsPostProcess:()=>_P,Hinge2Joint:()=>rl,HingeConstraint:()=>CA,HingeJoint:()=>sl,HtmlElementTexture:()=>Ux,IWebXRControllerPhysicsOptions:()=>GR,IcoSphereBlock:()=>QS,IcoSphereBuilder:()=>dh,ImageAssetTask:()=>wI,ImageProcessingBlock:()=>wb,ImageProcessingConfiguration:()=>zs,ImageProcessingPostProcess:()=>pP,ImageSourceBlock:()=>Kb,IncrementValueAction:()=>ke,IndexFormat:()=>Ff,InputBlock:()=>Ol,InspectableType:()=>pR,InstancedLinesMesh:()=>Ld,InstancedMesh:()=>ca,InstancesBlock:()=>Mb,InstantiateBlock:()=>MC,InstantiateLinearBlock:()=>OC,InstantiateOnFacesBlock:()=>PC,InstantiateOnVerticesBlock:()=>AC,InstantiateOnVolumeBlock:()=>IC,InstantiateRadialBlock:()=>DC,InstantiatedEntries:()=>_a,IntFloatConverterBlock:()=>wC,InternalTexture:()=>ss,InternalTextureSource:()=>is,InterpolateValueAction:()=>Lt,IntersectionInfo:()=>Rn,IsBase64DataUrl:()=>gs,IsDocumentAvailable:()=>Ut,IsFileURL:()=>ms,IsNavigatorAvailable:()=>Vt,IsWindowObjectExist:()=>kt,IsWrapper:()=>Ws,JoystickAxis:()=>Mh,KeepAssets:()=>da,KeyboardEventTypes:()=>dr,KeyboardInfo:()=>_r,KeyboardInfoPre:()=>pr,KhronosTextureContainer:()=>Xg,KhronosTextureContainer2:()=>ev,LatheBuilder:()=>i_,Layer:()=>Vv,LayerSceneComponent:()=>kv,LengthBlock:()=>ST,LensFlare:()=>Uv,LensFlareSystem:()=>Gv,LensFlareSystemSceneComponent:()=>zv,LensFlaresOptimization:()=>jI,LensRenderingPipeline:()=>AP,LerpBlock:()=>_T,Light:()=>ua,LightBlock:()=>jb,LightGizmo:()=>pg,LightInformationBlock:()=>Db,LineEdgesRenderer:()=>KP,LinesBuilder:()=>zd,LinesMesh:()=>Fd,LoadFile:()=>ps,LoadFileError:()=>as,LoadImage:()=>ds,LoadOp:()=>Uf,LoadTextureFromTranscodeResult:()=>mb,LockConstraint:()=>AA,Logger:()=>Ne,MapMode:()=>cf,MapRangeBlock:()=>aC,MappingBlock:()=>LC,MappingTypes:()=>bS,Material:()=>ta,MaterialAnisotropicDefines:()=>wg,MaterialClearCoatDefines:()=>Rg,MaterialDefines:()=>xl,MaterialDetailMapDefines:()=>ou,MaterialFlags:()=>$c,MaterialGreasedLineDefines:()=>Oy,MaterialHelper:()=>wx,MaterialIridescenceDefines:()=>Og,MaterialPluginBase:()=>nu,MaterialPluginEvent:()=>fo,MaterialPluginManager:()=>Zc,MaterialSheenDefines:()=>Fg,MaterialSubSurfaceDefines:()=>Bg,MathBlock:()=>oC,MathBlockOperations:()=>mS,Matrix:()=>me,MatrixBuilderBlock:()=>ey,MatrixComposeBlock:()=>BC,MatrixDeterminantBlock:()=>_y,MatrixTransposeBlock:()=>py,MaxBlock:()=>bT,MergeGeometryBlock:()=>uC,MergeMeshesOptimization:()=>ZI,Mesh:()=>ha,MeshAssetTask:()=>RI,MeshAttributeExistsBlock:()=>fy,MeshAttributeExistsBlockTypes:()=>iy,MeshBlock:()=>YS,MeshBuilder:()=>R_,MeshDebugMode:()=>Fy,MeshDebugPluginMaterial:()=>By,MeshExploder:()=>UI,MeshLODLevel:()=>sa,MeshParticleEmitter:()=>bE,MeshUVSpaceRenderer:()=>iS,MeshoptCompression:()=>Ky,MinBlock:()=>TT,MinMaxReducer:()=>Xv,MipmapFilterMode:()=>vf,MirrorTexture:()=>gg,ModBlock:()=>JT,ModelShape:()=>HE,MorphTarget:()=>ox,MorphTargetManager:()=>lx,MorphTargetsBlock:()=>Ob,MotionBlurPostProcess:()=>xP,MotorEnabledJoint:()=>il,MultiMaterial:()=>ia,MultiObserver:()=>zI,MultiPointerScaleBehavior:()=>Ya,MultiRenderTarget:()=>xb,MultiplyBlock:()=>Wl,NLerpBlock:()=>LT,NativeDataStream:()=>fp,NativeEngine:()=>rf,NativePointerInput:()=>gr,NativeXRFrame:()=>CM,NativeXRLayerRenderTargetTextureProvider:()=>xu,NativeXRLayerWrapper:()=>vu,NativeXRRenderTarget:()=>bu,NegateBlock:()=>CT,Node:()=>Et,NodeGeometry:()=>WS,NodeGeometryBlock:()=>kS,NodeGeometryBlockConnectionPointTypes:()=>dS,NodeGeometryBuildState:()=>US,NodeGeometryConnectionPoint:()=>BS,NodeGeometryConnectionPointCompatibilityStates:()=>_S,NodeGeometryConnectionPointDirection:()=>pS,NodeGeometryContextualSources:()=>fS,NodeMaterial:()=>hh,NodeMaterialBlock:()=>Tl,NodeMaterialBlockConnectionPointMode:()=>dl,NodeMaterialBlockConnectionPointTypes:()=>al,NodeMaterialBlockTargets:()=>ll,NodeMaterialConnectionPoint:()=>bl,NodeMaterialConnectionPointCompatibilityStates:()=>hl,NodeMaterialConnectionPointCustomObject:()=>Ib,NodeMaterialConnectionPointDirection:()=>cl,NodeMaterialDefines:()=>lh,NodeMaterialModes:()=>Hl,NodeMaterialOptimizer:()=>gy,NodeMaterialSystemValues:()=>_l,NodeMaterialTeleportInBlock:()=>iT,NodeMaterialTeleportOutBlock:()=>sT,NoiseBlock:()=>cC,NoiseProceduralTexture:()=>Sb,NormalBlendBlock:()=>VT,NormalizeBlock:()=>cT,NormalizeVectorBlock:()=>mC,NullBlock:()=>eC,NullEngine:()=>L_,NullEngineOptions:()=>F_,Observable:()=>K,Observer:()=>j,OcclusionMaterial:()=>Nx,Octree:()=>Qu,OctreeBlock:()=>Yu,OctreeSceneComponent:()=>ju,OimoJSPlugin:()=>_x,OnAfterEnteringVRObservableEvent:()=>Bu,OneMinusBlock:()=>gT,Orientation:()=>zr,OutlineRenderer:()=>iI,PBRAnisotropicConfiguration:()=>Ng,PBRBaseMaterial:()=>Gg,PBRBaseSimpleMaterial:()=>Fx,PBRClearCoatConfiguration:()=>Mg,PBRIridescenceConfiguration:()=>Dg,PBRMaterial:()=>zg,PBRMaterialDefines:()=>Ug,PBRMetallicRoughnessBlock:()=>ZT,PBRMetallicRoughnessMaterial:()=>Lx,PBRSheenConfiguration:()=>Lg,PBRSpecularGlossinessMaterial:()=>Bx,PBRSubSurfaceConfiguration:()=>kg,PHI:()=>Z,PadNumber:()=>ti,PanoramaToCubeMapTools:()=>ix,Particle:()=>IE,ParticleBlendMultiplyBlock:()=>Fl,ParticleHelper:()=>zE,ParticleRampGradientBlock:()=>Nl,ParticleSystem:()=>VE,ParticleSystemSet:()=>GE,ParticleTextureBlock:()=>wl,ParticlesOptimization:()=>$I,PassCubePostProcess:()=>Sc,PassPostProcess:()=>yc,Path2:()=>Zr,Path3D:()=>Jr,PathCursor:()=>vn,PerfCollectionStrategy:()=>wR,PerfCounter:()=>wr,PerformanceConfigurator:()=>se,PerformanceMonitor:()=>Qn,PerformanceViewerCollector:()=>OR,PerturbNormalBlock:()=>Fb,PhotoDome:()=>Sg,Physics6DoFConstraint:()=>TA,Physics6DoFLimit:()=>bA,PhysicsActivationControl:()=>rA,PhysicsAggregate:()=>RA,PhysicsBody:()=>cA,PhysicsConstraint:()=>xA,PhysicsConstraintAxis:()=>ZE,PhysicsConstraintAxisLimitMode:()=>qE,PhysicsConstraintMotorType:()=>tA,PhysicsConstraintType:()=>JE,PhysicsEngine:()=>ux,PhysicsEngineV2:()=>hA,PhysicsEventType:()=>iA,PhysicsHelper:()=>UA,PhysicsImpostor:()=>nl,PhysicsJoint:()=>el,PhysicsMaterialCombineMode:()=>nA,PhysicsMotionType:()=>sA,PhysicsRadialExplosionEventOptions:()=>XA,PhysicsRadialImpulseFalloff:()=>oA,PhysicsRaycastResult:()=>cx,PhysicsShape:()=>uA,PhysicsShapeBox:()=>fA,PhysicsShapeCapsule:()=>_A,PhysicsShapeContainer:()=>vA,PhysicsShapeConvexHull:()=>mA,PhysicsShapeCylinder:()=>pA,PhysicsShapeMesh:()=>gA,PhysicsShapeSphere:()=>dA,PhysicsShapeType:()=>eA,PhysicsUpdraftEventOptions:()=>YA,PhysicsUpdraftMode:()=>aA,PhysicsViewer:()=>M_,PhysicsVortexEventOptions:()=>QA,PickingInfo:()=>tr,PipelineErrorReason:()=>Af,PivotTools:()=>Ga,Plane:()=>Nr,PlaneBlock:()=>XS,PlaneBuilder:()=>Ha,PlaneDragGizmo:()=>ng,PlaneRotationGizmo:()=>sg,PlayAnimationAction:()=>Ve,PlaySoundAction:()=>je,PointColor:()=>$E,PointLight:()=>ex,PointParticleEmitter:()=>mE,PointerDragBehavior:()=>Xa,PointerEventTypes:()=>lr,PointerInfo:()=>ur,PointerInfoBase:()=>hr,PointerInfoPre:()=>cr,PointerInput:()=>mr,PointsCloudSystem:()=>lA,PointsGroup:()=>KE,Polar:()=>Uy,Polygon:()=>Xd,PolygonBuilder:()=>$d,PolygonMeshBuilder:()=>Yd,PolyhedronBuilder:()=>a_,PolyhedronData:()=>x_,PositionGizmo:()=>og,PositionNormalTextureVertex:()=>Pl,PositionNormalVertex:()=>Al,PostProcess:()=>Vl,PostProcessManager:()=>ir,PostProcessRenderEffect:()=>qA,PostProcessRenderPipeline:()=>yP,PostProcessRenderPipelineManager:()=>SP,PostProcessRenderPipelineManagerSceneComponent:()=>CP,PostProcessesOptimization:()=>QI,PosterizeBlock:()=>OT,PowBlock:()=>ET,PowerEase:()=>hn,PowerPreference:()=>of,PrePassOutputBlock:()=>Yb,PrePassRenderer:()=>qP,PrePassRendererSceneComponent:()=>ZP,PrePassTextureBlock:()=>tT,PrecisionDate:()=>Wt,PredicateCondition:()=>De,PrepareAttributesForBakedVertexAnimation:()=>Do,PrepareAttributesForBones:()=>Bo,PrepareAttributesForInstances:()=>ko,PrepareAttributesForMorphTargets:()=>Ao,PrepareAttributesForMorphTargetsInfluencers:()=>Eo,PrepareDefinesForAttributes:()=>jo,PrepareDefinesForBakedVertexAnimation:()=>Qo,PrepareDefinesForBones:()=>Xo,PrepareDefinesForCamera:()=>Zo,PrepareDefinesForFrameBoundValues:()=>Ho,PrepareDefinesForLight:()=>Wo,PrepareDefinesForLights:()=>zo,PrepareDefinesForMergedUV:()=>Mo,PrepareDefinesForMisc:()=>Go,PrepareDefinesForMorphTargets:()=>Yo,PrepareDefinesForMultiview:()=>Ko,PrepareDefinesForOIT:()=>$o,PrepareDefinesForPrePass:()=>qo,PrepareUniformsAndSamplersForLight:()=>Jo,PrepareUniformsAndSamplersList:()=>ea,PressureObserverWrapper:()=>ER,PrimitiveTopology:()=>If,PrismaticConstraint:()=>PA,ProceduralTexture:()=>rh,ProceduralTextureSceneComponent:()=>sh,PropertyTypeForEdition:()=>ul,ProximityCastResult:()=>jA,PushAttributesForInstances:()=>Po,PushMaterial:()=>ml,QuadraticEase:()=>cn,QuadraticErrorSimplification:()=>PS,QuarticEase:()=>un,Quaternion:()=>fe,QueryType:()=>zf,QueueNewFrame:()=>rs,QuinticEase:()=>dn,RGBDTextureTools:()=>mp,RSMCreatePluginMaterial:()=>vI,Ragdoll:()=>OA,RagdollBoneProperties:()=>MA,RandomBlock:()=>hC,RandomBlockLocks:()=>vS,RandomGUID:()=>Cs,RandomNumberBlock:()=>AT,RawCubeTexture:()=>Cb,RawTexture:()=>Oa,RawTexture2DArray:()=>ax,RawTexture3D:()=>Eb,Ray:()=>Ua,RayHelper:()=>O_,ReadFile:()=>_s,ReadFileError:()=>hs,RecastJSCrowd:()=>hE,RecastJSPlugin:()=>lE,ReciprocalBlock:()=>RT,ReflectBlock:()=>GT,ReflectionBlock:()=>YT,ReflectionProbe:()=>fx,ReflectionTextureBaseBlock:()=>qb,ReflectionTextureBlock:()=>Zb,ReflectiveShadowMap:()=>mI,Reflector:()=>CR,RefractBlock:()=>zT,RefractionBlock:()=>KT,RefractionPostProcess:()=>bP,RefractionTexture:()=>Ab,RegisterClass:()=>z,RegisterMaterialPlugin:()=>iu,RegisterNativeTypeAsync:()=>Jp,RemapBlock:()=>Gl,RenderPassTimestampLocation:()=>Vf,RenderTargetTexture:()=>ih,RenderTargetWrapper:()=>Bl,RenderTargetsOptimization:()=>qI,RenderingGroup:()=>sr,RenderingGroupInfo:()=>rr,RenderingManager:()=>nr,ReplaceColorBlock:()=>MT,RequestFile:()=>fs,RequestFileError:()=>ls,RequestFullscreen:()=>to,RequestPointerlock:()=>so,ResizeImageBitmap:()=>eo,RetryStrategy:()=>Xt,RibbonBuilder:()=>bd,RichType:()=>IM,RichTypeAny:()=>RM,RichTypeBoolean:()=>DM,RichTypeColor3:()=>BM,RichTypeColor4:()=>kM,RichTypeFlowGraphInteger:()=>UM,RichTypeMatrix:()=>LM,RichTypeNumber:()=>OM,RichTypeQuaternion:()=>VM,RichTypeString:()=>MM,RichTypeVector2:()=>wM,RichTypeVector3:()=>NM,RichTypeVector4:()=>FM,RollingAverage:()=>jn,Rotate2dBlock:()=>UT,RotationGizmo:()=>rg,RotationXBlock:()=>bC,RotationYBlock:()=>TC,RotationZBlock:()=>yC,RuntimeAnimation:()=>Bt,RuntimeError:()=>jt,SSAO2RenderingPipeline:()=>IP,SSAORenderingPipeline:()=>RP,SSRRenderingPipeline:()=>LP,SamplerBindingType:()=>yf,Scalar:()=>be,ScaleBlock:()=>nT,ScaleGizmo:()=>ag,ScalingBlock:()=>SC,Scene:()=>Hr,SceneComponentConstants:()=>or,SceneDepthBlock:()=>Jb,SceneInstrumentation:()=>Dv,SceneLoader:()=>fl,SceneLoaderAnimationGroupLoadingMode:()=>ol,SceneLoaderFlags:()=>Hn,SceneOptimization:()=>WI,SceneOptimizer:()=>eR,SceneOptimizerOptions:()=>JI,ScenePerformancePriority:()=>Vr,SceneRecorder:()=>vR,SceneSerializer:()=>rR,ScreenSizeBlock:()=>Ub,ScreenSpaceBlock:()=>Gb,ScreenSpaceCurvaturePostProcess:()=>GP,ScreenSpaceReflectionPostProcess:()=>OP,ScreenshotTools:()=>_R,SerializationHelper:()=>St,SetBasisTranscoderWorker:()=>_b,SetColorsBlock:()=>rC,SetCorsBehavior:()=>us,SetMaterialIDBlock:()=>gC,SetNormalsBlock:()=>iC,SetParentAction:()=>He,SetPositionsBlock:()=>tC,SetStateAction:()=>Le,SetTangentsBlock:()=>nC,SetUVsBlock:()=>sC,SetValueAction:()=>Be,ShaderCodeInliner:()=>Bp,ShaderLanguage:()=>di,ShaderMaterial:()=>Nd,ShaderStage:()=>bf,ShaderStore:()=>Bi,ShadowDepthWrapper:()=>xy,ShadowGenerator:()=>Wv,ShadowGeneratorSceneComponent:()=>Jv,ShadowLight:()=>hg,ShadowMapBlock:()=>Xb,ShadowsOptimization:()=>YI,ShapeBuilder:()=>e_,ShapeCastResult:()=>KA,SharpenPostProcess:()=>TP,SheenBlock:()=>HT,SimplexPerlin3DBlock:()=>kT,SimplicationQueueSceneComponent:()=>IS,SimplificationQueue:()=>nS,SimplificationSettings:()=>rS,SimplificationType:()=>oS,SineEase:()=>_n,SixDofDragBehavior:()=>ja,Size:()=>At,Skeleton:()=>Da,SkeletonViewer:()=>D_,SliderConstraint:()=>EA,SmartArray:()=>Fs,SmartArrayNoDuplicate:()=>Ls,SmoothStepBlock:()=>IT,SolidParticle:()=>WE,SolidParticleSystem:()=>QE,SolidParticleVertex:()=>YE,Sound:()=>ma,SoundTrack:()=>ga,SourceTextureFormat:()=>jg,Space:()=>Ur,SphereBlock:()=>jS,SphereBuilder:()=>pd,SphereDirectedParticleEmitter:()=>vE,SphereParticleEmitter:()=>gE,Spherical:()=>Gy,SphericalHarmonics:()=>Q_,SphericalPolynomial:()=>j_,SpotLight:()=>_g,SpringConstraint:()=>IA,Sprite:()=>gx,SpriteManager:()=>bx,SpriteMap:()=>SI,SpritePackedManager:()=>CI,SpriteSceneComponent:()=>vx,Stage:()=>ar,StandardMaterial:()=>cu,StandardMaterialDefines:()=>hu,StandardRenderingPipeline:()=>DP,StartsWith:()=>$t,StateCondition:()=>we,StencilOperation:()=>Nf,StencilState:()=>Ji,StencilStateComposer:()=>Zi,StepBlock:()=>mT,StereoscopicArcRotateCamera:()=>wc,StereoscopicFreeCamera:()=>Nc,StereoscopicGamepadCamera:()=>Fc,StereoscopicInterlacePostProcess:()=>Oc,StereoscopicInterlacePostProcessI:()=>Mc,StereoscopicScreenUniversalCamera:()=>Bc,StereoscopicUniversalCamera:()=>Lc,StickValues:()=>Bh,StopAnimationAction:()=>Ue,StopSoundAction:()=>Ke,StorageBuffer:()=>Eh,StorageTextureAccess:()=>Cf,StoreOp:()=>Gf,StringDictionary:()=>Bs,StringTools:()=>ii,SubEmitter:()=>OE,SubEmitterType:()=>ME,SubMesh:()=>Gn,SubSurfaceBlock:()=>$T,SubSurfaceSceneComponent:()=>tI,SubtractBlock:()=>fT,SurfaceMagnetismBehavior:()=>Ka,SwitchBooleanAction:()=>Fe,SwitchInput:()=>Tr,TAARenderingPipeline:()=>BP,TBNBlock:()=>Nb,TGATools:()=>tb,Tags:()=>Tt,TargetCamera:()=>oc,TargetedAnimation:()=>mn,TeleportInBlock:()=>kC,TeleportOutBlock:()=>VC,TestBase64DataUrl:()=>vs,TextFileAssetTask:()=>OI,Texture:()=>Pa,TextureAspect:()=>pf,TextureAssetTask:()=>NI,TextureBlock:()=>$b,TextureDimension:()=>uf,TextureFormat:()=>ff,TextureOptimization:()=>HI,TexturePacker:()=>Tb,TexturePackerFrame:()=>bb,TextureSampleType:()=>Sf,TextureSampler:()=>ts,TextureTools:()=>np,TextureUsage:()=>df,TextureViewDimension:()=>_f,ThinEngine:()=>qs,ThinRenderTargetTexture:()=>Pb,ThinTexture:()=>Ta,TiledBoxBuilder:()=>Rd,TiledPlaneBuilder:()=>Ad,TimerState:()=>gv,TmpColors:()=>Pe,TmpVectors:()=>ve,ToGammaSpace:()=>$,ToHalfFloat:()=>tp,ToLinearSpace:()=>q,TonemapPostProcess:()=>VP,TonemappingOperator:()=>kP,Tools:()=>Ds,TorusBlock:()=>$S,TorusBuilder:()=>Nu,TorusKnotBuilder:()=>Dd,TouchCamera:()=>lc,TrailMesh:()=>sS,Trajectory:()=>xR,TrajectoryClassifier:()=>SR,TranscodeAsync:()=>pb,TranscodeTarget:()=>Kg,TransformBlock:()=>yl,TransformNode:()=>lo,TranslationBlock:()=>EC,TriPlanarBlock:()=>uy,TrigonometryBlock:()=>oh,TrigonometryBlockOperations:()=>nh,TubeBuilder:()=>r_,TwirlBlock:()=>zb,UniformBuffer:()=>Zs,UniversalCamera:()=>bc,UnregisterAllMaterialPlugins:()=>ru,UnregisterMaterialPlugin:()=>su,UploadContent:()=>eb,UploadEnvLevelsAsync:()=>Ep,UploadEnvSpherical:()=>Ip,UploadLevelsAsync:()=>Pp,UtilityLayerRenderer:()=>Ju,VRCameraMetrics:()=>Vc,VRDeviceOrientationArcRotateCamera:()=>Yc,VRDeviceOrientationFreeCamera:()=>Qc,VRDeviceOrientationGamepadCamera:()=>jc,VRDistortionCorrectionPostProcess:()=>Uc,VRExperienceHelper:()=>ku,VRMultiviewToSingleviewPostProcess:()=>Hc,ValidatedNativeDataStream:()=>nf,ValueCondition:()=>Oe,Vector2:()=>de,Vector2ToFixed:()=>Wy,Vector3:()=>_e,Vector3ToFixed:()=>Hy,Vector4:()=>pe,Vector4ToFixed:()=>Xy,VectorConverterBlock:()=>fC,VectorMergerBlock:()=>Ul,VectorSplitterBlock:()=>dT,VertexAnimationBaker:()=>wa,VertexBuffer:()=>er,VertexData:()=>Wn,VertexDataMaterialInfo:()=>zn,VertexFormat:()=>Lf,VertexOutputBlock:()=>Sl,VertexStepMode:()=>Bf,VideoDome:()=>Mv,VideoRecorder:()=>nR,VideoTexture:()=>Rv,ViewDirectionBlock:()=>vT,Viewport:()=>Pn,VirtualJoystick:()=>rc,VirtualJoysticksCamera:()=>kc,VolumetricLightScatteringPostProcess:()=>UP,VoronoiNoiseBlock:()=>hy,WaveBlock:()=>wT,WaveBlockKind:()=>DT,WebGL2ParticleSystem:()=>yE,WebGL2ShaderProcessor:()=>Ys,WebGLDataBuffer:()=>js,WebGLHardwareTexture:()=>Ks,WebGLPipelineContext:()=>ki,WebGPUCacheBindGroups:()=>Am,WebGPUCacheRenderPipeline:()=>gm,WebGPUCacheRenderPipelineTree:()=>xm,WebGPUCacheSampler:()=>_m,WebGPUDataBuffer:()=>lm,WebGPUDrawContext:()=>Cm,WebGPUEngine:()=>Ym,WebGPURenderTargetWrapper:()=>qm,WebGPUTintWASM:()=>Um,WebRequest:()=>Pt,WebXRAbstractFeature:()=>Ja,WebXRAbstractMotionController:()=>nv,WebXRAnchorSystem:()=>BR,WebXRBackgroundRemover:()=>UR,WebXRCamera:()=>iv,WebXRControllerComponent:()=>rv,WebXRControllerMovement:()=>$R,WebXRControllerPhysics:()=>zR,WebXRControllerPointerSelection:()=>pv,WebXRDefaultExperience:()=>Av,WebXRDefaultExperienceOptions:()=>Ev,WebXRDepthSensing:()=>uM,WebXRDomOverlay:()=>KR,WebXREnterExitUI:()=>Tv,WebXREnterExitUIButton:()=>xv,WebXREnterExitUIOptions:()=>bv,WebXRExperienceHelper:()=>sv,WebXREyeTracking:()=>ZR,WebXRFeatureName:()=>qa,WebXRFeaturePointSystem:()=>HR,WebXRFeaturesManager:()=>Za,WebXRGenericHandController:()=>mM,WebXRGenericTriggerMotionController:()=>ov,WebXRHTCViveMotionController:()=>yM,WebXRHand:()=>gh,WebXRHandJoint:()=>ph,WebXRHandTracking:()=>vh,WebXRHitTest:()=>WR,WebXRHitTestLegacy:()=>FR,WebXRImageTracking:()=>jR,WebXRInput:()=>_v,WebXRInputSource:()=>dv,WebXRLayerRenderTargetTextureProvider:()=>_u,WebXRLayers:()=>cM,WebXRLightEstimation:()=>qR,WebXRManagedOutputCanvas:()=>gu,WebXRManagedOutputCanvasOptions:()=>mu,WebXRMeshDetector:()=>YR,WebXRMicrosoftMixedRealityController:()=>vM,WebXRMotionControllerManager:()=>cv,WebXRMotionControllerTeleportation:()=>Cv,WebXRNearControllerMode:()=>mv,WebXRNearInteraction:()=>vv,WebXROculusTouchMotionController:()=>bM,WebXRPlaneDetector:()=>VR,WebXRProfiledMotionController:()=>lv,WebXRRawCameraAccess:()=>fM,WebXRSessionManager:()=>Tu,WebXRSpaceWarp:()=>pM,WebXRSpaceWarpRenderTargetTextureProvider:()=>_M,WebXRState:()=>yu,WebXRTrackingState:()=>Su,WebXRWalkingLocomotion:()=>sM,WeightedSound:()=>xa,WorkerPool:()=>Yg,WorleyNoise3DBlock:()=>BT,XRSpaceWarpRenderTarget:()=>dM,Xbox360Button:()=>Oh,Xbox360Dpad:()=>Dh,Xbox360Pad:()=>mc,XboxInput:()=>br,_BabylonLoaderRegistered:()=>Tx,_BasisTextureLoader:()=>vb,_CommonDispose:()=>qn,_CommonInit:()=>$n,_CreationDataStorage:()=>ra,_DDSTextureLoader:()=>Wg,_ENVTextureLoader:()=>Hg,_HDRTextureLoader:()=>sb,_InstancesBatch:()=>oa,_KTXTextureLoader:()=>tv,_MeshCollisionData:()=>ho,_OcclusionDataStorage:()=>B_,_PrimaryIsoTriangle:()=>v_,_TGATextureLoader:()=>ib,_TimeToken:()=>G_,_UpdateRGBDAsync:()=>Rp,_forceSceneHelpersToBundle:()=>Pv,_forceTransformFeedbackToBundle:()=>z_,_injectLTSFileTools:()=>ys,_staticOffsetValueColor3:()=>Dt,_staticOffsetValueColor4:()=>wt,_staticOffsetValueQuaternion:()=>It,_staticOffsetValueSize:()=>Ot,_staticOffsetValueVector2:()=>Mt,_staticOffsetValueVector3:()=>Rt,addClipPlaneUniforms:()=>mo,allocateAndCopyTypedBuffer:()=>Kn,bindClipPlane:()=>xo,captureEquirectangularFromScene:()=>NR,className:()=>ws,createDetailMapPlugin:()=>Iy,createPBRAnisotropicPlugin:()=>yy,createPBRBRDFPlugin:()=>Sy,createPBRClearCoatPlugin:()=>Cy,createPBRIridescencePlugin:()=>Ey,createPBRSheenPlugin:()=>Ay,createPBRSubSurfacePlugin:()=>Py,createYieldingScheduler:()=>Tn,editableInPropertyPage:()=>Cl,expandToProperty:()=>st,extractMinAndMax:()=>Vn,extractMinAndMaxIndexed:()=>kn,getRichTypeFromValue:()=>GM,inlineScheduler:()=>bn,makeAsyncFunction:()=>An,makeSyncFunction:()=>En,nativeOverride:()=>gt,normalizeEnvInfo:()=>Tp,prepareDefinesForClipPlanes:()=>vo,prepareStringDefinesForClipPlanes:()=>go,runCoroutine:()=>yn,runCoroutineAsync:()=>Cn,runCoroutineSync:()=>Sn,serialize:()=>rt,serializeAsCameraReference:()=>mt,serializeAsColor3:()=>ot,serializeAsColor4:()=>dt,serializeAsColorCurves:()=>ut,serializeAsFresnelParameters:()=>at,serializeAsImageProcessingConfiguration:()=>_t,serializeAsMatrix:()=>ft,serializeAsMeshReference:()=>ct,serializeAsQuaternion:()=>pt,serializeAsTexture:()=>nt,serializeAsVector2:()=>lt,serializeAsVector3:()=>ht,setAndStartTimer:()=>yv,setStereoscopicAnaglyphRigMode:()=>Ec,setStereoscopicRigMode:()=>Dc,setVRRigMode:()=>Xc});var t={};i.r(t),i.d(t,{AbstractButton3D:()=>AN,AdvancedDynamicTexture:()=>xN,AdvancedDynamicTextureInstrumentation:()=>bN,BaseGradient:()=>fN,BaseSlider:()=>Zw,Button:()=>Bw,Button3D:()=>PN,Checkbox:()=>Vw,CheckboxGroup:()=>tN,ColorPicker:()=>Ww,Container:()=>Dw,Container3D:()=>IN,Control:()=>Ow,Control3D:()=>CN,CornerHandle:()=>jN,CylinderPanel:()=>MN,DisplayGrid:()=>dN,Ellipse:()=>Hw,FluentBackplateMaterial:()=>LN,FluentButtonMaterial:()=>UN,FluentMaterial:()=>DN,FluentMaterialDefines:()=>ON,FocusableButton:()=>Xw,GUI3DManager:()=>vF,GizmoHandle:()=>YN,Grid:()=>zw,HandMenu:()=>NN,HandleMaterial:()=>HN,HandleState:()=>XN,HolographicBackplate:()=>BN,HolographicButton:()=>kN,HolographicSlate:()=>$N,Image:()=>Lw,ImageBasedSlider:()=>_N,ImageScrollBar:()=>aN,InputPassword:()=>Qw,InputText:()=>Gw,InputTextArea:()=>Yw,KeyPropertySet:()=>cN,Line:()=>jw,LinearGradient:()=>mN,MRDLBackplateMaterial:()=>oF,MRDLSliderBarMaterial:()=>iF,MRDLSliderThumbMaterial:()=>rF,MathTools:()=>Mw,Matrix2D:()=>Rw,Measure:()=>Pw,MeshButton3D:()=>qN,MultiLine:()=>$w,MultiLinePoint:()=>Kw,NearMenu:()=>ZN,PlanePanel:()=>JN,RadialGradient:()=>gN,RadioButton:()=>qw,RadioGroup:()=>iN,Rectangle:()=>ww,ScatterPanel:()=>eF,ScrollBar:()=>oN,ScrollViewer:()=>lN,SelectionPanel:()=>rN,SelectorGroup:()=>eN,SideHandle:()=>QN,SlateGizmo:()=>KN,Slider:()=>Jw,Slider3D:()=>aF,SliderGroup:()=>sN,SpherePanel:()=>lF,StackPanel:()=>kw,StackPanel3D:()=>hF,Style:()=>vN,TextBlock:()=>Fw,TextWrapper:()=>Uw,TextWrapping:()=>Nw,ToggleButton:()=>hN,TouchButton3D:()=>GN,TouchHolographicButton:()=>zN,TouchHolographicButtonV3:()=>gF,TouchHolographicMenu:()=>wN,TouchMeshButton3D:()=>cF,ValueAndUnit:()=>yw,Vector2WithInfo:()=>Iw,Vector3WithInfo:()=>SN,VirtualKeyboard:()=>uN,VolumeBasedPanel:()=>RN,XmlLoader:()=>yN,name:()=>pN});var r={};i.r(r),i.d(r,{LodDto:()=>Xz,lodEnum:()=>Bz});var n={};i.r(n),i.d(n,{Part:()=>Yz});var o={};i.r(o),i.d(o,{SerenitySwirlData:()=>jz,SerenitySwirlDto:()=>Qz});var a={};i.r(a),i.d(a,{ArabicArchwayData:()=>qz,ArabicArchwayDrawingPart:()=>Zz,ArabicArchwayDrawingPartShapes:()=>Jz,ArabicArchwayDto:()=>$z,ArabicArchwayDtoBase:()=>Kz});var l={};i.r(l),i.d(l,{ArabicArchway:()=>a,SerenitySwirl:()=>o});var h={};i.r(h),i.d(h,{EternalLoveData:()=>iW,EternalLoveDto:()=>tW,EternalLoveDtoBase:()=>eW});var c={};i.r(c),i.d(c,{EternalLove:()=>h});var u={};i.r(u),i.d(u,{CalmCupData:()=>nW,CalmCupDto:()=>rW,CalmCupDtoBase:()=>sW});var d={};i.r(d),i.d(d,{DragonCupData:()=>lW,DragonCupDto:()=>aW,DragonCupDtoBase:()=>oW,DragonCupModelDto:()=>hW});var _={};i.r(_),i.d(_,{CalmCup:()=>u,DragonCup:()=>d});var p={};i.r(p),i.d(p,{PhoneNestData:()=>dW,PhoneNestDrawDto:()=>gW,PhoneNestDrawingPart:()=>_W,PhoneNestDrawingPartShapes:()=>pW,PhoneNestDto:()=>uW,PhoneNestDtoBase:()=>cW,PhoneNestMainPart:()=>fW,PhoneNestModelDto:()=>mW});var f={};i.r(f),i.d(f,{PhoneNest:()=>p});var m={};i.r(m),i.d(m,{SpicyBoxData:()=>bW,SpicyBoxDto:()=>xW,SpicyBoxDtoBase:()=>vW,SpicyBoxModelDto:()=>TW});var g={};i.r(g),i.d(g,{SpicyBox:()=>m});var v={};i.r(v),i.d(v,{Boxes:()=>g,Cups:()=>_,Desktop:()=>f,Medals:()=>c,Vases:()=>l});var x={};i.r(x),i.d(x,{ZenHideoutData:()=>CW,ZenHideoutDrawingPart:()=>EW,ZenHideoutDrawingPartShapes:()=>AW,ZenHideoutDto:()=>SW,ZenHideoutDtoBase:()=>yW});var b={};i.r(b),i.d(b,{ZenHideout:()=>x});var T={};i.r(T),i.d(T,{BeamPart:()=>BW,CeilingPart:()=>YW,ColumnPart:()=>LW,CornerEntranceDto:()=>jW,CornerEntrancePart:()=>WW,CornerPart:()=>FW,CornerStairDto:()=>GW,CornerStairPart:()=>zW,FloorPart:()=>QW,Houses:()=>b,RoofBeamsPart:()=>VW,RoofCoverOneSidedDto:()=>HW,RoofCoverPart:()=>XW,RoofPanelPart:()=>UW,RoofPart:()=>kW,SandwitchPanelDto:()=>OW,SandwitchPanelFlexDto:()=>DW,SandwitchPart:()=>wW,SandwitchPartFlex:()=>NW,WindowCornerDto:()=>PW,WindowCornerPart:()=>MW,WindowRectangularDto:()=>IW,WindowRectangularPart:()=>RW});var y={};i.r(y),i.d(y,{WingtipVillaData:()=>$W,WingtipVillaDto:()=>KW});var S={};i.r(S),i.d(S,{ChirpyChaletData:()=>ZW,ChirpyChaletDto:()=>qW});var C={};i.r(C),i.d(C,{ChirpyChalet:()=>S,WingtipVilla:()=>y});var E={};i.r(E),i.d(E,{BirdHouses:()=>C});var A={};i.r(A),i.d(A,{SnakeChairData:()=>tH,SnakeChairDrawDto:()=>oH,SnakeChairDrawingPart:()=>iH,SnakeChairDrawingPartShapes:()=>sH,SnakeChairDto:()=>eH,SnakeChairDtoBase:()=>JW,SnakeChairMainPart:()=>rH,SnakeChairModelDto:()=>nH});var P={};i.r(P),i.d(P,{SnakeChair:()=>A});var I={};i.r(I),i.d(I,{ElegantTableData:()=>hH,ElegantTableDrawDto:()=>mH,ElegantTableDrawingPart:()=>cH,ElegantTableDrawingPartShapes:()=>uH,ElegantTableDto:()=>lH,ElegantTableDtoBase:()=>aH,ElegantTableLegByIndexDto:()=>pH,ElegantTableLegPart:()=>dH,ElegantTableModelDto:()=>fH,ElegantTableTopPart:()=>_H});var R={};i.r(R),i.d(R,{GoodCoffeeTableData:()=>xH,GoodCoffeeTableDrawDto:()=>PH,GoodCoffeeTableDrawingPart:()=>bH,GoodCoffeeTableDrawingPartShapes:()=>TH,GoodCoffeeTableDto:()=>vH,GoodCoffeeTableDtoBase:()=>gH,GoodCoffeeTableLegByIndexDto:()=>EH,GoodCoffeeTableLegPart:()=>yH,GoodCoffeeTableModelDto:()=>AH,GoodCoffeeTableShelfPart:()=>SH,GoodCoffeeTableTopPart:()=>CH});var M={};i.r(M),i.d(M,{SnakeTableData:()=>MH,SnakeTableDrawDto:()=>FH,SnakeTableDrawingPart:()=>OH,SnakeTableDrawingPartShapes:()=>DH,SnakeTableDto:()=>RH,SnakeTableDtoBase:()=>IH,SnakeTableMainPart:()=>wH,SnakeTableModelDto:()=>NH});var O={};i.r(O),i.d(O,{ElegantTable:()=>I,GoodCoffeeTable:()=>R,SnakeTable:()=>M});var D={};i.r(D),i.d(D,{Chairs:()=>P,Tables:()=>O});var w={};i.r(w),i.d(w,{Architecture:()=>T,Enums:()=>r,Furniture:()=>D,KidsCorner:()=>E,Shared:()=>n,ThreeDPrinting:()=>v});var N={};i.r(N),i.d(N,{FontDefinition:()=>GH,Text3DData:()=>VH,Text3DDto:()=>BH,Text3DFaceDefinitionDto:()=>WH,Text3DFaceDto:()=>kH,Text3DLetterByIndexDto:()=>UH,Text3DModelDto:()=>zH,Texts3DFaceDto:()=>HH,faceTextVarEnum:()=>Uz,faceTypeEnum:()=>Gz,fontVariantsEnum:()=>Vz,fontsEnum:()=>kz,fontsModel:()=>LH,recAlignmentEnum:()=>zz});var F={};i.r(F),i.d(F,{PyramidSimpeByIndexDto:()=>jH,PyramidSimpleAffectorsDto:()=>YH,PyramidSimpleCellPart:()=>sX,PyramidSimpleData:()=>QH,PyramidSimpleDto:()=>XH,PyramidSimpleFacePart:()=>rX,PyramidSimpleModelCellDto:()=>ZH,PyramidSimpleModelCellsDto:()=>$H,PyramidSimpleModelCellsIndexDto:()=>qH,PyramidSimpleModelDto:()=>KH,PyramidSimpleModelFaceCellIndexDto:()=>eX,PyramidSimpleModelFaceCellsUIndexDto:()=>tX,PyramidSimpleModelFaceCellsVIndexDto:()=>iX,PyramidSimpleModelFaceIndexDto:()=>JH});var L={};i.r(L),i.d(L,{PyramidSimple:()=>F});var B={};i.r(B),i.d(B,{FacePatterns:()=>L});var k={};i.r(k),i.d(k,{outputShapeEnum:()=>nX});var V={};i.r(V),i.d(V,{Enums:()=>k,Patterns:()=>B,Text3D:()=>N});var U={};i.r(U),i.d(U,{Asset:()=>rU,BabylonCamera:()=>nU,BabylonGaussianSplatting:()=>lU,BabylonIO:()=>oU,BabylonMaterial:()=>aU,BabylonMesh:()=>hU,BabylonMeshBuilder:()=>dU,BabylonNode:()=>SU,BabylonPick:()=>cU,BabylonRay:()=>uU,BabylonScene:()=>PU,BabylonTexture:()=>_U,BabylonWebXR:()=>pU,Base:()=>AU,Color:()=>fU,Draw:()=>mU,JSCAD:()=>gU,JSON:()=>vU,Line:()=>xU,Lists:()=>bU,Logic:()=>TU,Math:()=>yU,OCCT:()=>Jk,Point:()=>CU,Polyline:()=>EU,Tag:()=>IU,Text:()=>RU,Time:()=>MU,Transforms:()=>OU,Vector:()=>DU,Verb:()=>wU});const G={};function z(e,t){G[e]=t}function W(e){return G[e]}function H(e){for(const t in G)if(e instanceof G[t]&&!t.includes("Abstract"))return t;return"Unknown"}class X{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,s){for(const r in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,r)&&this._BabylonFileParsers[r](e,t,i,s)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach((t=>e=e.concat(t.bones))),e}}X._BabylonFileParsers={},X._IndividualBabylonFileParsers={},z("BABYLON.AbstractScene",X);class Y{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(const e in Y.Triggers)if(Object.prototype.hasOwnProperty.call(Y.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in Y.Triggers)if(Object.prototype.hasOwnProperty.call(Y.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in Y.Triggers)if(Object.prototype.hasOwnProperty.call(Y.Triggers,t)&&parseInt(t)===e)return!0;return!1}}Y.Triggers={};class Q{constructor(e,t=!1,i,s){this.initialize(e,t,i,s)}initialize(e,t=!1,i,s){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=s,this}}class j{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class K{static FromPromise(e,t){const i=new K;return e.then((e=>{i.notifyObservers(e)})).catch((e=>{if(!t)throw e;t.notifyObservers(e)})),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new Q(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,r=!1){if(!e)return null;const n=new j(e,t,s);return n.unregisterOnNextCall=r,i?this._observers.unshift(n):this._observers.push(n),this._onObserverAdded&&this._onObserverAdded(n),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(n,this._lastNotifiedValue),n._remove=()=>{this.remove(n)},n}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return!!e&&(e._remove=null,-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))}removeCallback(e,t){for(let i=0;i{this._remove(e)}),0))}_remove(e,t=!0){if(!e)return!1;const i=this._observers.indexOf(e);return-1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,s,r){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const n=this._eventState;n.mask=t,n.target=i,n.currentTarget=s,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=r;for(const i of this._observers)if(!i._willBeUnregistered&&(i.mask&t&&(i.unregisterOnNextCall&&this._deferUnregister(i),i.scope?n.lastReturnValue=i.callback.apply(i.scope,[e,n]):n.lastReturnValue=i.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const s=this._eventState;s.mask=i,s.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,s)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new K;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}const $=1/2.2,q=2.2,Z=(1+Math.sqrt(5))/2,J=.001;class ee{static BuildArray(e,t){const i=[];for(let s=0;sfunction(e,t,i){const s=e[t];if("function"!=typeof s)return null;const r=function(){const s=e.length,n=r.previous.apply(e,arguments);return i(t,s),n};return s.next=r,r.previous=s,e[t]=r,()=>{const i=r.previous;if(!i)return;const s=r.next;s?(i.next=s,s.previous=i):(i.next=void 0,e[t]=i),r.next=void 0,r.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{e?.()}))}}class se{static SetMatrixPrecision(e){if(se.MatrixTrackPrecisionChange=!1,e&&!se.MatrixUse64Bits&&se.MatrixTrackedMatrices)for(let e=0;eparseInt(e.toString().replace(/\W/g,""));class de{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=ue(this.x);return e=397*e^ue(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return de.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new de(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new de(this.x+e.x,this.y+e.y)}subtract(e){return new de(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new de(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new de(this.x*e,this.y*t)}divide(e){return new de(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new de(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.x=this.x-e,i.y=this.y-t,i}negate(){return new de(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new de(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=J){return e&&ne(this.x,e.x,t)&&ne(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new de(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new de(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotateToRef(e,t){const i=Math.cos(e),s=Math.sin(e),r=i*this.x-s*this.y,n=s*this.x+i*this.y;return t.x=r,t.y=n,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new de;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new de(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new de(0,0)}static One(){return new de(1,1)}static Random(e=0,t=1){return new de(oe(e,t),oe(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(oe(e,t),oe(e,t))}static get ZeroReadOnly(){return de._ZeroReadOnly}static FromArray(e,t=0){return new de(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,a=.5*(2*t.x+(-e.x+i.x)*r+(2*e.x-5*t.x+4*i.x-s.x)*n+(-e.x+3*t.x-3*i.x+s.x)*o),l=.5*(2*t.y+(-e.y+i.y)*r+(2*e.y-5*t.y+4*i.y-s.y)*n+(-e.y+3*t.y-3*i.y+s.y)*o);return new de(a,l)}static ClampToRef(e,t,i,s){return s.x=le(e.x,t.x,i.x),s.y=le(e.y,t.y,i.y),s}static Clamp(e,t,i){const s=le(e.x,t.x,i.x),r=le(e.y,t.y,i.y);return new de(s,r)}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.x*a+i.x*l+t.x*h+s.x*c,d=e.y*a+i.y*l+t.y*h+s.y*c;return new de(u,d)}static Hermite1stDerivative(e,t,i,s,r){return this.Hermite1stDerivativeToRef(e,t,i,s,r,new de)}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n.x=6*(o-r)*e.x+(3*o-4*r+1)*t.x+6*(-o+r)*i.x+(3*o-2*r)*s.x,n.y=6*(o-r)*e.y+(3*o-4*r+1)*t.y+6*(-o+r)*i.y+(3*o-2*r)*s.y,n}static Lerp(e,t,i){const s=e.x+(t.x-e.x)*i,r=e.y+(t.y-e.y)*i;return new de(s,r)}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return de.NormalizeToRef(e,new de)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.xt.x?e.x:t.x,s=e.y>t.y?e.y:t.y;return new de(i,s)}static Transform(e,t){return de.TransformToRef(e,t,new de)}static TransformToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+s[12],n=e.x*s[1]+e.y*s[5]+s[13];return i.x=r,i.y=n,i}static PointInTriangle(e,t,i,s){const r=.5*(-i.y*s.x+t.y*(-i.x+s.x)+t.x*(i.y-s.y)+i.x*s.y),n=r<0?-1:1,o=(t.y*s.x-t.x*s.y+(s.y-t.y)*e.x+(t.x-s.x)*e.y)*n,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*n;return o>0&&a>0&&o+a<2*r*n}static Distance(e,t){return Math.sqrt(de.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y;return i*i+s*s}static Center(e,t){return de.CenterToRef(e,t,new de)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const s=de.DistanceSquared(t,i);if(0===s)return de.Distance(e,t);const r=i.subtract(t),n=Math.max(0,Math.min(1,de.Dot(e.subtract(t),r)/s)),o=t.add(r.multiplyByFloats(n,n));return de.Distance(e,o)}}de._ZeroReadOnly=de.Zero(),Object.defineProperties(de.prototype,{dimension:{value:[2]},rank:{value:1}});class _e{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=ue(this._x);return e=397*e^ue(this._y),e=397*e^ue(this._z),e}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return _e.FromArrayToRef(e,t,this),this}toQuaternion(){return fe.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new _e(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new _e(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new _e(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new _e(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new _e(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const s=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const r=t*Math.sin(i)*Math.cos(s),n=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(s);return e.set(r,n,o),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,r=this._z,n=e._x,o=e._y,a=e._z,l=e._w,h=2*(o*r-a*s),c=2*(a*i-n*r),u=2*(n*s-o*i);return t._x=i+l*h+o*u-a*c,t._y=s+l*c+a*h-n*u,t._z=r+l*u+n*c-o*h,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new _e)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new _e)}projectOnPlaneToRef(e,t,i){const s=e.normal,r=e.d,n=ge.Vector3[0];this.subtractToRef(t,n),n.normalize();const o=_e.Dot(n,s);if(Math.abs(o)<1e-10)i.setAll(1/0);else{const e=-(_e.Dot(t,s)+r)/o,a=n.scaleInPlace(e);t.addToRef(a,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=J){return e&&ne(this._x,e._x,t)&&ne(this._y,e._y,t)&&ne(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new _e(this._x*e,this._y*t,this._z*i)}divide(e){return new _e(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!ne(t,i,e))return!0;const s=Math.abs(this._z);return!ne(t,s,e)||!ne(i,s,e)}get isNonUniform(){const e=Math.abs(this._x);return e!==Math.abs(this._y)||e!==Math.abs(this._z)}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new _e(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))}fractToRef(e){return e._x=this.x-Math.floor(this._x),e._y=this.y-Math.floor(this._y),e._z=this.z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new _e(this.x-Math.floor(this._x),this.y-Math.floor(this._y),this.z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z==0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if("xyz"===(e=e.toLowerCase()))return this;const t=ge.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(ge.Matrix[0]),_e.TransformCoordinatesToRef(this,ge.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,ge.Vector3[0]),ge.Vector3[0].rotateByQuaternionToRef(e,ge.Vector3[0]),t.addToRef(ge.Vector3[0],i),i}cross(e){return _e.CrossToRef(this,e,new _e)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new _e)}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new _e(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,s){const r=_e.Dot(e,i);return(r-s)/(r-_e.Dot(t,i))}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(ge.Vector3[1]),r=t.normalizeToRef(ge.Vector3[2]);let n=_e.Dot(s,r);n=le(n,-1,1);const o=Math.acos(n),a=ge.Vector3[3];return _e.CrossToRef(s,r,a),_e.Dot(a,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){ge.Vector3[0].copyFrom(e);const s=ge.Vector3[0];ge.Vector3[1].copyFrom(t);const r=ge.Vector3[1];ge.Vector3[2].copyFrom(i);const n=ge.Vector3[2],o=ge.Vector3[3],a=ge.Vector3[4];return s.normalize(),r.normalize(),n.normalize(),_e.CrossToRef(n,s,o),_e.CrossToRef(o,n,a),he(Math.atan2(_e.Dot(r,o),_e.Dot(r,a)))}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=ve.Vector3[0];return t.subtractToRef(e,s),i._y=Math.atan2(s.x,s.z)||0,i._x=Math.atan2(Math.sqrt(s.x**2+s.z**2),s.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=_e.Zero();return _e.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=le(i,0,1);const r=ge.Vector3[0],n=ge.Vector3[1];r.copyFrom(e);const o=r.length();r.normalizeFromLength(o),n.copyFrom(t);const a=n.length();n.normalizeFromLength(a);const l=_e.Dot(r,n);let h,c;if(l<1-J){const e=Math.acos(l),t=1/Math.sin(e);h=Math.sin((1-i)*e)*t,c=Math.sin(i*e)*t}else h=1-i,c=i;return r.scaleInPlace(h),n.scaleInPlace(c),s.copyFrom(r).addInPlace(n),s.scaleInPlace(ae(o,a,i)),s}static SmoothToRef(e,t,i,s,r){return _e.SlerpToRef(e,t,0===s?1:i/s,r),r}static FromArray(e,t=0){return new _e(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return _e.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return _e.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new _e(0,0,0)}static One(){return new _e(1,1,1)}static Up(){return new _e(0,1,0)}static get UpReadOnly(){return _e._UpReadOnly}static get DownReadOnly(){return _e._DownReadOnly}static get RightReadOnly(){return _e._RightReadOnly}static get LeftReadOnly(){return _e._LeftReadOnly}static get LeftHandedForwardReadOnly(){return _e._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return _e._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return _e._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return _e._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return _e._ZeroReadOnly}static get OneReadOnly(){return _e._OneReadOnly}static Down(){return new _e(0,-1,0)}static Forward(e=!1){return new _e(0,0,e?-1:1)}static Backward(e=!1){return new _e(0,0,e?1:-1)}static Right(){return new _e(1,0,0)}static Left(){return new _e(-1,0,0)}static Random(e=0,t=1){return new _e(oe(e,t),oe(e,t),oe(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(oe(e,t),oe(e,t),oe(e,t))}static TransformCoordinates(e,t){const i=_e.Zero();return _e.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return _e.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=1/(e*n[3]+t*n[7]+i*n[11]+n[15]);return r._x=o*h,r._y=a*h,r._z=l*h,r._isDirty=!0,r}static TransformNormal(e,t){const i=_e.Zero();return _e.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,s,r){const n=s.m;return r._x=e*n[0]+t*n[4]+i*n[8],r._y=e*n[1]+t*n[5]+i*n[9],r._z=e*n[2]+t*n[6]+i*n[10],r._isDirty=!0,r}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,a=.5*(2*t._x+(-e._x+i._x)*r+(2*e._x-5*t._x+4*i._x-s._x)*n+(-e._x+3*t._x-3*i._x+s._x)*o),l=.5*(2*t._y+(-e._y+i._y)*r+(2*e._y-5*t._y+4*i._y-s._y)*n+(-e._y+3*t._y-3*i._y+s._y)*o),h=.5*(2*t._z+(-e._z+i._z)*r+(2*e._z-5*t._z+4*i._z-s._z)*n+(-e._z+3*t._z-3*i._z+s._z)*o);return new _e(a,l,h)}static Clamp(e,t,i){const s=new _e;return _e.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let r=e._x;r=r>i._x?i._x:r,r=ri._y?i._y:n,n=ni._z?i._z:o,o=o0&&E<0?(P.copyFrom(n),I=t,R=i):E>0&&A<0?(P.copyFrom(a),I=i,R=s):(P.copyFrom(o).scaleInPlace(-1),I=s,R=t);const M=ge.Vector3[9],O=ge.Vector3[4];if(I.subtractToRef(g,T),R.subtractToRef(g,M),_e.CrossToRef(T,M,O),!(_e.Dot(O,l)<0))return r.copyFrom(g),Math.abs(p*f);const D=ge.Vector3[5];_e.CrossToRef(P,O,D),D.normalize();const w=ge.Vector3[9];w.copyFrom(I).subtractInPlace(g);const N=w.length();if(Nthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,s){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(s,this.w),this}maximizeInPlaceFromFloats(e,t,i,s){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(s,this.w),this}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e}floor(){return new pe(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e.z=this.z-Math.floor(this.z),e.w=this.w-Math.floor(this.w),e}fract(){return new pe(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new pe)}normalizeToRef(e){const t=this.length();return 0===t||1===t?(e.x=this.x,e.y=this.y,e.z=this.z,e.w=this.w,e):this.scaleToRef(1/t,e)}toVector3(){return new _e(this.x,this.y,this.z)}clone(){return new pe(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}static FromArray(e,t){return t||(t=0),new pe(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return pe.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,s,r){return r.x=e,r.y=t,r.z=i,r.w=s,r}static Zero(){return new pe(0,0,0,0)}static One(){return new pe(1,1,1,1)}static Random(e=0,t=1){return new pe(oe(e,t),oe(e,t),oe(e,t),oe(e,t))}static RandomToRef(e=0,t=1,i){return i.x=oe(e,t),i.y=oe(e,t),i.z=oe(e,t),i.w=oe(e,t),i}static Clamp(e,t,i){return pe.ClampToRef(e,t,i,new pe)}static ClampToRef(e,t,i,s){return s.x=le(e.x,t.x,i.x),s.y=le(e.y,t.y,i.y),s.z=le(e.z,t.z,i.z),s.w=le(e.w,t.w,i.w),s}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return pe._ZeroReadOnly}static Normalize(e){return pe.NormalizeToRef(e,new pe)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new pe;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new pe;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(pe.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return pe.CenterToRef(e,t,new pe)}static CenterToRef(e,t,i){return i.x=(e.x+t.x)/2,i.y=(e.y+t.y)/2,i.z=(e.z+t.z)/2,i.w=(e.w+t.w)/2,i}static TransformCoordinates(e,t){return pe.TransformCoordinatesToRef(e,t,new pe)}static TransformCoordinatesToRef(e,t,i){return pe.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=e*n[3]+t*n[7]+i*n[11]+n[15];return r.x=o,r.y=a,r.z=l,r.w=h,r}static TransformNormal(e,t){return pe.TransformNormalToRef(e,t,new pe)}static TransformNormalToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+e.z*s[8],n=e.x*s[1]+e.y*s[5]+e.z*s[9],o=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=r,i.y=n,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,r,n){const o=r.m;return n.x=e*o[0]+t*o[4]+i*o[8],n.y=e*o[1]+t*o[5]+i*o[9],n.z=e*o[2]+t*o[6]+i*o[10],n.w=s,n}static FromVector3(e,t=0){return new pe(e._x,e._y,e._z,t)}static Dot(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w}}pe._ZeroReadOnly=pe.Zero(),Object.defineProperties(pe.prototype,{dimension:{value:[4]},rank:{value:1}});class fe{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,s=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=ue(this._x);return e=397*e^ue(this._y),e=397*e^ue(this._z),e=397*e^ue(this._w),e}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return fe.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=J){return e&&ne(this._x,e._x,t)&&ne(this._y,e._y,t)&&ne(this._z,e._z,t)&&ne(this._w,e._w,t)}clone(){return new fe(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._isDirty=!0,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new fe(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,s){return this._x+=e,this._y+=t,this._z+=i,this._w+=s,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,s){return this.subtractFromFloatsToRef(e,t,i,s,new fe)}subtractFromFloatsToRef(e,t,i,s,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._w=this._w-s,r._isDirty=!0,r}subtract(e){return new fe(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new fe(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){const t=new fe(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,s=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,n=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,s,r,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,s){return this._x*=e,this._y*=t,this._z*=i,this._w*=s,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new fe)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,s){return this._x===e&&this._y===t&&this._z===i&&this._w===s}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new fe(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return 0==e||1==e||this.scaleInPlace(1/e),this}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new fe(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=_e.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,s=this._y,r=this._w,n=s*t-i*r,o=.4999999;if(n<-o)e._y=2*Math.atan2(s,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>o)e._y=2*Math.atan2(s,r),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const o=r*r,a=t*t,l=i*i,h=s*s;e._z=Math.atan2(2*(i*s+t*r),-a-l+h+o),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*i+s*r),a-l-h+o),e._isDirty=!0}return e}toRotationMatrix(e){return me.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return fe.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}static FromRotationMatrix(e){const t=new fe;return fe.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[1],a=i[5],l=i[9],h=i[2],c=i[6],u=i[10],d=s+a+u;let _;return d>0?(_=.5/Math.sqrt(d+1),t._w=.25/_,t._x=(c-l)*_,t._y=(n-h)*_,t._z=(o-r)*_,t._isDirty=!0):s>a&&s>u?(_=2*Math.sqrt(1+s-a-u),t._w=(c-l)/_,t._x=.25*_,t._y=(r+o)/_,t._z=(n+h)/_,t._isDirty=!0):a>u?(_=2*Math.sqrt(1+a-s-u),t._w=(n-h)/_,t._x=(r+o)/_,t._y=.25*_,t._z=(l+c)/_,t._isDirty=!0):(_=2*Math.sqrt(1+u-s-a),t._w=(o-r)/_,t._x=(n+h)/_,t._y=(l+c)/_,t._z=.25*_,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const s=fe.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,r){let n=0===s?1:i/s;return n=le(n,0,1),fe.SlerpToRef(e,t,n,r),r}static Zero(){return new fe(0,0,0,0)}static Inverse(e){return new fe(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new fe(0,0,0,1)}static IsIdentity(e){return e&&0===e._x&&0===e._y&&0===e._z&&1===e._w}static RotationAxis(e,t){return fe.RotationAxisToRef(e,t,new fe)}static RotationAxisToRef(e,t,i){const s=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*s,i._y=e._y*s,i._z=e._z*s,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new fe(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,s,r){return r.copyFromFloats(e,t,i,s),r}static FromEulerAngles(e,t,i){const s=new fe;return fe.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return fe.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new fe;return fe.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return fe.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=J){const r=_e.Dot(e,t)+1;return rMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(_e.CrossToRef(e,t,ve.Vector3[0]),i.set(ve.Vector3[0].x,ve.Vector3[0].y,ve.Vector3[0].z,r)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new fe;return fe.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const r=.5*i,n=.5*t,o=.5*e,a=Math.sin(r),l=Math.cos(r),h=Math.sin(n),c=Math.cos(n),u=Math.sin(o),d=Math.cos(o);return s._x=d*h*l+u*c*a,s._y=u*c*l-d*h*a,s._z=d*c*a-u*h*l,s._w=d*c*l+u*h*a,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new fe;return fe.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const r=.5*(i+e),n=.5*(i-e),o=.5*t;return s._x=Math.cos(n)*Math.sin(o),s._y=Math.sin(n)*Math.sin(o),s._z=Math.sin(r)*Math.cos(o),s._w=Math.cos(r)*Math.cos(o),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new fe(0,0,0,0);return fe.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const r=ge.Matrix[0];return me.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),r),fe.FromRotationMatrixToRef(r,s),s}static FromLookDirectionLH(e,t){const i=new fe;return fe.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=ge.Matrix[0];return me.LookDirectionLHToRef(e,t,s),fe.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new fe;return fe.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=ge.Matrix[0];return me.LookDirectionRHToRef(e,t,s),fe.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=fe.Identity();return fe.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let r,n,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,a=!1;if(o<0&&(a=!0,o=-o),o>.999999)n=1-i,r=a?-i:i;else{const e=Math.acos(o),t=1/Math.sin(e);n=Math.sin((1-i)*e)*t,r=a?-Math.sin(i*e)*t:Math.sin(i*e)*t}return s._x=n*e._x+r*t._x,s._y=n*e._y+r*t._y,s._z=n*e._z+r*t._z,s._w=n*e._w+r*t._w,s._isDirty=!0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e._x*a+i._x*l+t._x*h+s._x*c,d=e._y*a+i._y*l+t._y*h+s._y*c,_=e._z*a+i._z*l+t._z*h+s._z*c,p=e._w*a+i._w*l+t._w*h+s._w*c;return new fe(u,d,_,p)}static Hermite1stDerivative(e,t,i,s,r){const n=new fe;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n._x=6*(o-r)*e._x+(3*o-4*r+1)*t._x+6*(-o+r)*i._x+(3*o-2*r)*s._x,n._y=6*(o-r)*e._y+(3*o-4*r+1)*t._y+6*(-o+r)*i._y+(3*o-2*r)*s._y,n._z=6*(o-r)*e._z+(3*o-4*r+1)*t._z+6*(-o+r)*i._z+(3*o-2*r)*s._z,n._w=6*(o-r)*e._w+(3*o-4*r+1)*t._w+6*(-o+r)*i._w+(3*o-2*r)*s._w,n._isDirty=!0,n}static Normalize(e){const t=fe.Zero();return fe.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const s=new fe;return fe.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(le(e.x,t.x,i.x),le(e.y,t.y,i.y),le(e.z,t.z,i.z),le(e.w,t.w,i.w))}static Random(e=0,t=1){return new fe(oe(e,t),oe(e,t),oe(e,t),oe(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(oe(e,t),oe(e,t),oe(e,t),oe(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(fe.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return fe.CenterToRef(e,t,fe.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}Object.defineProperties(fe.prototype,{dimension:{value:[4]},rank:{value:1}});class me{static get Use64Bits(){return se.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=me._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,s=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&s}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,se.MatrixTrackPrecisionChange&&se.MatrixTrackedMatrices.push(this),this._m=new se.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]||0!==this._m[1]||0!==this._m[2]||0!==this._m[3]||0!==this._m[4]||0!==this._m[6]||0!==this._m[7]||0!==this._m[8]||0!==this._m[9]||0!==this._m[10]||0!==this._m[11]||0!==this._m[12]||0!==this._m[13]||0!==this._m[14]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;const e=this._m,t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],o=e[5],a=e[6],l=e[7],h=e[8],c=e[9],u=e[10],d=e[11],_=e[12],p=e[13],f=e[14],m=e[15],g=u*m-f*d,v=c*m-p*d,x=c*f-p*u,b=h*m-_*d,T=h*f-u*_,y=h*p-_*c;return t*+(o*g-a*v+l*x)+i*-(n*g-a*b+l*T)+s*+(n*v-o*b+l*y)+r*-(n*x-o*T+a*y)}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}\n${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}\n${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}\n${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let s=0;s<16;s++)e[t+s]=i[s];return this}asArray(){return this._m}fromArray(e,t=0){return me.FromArrayToRef(e,t,this)}copyFromFloats(...e){return me.FromArrayToRef(e,0,this)}set(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){const t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return me.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){const t=new me;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,s=t._m,r=e.m;for(let e=0;e<16;e++)s[e]=i[e]+r[e];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]-s[e];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new me)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let e=0;e<16;e++)s[e]=i[e]-r[e];return t.markAsUpdated(),t}invertToRef(e){if(!0===this._isIdentity)return me.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],r=t[2],n=t[3],o=t[4],a=t[5],l=t[6],h=t[7],c=t[8],u=t[9],d=t[10],_=t[11],p=t[12],f=t[13],m=t[14],g=t[15],v=d*g-m*_,x=u*g-f*_,b=u*m-f*d,T=c*g-p*_,y=c*m-d*p,S=c*f-p*u,C=+(a*v-l*x+h*b),E=-(o*v-l*T+h*y),A=+(o*x-a*T+h*S),P=-(o*b-a*y+l*S),I=i*C+s*E+r*A+n*P;if(0===I)return e.copyFrom(this),e;const R=1/I,M=l*g-m*h,O=a*g-f*h,D=a*m-f*l,w=o*g-p*h,N=o*m-p*l,F=o*f-p*a,L=l*_-d*h,B=a*_-u*h,k=a*d-u*l,V=o*_-c*h,U=o*d-c*l,G=o*u-c*a,z=-(s*v-r*x+n*b),W=+(i*v-r*T+n*y),H=-(i*x-s*T+n*S),X=+(i*b-s*y+r*S),Y=+(s*M-r*O+n*D),Q=-(i*M-r*w+n*N),j=+(i*O-s*w+n*F),K=-(i*D-s*N+r*F),$=-(s*L-r*B+n*k),q=+(i*L-r*V+n*U),Z=-(i*B-s*V+n*G),J=+(i*k-s*U+r*G);return me.FromValuesToRef(C*R,z*R,Y*R,$*R,E*R,W*R,Q*R,q*R,A*R,H*R,j*R,Z*R,P*R,X*R,K*R,J*R,e),e}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new _e(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){const e=this.m;return me.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]),this}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){const i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiply(e){const t=new me;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]*=i[e];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let e=0;e<16;e++)s[e]=i[e]*r[e];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const s=this._m,r=e.m,n=s[0],o=s[1],a=s[2],l=s[3],h=s[4],c=s[5],u=s[6],d=s[7],_=s[8],p=s[9],f=s[10],m=s[11],g=s[12],v=s[13],x=s[14],b=s[15],T=r[0],y=r[1],S=r[2],C=r[3],E=r[4],A=r[5],P=r[6],I=r[7],R=r[8],M=r[9],O=r[10],D=r[11],w=r[12],N=r[13],F=r[14],L=r[15];return t[i]=n*T+o*E+a*R+l*w,t[i+1]=n*y+o*A+a*M+l*N,t[i+2]=n*S+o*P+a*O+l*F,t[i+3]=n*C+o*I+a*D+l*L,t[i+4]=h*T+c*E+u*R+d*w,t[i+5]=h*y+c*A+u*M+d*N,t[i+6]=h*S+c*P+u*O+d*F,t[i+7]=h*C+c*I+u*D+d*L,t[i+8]=_*T+p*E+f*R+m*w,t[i+9]=_*y+p*A+f*M+m*N,t[i+10]=_*S+p*P+f*O+m*F,t[i+11]=_*C+p*I+f*D+m*L,t[i+12]=g*T+v*E+x*R+b*w,t[i+13]=g*y+v*A+x*M+b*N,t[i+14]=g*S+v*P+x*O+b*F,t[i+15]=g*C+v*I+x*D+b*L,this}divide(e){return this.divideToRef(e,new me)}divideToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]/s[e];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]/=i[e];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new me)}negateInPlace(){const e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=-t[e];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,s=t.m;return i[0]===s[0]&&i[1]===s[1]&&i[2]===s[2]&&i[3]===s[3]&&i[4]===s[4]&&i[5]===s[5]&&i[6]===s[6]&&i[7]===s[7]&&i[8]===s[8]&&i[9]===s[9]&&i[10]===s[10]&&i[11]===s[11]&&i[12]===s[12]&&i[13]===s[13]&&i[14]===s[14]&&i[15]===s[15]}equalsWithEpsilon(e,t=0){const i=this._m,s=e.m;for(let e=0;e<16;e++)if(!ne(i[e],s[e],t))return!1;return!0}equalsToFloats(...e){const t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new me)}floorToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=Math.floor(t[e]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new me)}fractToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=t[e]-Math.floor(t[e]);return e.markAsUpdated(),e}clone(){const e=new me;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=ue(this._m[0]);for(let t=1;t<16;t++)e=397*e^ue(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new fe,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,s,r=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const n=this._m;if(i&&i.copyFromFloats(n[12],n[13],n[14]),(e=e||ge.Vector3[0]).x=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),e.y=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),e.z=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]),s){const t=(r?s.absoluteScaling.x:s.scaling.x)<0?-1:1,i=(r?s.absoluteScaling.y:s.scaling.y)<0?-1:1,n=(r?s.absoluteScaling.z:s.scaling.z)<0?-1:1;e.x*=t,e.y*=i,e.z*=n}else this.determinant()<=0&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const i=1/e._x,s=1/e._y,r=1/e._z;me.FromValuesToRef(n[0]*i,n[1]*i,n[2]*i,0,n[4]*s,n[5]*s,n[6]*s,0,n[8]*r,n[9]*r,n[10]*r,0,0,0,0,1,ge.Matrix[0]),fe.FromRotationMatrixToRef(ge.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new pe(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){const i=4*e;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){const e=new me;return me.TransposeToRef(this,e),e}transposeToRef(e){return me.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,s,r){if(e<0||e>3)return this;const n=4*e;return this._m[n+0]=t,this._m[n+1]=i,this._m[n+2]=s,this._m[n+3]=r,this.markAsUpdated(),this}scale(e){const t=new me;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){const t=ge.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return me.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){const e=new me;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=ge.Vector3[0];if(!this.decompose(t))return me.IdentityToRef(e),e;const i=this._m,s=1/t._x,r=1/t._y,n=1/t._z;return me.FromValuesToRef(i[0]*s,i[1]*s,i[2]*s,0,i[4]*r,i[5]*r,i[6]*r,0,i[8]*n,i[9]*n,i[10]*n,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){const i=new me;return me.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let s=0;s<16;s++)i._m[s]=e[s+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,s){for(let r=0;r<16;r++)s._m[r]=e[r+t]*i;return s.markAsUpdated(),s}static get IdentityReadOnly(){return me._IdentityReadOnly}static FromValuesToRef(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m){const g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=s,g[4]=r,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=p,g[15]=f,m.markAsUpdated()}static FromValues(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f){const m=new me,g=m._m;return g[0]=e,g[1]=t,g[2]=i,g[3]=s,g[4]=r,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=p,g[15]=f,m.markAsUpdated(),m}static Compose(e,t,i){const s=new me;return me.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const r=s._m,n=t._x,o=t._y,a=t._z,l=t._w,h=n+n,c=o+o,u=a+a,d=n*h,_=n*c,p=n*u,f=o*c,m=o*u,g=a*u,v=l*h,x=l*c,b=l*u,T=e._x,y=e._y,S=e._z;return r[0]=(1-(f+g))*T,r[1]=(_+b)*T,r[2]=(p-x)*T,r[3]=0,r[4]=(_-b)*y,r[5]=(1-(d+g))*y,r[6]=(m+v)*y,r[7]=0,r[8]=(p+x)*S,r[9]=(m-v)*S,r[10]=(1-(d+f))*S,r[11]=0,r[12]=i._x,r[13]=i._y,r[14]=i._z,r[15]=1,s.markAsUpdated(),s}static Identity(){const e=me.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return me.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){const e=me.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){const t=new me;return me.RotationXToRef(e,t),t}static Invert(e){const t=new me;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return me.FromValuesToRef(1,0,0,0,0,s,i,0,0,-i,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationY(e){const t=new me;return me.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return me.FromValuesToRef(s,0,-i,0,0,1,0,0,i,0,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationZ(e){const t=new me;return me.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return me.FromValuesToRef(s,i,0,0,-i,s,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationAxis(e,t){const i=new me;return me.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),r=Math.cos(-t),n=1-r;e.normalize();const o=i._m;return o[0]=e._x*e._x*n+r,o[1]=e._x*e._y*n-e._z*s,o[2]=e._x*e._z*n+e._y*s,o[3]=0,o[4]=e._y*e._x*n+e._z*s,o[5]=e._y*e._y*n+r,o[6]=e._y*e._z*n-e._x*s,o[7]=0,o[8]=e._z*e._x*n-e._y*s,o[9]=e._z*e._y*n+e._x*s,o[10]=e._z*e._z*n+r,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const r=_e.Dot(t,e),n=i._m;if(r<-1+J)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=s?1:-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=s?-1:1,n[11]=0;else{const i=_e.Cross(t,e),s=1/(1+r);n[0]=i._x*i._x*s+r,n[1]=i._y*i._x*s-i._z,n[2]=i._z*i._x*s+i._y,n[3]=0,n[4]=i._x*i._y*s+i._z,n[5]=i._y*i._y*s+r,n[6]=i._z*i._y*s-i._x,n[7]=0,n[8]=i._x*i._z*s-i._y,n[9]=i._y*i._z*s+i._x,n[10]=i._z*i._z*s+r,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const s=new me;return me.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return fe.RotationYawPitchRollToRef(e,t,i,ge.Quaternion[0]),ge.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new me;return me.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return me.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,s),s._updateIdentityStatus(1===e&&1===t&&1===i),s}static Translation(e,t,i){const s=new me;return me.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return me.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,s),s._updateIdentityStatus(0===e&&0===t&&0===i),s}static Lerp(e,t,i){const s=new me;return me.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const r=s._m,n=e.m,o=t.m;for(let e=0;e<16;e++)r[e]=n[e]*(1-i)+o[e]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new me;return me.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const r=ge.Vector3[0],n=ge.Quaternion[0],o=ge.Vector3[1];e.decompose(r,n,o);const a=ge.Vector3[2],l=ge.Quaternion[1],h=ge.Vector3[3];t.decompose(a,l,h);const c=ge.Vector3[4];_e.LerpToRef(r,a,i,c);const u=ge.Quaternion[2];fe.SlerpToRef(n,l,i,u);const d=ge.Vector3[5];return _e.LerpToRef(o,h,i,d),me.ComposeToRef(c,u,d,s),s}static LookAtLH(e,t,i){const s=new me;return me.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const r=ge.Vector3[0],n=ge.Vector3[1],o=ge.Vector3[2];t.subtractToRef(e,o),o.normalize(),_e.CrossToRef(i,o,r);const a=r.lengthSquared();0===a?r.x=1:r.normalizeFromLength(Math.sqrt(a)),_e.CrossToRef(o,r,n),n.normalize();const l=-_e.Dot(r,e),h=-_e.Dot(n,e),c=-_e.Dot(o,e);return me.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,l,h,c,1,s),s}static LookAtRH(e,t,i){const s=new me;return me.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const r=ge.Vector3[0],n=ge.Vector3[1],o=ge.Vector3[2];e.subtractToRef(t,o),o.normalize(),_e.CrossToRef(i,o,r);const a=r.lengthSquared();0===a?r.x=1:r.normalizeFromLength(Math.sqrt(a)),_e.CrossToRef(o,r,n),n.normalize();const l=-_e.Dot(r,e),h=-_e.Dot(n,e),c=-_e.Dot(o,e);return me.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,l,h,c,1,s),s}static LookDirectionLH(e,t){const i=new me;return me.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=ge.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const r=ge.Vector3[1];return _e.CrossToRef(t,s,r),me.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new me;return me.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=ge.Vector3[2];return _e.CrossToRef(t,e,s),me.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,s,r){const n=new me;return me.OrthoLHToRef(e,t,i,s,n,r),n}static OrthoLHToRef(e,t,i,s,r,n){const o=2/e,a=2/t,l=2/(s-i),h=-(s+i)/(s-i);return me.FromValuesToRef(o,0,0,0,0,a,0,0,0,0,l,0,0,0,h,1,r),n&&r.multiplyToRef(xe,r),r._updateIdentityStatus(1===o&&1===a&&1===l&&0===h),r}static OrthoOffCenterLH(e,t,i,s,r,n,o){const a=new me;return me.OrthoOffCenterLHToRef(e,t,i,s,r,n,a,o),a}static OrthoOffCenterLHToRef(e,t,i,s,r,n,o,a){const l=2/(t-e),h=2/(s-i),c=2/(n-r),u=-(n+r)/(n-r),d=(e+t)/(e-t),_=(s+i)/(i-s);return me.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,0,d,_,u,1,o),a&&o.multiplyToRef(xe,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,s,r,n,o,a,l,h,c){const u=-o*Math.cos(a),d=-o*Math.sin(a);return me.TranslationToRef(0,0,-l,ge.Matrix[1]),me.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,ge.Matrix[0]),ge.Matrix[1].multiplyToRef(ge.Matrix[0],ge.Matrix[0]),me.TranslationToRef(0,0,l,ge.Matrix[1]),ge.Matrix[0].multiplyToRef(ge.Matrix[1],ge.Matrix[0]),me.OrthoOffCenterLHToRef(e,t,i,s,r,n,h,c),ge.Matrix[0].multiplyToRef(h,h),h}static OrthoOffCenterRH(e,t,i,s,r,n,o){const a=new me;return me.OrthoOffCenterRHToRef(e,t,i,s,r,n,a,o),a}static OrthoOffCenterRHToRef(e,t,i,s,r,n,o,a){return me.OrthoOffCenterLHToRef(e,t,i,s,r,n,o,a),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,s,r,n,o,a,l,h,c){const u=o*Math.cos(a),d=o*Math.sin(a);return me.TranslationToRef(0,0,l,ge.Matrix[1]),me.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,ge.Matrix[0]),ge.Matrix[1].multiplyToRef(ge.Matrix[0],ge.Matrix[0]),me.TranslationToRef(0,0,-l,ge.Matrix[1]),ge.Matrix[0].multiplyToRef(ge.Matrix[1],ge.Matrix[0]),me.OrthoOffCenterRHToRef(e,t,i,s,r,n,h,c),ge.Matrix[0].multiplyToRef(h,h),h}static PerspectiveLH(e,t,i,s,r,n=0){const o=new me,a=2*i/e,l=2*i/t,h=(s+i)/(s-i),c=-2*s*i/(s-i),u=Math.tan(n);return me.FromValuesToRef(a,0,0,0,0,l,0,u,0,0,h,1,0,0,c,0,o),r&&o.multiplyToRef(xe,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,s,r,n=0,o=!1){const a=new me;return me.PerspectiveFovLHToRef(e,t,i,s,a,!0,r,n,o),a}static PerspectiveFovLHToRef(e,t,i,s,r,n=!0,o,a=0,l=!1){const h=i,c=s,u=1/Math.tan(.5*e),d=n?u/t:u,_=n?u:u*t,p=l&&0===h?-1:0!==c?(c+h)/(c-h):1,f=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,m=Math.tan(a);return me.FromValuesToRef(d,0,0,0,0,_,0,m,0,0,p,1,0,0,f,0,r),o&&r.multiplyToRef(xe,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,s,r,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return me.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,1,0,0,1,0,r),o&&r.multiplyToRef(xe,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,s,r,n=0,o=!1){const a=new me;return me.PerspectiveFovRHToRef(e,t,i,s,a,!0,r,n,o),a}static PerspectiveFovRHToRef(e,t,i,s,r,n=!0,o,a=0,l=!1){const h=i,c=s,u=1/Math.tan(.5*e),d=n?u/t:u,_=n?u:u*t,p=l&&0===h?1:0!==c?-(c+h)/(c-h):-1,f=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,m=Math.tan(a);return me.FromValuesToRef(d,0,0,0,0,_,0,m,0,0,p,-1,0,0,f,0,r),o&&r.multiplyToRef(xe,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,s,r,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return me.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,-1,0,0,-1,0,r),o&&r.multiplyToRef(xe,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,i,s,r,n){const o=e.width,a=e.height,l=e.x,h=e.y,c=me.FromValues(o/2,0,0,0,0,-a/2,0,0,0,0,n-r,0,l+o/2,a/2+h,r,1),u=new me;return t.multiplyToRef(i,u),u.multiplyToRef(s,u),u.multiplyToRef(c,u)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return se.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){const t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return se.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new me;return me.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[12],a=i[1],l=i[5],h=i[9],c=i[13],u=i[2],d=i[6],_=i[10],p=i[14],f=i[3],m=i[7],g=i[11],v=i[15],x=t._m;return x[0]=s,x[1]=r,x[2]=n,x[3]=o,x[4]=a,x[5]=l,x[6]=h,x[7]=c,x[8]=u,x[9]=d,x[10]=_,x[11]=p,x[12]=f,x[13]=m,x[14]=g,x[15]=v,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new me;return me.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,s=e.normal.y,r=e.normal.z,n=-2*i,o=-2*s,a=-2*r;return me.FromValuesToRef(n*i+1,o*i,a*i,0,n*s,o*s+1,a*s,0,n*r,o*r,a*r+1,0,n*e.d,o*e.d,a*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return me.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,s),s}static FromQuaternionToRef(e,t){const i=e._x*e._x,s=e._y*e._y,r=e._z*e._z,n=e._x*e._y,o=e._z*e._w,a=e._z*e._x,l=e._y*e._w,h=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(s+r),t._m[1]=2*(n+o),t._m[2]=2*(a-l),t._m[3]=0,t._m[4]=2*(n-o),t._m[5]=1-2*(r+i),t._m[6]=2*(h+c),t._m[7]=0,t._m[8]=2*(a+l),t._m[9]=2*(h-c),t._m[10]=1-2*(s+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}me._UpdateFlagSeed=0,me._IdentityReadOnly=me.Identity(),Object.defineProperties(me.prototype,{dimension:{value:[4,4]},rank:{value:2}});class ge{}ge.Vector3=ee.BuildTuple(11,_e.Zero),ge.Matrix=ee.BuildTuple(2,me.Identity),ge.Quaternion=ee.BuildTuple(3,fe.Zero);class ve{}ve.Vector2=ee.BuildTuple(3,de.Zero),ve.Vector3=ee.BuildTuple(13,_e.Zero),ve.Vector4=ee.BuildTuple(3,pe.Zero),ve.Quaternion=ee.BuildTuple(2,fe.Zero),ve.Matrix=ee.BuildTuple(8,me.Identity),z("BABYLON.Vector2",de),z("BABYLON.Vector3",_e),z("BABYLON.Vector4",pe),z("BABYLON.Matrix",me);const xe=me.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class be{static Sign(e){return 0==(e=+e)||isNaN(e)?e:e>0?1:-1}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(0===e)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e*=2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=be.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=be.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=be.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return s=Math.abs(t-e)<=i?t:e+be.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=be.DeltaAngle(e,t);let r=0;return-i180&&(s-=360),e+s*le(i)}static InverseLerp(e,t,i){let s=0;return s=e!=t?le((i-e)/(t-e)):0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n;return e*(2*o-3*n+1)+i*(-2*o+3*n)+t*(o-2*n+r)+s*(o-n)}static Hermite1stDerivative(e,t,i,s,r){const n=r*r;return 6*(n-r)*e+(3*n-4*r+1)*t+6*(-n+r)*i+(3*n-2*r)*s}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static HCF(e,t){const i=e%t;return 0===i?t:be.HCF(t,i)}}function Te(e){return Math.pow(e,q)}function ye(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function Se(e){return Math.pow(e,$)}function Ce(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}be.TwoPi=2*Math.PI,be.WithinEpsilon=ne,be.ToHex=ce,be.Clamp=le,be.Lerp=ae,be.RandomRange=oe,be.NormalizeRadians=he;class Ee{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return Ee.FromArrayToRef(e,t,this),this}toColor4(e=1){return new Ae(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return.3*this.r+.59*this.g+.11*this.b}multiply(e){return new Ee(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,i){return new Ee(this.r*e,this.g*t,this.b*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=J){return be.WithinEpsilon(this.r,e.r,t)&&be.WithinEpsilon(this.g,e.g,t)&&be.WithinEpsilon(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new Ee(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,i){return i.r=le(this.r,e,t),i.g=le(this.g,e,t),i.b=le(this.b,e,t),i}add(e){return new Ee(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new Ee(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,i){return new Ee(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,s){return s.r=this.r-e,s.g=this.g-t,s.b=this.b-i,s}clone(){return new Ee(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){const e=Math.round(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+ce(e)+ce(t)+ce(i)}toHSV(){return this.toHSVToRef(new Ee)}toHSVToRef(e){const t=this.r,i=this.g,s=this.b,r=Math.max(t,i,s),n=Math.min(t,i,s);let o=0,a=0;const l=r,h=r-n;return 0!==r&&(a=h/r),r!=n&&(r==t?(o=(i-s)/h,i=0&&n<=1?(a=r,l=o):n>=1&&n<=2?(a=o,l=r):n>=2&&n<=3?(l=r,h=o):n>=3&&n<=4?(l=o,h=r):n>=4&&n<=5?(a=o,h=r):n>=5&&n<=6&&(a=r,h=o);const c=i-r;return s.r=a+c,s.g=l+c,s.b=h+c,s}static FromHSV(e,t,i){const s=new Ee(0,0,0);return Ee.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new Ee(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16);return Ee.FromInts(t,i,s)}static FromArray(e,t=0){return new Ee(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new Ee(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new Ee(0,0,0);return Ee.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.r*a+i.r*l+t.r*h+s.r*c,d=e.g*a+i.g*l+t.g*h+s.g*c,_=e.b*a+i.b*l+t.b*h+s.b*c;return new Ee(u,d,_)}static Hermite1stDerivative(e,t,i,s,r){const n=Ee.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=6*(o-r)*e.r+(3*o-4*r+1)*t.r+6*(-o+r)*i.r+(3*o-2*r)*s.r,n.g=6*(o-r)*e.g+(3*o-4*r+1)*t.g+6*(-o+r)*i.g+(3*o-2*r)*s.g,n.b=6*(o-r)*e.b+(3*o-4*r+1)*t.b+6*(-o+r)*i.b+(3*o-2*r)*s.b}static Red(){return new Ee(1,0,0)}static Green(){return new Ee(0,1,0)}static Blue(){return new Ee(0,0,1)}static Black(){return new Ee(0,0,0)}static get BlackReadOnly(){return Ee._BlackReadOnly}static White(){return new Ee(1,1,1)}static Purple(){return new Ee(.5,0,.5)}static Magenta(){return new Ee(1,0,1)}static Yellow(){return new Ee(1,1,0)}static Gray(){return new Ee(.5,.5,.5)}static Teal(){return new Ee(0,1,1)}static Random(){return new Ee(Math.random(),Math.random(),Math.random())}}Ee._BlackReadOnly=Ee.Black(),Object.defineProperties(Ee.prototype,{dimension:{value:[3]},rank:{value:1}});class Ae{constructor(e=0,t=0,i=0,s=1){this.r=e,this.g=t,this.b=i,this.a=s}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new Ae(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,s){return this.r+=e,this.g+=t,this.b+=i,this.a+=s,this}subtract(e){return new Ae(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,s){return new Ae(this.r-e,this.g-t,this.b-i,this.a-s)}subtractFromFloatsToRef(e,t,i,s,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r.a=this.a-s,r}scale(e){return new Ae(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,i){return i.r=le(this.r,e,t),i.g=le(this.g,e,t),i.b=le(this.b,e,t),i.a=le(this.a,e,t),i}multiply(e){return new Ae(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,s){return new Ae(this.r*e,this.g*t,this.b*i,this.a*s)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,s){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(s,this.a),this}maximizeInPlaceFromFloats(e,t,i,s){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(s,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=J){return be.WithinEpsilon(this.r,e.r,t)&&be.WithinEpsilon(this.g,e.g,t)&&be.WithinEpsilon(this.b,e.b,t)&&be.WithinEpsilon(this.a,e.a,t)}equalsToFloats(e,t,i,s){return this.r===e&&this.g===t&&this.b===i&&this.a===s}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e=397*e^255*this.a,e}clone(){return(new Ae).copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,s){return this.r=e,this.g=t,this.b=i,this.a=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+ce(t)+ce(i)+ce(s);const r=Math.round(255*this.a);return"#"+ce(t)+ce(i)+ce(s)+ce(r)}toLinearSpace(e=!1){const t=new Ae;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=ye(this.r),e.g=ye(this.g),e.b=ye(this.b)):(e.r=Te(this.r),e.g=Te(this.g),e.b=Te(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new Ae;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=Ce(this.r),e.g=Ce(this.g),e.b=Ce(this.b)):(e.r=Se(this.r),e.g=Se(this.g),e.b=Se(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new Ae(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16),r=9===e.length?parseInt(e.substring(7,9),16):255;return Ae.FromInts(t,i,s,r)}static Lerp(e,t,i){return Ae.LerpToRef(e,t,i,new Ae)}static LerpToRef(e,t,i,s){return s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i,s.a=e.a+(t.a-e.a)*i,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.r*a+i.r*l+t.r*h+s.r*c,d=e.g*a+i.g*l+t.g*h+s.g*c,_=e.b*a+i.b*l+t.b*h+s.b*c,p=e.a*a+i.a*l+t.a*h+s.a*c;return new Ae(u,d,_,p)}static Hermite1stDerivative(e,t,i,s,r){const n=new Ae;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=6*(o-r)*e.r+(3*o-4*r+1)*t.r+6*(-o+r)*i.r+(3*o-2*r)*s.r,n.g=6*(o-r)*e.g+(3*o-4*r+1)*t.g+6*(-o+r)*i.g+(3*o-2*r)*s.g,n.b=6*(o-r)*e.b+(3*o-4*r+1)*t.b+6*(-o+r)*i.b+(3*o-2*r)*s.b,n.a=6*(o-r)*e.a+(3*o-4*r+1)*t.a+6*(-o+r)*i.a+(3*o-2*r)*s.a}static FromColor3(e,t=1){return new Ae(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new Ae(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,s){return new Ae(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;inew Ae(0,0,0,0))),z("BABYLON.Color3",Ee),z("BABYLON.Color4",Ae);class Ie{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new K,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}_prepare(){}getTriggerParameter(){return this._triggerParameter}setTriggerParameter(e){this._triggerParameter=e}_evaluateConditionForCurrentFrame(){const e=this._condition;if(!e)return!0;const t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){this._evaluateConditionForCurrentFrame()&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())}execute(e){}skipToNextActiveAction(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this}then(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(e){return null}_serialize(e,t){const i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){const e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}}Ie._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof de?e.x+", "+e.y:e instanceof _e?e.x+", "+e.y+", "+e.z:e instanceof Ee?e.r+", "+e.g+", "+e.b:e instanceof Ae?e.r+", "+e.g+", "+e.b+", "+e.a:e,Ie._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),z("BABYLON.Action",Ie);class Re{constructor(e,t,i,s,r,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=s,this.sourceEvent=r,this.additionalData=n}static CreateNew(e,t,i){const s=e.getScene();return new Re(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new Re(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new Re(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new Re(e,t.x,t.y,null,i,s)}}class Me{constructor(e){this._actionManager=e}isValid(){return!0}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(){}_serialize(e){return{type:2,children:[],name:e.name,properties:e.properties}}}class Oe extends Me{static get IsEqual(){return Oe._IsEqual}static get IsDifferent(){return Oe._IsDifferent}static get IsGreater(){return Oe._IsGreater}static get IsLesser(){return Oe._IsLesser}constructor(e,t,i,s,r=Oe.IsEqual){super(e),this.propertyPath=i,this.value=s,this.operator=r,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case Oe.IsGreater:return this._effectiveTarget[this._property]>this.value;case Oe.IsLesser:return this._effectiveTarget[this._property]e<10?"0"+e:""+e,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){const s=Array.isArray(t)?t[0]:t;if(void 0!==i&&!Ne._CheckLimit(s,i))return;const r=Ne._FormatMessage(s),n=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];n.logFunc&&n.logFunc("BJS - "+r,...o);const a=`
${r}

`;Ne._AddLogEntry(a),Ne._GenerateLimitMessage(s,e)}static get LogCache(){return Ne._LogCache}static ClearLogCache(){Ne._LogCache="",Ne._LogLimitOutputs={},Ne.errorsCount=0}static set LogLevels(e){Ne.Log=Ne._LogDisabled,Ne.Warn=Ne._LogDisabled,Ne.Error=Ne._LogDisabled,[Ne.MessageLogLevel,Ne.WarningLogLevel,Ne.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];Ne[e.name]=Ne._LogEnabled.bind(Ne,t)}}))}}Ne.NoneLogLevel=0,Ne.MessageLogLevel=1,Ne.WarningLogLevel=2,Ne.ErrorLogLevel=4,Ne.AllLogLevel=7,Ne.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",Ne._LogCache="",Ne._LogLimitOutputs={},Ne._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],Ne.errorsCount=0,Ne.Log=Ne._LogEnabled.bind(Ne,Ne.MessageLogLevel),Ne.Warn=Ne._LogEnabled.bind(Ne,Ne.WarningLogLevel),Ne.Error=Ne._LogEnabled.bind(Ne,Ne.ErrorLogLevel);class Fe extends Ie{constructor(e,t,i,s){super(e,s),this.propertyPath=i,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]}serialize(e){return super._serialize({name:"SwitchBooleanAction",properties:[Ie._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}class Le extends Ie{constructor(e,t,i,s){super(e,s),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[Ie._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}class Be extends Ie{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"SetValueAction",properties:[Ie._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Ie._SerializeValueAsString(this.value)}]},e)}}class ke extends Ie{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&Ne.Warn("Warning: IncrementValueAction can only be used with number values")}execute(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"IncrementValueAction",properties:[Ie._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Ie._SerializeValueAsString(this.value)}]},e)}}class Ve extends Ie{constructor(e,t,i,s,r,n){super(e,n),this.from=i,this.to=s,this.loop=r,this._target=t}_prepare(){}execute(){this._actionManager.getScene().beginAnimation(this._target,this.from,this.to,this.loop)}serialize(e){return super._serialize({name:"PlayAnimationAction",properties:[Ie._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:Ie._SerializeValueAsString(this.loop)||!1}]},e)}}class Ue extends Ie{constructor(e,t,i){super(e,i),this._target=t}_prepare(){}execute(){this._actionManager.getScene().stopAnimation(this._target)}serialize(e){return super._serialize({name:"StopAnimationAction",properties:[Ie._GetTargetProperty(this._target)]},e)}}class Ge extends Ie{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class ze extends Ie{constructor(e,t,i,s=!0){super(e,i),this.children=t,this.enableChildrenConditions=s}_prepare(){for(let e=0;ee?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?{...e}:null:e.clone(t):null;class Ye{static DeepCopy(e,t,i,s,r=!1){const n=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const o of n){if("_"===o[0]&&(!s||-1===s.indexOf(o)))continue;if(o.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(o))continue;const n=e[o],a=typeof n;if("function"!==a)try{if("object"===a)if(n instanceof Uint8Array)t[o]=Uint8Array.from(n);else if(n instanceof Array){if(t[o]=[],n.length>0)if("object"==typeof n[0])for(let e=0;e-1&&this._scene.actionManagers.splice(e,1);const t=this._scene.meshes.filter((e=>e.actionManager===this));for(const e of t)e.actionManager=null}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=Qe.OnPickTrigger&&t.trigger<=Qe.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=Qe.OnPickTrigger&&t.trigger<=Qe.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===Qe.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(Ne.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,Qe.Triggers[e.trigger]?Qe.Triggers[e.trigger]++:Qe.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){const t=this.actions.indexOf(e);return-1!==t&&(this.actions.splice(t,1),Qe.Triggers[e.trigger]-=1,0===Qe.Triggers[e.trigger]&&delete Qe.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i{if(null===s){const e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}const r=s.split("."),n=t.split(",");for(let e=0;e{if(e.detached)return;const h=[];let c=null,u=null;const d=e.combine&&e.combine.length>0;if(2===e.type?h.push(s):h.push(t),d){const t=[];for(let i=0;i{const i=W("BABYLON."+e);return i&&new i(...t)})(e.name,h);if(_ instanceof Me&&null!==o){const e=new Ge(t,o);a?a.then(e):s.registerAction(e),a=e}null===l?_ instanceof Me?(o=_,_=a):(o=null,a?a.then(_):s.registerAction(_)):l.push(_);for(let i=0;i0){const e=r.properties[0].value,t=null===r.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),s={trigger:Qe[r.name],parameter:t}}else s=Qe[r.name];for(let e=0;e=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o}Object.create,Object.create;const Je={},et={};function tt(e){const t=e.getClassName();if(Je[t])return Je[t];Je[t]={};const i=Je[t];let s=e,r=t;for(;r;){const e=et[r];for(const t in e)i[t]=e[t];let t,n=!1;do{if(t=Object.getPrototypeOf(s),!t.getClassName){n=!0;break}if(t.getClassName()!==r)break;s=t}while(t);if(n)break;r=t.getClassName(),s=t}return i}function it(e,t){return(i,s)=>{const r=function(e){const t=e.getClassName();return et[t]||(et[t]={}),et[t]}(i);r[s]||(r[s]={type:e,sourceName:t})}}function st(e,t=null){return function(e,t=null){return(i,s)=>{const r=t||"_"+s;Object.defineProperty(i,s,{get:function(){return this[r]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[r]!==t&&(this[r]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function rt(e){return it(0,e)}function nt(e){return it(1,e)}function ot(e){return it(2,e)}function at(e){return it(3,e)}function lt(e){return it(4,e)}function ht(e){return it(5,e)}function ct(e){return it(6,e)}function ut(e){return it(7,e)}function dt(e){return it(8,e)}function _t(e){return it(9,e)}function pt(e){return it(10,e)}function ft(e){return it(12,e)}function mt(e){return it(11,e)}function gt(e,t,i,s){const r=i.value;i.value=(...i)=>{let n=r;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];n=s?(...t)=>s(...t)?e(...t):r(...t):e}return e[t]=n,n(...i)}}gt.filter=function(e){return(t,i,s)=>gt(t,i,s,e)};const vt={};function xt(e,t=!1){if(!t||!vt[e])return vt[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}class bt{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),bt._HandleParenthesisContent(e,t)))):bt._HandleParenthesisContent(e,t))||"false"!==e&&bt.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const s=e.split("||");for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){let r=bt._SimplifyNegation(s[e].trim());const n=r.split("&&");if(n.length>1)for(let e=0;e(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}class Tt{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>Tt.HasTags(e),e.addTags=t=>Tt.AddTagsTo(e,t),e.removeTags=t=>Tt.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>Tt.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;const t=e._tags;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const t=[];for(const i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}return e._tags}static AddTagsTo(e,t){t&&"string"==typeof t&&t.split(" ").forEach((function(t){Tt._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(Tt.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!Tt.HasTags(e))return;const i=t.split(" ");for(const t in i)Tt._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?Tt.HasTags(e):bt.Eval(t,(t=>Tt.HasTags(e)&&e._tags[t])))}}const yt=function(e,t,i,s={}){const r=e();Tt&&Tt.HasTags(t)&&Tt.AddTagsTo(r,Tt.GetTags(t,!0));const n=tt(r),o={};for(const e in n){const a=n[e],l=t[e],h=a.type;if(null!=l&&("uniqueId"!==e||St.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:r[e]=l;break;case 1:s.cloneTexturesOnlyOnce&&o[l.uniqueId]?r[e]=o[l.uniqueId]:(r[e]=i||l.isRenderTarget?l:l.clone(),o[l.uniqueId]=r[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:r[e]=i?l:l.clone()}}return r};class St{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw xt("ImageProcessingConfiguration")},St._FresnelParametersParser=e=>{throw xt("FresnelParameters")},St._ColorCurvesParser=e=>{throw xt("ColorCurves")},St._TextureParser=(e,t,i)=>{throw xt("Texture")};class Ct{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new K,this._onClonedObservable=new K}}class Et{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,s){const r=this._NodeConstructors[e];return r?r(t,i,s):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;const t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){const t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){-1===this._nodeDataStorage._sceneRootNodesIndex&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(-1!==this._nodeDataStorage._sceneRootNodesIndex){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null,i=!0){this._isDirty=!1,this._nodeDataStorage=new Ct,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new K,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=me.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new K,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||re.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),i&&this._addToSceneRootNodes()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return-1!==this._behaviors.indexOf(e)||(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce((()=>{e.attach(this)})):e.attach(this),this._behaviors.push(e)),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),this}get behaviors(){return this._behaviors}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={}}updateCache(e){!e&&this.isSynchronized()||this._updateCache()}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return!this._parentNode||!this._parentNode._isDirty&&this._parentUpdateId===this._parentNode._childUpdateId&&this._parentNode.isSynchronized()}isSynchronized(){return!(this._parentNode&&!this.isSynchronizedWithParent())&&this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return!1===e?this._nodeDataStorage._isEnabled:!!this._nodeDataStorage._isEnabled&&this._nodeDataStorage._isParentEnabled}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),this._children&&this._children.forEach((e=>{e._syncParentEnabledState()}))}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return!!this.parent&&(this.parent===e||this.parent.isDescendantOf(e))}_getDescendants(e,t=!1,i){if(this._children)for(let s=0;s(!t||t(e))&&void 0!==e.cullingStrategy)),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)}getAnimationByName(e){for(let t=0;tnew Et(e,this.getScene())),this);if(t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i{throw xt("AnimationRange")},Et._NodeConstructors={},Ze([rt()],Et.prototype,"name",void 0),Ze([rt()],Et.prototype,"id",void 0),Ze([rt()],Et.prototype,"uniqueId",void 0),Ze([rt()],Et.prototype,"state",void 0),Ze([rt()],Et.prototype,"metadata",void 0);class At{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=0|this.width;return e=397*e^this.height,e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new At(this.width*e,this.height*t)}clone(){return new At(this.width,this.height)}equals(e){return!!e&&this.width===e.width&&this.height===e.height}get surface(){return this.width*this.height}static Zero(){return new At(0,0)}add(e){return new At(this.width+e.width,this.height+e.height)}subtract(e){return new At(this.width-e.width,this.height-e.height)}scale(e){return new At(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,r=e.height+(t.height-e.height)*i;return new At(s,r)}}class Pt{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(Pt.CustomRequestHeaders).length>0||Pt.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in Pt.CustomRequestHeaders){const t=Pt.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return Pt.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){Pt.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const e of Pt.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}t=(t=t.replace("file:http:","http:")).replace("file:https:","https:"),this._requestURL=t,this._xhr.open(e,t,!0)}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}Pt.CustomRequestHeaders={},Pt.CustomRequestModifiers=new Array,Pt.SkipRequestModificationForBabylonCDN=!0;const It=Object.freeze(new fe(0,0,0,0)),Rt=Object.freeze(_e.Zero()),Mt=Object.freeze(de.Zero()),Ot=Object.freeze(At.Zero()),Dt=Object.freeze(Ee.Black()),wt=Object.freeze(new Ae(0,0,0,0)),Nt={key:0,repeatCount:0,loopMode:2};class Ft{static _PrepareAnimation(e,t,i,s,r,n,o,a){let l;if(!isNaN(parseFloat(r))&&isFinite(r)?l=Ft.ANIMATIONTYPE_FLOAT:r instanceof fe?l=Ft.ANIMATIONTYPE_QUATERNION:r instanceof _e?l=Ft.ANIMATIONTYPE_VECTOR3:r instanceof de?l=Ft.ANIMATIONTYPE_VECTOR2:r instanceof Ee?l=Ft.ANIMATIONTYPE_COLOR3:r instanceof Ae?l=Ft.ANIMATIONTYPE_COLOR4:r instanceof At&&(l=Ft.ANIMATIONTYPE_SIZE),null==l)return null;const h=new Ft(e,t,i,l,o),c=[{frame:0,value:r},{frame:s,value:n}];return h.setKeys(c),void 0!==a&&h.setEasingFunction(a),h}static CreateAnimation(e,t,i,s){const r=new Ft(e+"Animation",e,i,t,Ft.ANIMATIONLOOPMODE_CONSTANT);return r.setEasingFunction(s),r}static CreateAndStartAnimation(e,t,i,s,r,n,o,a,l,h,c){const u=Ft._PrepareAnimation(e,i,s,r,n,o,a,l);return u?(t.getScene&&(c=t.getScene()),c?c.beginDirectAnimation(t,[u],0,r,1===u.loopMode,1,h):null):null}static CreateAndStartHierarchyAnimation(e,t,i,s,r,n,o,a,l,h,c){const u=Ft._PrepareAnimation(e,s,r,n,o,a,l,h);return u?t.getScene().beginDirectHierarchyAnimation(t,i,[u],0,n,1===u.loopMode,1,c):null}static CreateMergeAndStartAnimation(e,t,i,s,r,n,o,a,l,h){const c=Ft._PrepareAnimation(e,i,s,r,n,o,a,l);return c?(t.animations.push(c),t.getScene().beginAnimation(t,0,r,1===c.loopMode,1,h)):null}static MakeAnimationAdditive(e,t,i,s=!1,r){let n;n="object"==typeof t?t:{referenceFrame:t??0,range:i,cloneOriginalAnimation:s,clonedAnimationName:r};let o=e;if(n.cloneOriginalAnimation&&(o=e.clone(),o.name=n.clonedAnimationName||o.name),!o._keys.length)return o;const a=n.referenceFrame&&n.referenceFrame>=0?n.referenceFrame:0;let l=0;const h=o._keys[0];let c=o._keys.length-1;const u=o._keys[c],d={referenceValue:h.value,referencePosition:ve.Vector3[0],referenceQuaternion:ve.Quaternion[0],referenceScaling:ve.Vector3[1],keyPosition:ve.Vector3[2],keyQuaternion:ve.Quaternion[1],keyScaling:ve.Vector3[3]};let _=h.frame,p=u.frame;if(n.range){const e=o.getRange(n.range);e&&(_=e.from,p=e.to)}else _=n.fromFrame??_,p=n.toFrame??p;if(_!==h.frame&&(l=o.createKeyForFrame(_)),p!==u.frame&&(c=o.createKeyForFrame(p)),1===o._keys.length){const e=o._getKeyValue(o._keys[0]);d.referenceValue=e.clone?e.clone():e}else if(a<=h.frame){const e=o._getKeyValue(h.value);d.referenceValue=e.clone?e.clone():e}else if(a>=u.frame){const e=o._getKeyValue(u.value);d.referenceValue=e.clone?e.clone():e}else{Nt.key=0;const e=o._interpolate(a,Nt);d.referenceValue=e.clone?e.clone():e}o.dataType===Ft.ANIMATIONTYPE_QUATERNION?d.referenceValue.normalize().conjugateInPlace():o.dataType===Ft.ANIMATIONTYPE_MATRIX&&(d.referenceValue.decompose(d.referenceScaling,d.referenceQuaternion,d.referencePosition),d.referenceQuaternion.normalize().conjugateInPlace());let f=Number.MAX_VALUE;const m=n.clipKeys?[]:null;for(let e=l;e<=c;e++){let t=o._keys[e];if((m||n.cloneOriginalAnimation)&&(t={frame:t.frame,value:t.value.clone?t.value.clone():t.value,inTangent:t.inTangent,outTangent:t.outTangent,interpolation:t.interpolation,lockedTangent:t.lockedTangent},m&&(f===Number.MAX_VALUE&&(f=t.frame),t.frame-=f,m.push(t))),!e||o.dataType===Ft.ANIMATIONTYPE_FLOAT||t.value!==h.value)switch(o.dataType){case Ft.ANIMATIONTYPE_MATRIX:t.value.decompose(d.keyScaling,d.keyQuaternion,d.keyPosition),d.keyPosition.subtractInPlace(d.referencePosition),d.keyScaling.divideInPlace(d.referenceScaling),d.referenceQuaternion.multiplyToRef(d.keyQuaternion,d.keyQuaternion),me.ComposeToRef(d.keyScaling,d.keyQuaternion,d.keyPosition,t.value);break;case Ft.ANIMATIONTYPE_QUATERNION:d.referenceValue.multiplyToRef(t.value,t.value);break;case Ft.ANIMATIONTYPE_VECTOR2:case Ft.ANIMATIONTYPE_VECTOR3:case Ft.ANIMATIONTYPE_COLOR3:case Ft.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(d.referenceValue,t.value);break;case Ft.ANIMATIONTYPE_SIZE:t.value.width-=d.referenceValue.width,t.value.height-=d.referenceValue.height;break;default:t.value-=d.referenceValue}}return m&&o.setKeys(m,!0),o}static TransitionTo(e,t,i,s,r,n,o,a=null){if(o<=0)return i[e]=t,a&&a(),null;const l=r*(o/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);const h=s.beginAnimation(i,0,l,!1);return h.onAnimationEnd=a,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,s,r,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=s,this.loopMode=r,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=s,this.loopMode=void 0===r?Ft.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=Ft._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort(((e,t)=>e.frame-t.frame))}removeEvents(e){for(let t=0;t=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const s=this._keys,r=s.length;let n=t.key;for(;n>=0&&e=s[n+1].frame;)++n;if(t.key=n,n<0)return i?void 0:this._getKeyValue(s[0].value);if(n+1>r-1)return i?void 0:this._getKeyValue(s[r-1].value);const o=s[n],a=s[n+1];if(i&&(e===o.frame||e===a.frame))return;const l=this._getKeyValue(o.value),h=this._getKeyValue(a.value);if(o.interpolation===$e.STEP)return a.frame>e?l:h;const c=void 0!==o.outTangent&&void 0!==a.inTangent,u=a.frame-o.frame;let d=(e-o.frame)/u;const _=o.easingFunction||this.getEasingFunction();switch(null!==_&&(d=_.ease(d)),this.dataType){case Ft.ANIMATIONTYPE_FLOAT:{const e=c?this.floatInterpolateFunctionWithTangents(l,o.outTangent*u,h,a.inTangent*u,d):this.floatInterpolateFunction(l,h,d);switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return e;case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+e}break}case Ft.ANIMATIONTYPE_QUATERNION:{const e=c?this.quaternionInterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.quaternionInterpolateFunction(l,h,d);switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return e;case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||It).scale(t.repeatCount))}return e}case Ft.ANIMATIONTYPE_VECTOR3:{const e=c?this.vector3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.vector3InterpolateFunction(l,h,d);switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return e;case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Rt).scale(t.repeatCount))}break}case Ft.ANIMATIONTYPE_VECTOR2:{const e=c?this.vector2InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.vector2InterpolateFunction(l,h,d);switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return e;case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Mt).scale(t.repeatCount))}break}case Ft.ANIMATIONTYPE_SIZE:switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,h,d);case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(l,h,d).add((t.offsetValue||Ot).scale(t.repeatCount))}break;case Ft.ANIMATIONTYPE_COLOR3:{const e=c?this.color3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.color3InterpolateFunction(l,h,d);switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return e;case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Dt).scale(t.repeatCount))}break}case Ft.ANIMATIONTYPE_COLOR4:{const e=c?this.color4InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.color4InterpolateFunction(l,h,d);switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return e;case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||wt).scale(t.repeatCount))}break}case Ft.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case Ft.ANIMATIONLOOPMODE_CYCLE:case Ft.ANIMATIONLOOPMODE_CONSTANT:case Ft.ANIMATIONLOOPMODE_YOYO:return Ft.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,h,d,t.workValue):l;case Ft.ANIMATIONLOOPMODE_RELATIVE:case Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return l}}return 0}matrixInterpolateFunction(e,t,i,s){return Ft.AllowMatrixDecomposeForInterpolation?s?(me.DecomposeLerpToRef(e,t,i,s),s):me.DecomposeLerp(e,t,i):s?(me.LerpToRef(e,t,i,s),s):me.Lerp(e,t,i)}clone(){const e=new Ft(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(const t in this._ranges){const i=this._ranges[t];i&&(e._ranges[t]=i.clone())}}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){Nt.key=0;const t=this._interpolate(e,Nt,!0);if(!t)return this._keys[Nt.key].frame===e?Nt.key:Nt.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(Nt.key+1,0,i),Nt.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let s=0;s=2&&(o=t.values[1]),t.values.length>=3&&(a=t.values[2]),t.values.length>=4&&(l=t.values[3]);break;case Ft.ANIMATIONTYPE_QUATERNION:if(r=fe.FromArray(t.values),t.values.length>=8){const e=fe.FromArray(t.values.slice(4,8));e.equals(fe.Zero())||(o=e)}if(t.values.length>=12){const e=fe.FromArray(t.values.slice(8,12));e.equals(fe.Zero())||(a=e)}t.values.length>=13&&(l=t.values[12]);break;case Ft.ANIMATIONTYPE_MATRIX:r=me.FromArray(t.values),t.values.length>=17&&(l=t.values[16]);break;case Ft.ANIMATIONTYPE_COLOR3:r=Ee.FromArray(t.values),t.values[3]&&(o=Ee.FromArray(t.values[3])),t.values[4]&&(a=Ee.FromArray(t.values[4])),t.values[5]&&(l=t.values[5]);break;case Ft.ANIMATIONTYPE_COLOR4:r=Ae.FromArray(t.values),t.values[4]&&(o=Ae.FromArray(t.values[4])),t.values[5]&&(a=Ae.FromArray(t.values[5])),t.values[6]&&(l=Ae.FromArray(t.values[6]));break;case Ft.ANIMATIONTYPE_VECTOR3:default:r=_e.FromArray(t.values),t.values[3]&&(o=_e.FromArray(t.values[3])),t.values[4]&&(a=_e.FromArray(t.values[4])),t.values[5]&&(l=t.values[5])}const h={};h.frame=t.frame,h.value=r,null!=o&&(h.inTangent=o),null!=a&&(h.outTangent=a),null!=l&&(h.interpolation=l),s.push(h)}if(t.setKeys(s),e.ranges)for(n=0;n{const r=new Pt;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){let t=JSON.parse(r.responseText);if(t.animations&&(t=t.animations),t.length){const e=[];for(const i of t)e.push(this.Parse(i));i(e)}else{const s=this.Parse(t);e&&(s.name=e),i(s)}}else s("Unable to load the animation")})),r.open("GET",t),r.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const s=new Pt;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){const i=JSON.parse(JSON.parse(s.responseText).jsonPayload);if(i.animations){const s=JSON.parse(i.animations),r=[];for(const t of s.animations){const i=this.Parse(t);i.snippetId=e,r.push(i)}t(r)}else{const s=JSON.parse(i.animation),r=this.Parse(s);r.snippetId=e,t(r)}}else i("Unable to load the snippet "+e)})),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()}))}}Ft._UniqueIdGenerator=0,Ft.AllowMatricesInterpolation=!1,Ft.AllowMatrixDecomposeForInterpolation=!0,Ft.SnippetUrl="https://snippet.babylonjs.com",Ft.ANIMATIONTYPE_FLOAT=0,Ft.ANIMATIONTYPE_VECTOR3=1,Ft.ANIMATIONTYPE_QUATERNION=2,Ft.ANIMATIONTYPE_MATRIX=3,Ft.ANIMATIONTYPE_COLOR3=4,Ft.ANIMATIONTYPE_COLOR4=7,Ft.ANIMATIONTYPE_VECTOR2=5,Ft.ANIMATIONTYPE_SIZE=6,Ft.ANIMATIONLOOPMODE_RELATIVE=0,Ft.ANIMATIONLOOPMODE_CYCLE=1,Ft.ANIMATIONLOOPMODE_CONSTANT=2,Ft.ANIMATIONLOOPMODE_YOYO=4,Ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,Ft.CreateFromSnippetAsync=Ft.ParseFromSnippetAsync,z("BABYLON.Animation",Ft),Et._AnimationRangeFactory=(e,t,i)=>new qe(e,t,i);class Lt extends Ie{constructor(e,t,i,s,r=1e3,n,o,a){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new K,this.propertyPath=i,this.value=s,this.duration=r,this.stopOtherAnimations=o,this.onInterpolationDone=a,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){const e=this._actionManager.getScene(),t=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];let i;if("number"==typeof this.value)i=Ft.ANIMATIONTYPE_FLOAT;else if(this.value instanceof Ee)i=Ft.ANIMATIONTYPE_COLOR3;else if(this.value instanceof _e)i=Ft.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof me)i=Ft.ANIMATIONTYPE_MATRIX;else{if(!(this.value instanceof fe))return void Ne.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");i=Ft.ANIMATIONTYPE_QUATERNION}const s=new Ft("InterpolateValueAction",this._property,1e3/this.duration*100,i,Ft.ANIMATIONLOOPMODE_CONSTANT);s.setKeys(t),this.stopOtherAnimations&&e.stopAnimation(this._effectiveTarget),e.beginDirectAnimation(this._effectiveTarget,[s],0,100,!1,1,(()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()}))}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[Ie._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Ie._SerializeValueAsString(this.value)},{name:"duration",value:Ie._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:Ie._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}z("BABYLON.InterpolateValueAction",Lt);class Bt{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,i,s){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._yoyoDirection=1,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=s,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===Ft.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=me.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,0!==this._minFrame){const e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(const t of this._target)this._preparePath(t,e),this._getOriginalValues(e),e++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const r=t.getEvents();r&&r.length>0&&r.forEach((e=>{this._events.push(e._clone())})),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){const i=this._animation.targetPropertyPath;if(i.length>1){let s=e;for(let e=0;e-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray)for(let i=0;ii[i.length-1].frame&&(e=i[i.length-1].frame);const s=this._events;if(s.length)for(let t=0;tthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const h=i-t;let c,u=e*(o.framePerSecond*r)/1e3+this._absoluteFrameOffset,d=0,_=!1;const p=s&&this._animationState.loopMode===Ft.ANIMATIONLOOPMODE_YOYO;if(p){const e=(u-t)/h,i=Math.sin(e*Math.PI);u=Math.abs(i)*h+t;const s=i>=0?1:-1;this._yoyoDirection!==s&&(_=!0),this._yoyoDirection=s}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=u,!s&&i>=t&&(u>=h&&r>0||u<=0&&r<0))l=!1,d=o._getKeyValue(this._maxValue);else if(!s&&t>=i&&(u<=h&&r<0||u>=0&&r>0))l=!1,d=o._getKeyValue(this._minValue);else if(this._animationState.loopMode!==Ft.ANIMATIONLOOPMODE_CYCLE){const e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=Ft.ANIMATIONLOOPMODE_CYCLE;const s=o._interpolate(t,this._animationState),r=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case Ft.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=r-s;break;case Ft.ANIMATIONTYPE_QUATERNION:case Ft.ANIMATIONTYPE_VECTOR3:case Ft.ANIMATIONTYPE_VECTOR2:case Ft.ANIMATIONTYPE_SIZE:case Ft.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=r.subtract(s)}this._highLimitsCache[e]=r}d=this._highLimitsCache[e],c=this._offsetsCache[e]}if(void 0===c)switch(o.dataType){case Ft.ANIMATIONTYPE_FLOAT:c=0;break;case Ft.ANIMATIONTYPE_QUATERNION:c=It;break;case Ft.ANIMATIONTYPE_VECTOR3:c=Rt;break;case Ft.ANIMATIONTYPE_VECTOR2:c=Mt;break;case Ft.ANIMATIONTYPE_SIZE:c=Ot;break;case Ft.ANIMATIONTYPE_COLOR3:c=Dt;break;case Ft.ANIMATIONTYPE_COLOR4:c=wt}let f;if(this._host&&this._host.syncRoot){const e=this._host.syncRoot;f=t+h*((e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame))}else f=u>0&&t>i||u<0&&t0&&this.currentFrame>f||r<0&&this.currentFrame0?0:o.getKeys().length-1}this._currentFrame=f,this._animationState.repeatCount=0===h?0:u/h|0,this._animationState.highLimitValue=d,this._animationState.offsetValue=c;const g=o._interpolate(f,this._animationState);if(this.setValue(g,n),m.length)for(let e=0;e=0&&f>=m[e].frame&&m[e].frame>=t||h<0&&f<=m[e].frame&&m[e].frame<=t){const t=m[e];t.isDone||(t.onlyOnce&&(m.splice(e,1),e--),t.isDone=!0,t.action(f))}return l||(this._stopped=!0),l}}function kt(){return"undefined"!=typeof window}function Vt(){return"undefined"!=typeof navigator}function Ut(){return"undefined"!=typeof document}function Gt(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}const zt={IsWindowObjectExist:kt,IsNavigatorAvailable:Vt,IsDocumentAvailable:Ut,GetDOMTextContent:Gt};class Wt{static get Now(){return kt()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class Ht{}Ht.FilesToLoad={};class Xt{static ExponentialBackoff(e=3,t=500){return(i,s,r)=>0!==s.status||r>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,r)*t}}class Yt extends Error{}Yt._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));const Qt={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class jt extends Yt{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",Yt._setPrototypeOf(this,jt.prototype)}}const Kt=(e,t)=>e.endsWith(t),$t=(e,t)=>!!e&&e.startsWith(t),qt=e=>{if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0;i{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,s,r,n,o,a,l,h="",c=0;const u=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c>2,o=(3&i)<<4|s>>4,a=(15&s)<<2|r>>6,l=63&r,isNaN(s)?a=l=64:isNaN(r)&&(l=64),h+=t.charAt(n)+t.charAt(o)+t.charAt(a)+t.charAt(l);return h},Jt=e=>atob(e),ei=e=>{const t=Jt(e),i=t.length,s=new Uint8Array(new ArrayBuffer(i));for(let e=0;e{let i=String(e);for(;i.length{i+=s.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class ri{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(e);else{const e=t.split(";");for(let t=0;t{h=h.trim(),""!==h&&(i.push(h),h="")},n=e=>{sai._Stack[s],a=()=>-1===s?"!!INVALID EXPRESSION!!":ai._Stack[s--];let l=0,h="";for(;l1){for(r();-1!==s&&ai._OperatorPriority[o()]>=ai._OperatorPriority[c];)i.push(a());n(c),l++}else h+=t;l++}for(r();-1!==s;)"("===o()?a():i.push(a());return ai._InfixToPostfixCache.size>=ai.InfixToPostfixCacheLimitSize&&ai.ClearCache(),ai._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(ai._InfixToPostfixCache.entries()).sort(((e,t)=>e[1].accessTime-t[1].accessTime));for(let t=0;t":i=s>r;break;case"<":i=s=":i=s>=r;break;case"==":i=s===r;break;case"!=":i=s!==r}return i}}var di;!function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(di||(di={}));const _i={};function pi(e,t,i=""){return i+(t?t+"\n":"")+e}function fi(e,t,i,s,r,n,o){const a=o||_i.loadFile;if(a)return a(e,t,i,s,r,n);throw xt("FileTools")}function mi(e,t,i,s){if(e)return t?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,i?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(s?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return t&&(e+="#define IS_NDC_HALF_ZRANGE"),i&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),s&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}const gi=/defined\s*?\((.+?)\)/g,vi=/defined\s*?\[(.+?)\]/g,xi=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,bi=/__decl__/,Ti=/light\{X\}.(\w*)/g,yi=/\{X\}/g,Si=[],Ci=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function Ei(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}function Ai(e,t,i,s){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),Ni(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const r=function(e,t,i){let s=function(e,t){if(t.processor?.noPrecision)return e;const i=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=i?"precision highp float;\n"+e:"precision mediump float;\n"+e:i||(e=e.replace("precision highp float","precision mediump float")),e}(e,t);if(!t.processor)return s;if(t.processor.shaderLanguage===di.GLSL&&-1!==s.indexOf("#version 3")&&(s=s.replace("#version 300 es",""),!t.processor.parseGLES3))return s;const r=t.defines,n=wi(t,i);return t.processor.preProcessor&&(s=t.processor.preProcessor(s,r,n,t.isFragment,t.processingContext)),s=Di(s,n,t),t.processor.postProcessor&&(s=t.processor.postProcessor(s,r,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),i?._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}(e,t,s);i(r,e)}))}function Pi(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}function Ii(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new li(t[1].trim(),"!"===e[0]);const i=["==","!=",">=","<=","<",">"];let s="",r=0;for(s of i)if(r=e.indexOf(s),r>-1)break;if(-1===r)return new li(e);const n=e.substring(0,r).trim(),o=e.substring(r+s.length).trim();return new ui(n,s,o)}function Ri(e,t){const i=new oi,s=e.substring(0,t);let r=e.substring(t);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),i.testExpression="#ifdef"===s?new li(r):"#ifndef"===s?new li(r,!0):function(e){e=e.replace(gi,"defined[$1]");const t=ai.infixToPostfix(e),i=[];for(const e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],s=i[i.length-2];i.length-=2;const r="&&"==e?new ci:new hi;"string"==typeof t&&(t=t.replace(vi,"defined($1)")),"string"==typeof s&&(s=s.replace(vi,"defined($1)")),r.leftOperand="string"==typeof s?Ii(s):s,r.rightOperand="string"==typeof t?Ii(t):t,i.push(r)}let s=i[i.length-1];return"string"==typeof s&&(s=s.replace(vi,"defined($1)")),"string"==typeof s?Ii(s):s}(r),i}function Mi(e,t,i){let s=e.currentLine;for(;Oi(e,i);){s=e.currentLine;const r=s.substring(0,5).toLowerCase();if("#else"===r){const i=new si;return t.children.push(i),void Oi(e,i)}if("#elif"===r){const e=Ri(s,5);t.children.push(e),i=e}}}function Oi(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const s=Ci.exec(i);if(s&&s.length){switch(s[0]){case"#ifdef":{const s=new ni;t.children.push(s);const r=Ri(i,6);s.children.push(r),Mi(e,s,r);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const s=new ni;t.children.push(s);const r=Ri(i,7);s.children.push(r),Mi(e,s,r);break}case"#if":{const s=new ni,r=Ri(i,3);t.children.push(s),s.children.push(r),Mi(e,s,r);break}}continue}}const s=new si;if(s.line=i,t.children.push(s),"#"===i[0]&&"d"===i[1]){const e=i.replace(";","").split(" ");s.additionalDefineKey=e[1],3===e.length&&(s.additionalDefineValue=e[2])}}return!1}function Di(e,t,i){const s=new si,r=new ri;return r.lineIndex=-1,r.lines=e.split("\n"),Oi(r,s),s.process(t,i)}function wi(e,t){const i=e.defines,s={};for(const e of i){const t=e.replace("#define","").replace(";","").trim().split(" ");s[t[0]]=t.length>1?t[1]:""}return e.processor?.shaderLanguage===di.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",mi(s,t?.isNDCHalfZRange,t?.useReverseDepthBuffer,t?.useExactSrgbConversions),s}function Ni(e,t,i){let s;for(Si.length=0;null!==(s=xi.exec(e));)Si.push(s);let r=String(e),n=[e],o=!1;for(const e of Si){let s=e[1];if(-1!==s.indexOf("__decl__")&&(s=s.replace(bi,""),t.supportsUniformBuffers&&(s=s.replace("Vertex","Ubo").replace("Fragment","Ubo")),s+="Declaration"),!t.includesShadersStore[s]){const e=t.shadersRepository+"ShadersInclude/"+s+".fx";return void Fi.loadFile(e,(e=>{t.includesShadersStore[s]=e,Ni(n.join(""),t,i)}))}{let i=t.includesShadersStore[s];if(e[2]){const t=e[3].split(",");for(let e=0;et+"{X}"))),i+=o.replace(yi,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(Ti,((e,t)=>t+"{X}"))),i=i.replace(yi,s)}const r=[];for(const t of n){const s=t.split(e[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}}Si.length=0,r=n.join(""),o?Ni(r.toString(),t,i):i(r)}const Fi={loadFile:(e,t,i,s,r,n)=>{throw xt("FileTools")}};class Li{static SetImmediate(e){kt()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}class Bi{static GetShadersRepository(e=di.GLSL){return e===di.GLSL?Bi.ShadersRepository:Bi.ShadersRepositoryWGSL}static GetShadersStore(e=di.GLSL){return e===di.GLSL?Bi.ShadersStore:Bi.ShadersStoreWGSL}static GetIncludesShadersStore(e=di.GLSL){return e===di.GLSL?Bi.IncludesShadersStore:Bi.IncludesShadersStoreWGSL}}Bi.ShadersRepository="src/Shaders/",Bi.ShadersStore={},Bi.IncludesShadersStore={},Bi.ShadersRepositoryWGSL="src/ShadersWGSL/",Bi.ShadersStoreWGSL={},Bi.IncludesShadersStoreWGSL={};class ki{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,i,s,r,n,o,a){const l=this.engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this.engine.getUniforms(this,i).forEach(((e,t)=>{s[i[t]]=e})),this._uniforms=s,h=0;h{n[e]=t}));for(const e of l.getAttributes(this,o))a.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s||2!==s.length)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r||3!==r.length)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}const Vi=new WeakMap,Ui={_webGLVersion:2,cachedPipelines:{}};function Gi(e){let t=Vi.get(e);if(!t){if(!e)return Ui;t={_webGLVersion:e.TEXTURE_BINDING_3D?2:1,_context:e,cachedPipelines:{}},Vi.set(e,t)}return t}function zi(e,t,i,s,r,n){const o=Gi(s);return n||(n=o._createShaderProgramInjection??Hi),n(e,Qi(t,"vertex",s,o._contextWasLost),Qi(i,"fragment",s,o._contextWasLost),s,r,o.validateShaderPrograms)}function Wi(e,t,i,s,r,n=null,o){const a=Gi(r);o||(o=a._createShaderProgramInjection??Hi);const l=a._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"";return o(e,Yi(t,"vertex",s,l,r,a._contextWasLost),Yi(i,"fragment",s,l,r,a._contextWasLost),r,n,a.validateShaderPrograms)}function Hi(e,t,i,s,r=null,n){const o=s.createProgram();if(e.program=o,!o)throw new Error("Unable to create program");return s.attachShader(o,t),s.attachShader(o,i),s.linkProgram(o),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||Xi(e,s,n),o}function Xi(e,t,i){const s=e.context,r=e.vertexShader,n=e.fragmentShader,o=e.program;if(!s.getProgramParameter(o,s.LINK_STATUS)){if(!t.getShaderParameter(r,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(r);if(i)throw e.vertexCompilationError=i,new Error("VERTEX SHADER "+i)}if(!t.getShaderParameter(n,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(n);if(i)throw e.fragmentCompilationError=i,new Error("FRAGMENT SHADER "+i)}const i=s.getProgramInfoLog(o);if(i)throw e.programLinkError=i,new Error(i)}if(i&&(s.validateProgram(o),!s.getProgramParameter(o,s.VALIDATE_STATUS))){const t=s.getProgramInfoLog(o);if(t)throw e.programValidationError=t,new Error(t)}s.deleteShader(r),s.deleteShader(n),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}function Yi(e,t,i,s,r,n){return Qi(pi(e,i,s),t,r,n)}function Qi(e,t,i,s){const r=i.createShader("vertex"===t?i.VERTEX_SHADER:i.FRAGMENT_SHADER);if(!r){let e=i.NO_ERROR,r=i.NO_ERROR;for(;(r=i.getError())!==i.NO_ERROR;)e=r;throw new Error(`Something went wrong while creating a gl ${t} shader object. gl error=${e}, gl isContextLost=${i.isContextLost()}, _contextWasLost=${s}`)}return i.shaderSource(r,e),i.compileShader(r),r}function ji(e){const t=e._name,i=e.context;if(t&&i){const e=Gi(i),s=e.cachedPipelines[t];s?.dispose(),delete e.cachedPipelines[t]}}function Ki(e,t,i,s,r,n){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void s(Gt(e));if("source:"===e.substr(0,7))return void s(e.substr(7));if("base64:"===e.substr(0,7))return void s(window.atob(e.substr(7)));const o=Bi.GetShadersStore(r);if(o[e+t+"Shader"])return void s(o[e+t+"Shader"]);if(i&&o[e+i+"Shader"])return void s(o[e+i+"Shader"]);let a;if(a="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:Bi.GetShadersRepository(r)+e,!(n=n||fi))throw new Error("loadFileInjection is not defined");n(a+"."+t.toLowerCase()+".fx",s)}class $i{static get ShadersRepository(){return Bi.ShadersRepository}static set ShadersRepository(e){Bi.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new K),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,s=null,r,n=null,o=null,a=null,l=null,h,c="",u=di.GLSL){this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new K,this.onErrorObservable=new K,this._onBindObservable=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=c;const d=this._key.replace(/\r/g,"").replace(/\n/g,"|");let _;if(t.attributes){const e=t;if(this._engine=i,this._attributesNames=e.attributes,this._uniformsNames=e.uniformsNames.concat(e.samplers),this._samplerList=e.samplers.slice(),this.defines=e.defines,this.onError=e.onError,this.onCompiled=e.onCompiled,this._fallbacks=e.fallbacks,this._indexParameters=e.indexParameters,this._transformFeedbackVaryings=e.transformFeedbackVaryings||null,this._multiTarget=!!e.multiTarget,this._shaderLanguage=e.shaderLanguage??di.GLSL,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t{if(c[0]&&c[1]){e.isFragment=!0;const[a,l]=c;Ai(l,e,((n,l)=>{o&&(o._fragmentSourceCodeBeforeMigration=l),i&&(n=i("fragment",n));const h=Pi(a,n,e);e=null;const c=function(e,t,i,s){if(i){const r=i.vertexElement||i.vertex||i.spectorName||i,n=i.fragmentElement||i.fragment||i.spectorName||i;return{vertexSourceCode:(s===di.WGSL?"//":"")+"#define SHADER_NAME vertex:"+r+"\n"+e,fragmentSourceCode:(s===di.WGSL?"//":"")+"#define SHADER_NAME fragment:"+n+"\n"+t}}return{vertexSourceCode:e,fragmentSourceCode:t}}(h.vertexCode,h.fragmentCode,t,r);s?.(c.vertexSourceCode,c.fragmentSourceCode)}),n)}};Ki(a,"Vertex","",(t=>{Ei(e),Ai(t,e,((e,s)=>{o&&(o._rawVertexSourceCode=t,o._vertexSourceCodeBeforeMigration=s),i&&(e=i("vertex",e)),c[0]=e,u()}),n)}),r),Ki(l,"Fragment","Pixel",(e=>{o&&(o._rawFragmentSourceCode=e),c[1]=e,u()}),r)}({defines:this.defines.split("\n"),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:e??this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Bi.GetShadersRepository(this._shaderLanguage),includesShadersStore:Bi.GetIncludesShadersStore(this._shaderLanguage),version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:this._processCodeAfterIncludes},this.name,this._processFinalCode,((e,i)=>{this._vertexSourceCode=e,this._fragmentSourceCode=i,this._prepareEffect(t)}),this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getAttributesNames(){return this._attributesNames}getAttributeLocation(e){return this._attributes[e]}getAttributeLocationByName(e){return this._attributeLocationByName[e]}getAttributesCount(){return this._attributes.length}getUniformIndex(e){return this._uniformsNames.indexOf(e)}getUniform(e){return this._uniforms[e]}getSamplers(){return this._samplerList}getUniformNames(){return this._uniformsNames}getUniformBuffersNames(){return this._uniformBuffersNamesList}getIndexParameters(){return this._indexParameters}getCompilationError(){return this._compilationError}allFallbacksProcessed(){return this._allFallbacksProcessed}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}this._isDisposed||setTimeout((()=>{this._checkIsReady(e)}),16)}get vertexSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:this._pipelineContext?._getVertexShaderCode()??this._vertexSourceCode}get fragmentSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:this._pipelineContext?._getFragmentShaderCode()??this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}getPipelineGenerationOptions(){return{platformName:this._engine.shaderPlatformName,shaderLanguage:this._shaderLanguage,shaderNameOrContent:this.name,key:this._key,defines:this.defines.split("\n"),addGlobalDefines:!1,extendedProcessingOptions:{indexParameters:this._indexParameters,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,supportsUniformBuffers:this._engine.supportsUniformBuffers},extendedCreatePipelineOptions:{transformFeedbackVaryings:this._transformFeedbackVaryings,createAsRaw:!(!this._vertexSourceCodeOverride||!this._fragmentSourceCodeOverride)}}}_rebuildProgram(e,t,i,s){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{s&&s(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;t{try{const r=e.existingPipelineContext||t(e.shaderProcessingContext);return r._name=e.name,e.name&&e.context&&(Gi(e.context).cachedPipelines[e.name]=r),i(r,e.vertex,e.fragment,!!e.createAsRaw,"","",e.rebuildRebind,e.defines,e.transformFeedbackVaryings,""),s(r,(()=>{e.onRenderingStateCompiled?.(r)})),r}catch(e){throw Ne.Error("Error compiling effect"),e}})({existingPipelineContext:e?t:null,vertex:r,fragment:n,context:"WEBGL2"===o.shaderPlatformName?o._gl:void 0,rebuildRebind:(e,t,i,s)=>this._rebuildProgram(e,t,i,s),defines:s,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:i,parallelShaderCompile:o._caps.parallelShaderCompile,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:i=>{t&&!e&&this._engine._deletePipelineContext(t),i&&this._onRenderingStateCompiled(i)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContext.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t,i){const s=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let r=null;if(t&&e){const n=t.match(s);if(n&&2===n.length){const t=parseInt(n[1]),s=e.split("\n",-1);s.length>=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${s[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){this._compilationError=e.message;const i=this._attributesNames,s=this._fallbacks;if(Ne.Error("Unable to compile effect:"),Ne.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),Ne.Error("Attributes: "+i.map((function(e){return" "+e}))),Ne.Error("Defines:\n"+this.defines),$i.LogShaderCodeOnCompilationError){let e=null,t=null,i=null;this._pipelineContext?._getVertexShaderCode()&&([i,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),i&&(Ne.Error("Vertex code:"),Ne.Error(i))),this._pipelineContext?._getFragmentShaderCode()&&([i,t]=this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(),this._compilationError,!0),i&&(Ne.Error("Fragment code:"),Ne.Error(i))),e&&Ne.Error(e),t&&Ne.Error(t)}Ne.Error("Error: "+this._compilationError);const r=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,r()),s?(this._pipelineContext=null,s.hasMoreFallbacks?(this._allFallbacksProcessed=!1,Ne.Error("Trying next fallback."),this.defines=s.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,r(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||r())}get isSupported(){return""===this._compilationError}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){const s=this._samplerList.indexOf(e);for(let e=1;e{t._swapAndDie(this,!1),this.isReady=e.isReady};return void(e.isAsync?e.proxy.then(t):t(e.proxy))}let e;switch(this.source){case is.Temp:break;case is.Url:return void(e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,(e=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer));case is.Raw:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case is.Raw3D:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case is.Raw2DArray:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case is.Dynamic:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case is.Cube:return void(e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,(()=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer));case is.CubeRaw:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case is.CubeRawRGBD:return;case is.CubePrefiltered:return e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,(e=>{e&&e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension),void(e._sphericalPolynomial=this._sphericalPolynomial);case is.DepthStencil:case is.Depth:}}_swapAndDie(e,t=!0){this._hardwareTexture?.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const i=this._engine.getLoadedTexturesCache();let s=i.indexOf(this);-1!==s&&i.splice(s,1),s=i.indexOf(e),-1===s&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}function rs(e,t){if(kt()){const{requestAnimationFrame:i}=t||window;if("function"==typeof i)return i(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}ss._Counter=0;class ns{get frameId(){return this._frameId}get isWebGPU(){return this._isWebGPU}_getShaderProcessor(e){return this._shaderProcessor}get shaderPlatformName(){return this._shaderPlatformName}_clearEmptyResources(){this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,this._depthCullingState.depthFunc=e?518:515)}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}_getGlobalDefines(e){if(e)return this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return this.isNDCHalfZRange&&(e+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}_rebuildInternalTextures(){const e=this._internalTexturesCache.slice();for(const t of e)t._rebuild()}_rebuildRenderTargetWrappers(){const e=this._renderTargetWrapperCache.slice();for(const t of e)t._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}$i.ResetCache()}_rebuildGraphicsResources(){this.wipeCaches(!0),this._rebuildEffects(),this._rebuildComputeEffects?.(),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){Ne.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout((async()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=r,this._flagContextRestored()}),0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return 0}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){const e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get activeRenderLoops(){return this._activeRenderLoops}stopRenderLoop(e){if(!e)return this._activeRenderLoops.length=0,void this._cancelFrame();const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(0!==this._frameHandler){const e=this._frameHandler;if(this._frameHandler=0,kt()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if("function"==typeof t)return t(e)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(e);return clearTimeout(e)}}beginFrame(){this.onBeginFrameObservable.notifyObservers(this)}endFrame(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e-1?e.substring(T).toLowerCase():""),S=null;y.indexOf("?")>-1&&(y=y.split("?")[0]);for(const e of ns._TextureLoaders)if(e.canLoad(y,_)){S=e;break}s&&s.addPendingData(x),x.url=e,x.generateMipMaps=!t,x.samplingMode=r,x.invertY=i,x._useSRGBBuffer=this._getUseSRGBBuffer(!!f,t),this._doNotHandleContextLost||(x._buffer=h);let C=null;n&&!c&&(C=x.onLoadedObservable.add(n)),c||this._internalTexturesCache.push(x);const E=(i,c)=>{s&&s.removePendingData(x),e===b?(C&&x.onLoadedObservable.remove(C),re.UseFallbackTexture&&e!==re.FallbackTexture&&this._createTextureBase(re.FallbackTexture,t,x.invertY,s,r,null,o,a,l,h,x),i=(i||"Unknown error")+(re.UseFallbackTexture?" - Fallback texture was used":""),x.onErrorObservable.notifyObservers({message:i,exception:c}),o&&o(i,c)):(Ne.Warn(`Failed to load ${e}, falling back to ${b}`),this._createTextureBase(b,t,x.invertY,s,r,n,o,a,l,h,x,u,d,_,p,f))};if(S){const t=e=>{S.loadData(e,x,((e,t,i,n,o,l)=>{l?E("TextureLoader failed to load data"):a(x,y,s,{width:e,height:t},x.invertY,!i,n,(()=>(o(),!1)),r)}),p)};h?h instanceof ArrayBuffer?t(new Uint8Array(h)):ArrayBuffer.isView(h)?t(h):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,s?s.offlineProvider:void 0,!0,((e,t)=>{E("Unable to load "+(e&&e.responseURL,t))}))}else{const i=e=>{g&&!this._doNotHandleContextLost&&(x._buffer=e),a(x,y,s,e,x.invertY,t,!1,l,r)};!m||v?h&&("string"==typeof h.decoding||h.close)?i(h):ns._FileToolsLoadImage(e||"",i,E,s?s.offlineProvider:null,_,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof h||h instanceof ArrayBuffer||ArrayBuffer.isView(h)||h instanceof Blob?ns._FileToolsLoadImage(h,i,E,s?s.offlineProvider:null,_,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):h&&i(h)}return x}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuildAfterContextLost()}get _shouldUseHighPrecisionShader(){return!(!this._caps.highPrecisionShaderSupported||!this._highPrecisionShadersAllowed)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:Ut()?document:null}getLoadedTexturesCache(){return this._internalTexturesCache}clearInternalTexturesCache(){this._internalTexturesCache.length=0}getCaps(){return this._caps}resetTextureCache(){for(const e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}get name(){return this._name}set name(e){this._name=e}static get NpmPackage(){return"babylonjs@7.9.0"}static get Version(){return"7.9.0"}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get isStencilEnable(){return this._isStencilEnable}getCreationOptions(){return this._creationOptions}constructor(e,t,i){this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new qi,this._stencilStateComposer=new Zi,this._stencilState=new Ji,this._alphaState=new es,this._alphaMode=1,this._alphaEquation=0,this._activeRequests=[],this._badOS=!1,this._badDesktopOS=!1,this._compatibilityMode=!0,this._internalTexturesCache=new Array,this._currentRenderTarget=null,this._boundTexturesCache={},this._activeChannel=0,this._currentTextureChannel=-1,this._viewportCached={x:0,y:0,z:0,w:0},this._isWebGPU=!1,this.onCanvasBlurObservable=new K,this.onCanvasFocusObservable=new K,this.onNewSceneAddedObservable=new K,this.onResizeObservable=new K,this.onCanvasPointerOutObservable=new K,this.disablePerformanceMonitorInBackground=!1,this.disableVertexArrayObjects=!1,this._frameId=0,this.hostInformation={isMobile:!1},this.isFullscreen=!1,this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.currentRenderPassId=0,this.isPointerLock=!1,this.postProcesses=[],this.canvasTabIndex=1,this._contextWasLost=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this._renderTargetWrapperCache=new Array,this._compiledEffects={},this._isDisposed=!1,this.scenes=[],this._virtualScenes=new Array,this.onBeforeTextureInitObservable=new K,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new K,this.onAfterShaderCompilationObservable=new K,this.onBeginFrameObservable=new K,this.onEndFrameObservable=new K,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new K,this.onContextRestoredObservable=new K,this._name="",this.premultipliedAlpha=!0,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._doNotHandleContextLost=!1,this.cullBackFaces=null,this._renderPassNames=["main"],this._fps=60,this._deltaTime=0,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this.onDisposeObservable=new K,re.Instances.push(this),this.startTime=Wt.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,se.SetMatrixPrecision(!!t.useHighPrecisionMatrix),Vt()&&navigator.userAgent&&(this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),this.adaptToDeviceRatio=i??!1,t.antialias=e??t.antialias,t.deterministicLockstep=t.deterministicLockstep??!1,t.lockstepMaxSteps=t.lockstepMaxSteps??4,t.timeStep=t.timeStep??1/60,t.audioEngine=t.audioEngine??!0,t.stencil=t.stencil??!0,this._audioContext=t.audioEngineOptions?.audioContext??null,this._audioDestination=t.audioEngineOptions?.audioDestination??null,this.premultipliedAlpha=t.premultipliedAlpha??!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=t.useExactSrgbConversions??!1;const s=kt()&&window.devicePixelRatio||1,r=t.limitDeviceRatio||s;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(r,s):1,this._lastDevicePixelRatio=s,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const e=kt()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if(kt()&&Ut())if(this._renderingCanvas){const e=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||e.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||e.height||this._renderingCanvas.height||100}else t=window.innerWidth,i=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){if(!this._renderingCanvas)return!1;if(e|=0,t|=0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t)return!1;if(this._renderingCanvas.width=e,this._renderingCanvas.height=t,this.scenes){for(let e=0;e{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&Ut()&&"ontouchend"in document},this._checkForMobile(),kt()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){this._drawCalls?.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}_createImageBitmapFromSource(e,t){throw new Error("createImageBitmapFromSource is not implemented")}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){throw new Error("resizeImageBitmap is not implemented")}getFontOffset(e){throw new Error("getFontOffset is not implemented")}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return ns._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,s,r,n){throw xt("FileTools")}_loadFile(e,t,i,s,r,n){const o=fi(e,t,i,s,r,n);return this._activeRequests.push(o),o.onCompleteObservable.add((()=>{const e=this._activeRequests.indexOf(o);-1!==e&&this._activeRequests.splice(e,1)})),o}static _FileToolsLoadFile(e,t,i,s,r,n){if(_i.loadFile)return _i.loadFile(e,t,i,s,r,n);throw xt("FileTools")}dispose(){for(this.hideLoadingUI(),this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();this.releaseComputeEffects?.(),$i.ResetCache();for(const e of this._activeRequests)e.abort();this._boundRenderFunction=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onNewSceneAddedObservable.clear(),kt()&&window.removeEventListener("resize",this._checkForMobile);const e=re.Instances.indexOf(this);e>=0&&re.Instances.splice(e,1),re.Instances.length||(re.OnEnginesDisposedObservable.notifyObservers(this),re.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw xt("LoadingScreen")}}ns._TextureLoaders=[],ns._RenderPassIdCounter=0,ns._RescalePostProcessFactory=null;const os=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class as extends jt{constructor(e,t){super(e,Qt.LoadFileError),this.name="LoadFileError",Yt._setPrototypeOf(this,as.prototype),t instanceof Pt?this.request=t:this.file=t}}class ls extends jt{constructor(e,t){super(e,Qt.RequestFileError),this.request=t,this.name="RequestFileError",Yt._setPrototypeOf(this,ls.prototype)}}class hs extends jt{constructor(e,t){super(e,Qt.ReadFileError),this.file=t,this.name="ReadFileError",Yt._setPrototypeOf(this,hs.prototype)}}const cs={DefaultRetryStrategy:Xt.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e,CleanUrl:e=>e.replace(/#/gm,"%23")},us=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&cs.CorsBehavior)if("string"==typeof cs.CorsBehavior||cs.CorsBehavior instanceof String)t.crossOrigin=cs.CorsBehavior;else{const i=cs.CorsBehavior(e);i&&(t.crossOrigin=i)}},ds=(e,t,i,s,r="",n)=>{const o=re.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!o?._features.forceBitmapOverHTMLImageElement)return i("LoadImage is only supported in web or BabylonNative environments."),null;let a,l=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(a=URL.createObjectURL(new Blob([e],{type:r})),l=!0):a=`data:${r};base64,`+Zt(e):e instanceof Blob?(a=URL.createObjectURL(e),l=!0):(a=cs.CleanUrl(e),a=cs.PreprocessUrl(e));const h=t=>{if(i){const s=a||e.toString();i(`Error while trying to load image: ${0===s.indexOf("http")||s.length<=128?s:s.slice(0,128)+"..."}`,t)}};if(o?._features.forceBitmapOverHTMLImageElement)return ps(a,(s=>{o.createImageBitmap(new Blob([s],{type:r}),{premultiplyAlpha:"none",...n}).then((e=>{t(e),l&&URL.revokeObjectURL(a)})).catch((t=>{i&&i("Error while trying to load image: "+e,t)}))}),void 0,s||void 0,!0,((e,t)=>{h(t)})),null;const c=new Image;us(a,c);const u=[],d=()=>{u.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),u.length=0};u.push({target:c,name:"load",handler:()=>{d(),t(c),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:c,name:"error",handler:e=>{d(),h(e),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==c.src)return;d();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);re.UseFallbackTexture=!1,h(t),l&&c.src&&URL.revokeObjectURL(c.src),c.src=""}}),u.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const _="blob:"===a.substring(0,5),p="data:"===a.substring(0,5),f=()=>{_||p||!Pt.IsCustomRequestAvailable?c.src=a:ps(a,((e,t,i)=>{const s=new Blob([e],{type:!r&&i?i:r}),n=URL.createObjectURL(s);l=!0,c.src=n}),void 0,s||void 0,!0,((e,t)=>{h(t)}))};if(!_&&!p&&s&&s.enableTexturesOffline)s.open((()=>{s&&s.loadImage(a,c)}),f);else{if(-1!==a.indexOf("file:")){const e=decodeURIComponent(a.substring(5).toLowerCase());if(Ht.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(Ht.FilesToLoad[e])}catch(i){t=URL.createObjectURL(Ht.FilesToLoad[e])}c.src=t,l=!0}catch(e){c.src=""}return c}}f()}return c},_s=(e,t,i,s,r)=>{const n=new FileReader,o={onCompleteObservable:new K,abort:()=>n.abort()};return n.onloadend=()=>o.onCompleteObservable.notifyObservers(o),r&&(n.onerror=()=>{r(new hs(`Unable to read ${e.name}`,e))}),n.onload=e=>{t(e.target.result)},i&&(n.onprogress=i),s?n.readAsArrayBuffer(e):n.readAsText(e),o},ps=(e,t,i,s,r,n,o)=>{if(e.name)return _s(e,t,i,r,n?e=>{n(void 0,e)}:void 0);const a=e;if(-1!==a.indexOf("file:")){let e=decodeURIComponent(a.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const s=Ht.FilesToLoad[e];if(s)return _s(s,t,i,r,n?e=>n(void 0,new as(e.message,e.file)):void 0)}const{match:l,type:h}=vs(a);if(l){const e={onCompleteObservable:new K,abort:()=>()=>{}};try{const e=r?xs(a):bs(a);t(e,void 0,h)}catch(e){n?n(void 0,e):Ne.Error(e.message||"Failed to parse the Data URL")}return Li.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return fs(a,((e,i)=>{t(e,i?.responseURL,i?.getResponseHeader("content-type"))}),i,s,r,n?e=>{n(e.request,new as(e.message,e.request))}:void 0,o)},fs=(e,t,i,s,r,n,o)=>{e=cs.CleanUrl(e),e=cs.PreprocessUrl(e);const a=cs.BaseUrl+e;let l=!1;const h={onCompleteObservable:new K,abort:()=>l=!0},c=()=>{let e,s=new Pt,c=null;const u=()=>{s&&(i&&s.removeEventListener("progress",i),e&&s.removeEventListener("readystatechange",e),s.removeEventListener("loadend",d))};let d=()=>{u(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),i=void 0,e=null,d=null,n=void 0,o=void 0,t=void 0};h.abort=()=>{l=!0,d&&d(),s&&s.readyState!==(XMLHttpRequest.DONE||4)&&s.abort(),null!==c&&(clearTimeout(c),c=null),s=null};const _=e=>{const t=e.message||"Unknown error";n&&s?n(new ls(t,s)):Ne.Error(t)},p=h=>{if(s){if(s.open("GET",a),o)try{o(s)}catch(e){return void _(e)}r&&(s.responseType="arraybuffer"),i&&s.addEventListener("progress",i),d&&s.addEventListener("loadend",d),e=()=>{if(!l&&s&&s.readyState===(XMLHttpRequest.DONE||4)){if(e&&s.removeEventListener("readystatechange",e),s.status>=200&&s.status<300||0===s.status&&(!kt()||ms())){try{t&&t(r?s.response:s.responseText,s)}catch(e){_(e)}return}const i=cs.DefaultRetryStrategy;if(i){const e=i(a,s,h);if(-1!==e)return u(),s=new Pt,void(c=setTimeout((()=>p(h+1)),e))}const o=new ls("Error status: "+s.status+" "+s.statusText+" - Unable to load "+a,s);n&&n(o)}},s.addEventListener("readystatechange",e),s.send()}};p(0)};if(s&&s.enableSceneOffline){const o=e=>{e&&e.status>400?n&&n(e):c()},a=()=>{s&&s.loadFile(cs.BaseUrl+e,(e=>{!l&&t&&t(e),h.onCompleteObservable.notifyObservers(h)}),i?e=>{!l&&i&&i(e)}:void 0,o,r)};s.open(a,o)}else c();return h},ms=()=>"undefined"!=typeof location&&"file:"===location.protocol,gs=e=>os.test(e),vs=e=>{const t=os.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function xs(e){return ei(e.split(",")[1])}const bs=e=>Jt(e.split(",")[1]);let Ts;ns._FileToolsLoadImage=ds,_i.loadFile=ps,Fi.loadFile=ps;const ys=(e,t,i,s,r,n,o,a,l,h)=>{Ts={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:s,IsFileURL:r,LoadFile:n,LoadImage:o,ReadFile:a,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(Ts,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(Ts,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(Ts,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(Ts,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})};ys(xs,bs,cs,gs,ms,ps,ds,_s,fs,us);class Ss{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=W(e);if(t)return t;Ne.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let e=0,t=i.length;e{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}Ss.RegisteredExternalClasses={};const Es={RandomId:Cs};function As(e){let t=1;do{t*=2}while(te-i?i:t}function Rs(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}function Ms(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}function Os(e,t,i=2){let s;switch(i){case 1:s=Ms(e);break;case 2:s=Is(e);break;default:s=Rs(e)}return Math.min(s,t)}class Ds{static get BaseUrl(){return cs.BaseUrl}static set BaseUrl(e){cs.BaseUrl=e}static get CleanUrl(){return cs.CleanUrl}static set CleanUrl(e){cs.CleanUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||-1!==e.indexOf("://")&&-1!==e.indexOf(".")&&-1!==e.indexOf("/")&&!(e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://"){ps(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{s(t)}))}))}static GetBabylonScriptURL(e,t){if(!e)return"";if(Ds.ScriptBaseUrl&&e.startsWith(Ds._DefaultCdnUrl)){const t="/"===Ds.ScriptBaseUrl[Ds.ScriptBaseUrl.length-1]?Ds.ScriptBaseUrl.substring(0,Ds.ScriptBaseUrl.length-1):Ds.ScriptBaseUrl;e=e.replace(Ds._DefaultCdnUrl,t)}return e=Ds.ScriptPreprocessUrl(e),t&&(e=Ds.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=Ds.GetBabylonScriptURL(e),Ds.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=Ds.GetBabylonScriptURL(e),Ds.LoadScriptAsync(e)}static LoadScript(e,t,i,s){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){i?.(`Unable to load script '${e}' in worker`,t)}return}if(!kt())return void i?.(`Cannot load script '${e}' outside of a window or a worker`);const r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("src",e),s&&(n.id=s),n.onload=()=>{t&&t()},n.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},r.appendChild(n)}static LoadScriptAsync(e,t){return new Promise(((i,s)=>{this.LoadScript(e,(()=>{i()}),((e,t)=>{s(t||new Error(e))}),t)}))}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new K,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,s,r){return _s(e,t,i,s,r)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,s){Ye.DeepCopy(e,t,i,s)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{const s=atob(this.toDataURL(t,i).split(",")[1]),r=s.length,n=new Uint8Array(r);for(let e=0;et(e))):e.toBlob((function(e){t(e)}),i,s)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const e=new Date;t="screenshot_"+(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2)+".png"}Ds.Download(e,t)}else if(e&&"undefined"!=typeof URL){const t=URL.createObjectURL(e),i=window.open("");if(!i)return;const s=i.document.createElement("img");s.onload=function(){URL.revokeObjectURL(t)},s.src=t,i.document.body.appendChild(s)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,r){if("string"!=typeof s&&t){if(t){if(Ds._IsOffScreenCanvas(e))return void e.convertToBlob({type:i,quality:r}).then((e=>{const i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{const e=i.result;t(e)}}));const s=e.toDataURL(i,r);t(s)}}else this.ToBlob(e,(function(e){e&&Ds.DownloadBlob(e,s),t&&t("")}),i,r)}static Download(e,t){if("undefined"==typeof URL)return;const i=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.style.display="none",s.href=i,s.download=t,s.addEventListener("click",(()=>{s.parentElement&&s.parentElement.removeChild(s)})),s.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,s,r="image/png",n=!1,o){throw xt("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",r){throw xt("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,o=!1,a,l=!1,h=!1,c=!0,u){throw xt("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,o,a=!1,l=!1,h=!0,c){throw xt("ScreenshotTools")}static RandomId(){return Cs()}static IsBase64(e){return gs(e)}static DecodeBase64(e){return xs(e)}static get errorsCount(){return Ne.errorsCount}static Log(e){Ne.Log(e)}static Warn(e){Ne.Warn(e)}static Error(e){Ne.Error(e)}static get LogCache(){return Ne.LogCache}static ClearLogCache(){Ne.ClearLogCache()}static set LogLevels(e){Ne.LogLevels=e}static set PerformanceLogLevel(e){return(e&Ds.PerformanceUserMarkLogLevel)===Ds.PerformanceUserMarkLogLevel?(Ds.StartPerformanceCounter=Ds._StartUserMark,void(Ds.EndPerformanceCounter=Ds._EndUserMark)):(e&Ds.PerformanceConsoleLogLevel)===Ds.PerformanceConsoleLogLevel?(Ds.StartPerformanceCounter=Ds._StartPerformanceConsole,void(Ds.EndPerformanceCounter=Ds._EndPerformanceConsole)):(Ds.StartPerformanceCounter=Ds._StartPerformanceCounterDisabled,void(Ds.EndPerformanceCounter=Ds._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Ds._Performance){if(!kt())return;Ds._Performance=window.performance}t&&Ds._Performance.mark&&Ds._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&Ds._Performance.mark&&(Ds._Performance.mark(e+"-End"),Ds._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Ds._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Ds._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return Wt.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,s=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,s=r.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=s?s+".":"")+i:null}static DelayAsync(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}static IsSafari(){return!!Vt()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}function ws(e,t){return i=>{i.__bjsclassName__=e,i.__bjsmoduleName__=null!=t?t:null}}Ds.UseCustomRequestHeaders=!1,Ds.CustomRequestHeaders=Pt.CustomRequestHeaders,Ds.GetDOMTextContent=Gt,Ds._DefaultCdnUrl="https://cdn.babylonjs.com",Ds.GetAbsoluteUrl="object"==typeof document?e=>{const t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},Ds.NoneLogLevel=Ne.NoneLogLevel,Ds.MessageLogLevel=Ne.MessageLogLevel,Ds.WarningLogLevel=Ne.WarningLogLevel,Ds.ErrorLogLevel=Ne.ErrorLogLevel,Ds.AllLogLevel=Ne.AllLogLevel,Ds.IsWindowObjectExist=kt,Ds.PerformanceNoneLogLevel=0,Ds.PerformanceUserMarkLogLevel=1,Ds.PerformanceConsoleLogLevel=2,Ds.StartPerformanceCounter=Ds._StartPerformanceCounterDisabled,Ds.EndPerformanceCounter=Ds._EndPerformanceCounterDisabled;class Ns{constructor(e,t,i,s=0){this.iterations=e,this.index=s-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{r&&r()?s.breakLoop():setTimeout((()=>{for(let n=0;n=e)break;if(i(o),r&&r()){s.breakLoop();break}}s.executeNext()}),n)}),s)}}Ds.Mix=Ps,Ds.IsExponentOfTwo=As,re.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";class Fs{constructor(e){this.length=0,this.data=new Array(e),this._id=Fs._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}Fs._GlobalId=0;class Ls extends Fs{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return!(e.__smartArrayFlags&&e.__smartArrayFlags[this._id]===this._duplicateId||(this.push(e),0))}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;tthis.add(e,t)))}get(e){const t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let i=this.get(e);return void 0!==i||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return void 0!==i?i:(this.add(e,t),t)}contains(e){return void 0!==this._data[e]}add(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)}set(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null}remove(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data)e(t,this._data[t])}first(e){for(const t in this._data){const i=e(t,this._data[t]);if(i)return i}return null}}function ks(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class Vs{constructor(){this._dirty=!0,this._tempColor=new Ae(0,0,0,0),this._globalCurve=new Ae(0,0,0,0),this._highlightsCurve=new Ae(0,0,0,0),this._midtonesCurve=new Ae(0,0,0,0),this._shadowsCurve=new Ae(0,0,0,0),this._positiveCurve=new Ae(0,0,0,0),this._negativeCurve=new Ae(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",s="vCameraColorCurveNeutral",r="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(s,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(r,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,s,r){null!=e&&(e=Vs._Clamp(e,0,360),t=Vs._Clamp(t,-100,100),i=Vs._Clamp(i,-100,100),s=Vs._Clamp(s,-100,100),t=Vs._ApplyColorGradingSliderNonlinear(t),t*=.5,s=Vs._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),Vs._FromHSBToRef(e,t,50+.25*s,r),r.scaleToRef(2,r),r.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,s){let r=Vs._Clamp(e,0,360);const n=Vs._Clamp(t/100,0,1),o=Vs._Clamp(i/100,0,1);if(0===n)s.r=o,s.g=o,s.b=o;else{r/=60;const e=Math.floor(r),t=r-e,i=o*(1-n),a=o*(1-n*t),l=o*(1-n*(1-t));switch(e){case 0:s.r=o,s.g=l,s.b=i;break;case 1:s.r=a,s.g=o,s.b=i;break;case 2:s.r=i,s.g=o,s.b=l;break;case 3:s.r=i,s.g=a,s.b=o;break;case 4:s.r=l,s.g=i,s.b=o;break;default:s.r=o,s.g=i,s.b=a}}s.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return St.Clone((()=>new Vs),this)}serialize(){return St.Serialize(this)}static Parse(e){return St.Parse((()=>new Vs),e,null,null)}}function Us(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&ks(e),t.DITHER&&e.push("ditherIntensity")}function Gs(e,t){t.COLORGRADING&&e.push("txColorTransform")}Vs.PrepareUniforms=ks,Ze([rt()],Vs.prototype,"_globalHue",void 0),Ze([rt()],Vs.prototype,"_globalDensity",void 0),Ze([rt()],Vs.prototype,"_globalSaturation",void 0),Ze([rt()],Vs.prototype,"_globalExposure",void 0),Ze([rt()],Vs.prototype,"_highlightsHue",void 0),Ze([rt()],Vs.prototype,"_highlightsDensity",void 0),Ze([rt()],Vs.prototype,"_highlightsSaturation",void 0),Ze([rt()],Vs.prototype,"_highlightsExposure",void 0),Ze([rt()],Vs.prototype,"_midtonesHue",void 0),Ze([rt()],Vs.prototype,"_midtonesDensity",void 0),Ze([rt()],Vs.prototype,"_midtonesSaturation",void 0),Ze([rt()],Vs.prototype,"_midtonesExposure",void 0),St._ColorCurvesParser=Vs.Parse;class zs{constructor(){this.colorCurves=new Vs,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=zs.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new Ae(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=zs.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new K}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled)return e.VIGNETTE=!1,e.TONEMAPPING=0,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,void(e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===zs._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,this._toneMappingEnabled)switch(this._toneMappingType){case zs.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case zs.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1}else e.TONEMAPPING=0;e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||!!e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&Vs.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),s=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,s),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=null!=t?t:s/i;let n=Math.tan(.5*this.vignetteCameraFov),o=n*r;const a=Math.sqrt(o*n);o=Ps(o,a,this.vignetteStretch),n=Ps(n,a,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,n,-o*this.vignetteCenterX,-n*this.vignetteCenterY);const l=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,l)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return St.Clone((()=>new zs),this)}serialize(){return St.Serialize(this)}static Parse(e){const t=St.Parse((()=>new zs),e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}function Ws(e){return void 0===e.getPipelineContext}zs.TONEMAPPING_STANDARD=0,zs.TONEMAPPING_ACES=1,zs.TONEMAPPING_KHR_PBR_NEUTRAL=2,zs.PrepareUniforms=Us,zs.PrepareSamplers=Gs,zs._VIGNETTEMODE_MULTIPLY=0,zs._VIGNETTEMODE_OPAQUE=1,Ze([ut()],zs.prototype,"colorCurves",void 0),Ze([rt()],zs.prototype,"_colorCurvesEnabled",void 0),Ze([nt("colorGradingTexture")],zs.prototype,"_colorGradingTexture",void 0),Ze([rt()],zs.prototype,"_colorGradingEnabled",void 0),Ze([rt()],zs.prototype,"_colorGradingWithGreenDepth",void 0),Ze([rt()],zs.prototype,"_colorGradingBGR",void 0),Ze([rt()],zs.prototype,"_exposure",void 0),Ze([rt()],zs.prototype,"_toneMappingEnabled",void 0),Ze([rt()],zs.prototype,"_toneMappingType",void 0),Ze([rt()],zs.prototype,"_contrast",void 0),Ze([rt()],zs.prototype,"vignetteStretch",void 0),Ze([rt()],zs.prototype,"vignetteCenterX",void 0),Ze([rt()],zs.prototype,"vignetteCenterY",void 0),Ze([rt()],zs.prototype,"vignetteWeight",void 0),Ze([dt()],zs.prototype,"vignetteColor",void 0),Ze([rt()],zs.prototype,"vignetteCameraFov",void 0),Ze([rt()],zs.prototype,"_vignetteBlendMode",void 0),Ze([rt()],zs.prototype,"_vignetteEnabled",void 0),Ze([rt()],zs.prototype,"_ditheringEnabled",void 0),Ze([rt()],zs.prototype,"_ditheringIntensity",void 0),Ze([rt()],zs.prototype,"_skipFinalColorClamp",void 0),Ze([rt()],zs.prototype,"_applyByPostProcess",void 0),Ze([rt()],zs.prototype,"_isEnabled",void 0),St._ImageProcessingConfigurationParser=zs.Parse,z("BABYLON.ImageProcessingConfiguration",zs);class Hs{constructor(){this.shaderLanguage=di.GLSL}postProcessor(e,t,i,s,r){if(r.drawBuffersExtensionDisabled){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}const Xs=/(flat\s)?\s*varying\s*.*/;class Ys{constructor(){this.shaderLanguage=di.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return Xs.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(s||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}class Qs{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=Qs._Counter++}}Qs._Counter=0;class js extends Qs{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class Ks{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){return this._MSAARenderBuffers?.[e]??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}class $s{}class qs extends ns{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return $i.ShadersRepository}static set ShadersRepository(e){$i.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}snapshotRenderingReset(){this.snapshotRendering=!1}constructor(e,t,i,s){if(i=i||{},super(t??i.antialias,i,s),this._name="WebGL",this.forcePOTTextures=!1,this.validateShaderPrograms=!1,this.disableUniformBuffers=!1,this._webGLVersion=1,this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},!e)return;let r=null;if(e.getContext){if(r=e,this._renderingCanvas=r,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();const e=navigator.userAgent;for(const t of qs.ExceptionList){const s=t.key,r=t.targets;if(new RegExp(s).test(e)){if(t.capture&&t.captureConstraint){const i=t.capture,s=t.captureConstraint,r=new RegExp(i).exec(e);if(r&&r.length>0&&parseInt(r[r.length-1])>=s)continue}for(const e of r)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,Ne.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost((()=>this._initGLContext()))},r.addEventListener("webglcontextlost",this._onContextLost,!1),r.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=r.getContext("webgl2",i)||r.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!r)throw new Error("The provided canvas is null or undefined.");try{this._gl=r.getContext("webgl",i)||r.getContext("experimental-webgl",i)}catch(e){throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";const t=this._gl.getContextAttributes();t&&(i.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==i.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e1?new Ys:new Hs;const n=`Babylon.js v${qs.Version}`;Ne.Log(n+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",n);const o=Gi(this._gl);o.validateShaderPrograms=this.validateShaderPrograms,o.parallelShaderCompile=this._caps.parallelShaderCompile}_clearEmptyResources(){this._dummyFramebuffer=null,super._clearEmptyResources()}_getShaderProcessingContext(e){return null}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_initGLContext(){this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||null!==this._gl.getExtension("OES_standard_derivatives"),maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:1!==this._webGLVersion,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=e&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)??0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!(!this._creationOptions||!this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);this._gl.uniformBlockBinding(s,r,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,s,r,n,o){const a=this._currentBufferPointers[t];if(!a)return;let l=!1;a.active?(a.buffer!==e&&(a.buffer=e,l=!0),a.size!==i&&(a.size=i,l=!0),a.type!==s&&(a.type=s,l=!0),a.normalized!==r&&(a.normalized=r,l=!0),a.stride!==n&&(a.stride=n,l=!0),a.offset!==o&&(a.offset=o,l=!0)):(l=!0,a.active=!0,a.index=t,a.size=i,a.type=s,a.normalized=r,a.stride=n,a.offset=o,a.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),s===this._gl.UNSIGNED_INT||s===this._gl.INT?this._gl.vertexAttribIPointer(t,i,s,n,o):this._gl.vertexAttribPointer(t,i,s,r,n,o))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const s=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let r=0;r=0){const t=s[r];let o=null;if(i&&(o=i[t]),o||(o=e[t]),!o)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const a=o.getBuffer();a&&(this._vertexAttribPointer(a,n,o.getSize(),o.type,o.normalized,o.byteStride,o.byteOffset),o.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,o.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(a))))}}}recordVertexArrayObject(e,t,i,s){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,s),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,s,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const t=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let o=0;o=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[o],this._gl.FLOAT,!1,s,n)),n+=4*i[o]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,s){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,s)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t{s?.(),t(e)}}(e,t)}getUniforms(e,t){const i=new Array,s=e;for(let e=0;e1||this.isWebGPU)),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(a=1),1!==o||this._caps.textureFloat||(o=0,Ne.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=this._gl,d=new ss(this,s),_=e.width||e,p=e.height||e,f=e.depth||0,m=e.layers||0,g=this._getSamplingParameters(a,n),v=0!==m?u.TEXTURE_2D_ARRAY:0!==f?u.TEXTURE_3D:u.TEXTURE_2D,x=this._getRGBABufferInternalSizedFormat(o,l,h),b=this._getInternalFormat(l),T=this._getWebGLTextureType(o);return this._bindTextureDirectly(v,d),0!==m?(d.is2DArray=!0,u.texImage3D(v,0,x,_,p,m,0,b,T,null)):0!==f?(d.is3D=!0,u.texImage3D(v,0,x,_,p,f,0,b,T,null)):u.texImage2D(v,0,x,_,p,0,b,T,null),u.texParameteri(v,u.TEXTURE_MAG_FILTER,g.mag),u.texParameteri(v,u.TEXTURE_MIN_FILTER,g.min),u.texParameteri(v,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(v,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(v),this._bindTextureDirectly(v,null),d._useSRGBBuffer=h,d.baseWidth=_,d.baseHeight=p,d.width=_,d.height=p,d.depth=m,d.isReady=!0,d.samples=c,d.generateMipMaps=n,d.samplingMode=a,d.type=o,d.format=l,d.label=r,this._internalTexturesCache.push(d),d}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,_,p){return this._createTextureBase(e,t,i,s,r,n,o,((...e)=>this._prepareWebGLTexture(...e,h)),((e,t,i,r,n,o)=>{const a=this._gl,l=i.width===e&&i.height===t;n._creationFlags=_??0;const h=this._getTexImageParametersForCreateTexture(n.format,n._useSRGBBuffer);if(l)return a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,i),!1;const c=this._caps.maxTextureSize;if(i.width>c||i.height>c||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!(!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,this._workingCanvas),n.width=e,n.height=t,1));{const e=new ss(this,is.Temp);this._bindTextureDirectly(a.TEXTURE_2D,e,!0),a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,i),this._rescaleTexture(e,n,s,h.format,(()=>{this._releaseTexture(e),this._bindTextureDirectly(a.TEXTURE_2D,n,!0),o()}))}return!0}),a,l,h,c,u,d,p)}_getTexImageParametersForCreateTexture(e,t){let i,s;return 1===this.webGLVersion?(i=this._getInternalFormat(e,t),s=i):(i=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(0,e,t)),{internalFormat:s,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,s,r){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const s=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,r.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),t.samplingMode=e}updateTextureDimensions(e,t,i,s=1){}updateTextureWrappingMode(e,t,i=null,s=null){const r=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==s&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(r,null)}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){const a=this._gl;let l=a.TEXTURE_2D;if(e.isCube&&(l=a.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=a.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(l,o,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const o=this._gl,a=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=void 0===r?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=o.TEXTURE_2D;e.isCube&&(c=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);const u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),_=n?e.width:Math.pow(2,Math.max(u-s,0)),p=n?e.height:Math.pow(2,Math.max(d-s,0));o.texImage2D(c,s,h,_,p,0,l,a,t)}updateTextureData(e,t,i,s,r,n,o=0,a=0,l=!1){const h=this._gl,c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,_=h.TEXTURE_2D;e.isCube&&(_=h.TEXTURE_CUBE_MAP_POSITIVE_X+o,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(_,a,i,s,r,n,u,c,t),l&&this._gl.generateMipmap(_),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const r=this._gl,n=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,r){const n=this._gl;if(!n)return;const o=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,o.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,o.min),i||s||n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,r,n,o,a,l,h){const c=this.getCaps().maxTextureSize,u=Math.min(c,this.needPOTTextures?Os(s.width,c):s.width),d=Math.min(c,this.needPOTTextures?Os(s.height,c):s.height),_=this._gl;_&&(e._hardwareTexture?(this._bindTextureDirectly(_.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),e.baseWidth=s.width,e.baseHeight=s.height,e.width=u,e.height=d,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:h??(".jpg"!==t||e._useSRGBBuffer?5:4),a(u,d,s,t,e,(()=>{this._prepareWebGLTextureContinuation(e,i,n,o,l)}))||this._prepareWebGLTextureContinuation(e,i,n,o,l)):i&&i.removePendingData(e))}_setupFramebufferDepthAttachments(e,t,i,s,r=1){const n=this._gl;if(e&&t)return this._createRenderBuffer(i,s,r,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let e=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=n.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,r,e,e,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,r,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,r,n,o=!0){const a=this._gl.createRenderbuffer();return this._updateRenderBuffer(a,e,t,i,s,r,n,o)}_updateRenderBuffer(e,t,i,s,r,n,o,a=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),s>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,s,n,t,i):l.renderbufferStorage(l.RENDERBUFFER,r,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,o,l.RENDERBUFFER,e),a&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture?.underlyingResource),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);-1!==t&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(function(e,t){t.useProgram(e)}(e,this._gl),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t-1;if(i&&n&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw Ne.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,t?._hardwareTexture?.underlyingResource??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(r=!0,this._activateCurrentTexture());return n&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),r}_bindTexture(e,t,i){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;const s=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(s,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,s=!1,r=""){if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;const i=t.getInternalTexture();i&&(i._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;n=s?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&n&&(n._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),o=!1),this._activeChannel=e;const a=this._getTextureTarget(n);if(o&&this._bindTextureDirectly(a,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(a,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,s){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},kt()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&this._gl.getExtension("WEBGL_lose_context")?.loseContext(),function(e){Vi.delete(e)}(this._gl)}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const s=t.createTexture();t.bindTexture(t.TEXTURE_2D,s),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const n=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&n===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);const e=t.RGBA,s=t.UNSIGNED_BYTE,r=new Uint8Array(4);t.readPixels(0,0,1,1,e,s,r),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(r),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:i=this._gl.RED;break;case 7:i=this._gl.RG;break;case 4:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,s,r=!0,n=!0){const o=r?4:3,a=r?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(s*i*o);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,a,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{const e=ns._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{const e=ns._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}}qs._TempClearColorUint32=new Uint32Array(4),qs._TempClearColorInt32=new Int32Array(4),qs.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],qs.CollisionsEpsilon=.001,qs._ConcatenateShader=pi,qs._IsSupported=null,qs._HasMajorPerformanceCaveat=null,qs.CeilingPOT=Rs,qs.FloorPOT=Ms,qs.NearestPOT=Is,qs.GetExponentOfTwo=Os,qs.QueueNewFrame=rs,qs.prototype.createUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create uniform buffer");const s=new js(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},qs.prototype.createDynamicUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create dynamic uniform buffer");const s=new js(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},qs.prototype.updateUniformBuffer=function(e,t,i,s){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===s?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+s)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+s)),this.bindUniformBuffer(null)},qs.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},qs.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},qs.prototype.bindUniformBlock=function(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);4294967295!==r&&this._gl.uniformBlockBinding(s,r,i)};class Zs{constructor(e,t,i,s,r=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,this._dynamic=i,this._name=s??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){const e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const i=this._uniformLocationPointer-e;for(let e=0;e0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t?t*=i:t=t*i+(4-t)*i,s=[];for(let e=0;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(Zs._UpdatedUbosInFrame[this._name]||(Zs._UpdatedUbosInFrame[this._name]=0),Zs._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.trackUbosInFrame;else this.create()}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let s=this._uniformLocations[e];if(void 0===s){if(this._buffer)return void Ne.Error("Cannot add an uniform after UBO has been created. uniformName="+e);this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e0)return void(this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label));Ne.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,s=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,s?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),this._data=0===t&&void 0===i?e:null)}_increaseReferences(){this._buffer&&(this._isAlreadyOwned?this._buffer.references++:this._isAlreadyOwned=!0)}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class er{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,s,r,n,o,a,l,h,c=!1,u=!1,d=1,_=!1){this._isDisposed=!1;let p=!1;if(this.engine=e,"object"==typeof s&&null!==s?(p=s.updatable??!1,r=s.postponeInternalCreation,n=s.stride,o=s.instanced,a=s.offset,l=s.size,h=s.type,c=s.normalized??!1,u=s.useBytes??!1,d=s.divisor??1,_=s.takeBufferOwnership??!1,this._label=s.label):p=!!s,t instanceof Js?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new Js(e,t,p,n,r,o,u,d,this._label),this._ownsBuffer=!0),this.uniqueId=er._Counter++,this._kind=i,void 0===h){const e=this.getData();this.type=e?er.GetDataType(e):er.FLOAT}else this.type=h;const f=er.GetTypeByteLength(this.type);u?(this._size=l||(n?n/f:er.DeduceStride(i)),this.byteStride=n||this._buffer.byteStride||this._size*f,this.byteOffset=a||0):(this._size=l||n||er.DeduceStride(i),this.byteStride=n?n*f:this._buffer.byteStride||this._size*f,this.byteOffset=(a||0)*f),this.normalized=c,this._instanced=void 0!==o&&o,this._instanceDivisor=o?d:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120|0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){this._buffer?._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?er.GetFloatData(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/er.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/er.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*er.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){er.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case er.UVKind:case er.UV2Kind:case er.UV3Kind:case er.UV4Kind:case er.UV5Kind:case er.UV6Kind:return 2;case er.NormalKind:case er.PositionKind:return 3;case er.ColorKind:case er.ColorInstanceKind:case er.MatricesIndicesKind:case er.MatricesIndicesExtraKind:case er.MatricesWeightsKind:case er.MatricesWeightsExtraKind:case er.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?er.BYTE:e instanceof Uint8Array?er.UNSIGNED_BYTE:e instanceof Int16Array?er.SHORT:e instanceof Uint16Array?er.UNSIGNED_SHORT:e instanceof Int32Array?er.INT:e instanceof Uint32Array?er.UNSIGNED_INT:er.FLOAT}static GetTypeByteLength(e){switch(e){case er.BYTE:case er.UNSIGNED_BYTE:return 1;case er.SHORT:case er.UNSIGNED_SHORT:return 2;case er.INT:case er.UNSIGNED_INT:case er.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,s,r,n,o,a){if(e instanceof Array){let r=t/4;const o=i/4;for(let t=0;to[t]=e)),o}if(!(e instanceof Array||e instanceof Float32Array)||0!==s||e.length!==h){if(e instanceof Array){const t=s/4;return e.slice(t,t+h)}if(e instanceof ArrayBuffer)return new Float32Array(e,s,h);{let t=e.byteOffset+s;if(a){const i=new Float32Array(h),s=new Float32Array(e.buffer,t,h);return i.set(s),i}const i=t%4;return i&&(t=Math.max(0,t-i)),new Float32Array(e.buffer,t,h)}}return a?e.slice():e}}er._Counter=0,er.BYTE=5120,er.UNSIGNED_BYTE=5121,er.SHORT=5122,er.UNSIGNED_SHORT=5123,er.INT=5124,er.UNSIGNED_INT=5125,er.FLOAT=5126,er.PositionKind="position",er.NormalKind="normal",er.TangentKind="tangent",er.UVKind="uv",er.UV2Kind="uv2",er.UV3Kind="uv3",er.UV4Kind="uv4",er.UV5Kind="uv5",er.UV6Kind="uv6",er.ColorKind="color",er.ColorInstanceKind="instanceColor",er.MatricesIndicesKind="matricesIndices",er.MatricesWeightsKind="matricesWeights",er.MatricesIndicesExtraKind="matricesIndicesExtra",er.MatricesWeightsExtraKind="matricesWeightsExtra";class tr{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(er.NormalKind))return null;let i,s=this.pickedMesh.getIndices();0===s?.length&&(s=null);const r=ve.Vector3[0],n=ve.Vector3[1],o=ve.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(er.NormalKind);let t=s?_e.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),a=s?_e.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=s?_e.FromArrayToRef(e,3*s[3*this.faceId+2],o):o.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]);t=t.scale(this.bu),a=a.scale(this.bv),l=l.scale(1-this.bu-this.bv),i=new _e(t.x+a.x+l.x,t.y+a.y+l.y,t.z+a.z+l.z)}else{const e=this.pickedMesh.getVerticesData(er.PositionKind),t=s?_e.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),a=s?_e.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=s?_e.FromArrayToRef(e,3*s[3*this.faceId+2],o):o.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),h=t.subtract(a),c=l.subtract(a);i=_e.Cross(h,c)}const a=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(ve.Matrix[0].copyFrom(i),i=ve.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(ve.Matrix[1]),i=ve.Matrix[1]),_e.TransformNormalToRef(t,i,t)};if(e&&a(this.pickedMesh,i),this.ray){const t=ve.Vector3[0].copyFrom(i);e||a(this.pickedMesh,t),_e.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=er.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const i=this.pickedMesh.getVerticesData(e);if(!i)return null;let s=de.FromArray(i,2*t[3*this.faceId]),r=de.FromArray(i,2*t[3*this.faceId+1]),n=de.FromArray(i,2*t[3*this.faceId+2]);return s=s.scale(this.bu),r=r.scale(this.bv),n=n.scale(1-this.bu-this.bv),new de(s.x+r.x+n.x,s.y+r.y+n.y)}}class ir{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[er.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[er.PositionKind]=new er(this._scene.getEngine(),e,er.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}_rebuild(){const e=this._vertexBuffers[er.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!(!i||!(t=t||i._postProcesses.filter((e=>null!=e)))||0===t.length||!this._scene.postProcessesEnabled||(t[0].activate(i,e,null!=t),0))}directRender(e,t=null,i=!1,s=0,r=0,n=!1){const o=this._scene.getEngine();for(let a=0;anull!=e))).length||!this._scene.postProcessesEnabled)return;const o=this._scene.getEngine();for(let a=0,l=s.length;at._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),s=t.getMesh();return i.material&&s.material?i.material.uniqueId-s.material.uniqueId:i.uniqueId-s.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t.isEnabled()&&t.isVisible&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(0===this._particleSystems.length)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i=mr.LeftClick&&i<=mr.RightClick&&(a.type=1===s?"pointerdown":"pointerup",a.button=i-2),a}static _CreateWheelEvent(e,t,i,s,r,n){const o=this._CreateMouseEvent(e,t,i,s,r,n);switch(o.pointerId=1,o.type="wheel",o.deltaMode=Sr.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case mr.MouseWheelX:o.deltaX=s;break;case mr.MouseWheelY:o.deltaY=s;break;case mr.MouseWheelZ:o.deltaZ=s}return o}static _CreateMouseEvent(e,t,i,s,r,n){const o=this._CreateEvent(n),a=r.pollInput(e,t,mr.Horizontal),l=r.pollInput(e,t,mr.Vertical);return n?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-n.getBoundingClientRect().x,o.offsetY=o.movementY-n.getBoundingClientRect().y):(o.movementX=r.pollInput(e,t,gr.DeltaHorizontal),o.movementY=r.pollInput(e,t,gr.DeltaVertical),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,r),o.clientX=a,o.clientY=l,o.x=a,o.y=l,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=fr.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=1===t?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(fr.Keyboard),s=i&&1===t.pollInput(fr.Keyboard,0,18),r=i&&1===t.pollInput(fr.Keyboard,0,17),n=i&&(1===t.pollInput(fr.Keyboard,0,91)||1===t.pollInput(fr.Keyboard,0,92)||1===t.pollInput(fr.Keyboard,0,93)),o=i&&1===t.pollInput(fr.Keyboard,0,16);e.altKey=s,e.ctrlKey=r,e.metaKey=n,e.shiftKey=o}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class Er{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,s,r)=>{const n=Cr.CreateDeviceEvent(e,t,s,r,this);i(e,t,n)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===fr.Mouse||e===fr.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const Ar=Object.keys(mr).length/2;class Pr{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Ds.IsSafari(),this._usingMacOS=Vt()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=e=>{},this._keyboardUpEvent=e=>{},this._keyboardBlurEvent=e=>{},this._pointerMoveEvent=e=>{},this._pointerDownEvent=e=>{},this._pointerUpEvent=e=>{},this._pointerCancelEvent=e=>{},this._pointerWheelEvent=e=>{},this._pointerBlurEvent=e=>{},this._pointerMacOSChromeOutEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=Vt()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=Vt()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=Ds.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=s,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){const s=this._inputs[e][t];if(!s)throw`Unable to find device ${fr[e]}`;e>=fr.DualShock&&e<=fr.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(void 0===r)throw`Unable to find input ${i} for device ${fr[e]} in slot ${t}`;return i===mr.Move&&Ds.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this?._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(const e of this._inputs)if(e)for(const t in e){const i=e[+t];if(i)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(fr.Keyboard,0,255));const t=this._inputs[fr.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(fr.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(fr.Keyboard,0,255));const t=this._inputs[fr.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const i=Cr.CreateDeviceEvent(fr.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(fr.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(fr.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[fr.Keyboard][0];for(let t=0;t{const t=this._getPointerType(e);let i=t===fr.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===fr.Touch&&-1===i){const s=this._activeTouchIds.indexOf(-1);if(!(s>=0))return void Ds.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=s,this._activeTouchIds[s]=e.pointerId,this._onDeviceConnected(t,i)}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=e;r.inputIndex=mr.Move,s[mr.Horizontal]=e.clientX,s[mr.Vertical]=e.clientY,t===fr.Touch&&0===s[mr.LeftClick]&&(s[mr.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,r),this._usingSafari||-1===e.button||(r.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,r))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===fr.Mouse?0:e.pointerId;if(t===fr.Touch){let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t&&(t=this._activeTouchIds.indexOf(-1)),!(t>=0))return void Ds.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=t,this._activeTouchIds[t]=e.pointerId}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===fr.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=s[mr.Horizontal],n=s[mr.Vertical];if(t===fr.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}s[mr.Horizontal]=e.clientX,s[mr.Vertical]=e.clientY,s[e.button+2]=1;const o=e;o.inputIndex=e.button+2,this._onInputChanged(t,i,o),r===e.clientX&&n===e.clientY||(o.inputIndex=mr.Move,this._onInputChanged(t,i,o))}},this._pointerUpEvent=e=>{const t=this._getPointerType(e),i=t===fr.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===fr.Touch){if(-1===i)return;this._activeTouchIds[i]=-1}const s=this._inputs[t]?.[i];if(s&&0!==s[e.button+2]){const r=s[mr.Horizontal],n=s[mr.Vertical];s[mr.Horizontal]=e.clientX,s[mr.Vertical]=e.clientY,s[e.button+2]=0;const o=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),r===e.clientX&&n===e.clientY||(o.inputIndex=mr.Move,this._onInputChanged(t,i,o)),o.inputIndex=e.button+2,t===fr.Mouse&&this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(t,i,o),t===fr.Touch&&this._onDeviceDisconnected(t,i)}},this._pointerCancelEvent=e=>{if("mouse"===e.pointerType){const e=this._inputs[fr.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=mr.LeftClick;t<=mr.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=Cr.CreateDeviceEvent(fr.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(fr.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[fr.Touch][t][mr.LeftClick]=0;const i=Cr.CreateDeviceEvent(fr.Touch,t,mr.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(fr.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(fr.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1;const t=function(){};try{const i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch(e){}this._pointerBlurEvent=()=>{if(this.isDeviceAvailable(fr.Mouse)){const e=this._inputs[fr.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=mr.LeftClick;t<=mr.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=Cr.CreateDeviceEvent(fr.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(fr.Mouse,0,i)}}if(this.isDeviceAvailable(fr.Touch)){const e=this._inputs[fr.Touch];for(let t=0;t{const t=fr.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,Ar));const i=this._inputs[t][0];if(i){i[mr.MouseWheelX]=e.deltaX||0,i[mr.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[mr.MouseWheelZ]=e.deltaZ||0;const s=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[mr.MouseWheelX]&&(s.inputIndex=mr.MouseWheelX,this._onInputChanged(t,0,s)),0!==i[mr.MouseWheelY]&&(s.inputIndex=mr.MouseWheelY,this._onInputChanged(t,0,s)),0!==i[mr.MouseWheelZ]&&(s.inputIndex=mr.MouseWheelZ,this._onInputChanged(t,0,s))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=e=>{e.buttons>1&&this._pointerCancelEvent(e)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,!!e&&{passive:!1}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add((()=>{if(this.isDeviceAvailable(fr.Mouse)){const e=this._inputs[fr.Mouse][0];e[mr.MouseWheelX]=0,e[mr.MouseWheelY]=0,e[mr.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const s=navigator.getGamepads()[t];if(s&&e===this._gamepads[t]){const r=this._inputs[e][t];i>=s.buttons.length?r[i]=s.axes[i-s.buttons.length].valueOf():r[i]=s.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?fr.DualSense:fr.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?fr.Xbox:-1!==e.indexOf("057e")?fr.Switch:fr.Generic}_getPointerType(e){let t=fr.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=fr.Touch),t}}class Ir{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new K,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class Rr{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(fr).length/2;this._devices=new Array(t);const i=(e,t)=>{this._devices[e]||(this._devices[e]=new Array),this._devices[e][t]||(this._devices[e][t]=t);for(const i of this._registeredManagers){const s=new Ir(this._deviceInputSystem,e,t);i._addDevice(s)}},s=(e,t)=>{this._devices[e]?.[t]&&delete this._devices[e][t];for(const i of this._registeredManagers)i._removeDevice(e,t)},r=(e,t,i)=>{if(i)for(const s of this._registeredManagers)s._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new Er(i,s,r):this._deviceInputSystem=new Pr(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class Mr{getDeviceSource(e,t){if(void 0===t){if(void 0===this._firstDevice[e])return null;t=this._firstDevice[e]}return this._devices[e]&&void 0!==this._devices[e][t]?this._devices[e][t]:null}getDeviceSources(e){return this._devices[e]?this._devices[e].filter((e=>!!e)):[]}constructor(e){const t=Object.keys(fr).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new Rr(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new K((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new K,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){const i=this._devices[e]?.[t];this.onDeviceDisconnectedObservable.notifyObservers(i),this._devices[e]?.[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){this._devices[e]?.[t]?.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case fr.Keyboard:case fr.Mouse:this._firstDevice[e]=0;break;case fr.Touch:case fr.DualSense:case fr.DualShock:case fr.Xbox:case fr.Switch:case fr.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i=mr.MouseWheelX&&t.inputIndex<=mr.MouseWheelZ?lr.POINTERWHEEL:lr.POINTERMOVE;let o;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n)),e?(o=new ur(n,t,e),this._setRayOnPointerInfo(e,t)):(o=new ur(n,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,me.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const s=this._scene,r=new cr(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,"xr-near"===t.pointerType&&e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const s=i.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(s.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=mr.Move,this._checkPrePointerObservable(e,i,lr.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,lr.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const s=e.pickedMesh._getActionManagerForTrigger();if(s){if(s.hasPickTriggers)switch(s.processTrigger(5,Re.CreateNew(e.pickedMesh,t,e)),t.button){case 0:s.processTrigger(2,Re.CreateNew(e.pickedMesh,t,e));break;case 1:s.processTrigger(4,Re.CreateNew(e.pickedMesh,t,e));break;case 2:s.processTrigger(3,Re.CreateNew(e.pickedMesh,t,e))}s.hasSpecificTrigger(8)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);e?.pickedMesh&&s&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>Dr.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,s.processTrigger(8,Re.CreateNew(e.pickedMesh,t)))}),Dr.LongPressDelay)}}else for(const s of i._pointerDownStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=lr.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new ur(r,t,e),this._setRayOnPointerInfo(e,t)):s=new ur(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=mr.Move;const r=new Or;i?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,s,lr.POINTERUP)||this._processPointerUp(e,s,r)}_processPointerUp(e,t,i){const s=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){const i=lr.POINTERPICK,r=new ur(i,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,i)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,Re.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,Re.CreateNew(e.pickedMesh,t,e));const s=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&s&&s.processTrigger(6,Re.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,Re.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new ur(lr.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,lr.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,lr.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(i.singleClick?r=lr.POINTERTAP:i.doubleClick&&(r=lr.POINTERDOUBLETAP),r){const i=new ur(r,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(r)&&s.onPointerObservable.notifyObservers(i,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const r=this._scene,n=r.getEngine();s||(s=n.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new Mr(n),this._initActionManager=e=>{if(!this._meshPickProceed){const t=r.skipPointerUpPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers,r.pointerUpTrianglePredicate);this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>Dr.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){const t=this._delayedClicks[e].evt,i=lr.POINTERTAP,s=new ur(i,t,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(i)&&r.onPointerObservable.notifyObservers(s,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,s)=>{const r=new Or;this._currentPickResult=null;let n=null,o=e.hasSpecificMask(lr.POINTERPICK)||t.hasSpecificMask(lr.POINTERPICK)||e.hasSpecificMask(lr.POINTERTAP)||t.hasSpecificMask(lr.POINTERTAP)||e.hasSpecificMask(lr.POINTERDOUBLETAP)||t.hasSpecificMask(lr.POINTERDOUBLETAP);!o&&Y&&(n=this._initActionManager(n,r),n&&(o=n.hasPickTriggers));let a=!1;if(o){const o=i.button;if(r.hasSwiped=this._isPointerSwiping(),!r.hasSwiped){let l=!Dr.ExclusiveDoubleClickMode;if(l||(l=!e.hasSpecificMask(lr.POINTERDOUBLETAP)&&!t.hasSpecificMask(lr.POINTERDOUBLETAP),l&&!Y.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(l=!n.hasSpecificTrigger(6)))),l)(Date.now()-this._previousStartingPointerTime>Dr.DoubleClickDelay||o!==this._previousButtonPressed)&&(r.singleClick=!0,s(r,this._currentPickResult),a=!0);else{const e={evt:i,clickInfo:r,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,o,r,s),Dr.DoubleClickDelay)};this._delayedClicks[o]=e}let h=e.hasSpecificMask(lr.POINTERDOUBLETAP)||t.hasSpecificMask(lr.POINTERDOUBLETAP);!h&&Y.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(h=n.hasSpecificTrigger(6))),h&&(o===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>Dr.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>Dr.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=mr.MouseWheelX&&e.inputIndex<=mr.MouseWheelZ?lr.POINTERWHEEL:lr.POINTERMOVE))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking)return void this._processPointerMove(new tr,e);r.pointerMovePredicate||(r.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask)));const t=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,Dr.ExclusiveDoubleClickMode)for(let t=0;te.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,t=r.skipPointerDownPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerDown?new tr:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers,r.pointerDownTrianglePredicate),this._processPointerDown(t,e)},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),r.preventDefaultOnPointerUp&&s&&(e.preventDefault(),s.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,e,((t,i)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,lr.POINTERUP))return this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),void(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1));t.hasSwiped||(t.singleClick&&r.onPrePointerObservable.hasSpecificMask(lr.POINTERTAP)&&this._checkPrePointerObservable(null,e,lr.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&r.onPrePointerObservable.hasSpecificMask(lr.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,lr.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(r.cameraToUseForPointers||r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(Y&&Y.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))):this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1)})))},this._onKeyDown=e=>{const t=dr.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const i=new pr(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new _r(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(14,Re.CreateNewFromScene(r,e))},this._onKeyUp=e=>{const t=dr.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const i=new pr(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new _r(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(15,Re.CreateNewFromScene(r,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((s=>{s.deviceType===fr.Mouse?s.onInputChangedObservable.add((r=>{this._originMouseEvent=r,r.inputIndex===mr.LeftClick||r.inputIndex===mr.MiddleClick||r.inputIndex===mr.RightClick||r.inputIndex===mr.BrowserBack||r.inputIndex===mr.BrowserForward?t&&1===s.getInput(r.inputIndex)?this._onPointerDown(r):e&&0===s.getInput(r.inputIndex)&&this._onPointerUp(r):i&&(r.inputIndex===mr.Move?this._onPointerMove(r):r.inputIndex!==mr.MouseWheelX&&r.inputIndex!==mr.MouseWheelY&&r.inputIndex!==mr.MouseWheelZ||this._onPointerMove(r))})):s.deviceType===fr.Touch?s.onInputChangedObservable.add((r=>{r.inputIndex===mr.LeftClick&&(t&&1===s.getInput(r.inputIndex)?(this._onPointerDown(r),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===s.getInput(r.inputIndex)&&(this._onPointerUp(r),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&r.inputIndex===mr.Move&&this._onPointerMove(r)})):s.deviceType===fr.Keyboard&&s.onInputChangedObservable.add((e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)}))})),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,s){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const r=this._meshUnderPointerId[t];let n;r&&(n=r._getActionManagerForTrigger(10),n&&n.processTrigger(10,Re.CreateNew(r,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,Re.CreateNew(e,s,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(const t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}Dr.DragMovementThreshold=10,Dr.LongPressDelay=500,Dr.DoubleClickDelay=300,Dr.ExclusiveDoubleClickMode=!1;class wr{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){wr.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){wr.Enabled&&(this._startMonitoringTime=Wt.Now)}endMonitoring(e=!0){if(!wr.Enabled)return;e&&this.fetchNewFrame();const t=Wt.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;const e=Wt.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}wr.Enabled=!0;class Nr{constructor(e,t,i,s){this.normal=new _e(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new Nr(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^this.d,e}normalize(){const e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z);let t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=Nr._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,o=this.d,a=s*i[0]+r*i[1]+n*i[2]+o*i[3],l=s*i[4]+r*i[5]+n*i[6]+o*i[7],h=s*i[8]+r*i[9]+n*i[10]+o*i[11],c=s*i[12]+r*i[13]+n*i[14]+o*i[15];return new Nr(a,l,h,c)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const s=t.x-e.x,r=t.y-e.y,n=t.z-e.z,o=i.x-e.x,a=i.y-e.y,l=i.z-e.z,h=r*l-n*a,c=n*o-s*l,u=s*a-r*o,d=Math.sqrt(h*h+c*c+u*u);let _;return _=0!==d?1/d:0,this.normal.x=h*_,this.normal.y=c*_,this.normal.z=u*_,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return _e.Dot(this.normal,e)<=t}signedDistanceTo(e){return _e.Dot(e,this.normal)+this.d}static FromArray(e){return new Nr(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new Nr(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new Nr(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return _e.Dot(i,t)+s}}Nr._TmpMatrix=me.Identity();class Fr{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new Nr(0,0,0,0));return Fr.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){Fr.GetNearPlaneToRef(e,t[0]),Fr.GetFarPlaneToRef(e,t[1]),Fr.GetLeftPlaneToRef(e,t[2]),Fr.GetRightPlaneToRef(e,t[3]),Fr.GetTopPlaneToRef(e,t[4]),Fr.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}class Lr{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}Lr._UniqueIdCounter=1;class Br{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}Br.FALLOFF_DEFAULT=0,Br.FALLOFF_PHYSICAL=1,Br.FALLOFF_GLTF=2,Br.FALLOFF_STANDARD=3,Br.LIGHTMAP_DEFAULT=0,Br.LIGHTMAP_SPECULAR=1,Br.LIGHTMAP_SHADOWSONLY=2,Br.INTENSITYMODE_AUTOMATIC=0,Br.INTENSITYMODE_LUMINOUSPOWER=1,Br.INTENSITYMODE_LUMINOUSINTENSITY=2,Br.INTENSITYMODE_ILLUMINANCE=3,Br.INTENSITYMODE_LUMINANCE=4,Br.LIGHTTYPEID_POINTLIGHT=0,Br.LIGHTTYPEID_DIRECTIONALLIGHT=1,Br.LIGHTTYPEID_SPOTLIGHT=2,Br.LIGHTTYPEID_HEMISPHERICLIGHT=3;class kr{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var Vr,Ur,Gr,zr,Wr;!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(Vr||(Vr={}));class Hr extends X{static DefaultMaterialFactory(e){throw xt("StandardMaterial")}static CollisionCoordinatorFactory(){throw xt("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case Vr.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case Vr.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case Vr.Aggressive:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return Dr.DragMovementThreshold}static set DragMovementThreshold(e){Dr.DragMovementThreshold=e}static get LongPressDelay(){return Dr.LongPressDelay}static set LongPressDelay(e){Dr.LongPressDelay=e}static get DoubleClickDelay(){return Dr.DoubleClickDelay}static set DoubleClickDelay(e){Dr.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return Dr.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){Dr.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const s=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return ve.Vector4[0].set(s.x,s.y,s.z,r?-1:1),e&&(i?e.setFloat3(t,ve.Vector4[0].x,ve.Vector4[0].y,ve.Vector4[0].z):e.setVector4(t,ve.Vector4[0])),ve.Vector4[0]}finalizeSceneUbo(){const e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=ie(e,(()=>{this.onActiveCamerasChanged.notifyObservers(this)}))),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=Hr.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=Hr.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new Dr(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new Ae(.2,.2,.3,1),this.ambientColor=new Ee(0,0,0),this.environmentIntensity=1,this._performancePriority=Vr.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new K,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new K,this._onDisposeObserver=null,this.onBeforeRenderObservable=new K,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new K,this.onAfterRenderCameraObservable=new K,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new K,this.onAfterAnimationsObservable=new K,this.onBeforeDrawPhaseObservable=new K,this.onAfterDrawPhaseObservable=new K,this.onReadyObservable=new K,this.onBeforeCameraRenderObservable=new K,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new K,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new K,this.onAfterActiveMeshesEvaluationObservable=new K,this.onBeforeParticlesRenderingObservable=new K,this.onAfterParticlesRenderingObservable=new K,this.onDataLoadedObservable=new K,this.onNewCameraAddedObservable=new K,this.onCameraRemovedObservable=new K,this.onNewLightAddedObservable=new K,this.onLightRemovedObservable=new K,this.onNewGeometryAddedObservable=new K,this.onGeometryRemovedObservable=new K,this.onNewTransformNodeAddedObservable=new K,this.onTransformNodeRemovedObservable=new K,this.onNewMeshAddedObservable=new K,this.onMeshRemovedObservable=new K,this.onNewSkeletonAddedObservable=new K,this.onSkeletonRemovedObservable=new K,this.onNewMaterialAddedObservable=new K,this.onNewMultiMaterialAddedObservable=new K,this.onMaterialRemovedObservable=new K,this.onMultiMaterialRemovedObservable=new K,this.onNewTextureAddedObservable=new K,this.onTextureRemovedObservable=new K,this.onBeforeRenderTargetsRenderObservable=new K,this.onAfterRenderTargetsRenderObservable=new K,this.onBeforeStepObservable=new K,this.onAfterStepObservable=new K,this.onActiveCameraChanged=new K,this.onActiveCamerasChanged=new K,this.onBeforeRenderingGroupObservable=new K,this.onAfterRenderingGroupObservable=new K,this.onMeshImportedObservable=new K,this.onAnimationFileImportedObservable=new K,this._registeredForLateAnimationBindings=new Ls(256),this._pointerPickingConfiguration=new kr,this.onPrePointerObservable=new K,this.onPointerObservable=new K,this.onPreKeyboardObservable=new K,this.onKeyboardObservable=new K,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=Hr.FOGMODE_NONE,this.fogColor=new Ee(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new _e(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new Ls(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new wr,this._activeIndices=new wr,this._activeParticles=new wr,this._activeBones=new wr,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=new Array(256),this._activeRequests=new Array,this._pendingData=new Array,this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new Fs(256),this._processedMaterials=new Fs(256),this._renderTargets=new Ls(256),this._materialsRenderTargets=new Ls(256),this._activeParticleSystems=new Fs(256),this._activeSkeletons=new Ls(32),this._softwareSkinnedMeshes=new Ls(32),this._activeAnimatables=new Array,this._transformMatrix=me.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=ar.Create(),this._beforeClearStage=ar.Create(),this._beforeRenderTargetClearStage=ar.Create(),this._gatherRenderTargetsStage=ar.Create(),this._gatherActiveCameraRenderTargetsStage=ar.Create(),this._isReadyForMeshStage=ar.Create(),this._beforeEvaluateActiveMeshStage=ar.Create(),this._evaluateSubMeshStage=ar.Create(),this._preActiveMeshStage=ar.Create(),this._cameraDrawRenderTargetStage=ar.Create(),this._beforeCameraDrawStage=ar.Create(),this._beforeRenderTargetDrawStage=ar.Create(),this._beforeRenderingGroupDrawStage=ar.Create(),this._beforeRenderingMeshStage=ar.Create(),this._afterRenderingMeshStage=ar.Create(),this._afterRenderingGroupDrawStage=ar.Create(),this._afterCameraDrawStage=ar.Create(),this._afterCameraPostProcessStage=ar.Create(),this._afterRenderTargetDrawStage=ar.Create(),this._afterRenderTargetPostProcessStage=ar.Create(),this._afterRenderStage=ar.Create(),this._pointerMoveStage=ar.Create(),this._pointerDownStage=ar.Create(),this._pointerUpStage=ar.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];const i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};e=this._engine=e||re.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(re._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new nr(this),ir&&(this.postProcessManager=new ir(this)),kt()&&this.attachControl(),this._createUbo(),zs&&(this._imageProcessingConfiguration=new zs),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,t&&t.virtual||e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return void 0!==this._animationRatio?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){if(this._isDisposed)return!1;let t;const i=this.getEngine(),s=i.currentRenderPassId;i.currentRenderPassId=this.activeCamera?.renderPassId??s;let r=!0;for(this._pendingData.length>0&&(r=!1),this.prePassRenderer?.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&r&&(r=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const e of this._isReadyForMeshStage)e.action(s,n)||(r=!1);if(!e)continue;const o=s.material||this.defaultMaterial;if(o)if(o._storeEffectOnSubMeshes)for(const e of s.subMeshes){const t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else o.hasRenderTargetTextures&&null!=o.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(o)&&(this._processedMaterials.push(o),this._materialsRenderTargets.concatWithNoDuplicate(o.getRenderTargetTextures()))}if(e)for(t=0;t0)for(const e of this.activeCameras)e.isReady(!0)||(r=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(r=!1));for(const e of this.particleSystems)e.isReady()||(r=!1);if(this.layers)for(const e of this.layers)e.isReady()||(r=!1);return i.areAllEffectsReady()||(r=!1),i.currentRenderPassId=s,r}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout((()=>{this.unregisterBeforeRender(t)}))};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){void 0!==t?setTimeout((()=>{this._executeOnceBeforeRender(e)}),t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){const t=this.isLoading,i=this._pendingData.indexOf(e);-1!==i&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise((t=>{this.executeWhenReady((()=>{t()}),e)}))}_checkIsReady(e=!1){return this._registerTransientComponents(),this.isReady(e)?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):void(this._executeWhenReadyTimeoutId=setTimeout((()=>{this.incrementRenderId(),this._checkIsReady(e)}),100))}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=Wt.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,s){i||s||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?Fr.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Fr.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,s):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new Zs(this._engine,void 0,!1,e??"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return Lr.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.addMesh(e)})))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return-1!==i&&(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.removeMesh(e)})),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){const e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){const t=this.skeletons.indexOf(e);return-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(-1!==t){for(const t of this.meshes)t._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t}removeCamera(e){const t=this.cameras.indexOf(e);if(-1!==t&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){const t=this.particleSystems.indexOf(e);return-1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(-1!==t&&tt.uniqueId===e))}getMaterialById(e,t=!1){return this._getMaterial(t,(t=>t.id===e))}getMaterialByName(e,t=!1){return this._getMaterial(t,(t=>t.name===e))}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t)for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t];return null}getTextureByUniqueId(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const s=this.getLightById(e);if(s)return s;const r=this.getCameraById(e);if(r)return r;return this.getBoneById(e)||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const s=this.getLightByName(e);if(s)return s;const r=this.getCameraByName(e);if(r)return r;return this.getBoneByName(e)||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(this.activeCamera){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,s)for(let e=0;ee.dispose()))}_evaluateActiveMeshes(){if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode)return void(this._activeMeshes.length>0&&(this.activeCamera?._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset()));if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const e=this._activeMeshes.length;for(let t=0;t0&&t.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||t.alwaysSelectAsActiveMesh||t.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(t),this.activeCamera._activeMeshes.push(t),s!==t&&s._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(t);t._activate(this._renderId,!1)&&(t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(s=t):s._internalAbstractMeshDataInfo._onlyForInstances=!1,s._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(t,s)),t._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e0){const s=this.getActiveSubMeshCandidates(t),r=s.length;i=i||1===r;for(let n=0;n0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const e of this._gatherActiveCameraRenderTargetsStage)e.action(this._renderTargets);let r=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Ds.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e0),this._renderId++}for(const e of this._cameraDrawRenderTargetStage)r=e.action(this.activeCamera)||r;this._intermediateRendering=!1}this._engine.currentRenderPassId=e.outputRenderTarget?.renderPassId??e.renderPassId??0,r&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame();for(const e of this._beforeCameraDrawStage)e.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),s.snapshotRendering&&1===s.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const e of this._afterCameraDrawStage)e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(const e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview)return e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t-1&&(13===i.trigger&&i._executeCurrent(Re.CreateNew(t,void 0,s)),t.actionManager.hasSpecificTrigger(13,(e=>{const t=e.mesh?e.mesh:e;return s===t}))&&13!==i.trigger||t._intersectionsInProgress.splice(n,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(Hr.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Hr.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&s0)for(let e=0;e0),this._intermediateRendering=!0;for(let e=0;e0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=s?.renderPassId??0,this.activeCamera=s,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const e of this._beforeClearStage)e.action();this._clearFrameBuffer(this.activeCamera);for(const e of this._gatherRenderTargetsStage)e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const e of this._afterRenderStage)e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e{e.onAnimationEndObservable.clear(),e.onAnimationEnd=null})),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;const e=this._activeRequests.slice();for(const t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){Ne.Error("An error occurred while calling onDisposeObservable!",e)}if(this.detachControl(),this._engine.getInputElement())for(let e=0;ee.dispose(!0))),this._disposeList(this.transformNodes,(e=>e.dispose(!0)));const t=this.cameras;this._disposeList(t),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),re._LastCreatedScene===this&&(this._engine.scenes.length>0?re._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:re._LastCreatedScene=null),i=this._engine._virtualScenes.indexOf(this),i>-1&&this._engine._virtualScenes.splice(i,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const i=e.slice(0);t=t??(e=>e.dispose());for(const e of i)t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach((e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;const s=e.getBoundingInfo(),r=s.boundingBox.minimumWorld,n=s.boundingBox.maximumWorld;_e.CheckExtends(r,t,i),_e.CheckExtends(n,t,i)})),{min:t,max:i}}createPickingRay(e,t,i,s,r=!1){throw xt("Ray")}createPickingRayToRef(e,t,i,s,r,n=!1,o=!1){throw xt("Ray")}createPickingRayInCameraSpace(e,t,i){throw xt("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw xt("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,r,n){const o=xt("Ray",!0);return o&&Ne.Warn(o),new tr}pickWithBoundingInfo(e,t,i,s,r){const n=xt("Ray",!0);return n&&Ne.Warn(n),new tr}pickWithRay(e,t,i,s){throw xt("Ray")}multiPick(e,t,i,s,r){throw xt("Ray")}multiPickWithRay(e,t,i){throw xt("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(void 0===t)return e;const s=[];for(const r in e){const n=e[r];Tt&&Tt.MatchesQuery(n,t)&&(!i||i(n))&&s.push(n)}return s}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,s)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,s,r,n,o){const a=ps(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_loadFileAsync(e,t,i,s,r){return new Promise(((n,o)=>{this._loadFile(e,(e=>{n(e)}),t,i,s,((e,t)=>{o(t)}),r)}))}_requestFile(e,t,i,s,r,n,o){const a=fs(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_requestFileAsync(e,t,i,s,r){return new Promise(((n,o)=>{this._requestFile(e,(e=>{n(e)}),t,i,s,(e=>{o(e)}),r)}))}_readFile(e,t,i,s,r){const n=_s(e,t,i,s,r);return this._activeRequests.push(n),n.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),n}_readFileAsync(e,t,i){return new Promise(((s,r)=>{this._readFile(e,(e=>{s(e)}),t,i,(e=>{r(e)}))}))}getPerfCollector(){throw xt("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}Hr.FOGMODE_NONE=0,Hr.FOGMODE_EXP=1,Hr.FOGMODE_EXP2=2,Hr.FOGMODE_LINEAR=3,Hr.MinDeltaTime=1,Hr.MaxDeltaTime=1e3,z("BABYLON.Scene",Hr),function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(Ur||(Ur={}));class Xr{}Xr.X=new _e(1,0,0),Xr.Y=new _e(0,1,0),Xr.Z=new _e(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Gr||(Gr={}));class Yr extends Et{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){(e.updateFlag!==this._localMatrix.updateFlag||this._needToCompose)&&(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,s=null,r=null,n=null,o=null){super(e,t.getScene(),!1),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=s?.clone()??me.Identity(),this._restMatrix=r??this._localMatrix.clone(),this._bindMatrix=n??this._localMatrix.clone(),this._index=o,this._absoluteMatrix=new me,this._absoluteBindMatrix=new me,this._absoluteInverseBindMatrix=new me,this._finalMatrix=new me,t.bones.push(this),this.setParent(i,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return null===this._index?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){const e=this.parent.children.indexOf(this);-1!==e&&this.parent.children.splice(e,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){if(this._linkedTransformNode){const e=ve.Vector3[0],t=ve.Quaternion[0],i=ve.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??fe.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(t),this._linkedTransformNode.scaling.copyFrom(e)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._absoluteMatrix}getAbsoluteTransform(){return this._absoluteMatrix}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=_e.Zero(),this._localRotation=fe.Zero(),this._localPosition=_e.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,me.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let e=0;e-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(r)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const r=this._runtimeAnimations;for(let i=r.length-1;i>=0;i--){const s=r[i];e&&s.animation.name!=e||t&&!t(s.target)||(s.dispose(),r.splice(i,1))}0==r.length&&(i||this._scene._activeAnimatables.splice(s,1),this._raiseOnAnimationEnd())}}else{const e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);const t=this._runtimeAnimations;for(let e=0;e{this.onAnimationEndObservable.add((()=>{e(this)}),void 0,void 0,this,!0)}))}_animate(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),null!==this._manualJumpDelay&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,0===this._weight)return!0;let t=!1;const i=this._runtimeAnimations;let s;for(s=0;s0)return;this._animationTimeLast=t}this.deltaTime=void 0!==e?e:this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=t;const i=this._activeAnimatables;if(0===i.length)return;this._animationTime+=this.deltaTime;const s=this._animationTime;for(let e=0;ee.playOrder-t.playOrder))},Hr.prototype.beginWeightedAnimation=function(e,t,i,s=1,r,n=1,o,a,l,h,c=!1){const u=this.beginAnimation(e,t,i,r,n,o,a,!1,l,h,c);return u.weight=s,u},Hr.prototype.beginAnimation=function(e,t,i,s,r=1,n,o,a=!0,l,h,c=!1){t>i&&r>0&&(r*=-1),a&&this.stopAnimation(e,void 0,l),o||(o=new Qr(this,e,t,i,s,r,n,void 0,h,c));const u=!l||l(e);if(e.animations&&u&&o.appendAnimations(e,e.animations),e.getAnimatables){const c=e.getAnimatables();for(let e=0;es&&n>0)n*=-1;else if(s>i&&n<0){const e=s;s=i,i=e}return new Qr(this,e,i,s,r,n,o,t,a,l)},Hr.prototype.beginDirectHierarchyAnimation=function(e,t,i,s,r,n,o,a,l,h=!1){const c=e.getDescendants(t),u=[];u.push(this.beginDirectAnimation(e,i,s,r,n,o,a,l,h));for(const e of c)u.push(this.beginDirectAnimation(e,i,s,r,n,o,a,l,h));return u},Hr.prototype.getAnimatableByTarget=function(e){for(let t=0;t0?l:-l,r),a.scaleAndAddToRef(l,i)}r.normalize()}for(let t=0;t0)r.copyFrom(s);else if(1===e.animations.length){if(fe.SlerpToRef(s,i.currentValue,Math.min(1,e.totalWeight),r),0===e.totalAdditiveWeight)return r}else if(e.animations.length>1){let i,n,o=1;if(e.totalWeight<1){const t=1-e.totalWeight;i=[],n=[],i.push(s),n.push(t)}else{if(2===e.animations.length&&(fe.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],n=[],o=e.totalWeight}for(let t=0;t=o&&m.frame<=a&&(s?(v=m.value.clone(),d?(g=v.getTranslation(),v.setTranslation(g.scaleInPlace(_))):p&&r?(g=v.getTranslation(),v.setTranslation(g.multiplyInPlace(r))):v=m.value):v=m.value,f.push({frame:m.frame+i,value:v}));return this.animations[0].createRange(t,o+i,a+i),!0};class jr{constructor(){this.enableBlending=!1,this.blendingSpeed=.01,this.loopMode=Ft.ANIMATIONLOOPMODE_CYCLE}}!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(zr||(zr={}));class Kr{static Interpolate(e,t,i,s,r){const n=1-3*s+3*t,o=3*s-6*t,a=3*t;let l=e;for(let t=0;t<5;t++){const t=l*l;l-=1/(3*n*t+2*o*l+a)*(n*(t*l)+o*t+a*l-e),l=Math.min(1,Math.max(0,l))}return 3*Math.pow(1-l,2)*l*i+3*(1-l)*Math.pow(l,2)*r+Math.pow(l,3)}}class $r{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return 180*this._radians/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),s=Math.atan2(i.y,i.x);return new $r(s)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(0===i)return new $r(Math.PI/2);i=Math.sqrt(i);let s=e.dot(t)/i;s=be.Clamp(s,-1,1);const r=Math.acos(s);return new $r(r)}static FromRadians(e){return new $r(e)}static FromDegrees(e){return new $r(e*Math.PI/180)}}class qr{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const s=Math.pow(t.x,2)+Math.pow(t.y,2),r=(Math.pow(e.x,2)+Math.pow(e.y,2)-s)/2,n=(s-Math.pow(i.x,2)-Math.pow(i.y,2))/2,o=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new de((r*(t.y-i.y)-n*(e.y-t.y))/o,((e.x-t.x)*n-(t.x-i.x)*r)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=$r.BetweenTwoPoints(this.centerPoint,this.startPoint);const a=this.startAngle.degrees();let l=$r.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=$r.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-a>180&&(l-=360),l-a<-180&&(l+=360),h-l>180&&(h-=360),h-l<-180&&(h+=360),this.orientation=l-a<0?zr.CW:zr.CCW,this.angle=$r.FromDegrees(this.orientation===zr.CW?a-h:h-a)}}class Zr{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new de(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new de(e,t),s=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(s).length(),this}addArcTo(e,t,i,s,r=36){if(this.closed)return this;const n=this._points[this._points.length-1],o=new de(e,t),a=new de(i,s),l=new qr(n,o,a);let h=l.angle.radians()/r;l.orientation===zr.CW&&(h*=-1);let c=l.startAngle.radians()+h;for(let e=0;e(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*s,o=this._points[this._points.length-1];for(let a=0;a<=r;a++){const l=a/r,h=n(l,o.x,e,i),c=n(l,o.y,t,s);this.addLineTo(h,c)}return this}addBezierCurveTo(e,t,i,s,r,n,o=36){if(this.closed)return this;const a=(e,t,i,s,r)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*s+e*e*e*r,l=this._points[this._points.length-1];for(let h=0;h<=o;h++){const c=h/o,u=a(c,l.x,e,i,r),d=a(c,l.y,t,s,n);this.addLineTo(u,d)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let s=i-1,r=0;rNumber.EPSILON){if(a<0&&(i=this._points[r],o=-o,n=this._points[s],a=-a),e.yn.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{const s=a*(e.x-i.x)-o*(e.y-i.y);if(0===s)return!0;if(s<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(n.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=n.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1];e+=this._points[0].subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,s=0;s1)return de.Zero();const t=e*this.length();let i=0;for(let e=0;e=i&&t<=o){const e=n.normalize(),s=t-i;return new de(r.x+e.x*s,r.y+e.y*s)}i=o}return de.Zero()}static StartingAt(e,t){return new Zr(e,t)}}class Jr{constructor(e,t=null,i,s=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:_e.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:me.Identity()};for(let t=0;tt){const i=e;e=t,t=i}const i=this.getCurve(),s=this.getPointAt(e);let r=this.getPreviousPointIndexAt(e);const n=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,a=[];return 0!==e&&(r++,a.push(s)),a.push(...i.slice(r,o)),1===t&&1!==e||a.push(n),new Jr(a,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;tt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,s=e.length();if(0===s&&(s=1),null==t){let t;t=be.WithinEpsilon(Math.abs(e.y)/s,1,J)?be.WithinEpsilon(Math.abs(e.x)/s,1,J)?be.WithinEpsilon(Math.abs(e.z)/s,1,J)?_e.Zero():new _e(0,0,1):new _e(1,0,0):new _e(0,-1,0),i=_e.Cross(e,t)}else i=_e.Cross(e,t),_e.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;const i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let s,r=i[0],n=0;const o=e*this.length();for(let a=1;ao){const i=(n-o)/l,h=r.subtract(s),c=s.add(h.scaleInPlace(i));return this._setPointAtData(e,1-i,c,a-1,t)}r=s}return this._pointAtData}_setPointAtData(e,t,i,s,r){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=s,this._pointAtData.interpolateReady=r,r&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=me.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),s=this._normals[e].clone(),r=this._binormals[e].clone(),n=this._tangents[t].clone(),o=this._normals[t].clone(),a=this._binormals[t].clone(),l=fe.RotationQuaternionFromAxis(s,r,i),h=fe.RotationQuaternionFromAxis(o,a,n);fe.Slerp(l,h,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class en{static CreateQuadraticBezier(e,t,i,s){s=s>2?s:3;const r=[],n=(e,t,i,s)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*s;for(let o=0;o<=s;o++)r.push(new _e(n(o/s,e.x,t.x,i.x),n(o/s,e.y,t.y,i.y),n(o/s,e.z,t.z,i.z)));return new en(r)}static CreateCubicBezier(e,t,i,s,r){r=r>3?r:4;const n=[],o=(e,t,i,s,r)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*s+e*e*e*r;for(let a=0;a<=r;a++)n.push(new _e(o(a/r,e.x,t.x,i.x,s.x),o(a/r,e.y,t.y,i.y,s.y),o(a/r,e.z,t.z,i.z,s.z)));return new en(n)}static CreateHermiteSpline(e,t,i,s,r){const n=[],o=1/r;for(let a=0;a<=r;a++)n.push(_e.Hermite(e,t,i,s,a*o));return new en(n)}static CreateCatmullRomSpline(e,t,i){const s=[],r=1/t;let n=0;if(i){const i=e.length;for(let o=0;o=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}tn.EASINGMODE_EASEIN=0,tn.EASINGMODE_EASEOUT=1,tn.EASINGMODE_EASEINOUT=2;class sn extends tn{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class rn extends tn{constructor(e=1){super(),this.amplitude=e}easeInCore(e){const t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}}class nn extends tn{constructor(e=3,t=2){super(),this.bounces=e,this.bounciness=t}easeInCore(e){const t=Math.max(0,this.bounces);let i=this.bounciness;i<=1&&(i=1.001);const s=Math.pow(i,t),r=1-i,n=(1-s)/r+.5*s,o=e*n,a=Math.log(-o*(1-i)+1)/Math.log(i),l=Math.floor(a),h=l+1,c=(1-Math.pow(i,l))/(r*n),u=.5*(c+(1-Math.pow(i,h))/(r*n)),d=e-u,_=u-c;return-Math.pow(1/i,t-l)/(_*_)*(d-_)*(d+_)}}class on extends tn{easeInCore(e){return e*e*e}}class an extends tn{constructor(e=3,t=3){super(),this.oscillations=e,this.springiness=t}easeInCore(e){let t;const i=Math.max(0,this.oscillations),s=Math.max(0,this.springiness);return t=0==s?e:(Math.exp(s*e)-1)/(Math.exp(s)-1),t*Math.sin((6.283185307179586*i+1.5707963267948966)*e)}}class ln extends tn{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}}class hn extends tn{constructor(e=2){super(),this.power=e}easeInCore(e){const t=Math.max(0,this.power);return Math.pow(e,t)}}class cn extends tn{easeInCore(e){return e*e}}class un extends tn{easeInCore(e){return e*e*e*e}}class dn extends tn{easeInCore(e){return e*e*e*e*e}}class _n extends tn{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class pn extends tn{constructor(e=0,t=0,i=1,s=1){super(),this.x1=e,this.y1=t,this.x2=i,this.y2=s}easeInCore(e){return Kr.Interpolate(e,this.x1,this.y1,this.x2,this.y2)}}class fn{constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new fn(this.frame,this.action,this.onlyOnce)}}class mn{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class gn{get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this.syncWithMask(!0))}syncWithMask(e=!1){if(this.mask||e){this._numActiveAnimatables=0;for(let e=0;e0)){for(let e=0;en&&(n=t.to);const o=new gn(e[0].name+"_merged",e[0]._scene,s);for(const s of e){i&&s.normalize(r,n);for(const e of s.targetedAnimations)o.addTargetedAnimation(e.animation,e.target);t&&s.dispose()}return o}constructor(e,t=null,i=-1,s=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._parentContainer=null,this.onAnimationEndObservable=new K,this.onAnimationLoopObservable=new K,this.onAnimationGroupLoopObservable=new K,this.onAnimationGroupEndObservable=new K,this.onAnimationGroupPauseObservable=new K,this.onAnimationGroupPlayObservable=new K,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||re.LastCreatedScene,this._weight=i,this._playOrder=s,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new mn;i.animation=e,i.target=t;const s=e.getKeys();return this._from>s[0].frame&&(this._from=s[0].frame),this._to-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;ie){const t={frame:e,value:r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation};s.splice(0,0,t)}if(n.frame{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,s,r){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(a)},this._processLoop(a,o,n),this._animatables.push(a)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e0&&(this._scene._activeAnimatables[t++]=i)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const e=this._parentContainer.animationGroups.indexOf(this);e>-1&&this._parentContainer.animationGroups.splice(e,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e){const t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const s=new gn(e||this.name,this._scene,this._weight,this._playOrder);s._from=this.from,s._to=this.to,s._speedRatio=this.speedRatio,s._loopAnimation=this.loopAnimation,s._isAdditive=this.isAdditive,s._enableBlending=this.enableBlending,s._blendingSpeed=this.blendingSpeed,s.metadata=this.metadata,s.mask=this.mask;for(const e of this._targetedAnimations)s.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return s}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;tr[0].frame&&(e=r[0].frame),t=t&&e<=i||r&&s.frame>=t&&s.frame<=i){const e={frame:s.frame,value:s.value.clone?s.value.clone():s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation,lockedTangent:s.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,u.push(e)}}0!==u.length?(n>u[0].frame&&(n=u[0].frame),o1)throw"step size should be less than 1.";return this.value+=e,this._ensureLimits(),this._raiseOnChange(),this}_ensureLimits(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this}_raiseOnChange(){return this._onchange.forEach((e=>e(this))),this}onchange(e){return this._onchange.push(e),this}}!function(e){e[e.Include=0]="Include",e[e.Exclude=1]="Exclude"}(Wr||(Wr={}));class xn{constructor(e,t=Wr.Include){this.mode=t,this.disabled=!1,this._targetNames=new Set,e&&this.addTargetName(e)}addTargetName(e){if(Array.isArray(e))for(const t of e)this._targetNames.add(t);else this._targetNames.add(e)}removeTargetName(e){if(Array.isArray(e))for(const t of e)this._targetNames.delete(t);else this._targetNames.delete(e)}hasTarget(e){return this._targetNames.has(e)}retainsTarget(e){return this._targetNames.has(e)===(this.mode===Wr.Include)}}function bn(e,t,i){try{const s=e.next();s.done?t(s):s.value?s.value.then((()=>{s.value=void 0,t(s)}),i):t(s)}catch(e){i(e)}}function Tn(e=25){let t;return(i,s,r)=>{const n=performance.now();void 0===t||n-t>e?(t=n,setTimeout((()=>{bn(i,s,r)}),0)):bn(i,s,r)}}function yn(e,t,i,s,r){const n=()=>{let o;const a=e=>{e.done?i(e.value):void 0===o?o=!0:n()};do{o=void 0,r&&r.aborted?s(new Error("Aborted")):t(e,a,s),void 0===o&&(o=!1)}while(o)};n()}function Sn(e,t){let i;return yn(e,bn,(e=>i=e),(e=>{throw e}),t),i}function Cn(e,t,i){return new Promise(((s,r)=>{yn(e,t,s,r,i)}))}function En(e,t){return(...i)=>Sn(e(...i),t)}function An(e,t,i){return(...s)=>Cn(e(...s),t,i)}class Pn{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new Pn(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new Pn(this.x,this.y,this.width,this.height)}}class In extends Et{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){let e=0,t=0;if(this.mode===In.PERSPECTIVE_CAMERA)this.fovMode===In.FOVMODE_VERTICAL_FIXED?(t=2*this.minZ*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=2*this.minZ*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const i=this.getEngine().getRenderWidth()/2,s=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??s)-(this.orthoBottom??-s)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,s=!0){super(e,i,!1),this._position=_e.Zero(),this._upVector=_e.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=In.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new Pn(0,0,1,1),this.layerMask=268435455,this.fovMode=In.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=In.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new K,this.onProjectionMatrixChangedObservable=new K,this.onAfterCheckInputsObservable=new K,this.onRestoreStateObservable=new K,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new me,this._postProcesses=new Array,this._activeMeshes=new Fs(256),this._globalPosition=_e.Zero(),this._computedViewMatrix=me.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=me.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=fe.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),s&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i-1?(Ne.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))}detachPostProcess(e){const t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()||this.getViewMatrix(),this._worldMatrix}_getViewMatrix(){return me.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix)),this._computedViewMatrix}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const t=this.getEngine(),i=this.getScene(),s=t.useReverseDepthBuffer;if(this.mode===In.PERSPECTIVE_CAMERA){let e;this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=t.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),e=i.useRightHandedSystem?me.PerspectiveFovRHToRef:me.PerspectiveFovLHToRef,e(this.fov,t.getAspectRatio(this),s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===In.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{const e=t.getRenderWidth()/2,r=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?me.ObliqueOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):me.OrthoOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?me.ObliqueOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):me.OrthoOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=this.oblique?.angle,this._cache.obliqueLength=this.oblique?.length,this._cache.obliqueOffset=this.oblique?.offset,this._cache.renderWidth=t.getRenderWidth(),this._cache.renderHeight=t.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){return(this.radius||(this.target?_e.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?Fr.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Fr.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;return this.rigCameras.forEach((i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)})),t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw xt("Ray")}getForwardRayToRef(e,t=100,i,s){throw xt("Ray")}dispose(e,t=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){const e=this._parentContainer.cameras.indexOf(this);e>-1&&this._parentContainer.cameras.splice(e,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==In.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){const t=this._postProcesses[e];t&&t.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),super.dispose(e,t)}get isLeftCamera(){return this._isLeftCamera}get isRightCamera(){return this._isRightCamera}get leftCamera(){return this._rigCameras.length<1?null:this._rigCameras[0]}get rightCamera(){return this._rigCameras.length<2?null:this._rigCameras[1]}getLeftTarget(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()}getRightTarget(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()}setCameraRigMode(e,t){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=Ds.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==In.RIG_MODE_NONE){const e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);const t=this.createRigCamera(this.name+"_R",1);t&&(t._isRightCamera=!0),e&&t&&(this._rigCameras.push(e),this._rigCameras.push(t))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return me.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=Ds.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eIn._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=In.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=St.Parse(s,e,t);if(void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=_e.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(_e.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(_e.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t{throw xt("UniversalCamera")},In.PERSPECTIVE_CAMERA=0,In.ORTHOGRAPHIC_CAMERA=1,In.FOVMODE_VERTICAL_FIXED=0,In.FOVMODE_HORIZONTAL_FIXED=1,In.RIG_MODE_NONE=0,In.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,In.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,In.RIG_MODE_STEREOSCOPIC_INTERLACED=14,In.RIG_MODE_VR=20,In.RIG_MODE_CUSTOM=22,In.ForceAttachControlToAlwaysPreventDefault=!1,Ze([ht("position")],In.prototype,"_position",void 0),Ze([ht("upVector")],In.prototype,"_upVector",void 0),Ze([rt()],In.prototype,"orthoLeft",null),Ze([rt()],In.prototype,"orthoRight",null),Ze([rt()],In.prototype,"orthoBottom",null),Ze([rt()],In.prototype,"orthoTop",null),Ze([rt()],In.prototype,"fov",void 0),Ze([rt()],In.prototype,"projectionPlaneTilt",void 0),Ze([rt()],In.prototype,"minZ",void 0),Ze([rt()],In.prototype,"maxZ",void 0),Ze([rt()],In.prototype,"inertia",void 0),Ze([rt()],In.prototype,"mode",null),Ze([rt()],In.prototype,"layerMask",void 0),Ze([rt()],In.prototype,"fovMode",void 0),Ze([rt()],In.prototype,"cameraRigMode",void 0),Ze([rt()],In.prototype,"interaxialDistance",void 0),Ze([rt()],In.prototype,"isStereoscopicSideBySide",void 0);class Rn{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class Mn{constructor(e,t,i){this.vectors=ee.BuildArray(8,_e.Zero),this.center=_e.Zero(),this.centerWorld=_e.Zero(),this.extendSize=_e.Zero(),this.extendSizeWorld=_e.Zero(),this.directions=ee.BuildArray(3,_e.Zero),this.vectorsWorld=ee.BuildArray(8,_e.Zero),this.minimumWorld=_e.Zero(),this.maximumWorld=_e.Zero(),this.minimum=_e.Zero(),this.maximum=_e.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,r=e.y,n=e.z,o=t.x,a=t.y,l=t.z,h=this.vectors;this.minimum.copyFromFloats(s,r,n),this.maximum.copyFromFloats(o,a,l),h[0].copyFromFloats(s,r,n),h[1].copyFromFloats(o,a,l),h[2].copyFromFloats(o,r,n),h[3].copyFromFloats(s,a,n),h[4].copyFromFloats(s,r,l),h[5].copyFromFloats(o,a,n),h[6].copyFromFloats(s,a,l),h[7].copyFromFloats(o,r,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||me.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=Mn._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const r=s*e,n=i.scaleInPlace(.5*r),o=this.center.subtractToRef(n,t[1]),a=this.center.addToRef(n,t[2]);return this.reConstruct(o,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,s=this.directions,r=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)r[e].copyFrom(n[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let s=0;s<8;++s){const o=r[s];_e.TransformCoordinatesToRef(n[s],e,o),t.minimizeInPlace(o),i.maximizeInPlace(o)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}_e.FromArrayToRef(e.m,0,s[0]),_e.FromArrayToRef(e.m,4,s[1]),_e.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return Mn.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return Mn.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,r=t.y,n=t.z,o=i.x,a=i.y,l=i.z,h=e.x,c=e.y,u=e.z,d=-J;return!(o-hh-s||a-cc-r||l-uu-n)}intersectsSphere(e){return Mn.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,r=i.x,n=i.y,o=i.z,a=s.x,l=s.y,h=s.z,c=e.x,u=e.y,d=e.z,_=t.x,p=t.y,f=t.z;return!(a_||lp||hf)}dispose(){this._drawWrapperFront?.dispose(),this._drawWrapperBack?.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const r=Mn._TmpVector3[0];return _e.ClampToRef(i,e,t,r),_e.DistanceSquared(i,r)<=s*s}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let s=!0;const r=t[i];for(let t=0;t<8;++t)if(r.dotCoordinate(e[t])>=0){s=!1;break}if(s)return!1}return!0}}Mn._TmpVector3=ee.BuildArray(3,_e.Zero);class On{constructor(e,t,i){this.center=_e.Zero(),this.centerWorld=_e.Zero(),this.minimum=_e.Zero(),this.maximum=_e.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=_e.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*s,this._update(i||me.IdentityReadOnly)}scale(e){const t=this.radius*e,i=On._TmpVector3,s=i[0].setAll(t),r=this.center.subtractToRef(s,i[1]),n=this.center.addToRef(s,i[2]);return this.reConstruct(r,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{_e.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=On._TmpVector3[0];_e.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,i=this.radiusWorld;for(let s=0;s<6;s++)if(e[s].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=_e.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const s=_e.Dot(t.centerWorld,e),r=Math.abs(_e.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(_e.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(_e.Dot(t.directions[2],e))*t.extendSize.z;i.min=s-r,i.max=s+r},Fn=(e,t,i)=>(Nn(e,t,Dn),Nn(e,i,wn),!(Dn.min>wn.max||wn.min>Dn.max));class Ln{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new Mn(e,t,i),this.boundingSphere=new On(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}get minimum(){return this.boundingBox.minimum}get maximum(){return this.boundingBox.maximum}get isLocked(){return this._isLocked}set isLocked(e){this._isLocked=e}update(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))}centerOn(e,t){const i=Ln._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=Ln._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=_e.Minimize(this.minimum,e),i=_e.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=ve.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=ve.Vector3[0];return _e.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),_e.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return!(2!==t&&3!==t||!this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(!(1!==t&&3!==t)||this.boundingBox.isInFrustum(e))}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,Ln._TmpVector3[0]).length()}isCompletelyInFrustum(e){return this.boundingBox.isCompletelyInFrustum(e)}_checkCollision(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)}intersectsPoint(e){return!!this.boundingSphere.centerWorld&&!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e)}intersects(e,t){if(!On.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!Mn.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!!(Fn(i.directions[0],i,s)&&Fn(i.directions[1],i,s)&&Fn(i.directions[2],i,s)&&Fn(s.directions[0],i,s)&&Fn(s.directions[1],i,s)&&Fn(s.directions[2],i,s)&&Fn(_e.Cross(i.directions[0],s.directions[0]),i,s)&&Fn(_e.Cross(i.directions[0],s.directions[1]),i,s)&&Fn(_e.Cross(i.directions[0],s.directions[2]),i,s)&&Fn(_e.Cross(i.directions[1],s.directions[0]),i,s)&&Fn(_e.Cross(i.directions[1],s.directions[1]),i,s)&&Fn(_e.Cross(i.directions[1],s.directions[2]),i,s)&&Fn(_e.Cross(i.directions[2],s.directions[0]),i,s)&&Fn(_e.Cross(i.directions[2],s.directions[1]),i,s)&&Fn(_e.Cross(i.directions[2],s.directions[2]),i,s))}}Ln._TmpVector3=ee.BuildArray(2,_e.Zero);class Bn{static extractMinAndMaxIndexed(e,t,i,s,r,n){for(let o=i;o!Array.isArray(e)&&!Array.isArray(t)))],Bn,"extractMinAndMaxIndexed",null),Ze([gt.filter(((...[e])=>!Array.isArray(e)))],Bn,"extractMinAndMax",null);class Un{static GetEffect(e){return void 0===e.getPipelineContext?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){this.effect=e,void 0!==t&&(this.defines=t),i&&this.drawContext?.reset()}dispose(){this.drawContext?.dispose()}}class Gn{get materialDefines(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:this._getDrawWrapper()?.defines}set materialDefines(e){(this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new Un(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){t&&this._drawWrappers[e]?.dispose(),this._drawWrappers[e]=void 0}get effect(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:this._getDrawWrapper()?.effect??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,s=!0){const r=this._drawWrapper;r.setEffect(e,t,s),void 0!==i&&(r.materialContext=i),e||(r.defines=null,r.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)e?.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,s,r,n,o,a=!0){return new Gn(e,t,i,s,r,n,o,a)}constructor(e,t,i,s,r,n,o,a=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=s,this.indexCount=r,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=o||n,l&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,a&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){return(this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null)||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(!t)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(t)){const e=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return t}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(er.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();i={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else i=kn(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new Ln(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const i=[];for(let t=this.indexStart;ta&&(a=t)}return new Gn(e,o,a-o+1,t,i,s,r,n)}}class zn{}class Wn{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=En(this._applyToCoroutine.bind(this)),this.uniqueId=Wn._UniqueIDGenerator,Wn._UniqueIDGenerator++}set(e,t){switch(e.length||Ne.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case er.PositionKind:this.positions=e;break;case er.NormalKind:this.normals=e;break;case er.TangentKind:this.tangents=e;break;case er.UVKind:this.uvs=e;break;case er.UV2Kind:this.uvs2=e;break;case er.UV3Kind:this.uvs3=e;break;case er.UV4Kind:this.uvs4=e;break;case er.UV5Kind:this.uvs5=e;break;case er.UV6Kind:this.uvs6=e;break;case er.ColorKind:this.colors=e;break;case er.MatricesIndicesKind:this.matricesIndices=e;break;case er.MatricesWeightsKind:this.matricesWeights=e;break;case er.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case er.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){if(this.positions&&(e.setVerticesData(er.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(er.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(er.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(er.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(er.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(er.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(er.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(er.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(er.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(er.ColorKind,this.colors,t),this.hasVertexAlpha&&void 0!==e.hasVertexAlpha&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(er.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(er.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(er.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(er.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){const t=e;t.subMeshes=[];for(const e of this.materialInfos)new Gn(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,t)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(er.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(er.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(er.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(er.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(er.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(er.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(er.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(er.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(er.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(er.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(er.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(er.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(er.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(er.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const r=ve.Vector3[0],n=ve.Vector3[1];for(let o=i;o({vertexData:e}))):[{vertexData:e}];return Sn(this._mergeCoroutine(void 0,n,t,!1,i,s,r))}*_mergeCoroutine(e,t,i=!1,s,r,n=!1,o=!1){this._validate();let a=t.map((e=>e.vertexData)),l=this;if(o)for(const e of a)e&&(e._validate(),!this.normals&&e.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&e.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&e.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&e.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&e.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&e.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&e.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&e.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&e.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&e.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&e.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&e.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&e.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const e of a)if(e)if(o)this.normals&&!e.normals&&(e.normals=new Float32Array(e.positions.length)),this.tangents&&!e.tangents&&(e.tangents=new Float32Array(e.positions.length/3*4)),this.uvs&&!e.uvs&&(e.uvs=new Float32Array(e.positions.length/3*2)),this.uvs2&&!e.uvs2&&(e.uvs2=new Float32Array(e.positions.length/3*2)),this.uvs3&&!e.uvs3&&(e.uvs3=new Float32Array(e.positions.length/3*2)),this.uvs4&&!e.uvs4&&(e.uvs4=new Float32Array(e.positions.length/3*2)),this.uvs5&&!e.uvs5&&(e.uvs5=new Float32Array(e.positions.length/3*2)),this.uvs6&&!e.uvs6&&(e.uvs6=new Float32Array(e.positions.length/3*2)),this.colors&&!e.colors&&(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)),this.matricesIndices&&!e.matricesIndices&&(e.matricesIndices=new Float32Array(e.positions.length/3*4)),this.matricesWeights&&!e.matricesWeights&&(e.matricesWeights=new Float32Array(e.positions.length/3*4)),this.matricesIndicesExtra&&!e.matricesIndicesExtra&&(e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4)),this.matricesWeightsExtra&&!e.matricesWeightsExtra&&(e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4));else if(e._validate(),!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");if(n){let i=0,s=0,r=0;const n=[];let o=null;const h=[];for(const t of this.splitBasedOnMaterialID())h.push({vertexData:t,transform:e});for(const e of t)if(e.vertexData)for(const t of e.vertexData.splitBasedOnMaterialID())h.push({vertexData:t,transform:e.transform});h.sort(((e,t)=>{const i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,s=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>s?1:i===s?0:-1}));for(const e of h){const t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,o&&o.materialIndex===i)o.indexCount+=t.indices.length,o.verticesCount+=t.positions.length/3;else{const e=new zn;e.materialIndex=i,e.indexStart=s,e.indexCount=t.indices.length,e.verticesStart=r,e.verticesCount=t.positions.length/3,n.push(e),o=e}s+=t.indices.length,r+=t.positions.length/3}const c=h.splice(0,1)[0];l=c.vertexData,e=c.transform,a=h.map((e=>e.vertexData)),t=h,this.materialInfos=n}const h=a.reduce(((e,t)=>e+(t.indices?.length??0)),l.indices?.length??0);let c=r||a.some((e=>e.indices===l.indices))?l.indices?.slice():l.indices;if(h>0){let r=c?.length??0;if(c||(c=new Array(h)),c.length!==h){if(Array.isArray(c))c.length=h;else{const e=i||c instanceof Uint32Array?new Uint32Array(h):new Uint16Array(h);e.set(c),c=e}e&&e.determinant()<0&&Wn._FlipFaces(c,0,r)}let n=l.positions?l.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t[e.vertexData.positions,e.transform]))),s&&(yield),l.normals&&(this.normals=Wn._MergeElement(er.NormalKind,l.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),s&&(yield)),l.tangents&&(this.tangents=Wn._MergeElement(er.TangentKind,l.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),s&&(yield)),l.uvs&&(this.uvs=Wn._MergeElement(er.UVKind,l.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),s&&(yield)),l.uvs2&&(this.uvs2=Wn._MergeElement(er.UV2Kind,l.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),s&&(yield)),l.uvs3&&(this.uvs3=Wn._MergeElement(er.UV3Kind,l.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),s&&(yield)),l.uvs4&&(this.uvs4=Wn._MergeElement(er.UV4Kind,l.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),s&&(yield)),l.uvs5&&(this.uvs5=Wn._MergeElement(er.UV5Kind,l.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),s&&(yield)),l.uvs6&&(this.uvs6=Wn._MergeElement(er.UV6Kind,l.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),s&&(yield)),l.colors&&(this.colors=Wn._MergeElement(er.ColorKind,l.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),(void 0!==l.hasVertexAlpha||t.some((e=>void 0!==e.vertexData.hasVertexAlpha)))&&(this.hasVertexAlpha=l.hasVertexAlpha||t.some((e=>e.vertexData.hasVertexAlpha))),s&&(yield)),l.matricesIndices&&(this.matricesIndices=Wn._MergeElement(er.MatricesIndicesKind,l.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),s&&(yield)),l.matricesWeights&&(this.matricesWeights=Wn._MergeElement(er.MatricesWeightsKind,l.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),s&&(yield)),l.matricesIndicesExtra&&(this.matricesIndicesExtra=Wn._MergeElement(er.MatricesIndicesExtraKind,l.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),s&&(yield)),l.matricesWeightsExtra&&(this.matricesWeightsExtra=Wn._MergeElement(er.MatricesWeightsExtraKind,l.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform])))),this}static _MergeElement(e,t,i,s){const r=s.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==r.length)return t;if(!t)return this._MergeElement(e,r[0][0],r[0][1],r.slice(1));const n=r.reduce(((e,t)=>e+t[0].length),t.length),o=e===er.PositionKind?Wn._TransformVector3Coordinates:e===er.NormalKind?Wn._TransformVector3Normals:e===er.TangentKind?Wn._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(n);e.set(t),i&&o(e,i,0,t.length);let s=t.length;for(const[t,i]of r)e.set(t,s),i&&o(e,i,s,t.length),s+=t.length;return e}{const e=new Array(n);for(let i=0;i{const i=er.DeduceStride(e);if(t.length%i!=0)throw new Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(er.PositionKind,this.positions),i=(i,s)=>{const r=e(i,s);if(r!==t)throw new Error("The "+i+"s element count ("+r+") does not match the positions count ("+t+")")};this.normals&&i(er.NormalKind,this.normals),this.tangents&&i(er.TangentKind,this.tangents),this.uvs&&i(er.UVKind,this.uvs),this.uvs2&&i(er.UV2Kind,this.uvs2),this.uvs3&&i(er.UV3Kind,this.uvs3),this.uvs4&&i(er.UV4Kind,this.uvs4),this.uvs5&&i(er.UV5Kind,this.uvs5),this.uvs6&&i(er.UV6Kind,this.uvs6),this.colors&&i(er.ColorKind,this.colors),this.matricesIndices&&i(er.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(er.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(er.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(er.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return Wn.Parse(e)}serialize(){const e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos){e.materialInfos=[];for(const t of this.materialInfos){const i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return Wn._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return Wn._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new Wn;return e.isVerticesDataPresent(er.PositionKind)&&(s.positions=e.getVerticesData(er.PositionKind,t,i)),e.isVerticesDataPresent(er.NormalKind)&&(s.normals=e.getVerticesData(er.NormalKind,t,i)),e.isVerticesDataPresent(er.TangentKind)&&(s.tangents=e.getVerticesData(er.TangentKind,t,i)),e.isVerticesDataPresent(er.UVKind)&&(s.uvs=e.getVerticesData(er.UVKind,t,i)),e.isVerticesDataPresent(er.UV2Kind)&&(s.uvs2=e.getVerticesData(er.UV2Kind,t,i)),e.isVerticesDataPresent(er.UV3Kind)&&(s.uvs3=e.getVerticesData(er.UV3Kind,t,i)),e.isVerticesDataPresent(er.UV4Kind)&&(s.uvs4=e.getVerticesData(er.UV4Kind,t,i)),e.isVerticesDataPresent(er.UV5Kind)&&(s.uvs5=e.getVerticesData(er.UV5Kind,t,i)),e.isVerticesDataPresent(er.UV6Kind)&&(s.uvs6=e.getVerticesData(er.UV6Kind,t,i)),e.isVerticesDataPresent(er.ColorKind)&&(s.colors=e.getVerticesData(er.ColorKind,t,i)),e.isVerticesDataPresent(er.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(er.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(er.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(er.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(er.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(er.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(er.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(er.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw xt("ribbonBuilder")}static CreateBox(e){throw xt("boxBuilder")}static CreateTiledBox(e){throw xt("tiledBoxBuilder")}static CreateTiledPlane(e){throw xt("tiledPlaneBuilder")}static CreateSphere(e){throw xt("sphereBuilder")}static CreateCylinder(e){throw xt("cylinderBuilder")}static CreateTorus(e){throw xt("torusBuilder")}static CreateLineSystem(e){throw xt("linesBuilder")}static CreateDashedLines(e){throw xt("linesBuilder")}static CreateGround(e){throw xt("groundBuilder")}static CreateTiledGround(e){throw xt("groundBuilder")}static CreateGroundFromHeightMap(e){throw xt("groundBuilder")}static CreatePlane(e){throw xt("planeBuilder")}static CreateDisc(e){throw xt("discBuilder")}static CreatePolygon(e,t,i,s,r,n,o){throw xt("polygonBuilder")}static CreateIcoSphere(e){throw xt("icoSphereBuilder")}static CreatePolyhedron(e){throw xt("polyhedronBuilder")}static CreateCapsule(e={orientation:_e.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw xt("capsuleBuilder")}static CreateTorusKnot(e){throw xt("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let r=0,n=0,o=0,a=0,l=0,h=0,c=0,u=0,d=0,_=0,p=0,f=0,m=0,g=0,v=0,x=0,b=0,T=0,y=0,S=0,C=!1,E=!1,A=!1,P=!1,I=1,R=0,M=null;s&&(C=!!s.facetNormals,E=!!s.facetPositions,A=!!s.facetPartitioning,I=!0===s.useRightHandedSystem?-1:1,R=s.ratio||0,P=!!s.depthSort,M=s.distanceTo,P&&void 0===M&&(M=_e.Zero()));let O=0,D=0,w=0,N=0;for(A&&s&&s.bbSize&&(O=s.subDiv.X*R/s.bbSize.x,D=s.subDiv.Y*R/s.bbSize.y,w=s.subDiv.Z*R/s.bbSize.z,N=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),r=0;r!Array.isArray(e)))],Wn,"_TransformVector3Coordinates",null),Ze([gt.filter(((...[e])=>!Array.isArray(e)))],Wn,"_TransformVector3Normals",null),Ze([gt.filter(((...[e])=>!Array.isArray(e)))],Wn,"_TransformVector4Normals",null),Ze([gt.filter(((...[e])=>!Array.isArray(e)))],Wn,"_FlipFaces",null);class Hn{static get ForceFullSceneLoadingForIncremental(){return Hn._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Hn._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Hn._ShowLoadingScreen}static set ShowLoadingScreen(e){Hn._ShowLoadingScreen=e}static get loggingLevel(){return Hn._LoggingLevel}static set loggingLevel(e){Hn._LoggingLevel=e}static get CleanBoneMatrixWeights(){return Hn._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Hn._CleanBoneMatrixWeights=e}}Hn._ForceFullSceneLoadingForIncremental=!1,Hn._ShowLoadingScreen=!0,Hn._CleanBoneMatrixWeights=!1,Hn._LoggingLevel=0;class Xn{}Xn.UseOpenGLOrientationForUV=!1;class Yn{get boundingBias(){return this._boundingBias}set boundingBias(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)}static CreateGeometryForMesh(e){const t=new Yn(Yn.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,s=!1,r=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||re.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=s,i?this.setAllVerticesData(i,s):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e{e._rebuild()}))}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,s){i&&Array.isArray(t)&&(t=new Float32Array(t));const r=new er(this._engine,t,e,{updatable:i,postponeInternalCreation:0===this._meshes.length,stride:s,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(r)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const s=e.getKind();this._vertexBuffers[s]&&i&&this._vertexBuffers[s].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[s]=e;const r=this._meshes,n=r.length;if(s===er.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const i=this._extend&&this._extend.minimum||new _e(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),s=this._extend&&this._extend.maximum||new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e65535);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),null!=t&&(this._totalVertices=t);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?void 0!==this._totalIndices?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){e&&this._vertexArrayObjects&&this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const i=this._meshes,s=i.indexOf(e);-1!==s&&(i.splice(s,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;const t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();const i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&!(e=this.getVerticesData(er.PositionKind)))return;this._extend=Vn(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===er.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const e of this._meshes)e._markSubMeshesAsAttributesDirty()}load(e,t){2!==this.delayLoadState&&(this.isReady()?t&&t():(this.delayLoadState=2,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const s=this._meshes,r=s.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new Wn;t.indices=[];const i=this.getIndices();if(i)for(let e=0;e0){const s=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(er.PositionKind,s,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const s=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(er.NormalKind,s,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const s=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(er.TangentKind,s,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const s=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(Xn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(Xn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(Xn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(Xn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(Xn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(Xn.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(er.ColorKind,s,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(er.MatricesIndicesKind,r,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(er.MatricesIndicesExtraKind,r,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const s=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(er.MatricesWeightsKind,s,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){const s=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(s,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){const s=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(er.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(er.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(er.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(Yn._CleanMatricesWeights(e,t),t.setVerticesData(er.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(er.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;s=i.bones.length}const r=t.getVerticesData(er.MatricesIndicesKind),n=t.getVerticesData(er.MatricesIndicesExtraKind),o=e.matricesWeights,a=e.matricesWeightsExtra,l=e.numBoneInfluencer,h=o.length;for(let e=0;el-1)&&(h=l-1),t>i){const i=1/t;for(let t=0;t<4;t++)o[e+t]*=i;if(a)for(let t=0;t<4;t++)a[e+t]*=i}else h>=4?(a[e+h-4]=1-t,n[e+h-4]=s):(o[e+h]=1-t,r[e+h]=s)}t.setVerticesData(er.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(er.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const s=new Yn(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,Tt&&Tt.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new Ln(_e.FromArray(e.boundingBoxMinimum),_e.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(er.UVKind),e.hasUVs2&&s._delayInfo.push(er.UV2Kind),e.hasUVs3&&s._delayInfo.push(er.UV3Kind),e.hasUVs4&&s._delayInfo.push(er.UV4Kind),e.hasUVs5&&s._delayInfo.push(er.UV5Kind),e.hasUVs6&&s._delayInfo.push(er.UV6Kind),e.hasColors&&s._delayInfo.push(er.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(er.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(er.MatricesWeightsKind),s._delayLoadingFunction=Wn.ImportVertexData):Wn.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}class Qn{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new jn(e)}sampleFrame(e=Wt.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){const t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}}get averageFrameTime(){return this._rollingFrameTime.average}get averageFrameTimeVariance(){return this._rollingFrameTime.variance}get instantaneousFrameTime(){return this._rollingFrameTime.history(0)}get averageFPS(){return 1e3/this._rollingFrameTime.average}get instantaneousFPS(){const e=this._rollingFrameTime.history(0);return 0===e?0:1e3/e}get isSaturated(){return this._rollingFrameTime.isSaturated()}enable(){this._enabled=!0}disable(){this._enabled=!1,this._lastFrameTimeMs=null}get isEnabled(){return this._enabled}reset(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()}}class jn{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const e=this._samples[this._pos];t=e-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(e-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length}history(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;const t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]}isSaturated(){return this._sampleCount>=this._samples.length}reset(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0}_wrapPosition(e){const t=this._samples.length;return(e%t+t)%t}}function Kn(e,t,i=!1,s){switch(e){case 3:{const e=(ArrayBuffer,new Int8Array(t));return s&&e.set(new Int8Array(s)),e}case 0:{const e=(ArrayBuffer,new Uint8Array(t));return s&&e.set(new Uint8Array(s)),e}case 4:{const e=t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);return s&&e.set(new Int16Array(s)),e}case 5:case 8:case 9:case 10:case 2:{const e=t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);return s&&e.set(new Uint16Array(s)),e}case 6:{const e=t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);return s&&e.set(new Int32Array(s)),e}case 7:case 11:case 12:case 13:case 14:case 15:{const e=t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);return s&&e.set(new Uint32Array(s)),e}case 1:{const e=t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t);return s&&e.set(new Float32Array(s)),e}}const r=(ArrayBuffer,new Uint8Array(t));return s&&r.set(new Uint8Array(s)),r}function $n(e,t,i){e._onCanvasFocus=()=>{e.onCanvasFocusObservable.notifyObservers(e)},e._onCanvasBlur=()=>{e.onCanvasBlurObservable.notifyObservers(e)},e._onCanvasContextMenu=t=>{e.disableContextMenu&&t.preventDefault()},t.addEventListener("focus",e._onCanvasFocus),t.addEventListener("blur",e._onCanvasBlur),t.addEventListener("contextmenu",e._onCanvasContextMenu),e._onBlur=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.disable(),e._windowIsBackground=!0},e._onFocus=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.enable(),e._windowIsBackground=!1},e._onCanvasPointerOut=i=>{document.elementFromPoint(i.clientX,i.clientY)!==t&&e.onCanvasPointerOutObservable.notifyObservers(i)};const s=e.getHostWindow();s&&"function"==typeof s.addEventListener&&(s.addEventListener("blur",e._onBlur),s.addEventListener("focus",e._onFocus)),t.addEventListener("pointerout",e._onCanvasPointerOut),i.doNotHandleTouchAction||function(e){e&&e.setAttribute&&(e.setAttribute("touch-action","none"),e.style.touchAction="none",e.style.webkitTapHighlightColor="transparent")}(t),!ns.audioEngine&&i.audioEngine&&ns.AudioEngineFactory&&(ns.audioEngine=ns.AudioEngineFactory(e.getRenderingCanvas(),e.getAudioContext(),e.getAudioDestination())),Ut()&&(e._onFullscreenChange=()=>{e.isFullscreen=!!document.fullscreenElement,e.isFullscreen&&e._pointerLockRequested&&t&&so(t)},document.addEventListener("fullscreenchange",e._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",e._onFullscreenChange,!1),e._onPointerLockChange=()=>{e.isPointerLock=document.pointerLockElement===t},document.addEventListener("pointerlockchange",e._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",e._onPointerLockChange,!1)),e.enableOfflineSupport=void 0!==ns.OfflineProviderFactory,e._deterministicLockstep=!!i.deterministicLockstep,e._lockstepMaxSteps=i.lockstepMaxSteps||0,e._timeStep=i.timeStep||1/60}function qn(e,t){1===re.Instances.length&&ns.audioEngine&&(ns.audioEngine.dispose(),ns.audioEngine=null);const i=e.getHostWindow();i&&"function"==typeof i.removeEventListener&&(i.removeEventListener("blur",e._onBlur),i.removeEventListener("focus",e._onFocus)),t&&(t.removeEventListener("focus",e._onCanvasFocus),t.removeEventListener("blur",e._onCanvasBlur),t.removeEventListener("pointerout",e._onCanvasPointerOut),t.removeEventListener("contextmenu",e._onCanvasContextMenu)),Ut()&&(document.removeEventListener("fullscreenchange",e._onFullscreenChange),document.removeEventListener("mozfullscreenchange",e._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",e._onFullscreenChange),document.removeEventListener("msfullscreenchange",e._onFullscreenChange),document.removeEventListener("pointerlockchange",e._onPointerLockChange),document.removeEventListener("mspointerlockchange",e._onPointerLockChange),document.removeEventListener("mozpointerlockchange",e._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",e._onPointerLockChange))}function Zn(e){const t=document.createElement("span");t.textContent="Hg",t.style.font=e;const i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";const s=document.createElement("div");s.style.whiteSpace="nowrap",s.appendChild(t),s.appendChild(i),document.body.appendChild(s);let r=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",r=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(s)}return{ascent:r,height:n,descent:n-r}}function Jn(e,t,i){return new Promise(((s,r)=>{const n=new Image;n.onload=()=>{n.decode().then((()=>{e.createImageBitmap(n,i).then((e=>{s(e)}))}))},n.onerror=()=>{r(`Error loading image ${n.src}`)},n.src=t}))}function eo(e,t,i,s){const r=e.createCanvas(i,s).getContext("2d");if(!r)throw new Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(t,0,0),r.getImageData(0,0,i,s).data}function to(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}function io(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}function so(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}function ro(){document.exitPointerLock&&document.exitPointerLock()}qs.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode!==e){switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0}t||(this.depthCullingState.depthMask=0===e),this._alphaMode=e}else if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}},qs.prototype._readTexturePixelsSync=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=c.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),s>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+s,e._hardwareTexture?.underlyingResource,r):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,e._hardwareTexture?.underlyingResource,r);let u=void 0!==e.type?this._getWebGLTextureType(e.type):c.UNSIGNED_BYTE;return a?n||(n=Kn(e.type,4*t*i)):u===c.UNSIGNED_BYTE?(n||(n=new Uint8Array(4*t*i)),u=c.UNSIGNED_BYTE):(n||(n=new Float32Array(4*t*i)),u=c.FLOAT),o&&this.flushFramebuffer(),c.readPixels(l,h,t,i,c.RGBA,u,n),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),n},qs.prototype._readTexturePixels=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,s,r,n,o,a,l,h))},qs.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let s;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),s=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,s,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},qs.prototype.updateDynamicVertexBuffer=function(e,t,i,s){this.bindArrayBuffer(e),void 0===i&&(i=0);const r=t.byteLength||t.length;void 0===s||s>=r&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+s)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,s):new Uint8Array(t.buffer,t.byteOffset+i,s),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()},ns.prototype.displayLoadingUI=function(){if(!kt())return;const e=this.loadingScreen;e&&e.displayLoadingUI()},ns.prototype.hideLoadingUI=function(){if(!kt())return;const e=this._loadingScreen;e&&e.hideLoadingUI()},Object.defineProperty(ns.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=ns.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(ns.prototype,"loadingUIText",{set:function(e){this.loadingScreen.loadingUIText=e},enumerable:!0,configurable:!0}),Object.defineProperty(ns.prototype,"loadingUIBackgroundColor",{set:function(e){this.loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),ns.prototype.getInputElement=function(){return this._renderingCanvas},ns.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null},ns.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null},ns.prototype.getAspectRatio=function(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)},ns.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)},ns.prototype._verifyPointerLock=function(){this._onPointerLockChange?.()},ns.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774)}this._alphaEquation=e}},ns.prototype.getInputElement=function(){return this._renderingCanvas},ns.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},ns.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},ns.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)},ns.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)},ns.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)},ns.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)},ns.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},ns.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},ns.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},ns.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},ns.prototype.getStencilMask=function(){return this._stencilState.stencilMask},ns.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},ns.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},ns.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},ns.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},ns.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},ns.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},ns.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},ns.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},ns.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},ns.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},ns.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},ns.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},ns.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},ns.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()},ns.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)},ns.prototype.setAlphaConstants=function(e,t,i,s){this._alphaState.setAlphaBlendConstants(e,t,i,s)},ns.prototype.getAlphaMode=function(){return this._alphaMode},ns.prototype.getAlphaEquation=function(){return this._alphaEquation},ns.prototype.getRenderPassNames=function(){return this._renderPassNames},ns.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]},ns.prototype.createRenderPassId=function(e){const t=++ns._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t},ns.prototype.releaseRenderPassId=function(e){this._renderPassNames[e]=void 0;for(let t=0;tnew no(e,t,i);class no{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new K,this.onAudioLockedObservable=new K,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!kt())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);const s=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{s&&s.canPlayType&&(s.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||s.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{s&&s.canPlayType&&s.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){if("running"===this._audioContext?.state)return this._hideMuteButton(),void(this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)));this._tryToRun?this._audioContext?.suspend().then((()=>{this._tryToRun=!1,this._triggerRunningState()})):this._triggerRunningState()}_resumeAudioContext(){return this._audioContext?.resume?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,Ne.Error("Web Audio: "+e.message)}}_triggerRunningState(){this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then((()=>{this._tryToRun=!1,this._muteButton&&this._hideMuteButton(),this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)})).catch((()=>{this._tryToRun=!1,this.unlocked=!1})))}_triggerSuspendedState(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()}_displayMuteButton(){if(this.useCustomUnlockedButton||this._muteButton)return;this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";const e=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",(()=>{this._triggerRunningState()}),!0),this._muteButton.addEventListener("click",(()=>{this.unlock()}),!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}}class oo extends qs{static get NpmPackage(){return ns.NpmPackage}static get Version(){return ns.Version}static get Instances(){return re.Instances}static get LastCreatedEngine(){return re.LastCreatedEngine}static get LastCreatedScene(){return re.LastCreatedScene}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{this._loadFile(e,(e=>{s(e)}),void 0,t,i,((e,t)=>{r(t)}))}))}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return Zn(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(0!==this._frameHandler){this._frameHandler=0;const{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}enterPointerlock(){this._renderingCanvas&&so(this._renderingCanvas)}exitPointerlock(){ro()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){const t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,s,r,n=null){r=r||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const o=super.createShaderProgram(e,t,i,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),o}_createShaderProgram(e,t,i,s,r=null){const n=s.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");if(s.attachShader(n,t),s.attachShader(n,i),this.webGLVersion>1&&r){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=t}return s.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach((t=>{t.postProcesses.forEach((t=>{t._outputTexture===e&&(t._outputTexture=null)})),t.cameras.forEach((t=>{t._postProcesses.forEach((t=>{t&&t._outputTexture===e&&(t._outputTexture=null)}))}))}))}_rescaleTexture(e,t,i,s,r){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);const n=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&oo._RescalePostProcessFactory&&(this._rescalePostProcess=oo._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled((()=>{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let o=i;o||(o=this.scenes[this.scenes.length-1]),o.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()})))}wrapWebGLTexture(e,t=!1,i=3,s=0,r=0){const n=new Ks(e,this._gl),o=new ss(this,is.Unknown,!0);return o._hardwareTexture=n,o.baseWidth=s,o.baseHeight=r,o.width=s,o.height=r,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,s=0){const r=this._gl,n=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,o),l=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=r.TEXTURE_2D;e.isCube&&(h=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(h,s,a,o,n,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void Ne.Error("WebGL 1 does not support texture comparison.");const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");const i=new js(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const s=this._gl;return new Promise(((r,n)=>{const o=()=>{const a=s.clientWaitSync(e,t,0);a!=s.WAIT_FAILED?a!=s.TIMEOUT_EXPIRED?r():setTimeout(o,i):n()};o()}))}_readPixelsAsync(e,t,i,s,r,n,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const a=this._gl,l=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.bufferData(a.PIXEL_PACK_BUFFER,o.byteLength,a.STREAM_READ),a.readPixels(e,t,i,s,r,n,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null);const h=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(a.flush(),this._clientWaitAsync(h,0,10).then((()=>(a.deleteSync(h),a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,o),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.deleteBuffer(l),o)))):null}dispose(){this._rescalePostProcess&&this._rescalePostProcess.dispose(),qn(this,this._renderingCanvas),super.dispose()}}oo.ALPHA_DISABLE=0,oo.ALPHA_ADD=1,oo.ALPHA_COMBINE=2,oo.ALPHA_SUBTRACT=3,oo.ALPHA_MULTIPLY=4,oo.ALPHA_MAXIMIZED=5,oo.ALPHA_ONEONE=6,oo.ALPHA_PREMULTIPLIED=7,oo.ALPHA_PREMULTIPLIED_PORTERDUFF=8,oo.ALPHA_INTERPOLATE=9,oo.ALPHA_SCREENMODE=10,oo.DELAYLOADSTATE_NONE=0,oo.DELAYLOADSTATE_LOADED=1,oo.DELAYLOADSTATE_LOADING=2,oo.DELAYLOADSTATE_NOTLOADED=4,oo.NEVER=512,oo.ALWAYS=519,oo.LESS=513,oo.EQUAL=514,oo.LEQUAL=515,oo.GREATER=516,oo.GEQUAL=518,oo.NOTEQUAL=517,oo.KEEP=7680,oo.REPLACE=7681,oo.INCR=7682,oo.DECR=7683,oo.INVERT=5386,oo.INCR_WRAP=34055,oo.DECR_WRAP=34056,oo.TEXTURE_CLAMP_ADDRESSMODE=0,oo.TEXTURE_WRAP_ADDRESSMODE=1,oo.TEXTURE_MIRROR_ADDRESSMODE=2,oo.TEXTUREFORMAT_ALPHA=0,oo.TEXTUREFORMAT_LUMINANCE=1,oo.TEXTUREFORMAT_LUMINANCE_ALPHA=2,oo.TEXTUREFORMAT_RGB=4,oo.TEXTUREFORMAT_RGBA=5,oo.TEXTUREFORMAT_RED=6,oo.TEXTUREFORMAT_R=6,oo.TEXTUREFORMAT_RG=7,oo.TEXTUREFORMAT_RED_INTEGER=8,oo.TEXTUREFORMAT_R_INTEGER=8,oo.TEXTUREFORMAT_RG_INTEGER=9,oo.TEXTUREFORMAT_RGB_INTEGER=10,oo.TEXTUREFORMAT_RGBA_INTEGER=11,oo.TEXTURETYPE_UNSIGNED_BYTE=0,oo.TEXTURETYPE_UNSIGNED_INT=0,oo.TEXTURETYPE_FLOAT=1,oo.TEXTURETYPE_HALF_FLOAT=2,oo.TEXTURETYPE_BYTE=3,oo.TEXTURETYPE_SHORT=4,oo.TEXTURETYPE_UNSIGNED_SHORT=5,oo.TEXTURETYPE_INT=6,oo.TEXTURETYPE_UNSIGNED_INTEGER=7,oo.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,oo.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,oo.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,oo.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,oo.TEXTURETYPE_UNSIGNED_INT_24_8=12,oo.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,oo.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,oo.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,oo.TEXTURE_NEAREST_SAMPLINGMODE=1,oo.TEXTURE_BILINEAR_SAMPLINGMODE=2,oo.TEXTURE_TRILINEAR_SAMPLINGMODE=3,oo.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,oo.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,oo.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,oo.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,oo.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,oo.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,oo.TEXTURE_NEAREST_LINEAR=7,oo.TEXTURE_NEAREST_NEAREST=1,oo.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,oo.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,oo.TEXTURE_LINEAR_LINEAR=2,oo.TEXTURE_LINEAR_NEAREST=12,oo.TEXTURE_EXPLICIT_MODE=0,oo.TEXTURE_SPHERICAL_MODE=1,oo.TEXTURE_PLANAR_MODE=2,oo.TEXTURE_CUBIC_MODE=3,oo.TEXTURE_PROJECTION_MODE=4,oo.TEXTURE_SKYBOX_MODE=5,oo.TEXTURE_INVCUBIC_MODE=6,oo.TEXTURE_EQUIRECTANGULAR_MODE=7,oo.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,oo.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,oo.SCALEMODE_FLOOR=1,oo.SCALEMODE_NEAREST=2,oo.SCALEMODE_CEILING=3;const ao=me.Compose(_e.One(),fe.FromEulerAngles(0,Math.PI,0),_e.Zero());class lo extends Et{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=!!(this._billboardMode&lo.BILLBOARDMODE_USE_POSITION),this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==lo.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t,!1),this._forward=new _e(0,0,1),this._up=new _e(0,1,0),this._right=new _e(1,0,0),this._position=_e.Zero(),this._rotation=_e.Zero(),this._rotationQuaternion=null,this._scaling=_e.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=lo.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=me.Zero(),this._usePivotMatrix=!1,this._absolutePosition=_e.Zero(),this._absoluteScaling=_e.Zero(),this._absoluteRotationQuaternion=fe.Identity(),this._pivotMatrix=me.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new K,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return _e.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return _e.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return _e.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()}updatePoseMatrix(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=me.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==lo.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this._infiniteDistance||this._position._isDirty||this._scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)}_initCache(){super._initCache();const e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1,e.useBillboardPath=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=me.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const s=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);s&&i&&i(this,s);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(s,t,i);return s}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||fe.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,s;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],s=arguments[2]}else t=e.x,i=e.y,s=e.z;if(this.parent){const e=ve.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),_e.TransformCoordinatesFromFloatsToRef(t,i,s,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=s;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=_e.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=ve.Matrix[0];return this._localMatrix.invertToRef(e),_e.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=_e.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,r=Ur.LOCAL){const n=lo._LookAtVectorCache,o=r===Ur.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,n),this.setDirection(n,t,i,s),r===Ur.WORLD&&this.parent)if(this.rotationQuaternion){const e=ve.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=ve.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=ve.Quaternion[0];fe.FromEulerVectorToRef(this.rotation,e);const t=ve.Matrix[0];e.toRotationMatrix(t);const i=ve.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=_e.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return _e.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,n);return this.rotationQuaternion?fe.RotationYawPitchRollToRef(r+t,o+i,s,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=r+t,this.rotation.z=s),this}setPivotPoint(e,t=Ur.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==Ur.WORLD){const t=ve.Matrix[0];i.invertToRef(t),e=_e.TransformCoordinates(e,t)}return this.setPivotMatrix(me.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=_e.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){const e=_e.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),_e.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;const s=ve.Quaternion[0],r=ve.Vector3[0],n=ve.Vector3[1],o=ve.Matrix[1];me.IdentityToRef(o);const a=ve.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=lo._TmpRotation,fe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),me.ComposeToRef(this.scaling,l,this.position,a),this.parent&&a.multiplyToRef(this.parent.computeWorldMatrix(!0),a),e&&(e.computeWorldMatrix(!0).invertToRef(o),a.multiplyToRef(o,a)),a.decompose(n,s,r,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(r),this.parent=e,i&&this.setPivotMatrix(me.Identity()),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=e?this._currentParentWhenAttachingToBone:null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){let s;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==Ur.LOCAL){if(this.parent){const i=this.parent.getWorldMatrix(),s=ve.Matrix[0];i.invertToRef(s),e=_e.TransformNormal(e,s),i.determinant()<0&&(t*=-1)}s=fe.RotationAxisToRef(e,t,lo._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else s=fe.RotationAxisToRef(e,t,lo._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=fe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=ve.Vector3[0],r=ve.Vector3[1],n=ve.Vector3[2],o=ve.Quaternion[0],a=ve.Matrix[0],l=ve.Matrix[1],h=ve.Matrix[2],c=ve.Matrix[3];return e.subtractToRef(this.position,s),me.TranslationToRef(s.x,s.y,s.z,a),me.TranslationToRef(-s.x,-s.y,-s.z,l),me.RotationAxisToRef(t,i,h),l.multiplyToRef(h,c),c.multiplyToRef(a,c),c.decompose(r,o,n),this.position.addInPlace(n),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(i&&i!==Ur.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(s));else{const e=this.getPositionExpressedInLocalSpace().add(s);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let s;this.rotationQuaternion?s=this.rotationQuaternion:(s=ve.Quaternion[1],fe.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const r=ve.Quaternion[0];return fe.RotationYawPitchRollToRef(t,e,i,r),s.multiplyInPlace(r),this.rotationQuaternion||s.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==lo.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const r=this._getEffectiveParent(),n=lo._TmpScaling;let o,a=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new _e(e.m[12],e.m[13],e.m[14]);a=lo._TmpTranslation,a.copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,o=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(fe.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(o=lo._TmpRotation,fe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,o)),this._usePivotMatrix){const e=ve.Matrix[1];me.ScalingToRef(n.x,n.y,n.z,e);const t=ve.Matrix[0];o.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,ve.Matrix[4]),ve.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(a.x,a.y,a.z)}else me.ComposeToRef(n,o,a,this._localMatrix);if(r&&r.getWorldMatrix){if(e&&r.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),ve.Matrix[7])}else ve.Matrix[7].copyFrom(r.getWorldMatrix());const e=ve.Vector3[5],t=ve.Vector3[6],i=ve.Quaternion[0];ve.Matrix[7].decompose(t,i,e),me.ScalingToRef(t.x,t.y,t.z,ve.Matrix[7]),ve.Matrix[7].setTranslation(e),lo.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(ve.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),ve.Matrix[6]),ve.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(r.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){const e=ve.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),ve.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&ve.Matrix[1].multiplyToRef(ao,ve.Matrix[1]),ve.Matrix[1].setTranslationFromFloats(0,0,0),ve.Matrix[1].invertToRef(ve.Matrix[0]),(this.billboardMode&lo.BILLBOARDMODE_ALL)!==lo.BILLBOARDMODE_ALL){ve.Matrix[0].decompose(void 0,ve.Quaternion[0],void 0);const e=ve.Vector3[1];ve.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&lo.BILLBOARDMODE_X)!==lo.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&lo.BILLBOARDMODE_Y)!==lo.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&lo.BILLBOARDMODE_Z)!==lo.BILLBOARDMODE_Z&&(e.z=0),me.RotationYawPitchRollToRef(e.y,e.x,e.z,ve.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ve.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ve.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const e=ve.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(ve.Matrix[1]);const s=ve.Vector3[1];_e.TransformCoordinatesToRef(i,ve.Matrix[1],s),s.normalize();const r=-Math.atan2(s.z,s.x)+Math.PI/2,n=Math.sqrt(s.x*s.x+s.z*s.z),o=-Math.atan2(s.y,n);if(fe.RotationYawPitchRollToRef(r,o,0,ve.Quaternion[0]),(this.billboardMode&lo.BILLBOARDMODE_ALL)!==lo.BILLBOARDMODE_ALL){const e=ve.Vector3[1];ve.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&lo.BILLBOARDMODE_X)!==lo.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&lo.BILLBOARDMODE_Y)!==lo.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&lo.BILLBOARDMODE_Z)!==lo.BILLBOARDMODE_Z&&(e.z=0),me.RotationYawPitchRollToRef(e.y,e.x,e.z,ve.Matrix[0])}else me.FromQuaternionToRef(ve.Quaternion[0],ve.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ve.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ve.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):r&&r._nonUniformScaling?this._updateNonUniformScalingState(r._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=me.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;tnew lo(e,this.getScene())),this);if(s.name=e,s.id=e,t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;inew lo(e.name,t)),e,t,i);if(e.localMatrix?s.setPreTransformMatrix(me.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(me.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let t=0;t(!t||t(e))&&e instanceof lo)),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const e=this.getChildTransformNodes(!0);for(const t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let s=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),o=n.max.subtract(n.min),a=Math.max(o.x,o.y,o.z);if(0===a)return this;const l=1/a;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&s&&this.rotation.copyFrom(s)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}lo.BILLBOARDMODE_NONE=0,lo.BILLBOARDMODE_X=1,lo.BILLBOARDMODE_Y=2,lo.BILLBOARDMODE_Z=4,lo.BILLBOARDMODE_ALL=7,lo.BILLBOARDMODE_USE_POSITION=128,lo.BillboardUseParentOrientation=!1,lo._TmpRotation=fe.Zero(),lo._TmpScaling=_e.Zero(),lo._TmpTranslation=_e.Zero(),lo._LookAtVectorCache=new _e(0,0,0),lo._RotationAxisCache=new fe,Ze([ht("position")],lo.prototype,"_position",void 0),Ze([ht("rotation")],lo.prototype,"_rotation",void 0),Ze([pt("rotationQuaternion")],lo.prototype,"_rotationQuaternion",void 0),Ze([ht("scaling")],lo.prototype,"_scaling",void 0),Ze([rt("billboardMode")],lo.prototype,"_billboardMode",void 0),Ze([rt()],lo.prototype,"scalingDeterminant",void 0),Ze([rt("infiniteDistance")],lo.prototype,"_infiniteDistance",void 0),Ze([rt()],lo.prototype,"ignoreNonUniformScaling",void 0),Ze([rt()],lo.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class ho{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new _e(0,0,0),this._diffPositionForCollisions=new _e(0,0,0),this._collisionResponse=!0}}class co{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=_e.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class uo{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new co,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=null,this._currentLODIsUpToDate=!1,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new ho,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class _o extends lo{static get BILLBOARDMODE_NONE(){return lo.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return lo.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return lo.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return lo.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return lo.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return lo.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return!!super._updateNonUniformScalingState(e)&&(this._markSubMeshesAsMiscDirty(),!0)}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;const t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty((e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()}))}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){return this._internalAbstractMeshDataInfo._materialForRenderPass?.[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}get _positions(){return null}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new uo,this._waitingMaterialId=null,this.cullingStrategy=_o.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new K,this.onCollisionPositionChangeObservable=new K,this.onMaterialChangedObservable=new K,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this.isVisible=!0,this.isPickable=!0,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=Ee.Red(),this.outlineWidth=.02,this.overlayColor=Ee.Red(),this.overlayAlpha=.5,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.alwaysSelectAsActiveMesh=!1,this.doNotSyncBoundingInfo=!1,this.actionManager=null,this.ellipsoid=new _e(.5,1,.5),this.ellipsoidOffset=new _e(0,0,0),this.edgesWidth=1,this.edgesColor=new Ae(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new K,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>oo.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new Zs(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case Vr.Aggressive:this.doNotSyncBoundingInfo=!0;case Vr.Intermediate:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){const t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()}getMeshUniformBuffer(){return this._uniformBuffer}getClassName(){return"AbstractMesh"}toString(e){let t="Name: "+this.name+", isInstance: "+("InstancedMesh"!==this.getClassName()?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);const i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==lo.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),null!==this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes){for(const e of this.subMeshes)e._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let s=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;s=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(s)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;it.markAsLightDirty(e)))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty((e=>e.markAsAttributesDirty()))}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty((e=>e.markAsMiscDirty()))}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,s){return this}updateVerticesData(e,t,i,s){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new Ln(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(er.MatricesIndicesKind)&&this.isVerticesDataPresent(er.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===lo.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){const s=new me;(this.rotationQuaternion?this.rotationQuaternion:fe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const r=_e.Zero(),n=this.definedFacingForward?-1:1;return _e.TransformCoordinatesFromFloatsToRef(e*n,t,i*n,s,r),r}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const s=this.definedFacingForward?1:-1;return new _e(e*s,t,i*s)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){const i=Vn(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new Ln(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t4,n=r?this.getVerticesData(er.MatricesIndicesExtraKind):null,o=r?this.getVerticesData(er.MatricesWeightsExtraKind):null,a=this.skeleton.getTransformMatrices(this),l=ve.Vector3[0],h=ve.Matrix[0],c=ve.Matrix[1];let u=0;for(let d=0;d0&&(me.FromFloat32ArrayToRefScaled(a,Math.floor(16*e[u+_]),p,c),h.addToSelf(c));if(r)for(_=0;_<4;_++)p=o[u+_],p>0&&(me.FromFloat32ArrayToRefScaled(a,Math.floor(16*n[u+_]),p,c),h.addToSelf(c));s===er.NormalKind?_e.TransformNormalFromFloatsToRef(i[d],i[d+1],i[d+2],h,l):_e.TransformCoordinatesFromFloatsToRef(i[d],i[d+1],i[d+2],h,l),l.toArray(i,d),s===er.PositionKind&&this._positions&&this._positions[d/3].copyFrom(l)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,er.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,er.PositionKind)}_getPositionData(e,t){let i=this.getVerticesData(er.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),i&&(e&&this.skeleton||t&&this.morphTargetManager)){if(i=i.slice(),this._generatePointsArray(),this._positions){const e=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(e.length);for(let t=0;t1||!s.IsGlobal)&&s.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const s=this.getBoundingInfo(),r=e.getBoundingInfo();if(s.intersects(r,t))return!0;if(i)for(const i of this.getChildMeshes())if(i.intersectsMesh(e,t,!0))return!0;return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);const t=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=t.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,t.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const i=e.verticesStart,s=e.verticesStart+e.verticesCount;for(let r=i;r1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=ve.Matrix[0],i=ve.Matrix[1];return me.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,s=!1,r,n=!1){const o=new tr,a=this.getClassName(),l="InstancedLinesMesh"===a||"LinesMesh"===a||"GreasedLineMesh"===a?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes)return o;if(!(n||e.intersectsSphere(h.boundingSphere,l)&&e.intersectsBox(h.boundingBox,l)))return o;if(s)return o.hit=!n,o.pickedMesh=n?null:this,o.distance=n?0:_e.Distance(e.origin,h.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let c=null;const u=this._scene.getIntersectingSubMeshCandidates(this,e),d=u.length;let _=!1;for(let e=0;e1&&!n&&!r.canIntersects(e))continue;const o=r.intersects(e,this._positions,this.getIndices(),t,i);if(o&&(t||!c||o.distancee!==this&&e.actionManager===this.actionManager))||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(this),-1!==t&&e.excludedMeshes.splice(t,1);const i=e.getShadowGenerators();if(i){const e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){const e=i.value.getShadowMap();e&&e.renderList&&(t=e.renderList.indexOf(this),-1!==t&&e.renderList.splice(t,1))}}})),"InstancedMesh"===this.getClassName()&&"InstancedLinesMesh"===this.getClassName()||this.releaseSubMeshes();const r=s.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,r.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),r.wipeCaches(),s.removeMesh(this),this._parentContainer){const e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:_e.Zero()}e.depthSortedFacets=[];for(let t=0;tJ?r.maximum.x-r.minimum.x:J,e.bbSize.y=r.maximum.y-r.minimum.y>J?r.maximum.y-r.minimum.y:J,e.bbSize.z=r.maximum.z-r.minimum.z>J?r.maximum.z-r.minimum.z:J;let n=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(n=n>e.bbSize.z?n:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/n),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/n),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/n),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=r,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),_e.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&Wn.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let s=0;sr.subDiv.max||o<0||o>r.subDiv.max||a<0||a>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*o+r.subDiv.max*r.subDiv.max*a]}getClosestFacetAtCoordinates(e,t,i,s,r=!1,n=!0){const o=this.getWorldMatrix(),a=ve.Matrix[5];o.invertToRef(a);const l=ve.Vector3[8];_e.TransformCoordinatesFromFloatsToRef(e,t,i,a,l);const h=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,s,r,n);return s&&_e.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,o,s),h}getClosestFacetAtLocalCoordinates(e,t,i,s,r=!1,n=!0){let o=null,a=0,l=0,h=0,c=0,u=0,d=0,_=0,p=0;const f=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;let v,x,b,T=Number.MAX_VALUE,y=T;for(let S=0;S=0||r&&!n&&c<=0)&&(c=x.x*b.x+x.y*b.y+x.z*b.z,u=-(x.x*e+x.y*t+x.z*i-c)/(x.x*x.x+x.y*x.y+x.z*x.z),d=e+x.x*u,_=t+x.y*u,p=i+x.z*u,a=d-e,l=_-t,h=p-i,y=a*a+l*l+h*h,ye.emitter===this))}}_o.OCCLUSION_TYPE_NONE=0,_o.OCCLUSION_TYPE_OPTIMISTIC=1,_o.OCCLUSION_TYPE_STRICT=2,_o.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,_o.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,_o.CULLINGSTRATEGY_STANDARD=0,_o.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,_o.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,_o.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,z("BABYLON.AbstractMesh",_o);class po{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681}get func(){return this._func}set func(e){this._func=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){St.Clone((()=>e),this)}serialize(){return St.Serialize(this)}parse(e,t,i){St.Parse((()=>this),e,t,i)}}var fo;function mo(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}function go(e,t,i){const s=!!(e.clipPlane??t.clipPlane),r=!!(e.clipPlane2??t.clipPlane2),n=!!(e.clipPlane3??t.clipPlane3),o=!!(e.clipPlane4??t.clipPlane4),a=!!(e.clipPlane5??t.clipPlane5),l=!!(e.clipPlane6??t.clipPlane6);s&&i.push("#define CLIPPLANE"),r&&i.push("#define CLIPPLANE2"),n&&i.push("#define CLIPPLANE3"),o&&i.push("#define CLIPPLANE4"),a&&i.push("#define CLIPPLANE5"),l&&i.push("#define CLIPPLANE6")}function vo(e,t,i){let s=!1;const r=!!(e.clipPlane??t.clipPlane),n=!!(e.clipPlane2??t.clipPlane2),o=!!(e.clipPlane3??t.clipPlane3),a=!!(e.clipPlane4??t.clipPlane4),l=!!(e.clipPlane5??t.clipPlane5),h=!!(e.clipPlane6??t.clipPlane6);return i.CLIPPLANE!==r&&(i.CLIPPLANE=r,s=!0),i.CLIPPLANE2!==n&&(i.CLIPPLANE2=n,s=!0),i.CLIPPLANE3!==o&&(i.CLIPPLANE3=o,s=!0),i.CLIPPLANE4!==a&&(i.CLIPPLANE4=a,s=!0),i.CLIPPLANE5!==l&&(i.CLIPPLANE5=l,s=!0),i.CLIPPLANE6!==h&&(i.CLIPPLANE6=h,s=!0),s}function xo(e,t,i){let s=t.clipPlane??i.clipPlane;bo(e,"vClipPlane",s),s=t.clipPlane2??i.clipPlane2,bo(e,"vClipPlane2",s),s=t.clipPlane3??i.clipPlane3,bo(e,"vClipPlane3",s),s=t.clipPlane4??i.clipPlane4,bo(e,"vClipPlane4",s),s=t.clipPlane5??i.clipPlane5,bo(e,"vClipPlane5",s),s=t.clipPlane6??i.clipPlane6,bo(e,"vClipPlane6",s)}function bo(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}Ze([rt()],po.prototype,"func",null),Ze([rt()],po.prototype,"funcRef",null),Ze([rt()],po.prototype,"funcMask",null),Ze([rt()],po.prototype,"opStencilFail",null),Ze([rt()],po.prototype,"opDepthFail",null),Ze([rt()],po.prototype,"opStencilDepthPass",null),Ze([rt()],po.prototype,"mask",null),Ze([rt()],po.prototype,"enabled",null),function(e){e[e.Created=1]="Created",e[e.Disposed=2]="Disposed",e[e.GetDefineNames=4]="GetDefineNames",e[e.PrepareUniformBuffer=8]="PrepareUniformBuffer",e[e.IsReadyForSubMesh=16]="IsReadyForSubMesh",e[e.PrepareDefines=32]="PrepareDefines",e[e.BindForSubMesh=64]="BindForSubMesh",e[e.PrepareEffect=128]="PrepareEffect",e[e.GetAnimatables=256]="GetAnimatables",e[e.GetActiveTextures=512]="GetActiveTextures",e[e.HasTexture=1024]="HasTexture",e[e.FillRenderTargetTextures=2048]="FillRenderTargetTextures",e[e.HasRenderTargetTextures=4096]="HasRenderTargetTextures",e[e.HardBindForSubMesh=8192]="HardBindForSubMesh"}(fo||(fo={}));const To=Ee.Black(),yo={NUM_MORPH_INFLUENCERS:0};function So(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=i.activeCamera;1===e.mode&&Ne.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}function Co(e,t,i,s=!1){i&&e.fogEnabled&&(!t||t.applyFog)&&0!==e.fogMode&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),s?(e.fogColor.toLinearSpaceToRef(To,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",To)):i.setColor3("vFogColor",e.fogColor))}function Eo(e,t,i){yo.NUM_MORPH_INFLUENCERS=i,Ao(e,t,yo)}function Ao(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&re.LastCreatedEngine){const r=re.LastCreatedEngine.getCaps().maxVertexAttribs,n=t.morphTargetManager;if(n?.isUsingTextureForTargets)return;const o=n&&n.supportsNormals&&i.NORMAL,a=n&&n.supportsTangents&&i.TANGENT,l=n&&n.supportsUVs&&i.UV1;for(let i=0;ir&&Ne.Error("Cannot add more vertex attributes for mesh "+t.name)}}function Po(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}function Io(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}function Ro(e,t){t.bindToEffect(e,"Scene")}function Mo(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}function Oo(e,t,i){const s=e.getTextureMatrix();t.updateMatrix(i+"Matrix",s)}function Do(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}function wo(e,t,i){var s;if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const r=e.skeleton;if(r.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){const i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{const n=r.getTransformMatrices(e);n&&(t.setMatrices("mBones",n),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=n.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),s=n,i.previousBones[e.uniqueId].set(s)))}}}function No(e,t,i){e.transferToEffect(t,i+"")}function Fo(e,t,i,s,r,n=!0){e._bindLight(t,i,s,r,n)}function Lo(e,t,i,s,r=4){const n=Math.min(t.lightSources.length,r);for(let r=0;r0&&(s.addCPUSkinningFallback(0,t),e.push("matricesIndices"),e.push("matricesWeights"),i.NUM_BONE_INFLUENCERS>4&&(e.push("matricesIndicesExtra"),e.push("matricesWeightsExtra")))}function ko(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&Po(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push("instanceColor")}function Vo(e,t,i=4,s=0){let r=0;for(let n=0;n0&&(r=s+n,t.addFallback(r,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(s,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(s,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(s,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(s,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(s,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(s,"SHADOWCLOSEESM"+n));return r++}function Uo(e,t){return t.fogEnabled&&e.applyFog&&0!==t.fogMode}function Go(e,t,i,s,r,n,o,a=!1){o._areMiscDirty&&(o.LOGARITHMICDEPTH=i,o.POINTSIZE=s,o.FOG=r&&Uo(e,t),o.NONUNIFORMSCALING=e.nonUniformScaling,o.ALPHATEST=n,o.DECAL_AFTER_DETAIL=a)}function zo(e,t,i,s,r=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let o=0;const a={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n)for(const n of t.lightSources)if(Wo(e,t,n,o,i,s,a),o++,o===r)break;i.SPECULARTERM=a.specularEnabled,i.SHADOWS=a.shadowEnabled;for(let e=o;e0&&(o.shadowEnabled=!0,t.prepareDefines(r,s))}}i.lightmapMode!=Br.LIGHTMAP_DEFAULT?(o.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+s]=!0,r["LIGHTMAPNOSPECULAR"+s]=i.lightmapMode==Br.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+s]=!1,r["LIGHTMAPNOSPECULAR"+s]=!1)}function Ho(e,t,i,s,r,n=null,o=!1){let a=Zo(e,s);!1!==n&&(a=vo(i,e,s)),s.DEPTHPREPASS!==!t.getColorWrite()&&(s.DEPTHPREPASS=!s.DEPTHPREPASS,a=!0),s.INSTANCES!==r&&(s.INSTANCES=r,a=!0),s.THIN_INSTANCES!==o&&(s.THIN_INSTANCES=o,a=!0),a&&s.markAsUnprocessed()}function Xo(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;const s=e.getScene().prePassRenderer;if(s&&s.enabled){const i=-1===s.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}function Yo(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.NUM_MORPH_INFLUENCERS=i.numMaxInfluencers||i.numInfluencers,t.MORPHTARGETS=t.NUM_MORPH_INFLUENCERS>0,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}function Qo(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}function jo(e,t,i,s,r=!1,n=!0,o=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent("normal"),t._needNormals&&e.isVerticesDataPresent("tangent")&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){const i=e.useVertexColors&&e.isVerticesDataPresent("color");t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&n}return e.isVerticesDataPresent("instanceColor")&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),s&&Xo(e,t),r&&Yo(e,t),o&&Qo(e,t),!0}function Ko(e,t){if(e.activeCamera){const i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}function $o(e,t,i){const s=t.ORDER_INDEPENDENT_TRANSPARENCY,r=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,s===t.ORDER_INDEPENDENT_TRANSPARENCY&&r===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}function qo(e,t,i){const s=t.PREPASS;if(!t._arePrePassDirty)return;const r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let i=0;i{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const s=t||re.LastCreatedScene;s&&(this._scene=s,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||Ds.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Un(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=ta.ClockWiseSideOrientation:this.sideOrientation=ta.CounterClockWiseSideOrientation,this._uniformBuffer=new Zs(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),ta.OnEventObservable.notifyObservers(this,fo.Created))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const s=t.materialDefines;return!!s&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===ta.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===ta.MATERIAL_OPAQUE||this._transparencyMode===ta.MATERIAL_ALPHATEST}needAlphaBlending(){return!this._disableAlphaBlending&&this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1||!this._disableAlphaBlending&&(e.hasVertexAlpha||this.needAlphaBlending())}needAlphaTesting(){return!!this._forceAlphaTest}_shouldTurnAlphaTestOn(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)if(t.getMaterial()===this)for(const i of t._drawWrappers)i&&this._materialContext===i.materialContext&&(i._wasPreviouslyReady=!1,i._wasPreviouslyUsingInstances=null,i._forceRebindOnNextCall=e);e&&this.markAsDirty(ta.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),s=(null==t?this.sideOrientation:t)===ta.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(fo.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const s=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),s._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,Ro(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),this._scene._cachedVisibility=e?e.visibility:1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){const e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){const e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(fo.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(fo.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(fo.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),ta._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const t of this.pluginManager._plugins){const i=e.pluginManager.getPlugin(t.name);i&&t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}return this._scene.meshes.filter((e=>e.material===this))}forceCompilation(e,t,i,s){const r={clipPlane:!1,useInstances:!1,...i},n=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const a=()=>{if(!this._scene||!this._scene.getEngine())return;const i=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new Nr(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,n=null;if(e.subMeshes){const t=new Gn(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,r.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?n=t.effect.getCompilationError():(i=!1,setTimeout(a,16)))}i&&(this.allowShaderHotSwapping=o,n&&s&&s(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(a,16);r.clipPlane&&(n.clipPlane=i)};a()}forceCompilationAsync(e,t){return new Promise(((i,s)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{s(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(ta._DirtyCallbackArray.length=0,e&ta.TextureDirtyFlag&&ta._DirtyCallbackArray.push(ta._TextureDirtyCallBack),e&ta.LightDirtyFlag&&ta._DirtyCallbackArray.push(ta._LightsDirtyCallBack),e&ta.FresnelDirtyFlag&&ta._DirtyCallbackArray.push(ta._FresnelDirtyCallBack),e&ta.AttributesDirtyFlag&&ta._DirtyCallbackArray.push(ta._AttributeDirtyCallBack),e&ta.MiscDirtyFlag&&ta._DirtyCallbackArray.push(ta._MiscDirtyCallBack),e&ta.PrePassDirtyFlag&&ta._DirtyCallbackArray.push(ta._PrePassDirtyCallBack),ta._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(ta._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const e of t.subMeshes)e.getMaterial()===this&&e.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)if(t.getMaterial(!1)===this)for(const i of t._drawWrappers)i&&i.defines&&i.defines.markAllAsDirty&&this._materialContext===i.materialContext&&e(i.defines)}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(ta._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(ta._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(ta._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(ta._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(ta._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(ta._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(ta._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(ta._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(ta._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(ta._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==Vr.BackwardCompatible){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce((()=>{this.checkReadyOnlyOnce=!1}));this.onDisposeObservable.add((()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)}))}}setPrePassRenderer(e){return!1}dispose(e,t,i){const s=this.getScene();if(s.stopAnimation(this),s.freeProcessedMaterials(),s.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(fo.Disposed,this._eventInfo),this._parentContainer){const e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i)if(this.meshMap)for(const t in this.meshMap){const i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{const t=s.meshes;for(const i of t)i.material!==this||i.sourceMesh||(i.material=null,this.releaseVertexArrayObject(i,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const s of e.subMeshes)i._releaseVertexArrayObject(s.effect),t&&s.effect&&s.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=St.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(const t of this.pluginManager._plugins)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,i){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return Ne.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else e.customType="BABYLON.StandardMaterial";const s=Ds.Instantiate(e.customType).Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _ParsePlugins(e,t,i,s){if(e.plugins)for(const r in e.plugins){const n=e.plugins[r];let o=t.pluginManager?.getPlugin(n.name);if(!o){const e=Ds.Instantiate("BABYLON."+r);e&&(o=new e(t))}o?.parse(n,i,s)}}}ta.TriangleFillMode=0,ta.WireFrameFillMode=1,ta.PointFillMode=2,ta.PointListDrawMode=3,ta.LineListDrawMode=4,ta.LineLoopDrawMode=5,ta.LineStripDrawMode=6,ta.TriangleStripDrawMode=7,ta.TriangleFanDrawMode=8,ta.ClockWiseSideOrientation=0,ta.CounterClockWiseSideOrientation=1,ta.TextureDirtyFlag=1,ta.LightDirtyFlag=2,ta.FresnelDirtyFlag=4,ta.AttributesDirtyFlag=8,ta.MiscDirtyFlag=16,ta.PrePassDirtyFlag=32,ta.AllDirtyFlag=63,ta.MATERIAL_OPAQUE=0,ta.MATERIAL_ALPHATEST=1,ta.MATERIAL_ALPHABLEND=2,ta.MATERIAL_ALPHATESTANDBLEND=3,ta.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,ta.MATERIAL_NORMALBLENDMETHOD_RNM=1,ta.OnEventObservable=new K,ta._AllDirtyCallBack=e=>e.markAllAsDirty(),ta._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),ta._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),ta._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),ta._MiscDirtyCallBack=e=>e.markAsMiscDirty(),ta._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),ta._LightsDirtyCallBack=e=>e.markAsLightDirty(),ta._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),ta._FresnelAndMiscDirtyCallBack=e=>{ta._FresnelDirtyCallBack(e),ta._MiscDirtyCallBack(e)},ta._TextureAndMiscDirtyCallBack=e=>{ta._TextureDirtyCallBack(e),ta._MiscDirtyCallBack(e)},ta._DirtyCallbackArray=[],ta._RunDirtyCallBacks=e=>{for(const t of ta._DirtyCallbackArray)t(e)},Ze([rt()],ta.prototype,"id",void 0),Ze([rt()],ta.prototype,"uniqueId",void 0),Ze([rt()],ta.prototype,"name",void 0),Ze([rt()],ta.prototype,"metadata",void 0),Ze([rt()],ta.prototype,"checkReadyOnEveryCall",void 0),Ze([rt()],ta.prototype,"checkReadyOnlyOnce",void 0),Ze([rt()],ta.prototype,"state",void 0),Ze([rt("alpha")],ta.prototype,"_alpha",void 0),Ze([rt("backFaceCulling")],ta.prototype,"_backFaceCulling",void 0),Ze([rt("cullBackFaces")],ta.prototype,"_cullBackFaces",void 0),Ze([rt()],ta.prototype,"sideOrientation",void 0),Ze([rt("alphaMode")],ta.prototype,"_alphaMode",void 0),Ze([rt()],ta.prototype,"_needDepthPrePass",void 0),Ze([rt()],ta.prototype,"disableDepthWrite",void 0),Ze([rt()],ta.prototype,"disableColorWrite",void 0),Ze([rt()],ta.prototype,"forceDepthWrite",void 0),Ze([rt()],ta.prototype,"depthFunction",void 0),Ze([rt()],ta.prototype,"separateCullingPass",void 0),Ze([rt("fogEnabled")],ta.prototype,"_fogEnabled",void 0),Ze([rt()],ta.prototype,"pointSize",void 0),Ze([rt()],ta.prototype,"zOffset",void 0),Ze([rt()],ta.prototype,"zOffsetUnits",void 0),Ze([rt()],ta.prototype,"pointsCloud",null),Ze([rt()],ta.prototype,"fillMode",null),Ze([rt()],ta.prototype,"useLogarithmicDepth",null),Ze([rt()],ta.prototype,"transparencyMode",null);class ia extends ta{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);return this._markAllSubMeshesAsTexturesDirty(),r}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map((e=>e?e.getActiveTextures():[])))}hasTexture(e){if(super.hasTexture(e))return!0;for(let t=0;t=0&&s.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new ia(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,Tt&&Tt.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}z("BABYLON.MultiMaterial",ia);class sa{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class ra{}class na{constructor(){this.visibleInstances={},this.batchCache=new oa,this.batchCacheReplacementModeInFrozenMode=new oa,this.instancesBufferSize=2048}}class oa{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class aa{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class la{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}}class ha extends _o{static _GetDefaultSideOrientation(e){return e||ha.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(er.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(er.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new K),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new K),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new K),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new K),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new K),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}constructor(e,t=null,i=null,s=null,r,n=!0){if(super(e,t),this._internalMeshDataInfo=new la,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new na,this._thinInstanceDataStorage=new aa,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=ha.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,i)=>{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},s){if(s._geometry&&s._geometry.applyToMesh(this),Ye.DeepCopy(s,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=s,t.useClonedMeshMap&&(s._internalMeshDataInfo.meshMap||(s._internalMeshDataInfo.meshMap={}),s._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=s._originalBuilderSideOrientation,this._creationDataStorage=s._creationDataStorage,s._ranges){const e=s._ranges;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,Tt&&Tt.HasTags(s)&&Tt.AddTagsTo(this,Tt.GetTags(s,!0)),this.setEnabled(s.isEnabled(!1)),this.parent=s.parent,this.setPivotMatrix(s.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=e+"."+s.id,this.material=s.material,!r){const t=s.getDescendants(!0);for(let i=0;i{e.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add((()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))})))},this.onMeshReadyObservable=new K(this._internalMeshDataInfo._onMeshReadyObserverAdded),s&&s.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const s=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));s.parent=e||this.parent,s.position=this.position.clone(),s.scaling=this.scaling.clone(),this.rotationQuaternion?s.rotationQuaternion=this.rotationQuaternion.clone():s.rotation=this.rotation.clone(),i&&i(this,s);for(const e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===s.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(s,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:s},i):e.instantiateHierarchy(s,t,i);return s}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort(((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0))}addLODLevel(e,t){if(t&&t._masterMesh)return Ne.Warn("You cannot use a mesh as LOD level twice"),this;const i=new sa(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let i=0;io*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let e=0;e0||this.hasThinInstances);this.computeWorldMatrix();const n=this.material||s.defaultMaterial;if(n)if(n._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,r))return!1}else if(!t.isReady(this,r))return!1}else if(!n.isReady(this,r))return!1;const o=i.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const s=t.values();for(let e=s.next();!0!==e.done;e=s.next()){const t=e.value;if(t&&(!t.getShadowMap()?.renderList||t.getShadowMap()?.renderList&&-1!==t.getShadowMap()?.renderList?.indexOf(this))){const e=t.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let s=0;s0){const i=this.getIndices();if(!i)return null;const s=i.length;let r=!1;if(e)r=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>s){r=!0;break}if(e.verticesStart+e.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new Gn(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,s=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let r=0;r=t);r++)Gn.CreateFromIndices(0,s,r===e-1?t-s:i,this,void 0,!1),s+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,s){if(this._geometry)this._geometry.setVerticesData(e,t,i,s);else{const s=new Wn;s.set(t,e);const r=this.getScene();new Yn(Yn.RandomId(),r,s,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=Yn.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,s){return this._geometry?(s?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(er.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(er.PositionKind,i,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(er.NormalKind);if(!t)return this;Wn.ComputeNormals(i,e,t),this.updateVerticesData(er.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(1===this._geometry.meshes.length)return this;const e=this._geometry,t=this._geometry.copy(Yn.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let s=this._geometry;s||(s=new Yn(Yn.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const t=new Wn;t.indices=e;const s=this.getScene();new Yn(Yn.RandomId(),s,t,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,s=!0){if(!this._geometry)return this;const r=this.getScene().getEngine();let n;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)n=null;else switch(this._getRenderingFillMode(i)){case ta.PointFillMode:n=null;break;case ta.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case ta.TriangleFillMode:n=this._geometry.getIndexBuffer()}return s&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,n,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,n),this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const s=this.getScene().getEngine();return this._unIndexed||t==ta.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==ta.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):s.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const i=this.getScene(),s=i._isInIntermediateRendering(),r=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,r=i.getRenderId(),o=s?t.intermediateDefaultRenderId:t.defaultRenderId;n.visibleInstances[e]=t[r],!n.visibleInstances[e]&&o&&(n.visibleInstances[e]=t[o])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==n.visibleInstances[e]&&void 0!==n.visibleInstances[e],this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,i,s,r){const n=i.visibleInstances[e._id],o=n?n.length:0,a=this._instanceDataStorage,l=a.instancesBufferSize;let h=a.instancesBuffer,c=a.instancesPreviousBuffer;const u=16*(o+1)*4;for(;a.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera1&&s.activeCamera===s.activeCameras[0]||r<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const n=this._getInstancesRenderList(e._id,!!i);if(n.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const o=s.getEngine();let a=0,l=null;this.ignoreCameraMaxZ&&s.activeCamera&&!s._isInIntermediateRendering()&&(a=s.activeCamera.maxZ,l=s.activeCamera,s.activeCamera.maxZ=0,s.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const h=e.getRenderingMesh(),c=n.hardwareInstancedRendering[e._id]||h.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,u=this._instanceDataStorage,d=e.getMaterial();if(!d)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;if(u.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===d){if(d._storeEffectOnSubMeshes&&!e._drawWrapper?._wasPreviouslyReady||!d._storeEffectOnSubMeshes&&!d._getDrawWrapper()._wasPreviouslyReady)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this}else{if(d._storeEffectOnSubMeshes){if(!d.isReadyForSubMesh(this,e,c))return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this}else if(!d.isReady(this,c))return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=d}let _;t&&o.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),_=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const p=_?.effect??null;for(const t of s._beforeRenderingMeshStage)t.action(this,e,n,p);if(!_||!p)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;const f=i||this;let m;if(u.isFrozen||!this._internalMeshDataInfo._effectiveMaterial.backFaceCulling&&null===this.overrideMaterialSideOrientation&&!this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)m=u.sideOrientation;else{const e=f._getWorldMatrixDeterminant();m=this.overrideMaterialSideOrientation,null==m&&(m=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(m=m===ta.ClockWiseSideOrientation?ta.CounterClockWiseSideOrientation:ta.ClockWiseSideOrientation),u.sideOrientation=m}const g=this._internalMeshDataInfo._effectiveMaterial._preBind(_,m);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&o.setDepthWrite(!0);const v=this._internalMeshDataInfo._effectiveMaterial,x=v.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),c||this._bind(e,p,x,!1);const b=f.getWorldMatrix();v._storeEffectOnSubMeshes?v.bindForSubMesh(b,this,e):v.bind(b,this),!v.backFaceCulling&&v.separateCullingPass&&(o.setState(!0,v.zOffset,!1,!g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._processRendering(this,e,p,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),o.setState(!0,v.zOffset,!1,g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,p,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const t of s._afterRenderingMeshStage)t.action(this,e,n,p);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),l&&(l.maxZ=a,s.updateTransformMatrix(!0)),s.performancePriority!==Vr.Aggressive||u.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(er.MatricesWeightsKind)&&(this.isVerticesDataPresent(er.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(er.MatricesWeightsKind),t=e.length;for(let i=0;ii&&s++,0!==n&&u++,c+=n,i=n}if(l[u]++,u>n&&(n=u),0===c)r++;else{const i=1/c;let s=0;for(let r=0;r.001&&o++}}const h=this.skeleton.bones.length,c=this.getVerticesData(er.MatricesIndicesKind),u=this.getVerticesData(er.MatricesIndicesExtraKind);let d=0;for(let e=0;e=h||i<0)&&d++}return{skinned:!0,valid:0===r&&0===o&&0===d,report:"Number of Weights = "+i/4+"\nMaximum influences = "+n+"\nMissing Weights = "+r+"\nNot Sorted = "+s+"\nNot Normalized = "+o+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+d}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return Ds.LoadFile(this.delayLoadingFile,(t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach((e=>{e.refreshBoundingInfo(),e._syncSubMeshes()})),this.delayLoadState=1,e.removePendingData(this)}),(()=>{}),e.offlineProvider,t),this}isInFrustum(e){return 2!==this.delayLoadState&&!!super.isInFrustum(e)&&(this._checkDelayState(),!0)}setMaterialById(e){const t=this.getScene().materials;let i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;const s=this.getScene().multiMaterials;for(i=s.length-1;i>-1;i--)if(s[i].id===e)return this.material=s[i],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(er.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(er.PositionKind);const s=_e.Zero();let r;for(r=0;r{const a=e.width,l=e.height,h=this.getEngine().createCanvas(a,l).getContext("2d");h.drawImage(e,0,0);const c=h.getImageData(0,0,a,l).data;this.applyDisplacementMapFromBuffer(c,a,l,t,i,r,n,o),s&&s(this)}),a||(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,r,n,o,a=!1){if(!this.isVerticesDataPresent(er.PositionKind)||!this.isVerticesDataPresent(er.NormalKind)||!this.isVerticesDataPresent(er.UVKind))return Ne.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(er.PositionKind,!0,!0),h=this.getVerticesData(er.NormalKind),c=this.getVerticesData(er.UVKind);let u=_e.Zero();const d=_e.Zero(),_=de.Zero();n=n||de.Zero(),o=o||new de(1,1);for(let a=0;a{const s=new Float32Array(i.length*t);let r=0;for(let n=0;n{const t=s.length-1-e,i=s[t];for(let e=0;e{for(let e=0;e-1&&(s.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(s.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(s.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t4,l=a?this.getVerticesData(er.MatricesIndicesExtraKind):null,h=a?this.getVerticesData(er.MatricesWeightsExtraKind):null,c=e.getTransformMatrices(this),u=_e.Zero(),d=new me,_=new me;let p,f=0;for(let e=0;e0&&(me.FromFloat32ArrayToRefScaled(c,Math.floor(16*n[f+p]),m,_),d.addToSelf(_));if(a)for(p=0;p<4;p++)m=h[f+p],m>0&&(me.FromFloat32ArrayToRefScaled(c,Math.floor(16*l[f+p]),m,_),d.addToSelf(_));_e.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],d,u),u.toArray(s,e),t&&(_e.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],d,u),u.toArray(r,e)),d.reset()}return this.updateVerticesData(er.PositionKind,s),t&&this.updateVerticesData(er.NormalKind,r),this}static MinMax(e){let t=null,i=null;return e.forEach((function(e){const s=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(s.minimumWorld),i.maximizeInPlace(s.maximumWorld)):(t=s.minimumWorld,i=s.maximumWorld)})),t&&i?{min:t,max:i}:{min:_e.Zero(),max:_e.Zero()}}static Center(e){const t=e instanceof Array?ha.MinMax(e):e;return _e.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,r,n){return Sn(ha._MergeMeshesCoroutine(e,t,i,s,r,n,!1))}static MergeMeshesAsync(e,t=!0,i,s,r,n){return Cn(ha._MergeMeshesCoroutine(e,t,i,s,r,n,!0),Tn())}static*_MergeMeshesCoroutine(e,t=!0,i,s,r,n,o){if(0===(e=e.filter(Boolean)).length)return null;let a;if(!i){let t=0;for(a=0;a=65536)return Ne.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(r=!1);const l=new Array,h=new Array,c=new Array,u=e[0].overrideMaterialSideOrientation;for(a=0;a{const t=e.computeWorldMatrix(!0);return{vertexData:Wn.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:p,transform:f}=_(d);o&&(yield);const m=new Array(e.length-1);for(let t=1;t{throw xt("GroundMesh")},ha._GoldbergMeshParser=(e,t)=>{throw xt("GoldbergMesh")},ha._LinesMeshParser=(e,t)=>{throw xt("LinesMesh")},ha._GreasedLineMeshParser=(e,t)=>{throw xt("GreasedLineMesh")},ha._GreasedLineRibbonMeshParser=(e,t)=>{throw xt("GreasedLineRibbonMesh")},ha._TrailMeshParser=(e,t)=>{throw xt("TrailMesh")},z("BABYLON.Mesh",ha),ha._instancedMeshFactory=(e,t)=>{const i=new ca(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class ca extends _o{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const e of t.getAnimationRanges())null!=e&&this.createAnimationRange(e.name,e.from,e.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){this._sourceMesh?.receiveShadows!==e&&Ds.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){this._sourceMesh?.material!==e&&Ds.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){this._sourceMesh?.visibility!==e&&Ds.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){this._sourceMesh?.skeleton!==e&&Ds.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){this._sourceMesh&&e!==this._sourceMesh.renderingGroupId&&Ne.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,s),this.sourceMesh}updateVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,s),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||Ne.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),t){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1}_postActivate(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)}getWorldMatrix(){if(this._currentLOD&&this._currentLOD.billboardMode!==lo.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new me);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,ve.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(ve.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;const t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){const t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e0&&-1===this.includedOnlyMeshes.indexOf(e)||this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)||!(0===this.includeOnlyWithLayerMask||this.includeOnlyWithLayerMask&e.layerMask)||0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(const e of this.getScene().meshes)e._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){const i=ua.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=St.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=St.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0&&(e.excludedMeshesIds=[],this.excludedMeshes.forEach((t=>{e.excludedMeshesIds.push(t.id)}))),this.includedOnlyMeshes.length>0&&(e.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((t=>{e.includedOnlyMeshesIds.push(t.id)}))),St.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){return Et.Construct("Light_Type_"+e,t,i)||null}static Parse(e,t){const i=ua.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=St.Parse(i,e,t);if(e.excludedMeshesIds&&(s._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(s._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(s.falloffType=e.falloffType),void 0!==e.lightmapMode&&(s.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t{const s=t.apply(e,i);for(const e of i)e._resyncLightSource(this);return s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);for(const e of r)e._resyncLightSource(this);return r};for(const t of e)t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);return this._resyncMeshes(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);return this._resyncMeshes(),r},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===ua.INTENSITYMODE_AUTOMATIC&&(i=t===ua.LIGHTTYPEID_DIRECTIONALLIGHT?ua.INTENSITYMODE_ILLUMINANCE:ua.INTENSITYMODE_LUMINOUSINTENSITY),t){case ua.LIGHTTYPEID_POINTLIGHT:case ua.LIGHTTYPEID_SPOTLIGHT:switch(i){case ua.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case ua.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case ua.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case ua.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case ua.INTENSITYMODE_ILLUMINANCE:e=1;break;case ua.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001),e=2*Math.PI*(1-Math.cos(t));break}}break;case ua.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}ua.FALLOFF_DEFAULT=Br.FALLOFF_DEFAULT,ua.FALLOFF_PHYSICAL=Br.FALLOFF_PHYSICAL,ua.FALLOFF_GLTF=Br.FALLOFF_GLTF,ua.FALLOFF_STANDARD=Br.FALLOFF_STANDARD,ua.LIGHTMAP_DEFAULT=Br.LIGHTMAP_DEFAULT,ua.LIGHTMAP_SPECULAR=Br.LIGHTMAP_SPECULAR,ua.LIGHTMAP_SHADOWSONLY=Br.LIGHTMAP_SHADOWSONLY,ua.INTENSITYMODE_AUTOMATIC=Br.INTENSITYMODE_AUTOMATIC,ua.INTENSITYMODE_LUMINOUSPOWER=Br.INTENSITYMODE_LUMINOUSPOWER,ua.INTENSITYMODE_LUMINOUSINTENSITY=Br.INTENSITYMODE_LUMINOUSINTENSITY,ua.INTENSITYMODE_ILLUMINANCE=Br.INTENSITYMODE_ILLUMINANCE,ua.INTENSITYMODE_LUMINANCE=Br.INTENSITYMODE_LUMINANCE,ua.LIGHTTYPEID_POINTLIGHT=Br.LIGHTTYPEID_POINTLIGHT,ua.LIGHTTYPEID_DIRECTIONALLIGHT=Br.LIGHTTYPEID_DIRECTIONALLIGHT,ua.LIGHTTYPEID_SPOTLIGHT=Br.LIGHTTYPEID_SPOTLIGHT,ua.LIGHTTYPEID_HEMISPHERICLIGHT=Br.LIGHTTYPEID_HEMISPHERICLIGHT,Ze([ot()],ua.prototype,"diffuse",void 0),Ze([ot()],ua.prototype,"specular",void 0),Ze([rt()],ua.prototype,"falloffType",void 0),Ze([rt()],ua.prototype,"intensity",void 0),Ze([rt()],ua.prototype,"range",null),Ze([rt()],ua.prototype,"intensityMode",null),Ze([rt()],ua.prototype,"radius",null),Ze([rt()],ua.prototype,"_renderPriority",void 0),Ze([st("_reorderLightsInScene")],ua.prototype,"renderPriority",void 0),Ze([rt("shadowEnabled")],ua.prototype,"_shadowEnabled",void 0),Ze([rt("excludeWithLayerMask")],ua.prototype,"_excludeWithLayerMask",void 0),Ze([rt("includeOnlyWithLayerMask")],ua.prototype,"_includeOnlyWithLayerMask",void 0),Ze([rt("lightmapMode")],ua.prototype,"_lightmapMode",void 0);class da extends X{}class _a{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){this.rootNodes.slice(0).forEach((e=>{e.dispose()})),this.rootNodes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0}}class pa extends X{constructor(e){super(),this._wasAddedToScene=!1,(e=e||re.LastCreatedScene)&&(this.scene=e,this.sounds=[],this.effectLayers=[],this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.reflectionProbes=[],e.onDisposeObservable.add((()=>{this._wasAddedToScene||this.dispose()})),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();for(const e of this.particleSystems)e.rebuild();for(const e of this.textures)e._rebuild()})))}_topologicalSort(e){const t=new Map;for(const i of e)t.set(i.uniqueId,i);const i={dependsOn:new Map,dependedBy:new Map};for(const t of e){const e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(const s of e){const e=s.uniqueId,r=i.dependsOn.get(e);if(s instanceof ca){const n=s.sourceMesh;t.has(n.uniqueId)&&(r.add(n.uniqueId),i.dependedBy.get(n.uniqueId).add(e))}const n=i.dependedBy.get(e);for(const r of s.getDescendants()){const s=r.uniqueId;t.has(s)&&(n.add(s),i.dependsOn.get(s).add(e))}}const s=[],r=[];for(const s of e){const e=s.uniqueId;0===i.dependsOn.get(e).size&&(r.push(s),t.delete(e))}const n=r;for(;n.length>0;){const e=n.shift();s.push(e);const r=i.dependedBy.get(e.uniqueId);for(const s of Array.from(r.values())){const r=i.dependsOn.get(s);r.delete(e.uniqueId),0===r.size&&t.get(s)&&(n.push(t.get(s)),t.delete(s))}}return t.size>0&&(Ne.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>Ne.Error(e.name)))),s}_addNodeAndDescendantsToList(e,t,i,s){if(i&&(!s||s(i))&&!t.has(i.uniqueId)){e.push(i),t.add(i.uniqueId);for(const r of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,r,s)}}_isNodeInContainer(e){return e instanceof _o&&-1!==this.meshes.indexOf(e)||e instanceof lo&&-1!==this.transformNodes.indexOf(e)||e instanceof ua&&-1!==this.lights.indexOf(e)||e instanceof In&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return Ne.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return Ne.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return Ne.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return Ne.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Ds.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},r={},n=new _a,o=[],a=[],l={doNotInstantiate:!0,...i},h=[],c=new Set;for(const e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);for(const e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);const u=this._topologicalSort(h),d=(i,o)=>{if(((t,i)=>{if(s[t.uniqueId]=i.uniqueId,r[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof ha){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;te&&r[s[e.uniqueId]]))}}"InstancedMesh"!==n.getClassName()&&(n.material=r[s[t.uniqueId]])}else"MultiMaterial"===n.material.getClassName()?-1===this.scene.multiMaterials.indexOf(n.material)&&this.scene.addMultiMaterial(n.material):-1===this.scene.materials.indexOf(n.material)&&this.scene.addMaterial(n.material)}null===o.parent&&n.rootNodes.push(o)};return u.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,n=s[i.uniqueId],o=("number"==typeof n?r[n]:i).createInstance(t.name);d(t,o)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);const i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw new Error(`Could not clone or instantiate node on Asset Container ${e.name}`);d(e,i)}})),this.skeletons.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name);for(const e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){const t=r[s[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=i,-1!==o.indexOf(i))continue;o.push(i);for(const e of i.bones)e._linkedTransformNode&&(e._linkedTransformNode=r[s[e._linkedTransformNode.uniqueId]])}n.skeletons.push(i)})),this.animationGroups.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name,(e=>r[s[e.uniqueId]]||e));n.animationGroups.push(i)})),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Ds.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(const e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){const t=[];this.cameras.forEach((i=>{e&&!e(i)||(this.scene.addCamera(i),t.push(i))})),this.lights.forEach((i=>{e&&!e(i)||(this.scene.addLight(i),t.push(i))})),this.meshes.forEach((i=>{e&&!e(i)||(this.scene.addMesh(i),t.push(i))})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.addSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.addAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.addAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.addMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.addMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.addMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.addGeometry(t)})),this.transformNodes.forEach((i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.addActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.addTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.addReflectionProbe(t)}));for(const e of t)e.parent&&-1===this.scene.getNodes().indexOf(e.parent)&&(e.setParent?e.setParent(null):e.parent=null)}removeAllFromScene(){this._isValidHierarchy()||Ds.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach((t=>{e&&!e(t)||this.scene.removeCamera(t)})),this.lights.forEach((t=>{e&&!e(t)||this.scene.removeLight(t)})),this.meshes.forEach((t=>{e&&!e(t)||this.scene.removeMesh(t,!0)})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.removeSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.removeAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.removeMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.removeGeometry(t)})),this.transformNodes.forEach((t=>{e&&!e(t)||this.scene.removeTransformNode(t)})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.removeActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.removeTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)}))}dispose(){this.cameras.slice(0).forEach((e=>{e.dispose()})),this.cameras.length=0,this.lights.slice(0).forEach((e=>{e.dispose()})),this.lights.length=0,this.meshes.slice(0).forEach((e=>{e.dispose()})),this.meshes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach((e=>{e.dispose()})),this.multiMaterials.length=0,this.materials.slice(0).forEach((e=>{e.dispose()})),this.materials.length=0,this.geometries.slice(0).forEach((e=>{e.dispose()})),this.geometries.length=0,this.transformNodes.slice(0).forEach((e=>{e.dispose()})),this.transformNodes.length=0,this.actionManagers.slice(0).forEach((e=>{e.dispose()})),this.actionManagers.length=0,this.textures.slice(0).forEach((e=>{e.dispose()})),this.textures.length=0,this.reflectionProbes.slice(0).forEach((e=>{e.dispose()})),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach((e=>{e.dispose()})),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(e&&t)for(const s of e){let e=!0;if(i)for(const t of i)if(s===t){e=!1;break}e&&(t.push(s),s._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,void 0===e&&(e=new da);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||("_environmentTexture"===t?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new ha("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=re.LastCreatedScene,t,i=null){if(!e)return Ne.Error("No scene available to merge animations to"),[];const s=i||(t=>{let i=null;const s=t.animations.length?t.animations[0].targetProperty:"",r=t.name.split(".").join("").split("_primitive")[0];switch(s){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(r);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(r);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(r)}return i});this.getNodes().forEach((e=>{const t=s(e);if(null!==t){for(const i of e.animations){const e=t.animations.filter((e=>e.targetProperty===i.targetProperty));for(const i of e){const e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}}));const r=[];return this.animationGroups.slice().forEach((e=>{r.push(e.clone(e.name,s)),e.animatables.forEach((e=>{e.stop()}))})),t.forEach((t=>{const i=s(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))})),r}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.transformNodes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.lights.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.cameras.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}))}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const e=t.pop();if(e instanceof ha?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof lo?this.transformNodes.push(e):e instanceof ua?this.lights.push(e):e instanceof In&&this.cameras.push(e),e instanceof _o){if(e.material&&-1===this.materials.indexOf(e.material)){this.materials.push(e.material);for(const t of e.material.getActiveTextures())-1===this.textures.indexOf(t)&&this.textures.push(t)}e.skeleton&&-1===this.skeletons.indexOf(e.skeleton)&&this.skeletons.push(e.skeleton),e.morphTargetManager&&-1===this.morphTargetManagers.indexOf(e.morphTargetManager)&&this.morphTargetManagers.push(e.morphTargetManager)}for(const s of e.getChildren())i.has(s)||t.push(s);i.add(e)}this.populateRootNodes()}}class fa{constructor(e){this.SMOOTHING=.75,this.FFT_SIZE=512,this.BARGRAPHAMPLITUDE=256,this.DEBUGCANVASPOS={x:20,y:20},this.DEBUGCANVASSIZE={width:320,height:200},(e=e||re.LastCreatedScene)&&(this._scene=e,oo.audioEngine?(this._audioEngine=oo.audioEngine,this._audioEngine.canUseWebAudio&&this._audioEngine.audioContext&&(this._webAudioAnalyser=this._audioEngine.audioContext.createAnalyser(),this._webAudioAnalyser.minDecibels=-140,this._webAudioAnalyser.maxDecibels=0,this._byteFreqs=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._byteTime=new Uint8Array(this._webAudioAnalyser.frequencyBinCount),this._floatFreqs=new Float32Array(this._webAudioAnalyser.frequencyBinCount))):Ds.Warn("No audio engine initialized, failed to create an audio analyser"))}getFrequencyBinCount(){return this._audioEngine.canUseWebAudio?this._webAudioAnalyser.frequencyBinCount:0}getByteFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs)),this._byteFreqs}getByteTimeDomainData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getByteTimeDomainData(this._byteTime)),this._byteTime}getFloatFrequencyData(){return this._audioEngine.canUseWebAudio&&(this._webAudioAnalyser.smoothingTimeConstant=this.SMOOTHING,this._webAudioAnalyser.fftSize=this.FFT_SIZE,this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs)),this._floatFreqs}drawDebugCanvas(){if(this._audioEngine.canUseWebAudio&&(this._debugCanvas||(this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=this.DEBUGCANVASSIZE.width,this._debugCanvas.height=this.DEBUGCANVASSIZE.height,this._debugCanvas.style.position="absolute",this._debugCanvas.style.top=this.DEBUGCANVASPOS.y+"px",this._debugCanvas.style.left=this.DEBUGCANVASPOS.x+"px",this._debugCanvasContext=this._debugCanvas.getContext("2d"),document.body.appendChild(this._debugCanvas),this._registerFunc=()=>{this.drawDebugCanvas()},this._scene.registerBeforeRender(this._registerFunc)),this._registerFunc&&this._debugCanvasContext)){const e=this.getByteFrequencyData();this._debugCanvasContext.fillStyle="rgb(0, 0, 0)",this._debugCanvasContext.fillRect(0,0,this.DEBUGCANVASSIZE.width,this.DEBUGCANVASSIZE.height);for(let t=0;tt0&&(s=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()})),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(t,(e=>{this._soundLoaded(e)}),void 0,!0,!0,(e=>{e&&Ne.Error("XHR "+e.status+" error on: "+t+"."),Ne.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}));break}}break;default:e=!1}e?s||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)):Ne.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){Ne.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),oo.audioEngine&&!oo.audioEngine.WarnedWebAudioUnsupported&&(Ne.Error("Web Audio is not supported by your browser."),oo.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)}dispose(){oo.audioEngine?.canUseWebAudio&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,-1===this.soundTrackId?this._scene.mainSoundTrack.removeSound(this):this._scene.soundTracks&&this._scene.soundTracks[this.soundTrackId].removeSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._streamingSource&&this._streamingSource.disconnect(),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){oo.audioEngine?.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){oo.audioEngine?.audioContext&&oo.audioEngine.audioContext.decodeAudioData(e,(e=>{this._audioBufferLoaded(e)}),(e=>{Ne.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)}))}setAudioBuffer(e){oo.audioEngine?.canUseWebAudio&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){e&&(this.loop=e.loop??this.loop,this.maxDistance=e.maxDistance??this.maxDistance,this.useCustomAttenuation=e.useCustomAttenuation??this.useCustomAttenuation,this.rolloffFactor=e.rolloffFactor??this.rolloffFactor,this.refDistance=e.refDistance??this.refDistance,this.distanceModel=e.distanceModel??this.distanceModel,this._playbackRate=e.playbackRate??this._playbackRate,this._length=e.length??void 0,this.spatialSound=e.spatialSound??this._spatialSound,this._setOffset(e.offset??void 0),this.setVolume(e.volume??this._volume),this._updateSpatialParameters(),this.isPlaying&&(this._streaming&&this._htmlAudioElement?(this._htmlAudioElement.playbackRate=this._playbackRate,this._htmlAudioElement.loop!==this.loop&&(this._htmlAudioElement.loop=this.loop)):this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.loop!==this.loop&&(this._soundSource.loop=this.loop),void 0!==this._offset&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),void 0!==this._length&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(0|this._offset)+this._length))))}_createSpatialParameters(){oo.audioEngine?.canUseWebAudio&&oo.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??oo.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){this._spatialSound&&(this._inputAudioNode=this._soundGain,this._soundPanner?.disconnect(),this._soundPanner=null,this._spatialSound=!1)}_updateSpatialParameters(){this._spatialSound&&(this._soundPanner?this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel):this._createSpatialParameters())}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){oo.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){oo.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const e=()=>{if(oo.audioEngine?.unlocked){const t=this._htmlAudioElement.play();void 0!==t&&t.catch((()=>{oo.audioEngine?.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=oo.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))}))}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=oo.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))};e()}}else{const r=()=>{if(oo.audioEngine?.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){const e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=oo.audioEngine?.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,void 0!==t&&(this._soundSource.loopStart=t),void 0!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},s=e?oo.audioEngine?.audioContext.currentTime+e:oo.audioEngine.audioContext.currentTime;const r=((this.isPaused?this.currentTime:0)+(this._offset??0))%this._soundSource.buffer.duration;this._soundSource.start(s,r,this.loop?void 0:i)}}};"suspended"===oo.audioEngine?.audioContext.state?this._tryToPlayTimeout=setTimeout((()=>{"suspended"===oo.audioEngine?.audioContext.state?(oo.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=oo.audioEngine.onAudioUnlockedObservable.addOnce((()=>{r()})))):r()}),500):r()}this._startTime=s,this.isPlaying=!0,this.isPaused=!1}catch(e){Ne.Error("Error while trying to play audio: "+this.name+", "+e.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){if(this.isPlaying)if(this._clearTimeoutsAndObservers(),this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if(oo.audioEngine?.audioContext&&this._soundSource){const t=e?oo.audioEngine.audioContext.currentTime+e:void 0;this._soundSource.onended=()=>{this.isPlaying=!1,this.isPaused=!1,this._startTime=0,this._currentTime=0,this._soundSource&&(this._soundSource.onended=()=>{}),this._onended()},this._soundSource.stop(t)}else this.isPlaying=!1;else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):oo.audioEngine?.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=oo.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){oo.audioEngine?.canUseWebAudio&&this._soundGain&&(t&&oo.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(oo.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,oo.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,oo.audioEngine.audioContext.currentTime+t)):this._soundGain.gain.value=e),this._volume=e}setPlaybackRate(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))}getPlaybackRate(){return this._playbackRate}getVolume(){return this._volume}attachToMesh(e){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=e,this._spatialSound||(this._spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=e=>this._onRegisterAfterWorldMatrixUpdate(e),this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)}detachFromMesh(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)}_onRegisterAfterWorldMatrixUpdate(e){if(e.getBoundingInfo){const t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);oo.audioEngine?.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{const e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},i=new ma(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){const e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,s){const r=e.name;let n;n=e.url?i+e.url:i+r;const o={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};let a;if(s){const e=()=>{s._isReadyToPlay?(a._audioBuffer=s.getAudioBuffer(),a._isReadyToPlay=!0,a.autoplay&&a.play(0,a._offset,a._length)):setTimeout(e,300)};a=new ma(r,new ArrayBuffer(0),t,null,o),e()}else a=new ma(r,n,t,(()=>{t.removePendingData(a)}),o),t.addPendingData(a);if(e.position){const t=_e.FromArray(e.position);a.setPosition(t)}if(e.isDirectional&&(a.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const t=_e.FromArray(e.localDirectionToMesh);a.setLocalDirectionToMesh(t)}if(e.connectedMeshId){const i=t.getMeshById(e.connectedMeshId);i&&a.attachToMesh(i)}return e.metadata&&(a.metadata=e.metadata),a}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(oo.audioEngine?.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}ma._SceneComponentInitialization=e=>{throw xt("AudioSceneComponent")},z("BABYLON.Sound",ma);class ga{constructor(e,t={}){this.id=-1,this._isInitialized=!1,(e=e||re.LastCreatedScene)&&(this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1))}_initializeSoundTrackAudioGraph(){oo.audioEngine?.canUseWebAudio&&oo.audioEngine.audioContext&&(this._outputAudioNode=oo.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(oo.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(oo.audioEngine&&oo.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(e){this._isInitialized||this._initializeSoundTrackAudioGraph(),oo.audioEngine?.canUseWebAudio&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){const t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){oo.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){if(oo.audioEngine?.canUseWebAudio)for(let e=0;e{let r,n=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let o=0,a=e.sounds.length;o{e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)}))}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach((e=>{e.stop(),e.autoplay=!1,this.scene.mainSoundTrack.removeSound(e),t&&e.dispose()}))}dispose(){const e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(s=t.activeCameras[0]),this.audioListenerPositionProvider){const e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else s?this._cachedCameraPosition.equals(s.globalPosition)||(this._cachedCameraPosition.copyFrom(s.globalPosition),i.audioContext.listener.setPosition(s.globalPosition.x,s.globalPosition.y,s.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else s?(s.rigCameras&&s.rigCameras.length>0&&(s=s.rigCameras[0]),s.getViewMatrix().invertToRef(this._invertMatrixTemp),_e.TransformNormalToRef(va._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),isNaN(this._cameraDirectionTemp.x)||isNaN(this._cameraDirectionTemp.y)||isNaN(this._cameraDirectionTemp.z)||this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);for(e=0;e{let t=e._getComponent(or.NAME_AUDIO);t||(t=new va(e),e._addComponent(t))};class xa{constructor(e,t,i){if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],t.length!==i.length)throw new Error("Sounds length does not equal weights length");this.loop=e,this._weights=i;let s=0;for(const e of i)s+=e;const r=s>0?1/s:0;for(let e=0;e{this._onended()}))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAnglee),this)}serialize(){return St.Serialize(this)}parse(e,t,i){St.Parse((()=>this),e,t,i)}}Ze([nt(),st("_markSubMeshesAsAttributesDirty")],ba.prototype,"texture",void 0),Ze([rt(),st("_markSubMeshesAsAttributesDirty")],ba.prototype,"isEnabled",void 0),Ze([rt()],ba.prototype,"animationParameters",void 0),Ze([rt()],ba.prototype,"time",void 0);class Ta{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return!!this._texture&&this._texture.isCube}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return void 0!==e?.shareDepth}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=At.Zero(),this._cachedBaseSize=At.Zero(),this._initialSamplingMode=2,this._texture=Ta._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return this.isReady()&&this._texture?this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}class ya extends Ta{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return!!this._texture&&this._texture._linearSpecularLOD}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=Cs()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=ya.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new K,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?ya._IsScene(e)?this._scene=e:this._engine=e:this._scene=re.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}getTextureMatrix(){return me.IdentityReadOnly}getReflectionTextureMatrix(){return me.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,s,r,n){const o=this._getEngine();if(!o)return null;const a=o._getUseSRGBBuffer(!!r,t),l=o.getLoadedTexturesCache();for(let o=0;o=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const e=this._parentContainer.textures.indexOf(this);e>-1&&this._parentContainer.textures.splice(e,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;const t=St.Serialize(this);return St.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let s=0;s{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}function Sa(e,t,i=!1){const s=t.width,r=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let s=e[t];s<0?s=0:s>1&&(s=1),i[t]=255*s}e=i}const n=document.createElement("canvas");n.width=s,n.height=r;const o=n.getContext("2d");if(!o)return null;const a=o.createImageData(s,r);if(a.data.set(e),o.putImageData(a,0,0),i){const e=document.createElement("canvas");e.width=s,e.height=r;const t=e.getContext("2d");return t?(t.translate(0,r),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}function Ca(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=e._readPixelsSync(t,i);return r?Sa(r,e.getSize(),s.invertY):null}async function Ea(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=await e.readPixels(t,i);return r?Sa(r,e.getSize(),s.invertY):null}ya.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,Ze([rt()],ya.prototype,"uniqueId",void 0),Ze([rt()],ya.prototype,"name",void 0),Ze([rt()],ya.prototype,"metadata",void 0),Ze([rt("hasAlpha")],ya.prototype,"_hasAlpha",void 0),Ze([rt("getAlphaFromRGB")],ya.prototype,"_getAlphaFromRGB",void 0),Ze([rt()],ya.prototype,"level",void 0),Ze([rt("coordinatesIndex")],ya.prototype,"_coordinatesIndex",void 0),Ze([rt()],ya.prototype,"optimizeUVAllocation",void 0),Ze([rt("coordinatesMode")],ya.prototype,"_coordinatesMode",void 0),Ze([rt()],ya.prototype,"wrapU",null),Ze([rt()],ya.prototype,"wrapV",null),Ze([rt()],ya.prototype,"wrapR",void 0),Ze([rt()],ya.prototype,"anisotropicFilteringLevel",void 0),Ze([rt()],ya.prototype,"isCube",null),Ze([rt()],ya.prototype,"is3D",null),Ze([rt()],ya.prototype,"is2DArray",null),Ze([rt()],ya.prototype,"gammaSpace",null),Ze([rt()],ya.prototype,"invertZ",void 0),Ze([rt()],ya.prototype,"lodLevelInAlpha",void 0),Ze([rt()],ya.prototype,"lodGenerationOffset",null),Ze([rt()],ya.prototype,"lodGenerationScale",null),Ze([rt()],ya.prototype,"linearSpecularLOD",null),Ze([nt()],ya.prototype,"irradianceTexture",null),Ze([rt()],ya.prototype,"isRenderTarget",void 0);const Aa={GenerateBase64StringFromPixelData:Sa,GenerateBase64StringFromTexture:Ca,GenerateBase64StringFromTextureAsync:Ea};class Pa extends ya{static _CreateVideoTexture(e,t,i,s=!1,r=!1,n=Pa.TRILINEAR_SAMPLINGMODE,o={},a,l=5){throw xt("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,s,r=Pa.TRILINEAR_SAMPLINGMODE,n=null,o=null,a=null,l=!1,h,c,u,d,_){let p;super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=null,this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedIdentity3x2=!0,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new K,this._isBlocking=!0,this.name=e||"",this.url=e;let f=!1,m=null,g=!0;"object"==typeof i&&null!==i?(p=i.noMipmap??!1,s=i.invertY??!Xn.UseOpenGLOrientationForUV,r=i.samplingMode??Pa.TRILINEAR_SAMPLINGMODE,n=i.onLoad??null,o=i.onError??null,a=i.buffer??null,l=i.deleteBuffer??!1,h=i.format,c=i.mimeType,u=i.loaderOptions,d=i.creationFlags,f=i.useSRGBBuffer??!1,m=i.internalTexture??null,g=i.gammaSpace??g):p=!!i,this._gammaSpace=g,this._noMipmap=p,this._invertY=void 0===s?!Xn.UseOpenGLOrientationForUV:s,this._initialSamplingMode=r,this._buffer=a,this._deleteBuffer=l,this._mimeType=c,this._loaderOptions=u,this._creationFlags=d,this._useSRGBBuffer=f,this._forcedExtension=_,h&&(this._format=h);const v=this.getScene(),x=this._getEngine();if(!x)return;x.onBeforeTextureInitObservable.notifyObservers(this);const b=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),n&&n(),!this.isBlocking&&v&&v.resetCachedMaterial()},T=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},o&&o(e,t),Pa.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!m)return this._delayedOnLoad=b,void(this._delayedOnError=T);if(this._texture=m??this._getFromCache(this.url,p,r,this._invertY,f,this.isCube),this._texture)if(this._texture.isReady)Li.SetImmediate((()=>b()));else{const e=this._texture.onLoadedObservable.add(b);this._texture.onErrorObservable.add((t=>{T(t.message,t.exception),this._texture?.onLoadedObservable.remove(e)}))}else if(v&&v.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=b,this._delayedOnError=T;else{try{this._texture=x.createTexture(this.url,p,this._invertY,v,r,b,T,this._buffer,void 0,this._format,this._forcedExtension,c,u,d,f)}catch(e){throw T("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,i,s){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=s,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;const e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?Li.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,s){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,_e.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,s),s.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,s.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,s.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,this._cachedTextureMatrix&&this._rowGenerationMatrix||(this._cachedTextureMatrix=me.Zero(),this._rowGenerationMatrix=new me,this._t0=_e.Zero(),this._t1=_e.Zero(),this._t2=_e.Zero()),me.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(me.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,ve.Matrix[0]),me.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,ve.Matrix[1]),me.ScalingToRef(this._cachedUScale,this._cachedVScale,0,ve.Matrix[2]),me.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,ve.Matrix[3]),ve.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ve.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ve.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ve.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),me.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));const t=this.getScene();if(!t)return this._cachedTextureMatrix;const i=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&i!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedTextureMatrix}getReflectionTextureMatrix(){const e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode){if(this.coordinatesMode!==Pa.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=me.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=me.Zero());const t=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case Pa.PLANAR_MODE:me.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break;case Pa.PROJECTION_MODE:{me.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:me.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedReflectionTextureMatrix}clone(){const e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return St.Clone((()=>new Pa(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){const e=this.name;Pa.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(Pa._SerializeInternalTextureUniqueId);return t?((Pa.SerializeBuffers||Pa.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(t.base64String=this._buffer,t.name=t.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?t.base64String="data:image/png;base64,"+Zt(this._buffer):(Pa.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?Ca(this):Ea(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,Pa._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=this._texture?.uniqueId??void 0),t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const s=Ss.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&s.updateSamplingMode&&s._samplingMode&&s._samplingMode!==e.samplingMode&&s.updateSamplingMode(e.samplingMode),s}if(e.isCube&&!e.isRenderTarget)return Pa._CubeTextureParser(e,t,i);const s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;let r;if(s){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}const n=t=>{if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){const i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i{let s=!0;if(e.noMipmap&&(s=!1),e.mirrorPlane){const i=Pa._CreateMirror(e.name,e.renderTargetSize,t,s);return i._waitingRenderList=e.renderList,i.mirrorPlane=Nr.FromArray(e.mirrorPlane),n(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{n(o)}),e._creationFlags??0,e._useSRGBBuffer??!1),o.name=e.name;else{let a;a=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||Pa.UseSerializedUrlIfAny)&&(a=e.url);const l={noMipmap:!s,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(o)},internalTexture:r};o=new Pa(a,t,l)}return o}}),e,t)}static CreateFromBase64String(e,t,i,s,r,n=Pa.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=5,h,c){return new Pa("data:"+t,i,s,r,n,o,a,e,!1,l,void 0,void 0,h,c)}static LoadFromDataString(e,t,i,s=!1,r,n=!0,o=Pa.TRILINEAR_SAMPLINGMODE,a=null,l=null,h=5,c,u){return"data:"!==e.substr(0,5)&&(e="data:"+e),new Pa(e,i,r,n,o,a,l,t,s,h,void 0,void 0,c,u)}}function Ia(e,t,i,s){let r,n=1;1===s?r=new Float32Array(t*i*4):2===s?(r=new Uint16Array(t*i*4),n=15360):r=7===s?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let s=0;s{throw xt("CubeTexture")},Pa._CreateMirror=(e,t,i,s)=>{throw xt("MirrorTexture")},Pa._CreateRenderTargetTexture=(e,t,i,s,r)=>{throw xt("RenderTargetTexture")},Pa.NEAREST_SAMPLINGMODE=1,Pa.NEAREST_NEAREST_MIPLINEAR=8,Pa.BILINEAR_SAMPLINGMODE=2,Pa.LINEAR_LINEAR_MIPNEAREST=11,Pa.TRILINEAR_SAMPLINGMODE=3,Pa.LINEAR_LINEAR_MIPLINEAR=3,Pa.NEAREST_NEAREST_MIPNEAREST=4,Pa.NEAREST_LINEAR_MIPNEAREST=5,Pa.NEAREST_LINEAR_MIPLINEAR=6,Pa.NEAREST_LINEAR=7,Pa.NEAREST_NEAREST=1,Pa.LINEAR_NEAREST_MIPNEAREST=9,Pa.LINEAR_NEAREST_MIPLINEAR=10,Pa.LINEAR_LINEAR=2,Pa.LINEAR_NEAREST=12,Pa.EXPLICIT_MODE=0,Pa.SPHERICAL_MODE=1,Pa.PLANAR_MODE=2,Pa.CUBIC_MODE=3,Pa.PROJECTION_MODE=4,Pa.SKYBOX_MODE=5,Pa.INVCUBIC_MODE=6,Pa.EQUIRECTANGULAR_MODE=7,Pa.FIXED_EQUIRECTANGULAR_MODE=8,Pa.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Pa.CLAMP_ADDRESSMODE=0,Pa.WRAP_ADDRESSMODE=1,Pa.MIRROR_ADDRESSMODE=2,Pa.UseSerializedUrlIfAny=!1,Ze([rt()],Pa.prototype,"url",void 0),Ze([rt()],Pa.prototype,"uOffset",void 0),Ze([rt()],Pa.prototype,"vOffset",void 0),Ze([rt()],Pa.prototype,"uScale",void 0),Ze([rt()],Pa.prototype,"vScale",void 0),Ze([rt()],Pa.prototype,"uAng",void 0),Ze([rt()],Pa.prototype,"vAng",void 0),Ze([rt()],Pa.prototype,"wAng",void 0),Ze([rt()],Pa.prototype,"uRotationCenter",void 0),Ze([rt()],Pa.prototype,"vRotationCenter",void 0),Ze([rt()],Pa.prototype,"wRotationCenter",void 0),Ze([rt()],Pa.prototype,"homogeneousRotationInUVTransform",void 0),Ze([rt()],Pa.prototype,"isBlocking",null),z("BABYLON.Texture",Pa),St._TextureParser=Pa.Parse,qs.prototype.updateRawTexture=function(e,t,i,s,r=null,n=0,o=!1){if(!e)return;const a=this._getRGBABufferInternalSizedFormat(n,i,o),l=this._getInternalFormat(i),h=this._getWebGLTextureType(n);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=n,e.invertY=s,e._compression=r),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[r],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,e.width,e.height,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0},qs.prototype.createRawTexture=function(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new ss(this,is.Raw);u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u._compression=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!r),this._doNotHandleContextLost||(u._bufferView=e),this.updateRawTexture(u,e,s,n,a,l,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);const d=this._getSamplingParameters(o,r);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),r&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u},qs.prototype.createRawCubeTexture=function(e,t,i,s,r,n,o,a=null){const l=this._gl,h=new ss(this,is.CubeRaw);h.isCube=!0,h.format=i,h.type=s,this._doNotHandleContextLost||(h._bufferViewArray=e);const c=this._getWebGLTextureType(s);let u=this._getInternalFormat(i);u===l.RGB&&(u=l.RGBA),c!==l.FLOAT||this._caps.textureFloatLinearFiltering?c!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?c!==l.FLOAT||this._caps.textureFloatRender?c!==l.HALF_FLOAT||this._caps.colorBufferFloat||(r=!1,Ne.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(r=!1,Ne.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(r=!1,o=1,Ne.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(r=!1,o=1,Ne.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."));const d=t,_=d;if(h.width=d,h.height=_,h.invertY=n,h._compression=a,!this.needPOTTextures||As(h.width)&&As(h.height)||(r=!1),e)this.updateRawCubeTexture(h,e,i,s,n,a);else{const e=this._getRGBABufferInternalSizedFormat(s),t=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let i=0;i<6;i++)a?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,this.getCaps().s3tc[a],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,e,h.width,h.height,0,u,c,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),e&&r&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const p=this._getSamplingParameters(o,r);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,p.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,p.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),h.generateMipMaps=r,h.samplingMode=o,h.isReady=!0,h},qs.prototype.updateRawCubeTexture=function(e,t,i,s,r,n=null,o=0){e._bufferViewArray=t,e.format=i,e.type=s,e.invertY=r,e._compression=n;const a=this._gl,l=this._getWebGLTextureType(s);let h=this._getInternalFormat(i);const c=this._getRGBABufferInternalSizedFormat(s);let u=!1;h===a.RGB&&(h=a.RGBA,u=!0),this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===r||!!r),e.width%4!=0&&a.pixelStorei(a.UNPACK_ALIGNMENT,1);for(let i=0;i<6;i++){let r=t[i];n?a.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+i,o,this.getCaps().s3tc[n],e.width,e.height,0,r):(u&&(r=Ia(r,e.width,e.height,s)),a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+i,o,c,e.width,e.height,0,h,l,r))}(!this.needPOTTextures||As(e.width)&&As(e.height))&&e.generateMipMaps&&0===o&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},qs.prototype.createRawCubeTextureFromUrl=function(e,t,i,s,r,n,o,a,l=null,h=null,c=3,u=!1){const d=this._gl,_=this.createRawCubeTexture(null,i,s,r,!n,u,c,null);t?.addPendingData(_),_.url=e,_.isReady=!1,this._internalTexturesCache.push(_);const p=e=>{const i=_.width,n=o(e);if(n){if(a){const e=this._getWebGLTextureType(r);let t=this._getInternalFormat(s);const o=this._getRGBABufferInternalSizedFormat(r);let l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,_,!0),this._unpackFlipY(!1);const h=a(n);for(let s=0;s>s;for(let i=0;i<6;i++){let a=h[s][i];l&&(a=Ia(a,n,n,r)),d.texImage2D(i,s,o,n,n,0,t,e,a)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(_,n,s,r,u);_.isReady=!0,t?.removePendingData(_),_.onLoadedObservable.notifyObservers(_),_.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,(e=>{p(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(_),h&&e&&h(e.status+" "+e.statusText,i)})),_},qs.prototype.createRawTexture2DArray=Ra(!1),qs.prototype.createRawTexture3D=Ra(!0),qs.prototype.updateRawTexture2DArray=Ma(!1),qs.prototype.updateRawTexture3D=Ma(!0);class Oa extends Pa{constructor(e,t,i,s,r,n=!0,o=!1,a=3,l=0,h,c){super(null,r,!n,o,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=s,this._engine&&(this._engine._caps.textureFloatLinearFiltering||1!==l||(a=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(a=1),this._texture=this._engine.createRawTexture(e,t,i,s,n,o,a,null,l,h??0,c??!1),this.wrapU=Pa.CLAMP_ADDRESSMODE,this.wrapV=Pa.CLAMP_ADDRESSMODE)}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}static CreateLuminanceTexture(e,t,i,s,r=!0,n=!1,o=3){return new Oa(e,t,i,1,s,r,n,o)}static CreateLuminanceAlphaTexture(e,t,i,s,r=!0,n=!1,o=3){return new Oa(e,t,i,2,s,r,n,o)}static CreateAlphaTexture(e,t,i,s,r=!0,n=!1,o=3){return new Oa(e,t,i,0,s,r,n,o)}static CreateRGBTexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=0,h=!1){return new Oa(e,t,i,4,s,r,n,o,a,l,h)}static CreateRGBATexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=0,h=!1){return new Oa(e,t,i,5,s,r,n,o,a,l,h)}static CreateRGBAStorageTexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=!1){return new Oa(e,t,i,5,s,r,n,o,a,1,l)}static CreateRTexture(e,t,i,s,r=!0,n=!1,o=Pa.TRILINEAR_SAMPLINGMODE,a=1){return new Oa(e,t,i,6,s,r,n,o,a)}static CreateRStorageTexture(e,t,i,s,r=!0,n=!1,o=Pa.TRILINEAR_SAMPLINGMODE,a=1){return new Oa(e,t,i,6,s,r,n,o,a,1)}}class Da{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=me.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new K,this.bones=[],this._scene=i||re.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const s=this._scene.getEngine().getCaps();this._canUseTextureForBones=s.textureFloat&&s.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter((e=>!e.getParent()))}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return this._transformMatrices&&!this._isDirty||this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0)for(const e of this.bones)if(e._linkedTransformNode){const t=e._linkedTransformNode;e.position=t.position,t.rotationQuaternion?e.rotationQuaternion=t.rotationQuaternion:e.rotation=t.rotation,e.scaling=t.scaling}if(this.needInitialSkinMatrix)for(const e of this._meshesWithPoseMatrix){const t=e.getPoseMatrix();let i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){this._synchronizedWithMesh=e;for(const e of this.bones)e.getParent()||(e.getBindMatrix().multiplyToRef(t,ve.Matrix[1]),e._updateAbsoluteBindMatrices(ve.Matrix[1]));if(this.isUsingTextureForMatrices){const t=4*(this.bones.length+1);e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=Oa.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(e._bonesTransformMatrices,t),this.isUsingTextureForMatrices&&e._transformMatrixTexture&&e._transformMatrixTexture.update(e._bonesTransformMatrices)}}else{if(!this._isDirty)return;this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=Oa.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e{t.animations.forEach((t=>{t.enableBlending=!0,t.blendingSpeed=e}))}))}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){const e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){const e={};e.name=this.name,e.id=this.id,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let t=0;t0&&(r.animation=i.animations[0].serialize()),e.ranges=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const s={};s.name=t,s.from=i.from,s.to=i.to,e.ranges.push(s)}}return e}static Parse(e,t){const i=new Da(e.name,e.id,t);let s;for(e.dimensionsAtRest&&(i.dimensionsAtRest=_e.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,s=0;s-1&&(n=i.bones[t.parentBoneIndex]);const o=t.rest?me.FromArray(t.rest):null,a=new Yr(t.name,i,n,me.FromArray(t.matrix),o,null,r);void 0!==t.id&&null!==t.id&&(a.id=t.id),t.length&&(a.length=t.length),t.metadata&&(a.metadata=t.metadata),t.animation&&a.animations.push(Ft.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,a._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(s=0;s0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()}))}}class wa{constructor(e,t){this._scene=e,t instanceof Da?(this._skeleton=t,this._mesh=null):(this._mesh=t,this._skeleton=t.skeleton)}async bakeVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=e.reduce(((e,t)=>e+t.to-t.from+1),0);if(isNaN(i))throw new Error("Invalid animation ranges.");let s=0;const r=new Float32Array(4*(t+1)*4*i);this._scene.stopAnimation(this._skeleton),this._skeleton.returnToRest();for(const t of e)for(let e=t.from;e<=t.to;e++)await this._executeAnimationFrame(r,e,s++);return r}async _executeAnimationFrame(e,t,i){return new Promise(((s,r)=>{this._scene.beginAnimation(this._skeleton,t,t,!1,1,(()=>{const t=this._skeleton.getTransformMatrices(this._mesh);e.set(t,i*t.length),s()}))}))}textureFromBakedVertexData(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=Oa.CreateRGBATexture(e,4*(t+1),e.length/(4*(t+1)*4),this._scene,!1,!1,Pa.NEAREST_NEAREST,1);return i.name="VAT"+this._skeleton.name,i}serializeBakedVertexDataToObject(e){if(!this._skeleton)throw new Error("No skeleton provided.");const t=this._skeleton.bones.length,i=4*(t+1),s=e.length/(4*(t+1)*4);return{vertexData:Zt(e),width:i,height:s}}loadBakedVertexDataFromObject(e){return new Float32Array(ei(e.vertexData))}serializeBakedVertexDataToJSON(e){return JSON.stringify(this.serializeBakedVertexDataToObject(e))}loadBakedVertexDataFromJSON(e){return this.loadBakedVertexDataFromObject(JSON.parse(e))}}class Na{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==lr.POINTERDOWN?e.type===lr.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=Wt.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const i=e-this._lastInteractionTime-this._idleRotationWaitTime,s=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*s,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=e??Wt.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(e&&(e.computeWorldMatrix(!0),e.getBoundingInfo)){const t=e.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=.05*t,this.upperRadiusTransitionRange=.05*t}})):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))}))}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return!!this._attachedCamera&&this._attachedCamera.radius===e&&!this._radiusIsAnimating}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(Fa.EasingFunction.setEasingMode(Fa.EasingMode),this._radiusBounceTransition=Ft.CreateAnimation("radius",Ft.ANIMATIONTYPE_FLOAT,60,Fa.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=Ft.TransitionTo("radius",this._attachedCamera.radius+e,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,(()=>this._clearAnimationLocks()));t&&this._animatables.push(t)}_clearAnimationLocks(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()}}Fa.EasingFunction=new rn(.3),Fa.EasingMode=tn.EASINGMODE_EASEOUT;class La{constructor(){this.onTargetFramingAnimationEndObservable=new K,this._mode=La.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}get name(){return"Framing"}set mode(e){this._mode=e}get mode(){return this._mode}set radiusScale(e){this._radiusScale=e}get radiusScale(){return this._radiusScale}set positionScale(e){this._positionScale=e}get positionScale(){return this._positionScale}set defaultElevation(e){this._defaultElevation=e}get defaultElevation(){return this._defaultElevation}set elevationReturnTime(e){this._elevationReturnTime=e}get elevationReturnTime(){return this._elevationReturnTime}set elevationReturnWaitTime(e){this._elevationReturnWaitTime=e}get elevationReturnWaitTime(){return this._elevationReturnWaitTime}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set framingTime(e){this._framingTime=e}get framingTime(){return this._framingTime}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();La.EasingFunction.setEasingMode(La.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==lr.POINTERDOWN?e.type===lr.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add((e=>{e&&e.getBoundingInfo&&this.zoomOnMesh(e,void 0,(()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()}))})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(s.minimumWorld,s.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(s.min,s.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const s=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new _e(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t{this.stopAllAnimations(),s&&s(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),l&&this._animatables.push(l),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let s=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===La.IgnoreBoundsSizeMode&&(s=si.upperRadiusLimit?i.upperRadiusLimit:s),s}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=Wt.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation,i=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=Ft.CreateAnimation("beta",Ft.ANIMATIONTYPE_FLOAT,60,La.EasingFunction));const e=Ft.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(()=>{this._clearAnimationLocks(),this.stopAllAnimations()}));e&&this._animatables.push(e)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=Wt.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}La.EasingFunction=new ln,La.EasingMode=tn.EASINGMODE_EASEINOUT,La.IgnoreBoundsSizeMode=0,La.FitFrustumSidesMode=1;class Ba{constructor(e,t=new _e,i=0,s=!1){this.direction=e,this.rotatedDirection=t,this.diff=i,this.ignore=s}}class ka{constructor(e){this._ui=e,this.name="AttachToBoxBehavior",this.distanceAwayFromFace=.15,this.distanceAwayFromBottomOfFace=.15,this._faceVectors=[new Ba(_e.Up()),new Ba(_e.Down()),new Ba(_e.Left()),new Ba(_e.Right()),new Ba(_e.Forward()),new Ba(_e.Forward().scaleInPlace(-1))],this._tmpMatrix=new me,this._tmpVector=new _e,this._zeroVector=_e.Zero(),this._lookAtTmpMatrix=new me}init(){}_closestFace(e){return this._faceVectors.forEach((t=>{this._target.rotationQuaternion||(this._target.rotationQuaternion=fe.RotationYawPitchRoll(this._target.rotation.y,this._target.rotation.x,this._target.rotation.z)),this._target.rotationQuaternion.toRotationMatrix(this._tmpMatrix),_e.TransformCoordinatesToRef(t.direction,this._tmpMatrix,t.rotatedDirection),t.diff=_e.GetAngleBetweenVectors(t.rotatedDirection,e,_e.Cross(t.rotatedDirection,e))})),this._faceVectors.reduce(((e,t)=>e.ignore?t:t.ignore||e.diff{if(!this._scene.activeCamera)return;let t=this._scene.activeCamera.position;this._scene.activeCamera.devicePosition&&(t=this._scene.activeCamera.devicePosition);const i=this._closestFace(t.subtract(e.position));this._scene.activeCamera.leftCamera?this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix):this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix),_e.TransformCoordinatesToRef(_e.Up(),this._tmpMatrix,this._tmpVector),this._faceVectors.forEach((e=>{i.direction.x&&e.direction.x&&(e.ignore=!0),i.direction.y&&e.direction.y&&(e.ignore=!0),i.direction.z&&e.direction.z&&(e.ignore=!0)}));const s=this._closestFace(this._tmpVector);this._faceVectors.forEach((e=>{e.ignore=!1})),this._ui.position.copyFrom(e.position),i.direction.x&&(i.rotatedDirection.scaleToRef(e.scaling.x/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.y&&(i.rotatedDirection.scaleToRef(e.scaling.y/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),i.direction.z&&(i.rotatedDirection.scaleToRef(e.scaling.z/2+this.distanceAwayFromFace,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)),this._ui.rotationQuaternion||(this._ui.rotationQuaternion=fe.RotationYawPitchRoll(this._ui.rotation.y,this._ui.rotation.x,this._ui.rotation.z)),i.rotatedDirection.scaleToRef(-1,this._tmpVector),this._lookAtToRef(this._tmpVector,s.rotatedDirection,this._ui.rotationQuaternion),s.direction.x&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.x/2,this._tmpVector),s.direction.y&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.y/2,this._tmpVector),s.direction.z&&this._ui.up.scaleToRef(this.distanceAwayFromBottomOfFace-e.scaling.z/2,this._tmpVector),this._ui.position.addInPlace(this._tmpVector)}))}detach(){this._scene.onBeforeRenderObservable.remove(this._onRenderObserver)}}class Va{get delay(){return this.fadeInDelay}set delay(e){this.fadeInDelay=e,this.fadeOutDelay=e}constructor(){this.fadeInDelay=0,this.fadeOutDelay=0,this.fadeInTime=300,this.fadeOutTime=300,this._millisecondsPerFrame=1e3/60,this._hovered=!1,this._hoverValue=0,this._ownerNode=null,this._delay=0,this._time=300,this._update=()=>{if(this._ownerNode){if(this._hoverValue+=this._hovered?this._millisecondsPerFrame:-this._millisecondsPerFrame,this._setAllVisibility(this._ownerNode,(this._hoverValue-this._delay)/this._time),this._ownerNode.visibility>1){if(this._setAllVisibility(this._ownerNode,1),this._hoverValue>this._time)return this._hoverValue=this._time,void this._detachObserver()}else if(this._ownerNode.visibility<0&&(this._setAllVisibility(this._ownerNode,0),this._hoverValue<0))return this._hoverValue=0,void this._detachObserver();this._attachObserver()}}}get name(){return"FadeInOut"}init(){}attach(e){this._ownerNode=e,this._setAllVisibility(this._ownerNode,0)}detach(){this._ownerNode=null}fadeIn(e=!0){this._delay=e?this.fadeInDelay:this.fadeOutDelay,this._time=e?this.fadeInTime:this.fadeOutTime,this._detachObserver(),this._ownerNode&&(e&&this._ownerNode.visibility>=1||!e&&this._ownerNode.visibility<=0)||(this._hovered=e,this._hovered||(this._delay*=-1),this._ownerNode.visibility>=1?this._hoverValue=this._time:this._ownerNode.visibility<=0&&(this._hoverValue=0),this._update())}fadeOut(){this.fadeIn(!1)}_setAllVisibility(e,t){e.visibility=t,e.getChildMeshes().forEach((e=>{this._setAllVisibility(e,t)}))}_attachObserver(){this._onBeforeRenderObserver||(this._onBeforeRenderObserver=this._ownerNode?.getScene().onBeforeRenderObservable.add(this._update))}_detachObserver(){this._onBeforeRenderObserver&&(this._ownerNode?.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=null)}}class Ua{constructor(e,t,i=Number.MAX_VALUE,s=J){this.origin=e,this.direction=t,this.length=i,this.epsilon=s}clone(){return new Ua(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const s=Ua._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),r=Ua._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let n,o,a,l,h=0,c=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xr.x)return!1}else if(n=1/this.direction.x,o=(s.x-this.origin.x)*n,a=(r.x-this.origin.x)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yr.y)return!1}else if(n=1/this.direction.y,o=(s.y-this.origin.y)*n,a=(r.y-this.origin.y)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zr.z)return!1}else if(n=1/this.direction.z,o=(s.z-this.origin.z)*n,a=(r.z-this.origin.z)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){const i=e.center.x-this.origin.x,s=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=i*i+s*s+r*r,o=e.radius+t,a=o*o;if(n<=a)return!0;const l=i*this.direction.x+s*this.direction.y+r*this.direction.z;return!(l<0)&&n-l*l<=a}intersectsTriangle(e,t,i){const s=Ua._TmpVector3[0],r=Ua._TmpVector3[1],n=Ua._TmpVector3[2],o=Ua._TmpVector3[3],a=Ua._TmpVector3[4];t.subtractToRef(e,s),i.subtractToRef(e,r),_e.CrossToRef(this.direction,r,n);const l=_e.Dot(s,n);if(0===l)return null;const h=1/l;this.origin.subtractToRef(e,o);const c=_e.Dot(o,n)*h;if(c<-this.epsilon||c>1+this.epsilon)return null;_e.CrossToRef(o,s,a);const u=_e.Dot(this.direction,a)*h;if(u<-this.epsilon||c+u>1+this.epsilon)return null;const d=_e.Dot(r,a)*h;return d>this.length?null:new Rn(1-c-u,c,d)}intersectsPlane(e){let t;const i=_e.Dot(e.normal,this.direction);if(Math.abs(i)<9.99999997475243e-7)return null;{const s=_e.Dot(e.normal,this.origin);return t=(-e.d-s)/i,t<0?t<-9.99999997475243e-7?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const e=(this.origin.y-t)/this.direction.y;return e>0?null:new _e(this.origin.x+this.direction.x*-e,t,this.origin.z+this.direction.z*-e)}case"x":{const e=(this.origin.x-t)/this.direction.x;return e>0?null:new _e(t,this.origin.y+this.direction.y*-e,this.origin.z+this.direction.z*-e)}case"z":{const e=(this.origin.z-t)/this.direction.z;return e>0?null:new _e(this.origin.x+this.direction.x*-e,this.origin.y+this.direction.y*-e,t)}default:return null}}intersectsMesh(e,t,i,s=!1,r,n=!1){const o=ve.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?Ua.TransformToRef(this,o,this._tmpRay):this._tmpRay=Ua.Transform(this,o),e.intersects(this._tmpRay,t,i,s,r,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let s=0;st.distance?1:0}intersectionSegment(e,t,i){const s=this.origin,r=ve.Vector3[0],n=ve.Vector3[1],o=ve.Vector3[2],a=ve.Vector3[3];t.subtractToRef(e,r),this.direction.scaleToRef(Ua._Rayl,o),s.addToRef(o,n),e.subtractToRef(s,a);const l=_e.Dot(r,r),h=_e.Dot(r,o),c=_e.Dot(o,o),u=_e.Dot(r,a),d=_e.Dot(o,a),_=l*c-h*h;let p,f,m=_,g=_;_m&&(p=m,f=d+h,g=c)),f<0?(f=0,-u<0?p=0:-u>l?p=m:(p=-u,m=l)):f>g&&(f=g,-u+h<0?p=0:-u+h>l?p=m:(p=-u+h,m=l));const v=Math.abs(p)0&&x<=this.length&&y.lengthSquared()=e.distance?null:h:null},Hr.prototype._internalPick=function(e,t,i,s,r){let n=null;const o=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),a=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),n=this.cameraToUseForPointers||this.activeCamera;for(let o=0;o(this._tempPickingRay||(this._tempPickingRay=Ua.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,r||null),this._tempPickingRay)),i,s,!0);return n&&(n.ray=this.createPickingRay(e,t,me.Identity(),r||null)),n},Object.defineProperty(Hr.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),Hr.prototype.pick=function(e,t,i,s,r,n,o=!1){const a=this._internalPick(((i,s)=>(this._tempPickingRay||(this._tempPickingRay=Ua.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,r||null,!1,s),this._tempPickingRay)),i,s,!1,n);return a&&(a.ray=this.createPickingRay(e,t,me.Identity(),r||null)),a},Hr.prototype.pickWithRay=function(e,t,i,s){const r=this._internalPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=me.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Ua.Zero()),Ua.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i,!1,s);return r&&(r.ray=e),r},Hr.prototype.multiPick=function(e,t,i,s,r){return this._internalMultiPick((i=>this.createPickingRay(e,t,i,s||null)),i,r)},Hr.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=me.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=Ua.Zero()),Ua.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i)},In.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new Ua(_e.Zero(),_e.Zero(),e),e,t,i)},In.prototype.getForwardRayToRef=function(e,t=100,i,s){i||(i=this.getWorldMatrix()),e.length=t,s?e.origin.copyFrom(s):e.origin.copyFrom(this.position);const r=ve.Vector3[2];r.set(0,0,this._scene.useRightHandedSystem?-1:1);const n=ve.Vector3[3];return _e.TransformNormalToRef(r,i,n),_e.NormalizeToRef(n,e.direction),e};class Ga{static _RemoveAndStorePivotPoint(e){e&&0===Ga._PivotCached&&(e.getPivotPointToRef(Ga._OldPivotPoint),Ga._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,Ga._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(me.IdentityReadOnly),Ga._OldPivotPoint.subtractToRef(e.getPivotPoint(),Ga._PivotTranslation),Ga._PivotTmpVector.copyFromFloats(1,1,1),Ga._PivotTmpVector.subtractInPlace(e.scaling),Ga._PivotTmpVector.multiplyInPlace(Ga._PivotTranslation),e.position.addInPlace(Ga._PivotTmpVector))),Ga._PivotCached++}static _RestorePivotPoint(e){e&&!Ga._OldPivotPoint.equalsToFloats(0,0,0)&&1===Ga._PivotCached&&(e.setPivotPoint(Ga._OldPivotPoint),e._postMultiplyPivotMatrix=Ga._PivotPostMultiplyPivotMatrix,Ga._PivotTmpVector.copyFromFloats(1,1,1),Ga._PivotTmpVector.subtractInPlace(e.scaling),Ga._PivotTmpVector.multiplyInPlace(Ga._PivotTranslation),e.position.subtractInPlace(Ga._PivotTmpVector)),this._PivotCached--}}function za(e){const t=[],i=[],s=[],r=[],n=e.width||e.size||1,o=e.height||e.size||1,a=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,l=n/2,h=o/2;i.push(-l,-h,0),s.push(0,0,-1),r.push(0,Xn.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),s.push(0,0,-1),r.push(1,Xn.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),s.push(0,0,-1),r.push(1,Xn.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),s.push(0,0,-1),r.push(0,Xn.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),Wn._ComputeSides(a,i,t,s,r,e.frontUVs,e.backUVs);const c=new Wn;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function Wa(e,t={},i=null){const s=new ha(e,i);return t.sideOrientation=ha._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,za(t).applyToMesh(s,t.updatable),t.sourcePlane&&(s.translate(t.sourcePlane.normal,-t.sourcePlane.d),s.setDirection(t.sourcePlane.normal.scale(-1))),s}Ga._PivotCached=0,Ga._OldPivotPoint=new _e,Ga._PivotTranslation=new _e,Ga._PivotTmpVector=new _e,Ga._PivotPostMultiplyPivotMatrix=!1;const Ha={CreatePlane:Wa};Wn.CreatePlane=za,ha.CreatePlane=(e,t,i,s,r)=>Wa(e,{size:t,width:t,height:t,sideOrientation:r,updatable:s},i);class Xa{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new K,this.onDragStartObservable=new K,this.onDragEndObservable=new K,this.onEnabledObservable=new K,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new _e(0,0,0),this._alternatePickedPoint=new _e(0,0,0),this._worldDragAxis=new _e(0,0,0),this._targetPosition=new _e(0,0,0),this._attachedToElement=!1,this._startDragRay=new Ua(new _e,new _e),this._lastPointerRay={},this._dragDelta=new _e,this._pointA=new _e(0,0,0),this._pointC=new _e(0,0,0),this._localAxis=new _e(0,0,0),this._lookAt=new _e(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,Xa._PlaneScene||(this._debugMode?Xa._PlaneScene=this._scene:(Xa._PlaneScene=new Hr(this._scene.getEngine(),{virtual:!0}),Xa._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce((()=>{Xa._PlaneScene.dispose(),Xa._PlaneScene=null})))),this._dragPlane=Wa("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:ha.DOUBLESIDE},Xa._PlaneScene),this.lastDragPosition=new _e(0,0,0);const i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add((e=>{if(this.enabled){if(e.type==lr.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&i(e.pickInfo.pickedMesh)&&-1===this._activeDragButton&&-1!==this.dragButtons.indexOf(e.event.button)&&(this._activeDragButton=e.event.button,this._activePointerInfo=e,this._startDrag(e.event.pointerId,e.pickInfo.ray,e.pickInfo.pickedPoint));else if(e.type==lr.POINTERUP)!this.startAndReleaseDragOnPointerEvents||this.currentDraggingPointerId!=e.event.pointerId||this._activeDragButton!==e.event.button&&-1!==this._activeDragButton||this.releaseDrag();else if(e.type==lr.POINTERMOVE){const t=e.event.pointerId;if(this.currentDraggingPointerId===Xa._AnyMouseId&&t!==Xa._AnyMouseId){const i=e.event;("mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[t]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=t)}this._lastPointerRay[t]||(this._lastPointerRay[t]=new Ua(new _e,new _e)),e.pickInfo&&e.pickInfo.ray&&(this._lastPointerRay[t].origin.copyFrom(e.pickInfo.ray.origin),this._lastPointerRay[t].direction.copyFrom(e.pickInfo.ray.direction),this.currentDraggingPointerId==t&&this.dragging&&this._moveDrag(e.pickInfo.ray))}}else this._attachedToElement&&this.releaseDrag()})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{if(this._moving&&this.moveAttached){let e=!1;Ga._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),e=!0),Ga._RestorePivotPoint(this.attachedNode),e&&this.attachedNode.computeWorldMatrix()}}))}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){const e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}}startDrag(e=Xa._AnyMouseId,t,i){this._startDrag(e,t,i);let s=this._lastPointerRay[e];e===Xa._AnyMouseId&&(s=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),s&&this._moveDrag(s)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;Ga._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);const s=this._pickWithRayOnDragPlane(this._startDragRay);s?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(s),this.onDragStartObservable.notifyObservers({dragPlanePoint:s,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),Ga._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;const t=this._pickWithRayOnDragPlane(e);if(t){Ga._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?_e.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=_e.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),Ga._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(_e.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*_e.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);const t=_e.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-t,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}return null}const i=this._dragPlane.forward,s=this._dragPlane.position,r=e.direction.dot(i);if(Math.abs(r).999?Math.abs(_e.Dot(_e.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(_e.Right()):this._lookAt.copyFrom(_e.UpReadOnly):(_e.CrossToRef(this._localAxis,this._pointC,this._lookAt),_e.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?_e.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}}Xa._AnyMouseId=-2;class Ya{constructor(){this._startDistance=0,this._initialScale=new _e(0,0,0),this._targetScale=new _e(0,0,0),this._sceneRenderObserver=null,this._dragBehaviorA=new Xa({}),this._dragBehaviorA.moveAttached=!1,this._dragBehaviorB=new Xa({}),this._dragBehaviorB.moveAttached=!1}get name(){return"MultiPointerScale"}init(){}_getCurrentDistance(){return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length()}attach(e){this._ownerNode=e,this._dragBehaviorA.onDragStartObservable.add((()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorA.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))})),this._dragBehaviorB.onDragStartObservable.add((()=>{this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging&&(this._dragBehaviorA.currentDraggingPointerId==this._dragBehaviorB.currentDraggingPointerId?this._dragBehaviorB.releaseDrag():(this._initialScale.copyFrom(e.scaling),this._startDistance=this._getCurrentDistance()))})),[this._dragBehaviorA,this._dragBehaviorB].forEach((e=>{e.onDragObservable.add((()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const e=this._getCurrentDistance()/this._startDistance;this._initialScale.scaleToRef(e,this._targetScale)}}))})),e.addBehavior(this._dragBehaviorA),e.addBehavior(this._dragBehaviorB),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((()=>{if(this._dragBehaviorA.dragging&&this._dragBehaviorB.dragging){const t=this._targetScale.subtract(e.scaling).scaleInPlace(.1);t.length()>.01&&e.scaling.addInPlace(t)}}))}detach(){this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),[this._dragBehaviorA,this._dragBehaviorB].forEach((e=>{e.onDragStartObservable.clear(),e.onDragObservable.clear(),this._ownerNode.removeBehavior(e)}))}}class Qa{constructor(){this._attachedToElement=!1,this._virtualMeshesInfo={},this._tmpVector=new _e,this._tmpQuaternion=new fe,this._dragType={NONE:0,DRAG:1,DRAG_WITH_CONTROLLER:2,NEAR_DRAG:3},this._moving=!1,this._dragging=this._dragType.NONE,this.draggableMeshes=null,this.zDragFactor=3,this.currentDraggingPointerIds=[],this.detachCameraControls=!0,this.onDragStartObservable=new K,this.onDragObservable=new K,this.onDragEndObservable=new K,this.allowMultiPointer=!0}get currentDraggingPointerId(){return void 0!==this.currentDraggingPointerIds[0]?this.currentDraggingPointerIds[0]:-1}set currentDraggingPointerId(e){this.currentDraggingPointerIds[0]=e}get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}get name(){return"BaseSixDofDrag"}get isMoving(){return this._moving}init(){}get _pointerCamera(){return this._scene.cameraToUseForPointers?this._scene.cameraToUseForPointers:this._scene.activeCamera}_createVirtualMeshInfo(){const e=new _o("",Qa._virtualScene);e.rotationQuaternion=new fe;const t=new _o("",Qa._virtualScene);t.rotationQuaternion=new fe;const i=new _o("",Qa._virtualScene);return i.rotationQuaternion=new fe,{dragging:!1,moving:!1,dragMesh:e,originMesh:t,pivotMesh:i,startingPivotPosition:new _e,startingPivotOrientation:new fe,startingPosition:new _e,startingOrientation:new fe,lastOriginPosition:new _e,lastDragPosition:new _e}}_resetVirtualMeshesPosition(){for(let e=0;el&&(l=Math.min(h-a,0)),o.scaleInPlace(l),o.addToRef(r.pivotMesh.absolutePosition,this._tmpVector),r.pivotMesh.setAbsolutePosition(this._tmpVector),o.addToRef(r.dragMesh.absolutePosition,this._tmpVector),r.dragMesh.setAbsolutePosition(this._tmpVector)}}attach(e){this._ownerNode=e,this._scene=this._ownerNode.getScene(),Qa._virtualScene||(Qa._virtualScene=new Hr(this._scene.getEngine(),{virtual:!0}),Qa._virtualScene.detachControl());const t=e=>this._ownerNode===e||e.isDescendantOf(this._ownerNode)&&(!this.draggableMeshes||-1!==this.draggableMeshes.indexOf(e));this._pointerObserver=this._scene.onPointerObservable.add((e=>{const i=e.event.pointerId;this._virtualMeshesInfo[i]||(this._virtualMeshesInfo[i]=this._createVirtualMeshInfo());const s=this._virtualMeshesInfo[i],r="xr-near"===e.event.pointerType||"xr"===e.event.pointerType;if(e.type==lr.POINTERDOWN){if(!s.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&(!r||e.pickInfo.aimTransform)&&t(e.pickInfo.pickedMesh)){if((!this.allowMultiPointer||r)&&this.currentDraggingPointerIds.length>0)return;!this._pointerCamera||this._pointerCamera.cameraRigMode!==In.RIG_MODE_NONE||this._pointerCamera._isLeftCamera||this._pointerCamera._isRightCamera||e.pickInfo.ray.origin.copyFrom(this._pointerCamera.globalPosition),this._ownerNode.computeWorldMatrix(!0);const t=this._virtualMeshesInfo[i];r?(this._dragging=e.pickInfo.originMesh?this._dragType.NEAR_DRAG:this._dragType.DRAG_WITH_CONTROLLER,t.originMesh.position.copyFrom(e.pickInfo.aimTransform.position),this._dragging===this._dragType.NEAR_DRAG&&e.pickInfo.gripTransform?t.originMesh.rotationQuaternion.copyFrom(e.pickInfo.gripTransform.rotationQuaternion):t.originMesh.rotationQuaternion.copyFrom(e.pickInfo.aimTransform.rotationQuaternion)):(this._dragging=this._dragType.DRAG,t.originMesh.position.copyFrom(e.pickInfo.ray.origin)),t.lastOriginPosition.copyFrom(t.originMesh.position),t.dragMesh.position.copyFrom(e.pickInfo.pickedPoint),t.lastDragPosition.copyFrom(e.pickInfo.pickedPoint),t.pivotMesh.position.copyFrom(this._ownerNode.getAbsolutePivotPoint()),t.pivotMesh.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),t.startingPosition.copyFrom(t.dragMesh.position),t.startingPivotPosition.copyFrom(t.pivotMesh.position),t.startingOrientation.copyFrom(t.dragMesh.rotationQuaternion),t.startingPivotOrientation.copyFrom(t.pivotMesh.rotationQuaternion),r?(t.originMesh.addChild(t.dragMesh),t.originMesh.addChild(t.pivotMesh)):t.originMesh.lookAt(t.dragMesh.position),t.dragging=!0,-1===this.currentDraggingPointerIds.indexOf(i)&&this.currentDraggingPointerIds.push(i),this.detachCameraControls&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._pointerCamera.inputs&&this._pointerCamera.inputs.attachedToElement?(this._pointerCamera.detachControl(),this._attachedToElement=!0):this.allowMultiPointer&&0!==this.currentDraggingPointerIds.length||(this._attachedToElement=!1)),this._targetDragStart(t.pivotMesh.position,t.pivotMesh.rotationQuaternion,i),this.onDragStartObservable.notifyObservers({position:t.pivotMesh.position})}}else if(e.type==lr.POINTERUP||e.type==lr.POINTERDOUBLETAP){const e=this.currentDraggingPointerIds.indexOf(i);s.dragging=!1,-1!==e&&(this.currentDraggingPointerIds.splice(e,1),0===this.currentDraggingPointerIds.length&&(this._moving=!1,this._dragging=this._dragType.NONE,this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1)),s.originMesh.removeChild(s.dragMesh),s.originMesh.removeChild(s.pivotMesh),this._targetDragEnd(i),this.onDragEndObservable.notifyObservers({}))}else if(e.type==lr.POINTERMOVE&&-1!==this.currentDraggingPointerIds.indexOf(i)&&s.dragging&&e.pickInfo&&(e.pickInfo.ray||e.pickInfo.aimTransform)){let t=this.zDragFactor;(this.currentDraggingPointerIds.length>1||e.pickInfo.originMesh)&&(t=0),this._ownerNode.computeWorldMatrix(!0),r?this._pointerUpdateXR(e.pickInfo.aimTransform,e.pickInfo.gripTransform,i,t):this._pointerUpdate2D(e.pickInfo.ray,i,t),this._tmpQuaternion.copyFrom(s.startingPivotOrientation),this._tmpQuaternion.x=-this._tmpQuaternion.x,this._tmpQuaternion.y=-this._tmpQuaternion.y,this._tmpQuaternion.z=-this._tmpQuaternion.z,s.pivotMesh.absoluteRotationQuaternion.multiplyToRef(this._tmpQuaternion,this._tmpQuaternion),s.pivotMesh.absolutePosition.subtractToRef(s.startingPivotPosition,this._tmpVector),this.onDragObservable.notifyObservers({delta:this._tmpVector,position:s.pivotMesh.position,pickInfo:e.pickInfo}),this._targetDrag(this._tmpVector,this._tmpQuaternion,i),s.lastDragPosition.copyFrom(s.dragMesh.absolutePosition),this._moving=!0}}))}_applyZOffset(e,t,i){e.position.z-=e.position.z<1?t*i:t*i*e.position.z,e.position.z<0&&(e.position.z=0)}_targetDragStart(e,t,i){}_targetDrag(e,t,i){}_targetDragEnd(e){}_reattachCameraControls(){if(this._pointerCamera)if("ArcRotateCamera"===this._pointerCamera.getClassName()){const e=this._pointerCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._pointerCamera.attachControl(!this._pointerCamera.inputs||this._pointerCamera.inputs.noPreventDefault)}detach(){this._scene&&(this.detachCameraControls&&this._attachedToElement&&this._pointerCamera&&!this._pointerCamera.leftCamera&&(this._reattachCameraControls(),this._attachedToElement=!1),this._scene.onPointerObservable.remove(this._pointerObserver));for(const e in this._virtualMeshesInfo)this._virtualMeshesInfo[e].originMesh.dispose(),this._virtualMeshesInfo[e].dragMesh.dispose();this.onDragEndObservable.clear(),this.onDragObservable.clear(),this.onDragStartObservable.clear()}}class ja extends Qa{constructor(){super(...arguments),this._sceneRenderObserver=null,this._targetPosition=new _e(0,0,0),this._targetOrientation=new fe,this._targetScaling=new _e(1,1,1),this._startingPosition=new _e(0,0,0),this._startingOrientation=new fe,this._startingScaling=new _e(1,1,1),this.onPositionChangedObservable=new K,this.dragDeltaRatio=.2,this.rotateDraggedObject=!0,this.rotateAroundYOnly=!1,this.rotateWithMotionController=!0,this.disableMovement=!1,this.faceCameraOnDragStart=!1}get name(){return"SixDofDrag"}attach(e){super.attach(e),e.isNearGrabbable=!0,e.getChildMeshes().forEach((e=>{e.isNearGrabbable=!0})),this._virtualTransformNode=new lo("virtual_sixDof",Qa._virtualScene),this._virtualTransformNode.rotationQuaternion=fe.Identity(),this._sceneRenderObserver=e.getScene().onBeforeRenderObservable.add((()=>{if(1===this.currentDraggingPointerIds.length&&this._moving&&!this.disableMovement){const t=ve.Vector3[0];t.copyFrom(this._targetPosition).subtractInPlace(e.absolutePosition).scaleInPlace(this.dragDeltaRatio);const i=ve.Vector3[1];if(i.copyFrom(t),e.parent){const s=ve.Matrix[0];e.parent.absoluteRotationQuaternion.toRotationMatrix(s),s.invert(),_e.TransformNormalToRef(t,s,i)}if(e.position.addInPlace(i),this.onPositionChangedObservable.notifyObservers({position:e.absolutePosition}),!e.parent||e.parent.scaling&&!e.parent.scaling.isNonUniformWithinEpsilon(.001)){const t=ve.Quaternion[0];if(t.copyFrom(this._targetOrientation),e.parent){const i=ve.Quaternion[0];i.copyFrom(e.parent.absoluteRotationQuaternion),i.invertInPlace(),i.multiplyToRef(this._targetOrientation,t)}fe.SlerpToRef(e.rotationQuaternion,t,this.dragDeltaRatio,e.rotationQuaternion)}}}))}_getPositionOffsetAround(e,t,i){const s=ve.Matrix[0],r=ve.Matrix[1],n=ve.Matrix[2],o=ve.Matrix[3],a=ve.Matrix[4];return me.TranslationToRef(e.x,e.y,e.z,s),me.TranslationToRef(-e.x,-e.y,-e.z,r),me.FromQuaternionToRef(i,n),me.ScalingToRef(t,t,t,o),r.multiplyToRef(n,a),a.multiplyToRef(o,a),a.multiplyToRef(s,a),a.getTranslation()}_onePointerPositionUpdated(e,t){ve.Vector3[0].setAll(0),this._dragging===this._dragType.DRAG?this.rotateDraggedObject&&(this.rotateAroundYOnly?fe.RotationYawPitchRollToRef(t.toEulerAngles().y,0,0,ve.Quaternion[0]):ve.Quaternion[0].copyFrom(t),ve.Quaternion[0].multiplyToRef(this._startingOrientation,this._targetOrientation)):(this._dragging===this._dragType.NEAR_DRAG||this._dragging===this._dragType.DRAG_WITH_CONTROLLER&&this.rotateWithMotionController)&&t.multiplyToRef(this._startingOrientation,this._targetOrientation),this._targetPosition.copyFrom(this._startingPosition).addInPlace(e)}_twoPointersPositionUpdated(){const e=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].startingPosition,t=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].startingPosition,i=ve.Vector3[0];e.addToRef(t,i),i.scaleInPlace(.5);const s=ve.Vector3[1];t.subtractToRef(e,s);const r=this._virtualMeshesInfo[this.currentDraggingPointerIds[0]].dragMesh.absolutePosition,n=this._virtualMeshesInfo[this.currentDraggingPointerIds[1]].dragMesh.absolutePosition,o=ve.Vector3[2];r.addToRef(n,o),o.scaleInPlace(.5);const a=ve.Vector3[3];n.subtractToRef(r,a);const l=a.length()/s.length(),h=o.subtract(i),c=fe.FromEulerAngles(0,_e.GetAngleBetweenVectorsOnPlane(s.normalize(),a.normalize(),_e.UpReadOnly),0),u=this._ownerNode.parent;this._ownerNode.setParent(null);const d=this._getPositionOffsetAround(i.subtract(this._virtualTransformNode.getAbsolutePivotPoint()),l,c);this._virtualTransformNode.rotationQuaternion.multiplyToRef(c,this._ownerNode.rotationQuaternion),this._virtualTransformNode.scaling.scaleToRef(l,this._ownerNode.scaling),this._virtualTransformNode.position.addToRef(h.addInPlace(d),this._ownerNode.position),this.onPositionChangedObservable.notifyObservers({position:this._ownerNode.position}),this._ownerNode.setParent(u)}_targetDragStart(){const e=this.currentDraggingPointerIds.length;this._ownerNode.rotationQuaternion||(this._ownerNode.rotationQuaternion=fe.RotationYawPitchRoll(this._ownerNode.rotation.y,this._ownerNode.rotation.x,this._ownerNode.rotation.z));const t=this._ownerNode.getAbsolutePivotPoint();if(1===e){if(this._targetPosition.copyFrom(this._ownerNode.absolutePosition),this._targetOrientation.copyFrom(this._ownerNode.rotationQuaternion),this._targetScaling.copyFrom(this._ownerNode.absoluteScaling),this.faceCameraOnDragStart&&this._scene.activeCamera){const e=ve.Vector3[0];this._scene.activeCamera.position.subtractToRef(t,e),e.normalize();const i=ve.Quaternion[0];this._scene.useRightHandedSystem?fe.FromLookDirectionRHToRef(e,new _e(0,1,0),i):fe.FromLookDirectionLHToRef(e,new _e(0,1,0),i),i.normalize(),fe.RotationYawPitchRollToRef(i.toEulerAngles().y,0,0,ve.Quaternion[0]),this._targetOrientation.copyFrom(ve.Quaternion[0])}this._startingPosition.copyFrom(this._targetPosition),this._startingOrientation.copyFrom(this._targetOrientation),this._startingScaling.copyFrom(this._targetScaling)}else 2===e&&(this._virtualTransformNode.setPivotPoint(new _e(0,0,0),Ur.LOCAL),this._virtualTransformNode.position.copyFrom(this._ownerNode.absolutePosition),this._virtualTransformNode.scaling.copyFrom(this._ownerNode.absoluteScaling),this._virtualTransformNode.rotationQuaternion.copyFrom(this._ownerNode.absoluteRotationQuaternion),this._virtualTransformNode.setPivotPoint(t,Ur.WORLD),this._resetVirtualMeshesPosition())}_targetDrag(e,t){1===this.currentDraggingPointerIds.length?this._onePointerPositionUpdated(e,t):2===this.currentDraggingPointerIds.length&&this._twoPointersPositionUpdated()}_targetDragEnd(){if(1===this.currentDraggingPointerIds.length){this._resetVirtualMeshesPosition();const e=this.faceCameraOnDragStart;this.faceCameraOnDragStart=!1,this._targetDragStart(),this.faceCameraOnDragStart=e}}detach(){super.detach(),this._ownerNode&&this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver),this._virtualTransformNode&&this._virtualTransformNode.dispose()}}class Ka{constructor(){this._attachPointLocalOffset=new _e,this._workingPosition=new _e,this._workingQuaternion=new fe,this._lastTick=-1,this._hit=!1,this.hitNormalOffset=.05,this.meshes=[],this.interpolatePose=!0,this.lerpTime=250,this.keepOrientationVertical=!0,this.enabled=!0,this.maxStickingDistance=.8}get name(){return"SurfaceMagnetism"}init(){}attach(e,t){this._attachedMesh=e,this._scene=t||e.getScene(),this._attachedMesh.rotationQuaternion||(this._attachedMesh.rotationQuaternion=fe.RotationYawPitchRoll(this._attachedMesh.rotation.y,this._attachedMesh.rotation.x,this._attachedMesh.rotation.z)),this.updateAttachPoint(),this._workingPosition.copyFrom(this._attachedMesh.position),this._workingQuaternion.copyFrom(this._attachedMesh.rotationQuaternion),this._addObservables()}detach(){this._attachedMesh=null,this._removeObservables()}_getTargetPose(e){if(!this._attachedMesh)return null;if(e&&e.hit){const t=e.getNormal(!0,!0),i=e.pickedPoint;if(!t||!i)return null;t.normalize();const s=ve.Vector3[0];return s.copyFrom(t),s.scaleInPlace(this.hitNormalOffset),s.addInPlace(i),this._attachedMesh.parent&&(ve.Matrix[0].copyFrom(this._attachedMesh.parent.getWorldMatrix()).invert(),_e.TransformNormalToRef(s,ve.Matrix[0],s)),{position:s,quaternion:fe.RotationYawPitchRoll(-Math.atan2(t.x,-t.z),this.keepOrientationVertical?0:Math.atan2(t.y,Math.sqrt(t.z*t.z+t.x*t.x)),0)}}return null}updateAttachPoint(){this._getAttachPointOffsetToRef(this._attachPointLocalOffset)}findAndUpdateTarget(e){if(this._hit=!1,!e.ray)return!1;const t=e.ray.intersectsMeshes(this.meshes)[0];if(this._attachedMesh&&t&&t.hit&&t.pickedMesh){const e=this._getTargetPose(t);e&&_e.Distance(this._attachedMesh.position,e.position){this.enabled&&e.type==lr.POINTERMOVE&&e.pickInfo&&this.findAndUpdateTarget(e.pickInfo)})),this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((()=>{const e=Date.now();this._updateTransformToGoal(e-this._lastTick),this._lastTick=e}))}_removeObservables(){this._scene.onPointerObservable.remove(this._pointerObserver),this._scene.onBeforeRenderObservable.remove(this._onBeforeRender),this._pointerObserver=null,this._onBeforeRender=null}}class $a{constructor(){this._tmpQuaternion=new fe,this._tmpVectors=[new _e,new _e,new _e,new _e,new _e,new _e,new _e],this._tmpMatrix=new me,this._tmpInvertView=new me,this._tmpForward=new _e,this._tmpNodeForward=new _e,this._tmpPosition=new _e,this._workingPosition=new _e,this._workingQuaternion=new fe,this._lastTick=-1,this._recenterNextUpdate=!0,this.interpolatePose=!0,this.lerpTime=500,this.ignoreCameraPitchAndRoll=!1,this.pitchOffset=15,this.maxViewVerticalDegrees=30,this.maxViewHorizontalDegrees=30,this.orientToCameraDeadzoneDegrees=60,this.ignoreDistanceClamp=!1,this.ignoreAngleClamp=!1,this.verticalMaxDistance=0,this.defaultDistance=.8,this.maximumDistance=2,this.minimumDistance=.3,this.useFixedVerticalOffset=!1,this.fixedVerticalOffset=0,this._enabled=!0}get followedCamera(){return this._followedCamera||this._scene.activeCamera}set followedCamera(e){this._followedCamera=e}get name(){return"Follow"}init(){}attach(e,t){this._scene=e.getScene(),this.attachedNode=e,t&&(this.followedCamera=t),this._addObservables()}detach(){this.attachedNode=null,this._removeObservables()}recenter(){this._recenterNextUpdate=!0}_angleBetweenVectorAndPlane(e,t){return this._tmpVectors[0].copyFrom(e),e=this._tmpVectors[0],this._tmpVectors[1].copyFrom(t),t=this._tmpVectors[1],e.normalize(),t.normalize(),Math.PI/2-Math.acos(_e.Dot(e,t))}_length2D(e){return Math.sqrt(e.x*e.x+e.z*e.z)}_distanceClamp(e,t=!1){let i=this.minimumDistance,s=this.maximumDistance;const r=this.defaultDistance,n=this._tmpVectors[0];n.copyFrom(e);let o=n.length();if(n.normalizeFromLength(o),this.ignoreCameraPitchAndRoll){i=this._length2D(n)*i,s=this._length2D(n)*s;const t=this._length2D(e);n.scaleInPlace(o/t),o=t}let a=o;return a=t?r:be.Clamp(o,i,s),e.copyFrom(n).scaleInPlace(a),o!==a}_applyVerticalClamp(e){0!==this.verticalMaxDistance&&(e.y=be.Clamp(e.y,-this.verticalMaxDistance,this.verticalMaxDistance))}_toOrientationQuatToRef(e,t){fe.RotationYawPitchRollToRef(Math.atan2(e.x,e.z),Math.atan2(e.y,Math.sqrt(e.z*e.z+e.x*e.x)),0,t)}_applyPitchOffset(e){const t=this._tmpVectors[0],i=this._tmpVectors[1];t.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),i.copyFromFloats(1,0,0),_e.TransformNormalToRef(t,e,t),t.y=0,t.normalize(),_e.TransformNormalToRef(i,e,i),fe.RotationAxisToRef(i,this.pitchOffset*Math.PI/180,this._tmpQuaternion),t.rotateByQuaternionToRef(this._tmpQuaternion,t),this._toOrientationQuatToRef(t,this._tmpQuaternion),this._tmpQuaternion.toRotationMatrix(this._tmpMatrix),e.copyFrom(this._tmpMatrix)}_angularClamp(e,t){const i=this._tmpVectors[5];i.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1);const s=this._tmpVectors[6];s.copyFromFloats(1,0,0),_e.TransformNormalToRef(i,e,i),_e.TransformNormalToRef(s,e,s);const r=_e.UpReadOnly;if(t.length()r&&(fe.RotationAxisToRef(s,-e+r,o),t.rotateByQuaternionToRef(o,t),n=!0)}const a=this._angleBetweenVectorAndPlane(t,s)*(this._scene.useRightHandedSystem?-1:1),l=this.maxViewHorizontalDegrees*Math.PI/180*.5;return a<-l?(fe.RotationAxisToRef(r,-a-l,o),t.rotateByQuaternionToRef(o,t),n=!0):a>l&&(fe.RotationAxisToRef(r,-a+l,o),t.rotateByQuaternionToRef(o,t),n=!0),n}_orientationClamp(e,t){const i=this._tmpVectors[0];i.copyFrom(e).scaleInPlace(-1).normalize();const s=this._tmpVectors[1],r=this._tmpVectors[2];s.copyFromFloats(0,1,0),_e.CrossToRef(i,s,r);const n=r.length();nthis.orientToCameraDeadzoneDegrees}_updateLeashing(e){if(this.attachedNode&&this._enabled){const t=this.attachedNode.parent;this.attachedNode.setParent(null);const i=this.attachedNode.getWorldMatrix(),s=this._workingPosition,r=this._workingQuaternion,n=this.attachedNode.getPivotPoint(),o=this._tmpInvertView;o.copyFrom(e.getViewMatrix()),o.invert(),_e.TransformCoordinatesToRef(n,i,s);const a=this._tmpPosition;a.copyFromFloats(0,0,0),_e.TransformCoordinatesToRef(a,i,a),a.scaleInPlace(-1).subtractInPlace(n),s.subtractInPlace(e.globalPosition),this.ignoreCameraPitchAndRoll&&this._applyPitchOffset(o);let l=!1;const h=this._tmpForward;h.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),_e.TransformNormalToRef(h,o,h);const c=this._tmpNodeForward;if(c.copyFromFloats(0,0,this._scene.useRightHandedSystem?-1:1),_e.TransformNormalToRef(c,i,c),this._recenterNextUpdate)s.copyFrom(h).scaleInPlace(this.defaultDistance);else if(this.ignoreAngleClamp){const e=s.length();s.copyFrom(h).scaleInPlace(e)}else l=this._angularClamp(o,s);let u=!1;this.ignoreDistanceClamp||(u=this._distanceClamp(s,l),this._applyVerticalClamp(s)),this.useFixedVerticalOffset&&(s.y=a.y-e.globalPosition.y+this.fixedVerticalOffset),(l||u||this._passedOrientationDeadzone(s,c)||this._recenterNextUpdate)&&this._orientationClamp(s,r),this._workingPosition.subtractInPlace(n),this._recenterNextUpdate=!1,this.attachedNode.setParent(t)}}_updateTransformToGoal(e){if(!this.attachedNode||!this.followedCamera||!this._enabled)return;this.attachedNode.rotationQuaternion||(this.attachedNode.rotationQuaternion=fe.Identity());const t=this.attachedNode.parent;if(this.attachedNode.setParent(null),!this.interpolatePose)return this.attachedNode.position.copyFrom(this.followedCamera.globalPosition).addInPlace(this._workingPosition),void this.attachedNode.rotationQuaternion.copyFrom(this._workingQuaternion);const i=new _e;i.copyFrom(this.attachedNode.position).subtractInPlace(this.followedCamera.globalPosition),_e.SmoothToRef(i,this._workingPosition,e,this.lerpTime,i),i.addInPlace(this.followedCamera.globalPosition),this.attachedNode.position.copyFrom(i);const s=new fe;s.copyFrom(this.attachedNode.rotationQuaternion),fe.SmoothToRef(s,this._workingQuaternion,e,this.lerpTime,this.attachedNode.rotationQuaternion),this.attachedNode.setParent(t)}_addObservables(){this._lastTick=Date.now(),this._onBeforeRender=this._scene.onBeforeRenderObservable.add((()=>{if(!this.followedCamera)return;const e=Date.now();this._updateLeashing(this.followedCamera),this._updateTransformToGoal(e-this._lastTick),this._lastTick=e}))}_removeObservables(){this._onBeforeRender&&this._scene.onBeforeRenderObservable.remove(this._onBeforeRender)}}class qa{}qa.ANCHOR_SYSTEM="xr-anchor-system",qa.BACKGROUND_REMOVER="xr-background-remover",qa.HIT_TEST="xr-hit-test",qa.MESH_DETECTION="xr-mesh-detection",qa.PHYSICS_CONTROLLERS="xr-physics-controller",qa.PLANE_DETECTION="xr-plane-detection",qa.POINTER_SELECTION="xr-controller-pointer-selection",qa.TELEPORTATION="xr-controller-teleportation",qa.FEATURE_POINTS="xr-feature-points",qa.HAND_TRACKING="xr-hand-tracking",qa.IMAGE_TRACKING="xr-image-tracking",qa.NEAR_INTERACTION="xr-near-interaction",qa.DOM_OVERLAY="xr-dom-overlay",qa.MOVEMENT="xr-controller-movement",qa.LIGHT_ESTIMATION="xr-light-estimation",qa.EYE_TRACKING="xr-eye-tracking",qa.WALKING_LOCOMOTION="xr-walking-locomotion",qa.LAYERS="xr-layers",qa.DEPTH_SENSING="xr-depth-sensing",qa.SPACE_WARP="xr-space-warp",qa.RAW_CAMERA_ACCESS="xr-raw-camera-access";class Za{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)}))})),this._xrSessionManager.onXRSessionEnded.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)}))}))}static AddWebXRFeature(e,t,i=1,s=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),s&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,s){const r=this._AvailableFeatures[e][t];if(!r)throw new Error("feature not found");return r(i,s)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){const t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&(t.featureImplementation.attach()||Ds.Warn(`Feature ${e} failed to attach`))}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&(t.featureImplementation.detach()||Ds.Warn(`Feature ${e} failed to detach`))}disableFeature(e){const t="string"==typeof e?e:e.Name,i=this._features[t];return!(!i||!i.enabled||(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],0))}dispose(){this.getEnabledFeatures().forEach((e=>{this.disableFeature(e)}))}enableFeature(e,t="latest",i={},s=!0,r=!0){const n="string"==typeof e?e:e.Name;let o=0;if("string"==typeof t){if(!t)throw new Error(`Error in provided version - ${n} (${t})`);if(o="stable"===t?Za.GetStableVersionOfFeature(n):"latest"===t?Za.GetLatestVersionOfFeature(n):+t,-1===o||isNaN(o))throw new Error(`feature not found - ${n} (${t})`)}else o=t;const a=Za._ConflictingFeatures[n];if(void 0!==a&&-1!==this.getEnabledFeatures().indexOf(a))throw new Error(`Feature ${n} cannot be enabled while ${a} is enabled.`);const l=this._features[n],h=Za.ConstructFeature(n,o,this._xrSessionManager,i);if(!h)throw new Error(`feature not found - ${n}`);l&&this.disableFeature(n);const c=h();if(c.dependsOn){const e=c.dependsOn.every((e=>!!this._features[e]));if(!e)throw new Error(`Dependant features missing. Make sure the following features are enabled - ${c.dependsOn.join(", ")}`)}if(c.isCompatible())return this._features[n]={featureImplementation:c,enabled:!0,version:o,required:r},s?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(r)throw new Error("required feature not compatible");return Ds.Warn(`Feature ${n} not compatible with the current environment/browser and was not enabled.`),c}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){const t=this.getEnabledFeatures();for(const i of t){const t=this._features[i],s=t.featureImplementation.xrNativeFeatureName;if(s&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(s)&&e.requiredFeatures.push(s)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(s)&&e.optionalFeatures.push(s))),t.featureImplementation.getXRSessionInitExtension){const i=await t.featureImplementation.getXRSessionInitExtension();e={...e,...i}}}return e}}Za._AvailableFeatures={},Za._ConflictingFeatures={[qa.TELEPORTATION]:qa.MOVEMENT,[qa.MOVEMENT]:qa.TELEPORTATION};class Ja{get xrNativeFeatureName(){return this._xrNativeFeatureName}set xrNativeFeatureName(e){!this._xrSessionManager.isNative&&e&&this._xrSessionManager.inXRSession&&-1===this._xrSessionManager.enabledFeatures?.indexOf(e)&&Ne.Warn(`The feature ${e} needs to be enabled before starting the XR session. Note - It is still possible it is not supported.`),this._xrNativeFeatureName=e}constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this._xrNativeFeatureName="",this.onFeatureAttachObservable=new K,this.onFeatureDetachObservable=new K}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;if(this._xrSessionManager.enabledFeatures){if(!this._xrSessionManager.isNative&&this.xrNativeFeatureName&&-1===this._xrSessionManager.enabledFeatures.indexOf(this.xrNativeFeatureName))return!1}else Ne.Warn("session.enabledFeatures is not available on this device. It is possible that this feature is not supported.");return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,(e=>this._onXRFrame(e))),this.onFeatureAttachObservable.notifyObservers(this),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach((e=>{e.observable.remove(e.observer)})),this.onFeatureDetachObservable.notifyObservers(this),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0,this.onFeatureAttachObservable.clear(),this.onFeatureDetachObservable.clear()}isCompatible(){return!0}_addNewAttachObserver(e,t,i){this._removeOnDetach.push({observable:e,observer:e.add(t,void 0,i)})}}class el{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint,this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}el.DistanceJoint=0,el.HingeJoint=1,el.BallAndSocketJoint=2,el.WheelJoint=3,el.SliderJoint=4,el.PrismaticJoint=5,el.UniversalJoint=6,el.Hinge2Joint=el.WheelJoint,el.PointToPointJoint=8,el.SpringJoint=9,el.LockJoint=10;class tl extends el{constructor(e){super(el.DistanceJoint,e)}updateDistance(e,t){this._physicsPlugin.updateDistanceJoint(this,e,t)}}class il extends el{constructor(e,t){super(e,t)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class sl extends il{constructor(e){super(el.HingeJoint,e)}setMotor(e,t){this._physicsPlugin.setMotor(this,e||0,t)}setLimit(e,t){this._physicsPlugin.setLimit(this,e,t)}}class rl extends il{constructor(e){super(el.Hinge2Joint,e)}setMotor(e,t,i=0){this._physicsPlugin.setMotor(this,e||0,t,i)}setLimit(e,t,i=0){this._physicsPlugin.setLimit(this,e,t,i)}}ha._PhysicsImpostorParser=function(e,t,i){return new nl(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};class nl{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},s){this.object=e,this.type=t,this._options=i,this._scene=s,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=_e.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new fe,this._tmpQuat2=new fe,this.beforeStep=()=>{this._physicsEngine&&(this.object.translate(this._deltaPosition,-1),this._deltaRotationConjugated&&this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated,this.object.rotationQuaternion),this.object.computeWorldMatrix(!1),this.object.parent&&this.object.rotationQuaternion?(this.getParentsRotation(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this._tmpQuat)):this._tmpQuat.copyFrom(this.object.rotationQuaternion||new fe),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach((e=>{e(this)})))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach((e=>{e(this)})),this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this),this.object.parent&&this.object.rotationQuaternion&&(this.getParentsRotation(),this._tmpQuat.conjugateInPlace(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this.object.rotationQuaternion)),this.object.setAbsolutePosition(this.object.position),this._deltaRotation?(this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotation,this.object.rotationQuaternion),this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation,nl._TmpVecs[0]),this.object.translate(nl._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=e=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent)return;if(!this._physicsEngine)return;const t=this._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(this.onCollideEvent&&this.onCollideEvent(this,t),this._onPhysicsCollideCallbacks.filter((e=>-1!==e.otherImpostors.indexOf(t))).forEach((i=>{i.callback(this,t,e.point,e.distance,e.impulse,e.normal)})))},this.object?(this.object.parent&&0!==i.mass&&Ne.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),this._scene&&(this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=fe.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new fe),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&Ne.Warn("You must affect impostors to children before affecting impostor to parent.")):Ne.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):Ne.Error("No object was provided. A physics object is obligatory")}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))}_getPhysicsParent(){return this.object.parent instanceof _o?this.object.parent.physicsImpostor:null}isBodyInitRequired(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)}setScalingUpdated(){this.forceUpdate()}forceUpdate(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()}get physicsBody(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody}get parent(){return!this._options.ignoreParent&&this._parent?this._parent:null}set parent(e){this._parent=e}set physicsBody(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()}resetUpdateFlags(){this._bodyUpdateRequired=!1}getObjectExtents(){if(this.object.getBoundingInfo){const e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=nl.IDENTITY_QUATERNION;const i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);const s=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return s.x=Math.abs(s.x),s.y=Math.abs(s.y),s.z=Math.abs(s.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),s}return nl.DEFAULT_OBJECT_SIZE}getObjectCenter(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.centerWorld:this.object.position}getParam(e){return this._options[e]}setParam(e,t){this._options[e]=t,this._bodyUpdateRequired=!0}setMass(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)}getLinearVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):_e.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):_e.Zero()}setAngularVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)}executeNativeFunction(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)}registerBeforePhysicsStep(e){this._onBeforePhysicsStepCallbacks.push(e)}unregisterBeforePhysicsStep(e){const t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):Ne.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){const t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):Ne.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];let s=-1;this._onPhysicsCollideCallbacks.some(((e,r)=>{if(e.callback===t&&e.otherImpostors.length===i.length){const t=e.otherImpostors.every((e=>i.indexOf(e)>-1));return t&&(s=r),t}return!1}))?this._onPhysicsCollideCallbacks.splice(s,1):Ne.Warn("Function to remove was not found")}getParentsRotation(){let e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):fe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){const s=new el(t,i);return this.addJoint(e,s),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,s,r){if(!this._physicsEngine)return this;const n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor?(this._physicsEngine&&n.appendAnchor(this,e,t,i,s,r),this):this}addHook(e,t,i,s){if(!this._physicsEngine)return this;const r=this._physicsEngine.getPhysicsPlugin();return r.appendAnchor?(this._physicsEngine&&r.appendHook(this,e,t,i,s),this):this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new nl(e,this.type,this._options,this._scene):null}dispose(){this._physicsEngine&&(this._joints.forEach((e=>{this._physicsEngine&&this._physicsEngine.removeJoint(this,e.otherImpostor,e.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)}setDeltaPosition(e){this._deltaPosition.copyFrom(e)}setDeltaRotation(e){this._deltaRotation||(this._deltaRotation=new fe),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,s,r){const n=nl._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(r){const i=nl._TmpQuat;o.rotationQuaternion.multiplyToRef(r,i),e.setRotationQuaternion(i,Ur.WORLD,t)}else e.setRotationQuaternion(o.rotationQuaternion,Ur.WORLD,t);n.x=0,n.y=0,n.z=0,i&&(n.x=i.x,n.y=i.y,n.z=i.z,e.getDirectionToRef(n,t,n),null==s&&(s=i.length()),n.x*=s,n.y*=s,n.z*=s),e.getParent()?(n.addInPlace(o.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(o.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,s,r,n){const o=this.object;if(o.rotationQuaternion)if(r){const i=nl._TmpQuat;e.getRotationQuaternionToRef(Ur.WORLD,t,i),i.multiplyToRef(r,o.rotationQuaternion)}else e.getRotationQuaternionToRef(Ur.WORLD,t,o.rotationQuaternion);const a=nl._TmpVecs[0],l=nl._TmpVecs[1];n||((n=nl._TmpVecs[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,a),null==s&&i&&(s=i.length()),null!=s&&(a.x+=l.x*s,a.y+=l.y*s,a.z+=l.z*s),o.setAbsolutePosition(a)}}var ol,al,ll,hl,cl,ul,dl,_l,pl;nl.DEFAULT_OBJECT_SIZE=new _e(1,1,1),nl.IDENTITY_QUATERNION=fe.Identity(),nl._TmpVecs=ee.BuildArray(3,_e.Zero),nl._TmpQuat=fe.Identity(),nl.NoImpostor=0,nl.SphereImpostor=1,nl.BoxImpostor=2,nl.PlaneImpostor=3,nl.MeshImpostor=4,nl.CapsuleImpostor=6,nl.CylinderImpostor=7,nl.ParticleImpostor=8,nl.HeightmapImpostor=9,nl.ConvexHullImpostor=10,nl.CustomImpostor=100,nl.RopeImpostor=101,nl.ClothImpostor=102,nl.SoftbodyImpostor=103,function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(ol||(ol={}));class fl{static get ForceFullSceneLoadingForIncremental(){return Hn.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Hn.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Hn.ShowLoadingScreen}static set ShowLoadingScreen(e){Hn.ShowLoadingScreen=e}static get loggingLevel(){return Hn.loggingLevel}static set loggingLevel(e){Hn.loggingLevel=e}static get CleanBoneMatrixWeights(){return Hn.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Hn.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return fl._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){return fl._RegisteredPlugins[e]||(Ne.Warn("Unable to find a plugin to load "+e+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),fl.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in fl._RegisteredPlugins){const i=fl._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return fl._RegisteredPlugins[t]}return fl.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const i=e.lastIndexOf("."),s=e.substring(i,e.length).toLowerCase();return fl._GetPluginForExtension(s)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let s="Unable to load from "+(e.rawData?"binary data":e.url);return t?s+=`: ${t}`:i&&(s+=`: ${i}`),s}static _LoadData(e,t,i,s,r,n,o,a){const l=fl._GetDirectLoad(e.url);if(e.rawData&&!o)throw"When using ArrayBufferView to load data the file extension must be provided.";const h=o?fl._GetPluginForExtension(o):l?fl._GetPluginForDirectLoad(e.url):fl._GetPluginForFilename(e.url);if(e.rawData&&!h.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";let c;if(c=void 0!==h.plugin.createPlugin?h.plugin.createPlugin():h.plugin,!c)throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(fl.OnPluginActivatedObservable.notifyObservers(c),l&&(c.canDirectLoad&&c.canDirectLoad(e.url)||!gs(e.url))){if(c.directLoad){const e=c.directLoad(t,l);e.then?e.then((e=>{i(c,e)})).catch((e=>{r("Error in directLoad of _loadData: "+e,e)})):i(c,e)}else i(c,l);return c}const u=h.isBinary,d=(e,s)=>{t.isDisposed?r("Scene has been disposed"):i(c,e,s)};let _=null,p=!1;const f=c.onDisposeObservable;f&&f.add((()=>{p=!0,_&&(_.abort(),_=null),n()}));const m=()=>{if(p)return;const i=(e,t)=>{r(e?.statusText,t)};if(!c.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";_=c.loadFile?c.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,d,s,u,i,a):t._loadFile(e.file||e.url,d,s,!0,u,i)},g=t.getEngine();let v=g.enableOfflineSupport;if(v){let i=!1;for(const s of t.disableOfflineSupportExceptionRules)if(s.test(e.url)){i=!0;break}v=!i}return v&&oo.OfflineProviderFactory?t.offlineProvider=oo.OfflineProviderFactory(e.url,m,g.disableManifestCheck):m(),c}static _GetFileInfo(e,t){let i,s,r=null,n=null;if(t)if(t.name){const e=t;i=`file:${e.name}`,s=e.name,r=e}else if(ArrayBuffer.isView(t))i="",s=Cs(),n=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,s="";else{const r=t;if("/"===r.substr(0,1))return Ds.Error("Wrong sceneFilename parameter"),null;i=e+r,s=r}else i=e,s=Ds.GetFilename(e),e=Ds.GetFolderPath(e);return{url:i,rootUrl:e,name:s,file:r,rawData:n}}static GetPluginForExtension(e){return fl._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!fl._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){const t=e.extensions;fl._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{fl._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}}))}}static ImportMesh(e,t,i="",s=re.LastCreatedScene,r=null,n=null,o=null,a=null,l=""){if(!s)return Ne.Error("No scene available to import mesh to"),null;const h=fl._GetFileInfo(t,i);if(!h)return null;const c={};s.addPendingData(c);const u=()=>{s.removePendingData(c)},d=(e,t)=>{const i=fl._FormatErrorMessage(h,e,t);o?o(s,i,new jt(i,Qt.SceneLoaderError,t)):Ne.Error(i),u()},_=n?e=>{try{n(e)}catch(e){d("Error in onProgress callback: "+e,e)}}:void 0,p=(e,t,i,n,o,a,l,u)=>{if(s.importedMeshesFiles.push(h.url),r)try{r(e,t,i,n,o,a,l,u)}catch(e){d("Error in onSuccess callback: "+e,e)}s.removePendingData(c)};return fl._LoadData(h,s,((t,i,r)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,r)),t.importMesh){const r=[],n=[],o=[];if(!t.importMesh(e,s,i,h.rootUrl,r,n,o,d))return;s.loadingPluginName=t.name,p(r,n,o,[],[],[],[],[])}else t.importMeshAsync(e,s,i,h.rootUrl,_,h.name).then((e=>{s.loadingPluginName=t.name,p(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights,e.spriteManagers)})).catch((e=>{d(e.message,e)}))}),_,d,u,a,l)}static ImportMeshAsync(e,t,i="",s=re.LastCreatedScene,r=null,n=null,o=""){return new Promise(((a,l)=>{fl.ImportMesh(e,t,i,s,((e,t,i,s,r,n,o,l)=>{a({meshes:e,particleSystems:t,skeletons:i,animationGroups:s,transformNodes:r,geometries:n,lights:o,spriteManagers:l})}),r,((e,t,i)=>{l(i||new Error(t))}),n,o)}))}static Load(e,t="",i=re.LastCreatedEngine,s=null,r=null,n=null,o=null,a=""){return i?fl.Append(e,t,new Hr(i),s,r,n,o,a):(Ds.Error("No engine available"),null)}static LoadAsync(e,t="",i=re.LastCreatedEngine,s=null,r=null,n=""){return new Promise(((o,a)=>{fl.Load(e,t,i,(e=>{o(e)}),s,((e,t,i)=>{a(i||new Error(t))}),r,n)}))}static Append(e,t="",i=re.LastCreatedScene,s=null,r=null,n=null,o=null,a=""){if(!i)return Ne.Error("No scene available to append to"),null;const l=fl._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)};fl.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1})));const u=(e,t)=>{const s=fl._FormatErrorMessage(l,e,t);n?n(i,s,new jt(s,Qt.SceneLoaderError,t)):Ne.Error(s),c()},d=r?e=>{try{r(e)}catch(e){u("Error in onProgress callback",e)}}:void 0,_=()=>{if(s)try{s(i)}catch(e){u("Error in onSuccess callback",e)}i.removePendingData(h)};return fl._LoadData(l,i,((e,t)=>{if(e.load){if(!e.load(i,t,l.rootUrl,u))return;i.loadingPluginName=e.name,_()}else e.loadAsync(i,t,l.rootUrl,d,l.name).then((()=>{i.loadingPluginName=e.name,_()})).catch((e=>{u(e.message,e)}))}),d,u,c,o,a)}static AppendAsync(e,t="",i=re.LastCreatedScene,s=null,r=null,n=""){return new Promise(((o,a)=>{fl.Append(e,t,i,(e=>{o(e)}),s,((e,t,i)=>{a(i||new Error(t))}),r,n)}))}static LoadAssetContainer(e,t="",i=re.LastCreatedScene,s=null,r=null,n=null,o=null,a=""){if(!i)return Ne.Error("No scene available to load asset container to"),null;const l=fl._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)},u=(e,t)=>{const s=fl._FormatErrorMessage(l,e,t);n?n(i,s,new jt(s,Qt.SceneLoaderError,t)):Ne.Error(s),c()},d=r?e=>{try{r(e)}catch(e){u("Error in onProgress callback",e)}}:void 0,_=e=>{if(s)try{s(e)}catch(e){u("Error in onSuccess callback",e)}i.removePendingData(h)};return fl._LoadData(l,i,((e,t)=>{if(e.loadAssetContainer){const s=e.loadAssetContainer(i,t,l.rootUrl,u);if(!s)return;s.populateRootNodes(),i.loadingPluginName=e.name,_(s)}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,l.rootUrl,d,l.name).then((t=>{t.populateRootNodes(),i.loadingPluginName=e.name,_(t)})).catch((e=>{u(e.message,e)})):u("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),d,u,c,o,a)}static LoadAssetContainerAsync(e,t="",i=re.LastCreatedScene,s=null,r=null){return new Promise(((n,o)=>{fl.LoadAssetContainer(e,t,i,(e=>{n(e)}),s,((e,t,i)=>{o(i||new Error(t))}),r)}))}static ImportAnimations(e,t="",i=re.LastCreatedScene,s=!0,r=ol.Clean,n=null,o=null,a=null,l=null,h=null){if(!i)return void Ne.Error("No scene available to load animations to");if(s){for(const e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach((e=>{e.dispose()})),i.getNodes().forEach((e=>{e.animations&&(e.animations=[])}))}else switch(r){case ol.Clean:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case ol.Stop:i.animationGroups.forEach((e=>{e.stop()}));break;case ol.Sync:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case ol.NoSync:break;default:return void Ne.Error("Unknown animation group loading mode value '"+r+"'")}const c=i.animatables.length;this.LoadAssetContainer(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(c),n),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)}),a,l,h)}static ImportAnimationsAsync(e,t="",i=re.LastCreatedScene,s=!0,r=ol.Clean,n=null,o=null,a=null,l=null,h=null){return new Promise(((o,l)=>{fl.ImportAnimations(e,t,i,s,r,n,(e=>{o(e)}),a,((e,t,i)=>{l(i||new Error(t))}),h)}))}}fl.NO_LOGGING=0,fl.MINIMAL_LOGGING=1,fl.SUMMARY_LOGGING=2,fl.DETAILED_LOGGING=3,fl.OnPluginActivatedObservable=new K,fl._RegisteredPlugins={},fl._ShowingLoadingScreen=!1;class ml extends ta{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new me,this._storeEffectOnSubMeshes=i}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return!!e&&(!this._storeEffectOnSubMeshes||!e.subMeshes||0===e.subMeshes.length||this.isReadyForSubMesh(e,e.subMeshes[0],t))}_isReadyForSubMesh(e){const t=e.materialDefines;return!(this.checkReadyOnEveryCall||!e.effect||!t||t._renderId!==this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,i){super._afterBind(e,t,i),this.getScene()._cachedEffect=t,i?i._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,i,s=1){return i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,s)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}!function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.Object=256]="Object",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.All=4095]="All"}(al||(al={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(ll||(ll={}));class gl{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}get shaderLanguage(){return this.sharedData.nodeMaterial.shaderLanguage}get fSuffix(){return this.shaderLanguage===di.WGSL?"f":""}finalize(e){const t=e.sharedData.emitComments,i=this.target===ll.Fragment;this.shaderLanguage===di.WGSL?this.compilationString=i?`\n${t?"//Entry point\n":""}@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${this.compilationString}`:`\n${t?"//Entry point\n":""}@vertex\nfn main(input: VertexInputs) -> FragmentInputs{\n${this.compilationString}`:this.compilationString=`\n${t?"//Entry point\n":""}void main(void) {\n${this.compilationString}`,this._constantDeclaration&&(this.compilationString=`\n${t?"//Constants\n":""}${this._constantDeclaration}\n${this.compilationString}`);let s="";for(const e in this.functions)s+=this.functions[e]+"\n";if(this.compilationString=`\n${s}\n${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString}\n${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString}\n${this._injectAtEnd}`),this.compilationString=`${this.compilationString}\n}`,this.sharedData.varyingDeclaration&&(this.compilationString=`\n${t?"//Varyings\n":""}${this.sharedData.varyingDeclaration}\n${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=`\n${t?"//Samplers\n":""}${this._samplerDeclaration}\n${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=`\n${t?"//Uniforms\n":""}${this._uniformDeclaration}\n${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=`\n${t?"//Attributes\n":""}${this._attributeDeclaration}\n${this.compilationString}`),this.shaderLanguage!==di.WGSL){this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defines(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,i&&(this.compilationString="#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n"+this.compilationString);for(const e in this.extensions){const t=this.extensions[e];this.compilationString=`\n${t}\n${this.compilationString}`}}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e]?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){this.samplers.indexOf(e)<0&&(this.shaderLanguage===di.WGSL?(this._samplerDeclaration+=`var ${e+"Sampler"}: sampler;\n`,this._samplerDeclaration+=`var ${e}: texture_2d;\n`):this._samplerDeclaration+=`uniform sampler2D ${e};\n`,this.samplers.push(e))}_emit2DArraySampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2DArray ${e};\n`,this.samplers.push(e))}_getGLType(e){switch(e){case al.Float:return"float";case al.Int:return"int";case al.Vector2:return"vec2";case al.Color3:case al.Vector3:return"vec3";case al.Color4:case al.Vector4:return"vec4";case al.Matrix:return"mat4"}return""}_getShaderType(e){const t=this.shaderLanguage===di.WGSL;switch(e){case al.Float:return t?"f32":"float";case al.Int:return t?"i32":"int";case al.Vector2:return t?"vec2f":"vec2";case al.Color3:case al.Vector3:return t?"vec3f":"vec3";case al.Color4:case al.Vector4:return t?"vec4f":"vec4";case al.Matrix:return t?"mat4x4f":"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i}\n${t}\n#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+"\n"+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`;let s=Bi.GetIncludesShadersStore(this.shaderLanguage)[e]+"\n";if(this.sharedData.emitComments&&(s=t+"\n"+s),!i)return s;if(i.replaceStrings)for(let e=0;e${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`:this.functions[r]=`#include<${e}>${i?.substitutionVars?"("+i?.substitutionVars+")":""}\n`,void(this.sharedData.emitComments&&(this.functions[r]=t+"\n"+this.functions[r]));const n=Bi.GetIncludesShadersStore(this.shaderLanguage);if(this.functions[r]=n[e],this.sharedData.emitComments&&(this.functions[r]=t+"\n"+this.functions[r]),i.removeIfDef&&(this.functions[r]=this.functions[r].replace(/^\s*?#ifdef.+$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#endif.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#else.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[r]=this.functions[r].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[r]=this.functions[r].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[r]=this.functions[r].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(let e=0;e")}_convertTernaryOperandsToWGSL(e){return e.replace(new RegExp("\\[(.*?)\\?(.*?):(.*)\\]","g"),((e,t,i,s)=>`select(${s}, ${i}, ${t})`))}_convertModOperatorsToWGSL(e){return e.replace(new RegExp("mod\\((.+?),\\s*(.+?)\\)","g"),((e,t,i)=>`((${t})%(${i}))`))}_convertConstToWGSL(e){return e.replace(new RegExp("const var","g"),"const")}_convertInnerFunctionsToWGSL(e){return e.replace(new RegExp("inversesqrt","g"),"inverseSqrt")}_convertFunctionsToWGSL(e){const t=/var\s+(\w+)\s*:\s*(\w+)\((.*)\)/g;let i;for(;null!==(i=t.exec(e));){const t=i[1],s=i[2],r=i[3].replace(/var\s/g,"");e=e.replace(i[0],`fn ${t}(${r}) -> ${s}`)}return e}_babylonSLtoWGSL(e){return e=this._convertVariableDeclarationToWGSL("void","voidnull",e),e=this._convertVariableDeclarationToWGSL("bool","bool",e),e=this._convertVariableDeclarationToWGSL("int","i32",e),e=this._convertVariableDeclarationToWGSL("uint","u32",e),e=this._convertVariableDeclarationToWGSL("float","f32",e),e=this._convertVariableDeclarationToWGSL("vec2","vec2f",e),e=this._convertVariableDeclarationToWGSL("vec3","vec3f",e),e=this._convertVariableDeclarationToWGSL("vec4","vec4f",e),e=this._convertVariableDeclarationToWGSL("mat2","mat2x2f",e),e=this._convertVariableDeclarationToWGSL("mat3","mat3x3f",e),e=this._convertVariableDeclarationToWGSL("mat4","mat4x4f",e),e=this._convertVariableConstructorsToWGSL("float","f32",e),e=this._convertVariableConstructorsToWGSL("vec2","vec2f",e),e=this._convertVariableConstructorsToWGSL("vec3","vec3f",e),e=this._convertVariableConstructorsToWGSL("vec4","vec4f",e),e=this._convertVariableConstructorsToWGSL("mat2","mat2x2f",e),e=this._convertVariableConstructorsToWGSL("mat3","mat3x3f",e),e=this._convertVariableConstructorsToWGSL("mat4","mat4x4f",e),e=this._convertTernaryOperandsToWGSL(e),e=this._convertModOperatorsToWGSL(e),e=this._convertConstToWGSL(e),e=this._convertInnerFunctionsToWGSL(e),e=(e=this._convertOutParametersToWGSL(e)).replace(/\[\*\]/g,"*"),(e=(e=(e=this._convertFunctionsToWGSL(e)).replace(/\s->\svoidnull/g,"")).replace(/dFdx/g,"dpdx")).replace(/dFdy/g,"dpdy")}_convertTernaryOperandsToGLSL(e){return e.replace(new RegExp("\\[(.+?)\\?(.+?):(.+)\\]","g"),((e,t,i,s)=>`${t} ? ${i} : ${s}`))}_babylonSLtoGLSL(e){return e=e.replace(/\[\*\]/g,""),this._convertTernaryOperandsToGLSL(e)}}class vl{constructor(){this.temps=[],this.varyings=[],this.varyingDeclaration="",this.inputBlocks=[],this.textureBlocks=[],this.bindableBlocks=[],this.forcedBindableBlocks=[],this.blocksWithFallbacks=[],this.blocksWithDefines=[],this.repeatableContentBlocks=[],this.dynamicUniformBlocks=[],this.blockingBlocks=[],this.animatedInputs=[],this.variableNames={},this.defineNames={},this.hints={needWorldViewMatrix:!1,needWorldViewProjectionMatrix:!1,needAlphaBlending:!1,needAlphaTesting:!1},this.checks={emitVertex:!1,emitFragment:!1,notConnectedNonOptionalInputs:new Array},this.allowEmptyVertexProgram=!1,this.variableNames.position=0,this.variableNames.normal=0,this.variableNames.tangent=0,this.variableNames.uv=0,this.variableNames.uv2=0,this.variableNames.uv3=0,this.variableNames.uv4=0,this.variableNames.uv5=0,this.variableNames.uv6=0,this.variableNames.color=0,this.variableNames.matricesIndices=0,this.variableNames.matricesWeights=0,this.variableNames.matricesIndicesExtra=0,this.variableNames.matricesWeightsExtra=0,this.variableNames.diffuseBase=0,this.variableNames.specularBase=0,this.variableNames.worldPos=0,this.variableNames.shadow=0,this.variableNames.view=0,this.variableNames.vTBN=0,this.defineNames.MAINUV0=0,this.defineNames.MAINUV1=0,this.defineNames.MAINUV2=0,this.defineNames.MAINUV3=0,this.defineNames.MAINUV4=0,this.defineNames.MAINUV5=0,this.defineNames.MAINUV6=0,this.defineNames.MAINUV7=0}emitErrors(){let e="";this.checks.emitVertex||this.allowEmptyVertexProgram||(e+="NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.\n"),this.checks.emitFragment||(e+="NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\n");for(const t of this.checks.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional.\n`;if(e)throw"Build of NodeMaterial failed:\n"+e}}class xl{constructor(e){if(this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!1,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)-1===this._keys.indexOf(e)&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;tthis._setDefaultValue(e)))}_setDefaultValue(e){const t=this._externalProperties?.[e]?.type??typeof this[e],i=this._externalProperties?.[e]?.default;switch(t){case"number":this[e]=i??0;break;case"string":this[e]=i??"";break;default:this[e]=i??!1}}toString(){let e="";for(let t=0;tthis._connectedPointBackingField=e)),this._connectedPointBackingField&&(this._connectedPointTypeChangedObserver=this._connectedPointBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get _typeConnectionSource(){return this._typeConnectionSourceBackingField}set _typeConnectionSource(e){this._typeConnectionSourceBackingField!==e&&(this._typeConnectionSourceTypeChangedObserver?.remove(),this._updateTypeDependentState((()=>this._typeConnectionSourceBackingField=e)),this._typeConnectionSourceBackingField&&(this._typeConnectionSourceTypeChangedObserver=this._typeConnectionSourceBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get _defaultConnectionPointType(){return this._defaultConnectionPointTypeBackingField}set _defaultConnectionPointType(e){this._updateTypeDependentState((()=>this._defaultConnectionPointTypeBackingField=e))}get _linkedConnectionSource(){return this._linkedConnectionSourceBackingField}set _linkedConnectionSource(e){this._linkedConnectionSourceBackingField!==e&&(this._linkedConnectionSourceTypeChangedObserver?.remove(),this._updateTypeDependentState((()=>this._linkedConnectionSourceBackingField=e)),this._linkedConnectionSourceBackingField&&(this._linkedConnectionSourceTypeChangedObserver=this._linkedConnectionSourceBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get direction(){return this._direction}get declarationVariableName(){return this._ownerBlock.isInput?this._ownerBlock.declarationVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.declarationVariableName}get associatedVariableName(){return this._ownerBlock.isInput?this._ownerBlock.associatedVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}get type(){if(this._type===al.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===al.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._updateTypeDependentState((()=>this._type=e))}get target(){return this._prioritizeVertex&&this._ownerBlock?this._target!==ll.VertexAndFragment?this._target:this._ownerBlock.target===ll.Fragment?ll.Fragment:ll.Vertex:this._target}set target(e){this._target=e}get isConnected(){return null!==this.connectedPoint||this.hasEndpoints}get isConnectedToInputBlock(){return null!==this.connectedPoint&&this.connectedPoint.ownerBlock.isInput}get connectInputBlock(){return this.isConnectedToInputBlock?this.connectedPoint.ownerBlock:null}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return 0===this._endpoints.length?[]:this._endpoints.map((e=>e.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===ll.Vertex)return!0;if((e.ownerBlock.target===ll.Neutral||e.ownerBlock.target===ll.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isDirectlyConnectedToVertexOutput)))return!0}return!1}get isConnectedInVertexShader(){if(this.target===ll.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===ll.Vertex)return!0;if(e.target===ll.Vertex)return!0;if((e.ownerBlock.target===ll.Neutral||e.ownerBlock.target===ll.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInVertexShader)))return!0}return!1}get isConnectedInFragmentShader(){if(this.target===ll.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===ll.Fragment)return!0;if((e.ownerBlock.target===ll.Neutral||e.ownerBlock.target===ll.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0}return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPointBackingField=null,this._endpoints=new Array,this._typeConnectionSourceBackingField=null,this._defaultConnectionPointTypeBackingField=null,this._linkedConnectionSourceBackingField=null,this._acceptedConnectionPointType=null,this._type=al.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new K,this.onDisconnectionObservable=new K,this.onTypeChangedObservable=new K,this._isTypeChangeObservableNotifying=!1,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=ll.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===hl.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===ll.Fragment){if(i.target===ll.Vertex)return hl.TargetIncompatible;for(const e of i.outputs)if(e.ownerBlock.target!=ll.Neutral&&e.isConnectedInVertexShader)return hl.TargetIncompatible}if(this.type!==e.type&&e.innerType!==al.AutoDetect)return bl.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&bl.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?hl.Compatible:hl.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return hl.TypeIncompatible;let s=i,r=t;return this.direction===cl.Input&&(s=t,r=i),s.isAnAncestorOf(r)?hl.HierarchyIssue:hl.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear(),this.onTypeChangedObservable.clear(),this._connectedPoint=null,this._typeConnectionSource=null,this._linkedConnectionSource=null}_updateTypeDependentState(e){const t=this.type;e(),this.type!==t&&this._notifyTypeChanged()}_notifyTypeChanged(){this._isTypeChangeObservableNotifying||(this._isTypeChangeObservableNotifying=!0,this.onTypeChangedObservable.notifyObservers(this.type),this._isTypeChangeObservableNotifying=!1)}}class Tl{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){this._target&e||(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}constructor(e,t=ll.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===ll.Neutral,this._isFinalMerger=i,this._isInput="InputBlock"===this.getClassName(),this._isTeleportOut="NodeMaterialTeleportOutBlock"===this.getClassName(),this._isTeleportIn="NodeMaterialTeleportInBlock"===this.getClassName(),this._name=e,this.uniqueId=Lr.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===ll.Neutral}initialize(e){}bind(e,t,i,s){}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return-1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some((e=>e.isConnectedInFragmentShader))}registerInput(e,t,i=!1,s,r){return(r=r??new bl(e,this,cl.Input)).type=t,r.isOptional=i,s&&(r.target=s),this._inputs.push(r),this}registerOutput(e,t,i,s){return(s=s??new bl(e,this,cl.Output)).type=t,i&&(s.target=i),this._outputs.push(s),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!(t.connectedPoint||e&&e.type!==t.type&&t.type!==al.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===ll.Neutral||e.target&t.target)return t;return null}getSiblingOutput(e){const t=this._outputs.indexOf(e);return-1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){if(i.ownerBlock===e)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),s=!0;for(;s;){const r=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&r&&i.canConnectTo(r))i.connectTo(r),s=!1;else{if(!i)throw"Unable to find a compatible match";i=this.getSiblingOutput(i)}}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,s){}provideFallbacks(e,t){}initializeDefines(e,t,i,s=!1){}prepareDefines(e,t,i,s=!1,r){}autoConfigure(e,t=(()=>!0)){}replaceRepeatableContent(e,t,i,s){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some((e=>e.isDirectlyConnectedToVertexOutput))||this.target===ll.Vertex||this.target!==ll.VertexAndFragment&&this.target!==ll.Neutral||!this._outputs.some((e=>e.isConnectedInVertexShader)))}isReady(e,t,i,s=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,s){e.build(t,s);const r=null!=t._vertexState,n=e._buildTarget===ll.Vertex&&e.target!==ll.VertexAndFragment;if(r&&(!(e.target&e._buildTarget)||!(e.target&i.target)||this.target!==ll.VertexAndFragment&&n)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){const e=i.connectedPoint;if(t._vertexState._emitVaryingFromString("v_"+e.declarationVariableName,e.type)){const i=t.shaderLanguage===di.WGSL?"vertexOutputs.":"";t._vertexState.compilationString+=`${i}${"v_"+e.declarationVariableName} = ${e.associatedVariableName};\n`}const s=t.shaderLanguage===di.WGSL?"fragmentInputs.":"";i.associatedVariableName=s+"v_"+e.declarationVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){const t=["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"];for(const i of t)if(e===i)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(const t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==ll.Neutral){if(!(i.target&this.target))continue;if(!(i.target&e.target))continue}const s=i.connectedPoint.ownerBlock;s&&s!==this&&this._processBuild(s,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&Ne.Log(`${e.target===ll.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case ll.Vertex:e.sharedData.checks.emitVertex=!0;break;case ll.Fragment:e.sharedData.checks.emitFragment=!0}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=`\n//${this.name}\n`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(const i of this._outputs)if(i.target&e.target)for(const s of i.endpoints){const i=s.ownerBlock;i&&i.target&e.target&&-1!==t.indexOf(i)&&this._processBuild(i,e,s,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector};\n${e}.visibleOnFrame = ${this.visibleOnFrame};\n${e}.target = ${this.target};\n`}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let s=`\n// ${this.getClassName()}\n`;this.comments&&(s+=`// ${this.comments}\n`),s+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\n`,s+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint.ownerBlock;-1===t.indexOf(r)&&(s+=r._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const r of i.endpoints){const i=r.ownerBlock;i&&-1===t.indexOf(i)&&(s+=i._dumpCode(e,t))}return s}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}return t}clone(e,t=""){const i=this.serialize(),s=W(i.customType);if(s){const r=new s;return r._deserialize(i,e,t),r}return null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i,s){this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=e.target??this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach(((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class yl extends Tl{constructor(e){super(e,ll.Neutral),this.complementW=1,this.complementZ=0,this.target=ll.Vertex,this.registerInput("vector",al.AutoDetect),this.registerInput("transform",al.Matrix),this.registerOutput("output",al.Vector4),this.registerOutput("xyz",al.Vector3),this._inputs[0].onConnectionObservable.add((e=>{if(e.ownerBlock.isInput){const t=e.ownerBlock;"normal"!==t.name&&"tangent"!==t.name||(this.complementW=0)}}))}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.transform,s=e._getShaderType(al.Vector4),r=e._getShaderType(al.Vector3);if(t.connectedPoint){if(0===this.complementW){const n=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",n),e.sharedData.blocksWithDefines.push(this);const o=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.shaderLanguage===di.WGSL?e.compilationString+=`var ${o}: mat3x3f = mat3x3f(${i.associatedVariableName}[0].xyz, ${i.associatedVariableName}[1].xyz, ${i.associatedVariableName}[2].xyz);\n`:e.compilationString+=`mat3 ${o} = mat3(${i.associatedVariableName});\n`,e.compilationString+="#ifdef NONUNIFORMSCALING\n",e.compilationString+=`${o} = transposeMat3(inverseMat3(${o}));\n`,e.compilationString+="#endif\n",t.connectedPoint.type){case al.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${s}(${o} * ${r}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\n`;break;case al.Vector3:case al.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${s}(${o} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${s}(${o} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\n`}}else{const r=i.associatedVariableName;switch(t.connectedPoint.type){case al.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${r} * ${s}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\n`;break;case al.Vector3:case al.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${r} * ${s}(${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${r} * ${t.associatedVariableName};\n`}}this.xyz.hasEndpoints&&(e.compilationString+=e._declareOutput(this.xyz)+` = ${this.output.associatedVariableName}.xyz;\n`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){const e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ};\n`;return e+=`${this._codeVariableName}.complementW = ${this.complementW};\n`,e}}z("BABYLON.TransformBlock",yl);class Sl extends Tl{constructor(e){super(e,ll.Vertex,!0),this.registerInput("vector",al.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e,t){if(t)return!0;for(const t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);const t=this.vector;return e.shaderLanguage===di.WGSL?e.compilationString+=`vertexOutputs.position = ${t.associatedVariableName};\n`:e.compilationString+=`gl_Position = ${t.associatedVariableName};\n`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes,e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant",al.Float),e._emitVaryingFromString("vFragmentDepth",al.Float),e.compilationString+="vFragmentDepth = 1.0 + gl_Position.w;\n",e.compilationString+="gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\n"),this}}function Cl(e,t=ul.Boolean,i="PROPERTIES",s){return(r,n)=>{let o=r._propStore;o||(o=[],r._propStore=o),o.push({propertyName:n,displayName:e,type:t,groupName:i,options:s??{}})}}z("BABYLON.VertexOutputBlock",Sl),function(e){e[e.Boolean=0]="Boolean",e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=3]="Vector2",e[e.List=4]="List"}(ul||(ul={}));class El extends Tl{constructor(e){super(e,ll.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",al.Color4,!0),this.registerInput("rgb",al.AutoDetect,!0),this.registerInput("a",al.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){(this.useLogarithmicDepth||t.useLogarithmicDepth)&&i&&So(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,s=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||s.isConnected,e.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant",al.Float),e._emitVaryingFromString("vFragmentDepth",al.Float),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r);let n="gl_FragColor";e.shaderLanguage===di.WGSL&&(n="fragmentOutputs.color");const o=e._getShaderType(al.Vector4);if(t.connectedPoint)s.isConnected?e.compilationString+=`${n} = ${o}(${t.associatedVariableName}.rgb, ${s.associatedVariableName});\n`:e.compilationString+=`${n} = ${t.associatedVariableName};\n`;else if(i.connectedPoint){let t="1.0";s.connectedPoint&&(t=s.associatedVariableName),i.connectedPoint.type===al.Float?e.compilationString+=`${n} = ${o}(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t});\n`:e.compilationString+=`${n} = ${o}(${i.associatedVariableName}, ${t});\n`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${n} = toLinearSpace(${n});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${n} = toGammaSpace(${n});\n`,e.compilationString+="#endif\n",(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e.compilationString+="gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\n"),e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+="gl_FragData[0] = gl_FragColor;\r\n",e.compilationString+="#endif\r\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\n`,e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.useLogarithmicDepth=e.useLogarithmicDepth??!1}}Ze([Cl("Convert to gamma space",ul.Boolean,"PROPERTIES",{notifiers:{update:!0}})],El.prototype,"convertToGammaSpace",void 0),Ze([Cl("Convert to linear space",ul.Boolean,"PROPERTIES",{notifiers:{update:!0}})],El.prototype,"convertToLinearSpace",void 0),Ze([Cl("Use logarithmic depth",ul.Boolean,"PROPERTIES")],El.prototype,"useLogarithmicDepth",void 0),z("BABYLON.FragmentOutputBlock",El),function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(dl||(dl={})),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime",e[e.CameraParameters=10]="CameraParameters",e[e.MaterialAlpha=11]="MaterialAlpha"}(_l||(_l={}));class Al{constructor(e=_e.Zero(),t=_e.Up()){this.position=e,this.normal=t}clone(){return new Al(this.position.clone(),this.normal.clone())}}class Pl{constructor(e=_e.Zero(),t=_e.Up(),i=de.Zero()){this.position=e,this.normal=t,this.uv=i}clone(){return new Pl(this.position.clone(),this.normal.clone(),this.uv.clone())}}!function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime",e[e.MouseInfo=3]="MouseInfo"}(pl||(pl={}));const Il={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},Rl={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},Ml={particle_texturemask:!0};class Ol extends Tl{get type(){if(this._type===al.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=al.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=al.Vector2,this._type;case"Vector3":return this._type=al.Vector3,this._type;case"Vector4":return this._type=al.Vector4,this._type;case"Color3":return this._type=al.Color3,this._type;case"Color4":return this._type=al.Color4,this._type;case"Matrix":return this._type=al.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=al.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=al.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=al.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=al.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case _l.World:case _l.WorldView:case _l.WorldViewProjection:case _l.View:case _l.ViewProjection:case _l.Projection:return this._type=al.Matrix,this._type;case _l.CameraPosition:return this._type=al.Vector3,this._type;case _l.FogColor:return this._type=al.Color3,this._type;case _l.DeltaTime:case _l.MaterialAlpha:return this._type=al.Float,this._type;case _l.CameraParameters:return this._type=al.Vector4,this._type}}return this._type}constructor(e,t=ll.Vertex,i=al.AutoDetect){super(e,t,!1),this._mode=dl.Undefined,this._animationType=pl.None,this._prefix="",this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new K,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=dl.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===al.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=dl.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=dl.Uniform}get declarationVariableName(){return this._associatedVariableName}get associatedVariableName(){return this._prefix+this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===dl.Undefined}get isUniform(){return this._mode===dl.Uniform}set isUniform(e){this._mode=e?dl.Uniform:dl.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===dl.Attribute}set isAttribute(e){this._mode=e?dl.Attribute:dl.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===dl.Varying}set isVarying(e){this._mode=e?dl.Varying:dl.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=dl.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case pl.Time:this.type===al.Float&&(this.value+=.01*e.getAnimationRatio());break;case pl.RealTime:this.type===al.Float&&(this.value=(Wt.Now-e.getEngine().startTime)/1e3);break;case pl.MouseInfo:if(this.type===al.Vector4){const t=e._inputManager._originMouseEvent;if(t){const e=t.offsetX,i=t.offsetY,s=1&t.buttons?1:0,r=2&t.buttons?1:0;this.value=new pe(e,i,s,r)}else this.value=new pe(0,0,0,0)}}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)}\n`:`#ifdef ${e}\n`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case al.Float:this.value=0;break;case al.Vector2:this.value=de.Zero();break;case al.Vector3:this.value=_e.Zero();break;case al.Vector4:this.value=pe.Zero();break;case al.Color3:this.value=Ee.White();break;case al.Color4:this.value=new Ae(1,1,1,1);break;case al.Matrix:this.value=me.Identity()}}_emitConstant(e){switch(this.type){case al.Float:return`${e._emitFloat(this.value)}`;case al.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case al.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case al.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case al.Color3:return Pe.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&Pe.Color3[0].toGammaSpaceToRef(Pe.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Pe.Color3[0].toLinearSpaceToRef(Pe.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${Pe.Color3[0].r}, ${Pe.Color3[0].g}, ${Pe.Color3[0].b})`;case al.Color4:return Pe.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&Pe.Color4[0].toGammaSpaceToRef(Pe.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Pe.Color4[0].toLinearSpaceToRef(Pe.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${Pe.Color4[0].r}, ${Pe.Color4[0].g}, ${Pe.Color4[0].b}, ${Pe.Color4[0].a})`}return""}get _noContextSwitch(){return Rl[this.name]}_emit(e,t){if(this.isUniform){if(this._associatedVariableName||(this._associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;return e.constants.push(this.associatedVariableName),void(e._constantDeclaration+=e._declareOutput(this.output,!0)+` = ${this._emitConstant(e)};\n`)}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t));const i=e._getShaderType(this.type);e.shaderLanguage===di.WGSL?(e._uniformDeclaration+=`uniform ${this._associatedVariableName}: ${i};\n`,this._prefix="uniforms."):e._uniformDeclaration+=`uniform ${i} ${this.associatedVariableName};\n`,t&&(e._uniformDeclaration+="#endif\n");const s=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case _l.WorldView:s.needWorldViewMatrix=!0;break;case _l.WorldViewProjection:s.needWorldViewProjectionMatrix=!0}else this._animationType!==pl.None&&e.sharedData.animatedInputs.push(this)}else if(this.isAttribute){if(this.associatedVariableName=Il[this.name]??this.name,this.target===ll.Vertex&&e._vertexState)return void(Rl[this.name]?Ml[this.name]?(e._emitUniformFromString(this.associatedVariableName,this.type,t),e.shaderLanguage===di.WGSL&&(this._prefix="vertexInputs.")):e._emitVaryingFromString(this.associatedVariableName,this.type,t):this._emit(e._vertexState,t));if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),Rl[this.name]?Ml[this.name]?e._emitUniformFromString(this.associatedVariableName,this.type,t):e._emitVaryingFromString(this.associatedVariableName,this.type,t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e.shaderLanguage===di.WGSL?(e._attributeDeclaration+=`attribute ${this.associatedVariableName}: ${e._getShaderType(this.type)};\n`,this._prefix="vertexInputs."):e._attributeDeclaration+=`attribute ${e._getShaderType(this.type)} ${this.associatedVariableName};\n`,t&&(e._attributeDeclaration+="#endif\n"))}}_transmitWorld(e,t,i,s){if(!this._systemValue)return;const r=this._associatedVariableName;switch(this._systemValue){case _l.World:e.setMatrix(r,t);break;case _l.WorldView:e.setMatrix(r,i);break;case _l.WorldViewProjection:e.setMatrix(r,s)}}_transmit(e,t,i){if(this.isAttribute)return;const s=this._associatedVariableName;if(this._systemValue){switch(this._systemValue){case _l.World:case _l.WorldView:case _l.WorldViewProjection:return;case _l.View:e.setMatrix(s,t.getViewMatrix());break;case _l.Projection:e.setMatrix(s,t.getProjectionMatrix());break;case _l.ViewProjection:e.setMatrix(s,t.getTransformMatrix());break;case _l.CameraPosition:t.bindEyePosition(e,s,!0);break;case _l.FogColor:e.setColor3(s,t.fogColor);break;case _l.DeltaTime:e.setFloat(s,t.deltaTime/1e3);break;case _l.CameraParameters:t.activeCamera&&e.setFloat4(s,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case _l.MaterialAlpha:e.setFloat(s,i.alpha)}return}const r=this._valueCallback?this._valueCallback():this._storedValue;if(null!==r)switch(this.type){case al.Float:e.setFloat(s,r);break;case al.Int:e.setInt(s,r);break;case al.Color3:Pe.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&Pe.Color3[0].toGammaSpaceToRef(Pe.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Pe.Color3[0].toLinearSpaceToRef(Pe.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(s,Pe.Color3[0]);break;case al.Color4:Pe.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&Pe.Color4[0].toGammaSpaceToRef(Pe.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&Pe.Color4[0].toLinearSpaceToRef(Pe.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(s,Pe.Color4[0]);break;case al.Vector2:e.setVector2(s,r);break;case al.Vector3:e.setVector3(s,r);break;case al.Vector4:e.setVector4(s,r);break;case al.Matrix:e.setMatrix(s,r)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}");\n`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${_l[this._systemValue]});\n`;if(this.isUniform){const t=[];let i="";switch(this.type){case al.Float:i=`${this.value}`;break;case al.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case al.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case al.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case al.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case al.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case al.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===al.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${pl[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){const e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,null!=this._storedValue&&this._mode===dl.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,"tangent"===e.name&&e.mode===dl.Attribute&&e.type===al.Vector3&&(this._type=al.Vector4),e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=W(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}z("BABYLON.InputBlock",Ol);class Dl extends Tl{constructor(e){super(e,ll.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",al.AutoDetect,!1,ll.VertexAndFragment),this.registerOutput("rgba",al.Color4,ll.Neutral),this.registerOutput("rgb",al.Color3,ll.Neutral),this.registerOutput("r",al.Float,ll.Neutral),this.registerOutput("g",al.Float,ll.Neutral),this.registerOutput("b",al.Float,ll.Neutral),this.registerOutput("a",al.Float,ll.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Vector2|al.Vector3|al.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?ll.VertexAndFragment:ll.Fragment:ll.VertexAndFragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,al.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,al.Vector2),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===ll.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\n`}else this.uv.ownerBlock.target!==ll.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\n`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===ll.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target!==ll.Fragment?(e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"):e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.blockingBlocks.indexOf(this)<0&&e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.indexOf(this)<0&&e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.indexOf(this)<0&&e.sharedData.blocksWithDefines.push(this),e.target!==ll.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Pa.Parse(e.texture,t,i))}}z("BABYLON.CurrentScreenBlock",Dl);class wl extends Tl{constructor(e){super(e,ll.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",al.AutoDetect,!1,ll.VertexAndFragment),this.registerOutput("rgba",al.Color4,ll.Neutral),this.registerOutput("rgb",al.Color3,ll.Neutral),this.registerOutput("r",al.Float,ll.Neutral),this.registerOutput("g",al.Float,ll.Neutral),this.registerOutput("b",al.Float,ll.Neutral),this.registerOutput("a",al.Float,ll.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Vector2|al.Vector3|al.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"particle_uv"===e.name&&t(e)));i||(i=new Ol("uv"),i.setAsAttribute("particle_uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_writeOutput(e,t,i){e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"}_buildBlock(e){if(super._buildBlock(e),e.target===ll.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName});\n`;for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Pa.Parse(e.texture,t,i))}}z("BABYLON.ParticleTextureBlock",wl);class Nl extends Tl{constructor(e){super(e,ll.Fragment),this._isUnique=!0,this.registerInput("color",al.Color4,!1,ll.Fragment),this.registerOutput("rampColor",al.Color4,ll.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==ll.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges",al.Vector4,"RAMPGRADIENT"),e.compilationString+=`\n #ifdef RAMPGRADIENT\n vec4 baseColor = ${this.color.associatedVariableName};\n float alpha = ${this.color.associatedVariableName}.a;\n\n float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\n\n vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));\n baseColor.rgb *= rampColor.rgb;\n\n // Remapped alpha\n float finalAlpha = baseColor.a;\n baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);\n\n ${e._declareOutput(this.rampColor)} = baseColor;\n #else\n ${e._declareOutput(this.rampColor)} = ${this.color.associatedVariableName};\n #endif\n `,this}}z("BABYLON.ParticleRampGradientBlock",Nl);class Fl extends Tl{constructor(e){super(e,ll.Fragment),this._isUnique=!0,this.registerInput("color",al.Color4,!1,ll.Fragment),this.registerInput("alphaTexture",al.Float,!1,ll.Fragment),this.registerInput("alphaColor",al.Float,!1,ll.Fragment),this.registerOutput("blendColor",al.Color4,ll.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==ll.Vertex)return e.compilationString+=`\n #ifdef BLENDMULTIPLYMODE\n ${e._declareOutput(this.blendColor)};\n float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};\n ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);\n ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a;\n #else\n ${e._declareOutput(this.blendColor)} = ${this.color.associatedVariableName};\n #endif\n `,this}}z("BABYLON.ParticleBlendMultiplyBlock",Fl);class Ll{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let e=0;e0&&(s.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;i0}get is3D(){return this.depth>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){return this._textures?.[0]??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}constructor(e,t,i,s,r){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=s,this._depthStencilTexture=null,this.label=r}setTextures(e){Array.isArray(e)?this._textures=e:this._textures=e?[e]:null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){return this._depthStencilTexture?.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:s,depthTextureFormat:r,label:n},this),this._depthStencilTexture}_shareDepth(e){this.shareDepth(e)}shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){let e=null;if(this._isMulti){const t=this.textures;if(t&&t.length>0){let i=!1,s=t.length,r=-1;const n=t[t.length-1]._source;n!==is.Depth&&n!==is.DepthStencil||(i=!0,r=t[t.length-1].format,s--);const o=[],a=[],l=[],h=[],c=[],u=[],d=[],_={};for(let e=0;e1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e1){const r=this._context,n=r["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??this.layerIndices?.[t]??0,r.framebufferTextureLayer(r.FRAMEBUFFER,n,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=i??this.faceIndices?.[t]??0,r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const r=this._context,n=r["COLOR_ATTACHMENT"+t+"_WEBGL"],o=void 0!==i?r.TEXTURE_CUBE_MAP_POSITIVE_X+i:r.TEXTURE_2D;r.framebufferTexture2D(r.FRAMEBUFFER,n,o,e._hardwareTexture.underlyingResource,s)}n._bindUnboundFramebuffer(o)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=this._attachments?.length??this.textures.length;for(let e=0;e1&&(15===o.format?u=i.DEPTH_COMPONENT16:16===o.format?u=i.DEPTH_COMPONENT24:17===o.format||13===o.format?u=i.DEPTH24_STENCIL8:14===o.format?u=i.DEPTH_COMPONENT32F:18===o.format&&(u=i.DEPTH32F_STENCIL8)),o.is2DArray?i.texImage3D(n,0,u,o.width,o.height,s,0,c,h,null):o.is3D?i.texImage3D(n,0,u,o.width,o.height,r,0,c,h,null):i.texImage2D(n,0,u,o.width,o.height,0,c,h,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(o),o},qs.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);const s=e.texture._hardwareTexture;if(s.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){const r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBABufferInternalSizedFormat(e.texture.type,e.texture.format,e.texture._useSRGBBuffer),i.COLOR_ATTACHMENT0,!1);if(!n)throw new Error("Unable to create multi sampled framebuffer");s.addMSAARenderBuffer(n)}else this._bindUnboundFramebuffer(e._framebuffer);return e.texture.samples=t,e._samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t),this._bindUnboundFramebuffer(null),t},qs.prototype._setupDepthStencilTexture=function(e,t,i,s,r,n=1){const o=t.width||t,a=t.height||t,l=t.layers||0,h=t.depth||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.depth=l||h,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=0,e._comparisonFunction=r;const c=this._gl,u=this._getTextureTarget(e),d=this._getSamplingParameters(e.samplingMode,!1);c.texParameteri(u,c.TEXTURE_MAG_FILTER,d.mag),c.texParameteri(u,c.TEXTURE_MIN_FILTER,d.min),c.texParameteri(u,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(u,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===r?(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,515),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,r),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))},ns.prototype.setTextureFromPostProcess=function(e,t,i){let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,s?.texture??null,i)},ns.prototype.setTextureFromPostProcessOutput=function(e,t,i){this._bindTexture(e,t?._outputTexture?.texture??null,i)},$i.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)},$i.prototype.setTextureFromPostProcessOutput=function(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)};class Vl{static RegisterShaderCodeProcessing(e,t){t?Vl._CustomShaderCodeProcessing[e??""]=t:delete Vl._CustomShaderCodeProcessing[e??""]}static _GetShaderCodeProcessing(e){return Vl._CustomShaderCodeProcessing[e]??Vl._CustomShaderCodeProcessing[""]}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach((e=>{e.setSamples(this._samples)}))}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,s,r,n,o=1,a,l,h=null,c=0,u="postprocess",d,_=!1,p=5,f=di.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new Fs(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new de(1,1),this._texelSize=de.Zero(),this.onActivateObservable=new K,this.onSizeChangedObservable=new K,this.onApplyObservable=new K,this.onBeforeRenderObservable=new K,this.onAfterRenderObservable=new K,this.name=e;let m=1,g=null;if(i&&!Array.isArray(i)){const e=i;i=e.uniforms??null,s=e.samplers??null,m=e.size??1,n=e.camera??null,o=e.samplingMode??1,a=e.engine,l=e.reusable,h=e.defines??null,c=e.textureType??0,u=e.vertexUrl??"postprocess",d=e.indexParameters,_=e.blockCompilation??!1,p=e.textureFormat??5,f=e.shaderLanguage??di.GLSL,g=e.uniformBuffers??null}else r&&(m="number"==typeof r?r:{width:r.width,height:r.height});null!=n?(this._camera=n,this._scene=n.getScene(),n.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):a&&(this._engine=a,this._engine.postProcesses.push(this)),this._options=m,this.renderTargetSamplingMode=o||1,this._reusable=l||!1,this._textureType=c,this._textureFormat=p,this._shaderLanguage=f,this._samplers=s||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=u,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=g||[],this._indexParameters=d,this._drawWrapper=new Un(this._engine),_||this.updateEffect(h)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){0==this._textures.length&&(this._textures=new Fs(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,r,n,o,a){const l=Vl._GetShaderCodeProcessing(this.name);if(l?.defineCustomBindings){const s=t?.slice()??[];s.push(...this._parameters);const r=i?.slice()??[];r.push(...this._samplers),e=l.defineCustomBindings(this.name,e,s,r),t=s,i=r}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:o??this._vertexUrl,fragment:a??this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:r??null,onError:n??null,indexParameters:s||this._indexParameters,processCodeAfterIncludes:l?.processCodeAfterIncludes?(e,t)=>l.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:l?.processFinalCode?(e,t)=>l.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let s=0;s=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i)for(let e=0;e{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}return u||(u=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/l,a/h),this._engine.bindFramebuffer(u,0,o,a,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(u,0,void 0,void 0,this.forceFullscreenViewport)),this._engine._debugInsertMarker?.(`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:s.clearColor,s._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),u}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._drawWrapper.effect?.isReady()??!1}apply(){if(!this._drawWrapper.effect?.isReady())return null;let e;return this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),e=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e?.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),Vl._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name,this._drawWrapper.effect),this._drawWrapper.effect}_disposeTextures(){this._shareOutputWithPostProcess||this._forcedOutputTexture?this._disposeTextureCache():(this._disposeTextureCache(),this._textures.dispose())}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return!!this._prePassEffectConfiguration&&(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0)}dispose(e){let t;if(e=e||this._camera,this._disposeTextures(),this._scene&&(t=this._scene.postProcesses.indexOf(this),-1!==t&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),-1!==t&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),0===t&&e._postProcesses.length>0){const e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){const e=St.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const e=this.serialize();e._engine=this._engine,e.cameraId=null;const t=Vl.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const s=W(e.customType);if(!s||!s._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return s._Parse(e,r,t,i)}static _Parse(e,t,i,s){return St.Parse((()=>new Vl(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat)),e,i,s)}}Vl._CustomShaderCodeProcessing={},Ze([rt()],Vl.prototype,"uniqueId",void 0),Ze([rt()],Vl.prototype,"name",void 0),Ze([rt()],Vl.prototype,"width",void 0),Ze([rt()],Vl.prototype,"height",void 0),Ze([rt()],Vl.prototype,"renderTargetSamplingMode",void 0),Ze([dt()],Vl.prototype,"clearColor",void 0),Ze([rt()],Vl.prototype,"autoClear",void 0),Ze([rt()],Vl.prototype,"forceAutoClearInAlphaMode",void 0),Ze([rt()],Vl.prototype,"alphaMode",void 0),Ze([rt()],Vl.prototype,"alphaConstants",void 0),Ze([rt()],Vl.prototype,"enablePixelPerfectMode",void 0),Ze([rt()],Vl.prototype,"forceFullscreenViewport",void 0),Ze([rt()],Vl.prototype,"scaleMode",void 0),Ze([rt()],Vl.prototype,"alwaysForcePOT",void 0),Ze([rt("samples")],Vl.prototype,"_samples",void 0),Ze([rt()],Vl.prototype,"adaptScaleToCurrentViewport",void 0),z("BABYLON.PostProcess",Vl);class Ul extends Tl{constructor(e){super(e,ll.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",al.Vector4,!0),this.registerInput("xyz ",al.Vector3,!0),this.registerInput("xy ",al.Vector2,!0),this.registerInput("zw ",al.Vector2,!0),this.registerInput("x",al.Float,!0),this.registerInput("y",al.Float,!0),this.registerInput("z",al.Float,!0),this.registerInput("w",al.Float,!0),this.registerOutput("xyzw",al.Vector4),this.registerOutput("xyz",al.Vector3),this.registerOutput("xy",al.Vector2),this.registerOutput("zw",al.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.x,i=this.y,s=this.z,r=this.w,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],c=this._outputs[1],u=this._outputs[2],d=this._outputs[3],_=e._getShaderType(al.Vector4),p=e._getShaderType(al.Vector3),f=e._getShaderType(al.Vector2);return l.isConnected?(h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${l.associatedVariableName}${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${l.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${l.associatedVariableName}${this._buildSwizzle(2)};\n`)):a.isConnected?(h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${_}(${a.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${a.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${a.associatedVariableName}${this._buildSwizzle(2)};\n`)):n.isConnected?(h.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(h)+` = ${_}(${n.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=e._declareOutput(h)+` = ${_}(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${p}(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${n.associatedVariableName}${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(d)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=e._declareOutput(d)+` = ${f}(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};\n`)):(h.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(h)+` = ${_}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=e._declareOutput(h)+` = ${_}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${p}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${f}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(d)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=e._declareOutput(d)+` = ${f}(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};\n`)),this}serialize(){const e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.xSwizzle=e.xSwizzle??"x",this.ySwizzle=e.ySwizzle??"y",this.zSwizzle=e.zSwizzle??"z",this.wSwizzle=e.wSwizzle??"w"}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}";\n`,e+=`${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";\n`,e+=`${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";\n`,e+=`${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";\n`,e}}z("BABYLON.VectorMergerBlock",Ul);class Gl extends Tl{constructor(e){super(e,ll.Neutral),this.sourceRange=new de(-1,1),this.targetRange=new de(0,1),this.registerInput("input",al.AutoDetect),this.registerInput("sourceMin",al.Float,!0),this.registerInput("sourceMax",al.Float,!0),this.registerInput("targetMin",al.Float,!0),this.registerInput("targetMax",al.Float,!0),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),s=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),r=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),n=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=e._declareOutput(t)+` = ${r} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${r}) / (${s} - ${i});\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\n`;return e+=`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\n`,e}serialize(){const e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=de.FromArray(e.sourceRange),this.targetRange=de.FromArray(e.targetRange)}}Ze([Cl("From",ul.Vector2)],Gl.prototype,"sourceRange",void 0),Ze([Cl("To",ul.Vector2)],Gl.prototype,"targetRange",void 0),z("BABYLON.RemapBlock",Gl);class zl extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("left",al.AutoDetect),this.registerInput("right",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this.output._typeConnectionSource=this.left,this._linkConnectionTypes(0,1,!0),this.left.acceptedConnectionPointTypes.push(al.Float),this.right.acceptedConnectionPointTypes.push(al.Float),this._connectionObservers=[this.left.onTypeChangedObservable.add((()=>this._updateInputOutputTypes())),this.right.onTypeChangedObservable.add((()=>this._updateInputOutputTypes()))]}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===al.Int||this.left.type===al.Float&&this.right.type!==al.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(const[e,t]of[[this.left,this.right],[this.right,this.left]])e.acceptedConnectionPointTypes=[al.Int,al.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==al.Int&&t.type!==al.Float||e.acceptedConnectionPointTypes.push(al.Vector2,al.Vector3,al.Vector4,al.Color3,al.Color4,al.Matrix))}dispose(){super.dispose(),this._connectionObservers.forEach((e=>e.remove())),this._connectionObservers.length=0}}class Wl extends zl{constructor(e){super(e)}getClassName(){return"MultiplyBlock"}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};\n`,this}}var Hl;z("BABYLON.MultiplyBlock",Wl),function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture"}(Hl||(Hl={}));class Xl extends xl{constructor(){super(),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class Yl{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:_e.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:_e.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:_e.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:_e.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let s=0;for(const i of t){if(i.gradient===e){t.splice(s,1);break}s++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=_e.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this.applyFog=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new _e(10,10,10),this.onAnimationEnd=null,this.blendMode=Yl.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new de(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new _e(0,0,0),this._useLogarithmicDepth=!1,this.gravity=_e.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new Ae(1,1,1,1),this.color2=new Ae(1,1,1,1),this.colorDead=new Ae(0,0,0,1),this.textureMask=new Ae(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new Xl,this.id=e,this.name=e}createPointEmitter(e,t){throw new Error("Method not implemented.")}createHemisphericEmitter(e=1,t=1){throw new Error("Method not implemented.")}createSphereEmitter(e=1,t=1){throw new Error("Method not implemented.")}createDirectedSphereEmitter(e=1,t=new _e(0,1,0),i=new _e(0,1,0)){throw new Error("Method not implemented.")}createCylinderEmitter(e=1,t=1,i=1,s=0){throw new Error("Method not implemented.")}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new _e(0,1,0),r=new _e(0,1,0)){throw new Error("Method not implemented.")}createConeEmitter(e=1,t=Math.PI/4){throw new Error("Method not implemented.")}createBoxEmitter(e,t,i,s){throw new Error("Method not implemented.")}}Yl.BLENDMODE_ONEONE=0,Yl.BLENDMODE_STANDARD=1,Yl.BLENDMODE_ADD=2,Yl.BLENDMODE_MULTIPLY=3,Yl.BLENDMODE_MULTIPLYADD=4,z("BABYLON.BaseParticleSystem",Yl);class Ql extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("rgba",al.Color4,!0),this.registerInput("rgb ",al.Color3,!0),this.registerOutput("rgb",al.Color3),this.registerOutput("r",al.Float),this.registerOutput("g",al.Float),this.registerOutput("b",al.Float),this.registerOutput("a",al.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);const t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;const i=this._outputs[0],s=this._outputs[1],r=this._outputs[2],n=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${t.associatedVariableName}.rgb;\n`),s.hasEndpoints&&(e.compilationString+=e._declareOutput(s)+` = ${t.associatedVariableName}.r;\n`),r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = ${t.associatedVariableName}.g;\n`),n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = ${t.associatedVariableName}.b;\n`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = ${t.associatedVariableName}.a;\n`),this}}z("BABYLON.ColorSplitterBlock",Ql),qs.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,(1!==s.type||this._caps.textureFloatLinearFiltering)&&(2!==s.type||this._caps.textureHalfFloatLinearFiltering)||(s.samplingMode=1);const r=this._gl,n=new ss(this,is.RenderTarget);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,n,!0);const o=this._getSamplingParameters(s.samplingMode,s.generateMipMaps);1!==s.type||this._caps.textureFloat||(s.type=0,Ne.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,o.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,o.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let t=0;t<6;t++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(s.type,s.format),e,e,0,this._getInternalFormat(s.format),this._getWebGLTextureType(s.type),null);const a=r.createFramebuffer();return this._bindUnboundFramebuffer(a),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(s.generateStencilBuffer,s.generateDepthBuffer,e,e),s.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=a,i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=s.generateMipMaps,n.samplingMode=s.samplingMode,n.type=s.type,n.format=s.format,this._internalTexturesCache.push(n),i.setTextures(n),i},qs.prototype.setDepthStencilTexture=function(e,t,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,s):this._setTexture(e,null,void 0,void 0,s))};const jl={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class Kl{constructor(e,t=jl){this._fullscreenViewport=new Pn(0,0,1,1);const i=t.positions??jl.positions,s=t.indices??jl.indices;this.engine=e,this._vertexBuffers={[er.PositionKind]:new er(e,i,er.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(s),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(s);for(const e in this._vertexBuffers)this._vertexBuffers[e]._rebuild()}))}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=null===t?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){const e=this._vertexBuffers[er.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[er.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class $l{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new K;const i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add((()=>{this.effect.setFloat2("scale",1,1)})));const s=e.defines?e.defines.join("\n"):"";this._drawWrapper=new Un(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],i,e.samplerNames,s,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new $i(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,s,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add((()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const ql="passPixelShader",Zl="varying vec2 vUV;uniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);}";Bi.ShadersStore[ql]=Zl;const Jl=ql,eh=Zl;class th{static _CreateDumpRenderer(){if(!th._DumpToolsEngine){let e,t=null;const i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new qs(e,!1,i)}catch(s){e=document.createElement("canvas"),t=new qs(e,!1,i)}re.Instances.pop(),re.OnEnginesDisposedObservable.add((e=>{t&&e!==t&&!t.isDisposed&&0===re.Instances.length&&th.Dispose()})),t.getCaps().parallelShaderCompile=void 0;const s=new Kl(t),r=new $l({engine:t,name:Jl,fragmentShader:eh,samplerNames:["textureSampler"]});th._DumpToolsEngine={canvas:e,engine:t,renderer:s,wrapper:r}}return th._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,r="image/png",n,o){const a=await i.readPixels(0,0,e,t),l=new Uint8Array(a.buffer);th.DumpData(e,t,l,s,r,n,!0,void 0,o)}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,o=!1,a){return new Promise((l=>{th.DumpData(e,t,i,(e=>l(e)),s,r,n,o,a)}))}static DumpData(e,t,i,s,r="image/png",n,o=!1,a=!1,l){const h=th._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){const e=new Uint8Array(i.length);let t=i.length;for(;t--;){const s=i[t];e[t]=Math.round(255*be.Clamp(s))}i=e}const c=h.engine.createRawTexture(i,e,t,5,!1,!o,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",c),h.renderer.draw(),a?Ds.ToBlob(h.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;s&&s(t)},t.readAsArrayBuffer(e)}),r,l):Ds.EncodeScreenshotCanvasData(h.canvas,s,r,n,l),c.dispose()}static Dispose(){th._DumpToolsEngine&&(th._DumpToolsEngine.wrapper.dispose(),th._DumpToolsEngine.renderer.dispose(),th._DumpToolsEngine.engine.dispose()),th._DumpToolsEngine=null}}Ds.DumpData=th.DumpData,Ds.DumpDataAsync=th.DumpDataAsync,Ds.DumpFramebuffer=th.DumpFramebuffer,$i.prototype.setDepthStencilTexture=function(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)};class ih extends Pa{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=ie(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;i=Array.isArray(e)?e:[e];for(let e=0;e{const i=this._renderList?this._renderList.length:0;(0===t&&i>0||0===i)&&this.getScene()?.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new K,this.onAfterUnbindObservable=new K,this.onBeforeRenderObservable=new K,this.onAfterRenderObservable=new K,this.onClearObservable=new K,this.onResizeObservable=new K,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=_e.Zero(),!(i=this.getScene()))return;const x=this.getScene().getEngine();this._gammaSpace=v,this._coordinatesMode=Pa.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=o,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=x.onResizeObservable.add((()=>{})),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=r,this._renderingManager=new nr(i),this._renderingManager._useSceneAutoClearSetup=!0,c||(this._renderTargetOptions={generateMipMaps:s,type:n,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:h,samples:_,creationFlags:p,noColorAttachment:f,useSRGBBuffer:m,colorAttachment:g,label:this.name},this.samplingMode===Pa.NEAREST_SAMPLINGMODE&&(this.wrapU=Pa.CLAMP_ADDRESSMODE,this.wrapV=Pa.CLAMP_ADDRESSMODE),d||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=Pa.INVCUBIC_MODE,this._textureMatrix=me.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==_&&(this.samples=_)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){this._renderTarget?.createDepthStencilTexture(e,t,i,s,r,n)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;if(e)return e;return this._size.depth||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){const t=this.isCube;this._renderTarget?.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e,!1),this._renderTarget=t?i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==this._renderTargetOptions.samples&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){const s=this.getScene();if(!s)return i;const r=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let e=0;e{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):s&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0,r=null){const n=this.getScene();if(!n)return;const o=n.getEngine();if(o._debugPushGroup?.(`render to face #${e} layer #${s}`,1),this._prepareFrame(n,e,s,t),this.is2DArray||this.is3D?(o.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(o.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),o.snapshotRendering&&1===o.snapshotRenderingMode)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||n.clearColor,!0,!0,!0);else{let a=null;const l=this.renderList?this.renderList:n.getActiveMeshes().data,h=this.renderList?this.renderList.length:n.getActiveMeshes().length;this.getCustomRenderList&&(a=this.getCustomRenderList(this.is2DArray||this.is3D?s:e,l,h)),a?this._prepareRenderingManager(a,a.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(l,h,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),a=l);for(const t of n._beforeRenderTargetClearStage)t.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||n.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0);for(const t of n._beforeRenderTargetDrawStage)t.action(this,e,s);this._renderingManager.render(this.customRenderFunction,a,this.renderParticles,this.renderSprites);for(const t of n._afterRenderTargetDrawStage)t.action(this,e,s);const c=this._texture?.generateMipMaps??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&n.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e);for(const t of n._afterRenderTargetPostProcessStage)t.action(this,e,s);this._texture&&(this._texture.generateMipMaps=c),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0),i&&th.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),o)}this._unbindFrameBuffer(o,e),this._texture&&this.isCube&&5===e&&o.generateMipMapsForCubemap(this._texture,!0),o._debugPopGroup?.(1)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new ih(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&e.customRenderTargets.splice(t,1);for(const i of e.cameras)t=i.customRenderTargets.indexOf(this),t>=0&&i.customRenderTargets.splice(t,1);this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===ih.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=ih.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}ih.REFRESHRATE_RENDER_ONCE=0,ih.REFRESHRATE_RENDER_ONEVERYFRAME=1,ih.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,Pa._CreateRenderTargetTexture=(e,t,i,s,r)=>new ih(e,t,i,s);class sh{constructor(e){this.name=or.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(or.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){Ds.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}Bi.ShadersStore.proceduralVertexShader="attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class rh extends Pa{constructor(e,t,i,s,r=null,n=!0,o=!1,a=0){super(null,s,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new K,this.onBeforeGenerationObservable=new K,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._vectors4={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null,null===r||r instanceof Pa?(this._options={},this._fallbackTexture=r):(this._options=r,this._fallbackTexture=r.fallbackTexture??null);let l=(s=this.getScene()||re.LastCreatedScene)._getComponent(or.NAME_PROCEDURALTEXTURE);l||(l=new sh(s),s._addComponent(l)),s.proceduralTextures.push(this),this._fullEngine=s.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=a,this._generateMipMaps=n,this._drawWrapper=new Un(this._fullEngine),this.setFragment(i);const h=this._createRtWrapper(o,t,n,a);this._texture=h.texture;const c=[];c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1),this._vertexBuffers[er.PositionKind]=new er(this._fullEngine,c,er.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,s){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.then((e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId})):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId)),this._contentData}_createIndexBuffer(){const e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[er.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===ih.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=ih.REFRESHRATE_RENDER_ONCE)}reset(){this._drawWrapper.effect?.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}executeWhenReady(e){if(this.isReady())return void e(this);const t=this.getEffect();t&&t.executeWhenCompiled((()=>{e(this)}))}isReady(){const e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;const t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;const i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:"string"==typeof this._fragment?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[er.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,(()=>{this._rtWrapper?.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0}))),this._drawWrapper.effect.isReady()}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;const i=this._texture.isCube;this._rtWrapper.dispose();const s=this._createRtWrapper(i,e,t,this._textureType);this._texture=s.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){const t=this.getScene();if(!t)return;const i=this._fullEngine;if(i.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),i.setState(!1),!this.nodeMaterialSource){for(const e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(const e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(const e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(const e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(const e in this._colors4){const t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(const e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)this._drawWrapper.effect.setVector4(e,this._vectors4[e]);for(const e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;i._debugPushGroup?.(`procedural texture generation for ${this.name}`,1);const s=i.currentViewport;if(this.isCube)for(let e=0;e<6;e++)i.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(ta.TriangleFillMode,0,6);else{let e=1;this._rtWrapper.is3D?e=this._rtWrapper.depth:this._rtWrapper.is2DArray&&(e=this._rtWrapper.layers);for(let s=0;s=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[er.PositionKind];i&&(i.dispose(),this._vertexBuffers[er.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}var nh;Ze([rt()],rh.prototype,"isEnabled",void 0),Ze([rt()],rh.prototype,"autoClear",void 0),Ze([rt()],rh.prototype,"_generateMipMaps",void 0),Ze([rt()],rh.prototype,"_size",void 0),Ze([rt()],rh.prototype,"refreshRate",null),z("BABYLON.ProceduralTexture",rh),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees",e[e.Set=18]="Set"}(nh||(nh={}));class oh extends Tl{constructor(e){super(e,ll.Neutral),this.operation=nh.Cos,this.registerInput("input",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="";switch(this.operation){case nh.Cos:i="cos";break;case nh.Sin:i="sin";break;case nh.Abs:i="abs";break;case nh.Exp:i="exp";break;case nh.Exp2:i="exp2";break;case nh.Round:i="round";break;case nh.Floor:i="floor";break;case nh.Ceiling:i="ceil";break;case nh.Sqrt:i="sqrt";break;case nh.Log:i="log";break;case nh.Tan:i="tan";break;case nh.ArcTan:i="atan";break;case nh.ArcCos:i="acos";break;case nh.ArcSin:i="asin";break;case nh.Fract:i="fract";break;case nh.Sign:i="sign";break;case nh.Radians:i="radians";break;case nh.Degrees:i="degrees";break;case nh.Set:i=""}return e.compilationString+=e._declareOutput(t)+` = ${i}(${this.input.associatedVariableName});\n`,this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${nh[this.operation]};\n`}}z("BABYLON.TrigonometryBlock",oh);const ah={effect:null,subMesh:null};class lh extends xl{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class hh extends ml{static _BlockIsTextureBlock(e){return"TextureBlock"===e.getClassName()||"ReflectionTextureBaseBlock"===e.getClassName()||"ReflectionTextureBlock"===e.getClassName()||"ReflectionBlock"===e.getClassName()||"RefractionBlock"===e.getClassName()||"CurrentScreenBlock"===e.getClassName()||"ParticleTextureBlock"===e.getClassName()||"ImageSourceBlock"===e.getClassName()||"TriPlanarBlock"===e.getClassName()||"BiPlanarBlock"===e.getClassName()||"PrePassTextureBlock"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get shaderLanguage(){return this._options.shaderLanguage}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){if(super(e,t||re.LastCreatedScene),this._buildId=hh._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new me,this._cachedWorldViewProjectionMatrix=new me,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new K,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=[],this._mode=Hl.Material,this.forceAlphaBlending=!1,i&&i.shaderLanguage===di.WGSL&&!this.getScene().getEngine().isWebGPU)throw new Error("WebGPU shader language is only supported with WebGPU engine");this._options={emitComments:!1,shaderLanguage:hh.DefaultShaderLanguage,...i},this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return Ds.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(const t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){const t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return e.target&ll.Vertex&&this._addVertexOutputNode(e),e.target&ll.Fragment&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||(e.target&ll.Vertex&&this._removeVertexOutputNode(e),e.target&ll.Fragment&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=ll.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){const t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=ll.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){const t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,s=!0){(e.target===ll.VertexAndFragment||t.target===ll.Fragment&&e.target===ll.Vertex&&e._preparationId!==this._buildId)&&i.push(e),this._initializeBlock(e,t,i,s)}_initializeBlock(e,t,i,s=!0){if(e.initialize(t),s&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){const t=e.getClassName();for(const e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const r of e.inputs){r.associatedVariableName="";const n=r.connectedPoint;if(n){const r=n.ownerBlock;r!==e&&this._processInitializeOnLink(r,t,i,s)}}if(e.isTeleportOut){const r=e;r.entryPoint&&this._processInitializeOnLink(r.entryPoint,t,i,s)}for(const t of e.outputs)t.associatedVariableName=""}_resetDualBlocks(e,t){e.target===ll.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._resetDualBlocks(i.entryPoint,t)}}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){this._vertexCompilationState||i||(i=!0),this._buildWasSuccessful=!1;const s=this.getScene().getEngine(),r=this._mode===Hl.Particle;if(0===this._vertexOutputNodes.length&&!r)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new gl,this._vertexCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._vertexCompilationState.target=ll.Vertex,this._fragmentCompilationState=new gl,this._fragmentCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._fragmentCompilationState.target=ll.Fragment,this._sharedData=new vl,this._sharedData.nodeMaterial=this,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=r;const n=[],o=[];for(const e of this._vertexOutputNodes)n.push(e),this._initializeBlock(e,this._vertexCompilationState,o,i);for(const e of this._fragmentOutputNodes)o.push(e),this._initializeBlock(e,this._fragmentCompilationState,n,i);this.optimize();for(const e of n)e.build(this._vertexCompilationState,n);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(const e of o)this._resetDualBlocks(e,this._buildId-1);for(const e of o)e.build(this._fragmentCompilationState,o);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=hh._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(Ne.Log("Vertex shader:"),Ne.Log(this._vertexCompilationState.compilationString),Ne.Log("Fragment shader:"),Ne.Log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const a=this.getScene().meshes;for(const e of a)if(e.subMeshes)for(const t of e.subMeshes){if(t.getMaterial()!==this)continue;if(!t.materialDefines)continue;const e=t.materialDefines;e.markAllAsDirty(),e.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();const l=this.getScene().prePassRenderer;l&&l.markAsDirty()}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,s=t.TANGENT,r=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(er.NormalKind),t.TANGENT=e.isVerticesDataPresent(er.TangentKind);const n=e.useVertexColors&&e.isVerticesDataPresent(er.ColorKind);t.VERTEXCOLOR_NME=n;let o=!1;for(let i=1;i<=6;++i){const s=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),o=o||t["UV"+i]!==s}const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;qo(this.getScene(),t,!a),(i!==t.NORMAL||s!==t.TANGENT||r!==t.VERTEXCOLOR_NME||o)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){const e=this.getBlockByPredicate((e=>"PrePassOutputBlock"===e.getClassName())),t=[4];return e?(this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t):t}get prePassTextureInputs(){const e=this.getAllTextureBlocks().filter((e=>"PrePassTextureBlock"===e.getClassName())),t=[];for(const i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){const t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]}));for(const e of t)i.texturesRequired.includes(e)||i.texturesRequired.push(e);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,s,r,n=0,o=5){return this.mode!==Hl.PostProcess?(Ne.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,s,r,n,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,s=1,r,n,o=0,a=5){let l=this.name+this._buildId;const h=new lh,c=new _o(l+"PostProcess",this.getScene());let u=this._buildId;return this._processDefines(c,h),$i.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new Vl(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,s,r,n,h.toString(),o,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,a),e.nodeMaterialSource=this,e.onApplyObservable.add((t=>{u!==this._buildId&&(delete $i.ShadersStore[l+"VertexShader"],delete $i.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),u=this._buildId),this._processDefines(c,h)&&($i.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Li.SetImmediate((()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l)))),this._checkInternals(t)})),e}createProceduralTexture(e,t){if(this.mode!==Hl.ProceduralTexture)return Ne.Log("Incompatible material mode"),null;let i=this.name+this._buildId;const s=new rh(i,e,null,t),r=new _o(i+"Procedural",this.getScene());r.reservedDataStore={hidden:!0};const n=new lh,o=this._processDefines(r,n);$i.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[er.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),o?.fallbacks,void 0);s.nodeMaterialSource=this,s._setEffect(a);let l=this._buildId;return s.onBeforeGenerationObservable.add((()=>{l!==this._buildId&&(delete $i.ShadersStore[i+"VertexShader"],delete $i.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),l=this._buildId);const e=this._processDefines(r,n);e&&($i.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Li.SetImmediate((()=>{a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[er.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),e?.fallbacks,void 0),s._setEffect(a)}))),this._checkInternals(a)})),s}_createEffectForParticles(e,t,i,s,r,n,o,a=""){let l=this.name+this._buildId+"_"+t;n||(n=new lh),o||(o=this.getScene().getMeshByName(this.name+"Particle"))||((o=new _o(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId;const c=[];let u=a;if(!r){const a=this._processDefines(o,n);$i.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(c,t,!1),u=c.join("\n"),r=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,a?.fallbacks,i,s,e),e.setCustomEffect(r,t)}r.onBindObservable.add((r=>{h!==this._buildId&&(delete $i.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,n.markAllAsDirty(),h=this._buildId),c.length=0,e.fillDefines(c,t,!1);const d=c.join("\n");d!==u&&(n.markAllAsDirty(),u=d);const _=this._processDefines(o,n);if(_)return $i.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),r=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,_?.fallbacks,i,s,e),e.setCustomEffect(r,t),void this._createEffectForParticles(e,t,i,s,r,n,o,a);this._checkInternals(r)}))}_checkInternals(e){if(this._sharedData.animatedInputs){const e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(const t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(const t of this._sharedData.bindableBlocks)t.bind(e,this);for(const t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){this.mode===Hl.Particle?(this._createEffectForParticles(e,Yl.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,Yl.BLENDMODE_MULTIPLY,t,i)):Ne.Log("Incompatible material mode")}createAsShadowDepthWrapper(e){this.mode===Hl.Material?e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene()):Ne.Log("Incompatible material mode")}_processDefines(e,t,i=!1,s){let r=null;if(Zo(this.getScene(),t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach((s=>{s.initializeDefines(e,this,t,i)})),this._sharedData.blocksWithDefines.forEach((r=>{r.prepareDefines(e,this,t,i,s)})),t.isDirty){const i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach((i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)}));const s=[];this._sharedData.dynamicUniformBlocks.forEach((e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,s)}));const n=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach((e=>{-1===n.indexOf(e)&&n.push(e)}));const o=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach((e=>{-1===o.indexOf(e)&&o.push(e)}));const a=new Ll;this._sharedData.blocksWithFallbacks.forEach((t=>{t.provideFallbacks(e,a)})),r={lightDisposed:i,uniformBuffers:s,mergedUniforms:n,mergedSamplers:o,fallbacks:a}}return r}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const s=this.getScene();if(this._sharedData.animatedInputs){const e=s.getFrameId();if(this._animationFrame!==e){for(const e of this._sharedData.animatedInputs)e.animate(s);this._animationFrame=e}}const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new lh);const n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=s.getEngine();if(this._prepareDefinesForAttributes(e,n),this._sharedData.blockingBlocks.some((t=>!t.isReady(e,this,n,i))))return!1;const a=this._processDefines(e,n,i,t);if(a){const e=t.effect,i=n.toString();let r=o.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:i,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:n.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS},shaderLanguage:this.shaderLanguage},o);if(r)if(this._onEffectCreatedObservable&&(ah.effect=r,ah.subMesh=t,this._onEffectCreatedObservable.notifyObservers(ah)),this.allowShaderHotSwapping&&e&&!r.isReady()){if(r=e,n.markAsUnprocessed(),a.lightDisposed)return n._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(r,n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}get compiledShaders(){return`// Vertex shader\n${this._vertexCompilationState.compilationString}\n\n// Fragment shader\n${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){const t=this.getScene();if(!this._activeEffect)return;const i=this._sharedData.hints;i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(const t of this._sharedData.inputBlocks)t._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.effect;if(!r)return;this._activeEffect=r,this.bindOnlyWorldMatrix(e);const n=this._mustRebind(s,r,i,t.visibility),o=this._sharedData;if(n){for(const e of o.bindableBlocks)e.bind(r,this,t,i);for(const e of o.forcedBindableBlocks)e.bind(r,this,t,i);for(const e of o.inputBlocks)e._transmit(r,s,this)}else if(!this.isFrozen)for(const e of o.forcedBindableBlocks)e.bind(r,this,t,i);this._afterBind(t,this._activeEffect,i)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter((e=>e.texture)).map((e=>e.texture))),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)hh._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(const t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(const e of this.getTextureBlocks().filter((e=>e.texture)).map((e=>e.texture)))e.dispose();for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){const t={nodeMaterial:this,...e};this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise((t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),void 0===this.BJSNODEMATERIALEDITOR){const i=e&&e.editorURL?e.editorURL:hh.EditorURL;Ds.LoadBabylonScript(i,(()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(e?.nodeEditorConfig),t()}))}else this._createNodeEditor(e?.nodeEditorConfig),t()}))}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;const e=new Ol("Position");e.setAsAttribute("position");const t=new Ol("World");t.setAsSystemValue(_l.World);const i=new yl("WorldPos");e.connectTo(i),t.connectTo(i);const s=new Ol("ViewProjection");s.setAsSystemValue(_l.ViewProjection);const r=new yl("WorldPos * ViewProjectionTransform");i.connectTo(r),s.connectTo(r);const n=new Sl("VertexOutput");r.connectTo(n);const o=new Ol("color");o.value=new Ae(.8,.8,.8,1);const a=new El("FragmentOutput");o.connectTo(a),this.addOutputNode(n),this.addOutputNode(a),this._mode=Hl.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Ol("Position");e.setAsAttribute("position2d");const t=new Ol("Constant1");t.isConstant=!0,t.value=1;const i=new Ul("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new Sl("VertexOutput");i.connectTo(s);const r=new Ol("Scale");r.visibleInInspector=!0,r.value=new de(1,1);const n=new Gl("uv0");e.connectTo(n);const o=new Wl("UV scale");n.connectTo(o),r.connectTo(o);const a=new Dl("CurrentScreen");o.connectTo(a),a.texture=new Pa("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const l=new El("FragmentOutput");a.connectTo(l,{output:"rgba"}),this.addOutputNode(s),this.addOutputNode(l),this._mode=Hl.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Ol("Position");e.setAsAttribute("position2d");const t=new Ol("Constant1");t.isConstant=!0,t.value=1;const i=new Ul("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new Sl("VertexOutput");i.connectTo(s);const r=new Ol("Time");r.value=0,r.min=0,r.max=0,r.isBoolean=!1,r.matrixMode=0,r.animationType=pl.Time,r.isConstant=!1;const n=new Ol("Color3");n.value=new Ee(1,1,1),n.isConstant=!1;const o=new El("FragmentOutput"),a=new Ul("VectorMerger");a.visibleInInspector=!1;const l=new oh("Cos");l.operation=nh.Cos,e.connectTo(a),r.output.connectTo(l.input),l.output.connectTo(a.z),a.xyzOut.connectTo(o.rgb),this.addOutputNode(s),this.addOutputNode(o),this._mode=Hl.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Ol("uv");e.setAsAttribute("particle_uv");const t=new wl("ParticleTexture");e.connectTo(t);const i=new Ol("Color");i.setAsAttribute("particle_color");const s=new Wl("Texture * Color");t.connectTo(s),i.connectTo(s);const r=new Nl("ParticleRampGradient");s.connectTo(r);const n=new Ql("ColorSplitter");i.connectTo(n);const o=new Fl("ParticleBlendMultiply");r.connectTo(o),t.connectTo(o,{output:"a"}),n.connectTo(o,{output:"a"});const a=new El("FragmentOutput");o.connectTo(a),this.addOutputNode(a),this._mode=Hl.Particle}async loadAsync(e,t=""){return hh.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,t);const s=[];for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,s);let r=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}");\n`;r+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${Hl[this.mode]};\n`;for(const s of t)s.isInput&&-1===e.indexOf(s)&&(r+=s._dumpCode(i,e));for(const t of s)t.isInput&&-1===e.indexOf(t)&&(r+=t._dumpCode(i,e));e=[],r+="\n// Connections\n";for(const t of this._vertexOutputNodes)r+=t._dumpCodeForOutputConnections(e);for(const t of this._fragmentOutputNodes)r+=t._dumpCodeForOutputConnections(e);r+="\n// Output nodes\n";for(const e of this._vertexOutputNodes)r+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;for(const e of this._fragmentOutputNodes)r+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;return r+="nodeMaterial.build();\n",r}serialize(e){const t=e?{}:St.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{t.customType="BABYLON.NodeMaterial",t.outputNodes=[];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n)for(const o of r.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==s.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;s.connectTo(e,!0),this._restoreConnections(n,t,i)}}}parseSerializedObject(e,t="",i=!1,s){i||this.clear();const r={};for(const i of e.blocks){const e=W(i.customType);if(e){const n=new e;n._deserialize(i,this.getScene(),t,s),r[i.id]=n,this.attachedBlocks.push(n)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,i=t._tempEntryPointUniqueId;i&&r[i].attachToEndpoint(t)}for(let t=0;tnew hh(e,this.getScene(),this.options)),this);return s.id=e,s.name=e,s.parseSerializedObject(i),s._buildId=this._buildId,s.build(!1,!t),s}whenTexturesReadyAsync(){const e=[];return this.getActiveTextures().forEach((t=>{const i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise(((e,t)=>{i.onLoadedObservable.addOnce((()=>{e()})),i.onErrorObservable.addOnce((e=>{t(e)}))})))})),Promise.all(e)}static Parse(e,t,i="",s=di.GLSL){const r=St.Parse((()=>new hh(e.name,t,{shaderLanguage:s})),e,t,i);return r.parseSerializedObject(e,i),r.build(),r}static async ParseFromFileAsync(e,t,i,s="",r=!1,n,o){const a=n??new hh(e,i),l=await i._loadFileAsync(t),h=JSON.parse(l);return a.parseSerializedObject(h,s,void 0,o),r||a.build(),a}static ParseFromSnippetAsync(e,t=re.LastCreatedScene,i="",s,r=!1,n=!1,o){return"_BLANK"===e?Promise.resolve(hh.CreateDefault("blank",t)):new Promise(((a,l)=>{const h=new Pt;h.addEventListener("readystatechange",(()=>{if(4==h.readyState)if(200==h.status){const c=JSON.parse(JSON.parse(h.responseText).jsonPayload),u=JSON.parse(c.nodeMaterial);s||((s=St.Parse((()=>new hh(e,t)),u,t,i)).uniqueId=t.getUniqueId()),s.parseSerializedObject(u,void 0,void 0,o),s.snippetId=e;try{r||s.build()}catch(e){l(e)}n?s.whenTexturesReadyAsync().then((()=>{a(s)})).catch((e=>{l(e)})):a(s)}else l("Unable to load the snippet "+e)})),h.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),h.send()}))}static CreateDefault(e,t){const i=new hh(e,t);return i.setToDefault(),i.build(),i}}function ch(e){const t=e.sideOrientation||Wn.DEFAULTSIDE,i=e.radius||1,s=void 0===e.flat||e.flat,r=0|(e.subdivisions||4),n=e.radiusX||i,o=e.radiusY||i,a=e.radiusZ||i,l=(1+Math.sqrt(5))/2,h=[-1,l,-0,1,l,0,-1,-l,0,1,-l,0,0,-1,-l,0,1,-l,0,-1,l,0,1,l,l,0,1,l,0,-1,-l,0,1,-l,0,-1],c=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],u=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],d=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],_=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],p=[],f=[],m=[],g=[];let v=0;const x=new Array(3),b=new Array(3);let T;for(T=0;T<3;T++)x[T]=_e.Zero(),b[T]=de.Zero();for(let e=0;e<20;e++){for(T=0;T<3;T++){const t=c[3*e+T];x[T].copyFromFloats(h[3*u[t]],h[3*u[t]+1],h[3*u[t]+2]),x[T].normalize(),b[T].copyFromFloats(.134765625*d[2*t]+.05859375+-.0390625*_[e],.2333984375*d[2*t+1]+.025390625+.01953125*_[e])}const t=(e,t,i,l)=>{const h=_e.Lerp(x[0],x[2],t/r),c=_e.Lerp(x[1],x[2],t/r),u=r===t?x[2]:_e.Lerp(h,c,e/(r-t));let d;if(u.normalize(),s){const e=_e.Lerp(x[0],x[2],l/r),t=_e.Lerp(x[1],x[2],l/r);d=_e.Lerp(e,t,i/(r-l))}else d=new _e(u.x,u.y,u.z);d.x/=n,d.y/=o,d.z/=a,d.normalize();const _=de.Lerp(b[0],b[2],t/r),T=de.Lerp(b[1],b[2],t/r),y=r===t?b[2]:de.Lerp(_,T,e/(r-t));f.push(u.x*n,u.y*o,u.z*a),m.push(d.x,d.y,d.z),g.push(y.x,Xn.UseOpenGLOrientationForUV?1-y.y:y.y),p.push(v),v++};for(let e=0;euh(e,t,i),function(e){e.WRIST="wrist",e.THUMB="thumb",e.INDEX="index",e.MIDDLE="middle",e.RING="ring",e.LITTLE="little"}(_h||(_h={})),function(e){e.WRIST="wrist",e.THUMB_METACARPAL="thumb-metacarpal",e.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",e.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",e.THUMB_TIP="thumb-tip",e.INDEX_FINGER_METACARPAL="index-finger-metacarpal",e.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",e.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",e.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",e.INDEX_FINGER_TIP="index-finger-tip",e.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",e.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",e.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",e.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",e.MIDDLE_FINGER_TIP="middle-finger-tip",e.RING_FINGER_METACARPAL="ring-finger-metacarpal",e.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",e.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",e.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",e.RING_FINGER_TIP="ring-finger-tip",e.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",e.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",e.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",e.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",e.PINKY_FINGER_TIP="pinky-finger-tip"}(ph||(ph={}));const fh=[ph.WRIST,ph.THUMB_METACARPAL,ph.THUMB_PHALANX_PROXIMAL,ph.THUMB_PHALANX_DISTAL,ph.THUMB_TIP,ph.INDEX_FINGER_METACARPAL,ph.INDEX_FINGER_PHALANX_PROXIMAL,ph.INDEX_FINGER_PHALANX_INTERMEDIATE,ph.INDEX_FINGER_PHALANX_DISTAL,ph.INDEX_FINGER_TIP,ph.MIDDLE_FINGER_METACARPAL,ph.MIDDLE_FINGER_PHALANX_PROXIMAL,ph.MIDDLE_FINGER_PHALANX_INTERMEDIATE,ph.MIDDLE_FINGER_PHALANX_DISTAL,ph.MIDDLE_FINGER_TIP,ph.RING_FINGER_METACARPAL,ph.RING_FINGER_PHALANX_PROXIMAL,ph.RING_FINGER_PHALANX_INTERMEDIATE,ph.RING_FINGER_PHALANX_DISTAL,ph.RING_FINGER_TIP,ph.PINKY_FINGER_METACARPAL,ph.PINKY_FINGER_PHALANX_PROXIMAL,ph.PINKY_FINGER_PHALANX_INTERMEDIATE,ph.PINKY_FINGER_PHALANX_DISTAL,ph.PINKY_FINGER_TIP],mh={[_h.WRIST]:[ph.WRIST],[_h.THUMB]:[ph.THUMB_METACARPAL,ph.THUMB_PHALANX_PROXIMAL,ph.THUMB_PHALANX_DISTAL,ph.THUMB_TIP],[_h.INDEX]:[ph.INDEX_FINGER_METACARPAL,ph.INDEX_FINGER_PHALANX_PROXIMAL,ph.INDEX_FINGER_PHALANX_INTERMEDIATE,ph.INDEX_FINGER_PHALANX_DISTAL,ph.INDEX_FINGER_TIP],[_h.MIDDLE]:[ph.MIDDLE_FINGER_METACARPAL,ph.MIDDLE_FINGER_PHALANX_PROXIMAL,ph.MIDDLE_FINGER_PHALANX_INTERMEDIATE,ph.MIDDLE_FINGER_PHALANX_DISTAL,ph.MIDDLE_FINGER_TIP],[_h.RING]:[ph.RING_FINGER_METACARPAL,ph.RING_FINGER_PHALANX_PROXIMAL,ph.RING_FINGER_PHALANX_INTERMEDIATE,ph.RING_FINGER_PHALANX_DISTAL,ph.RING_FINGER_TIP],[_h.LITTLE]:[ph.PINKY_FINGER_METACARPAL,ph.PINKY_FINGER_PHALANX_PROXIMAL,ph.PINKY_FINGER_PHALANX_INTERMEDIATE,ph.PINKY_FINGER_PHALANX_DISTAL,ph.PINKY_FINGER_TIP]};class gh{get handMesh(){return this._handMesh}getHandPartMeshes(e){return mh[e].map((e=>this._jointMeshes[fh.indexOf(e)]))}getJointMesh(e){return this._jointMeshes[fh.indexOf(e)]}constructor(e,t,i,s,r=!1,n=!1,o=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=s,this._leftHandedMeshes=r,this._jointsInvisible=n,this._jointScaleFactor=o,this.onHandMeshSetObservable=new K,this._jointTransforms=new Array(fh.length),this._jointTransformMatrices=new Float32Array(16*fh.length),this._tempJointMatrix=new me,this._jointRadii=new Float32Array(fh.length),this._scene=t[0].getScene();for(let e=0;e{e._doNotLoadControllerMesh=!0}))}setHandMesh(e,t,i){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach((e=>{e.alwaysSelectAsActiveMesh=!0})),this._handMesh.skeleton){const e=this._handMesh.skeleton;fh.forEach(((i,s)=>{const r=e.getBoneIndexByName(t?t[i]:i);-1!==r&&e.bones[r].linkTransformNode(this._jointTransforms[s])}))}this.onHandMeshSetObservable.notifyObservers(this)}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const s=i,r=fh.map((e=>s[e]||i.get(e)));let n=!1;if(e.fillPoses&&e.fillJointRadii)n=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){n=!0;for(let i=0;i{const i=this._jointTransforms[t];me.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);const s=this._jointRadii[t]*this._jointScaleFactor,r=this._jointMeshes[t];r.isVisible=!this._handMesh&&!this._jointsInvisible,r.position.copyFrom(i.position),r.rotationQuaternion.copyFrom(i.rotationQuaternion),r.scaling.setAll(s),this._scene.useRightHandedSystem||(r.position.z*=-1,r.rotationQuaternion.z*=-1,r.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))})),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(e=!1){this._handMesh&&(e?(this._handMesh.skeleton?.dispose(),this._handMesh.dispose(!1,!0)):this._handMesh.isVisible=!1)}}class vh extends Ja{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map((i=>{const s=[],r=e.jointMeshes?.sourceMesh||uh("jointParent",vh._ICOSPHERE_PARAMS);r.isVisible=!!e.jointMeshes?.keepOriginalVisible;for(let t=0;t{const r={};vh._RightHandGLB?.meshes[1]?.isDisposed()&&(vh._RightHandGLB=null),vh._LeftHandGLB?.meshes[1]?.isDisposed()&&(vh._LeftHandGLB=null);const n=!(!vh._RightHandGLB||!vh._LeftHandGLB),o=await Promise.all([vh._RightHandGLB||fl.ImportMeshAsync("",vh.DEFAULT_HAND_MODEL_BASE_URL,vh.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),vh._LeftHandGLB||fl.ImportMeshAsync("",vh.DEFAULT_HAND_MODEL_BASE_URL,vh.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);vh._RightHandGLB=o[0],vh._LeftHandGLB=o[1];const a=await hh.ParseFromFileAsync("handShader",vh.DEFAULT_HAND_MODEL_SHADER_URL,e);a.needDepthPrePass=!0,a.transparencyMode=ta.MATERIAL_ALPHABLEND,a.alphaMode=2,a.build(!1);const l={base:Ee.FromInts(116,63,203),fresnel:Ee.FromInts(149,102,229),fingerColor:Ee.FromInts(177,130,255),tipFresnel:Ee.FromInts(220,200,255),...i?.handMeshes?.customColors},h={base:a.getBlockByName("baseColor"),fresnel:a.getBlockByName("fresnelColor"),fingerColor:a.getBlockByName("fingerColor"),tipFresnel:a.getBlockByName("tipFresnelColor")};h.base.value=l.base,h.fresnel.value=l.fresnel,h.fingerColor.value=l.fingerColor,h.tipFresnel.value=l.tipFresnel;const c=t._getBaseLayerWrapper()?.isMultiview;["left","right"].forEach((t=>{const i="left"==t?vh._LeftHandGLB:vh._RightHandGLB;if(!i)throw new Error("Could not load hand model");const s=i.meshes[1];s._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,c||(s.material=a.clone(`${t}HandShaderClone`,!0)),s.isVisible=!1,r[t]=s,n||e.useRightHandedSystem||i.meshes[1].rotate(Xr.Y,Math.PI)})),a.dispose(),s({left:r.left,right:r.right})}))}static _GenerateDefaultHandMeshRigMapping(e){const t="right"==e?"R":"L";return{[ph.WRIST]:`wrist_${t}`,[ph.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[ph.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[ph.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[ph.THUMB_TIP]:`thumb_tip_${t}`,[ph.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[ph.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[ph.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[ph.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[ph.INDEX_FINGER_TIP]:`index_tip_${t}`,[ph.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[ph.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[ph.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[ph.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[ph.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[ph.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[ph.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[ph.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[ph.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[ph.RING_FINGER_TIP]:`ring_tip_${t}`,[ph.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[ph.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[ph.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[ph.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[ph.PINKY_FINGER_TIP]:`little_tip_${t}`}}isCompatible(){return"undefined"!=typeof XRHand}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return"none"==e?null:this._trackingHands[e]}constructor(e,t){super(e),this.options=t,this._attachedHands={},this._trackingHands={left:null,right:null},this._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},this._worldScaleObserver=null,this.onHandAddedObservable=new K,this.onHandRemovedObservable=new K,this._attachHand=e=>{if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;const t=e.inputSource.handedness,i=new gh(e,this._handResources.jointMeshes[t],this._handResources.handMeshes&&this._handResources.handMeshes[t],this._handResources.rigMappings&&this._handResources.rigMappings[t],this.options.handMeshes?.meshesUseLeftHandedCoordinates,this.options.jointMeshes?.invisible,this.options.jointMeshes?.scaleFactor);this._attachedHands[e.uniqueId]=i,this._trackingHands[t]=i,this.onHandAddedObservable.notifyObservers(i)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";const i=t.jointMeshes;if(i&&(void 0!==i.disableDefaultHandMesh&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=i.disableDefaultHandMesh),void 0!==i.handMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=i.handMeshes),void 0!==i.leftHandedSystemMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=i.leftHandedSystemMeshes),void 0!==i.rigMapping)){t.handMeshes=t.handMeshes||{};const e={},s={};[[i.rigMapping.left,e],[i.rigMapping.right,s]].forEach((e=>{const t=e[0],i=e[1];t.forEach(((e,t)=>{i[fh[t]]=e}))})),t.handMeshes.customRigMappings={left:e,right:s}}}attach(){return!!super.attach()&&(this._handResources={jointMeshes:vh._GenerateTrackedJointMeshes(this.options),handMeshes:this.options.handMeshes?.customMeshes||null,rigMappings:this.options.handMeshes?.customRigMappings||null},this.options.handMeshes?.customMeshes||this.options.handMeshes?.disableDefaultMeshes||(vh._GenerateDefaultHandMeshesAsync(re.LastCreatedScene,this._xrSessionManager,this.options).then((e=>{this._handResources.handMeshes=e,this._handResources.rigMappings={left:vh._GenerateDefaultHandMeshRigMapping("left"),right:vh._GenerateDefaultHandMeshRigMapping("right")},this._trackingHands.left?.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left,this._xrSessionManager),this._trackingHands.right?.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right,this._xrSessionManager),this._handResources.handMeshes.left.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._handResources.handMeshes.right.scaling.setAll(this._xrSessionManager.worldScalingFactor)})),this._worldScaleObserver=this._xrSessionManager.onWorldScaleFactorChangedObservable.add((e=>{this._handResources.handMeshes&&(this._handResources.handMeshes.left.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor),this._handResources.handMeshes.right.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor))}))),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0)}_onXRFrame(e){this._trackingHands.left?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),this._trackingHands.right?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e,t){const i=this.getHandByControllerId(e);if(i){const s="left"==i.xrController.inputSource.handedness?"left":"right";this._trackingHands[s]?.xrController.uniqueId===e&&(this._trackingHands[s]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(t),delete this._attachedHands[e]}}detach(){return!!super.detach()&&(Object.keys(this._attachedHands).forEach((e=>this._detachHandById(e,this.options.handMeshes?.disposeOnSessionEnd))),this.options.handMeshes?.disposeOnSessionEnd&&this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose()))),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver),!0)}dispose(){super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!this.options.handMeshes?.customMeshes&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),vh._RightHandGLB=null,vh._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose())))}}var xh,bh,Th;vh.Name=qa.HAND_TRACKING,vh.Version=1,vh.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",vh.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",vh.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",vh.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",vh._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},vh._RightHandGLB=null,vh._LeftHandGLB=null,Za.AddWebXRFeature(vh.Name,((e,t)=>()=>new vh(e,t)),vh.Version,!1),function(e){e[e.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",e[e.RADIAL_SIDE=1]="RADIAL_SIDE",e[e.ULNAR_SIDE=2]="ULNAR_SIDE",e[e.BELOW_WRIST=3]="BELOW_WRIST"}(xh||(xh={})),function(e){e[e.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",e[e.HAND_ROTATION=1]="HAND_ROTATION"}(bh||(bh={})),function(e){e[e.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",e[e.PALM_UP=1]="PALM_UP",e[e.GAZE_FOCUS=2]="GAZE_FOCUS",e[e.PALM_AND_GAZE=3]="PALM_AND_GAZE"}(Th||(Th={}));class yh{constructor(){this._sceneRenderObserver=null,this._zoneAxis={},this.handConstraintVisibility=Th.PALM_AND_GAZE,this.palmUpStrictness=.95,this.gazeProximityRadius=.15,this.targetOffset=.1,this.targetZone=xh.ULNAR_SIDE,this.zoneOrientationMode=bh.HAND_ROTATION,this.nodeOrientationMode=bh.HAND_ROTATION,this.handedness="none",this.lerpTime=100,this._zoneAxis[xh.ABOVE_FINGER_TIPS]=new _e(0,1,0),this._zoneAxis[xh.RADIAL_SIDE]=new _e(-1,0,0),this._zoneAxis[xh.ULNAR_SIDE]=new _e(1,0,0),this._zoneAxis[xh.BELOW_WRIST]=new _e(0,-1,0)}get name(){return"HandConstraint"}enable(){this._node.setEnabled(!0)}disable(){this._node.setEnabled(!1)}_getHandPose(){if(!this._handTracking)return null;let e;if(e="none"===this.handedness?this._handTracking.getHandByHandedness("left")||this._handTracking.getHandByHandedness("right"):this._handTracking.getHandByHandedness(this.handedness),e){const t=e.getJointMesh(ph.PINKY_FINGER_METACARPAL),i=e.getJointMesh(ph.MIDDLE_FINGER_METACARPAL),s=e.getJointMesh(ph.WRIST);if(s&&i&&t){const r={position:i.absolutePosition,quaternion:new fe,id:e.xrController.uniqueId},n=ve.Vector3[0],o=ve.Vector3[1],a=ve.Vector3[2];return n.copyFrom(i.absolutePosition).subtractInPlace(s.absolutePosition).normalize(),o.copyFrom(t.absolutePosition).subtractInPlace(i.absolutePosition).normalize(),_e.CrossToRef(n,o,o),_e.CrossToRef(o,n,a),fe.FromLookDirectionLHToRef(o,n,r.quaternion),r}}return null}init(){}attach(e){this._node=e,this._scene=e.getScene(),this._node.rotationQuaternion||(this._node.rotationQuaternion=fe.RotationYawPitchRoll(this._node.rotation.y,this._node.rotation.x,this._node.rotation.z));let t=Date.now();this._sceneRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{const e=this._getHandPose();if(this._node.reservedDataStore=this._node.reservedDataStore||{},this._node.reservedDataStore.nearInteraction=this._node.reservedDataStore.nearInteraction||{},this._node.reservedDataStore.nearInteraction.excludedControllerId=null,e){const i=ve.Vector3[0],s=this._scene.activeCamera;i.copyFrom(this._zoneAxis[this.targetZone]);const r=ve.Quaternion[0];if(s&&(this.zoneOrientationMode===bh.LOOK_AT_CAMERA||this.nodeOrientationMode===bh.LOOK_AT_CAMERA)){const t=ve.Vector3[1];t.copyFrom(s.position).subtractInPlace(e.position).normalize(),this._scene.useRightHandedSystem?fe.FromLookDirectionRHToRef(t,_e.UpReadOnly,r):fe.FromLookDirectionLHToRef(t,_e.UpReadOnly,r)}this.zoneOrientationMode===bh.HAND_ROTATION?e.quaternion.toRotationMatrix(ve.Matrix[0]):r.toRotationMatrix(ve.Matrix[0]),_e.TransformNormalToRef(i,ve.Matrix[0],i),i.scaleInPlace(this.targetOffset);const n=ve.Vector3[2],o=ve.Quaternion[1];n.copyFrom(e.position).addInPlace(i),this.nodeOrientationMode===bh.HAND_ROTATION?o.copyFrom(e.quaternion):o.copyFrom(r);const a=Date.now()-t;_e.SmoothToRef(this._node.position,n,a,this.lerpTime,this._node.position),fe.SmoothToRef(this._node.rotationQuaternion,o,a,this.lerpTime,this._node.rotationQuaternion),this._node.reservedDataStore.nearInteraction.excludedControllerId=e.id}this._setVisibility(e),t=Date.now()}))}_setVisibility(e){let t=!0,i=!0;const s=this._scene.activeCamera;if(s){const r=s.getForwardRay();if(this.handConstraintVisibility===Th.GAZE_FOCUS||this.handConstraintVisibility===Th.PALM_AND_GAZE){let t;i=!1,this._eyeTracking&&(t=this._eyeTracking.getEyeGaze()),t=t||r;const s=ve.Vector3[0];e?e.position.subtractToRef(t.origin,s):this._node.getAbsolutePosition().subtractToRef(t.origin,s);const n=_e.Dot(s,t.direction),o=n*n;n>0&&s.lengthSquared()-o2*this.palmUpStrictness-1&&(t=!0)}}this._node.setEnabled(t&&i)}detach(){this._scene.onBeforeRenderObservable.remove(this._sceneRenderObserver)}linkToXRExperience(e){const t=e.featuresManager?e.featuresManager:e;if(t){try{this._eyeTracking=t.getEnabledFeature(qa.EYE_TRACKING)}catch{}try{this._handTracking=t.getEnabledFeature(qa.HAND_TRACKING)}catch{Ds.Error("Hand tracking must be enabled for the Hand Menu to work")}}else Ds.Error("XR features manager must be available or provided directly for the Hand Menu to work")}}class Sh{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=_e.Zero(),this.poleTargetPosition=_e.Zero(),this.poleTargetLocalOffset=_e.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=fe.Identity(),this._bone1Mat=me.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=_e.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;const s=t.getParent();if(!s)return this._notEnoughInformation=!0,void Ne.Error("BoneIKController: bone must have a parent for IK to work.");if(this._bone1=s,0===this._bone2.children.length&&!this._bone2.length)return this._notEnoughInformation=!0,void Ne.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();const r=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,r.x>r.y&&r.x>r.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){const e=this._bone1.getScale(),t=this._bone2.getScale();this._bone1Length=this._bone1.length*e.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);const t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),s=this._bone1.getAbsolutePosition(e);this._bone2Length=_e.Distance(t,i),this._bone1Length=_e.Distance(i,s)}else{e.computeWorldMatrix(!0);const t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;const i=this._bone2.getAbsolutePosition(e),s=this._bone1.getAbsolutePosition(e);this._bone1Length=_e.Distance(i,s)}this._bone1.getRotationMatrixToRef(Ur.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||null==e)&&(e=Math.PI),this._maxAngle=e;const t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;const e=this.targetPosition,t=this.poleTargetPosition,i=Sh._TmpMats[0],s=Sh._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&_e.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);const r=Sh._TmpVecs[0],n=Sh._TmpVecs[1],o=Sh._TmpVecs[2],a=Sh._TmpVecs[3],l=Sh._TmpVecs[4],h=Sh._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,r),t.subtractToRef(r,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),e.subtractToRef(r,a),a.normalize(),_e.CrossToRef(a,l,n),n.normalize(),_e.CrossToRef(a,n,o),o.normalize(),me.FromXYZAxesToRef(o,a,n,i);const c=this._bone1Length,u=this._bone2Length;let d=_e.Distance(r,e);this._maxReach>0&&(d=Math.min(this._maxReach,d));let _=(u*u+d*d-c*c)/(2*u*d),p=(d*d+c*c-u*u)/(2*d*c);_>1&&(_=1),p>1&&(p=1),_<-1&&(_=-1),p<-1&&(p=-1);const f=Math.acos(_),m=Math.acos(p);let g=-f-m;if(this._rightHandedSystem)me.RotationYawPitchRollToRef(0,0,this._adjustRoll,s),s.multiplyToRef(i,i),me.RotationAxisToRef(this._bendAxis,m,s),s.multiplyToRef(i,i);else{const e=Sh._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,me.RotationAxisToRef(e,-m,s),s.multiplyToRef(i,i)}this.poleAngle&&(me.RotationAxisToRef(a,this.poleAngle,s),i.multiplyToRef(s,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||fe.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),fe.FromRotationMatrixToRef(i,h),fe.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),g=this._bone2Ang*(1-this.slerpAmount)+g*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,Ur.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,Ur.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,g,Ur.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=g}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new fe),e.getRotationQuaternionToRef(Ur.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}Sh._TmpVecs=[_e.Zero(),_e.Zero(),_e.Zero(),_e.Zero(),_e.Zero(),_e.Zero()],Sh._TmpQuat=fe.Identity(),Sh._TmpMats=[me.Identity(),me.Identity()];class Ch{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,s){if(this.upAxis=_e.Up(),this.upAxisSpace=Ur.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=fe.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=_e.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,s){if(s.adjustYaw&&(this.adjustYaw=s.adjustYaw),s.adjustPitch&&(this.adjustPitch=s.adjustPitch),s.adjustRoll&&(this.adjustRoll=s.adjustRoll),null!=s.maxYaw?this.maxYaw=s.maxYaw:this.maxYaw=Math.PI,null!=s.minYaw?this.minYaw=s.minYaw:this.minYaw=-Math.PI,null!=s.maxPitch?this.maxPitch=s.maxPitch:this.maxPitch=Math.PI,null!=s.minPitch?this.minPitch=s.minPitch:this.minPitch=-Math.PI,null!=s.slerpAmount&&(this.slerpAmount=s.slerpAmount),null!=s.upAxis&&(this.upAxis=s.upAxis),null!=s.upAxisSpace&&(this.upAxisSpace=s.upAxisSpace),null!=s.yawAxis||null!=s.pitchAxis){let e=Xr.Y,t=Xr.X;null!=s.yawAxis&&(e=s.yawAxis.clone(),e.normalize()),null!=s.pitchAxis&&(t=s.pitchAxis.clone(),t.normalize());const i=_e.Cross(t,e);this._transformYawPitch=me.Identity(),me.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==s.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=s.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=Ur.BONE||(this.upAxisSpace=Ur.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped)return void(this._firstFrameSkipped=!0);const e=this.bone,t=Ch._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target;const s=Ch._TmpMats[0],r=Ch._TmpMats[1],n=this.mesh,o=e.getParent(),a=Ch._TmpVecs[1];a.copyFrom(this.upAxis),this.upAxisSpace==Ur.BONE&&o?(this._transformYawPitch&&_e.TransformCoordinatesToRef(a,this._transformYawPitchInv,a),o.getDirectionToRef(a,this.mesh,a)):this.upAxisSpace==Ur.LOCAL&&(n.getDirectionToRef(a,a),1==n.scaling.x&&1==n.scaling.y&&1==n.scaling.z||a.normalize());let l=!1,h=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(l=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(h=!0),l||h){const e=Ch._TmpMats[2],s=Ch._TmpMats[3];if(this.upAxisSpace==Ur.BONE&&1==a.y&&o)o.getRotationMatrixToRef(Ur.WORLD,this.mesh,e);else if(this.upAxisSpace!=Ur.LOCAL||1!=a.y||o){let t=Ch._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&_e.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),o?o.getDirectionToRef(t,this.mesh,t):n.getDirectionToRef(t,t);const i=_e.Cross(a,t);i.normalize(),t=_e.Cross(i,a),me.FromXYZAxesToRef(i,a,t,e)}else e.copyFrom(n.getWorldMatrix());e.invertToRef(s);let r=null;if(h){const n=Ch._TmpVecs[3];i.subtractToRef(t,n),_e.TransformCoordinatesToRef(n,s,n),r=Math.sqrt(n.x*n.x+n.z*n.z);const o=Math.atan2(n.y,r);let a=o;o>this._maxPitch?(n.y=this._maxPitchTan*r,a=this._maxPitch):othis._maxYaw||aMath.PI?this._isAngleBetween(o,this._maxYaw,this._midYawConstraint)?(n.z=this._maxYawCos*r,n.x=this._maxYawSin*r,l=this._maxYaw):this._isAngleBetween(o,this._midYawConstraint,this._minYaw)&&(n.z=this._minYawCos*r,n.x=this._minYawSin*r,l=this._minYaw):a>this._maxYaw?(n.z=this._maxYawCos*r,n.x=this._maxYawSin*r,o<0&&this.useAbsoluteValueForYaw&&(n.x*=-1),l=this._maxYaw):aMath.PI){const e=Ch._TmpVecs[8];e.copyFrom(Xr.Z),this._transformYawPitch&&_e.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);const t=Ch._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),_e.TransformCoordinatesToRef(e,t,e),_e.TransformCoordinatesToRef(e,s,e);const i=Math.atan2(e.x,e.z);if(this._getAngleBetween(i,o)>this._getAngleBetween(i,this._midYawConstraint)){null==r&&(r=Math.sqrt(n.x*n.x+n.z*n.z));const e=this._getAngleBetween(i,this._maxYaw);this._getAngleBetween(i,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){let i=0;return i=(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)<(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)?t-e:e-t,i>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e=(e%=2*Math.PI)<0?e+2*Math.PI:e,(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)<(i=(i%=2*Math.PI)<0?i+2*Math.PI:i)){if(e>t&&ei&&e{const e=new Uint8Array(4);return!!((new Uint32Array(e.buffer)[0]=1)&e[0])})();Object.defineProperty(er.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0}),Object.defineProperty(er.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0}),Object.defineProperty(er.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0}),er.prototype._rebuild=function(){this._buffer?._rebuild(),this._alignedBuffer?._rebuild()},er.prototype.dispose=function(){this._ownsBuffer&&this._buffer.dispose(),this._alignedBuffer?.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0},er.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer},er.prototype._alignBuffer=function(){const e=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes||this.byteStride%4==0&&this.byteOffset%4==0||!e)return;const t=er.GetTypeByteLength(this.type),i=this.byteStride+3&-4,s=i/t,r=this._maxVerticesCount,n=r*i/t;let o,a;if(Array.isArray(e)){const t=new Float32Array(e);o=new DataView(t.buffer,t.byteOffset,t.byteLength)}else o=e instanceof ArrayBuffer?new DataView(e,0,e.byteLength):new DataView(e.buffer,e.byteOffset,e.byteLength);a=this.type===er.BYTE?new Int8Array(n):this.type===er.UNSIGNED_BYTE?new Uint8Array(n):this.type===er.SHORT?new Int16Array(n):this.type===er.UNSIGNED_SHORT?new Uint16Array(n):this.type===er.INT?new Int32Array(n):this.type===er.UNSIGNED_INT?new Uint32Array(n):new Float32Array(n);const l=this.getSize();let h=this.byteOffset;for(let e=0;e{if(t.type!==lr.POINTERWHEEL)return;const i=t.event,s=i.deltaMode===Sr.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*s*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*s*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*s*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,lr.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}Ze([rt()],Ph.prototype,"wheelPrecisionX",void 0),Ze([rt()],Ph.prototype,"wheelPrecisionY",void 0),Ze([rt()],Ph.prototype,"wheelPrecisionZ",void 0);class Ih{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let s=0,r=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=n=>{const o=n.event,a="touch"===o.pointerType;if(n.type!==lr.POINTERMOVE&&-1===this.buttons.indexOf(o.button))return;const l=o.target;if(this._altKey=o.altKey,this._ctrlKey=o.ctrlKey,this._metaKey=o.metaKey,this._shiftKey=o.shiftKey,this._buttonsPressed=o.buttons,t.isPointerLock){const e=o.movementX,t=o.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(n.type!==lr.POINTERDOWN&&n.type!==lr.POINTERDOUBLETAP&&a&&this._pointA?.pointerId!==o.pointerId&&this._pointB?.pointerId!==o.pointerId)return;if(n.type!==lr.POINTERDOWN||-1!==this._currentActiveButton&&!a)if(n.type===lr.POINTERDOUBLETAP)this.onDoubleTap(o.pointerType);else if(n.type!==lr.POINTERUP||this._currentActiveButton!==o.button&&!a){if(n.type===lr.POINTERMOVE)if(e||o.preventDefault(),this._pointA&&null===this._pointB){const e=o.clientX-this._pointA.x,t=o.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=o.clientX,this._pointA.y=o.clientY}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===o.pointerId?this._pointA:this._pointB;e.x=o.clientX,e.y=o.clientY;const t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,a=t*t+i*i,l={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:o.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,s,a,r,l),r=l,s=a}}else{try{l?.releasePointerCapture(o.pointerId)}catch(e){}a||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==o.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==o.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==s||r)&&(this.onMultiTouch(this._pointA,this._pointB,s,0,r,null),s=0,r=null),this._currentActiveButton=-1,this.onButtonUp(o),e||o.preventDefault()}else{try{l?.setPointerCapture(o.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType};else{if(null!==this._pointB)return;this._pointB={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType}}-1!==this._currentActiveButton||a||(this._currentActiveButton=o.button),this.onButtonDown(o),e||(o.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,lr.POINTERDOWN|lr.POINTERUP|lr.POINTERMOVE|lr.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,r=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&Ds.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Ds.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,s,r,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}Ze([rt()],Ih.prototype,"buttons",void 0);var Rh,Mh,Oh,Dh,wh,Nh,Fh={};class Lh{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();this.attached[t]?Ne.Warn("camera input of type "+t+" already exists on camera"):(this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault))}remove(e){for(const t in this.attached){const i=this.attached[t];if(i===e)return i.detachControl(),i.camera=null,delete this.attached[t],void this.rebuildInputCheck()}}removeByType(e){for(const t in this.attached){const i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){const t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=!In.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e;for(const t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(const t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(const e in this.attached){const t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){const t={};for(const e in this.attached){const i=this.attached[e],s=St.Serialize(i);t[i.getClassName()]=s}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=Fh[e];if(i){const s=t[e],r=St.Parse((()=>new i),s,null);this.add(r)}}}else for(const t in this.attached){const i=Fh[this.attached[t].getClassName()];if(i){const s=St.Parse((()=>new i),e,null);this.remove(this.attached[t]),this.add(s)}}}}class Bh{constructor(e,t){this.x=e,this.y=t}}class kh{get isConnected(){return this._isConnected}constructor(e,t,i,s=0,r=1,n=2,o=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=kh.GAMEPAD,this._leftStickAxisX=s,this._leftStickAxisY=r,this._rightStickAxisX=n,this._rightStickAxisY=o,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}}kh.GAMEPAD=0,kh.GENERIC=1,kh.XBOX=2,kh.POSE_ENABLED=3,kh.DUALSHOCK=4;class Vh extends kh{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new K,this.onButtonUpObservable=new K,this.type=kh.GENERIC,this._buttons=new Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{e.type!==kh.POSE_ENABLED&&(this.gamepad&&e.type!==kh.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(kh.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){const e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){const i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){const i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}const i=this.gamepad.leftStick;if(i&&0!=i.y){const e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}Ze([rt()],Uh.prototype,"gamepadRotationSensibility",void 0),Ze([rt()],Uh.prototype,"gamepadMoveSensibility",void 0),Fh.ArcRotateCameraGamepadInput=Uh;class Gh{constructor(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===dr.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t0?s/(1+this.wheelDeltaPercentage):s*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==lr.POINTERWHEEL)return;const i=t.event;let s=0;const r=i.deltaMode===Sr.DOM_DELTA_LINE?40:1,n=-i.deltaY*r;if(this.customComputeDeltaFromMouseWheel)s=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if(s=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius),s>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+s;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=be.Clamp(e,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else s=n/(40*this.wheelPrecision);s&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(s)):this.camera.inertialRadiusOffset+=s),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,lr.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}checkInputs(){if(!this.zoomToMouseLocation)return;const e=this.camera;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){const e=this.camera,t=e.target.subtract(e.position);this._hitPlane=Nr.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,me.Identity(),e,!1);0===e.targetScreenOffset.x&&0===e.targetScreenOffset.y||(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=_e.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(s))}_zoomToMouse(e){const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const s=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/is&&(e=(t.radius-s)*i-t.inertialRadiusOffset)}const s=e/i/t.radius,r=this._getPosition(),n=ve.Vector3[6];r.subtractToRef(t.target,n),n.scaleInPlace(s),n.scaleInPlace(i),this._inertialPanning.addInPlace(n),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,s),this._isPinching=!0):this._computeMultiTouchPanning(r,n)):this.multiTouchPanning?this._computeMultiTouchPanning(r,n):this.pinchZoom&&this._computePinchZoom(i,s))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}Wh.MinimumRadiusForPinch=.001,Ze([rt()],Wh.prototype,"buttons",void 0),Ze([rt()],Wh.prototype,"angularSensibilityX",void 0),Ze([rt()],Wh.prototype,"angularSensibilityY",void 0),Ze([rt()],Wh.prototype,"pinchPrecision",void 0),Ze([rt()],Wh.prototype,"pinchDeltaPercentage",void 0),Ze([rt()],Wh.prototype,"useNaturalPinchZoom",void 0),Ze([rt()],Wh.prototype,"pinchZoom",void 0),Ze([rt()],Wh.prototype,"panningSensibility",void 0),Ze([rt()],Wh.prototype,"multiTouchPanning",void 0),Ze([rt()],Wh.prototype,"multiTouchPanAndZoom",void 0),Fh.ArcRotateCameraPointersInput=Wh;class Hh extends Lh{constructor(e){super(e)}addMouseWheel(){return this.add(new zh),this}addPointers(){return this.add(new Wh),this}addKeyboard(){return this.add(new Gh),this}}Hh.prototype.addVRDeviceOrientation=function(){return this.add(new Xh),this};class Xh{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=e=>this._onOrientationEvent(e)}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);const t=this.camera.getScene().getEngine().getHostWindow();t&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t.addEventListener("deviceorientation",this._deviceOrientationHandler):Ds.Warn("Permission not granted.")})).catch((e=>{Ds.Error(e)})):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*this.gammaCorrection),this._dirty=!0}checkInputs(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)}detachControl(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)}getClassName(){return"ArcRotateCameraVRDeviceOrientationInput"}getSimpleName(){return"VRDeviceOrientation"}}Fh.ArcRotateCameraVRDeviceOrientationInput=Xh;class Yh{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=new Array}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(t.type===dr.KEYDOWN)-1===this.keysForward.indexOf(i.keyCode)&&-1===this.keysBackward.indexOf(i.keyCode)&&-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{this._pointerInput(e)}),lr.POINTERDOWN|lr.POINTERUP|lr.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add((()=>{this.camera.rollCorrect&&this.camera.restoreRoll(this.camera.rollCorrect)}))}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)}getClassName(){return"FlyCameraMouseInput"}getSimpleName(){return"mouse"}_pointerInput(e){const t=e.event,i=this.camera.getEngine();if(!this.touchEnabled&&"touch"===t.pointerType)return;if(e.type!==lr.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;const s=t.target;if(e.type===lr.POINTERDOWN){try{s?.setPointerCapture(t.pointerId)}catch(t){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),i.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===lr.POINTERUP){try{s?.releasePointerCapture(t.pointerId)}catch(t){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===lr.POINTERMOVE){if(!this._previousPosition)return void(i.isPointerLock&&this._onMouseMove(e.event));const s=t.clientX-this._previousPosition.x,r=t.clientY-this._previousPosition.y;this._rotateCamera(s,r),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){if(!this.camera.getEngine().isPointerLock)return;const t=e.movementX,i=e.movementY;this._rotateCamera(t,i),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera,s=(e*=i._calculateHandednessMultiplier())/this.angularSensibility,r=t/this.angularSensibility,n=fe.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let o;if(this.buttonsPitch.some((e=>e===this.activeButton))&&(o=fe.RotationAxis(Xr.X,r),n.multiplyInPlace(o)),this.buttonsYaw.some((e=>e===this.activeButton))){o=fe.RotationAxis(Xr.Y,s),n.multiplyInPlace(o);const e=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-ee===this.activeButton))&&(o=fe.RotationAxis(Xr.Z,-s),i._trackRoll-=s,n.multiplyInPlace(o)),n.toEulerAnglesToRef(i.rotation)}}Ze([rt()],Qh.prototype,"buttons",void 0),Ze([rt()],Qh.prototype,"angularSensibility",void 0),Fh.FlyCameraMouseInput=Qh;class jh{constructor(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=new Array}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===dr.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){this._onKeyboardObserver&&this._keys.forEach((e=>{-1!==this.keysHeightOffsetIncr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:-1!==this.keysHeightOffsetDecr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:-1!==this.keysRotationOffsetIncr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRotationOffsetDecr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRadiusIncr.indexOf(e)&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:-1!==this.keysRadiusDecr.indexOf(e)&&this._modifierRadius()&&(this.camera.radius-=this.radiusSensibility)}))}getClassName(){return"FollowCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}_modifierHeightOffset(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed}_modifierRotationOffset(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed}_modifierRadius(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed}}Ze([rt()],jh.prototype,"keysHeightOffsetIncr",void 0),Ze([rt()],jh.prototype,"keysHeightOffsetDecr",void 0),Ze([rt()],jh.prototype,"keysHeightOffsetModifierAlt",void 0),Ze([rt()],jh.prototype,"keysHeightOffsetModifierCtrl",void 0),Ze([rt()],jh.prototype,"keysHeightOffsetModifierShift",void 0),Ze([rt()],jh.prototype,"keysRotationOffsetIncr",void 0),Ze([rt()],jh.prototype,"keysRotationOffsetDecr",void 0),Ze([rt()],jh.prototype,"keysRotationOffsetModifierAlt",void 0),Ze([rt()],jh.prototype,"keysRotationOffsetModifierCtrl",void 0),Ze([rt()],jh.prototype,"keysRotationOffsetModifierShift",void 0),Ze([rt()],jh.prototype,"keysRadiusIncr",void 0),Ze([rt()],jh.prototype,"keysRadiusDecr",void 0),Ze([rt()],jh.prototype,"keysRadiusModifierAlt",void 0),Ze([rt()],jh.prototype,"keysRadiusModifierCtrl",void 0),Ze([rt()],jh.prototype,"keysRadiusModifierShift",void 0),Ze([rt()],jh.prototype,"heightSensibility",void 0),Ze([rt()],jh.prototype,"rotationSensibility",void 0),Ze([rt()],jh.prototype,"radiusSensibility",void 0),Fh.FollowCameraKeyboardMoveInput=jh;class Kh{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==lr.POINTERWHEEL)return;const i=t.event;let s=0;const r=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(+this.axisControlRadius+ +this.axisControlHeight+ +this.axisControlRotation&&Ne.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?s=.01*r*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?s=.01*r*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(s=.01*r*this.wheelDeltaPercentage*this.camera.rotationOffset)):s=r*this.wheelPrecision,s&&(this.axisControlRadius?this.camera.radius+=s:this.axisControlHeight?this.camera.heightOffset-=s:this.axisControlRotation&&(this.camera.rotationOffset-=s)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,lr.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}Ze([rt()],Kh.prototype,"axisControlRadius",void 0),Ze([rt()],Kh.prototype,"axisControlHeight",void 0),Ze([rt()],Kh.prototype,"axisControlRotation",void 0),Ze([rt()],Kh.prototype,"wheelPrecision",void 0),Ze([rt()],Kh.prototype,"wheelDeltaPercentage",void 0),Fh.FollowCameraMouseWheelInput=Kh;class $h extends Ih{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,s,r,n){if(0===i&&null===r)return;if(0===s&&null===n)return;let o=(s-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(o*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=o*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=o*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=o*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=o),this.axisPinchControlHeight&&(this.camera.heightOffset+=o),this.axisPinchControlRadius&&(this.camera.radius-=o))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;const e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";+this.axisXControlRotation+ +this.axisXControlHeight+ +this.axisXControlRadius<=1&&Ne.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&Ne.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&Ne.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}Ze([rt()],$h.prototype,"angularSensibilityX",void 0),Ze([rt()],$h.prototype,"angularSensibilityY",void 0),Ze([rt()],$h.prototype,"pinchPrecision",void 0),Ze([rt()],$h.prototype,"pinchDeltaPercentage",void 0),Ze([rt()],$h.prototype,"axisXControlRadius",void 0),Ze([rt()],$h.prototype,"axisXControlHeight",void 0),Ze([rt()],$h.prototype,"axisXControlRotation",void 0),Ze([rt()],$h.prototype,"axisYControlRadius",void 0),Ze([rt()],$h.prototype,"axisYControlHeight",void 0),Ze([rt()],$h.prototype,"axisYControlRotation",void 0),Ze([rt()],$h.prototype,"axisPinchControlRadius",void 0),Ze([rt()],$h.prototype,"axisPinchControlHeight",void 0),Ze([rt()],$h.prototype,"axisPinchControlRotation",void 0),Fh.FollowCameraPointersInput=$h;class qh{constructor(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===dr.KEYDOWN)-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)&&-1===this.keysUpward.indexOf(i.keyCode)&&-1===this.keysDownward.indexOf(i.keyCode)&&-1===this.keysRotateLeft.indexOf(i.keyCode)&&-1===this.keysRotateRight.indexOf(i.keyCode)&&-1===this.keysRotateUp.indexOf(i.keyCode)&&-1===this.keysRotateDown.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysUpward.indexOf(i.keyCode)||-1!==this.keysDownward.indexOf(i.keyCode)||-1!==this.keysRotateLeft.indexOf(i.keyCode)||-1!==this.keysRotateRight.indexOf(i.keyCode)||-1!==this.keysRotateUp.indexOf(i.keyCode)||-1!==this.keysRotateDown.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{const r=s.event,n="touch"===r.pointerType;if(!this.touchEnabled&&n)return;if(s.type!==lr.POINTERMOVE&&-1===this.buttons.indexOf(r.button))return;const o=r.target;if(s.type===lr.POINTERDOWN){if(n&&-1!==this._activePointerId||!n&&-1!==this._currentActiveButton)return;this._activePointerId=r.pointerId;try{o?.setPointerCapture(r.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=r.button),this._previousPosition={x:r.clientX,y:r.clientY},e||(r.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(s.event)}else if(s.type===lr.POINTERUP){if(n&&this._activePointerId!==r.pointerId||!n&&this._currentActiveButton!==r.button)return;try{o?.releasePointerCapture(r.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||r.preventDefault(),this._activePointerId=-1}else if(s.type===lr.POINTERMOVE&&(this._activePointerId===r.pointerId||!n))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(s.event);else if(this._previousPosition){const t=this.camera._calculateHandednessMultiplier(),i=(r.clientX-this._previousPosition.x)*t,s=r.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=s/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:s}),this._previousPosition={x:r.clientX,y:r.clientY},e||r.preventDefault()}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;const s=this.camera._calculateHandednessMultiplier(),r=i.movementX*s;this.camera.cameraRotation.y+=r/this.angularSensibility;const n=i.movementY;this.camera.cameraRotation.x+=n/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,lr.POINTERDOWN|lr.POINTERUP|lr.POINTERMOVE),i&&(this._contextMenuBind=e=>this.onContextMenu(e),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}Ze([rt()],Zh.prototype,"buttons",void 0),Ze([rt()],Zh.prototype,"angularSensibility",void 0),Fh.FreeCameraMouseInput=Zh,function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(Rh||(Rh={}));class Jh extends Ph{constructor(){super(...arguments),this._moveRelative=_e.Zero(),this._rotateRelative=_e.Zero(),this._moveScene=_e.Zero(),this._wheelXAction=Rh.MoveRelative,this._wheelXActionCoordinate=Gr.X,this._wheelYAction=Rh.MoveRelative,this._wheelYActionCoordinate=Gr.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){null===e&&this._wheelXAction!==Rh.MoveRelative||(this._wheelXAction=Rh.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Rh.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){null===e&&this._wheelYAction!==Rh.MoveRelative||(this._wheelYAction=Rh.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Rh.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){null===e&&this._wheelZAction!==Rh.MoveRelative||(this._wheelZAction=Rh.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Rh.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){null===e&&this._wheelXAction!==Rh.RotateRelative||(this._wheelXAction=Rh.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Rh.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){null===e&&this._wheelYAction!==Rh.RotateRelative||(this._wheelYAction=Rh.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Rh.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){null===e&&this._wheelZAction!==Rh.RotateRelative||(this._wheelZAction=Rh.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Rh.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){null===e&&this._wheelXAction!==Rh.MoveScene||(this._wheelXAction=Rh.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Rh.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){null===e&&this._wheelYAction!==Rh.MoveScene||(this._wheelYAction=Rh.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Rh.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){null===e&&this._wheelZAction!==Rh.MoveScene||(this._wheelZAction=Rh.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Rh.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(0===this._wheelDeltaX&&0===this._wheelDeltaY&&0==this._wheelDeltaZ)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);const e=me.Zero();this.camera.getViewMatrix().invertToRef(e);const t=_e.Zero();_e.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,i){if(0===e)return;if(null===t||null===i)return;let s=null;switch(t){case Rh.MoveRelative:s=this._moveRelative;break;case Rh.RotateRelative:s=this._rotateRelative;break;case Rh.MoveScene:s=this._moveScene}switch(i){case Gr.X:s.set(e,0,0);break;case Gr.Y:s.set(0,e,0);break;case Gr.Z:s.set(0,0,e)}}}Ze([rt()],Jh.prototype,"wheelXMoveRelative",null),Ze([rt()],Jh.prototype,"wheelYMoveRelative",null),Ze([rt()],Jh.prototype,"wheelZMoveRelative",null),Ze([rt()],Jh.prototype,"wheelXRotateRelative",null),Ze([rt()],Jh.prototype,"wheelYRotateRelative",null),Ze([rt()],Jh.prototype,"wheelZRotateRelative",null),Ze([rt()],Jh.prototype,"wheelXMoveScene",null),Ze([rt()],Jh.prototype,"wheelYMoveScene",null),Ze([rt()],Jh.prototype,"wheelZMoveScene",null),Fh.FreeCameraMouseWheelInput=Jh;class ec{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=Ds.IsSafari()}attachControl(e){e=Ds.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const s=i.event,r="mouse"===s.pointerType||this._isSafari&&void 0===s.pointerType;if(this.allowMouse||!r)if(i.type===lr.POINTERDOWN){if(e||s.preventDefault(),this._pointerPressed.push(s.pointerId),1!==this._pointerPressed.length)return;t={x:s.clientX,y:s.clientY}}else if(i.type===lr.POINTERUP){e||s.preventDefault();const i=this._pointerPressed.indexOf(s.pointerId);if(-1===i)return;if(this._pointerPressed.splice(i,1),0!=i)return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===lr.POINTERMOVE){if(e||s.preventDefault(),!t)return;if(0!=this._pointerPressed.indexOf(s.pointerId))return;this._offsetX=s.clientX-t.x,this._offsetY=-(s.clientY-t.y)}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,lr.POINTERDOWN|lr.POINTERUP|lr.POINTERMOVE),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(null===this._offsetX||null===this._offsetY)return;if(0===this._offsetX&&0===this._offsetY)return;const e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility,this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{const t=e._computeLocalCameraSpeed(),i=new _e(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);me.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(_e.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}Ze([rt()],ec.prototype,"touchAngularSensibility",void 0),Ze([rt()],ec.prototype,"touchMoveSensibility",void 0),Fh.FreeCameraTouchInput=ec;class tc extends Lh{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new qh),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new Zh(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new Jh,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new ec),this}clear(){super.clear(),this._mouseInput=null}}tc.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new ic,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};class ic{static WaitForOrientationChangeAsync(e){return new Promise(((t,i)=>{let s=!1;const r=()=>{window.removeEventListener("deviceorientation",r),s=!0,t()};e&&setTimeout((()=>{s||(window.removeEventListener("deviceorientation",r),i("WaitForOrientationChangeAsync timed out"))}),e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"==e?window.addEventListener("deviceorientation",r):Ds.Warn("Permission not granted.")})).catch((e=>{Ds.Error(e)})):window.addEventListener("deviceorientation",r)}))}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new fe,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new K,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-Ds.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?Ds.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?Ds.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?Ds.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new fe(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new fe),this._camera&&this._camera.onDisposeObservable.add((()=>{this._onDeviceOrientationChangedObservable.clear()}))}attachControl(){const e=this.camera.getScene().getEngine().getHostWindow();if(e){const t=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t():Ds.Warn("Permission not granted.")})).catch((e=>{Ds.Error(e)})):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(fe.RotationYawPitchRollToRef(Ds.ToRadians(this._alpha),Ds.ToRadians(this._beta),-Ds.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}Fh.FreeCameraDeviceOrientationInput=ic;class sc{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=me.Identity(),this._deltaTransform=_e.Zero(),this._vector3=_e.Zero(),this._vector2=de.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{e.type!==kh.POSE_ENABLED&&(this.gamepad&&e.type!==kh.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(kh.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){const e=this.camera,t=this.gamepad.leftStick;0!==this.gamepadMoveSensibility&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&0!==this.gamepadAngularSensibility?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):me.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const s=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*s,0,-t.y*s),_e.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}}Ze([rt()],sc.prototype,"gamepadAngularSensibility",void 0),Ze([rt()],sc.prototype,"gamepadMoveSensibility",void 0),Fh.FreeCameraGamepadInput=sc,function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Mh||(Mh={}));class rc{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;const i={...rc._GetDefaultOptions(),...t};if(this._leftJoystick=!!e,rc._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=Mh.X,this._axisTargetedByUpAndDown=Mh.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new Bs,this.deltaPosition=_e.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{rc._VJCanvasWidth=window.innerWidth,rc._VJCanvasHeight=window.innerHeight,rc.Canvas&&(rc.Canvas.width=rc._VJCanvasWidth,rc.Canvas.height=rc._VJCanvasHeight),rc._HalfWidth=rc._VJCanvasWidth/2},!rc.Canvas){window.addEventListener("resize",this._onResize,!1),rc.Canvas=document.createElement("canvas"),rc._VJCanvasWidth=window.innerWidth,rc._VJCanvasHeight=window.innerHeight,rc.Canvas.width=window.innerWidth,rc.Canvas.height=window.innerHeight,rc.Canvas.style.width="100%",rc.Canvas.style.height="100%",rc.Canvas.style.position="absolute",rc.Canvas.style.backgroundColor="transparent",rc.Canvas.style.top="0px",rc.Canvas.style.left="0px",rc.Canvas.style.zIndex="5",rc.Canvas.style.touchAction="none",rc.Canvas.setAttribute("touch-action","none");const e=rc.Canvas.getContext("2d");if(!e)throw new Error("Unable to create canvas for virtual joystick");rc._VJCanvasContext=e,rc._VJCanvasContext.strokeStyle="#ffffff",rc._VJCanvasContext.lineWidth=2,document.body.appendChild(rc.Canvas)}rc._HalfWidth=rc.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&rc._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new de(0,0),this._joystickPreviousPointerPos=new de(0,0),this._joystickPointerStartPos=new de(0,0),this._deltaJoystickVector=new de(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},rc.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),rc.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),rc.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),rc.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),rc.Canvas.addEventListener("contextmenu",(e=>{e.preventDefault()}),!1),requestAnimationFrame((()=>{this._drawVirtualJoystick()}))}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){let t;e.preventDefault(),t=!0===this._leftJoystick?e.clientXrc._HalfWidth,t&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):rc._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){const t=new de(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0this._containerImage=t}setPuckImage(e){const t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){const e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?rc._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(rc._VJCanvasContext.beginPath(),rc._VJCanvasContext.strokeStyle=this._joystickColor,rc._VJCanvasContext.lineWidth=2,rc._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),rc._VJCanvasContext.stroke(),rc._VJCanvasContext.closePath(),rc._VJCanvasContext.beginPath(),rc._VJCanvasContext.lineWidth=6,rc._VJCanvasContext.strokeStyle=this._joystickColor,rc._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),rc._VJCanvasContext.stroke(),rc._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?rc._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(rc._VJCanvasContext.beginPath(),rc._VJCanvasContext.strokeStyle=this._joystickColor,rc._VJCanvasContext.lineWidth=2,rc._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),rc._VJCanvasContext.stroke(),rc._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach(((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(rc._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),rc._VJCanvasContext.beginPath(),rc._VJCanvasContext.fillStyle="white",rc._VJCanvasContext.beginPath(),rc._VJCanvasContext.strokeStyle="red",rc._VJCanvasContext.lineWidth=6,rc._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),rc._VJCanvasContext.stroke(),rc._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)})),requestAnimationFrame((()=>{this._drawVirtualJoystick()})))}releaseCanvas(){rc.Canvas&&(rc.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),rc.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),rc.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),rc.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(rc.Canvas),rc.Canvas=null),this._released=!0}}rc._GlobalJoystickIndex=0,rc._AlwaysVisibleSticks=0,tc.prototype.addVirtualJoystick=function(){return this.add(new nc),this};class nc{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=50*e._computeLocalCameraSpeed(),i=me.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),s=_e.TransformCoordinates(new _e(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(s),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new rc(!0),this._leftjoystick.setAxisForUpDown(Mh.Z),this._leftjoystick.setAxisForLeftRight(Mh.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new rc(!1),this._rightjoystick.setAxisForUpDown(Mh.X),this._rightjoystick.setAxisForLeftRight(Mh.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}}Fh.FreeCameraVirtualJoystickInput=nc,Et.AddNodeConstructor("TargetCamera",((e,t)=>()=>new oc(e,_e.Zero(),t)));class oc extends In{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=_e.Zero(),this._tmpTargetVector=_e.Zero(),this.cameraDirection=new _e(0,0,0),this.cameraRotation=new de(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new fe,this.rotation=new _e(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=_e.Zero(),this._initialFocalDistance=1,this._viewMatrix=me.Zero(),this._camMatrix=me.Zero(),this._cameraTransformMatrix=me.Zero(),this._cameraRotationMatrix=me.Zero(),this._referencePoint=new _e(0,0,1),this._transformedReferencePoint=_e.Zero(),this._deferredPositionUpdate=new _e,this._deferredRotationQuaternionUpdate=new fe,this._deferredRotationUpdate=new _e,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=_e.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();const t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){const e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)}_initCache(){super._initCache(),this._cache.lockedTarget=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new fe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();const t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;const e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){const e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=J),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),me.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);const t=e.subtract(this.position);t.x>=0?this.rotation.y=-Math.atan(t.z/t.x)+Math.PI/2:this.rotation.y=-Math.atan(t.z/t.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&fe.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(ve.Matrix[0]),_e.TransformNormalToRef(this.cameraDirection,ve.Matrix[0],ve.Vector3[0]),this._deferredPositionUpdate.addInPlace(ve.Vector3[0]),void(this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate));this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint){const e=1.570796;this._deferredRotationUpdate.x>e&&(this._deferredRotationUpdate.x=e),this._deferredRotationUpdate.x<-e&&(this._deferredRotationUpdate.x=-e)}this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(fe.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))}t&&(Math.abs(this.cameraDirection.x){this._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>oo.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new tc(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ds.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new _e(0,0,0),this.cameraRotation=new de(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?_e.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=_e.Zero(),this._transformedDirection=_e.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}}Ze([ht()],ac.prototype,"ellipsoid",void 0),Ze([ht()],ac.prototype,"ellipsoidOffset",void 0),Ze([rt()],ac.prototype,"checkCollisions",void 0),Ze([rt()],ac.prototype,"applyGravity",void 0),z("BABYLON.FreeCamera",ac),Et.AddNodeConstructor("TouchCamera",((e,t)=>()=>new lc(e,_e.Zero(),t)));class lc extends ac{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!e:e.allowMouse=!t}}Et.AddNodeConstructor("ArcRotateCamera",((e,t)=>()=>new hc(e,0,0,1,_e.Zero(),t)));class hc extends oc{get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new me,this._upToYMatrix=new me,this._upVector=_e.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){me.RotationAlignToRef(_e.UpReadOnly,this._upVector,this._yToUpMatrix),me.RotationAlignToRef(this._upVector,_e.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){const e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){const t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){const e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){const t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){const e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){const t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){const e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){const t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){const e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){const e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){const t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){const e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return null!=this._bouncingBehavior}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Fa,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return null!=this._framingBehavior}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new La,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return null!=this._autoRotationBehavior}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new Na,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,r,n,o=!0){super(e,_e.Zero(),n,o),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=_e.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=de.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new me,this.panningAxis=new _e(1,1,0),this._transformedDirection=new _e,this.mapPanning=!1,this.onMeshTargetChangedObservable=new K,this.checkCollisions=!1,this.collisionRadius=new _e(.5,.5,.5),this._previousPosition=_e.Zero(),this._collisionVelocity=_e.Zero(),this._newPosition=_e.Zero(),this._computationVector=_e.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);const s=Math.cos(this.alpha),r=Math.sin(this.alpha),n=Math.cos(this.beta);let o=Math.sin(this.beta);0===o&&(o=1e-4);const a=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*s*o,this.radius*n,this.radius*r*o),a.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=l.clone(),l=l.negate()),this._computeViewMatrix(this._position,a,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=_e.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new Hh(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=de.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){const e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}return this._getLockedTargetPosition()||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)}_isSynchronizedViewMatrix(){return!!super._isSynchronizedViewMatrix()&&this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset)}attachControl(e,t,i=!0,s=2){const r=arguments;t=Ds.BackCompatCameraNoPreventDefault(r),this._useCtrlForPanning=i,this._panningMouseButton=s,"boolean"==typeof r[0]&&(r.length>1&&(this._useCtrlForPanning=r[1]),r.length>2&&(this._panningMouseButton=r[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){const e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier();let i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||_e.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);const e=this.alpha;0===this._computationVector.x&&0===this._computationVector.z?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,s=!1){if(s=this.overrideCloneAlphaBetaRadius??s,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const t=e,s=this._getTargetPosition();if(s&&!i&&s.equals(t))return;this._targetHost=null,this._target=t,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}s||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let s=Math.sin(this.beta);0===s&&(s=1e-4),0===this.radius&&(this.radius=1e-4);const r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*s,this.radius*i,this.radius*t*s),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||_e.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),r.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&s<0&&(e=e.negate()),this._computeViewMatrix(this._position,r,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=ha.MinMax(e);let s=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);s=Math.max(Math.min(s,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=s*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:s},t)}focusOn(e,t=!1){let i,s;if(void 0===e.min){const t=e||this.getScene().meshes;i=ha.MinMax(t),s=_e.Distance(i.min,i.max)}else i=e,s=e.distance;this._target=ha.Center(i),t||(this.maxZ=2*s)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case In.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case In.RIG_MODE_STEREOSCOPIC_OVERUNDER:case In.RIG_MODE_STEREOSCOPIC_INTERLACED:case In.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const s=new hc(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return s._cameraRigParams={},s.isRigCamera=!0,s.rigParent=this,s.upVector=this.upVector,s.mode=this.mode,s.orthoLeft=this.orthoLeft,s.orthoRight=this.orthoRight,s.orthoBottom=this.orthoBottom,s.orthoTop=this.orthoTop,s}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case In.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case In.RIG_MODE_STEREOSCOPIC_OVERUNDER:case In.RIG_MODE_STEREOSCOPIC_INTERLACED:case In.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const s=_e.Distance(e,t),r=this.getScene().getEngine().getAspectRatio(this),n=Math.tan(this.fov/2),o=n*r,a=.5*s*i,l=a*Math.sqrt(1+1/(o*o)),h=a*Math.sqrt(1+1/(n*n));return Math.max(l,h)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}Ze([rt()],hc.prototype,"alpha",void 0),Ze([rt()],hc.prototype,"beta",void 0),Ze([rt()],hc.prototype,"radius",void 0),Ze([rt()],hc.prototype,"overrideCloneAlphaBetaRadius",void 0),Ze([ht("target")],hc.prototype,"_target",void 0),Ze([ct("targetHost")],hc.prototype,"_targetHost",void 0),Ze([rt()],hc.prototype,"inertialAlphaOffset",void 0),Ze([rt()],hc.prototype,"inertialBetaOffset",void 0),Ze([rt()],hc.prototype,"inertialRadiusOffset",void 0),Ze([rt()],hc.prototype,"lowerAlphaLimit",void 0),Ze([rt()],hc.prototype,"upperAlphaLimit",void 0),Ze([rt()],hc.prototype,"lowerBetaLimit",void 0),Ze([rt()],hc.prototype,"upperBetaLimit",void 0),Ze([rt()],hc.prototype,"lowerRadiusLimit",void 0),Ze([rt()],hc.prototype,"upperRadiusLimit",void 0),Ze([rt()],hc.prototype,"inertialPanningX",void 0),Ze([rt()],hc.prototype,"inertialPanningY",void 0),Ze([rt()],hc.prototype,"pinchToPanMaxDistance",void 0),Ze([rt()],hc.prototype,"panningDistanceLimit",void 0),Ze([ht()],hc.prototype,"panningOriginTarget",void 0),Ze([rt()],hc.prototype,"panningInertia",void 0),Ze([rt()],hc.prototype,"zoomToMouseLocation",null),Ze([rt()],hc.prototype,"zoomOnFactor",void 0),Ze([lt()],hc.prototype,"targetScreenOffset",void 0),Ze([rt()],hc.prototype,"allowUpsideDown",void 0),Ze([rt()],hc.prototype,"useInputToRestoreState",void 0),z("BABYLON.ArcRotateCamera",hc),Et.AddNodeConstructor("DeviceOrientationCamera",((e,t)=>()=>new cc(e,_e.Zero(),t)));class cc extends ac{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new fe,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new fe,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce((()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add((e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new fe),fe.FromEulerAnglesToRef(0,e.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))})))}))}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=Xr.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new fe),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}}class uc extends Lh{constructor(e){super(e)}addKeyboard(){return this.add(new Yh),this}addMouse(){return this.add(new Qh),this}}class dc extends oc{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){const e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){const t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){const e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){const t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,s=!0){super(e,t,i,s),this.ellipsoid=new _e(1,1,1),this.ellipsoidOffset=new _e(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=_e.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=_e.Zero(),this._diffPosition=_e.Zero(),this._newPosition=_e.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>oo.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new uc(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ds.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new _e(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?_e.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=_e.Zero(),this._transformedDirection=_e.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}restoreRoll(e){const t=this._trackRoll,i=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,Math.abs(t-this.rotation.z)<=.001&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}Ze([ht()],dc.prototype,"ellipsoid",void 0),Ze([ht()],dc.prototype,"ellipsoidOffset",void 0),Ze([rt()],dc.prototype,"checkCollisions",void 0),Ze([rt()],dc.prototype,"applyGravity",void 0),z("BABYLON.FlyCamera",dc);class _c extends Lh{constructor(e){super(e)}addKeyboard(){return this.add(new jh),this}addMouseWheel(){return this.add(new Kh),this}addPointers(){return this.add(new $h),this}addVRDeviceOrientation(){return Ne.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}Et.AddNodeConstructor("FollowCamera",((e,t)=>()=>new pc(e,_e.Zero(),t))),Et.AddNodeConstructor("ArcFollowCamera",((e,t)=>()=>new fc(e,0,0,1,null,t)));class pc extends oc{constructor(e,t,i,s=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=s,this.inputs=new _c(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=ve.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),s=Ds.ToRadians(this.rotationOffset)+i,r=e.getAbsolutePosition(),n=r.x+Math.sin(s)*this.radius,o=r.z+Math.cos(s)*this.radius,a=n-this.position.x,l=r.y+this.heightOffset-this.position.y,h=o-this.position.z;let c=a*this.cameraAcceleration*2,u=l*this.cameraAcceleration,d=h*this.cameraAcceleration*2;(c>this.maxCameraSpeed||c<-this.maxCameraSpeed)&&(c=c<1?-this.maxCameraSpeed:this.maxCameraSpeed),(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new _e(this.position.x+c,this.position.y+u,this.position.z+d),this.setTarget(r)}attachControl(e,t){t=Ds.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=()=>{}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){this.inputs.checkInputs(),this._checkLimits(),super._checkInputs(),this.lockedTarget&&this._follow(this.lockedTarget)}_checkLimits(){null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}Ze([rt()],pc.prototype,"radius",void 0),Ze([rt()],pc.prototype,"lowerRadiusLimit",void 0),Ze([rt()],pc.prototype,"upperRadiusLimit",void 0),Ze([rt()],pc.prototype,"rotationOffset",void 0),Ze([rt()],pc.prototype,"lowerRotationOffsetLimit",void 0),Ze([rt()],pc.prototype,"upperRotationOffsetLimit",void 0),Ze([rt()],pc.prototype,"heightOffset",void 0),Ze([rt()],pc.prototype,"lowerHeightOffsetLimit",void 0),Ze([rt()],pc.prototype,"upperHeightOffsetLimit",void 0),Ze([rt()],pc.prototype,"cameraAcceleration",void 0),Ze([rt()],pc.prototype,"maxCameraSpeed",void 0),Ze([ct("lockedTargetId")],pc.prototype,"lockedTarget",void 0);class fc extends oc{constructor(e,t,i,s,r,n){super(e,_e.Zero(),n),this.alpha=t,this.beta=i,this.radius=s,this._cartesianCoordinates=_e.Zero(),this.setMeshTarget(r)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);const e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}z("BABYLON.FollowCamera",pc),z("BABYLON.ArcFollowCamera",fc),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Oh||(Oh={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Dh||(Dh={}));class mc extends kh{constructor(e,t,i,s=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new K,this.onButtonUpObservable=new K,this.onPadDownObservable=new K,this.onPadUpObservable=new K,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this.type=kh.XBOX,this._isXboxOnePad=s}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,Oh.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,Oh.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,Oh.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,Oh.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,Oh.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,Oh.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,Oh.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,Oh.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Oh.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Oh.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Dh.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Dh.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Dh.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Dh.Right)}update(){super.update(),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}!function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(wh||(wh={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Nh||(Nh={}));class gc extends kh{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new K,this.onButtonUpObservable=new K,this.onPadDownObservable=new K,this.onPadUpObservable=new K,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=kh.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,wh.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,wh.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,wh.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,wh.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,wh.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,wh.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,wh.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,wh.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,wh.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,wh.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Nh.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Nh.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Nh.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Nh.Right)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class vc{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new K,kt()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new K((e=>{for(const t in this._babylonGamepads){const i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}})),this._onGamepadConnectedEvent=e=>{const t=e.gamepad;if(t.index in this._babylonGamepads&&this._babylonGamepads[t.index].isConnected)return;let i;this._babylonGamepads[t.index]?(i=this._babylonGamepads[t.index],i.browserGamepad=t,i._isConnected=!0):i=this._addNewGamepad(t),this.onGamepadConnectedObservable.notifyObservers(i),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=e=>{const t=e.gamepad;for(const e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){const t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){const e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}get gamepads(){return this._babylonGamepads}getGamepadByType(e=kh.XBOX){for(const t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach((e=>{e.dispose()})),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);const i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),s=-1!==e.id.search("Xbox One");return t=s||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new mc(e.id,e.index,e,s):i?new gc(e.id,e.index,e):new Vh(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){this._updateGamepadObjects();for(const e in this._babylonGamepads){const t=this._babylonGamepads[e];if(t&&t.isConnected)try{t.update()}catch{-1===this._loggedErrors.indexOf(t.index)&&(Ds.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&oo.QueueNewFrame((()=>{this._checkGamepadsStatus()}))}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new bc(e,_e.Zero(),t)));class bc extends lc{get gamepadAngularSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}}In._CreateDefaultParsedCamera=(e,t)=>new bc(e,_e.Zero(),t),Et.AddNodeConstructor("GamepadCamera",((e,t)=>()=>new Tc(e,_e.Zero(),t)));class Tc extends bc{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}Bi.ShadersStore.passCubePixelShader="varying vec2 vUV;uniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";class yc extends Vl{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,r,n,o=0,a=!1){super(e,"pass",null,null,t,i,s,r,n,void 0,o,void 0,null,a)}static _Parse(e,t,i,s){return St.Parse((()=>new yc(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,s)}}z("BABYLON.PassPostProcess",yc);class Sc extends Vl{get face(){return this._face}set face(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ")}}getClassName(){return"PassCubePostProcess"}constructor(e,t,i=null,s,r,n,o=0,a=!1){super(e,"passCube",null,null,t,i,s,r,n,"#define POSITIVEX",o,void 0,null,a),this._face=0}static _Parse(e,t,i,s){return St.Parse((()=>new Sc(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,s)}}ns._RescalePostProcessFactory=e=>new yc("rescale",1,null,2,e,!1,0);Bi.ShadersStore.anaglyphPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}";class Cc extends Vl{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,s,r,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],s,r,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)}))}}function Ec(e){e._rigCameras[0]._rigPostProcess=new yc(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new Cc(e.name+"_anaglyph",1,e._rigCameras)}z("BABYLON.AnaglyphPostProcess",Cc),Et.AddNodeConstructor("AnaglyphArcRotateCamera",((e,t,i)=>()=>new Ac(e,0,0,1,_e.Zero(),i.interaxial_distance,t)));class Ac extends hc{constructor(e,t,i,s,r,n,o){super(e,t,i,s,r,o),this._setRigMode=()=>Ec(this),this.interaxialDistance=n,this.setCameraRigMode(In.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}Et.AddNodeConstructor("AnaglyphFreeCamera",((e,t,i)=>()=>new Pc(e,_e.Zero(),i.interaxial_distance,t)));class Pc extends ac{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Ec(this),this.interaxialDistance=i,this.setCameraRigMode(In.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}Et.AddNodeConstructor("AnaglyphGamepadCamera",((e,t,i)=>()=>new Ic(e,_e.Zero(),i.interaxial_distance,t)));class Ic extends Tc{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Ec(this),this.interaxialDistance=i,this.setCameraRigMode(In.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}Et.AddNodeConstructor("AnaglyphUniversalCamera",((e,t,i)=>()=>new Rc(e,_e.Zero(),i.interaxial_distance,t)));class Rc extends bc{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Ec(this),this.interaxialDistance=i,this.setCameraRigMode(In.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}Bi.ShadersStore.stereoscopicInterlacePixelShader="const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\n#ifdef IS_STEREOSCOPIC_INTERLACED\nfloat rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n#endif\nif (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);}\n";class Mc extends Vl{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,s,r,n,o){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],r,n,o,s?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new de(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new de(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}class Oc extends Vl{getClassName(){return"StereoscopicInterlacePostProcess"}constructor(e,t,i,s,r,n){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,r,n,i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new de(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new de(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}function Dc(e){const t=e.cameraRigMode===In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;e.cameraRigMode===In.RIG_MODE_STEREOSCOPIC_INTERLACED?(e._rigCameras[0]._rigPostProcess=new yc(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new Mc(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new Pn(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new Pn(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}Et.AddNodeConstructor("StereoscopicArcRotateCamera",((e,t,i)=>()=>new wc(e,0,0,1,_e.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class wc extends hc{constructor(e,t,i,s,r,n,o,a){super(e,t,i,s,r,a),this._setRigMode=()=>Dc(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:In.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}Et.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new Nc(e,_e.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Nc extends ac{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Dc(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:In.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}Et.AddNodeConstructor("StereoscopicGamepadCamera",((e,t,i)=>()=>new Fc(e,_e.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Fc extends Tc{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Dc(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:In.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}Et.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new Lc(e,_e.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Lc extends bc{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Dc(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:In.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}class Bc extends bc{set distanceBetweenEyes(e){this._distanceBetweenEyes=e}get distanceBetweenEyes(){return this._distanceBetweenEyes}set distanceToProjectionPlane(e){this._distanceToProjectionPlane=e}get distanceToProjectionPlane(){return this._distanceToProjectionPlane}constructor(e,t,i,s=1,r=.065){super(e,t,i),this._distanceBetweenEyes=r,this._distanceToProjectionPlane=s,this.setCameraRigMode(In.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,{stereoHalfAngle:0}),this._cameraRigParams.stereoHalfAngle=0,this._cameraRigParams.interaxialDistance=r}getClassName(){return"StereoscopicUniversalCamera"}createRigCamera(e){const t=new oc(e,_e.Zero(),this.getScene()),i=new lo("tm_"+e,this.getScene());return t.parent=i,i.setPivotMatrix(me.Identity(),!1),t.isRigCamera=!0,t.rigParent=this,t}_updateRigCameras(){for(let e=0;e()=>new kc(e,_e.Zero(),t)));class kc extends ac{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class Vc{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return me.Translation(e,0,0)}get rightHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return me.Translation(-e,0,0)}get leftPreViewMatrix(){return me.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return me.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new Vc;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}Bi.ShadersStore.vrDistortionCorrectionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}";class Uc extends Vl{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,s){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,s.postProcessScaleFactor,t,Pa.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=s.distortionK,this._postProcessScaleFactor=s.postProcessScaleFactor,this._lensCenterOffset=s.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add((()=>{this._scaleIn=new de(2,2/this.aspectRatio),this._scaleFactor=new de(1/this._postProcessScaleFactor*.5,1/this._postProcessScaleFactor*.5*this.aspectRatio),this._lensCenter=new de(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)})),this.onApplyObservable.add((e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])}))}}Bi.ShadersStore.vrMultiviewToSingleviewPixelShader="precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}";class Gc extends ih{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}}function zc(e,t){const i=new Zs(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}oo.prototype.createMultiviewRenderTargetTexture=function(e,t,i,s){const r=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const n=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});n._framebuffer=r.createFramebuffer();const o=new ss(this,is.Unknown,!0);return o.width=e,o.height=t,o.isMultiview=!0,i||(i=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,i),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.RGBA8,e,t,2)),n._colorTextureArray=i,s||(s=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,s),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.DEPTH24_STENCIL8,e,t,2)),n._depthStencilTextureArray=s,o.isReady=!0,n.setTextures(o),n._depthStencilTexture=o,n},oo.prototype.bindMultiviewFramebuffer=function(e){const t=e,i=this._gl,s=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw"Invalid multiview frame buffer";this.getCaps().oculusMultiview?(s.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,t.samples,0,2),s.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,t.samples,0,2)):(s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,0,2))},oo.prototype.bindSpaceWarpFramebuffer=function(e){const t=e,i=this._gl,s=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw new Error("Invalid Space Warp framebuffer");s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_ATTACHMENT,t._depthStencilTextureArray,0,0,2)},In.prototype._useMultiviewToSingleView=!1,In.prototype._multiviewTexture=null,In.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==e&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new Gc(this.getScene(),{width:e,height:t})):this._multiviewTexture=new Gc(this.getScene(),{width:e,height:t})};const Wc=Hr.prototype.createSceneUniformBuffer;Hr.prototype._transformMatrixR=me.Zero(),Hr.prototype._multiviewSceneUbo=null,Hr.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=zc(this.getEngine(),"scene_multiview")},Hr.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?zc(this.getEngine(),e):Wc.bind(this)(e)},Hr.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,ve.Matrix[0]),Fr.GetRightPlaneToRef(ve.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))},Hr.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t{})),this.onApplyObservable.add((e=>{s._scene.activeCamera&&s._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",s._multiviewTexture)}))}}function Xc(e,t){const i=t.vrCameraMetrics||Vc.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new Pn(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new me,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new Pn(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new me,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new Hc("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(Ne.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new Uc("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new Uc("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}Et.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",((e,t)=>()=>new Yc(e,0,0,1,_e.Zero(),t)));class Yc extends hc{constructor(e,t,i,s,r,n,o=!0,a=Vc.GetDefault()){super(e,t,i,s,r,n),this._setRigMode=e=>Xc(this,e),a.compensateDistortion=o,this.setCameraRigMode(In.RIG_MODE_VR,{vrCameraMetrics:a}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}Et.AddNodeConstructor("VRDeviceOrientationFreeCamera",((e,t)=>()=>new Qc(e,_e.Zero(),t)));class Qc extends cc{constructor(e,t,i,s=!0,r=Vc.GetDefault()){super(e,t,i),this._setRigMode=e=>Xc(this,e),r.compensateDistortion=s,this.setCameraRigMode(In.RIG_MODE_VR,{vrCameraMetrics:r})}getClassName(){return"VRDeviceOrientationFreeCamera"}}Et.AddNodeConstructor("VRDeviceOrientationGamepadCamera",((e,t)=>()=>new jc(e,_e.Zero(),t)));class jc extends Qc{constructor(e,t,i,s=!0,r=Vc.GetDefault()){super(e,t,i,s,r),this._setRigMode=e=>Xc(this,e),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}class Kc{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,s,r){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(2)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=s.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const r=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==r.frameId&&(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=s.clone()}}}class $c{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,oo.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._TranslucencyIntensityTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get TranslucencyColorTextureEnabled(){return this._TranslucencyColorTextureEnabled}static set TranslucencyColorTextureEnabled(e){this._TranslucencyColorTextureEnabled!==e&&(this._TranslucencyColorTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,oo.MarkAllMaterialsAsDirty(1))}}$c._DiffuseTextureEnabled=!0,$c._DetailTextureEnabled=!0,$c._DecalMapEnabled=!0,$c._AmbientTextureEnabled=!0,$c._OpacityTextureEnabled=!0,$c._ReflectionTextureEnabled=!0,$c._EmissiveTextureEnabled=!0,$c._SpecularTextureEnabled=!0,$c._BumpTextureEnabled=!0,$c._LightmapTextureEnabled=!0,$c._RefractionTextureEnabled=!0,$c._ColorGradingTextureEnabled=!0,$c._FresnelEnabled=!0,$c._ClearCoatTextureEnabled=!0,$c._ClearCoatBumpTextureEnabled=!0,$c._ClearCoatTintTextureEnabled=!0,$c._SheenTextureEnabled=!0,$c._AnisotropicTextureEnabled=!0,$c._ThicknessTextureEnabled=!0,$c._RefractionIntensityTextureEnabled=!0,$c._TranslucencyIntensityTextureEnabled=!0,$c._TranslucencyColorTextureEnabled=!0,$c._IridescenceTextureEnabled=!0;Bi.IncludesShadersStore.decalFragmentDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;\n#endif\n";Bi.IncludesShadersStore.defaultFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;uniform vec4 refractionRightColor;\n#endif\n#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)\nuniform mat4 reflectionMatrix;\n#endif\n#ifndef REFLECTIONMAP_SKYBOX\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";Bi.IncludesShadersStore.sceneUboDeclaration="layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \nmat4 view;mat4 projection;vec4 vEyePosition;};\n";Bi.IncludesShadersStore.meshUboDeclaration="#ifdef WEBGL2\nuniform mat4 world;uniform float visibility;\n#else\nlayout(std140,column_major) uniform;uniform Mesh\n{mat4 world;float visibility;};\n#endif\n#define WORLD_UBO\n";Bi.IncludesShadersStore.defaultUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";Bi.IncludesShadersStore.prePassDeclaration="#ifdef PREPASS\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor;\n#ifdef PREPASS_DEPTH\nvarying highp vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nvarying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;\n#endif\n#endif\n";Bi.IncludesShadersStore.oitDeclaration="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out vec2 depth; \nlayout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor;\n#define MAX_DEPTH 99999.0\nhighp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler;\n#endif\n";Bi.IncludesShadersStore.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vec2 vMainUV{X};\n#endif\n";Bi.IncludesShadersStore.helperFunctions="const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; \nconst float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\n#define absEps(x) abs(x)+Epsilon\n#define maxEps(x) max(x,Epsilon)\n#define saturateEps(x) clamp(x,Epsilon,1.0)\nmat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nmat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;}\n#if USE_EXACT_SRGB_CONVERSIONS\nvec3 toLinearSpaceExact(vec3 color)\n{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));\n#else\nreturn\nvec3(\ncolor.r<=0.04045 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.04045 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.04045 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\nvec3 toGammaSpaceExact(vec3 color)\n{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));\n#else\nreturn\nvec3(\ncolor.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\n#endif\nfloat toLinearSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,LinearEncodePowerApprox);\n#endif\n}\nvec3 toLinearSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nvec4 toLinearSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfloat toGammaSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,GammaEncodePowerApprox);\n#endif\n}\nvec3 toGammaSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nvec4 toGammaSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfloat square(float value)\n{return value*value;}\nvec3 square(vec3 value)\n{return value*value;}\nfloat pow5(float value) {float sq=value*value;return sq*sq*value;}\nfloat getLuminance(vec3 color)\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfloat getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfloat dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;}\nconst float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); }\nvec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;}\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";Bi.IncludesShadersStore.lightFragmentDeclaration="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};\n#else\nuniform highp sampler2DArray shadowTexture{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowTexture{X};\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowTexture{X};\n#else\nuniform sampler2D shadowTexture{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};\n#endif\n#endif\n";Bi.IncludesShadersStore.lightUboDeclaration="#ifdef LIGHT{X}\nuniform Light{X}\n{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;vec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;vec2 depthValues;} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};\n#else\nuniform highp sampler2DArray shadowTexture{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowTexture{X}; \n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowTexture{X};\n#else\nuniform sampler2D shadowTexture{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";Bi.IncludesShadersStore.lightsFragmentFunctions="struct lightingInfo\n{vec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.)\n{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}";Bi.IncludesShadersStore.shadowsFragmentFunctions="#ifdef SHADOWS\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}\n#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\n#define inline\nfloat computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nreturn depth>shadow ? darkness : 1.0;}\n#define inline\nfloat computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}\n#endif\n#define inline\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}}\n#define inline\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#ifdef IS_NDC_HALF_ZRANGE\n#define ZINCLIP clipSpace.z\n#else\n#define ZINCLIP uvDepth.z\n#endif\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define GREATEST_LESS_THAN_ONE 0.99999994\n#define DISABLE_UNIFORMITY_ANALYSIS\n#define inline\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.)\n);const vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n#define inline\nfloat computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; ithis._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort(((e,t)=>e.priority-t.priority)),this._codeInjectionPoints={};const i={};i[Zc._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const e of this._plugins)e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t0&&e.uniforms.push(...this._uniformList),this._samplerList.length>0&&e.samplers.push(...this._samplerList),this._uboList.length>0&&e.uniformBuffersNames.push(...this._uboList),e.customCode=this._injectCustomCode(e,e.customCode);break}case fo.PrepareUniformBuffer:{const e=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const t of this._plugins){const i=t.getUniforms();if(i){if(i.ubo)for(const t of i.ubo){if(t.size&&t.type){const i=t.arraySize??0;e.ubo.addUniform(t.name,t.size,i),this._uboDeclaration+=`${t.type} ${t.name}${i>0?`[${i}]`:""};\n`}this._uniformList.push(t.name)}i.vertex&&(this._vertexDeclaration+=i.vertex+"\n"),i.fragment&&(this._fragmentDeclaration+=i.fragment+"\n")}t.getSamplers(this._samplerList),t.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,s)=>{t&&(s=t(i,s)),this._uboDeclaration&&(s=s.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(s=s.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(s=s.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const r=this._codeInjectionPoints?.[i];if(!r)return s;let n=null;for(let t in r){let r="";for(const s of this._activePlugins){let o=s.getCustomCode(i)?.[t];if(o){if(s.resolveIncludes){if(null===n){const t=di.GLSL;n={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Bi.GetShadersRepository(t),includesShadersStore:Bi.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}n.isFragment="fragment"===i,Ni(o,n,(e=>o=e))}r+=o+"\n"}}if(r.length>0)if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{const i=qc.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}e.indexOf("g")<0&&(e+="g");const i=s,n=new RegExp(t,e);let o=n.exec(i);for(;null!==o;){let e=r;for(let t=0;t{ru()}));const Jc=[];let eu=!1,tu=null;function iu(e,t){eu||(tu=ta.OnEventObservable.add((e=>{for(const[,t]of Jc)t(e)}),fo.Created),eu=!0);const i=Jc.filter((([t,i])=>t===e));i.length>0?i[0][1]=t:Jc.push([e,t])}function su(e){for(let t=0;t{e.pluginManager=void 0}))),this._pluginDefineNames=s,this._pluginManager=e.pluginManager,r&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,s){return!0}hardBindForSubMesh(e,t,i,s){}bindForSubMesh(e,t,i,s){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;const i=typeof this._pluginDefineNames[t];e[t]={type:"number"===i?"number":"string"===i?"string":"boolean"===i?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(){return{}}copyTo(e){St.Clone((()=>e),this)}serialize(){return St.Serialize(this)}parse(e,t,i){St.Parse((()=>this),e,t,i)}}Ze([rt()],nu.prototype,"name",void 0),Ze([rt()],nu.prototype,"priority",void 0),Ze([rt()],nu.prototype,"resolveIncludes",void 0),Ze([rt()],nu.prototype,"registerForExtraEvents",void 0),z("BABYLON.MaterialPluginBase",nu);class ou extends xl{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class au extends nu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new ou,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=ta.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&$c.DetailTextureEnabled&&!this._texture.isReady())}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&$c.DetailTextureEnabled&&this._isEnabled?(Mo(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||this._texture&&$c.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),Oo(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&$c.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture?.dispose()}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}Ze([nt("detailTexture"),st("_markAllSubMeshesAsTexturesDirty")],au.prototype,"texture",void 0),Ze([rt()],au.prototype,"diffuseBlendLevel",void 0),Ze([rt()],au.prototype,"roughnessBlendLevel",void 0),Ze([rt()],au.prototype,"bumpLevel",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],au.prototype,"normalBlendMethod",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],au.prototype,"isEnabled",void 0);const lu={effect:null,subMesh:null};class hu extends xl{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){const t=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];for(const i of t)this[i]=i===e}}class cu extends ml{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new Ee(0,0,0),this.diffuseColor=new Ee(1,1,1),this.specularColor=new Ee(1,1,1),this.emissiveColor=new Ee(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._renderTargets=new Fs(16),this._worldViewProjectionMatrix=me.Zero(),this._globalAmbientColor=new Ee(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new au(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new Kc,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),cu.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),cu.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return!!(cu.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||!!(cu.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===ta.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==ta.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(fo.GetDefineNames,this._eventInfo),t.materialDefines=new hu(this._eventInfo.defineNames));const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();n._needNormals=zo(r,e,n,!0,this._maxSimultaneousLights,this._disableLighting),Ko(r,n);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(qo(r,n,this.canRenderToMRT&&!a),$o(r,n,a),n._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n._needUVs=!1;for(let e=1;e<=6;++e)n["MAINUV"+e]=!1;if(r.texturesEnabled){if(n.DIFFUSEDIRECTUV=0,n.BUMPDIRECTUV=0,n.AMBIENTDIRECTUV=0,n.OPACITYDIRECTUV=0,n.EMISSIVEDIRECTUV=0,n.SPECULARDIRECTUV=0,n.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&cu.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;Mo(this._diffuseTexture,n,"DIFFUSE")}else n.DIFFUSE=!1;if(this._ambientTexture&&cu.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;Mo(this._ambientTexture,n,"AMBIENT")}else n.AMBIENT=!1;if(this._opacityTexture&&cu.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;Mo(this._opacityTexture,n,"OPACITY"),n.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else n.OPACITY=!1;if(this._reflectionTexture&&cu.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(n._needNormals=!0,n.REFLECTION=!0,n.ROUGHNESS=this._roughness>0,n.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,n.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===Pa.INVCUBIC_MODE,n.REFLECTIONMAP_3D=this._reflectionTexture.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,n.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case Pa.EXPLICIT_MODE:n.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case Pa.PLANAR_MODE:n.setReflectionMode("REFLECTIONMAP_PLANAR");break;case Pa.PROJECTION_MODE:n.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case Pa.SKYBOX_MODE:n.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case Pa.SPHERICAL_MODE:n.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case Pa.EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case Pa.FIXED_EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case Pa.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case Pa.CUBIC_MODE:case Pa.INVCUBIC_MODE:default:n.setReflectionMode("REFLECTIONMAP_CUBIC")}n.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else n.REFLECTION=!1,n.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&cu.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;Mo(this._emissiveTexture,n,"EMISSIVE")}else n.EMISSIVE=!1;if(this._lightmapTexture&&cu.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;Mo(this._lightmapTexture,n,"LIGHTMAP"),n.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,n.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else n.LIGHTMAP=!1;if(this._specularTexture&&cu.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;Mo(this._specularTexture,n,"SPECULAR"),n.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else n.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&cu.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;Mo(this._bumpTexture,n,"BUMP"),n.PARALLAX=this._useParallax,n.PARALLAX_RHS=r.useRightHandedSystem,n.PARALLAXOCCLUSION=this._useParallaxOcclusion,n.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else n.BUMP=!1,n.PARALLAX=!1,n.PARALLAX_RHS=!1,n.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&cu.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;n._needUVs=!0,n.REFRACTION=!0,n.REFRACTIONMAP_3D=this._refractionTexture.isCube,n.RGBDREFRACTION=this._refractionTexture.isRGBD,n.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else n.REFRACTION=!1;n.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else n.DIFFUSE=!1,n.AMBIENT=!1,n.OPACITY=!1,n.REFLECTION=!1,n.EMISSIVE=!1,n.LIGHTMAP=!1,n.BUMP=!1,n.REFRACTION=!1;n.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),n.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,n.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,n.SPECULAROVERALPHA=this._useSpecularOverAlpha,n.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,n.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,n.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n),n.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,n.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}n._areFresnelDirty&&(cu.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(n.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,n.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,n.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,n.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,n.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,n.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,n._needNormals=!0,n.FRESNEL=!0):n.FRESNEL=!1),Go(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,n,this._applyDecalMapAfterDetailMap),Ho(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=n,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),jo(e,n,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let l=!1;if(n.isDirty){const i=n._areLightsDisposed;n.markAsProcessed();const s=new Ll;n.REFLECTION&&s.addFallback(0,"REFLECTION"),n.SPECULAR&&s.addFallback(0,"SPECULAR"),n.BUMP&&s.addFallback(0,"BUMP"),n.PARALLAX&&s.addFallback(1,"PARALLAX"),n.PARALLAX_RHS&&s.addFallback(1,"PARALLAX_RHS"),n.PARALLAXOCCLUSION&&s.addFallback(0,"PARALLAXOCCLUSION"),n.SPECULAROVERALPHA&&s.addFallback(0,"SPECULAROVERALPHA"),n.FOG&&s.addFallback(1,"FOG"),n.POINTSIZE&&s.addFallback(0,"POINTSIZE"),n.LOGARITHMICDEPTH&&s.addFallback(0,"LOGARITHMICDEPTH"),Vo(n,s,this._maxSimultaneousLights),n.SPECULARTERM&&s.addFallback(0,"SPECULARTERM"),n.DIFFUSEFRESNEL&&s.addFallback(1,"DIFFUSEFRESNEL"),n.OPACITYFRESNEL&&s.addFallback(2,"OPACITYFRESNEL"),n.REFLECTIONFRESNEL&&s.addFallback(3,"REFLECTIONFRESNEL"),n.EMISSIVEFRESNEL&&s.addFallback(4,"EMISSIVEFRESNEL"),n.FRESNEL&&s.addFallback(4,"FRESNEL"),n.MULTIVIEW&&s.addFallback(0,"MULTIVIEW");const a=[er.PositionKind];n.NORMAL&&a.push(er.NormalKind),n.TANGENT&&a.push(er.TangentKind);for(let e=1;e<=6;++e)n["UV"+e]&&a.push(`uv${1===e?"":e}`);n.VERTEXCOLOR&&a.push(er.ColorKind),Bo(a,e,n,s),ko(a,n),Ao(a,e,n),Do(a,0,n);let h="default";const c=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],u=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],d=["Material","Scene","Mesh"],_={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=s,this._eventInfo.fallbackRank=0,this._eventInfo.defines=n,this._eventInfo.uniforms=c,this._eventInfo.attributes=a,this._eventInfo.samplers=u,this._eventInfo.uniformBuffersNames=d,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=_,this._callbackPluginEventGeneric(fo.PrepareEffect,this._eventInfo),Kc.AddUniforms(c),Kc.AddSamplers(u),zs&&(zs.PrepareUniforms(c,n),zs.PrepareSamplers(u,n)),ea({uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:n,maxSimultaneousLights:this._maxSimultaneousLights}),mo(c);const p={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,c,d,u,n,a,p));const f=n.toString(),m=t.effect;let g=r.getEngine().createEffect(h,{attributes:a,uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:f,fallbacks:s,onCompiled:this.onCompiled,onError:this.onError,indexParameters:_,processFinalCode:p.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:n.PREPASS},o);if(this._eventInfo.customCode=void 0,g)if(this._onEffectCreatedObservable&&(lu.effect=g,lu.subMesh=t,this._onEffectCreatedObservable.notifyObservers(lu)),this.allowShaderHotSwapping&&m&&!g.isReady()){if(g=m,n.markAsUnprocessed(),l=this.isFrozen,i)return n._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(g,n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!l,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(s,n,i,t.visibility);wo(t,n);const a=this._uniformBuffer;if(o){if(this.bindViewProjection(n),!a.useUbo||!this.isFrozen||!a.isSync||i._drawWrapper._forceRebindOnNextCall){if(cu.FresnelEnabled&&r.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(a.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),a.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&a.updateColor4("opacityParts",new Ee(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(a.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),a.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(a.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),a.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(a.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),a.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&cu.DiffuseTextureEnabled&&(a.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Oo(this._diffuseTexture,a,"diffuse")),this._ambientTexture&&cu.AmbientTextureEnabled&&(a.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),Oo(this._ambientTexture,a,"ambient")),this._opacityTexture&&cu.OpacityTextureEnabled&&(a.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Oo(this._opacityTexture,a,"opacity")),this._hasAlphaChannel()&&a.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&cu.ReflectionTextureEnabled&&(a.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),a.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const e=this._reflectionTexture;a.updateVector3("vReflectionPosition",e.boundingBoxPosition),a.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&cu.EmissiveTextureEnabled&&(a.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Oo(this._emissiveTexture,a,"emissive")),this._lightmapTexture&&cu.LightmapTextureEnabled&&(a.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Oo(this._lightmapTexture,a,"lightmap")),this._specularTexture&&cu.SpecularTextureEnabled&&(a.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),Oo(this._specularTexture,a,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&cu.BumpTextureEnabled&&(a.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),Oo(this._bumpTexture,a,"bump"),s._mirroredCameraPosition?a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&cu.RefractionTextureEnabled){let e=1;if(this._refractionTexture.isCube||(a.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),a.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const e=this._refractionTexture;a.updateVector3("vRefractionPosition",e.boundingBoxPosition),a.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&a.updateFloat("pointSize",this.pointSize),r.SPECULARTERM&&a.updateColor4("vSpecularColor",this.specularColor,this.specularPower),a.updateColor3("vEmissiveColor",cu.EmissiveTextureEnabled?this.emissiveColor:Ee.BlackReadOnly),a.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),a.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&cu.DiffuseTextureEnabled&&n.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&cu.AmbientTextureEnabled&&n.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&cu.OpacityTextureEnabled&&n.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&cu.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?n.setTexture("reflectionCubeSampler",this._reflectionTexture):n.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&cu.EmissiveTextureEnabled&&n.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&cu.LightmapTextureEnabled&&n.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&cu.SpecularTextureEnabled&&n.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&cu.BumpTextureEnabled&&n.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&cu.RefractionTextureEnabled&&(this._refractionTexture.isCube?n.setTexture("refractionCubeSampler",this._refractionTexture):n.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),xo(n,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!o&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&Lo(s,t,n,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),Co(s,t,n),r.NUM_MORPH_INFLUENCERS&&Io(t,n),r.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,r.INSTANCES),this.useLogarithmicDepth&&So(r,n,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),a.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e}dispose(e,t){t&&(this._diffuseTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._specularTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._refractionTexture?.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=St.Clone((()=>new cu(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return s.name=e,s.id=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}static Parse(e,t,i){const s=St.Parse((()=>new cu(e.name,t)),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),ta._ParsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return $c.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){$c.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return $c.DetailTextureEnabled}static set DetailTextureEnabled(e){$c.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return $c.AmbientTextureEnabled}static set AmbientTextureEnabled(e){$c.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return $c.OpacityTextureEnabled}static set OpacityTextureEnabled(e){$c.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return $c.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){$c.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return $c.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){$c.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return $c.SpecularTextureEnabled}static set SpecularTextureEnabled(e){$c.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return $c.BumpTextureEnabled}static set BumpTextureEnabled(e){$c.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return $c.LightmapTextureEnabled}static set LightmapTextureEnabled(e){$c.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return $c.RefractionTextureEnabled}static set RefractionTextureEnabled(e){$c.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return $c.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){$c.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return $c.FresnelEnabled}static set FresnelEnabled(e){$c.FresnelEnabled=e}}Ze([nt("diffuseTexture")],cu.prototype,"_diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesAndMiscDirty")],cu.prototype,"diffuseTexture",void 0),Ze([nt("ambientTexture")],cu.prototype,"_ambientTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"ambientTexture",void 0),Ze([nt("opacityTexture")],cu.prototype,"_opacityTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesAndMiscDirty")],cu.prototype,"opacityTexture",void 0),Ze([nt("reflectionTexture")],cu.prototype,"_reflectionTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"reflectionTexture",void 0),Ze([nt("emissiveTexture")],cu.prototype,"_emissiveTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"emissiveTexture",void 0),Ze([nt("specularTexture")],cu.prototype,"_specularTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"specularTexture",void 0),Ze([nt("bumpTexture")],cu.prototype,"_bumpTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"bumpTexture",void 0),Ze([nt("lightmapTexture")],cu.prototype,"_lightmapTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"lightmapTexture",void 0),Ze([nt("refractionTexture")],cu.prototype,"_refractionTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"refractionTexture",void 0),Ze([ot("ambient")],cu.prototype,"ambientColor",void 0),Ze([ot("diffuse")],cu.prototype,"diffuseColor",void 0),Ze([ot("specular")],cu.prototype,"specularColor",void 0),Ze([ot("emissive")],cu.prototype,"emissiveColor",void 0),Ze([rt()],cu.prototype,"specularPower",void 0),Ze([rt("useAlphaFromDiffuseTexture")],cu.prototype,"_useAlphaFromDiffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesAndMiscDirty")],cu.prototype,"useAlphaFromDiffuseTexture",void 0),Ze([rt("useEmissiveAsIllumination")],cu.prototype,"_useEmissiveAsIllumination",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useEmissiveAsIllumination",void 0),Ze([rt("linkEmissiveWithDiffuse")],cu.prototype,"_linkEmissiveWithDiffuse",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"linkEmissiveWithDiffuse",void 0),Ze([rt("useSpecularOverAlpha")],cu.prototype,"_useSpecularOverAlpha",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useSpecularOverAlpha",void 0),Ze([rt("useReflectionOverAlpha")],cu.prototype,"_useReflectionOverAlpha",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useReflectionOverAlpha",void 0),Ze([rt("disableLighting")],cu.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],cu.prototype,"disableLighting",void 0),Ze([rt("useObjectSpaceNormalMap")],cu.prototype,"_useObjectSpaceNormalMap",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useObjectSpaceNormalMap",void 0),Ze([rt("useParallax")],cu.prototype,"_useParallax",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useParallax",void 0),Ze([rt("useParallaxOcclusion")],cu.prototype,"_useParallaxOcclusion",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useParallaxOcclusion",void 0),Ze([rt()],cu.prototype,"parallaxScaleBias",void 0),Ze([rt("roughness")],cu.prototype,"_roughness",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"roughness",void 0),Ze([rt()],cu.prototype,"indexOfRefraction",void 0),Ze([rt()],cu.prototype,"invertRefractionY",void 0),Ze([rt()],cu.prototype,"alphaCutOff",void 0),Ze([rt("useLightmapAsShadowmap")],cu.prototype,"_useLightmapAsShadowmap",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useLightmapAsShadowmap",void 0),Ze([at("diffuseFresnelParameters")],cu.prototype,"_diffuseFresnelParameters",void 0),Ze([st("_markAllSubMeshesAsFresnelDirty")],cu.prototype,"diffuseFresnelParameters",void 0),Ze([at("opacityFresnelParameters")],cu.prototype,"_opacityFresnelParameters",void 0),Ze([st("_markAllSubMeshesAsFresnelAndMiscDirty")],cu.prototype,"opacityFresnelParameters",void 0),Ze([at("reflectionFresnelParameters")],cu.prototype,"_reflectionFresnelParameters",void 0),Ze([st("_markAllSubMeshesAsFresnelDirty")],cu.prototype,"reflectionFresnelParameters",void 0),Ze([at("refractionFresnelParameters")],cu.prototype,"_refractionFresnelParameters",void 0),Ze([st("_markAllSubMeshesAsFresnelDirty")],cu.prototype,"refractionFresnelParameters",void 0),Ze([at("emissiveFresnelParameters")],cu.prototype,"_emissiveFresnelParameters",void 0),Ze([st("_markAllSubMeshesAsFresnelDirty")],cu.prototype,"emissiveFresnelParameters",void 0),Ze([rt("useReflectionFresnelFromSpecular")],cu.prototype,"_useReflectionFresnelFromSpecular",void 0),Ze([st("_markAllSubMeshesAsFresnelDirty")],cu.prototype,"useReflectionFresnelFromSpecular",void 0),Ze([rt("useGlossinessFromSpecularMapAlpha")],cu.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"useGlossinessFromSpecularMapAlpha",void 0),Ze([rt("maxSimultaneousLights")],cu.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],cu.prototype,"maxSimultaneousLights",void 0),Ze([rt("invertNormalMapX")],cu.prototype,"_invertNormalMapX",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"invertNormalMapX",void 0),Ze([rt("invertNormalMapY")],cu.prototype,"_invertNormalMapY",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"invertNormalMapY",void 0),Ze([rt("twoSidedLighting")],cu.prototype,"_twoSidedLighting",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],cu.prototype,"twoSidedLighting",void 0),Ze([rt("applyDecalMapAfterDetailMap")],cu.prototype,"_applyDecalMapAfterDetailMap",void 0),Ze([st("_markAllSubMeshesAsMiscDirty")],cu.prototype,"applyDecalMapAfterDetailMap",void 0),z("BABYLON.StandardMaterial",cu),Hr.DefaultMaterialFactory=e=>new cu("default material",e),qs.prototype.createDynamicTexture=function(e,t,i,s){const r=new ss(this,is.Dynamic);return r.baseWidth=e,r.baseHeight=t,i&&(e=this.needPOTTextures?Os(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?Os(t,this._caps.maxTextureSize):t),r.width=e,r.height=t,r.isReady=!1,r.generateMipMaps=i,r.samplingMode=s,this.updateTextureSamplingMode(s,r),this._internalTexturesCache.push(r),r},qs.prototype.updateDynamicTexture=function(e,t,i,s=!1,r,n=!1,o=!1){if(!e)return;const a=this._gl,l=a.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,n);this._unpackFlipY(void 0===i?e.invertY:i),s&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(r||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,u);a.texImage2D(l,0,d,u,c,t),e.generateMipMaps&&a.generateMipmap(l),h||this._bindTextureDirectly(l,null),s&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),r&&(e.format=r),e._dynamicTextureSource=t,e._premulAlpha=s,e.invertY=i||!1,e.isReady=!0};class uu extends Pa{constructor(e,t,i=null,s=!1,r=3,n=5,o){super(null,i,!s,o,r,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=Pa.CLAMP_ADDRESSMODE,this.wrapV=Pa.CLAMP_ADDRESSMODE,this._generateMipMaps=s;const a=this._getEngine();if(!a)return;t.getContext?(this._canvas=t,this._ownCanvas=!1,this._texture=a.createDynamicTexture(t.width,t.height,s,r)):(this._canvas=a.createCanvas(1,1),this._ownCanvas=!0,t.width||0===t.width?this._texture=a.createDynamicTexture(t.width,t.height,s,r):this._texture=a.createDynamicTexture(t,t,s,r));const l=this.getSize();this._canvas.width!==l.width&&(this._canvas.width=l.width),this._canvas.height!==l.height&&(this._canvas.height=l.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){const t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){const i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){const t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0,void 0,i)}drawText(e,t,i,s,r,n,o,a=!0){const l=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,l.width,l.height)),this._context.font=s,null==t){const i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){const e=parseInt(s.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=r||"",this._context.fillText(e,t,i),a&&this.update(o)}dispose(){super.dispose(),this._ownCanvas&&this._canvas?.remove?.(),this._canvas=null,this._context=null}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new uu(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){const e=this.getScene();e&&!e.isReady()&&Ne.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return uu._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return void 0!==e.toDataURL}_rebuild(){this.update()}}class du{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){if(this.isFixedFoveationSupported){const t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}}createRenderTargetTextureProvider(e){return this._rttWrapper=this._createRenderTargetTextureProvider(e),this._rttWrapper}dispose(){this._rttWrapper&&(this._rttWrapper.dispose(),this._rttWrapper=null)}constructor(e,t,i,s,r){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this._createRenderTargetTextureProvider=r,this._rttWrapper=null}}class _u{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new ss(this._engine,is.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new Ks(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,s,r,n){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},a=n?new Gc(this._scene,o):new ih("XR renderTargetTexture",o,this._scene),l=a.renderTarget;if(l._samples=a.samples,!i&&s||(l._framebuffer=i),s)if(n)l._colorTextureArray=s;else{const e=this._createInternalTexture(o,s);l.setTexture(e,0),a._texture=e}return r&&(n?l._depthStencilTextureArray=r:l._depthStencilTexture=this._createInternalTexture(o,r)),a.disableRescaling(),this._renderTargetTextures.push(a),a}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.length=0}}class pu extends du{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new fu(e.scene,this))),this.layer=e}}class fu extends _u{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){const i=this._layer.getViewport(t);if(!i)return!1;const s=this._framebufferDimensions.framebufferWidth,r=this._framebufferDimensions.framebufferHeight;return e.x=i.x/s,e.y=i.y/r,e.width=i.width/s,e.height=i.height/r,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,s=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&s===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,s),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=s),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class mu{static GetDefaults(e){const t=new mu;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class gu{constructor(e,t=mu.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new K,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{const e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add((()=>{this._addCanvas()})),e.onXRSessionEnded.add((()=>{this._removeCanvas()})),this._makeCanvasCompatibleAsync()}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}_makeCanvasCompatibleAsync(){this._canvasCompatiblePromise=new Promise((e=>{this.canvasContext&&this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then((()=>{e()})):e()}))}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new pu(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this._canvasCompatiblePromise.then((()=>{}),(()=>{Ds.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")})).then((()=>t()))}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce((()=>{this._setCanvasSize(!0)}))}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class vu extends du{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new xu(e,this))),this.layer=e}}class xu extends _u{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}}class bu{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}}class Tu{get worldScalingFactor(){return this._worldScalingFactor}set worldScalingFactor(e){const t=this._worldScalingFactor;this._worldScalingFactor=e,this.onWorldScaleFactorChangedObservable.notifyObservers({previousScaleFactor:t,newScaleFactor:e})}constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new K,this.onXRReferenceSpaceChanged=new K,this.onXRSessionEnded=new K,this.onXRSessionInit=new K,this.onXRReferenceSpaceInitialized=new K,this.onXRReady=new K,this.inXRFrameLoop=!1,this.inXRSession=!1,this._worldScalingFactor=1,this.onWorldScaleFactorChangedObservable=new K(void 0,!0),this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),this.onWorldScaleFactorChangedObservable.clear(),this._engine?.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}async exitXRAsync(){if(this.session&&this.inXRSession){this.inXRSession=!1;try{return await this.session.end()}catch{Ne.Warn("Could not end XR session.")}}return Promise.resolve()}trySetViewportForView(e,t){return this._baseLayerRTTProvider?.trySetViewportForView(e,t)||!1}getRenderTargetTextureForEye(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForEye(e)||null}getRenderTargetTextureForView(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForView(e)||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new bu(this):((e=e||mu.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new gu(this,e))}initializeAsync(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then((t=>(this.session=t,this._sessionMode=e,this.inXRSession=!0,this.onXRSessionInit.notifyObservers(t),this.session.addEventListener("end",(()=>{this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&this._baseLayerRTTProvider?.dispose(),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null}),{once:!0}),this.session)))}isSessionSupportedAsync(e){return Tu.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:e=>this.session.requestAnimationFrame(e),renderFunction:(e,t)=>{if(this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t)){this.inXRFrameLoop=!0;const e=this._baseLayerRTTProvider?.getFramebufferDimensions()||null;this._engine.framebufferDimensionsObject!==e&&(this._engine.framebufferDimensionsObject=e),this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1}}},this._engine.framebufferDimensionsObject=this._baseLayerRTTProvider?.getFramebufferDimensions()||null,this.onXRFrameObservable.addOnce((()=>{this.onXRReady.notifyObservers(this)})),"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then((e=>e),(e=>(Ne.Error("XR.requestReferenceSpace failed for the following reason: "),Ne.Error(e),Ne.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then((e=>{const t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)}),(e=>{throw Ne.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))))).then((e=>this.session.requestReferenceSpace("viewer").then((t=>(this.viewerReferenceSpace=t,e))))).then((e=>(this.referenceSpace=this.baseReferenceSpace=e,this.onXRReferenceSpaceInitialized.notifyObservers(e),this.referenceSpace)))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){this.isNative&&this._baseLayerRTTProvider?.dispose(),this._baseLayerWrapper=e,this._baseLayerRTTProvider=this._baseLayerWrapper?.createRenderTargetTextureProvider(this)||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new vu(e.baseLayer):new pu(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);const t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then((e=>{const t=void 0===e||e;return Promise.resolve(t)})).catch((e=>(Ne.Warn(e),Promise.resolve(!1)))):Promise.resolve(!1)}get isNative(){return this._xrNavigator.xr.native??!1}get currentFrameRate(){return this.session?.frameRate}get supportedFrameRates(){return this.session?.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():!this.inXRSession&&t||this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){return this._baseLayerWrapper?.isFixedFoveationSupported||!1}get fixedFoveation(){return this._baseLayerWrapper?.fixedFoveation||null}set fixedFoveation(e){const t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)}get enabledFeatures(){return this.session?.enabledFeatures??null}}var yu,Su;!function(e){e[e.ENTERING_XR=0]="ENTERING_XR",e[e.EXITING_XR=1]="EXITING_XR",e[e.IN_XR=2]="IN_XR",e[e.NOT_IN_XR=3]="NOT_IN_XR"}(yu||(yu={})),function(e){e[e.NOT_TRACKING=0]="NOT_TRACKING",e[e.TRACKING_LOST=1]="TRACKING_LOST",e[e.TRACKING=2]="TRACKING"}(Su||(Su={})),ha._GroundMeshParser=(e,t)=>Cu.Parse(e,t);class Cu extends ha{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),s=ve.Matrix[5];i.invertToRef(s);const r=ve.Vector3[8];if(_e.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const n=this._getFacetAt(e,t),o=-(n.x*e+n.z*t+n.w)/n.y;return _e.TransformCoordinatesFromFloatsToRef(0,o,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new _e(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),r=ve.Matrix[5];s.invertToRef(r);const n=ve.Vector3[8];if(_e.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t);return _e.TransformNormalFromFloatsToRef(o.x,o.y,o.z,s,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),s=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[s*this._subdivisionsX+i];let n;return n=te.maxHeight){h=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(n=0;n<=e.subdivisions;n++)for(o=0;o<=e.subdivisions;o++){const t=new _e(o*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-n)*e.height/e.subdivisions-e.height/2),c=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let u=e.buffer[c]/255,d=e.buffer[c+1]/255,_=e.buffer[c+2]/255;const p=e.buffer[c+3]/255;h&&(u=1-u,d=1-d,_=1-_);const f=u*a.r+d*a.g+_*a.b;t.y=p>=l?e.minHeight+(e.maxHeight-e.minHeight)*f:e.minHeight-J,e.heightBuffer&&(e.heightBuffer[n*(e.subdivisions+1)+o]=t.y),i.push(t.x,t.y,t.z),s.push(0,0,0),r.push(o/e.subdivisions,1-n/e.subdivisions)}for(n=0;n=e.minHeight,c=i[3*r+1]>=e.minHeight,u=i[3*a+1]>=e.minHeight;h&&c&&u&&(t.push(s),t.push(r),t.push(a)),i[3*l+1]>=e.minHeight&&h&&u&&(t.push(l),t.push(s),t.push(a))}Wn.ComputeNormals(i,t,s);const c=new Wn;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function Iu(e,t={},i){const s=new Cu(e,i);return s._setReady(!1),s._subdivisionsX=t.subdivisionsX||t.subdivisions||1,s._subdivisionsY=t.subdivisionsY||t.subdivisions||1,s._width=t.width||1,s._height=t.height||1,s._maxX=s._width/2,s._maxZ=s._height/2,s._minX=-s._maxX,s._minZ=-s._maxZ,Eu(t).applyToMesh(s,t.updatable),s._setReady(!0),s}function Ru(e,t,i=null){const s=new ha(e,i);return Au(t).applyToMesh(s,t.updatable),s}function Mu(e,t,i={},s=null){const r=i.width||10,n=i.height||10,o=i.subdivisions||1,a=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new Ee(.3,.59,.11),c=i.alphaFilter||0,u=i.updatable,d=i.onReady;s=s||re.LastCreatedScene;const _=new Cu(e,s);let p;_._subdivisionsX=o,_._subdivisionsY=o,_._width=r,_._height=n,_._maxX=_._width/2,_._maxZ=_._height/2,_._minX=-_._maxX,_._minZ=-_._maxZ,_._setReady(!1),i.passHeightBufferInCallback&&(p=new Float32Array((o+1)*(o+1)));const f=(e,t,i)=>{Pu({width:r,height:n,subdivisions:o,minHeight:a,maxHeight:l,colorFilter:h,buffer:e,bufferWidth:t,bufferHeight:i,alphaFilter:c,heightBuffer:p}).applyToMesh(_,u),d&&d(_,p),_._setReady(!0)};if("string"==typeof t){const e=e=>{const t=e.width,i=e.height;if(s.isDisposed)return;const r=s?.getEngine().resizeImageBitmap(e,t,i);f(r,t,i)};Ds.LoadImage(t,e,i.onError?i.onError:()=>{},s.offlineProvider)}else f(t.data,t.width,t.height);return _}const Ou={CreateGround:Iu,CreateGroundFromHeightMap:Mu,CreateTiledGround:Ru};function Du(e){const t=[],i=[],s=[],r=[],n=e.diameter||1,o=e.thickness||.5,a=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,h=a+1;for(let e=0;e<=a;e++){const l=e/a,c=e*Math.PI*2/a-Math.PI/2,u=me.Translation(n/2,0,0).multiply(me.RotationY(c));for(let n=0;n<=a;n++){const c=1-n/a,d=n*Math.PI*2/a+Math.PI,_=Math.cos(d),p=Math.sin(d);let f=new _e(_,p,0),m=f.scale(o/2);const g=new de(l,c);m=_e.TransformCoordinates(m,u),f=_e.TransformNormal(f,u),i.push(m.x,m.y,m.z),s.push(f.x,f.y,f.z),r.push(g.x,Xn.UseOpenGLOrientationForUV?1-g.y:g.y);const v=(e+1)%h,x=(n+1)%h;t.push(e*h+n),t.push(e*h+x),t.push(v*h+n),t.push(e*h+x),t.push(v*h+x),t.push(v*h+n)}}Wn._ComputeSides(l,i,t,s,r,e.frontUVs,e.backUVs);const c=new Wn;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function wu(e,t={},i){const s=new ha(e,i);return t.sideOrientation=ha._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,Du(t).applyToMesh(s,t.updatable),s}Wn.CreateGround=Eu,Wn.CreateTiledGround=Au,Wn.CreateGroundFromHeightMap=Pu,ha.CreateGround=(e,t,i,s,r,n)=>Iu(e,{width:t,height:i,subdivisions:s,updatable:n},r),ha.CreateTiledGround=(e,t,i,s,r,n,o,a,l)=>Ru(e,{xmin:t,zmin:i,xmax:s,zmax:r,subdivisions:n,precision:o,updatable:l},a),ha.CreateGroundFromHeightMap=(e,t,i,s,r,n,o,a,l,h,c)=>Mu(e,t,{width:i,height:s,subdivisions:r,minHeight:n,maxHeight:o,updatable:l,onReady:h,alphaFilter:c},a);const Nu={CreateTorus:wu};Wn.CreateTorus=Du,ha.CreateTorus=(e,t,i,s,r,n,o)=>wu(e,{diameter:t,thickness:i,tessellation:s,sideOrientation:o,updatable:n},r);class Fu{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=Fu._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=wu("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const t=new cu("targetMat",e);t.specularColor=Ee.Black(),t.emissiveColor=new Ee(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new Ua(_e.Zero(),new _e(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}}Fu._IdCounter=0;class Lu extends Fu{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new Ua(_e.Zero(),_e.Forward())}}class Bu{}class ku{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._scene.activeCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated}constructor(e,t={}){if(this.webVROptions=t,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new K,this.onAfterEnteringVRObservable=new K,this.onExitingVRObservable=new K,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=ku.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new _e(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new _e(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new Ee(.2,.2,1),this._pickedGazeColor=new Ee(0,0,1),this.onNewMeshSelected=new K,this.onNewMeshPicked=new K,this.onBeforeCameraTeleport=new K,this.onAfterCameraTeleport=new K,this.onSelectedMeshUnselected=new K,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock||(this._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=e=>{e.type!==kh.POSE_ENABLED&&(e.leftStick&&e.onleftstickchanged((e=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))})),e.rightStick&&e.onrightstickchanged((e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)})),e.type===kh.XBOX&&(e.onbuttondown((e=>{this._interactionsEnabled&&e===Oh.A&&this._cameraGazer._selectionPointerDown()})),e.onbuttonup((e=>{this._interactionsEnabled&&e===Oh.A&&this._cameraGazer._selectionPointerUp()}))))},this._workingVector=_e.Zero(),this._workingQuaternion=fe.Identity(),this._workingMatrix=me.Identity(),Ne.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement(),"getVRDisplays"in navigator||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new _e(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new cc("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof oc&&this._scene.activeCamera.rotation)){const e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(fe.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?Tu.IsSessionSupportedAsync("immersive-vr").then((i=>{i?(Ne.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then((t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new Lu((()=>this.xr.baseExperience.camera),e),this.xr.baseExperience.onStateChangedObservable.add((e=>{switch(e){case yu.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case yu.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case yu.IN_XR:this._hasEnteredVR=!0;break;case yu.NOT_IN_XR:this._hasEnteredVR=!1}}))}))):this._completeVRInit(e,t)})):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new Qc("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new Lu((()=>this.currentVRCamera),e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let e=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";e+=".babylonVRicon.vrdisplaypresenting { display: none; }";const t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",(()=>{this.isInVRMode||this.enterVR()}));const i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add((()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())}),lr.POINTERDOUBLETAP,!1),e.onDisposeObservable.add((()=>{this.dispose()})),this._updateButtonVisibility(),this._circleEase=new sn,this._circleEase.setEasingMode(tn.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add((t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===lr.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===lr.POINTERUP&&this._cameraGazer._selectionPointerUp())})),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===yu.IN_XR||this._fullscreenVRpresenting}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){const e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))}enterVR(){if(this.xr)this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);else{if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){Ne.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=fe.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce((()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})}))),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}}exitVR(){if(this.xr)this.xr.baseExperience.exitXRAsync();else if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){Ne.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this.xr)return void(this.xr.baseExperience.state===yu.IN_XR&&this.xr.pointerSelection.attach());this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>!!(this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}_isTeleportationFloor(e){for(let t=0;t-1||this._floorMeshesCollection.push(e))}removeFloorMesh(e){if(!this._floorMeshesCollection)return;const t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const t=e.floorMeshes||[];if(!t.length){const i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr)return t.forEach((e=>{this.xr.teleportation.addFloorMesh(e)})),void(this.xr.teleportation.attached||this.xr.teleportation.attach());if(!this.xrTestDone){const t=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(t),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};return void this._scene.registerBeforeRender(t)}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction);const t=new zs;t.vignetteColor=new Ae(0,0,0,0),t.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}}_checkTeleportWithRay(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;const e=fe.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,fe.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),_e.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const s=new Ua(i,this._workingVector),r=this._scene.pickWithRay(s,this._raySelectionPredicate);r&&r.pickedPoint&&r.pickedMesh&&this._isTeleportationFloor(r.pickedMesh)&&r.distance<5&&this.teleportCamera(r.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_createTeleportationCircles(){this._teleportationTarget=Iu("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=new uu("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;const t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();const i=new cu("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;const s=wu("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);s.isPickable=!1,s.parent=this._teleportationTarget;const r=new Ft("animationInnerCircle","position.y",30,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),r.setKeys(n);const o=new _n;o.setEasingMode(tn.EASINGMODE_EASEINOUT),r.setEasingFunction(o),s.animations=[],s.animations.push(r),this._scene.beginAnimation(s,0,60,!0),this._hideTeleportationTarget()}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof ac))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=fe.FromRotationMatrix(me.RotationY(Math.PI/4*this._rotationAngle)),i=new Ft("animationRotation","rotationQuaternion",90,Ft.ANIMATIONTYPE_QUATERNION,Ft.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),s.push({frame:6,value:t}),i.setKeys(s),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const r=new Ft("animationPP","vignetteWeight",90,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),r.setKeys(n),r.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(r);const o=new Ft("animationPP2","vignetteStretch",90,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:10}),a.push({frame:6,value:0}),o.setKeys(a),o.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(o),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}teleportCamera(e){if(!(this.currentVRCamera instanceof ac))return;let t,i;if(this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==ku.TELEPORTATIONMODE_CONSTANTSPEED){i=90;const e=_e.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];const s=new Ft("animationCameraTeleportation","position",90,Ft.ANIMATIONTYPE_VECTOR3,Ft.ANIMATIONLOOPMODE_CONSTANT),r=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];s.setKeys(r),s.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(s),this._postProcessMove.animations=[];const n=Math.round(i/2),o=new Ft("animationPP","vignetteWeight",90,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:n,value:8}),a.push({frame:i,value:0}),o.setKeys(a),this._postProcessMove.animations.push(o);const l=new Ft("animationPP2","vignetteStretch",90,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:n,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,(()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)})),this._hideTeleportationTarget()}setLaserColor(e,t=this._pickedLaserColor){this._pickedLaserColor=t}setLaserLightingState(e=!0){}setGazeColor(e,t=this._pickedGazeColor){this._pickedGazeColor=t}changeLaserColor(e){this.updateControllerLaserColor}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}}ku.TELEPORTATIONMODE_CONSTANTTIME=0,ku.TELEPORTATIONMODE_CONSTANTSPEED=1;const Vu=function(){const e={root:0,found:!1};return function(t,i,s,r){e.root=0,e.found=!1;const n=i*i-4*t*s;if(n<0)return e;const o=Math.sqrt(n);let a=(-i-o)/(2*t),l=(-i+o)/(2*t);if(a>l){const e=l;l=a,a=e}return a>0&&a0&&l=0))}_canDoCollision(e,t,i,s){const r=_e.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(r>this._velocityWorldLength+n+t||!((e,t,i,s)=>!(e.x>i.x+s||i.x-s>t.x||e.y>i.y+s||i.y-s>t.y||e.z>i.z+s||i.z-s>t.z))(i,s,this._basePointWorld,this._velocityWorldLength+n))}_testTriangle(e,t,i,s,r,n,o){let a,l=!1;t||(t=[]),t[e]||(t[e]=new Nr(0,0,0,0),t[e].copyFromPoints(i,s,r));const h=t[e];if(!n&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;const c=h.signedDistanceTo(this._basePoint),u=_e.Dot(h.normal,this._velocity);if(Uu.DoubleSidedCheck&&u>1e-4)return;if(0==u){if(Math.abs(c)>=1)return;l=!0,a=0}else{a=(-1-c)/u;let e=(1-c)/u;if(a>e){const t=e;e=a,a=t}if(a>1||e<0)return;a<0&&(a=0),a>1&&(a=1)}this._collisionPoint.copyFromFloats(0,0,0);let d=!1,_=1;if(l||(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(a,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,s,r,h.normal)&&(d=!0,_=a,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!d){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*_e.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=Vu(e,t,n,_);o.found&&(_=o.root,d=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(s,this._tempVector),t=2*_e.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=Vu(e,t,n,_),o.found&&(_=o.root,d=!0,this._collisionPoint.copyFrom(s)),this._basePoint.subtractToRef(r,this._tempVector),t=2*_e.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=Vu(e,t,n,_),o.found&&(_=o.root,d=!0,this._collisionPoint.copyFrom(r)),s.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let a=this._edge.lengthSquared(),l=_e.Dot(this._edge,this._velocity),h=_e.Dot(this._edge,this._baseToVertex);if(e=a*-this._velocitySquaredLength+l*l,t=2*(a*_e.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=Vu(e,t,n,_),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(_=o.root,d=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(r.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=_e.Dot(this._edge,this._velocity),h=_e.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*_e.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=Vu(e,t,n,_),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(_=o.root,d=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=_e.Dot(this._edge,this._velocity),h=_e.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*_e.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=Vu(e,t,n,_),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(_=o.root,d=!0,this._edge.scaleInPlace(e),r.addToRef(this._edge,this._collisionPoint))}}if(d){const e=_*_*this._velocitySquaredLength;(!this.collisionFound||e=s)return void r.copyFrom(e);const a=n?n.collisionMask:i.collisionMask;i._initialize(e,t,o);const l=n&&n.surroundingMeshes||this._scene.meshes;for(let e=0;enew Gu;class zu{constructor(e,t,i,s=""){let r;this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new K,this.onErrorObservable=new K,this.onBindObservable=new K,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=di.WGSL,this.name=e,this._key=s,this._engine=i,this.uniqueId=zu._UniqueIdSeed++,this.defines=t.defines??"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=t.entryPoint??"main",this._shaderStore=Bi.GetShadersStore(this._shaderLanguage),this._shaderRepository=Bi.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=Bi.GetIncludesShadersStore(this._shaderLanguage);const n=kt()?this._engine.getHostDocument():null;r="string"==typeof e?e:e.computeSource?"source:"+e.computeSource:e.computeElement?n?.getElementById(e.computeElement)||e.computeElement:e.compute||e;const o={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(r,"Compute","",(i=>{Ei(o),function(e,t,i,s){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),Ni(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const r=function(e,t,i){let s=e;const r=t.defines,n=wi(t,i);return t.processor?.preProcessor&&(s=t.processor.preProcessor(s,r,n,t.isFragment,t.processingContext)),s=Di(s,n,t),t.processor?.postProcessor&&(s=t.processor.postProcessor(s,r,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),i._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}(e,t,s);i(r,e)}))}(i,o,(s=>{this._rawComputeSourceCode=i,t.processFinalCode&&(s=t.processFinalCode(s));const r=Pi(s,"",o);this._useFinalCode(r.vertexCode,e)}),this._engine)}))}_useFinalCode(e,t){if(t){const i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}setTimeout((()=>{this._checkIsReady(e)}),16)}_loadShader(e,t,i,s){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void s(Gt(e));if("source:"===e.substr(0,7))return void s(e.substr(7));if("base64:"===e.substr(0,7))return void s(window.atob(e.substr(7)));if(this._shaderStore[e+t+"Shader"])return void s(this._shaderStore[e+t+"Shader"]);if(i&&this._shaderStore[e+i+"Shader"])return void s(this._shaderStore[e+i+"Shader"]);let r;r="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(r+"."+t.toLowerCase()+".fx",s)}get computeSourceCode(){return this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._pipelineContext?._getComputeShaderCode()??this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){const e=this.defines,t=this._pipelineContext;this._isReady=!1;try{const i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,(e=>{e&&e.numErrors>0?this._processCompilationErrors(e,t):(this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t))})),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_processCompilationErrors(e,t=null){if(this._compilationError="",Ne.Error("Unable to compile compute effect:"),this.defines&&Ne.Error("Defines:\n"+this.defines),zu.LogShaderCodeOnCompilationError){const e=this._pipelineContext?._getComputeShaderCode();e&&(Ne.Error("Compute code:"),Ne.Error(e))}if("string"==typeof e)this._compilationError=e,Ne.Error("Error: "+this._compilationError);else for(const t of e.messages){let e="";void 0!==t.line&&(e+="Line "+t.line+", "),void 0!==t.offset&&(e+="Offset "+t.offset+", "),void 0!==t.length&&(e+="Length "+t.length+", "),e+=t.type+": "+t.text,this._compilationError&&(this._compilationError+="\n"),this._compilationError+=e,Ne.Error(e)}t&&(this._pipelineContext=t,this._isReady=!0),this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){Bi.GetShadersStore(di.WGSL)[`${e}ComputeShader`]=t}}var Wu;zu._UniqueIdSeed=0,zu.LogShaderCodeOnCompilationError=!0,function(e){e[e.Texture=0]="Texture",e[e.StorageTexture=1]="StorageTexture",e[e.UniformBuffer=2]="UniformBuffer",e[e.StorageBuffer=3]="StorageBuffer",e[e.TextureWithoutSampler=4]="TextureWithoutSampler",e[e.Sampler=5]="Sampler",e[e.ExternalTexture=6]="ExternalTexture",e[e.DataBuffer=7]="DataBuffer"}(Wu||(Wu={})),qs.prototype.createComputeEffect=function(e,t){throw new Error("createComputeEffect: This engine does not support compute shaders!")},qs.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")},qs.prototype.createComputeContext=function(){},qs.prototype.computeDispatch=function(e,t,i,s,r,n,o){throw new Error("computeDispatch: This engine does not support compute shaders!")},qs.prototype.computeDispatchIndirect=function(e,t,i,s,r,n){throw new Error("computeDispatchIndirect: This engine does not support compute shaders!")},qs.prototype.areAllComputeEffectsReady=function(){return!0},qs.prototype.releaseComputeEffects=function(){},qs.prototype._prepareComputePipelineContext=function(e,t,i,s,r){},qs.prototype._rebuildComputeEffects=function(){},ns.prototype._executeWhenComputeStateIsCompiled=function(e,t){t(null)},qs.prototype._releaseComputeEffect=function(e){},qs.prototype._deleteComputePipelineContext=function(e){};class Hu{constructor(){this._gpuTimeInFrameId=-1,this.counter=new wr}_addDuration(e,t){e{const n=()=>{this.dispatch(e,t,i)?r():setTimeout(n,s)};n()}))}serialize(){const e=St.Serialize(this);e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={};for(const t in this._bindings){const i=this._bindings[t],s=i.object;switch(i.type){case Wu.Texture:case Wu.TextureWithoutSampler:case Wu.StorageTexture:{const r=s.serialize();r&&(e.textures[t]=r,e.bindings[t]={type:i.type});break}case Wu.UniformBuffer:}}return e}static Parse(e,t,i){const s=St.Parse((()=>new Xu(e.name,t.getEngine(),e.shaderPath,e.options)),e,t,i);for(const r in e.textures){const n=e.bindings[r],o=Pa.Parse(e.textures[r],t,i);n.type===Wu.Texture?s.setTexture(r,o):n.type===Wu.TextureWithoutSampler?s.setTexture(r,o,!1):s.setStorageTexture(r,o)}return s}static _BufferIsDataBuffer(e){return void 0!==e.underlyingResource}}Ze([rt()],Xu.prototype,"name",void 0),Ze([rt()],Xu.prototype,"fastMode",void 0),z("BABYLON.ComputeShader",Xu);class Yu{constructor(e,t,i,s,r,n){this.entries=[],this._boundingVectors=new Array,this._capacity=i,this._depth=s,this._maxDepth=r,this._creationFunc=n,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks)for(let t=0;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{const i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},Qu.CreationFuncForSubMeshes=(e,t)=>{e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},Hr.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(or.NAME_OCTREE);i||(i=new ju(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new Qu(Qu.CreationFuncForMeshes,e,t));const s=this.getWorldExtends();return this._selectionOctree.update(s.min,s.max,this.meshes),this._selectionOctree},Object.defineProperty(Hr.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),_o.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){const i=this.getScene();let s=i._getComponent(or.NAME_OCTREE);s||(s=new ju(i),i._addComponent(s)),this._submeshesOctree||(this._submeshesOctree=new Qu(Qu.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);const r=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(r.minimumWorld,r.maximumWorld,this.subMeshes),this._submeshesOctree};class ju{constructor(e){this.name=or.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new Ua(_e.Zero(),new _e(1,1,1)),(e=e||re.LastCreatedScene)&&(this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=e=>this.getActiveSubMeshCandidates(e),this.scene.getCollidingSubMeshCandidates=(e,t)=>this.getCollidingSubMeshCandidates(e,t),this.scene.getIntersectingSubMeshCandidates=(e,t)=>this.getIntersectingSubMeshCandidates(e,t))}register(){this.scene.onMeshRemovedObservable.add((e=>{const t=this.scene.selectionOctree;if(null!=t){const i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}})),this.scene.onMeshImportedObservable.add((e=>{const t=this.scene.selectionOctree;null!=t&&t.addMesh(e)}))}getActiveMeshCandidates(){return this.scene._selectionOctree?.select(this.scene.frustumPlanes)||this.scene._getDefaultMeshCandidates()}getActiveSubMeshCandidates(e){return e._submeshesOctree&&e.useOctreeForRenderingSelection?e._submeshesOctree.select(this.scene.frustumPlanes):this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){return e._submeshesOctree&&e.useOctreeForPicking?(Ua.TransformToRef(t,e.getWorldMatrix(),this._tempRay),e._submeshesOctree.intersectsRay(this._tempRay)):this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){const i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z);return e._submeshesOctree.intersects(t._basePointWorld,i)}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}}function Ku(e){const t=e.height||2;let i=0===e.diameterTop?0:e.diameterTop||e.diameter||1,s=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;i=i||1e-5,s=s||1e-5;const r=0|(e.tessellation||24),n=0|(e.subdivisions||1),o=!!e.hasRings,a=!!e.enclose,l=0===e.cap?0:e.cap||ha.CAP_ALL,h=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,c=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,u=e.faceUV||new Array(3),d=e.faceColors,_=2+(1+(1!==h&&a?2:0))*(o?n:1);let p;for(p=0;p<_;p++)d&&void 0===d[p]&&(d[p]=new Ae(1,1,1,1));for(p=0;p<_;p++)u&&void 0===u[p]&&(u[p]=new pe(0,0,1,1));const f=[],m=[],g=[],v=[],x=[],b=2*Math.PI*h/r;let T,y,S;const C=(s-i)/2/t,E=_e.Zero(),A=_e.Zero(),P=_e.Zero(),I=_e.Zero(),R=_e.Zero(),M=Xr.Y;let O,D,w,N=1,F=1,L=0,B=0;for(O=0;O<=n;O++)for(y=O/n,S=(y*(i-s)+s)/2,N=o&&0!==O&&O!==n?2:1,w=0;w{const n=e?i/2:s/2;if(0===n)return;let o,a,l;const c=e?u[_-1]:u[0];let p=null;d&&(p=e?d[_-1]:d[0]);const b=m.length/3,T=e?t/2:-t/2,y=new _e(0,T,0);m.push(y.x,y.y,y.z),g.push(0,e?1:-1,0);const S=c.y+.5*(c.w-c.y);v.push(c.x+.5*(c.z-c.x),Xn.UseOpenGLOrientationForUV?1-S:S),p&&x.push(p.r,p.g,p.b,p.a);const C=new de(.5,.5);for(l=0;l<=r;l++){o=2*Math.PI*l*h/r;const t=Math.cos(-o),i=Math.sin(-o);a=new _e(t*n,T,i*n);const s=new de(t*C.x+.5,i*C.y+.5);m.push(a.x,a.y,a.z),g.push(0,e?1:-1,0);const u=c.y+(c.w-c.y)*s.y;v.push(c.x+(c.z-c.x)*s.x,Xn.UseOpenGLOrientationForUV?1-u:u),p&&x.push(p.r,p.g,p.b,p.a)}for(l=0;l(void 0!==o&&o instanceof Hr||(void 0!==o&&(l=a||ha.DEFAULTSIDE,a=o),o=n,n=1),$u(e,{height:t,diameterTop:i,diameterBottom:s,tessellation:r,subdivisions:n,sideOrientation:l,updatable:a},o)),Et.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new Zu(e,_e.Zero(),t)));class Zu extends ua{constructor(e,t,i){super(e,i),this.groundColor=new Ee(0,0,0),this.direction=t||_e.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=_e.Normalize(e.subtract(_e.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=_e.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){const i=_e.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=me.Identity()),this._worldMatrix}getTypeID(){return ua.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}Ze([ot()],Zu.prototype,"groundColor",void 0),Ze([ht()],Zu.prototype,"direction",void 0),z("BABYLON.HemisphericLight",Zu);class Ju{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new Zu("shared gizmo light",new _e(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=Ee.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==Ju._DefaultUtilityLayer?Ju._CreateDefaultUtilityLayerFromScene(re.LastCreatedScene):Ju._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return Ju._DefaultUtilityLayer=new Ju(e),Ju._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{Ju._DefaultUtilityLayer=null})),Ju._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==Ju._DefaultKeepDepthUtilityLayer&&(Ju._DefaultKeepDepthUtilityLayer=new Ju(re.LastCreatedScene),Ju._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,Ju._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{Ju._DefaultKeepDepthUtilityLayer=null}))),Ju._DefaultKeepDepthUtilityLayer}constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new K,this.utilityLayerScene=new Hr(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add((t=>{if(!this.utilityLayerScene.activeCamera)return;if(!this.pickingEnabled)return;if(!this.processAllEvents&&t.type!==lr.POINTERMOVE&&t.type!==lr.POINTERUP&&t.type!==lr.POINTERDOWN&&t.type!==lr.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const i=t.event;if(e.isPointerCaptured(i.pointerId))return void(this._pointerCaptures[i.pointerId]=!1);const s=i=>{let s=null;if(t.nearInteractionPickingInfo)s=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new tr;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)s=t.originalPickingInfo;else{let r=null;this._renderCamera&&(r=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),s=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),r&&(i._activeCamera=r)}return s},r=s(this.utilityLayerScene);if(!t.ray&&r&&(t.ray=r.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=lr.POINTERDOWN)return t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new ur(t.type,t.event,r),t.type),void(t.type===lr.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1));if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)r&&r.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new ur(t.type,t.event,r),t.type),t.skipOnPointerObservable=!0);else{const i=s(e),n=t.event;i&&r&&(0===r.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):t.type===lr.POINTERDOWN?this._pointerCaptures[n.pointerId]=!0:t.type!==lr.POINTERMOVE&&t.type!==lr.POINTERUP||(this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,i,n)):!this._pointerCaptures[n.pointerId]&&(r.distance0)):!this._pointerCaptures[n.pointerId]&&r.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):(t.type!==lr.POINTERMOVE&&t.type!==lr.POINTERUP||this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,r,n))),t.type===lr.POINTERUP&&this._pointerCaptures[n.pointerId]&&(this._pointerCaptures[n.pointerId]=!1))}})),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add((e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add((()=>{this.dispose()})),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new ur(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){const e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}}var ed,td,id;Ju._DefaultUtilityLayer=null,Ju._DefaultKeepDepthUtilityLayer=null,function(e){e[e.Origin=0]="Origin",e[e.Pivot=1]="Pivot"}(ed||(ed={})),function(e){e[e.World=0]="World",e[e.Local=1]="Local"}(td||(td={}));class sd{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach((e=>{e.dispose()})),e.parent=this._rootMesh,this._customMeshSet=!0}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){this._additionalTransformNode=e}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;const t=e==td.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=Ju.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=ed.Origin,this._updateScale=!0,this._coordinatesMode=td.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=me.RotationY(Math.PI),this._rootMesh=new ha("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=fe.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add((()=>{this._update()}))}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh)if(this.anchorPoint==ed.Pivot&&e.getAbsolutePivotPoint){const t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{const t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new _e(0,0,0);this._rootMesh.position.copyFrom(i)}if(this.updateGizmoRotationToMatchAttachedMesh){const t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName()?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,sd.PreserveScaling?t:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){const t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,ve.Vector3[0]);let s=this.scaleRatio;if(t.mode==In.ORTHOGRAPHIC_CAMERA)t.orthoTop&&t.orthoBottom&&(s*=t.orthoTop-t.orthoBottom);else{const e=t.getScene().useRightHandedSystem?_e.RightHandedForwardReadOnly:_e.LeftHandedForwardReadOnly,i=t.getDirection(e);s*=_e.Dot(ve.Vector3[0],i)}this._rootMesh.scaling.setAll(s),e._getWorldMatrixDeterminant()<0&&!sd.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}this.additionalTransformNode&&(this._rootMesh.computeWorldMatrix(!0),this._rootMesh.getWorldMatrix().multiplyToRef(this.additionalTransformNode.getWorldMatrix(),ve.Matrix[0]),ve.Matrix[0].decompose(this._rootMesh.scaling,this._rootMesh.rotationQuaternion,this._rootMesh.position))}_handlePivotMatrixInverse(e,t,i){if(e.isUsingPivotMatrix()&&!e.isUsingPostMultiplyPivotMatrix())return e.getPivotMatrix().invertToRef(ve.Matrix[5]),void ve.Matrix[5].multiplyToRef(t,i);i.copyFrom(t)}_matrixChanged(){if(this._attachedNode)if(this._attachedNode._isCamera){const e=this._attachedNode;let t,i;if(e.parent){const i=ve.Matrix[1];e.parent._worldMatrix.invertToRef(i),this._attachedNode._worldMatrix.multiplyToRef(i,ve.Matrix[0]),t=ve.Matrix[0]}else t=this._attachedNode._worldMatrix;if(e.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(t,ve.Matrix[1]),i=ve.Matrix[1]):i=t,i.decompose(ve.Vector3[1],ve.Quaternion[0],ve.Vector3[0]),"FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName()){const e=this._attachedNode;e.rotation=ve.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(ve.Quaternion[0]),e.rotationQuaternion.normalize())}e.position.copyFrom(ve.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){const e=this._attachedNode;if(e.parent){const t=ve.Matrix[0],i=ve.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i);const s=ve.Matrix[4];if(this._handlePivotMatrixInverse(e,i,s),s.decompose(ve.Vector3[0],ve.Quaternion[0],e.position,sd.PreserveScaling?e:void 0,sd.UseAbsoluteScaling),ve.Quaternion[0].normalize(),e.isUsingPivotMatrix()){const t=ve.Quaternion[1];fe.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,t);const i=ve.Matrix[2];me.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,i);const s=ve.Matrix[2];t.toRotationMatrix(s);const r=e.getPivotMatrix(),n=ve.Matrix[3];r.invertToRef(n),r.multiplyToRef(i,ve.Matrix[4]),ve.Matrix[4].multiplyToRef(s,ve.Matrix[5]),ve.Matrix[5].multiplyToRef(n,ve.Matrix[6]),ve.Matrix[6].getTranslationToRef(ve.Vector3[1]),e.position.subtractInPlace(ve.Vector3[1])}}else{const t=ve.Matrix[4];this._handlePivotMatrixInverse(e,this._attachedNode._worldMatrix,t),t.decompose(ve.Vector3[0],ve.Quaternion[0],e.position,sd.PreserveScaling?e:void 0,sd.UseAbsoluteScaling)}ve.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(ve.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(ve.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=ve.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){const e=this._attachedNode,t=e.getParent();if(t){const i=ve.Matrix[0],s=ve.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,s),e.getLocalMatrix().copyFrom(s)}else e.getLocalMatrix().copyFrom(e.getFinalMatrix());e.markAsDirty()}else{const e=this._attachedNode;if(e.getTypeID){const t=e.getTypeID();if(t===ua.LIGHTTYPEID_DIRECTIONALLIGHT||t===ua.LIGHTTYPEID_SPOTLIGHT||t===ua.LIGHTTYPEID_POINTLIGHT){const t=e.parent;if(t){const i=ve.Matrix[0],s=ve.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,s),s.decompose(void 0,ve.Quaternion[0],ve.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,ve.Quaternion[0],ve.Vector3[0]);e.position=new _e(ve.Vector3[0].x,ve.Vector3[0].y,ve.Vector3[0].z),e.direction&&(e.direction=new _e(e.direction.x,e.direction.y,e.direction.z))}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach((e=>{e.material=t,e.color&&(e.color=t.diffuseColor)}))}static GizmoAxisPointerObserver(e,t){let i=!1;return e.utilityLayerScene.onPointerObservable.add((e=>{if(e.pickInfo){if(e.type===lr.POINTERMOVE){if(i)return;t.forEach((t=>{if(t.colliderMeshes&&t.gizmoMeshes){const i=-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh),s=t.dragBehavior.enabled?i||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=s,e.color&&(e.color=s.diffuseColor)}))}}))}e.type===lr.POINTERDOWN&&t.has(e.pickInfo.pickedMesh?.parent)&&(i=!0,t.get(e.pickInfo.pickedMesh?.parent).active=!0,t.forEach((t=>{const i=(-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh)||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=i,e.color&&(e.color=i.diffuseColor)}))}))),e.type===lr.POINTERUP&&t.forEach((e=>{e.active=!1,i=!1,e.gizmoMeshes.forEach((t=>{t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)}))}))}}))}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}sd.PreserveScaling=!1,sd.UseAbsoluteScaling=!0;class rd extends sd{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreateArrow(e,t,i=1,s=!1){const r=new lo("arrow",e),n=$u("cylinder",{diameterTop:0,height:.075,diameterBottom:.0375*(1+(i-1)/4),tessellation:96},e),o=$u("cylinder",{diameterTop:.005*i,height:.275,diameterBottom:.005*i,tessellation:96},e);return n.parent=r,n.material=t,n.rotation.x=Math.PI/2,n.position.z+=.3,o.parent=r,o.material=t,o.position.z+=.1375,o.rotation.x=Math.PI/2,s&&(o.visibility=0,n.visibility=0),r}static _CreateArrowInstance(e,t){const i=new lo("arrow",e);for(const e of t.getChildMeshes())e.createInstance(e.name).parent=i;return i}constructor(e,t=Ee.Gray(),i=Ju.DefaultUtilityLayer,s=null,r=1,n=Ee.Yellow(),o=Ee.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new K,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._parent=s,this._coloredMaterial=new cu("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ee(.1,.1,.1)),this._hoverMaterial=new cu("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new cu("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4;const a=rd._CreateArrow(i.utilityLayerScene,this._coloredMaterial,r),l=rd._CreateArrow(i.utilityLayerScene,this._coloredMaterial,r+4,!0);this._gizmoMesh=new ha("",i.utilityLayerScene),this._gizmoMesh.addChild(a),this._gizmoMesh.addChild(l),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let h=0;const c={snapDistance:0};this.dragBehavior=new Xa({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add((e=>{if(this.attachedNode){let t=!1;if(0==this.snapDistance)this.attachedNode.getWorldMatrix().getTranslationToRef(ve.Vector3[2]),ve.Vector3[2].addInPlace(e.delta),this.dragBehavior.validateDrag(ve.Vector3[2])&&(this.attachedNode.position&&this.attachedNode.position.addInPlaceFromFloats(e.delta.x,e.delta.y,e.delta.z),this.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z),this.attachedNode.updateCache(),t=!0);else if(h+=e.dragDistance,Math.abs(h)>this.snapDistance){const i=Math.floor(Math.abs(h)/this.snapDistance);h%=this.snapDistance,e.delta.normalizeToRef(ve.Vector3[1]),ve.Vector3[1].scaleInPlace(this.snapDistance*i),this.attachedNode.getWorldMatrix().getTranslationToRef(ve.Vector3[2]),ve.Vector3[2].addInPlace(ve.Vector3[1]),this.dragBehavior.validateDrag(ve.Vector3[2])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(ve.Vector3[1].x,ve.Vector3[1].y,ve.Vector3[1].z),this.attachedNode.updateCache(),c.snapDistance=this.snapDistance*i*Math.sign(h),this.onSnapObservable.notifyObservers(c),t=!0)}t&&this._matrixChanged()}})),this.dragBehavior.onDragStartObservable.add((()=>{this._dragging=!0})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1}));const u=i._getSharedGizmoLight();u.includedOnlyMeshes=u.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const d={gizmoMeshes:a.getChildMeshes(),colliderMeshes:l.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(l,d),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this._isHovered=!(-1==d.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(d.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(d.gizmoMeshes,e?d.material:d.disableMaterial)}))}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}class nd{get scaleLines(){return this._scaleLines}set scaleLines(e){this._scaleLines=e,this._xAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._yAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor),this._zAxis.scaling.setAll(this._scaleLines*this._scaleLinesFactor)}get xAxis(){return this._xAxis}get yAxis(){return this._yAxis}get zAxis(){return this._zAxis}constructor(e,t=1,i=2,s,r,n,o=1){if(this._scaleLinesFactor=4,this._instanced=!1,this.scene=null,this._scaleLines=1,e=e||re.LastCreatedScene){if(!s){const t=new cu("xAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=Ee.Red().scale(.5),s=rd._CreateArrow(e,t,o)}if(!r){const t=new cu("yAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=Ee.Green().scale(.5),r=rd._CreateArrow(e,t,o)}if(!n){const t=new cu("zAxisMaterial",e);t.disableLighting=!0,t.emissiveColor=Ee.Blue().scale(.5),n=rd._CreateArrow(e,t,o)}this._xAxis=s,this._yAxis=r,this._zAxis=n,this.scaleLines=t,null!=i&&(nd._SetRenderingGroupId(this._xAxis,i),nd._SetRenderingGroupId(this._yAxis,i),nd._SetRenderingGroupId(this._zAxis,i)),this.scene=e,this.update(new _e,_e.Right(),_e.Up(),_e.Forward())}}update(e,t,i,s){this._xAxis.position.copyFrom(e),this._xAxis.setDirection(t),this._yAxis.position.copyFrom(e),this._yAxis.setDirection(i),this._zAxis.position.copyFrom(e),this._zAxis.setDirection(s)}createInstance(){const e=rd._CreateArrowInstance(this.scene,this._xAxis),t=rd._CreateArrowInstance(this.scene,this._yAxis),i=rd._CreateArrowInstance(this.scene,this._zAxis),s=new nd(this.scene,this.scaleLines,null,e,t,i);return s._instanced=!0,s}dispose(){this._xAxis&&this._xAxis.dispose(!1,!this._instanced),this._yAxis&&this._yAxis.dispose(!1,!this._instanced),this._zAxis&&this._zAxis.dispose(!1,!this._instanced),this.scene=null}static _SetRenderingGroupId(e,t){e.getChildMeshes().forEach((e=>{e.renderingGroupId=t}))}}class od extends nd{constructor(e,t,i,s=1){super(e,s),this.pos=_e.Zero(),this.xaxis=_e.Zero(),this.yaxis=_e.Zero(),this.zaxis=_e.Zero(),this.mesh=i,this.bone=t}update(){if(!this.mesh||!this.bone)return;const e=this.bone;e.getAbsolutePositionToRef(this.mesh,this.pos),e.getDirectionToRef(Xr.X,this.mesh,this.xaxis),e.getDirectionToRef(Xr.Y,this.mesh,this.yaxis),e.getDirectionToRef(Xr.Z,this.mesh,this.zaxis),super.update(this.pos,this.xaxis,this.yaxis,this.zaxis)}dispose(){this.mesh&&(this.mesh=null,this.bone=null,super.dispose())}}Object.defineProperty(Hr.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new ad(this)),this._debugLayer},enumerable:!0,configurable:!0}),function(e){e[e.Properties=0]="Properties",e[e.Debug=1]="Debug",e[e.Statistics=2]="Statistics",e[e.Tools=3]="Tools",e[e.Settings=4]="Settings"}(id||(id={}));class ad{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new K),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new K),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||re.LastCreatedScene,this._scene&&this._scene.onDisposeObservable.add((()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()}))}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(const e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(const e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}const t={...ad.Config,...e};this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise((t=>{if(void 0===this.BJSINSPECTOR){const i=e&&e.inspectorURL?e.inspectorURL:ad.InspectorURL;Ds.LoadBabylonScript(i,(()=>{this._createInspector(e),t(this)}))}else this._createInspector(e),t(this)}))}}function ld(e){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],s=[];let r=[];const n=e.width||e.size||1,o=e.height||e.size||1,a=e.depth||e.size||1,l=e.wrap||!1;let h=void 0===e.topBaseAt?1:e.topBaseAt,c=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,c=(c+4)%4;let u=[2,0,3,1][h],d=[2,0,1,3][c],_=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(l){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],_=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let e=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],i=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const s=[17,18,19,16],r=[22,23,20,21];for(;u>0;)e.unshift(e.pop()),s.unshift(s.pop()),u--;for(;d>0;)i.unshift(i.pop()),r.unshift(r.pop()),d--;e=e.flat(),i=i.flat(),_=_.concat(e).concat(i),t.push(s[0],s[2],s[3],s[0],s[1],s[2]),t.push(r[0],r[2],r[3],r[0],r[1],r[2])}const p=[n/2,o/2,a/2];r=_.reduce(((e,t,i)=>e.concat(t*p[i%3])),[]);const f=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,m=e.faceUV||new Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new pe(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new Ae(1,1,1,1));for(let e=0;e<6;e++)if(s.push(m[e].z,Xn.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),s.push(m[e].x,Xn.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),s.push(m[e].x,Xn.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),s.push(m[e].z,Xn.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);Wn._ComputeSides(f,r,t,i,s,e.frontUVs,e.backUVs);const x=new Wn;if(x.indices=t,x.positions=r,x.normals=i,x.uvs=s,g){const e=f===Wn.DOUBLESIDE?v.concat(v):v;x.colors=e}return x}function hd(e){const t=e.width||e.size||1,i=e.height||e.size||1,s=e.depth||e.size||1,r=0|(e.widthSegments||e.segments||1),n=0|(e.heightSegments||e.segments||1),o=0|(e.depthSegments||e.segments||1),a=new me,l=new me,h=new me,c=Eu({width:t,height:s,subdivisionsX:r,subdivisionsY:o});me.TranslationToRef(0,-i/2,0,l),me.RotationZToRef(Math.PI,a),a.multiplyToRef(l,h),c.transform(h);const u=Eu({width:t,height:s,subdivisionsX:r,subdivisionsY:o});me.TranslationToRef(0,i/2,0,h),u.transform(h);const d=Eu({width:i,height:s,subdivisionsX:n,subdivisionsY:o});me.TranslationToRef(-t/2,0,0,l),me.RotationZToRef(Math.PI/2,a),a.multiplyToRef(l,h),d.transform(h);const _=Eu({width:i,height:s,subdivisionsX:n,subdivisionsY:o});me.TranslationToRef(t/2,0,0,l),me.RotationZToRef(-Math.PI/2,a),a.multiplyToRef(l,h),_.transform(h);const p=Eu({width:t,height:i,subdivisionsX:r,subdivisionsY:n});me.TranslationToRef(0,0,-s/2,l),me.RotationXToRef(-Math.PI/2,a),a.multiplyToRef(l,h),p.transform(h);const f=Eu({width:t,height:i,subdivisionsX:r,subdivisionsY:n});return me.TranslationToRef(0,0,s/2,l),me.RotationXToRef(Math.PI/2,a),a.multiplyToRef(l,h),f.transform(h),c.merge([u,_,d,p,f],!0),c}function cd(e,t={},i=null){const s=new ha(e,i);return t.sideOrientation=ha._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,ld(t).applyToMesh(s,t.updatable),s}ad.InspectorURL=`${Ds._DefaultCdnUrl}/v${oo.Version}/inspector/babylon.inspector.bundle.js`,ad.Config={overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0};const ud={CreateBox:cd};function dd(e){const t=0|(e.segments||32),i=e.diameterX||e.diameter||1,s=e.diameterY||e.diameter||1,r=e.diameterZ||e.diameter||1,n=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,o=e.slice&&e.slice<=0?1:e.slice||1,a=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new _e(i/2,s/2,r/2),c=2+t,u=2*c,d=[],_=[],p=[],f=[];for(let e=0;e<=c;e++){const t=e/c,i=t*Math.PI*o;for(let e=0;e<=u;e++){const s=e/u,r=s*Math.PI*2*n,o=me.RotationZ(-i),a=me.RotationY(r),l=_e.TransformCoordinates(_e.Up(),o),c=_e.TransformCoordinates(l,a),d=c.multiply(h),m=c.divide(h).normalize();_.push(d.x,d.y,d.z),p.push(m.x,m.y,m.z),f.push(s,Xn.UseOpenGLOrientationForUV?1-t:t)}if(e>0){const t=_.length/3;for(let i=t-2*(u+1);i+u+21&&(d.push(i),d.push(i+1),d.push(i+u+1)),(ecd(e,{size:t,sideOrientation:r,updatable:s},i);const pd={CreateSphere:_d};function fd(e={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const t=0|Math.max(e.subdivisions?e.subdivisions:2,1),i=0|Math.max(e.tessellation?e.tessellation:16,3),s=Math.max(e.height?e.height:1,0),r=Math.max(e.radius?e.radius:.25,0),n=0|Math.max(e.capSubdivisions?e.capSubdivisions:6,1),o=i,a=t,l=Math.max(e.radiusTop?e.radiusTop:r,0),h=Math.max(e.radiusBottom?e.radiusBottom:r,0),c=s-(l+h),u=2*Math.PI,d=Math.max(e.topCapSubdivisions?e.topCapSubdivisions:n,1),_=Math.max(e.bottomCapSubdivisions?e.bottomCapSubdivisions:n,1),p=Math.acos((h-l)/s);let f=[];const m=[],g=[],v=[];let x=0;const b=[],T=.5*c,y=.5*Math.PI;let S,C;const E=_e.Zero(),A=_e.Zero(),P=Math.cos(p),I=Math.sin(p),R=new de(l*I,T+l*P).subtract(new de(h*I,h*P-T)).length(),M=l*p+R+h*(y-p);let O=0;for(C=0;C<=d;C++){const e=[],t=y-p*(C/d);O+=l*p/d;const i=Math.cos(t),s=Math.sin(t),r=i*l;for(S=0;S<=o;S++){const t=S/o,n=t*u+0,a=Math.sin(n),h=Math.cos(n);A.x=r*a,A.y=T+s*l,A.z=r*h,m.push(A.x,A.y,A.z),E.set(i*a,s,i*h),g.push(E.x,E.y,E.z),v.push(t,Xn.UseOpenGLOrientationForUV?O/M:1-O/M),e.push(x),x++}b.push(e)}const D=s-l-h+P*l-P*h,w=I*(h-l)/D;for(C=1;C<=a;C++){const e=[];O+=R/a;const t=I*(C*(h-l)/a+l);for(S=0;S<=o;S++){const i=S/o,s=i*u+0,r=Math.sin(s),n=Math.cos(s);A.x=t*r,A.y=T+P*l-C*D/a,A.z=t*n,m.push(A.x,A.y,A.z),E.set(r,w,n).normalize(),g.push(E.x,E.y,E.z),v.push(i,Xn.UseOpenGLOrientationForUV?O/M:1-O/M),e.push(x),x++}b.push(e)}for(C=1;C<=_;C++){const e=[],t=y-p-(Math.PI-p)*(C/_);O+=h*p/_;const i=Math.cos(t),s=Math.sin(t),r=i*h;for(S=0;S<=o;S++){const t=S/o,n=t*u+0,a=Math.sin(n),l=Math.cos(n);A.x=r*a,A.y=s*h-T,A.z=r*l,m.push(A.x,A.y,A.z),E.set(i*a,s,i*l),g.push(E.x,E.y,E.z),v.push(t,Xn.UseOpenGLOrientationForUV?O/M:1-O/M),e.push(x),x++}b.push(e)}for(S=0;S_d(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:n,updatable:r},s);const gd={CreateCapsule:md};function vd(e){let t=e.pathArray;const i=e.closeArray||!1,s=e.closePath||!1,r=e.invertUV||!1,n=Math.floor(t[0].length/2);let o=e.offset||n;o=o>n?n:Math.floor(o);const a=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,l=e.uvs,h=e.colors,c=[],u=[],d=[],_=[],p=[],f=[],m=[],g=[];let v;const x=[],b=[];let T,y,S;if(t.length<2){const e=[],i=[];for(y=0;y0&&(R=P[S].subtract(P[S-1]).length(),M=R+m[T],p[T].push(M),m[T]=M),S++;s&&(S--,c.push(P[0].x,P[0].y,P[0].z),R=P[S].subtract(P[0]).length(),M=R+m[T],p[T].push(M),m[T]=M),x[T]=I+E,b[T]=C,C+=I+E}let w,N,F=null,L=null;for(y=0;y{let r=s[0].length;const n=a;let o=0;const l=n._originalBuilderSideOrientation===ha.DOUBLESIDE?2:1;for(let a=1;a<=l;++a)for(let a=0;amd(e,t,i),Wn.CreateCapsule=fd;const bd={CreateRibbon:xd};function Td(e){const t=[],i=[],s=[],r=[],n=e.radius||.5,o=e.tessellation||64,a=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE;t.push(0,0,0),r.push(.5,.5);const h=2*Math.PI*a,c=1===a?h/o:h/(o-1);let u=0;for(let e=0;exd(e,{pathArray:t,closeArray:i,closePath:s,offset:r,updatable:o,sideOrientation:a,instance:l},n);const Sd={CreateDisc:yd};function Cd(e){const t=e.pattern||ha.NO_FLIP,i=e.tileWidth||e.tileSize||1,s=e.tileHeight||e.tileSize||1,r=e.alignHorizontal||0,n=e.alignVertical||0,o=e.width||e.size||1,a=Math.floor(o/i);let l=o-a*i;const h=e.height||e.size||1,c=Math.floor(h/s);let u=h-c*s;const d=i*a/2,_=s*c/2;let p=0,f=0,m=0,g=0,v=0,x=0;if(l>0||u>0){switch(m=-d,g=-_,v=d,x=_,r){case ha.CENTER:l/=2,m-=l,v+=l;break;case ha.LEFT:v+=l,p=-l/2;break;case ha.RIGHT:m-=l,p=l/2}switch(n){case ha.CENTER:u/=2,g-=u,x+=u;break;case ha.BOTTOM:x+=u,f=-u/2;break;case ha.TOP:g-=u,f=u/2}}const b=[],T=[],y=[];y[0]=[0,0,1,0,1,1,0,1],y[1]=[0,0,1,0,1,1,0,1],t!==ha.ROTATE_TILE&&t!==ha.ROTATE_ROW||(y[1]=[1,1,0,1,0,0,1,0]),t!==ha.FLIP_TILE&&t!==ha.FLIP_ROW||(y[1]=[1,0,0,0,0,1,1,1]),t!==ha.FLIP_N_ROTATE_TILE&&t!==ha.FLIP_N_ROTATE_ROW||(y[1]=[0,1,1,1,1,0,0,0]);let S=[];const C=[],E=[];let A=0;for(let e=0;e0||u>0){const e=u>0&&(n===ha.CENTER||n===ha.TOP),o=u>0&&(n===ha.CENTER||n===ha.BOTTOM),h=l>0&&(r===ha.CENTER||r===ha.RIGHT),y=l>0&&(r===ha.CENTER||r===ha.LEFT);let P,I,R,M,O=[];if(e&&h&&(b.push(m+p,g+f,0),b.push(-d+p,g+f,0),b.push(-d+p,g+u+f,0),b.push(m+p,g+u+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=1-l/i,I=1-u/s,R=1,M=1,O=[P,I,R,I,R,M,P,M],t===ha.ROTATE_ROW&&(O=[1-P,1-I,1-R,1-I,1-R,1-M,1-P,1-M]),t===ha.FLIP_ROW&&(O=[1-P,I,1-R,I,1-R,M,1-P,M]),t===ha.FLIP_N_ROTATE_ROW&&(O=[P,1-I,R,1-I,R,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e&&y&&(b.push(d+p,g+f,0),b.push(v+p,g+f,0),b.push(v+p,g+u+f,0),b.push(d+p,g+u+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=0,I=1-u/s,R=l/i,M=1,O=[P,I,R,I,R,M,P,M],(t===ha.ROTATE_ROW||t===ha.ROTATE_TILE&&a%2==0)&&(O=[1-P,1-I,1-R,1-I,1-R,1-M,1-P,1-M]),(t===ha.FLIP_ROW||t===ha.FLIP_TILE&&a%2==0)&&(O=[1-P,I,1-R,I,1-R,M,1-P,M]),(t===ha.FLIP_N_ROTATE_ROW||t===ha.FLIP_N_ROTATE_TILE&&a%2==0)&&(O=[P,1-I,R,1-I,R,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&h&&(b.push(m+p,_+f,0),b.push(-d+p,_+f,0),b.push(-d+p,x+f,0),b.push(m+p,x+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=1-l/i,I=0,R=1,M=u/s,O=[P,I,R,I,R,M,P,M],(t===ha.ROTATE_ROW&&c%2==1||t===ha.ROTATE_TILE&&c%1==0)&&(O=[1-P,1-I,1-R,1-I,1-R,1-M,1-P,1-M]),(t===ha.FLIP_ROW&&c%2==1||t===ha.FLIP_TILE&&c%2==0)&&(O=[1-P,I,1-R,I,1-R,M,1-P,M]),(t===ha.FLIP_N_ROTATE_ROW&&c%2==1||t===ha.FLIP_N_ROTATE_TILE&&c%2==0)&&(O=[P,1-I,R,1-I,R,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&y&&(b.push(d+p,_+f,0),b.push(v+p,_+f,0),b.push(v+p,x+f,0),b.push(d+p,x+f,0),E.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,P=0,I=0,R=l/i,M=u/s,O=[P,I,R,I,R,M,P,M],(t===ha.ROTATE_ROW&&c%2==1||t===ha.ROTATE_TILE&&(c+a)%2==1)&&(O=[1-P,1-I,1-R,1-I,1-R,1-M,1-P,1-M]),(t===ha.FLIP_ROW&&c%2==1||t===ha.FLIP_TILE&&(c+a)%2==1)&&(O=[1-P,I,1-R,I,1-R,M,1-P,M]),(t===ha.FLIP_N_ROTATE_ROW&&c%2==1||t===ha.FLIP_N_ROTATE_TILE&&(c+a)%2==1)&&(O=[P,1-I,R,1-I,R,1-M,P,1-M]),S=S.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e){const e=[];P=0,I=1-u/s,R=1,M=1,e[0]=[P,I,R,I,R,M,P,M],e[1]=[P,I,R,I,R,M,P,M],t!==ha.ROTATE_TILE&&t!==ha.ROTATE_ROW||(e[1]=[1-P,1-I,1-R,1-I,1-R,1-M,1-P,1-M]),t!==ha.FLIP_TILE&&t!==ha.FLIP_ROW||(e[1]=[1-P,I,1-R,I,1-R,M,1-P,M]),t!==ha.FLIP_N_ROTATE_TILE&&t!==ha.FLIP_N_ROTATE_ROW||(e[1]=[P,1-I,R,1-I,R,1-M,P,1-M]);for(let s=0;syd(e,{radius:t,tessellation:i,sideOrientation:n,updatable:r},s);const Ad={CreateTiledPlane:Ed};function Pd(e){const t=e.faceUV||new Array(6),i=e.faceColors,s=e.pattern||ha.NO_FLIP,r=e.width||e.size||1,n=e.height||e.size||1,o=e.depth||e.size||1,a=e.tileWidth||e.tileSize||1,l=e.tileHeight||e.tileSize||1,h=e.alignHorizontal||0,c=e.alignVertical||0,u=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE;for(let e=0;e<6;e++)void 0===t[e]&&(t[e]=new pe(0,0,1,1)),i&&void 0===i[e]&&(i[e]=new Ae(1,1,1,1));const d=r/2,_=n/2,p=o/2,f=[];for(let e=0;e<2;e++)f[e]=Cd({pattern:s,tileWidth:a,tileHeight:l,width:r,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});for(let e=2;e<4;e++)f[e]=Cd({pattern:s,tileWidth:a,tileHeight:l,width:o,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});let m=c;c===ha.BOTTOM?m=ha.TOP:c===ha.TOP&&(m=ha.BOTTOM);for(let e=4;e<6;e++)f[e]=Cd({pattern:s,tileWidth:a,tileHeight:l,width:r,height:o,alignVertical:m,alignHorizontal:h,sideOrientation:u});let g=[],v=[],x=[],b=[];const T=[],y=[],S=[],C=[];let E=0,A=0;for(let e=0;e<6;e++){const s=f[e].positions.length;y[e]=[],S[e]=[];for(let t=0;te+A))),A+=y[e].length,i)for(let t=0;t<4;t++)T.push(i[e].r,i[e].g,i[e].b,i[e].a)}const P=new _e(0,0,p),I=me.RotationY(Math.PI);g=y[0].map((e=>_e.TransformNormal(e,I).add(P))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),v=S[0].map((e=>_e.TransformNormal(e,I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),g=g.concat(y[1].map((e=>e.subtract(P))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[1].map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const R=new _e(d,0,0),M=me.RotationY(-Math.PI/2);g=g.concat(y[2].map((e=>_e.TransformNormal(e,M).add(R))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[2].map((e=>_e.TransformNormal(e,M))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const O=me.RotationY(Math.PI/2);g=g.concat(y[3].map((e=>_e.TransformNormal(e,O).subtract(R))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[3].map((e=>_e.TransformNormal(e,O))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const D=new _e(0,_,0),w=me.RotationX(Math.PI/2);g=g.concat(y[4].map((e=>_e.TransformNormal(e,w).add(D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[4].map((e=>_e.TransformNormal(e,w))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const N=me.RotationX(-Math.PI/2);g=g.concat(y[5].map((e=>_e.TransformNormal(e,N).subtract(D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(S[5].map((e=>_e.TransformNormal(e,N))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),Wn._ComputeSides(u,g,b,v,x);const F=new Wn;if(F.indices=b,F.positions=g,F.normals=v,F.uvs=x,i){const e=u===Wn.DOUBLESIDE?T.concat(T):T;F.colors=e}return F}function Id(e,t,i=null){const s=new ha(e,i);return t.sideOrientation=ha._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,Pd(t).applyToMesh(s,t.updatable),s}Wn.CreateTiledPlane=Cd;const Rd={CreateTiledBox:Id};function Md(e){const t=[],i=[],s=[],r=[],n=e.radius||2,o=e.tube||.5,a=e.radialSegments||32,l=e.tubularSegments||32,h=e.p||2,c=e.q||3,u=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,d=e=>{const t=Math.cos(e),i=Math.sin(e),s=c/h*e,r=Math.cos(s),o=n*(2+r)*.5*t,a=n*(2+r)*i*.5,l=n*Math.sin(s)*.5;return new _e(o,a,l)};let _,p;for(_=0;_<=a;_++){const e=_%a/a*2*h*Math.PI,t=d(e),s=d(e+.01),n=s.subtract(t);let c=s.add(t);const u=_e.Cross(n,c);for(c=_e.Cross(u,n),u.normalize(),c.normalize(),p=0;pOd(e,{radius:t,tube:i,radialSegments:s,tubularSegments:r,p:n,q:o,sideOrientation:h,updatable:l},a);const wd={effect:null,subMesh:null};class Nd extends ml{constructor(e,t,i,s={},r=!0){super(e,t,r),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new me,this._cachedWorldViewProjectionMatrix=new me,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...s}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return-1===this._options.externalTextures.indexOf(e)&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(16*t.length);for(let e=0;et===e||t.startsWith(i)));return s>=0&&this.options.defines.splice(s,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){const s=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const e=s?i._drawWrapper:this._drawWrapper;if(e.effect&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}const r=this.getScene(),n=r.getEngine(),o=[],a=[],l=new Ll;let h=this._shaderPath,c=this._options.uniforms,u=this._options.uniformBuffers,d=this._options.samplers;n.getCaps().multiview&&r.activeCamera&&r.activeCamera.outputRenderTarget&&r.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),-1!==c.indexOf("viewProjection")&&-1===c.indexOf("viewProjectionR")&&c.push("viewProjectionR"));for(let e=0;e4&&(a.push(er.MatricesIndicesExtraKind),a.push(er.MatricesWeightsExtraKind));const t=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),l.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),-1===c.indexOf("boneTextureWidth")&&c.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(t.bones.length+1)),-1===c.indexOf("mBones")&&c.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let _=0;const p=e?e.morphTargetManager:null;if(p){const e=p.supportsUVs&&-1!==o.indexOf("#define UV1"),t=p.supportsTangents&&-1!==o.indexOf("#define TANGENT"),i=p.supportsNormals&&-1!==o.indexOf("#define NORMAL");_=p.numMaxInfluencers||p.numInfluencers,e&&o.push("#define MORPHTARGETS_UV"),t&&o.push("#define MORPHTARGETS_TANGENT"),i&&o.push("#define MORPHTARGETS_NORMAL"),_>0&&o.push("#define MORPHTARGETS"),p.isUsingTextureForTargets&&(o.push("#define MORPHTARGETS_TEXTURE"),-1===c.indexOf("morphTargetTextureIndices")&&c.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),o.push("#define NUM_MORPH_INFLUENCERS "+_);for(let s=0;s<_;s++)a.push(er.PositionKind+s),i&&a.push(er.NormalKind+s),t&&a.push(er.TangentKind+s),e&&a.push(er.UVKind+"_"+s);_>0&&(c=c.slice(),c.push("morphTargetInfluences"),c.push("morphTargetCount"),c.push("morphTargetTextureInfo"),c.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===c.indexOf("bakedVertexAnimationSettings")&&c.push("bakedVertexAnimationSettings"),-1===c.indexOf("bakedVertexAnimationTextureSizeInverted")&&c.push("bakedVertexAnimationTextureSizeInverted"),-1===c.indexOf("bakedVertexAnimationTime")&&c.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),Do(a,0,o)}for(const e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&o.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&(mo(c),go(this,r,o)),r.fogEnabled&&e?.applyFog&&r.fogMode!==Hr.FOGMODE_NONE&&(o.push("#define FOG"),-1===c.indexOf("view")&&c.push("view"),-1===c.indexOf("vFogInfos")&&c.push("vFogInfos"),-1===c.indexOf("vFogColor")&&c.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),-1===c.indexOf("logarithmicDepthConstant")&&c.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(c=c.slice(),u=u.slice(),d=d.slice(),h=this.customShaderNameResolve(this.name,c,u,d,o,a));const f=s?i._getDrawWrapper(void 0,!0):this._drawWrapper,m=f?.effect??null,g=f?.defines??null,v=o.join("\n");let x=m;return g!==v&&(x=n.createEffect(h,{attributes:a,uniformsNames:c,uniformBuffersNames:u,samplers:d,defines:v,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:_},shaderLanguage:this._options.shaderLanguage},n),s?i.setEffect(x,v,this._materialContext):f&&f.setEffect(x,v),this._onEffectCreatedObservable&&(wd.effect=x,wd.subMesh=i??e?.subMeshes[0]??null,this._onEffectCreatedObservable.notifyObservers(wd))),f._wasPreviouslyUsingInstances=!!t,!(!x?.isReady()??1)&&(m!==x&&r.resetCachedMaterial(),f._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),s=t??this.getEffect();s&&(-1!==this._options.uniforms.indexOf("world")&&s.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),s.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),s.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),-1!==this._options.uniforms.indexOf("view")&&s.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){this.bind(e,t,i._drawWrapperOverride?.effect,i)}bind(e,t,i,s){const r=s&&this._storeEffectOnSubMeshes,n=i??(r?s.effect:this.getEffect());if(!n)return;const o=this.getScene();this._activeEffect=n,this.bindOnlyWorldMatrix(e,i);const a=this._options.uniformBuffers;let l=!1;if(n&&a&&a.length>0&&o.getEngine().supportsUniformBuffers)for(let i=0;i0&&Io(t,n);const i=t.bakedVertexAnimationManager;if(i&&i.isEnabled){const e=r?s._drawWrapper:this._drawWrapper;t.bakedVertexAnimationManager?.bind(n,!!e._wasPreviouslyUsingInstances)}}this._afterBind(t,n,s)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let t=0;tnew Nd(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes)),this);t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach((e=>{const t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))})),this.stencil.copyTo(t.stencil);for(const e in this._textures)t.setTexture(e,this._textures[e]);for(const e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(const e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(const e in this._ints)t.setInt(e,this._ints[e]);for(const e in this._uints)t.setUInt(e,this._uints[e]);for(const e in this._floats)t.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(const e in this._colors3)t.setColor3(e,this._colors3[e]);for(const e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(const e in this._colors4)t.setColor4(e,this._colors4[e]);for(const e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(const e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(const e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(const e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(const e in this._matrices)t.setMatrix(e,this._matrices[e]);for(const e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(const e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(const e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(const e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(const e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(const e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(const e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(const e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(const e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){const t=this._textureArrays[e];for(let e=0;enew Nd(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes)),e,t,i);let r;for(r in e.stencil&&s.stencil.parse(e.stencil,t,i),e.textures)s.setTexture(r,Pa.Parse(e.textures[r],t,i));for(r in e.textureArrays){const n=e.textureArrays[r],o=[];for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>Ee.FromArray(e)));s.setColor3Array(r,t)}for(r in e.colors4)s.setColor4(r,Ae.FromArray(e.colors4[r]));for(r in e.colors4Arrays){const t=e.colors4Arrays[r].reduce(((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>Ae.FromArray(e)));s.setColor4Array(r,t)}for(r in e.vectors2)s.setVector2(r,de.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,_e.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,pe.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,fe.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,me.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise(((r,n)=>{const o=new Pt;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=this.Parse(t,i||re.LastCreatedScene,s);e&&(n.name=e),r(n)}else n("Unable to load the ShaderMaterial")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return new Promise(((s,r)=>{const n=new Pt;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const r=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(r.shaderMaterial),a=this.Parse(o,t||re.LastCreatedScene,i);a.snippetId=e,s(a)}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}Nd.SnippetUrl="https://snippet.babylonjs.com",Nd.CreateFromSnippetAsync=Nd.ParseFromSnippetAsync,z("BABYLON.ShaderMaterial",Nd);Bi.ShadersStore.colorPixelShader="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n#include(color,gl_FragColor)\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.colorVertexShader="attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\n#ifdef FOG\nuniform mat4 view;\n#endif\n#include\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}",ha._LinesMeshParser=(e,t)=>Fd.Parse(e,t);class Fd extends ha{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,s=null,r,n,o,a){super(e,t,i,s,r),this.useVertexColor=n,this.useVertexAlpha=o,this.color=new Ee(1,1,1),this.alpha=1,s&&(this.color=s.color.clone(),this.alpha=s.alpha,this.useVertexColor=s.useVertexColor,this.useVertexAlpha=s.useVertexAlpha),this.intersectionThreshold=.1;const l={attributes:[er.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===o?l.needAlphaBlending=!1:l.defines.push("#define VERTEXALPHA"),n?(l.defines.push("#define VERTEXCOLOR"),l.attributes.push(er.ColorKind)):(l.uniforms.push("color"),this._color4=new Ae),a?this.material=a:(this.material=new Nd("colorShader",this.getScene(),"color",l,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=ta.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;const i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const s=this.getScene().getEngine();return this._unIndexed?s.drawArraysType(ta.LineListDrawMode,e.verticesStart,e.verticesCount,i):s.drawElementsType(ta.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new Fd(e,this.getScene(),t,this,i)}createInstance(e){const t=new Ld(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const e in this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new Fd(e.name,t);return i.color=Ee.FromArray(e.color),i.alpha=e.alpha,i}}class Ld extends ca{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function Bd(e){const t=[],i=[],s=e.lines,r=e.colors,n=[];let o=0;for(let e=0;e0&&(t.push(o-1),t.push(o)),o++}}const a=new Wn;return a.indices=t,a.positions=i,r&&(a.colors=n),a}function kd(e){const t=e.dashSize||3,i=e.gapSize||1,s=e.dashNb||200,r=e.points,n=[],o=[],a=_e.Zero();let l=0,h=0,c=0,u=0,d=0,_=0,p=0;for(p=0;p{const t=_e.Zero(),i=e.length/6;let n=0,o=0,a=0,l=0,h=0,c=0,u=0,d=0;for(u=0;uUd(e,{points:t,updatable:s,instance:r},i),ha.CreateDashedLines=(e,t,i,s,r,n=null,o,a)=>Gd(e,{points:t,dashSize:i,gapSize:s,dashNb:r,updatable:o,instance:a},n);class Wd extends de{constructor(e,t){super(e.x,e.y),this.index=t}}class Hd{constructor(){this.elements=[]}add(e){const t=[];return e.forEach((e=>{const i=new Wd(e,this.elements.length);t.push(i),this.elements.push(i)})),t}computeBounds(){const e=new de(this.elements[0].x,this.elements[0].y),t=new de(this.elements[0].x,this.elements[0].y);return this.elements.forEach((i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)})),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class Xd{static Rectangle(e,t,i,s){return[new de(e,t),new de(i,t),new de(i,s),new de(e,s)]}static Circle(e,t=0,i=0,s=32){const r=[];let n=0;const o=2*Math.PI/s;for(let a=0;a!isNaN(e)));let i;const s=[];for(i=0;i<(2147483646&t.length);i+=2)s.push(new de(t[i],t[i+1]));return s}static StartingAt(e,t){return Zr.StartingAt(e,t)}}class Yd{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,s=earcut){let r;this._points=new Hd,this._outlinepoints=new Hd,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=e,this._scene=i||re.LastCreatedScene,r=t instanceof Zr?t.getPoints():t,this._addToepoint(r),this._points.add(r),this._outlinepoints.add(r),void 0===this.bjsEarcut&&Ne.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new Hd;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){const s=new ha(this._name,this._scene),r=this.buildVertexData(t,i);return s.setVerticesData(er.PositionKind,r.positions,e),s.setVerticesData(er.NormalKind,r.normals,e),s.setVerticesData(er.UVKind,r.uvs,e),s.setIndices(r.indices),s}buildVertexData(e=0,t=2){const i=new Wn,s=[],r=[],n=[],o=this._points.computeBounds();this._points.elements.forEach((e=>{s.push(0,1,0),r.push(e.x,0,e.y),n.push((e.x-o.min.x)/o.width,(e.y-o.min.y)/o.height)}));const a=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e0){const i=r.length/3;this._points.elements.forEach((t=>{s.push(0,-1,0),r.push(t.x,-e,t.y),n.push(1-(t.x-o.min.x)/o.width,1-(t.y-o.min.y)/o.height)}));const l=a.length;for(let e=0;e{this._addSide(r,s,n,a,o,i,e,!0,t)}))}return i.indices=a,i.positions=r,i.normals=s,i.uvs=n,i}_addSide(e,t,i,s,r,n,o,a,l){let h=e.length/3,c=0;for(let u=0;ul?yl?S1),o=t.rotationFunction||(()=>0),a=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||ha.NO_CAP,c=t.updatable,u=t.firstNormal||null,d=t.adjustFrame||!1;return Jd(e,r,s,null,null,n,o,a,l,h,!0,i,!!c,ha._GetDefaultSideOrientation(t.sideOrientation),t.instance||null,t.invertUV||!1,t.frontUVs||null,t.backUVs||null,u,d)}function Jd(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v,x){const b=(e,t,i,s,r,n,o,a,l,h,c)=>{const u=i.getTangents(),d=i.getNormals(),_=i.getBinormals(),p=i.getDistances();if(c)for(let e=0;e0){let t=u[e-1];_e.Dot(t,u[e])<0&&u[e].scaleInPlace(-1),t=d[e-1],_e.Dot(t,d[e])<0&&d[e].scaleInPlace(-1),t=_[e-1],_e.Dot(t,_[e])<0&&_[e].scaleInPlace(-1)}let f=0;const m=h&&a?a:()=>null!==n?n:0,g=h&&o?o:()=>null!==r?r:1;let v=l===ha.NO_CAP||l===ha.CAP_END?0:2;const x=ve.Matrix[0];for(let i=0;i{const t=Array(),i=_e.Zero();let s;for(s=0;s3?0:h,c,x);const S=xd(e,{pathArray:y,closeArray:a,closePath:l,updatable:d,sideOrientation:_,invertUV:f,frontUVs:m||void 0,backUVs:g||void 0},u);return S._creationDataStorage.pathArray=y,S._creationDataStorage.path3D=T,S._creationDataStorage.cap=h,S}Wn.CreatePolygon=Qd,ha.CreatePolygon=(e,t,i,s,r,n,o=earcut)=>jd(e,{shape:t,holes:s,updatable:r,sideOrientation:n},i,o),ha.ExtrudePolygon=(e,t,i,s,r,n,o,a=earcut)=>Kd(e,{shape:t,holes:r,depth:i,updatable:n,sideOrientation:o},s,a);const e_={ExtrudeShape:qd,ExtrudeShapeCustom:Zd};function t_(e,t,i=null){const s=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,r=void 0===t.closed||t.closed,n=t.shape,o=t.radius||1,a=t.tessellation||64,l=t.clip||0,h=t.updatable,c=ha._GetDefaultSideOrientation(t.sideOrientation),u=t.cap||ha.NO_CAP,d=2*Math.PI,_=[],p=t.invertUV||!1;let f=0,m=0;const g=d/a*s;let v,x;for(f=0;f<=a-l;f++){for(x=[],u!=ha.CAP_START&&u!=ha.CAP_ALL||(x.push(new _e(0,n[0].y,0)),x.push(new _e(Math.cos(f*g)*n[0].x*o,n[0].y,Math.sin(f*g)*n[0].x*o))),m=0;mqd(e,{shape:t,path:i,scale:s,rotation:r,cap:0===n?0:n||ha.NO_CAP,sideOrientation:l,instance:h,updatable:a},o),ha.ExtrudeShapeCustom=(e,t,i,s,r,n,o,a,l,h,c,u)=>Zd(e,{shape:t,path:i,scaleFunction:s,rotationFunction:r,ribbonCloseArray:n,ribbonClosePath:o,cap:0===a?0:a||ha.NO_CAP,sideOrientation:c,instance:u,updatable:h},l);const i_={CreateLathe:t_};function s_(e,t,i=null){const s=t.path;let r=t.instance,n=1;void 0!==t.radius?n=t.radius:r&&(n=r._creationDataStorage.radius);const o=t.tessellation||64,a=t.radiusFunction||null;let l=t.cap||ha.NO_CAP;const h=t.invertUV||!1,c=t.updatable,u=ha._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;const d=(e,t,i,s,r,n,o,a)=>{const l=t.getTangents(),h=t.getNormals(),c=t.getDistances(),u=2*Math.PI/r*a,d=n||(()=>s);let _,p,f,m;const g=ve.Matrix[0];let v=o===ha.NO_CAP||o===ha.CAP_END?0:2;for(let t=0;t{const s=Array();for(let r=0;r3?0:l,p=d(s,_,new Array,n,o,a,l,t.arc);const f=xd(e,{pathArray:p,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:h,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return f._creationDataStorage.pathArray=p,f._creationDataStorage.path3D=_,f._creationDataStorage.tessellation=o,f._creationDataStorage.cap=l,f._creationDataStorage.arc=t.arc,f._creationDataStorage.radius=n,f}ha.CreateLathe=(e,t,i,s,r,n,o)=>t_(e,{shape:t,radius:i,tessellation:s,sideOrientation:o,updatable:n},r);const r_={CreateTube:s_};function n_(e){const t=[];t[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},t[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},t[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},t[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},t[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},t[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},t[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},t[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},t[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},t[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},t[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},t[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},t[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},t[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},t[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};const i=e.type&&(e.type<0||e.type>=t.length)?0:e.type||0,s=e.size,r=e.sizeX||s||1,n=e.sizeY||s||1,o=e.sizeZ||s||1,a=e.custom||t[i],l=a.face.length,h=e.faceUV||new Array(l),c=e.faceColors,u=void 0===e.flat||e.flat,d=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,_=[],p=[],f=[],m=[],g=[];let v=0,x=0;const b=[];let T,y,S,C,E,A,P=0,I=0;if(u)for(I=0;Is_(e,{path:t,radius:i,tessellation:s,radiusFunction:r,arc:1,cap:n,updatable:a,sideOrientation:l,instance:h},o);const a_={CreatePolyhedron:o_};Wn.CreatePolyhedron=n_,ha.CreatePolyhedron=(e,t,i)=>o_(e,t,i);const l_=new _e(1,0,0),h_=new _e(-1,0,0),c_=new _e(0,1,0),u_=new _e(0,-1,0),d_=new _e(0,0,1),__=new _e(0,0,-1);class p_{constructor(e=_e.Zero(),t=_e.Up(),i=de.Zero(),s=0,r=0,n=null,o=null,a=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=s,this.vertexIdxForBones=r,this.localPositionOverride=n,this.localNormalOverride=o,this.matrixIndicesOverride=a,this.matrixWeightsOverride=l}clone(){return new p_(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,this.localPositionOverride?.slice(),this.localNormalOverride?.slice(),this.matrixIndicesOverride?.slice(),this.matrixWeightsOverride?.slice())}}function f_(e,t,i){const s=!!t.skeleton,r=i.localMode||s,n=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,o=t.getIndices(),a=s?t.getPositionData(!0,!0):t.getVerticesData(er.PositionKind),l=s?t.getNormalsData(!0,!0):t.getVerticesData(er.NormalKind),h=r?s?t.getVerticesData(er.PositionKind):a:null,c=r?s?t.getVerticesData(er.NormalKind):l:null,u=t.getVerticesData(er.UVKind),d=s?t.getVerticesData(er.MatricesIndicesKind):null,_=s?t.getVerticesData(er.MatricesWeightsKind):null,p=s?t.getVerticesData(er.MatricesIndicesExtraKind):null,f=s?t.getVerticesData(er.MatricesWeightsExtraKind):null,m=i.position||_e.Zero();let g=i.normal||_e.Up();const v=i.size||_e.One(),x=i.angle||0;if(!g){const e=new _e(0,0,1),i=t.getScene().activeCamera,s=_e.TransformCoordinates(e,i.getWorldMatrix());g=i.globalPosition.subtract(s)}const b=-Math.atan2(g.z,g.x)-Math.PI/2,T=Math.sqrt(g.x*g.x+g.z*g.z),y=Math.atan2(g.y,T),S=new Wn;S.indices=[],S.positions=[],S.normals=[],S.uvs=[],S.matricesIndices=s?[]:null,S.matricesWeights=s?[]:null,S.matricesIndicesExtra=p?[]:null,S.matricesWeightsExtra=f?[]:null;let C=0;const E=(e,t)=>{const s=new p_;if(!o||!a||!l)return s;const r=o[e];if(s.vertexIdx=3*r,s.vertexIdxForBones=4*r,s.position=new _e(a[3*r],a[3*r+1],a[3*r+2]),_e.TransformCoordinatesToRef(s.position,t,s.position),s.normal=new _e(l[3*r],l[3*r+1],l[3*r+2]),_e.TransformNormalToRef(s.normal,t,s.normal),i.captureUVS&&u){const e=u[2*r+1];s.uv=new de(u[2*r],Xn.UseOpenGLOrientationForUV?1-e:e)}return s},A=[0,0,0,0],P=(e,t)=>{if(0===e.length)return e;const i=.5*Math.abs(_e.Dot(v,t)),s=(e,t,i,s)=>{for(let r=0;r{const n=_e.GetClipFactor(e.position,r.position,t,i);let o=A,a=A;if(d&&_){const t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=e.matrixIndicesOverride??d,l=e.matrixWeightsOverride??_,h=r.matrixIndicesOverride?0:r.vertexIdxForBones,c=r.matrixIndicesOverride??d,u=r.matrixWeightsOverride??_;o=[0,0,0,0],a=[0,0,0,0];let p=0;for(let e=0;e<4;++e)if(l[t+e]>0){const r=s(c,i[t+e],h,4);o[p]=i[t+e],a[p]=be.Lerp(l[t+e],r>=0?u[r]:0,n),p++}for(let e=0;e<4&&p<4;++e){const r=c[h+e];-1===s(i,r,t,4)&&(o[p]=r,a[p]=be.Lerp(0,u[h+e],n),p++)}const f=a[0]+a[1]+a[2]+a[3];a[0]/=f,a[1]/=f,a[2]/=f,a[3]/=f}const l=e.localPositionOverride?e.localPositionOverride[0]:h?.[e.vertexIdx]??0,u=e.localPositionOverride?e.localPositionOverride[1]:h?.[e.vertexIdx+1]??0,p=e.localPositionOverride?e.localPositionOverride[2]:h?.[e.vertexIdx+2]??0,f=r.localPositionOverride?r.localPositionOverride[0]:h?.[r.vertexIdx]??0,m=r.localPositionOverride?r.localPositionOverride[1]:h?.[r.vertexIdx+1]??0,g=r.localPositionOverride?r.localPositionOverride[2]:h?.[r.vertexIdx+2]??0,v=e.localNormalOverride?e.localNormalOverride[0]:c?.[e.vertexIdx]??0,x=e.localNormalOverride?e.localNormalOverride[1]:c?.[e.vertexIdx+1]??0,b=e.localNormalOverride?e.localNormalOverride[2]:c?.[e.vertexIdx+2]??0,T=v+((r.localNormalOverride?r.localNormalOverride[0]:c?.[r.vertexIdx]??0)-v)*n,y=x+((r.localNormalOverride?r.localNormalOverride[1]:c?.[r.vertexIdx+1]??0)-x)*n,S=b+((r.localNormalOverride?r.localNormalOverride[2]:c?.[r.vertexIdx+2]??0)-b)*n,C=Math.sqrt(T*T+y*y+S*S);return new p_(_e.Lerp(e.position,r.position,n),_e.Lerp(e.normal,r.normal,n).normalize(),de.Lerp(e.uv,r.uv,n),-1,-1,h?[l+(f-l)*n,u+(m-u)*n,p+(g-p)*n]:null,c?[T/C,y/C,S/C]:null,o,a)};let n=null;e.length>3&&(n=[]);for(let s=0;s0,d=_e.Dot(e[s+1].position,t)-i>0,_=_e.Dot(e[s+2].position,t)-i>0;switch(o=(u?1:0)+(d?1:0)+(_?1:0),o){case 0:e.length>3?(n.push(e[s]),n.push(e[s+1]),n.push(e[s+2])):n=e;break;case 1:if(n=n??new Array,u&&(a=e[s+1],l=e[s+2],h=r(e[s],a),c=r(e[s],l)),d){a=e[s],l=e[s+2],h=r(e[s+1],a),c=r(e[s+1],l),n.push(h),n.push(l.clone()),n.push(a.clone()),n.push(l.clone()),n.push(h.clone()),n.push(c);break}_&&(a=e[s],l=e[s+1],h=r(e[s+2],a),c=r(e[s+2],l)),a&&l&&h&&c&&(n.push(a.clone()),n.push(l.clone()),n.push(h),n.push(c),n.push(h.clone()),n.push(l.clone()));break;case 2:n=n??new Array,u||(a=e[s].clone(),l=r(a,e[s+1]),h=r(a,e[s+2]),n.push(a),n.push(l),n.push(h)),d||(a=e[s+1].clone(),l=r(a,e[s+2]),h=r(a,e[s]),n.push(a),n.push(l),n.push(h)),_||(a=e[s+2].clone(),l=r(a,e[s]),h=r(a,e[s+1]),n.push(a),n.push(l),n.push(h))}}return n},I=t instanceof ha?t:null,R=I?._thinInstanceDataStorage.matrixData,M=I?.thinInstanceCount||1,O=ve.Matrix[0];O.copyFrom(me.IdentityReadOnly);for(let e=0;ef_(e,t,{position:i,normal:s,size:r,angle:n});class g_{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(Math.floor(e),Ne.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(Math.floor(t),Ne.Warn("y is not an integer, floor(y) used"))}clone(){return new g_(this.x,this.y)}rotate60About(e){const t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){const t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&(Math.floor(e),Ne.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),Ne.Warn("n not an integer only floor(n) used"));const i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&(Math.floor(e),Ne.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),Ne.Warn("n is not an integer, floor(n) used"));const i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){const i=_e.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new g_(0,0)}}class v_{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new x_("icosahedron","Regular",[[0,Z,-1],[-Z,1,0],[-1,0,-Z],[1,0,-Z],[Z,1,0],[0,Z,1],[-1,0,Z],[-Z,-1,0],[0,-Z,-1],[Z,-1,0],[1,0,Z],[0,-Z,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12;const t={},i=this.m,s=this.n;let r,n,o,a,l,h=i,c=1,u=0;0!==s&&(h=be.HCF(i,s)),c=i/h,u=s/h;const d=g_.Zero(),_=new g_(i,s),p=new g_(-s,i+s),f=g_.Zero(),m=g_.Zero(),g=g_.Zero();let v,x,b,T,y=[];const S=[],C=this.vertByDist,E=(i,s,r,n)=>{v=i+"|"+r,x=s+"|"+n,v in t||x in t?v in t&&!(x in t)?t[x]=t[v]:x in t&&!(v in t)&&(t[v]=t[x]):(t[v]=e,t[x]=e,e++),C[r][0]>2?S[t[v]]=[-C[r][0],C[r][1],t[v]]:S[t[v]]=[y[C[r][0]],C[r][1],t[v]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let x=0;x<20;x++){if(y=this.IDATA.face[x],o=y[2],a=y[1],l=y[0],b=d.x+"|"+d.y,v=x+"|"+b,v in t||(t[v]=o,S[o]=[y[C[b][0]],C[b][1]]),b=_.x+"|"+_.y,v=x+"|"+b,v in t||(t[v]=a,S[a]=[y[C[b][0]],C[b][1]]),b=p.x+"|"+p.y,v=x+"|"+b,v in t||(t[v]=l,S[l]=[y[C[b][0]],C[b][1]]),r=this.IDATA.edgematch[x][0],n=this.IDATA.edgematch[x][1],"B"===n)for(let e=1;e2?S[t[v]]=[-C[b][0],C[b][1],t[v]]:S[t[v]]=[y[C[b][0]],C[b][1],t[v]])}this.closestTo=S,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,s=e*e+t*t+e*t;this.coau=(e+t)/s,this.cobu=-t/s,this.coav=-i*(e-t)/s,this.cobv=i*(2*e+t)/s}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i0&&e0){const s=be.HCF(e,t),r=e/s,n=t/s;for(let o=1;oe.x-t.x)),i.sort(((e,t)=>e.y-t.y));const o=new Array(e+t+1),a=new Array(e+t+1);for(let e=0;e{const r=i.clone();return"A"===s&&r.rotateNeg120(e,t),"B"===s&&r.rotate120(e,t),r.x<0?r.y:r.x+r.y},d=[],_=[],p=[],f=[],m={},g=[];let v=-1,x=-1;for(let e=0;ee[2]-t[2])),g.sort(((e,t)=>e[3]-t[3])),g.sort(((e,t)=>e[1]-t[1])),g.sort(((e,t)=>e[0]-t[0]));for(let e=0;et.vecToidx[e+i])))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let s=0;s-1?i[e][1]>0&&t[i[e][0]].push([e,i[e][1]]):t[12].push([e,i[e][0]]);const s=[];for(let e=0;e<12;e++)s[e]=e;let r=12;for(let e=0;e<12;e++){t[e].sort(((e,t)=>e[1]-t[1]));for(let i=0;ie[3]-t[3]));for(let e=0;e0;)r=t[a],this.face[r].indexOf(o)>-1?(n=(this.face[r].indexOf(o)+1)%3,o=this.face[r][n],i.push(o),s.push(r),t.splice(a,1),a=0):a++;return this.adjacentFaces.push(i),s}toGoldbergPolyhedronData(){const e=new x_("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let e=0;e{s=0,r=0,n=0,o=this.face[t];for(let e=0;e<3;e++)a=this.vertex[o[e]],s+=a[0],r+=a[1],n+=a[2];e.vertex[t]=[s/3,r/3,n/3]}));return e}static BuildGeodesicData(e){const t=new b_("Geodesic-m-n","Geodesic",[[0,Z,-1],[-Z,1,0],[-1,0,-Z],[1,0,-Z],[Z,1,0],[0,Z,1],[-1,0,Z],[-Z,-1,0],[0,-Z,-1],[Z,-1,0],[1,0,Z],[0,-Z,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let i=0;is){const e=r;r=s,s=e,Ne.Warn("n > m therefore m and n swapped")}const n=new v_;return n.build(s,r),o_(e,{custom:b_.BuildGeodesicData(n),size:t.size,sizeX:t.sizeX,sizeY:t.sizeY,sizeZ:t.sizeZ,faceUV:t.faceUV,faceColors:t.faceColors,flat:t.flat,updatable:t.updatable,sideOrientation:t.sideOrientation,frontUVs:t.frontUVs,backUVs:t.backUVs},i)}ha._GoldbergMeshParser=(e,t)=>y_.Parse(e,t);class y_ extends ha{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(Ne.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(Ne.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(Ne.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let t=0;t1&&(c=1),l.push(c,u);for(let e=0;e<6;e++)c=n.x+o*Math.cos(a+e*Math.PI/3),u=n.y+o*Math.sin(a+e*Math.PI/3),c<0&&(c=0),c>1&&(c=1),h.push(c,u);for(let e=s;eAe.FromArray(e))),i.faceCenters=i.faceCenters.map((e=>_e.FromArray(e))),i.faceZaxis=i.faceZaxis.map((e=>_e.FromArray(e))),i.faceXaxis=i.faceXaxis.map((e=>_e.FromArray(e))),i.faceYaxis=i.faceYaxis.map((e=>_e.FromArray(e)));const s=new y_(e.name,t);return s.goldbergData=i,s}}function S_(e,t){const i=e.size,s=e.sizeX||i||1,r=e.sizeY||i||1,n=e.sizeZ||i||1,o=0===e.sideOrientation?0:e.sideOrientation||Wn.DEFAULTSIDE,a=[],l=[],h=[],c=[];let u=1/0,d=-1/0,_=1/0,p=-1/0;for(let e=0;ea){const e=l;l=a,a=e,Ne.Warn("n > m therefore m and n swapped")}const h=new v_;h.build(a,l);const c=b_.BuildGeodesicData(h),u=c.toGoldbergPolyhedronData(),d=new y_(e,i);t.sideOrientation=ha._GetDefaultSideOrientation(t.sideOrientation),d._originalBuilderSideOrientation=t.sideOrientation,S_(t,u).applyToMesh(d,t.updatable),d.goldbergData.nbSharedFaces=c.sharedNodes,d.goldbergData.nbUnsharedFaces=c.poleNodes,d.goldbergData.adjacentFaces=c.adjacentFaces,d.goldbergData.nbFaces=d.goldbergData.nbSharedFaces+d.goldbergData.nbUnsharedFaces,d.goldbergData.nbFacesAtPole=(d.goldbergData.nbUnsharedFaces-12)/12;for(let e=0;e0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function A_(e,t,i,s,r,n){const o=n.glyphs[e]||n.glyphs["?"];if(!o)return null;const a=new E_(r);if(o.o){const e=o.o.split(" ");for(let r=0,n=e.length;rJ&&(e.x=1*Math.sign(e.x)),Math.abs(e.y-1)>J&&(e.y=1*Math.sign(e.y)),Math.abs(e.z-1)>J&&(e.z=1*Math.sign(e.z))}_updateDebugConstraint(e,t){if(!e._initOptions)return;const{pivotA:i,pivotB:s,axisA:r,axisB:n,perpAxisA:o,perpAxisB:a}=e._initOptions;i&&s&&r&&n&&o&&a&&t.getDescendants(!0).forEach((e=>{const t=e.getDescendants(!0)[0],l=e.getDescendants(!0)[1],{parentBody:h,parentBodyIndex:c}=t.metadata,{childBody:u,childBodyIndex:d}=l.metadata,_=this._getTransformFromBodyToRef(h,ve.Matrix[0],c),p=this._getTransformFromBodyToRef(u,ve.Matrix[1],d);_.decomposeToTransformNode(t),this._makeScalingUnitInPlace(t.scaling),p.decomposeToTransformNode(l),this._makeScalingUnitInPlace(l.scaling);const f=t.getDescendants(!0)[0];f.position.copyFrom(i);const m=l.getDescendants(!0)[0];m.position.copyFrom(s),fe.FromRotationMatrixToRef(me.FromXYZAxesToRef(r,o,_e.CrossToRef(r,o,ve.Vector3[0]),ve.Matrix[0]),f.rotationQuaternion),fe.FromRotationMatrixToRef(me.FromXYZAxesToRef(n,a,_e.CrossToRef(n,a,ve.Vector3[1]),ve.Matrix[1]),m.rotationQuaternion)}))}showImpostor(e,t){if(!this._scene)return null;for(let t=0;tthis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numMeshes++),i}showBody(e){if(!this._scene)return null;for(let t=0;tthis._updateDebugMeshes(),this._scene.registerBeforeRender(this._renderFunction)),this._numBodies++),t}showInertia(e){if(!this._scene)return null;for(let t=0;tthis._updateInertiaMeshes(),this._scene.registerBeforeRender(this._inertiaRenderFunction)),this._numInertiaBodies++),t}showConstraint(e){if(!this._scene)return null;for(let t=0;tthis._updateDebugConstraints(),this._scene.registerBeforeRender(this._constraintRenderFunction)),this._numConstraints++),t}hideImpostor(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let s=0;s-1&&this._debugMeshMeshes.splice(r,1),this._numMeshes--,this._numMeshes>0?(this._meshes[s]=this._meshes[this._numMeshes],this._impostors[s]=this._impostors[this._numMeshes],this._meshes[this._numMeshes]=null,this._impostors[this._numMeshes]=null):(this._meshes[0]=null,this._impostors[0]=null),t=!0;break}t&&0===this._numMeshes&&this._scene.unregisterBeforeRender(this._renderFunction)}hideBody(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let s=0;s0?(this._bodyMeshes[s]=this._bodyMeshes[this._numBodies],this._bodies[s]=this._bodies[this._numBodies],this._bodyMeshes[this._numBodies]=null,this._bodies[this._numBodies]=null):(this._bodyMeshes[0]=null,this._bodies[0]=null),t=!0;break}t&&0===this._numBodies&&this._scene.unregisterBeforeRender(this._renderFunction)}hideInertia(e){if(!e||!this._scene||!this._utilityLayer)return;let t=!1;const i=this._utilityLayer.utilityLayerScene;for(let s=0;s0?(this._constraints[s]=this._constraints[this._numConstraints],this._constraintMeshes[s]=this._constraintMeshes[this._numConstraints],this._constraints[this._numConstraints]=null,this._constraintMeshes[this._numConstraints]=null):(this._constraints[0]=null,this._constraintMeshes[0]=null),t=!0;break}t&&0===this._numConstraints&&this._scene.unregisterBeforeRender(this._constraintRenderFunction)}_getDebugMaterial(e){return this._debugMaterial||(this._debugMaterial=new cu("",e),this._debugMaterial.wireframe=!0,this._debugMaterial.emissiveColor=Ee.White(),this._debugMaterial.disableLighting=!0),this._debugMaterial}_getDebugInertiaMaterial(e){return this._debugInertiaMaterial||(this._debugInertiaMaterial=new cu("",e),this._debugInertiaMaterial.disableLighting=!0,this._debugInertiaMaterial.alpha=0),this._debugInertiaMaterial}_getDebugBoxMesh(e){return this._debugBoxMesh||(this._debugBoxMesh=cd("physicsBodyBoxViewMesh",{size:1},e),this._debugBoxMesh.rotationQuaternion=fe.Identity(),this._debugBoxMesh.material=this._getDebugMaterial(e),this._debugBoxMesh.setEnabled(!1)),this._debugBoxMesh.createInstance("physicsBodyBoxViewInstance")}_getDebugSphereMesh(e){return this._debugSphereMesh||(this._debugSphereMesh=_d("physicsBodySphereViewMesh",{diameter:1},e),this._debugSphereMesh.rotationQuaternion=fe.Identity(),this._debugSphereMesh.material=this._getDebugMaterial(e),this._debugSphereMesh.setEnabled(!1)),this._debugSphereMesh.createInstance("physicsBodySphereViewInstance")}_getDebugCapsuleMesh(e){return this._debugCapsuleMesh||(this._debugCapsuleMesh=md("physicsBodyCapsuleViewMesh",{height:1},e),this._debugCapsuleMesh.rotationQuaternion=fe.Identity(),this._debugCapsuleMesh.material=this._getDebugMaterial(e),this._debugCapsuleMesh.setEnabled(!1)),this._debugCapsuleMesh.createInstance("physicsBodyCapsuleViewInstance")}_getDebugCylinderMesh(e){return this._debugCylinderMesh||(this._debugCylinderMesh=$u("physicsBodyCylinderViewMesh",{diameterTop:1,diameterBottom:1,height:1},e),this._debugCylinderMesh.rotationQuaternion=fe.Identity(),this._debugCylinderMesh.material=this._getDebugMaterial(e),this._debugCylinderMesh.setEnabled(!1)),this._debugCylinderMesh.createInstance("physicsBodyCylinderViewInstance")}_getDebugMeshMesh(e,t){const i=new ha(e.name,t,null,e);return i.setParent(e),i.position=_e.Zero(),i.material=this._getDebugMaterial(t),this._debugMeshMeshes.push(i),i}_getDebugMesh(e,t){if(!this._utilityLayer)return null;if(t&&t.parent&&t.parent.physicsImpostor)return null;let i=null;const s=this._utilityLayer.utilityLayerScene;if(!e.physicsBody)return Ne.Warn("Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor."),null;switch(e.type){case nl.BoxImpostor:i=this._getDebugBoxMesh(s),e.getBoxSizeToRef(i.scaling);break;case nl.SphereImpostor:{i=this._getDebugSphereMesh(s);const t=e.getRadius();i.scaling.x=2*t,i.scaling.y=2*t,i.scaling.z=2*t;break}case nl.CapsuleImpostor:{i=this._getDebugCapsuleMesh(s);const t=e.object.getBoundingInfo();i.scaling.x=2*(t.boundingBox.maximum.x-t.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(t.boundingBox.maximum.y-t.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=2*(t.boundingBox.maximum.z-t.boundingBox.minimum.z)*e.object.scaling.z;break}case nl.MeshImpostor:t&&(i=this._getDebugMeshMesh(t,s));break;case nl.NoImpostor:t?t.getChildMeshes().filter((e=>e.physicsImpostor?1:0)).forEach((e=>{if(e.physicsImpostor&&"Mesh"===e.getClassName()){const t=e.getBoundingInfo(),r=t.boundingBox.minimum,n=t.boundingBox.maximum;switch(e.physicsImpostor.type){case nl.BoxImpostor:i=this._getDebugBoxMesh(s),i.position.copyFrom(r),i.position.addInPlace(n),i.position.scaleInPlace(.5);break;case nl.SphereImpostor:i=this._getDebugSphereMesh(s);break;case nl.CylinderImpostor:i=this._getDebugCylinderMesh(s);break;default:i=null}i&&(i.scaling.x=n.x-r.x,i.scaling.y=n.y-r.y,i.scaling.z=n.z-r.z,i.parent=e)}})):Ne.Warn("No target mesh parameter provided for NoImpostor. Skipping."),i=null;break;case nl.CylinderImpostor:{i=this._getDebugCylinderMesh(s);const t=e.object.getBoundingInfo();i.scaling.x=(t.boundingBox.maximum.x-t.boundingBox.minimum.x)*e.object.scaling.x,i.scaling.y=(t.boundingBox.maximum.y-t.boundingBox.minimum.y)*e.object.scaling.y,i.scaling.z=(t.boundingBox.maximum.z-t.boundingBox.minimum.z)*e.object.scaling.z;break}}return i}_getDebugBodyMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=new ha("custom",t),s=new Wn,r=e.getGeometry();if(s.positions=r.positions,s.indices=r.indices,s.applyToMesh(i),e._pluginDataInstances){const t=new Float32Array(16*e._pluginDataInstances.length);i.thinInstanceSetBuffer("matrix",t,16,!1)}return i.material=this._getDebugMaterial(t),i}_getMeshDebugInertiaMatrixToRef(e,t){const i=e.inertiaOrientation??fe.Identity(),s=e.inertia??_e.Zero(),r=e.centerOfMass??_e.Zero(),n=6*(s.x-s.y+s.z),o=Math.sqrt(Math.max(n,0)),a=12*s.x-n,l=Math.sqrt(Math.max(a,0)),h=12*s.z-n,c=Math.sqrt(Math.max(h,0)),u=ve.Vector3[0];u.set(c,o,l);const d=me.ScalingToRef(u.x,u.y,u.z,ve.Matrix[0]),_=i.toRotationMatrix(ve.Matrix[1]),p=me.TranslationToRef(r.x,r.y,r.z,ve.Matrix[2]);return d.multiplyToRef(_,t),t.multiplyToRef(p,t),t}_getDebugInertiaMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene,i=R_.CreateBox("custom",{size:1},t),s=me.Identity();if(e._pluginDataInstances.length){const t=new Float32Array(16*e._pluginDataInstances.length);for(let i=0;i=0?me.FromArrayToRef(s._thinInstanceDataStorage.matrixData,i,t):t.copyFrom(s.getWorldMatrix())}_getDebugConstraintMesh(e){if(!this._utilityLayer)return null;const t=this._utilityLayer.utilityLayerScene;if(!e._initOptions)return null;const{pivotA:i,pivotB:s,axisA:r,axisB:n,perpAxisA:o,perpAxisB:a}=e._initOptions;if(!(i&&s&&r&&n&&o&&a))return null;const l=new ha("parentingDebugConstraint",t),h=e.getBodiesUsingConstraint();for(const e of h){const h=new lo("parentOfPair",t);h.parent=l;const{parentBody:c,parentBodyIndex:u,childBody:d,childBodyIndex:_}=e,p=this._getTransformFromBodyToRef(c,ve.Matrix[0],u),f=this._getTransformFromBodyToRef(d,ve.Matrix[1],_),m=new lo("parentCoordSystem",t);m.parent=h,m.metadata={parentBody:c,parentBodyIndex:u},p.decomposeToTransformNode(m);const g=new lo("childCoordSystem",t);g.parent=h,g.metadata={childBody:d,childBodyIndex:_},f.decomposeToTransformNode(g);const v=fe.FromRotationMatrix(me.FromXYZAxesToRef(r,o,r.cross(o),ve.Matrix[0])),x=fe.FromRotationMatrix(me.FromXYZAxesToRef(n,a,n.cross(a),ve.Matrix[0])),b=i,T=s,y=new lo("constraint_parent",t);y.position.copyFrom(b),y.rotationQuaternion=v,y.parent=m;const S=new lo("constraint_child",t);S.parent=g,S.position.copyFrom(T),S.rotationQuaternion=x;const C=new nd(t,this._constraintAxesSize);C.xAxis.parent=y,C.yAxis.parent=y,C.zAxis.parent=y;const E=new nd(t,this._constraintAxesSize);E.xAxis.parent=S,E.yAxis.parent=S,E.zAxis.parent=S}return l}dispose(){for(let e=this._numMeshes-1;e>=0;e--)this.hideImpostor(this._impostors[0]);for(let e=this._numBodies-1;e>=0;e--)this.hideBody(this._bodies[0]);for(let e=this._numInertiaBodies-1;e>=0;e--)this.hideInertia(this._inertiaBodies[0]);this._debugBoxMesh&&this._debugBoxMesh.dispose(),this._debugSphereMesh&&this._debugSphereMesh.dispose(),this._debugCylinderMesh&&this._debugCylinderMesh.dispose(),this._debugMaterial&&this._debugMaterial.dispose(),this._impostors.length=0,this._scene=null,this._physicsEnginePlugin=null,this._utilityLayer&&(this._utilityLayer.dispose(),this._utilityLayer=null)}}class O_{static CreateAndShow(e,t,i){const s=new O_(e);return s.show(t,i),s}constructor(e){this.ray=e}show(e,t){if(!this._renderFunction&&this.ray){const t=this.ray;this._renderFunction=()=>this._render(),this._scene=e,this._renderPoints=[t.origin,t.origin.add(t.direction.scale(t.length))],this._renderLine=Ud("ray",{points:this._renderPoints,updatable:!0},e),this._renderLine.isPickable=!1,this._renderFunction&&this._scene.registerBeforeRender(this._renderFunction)}t&&this._renderLine&&this._renderLine.color.copyFrom(t)}hide(){this._renderFunction&&this._scene&&(this._scene.unregisterBeforeRender(this._renderFunction),this._scene=null,this._renderFunction=null,this._renderLine&&(this._renderLine.dispose(),this._renderLine=null),this._renderPoints=[])}_render(){const e=this.ray;if(!e)return;const t=this._renderPoints[1],i=Math.min(e.length,1e6);t.copyFrom(e.direction),t.scaleInPlace(i),t.addInPlace(e.origin),this._renderPoints[0].copyFrom(e.origin),Ud("ray",{points:this._renderPoints,updatable:!0,instance:this._renderLine},this._scene),this._renderLine?.refreshBoundingInfo()}attachToMesh(e,t,i,s){this._attachedToMesh=e;const r=this.ray;r&&(r.direction||(r.direction=_e.Zero()),r.origin||(r.origin=_e.Zero()),s&&(r.length=s),i||(i=_e.Zero()),t||(t=new _e(0,0,-1)),this._scene||(this._scene=e.getScene()),this._meshSpaceDirection?(this._meshSpaceDirection.copyFrom(t),this._meshSpaceOrigin.copyFrom(i)):(this._meshSpaceDirection=t.clone(),this._meshSpaceOrigin=i.clone()),this._onAfterRenderObserver||(this._onAfterRenderObserver=this._scene.onBeforeRenderObservable.add((()=>this._updateToMesh())),this._onAfterStepObserver=this._scene.onAfterStepObservable.add((()=>this._updateToMesh()))),this._attachedToMesh.computeWorldMatrix(!0),this._updateToMesh())}detachFromMesh(){this._attachedToMesh&&this._scene&&(this._onAfterRenderObserver&&(this._scene.onBeforeRenderObservable.remove(this._onAfterRenderObserver),this._scene.onAfterStepObservable.remove(this._onAfterStepObserver)),this._attachedToMesh=null,this._onAfterRenderObserver=null,this._onAfterStepObserver=null,this._scene=null)}_updateToMesh(){const e=this.ray;this._attachedToMesh&&e&&(this._attachedToMesh.isDisposed()?this.detachFromMesh():(this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection,e.direction),_e.TransformCoordinatesToRef(this._meshSpaceOrigin,this._attachedToMesh.getWorldMatrix(),e.origin)))}dispose(){this.hide(),this.detachFromMesh(),this.ray=null}}class D_{static CreateBoneWeightShader(e,t){const i=e.skeleton,s=e.colorBase??Ee.Black(),r=e.colorZero??Ee.Blue(),n=e.colorQuarter??Ee.Green(),o=e.colorHalf??Ee.Yellow(),a=e.colorFull??Ee.Red(),l=e.targetBoneIndex??0;$i.ShadersStore["boneWeights:"+i.name+"VertexShader"]="precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n\n #include\n\n varying vec3 vColor;\n\n uniform vec3 colorBase;\n uniform vec3 colorZero;\n uniform vec3 colorQuarter;\n uniform vec3 colorHalf;\n uniform vec3 colorFull;\n\n uniform float targetBoneIndex;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n vec3 color = colorBase;\n float totalWeight = 0.;\n if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){\n totalWeight += matricesWeights[0];\n }\n if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){\n totalWeight += matricesWeights[1];\n }\n if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){\n totalWeight += matricesWeights[2];\n }\n if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){\n totalWeight += matricesWeights[3];\n }\n\n color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));\n color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));\n color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));\n color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));\n vColor = color;\n\n gl_Position = projection * view * worldPos;\n }",$i.ShadersStore["boneWeights:"+i.name+"FragmentShader"]="\n precision highp float;\n varying vec3 vPosition;\n\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4(vColor, 1.0);\n gl_FragColor = color;\n }\n ";const h=new Nd("boneWeight:"+i.name,t,{vertex:"boneWeights:"+i.name,fragment:"boneWeights:"+i.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return h.setColor3("colorBase",s),h.setColor3("colorZero",r),h.setColor3("colorQuarter",n),h.setColor3("colorHalf",o),h.setColor3("colorFull",a),h.setFloat("targetBoneIndex",l),h.getClassName=()=>"BoneWeightShader",h.transparencyMode=ta.MATERIAL_OPAQUE,h}static CreateSkeletonMapShader(e,t){const i=e.skeleton,s=e.colorMap??[{color:new Ee(1,.38,.18),location:0},{color:new Ee(.59,.18,1),location:.2},{color:new Ee(.59,1,.18),location:.4},{color:new Ee(1,.87,.17),location:.6},{color:new Ee(1,.17,.42),location:.8},{color:new Ee(.17,.68,1),location:1}],r=i.bones.length+1,n=D_._CreateBoneMapColorBuffer(r,s,t),o=new Nd("boneWeights:"+i.name,t,{vertexSource:"precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n uniform float colorMap["+4*i.bones.length+"];\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n #include\n\n varying vec3 vColor;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec3 color = vec3(0.);\n bool first = true;\n\n for (int i = 0; i < 4; i++) {\n int boneIdx = int(matricesIndices[i]);\n float boneWgt = matricesWeights[i];\n\n vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);\n\n if (boneWgt > 0.) {\n if (first) {\n first = false;\n color = c;\n } else {\n color = mix(color, c, boneWgt);\n }\n }\n }\n\n vColor = color;\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n gl_Position = projection * view * worldPos;\n }",fragmentSource:"\n precision highp float;\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4( vColor, 1.0 );\n gl_FragColor = color;\n }\n "},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",n),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=ta.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){const s=new uu("temp",{width:e,height:1},i,!1),r=s.getContext(),n=r.createLinearGradient(0,0,e,0);t.forEach((e=>{n.addColorStop(e.location,e.color.toHexString())})),r.fillStyle=n,r.fillRect(0,0,e,1),s.update();const o=[],a=r.getImageData(0,0,e,1).data,l=1/255;for(let e=0;eD_.DISPLAY_SPHERE_AND_SPURS&&(e=D_.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,s=!0,r=3,n={}){if(this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=s,this.renderingGroupId=r,this.options=n,this.color=Ee.White(),this._debugLines=new Array,this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,n.pauseAnimations=n.pauseAnimations??!0,n.returnToRest=n.returnToRest??!1,n.displayMode=n.displayMode??D_.DISPLAY_LINES,n.displayOptions=n.displayOptions??{},n.displayOptions.midStep=n.displayOptions.midStep??.235,n.displayOptions.midStepFactor=n.displayOptions.midStepFactor??.155,n.displayOptions.sphereBaseSize=n.displayOptions.sphereBaseSize??.15,n.displayOptions.sphereScaleUnit=n.displayOptions.sphereScaleUnit??2,n.displayOptions.sphereFactor=n.displayOptions.sphereFactor??.865,n.displayOptions.spurFollowsChild=n.displayOptions.spurFollowsChild??!1,n.displayOptions.showLocalAxes=n.displayOptions.showLocalAxes??!1,n.displayOptions.localAxesSize=n.displayOptions.localAxesSize??.075,n.computeBonesUsingShaders=n.computeBonesUsingShaders??!0,n.useAllBones=n.useAllBones??!0,this._boneIndices=new Set,!n.useAllBones){const e=t?.getVerticesData(er.MatricesIndicesKind),i=t?.getVerticesData(er.MatricesWeightsKind);if(e&&i)for(let t=0;tD_.DISPLAY_SPHERE_AND_SPURS&&(o=D_.DISPLAY_LINES),this.displayMode=o,this.update(),this._bindObs()}_bindObs(){this.displayMode===D_.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add((()=>{this._displayLinesUpdate()})))}update(){switch(this.displayMode){case D_.DISPLAY_LINES:this._displayLinesUpdate();break;case D_.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case D_.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,s=0,r=0,n=0){const o=ve.Matrix[0],a=t.getParent();if(o.copyFrom(t.getLocalMatrix()),0!==s||0!==r||0!==n){const e=ve.Matrix[1];me.IdentityToRef(e),e.setTranslationFromFloats(s,r,n),e.multiplyToRef(o,o)}a&&o.multiplyToRef(a.getAbsoluteMatrix(),o),o.multiplyToRef(i,o),e.x=o.m[12],e.y=o.m[13],e.z=o.m[14]}_getLinesForBonesWithLength(e,t){const i=e.length;let s,r;t?(s=t.getWorldMatrix(),r=t.position):(s=new me,r=e[0].position);let n=0;for(let t=0;t=0;s--){const t=e[s],o=t.getParent();if(!o||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let a=this._debugLines[i];a||(a=[_e.Zero(),_e.Zero()],this._debugLines[i]=a),t.getAbsolutePositionToRef(r,a[0]),o.getAbsolutePositionToRef(r,a[1]),a[0].subtractInPlace(n),a[1].subtractInPlace(n),i++}s||r.dispose()}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){null!==e&&-1!==e._index?(this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)):t.copyFrom(me.Identity())}_createSpur(e,t,i,s,r,n){const o=i.subtract(e),a=o.length(),l=o.normalize().scale(a),h=r.midStep||.165,c=r.midStepFactor||.215,u=l.scale(h),d=Zd("skeletonViewer",{shape:[new _e(1,-1,0),new _e(1,1,0),new _e(-1,1,0),new _e(-1,-1,0),new _e(1,-1,0)],path:[_e.Zero(),u,l],scaleFunction:e=>{switch(e){case 0:case 2:return 0;case 1:return a*c}return 0},sideOrientation:ha.DEFAULTSIDE,updatable:!1},n),_=d.getTotalVertices(),p=[],f=[];for(let e=0;e<_;e++)p.push(1,0,0,0),s&&r.spurFollowsChild&&e>9?f.push(s.getIndex(),0,0,0):f.push(t.getIndex(),0,0,0);return d.position=e.clone(),d.setVerticesData(er.MatricesWeightsKind,p,!1),d.setVerticesData(er.MatricesIndicesKind,f,!1),d.convertToFlatShadedMesh(),d}_getBoundingSphereForBone(e){if(!this.mesh)return null;const t=this.mesh.getVerticesData(er.PositionKind),i=this.mesh.getIndices(),s=this.mesh.getVerticesData(er.MatricesWeightsKind),r=this.mesh.getVerticesData(er.MatricesIndicesKind);if(!(t&&i&&s&&r))return null;const n=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new _e(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);let a=0;for(let l=0;l1e-5){_e.FromArrayToRef(t,3*h,ve.Vector3[0]),n.minimizeInPlace(ve.Vector3[0]),o.maximizeInPlace(ve.Vector3[0]),a++;break}}}return a>1?{center:_e.Center(n,o),radius:_e.Distance(n,o)/2}:null}_buildSpheresAndSpurs(e=!0){this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;const t=this.utilityLayer?.utilityLayerScene,i=this.skeleton.bones,s=[],r=[],n=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,t.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let o=Number.NEGATIVE_INFINITY;const a=this.options.displayOptions||{};for(let n=0;n0)l.children.forEach((i=>{const s=new me;i.getLocalMatrix().multiplyToRef(h,s);const n=new _e;s.decompose(void 0,void 0,n);const u=_e.Distance(c,n);u>o&&(o=u),e||r.push(this._createSpur(c,l,n,i,a,t))}));else{const i=this._getBoundingSphereForBone(l.getIndex());if(i&&(i.radius>o&&(o=i.radius),!e)){let e;const s=l.getParent();s?(this._getAbsoluteBindPoseToRef(s,h),h.decompose(void 0,void 0,ve.Vector3[0]),e=c.subtract(ve.Vector3[0]).normalize().scale(i.radius).add(c)):e=i.center.subtract(c).normalize().scale(i.radius).add(c),r.push(this._createSpur(c,l,e,null,a,t))}}const u=_d("skeletonViewer",{segments:6,diameter:a.sphereBaseSize||.2,updatable:!0},t),d=u.getTotalVertices(),_=[],p=[];for(let e=0;e{e.setEnabled(t<6&&this._showLines||t>=6&&this._showPlanes)})),this._oldPosition.set(Number.NaN,Number.NaN,Number.NaN),this._visible=!0}hide(){this._lightHelperFrustumMeshes.forEach((e=>{e.setEnabled(!1)})),this._visible=!1}update(){if(!this._visible)return;if(this._oldPosition.equals(this._light.position)&&this._oldDirection.equals(this._light.direction)&&this._oldAutoCalc===this._light.autoCalcShadowZBounds&&this._oldMinZ===this._light.shadowMinZ&&this._oldMaxZ===this._light.shadowMaxZ)return;this._oldPosition.copyFrom(this._light.position),this._oldDirection.copyFrom(this._light.direction),this._oldAutoCalc=this._light.autoCalcShadowZBounds,this._oldMinZ=this._light.shadowMinZ,this._oldMaxZ=this._light.shadowMaxZ,ve.Vector3[0].set(this._light.orthoLeft,this._light.orthoBottom,void 0!==this._light.shadowMinZ?this._light.shadowMinZ:this._camera.minZ),ve.Vector3[1].set(this._light.orthoRight,this._light.orthoTop,void 0!==this._light.shadowMaxZ?this._light.shadowMaxZ:this._camera.maxZ);const e=this._getInvertViewMatrix();ve.Vector3[2].copyFromFloats(ve.Vector3[1].x,ve.Vector3[1].y,ve.Vector3[0].z),ve.Vector3[3].copyFromFloats(ve.Vector3[1].x,ve.Vector3[0].y,ve.Vector3[0].z),ve.Vector3[4].copyFromFloats(ve.Vector3[0].x,ve.Vector3[0].y,ve.Vector3[0].z),ve.Vector3[5].copyFromFloats(ve.Vector3[0].x,ve.Vector3[1].y,ve.Vector3[0].z),_e.TransformCoordinatesToRef(ve.Vector3[2],e,ve.Vector3[2]),_e.TransformCoordinatesToRef(ve.Vector3[3],e,ve.Vector3[3]),_e.TransformCoordinatesToRef(ve.Vector3[4],e,ve.Vector3[4]),_e.TransformCoordinatesToRef(ve.Vector3[5],e,ve.Vector3[5]),ve.Vector3[6].copyFromFloats(ve.Vector3[1].x,ve.Vector3[1].y,ve.Vector3[1].z),ve.Vector3[7].copyFromFloats(ve.Vector3[1].x,ve.Vector3[0].y,ve.Vector3[1].z),ve.Vector3[8].copyFromFloats(ve.Vector3[0].x,ve.Vector3[0].y,ve.Vector3[1].z),ve.Vector3[9].copyFromFloats(ve.Vector3[0].x,ve.Vector3[1].y,ve.Vector3[1].z),_e.TransformCoordinatesToRef(ve.Vector3[6],e,ve.Vector3[6]),_e.TransformCoordinatesToRef(ve.Vector3[7],e,ve.Vector3[7]),_e.TransformCoordinatesToRef(ve.Vector3[8],e,ve.Vector3[8]),_e.TransformCoordinatesToRef(ve.Vector3[9],e,ve.Vector3[9]),Ud("nearlines",{updatable:!0,points:this._nearLinesPoints,instance:this._lightHelperFrustumMeshes[0]},this._scene),Ud("farlines",{updatable:!0,points:this._farLinesPoints,instance:this._lightHelperFrustumMeshes[1]},this._scene),Ud("trlines",{updatable:!0,points:this._trLinesPoints,instance:this._lightHelperFrustumMeshes[2]},this._scene),Ud("brlines",{updatable:!0,points:this._brLinesPoints,instance:this._lightHelperFrustumMeshes[3]},this._scene),Ud("tllines",{updatable:!0,points:this._tlLinesPoints,instance:this._lightHelperFrustumMeshes[4]},this._scene),Ud("bllines",{updatable:!0,points:this._blLinesPoints,instance:this._lightHelperFrustumMeshes[5]},this._scene),ve.Vector3[2].toArray(this._nearPlaneVertices,0),ve.Vector3[3].toArray(this._nearPlaneVertices,3),ve.Vector3[4].toArray(this._nearPlaneVertices,6),ve.Vector3[5].toArray(this._nearPlaneVertices,9),this._lightHelperFrustumMeshes[6].geometry?.updateVerticesDataDirectly("position",this._nearPlaneVertices,0),ve.Vector3[6].toArray(this._farPlaneVertices,0),ve.Vector3[7].toArray(this._farPlaneVertices,3),ve.Vector3[8].toArray(this._farPlaneVertices,6),ve.Vector3[9].toArray(this._farPlaneVertices,9),this._lightHelperFrustumMeshes[7].geometry?.updateVerticesDataDirectly("position",this._farPlaneVertices,0),ve.Vector3[2].toArray(this._rightPlaneVertices,0),ve.Vector3[6].toArray(this._rightPlaneVertices,3),ve.Vector3[7].toArray(this._rightPlaneVertices,6),ve.Vector3[3].toArray(this._rightPlaneVertices,9),this._lightHelperFrustumMeshes[8].geometry?.updateVerticesDataDirectly("position",this._rightPlaneVertices,0),ve.Vector3[5].toArray(this._leftPlaneVertices,0),ve.Vector3[9].toArray(this._leftPlaneVertices,3),ve.Vector3[8].toArray(this._leftPlaneVertices,6),ve.Vector3[4].toArray(this._leftPlaneVertices,9),this._lightHelperFrustumMeshes[9].geometry?.updateVerticesDataDirectly("position",this._leftPlaneVertices,0),ve.Vector3[2].toArray(this._topPlaneVertices,0),ve.Vector3[6].toArray(this._topPlaneVertices,3),ve.Vector3[9].toArray(this._topPlaneVertices,6),ve.Vector3[5].toArray(this._topPlaneVertices,9),this._lightHelperFrustumMeshes[10].geometry?.updateVerticesDataDirectly("position",this._topPlaneVertices,0),ve.Vector3[3].toArray(this._bottomPlaneVertices,0),ve.Vector3[7].toArray(this._bottomPlaneVertices,3),ve.Vector3[8].toArray(this._bottomPlaneVertices,6),ve.Vector3[4].toArray(this._bottomPlaneVertices,9),this._lightHelperFrustumMeshes[11].geometry?.updateVerticesDataDirectly("position",this._bottomPlaneVertices,0)}dispose(){this._lightHelperFrustumMeshes.forEach((e=>{e.material?.dispose(),e.dispose()})),this._rootNode.dispose()}_createGeometry(){this._rootNode=new lo("directionalLightHelperRoot_"+this._light.name,this._scene),this._rootNode.parent=this._light.parent,this._nearLinesPoints=[ve.Vector3[0],ve.Vector3[1],ve.Vector3[2],ve.Vector3[3],ve.Vector3[4]];const e=Ud("nearlines",{updatable:!0,points:this._nearLinesPoints},this._scene);e.parent=this._rootNode,e.alwaysSelectAsActiveMesh=!0,this._farLinesPoints=[ve.Vector3[5],ve.Vector3[6],ve.Vector3[7],ve.Vector3[8],ve.Vector3[9]];const t=Ud("farlines",{updatable:!0,points:this._farLinesPoints},this._scene);t.parent=this._rootNode,t.alwaysSelectAsActiveMesh=!0,this._trLinesPoints=[ve.Vector3[10],ve.Vector3[11]];const i=Ud("trlines",{updatable:!0,points:this._trLinesPoints},this._scene);i.parent=this._rootNode,i.alwaysSelectAsActiveMesh=!0,this._brLinesPoints=[ve.Vector3[12],ve.Vector3[0]];const s=Ud("brlines",{updatable:!0,points:this._brLinesPoints},this._scene);s.parent=this._rootNode,s.alwaysSelectAsActiveMesh=!0,this._tlLinesPoints=[ve.Vector3[1],ve.Vector3[2]];const r=Ud("tllines",{updatable:!0,points:this._tlLinesPoints},this._scene);r.parent=this._rootNode,r.alwaysSelectAsActiveMesh=!0,this._blLinesPoints=[ve.Vector3[3],ve.Vector3[4]];const n=Ud("bllines",{updatable:!0,points:this._blLinesPoints},this._scene);n.parent=this._rootNode,n.alwaysSelectAsActiveMesh=!0,this._lightHelperFrustumMeshes.push(e,t,i,s,r,n);const o=(e,t,i)=>{const s=new ha(e+"plane",this._scene),r=new cu(e+"PlaneMat",this._scene);s.material=r,s.parent=this._rootNode,s.alwaysSelectAsActiveMesh=!0,r.emissiveColor=t,r.alpha=this.transparency,r.backFaceCulling=!1,r.disableLighting=!0;const n=new Wn;n.positions=i,n.indices=[0,1,2,0,2,3],n.applyToMesh(s,!0),this._lightHelperFrustumMeshes.push(s)};this._nearPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._farPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._rightPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._leftPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._topPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],this._bottomPlaneVertices=[0,0,0,0,0,0,0,0,0,0,0,0],o("near",new Ee(1,0,0),this._nearPlaneVertices),o("far",new Ee(.3,0,0),this._farPlaneVertices),o("right",new Ee(0,1,0),this._rightPlaneVertices),o("left",new Ee(0,.3,0),this._leftPlaneVertices),o("top",new Ee(0,0,1),this._topPlaneVertices),o("bottom",new Ee(0,0,.3),this._bottomPlaneVertices),this._nearLinesPoints[0]=ve.Vector3[2],this._nearLinesPoints[1]=ve.Vector3[3],this._nearLinesPoints[2]=ve.Vector3[4],this._nearLinesPoints[3]=ve.Vector3[5],this._nearLinesPoints[4]=ve.Vector3[2],this._farLinesPoints[0]=ve.Vector3[6],this._farLinesPoints[1]=ve.Vector3[7],this._farLinesPoints[2]=ve.Vector3[8],this._farLinesPoints[3]=ve.Vector3[9],this._farLinesPoints[4]=ve.Vector3[6],this._trLinesPoints[0]=ve.Vector3[2],this._trLinesPoints[1]=ve.Vector3[6],this._brLinesPoints[0]=ve.Vector3[3],this._brLinesPoints[1]=ve.Vector3[7],this._tlLinesPoints[0]=ve.Vector3[4],this._tlLinesPoints[1]=ve.Vector3[8],this._blLinesPoints[0]=ve.Vector3[5],this._blLinesPoints[1]=ve.Vector3[9]}_getInvertViewMatrix(){return me.LookAtLHToRef(this._light.position,this._light.position.add(this._light.direction),_e.UpReadOnly,this._inverseViewMatrix),this._inverseViewMatrix.invertToRef(this._inverseViewMatrix),this._inverseViewMatrix}}class N_{}N_.AUTOSAMPLERSUFFIX="Sampler",N_.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS",N_.ALPHA_DISABLE=0,N_.ALPHA_ADD=1,N_.ALPHA_COMBINE=2,N_.ALPHA_SUBTRACT=3,N_.ALPHA_MULTIPLY=4,N_.ALPHA_MAXIMIZED=5,N_.ALPHA_ONEONE=6,N_.ALPHA_PREMULTIPLIED=7,N_.ALPHA_PREMULTIPLIED_PORTERDUFF=8,N_.ALPHA_INTERPOLATE=9,N_.ALPHA_SCREENMODE=10,N_.ALPHA_ONEONE_ONEONE=11,N_.ALPHA_ALPHATOCOLOR=12,N_.ALPHA_REVERSEONEMINUS=13,N_.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,N_.ALPHA_ONEONE_ONEZERO=15,N_.ALPHA_EXCLUSION=16,N_.ALPHA_LAYER_ACCUMULATE=17,N_.ALPHA_EQUATION_ADD=0,N_.ALPHA_EQUATION_SUBSTRACT=1,N_.ALPHA_EQUATION_REVERSE_SUBTRACT=2,N_.ALPHA_EQUATION_MAX=3,N_.ALPHA_EQUATION_MIN=4,N_.ALPHA_EQUATION_DARKEN=5,N_.DELAYLOADSTATE_NONE=0,N_.DELAYLOADSTATE_LOADED=1,N_.DELAYLOADSTATE_LOADING=2,N_.DELAYLOADSTATE_NOTLOADED=4,N_.NEVER=512,N_.ALWAYS=519,N_.LESS=513,N_.EQUAL=514,N_.LEQUAL=515,N_.GREATER=516,N_.GEQUAL=518,N_.NOTEQUAL=517,N_.KEEP=7680,N_.ZERO=0,N_.REPLACE=7681,N_.INCR=7682,N_.DECR=7683,N_.INVERT=5386,N_.INCR_WRAP=34055,N_.DECR_WRAP=34056,N_.TEXTURE_CLAMP_ADDRESSMODE=0,N_.TEXTURE_WRAP_ADDRESSMODE=1,N_.TEXTURE_MIRROR_ADDRESSMODE=2,N_.TEXTURE_CREATIONFLAG_STORAGE=1,N_.TEXTUREFORMAT_ALPHA=0,N_.TEXTUREFORMAT_LUMINANCE=1,N_.TEXTUREFORMAT_LUMINANCE_ALPHA=2,N_.TEXTUREFORMAT_RGB=4,N_.TEXTUREFORMAT_RGBA=5,N_.TEXTUREFORMAT_RED=6,N_.TEXTUREFORMAT_R=6,N_.TEXTUREFORMAT_RG=7,N_.TEXTUREFORMAT_RED_INTEGER=8,N_.TEXTUREFORMAT_R_INTEGER=8,N_.TEXTUREFORMAT_RG_INTEGER=9,N_.TEXTUREFORMAT_RGB_INTEGER=10,N_.TEXTUREFORMAT_RGBA_INTEGER=11,N_.TEXTUREFORMAT_BGRA=12,N_.TEXTUREFORMAT_DEPTH24_STENCIL8=13,N_.TEXTUREFORMAT_DEPTH32_FLOAT=14,N_.TEXTUREFORMAT_DEPTH16=15,N_.TEXTUREFORMAT_DEPTH24=16,N_.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,N_.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,N_.TEXTUREFORMAT_STENCIL8=19,N_.TEXTUREFORMAT_UNDEFINED=4294967295,N_.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,N_.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,N_.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,N_.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,N_.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,N_.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,N_.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,N_.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,N_.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,N_.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,N_.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,N_.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,N_.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,N_.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,N_.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,N_.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,N_.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,N_.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,N_.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,N_.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,N_.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,N_.TEXTURETYPE_UNSIGNED_BYTE=0,N_.TEXTURETYPE_UNSIGNED_INT=0,N_.TEXTURETYPE_FLOAT=1,N_.TEXTURETYPE_HALF_FLOAT=2,N_.TEXTURETYPE_BYTE=3,N_.TEXTURETYPE_SHORT=4,N_.TEXTURETYPE_UNSIGNED_SHORT=5,N_.TEXTURETYPE_INT=6,N_.TEXTURETYPE_UNSIGNED_INTEGER=7,N_.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,N_.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,N_.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,N_.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,N_.TEXTURETYPE_UNSIGNED_INT_24_8=12,N_.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,N_.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,N_.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,N_.TEXTURETYPE_UNDEFINED=16,N_.TEXTURE_2D=3553,N_.TEXTURE_2D_ARRAY=35866,N_.TEXTURE_CUBE_MAP=34067,N_.TEXTURE_CUBE_MAP_ARRAY=3735928559,N_.TEXTURE_3D=32879,N_.TEXTURE_NEAREST_SAMPLINGMODE=1,N_.TEXTURE_NEAREST_NEAREST=1,N_.TEXTURE_BILINEAR_SAMPLINGMODE=2,N_.TEXTURE_LINEAR_LINEAR=2,N_.TEXTURE_TRILINEAR_SAMPLINGMODE=3,N_.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,N_.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,N_.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,N_.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,N_.TEXTURE_NEAREST_LINEAR=7,N_.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,N_.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,N_.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,N_.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,N_.TEXTURE_LINEAR_NEAREST=12,N_.TEXTURE_EXPLICIT_MODE=0,N_.TEXTURE_SPHERICAL_MODE=1,N_.TEXTURE_PLANAR_MODE=2,N_.TEXTURE_CUBIC_MODE=3,N_.TEXTURE_PROJECTION_MODE=4,N_.TEXTURE_SKYBOX_MODE=5,N_.TEXTURE_INVCUBIC_MODE=6,N_.TEXTURE_EQUIRECTANGULAR_MODE=7,N_.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,N_.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,N_.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,N_.TEXTURE_FILTERING_QUALITY_HIGH=64,N_.TEXTURE_FILTERING_QUALITY_MEDIUM=16,N_.TEXTURE_FILTERING_QUALITY_LOW=8,N_.SCALEMODE_FLOOR=1,N_.SCALEMODE_NEAREST=2,N_.SCALEMODE_CEILING=3,N_.MATERIAL_TextureDirtyFlag=1,N_.MATERIAL_LightDirtyFlag=2,N_.MATERIAL_FresnelDirtyFlag=4,N_.MATERIAL_AttributesDirtyFlag=8,N_.MATERIAL_MiscDirtyFlag=16,N_.MATERIAL_PrePassDirtyFlag=32,N_.MATERIAL_AllDirtyFlag=63,N_.MATERIAL_TriangleFillMode=0,N_.MATERIAL_WireFrameFillMode=1,N_.MATERIAL_PointFillMode=2,N_.MATERIAL_PointListDrawMode=3,N_.MATERIAL_LineListDrawMode=4,N_.MATERIAL_LineLoopDrawMode=5,N_.MATERIAL_LineStripDrawMode=6,N_.MATERIAL_TriangleStripDrawMode=7,N_.MATERIAL_TriangleFanDrawMode=8,N_.MATERIAL_ClockWiseSideOrientation=0,N_.MATERIAL_CounterClockWiseSideOrientation=1,N_.ACTION_NothingTrigger=0,N_.ACTION_OnPickTrigger=1,N_.ACTION_OnLeftPickTrigger=2,N_.ACTION_OnRightPickTrigger=3,N_.ACTION_OnCenterPickTrigger=4,N_.ACTION_OnPickDownTrigger=5,N_.ACTION_OnDoublePickTrigger=6,N_.ACTION_OnPickUpTrigger=7,N_.ACTION_OnPickOutTrigger=16,N_.ACTION_OnLongPressTrigger=8,N_.ACTION_OnPointerOverTrigger=9,N_.ACTION_OnPointerOutTrigger=10,N_.ACTION_OnEveryFrameTrigger=11,N_.ACTION_OnIntersectionEnterTrigger=12,N_.ACTION_OnIntersectionExitTrigger=13,N_.ACTION_OnKeyDownTrigger=14,N_.ACTION_OnKeyUpTrigger=15,N_.PARTICLES_BILLBOARDMODE_Y=2,N_.PARTICLES_BILLBOARDMODE_ALL=7,N_.PARTICLES_BILLBOARDMODE_STRETCHED=8,N_.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,N_.MESHES_CULLINGSTRATEGY_STANDARD=0,N_.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,N_.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,N_.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,N_.SCENELOADER_NO_LOGGING=0,N_.SCENELOADER_MINIMAL_LOGGING=1,N_.SCENELOADER_SUMMARY_LOGGING=2,N_.SCENELOADER_DETAILED_LOGGING=3,N_.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,N_.PREPASS_POSITION_TEXTURE_TYPE=1,N_.PREPASS_VELOCITY_TEXTURE_TYPE=2,N_.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,N_.PREPASS_COLOR_TEXTURE_TYPE=4,N_.PREPASS_DEPTH_TEXTURE_TYPE=5,N_.PREPASS_NORMAL_TEXTURE_TYPE=6,N_.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,N_.BUFFER_CREATIONFLAG_READ=1,N_.BUFFER_CREATIONFLAG_WRITE=2,N_.BUFFER_CREATIONFLAG_READWRITE=3,N_.BUFFER_CREATIONFLAG_UNIFORM=4,N_.BUFFER_CREATIONFLAG_VERTEX=8,N_.BUFFER_CREATIONFLAG_INDEX=16,N_.BUFFER_CREATIONFLAG_STORAGE=32,N_.BUFFER_CREATIONFLAG_INDIRECT=64,N_.RENDERPASS_MAIN=0,N_.INPUT_ALT_KEY=18,N_.INPUT_CTRL_KEY=17,N_.INPUT_META_KEY1=91,N_.INPUT_META_KEY2=92,N_.INPUT_META_KEY3=93,N_.INPUT_SHIFT_KEY=16,N_.SNAPSHOTRENDERING_STANDARD=0,N_.SNAPSHOTRENDERING_FAST=1,N_.PERSPECTIVE_CAMERA=0,N_.ORTHOGRAPHIC_CAMERA=1,N_.FOVMODE_VERTICAL_FIXED=0,N_.FOVMODE_HORIZONTAL_FIXED=1,N_.RIG_MODE_NONE=0,N_.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,N_.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,N_.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,N_.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,N_.RIG_MODE_STEREOSCOPIC_INTERLACED=14,N_.RIG_MODE_VR=20,N_.RIG_MODE_CUSTOM=22,N_.MAX_SUPPORTED_UV_SETS=6,N_.GL_ALPHA_EQUATION_ADD=32774,N_.GL_ALPHA_EQUATION_MIN=32775,N_.GL_ALPHA_EQUATION_MAX=32776,N_.GL_ALPHA_EQUATION_SUBTRACT=32778,N_.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,N_.GL_ALPHA_FUNCTION_SRC=768,N_.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,N_.GL_ALPHA_FUNCTION_SRC_ALPHA=770,N_.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,N_.GL_ALPHA_FUNCTION_DST_ALPHA=772,N_.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,N_.GL_ALPHA_FUNCTION_DST_COLOR=774,N_.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,N_.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,N_.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,N_.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,N_.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,N_.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,N_.SnippetUrl="https://snippet.babylonjs.com",N_.FOGMODE_NONE=0,N_.FOGMODE_EXP=1,N_.FOGMODE_EXP2=2,N_.FOGMODE_LINEAR=3,N_.BYTE=5120,N_.UNSIGNED_BYTE=5121,N_.SHORT=5122,N_.UNSIGNED_SHORT=5123,N_.INT=5124,N_.UNSIGNED_INT=5125,N_.FLOAT=5126,N_.PositionKind="position",N_.NormalKind="normal",N_.TangentKind="tangent",N_.UVKind="uv",N_.UV2Kind="uv2",N_.UV3Kind="uv3",N_.UV4Kind="uv4",N_.UV5Kind="uv5",N_.UV6Kind="uv6",N_.ColorKind="color",N_.ColorInstanceKind="instanceColor",N_.MatricesIndicesKind="matricesIndices",N_.MatricesWeightsKind="matricesWeights",N_.MatricesIndicesExtraKind="matricesIndicesExtra",N_.MatricesWeightsExtraKind="matricesWeightsExtra";class F_{constructor(){this.renderWidth=512,this.renderHeight=256,this.textureSize=512,this.deterministicLockstep=!1,this.lockstepMaxSteps=4}}class L_ extends oo{isDeterministicLockStep(){return this._options.deterministicLockstep}getLockstepMaxSteps(){return this._options.lockstepMaxSteps}getHardwareScalingLevel(){return 1}constructor(e=new F_){super(null),void 0===e.deterministicLockstep&&(e.deterministicLockstep=!1),void 0!==e.timeStep&&(this._timeStep=e.timeStep),void 0===e.lockstepMaxSteps&&(e.lockstepMaxSteps=4),this._options=e,se.SetMatrixPrecision(!!e.useHighPrecisionMatrix),this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:512,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!1,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:0,uintIndices:!1,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!1,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!1,instancedArrays:!1,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,maxMSAASamples:1,blendMinMax:!1,canUseGLInstanceID:!1,canUseGLVertexID:!1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:128,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!1,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1},e.renderingCanvas&&(this._renderingCanvas=e.renderingCanvas),Ne.Log(`Babylon.js v${oo.Version} - Null engine`);const t="undefined"!=typeof self?self:void 0!==i.g?i.g:window;"undefined"==typeof URL&&(t.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(t.Blob=function(){})}createVertexBuffer(e){const t=new Qs;return t.references=1,t}createIndexBuffer(e){const t=new Qs;return t.references=1,t}clear(e,t,i,s=!1){}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._options.renderWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._options.renderHeight}setViewport(e,t,i){this._cachedViewport=e}createShaderProgram(e,t,i,s,r){return{__SPECTOR_rebuildProgram:null}}getUniforms(e,t){return[]}getAttributes(e,t){return[]}bindSamplers(e){this._currentEffect=null}enableEffect(e){e=null!==e&&Ws(e)?e.effect:e,this._currentEffect=e,e&&(e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setState(e,t=0,i,s=!1,r,n,o=0){}setIntArray(e,t){return!0}setIntArray2(e,t){return!0}setIntArray3(e,t){return!0}setIntArray4(e,t){return!0}setFloatArray(e,t){return!0}setFloatArray2(e,t){return!0}setFloatArray3(e,t){return!0}setFloatArray4(e,t){return!0}setArray(e,t){return!0}setArray2(e,t){return!0}setArray3(e,t){return!0}setArray4(e,t){return!0}setMatrices(e,t){return!0}setMatrix3x3(e,t){return!0}setMatrix2x2(e,t){return!0}setFloat(e,t){return!0}setFloat2(e,t,i){return!0}setFloat3(e,t,i,s){return!0}setBool(e,t){return!0}setFloat4(e,t,i,s,r){return!0}setAlphaMode(e,t=!1){this._alphaMode!==e&&(this.alphaState.alphaBlend=0!==e,t||this.setDepthWrite(0===e),this._alphaMode=e)}bindBuffers(e,t,i){}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this.depthCullingState.reset(),this.alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}draw(e,t,i,s){}drawElementsType(e,t,i,s){}drawArraysType(e,t,i,s){}_createTexture(){return{}}_releaseTexture(e){}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u){const d=new ss(this,is.Url),_=String(e);return d.url=_,d.generateMipMaps=!t,d.samplingMode=r,d.invertY=i,d.baseWidth=this._options.textureSize,d.baseHeight=this._options.textureSize,d.width=this._options.textureSize,d.height=this._options.textureSize,h&&(d.format=h),d.isReady=!0,n&&setTimeout((()=>{n(d)})),this._internalTexturesCache.push(d),d}_createHardwareRenderTargetWrapper(e,t,i){const s=new Bl(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),s={};void 0!==t&&"object"==typeof t?(s.generateMipMaps=t.generateMipMaps,s.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,s.generateStencilBuffer=s.generateDepthBuffer&&t.generateStencilBuffer,s.type=void 0===t.type?0:t.type,s.samplingMode=void 0===t.samplingMode?3:t.samplingMode):(s.generateMipMaps=t,s.generateDepthBuffer=!0,s.generateStencilBuffer=!1,s.type=0,s.samplingMode=3);const r=new ss(this,is.RenderTarget),n=e.width||e,o=e.height||e;return i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer,r.baseWidth=n,r.baseHeight=o,r.width=n,r.height=o,r.isReady=!0,r.samples=1,r.generateMipMaps=!!s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,this._internalTexturesCache.push(r),i}createRenderTargetCubeTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,(1!==s.type||this._caps.textureFloatLinearFiltering)&&(2!==s.type||this._caps.textureHalfFloatLinearFiltering)||(s.samplingMode=1),i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer;const r=new ss(this,is.RenderTarget);return r.baseWidth=e,r.baseHeight=e,r.width=e,r.height=e,r.isReady=!0,r.isCube=!0,r.samples=1,r.generateMipMaps=!!s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,this._internalTexturesCache.push(r),i}updateTextureSamplingMode(e,t){t.samplingMode=e}createRawTexture(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new ss(this,is.Raw);return u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u._compression=a,u.type=l,u._useSRGBBuffer=c,this._doNotHandleContextLost||(u._bufferView=e),u}updateRawTexture(e,t,i,s,r=null,n=0,o=!1){e&&(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r,e.type=n,e._useSRGBBuffer=o)}bindFramebuffer(e,t,i,s,r){this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._currentFramebuffer=null,this._cachedViewport&&!r&&this.setViewport(this._cachedViewport,i,s)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._currentFramebuffer=null}createDynamicVertexBuffer(e){const t=new Qs;return t.references=1,t.capacity=1,t}updateDynamicTexture(e,t,i,s=!1,r){}areAllEffectsReady(){return!0}getError(){return 0}_getUnpackAlignement(){return 1}_unpackFlipY(e){}updateDynamicIndexBuffer(e,t,i=0){}updateDynamicVertexBuffer(e,t,i,s){}_bindTextureDirectly(e,t){return this._boundTexturesCache[this._activeChannel]!==t&&(this._boundTexturesCache[this._activeChannel]=t,!0)}_bindTexture(e,t){e<0||this._bindTextureDirectly(0,t)}_deleteBuffer(e){}releaseEffects(){}displayLoadingUI(){}hideLoadingUI(){}set loadingUIText(e){}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){}_uploadDataToTextureDirectly(e,t,i=0,s=0){}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){}_uploadImageToTexture(e,t,i=0,s=0){}}ns.prototype._partialLoadFile=function(e,t,i,s,r=null){this._loadFile(e,(e=>{i[t]=e,i._internalCount++,6===i._internalCount&&s(i)}),void 0,void 0,!0,((e,t)=>{r&&e&&r(e.status+" "+e.statusText,t)}))},ns.prototype._cascadeLoadFiles=function(e,t,i,s=null){const r=[];r._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,r,t,s)},ns.prototype._cascadeLoadImgs=function(e,t,i,s,r=null,n){const o=[];o._internalCount=0;for(let a=0;a<6;a++)this._partialLoadImg(s[a],a,o,e,t,i,r,n)},ns.prototype._partialLoadImg=function(e,t,i,s,r,n,o=null,a){const l=Cs();ds(e,(e=>{i[t]=e,i._internalCount++,s&&s.removePendingData(l),6===i._internalCount&&n&&n(r,i)}),((e,t)=>{s&&s.removePendingData(l),o&&o(e,t)}),s?s.offlineProvider:null,a),s&&s.addPendingData(l)},ns.prototype.createCubeTextureBase=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d=null,_=null,p=!1){const f=u||new ss(this,is.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!s,f._lodGenerationScale=h,f._lodGenerationOffset=c,f._useSRGBBuffer=!!p&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!s),f!==u&&(f.label=e.substring(0,60)),this._doNotHandleContextLost||(f._extension=a,f._files=i);const m=e;this._transformTextureUrl&&!u&&(e=this._transformTextureUrl(e));const g=e.split("?")[0],v=g.lastIndexOf("."),x=a||(v>-1?g.substring(v).toLowerCase():"");let b=null;for(const e of ns._TextureLoaders)if(e.canLoad(x)){b=e;break}const T=(u,g)=>{e===m?n&&u&&n(u.status+" "+u.statusText,g):(Ne.Warn(`Failed to load ${e}, falling back to the ${m}`),this.createCubeTextureBase(m,t,i,!!s,r,n,o,a,l,h,c,f,d,_,p))};if(b){const s=e=>{d&&d(f,e),b.loadCubeData(e,f,l,r,n)};i&&6===i.length?b.supportCascades?this._cascadeLoadFiles(t,(e=>s(e.map((e=>new Uint8Array(e))))),i,n):n?n("Textures type does not support cascades."):Ne.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>s(new Uint8Array(e))),void 0,void 0,!0,T)}else{if(!i||0===i.length)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(t,f,((e,t)=>{_&&_(e,t)}),i,n)}return this._internalTexturesCache.push(f),f};class B_{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=_o.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=_o.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}ns.prototype.getGPUFrameTimeCounter=function(){return null},ns.prototype.captureGPUFrameTime=function(e){},ns.prototype.createQuery=function(){return null},ns.prototype.deleteQuery=function(e){return this},ns.prototype.isQueryResultAvailable=function(e){return!1},ns.prototype.getQueryResult=function(e){return 0},ns.prototype.beginOcclusionQuery=function(e,t){return!1},ns.prototype.endOcclusionQuery=function(e){return this},Object.defineProperty(_o.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(_o.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new B_),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(_o.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(_o.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(_o.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(_o.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(_o.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),_o.prototype._checkOcclusionQuery=function(){const e=this._occlusionDataStorage;if(e.occlusionType===_o.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;const t=this.getEngine();if(!t.getCaps().supportOcclusionQuery)return e.isOccluded=!1,!1;if(!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&null!==this._occlusionQuery&&void 0!==this._occlusionQuery)if(t.isQueryResultAvailable(this._occlusionQuery)){const i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,!(-1!==e.occlusionRetryCount&&e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==_o.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==_o.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}const i=this.getScene();if(i.getBoundingBoxRenderer){const s=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),this._occlusionQuery&&t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(s.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded};class k_{}const V_=new K,U_=new K;Object.defineProperty(ns.prototype,"onBeforeViewRenderObservable",{get:function(){return V_}}),Object.defineProperty(ns.prototype,"onAfterViewRenderObservable",{get:function(){return U_}}),Object.defineProperty(ns.prototype,"inputElement",{get:function(){return this._inputElement},set:function(e){this._inputElement!==e&&(this._inputElement=e,this._onEngineViewChanged?.())}}),ns.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},ns.prototype.registerView=function(e,t,i){this.views||(this.views=[]);for(const t of this.views)if(t.target===e)return t;const s=this.getRenderingCanvas();s&&(e.width=s.width,e.height=s.height);const r={target:e,camera:t,clearBeforeCopy:i,enabled:!0,id:(1e5*Math.random()).toFixed()};return this.views.push(r),t&&!Array.isArray(t)&&t.onDisposeObservable.add((()=>{this.unRegisterView(e)})),r},ns.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(const t of this.views)if(t.target===e){const e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},ns.prototype._renderViewStep=function(e){const t=e.target,i=t.getContext("2d");if(!i)return!0;const s=this.getRenderingCanvas();V_.notifyObservers(e);const r=e.camera;let n=null,o=null,a=null;if(r&&(a=Array.isArray(r)?r[0].getScene():r.getScene(),n=a.activeCamera,o=a.activeCameras,this.activeView=e,Array.isArray(r)?a.activeCameras=r:(a.activeCamera=r,a.activeCameras=null)),e.customResize)e.customResize(t);else{const e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),r=e!==t.width||s.width!==t.width||i!==t.height||s.height!==t.height;t.clientWidth&&t.clientHeight&&r&&(t.width=e,t.height=i,this.setSize(e,i))}return!(!s.width||!s.height||(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,s.width,s.height),i.drawImage(s,0,0),a&&(a.activeCameras=o,a.activeCamera=n),U_.notifyObservers(e),0))},ns.prototype._renderViews=function(){if(!this.views||0===this.views.length)return!1;if(!this.getRenderingCanvas())return!1;let e;for(const t of this.views)if(t.enabled)if(t.target!==this.inputElement){if(!this._renderViewStep(t))return!1}else e=t;return!(e&&!this._renderViewStep(e)||(this.activeView=null,0))},ns.prototype._debugPushGroup=function(e,t){},ns.prototype._debugPopGroup=function(e){},ns.prototype._debugInsertMarker=function(e,t){},ns.prototype._debugFlushPendingCommands=function(){};class G_{constructor(){this._timeElapsedQueryEnded=!1}}oo.prototype.createQuery=function(){const e=this._gl.createQuery();if(!e)throw new Error("Unable to create Occlusion Query");return e},oo.prototype.deleteQuery=function(e){return this._gl.deleteQuery(e),this},oo.prototype.isQueryResultAvailable=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT_AVAILABLE)},oo.prototype.getQueryResult=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT)},oo.prototype.beginOcclusionQuery=function(e,t){const i=this._getGlAlgorithmType(e);return this._gl.beginQuery(i,t),!0},oo.prototype.endOcclusionQuery=function(e){const t=this._getGlAlgorithmType(e);return this._gl.endQuery(t),this},oo.prototype._createTimeQuery=function(){const e=this.getCaps().timerQuery;return e.createQueryEXT?e.createQueryEXT():this.createQuery()},oo.prototype._deleteTimeQuery=function(e){const t=this.getCaps().timerQuery;t.deleteQueryEXT?t.deleteQueryEXT(e):this.deleteQuery(e)},oo.prototype._getTimeQueryResult=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT):this.getQueryResult(e)},oo.prototype._getTimeQueryAvailability=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(e)},oo.prototype.startTimeQuery=function(){const e=this.getCaps(),t=e.timerQuery;if(!t)return null;const i=new G_;if(this._gl.getParameter(t.GPU_DISJOINT_EXT),e.canUseTimestampForTimerQuery)i._startTimeQuery=this._createTimeQuery(),i._startTimeQuery&&t.queryCounterEXT(i._startTimeQuery,t.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;i._timeElapsedQuery=this._createTimeQuery(),i._timeElapsedQuery&&(t.beginQueryEXT?t.beginQueryEXT(t.TIME_ELAPSED_EXT,i._timeElapsedQuery):this._gl.beginQuery(t.TIME_ELAPSED_EXT,i._timeElapsedQuery)),this._currentNonTimestampToken=i}return i},oo.prototype.endTimeQuery=function(e){const t=this.getCaps(),i=t.timerQuery;if(!i||!e)return-1;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery)return-1;e._endTimeQuery||(e._endTimeQuery=this._createTimeQuery(),e._endTimeQuery&&i.queryCounterEXT(e._endTimeQuery,i.TIMESTAMP_EXT))}else if(!e._timeElapsedQueryEnded){if(!e._timeElapsedQuery)return-1;i.endQueryEXT?i.endQueryEXT(i.TIME_ELAPSED_EXT):(this._gl.endQuery(i.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),e._timeElapsedQueryEnded=!0}const s=this._gl.getParameter(i.GPU_DISJOINT_EXT);let r=!1;if(e._endTimeQuery?r=this._getTimeQueryAvailability(e._endTimeQuery):e._timeElapsedQuery&&(r=this._getTimeQueryAvailability(e._timeElapsedQuery)),r&&!s){let i=0;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery||!e._endTimeQuery)return-1;const t=this._getTimeQueryResult(e._startTimeQuery);i=this._getTimeQueryResult(e._endTimeQuery)-t,this._deleteTimeQuery(e._startTimeQuery),this._deleteTimeQuery(e._endTimeQuery),e._startTimeQuery=null,e._endTimeQuery=null}else{if(!e._timeElapsedQuery)return-1;i=this._getTimeQueryResult(e._timeElapsedQuery),this._deleteTimeQuery(e._timeElapsedQuery),e._timeElapsedQuery=null,e._timeElapsedQueryEnded=!1}return i}return-1},oo.prototype._captureGPUFrameTime=!1,oo.prototype._gpuFrameTime=new wr,oo.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime},oo.prototype.captureGPUFrameTime=function(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.onBeginFrameObservable.add((()=>{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())})),this._onEndFrameObserver=this.onEndFrameObservable.add((()=>{if(!this._gpuFrameTimeToken)return;const e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))}))):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},oo.prototype._getGlAlgorithmType=function(e){return e===_o.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED};var z_=!0;oo.prototype.createTransformFeedback=function(){const e=this._gl.createTransformFeedback();if(!e)throw new Error("Unable to create Transform Feedback");return e},oo.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},oo.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},oo.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},oo.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},oo.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},oo.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},qs.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;const s=this._getInternalFormat(e.format),r=this._getRGBABufferInternalSizedFormat(0,e.format),n=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);const t=e._workingCanvas.getContext("2d");if(!t)throw new Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},qs.prototype.restoreSingleAttachment=function(){const e=this._gl;this.bindAttachments([e.BACK])},qs.prototype.restoreSingleAttachmentForRenderTarget=function(){const e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},qs.prototype.buildTextureLayout=function(e){const t=this._gl,i=[];for(let s=0;s1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],s.readBuffer(r[t]),s.drawBuffers(r),s.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,s.COLOR_BUFFER_BIT,s.NEAREST)}for(let e=0;e1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];s.drawBuffers(r)}for(let i=0;i1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(a=t.depthTextureFormat)),g.label=t?.label??"MultiRenderTargetWrapper";const v=this._gl,x=v.createFramebuffer();this._bindUnboundFramebuffer(x);const b=e.width||e,T=e.height||e,y=[],S=[],C=this.webGLVersion>1&&o&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),E=this._setupFramebufferDepthAttachments(!C&&n,!o&&r,b,T);g._framebuffer=x,g._depthStencilBuffer=E,g._generateDepthBuffer=!o&&r,g._generateStencilBuffer=!C&&n,g._attachments=S;for(let e=0;e1||this.isWebGPU);const p=this.webGLVersion>1,f=v[p?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(S.push(f),-1===o)continue;const g=new ss(this,is.MultiRenderTarget);y[e]=g,v.activeTexture(v["TEXTURE"+e]),v.bindTexture(o,g._hardwareTexture.underlyingResource),v.texParameteri(o,v.TEXTURE_MAG_FILTER,l.mag),v.texParameteri(o,v.TEXTURE_MIN_FILTER,l.min),v.texParameteri(o,v.TEXTURE_WRAP_S,v.CLAMP_TO_EDGE),v.texParameteri(o,v.TEXTURE_WRAP_T,v.CLAMP_TO_EDGE);const x=this._getRGBABufferInternalSizedFormat(i,n,r),C=this._getInternalFormat(n),E=this._getWebGLTextureType(i);if(!p||35866!==o&&32879!==o)if(34067===o){for(let e=0;e<6;e++)v.texImage2D(v.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,x,b,T,0,C,E,null);g.isCube=!0}else v.texImage2D(v.TEXTURE_2D,0,x,b,T,0,C,E,null);else 35866===o?g.is2DArray=!0:g.is3D=!0,g.baseDepth=g.depth=a,v.texImage3D(o,0,x,b,T,a,0,C,E,null);s&&v.generateMipmap(o),this._bindTextureDirectly(o,null),g.baseWidth=b,g.baseHeight=T,g.width=b,g.height=T,g.isReady=!0,g.samples=1,g.generateMipMaps=s,g.samplingMode=t,g.type=i,g._useSRGBBuffer=r,g.format=n,this._internalTexturesCache.push(g)}if(o&&this._caps.depthTextureExtension){const e=new ss(this,is.Depth);let t=5,i=v.DEPTH_COMPONENT16,r=v.DEPTH_COMPONENT,n=v.UNSIGNED_SHORT,o=v.DEPTH_ATTACHMENT;this.webGLVersion<2?i=v.DEPTH_COMPONENT:14===a?(t=1,n=v.FLOAT,i=v.DEPTH_COMPONENT32F):18===a?(t=0,n=v.FLOAT_32_UNSIGNED_INT_24_8_REV,i=v.DEPTH32F_STENCIL8,r=v.DEPTH_STENCIL,o=v.DEPTH_STENCIL_ATTACHMENT):16===a?(t=0,n=v.UNSIGNED_INT,i=v.DEPTH_COMPONENT24,o=v.DEPTH_ATTACHMENT):13!==a&&17!==a||(t=12,n=v.UNSIGNED_INT_24_8,i=v.DEPTH24_STENCIL8,r=v.DEPTH_STENCIL,o=v.DEPTH_STENCIL_ATTACHMENT),v.activeTexture(v.TEXTURE0),v.bindTexture(v.TEXTURE_2D,e._hardwareTexture.underlyingResource),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_MAG_FILTER,v.NEAREST),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_MIN_FILTER,v.NEAREST),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_WRAP_S,v.CLAMP_TO_EDGE),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_WRAP_T,v.CLAMP_TO_EDGE),v.texImage2D(v.TEXTURE_2D,0,i,b,T,0,r,n,null),v.framebufferTexture2D(v.FRAMEBUFFER,o,v.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=b,e.baseHeight=T,e.width=b,e.height=T,e.isReady=!0,e.samples=1,e.generateMipMaps=s,e.samplingMode=1,e.format=a,e.type=t,y[l]=e,this._internalTexturesCache.push(e)}return g.setTextures(y),i&&v.drawBuffers(S),this._bindUnboundFramebuffer(null),g.setLayerAndFaceIndices(f,p),this.resetTextureCache(),g},qs.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const s=e._attachments.length;if(0===s)return 1;const r=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);const n=!!e._depthStencilBuffer;if(n&&(r.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(r.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof r.renderbufferStorageMultisample){const n=r.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);const o=[];for(let t=0;t1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(s.width,s.height,t,-1,this._getRGBABufferInternalSizedFormat(s.type,s.format,s._useSRGBBuffer),a);if(!l)throw new Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(l),s.samples=t,o.push(a)}i&&r.drawBuffers(o)}else this._bindUnboundFramebuffer(e._framebuffer);return n&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},qs.prototype._createDepthStencilCubeTexture=function(e,t){const i=new ss(this,is.DepthStencil);if(i.isCube=!0,1===this.webGLVersion)return Ne.Error("Depth cube texture is not supported by WebGL 1."),i;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t},r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction);for(let t=0;t<6;t++)s.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH24_STENCIL8,e,e,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH_COMPONENT24,e,e,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(i),i},qs.prototype._setCubeMapTextureParams=function(e,t,i){const s=this._gl;s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,t?s.LINEAR_MIPMAP_LINEAR:s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null)},qs.prototype.createCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,_=!1){const p=this._gl;return this.createCubeTextureBase(e,t,i,!!s,r,n,o,a,l,h,c,u,(e=>this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const i=this.needPOTTextures?Os(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,n=i,a=[p.TEXTURE_CUBE_MAP_POSITIVE_X,p.TEXTURE_CUBE_MAP_POSITIVE_Y,p.TEXTURE_CUBE_MAP_POSITIVE_Z,p.TEXTURE_CUBE_MAP_NEGATIVE_X,p.TEXTURE_CUBE_MAP_NEGATIVE_Y,p.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const l=o?this._getInternalFormat(o,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:p.RGBA;let h=o?this._getInternalFormat(o):p.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(h=l);for(let e=0;e1,e=>e.y,e=>e.z,e=>e.x,e=>e.x*e.y,e=>e.y*e.z,e=>3*e.z*e.z-1,e=>e.x*e.z,e=>e.x*e.x-e.y*e.y],X_=(e,t)=>W_[e]*H_[e](t),Y_=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4];class Q_{constructor(){this.preScaled=!1,this.l00=_e.Zero(),this.l1_1=_e.Zero(),this.l10=_e.Zero(),this.l11=_e.Zero(),this.l2_2=_e.Zero(),this.l2_1=_e.Zero(),this.l20=_e.Zero(),this.l21=_e.Zero(),this.l22=_e.Zero()}addLight(e,t,i){ve.Vector3[0].set(t.r,t.g,t.b);const s=ve.Vector3[0],r=ve.Vector3[1];s.scaleToRef(i,r),r.scaleToRef(X_(0,e),ve.Vector3[2]),this.l00.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(1,e),ve.Vector3[2]),this.l1_1.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(2,e),ve.Vector3[2]),this.l10.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(3,e),ve.Vector3[2]),this.l11.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(4,e),ve.Vector3[2]),this.l2_2.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(5,e),ve.Vector3[2]),this.l2_1.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(6,e),ve.Vector3[2]),this.l20.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(7,e),ve.Vector3[2]),this.l21.addInPlace(ve.Vector3[2]),r.scaleToRef(X_(8,e),ve.Vector3[2]),this.l22.addInPlace(ve.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(Y_[0]),this.l1_1.scaleInPlace(Y_[1]),this.l10.scaleInPlace(Y_[2]),this.l11.scaleInPlace(Y_[3]),this.l2_2.scaleInPlace(Y_[4]),this.l2_1.scaleInPlace(Y_[5]),this.l20.scaleInPlace(Y_[6]),this.l21.scaleInPlace(Y_[7]),this.l22.scaleInPlace(Y_[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(W_[0]),this.l1_1.scaleInPlace(W_[1]),this.l10.scaleInPlace(W_[2]),this.l11.scaleInPlace(W_[3]),this.l2_2.scaleInPlace(W_[4]),this.l2_1.scaleInPlace(W_[5]),this.l20.scaleInPlace(W_[6]),this.l21.scaleInPlace(W_[7]),this.l22.scaleInPlace(W_[8])}updateFromArray(e){return _e.FromArrayToRef(e[0],0,this.l00),_e.FromArrayToRef(e[1],0,this.l1_1),_e.FromArrayToRef(e[2],0,this.l10),_e.FromArrayToRef(e[3],0,this.l11),_e.FromArrayToRef(e[4],0,this.l2_2),_e.FromArrayToRef(e[5],0,this.l2_1),_e.FromArrayToRef(e[6],0,this.l20),_e.FromArrayToRef(e[7],0,this.l21),_e.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return _e.FromFloatsToRef(e[0],e[1],e[2],this.l00),_e.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),_e.FromFloatsToRef(e[6],e[7],e[8],this.l10),_e.FromFloatsToRef(e[9],e[10],e[11],this.l11),_e.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),_e.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),_e.FromFloatsToRef(e[18],e[19],e[20],this.l20),_e.FromFloatsToRef(e[21],e[22],e[23],this.l21),_e.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new Q_).updateFromArray(e)}static FromPolynomial(e){const t=new Q_;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}}class j_{constructor(){this.x=_e.Zero(),this.y=_e.Zero(),this.z=_e.Zero(),this.xx=_e.Zero(),this.yy=_e.Zero(),this.zz=_e.Zero(),this.xy=_e.Zero(),this.yz=_e.Zero(),this.zx=_e.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=Q_.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){ve.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=ve.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),ve.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),ve.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(ve.Vector3[0]).addInPlace(ve.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(ve.Vector3[0]).subtractInPlace(ve.Vector3[1]),this.zz.copyFrom(e.l00),ve.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(ve.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return(new j_).updateFromHarmonics(e)}static FromArray(e){const t=new j_;return _e.FromArrayToRef(e[0],0,t.x),_e.FromArrayToRef(e[1],0,t.y),_e.FromArrayToRef(e[2],0,t.z),_e.FromArrayToRef(e[3],0,t.xx),_e.FromArrayToRef(e[4],0,t.yy),_e.FromArrayToRef(e[5],0,t.zz),_e.FromArrayToRef(e[6],0,t.yz),_e.FromArrayToRef(e[7],0,t.zx),_e.FromArrayToRef(e[8],0,t.xy),t}}class K_{constructor(e,t,i,s){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=s}}class $_{static ConvertCubeMapTextureToSphericalPolynomial(e){if(!e.isCube)return null;e.getScene()?.getEngine().flushFramebuffer();const t=e.getSize().width,i=e.readPixels(0,void 0,void 0,!1),s=e.readPixels(1,void 0,void 0,!1);let r,n;e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),n=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),n=e.readPixels(3,void 0,void 0,!1));const o=e.readPixels(4,void 0,void 0,!1),a=e.readPixels(5,void 0,void 0,!1),l=e.gammaSpace;let h=0;return 1!=e.textureType&&2!=e.textureType||(h=1),new Promise((e=>{Promise.all([s,i,r,n,o,a]).then((([i,s,r,n,o,a])=>{const c={size:t,right:s,left:i,up:r,down:n,front:o,back:a,format:5,type:h,gammaSpace:l};e(this.ConvertCubeMapToSphericalPolynomial(c))}))}))}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new Q_;let i=0;const s=2/e.size,r=s,n=.5*s,o=n-1;for(let a=0;a<6;a++){const l=this._FileFaces[a],h=e[l.name];let c=o;const u=5===e.format?4:3;for(let a=0;ag){const t=g/e;p*=t,f*=t,m*=t}}else p=be.Clamp(p,0,g),f=be.Clamp(f,0,g),m=be.Clamp(m,0,g);const v=new Ee(p,f,m);t.addLight(o,v,_),i+=_,d+=s}c+=r}}const a=4*Math.PI*6/6/i;return t.scaleInPlace(a),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),j_.FromHarmonics(t)}}$_._FileFaces=[new K_("right",new _e(1,0,0),new _e(0,0,-1),new _e(0,-1,0)),new K_("left",new _e(-1,0,0),new _e(0,0,1),new _e(0,-1,0)),new K_("up",new _e(0,1,0),new _e(1,0,0),new _e(0,0,1)),new K_("down",new _e(0,-1,0),new _e(1,0,0),new _e(0,0,-1)),new K_("front",new _e(0,0,1),new _e(1,0,0),new _e(0,-1,0)),new K_("back",new _e(0,0,-1),new _e(-1,0,0),new _e(0,-1,0))],$_.MAX_HDRI_VALUE=4096,$_.PRESERVE_CLAMPED_COLORS=!1;Bi.ShadersStore.lodPixelShader="#extension GL_EXT_shader_texture_lod : enable\nprecision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform sampler2D textureSampler;uniform float lod;uniform vec2 texSize;uniform bool gamma;void main(void)\n{gl_FragColor=textureLod(textureSampler,vUV,lod);if (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";function q_(e,t,i,s=!0){const r=e.getScene(),n=r.getEngine(),o=new ih("resized"+e.name,{width:t,height:i},r,!e.noMipmap,!0,e._texture.type,!1,e.samplingMode,!1);o.wrapU=e.wrapU,o.wrapV=e.wrapV,o.uOffset=e.uOffset,o.vOffset=e.vOffset,o.uScale=e.uScale,o.vScale=e.vScale,o.uAng=e.uAng,o.vAng=e.vAng,o.wAng=e.wAng,o.coordinatesIndex=e.coordinatesIndex,o.level=e.level,o.anisotropicFilteringLevel=e.anisotropicFilteringLevel,o._texture.isReady=!1,e.wrapU=Pa.CLAMP_ADDRESSMODE,e.wrapV=Pa.CLAMP_ADDRESSMODE;const a=new yc("pass",1,null,s?Pa.BILINEAR_SAMPLINGMODE:Pa.NEAREST_SAMPLINGMODE,n,!1,0);return a.externalTextureSamplerBinding=!0,a.getEffect().executeWhenCompiled((()=>{a.onApply=function(t){t.setTexture("textureSampler",e)};const t=o.renderTarget;t&&(r.postProcessManager.directRender([a],t),n.unBindFramebuffer(t),o.disposeFramebufferObjects(),a.dispose(),o.getInternalTexture().isReady=!0)})),o}function Z_(e,t,i,s,r,n,o,a){const l=t.getEngine();return t.isReady=!1,r=r??t.samplingMode,s=s??t.type,n=n??t.format,o=o??t.width,a=a??t.height,-1===s&&(s=0),new Promise((h=>{const c=new Vl("postprocess",e,null,null,1,null,r,l,!1,void 0,s,void 0,null,!1,n);c.externalTextureSamplerBinding=!0;const u=l.createRenderTargetTexture({width:o,height:a},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:r,type:s,format:n});c.getEffect().executeWhenCompiled((()=>{c.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([c],u,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),c&&c.dispose(),u._swapAndDie(t),t.type=s,t.format=5,t.isReady=!0,h(t)}))}))}let J_,ep;function tp(e){J_||(J_=new Float32Array(1),ep=new Int32Array(J_.buffer)),J_[0]=e;const t=ep[0];let i=t>>16&32768,s=t>>12&2047;const r=t>>23&255;return r<103?i:r>142?(i|=31744,i|=(255==r?0:1)&&8388607&t,i):r<113?(s|=2048,i|=(s>>114-r)+(s>>113-r&1),i):(i|=r-112<<10|s>>1,i+=1&s,i)}function ip(e){const t=(32768&e)>>15,i=(31744&e)>>10,s=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(s/Math.pow(2,10)):31==i?s?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+s/Math.pow(2,10))}Bi.ShadersStore.lodCubePixelShader="precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform samplerCube textureSampler;uniform float lod;uniform bool gamma;void main(void)\n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x),lod);\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x),lod);\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x),lod);\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x),lod);\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001),lod);\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001),lod);\n#endif\nif (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";const sp=async(e,t,i,s,r)=>{const n=e.getScene(),o=n.getEngine();let a;if(e.isCube){const e=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];a=new Vl("lodCube","lodCube",["lod","gamma"],null,1,null,Pa.NEAREST_NEAREST_MIPNEAREST,o,!1,e[s])}else a=new Vl("lod","lod",["lod","gamma"],null,1,null,Pa.NEAREST_NEAREST_MIPNEAREST,o);await new Promise((e=>{a.getEffect().executeWhenCompiled((()=>{e(0)}))}));const l=new ih("temp",{width:t,height:i},n,!1);a.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",r),t.setBool("gamma",e.gammaSpace)};const h=e.getInternalTexture();try{if(l.renderTarget&&h){const s=h.samplingMode;0!==r?e.updateSamplingMode(Pa.NEAREST_NEAREST_MIPNEAREST):e.updateSamplingMode(Pa.NEAREST_NEAREST),n.postProcessManager.directRender([a],l.renderTarget,!0),e.updateSamplingMode(s);const c=await o.readPixels(0,0,t,i),u=new Uint8Array(c.buffer,0,c.byteLength);return o.unBindFramebuffer(l.renderTarget),u}throw Error("Render to texture failed.")}finally{l.dispose(),a.dispose()}};async function rp(e,t,i,s=0,r=0){return!e.isReady()&&e._texture&&await new Promise(((t,i)=>{null!==e._texture?e._texture.onLoadedObservable.addOnce((()=>{t(0)})):i(0)})),await sp(e,t,i,s,r)}const np={CreateResizedCopy:q_,ApplyPostProcess:Z_,ToHalfFloat:tp,FromHalfFloat:ip,GetTextureDataAsync:rp},op=131072,ap=131072;function lp(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}const hp=lp("DXT1"),cp=lp("DXT3"),up=lp("DXT5"),dp=lp("DX10");class _p{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35);let s=1;t[2]&op&&(s=Math.max(1,t[7]));const r=t[21],n=r===dp?i[32]:0;let o=0;switch(r){case 113:o=2;break;case 116:o=1;break;case dp:if(10===n){o=2;break}if(2===n){o=1;break}}return{width:t[4],height:t[3],mipmapCount:s,isFourCC:!(4&~t[20]),isRGB:!(64&~t[20]),isLuminance:(t[20]&ap)===ap,isCube:!(512&~t[28]),isCompressed:r===hp||r===cp||r===up,dxgiFormat:n,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,s,r,n){const o=new Float32Array(s),a=new Uint16Array(r,i);let l=0;for(let i=0;i>8)}static _GetRGBArrayBuffer(e,t,i,s,r,n,o,a){const l=new Uint8Array(s),h=new Uint8Array(r,i);let c=0;for(let i=0;i>8&255,C>>16&255,C>>24&255))])}var C;const E=_p._ExtractLongWordOrder(u[23]),A=_p._ExtractLongWordOrder(u[24]),P=_p._ExtractLongWordOrder(u[25]),I=_p._ExtractLongWordOrder(u[26]);S&&(b=e._getRGBABufferInternalSizedFormat(s.textureType)),g=1,u[2]&op&&!1!==r&&(g=Math.max(1,u[7]));const R=a||0,M=e.getCaps();for(let r=R;r0?s.sphericalPolynomial=$_.ConvertCubeMapToSphericalPolynomial({size:u[4],right:h[0],left:h[1],up:h[2],down:h[3],front:h[4],back:h[5],format:5,type:1,gammaSpace:!1}):s.sphericalPolynomial=void 0}}function pp(e){if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some((t=>{const i="\\b"+t+"\\b";return e&&(e===t||e.match(new RegExp(i,"g")))})))return e;const t=e.lastIndexOf("."),i=e.lastIndexOf("?"),s=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+s}_p.StoreLODInAlphaChannel=!1,qs.prototype.createPrefilteredCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(r&&r(null));const n=e.texture;if(l?e.info.sphericalPolynomial&&(n._sphericalPolynomial=e.info.sphericalPolynomial):n._sphericalPolynomial=new j_,n._source=is.CubePrefiltered,this.getCaps().textureLOD)return void(r&&r(n));const o=this._gl,a=e.width;if(!a)return;const h=[];for(let r=0;r<3;r++){const l=1-r/2,c=s,u=be.Log2(a)*i+s,d=c+(u-c)*l,_=Math.round(Math.min(Math.max(d,0),u)),p=new ss(this,is.Temp);if(p.type=n.type,p.format=n.format,p.width=Math.pow(2,Math.max(be.Log2(a)-_,0)),p.height=p.width,p.isCube=!0,p._cachedWrapU=0,p._cachedWrapV=0,this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,p,!0),p.samplingMode=2,o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),e.isDDS){const t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),_p.UploadDDSLevels(this,p,i,t,!0,6,_)}else Ne.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null);const f=new ya(t);f._isCube=!0,f._texture=p,p.isReady=!0,h.push(f)}n._lodTextureHigh=h[2],n._lodTextureMid=h[1],n._lodTextureLow=h[0],r&&r(n)}),n,o,a,l,i,s)},Object.defineProperty(oo.prototype,"texturesSupported",{get:function(){const e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(oo.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),oo.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},oo.prototype.setTextureFormatToUse=function(e){const t=this.texturesSupported;for(let i=0,s=t.length;i{this._flush()}))}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}}fp.DEFAULT_BUFFER_SIZE=65536;Bi.ShadersStore.rgbdDecodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}";class mp{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),s=i.getCaps(),r=t.isReady;let n=!1;s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?(n=!0,t.type=2):s.textureFloatRender&&s.textureFloatLinearFiltering&&(n=!0,t.type=1),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const o=()=>{const s=new Vl("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);s.externalTextureSamplerBinding=!0;const r=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});s.getEffect().executeWhenCompiled((()=>{s.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([s],r,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),s&&s.dispose(),r._swapAndDie(t),t.isReady=!0}))};n&&(r?o():e.onLoadObservable.addOnce(o))}static EncodeTextureToRGBD(e,t,i=0){return Z_("rgbdEncode",e,t,i,1,5)}}ya.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(ya.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=$_.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then((e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))),null}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});Bi.ShadersStore.rgbdEncodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}";const gp="image/png",vp=2,xp=[134,22,135,150,246,214,150,54];function bp(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;for(let e=0;evp)throw new Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "${vp}".`);return 2===e.version?e:e={...e,version:2,imageType:gp}}async function yp(e,t={}){const i=e.getInternalTexture();if(!i)return Promise.reject("The cube texture is invalid.");const s=t.imageType??gp,r=i.getEngine();if(2!==e.textureType&&1!==e.textureType&&0!==e.textureType&&0!==e.textureType&&7!==e.textureType&&-1!==e.textureType)return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");let n=1;if(!r.getCaps().textureFloatRender&&(n=2,!r.getCaps().textureHalfFloatRender))return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");e.sphericalPolynomial;const o=e.getInternalTexture()?._sphericalPolynomialPromise,a=i.width,l=new Hr(r),h={};r.flushFramebuffer();const c=be.ILog2(i.width);for(let i=0;i<=c;i++){const o=Math.pow(2,c-i);for(let a=0;a<6;a++){let c=await e.readPixels(a,i,void 0,!1);if(c&&c.byteLength===c.length){const e=new Float32Array(4*c.byteLength);for(let t=0;t{if(i){const i=t.createTexture(null,!0,!0,null,1,null,(e=>{d(e)}),e);s.getEffect().executeWhenCompiled((()=>{s.externalTextureSamplerBinding=!0,s.onApply=s=>{s._bindTexture("textureSampler",i),s.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([s],h,!0,n,o),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(r),u())}))}else{if(t._uploadImageToTexture(c,e,n,o),a){const i=l[o];i&&t._uploadImageToTexture(i._texture,e,n,0)}u()}}))}function Pp(e,t,i=gp){if(!Ds.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");const s=be.ILog2(e.width)+1,r=e.getEngine();let n=!1,o=!1,a=null,l=null,h=null;const c=r.getCaps();if(e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,r.updateTextureSamplingMode(3,e),c.textureLOD?r._features.supportRenderAndCopyToLodForFloatTextures?c.textureHalfFloatRender&&c.textureHalfFloatLinearFiltering?(n=!0,e.type=2):c.textureFloatRender&&c.textureFloatLinearFiltering&&(n=!0,e.type=1):n=!1:(n=!1,o=!0,h={}),n)a=new Vl("rgbdDecode","rgbdDecode",null,null,1,null,3,r,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,l=r.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:e.type,format:5});else if(e._isRGBD=!0,e.invertY=!0,o){const t=3,i=e._lodGenerationScale,n=e._lodGenerationOffset;for(let o=0;oAp(t,r,n,a,p,c,s,o,h,l,e)));else{const t=new Image;t.src=p,f=new Promise(((i,u)=>{t.onload=()=>{Ap(t,r,n,a,p,c,s,o,h,l,e).then((()=>i())).catch((e=>{u(e)}))},t.onerror=e=>{u(e)}}))}u.push(f)}if(t.length{l&&(r._releaseTexture(e),l._swapAndDie(e)),a&&a.dispose(),o&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))}))}function Ip(e,t){const i=(t=Tp(t)).irradiance;if(!i)return;const s=new j_;_e.FromArrayToRef(i.x,0,s.x),_e.FromArrayToRef(i.y,0,s.y),_e.FromArrayToRef(i.z,0,s.z),_e.FromArrayToRef(i.xx,0,s.xx),_e.FromArrayToRef(i.yy,0,s.yy),_e.FromArrayToRef(i.zz,0,s.zz),_e.FromArrayToRef(i.yz,0,s.yz),_e.FromArrayToRef(i.zx,0,s.zx),_e.FromArrayToRef(i.xy,0,s.xy),e._sphericalPolynomial=s}function Rp(e,t,i,s,r){const n=Pp(e.getEngine().createRawCubeTexture(null,e.width,e.format,e.type,e.generateMipMaps,e.invertY,e.samplingMode,e._compression),t).then((()=>e));return e.onRebuildCallback=e=>({proxy:n,isReady:!0,isAsync:!0}),e._source=is.CubeRawRGBD,e._bufferViewArrayArray=t,e._lodGenerationScale=s,e._lodGenerationOffset=r,e._sphericalPolynomial=i,Pp(e,t).then((()=>(e.isReady=!0,e)))}const Mp={GetEnvInfo:bp,CreateEnvTextureAsync:yp,CreateImageDataArrayBufferViews:Cp,UploadEnvLevelsAsync:Ep,UploadLevelsAsync:Pp,UploadEnvSpherical:Ip};function Op(e,t,i,s){let r=s,n=0,o="";for(;r=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function Np(e){let t=0,i="",s=!1;const r=[];for(;t=0&&e.charAt(t)!==i&&(!s||e.charAt(t)!==s);)t--;return t}function Lp(e,t,i,s){let r=e.indexOf(t);if(r<0)return e;if(i){for(;r++=0&&d.push(t.substring(i+1))}"void"!==r&&d.push("return"),this._functionDescr.push({name:n,type:r,parameters:d,body:c,callIndex:0}),e=h+1;const _=t>0?this._sourceCode.substring(0,t):"",p=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&Ne.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:s,parameters:r,body:n}=t;let o=0;for(;o{const t=[];let i=0,s=0;for(;i0?this._sourceCode.substring(0,a):"";const g=h+1{const a=r[0];return wp(e.charAt(a-1))||wp(e.charAt(a+n))?t[s]:o}))}return e}}Bp._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;const kp=/(flat\s)?\s*varying\s*.*/;class Vp{constructor(){this.shaderLanguage=di.GLSL}initializeShaders(e){this._nativeProcessingContext=e,this._nativeProcessingContext&&(this._nativeProcessingContext.remappedAttributeNames={},this._nativeProcessingContext.injectInVertexMain="")}attributeProcessor(e){if(!this._nativeProcessingContext)return e.replace("attribute","in");const t=/\s*(?:attribute|in)\s+(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==t){const i=t[1],s=t[2],r=this._nativeProcessingContext.vertexBufferKindToNumberOfComponents[s];if(void 0!==r){const n=r<0?-1===r?"int":"ivec"+-r:1===r?"uint":"uvec"+r,o=`_int_${s}_`;e=e.replace(t[0],`in ${n} ${o}; ${i} ${s};`),this._nativeProcessingContext.injectInVertexMain+=`${s} = ${i}(${o});\n`,this._nativeProcessingContext.remappedAttributeNames[s]=o}else e=e.replace(t[0],`in ${i} ${s};`)}return e}varyingCheck(e,t){return kp.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(s||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(this._nativeProcessingContext?.injectInVertexMain&&(e=Lp(e,"void main",this._nativeProcessingContext.injectInVertexMain)),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}class Up{get isReady(){if(this.compilationError){const e=this.compilationError.message;throw new Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}constructor(e,t,i){this.isCompiled=!1,this.vertexBufferKindToType={},this._valueCache={},this._engine=e,this.isAsync=t,this.shaderProcessingContext=i}_fillEffectInformation(e,t,i,s,r,n,o,a){const l=this._engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this._engine.getUniforms(this,i).forEach(((e,t)=>{s[i[t]]=e})),this._uniforms=s,h=0;h{n[e]=t})),a.push(...l.getAttributes(this,o))}setEngine(e){this._engine=e}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this._engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this._engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this._engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this._engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}}class Gp extends Bl{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,s){super(e,t,i,s),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=s}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class zp{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}}function Wp(e,t){switch(e){case 15:return _native.Engine.TEXTURE_FORMAT_D16;case 16:return _native.Engine.TEXTURE_FORMAT_D24;case 13:return _native.Engine.TEXTURE_FORMAT_D24S8;case 14:return _native.Engine.TEXTURE_FORMAT_D32F;case 36492:return _native.Engine.TEXTURE_FORMAT_BC7;case 36494:return _native.Engine.TEXTURE_FORMAT_BC6H;case 33779:return _native.Engine.TEXTURE_FORMAT_BC3;case 33778:return _native.Engine.TEXTURE_FORMAT_BC2;case 33777:case 33776:return _native.Engine.TEXTURE_FORMAT_BC1;case 37808:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case 36196:return _native.Engine.TEXTURE_FORMAT_ETC1;case 37492:return _native.Engine.TEXTURE_FORMAT_ETC2;case 37496:return _native.Engine.TEXTURE_FORMAT_ETC2A;case 4:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGB8;case 3:return _native.Engine.TEXTURE_FORMAT_RGB8S;case 6:return _native.Engine.TEXTURE_FORMAT_RGB8I;case 7:return _native.Engine.TEXTURE_FORMAT_RGB8U}break;case 5:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGBA8;case 1:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case 2:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case 3:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case 4:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case 5:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case 6:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case 7:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break;case 6:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_R8;case 1:return _native.Engine.TEXTURE_FORMAT_R32F;case 2:return _native.Engine.TEXTURE_FORMAT_R16F;case 3:return _native.Engine.TEXTURE_FORMAT_R8S;case 4:return _native.Engine.TEXTURE_FORMAT_R16S;case 5:return _native.Engine.TEXTURE_FORMAT_R16U;case 6:return _native.Engine.TEXTURE_FORMAT_R32I;case 7:return _native.Engine.TEXTURE_FORMAT_R32U}break;case 7:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RG8;case 1:return _native.Engine.TEXTURE_FORMAT_RG32F;case 2:return _native.Engine.TEXTURE_FORMAT_RG16F;case 3:return _native.Engine.TEXTURE_FORMAT_RG8S;case 4:return _native.Engine.TEXTURE_FORMAT_RG16S;case 5:return _native.Engine.TEXTURE_FORMAT_RG16U;case 6:return _native.Engine.TEXTURE_FORMAT_RG32I;case 7:return _native.Engine.TEXTURE_FORMAT_RG32U}break;case 12:if(0===t)return _native.Engine.TEXTURE_FORMAT_BGRA8}throw new jt(`Unsupported texture format or type: format ${e}, type ${t}.`,Qt.UnsupportedTextureError)}function Hp(e){switch(e){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw new Error(`Unsupported sampling mode: ${e}.`)}}function Xp(e){switch(e){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw new Error("Unexpected wrap mode: "+e+".")}}function Yp(e){switch(e){case er.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case er.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case er.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case er.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case er.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${e}.`)}}const Qp={[er.PositionKind]:!0,[er.NormalKind]:!0,[er.TangentKind]:!0,[er.UVKind]:!0,[er.UV2Kind]:!0,[er.UV3Kind]:!0,[er.UV4Kind]:!0,[er.UV5Kind]:!0,[er.UV6Kind]:!0,[er.ColorKind]:!0,[er.ColorInstanceKind]:!0,[er.MatricesIndicesKind]:!0,[er.MatricesWeightsKind]:!0,[er.MatricesIndicesExtraKind]:!0,[er.MatricesWeightsExtraKind]:!0};function jp(e){switch(e){case er.BYTE:case er.SHORT:case er.INT:case er.FLOAT:return!0;case er.UNSIGNED_BYTE:case er.UNSIGNED_SHORT:case er.UNSIGNED_INT:return!1;default:throw new Error(`Invalid type '${e}'`)}}function Kp(e,t){const i=t.getEngine(),s=t._pipelineContext;if(!s?.vertexBufferKindToType)return;let r=null;for(const n in e){const o=e[n];if(!o||!Qp[n])continue;const a=o.normalized?er.FLOAT:o.type,l=s.vertexBufferKindToType[n];(a!==er.FLOAT&&void 0===l||void 0!==l&&l!==a)&&(r||(r=i._getShaderProcessingContext(t.shaderLanguage)),s.vertexBufferKindToType[n]=a,a!==er.FLOAT&&(r.vertexBufferKindToNumberOfComponents[n]=er.DeduceStride(n),jp(a)&&(r.vertexBufferKindToNumberOfComponents[n]*=-1)))}if(r){const e=i._caps.parallelShaderCompile;i._caps.parallelShaderCompile=void 0,t._processShaderCode(null,i._features._checkNonFloatVertexBuffersDontRecreatePipelineContext,r),i._caps.parallelShaderCompile=e}}class $p{constructor(){this.vertexBufferKindToNumberOfComponents={},this.remappedAttributeNames={},this.injectInVertexMain=""}}const qp=new K;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{e=t,e&&qp.notifyObservers(e)}})}function Zp(){return new Promise((e=>{"undefined"==typeof _native?qp.addOnce((t=>e(t))):e(_native)}))}async function Jp(e,t){(await Zp())[e]=t}class ef extends Qs{}class tf{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=rf._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw new Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw new Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}}const sf=[];class rf extends oo{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine({version:oo.Version,nonFloatVertexBuffers:!0}),this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new tf(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==rf.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${rf.PROTOCOL_VERSION} (JS)`);this._engine.setDeviceLostCallback&&this._engine.setDeviceLostCallback((()=>{this.onContextLostObservable.notifyObservers(this),this._contextWasLost=!0,this._restoreEngineAfterContextLost()})),this._webGLVersion=2,this.disableUniformBuffers=!0,this._shaderPlatformName="NATIVE",this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!0,textureFloatLinearFiltering:!0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1,parallelShaderCompile:{COMPLETION_STATUS_KHR:0}},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1},Ds.Log("Babylon Native (v"+oo.Version+") launched"),Ds.LoadScript=function(e,t,i,s){Ds.LoadFile(e,(e=>{Function(e).apply(null),t&&t()}),void 0,void 0,!1,((e,t)=>{i&&i("LoadScript Error",t)}))},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(){const t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,(function(i,s){return Array.isArray(s)?i.push.apply(i,e.call(s,t-1)):i.push(s),i}),[]):Array.prototype.slice.call(this)},writable:!0});const t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();const i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new Vp,this.onNewSceneAddedObservable.add((e=>{const t=e.render;e.render=(...i)=>{this._commandBufferEncoder.beginCommandScope(),t.apply(e,i),this._commandBufferEncoder.endCommandScope()}}))}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new fp}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_restoreEngineAfterContextLost(){this._clearEmptyResources();const e=this._depthCullingState.depthTest,t=this._depthCullingState.depthFunc,i=this._depthCullingState.depthMask,s=this._stencilState.stencilTest;this._rebuildGraphicsResources(),this._depthCullingState.depthTest=e,this._depthCullingState.depthFunc=t,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=s,this._flagContextRestored()}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,s=!1){if(this.useReverseDepthBuffer)throw new Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(s?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){const s=this._normalizeIndexData(e),r=new ef;return r.references=1,r.is32Bits=4===s.BYTES_PER_ELEMENT,s.byteLength&&(r.nativeIndexBuffer=this._engine.createIndexBuffer(s.buffer,s.byteOffset,s.byteLength,r.is32Bits,t??!1)),r}createVertexBuffer(e,t,i){const s=ArrayBuffer.isView(e)?e:new Float32Array(e),r=new ef;return r.references=1,s.byteLength&&(r.nativeVertexBuffer=this._engine.createVertexBuffer(s.buffer,s.byteOffset,s.byteLength,t??!1)),r}_recordVertexArrayObject(e,t,i,s,r){Kp(t,s),i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const n=s.getAttributesNames();for(let i=0;i=0){const s=n[i];let a=null;if(r&&(a=r[s]),a||(a=t[s]),a){const t=a.effectiveBuffer;t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,o,a.effectiveByteOffset,a.effectiveByteStride,a.getSize(),Yp(a.type),a.normalized,a.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,s){const r=this._engine.createVertexArray();return this._recordVertexArrayObject(r,e,t,i,s),r}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){const i=e,s=i.shaderProcessingContext;sf.length=0;for(let e=0;e{e(),t()}}else i.onCompiled=t;else t()}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,s){const r=e;this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=new Bp(t);n.processCode(),t=n.code;const o=new Bp(i);o.processCode(),i=o.code,t=qs._ConcatenateShader(t,s),i=qs._ConcatenateShader(i,s);const a=()=>{r.isCompiled=!0,r.onCompiled?.(),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(e.isAsync)r.program=this._engine.createProgramAsync(t,i,a,(e=>{r.compilationError=e}));else try{r.program=this._engine.createProgram(t,i),a()}catch(e){const t=e?.message;throw new Error("SHADER ERROR"+("string"==typeof t?"\n"+t:""))}return r.program}inlineShaderCode(e){const t=new Bp(e);return t.debug=!1,t.processCode(),t.code}_setProgram(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)}_deletePipelineContext(e){const t=e;t&&t.program&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(t.program),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){const i=e;return this._engine.getUniforms(i.program,t)}bindUniformBlock(e,t,i){throw new Error("Not Implemented")}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t{}}}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()}setDepthWrite(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}setColorWrite(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}getColorWrite(){return this._colorWrite}applyStencil(){this._setStencil(this._stencilMask,function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw new Error(`Unsupported stencil OpFail mode: ${e}.`)}}(this._stencilOpStencilFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw new Error(`Unsupported stencil depthFail mode: ${e}.`)}}(this._stencilOpDepthFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw new Error(`Unsupported stencil opPass mode: ${e}.`)}}(this._stencilOpStencilDepthPass),function(e){switch(e){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw new Error(`Unsupported stencil func mode: ${e}.`)}}(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,s,r,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,s){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=function(e){switch(e){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw new Error(`Unsupported alpha mode: ${e}.`)}}(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(0===e),this._alphaMode=e}setInt(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setArray(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))}setArray2(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))}setArray3(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))}setArray4(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))}setMatrices(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix3x3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix2x2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat2(e,t,i){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat3(e,t,i,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,s,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,s=!1,r){if(void 0===s&&(s=!1),e&&e._hardwareTexture){const i=t.getCanvasTexture(),s=e._hardwareTexture.underlyingResource;this._engine.copyTexture(s,i),e.isReady=!0}}createDynamicTexture(e,t,i,s){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,s)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const s=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(s,t,i)}}createRawTexture(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new ss(this,is.Raw);if(u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u.baseWidth=t,u.baseHeight=i,u.width=u.baseWidth,u.height=u.baseHeight,u._compression=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!r),this.updateRawTexture(u,e,s,n,a,l,u._useSRGBBuffer),u._hardwareTexture){const e=u._hardwareTexture.underlyingResource,t=Hp(o);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(u),u}createRawTexture2DArray(e,t,i,s,r,n,o,a,l=null,h=0){const c=new ss(this,is.Raw2DArray);if(c.baseWidth=t,c.baseHeight=i,c.baseDepth=s,c.width=t,c.height=i,c.depth=s,c.format=r,c.type=h,c.generateMipMaps=n,c.samplingMode=a,c.is2DArray=!0,c._hardwareTexture){const l=c._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,s,Wp(r,h),n,o);const u=Hp(a);this._setTextureSampling(l,u)}return c.isReady=!0,this._internalTexturesCache.push(c),c}updateRawTexture(e,t,i,s,r=null,n=0,o=!1){if(e){if(t&&e._hardwareTexture){const s=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(s,t,e.width,e.height,Wp(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,_,p=!1){const f="data:"===(e=e||"").substr(0,5),m=f&&-1!==e.indexOf(";base64,"),g=l||new ss(this,is.Url),v=e;!this._transformTextureUrl||m||l||a||(e=this._transformTextureUrl(e));const x=e.lastIndexOf("."),b=c||(x>-1?e.substring(x).toLowerCase():"");let T=null;for(const e of ns._TextureLoaders)if(e.canLoad(b)){T=e;break}s&&s.addPendingData(g),g.url=e,g.generateMipMaps=!t,g.samplingMode=r,g.invertY=i,g._useSRGBBuffer=this._getUseSRGBBuffer(p,t),this.doNotHandleContextLost||(g._buffer=a);let y=null;n&&!l&&(y=g.onLoadedObservable.add(n)),l||this._internalTexturesCache.push(g);const S=(i,l)=>{s&&s.removePendingData(g),e===v?(y&&g.onLoadedObservable.remove(y),re.UseFallbackTexture&&this.createTexture(re.FallbackTexture,t,g.invertY,s,r,null,o,a,g),o&&o((i||"Unknown error")+(re.UseFallbackTexture?" - Fallback texture was used":""),l)):(Ne.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,g.invertY,s,r,n,o,a,g,h,c,u,d))};if(T)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const n=e=>{if(!g._hardwareTexture)return void(s&&s.removePendingData(g));const n=g._hardwareTexture.underlyingResource;this._engine.loadTexture(n,e,!t,i,g._useSRGBBuffer,(()=>{g.baseWidth=this._engine.getTextureWidth(n),g.baseHeight=this._engine.getTextureHeight(n),g.width=g.baseWidth,g.height=g.baseHeight,g.isReady=!0;const e=Hp(r);this._setTextureSampling(n,e),s&&s.removePendingData(g),g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()}),(()=>{throw new Error("Could not load a native texture.")}))};if(f&&a)if(a instanceof ArrayBuffer)n(new Uint8Array(a));else if(ArrayBuffer.isView(a))n(a);else{if("string"!=typeof a)throw new Error("Unsupported buffer type");n(new Uint8Array(Ds.DecodeBase64(a)))}else m?n(new Uint8Array(Ds.DecodeBase64(e))):this._loadFile(e,(e=>n(new Uint8Array(e))),void 0,void 0,!0,((e,t)=>{S("Unable to load "+(e&&e.responseURL,t))}))}return g}wrapNativeTexture(e,t=!1,i=3){const s=new zp(e,this._engine),r=new ss(this,is.Unknown,!0);return r._hardwareTexture=s,r.baseWidth=this._engine.getTextureWidth(e),r.baseHeight=this._engine.getTextureHeight(e),r.width=r.baseWidth,r.height=r.baseHeight,r.isReady=!0,r.useMipMaps=t,this.updateTextureSamplingMode(i,r),r}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const s=t.generateStencil||!1,r=t.samples||1,n=i,o=new ss(this,is.DepthStencil),a=e.width??e,l=e.height??e,h=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,a,l,s,!0,r);return n._framebufferDepthStencil=h,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){return new Promise(((t,i)=>{const s=this.createCanvasImage();s.onload=()=>{try{const e=this._engine.createImageBitmap(s);t(e)}catch(e){i(`Error loading image ${s.src} with exception: ${e}`)}},s.onerror=e=>{i(`Error loading image ${s.src} with exception: ${e}`)},s.src=e}))}createImageBitmap(e,t){return new Promise(((t,i)=>{if(Array.isArray(e)){const i=e;if(i.length){const e=this._engine.createImageBitmap(i[0]);if(e)return void t(e)}}i("Unsupported data for createImageBitmap.")}))}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,_=!1){const p=u||new ss(this,is.Cube);p.isCube=!0,p.url=e,p.generateMipMaps=!s,p._lodGenerationScale=h,p._lodGenerationOffset=c,p._useSRGBBuffer=this._getUseSRGBBuffer(_,!!s),this._doNotHandleContextLost||(p._extension=a,p._files=i);const f=e.lastIndexOf(".");if(".env"===(a||(f>-1?e.substring(f).toLowerCase():""))){const t=e=>{const t=bp(e);p.width=t.width,p.height=t.width,Ip(p,t);const i=t.specular;if(!i)throw new Error("Nothing else parsed so far");p._lodGenerationScale=i.lodGenerationScale;const s=Cp(e,t);p.format=5,p.type=0,p.generateMipMaps=!0,p.getEngine().updateTextureSamplingMode(Pa.TRILINEAR_SAMPLINGMODE,p),p._isRGBD=!0,p.invertY=!0,this._engine.loadCubeTextureWithMips(p._hardwareTexture.underlyingResource,s,!1,p._useSRGBBuffer,(()=>{p.isReady=!0,r&&r()}),(()=>{throw new Error("Could not load a native cube texture.")}))};if(i&&6===i.length)throw new Error("Multi-file loading not allowed on env files.");{const i=(e,t)=>{n&&e&&n(e.status+" "+e.statusText,t)};this._loadFile(e,(e=>{t(new Uint8Array(e,0,e.byteLength))}),void 0,void 0,!0,i)}}else{if(!i||6!==i.length)throw new Error("Cannot load cubemap because 6 files were not defined");const e=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(e.map((e=>this._loadFileAsync(e,void 0,!0).then((e=>new Uint8Array(e,0,e.byteLength)))))).then((e=>new Promise(((t,i)=>{this._engine.loadCubeTexture(p._hardwareTexture.underlyingResource,e,!s,!0,p._useSRGBBuffer,t,i)})))).then((()=>{p.isReady=!0,r&&r()}),(e=>{n&&n(`Failed to load cubemap: ${e.message}`,e)}))}return this._internalTexturesCache.push(p),p}_createHardwareTexture(){return new zp(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const s=new Gp(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}_createInternalTexture(e,t,i=!0,s=is.Unknown){let r,n=!1,o=0,a=3,l=5,h=!1,c=1;void 0!==t&&"object"==typeof t?(n=!!t.generateMipMaps,o=void 0===t.type?0:t.type,a=void 0===t.samplingMode?3:t.samplingMode,l=void 0===t.format?5:t.format,h=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,c=t.samples??1,r=t.label):n=!!t,h=this._getUseSRGBBuffer(h,!n),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(a=1),1!==o||this._caps.textureFloat||(o=0,Ne.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=new ss(this,s),d=e.width??e,_=e.height??e,p=e.layers||0;if(0!==p)throw new Error("Texture layers are not supported in Babylon Native");const f=u._hardwareTexture.underlyingResource,m=Wp(l,o);return this._engine.initializeTexture(f,d,_,n,m,!0,h,c),this._setTextureSampling(f,Hp(a)),u._useSRGBBuffer=h,u.baseWidth=d,u.baseHeight=_,u.width=d,u.height=_,u.depth=p,u.isReady=!0,u.samples=c,u.generateMipMaps=n,u.samplingMode=a,u.type=o,u.format=l,u.label=r,this._internalTexturesCache.push(u),u}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e);let s,r=!0,n=!1,o=!1,a=1;void 0!==t&&"object"==typeof t&&(r=t.generateDepthBuffer??!0,n=!!t.generateStencilBuffer,o=!!t.noColorAttachment,s=t.colorAttachment,a=t.samples??1);const l=s||(o?null:this._createInternalTexture(e,t,!0,is.RenderTarget)),h=e.width??e,c=e.height??e,u=this._engine.createFrameBuffer(l?l._hardwareTexture.underlyingResource:null,h,c,n,r,a);return i._framebuffer=u,i._generateDepthBuffer=r,i._generateStencilBuffer=n,i._samples=a,i.setTextures(l),i}updateRenderTargetTextureSampleCount(e,t){return Ne.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=Hp(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,s,r){const n=e;if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||s)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");n._framebufferDepthStencil?this._bindUnboundFramebuffer(n._framebufferDepthStencil):this._bindUnboundFramebuffer(n._framebuffer)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e,!0)}updateDynamicIndexBuffer(e,t,i=0){const s=e,r=this._normalizeIndexData(t);s.is32Bits=4===r.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(s.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i=0,s){const r=e,n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,o=new Uint8Array(n.buffer,n.byteOffset,s??n.byteLength);this._engine.updateDynamicVertexBuffer(r.nativeVertexBuffer,o.buffer,o.byteOffset,o.byteLength,i)}_setTexture(e,t,i=!1,s=!1){const r=this._boundUniforms[e];if(!r)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null,this._unsetNativeTexture(r)),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;return n=s?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!(!n||!n._hardwareTexture||(this._setTextureWrapMode(n._hardwareTexture.underlyingResource,Xp(t.wrapU),Xp(t.wrapV),Xp(t.wrapR)),this._updateAnisotropicLevel(t),this._setNativeTexture(r,n._hardwareTexture.underlyingResource),0))}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,s){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.finishEncodingCommand()}_setNativeTexture(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_unsetNativeTexture(e){_native.Engine.COMMAND_UNSETTEXTURE&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNSETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_updateAnisotropicLevel(e){const t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){const i=this._boundUniforms[e];if(i)if(t&&t._hardwareTexture){const e=t._hardwareTexture.underlyingResource;this._setNativeTexture(i,e)}else this._unsetNativeTexture(i)}unbindAllTextures(){_native.Engine.COMMAND_DISCARDALLTEXTURES&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DISCARDALLTEXTURES),this._commandBufferEncoder.finishEncodingCommand())}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");const i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");return new _native.Image}updateTextureData(e,t,i,s,r,n,o=0,a=0,l=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,s=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}flushFramebuffer(){}_readTexturePixels(e,t,i,s,r,n,o,a,l,h){if(void 0!==s&&-1!==s)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${s}.`);return this._engine.readTexture(e._hardwareTexture?.underlyingResource,r??0,l??0,h??0,t,i,n?.buffer??null,n?.byteOffset??0,n?.byteLength??0).then((e=>(n||(n=new Uint8Array(e)),n)))}}rf.PROTOCOL_VERSION=8,rf._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new nf:new fp};class nf extends fp{constructor(){super()}writeUint32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32),super.writeUint32(e)}writeInt32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32),super.writeInt32(e)}writeFloat32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32),super.writeFloat32(e)}writeUint32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),super.writeUint32Array(e)}writeInt32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY),super.writeInt32Array(e)}writeFloat32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),super.writeFloat32Array(e)}writeNativeData(e){super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA),super.writeNativeData(e)}writeBoolean(e){super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN),super.writeBoolean(e)}}var of,af,lf,hf,cf,uf,df,_f,pf,ff,mf,gf,vf,xf,bf,Tf,yf,Sf,Cf,Ef,Af,Pf,If,Rf,Mf,Of,Df,wf,Nf,Ff,Lf,Bf,kf,Vf,Uf,Gf,zf,Wf,Hf,Xf;!function(e){e.LowPower="low-power",e.HighPerformance="high-performance"}(of||(of={})),function(e){e.DepthClipControl="depth-clip-control",e.Depth32FloatStencil8="depth32float-stencil8",e.TextureCompressionBC="texture-compression-bc",e.TextureCompressionETC2="texture-compression-etc2",e.TextureCompressionASTC="texture-compression-astc",e.TimestampQuery="timestamp-query",e.IndirectFirstInstance="indirect-first-instance",e.ShaderF16="shader-f16",e.RG11B10UFloatRenderable="rg11b10ufloat-renderable",e.BGRA8UnormStorage="bgra8unorm-storage",e.Float32Filterable="float32-filterable"}(af||(af={})),function(e){e.Unmapped="unmapped",e.Pending="pending",e.Mapped="mapped"}(lf||(lf={})),function(e){e[e.MapRead=1]="MapRead",e[e.MapWrite=2]="MapWrite",e[e.CopySrc=4]="CopySrc",e[e.CopyDst=8]="CopyDst",e[e.Index=16]="Index",e[e.Vertex=32]="Vertex",e[e.Uniform=64]="Uniform",e[e.Storage=128]="Storage",e[e.Indirect=256]="Indirect",e[e.QueryResolve=512]="QueryResolve"}(hf||(hf={})),function(e){e[e.Read=1]="Read",e[e.Write=2]="Write"}(cf||(cf={})),function(e){e.E1d="1d",e.E2d="2d",e.E3d="3d"}(uf||(uf={})),function(e){e[e.CopySrc=1]="CopySrc",e[e.CopyDst=2]="CopyDst",e[e.TextureBinding=4]="TextureBinding",e[e.StorageBinding=8]="StorageBinding",e[e.RenderAttachment=16]="RenderAttachment"}(df||(df={})),function(e){e.E1d="1d",e.E2d="2d",e.E2dArray="2d-array",e.Cube="cube",e.CubeArray="cube-array",e.E3d="3d"}(_f||(_f={})),function(e){e.All="all",e.StencilOnly="stencil-only",e.DepthOnly="depth-only"}(pf||(pf={})),function(e){e.R8Unorm="r8unorm",e.R8Snorm="r8snorm",e.R8Uint="r8uint",e.R8Sint="r8sint",e.R16Uint="r16uint",e.R16Sint="r16sint",e.R16Float="r16float",e.RG8Unorm="rg8unorm",e.RG8Snorm="rg8snorm",e.RG8Uint="rg8uint",e.RG8Sint="rg8sint",e.R32Uint="r32uint",e.R32Sint="r32sint",e.R32Float="r32float",e.RG16Uint="rg16uint",e.RG16Sint="rg16sint",e.RG16Float="rg16float",e.RGBA8Unorm="rgba8unorm",e.RGBA8UnormSRGB="rgba8unorm-srgb",e.RGBA8Snorm="rgba8snorm",e.RGBA8Uint="rgba8uint",e.RGBA8Sint="rgba8sint",e.BGRA8Unorm="bgra8unorm",e.BGRA8UnormSRGB="bgra8unorm-srgb",e.RGB9E5UFloat="rgb9e5ufloat",e.RGB10A2UINT="rgb10a2uint",e.RGB10A2Unorm="rgb10a2unorm",e.RG11B10UFloat="rg11b10ufloat",e.RG32Uint="rg32uint",e.RG32Sint="rg32sint",e.RG32Float="rg32float",e.RGBA16Uint="rgba16uint",e.RGBA16Sint="rgba16sint",e.RGBA16Float="rgba16float",e.RGBA32Uint="rgba32uint",e.RGBA32Sint="rgba32sint",e.RGBA32Float="rgba32float",e.Stencil8="stencil8",e.Depth16Unorm="depth16unorm",e.Depth24Plus="depth24plus",e.Depth24PlusStencil8="depth24plus-stencil8",e.Depth32Float="depth32float",e.BC1RGBAUnorm="bc1-rgba-unorm",e.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",e.BC2RGBAUnorm="bc2-rgba-unorm",e.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",e.BC3RGBAUnorm="bc3-rgba-unorm",e.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",e.BC4RUnorm="bc4-r-unorm",e.BC4RSnorm="bc4-r-snorm",e.BC5RGUnorm="bc5-rg-unorm",e.BC5RGSnorm="bc5-rg-snorm",e.BC6HRGBUFloat="bc6h-rgb-ufloat",e.BC6HRGBFloat="bc6h-rgb-float",e.BC7RGBAUnorm="bc7-rgba-unorm",e.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",e.ETC2RGB8Unorm="etc2-rgb8unorm",e.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",e.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",e.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",e.ETC2RGBA8Unorm="etc2-rgba8unorm",e.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",e.EACR11Unorm="eac-r11unorm",e.EACR11Snorm="eac-r11snorm",e.EACRG11Unorm="eac-rg11unorm",e.EACRG11Snorm="eac-rg11snorm",e.ASTC4x4Unorm="astc-4x4-unorm",e.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",e.ASTC5x4Unorm="astc-5x4-unorm",e.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",e.ASTC5x5Unorm="astc-5x5-unorm",e.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",e.ASTC6x5Unorm="astc-6x5-unorm",e.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",e.ASTC6x6Unorm="astc-6x6-unorm",e.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",e.ASTC8x5Unorm="astc-8x5-unorm",e.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",e.ASTC8x6Unorm="astc-8x6-unorm",e.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",e.ASTC8x8Unorm="astc-8x8-unorm",e.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",e.ASTC10x5Unorm="astc-10x5-unorm",e.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",e.ASTC10x6Unorm="astc-10x6-unorm",e.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",e.ASTC10x8Unorm="astc-10x8-unorm",e.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",e.ASTC10x10Unorm="astc-10x10-unorm",e.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",e.ASTC12x10Unorm="astc-12x10-unorm",e.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",e.ASTC12x12Unorm="astc-12x12-unorm",e.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",e.Depth32FloatStencil8="depth32float-stencil8"}(ff||(ff={})),function(e){e.ClampToEdge="clamp-to-edge",e.Repeat="repeat",e.MirrorRepeat="mirror-repeat"}(mf||(mf={})),function(e){e.Nearest="nearest",e.Linear="linear"}(gf||(gf={})),function(e){e.Nearest="nearest",e.Linear="linear"}(vf||(vf={})),function(e){e.Never="never",e.Less="less",e.Equal="equal",e.LessEqual="less-equal",e.Greater="greater",e.NotEqual="not-equal",e.GreaterEqual="greater-equal",e.Always="always"}(xf||(xf={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Compute=4]="Compute"}(bf||(bf={})),function(e){e.Uniform="uniform",e.Storage="storage",e.ReadOnlyStorage="read-only-storage"}(Tf||(Tf={})),function(e){e.Filtering="filtering",e.NonFiltering="non-filtering",e.Comparison="comparison"}(yf||(yf={})),function(e){e.Float="float",e.UnfilterableFloat="unfilterable-float",e.Depth="depth",e.Sint="sint",e.Uint="uint"}(Sf||(Sf={})),function(e){e.WriteOnly="write-only",e.ReadOnly="read-only",e.ReadWrite="read-write"}(Cf||(Cf={})),function(e){e.Error="error",e.Warning="warning",e.Info="info"}(Ef||(Ef={})),function(e){e.Validation="validation",e.Internal="internal"}(Af||(Af={})),function(e){e.Auto="auto"}(Pf||(Pf={})),function(e){e.PointList="point-list",e.LineList="line-list",e.LineStrip="line-strip",e.TriangleList="triangle-list",e.TriangleStrip="triangle-strip"}(If||(If={})),function(e){e.CCW="ccw",e.CW="cw"}(Rf||(Rf={})),function(e){e.None="none",e.Front="front",e.Back="back"}(Mf||(Mf={})),function(e){e[e.Red=1]="Red",e[e.Green=2]="Green",e[e.Blue=4]="Blue",e[e.Alpha=8]="Alpha",e[e.All=15]="All"}(Of||(Of={})),function(e){e.Zero="zero",e.One="one",e.Src="src",e.OneMinusSrc="one-minus-src",e.SrcAlpha="src-alpha",e.OneMinusSrcAlpha="one-minus-src-alpha",e.Dst="dst",e.OneMinusDst="one-minus-dst",e.DstAlpha="dst-alpha",e.OneMinusDstAlpha="one-minus-dst-alpha",e.SrcAlphaSaturated="src-alpha-saturated",e.Constant="constant",e.OneMinusConstant="one-minus-constant"}(Df||(Df={})),function(e){e.Add="add",e.Subtract="subtract",e.ReverseSubtract="reverse-subtract",e.Min="min",e.Max="max"}(wf||(wf={})),function(e){e.Keep="keep",e.Zero="zero",e.Replace="replace",e.Invert="invert",e.IncrementClamp="increment-clamp",e.DecrementClamp="decrement-clamp",e.IncrementWrap="increment-wrap",e.DecrementWrap="decrement-wrap"}(Nf||(Nf={})),function(e){e.Uint16="uint16",e.Uint32="uint32"}(Ff||(Ff={})),function(e){e.Uint8x2="uint8x2",e.Uint8x4="uint8x4",e.Sint8x2="sint8x2",e.Sint8x4="sint8x4",e.Unorm8x2="unorm8x2",e.Unorm8x4="unorm8x4",e.Snorm8x2="snorm8x2",e.Snorm8x4="snorm8x4",e.Uint16x2="uint16x2",e.Uint16x4="uint16x4",e.Sint16x2="sint16x2",e.Sint16x4="sint16x4",e.Unorm16x2="unorm16x2",e.Unorm16x4="unorm16x4",e.Snorm16x2="snorm16x2",e.Snorm16x4="snorm16x4",e.Float16x2="float16x2",e.Float16x4="float16x4",e.Float32="float32",e.Float32x2="float32x2",e.Float32x3="float32x3",e.Float32x4="float32x4",e.Uint32="uint32",e.Uint32x2="uint32x2",e.Uint32x3="uint32x3",e.Uint32x4="uint32x4",e.Sint32="sint32",e.Sint32x2="sint32x2",e.Sint32x3="sint32x3",e.Sint32x4="sint32x4",e.UNORM10x10x10x2="unorm10-10-10-2"}(Lf||(Lf={})),function(e){e.Vertex="vertex",e.Instance="instance"}(Bf||(Bf={})),function(e){e.Beginning="beginning",e.End="end"}(kf||(kf={})),function(e){e.Beginning="beginning",e.End="end"}(Vf||(Vf={})),function(e){e.Load="load",e.Clear="clear"}(Uf||(Uf={})),function(e){e.Store="store",e.Discard="discard"}(Gf||(Gf={})),function(e){e.Occlusion="occlusion",e.Timestamp="timestamp"}(zf||(zf={})),function(e){e.Opaque="opaque",e.Premultiplied="premultiplied"}(Wf||(Wf={})),function(e){e.Unknown="unknown",e.Destroyed="destroyed"}(Hf||(Hf={})),function(e){e.Validation="validation",e.OutOfMemory="out-of-memory",e.Internal="internal"}(Xf||(Xf={}));class Yf{constructor(){this.shaderLanguage=di.GLSL}_addUniformToLeftOverUBO(e,t,i){let s=0;[e,t,s]=this._getArraySize(e,t,i);for(let t=0;t=0&&(u.push(o[c]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=u,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new Zs(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=Yf.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}setEngine(e){this.engine=e}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,s)}setInt4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,s,r)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,s)}setUInt4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,s,r)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,s)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,s,r)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){return this.sources?.vertex}_getFragmentShaderCode(){return this.sources?.fragment}}const jf={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class Kf{static get KnownUBOs(){return Kf._SimplifiedKnownBindings?Kf._SimplifiedKnownUBOs:Kf._KnownUBOs}constructor(e){this.vertexBufferKindToNumberOfComponents={},this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=Kf.KnownUBOs,t=[];for(const i in e){const s=e[i].binding;-1!==s.groupIndex&&(void 0===t[s.groupIndex]?t[s.groupIndex]=s.bindingIndex:t[s.groupIndex]=Math.max(t[s.groupIndex],s.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){const i=this._attributeNextLocation;return this._attributeNextLocation+=(jf[e]??1)*(t||1),i}getVaryingNextLocation(e,t=0){const i=this._varyingNextLocation;return this._varyingNextLocation+=(jf[e]??1)*(t||1),i}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";const t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}Kf._SimplifiedKnownBindings=!0,Kf._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}},Kf._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};class $f extends Yf{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=di.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let s=0;const r=e.indexOf("["),n=e.indexOf("]");if(r>0&&n>0){const t=e.substring(r+1,n);s=+t,isNaN(s)&&(s=+i[t.trim()]),e=e.substr(0,r)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){const i=`// Internals UBO\nuniform ${Yf.InternalsUBOName} {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n`,s=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),s?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),s?e:i+e)}varyingCheck(e,t){return(t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/).test(e)}varyingProcessor(e,t,i){this._preProcessors=i;const s=(t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==s){const r=s[1]??"",n=s[2],o=s[3];let a;t?(a=this._webgpuProcessingContext.availableVaryings[o],this._missingVaryings[a]="",void 0===a&&Ne.Warn(`Invalid fragment shader: The varying named "${o}" is not declared in the vertex shader! This declaration will be ignored.`)):(a=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(o,n,i)[2]),this._webgpuProcessingContext.availableVaryings[o]=a,this._missingVaryings[a]=`layout(location = ${a}) ${r} in ${n} ${o};`),e=e.replace(s[0],void 0===a?"":`layout(location = ${a}) ${r} ${t?"in":"out"} ${n} ${o};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=(this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==i){const s=i[1],r=i[2],n=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(r,s,t)[2]);this._webgpuProcessingContext.availableAttributes[r]=n,this._webgpuProcessingContext.orderedAttributes[n]=r;const o=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[r];if(void 0!==o){const t=o<0?-1===o?"int":"ivec"+-o:1===o?"uint":"uvec"+o,a=`_int_${r}_`;e=e.replace(i[0],`layout(location = ${n}) in ${t} ${a}; ${s} ${r} = ${s}(${a});`)}else e=e.replace(i[0],`layout(location = ${n}) in ${s} ${r};`)}return e}uniformProcessor(e,t,i){this._preProcessors=i;const s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let r=s[1],n=s[2];if(0===r.indexOf("sampler")||1===r.indexOf("sampler")){let s=0;[n,r,s]=this._getArraySize(n,r,i);let o=this._webgpuProcessingContext.availableTextures[n];if(!o){o={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:Sf.Float};for(let e=0;e<(s||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const a=Yf._SamplerTypeByWebGLSamplerType[r]??"sampler",l=!!Yf._IsComparisonSamplerByWebGPUSamplerType[a],h=l?yf.Comparison:yf.Filtering,c=n+"Sampler";let u=this._webgpuProcessingContext.availableSamplers[c];u||(u={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:h});const d="u"===r.charAt(0)?"u":"i"===r.charAt(0)?"i":"";d&&(r=r.substr(1));const _=l?Sf.Depth:"u"===d?Sf.Uint:"i"===d?Sf.Sint:Sf.Float;o.sampleType=_;const p=s>0,f=u.binding.groupIndex,m=u.binding.bindingIndex,g=Yf._SamplerFunctionByWebGLSamplerType[r],v=Yf._TextureTypeByWebGLSamplerType[r],x=Yf._GpuTextureViewDimensionByWebGPUTextureType[v];if(p){const t=[];t.push(`layout(set = ${f}, binding = ${m}) uniform ${d}${a} ${c};`),e="\n";for(let i=0;i0?"\n":""}#define ${n}${i} ${d}${g}(${n}Texture${i}, ${c})`}e=t.join("\n")+e,this._textureArrayProcessing.push(n)}else s=1,e=`layout(set = ${f}, binding = ${m}) uniform ${a} ${c};\n layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${d}${v} ${n}Texture;\n #define ${n} ${d}${g}(${n}Texture, ${c})`;this._webgpuProcessingContext.availableTextures[n]=o,this._webgpuProcessingContext.availableSamplers[c]=u,this._addSamplerBindingDescription(c,u,!t);for(let e=0;e=0,i="\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n ",s=t?"vec4 glFragCoord_;\n":"",r=-1!==e.search(/layout *\(location *= *0\) *out/g);if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){const t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(n||r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",s),t&&(e=Lp(e,"void main",i))}else if(e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex"),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;if(!i){const t=e.lastIndexOf("}");e=e.substring(0,t),e+="gl_Position.y *= yFactor_;\n",e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let s=i.exec(e);for(;null!==s;){const r=s[1];let n=+r;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[r.trim()]),e=e.replace(s[0],t+n),s=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} {\n `;for(const e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}];\n`:i+=` ${e.type} ${e.name};\n`;return i+="};\n\n",i}finalizeShaders(e,t){for(let i=0;i0&&(t=i+"\n"+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}Bi.IncludesShadersStoreWGSL.bonesDeclaration="#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4;attribute matricesWeights : vec4;\n#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d;uniform boneTextureWidth : f32;\n#else\nuniform mBones : array;\n#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array;\n#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\n{let offset=i32(index) *4; \nlet m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);}\n#endif\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.bonesVertex="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\n#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\n#endif \n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4\n{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);}\n#endif\n";Bi.IncludesShadersStoreWGSL.bakedVertexAnimation="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\n#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\n#endif\nlet totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;}\n#endif\n";Bi.IncludesShadersStoreWGSL.clipPlaneFragment="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fragmentInputs.fClipDistance>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\n{discard;}\n#endif\n";Bi.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration="#ifdef CLIPPLANE\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nvarying fClipDistance6: f32;\n#endif\n";Bi.IncludesShadersStoreWGSL.clipPlaneVertex="#ifdef CLIPPLANE\nvertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nvertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nvertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nvertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nvertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nvertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);\n#endif\n";Bi.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration="#ifdef CLIPPLANE\nuniform vClipPlane: vec4;varying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4;varying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4;varying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4;varying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4;varying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4;varying fClipDistance6: f32;\n#endif\n";Bi.IncludesShadersStoreWGSL.instancesDeclaration="#ifdef INSTANCES\nattribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4;\n#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4;\n#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform previousWorld : mat4x4;\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.instancesVertex="#ifdef INSTANCES\nvar finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\n#if !defined(WORLD_UBO)\nfinalWorld=uniforms.world*finalWorld;\n#else\nfinalWorld=mesh.world*finalWorld;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nvar finalWorld=uniforms.world;\n#else\nvar finalWorld=mesh.world;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=previousWorld;\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.helperFunctions="const PI: f32=3.1415926535897932384626433832795;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const HALF_MIN: f32=5.96046448e-08; \nconst LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3=vec3 (0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\nfn transposeMat3(inMatrix: mat3x3f)->mat3x3f {let i0: vec3=inMatrix[0];let i1: vec3=inMatrix[1];let i2: vec3=inMatrix[2];let outMatrix:mat3x3f=mat3x3f(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nfn inverseMat3(inMatrix: mat3x3f)->mat3x3f {let a00: f32=inMatrix[0][0];let a01: f32=inMatrix[0][1];let a02: f32=inMatrix[0][2];let a10: f32=inMatrix[1][0];let a11: f32=inMatrix[1][1];let a12: f32=inMatrix[1][2];let a20: f32=inMatrix[2][0];let a21: f32=inMatrix[2][1];let a22: f32=inMatrix[2][2];let b01: f32=a22*a11-a12*a21;let b11: f32=-a22*a10+a12*a20;let b21: f32=a21*a10-a11*a20;let det: f32=a00*b01+a01*b11+a02*b21;return mat3x3f(b01/det,(-a22*a01+a02*a21)/det,(a12*a01-a02*a11)/det,\nb11/det,(a22*a00-a02*a20)/det,(-a12*a00+a02*a10)/det,\nb21/det,(-a21*a00+a01*a20)/det,(a11*a00-a01*a10)/det);}\n#if USE_EXACT_SRGB_CONVERSIONS\nfn toLinearSpaceExact(color: vec3)->vec3\n{let nearZeroSection: vec3=0.0773993808*color;let remainingSection: vec3=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));}\nfn toGammaSpaceExact(color: vec3)->vec3\n{let nearZeroSection: vec3=12.92*color;let remainingSection: vec3=1.055*pow(color,vec3(0.41666))-vec3(0.055);return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));}\n#endif\nfn toLinearSpace(color: vec4)->vec4\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfn toLinearSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nfn toGammaSpace(color: vec4)->vec4\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfn toGammaSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nfn square(value: vec3)->vec3\n{return value*value;}\nfn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;}\nfn getLuminance(color: vec3)->f32\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfn getRand(seed: vec2)->f32 {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfn dither(seed: vec2,varianceAmount: f32)->f32 {let rand: f32=getRand(seed);let normVariance: f32=varianceAmount/255.0;let dither: f32=mix(-normVariance,normVariance,rand);return dither;}\nconst rgbdMaxRange: f32=255.0;fn toRGBD(color: vec3)->vec4 {let maxRGB: f32=max(max(color.r,max(color.g,color.b)),Epsilon);var D: f32 =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);var rgb: vec3 =color.rgb*D;rgb=toGammaSpaceVec3(rgb);return vec4(clamp(rgb,vec3(0.,0.,0.),vec3(1.,1.,1.)),D); }\nfn fromRGBD(rgbd: vec4)->vec3 {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;}\nfn parallaxCorrectNormal(vertexPos: vec3,origVec: vec3,cubeSize: vec3,cubePos: vec3)->vec3 {let invOrigVec: vec3=vec3(1.0,1.0,1.0)/origVec;let halfSize: vec3=cubeSize*0.5;let intersecAtMaxPlane: vec3=(cubePos+halfSize-vertexPos)*invOrigVec;let intersecAtMinPlane: vec3=(cubePos-halfSize-vertexPos)*invOrigVec;let largestIntersec: vec3=max(intersecAtMaxPlane,intersecAtMinPlane);let distance: f32=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);let intersectPositionWS: vec3=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";Bi.IncludesShadersStoreWGSL.fresnelFunction="#ifdef FRESNEL\nfn computeFresnelTerm(viewDirection: vec3f,worldNormal: vec3f,bias: f32,power: f32)->f32\n{let fresnelTerm: f32=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}\n#endif\n";Bi.IncludesShadersStoreWGSL.meshUboDeclaration="struct Mesh {world : mat4x4,\nvisibility : f32,};var mesh : Mesh;\n#define WORLD_UBO\n";Bi.IncludesShadersStoreWGSL.morphTargetsVertex="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (var i=0; i=uniforms.morphTargetCount) {break;}\nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n}\n#endif\n#else\npositionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3;\n#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2;\n#endif\n#elif {X}==0\nuniform morphTargetCount: i32;\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.morphTargetsVertexGlobal="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration="#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array;\n#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3\n{ \nlet y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;}\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.sceneUboDeclaration="struct Scene {viewProjection : mat4x4,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4,\n#endif \nview : mat4x4,\nprojection : mat4x4,\nvEyePosition : vec4,};var scene : Scene;\n";Bi.IncludesShadersStoreWGSL.lightsFragmentFunctions="struct lightingInfo\n{diffuse: vec3f,\n#ifdef SPECULARTERM\nspecular: vec3f,\n#endif\n#ifdef NDOTL\nndl: f32,\n#endif\n};fn computeLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var lightVectorW: vec3f;var attenuation: f32=1.0;if (lightData.w==0.)\n{var direction: vec3f=lightData.xyz-vPositionW;var attenuation: f32=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nvar ndl: f32=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nfn computeSpotLighting(viewDirectionW: vec3f,vNormal: vec3f ,lightData: vec4f,lightDirection: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var direction: vec3f=lightData.xyz-vPositionW;var lightVectorW: vec3f=normalize(direction);var attenuation: f32=max(0.,1.0-length(direction)/range);var cosAngle: f32=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;var ndl: f32=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3f(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3f(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nfn computeHemisphericLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,groundColor: vec3f,glossiness: f32)->lightingInfo {var result: lightingInfo;var ndl: f32=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightData.xyz);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\nfn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f)->vec3f {var strq: vec4f=textureProjectionMatrix*vec4f(vPositionW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return textureColor;}";Bi.IncludesShadersStoreWGSL.lightFragment="#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(POINTLIGHT{X})\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(HEMILIGHT{X})\npreInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(DIRLIGHT{X})\npreInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#endif\npreInfo.NdotV=NdotV;\n#ifdef SPOTLIGHT{X}\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\n#elif defined(POINTLIGHT{X})\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\n#else\npreInfo.attenuation=1.0;\n#endif\n#ifdef HEMILIGHT{X}\npreInfo.roughness=roughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#ifdef IRIDESCENCE\npreInfo.iridescenceIntensity=iridescenceIntensity;\n#endif\n#ifdef HEMILIGHT{X}\ninfo.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround);\n#elif defined(SS_TRANSLUCENCY)\ninfo.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance);\n#else\ninfo.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef SPECULARTERM\n#ifdef ANISOTROPIC\ninfo.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#else\ninfo.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#endif\n#ifdef SHEEN\n#ifdef SHEEN_LINKWITHALBEDO\npreInfo.roughness=sheenOut.sheenIntensity;\n#else\n#ifdef HEMILIGHT{X}\npreInfo.roughness=sheenOut.sheenRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#endif\ninfo.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef CLEARCOAT\n#ifdef HEMILIGHT{X}\npreInfo.roughness=clearcoatOut.clearCoatRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\ninfo.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb);\n#ifdef CLEARCOAT_TINT\nabsorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;\n#ifdef SPECULARTERM\ninfo.specular*=absorption;\n#endif\n#endif\ninfo.diffuse*=info.clearCoat.w;\n#ifdef SPECULARTERM\ninfo.specular*=info.clearCoat.w;\n#endif\n#ifdef SHEEN\ninfo.sheen*=info.clearCoat.w;\n#endif\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},projectionLightTexture{X}Sampler,textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSMDEBUG{X} \nvar shadowDebug{X}: vec3f;\n#endif\n#ifdef SHADOWCSM{X}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nvar index{X}: i32=-1;\n#else\nvar index{X}: i32=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nvar diff{X}: f32=0.;vPositionFromLight{X}[0]=fragmentInputs.vPositionFromLight{X}_0;vPositionFromLight{X}[1]=fragmentInputs.vPositionFromLight{X}_1;vPositionFromLight{X}[2]=fragmentInputs.vPositionFromLight{X}_2;vPositionFromLight{X}[3]=fragmentInputs.vPositionFromLight{X}_3;vDepthMetric{X}[0]=fragmentInputs.vDepthMetric{X}_0;vDepthMetric{X}[1]=fragmentInputs.vDepthMetric{X}_1;vDepthMetric{X}[2]=fragmentInputs.vDepthMetric{X}_2;vDepthMetric{X}[3]=fragmentInputs.vDepthMetric{X}_3;for (var i:i32=0; i=0.) {index{X}=i;break;}}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nif (index{X}>=0)\n#endif\n{\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#else\nshadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#endif\n#else\nshadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=vec3f(shadow)*vCascadeColorsMultiplier{X}[index{X}];\n#endif\n#ifndef SHADOWCSMNOBLEND{X}\nvar frustumLength:f32=uniforms.frustumLengths{X}[index{X}];var diffRatio:f32=clamp(diff{X}/frustumLength,0.,1.)*uniforms.cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)\n{index{X}+=1;var nextShadow: f32=0.;\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nnextShadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#else\nnextShadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#endif\n#else\nnextShadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\nshadow=mix(nextShadow,shadow,diffRatio);\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);\n#endif\n}\n#endif\n}\n#elif defined(SHADOWCLOSEESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;shadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\naggShadow+=shadow;numLights+=1.0;\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor.rgb*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifndef LIGHTMAPNOSPECULAR{X}\nclearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef SHEEN\n#ifndef LIGHTMAPNOSPECULAR{X}\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#else\n#ifdef SHADOWCSMDEBUG{X}\ndiffuseBase+=info.diffuse*shadowDebug{X};\n#else \ndiffuseBase+=info.diffuse*shadow;\n#endif\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#ifdef CLEARCOAT\nclearCoatBase+=info.clearCoat.rgb*shadow;\n#endif\n#ifdef SHEEN\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.lightUboDeclaration="#ifdef LIGHT{X}\nstruct Light{X}\n{vLightData: vec4f,\nvLightDiffuse: vec4f,\nvLightSpecular: vec4f,\n#ifdef SPOTLIGHT{X}\nvLightDirection: vec4f,\nvLightFalloff: vec4f,\n#elif defined(POINTLIGHT{X})\nvLightFalloff: vec4f,\n#elif defined(HEMILIGHT{X})\nvLightGround: vec3f,\n#endif\nshadowsInfo: vec4f,\ndepthValues: vec2f} ;var light{X} : Light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform textureProjectionMatrix{X}: mat4x4f;var projectionLightTexture{X}sampler: sampler;var projectionLightTexture{X}: texture_2d;\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array;uniform viewFrustumZ{X}: array;uniform frustumLengths{X}: array;uniform cascadeBlendFactor{X}: f32;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;var vPositionFromLight{X}: array;var vDepthMetric{X} : array;\n#if defined(SHADOWPCSS{X})\nvar shadowTexture{X}Sampler: sampler_comparison; \nvar shadowTexture{X}: texture_depth_2d_array;var depthTexture{X}Sampler: sampler;var depthTexture{X}: texture_2d_array;uniform lightSizeUVCorrection{X}: array;uniform depthCorrection{X}: array;uniform penumbraDarkness{X}: f32;\n#elif defined(SHADOWPCF{X})\nvar shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d_array;\n#else \nvar shadowTexture{X}Sampler: sampler; \nvar shadowTexture{X}: texture_2d_array;\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vCascadeColorsMultiplier{X}: array=array\n(\nvec3f ( 1.5,0.0,0.0 ),\nvec3f ( 0.0,1.5,0.0 ),\nvec3f ( 0.0,0.0,5.5 ),\nvec3f ( 1.5,0.0,5.5 ),\nvec3f ( 1.5,1.5,0.0 ),\nvec3f ( 1.0,1.0,1.0 ),\nvec3f ( 0.0,1.0,5.5 ),\nvec3f ( 0.5,3.5,0.75 )\n);\n#endif\n#elif defined(SHADOWCUBE{X})\nvar shadowTexture{X}Sampler: sampler;var shadowTexture{X}: texture_cube;\n#else\nvarying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;\n#if defined(SHADOWPCSS{X})\nvar shadowTexture{X}Sampler: sampler_comparison; \nvar shadowTexture{X}: texture_depth_2d;var depthTexture{X}Sampler: sampler; \nvar depthTexture{X}: texture_2d;\n#elif defined(SHADOWPCF{X})\nvar shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d;\n#else\nvar shadowTexture{X}Sampler: sampler; \nvar shadowTexture{X}: texture_2d;\n#endif\nuniform lightMatrix{X}: mat4x4f;\n#endif\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.lightVxUboDeclaration="#ifdef LIGHT{X}\nstruct Light{X}\n{vLightData: vec4f,\nvLightDiffuse: vec4f,\nvLightSpecular: vec4f,\n#ifdef SPOTLIGHT{X}\nvLightDirection: vec4f,\nvLightFalloff: vec4f,\n#elif defined(POINTLIGHT{X})\nvLightFalloff: vec4f,\n#elif defined(HEMILIGHT{X})\nvLightGround: vec3f,\n#endif\nshadowsInfo: vec4f,\ndepthValues: vec2f} ;var light{X} : Light{X};\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f;\n#endif\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.shadowsFragmentFunctions="#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfn unpack(color: vec4f)->f32\n{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}\n#endif\nfn computeFallOff(value: f32,clipSpace: vec2f,frustumEdgeFalloff: f32)->f32\n{var mask: f32=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\nfn computeShadowCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadow: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nreturn select(darkness,1.0,depth>shadow);}\nfn computeShadowWithPoissonSamplingCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,mapSize: f32,darkness: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec3f(-1.0,1.0,-1.0);poissonDisk[1]= vec3f(1.0,-1.0,-1.0);poissonDisk[2]= vec3f(-1.0,-1.0,-1.0);poissonDisk[3]= vec3f(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[0]*mapSize)),shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nvar esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;}\nfn computeShadowWithCloseESMCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nvar esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;}\nfn computeShadowCSM(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d_array,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,uv,layer));\n#else\nvar shadow: f32=textureSample(shadowTexture,shadowSampler,uv,layer).x;\n#endif\nreturn select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}\nfn computeShadow(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadow: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nreturn select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}}\nfn computeShadowWithPoissonSampling(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,mapSize: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec2f(-0.94201624,-0.39906216);poissonDisk[1]= vec2f(0.94558609,-0.76890725);poissonDisk[2]= vec2f(-0.094184101,-0.92938870);poissonDisk[3]= vec2f(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[0]*mapSize,0.)),shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nvar esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithCloseESM(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nvar esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\nfn getZInClip(clipSpace: vec3f,uvDepth: vec3f)->f32\n{\n#ifdef IS_NDC_HALF_ZRANGE\nreturn clipSpace.z;\n#else\nreturn uvDepth.z;\n#endif\n}\nconst GREATEST_LESS_THAN_ONE: f32=0.99999994;\n#define DIAGNOSTIC_OFF\nfn computeShadowWithCSMPCF1(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var shadow: f32=textureSampleCompare(shadowTexture,shadowSampler,uvDepth.xy,layer,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithCSMPCF3(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithCSMPCF5(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),layer,uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),layer,uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),layer,uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),layer,uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithPCF1(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var shadow: f32=textureSampleCompareLevel(shadowTexture,shadowSampler,uvDepth.xy,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithPCF3(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithPCF5(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nconst PoissonSamplers32: array=array (\nvec3f(0.06407013,0.05409927,0.),\nvec3f(0.7366577,0.5789394,0.),\nvec3f(-0.6270542,-0.5320278,0.),\nvec3f(-0.4096107,0.8411095,0.),\nvec3f(0.6849564,-0.4990818,0.),\nvec3f(-0.874181,-0.04579735,0.),\nvec3f(0.9989998,0.0009880066,0.),\nvec3f(-0.004920578,-0.9151649,0.),\nvec3f(0.1805763,0.9747483,0.),\nvec3f(-0.2138451,0.2635818,0.),\nvec3f(0.109845,0.3884785,0.),\nvec3f(0.06876755,-0.3581074,0.),\nvec3f(0.374073,-0.7661266,0.),\nvec3f(0.3079132,-0.1216763,0.),\nvec3f(-0.3794335,-0.8271583,0.),\nvec3f(-0.203878,-0.07715034,0.),\nvec3f(0.5912697,0.1469799,0.),\nvec3f(-0.88069,0.3031784,0.),\nvec3f(0.5040108,0.8283722,0.),\nvec3f(-0.5844124,0.5494877,0.),\nvec3f(0.6017799,-0.1726654,0.),\nvec3f(-0.5554981,0.1559997,0.),\nvec3f(-0.3016369,-0.3900928,0.),\nvec3f(-0.5550632,-0.1723762,0.),\nvec3f(0.925029,0.2995041,0.),\nvec3f(-0.2473137,0.5538505,0.),\nvec3f(0.9183037,-0.2862392,0.),\nvec3f(0.2469421,0.6718712,0.),\nvec3f(0.3916397,-0.4328209,0.),\nvec3f(-0.03576927,-0.6220032,0.),\nvec3f(-0.04661255,0.7995201,0.),\nvec3f(0.4402924,0.3640312,0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.)\n);const PoissonSamplers64: array=array (\nvec3f(-0.613392,0.617481,0.),\nvec3f(0.170019,-0.040254,0.),\nvec3f(-0.299417,0.791925,0.),\nvec3f(0.645680,0.493210,0.),\nvec3f(-0.651784,0.717887,0.),\nvec3f(0.421003,0.027070,0.),\nvec3f(-0.817194,-0.271096,0.),\nvec3f(-0.705374,-0.668203,0.),\nvec3f(0.977050,-0.108615,0.),\nvec3f(0.063326,0.142369,0.),\nvec3f(0.203528,0.214331,0.),\nvec3f(-0.667531,0.326090,0.),\nvec3f(-0.098422,-0.295755,0.),\nvec3f(-0.885922,0.215369,0.),\nvec3f(0.566637,0.605213,0.),\nvec3f(0.039766,-0.396100,0.),\nvec3f(0.751946,0.453352,0.),\nvec3f(0.078707,-0.715323,0.),\nvec3f(-0.075838,-0.529344,0.),\nvec3f(0.724479,-0.580798,0.),\nvec3f(0.222999,-0.215125,0.),\nvec3f(-0.467574,-0.405438,0.),\nvec3f(-0.248268,-0.814753,0.),\nvec3f(0.354411,-0.887570,0.),\nvec3f(0.175817,0.382366,0.),\nvec3f(0.487472,-0.063082,0.),\nvec3f(-0.084078,0.898312,0.),\nvec3f(0.488876,-0.783441,0.),\nvec3f(0.470016,0.217933,0.),\nvec3f(-0.696890,-0.549791,0.),\nvec3f(-0.149693,0.605762,0.),\nvec3f(0.034211,0.979980,0.),\nvec3f(0.503098,-0.308878,0.),\nvec3f(-0.016205,-0.872921,0.),\nvec3f(0.385784,-0.393902,0.),\nvec3f(-0.146886,-0.859249,0.),\nvec3f(0.643361,0.164098,0.),\nvec3f(0.634388,-0.049471,0.),\nvec3f(-0.688894,0.007843,0.),\nvec3f(0.464034,-0.188818,0.),\nvec3f(-0.440840,0.137486,0.),\nvec3f(0.364483,0.511704,0.),\nvec3f(0.034028,0.325968,0.),\nvec3f(0.099094,-0.308023,0.),\nvec3f(0.693960,-0.366253,0.),\nvec3f(0.678884,-0.204688,0.),\nvec3f(0.001801,0.780328,0.),\nvec3f(0.145177,-0.898984,0.),\nvec3f(0.062655,-0.611866,0.),\nvec3f(0.315226,-0.604297,0.),\nvec3f(-0.780145,0.486251,0.),\nvec3f(-0.371868,0.882138,0.),\nvec3f(0.200476,0.494430,0.),\nvec3f(-0.494552,-0.711051,0.),\nvec3f(0.612476,0.705252,0.),\nvec3f(-0.578845,-0.768792,0.),\nvec3f(-0.772454,-0.090976,0.),\nvec3f(0.504440,0.372295,0.),\nvec3f(0.155736,0.065157,0.),\nvec3f(0.391522,0.849605,0.),\nvec3f(-0.620106,-0.328104,0.),\nvec3f(0.789239,-0.419965,0.),\nvec3f(-0.545396,0.538133,0.),\nvec3f(-0.178564,-0.596057,0.)\n);fn computeShadowWithCSMPCSS(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uvDepthLayer: vec4f= vec4f(uvDepth.x,uvDepth.y,f32(layer),uvDepth.z);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;var exitCondition: bool=depthMetric>1.0 || depthMetric<0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);}\nfn computeShadowWithPCSS32(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);}\nfn computeShadowWithPCSS64(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);}\nfn computeShadowWithCSMPCSS16(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\nfn computeShadowWithCSMPCSS32(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\nfn computeShadowWithCSMPCSS64(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#endif\n";Bi.IncludesShadersStoreWGSL.shadowsVertex="#ifdef SHADOWS\n#if defined(SHADOWCSM{X})\nvertexOutputs.vPositionFromCamera{X}=view*worldPos;\n#if SHADOWCSMNUM_CASCADES{X}>0\nvertexOutputs.vPositionFromLight{X}_0=uniforms.lightMatrix{X}[0]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_0=(-vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_0= (vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#if SHADOWCSMNUM_CASCADES{X}>1\nvertexOutputs.vPositionFromLight{X}_1=uniforms.lightMatrix{X}[1]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_1=(-vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_1= (vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#if SHADOWCSMNUM_CASCADES{X}>2\nvertexOutputs.vPositionFromLight{X}_2=uniforms.lightMatrix{X}[2]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_2=(-vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_2= (vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#if SHADOWCSMNUM_CASCADES{X}>3\nvertexOutputs.vPositionFromLight{X}_3=uniforms.lightMatrix{X}[3]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_3=(-vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_3= (vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvertexOutputs.vPositionFromLight{X}=uniforms.lightMatrix{X}*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}=(-vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}=(vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#endif\n";Bi.IncludesShadersStoreWGSL.fogFragmentDeclaration="#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vFogInfos: vec4f;uniform vFogColor: vec3f;varying vFogDistance: vec3f;fn CalcFogFactor()->f32\n{var fogCoeff: f32=1.0;var fogStart: f32=uniforms.vFogInfos.y;var fogEnd: f32=uniforms.vFogInfos.z;var fogDensity: f32=uniforms.vFogInfos.w;var fogDistance: f32=length(fragmentInputs.vFogDistance);if (FOGMODE_LINEAR==uniforms.vFogInfos.x)\n{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);}\nelse if (FOGMODE_EXP==uniforms.vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDensity);}\nelse if (FOGMODE_EXP2==uniforms.vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);}\nreturn clamp(fogCoeff,0.0,1.0);}\n#endif\n";Bi.IncludesShadersStoreWGSL.bumpFragment="var uvOffset: vec2f= vec2f(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)\n#ifdef NORMALXYSCALE\nvar normalScale: f32=1.0;\n#elif defined(BUMP)\nvar normalScale: f32=vBumpInfos.y;\n#else\nvar normalScale: f32=1.0;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nvar TBN: mat3x3f=vTBN;\n#elif defined(BUMP)\nvar TBNUV: vec2f=select(-vBumpUV,vBumpUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);\n#else\nvar TBNUV: vec2f=select(-vDetailUV,vDetailUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,vPositionW,TBNUV, vec2f(1.,1.));\n#endif\n#elif defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvar TBN: mat3x3f=vTBN;\n#else\nvar TBNUV: vec2f=select( -vMainUV1,vMainUV1,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW,vPositionW,TBNUV, vec2f(1.,1.));\n#endif\n#endif\n#ifdef PARALLAX\nvar invTBN: mat3x3f=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef DETAIL\nvar detailColor: vec4f=textureSample(detail,detailSampler,vDetailUV+uvOffset);var detailNormalRG: vec2f=detailColor.wy*2.0-1.0;var detailNormalB: f32=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));var detailNormal: vec3f= vec3f(detailNormalRG,detailNormalB);\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\n#define CUSTOM_FRAGMENT_BUMP_FRAGMENT\nnormalW=normalize(textureSample(bump,bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize( mat3x3f(normalMatrix)*normalW);\n#elif !defined(DETAIL)\nnormalW=perturbNormal(TBN,textureSample(bump,bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);\n#else\nvar bumpNormal: vec3f=textureSample(bump,bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;\n#if DETAIL_NORMALBLENDMETHOD==0 \ndetailNormal.xy*=vDetailInfos.z;var blendedNormal: vec3f=normalize( vec3f(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));\n#elif DETAIL_NORMALBLENDMETHOD==1 \ndetailNormal.xy*=vDetailInfos.z;bumpNormal+= vec3f(0.0,0.0,1.0);detailNormal*= vec3f(-1.0,-1.0,1.0);var blendedNormal: vec3f=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;\n#endif\nnormalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);\n#endif\n#elif defined(DETAIL)\ndetailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);\n#endif\n";Bi.IncludesShadersStoreWGSL.bumpFragmentMainFunctions="#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)\n#if defined(TANGENT) && defined(NORMAL) \nvarying vTBN: mat3x3f;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform normalMatrix: mat4x4f;\n#if defined(WEBGL2) || defined(WEBGPU)\nfn toNormalMatrix(wMatrix: mat4x4f)->mat4x4f\n{var ret: mat4x4f=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]= vec4f(0.,0.,0.,1.);return ret;}\n#else\nfn toNormalMatrix(m: mat4x4f)->mat4x4f\n{var a00: f32=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3],\na10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3],\na20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3],\na30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3],\nb00=a00*a11-a01*a10,\nb01=a00*a12-a02*a10,\nb02=a00*a13-a03*a10,\nb03=a01*a12-a02*a11,\nb04=a01*a13-a03*a11,\nb05=a02*a13-a03*a12,\nb06=a20*a31-a21*a30,\nb07=a20*a32-a22*a30,\nb08=a20*a33-a23*a30,\nb09=a21*a32-a22*a31,\nb10=a21*a33-a23*a31,\nb11=a22*a33-a23*a32,\ndet=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;var mi: mat4x4f= mat4x4f(\na11*b11-a12*b10+a13*b09,\na02*b10-a01*b11-a03*b09,\na31*b05-a32*b04+a33*b03,\na22*b04-a21*b05-a23*b03,\na12*b08-a10*b11-a13*b07,\na00*b11-a02*b08+a03*b07,\na32*b02-a30*b05-a33*b01,\na20*b05-a22*b02+a23*b01,\na10*b10-a11*b08+a13*b06,\na01*b08-a00*b10-a03*b06,\na30*b04-a31*b02+a33*b00,\na21*b02-a20*b04-a23*b00,\na11*b07-a10*b09-a12*b06,\na00*b09-a01*b07+a02*b06,\na31*b01-a30*b03-a32*b00,\na20*b03-a21*b01+a22*b00)/det;return mat4x4f(mi[0][0],mi[1][0],mi[2][0],mi[3][0],\nmi[0][1],mi[1][1],mi[2][1],mi[3][1],\nmi[0][2],mi[1][2],mi[2][2],mi[3][2],\nmi[0][3],mi[1][3],mi[2][3],mi[3][3]);}\n#endif\n#endif\nfn perturbNormalBase(cotangentFrame: mat3x3f,normal: vec3f,scale: f32)->vec3f\n{\n#ifdef NORMALXYSCALE\nnormal=normalize(normal* vec3f(scale,scale,1.0));\n#endif\nreturn normalize(cotangentFrame*normal);}\nfn perturbNormal(cotangentFrame: mat3x3f,textureSample: vec3f,scale: f32)->vec3f\n{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}\nfn cotangent_frame(normal: vec3f,p: vec3f,uv: vec2f,tangentSpaceParams: vec2f)->mat3x3f\n{var dp1: vec3f=dpdx(p);var dp2: vec3f=dpdy(p);var duv1: vec2f=dpdx(uv);var duv2: vec2f=dpdy(uv);var dp2perp: vec3f=cross(dp2,normal);var dp1perp: vec3f=cross(normal,dp1);var tangent: vec3f=dp2perp*duv1.x+dp1perp*duv2.x;var bitangent: vec3f=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;var det: f32=max(dot(tangent,tangent),dot(bitangent,bitangent));var invmax: f32=select(inverseSqrt(det),0.0,det==0.0);return mat3x3f(tangent*invmax,bitangent*invmax,normal);}\n#endif\n";Bi.IncludesShadersStoreWGSL.samplerFragmentDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying v_VARYINGNAME_UV: vec2f;\n#endif\nuniform _SAMPLERNAME_Sampler: sampler;uniform _SAMPLERNAME_: texture_2d;\n#endif\n";Bi.IncludesShadersStoreWGSL.bumpFragmentFunctions="#if defined(BUMP)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)\n#endif\n#if defined(DETAIL)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)\n#endif\n#if defined(BUMP) && defined(PARALLAX)\nconst minSamples: f32=4.;const maxSamples: f32=15.;const iMaxSamples: i32=15;fn parallaxOcclusion(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32)->vec2f {var parallaxLimit: f32=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;var vOffsetDir: vec2f=normalize(vViewDirCoT.xy);var vMaxOffset: vec2f=vOffsetDir*parallaxLimit;var numSamples: f32=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));var stepSize: f32=1.0/numSamples;var currRayHeight: f32=1.0;var vCurrOffset: vec2f= vec2f(0,0);var vLastOffset: vec2f= vec2f(0,0);var lastSampledHeight: f32=1.0;var currSampledHeight: f32=1.0;var keepWorking: bool=true;for (var i: i32=0; icurrRayHeight)\n{var delta1: f32=currSampledHeight-currRayHeight;var delta2: f32=(currRayHeight+stepSize)-lastSampledHeight;var ratio: f32=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}\nelse\n{currRayHeight-=stepSize;vLastOffset=vCurrOffset;\n#ifdef PARALLAX_RHS\nvCurrOffset-=stepSize*vMaxOffset;\n#else\nvCurrOffset+=stepSize*vMaxOffset;\n#endif\nlastSampledHeight=currSampledHeight;}}\nreturn vCurrOffset;}\nfn parallaxOffset(viewDir: vec3f,heightScale: f32)->vec2f\n{var height: f32=textureSample(bump,bumpSampler,vBumpUV).w;var texCoordOffset: vec2f=heightScale*viewDir.xy*height;\n#ifdef PARALLAX_RHS\nreturn texCoordOffset;\n#else\nreturn -texCoordOffset;\n#endif\n}\n#endif\n";const qf={texture_1d:_f.E1d,texture_2d:_f.E2d,texture_2d_array:_f.E2dArray,texture_3d:_f.E3d,texture_cube:_f.Cube,texture_cube_array:_f.CubeArray,texture_multisampled_2d:_f.E2d,texture_depth_2d:_f.E2d,texture_depth_2d_array:_f.E2dArray,texture_depth_cube:_f.Cube,texture_depth_cube_array:_f.CubeArray,texture_depth_multisampled_2d:_f.E2d,texture_storage_1d:_f.E1d,texture_storage_2d:_f.E2d,texture_storage_2d_array:_f.E2dArray,texture_storage_3d:_f.E3d,texture_external:null};class Zf extends Yf{constructor(){super(...arguments),this.shaderLanguage=di.WGSL,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0}preProcessor(e,t,i,s,r){for(const t in i){if("__VERSION__"===t)continue;const s=i[t];isNaN(parseInt(s))&&isNaN(parseFloat(s))||(e=`const ${t} = ${s};\n`+e)}return e}_getArraySize(e,t,i){let s=0;const r=t.lastIndexOf(">");if(t.indexOf("array")>=0&&r>0){let e=r;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;const n=t.substring(e+1,r);for(s=+n,isNaN(s)&&(s=+i[n.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){const t=`struct ${Yf.InternalsUBOName} {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar internals : ${Yf.InternalsUBOName};\n`;return-1!==e.indexOf(t)?e:t+Np(e)}varyingCheck(e,t){return/(flat|linear|perspective)?\s*(center|centroid|sample)?\s*\bvarying\b/.test(e)}varyingProcessor(e,t,i){const s=/\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==s){const r=s[1]??"perspective",n=s[2]??"center",o=s[4],a=s[3],l="flat"===r?`@interpolate(${r})`:`@interpolate(${r}, ${n})`;let h;t?(h=this._webgpuProcessingContext.availableVaryings[a],void 0===h&&Ne.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`)):(h=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(a,o,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=h,this._varyingsWGSL.push(` @location(${h}) ${l} ${a} : ${o},`),this._varyingNamesWGSL.push(a)),e=""}return e}attributeProcessor(e,t){const i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){const s=i[2],r=i[1],n=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(r,s,t)[2]);this._webgpuProcessingContext.availableAttributes[r]=n,this._webgpuProcessingContext.orderedAttributes[n]=r;const o=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[r];if(void 0!==o){const e=o<0?-1===o?"i32":"vec"+-o+"":1===o?"u32":"vec"+o+"",t=`_int_${r}_`;this._attributesInputWGSL.push(`@location(${n}) ${t} : ${e},`),this._attributesWGSL.push(`${r} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${r} = ${s}(vertexInputs_.${t});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${n}) ${r} : ${s},`),this._attributesWGSL.push(`${r} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${r} = vertexInputs_.${r};`);e=""}return e}uniformProcessor(e,t,i){const s=this.uniformRegexp.exec(e);if(null!==s){const t=s[2],r=s[1];this._addUniformToLeftOverUBO(r,t,i),e=""}return e}textureProcessor(e,t,i){const s=this.textureRegexp.exec(e);if(null!==s){const r=s[1],n=s[2],o=!!s[3],a=s[4],l=a.indexOf("storage")>0,h=s[6],c=l?h.substring(0,h.indexOf(",")).trim():null;let u=o?this._getArraySize(r,n,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[r];if(d)u=d.textures.length;else{d={isTextureArray:u>0,isStorageTexture:l,textures:[],sampleType:Sf.Float},u=u||1;for(let e=0;e0,p=qf[a],f=_?Sf.Depth:"u32"===h?Sf.Uint:"i32"===h?Sf.Sint:Sf.Float;if(d.sampleType=f,void 0===p)throw`Can't get the texture dimension corresponding to the texture function "${a}"!`;for(let i=0;i=0?"\n if (internals.yFactor_ == 1.) {\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\n }\n ":"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);const s=this._buildLeftOverUBO();t=s+t,e=(e=(e=s+e).replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;")).replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let r="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesInputWGSL.length>0&&(r+=this._attributesInputWGSL.join("\n")),r+="\n};\nvar vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(r+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n",r+=this._attributesWGSL.join("\n"),r+="\n};\nvar vertexInputs : VertexInputs_;\n");let n="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join("\n")),n+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=r+n+e;let o=`\n vertexInputs${this._hasNonFloatAttribute?"_":""} = input;\n`;this._hasNonFloatAttribute&&(o+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n",o+=this._attributesConversionCodeWGSL.join("\n"),o+="\n");let a=-1!==e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS");e=(a?"diagnostic(off, derivative_uniformity);\n":"")+Lp(e,"fn main",o," vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;"),t=(t=t.replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;")).replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let l="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(l+=this._varyingsWGSL.join("\n")),l+="\n};\nvar fragmentInputs : FragmentInputs;\n";let h="struct FragmentOutputs {\n @location(0) color : vec4,\n",c=!1,u=0;for(;!(c||(u=t.indexOf("fragmentOutputs.fragDepth",u),u<0));){const e=u;for(c=!0;u>1&&"\n"!==t.charAt(u);){if("/"===t.charAt(u)&&"/"===t.charAt(u-1)){c=!1;break}u--}u=e+25}c&&(h+=" @builtin(frag_depth) fragDepth: f32,\n"),h+="};\nvar fragmentOutputs : FragmentOutputs;\n";const d=" fragmentInputs = input;\n "+i;return a=-1!==(t=l+h+t).indexOf("#define DISABLE_UNIFORMITY_ANALYSIS"),t=(a?"diagnostic(off, derivative_uniformity);\n":"")+Lp(t,"fn main",d," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",s=`struct ${e} {\n`;for(const t of this._webgpuProcessingContext.leftOverUniforms){const r=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),n=Yf.UniformSizes[r];if(t.length>0)if(n<=2){const n=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${n} {\n @size(16)\n el: ${r},\n }`,this._stridedUniformArrays.push(t.name),s+=` @align(16) ${t.name} : array<${n}, ${t.length}>,\n`}else s+=` ${t.name} : array<${t.type}, ${t.length}>,\n`;else s+=` ${t.name} : ${t.type},\n`}return s+="};\n",s=`${i}\n${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var uniforms : ${e};\n`,s}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const s=i.exec(e);if(null===s)break;const r=s[1],n=s[2],o=r.indexOf("Sampler")===r.length-7?r.substring(0,r.indexOf("Sampler")):null,a="sampler_comparison"===n?yf.Comparison:yf.Filtering;if(o){const e=this._webgpuProcessingContext.availableTextures[o];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[r];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:a},this._webgpuProcessingContext.availableSamplers[r]=l),this._addSamplerBindingDescription(r,l,t);const h=e.substring(0,s.index),c=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `,u=e.substring(s.index);e=h+c+u,i.lastIndex+=c.length}return e}_processCustomBuffers(e,t){const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const s=i.exec(e);if(null===s)break;const r=s[1],n=s[3];let o=s[4];const a=s[5];let l=this._webgpuProcessingContext.availableBuffers[o];if(!l){const e="uniform"===r?Kf.KnownUBOs[a]:null;let t;e?(o=a,t=e.binding,-1===t.groupIndex&&(t=this._webgpuProcessingContext.availableBuffers[o]?.binding,t||(t=this._webgpuProcessingContext.getNextFreeUBOBinding()))):t=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:t},this._webgpuProcessingContext.availableBuffers[o]=l}this._addBufferBindingDescription(o,this._webgpuProcessingContext.availableBuffers[o],"read_write"===n?Tf.Storage:"storage"===r?Tf.ReadOnlyStorage:Tf.Uniform,t);const h=l.binding.groupIndex,c=l.binding.bindingIndex,u=e.substring(0,s.index),d=`@group(${h}) @binding(${c}) `,_=e.substring(s.index);e=u+d+_,i.lastIndex+=d.length}return e}_processStridedUniformArrays(e){for(const t of this._stridedUniformArrays)e=e.replace(new RegExp(`${t}\\s*\\[(.*?)\\]`,"g"),`${t}[$1].el`);return e}}class Jf{static ComputeNumMipmapLevels(e,t){return be.ILog2(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case ff.R8Unorm:case ff.R8Snorm:case ff.R8Uint:case ff.R8Sint:case ff.RG8Unorm:case ff.RG8Snorm:case ff.RG8Uint:case ff.RG8Sint:case ff.RGBA8Unorm:case ff.RGBA8UnormSRGB:case ff.RGBA8Snorm:case ff.RGBA8Uint:case ff.RGBA8Sint:case ff.BGRA8Unorm:case ff.BGRA8UnormSRGB:case ff.RGB10A2UINT:case ff.RGB10A2Unorm:case ff.RGB9E5UFloat:case ff.RG11B10UFloat:case ff.BC7RGBAUnorm:case ff.BC7RGBAUnormSRGB:case ff.BC6HRGBUFloat:case ff.BC6HRGBFloat:case ff.BC5RGUnorm:case ff.BC5RGSnorm:case ff.BC3RGBAUnorm:case ff.BC3RGBAUnormSRGB:case ff.BC2RGBAUnorm:case ff.BC2RGBAUnormSRGB:case ff.BC4RUnorm:case ff.BC4RSnorm:case ff.BC1RGBAUnorm:case ff.BC1RGBAUnormSRGB:case ff.ETC2RGB8Unorm:case ff.ETC2RGB8UnormSRGB:case ff.ETC2RGB8A1Unorm:case ff.ETC2RGB8A1UnormSRGB:case ff.ETC2RGBA8Unorm:case ff.ETC2RGBA8UnormSRGB:case ff.EACR11Unorm:case ff.EACR11Snorm:case ff.EACRG11Unorm:case ff.EACRG11Snorm:case ff.ASTC4x4Unorm:case ff.ASTC4x4UnormSRGB:case ff.ASTC5x4Unorm:case ff.ASTC5x4UnormSRGB:case ff.ASTC5x5Unorm:case ff.ASTC5x5UnormSRGB:case ff.ASTC6x5Unorm:case ff.ASTC6x5UnormSRGB:case ff.ASTC6x6Unorm:case ff.ASTC6x6UnormSRGB:case ff.ASTC8x5Unorm:case ff.ASTC8x5UnormSRGB:case ff.ASTC8x6Unorm:case ff.ASTC8x6UnormSRGB:case ff.ASTC8x8Unorm:case ff.ASTC8x8UnormSRGB:case ff.ASTC10x5Unorm:case ff.ASTC10x5UnormSRGB:case ff.ASTC10x6Unorm:case ff.ASTC10x6UnormSRGB:case ff.ASTC10x8Unorm:case ff.ASTC10x8UnormSRGB:case ff.ASTC10x10Unorm:case ff.ASTC10x10UnormSRGB:case ff.ASTC12x10Unorm:case ff.ASTC12x10UnormSRGB:case ff.ASTC12x12Unorm:case ff.ASTC12x12UnormSRGB:case ff.Stencil8:return 0;case ff.R16Uint:case ff.R16Sint:case ff.RG16Uint:case ff.RG16Sint:case ff.RGBA16Uint:case ff.RGBA16Sint:case ff.Depth16Unorm:return 5;case ff.R16Float:case ff.RG16Float:case ff.RGBA16Float:return 2;case ff.R32Uint:case ff.R32Sint:case ff.RG32Uint:case ff.RG32Sint:case ff.RGBA32Uint:case ff.RGBA32Sint:return 7;case ff.R32Float:case ff.RG32Float:case ff.RGBA32Float:case ff.Depth32Float:case ff.Depth32FloatStencil8:case ff.Depth24Plus:case ff.Depth24PlusStencil8:return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case ff.R8Unorm:case ff.R8Snorm:case ff.R8Uint:case ff.R8Sint:return{width:1,height:1,length:1};case ff.R16Uint:case ff.R16Sint:case ff.R16Float:case ff.RG8Unorm:case ff.RG8Snorm:case ff.RG8Uint:case ff.RG8Sint:return{width:1,height:1,length:2};case ff.R32Uint:case ff.R32Sint:case ff.R32Float:case ff.RG16Uint:case ff.RG16Sint:case ff.RG16Float:case ff.RGBA8Unorm:case ff.RGBA8UnormSRGB:case ff.RGBA8Snorm:case ff.RGBA8Uint:case ff.RGBA8Sint:case ff.BGRA8Unorm:case ff.BGRA8UnormSRGB:case ff.RGB9E5UFloat:case ff.RGB10A2UINT:case ff.RGB10A2Unorm:case ff.RG11B10UFloat:return{width:1,height:1,length:4};case ff.RG32Uint:case ff.RG32Sint:case ff.RG32Float:case ff.RGBA16Uint:case ff.RGBA16Sint:case ff.RGBA16Float:return{width:1,height:1,length:8};case ff.RGBA32Uint:case ff.RGBA32Sint:case ff.RGBA32Float:return{width:1,height:1,length:16};case ff.Stencil8:throw"No fixed size for Stencil8 format!";case ff.Depth16Unorm:return{width:1,height:1,length:2};case ff.Depth24Plus:throw"No fixed size for Depth24Plus format!";case ff.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case ff.Depth32Float:return{width:1,height:1,length:4};case ff.Depth32FloatStencil8:return{width:1,height:1,length:5};case ff.BC7RGBAUnorm:case ff.BC7RGBAUnormSRGB:case ff.BC6HRGBUFloat:case ff.BC6HRGBFloat:case ff.BC5RGUnorm:case ff.BC5RGSnorm:case ff.BC3RGBAUnorm:case ff.BC3RGBAUnormSRGB:case ff.BC2RGBAUnorm:case ff.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case ff.BC4RUnorm:case ff.BC4RSnorm:case ff.BC1RGBAUnorm:case ff.BC1RGBAUnormSRGB:case ff.ETC2RGB8Unorm:case ff.ETC2RGB8UnormSRGB:case ff.ETC2RGB8A1Unorm:case ff.ETC2RGB8A1UnormSRGB:case ff.EACR11Unorm:case ff.EACR11Snorm:return{width:4,height:4,length:8};case ff.ETC2RGBA8Unorm:case ff.ETC2RGBA8UnormSRGB:case ff.EACRG11Unorm:case ff.EACRG11Snorm:case ff.ASTC4x4Unorm:case ff.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case ff.ASTC5x4Unorm:case ff.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case ff.ASTC5x5Unorm:case ff.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case ff.ASTC6x5Unorm:case ff.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case ff.ASTC6x6Unorm:case ff.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case ff.ASTC8x5Unorm:case ff.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case ff.ASTC8x6Unorm:case ff.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case ff.ASTC8x8Unorm:case ff.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case ff.ASTC10x5Unorm:case ff.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case ff.ASTC10x6Unorm:case ff.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case ff.ASTC10x8Unorm:case ff.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case ff.ASTC10x10Unorm:case ff.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case ff.ASTC12x10Unorm:case ff.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case ff.ASTC12x12Unorm:case ff.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}static IsCompressedFormat(e){switch(e){case ff.BC7RGBAUnormSRGB:case ff.BC7RGBAUnorm:case ff.BC6HRGBFloat:case ff.BC6HRGBUFloat:case ff.BC5RGSnorm:case ff.BC5RGUnorm:case ff.BC4RSnorm:case ff.BC4RUnorm:case ff.BC3RGBAUnormSRGB:case ff.BC3RGBAUnorm:case ff.BC2RGBAUnormSRGB:case ff.BC2RGBAUnorm:case ff.BC1RGBAUnormSRGB:case ff.BC1RGBAUnorm:case ff.ETC2RGB8Unorm:case ff.ETC2RGB8UnormSRGB:case ff.ETC2RGB8A1Unorm:case ff.ETC2RGB8A1UnormSRGB:case ff.ETC2RGBA8Unorm:case ff.ETC2RGBA8UnormSRGB:case ff.EACR11Unorm:case ff.EACR11Snorm:case ff.EACRG11Unorm:case ff.EACRG11Snorm:case ff.ASTC4x4Unorm:case ff.ASTC4x4UnormSRGB:case ff.ASTC5x4Unorm:case ff.ASTC5x4UnormSRGB:case ff.ASTC5x5Unorm:case ff.ASTC5x5UnormSRGB:case ff.ASTC6x5Unorm:case ff.ASTC6x5UnormSRGB:case ff.ASTC6x6Unorm:case ff.ASTC6x6UnormSRGB:case ff.ASTC8x5Unorm:case ff.ASTC8x5UnormSRGB:case ff.ASTC8x6Unorm:case ff.ASTC8x6UnormSRGB:case ff.ASTC8x8Unorm:case ff.ASTC8x8UnormSRGB:case ff.ASTC10x5Unorm:case ff.ASTC10x5UnormSRGB:case ff.ASTC10x6Unorm:case ff.ASTC10x6UnormSRGB:case ff.ASTC10x8Unorm:case ff.ASTC10x8UnormSRGB:case ff.ASTC10x10Unorm:case ff.ASTC10x10UnormSRGB:case ff.ASTC12x10Unorm:case ff.ASTC12x10UnormSRGB:case ff.ASTC12x12Unorm:case ff.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return ff.Depth16Unorm;case 16:return ff.Depth24Plus;case 13:return ff.Depth24PlusStencil8;case 14:return ff.Depth32Float;case 18:return ff.Depth32FloatStencil8;case 19:return ff.Stencil8;case 36492:return i?ff.BC7RGBAUnormSRGB:ff.BC7RGBAUnorm;case 36495:return ff.BC6HRGBUFloat;case 36494:return ff.BC6HRGBFloat;case 33779:return i?ff.BC3RGBAUnormSRGB:ff.BC3RGBAUnorm;case 33778:return i?ff.BC2RGBAUnormSRGB:ff.BC2RGBAUnorm;case 33777:case 33776:return i?ff.BC1RGBAUnormSRGB:ff.BC1RGBAUnorm;case 37808:return i?ff.ASTC4x4UnormSRGB:ff.ASTC4x4Unorm;case 36196:case 37492:return i?ff.ETC2RGB8UnormSRGB:ff.ETC2RGB8Unorm;case 37496:return i?ff.ETC2RGBA8UnormSRGB:ff.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return ff.R8Snorm;case 7:return ff.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return ff.R8Sint;case 9:return ff.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return ff.RGBA8Sint;default:return ff.RGBA8Snorm}case 0:switch(t){case 6:return ff.R8Unorm;case 7:return ff.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?ff.RGBA8UnormSRGB:ff.RGBA8Unorm;case 12:return i?ff.BGRA8UnormSRGB:ff.BGRA8Unorm;case 8:return ff.R8Uint;case 9:return ff.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return ff.RGBA8Uint;case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return ff.RGBA8Unorm}case 4:switch(t){case 8:return ff.R16Sint;case 9:return ff.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ff.RGBA16Sint}case 5:switch(t){case 8:return ff.R16Uint;case 9:return ff.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ff.RGBA16Uint}case 6:switch(t){case 8:return ff.R32Sint;case 9:return ff.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ff.RGBA32Sint}case 7:switch(t){case 8:return ff.R32Uint;case 9:return ff.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ff.RGBA32Uint}case 1:switch(t){case 6:return ff.R32Float;case 7:return ff.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return ff.RGBA32Float}case 2:switch(t){case 6:return ff.R16Float;case 7:return ff.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return ff.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return ff.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"}case 14:switch(t){case 5:default:return ff.RGB9E5UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:default:return ff.RGB10A2Unorm;case 11:return ff.RGB10A2UINT}}return i?ff.RGBA8UnormSRGB:ff.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case ff.R8Unorm:case ff.R8Snorm:case ff.R8Uint:case ff.R8Sint:case ff.BC4RUnorm:case ff.BC4RSnorm:case ff.R16Uint:case ff.R16Sint:case ff.Depth16Unorm:case ff.R16Float:case ff.R32Uint:case ff.R32Sint:case ff.R32Float:case ff.Depth32Float:case ff.Stencil8:case ff.Depth24Plus:case ff.EACR11Unorm:case ff.EACR11Snorm:return 1;case ff.RG8Unorm:case ff.RG8Snorm:case ff.RG8Uint:case ff.RG8Sint:case ff.Depth32FloatStencil8:case ff.BC5RGUnorm:case ff.BC5RGSnorm:case ff.RG16Uint:case ff.RG16Sint:case ff.RG16Float:case ff.RG32Uint:case ff.RG32Sint:case ff.RG32Float:case ff.Depth24PlusStencil8:case ff.EACRG11Unorm:case ff.EACRG11Snorm:return 2;case ff.RGB9E5UFloat:case ff.RG11B10UFloat:case ff.BC6HRGBUFloat:case ff.BC6HRGBFloat:case ff.ETC2RGB8Unorm:case ff.ETC2RGB8UnormSRGB:return 3;case ff.RGBA8Unorm:case ff.RGBA8UnormSRGB:case ff.RGBA8Snorm:case ff.RGBA8Uint:case ff.RGBA8Sint:case ff.BGRA8Unorm:case ff.BGRA8UnormSRGB:case ff.RGB10A2UINT:case ff.RGB10A2Unorm:case ff.BC7RGBAUnorm:case ff.BC7RGBAUnormSRGB:case ff.BC3RGBAUnorm:case ff.BC3RGBAUnormSRGB:case ff.BC2RGBAUnorm:case ff.BC2RGBAUnormSRGB:case ff.BC1RGBAUnorm:case ff.BC1RGBAUnormSRGB:case ff.RGBA16Uint:case ff.RGBA16Sint:case ff.RGBA16Float:case ff.RGBA32Uint:case ff.RGBA32Sint:case ff.RGBA32Float:case ff.ETC2RGB8A1Unorm:case ff.ETC2RGB8A1UnormSRGB:case ff.ETC2RGBA8Unorm:case ff.ETC2RGBA8UnormSRGB:case ff.ASTC4x4Unorm:case ff.ASTC4x4UnormSRGB:case ff.ASTC5x4Unorm:case ff.ASTC5x4UnormSRGB:case ff.ASTC5x5Unorm:case ff.ASTC5x5UnormSRGB:case ff.ASTC6x5Unorm:case ff.ASTC6x5UnormSRGB:case ff.ASTC6x6Unorm:case ff.ASTC6x6UnormSRGB:case ff.ASTC8x5Unorm:case ff.ASTC8x5UnormSRGB:case ff.ASTC8x6Unorm:case ff.ASTC8x6UnormSRGB:case ff.ASTC8x8Unorm:case ff.ASTC8x8UnormSRGB:case ff.ASTC10x5Unorm:case ff.ASTC10x5UnormSRGB:case ff.ASTC10x6Unorm:case ff.ASTC10x6UnormSRGB:case ff.ASTC10x8Unorm:case ff.ASTC10x8UnormSRGB:case ff.ASTC10x10Unorm:case ff.ASTC10x10UnormSRGB:case ff.ASTC12x10Unorm:case ff.ASTC12x10UnormSRGB:case ff.ASTC12x12Unorm:case ff.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case ff.Stencil8:case ff.Depth32FloatStencil8:case ff.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case ff.Depth32FloatStencil8:case ff.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case ff.Depth16Unorm:return ff.Depth16Unorm;case ff.Depth24Plus:case ff.Depth24PlusStencil8:return ff.Depth24Plus;case ff.Depth32Float:case ff.Depth32FloatStencil8:return ff.Depth32Float}return e}static GetSample(e){return e>1?4:1}}class em{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){return this._webgpuMSAATexture?.[e]??null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),-1===t&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(const e of this._webgpuMSAATexture)e?.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this._originalFormatIsRGB=!1,this.format=ff.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,s,r,n,o,a){let l=_f.E2d,h=1;s?(l=i?_f.CubeArray:_f.Cube,h=6*(a||1)):r?(l=_f.E3d,h=1):i&&(l=_f.E2dArray,h=a);const c=Jf.GetDepthFormatOnly(this.format),u=Jf.HasDepthAndStencilAspects(this.format)?pf.DepthOnly:pf.All;this.createView({label:`TextureView${r?"3D":s?"Cube":"2D"}${i?"_Array"+h:""}_${n}x${o}_${t?"wmips":"womips"}_${this.format}_${l}`,format:c,dimension:l,mipLevelCount:t?be.ILog2(Math.max(n,o))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:h,aspect:u})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){this._webgpuTexture?.destroy(),this.releaseMSAATexture(),this._copyInvertYTempTexture?.destroy(),this.reset()}}const tm="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) out flat ivec2 vTextureSize;\n #endif\n\n void main() {\n #ifdef INVERTY\n vTextureSize = textureSize(img, 0);\n #endif\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",im=tm;var sm,rm;!function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"}(sm||(sm={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(rm||(rm={}));const nm=[{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(location = 0) out vec2 vTex;\n\n void main() {\n vTex = tex[gl_VertexIndex];\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform sampler imgSampler;\n layout(set = 0, binding = 1) uniform texture2D img;\n\n layout(location = 0) in vec2 vTex;\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = texture(sampler2D(img, imgSampler), vTex);\n }\n "},{vertex:tm,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "},{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n\n void main() {\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform Uniforms {\n uniform vec4 color;\n };\n\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = color;\n }\n "},{vertex:im,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n layout(set = 0, binding = 1) uniform Params {\n float ofstX;\n float ofstY;\n float width;\n float height;\n };\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) {\n discard;\n }\n if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) {\n discard;\n }\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "}],om={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};class am{constructor(e,t,i,s,r,n){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._glslang=i,this._tintWASM=s,this._bufferManager=r,-1!==n.indexOf(af.RG11B10UFloatRenderable)){const e=Object.keys(om);om[ff.RG11B10UFloat]=om[e[e.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:gf.Linear}),this._videoSampler=t.createSampler({minFilter:gf.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,hf.Uniform|hf.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(ff.RGBA8Unorm),this._getVideoPipeline(ff.RGBA8Unorm)}_getPipeline(e,t=sm.MipMap,i){const s=t===sm.MipMap?1:t===sm.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===sm.Clear?8:t===sm.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let r=this._pipelines[e][s];if(!r){let n="#version 450\n";t!==sm.InvertYPremultiplyAlpha&&t!==sm.InvertYPremultiplyAlphaWithOfst||(i.invertY&&(n+="#define INVERTY\n"),i.premultiplyAlpha&&(n+="#define PREMULTIPLYALPHA\n"));let o=this._compiledShaders[s];if(!o){let e=this._glslang.compileGLSL(n+nm[t].vertex,"vertex"),i=this._glslang.compileGLSL(n+nm[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));const r=this._device.createShaderModule({code:e}),a=this._device.createShaderModule({code:i});o=this._compiledShaders[s]=[r,a]}const a=this._device.createRenderPipeline({layout:Pf.Auto,vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:If.TriangleStrip,stripIndexFormat:Ff.Uint16}});r=this._pipelines[e][s]=[a,a.getBindGroupLayout(0)]}return r}_getVideoPipeline(e,t=rm.DontInvertY){const i=t===rm.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let s=this._videoPipelines[e][i];if(!s){let t=this._videoCompiledShaders[i];if(!t){const e=this._device.createShaderModule({code:"\n struct VertexOutput {\n @builtin(position) Position : vec4,\n @location(0) fragUV : vec2\n }\n\n @vertex\n fn main(\n @builtin(vertex_index) VertexIndex : u32\n ) -> VertexOutput {\n var pos = array, 4>(\n vec2(-1.0, 1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, -1.0)\n );\n var tex = array, 4>(\n vec2(0.0, 0.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(1.0, 1.0)\n );\n\n var output: VertexOutput;\n\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = tex[VertexIndex];\n\n return output;\n }\n "}),s=this._device.createShaderModule({code:0===i?"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\n }\n ":"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y));\n }\n "});t=this._videoCompiledShaders[i]=[e,s]}const r=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:Pf.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:If.TriangleStrip,stripIndexFormat:Ff.Uint16}});s=this._videoPipelines[e][i]=[r,r.getBindGroupLayout(0)]}return s}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,s=!1,r){const n=void 0===r,[o,a]=this._getVideoPipeline(i,s?rm.InvertY:rm.DontInvertY);n&&(r=this._device.createCommandEncoder({})),r.pushDebugGroup?.(`copy video to texture - invertY=${s}`);const l=t._hardwareTexture,h={label:`BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${i}_${s?"InvertY":"DontInvertY"}${t.label?"_"+t.label:""}`,colorAttachments:[{view:l.underlyingResource.createView({format:i,dimension:_f.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:pf.All}),loadOp:Uf.Load,storeOp:Gf.Store}]},c=r.beginRenderPass(h),u={layout:a,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},d=this._device.createBindGroup(u);c.setPipeline(o),c.setBindGroup(0,d),c.draw(4,1,0,0),c.end(),r.popDebugGroup?.(),n&&(this._device.queue.submit([r.finish()]),r=null)}invertYPreMultiplyAlpha(e,t,i,s,r=!1,n=!1,o=0,a=0,l=1,h=0,c=0,u=0,d=0,_,p){const f=0!==u,m=void 0===_,[g,v]=this._getPipeline(s,f?sm.InvertYPremultiplyAlphaWithOfst:sm.InvertYPremultiplyAlpha,{invertY:r,premultiplyAlpha:n});let x;if(o=Math.max(o,0),m&&(_=this._device.createCommandEncoder({})),_.pushDebugGroup?.(`internal process texture - invertY=${r} premultiplyAlpha=${n}`),Jf.IsHardwareTexture(e)?(x=e.underlyingResource,r&&!n&&1===l&&0===o||(e=void 0)):(x=e,e=void 0),!x)return;f&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,c,u,d]),0,16);const b=e,T=b?._copyInvertYTempTexture??this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,s,1,_,df.CopySrc|df.RenderAttachment|df.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),y=b?._copyInvertYRenderPassDescr??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${s}_${r?"InvertY":"DontInvertY"}_${n?"PremultiplyAlpha":"DontPremultiplyAlpha"}`,colorAttachments:[{view:T.createView({format:s,dimension:_f.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:Uf.Load,storeOp:Gf.Store}]},S=_.beginRenderPass(y);let C=f?b?._copyInvertYBindGroupWithOfst:b?._copyInvertYBindGroup;if(!C){const e={layout:v,entries:[{binding:0,resource:x.createView({format:s,dimension:_f.E2d,baseMipLevel:a,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:o})}]};f&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),C=this._device.createBindGroup(e)}S.setPipeline(g),S.setBindGroup(0,C),S.draw(4,1,0,0),S.end(),_.copyTextureToTexture({texture:T},{texture:x,mipLevel:a,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),b?(b._copyInvertYTempTexture=T,b._copyInvertYRenderPassDescr=y,f?b._copyInvertYBindGroupWithOfst=C:b._copyInvertYBindGroup=C):this._deferredReleaseTextures.push([T,null]),_.popDebugGroup?.(),m&&(this._device.queue.submit([_.finish()]),_=null)}copyWithInvertY(e,t,i,s){const r=void 0===s,[n,o]=this._getPipeline(t,sm.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});r&&(s=this._device.createCommandEncoder({})),s.pushDebugGroup?.("internal copy texture with invertY");const a=s.beginRenderPass(i),l=this._device.createBindGroup({layout:o,entries:[{binding:0,resource:e}]});a.setPipeline(n),a.setBindGroup(0,l),a.draw(4,1,0,0),a.end(),s.popDebugGroup?.(),r&&(this._device.queue.submit([s.finish()]),s=null)}createTexture(e,t=!1,i=!1,s=!1,r=!1,n=!1,o=ff.RGBA8Unorm,a=1,l,h=-1,c=0,u){a=Jf.GetSample(a);const d=e.layers||1,_={width:e.width,height:e.height,depthOrArrayLayers:d},p=om[o]?df.RenderAttachment:0,f=Jf.IsCompressedFormat(o),m=t?Jf.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:df.CopySrc|df.CopyDst|df.TextureBinding;c|=t&&!f?df.CopySrc|p:0,f||n||(c|=p|df.CopyDst);const v=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_Texture${n?"3D":"2D"}_${u?u+"_":""}${_.width}x${_.height}x${_.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${a}`,size:_,dimension:n?uf.E3d:uf.E2d,format:o,usage:g|c,sampleCount:a,mipLevelCount:m});return Jf.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,o,0,0,s,r,0,0),t&&i&&this.generateMipmaps(v,o,m,0,n,l)),v}createCubeTexture(e,t=!1,i=!1,s=!1,r=!1,n=ff.RGBA8Unorm,o=1,a,l=-1,h=0,c){o=Jf.GetSample(o);const u=Jf.IsImageBitmapArray(e)?e[0].width:e.width,d=Jf.IsImageBitmapArray(e)?e[0].height:e.height,_=om[n]?df.RenderAttachment:0,p=Jf.IsCompressedFormat(n),f=t?Jf.ComputeNumMipmapLevels(u,d):1,m=l>=0?l:df.CopySrc|df.CopyDst|df.TextureBinding;h|=t&&!p?df.CopySrc|_:0,p||(h|=_|df.CopyDst);const g=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${c?c+"_":""}${u}x${d}x6_${t?"wmips":"womips"}_${n}_samples${o}`,size:{width:u,height:d,depthOrArrayLayers:6},dimension:uf.E2d,format:n,usage:m|h,sampleCount:o,mipLevelCount:f});return Jf.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,u,d,n,s,r,0,0),t&&i&&this.generateCubeMipmaps(g,n,f,a)),g}generateCubeMipmaps(e,t,i,s){const r=void 0===s;r&&(s=this._device.createCommandEncoder({})),s.pushDebugGroup?.(`create cube mipmaps - ${i} levels`);for(let r=0;r<6;++r)this.generateMipmaps(e,t,i,r,!1,s);s.popDebugGroup?.(),r&&(this._device.queue.submit([s.finish()]),s=null)}generateMipmaps(e,t,i,s=0,r=!1,n){const o=void 0===n,[a,l]=this._getPipeline(t);let h;if(s=Math.max(s,0),o&&(n=this._device.createCommandEncoder({})),n.pushDebugGroup?.(`create mipmaps for face #${s} - ${i} levels`),Jf.IsHardwareTexture(e)?(h=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(h=e,e=void 0),!h)return;const c=e;for(let e=1;eh;)this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,h),c+=h;this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,r-c)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const s=new Uint16Array(t);for(;e--;)i[e]=ip(s[e]);return i}readDataFromBuffer(e,t,i,s,r,n,o=0,a=0,l=null,h=!0,c=!1){const u=1===o?2:2===o?1:0,d=this._engine.uniqueId;return new Promise(((i,_)=>{e.mapAsync(cf.Read,a,t).then((()=>{const d=e.getMappedRange(a,t);let _=l;if(c)_=null===_?Kn(o,t,!0,d):Kn(o,_.buffer,void 0,d);else if(null===_)switch(u){case 0:_=new Uint8Array(t),_.set(new Uint8Array(d));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:_=new Float32Array(t/4),_.set(new Float32Array(d))}else switch(u){case 0:_=new Uint8Array(_.buffer),_.set(new Uint8Array(d));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:_=new Float32Array(_.buffer),_.set(new Float32Array(d))}if(r!==n){1!==u||c||(r*=2,n*=2);const e=new Uint8Array(_.buffer);let t=r,i=0;for(let o=1;o{this._engine.isDisposed||this._engine.uniqueId!==d?i(new Uint8Array):_(e)}))}))}releaseBuffer(e){return hm._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e1?4:1;return cm[e.samplingMode]+um[(e._comparisonFunction||514)-512+1]+dm[e.samplingMode]+((e._cachedWrapU??1)<<8)+((e._cachedWrapV??1)<<10)+((e._cachedWrapR??1)<<12)+((e.useMipMaps?1:0)<<14)+(t<<15)}static _GetSamplerFilterDescriptor(e,t){let i,s,r,n,o;const a=e.useMipMaps;switch(e.samplingMode){case 11:i=gf.Linear,s=gf.Linear,r=gf.Nearest,a||(n=o=0);break;case 3:case 3:i=gf.Linear,s=gf.Linear,a?r=gf.Linear:(r=gf.Nearest,n=o=0);break;case 8:i=gf.Nearest,s=gf.Nearest,a?r=gf.Linear:(r=gf.Nearest,n=o=0);break;case 4:i=gf.Nearest,s=gf.Nearest,r=gf.Nearest,a||(n=o=0);break;case 5:i=gf.Nearest,s=gf.Linear,r=gf.Nearest,a||(n=o=0);break;case 6:i=gf.Nearest,s=gf.Linear,a?r=gf.Linear:(r=gf.Nearest,n=o=0);break;case 7:i=gf.Nearest,s=gf.Linear,r=gf.Nearest,n=o=0;break;case 1:case 1:default:i=gf.Nearest,s=gf.Nearest,r=gf.Nearest,n=o=0;break;case 9:i=gf.Linear,s=gf.Nearest,r=gf.Nearest,a||(n=o=0);break;case 10:i=gf.Linear,s=gf.Nearest,a?r=gf.Linear:(r=gf.Nearest,n=o=0);break;case 2:case 2:i=gf.Linear,s=gf.Linear,r=gf.Nearest,n=o=0;break;case 12:i=gf.Linear,s=gf.Nearest,r=gf.Nearest,n=o=0}return t>1&&(0!==n||0!==o)&&r!==gf.Nearest?{magFilter:gf.Linear,minFilter:gf.Linear,mipmapFilter:gf.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:s,mipmapFilter:r,lodMinClamp:n,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return mf.Repeat;case 0:return mf.ClampToEdge;case 2:return mf.MirrorRepeat}return mf.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,t){const i=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,s=this._GetSamplerFilterDescriptor(e,i);return{label:t,...s,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?_m.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:s.anisotropyEnabled?i:1}}static GetCompareFunction(e){switch(e){case 519:return xf.Always;case 514:return xf.Equal;case 516:return xf.Greater;case 518:return xf.GreaterEqual;case 513:default:return xf.Less;case 515:return xf.LessEqual;case 512:return xf.Never;case 517:return xf.NotEqual}}getSampler(e,t=!1,i=0,s){if(this.disabled)return this._device.createSampler(_m._GetSamplerDescriptor(e,s));t?i=0:0===i&&(i=_m.GetSamplerHashCode(e));let r=t?void 0:this._samplers[i];return r||(r=this._device.createSampler(_m._GetSamplerDescriptor(e,s)),t||(this._samplers[i]=r)),r}}var pm;!function(e){e[e.StencilReadMask=0]="StencilReadMask",e[e.StencilWriteMask=1]="StencilWriteMask",e[e.DepthBias=2]="DepthBias",e[e.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",e[e.DepthStencilState=4]="DepthStencilState",e[e.MRTAttachments1=5]="MRTAttachments1",e[e.MRTAttachments2=6]="MRTAttachments2",e[e.RasterizationState=7]="RasterizationState",e[e.ColorStates=8]="ColorStates",e[e.ShaderStage=9]="ShaderStage",e[e.TextureStage=10]="TextureStage",e[e.VertexState=11]="VertexState",e[e.NumStates=12]="NumStates"}(pm||(pm={}));const fm={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},mm={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class gm{constructor(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[ff.BGRA8Unorm],this.setColorFormat(ff.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(ff.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,s=0){if(i=Jf.GetSample(i),this.disabled){const r=gm._GetTopology(e);return this._setVertexState(t),this._setTextureState(s),this._parameter.pipeline=this._createRenderPipeline(t,r,i),gm.NumCacheMiss++,gm._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(s),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,gm.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return gm.NumCacheHitWithHash++,this._parameter.pipeline;const r=gm._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,r,i),this._setRenderPipeline(this._parameter),gm.NumCacheMiss++,gm._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){gm.NumPipelineCreationLastFrame=gm._NumPipelineCreationCurrentFrame,gm._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,s,r,n,o,a){this._depthWriteEnabled=o,this._depthTestEnabled=n,this._depthCompare=(a??519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(s),this.setDepthBias(r)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[pm.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[pm.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=om[e??""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const i=[0,0];let s=0,r=0,n=0;for(let o=0;o=32&&(r=0,s++)}this._mrtFormats.length=n,this._mrtAttachments1===i[0]&&this._mrtAttachments2===i[1]||(this._mrtAttachments1=i[0],this._mrtAttachments2=i[1],this._states[pm.MRTAttachments1]=i[0],this._states[pm.MRTAttachments2]=i[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=void 0===e?0:om[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(e??519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(e??519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=null===e?1:mm[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:mm[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:mm[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[pm.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[pm.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,s,r,n,o){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=null===i?1:mm[i],this._stencilFrontPassOp=null===s?2:mm[s],this._stencilFrontFailOp=null===r?1:mm[r],this.setStencilReadMask(n),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return If.TriangleList;case 2:case 3:return If.PointList;case 1:case 4:return If.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return If.LineStrip;case 7:return If.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return wf.Add;case 32778:return wf.Subtract;case 32779:return wf.ReverseSubtract;case 32775:return wf.Min;case 32776:return wf.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return Df.Zero;case 1:default:return Df.One;case 768:return Df.Src;case 769:return Df.OneMinusSrc;case 770:return Df.SrcAlpha;case 771:return Df.OneMinusSrcAlpha;case 772:return Df.DstAlpha;case 773:return Df.OneMinusDstAlpha;case 774:return Df.Dst;case 775:return Df.OneMinusDst;case 776:return Df.SrcAlphaSaturated;case 32769:case 32771:return Df.Constant;case 32770:case 32772:return Df.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:return xf.Never;case 1:return xf.Less;case 2:return xf.Equal;case 3:return xf.LessEqual;case 4:return xf.Greater;case 5:return xf.NotEqual;case 6:return xf.GreaterEqual;case 7:return xf.Always}return xf.Never}static _GetStencilOpFunction(e){switch(e){case 0:return Nf.Zero;case 1:return Nf.Keep;case 2:return Nf.Replace;case 3:return Nf.IncrementClamp;case 4:return Nf.DecrementClamp;case 5:return Nf.Invert;case 6:return Nf.IncrementWrap;case 7:return Nf.DecrementWrap}return Nf.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,s=e.getSize();switch(t){case er.BYTE:switch(s){case 1:case 2:return i?Lf.Snorm8x2:Lf.Sint8x2;case 3:case 4:return i?Lf.Snorm8x4:Lf.Sint8x4}break;case er.UNSIGNED_BYTE:switch(s){case 1:case 2:return i?Lf.Unorm8x2:Lf.Uint8x2;case 3:case 4:return i?Lf.Unorm8x4:Lf.Uint8x4}break;case er.SHORT:switch(s){case 1:case 2:return i?Lf.Snorm16x2:Lf.Sint16x2;case 3:case 4:return i?Lf.Snorm16x4:Lf.Sint16x4}break;case er.UNSIGNED_SHORT:switch(s){case 1:case 2:return i?Lf.Unorm16x2:Lf.Uint16x2;case 3:case 4:return i?Lf.Unorm16x4:Lf.Uint16x4}break;case er.INT:switch(s){case 1:return Lf.Sint32;case 2:return Lf.Sint32x2;case 3:return Lf.Sint32x3;case 4:return Lf.Sint32x4}break;case er.UNSIGNED_INT:switch(s){case 1:return Lf.Uint32;case 2:return Lf.Uint32x2;case 3:return Lf.Uint32x3;case 4:return Lf.Uint32x4}break;case er.FLOAT:switch(s){case 1:return Lf.Float32;case 2:return Lf.Float32x2;case 3:return Lf.Float32x3;case 4:return Lf.Float32x4}}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${s}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:gm._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:gm._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:gm._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:gm._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:gm._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:gm._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[pm.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace-1+((this._cullEnabled?this._cullFace:0)<<1)+((this._clampDepth?1:0)<<3)+((this._alphaToCoverageEnabled?1:0)<<4)+(e<<5)+(t<<8);this._rasterizationState!==i&&(this._rasterizationState=i,this._states[pm.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=(0|(null===this._alphaBlendFuncParams[0]?2:fm[this._alphaBlendFuncParams[0]]))+((null===this._alphaBlendFuncParams[1]?2:fm[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:fm[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:fm[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[pm.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.ColorStates))}_setDepthStencilState(){const e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[pm.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,pm.DepthStencilState))}_setVertexState(e){const t=this._statesLength;let i=pm.VertexState;const s=e._pipelineContext,r=s.shaderProcessingContext.attributeNamesFromEffect,n=s.shaderProcessingContext.attributeLocationsFromEffect;let o,a=0;for(let e=0;e0)for(let e=0;e=this._video.HAVE_CURRENT_DATA}dispose(){}}class Sm{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=Sm._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],s=-1;i?s=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?_m.GetSamplerHashCode(t):0;const r=s!==i.hashCode;r&&this.updateId++,this.isDirty||(this.isDirty=r)}setTexture(e,t){let i=this.textures[e],s=-1;i?s=i.texture?.uniqueId??-1:this.textures[e]=i={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},i.isExternalTexture&&this._numExternalTextures--,i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(i.isFloatOrDepthTexture=1===t.type||t.format>=13&&t.format<=18,i.isExternalTexture=ym.IsExternalTexture(t),i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,i.isExternalTexture&&this._numExternalTextures++):(i.isFloatOrDepthTexture=!1,i.isExternalTexture=!1),i.texture=t;const r=s!==(t?.uniqueId??-1);r&&this.updateId++,this.isDirty||(this.isDirty=r)}}Sm._Counter=0;class Cm{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,hf.CopyDst|hf.Indirect|hf.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=Cm._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){this._isDirty||(this._isDirty=t?.uniqueId!==this.buffers[e]?.uniqueId),this.buffers[e]=t}setIndirectData(e,t,i){t!==this._currentInstanceCount&&this.indirectDrawBuffer&&this._indirectDrawData&&(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}}Cm._Counter=0;class Em{constructor(){this.values={}}}class Am{static get Statistics(){return{totalCreated:Am.NumBindGroupsCreatedTotal,lastFrameCreated:Am.NumBindGroupsCreatedLastFrame,lookupLastFrame:Am.NumBindGroupsLookupLastFrame,noLookupLastFrame:Am.NumBindGroupsNoLookupLastFrame}}static ResetCache(){Am._Cache=new Em,Am.NumBindGroupsCreatedTotal=0,Am.NumBindGroupsCreatedLastFrame=0,Am.NumBindGroupsLookupLastFrame=0,Am.NumBindGroupsNoLookupLastFrame=0,Am._NumBindGroupsCreatedCurrentFrame=0,Am._NumBindGroupsLookupCurrentFrame=0,Am._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){Am.NumBindGroupsCreatedLastFrame=Am._NumBindGroupsCreatedCurrentFrame,Am.NumBindGroupsLookupLastFrame=Am._NumBindGroupsLookupCurrentFrame,Am.NumBindGroupsNoLookupLastFrame=Am._NumBindGroupsNoLookupCurrentFrame,Am._NumBindGroupsCreatedCurrentFrame=0,Am._NumBindGroupsLookupCurrentFrame=0,Am._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){let s,r=Am._Cache;const n=this.disabled||i.forceBindGroupCreation;if(!n){if(!t.isDirty(i.updateId)&&!i.isDirty)return Am._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const i of e.shaderProcessingContext.bufferNames){const e=t.buffers[i]?.uniqueId??0;let s=r.values[e];s||(s=new Em,r.values[e]=s),r=s}for(const t of e.shaderProcessingContext.samplerNames){const e=i.samplers[t]?.hashCode??0;let s=r.values[e];s||(s=new Em,r.values[e]=s),r=s}for(const t of e.shaderProcessingContext.textureNames){const e=i.textures[t]?.texture?.uniqueId??0;let s=r.values[e];s||(s=new Em,r.values[e]=s),r=s}s=r.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,s)return t.bindGroups=s,Am._NumBindGroupsLookupCurrentFrame++,s;s=[],t.bindGroups=s,n||(r.bindGroups=s),Am.NumBindGroupsCreatedTotal++,Am._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[i.textureState];for(let r=0;r"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=this._cacheSampler.getSampler(t,!1,e.hashCode,t.label)}else Ne.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.texture||n.storageTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){Ne.Error(`Trying to bind a null texture! entry=${JSON.stringify(n)}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||n.texture&&!t.view||n.storageTexture&&!t.viewForWriting)){Ne.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=n.storageTexture?t.viewForWriting:t.view}else Ne.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.externalTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){Ne.Error(`Trying to bind a null external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){Ne.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=this._device.importExternalTexture({source:t})}else Ne.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.buffer){const e=t.buffers[l];if(e){const t=e.underlyingResource;a[s].resource.buffer=t,a[s].resource.size=e.capacity}else Ne.Error(`Can't find buffer "${l}". entry=${JSON.stringify(n)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const l=o[r];s[r]=this._device.createBindGroup({layout:l,entries:a})}return s}}Am.NumBindGroupsCreatedTotal=0,Am.NumBindGroupsCreatedLastFrame=0,Am.NumBindGroupsLookupLastFrame=0,Am.NumBindGroupsNoLookupLastFrame=0,Am._Cache=new Em,Am._NumBindGroupsCreatedCurrentFrame=0,Am._NumBindGroupsLookupCurrentFrame=0,Am._NumBindGroupsNoLookupCurrentFrame=0;Bi.ShadersStoreWGSL.clearQuadVertexShader="uniform depthValue: f32;const pos=array(\nvec2f(-1.0,1.0),\nvec2f(1.0,1.0),\nvec2f(-1.0,-1.0),\nvec2f(1.0,-1.0)\n);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.position=vec4f(pos[input.vertexIndex],uniforms.depthValue,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";Bi.ShadersStoreWGSL.clearQuadPixelShader="uniform color: vec4f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;}\n";class Pm{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new xm(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"],void 0,void 0,void 0,void 0,void 0,void 0,di.WGSL)}clear(e,t,i,s,r=1){let n,o,a=null;const l=!!this._engine._currentRenderTarget;if(e)n=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t1?2**36:0)+h*2**37,o=this._keyTemp.join("_"),a=this._bundleCache[o],a)return a;n=this._device.createRenderBundleEncoder({label:"clearQuadRenderBundle",colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:Jf.GetSample(r)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!s&&!!this._depthTextureFormat&&Jf.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(s?255:0),this._cacheRenderPipeline.setStencilCompare(s?519:512),this._cacheRenderPipeline.setStencilPassOp(s?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const h=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,r),c=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),c.uniformBuffer.update();const u=l?this._engine._ubInvertY:this._engine._ubDontInvertY,d=c.uniformBuffer.getBuffer(),_=d.uniqueId+"-"+u.uniqueId;let p=this._bindGroups[_];if(!p){const e=c.bindGroupLayouts[0];p=this._bindGroups[_]=[],p.push(this._device.createBindGroup({label:`clearQuadBindGroup0-${_}`,layout:e[0],entries:[]})),Kf._SimplifiedKnownBindings||p.push(this._device.createBindGroup({label:`clearQuadBindGroup1-${_}`,layout:e[1],entries:[]})),p.push(this._device.createBindGroup({label:`clearQuadBindGroup${Kf._SimplifiedKnownBindings?1:2}-${_}`,layout:e[Kf._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:u.underlyingResource,size:u.capacity}},{binding:1,resource:{buffer:d.underlyingResource,size:d.capacity}}]}))}n.setPipeline(h);for(let e=0;e{const e=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,e}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==s)return null;throw e}))}async readValue(e=0){const t=this._getBuffer(e,1);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(cf.Read).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(cf.Read).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[1]-e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0})))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;const i=this._engine.frameId;this._measureDuration.stopPass(e).then((e=>{t._addDuration(i,null!==e&&e>0?e:0)}))}dispose(){this._measureDuration?.dispose()}}class km{constructor(e,t,i,s=2,r){this._count=s,this._querySet=new Lm(e,s,zf.Timestamp,t,i,!0,r)}start(e){e.writeTimestamp?.(this._querySet.querySet,0)}async stop(e){return e.writeTimestamp?.(this._querySet.querySet,1),e.writeTimestamp?this._querySet.readTwoValuesAndSubtract(0):0}startPass(e,t){if(t+3>this._count)throw new Error("WebGPUDurationMeasure: index out of range ("+t+")");e.timestampWrites={querySet:this._querySet.querySet,beginningOfPassWriteIndex:t+2,endOfPassWriteIndex:t+3}}async stopPass(e){return this._querySet.readTwoValuesAndSubtract(e+2)}dispose(){this._querySet.dispose()}}class Vm{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;const t=void 0!==this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,s=50,r=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=r,this._allocateNewIndices(s)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();const e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e})))}_allocateNewIndices(e){e=e??this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose),1e3)}dispose(){this._querySet?.dispose(),this._availableIndices.length=0}}class Um{async initTwgsl(e){if(!Um._Twgsl)return e=e||{},(e={...Um._TWgslDefaultOptions,...e}).twgsl?(Um._Twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await Ds.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(Um._Twgsl=await self.twgsl(Ds.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=Um._Twgsl.convertSpirV2WGSL(e,Um.DisableUniformityAnalysis||t);return Um.ShowWGSLShaderCode&&(Ne.Log(i),Ne.Log("***********************************************")),Um.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}Um._TWgslDefaultOptions={jsPath:`${Ds._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${Ds._DefaultCdnUrl}/twgsl/twgsl.wasm`},Um.ShowWGSLShaderCode=!1,Um.DisableUniformityAnalysis=!1,Um._Twgsl=null;class Gm{constructor(e,t,i){this._record=!1,this._play=!1,this._playBundleListIndex=0,this._allBundleLists=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._allBundleLists.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endRenderPass(e){if(!this._record&&!this._play)return!1;let t;if(this._record)t=this._bundleList.clone(),this._allBundleLists.push(t),this._bundleList.reset();else{if(this._playBundleListIndex>=this._allBundleLists.length)throw new Error(`Invalid playBundleListIndex! Your snapshot is no longer valid for the current frame, you should recreate a new one. playBundleListIndex=${this._playBundleListIndex}, allBundleLists.length=${this._allBundleLists.length}}`);t=this._allBundleLists[this._playBundleListIndex++]}return t.run(e),1===this._mode&&this._engine._reportDrawCall(t.numDrawCalls),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0}reset(){this.enabled=!1,this.enabled=!0}}Bi.ShadersStoreWGSL.postprocessVertexShader="attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class zm extends ym{constructor(e){super(e)}}const Wm={label:"TextureView_SwapChain_ResolveTarget",dimension:uf.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Hm={label:"TextureView_SwapChain",dimension:uf.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Xm=new Ae;class Ym extends ns{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return!!this._cacheSampler&&this._cacheSampler.disabled}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}areAllEffectsReady(){return!0}getFontOffset(e){return Zn(e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then((e=>!!e),(()=>!1)).catch((()=>!1)):Promise.resolve(!1)}static get IsSupported(){return Ne.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){return this.name+this.version}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get enableGPUTimingMeasurements(){return this._timestampQuery.enable}set enableGPUTimingMeasurements(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new Hu:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new Ym(e,t);return new Promise((e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then((()=>e(i)))}))}constructor(e,t={}){super(t.antialias??!0,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._timestampIndex=0,this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this.scenes=[],this._virtualScenes=new Array,this._commandBuffers=[null,null],this._currentRenderPass=null,this._mainRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._rttRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._pendingDebugCommands=[],this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this._snapshotRenderingMode=0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._performanceMonitor=new Qn,this._name="WebGPU",this._drawCalls=new wr,t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=t.enableGPUDebugMarkers??!1,Ne.Log(`Babylon.js v${oo.Version} - ${this.description} engine`),navigator.gpu?(t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,navigator&&navigator.userAgent&&this._setupMobileChecks(),this._sharedInit(this._renderingCanvas),this._shaderProcessor=new $f,this._shaderProcessorWGSL=new Zf):Ne.Error("WebGPU is not supported by your browser.")}initAsync(e,t){return this.uniqueId=Ym._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,this._initGlslang(e??this._options?.glslangOptions).then((e=>(this._glslang=e,this._tintWASM=Ym.UseTWGSL?new Um:null,this._tintWASM?this._tintWASM.initTwgsl(t??this._options?.twgslOptions).then((()=>navigator.gpu.requestAdapter(this._options))):navigator.gpu.requestAdapter(this._options)))).then((e=>{if(e){this._adapter=e,this._adapterSupportedExtensions=[],this._adapter.features?.forEach((e=>this._adapterSupportedExtensions.push(e))),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then((e=>{this._adapterInfo=e}));const t=this._options.deviceDescriptor??{},i=t?.requiredFeatures??(this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0);if(i){const e=i,s=[];for(const t of e)-1!==this._adapterSupportedExtensions.indexOf(t)&&s.push(t);t.requiredFeatures=s}if(this._options.setMaximumLimits&&!t.requiredLimits){t.requiredLimits={};for(const e in this._adapterSupportedLimits)"minSubgroupSize"!==e&&"maxSubgroupSize"!==e&&(t.requiredLimits[e]=this._adapterSupportedLimits[e])}return t.label=`BabylonWebGPUDevice${this.uniqueId}`,this._adapter.requestDevice(t)}throw"Could not retrieve a WebGPU adapter (adapter is null)."})).then((e=>{this._device=e,this._deviceEnabledExtensions=[],this._device.features?.forEach((e=>this._deviceEnabledExtensions.push(e))),this._deviceLimits=e.limits;let t=-1;this._device.addEventListener("uncapturederror",(e=>{++t{this._isDisposed||(this._contextWasLost=!0,Ne.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost((async()=>{const e=this.snapshotRenderingMode,t=this.snapshotRendering,i=this.disableCacheSamplers,s=this.disableCacheRenderPipelines,r=this.disableCacheBindGroups,n=this.enableGPUTimingMeasurements;await this.initAsync(this._glslangOptions??this._options?.glslangOptions,this._twgslOptions??this._options?.twgslOptions),this.snapshotRenderingMode=e,this.snapshotRendering=t,this.disableCacheSamplers=i,this.disableCacheRenderPipelines=s,this.disableCacheBindGroups=r,this.enableGPUTimingMeasurements=n,this._currentRenderPass=null})))}))})).then((()=>{this._bufferManager=new hm(this,this._device),this._textureHelper=new am(this,this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new _m(this._device),this._cacheBindGroups=new Am(this._device,this._cacheSampler,this),this._timestampQuery=new Bm(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new Vm(this,this._device,this._bufferManager):void 0,this._bundleList=new Fm(this._device),this._snapshotRendering=new Gm(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),hf.Uniform|hf.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),hf.Uniform|hf.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&void 0===this._count&&(this._count=0,Ne.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._initializeLimits(),this._emptyVertexBuffer=new er(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new xm(this._device,this._emptyVertexBuffer),this._depthCullingState=new Tm(this._cacheRenderPipeline),this._stencilStateComposer=new bm(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new Pm(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()})).catch((e=>{throw Ne.Error("A fatal error occurred during WebGPU creation/initialization."),e}))}_initGlslang(e){return e=e||{},(e={...Ym._GLSLslangDefaultOptions,...e}).glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?Ds.LoadBabylonScriptAsync(e.jsPath).then((()=>self.glslang(Ds.GetBabylonScriptURL(e.wasmPath)))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(af.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(af.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(af.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(af.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf(af.RG11B10UFloatRenderable)>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(af.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf(af.TimestampQuery)||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new em],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._setColorFormat(this._mainRenderPassWrapper)}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};const e=new Float32Array([this.getRenderHeight(!0)]);let t;if(this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e),this._options.antialias){const e={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:uf.E2d,format:this._options.swapChainFormat,usage:df.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(e),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:uf.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new Ae(0,0,0,1),loadOp:Uf.Clear,storeOp:Gf.Store}]}else t=[{view:void 0,clearValue:new Ae(0,0,0,1),loadOp:Uf.Clear,storeOp:Gf.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?ff.Depth24PlusStencil8:ff.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);const i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:uf.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:df.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const s={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:uf.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:Uf.Clear,depthStoreOp:Gf.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?Uf.Clear:void 0,stencilStoreOp:this.isStencilEnable?Gf.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:s}}_sharedInit(e){super._sharedInit(e),$n(this,e,this._creationOptions)}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:df.RenderAttachment|df.CopySrc,alphaMode:this.premultipliedAlpha?Wf.Premultiplied:Wf.Opaque})}resizeImageBitmap(e,t,i){return eo(this,e,t,i)}_createImageBitmapFromSource(e,t){return Jn(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&to(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&io()}enterPointerlock(){this._renderingCanvas&&so(this._renderingCanvas)}exitPointerlock(){ro()}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){xm.ResetCache(),Am.ResetCache();const t=e=>{for(const t of e){for(const e of t.meshes){const t=e.subMeshes;if(t)for(const e of t)e._drawWrappers=[]}for(const e of t.materials)e._materialContext?.reset()}};t(this.scenes),t(this._virtualScenes);const i=[];for(const e of this._uniformBuffers)e.name.indexOf("leftOver")<0&&i.push(e);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setSize(e,t,i=!1){return!!super.setSize(e,t,i)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0,r=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,n=i===di.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===di.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,o,i,s,r)}_compilePipelineStageDescriptor(e,t,i,s){this.onBeforeShaderCompilationObservable.notifyObservers(this);const r=e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,n=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,o="#version 450\n",a=s===di.GLSL?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),l=s===di.GLSL?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(a,l,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new Bp(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new Qf(e,this)}createMaterialContext(){return new Sm}createDrawContext(){return new Cm(this._bufferManager)}_preparePipelineContext(e,t,i,s,r,n,o,a){const l=e,h=l.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(Ne.Log(["defines",a]),Ne.Log(t),Ne.Log(i),Ne.Log("***********************************************")),l.sources={fragment:i,vertex:t,rawVertex:r,rawFragment:n},l.stages=s?this._compileRawPipelineStageDescriptor(t,i,h):this._compilePipelineStageDescriptor(t,i,a,h)}getAttributes(e,t){const i=new Array(t.length),s=e;for(let e=0;e0,n.is3D=l>0,n._cachedWrapU=0,n._cachedWrapV=0,n._useSRGBBuffer=r.useSRGBBuffer,n.label=r.label,this._internalTexturesCache.push(n),i||this._textureHelper.createGPUTextureForInternalTexture(n,o,a,h||1,r.creationFlags),n}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,_,p){return this._createTextureBase(e,t,i,s,r,n,o,((e,t,i,s,r,n,o,a)=>{const l=s;if(e.baseWidth=l.width,e.baseHeight=l.height,e.width=l.width,e.height=l.height,e.format=-1!==e.format?e.format:h??5,e.type=-1!==e.type?e.type:0,e._creationFlags=_??0,a(e.width,e.height,l,t,e,(()=>{})),e._hardwareTexture?.underlyingResource)n||o||this._generateMipmaps(e,this._uploadEncoder);else{const t=this._textureHelper.createGPUTextureForInternalTexture(e,l.width,l.height,void 0,_);Jf.IsImageBitmap(l)&&(this._textureHelper.updateTexture(l,e,l.width,l.height,e.depth,t.format,0,0,r,!1,0,0),n||o||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}),(()=>!1),a,l,h,c,u,d,p)}wrapWebGPUTexture(e){const t=new em(e),i=new ss(this,is.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers}_unpackFlipY(e){}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,s=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==s&&(e._cachedWrapR=s)}updateTextureDimensions(e,t,i,s=1){if(!e._hardwareTexture)return;if(e.width===t&&e.height===i&&e.depth===s)return;const r=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,s,r)}_setInternalTexture(e,t,i){if(i=i??e,this._currentEffect){const s=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),s&&s.autoBindSampler){const e=i+"Sampler";this._currentMaterialContext.setSampler(e,t)}}}createPrefilteredCubeTexture(e,t,i,s,r=null,n=null,o,a=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(r&&r(null));const t=e.texture;l?e.info.sphericalPolynomial&&(t._sphericalPolynomial=e.info.sphericalPolynomial):t._sphericalPolynomial=new j_,t._source=is.CubePrefiltered,r&&r(t)}),n,o,a,l,i,s)}setTexture(e,t,i,s){this._setTexture(e,i,!1,!1,s,s)}setTextureArray(e,t,i,s){for(let e=0;e{const o=()=>{n.mapAsync(cf.Read,0,i).then((()=>{const t=n.getMappedRange(0,i);let r=s;if(void 0===r)r=new Uint8Array(i),r.set(new Uint8Array(t));else{const e=r.constructor;r=new e(r.buffer),r.set(new e(t))}n.unmap(),this._bufferManager.releaseBuffer(n),e(r)}),(i=>{this.isDisposed?e(new Uint8Array):t(i)}))};r?(this.flushFramebuffer(),o()):this.onEndFrameObservable.addOnce((()=>{o()}))}))}setStorageBuffer(e,t){this._currentDrawContext?.setBuffer(e,t?.getBuffer()??null)}}Ym._GLSLslangDefaultOptions={jsPath:`${Ds._DefaultCdnUrl}/glslang/glslang.js`,wasmPath:`${Ds._DefaultCdnUrl}/glslang/glslang.wasm`},Ym._InstanceId=0,Ym.UseTWGSL=!0,Ym.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode===e&&(0===e&&!this._alphaState.alphaBlend||0!==e&&this._alphaState.alphaBlend)){if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.setDepthWrite(t),this._cacheRenderPipeline.setDepthWriteEnabled(t))}}else{switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,1),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,1),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(1,1,0,1),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(770,1,0,1),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(0,769,1,1),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(774,0,1,1),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(770,769,1,1),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(32769,32770,32771,32772),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(1,769,1,771),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,1),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(772,1,0,0),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(775,769,773,771),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,0),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(775,769,0,1),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,771),this._alphaState.alphaBlend=!0}t||(this.setDepthWrite(0===e),this._cacheRenderPipeline.setDepthWriteEnabled(0===e)),this._alphaMode=e,this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)}},Ym.prototype.setAlphaEquation=function(e){ns.prototype.setAlphaEquation.call(this,e),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};class Qm{getBindGroups(e,t,i){if(!i)throw new Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");if(0===this._bindGroups.length){const s=this._bindGroupEntries.length>0;for(const t in e){const r=e[t],n=i[t],o=n.group,a=n.binding,l=r.type,h=r.object;let c=r.indexInGroupEntries,u=this._bindGroupEntries[o];switch(u||(u=this._bindGroupEntries[o]=[]),l){case Wu.Sampler:{const e=h;void 0!==c&&s?u[c].resource=this._cacheSampler.getSampler(e):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:this._cacheSampler.getSampler(e)}));break}case Wu.Texture:case Wu.TextureWithoutSampler:{const e=h,t=e._texture._hardwareTexture;void 0!==c&&s?(l===Wu.Texture&&(u[c++].resource=this._cacheSampler.getSampler(e._texture)),u[c].resource=t.view):(r.indexInGroupEntries=u.length,l===Wu.Texture&&u.push({binding:a-1,resource:this._cacheSampler.getSampler(e._texture)}),u.push({binding:a,resource:t.view}));break}case Wu.StorageTexture:{const e=h,t=e._texture._hardwareTexture;t.textureAdditionalUsages&df.StorageBinding||Ne.Error(`computeDispatch: The texture (name=${e.name}, uniqueId=${e.uniqueId}) is not a storage texture!`,50),void 0!==c&&s?u[c].resource=t.viewForWriting:(r.indexInGroupEntries=u.length,u.push({binding:a,resource:t.viewForWriting}));break}case Wu.ExternalTexture:{const e=h.underlyingResource;void 0!==c&&s?u[c].resource=this._device.importExternalTexture({source:e}):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:this._device.importExternalTexture({source:e})}));break}case Wu.UniformBuffer:case Wu.StorageBuffer:case Wu.DataBuffer:{const e=l===Wu.DataBuffer?h:(Wu.UniformBuffer,h.getBuffer()),t=e.underlyingResource;void 0!==c&&s?(u[c].resource.buffer=t,u[c].resource.size=e.capacity):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:{buffer:t,offset:0,size:e.capacity}}));break}}}for(let e=0;e0&&d.dispatchWorkgroups(s,r,n),d.end(),h&&(this._timestampQuery.endPass(this._timestampIndex,h),this._timestampIndex+=2)},Ym.prototype.releaseComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e].getPipelineContext();this._deleteComputePipelineContext(t)}this._compiledComputeEffects={}},Ym.prototype._prepareComputePipelineContext=function(e,t,i,s,r){const n=e;this.dbgShowShaderCode&&(Ne.Log(s),Ne.Log(t)),n.sources={compute:t,rawCompute:i},n.stage=this._createComputePipelineStageDescriptor(t,s,r)},Ym.prototype._releaseComputeEffect=function(e){this._compiledComputeEffects[e._key]&&(delete this._compiledComputeEffects[e._key],this._deleteComputePipelineContext(e.getPipelineContext()))},Ym.prototype._rebuildComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}},Ym.prototype._executeWhenComputeStateIsCompiled=function(e,t){e.stage.module.getCompilationInfo().then((e=>{const i={numErrors:0,messages:[]};for(const t of e.messages)"error"===t.type&&i.numErrors++,i.messages.push({type:t.type,text:t.message,line:t.lineNum,column:t.linePos,length:t.length,offset:t.offset});t(i)}))},Ym.prototype._deleteComputePipelineContext=function(e){e&&e.dispose()},Ym.prototype._createComputePipelineStageDescriptor=function(e,t,i){return t=t?"//"+t.split("\n").join("\n//")+"\n":"",{module:this._device.createShaderModule({code:t+e}),entryPoint:i}},Ym.prototype._createDepthStencilCubeTexture=function(e,t){const i=new ss(this,t.generateStencil?is.DepthStencil:is.Depth);i.isCube=!0,i.label=t.label;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t};i.format=s.depthTextureFormat,this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction,s.samples),this._textureHelper.createGPUTextureForInternalTexture(i);const r=i._hardwareTexture;return i.type=Jf.GetTextureTypeFromFormat(r.format),this._internalTexturesCache.push(i),i},Ym.prototype.createCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d=!1){return this.createCubeTextureBase(e,t,i,!!s,r,n,o,a,l,h,c,u,null,((e,t)=>{const i=t,n=i[0].width,a=n;this._setCubeMapTextureParams(e,!s),e.format=o??-1;const l=this._textureHelper.createGPUTextureForInternalTexture(e,n,a);this._textureHelper.updateCubeTextures(i,l.underlyingResource,n,a,l.format,!1,!1,0,0),s||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),r&&r()}),!!d)},Ym.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},Ym.prototype.generateMipMapsForCubemap=function(e){if(e.generateMipMaps){const t=e._hardwareTexture?.underlyingResource;t||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e)}},Ym.prototype._debugPushGroup=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.pushDebugGroup(e):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e]))},Ym.prototype._debugPopGroup=function(e){this._options.enableGPUDebugMarkers&&(0===e||1===e?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))},Ym.prototype._debugInsertMarker=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.insertDebugMarker(e):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e]))},Ym.prototype._debugFlushPendingCommands=function(){for(let e=0;e{const i=d.width,n=o(e);if(n){if(a){const e=4===s,t=a(n),o=d._hardwareTexture,l=[0,1,2,3,4,5];for(let s=0;s>s,a=[];for(let i=0;i<6;i++){let o=t[s][l[i]];e&&(o=$m(o,n,n,r)),a.push(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}this._textureHelper.updateCubeTextures(a,o.underlyingResource,n,n,o.format,u,!1,0,0)}}else this.updateRawCubeTexture(d,n,s,r,u);d.isReady=!0,t?.removePendingData(d),l&&l()}};return this._loadFile(e,(e=>{_(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)})),d},Ym.prototype.createRawTexture3D=function(e,t,i,s,r,n,o,a,l=null,h=0,c=0){const u=is.Raw3D,d=new ss(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=s,d.width=t,d.height=i,d.depth=s,d.format=r,d.type=h,d.generateMipMaps=n,d.samplingMode=a,d.is3D=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,void 0,c),this.updateRawTexture3D(d,e,r,o,l,h),this._internalTexturesCache.push(d),d},Ym.prototype.updateRawTexture3D=function(e,t,i,s,r=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r),t){const r=e._hardwareTexture;4===i&&(t=$m(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,r.format,0,0,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Ym.prototype.createRawTexture2DArray=function(e,t,i,s,r,n,o,a,l=null,h=0,c=0){const u=is.Raw2DArray,d=new ss(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=s,d.width=t,d.height=i,d.depth=s,d.format=r,d.type=h,d.generateMipMaps=n,d.samplingMode=a,d.is2DArray=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,s,c),this.updateRawTexture2DArray(d,e,r,o,l,h),this._internalTexturesCache.push(d),d},Ym.prototype.updateRawTexture2DArray=function(e,t,i,s,r=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r),t){const r=e._hardwareTexture;4===i&&(t=$m(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,r.format,0,0,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Ym.prototype._readTexturePixels=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){const c=e._hardwareTexture;return o&&this.flushFramebuffer(),this._textureHelper.readPixels(c.underlyingResource,l,h,t,i,c.format,s,r,n,a)},Ym.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};class qm extends Bl{constructor(e,t,i,s,r){super(e,t,i,s,r),s.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new Hu)}}Ym.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const s=new qm(e,t,i,this);return this._renderTargetWrapperCache.push(s),s},Ym.prototype.createRenderTargetTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),s={};void 0!==t&&"object"==typeof t?(s.generateMipMaps=t.generateMipMaps,s.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,s.generateStencilBuffer=s.generateDepthBuffer&&t.generateStencilBuffer,s.samplingMode=void 0===t.samplingMode?3:t.samplingMode,s.creationFlags=t.creationFlags??0,s.noColorAttachment=!!t.noColorAttachment,s.samples=t.samples,s.label=t.label):(s.generateMipMaps=t,s.generateDepthBuffer=!0,s.generateStencilBuffer=!1,s.samplingMode=3,s.creationFlags=0,s.noColorAttachment=!1);const r=s.noColorAttachment?null:this._createInternalTexture(e,t,!0,is.RenderTarget);return i.label=s.label??"RenderTargetWrapper",i._samples=s.samples??1,i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer,i.setTextures(r),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,!1,i._generateStencilBuffer,i.samples,s.generateStencilBuffer?13:14,s.label?s.label+"-DepthStencil":void 0),r&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r,void 0,void 0,void 0,s.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!1)),i},Ym.prototype._createDepthStencilTexture=function(e,t){const i=new ss(this,t.generateStencil?is.DepthStencil:is.Depth);i.label=t.label;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t};i.format=s.depthTextureFormat,this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction,s.samples),this._textureHelper.createGPUTextureForInternalTexture(i);const r=i._hardwareTexture;return i.type=Jf.GetTextureTypeFromFormat(r.format),this._internalTexturesCache.push(i),i},Ym.prototype._setupDepthStencilTexture=function(e,t,i,s,r,n=1){const o=t.width||t,a=t.height||t,l=t.layers||0,h=t.depth||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.is3D=h>0,e.depth=l||h,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=1,e._comparisonFunction=r,e._cachedWrapU=0,e._cachedWrapV=0},Ym.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t?(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t,t):t},Ym.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,i.label=s.label??"RenderTargetWrapper",i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer;const r=new ss(this,is.RenderTarget);return r.width=e,r.height=e,r.depth=0,r.isReady=!0,r.isCube=!0,r.samples=s.samples,r.generateMipMaps=s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,r.format=s.format,this._internalTexturesCache.push(r),i.setTextures(r),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,void 0===s.samplingMode||2===s.samplingMode||2===s.samplingMode||3===s.samplingMode||3===s.samplingMode||5===s.samplingMode||6===s.samplingMode||7===s.samplingMode||11===s.samplingMode,i._generateStencilBuffer,i.samples),t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r),t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!1),i},Ym.prototype.setDepthStencilTexture=function(e,t,i,s){i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,s):this._setTexture(e,null,void 0,void 0,s)},Ym.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;e._hardwareTexture?.underlyingResource||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),function(e){return!(!e||void 0===e.underlyingResource)}(t)?(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0):t&&this.createImageBitmap(t).then((t=>{this._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,s.format,0,0,!i,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0})).catch((()=>{e.isReady=!0}))};class Zm{static async CreateAsync(e,t){return await Ym.IsSupportedAsync?Ym.CreateAsync(e,t):oo.IsSupported?new oo(e,void 0,t):new L_(t)}}class Jm{}Jm.COPY=1,Jm.CUT=2,Jm.PASTE=3;class eg{constructor(e,t){this.type=e,this.event=t}static GetTypeFromCharacter(e){switch(e){case 67:return Jm.COPY;case 86:return Jm.PASTE;case 88:return Jm.CUT;default:return-1}}}class tg extends sd{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=Ee.Gray(),i=Ju.DefaultUtilityLayer,s=null,r=1,n=Ee.Yellow(),o=Ee.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new K,this.uniformScaling=!1,this.sensitivity=1,this.dragScale=1,this.incrementalSnap=!1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._tmpVector=new _e(0,0,0),this._incrementalStartupValue=_e.Zero(),this._parent=s,this._coloredMaterial=new cu("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ee(.1,.1,.1)),this._hoverMaterial=new cu("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new cu("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4,this._gizmoMesh=new ha("axis",i.utilityLayerScene);const{arrowMesh:a,arrowTail:l}=this._createGizmoMesh(this._gizmoMesh,r),h=this._createGizmoMesh(this._gizmoMesh,r+4,!0);this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,sd.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3);const c=a.position.clone(),u=l.position.clone(),d=l.scaling.clone(),_=e=>{const t=e*(3/this._rootMesh.scaling.length())*6;a.position.z+=t/3.5,l.scaling.y+=t,this.dragScale=l.scaling.y,l.position.z=a.position.z/2},p=()=>{a.position.set(c.x,c.y,c.z),l.position.set(u.x,u.y,u.z),l.scaling.set(d.x,d.y,d.z),this.dragScale=l.scaling.y,this._dragging=!1};this.dragBehavior=new Xa({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior);let f=0,m=0;const g={snapDistance:0};this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const i=this.sensitivity*t.dragDistance*(3*this.scaleRatio/this._rootMesh.scaling.length()),s=this._tmpVector;let r=!1,n=0;if(this.uniformScaling?s.setAll(.57735):s.copyFrom(e),0==this.snapDistance)s.scaleToRef(i,s);else{f+=i,m+=i;const e=this.incrementalSnap?m:f;Math.abs(e)>this.snapDistance?(n=Math.floor(Math.abs(e)/this.snapDistance),e<0&&(n*=-1),f%=this.snapDistance,s.scaleToRef(this.snapDistance*n,s),r=!0):s.scaleInPlace(0)}s.addInPlaceFromFloats(1,1,1),s.x=Math.abs(s.x)0&&this.incrementalSnap?(this.attachedNode.getWorldMatrix().decompose(void 0,ve.Quaternion[0],ve.Vector3[2],sd.PreserveScaling?o:void 0),s.addInPlace(this._incrementalStartupValue),s.addInPlaceFromFloats(-1,-1,-1),s.x=Math.abs(s.x)*(this._incrementalStartupValue.x>0?1:-1),s.y=Math.abs(s.y)*(this._incrementalStartupValue.y>0?1:-1),s.z=Math.abs(s.z)*(this._incrementalStartupValue.z>0?1:-1),me.ComposeToRef(s,ve.Quaternion[0],ve.Vector3[2],ve.Matrix[1])):(me.ScalingToRef(s.x,s.y,s.z,ve.Matrix[2]),ve.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(),ve.Matrix[1])),ve.Matrix[1].decompose(ve.Vector3[1],void 0,void 0,sd.PreserveScaling?o:void 0);const a=1e5;Math.abs(ve.Vector3[1].x){this._dragging=!0;const e=this.attachedNode._isMesh?this.attachedNode:void 0;this.attachedNode?.getWorldMatrix().decompose(this._incrementalStartupValue,void 0,void 0,sd.PreserveScaling?e:void 0),f=0,m=0})),this.dragBehavior.onDragObservable.add((e=>_(e.dragDistance))),this.dragBehavior.onDragEndObservable.add(p),s?.uniformScaleGizmo?.dragBehavior?.onDragObservable?.add((e=>_(e.delta.y))),s?.uniformScaleGizmo?.dragBehavior?.onDragEndObservable?.add(p);const v={gizmoMeshes:[a,l],colliderMeshes:[h.arrowMesh,h.arrowTail],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,v),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(this._customMeshSet)return;let t=this._parent?.getAxisCache(this._gizmoMesh);if(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),t=this._parent?.getAxisCache(this._rootMesh),this._isHovered||(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh))),!this._parent){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(v.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(v.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}));const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes())}_createGizmoMesh(e,t,i=!1){const s=cd("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),r=$u("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return s.scaling.scaleInPlace(.1),s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,s.position.z+=.3,r.material=this._coloredMaterial,r.position.z+=.1375,r.rotation.x=Math.PI/2,i&&(s.visibility=0,r.visibility=0),e.addChild(s),e.addChild(r),{arrowMesh:s,arrowTail:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}setCustomMesh(e,t=!1){super.setCustomMesh(e),t&&(this._rootMesh.getChildMeshes().forEach((e=>{e.material=this._coloredMaterial,e.color&&(e.color=this._coloredMaterial.diffuseColor)})),this._customMeshSet=!1)}}tg.MinimumAbsoluteScale=J;class ig extends sd{set axisFactor(e){this._axisFactor=e;const t=this._scaleBoxesParent.getChildMeshes();let i=0;for(let e=0;e<3;e++)for(let s=0;s<3;s++)for(let r=0;r<3;r++){const n=(1===e?1:0)+(1===s?1:0)+(1===r?1:0);if(1!==n&&3!==n){if(t[i]){const n=new _e(e-1,s-1,r-1);n.multiplyInPlace(this._axisFactor),t[i].setEnabled(n.lengthSquared()>J)}i++}}}get axisFactor(){return this._axisFactor}set scaleDragSpeed(e){this._scaleDragSpeed=e}get scaleDragSpeed(){return this._scaleDragSpeed}get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverColoredMaterial}get pointerDragBehavior(){return this._pointerDragBehavior}get isDragging(){return this._dragging||this._pointerDragBehavior.dragging}setColor(e){this._coloredMaterial.emissiveColor=e,this._hoverColoredMaterial.emissiveColor=e.clone().add(new Ee(.3,.3,.3)),this._lineBoundingBox.getChildren().forEach((t=>{t.color&&(t.color=e)}))}constructor(e=Ee.Gray(),t=Ju.DefaultKeepDepthUtilityLayer){super(t),this._boundingDimensions=new _e(1,1,1),this._renderObserver=null,this._pointerObserver=null,this._scaleDragSpeed=.2,this._rotateSpheresDragBehaviors=[],this._scaleBoxesDragBehaviors=[],this._dragging=!1,this._tmpQuaternion=new fe,this._tmpVector=new _e(0,0,0),this._tmpRotationMatrix=new me,this._incrementalStartupValue=_e.Zero(),this._incrementalAnchorStartupValue=_e.Zero(),this.ignoreChildren=!1,this.includeChildPredicate=null,this.rotationSphereSize=.1,this.scaleBoxSize=.1,this.fixedDragMeshScreenSize=!1,this.fixedDragMeshBoundsSize=!1,this.fixedDragMeshScreenSizeDistanceFactor=10,this.scalingSnapDistance=0,this.rotationSnapDistance=0,this.onDragStartObservable=new K,this.onScaleBoxDragObservable=new K,this.onScaleBoxDragEndObservable=new K,this.onRotationSphereDragObservable=new K,this.onRotationSphereDragEndObservable=new K,this.scalePivot=null,this._axisFactor=new _e(1,1,1),this.incrementalSnap=!1,this._existingMeshScale=new _e,this._dragMesh=null,this._pointerDragBehavior=new Xa,this.updateScale=!1,this._anchorMesh=new _o("anchor",t.utilityLayerScene),this._coloredMaterial=new cu("",t.utilityLayerScene),this._coloredMaterial.disableLighting=!0,this._hoverColoredMaterial=new cu("",t.utilityLayerScene),this._hoverColoredMaterial.disableLighting=!0,this._lineBoundingBox=new _o("",t.utilityLayerScene),this._lineBoundingBox.rotationQuaternion=new fe;const i=[];i.push(Ud("lines",{points:[new _e(0,0,0),new _e(this._boundingDimensions.x,0,0)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(0,0,0),new _e(0,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(0,0,0),new _e(0,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(this._boundingDimensions.x,0,0),new _e(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(this._boundingDimensions.x,0,0),new _e(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(0,this._boundingDimensions.y,0),new _e(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(0,this._boundingDimensions.y,0),new _e(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(0,0,this._boundingDimensions.z),new _e(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(0,0,this._boundingDimensions.z),new _e(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new _e(0,this._boundingDimensions.y,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new _e(this._boundingDimensions.x,0,this._boundingDimensions.z)]},t.utilityLayerScene)),i.push(Ud("lines",{points:[new _e(this._boundingDimensions.x,this._boundingDimensions.y,this._boundingDimensions.z),new _e(this._boundingDimensions.x,this._boundingDimensions.y,0)]},t.utilityLayerScene)),i.forEach((t=>{t.color=e,t.position.addInPlace(new _e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),t.isPickable=!1,this._lineBoundingBox.addChild(t)})),this._rootMesh.addChild(this._lineBoundingBox),this.setColor(e),this._rotateSpheresParent=new _o("",t.utilityLayerScene),this._rotateSpheresParent.rotationQuaternion=new fe;for(let e=0;e<12;e++){const i=_d("",{diameter:1},t.utilityLayerScene);i.rotationQuaternion=new fe,i.material=this._coloredMaterial,i.isNearGrabbable=!0;const s=new Xa({});s.moveAttached=!1,s.updateDragPlane=!1,i.addBehavior(s);const r=new _e(1,0,0);let n=0,o=0;s.onDragStartObservable.add((()=>{r.copyFrom(i.forward),n=0,o=0})),s.onDragObservable.add((t=>{if(this.onRotationSphereDragObservable.notifyObservers({}),this.attachedMesh){const i=this.attachedMesh.parent;if(i&&i.scaling&&i.scaling.isNonUniformWithinEpsilon(.001))return void Ne.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");Ga._RemoveAndStorePivotPoint(this.attachedMesh);const s=r,a=t.dragPlaneNormal.scale(_e.Dot(t.dragPlaneNormal,s)),l=s.subtract(a).normalizeToNew();let h=_e.Dot(l,t.delta)<0?Math.abs(t.delta.length()):-Math.abs(t.delta.length());if(h=h/this._boundingDimensions.length()*this._anchorMesh.scaling.length(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=fe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=fe.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),n+=h,Math.abs(n)<=2*Math.PI){if(this.rotationSnapDistance>0){const e=Math.floor(Math.abs(n)/this.rotationSnapDistance)*(n<0?-1:1),t=this.rotationSnapDistance*e;h=t-o,o=t}e>=8?fe.RotationYawPitchRollToRef(0,0,h,this._tmpQuaternion):e>=4?fe.RotationYawPitchRollToRef(h,0,0,this._tmpQuaternion):fe.RotationYawPitchRollToRef(0,h,0,this._tmpQuaternion),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.copyFrom(this.attachedMesh.position),this._anchorMesh.addChild(this.attachedMesh),this._anchorMesh.getScene().useRightHandedSystem&&this._tmpQuaternion.conjugateInPlace(),this._tmpQuaternion.normalize(),this._anchorMesh.rotationQuaternion.multiplyToRef(this._tmpQuaternion,this._anchorMesh.rotationQuaternion),this._anchorMesh.rotationQuaternion.normalize(),this._anchorMesh.removeChild(this.attachedMesh),this.attachedMesh.setParent(i)}this.updateBoundingBox(),Ga._RestorePivotPoint(this.attachedMesh)}this._updateDummy()})),s.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({}),this._dragging=!0,this._selectNode(i)})),s.onDragEndObservable.add((e=>{this.onRotationSphereDragEndObservable.notifyObservers({}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(e.pointerInfo,i)})),this._rotateSpheresDragBehaviors.push(s),this._rotateSpheresParent.addChild(i)}this._rootMesh.addChild(this._rotateSpheresParent),this._scaleBoxesParent=new _o("",t.utilityLayerScene),this._scaleBoxesParent.rotationQuaternion=new fe;for(let e=0;e<3;e++)for(let i=0;i<3;i++)for(let s=0;s<3;s++){const r=(1===e?1:0)+(1===i?1:0)+(1===s?1:0);if(1===r||3===r)continue;const n=cd("",{size:1},t.utilityLayerScene);n.material=this._coloredMaterial,n._internalMetadata=2===r,n.isNearGrabbable=!0;const o=new _e(e-1,i-1,s-1).normalize(),a=new Xa({dragAxis:o});a.updateDragPlane=!1,a.moveAttached=!1;let l=0,h=0;n.addBehavior(a),a.onDragObservable.add((e=>{if(this.onScaleBoxDragObservable.notifyObservers({}),this.attachedMesh){const t=this.attachedMesh.parent;if(t&&t.scaling&&t.scaling.isNonUniformWithinEpsilon(.001))return void Ne.Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");Ga._RemoveAndStorePivotPoint(this.attachedMesh);let i=e.dragDistance/this._boundingDimensions.length()*this._anchorMesh.scaling.length();if(l+=i,this.scalingSnapDistance>0){const e=Math.floor(Math.abs(l)/this.scalingSnapDistance)*(l<0?-1:1),t=this.scalingSnapDistance*e;i=t-h,h=t}const s=new _e(i,i,i),a=new _e(h,h,h);2===r&&(s.x*=Math.abs(o.x),s.y*=Math.abs(o.y),s.z*=Math.abs(o.z)),s.scaleInPlace(this._scaleDragSpeed),s.multiplyInPlace(this._axisFactor),a.scaleInPlace(this._scaleDragSpeed),a.multiplyInPlace(this._axisFactor),a.addInPlace(this._incrementalStartupValue),this.updateBoundingBox(),this.scalePivot?(this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(this._tmpRotationMatrix),this._boundingDimensions.scaleToRef(.5,this._tmpVector),_e.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this._boundingDimensions.multiplyToRef(this.scalePivot,this._tmpVector),_e.TransformCoordinatesToRef(this._tmpVector,this._tmpRotationMatrix,this._tmpVector),this._anchorMesh.position.addInPlace(this._tmpVector)):(n.absolutePosition.subtractToRef(this._anchorMesh.position,this._tmpVector),this._anchorMesh.position.subtractInPlace(this._tmpVector),this.attachedMesh.isUsingPivotMatrix()&&this._anchorMesh.position.subtractInPlace(this.attachedMesh.getPivotPoint())),this._anchorMesh.addChild(this.attachedMesh),this.incrementalSnap?(a.x/=Math.abs(this._incrementalStartupValue.x){this.onDragStartObservable.notifyObservers({}),this._dragging=!0,this._selectNode(n),l=0,h=0,this._incrementalStartupValue.copyFrom(this.attachedMesh.scaling),this._incrementalAnchorStartupValue.copyFrom(this._anchorMesh.scaling)})),a.onDragEndObservable.add((e=>{this.onScaleBoxDragEndObservable.notifyObservers({}),this._dragging=!1,this._selectNode(null),this._updateDummy(),this._unhoverMeshOnTouchUp(e.pointerInfo,n)})),this._scaleBoxesParent.addChild(n),this._scaleBoxesDragBehaviors.push(a)}this._rootMesh.addChild(this._scaleBoxesParent);const s=[];this._pointerObserver=t.utilityLayerScene.onPointerObservable.add((e=>{s[e.event.pointerId]?e.pickInfo&&e.pickInfo.pickedMesh!=s[e.event.pointerId]&&(s[e.event.pointerId].material=this._coloredMaterial,delete s[e.event.pointerId],this._isHovered=!1):this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((t=>{e.pickInfo&&e.pickInfo.pickedMesh==t&&(s[e.event.pointerId]=t,t.material=this._hoverColoredMaterial,this._isHovered=!0)}))})),this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add((()=>{this.attachedMesh&&!this._existingMeshScale.equals(this.attachedMesh.scaling)?this.updateBoundingBox():(this.fixedDragMeshScreenSize||this.fixedDragMeshBoundsSize)&&(this._updateRotationSpheres(),this._updateScaleBoxes()),this._dragMesh&&this.attachedMesh&&this._pointerDragBehavior.dragging&&(this._lineBoundingBox.position.rotateByQuaternionToRef(this._rootMesh.rotationQuaternion,this._tmpVector),this.attachedMesh.setAbsolutePosition(this._dragMesh.position.add(this._tmpVector.scale(-1))))})),this.updateBoundingBox()}_attachedNodeChanged(e){if(e){this._anchorMesh.scaling.setAll(1),Ga._RemoveAndStorePivotPoint(e);const t=e.parent;this._anchorMesh.addChild(e),this._anchorMesh.removeChild(e),e.setParent(t),Ga._RestorePivotPoint(e),this.updateBoundingBox(),e.getChildMeshes(!1).forEach((e=>{e.markAsDirty("scaling")})),this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce((()=>{this._updateDummy()}))}}_selectNode(e){this._rotateSpheresParent.getChildMeshes().concat(this._scaleBoxesParent.getChildMeshes()).forEach((t=>{t.isVisible=!e||t==e}))}_unhoverMeshOnTouchUp(e,t){e?.event instanceof PointerEvent&&"touch"===e?.event.pointerType&&(t.material=this._coloredMaterial)}getScaleBoxes(){return this._scaleBoxesParent.getChildMeshes()}updateBoundingBox(){if(this.attachedMesh){Ga._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=fe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._anchorMesh.rotationQuaternion||(this._anchorMesh.rotationQuaternion=fe.RotationYawPitchRoll(this._anchorMesh.rotation.y,this._anchorMesh.rotation.x,this._anchorMesh.rotation.z)),this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);const t=this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren,this.includeChildPredicate);t.max.subtractToRef(t.min,this._boundingDimensions),this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions),this._lineBoundingBox.position.set((t.max.x+t.min.x)/2,(t.max.y+t.min.y)/2,(t.max.z+t.min.z)/2),this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position),this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position),this._lineBoundingBox.computeWorldMatrix(),this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),this.attachedMesh.setParent(e)}this._updateRotationSpheres(),this._updateScaleBoxes(),this.attachedMesh&&(this._existingMeshScale.copyFrom(this.attachedMesh.scaling),Ga._RestorePivotPoint(this.attachedMesh))}_updateRotationSpheres(){const e=this._rotateSpheresParent.getChildMeshes();for(let t=0;t<3;t++)for(let i=0;i<2;i++)for(let s=0;s<2;s++){const r=4*t+2*i+s;if(0==t&&(e[r].position.set(this._boundingDimensions.x/2,this._boundingDimensions.y*i,this._boundingDimensions.z*s),e[r].position.addInPlace(new _e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(_e.Cross(e[r].position.normalizeToNew(),_e.Right()).normalizeToNew().add(e[r].position))),1==t&&(e[r].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y/2,this._boundingDimensions.z*s),e[r].position.addInPlace(new _e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(_e.Cross(e[r].position.normalizeToNew(),_e.Up()).normalizeToNew().add(e[r].position))),2==t&&(e[r].position.set(this._boundingDimensions.x*i,this._boundingDimensions.y*s,this._boundingDimensions.z/2),e[r].position.addInPlace(new _e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),e[r].lookAt(_e.Cross(e[r].position.normalizeToNew(),_e.Forward()).normalizeToNew().add(e[r].position))),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[r].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position,this._tmpVector);const t=this.rotationSphereSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[r].scaling.set(t,t,t)}else this.fixedDragMeshBoundsSize?e[r].scaling.set(this.rotationSphereSize*this._boundingDimensions.x,this.rotationSphereSize*this._boundingDimensions.y,this.rotationSphereSize*this._boundingDimensions.z):e[r].scaling.set(this.rotationSphereSize,this.rotationSphereSize,this.rotationSphereSize)}}_updateScaleBoxes(){const e=this._scaleBoxesParent.getChildMeshes();let t=0;for(let i=0;i<3;i++)for(let s=0;s<3;s++)for(let r=0;r<3;r++){const n=(1===i?1:0)+(1===s?1:0)+(1===r?1:0);if(1!==n&&3!==n){if(e[t])if(e[t].position.set(this._boundingDimensions.x*(i/2),this._boundingDimensions.y*(s/2),this._boundingDimensions.z*(r/2)),e[t].position.addInPlace(new _e(-this._boundingDimensions.x/2,-this._boundingDimensions.y/2,-this._boundingDimensions.z/2)),this.fixedDragMeshScreenSize&&this.gizmoLayer.utilityLayerScene.activeCamera){e[t].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.globalPosition,this._tmpVector);const i=this.scaleBoxSize*this._tmpVector.length()/this.fixedDragMeshScreenSizeDistanceFactor;e[t].scaling.set(i,i,i)}else this.fixedDragMeshBoundsSize?e[t].scaling.set(this.scaleBoxSize*this._boundingDimensions.x,this.scaleBoxSize*this._boundingDimensions.y,this.scaleBoxSize*this._boundingDimensions.z):e[t].scaling.set(this.scaleBoxSize,this.scaleBoxSize,this.scaleBoxSize);t++}}}setEnabledRotationAxis(e){this._rotateSpheresParent.getChildMeshes().forEach(((t,i)=>{i<4?t.setEnabled(-1!=e.indexOf("x")):i<8?t.setEnabled(-1!=e.indexOf("y")):t.setEnabled(-1!=e.indexOf("z"))}))}setEnabledScaling(e,t=!1){this._scaleBoxesParent.getChildMeshes().forEach((i=>{let s=e;t&&!0===i._internalMetadata&&(s=!1),i.setEnabled(s)}))}_updateDummy(){this._dragMesh&&(this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition()),this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling),this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion))}enableDragBehavior(){this._dragMesh=cd("dummy",{size:1},this.gizmoLayer.utilityLayerScene),this._dragMesh.visibility=0,this._dragMesh.rotationQuaternion=new fe,this._pointerDragBehavior.useObjectOrientationForDragging=!1,this._dragMesh.addBehavior(this._pointerDragBehavior)}releaseDrag(){this._scaleBoxesDragBehaviors.forEach((e=>{e.releaseDrag()})),this._rotateSpheresDragBehaviors.forEach((e=>{e.releaseDrag()})),this._pointerDragBehavior.releaseDrag()}dispose(){this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver),this._lineBoundingBox.dispose(),this._rotateSpheresParent.dispose(),this._scaleBoxesParent.dispose(),this._dragMesh&&this._dragMesh.dispose(),this._scaleBoxesDragBehaviors.length=0,this._rotateSpheresDragBehaviors.length=0,super.dispose()}static MakeNotPickableAndWrapInBoundingBox(e){const t=e=>{e.isPickable=!1,e.getChildMeshes().forEach((e=>{t(e)}))};t(e),e.rotationQuaternion||(e.rotationQuaternion=fe.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z));const i=e.position.clone(),s=e.rotationQuaternion.clone();e.rotationQuaternion.set(0,0,0,1),e.position.set(0,0,0);const r=cd("box",{size:1},e.getScene()),n=e.getHierarchyBoundingVectors();return n.max.subtractToRef(n.min,r.scaling),0===r.scaling.y&&(r.scaling.y=J),0===r.scaling.x&&(r.scaling.x=J),0===r.scaling.z&&(r.scaling.z=J),r.position.set((n.max.x+n.min.x)/2,(n.max.y+n.min.y)/2,(n.max.z+n.min.z)/2),e.addChild(r),e.rotationQuaternion.copyFrom(s),e.position.copyFrom(i),e.removeChild(r),r.addChild(e),r.visibility=0,r}setCustomMesh(){Ne.Error("Custom meshes are not supported on this gizmo")}}class sg extends sd{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}set rotationColor(e){this._rotationShaderMaterial.setColor3("rotationColor",e)}get disableMaterial(){return this._disableMaterial}constructor(e,t=Ee.Gray(),i=Ju.DefaultUtilityLayer,s=32,r=null,n=!1,o=1,a=Ee.Yellow(),l=Ee.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new K,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new _e,this._parent=r,this._coloredMaterial=new cu("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ee(.1,.1,.1)),this._hoverMaterial=new cu("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a,this._hoverMaterial.specularColor=a,this._disableMaterial=new cu("",i.utilityLayerScene),this._disableMaterial.diffuseColor=l,this._disableMaterial.alpha=.4,this._gizmoMesh=new ha("",i.utilityLayerScene);const{rotationMesh:h,collider:c}=this._createGizmoMesh(this._gizmoMesh,o,s);this._rotationDisplayPlane=Wa("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),$i.ShadersStore.rotationGizmoVertexShader=sg._RotationGizmoVertexShader,$i.ShadersStore.rotationGizmoFragmentShader=sg._RotationGizmoFragmentShader,this._rotationShaderMaterial=new Nd("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles","rotationColor"]}),this._rotationShaderMaterial.backFaceCulling=!1,this.rotationColor=a,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,sd.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new Xa({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=sg.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);const u=new _e,d=new me,_=new _e;let p=new _e;this.dragBehavior.onDragStartObservable.add((e=>{this.attachedNode&&(u.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(d),_e.TransformCoordinatesToRef(e.dragPlanePoint,d,u),this._angles.x=Math.atan2(u.y,u.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,u.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)}));const f={snapDistance:0};let m=0;const g=new me,v=new fe;this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const s=new _e(1,1,1),r=new fe(0,0,0,1),n=new _e(0,0,0);if(this.attachedNode.getWorldMatrix().decompose(s,r,n),!(Math.abs(Math.abs(s.x)-Math.abs(s.y))<=J&&Math.abs(Math.abs(s.x)-Math.abs(s.z))<=J)&&this.updateGizmoRotationToMatchAttachedMesh)return void Ne.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");r.normalize();const o=this.updateGizmoPositionToMatchAttachedMesh?n:this._rootMesh.absolutePosition,a=t.dragPlanePoint.subtract(o).normalize(),l=u.subtract(o).normalize(),h=_e.Cross(a,l),c=_e.Dot(a,l);let x=Math.atan2(h.length(),c)*this.sensitivity;_.copyFrom(e),p.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(r.toRotationMatrix(d),p=_e.TransformCoordinates(_,d));let b=!1;if(i.utilityLayerScene.activeCamera){const e=i.utilityLayerScene.activeCamera.position.subtract(o).normalize();_e.Dot(e,p)>0&&(_.scaleInPlace(-1),p.scaleInPlace(-1),b=!0)}_e.Dot(p,h)>0&&(x=-x),ve.Vector3[0].set(x,0,0),this.dragBehavior.validateDrag(ve.Vector3[0])||(x=0);let T=!1;if(0!=this.snapDistance)if(m+=x,Math.abs(m)>this.snapDistance){let e=Math.floor(Math.abs(m)/this.snapDistance);m<0&&(e*=-1),m%=this.snapDistance,x=this.snapDistance*e,T=!0}else x=0;const y=Math.sin(x/2);if(v.set(_.x*y,_.y*y,_.z*y,Math.cos(x/2)),g.determinant()>0){const e=new _e;v.toEulerAnglesToRef(e),fe.RotationYawPitchRollToRef(e.y,-e.x,-e.z,v)}if(this.updateGizmoRotationToMatchAttachedMesh)r.multiplyToRef(v,r),r.normalize(),me.ComposeToRef(s,r,n,this.attachedNode.getWorldMatrix());else{v.toRotationMatrix(ve.Matrix[0]);const e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(ve.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}u.copyFrom(t.dragPlanePoint),T&&(f.snapDistance=x,this.onSnapObservable.notifyObservers(f)),this._angles.y+=x,this.angle+=b?-x:x,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}}));const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const b={colliderMeshes:[c],gizmoMeshes:[h],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,b),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=sg.MaxDragAngle,this._isHovered=!(-1==b.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=b.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(b.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(b.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_createGizmoMesh(e,t,i){const s=wu("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);s.visibility=0;const r=wu("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return r.material=this._coloredMaterial,r.rotation.x=Math.PI/2,s.rotation.x=Math.PI/2,e.addChild(r,sd.PreserveScaling),e.addChild(s,sd.PreserveScaling),{rotationMesh:r,collider:s}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}sg.MaxDragAngle=9*Math.PI/20,sg._RotationGizmoVertexShader="\n precision highp float;\n attribute vec3 position;\n attribute vec2 uv;\n uniform mat4 worldViewProjection;\n varying vec3 vPosition;\n varying vec2 vUV;\n\n void main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n vUV = uv;\n }",sg._RotationGizmoFragmentShader="\n precision highp float;\n varying vec2 vUV;\n varying vec3 vPosition;\n uniform vec3 angles;\n uniform vec3 rotationColor;\n\n #define twopi 6.283185307\n\n void main(void) {\n vec2 uv = vUV - vec2(0.5);\n float angle = atan(uv.y, uv.x) + 3.141592;\n float delta = gl_FrontFacing ? angles.y : -angles.y;\n float begin = angles.x - delta * angles.z;\n float start = (begin < (begin + delta)) ? begin : (begin + delta);\n float end = (begin > (begin + delta)) ? begin : (begin + delta);\n float len = sqrt(dot(uv,uv));\n float opacity = 1. - step(0.5, len);\n\n float base = abs(floor(start / twopi)) * twopi;\n start += base;\n end += base;\n\n float intensity = 0.;\n for (int i = 0; i < 5; i++)\n {\n intensity += max(step(start, angle) - step(end, angle), 0.);\n angle += twopi;\n }\n gl_FragColor = vec4(rotationColor, min(intensity * 0.25, 0.8)) * opacity;\n }\n ";class rg extends sd{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,this._checkBillboardTransform(),[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}_checkBillboardTransform(){this._nodeAttached&&this._nodeAttached.billboardMode&&Ne.Log("Rotation Gizmo will not work with transforms in billboard mode.")}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t&&(t.sensitivity=e)}))}get sensitivity(){return this._sensitivity}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=Ju.DefaultUtilityLayer,t=32,i=!1,s=1,r,n){super(e),this.onDragStartObservable=new K,this.onDragObservable=new K,this.onDragEndObservable=new K,this._observables=[],this._sensitivity=1,this._gizmoAxisCache=new Map;const o=n&&n.xOptions&&n.xOptions.color?n.xOptions.color:Ee.Red().scale(.5),a=n&&n.yOptions&&n.yOptions.color?n.yOptions.color:Ee.Green().scale(.5),l=n&&n.zOptions&&n.zOptions.color?n.zOptions.color:Ee.Blue().scale(.5);this.xGizmo=new sg(new _e(1,0,0),o,e,t,this,i,s),this.yGizmo=new sg(new _e(0,1,0),a,e,t,this,i,s),this.zGizmo=new sg(new _e(0,0,1),l,e,t,this,i,s),this.additionalTransformNode=n?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((e=>{n&&null!=n.updateScale&&(e.updateScale=n.updateScale),e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,this.attachedNode=null,r?r.addToAxisCache(this._gizmoAxisCache):sd.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set updateGizmoRotationToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.yGizmo.updateGizmoRotationToMatchAttachedMesh=e,this.zGizmo.updateGizmoRotationToMatchAttachedMesh=e)}get updateGizmoRotationToMatchAttachedMesh(){return this.xGizmo.updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this.xGizmo&&(this.xGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.yGizmo.updateGizmoPositionToMatchAttachedMesh=e,this.zGizmo.updateGizmoPositionToMatchAttachedMesh=e)}get updateGizmoPositionToMatchAttachedMesh(){return this.xGizmo.updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.anchorPoint=e}))}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t.coordinatesMode=e}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this.xGizmo&&(this.xGizmo.snapDistance=e,this.yGizmo.snapDistance=e,this.zGizmo.snapDistance=e)}get snapDistance(){return this.xGizmo.snapDistance}set scaleRatio(e){this.xGizmo&&(this.xGizmo.scaleRatio=e,this.yGizmo.scaleRatio=e,this.zGizmo.scaleRatio=e)}get scaleRatio(){return this.xGizmo.scaleRatio}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag()}dispose(){this.xGizmo.dispose(),this.yGizmo.dispose(),this.zGizmo.dispose(),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)}))}setCustomMesh(){Ne.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)")}}class ng extends sd{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}static _CreatePlane(e,t){const i=new lo("plane",e),s=Wa("dragPlane",{width:.1375,height:.1375,sideOrientation:2},e);return s.material=t,s.parent=i,i}constructor(e,t=Ee.Gray(),i=Ju.DefaultUtilityLayer,s=null,r=Ee.Yellow(),n=Ee.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new K,this._isEnabled=!1,this._parent=null,this._dragging=!1,this._parent=s,this._coloredMaterial=new cu("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Ee(.1,.1,.1)),this._hoverMaterial=new cu("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=r,this._disableMaterial=new cu("",i.utilityLayerScene),this._disableMaterial.diffuseColor=n,this._disableMaterial.alpha=.4,this._gizmoMesh=ng._CreatePlane(i.utilityLayerScene,this._coloredMaterial),this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._gizmoMesh.scaling.scaleInPlace(1/3),this._gizmoMesh.parent=this._rootMesh;let o=0;const a=new _e,l={snapDistance:0};this.dragBehavior=new Xa({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this._rootMesh.addBehavior(this.dragBehavior),this.dragBehavior.onDragObservable.add((e=>{if(this.attachedNode){if(0==this.snapDistance)this.attachedNode.getWorldMatrix().getTranslationToRef(ve.Vector3[0]),ve.Vector3[0].addToRef(e.delta,ve.Vector3[0]),this.dragBehavior.validateDrag(ve.Vector3[0])&&this.attachedNode.getWorldMatrix().addTranslationFromFloats(e.delta.x,e.delta.y,e.delta.z);else if(o+=e.dragDistance,Math.abs(o)>this.snapDistance){const t=Math.floor(Math.abs(o)/this.snapDistance);o%=this.snapDistance,e.delta.normalizeToRef(a),a.scaleInPlace(this.snapDistance*t),this.attachedNode.getWorldMatrix().getTranslationToRef(ve.Vector3[0]),ve.Vector3[0].addToRef(a,ve.Vector3[0]),this.dragBehavior.validateDrag(ve.Vector3[0])&&(this.attachedNode.getWorldMatrix().addTranslationFromFloats(a.x,a.y,a.z),l.snapDistance=this.snapDistance*t,this.onSnapObservable.notifyObservers(l))}this._matrixChanged()}})),this.dragBehavior.onDragStartObservable.add((()=>{this._dragging=!0})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1}));const h=i._getSharedGizmoLight();h.includedOnlyMeshes=h.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const c={gizmoMeshes:this._gizmoMesh.getChildMeshes(),colliderMeshes:this._gizmoMesh.getChildMeshes(),material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,c),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this._isHovered=!(-1==c.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=c.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(c.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(c.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedNode=this._parent.attachedNode):this.attachedNode=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),super.dispose(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()}))}}class og extends sd{get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.xPlaneGizmo.isHovered||this.yPlaneGizmo.isHovered||this.zPlaneGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.xPlaneGizmo.dragBehavior.dragging||this.yPlaneGizmo.dragBehavior.dragging||this.zPlaneGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=Ju.DefaultUtilityLayer,t=1,i,s){super(e),this._meshAttached=null,this._nodeAttached=null,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new K,this.onDragObservable=new K,this.onDragEndObservable=new K,this._planarGizmoEnabled=!1,this.xGizmo=new rd(new _e(1,0,0),Ee.Red().scale(.5),e,this,t),this.yGizmo=new rd(new _e(0,1,0),Ee.Green().scale(.5),e,this,t),this.zGizmo=new rd(new _e(0,0,1),Ee.Blue().scale(.5),e,this,t),this.xPlaneGizmo=new ng(new _e(1,0,0),Ee.Red().scale(.5),this.gizmoLayer,this),this.yPlaneGizmo=new ng(new _e(0,1,0),Ee.Green().scale(.5),this.gizmoLayer,this),this.zPlaneGizmo=new ng(new _e(0,0,1),Ee.Blue().scale(.5),this.gizmoLayer,this),this.additionalTransformNode=s?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((e=>{e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,i?i.addToAxisCache(this._gizmoAxisCache):sd.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}set planarGizmoEnabled(e){this._planarGizmoEnabled=e,[this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.isEnabled=e,e&&(t.attachedMesh?t.attachedMesh=this.attachedMesh:t.attachedNode=this.attachedNode))}),this)}get planarGizmoEnabled(){return this._planarGizmoEnabled}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.updateGizmoPositionToMatchAttachedMesh=e)}))}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.anchorPoint=e}))}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t.coordinatesMode=e}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.snapDistance=e)}))}get snapDistance(){return this._snapDistance}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.xPlaneGizmo.dragBehavior.releaseDrag(),this.yPlaneGizmo.dragBehavior.releaseDrag(),this.zPlaneGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.xPlaneGizmo,this.yPlaneGizmo,this.zPlaneGizmo].forEach((e=>{e&&e.dispose()})),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear()}setCustomMesh(){Ne.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)")}}class ag extends sd{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}get attachedMesh(){return this._meshAttached}set attachedMesh(e){this._meshAttached=e,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.isEnabled?t.attachedMesh=e:t.attachedMesh=null}))}get attachedNode(){return this._nodeAttached}set attachedNode(e){this._meshAttached=null,this._nodeAttached=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.isEnabled?t.attachedNode=e:t.attachedNode=null}))}set updateScale(e){this.xGizmo&&(this.xGizmo.updateScale=e,this.yGizmo.updateScale=e,this.zGizmo.updateScale=e)}get updateScale(){return this.xGizmo.updateScale}get isHovered(){return this.xGizmo.isHovered||this.yGizmo.isHovered||this.zGizmo.isHovered||this.uniformScaleGizmo.isHovered}get isDragging(){return this.xGizmo.dragBehavior.dragging||this.yGizmo.dragBehavior.dragging||this.zGizmo.dragBehavior.dragging||this.uniformScaleGizmo.dragBehavior.dragging}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t.additionalTransformNode=e}))}constructor(e=Ju.DefaultUtilityLayer,t=1,i,s){super(e),this._meshAttached=null,this._nodeAttached=null,this._incrementalSnap=!1,this._sensitivity=1,this._observables=[],this._gizmoAxisCache=new Map,this.onDragStartObservable=new K,this.onDragObservable=new K,this.onDragEndObservable=new K,this.uniformScaleGizmo=this._createUniformScaleMesh(),this.xGizmo=new tg(new _e(1,0,0),Ee.Red().scale(.5),e,this,t),this.yGizmo=new tg(new _e(0,1,0),Ee.Green().scale(.5),e,this,t),this.zGizmo=new tg(new _e(0,0,1),Ee.Blue().scale(.5),e,this,t),this.additionalTransformNode=s?.additionalTransformNode,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e.dragBehavior.onDragStartObservable.add((()=>{this.onDragStartObservable.notifyObservers({})})),e.dragBehavior.onDragObservable.add((()=>{this.onDragObservable.notifyObservers({})})),e.dragBehavior.onDragEndObservable.add((()=>{this.onDragEndObservable.notifyObservers({})}))})),this.attachedMesh=null,this.attachedNode=null,i?i.addToAxisCache(this._gizmoAxisCache):sd.GizmoAxisPointerObserver(e,this._gizmoAxisCache)}_createUniformScaleMesh(){this._coloredMaterial=new cu("",this.gizmoLayer.utilityLayerScene),this._coloredMaterial.diffuseColor=Ee.Gray(),this._hoverMaterial=new cu("",this.gizmoLayer.utilityLayerScene),this._hoverMaterial.diffuseColor=Ee.Yellow(),this._disableMaterial=new cu("",this.gizmoLayer.utilityLayerScene),this._disableMaterial.diffuseColor=Ee.Gray(),this._disableMaterial.alpha=.4;const e=new tg(new _e(0,1,0),Ee.Gray().scale(.5),this.gizmoLayer,this);e.updateGizmoRotationToMatchAttachedMesh=!1,e.uniformScaling=!0,this._uniformScalingMesh=o_("uniform",{type:1},e.gizmoLayer.utilityLayerScene),this._uniformScalingMesh.scaling.scaleInPlace(.01),this._uniformScalingMesh.visibility=0,this._octahedron=o_("",{type:1},e.gizmoLayer.utilityLayerScene),this._octahedron.scaling.scaleInPlace(.007),this._uniformScalingMesh.addChild(this._octahedron),e.setCustomMesh(this._uniformScalingMesh,!0);const t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._octahedron);const i={gizmoMeshes:[this._octahedron,this._uniformScalingMesh],colliderMeshes:[this._octahedron,this._uniformScalingMesh],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:e.dragBehavior};return this.addToAxisCache(e._rootMesh,i),e}set updateGizmoRotationToMatchAttachedMesh(e){e?(this._updateGizmoRotationToMatchAttachedMesh=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.updateGizmoRotationToMatchAttachedMesh=e)}))):Ne.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.")}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.anchorPoint=e)}))}get anchorPoint(){return this._anchorPoint}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.customRotationQuaternion=e)}))}set coordinatesMode(e){e==td.World&&Ne.Warn("Setting coordinates Mode to world on scaling gizmo is not supported."),[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e.coordinatesMode=td.Local}))}set snapDistance(e){this._snapDistance=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.snapDistance=e)}))}get snapDistance(){return this._snapDistance}set incrementalSnap(e){this._incrementalSnap=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.incrementalSnap=e)}))}get incrementalSnap(){return this._incrementalSnap}set scaleRatio(e){this._scaleRatio=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}set sensitivity(e){this._sensitivity=e,[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((t=>{t&&(t.sensitivity=e)}))}get sensitivity(){return this._sensitivity}addToAxisCache(e,t){this._gizmoAxisCache.set(e,t)}getAxisCache(e){return this._gizmoAxisCache.get(e)}releaseDrag(){this.xGizmo.dragBehavior.releaseDrag(),this.yGizmo.dragBehavior.releaseDrag(),this.zGizmo.dragBehavior.releaseDrag(),this.uniformScaleGizmo.dragBehavior.releaseDrag()}dispose(){[this.xGizmo,this.yGizmo,this.zGizmo,this.uniformScaleGizmo].forEach((e=>{e&&e.dispose()})),this._observables.forEach((e=>{this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(e)})),this.onDragStartObservable.clear(),this.onDragObservable.clear(),this.onDragEndObservable.clear(),[this._uniformScalingMesh,this._octahedron].forEach((e=>{e&&e.dispose()})),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()}))}}class lg{get keepDepthUtilityLayer(){return this._defaultKeepDepthUtilityLayer}get utilityLayer(){return this._defaultUtilityLayer}get isHovered(){let e=!1;for(const t in this.gizmos){const i=this.gizmos[t];if(i&&i.isHovered){e=!0;break}}return e}get isDragging(){let e=!1;return[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach((t=>{t&&t.isDragging&&(e=!0)})),e}set scaleRatio(e){this._scaleRatio=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach((t=>{t&&(t.scaleRatio=e)}))}get scaleRatio(){return this._scaleRatio}set coordinatesMode(e){this._coordinatesMode=e,[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo].forEach((t=>{t&&(t.coordinatesMode=e)}))}get coordinatesMode(){return this._coordinatesMode}get attachedMesh(){return this._attachedMesh}get attachedNode(){return this._attachedNode}get additionalTransformNode(){return this._additionalTransformNode}constructor(e,t=1,i=Ju.DefaultUtilityLayer,s=Ju.DefaultKeepDepthUtilityLayer){this._scene=e,this.clearGizmoOnEmptyPointerEvent=!1,this.enableAutoPicking=!0,this.onAttachedToMeshObservable=new K,this.onAttachedToNodeObservable=new K,this._gizmosEnabled={positionGizmo:!1,rotationGizmo:!1,scaleGizmo:!1,boundingBoxGizmo:!1},this._pointerObservers=[],this._attachedMesh=null,this._attachedNode=null,this._boundingBoxColor=Ee.FromHexString("#0984e3"),this._thickness=1,this._scaleRatio=1,this._coordinatesMode=td.Local,this._gizmoAxisCache=new Map,this.boundingBoxDragBehavior=new ja,this.attachableMeshes=null,this.attachableNodes=null,this.usePointerToAttachGizmos=!0,this._defaultUtilityLayer=i,this._defaultKeepDepthUtilityLayer=s,this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,this._thickness=t,this.gizmos={positionGizmo:null,rotationGizmo:null,scaleGizmo:null,boundingBoxGizmo:null};const r=this._attachToMeshPointerObserver(e),n=sd.GizmoAxisPointerObserver(this._defaultUtilityLayer,this._gizmoAxisCache);this._pointerObservers=[r,n]}_attachToMeshPointerObserver(e){return e.onPointerObservable.add((e=>{if(this.usePointerToAttachGizmos&&e.type==lr.POINTERDOWN)if(e.pickInfo&&e.pickInfo.pickedMesh){if(this.enableAutoPicking){let t=e.pickInfo.pickedMesh;if(null==this.attachableMeshes)for(;t&&null!=t.parent;)t=t.parent;else{let e=!1;this.attachableMeshes.forEach((i=>{t&&(t==i||t.isDescendantOf(i))&&(t=i,e=!0)})),e||(t=null)}t instanceof _o?this._attachedMesh!=t&&this.attachToMesh(t):this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}}else this.clearGizmoOnEmptyPointerEvent&&this.attachToMesh(null)}))}attachToMesh(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=e,this._attachedNode=null;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedMesh=e)}this.boundingBoxGizmoEnabled&&this._attachedMesh&&this._attachedMesh.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToMeshObservable.notifyObservers(e)}attachToNode(e){this._attachedMesh&&this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh=null,this._attachedNode=e;for(const t in this.gizmos){const i=this.gizmos[t];i&&this._gizmosEnabled[t]&&(i.attachedNode=e)}this.boundingBoxGizmoEnabled&&this._attachedNode&&this._attachedNode.addBehavior(this.boundingBoxDragBehavior),this.onAttachedToNodeObservable.notifyObservers(e)}set positionGizmoEnabled(e){e?(this.gizmos.positionGizmo||(this.gizmos.positionGizmo=new og(this._defaultUtilityLayer,this._thickness,this)),this._attachedNode?this.gizmos.positionGizmo.attachedNode=this._attachedNode:this.gizmos.positionGizmo.attachedMesh=this._attachedMesh):this.gizmos.positionGizmo&&(this.gizmos.positionGizmo.attachedNode=null),this._gizmosEnabled.positionGizmo=e,this._setAdditionalTransformNode()}get positionGizmoEnabled(){return this._gizmosEnabled.positionGizmo}set rotationGizmoEnabled(e){e?(this.gizmos.rotationGizmo||(this.gizmos.rotationGizmo=new rg(this._defaultUtilityLayer,32,!1,this._thickness,this)),this._attachedNode?this.gizmos.rotationGizmo.attachedNode=this._attachedNode:this.gizmos.rotationGizmo.attachedMesh=this._attachedMesh):this.gizmos.rotationGizmo&&(this.gizmos.rotationGizmo.attachedNode=null),this._gizmosEnabled.rotationGizmo=e,this._setAdditionalTransformNode()}get rotationGizmoEnabled(){return this._gizmosEnabled.rotationGizmo}set scaleGizmoEnabled(e){e?(this.gizmos.scaleGizmo=this.gizmos.scaleGizmo||new ag(this._defaultUtilityLayer,this._thickness,this),this._attachedNode?this.gizmos.scaleGizmo.attachedNode=this._attachedNode:this.gizmos.scaleGizmo.attachedMesh=this._attachedMesh):this.gizmos.scaleGizmo&&(this.gizmos.scaleGizmo.attachedNode=null),this._gizmosEnabled.scaleGizmo=e,this._setAdditionalTransformNode()}get scaleGizmoEnabled(){return this._gizmosEnabled.scaleGizmo}set boundingBoxGizmoEnabled(e){e?(this.gizmos.boundingBoxGizmo=this.gizmos.boundingBoxGizmo||new ig(this._boundingBoxColor,this._defaultKeepDepthUtilityLayer),this._attachedMesh?this.gizmos.boundingBoxGizmo.attachedMesh=this._attachedMesh:this.gizmos.boundingBoxGizmo.attachedNode=this._attachedNode,this._attachedMesh?(this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior),this._attachedMesh.addBehavior(this.boundingBoxDragBehavior)):this._attachedNode&&(this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this._attachedNode.addBehavior(this.boundingBoxDragBehavior))):this.gizmos.boundingBoxGizmo&&(this._attachedMesh?this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior):this._attachedNode&&this._attachedNode.removeBehavior(this.boundingBoxDragBehavior),this.gizmos.boundingBoxGizmo.attachedNode=null),this._gizmosEnabled.boundingBoxGizmo=e,this._setAdditionalTransformNode()}get boundingBoxGizmoEnabled(){return this._gizmosEnabled.boundingBoxGizmo}set additionalTransformNode(e){this._additionalTransformNode=e,this._setAdditionalTransformNode()}_setAdditionalTransformNode(){for(const e in this.gizmos){const t=this.gizmos[e];t&&this._gizmosEnabled[e]&&(t.additionalTransformNode=this._additionalTransformNode)}}addToAxisCache(e){e.size>0&&e.forEach(((e,t)=>{this._gizmoAxisCache.set(t,e)}))}releaseDrag(){[this.gizmos.positionGizmo,this.gizmos.rotationGizmo,this.gizmos.scaleGizmo,this.gizmos.boundingBoxGizmo].forEach((e=>{e?.releaseDrag()}))}dispose(){this._pointerObservers.forEach((e=>{this._scene.onPointerObservable.remove(e)}));for(const e in this.gizmos){const t=this.gizmos[e];t&&t.dispose()}this._defaultKeepDepthUtilityLayer!==Ju._DefaultKeepDepthUtilityLayer&&this._defaultKeepDepthUtilityLayer?.dispose(),this._defaultUtilityLayer!==Ju._DefaultUtilityLayer&&this._defaultUtilityLayer?.dispose(),this.boundingBoxDragBehavior.detach(),this.onAttachedToMeshObservable.clear()}}class hg extends ua{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=me.Identity(),this._projectionMatrix=me.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return!(!this.parent||!this.parent.getWorldMatrix||(this.transformedPosition||(this.transformedPosition=_e.Zero()),_e.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=_e.Zero()),_e.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),0))}getDepthScale(){return 50}getShadowDirection(e){return this.transformedDirection?this.transformedDirection:this.direction}getAbsolutePosition(){return this.transformedPosition?this.transformedPosition:this.position}setDirectionToTarget(e){return this.direction=_e.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=_e.Cross(this.direction,Xr.Y),t=_e.Cross(e,this.direction);return _e.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=_e.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=me.Identity()),me.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),this.parent&&this.parent.getWorldMatrix||(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){const t=ve.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),_e.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(_e.Dot(t,_e.Up()))&&(t.z=1e-13);const s=ve.Vector3[1];return i.addToRef(t,s),me.LookAtLHToRef(i,s,_e.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}Ze([ht()],hg.prototype,"position",null),Ze([ht()],hg.prototype,"direction",null),Ze([rt()],hg.prototype,"shadowMinZ",null),Ze([rt()],hg.prototype,"shadowMaxZ",null),Et.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new cg(e,_e.Zero(),t)));class cg extends hg{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,i){super(e,i),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return ua.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){const t=this.getScene().activeCamera;t&&me.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=_e.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let s=Number.MAX_VALUE,r=-Number.MAX_VALUE;for(let n=0;nthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zr&&(r=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=s,this._shadowMaxZ=r)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,o=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;me.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,l?a:o,l?o:a,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}function ug(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);const s=_d("",{slice:.5,diameter:t.diameter,segments:t.segments},i),r=yd("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);r.rotation.x=-Math.PI/2,r.parent=s;const n=ha.MergeMeshes([r,s],!0);return n.name=e,n}Ze([rt()],cg.prototype,"shadowFrustumSize",null),Ze([rt()],cg.prototype,"shadowOrthoScale",null),Ze([rt()],cg.prototype,"autoUpdateExtends",void 0),Ze([rt()],cg.prototype,"autoCalcShadowZBounds",void 0),Ze([rt("orthoLeft")],cg.prototype,"_orthoLeft",void 0),Ze([rt("orthoRight")],cg.prototype,"_orthoRight",void 0),Ze([rt("orthoTop")],cg.prototype,"_orthoTop",void 0),Ze([rt("orthoBottom")],cg.prototype,"_orthoBottom",void 0),z("BABYLON.DirectionalLight",cg);const dg={CreateHemisphere:ug};ha.CreateHemisphere=(e,t,i,s)=>ug(e,{segments:t,diameter:i},s),Et.AddNodeConstructor("Light_Type_2",((e,t)=>()=>new _g(e,_e.Zero(),_e.Zero(),0,0,t)));class _g extends hg{get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(.5*e),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()}get innerAngle(){return this._innerAngle}set innerAngle(e){this._innerAngle=e,this._computeAngleValues()}get shadowAngleScale(){return this._shadowAngleScale}set shadowAngleScale(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()}get projectionTextureMatrix(){return this._projectionTextureMatrix}get projectionTextureLightNear(){return this._projectionTextureLightNear}set projectionTextureLightNear(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureLightFar(){return this._projectionTextureLightFar}set projectionTextureLightFar(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureUpDirection(){return this._projectionTextureUpDirection}set projectionTextureUpDirection(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0}get projectionTexture(){return this._projectionTexture}set projectionTexture(e){this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(_g._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((()=>{this._markMeshesAsLightDirty()})):_g._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce((()=>{this._markMeshesAsLightDirty()}))))}static _IsProceduralTexture(e){return void 0!==e.onGeneratedObservable}static _IsTexture(e){return void 0!==e.onLoadObservable}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,s,r,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=me.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=_e.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=_e.Zero(),this._projectionTextureViewLightMatrix=me.Zero(),this._projectionTextureProjectionLightMatrix=me.Zero(),this._projectionTextureScalingMatrix=me.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=s,this.exponent=r}getClassName(){return"SpotLight"}getTypeID(){return ua.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;this._shadowAngleScale=this._shadowAngleScale||1;const r=this._shadowAngleScale*this._angle,n=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;me.PerspectiveFovLHToRef(r,1,a?o:n,a?n:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,a)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),me.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),s=-i*t,r=1/Math.tan(this._angle/2);me.FromValuesToRef(r/1,0,0,0,0,r,0,0,0,0,i,1,0,0,s,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof Pa){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;me.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}_computeAngleValues(){this._lightAngleScale=1/Math.max(.001,Math.cos(.5*this._innerAngle)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightTexture"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=_e.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=_e.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return i=this.computeTransformedInformation()?_e.Normalize(this.transformedDirection):_e.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!(!this.projectionTexture||!this.projectionTexture.isReady())}}Ze([rt()],_g.prototype,"angle",null),Ze([rt()],_g.prototype,"innerAngle",null),Ze([rt()],_g.prototype,"shadowAngleScale",null),Ze([rt()],_g.prototype,"exponent",void 0),Ze([rt()],_g.prototype,"projectionTextureLightNear",null),Ze([rt()],_g.prototype,"projectionTextureLightFar",null),Ze([rt()],_g.prototype,"projectionTextureUpDirection",null),Ze([nt("projectedLightTexture")],_g.prototype,"_projectionTexture",void 0),z("BABYLON.SpotLight",_g);class pg extends sd{constructor(e=Ju.DefaultUtilityLayer){super(e),this._cachedPosition=new _e,this._cachedForward=new _e(0,0,1),this._pointerObserver=null,this.onClickedObservable=new K,this._light=null,this.attachedMesh=new _o("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new lo("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new cu("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new Ee(.5,.5,.5),this._material.specularColor=new Ee(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._light&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._light))}),lr.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){Ne.Warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),this._lightMesh=e instanceof Zu?pg._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof cg?pg._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof _g?pg._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):pg._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._lightMesh.parent=this._rootMesh;const t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new fe,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction){this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0);const t=this._getMeshForward();this._cachedForward.copyFrom(t)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(ve.Vector3[0]),e=ve.Vector3[0]),e}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position)if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{const e=this.attachedMesh.position;this._light.position=new _e(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction){const e=this._getMeshForward();if(_e.DistanceSquared(e,this._cachedForward)>1e-4){const t=e;this._light.direction=new _e(t.x,t.y,t.z),this._cachedForward.copyFrom(e)}else _e.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){const t=new ha("hemisphereLight",e),i=ug(t.name,{segments:10,diameter:1},e);return i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(3,e).parent=t,t.scaling.scaleInPlace(pg._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){const t=new ha("pointLight",e),i=_d(t.name,{segments:10,diameter:1},e);return i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(5,e).parent=t,t.scaling.scaleInPlace(pg._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){const t=new ha("spotLight",e);_d(t.name,{segments:10,diameter:1},e).parent=t;const i=ug(t.name,{segments:10,diameter:2},e);return i.parent=t,i.rotation.x=-Math.PI/2,this._CreateLightLines(2,e).parent=t,t.scaling.scaleInPlace(pg._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){const t=new ha("directionalLight",e),i=new ha(t.name,e);i.parent=t,_d(t.name,{diameter:1.2,segments:10},e).parent=i;const s=$u(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);s.parent=i;let r=s.clone(t.name);r.scaling.y=.5,r.position.x+=1.25;let n=s.clone(t.name);n.scaling.y=.5,n.position.x+=-1.25;const o=$u(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,r=o.clone(t.name),r.position.y=1.5,r.position.x+=1.25,n=o.clone(t.name),n.position.y=1.5,n.position.x+=-1.25,i.scaling.scaleInPlace(pg._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}pg._Scale=.007,pg._CreateLightLines=(e,t)=>{const i=new ha("root",t);i.rotation.x=Math.PI/2;const s=new ha("linePivot",t);s.parent=i;const r=$u("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(r.position.y=r.scaling.y/2+1.2,r.parent=s,e<2)return s;for(let e=0;e<4;e++){const t=s.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){const t=s.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){const t=s.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}return e<5||(s.clone("linePivotClone").rotation.z=Math.PI),i};class fg extends sd{constructor(e=Ju.DefaultUtilityLayer,t,i){super(e),this._pointerObserver=null,this.onClickedObservable=new K,this._camera=null,this._invProjection=new me,this._material=new cu("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._frustumLinesColor=i,this._material.diffuseColor=t??new Ee(.5,.5,.5),this._material.specularColor=new Ee(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._camera&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._camera))}),lr.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){if(this._camera=e,this.attachedNode=e,e){this._customMeshSet||(this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=fg._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._cameraMesh.parent=this._rootMesh),this._cameraLinesMesh&&this._cameraLinesMesh.dispose();const t=this._frustumLinesColor?.toColor4(1)??new Ae(1,1,1,1);this._cameraLinesMesh=fg._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene,t),this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;const i=this.gizmoLayer._getSharedGizmoLight();i.includedOnlyMeshes=i.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}}get camera(){return this._camera}get material(){return this._material}_update(){super._update(),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=e,this._cameraMesh.parent=this._rootMesh,this._customMeshSet=!0}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),super.dispose()}static _CreateCameraMesh(e){const t=new ha("rootCameraGizmo",e),i=new ha(t.name,e);i.parent=t,cd(t.name,{width:1,height:.8,depth:.5},e).parent=i;const s=$u(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);s.parent=i,s.position.y=.3,s.position.x=-.6,s.rotation.x=.5*Math.PI;const r=$u(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);r.parent=i,r.position.y=.5,r.position.x=.4,r.rotation.x=.5*Math.PI;const n=$u(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return n.parent=i,n.position.y=0,n.position.x=.6,n.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(fg._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e,t){const i=new ha("rootCameraGizmo",e),s=new ha(i.name,e);s.parent=i;for(let i=0;i<4;i+=2)for(let r=0;r<4;r+=2){let n=Ud("lines",{points:[new _e(-1+r,-1+i,-1),new _e(-1+r,-1+i,1)],colors:[t,t]},e);n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Ud("lines",{points:[new _e(-1,-1+r,-1+i),new _e(1,-1+r,-1+i)],colors:[t,t]},e),n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Ud("lines",{points:[new _e(-1+r,-1,-1+i),new _e(-1+r,1,-1+i)],colors:[t,t]},e),n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1}return i}}fg._Scale=.05;Bi.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";Bi.IncludesShadersStore.packingFunctions="vec4 pack(float depth)\n{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}";Bi.IncludesShadersStore.kernelBlurFragment="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif\n";Bi.IncludesShadersStore.kernelBlurFragment2="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";Bi.ShadersStore.kernelBlurPixelShader="uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";Bi.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";Bi.ShadersStore.kernelBlurVertexShader="attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class mg extends Vl{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,s,r,n=Pa.BILINEAR_SAMPLINGMODE,o,a,l=0,h="",c=!1,u=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],s,r,n,o,a,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,u),this._blockCompilation=c,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add((e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)})),this.kernel=i}updateEffect(e=null,t=null,i=null,s,r,n){this._updateParameters(r,n)}_updateParameters(e,t){const i=this._kernel,s=(i-1)/2;let r=[],n=[],o=0;for(let e=0;e0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){const t=1/3,i=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(i)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,s){return St.Parse((()=>new mg(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)),e,i,s)}}Ze([rt("kernel")],mg.prototype,"_kernel",void 0),Ze([rt("packedFloat")],mg.prototype,"_packedFloat",void 0),Ze([lt()],mg.prototype,"direction",void 0),z("BABYLON.BlurPostProcess",mg);class gg extends ih{set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){const e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){const e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,s,r=0,n=Pa.BILINEAR_SAMPLINGMODE,o=!0){if(super(e,t,i,s,!0,r,!1,n,o),this.mirrorPlane=new Nr(0,1,0,1),this._transformMatrix=me.Zero(),this._mirrorMatrix=me.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateGammaSpace()}));const a=i.getEngine();let l;a.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add((()=>{a._debugPushGroup?.(`mirror generation for ${e}`,1)})),this.onAfterUnbindObservable.add((()=>{a._debugPopGroup?.(1)})),this.onBeforeRenderObservable.add((()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),me.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),l=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=_e.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)})),this.onAfterRenderObservable.add((()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=l}))}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){const e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new mg("horizontal blur",new de(1,0),this._blurKernelX,this._blurRatio,null,Pa.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new mg("vertical blur",new de(0,1),this._blurKernelY,this._blurRatio,null,Pa.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new gg(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){super.dispose();const e=this.getScene();e&&e.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),this._sceneUBO?.dispose()}}Pa._CreateMirror=(e,t,i,s)=>new gg(e,t,i,s);class vg extends ya{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(me.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let s="";return e.forEach((e=>s+=e)),new vg(s,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,s=!0){const r=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const n=new vg(e,t,null,!1,null,null,null,void 0,!0,i,s);return t.useDelayedTextureLoading=r,n}constructor(e,t,i=null,s=!1,r=null,n=null,o=null,a=5,l=!1,h=null,c=!1,u=.8,d=0,_,p){super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new K,this.boundingBoxPosition=_e.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new me,this.name=e,this.url=e,this._noMipmap=s,this.hasAlpha=!1,this._format=a,this.isCube=!0,this._textureMatrix=me.Identity(),this._createPolynomials=c,this.coordinatesMode=Pa.CUBIC_MODE,this._extensions=i,this._files=r,this._forcedExtension=h,this._loaderOptions=_,this._useSRGBBuffer=p,this._lodScale=u,this._lodOffset=d,(e||r)&&this.updateURL(e,h,n,l,o,i,this.getScene()?.useDelayedTextureLoading,r)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,s=!1,r=null,n=null,o=!1,a=null){this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,t&&(this._forcedExtension=t);const l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),c=0===h.indexOf(".dds"),u=0===h.indexOf(".env"),d=0===h.indexOf(".basis");if(u?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=s,s&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),a)this._files=a;else if(d||u||c||n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,n){for(let t=0;t-1!==e.getActiveTextures().indexOf(this))),this._textureMatrix=e,!this.getScene()?.useRightHandedSystem)return;const t=ve.Vector3[0],i=ve.Quaternion[0],s=ve.Vector3[1];this._textureMatrix.decompose(t,i,s),i.z*=-1,i.w*=-1,me.ComposeToRef(t,i,s,this._textureMatrixRefraction)}getRefractionTextureMatrix(){return this.getScene()?.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){const i=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const r=()=>{this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),this.getScene()?.markAllMaterialsAsDirty(1)),e&&e()},n=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),Pa.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Ds.SetImmediate((()=>r())):this._texture.onLoadedObservable.add((()=>r())):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,i,this._lodScale,this._lodOffset,e,n,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,i,this._files,this._noMipmap,e,n,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),this._texture?.onLoadedObservable.add((()=>this.onLoadObservable.notifyObservers(this))))}static Parse(e,t,i){const s=St.Parse((()=>{let s=!1;return e.prefiltered&&(s=e.prefiltered),new vg(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(s.boundingBoxPosition=_e.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=_e.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t{const t=new vg(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}Ze([rt()],vg.prototype,"url",void 0),Ze([ht()],vg.prototype,"boundingBoxPosition",void 0),Ze([ht()],vg.prototype,"boundingBoxSize",null),Ze([rt("rotationY")],vg.prototype,"rotationY",null),Ze([rt("files")],vg.prototype,"_files",void 0),Ze([rt("forcedExtension")],vg.prototype,"_forcedExtension",void 0),Ze([rt("extensions")],vg.prototype,"_extensions",void 0),Ze([ft("textureMatrix")],vg.prototype,"_textureMatrix",void 0),Ze([ft("textureMatrixRefraction")],vg.prototype,"_textureMatrixRefraction",void 0),Pa._CubeTextureParser=vg.Parse,z("BABYLON.CubeTexture",vg);Bi.IncludesShadersStore.backgroundFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;uniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef PROJECTED_GROUND\nuniform vec2 projectedGroundInfos;\n#endif\n";Bi.IncludesShadersStore.backgroundUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;};\n#include\n";Bi.ShadersStore.backgroundPixelShader="#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#include\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#ifdef PROJECTED_GROUND\nfloat diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; }\nvec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q)\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\nfloat shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.;\n#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n#ifndef BACKMAT_SHADOWONLY\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\n#ifdef PROJECTED_GROUND\nvec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.));\n#else\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);} else {reflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\nvec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor;\n#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\nvec4 color=vec4(finalColor,finalAlpha);\n#else\nvec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);\n#endif\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#endif\n#else\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Bi.IncludesShadersStore.backgroundVertexDeclaration="uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";Bi.ShadersStore.backgroundVertexShader="precision highp float;\n#include<__decl__backgroundVertex>\n#include\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vec2 vDiffuseUV;\n#endif\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif\n#include\n#include\n#include\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);}\n#else\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#endif\nvec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class xg extends xl{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.PROJECTED_GROUND=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}}class bg extends ml{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t*=2,this.reflectionReflectance0=bg.StandardReflectance0*t,this.reflectionReflectance90=bg.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=bg.StandardReflectance0+(1-bg.StandardReflectance0)*t,this.reflectionReflectance90=bg.StandardReflectance90+(1-bg.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()}))))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.primaryColor=Ee.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=_e.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._enableGroundProjection=!1,this.enableGroundProjection=!1,this.projectedGroundRadius=1e3,this.projectedGroundHeight=10,this._renderTargets=new Fs(16),this._reflectionControls=pe.Zero(),this._white=Ee.White(),this._primaryShadowColor=Ee.Black(),this._primaryHighlightColor=Ee.Black(),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!(!this._diffuseTexture||!this._diffuseTexture.isRenderTarget)||!(!this._reflectionTexture||!this._reflectionTexture.isRenderTarget)}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new xg);const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(zo(r,e,n,!1,this._maxSimultaneousLights),n._needNormals=!0,Ko(r,n),n._areTexturesDirty){if(n._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(n.TEXTURELODSUPPORT=!0),this._diffuseTexture&&$c.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;Mo(this._diffuseTexture,n,"DIFFUSE"),n.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,n.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,n.OPACITYFRESNEL=this._opacityFresnel}else n.DIFFUSE=!1,n.DIFFUSEDIRECTUV=0,n.DIFFUSEHASALPHA=!1,n.GAMMADIFFUSE=!1,n.OPACITYFRESNEL=!1;const e=this._reflectionTexture;if(e&&$c.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(n.REFLECTION=!0,n.GAMMAREFLECTION=e.gammaSpace,n.RGBDREFLECTION=e.isRGBD,n.REFLECTIONBLUR=this._reflectionBlur>0,n.LODINREFLECTIONALPHA=e.lodLevelInAlpha,n.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,n.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===Pa.INVCUBIC_MODE&&(n.INVERTCUBICMAP=!0),n.REFLECTIONMAP_3D=e.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case Pa.EXPLICIT_MODE:n.REFLECTIONMAP_EXPLICIT=!0;break;case Pa.PLANAR_MODE:n.REFLECTIONMAP_PLANAR=!0;break;case Pa.PROJECTION_MODE:n.REFLECTIONMAP_PROJECTION=!0;break;case Pa.SKYBOX_MODE:n.REFLECTIONMAP_SKYBOX=!0;break;case Pa.SPHERICAL_MODE:n.REFLECTIONMAP_SPHERICAL=!0;break;case Pa.EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Pa.FIXED_EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Pa.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Pa.CUBIC_MODE:case Pa.INVCUBIC_MODE:default:n.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(n.REFLECTIONFRESNEL=!0,n.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1)}else n.REFLECTION=!1,n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1,n.REFLECTIONBLUR=!1,n.REFLECTIONMAP_3D=!1,n.REFLECTIONMAP_SPHERICAL=!1,n.REFLECTIONMAP_PLANAR=!1,n.REFLECTIONMAP_CUBIC=!1,n.REFLECTIONMAP_PROJECTION=!1,n.REFLECTIONMAP_SKYBOX=!1,n.REFLECTIONMAP_EXPLICIT=!1,n.REFLECTIONMAP_EQUIRECTANGULAR=!1,n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,n.INVERTCUBICMAP=!1,n.REFLECTIONMAP_OPPOSITEZ=!1,n.LODINREFLECTIONALPHA=!1,n.GAMMAREFLECTION=!1,n.RGBDREFLECTION=!1}n.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,n.USERGBCOLOR=this._useRGBColor,n.NOISE=this._enableNoise}if(n._areLightsDirty&&(n.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),n.BACKMAT_SHADOWONLY=this._shadowOnly),n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n)}if(n._areMiscDirty&&(n.REFLECTIONMAP_3D&&this._enableGroundProjection?(n.PROJECTED_GROUND=!0,n.REFLECTIONMAP_SKYBOX=!0):n.PROJECTED_GROUND=!1),Go(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),Ho(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),jo(e,n,!1,!0,!1)&&e&&(r.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(er.NormalKind)||(e.createNormals(!0),Ne.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),n.isDirty){n.markAsProcessed(),r.resetCachedMaterial();const i=new Ll;n.FOG&&i.addFallback(0,"FOG"),n.POINTSIZE&&i.addFallback(1,"POINTSIZE"),n.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),Vo(n,i,this._maxSimultaneousLights);const s=[er.PositionKind];n.NORMAL&&s.push(er.NormalKind),n.UV1&&s.push(er.UVKind),n.UV2&&s.push(er.UV2Kind),Bo(s,e,n,i),ko(s,n);const a=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];mo(a);const l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];zs&&(zs.PrepareUniforms(a,n),zs.PrepareSamplers(l,n)),ea({uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:n,maxSimultaneousLights:this._maxSimultaneousLights});const c=n.toString(),u=r.getEngine().createEffect("background",{attributes:s,uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:c,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o);t.setEffect(u,n,this._materialContext),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady()||(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),wo(t,this._activeEffect);const o=this._mustRebind(s,n,i,t.visibility);if(o){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);const e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync&&!i._drawWrapper._forceRebindOnNextCall||(s.texturesEnabled&&(this._diffuseTexture&&$c.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),Oo(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&$c.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),r.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),s.texturesEnabled&&(this._diffuseTexture&&$c.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&$c.ReflectionTextureEnabled&&(r.REFLECTIONBLUR&&r.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):r.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),r.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),r.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),xo(this._activeEffect,this,s),s.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);!o&&this.isFrozen||(s.lightsEnabled&&Lo(s,t,this._activeEffect,r,this._maxSimultaneousLights),this.bindView(n),Co(s,t,this._activeEffect,!0),this._useLogarithmicDepth&&So(r,n,s),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return St.Clone((()=>new bg(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return St.Parse((()=>new bg(e.name,t)),e,t,i)}}bg.StandardReflectance0=.05,bg.StandardReflectance90=.5,Ze([ot()],bg.prototype,"_primaryColor",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],bg.prototype,"primaryColor",void 0),Ze([ot()],bg.prototype,"__perceptualColor",void 0),Ze([rt()],bg.prototype,"_primaryColorShadowLevel",void 0),Ze([rt()],bg.prototype,"_primaryColorHighlightLevel",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],bg.prototype,"primaryColorHighlightLevel",null),Ze([nt()],bg.prototype,"_reflectionTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"reflectionTexture",void 0),Ze([rt()],bg.prototype,"_reflectionBlur",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"reflectionBlur",void 0),Ze([nt()],bg.prototype,"_diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"shadowLights",void 0),Ze([rt()],bg.prototype,"_shadowLevel",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"shadowLevel",void 0),Ze([ht()],bg.prototype,"_sceneCenter",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"sceneCenter",void 0),Ze([rt()],bg.prototype,"_opacityFresnel",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"opacityFresnel",void 0),Ze([rt()],bg.prototype,"_reflectionFresnel",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"reflectionFresnel",void 0),Ze([rt()],bg.prototype,"_reflectionFalloffDistance",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"reflectionFalloffDistance",void 0),Ze([rt()],bg.prototype,"_reflectionAmount",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"reflectionAmount",void 0),Ze([rt()],bg.prototype,"_reflectionReflectance0",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"reflectionReflectance0",void 0),Ze([rt()],bg.prototype,"_reflectionReflectance90",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"reflectionReflectance90",void 0),Ze([rt()],bg.prototype,"_useRGBColor",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"useRGBColor",void 0),Ze([rt()],bg.prototype,"_enableNoise",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"enableNoise",void 0),Ze([rt()],bg.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],bg.prototype,"maxSimultaneousLights",void 0),Ze([rt()],bg.prototype,"_shadowOnly",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],bg.prototype,"shadowOnly",void 0),Ze([_t()],bg.prototype,"_imageProcessingConfiguration",void 0),Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],bg.prototype,"enableGroundProjection",void 0),Ze([rt()],bg.prototype,"projectedGroundRadius",void 0),Ze([rt()],bg.prototype,"projectedGroundHeight",void 0),z("BABYLON.BackgroundMaterial",bg);class Tg{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new Ee(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new Ee(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:_e.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}constructor(e,t){this._errorHandler=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options={...Tg._GetDefaultOptions(t),...e},this._scene=t,this.onErrorObservable=new K,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){const t={...this._options,...e};this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new Ae(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof ya)return void(this._scene.environmentTexture=this._options.environmentTexture);const e=vg.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new ha("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;const e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};const s=this._scene.getWorldExtends((e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox)),r=s.max.subtract(s.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof hc&&this._scene.activeCamera.upperRadiusLimit&&(e=2*this._scene.activeCamera.upperRadiusLimit,t=e);const n=r.length();n>e&&(e=2*n,t=e),e*=1.1,t*=1.5,i=s.min.add(r.scale(.5)),i.y=s.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){this._ground&&!this._ground.isDisposed()||(this._ground=Wa("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((()=>{this._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new bg("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){this._groundMaterial&&(this._groundTexture||(this._options.groundTexture instanceof ya?this._groundMaterial.diffuseTexture=this._options.groundTexture:(this._groundTexture=new Pa(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture)))}_setupGroundMirrorTexture(e){const t=Pa.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new gg("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,Pa.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new Nr(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e{this._skybox=null}))),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new bg("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){this._skyboxMaterial&&(this._skyboxTexture||(this._options.skyboxTexture instanceof ya?this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture:(this._skyboxTexture=new vg(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=Pa.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture)))}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}}Tg._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",Tg._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",Tg._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class yg extends lo{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=Pa.CLAMP_ADDRESSMODE,this._texture.wrapV=Pa.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=Pa.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=Pa.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,s,r=null){super(e,s),this.onError=r,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=yg.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new K,this.onLoadObservable=new K,s=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=Boolean(i.clickToPlay),i.autoPlay=void 0===i.autoPlay||Boolean(i.autoPlay),i.loop=void 0===i.loop||Boolean(i.loop),i.size=Math.abs(i.size)||(s.activeCamera?.48*s.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=_d(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:ha.BACKSIDE},s);const n=this._material=new bg(e+"_material",s);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;const o=this._initTexture(t,s,i);if(this.texture=o,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=_d("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:ha.BACKSIDE},s),this._halfDomeMask.rotate(Xr.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce((()=>{this._setReady(!0)})),i.faceForward&&s.activeCamera){const e=s.activeCamera,t=_e.Forward(),i=_e.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(_e.Dot(t,i))}this._changeTextureMode(this._textureMode)}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case yg.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case yg.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;const e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((i=>{let s=i.isRightCamera;this._crossEye&&(s=!s),this._texture.uOffset=s?e:t}));break}case yg.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0}))}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}}yg.MODE_MONOSCOPIC=0,yg.MODE_TOPBOTTOM=1,yg.MODE_SIDEBYSIDE=2;class Sg extends yg{get photoTexture(){return this.texture}set photoTexture(e){this.texture=e}get imageMode(){return this.textureMode}set imageMode(e){this.textureMode=e}_initTexture(e,t,i){return new Pa(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,(()=>{this.onLoadObservable.notifyObservers()}),((e,t)=>{this.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),this.onError&&this.onError(e,t)}))}}Sg.MODE_MONOSCOPIC=yg.MODE_MONOSCOPIC,Sg.MODE_TOPBOTTOM=yg.MODE_TOPBOTTOM,Sg.MODE_SIDEBYSIDE=yg.MODE_SIDEBYSIDE;let Cg=0;const Eg=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const i=e._blockEntityCollection;e._blockEntityCollection=!1;const s=Pa.CreateFromBase64String("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==","EnvironmentBRDFTexture"+Cg++,e,!0,!1,Pa.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;const r=e.getEngine().getLoadedTexturesCache(),n=r.indexOf(s.getInternalTexture());-1!==n&&r.splice(n,1),s.isRGBD=!0,s.wrapU=Pa.CLAMP_ADDRESSMODE,s.wrapV=Pa.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=s,e.useDelayedTextureLoading=t,mp.ExpandRGBDTexture(s);const o=e.getEngine().onContextRestoredObservable.add((()=>{s.isRGBD=!0;const t=e.onBeforeRenderObservable.add((()=>{s.isReady()&&(e.onBeforeRenderObservable.remove(t),mp.ExpandRGBDTexture(s))}))}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(o)}))}return e.environmentBRDFTexture},Ag={GetEnvironmentBRDFTexture:Eg};class Pg extends xl{constructor(){super(...arguments),this.BRDF_V_HEIGHT_CORRELATED=!1,this.MS_BRDF_ENERGY_CONSERVATION=!1,this.SPHERICAL_HARMONICS=!1,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1}}class Ig extends nu{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new Pg,t),this._useEnergyConservation=Ig.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=Ig.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=Ig.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=Ig.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=Ig.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=Ig.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=Ig.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=Ig.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation}getClassName(){return"PBRBRDFConfiguration"}}Ig.DEFAULT_USE_ENERGY_CONSERVATION=!0,Ig.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,Ig.DEFAULT_USE_SPHERICAL_HARMONICS=!0,Ig.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],Ig.prototype,"useEnergyConservation",void 0),Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],Ig.prototype,"useSmithVisibilityHeightCorrelated",void 0),Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],Ig.prototype,"useSphericalHarmonics",void 0),Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],Ig.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);Bi.IncludesShadersStore.pbrFragmentDeclaration="uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor;\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REALTIME_FILTERING\nuniform vec2 vReflectionFilteringInfo;\n#endif\nuniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams;\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#endif\n#ifdef IRIDESCENCE\nuniform vec4 vIridescenceParams;\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\nuniform vec4 vSheenColor;\n#ifdef SHEEN_ROUGHNESS\nuniform float vSheenRoughness;\n#endif\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;\n#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\n#endif\n#ifdef SS_DISPERSION\nuniform float dispersion;\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;\n#endif\nuniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity;uniform vec4 vTranslucencyColor;\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nuniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;\n#endif\n#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\n#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;\n#else\nuniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;\n#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";Bi.IncludesShadersStore.pbrUboDeclaration="layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";Bi.IncludesShadersStore.pbrFragmentExtraDeclaration="varying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#include[1..7]\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n";Bi.IncludesShadersStore.samplerFragmentAlternateDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n#endif\n";Bi.IncludesShadersStore.pbrFragmentSamplersDeclaration="#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform sampler2D clearCoatRoughnessSampler;\n#endif\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform sampler2D sheenRoughnessSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh;\n#endif\n#endif\n#endif\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)\n#endif\n";Bi.IncludesShadersStore.subSurfaceScatteringFunctions="bool testLightingForSSS(float diffusionProfile)\n{return diffusionProfile<1.;}";Bi.IncludesShadersStore.importanceSampling="vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { \nfloat phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}";Bi.IncludesShadersStore.pbrHelperFunctions="#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{return square(roughness)+MINIMUMVARIANCE;}\nfloat fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}\n#else\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;}\n#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);}\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);return clearCoatAbsorption;}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;}\n#endif\n";Bi.IncludesShadersStore.harmonicsFunctions="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nvec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00\n+ vSphericalL1_1*(normal.y)\n+ vSphericalL10*(normal.z)\n+ vSphericalL11*(normal.x)\n+ vSphericalL2_2*(normal.y*normal.x)\n+ vSphericalL2_1*(normal.y*normal.z)\n+ vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+ vSphericalL21*(normal.z*normal.x)\n+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}\n#else\nvec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;}\n#endif\n#endif\n";Bi.IncludesShadersStore.pbrDirectLightingSetupFunctions="struct preLightingInfo\n{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness;\n#ifdef IRIDESCENCE\nfloat iridescenceIntensity;\n#endif\n};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;}";Bi.IncludesShadersStore.pbrDirectLightingFalloffFunctions="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{return max(0.,1.0-length(lightOffset)/range);}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{return 1.0/maxEps(lightDistanceSquared);}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)\n{falloff=max(0.,pow(cosAngle,exponent));}\nreturn falloff;}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}";Bi.IncludesShadersStore.pbrBRDFFunctions="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;\n#endif\nreturn reflectance;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#endif\nreturn reflectance;}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfloat getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)\n{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\n/**\n* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.\n* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table\n*/\nvec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}\n#endif\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\n#ifdef CLEARCOAT\nvec3 getR0RemappedForClearCoat(vec3 f0) {\n#ifdef CLEARCOAT_DEFAULTIOR\n#ifdef MOBILE\nreturn saturate(f0*(f0*0.526868+0.529324)-0.0482256);\n#else\nreturn saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);\n#endif\n#else\nvec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t);\n#endif\n}\n#endif\n#ifdef IRIDESCENCE\nconst mat3 XYZ_TO_REC709=mat3(\n3.2404542,-0.9692660, 0.0556434,\n-1.5371385, 1.8760108,-0.2040259,\n-0.4985314, 0.0415560, 1.0572252\n);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}\nvec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));}\nfloat getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));}\nvec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;}\nvec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;}\nfloat cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose(),this._bumpTexture?.dispose(),this._tintTexture?.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}}Mg._DefaultIndexOfRefraction=1.5,Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"isEnabled",void 0),Ze([rt()],Mg.prototype,"intensity",void 0),Ze([rt()],Mg.prototype,"roughness",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"indexOfRefraction",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"texture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"useRoughnessFromMainTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"textureRoughness",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"remapF0OnInterfaceChange",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"bumpTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"isTintEnabled",void 0),Ze([ot()],Mg.prototype,"tintColor",void 0),Ze([rt()],Mg.prototype,"tintColorAtDistance",void 0),Ze([rt()],Mg.prototype,"tintThickness",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Mg.prototype,"tintTexture",void 0);class Og extends xl{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0}}class Dg extends nu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new Og,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=Dg._DefaultMinimumThickness,this.maximumThickness=Dg._DefaultMaximumThickness,this.indexOfRefraction=Dg._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&$c.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&$c.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&$c.IridescenceTextureEnabled?Mo(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&$c.IridescenceTextureEnabled?Mo(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||((this._texture||this._thicknessTexture)&&$c.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._thicknessTexture?.coordinatesIndex??0,this._thicknessTexture?.level??0),this._texture&&Oo(this._texture,e,"iridescence"),this._thicknessTexture&&Oo(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&$c.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&$c.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){e&&(this._texture?.dispose(),this._thicknessTexture?.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}}Dg._DefaultMinimumThickness=100,Dg._DefaultMaximumThickness=400,Dg._DefaultIndexOfRefraction=1.3,Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Dg.prototype,"isEnabled",void 0),Ze([rt()],Dg.prototype,"intensity",void 0),Ze([rt()],Dg.prototype,"minimumThickness",void 0),Ze([rt()],Dg.prototype,"maximumThickness",void 0),Ze([rt()],Dg.prototype,"indexOfRefraction",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Dg.prototype,"texture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Dg.prototype,"thicknessTexture",void 0);class wg extends xl{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class Ng extends nu{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new wg,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new de(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&$c.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(er.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&$c.AnisotropicTextureEnabled?Mo(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1),e._areMiscDirty&&(e.ANISOTROPIC_LEGACY=this._legacy)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.ANISOTROPIC_LEGACY=!1)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&$c.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),Oo(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&$c.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,i){super.parse(e,t,i),void 0===e.legacy&&(this.legacy=!0)}}Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Ng.prototype,"isEnabled",void 0),Ze([rt()],Ng.prototype,"intensity",void 0),Ze([lt()],Ng.prototype,"direction",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Ng.prototype,"texture",void 0),Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],Ng.prototype,"legacy",void 0);class Fg extends xl{constructor(){super(...arguments),this.SHEEN=!1,this.SHEEN_TEXTURE=!1,this.SHEEN_GAMMATEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS=!1,this.SHEEN_TEXTUREDIRECTUV=0,this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,this.SHEEN_LINKWITHALBEDO=!1,this.SHEEN_ROUGHNESS=!1,this.SHEEN_ALBEDOSCALING=!1,this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1}}class Lg extends nu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new Fg,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=Ee.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&$c.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&$c.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=null!==this._roughness,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&$c.SheenTextureEnabled?(Mo(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&$c.SheenTextureEnabled?Mo(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,s){if(!this._isEnabled)return;const r=s.materialDefines,n=this._material.isFrozen;e.useUbo&&n&&e.isSync||((this._texture||this._textureRoughness)&&$c.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&Oo(this._texture,e,"sheen"),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Oo(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),null!==this._roughness&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&$c.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&$c.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}}Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Lg.prototype,"isEnabled",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Lg.prototype,"linkSheenWithAlbedo",void 0),Ze([rt()],Lg.prototype,"intensity",void 0),Ze([ot()],Lg.prototype,"color",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Lg.prototype,"texture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Lg.prototype,"useRoughnessFromMainTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Lg.prototype,"roughness",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Lg.prototype,"textureRoughness",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Lg.prototype,"albedoScaling",void 0);class Bg extends xl{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_SCATTERING=!1,this.SS_DISPERSION=!1,this.SS_THICKNESSANDMASK_TEXTURE=!1,this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,this.SS_HAS_THICKNESS=!1,this.SS_REFRACTIONINTENSITY_TEXTURE=!1,this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,this.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0,this.SS_REFRACTIONMAP_3D=!1,this.SS_REFRACTIONMAP_OPPOSITEZ=!1,this.SS_LODINREFRACTIONALPHA=!1,this.SS_GAMMAREFRACTION=!1,this.SS_RGBDREFRACTION=!1,this.SS_LINEARSPECULARREFRACTION=!1,this.SS_LINKREFRACTIONTOTRANSPARENCY=!1,this.SS_ALBEDOFORREFRACTIONTINT=!1,this.SS_ALBEDOFORTRANSLUCENCYTINT=!1,this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.SS_USE_THICKNESS_AS_DEPTH=!1,this.SS_USE_GLTF_TEXTURES=!1}}class kg extends nu{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){this._volumeIndexOfRefraction=e>=1?e:-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new Bg,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isDispersionEnabled=!1,this.isDispersionEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this.useAlbedoToTintRefraction=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=Ee.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=Ee.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this.translucencyColor=null,this._translucencyColorTexture=null,this.translucencyColorTexture=null,this._useGltfStyleTextures=!0,this.useGltfStyleTextures=!0,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&$c.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;if(this._translucencyColorTexture&&$c.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&$c.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return e.SUBSURFACE=!1,e.SS_DISPERSION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,void(e.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0);if(e._areTexturesDirty){if(e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&$c.ThicknessTextureEnabled&&Mo(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&$c.RefractionIntensityTextureEnabled&&Mo(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&$c.TranslucencyIntensityTextureEnabled&&Mo(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&&$c.TranslucencyColorTextureEnabled&&Mo(this._translucencyColorTexture,e,"SS_TRANSLUCENCYCOLOR_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._refractionIntensityTexture,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._translucencyIntensityTexture,this._isRefractionEnabled&&t.texturesEnabled){const i=this._getRefractionTexture(t);i&&$c.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;s.getRenderingMesh().getWorldMatrix().decompose(ve.Vector3[0]);const r=Math.max(Math.abs(ve.Vector3[0].x),Math.abs(ve.Vector3[0].y),Math.abs(ve.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*r,(this.maximumThickness-this.minimumThickness)*r)}bindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const r=s.materialDefines,n=this._material.isFrozen,o=this._material.realTimeFiltering,a=r.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&$c.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),Oo(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&$c.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),Oo(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&&$c.TranslucencyColorTextureEnabled&&r.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),Oo(this._translucencyColorTexture,e,"translucencyColor")),l&&$c.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;l.isCube||l.depth&&(t=l.depth);const i=l.getSize().width,s=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",l.level,1/s,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",i,be.Log2(i)),l.boundingBoxSize){const t=l;e.updateVector3("vRefractionPosition",t.boundingBoxPosition),e.updateVector3("vRefractionSize",t.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateColor4("vTranslucencyColor",this.translucencyColor??this.tintColor,0),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&$c.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&$c.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&$c.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&&$c.TranslucencyColorTextureEnabled&&r.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),l&&$c.RefractionTextureEnabled&&(a?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){$c.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e||this._refractionIntensityTexture===e||this._translucencyIntensityTexture===e||this._translucencyColorTexture===e}hasRenderTargetTextures(){return!!($c.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture),this._translucencyColorTexture&&e.push(this._translucencyColorTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),this._translucencyColorTexture&&this._translucencyColorTexture.animations&&this._translucencyColorTexture.animations.length>0&&e.push(this._translucencyColorTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose(),this._translucencyColorTexture&&this._translucencyColorTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","translucencyColorSampler")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"},{name:"vTranslucencyColor",size:4,type:"vec4"},{name:"vTranslucencyColorInfos",size:2,type:"vec2"},{name:"translucencyColorMatrix",size:16,type:"mat4"}]}}}Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"isRefractionEnabled",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"isTranslucencyEnabled",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"isDispersionEnabled",void 0),Ze([rt(),st("_markScenePrePassDirty")],kg.prototype,"isScatteringEnabled",void 0),Ze([rt()],kg.prototype,"_scatteringDiffusionProfileIndex",void 0),Ze([rt()],kg.prototype,"refractionIntensity",void 0),Ze([rt()],kg.prototype,"translucencyIntensity",void 0),Ze([rt()],kg.prototype,"useAlbedoToTintRefraction",void 0),Ze([rt()],kg.prototype,"useAlbedoToTintTranslucency",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"thicknessTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"refractionTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"indexOfRefraction",void 0),Ze([rt()],kg.prototype,"_volumeIndexOfRefraction",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"volumeIndexOfRefraction",null),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"invertRefractionY",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"linkRefractionWithTransparency",void 0),Ze([rt()],kg.prototype,"minimumThickness",void 0),Ze([rt()],kg.prototype,"maximumThickness",void 0),Ze([rt()],kg.prototype,"useThicknessAsDepth",void 0),Ze([ot()],kg.prototype,"tintColor",void 0),Ze([rt()],kg.prototype,"tintColorAtDistance",void 0),Ze([rt()],kg.prototype,"dispersion",void 0),Ze([ot()],kg.prototype,"diffusionDistance",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"useMaskFromThicknessTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"refractionIntensityTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"translucencyIntensityTexture",void 0),Ze([ot()],kg.prototype,"translucencyColor",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"translucencyColorTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],kg.prototype,"useGltfStyleTextures",void 0);const Vg={effect:null,subMesh:null};class Ug extends xl{constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class Gg extends ml{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new pe(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=Gg.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._reflectivityTexture=null,this._metallicTexture=null,this._metallic=null,this._roughness=null,this._metallicF0Factor=1,this._metallicReflectanceColor=Ee.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new Ee(0,0,0),this._albedoColor=new Ee(1,1,1),this._reflectivityColor=new Ee(1,1,1),this._reflectionColor=new Ee(1,1,1),this._emissiveColor=new Ee(0,0,0),this._microSurface=.9,this._useLightmapAsShadowmap=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromAlbedoTexture=!1,this._useSpecularOverAlpha=!0,this._useMicroSurfaceFromReflectivityMapAlpha=!1,this._useRoughnessFromMetallicTextureAlpha=!0,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallnessFromMetallicTextureBlue=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useAmbientInGrayScale=!1,this._useAutoMicroSurfaceFromReflectivityMap=!1,this._lightFalloff=Gg.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._forceAlphaTest=!1,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new Fs(16),this._globalAmbientColor=new Ee(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new Ig(this),this.clearCoat=new Mg(this),this.iridescence=new Dg(this),this.anisotropy=new Ng(this),this.sheen=new Lg(this),this.subSurface=new kg(this),this.detailMap=new au(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),$c.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=Eg(this.getScene()),this.prePassConfiguration=new Kc}get hasRenderTargetTextures(){return!!($c.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){return this._transparencyMode===Gg.PBRMATERIAL_OPAQUE||this._transparencyMode===Gg.PBRMATERIAL_ALPHATEST||this.subSurface?.disableAlphaBlending}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){return!!this._forceAlphaTest||!this.subSurface?.disableAlphaBlending&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Gg.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==Gg.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(fo.GetDefineNames,this._eventInfo),t.materialDefines=new Ug(this._eventInfo.defineNames));const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=this.getScene(),o=n.getEngine();if(r._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&$c.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&$c.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&$c.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&$c.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&e.getInternalTexture()?._sphericalPolynomialPromise)return!1}if(this._lightmapTexture&&$c.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&$c.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if($c.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking())return!1;if(this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&$c.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&$c.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(r._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;o.getCaps().standardDerivatives||e.isVerticesDataPresent(er.NormalKind)||(e.createNormals(!0),Ne.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const a=t.effect,l=r._areLightsDisposed;let h=this._prepareEffect(e,r,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),c=!1;if(h)if(this._onEffectCreatedObservable&&(Vg.effect=h,Vg.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Vg)),this.allowShaderHotSwapping&&a&&!h.isReady()){if(h=a,r.markAsUnprocessed(),c=this.isFrozen,l)return r._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(h,r,this._materialContext);return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!c,s._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),0))}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,i=null,s=null,r=null,n=null,o){if(this._prepareDefines(e,t,r,n,o),!t.isDirty)return null;t.markAsProcessed();const a=this.getScene().getEngine(),l=new Ll;let h=0;t.USESPHERICALINVERTEX&&l.addFallback(h++,"USESPHERICALINVERTEX"),t.FOG&&l.addFallback(h,"FOG"),t.SPECULARAA&&l.addFallback(h,"SPECULARAA"),t.POINTSIZE&&l.addFallback(h,"POINTSIZE"),t.LOGARITHMICDEPTH&&l.addFallback(h,"LOGARITHMICDEPTH"),t.PARALLAX&&l.addFallback(h,"PARALLAX"),t.PARALLAX_RHS&&l.addFallback(h,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&l.addFallback(h++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&l.addFallback(h++,"ENVIRONMENTBRDF"),t.TANGENT&&l.addFallback(h++,"TANGENT"),t.BUMP&&l.addFallback(h++,"BUMP"),h=Vo(t,l,this._maxSimultaneousLights,h++),t.SPECULARTERM&&l.addFallback(h++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&l.addFallback(h++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&l.addFallback(h++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&l.addFallback(h++,"LIGHTMAP"),t.NORMAL&&l.addFallback(h++,"NORMAL"),t.AMBIENT&&l.addFallback(h++,"AMBIENT"),t.EMISSIVE&&l.addFallback(h++,"EMISSIVE"),t.VERTEXCOLOR&&l.addFallback(h++,"VERTEXCOLOR"),t.MORPHTARGETS&&l.addFallback(h++,"MORPHTARGETS"),t.MULTIVIEW&&l.addFallback(0,"MULTIVIEW");const c=[er.PositionKind];t.NORMAL&&c.push(er.NormalKind),t.TANGENT&&c.push(er.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&c.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&c.push(er.ColorKind),Bo(c,e,t,l),ko(c,t),Ao(c,e,t),Do(c,0,t);let u="pbr";const d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],_=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],p=["Material","Scene","Mesh"],f={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=l,this._eventInfo.fallbackRank=h,this._eventInfo.defines=t,this._eventInfo.uniforms=d,this._eventInfo.attributes=c,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=p,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=f,this._callbackPluginEventGeneric(fo.PrepareEffect,this._eventInfo),Kc.AddUniforms(d),Kc.AddSamplers(_),mo(d),zs&&(zs.PrepareUniforms(d,t),zs.PrepareSamplers(_,t)),ea({uniformsNames:d,uniformBuffersNames:p,samplers:_,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const m={};this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,d,p,_,t,c,m));const g=t.toString(),v=a.createEffect(u,{attributes:c,uniformsNames:d,uniformBuffersNames:p,samplers:_,defines:g,fallbacks:l,onCompiled:i,onError:s,indexParameters:f,processFinalCode:m.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},a);return this._eventInfo.customCode=void 0,v}_prepareDefines(e,t,i=null,s=null,r=!1){const n=this.getScene(),o=n.getEngine();zo(n,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,Ko(n,t);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(qo(n,t,this.canRenderToMRT&&!a),$o(n,t,a),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!1;if(n.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&$c.DiffuseTextureEnabled?(Mo(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&$c.AmbientTextureEnabled?(Mo(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&$c.OpacityTextureEnabled?(Mo(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&$c.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(t.NUM_SAMPLES=""+this.realTimeFilteringQuality,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===Pa.INVCUBIC_MODE,t.REFLECTIONMAP_3D=e.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.coordinatesMode){case Pa.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case Pa.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case Pa.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case Pa.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case Pa.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case Pa.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Pa.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Pa.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Pa.CUBIC_MODE:case Pa.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==Pa.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||o.getCaps().maxVaryingVectors<=8?t.USESPHERICALINVERTEX=!1:t.USESPHERICALINVERTEX=!0))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;this._lightmapTexture&&$c.LightmapTextureEnabled?(Mo(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&$c.EmissiveTextureEnabled?(Mo(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,$c.SpecularTextureEnabled?(this._metallicTexture?(Mo(this._metallicTexture,t,"REFLECTIVITY"),t.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,t.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,t.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,t.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,t.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(Mo(this._reflectivityTexture,t,"REFLECTIVITY"),t.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,t.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,t.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):t.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture?(t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture,this._metallicReflectanceTexture?(Mo(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(Mo(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1):(t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1),this._microSurfaceTexture?Mo(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1):(t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1),o.getCaps().standardDerivatives&&this._bumpTexture&&$c.BumpTextureEnabled&&!this._disableBumpMap?(Mo(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&$c.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=n.useRightHandedSystem,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAX_RHS=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&$c.ReflectionTextureEnabled?(t.ENVIRONMENTBRDF=!0,t.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(t.ENVIRONMENTBRDF=!1,t.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?t.ALPHAFROMALBEDO=!0:t.ALPHAFROMALBEDO=!1}t.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===Gg.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Gg.LIGHTFALLOFF_GLTF?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!0):(t.USEPHYSICALLIGHTFALLOFF=!0,t.USEGLTFLIGHTFALLOFF=!1),t.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?t.TWOSIDEDLIGHTING=!0:t.TWOSIDEDLIGHTING=!1,t.SPECULARAA=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(er.NormalKind),t.DEBUGMODE=this._debugMode),Ho(n,o,this,t,!!i,s,r),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),jo(e,t,!0,!0,!0,this._transparencyMode!==Gg.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const s={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(fo.GetDefineNames,this._eventInfo);const r=new Ug(this._eventInfo.defineNames),n=this._prepareEffect(e,r,void 0,void 0,s.useInstances,s.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(Vg.effect=n,Vg.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Vg)),n.isReady()?t&&t(this):n.onCompileObservable.add((()=>{t&&t(this)}))}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionFilteringInfo",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("reflectionMatrix",16),e.addUniform("vReflectionColor",3),e.addUniform("vAlbedoColor",4),e.addUniform("vLightingIntensity",4),e.addUniform("vReflectionMicrosurfaceInfos",3),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),e.addUniform("vSphericalL00",3),e.addUniform("vSphericalL1_1",3),e.addUniform("vSphericalL10",3),e.addUniform("vSphericalL11",3),e.addUniform("vSphericalL2_2",3),e.addUniform("vSphericalL2_1",3),e.addUniform("vSphericalL20",3),e.addUniform("vSphericalL21",3),e.addUniform("vSphericalL22",3),e.addUniform("vSphericalX",3),e.addUniform("vSphericalY",3),e.addUniform("vSphericalZ",3),e.addUniform("vSphericalXX_ZZ",3),e.addUniform("vSphericalYY_ZZ",3),e.addUniform("vSphericalZZ",3),e.addUniform("vSphericalXY",3),e.addUniform("vSphericalYZ",3),e.addUniform("vSphericalZX",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e);const o=s.getEngine();this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const a=this._mustRebind(s,n,i,t.visibility);wo(t,this._activeEffect,this.prePassConfiguration);let l=null;const h=this._uniformBuffer;if(a){if(this.bindViewProjection(n),l=this._getReflectionTexture(),!h.useUbo||!this.isFrozen||!h.isSync||i._drawWrapper._forceRebindOnNextCall){if(s.texturesEnabled){if(this._albedoTexture&&$c.DiffuseTextureEnabled&&(h.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),Oo(this._albedoTexture,h,"albedo")),this._ambientTexture&&$c.AmbientTextureEnabled&&(h.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),Oo(this._ambientTexture,h,"ambient")),this._opacityTexture&&$c.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Oo(this._opacityTexture,h,"opacity")),l&&$c.ReflectionTextureEnabled){if(h.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),h.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){const e=l;h.updateVector3("vReflectionPosition",e.boundingBoxPosition),h.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=l.getSize().width;h.updateFloat2("vReflectionFilteringInfo",e,be.Log2(e))}if(!r.USEIRRADIANCEMAP){const e=l.sphericalPolynomial;if(r.USESPHERICALFROMREFLECTIONMAP&&e)if(r.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;h.updateVector3("vSphericalL00",t.l00),h.updateVector3("vSphericalL1_1",t.l1_1),h.updateVector3("vSphericalL10",t.l10),h.updateVector3("vSphericalL11",t.l11),h.updateVector3("vSphericalL2_2",t.l2_2),h.updateVector3("vSphericalL2_1",t.l2_1),h.updateVector3("vSphericalL20",t.l20),h.updateVector3("vSphericalL21",t.l21),h.updateVector3("vSphericalL22",t.l22)}else h.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),h.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),h.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),h.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),h.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),h.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),h.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),h.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),h.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}h.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}this._emissiveTexture&&$c.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Oo(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&$c.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Oo(this._lightmapTexture,h,"lightmap")),$c.SpecularTextureEnabled&&(this._metallicTexture?(h.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),Oo(this._metallicTexture,h,"reflectivity")):this._reflectivityTexture&&(h.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),Oo(this._reflectivityTexture,h,"reflectivity")),this._metallicReflectanceTexture&&(h.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),Oo(this._metallicReflectanceTexture,h,"metallicReflectance")),this._reflectanceTexture&&r.REFLECTANCE&&(h.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),Oo(this._reflectanceTexture,h,"reflectance")),this._microSurfaceTexture&&(h.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),Oo(this._microSurfaceTexture,h,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&&$c.BumpTextureEnabled&&!this._disableBumpMap&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),Oo(this._bumpTexture,h,"bump"),s._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),r.METALLICWORKFLOW){Pe.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,Pe.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,h.updateColor4("vReflectivityColor",Pe.Color3[0],1);const e=this.subSurface?._indexOfRefraction??1.5,t=1,i=Math.pow((e-t)/(e+t),2);this._metallicReflectanceColor.scaleToRef(i*this._metallicF0Factor,Pe.Color3[0]);const s=this._metallicF0Factor;h.updateColor4("vMetallicReflectanceFactors",Pe.Color3[0],s)}else h.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);h.updateColor3("vEmissiveColor",$c.EmissiveTextureEnabled?this._emissiveColor:Ee.BlackReadOnly),h.updateColor3("vReflectionColor",this._reflectionColor),!r.SS_REFRACTION&&this.subSurface?._linkRefractionWithTransparency?h.updateColor4("vAlbedoColor",this._albedoColor,1):h.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*s.environmentIntensity,this._lightingInfos.w=this._specularIntensity,h.updateVector4("vLightingIntensity",this._lightingInfos),s.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor),h.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}s.texturesEnabled&&(this._albedoTexture&&$c.DiffuseTextureEnabled&&h.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&$c.AmbientTextureEnabled&&h.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&$c.OpacityTextureEnabled&&h.setTexture("opacitySampler",this._opacityTexture),l&&$c.ReflectionTextureEnabled&&(r.LODBASEDMICROSFURACE?h.setTexture("reflectionSampler",l):(h.setTexture("reflectionSampler",l._lodTextureMid||l),h.setTexture("reflectionSamplerLow",l._lodTextureLow||l),h.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)),r.USEIRRADIANCEMAP&&h.setTexture("irradianceSampler",l.irradianceTexture)),r.ENVIRONMENTBRDF&&h.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&$c.EmissiveTextureEnabled&&h.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&$c.LightmapTextureEnabled&&h.setTexture("lightmapSampler",this._lightmapTexture),$c.SpecularTextureEnabled&&(this._metallicTexture?h.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&h.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&h.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&r.REFLECTANCE&&h.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&h.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&&$c.BumpTextureEnabled&&!this._disableBumpMap&&h.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),xo(this._activeEffect,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!a&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&Lo(s,t,this._activeEffect,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE||l||this.subSurface.refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),Co(s,t,this._activeEffect,!0),r.NUM_MORPH_INFLUENCERS&&Io(t,this._activeEffect),r.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,r.INSTANCES),this._imageProcessingConfiguration.bind(this._activeEffect),So(r,this._activeEffect,s)),this._afterBind(t,this._activeEffect,i),h.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._albedoTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e}setPrePassRenderer(){if(!this.subSurface?.isScatteringEnabled)return!1;const e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._albedoTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._metallicTexture?.dispose(),this._reflectivityTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._metallicReflectanceTexture?.dispose(),this._reflectanceTexture?.dispose(),this._microSurfaceTexture?.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}Gg.PBRMATERIAL_OPAQUE=ta.MATERIAL_OPAQUE,Gg.PBRMATERIAL_ALPHATEST=ta.MATERIAL_ALPHATEST,Gg.PBRMATERIAL_ALPHABLEND=ta.MATERIAL_ALPHABLEND,Gg.PBRMATERIAL_ALPHATESTANDBLEND=ta.MATERIAL_ALPHATESTANDBLEND,Gg.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,Gg.LIGHTFALLOFF_PHYSICAL=0,Gg.LIGHTFALLOFF_GLTF=1,Gg.LIGHTFALLOFF_STANDARD=2,Ze([_t()],Gg.prototype,"_imageProcessingConfiguration",void 0),Ze([st("_markAllSubMeshesAsMiscDirty")],Gg.prototype,"debugMode",void 0);class zg extends Gg{get refractionTexture(){return this.subSurface.refractionTexture}set refractionTexture(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)}get indexOfRefraction(){return this.subSurface.indexOfRefraction}set indexOfRefraction(e){this.subSurface.indexOfRefraction=e}get invertRefractionY(){return this.subSurface.invertRefractionY}set invertRefractionY(e){this.subSurface.invertRefractionY=e}get linkRefractionWithTransparency(){return this.subSurface.linkRefractionWithTransparency}set linkRefractionWithTransparency(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)}get usePhysicalLightFalloff(){return this._lightFalloff===Gg.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Gg.LIGHTFALLOFF_PHYSICAL:Gg.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Gg.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Gg.LIGHTFALLOFF_GLTF:Gg.LIGHTFALLOFF_STANDARD)}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=zg.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=Ee.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new Ee(0,0,0),this.albedoColor=new Ee(1,1,1),this.reflectivityColor=new Ee(1,1,1),this.reflectionColor=new Ee(1,1,1),this.emissiveColor=new Ee(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=Eg(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const s=St.Clone((()=>new zg(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return s.id=e,s.name=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const s=St.Parse((()=>new zg(e.name,t)),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),ta._ParsePlugins(e,s,t,i),e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}zg.PBRMATERIAL_OPAQUE=Gg.PBRMATERIAL_OPAQUE,zg.PBRMATERIAL_ALPHATEST=Gg.PBRMATERIAL_ALPHATEST,zg.PBRMATERIAL_ALPHABLEND=Gg.PBRMATERIAL_ALPHABLEND,zg.PBRMATERIAL_ALPHATESTANDBLEND=Gg.PBRMATERIAL_ALPHATESTANDBLEND,zg.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Gg.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"directIntensity",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"emissiveIntensity",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"environmentIntensity",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"specularIntensity",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"disableBumpMap",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"albedoTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"ambientTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"ambientTextureStrength",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesAndMiscDirty")],zg.prototype,"opacityTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"reflectionTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"emissiveTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"reflectivityTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"metallicTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"metallic",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"roughness",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"metallicF0Factor",void 0),Ze([ot(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"metallicReflectanceColor",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"metallicReflectanceTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"reflectanceTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"microSurfaceTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"bumpTexture",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty",null)],zg.prototype,"lightmapTexture",void 0),Ze([ot("ambient"),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"ambientColor",void 0),Ze([ot("albedo"),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"albedoColor",void 0),Ze([ot("reflectivity"),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"reflectivityColor",void 0),Ze([ot("reflection"),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"reflectionColor",void 0),Ze([ot("emissive"),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"emissiveColor",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"microSurface",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useLightmapAsShadowmap",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesAndMiscDirty")],zg.prototype,"useAlphaFromAlbedoTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesAndMiscDirty")],zg.prototype,"forceAlphaTest",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesAndMiscDirty")],zg.prototype,"alphaCutOff",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useSpecularOverAlpha",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useRoughnessFromMetallicTextureGreen",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useMetallnessFromMetallicTextureBlue",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useAmbientInGrayScale",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),Ze([rt()],zg.prototype,"usePhysicalLightFalloff",null),Ze([rt()],zg.prototype,"useGLTFLightFalloff",null),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useRadianceOverAlpha",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useObjectSpaceNormalMap",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useParallax",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useParallaxOcclusion",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"parallaxScaleBias",void 0),Ze([rt(),st("_markAllSubMeshesAsLightsDirty")],zg.prototype,"disableLighting",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"forceIrradianceInFragment",void 0),Ze([rt(),st("_markAllSubMeshesAsLightsDirty")],zg.prototype,"maxSimultaneousLights",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"invertNormalMapX",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"invertNormalMapY",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"twoSidedLighting",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useAlphaFresnel",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useLinearAlphaFresnel",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"environmentBRDFTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"forceNormalForward",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"enableSpecularAntiAliasing",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useHorizonOcclusion",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],zg.prototype,"useRadianceOcclusion",void 0),Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],zg.prototype,"unlit",void 0),Ze([rt(),st("_markAllSubMeshesAsMiscDirty")],zg.prototype,"applyDecalMapAfterDetailMap",void 0),z("BABYLON.PBRMaterial",zg);class Wg{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,s){const r=t.getEngine();let n,o=!1,a=1e3;if(Array.isArray(e))for(let i=0;i1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),_p.UploadDDSLevels(r,t,s,n,o,6,-1,i),n.isFourCC||1!==n.mipmapCount?a=n.mipmapCount-1:r.generateMipMapsForCubemap(t)}else{const s=e;n=_p.GetDDSInfo(s),t.width=n.width,t.height=n.height,i&&(n.sphericalPolynomial=new j_),o=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),_p.UploadDDSLevels(r,t,s,n,o,6),n.isFourCC||1!==n.mipmapCount?a=n.mipmapCount-1:r.generateMipMapsForCubemap(t,!1)}r._setCubeMapTextureParams(t,o,a),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s({isDDS:!0,width:t.width,info:n,data:e,texture:t})}loadData(e,t,i){const s=_p.GetDDSInfo(e),r=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps&&s.width>>s.mipmapCount-1==1;i(s.width,s.height,r,s.isFourCC,(()=>{_p.UploadDDSLevels(t.getEngine(),t,e,s,r,1)}))}}oo._TextureLoaders.push(new Wg);class Hg{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=bp(e);if(n){t.width=n.width,t.height=n.width;try{Ip(t,n),Ep(t,e,n).then((()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}),(e=>{r?.("Can not upload environment levels",e)}))}catch(e){r?.("Can not upload environment file",e)}}else r&&r("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}oo._TextureLoaders.push(new Hg);class Xg{constructor(e,t){if(this.data=e,this.isInvalid=!1,!Xg.IsValid(e))return this.isInvalid=!0,void Ne.Error("texture missing KTX identifier");const i=Uint32Array.BYTES_PER_ELEMENT,s=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),r=67305985===s.getUint32(0,!0);return this.glType=s.getUint32(1*i,r),this.glTypeSize=s.getUint32(2*i,r),this.glFormat=s.getUint32(3*i,r),this.glInternalFormat=s.getUint32(4*i,r),this.glBaseInternalFormat=s.getUint32(5*i,r),this.pixelWidth=s.getUint32(6*i,r),this.pixelHeight=s.getUint32(7*i,r),this.pixelDepth=s.getUint32(8*i,r),this.numberOfArrayElements=s.getUint32(9*i,r),this.numberOfFaces=s.getUint32(10*i,r),this.numberOfMipmapLevels=s.getUint32(11*i,r),this.bytesOfKeyValueData=s.getUint32(12*i,r),0!==this.glType?(Ne.Error("only compressed formats currently supported"),void(this.isInvalid=!0)):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?(Ne.Error("only 2D textures currently supported"),void(this.isInvalid=!0)):0!==this.numberOfArrayElements?(Ne.Error("texture arrays not currently supported"),void(this.isInvalid=!0)):this.numberOfFaces!==t?(Ne.Error("number of faces expected"+t+", but found "+this.numberOfFaces),void(this.isInvalid=!0)):void(this.loadType=Xg.COMPRESSED_2D))}uploadLevels(e,t){switch(this.loadType){case Xg.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case Xg.TEX_2D:case Xg.COMPRESSED_3D:case Xg.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=Xg.HEADER_LEN+this.bytesOfKeyValueData,s=this.pixelWidth,r=this.pixelHeight;const n=t?this.numberOfMipmapLevels:1;for(let t=0;t=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}Xg.HEADER_LEN=64,Xg.COMPRESSED_2D=0,Xg.COMPRESSED_3D=1,Xg.TEX_2D=2,Xg.TEX_3D=3;class Yg{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map((e=>({workerPromise:Promise.resolve(e),idle:!0})))}dispose(){for(const e of this._workerInfos)e.workerPromise.then((e=>{e.terminate()}));this._workerInfos.length=0,this._pendingActions.length=0}push(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)}_executeOnIdleWorker(e){for(const t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then((i=>{t(i,(()=>{const t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0}))}))}}class Qg extends Yg{constructor(e,t,i=Qg.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,(()=>{s(),e.idle&&(e.timeoutId=setTimeout((()=>{e.workerPromise.then((e=>{e.terminate()}));const t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)}),this._options.idleTimeElapsedBeforeRelease))}))}))}}var jg,Kg,$g;function qg(e,t){const i=t?.jsDecoderModule||KTX2DECODER;e&&(e.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(i.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(i.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)),t&&(t.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmBinary=t.wasmUASTCToASTC),t.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmBinary=t.wasmUASTCToBC7),t.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary=t.wasmUASTCToRGBA_UNORM),t.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary=t.wasmUASTCToRGBA_SRGB),t.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmBinary=t.wasmUASTCToR8_UNORM),t.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary=t.wasmUASTCToRG8_UNORM),t.jsMSCTranscoder&&(i.MSCTranscoder.JSModule=t.jsMSCTranscoder),t.wasmMSCTranscoder&&(i.MSCTranscoder.WasmBinary=t.wasmMSCTranscoder),t.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmBinary=t.wasmZSTDDecoder))}function Zg(e){let t;void 0===e&&"undefined"!=typeof KTX2DECODER&&(e=KTX2DECODER),onmessage=i=>{if(i.data)switch(i.data.action){case"init":{const s=i.data.urls;s&&(s.jsDecoderModule&&void 0===e&&(importScripts(s.jsDecoderModule),e=KTX2DECODER),qg(s)),i.data.wasmBinaries&&qg(void 0,{...i.data.wasmBinaries,jsDecoderModule:e}),t=new e.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":e.KTX2Decoder.DefaultDecoderOptions=i.data.options;break;case"decode":t.decode(i.data.data,i.data.caps,i.data.options).then((e=>{const t=[];for(let i=0;i{postMessage({action:"decoded",success:!1,msg:e})}))}}}Qg.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(jg||(jg={})),function(e){e[e.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",e[e.BC7_RGBA=1]="BC7_RGBA",e[e.BC3_RGBA=2]="BC3_RGBA",e[e.BC1_RGB=3]="BC1_RGB",e[e.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",e[e.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",e[e.ETC2_RGBA=6]="ETC2_RGBA",e[e.ETC1_RGB=7]="ETC1_RGB",e[e.RGBA32=8]="RGBA32",e[e.R8=9]="R8",e[e.RG8=10]="RG8"}(Kg||(Kg={})),function(e){e[e.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",e[e.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",e[e.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",e[e.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",e[e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",e[e.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",e[e.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",e[e.RGBA8Format=32856]="RGBA8Format",e[e.R8Format=33321]="R8Format",e[e.RG8Format=33323]="RG8Format"}($g||($g={}));class Jg{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;const e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[Kg.BC1_RGB,Kg.BC3_RGBA],yes:{transcodeFormat:Kg.RGBA32,engineFormat:$g.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class ev{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(ev._WorkerPoolPromise||ev._DecoderModulePromise)return;const t={jsDecoderModule:Ds.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:Ds.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:Ds.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:Ds.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:Ds.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:Ds.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:Ds.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:Ds.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:Ds.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:Ds.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?ev._WorkerPoolPromise=new Promise((i=>{const s=`${qg}(${Zg})()`,r=URL.createObjectURL(new Blob([s],{type:"application/javascript"}));i(new Qg(e,(()=>function(e,t,i){return new Promise(((t,s)=>{const r=t=>{e.removeEventListener("error",r),e.removeEventListener("message",n),s(t)},n=i=>{"init"===i.data.action&&(e.removeEventListener("error",r),e.removeEventListener("message",n),t(e))};e.addEventListener("error",r),e.addEventListener("message",n),e.postMessage({action:"init",urls:i,wasmBinaries:undefined})}))}(new Worker(r),0,t))))})):void 0===ev._KTX2DecoderModule?ev._DecoderModulePromise=Ds.LoadBabylonScriptAsync(t.jsDecoderModule).then((()=>(ev._KTX2DecoderModule=KTX2DECODER,ev._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,ev._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,qg(t,ev._KTX2DecoderModule),new ev._KTX2DecoderModule.KTX2Decoder))):(ev._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,ev._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,ev._DecoderModulePromise=Promise.resolve(new ev._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=ev.DefaultNumWorkers){this._engine=e;const i="object"==typeof t&&t.workerPool||ev.WorkerPool;if(i)ev._WorkerPoolPromise=Promise.resolve(i);else{"object"==typeof t?ev._KTX2DecoderModule=t?.binariesAndModulesContainer?.jsDecoderModule:"undefined"!=typeof KTX2DECODER&&(ev._KTX2DecoderModule=KTX2DECODER);const e="number"==typeof t?t:t.numWorkers??ev.DefaultNumWorkers;ev._Initialize(e)}}_uploadAsync(e,t,i){const s=this._engine.getCaps(),r={astc:!!s.astc,bptc:!!s.bptc,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,etc1:!!s.etc1};if(ev._WorkerPoolPromise)return ev._WorkerPoolPromise.then((s=>new Promise(((n,o)=>{s.push(((s,a)=>{const l=e=>{s.removeEventListener("error",l),s.removeEventListener("message",h),o(e),a()},h=e=>{if("decoded"===e.data.action){if(s.removeEventListener("error",l),s.removeEventListener("message",h),e.data.success)try{this._createTexture(e.data.decodedData,t,i),n()}catch(e){o({message:e})}else o({message:e.data.msg});a()}};s.addEventListener("error",l),s.addEventListener("message",h),s.postMessage({action:"setDefaultDecoderOptions",options:ev.DefaultDecoderOptions._getKTX2DecoderOptions()});const c=new Uint8Array(e.byteLength);c.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),s.postMessage({action:"decode",data:c,caps:r,options:i},[c.buffer])}))}))));if(ev._DecoderModulePromise)return ev._DecoderModulePromise.then((i=>(ev.DefaultDecoderOptions.isDirty&&(ev._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=ev.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise(((r,n)=>{i.decode(e,s).then((e=>{this._createTexture(e,t),r()})).catch((e=>{n({message:e})}))})))));throw new Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let s=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,s=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw new Error("KTX2 container - could not transcode the data. "+e.errors);for(let i=0;i=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}ev.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null},ev.DefaultNumWorkers=ev.GetDefaultNumWorkers(),ev.DefaultDecoderOptions=new Jg;class tv{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,s){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const r=t.getEngine(),n=new Xg(e,6),o=n.numberOfMipmapLevels>1&&t.generateMipMaps;r._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,r._setCubeMapTextureParams(t,o,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}loadData(e,t,i,s){if(Xg.IsValid(e)){t._invertVScale=!t.invertY;const s=new Xg(e,1),r=function(e){switch(e){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}(s.glInternalFormat);r?(t.format=r,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=s.glInternalFormat,i(s.pixelWidth,s.pixelHeight,t.generateMipMaps,!0,(()=>{s.uploadLevels(t,t.generateMipMaps)}),s.isInvalid)}else ev.IsValid(e)?new ev(t.getEngine())._uploadAsync(e,t,s).then((()=>{i(t.width,t.height,t.generateMipMaps,!0,(()=>{}),!1)}),(e=>{Ne.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,(()=>{}),!0)})):(Ne.Error("texture missing KTX identifier"),i(0,0,!1,!1,(()=>{}),!0))}}oo._TextureLoaders.push(new tv);class iv extends ac{constructor(e,t,i){super(e,_e.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=fe.Identity(),this._referencedPosition=new _e,this._trackingState=Su.NOT_TRACKING,this.onXRCameraInitializedObservable=new K,this.onBeforeCameraTeleport=new K,this.onAfterCameraTeleport=new K,this.onTrackingStateChanged=new K,this.compensateOnFirstFrame=!0,this._rotate180=new fe(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new fe,this.cameraRigMode=In.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add((()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame,this._xrSessionManager.onWorldScaleFactorChangedObservable.add((()=>{this._xrSessionManager.currentFrame&&this._updateDepthNearFar()}))})),this._xrSessionManager.onXRFrameObservable.add((()=>{this._firstFrame&&this._updateFromXRSession(),this.onXRCameraInitializedObservable.hasObservers()&&(this.onXRCameraInitializedObservable.notifyObservers(this),this.onXRCameraInitializedObservable.clear()),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()}),void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y*this._xrSessionManager.worldScalingFactor:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new Pn(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new Pn(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){e&&e!==this&&(e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,fe.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace())}getClassName(){return"WebXRCamera"}setTarget(e){const t=ve.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),fe.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateDepthNearFar(){const e=(this.maxZ||1e4)*this._xrSessionManager.worldScalingFactor,t={depthFar:e,depthNear:this.minZ};this._xrSessionManager.updateRenderState(t),this._cache.minZ=this.minZ,this._cache.maxZ=e}_updateFromXRSession(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e)return void this._setTrackingState(Su.NOT_TRACKING);const t=e.emulatedPosition?Su.TRACKING_LOST:Su.TRACKING;if(this._setTrackingState(t),this.minZ===this._cache.minZ&&this.maxZ===this._cache.maxZ||this._updateDepthNearFar(),e.transform){const t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;const i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._referenceQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach(((e,t)=>{const i=this.rigCameras[t];i.isLeftCamera||i.isRightCamera||("right"===e.eye?i._isRightCamera=!0:"left"===e.eye&&(i._isLeftCamera=!0));const s=this.getScene().customRenderTargets;for(let e=0;ee;){const e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=ve.Matrix[0],t=ve.Matrix[1],i=ve.Matrix[2];me.ComposeToRef(iv._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),me.ComposeToRef(iv._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);const s=new XRRigidTransform({x:this._referencedPosition.x/this._xrSessionManager.worldScalingFactor,y:this._referencedPosition.y/this._xrSessionManager.worldScalingFactor,z:this._referencedPosition.z/this._xrSessionManager.worldScalingFactor},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(s)}}}iv._ScaleReadOnly=_e.One();class sv{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new K,this.onStateChangedObservable=new K,this.state=yu.NOT_IN_XR,this.sessionManager=new Tu(e),this.camera=new iv("webxr",e,this.sessionManager),this.featuresManager=new Za(this.sessionManager),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}static CreateAsync(e){const t=new sv(e);return t.sessionManager.initializeAsync().then((()=>(t._supported=!0,t))).catch((e=>{throw t._setState(yu.NOT_IN_XR),t.dispose(),e}))}dispose(){this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),this._spectatorCamera?.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),s={}){if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(yu.ENTERING_XR),"viewer"!==t&&"local"!==t&&(s.optionalFeatures=s.optionalFeatures||[],s.optionalFeatures.push(t)),s=await this.featuresManager._extendXRSessionInitObject(s),"immersive-ar"===e&&"unbounded"!==t&&Ne.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,s),await this.sessionManager.setReferenceSpaceTypeAsync(t);const r={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};if(!this.featuresManager.getEnabledFeature(qa.LAYERS)){const e=await i.initializeXRLayerAsync(this.sessionManager.session);r.baseLayer=e}return this.sessionManager.updateRenderState(r),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!this._nonVRCamera?.inputs?.attachedToElement,this._nonVRCamera?.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),this.sessionManager.onXRSessionEnded.addOnce((()=>{this.state!==yu.EXITING_XR&&this._setState(yu.EXITING_XR),this.camera.rigCameras.forEach((e=>{e.outputRenderTarget=null})),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(yu.NOT_IN_XR)})),this.sessionManager.onXRFrameObservable.addOnce((()=>{this._setState(yu.IN_XR)})),this.sessionManager}catch(e){throw Ne.Log(e),Ne.Log(e.message),this._setState(yu.NOT_IN_XR),e}}exitXRAsync(){return this.state!==yu.IN_XR?Promise.resolve():(this._setState(yu.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){const t=1/(e?.fps?e.fps:1e3)*1e3,i=e?.preferredCameraIndex?e?.preferredCameraIndex:0,s=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=t&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[i].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[i].absoluteRotation))};if(this._spectatorMode){if(i>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const e=()=>{this.state===yu.IN_XR?(this._spectatorCamera=new bc("webxr-spectator",_e.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new fe,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(s),this._scene.onAfterRenderCameraObservable.add((e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)}))):this.state===yu.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=null)};this.onStateChangedObservable.add(e),e()}else this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class rv{constructor(e,t,i=-1,s=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=s,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new K,this.onButtonStateChangedObservable=new K}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return 0!==this._axesIndices.length}isButton(){return-1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){const i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}}rv.BUTTON_TYPE="button",rv.SQUEEZE_TYPE="squeeze",rv.THUMBSTICK_TYPE="thumbstick",rv.TOUCHPAD_TYPE="touchpad",rv.TRIGGER_TYPE="trigger";class nv{constructor(e,t,i,s,r=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=s,this._doNotLoadControllerMesh=r,this._controllerCache=n,this._initComponent=e=>{if(!e)return;const t=this.layout.components[e],i=t.type,s=t.gamepadIndices.button,r=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&r.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new rv(e,i,s,r)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new K,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach((e=>this.getComponent(e).dispose())),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach((e=>{e.setEnabled(!1)})),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map((e=>this.components[e])).filter((t=>t.type===e))}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){const e=!this._getModelLoadingConstraints();let t=this._getGenericFilenameAndPath();return e?Ne.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise(((i,s)=>{const r=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const e=this._controllerCache.filter((e=>e.filename===t.filename&&e.path===t.path));if(e[0])return e[0].meshes.forEach((e=>e.setEnabled(!0))),void r(e[0].meshes)}fl.ImportMesh("",t.path,t.filename,this.scene,(e=>{this._controllerCache&&this._controllerCache.push({...t,meshes:e}),r(e)}),null,((e,i)=>{Ne.Log(i),Ne.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),s(i)}))}))}updateFromXRFrame(e){this.getComponentIds().forEach((e=>this.getComponent(e).update(this.gamepadObject))),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren((e=>e.name===t),!1)[0]}_getImmediateChildByName(e,t){return e.getChildren((e=>e.name==t),!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh)return;if(!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;const s=i?.5*t+.5:t;fe.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,s,e.valueMesh.rotationQuaternion),_e.LerpToRef(e.minMesh.position,e.maxMesh.position,s,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new ha(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))})),this.rootMesh.rotationQuaternion=fe.FromEulerAngles(0,Math.PI,0)}}class ov extends nv{constructor(e,t,i){super(e,av[i],t,i),this.profileId=ov.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new ha(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)})),this.rootMesh.rotationQuaternion=fe.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}ov.ProfileId="generic-trigger";const av={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};class lv extends nv{constructor(e,t,i,s,r){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,r),this._repositoryUrl=s,this.controllerCache=r,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach((e=>{this._touchDots[e].dispose()}))}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){const e=fl.IsPluginForExtensionAvailable(".glb");return e||Ne.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach((i=>{const s=t.visualResponses[i];if("transform"===s.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s.valueNodeName),minMesh:this._getChildByName(this.rootMesh,s.minNodeName),maxMesh:this._getChildByName(this.rootMesh,s.maxNodeName)};else{const r=t.type===rv.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:s.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r)},t.type===rv.TOUCHPAD_TYPE&&!this._touchDots[i]){const t=_d(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new cu(i+"mat",this.scene),t.material.diffuseColor=Ee.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}}))}))}_setRootMesh(e){let t;this.rootMesh=new ha(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i{const t=this.getComponent(e);if(!t.hasChanges)return;const i=this._buttonMeshMapping[e],s=this.layout.components[e];Object.keys(s.visualResponses).forEach((e=>{const r=s.visualResponses[e];let n=t.value;if("xAxis"===r.componentProperty?n=t.axes.x:"yAxis"===r.componentProperty&&(n=t.axes.y),"transform"===r.valueNodeProperty)this._lerpTransform(i.states[e],n,"button"!==r.componentProperty);else{const s=i.states[e].valueMesh;s&&(s.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}}))}))}}const hv=[];class cv{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){const t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){const s=[];i&&s.push(i),s.push(...e.profiles||[]),s.length&&!s[0]&&s.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&s.push("oculus-touch-v2");const r=s.indexOf("windows-mixed-reality");if(-1!==r&&s.splice(r,0,"microsoft-mixed-reality"),s.length||s.push("generic-trigger"),this.UseOnlineRepository){const i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,r=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,s,e,t).catch((()=>r.call(this,s,e,t)))}return this._LoadProfilesFromAvailableControllers(s,e,t)}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=Ds.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then((e=>JSON.parse(e))),this._ProfilesList}static ClearControllerCache(){hv.forEach((e=>{e.meshes.forEach((e=>{e.dispose(!1,!0)}))})),hv.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then((()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList())).then((t=>{for(let i=0;i(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=Ds.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then((e=>JSON.parse(e)))),this._ProfileLoadingPromises[e]))).then((e=>new lv(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:hv)))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let s=0;snew ov(t,e.gamepad,e.handedness))),cv.DefaultFallbacks();let uv=0;class dv{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new _e,this._disposed=!1,this.onDisposeObservable=new K,this.onMeshLoadedObservable=new K,this.onMotionControllerInitObservable=new K,this._uniqueId=`controller-${uv++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new _o(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new fe,this.inputSource.gripSpace&&(this.grip=new _o(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new fe),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&cv.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then((e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then((e=>{e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach((e=>e.renderingGroupId=this._options.renderingGroupId))),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&this.motionController?.dispose()}))}),(()=>{Ds.Warn("Could not find a matching motion controller for the registered input source")}))}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){const i=t&&this.grip?this.grip:this.pointer;_e.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i,s){const r=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=r,r){const e=r.transform.position;this.pointer.position.set(e.x,e.y,e.z).scaleInPlace(s.worldScalingFactor);const t=r.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent,this.pointer.scaling.setAll(s.worldScalingFactor)}if(this.inputSource.gripSpace&&this.grip){const r=e.getPose(this.inputSource.gripSpace,t);if(r){const e=r.transform.position,t=r.transform.orientation;this.grip.position.set(e.x,e.y,e.z).scaleInPlace(s.worldScalingFactor),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent,this.grip.scaling.setAll(s.worldScalingFactor)}this.motionController&&this.motionController.updateFromXRFrame(e)}}class _v{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new K,this.onControllerRemovedObservable=new K,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add((()=>{this._addAndRemoveControllers([],this.controllers.map((e=>e.inputSource)))})),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add((e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)})),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add((e=>{this.controllers.forEach((t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera,this.xrSessionManager)}))})),this._options.customControllersRepositoryURL&&(cv.BaseRepositoryUrl=this._options.customControllersRepositoryURL),cv.UseOnlineRepository=!this._options.disableOnlineControllerRepository,cv.UseOnlineRepository)try{cv.UpdateProfilesList().catch((()=>{cv.UseOnlineRepository=!1}))}catch(e){cv.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map((e=>e.inputSource));for(const t of e)if(-1===i.indexOf(t)){const e=new dv(this.xrSessionManager.scene,t,{...this._options.controllerOptions||{},forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation});this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}const s=[],r=[];this.controllers.forEach((e=>{-1===t.indexOf(e.inputSource)?s.push(e):r.push(e)})),this.controllers=s,r.forEach((e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()}))}dispose(){this.controllers.forEach((e=>{e.dispose()})),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),cv.ClearControllerCache()}}class pv extends Ja{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;const{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(this._options.forceGripIfAvailable&&e.grip?e.grip:e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new Ua(new _e,new _e),disabledByNearInteraction:!1,id:pv._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":case"transient-pointer":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new _e,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new Ee(.9,.9,.9),this.laserPointerDefaultColor=new Ee(.7,.7,.7),this.selectionMeshDefaultColor=new Ee(.8,.8,.8),this.selectionMeshPickedColor=new Ee(.3,.3,1),this._identityMatrix=me.Identity(),this._screenCoordinatesRef=_e.Zero(),this._viewportRef=new Pn(0,0,0,0),this._scene=this._xrSessionManager.scene,void 0===this._options.lookAndPickMode&&(this._scene.getEngine()._badDesktopOS||this._scene.getEngine()._badOS)&&(this._options.lookAndPickMode=!0),this._options.lookAndPickMode&&(this._options.enablePointerSelectionOnAllControllers=!0,this.displayLaserPointer=!1)}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController,!0),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)}),!0),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){const e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new Ua(new _e,new _e),disabledByNearInteraction:!1,id:pv._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i{const t=this._controllers[e];if(this._options.lookAndPickMode&&"transient-pointer"!==t.xrController?.inputSource.targetRayMode)return;if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||t.disabledByNearInteraction)return t.selectionMesh.isVisible=!1,t.laserPointer.isVisible=!1,void(t.pick=null);let i;if(t.laserPointer.isVisible=this.displayLaserPointer,t.xrController)i=this._options.forceGripIfAvailable&&t.xrController.grip?t.xrController.grip.position:t.xrController.pointer.position,t.xrController.getWorldPointerRayToRef(t.tmpRay,this._options.forceGripIfAvailable);else{if(!t.webXRCamera)return;i=t.webXRCamera.position,t.webXRCamera.getForwardRayToRef(t.tmpRay)}if(this._options.maxPointerDistance&&(t.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&i){const e=this._xrSessionManager.scene,s=this._options.xrInput.xrCamera;s&&(s.viewport.toGlobalToRef(e.getEngine().getRenderWidth()/s.rigCameras.length,e.getEngine().getRenderHeight(),this._viewportRef),_e.ProjectToRef(i,this._identityMatrix,s.getTransformationMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||this._screenCoordinatesRef.x===1/0||this._screenCoordinatesRef.y===1/0||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,t.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let s=null;this._utilityLayerScene&&(s=this._utilityLayerScene.pickWithRay(t.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const r=this._scene.pickWithRay(t.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);s&&s.hit?r&&r.hit?s.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit)if(this._pickingMoved(r,t.pick))a&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,l)),a=!1,o=0;else if(o>i/10&&(n.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,l),a=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),n.isVisible=!1;else{const e=1-o/i;n.scaling.set(e,e,e)}else a=!1,o=0;this._scene.simulatePointerMove(t.pick,l),r=t.pick}})),void 0!==this._options.renderingGroupId&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce((()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&a&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),n.dispose()}))}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const s={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),!t.pick||this._options.disablePointerUpOnTouchOut&&i||(i?this._scene.simulatePointerMove(t.pick,s):(this._scene.simulatePointerDown(t.pick,s),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,s)))})),e.onDisposeObservable.addOnce((()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame((()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,s),t.finalPointerUpTriggered=!0)}))}))}_attachTrackedPointerRayMode(e){const t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);const i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))})),e.inputSource.gamepad){const s=s=>{this._options.overrideButtonId&&(t.selectionComponent=s.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=s.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((s=>{if(s.changes.pressed){const r=s.changes.pressed.current;if(t.pick)(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),r?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor));else if(r&&!this._options.enablePointerSelectionOnAllControllers&&!this._options.disableSwitchOnClick){const t=this._controllers[this._attachedController];t&&t.pointerDownTriggered&&!t.finalPointerUpTriggered&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerUp(new tr,{pointerId:t.id,pointerType:"xr"}),t.finalPointerUpTriggered=!0),this._attachedController=e.uniqueId}}}))};e.motionController?s(e.motionController):e.onMotionControllerInitObservable.add(s)}else{const e=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)}))},s=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)}))};t.eventListeners={selectend:s,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",s)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(_e.Dot(e,t.direction)){const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),!t.finalPointerUpTriggered&&t.pointerDownTriggered){const e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame((()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new tr,e),t.finalPointerUpTriggered=!0}))}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce((()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){Ds.Warn("controller already detached.")}}))}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Ju.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():$u("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const s=new cu("laserPointerMat",t);s.emissiveColor=this.laserPointerDefaultColor,s.alpha=.7,i.material=s,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const r=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():wu("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);r.bakeCurrentTransformIntoVertices(),r.isPickable=!1,r.isVisible=!1;const n=new cu("targetMat",t);return n.specularColor=Ee.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,r.material=n,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:r}}_pickingMoved(e,t){if(!e.hit||!t.hit)return!0;if(!(e.pickedMesh&&e.pickedPoint&&t.pickedMesh&&t.pickedPoint))return!0;if(e.pickedMesh!==t.pickedMesh)return!0;e.pickedPoint?.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const i=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance;return this._tmpVectorForPickCompare.length()>i}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}}var fv,mv,gv;pv._IdCounter=200,pv.Name=qa.POINTER_SELECTION,pv.Version=1,Za.AddWebXRFeature(pv.Name,((e,t)=>()=>new pv(e,t)),pv.Version,!0),Gn.prototype._projectOnTrianglesToRef=function(e,t,i,s,r,n){const o=ve.Vector3[0],a=ve.Vector3[1];let l=1/0;for(let n=this.indexStart;n{if(this._controllers[e.uniqueId])return;const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s}=this._generateNewTouchPointMesh(),r=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s,currentAnimationState:fv.DEHYDRATED,grabRay:new Ua(new _e,new _e),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,downTriggered:!1,id:vv._IdCounter++,pickedPointVisualCue:r},this._controllers[e.uniqueId]._worldScaleObserver=this._controllers[e.uniqueId]._worldScaleObserver||this._xrSessionManager.onWorldScaleFactorChangedObservable.add((t=>{if(t.newScaleFactor!==t.previousScaleFactor){this._controllers[e.uniqueId].touchCollisionMesh.dispose(),this._controllers[e.uniqueId].pickedPointVisualCue.dispose();const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s}=this._generateNewTouchPointMesh();this._controllers[e.uniqueId].touchCollisionMesh=t,this._controllers[e.uniqueId].touchCollisionMeshFunction=i,this._controllers[e.uniqueId].hydrateCollisionMeshFunction=s,this._controllers[e.uniqueId].pickedPointVisualCue=this._generateVisualCue()}})),this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new Ee(.8,.8,.8),this.selectionMeshPickedColor=new Ee(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=mv.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;ie.currentAnimationState)switch(e.currentAnimationState){case fv.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===fv.HOVER)break;case fv.HOVER:if(e.touchCollisionMeshFunction(!0),t===fv.TOUCH)break}else switch(e.currentAnimationState){case fv.TOUCH:if(e.touchCollisionMeshFunction(!1),t===fv.HOVER)break;case fv.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===fv.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){const s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(ve.Vector3[0]),s.grabRay.direction.copyFrom(ve.Vector3[0]),this._options.nearInteractionControllerMode!==mv.CENTERED_IN_FRONT||s.xrController?.inputSource.hand||(s.xrController.getWorldPointerRayToRef(this._tmpRay),s.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),s.grabRay.length=this._nearGrabLengthScale*this._hoverRadius*this._xrSessionManager.worldScalingFactor,s.touchCollisionMesh.position.copyFrom(s.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor)}_onXRFrame(e){Object.keys(this._controllers).forEach((t=>{const i=this._controllers[t],s=i.xrController?.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!i.xrController||!s&&(!this._options.nearInteractionControllerMode||!i.xrController.inputSource.gamepad))return void(i.pick=null);if(i.hoverInteraction=!1,i.nearInteraction=!1,!i.xrController)return;if(s){const i=s.get("index-finger-tip");if(i){const s=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(s&&s.transform){const e=this._scene.useRightHandedSystem?1:-1;ve.Vector3[0].set(s.transform.position.x,s.transform.position.y,s.transform.position.z*e),ve.Quaternion[0].set(s.transform.orientation.x,s.transform.orientation.y,s.transform.orientation.z*e,s.transform.orientation.w*e),this._processTouchPoint(t,ve.Vector3[0],ve.Quaternion[0])}}}else if(i.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==mv.DISABLED){let e=i.xrController.pointer;i.xrController.grip&&this._options.nearInteractionControllerMode===mv.CENTERED_ON_CONTROLLER&&(e=i.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}const r=(e,t)=>{let i=null;return i=t&&t.hit?e&&e.hit?t.distance{let t=new tr,i=!1;const s=e&&e.pickedPoint&&e.hit;return e?.pickedPoint&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),s&&!i&&(t=e),t};if(!i.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._utilityLayerScene,(e=>this._nearInteractionPredicate(e))));const o=r(this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._scene,(e=>this._nearInteractionPredicate(e))),t);if(o&&o.hit&&(e=n(o),e.hit&&(i.hoverInteraction=!0)),i.hoverInteraction){let t=null;const o=(s?this._pickRadius:this._controllerPickRadius)*this._xrSessionManager.worldScalingFactor;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,o,this._utilityLayerScene,(e=>this._nearPickPredicate(e))));const a=n(r(this._pickWithSphere(i,o,this._scene,(e=>this._nearPickPredicate(e))),t));a.hit&&(e=a,i.nearInteraction=!0)}i.stalePick=i.pick,i.pick=e,i.pick&&i.pick.pickedPoint&&i.pick.hit?(i.meshUnderPointer=i.pick.pickedMesh,i.pickedPointVisualCue.position.copyFrom(i.pick.pickedPoint),i.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!0)):(i.meshUnderPointer=null,i.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!1))}let o=fv.DEHYDRATED;i.grabInteraction||i.nearInteraction?o=fv.TOUCH:i.hoverInteraction&&(o=fv.HOVER),this._handleTransitionAnimation(i,o)}))}get _utilityLayerScene(){return this._options.customUtilityLayerScene||Ju.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Ju.DefaultUtilityLayer.utilityLayerScene:this._scene,t=_d("nearInteraction",{diameter:.0105*this._xrSessionManager.worldScalingFactor},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=fe.Identity();const i=new cu("targetMat",e);return i.specularColor=Ee.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer,t.downTriggered=!0):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.downTriggered=!1,t.nearInteractionTargetMesh=null))}));const s=s=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),s&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0):!s&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.downTriggered=!1,t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!s||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const i=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;s(t)}})):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;s(t)}})))};e.motionController?i(e.motionController):e.onMotionControllerInitObservable.add(i)}else{const e=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0)},s=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0,t.downTriggered=!1)};t.eventListeners={selectend:s,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",s)}}_detachController(e){const t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach((e=>{const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame((()=>{if(!t.downTriggered)return;const e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new tr,e)})),t._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(t._worldScaleObserver),delete this._controllers[e],this._attachedController===e)){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){const e=this._xrSessionManager.worldScalingFactor,t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Ju.DefaultUtilityLayer.utilityLayerScene:this._scene,i=_d("PickSphere",{diameter:1*e},t);if(i.isVisible=!1,this._options.motionControllerOrbMaterial)i.material=this._options.motionControllerOrbMaterial;else{let e;e=this._options.motionControllerTouchMaterialSnippetUrl?hh.ParseFromFileAsync("motionControllerTouchMaterial",this._options.motionControllerTouchMaterialSnippetUrl,t):hh.ParseFromSnippetAsync("8RUNKL#3",t),e.then((e=>{i.material=e})).catch((e=>{Ne.Warn(`Error creating touch material in WebXRNearInteraction: ${e}`)}))}const s=new cn;s.setEasingMode(tn.EASINGMODE_EASEINOUT);const r=new _e(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius).scaleInPlace(e),n=this._controllerPickRadius*(4/3),o=new _e(n,n,n).scaleInPlace(e),a=this._controllerPickRadius*(7/6),l=new _e(a,a,a).scaleInPlace(e),h=.8*this._controllerPickRadius,c=new _e(h,h,h).scaleInPlace(e),u=1.5*this._controllerPickRadius,d=[{frame:0,value:r},{frame:10,value:new _e(u,u,u).scaleInPlace(e)},{frame:18,value:o}],_=[{frame:0,value:o},{frame:10,value:c},{frame:18,value:r}],p=[{frame:0,value:_e.ZeroReadOnly},{frame:12,value:l},{frame:15,value:r}],f=[{frame:0,value:r},{frame:10,value:_e.ZeroReadOnly},{frame:15,value:_e.ZeroReadOnly}],m=new Ft("touch","scaling",60,Ft.ANIMATIONTYPE_VECTOR3,Ft.ANIMATIONLOOPMODE_CONSTANT),g=new Ft("release","scaling",60,Ft.ANIMATIONTYPE_VECTOR3,Ft.ANIMATIONLOOPMODE_CONSTANT),v=new Ft("hydrate","scaling",60,Ft.ANIMATIONTYPE_VECTOR3,Ft.ANIMATIONLOOPMODE_CONSTANT),x=new Ft("dehydrate","scaling",60,Ft.ANIMATIONTYPE_VECTOR3,Ft.ANIMATIONLOOPMODE_CONSTANT);return m.setEasingFunction(s),g.setEasingFunction(s),v.setEasingFunction(s),x.setEasingFunction(s),m.setKeys(d),g.setKeys(_),v.setKeys(p),x.setKeys(f),{touchCollisionMesh:i,touchCollisionMeshFunction:e=>{const s=e?m:g;t.beginDirectAnimation(i,[s],0,18,!1,1)},hydrateCollisionMeshFunction:e=>{const s=e?v:x;e&&(i.isVisible=!0),t.beginDirectAnimation(i,[s],0,15,!1,1,(()=>{e||(i.isVisible=!1)}))}}}_pickWithSphere(e,t,i,s){const r=new tr;if(r.distance=1/0,e.touchCollisionMesh&&e.xrController){const n=e.touchCollisionMesh.position,o=On.CreateFromCenterAndRadius(n,t);for(let t=0;tc&&(h=0,a.copyFrom(t.center)),-1!==h&&h<_&&(_=h,Ua.CreateFromToToRef(t.center,a,l),l.length=2*_,d=l.intersectsMesh(e),o.copyFrom(a));return _()=>new vv(e,t)),vv.Version,!0);class xv{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class bv{}class Tv{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new K,this._onSessionGranted=e=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw Ds.Warn("WebXR can only be served over HTTPS"),new Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";const e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor";let s=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+("undefined"==typeof SVGSVGElement?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";s+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const r=document.createElement("style");r.appendChild(document.createTextNode(s)),document.getElementsByTagName("head")[0].appendChild(r);const n=document.createElement("button");n.className="babylonVRicon",n.title=`${e} - ${i}`,this._buttons.push(new xv(n,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",n.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}const i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce((()=>{this.dispose()})))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;const i=this._buttons.map((t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode)));e.onStateChangedObservable.add((e=>{e==yu.NOT_IN_XR&&this._updateButtons(null)})),(await Promise.all(i)).forEach(((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):Ds.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)}))}static async CreateAsync(e,t,i){const s=new Tv(e,i);return await s.setHelperAsync(t,i.renderTarget||void 0),s}async _enterXRWithButtonIndex(e=0){if(this._helper.state==yu.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==yu.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(t){this._updateButtons(null);const i=this._buttons[e].element,s=i.title;i.title="Error entering XR session : "+s,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t)}}dispose(){const e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach((e=>{e.update(this._activeButton)})),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}function yv(e){let t=0;const i=Date.now();e.observableParameters=e.observableParameters??{};const s=e.contextObservable.add((r=>{const n=Date.now();t=n-i;const o={startTime:i,currentTime:n,deltaTime:t,completeRate:t/e.timeout,payload:r};e.onTick&&e.onTick(o),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(o)),t>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(o))}),e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return s}!function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(gv||(gv={}));class Sv{constructor(e){this.onEachCountObservable=new K,this.onTimerAbortedObservable=new K,this.onTimerEndedObservable=new K,this.onStateChangedObservable=new K,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{const t=Date.now();this._timer=t-this._startTime;const i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},s=this._breakOnNextTick||this._breakCondition(i);s||this._timer>=this._timeToEnd?this._stop(i,s):this.onEachCountObservable.notifyObservers(i)},this._setState(gv.INIT),this._contextObservable=e.contextObservable,this._observableParameters=e.observableParameters??{},this._breakCondition=e.breakCondition??(()=>!1),this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}set breakCondition(e){this._breakCondition=e}clearObservables(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()}start(e=this._timeToEnd){if(this._state===gv.STARTED)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(gv.STARTED)}stop(){this._state===gv.STARTED&&(this._breakOnNextTick=!0)}dispose(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()}_setState(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)}_stop(e,t=!1){this._contextObservable.remove(this._observer),this._setState(gv.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class Cv extends Ja{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){const t=this._options.teleportationTargetMesh.getChildMeshes(!1,(e=>"rotationCone"===e.name));t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new Ae(1,1,1,1),this._tmpRay=new Ua(new _e,new _e),this._tmpVector=new _e,this._tmpQuaternion=new fe,this._worldScaleObserver=null,this.skipNextTeleportation=!1,this.backwardsMovementEnabled=!0,this.backwardsTeleportationDistance=.7,this.parabolicCheckRadius=5,this.parabolicRayEnabled=!0,this.straightRayEnabled=!0,this.rotationAngle=Math.PI/8,this.onTargetMeshPositionUpdatedObservable=new K,this.teleportationEnabled=!0,this._rotationEnabled=!0,this.onBeforeCameraTeleportRotation=new K,this.onAfterCameraTeleportRotation=new K,this._attachController=e=>{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1,initialHit:!1,mainComponentUsed:!1}};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController){const i=e.motionController.getComponentOfType(rv.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(rv.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){const i=e.motionController.getMainComponent();if(!i)return;t.teleportationState.mainComponentUsed=!0,t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add((()=>{if(!this.teleportationEnabled)return;const s=()=>{t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,yv({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};i.changes.pressed&&(i.changes.pressed.current?this._options.timeToTeleportStart?yv({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{i.pressed&&s()}}):s():(t.teleportationState.forward=!1,this._currentTeleportationControllerId=""))}))}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add((i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,fe.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);const e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,(e=>-1!==this._floorMeshes.indexOf(e)));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout((()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))})):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;const e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this.onBeforeCameraTeleportRotation.notifyObservers(e),fe.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),t.teleportationState.forward&&this._teleportForward(e.uniqueId))}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}else{t.teleportationState.mainComponentUsed=!0;let i=!1;const s=()=>{this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,yv({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};this._xrSessionManager.scene.onPointerObservable.add((e=>{e.type===lr.POINTERDOWN?(i=!1,this._options.timeToTeleportStart?yv({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&s()},breakCondition:()=>!!i&&(i=!1,!0)}):s()):e.type===lr.POINTERUP&&(i=!0,t.teleportationState.forward=!1,this._currentTeleportationControllerId="")}))}},this._colorArray=Array(24).fill(this._cachedColor4White),this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new Ae(1,0,0,.75),this._setTargetMeshVisibility(!1),this.onBeforeCameraTeleport=t.xrInput.xrCamera.onBeforeCameraTeleport,this.onAfterCameraTeleport=t.xrInput.xrCamera.onAfterCameraTeleport,this.parabolicCheckRadius*=this._xrSessionManager.worldScalingFactor,this._worldScaleObserver=e.onWorldScaleFactorChangedObservable.add((e=>{this.parabolicCheckRadius=this.parabolicCheckRadius/e.previousScaleFactor*e.newScaleFactor,this._options.teleportationTargetMesh?.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor)}))}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return!!super.attach()&&(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver)}removeFloorMesh(e){const t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];const t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){const t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(-1===t)for(let i=0;i{if(this._options.blockerMeshesPredicate&&this._options.blockerMeshesPredicate(e))return!0;if(this._options.blockAllPickableMeshes&&e.isPickable)return!0;if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;const t=this._floorMeshes.indexOf(e);return-1!==t&&this._floorMeshes[t].absolutePosition.y!(!this._options.blockerMeshesPredicate||!this._options.blockerMeshesPredicate(e))||!(!this._options.blockAllPickableMeshes||!e.isPickable)||!(!this._options.pickBlockerMeshes||-1===this._options.pickBlockerMeshes.indexOf(e))||-1!==this._floorMeshes.indexOf(e))),l=a&&a.pickedMesh&&-1!==this._floorMeshes.indexOf(a.pickedMesh);if(a&&a.pickedMesh&&!l)return e.teleportationState.mainComponentUsed&&!e.teleportationState.initialHit?void(e.teleportationState.forward=!1):(e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,r),void this._showParabolicPath(a));a&&a.pickedPoint&&(e.teleportationState.initialHit=!0,e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(a),this._setTargetMeshVisibility(!0,!1,r),this._showParabolicPath(a))}this._setTargetMeshVisibility(t,!1,r)}else this._setTargetMeshVisibility(!1,!1,!0)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1,!1,!0)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Ju.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=Iu("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const i=512,s=new uu("teleportationPlaneDynamicTexture",i,e,!0);s.hasAlpha=!0;const r=s.getContext(),n=i/2,o=i/2,a=200;r.beginPath(),r.arc(n,o,a,0,2*Math.PI,!1),r.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",r.fill(),r.lineWidth=10,r.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",r.stroke(),r.closePath(),s.update();const l=new cu("teleportationPlaneMaterial",e);l.diffuseTexture=s,t.material=l}const i=wu("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const t=new Ft("animationInnerCircle","position.y",30,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CYCLE),s=[];s.push({frame:0,value:0}),s.push({frame:30,value:.4}),s.push({frame:60,value:0}),t.setKeys(s);const r=new _n;r.setEasingMode(tn.EASINGMODE_EASEINOUT),t.setEasingFunction(r),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}const s=$u("rotationCone",{diameterTop:0,tessellation:4},e);if(s.isPickable=!1,s.scaling.set(.5,.12,.2),s.rotate(Xr.X,Math.PI/2),s.position.z=.6,s.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,s.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const t=new cu("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new Ee(.3,.3,1):t.diffuseColor=new Ee(.3,.3,1),t.alpha=.9,i.material=t,s.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._options.teleportationTargetMesh.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._setTargetMeshVisibility(!1)}_detachController(e){const t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,s=Number.MAX_VALUE;if(this._snapToPositions.length){const r=t*t;this._snapToPositions.forEach((t=>{const n=_e.DistanceSquared(t,e);n<=r&&n{t.isVisible=e})),e?this._selectionFeature&&i&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&i&&this._selectionFeature.attach()))}_disposeBezierCurve(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Ju.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],s=en.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),r=i.teleportationState.blocked?this._blockedRayColor:void 0,n=this._colorArray.fill(r||this._cachedColor4White),o=s.getPoints();o.shift(),o.shift(),this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(s.getPoints(),e):this._quadraticBezierCurve=Ud("teleportation path line",{points:o,instance:this._quadraticBezierCurve,updatable:!0,colors:n},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){const t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint))if(this.skipNextTeleportation)this.skipNextTeleportation=!1;else if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){const e=this._options.xrInput.xrCamera.realWorldHeight;this.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=e,fe.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}Cv.Name=qa.TELEPORTATION,Cv.Version=1,Za.AddWebXRFeature(Cv.Name,((e,t)=>()=>new Cv(e,t)),Cv.Version,!0);class Ev{}class Av{constructor(){}static CreateAsync(e,t={}){const i=new Av;if(e.onDisposeObservable.addOnce((()=>{i.dispose()})),!t.disableDefaultUI){const s={renderTarget:i.renderTarget,...t.uiOptions||{}};t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?s.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:s.optionalFeatures=t.optionalFeatures),i.enterExitUI=new Tv(e,s)}return sv.CreateAsync(e).then((e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new _v(e.sessionManager,e.camera,{controllerOptions:{renderingGroupId:t.renderingGroupId},...t.inputOptions||{}}),!t.disablePointerSelection){const e={...t.pointerSelectionOptions,xrInput:i.input,renderingGroupId:t.renderingGroupId};i.pointerSelection=i.baseExperience.featuresManager.enableFeature(pv.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(Cv.Name,t.useStablePlugins?"stable":"latest",{floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId,...t.teleportationOptions}),i.teleportation.setSelectionFeature(i.pointerSelection))}return t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(vv.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0,...t.nearInteractionOptions})),t.disableHandTracking||i.baseExperience.featuresManager.enableFeature(vh.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,...t.handSupportOptions},void 0,!1),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)})).then((()=>i)).catch((e=>(Ne.Error("Error initializing XR"),Ne.Error(e),i)))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}var Pv=!0;function Iv(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}Hr.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;ee.isVisible&&e.isEnabled())),s=t.max.subtract(t.min),r=t.min.add(s.scale(.5));let n,o=1.5*s.length();if(isFinite(o)||(o=1,r.copyFromFloats(0,0,0)),e){const e=new hc("default camera",-Math.PI/2,Math.PI/2,o,r,this);e.lowerRadiusLimit=.01*o,e.wheelPrecision=100/o,n=e}else{const e=new ac("default camera",new _e(r.x,r.y,-o),this);e.setTarget(r),n=e}n.minZ=.01*o,n.maxZ=1e3*o,n.speed=.2*o,this.activeCamera=n,i&&n.attachControl()}},Hr.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},Hr.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,s=0,r=!0){if(!e)return Ne.Warn("Can not create default skybox without environment texture."),null;r&&e&&(this.environmentTexture=e);const n=cd("hdrSkyBox",{size:i},this);if(t){const t=new zg("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Pa.SKYBOX_MODE),t.microSurface=1-s,t.disableLighting=!0,t.twoSidedLighting=!0,n.material=t}else{const t=new cu("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Pa.SKYBOX_MODE),t.disableLighting=!0,n.material=t}return n.isPickable=!1,n.infiniteDistance=!0,n.ignoreCameraMaxZ=!0,n},Hr.prototype.createDefaultEnvironment=function(e){return Tg?new Tg(e,this):null},Hr.prototype.createDefaultVRExperience=function(e={}){return new ku(this,e)},Hr.prototype.createDefaultXRExperienceAsync=function(e={}){return Av.CreateAsync(this,e).then((e=>e))};class Rv extends Pa{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new K),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e?.message):Ne.Error(e?.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch((e=>{if("NotAllowedError"===e?.name){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers())return void this._onUserActionRequestedObservable.notifyObservers(this);if(!this.video.muted)return Ne.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,void this.video.play().catch((e=>{this._processError(e)}))}this._processError(e)}))}constructor(e,t,i,s=!1,r=!1,n=Pa.TRILINEAR_SAMPLINGMODE,o={},a,l=5){super(null,i,!s,r),this._externalTexture=null,this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||Ds.IsExponentOfTwo(this.video.videoWidth)&&Ds.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=Pa.WRAP_ADDRESSMODE,this.wrapV=Pa.WRAP_ADDRESSMODE):(this.wrapU=Pa.CLAMP_ADDRESSMODE,this.wrapV=Pa.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=this._format??5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(null!=this._texture){if(!this._displayingPosterTexture)return;this._displayingPosterTexture=!1}if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{const e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture)return;if(this.video.readyState=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&u?u&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return Ds.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return"string"==typeof e?(Ds.SetCorsBehavior(e,t),t.src=e):(Ds.SetCorsBehavior(e[0],t),e.forEach((e=>{const i=document.createElement("source");i.src=e,t.appendChild(i)}))),this.onDisposeObservable.addOnce((()=>{Iv(t)})),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))}get externalTexture(){return this._externalTexture}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new Rv(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("loadeddata",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),this._externalTexture?.dispose()}static CreateFromStreamAsync(e,t,i,s=!0){const r=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(r),r.style.transform="scale(0.0001, 0.0001)",r.style.opacity="0",r.style.position="fixed",r.style.bottom="0px",r.style.right="0px"),r.setAttribute("autoplay",""),r.setAttribute("muted","true"),r.setAttribute("playsinline",""),r.muted=!0,r.isNative||(void 0!==r.mozSrcObject?r.mozSrcObject=t:"object"==typeof r.srcObject?r.srcObject=t:r.src=window.URL&&window.URL.createObjectURL(t)),new Promise((t=>{const i=()=>{const n=new Rv("video",r,e,!0,s,void 0,void 0,void 0,4);e.getEngine()._badOS&&n.onDisposeObservable.addOnce((()=>{r.remove()})),n.onDisposeObservable.addOnce((()=>{Iv(r)})),t(n),r.removeEventListener("playing",i)};r.addEventListener("playing",i),r.play()}))}static async CreateFromWebCamAsync(e,t,i=!1,s=!0){if(navigator.mediaDevices){const r=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,r,t,s);return n.onDisposeObservable.addOnce((()=>{r.getTracks().forEach((e=>{e.stop()}))})),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,s=!1,r=!0){this.CreateFromWebCamAsync(e,i,s,r).then((function(e){t&&t(e)})).catch((function(e){Ne.Error(e.name)}))}}Ze([rt("settings")],Rv.prototype,"_settings",void 0),Ze([rt("src")],Rv.prototype,"_currentSrc",void 0),Ze([rt()],Rv.prototype,"isVideo",void 0),Pa._CreateVideoTexture=(e,t,i,s=!1,r=!1,n=Pa.TRILINEAR_SAMPLINGMODE,o={},a,l=5)=>new Rv(e,t,i,s,r,n,o,a,l),z("BABYLON.VideoTexture",Rv);class Mv extends yg{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const s={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},r=new Rv((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,Pa.TRILINEAR_SAMPLINGMODE,s);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add((e=>{e.pickInfo?.pickedMesh===this.mesh&&this._texture.video.play()}),lr.POINTERDOWN)),this._textureObserver=r.onLoadObservable.add((()=>{this.onLoadObservable.notifyObservers()})),r}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}Mv.MODE_MONOSCOPIC=yg.MODE_MONOSCOPIC,Mv.MODE_TOPBOTTOM=yg.MODE_TOPBOTTOM,Mv.MODE_SIDEBYSIDE=yg.MODE_SIDEBYSIDE;class Ov{get gpuFrameTimeCounter(){return this.engine.getGPUFrameTimeCounter()}get captureGPUFrameTime(){return this._captureGPUFrameTime}set captureGPUFrameTime(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,this.engine.captureGPUFrameTime(e))}get shaderCompilationTimeCounter(){return this._shaderCompilationTime}get captureShaderCompilationTime(){return this._captureShaderCompilationTime}set captureShaderCompilationTime(e){e!==this._captureShaderCompilationTime&&(this._captureShaderCompilationTime=e,e?(this._onBeforeShaderCompilationObserver=this.engine.onBeforeShaderCompilationObservable.add((()=>{this._shaderCompilationTime.fetchNewFrame(),this._shaderCompilationTime.beginMonitoring()})),this._onAfterShaderCompilationObserver=this.engine.onAfterShaderCompilationObservable.add((()=>{this._shaderCompilationTime.endMonitoring()}))):(this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null))}constructor(e){this.engine=e,this._captureGPUFrameTime=!1,this._captureShaderCompilationTime=!1,this._shaderCompilationTime=new wr,this._onBeginFrameObserver=null,this._onEndFrameObserver=null,this._onBeforeShaderCompilationObserver=null,this._onAfterShaderCompilationObserver=null}dispose(){this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.engine.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null,this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver),this._onBeforeShaderCompilationObserver=null,this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver),this._onAfterShaderCompilationObserver=null,this.engine=null}}class Dv{get activeMeshesEvaluationTimeCounter(){return this._activeMeshesEvaluationTime}get captureActiveMeshesEvaluationTime(){return this._captureActiveMeshesEvaluationTime}set captureActiveMeshesEvaluationTime(e){e!==this._captureActiveMeshesEvaluationTime&&(this._captureActiveMeshesEvaluationTime=e,e?(this._onBeforeActiveMeshesEvaluationObserver=this.scene.onBeforeActiveMeshesEvaluationObservable.add((()=>{Ds.StartPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.beginMonitoring()})),this._onAfterActiveMeshesEvaluationObserver=this.scene.onAfterActiveMeshesEvaluationObservable.add((()=>{Ds.EndPerformanceCounter("Active meshes evaluation"),this._activeMeshesEvaluationTime.endMonitoring(!1)}))):(this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null))}get renderTargetsRenderTimeCounter(){return this._renderTargetsRenderTime}get captureRenderTargetsRenderTime(){return this._captureRenderTargetsRenderTime}set captureRenderTargetsRenderTime(e){e!==this._captureRenderTargetsRenderTime&&(this._captureRenderTargetsRenderTime=e,e?(this._onBeforeRenderTargetsRenderObserver=this.scene.onBeforeRenderTargetsRenderObservable.add((()=>{Ds.StartPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.beginMonitoring()})),this._onAfterRenderTargetsRenderObserver=this.scene.onAfterRenderTargetsRenderObservable.add((()=>{Ds.EndPerformanceCounter("Render targets rendering"),this._renderTargetsRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null))}get particlesRenderTimeCounter(){return this._particlesRenderTime}get captureParticlesRenderTime(){return this._captureParticlesRenderTime}set captureParticlesRenderTime(e){e!==this._captureParticlesRenderTime&&(this._captureParticlesRenderTime=e,e?(this._onBeforeParticlesRenderingObserver=this.scene.onBeforeParticlesRenderingObservable.add((()=>{Ds.StartPerformanceCounter("Particles"),this._particlesRenderTime.beginMonitoring()})),this._onAfterParticlesRenderingObserver=this.scene.onAfterParticlesRenderingObservable.add((()=>{Ds.EndPerformanceCounter("Particles"),this._particlesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null))}get spritesRenderTimeCounter(){return this._spritesRenderTime}get captureSpritesRenderTime(){return this._captureSpritesRenderTime}set captureSpritesRenderTime(e){e!==this._captureSpritesRenderTime&&(this._captureSpritesRenderTime=e,this.scene.spriteManagers&&(e?(this._onBeforeSpritesRenderingObserver=this.scene.onBeforeSpritesRenderingObservable.add((()=>{Ds.StartPerformanceCounter("Sprites"),this._spritesRenderTime.beginMonitoring()})),this._onAfterSpritesRenderingObserver=this.scene.onAfterSpritesRenderingObservable.add((()=>{Ds.EndPerformanceCounter("Sprites"),this._spritesRenderTime.endMonitoring(!1)}))):(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null,this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null)))}get physicsTimeCounter(){return this._physicsTime}get capturePhysicsTime(){return this._capturePhysicsTime}set capturePhysicsTime(e){e!==this._capturePhysicsTime&&this.scene.onBeforePhysicsObservable&&(this._capturePhysicsTime=e,e?(this._onBeforePhysicsObserver=this.scene.onBeforePhysicsObservable.add((()=>{Ds.StartPerformanceCounter("Physics"),this._physicsTime.beginMonitoring()})),this._onAfterPhysicsObserver=this.scene.onAfterPhysicsObservable.add((()=>{Ds.EndPerformanceCounter("Physics"),this._physicsTime.endMonitoring()}))):(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null,this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null))}get animationsTimeCounter(){return this._animationsTime}get captureAnimationsTime(){return this._captureAnimationsTime}set captureAnimationsTime(e){e!==this._captureAnimationsTime&&(this._captureAnimationsTime=e,e?this._onAfterAnimationsObserver=this.scene.onAfterAnimationsObservable.add((()=>{this._animationsTime.endMonitoring()})):(this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null))}get frameTimeCounter(){return this._frameTime}get captureFrameTime(){return this._captureFrameTime}set captureFrameTime(e){this._captureFrameTime=e}get interFrameTimeCounter(){return this._interFrameTime}get captureInterFrameTime(){return this._captureInterFrameTime}set captureInterFrameTime(e){this._captureInterFrameTime=e}get renderTimeCounter(){return this._renderTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeforeDrawPhaseObserver=this.scene.onBeforeDrawPhaseObservable.add((()=>{this._renderTime.beginMonitoring(),Ds.StartPerformanceCounter("Main render")})),this._onAfterDrawPhaseObserver=this.scene.onAfterDrawPhaseObservable.add((()=>{this._renderTime.endMonitoring(!1),Ds.EndPerformanceCounter("Main render")}))):(this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null))}get cameraRenderTimeCounter(){return this._cameraRenderTime}get captureCameraRenderTime(){return this._captureCameraRenderTime}set captureCameraRenderTime(e){e!==this._captureCameraRenderTime&&(this._captureCameraRenderTime=e,e?(this._onBeforeCameraRenderObserver=this.scene.onBeforeCameraRenderObservable.add((e=>{this._cameraRenderTime.beginMonitoring(),Ds.StartPerformanceCounter(`Rendering camera ${e.name}`)})),this._onAfterCameraRenderObserver=this.scene.onAfterCameraRenderObservable.add((e=>{this._cameraRenderTime.endMonitoring(!1),Ds.EndPerformanceCounter(`Rendering camera ${e.name}`)}))):(this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null))}get drawCallsCounter(){return this.scene.getEngine()._drawCalls}constructor(e){this.scene=e,this._captureActiveMeshesEvaluationTime=!1,this._activeMeshesEvaluationTime=new wr,this._captureRenderTargetsRenderTime=!1,this._renderTargetsRenderTime=new wr,this._captureFrameTime=!1,this._frameTime=new wr,this._captureRenderTime=!1,this._renderTime=new wr,this._captureInterFrameTime=!1,this._interFrameTime=new wr,this._captureParticlesRenderTime=!1,this._particlesRenderTime=new wr,this._captureSpritesRenderTime=!1,this._spritesRenderTime=new wr,this._capturePhysicsTime=!1,this._physicsTime=new wr,this._captureAnimationsTime=!1,this._animationsTime=new wr,this._captureCameraRenderTime=!1,this._cameraRenderTime=new wr,this._onBeforeActiveMeshesEvaluationObserver=null,this._onAfterActiveMeshesEvaluationObserver=null,this._onBeforeRenderTargetsRenderObserver=null,this._onAfterRenderTargetsRenderObserver=null,this._onAfterRenderObserver=null,this._onBeforeDrawPhaseObserver=null,this._onAfterDrawPhaseObserver=null,this._onBeforeAnimationsObserver=null,this._onBeforeParticlesRenderingObserver=null,this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver=null,this._onAfterSpritesRenderingObserver=null,this._onBeforePhysicsObserver=null,this._onAfterPhysicsObserver=null,this._onAfterAnimationsObserver=null,this._onBeforeCameraRenderObserver=null,this._onAfterCameraRenderObserver=null,this._onBeforeAnimationsObserver=e.onBeforeAnimationsObservable.add((()=>{this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.fetchNewFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.fetchNewFrame(),this._captureFrameTime&&(Ds.StartPerformanceCounter("Scene rendering"),this._frameTime.beginMonitoring()),this._captureInterFrameTime&&this._interFrameTime.endMonitoring(),this._captureParticlesRenderTime&&this._particlesRenderTime.fetchNewFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.fetchNewFrame(),this._captureAnimationsTime&&this._animationsTime.beginMonitoring(),this._captureRenderTime&&this._renderTime.fetchNewFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.fetchNewFrame(),this.scene.getEngine()._drawCalls.fetchNewFrame()})),this._onAfterRenderObserver=e.onAfterRenderObservable.add((()=>{this._captureFrameTime&&(Ds.EndPerformanceCounter("Scene rendering"),this._frameTime.endMonitoring()),this._captureRenderTime&&this._renderTime.endMonitoring(!1),this._captureInterFrameTime&&this._interFrameTime.beginMonitoring(),this._captureActiveMeshesEvaluationTime&&this._activeMeshesEvaluationTime.endFrame(),this._captureRenderTargetsRenderTime&&this._renderTargetsRenderTime.endFrame(),this._captureParticlesRenderTime&&this._particlesRenderTime.endFrame(),this._captureSpritesRenderTime&&this._spritesRenderTime.endFrame(),this._captureRenderTime&&this._renderTime.endFrame(),this._captureCameraRenderTime&&this._cameraRenderTime.endFrame()}))}dispose(){this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=null,this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver),this._onBeforeActiveMeshesEvaluationObserver=null,this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver),this._onAfterActiveMeshesEvaluationObserver=null,this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver),this._onBeforeRenderTargetsRenderObserver=null,this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver),this._onAfterRenderTargetsRenderObserver=null,this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver),this._onBeforeAnimationsObserver=null,this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver),this._onBeforeParticlesRenderingObserver=null,this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver),this._onAfterParticlesRenderingObserver=null,this._onBeforeSpritesRenderingObserver&&(this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver),this._onBeforeSpritesRenderingObserver=null),this._onAfterSpritesRenderingObserver&&(this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver),this._onAfterSpritesRenderingObserver=null),this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver),this._onBeforeDrawPhaseObserver=null,this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver),this._onAfterDrawPhaseObserver=null,this._onBeforePhysicsObserver&&(this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver),this._onBeforePhysicsObserver=null),this._onAfterPhysicsObserver&&(this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver),this._onAfterPhysicsObserver=null),this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver),this._onAfterAnimationsObserver=null,this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=null,this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=null,this.scene=null}}Bi.ShadersStore.glowMapGenerationPixelShader="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;uniform float glowIntensity;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;varying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform mat4 diffuseMatrix;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform mat4 opacityMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform mat4 emissiveMatrix;\n#endif\n#ifdef VERTEXALPHA\nattribute vec4 color;varying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef CUBEMAP\nvPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*worldPos;gl_Position=vPosition;\n#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef OPACITYUV2\nvUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef VERTEXALPHA\nvColor=color;\n#endif\n#include\n}";class wv{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||0===t)&&e.subMeshes)for(let t=0;t{let r;this.onBeforeRenderMainTextureObservable.notifyObservers(this);const n=this._scene.getEngine();if(s.length){for(n.setColorWrite(!1),r=0;r{e.clear(this.neutralColor,!0,!0,!0)})),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e})),this._mainTexture.onAfterUnbindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=e}))}}_addCustomEffectDefines(e){}_isReady(e,t,i){const s=this._scene.getEngine(),r=e.getMesh(),n=r._internalAbstractMeshDataInfo._materialForRenderPass?.[s.currentRenderPassId];if(n)return n.isReadyForSubMesh(r,e,t);const o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);const a=[],l=[er.PositionKind];let h=!1,c=!1;if(o){const e=o.needAlphaTesting(),t=o.getAlphaTestTexture(),i=t&&t.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);t&&(e||i)&&(a.push("#define DIFFUSE"),r.isVerticesDataPresent(er.UV2Kind)&&1===t.coordinatesIndex?(a.push("#define DIFFUSEUV2"),c=!0):r.isVerticesDataPresent(er.UVKind)&&(a.push("#define DIFFUSEUV1"),h=!0),e&&(a.push("#define ALPHATEST"),a.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||a.push("#define DIFFUSE_ISLINEAR"));const s=o.opacityTexture;s&&(a.push("#define OPACITY"),r.isVerticesDataPresent(er.UV2Kind)&&1===s.coordinatesIndex?(a.push("#define OPACITYUV2"),c=!0):r.isVerticesDataPresent(er.UVKind)&&(a.push("#define OPACITYUV1"),h=!0))}i&&(a.push("#define EMISSIVE"),r.isVerticesDataPresent(er.UV2Kind)&&1===i.coordinatesIndex?(a.push("#define EMISSIVEUV2"),c=!0):r.isVerticesDataPresent(er.UVKind)&&(a.push("#define EMISSIVEUV1"),h=!0),i.gammaSpace||a.push("#define EMISSIVE_ISLINEAR")),r.useVertexColors&&r.isVerticesDataPresent(er.ColorKind)&&r.hasVertexAlpha&&o.transparencyMode!==ta.MATERIAL_OPAQUE&&(l.push(er.ColorKind),a.push("#define VERTEXALPHA")),h&&(l.push(er.UVKind),a.push("#define UV1")),c&&(l.push(er.UV2Kind),a.push("#define UV2"));const u=new Ll;if(r.useBones&&r.computeBonesUsingShaders){l.push(er.MatricesIndicesKind),l.push(er.MatricesWeightsKind),r.numBoneInfluencers>4&&(l.push(er.MatricesIndicesExtraKind),l.push(er.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers);const e=r.skeleton;e&&e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),r.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,r)}else a.push("#define NUM_BONE_INFLUENCERS 0");const d=r.morphTargetManager;let _=0;d&&(_=d.numMaxInfluencers||d.numInfluencers,_>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+_),d.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),Eo(l,r,_))),t&&(a.push("#define INSTANCES"),Po(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),go(o,this._scene,a),this._addCustomEffectDefines(a);const p=e._getDrawWrapper(void 0,!0),f=p.defines,m=a.join("\n");if(f!==m){const e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];mo(e),p.setEffect(this._engine.createEffect("glowMapGeneration",l,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],m,u,void 0,void 0,{maxSimultaneousMorphTargets:_}),m)}return p.effect.isReady()}render(){for(let e=0;eh.setMatrix("world",t)))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(s)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[er.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return Ds.Instantiate(e.customType).Parse(e,t,i)}}wv._SceneComponentInitialization=e=>{throw xt("EffectLayerSceneComponent")},Ze([rt()],wv.prototype,"name",void 0),Ze([dt()],wv.prototype,"neutralColor",void 0),Ze([rt()],wv.prototype,"isEnabled",void 0),Ze([mt()],wv.prototype,"camera",null),Ze([rt()],wv.prototype,"renderingGroupId",null),Ze([rt()],wv.prototype,"disableBoundingBoxesFromEffectLayer",void 0),X.AddParser(or.NAME_EFFECTLAYER,((e,t,i,s)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let r=0;r{this.scene.addEffectLayer(e)}))}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach((e=>{this.scene.removeEffectLayer(e),t&&e.dispose()}))}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,s=this.scene.effectLayers;for(const r of s){if(!r.hasMesh(e))continue;const s=r._mainTexture;this._engine.currentRenderPassId=s.renderPassId;for(const s of e.subMeshes)if(!r.isReady(s,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const s of i)if(s.shouldRender()&&(!s.camera||s.camera.cameraRigMode===In.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==In.RIG_MODE_NONE&&s.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||s.needStencil();const e=s._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i{let t=e._getComponent(or.NAME_EFFECTLAYER);t||(t=new Nv(e),e._addComponent(t))};Bi.ShadersStore.glowMapMergePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);baseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.glowMapMergeVertexShader="attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}",X.prototype.getGlowLayerByName=function(e){for(let t=0;t{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess1=new mg("GlowLayerVBP1",new de(0,1),n,{width:e,height:t},null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new mg("GlowLayerHBP2",new de(1,0),n,{width:s,height:r},null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=s,this._horizontalBlurPostprocess2.height=r,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._blurTexture1)})),this._verticalBlurPostprocess2=new mg("GlowLayerVBP2",new de(0,1),n,{width:s,height:r},null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add((()=>{const e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);const t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(t??e,!0)}})),this._postProcesses.map((e=>{e.autoClear=!1}))}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s)return!1;const r=i.emissiveTexture;return super._isReady(e,t,r)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(ta.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let s=1;this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector?this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color):i.emissiveColor?(s*=i.emissiveIntensity??1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){const e=St.Serialize(this);let t;if(e.customType="BABYLON.GlowLayer",e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew Fv(e.name,t,e.options)),e,t,i);let r;for(r=0;r{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)}))}}class Bv extends wv{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new K,this.onAfterBlurObservable=new K,this._instanceGlowingMeshStencilReference=Bv.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=Bv.NeutralColor,this._engine.isStencilEnable||Ne.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return Bv.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[er.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?Os(e,this._maxSize):e,t=this._engine.needPOTTextures?Os(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new ih("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=Pa.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=Pa.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(Pa.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new yc("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._horizontalBlurPostprocess=new Lv("HighlightLayerHBP",new de(1,0),this._options.blurHorizontalSize,1,null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._verticalBlurPostprocess=new Lv("HighlightLayerVBP",new de(0,1),this._options.blurVerticalSize,1,null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new mg("HighlightLayerHBP",new de(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess=new mg("HighlightLayerVBP",new de(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add((()=>{this.onBeforeBlurObservable.notifyObservers(this);const e=this._blurTexture.renderTarget;e&&(this._scene.postProcessManager.directRender(this._postProcesses,e,!0),this._engine.unBindFramebuffer(e,!0)),this.onAfterBlurObservable.notifyObservers(this)})),this._postProcesses.map((e=>{e.autoClear=!1}))}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s||!this._meshes)return!1;let r=null;const n=this._meshes[s.uniqueId];return n&&n.glowEmissiveOnly&&i&&(r=i.emissiveTexture),super._isReady(e,t,r)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);const i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(ta.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(ta.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return!!super.shouldRender()&&!!this._meshes}_shouldRenderMesh(e){return!(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]||!super.hasMesh(e))}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){const s=this._meshes[e.uniqueId];s?this._emissiveTextureAndColor.color.set(s.color.r,s.color.g,s.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),s&&s.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(this._excludedMeshes&&!this._excludedMeshes[e.uniqueId]){const t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add((e=>{t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)})),t.afterRender=e.onAfterRenderObservable.add((e=>{e.getEngine().setStencilBuffer(t.stencilState)})),this._excludedMeshes[e.uniqueId]=t}}removeExcludedMesh(e){if(!this._excludedMeshes)return;const t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!!this._meshes&&!!super.hasMesh(e)&&void 0!==this._meshes[e.uniqueId]&&null!==this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;const s=this._meshes[e.uniqueId];s?s.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add((e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))})),observerDefault:e.onAfterRenderObservable.add((e=>{this.isEnabled&&this._defaultStencilReference(e)})),glowEmissiveOnly:i},e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;const t=this._meshes[e.uniqueId];t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(const e in this._meshes)if(this._meshes[e]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes)for(const e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){const t=this._meshes[e];t&&this.removeMesh(t.mesh)}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(Bv.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(const e in this._meshes){const t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(const e in this._excludedMeshes){const t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){const e=St.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(const t in this._meshes){const i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(const t in this._excludedMeshes){const i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){const s=St.Parse((()=>new Bv(e.name,t,e.options)),e,t,i);let r;for(r=0;rthis._drawCameraPredicate(t,!0,!0,e.layerMask)))}_drawCameraForegroundWithPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!0,e.layerMask)))}_drawCameraForegroundWithoutPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!1,e.layerMask)))}_drawRenderTargetPredicate(e,t,i,s,r){return e.renderTargetTextures.length>0&&e.isBackground===t&&e.applyPostProcess===i&&e.renderTargetTextures.indexOf(r)>-1&&!!(e.layerMask&s)}_drawRenderTargetBackground(e){this._draw((t=>this._drawRenderTargetPredicate(t,!0,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithoutPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!1,this.scene.activeCamera.layerMask,e)))}addFromContainer(e){e.layers&&e.layers.forEach((e=>{this.scene.layers.push(e)}))}removeFromContainer(e,t=!1){e.layers&&e.layers.forEach((e=>{const i=this.scene.layers.indexOf(e);-1!==i&&this.scene.layers.splice(i,1),t&&e.dispose()}))}}Bi.ShadersStore.layerPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef LINEAR\nbaseColor.rgb=toGammaSpace(baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.layerVertexShader="attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class Vv{set applyPostProcess(e){this._applyPostProcess=e}get applyPostProcess(){return this.isBackground||this._applyPostProcess}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}constructor(e,t,i,s,r){this.name=e,this._applyPostProcess=!0,this.scale=new de(1,1),this.offset=new de(0,0),this.alphaBlendingMode=2,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this.isEnabled=!0,this._vertexBuffers={},this.onDisposeObservable=new K,this.onBeforeRenderObservable=new K,this.onAfterRenderObservable=new K,this.texture=t?new Pa(t,i,!0):null,this.isBackground=void 0===s||s,this.color=void 0===r?new Ae(1,1,1,1):r,this._scene=i||re.LastCreatedScene;let n=this._scene._getComponent(or.NAME_LAYER);n||(n=new kv(this._scene),this._scene._addComponent(n)),this._scene.layers.push(this);const o=this._scene.getEngine();this._drawWrapper=new Un(o);const a=[];a.push(1,1),a.push(-1,1),a.push(-1,-1),a.push(1,-1);const l=new er(o,a,er.PositionKind,!1,!1,2);this._vertexBuffers[er.PositionKind]=l,this._createIndexBuffer()}_createIndexBuffer(){const e=this._scene.getEngine(),t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[er.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}isReady(){const e=this._scene.getEngine();let t="";this.alphaTest&&(t="#define ALPHATEST"),this.texture&&!this.texture.gammaSpace&&(t+="\n#define LINEAR"),this._previousDefines!==t&&(this._previousDefines=t,this._drawWrapper.effect=e.createEffect("layer",[er.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],t));const i=this._drawWrapper.effect;return i?.isReady()&&this.texture?.isReady()}render(){if(!this.isEnabled)return;const e=this._scene.getEngine();if(!this.isReady())return;const t=this._drawWrapper.effect;this.onBeforeRenderObservable.notifyObservers(this),e.enableEffect(this._drawWrapper),e.setState(!1),t.setTexture("textureSampler",this.texture),t.setMatrix("textureMatrix",this.texture.getTextureMatrix()),t.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),t.setVector2("offset",this.offset),t.setVector2("scale",this.scale),e.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.alphaTest?e.drawElementsType(ta.TriangleFillMode,0,6):(e.setAlphaMode(this.alphaBlendingMode),e.drawElementsType(ta.TriangleFillMode,0,6),e.setAlphaMode(0)),this.onAfterRenderObservable.notifyObservers(this)}dispose(){const e=this._vertexBuffers[er.PositionKind];e&&(e.dispose(),this._vertexBuffers[er.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null),this.renderTargetTextures=[];const t=this._scene.layers.indexOf(this);this._scene.layers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()}}class Uv{static AddFlare(e,t,i,s,r){return new Uv(e,t,i,s,r)}constructor(e,t,i,s,r){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new Ee(1,1,1),this.texture=s?new Pa(s,r.getScene(),!0):null,this._system=r;const n=r.scene.getEngine();this._drawWrapper=new Un(n),this._drawWrapper.effect=n.createEffect("lensFlare",[er.PositionKind],["color","viewportMatrix"],["textureSampler"],""),r.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();const e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}Bi.ShadersStore.lensFlarePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.lensFlareVertexShader="attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class Gv{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||re.LastCreatedScene,Gv._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&!!(e.layerMask&i.activeCamera.layerMask);const s=i.getEngine(),r=[];r.push(1,1),r.push(-1,1),r.push(-1,-1),r.push(1,-1),this._vertexBuffers[er.PositionKind]=new er(s,r,er.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=_e.Project(t,me.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=_e.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);const i=this._scene.useRightHandedSystem;return!!(t.z>0&&!i||t.z<0&&i)&&(this._positionX>e.x&&this._positionXe.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;const e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();const i=new Ua(this._scene.activeCamera.globalPosition,e),s=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!s||!s.hit||s.distance>t}render(){if(!this._scene.activeCamera)return!1;const e=this._scene.getEngine(),t=this._scene.activeCamera.viewport.toGlobal(e.getRenderWidth(!0),e.getRenderHeight(!0));if(!this.computeEffectivePosition(t))return!1;if(!this._isVisible())return!1;let i,s;i=this._positionXt.x+t.width-this.borderLimit?this._positionX-t.x-t.width+this.borderLimit:0,s=this._positionYt.y+t.height-this.borderLimit?this._positionY-t.y-t.height+this.borderLimit:0;let r=i>s?i:s;r-=this.viewportBorder,r>this.borderLimit&&(r=this.borderLimit);let n=1-be.Clamp(r/this.borderLimit,0,1);if(n<0)return!1;n>1&&(n=1),this.viewportBorder>0&&(t.x+=this.viewportBorder,t.y+=this.viewportBorder,t.width-=2*this.viewportBorder,t.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);const o=t.x+t.width/2,a=t.y+t.height/2,l=o-this._positionX,h=a-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let i=0;i{throw xt("LensFlareSystemSceneComponent")},X.AddParser(or.NAME_LENSFLARESYSTEM,((e,t,i,s)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(let r=0,n=e.lensFlareSystems.length;r{this.scene.addLensFlareSystem(e)}))}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach((e=>{this.scene.removeLensFlareSystem(e),t&&e.dispose()}))}serialize(e){e.lensFlareSystems=[];const t=this.scene.lensFlareSystems;for(const i of t)e.lensFlareSystems.push(i.serialize())}dispose(){const e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){const t=this.scene.lensFlareSystems;Ds.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)e.layerMask&i.layerMask&&i.render();Ds.EndPerformanceCounter("Lens flares",t.length>0)}}}Gv._SceneComponentInitialization=e=>{let t=e._getComponent(or.NAME_LENSFLARESYSTEM);t||(t=new zv(e),e._addComponent(t))};Bi.IncludesShadersStore.bayerDitherFunctions="float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);}\nfloat bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5*mod(_P,4.0)); \nreturn 4.0*bayerDither2(P1)+bayerDither2(P2);}\nfloat bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5 *mod(_P,4.0)); \nvec2 P4=floor(0.25*mod(_P,8.0)); \nreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}\n";Bi.IncludesShadersStore.shadowMapFragmentExtraDeclaration="#if SM_FLOAT==0\n#include\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include\nuniform float softTransparentShadowSM;\n#endif\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nuniform vec3 lightDataSM;varying vec3 vPositionWSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";Bi.IncludesShadersStore.shadowMapFragment="float depthSM=vDepthMetricSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\ndepthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_FragDepth=clamp(1.0-depthSM,0.0,1.0);\n#else\ngl_FragDepth=clamp(depthSM,0.0,1.0); \n#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);\n#endif\n#if SM_FLOAT==1\ngl_FragColor=vec4(depthSM,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depthSM);\n#endif\nreturn;";Bi.ShadersStore.shadowMapPixelShader="#include\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEXTURE\nfloat alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;\n#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard;\n#else\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;\n#endif\n#endif\n#include\n}";Bi.IncludesShadersStore.sceneVertexDeclaration="uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\nuniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition;\n";Bi.IncludesShadersStore.meshVertexDeclaration="uniform mat4 world;uniform float visibility;\n";Bi.IncludesShadersStore.shadowMapVertexDeclaration="#include\n#include\n";Bi.IncludesShadersStore.shadowMapUboDeclaration="layout(std140,column_major) uniform;\n#include\n#include\n";Bi.IncludesShadersStore.shadowMapVertexExtraDeclaration="#if SM_NORMALBIAS==1\nuniform vec3 lightDataSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nvarying vec3 vPositionWSM;\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";Bi.IncludesShadersStore.shadowMapVertexNormalBias="#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvec3 worldLightDirSM=normalize(-lightDataSM.xyz);\n#else\nvec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM);\n#endif\nfloat ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM;\n#endif\n";Bi.IncludesShadersStore.shadowMapVertexMetric="#if SM_USEDISTANCE==1\nvPositionWSM=worldPos.xyz;\n#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#else\ngl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nzSM=gl_Position.z;gl_Position.z=0.0;\n#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\nvDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n";Bi.ShadersStore.shadowMapVertexShader="attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;\n#endif\n#include\n#include<__decl__shadowMapVertex>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normWorldSM=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvec3 vNormalW=normalize(normWorldSM*normalUpdated);\n#endif\n#endif\n#include\ngl_Position=viewProjection*worldPos;\n#include\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}";Bi.ShadersStore.depthBoxBlurPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}";Bi.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow="#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;\n#endif\n";class Wv{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===Wv.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(e===Wv.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(e===Wv.FILTER_PCF||e===Wv.FILTER_PCSS)return void(this.usePoissonSampling=!0)}e!==Wv.FILTER_PCF&&e!==Wv.FILTER_PCSS||this._scene.getEngine()._features.supportShadowSamplers?this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0}get usePoissonSampling(){return this.filter===Wv.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(Wv.FILTER_POISSONSAMPLING);(e||this.filter===Wv.FILTER_POISSONSAMPLING)&&(this.filter=e?t:Wv.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===Wv.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(Wv.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===Wv.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:Wv.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===Wv.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(Wv.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===Wv.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:Wv.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===Wv.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(Wv.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===Wv.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:Wv.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===Wv.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(Wv.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===Wv.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:Wv.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===Wv.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(Wv.FILTER_PCF);(e||this.filter===Wv.FILTER_PCF)&&(this.filter=e?t:Wv.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===Wv.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(Wv.FILTER_PCSS);(e||this.filter===Wv.FILTER_PCSS)&&(this.filter=e?t:Wv.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return this._darkness=e>=1?1:e<=0?0:e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return Wv.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(const t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(const t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}_getCamera(){return this._camera??this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,s,r){this.onBeforeShadowMapRenderObservable=new K,this.onAfterShadowMapRenderObservable=new K,this.onBeforeShadowMapRenderMeshObservable=new K,this.onAfterShadowMapRenderMeshObservable=new K,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=Wv.FILTER_NONE,this._filteringQuality=Wv.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=_e.Zero(),this._viewMatrix=me.Zero(),this._projectionMatrix=me.Zero(),this._transformMatrix=me.Zero(),this._cachedPosition=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=me.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=s??null,this._useRedTextureType=!!r;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),Wv._SceneComponentInitialization(this._scene);const o=this._scene.getEngine().getCaps();i?o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new ih(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForShadowGenerator-${this._light.name}`)):this._shadowMap=new ih(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=Pa.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=Pa.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(Pa.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,s)=>this._renderForShadowMap(e,t,i,s),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`shadow map generation for pass id ${e.currentRenderPassId}`,1)})),this._shadowMap.onBeforeRenderObservable.add((t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===Wv.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onAfterUnbindObservable.add((()=>{if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===Wv.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap)return void e._debugPopGroup?.(1);const t=this.getShadowMapForRendering();t&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,t.renderTarget,!0),e.unBindFramebuffer(t.renderTarget,!0),e._debugPopGroup?.(1))}));const t=new Ae(0,0,0,0),i=new Ae(1,1,1,1);this._shadowMap.onClearObservable.add((e=>{this._filter===Wv.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)})),this._shadowMap.onResizeObservable.add((e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}));for(let e=nr.MIN_RENDERINGGROUPS;e{e.setTexture("textureSampler",this._shadowMap)})),this._kernelBlurYPostprocess=new mg(this._light.name+"KernelBlurY",new de(0,1),this.blurKernel,1,null,Pa.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new Vl(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,Pa.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add((e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,s){let r;if(s.length)for(r=0;r{s===i||e?(s.getMeshUniformBuffer().bindToEffect(h,"Mesh"),s.transferToEffect(e?t:_)):(i.getMeshUniformBuffer().bindToEffect(h,"Mesh"),i.transferToEffect(t))})),this.forceBackFacesOnly&&n.setState(!0,0,!1,!1,o.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(h),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===Wv.FILTER_NONE||this.filter===Wv.FILTER_PCSS?this._shadowMap.updateSamplingMode(Pa.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(Pa.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},s=this.getShadowMap();if(!s)return void(e&&e(this));const r=s.renderList;if(!r)return void(e&&e(this));const n=[];for(const e of r)n.push(...e.subMeshes);if(0===n.length)return void(e&&e(this));let o=0;const a=()=>{if(this._scene&&this._scene.getEngine()){for(;this.isReady(n[o],i.useInstances,n[o].getMaterial()?.needAlphaBlendingForMesh(n[o].getMesh())??!1);)if(o++,o>=n.length)return void(e&&e(this));setTimeout(a,16)}};a()}forceCompilationAsync(e){return new Promise((t=>{this.forceCompilation((()=>{t()}),e)}))}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,s){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const r=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&r.isVerticesDataPresent(er.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===ua.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&s?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){const s=e.getMaterial(),r=s?.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;const n=[];if(this._prepareShadowDefines(e,t,n,i),r){if(!r.isReadyForSubMesh(e,n,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const i=e._getDrawWrapper(void 0,!0);let r=i.effect,o=i.defines;const a=[er.PositionKind],l=e.getMesh();this.normalBias&&l.isVerticesDataPresent(er.NormalKind)&&(a.push(er.NormalKind),n.push("#define NORMAL"),l.nonUniformScaling&&n.push("#define NONUNIFORMSCALING"));const h=s.needAlphaTesting();if((h||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const e=s.alphaCutOff??Wv.DEFAULT_ALPHA_CUTOFF;n.push("#define ALPHATEXTURE"),h&&n.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),l.isVerticesDataPresent(er.UVKind)&&(a.push(er.UVKind),n.push("#define UV1")),l.isVerticesDataPresent(er.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(a.push(er.UV2Kind),n.push("#define UV2"))}const c=new Ll;if(l.useBones&&l.computeBonesUsingShaders&&l.skeleton){a.push(er.MatricesIndicesKind),a.push(er.MatricesWeightsKind),l.numBoneInfluencers>4&&(a.push(er.MatricesIndicesExtraKind),a.push(er.MatricesWeightsExtraKind));const e=l.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+l.numBoneInfluencers),l.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,l),e.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(e.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");const u=l.morphTargetManager;let d=0;if(u&&(d=u.numMaxInfluencers||u.numInfluencers,d>0&&(n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+d),u.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),Eo(a,l,d))),go(s,this._scene,n),t&&(n.push("#define INSTANCES"),Po(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const e of this.customShaderOptions.defines)-1===n.indexOf(e)&&n.push(e);const _=l.bakedVertexAnimationManager;t&&_&&_.isEnabled&&(n.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),a.push("bakedVertexAnimationSettingsInstanced"));const p=n.join("\n");if(o!==p){o=p;let e="shadowMap";const t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],s=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],n=["Scene","Mesh"];if(mo(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const e of this.customShaderOptions.attributes)-1===a.indexOf(e)&&a.push(e);if(this.customShaderOptions.uniforms)for(const e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(const e of this.customShaderOptions.samplers)-1===s.indexOf(e)&&s.push(e)}const l=this._scene.getEngine();r=l.createEffect(e,{attributes:a,uniformsNames:t,uniformBuffersNames:n,samplers:s,defines:p,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:d}},l),i.setEffect(r,o)}if(!r.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){const i=this._scene,s=this._light;i.shadowsEnabled&&s.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===Wv.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Wv.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===Wv.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===Wv.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),s.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();if(!r)return;i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix());const n=this.getShadowMapForRendering();this._filter===Wv.FILTER_PCF?(t.setDepthStencilTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),r.getSize().width,1/r.getSize().width,this.frustumEdgeFalloff,e)):this._filter===Wv.FILTER_PCSS?(t.setDepthStencilTexture("shadowTexture"+e,n),t.setTexture("depthTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/r.getSize().width,this._contactHardeningLightSizeUVRatio*r.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/r.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e)}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){const e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),_e.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(_e.Dot(this._lightDirection,_e.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),me.LookAtLHToRef(t,t.add(this._lightDirection),_e.Up(),this._viewMatrix);const e=this.getShadowMap();if(e){const t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){const e=this._shadowMap;if(!e)return;const t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(const e of t)this._shadowMap.renderList.push(e)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){const e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){const e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=this._camera?.id,e.id=this.id,e.mapSize=t.getRenderSize(),e.forceBackFacesOnly=this.forceBackFacesOnly,e.darkness=this.getDarkness(),e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.filteringQuality=this.filteringQuality,e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.depthScale=this.depthScale,e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.renderList=[],t.renderList)for(let i=0;i{throw xt("ShadowGeneratorSceneComponent")};Bi.ShadersStore.depthPixelShader="#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\nvarying float vDepthMetric;\n#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\n#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\n#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\n#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";Bi.IncludesShadersStore.pointCloudVertexDeclaration="#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";Bi.ShadersStore.depthVertexShader="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;uniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;varying vec4 vViewPos;\n#endif\n#include\nvarying float vDepthMetric;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#include\ngl_Position=viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\n#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}\n";class Hv{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,s=!1,r=Pa.TRILINEAR_SAMPLINGMODE,n=!1,o){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=s,this._storeCameraSpaceZ=n,this.isPacked=0===t,this.isPacked?this.clearColor=new Ae(1,1,1,1):this.clearColor=new Ae(n?1e8:1,0,0,1),Hv._SceneComponentInitialization(this._scene);const a=e.getEngine();this._camera=i,r!==Pa.NEAREST_SAMPLINGMODE&&(1!==t||a._caps.textureFloatLinearFiltering||(r=Pa.NEAREST_SAMPLINGMODE),2!==t||a._caps.textureHalfFloatLinearFiltering||(r=Pa.NEAREST_SAMPLINGMODE));const l=this.isPacked||!a._features.supportExtendedTextureFormats?5:6;this._depthMap=new ih(o??"DepthRenderer",{width:a.getRenderWidth(),height:a.getRenderHeight()},this._scene,!1,!0,t,!1,r,void 0,void 0,void 0,l),this._depthMap.wrapU=Pa.CLAMP_ADDRESSMODE,this._depthMap.wrapV=Pa.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((e=>{e.clear(this.clearColor,!0,!0,!0)})),this._depthMap.onBeforeBindObservable.add((()=>{a._debugPushGroup?.("depth renderer",1)})),this._depthMap.onAfterUnbindObservable.add((()=>{a._debugPopGroup?.(1)})),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),s=this._scene,r=s.getEngine(),n=e.getMaterial();if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!n||i.infiniteDistance||n.disableDepthWrite||0===e.verticesCount||e._renderId===s.getRenderId())return;const o=i._getWorldMatrixDeterminant()<0;let a=t.overrideMaterialSideOrientation??n.sideOrientation;o&&(a=0===a?1:0);const l=0===a;r.setState(n.backFaceCulling,0,!1,l,this.reverseCulling?!n.cullBackFaces:n.cullBackFaces);const h=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(h.mustReturn)return;const c=r.getCaps().instancedArrays&&(null!==h.visibleInstances[e._id]&&void 0!==h.visibleInstances[e._id]||t.hasThinInstances),u=this._camera||s.activeCamera;if(this.isReady(e,c)&&u){e._renderId=s.getRenderId();const o=i._internalAbstractMeshDataInfo._materialForRenderPass?.[r.currentRenderPassId];let a=e._getDrawWrapper();!a&&o&&(a=o._getDrawWrapper());const l=u.mode===In.ORTHOGRAPHIC_CAMERA;if(!a)return;const d=a.effect;let _,p;if(r.enableEffect(a),c||t._bind(e,d,n.fillMode),o?o.bindForSubMesh(i.getWorldMatrix(),i,e):(d.setMatrix("viewProjection",s.getTransformMatrix()),d.setMatrix("world",i.getWorldMatrix()),this._storeCameraSpaceZ&&d.setMatrix("view",s.getViewMatrix())),l?(_=!r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1,p=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1):(_=r.useReverseDepthBuffer&&r.isNDCHalfZRange?u.minZ:r.isNDCHalfZRange?0:u.minZ,p=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:u.maxZ),d.setFloat2("depthValues",_,_+p),!o){if(n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(d.setTexture("diffuseSampler",e),d.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices){const i=e.getTransformMatrixTexture(t);if(!i)return;d.setTexture("boneSampler",i),d.setFloat("boneTextureWidth",4*(e.bones.length+1))}else d.setMatrices("mBones",e.getTransformMatrices(t))}xo(d,n,s),Io(t,d),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(d),n.pointsCloud&&d.setFloat("pointSize",n.pointSize)}t._processRendering(i,e,d,n.fillMode,h,c,((e,t)=>d.setMatrix("world",t)))}};this._depthMap.customRenderFunction=(e,t,i,s)=>{let r;if(s.length)for(r=0;r4&&(l.push(er.MatricesIndicesExtraKind),l.push(er.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),a.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));const t=e.getRenderingMesh().skeleton;t?.isUsingTextureForMatrices&&a.push("#define BONETEXTURE")}else a.push("#define NUM_BONE_INFLUENCERS 0");const h=s.morphTargetManager;let c=0;h&&(c=h.numMaxInfluencers||h.numInfluencers,c>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+c),h.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),Eo(l,s,c))),o.pointsCloud&&a.push("#define POINTSIZE"),t&&(a.push("#define INSTANCES"),Po(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&a.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&a.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&a.push("#define PACKED"),go(o,r,a);const u=e._getDrawWrapper(void 0,!0),d=u.defines,_=a.join("\n");if(d!==_){const e=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];mo(e),u.setEffect(i.createEffect("depth",l,e,["diffuseSampler","morphTargets","boneSampler"],_,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),_)}return u.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}Hv._SceneComponentInitialization=e=>{throw xt("DepthRendererSceneComponent")};Bi.ShadersStore.minmaxReduxPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#if defined(INITIAL)\nuniform sampler2D sourceTexture;uniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4);\n#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\n#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\n#endif\nglFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(MAIN)\nuniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(LAST)\nvoid main(void)\n{glFragColor=vec4(0.);if (true) { \ndiscard;}}\n#endif\n";class Xv{constructor(e){this.onAfterReductionPerformed=new K,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new ir(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{this._postProcessManager._rebuild()}))}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,s=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=s;const r=this._camera.getScene(),n=new Vl("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,r.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);n.autoClear=!1,n.forceFullscreenViewport=s;let o=this._sourceTexture.getRenderWidth(),a=this._sourceTexture.getRenderHeight();n.onApply=((e,t)=>i=>{i.setTexture("sourceTexture",this._sourceTexture),i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(n);let l=1;for(;o>1||a>1;){o=Math.max(Math.round(o/2),1),a=Math.max(Math.round(a/2),1);const e=new Vl("Reduction phase "+l,"minmaxRedux",["texSize"],null,{width:o,height:a},null,1,r.getEngine(),!1,"#define "+(1==o&&1==a?"LAST":1==o||1==a?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=s,e.onApply=((e,t)=>i=>{1==e||1==t?i.setInt2("texSize",e,t):i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(e),l++,1==o&&1==a){const t=(e,t,i)=>{const s=new Float32Array(4*e*t),n={min:0,max:0};return()=>{r.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,s,!1),n.min=s[0],n.max=s[1],this.onAfterReductionPerformed.notifyObservers(n)}};e.onAfterRenderObservable.add(t(o,a,e))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add((()=>{const e=this._camera.getScene().getEngine();e._debugPushGroup?.("min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),e.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),e._debugPopGroup?.(1)})),this._activated=!0)}deactivate(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let e=0;ethis._computeShadowCastersBoundingInfo()))),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){const e=this._shadowMap.renderList;for(let t=0;tt&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return Zv.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let t=e.min,i=e.max;t>=i&&(t=0,i=1),t==this._minDistance&&i==this._maxDistance||this.setMinMaxDistance(t,i)})),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate??-1}set autoCalcDepthBoundsRefreshRate(e){this._depthReducer?.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,s=i-t,r=this._minDistance,n=t+r*s,o=t+(this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance)*s,a=o-n,l=o/n;for(let e=0;e{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===Wv.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()})),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==Wv.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,s=this._light;if(!i.shadowsEnabled||!s.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const r=this._getCamera();r&&this._shadowMaxZ<=(r.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();if(!r)return;const n=r.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===Wv.FILTER_PCF)t.setDepthStencilTexture("shadowTexture"+e,r),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n,1/n,this.frustumEdgeFalloff,e);else if(this._filter===Wv.FILTER_PCSS){for(let e=0;enew Zv(e,t,void 0,i)));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}Zv._FrustumCornersNDCSpace=[new _e(-1,1,-1),new _e(1,1,-1),new _e(1,-1,-1),new _e(-1,-1,-1),new _e(-1,1,1),new _e(1,1,1),new _e(1,-1,1),new _e(-1,-1,1)],Zv.CLASSNAME="CascadedShadowGenerator",Zv.DEFAULT_CASCADES_COUNT=4,Zv.MIN_CASCADES_COUNT=2,Zv.MAX_CASCADES_COUNT=4,Zv._SceneComponentInitialization=e=>{throw xt("ShadowGeneratorSceneComponent")},X.AddParser(or.NAME_SHADOWGENERATOR,((e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,s=e.shadowGenerators.length;i{let t=e._getComponent(or.NAME_SHADOWGENERATOR);t||(t=new Jv(e),e._addComponent(t))},Et.AddNodeConstructor("Light_Type_0",((e,t)=>()=>new ex(e,_e.Zero(),t)));class ex extends hg{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){const t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return ua.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new _e(1,0,0);case 1:return new _e(-1,0,0);case 2:return new _e(0,-1,0);case 3:return new _e(0,1,0);case 4:return new _e(0,0,1);case 5:return new _e(0,0,-1)}return _e.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;const r=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;me.PerspectiveFovLHToRef(this.shadowAngle,1,o?n:r,o?r:n,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}}Ze([rt()],ex.prototype,"shadowAngle",null),z("BABYLON.PointLight",ex);class tx{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css",this._style.innerHTML="@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }",document.getElementsByTagName("head")[0].appendChild(this._style);const e=!!window.SVGSVGElement,t=new Image;tx.DefaultLogoUrl?t.src=tx.DefaultLogoUrl:t.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",t.style.width="150px",t.style.gridColumn="1",t.style.gridRow="1",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.position="absolute";const i=document.createElement("div");i.style.width="300px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const s=new Image;if(tx.DefaultSpinnerUrl?s.src=tx.DefaultSpinnerUrl:s.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!e){const e={w:16,h:18.5},i={w:30,h:30};t.style.width=`${e.w}vh`,t.style.height=`${e.h}vh`,t.style.left=`calc(50% - ${e.w/2}vh)`,t.style.top=`calc(50% - ${e.h/2}vh)`,s.style.width=`${i.w}vh`,s.style.height=`${i.h}vh`,s.style.left=`calc(50% - ${i.w/2}vh)`,s.style.top=`calc(50% - ${i.h/2}vh)`}i.appendChild(s),this._loadingDiv.appendChild(t),this._loadingDiv.appendChild(i),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",(()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)})))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}tx.DefaultLogoUrl="",tx.DefaultSpinnerUrl="",ns.DefaultLoadingScreenFactory=e=>new tx(e);class ix{static ConvertPanoramaToCubemap(e,t,i,s,r=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(s,this.FACE_FRONT,e,t,i,r),back:this.CreateCubemapTexture(s,this.FACE_BACK,e,t,i,r),left:this.CreateCubemapTexture(s,this.FACE_LEFT,e,t,i,r),right:this.CreateCubemapTexture(s,this.FACE_RIGHT,e,t,i,r),up:this.CreateCubemapTexture(s,this.FACE_UP,e,t,i,r),down:this.CreateCubemapTexture(s,this.FACE_DOWN,e,t,i,r),size:s,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,s,r,n=!1){const o=new ArrayBuffer(e*e*4*3),a=new Float32Array(o),l=n?Math.max(1,Math.round(s/4/e)):1,h=1/l,c=h*h,u=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),_=1/e;let p=0;for(let n=0;nMath.PI;)r-=2*Math.PI;let o=r/Math.PI;const a=n/Math.PI;o=.5*o+.5;let l=Math.round(o*i);l<0?l=0:l>=i&&(l=i-1);let h=Math.round(a*s);h<0?h=0:h>=s&&(h=s-1);const c=s-h-1;return{r:t[c*i*3+3*l+0],g:t[c*i*3+3*l+1],b:t[c*i*3+3*l+2]}}}ix.FACE_LEFT=[new _e(-1,-1,-1),new _e(1,-1,-1),new _e(-1,1,-1),new _e(1,1,-1)],ix.FACE_RIGHT=[new _e(1,-1,1),new _e(-1,-1,1),new _e(1,1,1),new _e(-1,1,1)],ix.FACE_FRONT=[new _e(1,-1,-1),new _e(1,-1,1),new _e(1,1,-1),new _e(1,1,1)],ix.FACE_BACK=[new _e(-1,-1,1),new _e(-1,-1,-1),new _e(-1,1,1),new _e(-1,1,-1)],ix.FACE_DOWN=[new _e(1,1,-1),new _e(1,1,1),new _e(-1,1,-1),new _e(-1,1,1)],ix.FACE_UP=[new _e(-1,-1,-1),new _e(-1,-1,1),new _e(1,-1,-1),new _e(1,-1,1)];class sx{static _Ldexp(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,s,r,n){r>0?(r=this._Ldexp(1,r-136),e[n+0]=t*r,e[n+1]=i*r,e[n+2]=s*r):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}static _ReadStringLine(e,t){let i="",s="";for(let r=t;r32767)throw"HDR Bad header format, unsupported size";return o+=s.length+1,{height:t,width:i,dataPosition:o}}static GetCubeMapTextureData(e,t,i=!1){const s=new Uint8Array(e),r=this.RGBE_ReadHeader(s),n=this.RGBE_ReadPixels(s,r);return ix.ConvertPanoramaToCubemap(n,r.width,r.height,t,i)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i=t.height;const s=t.width;let r,n,o,a,l,h=t.dataPosition,c=0,u=0,d=0;const _=new ArrayBuffer(4*s),p=new Uint8Array(_),f=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(f);for(;i>0;){if(r=e[h++],n=e[h++],o=e[h++],a=e[h++],2!=r||2!=n||128&o||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((o<<8|a)!=s)throw"HDR Bad header format, wrong scan line width";for(c=0,d=0;d<4;d++)for(u=(d+1)*s;c128){if(l=r-128,0==l||l>u-c)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)p[c++]=n}else{if(l=r,0==l||l>u-c)throw"HDR Bad Format, bad scanline data (non-run)";if(p[c++]=n,--l>0)for(let t=0;t0;){for(l=0;l{this._effectRenderer=new Kl(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled((()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()}))})):(Ne.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}}class nx extends ya{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(me.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,s=!1,r=!0,n=!1,o=!1,a=null,l=null,h=!1){super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=_e.Zero(),this.onLoadObservable=new K,e&&(this._coordinatesMode=Pa.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=me.Identity(),this._prefilterOnLoad=o,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),a&&a()},this._onError=l,this.gammaSpace=n,this._noMipmap=s,this._size=i,this._supersample=h,this._generateHarmonics=r,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?Ds.SetImmediate((()=>this._onLoad())):this._texture.onLoadedObservable.add(this._onLoad):this.getScene()?.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture())}getClassName(){return"HDRCubeTexture"}_loadTexture(){const e=this._getEngine(),t=e.getCaps();let i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const t=this._onLoad,i=new rx(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,(e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const t=sx.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){const e=$_.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}const s=[];let r=null,n=null;for(let e=0;e<6;e++){2===i?n=new Uint16Array(this._size*this._size*3):0===i&&(r=new Uint8Array(this._size*this._size*3));const o=t[nx._FacesMapping[e]];if(this.gammaSpace||n||r)for(let e=0;e255){const e=255/n;t*=e,i*=e,s*=e}r[3*e+0]=t,r[3*e+1]=i,r[3*e+2]=s}n?s.push(n):r?s.push(r):s.push(o)}return s}),null,this._onLoad,this._onError)}clone(){const e=new nx(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&this.getScene()?.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(this)))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let s=null;return e.name&&!e.isRenderTarget&&(s=new nx(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),s.name=e.name,s.hasAlpha=e.hasAlpha,s.level=e.level,s.coordinatesMode=e.coordinatesMode,s.isBlocking=e.isBlocking),s&&(e.boundingBoxPosition&&(s.boundingBoxPosition=_e.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=_e.FromArray(e.boundingBoxSize)),e.rotationY&&(s.rotationY=e.rotationY)),s}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}nx._FacesMapping=["right","left","up","down","front","back"],z("BABYLON.HDRCubeTexture",nx);class ox{get influence(){return this._influence}set influence(e){if(this._influence===e)return;const t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new K,this._onDataLayoutChanged=new K,this._animationPropertiesOverride=null,this._scene=i||re.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}setPositions(e){const t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){const t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){const t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){const t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){const e=St.Clone((()=>new ox(this.name,this.influence,this._scene)),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e}serialize(){const e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),null!=this.id&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),St.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new ox(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Fs(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=re.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._syncActiveTargets(!0))}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get numTargets(){return this._targets.length}get numInfluencers(){return this._activeTargets.length}get influences(){return this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets=e}get isUsingTextureForTargets(){return lx.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!this._scene?.getEngine().getCaps().disableMorphTargetTexture}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}getTargetByName(e){for(const t of this._targets)if(t.name===e)return t;return null}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add((e=>{this._syncActiveTargets(e)}))),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add((()=>{this._syncActiveTargets(!0)}))),this._syncActiveTargets(!0)}removeTarget(e){const t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0)),this._scene&&this._scene.stopAnimation(e)}_bind(e){e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setInt("morphTargetCount",this.numInfluencers)}clone(){const e=new lx(this._scene);for(const t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){const e={};e.id=this.uniqueId,e.targets=[];for(const t of this._targets)e.targets.push(t.serialize());return e}_syncActiveTargets(e){if(this.areUpdatesFrozen)return;let t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),this._morphTargetTextureIndices&&this._morphTargetTextureIndices.length===this._targets.length||(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let i=-1;for(const e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=lx.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;const s=e.getPositions();if(s){const e=s.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e)return void Ne.Error("Incompatible target. Targets must all have the same vertices count.")}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e0)){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;const e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){const e=this._targetStoreTexture.getSize();e.width===this._textureWidth&&e.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4);let i=0;for(let s=0;s-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(const e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){const i=new lx(t);i._uniqueId=e.id;for(const s of e.targets)i.addTarget(ox.Parse(s,t));return i}}lx.EnableTextureStorage=!0,lx.MaxActiveMorphTargetsInVertexAttributeMode=8;class hx{constructor(){this._hasHit=!1,this._hitNormal=_e.Zero(),this._hitPoint=_e.Zero(),this._triangleIndex=-1}get hitPoint(){return this._hitPoint}get hitNormal(){return this._hitNormal}get hasHit(){return this._hasHit}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormal.set(e.x,e.y,e.z),this._hitPoint.set(t.x,t.y,t.z),this._triangleIndex=i??-1}reset(){this._hasHit=!1,this._hitNormal.setAll(0),this._hitPoint.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0,this.shape=void 0}}class cx extends hx{constructor(){super(...arguments),this._hitDistance=0,this._rayFromWorld=_e.Zero(),this._rayToWorld=_e.Zero()}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormal}get hitPointWorld(){return this._hitPoint}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=_e.Distance(this._rayFromWorld,this._hitPoint)}reset(e=_e.Zero(),t=_e.Zero()){super.reset(),this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hitDistance=0}}class ux{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw xt("CannonJSPlugin")}constructor(e,t=ux.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new _e(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){const t=this._impostors.indexOf(e);t>-1&&this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)}addJoint(e,t,i){const s={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(s),this._physicsPlugin.generateJoint(s)}removeJoint(e,t,i){const s=this._joints.filter((function(s){return s.connectedImpostor===t&&s.joint===i&&s.mainImpostor===e}));s.length&&this._physicsPlugin.removeJoint(s[0])}_step(e){this._impostors.forEach((e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t0&&(this._physicsBodiesToRemoveAfterStep.forEach((e=>{"function"==typeof this.world.removeBody?this.world.removeBody(e):this.world.remove(e)})),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(r,s)}applyForce(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(r,s)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const t=this._createShape(e);if(!t)return void Ne.Warn("It was not possible to create a physics body for this object.");const i=e.physicsBody;i&&this.removePhysicsBody(e);const s=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),r={mass:e.getParam("mass"),material:s},n=e.getParam("nativeOptions");for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(r[e]=n[e]);e.physicsBody=new this.BJSCANNON.Body(r),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){const s=i[t];e.physicsBody[t].set(s.x,s.y,s.z)})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}}_processChildMeshes(e){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],i=e.object.rotationQuaternion;if(i?i.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),t.length){const i=t=>{if(!t.rotationQuaternion)return;const s=t.getPhysicsImpostor();if(s&&s.parent!==e&&t.parent){const i=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),r=t.rotationQuaternion.multiply(this._tmpQuaternion);s.physicsBody&&(this.removePhysicsBody(s),s.physicsBody=null),s.parent=e,s.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(s),new this.BJSCANNON.Vec3(i.x,i.y,i.z),new this.BJSCANNON.Quaternion(r.x,r.y,r.z,r.w)),e.physicsBody.mass+=s.getParam("mass")}t.getChildMeshes(!0).filter((e=>!!e.physicsImpostor)).forEach(i)};t.filter((e=>!!e.physicsImpostor)).forEach(i)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;let s;const r=e.joint.jointData,n={pivotA:r.mainPivot?(new this.BJSCANNON.Vec3).set(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z):null,pivotB:r.connectedPivot?(new this.BJSCANNON.Vec3).set(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z):null,axisA:r.mainAxis?(new this.BJSCANNON.Vec3).set(r.mainAxis.x,r.mainAxis.y,r.mainAxis.z):null,axisB:r.connectedAxis?(new this.BJSCANNON.Vec3).set(r.connectedAxis.x,r.connectedAxis.y,r.connectedAxis.z):null,maxForce:r.nativeParams.maxForce,collideConnected:!!r.collision};switch(e.joint.type){case el.HingeJoint:case el.Hinge2Joint:s=new this.BJSCANNON.HingeConstraint(t,i,n);break;case el.DistanceJoint:s=new this.BJSCANNON.DistanceConstraint(t,i,r.maxDistance||2);break;case el.SpringJoint:{const e=r;s=new this.BJSCANNON.Spring(t,i,{restLength:e.length,stiffness:e.stiffness,damping:e.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break}case el.LockJoint:s=new this.BJSCANNON.LockConstraint(t,i,n);break;case el.PointToPointJoint:case el.BallAndSocketJoint:default:s=new this.BJSCANNON.PointToPointConstraint(t,n.pivotA,i,n.pivotB,n.maxForce)}s.collideConnected=!!r.collision,e.joint.physicsJoint=s,e.joint.type!==el.SpringJoint?this.world.addConstraint(s):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){s.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==el.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let s,r;for(s=0;s1e3*i));e++);this.time+=s;const a=this.time%i/i,l=e,h=this.bodies;for(let e=0;e!==h.length;e++){const i=h[e];i.type!==t.Body.STATIC&&i.sleepState!==t.Body.SLEEPING?(i.position.vsub(i.previousPosition,l),l.scale(a,l),i.position.vadd(l,i.interpolatedPosition)):(i.interpolatedPosition.set(i.position.x,i.position.y,i.position.z),i.interpolatedQuaternion.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w))}}}}raycast(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))}}ux.DefaultPluginFactory=()=>new dx;class _x{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=_e.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new cx}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this.world.timeStep=e}getTimeStep(){return this.world.timeStep}executeStep(e,t){t.forEach((function(e){e.beforeStep()})),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach((e=>{e.afterStep(),this._tmpImpostorsArray[e.uniqueId]=e}));let i=this.world.contacts;for(;null!==i;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];e&&t?(e.onCollide({body:t.physicsBody,point:null,distance:0,impulse:0,normal:null}),t.onCollide({body:e.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next):i=i.next}}applyImpulse(e,t,i){const s=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*s))}applyForce(e,t,i){Ne.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},s=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach((function(e){e.physicsImpostor&&s.push(e.physicsImpostor)}));const r=e=>Math.max(e,J),n=new fe;s.forEach((t=>{if(!t.object.rotationQuaternion)return;const s=t.object.rotationQuaternion;n.copyFrom(s),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);const o=n.toEulerAngles(),a=t.getObjectExtents(),l=57.29577951308232;if(t===e){const t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{const e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(o.x*l,o.y*l,o.z*l)}switch(t.object.rotationQuaternion.copyFrom(n),t.type){case nl.ParticleImpostor:Ne.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case nl.SphereImpostor:{const e=a.x,t=a.y,s=a.z,n=Math.max(r(e),r(t),r(s))/2;i.type.push("sphere"),i.size.push(n),i.size.push(n),i.size.push(n);break}case nl.CylinderImpostor:{const e=r(a.x)/2,t=r(a.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case nl.PlaneImpostor:case nl.BoxImpostor:default:{const e=r(a.x),t=r(a.y),s=r(a.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(s);break}}t.object.rotationQuaternion=s})),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(n),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}var t}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const s=e.joint.jointData,r=s.nativeParams||{};let n;const o={body1:t,body2:i,axe1:r.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:r.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:r.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:r.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:r.min,max:r.max,collision:r.collision||s.collision,spring:r.spring,world:this.world};switch(e.joint.type){case el.BallAndSocketJoint:n="jointBall";break;case el.SpringJoint:{Ne.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const e=s;o.min=e.length||o.min,o.max=Math.max(o.min,o.max)}case el.DistanceJoint:n="jointDistance",o.max=s.maxDistance;break;case el.PrismaticJoint:n="jointPrisme";break;case el.SliderJoint:n="jointSlide";break;case el.WheelJoint:n="jointWheel";break;case el.HingeJoint:default:n="jointHinge"}o.type=n,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){Ne.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{const t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){const t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){const s=e.physicsBody;e.physicsBody.shapes.next||(s.position.set(t.x,t.y,t.z),s.orientation.set(i.x,i.y,i.z,i.w),s.syncShapes(),s.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){const t=e.physicsBody.linearVelocity;return t?new _e(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new _e(t.x,t.y,t.z):null}setBodyMass(e,t){const i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,s){void 0!==i?Ne.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setMotor(t,i)}setLimit(e,t,i,s){const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setLimit(t,void 0===i?-t:i)}syncMeshWithImpostor(e,t){const i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)}getRadius(e){return e.physicsBody.shapes.radius}getBoxSizeToRef(e,t){const i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth}dispose(){this.world.clear()}raycast(e,t){return Ne.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){Ne.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class px{constructor(e=!0,t=Ammo,i=null){this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new fe,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new _e,this._tmpContactNormal=new _e,this._tmpVec3=new _e,this._tmpMatrix=new me,"function"!=typeof t?(this.bjsAMMO=t,this.isSupported()?(this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=e=>{const t=(e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint)).getPositionWorldOnA(),i=e.m_normalWorldOnB;this._tmpContactPoint.x=t.x(),this._tmpContactPoint.y=t.y(),this._tmpContactPoint.z=t.z(),this._tmpContactNormal.x=i.x(),this._tmpContactNormal.y=i.y(),this._tmpContactNormal.z=i.z(),this._tmpContactImpulse=e.getAppliedImpulse(),this._tmpContactDistance=e.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new cx,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)):Ne.Error("AmmoJS is not available. Please make sure you included the js file.")):Ne.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.")}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(e))for(const t of e._onPhysicsCollideCallbacks)for(const i of t.otherImpostors)(e.physicsBody.isActive()||i.physicsBody.isActive())&&this._isImpostorPairInContact(e,i)&&(e.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),i.onCollide({body:e.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===nl.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let s,r,n,o,a;const l=new Array;for(let e=0;e{this.bjsAMMO.destroy(e)})),e._pluginData.toDispose=[]))}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;if(e.joint.physicsJoint)return;const s=e.joint.jointData;let r;switch(s.mainPivot||(s.mainPivot=new _e(0,0,0)),s.connectedPivot||(s.connectedPivot=new _e(0,0,0)),e.joint.type){case el.DistanceJoint:{const e=s.maxDistance;e&&(s.mainPivot=new _e(0,-e/2,0),s.connectedPivot=new _e(0,e/2,0));const n=this._tmpAmmoVectorA;n.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const o=this._tmpAmmoVectorB;o.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,n,o);break}case el.HingeJoint:{s.mainAxis||(s.mainAxis=new _e(0,0,0)),s.connectedAxis||(s.connectedAxis=new _e(0,0,0));const e=this._tmpAmmoVectorA;e.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z);const o=this._tmpAmmoVectorC;o.setValue(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z);const a=this._tmpAmmoVectorD;a.setValue(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z),r=new this.bjsAMMO.btHingeConstraint(t,i,e,n,o,a);break}case el.BallAndSocketJoint:{const e=this._tmpAmmoVectorA;e.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,e,n);break}default:{Ne.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint");const e=this._tmpAmmoVectorA;e.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,e,n);break}}this.world.addConstraint(r,!e.joint.jointData.collision),e.joint.physicsJoint=r}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint),this.bjsAMMO.destroy(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n,o=i.getVerticesData(er.PositionKind);if(o||(o=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?fe.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):fe.Identity(),me.Compose(_e.One(),e,t.position).invertToRef(this._tmpMatrix),n=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else me.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),n=this._tmpMatrix;const a=r.length/3;for(let t=0;t{s+=this._addMeshVerts(e,t,i)}))}return s}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(er.PositionKind);i||(i=[]);let s=t.getVerticesData(er.NormalKind);s||(s=[]),t.computeWorldMatrix(!1);const r=[],n=[];for(let e=0;ee*e)).reduce(((e,t)=>e+t)))t=r.length,i=t/3-1,this._tmpAmmoVectorA.setValue(r[0],r[1],r[2]),this._tmpAmmoVectorB.setValue(r[t-3],r[t-2],r[t-1]);else{e._isFromLine=!1;const s=e.getParam("path");if(null===e.getParam("shape"))return Ne.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;t=s.length,i=t-1,this._tmpAmmoVectorA.setValue(s[0].x,s[0].y,s[0].z),this._tmpAmmoVectorB.setValue(s[t-1].x,s[t-1].y,s[t-1].z)}e.segments=i;let o=e.getParam("fixedPoints");o=o>3?3:o;const a=(new this.bjsAMMO.btSoftBodyHelpers).CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,o);return a.get_m_cfg().set_collisions(17),a}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n=i.getVerticesData(er.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);const o=r.length/3;for(let t=0;t{s+=this._addHullVerts(e,t,i)}))}return s}_createShape(e,t=!1){const i=e.object;let s;const r=e.getObjectExtents();if(!t){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];s=new this.bjsAMMO.btCompoundShape;let i=0;if(t.forEach((e=>{const t=e.getPhysicsImpostor();if(t){if(t.type==nl.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const r=this._createShape(t),n=e.parent.getWorldMatrix().clone(),o=new _e;n.decompose(o),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*o.x,e.position.y*o.y,e.position.z*o.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,r),t.dispose(),i++}})),i>0){if(e.type!=nl.NoImpostor){const t=this._createShape(e,!0);t&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,t))}return s}this.bjsAMMO.destroy(s),s=null}switch(e.type){case nl.SphereImpostor:if(be.WithinEpsilon(r.x,r.y,1e-4)&&be.WithinEpsilon(r.x,r.z,1e-4))s=new this.bjsAMMO.btSphereShape(r.x/2);else{this._tmpAmmoVectorA.setValue(0,0,0);const e=[this._tmpAmmoVectorA],t=[1];s=new this.bjsAMMO.btMultiSphereShape(e,t,1),this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s.setLocalScaling(this._tmpAmmoVectorA)}break;case nl.CapsuleImpostor:{const e=r.x/2;s=new this.bjsAMMO.btCapsuleShape(e,r.y-2*e)}break;case nl.CylinderImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case nl.PlaneImpostor:case nl.BoxImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case nl.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)s=this.onCreateCustomMeshImpostor(e);else{const t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);const r=this._addMeshVerts(t,i,i);s=0==r?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case nl.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)s=this.onCreateCustomConvexHullImpostor(e);else{const t=new this.bjsAMMO.btConvexHullShape;0==this._addHullVerts(t,i,i)?(e._pluginData.toDispose.push(t),s=new this.bjsAMMO.btCompoundShape):s=t}break;case nl.NoImpostor:s=new this.bjsAMMO.btSphereShape(r.x/2);break;case nl.CustomImpostor:s=this._createCustom(e);break;case nl.SoftbodyImpostor:s=this._createSoftbody(e);break;case nl.ClothImpostor:s=this._createCloth(e);break;case nl.RopeImpostor:s=this._createRope(e);break;default:Ne.Warn("The impostor type is not currently supported by the ammo plugin.")}return s}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){const s=e.physicsBody.getWorldTransform();if(Math.abs(s.getOrigin().x()-t.x)>J||Math.abs(s.getOrigin().y()-t.y)>J||Math.abs(s.getOrigin().z()-t.z)>J||Math.abs(s.getRotation().x()-i.x)>J||Math.abs(s.getRotation().y()-i.y)>J||Math.abs(s.getRotation().z()-i.z)>J||Math.abs(s.getRotation().w()-i.w)>J)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),s.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),s.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(s),0==e.mass){const t=e.physicsBody.getMotionState();t&&t.setWorldTransform(s)}else e.physicsBody.activate()}isSupported(){return void 0!==this.bjsAMMO}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity(),!t)return null;const i=new _e(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity(),!t)return null;const i=new _e(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}setBodyMass(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t}getBodyMass(e){return e._pluginData.mass||0}getBodyFriction(e){return e._pluginData.friction||0}setBodyFriction(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t}getBodyRestitution(e){return e._pluginData.restitution||0}setBodyRestitution(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t}getBodyPressure(e){return e.soft?e._pluginData.pressure||0:(Ne.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===nl.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):Ne.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(Ne.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):Ne.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(Ne.Warn("Velocity iterations is not a property of a rigid body"),0)}setBodyVelocityIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):Ne.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(Ne.Warn("Position iterations is not a property of a rigid body"),0)}setBodyPositionIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):Ne.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,s,r=1,n=!1){const o=e.segments,a=Math.round((o-1)*i)+o*(o-1-Math.round((o-1)*s));e.physicsBody.appendAnchor(a,t.physicsBody,n,r)}appendHook(e,t,i,s=1,r=!1){const n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,r,s)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){Ne.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){Ne.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){return e.getObjectExtents().x/2}getBoxSizeToRef(e,t){const i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._softBodySolver),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoVectorD),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);const s=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,s),i.reset(e,t),s.hasHit()&&(i.setHitData({x:s.get_m_hitNormalWorld().x(),y:s.get_m_hitNormalWorld().y(),z:s.get_m_hitNormalWorld().z()},{x:s.get_m_hitPointWorld().x(),y:s.get_m_hitPointWorld().y(),z:s.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(s),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}px._DISABLE_COLLISION_FLAG=4,px._KINEMATIC_FLAG=2,px._DISABLE_DEACTIVATION_FLAG=4,X.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return-1;const t=this.reflectionProbes.indexOf(e);return-1!==t&&this.reflectionProbes.splice(t,1),t},X.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};class fx{constructor(e,t,i,s=!0,r=!1,n=!1){if(this.name=e,this._viewMatrix=me.Identity(),this._target=_e.Zero(),this._add=_e.Zero(),this._invertYAxis=!1,this.position=_e.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(r){const e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?o=2:e.textureFloatRender&&(o=1)}this._renderTargetTexture=new ih(e,t,i,s,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const a=i.getEngine().useReverseDepthBuffer;let l;this._renderTargetTexture.onBeforeRenderObservable.add((e=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){case 0:this._add.copyFromFloats(1,0,0);break;case 1:this._add.copyFromFloats(-1,0,0);break;case 2:this._add.copyFromFloats(0,this._invertYAxis?1:-1,0);break;case 3:this._add.copyFromFloats(0,this._invertYAxis?-1:1,0);break;case 4:this._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:this._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1)}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);const t=i.useRightHandedSystem?me.LookAtRHToRef:me.LookAtLHToRef,s=i.useRightHandedSystem?me.PerspectiveFovRH:me.PerspectiveFovLH;t(this.position,this._target,_e.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=s(Math.PI/2,1,a?i.activeCamera.maxZ:i.activeCamera.minZ,a?i.activeCamera.minZ:i.activeCamera.maxZ,this._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(this._viewMatrix,this._projectionMatrix),i.activeCamera.isRigCamera&&!this._renderTargetTexture.activeCamera&&(this._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=this.position})),this._renderTargetTexture.onBeforeBindObservable.add((()=>{this._currentSceneUBO=i.getSceneUniformBuffer(),i.getEngine()._debugPushGroup?.(`reflection probe generation for ${e}`,1),l=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)})),this._renderTargetTexture.onAfterUnbindObservable.add((()=>{i.imageProcessingConfiguration.applyByPostProcess=l,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),i.getEngine()._debugPopGroup?.(1)}))}get samples(){return this._renderTargetTexture.samples}set samples(e){this._renderTargetTexture.samples=e}get refreshRate(){return this._renderTargetTexture.refreshRate}set refreshRate(e){this._renderTargetTexture.refreshRate=e}getScene(){return this._scene}get cubeTexture(){return this._renderTargetTexture}get renderList(){return this._renderTargetTexture.renderList}set renderList(e){this._renderTargetTexture.renderList=e}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){const e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){const e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}toString(e){let t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t}getClassName(){return"ReflectionProbe"}serialize(){const e=St.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let s=null;if(t.reflectionProbes)for(let i=0;is||new fx(e.name,e.renderTargetSize,t,e._generateMipMaps)),e,t,i),s.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&s.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(s.metadata=e.metadata),s}}Ze([ct()],fx.prototype,"_attachedMesh",void 0),Ze([ht()],fx.prototype,"position",void 0);class mx{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,s,r){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=s||1,this._animationStarted=!0,this._onBaseAnimationEnd=r,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class gx extends mx{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=new Array,this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new K,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new Ae(1,1,1,1),this.position=_e.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,s,r=null){this._onAnimationEnd=r,super.playAnimation(e,t,i,s,this._endAnimation)}dispose(){for(let e=0;e0)for(let n=0;n=r.distance))&&(r=a,i))break}return r||new tr},Hr.prototype._internalMultiPickSprites=function(e,t,i){if(!tr)return null;let s=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let r=0;r!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(or.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(or.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(or.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();const e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,s,r){const n=this.scene.pickSprite(t,i,this._spritePredicate,s,r);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,s,r){const n=this.scene;return s?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&r&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?r.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:r.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null),i}_pointerDown(e,t,i,s){const r=this.scene;if(r._pickedDownSprite=null,r.spriteManagers&&r.spriteManagers.length>0&&(i=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(r._pickedDownSprite=i.pickedSprite,s.button){case 0:i.pickedSprite.actionManager.processTrigger(2,Re.CreateNewFromSprite(i.pickedSprite,r,s));break;case 1:i.pickedSprite.actionManager.processTrigger(4,Re.CreateNewFromSprite(i.pickedSprite,r,s));break;case 2:i.pickedSprite.actionManager.processTrigger(3,Re.CreateNewFromSprite(i.pickedSprite,r,s))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,Re.CreateNewFromSprite(i.pickedSprite,r,s))}return i}_pointerUp(e,t,i,s,r){const n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){const i=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,Re.CreateNewFromSprite(i.pickedSprite,n,s)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,Re.CreateNewFromSprite(i.pickedSprite,n,s)),r&&i.pickedSprite.actionManager.processTrigger(6,Re.CreateNewFromSprite(i.pickedSprite,n,s)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==i.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,Re.CreateNewFromSprite(n._pickedDownSprite,n,s)))}return i}}Bi.IncludesShadersStore.imageProcessingCompatibility="#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));\n#endif\n";Bi.ShadersStore.spritesPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler;\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nvec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;}\n#endif\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvec2 uv=uvPixelPerfect(vUV);\n#else\nvec2 uv=vUV;\n#endif\nvec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.)\n{if (color.a<0.95)\ndiscard;}\ncolor*=vColor;\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.spritesVertexShader="attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor;\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); \nvColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y;\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";class xx{get fogEnabled(){return this._fogEnabled}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this._createEffects())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=!!this._scene?.getEngine().getCaps().fragmentDepthSupported;e&&!t&&Ne.Warn("Logarithmic depth has been requested for a sprite renderer on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._createEffects()}get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,s=null){this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this._fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=s,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new Js(e,this._vertexData,!0,this._vertexBufferSize);const r=this._buffer.createVertexBuffer(er.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),n=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing);let o,a=6;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Js(e,t,!1,2),o=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else o=this._buffer.createVertexBuffer("offsets",a,2,this._vertexBufferSize,this._useInstancing),a+=2;const l=this._buffer.createVertexBuffer("inverts",a,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",a+2,4,this._vertexBufferSize,this._useInstancing),c=this._buffer.createVertexBuffer(er.ColorKind,a+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[er.PositionKind]=r,this._vertexBuffers.options=n,this._vertexBuffers.offsets=o,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[er.ColorKind]=c,this._createEffects()}_createEffects(){this._drawWrapperBase?.dispose(),this._drawWrapperDepth?.dispose(),this._drawWrapperBase=new Un(this._engine),this._drawWrapperDepth=new Un(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing);let e="";this._pixelPerfect&&(e+="#define PIXEL_PERFECT\n"),this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&this._fogEnabled&&(e+="#define FOG\n"),this._useLogarithmicDepth&&(e+="#define LOGARITHMICDEPTH\n"),this._drawWrapperBase.effect=this._engine.createEffect("sprites",[er.PositionKind,"options","offsets","inverts","cellInfo",er.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor","logarithmicDepthConstant"],["diffuseSampler"],e),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext}render(e,t,i,s,r=null){if(!this.texture||!this.texture.isReady()||!e.length)return;const n=this._drawWrapperBase,o=this._drawWrapperDepth,a=this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode,l=n.effect;if(!l.isReady())return;const h=this._engine,c=!(!this._scene||!this._scene.useRightHandedSystem),u=this.texture.getBaseSize(),d=Math.min(this._capacity,e.length);let _=0,p=!0;for(let i=0;i{e.cellRef||(e.cellIndex=0);const i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=this._spriteMap[e.cellIndex]),e._xOffset=this._cellData[e.cellRef].frame.x/t.width,e._yOffset=this._cellData[e.cellRef].frame.y/t.height,e._xSize=this._cellData[e.cellRef].frame.w,e._ySize=this._cellData[e.cellRef].frame.h},r||(r=re.LastCreatedScene),r._getComponent(or.NAME_SPRITE)||r._addComponent(new vx(r)),this._fromPacked=a,this._scene=r;const h=this._scene.getEngine();if(this._spriteRenderer=new xx(h,i,n,r),s.width&&s.height)this.cellWidth=s.width,this.cellHeight=s.height;else{if(void 0===s)return void(this._spriteRenderer=null);this.cellWidth=s,this.cellHeight=s}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new Pa(t,r,!0,!1,o)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if(e="string"==typeof t?JSON.parse(t):t,e.frames.length){const t={};for(let i=0;i0);const s=e.substring(0,i-1)+".json",r=()=>{Ne.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},n=e=>{try{const t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};Ds.LoadFile(s,n,void 0,void 0,!1,r)}}_checkTextureAlpha(e,t,i,s,r){if(!e.useAlphaForPicking||!this.texture)return!0;const n=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(n.width*n.height*4),this.texture.readPixels(0,0,this._textureContent));const o=ve.Vector3[0];o.copyFrom(t.direction),o.normalize(),o.scaleInPlace(i),o.addInPlace(t.origin);const a=(o.x-s.x)/(r.x-s.x),l=1-(o.y-s.y)/(r.y-s.y),h=e._xOffset*n.width+a*e._xSize|0,c=e._yOffset*n.height+l*e._ySize|0;return this._textureContent[4*(h+c*n.width)+3]>.5}intersects(e,t,i,s){const r=Math.min(this.capacity,this.sprites.length),n=_e.Zero(),o=_e.Zero();let a=Number.MAX_VALUE,l=null;const h=ve.Vector3[0],c=ve.Vector3[1],u=t.getViewMatrix();let d=e,_=e;for(let t=0;te){if(!this._checkTextureAlpha(r,d,e,n,o))continue;if(_=d,a=e,l=r,s)break}}}}if(l){const e=new tr;u.invertToRef(ve.Matrix[0]),e.hit=!0,e.pickedSprite=l,e.distance=a;const t=ve.Vector3[2];return t.copyFrom(_.direction),t.normalize(),t.scaleInPlace(a),_.origin.addToRef(t,h),e.pickedPoint=_e.TransformCoordinates(h,ve.Matrix[0]),e}return null}multiIntersects(e,t,i){const s=Math.min(this.capacity,this.sprites.length),r=_e.Zero(),n=_e.Zero();let o;const a=[],l=ve.Vector3[0].copyFromFloats(0,0,0),h=ve.Vector3[1].copyFromFloats(0,0,0),c=t.getViewMatrix();for(let t=0;t{const o=new Pt;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=bx.Parse(t,i||re.LastCreatedScene,s);e&&(n.name=e),r(n)}else n("Unable to load the sprite manager")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new bx("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise(((s,r)=>{const n=new Pt;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const r=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(r.spriteManager),a=bx.Parse(o,t||re.LastCreatedScene,i);a.snippetId=e,s(a)}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}bx.SnippetUrl="https://snippet.babylonjs.com",bx.CreateFromSnippetAsync=bx.ParseFromSnippetAsync;var Tx=!0;class yx{}yx.LoaderInjectedPhysicsEngine=void 0;let Sx={},Cx={};const Ex=(e,t,i,s)=>{if(!t.materials)return null;for(let r=0,n=t.materials.length;r{for(const s in t)if(e.name===t[s])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},Px=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),Ix=(e,t)=>{const i=t;if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){const s=t._waitingData.lods.ids,r=i.isEnabled(!1);if(t._waitingData.lods.distances){const n=t._waitingData.lods.distances;if(n.length>=s.length){const t=n.length>s.length?n[n.length-1]:0;i.setEnabled(!1);for(let t=0;t0&&i.addLODLevel(t,null),!0===r&&i.setEnabled(!0)}else Ds.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},Rx=(e,t,i)=>{if("number"!=typeof e){const s=i.getLastEntryById(e);return s&&null!=t?s.instances[parseInt(t)]:s}const s=Sx[e];return s&&null!=t?s.instances[parseInt(t)]:s},Mx=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):Cx[e],Ox=(e,t,i,s,r=!1)=>{const n=new pa(e);let o="importScene has failed JSON parse";try{var a=JSON.parse(t);o="";const s=fl.loggingLevel===fl.DETAILED_LOGGING;let r,l;if(void 0!==a.environmentTexture&&null!==a.environmentTexture){const t=void 0===a.isPBR||a.isPBR;if(a.environmentTextureType&&"BABYLON.HDRCubeTexture"===a.environmentTextureType){const s=a.environmentTextureSize?a.environmentTextureSize:128,r=new nx((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,s,!0,!t,void 0,a.environmentTexturePrefilterOnLoad);a.environmentTextureRotationY&&(r.rotationY=a.environmentTextureRotationY),e.environmentTexture=r}else if("object"==typeof a.environmentTexture){const t=vg.Parse(a.environmentTexture,e,i);e.environmentTexture=t}else if(a.environmentTexture.endsWith(".env")){const t=new vg((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}else{const t=vg.CreateFromPrefilteredData((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}if(!0===a.createDefaultSkybox){const i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,s=a.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,s)}n.environmentTexture=e.environmentTexture}if(void 0!==a.environmentIntensity&&null!==a.environmentIntensity&&(e.environmentIntensity=a.environmentIntensity),void 0!==a.lights&&null!==a.lights)for(r=0,l=a.lights.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})))}if(void 0!==a.multiMaterials&&null!==a.multiMaterials)for(r=0,l=a.multiMaterials.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)}))}if(void 0!==a.morphTargetManagers&&null!==a.morphTargetManagers)for(const t of a.morphTargetManagers){const i=lx.Parse(t,e);n.morphTargetManagers.push(i),i._parentContainer=n}if(void 0!==a.skeletons&&null!==a.skeletons)for(r=0,l=a.skeletons.length;r{e&&(n.geometries.push(e),e._parentContainer=n)}))}if(void 0!==a.transformNodes&&null!==a.transformNodes)for(r=0,l=a.transformNodes.length;r{t._waitingSubMaterialsUniqueIds.forEach((i=>{t.subMaterials.push(Mx(i,e))})),t._waitingSubMaterialsUniqueIds=[]})),e.meshes.forEach((t=>{null!==t._waitingMaterialId&&(t.material=Mx(t._waitingMaterialId,e),t._waitingMaterialId=null)})),r=0,l=e.skeletons.length;r{if(t._waitingTransformNodeId){const i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}})),t._hasWaitingData=null)}for(r=0,l=e.meshes.length;r0){for(let i=0;i0){for(let i=0;i{e._loadedUniqueId=""})),X.Parse(a,e,n,i),r=0,l=e.meshes.length;r-1!==e.indexOf("babylon"),importMesh:(e,t,i,s,r,n,o,a)=>{let l="importMesh has failed JSON parse";try{var h=JSON.parse(i);l="";const a=fl.loggingLevel===fl.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;const c=[],u=new Map,d=[];if(void 0!==h.transformNodes&&null!==h.transformNodes)for(let e=0,i=h.transformNodes.length;e{!0!==e&&h.geometries[i]&&Array.isArray(h.geometries[i])&&h.geometries[i].forEach((r=>{r.id===f.geometryId&&("vertexData"===i&&Yn.Parse(r,t,s),e=!0)}))})),!1===e&&Ne.Warn("Geometry not found for mesh "+f.id)}if(f.materialUniqueId||f.materialId){const e=f.materialUniqueId?_:n;let i=-1!==e.indexOf(f.materialUniqueId||f.materialId);if(!1===i&&void 0!==h.multiMaterials&&null!==h.multiMaterials){const r=(i,r)=>{e.push(i);const n=Ex(r,h,t,s);n&&n.material&&(Cx[n.parsedMaterial.uniqueId||n.parsedMaterial.id]=n.material,l+="\n\tMaterial "+n.material.toString(a))};for(let s=0,n=h.multiMaterials.length;sr(e,(t=>t.uniqueId===e)))):n.materials.forEach((e=>r(e,(t=>t.id===e)))),e.push(n.uniqueId||n.id);const s=ia.ParseMultiMaterial(n,t);Cx[n.uniqueId||n.id]=s,s&&(i=!0,l+="\n\tMulti-Material "+s.toString(a));break}}}if(!1===i){e.push(f.materialUniqueId||f.materialId);const i=Ex((e=>f.materialUniqueId&&e.uniqueId===f.materialUniqueId||e.id===f.materialId),h,t,s);i&&i.material?(Cx[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,l+="\n\tMaterial "+i.material.toString(a)):Ne.Warn("Material not found for mesh "+f.id)}}if(null!==f.skeletonId&&void 0!==f.skeletonId&&-1!==h.skeletonId&&void 0!==h.skeletons&&null!==h.skeletons&&!(i.indexOf(f.skeletonId)>-1))for(let e=0,s=h.skeletons.length;e-1&&void 0!==h.morphTargetManagers&&null!==h.morphTargetManagers&&!(p.indexOf(f.morphTargetManagerId)>-1))for(let e=0,i=h.morphTargetManagers.length;e{e._waitingSubMaterialsUniqueIds.forEach((i=>{e.subMaterials.push(Mx(i,t))})),e._waitingSubMaterialsUniqueIds=[]})),t.meshes.forEach((e=>{null!==e._waitingMaterialId&&(e.material=Mx(e._waitingMaterialId,t),e._waitingMaterialId=null)}));for(let e=0,i=t.transformNodes.length;e-1&&d.splice(e,1)}f._waitingParentId=null}f._waitingData.lods&&Ix(t,f)}for(const e of d)e.dispose();for(let e=0,i=t.skeletons.length;e{if(e._waitingTransformNodeId){const i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}})),i._hasWaitingData=null)}for(let e=0,i=t.meshes.length;e{e._loadedUniqueId=""})),!0}catch(e){const t=Px("importMesh",h?h.producer:"Unknown")+l;if(!a)throw Ne.Log(t),e;a(t,e)}finally{null!==l&&fl.loggingLevel!==fl.NO_LOGGING&&Ne.Log(Px("importMesh",h?h.producer:"Unknown")+(fl.loggingLevel!==fl.MINIMAL_LOGGING?l:"")),Cx={}}return!1},load:(e,t,i,s)=>{let r="importScene has failed JSON parse";try{var n=JSON.parse(t);switch(r="",void 0!==n.useDelayedTextureLoading&&null!==n.useDelayedTextureLoading&&(e.useDelayedTextureLoading=n.useDelayedTextureLoading&&!fl.ForceFullSceneLoadingForIncremental),void 0!==n.autoClear&&null!==n.autoClear&&(e.autoClear=n.autoClear),void 0!==n.clearColor&&null!==n.clearColor&&(e.clearColor=Ae.FromArray(n.clearColor)),void 0!==n.ambientColor&&null!==n.ambientColor&&(e.ambientColor=Ee.FromArray(n.ambientColor)),void 0!==n.gravity&&null!==n.gravity&&(e.gravity=_e.FromArray(n.gravity)),void 0!==n.useRightHandedSystem&&(e.useRightHandedSystem=!!n.useRightHandedSystem),void 0!==n.fogMode&&null!==n.fogMode&&(e.fogMode=n.fogMode),void 0!==n.fogColor&&null!==n.fogColor&&(e.fogColor=Ee.FromArray(n.fogColor)),void 0!==n.fogStart&&null!==n.fogStart&&(e.fogStart=n.fogStart),void 0!==n.fogEnd&&null!==n.fogEnd&&(e.fogEnd=n.fogEnd),void 0!==n.fogDensity&&null!==n.fogDensity&&(e.fogDensity=n.fogDensity),r+="\tFog mode for scene: ",e.fogMode){case 0:r+="none\n";break;case 1:r+="exp\n";break;case 2:r+="exp2\n";break;case 3:r+="linear\n"}if(n.physicsEnabled){let t;"cannon"===n.physicsEngine||n.physicsEngine===dx.name?t=new dx(void 0,void 0,yx.LoaderInjectedPhysicsEngine):"oimo"===n.physicsEngine||n.physicsEngine===_x.name?t=new _x(void 0,yx.LoaderInjectedPhysicsEngine):"ammo"!==n.physicsEngine&&n.physicsEngine!==px.name||(t=new px(void 0,yx.LoaderInjectedPhysicsEngine,void 0)),r="\tPhysics engine "+(n.physicsEngine?n.physicsEngine:"oimo")+" enabled\n";const i=n.physicsGravity?_e.FromArray(n.physicsGravity):null;e.enablePhysics(i,t)}return void 0!==n.metadata&&null!==n.metadata&&(e.metadata=n.metadata),void 0!==n.collisionsEnabled&&null!==n.collisionsEnabled&&(e.collisionsEnabled=n.collisionsEnabled),!!Ox(e,t,i,s,!0)&&(n.autoAnimate&&e.beginAnimation(e,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1),void 0!==n.activeCameraID&&null!==n.activeCameraID&&e.setActiveCameraById(n.activeCameraID),!0)}catch(e){const t=Px("importScene",n?n.producer:"Unknown")+r;if(!s)throw Ne.Log(t),e;s(t,e)}finally{null!==r&&fl.loggingLevel!==fl.NO_LOGGING&&Ne.Log(Px("importScene",n?n.producer:"Unknown")+(fl.loggingLevel!==fl.MINIMAL_LOGGING?r:""))}return!1},loadAssetContainer:(e,t,i,s)=>Ox(e,t,i,s)});class Dx{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,oo.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||Ee.White(),this.rightColor=e.rightColor||Ee.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){const e=new Dx;return Ye.DeepCopy(this,e),e}equals(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled}serialize(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}}static Parse(e){return new Dx({isEnabled:e.isEnabled,leftColor:Ee.FromArray(e.leftColor),rightColor:Ee.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}St._FresnelParametersParser=Dx.Parse;class wx{}wx.BindSceneUniformBuffer=Ro,wx.PrepareDefinesForMergedUV=Mo,wx.BindTextureMatrix=Oo,wx.GetFogState=Uo,wx.PrepareDefinesForMisc=Go,wx.PrepareDefinesForCamera=Zo,wx.PrepareDefinesForFrameBoundValues=Ho,wx.PrepareDefinesForBones=Xo,wx.PrepareDefinesForMorphTargets=Yo,wx.PrepareDefinesForBakedVertexAnimation=Qo,wx.PrepareDefinesForAttributes=jo,wx.PrepareDefinesForMultiview=Ko,wx.PrepareDefinesForOIT=$o,wx.PrepareDefinesForPrePass=qo,wx.PrepareDefinesForLight=Wo,wx.PrepareDefinesForLights=zo,wx.PrepareUniformsAndSamplersForLight=Jo,wx.PrepareUniformsAndSamplersList=ea,wx.HandleFallbacksForShadows=Vo,wx.PrepareAttributesForMorphTargetsInfluencers=Eo,wx.PrepareAttributesForMorphTargets=Ao,wx.PrepareAttributesForBakedVertexAnimation=Do,wx.PrepareAttributesForBones=Bo,wx.PrepareAttributesForInstances=ko,wx.PushAttributesForInstances=Po,wx.BindLightProperties=No,wx.BindLight=Fo,wx.BindLights=Lo,wx.BindFogParameters=Co,wx.BindBonesParameters=wo,wx.BindMorphTargetParameters=Io,wx.BindLogDepth=So;class Nx extends Nd{constructor(e,t){super(e,t,"color",{attributes:["position"],uniforms:["world","viewProjection","color"]}),this.disableColorWrite=!0,this.forceDepthWrite=!0,this.setColor4("color",new Ae(0,0,0,1))}}class Fx extends Gg{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new Ee(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}Ze([rt(),st("_markAllSubMeshesAsLightsDirty")],Fx.prototype,"maxSimultaneousLights",void 0),Ze([rt(),st("_markAllSubMeshesAsLightsDirty")],Fx.prototype,"disableLighting",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],Fx.prototype,"environmentTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Fx.prototype,"invertNormalMapX",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Fx.prototype,"invertNormalMapY",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],Fx.prototype,"normalTexture",void 0),Ze([ot("emissive"),st("_markAllSubMeshesAsTexturesDirty")],Fx.prototype,"emissiveColor",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty")],Fx.prototype,"emissiveTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],Fx.prototype,"occlusionStrength",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],Fx.prototype,"occlusionTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],Fx.prototype,"alphaCutOff",void 0),Ze([rt()],Fx.prototype,"doubleSided",null),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty",null)],Fx.prototype,"lightmapTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Fx.prototype,"useLightmapAsShadowmap",void 0);class Lx extends Fx{constructor(e,t){super(e,t),this._useRoughnessFromMetallicTextureAlpha=!1,this._useRoughnessFromMetallicTextureGreen=!0,this._useMetallnessFromMetallicTextureBlue=!0,this.metallic=1,this.roughness=1}getClassName(){return"PBRMetallicRoughnessMaterial"}clone(e){const t=St.Clone((()=>new Lx(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=St.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const s=St.Parse((()=>new Lx(e.name,t)),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}Ze([ot(),st("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Lx.prototype,"baseColor",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Lx.prototype,"baseTexture",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Lx.prototype,"metallic",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],Lx.prototype,"roughness",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],Lx.prototype,"metallicRoughnessTexture",void 0),z("BABYLON.PBRMetallicRoughnessMaterial",Lx);class Bx extends Fx{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=St.Clone((()=>new Bx(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=St.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const s=St.Parse((()=>new Bx(e.name,t)),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}Ze([ot("diffuse"),st("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Bx.prototype,"diffuseColor",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Bx.prototype,"diffuseTexture",void 0),Ze([ot("specular"),st("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],Bx.prototype,"specularColor",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty","_microSurface")],Bx.prototype,"glossiness",void 0),Ze([nt(),st("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],Bx.prototype,"specularGlossinessTexture",void 0),z("BABYLON.PBRSpecularGlossinessMaterial",Bx);class kx extends ya{constructor(e,t,i=null){if(super(t),e)if(this._textureMatrix=me.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){const e=this._getEngine();let t;t=e._features.support3DTextures?e.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):e.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=t,this._texture.isReady=!1,this.isCube=!1,this.is3D=e._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;const i=i=>{if("string"!=typeof i)return;let s,r=null,n=null;const o=i.split("\n");let a=0,l=0,h=0,c=0,u=0;for(let e=0;e0&&(e+1)%4==0)r[e]=255;else{const t=n[e];r[e]=t/u*255}t.is3D?(t.updateSize(a,a,a),e.updateRawTexture3D(t,r,5,!1)):(t.updateSize(a*a,a),e.updateRawTexture(t,r,5,!1)),t.isReady=!0,this._triggerOnLoad()},s=this.getScene();return s?s._loadFile(this.url,i):e._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){const e=new kx(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())}static Parse(e,t){let i=null;return e.name&&!e.isRenderTarget&&(i=new kx(e.name,t),i.name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}}kx._NoneEmptyLineRegex=/\S+/,z("BABYLON.ColorGradingTexture",kx);class Vx extends ya{constructor(e,t,i,s=!1,r=!0,n=null,o=null,a=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=Pa.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=a,this._noMipmap=s,this.gammaSpace=r,this._onLoad=n,this._onError=o,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?n&&(this._texture.isReady?Ds.SetImmediate((()=>n())):this._texture.onLoadedObservable.add(n)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage((()=>this._loadTexture()),this._onError)}_loadImage(e,t){const i=this.getScene();if(!i)return;const s=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,!this._noMipmap,!1,3);s.generateMipMaps=!this._noMipmap,i.addPendingData(s),s.url=this.url,s.isReady=!1,i.getEngine()._internalTexturesCache.push(s),this._texture=s;const r=document.createElement("canvas");ds(this.url,(t=>{this._width=t.width,this._height=t.height,r.width=this._width,r.height=this._height;const i=r.getContext("2d");i.drawImage(t,0,0);const s=i.getImageData(0,0,t.width,t.height);this._buffer=s.data.buffer,r.remove(),e()}),((e,r)=>{i.removePendingData(s),t&&t(`${this.getClassName()} could not be loaded`,r)}),i?i.offlineProvider:null)}_loadTexture(){const e=this.getScene();if(!e)return;const t=(()=>{const e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=ix.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){const s=t[Vx._FacesMapping[e]];i.push(s)}return i})(),i=this._texture;e.getEngine().updateRawCubeTexture(i,t,i.format,i.type,i.invertY),i.isReady=!0,e.removePendingData(i),i.onLoadedObservable.notifyObservers(i),i.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(3*e.byteLength/4);let s=0;for(let r=0;rt.length)return void Ne.Error("Unable to load TGA file - Not enough data");i+=s.id_length;let r,n=!1,o=!1,a=!1;switch(s.image_type){case Hx:n=!0;case Gx:o=!0;break;case Xx:n=!0;case zx:break;case Yx:n=!0;case Wx:a=!0}const l=s.pixel_size>>3,h=s.width*s.height*l;let c,u,d,_,p,f,m;if(o&&(c=t.subarray(i,i+=s.colormap_length*(s.colormap_size>>3))),n){let e,s,n;r=new Uint8Array(h);let o=0;const a=new Uint8Array(l);for(;i>jx){default:case qx:u=0,_=1,m=s.width,d=0,p=1,f=s.height;break;case Kx:u=0,_=1,m=s.width,d=s.height-1,p=-1,f=-1;break;case Zx:u=s.width-1,_=-1,m=-1,d=0,p=1,f=s.height;break;case $x:u=s.width-1,_=-1,m=-1,d=s.height-1,p=-1,f=-1}const g="_getImageData"+(a?"Grey":"")+s.pixel_size+"bits",v=tb[g](s,c,r,d,p,f,u,_,m);e.getEngine()._uploadDataToTextureDirectly(e,v)}const tb={GetTGAHeader:Jx,UploadContent:eb,_getImageData8bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=t,u=e.width,d=e.height;let _,p,f,m=0;const g=new Uint8Array(u*d*4);for(f=s;f!==n;f+=r)for(p=o;p!==l;p+=a,m++)_=h[m],g[4*(p+u*f)+3]=255,g[4*(p+u*f)+2]=c[3*_+0],g[4*(p+u*f)+1]=c[3*_+1],g[4*(p+u*f)+0]=c[3*_+2];return g},_getImageData16bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p,f=0;const m=new Uint8Array(c*u*4);for(p=s;p!==n;p+=r)for(_=o;_!==l;_+=a,f+=2){d=h[f+0]+(h[f+1]<<8);const e=255*((31744&d)>>10)/31|0,t=255*((992&d)>>5)/31|0,i=255*(31&d)/31|0;m[4*(_+c*p)+0]=e,m[4*(_+c*p)+1]=t,m[4*(_+c*p)+2]=i,m[4*(_+c*p)+3]=32768&d?0:255}return m},_getImageData24bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p=0;const f=new Uint8Array(c*u*4);for(_=s;_!==n;_+=r)for(d=o;d!==l;d+=a,p+=3)f[4*(d+c*_)+3]=255,f[4*(d+c*_)+2]=h[p+0],f[4*(d+c*_)+1]=h[p+1],f[4*(d+c*_)+0]=h[p+2];return f},_getImageData32bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p=0;const f=new Uint8Array(c*u*4);for(_=s;_!==n;_+=r)for(d=o;d!==l;d+=a,p+=4)f[4*(d+c*_)+2]=h[p+0],f[4*(d+c*_)+1]=h[p+1],f[4*(d+c*_)+0]=h[p+2],f[4*(d+c*_)+3]=h[p+3];return f},_getImageDataGrey8bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p,f=0;const m=new Uint8Array(c*u*4);for(p=s;p!==n;p+=r)for(_=o;_!==l;_+=a,f++)d=h[f],m[4*(_+c*p)+0]=d,m[4*(_+c*p)+1]=d,m[4*(_+c*p)+2]=d,m[4*(_+c*p)+3]=255;return m},_getImageDataGrey16bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,_,p=0;const f=new Uint8Array(c*u*4);for(_=s;_!==n;_+=r)for(d=o;d!==l;d+=a,p+=2)f[4*(d+c*_)+0]=h[p+0],f[4*(d+c*_)+1]=h[p+0],f[4*(d+c*_)+2]=h[p+0],f[4*(d+c*_)+3]=h[p+1];return f}};class ib{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=Jx(s);i(r.width,r.height,t.generateMipMaps,!1,(()=>{eb(t,s)}))}}oo._TextureLoaders.push(new ib);class sb{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=sx.RGBE_ReadHeader(s),n=sx.RGBE_ReadPixels(s,r),o=r.width*r.height,a=new Float32Array(4*o);for(let e=0;e{const e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,a)}))}}function rb(){let e=null;function t(e,t,i,s,r){const n=e.getImageTranscodedSizeInBytes(t,i,s);let o=new Uint8Array(n);return e.transcodeImage(o,t,i,s,1,0)?(r&&(o=function(e,t,i,s){const r=new Uint16Array(4),n=new Uint16Array(i*s),o=i/4,a=s/4;for(let t=0;t>2&3],n[h++]=r[l>>4&3],n[h++]=r[l>>6&3]}}return n}(o,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)),o):null}onmessage=i=>{if("init"===i.data.action){if(i.data.url)try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}e||(e=BASIS({wasmBinary:i.data.wasmBinary})),null!==e&&e.then((e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})}))}else if("transcode"===i.data.action){const e=i.data.config,s=i.data.imageData,r=new BASIS.BasisFile(s),n=function(e){const t=e.getHasAlpha(),i=e.getNumImages(),s=[];for(let t=0;t{let i;switch(e){case ab.cTFETC1:i=36196;break;case ab.cTFBC1:i=33776;break;case ab.cTFBC4:i=33779;break;case ab.cTFASTC_4x4:i=37808;break;case ab.cTFETC2:i=37496;break;case ab.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i};let cb=null,ub=null,db=0;const _b=e=>{ub=e},pb=(e,t)=>{const i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise(((e,s)=>{(cb||(cb=new Promise(((e,t)=>{ub?e(ub):Ds.LoadFileAsync(Ds.GetBabylonScriptURL(lb.WasmModuleURL)).then((i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");const s=URL.createObjectURL(new Blob([`(${rb})()`],{type:"application/javascript"}));ub=new Worker(s),function(e,t,i){return new Promise(((s,r)=>{const n=t=>{"init"===t.data.action?(e.removeEventListener("message",n),s(e)):"error"===t.data.action&&r(t.data.error||"error initializing worker")};e.addEventListener("message",n),e.postMessage({action:"init",url:i?Ds.GetBabylonScriptURL(i):void 0,wasmBinary:t},[t])}))}(ub,i,lb.JSModuleURL).then(e,t)})).catch(t)}))),cb).then((()=>{const r=db++,n=t=>{"transcode"===t.data.action&&t.data.id===r&&(ub.removeEventListener("message",n),t.data.success?e(t.data):s("Transcode is not supported on this device"))};ub.addEventListener("message",n);const o=new Uint8Array(i.byteLength);o.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),ub.postMessage({action:"transcode",id:r,imageData:o,config:t,ignoreSupportedFormats:!1},[o.buffer])}),(e=>{s(e)}))}))},fb=(e,t)=>{let i=t._gl?.TEXTURE_2D;e.isCube&&(i=t._gl?.TEXTURE_CUBE_MAP),t._bindTextureDirectly(i,e,!0)},mb=(e,t)=>{const i=e.getEngine();for(let s=0;s{i._releaseTexture(t),fb(e,i)}))}else{e.width=r.width,e.height=r.height,e.generateMipMaps=t.fileInfo.images[s].levels.length>1;const n=gb.GetInternalFormatFromBasisFormat(t.format,i);e.format=n,fb(e,i),t.fileInfo.images[s].levels.forEach(((t,r)=>{i._uploadCompressedDataToTextureDirectly(e,n,t.width,t.height,t.transcodedPixels,s,r)})),!i._features.basisNeedsPOT||be.Log2(e.width)%1==0&&be.Log2(e.height)%1==0||(Ds.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),e._cachedWrapU=Pa.CLAMP_ADDRESSMODE,e._cachedWrapV=Pa.CLAMP_ADDRESSMODE)}}},gb={JSModuleURL:lb.JSModuleURL,WasmModuleURL:lb.WasmModuleURL,GetInternalFormatFromBasisFormat:hb,TranscodeAsync:pb,LoadTextureFromTranscodeResult:mb};Object.defineProperty(gb,"JSModuleURL",{get:function(){return lb.JSModuleURL},set:function(e){lb.JSModuleURL=e}}),Object.defineProperty(gb,"WasmModuleURL",{get:function(){return lb.WasmModuleURL},set:function(e){lb.WasmModuleURL=e}});class vb{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=t.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};pb(e,o).then((e=>{const i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;mb(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()})).catch((e=>{Ds.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,r&&r(e)}))}loadData(e,t,i){const s=t.getEngine().getCaps(),r={supportedCompressionFormats:{etc1:!!s.etc1,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,astc:!!s.astc,bc7:!!s.bptc}};pb(e,r).then((e=>{const s=e.fileInfo.images[0].levels[0],r=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(s.width,s.height,r,-1!==e.format,(()=>{mb(t,e)}))})).catch((e=>{Ds.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),Ds.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,(()=>{}),!0)}))}}ns._TextureLoaders.push(new vb);class xb extends ih{get isSupported(){return this._engine?.getCaps().drawBuffersExtension??!1}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,s,r,n,o,a,l,h){for(let c=0;c{this.onAfterRenderObservable.notifyObservers(t)}))}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){const e=this._renderTarget?.textures;if(e){for(let t=e.length-1;t>=0;t--)this._textures[t]._texture=null;this._renderTarget?.dispose(),this._renderTarget=null}}}class bb{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class Tb{constructor(e,t,i,s){return this.name=e,this.meshes=t,this.scene=s,this.options=i,this.options.map=this.options.map??["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=this.options.uvsIn??er.UVKind,this.options.uvsOut=this.options.uvsOut??er.UVKind,this.options.layout=this.options.layout??Tb.LAYOUT_STRIP,this.options.layout===Tb.LAYOUT_COLNUM&&(this.options.colnum=this.options.colnum??8),this.options.updateInputMeshes=this.options.updateInputMeshes??!0,this.options.disposeSources=this.options.disposeSources??!0,this._expecting=0,this.options.fillBlanks=this.options.fillBlanks??!0,!0===this.options.fillBlanks&&(this.options.customFillColor=this.options.customFillColor??"black"),this.options.frameSize=this.options.frameSize??256,this.options.paddingRatio=this.options.paddingRatio??.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=this.options.paddingMode??Tb.SUBUV_WRAP,this.options.paddingMode===Tb.SUBUV_COLOR&&(this.options.paddingColor=this.options.paddingColor??new Ae(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){const t=this._calculateSize(),i=new de(1,1).divide(t);let s=0;const r=this._expecting,n=this.meshes.length,o=Object.keys(this.sets);for(let e=0;e{this._calculateMeshUVFrames(a,l,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i{s++,d.update(!1);const i=_.getImageData(0,0,h,h),n=this.sets[m];if(n.getContext().putImageData(i,t.x*p.x,t.y*p.y),d.dispose(),n.update(!1),s==r)return c(),void e()},m=o[u]||"_blank";if(n&&null!==n[m]){const e=n[m],t=new Image;t.src=e instanceof uu?e.getContext().canvas.toDataURL("image/png"):e.url,Ds.SetCorsBehavior(t.src,t),t.onload=()=>{_.fillStyle="rgba(0,0,0,0)",_.fillRect(0,0,h,h),d.update(!1),_.setTransform(1,0,0,-1,0,0);const e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let i=0;i<9;i++)_.drawImage(t,0,0,t.width,t.height,l+a*e[i],l+a*e[i+1]-h,a,a);break;case 1:for(let i=0;i{e.dispose&&e.dispose()};for(let e=0;e{try{if(0===this.meshes.length)return void e();let t=0;const i=i=>{if(t++,this.options.map){for(let e=0;e{i(n)}));else if(t++,t===this.meshes.length)return this._createFrames(e)}}catch(e){return t(e)}}))}dispose(){const e=Object.keys(this.sets);for(let t=0;t{const i={name:this.name,sets:{},options:{},frames:[]},s=Object.keys(this.sets),r=Object.keys(this.options);try{for(let r=0;r{try{this.setFragment(this._texturePath)}catch(e){Ne.Log("No json or ShaderStore or DOM element found for CustomProceduralTexture")}},i=e+"/config.json",s=new Pt;s.open("GET",i),s.addEventListener("load",(()=>{if(200===s.status||s.responseText&&s.responseText.length>0)try{this._config=JSON.parse(s.response),this.updateShaderUniforms(),this.updateTextures(),this.setFragment(this._texturePath+"/custom"),this._animate=this._config.animate,this.refreshRate=this._config.refreshrate}catch(e){t()}else t()}),!1),s.addEventListener("error",(()=>{t()}),!1);try{s.send()}catch(e){Ne.Error("CustomProceduralTexture: Error on XHR send request.")}}isReady(){if(!super.isReady())return!1;for(const e in this._textures)if(!this._textures[e].isReady())return!1;return!0}render(e){const t=this.getScene();this._animate&&t&&(this._time+=.03*t.getAnimationRatio(),this.updateShaderUniforms()),super.render(e)}updateTextures(){for(let e=0;e{}))}clone(){return St.Clone((()=>{const e=this.getScene(),t=this._texture,i=new Cb(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return t.source===is.CubeRawRGBD&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i}),this)}}class Eb extends Pa{constructor(e,t,i,s,r,n,o=!0,a=!1,l=Pa.TRILINEAR_SAMPLINGMODE,h=0,c){super(null,n,!o,a),this.format=r,this._texture=n.getEngine().createRawTexture3D(e,t,i,s,r,o,a,l,null,h,c),this.is3D=!0}update(e){this._texture&&this._getEngine().updateRawTexture3D(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}}class Ab extends ih{constructor(e,t,i,s){super(e,t,i,s,!0),this.refractionPlane=new Nr(0,1,0,1),this.depth=2,this.onBeforeRenderObservable.add((()=>{this.getScene().clipPlane=this.refractionPlane})),this.onAfterRenderObservable.add((()=>{this.getScene().clipPlane=null}))}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Ab(this.name,t.width,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.refractionPlane=this.refractionPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i.depth=this.depth,i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.refractionPlane.asArray(),e.depth=this.depth,e}}class Pb extends Ta{get renderTarget(){return this._renderTarget}constructor(e,t,i){super(null),this._renderTarget=null,this._engine=e,this._renderTargetOptions=i,this.resize(t)}resize(e){this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,this._size=e,this._engine&&(this._renderTarget=this._engine.createRenderTargetTexture(this._size,this._renderTargetOptions)),this._texture=this.renderTarget.texture}getInternalTexture(){return this._texture}getClassName(){return"ThinRenderTargetTexture"}dispose(e=!1){this._renderTarget?.dispose(!0),this._renderTarget=null,e||super.dispose()}}class Ib extends bl{constructor(e,t,i,s,r){super(e,t,i),this._blockType=s,this._blockName=r,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof Ib&&e._blockName===this._blockName?hl.Compatible:hl.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}class Rb extends Tl{constructor(e){super(e,ll.Vertex),this.registerInput("matricesIndices",al.Vector4),this.registerInput("matricesWeights",al.Vector4),this.registerInput("matricesIndicesExtra",al.Vector4,!0),this.registerInput("matricesWeightsExtra",al.Vector4,!0),this.registerInput("world",al.Matrix),this.registerOutput("output",al.Matrix)}initialize(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh")}getClassName(){return"BonesBlock"}get matricesIndices(){return this._inputs[0]}get matricesWeights(){return this._inputs[1]}get matricesIndicesExtra(){return this._inputs[2]}get matricesWeightsExtra(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}autoConfigure(e,t=(()=>!0)){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesIndices"===e.name&&t(e)));i||(i=new Ol("matricesIndices"),i.setAsAttribute("matricesIndices")),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesWeights"===e.name&&t(e)));i||(i=new Ol("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.World&&t(e)));i||(i=new Ol("world"),i.setAsSystemValue(_l.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){wo(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&Xo(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");const t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});const i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});const s=this._outputs[0],r=this.world;return e.compilationString+="#if NUM_BONE_INFLUENCERS>0\n",e.compilationString+=e._declareOutput(s)+` = ${r.associatedVariableName} * ${i};\n`,e.compilationString+="#else\n",e.compilationString+=e._declareOutput(s)+` = ${r.associatedVariableName};\n`,e.compilationString+="#endif\n",this}}z("BABYLON.BonesBlock",Rb);class Mb extends Tl{constructor(e){super(e,ll.Vertex),this.registerInput("world0",al.Vector4),this.registerInput("world1",al.Vector4),this.registerInput("world2",al.Vector4),this.registerInput("world3",al.Vector4),this.registerInput("world",al.Matrix,!0),this.registerOutput("output",al.Matrix),this.registerOutput("instanceID",al.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e,t=(()=>!0)){if(!this.world0.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world0"===e.name&&t(e)));i||(i=new Ol("world0"),i.setAsAttribute("world0")),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world1"===e.name&&t(e)));i||(i=new Ol("world1"),i.setAsAttribute("world1")),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world2"===e.name&&t(e)));i||(i=new Ol("world2"),i.setAsAttribute("world2")),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world3"===e.name&&t(e)));i||(i=new Ol("world3"),i.setAsAttribute("world3")),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world"===e.name&&t(e)));i||(i=new Ol("world"),i.setAsSystemValue(_l.World)),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,s=!1,r){let n=!1;i.INSTANCES!==s&&(i.setValue("INSTANCES",s),n=!0),r&&i.THIN_INSTANCES!==!!r?.getRenderingMesh().hasThinInstances&&(i.setValue("THIN_INSTANCES",!!r?.getRenderingMesh().hasThinInstances),n=!0),n&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);const t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);const i=this._outputs[0],s=this._outputs[1],r=this.world0,n=this.world1,o=this.world2,a=this.world3;let l="mat4",h="gl_InstanceID",c="float";return e.shaderLanguage===di.WGSL&&(l="mat4x4f",h="vertexInputs.instanceIndex",c="f32"),e.compilationString+="#ifdef INSTANCES\n",e.compilationString+=e._declareOutput(i)+` = ${l}(${r.associatedVariableName}, ${n.associatedVariableName}, ${o.associatedVariableName}, ${a.associatedVariableName});\n`,e.compilationString+="#ifdef THIN_INSTANCES\n",e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName};\n`,e.compilationString+="#endif\n",t._caps.canUseGLInstanceID?e.compilationString+=e._declareOutput(s)+` = ${c}(${h});\n`:e.compilationString+=e._declareOutput(s)+" = 0.0;\n",e.compilationString+="#else\n",e.compilationString+=e._declareOutput(i)+` = ${this.world.associatedVariableName};\n`,e.compilationString+=e._declareOutput(s)+" = 0.0;\n",e.compilationString+="#endif\n",this}}z("BABYLON.InstancesBlock",Mb);class Ob extends Tl{constructor(e){super(e,ll.Vertex),this.registerInput("position",al.Vector3),this.registerInput("normal",al.Vector3),this.registerInput("tangent",al.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(al.Color4|al.Vector4|al.Vector3),this.registerInput("uv",al.Vector2),this.registerOutput("positionOutput",al.Vector3),this.registerOutput("normalOutput",al.Vector3),this.registerOutput("tangentOutput",al.Vector4),this.registerOutput("uvOutput",al.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Ol("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Ol("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&t(e)));i||(i=new Ol("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Ol("uv"),i.setAsAttribute("uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const t=e.morphTargetManager;t?.isUsingTextureForTargets&&(t.numMaxInfluencers||t.numInfluencers)!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&Yo(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(Io(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,s){const r=this.position,n=this.normal,o=this.tangent,a=this.uv,l=this.positionOutput,h=this.normalOutput,c=this.tangentOutput,u=this.uvOutput,d=e,_=s.NUM_MORPH_INFLUENCERS,p=i.morphTargetManager,f=p&&p.supportsNormals&&s.NORMAL,m=p&&p.supportsTangents&&s.TANGENT,g=p&&p.supportsUVs&&s.UV1;let v="";p?.isUsingTextureForTargets&&_>0&&(v+=`${d._declareLocalVar("vertexID",al.Float)};\n`),v+="#ifdef MORPHTARGETS\n";const x=d.shaderLanguage===di.WGSL,b=x?"uniforms.":"";if(p?.isUsingTextureForTargets)v+=`for (${x?"var":"int"} i = 0; i < NUM_MORPH_INFLUENCERS; i++) {\n`,v+=`if (i >= ${b}morphTargetCount) { break; }\n`,v+=`vertexID = ${x?"f32(vertexInputs.vertexIndex":"float(gl_VertexID"}) * ${b}morphTargetTextureInfo.x;\n`,v+=`${l.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${r.associatedVariableName}) * ${b}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",f&&(v+="#ifdef MORPHTARGETS_NORMAL\n",v+=`${h.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${n.associatedVariableName}) * ${b}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),g&&(v+="#ifdef MORPHTARGETS_UV\n",v+=`${u.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${a.associatedVariableName}) * ${b}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\n",v+=`${c.associatedVariableName}.xyz += (readVector3FromRawSampler(i, vertexID) - ${o.associatedVariableName}.xyz) * ${b}morphTargetInfluences[i];\n`,o.type===al.Vector4?v+=`${c.associatedVariableName}.w = ${o.associatedVariableName}.w;\n`:v+=`${c.associatedVariableName}.w = 1.;\n`,v+="#endif\n"),v+="}\n";else for(let e=0;e<_;e++)v+=`${l.associatedVariableName} += (position${e} - ${r.associatedVariableName}) * ${b}morphTargetInfluences[${e}];\n`,f&&(v+="#ifdef MORPHTARGETS_NORMAL\n",v+=`${h.associatedVariableName} += (normal${e} - ${n.associatedVariableName}) * ${b}morphTargetInfluences[${e}];\n`,v+="#endif\n"),g&&(v+="#ifdef MORPHTARGETS_UV\n",v+=`${u.associatedVariableName}.xy += (uv_${e} - ${a.associatedVariableName}.xy) * ${b}morphTargetInfluences[${e}];\n`,v+="#endif\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\n",v+=`${c.associatedVariableName}.xyz += (tangent${e} - ${o.associatedVariableName}.xyz) * ${b}morphTargetInfluences[${e}];\n`,o.type===al.Vector4?v+=`${c.associatedVariableName}.w = ${o.associatedVariableName}.w;\n`:v+=`${c.associatedVariableName}.w = 1.;\n`,v+="#endif\n");if(v+="#endif\n",d.compilationString=d.compilationString.replace(this._repeatableContentAnchor,v),_>0)for(let e=0;e<_;e++)d.attributes.push(er.PositionKind+e),f&&d.attributes.push(er.NormalKind+e),m&&d.attributes.push(er.TangentKind+e),g&&d.attributes.push(er.UVKind+"_"+e)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e.sharedData.repeatableContentBlocks.push(this);const t=this.position,i=this.normal,s=this.tangent,r=this.uv,n=this.positionOutput,o=this.normalOutput,a=this.tangentOutput,l=this.uvOutput,h=`//${this.name}`;return e.uniforms.push("morphTargetInfluences"),e.uniforms.push("morphTargetCount"),e.uniforms.push("morphTargetTextureInfo"),e.uniforms.push("morphTargetTextureIndices"),e.samplers.push("morphTargets"),e._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration",h),e._emitFunctionFromInclude("morphTargetsVertexDeclaration",h,{repeatKey:"maxSimultaneousMorphTargets"}),e.compilationString+=`${e._declareOutput(n)} = ${t.associatedVariableName};\n`,e.compilationString+="#ifdef NORMAL\n",e.compilationString+=`${e._declareOutput(o)} = ${i.associatedVariableName};\n`,e.compilationString+="#else\n",e.compilationString+=`${e._declareOutput(o)} = vec3(0., 0., 0.);\n`,e.compilationString+="#endif\n",e.compilationString+="#ifdef TANGENT\n",e.compilationString+=`${e._declareOutput(a)} = ${s.associatedVariableName};\n`,e.compilationString+="#else\n",e.compilationString+=`${e._declareOutput(a)} = vec4(0., 0., 0., 0.);\n`,e.compilationString+="#endif\n",e.compilationString+="#ifdef UV1\n",e.compilationString+=`${e._declareOutput(l)} = ${r.associatedVariableName};\n`,e.compilationString+="#else\n",e.compilationString+=`${e._declareOutput(l)} = vec2(0., 0.);\n`,e.compilationString+="#endif\n",this._repeatableContentAnchor=e._repeatableContentAnchor,e.compilationString+=this._repeatableContentAnchor,this}}z("BABYLON.MorphTargetsBlock",Ob);class Db extends Tl{constructor(e){super(e,ll.Vertex),this.registerInput("worldPosition",al.Vector4,!1,ll.Vertex),this.registerOutput("direction",al.Vector3),this.registerOutput("color",al.Color3),this.registerOutput("intensity",al.Float),this.registerOutput("shadowBias",al.Float),this.registerOutput("shadowNormalBias",al.Float),this.registerOutput("shadowDepthScale",al.Float),this.registerOutput("shadowDepthRange",al.Vector2)}getClassName(){return"LightInformationBlock"}get worldPosition(){return this._inputs[0]}get direction(){return this._outputs[0]}get color(){return this._outputs[1]}get intensity(){return this._outputs[2]}get shadowBias(){return this._outputs[3]}get shadowNormalBias(){return this._outputs[4]}get shadowDepthScale(){return this._outputs[5]}get shadowDepthRange(){return this._outputs[6]}bind(e,t,i){if(!i)return;this.light&&this.light.isDisposed()&&(this.light=null);let s=this.light;const r=t.getScene();if(!s&&r.lights.length&&(s=this.light=r.lights[0],this._forcePrepareDefines=!0),!s||!s.isEnabled)return e.setFloat3(this._lightDataUniformName,0,0,0),void e.setFloat4(this._lightColorUniformName,0,0,0,0);s.transferToNodeMaterialEffect(e,this._lightDataUniformName),e.setColor4(this._lightColorUniformName,s.diffuse,s.intensity);const n=s.getShadowGenerator();if((this.shadowBias.hasEndpoints||this.shadowNormalBias.hasEndpoints||this.shadowDepthScale.hasEndpoints)&&(n?e.setFloat3(this._lightShadowUniformName,n.bias,n.normalBias,n.depthScale):e.setFloat3(this._lightShadowUniformName,0,0,0)),this.shadowDepthRange)if(n&&r.activeCamera){const t=s;e.setFloat2(this._lightShadowExtraUniformName,t.getDepthMinZ(r.activeCamera),t.getDepthMinZ(r.activeCamera)+t.getDepthMaxZ(r.activeCamera))}else e.setFloat2(this._lightShadowExtraUniformName,0,0)}prepareDefines(e,t,i){if(!i._areLightsDirty&&!this._forcePrepareDefines)return;this._forcePrepareDefines=!1;const s=this.light;i.setValue(this._lightTypeDefineName,!!(s&&s instanceof ex),!0)}_buildBlock(e){super._buildBlock(e),e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const t=this.direction,i=this.color,s=this.intensity,r=this.shadowBias,n=this.shadowNormalBias,o=this.shadowDepthScale,a=this.shadowDepthRange;this._lightDataUniformName=e._getFreeVariableName("lightData"),this._lightColorUniformName=e._getFreeVariableName("lightColor"),this._lightShadowUniformName=e._getFreeVariableName("shadowData"),this._lightShadowExtraUniformName=e._getFreeVariableName("shadowExtraData"),this._lightTypeDefineName=e._getFreeDefineName("LIGHTPOINTTYPE");const l=e.shaderLanguage===di.WGSL?"uniforms.":"";return e._emitUniformFromString(this._lightDataUniformName,al.Vector3),e._emitUniformFromString(this._lightColorUniformName,al.Vector4),e.compilationString+=`#ifdef ${this._lightTypeDefineName}\n`,e.compilationString+=e._declareOutput(t)+` = normalize(${this.worldPosition.associatedVariableName}.xyz - ${this._lightDataUniformName});\n`,e.compilationString+="#else\n",e.compilationString+=e._declareOutput(t)+` = ${l}${this._lightDataUniformName};\n`,e.compilationString+="#endif\n",e.compilationString+=e._declareOutput(i)+` = ${l}${this._lightColorUniformName}.rgb;\n`,e.compilationString+=e._declareOutput(s)+` = ${l}${this._lightColorUniformName}.a;\n`,(r.hasEndpoints||n.hasEndpoints||o.hasEndpoints)&&(e._emitUniformFromString(this._lightShadowUniformName,al.Vector3),r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = ${l}${this._lightShadowUniformName}.x;\n`),n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = ${l}${this._lightShadowUniformName}.y;\n`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = ${l}${this._lightShadowUniformName}.z;\n`)),a.hasEndpoints&&(e._emitUniformFromString(this._lightShadowExtraUniformName,al.Vector2),e.compilationString+=e._declareOutput(a)+` = ${this._lightShadowUniformName};\n`),this}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId))}}z("BABYLON.LightInformationBlock",Db);class wb extends Tl{constructor(e){super(e,ll.Fragment),this.convertInputToLinearSpace=!0,this.registerInput("color",al.AutoDetect),this.registerOutput("output",al.Color4),this.registerOutput("rgb",al.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Color4|al.Vector3|al.Vector4)}getClassName(){return"ImageProcessingBlock"}get color(){return this._inputs[0]}get output(){return this._outputs[0]}get rgb(){return this._outputs[1]}initialize(e){e._excludeVariableName("exposureLinear"),e._excludeVariableName("contrast"),e._excludeVariableName("vInverseScreenSize"),e._excludeVariableName("vignetteSettings1"),e._excludeVariableName("vignetteSettings2"),e._excludeVariableName("vCameraColorCurveNegative"),e._excludeVariableName("vCameraColorCurveNeutral"),e._excludeVariableName("vCameraColorCurvePositive"),e._excludeVariableName("txColorTransform"),e._excludeVariableName("colorTransformSettings"),e._excludeVariableName("ditherIntensity")}isReady(e,t,i){return!(i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}prepareDefines(e,t,i){i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i)}bind(e,t,i){i&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),e.sharedData.bindableBlocks.push(this),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity");const t=this.color,i=this._outputs[0],s=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",s),e._emitFunctionFromInclude("imageProcessingDeclaration",s),e._emitFunctionFromInclude("imageProcessingFunctions",s),t.connectedPoint?.isConnected&&(t.connectedPoint.type===al.Color4||t.connectedPoint.type===al.Vector4?e.compilationString+=`${e._declareOutput(i)} = ${t.associatedVariableName};\n`:e.compilationString+=`${e._declareOutput(i)} = vec4(${t.associatedVariableName}, 1.0);\n`,e.compilationString+="#ifdef IMAGEPROCESSINGPOSTPROCESS\n",this.convertInputToLinearSpace&&(e.compilationString+=`${i.associatedVariableName}.rgb = toLinearSpace(${t.associatedVariableName}.rgb);\n`),e.compilationString+="#else\n",e.compilationString+="#ifdef IMAGEPROCESSING\n",this.convertInputToLinearSpace&&(e.compilationString+=`${i.associatedVariableName}.rgb = toLinearSpace(${t.associatedVariableName}.rgb);\n`),e.compilationString+=`${i.associatedVariableName} = applyImageProcessing(${i.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+="#endif\n",this.rgb.hasEndpoints&&(e.compilationString+=e._declareOutput(this.rgb)+` = ${this.output.associatedVariableName}.xyz;\n`)),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace};\n`,e}serialize(){const e=super.serialize();return e.convertInputToLinearSpace=this.convertInputToLinearSpace,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertInputToLinearSpace=e.convertInputToLinearSpace??!0}}Ze([Cl("Convert input to linear space",ul.Boolean,"ADVANCED")],wb.prototype,"convertInputToLinearSpace",void 0),z("BABYLON.ImageProcessingBlock",wb);class Nb extends Tl{constructor(e){super(e,ll.Fragment,!0),this.registerInput("normal",al.AutoDetect,!1),this.normal.addExcludedConnectionPointFromAllowedTypes(al.Color4|al.Vector4|al.Vector3),this.registerInput("tangent",al.Vector4,!1),this.registerInput("world",al.Matrix,!1),this.registerOutput("TBN",al.Object,ll.Fragment,new Ib("TBN",this,cl.Output,Nb,"TBNBlock")),this.registerOutput("row0",al.Vector3,ll.Fragment),this.registerOutput("row1",al.Vector3,ll.Fragment),this.registerOutput("row2",al.Vector3,ll.Fragment)}getClassName(){return"TBNBlock"}initialize(e){e._excludeVariableName("tbnNormal"),e._excludeVariableName("tbnTangent"),e._excludeVariableName("tbnBitangent"),e._excludeVariableName("TBN")}get normal(){return this._inputs[0]}get tangent(){return this._inputs[1]}get world(){return this._inputs[2]}get TBN(){return this._outputs[0]}get row0(){return this._outputs[1]}get row1(){return this._outputs[2]}get row2(){return this._outputs[3]}get target(){return ll.Fragment}set target(e){}autoConfigure(e,t=(()=>!0)){if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.isSystemValue&&e.systemValue===_l.World&&t(e)));i||(i=new Ol("world"),i.setAsSystemValue(_l.World)),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Ol("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&e.type===al.Vector4&&t(e)));i||(i=new Ol("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){const s=this.normal,r=this.tangent;let n=s.isConnected;s.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(s.connectInputBlock?.name)&&(n=!1);let o=r.isConnected;r.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(r.connectInputBlock?.name)&&(o=!1);const a=n&&o;i.setValue("TBNBLOCK",a,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,s=this.world,r=this.TBN,n=this.row0,o=this.row1,a=this.row2,l=e.shaderLanguage===di.WGSL,h=l?"mat3x3f":"mat3",c=l?"f":"";return e.target===ll.Fragment&&(e.compilationString+=`\n // ${this.name}\n ${e._declareLocalVar("tbnNormal",al.Vector3)} = normalize(${t.associatedVariableName}).xyz;\n ${e._declareLocalVar("tbnTangent",al.Vector3)} = normalize(${i.associatedVariableName}.xyz);\n ${e._declareLocalVar("tbnBitangent",al.Vector3)} = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w;\n ${l?"var":"mat3"} ${r.associatedVariableName} = ${h}(${s.associatedVariableName}[0].xyz, ${s.associatedVariableName}[1].xyz, ${s.associatedVariableName}[2].xyz) * ${h}(tbnTangent, tbnBitangent, tbnNormal);\n `,n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = vec3${c}(${r.associatedVariableName}[0][0], ${r.associatedVariableName}[0][1], ${r.associatedVariableName}[0][2]);\n`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = vec3${c}(${r.associatedVariableName}[1[0], ${r.associatedVariableName}[1][1], ${r.associatedVariableName}[1][2]);\n`),a.hasEndpoints&&(e.compilationString+=e._declareOutput(a)+` = vec3${c}(${r.associatedVariableName}[2][0], ${r.associatedVariableName}[2][1], ${r.associatedVariableName}[2][2]);\n`),e.sharedData.blocksWithDefines.push(this)),this}}z("BABYLON.TBNBlock",Nb);class Fb extends Tl{constructor(e){super(e,ll.Fragment),this._tangentSpaceParameterName="",this._tangentCorrectionFactorName="",this._worldMatrixName="",this.invertX=!1,this.invertY=!1,this.useParallaxOcclusion=!1,this.useObjectSpaceNormalMap=!1,this._isUnique=!0,this.registerInput("worldPosition",al.Vector4,!1),this.registerInput("worldNormal",al.Vector4,!1),this.registerInput("worldTangent",al.Vector4,!0),this.registerInput("uv",al.Vector2,!1),this.registerInput("normalMapColor",al.Color3,!1),this.registerInput("strength",al.Float,!1),this.registerInput("viewDirection",al.Vector3,!0),this.registerInput("parallaxScale",al.Float,!0),this.registerInput("parallaxHeight",al.Float,!0),this.registerInput("TBN",al.Object,!0,ll.VertexAndFragment,new Ib("TBN",this,cl.Input,Nb,"TBNBlock")),this.registerInput("world",al.Matrix,!0),this.registerOutput("output",al.Vector4),this.registerOutput("uvOffset",al.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}prepareDefines(e,t,i){const s=this.normalMapColor.connectedPoint._ownerBlock.samplerName,r=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&s||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",r,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Ol("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const e=new Ol("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,s=this.worldPosition,r=this.worldNormal,n=this.worldTangent,o=e.shaderLanguage===di.WGSL,a=o?"mat3x3f":"mat3",l=o?"f":"",h=o?"uniforms.":"";e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,al.Vector2),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,al.Float),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,al.Matrix);let c=null;this.normalMapColor.connectedPoint&&(c=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const u=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&c||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),d=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",_=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${e._emitFloat(this.strength.connectInputBlock.value)}`:`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${this.strength.associatedVariableName}`;o||e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const p={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},f=this.TBN;f.isConnected?e.compilationString+=`\n #ifdef TBNBLOCK\n ${o?"var":"mat3"} vTBN = ${f.associatedVariableName};\n #endif\n `:n.isConnected&&(e.compilationString+=`${e._declareLocalVar("tbnNormal",al.Vector3)} = normalize(${r.associatedVariableName}.xyz);\n`,e.compilationString+=`${e._declareLocalVar("tbnTangent",al.Vector3)} = normalize(${n.associatedVariableName}.xyz);\n`,e.compilationString+=`${e._declareLocalVar("tbnBitangent",al.Vector3)} = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\n`,e.compilationString+=`${o?"var":"mat3"} vTBN = ${a}(tbnTangent, tbnBitangent, tbnNormal);\n`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[p,{search:/varying mat3 vTBN;/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]});const m=o?"fn parallaxOcclusion(vViewDirCoT: vec3f, vNormalCoT: vec3f, texCoord: vec2f, parallaxScale:f32, bump: texture_2d, bumpSampler: sampler)":"#define inline\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)",g=o?/fn parallaxOcclusion\(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32\)/g:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,v=o?"fn parallaxOffset(viewDir: vec3f, heightScale: f32, height_: f32)":"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)",x=o?/fn parallaxOffset\(viewDir: vec3f,heightScale: f32\)/g:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g;e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:g,replace:m},{search:x,replace:v},{search:/texture.+?bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const b=u&&c?`${o?`textureSample(${c}, ${c+"Sampler"}`:`texture2D(${c}`}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName,T=e._getFreeVariableName("tempOutput");return e.compilationString+=e._declareLocalVar(T,al.Vector3)+` = vec3${l}(0.);\n`,e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture.+?bumpSampler,vBumpUV\)/g,replace:`${b}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`${e._declareLocalVar("normalMatrix",al.Matrix)} = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture.+?bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${b}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${o?u&&this.useParallaxOcclusion?`${c}, ${c+"Sampler"}`:"bump, bumpSampler":u&&this.useParallaxOcclusion?c:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${u?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:h+this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:_},{search:/vBumpInfos.z/g,replace:d},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:s.associatedVariableName+".xyz"},{search:/normalW=/g,replace:T+" = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:`${a}(normalMatrix) * `+T},{search:/normalW/g,replace:r.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:u?this.viewDirection.associatedVariableName:`vec3${l}(0.)`},p]}),e.compilationString+=e._declareOutput(this.output)+` = vec4${l}(${T}, 0.);\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX};\n`;return e+=`${this._codeVariableName}.invertY = ${this.invertY};\n`,e+=`${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};\n`,e+=`${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};\n`,e}serialize(){const e=super.serialize();return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!e.useObjectSpaceNormalMap}}Ze([Cl("Invert X axis",ul.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Fb.prototype,"invertX",void 0),Ze([Cl("Invert Y axis",ul.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Fb.prototype,"invertY",void 0),Ze([Cl("Use parallax occlusion",ul.Boolean)],Fb.prototype,"useParallaxOcclusion",void 0),Ze([Cl("Object Space Mode",ul.Boolean,"PROPERTIES",{notifiers:{update:!1}})],Fb.prototype,"useObjectSpaceNormalMap",void 0),z("BABYLON.PerturbNormalBlock",Fb);class Lb extends Tl{constructor(e){super(e,ll.Fragment,!0),this.registerInput("value",al.Float,!0),this.registerInput("cutoff",al.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) { discard; }\n`,this}}z("BABYLON.DiscardBlock",Lb);class Bb extends Tl{constructor(e){super(e,ll.Fragment),this.registerOutput("output",al.Float,ll.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===ll.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary("1.0","0.0",e.shaderLanguage===di.GLSL?"gl_FrontFacing":"fragmentInputs.frontFacing")};\n`,this}}z("BABYLON.FrontFacingBlock",Bb);class kb extends Tl{constructor(e){super(e,ll.Fragment),this.registerInput("input",al.AutoDetect,!1),this.registerOutput("dx",al.BasedOnInput),this.registerOutput("dy",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._outputs[1];e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let s="dFdx",r="dFdy";return e.shaderLanguage===di.WGSL&&(s="dpdx",r="dpdy"),t.hasEndpoints&&(e.compilationString+=e._declareOutput(t)+` = ${s}(${this.input.associatedVariableName});\n`),i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${r}(${this.input.associatedVariableName});\n`),this}}z("BABYLON.DerivativeBlock",kb);class Vb extends Tl{constructor(e){super(e,ll.Fragment),this.registerOutput("xy",al.Vector2,ll.Fragment),this.registerOutput("xyz",al.Vector3,ll.Fragment),this.registerOutput("xyzw",al.Vector4,ll.Fragment),this.registerOutput("x",al.Float,ll.Fragment),this.registerOutput("y",al.Float,ll.Fragment),this.registerOutput("z",al.Float,ll.Fragment),this.registerOutput("w",al.Float,ll.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";const i=e.shaderLanguage===di.WGSL?"fragmentInputs.position":"gl_FragCoord";for(const s of this._outputs)s.hasEndpoints&&(t+=`${e._declareOutput(s)} = ${i}.${s.name};\n`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===ll.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}z("BABYLON.FragCoordBlock",Vb);class Ub extends Tl{constructor(e){super(e,ll.Fragment),this.registerOutput("xy",al.Vector2,ll.Fragment),this.registerOutput("x",al.Float,ll.Fragment),this.registerOutput("y",al.Float,ll.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){const t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(const s of this._outputs)s.hasEndpoints&&(i+=`${e._declareOutput(s)} = ${t}.${s.name};\n`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===ll.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,al.Vector2);const t=e.shaderLanguage===di.WGSL?"uniforms.":"";return e.compilationString+=this.writeOutputs(e,t+this._varName),this}}z("BABYLON.ScreenSizeBlock",Ub);class Gb extends Tl{constructor(e){super(e,ll.Fragment),this.registerInput("vector",al.AutoDetect),this.registerInput("worldViewProjection",al.Matrix),this.registerOutput("output",al.Vector2),this.registerOutput("x",al.Float),this.registerOutput("y",al.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e,t=(()=>!0)){if(!this.worldViewProjection.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.WorldViewProjection&&t(e)));i||(i=new Ol("worldViewProjection"),i.setAsSystemValue(_l.WorldViewProjection)),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const s=i.associatedVariableName,r=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case al.Vector3:e.compilationString+=`${e._declareLocalVar(r,al.Vector4)} = ${s} * vec4${e.fSuffix}(${t.associatedVariableName}, 1.0);\n`;break;case al.Vector4:e.compilationString+=`${e._declareLocalVar(r,al.Vector4)} = ${s} * ${t.associatedVariableName};\n`}return e.compilationString+=`${r} = vec4${e.fSuffix}(${r}.xy / ${r}.w, ${r}.zw);`,e.compilationString+=`${r} = vec4${e.fSuffix}(${r}.xy * 0.5 + vec2${e.fSuffix}(0.5, 0.5), ${r}.zw);`,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${r}.xy;\n`),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${r}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${r}.y;\n`),this}}z("BABYLON.ScreenSpaceBlock",Gb);class zb extends Tl{constructor(e){super(e,ll.Fragment),this.registerInput("input",al.Vector2),this.registerInput("strength",al.Float),this.registerInput("center",al.Vector2),this.registerInput("offset",al.Vector2),this.registerOutput("output",al.Vector2),this.registerOutput("x",al.Float),this.registerOutput("y",al.Float)}getClassName(){return"TwirlBlock"}get input(){return this._inputs[0]}get strength(){return this._inputs[1]}get center(){return this._inputs[2]}get offset(){return this._inputs[3]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(){if(!this.center.isConnected){const e=new Ol("center");e.value=new de(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new Ol("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new Ol("offset");e.value=new de(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),s=e._getFreeVariableName("x"),r=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=` \n ${e._declareLocalVar(t,al.Vector2)} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName};\n ${e._declareLocalVar(i,al.Float)} = ${this.strength.associatedVariableName} * length(${t});\n ${e._declareLocalVar(s,al.Float)} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y;\n ${e._declareLocalVar(r,al.Float)} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y;\n ${e._declareLocalVar(n,al.Vector2)} = vec2(${s} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${r} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y);\n `,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${n};\n`),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${n}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${n}.y;\n`),this}}z("BABYLON.TwirlBlock",zb);class Wb extends Tl{constructor(e){super(e,ll.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",al.Float),this.registerInput("worldPosition",al.Vector3),this.registerInput("worldNormal",al.Vector3),this.registerInput("worldTangent",al.AutoDetect,!0),this.registerOutput("output",al.Vector4),this.registerOutput("xyz",al.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e.shaderLanguage===di.WGSL,s=e.fSuffix;this.generateInWorldSpace||this.worldTangent.isConnected||Ne.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const r=this.generateInWorldSpace?"":"\n vec3 biTangent = cross(norm, tgt);\n mat3 TBN = mat3(tgt, biTangent, norm);\n ",n=this.generateInWorldSpace?"":"\n result = TBN * result;\n result = result * vec3(0.5) + vec3(0.5);\n ";let o=`\n vec4 heightToNormal(float height, vec3 position, vec3 tangent, vec3 normal) {\n vec3 tgt = ${this.automaticNormalizationTangent?"normalize(tangent);":"tangent;"}\n vec3 norm = ${this.automaticNormalizationNormal?"normalize(normal);":"normal;"}\n ${r}\n vec3 worlddX = dFdx(position);\n vec3 worlddY = dFdy(position);\n vec3 crossX = cross(norm, worlddX);\n vec3 crossY = cross(norm, worlddY);\n float d = abs(dot(crossY, worlddX));\n vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));\n inToNormal.y *= -1.0;\n vec3 result = normalize((d * norm) - inToNormal);\n ${n}\n return vec4(result, 0.);\n }`;return i?o=e._babylonSLtoWGSL(o):e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",o,"// heightToNormal"),e.compilationString+=e._declareOutput(t)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:`vec3${s}(0.)`}.xyz, ${this.worldNormal.associatedVariableName});\n`,this.xyz.hasEndpoints&&(e.compilationString+=e._declareOutput(this.xyz)+` = ${this.output.associatedVariableName}.xyz;\n`),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};\n`,e+=`${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};\n`,e+=`${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};\n`,e}serialize(){const e=super.serialize();return e.generateInWorldSpace=this.generateInWorldSpace,e.automaticNormalizationNormal=this.automaticNormalizationNormal,e.automaticNormalizationTangent=this.automaticNormalizationTangent,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.generateInWorldSpace=e.generateInWorldSpace,this.automaticNormalizationNormal=e.automaticNormalizationNormal,this.automaticNormalizationTangent=e.automaticNormalizationTangent}}Ze([Cl("Generate in world space instead of tangent space",ul.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Wb.prototype,"generateInWorldSpace",void 0),Ze([Cl("Force normalization for the worldNormal input",ul.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Wb.prototype,"automaticNormalizationNormal",void 0),Ze([Cl("Force normalization for the worldTangent input",ul.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Wb.prototype,"automaticNormalizationTangent",void 0),z("BABYLON.HeightToNormalBlock",Wb);class Hb extends Tl{constructor(e){super(e,ll.Fragment,!0),this.registerInput("depth",al.Float,!0),this.registerInput("worldPos",al.Vector4,!0),this.registerInput("viewProjection",al.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){super._buildBlock(e);const t=e.shaderLanguage===di.GLSL?"gl_FragDepth":"fragmentOutputs.fragDepth";return this.depth.isConnected?e.compilationString+=`${t} = ${this.depth.associatedVariableName};\n`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=`\n ${e._declareLocalVar("p",al.Vector4)} = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName};\n ${e._declareLocalVar("v",al.Vector4)} = p.z / p.w;\n #ifndef IS_NDC_HALF_ZRANGE\n v = v * 0.5 + 0.5;\n #endif\n ${t} = v;\n \n `:Ne.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}z("BABYLON.FragDepthBlock",Hb);class Xb extends Tl{constructor(e){super(e,ll.Fragment),this.registerInput("worldPosition",al.Vector4,!1),this.registerInput("viewProjection",al.Matrix,!1),this.registerInput("worldNormal",al.AutoDetect,!0),this.registerOutput("depth",al.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM")}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitUniformFromString("biasAndScaleSM",al.Vector3),e._emitUniformFromString("lightDataSM",al.Vector3),e._emitUniformFromString("depthValuesSM",al.Vector3),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`vec4 worldPos = ${this.worldPosition.associatedVariableName};\n`,e.compilationString+="vec3 vPositionWSM;\n",e.compilationString+="float vDepthMetricSM = 0.0;\n",e.compilationString+="float zSM;\n",this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+="\n #if SM_DEPTHTEXTURE == 1\n #ifdef IS_NDC_HALF_ZRANGE\n gl_FragDepth = (clipPos.z / clipPos.w);\n #else\n gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5;\n #endif\n #endif\n ",e.compilationString+=`${e._declareOutput(this.depth)} = vec3(depthSM, 1., 1.);\n`,this}}z("BABYLON.ShadowMapBlock",Xb);class Yb extends Tl{constructor(e){super(e,ll.Fragment,!0),this.registerInput("viewDepth",al.Float,!0),this.registerInput("worldPosition",al.AutoDetect,!0),this.registerInput("viewNormal",al.AutoDetect,!0),this.registerInput("reflectivity",al.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(al.Vector3|al.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(al.Vector3|al.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(al.Vector3|al.Vector4|al.Color3|al.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}get reflectivity(){return this._inputs[3]}_buildBlock(e){super._buildBlock(e);const t=this.worldPosition,i=this.viewNormal,s=this.viewDepth,r=this.reflectivity;e.sharedData.blocksWithDefines.push(this);const n=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",n),e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+="#ifdef PREPASS_DEPTH\r\n",s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${s.associatedVariableName}, 0.0, 0.0, 1.0);\r\n`:e.compilationString+=" gl_FragData[PREPASS_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_POSITION\r\n",t.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===al.Vector4?t.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_NORMAL\r\n",i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===al.Vector4?i.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_REFLECTIVITY\r\n",r.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(${r.associatedVariableName}.rgb, ${r.connectedPoint.type===al.Vector4?r.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#endif\r\n",this}}z("BABYLON.PrePassOutputBlock",Yb);class Qb extends Tl{constructor(e){super(e,ll.VertexAndFragment,!1),this.registerInput("worldPosition",al.Vector4,!1,ll.Vertex),this.registerInput("view",al.Matrix,!1,ll.Vertex),this.registerInput("input",al.AutoDetect,!1,ll.Fragment),this.registerInput("fogColor",al.AutoDetect,!1,ll.Fragment),this.registerOutput("output",al.Color3,ll.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e,t=(()=>!0)){if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.View&&t(e)));i||(i=new Ol("view"),i.setAsSystemValue(_l.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.FogColor&&t(e)));i||(i=new Ol("fogColor",void 0,al.Color3),i.setAsSystemValue(_l.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const s=e.getScene();i.setValue("FOG",t.fogEnabled&&Uo(e,s))}bind(e,t,i){if(!i)return;const s=i.getScene();e.setFloat4(this._fogParameters,s.fogMode,s.fogStart,s.fogEnd,s.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===ll.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=[],i="",s="";e.shaderLanguage===di.WGSL?(t=[{search:/fn CalcFogFactor\(\)/,replace:"fn CalcFogFactor(vFogDistance: vec3f, vFogInfos: vec4f)"},{search:/uniforms.vFogInfos/g,replace:"vFogInfos"},{search:/fragmentInputs.vFogDistance/g,replace:"vFogDistance"}],i="fragmentInputs.",s="uniforms."):t=[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}],e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:t});const r=e._getFreeVariableName("fog"),n=this.input,o=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const a=this._outputs[0];e._emitUniformFromString(this._fogParameters,al.Vector4),e.compilationString+="#ifdef FOG\n",e.compilationString+=`${e._declareLocalVar(r,al.Float)} = CalcFogFactor(${i}${this._fogDistanceName}, ${s}${this._fogParameters});\n`,e.compilationString+=e._declareOutput(a)+` = ${r} * ${n.associatedVariableName}.rgb + (1.0 - ${r}) * ${o.associatedVariableName}.rgb;\n`,e.compilationString+=`#else\n${e._declareOutput(a)} = ${n.associatedVariableName}.rgb;\n`,e.compilationString+="#endif\n"}else{const t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,al.Vector3);const s=e.shaderLanguage===di.WGSL?"vertexOutputs.":"";e.compilationString+=`${s}${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz;\n`}return this}}z("BABYLON.FogBlock",Qb);class jb extends Tl{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,Ne.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?ll.Fragment:ll.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?ll.Fragment:ll.Vertex}constructor(e){super(e,ll.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",al.Vector4,!1,ll.Vertex),this.registerInput("worldNormal",al.Vector4,!1,ll.Fragment),this.registerInput("cameraPosition",al.Vector3,!1,ll.Fragment),this.registerInput("glossiness",al.Float,!0,ll.Fragment),this.registerInput("glossPower",al.Float,!0,ll.Fragment),this.registerInput("diffuseColor",al.Color3,!0,ll.Fragment),this.registerInput("specularColor",al.Color3,!0,ll.Fragment),this.registerInput("view",al.Matrix,!0),this.registerOutput("diffuseOutput",al.Color3,ll.Fragment),this.registerOutput("specularOutput",al.Color3,ll.Fragment),this.registerOutput("shadow",al.Float,ll.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.CameraPosition&&t(e)));i||(i=new Ol("cameraPosition"),i.setAsSystemValue(_l.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const s=e.getScene();if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};Wo(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else zo(s,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;Jo(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,t)}}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?Fo(this.light,this._lightId,s,e,!0):Lo(s,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,al.Vector4)&&(e.compilationString+=(e.shaderLanguage===di.WGSL?"vertexOutputs.":"")+`${s} = ${t.associatedVariableName};\n`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`${e._declareLocalVar("worldPos",al.Vector4)} = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`${e._declareLocalVar("view",al.Matrix)} = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_injectUBODeclaration(e){const t=`//${this.name}`;this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0})}_buildBlock(e){super._buildBlock(e);const t=e.shaderLanguage===di.WGSL,i=t?"f":"",s=`//${this.name}`;if(e.target!==ll.Fragment)return void this._injectVertexCode(e);this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const r=e.shaderLanguage===di.WGSL?"fragmentInputs.":"";e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const n=this.worldPosition;let o=n.associatedVariableName;this.generateOnlyFragmentCode?(o=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`${e._declareLocalVar(o,al.Vector3)};\n`,s),e.compilationString+=`${o} = ${n.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${n.associatedVariableName}`:void 0})):o=r+"v_"+o+".xyz",e._emitFunctionFromInclude("helperFunctions",s),e._emitFunctionFromInclude("lightsFragmentFunctions",s,{replaceStrings:[{search:/vPositionW/g,replace:o}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",s,{replaceStrings:[{search:/vPositionW/g,replace:o}]}),this._injectUBODeclaration(e),0===this._lightId&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`${e._declareLocalVar("viewDirectionW",al.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${o});\n`),e.compilationString+=t?"var info: lightingInfo;\n":"lightingInfo info;\n",e.compilationString+=`${e._declareLocalVar("shadow",al.Float)} = 1.;\n`,e.compilationString+=`${e._declareLocalVar("aggShadow",al.Float)} = 0.;\n`,e.compilationString+=`${e._declareLocalVar("numLights",al.Float)} = 0.;\n`,e.compilationString+=`${e._declareLocalVar("glossiness",al.Float)} = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"};\n`,e.compilationString+=`${e._declareLocalVar("diffuseBase",al.Vector3)} = vec3${i}(0., 0., 0.);\n`,e.compilationString+=`${e._declareLocalVar("specularBase",al.Vector3)} = vec3${i}(0., 0., 0.);\n`,e.compilationString+=`${e._declareLocalVar("normalW",al.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz;\n`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:o+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",s,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${o}.xyz`}),0===this._lightId&&(e.compilationString+="aggShadow = aggShadow / numLights;\n");const a=this.diffuseOutput,l=this.specularOutput;return e.compilationString+=e._declareOutput(a)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""};\n`,l.hasEndpoints&&(e.compilationString+=e._declareOutput(l)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""};\n`),this.shadow.hasEndpoints&&(e.compilationString+=e._declareOutput(this.shadow)+" = aggShadow;\n"),this}serialize(){const e=super.serialize();return e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}Ze([Cl("Generate only fragment code",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:jb._OnGenerateOnlyFragmentCodeChanged}})],jb.prototype,"generateOnlyFragmentCode",void 0),z("BABYLON.LightBlock",jb);class Kb extends Tl{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??re.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get samplerName(){return this._samplerName}constructor(e){super(e,ll.VertexAndFragment),this.registerOutput("source",al.Object,ll.VertexAndFragment,new Ib("source",this,cl.Output,Kb,"ImageSourceBlock"))}bind(e){this.texture&&e.setTexture(this._samplerName,this.texture)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}getClassName(){return"ImageSourceBlock"}get source(){return this._outputs[0]}_buildBlock(e){return super._buildBlock(e),e.target===ll.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Texture"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i,s){super._deserialize(e,t,i,s),e.texture&&!hh.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(0===e.texture.url.indexOf("data:")?i="":s&&(e.texture.url=s(e.texture.url),e.texture.name=e.texture.url),this.texture=Pa.Parse(e.texture,t,i))}}z("BABYLON.ImageSourceBlock",Kb);class $b extends Tl{get texture(){return this.source.isConnected?(this.source.connectedPoint?.ownerBlock).texture:this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??re.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _IsPrePassTextureBlock(e){return"PrePassTextureBlock"===e?.getClassName()}get _isSourcePrePass(){return $b._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!$b._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=this.texture.getScene()??re.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??re.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?ll.Fragment:ll.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",al.AutoDetect,!1,ll.VertexAndFragment),this.registerInput("source",al.Object,!0,ll.VertexAndFragment,new Ib("source",this,cl.Input,Kb,"ImageSourceBlock")),this.registerInput("layer",al.Float,!0),this.registerInput("lod",al.Float,!0),this.registerOutput("rgba",al.Color4,ll.Neutral),this.registerOutput("rgb",al.Color3,ll.Neutral),this.registerOutput("r",al.Float,ll.Neutral),this.registerOutput("g",al.Float,ll.Neutral),this.registerOutput("b",al.Float,ll.Neutral),this.registerOutput("a",al.Float,ll.Neutral),this.registerOutput("level",al.Float,ll.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Vector2|al.Vector3|al.Vector4),this._inputs[0]._prioritizeVertex=!t}getClassName(){return"TextureBlock"}get uv(){return this._inputs[0]}get source(){return this._inputs[1]}get layer(){return this._inputs[2]}get lod(){return this._inputs[3]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}get target(){if(this._fragmentOnly)return ll.Fragment;if(!this.uv.isConnected)return ll.VertexAndFragment;if(this.uv.sourceBlock.isInput)return ll.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===ll.Fragment)return ll.Fragment;if(e.target===ll.Vertex)return ll.VertexAndFragment;if(e.target===ll.Neutral||e.target===ll.VertexAndFragment){const t=e.ownerBlock;if(t.target===ll.Fragment)return ll.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return ll.VertexAndFragment}set target(e){}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected)if(e.mode===Hl.PostProcess){const i=e.getBlockByPredicate((e=>"uv"===e.name&&t(e)));i&&i.connectTo(this)}else{const i=e.mode===Hl.Particle?"particle_uv":"uv";let s=e.getInputBlockByPredicate((e=>e.isAttribute&&e.name===i&&t(e)));s||(s=new Ol("uv"),s.setAsAttribute(i)),s.output.connectTo(this.uv)}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix)return void(this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)));const s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),null==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!!this._isSourcePrePass||!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==ll.Fragment}_injectVertexCode(e){const t=this.uv;this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.declarationVariableName.toUpperCase(),this._mainUVName="vMain"+t.declarationVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,al.Vector2,this._defineName),e._emitVaryingFromString(this._mainUVName,al.Vector2,this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,al.Matrix,this._defineName);const i=e._getShaderType(al.Vector4),s=e._getShaderType(al.Vector2);if(e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`${e._getVaryingName(this._transformedUVName)} = ${s}(${this._textureTransformName} * ${i}(${t.associatedVariableName}.xy, 1.0, 0.0));\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`,e.compilationString+=`${e._getVaryingName(this._mainUVName)} = ${t.associatedVariableName}.xy;\n`,e.compilationString+="#endif\n",this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}}_getUVW(e){let t=e;const i=this._texture?._texture?.is2DArray??!1,s=this._texture?._texture?.is3D??!1;return(i||s)&&(t=`vec3(${e}, ${this.layer.isConnected?this.layer.associatedVariableName:"0"})`),t}_samplerFunc(e){return e.shaderLanguage===di.WGSL?e.target===ll.Vertex?"textureSampleLevel":"textureSample":this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureSample(e,t){if(t.shaderLanguage===di.WGSL){const i=t.target===ll.Vertex;return`${this._samplerFunc(t)}(${this.samplerName},${this.samplerName+"Sampler"}, ${this._getUVW(e)}${this._samplerLodSuffix}${i?", 0":""})`}return`${this._samplerFunc(t)}(${this.samplerName}, ${this._getUVW(e)}${this._samplerLodSuffix})`}_generateTextureLookup(e){e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,al.Vector4)} = ${this._generateTextureSample(e._getVaryingName(this._transformedUVName),e)};\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,al.Vector4)} = ${this._generateTextureSample(this._mainUVName?e._getVaryingName(this._mainUVName):this.uv.associatedVariableName,e)}${this._samplerLodSuffix};\n`,e.compilationString+="#endif\n"}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===ll.Fragment)return;this._generateTextureLookup(e)}else this.uv.ownerBlock.target!==ll.Fragment?this._generateTextureLookup(e):e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,al.Vector4)} = ${this._generateTextureSample(i.associatedVariableName,e)}${this._samplerLodSuffix};\n`}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i,s=!1){if(s){if(e.target===ll.Fragment)return;return e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i)}if(this.uv.ownerBlock.target===ll.Fragment)return e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i);let r="";this.disableLevelMultiplication||(r=" * "+(e.shaderLanguage===di.WGSL?"uniforms.":"")+this._textureInfoName),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${r};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===ll.Vertex||this._fragmentOnly||e.target===ll.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),!this._isMixed&&e.target===ll.Fragment||this._isMixed&&e.target===ll.Vertex){if(!this._imageSource){const t=e._getFreeVariableName(this.name);this._samplerName=t+"Texture",this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)}e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)}if(e.target!==ll.Fragment)return void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;this._isMixed&&!this._imageSource&&(this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._isMixed&&e._emitUniformFromString(this._textureInfoName,al.Float),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i,s){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!hh.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(0===e.texture.url.indexOf("data:")?i="":s&&(e.texture.url=s(e.texture.url),e.texture.name=e.texture.url),this.texture=Pa.Parse(e.texture,t,i))}}z("BABYLON.TextureBlock",$b);class qb extends Tl{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??re.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?ll.Fragment:ll.VertexAndFragment)}constructor(e){super(e,ll.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Ol("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.World&&t(e)));i||(i=new Ol("world"),i.setAsSystemValue(_l.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.View&&t(e)));i||(i=new Ol("view"),i.setAsSystemValue(_l.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this._getTexture();s&&s.getTextureMatrix&&(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLocalCubicName,!!s.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===s.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===s.coordinatesMode,!0),i.setValue(this._defineCubicName,3===s.coordinatesMode||6===s.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===s.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===s.coordinatesMode,!0),i.setValue(this._definePlanarName,2===s.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===s.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===s.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===s.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===s.coordinatesMode,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i,s){const r=this._getTexture();if(i&&r&&(e.setMatrix(this._reflectionMatrixName,r.getReflectionTextureMatrix()),r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),r.boundingBoxSize)){const t=r;e.setVector3(this._reflectionPositionName,t.boundingBoxPosition),e.setVector3(this._reflectionSizeName,t.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===ll.Vertex)return"";this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,al.Matrix);let t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");const i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,al.Vector4))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName};\n`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,al.Vector3,this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName}\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\n`,t+="#endif\n"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,al.Vector3,`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0)));\n`,t+="#endif\n"),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\n`,e._samplerDeclaration+="#else\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\n`,e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,al.Vector3),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,al.Vector3)}handleFragmentSideCodeReflectionCoords(e,t,i=!1,s=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const r=this._reflectionMatrixName,n=`normalize(${this._directionWName})`,o=`${this._positionUVWName}`,a=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=`\n #ifdef ${this._defineMirroredEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${n});\n #endif\n\n #ifdef ${this._defineEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${n});\n #endif\n\n #ifdef ${this._defineEquirectangularName}\n vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n\n #ifdef ${this._defineSphericalName}\n vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${r});\n #endif\n\n #ifdef ${this._definePlanarName}\n vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n\n #ifdef ${this._defineCubicName}\n #ifdef ${this._defineLocalCubicName}\n vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${a}.xyz, ${r}, ${this._reflectionSizeName}, ${this._reflectionPositionName});\n #else\n vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n #endif\n\n #ifdef ${this._defineProjectionName}\n vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${r});\n #endif\n\n #ifdef ${this._defineSkyboxName}\n vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${o}, ${r});\n #endif\n\n #ifdef ${this._defineExplicitName}\n vec3 ${this._reflectionVectorName} = vec3(0, 0, 0);\n #endif\n`;return s||(h+=`#ifdef ${this._defineOppositeZ}\n ${this._reflectionVectorName}.z *= -1.0;\n #endif\n`),i||(h+=`\n #ifdef ${this._define3DName}\n vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName};\n #else\n vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy;\n #ifdef ${this._defineProjectionName}\n ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;\n #endif\n ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;\n #endif\n`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i=`${"vec"+(0===t.length?"4":t.length-1)} ${this._reflectionColorName};\n #ifdef ${this._define3DName}\n`;return i+=e?`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t};\n`:`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t};\n`,i+="\n #else\n",i+=e?`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t};\n`:`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t};\n`,i+="#endif\n",i}writeOutputs(e,t){let i="";if(e.target===ll.Fragment)for(const s of this._outputs)s.hasEndpoints&&(i+=`${e._declareOutput(s)} = ${t}.${s.name};\n`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){const t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"});\n`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);\n`;return e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!hh.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=vg.Parse(e.texture,t,i):this.texture=Pa.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}Ze([Cl("Generate only fragment code",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:qb._OnGenerateOnlyFragmentCodeChanged}})],qb.prototype,"generateOnlyFragmentCode",void 0),z("BABYLON.ReflectionTextureBaseBlock",qb);class Zb extends qb{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,Ne.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,Ne.Error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?ll.Fragment:ll.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?ll.Fragment:ll.Vertex}constructor(e){super(e),this.registerInput("position",al.AutoDetect,!1,ll.Vertex),this.registerInput("worldPosition",al.Vector4,!1,ll.Vertex),this.registerInput("worldNormal",al.Vector4,!1,ll.Fragment),this.registerInput("world",al.Matrix,!1,ll.Vertex),this.registerInput("cameraPosition",al.Vector3,!1,ll.Fragment),this.registerInput("view",al.Matrix,!1,ll.Fragment),this.registerOutput("rgb",al.Color3,ll.Fragment),this.registerOutput("rgba",al.Color4,ll.Fragment),this.registerOutput("r",al.Float,ll.Fragment),this.registerOutput("g",al.Float,ll.Fragment),this.registerOutput("b",al.Float,ll.Fragment),this.registerOutput("a",al.Float,ll.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e,t=(()=>!0)){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.CameraPosition&&t(e)));i||(i=new Ol("cameraPosition"),i.setAsSystemValue(_l.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==ll.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);const t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName});\n`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}}z("BABYLON.ReflectionTextureBlock",Zb);class Jb extends Tl{constructor(e){super(e,ll.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",al.AutoDetect,!1,ll.VertexAndFragment),this.registerOutput("depth",al.Float,ll.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Vector2|al.Vector3|al.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"SceneDepthBlock"}get uv(){return this._inputs[0]}get depth(){return this._outputs[0]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?ll.VertexAndFragment:ll.Fragment:ll.VertexAndFragment}_getTexture(e){return e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ).getDepthMap()}bind(e,t){const i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,t.type===al.Vector3?al.Vector3:t.type===al.Vector4?al.Vector4:al.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,al.Vector2),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===ll.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\n`}else this.uv.ownerBlock.target!==ll.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\n`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===ll.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target,ll.Fragment,e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.bindableBlocks.indexOf(this)<0&&e.sharedData.bindableBlocks.push(this),e.target!==ll.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(this._outputs.some((e=>e.isConnectedInFragmentShader))){e._emit2DSampler(this._samplerName),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){const e=super.serialize();return e.useNonLinearDepth=this.useNonLinearDepth,e.storeCameraSpaceZ=this.storeCameraSpaceZ,e.force32itsFloat=this.force32itsFloat,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useNonLinearDepth=e.useNonLinearDepth,this.storeCameraSpaceZ=!!e.storeCameraSpaceZ,this.force32itsFloat=e.force32itsFloat}}Ze([Cl("Use non linear depth",ul.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let s=!1;return i.useNonLinearDepth&&(i.storeCameraSpaceZ=!1,s=!0),e&&e.disableDepthRenderer(),s}}})],Jb.prototype,"useNonLinearDepth",void 0),Ze([Cl("Store Camera space Z",ul.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let s=!1;return i.storeCameraSpaceZ&&(i.useNonLinearDepth=!1,s=!0),e&&e.disableDepthRenderer(),s}}})],Jb.prototype,"storeCameraSpaceZ",void 0),Ze([Cl("Force 32 bits float",ul.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>e?.disableDepthRenderer()}})],Jb.prototype,"force32itsFloat",void 0),z("BABYLON.SceneDepthBlock",Jb);class eT extends Tl{constructor(e){super(e,ll.VertexAndFragment,!0),this.registerInput("worldPosition",al.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6")}get worldPosition(){return this._inputs[0]}get target(){return ll.VertexAndFragment}set target(e){}prepareDefines(e,t,i){const s=e.getScene(),r=!!(t.clipPlane??s.clipPlane),n=!!(t.clipPlane2??s.clipPlane2),o=!!(t.clipPlane3??s.clipPlane3),a=!!(t.clipPlane4??s.clipPlane4),l=!!(t.clipPlane5??s.clipPlane5),h=!!(t.clipPlane6??s.clipPlane6);i.setValue("CLIPPLANE",r,!0),i.setValue("CLIPPLANE2",n,!0),i.setValue("CLIPPLANE3",o,!0),i.setValue("CLIPPLANE4",a,!0),i.setValue("CLIPPLANE5",l,!0),i.setValue("CLIPPLANE6",h,!0)}bind(e,t,i){i&&xo(e,t,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==ll.Fragment){const i=this.worldPosition;return e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane",al.Vector4),e._emitUniformFromString("vClipPlane2",al.Vector4),e._emitUniformFromString("vClipPlane3",al.Vector4),e._emitUniformFromString("vClipPlane4",al.Vector4),e._emitUniformFromString("vClipPlane5",al.Vector4),void e._emitUniformFromString("vClipPlane6",al.Vector4)}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}z("BABYLON.ClipPlanesBlock",eT);class tT extends Tl{get texture(){return null}set texture(e){}constructor(e,t=ll.VertexAndFragment){super(e,t,!1),this.registerOutput("position",al.Object,ll.VertexAndFragment,new Ib("position",this,cl.Output,Kb,"ImageSourceBlock")),this.registerOutput("depth",al.Object,ll.VertexAndFragment,new Ib("depth",this,cl.Output,Kb,"ImageSourceBlock")),this.registerOutput("normal",al.Object,ll.VertexAndFragment,new Ib("normal",this,cl.Output,Kb,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==ll.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){const i=t.getScene().enablePrePassRenderer();if(!i)return;const s=i.defaultRT;s.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,s.textures[i.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,s.textures[i.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,s.textures[i.getIndex(6)]))}}z("BABYLON.PrePassTextureBlock",tT);class iT extends Tl{get endpoints(){return this._endpoints}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==ll.VertexAndFragment)return t.target;if(e.connectedPoint.target!==ll.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}constructor(e){super(e,ll.Neutral),this._endpoints=[],this.registerInput("input",al.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some((e=>e.output.isConnectedInFragmentShader))}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)-1===t.indexOf(s)&&(i+=s._dumpCode(e,t));return i}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(t.isAnAncestorOf(e))return!0}return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){super.dispose();for(const e of this._endpoints)this.detachFromEndpoint(e);this._endpoints=[]}}z("BABYLON.NodeMaterialTeleportInBlock",iT);class sT extends Tl{constructor(e){super(e,ll.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",al.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){this._target&e||(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=e._declareOutput(this.output)+` = ${this.entryPoint.input.associatedVariableName};\n`)}clone(e,t=""){const i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}z("BABYLON.NodeMaterialTeleportOutBlock",sT);class rT extends zl{constructor(e){super(e)}getClassName(){return"AddBlock"}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName};\n`,this}}z("BABYLON.AddBlock",rT);class nT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("input",al.AutoDetect),this.registerInput("factor",al.Float),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ScaleBlock"}get input(){return this._inputs[0]}get factor(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName};\n`,this}}z("BABYLON.ScaleBlock",nT);class oT extends Tl{constructor(e){super(e,ll.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e.shaderLanguage===di.WGSL?e._getShaderType(this.value.type):"";return e.compilationString+=e._declareOutput(t)+` = clamp(${this.value.associatedVariableName}, ${i}(${this._writeFloat(this.minimum)}), ${i}(${this._writeFloat(this.maximum)}));\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.minimum=e.minimum,this.maximum=e.maximum}}Ze([Cl("Minimum",ul.Float)],oT.prototype,"minimum",void 0),Ze([Cl("Maximum",ul.Float)],oT.prototype,"maximum",void 0),z("BABYLON.ClampBlock",oT);class aT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("left",al.AutoDetect),this.registerInput("right",al.AutoDetect),this.registerOutput("output",al.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(al.Float),this._inputs[0].excludedConnectionPointTypes.push(al.Matrix),this._inputs[0].excludedConnectionPointTypes.push(al.Vector2),this._inputs[1].excludedConnectionPointTypes.push(al.Float),this._inputs[1].excludedConnectionPointTypes.push(al.Matrix),this._inputs[1].excludedConnectionPointTypes.push(al.Vector2)}getClassName(){return"CrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz);\n`,this}}z("BABYLON.CrossBlock",aT);class lT extends Tl{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach((s=>{const r=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),n=e._getGLType(s.type);t=t.replace(r,n),i=i.replace(r,n)})),this._outputs.forEach((s=>{const r=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),n=e._getGLType(s.type);t=t.replace(r,n),i=i.replace(r,n)})),e._emitFunction(i,t,""),this._outputs.forEach((t=>{e.compilationString+=e._declareOutput(t)+";\n"})),e.compilationString+=i+"(";let s=!1;return this._inputs.forEach(((t,i)=>{i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=t.connectedPoint?.ownerBlock?.samplerName??t.associatedVariableName:e.compilationString+=t.associatedVariableName,s=!0})),this._outputs.forEach(((t,i)=>{(i>0||s)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName})),e.compilationString+=");\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.options = ${JSON.stringify(this._options)};\n`,e}serialize(){const e=super.serialize();return e.options=this._options,e}_deserialize(e,t,i){this._deserializeOptions(e.options),super._deserialize(e,t,i)}_deserializeOptions(e){this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=ll[e.target],e.inParameters?.forEach(((e,t)=>{const i=al[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,al.Object,!0,ll.VertexAndFragment,new Ib(e.name,this,cl.Input,Kb,"ImageSourceBlock"))):this.registerInput(e.name,i),Object.defineProperty(this,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})})),e.outParameters?.forEach(((e,t)=>{this.registerOutput(e.name,al[e.type]),Object.defineProperty(this,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(this._outputs[t]._typeConnectionSource=this._findInputByName(e.typeFromInput)[0])})),e.inLinkedConnectionTypes?.forEach((e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])}))}_findInputByName(e){if(!e)return null;for(let t=0;t!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.CameraPosition&&t(e)));i||(i=new Ol("cameraPosition"),i.setAsSystemValue(_l.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz);\n`,this}}z("BABYLON.ViewDirectionBlock",vT);class xT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("worldNormal",al.Vector4),this.registerInput("viewDirection",al.Vector3),this.registerInput("bias",al.Float),this.registerInput("power",al.Float),this.registerOutput("fresnel",al.Float)}getClassName(){return"FresnelBlock"}get worldNormal(){return this._inputs[0]}get viewDirection(){return this._inputs[1]}get bias(){return this._inputs[2]}get power(){return this._inputs[3]}get fresnel(){return this._outputs[0]}autoConfigure(e){if(!this.viewDirection.isConnected){const t=new vT("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const e=new Ol("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){const e=new Ol("power");e.value=1,e.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitFunctionFromInclude("fresnelFunction",t,{removeIfDef:!0}),e.compilationString+=e._declareOutput(this.fresnel)+` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName});\n`,this}}z("BABYLON.FresnelBlock",xT);class bT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("left",al.AutoDetect),this.registerInput("right",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MaxBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`,this}}z("BABYLON.MaxBlock",bT);class TT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("left",al.AutoDetect),this.registerInput("right",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MinBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`,this}}z("BABYLON.MinBlock",TT);class yT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("left",al.AutoDetect),this.registerInput("right",al.AutoDetect),this.registerOutput("output",al.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(al.Float),this._inputs[0].excludedConnectionPointTypes.push(al.Matrix),this._inputs[1].excludedConnectionPointTypes.push(al.Float),this._inputs[1].excludedConnectionPointTypes.push(al.Matrix)}getClassName(){return"DistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName});\n`,this}}z("BABYLON.DistanceBlock",yT);class ST extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("value",al.AutoDetect),this.registerOutput("output",al.Float),this._inputs[0].excludedConnectionPointTypes.push(al.Float),this._inputs[0].excludedConnectionPointTypes.push(al.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = length(${this.value.associatedVariableName});\n`,this}}z("BABYLON.LengthBlock",ST);class CT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("value",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NegateBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = -1.0 * ${this.value.associatedVariableName};\n`,this}}z("BABYLON.NegateBlock",CT);class ET extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("value",al.AutoDetect),this.registerInput("power",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"PowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName});\n`,this}}z("BABYLON.PowBlock",ET);class AT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("seed",al.AutoDetect),this.registerOutput("output",al.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Vector2|al.Vector3|al.Vector4|al.Color3|al.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=e._declareOutput(t)+` = getRand(${this.seed.associatedVariableName}.xy);\n`,this}}z("BABYLON.RandomNumberBlock",AT);class PT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("x",al.Float),this.registerInput("y",al.Float),this.registerOutput("output",al.Float)}getClassName(){return"ArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e.shaderLanguage===di.WGSL?"atan2":"atan";return e.compilationString+=e._declareOutput(t)+` = ${i}(${this.x.associatedVariableName}, ${this.y.associatedVariableName});\n`,this}}z("BABYLON.ArcTan2Block",PT);class IT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("value",al.AutoDetect),this.registerInput("edge0",al.Float),this.registerInput("edge1",al.Float),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"SmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e._getShaderType(this.value.type);return e.compilationString+=e._declareOutput(t)+` = smoothstep(${i}(${this.edge0.associatedVariableName}), ${i}(${this.edge1.associatedVariableName}), ${this.value.associatedVariableName});\n`,this}}z("BABYLON.SmoothStepBlock",IT);class RT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("input",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ReciprocalBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return this.input.type===al.Matrix?e.compilationString+=e._declareOutput(t)+` = inverse(${this.input.associatedVariableName});\n`:e.compilationString+=e._declareOutput(t)+` = 1. / ${this.input.associatedVariableName};\n`,this}}z("BABYLON.ReciprocalBlock",RT);class MT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("value",al.AutoDetect),this.registerInput("reference",al.AutoDetect),this.registerInput("distance",al.Float),this.registerInput("replacement",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(al.Float),this._inputs[0].excludedConnectionPointTypes.push(al.Matrix),this._inputs[1].excludedConnectionPointTypes.push(al.Float),this._inputs[1].excludedConnectionPointTypes.push(al.Matrix),this._inputs[3].excludedConnectionPointTypes.push(al.Float),this._inputs[3].excludedConnectionPointTypes.push(al.Matrix)}getClassName(){return"ReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+";\n",e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {\n`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName};\n`,e.compilationString+="} else {\n",e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName};\n`,e.compilationString+="}\n",this}}z("BABYLON.ReplaceColorBlock",MT);class OT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("value",al.AutoDetect),this.registerInput("steps",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(al.Matrix),this._inputs[1].excludedConnectionPointTypes.push(al.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(al.Float)}getClassName(){return"PosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName});\n`,this}}var DT;z("BABYLON.PosterizeBlock",OT),function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(DT||(DT={}));class wT extends Tl{constructor(e){super(e,ll.Neutral),this.kind=DT.SawTooth,this.registerInput("input",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(al.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];switch(this.kind){case DT.SawTooth:e.compilationString+=e._declareOutput(t)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\n`;break;case DT.Square:e.compilationString+=e._declareOutput(t)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\n`;break;case DT.Triangle:e.compilationString+=e._declareOutput(t)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\n`}return this}serialize(){const e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}}z("BABYLON.WaveBlock",wT);class NT{get step(){return this._step}set step(e){this._step=e}get color(){return this._color}set color(e){this._color=e}constructor(e,t){this.step=e,this.color=t}}class FT extends Tl{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,ll.Neutral),this.colorSteps=[new NT(0,Ee.Black()),new NT(1,Ee.White())],this.onValueChangedObservable=new K,this.registerInput("gradient",al.AutoDetect),this.registerOutput("output",al.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Float|al.Vector2|al.Vector3|al.Vector4|al.Color3|al.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e,t){const i=this.colorSteps[e];return`${t}(${i.color.r}, ${i.color.g}, ${i.color.b})`}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e._getShaderType(al.Vector3);if(!this.colorSteps.length||!this.gradient.connectedPoint)return void(e.compilationString+=e._declareOutput(t)+` = ${i}(0., 0., 0.);\n`);const s=e._getFreeVariableName("gradientTempColor"),r=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`${e._declareLocalVar(s,al.Vector3)} = ${this._writeColorConstant(0,i)};\n`,e.compilationString+=`${e._declareLocalVar(r,al.Float)};\n`;let n=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==al.Float&&(n+=".x");for(let t=1;t!0)){if(!this.intensity.isConnected){const e=new Ol("Refraction intensity",ll.Fragment,al.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.View&&t(e)));i||(i=new Ol("view"),i.setAsSystemValue(_l.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this._getTexture(),r=s&&s.getTextureMatrix;i.setValue("SS_REFRACTION",r,!0),r&&(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLODRefractionAlpha,s.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,s.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&s.isCube?!s.invertZ:s.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",s.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",s.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!s.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){super.bind(e,t,i);const s=this._getTexture();if(!s)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s),e.setMatrix(this._refractionMatrixName,s.getRefractionTextureMatrix());let r=1;s.isCube||s.depth&&(r=s.depth);const n=this.volumeIndexOfRefraction.connectInputBlock?.value??this.indexOfRefractionConnectionPoint.connectInputBlock?.value??1.5;e.setFloat4(this._vRefractionInfosName,s.level,1/n,r,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,s.getSize().width,s.lodGenerationScale,s.lodGenerationOffset,1/n);const o=s.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,o,be.Log2(o)),s.boundingBoxSize){const t=s;e.setVector3("vRefractionPosition",t.boundingBoxPosition),e.setVector3("vRefractionSize",t.boundingBoxSize)}}getCode(e){return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\n`,e._samplerDeclaration+="#else\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\n`,e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,al.Matrix),e._emitFunction("sampleRefraction",`\n #ifdef ${this._define3DName}\n #define sampleRefraction(s, c) textureCube(s, c)\n #else\n #define sampleRefraction(s, c) texture2D(s, c)\n #endif\n`,`//${this.name}`),e._emitFunction("sampleRefractionLod",`\n #ifdef ${this._define3DName}\n #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\n`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,al.Vector4),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,al.Vector4),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,al.Vector2),e._emitUniformFromString("vRefractionPosition",al.Vector3),e._emitUniformFromString("vRefractionSize",al.Vector3),""}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e=this.texture.isCube?`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\n`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\n`,e+=`${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\n`,e+=`${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=vg.Parse(e.texture,t,i):this.texture=Pa.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}Ze([Cl("Link refraction to transparency",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],KT.prototype,"linkRefractionWithTransparency",void 0),Ze([Cl("Invert refraction Y",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],KT.prototype,"invertRefractionY",void 0),Ze([Cl("Use thickness as depth",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],KT.prototype,"useThicknessAsDepth",void 0),z("BABYLON.RefractionBlock",KT);class $T extends Tl{constructor(e){super(e,ll.Fragment),this._isUnique=!0,this.registerInput("thickness",al.Float,!1,ll.Fragment),this.registerInput("tintColor",al.Color3,!0,ll.Fragment),this.registerInput("translucencyIntensity",al.Float,!0,ll.Fragment),this.registerInput("translucencyDiffusionDist",al.Color3,!0,ll.Fragment),this.registerInput("refraction",al.Object,!0,ll.Fragment,new Ib("refraction",this,cl.Input,KT,"RefractionBlock")),this.registerInput("dispersion",al.Float,!0,ll.Fragment),this.registerOutput("subsurface",al.Object,ll.Fragment,new Ib("subsurface",this,cl.Output,$T,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vTranslucencyColor"),e._excludeVariableName("vSubSurfaceIntensity"),e._excludeVariableName("dispersion")}getClassName(){return"SubSurfaceBlock"}get thickness(){return this._inputs[0]}get tintColor(){return this._inputs[1]}get translucencyIntensity(){return this._inputs[2]}get translucencyDiffusionDist(){return this._inputs[3]}get refraction(){return this._inputs[4]}get dispersion(){return this._inputs[5]}get subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){const e=new Ol("SubSurface thickness",ll.Fragment,al.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",s||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",s,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0),i.setValue("SS_DISPERSION",this.dispersion.isConnected,!0)}static GetCode(e,t,i,s){let r="";const n=t?.thickness.isConnected?t.thickness.associatedVariableName:"0.",o=t?.tintColor.isConnected?t.tintColor.associatedVariableName:"vec3(1.)",a=t?.translucencyIntensity.isConnected?t?.translucencyIntensity.associatedVariableName:"1.",l=t?.translucencyDiffusionDist.isConnected?t?.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",h=t?.refraction.isConnected?t?.refraction.connectedPoint?.ownerBlock:null,c=h?.tintAtDistance.isConnected?h.tintAtDistance.associatedVariableName:"1.",u=h?.intensity.isConnected?h.intensity.associatedVariableName:"1.",d=h?.view.isConnected?h.view.associatedVariableName:"",_=t?.dispersion.isConnected?t?.dispersion.associatedVariableName:"0.0";return r+=h?.getCode(e)??"",r+=`subSurfaceOutParams subSurfaceOut;\n\n #ifdef SUBSURFACE\n vec2 vThicknessParam = vec2(0., ${n});\n vec4 vTintColor = vec4(${o}, ${c});\n vec3 vSubSurfaceIntensity = vec3(${u}, ${a}, 0.);\n float dispersion = ${_};\n subSurfaceBlock(\n vSubSurfaceIntensity,\n vThicknessParam,\n vTintColor,\n normalW,\n specularEnvironmentReflectance,\n #ifdef SS_THICKNESSANDMASK_TEXTURE\n vec4(0.),\n #endif\n #ifdef REFLECTION\n #ifdef SS_TRANSLUCENCY\n ${i?._reflectionMatrixName},\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n reflectionOut.irradianceVector,\n #endif\n #if defined(REALTIME_FILTERING)\n ${i?._cubeSamplerName},\n ${i?._vReflectionFilteringInfoName},\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n irradianceSampler,\n #endif\n #endif\n #endif\n #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n surfaceAlbedo,\n #endif\n #ifdef SS_REFRACTION\n ${s}.xyz,\n viewDirectionW,\n ${d},\n ${h?._vRefractionInfosName??""},\n ${h?._refractionMatrixName??""},\n ${h?._vRefractionMicrosurfaceInfosName??""},\n vLightingIntensity,\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha,\n #endif\n #ifdef ${h?._defineLODRefractionAlpha??"IGNORE"}\n NdotVUnclamped,\n #endif\n #ifdef ${h?._defineLinearSpecularRefraction??"IGNORE"}\n roughness,\n #endif\n alphaG,\n #ifdef ${h?._define3DName??"IGNORE"}\n ${h?._cubeSamplerName??""},\n #else\n ${h?._2DSamplerName??""},\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${h?._define3DName??"IGNORE"}\n ${h?._cubeSamplerName??""},\n ${h?._cubeSamplerName??""},\n #else\n ${h?._2DSamplerName??""},\n ${h?._2DSamplerName??""},\n #endif\n #endif\n #ifdef ANISOTROPIC\n anisotropicOut,\n #endif\n #ifdef REALTIME_FILTERING\n ${h?._vRefractionFilteringInfoName??""},\n #endif\n #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n vRefractionPosition,\n vRefractionSize,\n #endif\n #ifdef SS_DISPERSION\n dispersion,\n #endif\n #endif\n #ifdef SS_TRANSLUCENCY\n ${l},\n vTintColor,\n #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\n vec4(0.),\n #endif\n #endif\n subSurfaceOut\n );\n\n #ifdef SS_REFRACTION\n surfaceAlbedo = subSurfaceOut.surfaceAlbedo;\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha = subSurfaceOut.alpha;\n #endif\n #endif\n #else\n subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;\n #endif\n`,r}_buildBlock(e){return e.target===ll.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}z("BABYLON.SubSurfaceBlock",$T);const qT={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]};class ZT extends Tl{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,Ne.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?ll.Fragment:ll.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?ll.Fragment:ll.Vertex}constructor(e){super(e,ll.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=Ee.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",al.Vector4,!1,ll.Vertex),this.registerInput("worldNormal",al.Vector4,!1,ll.Fragment),this.registerInput("view",al.Matrix,!1),this.registerInput("cameraPosition",al.Vector3,!1,ll.Fragment),this.registerInput("perturbedNormal",al.Vector4,!0,ll.Fragment),this.registerInput("baseColor",al.Color3,!0,ll.Fragment),this.registerInput("metallic",al.Float,!1,ll.Fragment),this.registerInput("roughness",al.Float,!1,ll.Fragment),this.registerInput("ambientOcc",al.Float,!0,ll.Fragment),this.registerInput("opacity",al.Float,!0,ll.Fragment),this.registerInput("indexOfRefraction",al.Float,!0,ll.Fragment),this.registerInput("ambientColor",al.Color3,!0,ll.Fragment),this.registerInput("reflection",al.Object,!0,ll.Fragment,new Ib("reflection",this,cl.Input,YT,"ReflectionBlock")),this.registerInput("clearcoat",al.Object,!0,ll.Fragment,new Ib("clearcoat",this,cl.Input,QT,"ClearCoatBlock")),this.registerInput("sheen",al.Object,!0,ll.Fragment,new Ib("sheen",this,cl.Input,HT,"SheenBlock")),this.registerInput("subsurface",al.Object,!0,ll.Fragment,new Ib("subsurface",this,cl.Input,$T,"SubSurfaceBlock")),this.registerInput("anisotropy",al.Object,!0,ll.Fragment,new Ib("anisotropy",this,cl.Input,XT,"AnisotropyBlock")),this.registerInput("iridescence",al.Object,!0,ll.Fragment,new Ib("iridescence",this,cl.Input,jT,"IridescenceBlock")),this.registerOutput("ambientClr",al.Color3,ll.Fragment),this.registerOutput("diffuseDir",al.Color3,ll.Fragment),this.registerOutput("specularDir",al.Color3,ll.Fragment),this.registerOutput("clearcoatDir",al.Color3,ll.Fragment),this.registerOutput("sheenDir",al.Color3,ll.Fragment),this.registerOutput("diffuseInd",al.Color3,ll.Fragment),this.registerOutput("specularInd",al.Color3,ll.Fragment),this.registerOutput("clearcoatInd",al.Color3,ll.Fragment),this.registerOutput("sheenInd",al.Color3,ll.Fragment),this.registerOutput("refraction",al.Color3,ll.Fragment),this.registerOutput("lighting",al.Color3,ll.Fragment),this.registerOutput("shadow",al.Float,ll.Fragment),this.registerOutput("alpha",al.Float,ll.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.CameraPosition&&t(e)));i||(i=new Ol("cameraPosition"),i.setAsSystemValue(_l.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===_l.View&&t(e)));i||(i=new Ol("view"),i.setAsSystemValue(_l.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===Gg.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===Gg.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const s=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",s.indexOf(".")<0?s+".":s,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);const r=e.getScene();if(r.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&$c.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),i._areLightsDirty)if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};Wo(r,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else zo(r,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,Ko(r,i)}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;Jo(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,t)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?Fo(this.light,this._lightId,s,e,!0):Lo(s,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const r=this._scene.ambientColor;r&&e.setColor3("ambientFromScene",r);const n=s.useRightHandedSystem===(null!=s._mirroredCameraPosition);e.setFloat(this._invertNormalName,n?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const o=this.indexOfRefraction.connectInputBlock?.value??1.5,a=Math.pow((o-1)/(o+1),2);this._metallicReflectanceColor.scaleToRef(a*this._metallicF0Factor,Pe.Color3[0]);const l=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,Pe.Color3[0],l),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,al.Vector4)&&(e.compilationString+=`${s} = ${t.associatedVariableName};\n`);const r=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;r&&(r.viewConnectionPoint=this.view),e.compilationString+=r?.handleVertexSide(e)??"",e._emitVaryingFromString("vClipSpacePosition",al.Vector4,"defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+="#if DEBUGMODE > 0\n",e._injectAtEnd+="vClipSpacePosition = gl_Position;\n",e._injectAtEnd+="#endif\n"),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e="albedoOpacityOutParams albedoOpacityOut;\n";return e+=`albedoOpacityBlock(\n vec4(${this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)"}, 1.),\n #ifdef ALBEDO\n vec4(1.),\n vec2(1., 1.),\n #endif\n #ifdef OPACITY\n vec4(${this.opacity.isConnected?this.opacity.associatedVariableName:"1."}),\n vec2(1., 1.),\n #endif\n albedoOpacityOut\n );\n\n vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;\n float alpha = albedoOpacityOut.alpha;\n`,e}_getAmbientOcclusionCode(){let e="ambientOcclusionOutParams aoOut;\n";return e+=`ambientOcclusionBlock(\n #ifdef AMBIENT\n vec3(${this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1."}),\n vec4(0., 1.0, 1.0, 0.),\n #endif\n aoOut\n );\n`,e}_getReflectivityCode(e){let t="reflectivityOutParams reflectivityOut;\n";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,al.Vector4),t+=`vec3 baseColor = surfaceAlbedo;\n\n reflectivityBlock(\n vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.),\n #ifdef METALLICWORKFLOW\n surfaceAlbedo,\n ${this._vMetallicReflectanceFactorsName},\n #endif\n #ifdef REFLECTIVITY\n vec3(0., 0., 1.),\n vec4(1.),\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor,\n #endif\n #ifdef MICROSURFACEMAP\n microSurfaceTexel, <== not handled!\n #endif\n reflectivityOut\n );\n\n float microSurface = reflectivityOut.microSurface;\n float roughness = reflectivityOut.roughness;\n\n #ifdef METALLICWORKFLOW\n surfaceAlbedo = reflectivityOut.surfaceAlbedo;\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;\n #endif\n`,t}_buildBlock(e){super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=Eg(this._scene));const t=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;if(t&&(t.worldPositionConnectionPoint=this.worldPosition,t.cameraPositionConnectionPoint=this.cameraPosition,t.worldNormalConnectionPoint=this.worldNormal,t.viewConnectionPoint=this.view),e.target!==ll.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const i=`//${this.name}`,s=this.perturbedNormal;let r=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${r};\n`,i),e.compilationString+=`${r} = ${this.worldPosition.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+="#if DEBUGMODE > 0\n",e.compilationString+="vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0);\n",e.compilationString+="#endif\n"):r="v_"+r,this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode",al.Vector2,"defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene",al.Vector3),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",i),e._emitFunctionFromInclude("importanceSampling",i),e._emitFunctionFromInclude("pbrHelperFunctions",i),e._emitFunctionFromInclude("imageProcessingDeclaration",i),e._emitFunctionFromInclude("imageProcessingFunctions",i),e._emitFunctionFromInclude("shadowsFragmentFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",i),e._emitFunctionFromInclude("pbrBRDFFunctions",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",i),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",i),e._emitFunctionFromInclude("pbrBlockReflectivity",i),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",i),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",i),e._emitFunctionFromInclude("pbrBlockAnisotropic",i),e._emitUniformFromString("vLightingIntensity",al.Vector4),t?.generateOnlyFragmentCode&&(e.compilationString+=t.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName});\n`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${r}.xyz);\n`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz;\n`,e.compilationString+=`vec3 normalW = ${s.isConnected?"normalize("+s.associatedVariableName+".xyz)":"geometricNormalW"};\n`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,al.Float),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",i),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",i),e.compilationString+="#ifdef UNLIT\n vec3 diffuseBase = vec3(1., 1., 1.);\n #else\n",e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"}]});const n=this.anisotropy.isConnected?this.anisotropy.connectedPoint?.ownerBlock:null;n&&(n.worldPositionConnectionPoint=this.worldPosition,n.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=n.getCode(e,!this.perturbedNormal.isConnected)),t&&t.hasTexture&&(e.compilationString+=t.getCode(e,n?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:t?._vReflectionFilteringInfoName??"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",i,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});const o=this.sheen.isConnected?this.sheen.connectedPoint?.ownerBlock:null;o&&(e.compilationString+=o.getCode(t)),e._emitFunctionFromInclude("pbrBlockSheen",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"}]});const a=this.iridescence.isConnected?this.iridescence.connectedPoint?.ownerBlock:null;e.compilationString+=jT.GetCode(a),e._emitFunctionFromInclude("pbrBlockIridescence",i,{replaceStrings:[]});const l=this.clearcoat.isConnected?this.clearcoat.connectedPoint?.ownerBlock:null,h=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,c=this.perturbedNormal.isConnected&&(this.perturbedNormal.connectedPoint?.ownerBlock).worldTangent?.isConnected,u=this.anisotropy.isConnected&&(this.anisotropy.connectedPoint?.ownerBlock).worldTangent.isConnected;let d=c||!this.perturbedNormal.isConnected&&u;e.compilationString+=QT.GetCode(e,l,t,r,h,d,this.worldNormal.associatedVariableName),h&&(d=l?.worldTangent.isConnected??!1),e._emitFunctionFromInclude("pbrBlockClearcoat",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:d?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"}]});const _=this.subsurface.isConnected?this.subsurface.connectedPoint?.ownerBlock:null,p=this.subsurface.isConnected?(this.subsurface.connectedPoint?.ownerBlock).refraction.connectedPoint?.ownerBlock:null;p&&(p.viewConnectionPoint=this.view,p.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=$T.GetCode(e,_,t,r),e._emitFunctionFromInclude("pbrBlockSubSurface",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:p?._define3DName??"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:p?._defineLODRefractionAlpha??"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:p?._defineLinearSpecularRefraction??"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:p?._defineOppositeZ??"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",i),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:r+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${r}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",i),e.compilationString+="#endif\n";const f=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)";let m=Gg.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();-1===m.indexOf(".")&&(m+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",i,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:f+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:m}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",i,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",i,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",i,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:r},{search:/albedoTexture\.rgb;/g,replace:"vec3(1.);\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\n"}]});for(const t of this._outputs)if(t.hasEndpoints){const i=qT[t.name];if(i){const[s,r]=i;r&&(e.compilationString+=`#if ${r}\n`),e.compilationString+=`${e._declareOutput(t)} = ${s};\n`,r&&(e.compilationString+="#else\n",e.compilationString+=`${e._declareOutput(t)} = vec3(0.);\n`,e.compilationString+="#endif\n")}else Ne.Error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.lightFalloff = ${this.lightFalloff};\n`,e+=`${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};\n`,e+=`${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};\n`,e+=`${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};\n`,e+=`${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};\n`,e+=`${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};\n`,e+=`${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};\n`,e+=`${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};\n`,e+=`${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};\n`,e+=`${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};\n`,e+=`${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};\n`,e+=`${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};\n`,e+=`${this._codeVariableName}.unlit = ${this.unlit};\n`,e+=`${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};\n`,e+=`${this._codeVariableName}.debugMode = ${this.debugMode};\n`,e+=`${this._codeVariableName}.debugLimit = ${this.debugLimit};\n`,e+=`${this._codeVariableName}.debugFactor = ${this.debugFactor};\n`,e}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=e.lightFalloff??0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=e.realTimeFilteringQuality??8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor,this.generateOnlyFragmentCode=!!e.generateOnlyFragmentCode,this._setTarget()}}Ze([Cl("Direct lights",ul.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],ZT.prototype,"directIntensity",void 0),Ze([Cl("Environment lights",ul.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],ZT.prototype,"environmentIntensity",void 0),Ze([Cl("Specular highlights",ul.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],ZT.prototype,"specularIntensity",void 0),Ze([Cl("Light falloff",ul.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:Gg.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:Gg.LIGHTFALLOFF_GLTF},{label:"Standard",value:Gg.LIGHTFALLOFF_STANDARD}]})],ZT.prototype,"lightFalloff",void 0),Ze([Cl("Alpha Testing",ul.Boolean,"OPACITY")],ZT.prototype,"useAlphaTest",void 0),Ze([Cl("Alpha CutOff",ul.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],ZT.prototype,"alphaTestCutoff",void 0),Ze([Cl("Alpha blending",ul.Boolean,"OPACITY")],ZT.prototype,"useAlphaBlending",void 0),Ze([Cl("Radiance over alpha",ul.Boolean,"RENDERING",{notifiers:{update:!0}})],ZT.prototype,"useRadianceOverAlpha",void 0),Ze([Cl("Specular over alpha",ul.Boolean,"RENDERING",{notifiers:{update:!0}})],ZT.prototype,"useSpecularOverAlpha",void 0),Ze([Cl("Specular anti-aliasing",ul.Boolean,"RENDERING",{notifiers:{update:!0}})],ZT.prototype,"enableSpecularAntiAliasing",void 0),Ze([Cl("Realtime filtering",ul.Boolean,"RENDERING",{notifiers:{update:!0}})],ZT.prototype,"realTimeFiltering",void 0),Ze([Cl("Realtime filtering quality",ul.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],ZT.prototype,"realTimeFilteringQuality",void 0),Ze([Cl("Energy Conservation",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],ZT.prototype,"useEnergyConservation",void 0),Ze([Cl("Radiance occlusion",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],ZT.prototype,"useRadianceOcclusion",void 0),Ze([Cl("Horizon occlusion",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],ZT.prototype,"useHorizonOcclusion",void 0),Ze([Cl("Unlit",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],ZT.prototype,"unlit",void 0),Ze([Cl("Force normal forward",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],ZT.prototype,"forceNormalForward",void 0),Ze([Cl("Generate only fragment code",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:ZT._OnGenerateOnlyFragmentCodeChanged}})],ZT.prototype,"generateOnlyFragmentCode",void 0),Ze([Cl("Debug mode",ul.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87},{label:"Albedo color",value:88},{label:"Ambient occlusion color",value:89}]})],ZT.prototype,"debugMode",void 0),Ze([Cl("Split position",ul.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],ZT.prototype,"debugLimit",void 0),Ze([Cl("Output factor",ul.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],ZT.prototype,"debugFactor",void 0),z("BABYLON.PBRMetallicRoughnessBlock",ZT);class JT extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("left",al.AutoDetect),this.registerInput("right",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[1].acceptedConnectionPointTypes.push(al.Float)}getClassName(){return"ModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.shaderLanguage===di.GLSL?e.compilationString+=e._declareOutput(t)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`:e.compilationString+=e._declareOutput(t)+` = (${this.left.associatedVariableName} % ${this.right.associatedVariableName});\n`,this}}z("BABYLON.ModBlock",JT);class ey extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("row0",al.Vector4),this.registerInput("row1",al.Vector4),this.registerInput("row2",al.Vector4),this.registerInput("row3",al.Vector4),this.registerOutput("output",al.Matrix)}getClassName(){return"MatrixBuilder"}get row0(){return this._inputs[0]}get row1(){return this._inputs[1]}get row2(){return this._inputs[2]}get row3(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(){if(!this.row0.isConnected){const e=new Ol("row0");e.value=new pe(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new Ol("row1");e.value=new pe(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new Ol("row2");e.value=new pe(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new Ol("row3");e.value=new pe(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,s=this.row1,r=this.row2,n=this.row3,o=e.shaderLanguage===di.WGSL?"mat4x4f":"mat4";return e.compilationString+=e._declareOutput(t)+` = ${o}(${i.associatedVariableName}, ${s.associatedVariableName}, ${r.associatedVariableName}, ${n.associatedVariableName});\n`,this}}var ty,iy,sy,ry,ny,oy;z("BABYLON.MatrixBuilder",ey),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(ty||(ty={}));class ay extends Tl{constructor(e){super(e,ll.Neutral),this.condition=ty.LessThan,this.registerInput("a",al.Float),this.registerInput("b",al.Float),this.registerInput("true",al.AutoDetect,!0),this.registerInput("false",al.AutoDetect,!0),this.registerOutput("output",al.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=al.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",s=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case ty.Equal:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} == ${this.b.associatedVariableName}`)};\n`;break;case ty.NotEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} != ${this.b.associatedVariableName}`)};\n`;break;case ty.LessThan:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} < ${this.b.associatedVariableName}`)};\n`;break;case ty.LessOrEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} <= ${this.b.associatedVariableName}`)};\n`;break;case ty.GreaterThan:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} > ${this.b.associatedVariableName}`)};\n`;break;case ty.GreaterOrEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} >= ${this.b.associatedVariableName}`)};\n`;break;case ty.Xor:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`(((${this.a.associatedVariableName} + ${this.b.associatedVariableName}) % 2.0) > 0.0)`)};\n`;break;case ty.Or:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`(min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0)`)};\n`;break;case ty.And:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`(${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0)`)};\n`}return this}serialize(){const e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${ty[this.condition]};\n`}}z("BABYLON.ConditionalBlock",ay);class ly extends Tl{constructor(e){super(e,ll.Neutral),this.octaves=6,this.registerInput("seed",al.AutoDetect),this.registerInput("chaos",al.AutoDetect,!0),this.registerInput("offsetX",al.Float,!0),this.registerInput("offsetY",al.Float,!0),this.registerInput("offsetZ",al.Float,!0),this.registerOutput("output",al.Float),this._inputs[0].acceptedConnectionPointTypes.push(al.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(al.Vector3),this._linkConnectionTypes(0,1)}getClassName(){return"CloudBlock"}get seed(){return this._inputs[0]}get chaos(){return this._inputs[1]}get offsetX(){return this._inputs[2]}get offsetY(){return this._inputs[3]}get offsetZ(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;if(!this._outputs[0].hasEndpoints)return;let t="\n\n float cloudRandom(float p) { \n float temp = fract(p * 0.011); \n temp *= temp + 7.5; \n temp *= temp + temp; \n return fract(temp); \n }\n\n // Based on Morgan McGuire @morgan3d\n // https://www.shadertoy.com/view/4dS3Wd\n float cloudNoise2(vec2 x, vec2 chaos) {\n vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);\n\n vec2 i = floor(x);\n vec2 f = fract(x);\n\n float n = dot(i, step);\n\n vec2 u = f * f * (3.0 - 2.0 * f);\n return mix(\n mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),\n mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),\n u.y\n );\n }\n\n float cloudNoise3(vec3 x, vec3 chaos) {\n vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);\n\n vec3 i = floor(x);\n vec3 f = fract(x);\n\n float n = dot(i, step);\n\n vec3 u = f * f * (3.0 - 2.0 * f);\n return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),\n mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);\n }",i="\n float fbm2(vec2 st, vec2 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = .5;\n float frequency = 0.;\n\n // Loop of octaves\n vec2 tempST = st;\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise2(tempST, chaos);\n tempST *= 2.0;\n amplitude *= 0.5;\n }\n return value;\n }\n\n float fbm3(vec3 x, vec3 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = 0.5;\n vec3 tempX = x;\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise3(tempX, chaos);\n tempX = tempX * 2.0;\n amplitude *= 0.5;\n }\n return value;\n }";e.shaderLanguage===di.WGSL&&(t=e._babylonSLtoWGSL(t),i=e._babylonSLtoWGSL(i));const s=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",t,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,i.replace(/fbm/gi,s).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");const r=e._getFreeVariableName("st"),n=this.seed.connectedPoint?.type||al.Vector3;e.compilationString+=`${e._declareLocalVar(r,n)} = ${this.seed.associatedVariableName};\n`,this.offsetX.isConnected&&(e.compilationString+=`${r}.x += 0.1 * ${this.offsetX.associatedVariableName};\n`),this.offsetY.isConnected&&(e.compilationString+=`${r}.y += 0.1 * ${this.offsetY.associatedVariableName};\n`),this.offsetZ.isConnected&&n===al.Vector3&&(e.compilationString+=`${r}.z += 0.1 * ${this.offsetZ.associatedVariableName};\n`);let o="";if(this.chaos.isConnected)o=this.chaos.associatedVariableName;else{const t=e.fSuffix;o=this.seed.connectedPoint?.type===al.Vector2?`vec2${t}(0., 0.)`:`vec3${t}(0., 0., 0.)`}return e.compilationString+=e._declareOutput(this._outputs[0])+` = ${s}${this.seed.connectedPoint?.type===al.Vector2?"2":"3"}(${r}, ${o});\n`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves};\n`}serialize(){const e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}Ze([Cl("Octaves",ul.Int)],ly.prototype,"octaves",void 0),z("BABYLON.CloudBlock",ly);class hy extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("seed",al.Vector2),this.registerInput("offset",al.Float),this.registerInput("density",al.Float),this.registerOutput("output",al.Float),this.registerOutput("cells",al.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t="vec2 voronoiRandom(vec2 p){\n p = vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3)));\n return fract(sin(p)*18.5453);\n }\n ";e.shaderLanguage===di.WGSL&&(t=e._babylonSLtoWGSL(t)),e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t="void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){\n vec2 n = floor(seed * density);\n vec2 f = fract(seed * density);\n vec3 m = vec3( 8.0 );\n for( int j=-1; j<=1; j++ ){\n for( int i=-1; i<=1; i++ ){\n vec2 g = vec2( float(i), float(j) );\n vec2 o = voronoiRandom( n + g);\n vec2 r = g - f + (0.5+0.5*sin(offset+6.2831*o));\n float d = dot( r, r );\n if( de.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get textureY(){return this.sourceY.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}get textureZ(){return this.sourceZ?.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}_getImageSourceBlock(e){return e?.isConnected?e.connectedPoint.ownerBlock:null}get samplerName(){const e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){return this._getImageSourceBlock(this.sourceY)?.samplerName??null}get samplerZName(){return this._getImageSourceBlock(this.sourceZ)?.samplerName??null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=this.texture.getScene()??re.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??re.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,ll.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",al.AutoDetect,!1),this.registerInput("normal",al.AutoDetect,!1),this.registerInput("sharpness",al.Float,!0),this.registerInput("source",al.Object,!0,ll.VertexAndFragment,new Ib("source",this,cl.Input,Kb,"ImageSourceBlock")),this.registerInput("sourceY",al.Object,!0,ll.VertexAndFragment,new Ib("sourceY",this,cl.Input,Kb,"ImageSourceBlock")),t||this.registerInput("sourceZ",al.Object,!0,ll.VertexAndFragment,new Ib("sourceZ",this,cl.Input,Kb,"ImageSourceBlock")),this.registerOutput("rgba",al.Color4,ll.Neutral),this.registerOutput("rgb",al.Color3,ll.Neutral),this.registerOutput("r",al.Float,ll.Neutral),this.registerOutput("g",al.Float,ll.Neutral),this.registerOutput("b",al.Float,ll.Neutral),this.registerOutput("a",al.Float,ll.Neutral),this.registerOutput("level",al.Float,ll.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(al.Color3|al.Vector3|al.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_samplerFunc(e){return e.shaderLanguage===di.WGSL?"textureSample":"texture2D"}_generateTextureSample(e,t,i){return i.shaderLanguage===di.WGSL?`${this._samplerFunc(i)}(${e},${e+"Sampler"}, ${t})`:`${this._samplerFunc(i)}(${e}, ${t})`}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??t,s=this.samplerZName??t,r=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("x"),o=e._getFreeVariableName("y"),a=e._getFreeVariableName("z"),l=e._getFreeVariableName("w"),h=e._getFreeVariableName("n"),c=e._getFreeVariableName("uvx"),u=e._getFreeVariableName("uvy"),d=e._getFreeVariableName("uvz");e.compilationString+=`\n ${e._declareLocalVar(h,al.Vector3)} = ${this.normal.associatedVariableName}.xyz;\n\n ${e._declareLocalVar(c,al.Vector2)} = ${this.position.associatedVariableName}.yz;\n ${e._declareLocalVar(u,al.Vector2)} = ${this.position.associatedVariableName}.zx;\n ${e._declareLocalVar(d,al.Vector2)} = ${this.position.associatedVariableName}.xy;\n `,this.projectAsCube&&(e.compilationString+=`\n ${c}.xy = ${c}.yx;\n\n if (${h}.x >= 0.0) {\n ${c}.x = -${c}.x;\n }\n if (${h}.y < 0.0) {\n ${u}.y = -${u}.y;\n }\n if (${h}.z < 0.0) {\n ${d}.x = -${d}.x;\n }\n `);const _=e.fSuffix;e.compilationString+=`\n ${e._declareLocalVar(n,al.Vector4)} = ${this._generateTextureSample(t,c,e)};\n ${e._declareLocalVar(o,al.Vector4)} = ${this._generateTextureSample(i,u,e)};\n ${e._declareLocalVar(a,al.Vector4)} = ${this._generateTextureSample(s,d,e)};\n \n // blend weights\n ${e._declareLocalVar(l,al.Vector3)} = pow(abs(${h}), vec3${_}(${r}));\n\n // blend and return\n ${e._declareLocalVar(this._tempTextureRead,al.Vector4)} = (${n}*${l}.x + ${o}*${l}.y + ${a}*${l}.z) / (${l}.x + ${l}.y + ${l}.z); \n `}_generateConversionCode(e,t,i){let s="";e.shaderLanguage!==di.WGSL||t.type!==al.Vector3&&t.type!==al.Color3||(s="Vec3"),"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace${s}(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace${s}(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i){let s="";this.disableLevelMultiplication||(s=` * ${e.shaderLanguage===di.WGSL?"uniforms.":""}${this._textureInfoName}`),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${s};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=(e.shaderLanguage===di.WGSL?"uniforms.":"")+this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Texture"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,al.Float),this._generateTextureLookup(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,e+=`${this._codeVariableName}.projectAsCube = ${this.projectAsCube};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!hh.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Pa.Parse(e.texture,t,i))}}Ze([Cl("Project as cube",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],uy.prototype,"projectAsCube",void 0),z("BABYLON.TriPlanarBlock",uy);class dy extends uy{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_declareLocalVarAsVec3I(e,t){return t.shaderLanguage===di.WGSL?`var ${e}: vec3`:`ivec3 ${e}`}_getTextureGrad(e,t){return e.shaderLanguage===di.WGSL?`textureSampleGrad(${t},${t+"Sampler"}`:`textureGrad(${t}`}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",r=e._getFreeVariableName("dxValue"),n=e._getFreeVariableName("dyValue"),o=e._getFreeVariableName("n"),a=e._getFreeVariableName("ma"),l=e._getFreeVariableName("mi"),h=e._getFreeVariableName("me"),c=e._getFreeVariableName("x"),u=e._getFreeVariableName("y"),d=e._getFreeVariableName("w");let _="ivec3",p="dFdx",f="dFdy";const m=e.fSuffix;e.shaderLanguage===di.WGSL&&(_="vec3",p="dpdx",f="dpdy"),e.compilationString+=`\n // grab coord derivatives for texturing\n ${e._declareLocalVar(r,al.Vector3)} = ${p}(${this.position.associatedVariableName}.xyz);\n ${e._declareLocalVar(n,al.Vector3)} = ${f}(${this.position.associatedVariableName}.xyz);\n ${e._declareLocalVar(o,al.Vector3)} = abs(${this.normal.associatedVariableName}.xyz);\n \n // determine major axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(a,e)} = ${e._generateTernary(`${_}(0,1,2)`,`${e._generateTernary(`${_}(1,2,0)`,`${_}(2,0,1)`,`(${o}.y>${o}.z)`)}`,`(${o}.x>${o}.y && ${o}.x>${o}.z)`)}; \n\n // determine minor axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(l,e)} = ${e._generateTernary(`${_}(0,1,2)`,`${e._generateTernary(`${_}(1,2,0)`,`${_}(2,0,1)`,`(${o}.y<${o}.z)`)}`,`(${o}.x<${o}.y && ${o}.x<${o}.z)`)}; \n \n // determine median axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(h,e)} = ${_}(3) - ${l} - ${a};\n \n // project+fetch\n ${e._declareLocalVar(c,al.Vector4)} = ${this._getTextureGrad(e,t)}, vec2${m}(${this.position.associatedVariableName}[${a}.y], ${this.position.associatedVariableName}[${a}.z]), \n vec2${m}(${r}[${a}.y],${r}[${a}.z]), \n vec2${m}(${n}[${a}.y],${n}[${a}.z]));\n ${e._declareLocalVar(u,al.Vector4)} = ${this._getTextureGrad(e,i)}, vec2${m}(${this.position.associatedVariableName}[${h}.y], ${this.position.associatedVariableName}[${h}.z]), \n vec2${m}(${r}[${h}.y],${r}[${h}.z]),\n vec2${m}(${n}[${h}.y],${n}[${h}.z]));\n \n // blend factors\n ${e._declareLocalVar(d,al.Vector2)} = vec2${m}(${o}[${a}.x],${o}[${h}.x]);\n // make local support\n ${d} = clamp( (${d}-0.5773)/(1.0-0.5773), vec2${m}(0.0), vec2${m}(1.0) );\n // shape transition\n ${d} = pow( ${d}, vec2${m}(${s}/8.0) );\n // blend and return\n ${e._declareLocalVar(this._tempTextureRead,al.Vector4)} = (${c}*${d}.x + ${u}*${d}.y) / (${d}.x + ${d}.y);\n `}}z("BABYLON.BiPlanarBlock",dy);class _y extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("input",al.Matrix),this.registerOutput("output",al.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=e._declareOutput(t)+` = determinant(${i.associatedVariableName});\n`,this}}z("BABYLON.MatrixDeterminantBlock",_y);class py extends Tl{constructor(e){super(e,ll.Neutral),this.registerInput("input",al.Matrix),this.registerOutput("output",al.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=e._declareOutput(t)+` = transpose(${i.associatedVariableName});\n`,this}}z("BABYLON.MatrixTransposeBlock",py),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Tangent=2]="Tangent",e[e.VertexColor=3]="VertexColor",e[e.UV1=4]="UV1",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6"}(iy||(iy={}));class fy extends Tl{constructor(e){super(e,ll.Neutral),this.attributeType=iy.None,this.registerInput("input",al.AutoDetect),this.registerInput("fallback",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add((e=>{if(this.attributeType)return;const t=e.ownerBlock;if(t instanceof Ol&&t.isAttribute)switch(t.name){case"color":this.attributeType=iy.VertexColor;break;case"normal":this.attributeType=iy.Normal;break;case"tangent":this.attributeType=iy.Tangent;break;case"uv":this.attributeType=iy.UV1;break;case"uv2":this.attributeType=iy.UV2;break;case"uv3":this.attributeType=iy.UV3;break;case"uv4":this.attributeType=iy.UV4;break;case"uv5":this.attributeType=iy.UV5;break;case"uv6":this.attributeType=iy.UV6}else if(t instanceof Ob)switch(this.input.connectedPoint?.name){case"normalOutput":this.attributeType=iy.Normal;break;case"tangentOutput":this.attributeType=iy.Tangent;break;case"uvOutput":this.attributeType=iy.UV1}}))}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case iy.VertexColor:t="VERTEXCOLOR_NME";break;case iy.Normal:t="NORMAL";break;case iy.Tangent:t="TANGENT";break;case iy.UV1:t="UV1";break;case iy.UV2:t="UV2";break;case iy.UV3:t="UV3";break;case iy.UV4:t="UV4";break;case iy.UV5:t="UV5";break;case iy.UV6:t="UV6"}const i=e._declareOutput(this.output);return t&&(e.compilationString+=`#ifdef ${t}\n`),e.compilationString+=`${i} = ${this.input.associatedVariableName};\n`,t&&(e.compilationString+="#else\n",e.compilationString+=`${i} = ${this.fallback.associatedVariableName};\n`,e.compilationString+="#endif\n"),this}serialize(){const e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.attributeType=e.attributeType??iy.None}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType};\n`,e}}Ze([Cl("Attribute lookup",ul.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:iy.None},{label:"Normal",value:iy.Normal},{label:"Tangent",value:iy.Tangent},{label:"Vertex Color",value:iy.VertexColor},{label:"UV1",value:iy.UV1},{label:"UV2",value:iy.UV2},{label:"UV3",value:iy.UV3},{label:"UV4",value:iy.UV4},{label:"UV5",value:iy.UV5},{label:"UV6",value:iy.UV6}]})],fy.prototype,"attributeType",void 0),z("BABYLON.MeshAttributeExistsBlock",fy),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(sy||(sy={}));class my extends Tl{constructor(e){super(e,ll.Neutral),this.type=sy.EaseInOutSine,this.registerInput("input",al.AutoDetect),this.registerOutput("output",al.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(al.Matrix),this._inputs[0].excludedConnectionPointTypes.push(al.Object),this._inputs[0].excludedConnectionPointTypes.push(al.Int)}getClassName(){return"CurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_duplicateEntry(e,t){return`ret.${t} = ${e.replace(/VAL/g,"v."+t)}`}_duplicateEntryDirect(e){return`return ${e.replace(/VAL/g,"v")}`}_duplicateVector(e,t,i){if("float"===t||"f32"===t)return this._duplicateEntryDirect(e);const s=parseInt(t.replace("vec",""));let r=i?`\n var ret: vec${s}f = vec${s}f(0.0);\n `:`\n vec${s} ret = vec${s}(0.0);\n `;for(let t=1;t<=s;t++)r+=this._duplicateEntry(e,1===t?"x":2===t?"y":3===t?"z":"w")+";\n";return r+="return ret;\n",r}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",s="";const r=e._getShaderType(this.input.type),n=e.shaderLanguage===di.WGSL;switch(s=sy[this.type]+"_"+r.replace("<","").replace(">",""),this.type){case sy.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case sy.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case sy.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case sy.EaseInQuad:i="return v * v";break;case sy.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case sy.EaseInOutQuad:{const t=e._generateTernary("2.0 * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case sy.EaseInCubic:i="return v * v * v";break;case sy.EaseOutCubic:{const e="1.0 - pow(1.0 - VAL, 3.0)";i=this._duplicateVector(e,r,n);break}case sy.EaseInOutCubic:{const t=e._generateTernary("4.0 * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case sy.EaseInQuart:i="return v * v * v * v";break;case sy.EaseOutQuart:{const e="1.0 - pow(1.0 - VAL, 4.0)";i=this._duplicateVector(e,r,n);break}case sy.EaseInOutQuart:{const t=e._generateTernary("8.0 * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case sy.EaseInQuint:i="return v * v * v * v * v";break;case sy.EaseOutQuint:{const e="1.0 - pow(1.0 - VAL, 5.0)";i=this._duplicateVector(e,r,n);break}case sy.EaseInOutQuint:{const t=e._generateTernary("16.0 * VAL * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case sy.EaseInExpo:{const t=e._generateTernary("0.0","pow(2.0, 10.0 * VAL - 10.0)","VAL == 0.0");i=this._duplicateVector(t,r,n);break}case sy.EaseOutExpo:{const t=e._generateTernary("1.0","1.0 - pow(2.0, -10.0 * VAL)","VAL == 1.0");i=this._duplicateVector(t,r,n);break}case sy.EaseInOutExpo:{const t=e._generateTernary("0.0",e._generateTernary("1.0",e._generateTernary("pow(2.0, 20.0 * VAL - 10.0) / 2.0","(2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}case sy.EaseInCirc:{const e="1.0 - sqrt(1.0 - pow(VAL, 2.0))";i=this._duplicateVector(e,r,n);break}case sy.EaseOutCirc:{const e="sqrt(1.0 - pow(VAL - 1.0, 2.0))";i=this._duplicateVector(e,r,n);break}case sy.EaseInOutCirc:{const t=e._generateTernary("(1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0","(sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case sy.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case sy.EaseOutBack:{const e="2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)";i=this._duplicateVector(e,r,n);break}case sy.EaseInOutBack:{const t=e._generateTernary("(pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0","(pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case sy.EaseInElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0","-pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))","VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}case sy.EaseOutElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0","pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0","VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}case sy.EaseInOutElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0",e._generateTernary("-(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0","(pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}}return n?e._emitFunction(s,`fn ${s}(v: ${r}) -> ${r} {${i};}\n`,""):e._emitFunction(s,`${r} ${s}(${r} v) {${i};}\n`,""),e.compilationString+=e._declareOutput(t)+` = ${s}(${this.input.associatedVariableName});\n`,this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${sy[this.type]};\n`}}z("BABYLON.CurveBlock",my);class gy{optimize(e,t){}}class vy{constructor(){this.mm=new Map}get(e,t){const i=this.mm.get(e);if(void 0!==i)return i.get(t)}set(e,t,i){let s=this.mm.get(e);void 0===s&&this.mm.set(e,s=new Map),s.set(t,i)}}class xy{get standalone(){return this._options?.standalone??!1}get baseMaterial(){return this._baseMaterial}get doNotInjectCode(){return this._options?.doNotInjectCode??!1}constructor(e,t,i){this._baseMaterial=e,this._scene=t??re.LastCreatedScene,this._options=i,this._subMeshToEffect=new Map,this._subMeshToDepthWrapper=new vy,this._meshes=new Map,this._onEffectCreatedObserver=this._baseMaterial.onEffectCreatedObservable.add((e=>{const t=e.subMesh?.getMesh();t&&!this._meshes.has(t)&&this._meshes.set(t,t.onDisposeObservable.add((e=>{const t=this._subMeshToEffect.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value;t?.getMesh()===e&&(this._subMeshToEffect.delete(t),this._deleteDepthWrapperEffect(t))}}))),this._subMeshToEffect.get(e.subMesh)?.[0]!==e.effect&&(this._subMeshToEffect.set(e.subMesh,[e.effect,this._scene.getEngine().currentRenderPassId]),this._deleteDepthWrapperEffect(e.subMesh))}))}_deleteDepthWrapperEffect(e){const t=this._subMeshToDepthWrapper.mm.get(e);t&&(t.forEach((e=>{e.mainDrawWrapper.effect?.dispose()})),this._subMeshToDepthWrapper.mm.delete(e))}getEffect(e,t,i){const s=this._subMeshToDepthWrapper.mm.get(e)?.get(t);if(!s)return null;let r=s.drawWrapper[i];return r||(r=s.drawWrapper[i]=new Un(this._scene.getEngine()),r.setEffect(s.mainDrawWrapper.effect,s.mainDrawWrapper.defines)),r}isReadyForSubMesh(e,t,i,s,r){return!(this.standalone&&!this._baseMaterial.isReadyForSubMesh(e.getMesh(),e,s))&&(this._makeEffect(e,t,i,r)?.isReady()??!1)}dispose(){this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver),this._onEffectCreatedObserver=null;const e=this._meshes.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;e.onDisposeObservable.remove(i)}}_makeEffect(e,t,i,s){const r=this._scene.getEngine(),n=this._subMeshToEffect.get(e);if(!n)return null;const[o,a]=n;let l=this._subMeshToDepthWrapper.get(e,i);if(!l){const t=new Un(r);t.defines=e._getDrawWrapper(a)?.defines??null,l={drawWrapper:[],mainDrawWrapper:t,depthDefines:"",token:Cs()},l.drawWrapper[s]=t,this._subMeshToDepthWrapper.set(e,i,l)}const h=t.join("\n");if(l.mainDrawWrapper.effect&&h===l.depthDefines)return l.mainDrawWrapper.effect;l.depthDefines=h;const c=o.getUniformNames().slice();let u=o.vertexSourceCodeBeforeMigration,d=o.fragmentSourceCodeBeforeMigration;if(!this.doNotInjectCode){const e=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",t=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",i=this._options&&this._options.remappedVariables?`#include(${this._options.remappedVariables.join(",")})`:"#include",s="#include",r="#include";u=o.shaderLanguage===di.GLSL?u.replace(/void\s+?main/g,`\n${r}\nvoid main`):u.replace(/@vertex/g,`\n${r}\n@vertex`),u=u.replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g,e),u=-1!==u.indexOf("#define SHADOWDEPTH_METRIC")?u.replace(/#define SHADOWDEPTH_METRIC/g,t):u.replace(/}\s*$/g,t+"\n}"),u=u.replace(/#define SHADER_NAME.*?\n|out vec4 glFragColor;\n/g,"");const n=d.indexOf("#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW")>=0||d.indexOf("#define CUSTOM_FRAGMENT_BEFORE_FOG")>=0,a=-1!==d.indexOf("#define SHADOWDEPTH_FRAGMENT");let l="";n?d=d.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g,i):l=i+"\n",d=d.replace(/void\s+?main/g,$i.IncludesShadersStore.shadowMapFragmentExtraDeclaration+"\nvoid main"),a?d=d.replace(/#define SHADOWDEPTH_FRAGMENT/g,s):l+=s+"\n",l&&(d=d.replace(/}\s*$/g,l+"}")),c.push("biasAndScaleSM","depthValuesSM","lightDataSM","softTransparentShadowSM")}l.mainDrawWrapper.effect=r.createEffect({vertexSource:u,fragmentSource:d,vertexToken:l.token,fragmentToken:l.token},{attributes:o.getAttributesNames(),uniformsNames:c,uniformBuffersNames:o.getUniformBuffersNames(),samplers:o.getSamplers(),defines:h+"\n"+o.defines.replace("#define SHADOWS","").replace(/#define SHADOW\d/g,""),indexParameters:o.getIndexParameters(),shaderLanguage:o.shaderLanguage},r);for(let e=0;e0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof _e){const t=[];return e.forEach((e=>{t.push(e.flatMap((e=>[e.x,e.y,e.z])))})),t}if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){const t=[];return e.forEach((e=>{t.push(Array.from(e))})),t}return[]}static OmitZeroLengthPredicate(e,t,i){const s=[];return t.subtract(e).lengthSquared()>0&&s.push([e,t]),i.subtract(t).lengthSquared()>0&&s.push([t,i]),e.subtract(i).lengthSquared()>0&&s.push([i,e]),0===s.length?null:s}static OmitDuplicatesPredicate(e,t,i,s){const r=[];return My._SearchInPoints(e,t,s)||r.push([e,t]),My._SearchInPoints(t,i,s)||r.push([t,i]),My._SearchInPoints(i,e,s)||r.push([i,e]),0===r.length?null:r}static _SearchInPoints(e,t,i){for(const s of i)for(let i=0;i{const r=e.getVerticesData(er.PositionKind),n=e.getIndices();if(r&&n)for(let o=0,a=0;o[e.x,e.y,e.z]))}static GetPointsCountInfo(e){const t=new Array(e.length);let i=0;for(let s=e.length;s--;)t[s]=e[s].length/3,i+=t[s];return{total:i,counts:t}}static GetLineLength(e){if(0===e.length)return 0;let t;t="number"==typeof e[0]?My.ToVector3Array(e):e;const i=ve.Vector3[0];let s=0;for(let e=0;e{e.length>t?My.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t)).forEach((e=>{s.push(e)})):(s.push(e.point1),s.push(e.point2))})),s}static SegmentizeLineBySegmentCount(e,t){const i="number"==typeof e[0]?My.ToVector3Array(e):e,s=My.GetLineLength(i)/t;return My.SegmentizeLineBySegmentLength(i,s)}static GetLineSegments(e){const t=[];for(let i=0;ie.length));return{min:t[0].length,max:t[t.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,s=!1){const r=t*i;let n=0,o=0;const a=e.length;for(let t=0;t[e.x,e.y,e.z]))}static GetArrowCap(e,t,i,s,r,n=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[s,r,n,o]}}static GetPointsFromText(e,t,i,s,r=0,n=!0){const o=[],a=P_(e,t,i,s);for(const e of a){for(const t of e.paths){const e=[],i=t.getPoints();for(const t of i)e.push(t.x,t.y,r);o.push(e)}if(n)for(const t of e.holes){const e=[],i=t.getPoints();for(const t of i)e.push(t.x,t.y,r);o.push(e)}}return o}static Color3toRGBAUint8(e){const t=new Uint8Array(4*e.length);for(let i=0,s=0;ir?r:t.length,o=Math.ceil(t.length/r);o>1&&(t=[...t,...Array(n*o-t.length).fill(t[0])]);const a=My.Color3toRGBAUint8(t),l=new Oa(a,n,o,oo.TEXTUREFORMAT_RGBA,s,!1,!0,i);return l.name=e,l}static PrepareEmptyColorsTexture(e){if(!Ry.EmptyColorsTexture){const t=new Uint8Array(4);Ry.EmptyColorsTexture=new Oa(t,1,1,oo.TEXTUREFORMAT_RGBA,e,!1,!1,Oa.NEAREST_NEAREST),Ry.EmptyColorsTexture.name="grlEmptyColorsTexture"}return Ry.EmptyColorsTexture}static DisposeEmptyColorsTexture(){Ry.EmptyColorsTexture?.dispose(),Ry.EmptyColorsTexture=null}static BooleanToNumber(e){return e?1:0}}class Oy extends xl{constructor(){super(...arguments),this.GREASED_LINE_HAS_COLOR=!1,this.GREASED_LINE_SIZE_ATTENUATION=!1,this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=!1,this.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=!1,this.GREASED_LINE_CAMERA_FACING=!0}}class Dy extends nu{constructor(e,t,i){i=i||{color:Ry.DEFAULT_COLOR};const s=new Oy;s.GREASED_LINE_HAS_COLOR=!!i.color&&!i.useColors,s.GREASED_LINE_SIZE_ATTENUATION=i.sizeAttenuation??!1,s.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=i.colorDistributionType===oy.COLOR_DISTRIBUTION_TYPE_LINE,s.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=(t??e.getScene()).useRightHandedSystem,s.GREASED_LINE_CAMERA_FACING=i.cameraFacing??!0,super(e,Dy.GREASED_LINE_MATERIAL_NAME,200,s),this.colorsTexture=null,this._scene=t??e.getScene(),this._engine=this._scene.getEngine(),this._cameraFacing=i.cameraFacing??!0,this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.width=i.width?i.width:i.sizeAttenuation?Ry.DEFAULT_WIDTH_ATTENUATED:Ry.DEFAULT_WIDTH,this._sizeAttenuation=i.sizeAttenuation??!1,this.colorMode=i.colorMode??ny.COLOR_MODE_SET,this._color=i.color??null,this.useColors=i.useColors??!1,this._colorsDistributionType=i.colorDistributionType??oy.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=i.colorsSampling??Oa.NEAREST_NEAREST,this._colors=i.colors??null,this.dashCount=i.dashCount??1,this.resolution=i.resolution??new de(this._engine.getRenderWidth(),this._engine.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this._colors?this.colorsTexture=My.CreateColorsTexture(`${e.name}-colors-texture`,this._colors,this.colorsSampling,this._scene):(this._color=this._color??Ry.DEFAULT_COLOR,My.PrepareEmptyColorsTexture(this._scene)),this._engine.onDisposeObservable.add((()=>{My.DisposeEmptyColorsTexture()})),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this.colorsTexture&&e.push(this.colorsTexture)}getUniforms(){const e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_textureSize",size:2,type:"vec2"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?"\n uniform vec4 grl_aspect_resolution_lineWidth;\n uniform mat4 grl_projection;\n ":"",fragment:"\n uniform vec4 grl_dashOptions;\n uniform vec2 grl_textureSize;\n uniform vec4 grl_colorMode_visibility_colorsWidth_useColors;\n uniform vec3 grl_singleColor;\n "}}get isEnabled(){return!0}bindForSubMesh(e){if(this._cameraFacing){const t=this._scene.activeCamera;if(!t)throw Error("GreasedLinePluginMaterial requires an active camera.");{const i=t.getProjectionMatrix();e.updateMatrix("grl_projection",i)}const i=ve.Vector4[0];i.x=this._aspect,i.y=this._resolution.x,i.z=this._resolution.y,i.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",i)}const t=ve.Vector4[0];t.x=My.BooleanToNumber(this.useDash),t.y=this._dashArray,t.z=this.dashOffset,t.w=this.dashRatio,e.updateVector4("grl_dashOptions",t);const i=ve.Vector4[1];i.x=this.colorMode,i.y=this.visibility,i.z=this.colorsTexture?this.colorsTexture.getSize().width:0,i.w=My.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",i),this._color&&e.updateColor3("grl_singleColor",this._color);const s=this.colorsTexture??Ry.EmptyColorsTexture;e.setTexture("grl_colors",s),e.updateFloat2("grl_textureSize",s?.getSize().width??1,s?.getSize().height??1)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===oy.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return Dy.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if("vertex"===e){const e={CUSTOM_VERTEX_DEFINITIONS:"\n attribute float grl_widths;\n attribute vec3 grl_offsets;\n attribute float grl_colorPointers;\n varying float grlCounters;\n varying float grlColorPointer;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n attribute vec4 grl_previousAndSide;\n attribute vec4 grl_nextAndCounters;\n\n vec2 grlFix( vec4 i, float aspect ) {\n vec2 res = i.xy / i.w;\n res.x *= aspect;\n return res;\n }\n #else\n attribute vec3 grl_slopes;\n attribute float grl_counters;\n #endif\n ",CUSTOM_VERTEX_UPDATE_POSITION:"\n #ifdef GREASED_LINE_CAMERA_FACING\n vec3 grlPositionOffset = grl_offsets;\n positionUpdated += grlPositionOffset;\n #else\n positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths);\n #endif\n ",CUSTOM_VERTEX_MAIN_END:"\n grlColorPointer = grl_colorPointers;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n\n float grlAspect = grl_aspect_resolution_lineWidth.x;\n float grlBaseWidth = grl_aspect_resolution_lineWidth.w;\n\n\n vec3 grlPrevious = grl_previousAndSide.xyz;\n float grlSide = grl_previousAndSide.w;\n\n vec3 grlNext = grl_nextAndCounters.xyz;\n grlCounters = grl_nextAndCounters.w;\n\n mat4 grlMatrix = viewProjection * finalWorld;\n vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 );\n vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 );\n vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 );\n\n vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect );\n vec2 grlPrevP = grlFix( grlPrevPos, grlAspect );\n vec2 grlNextP = grlFix( grlNextPos, grlAspect );\n\n float grlWidth = grlBaseWidth * grl_widths;\n\n vec2 grlDir;\n if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP );\n else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP );\n else {\n vec2 grlDir1 = normalize( grlCurrentP - grlPrevP );\n vec2 grlDir2 = normalize( grlNextP - grlCurrentP );\n grlDir = normalize( grlDir1 + grlDir2 );\n }\n vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. );\n #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\n grlNormal.xy *= -.5 * grlWidth;\n #else\n grlNormal.xy *= .5 * grlWidth;\n #endif\n\n grlNormal *= grl_projection;\n\n #ifdef GREASED_LINE_SIZE_ATTENUATION\n grlNormal.xy *= grlFinalPosition.w;\n grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy;\n #endif\n\n grlFinalPosition.xy += grlNormal.xy * grlSide;\n gl_Position = grlFinalPosition;\n\n vPositionW = vec3(grlFinalPosition);\n #else\n grlCounters = grl_counters;\n #endif\n "};return this._cameraFacing&&(e["!gl_Position\\=viewProjection\\*worldPos;"]="//"),e}return"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:"\n varying float grlCounters;\n varying float grlColorPointer;\n uniform sampler2D grl_colors;\n ",CUSTOM_FRAGMENT_MAIN_END:`\n float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x;\n float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y;\n float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z;\n float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w;\n\n float grlUseDash = grl_dashOptions.x;\n float grlDashArray = grl_dashOptions.y;\n float grlDashOffset = grl_dashOptions.z;\n float grlDashRatio = grl_dashOptions.w;\n\n gl_FragColor.a *= step(grlCounters, grlVisibility);\n if( gl_FragColor.a == 0. ) discard;\n\n if(grlUseDash == 1.){\n gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio));\n if (gl_FragColor.a == 0.) discard;\n }\n\n #ifdef GREASED_LINE_HAS_COLOR\n if (grlColorMode == ${ny.COLOR_MODE_SET}.) {\n gl_FragColor.rgb = grl_singleColor;\n } else if (grlColorMode == ${ny.COLOR_MODE_ADD}.) {\n gl_FragColor.rgb += grl_singleColor;\n } else if (grlColorMode == ${ny.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor.rgb *= grl_singleColor;\n }\n #else\n if (grlUseColors == 1.) {\n #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE\n vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.);\n #else\n vec2 lookup = vec2(fract(grlColorPointer / grl_textureSize.x), 1.0 - floor(grlColorPointer / grl_textureSize.x) / max(grl_textureSize.y - 1.0, 1.0));\n vec4 grlColor = texture2D(grl_colors, lookup, 0.0);\n #endif\n if (grlColorMode == ${ny.COLOR_MODE_SET}.) {\n gl_FragColor = grlColor;\n } else if (grlColorMode == ${ny.COLOR_MODE_ADD}.) {\n gl_FragColor += grlColor;\n } else if (grlColorMode == ${ny.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor *= grlColor;\n }\n }\n #endif\n\n `}:null}dispose(){this.colorsTexture?.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){const s=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this.colorsTexture&&s===e.length&&!i){const t=My.Color3toRGBAUint8(e);this.colorsTexture.update(t)}else this.colorsTexture?.dispose(),this.colorsTexture=My.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}else this.colorsTexture?.dispose()}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){null===this._color&&null!==e||null!==this._color&&null===e?(this._color=e,!t&&this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){super.parse(e,t,i);const s=e.greasedLineMaterialOptions;this.colorsTexture?.dispose(),s.color&&this.setColor(s.color,!0),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colors&&(this.colors=s.colors),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),this.colors?this.colorsTexture=My.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):My.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){const t=e;t.colorsTexture?.dispose(),this._colors&&(t.colorsTexture=My.CreateColorsTexture(`${t._material.name}-colors-texture`,this._colors,t.colorsSampling,this._scene)),t.setColor(this.color,!0),t.colorsDistributionType=this.colorsDistributionType,t.colorsSampling=this.colorsSampling,t.colorMode=this.colorMode,t.useColors=this.useColors,t.visibility=this.visibility,t.useDash=this.useDash,t.dashCount=this.dashCount,t.dashRatio=this.dashRatio,t.dashOffset=this.dashOffset,t.width=this.width,t.sizeAttenuation=this.sizeAttenuation,t.resolution=this.resolution,t.markAllDefinesAsDirty()}}Dy.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",z(`BABYLON.${Dy.GREASED_LINE_MATERIAL_NAME}`,Dy);Bi.ShadersStore.greasedLinePixelShader="precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;}\nif (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { \ntextureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);}\nif (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}}\n";Bi.ShadersStore.greasedLineVertexShader="precision highp float;\n#include\nattribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer;\n#ifdef GREASED_LINE_CAMERA_FACING\nattribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;}\n#else\nattribute vec3 grl_slopes;attribute float grl_counters;\n#endif\nvoid main() {\n#include\ngrlColorPointer=grl_colorPointers;mat4 grlMatrix=viewProjection*finalWorld ;\n#ifdef GREASED_LINE_CAMERA_FACING\nfloat grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );}\nvec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. );\n#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\ngrlNormal.xy*=-.5*grlWidth;\n#else\ngrlNormal.xy*=.5*grlWidth;\n#endif\ngrlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;}\ngrlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition;\n#else\ngrlCounters=grl_counters;vec4 grlFinalPosition=grlMatrix*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition;\n#endif\n}\n";class wy extends Nd{constructor(e,t,i){const s=[`COLOR_DISTRIBUTION_TYPE_LINE ${oy.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${oy.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${ny.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${ny.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${ny.COLOR_MODE_MULTIPLY}.`],r=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&s.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(s.push("GREASED_LINE_CAMERA_FACING"),r.push("grl_previousAndSide","grl_nextAndCounters")):(r.push("grl_slopes"),r.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:r,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:s}),this._color=Ee.White(),this._colorsDistributionType=oy.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:Ry.DEFAULT_COLOR};const n=t.getEngine();this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.dashCount=i.dashCount??1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?Ry.DEFAULT_WIDTH_ATTENUATED:Ry.DEFAULT_WIDTH,this.sizeAttenuation=i.sizeAttenuation??!1,this.color=i.color??Ee.White(),this.useColors=i.useColors??!1,this.colorsDistributionType=i.colorDistributionType??oy.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=i.colorsSampling??Oa.NEAREST_NEAREST,this.colorMode=i.colorMode??ny.COLOR_MODE_SET,this._colors=i.colors??null,this._cameraFacing=i.cameraFacing??!0,this.resolution=i.resolution??new de(n.getRenderWidth(),n.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=My.PrepareEmptyColorsTexture(t),this._colors&&this.setColors(this._colors),n.onDisposeObservable.add((()=>{My.DisposeEmptyColorsTexture()}))}dispose(){this._colorsTexture?.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new de(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){const s=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this._colorsTexture&&s===e.length&&!i){const t=My.Color3toRGBAUint8(e);this._colorsTexture.update(t)}else this._colorsTexture?.dispose(),this.colorsTexture=My.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}else this._colorsTexture?.dispose()}get colorsTexture(){return this._colorsTexture??null}set colorsTexture(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",My.BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",My.BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",My.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=e??Ry.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){const s=e.greasedLineMaterialOptions;this._colorsTexture?.dispose(),s.color&&(this.color=s.color),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),s.colors?this.colorsTexture=My.CreateColorsTexture(`${this.name}-colors-texture`,s.colors,this.colorsSampling,this.getScene()):this.colorsTexture=My.PrepareEmptyColorsTexture(t),this._cameraFacing=s.cameraFacing??!0,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}const Ny=[new Ee(.98,.26,.38),new Ee(.47,.75,.3),new Ee(0,.26,.77),new Ee(.97,.6,.76),new Ee(.19,.63,.78),new Ee(.98,.8,.6),new Ee(.65,.43,.15),new Ee(.15,.47,.22),new Ee(.67,.71,.86),new Ee(.09,.46,.56),new Ee(.8,.98,.02),new Ee(.39,.29,.13),new Ee(.53,.63,.06),new Ee(.95,.96,.41),new Ee(1,.72,.94),new Ee(.63,.08,.31),new Ee(.66,.96,.95),new Ee(.22,.14,.19),new Ee(.14,.65,.59),new Ee(.93,1,.68),new Ee(.93,.14,.44),new Ee(.47,.86,.67),new Ee(.85,.07,.78),new Ee(.53,.64,.98),new Ee(.43,.37,.56),new Ee(.71,.65,.25),new Ee(.66,.19,.01),new Ee(.94,.53,.12),new Ee(.41,.44,.44),new Ee(.24,.71,.96),new Ee(.57,.28,.56),new Ee(.44,.98,.42)];var Fy;!function(e){e[e.NONE=0]="NONE",e[e.TRIANGLES=1]="TRIANGLES",e[e.VERTICES=2]="VERTICES",e[e.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",e[e.UV0=4]="UV0",e[e.UV1=5]="UV1",e[e.VERTEXCOLORS=6]="VERTEXCOLORS",e[e.MATERIALIDS=7]="MATERIALIDS"}(Fy||(Fy={}));class Ly extends xl{constructor(){super(...arguments),this.DBG_MODE=Fy.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class By extends nu{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){const i=new Ly;i.DBG_MODE=t.mode??i.DBG_MODE,i.DBG_MULTIPLY=t.multiply??i.DBG_MULTIPLY,super(e,"MeshDebug",200,i,!0,!0),this._mode=i.DBG_MODE,this._multiply=i.DBG_MULTIPLY,this.shadedDiffuseColor=t.shadedDiffuseColor??new Ee(1,1,1),this.shadedSpecularColor=t.shadedSpecularColor??new Ee(.8,.8,.8),this.shadedSpecularPower=t.shadedSpecularPower??10,this.wireframeThickness=t.wireframeThickness??.7,this.wireframeTrianglesColor=t.wireframeTrianglesColor??new Ee(0,0,0),this.wireframeVerticesColor=t.wireframeVerticesColor??new Ee(.8,.8,.8),this.vertexColor=t.vertexColor??new Ee(0,0,0),this.vertexRadius=t.vertexRadius??1.2,this.uvScale=t.uvScale??20,this.uvPrimaryColor=t.uvPrimaryColor??new Ee(1,1,1),this.uvSecondaryColor=t.uvSecondaryColor??new Ee(.5,.5,.5),this._materialColor=By.MaterialColors[By._PluginCount++%By.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&1==this._material.getScene().getEngine().version)return Ne.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),void(this._isEnabled=!1);this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){this._mode!=Fy.VERTICES&&this._mode!=Fy.TRIANGLES&&this._mode!=Fy.TRIANGLES_VERTICES||i.isVerticesDataPresent("dbg_initialPass")||Ne.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:"#if defined(DBG_ENABLED)\nuniform vec3 dbg_shadedDiffuseColor;\nuniform vec4 dbg_shadedSpecularColorPower;\nuniform vec3 dbg_thicknessRadiusScale;\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n uniform vec3 dbg_vertexColor;\n#endif\n\n#if DBG_MODE == 1\n uniform vec3 dbg_wireframeTrianglesColor;\n#elif DBG_MODE == 3\n uniform vec3 dbg_wireframeVerticesColor;\n#elif DBG_MODE == 4 || DBG_MODE == 5\n uniform vec3 dbg_uvPrimaryColor;\n uniform vec3 dbg_uvSecondaryColor;\n#elif DBG_MODE == 7\n uniform vec3 dbg_materialColor;\n#endif\n#endif"}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:"#if defined(DBG_ENABLED)\nattribute float dbg_initialPass;\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n#endif",CUSTOM_VERTEX_MAIN_END:"#if defined(DBG_ENABLED)\nfloat dbg_vertexIndex = mod(float(gl_VertexID), 3.);\nif (dbg_vertexIndex == 0.0) { \n dbg_vBarycentric = vec3(1.,0.,0.); \n}\nelse if (dbg_vertexIndex == 1.0) { \n dbg_vBarycentric = vec3(0.,1.,0.); \n}\nelse { \n dbg_vBarycentric = vec3(0.,0.,1.); \n}\n\ndbg_vVertexWorldPos = vPositionW;\ndbg_vPass = dbg_initialPass;\n#endif"}:{CUSTOM_FRAGMENT_DEFINITIONS:"#if defined(DBG_ENABLED)\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n\n#if !defined(DBG_MULTIPLY)\n vec3 dbg_applyShading(vec3 color) {\n vec3 N = vNormalW.xyz;\n vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz);\n vec3 H = normalize(L + L);\n float LdotN = clamp(dot(L,N), 0., 1.);\n float HdotN = clamp(dot(H,N), 0., 1.);\n float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w);\n color *= (LdotN / PI);\n color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI);\n return color;\n }\n#endif\n\n#if DBG_MODE == 1 || DBG_MODE == 3\n float dbg_edgeFactor() {\n vec3 d = fwidth(dbg_vBarycentric);\n vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric);\n return min(min(a3.x, a3.y), a3.z);\n }\n#endif\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor() {\n vec3 worldPos = vPositionW;\n float dist = length(worldPos - dbg_vVertexWorldPos);\n float camDist = length(worldPos - vEyePosition.xyz);\n float d = sqrt(camDist) * .001;\n return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist);\n }\n#endif\n\n#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2))\n float dbg_checkerboardFactor(vec2 uv) {\n vec2 f = fract(uv * dbg_thicknessRadiusScale.z);\n f -= .5;\n return (f.x * f.y) > 0. ? 1. : 0.;\n }\n#endif\n#endif",CUSTOM_FRAGMENT_MAIN_END:"#if defined(DBG_ENABLED)\nvec3 dbg_color = vec3(1.);\n#if DBG_MODE == 1\n dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor());\n#elif DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor = dbg_cornerFactor();\n if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard;\n dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor);\n #if DBG_MODE == 3\n dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor());\n #endif\n#elif DBG_MODE == 4 && defined(MAINUV1)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1));\n#elif DBG_MODE == 5 && defined(MAINUV2)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2));\n#elif DBG_MODE == 6 && defined(VERTEXCOLOR)\n dbg_color = vColor.rgb;\n#elif DBG_MODE == 7\n dbg_color = dbg_materialColor;\n#endif\n\n#if defined(DBG_MULTIPLY)\n gl_FragColor *= vec4(dbg_color, 1.);\n#else\n #if DBG_MODE != 6\n gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.);\n #else\n gl_FragColor = vec4(dbg_color, 1.);\n #endif\n#endif\n#endif"}}static Reset(){this._PluginCount=0,this.MaterialColors=Ny}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(0==e.getTotalIndices())return i;if(t){const t=e.getVerticesDataKinds(),s=e.getIndices(),r={};for(const i of t)r[i]=e.getVerticesData(i);i=function(){e.setIndices(s);for(const i of t){const t=e.getVertexBuffer(i).getStrideSize();e.setVerticesData(i,r[i],void 0,t)}e.removeVerticesData("dbg_initialPass")}}let s=Array.from(e.getIndices());const r=[];for(let e=0;enew Vy(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GaussianSplattingMaterial",e}getClassName(){return"GaussianSplattingMaterial"}static Parse(e,t,i){return St.Parse((()=>new Vy(e.name,t)),e,t,i)}}z("BABYLON.GaussianSplattingMaterial",Vy),Object.defineProperty(cu.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new Ty(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(Gg.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new Ty(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(_o.prototype,"decalMap",{get:function(){return this._decalMap},set:function(e){this._decalMap=e},enumerable:!0,configurable:!0});class Uy{constructor(e,t){this.radius=e,this.theta=t,this.radius=e,this.theta=t}getClassName(){return"Polar"}toString(){return JSON.stringify(this)}asArray(){return[this.radius,this.theta]}addToRef(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t}add(e){const t=new Uy(0,0);return this.addToRef(e,t),t}addInPlace(e){return this.addToRef(e,this),this}addInPlaceFromFloats(e,t){return this.radius+=e,this.theta+=t,this}subtractToRef(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t}subtract(e){const t=new Uy(0,0);return this.subtractToRef(e,t),t}subtractInPlace(e){return this.subtractToRef(e,this),this}subtractFromFloatsToRef(e,t,i){return i.radius=this.radius-e,i.theta=this.theta-t,i}subtractFromFloats(e,t){const i=new Uy(0,0);return this.subtractFromFloatsToRef(e,t,i),i}multiplyToRef(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t}multiply(e){const t=new Uy(0,0);return this.multiplyToRef(e,t),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}divideToRef(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t}divide(e){const t=new Uy(0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new Uy(this.radius,this.theta)}copyFrom(e){return this.radius=e.radius,this.theta=e.theta,this}copyFromFloats(e,t){return this.radius=e,this.theta=t,this}scaleToRef(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t}scale(e){const t=new Uy(0,0);return this.scaleToRef(e,t),t}scaleInPlace(e){return this.scaleToRef(e,this),this}set(e,t){return this.radius=e,this.theta=t,this}setAll(e){return this.set(e,e),this}toVector2ToRef(e){const t=this.radius*Math.cos(this.theta),i=this.radius*Math.sin(this.theta);return e.set(t,i),e}toVector2(){const e=new de(0,0);return this.toVector2ToRef(e)}static FromVector2ToRef(e,t){const i=Math.sign(e.y)*Math.acos(e.x/e.length());return t.radius=e.length(),t.theta=i,t}static FromVector2(e){const t=new Uy(0,0);return Uy.FromVector2ToRef(e,t),t}static FromArray(e){return new Uy(e[0],e[1])}}class Gy{constructor(e,t,i){this.radius=e,this.theta=t,this.phi=i,this.radius=e,this.theta=t,this.phi=i}getClassName(){return"Spherical"}toString(){return JSON.stringify(this)}asArray(){return[this.radius,this.theta,this.phi]}addToRef(e,t){return t.radius=this.radius+e.radius,t.theta=this.theta+e.theta,t.phi=this.phi+e.phi,t}add(e){const t=new Gy(0,0,0);return this.addToRef(e,t),t}addInPlace(e){return this.addToRef(e,this),this}addInPlaceFromFloats(e,t,i){return this.radius+=e,this.theta+=t,this.phi+=i,this}subtractToRef(e,t){return t.radius=this.radius-e.radius,t.theta=this.theta-e.theta,t.phi=this.phi-e.phi,t}subtract(e){const t=new Gy(0,0,0);return this.subtractToRef(e,t),t}subtractInPlace(e){return this.subtractToRef(e,this),this}subtractFromFloatsToRef(e,t,i,s){return s.radius=this.radius-e,s.theta=this.theta-t,s.phi=this.phi-i,s}subtractFromFloats(e,t,i){const s=new Gy(0,0,0);return this.subtractFromFloatsToRef(e,t,i,s),s}multiplyToRef(e,t){return t.radius=this.radius*e.radius,t.theta=this.theta*e.theta,t.phi=this.phi*e.phi,t}multiply(e){const t=new Gy(0,0,0);return this.multiplyToRef(e,t),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}divideToRef(e,t){return t.radius=this.radius/e.radius,t.theta=this.theta/e.theta,t.phi=this.phi/e.phi,t}divide(e){const t=new Gy(0,0,0);return this.divideToRef(e,t),t}divideInPlace(e){return this.divideToRef(e,this),this}clone(){return new Gy(this.radius,this.theta,this.phi)}copyFrom(e){return this.radius=e.radius,this.theta=e.theta,this.phi=e.phi,this}copyFromFloats(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this}scaleToRef(e,t){return t.radius=this.radius*e,t.theta=this.theta*e,t.phi=this.phi*e,t}scale(e){const t=new Gy(0,0,0);return this.scaleToRef(e,t),t}scaleInPlace(e){return this.scaleToRef(e,this),this}set(e,t,i){return this.radius=e,this.theta=t,this.phi=i,this}setAll(e){return this.set(e,e,e),this}toVector3ToRef(e){const t=this.radius*Math.sin(this.theta)*Math.cos(this.phi),i=this.radius*Math.cos(this.theta),s=this.radius*Math.sin(this.theta)*Math.sin(this.phi);return e.set(t,i,s),e}toVector3(){const e=new _e(0,0,0);return this.toVector3ToRef(e)}static FromVector3ToRef(e,t){return t.radius=e.length(),t.theta=Math.acos(e.y/t.radius),t.phi=Math.atan2(e.z,e.x),t}static FromVector3(e){const t=new Gy(0,0,0);return Gy.FromVector3ToRef(e,t),t}static FromArray(e){return new Gy(e[0],e[1],e[2])}}class zy{constructor(e,t=2,i=3,s=1,r=1){this._curIndex=0,this._sequence=[],this._numSamples=0,this.x=0,this.y=0,this._width=s,this._height=r,this._baseX=t,this._baseY=i,this._generateSequence(e),this.next()}regenerate(e){this._generateSequence(e),this.next()}setDimensions(e,t){this._width=e,this._height=t}next(){this.x=this._sequence[this._curIndex]/this._width,this.y=this._sequence[this._curIndex+1]/this._height,this._curIndex+=2,this._curIndex>=2*this._numSamples&&(this._curIndex=0)}_generateSequence(e){this._sequence=[],this._curIndex=0,this._numSamples=e;for(let t=1;t<=e;++t)this._sequence.push(this._halton(t,this._baseX)-.5,this._halton(t,this._baseY)-.5)}_halton(e,t){let i=1,s=0;for(;e>0;)i/=t,s+=i*(e%t),e=~~(e/t);return s}}function Wy(e,t){return`{X: ${e.x.toFixed(t)} Y: ${e.y.toFixed(t)}}`}function Hy(e,t){return`{X: ${e._x.toFixed(t)} Y: ${e._y.toFixed(t)} Z: ${e._z.toFixed(t)}}`}function Xy(e,t){return`{X: ${e.x.toFixed(t)} Y: ${e.y.toFixed(t)} Z: ${e.z.toFixed(t)} W: ${e.w.toFixed(t)}}`}function Yy(e,t,i,s,r){let n=null,o=null,a=null;try{let l;n=new e.Decoder,o=new e.DecoderBuffer,o.Init(t,t.byteLength);const h=n.GetEncodedGeometryType(o);switch(h){case e.TRIANGULAR_MESH:{const t=new e.Mesh;if(l=n.DecodeBufferToMesh(o,t),!l.ok()||0===t.ptr)throw new Error(l.error_msg());const i=3*t.num_faces(),r=4*i,h=e._malloc(r);try{n.GetTrianglesUInt32Array(t,r,h);const o=new Uint32Array(i);o.set(new Uint32Array(e.HEAPF32.buffer,h,i)),s(o)}finally{e._free(h)}a=t;break}case e.POINT_CLOUD:{const t=new e.PointCloud;if(l=n.DecodeBufferToPointCloud(o,t),!l.ok()||!t.ptr)throw new Error(l.error_msg());a=t;break}default:throw new Error(`Invalid geometry type ${h}`)}const c=a.num_points(),u=(t,i,s,n)=>{const o=n.data_type(),a=n.num_components(),l=n.normalized(),h=n.byte_stride(),u=n.byte_offset(),d={[e.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:e.HEAPF32},[e.DT_INT8]:{typedArrayConstructor:Int8Array,heap:e.HEAP8},[e.DT_INT16]:{typedArrayConstructor:Int16Array,heap:e.HEAP16},[e.DT_INT32]:{typedArrayConstructor:Int32Array,heap:e.HEAP32},[e.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:e.HEAPU8},[e.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:e.HEAPU16},[e.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:e.HEAPU32}}[o];if(!d)throw new Error(`Invalid data type ${o}`);const _=c*a,p=_*d.typedArrayConstructor.BYTES_PER_ELEMENT,f=e._malloc(p);try{t.GetAttributeDataArrayForAllPoints(i,n,o,p,f);const e=new d.typedArrayConstructor(d.heap.buffer,f,_);r(s,e.slice(),a,u,h,l)}finally{e._free(f)}};if(i)for(const e in i){const t=i[e],s=n.GetAttributeByUniqueId(a,t);u(n,a,e,s)}else{const t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(const e in t){const i=n.GetAttributeId(a,t[e]);if(-1!==i){const t=n.GetAttribute(a,i);u(n,a,e,t)}}}return c}finally{a&&e.destroy(a),o&&e.destroy(o),n&&e.destroy(n)}}function Qy(){let e;onmessage=t=>{const i=t.data;switch(i.id){case"init":{const t=i.decoder;t.url&&importScripts(t.url);const s=t.wasmBinary?{wasmBinary:t.wasmBinary}:{};e=DracoDecoderModule(s),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((e=>{const t=Yy(e,i.dataView,i.attributes,(e=>{postMessage({id:"indices",data:e},[e.buffer])}),((e,t,i,s,r,n)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:s,byteStride:r,normalized:n},[t.buffer])}));postMessage({id:"decodeMeshDone",totalVertices:t})}))}}}class jy{static get DecoderAvailable(){const e=jy.Configuration.decoder;return!!(e.wasmUrl&&e.wasmBinaryUrl&&"object"==typeof WebAssembly||e.fallbackUrl)}static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static get Default(){return jy._Default||(jy._Default=new jy),jy._Default}static ResetDefault(e){jy._Default&&(e||jy._Default.dispose(),jy._Default=null)}constructor(e=jy.DefaultNumWorkers){const t=jy.Configuration.decoder;if(t.workerPool||"object"==typeof e&&e.workerPool)this._workerPoolPromise=Promise.resolve(t.workerPool||e.workerPool);else{const i=t.wasmBinary||"object"==typeof e&&e.wasmBinary,s="number"==typeof e?e:e.numWorkers,r=s&&"function"==typeof Worker&&"function"==typeof URL,n=r||!r&&!t.jsModule,o=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:n?Ds.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:i?Promise.resolve(i):Ds.LoadFileAsync(Ds.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:n?Ds.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};r?this._workerPoolPromise=o.wasmBinaryPromise.then((e=>{const t=`${Yy}(${Qy})()`,i=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));return new Qg(s,(()=>function(e,t,i){return new Promise(((s,r)=>{const n=t=>{e.removeEventListener("error",n),e.removeEventListener("message",o),r(t)},o=t=>{"initDone"===t.data.id&&(e.removeEventListener("error",n),e.removeEventListener("message",o),s(e))};if(e.addEventListener("error",n),e.addEventListener("message",o),t){const s=t.slice(0);e.postMessage({id:"init",decoder:{url:i,wasmBinary:s}},[s])}else e.postMessage({id:"init",decoder:{url:i}})}))}(new Worker(i),e,o.url)))})):this._decoderModulePromise=o.wasmBinaryPromise.then((async e=>{if("undefined"==typeof DracoDecoderModule&&!t.jsModule){if(!o.url)throw new Error("Draco decoder module is not available");await Ds.LoadBabylonScriptAsync(o.url)}return await(i=e,s=t.jsModule,new Promise((e=>{(s||DracoDecoderModule)({wasmBinary:i}).then((t=>{e({module:t})}))})));var i,s}))}}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then((e=>{e.dispose()})),delete this._workerPoolPromise,delete this._decoderModulePromise}async whenReadyAsync(){this._workerPoolPromise?await this._workerPoolPromise:this._decoderModulePromise&&await this._decoderModulePromise}decodeMeshToMeshDataAsync(e,t,i){const s=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength);if(this._workerPoolPromise)return this._workerPoolPromise.then((e=>new Promise(((r,n)=>{e.push(((e,o)=>{let a=null;const l=[],h=t=>{e.removeEventListener("error",h),e.removeEventListener("message",c),n(t),o()},c=t=>{const s=t.data;switch(s.id){case"decodeMeshDone":e.removeEventListener("error",h),e.removeEventListener("message",c),r({indices:a,attributes:l,totalVertices:s.totalVertices}),o();break;case"indices":a=s.data;break;case"attribute":l.push({kind:s.kind,data:s.data,size:s.size,byteOffset:s.byteOffset,byteStride:s.byteStride,normalized:(n=s.kind,u=s.normalized,i&&void 0!==i[n]?(u!==i[n]&&Ne.Warn(`Normalized flag from Draco data (${u}) does not match normalized flag from glTF accessor (${i[n]}). Using flag from glTF accessor.`),i[n]):u)})}var n,u};e.addEventListener("error",h),e.addEventListener("message",c);const u=s.slice();e.postMessage({id:"decodeMesh",dataView:u,attributes:t},[u.buffer])}))}))));if(this._decoderModulePromise)return this._decoderModulePromise.then((e=>{let i=null;const r=[],n=Yy(e.module,s,t,(e=>{i=e}),((e,t,i,s,n,o)=>{r.push({kind:e,data:t,size:i,byteOffset:s,byteStride:n,normalized:o})}));return{indices:i,attributes:r,totalVertices:n}}));throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,i,s){const r=await this.decodeMeshToMeshDataAsync(i,s),n=new Yn(e,t);r.indices&&n.setIndices(r.indices);for(const e of r.attributes)n.setVerticesBuffer(new er(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),r.totalVertices);return n}async _decodeMeshToGeometryForGltfAsync(e,t,i,s,r){const n=await this.decodeMeshToMeshDataAsync(i,s,r),o=new Yn(e,t);n.indices&&o.setIndices(n.indices);for(const e of n.attributes)o.setVerticesBuffer(new er(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),n.totalVertices);return o}async decodeMeshAsync(e,t){const i=await this.decodeMeshToMeshDataAsync(e,t),s=new Wn;i.indices&&(s.indices=i.indices);for(const e of i.attributes){const t=er.GetFloatData(e.data,e.size,er.GetDataType(e.data),e.byteOffset,e.byteStride,e.normalized,i.totalVertices);s.set(t,e.kind)}return s}}jy.Configuration={decoder:{wasmUrl:`${Ds._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${Ds._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${Ds._DefaultCdnUrl}/draco_decoder_gltf.js`}},jy.DefaultNumWorkers=jy.GetDefaultNumWorkers(),jy._Default=null;class Ky{static get Default(){return Ky._Default||(Ky._Default=new Ky),Ky._Default}constructor(){const e=Ky.Configuration.decoder;this._decoderModulePromise=Ds.LoadBabylonScriptAsync(e.url).then((()=>MeshoptDecoder.ready))}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,s,r){return this._decoderModulePromise.then((async()=>{MeshoptDecoder.useWorkers(1);const n=await MeshoptDecoder.decodeGltfBufferAsync(t,i,e,s,r);return MeshoptDecoder.useWorkers(0),n}))}}Ky.Configuration={decoder:{url:`${Ds._DefaultCdnUrl}/meshopt_decoder.js`}},Ky._Default=null;let $y=0;class qy{constructor(e,t,i,s){this.pos=e,this.normal=t,this.uv=i,this.vertColor=s}clone(){return new qy(this.pos.clone(),this.normal.clone(),this.uv?.clone(),this.vertColor?.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new qy(_e.Lerp(this.pos,e.pos,t),_e.Lerp(this.normal,e.normal,t),this.uv&&e.uv?de.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?Ae.Lerp(this.vertColor,e.vertColor,t):void 0)}}class Zy{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const s=i.subtract(e),r=t.subtract(e);if(0===s.lengthSquared()||0===r.lengthSquared())return null;const n=_e.Normalize(_e.Cross(s,r));return new Zy(n,_e.Dot(n,e))}clone(){return new Zy(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,s,r){let n=0;const o=[];let a,l;for(a=0;aZy.EPSILON?1:0;n|=t,o.push(t)}switch(n){case 0:(_e.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:s.push(e);break;case 2:r.push(e);break;case 3:{const t=[],i=[];for(a=0;a=3&&(n=new Jy(t,e.shared),n.plane&&s.push(n)),i.length>=3&&(n=new Jy(i,e.shared),n.plane&&r.push(n));break}}}}Zy.EPSILON=1e-5;class Jy{constructor(e,t){this.vertices=e,this.shared=t,this.plane=Zy.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map((e=>e.clone()));return new Jy(e,this.shared)}flip(){this.vertices.reverse().map((e=>{e.flip()})),this.plane.flip()}}class eS{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new eS;return e._plane=this._plane&&this._plane.clone(),e._front=this._front&&this._front.clone(),e._back=this._back&&this._back.clone(),e._polygons=this._polygons.map((e=>e.clone())),e}invert(){for(let e=0;ee.clone())),e.copyTransformAttributes(this),e}union(e){const t=new eS(this.clone()._polygons),i=new eS(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),tS._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new eS(this._polygons),i=new eS(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()}subtract(e){const t=new eS(this.clone()._polygons),i=new eS(e.clone()._polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),tS._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new eS(this._polygons),i=new eS(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}intersect(e){const t=new eS(this.clone()._polygons),i=new eS(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),tS._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new eS(this._polygons),i=new eS(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){const e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map((e=>{e.flip()}))}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){const i=this.matrix.clone();i.invert();const s=this._polygons,r=[],n=[],o=[];let a=null,l=null;const h=_e.Zero(),c=_e.Zero(),u=de.Zero(),d=new Ae(0,0,0,0),_=[0,0,0],p={};let f;for(let m=0,g=s.length;me.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId)),this.toVertexData((e=>{o[e.shared.meshId]||(o[e.shared.meshId]={}),o[e.shared.meshId][e.shared.subMeshId]||(o[e.shared.meshId][e.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:e.shared.materialIndex}),a=o[e.shared.meshId][e.shared.subMeshId]}),(()=>{a.indexStart=Math.min(n,a.indexStart),a.indexEnd=Math.max(n,a.indexEnd),n++})).applyToMesh(s),i){let e,t=0;s.subMeshes=[];for(const i in o){e=-1;for(const r in o[i])a=o[i][r],Gn.CreateFromIndices(a.materialIndex+t,a.indexStart,a.indexEnd-a.indexStart+1,s),e=Math.max(a.materialIndex,e);t+=++e}}return s}toMesh(e,t=null,i,s){const r=this.buildMeshGeometry(e,i,s);return r.material=t,r.position.copyFrom(this.position),r.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(r.rotationQuaternion=this.rotationQuaternion.clone()),r.scaling.copyFrom(this.scaling),r.computeWorldMatrix(!0),r}}Bi.ShadersStore.meshUVSpaceRendererVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nvoid main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW;\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\n#endif\nvec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);}";Bi.ShadersStore.meshUVSpaceRendererPixelShader="precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;}\ngl_FragColor=texture2D(textureSampler,vDecalTC);}\n";Bi.ShadersStore.meshUVSpaceRendererMaskerVertexShader="attribute vec2 uv;varying vec2 vUV;void main(void) {gl_Position=vec4(vec2(uv.x,uv.y)*2.0-1.0,0.,1.0);vUV=uv;}";Bi.ShadersStore.meshUVSpaceRendererMaskerPixelShader="varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);}\n";Bi.ShadersStore.meshUVSpaceRendererFinaliserPixelShader="precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D maskTextureSampler;uniform vec2 textureSize;void main() {vec4 mask=texture2D(maskTextureSampler,vUV).rgba;if (mask.r>0.5) {gl_FragColor=texture2D(textureSampler,vUV);} else {vec2 texelSize=4.0/textureSize;vec2 uv_p01=vUV+vec2(-1.0,0.0)*texelSize;vec2 uv_p21=vUV+vec2(1.0,0.0)*texelSize;vec2 uv_p10=vUV+vec2(0.0,-1.0)*texelSize;vec2 uv_p12=vUV+vec2(0.0,1.0)*texelSize;float mask_p01=texture2D(maskTextureSampler,uv_p01).r;float mask_p21=texture2D(maskTextureSampler,uv_p21).r;float mask_p10=texture2D(maskTextureSampler,uv_p10).r;float mask_p12=texture2D(maskTextureSampler,uv_p12).r;vec4 col=vec4(0.0,0.0,0.0,0.0);float total_weight=0.0;if (mask_p01>0.5) {col+=texture2D(textureSampler,uv_p01);total_weight+=1.0;}\nif (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;}\nif (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;}\nif (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;}\nif (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}}\n";Bi.ShadersStore.meshUVSpaceRendererFinaliserVertexShader="precision highp float;attribute vec3 position;attribute vec2 uv;uniform mat4 worldViewProjection;varying vec2 vUV;void main() {gl_Position=worldViewProjection*vec4(position,1.0);vUV=uv;}\n";class iS{static _GetShader(e){if(!e._meshUVSpaceRendererShader){const t=new Nd("meshUVSpaceRendererShader",e,{vertex:"meshUVSpaceRenderer",fragment:"meshUVSpaceRenderer"},{attributes:["position","normal","uv"],uniforms:["world","projMatrix"],samplers:["textureSampler"],needAlphaBlending:!0});t.backFaceCulling=!1,t.alphaMode=2,e.onDisposeObservable.add((()=>{e._meshUVSpaceRendererShader?.dispose(),e._meshUVSpaceRendererShader=null})),e._meshUVSpaceRendererShader=t}return e._meshUVSpaceRendererShader}static _GetMaskShader(e){if(!e._meshUVSpaceRendererMaskShader){const t=new Nd("meshUVSpaceRendererMaskShader",e,{vertex:"meshUVSpaceRendererMasker",fragment:"meshUVSpaceRendererMasker"},{attributes:["position","uv"],uniforms:["worldViewProjection"]});t.backFaceCulling=!1,t.alphaMode=2,e.onDisposeObservable.add((()=>{e._meshUVSpaceRendererMaskShader?.dispose(),e._meshUVSpaceRendererMaskShader=null})),e._meshUVSpaceRendererMaskShader=t}return e._meshUVSpaceRendererMaskShader}static _IsRenderTargetTexture(e){return void 0!==e.renderList}constructor(e,t,i){this._textureCreatedInternally=!1,this._configureUserCreatedTexture=!0,this._maskTexture=null,this._finalPostProcess=null,this.clearColor=new Ae(0,0,0,0),this._mesh=e,this._scene=t,this._options={width:1024,height:1024,textureType:0,generateMipMaps:!0,optimizeUVAllocation:!0,uvEdgeBlending:!1,...i}}isReady(){this.texture||this._createDiffuseRTT();const e=iS._IsRenderTargetTexture(this.texture)?this.texture.isReadyForRendering():this.texture.isReady(),t=this._maskTexture?.isReadyForRendering()??!0,i=this._finalPostProcess?.isReady()??!0;return e&&t&&i}renderTexture(e,t,i,s,r=0){if(this.texture?this._configureUserCreatedTexture&&this._configureUserCreatedRTT():this._createDiffuseRTT(),iS._IsRenderTargetTexture(this.texture)){const n=this._createProjectionMatrix(t,i,s,r),o=iS._GetShader(this._scene);o.setTexture("textureSampler",e),o.setMatrix("projMatrix",n),this.texture.render()}}clear(){if(iS._IsRenderTargetTexture(this.texture)&&this.texture.renderTarget){const e=this._scene.getEngine();e.bindFramebuffer(this.texture.renderTarget),e.clear(this.clearColor,!0,!0,!0),e.unBindFramebuffer(this.texture.renderTarget)}if(this._finalPostProcess?.inputTexture){const e=this._scene.getEngine();e.bindFramebuffer(this._finalPostProcess?.inputTexture),e.clear(this.clearColor,!0,!0,!0),e.unBindFramebuffer(this._finalPostProcess?.inputTexture)}}dispose(){this._textureCreatedInternally&&(this.texture.dispose(),this._textureCreatedInternally=!1),this._configureUserCreatedTexture=!0,this._maskTexture?.dispose(),this._maskTexture=null,this._finalPostProcess?.dispose(),this._finalPostProcess=null}_configureUserCreatedRTT(){this._configureUserCreatedTexture=!1,iS._IsRenderTargetTexture(this.texture)&&(this.texture.setMaterialForRendering(this._mesh,iS._GetShader(this._scene)),this.texture.onClearObservable.add((()=>{})),this.texture.renderList=[this._mesh],this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),this.texture.addPostProcess(this._finalPostProcess)))}_createDiffuseRTT(){this._textureCreatedInternally=!0;const e=this._createRenderTargetTexture(this._options.width,this._options.height);e.setMaterialForRendering(this._mesh,iS._GetShader(this._scene)),this.texture=e,this._configureUserCreatedTexture=!1,this._options.uvEdgeBlending&&(this._createMaskTexture(),this._createPostProcess(),e.addPostProcess(this._finalPostProcess))}_createMaskTexture(){this._maskTexture||(this._maskTexture=new ih(this._mesh.name+"_maskTexture",{width:this._options.width,height:this._options.height},this._scene,!1,!0,0,!1,2,void 0,void 0,void 0,6),this._maskTexture.clearColor=new Ae(0,0,0,0),this._maskTexture.renderList.push(this._mesh),this._maskTexture.setMaterialForRendering(this._mesh,iS._GetMaskShader(this._scene)),this._maskTexture.refreshRate=ih.REFRESHRATE_RENDER_ONCE,this._scene.customRenderTargets.push(this._maskTexture))}_createPostProcess(){this._finalPostProcess||(this._finalPostProcess=new Vl(this._mesh.name+"_fixSeamsPostProcess","meshUVSpaceRendererFinaliser",["textureSize"],["textureSampler","maskTextureSampler"],1,null,1,this._scene.getEngine(),!1,null,this._options.textureType),this._finalPostProcess.onApplyObservable.add((e=>{e.setTexture("maskTextureSampler",this._maskTexture),e.setFloat2("textureSize",this._options.width,this._options.height)})))}_createRenderTargetTexture(e,t){const i=new ih(this._mesh.name+"_uvspaceTexture",{width:e,height:t},this._scene,this._options.generateMipMaps,!0,this._options.textureType,!1,this._options.generateMipMaps?3:2,!1,!1,!1,5);return i.renderParticles=!1,i.optimizeUVAllocation=!!this._options.optimizeUVAllocation,i.onClearObservable.addOnce((()=>{this._scene.getEngine().clear(this.clearColor,!0,!0,!0),i.onClearObservable.add((()=>{}))})),i.renderList=[this._mesh],i}_createProjectionMatrix(e,t,i,s=0){const r=-Math.atan2(t.z,t.x)-Math.PI/2,n=Math.sqrt(t.x*t.x+t.z*t.z),o=Math.atan2(t.y,n),a=e.add(t.scale(.5*i.z)),l=me.RotationYawPitchRoll(r,o,s).multiply(me.Translation(a.x,a.y,a.z)),h=me.Invert(l),c=me.FromArray([2/i.x,0,0,0,0,2/i.y,0,0,0,0,1/i.z,0,0,0,0,1]),u=me.FromArray([.5,0,0,0,0,.5,0,0,0,0,1,0,.5,.5,0,1]);return h.multiply(c).multiply(u)}}ha._TrailMeshParser=(e,t)=>sS.Parse(e,t);class sS extends ha{constructor(e,t,i,s,r=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._generator=t,"object"==typeof s&&null!==s?(this.diameter=s.diameter||1,this._length=s.length||60,this._segments=s.segments?s.segments>this._length?this._length:s.segments:this._length,this._sectionPolygonPointsCount=s.sections||4,this._doNotTaper=s.doNotTaper||!1,this._autoStart=s.autoStart||!0):(this.diameter=s||1,this._length=r,this._segments=this._length,this._doNotTaper=!1,this._autoStart=n),this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e<=this._sectionPolygonPointsCount;e++)this._sectionVectors[e]=_e.Zero(),this._sectionNormalVectors[e]=_e.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){const e=new Wn,t=[],i=[],s=[],r=[];let n=_e.Zero();n=this._generator instanceof _o&&this._generator.hasBoundingInfo?this._generator.getBoundingInfo().boundingBox.centerWorld:this._generator.absolutePosition;const o=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<=this._sectionPolygonPointsCount;e++){const i=e!==this._sectionPolygonPointsCount?e*o:0;t.push(n.x+Math.cos(i)*this.diameter,n.y+Math.sin(i)*this.diameter,n.z),r.push(e/this._sectionPolygonPointsCount,0)}for(let e=1;e<=this._segments;e++){for(let i=0;i<=this._sectionPolygonPointsCount;i++){const s=i!==this._sectionPolygonPointsCount?i*o:0;t.push(n.x+Math.cos(s)*this.diameter,n.y+Math.sin(s)*this.diameter,n.z),r.push(i/this._sectionPolygonPointsCount,e/this._segments)}const i=t.length/3-2*(this._sectionPolygonPointsCount+1);for(let e=0;e<=this._sectionPolygonPointsCount;e++)s.push(i+e,i+e+this._sectionPolygonPointsCount,i+e+this._sectionPolygonPointsCount+1),s.push(i+e,i+e+this._sectionPolygonPointsCount+1,i+e+1)}Wn.ComputeNormals(t,s,i),e.positions=t,e.normals=i,e.indices=s,e.uvs=r,e.applyToMesh(this,!0),this._autoStart&&this.start()}start(){this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add((()=>{this.update()})))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){const e=this.getVerticesData(er.PositionKind),t=this.getVerticesData(er.NormalKind),i=this._generator.getWorldMatrix(),s=3*(this._sectionPolygonPointsCount+1);if(e&&t){if(this._doNotTaper)for(let t=s;t{this._getSimplifier(e).simplify(t,(i=>{void 0!==t.distance&&e.mesh.addLODLevel(t.distance,i),i.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()}))}));else{const t=this._getSimplifier(e),i=(i,s)=>{t.simplify(i,(t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,s()}))};Ns.Run(e.settings.length,(t=>{i(e.settings[t.index],(()=>{t.executeNext()}))}),(()=>{e.successCallback&&e.successCallback(),this.executeNext()}))}}_getSimplifier(e){return e.simplificationType,oS.QUADRATIC,new PS(e.mesh)}}var oS,aS,lS,hS,cS,uS,dS,_S,pS,fS,mS,gS,vS,xS,bS,TS,yS;!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(oS||(oS={}));class SS{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class CS{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new ES,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class ES{constructor(e){this.data=new Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,s,r,n,o,a,l){return this.data[e]*this.data[r]*this.data[l]+this.data[i]*this.data[s]*this.data[a]+this.data[t]*this.data[n]*this.data[o]-this.data[i]*this.data[r]*this.data[o]-this.data[e]*this.data[n]*this.data[a]-this.data[t]*this.data[s]*this.data[l]}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){const t=new ES;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,s){return new ES(ES.DataFromNumbers(e,t,i,s))}static DataFromNumbers(e,t,i,s){return[e*e,e*t,e*i,e*s,t*t,t*i,t*s,i*i,i*s,s*s]}}class AS{constructor(e,t){this.vertexId=e,this.triangleId=t}}class PS{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=J}simplify(e,t){this._initDecimatedMesh(),Ns.Run(this._mesh.subMeshes.length,(t=>{this._initWithMesh(t.index,(()=>{this._runDecimation(e,t.index,(()=>{t.executeNext()}))}),e.optimizeMesh)}),(()=>{setTimeout((()=>{t(this._reconstructedMesh)}),0)}))}_runDecimation(e,t,i){const s=~~(this._triangles.length*e.quality);let r=0;const n=this._triangles.length,o=(e,t)=>{setTimeout((()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e{const t=~~((this._triangles.length/2+e)%this._triangles.length),s=this._triangles[t];if(s&&!(s.error[3]>i||s.deleted||s.isDirty))for(let e=0;e<3;++e)if(s.error[e]{-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))})),h.length%2!=0)continue;n.q=o.q.add(n.q),n.updatePosition(a);const c=this._references.length;r=this._updateTriangles(n,n,t,r),r=this._updateTriangles(n,o,i,r);const u=this._references.length-c;if(u<=n.triangleCount){if(u)for(let e=0;en-r<=s))}),0)};Ns.Run(this.decimationIterations,(e=>{n-r<=s?e.breakLoop():o(e.index,(()=>{e.executeNext()}))}),(()=>{setTimeout((()=>{this._reconstructMesh(t),i()}),0)}))}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const s=this._mesh.getVerticesData(er.PositionKind),r=this._mesh.getIndices(),n=this._mesh.subMeshes[e],o=e=>{if(i)for(let t=0;t{if(!s)return;const t=e+n.verticesStart,i=_e.FromArray(s,3*t),r=o(i)||new CS(i,this._vertices.length);r.originalOffsets.push(t),r.id===this._vertices.length&&this._vertices.push(r),a.push(r.id)}),(()=>{Ns.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,(e=>{if(!r)return;const t=3*(n.indexStart/3+e),i=r[t+0],s=r[t+1],o=r[t+2],l=this._vertices[a[i-n.verticesStart]],h=this._vertices[a[s-n.verticesStart]],c=this._vertices[a[o-n.verticesStart]],u=new SS([l,h,c]);u.originalOffset=t,this._triangles.push(u)}),(()=>{this._init(t)}))}))}_init(e){Ns.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];t.normal=_e.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(ES.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-_e.Dot(t.normal,t._vertices[0].position)))}),(()=>{Ns.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])}),(()=>{e()}))}))}_reconstructMesh(e){const t=[];let i,s,r;for(i=0;i{n.push(e.position.x),n.push(e.position.y),n.push(e.position.z),h&&h.length&&(o.push(h[3*t]),o.push(h[3*t+1]),o.push(h[3*t+2])),c&&c.length&&(a.push(c[2*t]),a.push(c[2*t+1])),u&&u.length&&(l.push(u[4*t]),l.push(u[4*t+1]),l.push(u[4*t+2]),l.push(u[4*t+3])),++d}))}const _=this._reconstructedMesh.getTotalIndices(),p=this._reconstructedMesh.getTotalVertices(),f=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(i=0;i{const t=g[s.originalOffset+e];let i=s._vertices[e].originalOffsets.indexOf(t);i<0&&(i=0),m.push(s._vertices[e].id+i+p)}));this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(er.PositionKind,n),o.length>0&&this._reconstructedMesh.setVerticesData(er.NormalKind,o),a.length>0&&this._reconstructedMesh.setVerticesData(er.UVKind,a),l.length>0&&this._reconstructedMesh.setVerticesData(er.ColorKind,l);const v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],f.forEach((e=>{Gn.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())})),Gn.AddToMesh(v.materialIndex,p,d,_,3*t.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new ha(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,s,r){for(let n=0;n.999)return!0;const d=_e.Cross(c,u).normalize();if(s[n]=!1,_e.Dot(d,o.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,s){let r=s;for(let s=0;sMS.Parse(e,t);class MS extends RS{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(My.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[],this._points.forEach((t=>{for(let i=0;i{i+=2*e.length,s+=2*(e.length-3),r+=4*e.length/3,n+=8*e.length/3}));const o=new Float32Array(i),a=i>65535?new Uint32Array(s):new Uint16Array(s),l=new Float32Array(r),h=new Float32Array(n),c=new Float32Array(n);let u=0,d=0,_=0,p=0,f=0;e.forEach((e=>{const i=My.GetLineLengthArray(e),s=i[i.length-1];for(let i=0,s=0;s>1]/s;if(this._options.uvs)for(let e=0;eOS.Parse(e,t);class OS extends RS{constructor(e,t,i,s){if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=i.widths??[],this._ribbonWidths=[],this._pathsOptions=s??[],i.points&&this.addPoints(My.ConvertPoints(i.points),i,!!s)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t{const r=OS._ConvertToRibbonPath(e,n.ribbonOptions,this._scene.useRightHandedSystem,i?i[t]:i);s=this._preprocess(r,s,n)}))}}this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:new Array(e).fill(t)}static _CreateRibbonVertexData(e,t){const i=e.length;if(i<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";const s=[],r=[],n=e[0];for(let t=0;t2)for(let e=0;e0&&(o[0]+=1,o[1]+=1),r.push(o[1]+(e%2!=0?i:0),o[0],o[2]),a&&r.push(o[0],o[1]+(e%2!=0?i:0),o[2])}else for(let e=0;ee.y&&e.x>e.z?i?OS._RightHandedForwardReadOnlyQuaternion:OS._LeftHandedForwardReadOnlyQuaternion:OS._LeftReadOnlyQuaternion),l=e.normalize()}h=l.multiplyByFloats(o,o,o),r.push(c.add(h)),n.push(c.subtract(h))}s||(r.push(a[a.length-1].add(h)),n.push(a[a.length-1].subtract(h)))}return[r,n]}static _GetDirectionFromPoints(e,t,i){return e.x!==t.x||i&&1!==i?.x?e.y===t.y?OS.DIRECTION_XZ:e.z===t.z?OS.DIRECTION_XY:OS.DIRECTION_XZ:OS.DIRECTION_YZ}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),s={},r=[];Ye.DeepCopy(this._pathsOptions,r,void 0,void 0,!0),Ye.DeepCopy(i,s,["instance"],void 0,!0);const n=new OS(e,this._scene,s,r);return t&&(n.parent=t),n.material=this.material,n}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions(),e.pathsOptions=this._pathsOptions}static Parse(e,t){const i=e.lineOptions,s=e.name,r=e.pathOptions;return new OS(s,t,i,r)}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){const t=e.length;this._vSegmentLengths=new Array(t),this._vTotalLengths=new Array(t);let i=0;for(let s=0;s0){if(t.length%2!=0&&t.push(s),i===uS.WIDTH_DISTRIBUTION_START_END){const e=Math.floor(t.length/2);for(let i=0,s=0;i0){if(i===cS.COLOR_DISTRIBUTION_START_END){const e=Math.floor(t.length/2);for(let i=0;i=this._thinInstanceDataStorage.instancesCount)return!1;const s=this._thinInstanceDataStorage.matrixData;return t.copyToArray(s,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},ha.prototype.thinInstanceSetAttributeAt=function(e,t,i,s=!0){return e===er.ColorKind&&(e=er.ColorInstanceKind),!(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[e]||t>=this._thinInstanceDataStorage.instancesCount||(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),s&&this.thinInstanceBufferUpdated(e),0))},Object.defineProperty(ha.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){const t=this._thinInstanceDataStorage.matrixData??this.source?._thinInstanceDataStorage.matrixData;e<=(t?t.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),ha.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!0){const s=new Js(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(s.createVertexBuffer(e+t,4*t,4));return s},ha.prototype.thinInstanceSetBuffer=function(e,t,i=0,s=!0){i=i||16,"matrix"===e?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*i,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/i,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,s),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,s))):(e===er.ColorKind&&(e=er.ColorInstanceKind),null===t?this._userThinInstanceBuffersStorage?.data[e]&&(this.removeVerticesData(e),delete this._userThinInstanceBuffersStorage.data[e],delete this._userThinInstanceBuffersStorage.strides[e],delete this._userThinInstanceBuffersStorage.sizes[e],delete this._userThinInstanceBuffersStorage.vertexBuffers[e]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[e]=t,this._userThinInstanceBuffersStorage.strides[e]=i,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new er(this.getEngine(),t,e,!s,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},ha.prototype.thinInstanceBufferUpdated=function(e){"matrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.matrixBuffer?.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):"previousMatrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.previousMatrixBuffer?.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(e===er.ColorKind&&(e=er.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[e].isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0)))},ha.prototype.thinInstancePartialBufferUpdate=function(e,t,i){"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===er.ColorKind&&(e=er.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},ha.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;te.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}_resetCounters(){this._callCount=0,this._executionCount=0}get callCount(){return this._callCount}get executionCount(){return this._executionCount}getConnectedValue(e){return this.isConnected?this._connectedPoint?._storedFunction?(this._connectedPoint._callCount++,this._connectedPoint._executionCount++,this._connectedPoint._storedFunction(e)):(this._connectedPoint._callCount++,this._connectedPoint._executionCount=1,this._connectedPoint._storedValue):(this._callCount++,this._executionCount=1,this.value)}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=new Array,this._type=dS.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new K,this.onDisconnectionObservable=new K,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._callCount=0,this._executionCount=0,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===_S.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==dS.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?_S.Compatible:_S.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return _S.TypeIncompatible;let s=i,r=t;return this.direction===pS.Input&&(s=t,r=i),s.isAnAncestorOf(r)?_S.HierarchyIssue:_S.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear()}}class kS{get buildExecutionTime(){return this._buildExecutionTime}get inputs(){return this._inputs}get outputs(){return this._outputs}get name(){return this._name}set name(e){this._name=e}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get isDebug(){return this._isDebug}get isUnique(){return this._isUnique}getClassName(){return"NodeGeometryBlock"}_inputRename(e){return e}_outputRename(e){return e}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){if(i.ownerBlock===e)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints)if(i.ownerBlock.isAnAncestorOfType(e))return!0;return!1}getDescendantOfPredicate(e){if(e(this))return this;for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){const t=i.ownerBlock.getDescendantOfPredicate(e);if(t)return t}return null}constructor(e){this._name="",this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._isDebug=!1,this._isUnique=!1,this._buildExecutionTime=0,this.onBuildObservable=new K,this._inputs=new Array,this._outputs=new Array,this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this.uniqueId=Lr.UniqueId}registerInput(e,t,i=!1,s,r,n){const o=new BS(e,this,pS.Input);return o.type=t,o.isOptional=i,o.defaultValue=s,o.value=s,o.valueMin=r,o.valueMax=n,this._inputs.push(o),this}registerOutput(e,t,i){return(i=i??new BS(e,this,pS.Output)).type=t,this._outputs.push(i),this}_buildBlock(e){}_customBuildStep(e){}build(e){if(this._buildId===e.buildId)return!0;if(this._outputs.length>0){if(!this._outputs.some((e=>e.hasEndpoints))&&!this.isDebug)return!1;this.outputs.forEach((e=>e._resetCounters()))}this._buildId=e.buildId;for(const t of this._inputs){if(!t.connectedPoint){t.isOptional||e.notConnectedNonOptionalInputs.push(t);continue}const i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}this._customBuildStep(e),e.verbose&&Ne.Log(`Building ${this.name} [${this.getClassName()}]`);const t=Wt.Now;this._buildBlock(e),this._buildExecutionTime=Wt.Now-t;for(const t of this._outputs)for(const i of t.endpoints){const t=i.ownerBlock;t&&t.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.visibleOnFrame=this.visibleOnFrame,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach((e=>{const t=this.inputs.find((t=>t.name===e.name));if(t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value))if("number"===e.valueType)t.value=e.value;else{const i=W(e.valueType);i&&(t.value=i.FromArray(e.value))}})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}_dumpPropertiesCode(){return`${this._codeVariableName}.visibleOnFrame = ${this.visibleOnFrame};\n`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}return t}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let s=`\n// ${this.getClassName()}\n`;this.comments&&(s+=`// ${this.comments}\n`);const r=this.getClassName();if("GeometryInputBlock"===r){const e=this.type;s+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${e});\n`}else s+=`var ${this._codeVariableName} = new BABYLON.${r}("${this.name}");\n`;s+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint.ownerBlock;-1===t.indexOf(r)&&(s+=r._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const r of i.endpoints){const i=r.ownerBlock;i&&-1===t.indexOf(i)&&(s+=i._dumpCode(e,t))}return s}clone(){const e=this.serialize(),t=W(e.customType);if(t){const i=new t;return i._deserialize(e),i}return null}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose();this.onBuildObservable.clear()}}Ze([rt("comment")],kS.prototype,"comments",void 0);class VS extends kS{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",dS.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}z("BABYLON.GeometryOutputBlock",VS),function(e){e[e.None=0]="None",e[e.Positions=1]="Positions",e[e.Normals=2]="Normals",e[e.Tangents=3]="Tangents",e[e.UV=4]="UV",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6",e[e.Colors=10]="Colors",e[e.VertexID=11]="VertexID",e[e.FaceID=12]="FaceID",e[e.GeometryID=13]="GeometryID",e[e.CollectionID=14]="CollectionID",e[e.LoopID=15]="LoopID",e[e.InstanceID=16]="InstanceID"}(fS||(fS={}));class US{constructor(){this._rotationMatrix=new me,this._scalingMatrix=new me,this._positionMatrix=new me,this._scalingRotationMatrix=new me,this._transformMatrix=new me,this._tempVector3=new _e,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}get geometryContext(){return this._geometryContext}get executionContext(){return this._executionContext}get instancingContext(){return this._instancingContext}pushGeometryContext(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)}pushExecutionContext(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)}pushInstancingContext(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)}restoreGeometryContext(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null}restoreExecutionContext(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null}restoreInstancingContext(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null}getContextualValue(e,t=!1){if(!this.executionContext)return t||this.noContextualData.push(e),null;const i=this.executionContext.getExecutionIndex();switch(e){case fS.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():this.geometryContext&&this.geometryContext.positions?_e.FromArray(this.geometryContext.positions,3*i):_e.Zero();case fS.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():this.geometryContext&&this.geometryContext.normals?_e.FromArray(this.geometryContext.normals,3*i):_e.Zero();case fS.Colors:return this.geometryContext&&this.geometryContext.colors?pe.FromArray(this.geometryContext.colors,4*i):pe.Zero();case fS.Tangents:return this.geometryContext&&this.geometryContext.tangents?pe.FromArray(this.geometryContext.tangents,4*i):pe.Zero();case fS.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():this.geometryContext&&this.geometryContext.uvs?de.FromArray(this.geometryContext.uvs,2*i):de.Zero();case fS.UV2:return this.geometryContext&&this.geometryContext.uvs2?de.FromArray(this.geometryContext.uvs2,2*i):de.Zero();case fS.UV3:return this.geometryContext&&this.geometryContext.uvs3?de.FromArray(this.geometryContext.uvs3,2*i):de.Zero();case fS.UV4:return this.geometryContext&&this.geometryContext.uvs4?de.FromArray(this.geometryContext.uvs4,2*i):de.Zero();case fS.UV5:return this.geometryContext&&this.geometryContext.uvs5?de.FromArray(this.geometryContext.uvs5,2*i):de.Zero();case fS.UV6:return this.geometryContext&&this.geometryContext.uvs6?de.FromArray(this.geometryContext.uvs6,2*i):de.Zero();case fS.VertexID:return i;case fS.FaceID:return this.executionContext.getExecutionFaceIndex();case fS.LoopID:return this.executionContext.getExecutionLoopIndex();case fS.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case fS.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case fS.CollectionID:return this.geometryContext&&this.geometryContext.metadata&&this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){const i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case dS.Vector2:return new de(i,i);case dS.Vector3:return new _e(i,i,i);case dS.Vector4:return new pe(i,i,i,i)}return null}adaptInput(e,t,i){if(!e.isConnected)return e.value||i;const s=e.getConnectedValue(this);if(e._connectedPoint?.type===t)return s;switch(t){case dS.Vector2:return new de(s,s);case dS.Vector3:return new _e(s,s,s);case dS.Vector4:return new pe(s,s,s,s)}return null}emitErrors(){let e="";for(const t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional.\n`;for(const t of this.noContextualData)e+=`Contextual input ${fS[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block).\n`;if(e)throw"Build of NodeGeometry failed:\n"+e}_instantiate(e,t,i,s,r){me.ScalingToRef(s.x,s.y,s.z,this._scalingMatrix),me.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),me.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let t=0;te.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${fS[this._contextualSource]};\n`;const t=[];let i="";switch(this.type){case dS.Float:case dS.Int:i=`${this.value}`;break;case dS.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case dS.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case dS.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`}return t.push(`${e}.value = ${i}`),this.type!==dS.Float&&this.type!==dS.Int||t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}serialize(){const e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,null===this._storedValue||this.isContextual||(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=W(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}z("BABYLON.GeometryInputBlock",GS);class zS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",dS.Float,!0,1),this.registerInput("width",dS.Float,!0,0),this.registerInput("height",dS.Float,!0,0),this.registerInput("depth",dS.Float,!0,0),this.registerInput("subdivisions",dS.Int,!0,1),this.registerInput("subdivisionsX",dS.Int,!0,0),this.registerInput("subdivisionsY",dS.Int,!0,0),this.registerInput("subdivisionsZ",dS.Int,!0,0),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){const e=new GS("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){const e=new GS("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new GS("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new GS("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){const t={},i=e=>{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.depth=this.depth.getConnectedValue(e);const i=this.subdivisions.getConnectedValue(e),s=this.subdivisionsX.getConnectedValue(e),r=this.subdivisionsY.getConnectedValue(e),n=this.subdivisionsZ.getConnectedValue(e);return i&&(t.segments=i),s&&(t.widthSegments=s),r&&(t.heightSegments=r),n&&(t.depthSegments=n),hd(t)};if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],zS.prototype,"evaluateContext",void 0),z("BABYLON.BoxBlock",zS);class WS{_getGlobalNodeGeometryEditor(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=WS._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new K,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return Ds.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise((t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),void 0===this.BJSNODEGEOMETRYEDITOR){const i=e&&e.editorURL?e.editorURL:WS.EditorURL;Ds.LoadBabylonScript(i,(()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}else this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}_createNodeEditor(e){const t={nodeGeometry:this,...e};this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";const s=Wt.Now;this._initializeBlock(this.outputBlock,i);const r=new US;r.buildId=this._buildId,r.verbose=e,this.outputBlock.build(r),t&&(this._buildId=WS._BuildIdGenerator++),this._buildExecutionTime=Wt.Now-s,r.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=r.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;const i=new ha(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),!!this._vertexData&&(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e)}_initializeBlock(e,t=!0){e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._initializeBlock(i,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();const i={};for(const t of e.blocks){const e=W(t.customType);if(e){const s=new e;s._deserialize(t),i[t.id]=s,this.attachedBlocks.push(s)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,s=t._tempEntryPointUniqueId;if(s){const e=i[s];e&&e.attachToEndpoint(t)}}for(let s=0;se.targetConnectionName))&&!t||this._restoreConnections(n,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const s=e.locations||e.editorData.locations;for(const e of s)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&s.concat(this.editorData.locations),e.locations?this.editorData={locations:s}:(this.editorData=e.editorData,this.editorData.locations=s);const r=[];for(const e in i)r[e]=i[e].uniqueId;this.editorData.map=r}this.comment=e.comment}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n)for(const o of r.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==s.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;s.connectTo(e,!0),this._restoreConnections(n,t,i)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let s=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}");\n`;for(const r of t)r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));return this.outputBlock&&(e=[],s+="// Connections\n",s+=this.outputBlock._dumpCodeForOutputConnections(e),s+="// Output nodes\n",s+=`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName};\n`,s+="nodeGeometry.build();\n"),s}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new zS("Box");e.autoConfigure();const t=new VS("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=St.Clone((()=>new WS(e)),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){const t=e?{}:St.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}dispose(){for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){const t=new WS(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=St.Parse((()=>new WS(e.name)),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return"_BLANK"===e?Promise.resolve(WS.CreateDefault("blank")):new Promise(((s,r)=>{const n=new Pt;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(o.nodeGeometry);t||(t=St.Parse((()=>new WS(e)),a,null)),t.parseSerializedObject(a),t.snippetId=e;try{i||t.build(),s(t)}catch(e){r(e)}}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}WS._BuildIdGenerator=0,WS.EditorURL=`${Ds._DefaultCdnUrl}/v${oo.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`,WS.SnippetUrl="https://snippet.babylonjs.com",Ze([rt()],WS.prototype,"name",void 0),Ze([rt("comment")],WS.prototype,"comment",void 0);class HS extends kS{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=J,this.registerInput("geometry",dS.Geometry),this.registerOutput("output",dS.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e),i=[],s={};for(let e=0;es[e])),r};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`;return e+=`${this._codeVariableName}.epsilon = ${this.epsilon};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],HS.prototype,"evaluateContext",void 0),Ze([Cl("Epsilon",ul.Float,"ADVANCED",{notifiers:{rebuild:!0}})],HS.prototype,"epsilon",void 0),z("BABYLON.GeometryOptimizeBlock",HS);class XS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",dS.Float,!0,1),this.registerInput("width",dS.Float,!0,0),this.registerInput("height",dS.Float,!0,0),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){const e=new GS("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){const e=new GS("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new GS("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){const t={},i=e=>(t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),za(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],XS.prototype,"evaluateContext",void 0),z("BABYLON.PlaneBlock",XS);class YS extends kS{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.reverseWindingOrder=!1,this.serializedCachedData=!1,this.registerOutput("geometry",dS.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}cleanData(){this._mesh=null,this._cachedVertexData=null}_buildBlock(){if(!this._mesh)return void(this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null);const e=Wn.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;te.clone()}serialize(){const e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=Wn.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(e.cachedVertexData=this._cachedVertexData.serialize())),e.reverseWindingOrder=this.reverseWindingOrder,e}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=Wn.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}Ze([Cl("Serialize cached data",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],YS.prototype,"serializedCachedData",void 0),z("BABYLON.MeshBlock",YS);class QS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",dS.Float,!0,1),this.registerInput("radiusX",dS.Float,!0,0),this.registerInput("radiusY",dS.Float,!0,0),this.registerInput("radiusZ",dS.Float,!0,0),this.registerInput("subdivisions",dS.Int,!0,4),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new GS("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.radiusX=this.radiusX.getConnectedValue(e),t.radiusY=this.radiusY.getConnectedValue(e),t.radiusZ=this.radiusZ.getConnectedValue(e),ch(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],QS.prototype,"evaluateContext",void 0),z("BABYLON.IcoSphereBlock",QS);class jS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",dS.Int,!0,32),this.registerInput("diameter",dS.Float,!0,1),this.registerInput("diameterX",dS.Float,!0,0),this.registerInput("diameterY",dS.Float,!0,0),this.registerInput("diameterZ",dS.Float,!0,0),this.registerInput("arc",dS.Float,!0,1),this.registerInput("slice",dS.Float,!0,1),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new GS("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.segments=this.segments.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterX=this.diameterX.getConnectedValue(e),t.diameterY=this.diameterY.getConnectedValue(e),t.diameterZ=this.diameterZ.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),t.slice=this.slice.getConnectedValue(e),dd(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],jS.prototype,"evaluateContext",void 0),z("BABYLON.SphereBlock",jS);class KS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",dS.Float,!0,1),this.registerInput("height",dS.Float,!0,1),this.registerInput("subdivisions",dS.Int,!0,1),this.registerInput("subdivisionsX",dS.Int,!0,0),this.registerInput("subdivisionsY",dS.Int,!0,0),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){const e=new GS("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new GS("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.subdivisionsX=this.subdivisionsX.getConnectedValue(e),t.subdivisionsY=this.subdivisionsY.getConnectedValue(e),Eu(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],KS.prototype,"evaluateContext",void 0),z("BABYLON.GridBlock",KS);class $S extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",dS.Float,!0,1),this.registerInput("thickness",dS.Float,!0,.5),this.registerInput("tessellation",dS.Int,!0,16),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new GS("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.thickness=this.thickness.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),Du(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],$S.prototype,"evaluateContext",void 0),z("BABYLON.TorusBlock",$S);class qS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",dS.Float,!0,25),this.registerInput("diameter",dS.Float,!0,1),this.registerInput("diameterTop",dS.Float,!0,-1),this.registerInput("diameterBottom",dS.Float,!0,-1),this.registerInput("subdivisions",dS.Int,!0,1),this.registerInput("tessellation",dS.Int,!0,24),this.registerInput("arc",dS.Float,!0,1),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new GS("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new GS("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterTop=this.diameterTop.getConnectedValue(e),t.diameterBottom=this.diameterBottom.getConnectedValue(e),-1===t.diameterTop&&(t.diameterTop=t.diameter),-1===t.diameterBottom&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),Ku(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],qS.prototype,"evaluateContext",void 0),z("BABYLON.CylinderBlock",qS);class ZS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",dS.Float,!0,1),this.registerInput("radius",dS.Float,!0,.25),this.registerInput("tessellation",dS.Int,!0,16),this.registerInput("subdivisions",dS.Int,!0,2),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){const e=new GS("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new GS("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),fd(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],ZS.prototype,"evaluateContext",void 0),z("BABYLON.CapsuleBlock",ZS);class JS extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",dS.Float,!0,.5),this.registerInput("tessellation",dS.Int,!0,64),this.registerInput("arc",dS.Float,!0,1),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new GS("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),Td(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],JS.prototype,"evaluateContext",void 0),z("BABYLON.DiscBlock",JS);class eC extends kS{constructor(e){super(e),this.registerOutput("geometry",dS.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}}z("BABYLON.NullBlock",eC);class tC extends kS{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",dS.Geometry),this.registerInput("positions",dS.Vector3),this.registerOutput("output",dS.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.normals.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.normals||(this._vertexData.normals=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.uvs.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);const t=[],i=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.colors.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.colors||(this._vertexData.colors=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.tangents.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.tangents||(this._vertexData.tangents=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndexthis._updateInputOutputTypes())),this.left.onDisconnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onConnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onDisconnectionObservable.add((()=>this._updateInputOutputTypes()))]}getClassName(){return"MathBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){let e;const t=this.left,i=this.right;if(!t.isConnected||!i.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const s=t.type===dS.Float||t.type===dS.Int,r=i.type===dS.Float||i.type===dS.Int,n=s&&r;switch(this.operation){case mS.Add:e=n?e=>t.getConnectedValue(e)+i.getConnectedValue(e):s?e=>e.adapt(t,i.type).add(i.getConnectedValue(e)):e=>t.getConnectedValue(e).add(e.adapt(i,t.type));break;case mS.Subtract:e=n?e=>t.getConnectedValue(e)-i.getConnectedValue(e):s?e=>e.adapt(t,i.type).subtract(i.getConnectedValue(e)):e=>t.getConnectedValue(e).subtract(e.adapt(i,t.type));break;case mS.Multiply:e=n?e=>t.getConnectedValue(e)*i.getConnectedValue(e):s?e=>e.adapt(t,i.type).multiply(i.getConnectedValue(e)):e=>t.getConnectedValue(e).multiply(e.adapt(i,t.type));break;case mS.Divide:e=n?e=>t.getConnectedValue(e)/i.getConnectedValue(e):s?e=>e.adapt(t,i.type).divide(i.getConnectedValue(e)):e=>t.getConnectedValue(e).divide(e.adapt(i,t.type));break;case mS.Min:if(n)e=e=>Math.min(t.getConnectedValue(e),i.getConnectedValue(e));else{const[r,n]=s?[i,t]:[t,i];switch(r.type){case dS.Vector2:e=e=>de.Minimize(r.getConnectedValue(e),e.adapt(n,r.type));break;case dS.Vector3:e=e=>_e.Minimize(r.getConnectedValue(e),e.adapt(n,r.type));break;case dS.Vector4:e=e=>pe.Minimize(r.getConnectedValue(e),e.adapt(n,r.type))}}break;case mS.Max:if(!n){const[r,n]=s?[i,t]:[t,i];switch(r.type){case dS.Vector2:e=e=>de.Maximize(r.getConnectedValue(e),e.adapt(n,r.type));break;case dS.Vector3:e=e=>_e.Maximize(r.getConnectedValue(e),e.adapt(n,r.type));break;case dS.Vector4:e=e=>pe.Maximize(r.getConnectedValue(e),e.adapt(n,r.type))}break}e=e=>Math.max(t.getConnectedValue(e),i.getConnectedValue(e))}this.output._storedFunction=i=>t.type===dS.Int?0|e(i):e(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${mS[this.operation]};\n`}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===dS.Int||this.left.type===dS.Float&&this.right.type!==dS.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(const[e,t]of[[this.left,this.right],[this.right,this.left]])e.acceptedConnectionPointTypes=[dS.Int,dS.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==dS.Int&&t.type!==dS.Float||e.acceptedConnectionPointTypes.push(dS.Vector2,dS.Vector3,dS.Vector4))}dispose(){super.dispose(),this._connectionObservers.forEach((e=>e.remove())),this._connectionObservers.length=0}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}}Ze([Cl("Operation",ul.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:mS.Add},{label:"Subtract",value:mS.Subtract},{label:"Multiply",value:mS.Multiply},{label:"Divide",value:mS.Divide},{label:"Max",value:mS.Max},{label:"Min",value:mS.Min}]})],oC.prototype,"operation",void 0),z("BABYLON.MathBlock",oC);class aC extends kS{constructor(e){super(e),this.registerInput("value",dS.AutoDetect),this.registerInput("fromMin",dS.Float,!0,0),this.registerInput("fromMax",dS.Float,!0,1),this.registerInput("toMin",dS.Float,!0,0),this.registerInput("toMax",dS.Float,!0,1),this.registerOutput("output",dS.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(dS.Vector2),this._inputs[0].excludedConnectionPointTypes.push(dS.Vector3),this._inputs[0].excludedConnectionPointTypes.push(dS.Vector4),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),s=this.fromMax.getConnectedValue(e),r=this.toMin.getConnectedValue(e),n=(t-i)/(s-i)*(this.toMax.getConnectedValue(e)-r)+r;return this.output.type===dS.Int?Math.floor(n):n}}}z("BABYLON.MapRangeBlock",aC),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(gS||(gS={}));class lC extends kS{constructor(e){super(e),this.test=gS.Equal,this.registerInput("left",dS.Float),this.registerInput("right",dS.Float,!0,0),this.registerInput("ifTrue",dS.AutoDetect,!0,1),this.registerInput("ifFalse",dS.AutoDetect,!0,0),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=dS.Float,this._inputs[0].acceptedConnectionPointTypes.push(dS.Int),this._inputs[1].acceptedConnectionPointTypes.push(dS.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);let s=!1;switch(this.test){case gS.Equal:s=be.WithinEpsilon(t,i,J);break;case gS.NotEqual:s=t!==i;break;case gS.LessThan:s=ti;break;case gS.LessOrEqual:s=t<=i;break;case gS.GreaterOrEqual:s=t>=i;break;case gS.Xor:s=!!t&&!i||!t&&!!i;break;case gS.Or:s=!!t||!!i;break;case gS.And:s=!!t&&!!i}return s};this.output._storedFunction=t=>e(t)?this.ifTrue.getConnectedValue(t):this.ifFalse.getConnectedValue(t)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${gS[this.test]};\n`}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}Ze([Cl("Test",ul.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:gS.Equal},{label:"NotEqual",value:gS.NotEqual},{label:"LessThan",value:gS.LessThan},{label:"GreaterThan",value:gS.GreaterThan},{label:"LessOrEqual",value:gS.LessOrEqual},{label:"GreaterOrEqual",value:gS.GreaterOrEqual},{label:"Xor",value:gS.Xor},{label:"Or",value:gS.Or},{label:"And",value:gS.And}]})],lC.prototype,"test",void 0),z("BABYLON.ConditionBlock",lC),function(e){e[e.None=0]="None",e[e.LoopID=1]="LoopID",e[e.InstanceID=2]="InstanceID"}(vS||(vS={}));class hC extends kS{constructor(e){super(e),this._currentLockId=-1,this.lockMode=vS.None,this.registerInput("min",dS.AutoDetect),this.registerInput("max",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture),this._inputs[1].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[1].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[1].excludedConnectionPointTypes.push(dS.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){const e=new GS("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new GS("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case dS.Int:case dS.Float:e=e=>{const t=this.min.getConnectedValue(e)||0,i=this.max.getConnectedValue(e)||0;return t+Math.random()*(i-t)};break;case dS.Vector2:e=e=>{const t=this.min.getConnectedValue(e)||de.Zero(),i=this.max.getConnectedValue(e)||de.Zero();return new de(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y))};break;case dS.Vector3:e=e=>{const t=this.min.getConnectedValue(e)||_e.Zero(),i=this.max.getConnectedValue(e)||_e.Zero();return new _e(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z))};break;case dS.Vector4:e=e=>{const t=this.min.getConnectedValue(e)||pe.Zero(),i=this.max.getConnectedValue(e)||pe.Zero();return new pe(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z),t.w+Math.random()*(i.w-t.w))}}this.lockMode!==vS.None&&e?this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case vS.InstanceID:i=t.getContextualValue(fS.InstanceID,!0)||0;break;case vS.LoopID:i=t.getContextualValue(fS.LoopID,!0)||0}return this._currentLockId===i&&this.lockMode!==vS.None||(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}:this.output._storedFunction=e}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${vS[this.lockMode]};\n`}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}Ze([Cl("LockMode",ul.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:vS.None},{label:"LoopID",value:vS.LoopID},{label:"InstanceID",value:vS.InstanceID}]})],hC.prototype,"lockMode",void 0),z("BABYLON.RandomBlock",hC);class cC extends kS{constructor(e){super(e),this.registerInput("offset",dS.Vector3,!0,_e.Zero()),this.registerInput("scale",dS.Float,!0,1),this.registerInput("octaves",dS.Float,!0,2,0,16),this.registerInput("roughness",dS.Float,!0,.5,0,1),this.registerOutput("output",dS.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return 0!==t?-e:e}_noiseGrad(e,t,i,s){const r=15&e,n=r<8?t:i,o=r<4?i:12===r||14==r?t:s;return this._negateIf(n,r&n)+this._negateIf(o,2&r)}_fade(e){return e*e*e*(e*(6*e-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let s,r,n;return s=r=n=3735928584,n+=i,r+=t,s+=e,n^=r,n-=this._hashBitRotate(r,14),s^=n,s-=this._hashBitRotate(n,11),r^=s,r-=this._hashBitRotate(s,25),n^=r,n-=this._hashBitRotate(r,16),s^=n,s-=this._hashBitRotate(n,4),r^=s,r-=this._hashBitRotate(s,14),n^=r,n-=this._hashBitRotate(r,24),n}_mix(e,t,i,s,r,n,o,a,l,h,c){const u=1-l,d=1-h;return(1-c)*(d*(e*u+t*l)+h*(i*u+s*l))+c*(d*(r*u+n*l)+h*(o*u+a*l))}_perlinNoise(e){const t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),s=(0|e.z)-(e.z<0?1:0),r=e.x-t,n=e.y-i,o=e.z-s,a=this._fade(r),l=this._fade(n),h=this._fade(o);return this._mix(this._noiseGrad(this._hash(t,i,s),r,n,o),this._noiseGrad(this._hash(t+1,i,s),r-1,n,o),this._noiseGrad(this._hash(t,i+1,s),r,n-1,o),this._noiseGrad(this._hash(t+1,i+1,s),r-1,n-1,o),this._noiseGrad(this._hash(t,i,s+1),r,n,o-1),this._noiseGrad(this._hash(t+1,i,s+1),r-1,n,o-1),this._noiseGrad(this._hash(t,i+1,s+1),r,n-1,o-1),this._noiseGrad(this._hash(t+1,i+1,s+1),r-1,n-1,o-1),a,l,h)}_perlinSigned(e){return.982*this._perlinNoise(e)}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,s,r){const n=new _e(i.x*r+s.x,i.y*r+s.y,i.z*r+s.z);let o=1,a=1,l=0,h=0;const c=0|(e=be.Clamp(e,0,15));for(let e=0;e<=c;e++)h+=this._perlin(n.scale(o))*a,l+=a,a*=be.Clamp(t,0,1),o*=2;const u=e-Math.floor(e);if(0==u)return h/l;let d=h+this._perlin(n.scale(o))*a;return h/=l,d/=l+a,(1-u)*h+u*d}_buildBlock(){this.output._storedFunction=e=>{const t=e.getContextualValue(fS.Positions),i=this.octaves.getConnectedValue(e),s=this.roughness.getConnectedValue(e),r=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,s,t,r,n)}}}z("BABYLON.NoiseBlock",cC);class uC extends kS{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",dS.Geometry),this.registerInput("geometry1",dS.Geometry,!0),this.registerInput("geometry2",dS.Geometry,!0),this.registerInput("geometry3",dS.Geometry,!0),this.registerInput("geometry4",dS.Geometry,!0),this.registerOutput("output",dS.Geometry)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{let t=this.geometry0.getConnectedValue(e);const i=[];if(!t)return null;if(t=t.clone(),this.geometry1.isConnected){const t=this.geometry1.getConnectedValue(e);t&&i.push(t)}if(this.geometry2.isConnected){const t=this.geometry2.getConnectedValue(e);t&&i.push(t)}if(this.geometry3.isConnected){const t=this.geometry3.getConnectedValue(e);t&&i.push(t)}if(this.geometry4.isConnected){const t=this.geometry4.getConnectedValue(e);t&&i.push(t)}return i.length&&t&&(t=t.merge(i,!0,!1,!0,!0)),t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],uC.prototype,"evaluateContext",void 0),z("BABYLON.MergeGeometryBlock",uC);class dC extends kS{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",dS.Geometry,!0),this.registerInput("geometry1",dS.Geometry,!0),this.registerInput("geometry2",dS.Geometry,!0),this.registerInput("geometry3",dS.Geometry,!0),this.registerInput("geometry4",dS.Geometry,!0),this.registerInput("geometry5",dS.Geometry,!0),this.registerInput("geometry6",dS.Geometry,!0),this.registerInput("geometry7",dS.Geometry,!0),this.registerInput("geometry8",dS.Geometry,!0),this.registerInput("geometry9",dS.Geometry,!0),this.registerOutput("output",dS.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,s){if(e.isConnected){const r=e.getConnectedValue(t);if(!r)return;r.metadata=r.metadata||{},r.metadata.collectionId=i,s.push(r)}}_buildBlock(e){const t=e=>{const t=[];return this._storeGeometry(this.geometry0,e,0,t),this._storeGeometry(this.geometry1,e,1,t),this._storeGeometry(this.geometry2,e,2,t),this._storeGeometry(this.geometry3,e,3,t),this._storeGeometry(this.geometry4,e,4,t),this._storeGeometry(this.geometry5,e,5,t),this._storeGeometry(this.geometry6,e,6,t),this._storeGeometry(this.geometry7,e,7,t),this._storeGeometry(this.geometry8,e,8,t),this._storeGeometry(this.geometry9,e,9,t),t.length?t[Math.round(Math.random()*(t.length-1))]:null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],dC.prototype,"evaluateContext",void 0),z("BABYLON.GeometryCollectionBlock",dC);class _C extends kS{constructor(e){super(e),this.registerInput("input",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];t._storedFunction=e=>i.getConnectedValue(e)}}z("BABYLON.GeometryElbowBlock",_C);class pC extends kS{constructor(e){super(e),this.registerInput("geometry",dS.Geometry),this.registerOutput("output",dS.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),Wn.ComputeNormals(t.positions,t.indices,t.normals),t}}}z("BABYLON.ComputeNormalsBlock",pC);class fC extends kS{constructor(e){super(e),this.registerInput("xyzw ",dS.Vector4,!0),this.registerInput("xyz ",dS.Vector3,!0),this.registerInput("xy ",dS.Vector2,!0),this.registerInput("zw ",dS.Vector2,!0),this.registerInput("x ",dS.Float,!0),this.registerInput("y ",dS.Float,!0),this.registerInput("z ",dS.Float,!0),this.registerInput("w ",dS.Float,!0),this.registerOutput("xyzw",dS.Vector4),this.registerOutput("xyz",dS.Vector3),this.registerOutput("xy",dS.Vector2),this.registerOutput("zw",dS.Vector2),this.registerOutput("x",dS.Float),this.registerOutput("y",dS.Float),this.registerOutput("z",dS.Float),this.registerOutput("w",dS.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);const t=this.xIn,i=this.yIn,s=this.zIn,r=this.wIn,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,c=this.xyzOut,u=this.xyOut,d=this.zwOut,_=this.xOut,p=this.yOut,f=this.zOut,m=this.wOut,g=e=>{if(l.isConnected)return l.getConnectedValue(e);let h=0,c=0,u=0,d=0;if(t.isConnected&&(h=t.getConnectedValue(e)),i.isConnected&&(c=i.getConnectedValue(e)),s.isConnected&&(u=s.getConnectedValue(e)),r.isConnected&&(d=r.getConnectedValue(e)),n.isConnected){const t=n.getConnectedValue(e);t&&(h=t.x,c=t.y)}if(o.isConnected){const t=o.getConnectedValue(e);t&&(u=t.x,d=t.y)}if(a.isConnected){const t=a.getConnectedValue(e);t&&(h=t.x,c=t.y,u=t.z)}return new pe(h,c,u,d)};h._storedFunction=e=>g(e),c._storedFunction=e=>{const t=g(e);return new _e(t.x,t.y,t.z)},u._storedFunction=e=>{const t=g(e);return new de(t.x,t.y)},d._storedFunction=e=>{const t=g(e);return new de(t.z,t.w)},_._storedFunction=e=>g(e).x,p._storedFunction=e=>g(e).y,f._storedFunction=e=>g(e).z,m._storedFunction=e=>g(e).w}}z("BABYLON.VectorConverterBlock",fC);class mC extends kS{constructor(e){super(e),this.registerInput("input",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(dS.Float),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.output._storedFunction=null,this.input.isConnected?this.output._storedFunction=e=>this.input.getConnectedValue(e).normalize():this.output._storedValue=null}}z("BABYLON.NormalizeVectorBlock",mC);class gC extends kS{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",dS.Geometry),this.registerInput("id",dS.Int,!0,0),this.registerOutput("output",dS.Geometry),this.id.acceptedConnectionPointTypes.push(dS.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.geometry.getConnectedValue(e);if(!t||!t.indices||!t.positions)return t;const i=new zn;return i.materialIndex=0|this.id.getConnectedValue(e),i.indexStart=0,i.indexCount=t.indices.length,i.verticesStart=0,i.verticesCount=t.positions.length/3,t.materialInfos=[i],t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],gC.prototype,"evaluateContext",void 0),z("BABYLON.SetMaterialIDBlock",gC),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Round=4]="Round",e[e.Floor=5]="Floor",e[e.Ceiling=6]="Ceiling",e[e.Sqrt=7]="Sqrt",e[e.Log=8]="Log",e[e.Tan=9]="Tan",e[e.ArcTan=10]="ArcTan",e[e.ArcCos=11]="ArcCos",e[e.ArcSin=12]="ArcSin",e[e.Sign=13]="Sign",e[e.Negate=14]="Negate",e[e.OneMinus=15]="OneMinus",e[e.Reciprocal=16]="Reciprocal",e[e.ToDegrees=17]="ToDegrees",e[e.ToRadians=18]="ToRadians",e[e.Fract=19]="Fract",e[e.Exp2=20]="Exp2"}(xS||(xS={}));class vC extends kS{constructor(e){super(e),this.operation=xS.Cos,this.registerInput("input",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case xS.Cos:t=e=>Math.cos(e);break;case xS.Sin:t=e=>Math.sin(e);break;case xS.Abs:t=e=>Math.abs(e);break;case xS.Exp:t=e=>Math.exp(e);break;case xS.Exp2:t=e=>Math.pow(2,e);break;case xS.Round:t=e=>Math.round(e);break;case xS.Floor:t=e=>Math.floor(e);break;case xS.Ceiling:t=e=>Math.ceil(e);break;case xS.Sqrt:t=e=>Math.sqrt(e);break;case xS.Log:t=e=>Math.log(e);break;case xS.Tan:t=e=>Math.tan(e);break;case xS.ArcTan:t=e=>Math.atan(e);break;case xS.ArcCos:t=e=>Math.acos(e);break;case xS.ArcSin:t=e=>Math.asin(e);break;case xS.Sign:t=e=>Math.sign(e);break;case xS.Negate:t=e=>-e;break;case xS.OneMinus:t=e=>1-e;break;case xS.Reciprocal:t=e=>1/e;break;case xS.ToRadians:t=e=>e*Math.PI/180;break;case xS.ToDegrees:t=e=>180*e/Math.PI;break;case xS.Fract:t=e=>e>=0?e-Math.floor(e):e-Math.ceil(e)}if(!t)return this.output._storedFunction=null,void(this.output._storedValue=null);switch(this.input.type){case dS.Int:case dS.Float:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return t(i)};break;case dS.Vector2:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new de(t(i.x),t(i.y))};break;case dS.Vector3:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new _e(t(i.x),t(i.y),t(i.z))};break;case dS.Vector4:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new pe(t(i.x),t(i.y),t(i.z),t(i.w))}}return this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${xS[this.operation]};\n`}}Ze([Cl("Operation",ul.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:xS.Cos},{label:"Sin",value:xS.Sin},{label:"Abs",value:xS.Abs},{label:"Exp",value:xS.Exp},{label:"Exp2",value:xS.Exp2},{label:"Round",value:xS.Round},{label:"Floor",value:xS.Floor},{label:"Ceiling",value:xS.Ceiling},{label:"Sqrt",value:xS.Sqrt},{label:"Log",value:xS.Log},{label:"Tan",value:xS.Tan},{label:"ArcTan",value:xS.ArcTan},{label:"ArcCos",value:xS.ArcCos},{label:"ArcSin",value:xS.ArcSin},{label:"Sign",value:xS.Sign},{label:"Negate",value:xS.Negate},{label:"OneMinus",value:xS.OneMinus},{label:"Reciprocal",value:xS.Reciprocal},{label:"ToDegrees",value:xS.ToDegrees},{label:"ToRadians",value:xS.ToRadians},{label:"Fract",value:xS.Fract}]})],vC.prototype,"operation",void 0),z("BABYLON.GeometryTrigonometryBlock",vC);class xC extends kS{constructor(e){super(e),this._rotationMatrix=new me,this._scalingMatrix=new me,this._translationMatrix=new me,this._scalingRotationMatrix=new me,this._transformMatrix=new me,this.evaluateContext=!0,this.registerInput("value",dS.AutoDetect),this.registerInput("matrix",dS.Matrix,!0),this.registerInput("translation",dS.Vector3,!0,_e.Zero()),this.registerInput("rotation",dS.Vector3,!0,_e.Zero()),this.registerInput("scaling",dS.Vector3,!0,_e.One()),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(dS.Float),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.value.getConnectedValue(e);if(!t)return null;let i;if(this.matrix.isConnected)i=this.matrix.getConnectedValue(e);else{const t=this.scaling.getConnectedValue(e),s=this.rotation.getConnectedValue(e),r=this.translation.getConnectedValue(e);me.ScalingToRef(t.x,t.y,t.z,this._scalingMatrix),me.RotationYawPitchRollToRef(s.y,s.x,s.z,this._rotationMatrix),me.TranslationToRef(r.x,r.y,r.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),i=this._transformMatrix}switch(this.value.type){case dS.Geometry:{const e=t.clone();return e.transform(i),e}case dS.Vector2:return de.Transform(t,i);case dS.Vector3:return _e.TransformCoordinates(t,i);case dS.Vector4:return pe.TransformCoordinates(t,i)}return null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],xC.prototype,"evaluateContext",void 0),z("BABYLON.GeometryTransformBlock",xC);class bC extends kS{constructor(e){super(e),this.registerInput("angle",dS.Float,!1,0),this.registerOutput("matrix",dS.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new GS("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>me.RotationX(this.angle.getConnectedValue(e))}}z("BABYLON.RotationXBlock",bC);class TC extends kS{constructor(e){super(e),this.registerInput("angle",dS.Float,!1,0),this.registerOutput("matrix",dS.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new GS("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>me.RotationY(this.angle.getConnectedValue(e))}}z("BABYLON.RotationYBlock",TC);class yC extends kS{constructor(e){super(e),this.registerInput("angle",dS.Float,!1,0),this.registerOutput("matrix",dS.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new GS("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>me.RotationZ(this.angle.getConnectedValue(e))}}z("BABYLON.RotationZBlock",yC);class SC extends kS{constructor(e){super(e),this.registerInput("scale",dS.Vector3,!1,_e.One()),this.registerOutput("matrix",dS.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new GS("Scale");e.value=new _e(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.scale.getConnectedValue(e);return me.Scaling(t.x,t.y,t.z)}}}z("BABYLON.ScalingBlock",SC);class CC extends kS{constructor(e){super(e),this.registerInput("source",dS.Vector3,!0,_e.Up()),this.registerInput("target",dS.Vector3,!0,_e.Left()),this.registerOutput("matrix",dS.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.source.getConnectedValue(e).clone(),i=this.target.getConnectedValue(e).clone(),s=new me;return t.normalize(),i.normalize(),me.RotationAlignToRef(t,i,s,!0),s}}}z("BABYLON.AlignBlock",CC);class EC extends kS{constructor(e){super(e),this.registerInput("translation",dS.Vector3,!1,_e.Zero()),this.registerOutput("matrix",dS.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new GS("Translation");e.value=new _e(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.translation.getConnectedValue(e);return me.Translation(t.x,t.y,t.z)}}}z("BABYLON.TranslationBlock",EC);class AC extends kS{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",dS.Geometry),this.registerInput("instance",dS.Geometry,!0),this.registerInput("density",dS.Float,!0,1,0,1),this.registerInput("matrix",dS.Matrix,!0),this.registerInput("rotation",dS.Vector3,!0,_e.Zero()),this.registerInput("scaling",dS.Vector3,!0,_e.One()),this.scaling.acceptedConnectionPointTypes.push(dS.Float),this.registerOutput("output",dS.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get density(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected)return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=this._vertexData.positions.length/3;const i=[],s=new _e,r=[];let n=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexr)continue;s.fromArray(n,3*this._currentIndex);const o=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(o,s,t,i)}else{const t=e.adaptInput(this.scaling,dS.Vector3,_e.OneReadOnly),r=this.rotation.getConnectedValue(e)||_e.ZeroReadOnly;e._instantiate(o,s,r,t,i)}this._currentLoopIndex++}if(e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),!i.length)return null;if(1===i.length)this._vertexData=i[0];else{const e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}return this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"};\n`;return e+=`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`,e}serialize(){const e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],AC.prototype,"evaluateContext",void 0),Ze([Cl("Remove duplicated positions",ul.Boolean,"ADVANCED",{notifiers:{update:!0}})],AC.prototype,"removeDuplicatedPositions",void 0),z("BABYLON.InstantiateOnVerticesBlock",AC);class PC extends kS{constructor(e){super(e),this._currentPosition=new _e,this._currentUV=new de,this._vertex0=new _e,this._vertex1=new _e,this._vertex2=new _e,this._tempVector0=new _e,this._tempVector1=new _e,this._uv0=new de,this._uv1=new de,this._uv2=new de,this.evaluateContext=!0,this.registerInput("geometry",dS.Geometry),this.registerInput("instance",dS.Geometry,!0),this.registerInput("count",dS.Int,!0,256),this.registerInput("matrix",dS.Matrix,!0),this.registerInput("rotation",dS.Vector3,!0,_e.Zero()),this.registerInput("scaling",dS.Vector3,!0,_e.One()),this.scaling.acceptedConnectionPointTypes.push(dS.Float),this.registerOutput("output",dS.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),_e.Cross(this._tempVector1,this._tempVector0)}getOverrideUVs1ContextualValue(){return this._currentUV}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),s=this._vertexData.indices.length/3,r=i/s;let n=0;const o=[];let a=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=i);l++){let i=Math.random(),s=Math.random();if(i>s){const e=i;i=s,s=e}const l=i,h=s-i,c=1-l-h;if(this._currentPosition.set(l*this._vertex0.x+h*this._vertex1.x+c*this._vertex2.x,l*this._vertex0.y+h*this._vertex1.y+c*this._vertex2.y,l*this._vertex0.z+h*this._vertex1.z+c*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(l*this._uv0.x+h*this._uv1.x+c*this._uv2.x,l*this._uv0.y+h*this._uv1.y+c*this._uv2.y),t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length){n-=r;continue}const u=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(u,this._currentPosition,t,o)}else{const t=e.adaptInput(this.scaling,dS.Vector3,_e.OneReadOnly),i=this.rotation.getConnectedValue(e)||_e.ZeroReadOnly;e._instantiate(u,this._currentPosition,i,t,o)}a++,this._currentLoopIndex++}}if(o.length)if(1===o.length)this._vertexData=o[0];else{const e=o.splice(0,1)[0];this._vertexData=e.merge(o,!0,!1,!0,!0)}return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],PC.prototype,"evaluateContext",void 0),z("BABYLON.InstantiateOnFacesBlock",PC);class IC extends kS{constructor(e){super(e),this._currentPosition=new _e,this._vertex0=new _e,this._vertex1=new _e,this._vertex2=new _e,this.evaluateContext=!0,this.registerInput("geometry",dS.Geometry),this.registerInput("instance",dS.Geometry,!0),this.registerInput("count",dS.Int,!0,256),this.registerInput("matrix",dS.Matrix,!0),this.registerInput("rotation",dS.Vector3,!0,_e.Zero()),this.registerInput("scaling",dS.Vector3,!0,_e.One()),this.scaling.acceptedConnectionPointTypes.push(dS.Float),this.registerOutput("output",dS.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),s=[],r=Vn(this._vertexData.positions,0,this._vertexData.positions.length/3),n=r.minimum,o=r.maximum,a=new _e(1,0,0),l=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let r=0;r0&&h++}if(h%2==0){r--;continue}if(t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length)continue;const c=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(c,this._currentPosition,t,s)}else{const t=e.adaptInput(this.scaling,dS.Vector3,_e.OneReadOnly),i=this.rotation.getConnectedValue(e)||_e.ZeroReadOnly;e._instantiate(c,this._currentPosition,i,t,s)}this._currentLoopIndex++}if(s.length)if(1===s.length)this._vertexData=s[0];else{const e=s.splice(0,1)[0];this._vertexData=e.merge(s,!0,!1,!0,!0)}return e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],IC.prototype,"evaluateContext",void 0),z("BABYLON.InstantiateOnVolumeBlock",IC);class RC extends kS{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",dS.Geometry,!0),this.registerInput("count",dS.Int,!0,1),this.registerOutput("output",dS.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBaseBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get output(){return this._outputs[0]}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],RC.prototype,"evaluateContext",void 0);class MC extends RC{constructor(e){super(e),this.registerInput("matrix",dS.Matrix,!0),this.registerInput("position",dS.Vector3,!0,_e.Zero()),this.registerInput("rotation",dS.Vector3,!0,_e.Zero()),this.registerInput("scaling",dS.Vector3,!0,_e.One()),this.scaling.acceptedConnectionPointTypes.push(dS.Float)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get matrix(){return this._inputs[2]}get position(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}_buildBlock(e){const t=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[];for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],s=me.Identity(),r=_e.Zero(),n=_e.Zero(),o=_e.Zero();for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],s=me.Identity(),r=me.Identity(),n=me.Identity(),o=_e.Zero(),a=_e.Zero(),l=_e.Zero();for(this._currentIndex=0;this._currentIndexthis.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?Math.floor(this.floatIn.getConnectedValue(e)):this.intIn.isConnected?Math.floor(this.intIn.getConnectedValue(e)):0}}z("BABYLON.IntFloatConverterBlock",wC);class NC extends kS{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.log=[];const t=e=>{const t=this.input.getConnectedValue(e);if(null==t)return this.log.push(["null",""]),t;switch(this.input.type){case dS.Vector2:this.log.push([Wy(t,4),t.toString()]);break;case dS.Vector3:this.log.push([Hy(t,4),t.toString()]);break;case dS.Vector4:this.log.push([Xy(t,4),t.toString()]);break;default:this.log.push([t.toString(),t.toString()])}return t};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}z("BABYLON.DebugBlock",NC);class FC extends kS{constructor(e){super(e),this.registerInput("geometry",dS.Geometry),this.registerOutput("output",dS.Geometry),this.registerOutput("id",dS.Int),this.registerOutput("collectionId",dS.Int),this.registerOutput("verticesCount",dS.Int),this.registerOutput("facesCount",dS.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected)return this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,void(this.output._storedFunction=null);this.output._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData),this.id._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}}z("BABYLON.GeometryInfoBlock",FC),function(e){e[e.Spherical=0]="Spherical",e[e.Cylindrical=1]="Cylindrical",e[e.Cubic=2]="Cubic"}(bS||(bS={}));class LC extends kS{constructor(e){super(e),this.mapping=bS.Spherical,this.registerInput("position",dS.Vector3),this.registerInput("normal",dS.Vector3),this.registerInput("center",dS.Vector3,!0,_e.Zero()),this.registerOutput("uv",dS.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get center(){return this._inputs[2]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected)return this.uv._storedFunction=null,void(this.uv._storedValue=null);const e=_e.Zero(),t=t=>{const i=this.position.getConnectedValue(t)||_e.Zero(),s=this.normal.getConnectedValue(t)||_e.Zero(),r=this.center.getConnectedValue(t),n=de.Zero();switch(this.mapping){case bS.Spherical:{i.subtractToRef(r,e);const t=e.length();t>0&&(n.x=Math.acos(e.y/t)/Math.PI,0===e.x&&0===e.z||(n.y=Math.atan2(e.x,e.z)/(2*Math.PI)));break}case bS.Cylindrical:{i.subtractToRef(r,e);const t=e.length();t>0&&(n.x=Math.atan2(e.x/t,e.z/t)/(2*Math.PI),n.y=(e.y+1)/2);break}case bS.Cubic:{const e=Math.abs(s.x),t=Math.abs(s.y),o=Math.abs(s.z),a=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z));let l=0,h=0;e>=t&&e>=o?(l=i.y/a-r.y,h=i.z/a-r.z):t>=e&&t>=o?(l=i.x/a-r.x,h=i.z/a-r.z):(l=i.x/a-r.x,h=i.y/a-r.y),n.x=(l+1)/2,n.y=(h+1)/2}}return n};this.uv._storedFunction=e=>t(e)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${bS[this.mapping]};\n`}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}Ze([Cl("Mapping",ul.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:bS.Spherical},{label:"Cylindrical",value:bS.Cylindrical},{label:"Cubic",value:bS.Cubic}]})],LC.prototype,"mapping",void 0),z("BABYLON.MappingBlock",LC);class BC extends kS{constructor(e){super(e),this.registerInput("matrix0",dS.Matrix),this.registerInput("matrix1",dS.Matrix),this.registerOutput("output",dS.Matrix)}getClassName(){return"MatrixComposeBlock"}get matrix0(){return this._inputs[0]}get matrix1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.matrix0.isConnected||!this.matrix1.isConnected)return null;const t=this.matrix0.getConnectedValue(e),i=this.matrix1.getConnectedValue(e);return t&&i?t.multiply(i):null}}}z("BABYLON.MatrixComposeBlock",BC);class kC extends kS{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",dS.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)-1===t.indexOf(s)&&(i+=s._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(t.isAnAncestorOf(e))return!0}return!1}getDescendantOfPredicate(e){if(e(this))return this;for(const t of this.endpoints){const i=t.getDescendantOfPredicate(e);if(i)return i}return null}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(const e of this._endpoints)e.output._storedFunction=e=>this.input.getConnectedValue(e)}}z("BABYLON.TeleportInBlock",kC);class VC extends kS{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",dS.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){const e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}z("BABYLON.TeleportOutBlock",VC);class UC extends kS{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.serializedCachedData=!1,this.registerOutput("texture",dS.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise(((t,i)=>{const s=new Image,r=document.createElement("canvas"),n=r.getContext("2d");s.onload=()=>{r.width=s.width,r.height=s.height,n.drawImage(s,0,0);const e=n.getImageData(0,0,s.width,s.height).data,i=new Float32Array(e.length);for(let t=0;t{this._data=null,i()},s.src=e}))}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise(((t,i)=>{if(!e.isReady())return void e.onLoadObservable.addOnce((()=>this.extractFromTextureAsync(e).then(t).catch(i)));const s=e.getSize();np.GetTextureDataAsync(e,s.width,s.height).then((async e=>{const i=new Float32Array(e.length);for(let t=0;t=0?e%1:1-Math.abs(e)%1}_buildBlock(){const e=e=>{const t=this.texture.getConnectedValue(e);if(!t||!t.data)return null;const i=this.coordinates.getConnectedValue(e);if(!i)return null;const s=this.clampCoordinates?Math.max(0,Math.min(i.x,1)):this._repeatClamp(i.x),r=this.clampCoordinates?Math.max(0,Math.min(i.y,1)):this._repeatClamp(i.y),n=Math.floor(s*(t.width-1)),o=Math.floor(r*(t.height-1)),a=n+t.width*o;return pe.FromArray(t.data,4*a)};this.rgba._storedFunction=t=>e(t),this.rgb._storedFunction=t=>{const i=e(t);return i?i.toVector3():null},this.r._storedFunction=t=>{const i=e(t);return i?i.x:null},this.g._storedFunction=t=>{const i=e(t);return i?i.y:null},this.b._storedFunction=t=>{const i=e(t);return i?i.z:null},this.a._storedFunction=t=>{const i=e(t);return i?i.w:null}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates};\n`}serialize(){const e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}}Ze([Cl("Clamp Coordinates",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GC.prototype,"clampCoordinates",void 0),z("BABYLON.GeometryTextureFetchBlock",GC);class zC extends kS{constructor(e){super(e),this.registerInput("geometry",dS.Geometry),this.registerOutput("min",dS.Vector3),this.registerOutput("max",dS.Vector3)}getClassName(){return"BoundingBlock"}get geometry(){return this._inputs[0]}get min(){return this._outputs[0]}get max(){return this._outputs[1]}_buildBlock(){this.min._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?Vn(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?Vn(t.positions,0,t.positions.length/3).maximum:null}}}z("BABYLON.BoundingBlock",zC),function(e){e[e.Intersect=0]="Intersect",e[e.Subtract=1]="Subtract",e[e.Union=2]="Union"}(TS||(TS={}));class WC extends kS{constructor(e){super(e),this.evaluateContext=!1,this.operation=TS.Intersect,this.registerInput("geometry0",dS.Geometry),this.registerInput("geometry1",dS.Geometry),this.registerOutput("output",dS.Geometry)}getClassName(){return"BooleanGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{const t=this.geometry0.getConnectedValue(e),i=this.geometry1.getConnectedValue(e);if(!t||!i)return null;const s=t.positions.length/3;!t.normals&&i.normals&&(t.normals=new Array(t.positions.length)),!i.normals&&t.normals&&(i.normals=new Array(i.positions.length)),!t.uvs&&i.uvs&&(t.uvs=new Array(2*s)),!i.uvs&&t.uvs&&(i.uvs=new Array(2*s)),!t.colors&&i.colors&&(t.colors=new Array(4*s)),!i.colors&&t.colors&&(i.colors=new Array(4*s));const r=tS.FromVertexData(t),n=tS.FromVertexData(i);let o;switch(this.operation){case TS.Intersect:o=r.intersect(n);break;case TS.Subtract:o=r.subtract(n);break;case TS.Union:o=r.union(n)}return o.toVertexData()};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`;return e+=`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${TS[this.operation]};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation)}}Ze([Cl("Evaluate context",ul.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],WC.prototype,"evaluateContext",void 0),Ze([Cl("Operation",ul.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:TS.Intersect},{label:"Subtract",value:TS.Subtract},{label:"Union",value:TS.Union}]})],WC.prototype,"operation",void 0),z("BABYLON.BooleanGeometryBlock",WC);class HC extends kS{constructor(e){super(e),this.registerInput("x",dS.AutoDetect),this.registerInput("y",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.x.isConnected||!this.y.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.atan2(e,t);this.output._storedFunction=t=>{const i=this.x.getConnectedValue(t),s=this.y.getConnectedValue(t);switch(this.x.type){case dS.Int:case dS.Float:return e(i,s);case dS.Vector2:return new de(e(i.x,s.x),e(i.y,s.y));case dS.Vector3:return new _e(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case dS.Vector4:return new pe(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0}}}z("BABYLON.GeometryArcTan2Block",HC);class XC extends kS{constructor(e){super(e),this.registerInput("left",dS.AutoDetect),this.registerInput("right",dS.AutoDetect),this.registerInput("gradient",dS.Float),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case dS.Int:case dS.Float:return e(r,i,s);case dS.Vector2:return new de(e(r,i.x,s.x),e(r,i.y,s.y));case dS.Vector3:return new _e(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));case dS.Vector4:return new pe(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w))}return 0},this}}z("BABYLON.GeometryLerpBlock",XC);class YC extends kS{constructor(e){super(e),this.registerInput("left",dS.AutoDetect),this.registerInput("right",dS.AutoDetect),this.registerInput("gradient",dS.Float),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryNLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case dS.Int:case dS.Float:return e(r,i,s);case dS.Vector2:{const t=new de(e(r,i.x,s.x),e(r,i.y,s.y));return t.normalize(),t}case dS.Vector3:{const t=new _e(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));return t.normalize(),t}case dS.Vector4:{const t=new pe(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w));return t.normalize(),t}}return 0},this}}z("BABYLON.GeometryNLerpBlock",YC);class QC extends kS{constructor(e){super(e),this.registerInput("value",dS.AutoDetect),this.registerInput("edge",dS.Float),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryStepBlock"}get value(){return this._inputs[0]}get edge(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e{const i=this.value.getConnectedValue(t),s=this.edge.getConnectedValue(t);switch(this.value.type){case dS.Int:case dS.Float:return e(i,s);case dS.Vector2:return new de(e(i.x,s),e(i.y,s));case dS.Vector3:return new _e(e(i.x,s),e(i.y,s),e(i.z,s));case dS.Vector4:return new pe(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}}z("BABYLON.GeometryStepBlock",QC);class jC extends kS{constructor(e){super(e),this.registerInput("value",dS.AutoDetect),this.registerInput("edge0",dS.Float),this.registerInput("edge1",dS.Float),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometrySmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge0.isConnected||!this.edge1.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>{const s=Math.max(0,Math.min((e-t)/(i-t),1));return s*s*(3-2*s)};return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.edge0.getConnectedValue(t),r=this.edge1.getConnectedValue(t);switch(this.value.type){case dS.Int:case dS.Float:return e(i,s,r);case dS.Vector2:return new de(e(i.x,s,r),e(i.y,s,r));case dS.Vector3:return new _e(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r));case dS.Vector4:return new pe(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r),e(i.w,s,r))}return 0},this}}z("BABYLON.GeometrySmoothStepBlock",jC);class KC extends kS{constructor(e){super(e),this.registerInput("left",dS.AutoDetect),this.registerInput("right",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e-Math.floor(e/t)*t;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t);switch(this.left.type){case dS.Int:case dS.Float:return e(i,s);case dS.Vector2:return new de(e(i.x,s.x),e(i.y,s.y));case dS.Vector3:return new _e(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case dS.Vector4:return new pe(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0},this}}z("BABYLON.GeometryModBlock",KC);class $C extends kS{constructor(e){super(e),this.registerInput("value",dS.AutoDetect),this.registerInput("power",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryPowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.power.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.pow(e,t);return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.power.getConnectedValue(t);switch(this.value.type){case dS.Int:case dS.Float:return e(i,s);case dS.Vector2:return new de(e(i.x,s),e(i.y,s));case dS.Vector3:return new _e(e(i.x,s),e(i.y,s),e(i.z,s));case dS.Vector4:return new pe(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}}z("BABYLON.GeometryPowBlock",$C);class qC extends kS{constructor(e){super(e),this.minimum=0,this.maximum=1,this.registerInput("value",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Geometry),this._inputs[0].excludedConnectionPointTypes.push(dS.Texture)}getClassName(){return"GeometryClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=e=>Math.max(this.minimum,Math.min(e,this.maximum));return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t);switch(this.value.type){case dS.Int:case dS.Float:return e(i);case dS.Vector2:return new de(e(i.x),e(i.y));case dS.Vector3:return new _e(e(i.x),e(i.y),e(i.z));case dS.Vector4:return new pe(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e){super._deserialize(e),this.minimum=e.minimum,this.maximum=e.maximum}}Ze([Cl("Minimum",ul.Float)],qC.prototype,"minimum",void 0),Ze([Cl("Maximum",ul.Float)],qC.prototype,"maximum",void 0),z("BABYLON.GeometryClampBlock",qC);class ZC extends kS{constructor(e){super(e),this.registerInput("left",dS.AutoDetect),this.registerInput("right",dS.AutoDetect),this.registerOutput("output",dS.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Int),this._inputs[0].excludedConnectionPointTypes.push(dS.Float),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Vector2),this._inputs[1].excludedConnectionPointTypes.push(dS.Int),this._inputs[1].excludedConnectionPointTypes.push(dS.Float),this._inputs[1].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[1].excludedConnectionPointTypes.push(dS.Vector2)}getClassName(){return"GeometryCrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);switch(this.left.type){case dS.Vector3:return _e.Cross(t,i);case dS.Vector4:return _e.Cross(t.toVector3(),i.toVector3())}return 0},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}z("BABYLON.GeometryCrossBlock",ZC),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(yS||(yS={}));class JC extends kS{constructor(e){super(e),this.type=yS.EaseInOutSine,this.registerInput("input",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[0].excludedConnectionPointTypes.push(dS.Int)}getClassName(){return"GeometryCurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);let e;switch(this.type){case yS.EaseInSine:e=e=>1-Math.cos(3.1415*e/2);break;case yS.EaseOutSine:e=e=>Math.sin(3.1415*e/2);break;case yS.EaseInOutSine:e=e=>-(Math.cos(3.1415*e)-1)/2;break;case yS.EaseInQuad:e=e=>e*e;break;case yS.EaseOutQuad:e=e=>(1-e)*(1-e);break;case yS.EaseInOutQuad:e=e=>e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;break;case yS.EaseInCubic:e=e=>e*e*e;break;case yS.EaseOutCubic:e=e=>1-Math.pow(1-e,3);break;case yS.EaseInOutCubic:e=e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;break;case yS.EaseInQuart:e=e=>e*e*e*e;break;case yS.EaseOutQuart:e=e=>1-Math.pow(1-e,4);break;case yS.EaseInOutQuart:e=e=>e<.5?8*e*e*e*e:1-Math.pow(-2*e+2,4)/2;break;case yS.EaseInQuint:e=e=>e*e*e*e*e;break;case yS.EaseOutQuint:e=e=>1-Math.pow(1-e,5);break;case yS.EaseInOutQuint:e=e=>e<.5?16*e*e*e*e*e:1-Math.pow(-2*e+2,5)/2;break;case yS.EaseInExpo:e=e=>0===e?0:Math.pow(2,10*e-10);break;case yS.EaseOutExpo:e=e=>1===e?1:1-Math.pow(2,-10*e);break;case yS.EaseInOutExpo:e=e=>0===e?0:1===e?1:e<.5?Math.pow(2,20*e-10)/2:(2-Math.pow(2,-20*e+10))/2;break;case yS.EaseInCirc:e=e=>1-Math.sqrt(1-Math.pow(e,2));break;case yS.EaseOutCirc:e=e=>Math.sqrt(1-Math.pow(e-1,2));break;case yS.EaseInOutCirc:e=e=>e<.5?(1-Math.sqrt(1-Math.pow(2*e,2)))/2:(Math.sqrt(1-Math.pow(-2*e+2,2))+1)/2;break;case yS.EaseInBack:e=e=>2.70158*e*e*e-1.70158*e*e;break;case yS.EaseOutBack:e=e=>2.70158*Math.pow(e-1,3)+1.70158*Math.pow(e-1,2);break;case yS.EaseInOutBack:e=e=>e<.5?Math.pow(2*e,2)*(7.189819*e-2.5949095)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+3.5949095)+2)/2;break;case yS.EaseInElastic:e=e=>0===e?0:1===e?1:-Math.pow(2,10*e-10)*Math.sin(6.283/3*(10*e-10.75));break;case yS.EaseOutElastic:e=e=>0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(6.283/3*(10*e-.75))+1;break;case yS.EaseInOutElastic:e=e=>0===e?0:1==e?1:e<.5?-Math.pow(2,20*e-10)*Math.sin(6.283/4.5*(20*e-11.125))/2:Math.pow(2,-20*e+10)*Math.sin(6.283/4.5*(20*e-11.125))/2+1}return this.output._storedFunction=t=>{const i=this.input.getConnectedValue(t);switch(this.input.type){case dS.Float:return e(i);case dS.Vector2:return new de(e(i.x),e(i.y));case dS.Vector3:return new _e(e(i.x),e(i.y),e(i.z));case dS.Vector4:return new pe(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e){super._deserialize(e),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.GeometryCurveBlockTypes.${yS[this.type]};\n`}}Ze([Cl("Type",ul.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"EaseInSine",value:yS.EaseInSine},{label:"EaseOutSine",value:yS.EaseOutSine},{label:"EaseInOutSine",value:yS.EaseInOutSine},{label:"EaseInQuad",value:yS.EaseInQuad},{label:"EaseOutQuad",value:yS.EaseOutQuad},{label:"EaseInOutQuad",value:yS.EaseInOutQuad},{label:"EaseInCubic",value:yS.EaseInCubic},{label:"EaseOutCubic",value:yS.EaseOutCubic},{label:"EaseInOutCubic",value:yS.EaseInOutCubic},{label:"EaseInQuart",value:yS.EaseInQuart},{label:"EaseOutQuart",value:yS.EaseOutQuart},{label:"EaseInOutQuart",value:yS.EaseInOutQuart},{label:"EaseInQuint",value:yS.EaseInQuint},{label:"EaseOutQuint",value:yS.EaseOutQuint},{label:"EaseInOutQuint",value:yS.EaseInOutQuint},{label:"EaseInExpo",value:yS.EaseInExpo},{label:"EaseOutExpo",value:yS.EaseOutExpo},{label:"EaseInOutExpo",value:yS.EaseInOutExpo},{label:"EaseInCirc",value:yS.EaseInCirc},{label:"EaseOutCirc",value:yS.EaseOutCirc},{label:"EaseInOutCirc",value:yS.EaseInOutCirc},{label:"EaseInBack",value:yS.EaseInBack},{label:"EaseOutBack",value:yS.EaseOutBack},{label:"EaseInOutBack",value:yS.EaseInOutBack},{label:"EaseInElastic",value:yS.EaseInElastic},{label:"EaseOutElastic",value:yS.EaseOutElastic},{label:"EaseInOutElastic",value:yS.EaseInOutElastic}]})],JC.prototype,"type",void 0),z("BABYLON.GeometryCurveBlock",JC);class eE extends kS{constructor(e){super(e),this.registerInput("color",dS.Vector3),this.registerInput("level",dS.Float,!0,0),this.registerOutput("output",dS.Vector3)}getClassName(){return"GeometryDesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.color.isConnected?(this.output._storedFunction=e=>{const t=this.color.getConnectedValue(e),i=this.level.getConnectedValue(e),s=.5*(Math.min(t.x,t.y,t.z)+Math.max(t.x,t.y,t.z));return new _e(t.x*(1-i)+s*i,t.y*(1-i)+s*i,t.z*(1-i)+s*i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}z("BABYLON.GeometryDesaturateBlock",eE);class tE extends kS{constructor(e){super(e),this.registerInput("value",dS.AutoDetect),this.registerInput("steps",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[1].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(dS.Float)}getClassName(){return"GeometryPosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected&&this.steps.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.steps.getConnectedValue(e);let s=i;if(this.steps.type===dS.Float)switch(this.value.type){case dS.Vector2:s=new de(i,i);break;case dS.Vector3:s=new _e(i,i,i);break;case dS.Vector4:s=new pe(i,i,i,i)}switch(this.value.type){case dS.Vector2:return new de(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y));case dS.Vector3:return new _e(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z));case dS.Vector4:return new pe(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z),t.w/(1/s.w)*(1/s.w));default:return Math.floor(t/(1/i)*(1/i))}},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}z("BABYLON.GeometryPosterizeBlock",tE);class iE extends kS{constructor(e){super(e),this.registerInput("value",dS.AutoDetect),this.registerInput("reference",dS.AutoDetect),this.registerInput("distance",dS.Float),this.registerInput("replacement",dS.AutoDetect),this.registerOutput("output",dS.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(dS.Float),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[1].excludedConnectionPointTypes.push(dS.Float),this._inputs[1].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[3].excludedConnectionPointTypes.push(dS.Float),this._inputs[3].excludedConnectionPointTypes.push(dS.Matrix)}getClassName(){return"GeometryReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected&&this.reference.isConnected&&this.distance.isConnected&&this.replacement.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.reference.getConnectedValue(e),s=this.distance.getConnectedValue(e),r=this.replacement.getConnectedValue(e);return t.subtract(i).length(){const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.subtract(i).length()},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}z("BABYLON.GeometryDistanceBlock",sE);class rE extends kS{constructor(e){super(e),this.registerInput("left",dS.AutoDetect),this.registerInput("right",dS.AutoDetect),this.registerOutput("output",dS.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(dS.Int),this._inputs[0].excludedConnectionPointTypes.push(dS.Float),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix),this._inputs[1].excludedConnectionPointTypes.push(dS.Float),this._inputs[1].excludedConnectionPointTypes.push(dS.Matrix)}getClassName(){return"GeometryDotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.dot(i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}z("BABYLON.GeometryDotBlock",rE);class nE extends kS{constructor(e){super(e),this.registerInput("value",dS.AutoDetect),this.registerOutput("output",dS.Float),this._inputs[0].excludedConnectionPointTypes.push(dS.Int),this._inputs[0].excludedConnectionPointTypes.push(dS.Float),this._inputs[0].excludedConnectionPointTypes.push(dS.Matrix)}getClassName(){return"GeometryLengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected?(this.output._storedFunction=e=>this.value.getConnectedValue(e).length(),this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}z("BABYLON.GeometryLengthBlock",nE);class oE extends kS{constructor(e){super(e),this.registerInput("input",dS.Vector2),this.registerInput("angle",dS.Float),this.registerOutput("output",dS.Vector2)}getClassName(){return"GeometryRotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.angle.isConnected&&this.input.isConnected?(this.output._storedFunction=e=>{const t=this.input.getConnectedValue(e),i=this.angle.getConnectedValue(e);return new de(Math.cos(i)*t.x-Math.sin(i)*t.y,Math.sin(i)*t.x+Math.cos(i)*t.y)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}z("BABYLON.GeometryRotate2dBlock",oE);class aE extends ha{get covariancesATexture(){return this._covariancesATexture}get covariancesBTexture(){return this._covariancesBTexture}get centersTexture(){return this._centersTexture}get colorsTexture(){return this._colorsTexture}constructor(e,t=null,i=null){super(e,i),this._vertexCount=0,this._worker=null,this._frameIdLastUpdate=-1,this._modelViewMatrix=me.Identity(),this._material=null,this._canPostToWorker=!0,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null;const s=new Wn;s.positions=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],s.indices=[0,1,2,0,2,3],s.applyToMesh(this),this.subMeshes=[],new Gn(0,0,4,0,6,this),this.doNotSyncBoundingInfo=!0,this.setEnabled(!1),this._lastProj=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t&&this.loadFileAsync(t)}getClassName(){return"GaussianSplattingMesh"}getTotalVertices(){return this._vertexCount}render(e,t,i){this.material||(this._material=new Vy(this.name+"_material",this._scene),this.material=this._material);const s=this.getScene().getFrameId();if(s!==this._frameIdLastUpdate&&this._worker&&this._scene.activeCamera&&this._canPostToWorker){this.getWorldMatrix().multiplyToRef(this._scene.activeCamera.getViewMatrix(),this._modelViewMatrix);const e=this._lastProj[2]*this._modelViewMatrix.m[2]+this._lastProj[6]*this._modelViewMatrix.m[6]+this._lastProj[10]*this._modelViewMatrix.m[10];Math.abs(e-1)>=.01&&(this._frameIdLastUpdate=s,this._canPostToWorker=!1,this._lastProj=this._modelViewMatrix.m.slice(0),this._worker.postMessage({view:this._modelViewMatrix.m,depthMix:this._depthMix,useRightHandedSystem:this._scene.useRightHandedSystem},[this._depthMix.buffer]))}return super.render(e,t,i)}static ConvertPLYToSplat(e){const t=new Uint8Array(e),i=(new TextDecoder).decode(t.slice(0,10240)),s=i.indexOf("end_header\n");if(s<0||!i)return e;const r=parseInt(/element vertex (\d+)\n/.exec(i)[1]);let n=0;const o={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1},a=[],l=i.slice(0,s).split("\n").filter((e=>e.startsWith("property ")));for(const e of l){const[,t,i]=e.split(" ");if(a.push({name:i,type:t,offset:n}),!o[t])return Ne.Error(`Unsupported property type: ${t}. Are you sure it's a valid Gaussian Splatting file?`),new ArrayBuffer(0);n+=o[t]}const h=.28209479177387814,c=new DataView(e,s+11),u=new ArrayBuffer(32*r),d=new fe;for(let e=0;e{this._loadData(aE.ConvertPLYToSplat(e))}))}dispose(e){this._covariancesATexture?.dispose(),this._covariancesBTexture?.dispose(),this._centersTexture?.dispose(),this._colorsTexture?.dispose(),this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._material?.dispose(!1,!0),this._material=null,this._worker?.terminate(),this._worker=null,super.dispose(e)}_loadData(e){if(!e.byteLength)return;const t=new Uint8Array(e),i=new Float32Array(t.buffer),s=t.length/32;this._vertexCount=s;const r=this._getTextureSize(s),n=r.x*r.y,o=new Float32Array(3*n),a=new Float32Array(3*n),l=new Float32Array(3*n),h=ve.Matrix[0],c=ve.Matrix[1],u=ve.Quaternion[0],d=new _e(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),_=new _e(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let e=0;enew Oa(e,t,i,s,this._scene,!1,!1,2,1),g=e=>{const t=e.length/3,i=new Float32Array(4*t);for(let s=0;s{this._depthMix=e.data.depthMix;const t=new Uint32Array(e.data.depthMix.buffer);for(let e=0;ei&&(Ne.Error("GaussianSplatting texture size: ("+i+", "+s+"), maxTextureSize: "+i),s=i),new de(i,s)}}aE._CreateWorker=function(e){let t,i,s,r,n=0;e.onmessage=o=>{if(o.data.positions)t=o.data.positions,n=o.data.vertexCount;else{const a=o.data.view;if(!t||!a)throw new Error("positions or view is not defined!");i=o.data.depthMix,s=new Uint32Array(i.buffer),r=new Float32Array(i.buffer);for(let e=0;e{this.update(.001*s.getEngine().getDeltaTime()*e.timeFactor)}))}addAgent(e,t,i){const s=new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams;s.radius=t.radius,s.height=t.height,s.maxAcceleration=t.maxAcceleration,s.maxSpeed=t.maxSpeed,s.collisionQueryRange=t.collisionQueryRange,s.pathOptimizationRange=t.pathOptimizationRange,s.separationWeight=t.separationWeight,s.updateFlags=7,s.obstacleAvoidanceType=0,s.queryFilterType=0,s.userData=0;const r=this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(e.x,e.y,e.z),s);return this.transforms.push(i),this.agents.push(r),this.reachRadii.push(t.reachRadius?t.reachRadius:t.radius),this._agentDestinationArmed.push(!1),this._agentDestination.push(new _e(0,0,0)),r}getAgentPosition(e){const t=this.recastCrowd.getAgentPosition(e);return new _e(t.x,t.y,t.z)}getAgentPositionToRef(e,t){const i=this.recastCrowd.getAgentPosition(e);t.set(i.x,i.y,i.z)}getAgentVelocity(e){const t=this.recastCrowd.getAgentVelocity(e);return new _e(t.x,t.y,t.z)}getAgentVelocityToRef(e,t){const i=this.recastCrowd.getAgentVelocity(e);t.set(i.x,i.y,i.z)}getAgentNextTargetPath(e){const t=this.recastCrowd.getAgentNextTargetPath(e);return new _e(t.x,t.y,t.z)}getAgentNextTargetPathToRef(e,t){const i=this.recastCrowd.getAgentNextTargetPath(e);t.set(i.x,i.y,i.z)}getAgentState(e){return this.recastCrowd.getAgentState(e)}overOffmeshConnection(e){return this.recastCrowd.overOffmeshConnection(e)}agentGoto(e,t){this.recastCrowd.agentGoto(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z));const i=this.agents.indexOf(e);i>-1&&(this._agentDestinationArmed[i]=!0,this._agentDestination[i].set(t.x,t.y,t.z))}agentTeleport(e,t){this.recastCrowd.agentTeleport(e,new this.bjsRECASTPlugin.bjsRECAST.Vec3(t.x,t.y,t.z))}updateAgentParameters(e,t){const i=this.recastCrowd.getAgentParameters(e);void 0!==t.radius&&(i.radius=t.radius),void 0!==t.height&&(i.height=t.height),void 0!==t.maxAcceleration&&(i.maxAcceleration=t.maxAcceleration),void 0!==t.maxSpeed&&(i.maxSpeed=t.maxSpeed),void 0!==t.collisionQueryRange&&(i.collisionQueryRange=t.collisionQueryRange),void 0!==t.pathOptimizationRange&&(i.pathOptimizationRange=t.pathOptimizationRange),void 0!==t.separationWeight&&(i.separationWeight=t.separationWeight),this.recastCrowd.setAgentParameters(e,i)}removeAgent(e){this.recastCrowd.removeAgent(e);const t=this.agents.indexOf(e);t>-1&&(this.agents.splice(t,1),this.transforms.splice(t,1),this.reachRadii.splice(t,1),this._agentDestinationArmed.splice(t,1),this._agentDestination.splice(t,1))}getAgents(){return this.agents}update(e){if(this.bjsRECASTPlugin.navMesh.update(),e<=J)return;const t=this.bjsRECASTPlugin.getTimeStep(),i=this.bjsRECASTPlugin.getMaximumSubStepCount();if(t<=J)this.recastCrowd.update(e);else{let s=Math.floor(e/t);i&&s>i&&(s=i),s<1&&(s=1);const r=e/s;for(let e=0;eo&&i.ynew cE(e,t,i);class cE{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=cE._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,cE.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,Ds.SetImmediate((()=>{t(!0)}))):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){const t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){const e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`};let s=!1,r=i();const n=new Pt;navigator.onLine&&(s=!0,r=r+(null==r.match(/\?/)?"?":"&")+Date.now()),n.open("GET",r),n.addEventListener("load",(()=>{if(200===n.status||cE._ValidateXHRData(n,1))try{const t=JSON.parse(n.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&cE._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){t()}else t()}),!1),n.addEventListener("error",(()=>{if(s){s=!1;const e=i();n.open("GET",e),n.send()}else t()}),!1);try{n.send()}catch(t){Ne.Error("Error on XHR send request."),e(!1)}}open(e,t){const i=()=>{this._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline))if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;const t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{i()},t.onblocked=()=>{Ne.Error("IDB request blocked. Please reload the page."),i()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){Ne.Error("Error while creating object stores. Exception: "+e.message),i()}}}else this._isSupported=!1,t&&t()}loadImage(e,t){const i=cE._ReturnFullUrlLocation(e),s=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?s():this._loadImageFromDBAsync(i,t,s)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let s;const r=this._db.transaction(["textures"]);r.onabort=()=>{t.src=e},r.oncomplete=()=>{let r;s&&"function"==typeof URL?(r=URL.createObjectURL(s.data),t.onerror=()=>{Ne.Error("Error loading image from blob URL: "+r+" switching back to web url: "+e),t.src=e},t.src=r):i()};const n=r.objectStore("textures").get(e);n.onsuccess=e=>{s=e.target.result},n.onerror=()=>{Ne.Error("Error loading texture "+e+" from DB."),t.src=e}}else Ne.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){const s=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(cE._IsUASupportingBlobStorage){const r=new Pt;r.open("GET",e),r.responseType="blob",r.addEventListener("load",(()=>{if(200===r.status&&this._db){i=r.response;const n=this._db.transaction(["textures"],"readwrite");n.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}s()},n.oncomplete=()=>{s()};const o={textureUrl:e,data:i};try{const e=n.objectStore("textures").put(o);e.onsuccess=()=>{},e.onerror=()=>{s()}}catch(i){25===i.code&&(cE._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e}),!1),r.addEventListener("error",(()=>{Ne.Error("Error in XHR request in BABYLON.Database."),t.src=e}),!1),r.send()}else t.src=e}else Ne.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,(()=>{this._saveVersionIntoDBAsync(e,t)}))}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let s;try{const r=this._db.transaction(["versions"]);r.oncomplete=()=>{s?this._manifestVersionFound!==s.data?(this._mustUpdateRessources=!0,i()):t(s.data):(this._mustUpdateRessources=!0,i())},r.onabort=()=>{t(-1)};const n=r.objectStore("versions").get(e);n.onsuccess=e=>{s=e.target.result},n.onerror=()=>{Ne.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){Ne.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else Ne.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)}_saveVersionIntoDBAsync(e,t){if(this._isSupported&&!this._hasReachedQuota&&this._db)try{const i=this._db.transaction(["versions"],"readwrite");i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const s={sceneUrl:e,data:this._manifestVersionFound},r=i.objectStore("versions").put(s);r.onsuccess=()=>{},r.onerror=()=>{Ne.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){Ne.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,s,r){const n=cE._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(n,t,i,r,s)};this._checkVersionFromDB(n,(e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(n,t,i,r,s):this._loadFileAsync(n,t,o):s&&s()}))}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let s,r;s=-1!==e.indexOf(".babylon")?"scenes":"textures";const n=this._db.transaction([s]);n.oncomplete=()=>{r?t(r.data):i()},n.onabort=()=>{i()};const o=n.objectStore(s).get(e);o.onsuccess=e=>{r=e.target.result},o.onerror=()=>{Ne.Error("Error loading file "+e+" from DB."),i()}}else Ne.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,s,r){if(this._isSupported){let n;n=-1!==e.indexOf(".babylon")?"scenes":"textures";const o=new Pt;let a;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),s&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",(()=>{if(200===o.status||o.status<400&&cE._ValidateXHRData(o,s?6:1))if(a=s?o.response:o.responseText,!this._hasReachedQuota&&this._db){const i=this._db.transaction([n],"readwrite");let s;i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(a)},i.oncomplete=()=>{t(a)},s="scenes"===n?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{const e=i.objectStore(n).put(s);e.onsuccess=()=>{},e.onerror=()=>{Ne.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(a)}}else t(a);else o.status>=400&&r?r(o):t()}),!1),o.addEventListener("error",(()=>{Ne.Error("error on XHR request."),r&&r()}),!1),o.send()}else Ne.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),r&&r()}static _ValidateXHRData(e,t=7){try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){const i=Jx(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){const t=new Uint8Array(e.response,0,3);return 68===t[0]&&68===t[1]&&83===t[2]}}catch(e){}return!1}}cE._IsUASupportingBlobStorage=!0,cE.IDBStorageEnabled=!1,cE._ParseURL=e=>{document.createElement("a").href=e;const t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},cE._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?cE._ParseURL(window.location.href)+e:e;class uE{constructor(){this.direction1=new _e(0,1,0),this.direction2=new _e(0,1,0),this.minEmitBox=new _e(-.5,-.5,-.5),this.maxEmitBox=new _e(.5,.5,.5)}startDirectionFunction(e,t,i,s){const r=oe(this.direction1.x,this.direction2.x),n=oe(this.direction1.y,this.direction2.y),o=oe(this.direction1.z,this.direction2.z);if(s)return t.x=r,t.y=n,void(t.z=o);_e.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){const r=oe(this.minEmitBox.x,this.maxEmitBox.x),n=oe(this.minEmitBox.y,this.maxEmitBox.y),o=oe(this.minEmitBox.z,this.maxEmitBox.z);if(s)return t.x=r,t.y=n,void(t.z=o);_e.TransformCoordinatesFromFloatsToRef(r,n,o,e,t)}clone(){const e=new uE;return Ye.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){_e.FromArrayToRef(e.direction1,0,this.direction1),_e.FromArrayToRef(e.direction2,0,this.direction2),_e.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),_e.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class dE{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,s){s?ve.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),ve.Vector3[0]).normalize();const r=be.RandomRange(0,this.directionRandomizer),n=be.RandomRange(0,this.directionRandomizer),o=be.RandomRange(0,this.directionRandomizer);t.x=ve.Vector3[0].x+r,t.y=ve.Vector3[0].y+n,t.z=ve.Vector3[0].z+o,t.normalize()}startPositionFunction(e,t,i,s){const r=be.RandomRange(0,2*Math.PI);let n;this.emitFromSpawnPointOnly?n=1e-4:(n=be.RandomRange(0,this.heightRange),n=1-n*n);let o=this._radius-be.RandomRange(0,this._radius*this.radiusRange);o*=n;const a=o*Math.sin(r),l=o*Math.cos(r),h=n*this._height;if(s)return t.x=a,t.y=h,void(t.z=l);_e.TransformCoordinatesFromFloatsToRef(a,h,l,e,t)}clone(){const e=new dE(this._radius,this._angle,this.directionRandomizer);return Ye.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e}getClassName(){return"ConeParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}}class _E{constructor(e=1,t=1,i=1,s=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=s,this._tempVector=_e.Zero()}startDirectionFunction(e,t,i,s,r){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),_e.TransformNormalToRef(this._tempVector,r,this._tempVector);const n=be.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let o=Math.atan2(this._tempVector.x,this._tempVector.z);o+=be.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=n,this._tempVector.x=Math.sin(o),this._tempVector.z=Math.cos(o),this._tempVector.normalize(),s?t.copyFrom(this._tempVector):_e.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,s){const r=be.RandomRange(-this.height/2,this.height/2),n=be.RandomRange(0,2*Math.PI),o=be.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),a=Math.sqrt(o)*this.radius,l=a*Math.cos(n),h=a*Math.sin(n);s?t.copyFromFloats(l,r,h):_e.TransformCoordinatesFromFloatsToRef(l,r,h,e,t)}clone(){const e=new _E(this.radius,this.directionRandomizer);return Ye.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class pE extends _E{constructor(e=1,t=1,i=1,s=new _e(0,1,0),r=new _e(0,1,0)){super(e,t,i),this.direction1=s,this.direction2=r}startDirectionFunction(e,t,i,s){const r=be.RandomRange(this.direction1.x,this.direction2.x),n=be.RandomRange(this.direction1.y,this.direction2.y),o=be.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):_e.TransformNormalFromFloatsToRef(r,n,o,e,t)}clone(){const e=new pE(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return Ye.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),_e.FromArrayToRef(e.direction1,0,this.direction1),_e.FromArrayToRef(e.direction2,0,this.direction2)}}class fE{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=be.RandomRange(0,this.directionRandomizer),o=be.RandomRange(0,this.directionRandomizer),a=be.RandomRange(0,this.directionRandomizer);r.x+=n,r.y+=o,r.z+=a,r.normalize(),s?t.copyFrom(r):_e.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-be.RandomRange(0,this.radius*this.radiusRange),n=be.RandomRange(0,1),o=be.RandomRange(0,2*Math.PI),a=Math.acos(2*n-1),l=r*Math.cos(o)*Math.sin(a),h=r*Math.cos(a),c=r*Math.sin(o)*Math.sin(a);s?t.copyFromFloats(l,Math.abs(h),c):_e.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),c,e,t)}clone(){const e=new fE(this.radius,this.directionRandomizer);return Ye.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class mE{constructor(){this.direction1=new _e(0,1,0),this.direction2=new _e(0,1,0)}startDirectionFunction(e,t,i,s){const r=be.RandomRange(this.direction1.x,this.direction2.x),n=be.RandomRange(this.direction1.y,this.direction2.y),o=be.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):_e.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){s?t.copyFromFloats(0,0,0):_e.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new mE;return Ye.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){_e.FromArrayToRef(e.direction1,0,this.direction1),_e.FromArrayToRef(e.direction2,0,this.direction2)}}class gE{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=be.RandomRange(0,this.directionRandomizer),o=be.RandomRange(0,this.directionRandomizer),a=be.RandomRange(0,this.directionRandomizer);r.x+=n,r.y+=o,r.z+=a,r.normalize(),s?t.copyFrom(r):_e.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-be.RandomRange(0,this.radius*this.radiusRange),n=be.RandomRange(0,1),o=be.RandomRange(0,2*Math.PI),a=Math.acos(2*n-1),l=r*Math.cos(o)*Math.sin(a),h=r*Math.cos(a),c=r*Math.sin(o)*Math.sin(a);s?t.copyFromFloats(l,h,c):_e.TransformCoordinatesFromFloatsToRef(l,h,c,e,t)}clone(){const e=new gE(this.radius,this.directionRandomizer);return Ye.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class vE extends gE{constructor(e=1,t=new _e(0,1,0),i=new _e(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=be.RandomRange(this.direction1.x,this.direction2.x),s=be.RandomRange(this.direction1.y,this.direction2.y),r=be.RandomRange(this.direction1.z,this.direction2.z);_e.TransformNormalFromFloatsToRef(i,s,r,e,t)}clone(){const e=new vE(this.radius,this.direction1,this.direction2);return Ye.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class xE{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,s){const r=ve.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,r);const e=ve.Vector3[1];r.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,r)}else r.set(0,0,0);s?t.copyFrom(r):_e.TransformNormalToRef(r,e,t)}startPositionFunction(e,t,i,s){const r=ve.Vector3[0];this.particlePositionGenerator?this.particlePositionGenerator(-1,i,r):r.set(0,0,0),s?t.copyFrom(r):_e.TransformCoordinatesToRef(r,e,t)}clone(){const e=new xE;return Ye.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.particlePositionGenerator=this.particlePositionGenerator,e.particleDestinationGenerator=this.particleDestinationGenerator,e}parse(e){e.particlePositionGenerator&&(this.particlePositionGenerator=e.particlePositionGenerator),e.particleDestinationGenerator&&(this.particleDestinationGenerator=e.particleDestinationGenerator)}}class bE{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(er.PositionKind),this._normals=e.getVerticesData(er.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=_e.Zero(),this._mesh=null,this.direction1=new _e(0,1,0),this.direction2=new _e(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,s){if(this.useMeshNormalsForDirection&&this._normals)return void _e.TransformNormalToRef(this._storedNormal,e,t);const r=be.RandomRange(this.direction1.x,this.direction2.x),n=be.RandomRange(this.direction1.y,this.direction2.y),o=be.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):_e.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){if(!this._indices||!this._positions)return;const r=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),o=Math.random()*(1-n),a=1-n-o,l=this._indices[r],h=this._indices[r+1],c=this._indices[r+2],u=ve.Vector3[0],d=ve.Vector3[1],_=ve.Vector3[2],p=ve.Vector3[3];_e.FromArrayToRef(this._positions,3*l,u),_e.FromArrayToRef(this._positions,3*h,d),_e.FromArrayToRef(this._positions,3*c,_),p.x=n*u.x+o*d.x+a*_.x,p.y=n*u.y+o*d.y+a*_.y,p.z=n*u.z+o*d.z+a*_.z,s?t.copyFromFloats(p.x,p.y,p.z):_e.TransformCoordinatesFromFloatsToRef(p.x,p.y,p.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(_e.FromArrayToRef(this._normals,3*l,u),_e.FromArrayToRef(this._normals,3*h,d),_e.FromArrayToRef(this._normals,3*c,_),this._storedNormal.x=n*u.x+o*d.x+a*_.x,this._storedNormal.y=n*u.y+o*d.y+a*_.y,this._storedNormal.z=n*u.z+o*d.z+a*_.z)}clone(){const e=new bE(this.mesh);return Ye.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.meshId=this.mesh?.id,e.useMeshNormalsForDirection=this.useMeshNormalsForDirection,e}parse(e,t){_e.FromArrayToRef(e.direction1,0,this.direction1),_e.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class TE{_isUbo(e){return void 0!==e.addUniform}constructor(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}}Bi.ShadersStore.gpuUpdateParticlesPixelShader="#version 300 es\nvoid main() {discard;}\n";Bi.ShadersStore.gpuUpdateParticlesVertexShader="#version 300 es\n#define PI 3.14159\nuniform float currentCount;uniform float timeDelta;uniform float stopFactor;\n#ifndef LOCAL\nuniform mat4 emitterWM;\n#endif\nuniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;uniform vec4 color2;\n#endif\nuniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;uniform float radiusRange;uniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;uniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;uniform float height;uniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer;\n#endif\nin vec3 position;\n#ifdef CUSTOMEMITTER\nin vec3 initialPosition;\n#endif\nin float age;in float life;in vec4 seed;in vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;in vec3 noiseCoordinates2;\n#endif\nout vec3 outPosition;\n#ifdef CUSTOMEMITTER\nout vec3 outInitialPosition;\n#endif\nout float outAge;out float outLife;out vec4 outSeed;out vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;uniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec4 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;}\nvec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));}\nvoid main() {float newAge=age+timeDelta; \nif (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed;\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(direction1+(direction2-direction1)*randoms3);\n#else\nnewDirection=normalize(newPosition+directionRandomizer*randoms3);\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\nangle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.0001;\n#else\nfloat h=randoms2.y*height.y;h=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); \nif (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); }\n#elif defined(CUSTOMEMITTER)\nnewPosition=initialPosition;outInitialPosition=initialPosition;\n#else \nnewPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\n#ifdef LOCAL\noutPosition=newPosition;\n#else\noutPosition=(emitterWM*vec4(newPosition,1.)).xyz;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#ifndef BILLBOARD \noutInitialDirection=direction;\n#endif\n#else\n#ifdef LOCAL\nvec3 initial=newDirection;\n#else \nvec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;\n#endif\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#if defined(CUSTOMEMITTER)\noutPosition=position+(direction-position)*ageGradient; \noutInitialPosition=initialPosition;\n#else\noutPosition=position+direction*directionScale;\n#endif\noutLife=life;outSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#else\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;float dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset;\n#else\nfloat cellStartOffset=0.;\n#endif \nfloat ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);}\nelse {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);}\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}}";class yE{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){return this._updateEffect?.isReady()??!1}createUpdateBuffer(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof xE&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new $i("gpuUpdateParticles",this._updateEffectOptions,this._engine),new TE(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){const e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);const s=this._engine;s.bindTransformFeedbackBuffer(t.getBuffer()),s.setRasterizerState(!1),s.beginTransformFeedback(!0),s.drawArraysType(3,0,i),s.endTransformFeedback(),s.setRasterizerState(!0),s.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;ee)return void i(t[0],t[0],1);for(let s=0;s=r.gradient&&e<=n.gradient)return void i(r,n,(e-r.gradient)/(n.gradient-r.gradient))}const s=t.length-1;i(t[s],t[s],1)}}class IE{constructor(e){this.particleSystem=e,this.position=_e.Zero(),this.direction=_e.Zero(),this.color=new Ae(0,0,0,0),this.colorStep=new Ae(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new de(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new Ae(0,0,0,0),this._currentColor2=new Ae(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=IE._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===t?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);const i=this._initialEndSpriteCellID-this._initialStartSpriteCellID+1;let s;s=this._initialSpriteCellLoop?le(e*t%this.lifeTime/this.lifeTime):le(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+s*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const e=ve.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,ve.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(ve.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach((e=>{this._inheritParticleInfoToSubEmitter(e)}))}_reset(){this.age=0,this.id=IE._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new pe(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}}IE._Count=0;Bi.ShadersStore.particlesPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler;\n#include\n#include\n#include\n#include\n#include\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;uniform sampler2D rampSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n#include\n#include(color,baseColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.particlesVertexShader="attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos; \n#endif\nvarying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#include\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvec3 row1=direction;\n#else\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nmat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size;\n#ifdef BILLBOARD\nvec3 rotatedCorner;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\ngl_Position=projection*vec4(viewPos,1.0);\n#else\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0);\n#endif\nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";class RE extends Yl{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Un(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new K),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,s=null,r=!1,n=.01){super(e),this._emitterInverseWorldMatrix=me.Identity(),this._inheritedVelocityOffset=new _e,this.onDisposeObservable=new K,this.onStoppedObservable=new K,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new Ae(0,0,0,0),this._colorDiff=new Ae(0,0,0,0),this._scaledDirection=_e.Zero(),this._scaledGravity=_e.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this._emitFromParticle=e=>{},this.recycleParticle=e=>{const t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;return 0!==this._stockParticles.length?(e=this._stockParticles.pop(),e._reset()):e=new IE(this),this._prepareParticle(e),e},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=r,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=me.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||re.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new Un(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new uE;let o=null;this.updateFunction=e=>{let t=null;this.noiseTexture&&(t=this.noiseTexture.getSize(),this.noiseTexture.getContent()?.then((e=>{o=e})));const i=e===this._particles;for(let s=0;sr.lifeTime){const e=r.age-a;n=(r.lifeTime-a)*n/e,r.age=r.lifeTime}const l=r.age/r.lifeTime;this._colorGradients&&this._colorGradients.length>0?PE.GetCurrentGradient(l,this._colorGradients,((e,t,i)=>{e!==r._currentColorGradient&&(r._currentColor1.copyFrom(r._currentColor2),t.getColorToRef(r._currentColor2),r._currentColorGradient=e),Ae.LerpToRef(r._currentColor1,r._currentColor2,i,r.color)})):(r.colorStep.scaleToRef(n,this._scaledColorStep),r.color.addInPlace(this._scaledColorStep),r.color.a<0&&(r.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&PE.GetCurrentGradient(l,this._angularSpeedGradients,((e,t,i)=>{e!==r._currentAngularSpeedGradient&&(r._currentAngularSpeed1=r._currentAngularSpeed2,r._currentAngularSpeed2=t.getFactor(),r._currentAngularSpeedGradient=e),r.angularSpeed=ae(r._currentAngularSpeed1,r._currentAngularSpeed2,i)})),r.angle+=r.angularSpeed*n;let h=n;if(this._velocityGradients&&this._velocityGradients.length>0&&PE.GetCurrentGradient(l,this._velocityGradients,((e,t,i)=>{e!==r._currentVelocityGradient&&(r._currentVelocity1=r._currentVelocity2,r._currentVelocity2=t.getFactor(),r._currentVelocityGradient=e),h*=ae(r._currentVelocity1,r._currentVelocity2,i)})),r.direction.scaleToRef(h,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&PE.GetCurrentGradient(l,this._limitVelocityGradients,((e,t,i)=>{e!==r._currentLimitVelocityGradient&&(r._currentLimitVelocity1=r._currentLimitVelocity2,r._currentLimitVelocity2=t.getFactor(),r._currentLimitVelocityGradient=e);const s=ae(r._currentLimitVelocity1,r._currentLimitVelocity2,i);r.direction.length()>s&&r.direction.scaleInPlace(this.limitVelocityDamping)})),this._dragGradients&&this._dragGradients.length>0&&PE.GetCurrentGradient(l,this._dragGradients,((e,t,i)=>{e!==r._currentDragGradient&&(r._currentDrag1=r._currentDrag2,r._currentDrag2=t.getFactor(),r._currentDragGradient=e);const s=ae(r._currentDrag1,r._currentDrag2,i);this._scaledDirection.scaleInPlace(1-s)})),this.isLocal&&r._localPosition?(r._localPosition.addInPlace(this._scaledDirection),_e.TransformCoordinatesToRef(r._localPosition,this._emitterWorldMatrix,r.position)):r.position.addInPlace(this._scaledDirection),o&&t&&r._randomNoiseCoordinates1){const e=this._fetchR(r._randomNoiseCoordinates1.x,r._randomNoiseCoordinates1.y,t.width,t.height,o),i=this._fetchR(r._randomNoiseCoordinates1.z,r._randomNoiseCoordinates2.x,t.width,t.height,o),s=this._fetchR(r._randomNoiseCoordinates2.y,r._randomNoiseCoordinates2.z,t.width,t.height,o),a=ve.Vector3[0],l=ve.Vector3[1];a.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*i-1)*this.noiseStrength.y,(2*s-1)*this.noiseStrength.z),a.scaleToRef(n,l),r.direction.addInPlace(l)}this.gravity.scaleToRef(n,this._scaledGravity),r.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&PE.GetCurrentGradient(l,this._sizeGradients,((e,t,i)=>{e!==r._currentSizeGradient&&(r._currentSize1=r._currentSize2,r._currentSize2=t.getFactor(),r._currentSizeGradient=e),r.size=ae(r._currentSize1,r._currentSize2,i)})),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&PE.GetCurrentGradient(l,this._colorRemapGradients,((e,t,i)=>{const s=ae(e.factor1,t.factor1,i),n=ae(e.factor2,t.factor2,i);r.remapData.x=s,r.remapData.y=n-s})),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&PE.GetCurrentGradient(l,this._alphaRemapGradients,((e,t,i)=>{const s=ae(e.factor1,t.factor1,i),n=ae(e.factor2,t.factor2,i);r.remapData.z=s,r.remapData.w=n-s}))),this._isAnimationSheetEnabled&&r.updateCellIndex(),r._inheritParticleInfoToSubEmitters(),r.age>=r.lifeTime&&(this._emitFromParticle(r),r._attachedSubEmitters&&(r._attachedSubEmitters.forEach((e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()})),r._attachedSubEmitters=null),this.recycleParticle(r),i&&s--)}}}serialize(e){throw new Error("Method not implemented.")}clone(e,t,i=!1){throw new Error("Method not implemented.")}_addFactorGradient(e,t,i,s){const r=new AE(t,i,s);e.push(r),e.sort(((e,t)=>e.gradientt.gradient?1:0))}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const s of e){if(s.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;const e=new Uint8Array(4*this._rawTextureWidth),t=Pe.Color3[0];for(let i=0;i{Ee.LerpToRef(s.color,r.color,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255}))}this._rampGradientsTexture=Oa.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);const i=new EE(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);const s=new CE(e,t,i);return this._colorGradients.push(s),this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(const i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(const e of this._drawWrappers)if(e)for(const t of e)t?.dispose();this._drawWrappers=[]}_fetchR(e,t,i,s,r){return r[4*(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*s%s|0)*i)]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&8!==this.billboardMode&&9!==this.billboardMode||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);const e=this._engine,t=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*t),this._vertexBuffer=new Js(e,this._vertexData,!0,t);let i=0;const s=this._vertexBuffer.createVertexBuffer(er.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[er.PositionKind]=s,i+=3;const r=this._vertexBuffer.createVertexBuffer(er.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[er.ColorKind]=r,i+=4;const n=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=n,i+=1;const o=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,i+=2,this._isAnimationSheetEnabled){const e=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,i+=1}if(!this._isBillboardBased||8===this.billboardMode||9===this.billboardMode){const e=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,i+=3}if(this._useRampGradients){const e=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,i+=4}let a;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Js(e,t,!1,2),a=this._spriteBuffer.createVertexBuffer("offset",0,2)}else a=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=a,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing)return void(this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3])));const e=[],t=[];let i=0;for(let s=0;s{this.start(0)}),e);else{if(this._started=!0,this._stopped=!1,this._actualFrame=0,this._preStart(),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){-1!==this.emitter?.getClassName().indexOf("Mesh")&&this.emitter.computeWorldMatrix(!0);const e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce((()=>{setTimeout((()=>{for(let t=0;t0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,this._postStop(e))}_postStop(e){}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,s){let r=e*this._vertexBufferSize;if(this._vertexData[r++]=t.position.x+this.worldOffset.x,this._vertexData[r++]=t.position.y+this.worldOffset.y,this._vertexData[r++]=t.position.z+this.worldOffset.z,this._vertexData[r++]=t.color.r,this._vertexData[r++]=t.color.g,this._vertexData[r++]=t.color.b,this._vertexData[r++]=t.color.a,this._vertexData[r++]=t.angle,this._vertexData[r++]=t.scale.x*t.size,this._vertexData[r++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[r++]=t.cellIndex),this._isBillboardBased)8!==this.billboardMode&&9!==this.billboardMode||(this._vertexData[r++]=t.direction.x,this._vertexData[r++]=t.direction.y,this._vertexData[r++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(_e.TransformNormalToRef(e,this._emitterWorldMatrix,ve.Vector3[0]),e=ve.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[r++]=e.x,this._vertexData[r++]=e.y,this._vertexData[r++]=e.z}else{let e=t.direction;this.isLocal&&(_e.TransformNormalToRef(e,this._emitterWorldMatrix,ve.Vector3[0]),e=ve.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[r++]=e.x,this._vertexData[r++]=e.y,this._vertexData[r++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[r++]=t.remapData.x,this._vertexData[r++]=t.remapData.y,this._vertexData[r++]=t.remapData.z,this._vertexData[r++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===s?s=this._epsilon:1===s&&(s=1-this._epsilon)),this._vertexData[r++]=i,this._vertexData[r++]=s)}_prepareParticle(e){}_update(e){if(this._alive=this._particles.length>0,this.emitter.position){const e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{const e=this.emitter;this._emitterWorldMatrix=me.Translation(e.x,e.y,e.z)}let t;this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i0){const e=le(this._actualFrame/this.targetStopDuration);PE.GetCurrentGradient(e,this._lifeTimeGradients,((i,s)=>{const r=i,n=s,o=r.getFactor(),a=n.getFactor(),l=(e-r.gradient)/(n.gradient-r.gradient);t.lifeTime=ae(o,a,l)}))}else t.lifeTime=oe(this.minLifeTime,this.maxLifeTime);const e=oe(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),_e.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=oe(this.minSize,this.maxSize),t.scale.copyFromFloats(oe(this.minScaleX,this.maxScaleX),oe(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const e=this._actualFrame/this.targetStopDuration;PE.GetCurrentGradient(e,this._startSizeGradients,((e,i,s)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);const r=ae(this._currentStartSize1,this._currentStartSize2,s);t.scale.scaleInPlace(r)}))}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=oe(this.minAngularSpeed,this.maxAngularSpeed),t.angle=oe(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),this._colorGradients&&0!==this._colorGradients.length)t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);else{const e=oe(0,1);Ae.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new pe(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new _e(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new _e(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const s=[er.PositionKind,er.ColorKind,"angle","offset","size"];return e&&s.push("cellIndex"),t||s.push("direction"),i&&s.push("remapData"),s}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["invView","view","projection","textureMask","translationPivot","eyePosition"];return mo(s),e&&s.push("particlesInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t,i=!0){if(this._scene&&(go(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&0!==this._scene.fogMode&&e.push("#define FOG")),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===Yl.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case 2:e.push("#define BILLBOARDY");break;case 8:case 9:e.push("#define BILLBOARDSTRETCHED"),9===this.billboardMode&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case 7:e.push("#define BILLBOARDMODE_ALL")}i&&this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...RE._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&8!==this.billboardMode&&9!==this.billboardMode,this._useRampGradients)),e.push(...RE._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(Us(e,this._imageProcessingConfigurationDefines),Gs(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);const s=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let r=this._drawWrappers[s];r||(r=this._drawWrappers[s]=[]);let n=r[e];n||(n=new Un(this._engine),n.drawContext&&(n.drawContext.useInstancing=this._useInstancing),r[e]=n);const o=i.join("\n");if(n.defines!==o){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("particles",e,t,i,o),o)}return n}animate(e=!1){if(!this._started)return;if(!e&&this._scene){if(!this.isReady())return;if(this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}let t;if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this.manualEmitCount>-1)t=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const t=this._actualFrame/this.targetStopDuration;PE.GetCurrentGradient(t,this._emitRateGradients,((t,i,s)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=ae(this._currentEmitRate1,this._currentEmitRate2,s)}))}t=e*this._scaledUpdateSpeed|0,this._newPartsExcess+=e*this._scaledUpdateSpeed-t}if(this._newPartsExcess>1&&(t+=0|this._newPartsExcess,this._newPartsExcess-=0|this._newPartsExcess),this._alive=!1,this._stopped?t=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(t),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){let e=0;for(let t=0;t=0&&(r.invertToRef(ve.Matrix[0]),i.setMatrix("invView",ve.Matrix[0])),void 0!==this._vertexArrayObject?this._scene?.forceWireframe?s.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,i):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,i)),this._engine.bindVertexArrayObject(this._vertexArrayObject,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?s.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBuffer:this._indexBuffer,i):s.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null,i),this.useLogarithmicDepth&&this._scene&&So(n,i,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(i),e){case Yl.BLENDMODE_ADD:s.setAlphaMode(1);break;case Yl.BLENDMODE_ONEONE:s.setAlphaMode(6);break;case Yl.BLENDMODE_STANDARD:s.setAlphaMode(2);break;case Yl.BLENDMODE_MULTIPLY:s.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(i),this._useInstancing?this._scene?.forceWireframe?s.drawElementsType(6,0,10,this._particles.length):s.drawArraysType(7,0,4,this._particles.length):this._scene?.forceWireframe?s.drawElementsType(1,0,10*this._particles.length):s.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;const e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===Yl.BLENDMODE_MULTIPLYADD?this._render(Yl.BLENDMODE_MULTIPLY)+this._render(Yl.BLENDMODE_ADD):this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}_onDispose(e=!1,t=!1){}dispose(e=!0,t=!1,i=!1){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._onDispose(t,i),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.clear(),this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}}var ME;!function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(ME||(ME={}));class OE{constructor(e){if(this.particleSystem=e,this.type=ME.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=W("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;e?e instanceof _e?e=e.clone():-1!==e.getClassName().indexOf("Mesh")&&(e=new(W("BABYLON.Mesh"))("",e.getScene()),e.isVisible=!1):e=new _e;const t=new OE(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){const t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,s=!1){throw xt("ParseParticle")}static Parse(e,t,i){const s=e.particleSystem,r=new OE(OE._ParseParticleSystem(s,t,i,!0));return r.type=e.type,r.inheritDirection=e.inheritDirection,r.inheritedVelocityAmount=e.inheritedVelocityAmount,r.particleSystem._isSubEmitter=!0,r}dispose(){this.particleSystem.dispose()}}function DE(e,t){const i=new mE;return i.direction1=e,i.direction2=t,i}function wE(e=1,t=1){return new fE(e,t)}function NE(e=1,t=1){return new gE(e,t)}function FE(e=1,t=new _e(0,1,0),i=new _e(0,1,0)){return new vE(e,t,i)}function LE(e=1,t=1,i=1,s=0){return new _E(e,t,i,s)}function BE(e=1,t=1,i=1,s=new _e(0,1,0),r=new _e(0,1,0)){return new pE(e,t,i,s,r)}function kE(e=1,t=Math.PI/4){return new dE(e,t)}class VE extends RE{constructor(){super(...arguments),this._disposeEmitterOnDispose=!1,this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;const t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach((t=>{if(t.type===ME.END){const i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}}))}}createPointEmitter(e,t){const i=DE(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=wE(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=NE(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new _e(0,1,0),i=new _e(0,1,0)){const s=FE(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=LE(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new _e(0,1,0),r=new _e(0,1,0)){const n=BE(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=kE(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new uE;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}_prepareSubEmitterInternalArray(){this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach((e=>{e instanceof VE?this._subEmitters.push([new OE(e)]):e instanceof OE?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)}))}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach((e=>{e.stop(!0)})),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;const e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_preStart(){this._prepareSubEmitterInternalArray(),this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=[])}_postStop(e){e&&this._stopSubEmitters()}_prepareParticle(e){if(this._subEmitters&&this._subEmitters.length>0){const t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach((t=>{if(t.type===ME.ATTACHED){const i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}}))}}_onDispose(e=!1,t=!1){if(this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),e&&this.particles?.forEach((e=>{if(e._attachedSubEmitters)for(let t=e._attachedSubEmitters.length-1;t>=0;t-=1)e._attachedSubEmitters[t].dispose()})),t&&this.activeSubSystems)for(let e=this.activeSubSystems.length-1;e>=0;e-=1)this.activeSubSystems[e].dispose();if(this._subEmitters&&this._subEmitters.length){for(let e=0;e0?h.shaderOptions.defines.join("\n"):"";l=o.createEffectForParticles(h.shaderPath.fragmentElement,h.shaderOptions.uniforms,h.shaderOptions.samplers,t)}const c=new VE(n,r||e.capacity,t,l,e.isAnimationSheetEnabled);if(c.customShader=h,c._rootUrl=i,e.id&&(c.id=e.id),e.subEmitters){c.subEmitters=[];for(const s of e.subEmitters){const e=[];for(const r of s)e.push(OE.Parse(r,t,i));c.subEmitters.push(e)}}return VE._Parse(e,c,t,i),e.textureMask&&(c.textureMask=Ae.FromArray(e.textureMask)),e.worldOffset&&(c.worldOffset=_e.FromArray(e.worldOffset)),e.preventAutoStart&&(c.preventAutoStart=e.preventAutoStart),s||c.preventAutoStart||c.start(),c}serialize(e=!1){const t={};if(VE._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,t.worldOffset=this.worldOffset.asArray(),this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const s=[];for(const t of i)s.push(t.serialize(e));t.subEmitters.push(s)}}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){const i=t.emitter;e.emitterId=i.id}else{const i=t.emitter;e.emitter=i.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,St.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;const s=t.getColorGradients();if(s){e.colorGradients=[];for(const t of s){const i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}}const r=t.getRampGradients();if(r){e.rampGradients=[];for(const t of r){const i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}const n=t.getColorRemapGradients();if(n){e.colorRemapGradients=[];for(const t of n){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const t of o){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}}const a=t.getSizeGradients();if(a){e.sizeGradients=[];for(const t of a){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}}const l=t.getAngularSpeedGradients();if(l){e.angularSpeedGradients=[];for(const t of l){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}}const h=t.getVelocityGradients();if(h){e.velocityGradients=[];for(const t of h){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}}const c=t.getDragGradients();if(c){e.dragGradients=[];for(const t of c){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}}const u=t.getEmitRateGradients();if(u){e.emitRateGradients=[];for(const t of u){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}}const d=t.getStartSizeGradients();if(d){e.startSizeGradients=[];for(const t of d){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}}const _=t.getLifeTimeGradients();if(_){e.lifeTimeGradients=[];for(const t of _){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}}const p=t.getLimitVelocityGradients();if(p){e.limitVelocityGradients=[];for(const t of p){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}clone(e,t,i=!1){const s={...this._customWrappers};let r=null;const n=this._engine;if(n.createEffectForParticles&&null!=this.customShader){r=this.customShader;const e=r.shaderOptions.defines.length>0?r.shaderOptions.defines.join("\n"):"",t=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,e);s[0]?s[0].effect=t:this.setCustomEffect(t,0)}const o=this.serialize(i),a=VE.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=r,a._customWrappers=s,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,this.preventAutoStart||a.start(),a}}VE.BILLBOARDMODE_Y=2,VE.BILLBOARDMODE_ALL=7,VE.BILLBOARDMODE_STRETCHED=8,VE.BILLBOARDMODE_STRETCHED_LOCAL=9,OE._ParseParticleSystem=VE.Parse;Bi.IncludesShadersStore.clipPlaneFragmentDeclaration2="#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nin float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nin float fClipDistance6;\n#endif\n";Bi.ShadersStore.gpuRenderParticlesPixelShader="precision highp float;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor;\n#include \n#include\n#include\n#include\n#include\n#include\nvoid main() {\n#include \nvec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha);\n#endif \n#include\n#include(color,gl_FragColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor);\n#endif\n#endif\n}\n";Bi.IncludesShadersStore.clipPlaneVertexDeclaration2="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;out float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;out float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;out float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;out float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;out float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;out float fClipDistance6;\n#endif\n";Bi.ShadersStore.gpuRenderParticlesVertexShader="precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset;\n#ifdef LOCAL\nuniform mat4 emitterWM;\n#endif\nattribute vec3 position;attribute float age;attribute float life;attribute vec3 size;\n#ifndef BILLBOARD\nattribute vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\nattribute float angle;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\nattribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#include\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;attribute vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture2D(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x;\n#ifdef BILLBOARD\nvec4 rotatedCorner;rotatedCorner.w=0.;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;\n#ifdef LOCAL\nvec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner;\n#else\nvec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner;\n#endif\nvPositionW=(invView*viewPosition).xyz;\n#endif\n#else\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0);\n#endif\ngl_Position=projection*viewPosition;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#include\n}";class UE extends Yl{static get IsSupported(){if(!re.LastCreatedEngine)return!1;const e=re.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]),void 0,"GPUParticleSystemLinesIndexBuffer")}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}createPointEmitter(e,t){const i=DE(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=wE(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=NE(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new _e(0,1,0),i=new _e(0,1,0)){const s=FE(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=LE(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new _e(0,1,0),r=new _e(0,1,0)){const n=BE(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=kE(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new uE;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady()||this._rebuildingAfterContextLost)return!1;if(this.blendMode!==VE.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else{if(!this._getWrapper(VE.BLENDMODE_MULTIPLY).effect.isReady())return!1;if(!this._getWrapper(VE.BLENDMODE_ADD).effect.isReady())return!1}return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";e?setTimeout((()=>{this.start(0)}),e):(this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop))}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new Un(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new K),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[1^this._targetIndex]}get indexBuffer(){return null}_removeGradientAndTexture(e,t,i){return super._removeGradientAndTexture(e,t,i),this._releaseBuffers(),this}addColorGradient(e,t){this._colorGradients||(this._colorGradients=[]);const i=new CE(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))}forceRefreshGradients(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()}removeColorGradient(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this}resetDrawCache(){for(const e in this._drawWrappers){const t=this._drawWrappers[e];t.drawContext?.reset()}}_addFactorGradient(e,t,i){const s=new AE(t,i);e.push(s),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){if(!e)return;i&&e.sort(((e,t)=>e.gradientt.gradient?1:0));const s=this;s[t]&&(s[t].dispose(),s[t]=null)}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,s=null,r=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this._rebuildingAfterContextLost=!1,this.onDisposeObservable=new K,this.onStoppedObservable=new K,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=me.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||re.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!W("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new(W("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!W("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new(W("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new Un(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers={0:new Un(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),(t=t??{}).randomTextureSize||delete t.randomTextureSize;const n={capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize,...t},o=t;isFinite(o)&&(n.capacity=o),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=r,this.particleEmitterType=new uE;const a=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize);let l=[];for(let e=0;e0;)i.push(0)}const o=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),a=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new Js(t,a,!1,this._attributesStrideSize),this._buffer1=new Js(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new Js(t,o,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}_recreateUpdateEffect(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();let e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e)),this._platform.isUpdateBufferReady()}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);let s=this._drawWrappers[e];s||(s=new Un(this._engine),s.drawContext&&(s.drawContext.useInstancing=!0),this._drawWrappers[e]=s);const r=i.join("\n");if(s.defines!==r){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),s.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,r),r)}return s}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,s=!1){const r=[er.PositionKind,"age","life","size","angle"];return e||r.push(er.ColorKind),t&&r.push("cellIndex"),i||r.push("initialDirection"),s&&r.push("direction"),r.push("offset",er.UVKind),r}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return mo(s),e&&s.push("sheetInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t=0,i=!0){if(this._scene&&(go(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==Hr.FOGMODE_NONE&&e.push("#define FOG")),t===VE.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case VE.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case VE.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case VE.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),i&&this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...UE._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===VE.BILLBOARDMODE_STRETCHED)),e.push(...UE._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(zs.PrepareUniforms(e,this._imageProcessingConfigurationDefines),zs.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){const i=this[t];if(!e||!e.length||i)return;const s=new Float32Array(this._rawTextureWidth);for(let t=0;t{s[t]=be.Lerp(e.factor1,i.factor1,r)}))}this[t]=Oa.CreateRTexture(s,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;const e=new Uint8Array(4*this._rawTextureWidth),t=Pe.Color4[0];for(let i=0;i{Ae.LerpToRef(s.color1,r.color1,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a}))}this._colorGradientsTexture=Oa.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){const i=this._getWrapper(e),s=i.effect;this._engine.enableEffect(i);const r=this._scene?.getViewMatrix()||me.IdentityReadOnly;if(s.setMatrix("view",r),s.setMatrix("projection",this.defaultProjectionMatrix??this._scene.getProjectionMatrix()),s.setTexture("diffuseSampler",this.particleTexture),s.setVector2("translationPivot",this.translationPivot),s.setVector3("worldOffset",this.worldOffset),this.isLocal&&s.setMatrix("emitterWM",t),this._colorGradientsTexture?s.setTexture("colorGradientSampler",this._colorGradientsTexture):s.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const e=this.particleTexture.getBaseSize();s.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const e=this._scene.activeCamera;s.setVector3("eyePosition",e.globalPosition)}const n=s.defines;if(this._scene&&(xo(s,this,this._scene),this.applyFog&&Co(this._scene,void 0,s)),n.indexOf("#define BILLBOARDMODE_ALL")>=0){const e=r.clone();e.invert(),s.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&So(n,s,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(s),e){case VE.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case VE.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case VE.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case VE.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,s,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(s),this._scene?.forceWireframe?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),this._scene?.forceWireframe&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer)return;if(!this._recreateUpdateEffect()||this._rebuildingAfterContextLost)return;if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{const t=this.emitter;e=ve.Matrix[0],me.TranslationToRef(t.x,t.y,t.z,e)}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,2===this._targetIndex&&(this._targetIndex=0);const t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){if(!this._started)return 0;if(!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e1){const e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount+=e}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;let i;if(this.emitter.position)i=this.emitter.getWorldMatrix();else{const e=this.emitter;i=ve.Matrix[0],me.TranslationToRef(e.x,e.y,e.z,i)}const s=this._engine;this.updateInAnimate||this._update(i);let r=0;return e||t||(s.setState(!1),this.forceDepthWrite&&s.setDepthWrite(!0),r=this.blendMode===VE.BLENDMODE_MULTIPLYADD?this._render(VE.BLENDMODE_MULTIPLY,i)+this._render(VE.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),r}rebuild(){const e=()=>{this._recreateUpdateEffect()&&this._platform.isUpdateBufferReady()?(this._initialize(!0),this._rebuildingAfterContextLost=!1):setTimeout(e,10)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),this._rebuildingAfterContextLost=!0,e()}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(const e in this._drawWrappers)this._drawWrappers[e].dispose();if(this._drawWrappers={},this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e0?r.shaderOptions.defines.join("\n"):"";s[0]=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,e,void 0,void 0,void 0,this)}const o=this.serialize(i),a=UE.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=r,a._customWrappers=s,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,a}serialize(e=!1){const t={};return VE._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,s=!1,r){const n=e.name;let o,a;t instanceof ns?o=t:(a=t,o=a.getEngine());const l=new UE(n,{capacity:r||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(l._rootUrl=i,e.customShader&&o.createEffectForParticles){const t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",s=o.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,l);l.setCustomEffect(s,0),l.customShader=t}return e.id&&(l.id=e.id),e.activeParticleCount&&(l.activeParticleCount=e.activeParticleCount),VE._Parse(e,l,t,i),e.preventAutoStart&&(l.preventAutoStart=e.preventAutoStart),s||l.preventAutoStart||l.start(),l}}class GE{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1);for(const t of this.systems)t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};const s=_d("emitterSphere",{diameter:e.diameter,segments:e.segments},i);s.renderingGroupId=t;const r=new cu("emitterSphereMaterial",i);r.emissiveColor=e.color,s.material=r;for(const e of this.systems)e.emitter=s;this._emitterNode=s}start(e){for(const t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(const e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){const t={systems:[]};for(const i of this.systems)t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,s){const r=new GE,n=this.BaseAssetsUrl+"/textures/";t=t||re.LastCreatedScene;for(const o of e.systems)r.systems.push(i?UE.Parse(o,t,n,!0,s):VE.Parse(o,t,n,!0,s));if(e.emitter){const i=e.emitter.options;"Sphere"===e.emitter.kind&&r.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:Ee.FromArray(i.color)},e.emitter.renderingGroupId,t)}return r}}GE.BaseAssetsUrl="https://assets.babylonjs.com/particles";class zE{static CreateDefault(e,t=500,i,s=!1){let r;return r=s?new UE("default system",{capacity:t},i):new VE("default system",t,i),r.emitter=e,r.particleTexture=new Pa("https://assets.babylonjs.com/textures/flare.png",r.getScene()),r.createConeEmitter(.1,Math.PI/4),r.color1=new Ae(1,1,1,1),r.color2=new Ae(1,1,1,1),r.colorDead=new Ae(1,1,1,0),r.minSize=.1,r.maxSize=.1,r.minEmitPower=2,r.maxEmitPower=2,r.updateSpeed=1/60,r.emitRate=30,r}static CreateAsync(e,t,i=!1,s){t||(t=re.LastCreatedScene);const r={};return t.addPendingData(r),new Promise(((n,o)=>{if(i&&!UE.IsSupported)return t.removePendingData(r),o("Particle system with GPU is not supported.");Ds.LoadFile(`${zE.BaseAssetsUrl}/systems/${e}.json`,(e=>{t.removePendingData(r);const o=JSON.parse(e.toString());return n(GE.Parse(o,t,i,s))}),void 0,void 0,void 0,(()=>(t.removePendingData(r),o(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`))))}))}static ExportSet(e){const t=new GE;for(const i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,s=!1,r="",n){return new Promise(((o,a)=>{const l=new Pt;l.addEventListener("readystatechange",(()=>{if(4==l.readyState)if(200==l.status){const t=JSON.parse(l.responseText);let a;a=s?UE.Parse(t,i,r,!1,n):VE.Parse(t,i,r,!1,n),e&&(a.name=e),o(a)}else a("Unable to load the particle system")})),l.open("GET",t),l.send()}))}static ParseFromSnippetAsync(e,t,i=!1,s="",r){if("_BLANK"===e){const e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise(((n,o)=>{const a=new Pt;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.particleSystem);let h;h=i?UE.Parse(l,t,s,!1,r):VE.Parse(l,t,s,!1,r),h.snippetId=e,n(h)}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}}zE.BaseAssetsUrl=GE.BaseAssetsUrl,zE.SnippetUrl="https://snippet.babylonjs.com",zE.CreateFromSnippetAsync=zE.ParseFromSnippetAsync,X.AddParser(or.NAME_PARTICLESYSTEM,((e,t,i,s)=>{const r=X.GetIndividualParser(or.NAME_PARTICLESYSTEM);if(r&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,o=e.particleSystems.length;ne.activeParticleCount?UE.Parse(e,t,i):VE.Parse(e,t,i))),ns.prototype.createEffectForParticles=function(e,t=[],i=[],s="",r,n,o,a){let l=[],h=[];const c=[];return a?a.fillUniformsAttributesAndSamplerNames(h,l,c):(l=VE._GetAttributeNamesOrOptions(),h=VE._GetEffectCreationOptions()),-1===s.indexOf(" BILLBOARD")&&(s+="\n#define BILLBOARD\n"),a?.isAnimationSheetEnabled&&-1===s.indexOf(" ANIMATESHEET")&&(s+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:a?.vertexShaderName??"particles",fragmentElement:e},l,h.concat(t),c.concat(i),s,r,n,o)},ha.prototype.getEmittedParticleSystems=function(){const e=[];for(let t=0;tt.sqDistance-e.sqDistance,this._materialSortFunction=(e,t)=>e.materialIndex-t.materialIndex,this._autoUpdateSubMeshes=!1,this._recomputeInvisibles=!1,this.name=e,this._scene=t||re.LastCreatedScene,this._camera=t.activeCamera,this._pickable=!!i&&i.isPickable,this._depthSort=!!i&&i.enableDepthSort,this._multimaterialEnabled=!!i&&i.enableMultiMaterial,this._useModelMaterial=!!i&&i.useModelMaterial,this._multimaterialEnabled=!!this._useModelMaterial||this._multimaterialEnabled,this._expandable=!!i&&i.expandable,this._particlesIntersect=!!i&&i.particleIntersection,this._bSphereOnly=!!i&&i.boundingSphereOnly,this._bSphereRadiusFactor=i&&i.bSphereRadiusFactor?i.bSphereRadiusFactor:1,this._computeBoundingBox=!!i?.computeBoundingBox&&i.computeBoundingBox,this._autoFixFaceOrientation=!!i?.autoFixFaceOrientation&&i.autoFixFaceOrientation,i&&void 0!==i.updatable?this._updatable=i.updatable:this._updatable=!0,this._pickable&&(this.pickedBySubMesh=[[]],this.pickedParticles=this.pickedBySubMesh[0]),(this._depthSort||this._multimaterialEnabled)&&(this.depthSortedParticles=[]),this._multimaterialEnabled&&(this._multimaterial=new ia(this.name+"MultiMaterial",this._scene),this._materials=[],this._materialIndexesById={}),this._tmpVertex=new YE}buildMesh(){if(!this._isNotBuilt&&this.mesh)return this.mesh;if(0===this.nbParticles&&!this.mesh){const e=yd("",{radius:1,tessellation:3},this._scene);this.addShape(e,1),e.dispose()}if(this._indices32=this._needs32Bits?new Uint32Array(this._indices):new Uint16Array(this._indices),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors),!this.mesh){const e=new ha(this.name,this._scene);this.mesh=e}!this._updatable&&this._multimaterialEnabled&&this._sortParticlesByMaterial(),this.recomputeNormals&&Wn.ComputeNormals(this._positions32,this._indices32,this._normals),this._normals32=new Float32Array(this._normals),this._fixedNormal32=new Float32Array(this._normals),this._mustUnrotateFixedNormals&&this._unrotateFixedNormals();const e=new Wn;if(e.indices=this._depthSort?this._indices:this._indices32,e.set(this._positions32,er.PositionKind),e.set(this._normals32,er.NormalKind),this._uvs32.length>0&&e.set(this._uvs32,er.UVKind),this._colors32.length>0&&e.set(this._colors32,er.ColorKind),e.applyToMesh(this.mesh,this._updatable),this.mesh.isPickable=this._pickable,this._pickable){let e=0;for(let t=0;td?d:s,i=Math.round(d/s),r=0):i=i>d?d:i;const _=[],p=[],f=[],m=[],g=[],v=_e.Zero(),x=i;for(;ud-i&&(i=d-u),_.length=0,p.length=0,f.length=0,m.length=0,g.length=0;let t=0;for(let e=3*u;e<3*(u+i);e++){f.push(t);const i=o[e],s=3*i;if(_.push(n[s],n[s+1],n[s+2]),p.push(h[s],h[s+1],h[s+2]),a){const e=2*i;m.push(a[e],a[e+1])}if(l){const e=4*i;g.push(l[e],l[e+1],l[e+2],l[e+3])}t++}let s=this.nbParticles;const b=this._posToShape(_),T=this._uvsToShapeUV(m),y=f.slice(),S=g.slice(),C=p.slice();let E;for(v.copyFromFloats(0,0,0),E=0;E65535&&(this._needs32Bits=!0)}if(this._depthSort||this._multimaterialEnabled){const e=null!==b.materialIndex?b.materialIndex:0;this.depthSortedParticles.push(new XE(d,t,r.length,e))}return b}_posToShape(e){const t=[];for(let i=0;i=this.nbParticles||!this._updatable)return[];const s=this.particles,r=this.nbParticles;if(t=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){const e=this.mesh.getBoundingInfo();e&&(v.copyFrom(e.minimum),x.copyFrom(e.maximum))}A=this.particles[e]._pos;const D=A/3|0;I=4*D,M=2*D;for(let i=e;i<=t;i++){const e=this.particles[i];this.updateParticle(e);const t=e._model._shape,r=e._model._shapeUV,c=e._rotationMatrix,u=e.position,D=e.rotation,w=e.scaling,N=e._globalPosition;if(_){const t=this.depthSortedParticles[i];t.idx=e.idx,t.ind=e._ind,t.indicesLength=e._model._indicesLength,t.sqDistance=_e.DistanceSquared(e.position,b)}if(e.alive&&(!e._stillInvisible||e.isVisible||this._recomputeInvisibles)){if(e.isVisible){e._stillInvisible=!1;const i=p[12];if(e.pivot.multiplyToRef(w,i),this.billboard&&(D.x=0,D.y=0),(this._computeParticleRotation||this.billboard)&&e.getRotationMatrix(s),null!==e.parentId){const t=this.getParticleById(e.parentId);if(t){const e=t._rotationMatrix,i=t._globalPosition,r=u.x*e[1]+u.y*e[4]+u.z*e[7],n=u.x*e[0]+u.y*e[3]+u.z*e[6],o=u.x*e[2]+u.y*e[5]+u.z*e[8];if(N.x=i.x+n,N.y=i.y+r,N.z=i.z+o,this._computeParticleRotation||this.billboard){const t=s.m;c[0]=t[0]*e[0]+t[1]*e[3]+t[2]*e[6],c[1]=t[0]*e[1]+t[1]*e[4]+t[2]*e[7],c[2]=t[0]*e[2]+t[1]*e[5]+t[2]*e[8],c[3]=t[4]*e[0]+t[5]*e[3]+t[6]*e[6],c[4]=t[4]*e[1]+t[5]*e[4]+t[6]*e[7],c[5]=t[4]*e[2]+t[5]*e[5]+t[6]*e[8],c[6]=t[8]*e[0]+t[9]*e[3]+t[10]*e[6],c[7]=t[8]*e[1]+t[9]*e[4]+t[10]*e[7],c[8]=t[8]*e[2]+t[9]*e[5]+t[10]*e[8]}}else e.parentId=null}else if(N.x=u.x,N.y=u.y,N.z=u.z,this._computeParticleRotation||this.billboard){const e=s.m;c[0]=e[0],c[1]=e[1],c[2]=e[2],c[3]=e[4],c[4]=e[5],c[5]=e[6],c[6]=e[8],c[7]=e[9],c[8]=e[10]}const n=p[11];for(e.translateFromPivot?n.setAll(0):n.copyFrom(i),O=0;O0)for(let t=0;t(this._isReady=!0,this._buildMesh(e))))}_buildMesh(e){0===this.nbParticles&&this.addPoints(1),this._positions32=new Float32Array(this._positions),this._uvs32=new Float32Array(this._uvs),this._colors32=new Float32Array(this._colors);const t=new Wn;t.set(this._positions32,er.PositionKind),this._uvs32.length>0&&t.set(this._uvs32,er.UVKind);let i=0;this._colors32.length>0&&(i=1,t.set(this._colors32,er.ColorKind));const s=new ha(this.name,this._scene);t.applyToMesh(s,this._updatable),this.mesh=s,this._positions=null,this._uvs=null,this._colors=null,this._updatable||(this.particles.length=0);let r=e;return r||(r=new cu("point cloud material",this._scene),r.emissiveColor=new Ee(i,i,i),r.disableLighting=!0,r.pointsCloud=!0,r.pointSize=this._size),s.material=r,new Promise((e=>e(s)))}_addParticle(e,t,i,s){const r=new jE(e,t,i,s,this);return this.particles.push(r),r}_randomUnitVector(e){e.position=new _e(Math.random(),Math.random(),Math.random()),e.color=new Ae(1,1,1,1)}_getColorIndicesForCoord(e,t,i,s){const r=e._groupImageData,n=i*(4*s)+4*t,o=[n,n+1,n+2,n+3],a=o[1],l=o[2],h=o[3],c=r[o[0]],u=r[a],d=r[l],_=r[h];return new Ae(c/255,u/255,d/255,_)}_setPointsColorOrUV(e,t,i,s,r,n,o,a){a=a??0,i&&e.updateFacetData();const l=2*e.getBoundingInfo().boundingSphere.radius;let h=e.getVerticesData(er.PositionKind);const c=e.getIndices(),u=e.getVerticesData(er.UVKind+(a?a+1:"")),d=e.getVerticesData(er.ColorKind),_=_e.Zero();e.computeWorldMatrix();const p=e.getWorldMatrix();if(!p.isIdentity()){h=h.slice(0);for(let e=0;e1&&(Re=1),Me<0&&(Me=0),Me>1&&(Me=1),Ee.HSVtoRGBToRef(Ie,Re,Me,we),ue.set(we.r,we.g,we.b,1)):ue=ie.set(Math.random(),Math.random(),Math.random(),1),Fe.color=new Ae(ue.x,ue.y,ue.z,ue.w),this._colors.push(ue.x,ue.y,ue.z,ue.w))}}_colorFromTexture(e,t,i){if(null===e.material)return Ne.Warn(e.name+"has no material."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);const s=e.material.getActiveTextures();if(0===s.length)return Ne.Warn(e.name+"has no usable texture."),t._groupImageData=null,void this._setPointsColorOrUV(e,t,i,!0,!1);const r=e.clone();r.setEnabled(!1),this._promises.push(new Promise((e=>{ya.WhenAllReady(s,(()=>{let n=t._textureNb;n<0&&(n=0),n>s.length-1&&(n=s.length-1);const o=()=>{t._groupImgWidth=s[n].getSize().width,t._groupImgHeight=s[n].getSize().height,this._setPointsColorOrUV(r,t,i,!0,!0,void 0,void 0,s[n].coordinatesIndex),r.dispose(),e()};t._groupImageData=null;const a=s[n].readPixels();a?a.then((e=>{t._groupImageData=e,o()})):o()}))})))}_calculateDensity(e,t,i){let s,r,n,o,a,l,h,c,u,d,_,p;const f=_e.Zero(),m=_e.Zero(),g=_e.Zero(),v=_e.Zero(),x=_e.Zero(),b=_e.Zero();let T;const y=[];let S=0;const C=i.length/3;for(let e=0;e0;e--){const t=y[e];if(0===t)E[e]=0;else{const i=(t-y[e-1])/t*A,s=Math.floor(i),r=i-s,n=s+Number(Math.random()3)&&(n=$E.Random);const o=e.getVerticesData(er.PositionKind),a=e.getIndices();this._groups.push(this._groupCounter);const l=new KE(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,a),n===$E.Color?l._textureNb=s||0:s=s||new Ae(1,1,1,1),n){case $E.Color:this._colorFromTexture(e,l,!1);break;case $E.UV:this._setPointsColorOrUV(e,l,!1,!1,!1);break;case $E.Random:this._setPointsColorOrUV(e,l,!1);break;case $E.Stated:this._setPointsColorOrUV(e,l,!1,void 0,void 0,s,r)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}addVolumePoints(e,t,i,s,r){let n=i||$E.Random;(isNaN(n)||n<0||n>3)&&(n=$E.Random);const o=e.getVerticesData(er.PositionKind),a=e.getIndices();this._groups.push(this._groupCounter);const l=new KE(this._groupCounter,null);switch(l._groupDensity=this._calculateDensity(t,o,a),n===$E.Color?l._textureNb=s||0:s=s||new Ae(1,1,1,1),n){case $E.Color:this._colorFromTexture(e,l,!0);break;case $E.UV:this._setPointsColorOrUV(e,l,!0,!1,!1);break;case $E.Random:this._setPointsColorOrUV(e,l,!0);break;case $E.Stated:this._setPointsColorOrUV(e,l,!0,void 0,void 0,s,r)}return this.nbParticles+=t,this._groupCounter++,this._groupCounter-1}setParticles(e=0,t=this.nbParticles-1,i=!0){if(!this._updatable||!this._isReady)return this;this.beforeUpdateParticles(e,t,i);const s=ve.Matrix[0],r=this.mesh,n=this._colors32,o=this._positions32,a=this._uvs32,l=ve.Vector3,h=l[5].copyFromFloats(1,0,0),c=l[6].copyFromFloats(0,1,0),u=l[7].copyFromFloats(0,0,1),d=l[8].setAll(Number.MAX_VALUE),_=l[9].setAll(-Number.MAX_VALUE);me.IdentityToRef(s);let p=0;if(this.mesh?.isFacetDataEnabled&&(this._computeBoundingBox=!0),t=t>=this.nbParticles?this.nbParticles-1:t,this._computeBoundingBox&&(0!=e||t!=this.nbParticles-1)){const e=this.mesh?.getBoundingInfo();e&&(d.copyFrom(e.minimum),_.copyFrom(e.maximum))}p=0;let f=0,m=0,g=0;for(let i=e;i<=t;i++){const e=this.particles[i];p=e.idx,f=3*p,m=4*p,g=2*p,this.updateParticle(e);const t=e._rotationMatrix,r=e.position,n=e._globalPosition;if(this._computeParticleRotation&&e.getRotationMatrix(s),null!==e.parentId){const i=this.particles[e.parentId],o=i._rotationMatrix,a=i._globalPosition,l=r.x*o[1]+r.y*o[4]+r.z*o[7],h=r.x*o[0]+r.y*o[3]+r.z*o[6],c=r.x*o[2]+r.y*o[5]+r.z*o[8];if(n.x=a.x+h,n.y=a.y+l,n.z=a.z+c,this._computeParticleRotation){const e=s.m;t[0]=e[0]*o[0]+e[1]*o[3]+e[2]*o[6],t[1]=e[0]*o[1]+e[1]*o[4]+e[2]*o[7],t[2]=e[0]*o[2]+e[1]*o[5]+e[2]*o[8],t[3]=e[4]*o[0]+e[5]*o[3]+e[6]*o[6],t[4]=e[4]*o[1]+e[5]*o[4]+e[6]*o[7],t[5]=e[4]*o[2]+e[5]*o[5]+e[6]*o[8],t[6]=e[8]*o[0]+e[9]*o[3]+e[10]*o[6],t[7]=e[8]*o[1]+e[9]*o[4]+e[10]*o[7],t[8]=e[8]*o[2]+e[9]*o[5]+e[10]*o[8]}}else if(n.x=0,n.y=0,n.z=0,this._computeParticleRotation){const e=s.m;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10]}const a=l[11];e.translateFromPivot?a.setAll(0):a.copyFrom(e.pivot);const v=l[0];v.copyFrom(e.position);const x=v.x-e.pivot.x,b=v.y-e.pivot.y,T=v.z-e.pivot.z;let y=x*t[0]+b*t[3]+T*t[6],S=x*t[1]+b*t[4]+T*t[7],C=x*t[2]+b*t[5]+T*t[8];y+=a.x,S+=a.y,C+=a.z;const E=o[f]=n.x+h.x*y+c.x*S+u.x*C,A=o[f+1]=n.y+h.y*y+c.y*S+u.y*C,P=o[f+2]=n.z+h.z*y+c.z*S+u.z*C;if(this._computeBoundingBox&&(d.minimizeInPlaceFromFloats(E,A,P),_.maximizeInPlaceFromFloats(E,A,P)),this._computeParticleColor&&e.color){const t=e.color,i=this._colors32;i[m]=t.r,i[m+1]=t.g,i[m+2]=t.b,i[m+3]=t.a}if(this._computeParticleTexture&&e.uv){const t=e.uv,i=this._uvs32;i[g]=t.x,i[g+1]=t.y}}return r&&(i&&(this._computeParticleColor&&r.updateVerticesData(er.ColorKind,n,!1,!1),this._computeParticleTexture&&r.updateVerticesData(er.UVKind,a,!1,!1),r.updateVerticesData(er.PositionKind,o,!1,!1)),this._computeBoundingBox&&(r.hasBoundingInfo?r.getBoundingInfo().reConstruct(d,_,r._worldMatrix):r.buildBoundingInfo(d,_,r._worldMatrix))),this.afterUpdateParticles(e,t,i),this}dispose(){this.mesh?.dispose(),this.vars=null,this._positions=null,this._indices=null,this._normals=null,this._uvs=null,this._colors=null,this._indices32=null,this._positions32=null,this._uvs32=null,this._colors32=null}refreshVisibleSize(){return this._isVisibilityBoxLocked||this.mesh?.refreshBoundingInfo(),this}setVisibilityBox(e){if(!this.mesh)return;const t=e/2;this.mesh.buildBoundingInfo(new _e(-t,-t,-t),new _e(t,t,t))}get isAlwaysVisible(){return this._alwaysVisible}set isAlwaysVisible(e){this.mesh&&(this._alwaysVisible=e,this.mesh.alwaysSelectAsActiveMesh=e)}set computeParticleRotation(e){this._computeParticleRotation=e}set computeParticleColor(e){this._computeParticleColor=e}set computeParticleTexture(e){this._computeParticleTexture=e}get computeParticleColor(){return this._computeParticleColor}get computeParticleTexture(){return this._computeParticleTexture}set computeBoundingBox(e){this._computeBoundingBox=e}get computeBoundingBox(){return this._computeBoundingBox}initParticles(){}recycleParticle(e){return e}updateParticle(e){return e}beforeUpdateParticles(e,t,i){}afterUpdateParticles(e,t,i){}}Object.defineProperty(_o.prototype,"physicsImpostor",{get:function(){return this._physicsImpostor},set:function(e){this._physicsImpostor!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsImpostor=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)}))))},enumerable:!0,configurable:!0}),_o.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},_o.prototype.applyImpulse=function(e,t){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(e,t),this):this},_o.prototype.setPhysicsLinkWith=function(e,t,i,s){return this.physicsImpostor&&e.physicsImpostor?(this.physicsImpostor.createJoint(e.physicsImpostor,el.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:s}),this):this};class hA{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw xt("")}constructor(e,t=hA.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new _e(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){const t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,s){this._physicsPlugin.raycast(e,t,i,s)}raycast(e,t,i){const s=new cx;return this._physicsPlugin.raycast(e,t,s,i),s}}!function(e){e[e.FREE=0]="FREE",e[e.LIMITED=1]="LIMITED",e[e.LOCKED=2]="LOCKED"}(qE||(qE={})),function(e){e[e.LINEAR_X=0]="LINEAR_X",e[e.LINEAR_Y=1]="LINEAR_Y",e[e.LINEAR_Z=2]="LINEAR_Z",e[e.ANGULAR_X=3]="ANGULAR_X",e[e.ANGULAR_Y=4]="ANGULAR_Y",e[e.ANGULAR_Z=5]="ANGULAR_Z",e[e.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"}(ZE||(ZE={})),function(e){e[e.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",e[e.DISTANCE=2]="DISTANCE",e[e.HINGE=3]="HINGE",e[e.SLIDER=4]="SLIDER",e[e.LOCK=5]="LOCK",e[e.PRISMATIC=6]="PRISMATIC",e[e.SIX_DOF=7]="SIX_DOF"}(JE||(JE={})),function(e){e[e.SPHERE=0]="SPHERE",e[e.CAPSULE=1]="CAPSULE",e[e.CYLINDER=2]="CYLINDER",e[e.BOX=3]="BOX",e[e.CONVEX_HULL=4]="CONVEX_HULL",e[e.CONTAINER=5]="CONTAINER",e[e.MESH=6]="MESH",e[e.HEIGHTFIELD=7]="HEIGHTFIELD"}(eA||(eA={})),function(e){e[e.NONE=0]="NONE",e[e.VELOCITY=1]="VELOCITY",e[e.POSITION=2]="POSITION"}(tA||(tA={})),function(e){e.COLLISION_STARTED="COLLISION_STARTED",e.COLLISION_CONTINUED="COLLISION_CONTINUED",e.COLLISION_FINISHED="COLLISION_FINISHED",e.TRIGGER_ENTERED="TRIGGER_ENTERED",e.TRIGGER_EXITED="TRIGGER_EXITED"}(iA||(iA={})),function(e){e[e.STATIC=0]="STATIC",e[e.ANIMATED=1]="ANIMATED",e[e.DYNAMIC=2]="DYNAMIC"}(sA||(sA={})),function(e){e[e.SIMULATION_CONTROLLED=0]="SIMULATION_CONTROLLED",e[e.ALWAYS_ACTIVE=1]="ALWAYS_ACTIVE",e[e.ALWAYS_INACTIVE=2]="ALWAYS_INACTIVE"}(rA||(rA={}));class cA{constructor(e,t,i,s){if(this._pluginData=void 0,this._pluginDataInstances=[],this._collisionCBEnabled=!1,this._collisionEndedCBEnabled=!1,this.disablePreStep=!0,this.disableSync=!1,this._isDisposed=!1,this._shape=null,!s)return;const r=s.getPhysicsEngine();if(!r)throw new Error("No Physics Engine available.");if(this._physicsEngine=r,2!=r.getPluginVersion())throw new Error("Plugin version is incorrect. Expected version 2.");const n=r.getPhysicsPlugin();if(!n)throw new Error("No Physics Plugin available.");this._physicsPlugin=n,e.rotationQuaternion||(e.rotationQuaternion=fe.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z)),this.startAsleep=i,this._motionType=t,this.disableSync=t==sA.STATIC;const o=e;o.hasThinInstances?this._physicsPlugin.initBodyInstances(this,t,o):(e.parent&&e.computeWorldMatrix(!0),this._physicsPlugin.initBody(this,t,e.absolutePosition,e.absoluteRotationQuaternion)),this.transformNode=e,e.physicsBody=this,r.addBody(this),this._nodeDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}getClassName(){return"PhysicsBody"}clone(e){const t=new cA(e,this.getMotionType(),this.startAsleep,this.transformNode.getScene());return t.shape=this.shape,t.setMassProperties(this.getMassProperties()),t.setLinearDamping(this.getLinearDamping()),t.setAngularDamping(this.getAngularDamping()),t}updateBodyInstances(){const e=this.transformNode;e.hasThinInstances&&this._physicsPlugin.updateBodyInstances(this,e)}get numInstances(){return this._pluginDataInstances.length}get motionType(){return this._motionType}set shape(e){this._shape=e,e&&this._physicsPlugin.setShape(this,e)}get shape(){return this._shape}getBoundingBox(){return this._physicsPlugin.getBodyBoundingBox(this)}setEventMask(e,t){this._physicsPlugin.setEventMask(this,e,t)}getEventMask(e){return this._physicsPlugin.getEventMask(this,e)}setMotionType(e,t){this.disableSync=e==sA.STATIC,this._physicsPlugin.setMotionType(this,e,t)}getMotionType(e){return this._physicsPlugin.getMotionType(this,e)}computeMassProperties(e){return this._physicsPlugin.computeMassProperties(this,e)}setMassProperties(e,t){this._physicsPlugin.setMassProperties(this,e,t)}getMassProperties(e){return this._physicsPlugin.getMassProperties(this,e)}setLinearDamping(e,t){this._physicsPlugin.setLinearDamping(this,e,t)}getLinearDamping(e){return this._physicsPlugin.getLinearDamping(this,e)}setAngularDamping(e,t){this._physicsPlugin.setAngularDamping(this,e,t)}getAngularDamping(e){return this._physicsPlugin.getAngularDamping(this,e)}setLinearVelocity(e,t){this._physicsPlugin.setLinearVelocity(this,e,t)}getLinearVelocityToRef(e,t){this._physicsPlugin.getLinearVelocityToRef(this,e,t)}getLinearVelocity(e){const t=new _e;return this.getLinearVelocityToRef(t,e),t}setAngularVelocity(e,t){this._physicsPlugin.setAngularVelocity(this,e,t)}getAngularVelocityToRef(e,t){this._physicsPlugin.getAngularVelocityToRef(this,e,t)}getAngularVelocity(e){const t=new _e;return this.getAngularVelocityToRef(t,e),t}applyImpulse(e,t,i){this._physicsPlugin.applyImpulse(this,e,t,i)}applyAngularImpulse(e,t){this._physicsPlugin.applyAngularImpulse(this,e,t)}applyForce(e,t,i){this._physicsPlugin.applyForce(this,e,t,i)}getGeometry(){return this._physicsPlugin.getBodyGeometry(this)}getCollisionObservable(){return this._physicsPlugin.getCollisionObservable(this)}getCollisionEndedObservable(){return this._physicsPlugin.getCollisionEndedObservable(this)}setCollisionCallbackEnabled(e){this._collisionCBEnabled=e,this._physicsPlugin.setCollisionCallbackEnabled(this,e)}setCollisionEndedCallbackEnabled(e){this._collisionEndedCBEnabled=e,this._physicsPlugin.setCollisionEndedCallbackEnabled(this,e)}getObjectCenterWorld(e){const t=new _e;return this.getObjectCenterWorldToRef(t,e)}getObjectCenterWorldToRef(e,t){if(this._pluginDataInstances?.length>0){const i=t||0,s=this.transformNode._thinInstanceDataStorage.matrixData;s&&e.set(s[16*i+12],s[16*i+13],s[16*i+14])}else e.copyFrom(this.transformNode.position);return e}addConstraint(e,t,i,s){this._physicsPlugin.addConstraint(this,e,t,i,s)}syncWithBone(e,t,i,s,r,n){const o=this.transformNode;if(o.rotationQuaternion)if(r){const i=ve.Quaternion[0];e.getRotationQuaternionToRef(Ur.WORLD,t,i),i.multiplyToRef(r,o.rotationQuaternion)}else e.getRotationQuaternionToRef(Ur.WORLD,t,o.rotationQuaternion);const a=ve.Vector3[0],l=ve.Vector3[1];n||((n=ve.Vector3[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,a),null==s&&i&&(s=i.length()),null!=s&&(a.x+=l.x*s,a.y+=l.y*s,a.z+=l.z*s),o.setAbsolutePosition(a)}iterateOverAllInstances(e){if(this._pluginDataInstances?.length>0)for(let t=0;t{this.dispose()}))}_getObjectBoundingBox(){return this.transformNode.getRawBoundingInfo?this.transformNode.getRawBoundingInfo().boundingBox:new Mn(new _e(-.5,-.5,-.5),new _e(.5,.5,.5))}_hasVertices(e){return e?.getTotalVertices()>0}_addSizeOptions(){this.transformNode.computeWorldMatrix(!0);const e=this._getObjectBoundingBox(),t=ve.Vector3[0];t.copyFrom(e.extendSize),t.scaleInPlace(2),t.multiplyInPlace(this.transformNode.absoluteScaling),t.x=Math.abs(t.x),t.y=Math.abs(t.y),t.z=Math.abs(t.z);const i=ve.Vector3[1];if(i.copyFrom(e.minimum),i.multiplyInPlace(this.transformNode.absoluteScaling),!this._options.center){const t=new _e;t.copyFrom(e.center),t.multiplyInPlace(this.transformNode.absoluteScaling),this._options.center=t}switch(this.type){case eA.SPHERE:!this._options.radius&&be.WithinEpsilon(t.x,t.y,1e-4)&&be.WithinEpsilon(t.x,t.z,1e-4)?this._options.radius=t.x/2:this._options.radius||(Ne.Warn("Non uniform scaling is unsupported for sphere shapes. Setting the radius to the biggest bounding box extent."),this._options.radius=Math.max(t.x,t.y,t.z)/2);break;case eA.CAPSULE:{const e=t.x/2;this._options.radius=this._options.radius??e,this._options.pointA=this._options.pointA??new _e(0,i.y+e,0),this._options.pointB=this._options.pointB??new _e(0,i.y+t.y-e,0)}break;case eA.CYLINDER:{const e=t.x/2;this._options.radius=this._options.radius??e,this._options.pointA=this._options.pointA??new _e(0,i.y,0),this._options.pointB=this._options.pointB??new _e(0,i.y+t.y,0)}break;case eA.MESH:case eA.CONVEX_HULL:if(!this._options.mesh&&this._hasVertices(this.transformNode))this._options.mesh=this.transformNode;else if(!this._options.mesh||!this._hasVertices(this._options.mesh))throw new Error("No valid mesh was provided for mesh or convex hull shape parameter. Please provide a mesh with valid geometry (number of vertices greater than 0).");break;case eA.BOX:this._options.extents=this._options.extents??new _e(t.x,t.y,t.z),this._options.rotation=this._options.rotation??fe.Identity()}}dispose(){this._nodeDisposeObserver&&(this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver),this._nodeDisposeObserver=null),this.body.dispose(),this._disposeShapeWhenDisposed&&this.shape.dispose()}}class MA{}class OA{constructor(e,t,i){this._boxConfigs=new Array,this._joints=new Array,this._bones=new Array,this._initialRotation=new Array,this._initialRotation2=new Array,this._boneNames=[],this._transforms=new Array,this._aggregates=new Array,this._ragdollMode=!1,this._rootBoneName="",this._rootBoneIndex=-1,this._mass=10,this._restitution=0,this.pauseSync=!1,this._defaultJoint=JE.HINGE,this._defaultJointMin=-90,this._defaultJointMax=90,this._skeleton=e,this._scene=e.getScene(),this._rootTransformNode=t,this._config=i,this._boxConfigs=[],this._putBoxesInBoneCenter=!1,this._defaultJoint=JE.HINGE,this._init()}getAggregate(e){return e<0||e>=this._aggregates.length?this._aggregates[this._rootBoneIndex]:this._aggregates[e]}_createColliders(){this._rootTransformNode.computeWorldMatrix(),this._skeleton.computeAbsoluteMatrices(!0),this._skeleton.prepare(!0);const e=this._config;for(let t=0;t{this._syncBonesAndBoxes()})),this._syncBonesToPhysics())}ragdoll(){this._ragdollMode=!0,this._skeleton.bones.forEach((e=>{e.linkTransformNode(null)}));for(let e=0;e{e.dispose()}))}}class DA{constructor(e,t,i){this._vertices=[],this._indices=[],this._isRightHanded=i.useRightHandedSystem,this._collectIndices=t}addNodeMeshes(e,t){e.computeWorldMatrix(!0);const i=ve.Matrix[0];if(me.ScalingToRef(e.absoluteScaling.x,e.absoluteScaling.y,e.absoluteScaling.z,i),e instanceof ha?this._addMesh(e,i):e instanceof ca&&this._addMesh(e.sourceMesh,i),t){const t=ve.Matrix[1];e.computeWorldMatrix().invertToRef(t);const s=ve.Matrix[2];t.multiplyToRef(i,s),e.getChildMeshes(!1).filter((e=>!e.physicsBody)).forEach((e=>{const t=e.computeWorldMatrix(),i=ve.Matrix[3];t.multiplyToRef(s,i),e instanceof ha?this._addMesh(e,i):e instanceof ca&&this._addMesh(e.sourceMesh,i)}))}}_addMesh(e,t){const i=e.getVerticesData(er.PositionKind)||[],s=i.length/3,r=this._vertices.length;for(let e=0;e0)for(const t of e._pluginDataInstances)this._bodyCollisionObservable.delete(t.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,t.hpBodyId),this._bodies.delete(t.hpBodyId[0]);e._pluginData&&(this._bodyCollisionObservable.delete(e._pluginData.hpBodyId[0]),this._hknp.HP_World_RemoveBody(this.world,e._pluginData.hpBodyId),this._bodies.delete(e._pluginData.hpBodyId[0]))}initBodyInstances(e,t,i){const s=i._thinInstanceDataStorage?.instancesCount??0,r=i._thinInstanceDataStorage.matrixData;r&&(this._createOrUpdateBodyInstances(e,t,r,0,s,!1),e._pluginDataInstances.forEach(((t,i)=>{this._bodies.set(t.hpBodyId[0],{body:e,index:i})})))}_createOrUpdateBodyInstances(e,t,i,s,r,n){const o=ve.Quaternion[0],a=me.Identity();for(let l=s;lr){this._createOrUpdateBodyInstances(e,n,s,r,i,!1);const t=this._hknp.HP_Body_GetShape(e._pluginDataInstances[0].hpBodyId)[1];t[0]||(t[0]=e.shape?._pluginData[0]);for(let s=r;s{this._hknp.HP_Body_SetEventMask(e.hpBodyId,t)}),i)}getEventMask(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1]}_fromMassPropertiesTuple(e){return{centerOfMass:_e.FromArray(e[0]),mass:e[1],inertia:_e.FromArray(e[2]),inertiaOrientation:fe.FromArray(e[3])}}_internalUpdateMassProperties(e){const t=this._internalComputeMassProperties(e),i=e.userMassProps;i.centerOfMass&&(t[0]=i.centerOfMass.asArray()),null!=i.mass&&(t[1]=i.mass),i.inertia&&(t[2]=i.inertia.asArray()),i.inertiaOrientation&&(t[3]=i.inertiaOrientation.asArray()),this._hknp.HP_Body_SetMassProperties(e.hpBodyId,t)}_internalSetMotionType(e,t){switch(t){case sA.STATIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.STATIC);break;case sA.ANIMATED:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.KINEMATIC);break;case sA.DYNAMIC:this._hknp.HP_Body_SetMotionType(e.hpBodyId,this._hknp.MotionType.DYNAMIC)}}setMotionType(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._internalSetMotionType(e,t)}),i)}getMotionType(e,t){const i=this._getPluginReference(e,t),s=this._hknp.HP_Body_GetMotionType(i.hpBodyId)[1];switch(s){case this._hknp.MotionType.STATIC:return sA.STATIC;case this._hknp.MotionType.KINEMATIC:return sA.ANIMATED;case this._hknp.MotionType.DYNAMIC:return sA.DYNAMIC}throw new Error("Unknown motion type: "+s)}setActivationControl(e,t){switch(t){case rA.ALWAYS_ACTIVE:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_ACTIVE);break;case rA.ALWAYS_INACTIVE:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.ALWAYS_INACTIVE);break;case rA.SIMULATION_CONTROLLED:this._hknp.HP_Body_SetActivationControl(e._pluginData.hpBodyId,this._hknp.ActivationControl.SIMULATION_CONTROLLED)}}_internalComputeMassProperties(e){const t=this._hknp.HP_Body_GetShape(e.hpBodyId);if(t[0]==this._hknp.Result.RESULT_OK){const e=this._hknp.HP_Shape_BuildMassProperties(t[1]);if(e[0]==this._hknp.Result.RESULT_OK)return e[1]}return[[0,0,0],1,[1,1,1],[0,0,0,1]]}computeMassProperties(e,t){const i=this._getPluginReference(e,t),s=this._internalComputeMassProperties(i);return this._fromMassPropertiesTuple(s)}setMassProperties(e,t,i){this._applyToBodyOrInstances(e,(e=>{e.userMassProps=t,this._internalUpdateMassProperties(e)}),i)}getMassProperties(e,t){const i=this._getPluginReference(e,t),s=this._hknp.HP_Body_GetMassProperties(i.hpBodyId)[1];return this._fromMassPropertiesTuple(s)}setLinearDamping(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetLinearDamping(e.hpBodyId,t)}),i)}getLinearDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetLinearDamping(i.hpBodyId)[1]}setAngularDamping(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetAngularDamping(e.hpBodyId,t)}),i)}getAngularDamping(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetAngularDamping(i.hpBodyId)[1]}setLinearVelocity(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetLinearVelocity(e.hpBodyId,this._bVecToV3(t))}),i)}getLinearVelocityToRef(e,t,i){const s=this._getPluginReference(e,i),r=this._hknp.HP_Body_GetLinearVelocity(s.hpBodyId)[1];this._v3ToBvecRef(r,t)}_applyToBodyOrInstances(e,t,i){if(e._pluginDataInstances?.length>0&&void 0===i)for(let i=0;i{this._hknp.HP_Body_ApplyImpulse(e.hpBodyId,this._bVecToV3(i),this._bVecToV3(t))}),s)}applyAngularImpulse(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_ApplyAngularImpulse(e.hpBodyId,this._bVecToV3(t))}),i)}applyForce(e,t,i,s){t.scaleToRef(this.getTimeStep(),this._tmpVec3[0]),this.applyImpulse(e,this._tmpVec3[0],i,s)}setAngularVelocity(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetAngularVelocity(e.hpBodyId,this._bVecToV3(t))}),i)}getAngularVelocityToRef(e,t,i){const s=this._getPluginReference(e,i),r=this._hknp.HP_Body_GetAngularVelocity(s.hpBodyId)[1];this._v3ToBvecRef(r,t)}setPhysicsBodyTransformation(e,t){const i=e.transformNode;if(e.numInstances>0){const t=i._thinInstanceDataStorage.matrixData;if(!t)return;const s=e.numInstances;this._createOrUpdateBodyInstances(e,e.getMotionType(),t,0,s,!0)}else this._hknp.HP_Body_SetQTransform(e._pluginData.hpBodyId,this._getTransformInfos(t))}setTargetTransform(e,t,i,s){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetTargetQTransform(e.hpBodyId,[this._bVecToV3(t),this._bQuatToV4(i)])}),s)}setGravityFactor(e,t,i){this._applyToBodyOrInstances(e,(e=>{this._hknp.HP_Body_SetGravityFactor(e.hpBodyId,t)}),i)}getGravityFactor(e,t){const i=this._getPluginReference(e,t);return this._hknp.HP_Body_GetGravityFactor(i.hpBodyId)[1]}disposeBody(e){if(e._pluginDataInstances&&e._pluginDataInstances.length>0)for(const t of e._pluginDataInstances)this._hknp.HP_Body_Release(t.hpBodyId),t.hpBodyId=void 0;e._pluginData&&(this._hknp.HP_Body_Release(e._pluginData.hpBodyId),e._pluginData.hpBodyId=void 0)}initShape(e,t,i){switch(t){case eA.SPHERE:{const t=i.radius||1,s=i.center?this._bVecToV3(i.center):[0,0,0];e._pluginData=this._hknp.HP_Shape_CreateSphere(s,t)[1]}break;case eA.BOX:{const t=i.rotation?this._bQuatToV4(i.rotation):[0,0,0,1],s=i.extents?this._bVecToV3(i.extents):[1,1,1],r=i.center?this._bVecToV3(i.center):[0,0,0];e._pluginData=this._hknp.HP_Shape_CreateBox(r,t,s)[1]}break;case eA.CAPSULE:{const t=i.pointA?this._bVecToV3(i.pointA):[0,0,0],s=i.pointB?this._bVecToV3(i.pointB):[0,1,0],r=i.radius||0;e._pluginData=this._hknp.HP_Shape_CreateCapsule(t,s,r)[1]}break;case eA.CONTAINER:e._pluginData=this._hknp.HP_Shape_CreateContainer()[1];break;case eA.CYLINDER:{const t=i.pointA?this._bVecToV3(i.pointA):[0,0,0],s=i.pointB?this._bVecToV3(i.pointB):[0,1,0],r=i.radius||0;e._pluginData=this._hknp.HP_Shape_CreateCylinder(t,s,r)[1]}break;case eA.CONVEX_HULL:case eA.MESH:{const s=i.mesh;if(!s)throw new Error("No mesh provided to create physics shape.");{const r=!!i.includeChildMeshes,n=t!=eA.CONVEX_HULL,o=new DA(s,n,s?.getScene());o.addNodeMeshes(s,r);const a=o.getVertices(this._hknp),l=a.numObjects/3;if(t==eA.CONVEX_HULL)e._pluginData=this._hknp.HP_Shape_CreateConvexHull(a.offset,l)[1];else{const t=o.getTriangles(this._hknp),i=t.numObjects/3;e._pluginData=this._hknp.HP_Shape_CreateMesh(a.offset,l,t.offset,i)[1],o.freeBuffer(this._hknp,t)}o.freeBuffer(this._hknp,a)}}break;case eA.HEIGHTFIELD:if(!(i.numHeightFieldSamplesX&&i.numHeightFieldSamplesZ&&i.heightFieldSizeX&&i.heightFieldSizeZ&&i.heightFieldData))throw new Error("Missing required heightfield parameters");{const t=i.numHeightFieldSamplesX*i.numHeightFieldSamplesZ,s=4*t,r=this._hknp._malloc(s),n=new Float32Array(this._hknp.HEAPU8.buffer,r,t);for(let e=0;e0?e._pluginDataInstances[0]:e._pluginData,i=this._hknp.HP_Body_GetShape(t.hpBodyId)[1],s=this._hknp.HP_Shape_CreateDebugDisplayGeometry(i);if(s[0]!=this._hknp.Result.RESULT_OK)return{positions:[],indices:[]};const r=this._hknp.HP_DebugGeometry_GetInfo(s[1])[1],n=new Float32Array(this._hknp.HEAPU8.buffer,r[0],3*r[1]),o=new Uint32Array(this._hknp.HEAPU8.buffer,r[2],3*r[3]),a=n.slice(0),l=o.slice(0);return this._hknp.HP_DebugGeometry_Release(s[1]),{positions:a,indices:l}}disposeShape(e){this._hknp.HP_Shape_Release(e._pluginData),e._pluginData=void 0}initConstraint(e,t,i,s,r){const n=e.type,o=e.options;if(!n||!o)return void Ne.Warn("No constraint type or options. Constraint is invalid.");if(t._pluginDataInstances.length>0&&void 0===s||i._pluginDataInstances.length>0&&void 0===r)return void Ne.Warn("Body is instanced but no instance index was specified. Constraint will not be applied.");e._pluginData=e._pluginData??[];const a=this._hknp.HP_Constraint_Create()[1];e._pluginData.push(a);const l=this._getPluginReference(t,s).hpBodyId,h=this._getPluginReference(i,r).hpBodyId;this._hknp.HP_Constraint_SetParentBody(a,l),this._hknp.HP_Constraint_SetChildBody(a,h),this._constraintToBodyIdPair.set(a[0],[l[0],h[0]]);const c=o.pivotA?this._bVecToV3(o.pivotA):this._bVecToV3(_e.Zero()),u=o.axisA??new _e(1,0,0),d=this._tmpVec3[0];o.perpAxisA?d.copyFrom(o.perpAxisA):u.getNormalToRef(d),this._hknp.HP_Constraint_SetAnchorInParent(a,c,this._bVecToV3(u),this._bVecToV3(d));const _=o.pivotB?this._bVecToV3(o.pivotB):this._bVecToV3(_e.Zero()),p=o.axisB??new _e(1,0,0),f=this._tmpVec3[0];if(o.perpAxisB?f.copyFrom(o.perpAxisB):p.getNormalToRef(f),this._hknp.HP_Constraint_SetAnchorInChild(a,_,this._bVecToV3(p),this._bVecToV3(f)),e._initOptions||(e._initOptions={axisA:u.clone(),axisB:p.clone(),perpAxisA:d.clone(),perpAxisB:f.clone(),pivotA:new _e(c[0],c[1],c[2]),pivotB:new _e(_[0],_[1],_[2])}),n==JE.LOCK)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==JE.DISTANCE){const e=o.maxDistance||0,t=this._hknp.ConstraintAxis.LINEAR_DISTANCE;this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(a,t,e),this._hknp.HP_Constraint_SetAxisMaxLimit(a,t,e)}else if(n==JE.HINGE)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==JE.PRISMATIC)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==JE.SLIDER)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.ANGULAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else if(n==JE.BALL_AND_SOCKET)this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_X,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Y,this._hknp.ConstraintAxisLimitMode.LOCKED),this._hknp.HP_Constraint_SetAxisMode(a,this._hknp.ConstraintAxis.LINEAR_Z,this._hknp.ConstraintAxisLimitMode.LOCKED);else{if(n!=JE.SIX_DOF)throw new Error("Unsupported Constraint Type.");{const t=e;for(const e of t.limits){const t=this._constraintAxisToNative(e.axis);0==(e.minLimit??-1)&&0==(e.maxLimit??-1)?this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LOCKED):(null!=e.minLimit&&(this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMinLimit(a,t,e.minLimit)),null!=e.maxLimit&&(this._hknp.HP_Constraint_SetAxisMode(a,t,this._hknp.ConstraintAxisLimitMode.LIMITED),this._hknp.HP_Constraint_SetAxisMaxLimit(a,t,e.maxLimit))),e.stiffness&&this._hknp.HP_Constraint_SetAxisStiffness(a,t,e.stiffness),e.damping&&this._hknp.HP_Constraint_SetAxisDamping(a,t,e.damping)}}}const m=!!o.collision;this._hknp.HP_Constraint_SetCollisionsEnabled(a,m),this._hknp.HP_Constraint_SetEnabled(a,!0)}getBodiesUsingConstraint(e){const t=[];for(const i of e._pluginData){const e=this._constraintToBodyIdPair.get(i[0]);if(e){const i=this._bodies.get(e[0]),s=this._bodies.get(e[1]);i&&s&&t.push({parentBody:i.body,parentBodyIndex:i.index,childBody:s.body,childBodyIndex:s.index})}}return t}addConstraint(e,t,i,s,r){this.initConstraint(i,e,t,s,r)}setEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetEnabled(i,t)}getEnabled(e){const t=e._pluginData&&e._pluginData[0];return!!t&&this._hknp.HP_Constraint_GetEnabled(t)[1]}setCollisionsEnabled(e,t){for(const i of e._pluginData)this._hknp.HP_Constraint_SetCollisionsEnabled(i,t)}getCollisionsEnabled(e){const t=e._pluginData&&e._pluginData[0];return!!t&&this._hknp.HP_Constraint_GetCollisionsEnabled(t)[1]}setAxisFriction(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisFriction(s,this._constraintAxisToNative(t),i)}getAxisFriction(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisFriction(i,this._constraintAxisToNative(t))[1]:null}setAxisMode(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMode(s,this._constraintAxisToNative(t),this._limitModeToNative(i))}getAxisMode(e,t){const i=e._pluginData&&e._pluginData[0];if(i){const e=this._hknp.HP_Constraint_GetAxisMode(i,this._constraintAxisToNative(t))[1];return this._nativeToLimitMode(e)}return null}setAxisMinLimit(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMinLimit(s,this._constraintAxisToNative(t),i)}getAxisMinLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMinLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMaxLimit(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMaxLimit(s,this._constraintAxisToNative(t),i)}getAxisMaxLimit(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMaxLimit(i,this._constraintAxisToNative(t))[1]:null}setAxisMotorType(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorType(s,this._constraintAxisToNative(t),this._constraintMotorTypeToNative(i))}getAxisMotorType(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._nativeToMotorType(this._hknp.HP_Constraint_GetAxisMotorType(i,this._constraintAxisToNative(t))[1]):null}setAxisMotorTarget(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorTarget(s,this._constraintAxisToNative(t),i)}getAxisMotorTarget(e,t){return e._pluginData&&e._pluginData[0]?this._hknp.HP_Constraint_GetAxisMotorTarget(e._pluginData,this._constraintAxisToNative(t))[1]:null}setAxisMotorMaxForce(e,t,i){for(const s of e._pluginData)this._hknp.HP_Constraint_SetAxisMotorMaxForce(s,this._constraintAxisToNative(t),i)}getAxisMotorMaxForce(e,t){const i=e._pluginData&&e._pluginData[0];return i?this._hknp.HP_Constraint_GetAxisMotorMaxForce(i,this._constraintAxisToNative(t))[1]:null}disposeConstraint(e){for(const t of e._pluginData)this._hknp.HP_Constraint_SetEnabled(t,!1),this._hknp.HP_Constraint_Release(t);e._pluginData.length=0}_populateHitData(e,t){const i=this._bodies.get(e[0][0]);t.body=i?.body,t.bodyIndex=i?.index;const s=this._shapes.get(e[1][0]);t.shape=s;const r=e[3],n=e[4],o=e[5];t.setHitData({x:n[0],y:n[1],z:n[2]},{x:r[0],y:r[1],z:r[2]},o)}raycast(e,t,i,s){const r=s?.membership??-1,n=s?.collideWith??-1;i.reset(e,t);const o=[BigInt(0)],a=[this._bVecToV3(e),this._bVecToV3(t),[r,n],!1,o];if(this._hknp.HP_World_CastRayWithCollector(this.world,this._queryCollector,a),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[,e]=this._hknp.HP_QueryCollector_GetCastRayResult(this._queryCollector,0)[1];this._populateHitData(e,i),i.calculateHitDistance()}}pointProximity(e,t){const i=e?.collisionFilter?.membership??-1,s=e?.collisionFilter?.collideWith??-1;t.reset();const r=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[this._bVecToV3(e.position),e.maxDistance,[i,s],e.shouldHitTriggers,r];if(this._hknp.HP_World_PointProximityWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,i]=this._hknp.HP_QueryCollector_GetPointProximityResult(this._queryCollector,0)[1];this._populateHitData(i,t),t.setHitDistance(e)}}shapeProximity(e,t,i){t.reset(),i.reset();const s=e.shape._pluginData,r=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[s,this._bVecToV3(e.position),this._bQuatToV4(e.rotation),e.maxDistance,e.shouldHitTriggers,r];if(this._hknp.HP_World_ShapeProximityWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,s,r]=this._hknp.HP_QueryCollector_GetShapeProximityResult(this._queryCollector,0)[1];this._populateHitData(s,t),this._populateHitData(r,i),t.setHitDistance(e),i.setHitDistance(e)}}shapeCast(e,t,i){t.reset(),i.reset();const s=e.shape._pluginData,r=e.ignoreBody?[BigInt(e.ignoreBody._pluginData.hpBodyId[0])]:[BigInt(0)],n=[s,this._bQuatToV4(e.rotation),this._bVecToV3(e.startPosition),this._bVecToV3(e.endPosition),e.shouldHitTriggers,r];if(this._hknp.HP_World_ShapeCastWithCollector(this.world,this._queryCollector,n),this._hknp.HP_QueryCollector_GetNumHits(this._queryCollector)[1]>0){const[e,s,r]=this._hknp.HP_QueryCollector_GetShapeCastResult(this._queryCollector,0)[1];this._populateHitData(s,t),this._populateHitData(r,i),t.setHitFraction(e),i.setHitFraction(e)}}getCollisionObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionObservable.get(t);return i||(i=new K,this._bodyCollisionObservable.set(t,i)),i}getCollisionEndedObservable(e){const t=e._pluginData.hpBodyId[0];let i=this._bodyCollisionEndedObservable.get(t);return i||(i=new K,this._bodyCollisionEndedObservable.set(t,i)),i}setCollisionCallbackEnabled(e,t){const i=this._hknp.EventType.COLLISION_STARTED.value|this._hknp.EventType.COLLISION_CONTINUED.value|this._hknp.EventType.COLLISION_FINISHED.value;e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach((e=>{this._hknp.HP_Body_SetEventMask(e.hpBodyId,t?i:0)})):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,t?i:0)}setCollisionEndedCallbackEnabled(e,t){const i=this._getPluginReference(e);let s=this._hknp.HP_Body_GetEventMask(i.hpBodyId)[1];s=t?s|this._hknp.EventType.COLLISION_FINISHED.value:s&~this._hknp.EventType.COLLISION_FINISHED.value,e._pluginDataInstances&&e._pluginDataInstances.length?e._pluginDataInstances.forEach((e=>{this._hknp.HP_Body_SetEventMask(e.hpBodyId,s)})):e._pluginData&&this._hknp.HP_Body_SetEventMask(e._pluginData.hpBodyId,s)}_notifyTriggers(){let e=this._hknp.HP_World_GetTriggerEvents(this.world)[1];const t=new LA;for(;e;){LA.readToRef(this._hknp.HEAPU8.buffer,e,t);const i=this._bodies.get(t.bodyIdA),s=this._bodies.get(t.bodyIdB);if(i&&s){const e={collider:i.body,colliderIndex:i.index,collidedAgainst:s.body,collidedAgainstIndex:s.index,type:this._nativeTriggerCollisionValueToCollisionType(t.type)};this.onTriggerCollisionObservable.notifyObservers(e)}e=this._hknp.HP_World_GetNextTriggerEvent(this.world,e)}}_notifyCollisions(){let e=this._hknp.HP_World_GetCollisionEvents(this.world)[1];const t=new FA,i=Number(this.world);for(;e;){FA.readToRef(this._hknp.HEAPU8.buffer,e,t);const s=this._bodies.get(t.contactOnA.bodyId),r=this._bodies.get(t.contactOnB.bodyId);if(s&&r){const e={collider:s.body,colliderIndex:s.index,collidedAgainst:r.body,collidedAgainstIndex:r.index,type:this._nativeCollisionValueToCollisionType(t.type)};if(e.type===iA.COLLISION_FINISHED)this.onCollisionEndedObservable.notifyObservers(e);else{t.contactOnB.position.subtractToRef(t.contactOnA.position,this._tmpVec3[0]);const i=_e.Dot(this._tmpVec3[0],t.contactOnA.normal);e.point=t.contactOnA.position,e.distance=i,e.impulse=t.impulseApplied,e.normal=t.contactOnA.normal,this.onCollisionObservable.notifyObservers(e)}if(this._bodyCollisionObservable.size&&e.type!==iA.COLLISION_FINISHED){const i=this._bodyCollisionObservable.get(t.contactOnA.bodyId),n=this._bodyCollisionObservable.get(t.contactOnB.bodyId);i?i.notifyObservers(e):n&&(e.collider=r.body,e.colliderIndex=r.index,e.collidedAgainst=s.body,e.collidedAgainstIndex=s.index,e.normal=t.contactOnB.normal,n.notifyObservers(e))}else if(this._bodyCollisionEndedObservable.size){const i=this._bodyCollisionEndedObservable.get(t.contactOnA.bodyId),n=this._bodyCollisionEndedObservable.get(t.contactOnB.bodyId);i?i.notifyObservers(e):n&&(e.collider=r.body,e.colliderIndex=r.index,e.collidedAgainst=s.body,e.collidedAgainstIndex=s.index,e.normal=t.contactOnB.normal,n.notifyObservers(e))}}e=this._hknp.HP_World_GetNextCollisionEvent(i,e)}}get numBodies(){return this._hknp.HP_World_GetNumBodies(this.world)[1]}dispose(){this._queryCollector&&(this._hknp.HP_QueryCollector_Release(this._queryCollector),this._queryCollector=void 0),this.world&&(this._hknp.HP_World_Release(this.world),this.world=void 0)}_v3ToBvecRef(e,t){t.set(e[0],e[1],e[2])}_bVecToV3(e){return[e._x,e._y,e._z]}_bQuatToV4(e){return[e._x,e._y,e._z,e._w]}_constraintMotorTypeToNative(e){switch(e){case tA.POSITION:return this._hknp.ConstraintMotorType.POSITION;case tA.VELOCITY:return this._hknp.ConstraintMotorType.VELOCITY}return this._hknp.ConstraintMotorType.NONE}_nativeToMotorType(e){switch(e){case this._hknp.ConstraintMotorType.POSITION:return tA.POSITION;case this._hknp.ConstraintMotorType.VELOCITY:return tA.VELOCITY}return tA.NONE}_materialCombineToNative(e){switch(e){case nA.GEOMETRIC_MEAN:return this._hknp.MaterialCombine.GEOMETRIC_MEAN;case nA.MINIMUM:return this._hknp.MaterialCombine.MINIMUM;case nA.MAXIMUM:return this._hknp.MaterialCombine.MAXIMUM;case nA.ARITHMETIC_MEAN:return this._hknp.MaterialCombine.ARITHMETIC_MEAN;case nA.MULTIPLY:return this._hknp.MaterialCombine.MULTIPLY}}_nativeToMaterialCombine(e){switch(e){case this._hknp.MaterialCombine.GEOMETRIC_MEAN:return nA.GEOMETRIC_MEAN;case this._hknp.MaterialCombine.MINIMUM:return nA.MINIMUM;case this._hknp.MaterialCombine.MAXIMUM:return nA.MAXIMUM;case this._hknp.MaterialCombine.ARITHMETIC_MEAN:return nA.ARITHMETIC_MEAN;case this._hknp.MaterialCombine.MULTIPLY:return nA.MULTIPLY;default:return}}_constraintAxisToNative(e){switch(e){case ZE.LINEAR_X:return this._hknp.ConstraintAxis.LINEAR_X;case ZE.LINEAR_Y:return this._hknp.ConstraintAxis.LINEAR_Y;case ZE.LINEAR_Z:return this._hknp.ConstraintAxis.LINEAR_Z;case ZE.ANGULAR_X:return this._hknp.ConstraintAxis.ANGULAR_X;case ZE.ANGULAR_Y:return this._hknp.ConstraintAxis.ANGULAR_Y;case ZE.ANGULAR_Z:return this._hknp.ConstraintAxis.ANGULAR_Z;case ZE.LINEAR_DISTANCE:return this._hknp.ConstraintAxis.LINEAR_DISTANCE}}_nativeToLimitMode(e){switch(e){case this._hknp.ConstraintAxisLimitMode.FREE:return qE.FREE;case this._hknp.ConstraintAxisLimitMode.LIMITED:return qE.LIMITED;case this._hknp.ConstraintAxisLimitMode.LOCKED:return qE.LOCKED}return qE.FREE}_limitModeToNative(e){switch(e){case qE.FREE:return this._hknp.ConstraintAxisLimitMode.FREE;case qE.LIMITED:return this._hknp.ConstraintAxisLimitMode.LIMITED;case qE.LOCKED:return this._hknp.ConstraintAxisLimitMode.LOCKED}}_nativeCollisionValueToCollisionType(e){switch(e){case this._hknp.EventType.COLLISION_STARTED.value:return iA.COLLISION_STARTED;case this._hknp.EventType.COLLISION_FINISHED.value:return iA.COLLISION_FINISHED;case this._hknp.EventType.COLLISION_CONTINUED.value:return iA.COLLISION_CONTINUED}return iA.COLLISION_STARTED}_nativeTriggerCollisionValueToCollisionType(e){switch(e){case 8:return iA.TRIGGER_ENTERED;case 16:return iA.TRIGGER_EXITED}return iA.TRIGGER_ENTERED}}Hr.prototype.getPhysicsEngine=function(){return this._physicsEngine},Hr.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(or.NAME_PHYSICSENGINE);i||(i=new kA(this),this._addComponent(i));try{if(t&&1!==t?.getPluginVersion()){if(2!==t?.getPluginVersion())throw new Error("Unsupported Physics plugin version.");this._physicsEngine=new hA(e,t)}else this._physicsEngine=new ux(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return Ne.Error(e.message),!1}},Hr.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},Hr.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},Hr.prototype.deleteCompoundImpostor=function(e){const t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},Hr.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){const t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class kA{constructor(e){this.name=or.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new K,this.scene.onAfterPhysicsObservable=new K,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?1e3*this.scene._physicsEngine.getTimeStep():1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(lo.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)}))))},enumerable:!0,configurable:!0}),lo.prototype.getPhysicsBody=function(){return this.physicsBody},lo.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this},lo.prototype.applyAngularImpulse=function(e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyAngularImpulse(e),this};class VA{static GetContactPointToRef(e,t,i,s,r){const n=e.getScene().getPhysicsEngine(),o=n?.getPluginVersion();if(1===o){const r=new Ua(t,i).intersectsMesh(e);if(r.hit&&r.pickedPoint)return s.copyFrom(r.pickedPoint),!0}else if(2===o)return e.physicsBody.getObjectCenterWorldToRef(s,r),!0;return!1}static HasAppliedForces(e,t){return e.getMotionType(t)===sA.STATIC||0===(e.getMassProperties(t)?.mass??0)||0===e.transformNode?.getTotalVertices()}static IsInsideCylinder(e,t,i,s){const r=ve.Vector3[0];return e.subtractToRef(t,r),Math.abs(r.x)<=i&&Math.abs(r.z)<=i&&r.y>=0&&r.y<=s}}class UA{constructor(e){this._hitData={force:new _e,contactPoint:new _e,distanceFromOrigin:0},this._scene=e,this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine||Ne.Warn("Physics engine not enabled. Please enable the physics before you can use the methods.")}applyRadialExplosionImpulse(e,t,i,s){if(!this._physicsEngine)return Ne.Warn("Physics engine not enabled. Please enable the physics before you call this method."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;let r=!1;if("number"==typeof t){const e=t;(t=new XA).radius=e,t.strength=i??t.strength,t.falloff=s??t.falloff}else r=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);const n=new GA(this._scene,t),o=this._hitData;if(1===this._physicsEngine.getPluginVersion()){const t=Array();this._physicsEngine.getImpostors().forEach((i=>{n.getImpostorHitData(i,e,o)&&(i.applyImpulse(o.force,o.contactPoint),r&&t.push({impostor:i,hitData:this._copyPhysicsHitData(o)}))})),n.triggerAffectedImpostorsCallback(t)}else this._applicationForBodies(n,e,o,r,((e,t)=>{e.applyImpulse(t.force,t.contactPoint,t.instanceIndex)}));return n.dispose(!1),n}applyRadialExplosionForce(e,t,i,s){if(!this._physicsEngine)return Ne.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;let r=!1;if("number"==typeof t){const e=t;(t=new XA).radius=e,t.strength=i??t.strength,t.falloff=s??t.falloff}else r=!(!t.affectedImpostorsCallback&&!t.affectedBodiesCallback);const n=new GA(this._scene,t),o=this._hitData;if(1===this._physicsEngine.getPluginVersion()){const t=Array();this._physicsEngine.getImpostors().forEach((i=>{n.getImpostorHitData(i,e,o)&&(i.applyForce(o.force,o.contactPoint),r&&t.push({impostor:i,hitData:this._copyPhysicsHitData(o)}))})),n.triggerAffectedImpostorsCallback(t)}else this._applicationForBodies(n,e,o,r,((e,t)=>{e.applyForce(t.force,t.contactPoint,t.instanceIndex)}));return n.dispose(!1),n}_applicationForBodies(e,t,i,s,r){const n=Array(),o=this._physicsEngine.getBodies();for(const a of o)a.iterateOverAllInstances(((o,a)=>{e.getBodyHitData(o,t,i,a)&&(r(o,i),s&&n.push({body:o,hitData:this._copyPhysicsHitData(i)}))}));e.triggerAffectedBodiesCallback(n)}gravitationalField(e,t,i,s){if(!this._physicsEngine)return Ne.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new XA).radius=e,t.strength=i??t.strength,t.falloff=s??t.falloff}const r=new zA(this,this._scene,e,t);return r.dispose(!1),r}updraft(e,t,i,s,r){if(!this._physicsEngine)return Ne.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new YA).radius=e,t.strength=i??t.strength,t.height=s??t.height,t.updraftMode=r??t.updraftMode}const n=new WA(this._scene,e,t);return n.dispose(!1),n}vortex(e,t,i,s){if(!this._physicsEngine)return Ne.Warn("Physics engine not enabled. Please enable the physics before you call the PhysicsHelper."),null;if(1===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getImpostors().length)return null;if(2===this._physicsEngine.getPluginVersion()&&0===this._physicsEngine.getBodies().length)return null;if("number"==typeof t){const e=t;(t=new QA).radius=e,t.strength=i??t.strength,t.height=s??t.height}const r=new HA(this._scene,e,t);return r.dispose(!1),r}_copyPhysicsHitData(e){return{force:e.force.clone(),contactPoint:e.contactPoint.clone(),distanceFromOrigin:e.distanceFromOrigin,instanceIndex:e.instanceIndex}}}class GA{constructor(e,t){this._scene=e,this._options=t,this._dataFetched=!1,this._options={...new XA,...this._options}}getData(){return this._dataFetched=!0,{sphere:this._sphere}}_getHitData(e,t,i,s){const r=ve.Vector3[0];r.copyFrom(t).subtractInPlace(i);const n=ve.Vector3[1];if(!VA.GetContactPointToRef(e,i,r,n,s.instanceIndex))return!1;const o=_e.Distance(i,n);if(o>this._options.radius)return!1;const a=this._options.falloff===oA.Constant?this._options.strength:this._options.strength*(1-o/this._options.radius);return r.scaleInPlace(a),s.force.copyFrom(r),s.contactPoint.copyFrom(n),s.distanceFromOrigin=o,!0}getBodyHitData(e,t,i,s){if(VA.HasAppliedForces(e,s))return!1;const r=e.transformNode,n=e.getObjectCenterWorld(s);return i.instanceIndex=s,this._getHitData(r,n,t,i)}getImpostorHitData(e,t,i){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const s=e.object;if(!this._intersectsWithSphere(s,t,this._options.radius))return!1;const r=e.getObjectCenter();return this._getHitData(s,r,t,i),!0}triggerAffectedImpostorsCallback(e){this._options.affectedImpostorsCallback&&this._options.affectedImpostorsCallback(e)}triggerAffectedBodiesCallback(e){this._options.affectedBodiesCallback&&this._options.affectedBodiesCallback(e)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout((()=>{this._dataFetched||this._sphere.dispose()}),0))}_prepareSphere(){this._sphere||(this._sphere=_d("radialExplosionEventSphere",this._options.sphere,this._scene),this._sphere.isVisible=!1)}_intersectsWithSphere(e,t,i){return this._prepareSphere(),this._sphere.position=t,this._sphere.scaling.setAll(2*i),this._sphere._updateBoundingInfo(),this._sphere.computeWorldMatrix(!0),this._sphere.intersectsMesh(e,!0)}}class zA{constructor(e,t,i,s){this._physicsHelper=e,this._scene=t,this._origin=i,this._options=s,this._dataFetched=!1,this._options={...new XA,...this._options},this._tickCallback=()=>this._tick(),this._options.strength=-1*this._options.strength}getData(){return this._dataFetched=!0,{sphere:this._sphere}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._sphere&&(e?this._sphere.dispose():setTimeout((()=>{this._dataFetched||this._sphere.dispose()}),0))}_tick(){if(this._sphere)this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);else{const e=this._physicsHelper.applyRadialExplosionForce(this._origin,this._options);e&&(this._sphere=e.getData().sphere?.clone("radialExplosionEventSphereClone"))}}}class WA{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=_e.Zero(),this._originDirection=_e.Zero(),this._cylinderPosition=_e.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new YA,...this._options},this._origin.addToRef(new _e(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new _e(0,this._options.height,0),this._originTop),this._options.updraftMode===aA.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout((()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)}),0))}_getHitData(e,t){let i;i=this._options.updraftMode===aA.Perpendicular?this._originDirection:e.subtract(this._originTop);const s=_e.Distance(this._origin,e),r=-1*this._options.strength,n=i.multiplyByFloats(r,r,r);t.force.copyFrom(n),t.contactPoint.copyFrom(e),t.distanceFromOrigin=s}_getBodyHitData(e,t,i){if(VA.HasAppliedForces(e))return!1;const s=e.getObjectCenterWorld(i);return!!VA.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(s,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const s=e.getObjectCenter();return this._getHitData(s,t),!0}_tick(){const e=WA._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=$u("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))}}WA._HitData={force:new _e,contactPoint:new _e,distanceFromOrigin:0};class HA{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=_e.Zero(),this._cylinderPosition=_e.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new QA,...this._options},this._origin.addToRef(new _e(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new _e(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout((()=>{this._dataFetched||this._cylinder.dispose()}),0))}_getHitData(e,t,i){const s=HA._OriginOnPlane;s.set(this._origin.x,t.y,this._origin.z);const r=ve.Vector3[0];t.subtractToRef(s,r);const n=ve.Vector3[1];if(!VA.GetContactPointToRef(e,s,r,n,i.instanceIndex))return!1;const o=_e.Distance(n,s)/this._options.radius,a=ve.Vector3[2];let l,h,c;if(n.normalizeToRef(a),o>this._options.centripetalForceThreshold&&a.negateInPlace(),o>this._options.centripetalForceThreshold)l=a.x*this._options.centripetalForceMultiplier,h=a.y*this._options.updraftForceMultiplier,c=a.z*this._options.centripetalForceMultiplier;else{const e=_e.Cross(s,t).normalize();l=(e.x+a.x)*this._options.centrifugalForceMultiplier,h=this._originTop.y*this._options.updraftForceMultiplier,c=(e.z+a.z)*this._options.centrifugalForceMultiplier}const u=ve.Vector3[3];return u.set(l,h,c),u.scaleInPlace(this._options.strength),i.force.copyFrom(u),i.contactPoint.copyFrom(t),i.distanceFromOrigin=o,!0}_getBodyHitData(e,t,i){if(VA.HasAppliedForces(e,i))return!1;const s=e.transformNode,r=e.getObjectCenterWorld(i);return!!VA.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(s,r,t))}_getImpostorHitData(e,t){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const s=e.getObjectCenter();return this._getHitData(i,s,t),!0}_tick(){const e=HA._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=$u("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}}HA._OriginOnPlane=_e.Zero(),HA._HitData={force:new _e,contactPoint:new _e,distanceFromOrigin:0};class XA{constructor(){this.radius=5,this.strength=10,this.falloff=oA.Constant,this.sphere={segments:32,diameter:1}}}class YA{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=aA.Center}}class QA{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}!function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"}(oA||(oA={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(aA||(aA={}));class jA extends hx{constructor(){super(...arguments),this._hitDistance=0}get hitDistance(){return this._hitDistance}setHitDistance(e){this._hitDistance=e}reset(){super.reset(),this._hitDistance=0}}class KA extends hx{constructor(){super(...arguments),this._hitFraction=0}get hitFraction(){return this._hitFraction}setHitFraction(e){this._hitFraction=e}}Bi.ShadersStore.blackAndWhitePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}";class $A extends Vl{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,s,r,n){super(e,"blackAndWhite",["degree"],null,t,i,s,r,n),this.degree=1,this.onApplyObservable.add((e=>{e.setFloat("degree",this.degree)}))}static _Parse(e,t,i,s){return St.Parse((()=>new $A(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}Ze([rt()],$A.prototype,"degree",void 0),z("BABYLON.BlackAndWhitePostProcess",$A);class qA{constructor(e,t,i,s){this._name=t,this._singleInstance=s||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let e=0;e{const t=s.attachPostProcess(e);this._indicesForCamera[r].push(t)})),this._cameras[r]||(this._cameras[r]=s)}}_detachCameras(e){const t=Ds.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)})),this._cameras[s]&&(this._cameras[s]=null),delete this._indicesForCamera[s]}}_enable(e){const t=Ds.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)}))}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}Bi.ShadersStore.extractHighlightsPixelShader="#include\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}";class ZA extends Vl{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,s,r,n,null,o,void 0,null,a),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add((e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess),e.setFloat("threshold",Math.pow(this.threshold,$)),e.setFloat("exposure",this._exposure)}))}}Ze([rt()],ZA.prototype,"threshold",void 0),z("BABYLON.ExtractHighlightsPostProcess",ZA);Bi.ShadersStore.bloomMergePixelShader="uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); }\n";class JA extends Vl{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,s,r,n,o,a,l,h=0,c=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],r,n,o,a,l,null,h,void 0,null,!0),this.weight=1,this.weight=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)})),c||this.updateEffect()}}Ze([rt()],JA.prototype,"weight",void 0),z("BABYLON.BloomMergePostProcess",JA);class eP extends qA{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,s,r=0,n=!1){super(e.getEngine(),"bloom",(()=>this._effects),!0),this._bloomScale=t,this._effects=[],this._downscale=new ZA("highlights",1,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._blurX=new mg("horizontal blur",new de(1,0),10,t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new mg("vertical blur",new de(0,1),10,t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=s,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new JA("bloomMerge",this._downscale,this._blurY,i,t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)}))}static _Parse(e,t,i,s){return St.Parse((()=>new tP(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,s)}}Ze([rt()],tP.prototype,"aberrationAmount",void 0),Ze([rt()],tP.prototype,"radialIntensity",void 0),Ze([rt()],tP.prototype,"direction",void 0),Ze([rt()],tP.prototype,"centerPosition",void 0),Ze([rt()],tP.prototype,"screenWidth",void 0),Ze([rt()],tP.prototype,"screenHeight",void 0),z("BABYLON.ChromaticAberrationPostProcess",tP);Bi.ShadersStore.circleOfConfusionPixelShader="uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float depth=texture2D(depthSampler,vUV).r;\n#define CUSTOM_COC_DEPTH\nfloat pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; \n#define CUSTOM_COC_PIXELDISTANCE\nfloat coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);}\n";class iP extends Vl{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,s,r,n,o,a=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,s,r,n,o,null,a,void 0,null,l),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add((e=>{if(!this._depthTexture)return void Ne.Warn("No depth texture set on CircleOfConfusionPostProcess");e.setTexture("depthSampler",this._depthTexture);const t=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",t);const i=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",i.minZ,i.maxZ-i.minZ)}))}set depthTexture(e){this._depthTexture=e}}Ze([rt()],iP.prototype,"lensSize",void 0),Ze([rt()],iP.prototype,"fStop",void 0),Ze([rt()],iP.prototype,"focusDistance",void 0),Ze([rt()],iP.prototype,"focalLength",void 0),z("BABYLON.CircleOfConfusionPostProcess",iP);Bi.ShadersStore.colorCorrectionPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D colorTable; \nvarying vec2 vUV;const float SLICE_COUNT=16.0; \nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}";class sP extends Vl{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"colorCorrection",null,["colorTable"],i,s,r,n,o);const a=s?.getScene()||null;this._colorTableTexture=new Pa(t,a,!0,!1,Pa.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=Pa.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=Pa.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,s){return St.Parse((()=>new sP(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}Ze([rt()],sP.prototype,"colorTableUrl",void 0),z("BABYLON.ColorCorrectionPostProcess",sP);Bi.ShadersStore.convolutionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9];\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}";class rP extends Vl{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,s,r,n,o,a=0){super(e,"convolution",["kernel","screenSize"],null,i,s,r,n,o,null,a),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,s){return St.Parse((()=>new rP(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType)),e,i,s)}}rP.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],rP.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],rP.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],rP.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],rP.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],rP.GaussianKernel=[0,1,0,1,1,1,0,1,0],Ze([rt()],rP.prototype,"kernel",void 0),z("BABYLON.ConvolutionPostProcess",rP);class nP extends mg{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,s,r,n,o,a=null,l=Pa.BILINEAR_SAMPLINGMODE,h,c,u=0,d=!1,_=5){super(e,i,s,r,n,2,h,c,u,"#define DOF 1\n",d,_),this.direction=i,this.externalTextureSamplerBinding=!!a,this.onApplyObservable.add((e=>{null!=a&&e.setTextureFromPostProcess("textureSampler",a),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)}))}}Ze([rt()],nP.prototype,"direction",void 0),z("BABYLON.DepthOfFieldBlurPostProcess",nP);Bi.ShadersStore.depthOfFieldMergePixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;\n#if BLUR_LEVEL==0\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);}\n#endif\n#if BLUR_LEVEL==2\nif(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);}\n#endif\n}\n";class oP extends Vl{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,s,r,n,o,a,l,h=0,c=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],r,n,o,a,l,null,h,void 0,null,!0),this._blurSteps=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),s.forEach(((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(s.length-i-1),t)}))})),c||this.updateEffect()}updateEffect(e=null,t=null,i=null,s,r,n){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,s,r,n)}}var aP;!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(aP||(aP={}));class lP extends qA{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=aP.Low,s=0,r=!1){super(e.getEngine(),"depth of field",(()=>this._effects),!0),this._effects=[];const n=e.getEngine(),o=n.isWebGPU||n.version>1?6:5;this._circleOfConfusion=new iP("circleOfConfusion",t,1,null,Pa.BILINEAR_SAMPLINGMODE,n,!1,s,r),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let a=1,l=15;switch(i){case aP.High:a=3,l=51;break;case aP.Medium:a=2,l=31;break;default:l=15,a=1}const h=l/Math.pow(2,a-1);let c=1;for(let t=0;tnew hP(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}z("BABYLON.DisplayPassPostProcess",hP);Bi.ShadersStore.filterPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}";class cP extends Vl{getClassName(){return"FilterPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"filter",["kernelMatrix"],null,i,s,r,n,o),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,s){return St.Parse((()=>new cP(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}Ze([ft()],cP.prototype,"kernelMatrix",void 0),z("BABYLON.FilterPostProcess",cP);Bi.ShadersStore.fxaaPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)\n{lumaN=lumaW;}\nif (!horzSpan) \n{lumaS=lumaE;}\nif (horzSpan) \n{lengthSign=texelSize.y;}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN)\n{lengthSign=-lengthSign;}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) \n{posB.x+=lengthSign*0.5;}\nif (horzSpan)\n{posB.y+=lengthSign*0.5;}\nvec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) \n{lumaNN=lumaSS;}\nfloat gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) \n{posN.x-=offNP.x*3.0;}\nif (!doneN) \n{posN.y-=offNP.y*3.0;}\nbool doneNP=(!doneN) || (!doneP);if (!doneP) \n{posP.x+=offNP.x*3.0;}\nif (!doneP)\n{posP.y+=offNP.y*3.0;}\nif (doneNP)\n{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;}\nfloat dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan)\n{dstN=posM.y-posN.y;}\nif (!horzSpan) \n{dstP=posP.y-posM.y;}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{const t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)}))}_getDefines(){const e=this.getEngine();return e&&e.extractDriverInfo().toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,s){return St.Parse((()=>new uP(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}z("BABYLON.FxaaPostProcess",uP);Bi.ShadersStore.grainPixelShader="#include\nuniform sampler2D textureSampler; \nuniform float intensity;uniform float animatedSeed;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}";class dP extends Vl{getClassName(){return"GrainPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,s,r,n,null,o,void 0,null,a),this.intensity=30,this.animated=!1,this.onApplyObservable.add((e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)}))}static _Parse(e,t,i,s){return St.Parse((()=>new dP(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}Ze([rt()],dP.prototype,"intensity",void 0),Ze([rt()],dP.prototype,"animated",void 0),z("BABYLON.GrainPostProcess",dP);Bi.ShadersStore.highlightsPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }";class _P extends Vl{getClassName(){return"HighlightsPostProcess"}constructor(e,t,i,s,r,n,o=0){super(e,"highlights",null,null,t,i,s,r,n,null,o)}}Bi.ShadersStore.imageProcessingPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;}";class pP extends Vl{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null;const t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){const i=t.scenes;e=i[i.length-1]}else e=re.LastCreatedScene;this._imageProcessingConfiguration=e?e.imageProcessingConfiguration:new zs}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateParameters()}))),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,s,r,n,o=0,a){super(e,"imageProcessing",[],[],t,i,s,r,n,null,o,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:0,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},a?(a.applyByPostProcess=!0,this._attachImageProcessingConfiguration(a,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const t in this._defines){const i=this._defines[t];switch(typeof i){case"number":case"string":e+=`#define ${t} ${i};\n`;break;default:i&&(e+=`#define ${t};\n`)}}const t=["textureSampler"],i=["scale"];zs&&(zs.PrepareSamplers(t,this._defines),zs.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}Ze([rt()],pP.prototype,"_fromLinearSpace",void 0);Bi.IncludesShadersStore.mrtFragmentDeclaration="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n";Bi.ShadersStore.geometryPixelShader="#extension GL_EXT_draw_buffers : require\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\nprecision highp float;\n#ifdef BUMP\nvarying mat4 vWorldView;varying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nvarying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#ifdef NEED_UV\nvarying vec2 vUV;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIVITY)\n#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nuniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV;\n#endif\n#ifdef ALBEDOTEXTURE\nvarying vec2 vAlbedoUV;uniform sampler2D albedoSampler;\n#endif\n#ifdef REFLECTIVITYCOLOR\nuniform vec3 reflectivityColor;\n#endif\n#ifdef ALBEDOCOLOR\nuniform vec3 albedoColor;\n#endif\n#ifdef METALLIC\nuniform float metallic;\n#endif\n#if defined(ROUGHNESS) || defined(GLOSSINESS)\nuniform float glossiness;\n#endif\n#endif\n#if defined(ALPHATEST) && defined(NEED_UV)\nuniform sampler2D diffuseSampler;\n#endif\n#include\n#include[RENDER_TARGET_COUNT]\n#include\n#include\n#include\nvoid main() {\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nvec3 normalOutput;\n#ifdef BUMP\nvec3 normalW=normalize(vNormalW);\n#include\n#ifdef NORMAL_WORLDSPACE\nnormalOutput=normalW;\n#else\nnormalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0)));\n#endif\n#else\nnormalOutput=normalize(vNormalV);\n#endif\n#ifdef ENCODE_NORMAL\nnormalOutput=normalOutput*0.5+0.5;\n#endif\n#ifdef PREPASS\n#ifdef PREPASS_DEPTH\ngl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n#endif\n#ifdef PREPASS_NORMAL\ngl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0);\n#endif\n#else\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0);\n#endif\n#ifdef POSITION\ngl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);\n#endif\n#ifdef REFLECTIVITY\nvec4 reflectivity=vec4(0.0,0.0,0.0,1.0);\n#ifdef METALLICWORKFLOW\nfloat metal=1.0;float roughness=1.0;\n#ifdef ORMTEXTURE\nmetal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g;\n#endif\n#ifdef METALLIC\nmetal*=metallic;\n#endif\n#ifdef ROUGHNESS\nroughness*=(1.0-glossiness); \n#endif\nreflectivity.a-=roughness;vec3 color=vec3(1.0);\n#ifdef ALBEDOTEXTURE\ncolor=texture2D(albedoSampler,vAlbedoUV).rgb;\n#ifdef GAMMAALBEDO\ncolor=toLinearSpace(color);\n#endif\n#endif\n#ifdef ALBEDOCOLOR\ncolor*=albedoColor.xyz;\n#endif\nreflectivity.rgb=mix(vec3(0.04),color,metal);\n#else\n#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nreflectivity=texture2D(reflectivitySampler,vReflectivityUV);\n#ifdef GAMMAREFLECTIVITYTEXTURE\nreflectivity.rgb=toLinearSpace(reflectivity.rgb);\n#endif\n#else \n#ifdef REFLECTIVITYCOLOR\nreflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0;\n#endif\n#endif\n#ifdef GLOSSINESSS\nreflectivity.a*=glossiness; \n#endif\n#endif\ngl_FragData[REFLECTIVITY_INDEX]=reflectivity;\n#endif\n}\n";Bi.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;";Bi.IncludesShadersStore.geometryUboDeclaration="#include\n";Bi.ShadersStore.geometryVertexShader="precision highp float;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include<__decl__geometryVertex>\n#include\nattribute vec3 position;attribute vec3 normal;\n#ifdef NEED_UV\nvarying vec2 vUV;\n#ifdef ALPHATEST\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef BUMP\nuniform mat4 bumpMatrix;varying vec2 vBumpUV;\n#endif\n#ifdef REFLECTIVITY\nuniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef BUMP\nvarying mat4 vWorldView;\n#endif\n#ifdef BUMP\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nuniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include\n#include\nvec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0));\n#ifdef BUMP\nvWorldView=view*finalWorld;vNormalW=normalUpdated;\n#else\n#ifdef NORMAL_WORLDSPACE\nvNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#else\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));\n#endif\n#endif\nvViewPos=view*worldPos;\n#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n#if defined(POSITION) || defined(BUMP)\nvPositionW=worldPos.xyz/worldPos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#include\n#ifdef NEED_UV\n#ifdef UV1\n#if defined(ALPHATEST) && defined(ALPHATEST_UV1)\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#else\nvUV=uv;\n#endif\n#ifdef BUMP_UV1\nvBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV1\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV1\nvAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#endif\n#ifdef UV2\n#if defined(ALPHATEST) && defined(ALPHATEST_UV2)\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#else\nvUV=uv2;\n#endif\n#ifdef BUMP_UV2\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV2\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV2\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#endif\n#include\n}\n";const fP=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];mo(fP);class mP{get normalsAreUnsigned(){return this._normalsAreUnsigned}_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add((()=>{})))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===mP.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===mP.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===mP.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===mP.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===mP.NORMAL_TEXTURE_TYPE&&(this._normalIndex=t)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case mP.POSITION_TEXTURE_TYPE:return this._positionIndex;case mP.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case mP.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case mP.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case mP.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return-1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return"object"==typeof this._ratioOrDimensions?1:this._ratioOrDimensions}constructor(e,t=1,i=15,s){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new Ae(0,0,0,0),this._clearDepthColor=new Ae(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=s||{},mP._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const s=[],r=[er.PositionKind,er.NormalKind],n=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(s.push("#define ALPHATEST"),s.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&$c.BumpTextureEnabled&&(s.push("#define BUMP"),s.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(i.metallicRoughnessTexture&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!=i.metallic&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),t=!0),null!=i.roughness&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),t=!0),t&&(i.baseTexture&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),e=!0),i.baseColor&&s.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(i.specularGlossinessTexture?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor&&s.push("#define REFLECTIVITYCOLOR"),null!=i.glossiness&&s.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(i.metallicTexture&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!=i.metallic&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),t=!0),null!=i.roughness&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),t=!0),t?(i.albedoTexture&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),e=!0),i.albedoColor&&s.push("#define ALBEDOCOLOR")):(i.reflectivityTexture?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):i.reflectivityColor&&s.push("#define REFLECTIVITYCOLOR"),null!=i.microSurface&&s.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(i.specularTexture&&(s.push("#define REFLECTIVITYTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),i.specularColor&&s.push("#define REFLECTIVITYCOLOR"))}e&&(s.push("#define NEED_UV"),n.isVerticesDataPresent(er.UVKind)&&(r.push(er.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(er.UV2Kind)&&(r.push(er.UV2Kind),s.push("#define UV2")))}this._linkedWithPrePass&&(s.push("#define PREPASS"),-1!==this._depthIndex&&(s.push("#define DEPTH_INDEX "+this._depthIndex),s.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(s.push("#define NORMAL_INDEX "+this._normalIndex),s.push("#define PREPASS_NORMAL"))),this._enablePosition&&(s.push("#define POSITION"),s.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(s.push("#define VELOCITY"),s.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(n)&&s.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(s.push("#define REFLECTIVITY"),s.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&s.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&s.push("#define ENCODE_NORMAL"),n.useBones&&n.computeBonesUsingShaders&&n.skeleton?(r.push(er.MatricesIndicesKind),r.push(er.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(er.MatricesIndicesExtraKind),r.push(er.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BONETEXTURE "+n.skeleton.isUsingTextureForMatrices),s.push("#define BonesPerMesh "+(n.skeleton.bones.length+1))):(s.push("#define NUM_BONE_INFLUENCERS 0"),s.push("#define BONETEXTURE false"),s.push("#define BonesPerMesh 0"));const o=n.morphTargetManager;let a=0;o&&(a=o.numMaxInfluencers||o.numInfluencers,a>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+a),o.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),Eo(r,n,a))),t&&(s.push("#define INSTANCES"),Po(r,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES")),this._linkedWithPrePass?s.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):s.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),go(i,this._scene,s);const l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),c=h.defines,u=s.join("\n");return c!==u&&h.setEffect(l.createEffect("geometry",{attributes:r,uniformsNames:fP,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler"],defines:u,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:a}},l),u),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.getGBuffer().dispose()}_assignRenderTargetIndices(){const e=[],t=[];let i=2;return e.push("gBuffer_Depth","gBuffer_Normal"),t.push(this._textureTypesAndFormats[mP.DEPTH_TEXTURE_TYPE]),t.push(this._textureTypesAndFormats[mP.NORMAL_TEXTURE_TYPE]),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[mP.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[mP.VELOCITY_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[mP.REFLECTIVITY_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i,s]=this._assignRenderTargetIndices();let r=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?r=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(r=2);const n=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],a=[];for(const e of s)e?(o.push(e.textureType),a.push(e.textureFormat)):(o.push(r),a.push(5));if(this._normalsAreUnsigned=11===o[mP.NORMAL_TEXTURE_TYPE]||13===o[mP.NORMAL_TEXTURE_TYPE],this._multiRenderTarget=new xb("gBuffer",n,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:o,formats:a,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=Pa.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=Pa.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const l=[!0],h=[!1],c=[!0];for(let e=1;e{e.bindAttachments(this.useSpecificClearForDepthTexture?d:u),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(_),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(u)})),this._resizeObserver=e.onResizeObservable.add((()=>{if(this._multiRenderTarget){const t=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(t)}}));const p=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),s=this._scene,r=s.getEngine(),n=e.getMaterial();if(!n)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:me.Identity(),viewProjection:s.getTransformMatrix()},t.skeleton)){const e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=r.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances),l=i.getWorldMatrix();if(this.isReady(e,a)){const h=e._getDrawWrapper();if(!h)return;const c=h.effect;let u;r.enableEffect(h),a||t._bind(e,c,n.fillMode),this._useUbo?(Ro(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",s.getTransformMatrix()),c.setMatrix("view",s.getViewMatrix()));const d=t._instanceDataStorage;if(d.isFrozen||!n.backFaceCulling&&null===t.overrideMaterialSideOrientation)u=d.sideOrientation;else{const e=i._getWorldMatrixDeterminant();u=t.overrideMaterialSideOrientation,null===u&&(u=n.sideOrientation),e<0&&(u=u===ta.ClockWiseSideOrientation?ta.CounterClockWiseSideOrientation:ta.ClockWiseSideOrientation)}if(n._preBind(h,u),n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(n.bumpTexture&&s.getEngine().getCaps().standardDerivatives&&$c.BumpTextureEnabled&&(c.setFloat3("vBumpInfos",n.bumpTexture.coordinatesIndex,1/n.bumpTexture.level,n.parallaxScaleBias),c.setMatrix("bumpMatrix",n.bumpTexture.getTextureMatrix()),c.setTexture("bumpSampler",n.bumpTexture),c.setFloat2("vTangentSpaceParams",n.invertNormalMapX?-1:1,n.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===n.getClassName()?(null!==n.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",n.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",n.metallicRoughnessTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.baseTexture&&(c.setTexture("albedoSampler",n.baseTexture),c.setMatrix("albedoMatrix",n.baseTexture.getTextureMatrix())),null!==n.baseColor&&c.setColor3("albedoColor",n.baseColor)):"PBRSpecularGlossinessMaterial"===n.getClassName()?(null!==n.specularGlossinessTexture?(c.setTexture("reflectivitySampler",n.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",n.specularGlossinessTexture.getTextureMatrix())):null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor),null!==n.glossiness&&c.setFloat("glossiness",n.glossiness)):"PBRMaterial"===n.getClassName()?(null!==n.metallicTexture&&(c.setTexture("reflectivitySampler",n.metallicTexture),c.setMatrix("reflectivityMatrix",n.metallicTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.roughness||null!==n.metallic||null!==n.metallicTexture?(null!==n.albedoTexture&&(c.setTexture("albedoSampler",n.albedoTexture),c.setMatrix("albedoMatrix",n.albedoTexture.getTextureMatrix())),null!==n.albedoColor&&c.setColor3("albedoColor",n.albedoColor)):(null!==n.reflectivityTexture?(c.setTexture("reflectivitySampler",n.reflectivityTexture),c.setMatrix("reflectivityMatrix",n.reflectivityTexture.getTextureMatrix())):null!==n.reflectivityColor&&c.setColor3("reflectivityColor",n.reflectivityColor),null!==n.microSurface&&c.setFloat("glossiness",n.microSurface))):"StandardMaterial"===n.getClassName()&&(null!==n.specularTexture&&(c.setTexture("reflectivitySampler",n.specularTexture),c.setMatrix("reflectivityMatrix",n.specularTexture.getTextureMatrix())),null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor))),xo(c,n,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices&&c.getUniformIndex("boneTextureWidth")>-1){const i=e.getTransformMatrixTexture(t);c.setTexture("boneSampler",i),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",t.skeleton.getTransformMatrices(t));this._enableVelocity&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])}Io(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c),this._enableVelocity&&(c.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),c.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),a&&t.hasThinInstances&&c.setMatrix("world",l),t._processRendering(i,e,c,n.fillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=l.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,s)=>{if((s||0===i)&&t.subMeshes)for(let i=0;i{let n;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(r.length){for(e.setColorWrite(!1),n=0;n{throw xt("GeometryBufferRendererSceneComponent")};class gP{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(Hr.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),Hr.prototype.enableGeometryBufferRenderer=function(e=1,t=15,i){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new mP(this,e,t,i),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},Hr.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class vP{constructor(e){this.name=or.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(or.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}mP._SceneComponentInitialization=e=>{let t=e._getComponent(or.NAME_GEOMETRYBUFFERRENDERER);t||(t=new vP(e),e._addComponent(t))};Bi.ShadersStore.motionBlurPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize;\n#ifdef OBJECT_BASED\nuniform sampler2D velocitySampler;\n#else\nuniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\n#ifdef OBJECT_BASED\nvec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=samplesCount)\nbreak;vec2 offset=vUV+velocity*(hlim+float(i));\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset,0.0);\n#else\nresult+=texture2D(textureSampler,offset);\n#endif\n}\ngl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0;\n#else\nvec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; \nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=nSamples)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset1,0.0);\n#else\nresult+=texture2D(textureSampler,offset1);\n#endif\n}\ngl_FragColor=result/float(nSamples);\n#endif\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";class xP extends Vl{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,s,r,n,o,a=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,s,r,n,o,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",a,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new gP)),this._applyMode()}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}const i=t.indexOf(e);-1!==i&&t.splice(i,1)}}dispose(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),super.dispose(e)}_applyMode(){if(!this._geometryBufferRenderer&&!this._prePassRenderer)return Ne.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=me.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=5),this.onApply=e=>this._onApplyScreenBased(e))}_onApplyObjectBased(e){if(e.setVector2("screenSize",new de(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(mP.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){const t=ve.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new de(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(mP.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){const e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}}static _Parse(e,t,i,s){return St.Parse((()=>new xP(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,s)}}Ze([rt()],xP.prototype,"motionStrength",void 0),Ze([rt()],xP.prototype,"motionBlurSamples",null),Ze([rt()],xP.prototype,"isObjectBased",null),z("BABYLON.MotionBlurPostProcess",xP);Bi.ShadersStore.refractionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";class bP extends Vl{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,s,r,n,o,a,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,o,a,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=s,this.colorLevel=r,this.refractionTextureUrl=t,this.onActivateObservable.add((e=>{this._refTexture=this._refTexture||new Pa(t,e.getScene())})),this.onApplyObservable.add((e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)}))}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,s){return St.Parse((()=>new bP(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}Ze([rt()],bP.prototype,"color",void 0),Ze([rt()],bP.prototype,"depth",void 0),Ze([rt()],bP.prototype,"colorLevel",void 0),Ze([rt()],bP.prototype,"refractionTextureUrl",void 0),z("BABYLON.RefractionPostProcess",bP);Bi.ShadersStore.sharpenPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}";class TP extends Vl{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,s,r,n,null,o,void 0,null,a),this.colorAmount=1,this.edgeAmount=.3,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,s){return St.Parse((()=>new TP(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}Ze([rt()],TP.prototype,"colorAmount",void 0),Ze([rt()],TP.prototype,"edgeAmount",void 0),z("BABYLON.SharpenPostProcess",TP);class yP{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(const e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){const i=this._renderEffects[e];i&&i._enable(Ds.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(Ds.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=Ds.MakeArray(e||this._cameras);if(!i)return;const s=[];let r;for(r=0;r0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){const e=Object.keys(this._renderEffects);for(const t of e){const e=this._renderEffects[t].getPostProcesses();if(e)for(const t of e)t.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}Ze([rt()],yP.prototype,"_name",void 0);class SP{constructor(){this._renderPipelines={}}get supportedPipelines(){const e=[];for(const t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){const i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){const s=this._renderPipelines[e];s&&s._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._disableEffect(t,i)}update(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){const t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e]._rebuild()}dispose(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e].dispose()}}Object.defineProperty(Hr.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(or.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new CP(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new SP}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class CP{constructor(e){this.name=or.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(or.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}}class EP extends yP{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){const e=this.bloom;this.bloom=new eP(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen),!0),this.depthOfField=new lP(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=o.getHardwareScalingLevel(),this._resizeObserver=o.onResizeObservable.add((()=>{this._hardwareScaleLevel=o.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel})),this.bloom=new eP(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new tP("ChromaticAberration",o.getRenderWidth(),o.getRenderHeight(),1,null,Pa.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new qA(o,this.ChromaticAberrationPostProcessId,(()=>this.chromaticAberration),!0),this.grain=new dP("Grain",1,null,Pa.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new qA(o,this.GrainPostProcessId,(()=>this.grain),!0);let a=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add((()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,a?Ds.SetImmediate((()=>{this._buildPipeline()})):this._buildPipeline())})),this._buildPipeline(),a=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){const e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;const e=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(const e of this._cameras)this._scene.enableDepthRenderer(e).useOnlyInActiveCamera=!0;this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add((e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())}))}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new pP("imageProcessing",1,null,Pa.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new qA(e,this.ImageProcessingPostProcessId,(()=>this.imageProcessing),!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new uP("fxaa",1,null,Pa.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new qA(e,this.FxaaPostProcessId,(()=>this.fxaa),!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add((()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)}))),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add((()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)}))),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&Ne.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew EP(e._name,e._name._hdr,t)),e,t,i)}}Ze([rt()],EP.prototype,"sharpenEnabled",null),Ze([rt()],EP.prototype,"bloomKernel",null),Ze([rt()],EP.prototype,"_bloomWeight",void 0),Ze([rt()],EP.prototype,"_bloomThreshold",void 0),Ze([rt()],EP.prototype,"_hdr",void 0),Ze([rt()],EP.prototype,"bloomWeight",null),Ze([rt()],EP.prototype,"bloomThreshold",null),Ze([rt()],EP.prototype,"bloomScale",null),Ze([rt()],EP.prototype,"bloomEnabled",null),Ze([rt()],EP.prototype,"depthOfFieldEnabled",null),Ze([rt()],EP.prototype,"depthOfFieldBlurLevel",null),Ze([rt()],EP.prototype,"fxaaEnabled",null),Ze([rt()],EP.prototype,"samples",null),Ze([rt()],EP.prototype,"imageProcessingEnabled",null),Ze([rt()],EP.prototype,"glowLayerEnabled",null),Ze([rt()],EP.prototype,"chromaticAberrationEnabled",null),Ze([rt()],EP.prototype,"grainEnabled",null),z("BABYLON.DefaultRenderingPipeline",EP);Bi.ShadersStore.lensHighlightsPixelShader="uniform sampler2D textureSampler; \nuniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;}\nfloat w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;gl_FragColor=blurred;}";Bi.ShadersStore.depthOfFieldPixelShader="uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; \nuniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV;\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \nvec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co)\n{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);}\nvec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;}\nfloat sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;}\nfloat getBlurLevel(float size) {return min(3.0,ceil(size/1.0));}\nvec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);}\nif (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);}\ncol/=total_weight; \nif (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);}\nreturn col;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; }\nfloat edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;}\nfloat blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);}\nelse {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;}\nif (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}}\nif (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}}\n";class AP extends yP{constructor(e,t,i,s=1,r){super(i.getEngine(),e),this.LensChromaticAberrationEffect="LensChromaticAberrationEffect",this.HighlightsEnhancingEffect="HighlightsEnhancingEffect",this.LensDepthOfFieldEffect="LensDepthOfFieldEffect",this._pentagonBokehIsEnabled=!1,this._scene=i,this._depthTexture=i.enableDepthRenderer().getDepthMap(),t.grain_texture?this._grainTexture=t.grain_texture:this._createGrainTexture(),this._edgeBlur=t.edge_blur?t.edge_blur:0,this._grainAmount=t.grain_amount?t.grain_amount:0,this._chromaticAberration=t.chromatic_aberration?t.chromatic_aberration:0,this._distortion=t.distortion?t.distortion:0,this._highlightsGain=void 0!==t.dof_gain?t.dof_gain:-1,this._highlightsThreshold=t.dof_threshold?t.dof_threshold:1,this._dofDistance=void 0!==t.dof_focus_distance?t.dof_focus_distance:-1,this._dofAperture=t.dof_aperture?t.dof_aperture:1,this._dofDarken=t.dof_darken?t.dof_darken:0,this._dofPentagon=void 0===t.dof_pentagon||t.dof_pentagon,this._blurNoise=void 0===t.blur_noise||t.blur_noise,this._createChromaticAberrationPostProcess(s),this._createHighlightsPostProcess(s),this._createDepthOfFieldPostProcess(s/4),this.addEffect(new qA(i.getEngine(),this.LensChromaticAberrationEffect,(()=>this._chromaticAberrationPostProcess),!0)),this.addEffect(new qA(i.getEngine(),this.HighlightsEnhancingEffect,(()=>this._highlightsPostProcess),!0)),this.addEffect(new qA(i.getEngine(),this.LensDepthOfFieldEffect,(()=>this._depthOfFieldPostProcess),!0)),-1===this._highlightsGain&&this._disableEffect(this.HighlightsEnhancingEffect,null),i.postProcessRenderPipelineManager.addPipeline(this),r&&i.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}getClassName(){return"LensRenderingPipeline"}get scene(){return this._scene}get edgeBlur(){return this._edgeBlur}set edgeBlur(e){this.setEdgeBlur(e)}get grainAmount(){return this._grainAmount}set grainAmount(e){this.setGrainAmount(e)}get chromaticAberration(){return this._chromaticAberration}set chromaticAberration(e){this.setChromaticAberration(e)}get dofAperture(){return this._dofAperture}set dofAperture(e){this.setAperture(e)}get edgeDistortion(){return this._distortion}set edgeDistortion(e){this.setEdgeDistortion(e)}get dofDistortion(){return this._dofDistance}set dofDistortion(e){this.setFocusDistance(e)}get darkenOutOfFocus(){return this._dofDarken}set darkenOutOfFocus(e){this.setDarkenOutOfFocus(e)}get blurNoise(){return this._blurNoise}set blurNoise(e){this._blurNoise=e}get pentagonBokeh(){return this._pentagonBokehIsEnabled}set pentagonBokeh(e){e?this.enablePentagonBokeh():this.disablePentagonBokeh()}get highlightsGain(){return this._highlightsGain}set highlightsGain(e){this.setHighlightsGain(e)}get highlightsThreshold(){return this._highlightsThreshold}set highlightsThreshold(e){this.setHighlightsThreshold(e)}setEdgeBlur(e){this._edgeBlur=e}disableEdgeBlur(){this._edgeBlur=0}setGrainAmount(e){this._grainAmount=e}disableGrain(){this._grainAmount=0}setChromaticAberration(e){this._chromaticAberration=e}disableChromaticAberration(){this._chromaticAberration=0}setEdgeDistortion(e){this._distortion=e}disableEdgeDistortion(){this._distortion=0}setFocusDistance(e){this._dofDistance=e}disableDepthOfField(){this._dofDistance=-1}setAperture(e){this._dofAperture=e}setDarkenOutOfFocus(e){this._dofDarken=e}enablePentagonBokeh(){this._highlightsPostProcess.updateEffect("#define PENTAGON\n"),this._pentagonBokehIsEnabled=!0}disablePentagonBokeh(){this._pentagonBokehIsEnabled=!1,this._highlightsPostProcess.updateEffect()}enableNoiseBlur(){this._blurNoise=!0}disableNoiseBlur(){this._blurNoise=!1}setHighlightsGain(e){this._highlightsGain=e}setHighlightsThreshold(e){-1===this._highlightsGain&&(this._highlightsGain=1),this._highlightsThreshold=e}disableHighlights(){this._highlightsGain=-1}dispose(e=!1){this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._scene.cameras),this._chromaticAberrationPostProcess=null,this._highlightsPostProcess=null,this._depthOfFieldPostProcess=null,this._grainTexture.dispose(),e&&this._scene.disableDepthRenderer()}_createChromaticAberrationPostProcess(e){this._chromaticAberrationPostProcess=new Vl("LensChromaticAberration","chromaticAberration",["chromatic_aberration","screen_width","screen_height","direction","radialIntensity","centerPosition"],[],e,null,Pa.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._chromaticAberrationPostProcess.onApply=e=>{e.setFloat("chromatic_aberration",this._chromaticAberration),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),e.setFloat("radialIntensity",1),e.setFloat2("direction",17,17),e.setFloat2("centerPosition",.5,.5)}}_createHighlightsPostProcess(e){this._highlightsPostProcess=new Vl("LensHighlights","lensHighlights",["gain","threshold","screen_width","screen_height"],[],e,null,Pa.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,this._dofPentagon?"#define PENTAGON\n":""),this._highlightsPostProcess.externalTextureSamplerBinding=!0,this._highlightsPostProcess.onApply=e=>{e.setFloat("gain",this._highlightsGain),e.setFloat("threshold",this._highlightsThreshold),e.setTextureFromPostProcess("textureSampler",this._chromaticAberrationPostProcess),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight())}}_createDepthOfFieldPostProcess(e){this._depthOfFieldPostProcess=new Vl("LensDepthOfField","depthOfField",["grain_amount","blur_noise","screen_width","screen_height","distortion","dof_enabled","screen_distance","aperture","darken","edge_blur","highlights","near","far"],["depthSampler","grainSampler","highlightsSampler"],e,null,Pa.TRILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._depthOfFieldPostProcess.externalTextureSamplerBinding=!0,this._depthOfFieldPostProcess.onApply=e=>{e.setTexture("depthSampler",this._depthTexture),e.setTexture("grainSampler",this._grainTexture),e.setTextureFromPostProcess("textureSampler",this._highlightsPostProcess),e.setTextureFromPostProcess("highlightsSampler",this._depthOfFieldPostProcess),e.setFloat("grain_amount",this._grainAmount),e.setBool("blur_noise",this._blurNoise),e.setFloat("screen_width",this._scene.getEngine().getRenderWidth()),e.setFloat("screen_height",this._scene.getEngine().getRenderHeight()),e.setFloat("distortion",this._distortion),e.setBool("dof_enabled",-1!==this._dofDistance),e.setFloat("screen_distance",1/(.1-1/this._dofDistance)),e.setFloat("aperture",this._dofAperture),e.setFloat("darken",this._dofDarken),e.setFloat("edge_blur",this._edgeBlur),e.setBool("highlights",-1!==this._highlightsGain),this._scene.activeCamera&&(e.setFloat("near",this._scene.activeCamera.minZ),e.setFloat("far",this._scene.activeCamera.maxZ))}}_createGrainTexture(){const e=new Uint8Array(1048576);for(let t=0;t1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;}\nfloat sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);}\n#endif\n#ifdef BLUR\nuniform float outSize;uniform float soften;uniform float tolerance;uniform int samples;\n#ifndef BLUR_BYPASS\nuniform sampler2D depthSampler;\n#ifdef BLUR_LEGACY\n#define inline\nfloat blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;}\n#endif\n#endif\nvoid main()\n{float result=0.0;\n#ifdef BLUR_BYPASS\nresult=textureLod(textureSampler,vUV,0.0).r;\n#else\n#ifdef BLUR_H\nvec2 step=vec2(1.0/outSize,0.0);\n#else\nvec2 step=vec2(0.0,1.0/outSize);\n#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,vUV,step);\n#else\nfloat compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; ithis._originalColorPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e{if(!this._scene.activeCamera)return;const t=n?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=n?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},o.samples=this.textureSamples,o.autoClear=!1,o}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,2.3283064365386963e-10*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){const i=2*t*Math.PI,s=1-.85*e,r=Math.sqrt(1-s*s);return new _e(Math.cos(i)*r,Math.sin(i)*r,s)}_generateHemisphere(){const e=this.samples,t=[];let i,s=0;for(;s{if(this._scene.activeCamera){if(e.setArray3("sampleSphere",this._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/this.samples),e.setFloat("totalStrength",this.totalStrength),e.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),e.setFloat("radius",this.radius),e.setFloat("maxZ",this.maxZ),e.setFloat("minZAspect",this.minZAspect),e.setFloat("base",this.base),e.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===In.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",IP.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const t=this._scene.getEngine().getRenderWidth()/2,i=this._scene.getEngine().getRenderHeight()/2,s=this._scene.activeCamera.orthoLeft??-t,r=this._scene.activeCamera.orthoRight??t,n=this._scene.activeCamera.orthoBottom??-i,o=this._scene.activeCamera.orthoTop??i;e.setMatrix3x3("depthProjection",IP.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",.5*(r-s)),e.setFloat("yViewport",.5*(o-n))}e.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),e.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),e.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new PP)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new Vl("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{const t=this._scene.activeCamera.viewport;e.setVector4("viewport",ve.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.autoClear=!1,this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){const e=new Uint8Array(65536),t=de.Zero();for(let i=0;inew IP(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType)),e,t,i)}}IP.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],IP.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],Ze([rt()],IP.prototype,"totalStrength",void 0),Ze([rt()],IP.prototype,"maxZ",void 0),Ze([rt()],IP.prototype,"minZAspect",void 0),Ze([rt("epsilon")],IP.prototype,"_epsilon",void 0),Ze([rt("samples")],IP.prototype,"_samples",void 0),Ze([rt("textureSamples")],IP.prototype,"_textureSamples",void 0),Ze([rt()],IP.prototype,"_forceGeometryBuffer",void 0),Ze([rt()],IP.prototype,"_ratio",void 0),Ze([rt()],IP.prototype,"_textureType",void 0),Ze([rt()],IP.prototype,"radius",void 0),Ze([rt()],IP.prototype,"base",void 0),Ze([rt("bypassBlur")],IP.prototype,"_bypassBlur",void 0),Ze([rt("expensiveBlur")],IP.prototype,"_expensiveBlur",void 0),Ze([rt()],IP.prototype,"bilateralSamples",void 0),Ze([rt()],IP.prototype,"bilateralSoften",void 0),Ze([rt()],IP.prototype,"bilateralTolerance",void 0),z("BABYLON.SSAO2RenderingPipeline",IP);Bi.ShadersStore.ssaoPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords)\n{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);}\nvoid main()\n{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; ithis._originalColorPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new qA(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}_attachCameras(e,t){super._attachCameras(e,t);for(const e of this._cameras)this._scene.enableDepthRenderer(e).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e{const e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e})),this._blurVPostProcess.onActivateObservable.add((()=>{const e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e}))}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){const t=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271];this._ssaoPostProcess=new Vl("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=e=>{this._firstUpdate&&(e.setArray3("sampleSphere",t),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",this.totalStrength),e.setFloat("radius",this.radius),e.setFloat("area",this.area),e.setFloat("fallOff",this.fallOff),e.setFloat("base",this.base),e.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new Vl("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Pa.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",ve.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const e=new Uint8Array(1048576);for(let t=0;t0.0)\nhitCoord-=dir;else\nhitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;}\nprojectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;}\n/**\n* Tests the given world position (hitCoord) according to the given reflection vector (dir)\n* until it finds a collision (means that depth is enough close to say \"it's the pixel to sample!\").\n*/\nReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)\n{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i{const i=this._geometryBufferRenderer,s=this._prePassRenderer;if(!s&&!i)return;if(i){const t=i.getTextureIndex(mP.POSITION_TEXTURE_TYPE),s=i.getTextureIndex(mP.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[s])}else if(s){const t=s.getIndex(1),i=s.getIndex(3),r=s.getIndex(6);e.setTexture("normalSampler",s.getRenderTarget().textures[r]),e.setTexture("positionSampler",s.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",s.getRenderTarget().textures[i])}const r=t.activeCamera;if(!r)return;const n=r.getViewMatrix(!0),o=r.getProjectionMatrix(!0);e.setMatrix("projection",o),e.setMatrix("view",n),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(0|this._reflectionSamples)),e.push("#define SMOOTH_STEPS "+(0|this._smoothSteps)),this.updateEffect(e.join("\n"))}static _Parse(e,t,i,s){return St.Parse((()=>new OP(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}Ze([rt()],OP.prototype,"threshold",void 0),Ze([rt()],OP.prototype,"strength",void 0),Ze([rt()],OP.prototype,"reflectionSpecularFalloffExponent",void 0),Ze([rt()],OP.prototype,"step",void 0),Ze([rt()],OP.prototype,"roughnessFactor",void 0),Ze([rt()],OP.prototype,"enableSmoothReflections",null),Ze([rt()],OP.prototype,"reflectionSamples",null),Ze([rt()],OP.prototype,"smoothSteps",null),z("BABYLON.ScreenSpaceReflectionPostProcess",OP);Bi.ShadersStore.standardPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];void main(void)\n{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void)\n{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminanceshadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;}\naccumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;void main(void)\n{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];void main()\n{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++)\n{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));}\naverage=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];uniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\n#include\n#endif\nvoid main()\n{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++)\n{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;uniform float averageLuminance;void main()\n{vec4 color=texture2D(textureAdderSampler,vUV);\n#ifndef AUTO_EXPOSURE\nvec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0;\n#endif\ngl_FragColor=color;}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p)\n{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);}\nfloat noise(in vec2 p)\n{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);}\nfloat fbm(vec2 p)\n{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;}\nvec3 pattern(vec2 uv)\n{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);}\nfloat luminance(vec3 color)\n{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{return vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);}\nvoid main(void)\n{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i=nSamples)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);}\ngl_FragColor=result/float(nSamples);}\n#endif\n";class DP extends yP{get exposure(){return this._fixedExposure}set exposure(e){this._fixedExposure=e,this._currentExposure=e}get hdrAutoExposure(){return this._hdrAutoExposure}set hdrAutoExposure(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){const t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join("\n"))}}get motionStrength(){return this._motionStrength}set motionStrength(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)}get objectBasedMotionBlur(){return this._isObjectBasedMotionBlur}set objectBasedMotionBlur(e){const t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()}get BloomEnabled(){return this._bloomEnabled}set BloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get DepthOfFieldEnabled(){return this._depthOfFieldEnabled}set DepthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get LensFlareEnabled(){return this._lensFlareEnabled}set LensFlareEnabled(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())}get HDREnabled(){return this._hdrEnabled}set HDREnabled(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())}get VLSEnabled(){return this._vlsEnabled}set VLSEnabled(e){if(this._vlsEnabled!==e){if(e&&!this._scene.enableGeometryBufferRenderer())return void Ne.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,s=null,r){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=r||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=s,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){const e=this._ratio,t=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new OP("HDRPass",t,e,null,Pa.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess})),this.addEffect(new qA(t.getEngine(),"HDRScreenSpaceReflections",(()=>this.screenSpaceReflectionPostProcess),!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new Vl("HDRPass","standard",[],[],e,null,Pa.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.originalPostProcess})),this.addEffect(new qA(t.getEngine(),"HDRPassPostProcess",(()=>this.originalPostProcess),!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(t,e/4),this._createBrightPassPostProcess(t,e/4),this._createBlurPostProcesses(t,e/4,1),this._createTextureAdderPostProcess(t,e),this.textureAdderFinalPostProcess=new Vl("HDRDepthOfFieldSource","standard",[],[],e,null,Pa.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new qA(t.getEngine(),"HDRBaseDepthOfFieldSource",(()=>this.textureAdderFinalPostProcess),!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new Vl("HDRVLSFinal","standard",[],[],e,null,Pa.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new qA(t.getEngine(),"HDRVLSFinal",(()=>this.volumetricLightFinalPostProcess),!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new Vl("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,Pa.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new qA(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",(()=>this.lensFlareFinalPostProcess),!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new Vl("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,Pa.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new qA(t.getEngine(),"HDRPostHDReDepthOfFieldSource",(()=>this.hdrFinalPostProcess),!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(t,e/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(t,e)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(t,e),this._fxaaEnabled&&(this.fxaaPostProcess=new uP("fxaa",1,null,Pa.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new qA(t.getEngine(),"HDRFxaa",(()=>this.fxaaPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&Ne.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){const i=new Array(32);this.downSampleX4PostProcess=new Vl("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0;const s=this.downSampleX4PostProcess.width,r=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let n=-2;n<2;n++)i[t]=(e+.5)*(1/s),i[t+1]=(n+.5)*(1/r),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new qA(e.getEngine(),"HDRDownSampleX4",(()=>this.downSampleX4PostProcess),!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new Vl("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{const t=1/this.brightPassPostProcess.width,s=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*s,i[2]=.5*t,i[3]=.5*s,i[4]=-.5*t,i[5]=-.5*s,i[6]=.5*t,i[7]=-.5*s,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new qA(e.getEngine(),"HDRBrightPass",(()=>this.brightPassPostProcess),!0))}_createBlurPostProcesses(e,t,i,s="blurWidth"){const r=e.getEngine(),n=new mg("HDRBlurH_"+i,new de(1,0),this[s],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),o=new mg("HDRBlurV_"+i,new de(0,1),this[s],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add((()=>{const e=n.width/r.getRenderWidth();n.kernel=this[s]*e})),o.onActivateObservable.add((()=>{const e=o.height/r.getRenderHeight();o.kernel=this.horizontalBlur?64*e:this[s]*e})),this.addEffect(new qA(e.getEngine(),"HDRBlurH"+i,(()=>n),!0)),this.addEffect(new qA(e.getEngine(),"HDRBlurV"+i,(()=>o),!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(o)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new Vl("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),e.setTexture("lensSampler",this.lensTexture),e.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new qA(e.getEngine(),"HDRTextureAdder",(()=>this.textureAdderPostProcess),!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const s=i.getGBuffer();this.volumetricLightPostProcess=new Vl("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));const r=de.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",s.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),r.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),r.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",r)}},this.addEffect(new qA(e.getEngine(),"HDRVLS",(()=>this.volumetricLightPostProcess),!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new Vl("HDRVLSMerge","standard",[],["originalSampler"],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=e=>{e.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new qA(e.getEngine(),"HDRVLSMerge",(()=>this.volumetricLightMergePostProces),!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,DP.LuminanceSteps);this.luminancePostProcess=new Vl("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const s=[];this.luminancePostProcess.onApply=e=>{const t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;s[0]=-.5*t,s[1]=.5*i,s[2]=.5*t,s[3]=.5*i,s[4]=-.5*t,s[5]=-.5*i,s[6]=.5*t,s[7]=-.5*i,e.setArray2("lumOffsets",s)},this.addEffect(new qA(e.getEngine(),"HDRLuminance",(()=>this.luminancePostProcess),!0));for(let s=DP.LuminanceSteps-1;s>=0;s--){i=Math.pow(3,s);let r="#define LUMINANCE_DOWN_SAMPLE\n";0===s&&(r+="#define FINAL_DOWN_SAMPLER");const n=new Vl("HDRLuminanceDownSample"+s,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,t);this.luminanceDownSamplePostProcesses.push(n)}let r=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach(((t,i)=>{const s=new Array(18);t.onApply=e=>{if(!r)return;let n=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)s[n]=e/r.width,s[n+1]=t/r.height,n+=2;e.setArray2("dsOffsets",s),e.setFloat("halfDestPixelSize",.5/r.width),r=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{const t=e.getEngine().readPixels(0,0,1,1),i=new pe(1/16581375,1/65025,1/255,1);t.then((e=>{const t=new Uint8Array(e.buffer);this._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100}))}),this.addEffect(new qA(e.getEngine(),"HDRLuminanceDownSample"+i,(()=>t),!0))}))}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new Vl("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let s=1,r=0,n=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),r+=e.getEngine().getDeltaTime(),s<0)s=this._hdrCurrentLuminance;else{const e=(n-r)/1e3;this._hdrCurrentLuminances-this.hdrIncreaseRate*e?s-=this.hdrIncreaseRate*e:s=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/s:(s=be.Clamp(s,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",s)),n=r,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new qA(e.getEngine(),"HDR",(()=>this.hdrPostProcess),!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new Vl("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new qA(e.getEngine(),"HDRLensFlare",(()=>this.lensFlarePostProcess),!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new Vl("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new qA(e.getEngine(),"HDRLensFlareCompose",(()=>this.lensFlareComposePostProcess),!0));const i=new de(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=e=>{e.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),e.setTexture("lensColorSampler",this.lensColorTexture),e.setFloat("strength",this.lensFlareStrength),e.setFloat("ghostDispersal",this.lensFlareGhostDispersal),e.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,e.setVector2("resolution",i),e.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const s=me.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),r=me.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=e=>{if(!this._scene.activeCamera)return;e.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),e.setTexture("lensDirtSampler",this.lensFlareDirtTexture),e.setTexture("lensStarSampler",this.lensStarTexture);const t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2);let n=_e.Dot(t.toVector3(),new _e(1,0,0))+_e.Dot(i.toVector3(),new _e(0,0,1));n*=4;const o=me.FromValues(.5*Math.cos(n),-Math.sin(n),0,0,Math.sin(n),.5*Math.cos(n),0,0,0,0,1,0,0,0,0,1),a=r.multiply(o).multiply(s);e.setMatrix("lensStarMatrix",a),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new Vl("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),e.setTexture("depthSampler",this._getDepthTexture()),e.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new qA(e.getEngine(),"HDRDepthOfField",(()=>this.depthOfFieldPostProcess),!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new xP("HDRMotionBlur",e,t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new Vl("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,Pa.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,s=me.Identity();const r=me.Identity();let n=me.Identity();const o=de.Zero();this.motionBlurPostProcess.onApply=t=>{n=e.getProjectionMatrix().multiply(e.getViewMatrix()),n.invertToRef(r),t.setMatrix("inverseViewProjection",r),t.setMatrix("prevViewProjection",s),s=n,o.x=this.motionBlurPostProcess.width,o.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",o),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new qA(e.getEngine(),"HDRMotionBlur",(()=>this.motionBlurPostProcess),!0))}_getDepthTexture(){return this._scene.getEngine().getCaps().drawBuffersExtension?this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]:this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;enew DP(e._name,t,e._ratio)),e,t,i);return e.sourceLightId&&(s.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&St.Parse((()=>s.screenSpaceReflectionPostProcess),e.screenSpaceReflectionPostProcess,t,i),s}}DP.LuminanceSteps=6,Ze([rt()],DP.prototype,"brightThreshold",void 0),Ze([rt()],DP.prototype,"blurWidth",void 0),Ze([rt()],DP.prototype,"horizontalBlur",void 0),Ze([rt()],DP.prototype,"exposure",null),Ze([nt("lensTexture")],DP.prototype,"lensTexture",void 0),Ze([rt()],DP.prototype,"volumetricLightCoefficient",void 0),Ze([rt()],DP.prototype,"volumetricLightPower",void 0),Ze([rt()],DP.prototype,"volumetricLightBlurScale",void 0),Ze([rt()],DP.prototype,"hdrMinimumLuminance",void 0),Ze([rt()],DP.prototype,"hdrDecreaseRate",void 0),Ze([rt()],DP.prototype,"hdrIncreaseRate",void 0),Ze([rt()],DP.prototype,"hdrAutoExposure",null),Ze([nt("lensColorTexture")],DP.prototype,"lensColorTexture",void 0),Ze([rt()],DP.prototype,"lensFlareStrength",void 0),Ze([rt()],DP.prototype,"lensFlareGhostDispersal",void 0),Ze([rt()],DP.prototype,"lensFlareHaloWidth",void 0),Ze([rt()],DP.prototype,"lensFlareDistortionStrength",void 0),Ze([rt()],DP.prototype,"lensFlareBlurWidth",void 0),Ze([nt("lensStarTexture")],DP.prototype,"lensStarTexture",void 0),Ze([nt("lensFlareDirtTexture")],DP.prototype,"lensFlareDirtTexture",void 0),Ze([rt()],DP.prototype,"depthOfFieldDistance",void 0),Ze([rt()],DP.prototype,"depthOfFieldBlurWidth",void 0),Ze([rt()],DP.prototype,"motionStrength",null),Ze([rt()],DP.prototype,"objectBasedMotionBlur",null),Ze([rt()],DP.prototype,"_ratio",void 0),Ze([rt()],DP.prototype,"BloomEnabled",null),Ze([rt()],DP.prototype,"DepthOfFieldEnabled",null),Ze([rt()],DP.prototype,"LensFlareEnabled",null),Ze([rt()],DP.prototype,"HDREnabled",null),Ze([rt()],DP.prototype,"VLSEnabled",null),Ze([rt()],DP.prototype,"MotionBlurEnabled",null),Ze([rt()],DP.prototype,"fxaaEnabled",null),Ze([rt()],DP.prototype,"screenSpaceReflectionsEnabled",null),Ze([rt()],DP.prototype,"volumetricLightStepsCount",null),Ze([rt()],DP.prototype,"motionBlurSamples",null),Ze([rt()],DP.prototype,"samples",null),z("BABYLON.StandardRenderingPipeline",DP);class wP{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}Bi.IncludesShadersStore.screenSpaceRayTrace="float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }\n/**\nparam csOrigin Camera-space ray origin,which must be \nwithin the view volume and must have z>0.01 and project within the valid screen rectangle\nparam csDirection Unit length camera-space ray direction\nparam projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \n(**not** [-1,+1] normalized device coordinates).\nparam csZBuffer The camera-space Z buffer\nparam csZBufferSize Dimensions of csZBuffer\nparam csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\nparam nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\nfor clipping rays headed towards the camera\nparam stride Step in horizontal or vertical pixels between samples. This is a float\nbecause integer math is slow on GPUs,but should be set to an integer>=1\nparam jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\nto conceal banding artifacts,plus the stride ray offset.\nparam maxSteps Maximum number of iterations. Higher gives better images but may be slow\nparam maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\nparam selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.\n1 is a reasonable value,depending on the scene you may need to set this value to 2\nparam hitPixel Pixel coordinates of the first intersection with the scene\nparam numIterations number of iterations performed\nparam csHitPoint Camera space location of the ray hit\n*/\n#define inline\nbool traceScreenSpaceRay1(\nvec3 csOrigin,\nvec3 csDirection,\nmat4 projectToPixelMatrix,\nsampler2D csZBuffer,\nvec2 csZBufferSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nsampler2D csZBackBuffer,\nfloat csZBackSizeFactor,\n#endif\nfloat csZThickness,\nfloat nearPlaneZ,\nfloat stride,\nfloat jitterFraction,\nfloat maxSteps,\nfloat maxRayTraceDistance,\nfloat selfCollisionNumSkip,\nout vec2 startPixel,\nout vec2 hitPixel,\nout vec3 csHitPoint,\nout float numIterations\n#ifdef SSRAYTRACE_DEBUG\n,out vec3 debugColor\n#endif\n)\n{\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\n#else\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);}\nif ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));}\nP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\n#endif\nP1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { \nfloat t=rayZMin; rayZMin=rayZMax; rayZMax=t;}\nsceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\n#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\n#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\n#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\n#endif\n#endif\n}\npqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;}\n#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 ||\n(refinementStepCount<=stride*1.4) &&\n(rayZMaxend) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);}\n#endif\nreturn hit;}\n/**\ntexCoord: in the [0,1] range\ndepth: depth in view space (range [znear,zfar]])\n*/\nvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef ORTHOGRAPHIC_CAMERA\nndc.z=-projection[2].z*depth+projection[3].z;\n#else\nndc.z=-projection[2].z-projection[3].z/depth;\n#endif\n#else\n#ifdef ORTHOGRAPHIC_CAMERA\nndc.z=projection[2].z*depth+projection[3].z;\n#else\nndc.z=projection[2].z+projection[3].z/depth;\n#endif\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\n";Bi.ShadersStore.screenSpaceReflection2PixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nuniform sampler2D backDepthSampler;uniform float backSizeFactor;\n#endif\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nuniform samplerCube envCubeSampler;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize;\n#endif\n#endif\nuniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold;\n#include\n#include\n#include\nvec3 hash(vec3 a)\n{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);}\nfloat computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0;\n#ifdef SSR_ATTENUATE_SCREEN_BORDERS\nvec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE\nattenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\nattenuation*=1.0-(numIterations/maxSteps);\n#endif\n#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION\nvec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation;\n#endif\nreturn attenuation;}\n#endif\nvoid main()\n{\n#ifdef SSR_SUPPORTED\nvec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {\n#ifdef SSR_USE_BLUR\ngl_FragColor=vec4(0.);\n#else\ngl_FragColor=colorFull;\n#endif\nreturn;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; \n#ifdef SSR_DECODE_NORMAL\ncsNormal=csNormal*2.0-1.0;\n#endif\n#ifdef SSR_NORMAL_IS_IN_WORLDSPACE\ncsNormal=(view*vec4(csNormal,0.0)).xyz;\n#endif\nfloat depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);\n#ifdef ORTHOGRAPHIC_CAMERA\nvec3 csViewDirection=vec3(0.,0.,1.);\n#else\nvec3 csViewDirection=normalize(csPosition);\n#endif\nvec3 csReflectedVector=reflect(csViewDirection,csNormal);\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0));\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nvec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition);\n#endif\n#ifdef SSR_INVERTCUBICMAP\nwReflectedVector.y*=-1.0;\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nwReflectedVector.z*=-1.0;\n#endif\nvec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz;\n#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\nenvColor=toLinearSpace(envColor);\n#endif\n#else\nvec3 envColor=color;\n#endif\nfloat reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations;\n#ifdef SSRAYTRACE_DEBUG\nvec3 debugColor;\n#endif\n#ifdef SSR_ATTENUATE_FACING_CAMERA\nreflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));\n#endif\nif (reflectionAttenuation>0.0) {\n#ifdef SSR_USE_BLUR\nvec3 jitt=vec3(0.);\n#else\nfloat roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; \n#endif\nvec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); \nrayHasHit=traceScreenSpaceRay1(\ncsPosition,\nnormalize(csReflectedVector+jitt),\nprojectionPixel,\ndepthSampler,\ntexSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nbackDepthSampler,\nbackSizeFactor,\n#endif\nthickness,\nnearPlaneZ,\nstepSize,\njitter,\nmaxSteps,\nmaxDistance,\nselfCollisionNumSkip,\nstartPixel,\nhitPixel,\nhitPoint,\nnumIterations\n#ifdef SSRAYTRACE_DEBUG\n,debugColor\n#endif\n);}\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=vec4(debugColor,1.);return;\n#endif\nvec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb;\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\nreflectedColor=toLinearSpace(reflectedColor);\n#endif\nreflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;}\n#ifndef SSR_BLEND_WITH_FRESNEL\nSSR*=fresnel;\n#endif\n#ifdef SSR_USE_BLUR\nfloat blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; \nfloat a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);}\ngl_FragColor=vec4(SSR,blur_radius/255.0); \n#else\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,colorFull.a);\n#endif\n#else\ngl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0);\n#endif\n}\n";Bi.ShadersStore.screenSpaceReflection2BlurPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator)\n{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;}\nvoid main()\n{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;}\nfloat blurRadius=colorFull.a*255.0; \nvec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);}\n";Bi.ShadersStore.screenSpaceReflection2BlurCombinerPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV;\n#include\n#ifdef SSR_BLEND_WITH_FRESNEL\n#include\n#include\nuniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#endif\nvoid main()\n{\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=texture2D(textureSampler,vUV);\n#else\nvec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,color.a);\n#endif\n}\n";const NP=me.Compose(new _e(.5,.5,.5),fe.Identity(),new _e(.5,.5,.5)),FP=me.Compose(new _e(.5,.5,1),fe.Identity(),new _e(.5,.5,0));class LP extends yP{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}get reflectivityThreshold(){return this._reflectivityThreshold}set reflectivityThreshold(e){e!==this._reflectivityThreshold&&(0===e&&0!==this._reflectivityThreshold||0!==e&&0===this._reflectivityThreshold?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)}get ssrDownsample(){return this._ssrDownsample}set ssrDownsample(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())}get blurDispersionStrength(){return this._blurDispersionStrength}set blurDispersionStrength(e){if(e===this._blurDispersionStrength)return;const t=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;this._blurDispersionStrength=e,t&&this._buildPipeline()}_useBlur(){return this._blurDispersionStrength>0}get blurDownsample(){return this._blurDownsample}set blurDownsample(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e,this._updateEffectDefines()}get environmentTextureIsProbe(){return this._environmentTextureIsProbe}set environmentTextureIsProbe(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()}get attenuateScreenBorders(){return this._attenuateScreenBorders}set attenuateScreenBorders(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())}get attenuateIntersectionDistance(){return this._attenuateIntersectionDistance}set attenuateIntersectionDistance(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())}get attenuateIntersectionIterations(){return this._attenuateIntersectionIterations}set attenuateIntersectionIterations(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())}get attenuateFacingCamera(){return this._attenuateFacingCamera}set attenuateFacingCamera(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())}get attenuateBackfaceReflection(){return this._attenuateBackfaceReflection}set attenuateBackfaceReflection(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())}get clipToFrustum(){return this._clipToFrustum}set clipToFrustum(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())}get useFresnel(){return this._useFresnel}set useFresnel(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())}get enableAutomaticThicknessComputation(){return this._enableAutomaticThicknessComputation}set enableAutomaticThicknessComputation(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())}get backfaceDepthRenderer(){return this._depthRenderer}get backfaceDepthTextureDownsample(){return this._backfaceDepthTextureDownsample}set backfaceDepthTextureDownsample(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())}get backfaceForceDepthWriteTransparentMeshes(){return this._backfaceForceDepthWriteTransparentMeshes}set backfaceForceDepthWriteTransparentMeshes(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){const e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,s=!1,r=0){if(super(t.getEngine(),e),this.SSRRenderEffect="SSRRenderEffect",this.SSRBlurRenderEffect="SSRBlurRenderEffect",this.SSRCombineRenderEffect="SSRCombineRenderEffect",this._samples=1,this.maxDistance=1e3,this.step=1,this.thickness=.5,this.strength=1,this.reflectionSpecularFalloffExponent=1,this.maxSteps=1e3,this.roughnessFactor=.2,this.selfCollisionNumSkip=1,this._reflectivityThreshold=.04,this._ssrDownsample=0,this._blurDispersionStrength=.03,this._blurDownsample=0,this._enableSmoothReflections=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=r,this._forceGeometryBuffer=s,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0)}else{const e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty())}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){const e=this._scene.getEngine(),t=this._prePassRenderer;let i={width:e.getRenderWidth(),height:e.getRenderHeight()};if(t&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const e=t.getRenderTarget();e&&e.textures&&(i=e.textures[t.getIndex(4)].getSize())}else this._ssrPostProcess?.inputTexture&&(i.width=this._ssrPostProcess.inputTexture.width,i.height=this._ssrPostProcess.inputTexture.height);return i}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&e.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(e.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&e.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&e.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&e.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&e.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&e.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&e.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&e.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&e.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&e.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&e.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&e.push("#define SSR_USE_BLUR"),this._debug&&e.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&e.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&e.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&e.push("#define SSR_BLEND_WITH_FRESNEL"),0===this._reflectivityThreshold&&e.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(this._geometryBufferRenderer?.generateNormalsInWorldSpace??this._prePassRenderer?.generateNormalsInWorldSpace)&&e.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),this._geometryBufferRenderer?.normalsAreUnsigned&&e.push("#define SSR_DECODE_NORMAL");const t=this._cameras?.[0];t&&1===t.mode&&e.push("#define ORTHOGRAPHIC_CAMERA"),this._ssrPostProcess?.updateEffect(e.join("\n"))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){const e=this._cameras?.[0];e&&(this._depthRendererCamera=e,this._depthRenderer=new Hv(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),e.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new qA(e,this.SSRRenderEffect,(()=>this._ssrPostProcess),!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new qA(e,this.SSRBlurRenderEffect,(()=>[this._blurPostProcessX,this._blurPostProcessY]),!0)),this.addEffect(new qA(e,this.SSRCombineRenderEffect,(()=>this._blurCombinerPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;const e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),s=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));t.width===i&&t.height===s||this._depthRenderer.getDepthMap().resize({width:i,height:s})}_disposeDepthRenderer(){if(this._depthRenderer){if(this._depthRendererCamera){const e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap())??-1;-1!==e&&this._depthRendererCamera.customRenderTargets.splice(e,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){for(let e=0;e{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const i=t.getTextureIndex(mP.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){const t=i.getIndex(5),s=i.getIndex(3),r=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[r]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[s])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const s=this._scene.activeCamera;if(!s)return;const r=s.getViewMatrix(),n=s.getProjectionMatrix();n.invertToRef(ve.Matrix[0]),r.invertToRef(ve.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",r),e.setMatrix("invView",ve.Matrix[1]),e.setMatrix("invProjectionMatrix",ve.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",s.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const o=this._getTextureSize();me.ScalingToRef(o.width,o.height,1,ve.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?FP:NP,ve.Matrix[3]),ve.Matrix[3].multiplyToRef(ve.Matrix[2],ve.Matrix[4]),e.setMatrix("projectionPixel",ve.Matrix[4]),this._environmentTexture&&(e.setTexture("envCubeSampler",this._environmentTexture),this._environmentTexture.boundingBoxSize&&(e.setVector3("vReflectionPosition",this._environmentTexture.boundingBoxPosition),e.setVector3("vReflectionSize",this._environmentTexture.boundingBoxSize)))},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new wP)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new Vl("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add((e=>{const t=this._blurPostProcessX?.inputTexture.width??this._scene.getEngine().getRenderWidth();e.setFloat2("texelOffsetScale",this._blurDispersionStrength/t,0)})),this._blurPostProcessY=new Vl("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add((e=>{const t=this._blurPostProcessY?.inputTexture.height??this._scene.getEngine().getRenderHeight();e.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/t)}));const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"];let s="";this._debug&&(s+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(s+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(s+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(s+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(s+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new Vl("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,s,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add((e=>{const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(i||t){if(i&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const t=i.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[i.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(t){const i=t.getTextureIndex(mP.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),this.useFresnel&&(e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("depthSampler",t.getGBuffer().textures[0]))}else if(i){const t=i.getIndex(3);if(e.setTexture("reflectivitySampler",i.getRenderTarget().textures[t]),this.useFresnel){const t=i.getIndex(5),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const t=this._scene.activeCamera;if(t){const i=t.getProjectionMatrix();i.invertToRef(ve.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",ve.Matrix[0])}}}}))}serialize(){const e=St.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return St.Parse((()=>new LP(e._name,t,e._ratio)),e,t,i)}}Ze([rt()],LP.prototype,"samples",null),Ze([rt()],LP.prototype,"maxDistance",void 0),Ze([rt()],LP.prototype,"step",void 0),Ze([rt()],LP.prototype,"thickness",void 0),Ze([rt()],LP.prototype,"strength",void 0),Ze([rt()],LP.prototype,"reflectionSpecularFalloffExponent",void 0),Ze([rt()],LP.prototype,"maxSteps",void 0),Ze([rt()],LP.prototype,"roughnessFactor",void 0),Ze([rt()],LP.prototype,"selfCollisionNumSkip",void 0),Ze([rt()],LP.prototype,"_reflectivityThreshold",void 0),Ze([rt("_ssrDownsample")],LP.prototype,"_ssrDownsample",void 0),Ze([rt()],LP.prototype,"ssrDownsample",null),Ze([rt("blurDispersionStrength")],LP.prototype,"_blurDispersionStrength",void 0),Ze([rt("blurDownsample")],LP.prototype,"_blurDownsample",void 0),Ze([rt("enableSmoothReflections")],LP.prototype,"_enableSmoothReflections",void 0),Ze([rt("environmentTexture")],LP.prototype,"_environmentTexture",void 0),Ze([rt("environmentTextureIsProbe")],LP.prototype,"_environmentTextureIsProbe",void 0),Ze([rt("attenuateScreenBorders")],LP.prototype,"_attenuateScreenBorders",void 0),Ze([rt("attenuateIntersectionDistance")],LP.prototype,"_attenuateIntersectionDistance",void 0),Ze([rt("attenuateIntersectionIterations")],LP.prototype,"_attenuateIntersectionIterations",void 0),Ze([rt("attenuateFacingCamera")],LP.prototype,"_attenuateFacingCamera",void 0),Ze([rt("attenuateBackfaceReflection")],LP.prototype,"_attenuateBackfaceReflection",void 0),Ze([rt("clipToFrustum")],LP.prototype,"_clipToFrustum",void 0),Ze([rt("useFresnel")],LP.prototype,"_useFresnel",void 0),Ze([rt("enableAutomaticThicknessComputation")],LP.prototype,"_enableAutomaticThicknessComputation",void 0),Ze([rt("backfaceDepthTextureDownsample")],LP.prototype,"_backfaceDepthTextureDownsample",void 0),Ze([rt("backfaceForceDepthWriteTransparentMeshes")],LP.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),Ze([rt("isEnabled")],LP.prototype,"_isEnabled",void 0),Ze([rt("inputTextureColorIsInGammaSpace")],LP.prototype,"_inputTextureColorIsInGammaSpace",void 0),Ze([rt("generateOutputInGammaSpace")],LP.prototype,"_generateOutputInGammaSpace",void 0),Ze([rt("debug")],LP.prototype,"_debug",void 0),z("BABYLON.SSRRenderingPipeline",LP);Bi.ShadersStore.taaPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D historySampler;uniform float factor;void main() {vec4 c=texelFetch(textureSampler,ivec2(gl_FragCoord.xy),0);vec4 h=texelFetch(historySampler,ivec2(gl_FragCoord.xy),0);gl_FragColor=mix(h,c,factor);}\n";class BP extends yP{set samples(e){this._samples!==e&&(this._samples=e,this._hs.regenerate(e))}get samples(){return this._samples}set msaaSamples(e){this._msaaSamples!==e&&(this._msaaSamples=e,this._taaPostProcess&&(this._taaPostProcess.samples=e))}get msaaSamples(){return this._msaaSamples}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&(this._firstUpdate=!0,this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras))):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get scene(){return this._scene}get isSupported(){return this._scene.getEngine().getCaps().texelFetch}constructor(e,t,i,s=0){const r=t.getEngine();super(r,e),this.TAARenderEffect="TAARenderEffect",this.TAAPassEffect="TAAPassEffect",this._samples=8,this._msaaSamples=1,this.factor=.05,this.disableOnCameraMove=!0,this._isEnabled=!0,this._isDirty=!1,this._camerasToBeAttached=[],this._pingpong=0,this._firstUpdate=!0,this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._hs=new zy(this.samples),this.isSupported&&(this._createPingPongTextures(r.getRenderWidth(),r.getRenderHeight()),t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline())}getClassName(){return"TAARenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._ping.dispose(),this._pong.dispose(),super.dispose()}_createPingPongTextures(e,t){const i=this._scene.getEngine();this._ping?.dispose(),this._pong?.dispose(),this._ping=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._pong=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._hs.setDimensions(e/2,t/2),this._firstUpdate=!0}_updateEffectDefines(){this._taaPostProcess?.updateEffect([].join("\n"))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._createTAAPostProcess(),this.addEffect(new qA(e,this.TAARenderEffect,(()=>this._taaPostProcess),!0)),this._createPassPostProcess(),this.addEffect(new qA(e,this.TAAPassEffect,(()=>this._passPostProcess),!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_disposePostProcesses(){for(let e=0;e{const e=this._scene.activeCamera;if(this._taaPostProcess?.width!==this._ping.width||this._taaPostProcess?.height!==this._ping.height){const e=this._scene.getEngine();this._createPingPongTextures(e.getRenderWidth(),e.getRenderHeight())}if(e&&!e.hasMoved)if(e.mode===In.PERSPECTIVE_CAMERA){const t=e.getProjectionMatrix();t.setRowFromFloats(2,this._hs.x,this._hs.y,t.m[10],t.m[11])}else{const t=e.getProjectionMatrix(!0);t.setRowFromFloats(3,this._hs.x+t.m[12],this._hs.y+t.m[13],t.m[14],t.m[15])}this._passPostProcess&&(this._passPostProcess.inputTexture=this._pingpong?this._ping:this._pong),this._pingpong=1^this._pingpong,this._hs.next()})),this._taaPostProcess.onApplyObservable.add((e=>{const t=this._scene.activeCamera;e._bindTexture("historySampler",this._pingpong?this._ping.texture:this._pong.texture),e.setFloat("factor",t?.hasMoved&&this.disableOnCameraMove||this._firstUpdate?1:this.factor),this._firstUpdate=!1}))}_createPassPostProcess(){const e=this._scene.getEngine();this._passPostProcess=new yc("TAAPass",1,null,1,e),this._passPostProcess.inputTexture=this._ping,this._passPostProcess.autoClear=!1}serialize(){const e=St.Serialize(this);return e.customType="TAARenderingPipeline",e}static Parse(e,t,i){return St.Parse((()=>new BP(e._name,t,e._ratio)),e,t,i)}}Ze([rt("samples")],BP.prototype,"_samples",void 0),Ze([rt("msaaSamples")],BP.prototype,"_msaaSamples",void 0),Ze([rt()],BP.prototype,"factor",void 0),Ze([rt()],BP.prototype,"disableOnCameraMove",void 0),Ze([rt("isEnabled")],BP.prototype,"_isEnabled",void 0),z("BABYLON.TAARenderingPipeline",BP);var kP;Bi.ShadersStore.tonemapPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{return dot(c,vec3(0.22,0.707,0.071));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);}",function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(kP||(kP={}));class VP extends Vl{getClassName(){return"TonemapPostProcess"}constructor(e,t,i,s,r=2,n,o=0,a){super(e,"tonemap",["_ExposureAdjustment"],null,1,s,r,n,a,null,o),this._operator=t,this.exposureAdjustment=i;let l="#define ";this._operator===kP.Hable?l+="HABLE_TONEMAPPING":this._operator===kP.Reinhard?l+="REINHARD_TONEMAPPING":this._operator===kP.HejiDawson?l+="OPTIMIZED_HEJIDAWSON_TONEMAPPING":this._operator===kP.Photographic&&(l+="PHOTOGRAPHIC_TONEMAPPING"),this.updateEffect(l),this.onApply=e=>{e.setFloat("_ExposureAdjustment",this.exposureAdjustment)}}}Bi.ShadersStore.volumetricLightScatteringPixelShader="uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add((e=>{this._updateMeshScreenCoordinates(l),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)}))}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){const i=e.getMesh();if(i===this.mesh&&i.material)return i.material.isReady(i);const s=i._internalAbstractMeshDataInfo._materialForRenderPass?.[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(i,e,t);const r=[],n=[er.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&r.push("#define ALPHATEST"),i.isVerticesDataPresent(er.UVKind)&&(n.push(er.UVKind),r.push("#define UV1")),i.isVerticesDataPresent(er.UV2Kind)&&(n.push(er.UV2Kind),r.push("#define UV2"))),i.useBones&&i.computeBonesUsingShaders?(n.push(er.MatricesIndicesKind),n.push(er.MatricesWeightsKind),r.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),r.push("#define BonesPerMesh "+(i.skeleton?i.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0"),t&&(r.push("#define INSTANCES"),Po(n),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));const a=e._getDrawWrapper(void 0,!0),l=a.defines,h=r.join("\n");return l!==h&&a.setEffect(i.getScene().getEngine().createEffect("volumetricLightScatteringPass",n,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],h,void 0,void 0,void 0,{maxSimultaneousMorphTargets:i.numBoneInfluencers}),h),a.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){const t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==t&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)}_createPass(e,t){const i=e.getEngine();this._volumetricLightScatteringRTT=new ih("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=Pa.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=Pa.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const r=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh();if(this._meshExcluded(t))return;i._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const s=e.getMaterial();if(!s)return;const r=t.getScene(),n=r.getEngine();n.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=n.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances);if(this._isReady(e,a)){const l=i._internalAbstractMeshDataInfo._materialForRenderPass?.[n.currentRenderPassId];let h=e._getDrawWrapper();if(t!==this.mesh||h||(h=s._getDrawWrapper()),!h)return;const c=h.effect;if(n.enableEffect(h),a||t._bind(e,c,s.fillMode),t===this.mesh)s.bind(i.getWorldMatrix(),t);else if(l)l.bindForSubMesh(i.getWorldMatrix(),i,e);else{if(c.setMatrix("viewProjection",r.getTransformMatrix()),s&&s.needAlphaTesting()){const e=s.getAlphaTestTexture();c.setTexture("diffuseSampler",e),e&&c.setMatrix("diffuseMatrix",e.getTextureMatrix())}t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&c.setMatrices("mBones",t.skeleton.getTransformMatrices(t))}a&&t.hasThinInstances&&c.setMatrix("world",i.getWorldMatrix()),t._processRendering(i,e,c,ta.TriangleFillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}};let n;const o=new Ae(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((()=>{n=e.clearColor,e.clearColor=o})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((()=>{e.clearColor=n})),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,s)=>{if((s||0===t)&&e.subMeshes)for(let t=0;t{const o=e.getEngine();let a;if(n.length){for(o.setColorWrite(!1),a=0;ae._alphaIndex>t._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0)),o.setAlphaMode(2),a=0;a{e.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));const t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}):Ne.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=re.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,s){return St.Parse((()=>new GP(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}Ze([rt()],GP.prototype,"ridge",void 0),Ze([rt()],GP.prototype,"valley",void 0),z("BABYLON.ScreenSpaceCurvaturePostProcess",GP);Bi.IncludesShadersStore.boundingBoxRendererFragmentDeclaration="uniform vec4 color;\n";Bi.IncludesShadersStore.boundingBoxRendererUboDeclaration="#ifdef WEBGL2\nuniform vec4 color;uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#else\nlayout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;};\n#endif\n";Bi.ShadersStore.boundingBoxRendererPixelShader="#include<__decl__boundingBoxRendererFragment>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.IncludesShadersStore.boundingBoxRendererVertexDeclaration="uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n";Bi.ShadersStore.boundingBoxRendererVertexShader="attribute vec3 position;\n#include<__decl__boundingBoxRendererVertex>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec4 worldPos=world*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n",Object.defineProperty(Hr.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),Hr.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new zP(this)),this._boundingBoxRenderer},Object.defineProperty(_o.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class zP{constructor(e){this.name=or.NAME_BOUNDINGBOXRENDERER,this.frontColor=new Ee(1,1,1),this.backColor=new Ee(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new K,this.onAfterBoxRenderingObservable=new K,this.onResourcesReadyObservable=new K,this.enabled=!0,this.renderList=new Fs(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new Zs(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new Zs(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(or.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(or.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(or.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(or.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){const i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){const t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new Nd("colorShader",this.scene,"boundingBoxRenderer",{attributes:[er.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new Nd("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[er.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=ld({size:1});this._vertexBuffers[er.PositionKind]=new er(e,t.positions,er.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){const e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){const e=this._vertexBuffers[er.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){if(0===this.renderList.length||!this.enabled)return;if(this._prepareResources(),!this._colorShader.isReady())return;const t=this.scene.getEngine();t.setDepthWrite(!1);const i=this.scene.getTransformMatrix();for(let s=0;s{let t=e._getComponent(or.NAME_DEPTHRENDERER);t||(t=new WP(e),e._addComponent(t))};Bi.ShadersStore.oitFinalPixelShader="precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4(\nfrontColor.rgb+alphaMultiplier*backColor.rgb,\nfrontColor.a+backColor.a\n);}";Bi.ShadersStore.oitBackBlendPixelShader="precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { \ndiscard;}}";class HP{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class XP{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new Fs(10),this._excludedSubMeshes=new Fs(10),this._excludedMeshes=[],this._colorCache=[new Ae(XP._DEPTH_CLEAR_VALUE,XP._DEPTH_CLEAR_VALUE,0,0),new Ae(-XP._MIN_DEPTH,XP._MAX_DEPTH,0,0),new Ae(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,e.enablePrePassRenderer()){for(let e=0;e\nuniform vec4 color;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.lineVertexShader="#include\n#include\nattribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio;\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nmat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}",_o.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},_o.prototype.enableEdgesRendering=function(e=.95,t=!1,i){return this.disableEdgesRendering(),this._edgesRenderer=new jP(this,e,t,!0,i),this},Object.defineProperty(_o.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),Fd.prototype.enableEdgesRendering=function(e=.95,t=!1){return this.disableEdgesRendering(),this._edgesRenderer=new KP(this,e,t),this},Ld.prototype.enableEdgesRendering=function(e=.95,t=!1){return Fd.prototype.enableEdgesRendering.apply(this,arguments),this};class QP{constructor(){this.edges=[],this.edgesConnectedCount=0}}class jP{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){const t=new Nd("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,s=!0,r){this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new Fs(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=r??null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new Un(e.getEngine())),this._prepareRessources(),s&&(r?.useAlternateEdgeFinder??1?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add((()=>{this._rebuild()})),this._meshDisposeObserver=this._source.onDisposeObservable.add((()=>{this.dispose()}))}_prepareRessources(){this._lineShader||(this._lineShader=jP._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[er.PositionKind];e&&e._rebuild(),e=this._buffers[er.NormalKind],e&&e._rebuild();const t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)}dispose(){this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let e=this._buffers[er.PositionKind];e&&(e.dispose(),this._buffers[er.PositionKind]=null),e=this._buffers[er.NormalKind],e&&(e.dispose(),this._buffers[er.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),this._drawWrapper?.dispose()}_processEdgeForAdjacencies(e,t,i,s,r){return e===i&&t===s||e===s&&t===i?0:e===s&&t===r||e===r&&t===s?1:e===r&&t===i||e===i&&t===r?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,s,r){const n=1e-10;return e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(s,n)||e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(i,n)?0:e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(r,n)||e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(s,n)?1:e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(i,n)||e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(r,n)?2:-1}_checkEdge(e,t,i,s,r){let n;n=void 0===t||_e.Dot(i[e],i[t]){i>=0&&t.push(i);for(let i=0;i=e[0].length&&e[1].length>=e[2].length?n=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(n=2);for(let t=0;t<3;++t)t===n?e[t].sort(((e,t)=>e[1]t[1]?1:0)):e[t].sort(((e,t)=>e[1]>t[1]?-1:e[1]=n+1;--o)r(e[o%3],a,o!==n+2?s[i[t+(o+1)%3]]:-1);const h=a.length;i.push(s[i[t+n]],o[0],a[0]),i.push(s[i[t+(n+1)%3]],a[h-1],o[l-1]);const c=l<=h,u=c?l:h,d=c?h:l,_=c?l-1:h-1,p=c?0:1;let f=l+h-2,m=0,g=0;const v=c?o:a,x=c?a:o;let b=0;for(;f-- >0;){let e;p?i.push(v[m],x[g]):i.push(x[g],v[m]),b+=u,b>=d&&m<_?(e=v[++m],b-=d):e=x[++g],i.push(e)}i[t+0]=i[i.length-3],i[t+1]=i[i.length-2],i[t+2]=i[i.length-1],i.length=i.length-3}_generateEdgesLinesAlternate(){const e=this._source.getVerticesData(er.PositionKind);let t=this._source.getIndices();if(!t||!e)return;Array.isArray(t)||(t=Array.from(t));const i=this._options?.useFastVertexMerger??!0,s=i?Math.round(-Math.log(this._options?.epsilonVertexMerge??1e-6)/Math.log(10)):this._options?.epsilonVertexMerge??1e-6,r=[],n=[];if(i){const t={};for(let i=0;il){const e=a;a=l,l=e}const c=a+"_"+l,u=o[c];u?u.done||(_e.Dot(s,u.normal)0||this._source.hasThinInstances)}render(){const e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera)return void this._lineShader._setDrawWrapper(t);const i=this._source.hasInstances&&this.customInstances.length>0,s=i||this._source.hasThinInstances;let r=0;if(s)if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){const e=this._source._instanceDataStorage;if(r=this.customInstances.length,!e.instancesData)return void(this._source.getScene()._activeMeshesFrozen||this.customInstances.reset());if(!e.isFrozen){let t=0;for(let i=0;i0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[r]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),s.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(s)}_resetLayout(){for(let e=0;enull!=e)),this._scene.autoClear=!0;const s=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!s&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const r=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||s,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?o=n:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:r&&(o=r),this._bindFrameBuffer(),this._linkInternalTexture(e,o)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;enull!=e)),e)){for(let s=0;s=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw xt("PrePassRendererSceneComponent")},qP.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}],Object.defineProperty(Hr.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),Hr.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new qP(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,Ne.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},Hr.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class ZP{constructor(e){this.name=or.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(or.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(or.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(or.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(or.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(or.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(or.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(or.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(or.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,s){if(!s)return;const r=e.getScene();r.prePassRenderer&&r.prePassRenderer.bindAttachmentsForEffect(s,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){}dispose(){this.scene.disablePrePassRenderer()}}qP._SceneComponentInitialization=e=>{let t=e._getComponent(or.NAME_PREPASSRENDERER);t||(t=new ZP(e),e._addComponent(t))};Bi.IncludesShadersStore.fibonacci="#define rcp(x) 1./x\n#define GOLDEN_RATIO 1.618033988749895\n#define TWO_PI 6.2831855\nvec2 Golden2dSeq(int i,float n)\n{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));}\nvec2 SampleDiskGolden(int i,int sampleCount)\n{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}";Bi.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";Bi.ShadersStore.subSurfaceScatteringPixelShader="#include\n#include\n#include\n#include\nvarying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40;\n#define rcp(x) 1./x\n#define Sq(x) x*x\n#define SSS_BILATERAL_FILTER true\nvec3 EvalBurleyDiffusionProfile(float r,vec3 S)\n{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); \nvec3 expSum=exp_13*(1.+exp_13*exp_13); \nreturn (S*rcp(8.*PI))*expSum; }\nvec2 SampleBurleyDiffusionProfile(float u,float rcpS)\n{u=1.-u; \nfloat g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); \nfloat p=(g*n)*n; \nfloat c=1.+p+n; \nfloat d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); \nfloat x=(3./LOG2_E)*log2(c)-d; \nfloat rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; \nreturn vec2(r,rcpPdf);}\nvec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)\n{\n#ifndef SSS_BILATERAL_FILTER\nz=0.;\n#endif\nfloat r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf;\n#if SSS_CLAMP_ARTIFACT\nreturn clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);\n#else\nreturn EvalBurleyDiffusionProfile(r,S)*area;\n#endif\n}\nvoid EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,\nfloat phase,inout vec3 totalIrradiance,inout vec3 totalWeight)\n{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; \nfloat cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; \nvec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; \nfloat xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a))\n{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;}\nelse\n{}}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest)\n{centerDepth=texture2D(depthSampler,vUV).r;}\nif (!passedStencilTest) { \ngl_FragColor=inputColor;return;}\nfloat distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; \nvec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; \nfloat mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1)\n{\n#ifdef DEBUG_SSS_SAMPLES\nvec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return;\n#endif\ngl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;}\n#ifdef DEBUG_SSS_SAMPLES\nvec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return;\n#endif\nfloat phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); \nvec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration)return void Ne.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");const i=this.texelSize;e.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",i.x,i.y),e.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),e.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),e.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),e.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),e.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)}))}}class eI{get ssDiffusionS(){return this._ssDiffusionS}get ssDiffusionD(){return this._ssDiffusionD}get ssFilterRadii(){return this._ssFilterRadii}constructor(e){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=or.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new Ee(1,1,1)),this._scene=e,eI._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return Ne.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw xt("SubSurfaceSceneComponent")},X.AddParser(or.NAME_SUBSURFACE,((e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,s=e.ssDiffusionProfileColors.length;i{let t=e._getComponent(or.NAME_SUBSURFACE);t||(t=new tI(e),e._addComponent(t))};Bi.ShadersStore.outlinePixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.outlineVertexShader="attribute vec3 position;attribute vec3 normal;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n#include\n}\n",Hr.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new iI(this)),this._outlineRenderer},Object.defineProperty(ha.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(ha.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});class iI{constructor(e){this.name=or.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(or.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(or.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{_.setMatrix("world",t)})),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=i??this._passIdForDrawWrapper[0];const s=[],r=[er.PositionKind,er.NormalKind],n=e.getMesh(),o=e.getMaterial();if(!o)return!1;const a=n.getScene();o.needAlphaTesting()&&(s.push("#define ALPHATEST"),n.isVerticesDataPresent(er.UVKind)&&(r.push(er.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(er.UV2Kind)&&(r.push(er.UV2Kind),s.push("#define UV2"))),o.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),go(o,a,s),n.useBones&&n.computeBonesUsingShaders?(r.push(er.MatricesIndicesKind),r.push(er.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(er.MatricesIndicesExtraKind),r.push(er.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):s.push("#define NUM_BONE_INFLUENCERS 0");const l=n.morphTargetManager;let h=0;l&&(h=l.numMaxInfluencers||l.numInfluencers,h>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),Eo(r,n,h))),t&&(s.push("#define INSTANCES"),Po(r),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const c=e._getDrawWrapper(i,!0),u=c.defines,d=s.join("\n");if(u!==d){const e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];mo(e),c.setEffect(this.scene.getEngine().createEffect("outline",r,e,["diffuseSampler","morphTargets"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),d)}return c.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const s=t.getMaterial();s&&s.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(iI._StencilReference),this._engine.setStencilFunctionReference(iI._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),s&&s.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const e=this._engine.getAlphaMode(),s=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=s}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}iI._StencilReference=4;class sI{get particleSize(){return this._particleSize}set particleSize(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))}get useInstancing(){return!this.indexBuffer}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&this._hasVelocity()&&(this._useVelocity=e,this._effectsAreDirty=!0)}_hasVelocity(){return!!this.vertexBuffers?.velocity}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new K,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){const e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new $l({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new $l({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})}isReady(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;const e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){const e=this.numParticles;if(!this._depthEffectWrapper||0===e)return;const t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}renderThicknessTexture(){const e=this.numParticles;if(!this._thicknessEffectWrapper||0===e)return;const t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(6),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0)}renderDiffuseTexture(){}dispose(){this._depthEffectWrapper?.dispose(),this._thicknessEffectWrapper?.dispose()}}class rI extends sI{get particleSystem(){return this._particleSystem}getClassName(){return"FluidRenderingObjectParticleSystem"}get useTrueRenderingForDiffuseTexture(){return this._useTrueRenderingForDiffuseTexture}set useTrueRenderingForDiffuseTexture(e){this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add((()=>{this._engine.setAlphaMode(2)}))))}get vertexBuffers(){return this._particleSystem.vertexBuffers}get indexBuffer(){return this._particleSystem.indexBuffer}constructor(e,t){super(e),this._useTrueRenderingForDiffuseTexture=!0,this._particleSystem=t,this._originalRender=t.render.bind(t),this._blendMode=t.blendMode,this._onBeforeDrawParticleObserver=null,this._updateInAnimate=this._particleSystem.updateInAnimate,this._particleSystem.updateInAnimate=!0,this._particleSystem.render=()=>0,this.particleSize=(t.minSize+t.maxSize)/2,this.useTrueRenderingForDiffuseTexture=!1}isReady(){return super.isReady()&&this._particleSystem.isReady()}get numParticles(){return this._particleSystem.getActiveCount()}renderDiffuseTexture(){this._originalRender()}dispose(){super.dispose(),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate}}class nI{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){const e=this._blurPostProcesses[0],t=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let i=0;i<2*this._blurNumIterations;++i)this._blurPostProcesses[i]=1&i?t:e}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}constructor(e,t,i,s,r,n,o=1,a=6,l=1,h=6,c=!1,u=null,d=!0,_=1){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new K,this._name=e,this._scene=t,this._camera=u,this._engine=t.getEngine(),this._width=i,this._height=s,this._blurTextureSizeX=r,this._blurTextureSizeY=n,this._textureType=o,this._textureFormat=a,this._blurTextureType=l,this._blurTextureFormat=h,this._useStandardBlur=c,this._generateDepthBuffer=d,this._samples=_,this._postProcessRunningIndex=0,this.enableBlur=0!==r&&0!==n,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){const[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});const e=this._rt.texture;e.incrementReferences(),this._texture=new Pa(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=Pa.CLAMP_ADDRESSMODE,this._texture.wrapV=Pa.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,s,r,n=!1){const o=this._scene.getEngine(),a=new de(Math.floor(this._blurTextureSizeX/s),Math.floor(this._blurTextureSizeY/s)),l=1===t&&o.getCaps().textureFloatLinearFiltering||2===t&&o.getCaps().textureHalfFloatLinearFiltering,h=this._engine.createRenderTargetTexture({width:a.x,height:a.y},{generateMipMaps:!1,type:t,format:i,samplingMode:l?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${r}`}),c=h.texture;c.incrementReferences();const u=new Pa(null,this._scene);if(u.name="rttBlurred"+r,u._texture=c,u.wrapU=Pa.CLAMP_ADDRESSMODE,u.wrapV=Pa.CLAMP_ADDRESSMODE,u.anisotropicFilteringLevel=1,n){const s=new Vl("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",s.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++})),s.onSizeChangedObservable.add((()=>{s._textures.forEach((e=>{e.texture.wrapU=Pa.CLAMP_ADDRESSMODE,e.texture.wrapV=Pa.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(s);const r=new Vl("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.onApplyObservable.add((e=>{e.setInt("filterSize",this.blurFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++})),r.onSizeChangedObservable.add((()=>{r._textures.forEach((e=>{e.texture.wrapU=Pa.CLAMP_ADDRESSMODE,e.texture.wrapV=Pa.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(r),s.autoClear=!1,r.autoClear=!1;const n=[];for(let e=0;e<2*this._blurNumIterations;++e)n[e]=1&e?r:s;return[h,u,n]}{const s=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],r=new Vl("BilateralBlurX","fluidRenderingBilateralBlur",s,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",r.inputTexture.texture),t.setInt("maxFilterSize",this.blurMaxFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),t.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),r.onSizeChangedObservable.add((()=>{r._textures.forEach((e=>{e.texture.wrapU=Pa.CLAMP_ADDRESSMODE,e.texture.wrapV=Pa.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(r);const n=new Vl("BilateralBlurY","fluidRenderingBilateralBlur",s,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);n.samples=this._samples,n.onApplyObservable.add((e=>{e.setInt("maxFilterSize",this.blurMaxFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),e.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),e.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),n.onSizeChangedObservable.add((()=>{n._textures.forEach((e=>{e.texture.wrapU=Pa.CLAMP_ADDRESSMODE,e.texture.wrapV=Pa.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(n),r.autoClear=!1,n.autoClear=!1;const a=[];for(let e=0;e<2*this._blurNumIterations;++e)a[e]=1&e?n:r;return[h,u,a]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})),e.onApplyObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})))}_getProjectedParticleConstant(){return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((this._camera?.fov??45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),this._rt?.dispose(),this._rt=null,this._texture?.dispose(),this._texture=null,this._rtBlur?.dispose(),this._rtBlur=null,this._textureBlurred?.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}var oI;!function(e){e[e.DepthTexture=0]="DepthTexture",e[e.DepthBlurredTexture=1]="DepthBlurredTexture",e[e.ThicknessTexture=2]="ThicknessTexture",e[e.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",e[e.DiffuseTexture=4]="DiffuseTexture",e[e.Normals=5]="Normals",e[e.DiffuseRendering=6]="DiffuseRendering"}(oI||(oI={}));class aI{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get compositeMode(){return this._compositeMode}set compositeMode(e){this._compositeMode!==e&&(this._compositeMode=e,this._needInitialization=!0)}get camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new Ee(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new _e(-2,-1,1).normalize(),this._debugFeature=oI.DepthBlurredTexture,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new K,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._compositeMode=!1,this._scene=e,this._engine=e.getEngine(),this._camera=t??e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new me,this._depthClearColor=new Ae(1e6,1e6,1e6,1),this._thicknessClearColor=new Ae(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){this.dispose(),this._needInitialization=!1;const e=this._depthMapSize??this._engine.getRenderWidth(),t=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new nI("Depth",this._scene,e,t,e,t,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const e=this._diffuseMapSize??this._engine.getRenderWidth(),t=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new nI("Diffuse",this._scene,e,t,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const i=this._thicknessMapSize??this._engine.getRenderWidth(),s=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new nI("Thickness",this._scene,i,s,i,s,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){null!==e&&e!==this._depthRenderTarget||this._setBlurDepthParameters(),null!==e&&e!==this._thicknessRenderTarget||this._setBlurThicknessParameters()}_setBlurDepthParameters(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)}_setBlurThicknessParameters(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)}_initializeRenderTarget(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()}_createLiquidRenderingPostProcess(){const e=this._scene.getEngine(),t=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],i=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;const r=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,n=new de(1/r.getSize().width,1/r.getSize().height);this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap&&(this._environmentMap??this._scene.environmentTexture)&&(i.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(i.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):t.push("diffuseColor"),this._useVelocity&&(i.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(t.push("thickness"),i.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(t.push("minimumThickness"),i.push("thicknessSampler")),this._compositeMode&&s.push("#define FLUIDRENDERING_COMPOSITE_MODE"),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===oI.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===oI.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),i.push("debugSampler"),this._debugFeature!==oI.DepthTexture&&this._debugFeature!==oI.DepthBlurredTexture||s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new Vl("FluidRendering","fluidRenderingRender",t,i,1,null,2,e,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(s.join("\n")),this._renderPostProcess.samples=this._samples;const o=e,a=o.setTextureSampler;this._renderPostProcess.onApplyObservable.add((e=>{if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),a&&a.call(o,"textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(e.setTexture("depthSampler",this._depthRenderTarget.textureBlur),a&&a.call(o,"depthSamplerSampler",this._depthRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),a&&a.call(o,"depthSamplerSampler",this._depthRenderTarget.texture?.getInternalTexture()??null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),a&&a.call(o,"diffuseSamplerSampler",this._diffuseRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),a&&a.call(o,"diffuseSamplerSampler",this._diffuseRenderTarget.texture?.getInternalTexture()??null)):e.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(e.setFloat("thickness",this.minimumThickness),e._bindTexture("bgDepthSampler",this._bgDepthTexture),a&&a.call(o,"bgDepthSamplerSampler",this._bgDepthTexture??null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),a&&a.call(o,"thicknessSamplerSampler",this._thicknessRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),a&&a.call(o,"thicknessSamplerSampler",this._thicknessRenderTarget.texture?.getInternalTexture()??null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){const t=this._environmentMap??this._scene.environmentTexture;t&&(e.setTexture("reflectionSampler",t),a&&a.call(o,"reflectionSamplerSampler",t?.getInternalTexture()??null))}if(e.setMatrix("viewMatrix",this._scene.getViewMatrix()),e.setMatrix("invProjectionMatrix",this._invProjectionMatrix),e.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),e.setVector2("texelSize",n),e.setFloat("density",this.density),e.setFloat("refractionStrength",this.refractionStrength),e.setFloat("fresnelClamp",this.fresnelClamp),e.setFloat("specularPower",this.specularPower),e.setVector3("dirLight",this.dirLight),e.setFloat("cameraFar",this._camera.maxZ),this._debug){let t=null;switch(this._debugFeature){case oI.DepthTexture:t=this._depthRenderTarget.texture;break;case oI.DepthBlurredTexture:t=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case oI.ThicknessTexture:t=this._thicknessRenderTarget?.texture??null;break;case oI.ThicknessBlurredTexture:t=this._thicknessRenderTarget?.enableBlur?this._thicknessRenderTarget?.textureBlur??null:this._thicknessRenderTarget?.texture??null;break;case oI.DiffuseTexture:this._diffuseRenderTarget&&(t=this._diffuseRenderTarget.texture)}this._debugFeature!==oI.Normals&&(e.setTexture("debugSampler",t),a&&a.call(o,"debugSamplerSampler",t?.getInternalTexture()??null))}}))}_clearTargets(){this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){if(this._needInitialization||!e.isReady())return;const t=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0),this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),this._depthRenderTarget?.applyBlurPostProcesses(),this._diffuseRenderTarget?.applyBlurPostProcesses(),this._thicknessRenderTarget?.applyBlurPostProcesses(),t&&this._engine.bindFramebuffer(t)}dispose(e=!1){e||(this._depthRenderTarget?.dispose(),this._depthRenderTarget=null,this._diffuseRenderTarget?.dispose(),this._diffuseRenderTarget=null,this._thicknessRenderTarget?.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),this._renderPostProcess?.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class lI extends sI{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i){super(e),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(const t in e){let i,s=!0;switch(t){case"velocity":i=3;break;case"offset":s=!1}this._vertexBuffers[t]=new er(this._engine,e[t],t,!0,!1,i,s)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new $l({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[]})}isReady(){return this._vertexBuffers.offset||(this._vertexBuffers.offset=new er(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&(this._diffuseEffectWrapper?.effect.isReady()??!1)}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){const e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)return;const t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),null!==this._particleSize&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){super.dispose(),this._diffuseEffectWrapper?.dispose();for(const e in this._vertexBuffers)this._vertexBuffers[e].dispose();this._vertexBuffers={}}}var hI;Bi.ShadersStore.copyTextureToTexturePixelShader="uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV;\n#include\nvoid main(void) \n{vec4 color=texture2D(textureSampler,vUV);\n#ifdef DEPTH_TEXTURE\ngl_FragDepth=color.r;\n#else\nif (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);}\ngl_FragColor=color;\n#endif\n}\n",function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(hI||(hI={}));class cI{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new Kl(e),this._effectWrapper=new $l({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add((()=>{t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.depthCullingState.depthFunc=519),this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)}))}isReady(){return this._effectWrapper.effect.isReady()}copy(e,t,i=hI.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;const s=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&s&&(this._engine.depthCullingState.depthFunc=s),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class uI{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,s=1){this._engine=e,this._copyTextureToTexture=new cI(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:s,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil").label=`FluidDepthTextureCopy${t}x${i}x${s}`}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}Bi.ShadersStore.fluidRenderingParticleDepthVertexShader="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nattribute vec3 velocity;varying float velocityNorm;\n#endif\nvoid main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0;\n#ifdef FLUIDRENDERING_VELOCITY\nvelocityNorm=length(velocity);\n#endif\n}\n";Bi.ShadersStore.fluidRenderingParticleDepthPixelShader="uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nvarying float velocityNorm;\n#endif\nvoid main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2);\n#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\n#endif\nvec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos;\n#ifdef WEBGPU\ngl_FragDepth=clipSpacePos.z/clipSpacePos.w;\n#else\ngl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;\n#endif\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nglFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);\n#else\nglFragColor=vec4(realViewPos.z,0.,0.,1.);\n#endif\n}\n";Bi.ShadersStore.fluidRenderingParticleThicknessVertexShader="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;}\n";Bi.ShadersStore.fluidRenderingParticleThicknessPixelShader="uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);}\n";Bi.ShadersStore.fluidRenderingParticleDiffuseVertexShader="attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;}\n";Bi.ShadersStore.fluidRenderingParticleDiffusePixelShader="uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);}\n";Bi.ShadersStore.fluidRenderingBilateralBlurPixelShader="uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;}\nint filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;}\nglFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);}\n";Bi.ShadersStore.fluidRenderingStandardBlurPixelShader="uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;}\nfloat sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;}\nsum/=wsum;glFragColor=vec4(sum.rgb,1.);}\n";function dI(e){return!!e.particleSystem}function _I(e){return!!e.addBuffers}Bi.ShadersStore.fluidRenderingRenderPixelShader="#define DISABLE_UNIFORMITY_ANALYSIS\n#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nuniform sampler2D textureSampler;uniform sampler2D depthSampler;\n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nuniform sampler2D diffuseSampler;\n#else\nuniform vec3 diffuseColor;\n#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform float thickness;uniform sampler2D bgDepthSampler;\n#else\nuniform float minimumThickness;uniform sampler2D thicknessSampler;\n#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nuniform samplerCube reflectionSampler;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nuniform sampler2D debugSampler;\n#endif\nuniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef FLUIDRENDERING_RHS\nndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#else\nndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\nvec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);}\nvoid main(void) {vec2 texCoord=vUV;\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvec4 color=texture2D(debugSampler,texCoord);\n#ifdef FLUIDRENDERING_DEBUG_DEPTH\nglFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);}\n#else\nglFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);}\n#endif\nreturn;\n#endif\nvec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r;\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nfloat thickness=texture2D(thicknessSampler,texCoord).x;\n#else\nfloat bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5;\n#endif\nvec4 backColor=texture2D(textureSampler,texCoord);\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {\n#else\nif (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\n#endif\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nglFragColor.rgb=backColor.rgb*backColor.a;glFragColor.a=backColor.a;\n#else\nglFragColor=backColor;\n#endif\nreturn;}\nvec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;}\nvec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;}\nvec3 normal=normalize(cross(ddy,ddx));\n#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\n#endif\n#ifndef WEBGPU\nif(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);}\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nglFragColor=vec4(normal*0.5+0.5,1.0);return;\n#endif\nvec3 rayDir=normalize(viewPos); \n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;\n#endif\nvec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower);\n#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nfloat diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return;\n#endif\nvec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nif (transmitted.a==0.) transmitted.a=thickness;\n#endif\nvec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); \nvec3 refractionColor=transmitted.rgb*transmittance;\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular;\n#else\nvec3 finalColor=refractionColor+specular;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfloat velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));\n#endif\nglFragColor=vec4(finalColor,transmitted.a);}\n",Object.defineProperty(Hr.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),Hr.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new fI(this)),this._fluidRenderer},Hr.prototype.disableFluidRenderer=function(){this._fluidRenderer?.dispose(),this._fluidRenderer=null};class pI{constructor(e){this.name=or.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(or.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(or.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){this.scene.fluidRenderer?._prepareRendering()}_afterCameraDraw(e){this.scene.fluidRenderer?._render(e)}rebuild(){const e=this.scene.fluidRenderer;if(!e)return;const t=new Set;for(let i=0;i{e._rebuild()}))}dispose(){this.scene.disableFluidRenderer()}}class fI{static _SceneComponentInitialization(e){let t=e._getComponent(or.NAME_FLUIDRENDERER);t||(t=new pI(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,fI._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add((()=>{this._initialize()}))}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){const t=this._getParticleSystemIndex(e);return-1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,s){const r=new rI(this._scene,e);r.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),i||(i=new aI(this._scene,s),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==t&&(i.generateDiffuseTexture=t);const n={object:r,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,s,r){const n=new lI(this._scene,e,t);n.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),s||(s=new aI(this._scene,r),this.targetRenderers.push(s)),s._onUseVelocityChanged.hasObservers()||s._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==i&&(s.generateDiffuseTexture=i);const o={object:n,targetRenderer:s};return this.renderObjects.push(o),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),o}removeRenderObject(e,t=!0){const i=this.renderObjects.indexOf(e);return-1!==i&&(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort(((e,t)=>e.object.priorityt.object.priority?1:0))}_removeUnusedTargetRenderers(){const e={};for(let t=0;t{r.inputTexture.depthStencilTexture||r.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,n[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${r.name}`);for(const e of n){const t=e._thicknessRenderTarget?.renderTarget,i=t?.texture;if(t&&i){const e=i.width+"_"+i.height;let s=o[e];s||(s=o[e]=new uI(this._engine,i.width,i.height)),s.depthRTWrapper.shareDepth(t)}}}))}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value,s=this._cameras.get(t)[1],r=e.get(t);if(r)for(const e in s)r[1][e]||s[e].dispose();else for(const e in s)s[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){const e=new Map;for(let t=0;t{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)}))}_setUseVelocityForRenderObject(){for(const e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(const e of this.targetRenderers)if(e.needInitialization)return void this._initialize()}_render(e){for(let t=0;t{const t=e[1];for(const e in t)t[e].dispose()})),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class mI{get enable(){return this._enable}set enable(e){this._enable!==e&&(this._enable=e,this._customRenderTarget(e))}get positionWorldTexture(){return this._mrt.textures[0]}get normalWorldTexture(){return this._mrt.textures[1]}get fluxTexture(){return this._mrt.textures[2]}get renderList(){return this._mrt.renderList}get light(){return this._light}constructor(e,t,i={width:512,height:512}){this._lightTransformMatrix=me.Identity(),this._enable=!1,this.forceUpdateLightParameters=!1,this._scene=e,this._light=t,this._textureDimensions=i,this._regularMatToMatWithPlugin=new Map,this._counters=[{name:"RSM Generation "+t.name,value:0}],this._createMultiRenderTarget(),this._recomputeLightTransformationMatrix(),this.enable=!0}setTextureDimensions(e){const t=this._mrt.renderList;this._textureDimensions=e,this._disposeMultiRenderTarget(),this._createMultiRenderTarget(),t?.forEach((e=>{this._addMeshToMRT(e)}))}addMesh(e){e?this._addMeshToMRT(e):this._scene.meshes.forEach((e=>{this._addMeshToMRT(e)})),this._recomputeLightTransformationMatrix()}updateLightParameters(){this._recomputeLightTransformationMatrix()}get lightTransformationMatrix(){return this.forceUpdateLightParameters&&this.updateLightParameters(),this._lightTransformMatrix}get countersGPU(){return this._counters}dispose(){this._disposeMultiRenderTarget()}_createMultiRenderTarget(){const e=this._light.name,t=this._scene.getEngine().getCaps(),i=t.rg11b10ufColorRenderable?13:2,s=t.rg11b10ufColorRenderable?4:5;let r,n;this._mrt=new xb("RSMmrt_"+e,this._textureDimensions,3,this._scene,{types:[2,11,i],samplingModes:[2,2,2],generateMipMaps:!1,targetTypes:[3553,3553,3553],formats:[5,5,s]},["RSMPosition_"+e,"RSMNormal_"+e,"RSMFlux_"+e]),this._mrt.renderList=[],this._mrt.clearColor=new Ae(0,0,0,1),this._mrt.noPrePassRenderer=!0;const o=this._scene.getEngine().supportsUniformBuffers;let a;o&&(r=this._scene.createSceneUniformBuffer(`Scene for RSM (light "${e}")`)),this._mrt.onBeforeBindObservable.add((()=>{n=this._scene.getSceneUniformBuffer(),a=this._light.shadowEnabled,this._light.shadowEnabled=!1})),this._mrt.onBeforeRenderObservable.add((e=>{r&&this._scene.setSceneUniformBuffer(r);const t=this._light.getViewMatrix(e),i=this._light.getProjectionMatrix(t||void 0,this._mrt.renderList||void 0);t&&i&&this._scene.setTransformMatrix(t,i),o&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._mrt.onAfterUnbindObservable.add((()=>{r&&this._scene.setSceneUniformBuffer(n),this._scene.updateTransformMatrix(),this._light.shadowEnabled=a,this._counters[0].value=this._mrt.renderTarget.gpuTimeInFrame?.counter.lastSecAverage??0})),this._customRenderTarget(!0)}_customRenderTarget(e){const t=this._scene.customRenderTargets.indexOf(this._mrt);e?-1===t&&this._scene.customRenderTargets.push(this._mrt):-1!==t&&this._scene.customRenderTargets.splice(t,1)}_recomputeLightTransformationMatrix(){const e=this._light.getViewMatrix(),t=this._light.getProjectionMatrix(e||void 0,this._mrt.renderList||void 0);e&&t&&e.multiplyToRef(t,this._lightTransformMatrix)}_addMeshToMRT(e){this._mrt.renderList?.push(e);const t=e.material;if(0===e.getTotalVertices()||!t)return;let i=this._regularMatToMatWithPlugin.get(t);if(!i&&(i=t.clone("RSMCreate_"+t.name)||void 0,i)){Object.defineProperty(i,"canRenderToMRT",{get:function(){return!1},enumerable:!0,configurable:!0}),i.disableLighting=!0;const e=new vI(i);e.isEnabled=!0,e.light=this._light,this._regularMatToMatWithPlugin.set(t,i)}this._mrt.setMaterialForRendering(e,i)}_disposeMultiRenderTarget(){this._customRenderTarget(!1),this._mrt.dispose()}}class gI extends xl{constructor(){super(...arguments),this.RSMCREATE=!1,this.RSMCREATE_PROJTEXTURE=!1,this.RSMCREATE_LIGHT_IS_SPOT=!1}}class vI extends nu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,vI.Name,300,new gI),this._lightColor=new Ee,this._hasProjectionTexture=!1,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._varAlbedoName=e instanceof Gg?"surfaceAlbedo":"baseColor.rgb"}prepareDefines(e){e.RSMCREATE=this._isEnabled,this._hasProjectionTexture=!1;const t=this.light.getTypeID()===ua.LIGHTTYPEID_SPOTLIGHT;if(t){const e=this.light;this._hasProjectionTexture=!!e.projectionTexture&&e.projectionTexture.isReady()}e.RSMCREATE_PROJTEXTURE=this._hasProjectionTexture,e.RSMCREATE_LIGHT_IS_SPOT=t}getClassName(){return"RSMCreatePluginMaterial"}getUniforms(){return{ubo:[{name:"rsmTextureProjectionMatrix",size:16,type:"mat4"},{name:"rsmSpotInfo",size:4,type:"vec4"},{name:"rsmLightColor",size:3,type:"vec3"},{name:"rsmLightPosition",size:3,type:"vec3"}],fragment:"#ifdef RSMCREATE\n uniform mat4 rsmTextureProjectionMatrix;\n uniform vec4 rsmSpotInfo;\n uniform vec3 rsmLightColor;\n uniform vec3 rsmLightPosition;\n #endif"}}getSamplers(e){e.push("rsmTextureProjectionSampler")}bindForSubMesh(e){if(this._isEnabled&&(this.light.diffuse.scaleToRef(this.light.getScaledIntensity(),this._lightColor),e.updateColor3("rsmLightColor",this._lightColor),this.light.getTypeID()===ua.LIGHTTYPEID_SPOTLIGHT)){const t=this.light;this._hasProjectionTexture&&(e.updateMatrix("rsmTextureProjectionMatrix",t.projectionTextureMatrix),e.setTexture("rsmTextureProjectionSampler",t.projectionTexture));const i=ve.Vector3[0];t.computeTransformedInformation()?(e.updateFloat3("rsmLightPosition",this.light.transformedPosition.x,this.light.transformedPosition.y,this.light.transformedPosition.z),t.transformedDirection.normalizeToRef(i)):(e.updateFloat3("rsmLightPosition",this.light.position.x,this.light.position.y,this.light.position.z),t.direction.normalizeToRef(i)),e.updateFloat4("rsmSpotInfo",i.x,i.y,i.z,Math.cos(.5*t.angle))}}getCustomCode(e){return"vertex"===e?null:{CUSTOM_FRAGMENT_BEGIN:"\n #ifdef RSMCREATE\n #extension GL_EXT_draw_buffers : require\n #endif\n ",CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RSMCREATE\n #ifdef RSMCREATE_PROJTEXTURE\n uniform highp sampler2D rsmTextureProjectionSampler; \n #endif\n layout(location = 0) out highp vec4 glFragData[3];\n vec4 glFragColor;\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:`\n #ifdef RSMCREATE\n vec3 rsmColor = ${this._varAlbedoName} * rsmLightColor;\n #ifdef RSMCREATE_PROJTEXTURE\n {\n vec4 strq = rsmTextureProjectionMatrix * vec4(vPositionW, 1.0);\n strq /= strq.w;\n rsmColor *= texture2D(rsmTextureProjectionSampler, strq.xy).rgb;\n }\n #endif\n #ifdef RSMCREATE_LIGHT_IS_SPOT\n {\n float cosAngle = max(0., dot(rsmSpotInfo.xyz, normalize(vPositionW - rsmLightPosition)));\n rsmColor = sign(cosAngle - rsmSpotInfo.w) * rsmColor;\n }\n #endif\n glFragData[0] = vec4(vPositionW, 1.);\n glFragData[1] = vec4(normalize(normalW) * 0.5 + 0.5, 1.);\n glFragData[2] = vec4(rsmColor, 1.);\n #endif\n `}}}vI.Name="RSMCreate",Ze([rt()],vI.prototype,"light",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],vI.prototype,"isEnabled",void 0),z("BABYLON.RSMCreatePluginMaterial",vI);class xI{constructor(e){this.numSamples=400,this.radius=.1,this.intensity=.1,this.edgeArtifactCorrection=.1,this.rotateSample=!0,this.noiseFactor=100,this.useFullTexture=!1,this.rsm=e}dispose(){this.rsm.dispose()}}Bi.ShadersStore.bilateralBlurPixelShader="uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec3 sampleColor=textureLod(textureSampler,vUV+coords*blurDir,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords*blurDir,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords*blurDir,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat r=dot(coords,coords);float w=exp(-r/two_sigma2);float depthDelta=abs(sampleDepth-depth);float wd=step(depthDelta,depthThreshold);vec3 normalDelta=abs(sampleNormal-normal);float wn=step(normalDelta.x+normalDelta.y+normalDelta.z,normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}\nglFragColor=vec4(sum/wsum,1.);}\n";Bi.ShadersStore.bilateralBlurQualityPixelShader="uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {for (int y=-filterSize; y<=filterSize; ++y) {vec2 coords=vec2(x,y)*blurDir;vec3 sampleColor=textureLod(textureSampler,vUV+coords,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepth-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);float rNormal=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);float wn=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}}\nglFragColor=vec4(sum/wsum,1.);}\n";Bi.ShadersStore.rsmGlobalIlluminationPixelShader="/**\n* The implementation is an application of the formula found in http:\n* For better results,it also adds a random (noise) rotation to the RSM samples (the noise artifacts are easier to remove than the banding artifacts).\n*/\nprecision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform vec4 rsmInfo2;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;uniform sampler2D rsmSamples;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nfloat mod289(float x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 perm(vec4 x){return mod289(((x*34.0)+1.0)*x);}\nfloat noise(vec3 p){vec3 a=floor(p);vec3 d=p-a;d=d*d*(3.0-2.0*d);vec4 b=a.xxyy+vec4(0.0,1.0,0.0,1.0);vec4 k1=perm(b.xyxy);vec4 k2=perm(k1.xyxy+b.zzww);vec4 c=k2+a.zzzz;vec4 k3=perm(c);vec4 k4=perm(c+1.0);vec4 o1=fract(k3*(1.0/41.0));vec4 o2=fract(k4*(1.0/41.0));vec4 o3=o2*d.z+o1*(1.0-d.z);vec2 o4=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);}\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);int numSamples=int(rsmInfo.x);float radius=rsmInfo.y;float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;float angle=noise(p*rsmInfo2.x);float c=cos(angle);float s=sin(angle);for (int i=0; i1. || uv.y<0. || uv.y>1.) continue;vec3 vplPositionW=textureLod(rsmPositionW,uv,0.).xyz;vec3 vplNormalW=textureLod(rsmNormalW,uv,0.).xyz*2.0-1.0;vec3 vplFlux=textureLod(rsmFlux,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; \nfloat dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}\nreturn clamp(indirectDiffuse*intensity,0.0,1.0);}\nvoid main(void) \n{vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz;\n#ifdef DECODE_NORMAL\nnormalW=normalW*2.0-1.0;\n#endif\n#ifdef TRANSFORM_NORMAL\nnormalW=(invView*vec4(normalW,0.)).xyz;\n#endif\ngl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;}\n";Bi.ShadersStore.rsmFullGlobalIlluminationPixelShader="/**\n* The implementation is a direct application of the formula found in http:\n*/\nprecision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;int width=int(rsmInfo.x);int height=int(rsmInfo.y);for (int j=0; j{t.pluginManager&&(t.pluginManager.getPlugin(yI.Name).isEnabled=e)})),this.recreateResources(!e))}get enableBlur(){return this._enableBlur}set enableBlur(e){e!==this._enableBlur&&(this._enableBlur=e,this.recreateResources())}get useQualityBlur(){return this._useQualityBlur}set useQualityBlur(e){e!==this._useQualityBlur&&(this._useQualityBlur=e,this.recreateResources())}get fullSizeBlur(){return this._forceFullSizeBlur}set fullSizeBlur(e){this._forceFullSizeBlur!==e&&(this._forceFullSizeBlur=e,this.recreateResources())}get useQualityUpsampling(){return this._useQualityUpsampling}set useQualityUpsampling(e){e!==this._useQualityUpsampling&&(this._useQualityUpsampling=e,this.recreateResources())}get showOnlyGI(){return this._showOnlyGI}set showOnlyGI(e){this._showOnlyGI!==e&&(this._showOnlyGI=e,this._debugLayer.isEnabled=e)}get use32BitsDepthBuffer(){return this._use32BitsDepthBuffer}set use32BitsDepthBuffer(e){this._use32BitsDepthBuffer!==e&&(this._use32BitsDepthBuffer=e,this.recreateResources())}setOutputDimensions(e){this._outputDimensions=e,this.recreateResources()}setGITextureDimensions(e){this._giTextureDimensions=e,this.recreateResources()}get giTextureType(){return this._giTextureType}set giTextureType(e){this._giTextureType!==e&&(this._giTextureType=e,this.recreateResources())}get giRSM(){return this._giRSM}addGIRSM(e){Array.isArray(e)?this._giRSM.push(...e):this._giRSM.push(e),this.recreateResources()}removeGIRSM(e){if(Array.isArray(e))for(let t=0;t{e.getTotalVertices()>0&&e.isEnabled()&&e.material&&this._addGISupportToMaterial(e.material)}))}get countersGPU(){return this._counters}recreateResources(e=!1){this._disposePostProcesses(e),this._createPostProcesses(),this._setPluginParameters()}generateSampleTexture(e){this._sampleTexture?.dispose(),this._maxSamples=e;const t=new Float32Array(4*this._maxSamples);for(let e=0;e{const e=this._engine._currentRenderTarget;let t=!1;if(this._enable){this.pause||(this._scene.postProcessManager.directRender(this._ppGlobalIllumination,this._ppGlobalIllumination[0].inputTexture),this._engine.unBindFramebuffer(this._ppGlobalIllumination[0].inputTexture,!0),this._engine.setAlphaMode(0),t=!0,this.enableBlur&&this._blurPostProcesses&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,this._blurRTT.renderTarget,!0),this._engine.unBindFramebuffer(this._blurRTT.renderTarget,!0)));for(let e=0;e{if(e.pluginManager){const t=e.pluginManager.getPlugin(yI.Name);t.textureGIContrib=this.enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height}}))}_createPostProcesses(){if(!this._enable)return;const e=13===this._giTextureType?4:5;this._firstActivation&&(this._firstActivation=!1,this._geomBufferEnabled=!!this._scene.geometryBufferRenderer,this._geomBufferEnablePosition=this._scene.geometryBufferRenderer?.enablePosition??!1),this._geomBufferEnabled||this._scene.disableGeometryBufferRenderer();const t=this._scene.enableGeometryBufferRenderer(this._enableBlur?this._outputDimensions:this._giTextureDimensions,this._use32BitsDepthBuffer?14:15,bI.GeometryBufferTextureTypesAndFormats);if(!t)throw new Error("Geometry buffer renderer is not supported but is required for GIRSMManager.");t.enablePosition=!0,this._geomBufferEnabled||(t.generateNormalsInWorldSpace=!0);const i=t.normalsAreUnsigned,s=t.generateNormalsInWorldSpace;this._counters.push({name:"Geometry buffer renderer",value:0}),this._countersRTW.push([this._scene.geometryBufferRenderer.getGBuffer().renderTarget]);let r="";i&&(r+="#define DECODE_NORMAL\n"),s||(r+="#define TRANSFORM_NORMAL\n");for(let i=0;i{e.setTexture("textureSampler",t.getGBuffer().textures[t.getTextureIndex(mP.POSITION_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(mP.NORMAL_TEXTURE_TYPE)]),e.setTexture("rsmPositionW",o.positionWorldTexture),e.setTexture("rsmNormalW",o.normalWorldTexture),e.setTexture("rsmFlux",o.fluxTexture),e.setMatrix("rsmLightMatrix",o.lightTransformationMatrix),n.useFullTexture?e.setFloat4("rsmInfo",o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height,n.intensity,n.edgeArtifactCorrection):(e.setTexture("rsmSamples",this._sampleTexture),e.setFloat4("rsmInfo",n.numSamples,n.radius,n.intensity,n.edgeArtifactCorrection),e.setFloat4("rsmInfo2",n.noiseFactor,n.rotateSample?1:0,o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height)),s||(this._tempMatrix.copyFrom(this._scene.activeCamera.getViewMatrix()),this._tempMatrix.invert(),e.setMatrix("invView",this._tempMatrix))}))}for(const e of this._ppGlobalIllumination)e.inputTexture||e.resize(this._giTextureDimensions.width,this._giTextureDimensions.height);if(this._counters.push({name:"GI generation",value:0}),this._countersRTW.push([this._ppGlobalIllumination[0].inputTexture]),this._enableBlur){const s=this._forceFullSizeBlur?this._outputDimensions:this._giTextureDimensions;this._blurRTT=new ih("GIRSMContribution",this._outputDimensions,this._scene,{type:this._giTextureType,format:e,generateDepthBuffer:!1}),this._blurRTT.wrapU=0,this._blurRTT.wrapV=0,this._blurRTT.updateSamplingMode(1),this._blurRTT.skipInitialClear=!0;const r=[];if(this._counters.push({name:"GI blur",value:0}),this._countersRTW.push(r),this._blurXPostprocess=new Vl(this._useQualityBlur?"BilateralBlur":"BilateralBlurX",this._useQualityBlur?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._blurXPostprocess.onApplyObservable.add((e=>{e._bindTexture("textureSampler",this._ppGlobalIllumination[0].inputTexture.texture),e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(mP.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(mP.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",1/this._giTextureDimensions.width,this._useQualityBlur?1/this._giTextureDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurXPostprocess.externalTextureSamplerBinding=!0,this._blurXPostprocess.autoClear=!1,this._useQualityBlur||(this._blurYPostprocess=new Vl("BilateralBlurY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._blurYPostprocess.autoClear=!1,this._blurYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(mP.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(mP.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",0,1/this._giTextureDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurYPostprocess.resize(s.width,s.height),r.push(this._blurYPostprocess.inputTexture)),this._blurPostProcesses=[this._blurXPostprocess],this._blurYPostprocess&&this._blurPostProcesses.push(this._blurYPostprocess),this._giTextureDimensions.width>=this._outputDimensions.width&&this._giTextureDimensions.height>=this._outputDimensions.height||this._forceFullSizeBlur)r.push(this._blurRTT.renderTarget);else{const n=[];this._counters.push({name:"GI upsampling",value:0}),this._countersRTW.push(n),this._upsamplingXPostprocess=new Vl(this._useQualityUpsampling?"BilateralUpsampling":"BilateralUpsamplingX",this._useQualityUpsampling?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._upsamplingXPostprocess.autoClear=!1,this._upsamplingXPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(mP.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(mP.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",1/this._outputDimensions.width,this._useQualityUpsampling?1/this._outputDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingXPostprocess.resize(s.width,s.height),r.push(this._upsamplingXPostprocess.inputTexture),this.useQualityUpsampling||(this._upsamplingYPostprocess=new Vl("BilateralUpsamplingY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:this._outputDimensions,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._upsamplingYPostprocess.autoClear=!1,this._upsamplingYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(mP.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(mP.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",0,1/this._outputDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingYPostprocess.resize(this._outputDimensions.width,this._outputDimensions.height),n.push(this._upsamplingYPostprocess.inputTexture)),n.push(this._blurRTT.renderTarget),this._blurPostProcesses.push(this._upsamplingXPostprocess),this._upsamplingYPostprocess&&this._blurPostProcesses.push(this._upsamplingYPostprocess)}}this._debugLayer.texture?.dispose(),this._debugLayer.texture=new ya(this._scene,this._enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture)}_addGISupportToMaterial(e){if(e.pluginManager?.getPlugin(yI.Name))return;const t=new yI(e);this._enable&&this._ppGlobalIllumination.length>0&&(t.textureGIContrib=this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height),t.isEnabled=this._enable,this._materialsWithRenderPlugin.push(e)}}bI.GeometryBufferTextureTypesAndFormats={0:{textureType:2,textureFormat:6},1:{textureType:11,textureFormat:5},2:{textureType:2,textureFormat:5}};class TI extends xl{constructor(){super(...arguments),this.RENDER_WITH_GIRSM=!1,this.RSMCREATE_PROJTEXTURE=!1}}class yI extends nu{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,yI.Name,310,new TI),this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._isPBR=e instanceof Gg}prepareDefines(e){e.RENDER_WITH_GIRSM=this._isEnabled}getClassName(){return"GIRSMRenderPluginMaterial"}getUniforms(){return{ubo:[{name:"girsmTextureOutputSize",size:2,type:"vec2"}],fragment:"#ifdef RENDER_WITH_GIRSM\n uniform vec2 girsmTextureOutputSize;\n #endif"}}getSamplers(e){e.push("girsmTextureGIContrib")}bindForSubMesh(e){this._isEnabled&&(e.bindTexture("girsmTextureGIContrib",this.textureGIContrib),e.updateFloat2("girsmTextureOutputSize",this.outputTextureWidth,this.outputTextureHeight))}getCustomCode(e){const t={CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RENDER_WITH_GIRSM\n uniform sampler2D girsmTextureGIContrib;\n\n vec3 computeIndirect() {\n vec2 uv = gl_FragCoord.xy / girsmTextureOutputSize;\n return texture2D(girsmTextureGIContrib, uv).rgb;\n }\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:"\n #ifdef RENDER_WITH_GIRSM\n finalDiffuse += computeIndirect() * surfaceAlbedo.rgb;\n #endif\n "};return this._isPBR||(t.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR="\n #ifdef RENDER_WITH_GIRSM\n color.rgb += computeIndirect() * baseColor.rgb;\n #endif\n "),"vertex"===e?null:t}}yI.Name="GIRSMRender",Ze([rt()],yI.prototype,"textureGIContrib",void 0),Ze([rt()],yI.prototype,"outputTextureWidth",void 0),Ze([rt()],yI.prototype,"outputTextureHeight",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],yI.prototype,"isEnabled",void 0),z("BABYLON.GIRSMRenderPluginMaterial",yI);Bi.ShadersStore.spriteMapPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nprecision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4(\ntexture2D(frameMap,vec2(fX,0.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*1.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*2.),0.),\nvec4(0.)\n);}\nvoid main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV);\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\nvec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; fmt){frameID=animationData.x;break;}\nanimationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}}\nmat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;}\nvec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}}\ncolor.xyz*=colorMul;gl_FragColor=color;}";Bi.ShadersStore.spriteMapVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; \ngl_Position=worldViewProjection*p;}";class SI{get spriteCount(){return this.sprites.length}get position(){return this._output.position}set position(e){this._output.position=e}get rotation(){return this._output.rotation}set rotation(e){this._output.rotation=e}get animationMap(){return this._animationMap}set animationMap(e){const t=e._texture._bufferView,i=this._createTileAnimationBuffer(t);this._animationMap.dispose(),this._animationMap=i,this._material.setTexture("animationMap",this._animationMap)}constructor(e,t,i,s,r){this.name=e,this.sprites=[],this.atlasJSON=t,this.sprites=this.atlasJSON.frames,this.spriteSheet=i,this.options=s,s.stageSize=s.stageSize||new de(1,1),s.outputSize=s.outputSize||s.stageSize,s.outputPosition=s.outputPosition||_e.Zero(),s.outputRotation=s.outputRotation||_e.Zero(),s.layerCount=s.layerCount||1,s.maxAnimationFrames=s.maxAnimationFrames||0,s.baseTile=s.baseTile||0,s.flipU=s.flipU||!1,s.colorMultiply=s.colorMultiply||new _e(1,1,1),this._scene=r,this._frameMap=this._createFrameBuffer(),this._tileMaps=new Array;for(let e=0;e{this.spriteSheet&&this.spriteSheet.isReady()&&this.spriteSheet._texture?this._material.setVector2("spriteMapSize",new de(this.spriteSheet._texture.baseWidth||1,this.spriteSheet._texture.baseHeight||1)):l<100&&setTimeout((()=>{l++,h()}),100)};h(),this._material.setVector3("colorMul",s.colorMultiply),this._material.setTexture("frameMap",this._frameMap),this._material.setTextureArray("tileMaps",this._tileMaps),this._material.setTexture("animationMap",this._animationMap),this._material.setFloat("time",this._time),this._output=Wa(e+":output",{size:1,updatable:!0},r),this._output.scaling.x=s.outputSize.x,this._output.scaling.y=s.outputSize.y,this.position=s.outputPosition,this.rotation=s.outputRotation,this._scene.onBeforeRenderObservable.add((()=>{this._time+=this._scene.getEngine().getDeltaTime(),this._material.setFloat("time",this._time)})),this._output.material=this._material}getTileID(){const e=this.getMousePosition();return e.multiplyInPlace(this.options.stageSize||de.Zero()),e.x=Math.floor(e.x),e.y=Math.floor(e.y),e}getMousePosition(){const e=this._output,t=this._scene.pick(this._scene.pointerX,this._scene.pointerY,(t=>t===e));if(!t||!t.hit||!t.getTextureCoordinates)return new de(-1,-1);return t.getTextureCoordinates()||new de(-1,-1)}_createFrameBuffer(){const e=[];for(let t=0;t0&&(e+="\n\r"),e+=this._tileMaps[t]._texture._bufferView.toString();const t=document.createElement("a");t.href="data:octet/stream;charset=utf-8,"+encodeURI(e),t.target="_blank",t.download=this.name+".tilemaps",t.click(),t.remove()}loadTileMaps(e){const t=new XMLHttpRequest;t.open("GET",e);const i=this.options.layerCount||0;t.onload=()=>{const e=t.response.split("\n\r");for(let t=0;t{e.dispose()})),this._frameMap.dispose()}}class CI extends bx{constructor(e,t,i,s,r=null,n=.01,o=Pa.TRILINEAR_SAMPLINGMODE){super(e,t,i,64,s,n,o,!0,r),this.name=e}}var EI;!function(e){e[e.INIT=0]="INIT",e[e.RUNNING=1]="RUNNING",e[e.DONE=2]="DONE",e[e.ERROR=3]="ERROR"}(EI||(EI={}));class AI{constructor(e){this.name=e,this._isCompleted=!1,this._taskState=EI.INIT}get isCompleted(){return this._isCompleted}get taskState(){return this._taskState}get errorObject(){return this._errorObject}_setErrorObject(e,t){this._errorObject||(this._errorObject={message:e,exception:t})}run(e,t,i){this._taskState=EI.RUNNING,this.runTask(e,(()=>{this._onDoneCallback(t,i)}),((e,t)=>{this._onErrorCallback(i,e,t)}))}runTask(e,t,i){throw new Error("runTask is not implemented")}reset(){this._taskState=EI.INIT}_onErrorCallback(e,t,i){this._taskState=EI.ERROR,this._errorObject={message:t,exception:i},this.onError&&this.onError(this,t,i),e()}_onDoneCallback(e,t){try{this._taskState=EI.DONE,this._isCompleted=!0,this.onSuccess&&this.onSuccess(this),e()}catch(e){this._onErrorCallback(t,"Task is done, error executing success callback(s)",e)}}}class PI{constructor(e,t,i){this.remainingCount=e,this.totalCount=t,this.task=i}}class II extends AI{constructor(e,t,i,s,r){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=s,this.extension=r}runTask(e,t,i){fl.LoadAssetContainer(this.rootUrl,this.sceneFilename,e,(e=>{this.loadedContainer=e,this.loadedMeshes=e.meshes,this.loadedTransformNodes=e.transformNodes,this.loadedParticleSystems=e.particleSystems,this.loadedSkeletons=e.skeletons,this.loadedAnimationGroups=e.animationGroups,t()}),null,((e,t,s)=>{i(t,s)}),this.extension)}}class RI extends AI{constructor(e,t,i,s,r){super(e),this.name=e,this.meshesNames=t,this.rootUrl=i,this.sceneFilename=s,this.extension=r}runTask(e,t,i){fl.ImportMesh(this.meshesNames,this.rootUrl,this.sceneFilename,e,((e,i,s,r,n)=>{this.loadedMeshes=e,this.loadedTransformNodes=n,this.loadedParticleSystems=i,this.loadedSkeletons=s,this.loadedAnimationGroups=r,t()}),null,((e,t,s)=>{i(t,s)}),this.extension)}}class MI extends AI{constructor(e,t,i,s,r){super(e),this.name=e,this.rootUrl=t,this.filename=i,this.targetConverter=s,this.extension=r}runTask(e,t,i){const s=e.animatables.length,r=e.animationGroups.length;this.loadedAnimatables=[],this.loadedAnimationGroups=[],fl.ImportAnimations(this.rootUrl,this.filename,e,!1,ol.NoSync,this.targetConverter,(()=>{this.loadedAnimatables=e.animatables.slice(s),this.loadedAnimationGroups=e.animationGroups.slice(r),t()}),null,((e,t,s)=>{i(t,s)}),this.extension)}}class OI extends AI{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.text=e,t()}),void 0,!1,!1,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class DI extends AI{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){e._loadFile(this.url,(e=>{this.data=e,t()}),void 0,!0,!0,((e,t)=>{e&&i(e.status+" "+e.statusText,t)}))}}class wI extends AI{constructor(e,t){super(e),this.name=e,this.url=t}runTask(e,t,i){const s=new Image;Ds.SetCorsBehavior(this.url,s),s.onload=()=>{this.image=s,t()},s.onerror=e=>{i("Error loading image",e)},s.src=this.url}}class NI extends AI{constructor(e,t,i,s=!0,r=Pa.TRILINEAR_SAMPLINGMODE){super(e),this.name=e,this.url=t,this.noMipmap=i,this.invertY=s,this.samplingMode=r}runTask(e,t,i){this.texture=new Pa(this.url,e,this.noMipmap,this.invertY,this.samplingMode,(()=>{t()}),((e,t)=>{i(e,t)}))}}class FI extends AI{constructor(e,t,i,s,r,n){super(e),this.name=e,this.url=t,this.extensions=i,this.noMipmap=s,this.files=r,this.prefiltered=n}runTask(e,t,i){this.texture=new vg(this.url,e,this.extensions,this.noMipmap,this.files,(()=>{t()}),((e,t)=>{i(e,t)}),void 0,this.prefiltered)}}class LI extends AI{constructor(e,t,i,s=!1,r=!0,n=!1,o=!1){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=s,this.generateHarmonics=r,this.gammaSpace=n,this.reserved=o}runTask(e,t,i){this.texture=new nx(this.url,e,this.size,this.noMipmap,this.generateHarmonics,this.gammaSpace,this.reserved,(()=>{t()}),((e,t)=>{i(e,t)}))}}class BI extends AI{constructor(e,t,i,s=!1,r=!0){super(e),this.name=e,this.url=t,this.size=i,this.noMipmap=s,this.gammaSpace=r}runTask(e,t,i){this.texture=new Vx(this.url,e,this.size,this.noMipmap,this.gammaSpace,(()=>{t()}),((e,t)=>{i(e,t)}))}}class kI{constructor(e){this._isLoading=!1,this._tasks=new Array,this._waitingTasksCount=0,this._totalTasksCount=0,this.onTaskSuccessObservable=new K,this.onTaskErrorObservable=new K,this.onTasksDoneObservable=new K,this.onProgressObservable=new K,this.useDefaultLoadingScreen=!0,this.autoHideLoadingUI=!0,this._scene=e||re.LastCreatedScene}addContainerTask(e,t,i,s,r){const n=new II(e,t,i,s,r);return this._tasks.push(n),n}addMeshTask(e,t,i,s,r){const n=new RI(e,t,i,s,r);return this._tasks.push(n),n}addTextFileTask(e,t){const i=new OI(e,t);return this._tasks.push(i),i}addBinaryFileTask(e,t){const i=new DI(e,t);return this._tasks.push(i),i}addImageTask(e,t){const i=new wI(e,t);return this._tasks.push(i),i}addTextureTask(e,t,i,s,r=Pa.TRILINEAR_SAMPLINGMODE){const n=new NI(e,t,i,s,r);return this._tasks.push(n),n}addCubeTextureTask(e,t,i,s,r,n){const o=new FI(e,t,i,s,r,n);return this._tasks.push(o),o}addHDRCubeTextureTask(e,t,i,s=!1,r=!0,n=!1,o=!1){const a=new LI(e,t,i,s,r,n,o);return this._tasks.push(a),a}addEquiRectangularCubeTextureAssetTask(e,t,i,s=!1,r=!0){const n=new BI(e,t,i,s,r);return this._tasks.push(n),n}removeTask(e){const t=this._tasks.indexOf(e);t>-1&&this._tasks.splice(t,1)}_decreaseWaitingTasksCount(e){this._waitingTasksCount--;try{this.onProgress&&this.onProgress(this._waitingTasksCount,this._totalTasksCount,e),this.onProgressObservable.notifyObservers(new PI(this._waitingTasksCount,this._totalTasksCount,e))}catch(e){Ne.Error("Error running progress callbacks."),Ne.Log(e)}if(0===this._waitingTasksCount){try{const e=this._tasks.slice();this.onFinish&&this.onFinish(e);for(const t of e)if(t.taskState===EI.DONE){const e=this._tasks.indexOf(t);e>-1&&this._tasks.splice(e,1)}this.onTasksDoneObservable.notifyObservers(this._tasks)}catch(e){Ne.Error("Error running tasks-done callbacks."),Ne.Log(e)}this._isLoading=!1,this.autoHideLoadingUI&&this._scene.getEngine().hideLoadingUI()}}_runTask(e){const t=(t,i)=>{e._setErrorObject(t,i),this.onTaskError?this.onTaskError(e):e.onError||Ne.Error(this._formatTaskErrorMessage(e)),this.onTaskErrorObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)};e.run(this._scene,(()=>{try{this.onTaskSuccess&&this.onTaskSuccess(e),this.onTaskSuccessObservable.notifyObservers(e),this._decreaseWaitingTasksCount(e)}catch(e){t("Error executing task success callbacks",e)}}),t)}_formatTaskErrorMessage(e){let t="Unable to complete task "+e.name;return e.errorObject.message&&(t+=`: ${e.errorObject.message}`),e.errorObject.exception&&(t+=`: ${e.errorObject.exception}`),t}reset(){return this._isLoading=!1,this._tasks=new Array,this}load(){if(this._isLoading)return this;if(this._isLoading=!0,this._waitingTasksCount=this._tasks.length,this._totalTasksCount=this._tasks.length,0===this._waitingTasksCount)return this._isLoading=!1,this.onFinish&&this.onFinish(this._tasks),this.onTasksDoneObservable.notifyObservers(this._tasks),this;this.useDefaultLoadingScreen&&this._scene.getEngine().displayLoadingUI();for(let e=0;e{this._isLoading?e():(this.onTasksDoneObservable.addOnce((i=>{i&&i.length?t(i):e()})),this.load())}))}}class VI{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}}class UI{constructor(e,t){this._meshesOrigins=[],this._toCenterVectors=[],this._scaledDirection=new _e(1,1,1),this._newPosition=_e.Zero(),this._centerPosition=_e.Zero(),this._meshes=e.slice(),t?this._centerMesh=t:this._setCenterMesh(),this._centerMesh.computeWorldMatrix(!0);const i=this._meshes.indexOf(this._centerMesh);i>=0&&this._meshes.splice(i,1),this._centerPosition=this._centerMesh.getAbsolutePosition().clone();for(let e=0;e!0,this.displayLoadingUI=!0,this.loadAsync=(e,t)=>this.useAppend?fl.AppendAsync("file:",e,this._currentScene,t):fl.LoadAsync("file:",e,this._engine,t),this._engine=e,this._currentScene=t,this._sceneLoadedCallback=i,this._progressCallback=s,this._additionalRenderLoopLogicCallback=r,this._textureLoadingCallback=n,this._startingProcessingFilesCallback=o,this._onReloadCallback=a,this._errorCallback=l}monitorElementForDragNDrop(e){e&&(this._elementToMonitor=e,this._dragEnterHandler=e=>{this._drag(e)},this._dragOverHandler=e=>{this._drag(e)},this._dropHandler=e=>{this._drop(e)},this._elementToMonitor.addEventListener("dragenter",this._dragEnterHandler,!1),this._elementToMonitor.addEventListener("dragover",this._dragOverHandler,!1),this._elementToMonitor.addEventListener("drop",this._dropHandler,!1))}get filesToLoad(){return this._filesToLoad}dispose(){this._elementToMonitor&&(this._elementToMonitor.removeEventListener("dragenter",this._dragEnterHandler),this._elementToMonitor.removeEventListener("dragover",this._dragOverHandler),this._elementToMonitor.removeEventListener("drop",this._dropHandler))}_renderFunction(){if(this._additionalRenderLoopLogicCallback&&this._additionalRenderLoopLogicCallback(),this._currentScene){if(this._textureLoadingCallback){const e=this._currentScene.getWaitingItemsCount();e>0&&this._textureLoadingCallback(e)}this._currentScene.render()}}_drag(e){e.stopPropagation(),e.preventDefault()}_drop(e){e.stopPropagation(),e.preventDefault(),this.loadFiles(e)}_traverseFolder(e,t,i,s){const r=e.createReader(),n=e.fullPath.replace(/^\//,"").replace(/(.+?)\/?$/,"$1/");r.readEntries((e=>{i.count+=e.length;for(const r of e)r.isFile?r.file((e=>{e.correctName=n+e.name,t.push(e),0==--i.count&&s()})):r.isDirectory&&this._traverseFolder(r,t,i,s);0==--i.count&&s()}))}_processFiles(e){for(let t=0;tthis._sceneFileToLoad=e))&&(fl.IsPluginForExtensionAvailable("."+s)&&(this._sceneFileToLoad=e[t]),GI.FilesToLoad[i]=e[t])}}loadFiles(e){if(e&&e.dataTransfer&&e.dataTransfer.files&&(this._filesToLoad=e.dataTransfer.files),e&&e.target&&e.target.files&&(this._filesToLoad=e.target.files),this._filesToLoad&&0!==this._filesToLoad.length&&(this._startingProcessingFilesCallback&&this._startingProcessingFilesCallback(this._filesToLoad),this._filesToLoad&&this._filesToLoad.length>0)){const t=[],i=[],s=e.dataTransfer?e.dataTransfer.items:null;for(let e=0;e{this._processFiles(t),0===e.count&&this._processReload()}))}}}_processReload(){this._onReloadCallback?this._onReloadCallback(this._sceneFileToLoad):this.reload()}reload(){this._sceneFileToLoad?(this.useAppend||this._currentScene&&(Ne.errorsCount>0&&Ne.ClearLogCache(),this._engine.stopRenderLoop()),fl.ShowLoadingScreen=!1,this.displayLoadingUI&&this._engine.displayLoadingUI(),this.loadAsync(this._sceneFileToLoad,this._progressCallback).then((e=>{this.useAppend?this.displayLoadingUI&&this._engine.hideLoadingUI():(this._currentScene&&this._currentScene.dispose(),this._currentScene=e,this._currentScene.executeWhenReady((()=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._engine.runRenderLoop((()=>{this._renderFunction()}))}))),this._sceneLoadedCallback&&this._currentScene&&this._sceneLoadedCallback(this._sceneFileToLoad,this._currentScene)})).catch((e=>{this.displayLoadingUI&&this._engine.hideLoadingUI(),this._errorCallback&&this._errorCallback(this._sceneFileToLoad,this._currentScene,e.message)}))):Ne.Error("Please provide a valid .babylon file.")}}class zI{dispose(){if(this._observers&&this._observables)for(let e=0;e{o.skipNextObservers||i._willBeUnregistered||i.mask&t&&(n=i.scope?n.then((t=>(o.lastReturnValue=t,i.callback.apply(i.scope,[e,o])))):n.then((t=>(o.lastReturnValue=t,i.callback(e,o)))),i.unregisterOnNextCall&&this._deferUnregister(i))})),await n,e};class WI{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class HI extends WI{getDescription(){return"Reducing render target texture size to "+this.maximumSize}constructor(e=0,t=1024,i=.5){super(e),this.priority=e,this.maximumSize=t,this.step=i}apply(e,t){let i=!0;for(let t=0;tthis.maximumSize&&(s.scale(this.step),i=!1)}return i}}class XI extends WI{getDescription(){return"Setting hardware scaling level to "+this._currentScale}constructor(e=0,t=2,i=.25){super(e),this.priority=e,this.maximumScale=t,this.step=i,this._currentScale=-1,this._directionOffset=1}apply(e,t){return-1===this._currentScale&&(this._currentScale=e.getEngine().getHardwareScalingLevel(),this._currentScale>this.maximumScale&&(this._directionOffset=-1)),this._currentScale+=this._directionOffset*this.step,e.getEngine().setHardwareScalingLevel(this._currentScale),1===this._directionOffset?this._currentScale>=this.maximumScale:this._currentScale<=this.maximumScale}}class YI extends WI{getDescription(){return"Turning shadows on/off"}apply(e,t){return e.shadowsEnabled=t.isInImprovementMode,!0}}class QI extends WI{getDescription(){return"Turning post-processes on/off"}apply(e,t){return e.postProcessesEnabled=t.isInImprovementMode,!0}}class jI extends WI{getDescription(){return"Turning lens flares on/off"}apply(e,t){return e.lensFlaresEnabled=t.isInImprovementMode,!0}}class KI extends WI{getDescription(){return this.onGetDescription?this.onGetDescription():"Running user defined callback"}apply(e,t){return!this.onApply||this.onApply(e,t)}}class $I extends WI{getDescription(){return"Turning particles on/off"}apply(e,t){return e.particlesEnabled=t.isInImprovementMode,!0}}class qI extends WI{getDescription(){return"Turning render targets off"}apply(e,t){return e.renderTargetsEnabled=t.isInImprovementMode,!0}}class ZI extends WI{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof ha))return!1;const t=e;return!(t.isDisposed()||!t.isVisible||!t.isEnabled()||t.instances.length>0||t.skeleton||t.hasLODLevels||0===t.getTotalVertices())}}static get UpdateSelectionTree(){return ZI._UpdateSelectionTree}static set UpdateSelectionTree(e){ZI._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const s=e.meshes.slice(0);let r=s.length;for(let e=0;e{this._sceneDisposeObserver=null,this.dispose()}))}stop(){this._isRunning=!1}reset(){this._currentPriorityLevel=0}start(){this._isRunning||(this._isRunning=!0,this._scene.executeWhenReady((()=>{setTimeout((()=>{this._checkCurrentState()}),this._trackerDuration)})))}_checkCurrentState(){if(!this._isRunning)return;const e=this._scene,t=this._options;if(this._currentFrameRate=Math.round(e.getEngine().getFps()),this._improvementMode&&this._currentFrameRate<=this._targetFrameRate||!this._improvementMode&&this._currentFrameRate>=this._targetFrameRate)return this._isRunning=!1,void this.onSuccessObservable.notifyObservers(this);let i=!0,s=!0;for(let r=0;r{setTimeout((()=>{this._checkCurrentState()}),this._trackerDuration)}))}dispose(){this.stop(),this.onSuccessObservable.clear(),this.onFailureObservable.clear(),this.onNewOptimizationAppliedObservable.clear(),this._sceneDisposeObserver&&this._scene.onDisposeObservable.remove(this._sceneDisposeObserver)}static OptimizeAsync(e,t,i,s){const r=new eR(e,t||JI.ModerateDegradationAllowed(),!1);return i&&r.onSuccessObservable.add((()=>{i()})),s&&r.onFailureObservable.add((()=>{s()})),r.start(),r}}let tR=[];const iR=(e,t)=>{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),tR[e.id]=!0)},sR=(e,t)=>{const i={},s=e._geometry;return s&&(e.getScene().getGeometryById(s.id)||iR(s,t.geometries)),e.serialize&&e.serialize(i),i};class rR{static ClearCache(){tR=[]}static Serialize(e){return rR._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&Pa.ForceSerializeBuffers&&Ne.Warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),rR.ClearCache(),i.useDelayedTextureLoading=e.useDelayedTextureLoading,i.autoClear=e.autoClear,i.clearColor=e.clearColor.asArray(),i.ambientColor=e.ambientColor.asArray(),i.gravity=e.gravity.asArray(),i.collisionsEnabled=e.collisionsEnabled,i.useRightHandedSystem=e.useRightHandedSystem,void 0!==e.fogMode&&null!==e.fogMode&&(i.fogMode=e.fogMode),void 0!==e.fogColor&&null!==e.fogColor&&(i.fogColor=e.fogColor.asArray()),void 0!==e.fogStart&&null!==e.fogStart&&(i.fogStart=e.fogStart),void 0!==e.fogEnd&&null!==e.fogEnd&&(i.fogEnd=e.fogEnd),void 0!==e.fogDensity&&null!==e.fogDensity&&(i.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){const t=e.getPhysicsEngine();t&&(i.physicsEnabled=!0,i.physicsGravity=t.gravity.asArray(),i.physicsEngine=t.getPhysicsPluginName())}e.metadata&&(i.metadata=e.metadata),i.morphTargetManagers=[];for(const t of e.meshes){const e=t.morphTargetManager;e&&i.morphTargetManagers.push(e.serialize())}let s,r,n;for(i.lights=[],s=0;s0){i.animationGroups=[];for(let t=0;t0)for(i.reflectionProbes=[],s=0;st))}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=t))):(s instanceof Object||Array.isArray(s))&&this._CollectPromises(s,t)}else if(e instanceof Object)for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const s=e[i];s instanceof Promise?t.push(s.then((t=>e[i]=t))):(s instanceof Object||Array.isArray(s))&&this._CollectPromises(s,t)}}static SerializeMesh(e,t=!1,i=!1){const s={meshes:[],transformNodes:[],cameras:[],lights:[]};if(rR.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let s=0;s{e.indexOf(t)<0&&!t.doNotSerialize&&e.push(t)})),t&&e[s].parent&&e.indexOf(e[s].parent)<0&&!e[s].parent.doNotSerialize&&e.push(e[s].parent);return e.forEach((e=>{((e,t)=>{if(e._isMesh){const i=e;if(1===i.delayLoadState||0===i.delayLoadState){const e=e=>{t.materials=t.materials||[],i.material&&!t.materials.some((e=>e.id===i.material.id))&&t.materials.push(e.serialize())};if(i.material&&!i.material.doNotSerialize)if(i.material instanceof ia){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some((e=>e.id===i.material.id))){t.multiMaterials.push(i.material.serialize());for(const t of i.material.subMaterials)t&&e(t)}}else e(i.material);else i.material||e(i.getScene().defaultMaterial);const s=i._geometry;s&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),iR(s,t.geometries)),i.skeleton&&!i.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(i.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(sR(i,t))}}else if("TransformNode"===e.getClassName()){const i=e;t.transformNodes.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Camera")){const i=e;t.cameras.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Light")){const i=e;t.lights.push(i.serialize())}})(e,s)})),s}}class nR{static IsSupported(e,t){const i=t??e.getRenderingCanvas();return!!i&&"function"==typeof i.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!nR.IsSupported(e,t.canvas))throw"Your browser does not support recording so far.";const i=t.canvas??e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options={...nR._DefaultOptions,...t};const s=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const e of this._options.audioTracks)s.addTrack(e);this._mediaRecorder=new MediaRecorder(s,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=e=>this._handleDataAvailable(e),this._mediaRecorder.onerror=e=>this._handleError(e),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout((()=>{this.stopRecording()}),1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),!this._reject)throw new e.error;this._reject(e.error)}_handleStop(){this.stopRecording();const e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&Ds.Download(e,this._fileName)}}nR._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let oR=null;function aR(e,t,i,s,r="image/png",n=!1,o){const{height:a,width:l}=dR(e,t,i);if(!a||!l)return void Ne.Error("Invalid 'size' parameter !");oR||(oR=document.createElement("canvas")),oR.width=l,oR.height=a;const h=oR.getContext("2d"),c=e.getRenderWidth()/e.getRenderHeight();let u=l,d=u/c;d>a&&(d=a,u=d*c);const _=Math.max(0,l-u)/2,p=Math.max(0,a-d)/2;t.getScene().activeCamera!==t?cR(e,t,i,(e=>{if(n){const t=new Blob([e]);Ds.DownloadBlob(t),s&&s("")}else s&&s(e)}),r,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,o):e.onEndFrameObservable.addOnce((()=>{const t=e.getRenderingCanvas();h&&t&&h.drawImage(t,_,p,u,d),oR&&(n?(Ds.EncodeScreenshotCanvasData(oR,void 0,r,void 0,o),s&&s("")):Ds.EncodeScreenshotCanvasData(oR,s,r,void 0,o))}))}function lR(e,t,i,s="image/png",r){return new Promise(((n,o)=>{aR(e,t,i,(e=>{void 0!==e?n(e):o(new Error("Data is undefined"))}),s,void 0,r)}))}function hR(e,t,i,s,r="image/png",n){return new Promise((o=>{aR(e,t,{width:i,height:s},(()=>{o()}),r,!0,n)}))}function cR(e,t,i,s,r="image/png",n=1,o=!1,a,l=!1,h=!1,c=!0,u,d){const{height:_,width:p,finalWidth:f,finalHeight:m}=dR(e,t,i),g={width:p,height:_};if(!_||!p)return void Ne.Error("Invalid 'size' parameter !");const v={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(p,_);const x=t.getScene(),b=new ih("screenShot",g,x,!1,!1,0,!1,Pa.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,n);b.renderList=x.meshes.slice(),b.samples=n,b.renderSprites=l,b.activeCamera=t,b.forceLayerMaskCheck=c,d?.(b);const T=()=>{b.isReadyForRendering()&&t.isReady(!0)?(e.onEndFrameObservable.addOnce((()=>{f===p&&m===_?b.readPixels(void 0,void 0,void 0,!1).then((e=>{th.DumpData(p,_,e,s,r,a,!0,void 0,u),b.dispose()})):Z_("pass",b.getInternalTexture(),x,void 0,void 0,void 0,f,m).then((t=>{e._readTexturePixels(t,f,m,-1,0,null,!0,!1,0,0).then((e=>{th.DumpData(f,m,e,s,r,a,!0,void 0,u),t.dispose()}))}))})),b.render(!0),x.incrementRenderId(),x.resetCachedMaterial(),e.setSize(v.width,v.height),t.getProjectionMatrix(!0),x.render()):setTimeout(T,16)},y=()=>{x.incrementRenderId(),x.resetCachedMaterial(),T()};if(o){const e=new uP("antialiasing",1,x.activeCamera);b.addPostProcess(e),e.getEffect().isReady()?y():e.getEffect().onCompiled=()=>{y()}}else y()}function uR(e,t,i,s="image/png",r=1,n=!1,o,a=!1,l=!1,h=!0,c){return new Promise(((u,d)=>{cR(e,t,i,(e=>{void 0!==e?u(e):d(new Error("Data is undefined"))}),s,r,n,o,a,l,h,c)}))}function dR(e,t,i){let s=0,r=0,n=0,o=0;if("object"==typeof i){const a=i.precision?Math.abs(i.precision):1;i.width&&i.height?(s=i.height*a,r=i.width*a):i.width&&!i.height?(r=i.width*a,s=Math.round(r/e.getAspectRatio(t))):i.height&&!i.width?(s=i.height*a,r=Math.round(s*e.getAspectRatio(t))):(r=Math.round(e.getRenderWidth()*a),s=Math.round(r/e.getAspectRatio(t))),i.finalWidth&&i.finalHeight?(o=i.finalHeight,n=i.finalWidth):i.finalWidth&&!i.finalHeight?(n=i.finalWidth,o=Math.round(n/e.getAspectRatio(t))):i.finalHeight&&!i.finalWidth?(o=i.finalHeight,n=Math.round(o*e.getAspectRatio(t))):(n=r,o=s)}else isNaN(i)||(s=i,r=i,n=i,o=i);return r&&(r=Math.floor(r)),s&&(s=Math.floor(s)),n&&(n=Math.floor(n)),o&&(o=Math.floor(o)),{height:0|s,width:0|r,finalWidth:0|n,finalHeight:0|o}}const _R={CreateScreenshot:aR,CreateScreenshotAsync:lR,CreateScreenshotWithResizeAsync:hR,CreateScreenshotUsingRenderTarget:cR,CreateScreenshotUsingRenderTargetAsync:uR};var pR,fR;Ds.CreateScreenshot=aR,Ds.CreateScreenshotAsync=lR,Ds.CreateScreenshotUsingRenderTarget=cR,Ds.CreateScreenshotUsingRenderTargetAsync=uR,function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String",e[e.Button=6]="Button",e[e.Options=7]="Options",e[e.Tab=8]="Tab",e[e.FileButton=9]="FileButton",e[e.Vector2=10]="Vector2"}(pR||(pR={}));class mR{constructor(e){this.byteOffset=0,this.buffer=e}loadAsync(e){return this.buffer.readAsync(this.byteOffset,e).then((e=>{this._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),this._dataByteOffset=0}))}readUint32(){const e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e}readUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t}readString(e){return qt(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}class gR{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{const e={};return{getItem:t=>{const i=e[t];return void 0===i?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){const i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){const i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){const i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}gR._Storage=gR._GetStorage();class vR{constructor(){this._trackedScene=null}track(e){this._trackedScene=e,St.AllowLoadingUniqueId=!0,this._savedJSON=rR.Serialize(e),St.AllowLoadingUniqueId=!1}getDelta(){if(!this._trackedScene)return null;const e=Pa.ForceSerializeBuffers;Pa.ForceSerializeBuffers=!1,St.AllowLoadingUniqueId=!0;const t=rR.Serialize(this._trackedScene);St.AllowLoadingUniqueId=!1;const i={};for(const e in t)this._compareCollections(e,this._savedJSON[e],t[e],i);return Pa.ForceSerializeBuffers=e,i}_compareArray(e,t,i,s){if(0===t.length&&0===i.length)return!0;if(t.length&&!isNaN(t[0])||i.length&&!isNaN(i[0])){if(t.length!==i.length)return!1;if(0===t.length)return!0;for(let r=0;re.uniqueId===a));if(l.length){const t=l[0],i={};this._compareObjects(o,t,i)||(s[e]||(s[e]=[]),i.__state={id:t.id||t.name},s[e].push(i))}else{const t={__state:{deleteId:o.id||o.name}};s[e]||(s[e]=[]),s[e].push(t)}}for(let t=0;te.getShadowGenerators()));for(const e of i)if(e){const i=e.values();for(let e=i.next();!0!==e.done;e=i.next()){const i=e.value;if(i&&i.id===t)return i}}return null}static ApplyDelta(e,t){"string"==typeof e&&(e=JSON.parse(e));const i=t;for(const s in e){const r=e[s],n=i[s];if(Array.isArray(n)||"shadowGenerators"===s)switch(s){case"cameras":this._ApplyDeltaForEntity(r,t,t.getCameraById.bind(t),(e=>In.Parse(e,t)));break;case"lights":this._ApplyDeltaForEntity(r,t,t.getLightById.bind(t),(e=>ua.Parse(e,t)));break;case"shadowGenerators":this._ApplyDeltaForEntity(r,t,(e=>this.GetShadowGeneratorById(t,e)),(e=>Wv.Parse(e,t)));break;case"meshes":this._ApplyDeltaForEntity(r,t,t.getMeshById.bind(t),(e=>ha.Parse(e,t,"")));break;case"skeletons":this._ApplyDeltaForEntity(r,t,t.getSkeletonById.bind(t),(e=>Da.Parse(e,t)));break;case"materials":this._ApplyDeltaForEntity(r,t,t.getMaterialById.bind(t),(e=>ta.Parse(e,t,"")));break;case"multiMaterials":this._ApplyDeltaForEntity(r,t,t.getMaterialById.bind(t),(e=>ia.Parse(e,t,"")));break;case"transformNodes":this._ApplyDeltaForEntity(r,t,t.getTransformNodeById.bind(t),(e=>lo.Parse(e,t,"")));break;case"particleSystems":this._ApplyDeltaForEntity(r,t,t.getParticleSystemById.bind(t),(e=>VE.Parse(e,t,"")));break;case"morphTargetManagers":this._ApplyDeltaForEntity(r,t,t.getMorphTargetById.bind(t),(e=>lx.Parse(e,t)));break;case"postProcesses":this._ApplyDeltaForEntity(r,t,t.getPostProcessByName.bind(t),(e=>Vl.Parse(e,t,"")))}else isNaN(n)?n.fromArray&&n.fromArray(r):i[s]=r}}static _ApplyPropertiesToEntity(e,t){for(const i in e){const s=e[i],r=t[i];void 0!==r&&(!isNaN(r)||Array.isArray(r)?t[i]=s:r.fromArray?r.fromArray(s):"object"==typeof r&&null!==r&&this._ApplyPropertiesToEntity(s,r))}}static _ApplyDeltaForEntity(e,t,i,s){for(const r of e)if(r.__state&&void 0!==r.__state.id){const e=i(r.__state.id);e&&(this._ApplyPropertiesToEntity(r,e),St.ParseProperties(r,e,t,null))}else if(r.__state&&void 0!==r.__state.deleteId){const e=i(r.__state.deleteId);e?.dispose()}else s(r)}}!function(e){class t{serialize(){const e={},t=new Array(this._characterToIdx.size);return this._characterToIdx.forEach(((e,i)=>{t[e]=i})),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){const i=JSON.parse(e),s=new t(i.characters);return s._insertionCosts=i.insertionCosts,s._deletionCosts=i.deletionCosts,s._substitutionCosts=i.substitutionCosts,s}constructor(e,t=null,i=null,s=null){let r;t=t??(()=>1),i=i??(()=>1),s=s??((e,t)=>e===t?0:1),this._characterToIdx=new Map,this._insertionCosts=new Array(e.length),this._deletionCosts=new Array(e.length),this._substitutionCosts=new Array(e.length);for(let n=0;ni._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+i._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map((e=>this._alphabet.getCharacterIdx(e)))}distance(e){return i._Distance(this,e)}static _Distance(e,t){const s=e._alphabet;if(s!==t._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const r=e._characters,n=t._characters,o=r.length,a=n.length,l=i._CostMatrix;l[0][0]=0;for(let e=0;enew Array(i._MAX_SEQUENCE_LENGTH+1))),e.Sequence=i}(fR||(fR={}));class xR{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new xR(t._segmentLength);return i._points=t._points.map((e=>new _e(e._x,e._y,e._z))),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{const i=()=>this._segmentLength/_e.Distance(this._points[t-1],e);for(let s=i();s<=1;s=i()){const i=this._points[t-1].scale(1-s);e.scaleAndAddToRef(s,i),this._points.push(i),++t}}}resampleAtTargetResolution(e){const t=new xR(this.getLength()/e);return this._points.forEach((e=>{t.add(e)})),t}tokenize(e){const t=[],i=new _e;for(let s=2;s.98||(_e.CrossToRef(xR._ForwardDir,xR._InverseFromVec,xR._UpDir),xR._UpDir.normalize(),me.LookAtLHToRef(e,t,xR._UpDir,xR._LookMatrix),i.subtractToRef(t,xR._FromToVec),xR._FromToVec.normalize(),_e.TransformNormalToRef(xR._FromToVec,xR._LookMatrix,s),0))}static _TokenizeSegment(e,t){xR._BestMatch=0,xR._Score=_e.Dot(e,t[0]),xR._BestScore=xR._Score;for(let i=1;ixR._BestScore&&(xR._BestMatch=i,xR._BestScore=xR._Score);return xR._BestMatch}}xR._ForwardDir=new _e,xR._InverseFromVec=new _e,xR._UpDir=new _e,xR._FromToVec=new _e,xR._LookMatrix=new me;class bR{static Generate(e=64,t=256,i=.1,s=.001,r=[]){const n=new bR(e);for(let t=0;t{n.chars[e].subtractToRef(t,h),a=h.lengthSquared(),a>1e-6&&h.scaleAndAddToRef(1/(h.lengthSquared()*a),l)})),l.scaleInPlace(o),n.chars[e].addInPlace(l),n.chars[e].normalize()}var c;return n}serialize(){return JSON.stringify(this.chars)}static Deserialize(e){const t=JSON.parse(e),i=new bR(t.length);for(let e=0;ee.serialize())))}static Deserialize(e,t){const i=new TR;return i._sequences=JSON.parse(e).map((e=>fR.Sequence.Deserialize(e,t))),i}static CreateFromTrajectory(e,t,i){return TR.CreateFromTokenizationPyramid(TR._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new TR;return i._sequences=e.map((e=>new fR.Sequence(e,t))),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=TR._FINEST_DESCRIPTOR_RESOLUTION){const s=[];for(let r=i;r>4;r=Math.floor(r/2))s.push(e.resampleAtTargetResolution(r).tokenize(t.chars));return s}distance(e){let t,i=0;for(let s=0;se.serialize())),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),s=new yR;return s._descriptors=i.descriptors.map((e=>TR.Deserialize(e,t))),s._centroidIdx=i.centroidIdx,s._averageDistance=i.averageDistance,s}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map((t=>t.distance(e))))}_refreshDescription(){let e;this._centroidIdx=-1;const t=this._descriptors.map((t=>(e=0,this._descriptors.forEach((i=>{e+=t.distance(i)})),e)));for(let e=0;e{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])})),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,yR._MIN_AVERAGE_DISTANCE))}}yR._MIN_AVERAGE_DISTANCE=1;class SR{serialize(){const e={};return e.maximumAllowableMatchCost=this._maximumAllowableMatchCost,e.vector3Alphabet=this._vector3Alphabet.serialize(),e.levenshteinAlphabet=this._levenshteinAlphabet.serialize(),e.nameToDescribedTrajectory=[],this._nameToDescribedTrajectory.forEach(((t,i)=>{e.nameToDescribedTrajectory.push(i),e.nameToDescribedTrajectory.push(t.serialize())})),JSON.stringify(e)}static Deserialize(e){const t=JSON.parse(e),i=new SR;i._maximumAllowableMatchCost=t.maximumAllowableMatchCost,i._vector3Alphabet=bR.Deserialize(t.vector3Alphabet),i._levenshteinAlphabet=fR.Alphabet.Deserialize(t.levenshteinAlphabet);for(let e=0;e0===e?0:1),(e=>0===e?0:1),((t,i)=>Math.min(1-_e.Dot(e.chars[t],e.chars[i]),1))),s=new SR;return s._vector3Alphabet=e,s._levenshteinAlphabet=i,s}constructor(){this._maximumAllowableMatchCost=4,this._nameToDescribedTrajectory=new Map}addTrajectoryToClassification(e,t){this._nameToDescribedTrajectory.has(t)||this._nameToDescribedTrajectory.set(t,new yR),this._nameToDescribedTrajectory.get(t).add(TR.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet))}deleteClassification(e){return this._nameToDescribedTrajectory.delete(e)}classifyTrajectory(e){const t=TR.CreateFromTrajectory(e,this._vector3Alphabet,this._levenshteinAlphabet),i=[];if(this._nameToDescribedTrajectory.forEach(((e,s)=>{e.getMatchCost(t){const t=e.data;if(t.startsWith(CR._SERVER_PREFIX)){const e=t.substr(CR._SERVER_PREFIX.length);return Ne.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),void this._handleServerMessage(e)}Ne.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{Ne.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&rR.SerializeAsync(this._scene).then((e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)}))}_handleClientMessage(){}}CR._SERVER_PREFIX="$$";class ER{constructor(e){this._observer=null,this._currentState=[],this.onPressureChanged=new K,ER.IsAvailable&&(this._observer=new PressureObserver((e=>{this._currentState=e,this.onPressureChanged.notifyObservers(e)}),e))}static get IsAvailable(){return"undefined"!=typeof PressureObserver&&PressureObserver.knownSources&&PressureObserver.knownSources.includes("cpu")}observe(e){try{this._observer?.observe(e),this.onPressureChanged.notifyObservers(this._currentState)}catch{}}unobserve(e){try{this._observer?.unobserve(e)}catch{}}dispose(){this._observer?.disconnect(),this._observer=null,this.onPressureChanged.clear()}}class AR{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){const e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}}const PR=1800,IR="timestamp",RR="numPoints",MR=/\r/g;class OR{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const e=Wt.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength;let s=0;if(i>0){const e=this.datasets.startingIndices.at(i-1);s=e+this.datasets.data.at(e+OR.NumberOfPointsOffset)+OR.SliceDataOffset}if(this.datasets.startingIndices.push(s),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach((e=>{const t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())})),this.datasetObservable.hasObservers()){const i=[e,t];for(let e=0;ee.callback(this._datasetMeta,new Q(0)))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&(this._strategies.get(e)?.dispose(),this._strategies.delete(e));const s={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,s=0;const r=t.onAfterRenderObservable.add((()=>{s=i,i=0})),n=this._customEventObservable.add((t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)}));return{id:e,getData:()=>s,dispose:()=>{t.onAfterRenderObservable.remove(r),this._customEventObservable.remove(n)}}},category:i}),s}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach((e=>{this.registerEvent(e,!0)}))}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:s}of e){const e=t(this._scene);this._strategies.has(e.id)?e.dispose():(this.datasets.ids.push(e.id),i&&(i=i.replace(new RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:s}),this._strategies.set(e.id,e))}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i>e&255).toString(16)).substr(-2);return i}getCurrentSlice(){const e=[Wt.Now-this._startingTimestamp,this.datasets.ids.length];this.datasets.ids.forEach((t=>{const i=this._strategies.get(t);i&&this.datasetObservable.hasObservers()&&e.push(i.getData())})),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(e)}updateMetadata(e,t,i){const s=this._datasetMeta.get(e);s&&(s[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new AR(PR),this.datasets.ids.length=0,this.datasets.startingIndices=new AR(PR),this._datasetMeta.clear(),this._strategies.forEach((e=>e.dispose())),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){const i=e.replace(MR,"").split("\n").map((e=>e.split(",").filter((e=>e.length>0)))).filter((e=>e.length>0)),s=OR.NumberOfPointsOffset;if(i.length<2)return!1;const r={ids:[],data:new AR(PR),startingIndices:new AR(PR)},[n,...o]=i;if(n.length<2||n[0]!==IR||n[s]!==RR)return!1;const a=new Map;for(let e=OR.SliceDataOffset;ee.dispose())),this._strategies.clear(),!t)for(const e of this.datasets.ids){const t=a.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${IR},${RR}`;for(let t=0;t{e.dispose()})),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}const DR=()=>{};class wR{static FpsStrategy(){return e=>{const t=e.getEngine();return{id:"FPS",getData:()=>t.getFps(),dispose:DR}}}static ThermalStrategy(){return this._PressureStrategy("Thermal utilization","thermal")}static PowerSupplyStrategy(){return this._PressureStrategy("Power supply utilization","power-supply")}static PressureStrategy(){return this._PressureStrategy("Pressure")}static _PressureStrategy(e,t=null){return()=>{let i=0;const s=new ER;return s.observe("cpu"),s.onPressureChanged.add((e=>{for(const s of e)if(t&&s.factors.includes(t)||!t&&0===(s.factors?.length??0))switch(s.state){case"nominal":i=0;break;case"fair":i=.25;break;case"serious":i=.5;break;case"critical":i=1}})),{id:e,getData:()=>i,dispose:()=>s.dispose()}}}static TotalMeshesStrategy(){return e=>({id:"Total meshes",getData:()=>e.meshes.length,dispose:DR})}static ActiveMeshesStrategy(){return e=>({id:"Active meshes",getData:()=>e.getActiveMeshes().length,dispose:DR})}static ActiveIndicesStrategy(){return e=>({id:"Active indices",getData:()=>e.getActiveIndices(),dispose:DR})}static ActiveFacesStrategy(){return e=>({id:"Active faces",getData:()=>e.getActiveIndices()/3,dispose:DR})}static ActiveBonesStrategy(){return e=>({id:"Active bones",getData:()=>e.getActiveBones(),dispose:DR})}static ActiveParticlesStrategy(){return e=>({id:"Active particles",getData:()=>e.getActiveParticles(),dispose:DR})}static DrawCallsStrategy(){return e=>{let t=0;const i=e.onBeforeAnimationsObservable.add((()=>{e.getEngine()._drawCalls.fetchNewFrame()})),s=e.onAfterRenderObservable.add((()=>{t=e.getEngine()._drawCalls.current}));return{id:"Draw calls",getData:()=>t,dispose:()=>{e.onBeforeAnimationsObservable.remove(i),e.onAfterRenderObservable.remove(s)}}}}static TotalLightsStrategy(){return e=>({id:"Total lights",getData:()=>e.lights.length,dispose:DR})}static TotalVerticesStrategy(){return e=>({id:"Total vertices",getData:()=>e.getTotalVertices(),dispose:DR})}static TotalMaterialsStrategy(){return e=>({id:"Total materials",getData:()=>e.materials.length,dispose:DR})}static TotalTexturesStrategy(){return e=>({id:"Total textures",getData:()=>e.textures.length,dispose:DR})}static AbsoluteFpsStrategy(){return e=>{const t=new Dv(e);return t.captureFrameTime=!0,{id:"Absolute FPS",getData:()=>1e3/t.frameTimeCounter.lastSecAverage,dispose:DR}}}static MeshesSelectionStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeActiveMeshesEvaluationObservable.add((()=>{t=Wt.Now})),r=e.onAfterActiveMeshesEvaluationObservable.add((()=>{i=Wt.Now-t}));return{id:"Meshes Selection",getData:()=>i,dispose:()=>{e.onBeforeActiveMeshesEvaluationObservable.remove(s),e.onAfterActiveMeshesEvaluationObservable.remove(r)}}}}static RenderTargetsStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeRenderTargetsRenderObservable.add((()=>{t=Wt.Now})),r=e.onAfterRenderTargetsRenderObservable.add((()=>{i=Wt.Now-t}));return{id:"Render Targets",getData:()=>i,dispose:()=>{e.onBeforeRenderTargetsRenderObservable.remove(s),e.onAfterRenderTargetsRenderObservable.remove(r)}}}}static ParticlesStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeParticlesRenderingObservable.add((()=>{t=Wt.Now})),r=e.onAfterParticlesRenderingObservable.add((()=>{i=Wt.Now-t}));return{id:"Particles",getData:()=>i,dispose:()=>{e.onBeforeParticlesRenderingObservable.remove(s),e.onAfterParticlesRenderingObservable.remove(r)}}}}static SpritesStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeSpritesRenderingObservable?.add((()=>{t=Wt.Now})),r=e.onAfterSpritesRenderingObservable?.add((()=>{i=Wt.Now-t}));return{id:"Sprites",getData:()=>i,dispose:()=>{e.onBeforeSpritesRenderingObservable?.remove(s),e.onAfterSpritesRenderingObservable?.remove(r)}}}}static AnimationsStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeAnimationsObservable.add((()=>{t=Wt.Now})),r=e.onAfterAnimationsObservable.add((()=>{i=Wt.Now-t}));return{id:"Animations",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(s),e.onAfterAnimationsObservable.remove(r)}}}}static PhysicsStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforePhysicsObservable?.add((()=>{t=Wt.Now})),r=e.onAfterPhysicsObservable?.add((()=>{i=Wt.Now-t}));return{id:"Physics",getData:()=>i,dispose:()=>{e.onBeforePhysicsObservable?.remove(s),e.onAfterPhysicsObservable?.remove(r)}}}}static RenderStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeDrawPhaseObservable.add((()=>{t=Wt.Now})),r=e.onAfterDrawPhaseObservable.add((()=>{i=Wt.Now-t}));return{id:"Render",getData:()=>i,dispose:()=>{e.onBeforeDrawPhaseObservable.remove(s),e.onAfterDrawPhaseObservable.remove(r)}}}}static FrameTotalStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeAnimationsObservable.add((()=>{t=Wt.Now})),r=e.onAfterRenderObservable.add((()=>{i=Wt.Now-t}));return{id:"Frame Total",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(s),e.onAfterRenderObservable.remove(r)}}}}static InterFrameStrategy(){return e=>{let t=Wt.Now,i=0;const s=e.onBeforeAnimationsObservable.add((()=>{i=Wt.Now-t})),r=e.onAfterRenderObservable.add((()=>{t=Wt.Now}));return{id:"Inter-frame",getData:()=>i,dispose:()=>{e.onBeforeAnimationsObservable.remove(s),e.onAfterRenderObservable.remove(r)}}}}static GpuFrameTimeStrategy(){return e=>{const t=new Ov(e.getEngine());return t.captureGPUFrameTime=!0,{id:"GPU frame time",getData:()=>Math.max(1e-6*t.gpuFrameTimeCounter.current,0),dispose:()=>{t.dispose()}}}}}Hr.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new OR(this)),this._perfCollector},K.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){const e=function(e){const t=new Array,i=new Array,s=new Array,r=e.add((()=>{const e=t.length;for(let r=0;r{t.push(e),i.push(r),s.push(n)},dispose:()=>{e.remove(r)}}}(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return Cn(e,this._coroutineScheduler)},K.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};async function NR(e,t){const i=t.probe??new fx("tempProbe",t.size,e),s=!!t.probe;s||(t.position?i.position=t.position.clone():e.activeCamera&&(i.position=e.activeCamera.position.clone()));const r=t.meshesFilter?e.meshes.filter(t.meshesFilter):e.meshes;i.renderList?.push(...r),i.refreshRate=ih.REFRESHRATE_RENDER_ONCE,i.cubeTexture.render();const n=new yb("tempProceduralTexture","equirectangularPanorama",{width:2*t.size,height:t.size},e);return n.setTexture("cubeMap",i.cubeTexture),new Promise(((e,r)=>{n.onGeneratedObservable.addOnce((()=>{const o=n.readPixels();if(!o)return r(new Error("No Pixel Data found on procedural texture")),n.dispose(),void(s||i.dispose());o.then((r=>{n.dispose(),s||i.dispose(),t.filename?(th.DumpData(2*t.size,t.size,r,void 0,"image/png",t.filename),e(null)):e(r)}))}))}))}Bi.ShadersStore.equirectangularPanoramaPixelShader="#ifdef GL_ES\nprecision highp float;\n#endif\n#define M_PI 3.1415926535897932384626433832795\nvarying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3(\n- sin( longitude )*sin( latitude ),\ncos( latitude ),\n- cos( longitude )*sin( latitude )\n);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}";class FR extends Ja{constructor(e,t={}){super(e),this.options=t,this._direction=new _e(0,0,-1),this._mat=new me,this._onSelectEnabled=!1,this._origin=new _e(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new K,this._onHitTestResults=e=>{const t=e.map((e=>{const t=me.FromArray(e.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&t.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}}));this.lastNativeXRHitResults=e,this.onHitTestResultObservable.notifyObservers(t)},this._onSelect=e=>{this._onSelectEnabled&&FR.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",Ds.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,s){return e.requestHitTest(t,i).then((e=>{const t=s||(e=>!!e.hitMatrix);return e.filter(t)}))}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const s=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,s,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;me.FromArrayToRef(t.transform.matrix,0,this._mat),_e.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),_e.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();const i=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});FR.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}FR.Name=qa.HIT_TEST,FR.Version=1,Za.AddWebXRFeature(FR.Name,((e,t)=>()=>new FR(e,t)),FR.Version,!1);let LR=0;class BR extends Ja{set referenceSpaceForFrameAnchors(e){this._referenceSpaceForFrameAnchors=e}constructor(e,t={}){super(e),this._options=t,this._lastFrameDetected=new Set,this._trackedAnchors=[],this._futureAnchors=[],this.onAnchorAddedObservable=new K,this.onAnchorRemovedObservable=new K,this.onAnchorUpdatedObservable=new K,this._tmpVector=new _e,this._tmpQuaternion=new fe,this.xrNativeFeatureName="anchors"}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new _e,i=new fe){this._populateTmpTransformation(t,i);const s=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(!e.xrHitResult.createAnchor)throw this.detach(),new Error("Anchors not enabled in this environment/browser");try{const t=await e.xrHitResult.createAnchor(s);return new Promise(((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:s,resolve:e,reject:i})}))}catch(e){throw new Error(e)}}async addAnchorAtPositionAndRotationAsync(e,t=new fe,i=!1){this._populateTmpTransformation(e,t);const s=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),r=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(s,this._xrSessionManager.currentFrame):void 0;return new Promise(((e,t)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!1,xrTransformation:s,resolve:e,reject:t})}))}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){const e=this._trackedAnchors.pop();if(e){try{e.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(e)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;const t=e.trackedAnchors;if(t){const i=this._trackedAnchors.filter((e=>!t.has(e.xrAnchor))).map((e=>this._trackedAnchors.indexOf(e)));let s=0;i.forEach((e=>{const t=this._trackedAnchors.splice(e-s,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),s++})),t.forEach((t=>{if(this._lastFrameDetected.has(t)){const i=this._findIndexInAnchorArray(t),s=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,s,e),s.attachedNode&&(s.attachedNode.rotationQuaternion=s.attachedNode.rotationQuaternion||new fe,s.transformationMatrix.decompose(s.attachedNode.scaling,s.attachedNode.rotationQuaternion,s.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(s)}catch(e){Ds.Warn("Anchor could not be updated")}}else{const i={id:LR++,xrAnchor:t,remove:()=>t.delete()},s=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(s),this.onAnchorAddedObservable.notifyObservers(s);const r=this._futureAnchors.filter((e=>e.nativeAnchor===t))[0];r&&(r.resolve(s),r.resolved=!0)}})),this._lastFrameDetected=t}this._futureAnchors.forEach((t=>{t.resolved||t.submitted||(this._createAnchorAtTransformation(t.xrTransformation,e).then((e=>{t.nativeAnchor=e}),(e=>{t.resolved=!0,t.reject(e)})),t.submitted=!0)}))}_findIndexInAnchorArray(e){for(let t=0;t()=>new BR(e,t)),BR.Version);let kR=0;class VR extends Ja{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new K,this.onPlaneRemovedObservable=new K,this.onPlaneUpdatedObservable=new K,this.xrNativeFeatureName="plane-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){if(!super.detach())return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){const e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return"undefined"!=typeof XRPlane}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.detectedPlanes||e.worldInformation?.detectedPlanes;if(t){for(let e=0;e{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._findIndexInPlaneArray(t),s=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,s,e),this.onPlaneUpdatedObservable.notifyObservers(s)}}else{const i={id:kR++,xrPlane:t,polygonDefinition:[]},s=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(s),this.onPlaneAddedObservable.notifyObservers(s)}})),this._lastFrameDetected=t}}_init(){const e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),this._xrSessionManager.session.updateWorldTrackingState?(this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()):e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map((e=>{const t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new _e(e.x,e.y,e.z*t)}));const s=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(s){const e=t.transformationMatrix||new me;me.FromArrayToRef(s.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new VR(e,t)),VR.Version);class UR extends Ja{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new K}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){const t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper)if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){const i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){const i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{const i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach((t=>t.setEnabled(e))),this.onBackgroundStateChangedObservable.notifyObservers(e)}}UR.Name=qa.BACKGROUND_REMOVER,UR.Version=1,Za.AddWebXRFeature(UR.Name,((e,t)=>()=>new UR(e,t)),UR.Version,!0);class GR{}class zR extends Ja{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||nl.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,s=_d("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});s.isVisible=this._debugMode,s.isPickable=!1,s.rotationQuaternion=new fe;const r=e.grip||e.pointer;s.position.copyFrom(r.position),s.rotationQuaternion.copyFrom(r.rotationQuaternion);const n=new nl(s,t,{mass:0,...this._options.physicsProperties});this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:s}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||Ne.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce((t=>{t._doNotLoadControllerMesh?this._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce((()=>{const i=new nl(t.rootMesh,nl.MeshImpostor,{mass:0,...this._options.physicsProperties}),s=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:s.position.clone(),oldRotation:s.rotationQuaternion.clone()}}))})):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new fe,this._tmpVector=new _e,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e];t.impostorMesh&&(t.impostorMesh.isVisible=!0)}))}addController(e){this._attachController(e)}attach(){if(!super.attach())return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._options.enableHeadsetImpostor){const e=this._options.headsetImpostorParams||{impostorType:nl.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=_d("headset-mesh",{diameterX:"number"==typeof t?t:t.width,diameterY:"number"==typeof t?t:t.height,diameterZ:"number"==typeof t?t:t.depth}),this._headsetMesh.rotationQuaternion=new fe,this._headsetMesh.isVisible=!1,this._headsetImpostor=new nl(this._headsetMesh,e.impostorType,{mass:0,...e})}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._headsetMesh&&this._headsetMesh.dispose(),!0)}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){const t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties={...this._options.physicsProperties,...e}}_onXRFrame(e){if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),this._options.xrInput.xrCamera._lastXRViewerPose?.linearVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(this._options.xrInput.xrCamera._lastXRViewerPose?.angularVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e],i=t.xrController.grip||t.xrController.pointer,s=t.oldPos||t.impostorMesh.position;if(t.xrController._lastXRPose?.linearVelocity){const e=t.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setLinearVelocity(this._tmpVector)}else i.position.subtractToRef(s,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),t.impostor.setLinearVelocity(this._tmpVector);s.copyFrom(i.position),this._debugMode&&Ne.Log([this._tmpVector,"linear"]);const r=t.oldRotation||t.impostorMesh.rotationQuaternion;if(t.xrController._lastXRPose?.angularVelocity){const e=t.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setAngularVelocity(this._tmpVector)}else if(!r.equalsWithEpsilon(i.rotationQuaternion)){r.conjugateInPlace().multiplyToRef(i.rotationQuaternion,this._tmpQuaternion);const e=Math.sqrt(this._tmpQuaternion.x*this._tmpQuaternion.x+this._tmpQuaternion.y*this._tmpQuaternion.y+this._tmpQuaternion.z*this._tmpQuaternion.z);if(this._tmpVector.set(this._tmpQuaternion.x,this._tmpQuaternion.y,this._tmpQuaternion.z),e<.001)this._tmpVector.scaleInPlace(2);else{const t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}t.impostor.setAngularVelocity(this._tmpVector)}r.copyFrom(i.rotationQuaternion),this._debugMode&&Ne.Log([this._tmpVector,this._tmpQuaternion,"angular"])}))}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}zR.Name=qa.PHYSICS_CONTROLLERS,zR.Version=1,Za.AddWebXRFeature(zR.Name,((e,t)=>()=>new zR(e,t)),zR.Version,!0);class WR extends Ja{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new me,this._tmpPos=new _e,this._tmpQuat=new fe,this._initHitTestSource=e=>{if(!e)return;const t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),i.space?this._xrSessionManager.session.requestHitTestSource(i).then((e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})):Ds.Warn("waiting for viewer reference space to initialize")},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new K,this.paused=!1,this.xrNativeFeatureName="hit-test",Ds.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach())return!1;if(!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){const e=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:e,entityTypes:this.options.entityTypes}).then((e=>{this._transientXrHitTestSource=e}))}return!0}detach(){return!!super.detach()&&(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(this.attached&&!this.paused){if(this._xrHitTestSource){const t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}this._transientXrHitTestSource&&e.getHitTestResultsForTransientInput(this._transientXrHitTestSource).forEach((e=>{this._processWebXRHitTestResult(e.results,e.inputSource)}))}}_processWebXRHitTestResult(e,t){const i=[];e.forEach((e=>{const s=e.getPose(this._xrSessionManager.referenceSpace);if(!s)return;const r=s.transform.position,n=s.transform.orientation;this._tmpPos.set(r.x,r.y,r.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._tmpQuat.set(n.x,n.y,n.z,n.w),me.FromFloat32ArrayToRefScaled(s.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());const o={position:this.autoCloneTransformation?this._tmpPos.clone():this._tmpPos,rotationQuaternion:this.autoCloneTransformation?this._tmpQuat.clone():this._tmpQuat,transformationMatrix:this.autoCloneTransformation?this._tmpMat.clone():this._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:e};i.push(o)})),this.onHitTestResultObservable.notifyObservers(i)}}WR.Name=qa.HIT_TEST,WR.Version=2,Za.AddWebXRFeature(WR.Name,((e,t)=>()=>new WR(e,t)),WR.Version,!1);class HR extends Ja{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new K,this.onFeaturePointsUpdatedObservable=new K,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this.featurePointCloud.length=0,!0)}dispose(){super.dispose(),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw new Error("Received malformed feature point cloud of length: "+t.length);const e=t.length/5,i=[],s=[];for(let r=0;r0&&this.onFeaturePointsAddedObservable.notifyObservers(s),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}}HR.Name=qa.FEATURE_POINTS,HR.Version=1,Za.AddWebXRFeature(HR.Name,(e=>()=>new HR(e)),HR.Version);let XR=0;class YR extends Ja{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new K,this.onMeshRemovedObservable=new K,this.onMeshUpdatedObservable=new K,this.xrNativeFeatureName="mesh-detection",this._options.generateMeshes&&(this._options.convertCoordinateSystems=!0),this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach((e=>{this.onMeshRemovedObservable.notifyObservers(e)})),this._detectedMeshes.clear()),!0)}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){try{if(!this.attached||!e)return;const t=e.detectedMeshes||e.worldInformation?.detectedMeshes;if(t){const i=new Set;this._detectedMeshes.forEach(((e,s)=>{t.has(s)||i.add(s)})),i.forEach((e=>{const t=this._detectedMeshes.get(e);t&&(this.onMeshRemovedObservable.notifyObservers(t),this._detectedMeshes.delete(e))})),t.forEach((t=>{if(this._detectedMeshes.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{const i={id:XR++,xrMesh:t},s=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,s),this.onMeshAddedObservable.notifyObservers(s)}}))}}catch(e){Ne.Log(e.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;const s=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=s,t.normals=e.normals;else{t.positions=new Float32Array(s.length);for(let e=0;e()=>new YR(e,t)),YR.Version,!1),function(e){e[e.NotReceived=0]="NotReceived",e[e.Waiting=1]="Waiting",e[e.Received=2]="Received"}(QR||(QR={}));class jR extends Ja{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new K,this.onTrackableImageFoundObservable=new K,this.onTrackedImageUpdatedObservable=new K,this._trackableScoreStatus=QR.NotReceived,this._trackedImages=[],this.xrNativeFeatureName="image-tracking"}attach(){return super.attach()}detach(){return super.detach()}getTrackedImageById(e){return this._trackedImages[e]||null}dispose(){super.dispose(),this._trackedImages.forEach((e=>{e.originalBitmap.close()})),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()}async getXRSessionInitExtension(){if(!this.options.images||!this.options.images.length)return{};const e=this.options.images.map((e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src)));try{const t=await Promise.all(e);return this._originalTrackingRequest=t.map(((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth}))),{trackedImages:this._originalTrackingRequest}}catch(e){return Ds.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===QR.Waiting)return;if(this._trackableScoreStatus===QR.NotReceived)return void this._checkScoresAsync();const t=e.getImageTrackingResults();for(const i of t){let t=!1;const s=i.index,r=this._trackedImages[s];if(!r)continue;r.xrTrackingResult=i,r.realWorldWidth!==i.measuredWidthInMeters&&(r.realWorldWidth=i.measuredWidthInMeters,t=!0);const n=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(n){const e=r.transformationMatrix;me.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}const o="emulated"===i.trackingState;r.emulated!==o&&(r.emulated=o,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(r)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==QR.NotReceived)return;this._trackableScoreStatus=QR.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(e&&0!==e.length){for(let t=0;t0?QR.Received:QR.NotReceived}else this._trackableScoreStatus=QR.NotReceived}}jR.Name=qa.IMAGE_TRACKING,jR.Version=1,Za.AddWebXRFeature(jR.Name,((e,t)=>()=>new jR(e,t)),jR.Version,!1);class KR extends Ja{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",Ds.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!(!super.attach()||!this._xrSessionManager.session.domOverlayState||null===this._xrSessionManager.session.domOverlayState.type||(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),0))}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(void 0===this.options.element)return Ds.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){const e=document.querySelector(this.options.element);if(null===e)return Ds.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`),{};this._element=e}else this._element=this.options.element;return{domOverlay:{root:this._element}}}}KR.Name=qa.DOM_OVERLAY,KR.Version=1,Za.AddWebXRFeature(KR.Name,((e,t)=>()=>new KR(e,t)),KR.Version,!1);class $R extends Ja{get movementDirection(){return this._movementDirection}get movementEnabled(){return this._featureContext.movementEnabled}set movementEnabled(e){this._featureContext.movementEnabled=e}get movementOrientationFollowsViewerPose(){return this._featureContext.movementOrientationFollowsViewerPose}set movementOrientationFollowsViewerPose(e){this._featureContext.movementOrientationFollowsViewerPose=e}get movementSpeed(){return this._featureContext.movementSpeed}set movementSpeed(e){this._featureContext.movementSpeed=e}get movementThreshold(){return this._featureContext.movementThreshold}set movementThreshold(e){this._featureContext.movementThreshold=e}get rotationEnabled(){return this._featureContext.rotationEnabled}set rotationEnabled(e){this._featureContext.rotationEnabled=e}get rotationSpeed(){return this._featureContext.rotationSpeed}set rotationSpeed(e){this._featureContext.rotationSpeed=e}get rotationThreshold(){return this._featureContext.rotationThreshold}set rotationThreshold(e){this._featureContext.rotationThreshold=e}constructor(e,t){super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new fe,this._tmpRotationMatrix=me.Identity(),this._tmpTranslationDirection=new _e,this._tmpMovementTranslation=new _e,this._tempCacheQuaternion=new fe,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController)for(const i of this._currentRegistrationConfigurations){let s=null;if(i.allowedComponentTypes)for(const t of i.allowedComponentTypes){const i=e.motionController.getComponentOfType(t);if(null!==i){s=i;break}}if(i.mainComponentOnly){const t=e.motionController.getMainComponent();if(null===t)continue;s=t}if("function"==typeof i.componentSelectionPredicate&&(s=i.componentSelectionPredicate(e)),s&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness)continue;if(null===s)continue;const r={registrationConfiguration:i,component:s};t.registeredComponents.push(r),"axisChangedHandler"in i&&(r.onAxisChangedObserver=s.onAxisValueChangedObservable.add((e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)}))),"buttonChangedhandler"in i&&(r.onButtonChangedObserver=s.onButtonStateChangedObservable.add((()=>{s.changes.pressed&&i.buttonChangedhandler(s.changes.pressed,this._movementState,this._featureContext,this._xrInput)})))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}},t&&void 0!==t.xrInput?(Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=$R.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:t.movementOrientationFollowsViewerPose??!0,movementSpeed:t.movementSpeed??1,movementThreshold:t.movementThreshold??.25,rotationEnabled:t.rotationEnabled??!0,rotationSpeed:t.rotationSpeed??1,rotationThreshold:t.rotationThreshold??.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput):Ds.Error('WebXRControllerMovement feature requires "xrInput" option.')}attach(){return!!super.attach()&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._controllers={},!0)}_onXRFrame(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){const e=.001*this._xrSessionManager.scene.getEngine().getDeltaTime()*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=e,fe.RotationYawPitchRollToRef(e,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(fe.RotationYawPitchRollToRef(3*e,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(me.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),_e.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}}_detachController(e){const t=this._controllers[e];if(t){for(const e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}}$R.Name=qa.MOVEMENT,$R.REGISTRATIONS={default:[{allowedComponentTypes:[rv.THUMBSTICK_TYPE,rv.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(e,t,i)=>{t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[rv.THUMBSTICK_TYPE,rv.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(e,t,i)=>{t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},$R.Version=1,Za.AddWebXRFeature($R.Name,((e,t)=>()=>new $R(e,t)),$R.Version,!0);class qR extends Ja{constructor(e,t){super(e),this.options=t,this._canvasContext=null,this._reflectionCubeMap=null,this._xrLightEstimate=null,this._xrLightProbe=null,this._xrWebGLBinding=null,this._lightDirection=_e.Up().negateInPlace(),this._lightColor=Ee.White(),this._intensity=1,this._sphericalHarmonics=new Q_,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new K,this._updateReflectionCubeMap=()=>{if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const e=Date.now();if(e-this._cubeMapPollTime{this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap)})))}},this.xrNativeFeatureName="light-estimation",this.options.createDirectionalLightSource&&(this.directionalLight=new cg("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new _e(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=Br.FALLOFF_GLTF),this._hdrFilter=new rx(this._xrSessionManager.scene.getEngine()),Ds.Warn("light-estimation is an experimental and unstable feature.")}get reflectionCubeMapTexture(){return this._reflectionCubeMap}get xrLightingEstimate(){return this._xrLightEstimate?{lightColor:this._lightColor,lightDirection:this._lightDirection,lightIntensity:this._intensity,sphericalHarmonics:this._sphericalHarmonics}:this._xrLightEstimate}_getCanvasContext(){return null===this._canvasContext&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(null===this._xrWebGLBinding){const e=this._getCanvasContext();this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,e)}return this._xrWebGLBinding}attach(){if(!super.attach())return!1;const e=this.options.reflectionFormat??(this._xrSessionManager.session.preferredReflectionFormat||"srgba8");return this.options.reflectionFormat=e,this._xrSessionManager.session.requestLightProbe({reflectionFormat:e}).then((e=>{this._xrLightProbe=e,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new ya(this._xrSessionManager.scene),this._reflectionCubeMap._isCube=!0,this._reflectionCubeMap.coordinatesMode=3,this.options.setSceneEnvironmentTexture&&(this._xrSessionManager.scene.environmentTexture=this._reflectionCubeMap)),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap))})),!0}detach(){const e=super.detach();return null===this._xrLightProbe||this.options.disableCubeMapReflection||(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,e}dispose(){super.dispose(),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){const e=Date.now();if(e-this._lightEstimationPollTime()=>new qR(e,t)),qR.Version,!1);class ZR extends Ja{constructor(e){super(e),this.onEyeTrackingStartedObservable=new K,this.onEyeTrackingEndedObservable=new K,this.onEyeTrackingFrameUpdateObservable=new K,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new Ua(_e.Zero(),_e.Forward()),this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay)},this._eyeTrackingEndListener=()=>{this._latestEyeSpace=null,this._gazeRay=null,this.onEyeTrackingEndedObservable.notifyObservers()},this.xrNativeFeatureName="eye-tracking",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}dispose(){super.dispose(),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()}get isEyeGazeValid(){return!!this._gazeRay}getEyeGaze(){return this._gazeRay}_onXRFrame(e){if(this.attached&&e&&this._latestEyeSpace&&this._gazeRay){const t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z).scaleInPlace(this._xrSessionManager.worldScalingFactor);const e=t.transform.orientation;ve.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?_e.RightHandedForwardReadOnly.rotateByQuaternionToRef(ve.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,ve.Quaternion[0].z*=-1,ve.Quaternion[0].w*=-1,_e.LeftHandedForwardReadOnly.rotateByQuaternionToRef(ve.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))}}ZR.Name=qa.EYE_TRACKING,ZR.Version=1,Za.AddWebXRFeature(ZR.Name,(e=>()=>new ZR(e)),ZR.Version,!1);class JR{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw new Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class eM{constructor(){this._samples=new JR(20),this._entropy=0,this.onFirstStepDetected=new K}update(e,t,i,s){this._samples.push(e,t);const r=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=de.Distance(r,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let n;for(n=this._samePointCheckStartIdx;no&&(a=t,o=e);if(on*this._squaredProjectionDistanceThreshold)return;const p=ve.Vector3[0];p.set(i,s,0);const f=ve.Vector3[1];f.set(h.x,h.y,0);const m=_e.Cross(p,f).z>0,g=r.clone(),v=r.clone();l.subtractToRef(r,h),m?(h.scaleAndAddToRef(this._axisToApexShrinkFactor,g),h.scaleAndAddToRef(this._axisToApexExtendFactor,v)):(h.scaleAndAddToRef(this._axisToApexExtendFactor,g),h.scaleAndAddToRef(this._axisToApexShrinkFactor,v)),this.onFirstStepDetected.notifyObservers({leftApex:g,rightApex:v,currentPosition:r,currentStepDirection:m?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),this._axisLength<.03))}get _vitalityThreshold(){return.1}get forward(){return this._forward}}class iM{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new eM,this._walker=null,this._movement=new de,this._millisecondsSinceLastUpdate=iM._MillisecondsPerUpdate,this.movementThisFrame=_e.Zero(),this._engine=e,this._detector.onFirstStepDetected.add((e=>{this._walker||(this._walker=new tM(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),this._walker.onFootfall.add((()=>{Ne.Log("Footfall!")})),this._walker.onMovement.add((e=>{this._walker.forward.scaleAndAddToRef(.024*e.deltaT,this._movement)})))}))}update(e,t){t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=iM._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=iM._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker&&(this._walker.update(e.x,e.z)||(this._walker=null)),this._movement.scaleInPlace(.85)),this.movementThisFrame.set(this._movement.x,0,this._movement.y)}}class sM extends Ja{static get Name(){return qa.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()}constructor(e,t){super(e),this._up=new _e,this._forward=new _e,this._position=new _e,this._movement=new _e,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&Ne.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended")}isCompatible(){return void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!(!this.isCompatible||!super.attach()||(this._walker=new iM(this._sessionManager.scene.getEngine()),0))}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){const t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;const i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,s=t.transform.matrix;this._up.copyFromFloats(s[4],s[5],i*s[6]),this._forward.copyFromFloats(s[8],s[9],i*s[10]),this._position.copyFromFloats(s[12],s[13],i*s[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||_e.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}Za.AddWebXRFeature(sM.Name,((e,t)=>()=>new sM(e,t)),sM.Version,!1);class rM extends du{constructor(e,t,i,s,r,n,o=null){super(e,t,i,s,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this.isMultiview=r,this.createRTTProvider=n,this._originalInternalTexture=o}}class nM extends _u{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this.onRenderTargetTextureCreatedObservable=new K,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t="none"){const i=this._lastSubImages.get(t),s="right"==t?1:0,r=e.colorTextureWidth??e.textureWidth,n=e.colorTextureHeight??e.textureHeight;if(!this._renderTargetTextures[s]||i?.textureWidth!==r||i?.textureHeight!==n){let i;const o=e.depthStencilTextureWidth??r,a=e.depthStencilTextureHeight??n;r!==o&&n!==a||(i=e.depthStencilTexture),this._renderTargetTextures[s]=this._createRenderTargetTexture(r,n,null,e.colorTexture,i,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n},this.onRenderTargetTextureCreatedObservable.notifyObservers({texture:this._renderTargetTextures[s],eye:t})}return this._lastSubImages.set(t,e),this._renderTargetTextures[s]}_getSubImageForEye(e){const t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){const t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e?.eye)}_setViewportForSubImage(e,t){const i=t.colorTextureWidth??t.textureWidth,s=t.colorTextureHeight??t.textureHeight,r=t.viewport;e.x=r.x/i,e.y=r.y/s,e.width=r.width/i,e.height=r.height/s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}}class oM extends rM{constructor(e,t,i){super((()=>e.textureWidth),(()=>e.textureHeight),e,"XRProjectionLayer",t,(e=>new aM(e,i,this))),this.layer=e}}class aM extends nM{constructor(e,t,i){super(e,t,i),this.layerWrapper=i,this._projectionLayer=i.layer}_getSubImageForView(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)}getRenderTargetTextureForView(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)}getRenderTargetTextureForEye(e){const t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}}const lM={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1,clearOnAccess:!1},hM={};class cM extends Ja{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this._isMultiviewEnabled=!1,this._projectionLayerInitialized=!1,this._compositionLayerTextureMapping=new WeakMap,this._layerToRTTProviderMapping=new WeakMap,this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;const t={...lM,...this._options.projectionLayerInit};return this._isMultiviewEnabled=this._options.preferMultiviewOnInit&&e.getCaps().multiview,this.createProjectionLayer(t),this._projectionLayerInitialized=!0,!0}detach(){return!!super.detach()&&(this._existingLayers.forEach((e=>{e.dispose()})),this._existingLayers.length=0,this._projectionLayerInitialized=!1,!0)}createXRWebGLLayer(e=hM){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new pu(t)}_validateLayerInit(e,t=this._isMultiviewEnabled){if(!this._xrSessionManager.inXRSession)throw new Error("Cannot create a layer outside of a WebXR session. Make sure the session has started before creating layers.");if(t&&"texture-array"!==e.textureType)throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)throw new Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.")}_extendXRLayerInit(e,t=this._isMultiviewEnabled){return t&&(e.textureType="texture-array"),e}createProjectionLayer(e=lM,t=this._isMultiviewEnabled){this._extendXRLayerInit(e,t),this._validateLayerInit(e,t);const i=this._xrWebGLBinding.createProjectionLayer(e),s=new oM(i,t,this._xrWebGLBinding);return this.addXRSessionLayer(s),s}_createQuadLayer(e={params:{}},t){this._extendXRLayerInit(e.params,!1);const i=this._existingLayers[0].layer.textureWidth,s=this._existingLayers[0].layer.textureHeight,r={space:this._xrSessionManager.referenceSpace,viewPixelWidth:i,viewPixelHeight:s,clearOnAccess:!0,...e.params};this._validateLayerInit(r,!1);const n=this._xrWebGLBinding.createQuadLayer(r);n.width=this._isMultiviewEnabled?1:2,n.height=1;const o=new rM((()=>n.width),(()=>n.height),n,"XRQuadLayer",!1,(e=>new nM(e,this._xrWebGLBinding,o)));t&&this._compositionLayerTextureMapping.set(n,t);const a=o.createRenderTargetTextureProvider(this._xrSessionManager);return this._layerToRTTProviderMapping.set(n,a),this.addXRSessionLayer(o),o}addFullscreenAdvancedDynamicTexture(e,t={distanceFromHeadset:1.5}){const i=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}},e),s=i.layer,r={x:0,y:0,z:-Math.max(.1,t.distanceFromHeadset)};s.transform=new XRRigidTransform(r,{x:0,y:0,z:0,w:1});const n=this._layerToRTTProviderMapping.get(s);if(!n)throw new Error("Could not find the RTT provider for the layer");const o=this._xrSessionManager.scene.layers.find((t=>t.texture===e));if(!o)throw new Error("Could not find the babylon layer for the texture");return n.onRenderTargetTextureCreatedObservable.add((e=>{e.eye&&"right"===e.eye||(e.texture.clearColor=new Ae(0,0,0,0),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.scene.onBeforeRenderObservable.add((()=>{e.texture.render()})),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.onXRSessionEnded.addOnce((()=>{o.renderTargetTextures.splice(o.renderTargetTextures.indexOf(e.texture),1),o.renderOnlyInRenderTargetTextures=!1})))})),i}_addLensFlareSystem(e){const t=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}}),i=t.layer;i.width=2,i.height=1;i.transform=new XRRigidTransform({x:0,y:0,z:-10},{x:0,y:0,z:0,w:1});const s=this._layerToRTTProviderMapping.get(i);if(!s)throw new Error("Could not find the RTT provider for the layer");return s.onRenderTargetTextureCreatedObservable.add((t=>{t.texture.clearColor=new Ae(0,0,0,0),t.texture.customRenderFunction=()=>{e.render()}})),this._xrSessionManager.onXRSessionInit.add((()=>{this._xrSessionManager.scene.lensFlareSystems.splice(this._xrSessionManager.scene.lensFlareSystems.indexOf(e),1)})),this._xrSessionManager.onXRSessionEnded.add((()=>{this._xrSessionManager.scene.lensFlareSystems.push(e)})),t}addXRSessionLayer(e){this._existingLayers.push(e),this.setXRSessionLayers(this._existingLayers)}setXRSessionLayers(e=this._existingLayers){const t={...this._xrSessionManager.session.renderState};t.baseLayer=void 0,t.layers=e.map((e=>e.layer)),this._xrSessionManager.updateRenderState(t),this._projectionLayerInitialized||this._xrSessionManager._setBaseLayerWrapper(e.length>0?e.at(0):null)}isCompatible(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){const t=this._existingLayers;for(let i=0;i()=>new cM(e,t)),cM.Version,!1);class uM extends Ja{get width(){return this._width}get height(){return this._height}get rawValueToMeters(){return this._rawValueToMeters}get normDepthBufferFromNormView(){return this._normDepthBufferFromNormView}get depthUsage(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}}get depthDataFormat(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}}get latestInternalTexture(){if(!this._cachedWebGLTexture)return null;const e=this._xrSessionManager.scene.getEngine(),t=new ss(e,is.Unknown);return t.isCube=!1,t.invertY=!1,t._useSRGBBuffer=!1,t.format="ushort"===this.depthDataFormat?2:5,t.generateMipMaps=!1,t.type="ushort"===this.depthDataFormat?5:1,t.samplingMode=7,t.width=this.width??0,t.height=this.height??0,t._cachedWrapU=1,t._cachedWrapV=1,t._hardwareTexture=new Ks(this._cachedWebGLTexture,e._gl),t}get latestDepthBuffer(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null}get latestDepthImageTexture(){return this._cachedDepthImageTexture}constructor(e,t){super(e),this.options=t,this._width=null,this._height=null,this._rawValueToMeters=null,this._normDepthBufferFromNormView=null,this._cachedDepthBuffer=null,this._cachedWebGLTexture=null,this._cachedDepthImageTexture=null,this.onGetDepthInMetersAvailable=new K,this.xrNativeFeatureName="depth-sensing",Ds.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){return!!super.attach(e)&&(null!=this._xrSessionManager.session.depthDataFormat&&null!=this._xrSessionManager.session.depthUsage&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0))}dispose(){this._cachedDepthImageTexture?.dispose()}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(const t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:Ds.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(null===s)return;const{data:r,width:n,height:o,rawValueToMeters:a,getDepthInMeters:l}=s;switch(this._width=n,this._height=o,this._rawValueToMeters=a,this._cachedDepthBuffer=r,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(s)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Oa.CreateRTexture(null,n,o,this._xrSessionManager.scene,!1,!0,Pa.NEAREST_SAMPLINGMODE,oo.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(r)).map((e=>e*a)));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(r).map((e=>e*a)))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(null===s)return;const{texture:r,width:n,height:o}=s;this._width=n,this._height=o,this._cachedWebGLTexture=r;const a=this._xrSessionManager.scene,l=a.getEngine().wrapWebGLTexture(r);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=Oa.CreateRTexture(null,n,o,a,!1,!0,Pa.NEAREST_SAMPLINGMODE,"ushort"===i?oo.TEXTURETYPE_UNSIGNED_BYTE:oo.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=l}getXRSessionInitExtension(){const e=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,t=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise((i=>{i(e&&t?{depthSensing:{usagePreference:this.options.usagePreference.map((e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}})),dataFormatPreference:this.options.dataFormatPreference.map((e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}}))}}:{})}))}}uM.Name=qa.DEPTH_SENSING,uM.Version=1,Za.AddWebXRFeature(uM.Name,((e,t)=>()=>new uM(e,t)),uM.Version,!1);Bi.ShadersStore.velocityPixelShader="precision highp float;\n#define CUSTOM_FRAGMENT_BEGIN\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nhighp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.velocityVertexShader="#define CUSTOM_VERTEX_BEGIN\n#define VELOCITY\nattribute vec3 position;\n#include\nuniform mat4 viewProjection;uniform mat4 previousViewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR;\n#endif\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;}\n#elif\nclipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class dM extends ih{constructor(e,t,i,s=512){super("spacewarp rtt",s,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[me.Identity(),me.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new Nd("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add((e=>{this._previousWorldMatrices[e.uniqueId]=this._previousWorldMatrices[e.uniqueId]||e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[e.uniqueId]),this._previousWorldMatrices[e.uniqueId]=e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)})),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;const i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach((e=>{this._originalPairing.push([e,e.material]),e.material=this._velocityMaterial})),super.render(e,t),this._originalPairing.forEach((e=>{e[0].material=e[1]}))}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}}class _M{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){const t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');const i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,s,r){if(!this._engine)throw new Error("Engine is disposed");const n={width:e,height:t},o=new dM(s,r,this._scene,n),a=o.renderTarget;return i&&(a._framebuffer=i),a._colorTextureArray=s,a._depthStencilTextureArray=r,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let s=this._renderTargetTextures.get(t.eye);const r=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return s&&i?.textureWidth===r&&i?.textureHeight==n||(s=this._createRenderTargetTexture(r,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,s),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n}),this._lastSubImages.set(t,e),s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}accessMotionVector(e){const t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){const t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.clear()}}class pM extends Ja{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[qa.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new _M(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add((()=>this._onAfterRender())),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;const i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}}pM.Name=qa.SPACE_WARP,pM.Version=1,Za.AddWebXRFeature(pM.Name,(e=>()=>new pM(e)),pM.Version,!1);class fM extends Ja{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new K,this.xrNativeFeatureName="camera-access"}attach(e){return!!super.attach(e)&&(this._glContext=this._xrSessionManager.scene.getEngine()._gl,this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),!0)}detach(){return!!super.detach()&&(this._glBinding=void 0,this.options.doNotDisposeOnDetach||(this._cachedInternalTextures.forEach((e=>e.dispose())),this.texturesData.forEach((e=>e.dispose())),this._cachedInternalTextures.length=0,this.texturesData.length=0,this.cameraIntrinsics.length=0),!0)}dispose(){super.dispose(),this.onTexturesUpdatedObservable.clear()}_updateCameraIntrinsics(e,t){const i={width:e.camera.width,height:e.camera.height,x:0,y:0},s=e.projectionMatrix,r=(1-s[8])*i.width/2+i.x,n=(1-s[9])*i.height/2+i.y,o=i.width/2*s[0],a=i.height/2*s[5],l=i.width/2*s[4];this.cameraIntrinsics[t]={u0:r,v0:n,ax:o,ay:a,gamma:l,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){if(!e.camera)return!1;this.viewIndex[t]=e.eye;const i=this._glBinding?.getCameraImage(e.camera);if(this._cachedInternalTextures[t])this._cachedInternalTextures[t]._hardwareTexture?.set(i);else{const s=new ss(this._xrSessionManager.scene.getEngine(),is.Unknown,!0);s.isCube=!0,s.invertY=!1,s.format=5,s.generateMipMaps=!0,s.type=1,s.samplingMode=3,s.width=e.camera.width,s.height=e.camera.height,s._cachedWrapU=1,s._cachedWrapV=1,s._hardwareTexture=new Ks(i,this._glContext),this._cachedInternalTextures[t]=s;const r=new ya(this._xrSessionManager.scene);r.name=`WebXR Raw Camera Access (${t})`,r._texture=this._cachedInternalTextures[t],this.texturesData[t]=r,this._updateCameraIntrinsics(e,t)}return this._cachedInternalTextures[t].isReady=!0,!0}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(!i||!i.views)return;let s=!0;i.views.forEach(((e,t)=>{s=s&&this._updateInternalTextures(e,t)})),s&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}fM.Name=qa.RAW_CAMERA_ACCESS,fM.Version=1,Za.AddWebXRFeature(fM.Name,((e,t)=>()=>new fM(e,t)),fM.Version,!1);class mM extends nv{constructor(e,t,i){super(e,gM[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}}cv.RegisterController("generic-hand-select-grasp",((e,t)=>new mM(t,e.gamepad,e.handedness)));const gM={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};class vM extends nv{constructor(e,t,i){super(e,xM["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";return e="left"===this.handedness?vM.MODEL_LEFT_FILENAME:vM.MODEL_RIGHT_FILENAME,{filename:e,path:vM.MODEL_BASE_URL+"default/"}}_getModelLoadingConstraints(){const e=fl.IsPluginForExtensionAvailable(".glb");return e||Ne.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach(((e,t)=>{if(!this.disableAnimation&&e&&this.rootMesh){const i=this._mapping.buttons[e],s=i.rootNodeName;if(!s)return void Ne.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);const r=this._getChildByName(this.rootMesh,s);if(!r)return void Ne.Warn("Missing button mesh with name: "+s);if(i.valueMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.valueNodeName),i.pressedMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.pressedNodeName),i.unpressedMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.unpressedNodeName),i.valueMesh&&i.pressedMesh&&i.unpressedMesh){const t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add((e=>{this._lerpTransform(i,e.value)}),void 0,!0)}else Ne.Warn("Missing button submesh under mesh with name: "+s)}})),this.getComponentIds().forEach((e=>{const t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach((i=>{if(!this.rootMesh)return;const s=this._mapping.axes[e][i],r=this._getChildByName(this.rootMesh,s.rootNodeName);r?(s.valueMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.valueNodeName),s.minMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.minNodeName),s.maxMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.maxNodeName),s.valueMesh&&s.minMesh&&s.maxMesh?t&&t.onAxisValueChangedObservable.add((e=>{const t="x-axis"===i?e.x:e.y;this._lerpTransform(s,t,!0)}),void 0,!0):Ne.Warn("Missing axis submesh under mesh with name: "+s.rootNodeName)):Ne.Warn("Missing axis mesh with name: "+s.rootNodeName)}))})))}_setRootMesh(e){let t;this.rootMesh=new ha(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;inew vM(t,e.gamepad,e.handedness)));const xM={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};class bM extends nv{constructor(e,t,i,s=!1,r=!1){super(e,TM[i],t,i),this._forceLegacyControllers=r,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";return e="left"===this.handedness?bM.MODEL_LEFT_FILENAME:bM.MODEL_RIGHT_FILENAME,{filename:e,path:this._isQuest()?bM.QUEST_MODEL_BASE_URL:bM.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){const t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach((e=>{const s=e&&this.getComponent(e);s&&s.onButtonStateChangedObservable.add((s=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(t||(this._modelRootNode.getChildren()[3].rotation.x=.2*-s.value,this._modelRootNode.getChildren()[3].position.y=.005*-s.value,this._modelRootNode.getChildren()[3].position.z=.005*-s.value));case"xr-standard-squeeze":return void(t||(this._modelRootNode.getChildren()[4].position.x=i*s.value*.0035));case"xr-standard-thumbstick":return;case"a-button":case"x-button":return void(t||(s.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0));case"b-button":case"y-button":return void(t||(s.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0))}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new ha(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=fe.FromEulerAngles(0,Math.PI,0)),e.forEach((e=>{e.isPickable=!1})),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}}bM.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",bM.MODEL_LEFT_FILENAME="left.babylon",bM.MODEL_RIGHT_FILENAME="right.babylon",bM.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",cv.RegisterController("oculus-touch",((e,t)=>new bM(t,e.gamepad,e.handedness))),cv.RegisterController("oculus-touch-legacy",((e,t)=>new bM(t,e.gamepad,e.handedness,!0)));const TM={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};class yM extends nv{constructor(e,t,i){super(e,SM[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){return{filename:yM.MODEL_FILENAME,path:yM.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add((t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(this._modelRootNode.getChildren()[6].rotation.x=.15*-t.value);case"xr-standard-touchpad":case"xr-standard-squeeze":return}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new ha(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1})),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=fe.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}yM.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",yM.MODEL_FILENAME="wand.babylon",cv.RegisterController("htc-vive",((e,t)=>new yM(t,e.gamepad,e.handedness)));const SM={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};class CM{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw new Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>this._nativeImpl._imageTrackingResults??[]}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;const i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];const s=this._xrTransform.orientation;return s.x=this._xrPoseVectorData[4],s.y=this._xrPoseVectorData[5],s.z=this._xrPoseVectorData[6],s.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw new Error("This function is not available in Babylon Native")}}var EM;Jp("NativeXRFrame",CM),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(EM||(EM={}));class AM{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=Cs(),this.connectedPointIds=[],this.name=e,this._connectionType=t}get connectionType(){return this._connectionType}_isSingularConnection(){return!0}isConnected(){return this._connectedPoint.length>0}connectTo(e){if(this._connectionType===e._connectionType)throw new Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw new Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName();for(const t of this._connectedPoint)e.connectedPointIds.push(t.uniqueId)}getClassName(){return"FGConnection"}deserialize(e){this.uniqueId=e.uniqueId,this.name=e.name,this._connectionType=e._connectionType,this.connectedPointIds=e.connectedPointIds}static Parse(e={},t){const i=new(Ds.Instantiate(e.className))(e.name,e._connectionType,t);return i.deserialize(e),i}}class PM{constructor(e){this.value=this._toInt(e)}_toInt(e){return 0|e}add(e){return new PM(this.value+e.value)}subtract(e){return new PM(this.value-e.value)}multiply(e){return new PM(Math.imul(this.value,e.value))}divide(e){return new PM(this.value/e.value)}getClassName(){return PM.ClassName}equals(e){return this.value===e.value}static Parse(e){return new PM(e.value)}}PM.ClassName="FlowGraphInteger",z("FlowGraphInteger",PM);class IM{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new IM(e.typeName,e.defaultValue)}}const RM=new IM("any",void 0),MM=new IM("string",""),OM=new IM("number",0),DM=new IM("boolean",!1),wM=new IM("Vector2",de.Zero()),NM=new IM("Vector3",_e.Zero()),FM=new IM("Vector4",pe.Zero()),LM=new IM("Matrix",me.Identity()),BM=new IM("Color3",Ee.Black()),kM=new IM("Color4",new Ae(0,0,0,0)),VM=new IM("Quaternion",fe.Identity()),UM=new IM("FlowGraphInteger",new PM(0));function GM(e){switch(typeof e){case"string":return MM;case"number":return OM;case"boolean":return DM;case"object":return e instanceof de?wM:e instanceof _e?NM:e instanceof pe?FM:e instanceof Ee?BM:e instanceof Ae?kM:e instanceof fe?VM:e instanceof PM?UM:RM;default:return RM}}class zM extends AM{constructor(e,t,i,s){super(e,t,i),this.richType=s}_isSingularConnection(){return this.connectionType===EM.Input}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===EM.Output?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){const i=AM.Parse(e,t);return i.richType=IM.Parse(e.richType),i}}function WM(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function HM(e){return"Vector2"===e||"Vector3"===e||"Vector4"===e||"Quaternion"===e||"Color3"===e||"Color4"===e}function XM(e,t,i){const s=t?.getClassName?.()??"";WM(s)?i[e]={name:t.name,className:s}:HM(s)?i[e]={value:t.asArray(),className:s}:i[e]=t}function YM(e,t,i){const s=t[e];let r;const n=s?.className;return r=WM(n)?i.getMeshByName(s.name):HM(n)?function(e,t){if("Vector2"===e)return de.FromArray(t);if("Vector3"===e)return _e.FromArray(t);if("Vector4"===e)return pe.FromArray(t);if("Quaternion"===e)return fe.FromArray(t);if("Color3"===e)return new Ee(t[0],t[1],t[2]);if("Color4"===e)return new Ae(t[0],t[1],t[2],t[3]);throw new Error(`Unknown vector class name ${e}`)}(n,s.value):"Matrix"===n?me.FromArray(s.value):n===PM.ClassName?PM.Parse(s):s&&void 0!==s.value?s.value:s,r}z("FGDataConnection",zM);class QM{constructor(e){this.config=e,this.uniqueId=Cs(),this.name=this.config?.name??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new zM(e,EM.Input,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new zM(e,EM.Output,this,t);return this.dataOutputs.push(i),i}getDataInput(e){return this.dataInputs.find((t=>t.name===e))}getDataOutput(e){return this.dataOutputs.find((t=>t.name===e))}serialize(e={},t=XM){e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName();for(const t of this.dataInputs){const i={};t.serialize(i),e.dataInputs.push(i)}for(const t of this.dataOutputs){const i={};t.serialize(i),e.dataOutputs.push(i)}}getClassName(){return"FGBlock"}static Parse(e,t){const i=Ds.Instantiate(e.className),s={},r=t.valueParseFunction??YM;if(e.config)for(const i in e.config)s[i]=r(i,e.config,t.scene);(function(e){return"FGSetPropertyBlock"===e||"FGGetPropertyBlock"===e||"FGPlayAnimationBlock"===e||"FGMeshPickEventBlock"===e})(e.className)&&(s.pathConverter=t.pathConverter);const n=new i(s);n.uniqueId=e.uniqueId;for(let t=0;tt.name===e))}getSignalOutput(e){return this.signalOutputs.find((t=>t.name===e))}serialize(e={}){super.serialize(e),e.signalInputs=[],e.signalOutputs=[];for(const t of this.signalInputs){const i={};t.serialize(i),e.signalInputs.push(i)}for(const t of this.signalOutputs){const i={};t.serialize(i),e.signalOutputs.push(i)}}deserialize(e){for(let t=0;t{t.type===lr.POINTERPICK&&t.pickInfo?.pickedMesh&&(t.pickInfo?.pickedMesh===i||JM(t.pickInfo?.pickedMesh,i))&&this._execute(e)}));const s=i.onDisposeObservable.add((()=>this._onDispose));e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",s)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),s=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(s),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return eO.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}var tO;eO.ClassName="FGMeshPickEventBlock",z(eO.ClassName,eO),function(e){e[e.Stopped=0]="Stopped",e[e.Started=1]="Started"}(tO||(tO={}));class iO{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=tO.Stopped,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>this.dispose()))}createContext(){const e=new ZM({scene:this._scene,coordinator:this._coordinator});return this._executionContexts.push(e),e}getContext(e){return this._executionContexts[e]}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==tO.Started){this.state=tO.Started,0===this._executionContexts.length&&this.createContext();for(const e of this._executionContexts){const t=this._getContextualOrder();for(const i of t)i._startPendingTasks(e)}}}_getContextualOrder(){const e=[];for(const t of this._eventBlocks)if(t.getClassName()===eO.ClassName){const i=t._getReferencedMesh();let s=0;for(;s0;){const s=t.pop();e(s);for(const e of s.dataInputs)for(const s of e._connectedPoint)i.has(s._ownerBlock.uniqueId)||(t.push(s._ownerBlock),i.add(s._ownerBlock.uniqueId));if(s instanceof KM)for(const e of s.signalOutputs)for(const s of e._connectedPoint)i.has(s._ownerBlock.uniqueId)||(t.push(s._ownerBlock),i.add(s._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks((t=>{const i={};t.serialize(i),e.allBlocks.push(i)})),e.executionContexts=[];for(const i of this._executionContexts){const s={};i.serialize(s,t),e.executionContexts.push(s)}}static GetDataOutConnectionByUniqueId(e,t){for(const i of e)for(const e of i.dataOutputs)if(e.uniqueId===t)return e;throw new Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(const i of e)if(i instanceof KM)for(const e of i.signalInputs)if(e.uniqueId===t)return e;throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const i=t.coordinator.createGraph(),s=[],r=t.valueParseFunction??YM;for(const n of e.allBlocks){const e=QM.Parse(n,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:r});s.push(e),e instanceof qM&&i.addEventBlock(e)}for(const e of s){for(const t of e.dataInputs)for(const e of t.connectedPointIds){const i=iO.GetDataOutConnectionByUniqueId(s,e);t.connectTo(i)}if(e instanceof KM)for(const t of e.signalOutputs)for(const e of t.connectedPointIds){const i=iO.GetSignalInConnectionByUniqueId(s,e);t.connectTo(i)}}for(const t of e.executionContexts)ZM.Parse(t,{graph:i,valueParseFunction:r});return i}}class sO{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add((()=>{this.dispose()})),(sO.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new iO({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){const t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach((e=>e.start()))}dispose(){this._flowGraphs.forEach((e=>e.dispose())),this._flowGraphs.length=0;const e=sO.SceneCoordinators.get(this.config.scene)??[],t=e.indexOf(this);-1!==t&&e.splice(t,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach((i=>{const s={};i.serialize(s,t),e._flowGraphs.push(s)}))}static Parse(e,t){const i=t.valueParseFunction??YM,s=new sO({scene:t.scene});return e._flowGraphs?.forEach((e=>{iO.Parse(e,{coordinator:s,valueParseFunction:i,pathConverter:t.pathConverter})})),s}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new K,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}sO.SceneCoordinators=new Map;class rO{constructor(e){this._context=e,this._context.onNodeExecutedObservable.add((e=>{Ds.Log(`Node executed: ${e.getClassName()}`)}))}}class nO extends KM{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class oO extends nO{constructor(e){super(e),this.message=this.registerDataInput("message",RM)}_execute(e){const t=this.message.getValue(e);Ne.Log(t),this.out._activateSignal(e)}getClassName(){return oO.ClassName}}oO.ClassName="FGConsoleLogBlock",z(oO.ClassName,oO);class aO extends nO{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,RM)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return aO.ClassName}}aO.ClassName="FGSetVariableBlock",z(aO.ClassName,aO);const lO=new RegExp(/\{(\w+)\}/g);class hO{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=lO.exec(e);for(;i;){const[,s]=i;this.templatedInputs.push(t.registerDataInput(s,UM)),i=lO.exec(e)}}getAccessor(e,t){let i=this.path;for(const e of this.templatedInputs){const s=e.getValue(t).value;i=i.replace(`{${e.name}}`,s.toString())}return e.convert(i)}}class cO extends nO{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",RM),this.templateComponent=new hO(e.path,this)}_execute(e){const t=this.a.getValue(e),i=this.templateComponent.getAccessor(this.config.pathConverter,e);i.info.set(t,i.object),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path}getClassName(){return cO.ClassName}}cO.ClassName="FGSetPropertyBlock",z("FGSetPropertyBlock",cO);class uO extends nO{constructor(e){super(e),this.config=e;for(let e=0;et.getValue(e)));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return uO.ClassName}}uO.ClassName="FGSendCustomEventBlock",z("FGSendCustomEventBlock",uO);class dO extends KM{constructor(e){super(e),this.condition=this.registerDataInput("condition",DM),this.onTrue=this._registerSignalOutput("onTrue"),this.onFalse=this._registerSignalOutput("onFalse")}_execute(e){this.condition.getValue(e)?this.onTrue._activateSignal(e):this.onFalse._activateSignal(e)}getClassName(){return"FGBranchBlock"}}z("FGBranchBlock",dO);class _O extends nO{constructor(e={startIndex:new PM(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",UM),this.value=this.registerDataOutput("value",UM)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const t=this.value.getValue(e);t.values)this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",r);else{const t=s-(r-i);this.timeRemaining.setValue(t,e)}}getClassName(){return"FGThrottleBlock"}}z("FGThrottleBlock",fO);class mO extends $M{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",OM)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(void 0!==t&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],s=e.configuration.scene,r=new Sv({timeout:t,contextObservable:s.onBeforeRenderObservable,onEnded:()=>this._onEnded(r,e)});r.start(),i.push(r),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],s=i.indexOf(e);-1!==s?i.splice(s,1):Ds.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningTimers")||[];for(const e of t)e.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return mO.ClassName}}mO.ClassName="FGTimerBlock",z("FGTimerBlock",mO);class gO extends KM{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",OM),this.config.startIndex=void 0!==this.config.startIndex?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let e=0;e=this.config.numberOutputFlows&&this.config.loop)r=0;else if(r>=this.config.numberOutputFlows&&!this.config.loop)return;if(s=s.filter((e=>e!==r)),0===s.length)for(let e=0;e=0&&(i[e+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every((e=>e))){this.out._activateSignal(e);for(let e=0;e=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}z("FGDebounceBlock",yO);class SO extends KM{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",DM)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}}z("FGFlipFlopBlock",SO);class CO extends KM{constructor(e){super(e),this.config=e,this.outFlows=[];for(let e=0;ethis._onAnimationEnd(t,e)));this.runningAnimatable.setValue(t,e),n.push(t)}e._setExecutionVariable(this,"runningAnimatables",n)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){const i=t._getExecutionVariable(this,"runningAnimatables")??[],s=i.indexOf(e);-1!==s&&i.splice(s,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningAnimatables")??[];for(const e of t)e.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return EO.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}EO.ClassName="FGPlayAnimationBlock",z(EO.ClassName,EO);class AO extends nO{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",RM)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}z("FGStopAnimationBlock",AO);class PO extends nO{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",RM)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}z("FGPauseAnimationBlock",PO);class IO extends QM{constructor(e){super(e),this.condition=this.registerDataInput("condition",DM),this.trueValue=this.registerDataInput("trueValue",RM),this.falseValue=this.registerDataInput("falseValue",RM),this.output=this.registerDataOutput("output",RM)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}z("FGConditionalDataBlock",IO);class RO extends QM{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,RM)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return RO.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}RO.ClassName="FGGetVariableBlock",z(RO.ClassName,RO);class MO extends QM{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",RM),this.destinationSystem=this.registerDataInput("destinationSystem",RM),this.inputCoordinates=this.registerDataInput("inputCoordinates",NM),this.outputCoordinates=this.registerDataOutput("outputCoordinates",NM)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),s=this.inputCoordinates.getValue(e),r=t.getWorldMatrix(),n=i.getWorldMatrix(),o=ve.Matrix[0].copyFrom(n);o.invert();const a=ve.Matrix[1];o.multiplyToRef(r,a);const l=this.outputCoordinates.getValue(e);_e.TransformCoordinatesToRef(s,a,l)}getClassName(){return"FGCoordinateTransformBlock"}}z("FGCoordinateTransformBlock",MO);class OO extends QM{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",GM(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=XM){super.serialize(e),t("value",this.config.value,e.config)}}z("FGConstantBlock",OO);class DO extends QM{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",RM),this.templateComponent=new hO(e.path,this)}_updateOutputs(e){const t=this.templateComponent.getAccessor(this.config.pathConverter,e),i=t.info.get(t.object);this.value.setValue(i,e)}getClassName(){return DO.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}DO.ClassName="FGGetPropertyBlock",z(DO.ClassName,DO);const wO="cachedOperationValue",NO="cachedExecutionId";class FO extends QM{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,NO),i=e._getExecutionVariable(this,wO);if(void 0!==i&&t===e.executionId)this.value.setValue(i,e);else{const t=this._doOperation(e);e._setExecutionVariable(this,wO,t),e._setExecutionVariable(this,NO,e.executionId),this.value.setValue(t,e)}}}class LO extends FO{constructor(e,t,i,s,r,n){super(i,n),this._operation=s,this._className=r,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e))}getClassName(){return this._className}}class BO extends FO{constructor(e,t,i,s,r){super(t,r),this._operation=i,this._className=s,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}const kO="FGLogic",VO="AndBlock",UO="OrBlock",GO="NotBlock";class zO extends LO{constructor(e){super(DM,DM,DM,((e,t)=>e&&t),`${kO}${VO}`,e)}}z(`${kO}${VO}`,zO);class WO extends LO{constructor(e){super(DM,DM,DM,((e,t)=>e||t),`${kO}${UO}`,e)}}z(`${kO}${UO}`,WO);class HO extends BO{constructor(e){super(DM,DM,(e=>!e),`${kO}${GO}`,e)}}z(`${kO}${GO}`,HO);class XO extends FO{constructor(e,t,i,s){super(e,s),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class YO extends FO{constructor(e,t,i,s,r,n,o){super(s,o),this._operation=r,this._className=n,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t),this.c=this.registerDataInput("c",i)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e),this.c.getValue(e))}getClassName(){return this._className}}function QO(e){return e.getClassName?e.getClassName():""}function jO(e,t){return"Vector2"===e&&"Vector2"===t||"Vector3"===e&&"Vector3"===t||"Vector4"===e&&"Vector4"===t}function KO(e,t){return"Matrix"===e&&"Matrix"===t}function $O(e,t){return"FlowGraphInteger"===e&&"FlowGraphInteger"===t}class qO extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicAdd(e,t)),qO.ClassName,e)}_polymorphicAdd(e,t){const i=QO(e),s=QO(t);return jO(i,s)||KO(i,s)||$O(i,s)?e.add(t):e+t}}qO.ClassName="FGAddBlock",z(qO.ClassName,qO);class ZO extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicAdd(e,t)),ZO.ClassName,e)}_polymorphicAdd(e,t){const i=QO(e),s=QO(t);return jO(i,s)||$O(i,s)?e.subtract(t):KO(i,s)?e.add(t.scale(-1)):e-t}}ZO.ClassName="FGSubBlock",z(ZO.ClassName,ZO);class JO extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicMultiply(e,t)),JO.ClassName,e)}_polymorphicMultiply(e,t){const i=QO(e),s=QO(t);return jO(i,s)||$O(i,s)?e.multiply(t):KO(i,s)?me.FromValues(e.m[0]*t.m[0],e.m[4]*t.m[4],e.m[8]*t.m[8],e.m[12]*t.m[12],e.m[1]*t.m[1],e.m[5]*t.m[5],e.m[9]*t.m[9],e.m[13]*t.m[13],e.m[2]*t.m[2],e.m[6]*t.m[6],e.m[10]*t.m[10],e.m[14]*t.m[14],e.m[3]*t.m[3],e.m[7]*t.m[7],e.m[11]*t.m[11],e.m[15]*t.m[15]):e*t}}JO.ClassName="FGMultiplyBlock",z(JO.ClassName,JO);class eD extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicDivide(e,t)),eD.ClassName,e)}_polymorphicDivide(e,t){const i=QO(e),s=QO(t);return jO(i,s)||$O(i,s)?e.divide(t):KO(i,s)?me.FromValues(e.m[0]/t.m[0],e.m[4]/t.m[4],e.m[8]/t.m[8],e.m[12]/t.m[12],e.m[1]/t.m[1],e.m[5]/t.m[5],e.m[9]/t.m[9],e.m[13]/t.m[13],e.m[2]/t.m[2],e.m[6]/t.m[6],e.m[10]/t.m[10],e.m[14]/t.m[14],e.m[3]/t.m[3],e.m[7]/t.m[7],e.m[11]/t.m[11],e.m[15]/t.m[15]):e/t}}eD.ClassName="FGDivideBlock",z(eD.ClassName,eD);class tD extends XO{constructor(e){super(OM,(()=>Math.random()),tD.ClassName,e)}}tD.ClassName="FGRandomBlock",z(tD.ClassName,tD);class iD extends LO{constructor(e){super(RM,RM,OM,((e,t)=>this._polymorphicDot(e,t)),iD.ClassName,e)}_polymorphicDot(e,t){switch(QO(e)){case"Vector2":return de.Dot(e,t);case"Vector3":return _e.Dot(e,t);case"Vector4":return pe.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}iD.ClassName="FGDotBlock",z(iD.ClassName,iD);class sD extends XO{constructor(e){super(OM,(()=>Math.E),sD.ClassName,e)}}sD.ClassName="FGEBlock",z(sD.ClassName,sD);class rD extends XO{constructor(e){super(OM,(()=>Math.PI),rD.ClassName,e)}}rD.ClassName="FGPIBlock",z(rD.ClassName,rD);class nD extends XO{constructor(e){super(OM,(()=>Number.POSITIVE_INFINITY),nD.ClassName,e)}}nD.ClassName="FGInfBlock",z(nD.ClassName,nD);class oD extends XO{constructor(e){super(OM,(()=>Number.NaN),oD.ClassName,e)}}function aD(e,t){switch(QO(e)){case"FlowGraphInteger":return new PM(t(e.value));case"Vector2":return new de(t(e.x),t(e.y));case"Vector3":return new _e(t(e.x),t(e.y),t(e.z));case"Vector4":return new pe(t(e.x),t(e.y),t(e.z),t(e.w));case"Matrix":return me.FromValues(t(e.m[0]),t(e.m[4]),t(e.m[8]),t(e.m[12]),t(e.m[1]),t(e.m[5]),t(e.m[9]),t(e.m[13]),t(e.m[2]),t(e.m[6]),t(e.m[10]),t(e.m[14]),t(e.m[3]),t(e.m[7]),t(e.m[11]),t(e.m[15]));default:return t(e)}}oD.ClassName="FGNaNBlock",z(oD.ClassName,oD);class lD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicAbs(e)),lD.ClassName,e)}_polymorphicAbs(e){return aD(e,Math.abs)}}lD.ClassName="FGAbsBlock",z(lD.ClassName,lD);class hD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicSign(e)),hD.ClassName,e)}_polymorphicSign(e){return aD(e,Math.sign)}}hD.ClassName="FGSignBlock",z(hD.ClassName,hD);class cD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicTrunc(e)),cD.ClassName,e)}_polymorphicTrunc(e){return aD(e,Math.trunc)}}cD.ClassName="FGTruncBlock",z(cD.ClassName,cD);class uD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicFloor(e)),uD.ClassName,e)}_polymorphicFloor(e){return aD(e,Math.floor)}}uD.ClassName="FGFloorBlock",z(uD.ClassName,uD);class dD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicCeiling(e)),dD.ClassName,e)}_polymorphicCeiling(e){return aD(e,Math.ceil)}}dD.ClassName="FGCeilBlock",z(dD.ClassName,dD);class _D extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicFract(e)),_D.ClassName,e)}_polymorphicFract(e){return aD(e,(e=>e-Math.floor(e)))}}_D.ClassName="FGFractBlock",z(_D.ClassName,_D);class pD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicNeg(e)),pD.ClassName,e)}_polymorphicNeg(e){return aD(e,(e=>-e))}}function fD(e,t,i){switch(QO(e)){case"FlowGraphInteger":return new PM(i(e.value,t.value));case"Vector2":return new de(i(e.x,t.x),i(e.y,t.y));case"Vector3":return new _e(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z));case"Vector4":return new pe(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z),i(e.w,t.w));case"Matrix":return me.FromValues(i(e.m[0],t.m[0]),i(e.m[4],t.m[4]),i(e.m[8],t.m[8]),i(e.m[12],t.m[12]),i(e.m[1],t.m[1]),i(e.m[5],t.m[5]),i(e.m[9],t.m[9]),i(e.m[13],t.m[13]),i(e.m[2],t.m[2]),i(e.m[6],t.m[6]),i(e.m[10],t.m[10]),i(e.m[14],t.m[14]),i(e.m[3],t.m[3]),i(e.m[7],t.m[7]),i(e.m[11],t.m[11]),i(e.m[15],t.m[15]));default:return i(e,t)}}pD.ClassName="FGNegBlock",z(pD.ClassName,pD);class mD extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicRemainder(e,t)),mD.ClassName,e)}_polymorphicRemainder(e,t){return fD(e,t,((e,t)=>e%t))}}mD.ClassName="FGRemainderBlock",z(mD.ClassName,mD);class gD extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicMin(e,t)),gD.ClassName,e)}_polymorphicMin(e,t){return fD(e,t,Math.min)}}gD.ClassName="FGMinBlock",z(gD.ClassName,gD);class vD extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicMax(e,t)),vD.ClassName,e)}_polymorphicMax(e,t){return fD(e,t,Math.max)}}function xD(e,t,i){return Math.min(Math.max(e,Math.min(t,i)),Math.max(t,i))}function bD(e,t,i,s){switch(QO(e)){case"FlowGraphInteger":return new PM(s(e.value,t.value,i.value));case"Vector2":return new de(s(e.x,t.x,i.x),s(e.y,t.y,i.y));case"Vector3":return new _e(s(e.x,t.x,i.x),s(e.y,t.y,i.y),s(e.z,t.z,i.z));case"Vector4":return new pe(s(e.x,t.x,i.x),s(e.y,t.y,i.y),s(e.z,t.z,i.z),s(e.w,t.w,i.w));case"Matrix":return me.FromValues(s(e.m[0],t.m[0],i.m[0]),s(e.m[4],t.m[4],i.m[4]),s(e.m[8],t.m[8],i.m[8]),s(e.m[12],t.m[12],i.m[12]),s(e.m[1],t.m[1],i.m[1]),s(e.m[5],t.m[5],i.m[5]),s(e.m[9],t.m[9],i.m[9]),s(e.m[13],t.m[13],i.m[13]),s(e.m[2],t.m[2],i.m[2]),s(e.m[6],t.m[6],i.m[6]),s(e.m[10],t.m[10],i.m[10]),s(e.m[14],t.m[14],i.m[14]),s(e.m[3],t.m[3],i.m[3]),s(e.m[7],t.m[7],i.m[7]),s(e.m[11],t.m[11],i.m[11]),s(e.m[15],t.m[15],i.m[15]));default:return s(e,t,i)}}vD.ClassName="FGMaxBlock",z(vD.ClassName,vD);class TD extends YO{constructor(e){super(RM,RM,RM,RM,((e,t,i)=>this._polymorphicClamp(e,t,i)),TD.ClassName,e)}_polymorphicClamp(e,t,i){return bD(e,t,i,xD)}}function yD(e){return Math.min(Math.max(e,0),1)}TD.ClassName="FGClampBlock",z(TD.ClassName,TD);class SD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicSaturate(e)),SD.ClassName,e)}_polymorphicSaturate(e){return aD(e,yD)}}SD.ClassName="FGSaturateBlock",z(SD.ClassName,SD);class CD extends YO{constructor(e){super(RM,RM,RM,RM,((e,t,i)=>this._polymorphicInterpolate(e,t,i)),CD.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return bD(e,t,i,this._interpolate)}}CD.ClassName="FGInterpolateBlock",z(CD.ClassName,CD);class ED extends LO{constructor(e){super(RM,RM,DM,((e,t)=>this._polymorphicEq(e,t)),ED.ClassName,e)}_polymorphicEq(e,t){const i=QO(e),s=QO(t);return jO(i,s)||KO(i,s)||$O(i,s)?e.equals(t):e===t}}function AD(e,t,i){const s=QO(e);if(s===QO(t)){if(""===s)return i(e,t);if("FlowGraphInteger"===s)return i(e.value,t.value);throw new Error(`Cannot compare ${e} and ${t}`)}throw new Error(`${e} and ${t} are of different types.`)}ED.ClassName="FGEqBlock",z(ED.ClassName,ED);class PD extends LO{constructor(e){super(RM,RM,DM,((e,t)=>this._polymorphicLessThan(e,t)),PD.ClassName,e)}_polymorphicLessThan(e,t){return AD(e,t,((e,t)=>ethis._polymorphicLessThanOrEqual(e,t)),ID.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return AD(e,t,((e,t)=>e<=t))}}ID.ClassName="FGLessThanOrEqualBlock";class RD extends LO{constructor(e){super(RM,RM,DM,((e,t)=>this._polymorphicGreaterThan(e,t)),RD.ClassName,e)}_polymorphicGreaterThan(e,t){return AD(e,t,((e,t)=>e>t))}}RD.ClassName="FGGreaterThanBlock",z(RD.ClassName,RD);class MD extends LO{constructor(e){super(RM,RM,DM,((e,t)=>this._polymorphicGreaterThanOrEqual(e,t)),MD.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return AD(e,t,((e,t)=>e>=t))}}MD.ClassName="FGGreaterThanOrEqualBlock",z(MD.ClassName,MD);class OD extends BO{constructor(e){super(RM,DM,(e=>this._polymorphicIsNan(e)),OD.ClassName,e)}_polymorphicIsNan(e){const t=QO(e);if(""===t)return isNaN(e);if("FlowGraphInteger"===t)return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}OD.ClassName="FGIsNanBlock",z(OD.ClassName,OD);class DD extends BO{constructor(e){super(RM,DM,(e=>this._polymorphicIsInf(e)),DD.ClassName,e)}_polymorphicIsInf(e){const t=QO(e);if(""===t)return!isFinite(e);if("FlowGraphInteger"===t)return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}DD.ClassName="FGIsInfBlock";class wD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicDegToRad(e)),wD.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return aD(e,this._degToRad)}}wD.ClassName="FGDegToRadBlock",z(wD.ClassName,wD);class ND extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicRadToDeg(e)),ND.ClassName,e)}_radToDeg(e){return 180*e/Math.PI}_polymorphicRadToDeg(e){return aD(e,this._radToDeg)}}ND.ClassName="FGRadToDegBlock",z(ND.ClassName,ND);class FD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicSin(e)),FD.ClassName,e)}_polymorphicSin(e){return aD(e,Math.sin)}}FD.ClassName="FGSinBlock",z(FD.ClassName,FD);class LD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicCos(e)),LD.ClassName,e)}_polymorphicCos(e){return aD(e,Math.cos)}}LD.ClassName="FGCosBlock",z(LD.ClassName,LD);class BD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicTan(e)),BD.ClassName,e)}_polymorphicTan(e){return aD(e,Math.tan)}}BD.ClassName="FGTanBlock",z(BD.ClassName,BD);class kD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicAsin(e)),kD.ClassName,e)}_polymorphicAsin(e){return aD(e,Math.asin)}}kD.ClassName="FGAsinBlock",z(kD.ClassName,kD);class VD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicAcos(e)),VD.ClassName,e)}_polymorphicAcos(e){return aD(e,Math.acos)}}VD.ClassName="FGAcosBlock",z(VD.ClassName,VD);class UD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicAtan(e)),UD.ClassName,e)}_polymorphicAtan(e){return aD(e,Math.atan)}}UD.ClassName="FGAtanBlock",z(UD.ClassName,UD);class GD extends LO{constructor(e){super(RM,RM,RM,((e,t)=>this._polymorphicAtan2(e,t)),GD.ClassName,e)}_polymorphicAtan2(e,t){return fD(e,t,Math.atan2)}}GD.ClassName="FGAtan2Block",z(GD.ClassName,GD);class zD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicSinh(e)),zD.ClassName,e)}_polymorphicSinh(e){return aD(e,Math.sinh)}}zD.ClassName="FGSinhBlock",z(zD.ClassName,zD);class WD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicCosh(e)),WD.ClassName,e)}_polymorphicCosh(e){return aD(e,Math.cosh)}}WD.ClassName="FGCoshBlock",z(WD.ClassName,WD);class HD extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicTanh(e)),HD.ClassName,e)}_polymorphicTanh(e){return aD(e,Math.tanh)}}HD.ClassName="FGTanhBlock",z(HD.ClassName,HD);class XD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicAsinh(e)),XD.ClassName,e)}_polymorphicAsinh(e){return aD(e,Math.asinh)}}XD.ClassName="FGAsinhBlock",z(XD.ClassName,XD);class YD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicAcosh(e)),YD.ClassName,e)}_polymorphicAcosh(e){return aD(e,Math.acosh)}}YD.ClassName="FGAcoshBlock",z(YD.ClassName,YD);class QD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicAtanh(e)),QD.ClassName,e)}_polymorphicAtanh(e){return aD(e,Math.atanh)}}QD.ClassName="FGAtanhBlock",z(QD.ClassName,QD);class jD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicExp(e)),jD.ClassName,e)}_polymorphicExp(e){return aD(e,Math.exp)}}jD.ClassName="FGExpBlock",z(jD.ClassName,jD);class KD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicLog(e)),KD.ClassName,e)}_polymorphicLog(e){return aD(e,Math.log)}}KD.ClassName="FGLogBlock",z(KD.ClassName,KD);class $D extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicLog2(e)),$D.ClassName,e)}_polymorphicLog2(e){return aD(e,Math.log2)}}$D.ClassName="FGLog2Block",z($D.ClassName,$D);class qD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicLog10(e)),qD.ClassName,e)}_polymorphicLog10(e){return aD(e,Math.log10)}}qD.ClassName="FGLog10Block",z(qD.ClassName,qD);class ZD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicSqrt(e)),ZD.ClassName,e)}_polymorphicSqrt(e){return aD(e,Math.sqrt)}}ZD.ClassName="FGSqrtBlock",z(ZD.ClassName,ZD);class JD extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicCubeRoot(e)),JD.ClassName,e)}_polymorphicCubeRoot(e){return aD(e,Math.cbrt)}}JD.ClassName="FGCubeRootBlock",z(JD.ClassName,JD);class ew extends LO{constructor(e){super(RM,OM,OM,((e,t)=>this._polymorphicPow(e,t)),ew.ClassName,e)}_polymorphicPow(e,t){return fD(e,t,Math.pow)}}ew.ClassName="FGPowBlock",z(ew.ClassName,ew);class tw extends BO{constructor(e){super(RM,OM,(e=>this._polymorphicLength(e)),tw.ClassName,e)}_polymorphicLength(e){switch(QO(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}tw.ClassName="FGLengthBlock",z(tw.ClassName,tw);class iw extends BO{constructor(e){super(RM,RM,(e=>this._polymorphicNormalize(e)),iw.ClassName,e)}_polymorphicNormalize(e){switch(QO(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}iw.ClassName="FGNormalizeBlock",z(iw.ClassName,iw);class sw extends LO{constructor(e){super(NM,NM,NM,((e,t)=>_e.Cross(e,t)),sw.ClassName,e)}}sw.ClassName="FGCrossBlock",z(sw.ClassName,sw);class rw extends LO{constructor(e){super(wM,OM,wM,((e,t)=>de.Transform(e,me.RotationZ(t))),rw.ClassName,e)}}rw.ClassName="FGRotate2DBlock",z(rw.ClassName,rw);class nw extends YO{constructor(e){super(NM,NM,OM,NM,((e,t,i)=>_e.TransformCoordinates(e,me.RotationAxis(t,i))),nw.ClassName,e)}}nw.ClassName="FGRotate3DBlock",z(nw.ClassName,nw);class ow extends BO{constructor(e){super(LM,LM,(e=>me.Transpose(e)),ow.ClassName,e)}}ow.ClassName="FGTransposeBlock",z(ow.ClassName,ow);class aw extends BO{constructor(e){super(LM,OM,(e=>e.determinant()),aw.ClassName,e)}}aw.ClassName="FGDeterminantBlock",z(aw.ClassName,aw);class lw extends BO{constructor(e){super(LM,LM,(e=>me.Invert(e)),lw.ClassName,e)}}lw.ClassName="FGInvertMatrixBlock",z(lw.ClassName,lw);class hw extends LO{constructor(e){super(LM,LM,LM,((e,t)=>t.multiply(e)),hw.ClassName,e)}}hw.ClassName="FGMatMulBlock",z(hw.ClassName,hw);class cw extends BO{constructor(e){super(UM,UM,(e=>new PM(~e.value)),cw.ClassName,e)}}cw.ClassName="FGBitwiseNotBlock",z(cw.ClassName,cw);class uw extends LO{constructor(e){super(UM,UM,UM,((e,t)=>new PM(e.value&t.value)),uw.ClassName,e)}}uw.ClassName="FGBitwiseAndBlock",z(uw.ClassName,uw);class dw extends LO{constructor(e){super(UM,UM,UM,((e,t)=>new PM(e.value|t.value)),dw.ClassName,e)}}dw.ClassName="FGBitwiseOrBlock",z(dw.ClassName,dw);class _w extends LO{constructor(e){super(UM,UM,UM,((e,t)=>new PM(e.value^t.value)),_w.ClassName,e)}}_w.ClassName="FGBitwiseXorBlock",z(_w.ClassName,_w);class pw extends LO{constructor(e){super(UM,UM,UM,((e,t)=>new PM(e.value<new PM(e.value>>t.value)),fw.ClassName,e)}}fw.ClassName="FGBitwiseRightShiftBlock",z(fw.ClassName,fw);class mw extends BO{constructor(e){super(UM,UM,(e=>new PM(Math.clz32(e.value))),mw.ClassName,e)}}mw.ClassName="FGCountLeadingZerosBlock",z(mw.ClassName,mw);class gw extends BO{constructor(e){super(UM,UM,(e=>new PM(e.value?31-Math.clz32(e.value&-e.value):32)),gw.ClassName,e)}}gw.ClassName="FGCountTrailingZerosBlock",z(gw.ClassName,gw);class vw extends BO{constructor(e){super(UM,UM,(e=>new PM(function(e){let t=0;for(;e;)t+=1&e,e>>=1;return t}(e.value))),vw.ClassName,e)}}vw.ClassName="FGCountOneBitsBlock",z(vw.ClassName,vw);class xw extends qM{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const t=e.configuration.scene.onReadyObservable.add((()=>{this._execute(e)}));e._setExecutionVariable(this,"sceneReadyObserver",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return xw.ClassName}}xw.ClassName="FGSceneReadyEventBlock",z("FGSceneReadyEventBlock",xw);class bw extends qM{constructor(e){super(e),this.config=e;for(let e=0;e{for(let i=0;i{this._execute(e)}));e._setExecutionVariable(this,"sceneBeforeRender",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return Tw.ClassName}}Tw.ClassName="FGSceneTickEventBlock",z(Tw.ClassName,Tw);class yw{constructor(e,t=yw.UNITMODE_PIXEL,i=!0){this.negativeValueAllowed=i,this._value=1,this._unit=yw.UNITMODE_PIXEL,this.ignoreAdaptiveScaling=!1,this.onChangedObservable=new K,this._value=e,this._unit=t,this._originalUnit=t}get isPercentage(){return this._unit===yw.UNITMODE_PERCENTAGE}get isPixel(){return this._unit===yw.UNITMODE_PIXEL}get internalValue(){return this._value}get value(){return this._value}set value(e){e!==this._value&&(this._value=e,this.onChangedObservable.notifyObservers())}get unit(){return this._unit}set unit(e){e!==this._unit&&(this._unit=e,this.onChangedObservable.notifyObservers())}getValueInPixel(e,t){return this.isPixel?this.getValue(e):this.getValue(e)*t}updateInPlace(e,t=yw.UNITMODE_PIXEL){return this.value===e&&this.unit===t||(this._value=e,this._unit=t,this.onChangedObservable.notifyObservers()),this}getValue(e){if(e&&!this.ignoreAdaptiveScaling&&this.unit!==yw.UNITMODE_PERCENTAGE){let t=0,i=0;if(e.idealWidth&&(t=Math.ceil(this._value*e.getSize().width/e.idealWidth)),e.idealHeight&&(i=Math.ceil(this._value*e.getSize().height/e.idealHeight)),e.useSmallestIdeal&&e.idealWidth&&e.idealHeight)return window.innerWidth{this._markAsDirty(),this._resetFontCache()}))),this._markAsDirty(),this._resetFontCache()}get _isFontSizeInPercentage(){return this._fontSize.isPercentage}get fontSizeInPixels(){const e=this._style?this._style._fontSize:this._fontSize;return e.isPixel?e.getValue(this._host):e.getValueInPixel(this._host,this._tempParentMeasure.height||this._cachedParentMeasure.height)}set fontSizeInPixels(e){isNaN(e)||(this.fontSize=e+"px")}get fontSize(){return this._fontSize.toString(this._host)}set fontSize(e){this._fontSize.toString(this._host)!==e&&this._fontSize.fromString(e)&&(this._markAsDirty(),this._resetFontCache())}get color(){return this._color}set color(e){this._color!==e&&(this._color=e,this._markAsDirty())}get gradient(){return this._gradient}set gradient(e){this._gradient!==e&&(this._gradient=e,this._markAsDirty())}get zIndex(){return this._zIndex}set zIndex(e){this.zIndex!==e&&(this._zIndex=e,this.parent&&this.parent._reOrderControl(this))}get notRenderable(){return this._doNotRender}set notRenderable(e){this._doNotRender!==e&&(this._doNotRender=e,this._markAsDirty())}get isVisible(){return this._isVisible}set isVisible(e){this._isVisible!==e&&(this._isVisible=e,this._markAsDirty(!0),this.onIsVisibleChangedObservable.notifyObservers(e))}get isDirty(){return this._isDirty}get linkedMesh(){return this._linkedMesh}get descendantsOnlyPadding(){return this._descendantsOnlyPadding}set descendantsOnlyPadding(e){this._descendantsOnlyPadding!==e&&(this._descendantsOnlyPadding=e,this._markAsDirty())}get paddingLeft(){return this._paddingLeft.toString(this._host)}set paddingLeft(e){this._paddingLeft.fromString(e)&&this._markAsDirty()}get paddingLeftInPixels(){return this._paddingLeft.getValueInPixel(this._host,this._cachedParentMeasure.width)}set paddingLeftInPixels(e){isNaN(e)||(this.paddingLeft=e+"px")}get _paddingLeftInPixels(){return this._descendantsOnlyPadding?0:this.paddingLeftInPixels}get paddingRight(){return this._paddingRight.toString(this._host)}set paddingRight(e){this._paddingRight.fromString(e)&&this._markAsDirty()}get paddingRightInPixels(){return this._paddingRight.getValueInPixel(this._host,this._cachedParentMeasure.width)}set paddingRightInPixels(e){isNaN(e)||(this.paddingRight=e+"px")}get _paddingRightInPixels(){return this._descendantsOnlyPadding?0:this.paddingRightInPixels}get paddingTop(){return this._paddingTop.toString(this._host)}set paddingTop(e){this._paddingTop.fromString(e)&&this._markAsDirty()}get paddingTopInPixels(){return this._paddingTop.getValueInPixel(this._host,this._cachedParentMeasure.height)}set paddingTopInPixels(e){isNaN(e)||(this.paddingTop=e+"px")}get _paddingTopInPixels(){return this._descendantsOnlyPadding?0:this.paddingTopInPixels}get paddingBottom(){return this._paddingBottom.toString(this._host)}set paddingBottom(e){this._paddingBottom.fromString(e)&&this._markAsDirty()}get paddingBottomInPixels(){return this._paddingBottom.getValueInPixel(this._host,this._cachedParentMeasure.height)}set paddingBottomInPixels(e){isNaN(e)||(this.paddingBottom=e+"px")}get _paddingBottomInPixels(){return this._descendantsOnlyPadding?0:this.paddingBottomInPixels}get left(){return this._left.toString(this._host)}set left(e){this._left.fromString(e)&&this._markAsDirty()}get leftInPixels(){return this._left.getValueInPixel(this._host,this._cachedParentMeasure.width)}set leftInPixels(e){isNaN(e)||(this.left=e+"px")}get top(){return this._top.toString(this._host)}set top(e){this._top.fromString(e)&&this._markAsDirty()}get topInPixels(){return this._top.getValueInPixel(this._host,this._cachedParentMeasure.height)}set topInPixels(e){isNaN(e)||(this.top=e+"px")}get linkOffsetX(){return this._linkOffsetX.toString(this._host)}set linkOffsetX(e){this._linkOffsetX.fromString(e)&&this._markAsDirty()}get linkOffsetXInPixels(){return this._linkOffsetX.getValueInPixel(this._host,this._cachedParentMeasure.width)}set linkOffsetXInPixels(e){isNaN(e)||(this.linkOffsetX=e+"px")}get linkOffsetY(){return this._linkOffsetY.toString(this._host)}set linkOffsetY(e){this._linkOffsetY.fromString(e)&&this._markAsDirty()}get linkOffsetYInPixels(){return this._linkOffsetY.getValueInPixel(this._host,this._cachedParentMeasure.height)}set linkOffsetYInPixels(e){isNaN(e)||(this.linkOffsetY=e+"px")}get centerX(){return this._currentMeasure.left+this._currentMeasure.width/2}get centerY(){return this._currentMeasure.top+this._currentMeasure.height/2}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled===e)return;this._isEnabled=e,this._markAsDirty();const t=e=>{if(e.host){for(const t in e.host._lastControlOver)e===this.host._lastControlOver[t]&&(e._onPointerOut(e,null,!0),delete e.host._lastControlOver[t]);void 0!==e.children&&e.children.forEach(t)}};t(this),this.onEnabledStateChangedObservable.notifyObservers(e)}get disabledColor(){return this._disabledColor}set disabledColor(e){this._disabledColor!==e&&(this._disabledColor=e,this._markAsDirty())}get disabledColorItem(){return this._disabledColorItem}set disabledColorItem(e){this._disabledColorItem!==e&&(this._disabledColorItem=e,this._markAsDirty())}constructor(e){this.name=e,this._alpha=1,this._alphaSet=!1,this._zIndex=0,this._currentMeasure=Pw.Empty(),this._tempPaddingMeasure=Pw.Empty(),this._fontFamily="",this._fontStyle="",this._fontWeight="",this._fontSize=new yw(18,yw.UNITMODE_PIXEL,!1),this._width=new yw(1,yw.UNITMODE_PERCENTAGE,!1),this._height=new yw(1,yw.UNITMODE_PERCENTAGE,!1),this._color="",this._style=null,this._horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_CENTER,this._verticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,this._isDirty=!0,this._wasDirty=!1,this._tempParentMeasure=Pw.Empty(),this._prevCurrentMeasureTransformedIntoGlobalSpace=Pw.Empty(),this._cachedParentMeasure=Pw.Empty(),this._descendantsOnlyPadding=!1,this._paddingLeft=new yw(0),this._paddingRight=new yw(0),this._paddingTop=new yw(0),this._paddingBottom=new yw(0),this._left=new yw(0),this._top=new yw(0),this._scaleX=1,this._scaleY=1,this._rotation=0,this._transformCenterX=.5,this._transformCenterY=.5,this._transformMatrix=Rw.Identity(),this._invertTransformMatrix=Rw.Identity(),this._transformedPosition=de.Zero(),this._isMatrixDirty=!0,this._isVisible=!0,this._isHighlighted=!1,this._highlightColor="#4affff",this._highlightLineWidth=2,this._fontSet=!1,this._dummyVector2=de.Zero(),this._downCount=0,this._enterCount=-1,this._doNotRender=!1,this._downPointerIds={},this._evaluatedMeasure=new Pw(0,0,0,0),this._evaluatedParentMeasure=new Pw(0,0,0,0),this._isEnabled=!0,this._disabledColor="#9a9a9a",this._disabledColorItem="#6a6a6a",this._isReadOnly=!1,this._gradient=null,this._rebuildLayout=!1,this.onEnabledStateChangedObservable=new K,this._customData={},this._isClipped=!1,this._automaticSize=!1,this.metadata=null,this.isHitTestVisible=!0,this.isPointerBlocker=!1,this.isFocusInvisible=!1,this._clipChildren=!0,this._clipContent=!0,this.useBitmapCache=!1,this._shadowOffsetX=0,this._shadowOffsetY=0,this._shadowBlur=0,this._previousShadowBlur=0,this._shadowColor="black",this.hoverCursor="",this._linkOffsetX=new yw(0),this._linkOffsetY=new yw(0),this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new K,this.onWheelObservable=new K,this.onPointerMoveObservable=new K,this.onPointerOutObservable=new K,this.onPointerDownObservable=new K,this.onPointerUpObservable=new K,this.onPointerClickObservable=new K,this.onPointerEnterObservable=new K,this.onDirtyObservable=new K,this.onBeforeDrawObservable=new K,this.onAfterDrawObservable=new K,this.onDisposeObservable=new K,this.onIsVisibleChangedObservable=new K,this.isSerializable=!0,this._fixedRatio=0,this._fixedRatioMasterIsWidth=!0,this.animations=null,this._tmpMeasureA=new Pw(0,0,0,0)}_getTypeName(){return"Control"}getAscendantOfClass(e){return this.parent?this.parent.getClassName()===e?this.parent:this.parent.getAscendantOfClass(e):null}markAsDirty(e=!1){this._markAsDirty(e)}markAllAsDirty(){this._markAllAsDirty()}_resetFontCache(){this._fontSet=!0,this._markAsDirty()}isAscendant(e){return!!this.parent&&(this.parent===e||this.parent.isAscendant(e))}getLocalCoordinates(e){const t=de.Zero();return this.getLocalCoordinatesToRef(e,t),t}getLocalCoordinatesToRef(e,t){return t.x=e.x-this._currentMeasure.left,t.y=e.y-this._currentMeasure.top,this}getParentLocalCoordinates(e){const t=de.Zero();return t.x=e.x-this._cachedParentMeasure.left,t.y=e.y-this._cachedParentMeasure.top,t}moveToVector3(e,t){if(!this._host||this.parent!==this._host._rootContainer)return void Ds.Error("Cannot move a control to a vector3 if the control is not at root level");this.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP;const i=this._host._getGlobalViewport(),s=_e.Project(e,me.IdentityReadOnly,t.getTransformMatrix(),i);this._moveToProjectedPosition(s),s.z<0||s.z>1?this.notRenderable=!0:this.notRenderable=!1}getDescendantsToRef(e,t=!1,i){}getDescendants(e,t){const i=[];return this.getDescendantsToRef(i,e,t),i}linkWithMesh(e){if(!this._host||this.parent&&this.parent!==this._host._rootContainer)return void(e&&Ds.Error("Cannot link a control to a mesh if the control is not at root level"));const t=this._host._linkedControls.indexOf(this);if(-1!==t)return this._linkedMesh=e,void(e||this._host._linkedControls.splice(t,1));e&&(this.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,this._linkedMesh=e,this._host._linkedControls.push(this))}setPadding(e,t,i,s){const r=e,n=t??r,o=i??r,a=s??n;this.paddingTop=r,this.paddingRight=n,this.paddingBottom=o,this.paddingLeft=a}setPaddingInPixels(e,t,i,s){const r=e,n=t??r,o=i??r,a=s??n;this.paddingTopInPixels=r,this.paddingRightInPixels=n,this.paddingBottomInPixels=o,this.paddingLeftInPixels=a}_moveToProjectedPosition(e){const t=this._left.getValue(this._host),i=this._top.getValue(this._host),s=this.parent?._currentMeasure;s&&this._processMeasures(s,this._host.getContext());let r=e.x+this._linkOffsetX.getValue(this._host)-this._currentMeasure.width/2,n=e.y+this._linkOffsetY.getValue(this._host)-this._currentMeasure.height/2;const o=this._left.ignoreAdaptiveScaling&&this._top.ignoreAdaptiveScaling;o&&(Math.abs(r-t)<.5&&(r=t),Math.abs(n-i)<.5&&(n=i)),(o||t!==r||i!==n)&&(this.left=r+"px",this.top=n+"px",this._left.ignoreAdaptiveScaling=!0,this._top.ignoreAdaptiveScaling=!0,this._markAsDirty())}_offsetLeft(e){this._isDirty=!0,this._currentMeasure.left+=e}_offsetTop(e){this._isDirty=!0,this._currentMeasure.top+=e}_markMatrixAsDirty(){this._isMatrixDirty=!0,this._flagDescendantsAsMatrixDirty()}_flagDescendantsAsMatrixDirty(){}_intersectsRect(e,t){return this._transform(t),!(this._evaluatedMeasure.left>=e.left+e.width||this._evaluatedMeasure.top>=e.top+e.height||this._evaluatedMeasure.left+this._evaluatedMeasure.width<=e.left||this._evaluatedMeasure.top+this._evaluatedMeasure.height<=e.top)}_computeAdditionalOffsetX(){return 0}_computeAdditionalOffsetY(){return 0}invalidateRect(){if(this._transform(),this.host&&this.host.useInvalidateRectOptimization){this._currentMeasure.transformToRef(this._transformMatrix,this._tmpMeasureA),Pw.CombineToRef(this._tmpMeasureA,this._prevCurrentMeasureTransformedIntoGlobalSpace,this._tmpMeasureA);const e=this.shadowOffsetX,t=this.shadowOffsetY,i=Math.max(this._previousShadowBlur,this.shadowBlur),s=Math.min(Math.min(e,0)-2*i,0),r=Math.max(Math.max(e,0)+2*i,0),n=Math.min(Math.min(t,0)-2*i,0),o=Math.max(Math.max(t,0)+2*i,0),a=this._computeAdditionalOffsetX(),l=this._computeAdditionalOffsetY();this.host.invalidateRect(Math.floor(this._tmpMeasureA.left+s-a),Math.floor(this._tmpMeasureA.top+n-l),Math.ceil(this._tmpMeasureA.left+this._tmpMeasureA.width+r+a),Math.ceil(this._tmpMeasureA.top+this._tmpMeasureA.height+o+l))}}_markAsDirty(e=!1){(this._isVisible||e)&&(this._isDirty=!0,this._markMatrixAsDirty(),this._host&&this._host.markAsDirty())}_markAllAsDirty(){this._markAsDirty(),this._font&&this._prepareFont()}_link(e){this._host=e,this._host&&(this.uniqueId=this._host.getScene().getUniqueId())}_transform(e){if(!this._isMatrixDirty&&1===this._scaleX&&1===this._scaleY&&0===this._rotation)return;const t=this._currentMeasure.width*this._transformCenterX+this._currentMeasure.left,i=this._currentMeasure.height*this._transformCenterY+this._currentMeasure.top;e&&(e.translate(t,i),e.rotate(this._rotation),e.scale(this._scaleX,this._scaleY),e.translate(-t,-i)),(this._isMatrixDirty||this._cachedOffsetX!==t||this._cachedOffsetY!==i)&&(this._cachedOffsetX=t,this._cachedOffsetY=i,this._isMatrixDirty=!1,this._flagDescendantsAsMatrixDirty(),Rw.ComposeToRef(-t,-i,this._rotation,this._scaleX,this._scaleY,this.parent?this.parent._transformMatrix:null,this._transformMatrix),this._transformMatrix.invertToRef(this._invertTransformMatrix),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure))}_renderHighlight(e){this.isHighlighted&&(e.save(),e.strokeStyle=this._highlightColor,e.lineWidth=this._highlightLineWidth,this._renderHighlightSpecific(e),e.restore())}_renderHighlightSpecific(e){e.strokeRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)}_getColor(e){return this.gradient?this.gradient.getCanvasGradient(e):this.color}_applyStates(e){this._isFontSizeInPercentage&&(this._fontSet=!0),this._host&&this._host.useSmallestIdeal&&!this._font&&(this._fontSet=!0),this._fontSet&&(this._prepareFont(),this._fontSet=!1),this._font&&(e.font=this._font),(this._color||this.gradient)&&(e.fillStyle=this._getColor(e)),Ow.AllowAlphaInheritance?e.globalAlpha*=this._alpha:this._alphaSet&&(e.globalAlpha=this.parent&&!this.parent.renderToIntermediateTexture?this.parent.alpha*this._alpha:this._alpha)}_layout(e,t){if(!this.isDirty&&(!this.isVisible||this.notRenderable))return!1;if(this._isDirty||!this._cachedParentMeasure.isEqualsTo(e)){this.host._numLayoutCalls++,this._currentMeasure.addAndTransformToRef(this._transformMatrix,0|-this._paddingLeftInPixels,0|-this._paddingTopInPixels,0|this._paddingRightInPixels,0|this._paddingBottomInPixels,this._prevCurrentMeasureTransformedIntoGlobalSpace),t.save(),this._applyStates(t);let i=0;do{this._rebuildLayout=!1,this._processMeasures(e,t),i++}while(this._rebuildLayout&&i<3);i>=3&&Ne.Error(`Layout cycle detected in GUI (Control name=${this.name}, uniqueId=${this.uniqueId})`),t.restore(),this.invalidateRect(),this._evaluateClippingState(e)}return this._wasDirty=this._isDirty,this._isDirty=!1,!0}_processMeasures(e,t){this._tempPaddingMeasure.copyFrom(e),this.parent&&this.parent.descendantsOnlyPadding&&(this._tempPaddingMeasure.left+=this.parent.paddingLeftInPixels,this._tempPaddingMeasure.top+=this.parent.paddingTopInPixels,this._tempPaddingMeasure.width-=this.parent.paddingLeftInPixels+this.parent.paddingRightInPixels,this._tempPaddingMeasure.height-=this.parent.paddingTopInPixels+this.parent.paddingBottomInPixels),this._currentMeasure.copyFrom(this._tempPaddingMeasure),this._preMeasure(this._tempPaddingMeasure,t),this._measure(),this._postMeasure(this._tempPaddingMeasure,t),this._computeAlignment(this._tempPaddingMeasure,t),this._currentMeasure.left=0|this._currentMeasure.left,this._currentMeasure.top=0|this._currentMeasure.top,this._currentMeasure.width=0|this._currentMeasure.width,this._currentMeasure.height=0|this._currentMeasure.height,this._additionalProcessing(this._tempPaddingMeasure,t),this._cachedParentMeasure.copyFrom(this._tempPaddingMeasure),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure),this.onDirtyObservable.hasObservers()&&this.onDirtyObservable.notifyObservers(this)}_evaluateClippingState(e){if(this._transform(),this._currentMeasure.transformToRef(this._transformMatrix,this._evaluatedMeasure),this.parent&&this.parent.clipChildren){if(e.transformToRef(this.parent._transformMatrix,this._evaluatedParentMeasure),this._evaluatedMeasure.left>this._evaluatedParentMeasure.left+this._evaluatedParentMeasure.width)return void(this._isClipped=!0);if(this._evaluatedMeasure.left+this._evaluatedMeasure.widththis._evaluatedParentMeasure.top+this._evaluatedParentMeasure.height)return void(this._isClipped=!0);if(this._evaluatedMeasure.top+this._evaluatedMeasure.heightthis._currentMeasure.left+this._currentMeasure.width||tthis._currentMeasure.top+this._currentMeasure.height||(this.isPointerBlocker&&(this._host._shouldBlockPointer=!0),0))}_processPicking(e,t,i,s,r,n,o,a){return!(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this._doNotRender||!this.contains(e,t)||(this._processObservables(s,e,t,i,r,n,o,a),0))}_onPointerMove(e,t,i,s){this.onPointerMoveObservable.notifyObservers(t,-1,e,this,s)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerMove(e,t,i,s)}_onPointerEnter(e,t){return!!this._isEnabled&&(!(this._enterCount>0)&&(-1===this._enterCount&&(this._enterCount=0),this._enterCount++,this.onPointerEnterObservable.notifyObservers(this,-1,e,this,t)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerEnter(e,t),!0))}_onPointerOut(e,t,i=!1){if(!(i||this._isEnabled&&e!==this))return;this._enterCount=0;let s=!0;e.isAscendant(this)||(s=this.onPointerOutObservable.notifyObservers(this,-1,e,this,t)),s&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerOut(e,t,i)}_onPointerDown(e,t,i,s,r){return this._onPointerEnter(this,r),0===this._downCount&&(this._downCount++,this._downPointerIds[i]=!0,this.onPointerDownObservable.notifyObservers(new Iw(t,s),-1,e,this,r)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerDown(e,t,i,s,r),r&&this.uniqueId!==this._host.rootContainer.uniqueId&&this._host._capturedPointerIds.add(r.event.pointerId),!0)}_onPointerUp(e,t,i,s,r,n){if(!this._isEnabled)return;this._downCount=0,delete this._downPointerIds[i];let o=r;r&&(this._enterCount>0||-1===this._enterCount)&&(o=this.onPointerClickObservable.notifyObservers(new Iw(t,s),-1,e,this,n)),this.onPointerUpObservable.notifyObservers(new Iw(t,s),-1,e,this,n)&&null!=this.parent&&!this.isPointerBlocker&&this.parent._onPointerUp(e,t,i,s,o,n),n&&this.uniqueId!==this._host.rootContainer.uniqueId&&this._host._capturedPointerIds.delete(n.event.pointerId)}_forcePointerUp(e=null){if(null!==e)this._onPointerUp(this,de.Zero(),e,0,!0);else for(const e in this._downPointerIds)this._onPointerUp(this,de.Zero(),+e,0,!0)}_onWheelScroll(e,t){this._isEnabled&&this.onWheelObservable.notifyObservers(new de(e,t))&&null!=this.parent&&this.parent._onWheelScroll(e,t)}_onCanvasBlur(){}_processObservables(e,t,i,s,r,n,o,a){if(!this._isEnabled)return!1;if(this._dummyVector2.copyFromFloats(t,i),e===lr.POINTERMOVE){this._onPointerMove(this,this._dummyVector2,r,s);const e=this._host._lastControlOver[r];return e&&e!==this&&e._onPointerOut(this,s),e!==this&&this._onPointerEnter(this,s),this._host._lastControlOver[r]=this,!0}return e===lr.POINTERDOWN?(this._onPointerDown(this,this._dummyVector2,r,n,s),this._host._registerLastControlDown(this,r),this._host._lastPickedControl=this,!0):e===lr.POINTERUP?(this._host._lastControlDown[r]&&this._host._lastControlDown[r]._onPointerUp(this,this._dummyVector2,r,n,!0,s),delete this._host._lastControlDown[r],!0):!(e!==lr.POINTERWHEEL||!this._host._lastControlOver[r]||(this._host._lastControlOver[r]._onWheelScroll(o,a),0))}_getStyleProperty(e,t){const i=(this._style&&this._style[e])??this[e];return!i&&this.parent?this.parent._getStyleProperty(e,t):this.parent?i:t}_prepareFont(){(this._font||this._fontSet)&&(this._font=this._getStyleProperty("fontStyle","")+" "+this._getStyleProperty("fontWeight","")+" "+this.fontSizeInPixels+"px "+this._getStyleProperty("fontFamily","Arial"),this._fontOffset=Ow._GetFontOffset(this._font,this._host?.getScene()?.getEngine()),this.getDescendants().forEach((e=>e._markAllAsDirty())))}isDimensionFullyDefined(e){return this.getDimension(e).isPixel}getDimension(e){return"width"===e?this._width:this._height}clone(e){const t={};this.serialize(t,!0);const i=new(Ds.Instantiate("BABYLON.GUI."+t.className));return i.parse(t,e),i}parse(e,t,i){return this._urlRewriter=i,St.Parse((()=>this),e,null),this.name=e.name,this._parseFromContent(e,t??this._host),this}serialize(e,t=!1,i=!0){(this.isSerializable||t)&&(St.Serialize(this,e),e.name=this.name,e.className=this.getClassName(),i&&this._prepareFont(),this._fontFamily&&(e.fontFamily=this._fontFamily),this.fontSize&&(e.fontSize=this.fontSize),this.fontWeight&&(e.fontWeight=this.fontWeight),this.fontStyle&&(e.fontStyle=this.fontStyle),this._gradient&&(e.gradient={},this._gradient.serialize(e.gradient)),St.AppendSerializedAnimations(this,e))}_parseFromContent(e,t,i){if(e.fontFamily&&(this.fontFamily=e.fontFamily),e.fontSize&&(this.fontSize=e.fontSize),e.fontWeight&&(this.fontWeight=e.fontWeight),e.fontStyle&&(this.fontStyle=e.fontStyle),e.gradient){const t=Ds.Instantiate("BABYLON.GUI."+e.gradient.className);this._gradient=new t,this._gradient?.parse(e.gradient)}if(e.animations){this.animations=[];for(let t=0;t-1&&this.linkWithMesh(null),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear()}static get HORIZONTAL_ALIGNMENT_LEFT(){return Ow._HORIZONTAL_ALIGNMENT_LEFT}static get HORIZONTAL_ALIGNMENT_RIGHT(){return Ow._HORIZONTAL_ALIGNMENT_RIGHT}static get HORIZONTAL_ALIGNMENT_CENTER(){return Ow._HORIZONTAL_ALIGNMENT_CENTER}static get VERTICAL_ALIGNMENT_TOP(){return Ow._VERTICAL_ALIGNMENT_TOP}static get VERTICAL_ALIGNMENT_BOTTOM(){return Ow._VERTICAL_ALIGNMENT_BOTTOM}static get VERTICAL_ALIGNMENT_CENTER(){return Ow._VERTICAL_ALIGNMENT_CENTER}static _GetFontOffset(e,t){if(Ow._FontHeightSizes[e])return Ow._FontHeightSizes[e];const i=t||re.LastCreatedEngine;if(!i)throw new Error("Invalid engine. Unable to create a canvas.");const s=i.getFontOffset(e);return Ow._FontHeightSizes[e]=s,s}static Parse(e,t,i){const s=Ds.Instantiate("BABYLON.GUI."+e.className),r=St.Parse((()=>{const e=new s;return e._urlRewriter=i,e}),e,null);return r.name=e.name,r._parseFromContent(e,t,i),r}static drawEllipse(e,t,i,s,r){r.translate(e,t),r.scale(i,s),r.beginPath(),r.arc(0,0,1,0,2*Math.PI),r.closePath(),r.scale(1/i,1/s),r.translate(-e,-t)}isReady(){return!0}}Ow.AllowAlphaInheritance=!1,Ow._ClipMeasure=new Pw(0,0,0,0),Ow._HORIZONTAL_ALIGNMENT_LEFT=0,Ow._HORIZONTAL_ALIGNMENT_RIGHT=1,Ow._HORIZONTAL_ALIGNMENT_CENTER=2,Ow._VERTICAL_ALIGNMENT_TOP=0,Ow._VERTICAL_ALIGNMENT_BOTTOM=1,Ow._VERTICAL_ALIGNMENT_CENTER=2,Ow._FontHeightSizes={},Ow.AddHeader=()=>{},Ze([rt()],Ow.prototype,"metadata",void 0),Ze([rt()],Ow.prototype,"isHitTestVisible",void 0),Ze([rt()],Ow.prototype,"isPointerBlocker",void 0),Ze([rt()],Ow.prototype,"isFocusInvisible",void 0),Ze([rt()],Ow.prototype,"clipChildren",null),Ze([rt()],Ow.prototype,"clipContent",null),Ze([rt()],Ow.prototype,"useBitmapCache",void 0),Ze([rt()],Ow.prototype,"shadowOffsetX",null),Ze([rt()],Ow.prototype,"shadowOffsetY",null),Ze([rt()],Ow.prototype,"shadowBlur",null),Ze([rt()],Ow.prototype,"shadowColor",null),Ze([rt()],Ow.prototype,"hoverCursor",void 0),Ze([rt()],Ow.prototype,"fontOffset",null),Ze([rt()],Ow.prototype,"alpha",null),Ze([rt()],Ow.prototype,"isSerializable",void 0),Ze([rt()],Ow.prototype,"scaleX",null),Ze([rt()],Ow.prototype,"scaleY",null),Ze([rt()],Ow.prototype,"rotation",null),Ze([rt()],Ow.prototype,"transformCenterY",null),Ze([rt()],Ow.prototype,"transformCenterX",null),Ze([rt()],Ow.prototype,"horizontalAlignment",null),Ze([rt()],Ow.prototype,"verticalAlignment",null),Ze([rt()],Ow.prototype,"fixedRatio",null),Ze([rt()],Ow.prototype,"fixedRatioMasterIsWidth",null),Ze([rt()],Ow.prototype,"width",null),Ze([rt()],Ow.prototype,"height",null),Ze([rt()],Ow.prototype,"style",null),Ze([rt()],Ow.prototype,"color",null),Ze([rt()],Ow.prototype,"gradient",null),Ze([rt()],Ow.prototype,"zIndex",null),Ze([rt()],Ow.prototype,"notRenderable",null),Ze([rt()],Ow.prototype,"isVisible",null),Ze([rt()],Ow.prototype,"descendantsOnlyPadding",null),Ze([rt()],Ow.prototype,"paddingLeft",null),Ze([rt()],Ow.prototype,"paddingRight",null),Ze([rt()],Ow.prototype,"paddingTop",null),Ze([rt()],Ow.prototype,"paddingBottom",null),Ze([rt()],Ow.prototype,"left",null),Ze([rt()],Ow.prototype,"top",null),Ze([rt()],Ow.prototype,"linkOffsetX",null),Ze([rt()],Ow.prototype,"linkOffsetY",null),Ze([rt()],Ow.prototype,"isEnabled",null),Ze([rt()],Ow.prototype,"disabledColor",null),Ze([rt()],Ow.prototype,"disabledColorItem",null),Ze([rt()],Ow.prototype,"overlapGroup",void 0),Ze([rt()],Ow.prototype,"overlapDeltaMultiplier",void 0),z("BABYLON.GUI.Control",Ow);class Dw extends Ow{get renderToIntermediateTexture(){return this._renderToIntermediateTexture}set renderToIntermediateTexture(e){this._renderToIntermediateTexture!==e&&(this._renderToIntermediateTexture=e,this._markAsDirty())}get adaptHeightToChildren(){return this._adaptHeightToChildren}set adaptHeightToChildren(e){this._adaptHeightToChildren!==e&&(this._adaptHeightToChildren=e,e&&(this.height="100%"),this._markAsDirty())}get adaptWidthToChildren(){return this._adaptWidthToChildren}set adaptWidthToChildren(e){this._adaptWidthToChildren!==e&&(this._adaptWidthToChildren=e,e&&(this.width="100%"),this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get backgroundGradient(){return this._backgroundGradient}set backgroundGradient(e){this._backgroundGradient!==e&&(this._backgroundGradient=e,this._markAsDirty())}get children(){return this._children}get isReadOnly(){return this._isReadOnly}set isReadOnly(e){this._isReadOnly=e;for(const t of this._children)t.isReadOnly=e}constructor(e){super(e),this.name=e,this._children=new Array,this._measureForChildren=Pw.Empty(),this._background="",this._backgroundGradient=null,this._adaptWidthToChildren=!1,this._adaptHeightToChildren=!1,this._renderToIntermediateTexture=!1,this._intermediateTexture=null,this.delegatePickingToChildren=!1,this.logLayoutCycleErrors=!1,this.maxLayoutCycle=3,this.onControlAddedObservable=new K,this.onControlRemovedObservable=new K,this._inverseTransformMatrix=Rw.Identity(),this._inverseMeasure=new Pw(0,0,0,0)}_getTypeName(){return"Container"}_flagDescendantsAsMatrixDirty(){for(const e of this.children)e._isClipped=!1,e._markMatrixAsDirty()}getChildByName(e){for(const t of this.children)if(t.name===e)return t;return null}getChildByType(e,t){for(const e of this.children)if(e.typeName===t)return e;return null}containsControl(e){return-1!==this.children.indexOf(e)}addControl(e){return e?(-1!==this._children.indexOf(e)||(e._link(this._host),e._markAllAsDirty(),this._reOrderControl(e),this._markAsDirty(),this.onControlAddedObservable.notifyObservers(e)),this):this}clearControls(){const e=this.children.slice();for(const t of e)this.removeControl(t);return this}removeControl(e){const t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e.parent=null),e.linkWithMesh(null),this._host&&this._host._cleanControlAfterRemoval(e),this._markAsDirty(),this.onControlRemovedObservable.notifyObservers(e),this}_reOrderControl(e){const t=e.linkedMesh;this.removeControl(e);let i=!1;for(let t=0;te.zIndex){this._children.splice(t,0,e),i=!0;break}i||this._children.push(e),e.parent=this,t&&e.linkWithMesh(t),this._markAsDirty()}_offsetLeft(e){super._offsetLeft(e);for(const t of this._children)t._offsetLeft(e)}_offsetTop(e){super._offsetTop(e);for(const t of this._children)t._offsetTop(e)}_markAllAsDirty(){super._markAllAsDirty();for(let e=0;e=0&&(s+=this.paddingLeftInPixels+this.paddingRightInPixels,this.width!==s+"px"&&(this.parent?._markAsDirty(),this.width=s+"px",this._width.ignoreAdaptiveScaling=!0,this._rebuildLayout=!0)),this.adaptHeightToChildren&&r>=0&&(r+=this.paddingTopInPixels+this.paddingBottomInPixels,this.height!==r+"px"&&(this.parent?._markAsDirty(),this.height=r+"px",this._height.ignoreAdaptiveScaling=!0,this._rebuildLayout=!0)),this._postMeasure()}i++}while(this._rebuildLayout&&i=3&&this.logLayoutCycleErrors&&Ne.Error(`Layout cycle detected in GUI (Container name=${this.name}, uniqueId=${this.uniqueId})`),t.restore(),this._isDirty&&(this.invalidateRect(),this._isDirty=!1),!0}_postMeasure(){}_draw(e,t){const i=this._renderToIntermediateTexture&&this._intermediateTexture,s=i?this._intermediateTexture.getContext():e;i&&(s.save(),s.translate(-this._currentMeasure.left,-this._currentMeasure.top),t?(this._transformMatrix.invertToRef(this._inverseTransformMatrix),t.transformToRef(this._inverseTransformMatrix,this._inverseMeasure),s.clearRect(this._inverseMeasure.left,this._inverseMeasure.top,this._inverseMeasure.width,this._inverseMeasure.height)):s.clearRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),this._localDraw(s),e.save(),this.clipChildren&&this._clipForChildren(s);for(const e of this._children)t&&!e._intersectsRect(t)||e._render(s,t);i&&(s.restore(),e.save(),e.globalAlpha=this.alpha,e.drawImage(s.canvas,this._currentMeasure.left,this._currentMeasure.top),e.restore()),e.restore()}getDescendantsToRef(e,t=!1,i){if(this.children)for(let s=0;s=0;s--){const r=this._children[s];if(r.isEnabled&&r.isHitTestVisible&&r.isVisible&&!r.notRenderable&&r.contains(e,t)){i=!0;break}}if(!i)return!1}for(let l=this._children.length-1;l>=0;l--){const h=this._children[l];if(h._processPicking(e,t,i,s,r,n,o,a))return h.hoverCursor&&this._host._changeCursor(h.hoverCursor),!0}return!!l&&!!this.isHitTestVisible&&this._processObservables(s,e,t,i,r,n,o,a)}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.copyFrom(this._currentMeasure)}_getAdaptDimTo(e){return"width"===e?this.adaptWidthToChildren:this.adaptHeightToChildren}isDimensionFullyDefined(e){if(this._getAdaptDimTo(e)){for(const t of this.children)if(!t.isDimensionFullyDefined(e))return!1;return!0}return super.isDimensionFullyDefined(e)}serialize(e,t=!1,i=!0){if(super.serialize(e,t,i),(this.isSerializable||t)&&(this.backgroundGradient&&(e.backgroundGradient={},this.backgroundGradient.serialize(e.backgroundGradient)),this.children.length)){e.children=[];for(const s of this.children)if(s.isSerializable||t){const r={};s.serialize(r,t,i),e.children.push(r)}}}dispose(){super.dispose();for(let e=this.children.length-1;e>=0;e--)this.children[e].dispose();this._intermediateTexture?.dispose()}_parseFromContent(e,t,i){if(super._parseFromContent(e,t,i),this._link(t),e.backgroundGradient){const t=Ds.Instantiate("BABYLON.GUI."+e.backgroundGradient.className);this._backgroundGradient=new t,this._backgroundGradient?.parse(e.backgroundGradient)}if(e.children)for(const s of e.children)this.addControl(Ow.Parse(s,t,i))}isReady(){for(const e of this.children)if(!e.isReady())return!1;return!0}}Ze([rt()],Dw.prototype,"delegatePickingToChildren",void 0),Ze([rt()],Dw.prototype,"renderToIntermediateTexture",null),Ze([rt()],Dw.prototype,"maxLayoutCycle",void 0),Ze([rt()],Dw.prototype,"adaptHeightToChildren",null),Ze([rt()],Dw.prototype,"adaptWidthToChildren",null),Ze([rt()],Dw.prototype,"background",null),Ze([rt()],Dw.prototype,"backgroundGradient",null),z("BABYLON.GUI.Container",Dw);class ww extends Dw{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get cornerRadius(){return this._cornerRadius[0]}set cornerRadius(e){e<0&&(e=0),this._cornerRadius[0]===e&&this._cornerRadius[1]===e&&this._cornerRadius[2]===e&&this._cornerRadius[3]===e||(this._cornerRadius[0]=this._cornerRadius[1]=this._cornerRadius[2]=this._cornerRadius[3]=e,this._markAsDirty())}get cornerRadiusX(){return this._cornerRadius[0]}set cornerRadiusX(e){this._cornerRadius[0]!==e&&(this._cornerRadius[0]=e)}get cornerRadiusY(){return this._cornerRadius[1]}set cornerRadiusY(e){this._cornerRadius[1]!==e&&(this._cornerRadius[1]=e)}get cornerRadiusZ(){return this._cornerRadius[2]}set cornerRadiusZ(e){this._cornerRadius[2]!==e&&(this._cornerRadius[2]=e)}get cornerRadiusW(){return this._cornerRadius[3]}set cornerRadiusW(e){this._cornerRadius[3]!==e&&(this._cornerRadius[3]=e)}constructor(e){super(e),this.name=e,this._thickness=1,this._cornerRadius=[0,0,0,0],this._cachedRadius=[0,0,0,0]}_getTypeName(){return"Rectangle"}_computeAdditionalOffsetX(){let e=0;return 0===this._cornerRadius[0]&&0===this._cornerRadius[1]&&0===this._cornerRadius[2]&&0===this._cornerRadius[3]||(e+=1),this.thickness&&(e+=this.thickness/2),e}_computeAdditionalOffsetY(){let e=0;return 0===this._cornerRadius[0]&&0===this._cornerRadius[1]&&0===this._cornerRadius[2]&&0===this._cornerRadius[3]||(e+=1),this.thickness&&(e+=this.thickness/2),e}_getRectangleFill(e){return this._getBackgroundColor(e)}_localDraw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),(this._background||this._backgroundGradient)&&(e.fillStyle=this._getRectangleFill(e),0!==this._cornerRadius[0]||0!==this._cornerRadius[1]||0!==this._cornerRadius[2]||0!==this._cornerRadius[3]?(this._drawRoundedRect(e,this._thickness/2),e.fill()):e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),this._thickness&&((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),(this.color||this.gradient)&&(e.strokeStyle=this.gradient?this.gradient.getCanvasGradient(e):this.color),e.lineWidth=this._thickness,0!==this._cornerRadius[0]||0!==this._cornerRadius[1]||0!==this._cornerRadius[2]||0!==this._cornerRadius[3]?(this._drawRoundedRect(e,this._thickness/2),e.stroke()):e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness)),e.restore()}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.width-=2*this._thickness,this._measureForChildren.height-=2*this._thickness,this._measureForChildren.left+=this._thickness,this._measureForChildren.top+=this._thickness}_drawRoundedRect(e,t=0){const i=this._currentMeasure.left+t,s=this._currentMeasure.top+t,r=this._currentMeasure.width-2*t,n=this._currentMeasure.height-2*t;for(let e=0;ei&&(i=t.width)}if(this._resizeToFit){if(this._textWrapping===Nw.Clip||this._forceResizeWidth){const e=Math.ceil(this._paddingLeftInPixels)+Math.ceil(this._paddingRightInPixels)+Math.ceil(i);e!==this._width.getValueInPixel(this._host,this._tempParentMeasure.width)&&(this._width.updateInPlace(e,yw.UNITMODE_PIXEL),this._rebuildLayout=!0)}let e=this._paddingTopInPixels+this._paddingBottomInPixels+this._fontOffset.height*this._lines.length|0;if(this._lines.length>0&&0!==this._lineSpacing.internalValue){let t=0;t=this._lineSpacing.isPixel?this._lineSpacing.getValue(this._host):this._lineSpacing.getValue(this._host)*this._height.getValueInPixel(this._host,this._cachedParentMeasure.height),e+=(this._lines.length-1)*t}e!==this._height.internalValue&&(this._height.updateInPlace(e,yw.UNITMODE_PIXEL),this._rebuildLayout=!0)}}_drawText(e,t,i,s){const r=this._currentMeasure.width;let n=0;switch(this._textHorizontalAlignment){case Ow.HORIZONTAL_ALIGNMENT_LEFT:n=0;break;case Ow.HORIZONTAL_ALIGNMENT_RIGHT:n=r-t;break;case Ow.HORIZONTAL_ALIGNMENT_CENTER:n=(r-t)/2}(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(s.shadowColor=this.shadowColor,s.shadowBlur=this.shadowBlur,s.shadowOffsetX=this.shadowOffsetX,s.shadowOffsetY=this.shadowOffsetY),this.outlineWidth&&s.strokeText(e,this._currentMeasure.left+n,i),s.fillText(e,this._currentMeasure.left+n,i),this._underline&&this._drawLine(this._currentMeasure.left+n,i+3,this._currentMeasure.left+n+t,i+3,s),this._lineThrough&&this._drawLine(this._currentMeasure.left+n,i-this.fontSizeInPixels/3,this._currentMeasure.left+n+t,i-this.fontSizeInPixels/3,s)}_drawLine(e,t,i,s,r){if(r.beginPath(),r.lineWidth=Math.round(.05*this.fontSizeInPixels),r.moveTo(e,t),r.lineTo(i,s),this.outlineWidth&&this.applyOutlineToUnderline)r.stroke(),r.fill();else{const e=r.strokeStyle;r.strokeStyle=r.fillStyle,r.stroke(),r.strokeStyle=e}r.closePath()}_draw(e){e.save(),this._applyStates(e),this._renderLines(e),e.restore()}_applyStates(e){super._applyStates(e),this.outlineWidth&&(e.lineWidth=this.outlineWidth,e.strokeStyle=this.outlineColor,e.lineJoin="miter",e.miterLimit=2)}_breakLines(e,t,i){this._linesTemp.length=0;const s=this.text.split("\n");if(this._textWrapping===Nw.Ellipsis)for(const t of s)this._linesTemp.push(this._parseLineEllipsis(t,e,i));else if(this._textWrapping===Nw.WordWrap)for(const t of s)this._linesTemp.push(...this._parseLineWordWrap(t,e,i));else if(this._textWrapping===Nw.WordWrapEllipsis)for(const r of s)this._linesTemp.push(...this._parseLineWordWrapEllipsis(r,e,t,i));else for(const e of s)this._linesTemp.push(this._parseLine(e,i));return this._linesTemp}_parseLine(e="",t){return{text:e,width:this._getTextMetricsWidth(t.measureText(e))}}_getCharsToRemove(e,t,i){const s=e>t?e-t:0,r=e/i;return Math.max(Math.floor(s/r),1)}_parseLineEllipsis(e="",t,i){let s=this._getTextMetricsWidth(i.measureText(e)),r=this._getCharsToRemove(s,t,e.length);const n=Array.from&&Array.from(e);if(n)for(;n.length&&s>t;)n.splice(n.length-r,r),e=`${n.join("")}…`,s=this._getTextMetricsWidth(i.measureText(e)),r=this._getCharsToRemove(s,t,e.length);else{for(;e.length>2&&s>t;)e=e.slice(0,-r),s=this._getTextMetricsWidth(i.measureText(e+"…")),r=this._getCharsToRemove(s,t,e.length);e+="…"}return{text:e,width:s}}_getTextMetricsWidth(e){return void 0!==e.actualBoundingBoxLeft?Math.abs(e.actualBoundingBoxLeft)+Math.abs(e.actualBoundingBoxRight):e.width}_parseLineWordWrap(e="",t,i){const s=[],r=this.wordSplittingFunction?this.wordSplittingFunction(e):e.split(this._wordDivider);let n=this._getTextMetricsWidth(i.measureText(e));for(let o=0;o0?e+this._wordDivider+r[o]:r[0],l=this._getTextMetricsWidth(i.measureText(a));l>t&&o>0?(s.push({text:e,width:n}),e=r[o],n=this._getTextMetricsWidth(i.measureText(e))):(n=l,e=a)}return s.push({text:e,width:n}),s}_parseLineWordWrapEllipsis(e="",t,i,s){const r=this._parseLineWordWrap(e,t,s);for(let e=1;e<=r.length;e++)if(this._computeHeightForLinesOf(e)>i&&e>1){const i=r[e-2],n=r[e-1];r[e-2]=this._parseLineEllipsis(i.text+this._wordDivider+n.text,t,s);const o=r.length-e+1;for(let e=0;e0&&0!==this._lineSpacing.internalValue){let i=0;i=this._lineSpacing.isPixel?this._lineSpacing.getValue(this._host):this._lineSpacing.getValue(this._host)*this._height.getValueInPixel(this._host,this._cachedParentMeasure.height),t+=(e-1)*i}return t}isDimensionFullyDefined(e){return!!this.resizeToFit||super.isDimensionFullyDefined(e)}computeExpectedHeight(){if(this.text&&this.widthInPixels){const e=re.LastCreatedEngine?.createCanvas(0,0).getContext("2d");if(e){this._applyStates(e),this._fontOffset||(this._fontOffset=Ow._GetFontOffset(e.font,this._host.getScene()?.getEngine()));const t=this._lines?this._lines:this._breakLines(this.widthInPixels-this._paddingLeftInPixels-this._paddingRightInPixels,this.heightInPixels-this._paddingTopInPixels-this._paddingBottomInPixels,e);return this._computeHeightForLinesOf(t.length)}}return 0}dispose(){super.dispose(),this.onTextChangedObservable.clear()}}Ze([rt()],Fw.prototype,"resizeToFit",null),Ze([rt()],Fw.prototype,"textWrapping",null),Ze([rt()],Fw.prototype,"text",null),Ze([rt()],Fw.prototype,"textHorizontalAlignment",null),Ze([rt()],Fw.prototype,"textVerticalAlignment",null),Ze([rt()],Fw.prototype,"lineSpacing",null),Ze([rt()],Fw.prototype,"outlineWidth",null),Ze([rt()],Fw.prototype,"underline",null),Ze([rt()],Fw.prototype,"lineThrough",null),Ze([rt()],Fw.prototype,"applyOutlineToUnderline",null),Ze([rt()],Fw.prototype,"outlineColor",null),Ze([rt()],Fw.prototype,"wordDivider",null),Ze([rt()],Fw.prototype,"forceResizeWidth",null),z("BABYLON.GUI.TextBlock",Fw);class Lw extends Ow{get isLoaded(){return this._loaded}isReady(){return this.isLoaded}get detectPointerOnOpaqueOnly(){return this._detectPointerOnOpaqueOnly}set detectPointerOnOpaqueOnly(e){this._detectPointerOnOpaqueOnly!==e&&(this._detectPointerOnOpaqueOnly=e)}get sliceLeft(){return this._sliceLeft}set sliceLeft(e){this._sliceLeft!==e&&(this._sliceLeft=e,this._markAsDirty())}get sliceRight(){return this._sliceRight}set sliceRight(e){this._sliceRight!==e&&(this._sliceRight=e,this._markAsDirty())}get sliceTop(){return this._sliceTop}set sliceTop(e){this._sliceTop!==e&&(this._sliceTop=e,this._markAsDirty())}get sliceBottom(){return this._sliceBottom}set sliceBottom(e){this._sliceBottom!==e&&(this._sliceBottom=e,this._markAsDirty())}get sourceLeft(){return this._sourceLeft}set sourceLeft(e){this._sourceLeft!==e&&(this._sourceLeft=e,this._markAsDirty())}get sourceTop(){return this._sourceTop}set sourceTop(e){this._sourceTop!==e&&(this._sourceTop=e,this._markAsDirty())}get sourceWidth(){return this._sourceWidth}set sourceWidth(e){this._sourceWidth!==e&&(this._sourceWidth=e,this._markAsDirty())}get sourceHeight(){return this._sourceHeight}set sourceHeight(e){this._sourceHeight!==e&&(this._sourceHeight=e,this._markAsDirty())}get imageWidth(){return this._imageWidth}get imageHeight(){return this._imageHeight}get populateNinePatchSlicesFromImage(){return this._populateNinePatchSlicesFromImage}set populateNinePatchSlicesFromImage(e){this._populateNinePatchSlicesFromImage!==e&&(this._populateNinePatchSlicesFromImage=e,this._populateNinePatchSlicesFromImage&&this._loaded&&this._extractNinePatchSliceDataFromImage())}get isSVG(){return this._isSVG}get svgAttributesComputationCompleted(){return this._svgAttributesComputationCompleted}get autoScale(){return this._autoScale}set autoScale(e){this._autoScale!==e&&(this._autoScale=e,e&&this._loaded&&this.synchronizeSizeWithContent())}get stretch(){return this._stretch}set stretch(e){this._stretch!==e&&(this._stretch=e,this._markAsDirty())}_rotate90(e,t=!1){const i=this._domImage.width,s=this._domImage.height,r=this._host?.getScene()?.getEngine()||re.LastCreatedEngine;if(!r)throw new Error("Invalid engine. Unable to create a canvas.");const n=r.createCanvas(s,i),o=n.getContext("2d");o.translate(n.width/2,n.height/2),o.rotate(e*Math.PI/2),o.drawImage(this._domImage,0,0,i,s,-i/2,-s/2,i,s);const a=n.toDataURL("image/jpg"),l=new Lw(this.name+"rotated",a);return t&&(l._stretch=this._stretch,l._autoScale=this._autoScale,l._cellId=this._cellId,l._cellWidth=e%1?this._cellHeight:this._cellWidth,l._cellHeight=e%1?this._cellWidth:this._cellHeight),this._handleRotationForSVGImage(this,l,e),this._imageDataCache.data=null,l}_handleRotationForSVGImage(e,t,i){e._isSVG&&(e._svgAttributesComputationCompleted?(this._rotate90SourceProperties(e,t,i),this._markAsDirty()):e.onSVGAttributesComputedObservable.addOnce((()=>{this._rotate90SourceProperties(e,t,i),this._markAsDirty()})))}_rotate90SourceProperties(e,t,i){let s=e.sourceLeft,r=e.sourceTop,n=e.domImage.width,o=e.domImage.height,a=s,l=r,h=e.sourceWidth,c=e.sourceHeight;if(0!=i){const e=i<0?-1:1;i%=4;for(let t=0;t127&&-1===this._sliceLeft)this._sliceLeft=t;else if(e<127&&this._sliceLeft>-1){this._sliceRight=t;break}}this._sliceTop=-1,this._sliceBottom=-1;for(let i=0;i127&&-1===this._sliceTop)this._sliceTop=i;else if(t<127&&this._sliceTop>-1){this._sliceBottom=i;break}}}set domImage(e){this._domImage=e,this._loaded=!1,this._imageDataCache.data=null,this._domImage.width?this._onImageLoaded():this._domImage.onload=()=>{this._onImageLoaded()}}get domImage(){return this._domImage}_onImageLoaded(){this._imageDataCache.data=null,this._imageWidth=this._domImage.width,this._imageHeight=this._domImage.height,this._loaded=!0,this._populateNinePatchSlicesFromImage&&this._extractNinePatchSliceDataFromImage(),this._autoScale&&this.synchronizeSizeWithContent(),this.onImageLoadedObservable.notifyObservers(this),this._markAsDirty()}get source(){return this._source}static ResetImageCache(){Lw.SourceImgCache.clear()}_removeCacheUsage(e){const t=e&&Lw.SourceImgCache.get(e);t&&(t.timesUsed-=1,0===t.timesUsed&&Lw.SourceImgCache.delete(e))}set source(e){if(this._urlRewriter&&e&&(e=this._urlRewriter(e)),this._source===e)return;this._removeCacheUsage(this._source),this._loaded=!1,this._source=e,this._imageDataCache.data=null,e&&(e=this._svgCheck(e));const t=this._host?.getScene()?.getEngine()||re.LastCreatedEngine;if(!t)throw new Error("Invalid engine. Unable to create a canvas.");if(e&&Lw.SourceImgCache.has(e)){const t=Lw.SourceImgCache.get(e);return this._domImage=t.img,t.timesUsed+=1,void(t.loaded?this._onImageLoaded():t.waitingForLoadCallback.push(this._onImageLoaded.bind(this)))}this._domImage=t.createCanvasImage(),e&&Lw.SourceImgCache.set(e,{img:this._domImage,timesUsed:1,loaded:!1,waitingForLoadCallback:[this._onImageLoaded.bind(this)]}),this._domImage.onload=()=>{if(e){const t=Lw.SourceImgCache.get(e);if(t){t.loaded=!0;for(const e of t.waitingForLoadCallback)e();return void(t.waitingForLoadCallback.length=0)}}this._onImageLoaded()},e&&(Ds.SetCorsBehavior(e,this._domImage),Ds.SetReferrerPolicyBehavior(this.referrerPolicy,this._domImage),this._domImage.src=e)}_svgCheck(e){if(window.SVGSVGElement&&-1!==e.search(/.svg#/gi)&&e.indexOf("#")===e.lastIndexOf("#")){this._isSVG=!0;const t=e.split("#")[0],i=e.split("#")[1],s=document.body.querySelector('object[data="'+t+'"]');if(s){const t=s.contentDocument;if(t&&t.documentElement){const r=t.documentElement.getAttribute("viewBox"),n=Number(t.documentElement.getAttribute("width")),o=Number(t.documentElement.getAttribute("height"));if(t.getElementById(i)&&r&&n&&o)return this._getSVGAttribs(s,i),e}s.addEventListener("load",(()=>{this._getSVGAttribs(s,i)}))}else{const e=document.createElement("object");e.data=t,e.type="image/svg+xml",e.width="0%",e.height="0%",document.body.appendChild(e),e.onload=()=>{const e=document.body.querySelector('object[data="'+t+'"]');e&&this._getSVGAttribs(e,i)}}return t}return e}_getSVGAttribs(e,t){const i=e.contentDocument;if(i&&i.documentElement){const e=i.documentElement.getAttribute("viewBox"),s=Number(i.documentElement.getAttribute("width")),r=Number(i.documentElement.getAttribute("height")),n=i.getElementById(t);if(e&&s&&r&&n){const t=Number(e.split(" ")[2]),i=Number(e.split(" ")[3]),o=n.getBBox();let a=1,l=1,h=0,c=0;const u=n.transform.baseVal.consolidate().matrix;n.transform&&n.transform.baseVal.consolidate()&&(a=u.a,l=u.d,h=u.e,c=u.f),this.sourceLeft=(a*o.x+h)*s/t,this.sourceTop=(l*o.y+c)*r/i,this.sourceWidth=o.width*a*(s/t),this.sourceHeight=o.height*l*(r/i),this._svgAttributesComputationCompleted=!0,this.onSVGAttributesComputedObservable.notifyObservers(this)}}}get cellWidth(){return this._cellWidth}set cellWidth(e){this._cellWidth!==e&&(this._cellWidth=e,this._markAsDirty())}get cellHeight(){return this._cellHeight}set cellHeight(e){this._cellHeight!==e&&(this._cellHeight=e,this._markAsDirty())}get cellId(){return this._cellId}set cellId(e){this._cellId!==e&&(this._cellId=e,this._markAsDirty())}constructor(e,t=null){super(e),this.name=e,this._workingCanvas=null,this._loaded=!1,this._stretch=Lw.STRETCH_FILL,this._autoScale=!1,this._sourceLeft=0,this._sourceTop=0,this._sourceWidth=0,this._sourceHeight=0,this._svgAttributesComputationCompleted=!1,this._isSVG=!1,this._cellWidth=0,this._cellHeight=0,this._cellId=-1,this._populateNinePatchSlicesFromImage=!1,this._imageDataCache={data:null,key:""},this.onImageLoadedObservable=new K,this.onSVGAttributesComputedObservable=new K,this.source=t}contains(e,t){if(!super.contains(e,t))return!1;if(!this._detectPointerOnOpaqueOnly||!this._workingCanvas)return!0;const i=0|this._currentMeasure.width,s=0|this._currentMeasure.height,r=i+"_"+s;let n=this._imageDataCache.data;if(!n||this._imageDataCache.key!==r){const e=this._workingCanvas.getContext("2d");this._imageDataCache.data=n=e.getImageData(0,0,i,s).data,this._imageDataCache.key=r}return n[4*((e=e-this._currentMeasure.left|0)+(t=t-this._currentMeasure.top|0)*i)+3]>0}_getTypeName(){return"Image"}synchronizeSizeWithContent(){this._loaded&&(this.width=this._domImage.width+"px",this.height=this._domImage.height+"px")}_processMeasures(e,t){if(this._loaded)switch(this._stretch){case Lw.STRETCH_NONE:case Lw.STRETCH_FILL:case Lw.STRETCH_UNIFORM:case Lw.STRETCH_NINE_PATCH:break;case Lw.STRETCH_EXTEND:this._autoScale&&this.synchronizeSizeWithContent(),this.parent&&this.parent.parent&&(this.parent.adaptWidthToChildren=!0,this.parent.adaptHeightToChildren=!0)}super._processMeasures(e,t)}_prepareWorkingCanvasForOpaqueDetection(){if(!this._detectPointerOnOpaqueOnly)return;const e=this._currentMeasure.width,t=this._currentMeasure.height;if(!this._workingCanvas){const i=this._host?.getScene()?.getEngine()||re.LastCreatedEngine;if(!i)throw new Error("Invalid engine. Unable to create a canvas.");this._workingCanvas=i.createCanvas(e,t)}this._workingCanvas.getContext("2d").clearRect(0,0,e,t)}_drawImage(e,t,i,s,r,n,o,a,l){if(e.drawImage(this._domImage,t,i,s,r,n,o,a,l),!this._detectPointerOnOpaqueOnly)return;const h=e.getTransform(),c=this._workingCanvas.getContext("2d");c.save();const u=n-this._currentMeasure.left,d=o-this._currentMeasure.top;c.setTransform(h.a,h.b,h.c,h.d,(u+a)/2,(d+l)/2),c.translate(-(u+a)/2,-(d+l)/2),c.drawImage(this._domImage,t,i,s,r,u,d,a,l),c.restore()}_draw(e){let t,i,s,r;if(e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),-1==this.cellId)t=this._sourceLeft,i=this._sourceTop,s=this._sourceWidth?this._sourceWidth:this._imageWidth,r=this._sourceHeight?this._sourceHeight:this._imageHeight;else{const e=this._domImage.naturalWidth/this.cellWidth,n=this.cellId/e|0,o=this.cellId%e;t=this.cellWidth*o,i=this.cellHeight*n,s=this.cellWidth,r=this.cellHeight}if(this._prepareWorkingCanvasForOpaqueDetection(),this._applyStates(e),this._loaded)switch(this._stretch){case Lw.STRETCH_NONE:case Lw.STRETCH_FILL:this._drawImage(e,t,i,s,r,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case Lw.STRETCH_UNIFORM:{const n=this._currentMeasure.width/s,o=this._currentMeasure.height/r,a=Math.min(n,o),l=(this._currentMeasure.width-s*a)/2,h=(this._currentMeasure.height-r*a)/2;this._drawImage(e,t,i,s,r,this._currentMeasure.left+l,this._currentMeasure.top+h,s*a,r*a);break}case Lw.STRETCH_EXTEND:this._drawImage(e,t,i,s,r,this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height);break;case Lw.STRETCH_NINE_PATCH:this._renderNinePatch(e,t,i,s,r)}e.restore()}_renderNinePatch(e,t,i,s,r){const n=this.host.idealWidth?this._width.getValue(this.host)/this.host.idealWidth:this.host.idealHeight?this._height.getValue(this.host)/this.host.idealHeight:1,o=this._sliceLeft,a=this._sliceTop,l=r-this._sliceBottom,h=s-this._sliceRight,c=this._sliceRight-this._sliceLeft,u=this._sliceBottom-this._sliceTop,d=Math.round(o*n),_=Math.round(a*n),p=Math.round(l*n),f=Math.round(h*n),m=Math.round(this._currentMeasure.width)-f-d+2,g=Math.round(this._currentMeasure.height)-p-_+2,v=Math.round(this._currentMeasure.left)+d-1,x=Math.round(this._currentMeasure.top)+_-1,b=Math.round(this._currentMeasure.left+this._currentMeasure.width)-f,T=Math.round(this._currentMeasure.top+this._currentMeasure.height)-p;this._drawImage(e,t,i,o,a,this._currentMeasure.left,this._currentMeasure.top,d,_),this._drawImage(e,t+this._sliceLeft,i,c,a,v+1,this._currentMeasure.top,m-2,_),this._drawImage(e,t+this._sliceRight,i,h,a,b,this._currentMeasure.top,f,_),this._drawImage(e,t,i+this._sliceTop,o,u,this._currentMeasure.left,x+1,d,g-2),this._drawImage(e,t+this._sliceLeft,i+this._sliceTop,c,u,v+1,x+1,m-2,g-2),this._drawImage(e,t+this._sliceRight,i+this._sliceTop,h,u,b,x+1,f,g-2),this._drawImage(e,t,i+this._sliceBottom,o,l,this._currentMeasure.left,T,d,p),this._drawImage(e,t+this.sliceLeft,i+this._sliceBottom,c,l,v+1,T,m-2,p),this._drawImage(e,t+this._sliceRight,i+this._sliceBottom,h,l,b,T,f,p)}dispose(){super.dispose(),this.onImageLoadedObservable.clear(),this.onSVGAttributesComputedObservable.clear(),this._removeCacheUsage(this._source)}}Lw.SourceImgCache=new Map,Lw.STRETCH_NONE=0,Lw.STRETCH_FILL=1,Lw.STRETCH_UNIFORM=2,Lw.STRETCH_EXTEND=3,Lw.STRETCH_NINE_PATCH=4,Ze([rt()],Lw.prototype,"detectPointerOnOpaqueOnly",null),Ze([rt()],Lw.prototype,"sliceLeft",null),Ze([rt()],Lw.prototype,"sliceRight",null),Ze([rt()],Lw.prototype,"sliceTop",null),Ze([rt()],Lw.prototype,"sliceBottom",null),Ze([rt()],Lw.prototype,"sourceLeft",null),Ze([rt()],Lw.prototype,"sourceTop",null),Ze([rt()],Lw.prototype,"sourceWidth",null),Ze([rt()],Lw.prototype,"sourceHeight",null),Ze([rt()],Lw.prototype,"populateNinePatchSlicesFromImage",null),Ze([rt()],Lw.prototype,"autoScale",null),Ze([rt()],Lw.prototype,"stretch",null),Ze([rt()],Lw.prototype,"source",null),Ze([rt()],Lw.prototype,"cellWidth",null),Ze([rt()],Lw.prototype,"cellHeight",null),Ze([rt()],Lw.prototype,"cellId",null),z("BABYLON.GUI.Image",Lw);class Bw extends ww{get image(){return this._image}get textBlock(){return this._textBlock}constructor(e){super(e),this.name=e,this.thickness=1,this.isPointerBlocker=!0;let t=null;this.pointerEnterAnimation=()=>{t=this.alpha,this.alpha-=.1},this.pointerOutAnimation=()=>{null!==t&&(this.alpha=t)},this.pointerDownAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05}}_getTypeName(){return"Button"}_processPicking(e,t,i,s,r,n,o,a){if(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this.notRenderable)return!1;if(!super.contains(e,t))return!1;if(this.delegatePickingToChildren){let i=!1;for(let s=this._children.length-1;s>=0;s--){const r=this._children[s];if(r.isEnabled&&r.isHitTestVisible&&r.isVisible&&!r.notRenderable&&r.contains(e,t)){i=!0;break}}if(!i)return!1}return this._processObservables(s,e,t,i,r,n,o,a),!0}_onPointerEnter(e,t){return!!super._onPointerEnter(e,t)&&(!this.isReadOnly&&this.pointerEnterAnimation&&this.pointerEnterAnimation(),!0)}_onPointerOut(e,t,i=!1){!this.isReadOnly&&this.pointerOutAnimation&&this.pointerOutAnimation(),super._onPointerOut(e,t,i)}_onPointerDown(e,t,i,s,r){return!!super._onPointerDown(e,t,i,s,r)&&(!this.isReadOnly&&this.pointerDownAnimation&&this.pointerDownAnimation(),!0)}_getRectangleFill(e){return this.isEnabled?this._getBackgroundColor(e):this._disabledColor}_onPointerUp(e,t,i,s,r,n){!this.isReadOnly&&this.pointerUpAnimation&&this.pointerUpAnimation(),super._onPointerUp(e,t,i,s,r,n)}serialize(e,t){super.serialize(e,t),(this.isSerializable||t)&&(this._textBlock&&(e.textBlockName=this._textBlock.name),this._image&&(e.imageName=this._image.name))}_parseFromContent(e,t){super._parseFromContent(e,t),e.textBlockName&&(this._textBlock=this.getChildByName(e.textBlockName)),e.imageName&&(this._image=this.getChildByName(e.imageName))}static CreateImageButton(e,t,i){const s=new this(e),r=new Fw(e+"_button",t);r.textWrapping=!0,r.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_CENTER,r.paddingLeft="20%",s.addControl(r);const n=new Lw(e+"_icon",i);return n.width="20%",n.stretch=Lw.STRETCH_UNIFORM,n.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,s.addControl(n),s._image=n,s._textBlock=r,s}static CreateImageOnlyButton(e,t){const i=new this(e),s=new Lw(e+"_icon",t);return s.stretch=Lw.STRETCH_FILL,s.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,i.addControl(s),i._image=s,i}static CreateSimpleButton(e,t){const i=new this(e),s=new Fw(e+"_button",t);return s.textWrapping=!0,s.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_CENTER,i.addControl(s),i._textBlock=s,i}static CreateImageWithCenterTextButton(e,t,i){const s=new this(e),r=new Lw(e+"_icon",i);r.stretch=Lw.STRETCH_FILL,s.addControl(r);const n=new Fw(e+"_button",t);return n.textWrapping=!0,n.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_CENTER,s.addControl(n),s._image=r,s._textBlock=n,s}}z("BABYLON.GUI.Button",Bw);class kw extends Dw{get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,this._markAsDirty())}get spacing(){return this._spacing}set spacing(e){this._spacing!==e&&(this._spacing=e,this._markAsDirty())}set width(e){this._doNotTrackManualChanges||(this._manualWidth=!0),this._width.toString(this._host)!==e&&this._width.fromString(e)&&this._markAsDirty()}get width(){return this._width.toString(this._host)}set height(e){this._doNotTrackManualChanges||(this._manualHeight=!0),this._height.toString(this._host)!==e&&this._height.fromString(e)&&this._markAsDirty()}get height(){return this._height.toString(this._host)}constructor(e){super(e),this.name=e,this._isVertical=!0,this._manualWidth=!1,this._manualHeight=!1,this._doNotTrackManualChanges=!1,this._spacing=0,this.ignoreLayoutWarnings=!1}_getTypeName(){return"StackPanel"}_preMeasure(e,t){for(const e of this._children)this._isVertical?e.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP:e.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT;super._preMeasure(e,t)}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.copyFrom(e),this._measureForChildren.left=this._currentMeasure.left,this._measureForChildren.top=this._currentMeasure.top,this.isVertical&&!this._manualWidth||(this._measureForChildren.width=this._currentMeasure.width),(this.isVertical||this._manualHeight)&&(this._measureForChildren.height=this._currentMeasure.height)}_postMeasure(){let e=0,t=0;const i=this._children.length;for(let s=0;s=0?Math.min(e,this._characters.length):this._characters.length+Math.max(e,-this._characters.length),void 0===t?t=this._characters.length-e:(isNaN(t)||t<0)&&(t=0);const i=[];for(;--t>=0;)i[t]=this._characters[e+t];return i.join("")}return this._text.substr(e,t)}substring(e,t){if(this._characters){isNaN(e)?e=0:e>this._characters.length?e=this._characters.length:e<0&&(e=0),void 0===t?t=this._characters.length:isNaN(t)?t=0:t>this._characters.length?t=this._characters.length:t<0&&(t=0);const i=[];let s=0;for(;e{switch(e.type){case Jm.COPY:this._onCopyText(e.event),this.onTextCopyObservable.notifyObservers(this);break;case Jm.CUT:this._onCutText(e.event),this.onTextCutObservable.notifyObservers(this);break;case Jm.PASTE:this._onPasteText(e.event),this.onTextPasteObservable.notifyObservers(this);break;default:return}}));const e=this._host.getScene();e&&(this._onPointerDblTapObserver=e.onPointerObservable.add((e=>{this._isFocused&&e.type===lr.POINTERDOUBLETAP&&this._processDblClick(e)}))),this._onFocusSelectAll&&this._selectAllText()}focus(){this._host.moveFocusToControl(this)}blur(){this._host.focusedControl=null}_getTypeName(){return"InputText"}keepsFocusWith(){return this._connectedVirtualKeyboard?[this._connectedVirtualKeyboard]:null}processKey(e,t,i){if(!this.isReadOnly&&(!i||!i.ctrlKey&&!i.metaKey||67!==e&&86!==e&&88!==e)){if(i&&(i.ctrlKey||i.metaKey)&&65===e)return this._selectAllText(),void i.preventDefault();switch(e){case 32:t=" ";break;case 191:i&&i.preventDefault();break;case 8:if(this._textWrapper.text&&this._textWrapper.length>0){if(this.isTextHighlightOn)return this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this._blinkIsEven=!1,void(i&&i.preventDefault());if(0===this._cursorOffset)this.text=this._textWrapper.substr(0,this._textWrapper.length-1);else{const e=this._textWrapper.length-this._cursorOffset;e>0&&(this._textWrapper.removePart(e-1,e),this._textHasChanged())}}return void(i&&i.preventDefault());case 46:if(this.isTextHighlightOn)return this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,void(i&&i.preventDefault());if(this._textWrapper.text&&this._textWrapper.length>0&&this._cursorOffset>0){const e=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(e,e+1),this._textHasChanged(),this._cursorOffset--}return void(i&&i.preventDefault());case 13:return this._host.focusedControl=null,void(this.isTextHighlightOn=!1);case 35:return this._cursorOffset=0,this._blinkIsEven=!1,this.isTextHighlightOn=!1,void this._markAsDirty();case 36:return this._cursorOffset=this._textWrapper.length,this._blinkIsEven=!1,this.isTextHighlightOn=!1,void this._markAsDirty();case 37:if(this._cursorOffset++,this._cursorOffset>this._textWrapper.length&&(this._cursorOffset=this._textWrapper.length),i&&i.shiftKey){if(this._blinkIsEven=!1,i.ctrlKey||i.metaKey){if(!this.isTextHighlightOn){if(this._textWrapper.length===this._cursorOffset)return;this._endHighlightIndex=this._textWrapper.length-this._cursorOffset+1}return this._startHighlightIndex=0,this._cursorIndex=this._textWrapper.length-this._endHighlightIndex,this._cursorOffset=this._textWrapper.length,this.isTextHighlightOn=!0,void this._markAsDirty()}return this.isTextHighlightOn?-1===this._cursorIndex&&(this._cursorIndex=this._textWrapper.length-this._endHighlightIndex,this._cursorOffset=0===this._startHighlightIndex?this._textWrapper.length:this._textWrapper.length-this._startHighlightIndex+1):(this.isTextHighlightOn=!0,this._cursorIndex=this._cursorOffset>=this._textWrapper.length?this._textWrapper.length:this._cursorOffset-1),this._cursorIndexthis._cursorOffset?(this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex):this.isTextHighlightOn=!1,void this._markAsDirty()}return this.isTextHighlightOn&&(this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this.isTextHighlightOn=!1),i&&(i.ctrlKey||i.metaKey)&&(this._cursorOffset=this._textWrapper.length,i.preventDefault()),this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._cursorIndex=-1,void this._markAsDirty();case 39:if(this._cursorOffset--,this._cursorOffset<0&&(this._cursorOffset=0),i&&i.shiftKey){if(this._blinkIsEven=!1,i.ctrlKey||i.metaKey){if(!this.isTextHighlightOn){if(0===this._cursorOffset)return;this._startHighlightIndex=this._textWrapper.length-this._cursorOffset-1}return this._endHighlightIndex=this._textWrapper.length,this.isTextHighlightOn=!0,this._cursorIndex=this._textWrapper.length-this._startHighlightIndex,this._cursorOffset=0,void this._markAsDirty()}return this.isTextHighlightOn?-1===this._cursorIndex&&(this._cursorIndex=this._textWrapper.length-this._startHighlightIndex,this._cursorOffset=this._textWrapper.length===this._endHighlightIndex?0:this._textWrapper.length-this._endHighlightIndex-1):(this.isTextHighlightOn=!0,this._cursorIndex=this._cursorOffset<=0?0:this._cursorOffset+1),this._cursorIndexthis._cursorOffset?(this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex):this.isTextHighlightOn=!1,void this._markAsDirty()}return this.isTextHighlightOn&&(this._cursorOffset=this._textWrapper.length-this._endHighlightIndex,this.isTextHighlightOn=!1),i&&(i.ctrlKey||i.metaKey)&&(this._cursorOffset=0,i.preventDefault()),this._blinkIsEven=!1,this.isTextHighlightOn=!1,this._cursorIndex=-1,void this._markAsDirty()}if(32===e&&(t=i?.key??" "),this._deadKey="Dead"===t,t&&(-1===e||32===e||34===e||39===e||e>47&&e<64||e>64&&e<91||e>159&&e<193||e>218&&e<223||e>95&&e<112)&&(this._currentKey=t,this.onBeforeKeyAddObservable.notifyObservers(this),t=this._currentKey,this._addKey&&!this._deadKey))if(this.isTextHighlightOn)this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex,t),this._textHasChanged(),this._cursorOffset=this._textWrapper.length-(this._startHighlightIndex+1),this.isTextHighlightOn=!1,this._blinkIsEven=!1,this._markAsDirty();else if(0===this._cursorOffset)this.text+=this._deadKey&&i?.key?i.key:t;else{const e=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(e,e,t),this._textHasChanged()}}}_updateValueFromCursorIndex(e){if(this._blinkIsEven=!1,-1===this._cursorIndex)this._cursorIndex=e;else if(this._cursorIndexthis._cursorOffset))return this.isTextHighlightOn=!1,void this._markAsDirty();this._endHighlightIndex=this._textWrapper.length-this._cursorOffset,this._startHighlightIndex=this._textWrapper.length-this._cursorIndex}this.isTextHighlightOn=!0,this._markAsDirty()}_processDblClick(e){let t,i;this._startHighlightIndex=this._textWrapper.length-this._cursorOffset,this._endHighlightIndex=this._startHighlightIndex;do{i=this._endHighlightIndex0&&this._textWrapper.isWord(this._startHighlightIndex-1)?--this._startHighlightIndex:0}while(t||i);this._cursorOffset=this._textWrapper.length-this._startHighlightIndex,this.isTextHighlightOn=!0,this._clickedCoordinate=null,this._blinkIsEven=!0,this._cursorIndex=-1,this._markAsDirty()}_selectAllText(){this._blinkIsEven=!0,this.isTextHighlightOn=!0,this._startHighlightIndex=0,this._endHighlightIndex=this._textWrapper.length,this._cursorOffset=this._textWrapper.length,this._cursorIndex=-1,this._markAsDirty()}processKeyboard(e){this.processKey(e.keyCode,e.key,e),this.onKeyboardEventProcessedObservable.notifyObservers(e)}_onCopyText(e){this.isTextHighlightOn=!1;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText}_onCutText(e){if(this._highlightedText){this._textWrapper.removePart(this._startHighlightIndex,this._endHighlightIndex),this._textHasChanged(),this.isTextHighlightOn=!1,this._cursorOffset=this._textWrapper.length-this._startHighlightIndex;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText,this._highlightedText=""}}_onPasteText(e){let t="";t=e.clipboardData&&-1!==e.clipboardData.types.indexOf("text/plain")?e.clipboardData.getData("text/plain"):this._host.clipboardData;const i=this._textWrapper.length-this._cursorOffset;this._textWrapper.removePart(i,i,t),this._textHasChanged()}_draw(e){e.save(),this._applyStates(e),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._isEnabled?this._focusedBackground:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._fontOffset&&!this._wasDirty||(this._fontOffset=Ow._GetFontOffset(e.font,this._host.getScene()?.getEngine()));const t=this._currentMeasure.left+this._margin.getValueInPixel(this._host,this._tempParentMeasure.width);this.color&&(e.fillStyle=this.color);let i=this._beforeRenderText(this._textWrapper);this._isFocused||this._textWrapper.text||!this._placeholderText||(i=new Uw,i.text=this._placeholderText,this._placeholderColor&&(e.fillStyle=this._placeholderColor)),this._textWidth=e.measureText(i.text).width;const s=2*this._margin.getValueInPixel(this._host,this._tempParentMeasure.width);this._autoStretchWidth&&(this.width=Math.min(this._maxWidth.getValueInPixel(this._host,this._tempParentMeasure.width),this._textWidth+s)+"px",this._autoStretchWidth=!0);const r=this._fontOffset.ascent+(this._currentMeasure.height-this._fontOffset.height)/2,n=this._width.getValueInPixel(this._host,this._tempParentMeasure.width)-s;if(e.save(),e.beginPath(),e.rect(t,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,n+2,this._currentMeasure.height),e.clip(),this._isFocused&&this._textWidth>n){const e=t-this._textWidth+n;this._scrollLeft||(this._scrollLeft=e)}else this._scrollLeft=t;if(this.outlineWidth&&e.strokeText(i.text,this._scrollLeft,this._currentMeasure.top+r),e.fillText(i.text,this._scrollLeft,this._currentMeasure.top+r),this._isFocused){if(this._clickedCoordinate){const t=this._scrollLeft+this._textWidth-this._clickedCoordinate;let s=0;this._cursorOffset=0;let r=0;do{this._cursorOffset&&(r=Math.abs(t-s)),this._cursorOffset++,s=e.measureText(i.substr(i.length-this._cursorOffset,this._cursorOffset)).width}while(s=this._cursorOffset);Math.abs(t-s)>r&&this._cursorOffset--,this._blinkIsEven=!1,this._clickedCoordinate=null}if(!this._blinkIsEven){const s=i.substr(i.length-this._cursorOffset),r=e.measureText(s).width;let o=this._scrollLeft+this._textWidth-r;ot+n&&(this._scrollLeft+=t+n-o,o=t+n,this._markAsDirty()),this.isTextHighlightOn||e.fillRect(o,this._currentMeasure.top+(this._currentMeasure.height-this._fontOffset.height)/2,2,this._fontOffset.height)}if(clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout((()=>{this._blinkIsEven=!this._blinkIsEven,this._markAsDirty()}),500),this.isTextHighlightOn){clearTimeout(this._blinkTimeout);const s=e.measureText(i.substring(this._startHighlightIndex)).width;let r=this._scrollLeft+this._textWidth-s;this._highlightedText=i.substring(this._startHighlightIndex,this._endHighlightIndex);let n=e.measureText(i.substring(this._startHighlightIndex,this._endHighlightIndex)).width;r=this._rowDefinitions.length?null:this._rowDefinitions[e]}getColumnDefinition(e){return e<0||e>=this._columnDefinitions.length?null:this._columnDefinitions[e]}addRowDefinition(e,t=!1){return this._rowDefinitions.push(new yw(e,t?yw.UNITMODE_PIXEL:yw.UNITMODE_PERCENTAGE)),this._rowDefinitionObservers.push(this._rowDefinitions[this.rowCount-1].onChangedObservable.add((()=>this._markAsDirty()))),this._markAsDirty(),this}addColumnDefinition(e,t=!1){return this._columnDefinitions.push(new yw(e,t?yw.UNITMODE_PIXEL:yw.UNITMODE_PERCENTAGE)),this._columnDefinitionObservers.push(this._columnDefinitions[this.columnCount-1].onChangedObservable.add((()=>this._markAsDirty()))),this._markAsDirty(),this}setRowDefinition(e,t,i=!1){if(e<0||e>=this._rowDefinitions.length)return this;const s=this._rowDefinitions[e];return s&&s.isPixel===i&&s.value===t||(this._rowDefinitions[e].onChangedObservable.remove(this._rowDefinitionObservers[e]),this._rowDefinitions[e]=new yw(t,i?yw.UNITMODE_PIXEL:yw.UNITMODE_PERCENTAGE),this._rowDefinitionObservers[e]=this._rowDefinitions[e].onChangedObservable.add((()=>this._markAsDirty())),this._markAsDirty()),this}setColumnDefinition(e,t,i=!1){if(e<0||e>=this._columnDefinitions.length)return this;const s=this._columnDefinitions[e];return s&&s.isPixel===i&&s.value===t||(this._columnDefinitions[e].onChangedObservable.remove(this._columnDefinitionObservers[e]),this._columnDefinitions[e]=new yw(t,i?yw.UNITMODE_PIXEL:yw.UNITMODE_PERCENTAGE),this._columnDefinitionObservers[e]=this._columnDefinitions[e].onChangedObservable.add((()=>this._markAsDirty())),this._markAsDirty()),this}getChildrenAt(e,t){const i=this._cells[`${e}:${t}`];return i?i.children:null}getChildCellInfo(e){return e._tag}_removeCell(e,t){if(e){super.removeControl(e);for(const t of e.children){const e=this._childControls.indexOf(t);-1!==e&&this._childControls.splice(e,1)}delete this._cells[t]}}_offsetCell(e,t){if(this._cells[t]){this._cells[e]=this._cells[t];for(const t of this._cells[e].children)t._tag=e;delete this._cells[t]}}removeColumnDefinition(e){if(e<0||e>=this._columnDefinitions.length)return this;for(let t=0;t=this._rowDefinitions.length)return this;for(let t=0;t{for(const r in this._cells){if(!Object.prototype.hasOwnProperty.call(this._cells,r))continue;const n=r.split(":"),o=parseInt(n[0]),a=parseInt(n[1]),l=this._cells[r];l.leftInPixels=e[a],l.topInPixels=t[o],l.widthInPixels=i[a],l.heightInPixels=s[o],l._left.ignoreAdaptiveScaling=!0,l._top.ignoreAdaptiveScaling=!0,l._width.ignoreAdaptiveScaling=!0,l._height.ignoreAdaptiveScaling=!0}})),super._additionalProcessing(e,t)}_flagDescendantsAsMatrixDirty(){for(const e in this._cells)Object.prototype.hasOwnProperty.call(this._cells,e)&&this._cells[e]._markMatrixAsDirty()}_renderHighlightSpecific(e){super._renderHighlightSpecific(e),this._getGridDefinitions(((t,i,s,r)=>{for(let i=0;i{e.tags.push(t._tag)}))}}_parseFromContent(e,t){super._parseFromContent(e,t);const i=[];this.children.forEach((e=>{i.push(e)})),this.removeRowDefinition(0),this.removeColumnDefinition(0);for(let t=0;t=1-Ww._Epsilon&&(this._value.r=1),this._value.g>=1-Ww._Epsilon&&(this._value.g=1),this._value.b>=1-Ww._Epsilon&&(this._value.b=1),this.onValueChangedObservable.notifyObservers(this._value))}get width(){return this._width.toString(this._host)}set width(e){this._width.toString(this._host)!==e&&this._width.fromString(e)&&(0===this._width.getValue(this._host)&&(e="1px",this._width.fromString(e)),this._height.fromString(e),this._markAsDirty())}get height(){return this._height.toString(this._host)}set height(e){this._height.toString(this._host)!==e&&this._height.fromString(e)&&(0===this._height.getValue(this._host)&&(e="1px",this._height.fromString(e)),this._width.fromString(e),this._markAsDirty())}get size(){return this.width}set size(e){this.width=e}constructor(e){super(e),this.name=e,this._value=Ee.Red(),this._tmpColor=new Ee,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._squareLeft=0,this._squareTop=0,this._squareSize=0,this._h=360,this._s=1,this._v=1,this._lastPointerDownId=-1,this.onValueChangedObservable=new K,this._pointerIsDown=!1,this.value=new Ee(.88,.1,.1),this.size="200px",this.isPointerBlocker=!0}_getTypeName(){return"ColorPicker"}_preMeasure(e){e.widthl||sg?f:(f-p)*(e-m)/(g-m)+p,d=(r-h)/(e-h),o[u+3]=d<_?d/_*255:d>1-_?255*(1-(d-(1-_))/_):255}return r.putImageData(n,0,0),s}_draw(e){e.save(),this._applyStates(e);const t=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),i=.2*t,s=this._currentMeasure.left,r=this._currentMeasure.top;this._colorWheelCanvas&&this._colorWheelCanvas.width==2*t||(this._colorWheelCanvas=this._createColorWheelCanvas(t,i)),this._updateSquareProps(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY,e.fillRect(this._squareLeft,this._squareTop,this._squareSize,this._squareSize)),e.drawImage(this._colorWheelCanvas,s,r),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._drawGradientSquare(this._h,this._squareLeft,this._squareTop,this._squareSize,this._squareSize,e);let n=this._squareLeft+this._squareSize*this._s,o=this._squareTop+this._squareSize*(1-this._v);this._drawCircle(n,o,.04*t,e);const a=t-.5*i;n=s+t+Math.cos((this._h-180)*Math.PI/180)*a,o=r+t+Math.sin((this._h-180)*Math.PI/180)*a,this._drawCircle(n,o,.35*i,e),e.restore()}_updateValueFromPointer(e,t){if(this._pointerStartedOnWheel){const i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),s=i+this._currentMeasure.left,r=i+this._currentMeasure.top;this._h=180*Math.atan2(t-r,e-s)/Math.PI+180}else this._pointerStartedOnSquare&&(this._updateSquareProps(),this._s=(e-this._squareLeft)/this._squareSize,this._v=1-(t-this._squareTop)/this._squareSize,this._s=Math.min(this._s,1),this._s=Math.max(this._s,Ww._Epsilon),this._v=Math.min(this._v,1),this._v=Math.max(this._v,Ww._Epsilon));Ee.HSVtoRGBToRef(this._h,this._s,this._v,this._tmpColor),this.value=this._tmpColor}_isPointOnSquare(e,t){this._updateSquareProps();const i=this._squareLeft,s=this._squareTop,r=this._squareSize;return e>=i&&e<=i+r&&t>=s&&t<=s+r}_isPointOnWheel(e,t){const i=.5*Math.min(this._currentMeasure.width,this._currentMeasure.height),s=i-.2*i,r=e-(i+this._currentMeasure.left),n=t-(i+this._currentMeasure.top),o=r*r+n*n;return o<=i*i&&o>=s*s}_onPointerDown(e,t,i,s,r){if(!super._onPointerDown(e,t,i,s,r))return!1;if(this.isReadOnly)return!0;this._pointerIsDown=!0,this._pointerStartedOnSquare=!1,this._pointerStartedOnWheel=!1,this._invertTransformMatrix.transformCoordinates(t.x,t.y,this._transformedPosition);const n=this._transformedPosition.x,o=this._transformedPosition.y;return this._isPointOnSquare(n,o)?this._pointerStartedOnSquare=!0:this._isPointOnWheel(n,o)&&(this._pointerStartedOnWheel=!0),this._updateValueFromPointer(n,o),this._host._capturingControl[i]=this,this._lastPointerDownId=i,!0}_onPointerMove(e,t,i,s){if(i==this._lastPointerDownId){if(!this.isReadOnly){this._invertTransformMatrix.transformCoordinates(t.x,t.y,this._transformedPosition);const e=this._transformedPosition.x,i=this._transformedPosition.y;this._pointerIsDown&&this._updateValueFromPointer(e,i)}super._onPointerMove(e,t,i,s)}}_onPointerUp(e,t,i,s,r,n){this._pointerIsDown=!1,delete this._host._capturingControl[i],super._onPointerUp(e,t,i,s,r,n)}_onCanvasBlur(){this._forcePointerUp(),super._onCanvasBlur()}static ShowPickerDialogAsync(e,t){return new Promise((i=>{t.pickerWidth=t.pickerWidth||"640px",t.pickerHeight=t.pickerHeight||"400px",t.headerHeight=t.headerHeight||"35px",t.lastColor=t.lastColor||"#000000",t.swatchLimit=t.swatchLimit||20,t.numSwatchesPerLine=t.numSwatchesPerLine||10;const s=t.swatchLimit/t.numSwatchesPerLine,r=parseFloat(t.pickerWidth)/t.numSwatchesPerLine,n=Math.floor(.25*r),o=n*(t.numSwatchesPerLine+1),a=Math.floor((parseFloat(t.pickerWidth)-o)/t.numSwatchesPerLine),l=a*s+n*(s+1),h=(parseInt(t.pickerHeight)+l+Math.floor(.25*a)).toString()+"px",c="#c0c0c0",u="#535353",d="#414141",_="515151",p="#555555",f="#454545",m=Ee.FromHexString("#dddddd"),g=m.r+m.g+m.b,v="#aaaaaa",x="#ffffff";let b,T;const y=["R","G","B"],S="#454545",C="#f0f0f0";let E,A,P,I,R,M=!1;const O=new zw;if(O.name="Dialog Container",O.width=t.pickerWidth,t.savedColors){O.height=h;const e=parseInt(t.pickerHeight)/parseInt(h);O.addRowDefinition(e,!1),O.addRowDefinition(1-e,!1)}else O.height=t.pickerHeight,O.addRowDefinition(1,!1);if(e.addControl(O),t.savedColors){A=new zw,A.name="Swatch Drawer",A.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,A.background=u,A.width=t.pickerWidth;const e=t.savedColors.length/t.numSwatchesPerLine;let i;i=0==e?0:e+1,A.height=(a*e+i*n).toString()+"px",A.top=Math.floor(.25*a).toString()+"px";for(let e=0;e<2*Math.ceil(t.savedColors.length/t.numSwatchesPerLine)+1;e++)e%2!=0?A.addRowDefinition(a,!0):A.addRowDefinition(n,!0);for(let e=0;e<2*t.numSwatchesPerLine+1;e++)e%2!=0?A.addColumnDefinition(a,!0):A.addColumnDefinition(n,!0);O.addControl(A,1,0)}const D=new zw;D.name="Picker Panel",D.height=t.pickerHeight;const w=parseInt(t.headerHeight)/parseInt(t.pickerHeight),N=[w,1-w];D.addRowDefinition(N[0],!1),D.addRowDefinition(N[1],!1),O.addControl(D,0,0);const F=new ww;F.name="Dialogue Header Bar",F.background="#cccccc",F.thickness=0,D.addControl(F,0,0);const L=Bw.CreateSimpleButton("closeButton","a");L.fontFamily="coreglyphs";const B=Ee.FromHexString(F.background),k=new Ee(1-B.r,1-B.g,1-B.b);L.color=k.toHexString(),L.fontSize=Math.floor(.6*parseInt(t.headerHeight)),L.textBlock.textVerticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,L.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_RIGHT,L.height=L.width=t.headerHeight,L.background=F.background,L.thickness=0,L.pointerDownAnimation=()=>{},L.pointerUpAnimation=()=>{L.background=F.background},L.pointerEnterAnimation=()=>{L.color=F.background,L.background="red"},L.pointerOutAnimation=()=>{L.color=k.toHexString(),L.background=F.background},L.onPointerClickObservable.add((()=>{De(te.background)})),D.addControl(L,0,0);const V=new zw;V.name="Dialogue Body",V.background=u;const U=[.4375,.5625];V.addRowDefinition(1,!1),V.addColumnDefinition(U[0],!1),V.addColumnDefinition(U[1],!1),D.addControl(V,1,0);const G=new zw;G.name="Picker Grid",G.addRowDefinition(.85,!1),G.addRowDefinition(.15,!1),V.addControl(G,0,0);const z=new Ww;z.name="GUI Color Picker",t.pickerHeight{R=z.name,I="",Ie(!1)})),z.onValueChangedObservable.add((function(e){R==z.name&&Se(e,z.name)})),G.addControl(z,0,0);const W=new zw;W.name="Dialogue Right Half",W.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT;const H=[.514,.486];W.addRowDefinition(H[0],!1),W.addRowDefinition(H[1],!1),V.addControl(W,1,1);const X=new zw;X.name="Swatches and Buttons";const Y=[.417,.583];X.addRowDefinition(1,!1),X.addColumnDefinition(Y[0],!1),X.addColumnDefinition(Y[1],!1),W.addControl(X,0,0);const Q=new zw;Q.name="New and Current Swatches";const j=[.04,.16,.64,.16];Q.addRowDefinition(j[0],!1),Q.addRowDefinition(j[1],!1),Q.addRowDefinition(j[2],!1),Q.addRowDefinition(j[3],!1),X.addControl(Q,0,0);const K=new zw;K.name="Active Swatches",K.width=.67,K.addRowDefinition(.5,!1),K.addRowDefinition(.5,!1),Q.addControl(K,2,0);const $=Math.floor(parseInt(t.pickerWidth)*U[1]*Y[0]*.11),q=Math.floor(parseInt(t.pickerHeight)*N[1]*H[0]*j[1]*.5);let Z;Z=t.pickerWidth>t.pickerHeight?q:$;const J=new Fw;J.text="new",J.name="New Color Label",J.color=c,J.fontSize=Z,Q.addControl(J,1,0);const ee=new ww;ee.name="New Color Swatch",ee.background=t.lastColor,ee.thickness=0,K.addControl(ee,0,0);const te=Bw.CreateSimpleButton("currentSwatch","");te.background=t.lastColor,te.thickness=0,te.onPointerClickObservable.add((()=>{Se(Ee.FromHexString(te.background),te.name),Ie(!1)})),te.pointerDownAnimation=()=>{},te.pointerUpAnimation=()=>{},te.pointerEnterAnimation=()=>{},te.pointerOutAnimation=()=>{},K.addControl(te,1,0);const ie=new ww;ie.name="Swatch Outline",ie.width=.67,ie.thickness=2,ie.color="#404040",ie.isHitTestVisible=!1,Q.addControl(ie,2,0);const se=new Fw;se.name="Current Color Label",se.text="current",se.color=c,se.fontSize=Z,Q.addControl(se,3,0);const re=new zw;re.name="Button Grid",re.height=.8;const ne=1/3;re.addRowDefinition(ne,!1),re.addRowDefinition(ne,!1),re.addRowDefinition(ne,!1),X.addControl(re,0,1);const oe=Math.floor(parseInt(t.pickerWidth)*U[1]*Y[1]*.67).toString()+"px",ae=Math.floor(parseInt(t.pickerHeight)*N[1]*H[0]*(parseFloat(re.height.toString())/100)*ne*.7).toString()+"px";b=parseFloat(oe)>parseFloat(ae)?Math.floor(.45*parseFloat(ae)):Math.floor(.11*parseFloat(oe));const le=Bw.CreateSimpleButton("butOK","OK");le.width=oe,le.height=ae,le.verticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,le.thickness=2,le.color=c,le.fontSize=b,le.background=u,le.onPointerEnterObservable.add((()=>{le.background=d})),le.onPointerOutObservable.add((()=>{le.background=u})),le.pointerDownAnimation=()=>{le.background=_},le.pointerUpAnimation=()=>{le.background=d},le.onPointerClickObservable.add((()=>{Ie(!1),De(ee.background)})),re.addControl(le,0,0);const he=Bw.CreateSimpleButton("butCancel","Cancel");he.width=oe,he.height=ae,he.verticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,he.thickness=2,he.color=c,he.fontSize=b,he.background=u,he.onPointerEnterObservable.add((()=>{he.background=d})),he.onPointerOutObservable.add((()=>{he.background=u})),he.pointerDownAnimation=()=>{he.background=_},he.pointerUpAnimation=()=>{he.background=d},he.onPointerClickObservable.add((()=>{Ie(!1),De(te.background)})),re.addControl(he,1,0),t.savedColors&&(P=Bw.CreateSimpleButton("butSave","Save"),P.width=oe,P.height=ae,P.verticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,P.thickness=2,P.fontSize=b,t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&t.savedColors.length{t.savedColors&&(0==t.savedColors.length&&Me(!0),t.savedColors.length0&&Me(!0),re.addControl(P,2,0));const ce=new zw;ce.name="Dialog Lower Right",ce.addRowDefinition(.02,!1),ce.addRowDefinition(.63,!1),ce.addRowDefinition(.21,!1),ce.addRowDefinition(.14,!1),W.addControl(ce,1,0);const ue=Ee.FromHexString(t.lastColor),de=new zw;de.name="RGB Values",de.width=.82,de.verticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,de.addRowDefinition(1/3,!1),de.addRowDefinition(1/3,!1),de.addRowDefinition(1/3,!1),de.addColumnDefinition(.1,!1),de.addColumnDefinition(.2,!1),de.addColumnDefinition(.7,!1),ce.addControl(de,1,0);for(let e=0;e{R=_e.name,I=_e.text,Ie(!1)})),_e.onBlurObservable.add((()=>{""==_e.text&&(_e.text="0"),Ce(_e,"r"),R==_e.name&&(R="")})),_e.onTextChangedObservable.add((()=>{R==_e.name&&Ce(_e,"r")})),de.addControl(_e,0,1);const pe=new Gw;pe.width=.83,pe.height=.72,pe.name="gIntField",pe.fontSize=b,pe.text=(255*ue.g).toString(),pe.color=C,pe.background=S,pe.onFocusObservable.add((()=>{R=pe.name,I=pe.text,Ie(!1)})),pe.onBlurObservable.add((()=>{""==pe.text&&(pe.text="0"),Ce(pe,"g"),R==pe.name&&(R="")})),pe.onTextChangedObservable.add((()=>{R==pe.name&&Ce(pe,"g")})),de.addControl(pe,1,1);const fe=new Gw;fe.width=.83,fe.height=.72,fe.name="bIntField",fe.fontSize=b,fe.text=(255*ue.b).toString(),fe.color=C,fe.background=S,fe.onFocusObservable.add((()=>{R=fe.name,I=fe.text,Ie(!1)})),fe.onBlurObservable.add((()=>{""==fe.text&&(fe.text="0"),Ce(fe,"b"),R==fe.name&&(R="")})),fe.onTextChangedObservable.add((()=>{R==fe.name&&Ce(fe,"b")})),de.addControl(fe,2,1);const me=new Gw;me.width=.95,me.height=.72,me.name="rDecField",me.fontSize=b,me.text=ue.r.toString(),me.color=C,me.background=S,me.onFocusObservable.add((()=>{R=me.name,I=me.text,Ie(!1)})),me.onBlurObservable.add((()=>{0!=parseFloat(me.text)&&""!=me.text||(me.text="0",Ae(me,"r")),R==me.name&&(R="")})),me.onTextChangedObservable.add((()=>{R==me.name&&Ae(me,"r")})),de.addControl(me,0,2);const ge=new Gw;ge.width=.95,ge.height=.72,ge.name="gDecField",ge.fontSize=b,ge.text=ue.g.toString(),ge.color=C,ge.background=S,ge.onFocusObservable.add((()=>{R=ge.name,I=ge.text,Ie(!1)})),ge.onBlurObservable.add((()=>{0!=parseFloat(ge.text)&&""!=ge.text||(ge.text="0",Ae(ge,"g")),R==ge.name&&(R="")})),ge.onTextChangedObservable.add((()=>{R==ge.name&&Ae(ge,"g")})),de.addControl(ge,1,2);const ve=new Gw;ve.width=.95,ve.height=.72,ve.name="bDecField",ve.fontSize=b,ve.text=ue.b.toString(),ve.color=C,ve.background=S,ve.onFocusObservable.add((()=>{R=ve.name,I=ve.text,Ie(!1)})),ve.onBlurObservable.add((()=>{0!=parseFloat(ve.text)&&""!=ve.text||(ve.text="0",Ae(ve,"b")),R==ve.name&&(R="")})),ve.onTextChangedObservable.add((()=>{R==ve.name&&Ae(ve,"b")})),de.addControl(ve,2,2);const xe=new zw;xe.name="Hex Value",xe.width=.82,xe.addRowDefinition(1,!1),xe.addColumnDefinition(.1,!1),xe.addColumnDefinition(.9,!1),ce.addControl(xe,2,0);const be=new Fw;be.text="#",be.color=c,be.fontSize=b,xe.addControl(be,0,0);const Te=new Gw;Te.width=.96,Te.height=.72,Te.name="hexField",Te.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_CENTER,Te.fontSize=b;const ye=t.lastColor.split("#");function Se(e,t){R=t;const i=e.toHexString();if(ee.background=i,_e.name!=R&&(_e.text=Math.floor(255*e.r).toString()),pe.name!=R&&(pe.text=Math.floor(255*e.g).toString()),fe.name!=R&&(fe.text=Math.floor(255*e.b).toString()),me.name!=R&&(me.text=e.r.toString()),ge.name!=R&&(ge.text=e.g.toString()),ve.name!=R&&(ve.text=e.b.toString()),Te.name!=R){const e=i.split("#");Te.text=e[1]}z.name!=R&&(z.value=e)}function Ce(e,t){let i=e.text;if(/[^0-9]/g.test(i))e.text=I;else if(""!=i&&(Math.floor(parseInt(i))<0?i="0":Math.floor(parseInt(i))>255?i="255":isNaN(parseInt(i))&&(i="0")),R==e.name&&(I=i),""!=i){i=parseInt(i).toString(),e.text=i;const s=Ee.FromHexString(ee.background);R==e.name&&Se("r"==t?new Ee(parseInt(i)/255,s.g,s.b):"g"==t?new Ee(s.r,parseInt(i)/255,s.b):new Ee(s.r,s.g,parseInt(i)/255),e.name)}}function Ae(e,t){let i=e.text;if(/[^0-9.]/g.test(i))return void(e.text=I);""!=i&&"."!=i&&0!=parseFloat(i)&&(parseFloat(i)<0?i="0.0":parseFloat(i)>1?i="1.0":isNaN(parseFloat(i))&&(i="0.0")),R==e.name&&(I=i),""!=i&&"."!=i&&0!=parseFloat(i)?(i=parseFloat(i).toString(),e.text=i):i="0.0";const s=Ee.FromHexString(ee.background);R==e.name&&Se("r"==t?new Ee(parseFloat(i),s.g,s.b):"g"==t?new Ee(s.r,parseFloat(i),s.b):new Ee(s.r,s.g,parseFloat(i)),e.name)}function Pe(){if(t.savedColors&&t.savedColors[E]){let e;e=M?"b":"";const i=Bw.CreateSimpleButton("Swatch_"+E,e);i.fontFamily="coreglyphs";const s=Ee.FromHexString(t.savedColors[E]),r=s.r+s.g+s.b;i.color=r>g?v:x,i.fontSize=Math.floor(.7*a),i.textBlock.verticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,i.height=i.width=a.toString()+"px",i.background=t.savedColors[E],i.thickness=2;const n=E;return i.pointerDownAnimation=()=>{i.thickness=4},i.pointerUpAnimation=()=>{i.thickness=3},i.pointerEnterAnimation=()=>{i.thickness=3},i.pointerOutAnimation=()=>{i.thickness=2},i.onPointerClickObservable.add((()=>{var e;M?(e=n,t.savedColors&&t.savedColors.splice(e,1),t.savedColors&&0==t.savedColors.length&&(Me(!1),M=!1),Re("",P)):t.savedColors&&Se(Ee.FromHexString(t.savedColors[n]),i.name)})),i}return null}function Ie(e){let t;if(void 0!==e&&(M=e),M){for(let e=0;ei*t.numSwatchesPerLine?t.numSwatchesPerLine:t.savedColors.length-(i-1)*t.numSwatchesPerLine;const r=Math.min(Math.max(s,0),t.numSwatchesPerLine);for(let i=0,s=1;it.numSwatchesPerLine)continue;const r=Pe();null!=r&&(A.addControl(r,e,s),s+=2,E++)}}t.savedColors.length>=t.swatchLimit?Oe(i,!0):Oe(i,!1)}}function Me(e){e?(T=Bw.CreateSimpleButton("butEdit","Edit"),T.width=oe,T.height=ae,T.left=Math.floor(.1*parseInt(oe)).toString()+"px",T.top=(-1*parseFloat(T.left)).toString()+"px",T.verticalAlignment=Ow.VERTICAL_ALIGNMENT_BOTTOM,T.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,T.thickness=2,T.color=c,T.fontSize=b,T.background=u,T.onPointerEnterObservable.add((()=>{T.background=d})),T.onPointerOutObservable.add((()=>{T.background=u})),T.pointerDownAnimation=()=>{T.background=_},T.pointerUpAnimation=()=>{T.background=d},T.onPointerClickObservable.add((()=>{M=!M,Ie()})),G.addControl(T,1,0)):G.removeControl(T)}function Oe(e,t){t?(e.color=p,e.background=f):(e.color=c,e.background=u)}function De(s){t.savedColors&&t.savedColors.length>0?i({savedColors:t.savedColors,pickedColor:s}):i({pickedColor:s}),e.removeControl(O)}Te.text=ye[1],Te.color=C,Te.background=S,Te.onFocusObservable.add((()=>{R=Te.name,I=Te.text,Ie(!1)})),Te.onBlurObservable.add((()=>{if(3==Te.text.length){const e=Te.text.split("");Te.text=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]}""==Te.text&&(Te.text="000000",Se(Ee.FromHexString(Te.text),"b")),R==Te.name&&(R="")})),Te.onTextChangedObservable.add((()=>{let e=Te.text;const t=/[^0-9A-F]/i.test(e);if((Te.text.length>6||t)&&R==Te.name)Te.text=I;else{if(Te.text.length<6){const t=6-Te.text.length;for(let i=0;i0&&Re("",P)}))}}Ww._Epsilon=1e-6,Ze([rt()],Ww.prototype,"value",null),Ze([rt()],Ww.prototype,"width",null),Ze([rt()],Ww.prototype,"height",null),Ze([rt()],Ww.prototype,"size",null),z("BABYLON.GUI.ColorPicker",Ww);class Hw extends Dw{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thickness=1}_getTypeName(){return"Ellipse"}_localDraw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),Ow.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,e),(this._backgroundGradient||this._background)&&(e.fillStyle=this._getBackgroundColor(e),e.fill()),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this._thickness&&(this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.stroke()),e.restore()}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._measureForChildren.width-=2*this._thickness,this._measureForChildren.height-=2*this._thickness,this._measureForChildren.left+=this._thickness,this._measureForChildren.top+=this._thickness}_clipForChildren(e){Ow.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2,this._currentMeasure.height/2,e),e.clip()}_renderHighlightSpecific(e){Ow.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._highlightLineWidth/2,this._currentMeasure.height/2-this._highlightLineWidth/2,e),e.stroke()}}Ze([rt()],Hw.prototype,"thickness",null),z("BABYLON.GUI.Ellipse",Hw);class Xw extends Bw{constructor(e){super(e),this.name=e,this.focusedColor=null,this._isFocused=!1,this._unfocusedColor=null,this.onFocusObservable=new K,this.onBlurObservable=new K,this.onKeyboardEventProcessedObservable=new K,this._unfocusedColor=this.color}onBlur(){this._isFocused&&(this._isFocused=!1,this.focusedColor&&null!=this._unfocusedColor&&(this.color=this._unfocusedColor),this.onBlurObservable.notifyObservers(this))}onFocus(){this._isFocused=!0,this.focusedColor&&(this._unfocusedColor=this.color,this.color=this.focusedColor),this.onFocusObservable.notifyObservers(this)}keepsFocusWith(){return null}focus(){this._host.moveFocusToControl(this)}blur(){this._host.focusedControl=null}processKeyboard(e){this.onKeyboardEventProcessedObservable.notifyObservers(e,-1,this)}_onPointerDown(e,t,i,s,r){return this.isReadOnly||this.focus(),super._onPointerDown(e,t,i,s,r)}dispose(){super.dispose(),this.onBlurObservable.clear(),this.onFocusObservable.clear(),this.onKeyboardEventProcessedObservable.clear()}}z("BABYLON.GUI.FocusableButton",Xw);class Yw extends Gw{get autoStretchHeight(){return this._autoStretchHeight}set autoStretchHeight(e){this._autoStretchHeight!==e&&(this._autoStretchHeight=e,this._markAsDirty())}set height(e){this.fixedRatioMasterIsWidth=!1,this._height.toString(this._host)!==e&&(this._height.fromString(e)&&this._markAsDirty(),this._autoStretchHeight=!1)}get maxHeight(){return this._maxHeight.toString(this._host)}get maxHeightInPixels(){return this._maxHeight.getValueInPixel(this._host,this._cachedParentMeasure.height)}set maxHeight(e){this._maxHeight.toString(this._host)!==e&&this._maxHeight.fromString(e)&&this._markAsDirty()}constructor(e,t=""){super(e),this.name=e,this._textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._textVerticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,this._prevText=this.text,this._lineSpacing=new yw(0),this._maxHeight=new yw(1,yw.UNITMODE_PERCENTAGE,!1),this.onLinesReadyObservable=new K,this.text=t,this.isPointerBlocker=!0,this.onLinesReadyObservable.add((()=>this._updateCursorPosition())),this._highlightCursorInfo={initialStartIndex:-1,initialRelativeStartIndex:-1,initialLineIndex:-1},this._cursorInfo={globalStartIndex:0,globalEndIndex:0,relativeEndIndex:0,relativeStartIndex:0,currentLineIndex:0}}_getTypeName(){return"InputTextArea"}processKeyboard(e){this.isReadOnly||(this.alternativeProcessKey(e.code,e.key,e),this.onKeyboardEventProcessedObservable.notifyObservers(e))}alternativeProcessKey(e,t,i){if(!i||!i.ctrlKey&&!i.metaKey||"KeyC"!==e&&"KeyV"!==e&&"KeyX"!==e){switch(e){case"KeyA":if(i&&(i.ctrlKey||i.metaKey))return this._selectAllText(),void i.preventDefault();break;case"Period":i&&i.shiftKey&&i.preventDefault();break;case"Backspace":!this._isTextHighlightOn&&this._cursorInfo.globalStartIndex>0&&(this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex--),this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,i&&i.preventDefault(),this._blinkIsEven=!1,this._isTextHighlightOn=!1,this._textHasChanged();break;case"Delete":!this._isTextHighlightOn&&this._cursorInfo.globalEndIndexthis._highlightCursorInfo.initialStartIndex?this._cursorInfo.globalEndIndex--:this._cursorInfo.globalStartIndex--:(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex--,this._isTextHighlightOn=!0),this._blinkIsEven=!0,void i.preventDefault()):(this._isTextHighlightOn?this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex:i&&(i.ctrlKey||i.metaKey)?(this._cursorInfo.globalStartIndex-=this._cursorInfo.relativeStartIndex,i.preventDefault()):this._cursorInfo.globalStartIndex>0&&this._cursorInfo.globalStartIndex--,this._blinkIsEven=!1,void(this._isTextHighlightOn=!1));case"ArrowRight":if(this._markAsDirty(),i&&i.shiftKey){if(i.ctrlKey||i.metaKey){const e=this._lines[this._cursorInfo.currentLineIndex].text.length-this._cursorInfo.relativeEndIndex-1;this._cursorInfo.globalEndIndex+=e,this._cursorInfo.globalStartIndex=this._highlightCursorInfo.initialStartIndex}return this._isTextHighlightOn?this._cursorInfo.globalStartIndexa&&l>0&&i--,this._isTextHighlightOn?this._cursorInfo.currentLineIndex<=this._highlightCursorInfo.initialLineIndex?(this._cursorInfo.globalStartIndex=i,this._cursorInfo.globalEndIndex=this._highlightCursorInfo.initialStartIndex,this._cursorInfo.relativeEndIndex=this._highlightCursorInfo.initialRelativeStartIndex):this._cursorInfo.globalEndIndex=i:this._cursorInfo.globalStartIndex=i}return void this._markAsDirty();case"ArrowDown":if(this._blinkIsEven=!1,i&&(i.shiftKey?(this._isTextHighlightOn||(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex),this._isTextHighlightOn=!0,this._blinkIsEven=!0):this._isTextHighlightOn=!1,i.preventDefault()),this._cursorInfo.currentLineIndex===this._lines.length-1)this._cursorInfo.globalStartIndex=this.text.length;else{const e=this._lines[this._cursorInfo.currentLineIndex],t=this._lines[this._cursorInfo.currentLineIndex+1];let i=0,s=0;!this._isTextHighlightOn||this._cursorInfo.currentLineIndexa&&l>0&&i--,this._isTextHighlightOn?this._cursorInfo.currentLineIndexthis._cursorInfo.globalEndIndex&&(this._cursorInfo.globalEndIndex+=this._cursorInfo.globalStartIndex,this._cursorInfo.globalStartIndex=this._cursorInfo.globalEndIndex-this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex-=this._cursorInfo.globalStartIndex)):(this._cursorInfo.globalEndIndex=i,this._cursorInfo.globalStartIndex=this._highlightCursorInfo.initialStartIndex):this._cursorInfo.globalStartIndex=i}return void this._markAsDirty()}1===t?.length&&(i?.preventDefault(),this._currentKey=t,this.onBeforeKeyAddObservable.notifyObservers(this),t=this._currentKey,this._addKey&&(this._isTextHighlightOn=!1,this._blinkIsEven=!1,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex,t),this._cursorInfo.globalStartIndex+=t.length,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._textHasChanged()))}}_parseLineWordWrap(e="",t,i){const s=[],r=e.split(" ");let n=0;for(let o=0;o0?e+" "+r[o]:r[0],l=i.measureText(a).width;if(l>t){o>0&&(n=i.measureText(e).width,s.push({text:e,width:n,lineEnding:" "})),e=r[o];let a="";e.split("").map((e=>{i.measureText(a+e).width>t&&(s.push({text:a,width:i.measureText(a).width,lineEnding:""}),a=""),a+=e})),e=a,n=i.measureText(e).width}else n=l,e=a}return s.push({text:e,width:n,lineEnding:" "}),s}_breakLines(e,t){const i=[],s=(this.text||this.placeholderText).split("\n");if(this.clipContent)for(const r of s)i.push(...this._parseLineWordWrap(r,e,t));else for(const e of s)i.push(this._parseLine(e,t));return i[i.length-1].lineEnding="\n",i}_parseLine(e="",t){return{text:e,width:t.measureText(e).width,lineEnding:" "}}_preMeasure(e,t){this._fontOffset&&!this._wasDirty||(this._fontOffset=Ow._GetFontOffset(t.font,this._host.getScene()?.getEngine()));let i=this._beforeRenderText(this._textWrapper).text;!this.text&&this._placeholderText&&(i=this._placeholderText),this._textWidth=t.measureText(i).width;const s=2*this._margin.getValueInPixel(this._host,e.width);if(this._autoStretchWidth){const r=i.split("\n").reduce(((e,i)=>t.measureText(i).width>t.measureText(e).width?i:e),""),n=t.measureText(r).width;this.width=Math.min(this._maxWidth.getValueInPixel(this._host,e.width),n+s)+"px",this.autoStretchWidth=!0}if(this._availableWidth=this._width.getValueInPixel(this._host,e.width)-s,this._lines=this._breakLines(this._availableWidth,t),this._contextForBreakLines=t,this._autoStretchHeight){const t=this._lines.length*this._fontOffset.height+2*this._margin.getValueInPixel(this._host,e.height);this.height=Math.min(this._maxHeight.getValueInPixel(this._host,e.height),t)+"px",this._autoStretchHeight=!0}if(this._availableHeight=this._height.getValueInPixel(this._host,e.height)-s,this._isFocused){this._cursorInfo.currentLineIndex=0;let e=this._lines[this._cursorInfo.currentLineIndex].text.length+this._lines[this._cursorInfo.currentLineIndex].lineEnding.length,t=0;for(;t+e<=this._cursorInfo.globalStartIndex;)t+=e,this._cursorInfo.currentLineIndexthis._availableWidth){const e=this._clipTextLeft-this._lines[this._cursorInfo.currentLineIndex].width+this._availableWidth;this._scrollLeft||(this._scrollLeft=e)}else this._scrollLeft=this._clipTextLeft;if(this._isFocused&&!this._autoStretchHeight){const e=(this._cursorInfo.currentLineIndex+1)*this._fontOffset.height,t=this._clipTextTop-e;this._scrollTop||(this._scrollTop=t)}else this._scrollTop=this._clipTextTop}_additionalProcessing(){this.highlightedText="",this.onLinesReadyObservable.notifyObservers(this)}_drawText(e,t,i,s){const r=this._currentMeasure.width;let n=this._scrollLeft;switch(this._textHorizontalAlignment){case Ow.HORIZONTAL_ALIGNMENT_LEFT:n+=0;break;case Ow.HORIZONTAL_ALIGNMENT_RIGHT:n+=r-t;break;case Ow.HORIZONTAL_ALIGNMENT_CENTER:n+=(r-t)/2}(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(s.shadowColor=this.shadowColor,s.shadowBlur=this.shadowBlur,s.shadowOffsetX=this.shadowOffsetX,s.shadowOffsetY=this.shadowOffsetY),this.outlineWidth&&s.strokeText(e,this._currentMeasure.left+n,i),s.fillText(e,n,i)}_onCopyText(e){this._isTextHighlightOn=!1;try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText}_onCutText(e){if(this._highlightedText){try{e.clipboardData&&e.clipboardData.setData("text/plain",this._highlightedText)}catch{}this._host.clipboardData=this._highlightedText,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),this._textHasChanged()}}_onPasteText(e){let t="";t=e.clipboardData&&-1!==e.clipboardData.types.indexOf("text/plain")?e.clipboardData.getData("text/plain"):this._host.clipboardData,this._isTextHighlightOn=!1,this._prevText=this._textWrapper.text,this._textWrapper.removePart(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex,t);const i=t.length-(this._cursorInfo.globalEndIndex-this._cursorInfo.globalStartIndex);this._cursorInfo.globalStartIndex+=i,this._cursorInfo.globalEndIndex=this._cursorInfo.globalStartIndex,this._textHasChanged()}_draw(e){this._computeScroll(),this._scrollLeft=this._scrollLeft??0,this._scrollTop=this._scrollTop??0,e.save(),this._applyStates(e),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._isFocused?this._focusedBackground&&(e.fillStyle=this._isEnabled?this._focusedBackground:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)):this._background&&(e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height)),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),this.color&&(e.fillStyle=this.color);const t=this._currentMeasure.height,i=this._currentMeasure.width;let s=0;switch(this._textVerticalAlignment){case Ow.VERTICAL_ALIGNMENT_TOP:s=this._fontOffset.ascent;break;case Ow.VERTICAL_ALIGNMENT_BOTTOM:s=t-this._fontOffset.height*(this._lines.length-1)-this._fontOffset.descent;break;case Ow.VERTICAL_ALIGNMENT_CENTER:s=this._fontOffset.ascent+(t-this._fontOffset.height*this._lines.length)/2}e.save(),e.beginPath(),e.fillStyle=this.fontStyle,!this._textWrapper.text&&this.placeholderText&&(e.fillStyle=this._placeholderColor),e.rect(this._clipTextLeft,this._clipTextTop,this._availableWidth+2,this._availableHeight+2),e.clip(),s+=this._scrollTop;for(let t=0;tthis._clipTextLeft+this._availableWidth&&(this._scrollLeft+=this._clipTextLeft+this._availableWidth-t,t=this._clipTextLeft+this._availableWidth,this._markAsDirty());let i=this._scrollTop+this._cursorInfo.currentLineIndex*this._fontOffset.height;ithis._clipTextTop+this._availableHeight&&(this._scrollTop+=this._clipTextTop+this._availableHeight-i-this._fontOffset.height,i=this._clipTextTop+this._availableHeight-this._fontOffset.height,this._markAsDirty()),this._isTextHighlightOn||e.fillRect(t,i,2,this._fontOffset.height)}if(this._resetBlinking(),this._isTextHighlightOn){clearTimeout(this._blinkTimeout),this._highlightedText=this.text.substring(this._cursorInfo.globalStartIndex,this._cursorInfo.globalEndIndex),e.globalAlpha=this._highligherOpacity,e.fillStyle=this._textHighlightColor;const t=Math.min(this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialLineIndex),s=Math.max(this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialLineIndex);let r=this._scrollTop+t*this._fontOffset.height;for(let n=t;n<=s;n++){const o=this._lines[n];let a=this._scrollLeft;switch(this._textHorizontalAlignment){case Ow.HORIZONTAL_ALIGNMENT_LEFT:a+=0;break;case Ow.HORIZONTAL_ALIGNMENT_RIGHT:a+=i-o.width;break;case Ow.HORIZONTAL_ALIGNMENT_CENTER:a+=(i-o.width)/2}const l=n===t?this._cursorInfo.relativeStartIndex:0,h=n===s?this._cursorInfo.relativeEndIndex:o.text.length,c=e.measureText(o.text.substr(0,l)).width,u=o.text.substring(l,h),d=e.measureText(u).width;e.fillRect(a+c,r,d,this._fontOffset.height),r+=this._fontOffset.height}this._cursorInfo.globalEndIndex===this._cursorInfo.globalStartIndex&&this._resetBlinking()}}e.restore(),this._thickness&&(this._isFocused?this.focusedColor&&(e.strokeStyle=this.focusedColor):this.color&&(e.strokeStyle=this.color),e.lineWidth=this._thickness,e.strokeRect(this._currentMeasure.left+this._thickness/2,this._currentMeasure.top+this._thickness/2,this._currentMeasure.width-this._thickness,this._currentMeasure.height-this._thickness))}_resetBlinking(){clearTimeout(this._blinkTimeout),this._blinkTimeout=setTimeout((()=>{this._blinkIsEven=!this._blinkIsEven,this._markAsDirty()}),500)}_onPointerDown(e,t,i,s,r){return!(!super._onPointerDown(e,t,i,s,r)||!this.isReadOnly&&(this._clickedCoordinateX=t.x,this._clickedCoordinateY=t.y,this._isTextHighlightOn=!1,this._highlightedText="",this._isPointerDown=!0,this._host._capturingControl[i]=this,this._host.focusedControl===this?(clearTimeout(this._blinkTimeout),this._markAsDirty(),0):!this._isEnabled||(this._host.focusedControl=this,0)))}_onPointerMove(e,t,i,s){0===s.event.movementX&&0===s.event.movementY||(this._host.focusedControl===this&&this._isPointerDown&&!this.isReadOnly&&(this._clickedCoordinateX=t.x,this._clickedCoordinateY=t.y,this._isTextHighlightOn||(this._highlightCursorInfo.initialLineIndex=this._cursorInfo.currentLineIndex,this._highlightCursorInfo.initialStartIndex=this._cursorInfo.globalStartIndex,this._highlightCursorInfo.initialRelativeStartIndex=this._cursorInfo.relativeStartIndex,this._isTextHighlightOn=!0),this._markAsDirty()),super._onPointerMove(e,t,i,s))}_updateCursorPosition(){if(this._isFocused)if(!this._textWrapper.text&&this.placeholderText)this._cursorInfo.currentLineIndex=0,this._cursorInfo.globalStartIndex=0,this._cursorInfo.globalEndIndex=0,this._cursorInfo.relativeStartIndex=0,this._cursorInfo.relativeEndIndex=0;else if(this._clickedCoordinateX&&this._clickedCoordinateY){this._isTextHighlightOn||(this._cursorInfo={globalStartIndex:0,globalEndIndex:0,relativeStartIndex:0,relativeEndIndex:0,currentLineIndex:0});let e=0,t=0;const i=this._clickedCoordinateY-this._scrollTop,s=Math.floor(i/this._fontOffset.height);this._cursorInfo.currentLineIndex=Math.min(Math.max(s,0),this._lines.length-1);let r=0;const n=this._clickedCoordinateX-(this._scrollLeft??0);let o=0;for(let t=0;tt;)t++,o=Math.abs(n-r),r=this._contextForBreakLines.measureText(this._lines[this._cursorInfo.currentLineIndex].text.substr(0,t)).width;Math.abs(n-r)>o&&t>0&&t--,e+=t,this._isTextHighlightOn?e=this._highlightCursorInfo.initialStartIndex){for(;t+e<=this._cursorInfo.globalEndIndex;)t+=e,this._cursorInfo.currentLineIndex0&&this._textWrapper.isWord(this._cursorInfo.globalStartIndex-1)?--this._cursorInfo.globalStartIndex:0,i=this._cursorInfo.globalEndIndexthis._markAsDirty()))),this._connectedControl=e,this._markAsDirty())}get x1(){return this._x1.toString(this._host)}set x1(e){this._x1.toString(this._host)!==e&&this._x1.fromString(e)&&this._markAsDirty()}get y1(){return this._y1.toString(this._host)}set y1(e){this._y1.toString(this._host)!==e&&this._y1.fromString(e)&&this._markAsDirty()}get x2(){return this._x2.toString(this._host)}set x2(e){this._x2.toString(this._host)!==e&&this._x2.fromString(e)&&this._markAsDirty()}get y2(){return this._y2.toString(this._host)}set y2(e){this._y2.toString(this._host)!==e&&this._y2.fromString(e)&&this._markAsDirty()}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth!==e&&(this._lineWidth=e,this._markAsDirty())}set horizontalAlignment(e){}set verticalAlignment(e){}get _effectiveX2(){return(this._connectedControl?this._connectedControl.centerX:0)+this._x2.getValue(this._host)}get _effectiveY2(){return(this._connectedControl?this._connectedControl.centerY:0)+this._y2.getValue(this._host)}constructor(e){super(e),this.name=e,this._lineWidth=1,this._x1=new yw(0),this._y1=new yw(0),this._x2=new yw(0),this._y2=new yw(0),this._dash=new Array,this._automaticSize=!0,this.isHitTestVisible=!1,this._horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP}_getTypeName(){return"Line"}_draw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._applyStates(e),e.strokeStyle=this._getColor(e),e.lineWidth=this._lineWidth,e.setLineDash(this._dash),e.beginPath(),e.moveTo(this._cachedParentMeasure.left+this._x1.getValue(this._host),this._cachedParentMeasure.top+this._y1.getValue(this._host)),e.lineTo(this._cachedParentMeasure.left+this._effectiveX2,this._cachedParentMeasure.top+this._effectiveY2),e.stroke(),e.restore()}_measure(){this._currentMeasure.width=Math.abs(this._x1.getValue(this._host)-this._effectiveX2)+this._lineWidth,this._currentMeasure.height=Math.abs(this._y1.getValue(this._host)-this._effectiveY2)+this._lineWidth}_computeAlignment(e){this._currentMeasure.left=e.left+Math.min(this._x1.getValue(this._host),this._effectiveX2)-this._lineWidth/2,this._currentMeasure.top=e.top+Math.min(this._y1.getValue(this._host),this._effectiveY2)-this._lineWidth/2}moveToVector3(e,t,i=!1){if(!this._host||this.parent!==this._host._rootContainer)return void Ds.Error("Cannot move a control to a vector3 if the control is not at root level");const s=this._host._getGlobalViewport(),r=_e.Project(e,me.IdentityReadOnly,t.getTransformMatrix(),s);this._moveToProjectedPosition(r,i),r.z<0||r.z>1?this.notRenderable=!0:this.notRenderable=!1}_moveToProjectedPosition(e,t=!1){const i=e.x+this._linkOffsetX.getValue(this._host)+"px",s=e.y+this._linkOffsetY.getValue(this._host)+"px";t?(this.x2=i,this.y2=s,this._x2.ignoreAdaptiveScaling=!0,this._y2.ignoreAdaptiveScaling=!0):(this.x1=i,this.y1=s,this._x1.ignoreAdaptiveScaling=!0,this._y1.ignoreAdaptiveScaling=!0)}}Ze([rt()],jw.prototype,"dash",null),Ze([rt()],jw.prototype,"x1",null),Ze([rt()],jw.prototype,"y1",null),Ze([rt()],jw.prototype,"x2",null),Ze([rt()],jw.prototype,"y2",null),Ze([rt()],jw.prototype,"lineWidth",null),z("BABYLON.GUI.Line",jw);class Kw{constructor(e){this._multiLine=e,this._x=new yw(0),this._y=new yw(0),this._point=new _e(0,0,0)}get x(){return this._x.toString(this._multiLine._host)}set x(e){this._x.toString(this._multiLine._host)!==e&&this._x.fromString(e)&&this._multiLine._markAsDirty()}get y(){return this._y.toString(this._multiLine._host)}set y(e){this._y.toString(this._multiLine._host)!==e&&this._y.fromString(e)&&this._multiLine._markAsDirty()}get control(){return this._control}set control(e){this._control!==e&&(this._control&&this._controlObserver&&(this._control.onDirtyObservable.remove(this._controlObserver),this._controlObserver=null),this._control=e,this._control&&(this._controlObserver=this._control.onDirtyObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())}get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh&&this._meshObserver&&this._mesh.getScene().onAfterCameraRenderObservable.remove(this._meshObserver),this._mesh=e,this._mesh&&(this._meshObserver=this._mesh.getScene().onAfterCameraRenderObservable.add(this._multiLine.onPointUpdate)),this._multiLine._markAsDirty())}resetLinks(){this.control=null,this.mesh=null}translate(){return this._point=this._translatePoint(),this._point}_translatePoint(){if(null!=this._mesh)return this._multiLine._host.getProjectedPositionWithZ(this._mesh.getBoundingInfo().boundingSphere.center,this._mesh.getWorldMatrix());if(null!=this._control)return new _e(this._control.centerX,this._control.centerY,1-J);{const e=this._multiLine._host,t=this._x.getValueInPixel(e,Number(e._canvas.width)),i=this._y.getValueInPixel(e,Number(e._canvas.height));return new _e(t,i,1-J)}}dispose(){this.resetLinks()}}class $w extends Ow{constructor(e){super(e),this.name=e,this._lineWidth=1,this.onPointUpdate=()=>{this._markAsDirty()},this._automaticSize=!0,this.isHitTestVisible=!1,this._horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,this._dash=[],this._points=[]}get dash(){return this._dash}set dash(e){this._dash!==e&&(this._dash=e,this._markAsDirty())}getAt(e){return this._points[e]||(this._points[e]=new Kw(this)),this._points[e]}add(...e){return e.map((e=>this.push(e)))}push(e){const t=this.getAt(this._points.length);return null==e||(e instanceof _o?t.mesh=e:e instanceof Ow?t.control=e:null!=e.x&&null!=e.y&&(t.x=e.x,t.y=e.y)),t}remove(e){let t;if(e instanceof Kw){if(t=this._points.indexOf(e),-1===t)return}else t=e;const i=this._points[t];i&&(i.dispose(),this._points.splice(t,1))}reset(){for(;this._points.length>0;)this.remove(this._points.length-1)}resetLinks(){this._points.forEach((e=>{null!=e&&e.resetLinks()}))}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth!==e&&(this._lineWidth=e,this._markAsDirty())}set horizontalAlignment(e){}set verticalAlignment(e){}_getTypeName(){return"MultiLine"}_draw(e){e.save(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),this._applyStates(e),e.strokeStyle=this.color,e.lineWidth=this._lineWidth,e.setLineDash(this._dash),e.beginPath();let t,i=!0;this._points.forEach((s=>{s&&(i?(e.moveTo(s._point.x,s._point.y),i=!1):s._point.z<1&&t.z<1?e.lineTo(s._point.x,s._point.y):e.moveTo(s._point.x,s._point.y),t=s._point)})),e.stroke(),e.restore()}_additionalProcessing(){this._minX=null,this._minY=null,this._maxX=null,this._maxY=null,this._points.forEach((e=>{e&&(e.translate(),(null==this._minX||e._point.xthis._maxX)&&(this._maxX=e._point.x),(null==this._maxY||e._point.y>this._maxY)&&(this._maxY=e._point.y))})),null==this._minX&&(this._minX=0),null==this._minY&&(this._minY=0),null==this._maxX&&(this._maxX=0),null==this._maxY&&(this._maxY=0)}_measure(){null!=this._minX&&null!=this._maxX&&null!=this._minY&&null!=this._maxY&&(this._currentMeasure.width=Math.abs(this._maxX-this._minX)+this._lineWidth,this._currentMeasure.height=Math.abs(this._maxY-this._minY)+this._lineWidth)}_computeAlignment(){null!=this._minX&&null!=this._minY&&(this._currentMeasure.left=this._minX-this._lineWidth/2,this._currentMeasure.top=this._minY-this._lineWidth/2)}dispose(){this.reset(),super.dispose()}}Ze([rt()],$w.prototype,"dash",null),z("BABYLON.GUI.MultiLine",$w);class qw extends Ow{get thickness(){return this._thickness}set thickness(e){this._thickness!==e&&(this._thickness=e,this._markAsDirty())}get checkSizeRatio(){return this._checkSizeRatio}set checkSizeRatio(e){e=Math.max(Math.min(1,e),0),this._checkSizeRatio!==e&&(this._checkSizeRatio=e,this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get isChecked(){return this._isChecked}set isChecked(e){this._isChecked!==e&&(this._isChecked=e,this._markAsDirty(),this.onIsCheckedChangedObservable.notifyObservers(e),this._isChecked&&this._host&&this._host.executeOnAllControls((e=>{if(e===this)return;if(void 0===e.group)return;const t=e;t.group===this.group&&(t.isChecked=!1)})))}constructor(e){super(e),this.name=e,this._isChecked=!1,this._background="black",this._checkSizeRatio=.8,this._thickness=1,this.group="",this.onIsCheckedChangedObservable=new K,this.isPointerBlocker=!0}_getTypeName(){return"RadioButton"}_draw(e){e.save(),this._applyStates(e);const t=this._currentMeasure.width-this._thickness,i=this._currentMeasure.height-this._thickness;if((this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowColor=this.shadowColor,e.shadowBlur=this.shadowBlur,e.shadowOffsetX=this.shadowOffsetX,e.shadowOffsetY=this.shadowOffsetY),Ow.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,this._currentMeasure.width/2-this._thickness/2,this._currentMeasure.height/2-this._thickness/2,e),e.fillStyle=this._isEnabled?this._background:this._disabledColor,e.fill(),(this.shadowBlur||this.shadowOffsetX||this.shadowOffsetY)&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),e.strokeStyle=this.color,e.lineWidth=this._thickness,e.stroke(),this._isChecked){e.fillStyle=this._isEnabled?this.color:this._disabledColor;const s=t*this._checkSizeRatio,r=i*this._checkSizeRatio;Ow.drawEllipse(this._currentMeasure.left+this._currentMeasure.width/2,this._currentMeasure.top+this._currentMeasure.height/2,s/2-this._thickness/2,r/2-this._thickness/2,e),e.fill()}e.restore()}_onPointerDown(e,t,i,s,r){return!!super._onPointerDown(e,t,i,s,r)&&(this.isReadOnly||this.isChecked||(this.isChecked=!0),!0)}static AddRadioButtonWithHeader(e,t,i,s){const r=new kw;r.isVertical=!1,r.height="30px";const n=new qw;n.width="20px",n.height="20px",n.isChecked=i,n.color="green",n.group=t,n.onIsCheckedChangedObservable.add((e=>s(n,e))),r.addControl(n);const o=new Fw;return o.text=e,o.width="180px",o.paddingLeft="5px",o.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,o.color="white",r.addControl(o),r}}Ze([rt()],qw.prototype,"thickness",null),Ze([rt()],qw.prototype,"group",void 0),Ze([rt()],qw.prototype,"checkSizeRatio",null),Ze([rt()],qw.prototype,"background",null),Ze([rt()],qw.prototype,"isChecked",null),z("BABYLON.GUI.RadioButton",qw);class Zw extends Ow{get displayThumb(){return this._displayThumb}set displayThumb(e){this._displayThumb!==e&&(this._displayThumb=e,this._markAsDirty())}get step(){return this._step}set step(e){this._step!==e&&(this._step=e,this._markAsDirty())}get barOffset(){return this._barOffset.toString(this._host)}get barOffsetInPixels(){return this._barOffset.getValueInPixel(this._host,this._cachedParentMeasure.width)}set barOffset(e){this._barOffset.toString(this._host)!==e&&this._barOffset.fromString(e)&&this._markAsDirty()}get thumbWidth(){return this._thumbWidth.toString(this._host)}get thumbWidthInPixels(){return this._thumbWidth.getValueInPixel(this._host,this._cachedParentMeasure.width)}set thumbWidth(e){this._thumbWidth.toString(this._host)!==e&&this._thumbWidth.fromString(e)&&this._markAsDirty()}get minimum(){return this._minimum}set minimum(e){this._minimum!==e&&(this._minimum=e,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))}get maximum(){return this._maximum}set maximum(e){this._maximum!==e&&(this._maximum=e,this._markAsDirty(),this.value=Math.max(Math.min(this.value,this._maximum),this._minimum))}get value(){return this._value}set value(e){e=Math.max(Math.min(e,this._maximum),this._minimum),this._value!==e&&(this._value=e,this._markAsDirty(),this.onValueChangedObservable.notifyObservers(this._value))}get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,this._markAsDirty())}get isThumbClamped(){return this._isThumbClamped}set isThumbClamped(e){this._isThumbClamped!==e&&(this._isThumbClamped=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thumbWidth=new yw(20,yw.UNITMODE_PIXEL,!1),this._minimum=0,this._maximum=100,this._value=50,this._isVertical=!1,this._barOffset=new yw(5,yw.UNITMODE_PIXEL,!1),this._isThumbClamped=!1,this._displayThumb=!0,this._step=0,this._lastPointerDownId=-1,this._effectiveBarOffset=0,this.onValueChangedObservable=new K,this._pointerIsDown=!1,this.isPointerBlocker=!0}_getTypeName(){return"BaseSlider"}_getThumbPosition(){return this.isVertical?(this.maximum-this.value)/(this.maximum-this.minimum)*this._backgroundBoxLength:(this.value-this.minimum)/(this.maximum-this.minimum)*this._backgroundBoxLength}_getThumbThickness(e){let t=0;switch(e){case"circle":t=this._thumbWidth.isPixel?Math.max(this._thumbWidth.getValue(this._host),this._backgroundBoxThickness):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host);break;case"rectangle":t=this._thumbWidth.isPixel?Math.min(this._thumbWidth.getValue(this._host),this._backgroundBoxThickness):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host)}return t}_prepareRenderingData(e){this._effectiveBarOffset=0,this._renderLeft=this._currentMeasure.left,this._renderTop=this._currentMeasure.top,this._renderWidth=this._currentMeasure.width,this._renderHeight=this._currentMeasure.height,this._backgroundBoxLength=Math.max(this._currentMeasure.width,this._currentMeasure.height),this._backgroundBoxThickness=Math.min(this._currentMeasure.width,this._currentMeasure.height),this._effectiveThumbThickness=this._getThumbThickness(e),this.displayThumb&&(this._backgroundBoxLength-=this._effectiveThumbThickness),this.isVertical&&this._currentMeasure.height=this._selectors.length))return this._selectors[e]}removeSelector(e){e<0||e>=this._selectors.length||(this._groupPanel.removeControl(this._selectors[e]),this._selectors.splice(e,1))}}class tN extends eN{addCheckbox(e,t=(e=>{}),i=!1){i=i||!1;const s=new Vw;s.width="20px",s.height="20px",s.color="#364249",s.background="#CCCCCC",s.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,s.onIsCheckedChangedObservable.add((function(e){t(e)}));const r=Ow.AddHeader(s,e,"200px",{isHorizontal:!0,controlFirst:!0});r.height="30px",r.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,r.left="4px",this.groupPanel.addControl(r),this.selectors.push(r),s.isChecked=i,this.groupPanel.parent&&this.groupPanel.parent.parent&&(s.color=this.groupPanel.parent.parent.buttonColor,s.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[1].text=t}_setSelectorLabelColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[0].background=t}}class iN extends eN{constructor(){super(...arguments),this._selectNb=0}addRadio(e,t=(e=>{}),i=!1){const s=this._selectNb++,r=new qw;r.name=e,r.width="20px",r.height="20px",r.color="#364249",r.background="#CCCCCC",r.group=this.name,r.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,r.onIsCheckedChangedObservable.add((function(e){e&&t(s)}));const n=Ow.AddHeader(r,e,"200px",{isHorizontal:!0,controlFirst:!0});n.height="30px",n.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,n.left="4px",this.groupPanel.addControl(n),this.selectors.push(n),r.isChecked=i,this.groupPanel.parent&&this.groupPanel.parent.parent&&(r.color=this.groupPanel.parent.parent.buttonColor,r.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[1].text=t}_setSelectorLabelColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[0].background=t}}class sN extends eN{addSlider(e,t=(e=>{}),i="Units",s=0,r=0,n=0,o=(e=>0|e)){const a=new Jw;a.name=i,a.value=n,a.minimum=s,a.maximum=r,a.width=.9,a.height="20px",a.color="#364249",a.background="#CCCCCC",a.borderColor="black",a.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,a.left="4px",a.paddingBottom="4px",a.onValueChangedObservable.add((function(e){a.parent.children[0].text=a.parent.children[0].name+": "+o(e)+" "+a.name,t(e)}));const l=Ow.AddHeader(a,e+": "+o(n)+" "+i,"30px",{isHorizontal:!1,controlFirst:!1});l.height="60px",l.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,l.left="4px",l.children[0].name=e,this.groupPanel.addControl(l),this.selectors.push(l),this.groupPanel.parent&&this.groupPanel.parent.parent&&(a.color=this.groupPanel.parent.parent.buttonColor,a.background=this.groupPanel.parent.parent.buttonBackground)}_setSelectorLabel(e,t){this.selectors[e].children[0].name=t,this.selectors[e].children[0].text=t+": "+this.selectors[e].children[1].value+" "+this.selectors[e].children[1].name}_setSelectorLabelColor(e,t){this.selectors[e].children[0].color=t}_setSelectorButtonColor(e,t){this.selectors[e].children[1].color=t}_setSelectorButtonBackground(e,t){this.selectors[e].children[1].background=t}}class rN extends ww{constructor(e,t=[]){if(super(e),this.name=e,this.groups=t,this._buttonColor="#364249",this._buttonBackground="#CCCCCC",this._headerColor="black",this._barColor="white",this._barHeight="2px",this._spacerHeight="20px",this._bars=new Array,this._groups=t,this.thickness=2,this._panel=new kw,this._panel.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,this._panel.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._panel.top=5,this._panel.left=5,this._panel.width=.95,t.length>0){for(let e=0;e0&&this._addSpacer(),this._panel.addControl(e.groupPanel),this._groups.push(e),e.groupPanel.children[0].color=this._headerColor;for(let t=0;t=this._groups.length)return;const t=this._groups[e];this._panel.removeControl(t.groupPanel),this._groups.splice(e,1),e=this._groups.length||(this._groups[t].groupPanel.children[0].text=e)}relabel(e,t,i){if(t<0||t>=this._groups.length)return;const s=this._groups[t];i<0||i>=s.selectors.length||s._setSelectorLabel(i,e)}removeFromGroupSelector(e,t){if(e<0||e>=this._groups.length)return;const i=this._groups[e];t<0||t>=i.selectors.length||i.removeSelector(t)}addToGroupCheckbox(e,t,i=(()=>{}),s=!1){e<0||e>=this._groups.length||this._groups[e].addCheckbox(t,i,s)}addToGroupRadio(e,t,i=(()=>{}),s=!1){e<0||e>=this._groups.length||this._groups[e].addRadio(t,i,s)}addToGroupSlider(e,t,i=(()=>{}),s="Units",r=0,n=0,o=0,a=(e=>0|e)){e<0||e>=this._groups.length||this._groups[e].addSlider(t,i,s,r,n,o,a)}}class nN extends Dw{get freezeControls(){return this._freezeControls}set freezeControls(e){if(this._freezeControls===e)return;e||this._restoreMeasures(),this._freezeControls=!1;const t=this.host.getSize(),i=t.width,s=t.height,r=this.host.getContext(),n=new Pw(0,0,i,s);this.host._numLayoutCalls=0,this.host._rootContainer._layout(n,r),e&&(this._updateMeasures(),this._useBuckets()&&this._makeBuckets()),this._freezeControls=e,this.host.markAsDirty()}get bucketWidth(){return this._bucketWidth}get bucketHeight(){return this._bucketHeight}setBucketSizes(e,t){this._bucketWidth=e,this._bucketHeight=t,this._useBuckets()?this._freezeControls&&this._makeBuckets():this._buckets={}}_useBuckets(){return this._bucketWidth>0&&this._bucketHeight>0}_makeBuckets(){this._buckets={},this._bucketLen=Math.ceil(this.widthInPixels/this._bucketWidth),this._dispatchInBuckets(this._children),this._oldLeft=null,this._oldTop=null}_dispatchInBuckets(e){for(let t=0;t0&&this._dispatchInBuckets(i._children)}}_updateMeasures(){const e=0|this.leftInPixels,t=0|this.topInPixels;this._measureForChildren.left-=e,this._measureForChildren.top-=t,this._currentMeasure.left-=e,this._currentMeasure.top-=t,this._customData.origLeftForChildren=this._measureForChildren.left,this._customData.origTopForChildren=this._measureForChildren.top,this._customData.origLeft=this._currentMeasure.left,this._customData.origTop=this._currentMeasure.top,this._updateChildrenMeasures(this._children,e,t)}_updateChildrenMeasures(e,t,i){for(let s=0;s0&&this._updateChildrenMeasures(r._children,t,i)}}_restoreMeasures(){const e=0|this.leftInPixels,t=0|this.topInPixels;this._measureForChildren.left=this._customData.origLeftForChildren+e,this._measureForChildren.top=this._customData.origTopForChildren+t,this._currentMeasure.left=this._customData.origLeft+e,this._currentMeasure.top=this._customData.origTop+t}constructor(e){super(e),this._freezeControls=!1,this._bucketWidth=0,this._bucketHeight=0,this._buckets={}}_getTypeName(){return"ScrollViewerWindow"}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._parentMeasure=e,this._measureForChildren.left=this._currentMeasure.left,this._measureForChildren.top=this._currentMeasure.top,this._measureForChildren.width=e.width,this._measureForChildren.height=e.height}_layout(e,t){return this._freezeControls?(this.invalidateRect(),!1):super._layout(e,t)}_scrollChildren(e,t,i){for(let s=0;s0&&this._scrollChildren(r._children,t,i)}}_scrollChildrenWithBuckets(e,t,i,s){const r=Math.max(0,Math.floor(-e/this._bucketWidth)),n=Math.floor((-e+this._parentMeasure.width-1)/this._bucketWidth),o=Math.floor((-t+this._parentMeasure.height-1)/this._bucketHeight);let a=Math.max(0,Math.floor(-t/this._bucketHeight));for(;a<=o;){for(let e=r;e<=n;++e){const t=a*this._bucketLen+e,r=this._buckets[t];if(r)for(let e=0;ethis._tempMeasure.left+this._tempMeasure.width||tthis._tempMeasure.top+this._tempMeasure.height)&&(this.isVertical?this.value=this.minimum+(1-(t-this._currentMeasure.top)/this._currentMeasure.height)*(this.maximum-this.minimum):this.value=this.minimum+(e-this._currentMeasure.left)/this._currentMeasure.width*(this.maximum-this.minimum)));let s=0;s=this.isVertical?-(t-this._originY)/(this._currentMeasure.height-this._effectiveThumbThickness):(e-this._originX)/(this._currentMeasure.width-this._effectiveThumbThickness),this.value+=i*s*(this.maximum-this.minimum),this._originX=e,this._originY=t}_onPointerDown(e,t,i,s,r){return this._first=!0,super._onPointerDown(e,t,i,s,r)}serialize(e){super.serialize(e),this.backgroundGradient&&(e.backgroundGradient={},this.backgroundGradient.serialize(e.backgroundGradient))}_parseFromContent(e,t){if(super._parseFromContent(e,t),e.backgroundGradient){const t=Ds.Instantiate("BABYLON.GUI."+e.backgroundGradient.className);this.backgroundGradient=new t,this.backgroundGradient.parse(e.backgroundGradient)}}}Ze([rt()],oN.prototype,"borderColor",null),Ze([rt()],oN.prototype,"background",null),Ze([rt()],oN.prototype,"invertScrollDirection",null),z("BABYLON.GUI.Scrollbar",oN);class aN extends Zw{get invertScrollDirection(){return this._invertScrollDirection}set invertScrollDirection(e){this._invertScrollDirection=e}get backgroundImage(){return this._backgroundBaseImage}set backgroundImage(e){this._backgroundBaseImage!==e&&(this._backgroundBaseImage=e,this.isVertical&&0!==this.num90RotationInVerticalMode?e.isLoaded?(this._backgroundImage=e._rotate90(this.num90RotationInVerticalMode,!0),this._markAsDirty()):e.onImageLoadedObservable.addOnce((()=>{const t=e._rotate90(this.num90RotationInVerticalMode,!0);this._backgroundImage=t,t.isLoaded||t.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()})):(this._backgroundImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()))}get thumbImage(){return this._thumbBaseImage}set thumbImage(e){this._thumbBaseImage!==e&&(this._thumbBaseImage=e,this.isVertical&&0!==this.num90RotationInVerticalMode?e.isLoaded?(this._thumbImage=e._rotate90(-this.num90RotationInVerticalMode,!0),this._markAsDirty()):e.onImageLoadedObservable.addOnce((()=>{const t=e._rotate90(-this.num90RotationInVerticalMode,!0);this._thumbImage=t,t.isLoaded||t.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()})):(this._thumbImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>{this._markAsDirty()})),this._markAsDirty()))}get thumbLength(){return this._thumbLength}set thumbLength(e){this._thumbLength!==e&&(this._thumbLength=e,this._markAsDirty())}get thumbHeight(){return this._thumbHeight}set thumbHeight(e){this._thumbLength!==e&&(this._thumbHeight=e,this._markAsDirty())}get barImageHeight(){return this._barImageHeight}set barImageHeight(e){this._barImageHeight!==e&&(this._barImageHeight=e,this._markAsDirty())}constructor(e){super(e),this.name=e,this._thumbLength=.5,this._thumbHeight=1,this._barImageHeight=1,this._tempMeasure=new Pw(0,0,0,0),this._invertScrollDirection=!1,this.num90RotationInVerticalMode=1}_getTypeName(){return"ImageScrollBar"}_getThumbThickness(){let e=0;return e=this._thumbWidth.isPixel?this._thumbWidth.getValue(this._host):this._backgroundBoxThickness*this._thumbWidth.getValue(this._host),e}_draw(e){e.save(),this._applyStates(e),this._prepareRenderingData("rectangle");const t=this._getThumbPosition(),i=this._renderLeft,s=this._renderTop,r=this._renderWidth,n=this._renderHeight;this._backgroundImage&&(this._tempMeasure.copyFromFloats(i,s,r,n),this.isVertical?(this._tempMeasure.copyFromFloats(i+r*(1-this._barImageHeight)*.5,this._currentMeasure.top,r*this._barImageHeight,n),this._tempMeasure.height+=this._effectiveThumbThickness,this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure)):(this._tempMeasure.copyFromFloats(this._currentMeasure.left,s+n*(1-this._barImageHeight)*.5,r,n*this._barImageHeight),this._tempMeasure.width+=this._effectiveThumbThickness,this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure)),this._backgroundImage._draw(e)),this.isVertical?this._tempMeasure.copyFromFloats(i-this._effectiveBarOffset+this._currentMeasure.width*(1-this._thumbHeight)*.5,this._currentMeasure.top+t,this._currentMeasure.width*this._thumbHeight,this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(this._currentMeasure.left+t,this._currentMeasure.top+this._currentMeasure.height*(1-this._thumbHeight)*.5,this._effectiveThumbThickness,this._currentMeasure.height*this._thumbHeight),this._thumbImage&&(this._thumbImage._currentMeasure.copyFrom(this._tempMeasure),this._thumbImage._draw(e)),e.restore()}_updateValueFromPointer(e,t){0!=this.rotation&&(this._invertTransformMatrix.transformCoordinates(e,t,this._transformedPosition),e=this._transformedPosition.x,t=this._transformedPosition.y);const i=this._invertScrollDirection?-1:1;this._first&&(this._first=!1,this._originX=e,this._originY=t,(ethis._tempMeasure.left+this._tempMeasure.width||tthis._tempMeasure.top+this._tempMeasure.height)&&(this.isVertical?this.value=this.minimum+(1-(t-this._currentMeasure.top)/this._currentMeasure.height)*(this.maximum-this.minimum):this.value=this.minimum+(e-this._currentMeasure.left)/this._currentMeasure.width*(this.maximum-this.minimum)));let s=0;s=this.isVertical?-(t-this._originY)/(this._currentMeasure.height-this._effectiveThumbThickness):(e-this._originX)/(this._currentMeasure.width-this._effectiveThumbThickness),this.value+=i*s*(this.maximum-this.minimum),this._originX=e,this._originY=t}_onPointerDown(e,t,i,s,r){return this._first=!0,super._onPointerDown(e,t,i,s,r)}}Ze([rt()],aN.prototype,"num90RotationInVerticalMode",void 0),Ze([rt()],aN.prototype,"invertScrollDirection",null);class lN extends ww{get horizontalBar(){return this._horizontalBar}get verticalBar(){return this._verticalBar}addControl(e){return e?(this._window.addControl(e),this):this}removeControl(e){return this._window.removeControl(e),this}get children(){return this._window.children}_flagDescendantsAsMatrixDirty(){for(const e of this._children)e._markMatrixAsDirty()}get freezeControls(){return this._window.freezeControls}set freezeControls(e){this._window.freezeControls=e}get bucketWidth(){return this._window.bucketWidth}get bucketHeight(){return this._window.bucketHeight}setBucketSizes(e,t){this._window.setBucketSizes(e,t)}get forceHorizontalBar(){return this._forceHorizontalBar}set forceHorizontalBar(e){this._grid.setRowDefinition(1,e?this._barSize:0,!0),this._horizontalBar.isVisible=e,this._forceHorizontalBar=e}get forceVerticalBar(){return this._forceVerticalBar}set forceVerticalBar(e){this._grid.setColumnDefinition(1,e?this._barSize:0,!0),this._verticalBar.isVisible=e,this._forceVerticalBar=e}constructor(e,t){super(e),this._barSize=20,this._pointerIsOver=!1,this._wheelPrecision=.05,this._thumbLength=.5,this._thumbHeight=1,this._barImageHeight=1,this._horizontalBarImageHeight=1,this._verticalBarImageHeight=1,this._oldWindowContentsWidth=0,this._oldWindowContentsHeight=0,this._forceHorizontalBar=!1,this._forceVerticalBar=!1,this._useImageBar=t||!1,this.onDirtyObservable.add((()=>{this._horizontalBarSpace.color=this.color,this._verticalBarSpace.color=this.color,this._dragSpace.color=this.color})),this.onPointerEnterObservable.add((()=>{this._pointerIsOver=!0})),this.onPointerOutObservable.add((()=>{this._pointerIsOver=!1})),this._grid=new zw,this._useImageBar?(this._horizontalBar=new aN,this._verticalBar=new aN):(this._horizontalBar=new oN,this._verticalBar=new oN),this._window=new nN("scrollViewer_window"),this._window.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._window.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,this._grid.addColumnDefinition(1),this._grid.addColumnDefinition(0,!0),this._grid.addRowDefinition(1),this._grid.addRowDefinition(0,!0),super.addControl(this._grid),this._grid.addControl(this._window,0,0),this._verticalBarSpace=new ww,this._verticalBarSpace.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._verticalBarSpace.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,this._verticalBarSpace.thickness=1,this._grid.addControl(this._verticalBarSpace,0,1),this._addBar(this._verticalBar,this._verticalBarSpace,!0,Math.PI),this._horizontalBarSpace=new ww,this._horizontalBarSpace.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._horizontalBarSpace.verticalAlignment=Ow.VERTICAL_ALIGNMENT_TOP,this._horizontalBarSpace.thickness=1,this._grid.addControl(this._horizontalBarSpace,1,0),this._addBar(this._horizontalBar,this._horizontalBarSpace,!1,0),this._dragSpace=new ww,this._dragSpace.thickness=1,this._grid.addControl(this._dragSpace,1,1),this._grid.clipChildren=!1,this._useImageBar||(this.barColor="grey",this.barBackground="transparent")}resetWindow(){this._window.width="100%",this._window.height="100%"}_getTypeName(){return"ScrollViewer"}_buildClientSizes(){const e=this.host.idealRatio;this._window.parentClientWidth=this._currentMeasure.width-(this._verticalBar.isVisible||this.forceVerticalBar?this._barSize*e:0)-2*this.thickness,this._window.parentClientHeight=this._currentMeasure.height-(this._horizontalBar.isVisible||this.forceHorizontalBar?this._barSize*e:0)-2*this.thickness,this._clientWidth=this._window.parentClientWidth,this._clientHeight=this._window.parentClientHeight}_additionalProcessing(e,t){super._additionalProcessing(e,t),this._buildClientSizes()}_postMeasure(){super._postMeasure(),this._updateScroller(),this._setWindowPosition(!1)}get wheelPrecision(){return this._wheelPrecision}set wheelPrecision(e){this._wheelPrecision!==e&&(e<0&&(e=0),e>1&&(e=1),this._wheelPrecision=e)}get scrollBackground(){return this._horizontalBarSpace.background}set scrollBackground(e){this._horizontalBarSpace.background!==e&&(this._horizontalBarSpace.background=e,this._verticalBarSpace.background=e)}get barColor(){return this._barColor}set barColor(e){this._barColor!==e&&(this._barColor=e,this._horizontalBar.color=e,this._verticalBar.color=e)}get thumbImage(){return this._barImage}set thumbImage(e){if(this._barImage===e)return;this._barImage=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbImage=e,i.thumbImage=e}get horizontalThumbImage(){return this._horizontalBarImage}set horizontalThumbImage(e){this._horizontalBarImage!==e&&(this._horizontalBarImage=e,this._horizontalBar.thumbImage=e)}get verticalThumbImage(){return this._verticalBarImage}set verticalThumbImage(e){this._verticalBarImage!==e&&(this._verticalBarImage=e,this._verticalBar.thumbImage=e)}get barSize(){return this._barSize}set barSize(e){this._barSize!==e&&(this._barSize=e,this._markAsDirty(),this._horizontalBar.isVisible&&this._grid.setRowDefinition(1,this._barSize,!0),this._verticalBar.isVisible&&this._grid.setColumnDefinition(1,this._barSize,!0))}get thumbLength(){return this._thumbLength}set thumbLength(e){if(this._thumbLength===e)return;e<=0&&(e=.1),e>1&&(e=1),this._thumbLength=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbLength=e,i.thumbLength=e,this._markAsDirty()}get thumbHeight(){return this._thumbHeight}set thumbHeight(e){if(this._thumbHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._thumbHeight=e;const t=this._horizontalBar,i=this._verticalBar;t.thumbHeight=e,i.thumbHeight=e,this._markAsDirty()}get barImageHeight(){return this._barImageHeight}set barImageHeight(e){if(this._barImageHeight===e)return;e<=0&&(e=.1),e>1&&(e=1),this._barImageHeight=e;const t=this._horizontalBar,i=this._verticalBar;t.barImageHeight=e,i.barImageHeight=e,this._markAsDirty()}get horizontalBarImageHeight(){return this._horizontalBarImageHeight}set horizontalBarImageHeight(e){this._horizontalBarImageHeight!==e&&(e<=0&&(e=.1),e>1&&(e=1),this._horizontalBarImageHeight=e,this._horizontalBar.barImageHeight=e,this._markAsDirty())}get verticalBarImageHeight(){return this._verticalBarImageHeight}set verticalBarImageHeight(e){this._verticalBarImageHeight!==e&&(e<=0&&(e=.1),e>1&&(e=1),this._verticalBarImageHeight=e,this._verticalBar.barImageHeight=e,this._markAsDirty())}get barBackground(){return this._barBackground}set barBackground(e){if(this._barBackground===e)return;this._barBackground=e;const t=this._horizontalBar,i=this._verticalBar;t.background=e,i.background=e,this._dragSpace.background=e}get barImage(){return this._barBackgroundImage}set barImage(e){this._barBackgroundImage=e;const t=this._horizontalBar,i=this._verticalBar;t.backgroundImage=e,i.backgroundImage=e}get horizontalBarImage(){return this._horizontalBarBackgroundImage}set horizontalBarImage(e){this._horizontalBarBackgroundImage=e,this._horizontalBar.backgroundImage=e}get verticalBarImage(){return this._verticalBarBackgroundImage}set verticalBarImage(e){this._verticalBarBackgroundImage=e,this._verticalBar.backgroundImage=e}_setWindowPosition(e=!0){const t=this.host.idealRatio,i=this._window._currentMeasure.width,s=this._window._currentMeasure.height;if(!e&&this._oldWindowContentsWidth===i&&this._oldWindowContentsHeight===s)return;this._oldWindowContentsWidth=i,this._oldWindowContentsHeight=s;const r=this._clientWidth-i,n=this._clientHeight-s,o=this._horizontalBar.value/t*r+"px",a=this._verticalBar.value/t*n+"px";o!==this._window.left&&(this._window.left=o,this.freezeControls||(this._rebuildLayout=!0)),a!==this._window.top&&(this._window.top=a,this.freezeControls||(this._rebuildLayout=!0))}_updateScroller(){const e=this._window._currentMeasure.width,t=this._window._currentMeasure.height;this._horizontalBar.isVisible&&e<=this._clientWidth&&!this.forceHorizontalBar?(this._grid.setRowDefinition(1,0,!0),this._horizontalBar.isVisible=!1,this._horizontalBar.value=0,this._rebuildLayout=!0):!this._horizontalBar.isVisible&&(e>this._clientWidth||this.forceHorizontalBar)&&(this._grid.setRowDefinition(1,this._barSize,!0),this._horizontalBar.isVisible=!0,this._rebuildLayout=!0),this._verticalBar.isVisible&&t<=this._clientHeight&&!this.forceVerticalBar?(this._grid.setColumnDefinition(1,0,!0),this._verticalBar.isVisible=!1,this._verticalBar.value=0,this._rebuildLayout=!0):!this._verticalBar.isVisible&&(t>this._clientHeight||this.forceVerticalBar)&&(this._grid.setColumnDefinition(1,this._barSize,!0),this._verticalBar.isVisible=!0,this._rebuildLayout=!0),this._buildClientSizes();const i=this.host.idealRatio;this._horizontalBar.thumbWidth=.9*this._thumbLength*(this._clientWidth/i)+"px",this._verticalBar.thumbWidth=.9*this._thumbLength*(this._clientHeight/i)+"px"}_link(e){super._link(e),this._attachWheel()}_addBar(e,t,i,s){e.paddingLeft=0,e.width="100%",e.height="100%",e.barOffset=0,e.value=0,e.maximum=1,e.horizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_CENTER,e.verticalAlignment=Ow.VERTICAL_ALIGNMENT_CENTER,e.isVertical=i,e.rotation=s,e.isVisible=!1,t.addControl(e),e.onValueChangedObservable.add((()=>{this._setWindowPosition()}))}_attachWheel(){this._host&&!this._onWheelObserver&&(this._onWheelObserver=this.onWheelObservable.add((e=>{this._pointerIsOver&&!this.isReadOnly&&(1==this._verticalBar.isVisible&&(e.y<0&&this._verticalBar.value>0?this._verticalBar.value-=this._wheelPrecision:e.y>0&&this._verticalBar.value0&&this._horizontalBar.value>0&&(this._horizontalBar.value-=this._wheelPrecision)))})))}_renderHighlightSpecific(e){this.isHighlighted&&(super._renderHighlightSpecific(e),this._grid._renderHighlightSpecific(e),e.restore())}dispose(){this.onWheelObservable.remove(this._onWheelObserver),this._onWheelObserver=null,super.dispose()}}Ze([rt()],lN.prototype,"wheelPrecision",null),Ze([rt()],lN.prototype,"scrollBackground",null),Ze([rt()],lN.prototype,"barColor",null),Ze([rt()],lN.prototype,"barSize",null),Ze([rt()],lN.prototype,"barBackground",null),z("BABYLON.GUI.ScrollViewer",lN);class hN extends ww{get group(){return this._group}set group(e){this._group!==e&&(this._group=e)}get isActive(){return this._isActive}set isActive(e){this._isActive!==e&&(this._isActive=e,this._isActive?this.toActiveAnimation?.():this.toInactiveAnimation?.(),this._markAsDirty(),this.onIsActiveChangedObservable.notifyObservers(e),this._isActive&&this._host&&this._group&&this._host.executeOnAllControls((e=>{if("ToggleButton"===e.typeName){if(e===this)return;const t=e;t.group===this.group&&(t.isActive=!1)}})))}constructor(e,t){super(e),this.name=e,this.onIsActiveChangedObservable=new K,this.delegatePickingToChildren=!1,this._isActive=!1,this.group=t??"",this.thickness=0,this.isPointerBlocker=!0;let i=null;this.toActiveAnimation=()=>{this.thickness=1},this.toInactiveAnimation=()=>{this.thickness=0},this.pointerEnterActiveAnimation=()=>{i=this.alpha,this.alpha-=.1},this.pointerOutActiveAnimation=()=>{null!==i&&(this.alpha=i)},this.pointerDownActiveAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpActiveAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05},this.pointerEnterInactiveAnimation=()=>{i=this.alpha,this.alpha-=.1},this.pointerOutInactiveAnimation=()=>{null!==i&&(this.alpha=i)},this.pointerDownInactiveAnimation=()=>{this.scaleX-=.05,this.scaleY-=.05},this.pointerUpInactiveAnimation=()=>{this.scaleX+=.05,this.scaleY+=.05}}_getTypeName(){return"ToggleButton"}_processPicking(e,t,i,s,r,n,o,a){if(!this._isEnabled||!this.isHitTestVisible||!this.isVisible||this.notRenderable)return!1;if(!super.contains(e,t))return!1;if(this.delegatePickingToChildren){let i=!1;for(let s=this._children.length-1;s>=0;s--){const r=this._children[s];if(r.isEnabled&&r.isHitTestVisible&&r.isVisible&&!r.notRenderable&&r.contains(e,t)){i=!0;break}}if(!i)return!1}return this._processObservables(s,e,t,i,r,n,o,a),!0}_onPointerEnter(e,t){return!!super._onPointerEnter(e,t)&&(this.isReadOnly||(this._isActive?this.pointerEnterActiveAnimation&&this.pointerEnterActiveAnimation():this.pointerEnterInactiveAnimation&&this.pointerEnterInactiveAnimation()),!0)}_onPointerOut(e,t,i=!1){this.isReadOnly||(this._isActive?this.pointerOutActiveAnimation&&this.pointerOutActiveAnimation():this.pointerOutInactiveAnimation&&this.pointerOutInactiveAnimation()),super._onPointerOut(e,t,i)}_onPointerDown(e,t,i,s,r){return!!super._onPointerDown(e,t,i,s,r)&&(this.isReadOnly||(this._isActive?this.pointerDownActiveAnimation&&this.pointerDownActiveAnimation():this.pointerDownInactiveAnimation&&this.pointerDownInactiveAnimation()),!0)}_onPointerUp(e,t,i,s,r,n){this.isReadOnly||(this._isActive?this.pointerUpActiveAnimation&&this.pointerUpActiveAnimation():this.pointerUpInactiveAnimation&&this.pointerUpInactiveAnimation()),super._onPointerUp(e,t,i,s,r,n)}}z("BABYLON.GUI.ToggleButton",hN);class cN{}class uN extends kw{constructor(){super(...arguments),this.onKeyPressObservable=new K,this.defaultButtonWidth="40px",this.defaultButtonHeight="40px",this.defaultButtonPaddingLeft="2px",this.defaultButtonPaddingRight="2px",this.defaultButtonPaddingTop="2px",this.defaultButtonPaddingBottom="2px",this.defaultButtonColor="#DDD",this.defaultButtonBackground="#070707",this.shiftButtonColor="#7799FF",this.selectedShiftThickness=1,this.shiftState=0,this._currentlyConnectedInputText=null,this._connectedInputTexts=[],this._onKeyPressObserver=null}_getTypeName(){return"VirtualKeyboard"}_createKey(e,t){const i=Bw.CreateSimpleButton(e,e);return i.width=t&&t.width?t.width:this.defaultButtonWidth,i.height=t&&t.height?t.height:this.defaultButtonHeight,i.color=t&&t.color?t.color:this.defaultButtonColor,i.background=t&&t.background?t.background:this.defaultButtonBackground,i.paddingLeft=t&&t.paddingLeft?t.paddingLeft:this.defaultButtonPaddingLeft,i.paddingRight=t&&t.paddingRight?t.paddingRight:this.defaultButtonPaddingRight,i.paddingTop=t&&t.paddingTop?t.paddingTop:this.defaultButtonPaddingTop,i.paddingBottom=t&&t.paddingBottom?t.paddingBottom:this.defaultButtonPaddingBottom,i.thickness=0,i.isFocusInvisible=!0,i.shadowColor=this.shadowColor,i.shadowBlur=this.shadowBlur,i.shadowOffsetX=this.shadowOffsetX,i.shadowOffsetY=this.shadowOffsetY,i.onPointerUpObservable.add((()=>{this.onKeyPressObservable.notifyObservers(e)})),i}addKeysRow(e,t){const i=new kw;i.isVertical=!1,i.isFocusInvisible=!0;let s=null;for(let r=0;rs.heightInPixels)&&(s=o),i.addControl(o)}i.height=s?s.height:this.defaultButtonHeight,this.addControl(i)}applyShiftState(e){if(this.children)for(let t=0;t1?this.selectedShiftThickness:0),r.text=e>0?r.text.toUpperCase():r.text.toLowerCase()}}}get connectedInputText(){return this._currentlyConnectedInputText}connect(e){if(this._connectedInputTexts.some((t=>t.input===e)))return;null===this._onKeyPressObserver&&(this._onKeyPressObserver=this.onKeyPressObservable.add((e=>{if(this._currentlyConnectedInputText){switch(this._currentlyConnectedInputText._host.focusedControl=this._currentlyConnectedInputText,e){case"⇧":return this.shiftState++,this.shiftState>2&&(this.shiftState=0),void this.applyShiftState(this.shiftState);case"←":return void(this._currentlyConnectedInputText instanceof Yw?this._currentlyConnectedInputText.alternativeProcessKey("Backspace"):this._currentlyConnectedInputText.processKey(8));case"↵":return void(this._currentlyConnectedInputText instanceof Yw?this._currentlyConnectedInputText.alternativeProcessKey("Enter"):this._currentlyConnectedInputText.processKey(13))}this._currentlyConnectedInputText instanceof Yw?this._currentlyConnectedInputText.alternativeProcessKey("",this.shiftState?e.toUpperCase():e):this._currentlyConnectedInputText.processKey(-1,this.shiftState?e.toUpperCase():e),1===this.shiftState&&(this.shiftState=0,this.applyShiftState(this.shiftState))}}))),this.isVisible=!1,this._currentlyConnectedInputText=e,e._connectedVirtualKeyboard=this;const t=e.onFocusObservable.add((()=>{this._currentlyConnectedInputText=e,e._connectedVirtualKeyboard=this,this.isVisible=!0})),i=e.onBlurObservable.add((()=>{e._connectedVirtualKeyboard=null,this._currentlyConnectedInputText=null,this.isVisible=!1}));this._connectedInputTexts.push({input:e,onBlurObserver:i,onFocusObserver:t})}disconnect(e){if(e){const t=this._connectedInputTexts.filter((t=>t.input===e));1===t.length&&(this._removeConnectedInputObservables(t[0]),this._connectedInputTexts=this._connectedInputTexts.filter((t=>t.input!==e)),this._currentlyConnectedInputText===e&&(this._currentlyConnectedInputText=null))}else this._connectedInputTexts.forEach((e=>{this._removeConnectedInputObservables(e)})),this._connectedInputTexts.length=0;0===this._connectedInputTexts.length&&(this._currentlyConnectedInputText=null,this.onKeyPressObservable.remove(this._onKeyPressObserver),this._onKeyPressObserver=null)}_removeConnectedInputObservables(e){e.input._connectedVirtualKeyboard=null,e.input.onFocusObservable.remove(e.onFocusObserver),e.input.onBlurObservable.remove(e.onBlurObserver)}dispose(){super.dispose(),this.disconnect()}static CreateDefaultLayout(e){const t=new uN(e);return t.addKeysRow(["1","2","3","4","5","6","7","8","9","0","←"]),t.addKeysRow(["q","w","e","r","t","y","u","i","o","p"]),t.addKeysRow(["a","s","d","f","g","h","j","k","l",";","'","↵"]),t.addKeysRow(["⇧","z","x","c","v","b","n","m",",",".","/"]),t.addKeysRow([" "],[{width:"200px"}]),t}_parseFromContent(e,t){super._parseFromContent(e,t);for(const e of this.children)if("StackPanel"===e.getClassName()){const t=e;for(const e of t.children)"Button"===e.getClassName()&&e.name&&e.onPointerUpObservable.add((()=>{this.onKeyPressObservable.notifyObservers(e.name)}))}}}z("BABYLON.GUI.VirtualKeyboard",uN);class dN extends Ow{get displayMinorLines(){return this._displayMinorLines}set displayMinorLines(e){this._displayMinorLines!==e&&(this._displayMinorLines=e,this._markAsDirty())}get displayMajorLines(){return this._displayMajorLines}set displayMajorLines(e){this._displayMajorLines!==e&&(this._displayMajorLines=e,this._markAsDirty())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this._markAsDirty())}get cellWidth(){return this._cellWidth}set cellWidth(e){this._cellWidth=e,this._markAsDirty()}get cellHeight(){return this._cellHeight}set cellHeight(e){this._cellHeight=e,this._markAsDirty()}get minorLineTickness(){return this._minorLineTickness}set minorLineTickness(e){this._minorLineTickness=e,this._markAsDirty()}get minorLineColor(){return this._minorLineColor}set minorLineColor(e){this._minorLineColor=e,this._markAsDirty()}get majorLineTickness(){return this._majorLineTickness}set majorLineTickness(e){this._majorLineTickness=e,this._markAsDirty()}get majorLineColor(){return this._majorLineColor}set majorLineColor(e){this._majorLineColor=e,this._markAsDirty()}get majorLineFrequency(){return this._majorLineFrequency}set majorLineFrequency(e){this._majorLineFrequency=e,this._markAsDirty()}constructor(e){super(e),this.name=e,this._cellWidth=20,this._cellHeight=20,this._minorLineTickness=1,this._minorLineColor="DarkGray",this._majorLineTickness=2,this._majorLineColor="White",this._majorLineFrequency=5,this._background="Black",this._displayMajorLines=!0,this._displayMinorLines=!0}_draw(e){if(e.save(),this._applyStates(e),this._isEnabled){this._background&&(e.fillStyle=this._background,e.fillRect(this._currentMeasure.left,this._currentMeasure.top,this._currentMeasure.width,this._currentMeasure.height));const t=this._currentMeasure.width/this._cellWidth,i=this._currentMeasure.height/this._cellHeight,s=this._currentMeasure.left+this._currentMeasure.width/2,r=this._currentMeasure.top+this._currentMeasure.height/2;if(this._displayMinorLines){e.strokeStyle=this._minorLineColor,e.lineWidth=this._minorLineTickness;for(let i=-t/2+1;ithis._markAsDirty())),this._markAsDirty())}get valueBarImage(){return this._valueBarImage}set valueBarImage(e){this._valueBarImage!==e&&(this._valueBarImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>this._markAsDirty())),this._markAsDirty())}get thumbImage(){return this._thumbImage}set thumbImage(e){this._thumbImage!==e&&(this._thumbImage=e,e&&!e.isLoaded&&e.onImageLoadedObservable.addOnce((()=>this._markAsDirty())),this._markAsDirty())}constructor(e){super(e),this.name=e,this._tempMeasure=new Pw(0,0,0,0)}_getTypeName(){return"ImageBasedSlider"}_draw(e){e.save(),this._applyStates(e),this._prepareRenderingData("rectangle");const t=this._getThumbPosition(),i=this._renderLeft,s=this._renderTop,r=this._renderWidth,n=this._renderHeight;this._backgroundImage&&(this._tempMeasure.copyFromFloats(i,s,r,n),this.isThumbClamped&&this.displayThumb&&(this.isVertical?this._tempMeasure.height+=this._effectiveThumbThickness:this._tempMeasure.width+=this._effectiveThumbThickness),this._backgroundImage._currentMeasure.copyFrom(this._tempMeasure),this._backgroundImage._draw(e)),this._valueBarImage&&(this.isVertical?this.isThumbClamped&&this.displayThumb?this._tempMeasure.copyFromFloats(i,s+t,r,n-t+this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(i,s+t,r,n-t):this.isThumbClamped&&this.displayThumb?this._tempMeasure.copyFromFloats(i,s,t+this._effectiveThumbThickness/2,n):this._tempMeasure.copyFromFloats(i,s,t,n),this._valueBarImage._currentMeasure.copyFrom(this._tempMeasure),this._valueBarImage._draw(e)),this.displayThumb&&(this.isVertical?this._tempMeasure.copyFromFloats(i-this._effectiveBarOffset,this._currentMeasure.top+t,this._currentMeasure.width,this._effectiveThumbThickness):this._tempMeasure.copyFromFloats(this._currentMeasure.left+t,this._currentMeasure.top,this._effectiveThumbThickness,this._currentMeasure.height),this._thumbImage._currentMeasure.copyFrom(this._tempMeasure),this._thumbImage._draw(e)),e.restore()}serialize(e){super.serialize(e);const t={},i={},s={};this.backgroundImage.serialize(t),this.thumbImage.serialize(i),this.valueBarImage.serialize(s),e.backgroundImage=t,e.thumbImage=i,e.valueBarImage=s}_parseFromContent(e,t){super._parseFromContent(e,t),this.backgroundImage=Lw.Parse(e.backgroundImage,t),this.thumbImage=Lw.Parse(e.thumbImage,t),this.valueBarImage=Lw.Parse(e.valueBarImage,t)}}Ze([rt()],_N.prototype,"displayThumb",null),z("BABYLON.GUI.ImageBasedSlider",_N);const pN="Statics";Ow.AddHeader=function(e,t,i,s){const r=new kw("panel"),n=!s||s.isHorizontal,o=!s||s.controlFirst;r.isVertical=!n;const a=new Fw("header");return a.text=t,a.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,n?a.width=i:a.height=i,o?(r.addControl(e),r.addControl(a),a.paddingLeft="5px"):(r.addControl(a),r.addControl(e),a.paddingRight="5px"),a.shadowBlur=e.shadowBlur,a.shadowColor=e.shadowColor,a.shadowOffsetX=e.shadowOffsetX,a.shadowOffsetY=e.shadowOffsetY,r};class fN{constructor(){this._colorStops=[],this._gradientDirty=!0}_addColorStopsToCanvasGradient(){for(const e of this._colorStops)this._canvasGradient.addColorStop(e.offset,e.color)}getCanvasGradient(e){return(this._gradientDirty||this._context!==e)&&(this._context=e,this._canvasGradient=this._createCanvasGradient(e),this._addColorStopsToCanvasGradient(),this._gradientDirty=!1),this._canvasGradient}addColorStop(e,t){this._colorStops.push({offset:e,color:t}),this._gradientDirty=!0}removeColorStop(e){this._colorStops=this._colorStops.filter((t=>t.offset!==e)),this._gradientDirty=!0}clearColorStops(){this._colorStops=[],this._gradientDirty=!0}get colorStops(){return this._colorStops}getClassName(){return"BaseGradient"}serialize(e){e.colorStops=this._colorStops,e.className=this.getClassName()}parse(e){this._colorStops=e.colorStops}}class mN extends fN{constructor(e,t,i,s){super(),this._x0=e??0,this._y0=t??0,this._x1=i??0,this._y1=s??0}_createCanvasGradient(e){return e.createLinearGradient(this._x0,this._y0,this._x1,this._y1)}get x0(){return this._x0}get x1(){return this._x1}get y0(){return this._y0}get y1(){return this._y1}getClassName(){return"LinearGradient"}serialize(e){super.serialize(e),e.x0=this._x0,e.y0=this._y0,e.x1=this._x1,e.y1=this._y1}parse(e){super.parse(e),this._x0=e.x0,this._y0=e.y0,this._x1=e.x1,this._y1=e.y1}}z("BABYLON.GUI.LinearGradient",mN);class gN extends fN{constructor(e,t,i,s,r,n){super(),this._x0=e??0,this._y0=t??0,this._r0=i??0,this._x1=s??0,this._y1=r??0,this._r1=n??0}_createCanvasGradient(e){return e.createRadialGradient(this._x0,this._y0,this._r0,this._x1,this._y1,this._r1)}get x0(){return this._x0}get x1(){return this._x1}get y0(){return this._y0}get y1(){return this._y1}get r0(){return this._r0}get r1(){return this._r1}getClassName(){return"RadialGradient"}serialize(e){super.serialize(e),e.x0=this._x0,e.y0=this._y0,e.r0=this._r0,e.x1=this._x1,e.y1=this._y1,e.r1=this._r1}parse(e){super.parse(e),this._x0=e.x0,this._y0=e.y0,this._r0=e.r0,this._x1=e.x1,this._y1=e.y1,this._r1=e.r1}}z("BABYLON.GUI.RadialGradient",gN);class vN{constructor(e){this._fontFamily="Arial",this._fontStyle="",this._fontWeight="",this._fontSize=new yw(18,yw.UNITMODE_PIXEL,!1),this.onChangedObservable=new K,this._host=e}get fontSize(){return this._fontSize.toString(this._host)}set fontSize(e){this._fontSize.toString(this._host)!==e&&this._fontSize.fromString(e)&&this.onChangedObservable.notifyObservers(this)}get fontFamily(){return this._fontFamily}set fontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.onChangedObservable.notifyObservers(this))}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.onChangedObservable.notifyObservers(this))}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.onChangedObservable.notifyObservers(this))}dispose(){this.onChangedObservable.clear()}}class xN extends uu{get numLayoutCalls(){return this._numLayoutCalls}get numRenderCalls(){return this._numRenderCalls}get renderScale(){return this._renderScale}set renderScale(e){e!==this._renderScale&&(this._renderScale=e,this._onResize())}get background(){return this._background}set background(e){this._background!==e&&(this._background=e,this.markAsDirty())}get idealWidth(){return this._idealWidth}set idealWidth(e){this._idealWidth!==e&&(this._idealWidth=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get idealHeight(){return this._idealHeight}set idealHeight(e){this._idealHeight!==e&&(this._idealHeight=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get useSmallestIdeal(){return this._useSmallestIdeal}set useSmallestIdeal(e){this._useSmallestIdeal!==e&&(this._useSmallestIdeal=e,this.markAsDirty(),this._rootContainer._markAllAsDirty())}get renderAtIdealSize(){return this._renderAtIdealSize}set renderAtIdealSize(e){this._renderAtIdealSize!==e&&(this._renderAtIdealSize=e,this._onResize())}get idealRatio(){let e=0,t=0;return this._idealWidth&&(e=this.getSize().width/this._idealWidth),this._idealHeight&&(t=this.getSize().height/this._idealHeight),this._useSmallestIdeal&&this._idealWidth&&this._idealHeight?window.innerWidtht.typeName===e))}getControlByName(e){return this._getControlByKey("name",e)}_getControlByKey(e,t){return this._rootContainer.getDescendants().find((i=>i[e]===t))||null}get focusedControl(){return this._focusedControl}set focusedControl(e){this._focusedControl!=e&&(this._focusedControl&&this._focusedControl.onBlur(),e&&e.onFocus(),this._focusedControl=e)}get isForeground(){return!this.layer||!this.layer.isBackground}set isForeground(e){this.layer&&this.layer.isBackground!==!e&&(this.layer.isBackground=!e)}get clipboardData(){return this._clipboardData}set clipboardData(e){this._clipboardData=e}constructor(e,t=0,i=0,s,r=!1,n=Pa.NEAREST_SAMPLINGMODE,o=!0){super(e,{width:t,height:i},s,r,n,N_.TEXTUREFORMAT_RGBA,o),this.onGuiReadyObservable=new K,this._isDirty=!1,this._rootContainer=new Dw("root"),this._lastControlOver={},this._lastControlDown={},this._capturingControl={},this._linkedControls=new Array,this._isFullscreen=!1,this._fullscreenViewport=new Pn(0,0,1,1),this._idealWidth=0,this._idealHeight=0,this._useSmallestIdeal=!1,this._renderAtIdealSize=!1,this._blockNextFocusCheck=!1,this._renderScale=1,this._cursorChanged=!1,this._defaultMousePointerId=0,this._rootChildrenHaveChanged=!1,this._capturedPointerIds=new Set,this._numLayoutCalls=0,this._numRenderCalls=0,this._clipboardData="",this.onClipboardObservable=new K,this.onControlPickedObservable=new K,this.onBeginLayoutObservable=new K,this.onEndLayoutObservable=new K,this.onBeginRenderObservable=new K,this.onEndRenderObservable=new K,this.premulAlpha=!1,this.applyYInversionOnUpdate=!0,this.skipBlockEvents=0,this.checkPointerEveryFrame=!1,this._useInvalidateRectOptimization=!0,this._invalidatedRectangle=null,this._clearMeasure=new Pw(0,0,0,0),this._onClipboardCopy=e=>{const t=e,i=new eg(Jm.COPY,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this._onClipboardCut=e=>{const t=e,i=new eg(Jm.CUT,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this._onClipboardPaste=e=>{const t=e,i=new eg(Jm.PASTE,t);this.onClipboardObservable.notifyObservers(i),t.preventDefault()},this.parseContent=this.parseSerializedObject,(s=this.getScene())&&this._texture&&(this.applyYInversionOnUpdate=o,this._rootElement=s.getEngine().getInputElement(),this._renderObserver=s.onBeforeCameraRenderObservable.add((e=>this._checkUpdate(e))),this._controlAddedObserver=this._rootContainer.onControlAddedObservable.add((e=>{e&&(this._rootChildrenHaveChanged=!0)})),this._controlRemovedObserver=this._rootContainer.onControlRemovedObservable.add((e=>{e&&(this._rootChildrenHaveChanged=!0)})),this._preKeyboardObserver=s.onPreKeyboardObservable.add((e=>{this._focusedControl&&(e.type===dr.KEYDOWN&&this._focusedControl.processKeyboard(e.event),e.skipOnPointerObservable=!0)})),this._rootContainer._link(this),this.hasAlpha=!0,t&&i||(this._resizeObserver=s.getEngine().onResizeObservable.add((()=>this._onResize())),this._onResize()),this._texture.isReady=!0)}getClassName(){return"AdvancedDynamicTexture"}executeOnAllControls(e,t){t||(t=this._rootContainer),e(t);for(const i of t.children)i.children?this.executeOnAllControls(e,i):e(i)}get useInvalidateRectOptimization(){return this._useInvalidateRectOptimization}set useInvalidateRectOptimization(e){this._useInvalidateRectOptimization=e}invalidateRect(e,t,i,s){if(this._useInvalidateRectOptimization)if(this._invalidatedRectangle){const r=Math.ceil(Math.max(this._invalidatedRectangle.left+this._invalidatedRectangle.width-1,i)),n=Math.ceil(Math.max(this._invalidatedRectangle.top+this._invalidatedRectangle.height-1,s));this._invalidatedRectangle.left=Math.floor(Math.min(this._invalidatedRectangle.left,e)),this._invalidatedRectangle.top=Math.floor(Math.min(this._invalidatedRectangle.top,t)),this._invalidatedRectangle.width=r-this._invalidatedRectangle.left+1,this._invalidatedRectangle.height=n-this._invalidatedRectangle.top+1}else this._invalidatedRectangle=new Pw(e,t,i-e+1,s-t+1)}markAsDirty(){this._isDirty=!0}createStyle(){return new vN(this)}addControl(e){return this._rootContainer.addControl(e),this}removeControl(e){return this._rootContainer.removeControl(e),this}moveToNonOverlappedPosition(e,t=1,i=1){let s;if(Array.isArray(e))s=e;else{const t=this.getDescendants(!0);s=void 0===e?t.filter((e=>void 0!==e.overlapGroup)):t.filter((t=>t.overlapGroup===e))}s.forEach((e=>{let r=de.Zero();const n=new de(e.centerX,e.centerY);s.forEach((t=>{if(e!==t&&xN._Overlaps(e,t)){const e=n.subtract(new de(t.centerX,t.centerY)),s=e.length();s>0&&(r=r.add(e.normalize().scale(i/s)))}})),r.length()>0&&(r=r.normalize().scale(t*(e.overlapDeltaMultiplier??1)),e.linkOffsetXInPixels+=r.x,e.linkOffsetYInPixels+=r.y)}))}dispose(){const e=this.getScene();e&&(this._rootElement=null,e.onBeforeCameraRenderObservable.remove(this._renderObserver),this._resizeObserver&&e.getEngine().onResizeObservable.remove(this._resizeObserver),this._prePointerObserver&&e.onPrePointerObservable.remove(this._prePointerObserver),this._sceneRenderObserver&&e.onBeforeRenderObservable.remove(this._sceneRenderObserver),this._pointerObserver&&e.onPointerObservable.remove(this._pointerObserver),this._preKeyboardObserver&&e.onPreKeyboardObservable.remove(this._preKeyboardObserver),this._canvasPointerOutObserver&&e.getEngine().onCanvasPointerOutObservable.remove(this._canvasPointerOutObserver),this._canvasBlurObserver&&e.getEngine().onCanvasBlurObservable.remove(this._canvasBlurObserver),this._controlAddedObserver&&this._rootContainer.onControlAddedObservable.remove(this._controlAddedObserver),this._controlRemovedObserver&&this._rootContainer.onControlRemovedObservable.remove(this._controlRemovedObserver),this._layerToDispose&&(this._layerToDispose.texture=null,this._layerToDispose.dispose(),this._layerToDispose=null),this._rootContainer.dispose(),this.onClipboardObservable.clear(),this.onControlPickedObservable.clear(),this.onBeginRenderObservable.clear(),this.onEndRenderObservable.clear(),this.onBeginLayoutObservable.clear(),this.onEndLayoutObservable.clear(),this.onGuiReadyObservable.clear(),super.dispose())}_onResize(){const e=this.getScene();if(!e)return;const t=e.getEngine(),i=this.getSize();let s=t.getRenderWidth()*this._renderScale,r=t.getRenderHeight()*this._renderScale;this._renderAtIdealSize&&(this._idealWidth?(r=r*this._idealWidth/s,s=this._idealWidth):this._idealHeight&&(s=s*this._idealHeight/r,r=this._idealHeight)),i.width===s&&i.height===r||(this.scaleTo(s,r),this.markAsDirty(),(this._idealWidth||this._idealHeight)&&this._rootContainer._markAllAsDirty()),this.invalidateRect(0,0,i.width-1,i.height-1)}_getGlobalViewport(){const e=this.getSize(),t=this._fullscreenViewport.toGlobal(e.width,e.height),i=Math.round(t.width*(1/this.rootContainer.scaleX)),s=Math.round(t.height*(1/this.rootContainer.scaleY));return t.x+=(t.width-i)/2,t.y+=(t.height-s)/2,t.width=i,t.height=s,t}getProjectedPosition(e,t){const i=this.getProjectedPositionWithZ(e,t);return new de(i.x,i.y)}getProjectedPositionWithZ(e,t){const i=this.getScene();if(!i)return _e.Zero();const s=this._getGlobalViewport(),r=_e.Project(e,t,i.getTransformMatrix(),s);return new _e(r.x,r.y,r.z)}_checkUpdate(e,t){if(!this._layerToDispose||e.layerMask&this._layerToDispose.layerMask){if(this._isFullscreen&&this._linkedControls.length){const e=this.getScene();if(!e)return;const t=this._getGlobalViewport();for(const i of this._linkedControls){if(!i.isVisible)continue;const s=i._linkedMesh;if(!s||s.isDisposed()){Ds.SetImmediate((()=>{i.linkWithMesh(null)}));continue}const r=s.getBoundingInfo?s.getBoundingInfo().boundingSphere.center:_e.ZeroReadOnly,n=_e.Project(r,s.getWorldMatrix(),e.getTransformMatrix(),t);n.z<0||n.z>1?i.notRenderable=!0:(i.notRenderable=!1,this.useInvalidateRectOptimization&&i.invalidateRect(),i._moveToProjectedPosition(n))}}(this._isDirty||this._rootContainer.isDirty)&&(this._isDirty=!1,this._render(t),t||this.update(this.applyYInversionOnUpdate,this.premulAlpha,xN.AllowGPUOptimizations))}}_render(e){const t=this.getSize(),i=t.width,s=t.height,r=this.getContext();if(r.font="18px Arial",r.strokeStyle="white",this.onGuiReadyObservable.hasObservers()&&this._checkGuiIsReady(),this._rootChildrenHaveChanged){const e=this.getScene()?.activeCamera;e&&(this._rootChildrenHaveChanged=!1,this._checkUpdate(e,!0))}this.onBeginLayoutObservable.notifyObservers(this);const n=new Pw(0,0,i,s);this._numLayoutCalls=0,this._rootContainer._layout(n,r),this.onEndLayoutObservable.notifyObservers(this),this._isDirty=!1,e||(this._invalidatedRectangle?this._clearMeasure.copyFrom(this._invalidatedRectangle):this._clearMeasure.copyFromFloats(0,0,i,s),r.clearRect(this._clearMeasure.left,this._clearMeasure.top,this._clearMeasure.width,this._clearMeasure.height),this._background&&(r.save(),r.fillStyle=this._background,r.fillRect(this._clearMeasure.left,this._clearMeasure.top,this._clearMeasure.width,this._clearMeasure.height),r.restore()),this.onBeginRenderObservable.notifyObservers(this),this._numRenderCalls=0,this._rootContainer._render(r,this._invalidatedRectangle),this.onEndRenderObservable.notifyObservers(this),this._invalidatedRectangle=null)}_changeCursor(e){this._rootElement&&(this._rootElement.style.cursor=e,this._cursorChanged=!0)}_registerLastControlDown(e,t){this._lastControlDown[t]=e,this.onControlPickedObservable.notifyObservers(e)}_doPicking(e,t,i,s,r,n,o,a){const l=this.getScene();if(!l)return;const h=l.getEngine(),c=this.getSize();if(this._isFullscreen){const i=l.cameraToUseForPointers||l.activeCamera;if(!i)return;const s=i.viewport;e*=c.width/(h.getRenderWidth()*s.width),t*=c.height/(h.getRenderHeight()*s.height)}if(this._capturingControl[r])return this._capturingControl[r].isPointerBlocker&&(this._shouldBlockPointer=!0),void this._capturingControl[r]._processObservables(s,e,t,i,r,n);this._cursorChanged=!1,this._rootContainer._processPicking(e,t,i,s,r,n,o,a)||(l.doNotHandleCursors||this._changeCursor(""),s===lr.POINTERMOVE&&this._lastControlOver[r]&&(this._lastControlOver[r]._onPointerOut(this._lastControlOver[r],i),delete this._lastControlOver[r])),this._cursorChanged||l.doNotHandleCursors||this._changeCursor(""),this._manageFocus()}_cleanControlAfterRemovalFromList(e,t){for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&e[i]===t&&delete e[i]}_cleanControlAfterRemoval(e){this._cleanControlAfterRemovalFromList(this._lastControlDown,e),this._cleanControlAfterRemovalFromList(this._lastControlOver,e)}pick(e,t,i=null){this._isFullscreen&&this._scene&&this._translateToPicking(this._scene,new Pn(0,0,0,0),i,e,t)}_translateToPicking(e,t,i,s=e.pointerX,r=e.pointerY){const n=e.cameraToUseForPointers||e.activeCamera,o=e.getEngine(),a=e.cameraToUseForPointers;if(n)if(n.rigCameras.length){const i=new Pn(0,0,1,1);n.rigCameras.forEach((n=>{n.viewport.toGlobalToRef(o.getRenderWidth(),o.getRenderHeight(),i);const a=s/o.getHardwareScalingLevel()-i.x,l=r/o.getHardwareScalingLevel()-(o.getRenderHeight()-i.y-i.height);a<0||l<0||s>i.width||r>i.height||(e.cameraToUseForPointers=n,t.x=i.x,t.y=i.y,t.width=i.width,t.height=i.height)}))}else n.viewport.toGlobalToRef(o.getRenderWidth(),o.getRenderHeight(),t);else t.x=0,t.y=0,t.width=o.getRenderWidth(),t.height=o.getRenderHeight();const l=s/o.getHardwareScalingLevel()-t.x,h=r/o.getHardwareScalingLevel()-(o.getRenderHeight()-t.y-t.height);if(this._shouldBlockPointer=!1,i){const e=i.event.pointerId||this._defaultMousePointerId;this._doPicking(l,h,i,i.type,e,i.event.button,i.event.deltaX,i.event.deltaY),(this._shouldBlockPointer&&!(i.type&this.skipBlockEvents)||this._capturingControl[e])&&(i.skipOnPointerObservable=!0)}else this._doPicking(l,h,null,lr.POINTERMOVE,this._defaultMousePointerId,0);e.cameraToUseForPointers=a}attach(){const e=this.getScene();if(!e)return;const t=new Pn(0,0,0,0);this._prePointerObserver=e.onPrePointerObservable.add((i=>{if((!e.isPointerCaptured(i.event.pointerId)||i.type!==lr.POINTERUP||this._capturedPointerIds.has(i.event.pointerId))&&(i.type===lr.POINTERMOVE||i.type===lr.POINTERUP||i.type===lr.POINTERDOWN||i.type===lr.POINTERWHEEL)){if(i.type===lr.POINTERMOVE){if(e.isPointerCaptured(i.event.pointerId))return;i.event.pointerId&&(this._defaultMousePointerId=i.event.pointerId)}this._translateToPicking(e,t,i)}})),this._attachPickingToSceneRender(e,(()=>this._translateToPicking(e,t,null)),!1),this._attachToOnPointerOut(e),this._attachToOnBlur(e)}registerClipboardEvents(){self.addEventListener("copy",this._onClipboardCopy,!1),self.addEventListener("cut",this._onClipboardCut,!1),self.addEventListener("paste",this._onClipboardPaste,!1)}unRegisterClipboardEvents(){self.removeEventListener("copy",this._onClipboardCopy),self.removeEventListener("cut",this._onClipboardCut),self.removeEventListener("paste",this._onClipboardPaste)}_transformUvs(e){const t=this.getTextureMatrix();let i;if(t.isIdentityAs3x2())i=e;else{const s=ve.Matrix[0];t.getRowToRef(0,ve.Vector4[0]),t.getRowToRef(1,ve.Vector4[1]),t.getRowToRef(2,ve.Vector4[2]);const r=ve.Vector4[0],n=ve.Vector4[1],o=ve.Vector4[2];s.setRowFromFloats(0,r.x,r.y,0,0),s.setRowFromFloats(1,n.x,n.y,0,0),s.setRowFromFloats(2,0,0,1,0),s.setRowFromFloats(3,o.x,o.y,0,1),i=ve.Vector2[0],de.TransformToRef(e,s,i)}if((this.wrapU===Pa.WRAP_ADDRESSMODE||this.wrapU===Pa.MIRROR_ADDRESSMODE)&&i.x>1){let e=i.x-Math.trunc(i.x);this.wrapU===Pa.MIRROR_ADDRESSMODE&&Math.trunc(i.x)%2==1&&(e=1-e),i.x=e}if((this.wrapV===Pa.WRAP_ADDRESSMODE||this.wrapV===Pa.MIRROR_ADDRESSMODE)&&i.y>1){let e=i.y-Math.trunc(i.y);this.wrapV===Pa.MIRROR_ADDRESSMODE&&Math.trunc(i.x)%2==1&&(e=1-e),i.y=e}return i}attachToMesh(e,t=!0){const i=this.getScene();i&&(this._pointerObserver&&i.onPointerObservable.remove(this._pointerObserver),this._pointerObserver=i.onPointerObservable.add((t=>{if(t.type!==lr.POINTERMOVE&&t.type!==lr.POINTERUP&&t.type!==lr.POINTERDOWN&&t.type!==lr.POINTERWHEEL)return;t.type===lr.POINTERMOVE&&t.event.pointerId&&(this._defaultMousePointerId=t.event.pointerId);const i=t.event.pointerId||this._defaultMousePointerId;if(t.pickInfo&&t.pickInfo.hit&&t.pickInfo.pickedMesh===e){let e=t.pickInfo.getTextureCoordinates();if(e){e=this._transformUvs(e);const s=this.getSize();this._doPicking(e.x*s.width,(this.applyYInversionOnUpdate?1-e.y:e.y)*s.height,t,t.type,i,t.event.button,t.event.deltaX,t.event.deltaY)}}else if(t.type===lr.POINTERUP){if(this._lastControlDown[i]&&this._lastControlDown[i]._forcePointerUp(i),delete this._lastControlDown[i],this.focusedControl){const e=this.focusedControl.keepsFocusWith();let t=!0;if(e)for(const s of e){if(this===s._host)continue;const e=s._host;if(e._lastControlOver[i]&&e._lastControlOver[i].isAscendant(s)){t=!1;break}}t&&(this.focusedControl=null)}}else t.type===lr.POINTERMOVE&&(this._lastControlOver[i]&&this._lastControlOver[i]._onPointerOut(this._lastControlOver[i],t,!0),delete this._lastControlOver[i])})),e.enablePointerMoveEvents=t,this._attachPickingToSceneRender(i,(()=>{const t=this._defaultMousePointerId,s=i?.pick(i.pointerX,i.pointerY);if(s&&s.hit&&s.pickedMesh===e){let e=s.getTextureCoordinates();if(e){e=this._transformUvs(e);const i=this.getSize();this._doPicking(e.x*i.width,(this.applyYInversionOnUpdate?1-e.y:e.y)*i.height,null,lr.POINTERMOVE,t,0)}}else this._lastControlOver[t]&&this._lastControlOver[t]._onPointerOut(this._lastControlOver[t],null,!0),delete this._lastControlOver[t]}),!0),this._attachToOnPointerOut(i),this._attachToOnBlur(i))}moveFocusToControl(e){this.focusedControl=e,this._lastPickedControl=e,this._blockNextFocusCheck=!0}_manageFocus(){if(this._blockNextFocusCheck)return this._blockNextFocusCheck=!1,void(this._lastPickedControl=this._focusedControl);if(this._focusedControl&&this._focusedControl!==this._lastPickedControl){if(this._lastPickedControl.isFocusInvisible)return;this.focusedControl=null}}_attachPickingToSceneRender(e,t,i){this._sceneRenderObserver=e.onBeforeRenderObservable.add((()=>{this.checkPointerEveryFrame&&(this._linkedControls.length>0||i)&&t()}))}_attachToOnPointerOut(e){this._canvasPointerOutObserver=e.getEngine().onCanvasPointerOutObservable.add((e=>{this._lastControlOver[e.pointerId]&&this._lastControlOver[e.pointerId]._onPointerOut(this._lastControlOver[e.pointerId],null),delete this._lastControlOver[e.pointerId],this._lastControlDown[e.pointerId]&&this._lastControlDown[e.pointerId]!==this._capturingControl[e.pointerId]&&(this._lastControlDown[e.pointerId]._forcePointerUp(e.pointerId),delete this._lastControlDown[e.pointerId])}))}_attachToOnBlur(e){this._canvasBlurObserver=e.getEngine().onCanvasBlurObservable.add((()=>{Object.entries(this._lastControlDown).forEach((([,e])=>{e._onCanvasBlur()})),this.focusedControl=null,this._lastControlDown={}}))}serializeContent(){const e=this.getSize(),t={root:{},width:e.width,height:e.height};return this._rootContainer.serialize(t.root),t}parseSerializedObject(e,t,i){if(this._rootContainer=Ow.Parse(e.root,this,i),t){const t=e.width,i=e.height;"number"==typeof t&&"number"==typeof i&&t>=0&&i>=0?this.scaleTo(t,i):this.scaleTo(1920,1080)}}clone(e,t){const i=this.getScene();if(!i)return this;const s=this.getSize(),r=this.serializeContent();let n;return n=this._isFullscreen?xN.CreateFullscreenUI(e??"Clone of "+this.name):t?xN.CreateForMesh(t,s.width,s.height):new xN(e??"Clone of "+this.name,s.width,s.height,i,!this.noMipmap,this.samplingMode),n.parseSerializedObject(r),n}static async ParseFromSnippetAsync(e,t,i,s){const r=i??xN.CreateFullscreenUI("ADT from snippet");if("_BLANK"===e)return r;const n=await xN._LoadURLContentAsync(xN.SnippetUrl+"/"+e.replace(/#/g,"/"),!0);return r.parseSerializedObject(n,t,s),r}parseFromSnippetAsync(e,t,i){return xN.ParseFromSnippetAsync(e,t,this,i)}static async ParseFromFileAsync(e,t,i,s){const r=i??xN.CreateFullscreenUI("ADT from URL"),n=await xN._LoadURLContentAsync(e);return r.parseSerializedObject(n,t,s),r}parseFromURLAsync(e,t,i){return xN.ParseFromFileAsync(e,t,this,i)}static _LoadURLContentAsync(e,t=!1){return""===e?Promise.reject("No URL provided"):new Promise(((i,s)=>{const r=new Pt;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){let e;if(t){const t=JSON.parse(JSON.parse(r.responseText).jsonPayload);e=t.encodedGui?new TextDecoder("utf-8").decode(ei(t.encodedGui)):t.gui}else e=r.responseText;const s=JSON.parse(e);i(s)}else s("Unable to load")})),r.open("GET",e),r.send()}))}static _Overlaps(e,t){return!(e.centerX>t.centerX+t.widthInPixels||e.centerX+e.widthInPixelst.centerY+t.heightInPixels)}static CreateForMesh(e,t=1024,i=1024,s=!0,r=!1,n,o=this._CreateMaterial,a=Pa.TRILINEAR_SAMPLINGMODE){const l=Cs(),h=new xN(`AdvancedDynamicTexture for ${e.name} [${l}]`,t,i,e.getScene(),!0,a,n);return o(e,l,h,r),h.attachToMesh(e,s),h}static _CreateMaterial(e,t,i,s){const r=W("BABYLON.StandardMaterial");if(!r)throw"StandardMaterial needs to be imported before as it contains a side-effect required by your code.";const n=new r(`AdvancedDynamicTextureMaterial for ${e.name} [${t}]`,e.getScene());n.backFaceCulling=!1,n.diffuseColor=Ee.Black(),n.specularColor=Ee.Black(),s?(n.diffuseTexture=i,n.emissiveTexture=i,i.hasAlpha=!0):(n.emissiveTexture=i,n.opacityTexture=i),e.material=n}static CreateForMeshTexture(e,t=1024,i=1024,s=!0,r,n=Pa.TRILINEAR_SAMPLINGMODE){const o=new xN(e.name+" AdvancedDynamicTexture",t,i,e.getScene(),!0,n,r);return o.attachToMesh(e,s),o}static CreateFullscreenUI(e,t=!0,i=null,s=Pa.BILINEAR_SAMPLINGMODE,r=!1){const n=new xN(e,0,0,i,!1,s),o=n.getScene(),a=new Vv(e+"_layer",null,o,!t);if(a.texture=n,n._layerToDispose=a,n._isFullscreen=!0,r&&o){const e=1/o.getEngine().getHardwareScalingLevel();n._rootContainer.scaleX=e,n._rootContainer.scaleY=e}return n.attach(),n}scale(e){super.scale(e),this.markAsDirty()}scaleTo(e,t){super.scaleTo(e,t),this.markAsDirty()}_checkGuiIsReady(){this.guiIsReady()&&(this.onGuiReadyObservable.notifyObservers(this),this.onGuiReadyObservable.clear())}guiIsReady(){return this._rootContainer.isReady()}}xN.SnippetUrl=N_.SnippetUrl,xN.AllowGPUOptimizations=!0;class bN{get renderTimeCounter(){return this._renderTime}get layoutTimeCounter(){return this._layoutTime}get captureRenderTime(){return this._captureRenderTime}set captureRenderTime(e){e!==this._captureRenderTime&&(this._captureRenderTime=e,e?(this._onBeginRenderObserver=this.texture.onBeginRenderObservable.add((()=>{this._renderTime.beginMonitoring()})),this._onEndRenderObserver=this.texture.onEndRenderObservable.add((()=>{this._renderTime.endMonitoring(!0)}))):(this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver),this._onBeginRenderObserver=null,this.texture.onEndRenderObservable.remove(this._onEndRenderObserver),this._onEndRenderObserver=null))}get captureLayoutTime(){return this._captureLayoutTime}set captureLayoutTime(e){e!==this._captureLayoutTime&&(this._captureLayoutTime=e,e?(this._onBeginLayoutObserver=this.texture.onBeginLayoutObservable.add((()=>{this._layoutTime.beginMonitoring()})),this._onEndLayoutObserver=this.texture.onEndLayoutObservable.add((()=>{this._layoutTime.endMonitoring(!0)}))):(this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver),this._onBeginLayoutObserver=null,this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver),this._onEndLayoutObserver=null))}constructor(e){this.texture=e,this._captureRenderTime=!1,this._renderTime=new wr,this._captureLayoutTime=!1,this._layoutTime=new wr,this._onBeginRenderObserver=null,this._onEndRenderObserver=null,this._onBeginLayoutObserver=null,this._onEndLayoutObserver=null}dispose(){this.texture.onBeginRenderObservable.remove(this._onBeginRenderObserver),this._onBeginRenderObserver=null,this.texture.onEndRenderObservable.remove(this._onEndRenderObserver),this._onEndRenderObserver=null,this.texture.onBeginLayoutObservable.remove(this._onBeginLayoutObserver),this._onBeginLayoutObserver=null,this.texture.onEndLayoutObservable.remove(this._onEndLayoutObserver),this._onEndLayoutObserver=null,this.texture=null}}const TN="XmlLoader Exception : XML file is malformed or corrupted.";class yN{constructor(e=null){this._nodes={},this._nodeTypes={element:1,attribute:2,text:3},this._isLoaded=!1,this._objectAttributes={textHorizontalAlignment:1,textVerticalAlignment:2,horizontalAlignment:3,verticalAlignment:4,stretch:5},e&&(this._parentClass=e)}_getChainElement(e){let t=window;this._parentClass&&(t=this._parentClass);let i=e;i=i.split(".");for(let e=0;e0&&u>d)throw"XmlLoader Exception : In the Grid element, the number of columns is defined in the first row, do not add more columns in the subsequent rows.";if(0==c){if(!n[e].attributes.getNamedItem("width"))throw"XmlLoader Exception : Width must be defined for all the grid columns in the first row";s=Number(n[e].attributes.getNamedItem("width").nodeValue),h=!!n[e].attributes.getNamedItem("isPixel")&&JSON.parse(n[e].attributes.getNamedItem("isPixel").nodeValue),t.addColumnDefinition(s,h)}a=n[e].children;for(let e=0;e{if(4===r.readyState&&200===r.status){if(!r.responseXML){if(s)return void s(TN);throw TN}const e=r.responseXML.documentElement;this._parseXml(e.firstChild,t),this._isLoaded=!0,i&&i()}},r.onerror=function(){s&&s("an error occurred during loading the layout")},r.open("GET",e,!0),r.send()}async loadLayoutAsync(e,t){return new Promise(((i,s)=>{this.loadLayout(e,t,i,s)}))}}class SN extends _e{constructor(e,t=0){super(e.x,e.y,e.z),this.buttonIndex=t}}class CN{get position(){return this._node?this._node.position:_e.Zero()}set position(e){this._node&&(this._node.position=e)}get scaling(){return this._node?this._node.scaling:new _e(1,1,1)}set scaling(e){this._node&&(this._isScaledByManager=!1,this._node.scaling=e)}get behaviors(){return this._behaviors}addBehavior(e){if(-1!==this._behaviors.indexOf(e))return this;e.init();const t=this._host.scene;return t.isLoading?t.onDataLoadedObservable.addOnce((()=>{e.attach(this)})):e.attach(this),this._behaviors.push(e),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),this}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}get isVisible(){return this._isVisible}set isVisible(e){if(this._isVisible===e)return;this._isVisible=e;const t=this.mesh;t&&t.setEnabled(e)}constructor(e){this.name=e,this._downCount=0,this._enterCount=-1,this._downPointerIds={},this._isVisible=!0,this._isScaledByManager=!1,this.onPointerMoveObservable=new K,this.onPointerOutObservable=new K,this.onPointerDownObservable=new K,this.onPointerUpObservable=new K,this.onPointerClickObservable=new K,this.onPointerEnterObservable=new K,this._behaviors=new Array}get typeName(){return this._getTypeName()}getClassName(){return this._getTypeName()}_getTypeName(){return"Control3D"}get node(){return this._node}get mesh(){return this._node instanceof _o?this._node:null}linkToTransformNode(e){return this._node&&(this._node.parent=e),this}_prepareNode(e){if(!this._node){if(this._node=this._createNode(e),!this.node)return;this._injectGUI3DReservedDataStore(this.node).control=this;const t=this.mesh;t&&(t.isPickable=!0,this._affectMaterial(t))}}_injectGUI3DReservedDataStore(e){return e.reservedDataStore=e.reservedDataStore??{},e.reservedDataStore.GUI3D=e.reservedDataStore.GUI3D??{},e.reservedDataStore.GUI3D}_createNode(e){return null}_affectMaterial(e){e.material=null}_isTouchButton3D(e){return void 0!==e._generatePointerEventType}_onPointerMove(e,t){this.onPointerMoveObservable.notifyObservers(t,-1,e,this)}_onPointerEnter(e){return-1===this._enterCount&&(this._enterCount=0),this._enterCount++,!(this._enterCount>1||(this.onPointerEnterObservable.notifyObservers(this,-1,e,this),this.pointerEnterAnimation&&this.pointerEnterAnimation(),0))}_onPointerOut(e){this._enterCount--,this._enterCount>0||(this._enterCount=0,this.onPointerOutObservable.notifyObservers(this,-1,e,this),this.pointerOutAnimation&&this.pointerOutAnimation())}_onPointerDown(e,t,i,s){return this._downCount++,this._downPointerIds[i]=this._downPointerIds[i]+1||1,1===this._downCount&&(this.onPointerDownObservable.notifyObservers(new SN(t,s),-1,e,this),this.pointerDownAnimation&&this.pointerDownAnimation(),!0)}_onPointerUp(e,t,i,s,r){this._downCount--,this._downPointerIds[i]--,this._downPointerIds[i]<=0&&delete this._downPointerIds[i],this._downCount<0?this._downCount=0:0==this._downCount&&(r&&(this._enterCount>0||-1===this._enterCount)&&this.onPointerClickObservable.notifyObservers(new SN(t,s),-1,e,this),this.onPointerUpObservable.notifyObservers(new SN(t,s),-1,e,this),this.pointerUpAnimation&&this.pointerUpAnimation())}forcePointerUp(e=null){if(null!==e)this._onPointerUp(this,_e.Zero(),e,0,!0);else{for(const e in this._downPointerIds)this._onPointerUp(this,_e.Zero(),+e,0,!0);this._downCount>0&&(this._downCount=1,this._onPointerUp(this,_e.Zero(),0,0,!0))}}_processObservables(e,t,i,s,r){if(this._isTouchButton3D(this)&&i&&(e=this._generatePointerEventType(e,i,this._downCount)),e===lr.POINTERMOVE){this._onPointerMove(this,t);const e=this._host._lastControlOver[s];return e&&e!==this&&e._onPointerOut(this),e!==this&&this._onPointerEnter(this),this._host._lastControlOver[s]=this,!0}return e===lr.POINTERDOWN?(this._onPointerDown(this,t,s,r),this._host._lastControlDown[s]=this,this._host._lastPickedControl=this,!0):(e===lr.POINTERUP||e===lr.POINTERDOUBLETAP)&&(this._host._lastControlDown[s]&&this._host._lastControlDown[s]._onPointerUp(this,t,s,r,!0),delete this._host._lastControlDown[s],!0)}_disposeNode(){this._node&&(this._node.dispose(),this._node=null)}dispose(){this.onPointerDownObservable.clear(),this.onPointerEnterObservable.clear(),this.onPointerMoveObservable.clear(),this.onPointerOutObservable.clear(),this.onPointerUpObservable.clear(),this.onPointerClickObservable.clear(),this._disposeNode();for(const e of this._behaviors)e.detach()}}class EN extends CN{constructor(){super(...arguments),this._contentResolution=512,this._contentScaleRatio=2}get content(){return this._content}set content(e){this._content=e,e&&this._host&&this._host.utilityLayer&&(this._facadeTexture?this._facadeTexture.rootContainer.clearControls():(this._facadeTexture=new xN("Facade",this._contentResolution,this._contentResolution,this._host.utilityLayer.utilityLayerScene,!0,Pa.TRILINEAR_SAMPLINGMODE),this._setFacadeTextureScaling(),this._facadeTexture.premulAlpha=!0),this._facadeTexture.addControl(e),this._applyFacade(this._facadeTexture))}_setFacadeTextureScaling(){this._facadeTexture&&(this._facadeTexture.rootContainer.scaleX=this._contentScaleRatio,this._facadeTexture.rootContainer.scaleY=this._contentScaleRatioY??this._contentScaleRatio)}get contentResolution(){return this._contentResolution}set contentResolution(e){this._contentResolution!==e&&(this._contentResolution=e,this._resetContent())}_disposeFacadeTexture(){this._facadeTexture&&(this._facadeTexture.dispose(),this._facadeTexture=null)}_resetContent(){this._disposeFacadeTexture(),this.content=this._content}_applyFacade(e){}}class AN extends EN{constructor(e){super(e)}_getTypeName(){return"AbstractButton3D"}_createNode(e){return new lo("button"+this.name,e)}}class PN extends AN{constructor(e,t){super(e),this._options={width:1,height:1,depth:.08,...t},this.pointerEnterAnimation=()=>{this.mesh&&(this._currentMaterial.emissiveColor=Ee.Red())},this.pointerOutAnimation=()=>{this._currentMaterial.emissiveColor=Ee.Black()},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_applyFacade(e){this._currentMaterial.emissiveTexture=e}_getTypeName(){return"Button3D"}_createNode(e){const t=new Array(6);for(let e=0;e<6;e++)t[e]=new pe(0,0,0,0);e.useRightHandedSystem?t[0].copyFromFloats(1,0,0,1):t[1].copyFromFloats(0,0,1,1);const i=cd(this.name+"_rootMesh",{width:this._options.width,height:this._options.height,depth:this._options.depth,faceUV:t,wrap:!0},e);return this._contentScaleRatioY=this._contentScaleRatio*this._options.width/this._options.height,this._setFacadeTextureScaling(),i}_affectMaterial(e){const t=new cu(this.name+"Material",e.getScene());t.specularColor=Ee.Black(),e.material=t,this._currentMaterial=t,this._resetContent()}dispose(){super.dispose(),this._disposeFacadeTexture(),this._currentMaterial&&this._currentMaterial.dispose()}}class IN extends CN{get children(){return this._children}get blockLayout(){return this._blockLayout}set blockLayout(e){this._blockLayout!==e&&(this._blockLayout=e,this._blockLayout||this._arrangeChildren())}constructor(e){super(e),this._blockLayout=!1,this._children=new Array}updateLayout(){return this._arrangeChildren(),this}containsControl(e){return-1!==this._children.indexOf(e)}addControl(e){return-1!==this._children.indexOf(e)||(e.parent=this,e._host=this._host,this._children.push(e),this._host.utilityLayer&&(e._prepareNode(this._host.utilityLayer.utilityLayerScene),e.node&&(e.node.parent=this.node),this.blockLayout||this._arrangeChildren())),this}_arrangeChildren(){}_createNode(e){return new lo("ContainerNode",e)}removeControl(e){const t=this._children.indexOf(e);return-1!==t&&(this._children.splice(t,1),e.parent=null,e._disposeNode()),this}_getTypeName(){return"Container3D"}dispose(){for(const e of this._children)e.dispose();this._children.length=0,super.dispose()}}IN.UNSET_ORIENTATION=0,IN.FACEORIGIN_ORIENTATION=1,IN.FACEORIGINREVERSED_ORIENTATION=2,IN.FACEFORWARD_ORIENTATION=3,IN.FACEFORWARDREVERSED_ORIENTATION=4;class RN extends IN{get orientation(){return this._orientation}set orientation(e){this._orientation!==e&&(this._orientation=e,Ds.SetImmediate((()=>{this._arrangeChildren()})))}get columns(){return this._columns}set columns(e){this._columns!==e&&(this._columns=e,this._rowThenColum=!0,Ds.SetImmediate((()=>{this._arrangeChildren()})))}get rows(){return this._rows}set rows(e){this._rows!==e&&(this._rows=e,this._rowThenColum=!1,Ds.SetImmediate((()=>{this._arrangeChildren()})))}constructor(e){super(e),this._columns=10,this._rows=0,this._rowThenColum=!0,this._orientation=IN.FACEORIGIN_ORIENTATION,this.margin=0}_arrangeChildren(){this._cellWidth=0,this._cellHeight=0;let e=0,t=0,i=0;const s=me.Invert(this.node.computeWorldMatrix(!0));for(const e of this._children){if(!e.mesh)continue;i++,e.mesh.computeWorldMatrix(!0);const t=e.mesh.getHierarchyBoundingVectors(),r=ve.Vector3[0],n=ve.Vector3[1];t.max.subtractToRef(t.min,n),n.scaleInPlace(.5),_e.TransformNormalToRef(n,s,r),this._cellWidth=Math.max(this._cellWidth,2*r.x),this._cellHeight=Math.max(this._cellHeight,2*r.y)}this._cellWidth+=2*this.margin,this._cellHeight+=2*this.margin,this._rowThenColum?(t=this._columns,e=Math.ceil(i/this._columns)):(e=this._rows,t=Math.ceil(i/this._rows));const r=.5*t*this._cellWidth,n=.5*e*this._cellHeight,o=[];let a=0;if(this._rowThenColum)for(let s=0;si));e++);else for(let s=0;si));t++);a=0;for(const e of this._children)e.mesh&&(this._mapGridNode(e,o[a]),a++);this._finalProcessing()}_finalProcessing(){}}class MN extends RN{constructor(){super(...arguments),this._radius=5}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,Ds.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh;if(!i)return;const s=this._cylindricalMapping(t);switch(e.position=s,this.orientation){case IN.FACEORIGIN_ORIENTATION:i.lookAt(new _e(2*s.x,s.y,2*s.z));break;case IN.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new _e(-s.x,s.y,-s.z));break;case IN.FACEFORWARD_ORIENTATION:break;case IN.FACEFORWARDREVERSED_ORIENTATION:i.rotate(Xr.Y,Math.PI,Ur.LOCAL)}}_cylindricalMapping(e){const t=new _e(0,e.y,this._radius),i=e.x/this._radius;return me.RotationYawPitchRollToRef(i,0,0,ve.Matrix[0]),_e.TransformNormal(t,ve.Matrix[0])}}Bi.ShadersStore.fluentVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 world;uniform mat4 viewProjection;varying vec2 vUV;\n#ifdef BORDER\nvarying vec2 scaleInfo;uniform float borderWidth;uniform vec3 scaleFactor;\n#endif\n#ifdef HOVERLIGHT\nvarying vec3 worldPosition;\n#endif\nvoid main(void) {vUV=uv;\n#ifdef BORDER\nvec3 scale=scaleFactor;float minScale=min(min(scale.x,scale.y),scale.z);float maxScale=max(max(scale.x,scale.y),scale.z);float minOverMiddleScale=minScale/(scale.x+scale.y+scale.z-minScale-maxScale);float areaYZ=scale.y*scale.z;float areaXZ=scale.x*scale.z;float areaXY=scale.x*scale.y;float scaledBorderWidth=borderWidth; \nif (abs(normal.x)==1.0) \n{scale.x=scale.y;scale.y=scale.z;if (areaYZ>areaXZ && areaYZ>areaXY)\n{scaledBorderWidth*=minOverMiddleScale;}}\nelse if (abs(normal.y)==1.0) \n{scale.x=scale.z;if (areaXZ>areaXY && areaXZ>areaYZ)\n{scaledBorderWidth*=minOverMiddleScale;}}\nelse \n{if (areaXY>areaYZ && areaXY>areaXZ)\n{scaledBorderWidth*=minOverMiddleScale;}}\nfloat scaleRatio=min(scale.x,scale.y)/max(scale.x,scale.y);if (scale.x>scale.y)\n{scaleInfo.x=1.0-(scaledBorderWidth*scaleRatio);scaleInfo.y=1.0-scaledBorderWidth;}\nelse\n{scaleInfo.x=1.0-scaledBorderWidth;scaleInfo.y=1.0-(scaledBorderWidth*scaleRatio);} \n#endif \nvec4 worldPos=world*vec4(position,1.0);\n#ifdef HOVERLIGHT\nworldPosition=worldPos.xyz;\n#endif\ngl_Position=viewProjection*worldPos;}\n";Bi.ShadersStore.fluentPixelShader="precision highp float;varying vec2 vUV;uniform vec4 albedoColor;\n#ifdef INNERGLOW\nuniform vec4 innerGlowColor;\n#endif\n#ifdef BORDER\nvarying vec2 scaleInfo;uniform float edgeSmoothingValue;uniform float borderMinValue;\n#endif\n#ifdef HOVERLIGHT\nvarying vec3 worldPosition;uniform vec3 hoverPosition;uniform vec4 hoverColor;uniform float hoverRadius;\n#endif\n#ifdef TEXTURE\nuniform sampler2D albedoSampler;uniform mat4 textureMatrix;vec2 finalUV;\n#endif\nvoid main(void) {vec3 albedo=albedoColor.rgb;float alpha=albedoColor.a;\n#ifdef TEXTURE\nfinalUV=vec2(textureMatrix*vec4(vUV,1.0,0.0));albedo=texture2D(albedoSampler,finalUV).rgb;\n#endif\n#ifdef HOVERLIGHT\nfloat pointToHover=(1.0-clamp(length(hoverPosition-worldPosition)/hoverRadius,0.,1.))*hoverColor.a;albedo=clamp(albedo+hoverColor.rgb*pointToHover,0.,1.);\n#else\nfloat pointToHover=1.0;\n#endif\n#ifdef BORDER \nfloat borderPower=10.0;float inverseBorderPower=1.0/borderPower;vec3 borderColor=albedo*borderPower;vec2 distanceToEdge;distanceToEdge.x=abs(vUV.x-0.5)*2.0;distanceToEdge.y=abs(vUV.y-0.5)*2.0;float borderValue=max(smoothstep(scaleInfo.x-edgeSmoothingValue,scaleInfo.x+edgeSmoothingValue,distanceToEdge.x),\nsmoothstep(scaleInfo.y-edgeSmoothingValue,scaleInfo.y+edgeSmoothingValue,distanceToEdge.y));borderColor=borderColor*borderValue*max(borderMinValue*inverseBorderPower,pointToHover); \nalbedo+=borderColor;alpha=max(alpha,borderValue);\n#endif\n#ifdef INNERGLOW\nvec2 uvGlow=(vUV-vec2(0.5,0.5))*(innerGlowColor.a*2.0);uvGlow=uvGlow*uvGlow;uvGlow=uvGlow*uvGlow;albedo+=mix(vec3(0.0,0.0,0.0),innerGlowColor.rgb,uvGlow.x+uvGlow.y); \n#endif\ngl_FragColor=vec4(albedo,alpha);}";class ON extends xl{constructor(){super(),this.INNERGLOW=!1,this.BORDER=!1,this.HOVERLIGHT=!1,this.TEXTURE=!1,this.rebuild()}}class DN extends ml{constructor(e,t){super(e,t),this.innerGlowColorIntensity=.5,this.innerGlowColor=new Ee(1,1,1),this.albedoColor=new Ee(.3,.35,.4),this.renderBorders=!1,this.borderWidth=.5,this.edgeSmoothingValue=.02,this.borderMinValue=.1,this.renderHoverLight=!1,this.hoverRadius=.01,this.hoverColor=new Ae(.3,.3,.3,1),this.hoverPosition=_e.Zero()}needAlphaBlending(){return 1!==this.alpha}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new ON);const s=this.getScene(),r=t.materialDefines;if(!this.checkReadyOnEveryCall&&t.effect&&r._renderId===s.getRenderId())return!0;if(r._areTexturesDirty)if(r.INNERGLOW=this.innerGlowColorIntensity>0,r.BORDER=this.renderBorders,r.HOVERLIGHT=this.renderHoverLight,this._albedoTexture){if(!this._albedoTexture.isReadyOrNotBlocking())return!1;r.TEXTURE=!0}else r.TEXTURE=!1;const n=s.getEngine();if(r.isDirty){r.markAsProcessed(),s.resetCachedMaterial();const e=[er.PositionKind];e.push(er.NormalKind),e.push(er.UVKind);const i="fluent",o=["world","viewProjection","innerGlowColor","albedoColor","borderWidth","edgeSmoothingValue","scaleFactor","borderMinValue","hoverColor","hoverPosition","hoverRadius","textureMatrix"],a=["albedoSampler"],l=[];ea({uniformsNames:o,uniformBuffersNames:l,samplers:a,defines:r,maxSimultaneousLights:4});const h=r.toString();t.setEffect(s.getEngine().createEffect(i,{attributes:e,uniformsNames:o,uniformBuffersNames:l,samplers:a,defines:h,fallbacks:null,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=s.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(n){if(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._mustRebind(s,n,i)&&(this._activeEffect.setColor4("albedoColor",this.albedoColor,this.alpha),r.INNERGLOW&&this._activeEffect.setColor4("innerGlowColor",this.innerGlowColor,this.innerGlowColorIntensity),r.BORDER&&(this._activeEffect.setFloat("borderWidth",this.borderWidth),this._activeEffect.setFloat("edgeSmoothingValue",this.edgeSmoothingValue),this._activeEffect.setFloat("borderMinValue",this.borderMinValue),t.getBoundingInfo().boundingBox.extendSize.multiplyToRef(t.scaling,ve.Vector3[0]),this._activeEffect.setVector3("scaleFactor",ve.Vector3[0])),r.HOVERLIGHT&&(this._activeEffect.setDirectColor4("hoverColor",this.hoverColor),this._activeEffect.setFloat("hoverRadius",this.hoverRadius),this._activeEffect.setVector3("hoverPosition",this.hoverPosition)),r.TEXTURE&&this._albedoTexture)){this._activeEffect.setTexture("albedoSampler",this._albedoTexture);const e=this._albedoTexture.getTextureMatrix();this._activeEffect.setMatrix("textureMatrix",e)}this._afterBind(t,this._activeEffect,i)}}getActiveTextures(){return super.getActiveTextures()}hasTexture(e){return!!super.hasTexture(e)}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new DN(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GUI.FluentMaterial",e}getClassName(){return"FluentMaterial"}static Parse(e,t,i){return St.Parse((()=>new DN(e.name,t)),e,t,i)}}Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],DN.prototype,"innerGlowColorIntensity",void 0),Ze([ot()],DN.prototype,"innerGlowColor",void 0),Ze([ot()],DN.prototype,"albedoColor",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],DN.prototype,"renderBorders",void 0),Ze([rt()],DN.prototype,"borderWidth",void 0),Ze([rt()],DN.prototype,"edgeSmoothingValue",void 0),Ze([rt()],DN.prototype,"borderMinValue",void 0),Ze([rt(),st("_markAllSubMeshesAsTexturesDirty")],DN.prototype,"renderHoverLight",void 0),Ze([rt()],DN.prototype,"hoverRadius",void 0),Ze([dt()],DN.prototype,"hoverColor",void 0),Ze([ht()],DN.prototype,"hoverPosition",void 0),Ze([nt("albedoTexture")],DN.prototype,"_albedoTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesAndMiscDirty")],DN.prototype,"albedoTexture",void 0),z("BABYLON.GUI.FluentMaterial",DN);class wN extends RN{get backPlateMargin(){return this._backPlateMargin}set backPlateMargin(e){this._backPlateMargin=e,this._children.length>=1&&(this.children.forEach((e=>{this._updateCurrentMinMax(e.position)})),this._updateMargins())}_createNode(e){const t=new ha(`menu_${this.name}`,e);return this._backPlate=cd("backPlate"+this.name,{size:1},e),this._backPlate.parent=t,t}_affectMaterial(e){this._backPlateMaterial=new DN(this.name+"backPlateMaterial",e.getScene()),this._backPlateMaterial.albedoColor=new Ee(.08,.15,.55),this._backPlateMaterial.renderBorders=!0,this._backPlateMaterial.renderHoverLight=!0,this._pickedPointObserver=this._host.onPickedPointChangedObservable.add((e=>{e?(this._backPlateMaterial.hoverPosition=e,this._backPlateMaterial.hoverColor.a=1):this._backPlateMaterial.hoverColor.a=0})),this._backPlate.material=this._backPlateMaterial}_mapGridNode(e,t){e.mesh&&(e.position=t.clone(),this._updateCurrentMinMax(t))}_finalProcessing(){this._updateMargins()}_updateCurrentMinMax(e){this._currentMin||(this._currentMin=e.clone(),this._currentMax=e.clone()),this._currentMin.minimizeInPlace(e),this._currentMax.maximizeInPlace(e)}_updateMargins(){if(this._children.length>0){this._currentMin.addInPlaceFromFloats(-this._cellWidth/2,-this._cellHeight/2,0),this._currentMax.addInPlaceFromFloats(this._cellWidth/2,this._cellHeight/2,0);const e=this._currentMax.subtract(this._currentMin);this._backPlate.scaling.x=e.x+this._cellWidth*this.backPlateMargin,this._backPlate.scaling.y=e.y+this._cellHeight*this.backPlateMargin,this._backPlate.scaling.z=.001;for(let t=0;t0.0 ? g : 1.0;Gradient2=Position_Object.z>0.0 ? 1.0 : g;} else {Gradient1=g+(1.0-g)*(Radial_Gradient);Gradient2=1.0;}}\nvoid Pick_Radius_B144(\nfloat Radius,\nfloat Radius_Top_Left,\nfloat Radius_Top_Right,\nfloat Radius_Bottom_Left,\nfloat Radius_Bottom_Right,\nvec3 Position,\nout float Result)\n{bool whichY=Position.y>0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid main()\n{vec3 Nrm_World_Q128;Nrm_World_Q128=normalize((world*vec4(normal,0.0)).xyz);vec3 Tangent_World_Q131;vec3 Tangent_World_N_Q131;float Tangent_Length_Q131;Tangent_World_Q131=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q131=length(Tangent_World_Q131);Tangent_World_N_Q131=Tangent_World_Q131/Tangent_Length_Q131;vec3 Binormal_World_Q132;vec3 Binormal_World_N_Q132;float Binormal_Length_Q132;Object_To_World_Dir_B132(vec3(0,1,0),Binormal_World_Q132,Binormal_World_N_Q132,Binormal_Length_Q132);float Anisotropy_Q133=Tangent_Length_Q131/Binormal_Length_Q132;vec3 Result_Q177;Result_Q177=mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(_Use_Global_Left_Index_));vec3 Result_Q178;Result_Q178=mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(_Use_Global_Right_Index_));float Result_Q144;Pick_Radius_B144(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q144);vec3 Dir_Q140;PickDir_B140(_Angle_,Tangent_World_N_Q131,Binormal_World_N_Q132,Dir_Q140);float Radius_Q147;float Line_Width_Q147;RelativeOrAbsoluteDetail_B147(Result_Q144,_Line_Width_,_Absolute_Sizes_,Binormal_Length_Q132,Radius_Q147,Line_Width_Q147);vec4 Out_Color_Q145=vec4(Radius_Q147,Line_Width_Q147,0,1);vec3 New_P_Q129;vec2 New_UV_Q129;float Radial_Gradient_Q129;vec3 Radial_Dir_Q129;Move_Verts_B129(Anisotropy_Q133,position,Radius_Q147,New_P_Q129,New_UV_Q129,Radial_Gradient_Q129,Radial_Dir_Q129);vec3 Pos_World_Q115;Object_To_World_Pos_B115(New_P_Q129,Pos_World_Q115);vec4 Blob_Info_Q180;\n#if BLOB_ENABLE\nBlob_Vertex_B180(Pos_World_Q115,Nrm_World_Q128,Tangent_World_N_Q131,Binormal_World_N_Q132,Result_Q177,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q180);\n#else\nBlob_Info_Q180=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q181;\n#if BLOB_ENABLE_2\nBlob_Vertex_B180(Pos_World_Q115,Nrm_World_Q128,Tangent_World_N_Q131,Binormal_World_N_Q132,Result_Q178,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q181);\n#else\nBlob_Info_Q181=vec4(0,0,0,0);\n#endif\nfloat Gradient1_Q130;float Gradient2_Q130;\n#if SMOOTH_EDGES\nEdge_AA_Vertex_B130(Pos_World_Q115,position,normal,cameraPosition,Radial_Gradient_Q129,Radial_Dir_Q129,tangent,Gradient1_Q130,Gradient2_Q130);\n#else\nGradient1_Q130=1.0;Gradient2_Q130=1.0;\n#endif\nvec2 Rect_UV_Q139;vec4 Rect_Parms_Q139;vec2 Scale_XY_Q139;vec2 Line_UV_Q139;Round_Rect_Vertex_B139(New_UV_Q129,Radius_Q147,0.0,Anisotropy_Q133,Gradient1_Q130,Gradient2_Q130,Rect_UV_Q139,Rect_Parms_Q139,Scale_XY_Q139,Line_UV_Q139);vec3 Line_Vertex_Q135;Line_Vertex_B135(Scale_XY_Q139,Line_UV_Q139,0.0,_Rate_,_Highlight_Transform_,Line_Vertex_Q135);vec3 Position=Pos_World_Q115;vec3 Normal=Dir_Q140;vec2 UV=Rect_UV_Q139;vec3 Tangent=Line_Vertex_Q135;vec3 Binormal=Nrm_World_Q128;vec4 Color=Out_Color_Q145;vec4 Extra1=Rect_Parms_Q139;vec4 Extra2=Blob_Info_Q180;vec4 Extra3=Blob_Info_Q181;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class FN extends xl{constructor(){super(),this.BLOB_ENABLE=!0,this.BLOB_ENABLE_2=!0,this.SMOOTH_EDGES=!0,this.IRIDESCENT_MAP_ENABLE=!0,this._needNormals=!0,this.rebuild()}}class LN extends ml{constructor(e,t){super(e,t),this.radius=.03,this.lineWidth=.01,this.absoluteSizes=!1,this._filterWidth=1,this.baseColor=new Ae(.0392157,.0666667,.207843,1),this.lineColor=new Ae(.14902,.133333,.384314,1),this.blobIntensity=.98,this.blobFarSize=.04,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.08,this.blobNearSize=.22,this.blobPulse=0,this.blobFade=0,this.blobNearSize2=.22,this.blobPulse2=0,this.blobFade2=0,this._rate=.135,this.highlightColor=new Ae(.98,.98,.98,1),this.highlightWidth=.25,this._highlightTransform=new pe(1,1,0,0),this._highlight=1,this.iridescenceIntensity=0,this.iridescenceEdgeIntensity=1,this._angle=-45,this.fadeOut=1,this._reflected=!0,this._frequency=1,this._verticalOffset=0,this.globalLeftIndexTipPosition=_e.Zero(),this._globalLeftIndexTipPosition4=pe.Zero(),this.globalRightIndexTipPosition=_e.Zero(),this._globalRightIndexTipPosition4=pe.Zero(),this.alphaMode=N_.ALPHA_DISABLE,this.backFaceCulling=!1,this._blobTexture=new Pa(LN.BLOB_TEXTURE_URL,this.getScene(),!0,!1,Pa.NEAREST_SAMPLINGMODE),this._iridescentMap=new Pa(LN.IM_TEXTURE_URL,this.getScene(),!0,!1,Pa.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new FN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="fluentBackplate",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Absolute_Sizes_","_Filter_Width_","_Base_Color_","_Line_Color_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Rate_","_Highlight_Color_","_Highlight_Width_","_Highlight_Transform_","_Highlight_","_Iridescence_Intensity_","_Iridescence_Edge_Intensity_","_Angle_","_Fade_Out_","_Reflected_","_Frequency_","_Vertical_Offset_","_Iridescent_Map_","_Use_Global_Left_Index_","_Use_Global_Right_Index_","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position"],h=["_Blob_Texture_","_Iridescent_Map_"],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera?.position??_e.ZeroReadOnly),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Base_Color_",this.baseColor),this._activeEffect.setDirectColor4("_Line_Color_",this.lineColor),this._activeEffect.setFloat("_Radius_Top_Left_",1),this._activeEffect.setFloat("_Radius_Top_Right_",1),this._activeEffect.setFloat("_Radius_Bottom_Left_",1),this._activeEffect.setFloat("_Radius_Bottom_Right_",1),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setFloat("_Rate_",this._rate),this._activeEffect.setDirectColor4("_Highlight_Color_",this.highlightColor),this._activeEffect.setFloat("_Highlight_Width_",this.highlightWidth),this._activeEffect.setVector4("_Highlight_Transform_",this._highlightTransform),this._activeEffect.setFloat("_Highlight_",this._highlight),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setFloat("_Iridescence_Edge_Intensity_",this.iridescenceEdgeIntensity),this._activeEffect.setFloat("_Angle_",this._angle),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._activeEffect.setFloat("_Reflected_",this._reflected?1:0),this._activeEffect.setFloat("_Frequency_",this._frequency),this._activeEffect.setFloat("_Vertical_Offset_",this._verticalOffset),this._activeEffect.setTexture("_Iridescent_Map_",this._iridescentMap),this._activeEffect.setFloat("_Use_Global_Left_Index_",1),this._activeEffect.setFloat("_Use_Global_Right_Index_",1),this._globalLeftIndexTipPosition4.set(this.globalLeftIndexTipPosition.x,this.globalLeftIndexTipPosition.y,this.globalLeftIndexTipPosition.z,1),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this._globalLeftIndexTipPosition4),this._globalRightIndexTipPosition4.set(this.globalRightIndexTipPosition.x,this.globalRightIndexTipPosition.y,this.globalRightIndexTipPosition.z,1),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this._globalRightIndexTipPosition4),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._blobTexture.dispose(),this._iridescentMap.dispose()}clone(e){return St.Clone((()=>new LN(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FluentBackplateMaterial",e}getClassName(){return"FluentBackplateMaterial"}static Parse(e,t,i){return St.Parse((()=>new LN(e.name,t)),e,t,i)}}LN.BLOB_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-backplate-blob.png",LN.IM_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-backplate-iridescence.png",Ze([rt()],LN.prototype,"radius",void 0),Ze([rt()],LN.prototype,"lineWidth",void 0),Ze([rt()],LN.prototype,"absoluteSizes",void 0),Ze([rt()],LN.prototype,"baseColor",void 0),Ze([rt()],LN.prototype,"lineColor",void 0),Ze([rt()],LN.prototype,"blobIntensity",void 0),Ze([rt()],LN.prototype,"blobFarSize",void 0),Ze([rt()],LN.prototype,"blobNearDistance",void 0),Ze([rt()],LN.prototype,"blobFarDistance",void 0),Ze([rt()],LN.prototype,"blobFadeLength",void 0),Ze([rt()],LN.prototype,"blobNearSize",void 0),Ze([rt()],LN.prototype,"blobPulse",void 0),Ze([rt()],LN.prototype,"blobFade",void 0),Ze([rt()],LN.prototype,"blobNearSize2",void 0),Ze([rt()],LN.prototype,"blobPulse2",void 0),Ze([rt()],LN.prototype,"blobFade2",void 0),Ze([rt()],LN.prototype,"highlightColor",void 0),Ze([rt()],LN.prototype,"highlightWidth",void 0),Ze([rt()],LN.prototype,"iridescenceIntensity",void 0),Ze([rt()],LN.prototype,"iridescenceEdgeIntensity",void 0),Ze([rt()],LN.prototype,"fadeOut",void 0),Ze([ht()],LN.prototype,"globalLeftIndexTipPosition",void 0),Ze([ht()],LN.prototype,"globalRightIndexTipPosition",void 0),z("BABYLON.GUI.FluentBackplateMaterial",LN);class BN extends CN{set renderingGroupId(e){this._model.renderingGroupId=e}get renderingGroupId(){return this._model.renderingGroupId}get material(){return this._material}get shareMaterials(){return this._shareMaterials}constructor(e,t=!0){super(e),this._shareMaterials=t}_getTypeName(){return"HolographicBackplate"}_createNode(e){const t=cd((this.name??"HolographicBackplate")+"_CollisionMesh",{width:1,height:1,depth:1},e);return t.isPickable=!0,t.visibility=0,fl.ImportMeshAsync(void 0,BN.MODEL_BASE_URL,BN.MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_frontPlate`,i.isPickable=!1,i.parent=t,this._material&&(i.material=this._material),this._model=i})),t}_createMaterial(e){this._material=new LN(this.name+" Material",e.getScene())}_affectMaterial(e){this._shareMaterials?this._host._touchSharedMaterials.fluentBackplateMaterial?this._material=this._host._touchSharedMaterials.fluentBackplateMaterial:(this._createMaterial(e),this._host._touchSharedMaterials.fluentBackplateMaterial=this._material):this._createMaterial(e)}dispose(){super.dispose(),this.shareMaterials||this._material.dispose(),this._model.dispose()}}BN.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",BN.MODEL_FILENAME="mrtk-fluent-backplate.glb";class kN extends PN{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=Wa("",{size:1},this._backPlate._scene);const t=Wa("",{size:1,sideOrientation:ha.DOUBLESIDE},this._backPlate._scene),i=new cu("",this._backPlate._scene);i.diffuseColor=Ee.FromHexString("#212121"),t.material=i,t.isPickable=!1,this._tooltipMesh.addChild(t),t.position=_e.Forward(e).scale(.05),this._tooltipMesh.scaling.y=1/3,this._tooltipMesh.position=_e.Up().scale(.7).add(_e.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._backPlate,this._tooltipTexture=xN.CreateForMesh(this._tooltipMesh),this._tooltipTextBlock=new Fw,this._tooltipTextBlock.scaleY=3,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=130,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new Va,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?this._tooltipTextBlock.text:null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}constructor(e,t=!0){super(e),this._shareMaterials=!0,this._shareMaterials=t,this.pointerEnterAnimation=()=>{this.mesh&&this._frontPlate.setEnabled(!0)},this.pointerOutAnimation=()=>{this.mesh&&this._frontPlate.setEnabled(!1)}}_getTypeName(){return"HolographicButton"}_rebuildContent(){this._disposeFacadeTexture();const e=new kw;if(e.isVertical=!0,Ut()&&document.createElement&&this._imageUrl){const t=new Lw;t.source=this._imageUrl,t.paddingTop="40px",t.height="180px",t.width="100px",t.paddingBottom="40px",e.addControl(t)}if(this._text){const t=new Fw;t.text=this._text,t.color="white",t.height="30px",t.fontSize=24,e.addControl(t)}this._frontPlate&&(this.content=e)}_createNode(e){return this._backPlate=cd(this.name+"BackMesh",{width:1,height:1,depth:.08},e),this._frontPlate=cd(this.name+"FrontMesh",{width:1,height:1,depth:.08},e),this._frontPlate.parent=this._backPlate,this._frontPlate.position=_e.Forward(e.useRightHandedSystem).scale(-.08),this._frontPlate.isPickable=!1,this._frontPlate.setEnabled(!1),this._textPlate=super._createNode(e),this._textPlate.parent=this._backPlate,this._textPlate.position=_e.Forward(e.useRightHandedSystem).scale(-.08),this._textPlate.isPickable=!1,this._backPlate}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e}_createBackMaterial(e){this._backMaterial=new DN(this.name+"Back Material",e.getScene()),this._backMaterial.renderHoverLight=!0,this._pickedPointObserver=this._host.onPickedPointChangedObservable.add((e=>{e?(this._backMaterial.hoverPosition=e,this._backMaterial.hoverColor.a=1):this._backMaterial.hoverColor.a=0}))}_createFrontMaterial(e){this._frontMaterial=new DN(this.name+"Front Material",e.getScene()),this._frontMaterial.innerGlowColorIntensity=0,this._frontMaterial.alpha=.5,this._frontMaterial.renderBorders=!0}_createPlateMaterial(e){this._plateMaterial=new cu(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=Ee.Black()}_affectMaterial(e){this._shareMaterials?(this._host._sharedMaterials.backFluentMaterial?this._backMaterial=this._host._sharedMaterials.backFluentMaterial:(this._createBackMaterial(e),this._host._sharedMaterials.backFluentMaterial=this._backMaterial),this._host._sharedMaterials.frontFluentMaterial?this._frontMaterial=this._host._sharedMaterials.frontFluentMaterial:(this._createFrontMaterial(e),this._host._sharedMaterials.frontFluentMaterial=this._frontMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._frontPlate.material=this._frontMaterial,this._textPlate.material=this._plateMaterial,this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}Bi.ShadersStore.fluentButtonPixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;uniform float _Edge_Width_;uniform vec4 _Edge_Color_;uniform bool _Relative_Width_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Active_Face_Dir_;uniform vec3 _Active_Face_Up_;uniform bool Enable_Fade;uniform float _Fade_Width_;uniform bool _Smooth_Active_Face_;uniform bool _Show_Frame_;uniform bool _Use_Blob_Texture_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;void Holo_Edge_Fragment_B35(\nvec4 Edges,\nfloat Edge_Width,\nout float NotEdge)\n{vec2 c=vec2(min(Edges.r,Edges.g),min(Edges.b,Edges.a));vec2 df=fwidth(c)*Edge_Width;vec2 g=clamp(c/df,0.0,1.0);NotEdge=g.x*g.y;}\nvoid Blob_Fragment_B39(\nvec2 UV,\nvec3 Blob_Info,\nsampler2D Blob_Texture,\nout vec4 Blob_Color)\n{float k=dot(UV,UV);Blob_Color=Blob_Info.y*texture(Blob_Texture,vec2(vec2(sqrt(k),Blob_Info.x).x,1.0-vec2(sqrt(k),Blob_Info.x).y))*(1.0-clamp(k,0.0,1.0));}\nvec2 FilterStep(vec2 Edge,vec2 X)\n{vec2 dX=max(fwidth(X),vec2(0.00001,0.00001));return clamp( (X+dX-max(Edge,X-dX))/(dX*2.0),0.0,1.0);}\nvoid Wireframe_Fragment_B59(\nvec3 Widths,\nvec2 UV,\nfloat Proximity,\nvec4 Edge_Color,\nout vec4 Wireframe)\n{vec2 c=min(UV,vec2(1.0,1.0)-UV);vec2 g=FilterStep(Widths.xy*0.5,c); \nWireframe=(1.0-min(g.x,g.y))*Proximity*Edge_Color;}\nvoid Proximity_B53(\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Proximity_Max_Intensity,\nfloat Proximity_Near_Radius,\nvec3 Position,\nvec3 Show_Selection,\nvec4 Extra1,\nfloat Dist_To_Face,\nfloat Intensity,\nout float Proximity)\n{vec2 delta1=Extra1.xy;vec2 delta2=Extra1.zw;float d2=sqrt(min(dot(delta1,delta1),dot(delta2,delta2))+Dist_To_Face*Dist_To_Face);Proximity=Intensity*Proximity_Max_Intensity*(1.0-clamp(d2/Proximity_Near_Radius,0.0,1.0))*(1.0-Show_Selection.x)+Show_Selection.x;}\nvoid To_XYZ_B46(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid main()\n{float NotEdge_Q35;\n#if ENABLE_FADE\nHolo_Edge_Fragment_B35(vColor,_Fade_Width_,NotEdge_Q35);\n#else\nNotEdge_Q35=1.0;\n#endif\nvec4 Blob_Color_Q39;float k=dot(vUV,vUV);vec2 blobTextureCoord=vec2(vec2(sqrt(k),vTangent.x).x,1.0-vec2(sqrt(k),vTangent.x).y);vec4 blobColor=mix(vec4(1.0,1.0,1.0,1.0)*step(1.0-vTangent.x,clamp(sqrt(k)+0.1,0.0,1.0)),texture(_Blob_Texture_,blobTextureCoord),float(_Use_Blob_Texture_));Blob_Color_Q39=vTangent.y*blobColor*(1.0-clamp(k,0.0,1.0));float Is_Quad_Q24;Is_Quad_Q24=vNormal.z;vec3 Blob_Position_Q41= mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(Use_Global_Left_Index));vec3 Blob_Position_Q42= mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(Use_Global_Right_Index));float X_Q46;float Y_Q46;float Z_Q46;To_XYZ_B46(vBinormal,X_Q46,Y_Q46,Z_Q46);float Proximity_Q53;Proximity_B53(Blob_Position_Q41,Blob_Position_Q42,_Proximity_Max_Intensity_,_Proximity_Near_Radius_,vPosition,vBinormal,vExtra1,Y_Q46,Z_Q46,Proximity_Q53);vec4 Wireframe_Q59;Wireframe_Fragment_B59(vNormal,vUV,Proximity_Q53,_Edge_Color_,Wireframe_Q59);vec4 Wire_Or_Blob_Q23=mix(Wireframe_Q59,Blob_Color_Q39,Is_Quad_Q24);vec4 Result_Q22;Result_Q22=mix(Wire_Or_Blob_Q23,vec4(0.3,0.3,0.3,0.3),float(_Show_Frame_));vec4 Final_Color_Q37=NotEdge_Q35*Result_Q22;vec4 Out_Color=Final_Color_Q37;float Clip_Threshold=0.0;bool To_sRGB=false;gl_FragColor=Out_Color;}";Bi.ShadersStore.fluentButtonVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform float _Edge_Width_;uniform vec4 _Edge_Color_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Active_Face_Dir_;uniform vec3 _Active_Face_Up_;uniform bool _Enable_Fade_;uniform float _Fade_Width_;uniform bool _Smooth_Active_Face_;uniform bool _Show_Frame_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;void Blob_Vertex_B47(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nvec3 Blob_Position,\nfloat Intensity,\nfloat Blob_Near_Size,\nfloat Blob_Far_Size,\nfloat Blob_Near_Distance,\nfloat Blob_Far_Distance,\nvec4 Vx_Color,\nvec2 UV,\nvec3 Face_Center,\nvec2 Face_Size,\nvec2 In_UV,\nfloat Blob_Fade_Length,\nfloat Selection_Fade,\nfloat Selection_Fade_Size,\nfloat Inner_Fade,\nvec3 Active_Face_Center,\nfloat Blob_Pulse,\nfloat Blob_Fade,\nfloat Blob_Enabled,\nout vec3 Out_Position,\nout vec2 Out_UV,\nout vec3 Blob_Info)\n{float blobSize,fadeIn;vec3 Hit_Position;Blob_Info=vec3(0.0,0.0,0.0);float Hit_Distance=dot(Blob_Position-Face_Center,Normal);Hit_Position=Blob_Position-Hit_Distance*Normal;float absD=abs(Hit_Distance);float lerpVal=clamp((absD-Blob_Near_Distance)/(Blob_Far_Distance-Blob_Near_Distance),0.0,1.0);fadeIn=1.0-clamp((absD-Blob_Far_Distance)/Blob_Fade_Length,0.0,1.0);float innerFade=1.0-clamp(-Hit_Distance/Inner_Fade,0.0,1.0);float farClip=clamp(1.0-step(Blob_Far_Distance+Blob_Fade_Length,absD),0.0,1.0);float size=mix(Blob_Near_Size,Blob_Far_Size,lerpVal)*farClip;blobSize=mix(size,Selection_Fade_Size,Selection_Fade)*innerFade*Blob_Enabled;Blob_Info.x=lerpVal*0.5+0.5;Blob_Info.y=fadeIn*Intensity*(1.0-Selection_Fade)*Blob_Fade;Blob_Info.x*=(1.0-Blob_Pulse);vec3 delta=Hit_Position-Face_Center;vec2 blobCenterXY=vec2(dot(delta,Tangent),dot(delta,Bitangent));vec2 quadUVin=2.0*UV-1.0; \nvec2 blobXY=blobCenterXY+quadUVin*blobSize;vec2 blobClipped=clamp(blobXY,-Face_Size*0.5,Face_Size*0.5);vec2 blobUV=(blobClipped-blobCenterXY)/max(blobSize,0.0001)*2.0;vec3 blobCorner=Face_Center+blobClipped.x*Tangent+blobClipped.y*Bitangent;Out_Position=mix(Position,blobCorner,Vx_Color.rrr);Out_UV=mix(In_UV,blobUV,Vx_Color.rr);}\nvec2 ProjectProximity(\nvec3 blobPosition,\nvec3 position,\nvec3 center,\nvec3 dir,\nvec3 xdir,\nvec3 ydir,\nout float vdistance\n)\n{vec3 delta=blobPosition-position;vec2 xy=vec2(dot(delta,xdir),dot(delta,ydir));vdistance=abs(dot(delta,dir));return xy;}\nvoid Proximity_Vertex_B66(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Active_Face_Center,\nvec3 Active_Face_Dir,\nvec3 Position,\nfloat Proximity_Far_Distance,\nfloat Relative_Scale,\nfloat Proximity_Anisotropy,\nvec3 Up,\nout vec4 Extra1,\nout float Distance_To_Face,\nout float Intensity)\n{vec3 Active_Face_Dir_X=normalize(cross(Active_Face_Dir,Up));vec3 Active_Face_Dir_Y=cross(Active_Face_Dir,Active_Face_Dir_X);float distz1,distz2;Extra1.xy=ProjectProximity(Blob_Position,Position,Active_Face_Center,Active_Face_Dir,Active_Face_Dir_X*Proximity_Anisotropy,Active_Face_Dir_Y,distz1)/Relative_Scale;Extra1.zw=ProjectProximity(Blob_Position_2,Position,Active_Face_Center,Active_Face_Dir,Active_Face_Dir_X*Proximity_Anisotropy,Active_Face_Dir_Y,distz2)/Relative_Scale;Distance_To_Face=dot(Active_Face_Dir,Position-Active_Face_Center);Intensity=1.0-clamp(min(distz1,distz2)/Proximity_Far_Distance,0.0,1.0);}\nvoid Holo_Edge_Vertex_B44(\nvec3 Incident,\nvec3 Normal,\nvec2 UV,\nvec3 Tangent,\nvec3 Bitangent,\nbool Smooth_Active_Face,\nfloat Active,\nout vec4 Holo_Edges)\n{float NdotI=dot(Incident,Normal);vec2 flip=(UV-vec2(0.5,0.5));float udot=dot(Incident,Tangent)*flip.x*NdotI;float uval=1.0-float(udot>0.0);float vdot=-dot(Incident,Bitangent)*flip.y*NdotI;float vval=1.0-float(vdot>0.0);float Smooth_And_Active=step(1.0,float(Smooth_Active_Face && Active>0.0));uval=mix(uval,max(1.0,uval),Smooth_And_Active); \nvval=mix(vval,max(1.0,vval),Smooth_And_Active);Holo_Edges=vec4(1.0,1.0,1.0,1.0)-vec4(uval*UV.x,uval*(1.0-UV.x),vval*UV.y,vval*(1.0-UV.y));}\nvoid Object_To_World_Pos_B13(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Choose_Blob_B38(\nvec4 Vx_Color,\nvec3 Position1,\nvec3 Position2,\nbool Blob_Enable_1,\nbool Blob_Enable_2,\nfloat Near_Size_1,\nfloat Near_Size_2,\nfloat Blob_Inner_Fade_1,\nfloat Blob_Inner_Fade_2,\nfloat Blob_Pulse_1,\nfloat Blob_Pulse_2,\nfloat Blob_Fade_1,\nfloat Blob_Fade_2,\nout vec3 Position,\nout float Near_Size,\nout float Inner_Fade,\nout float Blob_Enable,\nout float Fade,\nout float Pulse)\n{Position=Position1*(1.0-Vx_Color.g)+Vx_Color.g*Position2;float b1=float(Blob_Enable_1);float b2=float(Blob_Enable_2);Blob_Enable=b1+(b2-b1)*Vx_Color.g;Pulse=Blob_Pulse_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Pulse_2;Fade=Blob_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Fade_2;Near_Size=Near_Size_1*(1.0-Vx_Color.g)+Vx_Color.g*Near_Size_2;Inner_Fade=Blob_Inner_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Inner_Fade_2;}\nvoid Wireframe_Vertex_B51(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Edge_Width,\nvec2 Face_Size,\nout vec3 Wire_Vx_Pos,\nout vec2 UV,\nout vec2 Widths)\n{Widths.xy=Edge_Width/Face_Size;float x=dot(Position,Tangent);float y=dot(Position,Bitangent);float dx=0.5-abs(x);float newx=(0.5-dx*Widths.x*2.0)*sign(x);float dy=0.5-abs(y);float newy=(0.5-dy*Widths.y*2.0)*sign(y);Wire_Vx_Pos=Normal*0.5+newx*Tangent+newy*Bitangent;UV.x=dot(Wire_Vx_Pos,Tangent)+0.5;UV.y=dot(Wire_Vx_Pos,Bitangent)+0.5;}\nvec2 ramp2(vec2 start,vec2 end,vec2 x)\n{return clamp((x-start)/(end-start),vec2(0.0,0.0),vec2(1.0,1.0));}\nfloat computeSelection(\nvec3 blobPosition,\nvec3 normal,\nvec3 tangent,\nvec3 bitangent,\nvec3 faceCenter,\nvec2 faceSize,\nfloat selectionFuzz,\nfloat farDistance,\nfloat fadeLength\n)\n{vec3 delta=blobPosition-faceCenter;float absD=abs(dot(delta,normal));float fadeIn=1.0-clamp((absD-farDistance)/fadeLength,0.0,1.0);vec2 blobCenterXY=vec2(dot(delta,tangent),dot(delta,bitangent));vec2 innerFace=faceSize*(1.0-selectionFuzz)*0.5;vec2 selectPulse=ramp2(-faceSize*0.5,-innerFace,blobCenterXY)-ramp2(innerFace,faceSize*0.5,blobCenterXY);return selectPulse.x*selectPulse.y*fadeIn;}\nvoid Selection_Vertex_B48(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec2 Face_Size,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Selection_Fuzz,\nfloat Selected,\nfloat Far_Distance,\nfloat Fade_Length,\nvec3 Active_Face_Dir,\nout float Show_Selection)\n{float select1=computeSelection(Blob_Position,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float select2=computeSelection(Blob_Position_2,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float Active=max(0.0,dot(Active_Face_Dir,Normal));Show_Selection=mix(max(select1,select2),1.0,Selected)*Active;}\nvoid Proximity_Visibility_B54(\nfloat Selection,\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Input_Width,\nfloat Proximity_Far_Distance,\nfloat Proximity_Radius,\nvec3 Active_Face_Center,\nvec3 Active_Face_Dir,\nout float Width)\n{vec3 boxEdges=(world*vec4(vec3(0.5,0.5,0.5),0.0)).xyz;float boxMaxSize=length(boxEdges);float d1=dot(Proximity_Center-Active_Face_Center,Active_Face_Dir);vec3 blob1=Proximity_Center-d1*Active_Face_Dir;float d2=dot(Proximity_Center_2-Active_Face_Center,Active_Face_Dir);vec3 blob2=Proximity_Center_2-d2*Active_Face_Dir;vec3 delta1=blob1-Active_Face_Center;vec3 delta2=blob2-Active_Face_Center;float dist1=dot(delta1,delta1);float dist2=dot(delta2,delta2);float nearestProxDist=sqrt(min(dist1,dist2));Width=Input_Width*(1.0-step(boxMaxSize+Proximity_Radius,nearestProxDist))*(1.0-step(Proximity_Far_Distance,min(d1,d2))*(1.0-step(0.0001,Selection)));}\nvoid Object_To_World_Dir_B67(\nvec3 Dir_Object,\nout vec3 Dir_World)\n{Dir_World=(world*vec4(Dir_Object,0.0)).xyz;}\nvoid main()\n{vec3 Active_Face_Center_Q49;Active_Face_Center_Q49=(world*vec4(_Active_Face_Dir_*0.5,1.0)).xyz;vec3 Blob_Position_Q41= mix(_Blob_Position_,Global_Left_Index_Tip_Position.xyz,float(Use_Global_Left_Index));vec3 Blob_Position_Q42= mix(_Blob_Position_2_,Global_Right_Index_Tip_Position.xyz,float(Use_Global_Right_Index));vec3 Active_Face_Dir_Q64=normalize((world*vec4(_Active_Face_Dir_,0.0)).xyz);float Relative_Scale_Q57;\n#if RELATIVE_WIDTH\nRelative_Scale_Q57=length((world*vec4(vec3(0,1,0),0.0)).xyz);\n#else\nRelative_Scale_Q57=1.0;\n#endif\nvec3 Tangent_World_Q30;Tangent_World_Q30=(world*vec4(tangent,0.0)).xyz;vec3 Binormal_World_Q31;Binormal_World_Q31=(world*vec4((cross(normal,tangent)),0.0)).xyz;vec3 Normal_World_Q60;Normal_World_Q60=(world*vec4(normal,0.0)).xyz;vec3 Result_Q18=0.5*normal;vec3 Dir_World_Q67;Object_To_World_Dir_B67(_Active_Face_Up_,Dir_World_Q67);float Product_Q56=_Edge_Width_*Relative_Scale_Q57;vec3 Normal_World_N_Q29=normalize(Normal_World_Q60);vec3 Tangent_World_N_Q28=normalize(Tangent_World_Q30);vec3 Binormal_World_N_Q32=normalize(Binormal_World_Q31);vec3 Position_Q38;float Near_Size_Q38;float Inner_Fade_Q38;float Blob_Enable_Q38;float Fade_Q38;float Pulse_Q38;Choose_Blob_B38(color,Blob_Position_Q41,Blob_Position_Q42,_Blob_Enable_,_Blob_Enable_2_,_Blob_Near_Size_,_Blob_Near_Size_2_,_Blob_Inner_Fade_,_Blob_Inner_Fade_2_,_Blob_Pulse_,_Blob_Pulse_2_,_Blob_Fade_,_Blob_Fade_2_,Position_Q38,Near_Size_Q38,Inner_Fade_Q38,Blob_Enable_Q38,Fade_Q38,Pulse_Q38);vec3 Face_Center_Q33;Face_Center_Q33=(world*vec4(Result_Q18,1.0)).xyz;vec2 Face_Size_Q50=vec2(length(Tangent_World_Q30),length(Binormal_World_Q31));float Show_Selection_Q48;Selection_Vertex_B48(Blob_Position_Q41,Blob_Position_Q42,Face_Center_Q33,Face_Size_Q50,Normal_World_N_Q29,Tangent_World_N_Q28,Binormal_World_N_Q32,_Selection_Fuzz_,_Selected_,_Selected_Distance_,_Selected_Fade_Length_,Active_Face_Dir_Q64,Show_Selection_Q48);vec3 Normalized_Q72=normalize(Dir_World_Q67);float Active_Q34=max(0.0,dot(Active_Face_Dir_Q64,Normal_World_N_Q29));float Width_Q54;Proximity_Visibility_B54(Show_Selection_Q48,Blob_Position_Q41,Blob_Position_Q42,Product_Q56,_Proximity_Far_Distance_,_Proximity_Near_Radius_,Active_Face_Center_Q49,Active_Face_Dir_Q64,Width_Q54);vec3 Wire_Vx_Pos_Q51;vec2 UV_Q51;vec2 Widths_Q51;Wireframe_Vertex_B51(position,normal,tangent,(cross(normal,tangent)),Width_Q54,Face_Size_Q50,Wire_Vx_Pos_Q51,UV_Q51,Widths_Q51);vec3 Vec3_Q27=vec3(Widths_Q51.x,Widths_Q51.y,color.r);vec3 Pos_World_Q13;Object_To_World_Pos_B13(Wire_Vx_Pos_Q51,Pos_World_Q13);vec3 Incident_Q36=normalize(Pos_World_Q13-cameraPosition);vec3 Out_Position_Q47;vec2 Out_UV_Q47;vec3 Blob_Info_Q47;Blob_Vertex_B47(Pos_World_Q13,Normal_World_N_Q29,Tangent_World_N_Q28,Binormal_World_N_Q32,Position_Q38,_Blob_Intensity_,Near_Size_Q38,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,color,uv,Face_Center_Q33,Face_Size_Q50,UV_Q51,_Blob_Fade_Length_,_Selection_Fade_,_Selection_Fade_Size_,Inner_Fade_Q38,Active_Face_Center_Q49,Pulse_Q38,Fade_Q38,Blob_Enable_Q38,Out_Position_Q47,Out_UV_Q47,Blob_Info_Q47);vec4 Extra1_Q66;float Distance_To_Face_Q66;float Intensity_Q66;Proximity_Vertex_B66(Blob_Position_Q41,Blob_Position_Q42,Active_Face_Center_Q49,Active_Face_Dir_Q64,Pos_World_Q13,_Proximity_Far_Distance_,Relative_Scale_Q57,_Proximity_Anisotropy_,Normalized_Q72,Extra1_Q66,Distance_To_Face_Q66,Intensity_Q66);vec4 Holo_Edges_Q44;Holo_Edge_Vertex_B44(Incident_Q36,Normal_World_N_Q29,uv,Tangent_World_Q30,Binormal_World_Q31,_Smooth_Active_Face_,Active_Q34,Holo_Edges_Q44);vec3 Vec3_Q19=vec3(Show_Selection_Q48,Distance_To_Face_Q66,Intensity_Q66);vec3 Position=Out_Position_Q47;vec2 UV=Out_UV_Q47;vec3 Tangent=Blob_Info_Q47;vec3 Binormal=Vec3_Q19;vec3 Normal=Vec3_Q27;vec4 Extra1=Extra1_Q66;vec4 Color=Holo_Edges_Q44;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;}";class VN extends xl{constructor(){super(),this.RELATIVE_WIDTH=!0,this.ENABLE_FADE=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class UN extends ml{constructor(e,t){super(e,t),this.edgeWidth=.04,this.edgeColor=new Ae(.592157,.592157,.592157,1),this.proximityMaxIntensity=.45,this.proximityFarDistance=.16,this.proximityNearRadius=1.5,this.proximityAnisotropy=1,this.selectionFuzz=.5,this.selected=0,this.selectionFade=0,this.selectionFadeSize=.3,this.selectedDistance=.08,this.selectedFadeLength=.08,this.blobIntensity=.5,this.blobFarSize=.05,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.08,this.leftBlobEnable=!0,this.leftBlobNearSize=.025,this.leftBlobPulse=0,this.leftBlobFade=1,this.leftBlobInnerFade=.01,this.rightBlobEnable=!0,this.rightBlobNearSize=.025,this.rightBlobPulse=0,this.rightBlobFade=1,this.rightBlobInnerFade=.01,this.activeFaceDir=new _e(0,0,-1),this.activeFaceUp=new _e(0,1,0),this.enableFade=!0,this.fadeWidth=1.5,this.smoothActiveFace=!0,this.showFrame=!1,this.useBlobTexture=!0,this.globalLeftIndexTipPosition=_e.Zero(),this.globalRightIndexTipPosition=_e.Zero(),this.alphaMode=N_.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1,this._blobTexture=new Pa(UN.BLOB_TEXTURE_URL,this.getScene(),!0,!1,Pa.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!0}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new VN);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!0,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="fluentButton",a=s.toString(),l=["world","viewProjection","cameraPosition","_Edge_Width_","_Edge_Color_","_Relative_Width_","_Proximity_Max_Intensity_","_Proximity_Far_Distance_","_Proximity_Near_Radius_","_Proximity_Anisotropy_","_Selection_Fuzz_","_Selected_","_Selection_Fade_","_Selection_Fade_Size_","_Selected_Distance_","_Selected_Fade_Length_","_Blob_Enable_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Inner_Fade_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Enable_2_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Inner_Fade_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Active_Face_Dir_","_Active_Face_Up_","_Enable_Fade_","_Fade_Width_","_Smooth_Active_Face_","_Show_Frame_","_Use_Blob_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Blob_Texture_"],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Edge_Width_",this.edgeWidth),this._activeEffect.setColor4("_Edge_Color_",new Ee(this.edgeColor.r,this.edgeColor.g,this.edgeColor.b),this.edgeColor.a),this._activeEffect.setFloat("_Proximity_Max_Intensity_",this.proximityMaxIntensity),this._activeEffect.setFloat("_Proximity_Far_Distance_",this.proximityFarDistance),this._activeEffect.setFloat("_Proximity_Near_Radius_",this.proximityNearRadius),this._activeEffect.setFloat("_Proximity_Anisotropy_",this.proximityAnisotropy),this._activeEffect.setFloat("_Selection_Fuzz_",this.selectionFuzz),this._activeEffect.setFloat("_Selected_",this.selected),this._activeEffect.setFloat("_Selection_Fade_",this.selectionFade),this._activeEffect.setFloat("_Selection_Fade_Size_",this.selectionFadeSize),this._activeEffect.setFloat("_Selected_Distance_",this.selectedDistance),this._activeEffect.setFloat("_Selected_Fade_Length_",this.selectedFadeLength),this._activeEffect.setFloat("_Blob_Enable_",this.leftBlobEnable?1:0),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.leftBlobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Inner_Fade_",this.leftBlobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_",this.leftBlobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.leftBlobFade),this._activeEffect.setFloat("_Blob_Enable_2_",this.rightBlobEnable?1:0),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.rightBlobNearSize),this._activeEffect.setFloat("_Blob_Inner_Fade_2_",this.rightBlobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_2_",this.rightBlobPulse),this._activeEffect.setFloat("_Blob_Fade_2_",this.rightBlobFade),this._activeEffect.setVector3("_Active_Face_Dir_",this.activeFaceDir),this._activeEffect.setVector3("_Active_Face_Up_",this.activeFaceUp),this._activeEffect.setFloat("_Fade_Width_",this.fadeWidth),this._activeEffect.setFloat("_Smooth_Active_Face_",this.smoothActiveFace?1:0),this._activeEffect.setFloat("_Show_Frame_",this.showFrame?1:0),this._activeEffect.setFloat("_Use_Blob_Texture_",this.useBlobTexture?1:0),this._activeEffect.setFloat("Use_Global_Left_Index",1),this._activeEffect.setFloat("Use_Global_Right_Index",1),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",new pe(this.globalLeftIndexTipPosition.x,this.globalLeftIndexTipPosition.y,this.globalLeftIndexTipPosition.z,1)),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",new pe(this.globalRightIndexTipPosition.x,this.globalRightIndexTipPosition.y,this.globalRightIndexTipPosition.z,1)),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new UN(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FluentButtonMaterial",e}getClassName(){return"FluentButtonMaterial"}static Parse(e,t,i){return St.Parse((()=>new UN(e.name,t)),e,t,i)}}UN.BLOB_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/mrtk-fluent-button-blob.png",Ze([rt()],UN.prototype,"edgeWidth",void 0),Ze([dt()],UN.prototype,"edgeColor",void 0),Ze([rt()],UN.prototype,"proximityMaxIntensity",void 0),Ze([rt()],UN.prototype,"proximityFarDistance",void 0),Ze([rt()],UN.prototype,"proximityNearRadius",void 0),Ze([rt()],UN.prototype,"proximityAnisotropy",void 0),Ze([rt()],UN.prototype,"selectionFuzz",void 0),Ze([rt()],UN.prototype,"selected",void 0),Ze([rt()],UN.prototype,"selectionFade",void 0),Ze([rt()],UN.prototype,"selectionFadeSize",void 0),Ze([rt()],UN.prototype,"selectedDistance",void 0),Ze([rt()],UN.prototype,"selectedFadeLength",void 0),Ze([rt()],UN.prototype,"blobIntensity",void 0),Ze([rt()],UN.prototype,"blobFarSize",void 0),Ze([rt()],UN.prototype,"blobNearDistance",void 0),Ze([rt()],UN.prototype,"blobFarDistance",void 0),Ze([rt()],UN.prototype,"blobFadeLength",void 0),Ze([rt()],UN.prototype,"leftBlobEnable",void 0),Ze([rt()],UN.prototype,"leftBlobNearSize",void 0),Ze([rt()],UN.prototype,"leftBlobPulse",void 0),Ze([rt()],UN.prototype,"leftBlobFade",void 0),Ze([rt()],UN.prototype,"leftBlobInnerFade",void 0),Ze([rt()],UN.prototype,"rightBlobEnable",void 0),Ze([rt()],UN.prototype,"rightBlobNearSize",void 0),Ze([rt()],UN.prototype,"rightBlobPulse",void 0),Ze([rt()],UN.prototype,"rightBlobFade",void 0),Ze([rt()],UN.prototype,"rightBlobInnerFade",void 0),Ze([ht()],UN.prototype,"activeFaceDir",void 0),Ze([ht()],UN.prototype,"activeFaceUp",void 0),Ze([rt()],UN.prototype,"enableFade",void 0),Ze([rt()],UN.prototype,"fadeWidth",void 0),Ze([rt()],UN.prototype,"smoothActiveFace",void 0),Ze([rt()],UN.prototype,"showFrame",void 0),Ze([rt()],UN.prototype,"useBlobTexture",void 0),Ze([ht()],UN.prototype,"globalLeftIndexTipPosition",void 0),Ze([ht()],UN.prototype,"globalRightIndexTipPosition",void 0),z("BABYLON.GUI.FluentButtonMaterial",UN);class GN extends PN{constructor(e,t){super(e),this._isNearPressed=!1,this._interactionSurfaceHeight=0,this._isToggleButton=!1,this._toggleState=!1,this._toggleButtonCallback=()=>{this._onToggle(!this._toggleState)},this.onToggleObservable=new K,this.collidableFrontDirection=_e.Zero(),t&&(this.collisionMesh=t)}get isActiveNearInteraction(){return this._isNearPressed}set collidableFrontDirection(e){if(this._collidableFrontDirection=e.normalize(),this._collisionMesh){const e=ve.Matrix[0];e.copyFrom(this._collisionMesh.getWorldMatrix()),e.invert(),_e.TransformNormalToRef(this._collidableFrontDirection,e,this._collidableFrontDirection),this._collidableFrontDirection.normalize()}}get collidableFrontDirection(){if(this._collisionMesh){const e=ve.Vector3[0];return _e.TransformNormalToRef(this._collidableFrontDirection,this._collisionMesh.getWorldMatrix(),e),e.normalize()}return this._collidableFrontDirection}set collisionMesh(e){this._collisionMesh&&(this._collisionMesh.isNearPickable=!1,this._collisionMesh.reservedDataStore?.GUI3D&&(this._collisionMesh.reservedDataStore.GUI3D={}),this._collisionMesh.getChildMeshes().forEach((e=>{e.isNearPickable=!1,e.reservedDataStore?.GUI3D&&(e.reservedDataStore.GUI3D={})}))),this._collisionMesh=e,this._injectGUI3DReservedDataStore(this._collisionMesh).control=this,this._collisionMesh.isNearPickable=!0,this._collisionMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this,e.isNearPickable=!0})),this.collidableFrontDirection=e.forward}set isToggleButton(e){e!==this._isToggleButton&&(this._isToggleButton=e,e?this.onPointerUpObservable.add(this._toggleButtonCallback):(this.onPointerUpObservable.removeCallback(this._toggleButtonCallback),this._toggleState&&this._onToggle(!1)))}get isToggleButton(){return this._isToggleButton}set isToggled(e){this._isToggleButton&&this._toggleState!==e&&this._onToggle(e)}get isToggled(){return this._toggleState}_onToggle(e){this._toggleState=e,this.onToggleObservable.notifyObservers(e)}_isInteractionInFrontOfButton(e){return this._getInteractionHeight(e,this._collisionMesh.getAbsolutePosition())>0}getPressDepth(e){if(!this._isNearPressed)return 0;const t=this._getInteractionHeight(e,this._collisionMesh.getAbsolutePosition());return this._interactionSurfaceHeight-t}_getInteractionHeight(e,t){const i=this.collidableFrontDirection;if(0===i.length())return _e.Distance(e,t);const s=_e.Dot(t,i);return _e.Dot(e,i)-s}_generatePointerEventType(e,t,i){if(e===lr.POINTERDOWN||e===lr.POINTERMOVE){if(!this._isInteractionInFrontOfButton(t))return lr.POINTERMOVE;this._isNearPressed=!0,this._interactionSurfaceHeight=this._getInteractionHeight(t,this._collisionMesh.getAbsolutePosition())}if(e===lr.POINTERUP){if(0==i)return lr.POINTERMOVE;this._isNearPressed=!1}return e}_getTypeName(){return"TouchButton3D"}_createNode(e){return super._createNode(e)}dispose(){super.dispose(),this.onPointerUpObservable.removeCallback(this._toggleButtonCallback),this.onToggleObservable.clear(),this._collisionMesh&&this._collisionMesh.dispose()}}class zN extends GN{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}get mesh(){return this._backPlate}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=Wa("",{size:1},this._backPlate._scene);const t=Wa("",{size:1,sideOrientation:ha.DOUBLESIDE},this._backPlate._scene),i=new cu("",this._backPlate._scene);i.diffuseColor=Ee.FromHexString("#212121"),t.material=i,t.isPickable=!1,this._tooltipMesh.addChild(t),t.position=_e.Forward(e).scale(.05),this._tooltipMesh.scaling.y=1/3,this._tooltipMesh.position=_e.Up().scale(.7).add(_e.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._backPlate,this._tooltipTexture=xN.CreateForMesh(this._tooltipMesh),this._tooltipTextBlock=new Fw,this._tooltipTextBlock.scaleY=3,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=130,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new Va,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?this._tooltipTextBlock.text:null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}set isBackplateVisible(e){this.mesh&&this._backMaterial&&(e&&!this._isBackplateVisible?this._backPlate.visibility=1:!e&&this._isBackplateVisible&&(this._backPlate.visibility=0)),this._isBackplateVisible=e}constructor(e,t=!0){super(e),this._shareMaterials=!0,this._isBackplateVisible=!0,this._frontPlateDepth=.5,this._backPlateDepth=.04,this._backplateColor=new Ee(.08,.15,.55),this._backplateToggledColor=new Ee(.25,.4,.95),this._shareMaterials=t,this.pointerEnterAnimation=()=>{this._frontMaterial.leftBlobEnable=!0,this._frontMaterial.rightBlobEnable=!0},this.pointerOutAnimation=()=>{this._frontMaterial.leftBlobEnable=!1,this._frontMaterial.rightBlobEnable=!1},this.pointerDownAnimation=()=>{this._frontPlate&&!this.isActiveNearInteraction&&(this._frontPlate.scaling.z=.2*this._frontPlateDepth,this._frontPlate.position=_e.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-.2*this._frontPlateDepth)/2),this._textPlate.position=_e.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+.2*this._frontPlateDepth)/2))},this.pointerUpAnimation=()=>{this._frontPlate&&(this._frontPlate.scaling.z=this._frontPlateDepth,this._frontPlate.position=_e.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-this._frontPlateDepth)/2),this._textPlate.position=_e.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+this._frontPlateDepth)/2))},this.onPointerMoveObservable.add((e=>{if(this._frontPlate&&this.isActiveNearInteraction){const t=_e.Zero();if(this._backPlate.getWorldMatrix().decompose(t,void 0,void 0)){let i=this._getInteractionHeight(e,this._backPlate.getAbsolutePosition())/t.z;i=be.Clamp(i-this._backPlateDepth/2,.2*this._frontPlateDepth,this._frontPlateDepth),this._frontPlate.scaling.z=i,this._frontPlate.position=_e.Forward(this._frontPlate._scene.useRightHandedSystem).scale((this._frontPlateDepth-i)/2),this._textPlate.position=_e.Forward(this._textPlate._scene.useRightHandedSystem).scale(-(this._backPlateDepth+i)/2)}}})),this._pointerHoverObserver=this.onPointerMoveObservable.add((e=>{this._frontMaterial.globalLeftIndexTipPosition=e}))}_getTypeName(){return"TouchHolographicButton"}_rebuildContent(){this._disposeFacadeTexture();const e=new kw;if(e.isVertical=!0,Ut()&&document.createElement&&this._imageUrl){const t=new Lw;t.source=this._imageUrl,t.paddingTop="40px",t.height="180px",t.width="100px",t.paddingBottom="40px",e.addControl(t)}if(this._text){const t=new Fw;t.text=this._text,t.color="white",t.height="30px",t.fontSize=24,e.addControl(t)}this.content=e}_createNode(e){this.name=this.name??"TouchHolographicButton";const t=cd(`${this.name}_collisionMesh`,{width:1,height:1,depth:this._frontPlateDepth},e);t.isPickable=!0,t.isNearPickable=!0,t.visibility=0,t.position=_e.Forward(e.useRightHandedSystem).scale(-this._frontPlateDepth/2),fl.ImportMeshAsync(void 0,zN.MODEL_BASE_URL,zN.MODEL_FILENAME,e).then((i=>{const s=cd("${this.name}_alphaMesh",{width:1,height:1,depth:1},e);s.isPickable=!1,s.material=new cu("${this.name}_alphaMesh_material",e),s.material.alpha=.15;const r=i.meshes[1];r.name=`${this.name}_frontPlate`,r.isPickable=!1,r.scaling.z=this._frontPlateDepth,s.parent=r,r.parent=t,this._frontMaterial&&(r.material=this._frontMaterial),this._frontPlate=r})),this._backPlate=cd(`${this.name}_backPlate`,{width:1,height:1,depth:this._backPlateDepth},e),this._backPlate.position=_e.Forward(e.useRightHandedSystem).scale(this._backPlateDepth/2),this._backPlate.isPickable=!1,this._textPlate=super._createNode(e),this._textPlate.name=`${this.name}_textPlate`,this._textPlate.isPickable=!1,this._textPlate.position=_e.Forward(e.useRightHandedSystem).scale(-this._frontPlateDepth/2),this._backPlate.addChild(t),this._backPlate.addChild(this._textPlate);const i=new lo("{this.name}_root",e);return this._backPlate.setParent(i),this.collisionMesh=t,this.collidableFrontDirection=this._backPlate.forward.negate(),i}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e,this._plateMaterial.diffuseColor=new Ee(.4,.4,.4)}_createBackMaterial(e){this._backMaterial=new DN(this.name+"backPlateMaterial",e.getScene()),this._backMaterial.albedoColor=this._backplateColor,this._backMaterial.renderBorders=!0,this._backMaterial.renderHoverLight=!1}_createFrontMaterial(e){this._frontMaterial=new UN(this.name+"Front Material",e.getScene())}_createPlateMaterial(e){this._plateMaterial=new cu(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=Ee.Black()}_onToggle(e){this._backMaterial&&(this._backMaterial.albedoColor=e?this._backplateToggledColor:this._backplateColor),super._onToggle(e)}_affectMaterial(e){this._shareMaterials?(this._host._touchSharedMaterials.backFluentMaterial?this._backMaterial=this._host._touchSharedMaterials.backFluentMaterial:(this._createBackMaterial(e),this._host._touchSharedMaterials.backFluentMaterial=this._backMaterial),this._host._touchSharedMaterials.frontFluentMaterial?this._frontMaterial=this._host._touchSharedMaterials.frontFluentMaterial:(this._createFrontMaterial(e),this._host._touchSharedMaterials.frontFluentMaterial=this._frontMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._textPlate.material=this._plateMaterial,this._isBackplateVisible||(this._backPlate.visibility=0),this._frontPlate&&(this._frontPlate.material=this._frontMaterial),this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.onPointerMoveObservable.remove(this._pointerHoverObserver),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}zN.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",zN.MODEL_FILENAME="mrtk-fluent-button.glb";class WN{constructor(){this.followBehaviorEnabled=!1,this.sixDofDragBehaviorEnabled=!0,this.surfaceMagnetismBehaviorEnabled=!0,this._followBehavior=new $a,this._sixDofDragBehavior=new ja,this._surfaceMagnetismBehavior=new Ka}get name(){return"Default"}get followBehavior(){return this._followBehavior}get sixDofDragBehavior(){return this._sixDofDragBehavior}get surfaceMagnetismBehavior(){return this._surfaceMagnetismBehavior}init(){}attach(e,t,i){this._scene=e.getScene(),this.attachedNode=e,this._addObservables(),this._followBehavior.attach(e),this._sixDofDragBehavior.attach(e),this._sixDofDragBehavior.draggableMeshes=t||null,this._sixDofDragBehavior.faceCameraOnDragStart=!0,this._surfaceMagnetismBehavior.attach(e,this._scene),i&&(this._surfaceMagnetismBehavior.meshes=i),this._surfaceMagnetismBehavior.enabled=!1}detach(){this.attachedNode=null,this._removeObservables(),this._followBehavior.detach(),this._sixDofDragBehavior.detach(),this._surfaceMagnetismBehavior.detach()}_addObservables(){this._onBeforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{this._followBehavior._enabled=!this._sixDofDragBehavior.isMoving&&this.followBehaviorEnabled})),this._onDragObserver=this._sixDofDragBehavior.onDragObservable.add((e=>{this._sixDofDragBehavior.disableMovement=this._surfaceMagnetismBehavior.findAndUpdateTarget(e.pickInfo)}))}_removeObservables(){this._scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._sixDofDragBehavior.onDragObservable.remove(this._onDragObserver)}}Bi.ShadersStore.handleVertexShader="precision highp float;attribute vec3 position;uniform vec3 positionOffset;uniform mat4 worldViewProjection;uniform float scale;void main(void) {vec4 vPos=vec4((vec3(position)+positionOffset)*scale,1.0);gl_Position=worldViewProjection*vPos;}";Bi.ShadersStore.handlePixelShader="uniform vec3 color;void main(void) {gl_FragColor=vec4(color,1.0);}";class HN extends Nd{get hover(){return this._hover}set hover(e){this._hover=e,this._updateInterpolationTarget()}get drag(){return this._drag}set drag(e){this._drag=e,this._updateInterpolationTarget()}constructor(e,t){super(e,t,"handle",{attributes:["position"],uniforms:["worldViewProjection","color","scale","positionOffset"],needAlphaBlending:!1,needAlphaTesting:!1}),this._hover=!1,this._drag=!1,this._color=new Ee,this._scale=1,this._lastTick=-1,this.animationLength=100,this.hoverColor=new Ee(0,.467,.84),this.baseColor=new Ee(1,1,1),this.hoverScale=.75,this.baseScale=.35,this.dragScale=.55,this._positionOffset=_e.Zero(),this._updateInterpolationTarget(),this._lastTick=Date.now(),this._onBeforeRender=this.getScene().onBeforeRenderObservable.add((()=>{const e=Date.now(),t=e-this._lastTick,i=this._targetScale-this._scale,s=Pe.Color3[0].copyFrom(this._targetColor).subtractToRef(this._color,Pe.Color3[0]);this._scale=this._scale+i*t/this.animationLength,s.scaleToRef(t/this.animationLength,s),this._color.addToRef(s,this._color),this.setColor3("color",this._color),this.setFloat("scale",this._scale),this.setVector3("positionOffset",this._positionOffset),this._lastTick=e}))}_updateInterpolationTarget(){this.drag?(this._targetColor=this.hoverColor,this._targetScale=this.dragScale):this.hover?(this._targetColor=this.hoverColor,this._targetScale=this.hoverScale):(this._targetColor=this.baseColor,this._targetScale=this.baseScale)}dispose(){super.dispose(),this.getScene().onBeforeRenderObservable.remove(this._onBeforeRender)}}var XN;!function(e){e[e.IDLE=0]="IDLE",e[e.HOVER=1]="HOVER",e[e.DRAG=2]="DRAG"}(XN||(XN={}));class YN{get state(){return this._state}get gizmo(){return this._gizmo}set hover(e){e?this._state|=XN.HOVER:this._state&=~XN.HOVER,this._updateMaterial()}set drag(e){e?this._state|=XN.DRAG:this._state&=~XN.DRAG,this._updateMaterial()}constructor(e,t){this._state=XN.IDLE,this._materials=[],this._scene=t,this._gizmo=e,this.node=this.createNode(),this.node.reservedDataStore={handle:this}}_createMaterial(e){const t=new HN("handle",this._scene);return e&&(t._positionOffset=e),t}_updateMaterial(){const e=this._state;for(const e of this._materials)e.hover=!1,e.drag=!1;if(e&XN.DRAG)for(const e of this._materials)e.drag=!0;else if(e&XN.HOVER)for(const e of this._materials)e.hover=!0}setDragBehavior(e,t,i){const s=new Qa;this._dragBehavior=s,this._dragStartObserver=s.onDragStartObservable.add(e),this._draggingObserver=s.onDragObservable.add(t),this._dragEndObserver=s.onDragEndObservable.add(i),this._dragBehavior.attach(this.node)}dispose(){this._dragBehavior.onDragStartObservable.remove(this._dragStartObserver),this._dragBehavior.onDragObservable.remove(this._draggingObserver),this._dragBehavior.onDragEndObservable.remove(this._dragEndObserver),this._dragBehavior.detach();for(const e of this._materials)e.dispose();this.node.dispose()}}class QN extends YN{createNode(){const e=cd("sideVert",{width:1,height:10,depth:.1},this._scene),t=new lo("side",this._scene);e.parent=t;const i=this._createMaterial();return e.material=i,e.isNearGrabbable=!0,this._materials.push(i),t}}class jN extends YN{createNode(){const e=cd("angleHor",{width:3,height:1,depth:.1},this._scene),t=cd("angleVert",{width:1,height:3,depth:.1},this._scene),i=new lo("angle",this._scene);return e.parent=i,t.parent=i,e.material=this._createMaterial(new _e(1,0,0)),t.material=this._createMaterial(new _e(0,1,0)),t.isNearGrabbable=!0,e.isNearGrabbable=!0,this._materials.push(e.material),this._materials.push(t.material),i}}class KN extends sd{set attachedSlate(e){e?(this.attachedMesh=e.mesh,this.updateBoundingBox(),this._pickedPointObserver=e._host.onPickingObservable.add((e=>{if(!this._handleHovered||e&&e.parent===this._handleHovered.node||(this._handleHovered.hover=!1,this._handleHovered=null),e&&e.parent&&e.parent.reservedDataStore&&e.parent.reservedDataStore.handle){const t=e.parent.reservedDataStore.handle;t.gizmo===this&&(this._handleHovered=t,this._handleHovered.hover=!0)}}))):this._attachedSlate&&this._attachedSlate._host.onPickingObservable.remove(this._pickedPointObserver),this._attachedSlate=e}get attachedSlate(){return this._attachedSlate}constructor(e){super(e),this._boundingDimensions=new _e(0,0,0),this._renderObserver=null,this._tmpQuaternion=new fe,this._tmpVector=new _e(0,0,0),this._corners=[],this._sides=[],this._boundingBoxGizmo={min:new _e,max:new _e},this._margin=.35,this._handleSize=.075,this._attachedSlate=null,this._existingSlateScale=new _e,this.fixedScreenSize=!1,this.fixedScreenSizeDistanceFactor=10,this._createNode(),this.updateScale=!1,this._renderObserver=this.gizmoLayer.originalScene.onBeforeRenderObservable.add((()=>{this.attachedMesh&&!this._existingSlateScale.equals(this.attachedMesh.scaling)&&this.updateBoundingBox()}))}_createNode(){this._handlesParent=new lo("handlesParent",this.gizmoLayer.utilityLayerScene),this._handlesParent.rotationQuaternion=fe.Identity();const e=[{dimensions:new _e(-1,-1,0),origin:new _e(1,0,0)},{dimensions:new _e(1,-1,0),origin:new _e(0,0,0)},{dimensions:new _e(1,1,0),origin:new _e(0,1,0)},{dimensions:new _e(-1,1,0),origin:new _e(1,1,0)}];for(let t=0;t<4;t++){const i=new jN(this,this.gizmoLayer.utilityLayerScene);this._corners.push(i),i.node.rotation.z=Math.PI/2*t,i.node.parent=this._handlesParent,this._assignDragBehaviorCorners(i,((e,t,i,s)=>this._moveHandle(e,t,i,s,!0)),e[t])}for(let e=0;e<4;e++){const t=new QN(this,this.gizmoLayer.utilityLayerScene);this._sides.push(t),t.node.rotation.z=Math.PI/2*e,t.node.parent=this._handlesParent,this._assignDragBehaviorSides(t,e%2==0?new _e(0,1,0):new _e(1,0,0))}this._handlesParent.parent=this._rootMesh}_keepAspectRatio(e,t,i=!1){const s=ve.Vector3[0];s.copyFromFloats(t,1,0).normalize(),i&&(s.y*=-1);const r=_e.Dot(e,s);e.copyFrom(s).scaleInPlace(r)}_clampDimensions(e,t,i,s=!1){const r=ve.Vector3[0];r.copyFrom(e).multiplyInPlace(i);const n=ve.Vector3[1];if(n.copyFromFloats(Math.max(this._attachedSlate.minDimensions.x,r.x+t.x),Math.max(this._attachedSlate.minDimensions.y,r.y+t.y),0),s){const e=t.x/t.y;n.x=Math.max(n.x,n.y*e),n.y=Math.max(n.y,n.x/e)}r.copyFrom(n).subtractInPlace(t),e.x=Math.sign(e.x)*Math.abs(r.x),e.y=Math.sign(e.y)*Math.abs(r.y)}_moveHandle(e,t,i,s,r){if(!this._attachedSlate)return;if(r){const e=t.x/t.y;this._keepAspectRatio(i,e,s.dimensions.x*s.dimensions.y<0)}this._clampDimensions(i,t,s.dimensions,r);const n=ve.Vector3[0],o=ve.Vector3[1];n.copyFrom(i).multiplyInPlace(s.origin),o.copyFrom(i).multiplyInPlace(s.dimensions),this._attachedSlate.origin.copyFrom(e).addInPlace(n),this._attachedSlate.dimensions.set(t.x+o.x,t.y+o.y)}_assignDragBehaviorCorners(e,t,i){const s=new _e,r=new _e,n=new _e,o=new me,a=new _e;e.setDragBehavior((e=>{this.attachedSlate&&this.attachedMesh&&(s.set(this.attachedSlate.dimensions.x,this.attachedSlate.dimensions.y,J),r.copyFrom(this.attachedSlate.origin),n.copyFrom(e.position),o.copyFrom(this.attachedMesh.computeWorldMatrix(!0)),o.invert(),this.attachedSlate._followButton.isToggled=!1,_e.TransformNormalToRef(_e.Forward(),this.attachedMesh.getWorldMatrix(),a),a.normalize(),this._handleHovered&&(this._handleDragged=this._handleHovered,this._handleDragged.drag=!0))}),(e=>{this.attachedSlate&&this.attachedMesh&&(((e,t,i,s)=>{e.subtractToRef(i,ve.Vector3[0]);const r=_e.Dot(ve.Vector3[0],t);ve.Vector3[1].copyFrom(t).scaleInPlace(r),ve.Vector3[0].subtractInPlace(ve.Vector3[1]),ve.Vector3[0].addToRef(i,s)})(e.position,a,n,this._tmpVector),this._tmpVector.subtractInPlace(n),_e.TransformNormalToRef(this._tmpVector,o,this._tmpVector),t(r,s,this._tmpVector,i),this.attachedSlate._positionElements(),this.updateBoundingBox())}),(()=>{this.attachedSlate&&this.attachedNode&&(this.attachedSlate._updatePivot(),this._handleDragged&&(this._handleDragged.drag=!1,this._handleDragged=null))}))}_assignDragBehaviorSides(e,t){const i=new fe,s=new _e,r=new _e,n=new _e,o=new _e;e.setDragBehavior((e=>{this.attachedSlate&&this.attachedMesh&&(i.copyFrom(this.attachedMesh.rotationQuaternion),s.copyFrom(e.position),n.copyFrom(this.attachedMesh.getAbsolutePivotPoint()),r.copyFrom(s).subtractInPlace(n).normalize(),this.attachedSlate._followButton.isToggled=!1,_e.TransformNormalToRef(t,this.attachedMesh.getWorldMatrix(),o),o.normalize(),this._handleHovered&&(this._handleDragged=this._handleHovered,this._handleDragged.drag=!0))}),(e=>{if(this.attachedSlate&&this.attachedMesh){this._tmpVector.copyFrom(e.position),this._tmpVector.subtractInPlace(n),this._tmpVector.normalize();const s=-_e.GetAngleBetweenVectorsOnPlane(this._tmpVector,r,o);fe.RotationAxisToRef(t,s,this._tmpQuaternion),i.multiplyToRef(this._tmpQuaternion,this.attachedMesh.rotationQuaternion)}}),(()=>{this.attachedSlate&&this.attachedNode&&(this.attachedSlate._updatePivot(),this._handleDragged&&(this._handleDragged.drag=!1,this._handleDragged=null))}))}_attachedNodeChanged(e){e&&this.updateBoundingBox()}updateBoundingBox(){if(this.attachedMesh){Ga._RemoveAndStorePivotPoint(this.attachedMesh);const e=this.attachedMesh.parent;this.attachedMesh.setParent(null),this._update(),this.attachedMesh.rotationQuaternion||(this.attachedMesh.rotationQuaternion=fe.RotationYawPitchRoll(this.attachedMesh.rotation.y,this.attachedMesh.rotation.x,this.attachedMesh.rotation.z)),this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion),this._tmpVector.copyFrom(this.attachedMesh.position),this.attachedMesh.rotationQuaternion.set(0,0,0,1),this.attachedMesh.position.set(0,0,0);const t=this.attachedMesh.getHierarchyBoundingVectors();t.max.subtractToRef(t.min,this._boundingDimensions),this._boundingBoxGizmo.min=t.min,this._boundingBoxGizmo.max=t.max,this._updateHandlesPosition(),this._updateHandlesScaling(),this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion),this.attachedMesh.position.copyFrom(this._tmpVector),Ga._RestorePivotPoint(this.attachedMesh),this.attachedMesh.setParent(e),this.attachedMesh.computeWorldMatrix(!0),this._existingSlateScale.copyFrom(this.attachedMesh.scaling)}}_updateHandlesPosition(){const e=this._boundingBoxGizmo.min.clone(),t=this._boundingBoxGizmo.max.clone(),i=this._corners[0].node.scaling.length();e.x-=this._margin*i,e.y-=this._margin*i,t.x+=this._margin*i,t.y+=this._margin*i;const s=e.add(t).scaleInPlace(.5);this._corners[0].node.position.copyFromFloats(e.x,e.y,0),this._corners[1].node.position.copyFromFloats(t.x,e.y,0),this._corners[2].node.position.copyFromFloats(t.x,t.y,0),this._corners[3].node.position.copyFromFloats(e.x,t.y,0),this._sides[0].node.position.copyFromFloats(e.x,s.y,0),this._sides[1].node.position.copyFromFloats(s.x,e.y,0),this._sides[2].node.position.copyFromFloats(t.x,s.y,0),this._sides[3].node.position.copyFromFloats(s.x,t.y,0)}_updateHandlesScaling(){if(this._attachedSlate&&this._attachedSlate.mesh){const e=this._attachedSlate.mesh.scaling.x*this._attachedSlate.dimensions.x,t=this._attachedSlate.mesh.scaling.y*this._attachedSlate.dimensions.y,i=Math.min(e,t)*this._handleSize;for(let e=0;ei?this.minDimensions.x/e.x:this.minDimensions.y/e.y}this._dimensions.copyFrom(e).scaleInPlace(t),this._updatePivot(),this._positionElements()}get titleBarHeight(){return this._titleBarHeight}set titleBarHeight(e){this._titleBarHeight=e}set renderingGroupId(e){this._titleBar.renderingGroupId=e,this._titleBarTitle.renderingGroupId=e,this._contentPlate.renderingGroupId=e,this._backPlate.renderingGroupId=e}get renderingGroupId(){return this._titleBar.renderingGroupId}set title(e){this._titleText=e,this._titleTextComponent&&(this._titleTextComponent.text=e)}get title(){return this._titleText}constructor(e){super(e),this.titleBarMargin=.005,this.origin=new _e(0,0,0),this._dimensions=new de(21.875,12.5),this._titleBarHeight=.625,this._titleText="",this._contentScaleRatio=1,this.minDimensions=new de(15.625,6.25),this.defaultDimensions=this._dimensions.clone(),this._followButton=new zN("followButton"+this.name),this._followButton.isToggleButton=!0,this._closeButton=new zN("closeButton"+this.name),this._contentViewport=new Pn(0,0,1,1),this._contentDragBehavior=new Xa({dragPlaneNormal:new _e(0,0,-1)})}_applyFacade(e){this._contentMaterial.albedoTexture=e,this._resetContentPositionAndZoom(),this._applyContentViewport(),e.attachToMesh(this._contentPlate,!0)}_addControl(e){e._host=this._host,this._host.utilityLayer&&e._prepareNode(this._host.utilityLayer.utilityLayerScene)}_getTypeName(){return"HolographicSlate"}_positionElements(){const e=this._followButton,t=this._closeButton,i=this._titleBar,s=this._titleBarTitle,r=this._contentPlate,n=this._backPlate;if(e&&t&&i){t.scaling.setAll(this.titleBarHeight),e.scaling.setAll(this.titleBarHeight),t.position.copyFromFloats(this.dimensions.x-this.titleBarHeight/2,-this.titleBarHeight/2,0).addInPlace(this.origin),e.position.copyFromFloats(this.dimensions.x-3*this.titleBarHeight/2,-this.titleBarHeight/2,0).addInPlace(this.origin);const o=this.dimensions.y-this.titleBarHeight-this.titleBarMargin,a=r.getScene().useRightHandedSystem;i.scaling.set(this.dimensions.x,this.titleBarHeight,J),s.scaling.set(this.dimensions.x-2*this.titleBarHeight,this.titleBarHeight,J),r.scaling.copyFromFloats(this.dimensions.x,o,J),n.scaling.copyFromFloats(this.dimensions.x,o,J),i.position.copyFromFloats(this.dimensions.x/2,-this.titleBarHeight/2,0).addInPlace(this.origin),s.position.copyFromFloats(this.dimensions.x/2-this.titleBarHeight,-this.titleBarHeight/2,a?J:-J).addInPlace(this.origin),r.position.copyFromFloats(this.dimensions.x/2,-(this.titleBarHeight+this.titleBarMargin+o/2),0).addInPlace(this.origin),n.position.copyFromFloats(this.dimensions.x/2,-(this.titleBarHeight+this.titleBarMargin+o/2),a?-J:J).addInPlace(this.origin),this._titleTextComponent.host.scaleTo($N._DEFAULT_TEXT_RESOLUTION_Y*s.scaling.x/s.scaling.y,$N._DEFAULT_TEXT_RESOLUTION_Y);const l=this.dimensions.x/o;this._contentViewport.width=this._contentScaleRatio,this._contentViewport.height=this._contentScaleRatio/l,this._applyContentViewport(),this._gizmo&&this._gizmo.updateBoundingBox()}}_applyContentViewport(){if(this._contentPlate?.material&&this._contentPlate.material.albedoTexture){const e=this._contentPlate.material.albedoTexture;e.uScale=this._contentScaleRatio,e.vScale=this._contentScaleRatio/this._contentViewport.width*this._contentViewport.height,e.uOffset=this._contentViewport.x,e.vOffset=this._contentViewport.y}}_resetContentPositionAndZoom(){this._contentViewport.x=0,this._contentViewport.y=1-this._contentViewport.height/this._contentViewport.width,this._contentScaleRatio=1}_updatePivot(){if(!this.mesh)return;const e=new _e(.5*this.dimensions.x,.5*-this.dimensions.y,J);e.addInPlace(this.origin),e.z=0;const t=new _e(0,0,0);_e.TransformCoordinatesToRef(t,this.mesh.computeWorldMatrix(!0),t),this.mesh.setPivotPoint(e);const i=new _e(0,0,0);_e.TransformCoordinatesToRef(i,this.mesh.computeWorldMatrix(!0),i),this.mesh.position.addInPlace(t).subtractInPlace(i)}_createNode(e){const t=new ha("slate_"+this.name,e);this._titleBar=cd("titleBar_"+this.name,{size:1},e),this._titleBarTitle=Wa("titleText_"+this.name,{size:1},e),this._titleBarTitle.parent=t,this._titleBarTitle.isPickable=!1;const i=xN.CreateForMesh(this._titleBarTitle);if(this._titleTextComponent=new Fw("titleText_"+this.name,this._titleText),this._titleTextComponent.textWrapping=Nw.Ellipsis,this._titleTextComponent.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,this._titleTextComponent.color="white",this._titleTextComponent.fontSize=$N._DEFAULT_TEXT_RESOLUTION_Y/2,this._titleTextComponent.paddingLeft=$N._DEFAULT_TEXT_RESOLUTION_Y/4,i.addControl(this._titleTextComponent),e.useRightHandedSystem){const t=new pe(0,0,1,1);this._contentPlate=Wa("contentPlate_"+this.name,{size:1,sideOrientation:Wn.BACKSIDE,frontUVs:t},e),this._backPlate=Wa("backPlate_"+this.name,{size:1,sideOrientation:Wn.FRONTSIDE},e)}else{const t=new pe(0,0,1,1);this._contentPlate=Wa("contentPlate_"+this.name,{size:1,sideOrientation:Wn.FRONTSIDE,frontUVs:t},e),this._backPlate=Wa("backPlate_"+this.name,{size:1,sideOrientation:Wn.BACKSIDE},e)}this._titleBar.parent=t,this._titleBar.isNearGrabbable=!0,this._contentPlate.parent=t,this._backPlate.parent=t,this._attachContentPlateBehavior(),this._addControl(this._followButton),this._addControl(this._closeButton);const s=this._followButton,r=this._closeButton;return s.node.parent=t,r.node.parent=t,this._positionElements(),this._followButton.imageUrl=$N.ASSETS_BASE_URL+$N.FOLLOW_ICON_FILENAME,this._closeButton.imageUrl=$N.ASSETS_BASE_URL+$N.CLOSE_ICON_FILENAME,this._followButton.isBackplateVisible=!1,this._closeButton.isBackplateVisible=!1,this._followButton.onToggleObservable.add((e=>{this._defaultBehavior.followBehaviorEnabled=e,this._defaultBehavior.followBehaviorEnabled&&this._defaultBehavior.followBehavior.recenter()})),this._closeButton.onPointerClickObservable.add((()=>{this.dispose()})),t.rotationQuaternion=fe.Identity(),t.isVisible=!1,t}_attachContentPlateBehavior(){this._contentDragBehavior.attach(this._contentPlate),this._contentDragBehavior.moveAttached=!1,this._contentDragBehavior.useObjectOrientationForDragging=!0,this._contentDragBehavior.updateDragPlane=!1;const e=new _e,t=new _e,i=new _e,s=new _e,r=new de;let n,o;this._contentDragBehavior.onDragStartObservable.add((r=>{this.node&&(n=this._contentViewport.clone(),o=this.node.computeWorldMatrix(!0),e.copyFrom(r.dragPlanePoint),t.set(this.dimensions.x,this.dimensions.y,J),t.y-=this.titleBarHeight+this.titleBarMargin,_e.TransformNormalToRef(t,o,t),i.copyFromFloats(0,1,0),_e.TransformNormalToRef(i,o,i),s.copyFromFloats(1,0,0),_e.TransformNormalToRef(s,o,s),i.normalize(),i.scaleInPlace(1/_e.Dot(i,t)),s.normalize(),s.scaleInPlace(1/_e.Dot(s,t)))}));const a=new _e;this._contentDragBehavior.onDragObservable.add((t=>{a.copyFrom(t.dragPlanePoint),a.subtractInPlace(e),r.copyFromFloats(_e.Dot(a,s),_e.Dot(a,i)),this._contentViewport.x=be.Clamp(n.x-a.x,0,1-this._contentViewport.width*this._contentScaleRatio),this._contentViewport.y=be.Clamp(n.y-a.y,0,1-this._contentViewport.height*this._contentScaleRatio),this._applyContentViewport()}))}_affectMaterial(e){this._titleBarMaterial=new LN(`${this.name} plateMaterial`,e.getScene()),this._contentMaterial=new DN(`${this.name} contentMaterial`,e.getScene()),this._contentMaterial.renderBorders=!0,this._backMaterial=new LN(`${this.name} backPlate`,e.getScene()),this._backMaterial.lineWidth=J,this._backMaterial.radius=.005,this._backMaterial.backFaceCulling=!0,this._titleBar.material=this._titleBarMaterial,this._contentPlate.material=this._contentMaterial,this._backPlate.material=this._backMaterial,this._resetContent(),this._applyContentViewport()}_prepareNode(e){super._prepareNode(e),this._gizmo=new KN(this._host.utilityLayer),this._gizmo.attachedSlate=this,this._defaultBehavior=new WN,this._defaultBehavior.attach(this.node,[this._titleBar]),this._defaultBehavior.sixDofDragBehavior.onDragStartObservable.add((()=>{this._followButton.isToggled=!1})),this._positionChangedObserver=this._defaultBehavior.sixDofDragBehavior.onPositionChangedObservable.add((()=>{this._gizmo.updateBoundingBox()})),this._updatePivot(),this.resetDefaultAspectAndPose(!1)}resetDefaultAspectAndPose(e=!0){if(!this._host||!this._host.utilityLayer||!this.node)return;const t=this._host.utilityLayer.utilityLayerScene,i=t.activeCamera;if(i){const s=i.getWorldMatrix(),r=_e.TransformNormal(_e.Backward(t.useRightHandedSystem),s);this.origin.setAll(0),this._gizmo.updateBoundingBox();const n=this.node.getAbsolutePivotPoint();this.node.position.copyFrom(i.position).subtractInPlace(r).subtractInPlace(n),this.node.rotationQuaternion=fe.FromLookDirectionLH(r,new _e(0,1,0)),e&&(this.dimensions=this.defaultDimensions)}}dispose(){super.dispose(),this._titleBarMaterial.dispose(),this._contentMaterial.dispose(),this._titleBar.dispose(),this._titleBarTitle.dispose(),this._contentPlate.dispose(),this._backPlate.dispose(),this._followButton.dispose(),this._closeButton.dispose(),this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._defaultBehavior.sixDofDragBehavior.onPositionChangedObservable.remove(this._positionChangedObserver),this._defaultBehavior.detach(),this._gizmo.dispose(),this._contentDragBehavior.detach()}}$N.ASSETS_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",$N.CLOSE_ICON_FILENAME="IconClose.png",$N.FOLLOW_ICON_FILENAME="IconFollowMe.png",$N._DEFAULT_TEXT_RESOLUTION_Y=102.4;class qN extends PN{constructor(e,t){super(t),this._currentMesh=e,this.pointerEnterAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1.1)},this.pointerOutAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/1.1)},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_getTypeName(){return"MeshButton3D"}_createNode(e){return this._currentMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this})),this._currentMesh}_affectMaterial(e){}}class ZN extends wN{get defaultBehavior(){return this._defaultBehavior}get isPinned(){return this._isPinned}set isPinned(e){this._pinButton.isToggled===e?(this._isPinned=e,this._defaultBehavior.followBehaviorEnabled=!e):this._pinButton.isToggled=e}_createPinButton(e){const t=new zN("pin"+this.name,!1);return t.imageUrl=ZN._ASSETS_BASE_URL+ZN._PIN_ICON_FILENAME,t.parent=this,t._host=this._host,t.isToggleButton=!0,t.onToggleObservable.add((e=>{this.isPinned=e})),this._host.utilityLayer&&(t._prepareNode(this._host.utilityLayer.utilityLayerScene),t.scaling.scaleInPlace(wN.MENU_BUTTON_SCALE),t.node&&(t.node.parent=e)),t}_createNode(e){const t=super._createNode(e);return this._pinButton=this._createPinButton(t),this.isPinned=!1,this._defaultBehavior.attach(t,[this._backPlate]),this._defaultBehavior.followBehavior.ignoreCameraPitchAndRoll=!0,this._defaultBehavior.followBehavior.pitchOffset=-15,this._defaultBehavior.followBehavior.minimumDistance=.3,this._defaultBehavior.followBehavior.defaultDistance=.4,this._defaultBehavior.followBehavior.maximumDistance=.6,this._backPlate.isNearGrabbable=!0,t.isVisible=!1,t}_finalProcessing(){super._finalProcessing(),this._pinButton.position.copyFromFloats((this._backPlate.scaling.x+wN.MENU_BUTTON_SCALE)/2,this._backPlate.scaling.y/2,0)}constructor(e){super(e),this._isPinned=!1,this._defaultBehavior=new WN,this._dragObserver=this._defaultBehavior.sixDofDragBehavior.onDragObservable.add((()=>{this.isPinned=!0})),this.backPlateMargin=1}dispose(){super.dispose(),this._defaultBehavior.sixDofDragBehavior.onDragObservable.remove(this._dragObserver),this._defaultBehavior.detach()}}ZN._ASSETS_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",ZN._PIN_ICON_FILENAME="IconPin.png";class JN extends RN{_mapGridNode(e,t){const i=e.mesh;if(!i)return;e.position=t.clone();const s=ve.Vector3[0];switch(s.copyFrom(t),this.orientation){case IN.FACEORIGIN_ORIENTATION:case IN.FACEFORWARD_ORIENTATION:s.addInPlace(new _e(0,0,1)),i.lookAt(s);break;case IN.FACEFORWARDREVERSED_ORIENTATION:case IN.FACEORIGINREVERSED_ORIENTATION:s.addInPlace(new _e(0,0,-1)),i.lookAt(s)}}}class eF extends RN{constructor(){super(...arguments),this._iteration=100}get iteration(){return this._iteration}set iteration(e){this._iteration!==e&&(this._iteration=e,Ds.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh,s=this._scatterMapping(t);if(i){switch(this.orientation){case IN.FACEORIGIN_ORIENTATION:case IN.FACEFORWARD_ORIENTATION:i.lookAt(new _e(0,0,1));break;case IN.FACEFORWARDREVERSED_ORIENTATION:case IN.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new _e(0,0,-1))}e.position=s}}_scatterMapping(e){return e.x=(1-2*Math.random())*this._cellWidth,e.y=(1-2*Math.random())*this._cellHeight,e}_finalProcessing(){const e=[];for(const t of this._children)t.mesh&&e.push(t.mesh);for(let t=0;t{const i=e.position.lengthSquared(),s=t.position.lengthSquared();return is?-1:0}));const t=Math.pow(this.margin,2),i=Math.max(this._cellWidth,this._cellHeight),s=ve.Vector2[0],r=ve.Vector3[0];for(let n=0;n0.0) {C=mix(H,S,k);} else {C=mix(H,G,k); }\nreturn C;}\nvoid Sky_Environment_B50(\nvec3 Normal,\nvec3 Reflected,\nvec4 Sky_Color,\nvec4 Horizon_Color,\nvec4 Ground_Color,\nfloat Horizon_Power,\nout vec4 Reflected_Color,\nout vec4 Indirect_Color)\n{Reflected_Color=SampleEnv_Bid50(Reflected,Sky_Color,Horizon_Color,Ground_Color,Horizon_Power);Indirect_Color=mix(Ground_Color,Sky_Color,Normal.y*0.5+0.5);}\nvoid Min_Segment_Distance_B65(\nvec3 P0,\nvec3 P1,\nvec3 Q0,\nvec3 Q1,\nout vec3 NearP,\nout vec3 NearQ,\nout float Distance)\n{vec3 u=P1-P0;vec3 v=Q1-Q0;vec3 w=P0-Q0;float a=dot(u,u);float b=dot(u,v);float c=dot(v,v);float d=dot(u,w);float e=dot(v,w);float D=a*c-b*b;float sD=D;float tD=D;float sc,sN,tc,tN;if (D<0.00001) {sN=0.0;sD=1.0;tN=e;tD=c;} else {sN=(b*e-c*d);tN=(a*e-b*d);if (sN<0.0) {sN=0.0;tN=e;tD=c;} else if (sN>sD) {sN=sD;tN=e+b;tD=c;}}\nif (tN<0.0) {tN=0.0;if (-d<0.0) {sN=0.0;} else if (-d>a) {sN=sD;} else {sN=-d;sD=a;}} else if (tN>tD) {tN=tD;if ((-d+b)<0.0) {sN=0.0;} else if ((-d+b)>a) {sN=sD;} else {sN=(-d+b);sD=a;}}\nsc=abs(sN)<0.000001 ? 0.0 : sN/sD;tc=abs(tN)<0.000001 ? 0.0 : tN/tD;NearP=P0+sc*u;NearQ=Q0+tc*v;Distance=distance(NearP,NearQ);}\nvoid To_XYZ_B74(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid Finger_Positions_B64(\nvec3 Left_Index_Pos,\nvec3 Right_Index_Pos,\nvec3 Left_Index_Middle_Pos,\nvec3 Right_Index_Middle_Pos,\nout vec3 Left_Index,\nout vec3 Right_Index,\nout vec3 Left_Index_Middle,\nout vec3 Right_Index_Middle)\n{Left_Index= (Use_Global_Left_Index ? Global_Left_Index_Tip_Position.xyz : Left_Index_Pos);Right_Index= (Use_Global_Right_Index ? Global_Right_Index_Tip_Position.xyz : Right_Index_Pos);Left_Index_Middle= (Use_Global_Left_Index ? Global_Left_Index_Middle_Position.xyz : Left_Index_Middle_Pos);Right_Index_Middle= (Use_Global_Right_Index ? Global_Right_Index_Middle_Position.xyz : Right_Index_Middle_Pos);}\nvoid VaryHSV_B108(\nvec3 HSV_In,\nfloat Hue_Shift,\nfloat Saturation_Shift,\nfloat Value_Shift,\nout vec3 HSV_Out)\n{HSV_Out=vec3(fract(HSV_In.x+Hue_Shift),clamp(HSV_In.y+Saturation_Shift,0.0,1.0),clamp(HSV_In.z+Value_Shift,0.0,1.0));}\nvoid Remap_Range_B114(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid To_HSV_B75(\nvec4 Color,\nout float Hue,\nout float Saturation,\nout float Value,\nout float Alpha,\nout vec3 HSV)\n{vec4 K=vec4(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4 p=Color.g0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Conditional_Float_B36(\nbool Which,\nfloat If_True,\nfloat If_False,\nout float Result)\n{Result=Which ? If_True : If_False;}\nvoid Greater_Than_B37(\nfloat Left,\nfloat Right,\nout bool Not_Greater_Than,\nout bool Greater_Than)\n{Greater_Than=Left>Right;Not_Greater_Than=!Greater_Than;}\nvoid Remap_Range_B105(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid main()\n{vec2 XY_Q85;XY_Q85=(uv-vec2(0.5,0.5))*_Decal_Scale_XY_+vec2(0.5,0.5);vec3 Tangent_World_Q27;vec3 Tangent_World_N_Q27;float Tangent_Length_Q27;Tangent_World_Q27=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q27=length(Tangent_World_Q27);Tangent_World_N_Q27=Tangent_World_Q27/Tangent_Length_Q27;vec3 Normal_World_Q60;vec3 Normal_World_N_Q60;float Normal_Length_Q60;Object_To_World_Dir_B60(vec3(0,0,1),Normal_World_Q60,Normal_World_N_Q60,Normal_Length_Q60);float X_Q78;float Y_Q78;float Z_Q78;To_XYZ_B78(position,X_Q78,Y_Q78,Z_Q78);vec3 Nrm_World_Q26;Nrm_World_Q26=normalize((world*vec4(normal,0.0)).xyz);vec3 Binormal_World_Q28;vec3 Binormal_World_N_Q28;float Binormal_Length_Q28;Object_To_World_Dir_B28(vec3(0,1,0),Binormal_World_Q28,Binormal_World_N_Q28,Binormal_Length_Q28);float Anisotropy_Q29=Tangent_Length_Q27/Binormal_Length_Q28;float Result_Q69;Pick_Radius_B69(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q69);float Anisotropy_Q53=Binormal_Length_Q28/Normal_Length_Q60;bool Not_Greater_Than_Q37;bool Greater_Than_Q37;Greater_Than_B37(Z_Q78,0.0,Not_Greater_Than_Q37,Greater_Than_Q37);vec4 Linear_Q101;Linear_Q101.rgb=clamp(_Left_Color_.rgb*_Left_Color_.rgb,0.0,1.0);Linear_Q101.a=_Left_Color_.a;vec4 Linear_Q102;Linear_Q102.rgb=clamp(_Right_Color_.rgb*_Right_Color_.rgb,0.0,1.0);Linear_Q102.a=_Right_Color_.a;vec3 Difference_Q61=vec3(0,0,0)-Normal_World_N_Q60;vec4 Out_Color_Q34=vec4(X_Q78,Y_Q78,Z_Q78,1);float Result_Q36;Conditional_Float_B36(Greater_Than_Q37,_Bevel_Back_,_Bevel_Front_,Result_Q36);float Result_Q94;Conditional_Float_B36(Greater_Than_Q37,_Bevel_Back_Stretch_,_Bevel_Front_Stretch_,Result_Q94);vec3 New_P_Q130;vec2 New_UV_Q130;float Radial_Gradient_Q130;vec3 Radial_Dir_Q130;vec3 New_Normal_Q130;Move_Verts_B130(Anisotropy_Q29,position,Result_Q69,Result_Q36,normal,Anisotropy_Q53,Result_Q94,New_P_Q130,New_UV_Q130,Radial_Gradient_Q130,Radial_Dir_Q130,New_Normal_Q130);float X_Q98;float Y_Q98;X_Q98=New_UV_Q130.x;Y_Q98=New_UV_Q130.y;vec3 Pos_World_Q12;Object_To_World_Pos_B12(New_P_Q130,Pos_World_Q12);vec3 Nrm_World_Q32;Object_To_World_Normal_B32(New_Normal_Q130,Nrm_World_Q32);vec4 Blob_Info_Q23;\n#if BLOB_ENABLE\nBlob_Vertex_B23(Pos_World_Q12,Nrm_World_Q26,Tangent_World_N_Q27,Binormal_World_N_Q28,_Blob_Position_,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q23);\n#else\nBlob_Info_Q23=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q24;\n#if BLOB_ENABLE_2\nBlob_Vertex_B24(Pos_World_Q12,Nrm_World_Q26,Tangent_World_N_Q27,Binormal_World_N_Q28,_Blob_Position_2_,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q24);\n#else\nBlob_Info_Q24=vec4(0,0,0,0);\n#endif\nfloat Out_Q105;Remap_Range_B105(0.0,1.0,0.0,1.0,X_Q98,Out_Q105);float X_Q86;float Y_Q86;float Z_Q86;To_XYZ_B78(Nrm_World_Q32,X_Q86,Y_Q86,Z_Q86);vec4 Color_At_T_Q97=mix(Linear_Q101,Linear_Q102,Out_Q105);float Minus_F_Q87=-Z_Q86;float R_Q99;float G_Q99;float B_Q99;float A_Q99;R_Q99=Color_At_T_Q97.r; G_Q99=Color_At_T_Q97.g; B_Q99=Color_At_T_Q97.b; A_Q99=Color_At_T_Q97.a;float ClampF_Q88=clamp(0.0,Minus_F_Q87,1.0);float Result_Q93;Conditional_Float_B93(_Decal_Front_Only_,ClampF_Q88,1.0,Result_Q93);vec4 Vec4_Q89=vec4(Result_Q93,Radial_Gradient_Q130,G_Q99,B_Q99);vec3 Position=Pos_World_Q12;vec3 Normal=Nrm_World_Q32;vec2 UV=XY_Q85;vec3 Tangent=Tangent_World_N_Q27;vec3 Binormal=Difference_Q61;vec4 Color=Out_Color_Q34;vec4 Extra1=Vec4_Q89;vec4 Extra2=Blob_Info_Q23;vec4 Extra3=Blob_Info_Q24;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class tF extends xl{constructor(){super(),this.SKY_ENABLED=!0,this.BLOB_ENABLE_2=!0,this.IRIDESCENCE_ENABLED=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class iF extends ml{constructor(e,t){super(e,t),this.radius=.6,this.bevelFront=.6,this.bevelFrontStretch=.077,this.bevelBack=0,this.bevelBackStretch=0,this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this.bulgeEnabled=!1,this.bulgeHeight=-.323,this.bulgeRadius=.73,this.sunIntensity=1.102,this.sunTheta=.76,this.sunPhi=.526,this.indirectDiffuse=.658,this.albedo=new Ae(.0117647,.505882,.996078,1),this.specular=0,this.shininess=10,this.sharpness=0,this.subsurface=0,this.leftGradientColor=new Ae(.0117647,.505882,.996078,1),this.rightGradientColor=new Ae(.0117647,.505882,.996078,1),this.reflection=.749,this.frontReflect=0,this.edgeReflect=.09,this.power=8.13,this.skyColor=new Ae(.0117647,.964706,.996078,1),this.horizonColor=new Ae(.0117647,.333333,.996078,1),this.groundColor=new Ae(0,.254902,.996078,1),this.horizonPower=1,this.width=.02,this.fuzz=.5,this.minFuzz=.001,this.clipFade=.01,this.hueShift=0,this.saturationShift=0,this.valueShift=0,this.blobPosition=new _e(0,0,.1),this.blobIntensity=.5,this.blobNearSize=.01,this.blobFarSize=.03,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.576,this.blobPulse=0,this.blobFade=1,this.blobPosition2=new _e(.2,0,.1),this.blobNearSize2=.01,this.blobPulse2=0,this.blobFade2=1,this.blobTexture=new Pa("",this.getScene()),this.leftIndexPosition=new _e(0,0,1),this.rightIndexPosition=new _e(-1,-1,-1),this.leftIndexMiddlePosition=new _e(0,0,0),this.rightIndexMiddlePosition=new _e(0,0,0),this.decalScaleXY=new de(1.5,1.5),this.decalFrontOnly=!0,this.rimIntensity=.287,this.rimHueShift=0,this.rimSaturationShift=0,this.rimValueShift=-1,this.iridescenceIntensity=0,this.useGlobalLeftIndex=1,this.useGlobalRightIndex=1,this.globalLeftIndexTipProximity=0,this.globalRightIndexTipProximity=0,this.globalLeftIndexTipPosition=new pe(.5,0,-.55,1),this.globaRightIndexTipPosition=new pe(0,0,0,1),this.globalLeftThumbTipPosition=new pe(.5,0,-.55,1),this.globalRightThumbTipPosition=new pe(0,0,0,1),this.globalLeftIndexMiddlePosition=new pe(.5,0,-.55,1),this.globalRightIndexMiddlePosition=new pe(0,0,0,1),this.alphaMode=N_.ALPHA_DISABLE,this.backFaceCulling=!1,this._blueGradientTexture=new Pa(iF.BLUE_GRADIENT_TEXTURE_URL,this.getScene(),!0,!1,Pa.NEAREST_SAMPLINGMODE),this._decalTexture=new Pa("",this.getScene()),this._reflectionMapTexture=new Pa("",this.getScene()),this._indirectEnvTexture=new Pa("",this.getScene())}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new tF);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="mrdlSliderBar",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Bevel_Front_","_Bevel_Front_Stretch_","_Bevel_Back_","_Bevel_Back_Stretch_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Bulge_Enabled_","_Bulge_Height_","_Bulge_Radius_","_Sun_Intensity_","_Sun_Theta_","_Sun_Phi_","_Indirect_Diffuse_","_Albedo_","_Specular_","_Shininess_","_Sharpness_","_Subsurface_","_Left_Color_","_Right_Color_","_Reflection_","_Front_Reflect_","_Edge_Reflect_","_Power_","_Sky_Color_","_Horizon_Color_","_Ground_Color_","_Horizon_Power_","_Reflection_Map_","_Indirect_Environment_","_Width_","_Fuzz_","_Min_Fuzz_","_Clip_Fade_","_Hue_Shift_","_Saturation_Shift_","_Value_Shift_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Left_Index_Pos_","_Right_Index_Pos_","_Left_Index_Middle_Pos_","_Right_Index_Middle_Pos_","_Decal_","_Decal_Scale_XY_","_Decal_Front_Only_","_Rim_Intensity_","_Rim_Texture_","_Rim_Hue_Shift_","_Rim_Saturation_Shift_","_Rim_Value_Shift_","_Iridescence_Intensity_","_Iridescence_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Middle_Position;","Global_Right_Index_Middle_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Rim_Texture_","_Iridescence_Texture_"],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Bevel_Front_",this.bevelFront),this._activeEffect.setFloat("_Bevel_Front_Stretch_",this.bevelFrontStretch),this._activeEffect.setFloat("_Bevel_Back_",this.bevelBack),this._activeEffect.setFloat("_Bevel_Back_Stretch_",this.bevelBackStretch),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Bulge_Enabled_",this.bulgeEnabled?1:0),this._activeEffect.setFloat("_Bulge_Height_",this.bulgeHeight),this._activeEffect.setFloat("_Bulge_Radius_",this.bulgeRadius),this._activeEffect.setFloat("_Sun_Intensity_",this.sunIntensity),this._activeEffect.setFloat("_Sun_Theta_",this.sunTheta),this._activeEffect.setFloat("_Sun_Phi_",this.sunPhi),this._activeEffect.setFloat("_Indirect_Diffuse_",this.indirectDiffuse),this._activeEffect.setDirectColor4("_Albedo_",this.albedo),this._activeEffect.setFloat("_Specular_",this.specular),this._activeEffect.setFloat("_Shininess_",this.shininess),this._activeEffect.setFloat("_Sharpness_",this.sharpness),this._activeEffect.setFloat("_Subsurface_",this.subsurface),this._activeEffect.setDirectColor4("_Left_Color_",this.leftGradientColor),this._activeEffect.setDirectColor4("_Right_Color_",this.rightGradientColor),this._activeEffect.setFloat("_Reflection_",this.reflection),this._activeEffect.setFloat("_Front_Reflect_",this.frontReflect),this._activeEffect.setFloat("_Edge_Reflect_",this.edgeReflect),this._activeEffect.setFloat("_Power_",this.power),this._activeEffect.setDirectColor4("_Sky_Color_",this.skyColor),this._activeEffect.setDirectColor4("_Horizon_Color_",this.horizonColor),this._activeEffect.setDirectColor4("_Ground_Color_",this.groundColor),this._activeEffect.setFloat("_Horizon_Power_",this.horizonPower),this._activeEffect.setTexture("_Reflection_Map_",this._reflectionMapTexture),this._activeEffect.setTexture("_Indirect_Environment_",this._indirectEnvTexture),this._activeEffect.setFloat("_Width_",this.width),this._activeEffect.setFloat("_Fuzz_",this.fuzz),this._activeEffect.setFloat("_Min_Fuzz_",this.minFuzz),this._activeEffect.setFloat("_Clip_Fade_",this.clipFade),this._activeEffect.setFloat("_Hue_Shift_",this.hueShift),this._activeEffect.setFloat("_Saturation_Shift_",this.saturationShift),this._activeEffect.setFloat("_Value_Shift_",this.valueShift),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this.blobTexture),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setVector3("_Left_Index_Pos_",this.leftIndexPosition),this._activeEffect.setVector3("_Right_Index_Pos_",this.rightIndexPosition),this._activeEffect.setVector3("_Left_Index_Middle_Pos_",this.leftIndexMiddlePosition),this._activeEffect.setVector3("_Right_Index_Middle_Pos_",this.rightIndexMiddlePosition),this._activeEffect.setTexture("_Decal_",this._decalTexture),this._activeEffect.setVector2("_Decal_Scale_XY_",this.decalScaleXY),this._activeEffect.setFloat("_Decal_Front_Only_",this.decalFrontOnly?1:0),this._activeEffect.setFloat("_Rim_Intensity_",this.rimIntensity),this._activeEffect.setTexture("_Rim_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("_Rim_Hue_Shift_",this.rimHueShift),this._activeEffect.setFloat("_Rim_Saturation_Shift_",this.rimSaturationShift),this._activeEffect.setFloat("_Rim_Value_Shift_",this.rimValueShift),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setTexture("_Iridescence_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("Use_Global_Left_Index",this.useGlobalLeftIndex),this._activeEffect.setFloat("Use_Global_Right_Index",this.useGlobalRightIndex),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this.globalLeftIndexTipPosition),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this.globaRightIndexTipPosition),this._activeEffect.setVector4("Global_Left_Thumb_Tip_Position",this.globalLeftThumbTipPosition),this._activeEffect.setVector4("Global_Right_Thumb_Tip_Position",this.globalRightThumbTipPosition),this._activeEffect.setVector4("Global_Left_Index_Middle_Position",this.globalLeftIndexMiddlePosition),this._activeEffect.setVector4("Global_Right_Index_Middle_Position",this.globalRightIndexMiddlePosition),this._activeEffect.setFloat("Global_Left_Index_Tip_Proximity",this.globalLeftIndexTipProximity),this._activeEffect.setFloat("Global_Right_Index_Tip_Proximity",this.globalRightIndexTipProximity),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._reflectionMapTexture.dispose(),this._indirectEnvTexture.dispose(),this._blueGradientTexture.dispose(),this._decalTexture.dispose()}clone(e){return St.Clone((()=>new iF(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLSliderBarMaterial",e}getClassName(){return"MRDLSliderBarMaterial"}static Parse(e,t,i){return St.Parse((()=>new iF(e.name,t)),e,t,i)}}iF.BLUE_GRADIENT_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-blue-gradient.png",Ze([rt()],iF.prototype,"radius",void 0),Ze([rt()],iF.prototype,"bevelFront",void 0),Ze([rt()],iF.prototype,"bevelFrontStretch",void 0),Ze([rt()],iF.prototype,"bevelBack",void 0),Ze([rt()],iF.prototype,"bevelBackStretch",void 0),Ze([rt()],iF.prototype,"radiusTopLeft",void 0),Ze([rt()],iF.prototype,"radiusTopRight",void 0),Ze([rt()],iF.prototype,"radiusBottomLeft",void 0),Ze([rt()],iF.prototype,"radiusBottomRight",void 0),Ze([rt()],iF.prototype,"bulgeEnabled",void 0),Ze([rt()],iF.prototype,"bulgeHeight",void 0),Ze([rt()],iF.prototype,"bulgeRadius",void 0),Ze([rt()],iF.prototype,"sunIntensity",void 0),Ze([rt()],iF.prototype,"sunTheta",void 0),Ze([rt()],iF.prototype,"sunPhi",void 0),Ze([rt()],iF.prototype,"indirectDiffuse",void 0),Ze([rt()],iF.prototype,"albedo",void 0),Ze([rt()],iF.prototype,"specular",void 0),Ze([rt()],iF.prototype,"shininess",void 0),Ze([rt()],iF.prototype,"sharpness",void 0),Ze([rt()],iF.prototype,"subsurface",void 0),Ze([rt()],iF.prototype,"leftGradientColor",void 0),Ze([rt()],iF.prototype,"rightGradientColor",void 0),Ze([rt()],iF.prototype,"reflection",void 0),Ze([rt()],iF.prototype,"frontReflect",void 0),Ze([rt()],iF.prototype,"edgeReflect",void 0),Ze([rt()],iF.prototype,"power",void 0),Ze([rt()],iF.prototype,"skyColor",void 0),Ze([rt()],iF.prototype,"horizonColor",void 0),Ze([rt()],iF.prototype,"groundColor",void 0),Ze([rt()],iF.prototype,"horizonPower",void 0),Ze([rt()],iF.prototype,"width",void 0),Ze([rt()],iF.prototype,"fuzz",void 0),Ze([rt()],iF.prototype,"minFuzz",void 0),Ze([rt()],iF.prototype,"clipFade",void 0),Ze([rt()],iF.prototype,"hueShift",void 0),Ze([rt()],iF.prototype,"saturationShift",void 0),Ze([rt()],iF.prototype,"valueShift",void 0),Ze([rt()],iF.prototype,"blobPosition",void 0),Ze([rt()],iF.prototype,"blobIntensity",void 0),Ze([rt()],iF.prototype,"blobNearSize",void 0),Ze([rt()],iF.prototype,"blobFarSize",void 0),Ze([rt()],iF.prototype,"blobNearDistance",void 0),Ze([rt()],iF.prototype,"blobFarDistance",void 0),Ze([rt()],iF.prototype,"blobFadeLength",void 0),Ze([rt()],iF.prototype,"blobPulse",void 0),Ze([rt()],iF.prototype,"blobFade",void 0),Ze([rt()],iF.prototype,"blobPosition2",void 0),Ze([rt()],iF.prototype,"blobNearSize2",void 0),Ze([rt()],iF.prototype,"blobPulse2",void 0),Ze([rt()],iF.prototype,"blobFade2",void 0),Ze([rt()],iF.prototype,"blobTexture",void 0),Ze([rt()],iF.prototype,"leftIndexPosition",void 0),Ze([rt()],iF.prototype,"rightIndexPosition",void 0),Ze([rt()],iF.prototype,"leftIndexMiddlePosition",void 0),Ze([rt()],iF.prototype,"rightIndexMiddlePosition",void 0),Ze([rt()],iF.prototype,"decalScaleXY",void 0),Ze([rt()],iF.prototype,"decalFrontOnly",void 0),Ze([rt()],iF.prototype,"rimIntensity",void 0),Ze([rt()],iF.prototype,"rimHueShift",void 0),Ze([rt()],iF.prototype,"rimSaturationShift",void 0),Ze([rt()],iF.prototype,"rimValueShift",void 0),Ze([rt()],iF.prototype,"iridescenceIntensity",void 0),z("BABYLON.GUI.MRDLSliderBarMaterial",iF);Bi.ShadersStore.mrdlSliderThumbPixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vColor;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;uniform float _Radius_;uniform float _Bevel_Front_;uniform float _Bevel_Front_Stretch_;uniform float _Bevel_Back_;uniform float _Bevel_Back_Stretch_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform bool _Bulge_Enabled_;uniform float _Bulge_Height_;uniform float _Bulge_Radius_;uniform float _Sun_Intensity_;uniform float _Sun_Theta_;uniform float _Sun_Phi_;uniform float _Indirect_Diffuse_;uniform vec4 _Albedo_;uniform float _Specular_;uniform float _Shininess_;uniform float _Sharpness_;uniform float _Subsurface_;uniform vec4 _Left_Color_;uniform vec4 _Right_Color_;uniform float _Reflection_;uniform float _Front_Reflect_;uniform float _Edge_Reflect_;uniform float _Power_;uniform vec4 _Sky_Color_;uniform vec4 _Horizon_Color_;uniform vec4 _Ground_Color_;uniform float _Horizon_Power_;uniform sampler2D _Reflection_Map_;uniform sampler2D _Indirect_Environment_;uniform float _Width_;uniform float _Fuzz_;uniform float _Min_Fuzz_;uniform float _Clip_Fade_;uniform float _Hue_Shift_;uniform float _Saturation_Shift_;uniform float _Value_Shift_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform sampler2D _Blob_Texture_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform vec3 _Left_Index_Pos_;uniform vec3 _Right_Index_Pos_;uniform vec3 _Left_Index_Middle_Pos_;uniform vec3 _Right_Index_Middle_Pos_;uniform sampler2D _Decal_;uniform vec2 _Decal_Scale_XY_;uniform bool _Decal_Front_Only_;uniform float _Rim_Intensity_;uniform sampler2D _Rim_Texture_;uniform float _Rim_Hue_Shift_;uniform float _Rim_Saturation_Shift_;uniform float _Rim_Value_Shift_;uniform float _Iridescence_Intensity_;uniform sampler2D _Iridescence_Texture_;uniform bool Use_Global_Left_Index;uniform bool Use_Global_Right_Index;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;uniform vec4 Global_Left_Thumb_Tip_Position;uniform vec4 Global_Right_Thumb_Tip_Position;uniform vec4 Global_Left_Index_Middle_Position;uniform vec4 Global_Right_Index_Middle_Position;uniform float Global_Left_Index_Tip_Proximity;uniform float Global_Right_Index_Tip_Proximity;void Blob_Fragment_B180(\nsampler2D Blob_Texture,\nvec4 Blob_Info1,\nvec4 Blob_Info2,\nout vec4 Blob_Color)\n{float k1=dot(Blob_Info1.xy,Blob_Info1.xy);float k2=dot(Blob_Info2.xy,Blob_Info2.xy);vec3 closer=k10.0) {C=mix(H,S,k);} else {C=mix(H,G,k); }\nreturn C;}\nvoid Sky_Environment_B200(\nvec3 Normal,\nvec3 Reflected,\nvec4 Sky_Color,\nvec4 Horizon_Color,\nvec4 Ground_Color,\nfloat Horizon_Power,\nout vec4 Reflected_Color,\nout vec4 Indirect_Color)\n{Reflected_Color=SampleEnv_Bid200(Reflected,Sky_Color,Horizon_Color,Ground_Color,Horizon_Power);Indirect_Color=mix(Ground_Color,Sky_Color,Normal.y*0.5+0.5);}\nvoid Min_Segment_Distance_B215(\nvec3 P0,\nvec3 P1,\nvec3 Q0,\nvec3 Q1,\nout vec3 NearP,\nout vec3 NearQ,\nout float Distance)\n{vec3 u=P1-P0;vec3 v=Q1-Q0;vec3 w=P0-Q0;float a=dot(u,u);float b=dot(u,v);float c=dot(v,v);float d=dot(u,w);float e=dot(v,w);float D=a*c-b*b;float sD=D;float tD=D;float sc,sN,tc,tN;if (D<0.00001) {sN=0.0;sD=1.0;tN=e;tD=c;} else {sN=(b*e-c*d);tN=(a*e-b*d);if (sN<0.0) {sN=0.0;tN=e;tD=c;} else if (sN>sD) {sN=sD;tN=e+b;tD=c;}}\nif (tN<0.0) {tN=0.0;if (-d<0.0) {sN=0.0;} else if (-d>a) {sN=sD;} else {sN=-d;sD=a;}} else if (tN>tD) {tN=tD;if ((-d+b)<0.0) {sN=0.0;} else if ((-d+b)>a) {sN=sD;} else {sN=(-d+b);sD=a;}}\nsc=abs(sN)<0.000001 ? 0.0 : sN/sD;tc=abs(tN)<0.000001 ? 0.0 : tN/tD;NearP=P0+sc*u;NearQ=Q0+tc*v;Distance=distance(NearP,NearQ);}\nvoid To_XYZ_B224(\nvec3 Vec3,\nout float X,\nout float Y,\nout float Z)\n{X=Vec3.x;Y=Vec3.y;Z=Vec3.z;}\nvoid Finger_Positions_B214(\nvec3 Left_Index_Pos,\nvec3 Right_Index_Pos,\nvec3 Left_Index_Middle_Pos,\nvec3 Right_Index_Middle_Pos,\nout vec3 Left_Index,\nout vec3 Right_Index,\nout vec3 Left_Index_Middle,\nout vec3 Right_Index_Middle)\n{Left_Index= (Use_Global_Left_Index ? Global_Left_Index_Tip_Position.xyz : Left_Index_Pos);Right_Index= (Use_Global_Right_Index ? Global_Right_Index_Tip_Position.xyz : Right_Index_Pos);Left_Index_Middle= (Use_Global_Left_Index ? Global_Left_Index_Middle_Position.xyz : Left_Index_Middle_Pos);Right_Index_Middle= (Use_Global_Right_Index ? Global_Right_Index_Middle_Position.xyz : Right_Index_Middle_Pos);}\nvoid VaryHSV_B258(\nvec3 HSV_In,\nfloat Hue_Shift,\nfloat Saturation_Shift,\nfloat Value_Shift,\nout vec3 HSV_Out)\n{HSV_Out=vec3(fract(HSV_In.x+Hue_Shift),clamp(HSV_In.y+Saturation_Shift,0.0,1.0),clamp(HSV_In.z+Value_Shift,0.0,1.0));}\nvoid Remap_Range_B264(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid To_HSV_B225(\nvec4 Color,\nout float Hue,\nout float Saturation,\nout float Value,\nout float Alpha,\nout vec3 HSV)\n{vec4 K=vec4(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4 p=Color.g0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Conditional_Float_B186(\nbool Which,\nfloat If_True,\nfloat If_False,\nout float Result)\n{Result=Which ? If_True : If_False;}\nvoid Greater_Than_B187(\nfloat Left,\nfloat Right,\nout bool Not_Greater_Than,\nout bool Greater_Than)\n{Greater_Than=Left>Right;Not_Greater_Than=!Greater_Than;}\nvoid Remap_Range_B255(\nfloat In_Min,\nfloat In_Max,\nfloat Out_Min,\nfloat Out_Max,\nfloat In,\nout float Out)\n{Out=mix(Out_Min,Out_Max,clamp((In-In_Min)/(In_Max-In_Min),0.0,1.0));}\nvoid main()\n{vec2 XY_Q235;XY_Q235=(uv-vec2(0.5,0.5))*_Decal_Scale_XY_+vec2(0.5,0.5);vec3 Tangent_World_Q177;vec3 Tangent_World_N_Q177;float Tangent_Length_Q177;Tangent_World_Q177=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q177=length(Tangent_World_Q177);Tangent_World_N_Q177=Tangent_World_Q177/Tangent_Length_Q177;vec3 Normal_World_Q210;vec3 Normal_World_N_Q210;float Normal_Length_Q210;Object_To_World_Dir_B210(vec3(0,0,1),Normal_World_Q210,Normal_World_N_Q210,Normal_Length_Q210);float X_Q228;float Y_Q228;float Z_Q228;To_XYZ_B228(position,X_Q228,Y_Q228,Z_Q228);vec3 Nrm_World_Q176;Nrm_World_Q176=normalize((world*vec4(normal,0.0)).xyz);vec3 Binormal_World_Q178;vec3 Binormal_World_N_Q178;float Binormal_Length_Q178;Object_To_World_Dir_B178(vec3(0,1,0),Binormal_World_Q178,Binormal_World_N_Q178,Binormal_Length_Q178);float Anisotropy_Q179=Tangent_Length_Q177/Binormal_Length_Q178;float Result_Q219;Pick_Radius_B219(_Radius_,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q219);float Anisotropy_Q203=Binormal_Length_Q178/Normal_Length_Q210;bool Not_Greater_Than_Q187;bool Greater_Than_Q187;Greater_Than_B187(Z_Q228,0.0,Not_Greater_Than_Q187,Greater_Than_Q187);vec4 Linear_Q251;Linear_Q251.rgb=clamp(_Left_Color_.rgb*_Left_Color_.rgb,0.0,1.0);Linear_Q251.a=_Left_Color_.a;vec4 Linear_Q252;Linear_Q252.rgb=clamp(_Right_Color_.rgb*_Right_Color_.rgb,0.0,1.0);Linear_Q252.a=_Right_Color_.a;vec3 Difference_Q211=vec3(0,0,0)-Normal_World_N_Q210;vec4 Out_Color_Q184=vec4(X_Q228,Y_Q228,Z_Q228,1);float Result_Q186;Conditional_Float_B186(Greater_Than_Q187,_Bevel_Back_,_Bevel_Front_,Result_Q186);float Result_Q244;Conditional_Float_B186(Greater_Than_Q187,_Bevel_Back_Stretch_,_Bevel_Front_Stretch_,Result_Q244);vec3 New_P_Q280;vec2 New_UV_Q280;float Radial_Gradient_Q280;vec3 Radial_Dir_Q280;vec3 New_Normal_Q280;Move_Verts_B280(Anisotropy_Q179,position,Result_Q219,Result_Q186,normal,Anisotropy_Q203,Result_Q244,New_P_Q280,New_UV_Q280,Radial_Gradient_Q280,Radial_Dir_Q280,New_Normal_Q280);float X_Q248;float Y_Q248;X_Q248=New_UV_Q280.x;Y_Q248=New_UV_Q280.y;vec3 Pos_World_Q162;Object_To_World_Pos_B162(New_P_Q280,Pos_World_Q162);vec3 Nrm_World_Q182;Object_To_World_Normal_B182(New_Normal_Q280,Nrm_World_Q182);vec4 Blob_Info_Q173;\n#if BLOB_ENABLE\nBlob_Vertex_B173(Pos_World_Q162,Nrm_World_Q176,Tangent_World_N_Q177,Binormal_World_N_Q178,_Blob_Position_,_Blob_Intensity_,_Blob_Near_Size_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_,_Blob_Fade_,Blob_Info_Q173);\n#else\nBlob_Info_Q173=vec4(0,0,0,0);\n#endif\nvec4 Blob_Info_Q174;\n#if BLOB_ENABLE_2\nBlob_Vertex_B174(Pos_World_Q162,Nrm_World_Q176,Tangent_World_N_Q177,Binormal_World_N_Q178,_Blob_Position_2_,_Blob_Intensity_,_Blob_Near_Size_2_,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,_Blob_Fade_Length_,_Blob_Pulse_2_,_Blob_Fade_2_,Blob_Info_Q174);\n#else\nBlob_Info_Q174=vec4(0,0,0,0);\n#endif\nfloat Out_Q255;Remap_Range_B255(0.0,1.0,0.0,1.0,X_Q248,Out_Q255);float X_Q236;float Y_Q236;float Z_Q236;To_XYZ_B228(Nrm_World_Q182,X_Q236,Y_Q236,Z_Q236);vec4 Color_At_T_Q247=mix(Linear_Q251,Linear_Q252,Out_Q255);float Minus_F_Q237=-Z_Q236;float R_Q249;float G_Q249;float B_Q249;float A_Q249;R_Q249=Color_At_T_Q247.r; G_Q249=Color_At_T_Q247.g; B_Q249=Color_At_T_Q247.b; A_Q249=Color_At_T_Q247.a;float ClampF_Q238=clamp(0.0,Minus_F_Q237,1.0);float Result_Q243;Conditional_Float_B243(_Decal_Front_Only_,ClampF_Q238,1.0,Result_Q243);vec4 Vec4_Q239=vec4(Result_Q243,Radial_Gradient_Q280,G_Q249,B_Q249);vec3 Position=Pos_World_Q162;vec3 Normal=Nrm_World_Q182;vec2 UV=XY_Q235;vec3 Tangent=Tangent_World_N_Q177;vec3 Binormal=Difference_Q211;vec4 Color=Out_Color_Q184;vec4 Extra1=Vec4_Q239;vec4 Extra2=Blob_Info_Q173;vec4 Extra3=Blob_Info_Q174;gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vColor=Color;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class sF extends xl{constructor(){super(),this.SKY_ENABLED=!0,this.BLOB_ENABLE_2=!0,this.IRIDESCENCE_ENABLED=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class rF extends ml{constructor(e,t){super(e,t),this.radius=.157,this.bevelFront=.065,this.bevelFrontStretch=.077,this.bevelBack=.031,this.bevelBackStretch=0,this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this.bulgeEnabled=!1,this.bulgeHeight=-.323,this.bulgeRadius=.73,this.sunIntensity=2,this.sunTheta=.937,this.sunPhi=.555,this.indirectDiffuse=1,this.albedo=new Ae(.0117647,.505882,.996078,1),this.specular=0,this.shininess=10,this.sharpness=0,this.subsurface=.31,this.leftGradientColor=new Ae(.0117647,.505882,.996078,1),this.rightGradientColor=new Ae(.0117647,.505882,.996078,1),this.reflection=.749,this.frontReflect=0,this.edgeReflect=.09,this.power=8.1,this.skyColor=new Ae(.0117647,.960784,.996078,1),this.horizonColor=new Ae(.0117647,.333333,.996078,1),this.groundColor=new Ae(0,.254902,.996078,1),this.horizonPower=1,this.width=.02,this.fuzz=.5,this.minFuzz=.001,this.clipFade=.01,this.hueShift=0,this.saturationShift=0,this.valueShift=0,this.blobPosition=new _e(0,0,.1),this.blobIntensity=.5,this.blobNearSize=.01,this.blobFarSize=.03,this.blobNearDistance=0,this.blobFarDistance=.08,this.blobFadeLength=.576,this.blobPulse=0,this.blobFade=1,this.blobPosition2=new _e(.2,0,.1),this.blobNearSize2=.01,this.blobPulse2=0,this.blobFade2=1,this.blobTexture=new Pa("",this.getScene()),this.leftIndexPosition=new _e(0,0,1),this.rightIndexPosition=new _e(-1,-1,-1),this.leftIndexMiddlePosition=new _e(0,0,0),this.rightIndexMiddlePosition=new _e(0,0,0),this.decalScaleXY=new de(1.5,1.5),this.decalFrontOnly=!0,this.rimIntensity=.287,this.rimHueShift=0,this.rimSaturationShift=0,this.rimValueShift=-1,this.iridescenceIntensity=0,this.useGlobalLeftIndex=1,this.useGlobalRightIndex=1,this.globalLeftIndexTipProximity=0,this.globalRightIndexTipProximity=0,this.globalLeftIndexTipPosition=new pe(.5,0,-.55,1),this.globaRightIndexTipPosition=new pe(0,0,0,1),this.globalLeftThumbTipPosition=new pe(.5,0,-.55,1),this.globalRightThumbTipPosition=new pe(0,0,0,1),this.globalLeftIndexMiddlePosition=new pe(.5,0,-.55,1),this.globalRightIndexMiddlePosition=new pe(0,0,0,1),this.alphaMode=N_.ALPHA_DISABLE,this.backFaceCulling=!1,this._blueGradientTexture=new Pa(rF.BLUE_GRADIENT_TEXTURE_URL,t,!0,!1,Pa.NEAREST_SAMPLINGMODE),this._decalTexture=new Pa("",this.getScene()),this._reflectionMapTexture=new Pa("",this.getScene()),this._indirectEnvTexture=new Pa("",this.getScene())}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new sF);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="mrdlSliderThumb",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Bevel_Front_","_Bevel_Front_Stretch_","_Bevel_Back_","_Bevel_Back_Stretch_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Bulge_Enabled_","_Bulge_Height_","_Bulge_Radius_","_Sun_Intensity_","_Sun_Theta_","_Sun_Phi_","_Indirect_Diffuse_","_Albedo_","_Specular_","_Shininess_","_Sharpness_","_Subsurface_","_Left_Color_","_Right_Color_","_Reflection_","_Front_Reflect_","_Edge_Reflect_","_Power_","_Sky_Color_","_Horizon_Color_","_Ground_Color_","_Horizon_Power_","_Reflection_Map_","_Indirect_Environment_","_Width_","_Fuzz_","_Min_Fuzz_","_Clip_Fade_","_Hue_Shift_","_Saturation_Shift_","_Value_Shift_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Pulse_","_Blob_Fade_","_Blob_Texture_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Left_Index_Pos_","_Right_Index_Pos_","_Left_Index_Middle_Pos_","_Right_Index_Middle_Pos_","_Decal_","_Decal_Scale_XY_","_Decal_Front_Only_","_Rim_Intensity_","_Rim_Texture_","_Rim_Hue_Shift_","_Rim_Saturation_Shift_","_Rim_Value_Shift_","_Iridescence_Intensity_","_Iridescence_Texture_","Use_Global_Left_Index","Use_Global_Right_Index","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","Global_Left_Thumb_Tip_Position","Global_Right_Thumb_Tip_Position","Global_Left_Index_Middle_Position;","Global_Right_Index_Middle_Position","Global_Left_Index_Tip_Proximity","Global_Right_Index_Tip_Proximity"],h=["_Rim_Texture_","_Iridescence_Texture_"],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Bevel_Front_",this.bevelFront),this._activeEffect.setFloat("_Bevel_Front_Stretch_",this.bevelFrontStretch),this._activeEffect.setFloat("_Bevel_Back_",this.bevelBack),this._activeEffect.setFloat("_Bevel_Back_Stretch_",this.bevelBackStretch),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Bulge_Enabled_",this.bulgeEnabled?1:0),this._activeEffect.setFloat("_Bulge_Height_",this.bulgeHeight),this._activeEffect.setFloat("_Bulge_Radius_",this.bulgeRadius),this._activeEffect.setFloat("_Sun_Intensity_",this.sunIntensity),this._activeEffect.setFloat("_Sun_Theta_",this.sunTheta),this._activeEffect.setFloat("_Sun_Phi_",this.sunPhi),this._activeEffect.setFloat("_Indirect_Diffuse_",this.indirectDiffuse),this._activeEffect.setDirectColor4("_Albedo_",this.albedo),this._activeEffect.setFloat("_Specular_",this.specular),this._activeEffect.setFloat("_Shininess_",this.shininess),this._activeEffect.setFloat("_Sharpness_",this.sharpness),this._activeEffect.setFloat("_Subsurface_",this.subsurface),this._activeEffect.setDirectColor4("_Left_Color_",this.leftGradientColor),this._activeEffect.setDirectColor4("_Right_Color_",this.rightGradientColor),this._activeEffect.setFloat("_Reflection_",this.reflection),this._activeEffect.setFloat("_Front_Reflect_",this.frontReflect),this._activeEffect.setFloat("_Edge_Reflect_",this.edgeReflect),this._activeEffect.setFloat("_Power_",this.power),this._activeEffect.setDirectColor4("_Sky_Color_",this.skyColor),this._activeEffect.setDirectColor4("_Horizon_Color_",this.horizonColor),this._activeEffect.setDirectColor4("_Ground_Color_",this.groundColor),this._activeEffect.setFloat("_Horizon_Power_",this.horizonPower),this._activeEffect.setTexture("_Reflection_Map_",this._reflectionMapTexture),this._activeEffect.setTexture("_Indirect_Environment_",this._indirectEnvTexture),this._activeEffect.setFloat("_Width_",this.width),this._activeEffect.setFloat("_Fuzz_",this.fuzz),this._activeEffect.setFloat("_Min_Fuzz_",this.minFuzz),this._activeEffect.setFloat("_Clip_Fade_",this.clipFade),this._activeEffect.setFloat("_Hue_Shift_",this.hueShift),this._activeEffect.setFloat("_Saturation_Shift_",this.saturationShift),this._activeEffect.setFloat("_Value_Shift_",this.valueShift),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setTexture("_Blob_Texture_",this.blobTexture),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setVector3("_Left_Index_Pos_",this.leftIndexPosition),this._activeEffect.setVector3("_Right_Index_Pos_",this.rightIndexPosition),this._activeEffect.setVector3("_Left_Index_Middle_Pos_",this.leftIndexMiddlePosition),this._activeEffect.setVector3("_Right_Index_Middle_Pos_",this.rightIndexMiddlePosition),this._activeEffect.setTexture("_Decal_",this._decalTexture),this._activeEffect.setVector2("_Decal_Scale_XY_",this.decalScaleXY),this._activeEffect.setFloat("_Decal_Front_Only_",this.decalFrontOnly?1:0),this._activeEffect.setFloat("_Rim_Intensity_",this.rimIntensity),this._activeEffect.setTexture("_Rim_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("_Rim_Hue_Shift_",this.rimHueShift),this._activeEffect.setFloat("_Rim_Saturation_Shift_",this.rimSaturationShift),this._activeEffect.setFloat("_Rim_Value_Shift_",this.rimValueShift),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setTexture("_Iridescence_Texture_",this._blueGradientTexture),this._activeEffect.setFloat("Use_Global_Left_Index",this.useGlobalLeftIndex),this._activeEffect.setFloat("Use_Global_Right_Index",this.useGlobalRightIndex),this._activeEffect.setVector4("Global_Left_Index_Tip_Position",this.globalLeftIndexTipPosition),this._activeEffect.setVector4("Global_Right_Index_Tip_Position",this.globaRightIndexTipPosition),this._activeEffect.setVector4("Global_Left_Thumb_Tip_Position",this.globalLeftThumbTipPosition),this._activeEffect.setVector4("Global_Right_Thumb_Tip_Position",this.globalRightThumbTipPosition),this._activeEffect.setVector4("Global_Left_Index_Middle_Position",this.globalLeftIndexMiddlePosition),this._activeEffect.setVector4("Global_Right_Index_Middle_Position",this.globalRightIndexMiddlePosition),this._activeEffect.setFloat("Global_Left_Index_Tip_Proximity",this.globalLeftIndexTipProximity),this._activeEffect.setFloat("Global_Right_Index_Tip_Proximity",this.globalRightIndexTipProximity),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e),this._reflectionMapTexture.dispose(),this._indirectEnvTexture.dispose(),this._blueGradientTexture.dispose(),this._decalTexture.dispose()}clone(e){return St.Clone((()=>new rF(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLSliderThumbMaterial",e}getClassName(){return"MRDLSliderThumbMaterial"}static Parse(e,t,i){return St.Parse((()=>new rF(e.name,t)),e,t,i)}}rF.BLUE_GRADIENT_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-blue-gradient.png",Ze([rt()],rF.prototype,"radius",void 0),Ze([rt()],rF.prototype,"bevelFront",void 0),Ze([rt()],rF.prototype,"bevelFrontStretch",void 0),Ze([rt()],rF.prototype,"bevelBack",void 0),Ze([rt()],rF.prototype,"bevelBackStretch",void 0),Ze([rt()],rF.prototype,"radiusTopLeft",void 0),Ze([rt()],rF.prototype,"radiusTopRight",void 0),Ze([rt()],rF.prototype,"radiusBottomLeft",void 0),Ze([rt()],rF.prototype,"radiusBottomRight",void 0),Ze([rt()],rF.prototype,"bulgeEnabled",void 0),Ze([rt()],rF.prototype,"bulgeHeight",void 0),Ze([rt()],rF.prototype,"bulgeRadius",void 0),Ze([rt()],rF.prototype,"sunIntensity",void 0),Ze([rt()],rF.prototype,"sunTheta",void 0),Ze([rt()],rF.prototype,"sunPhi",void 0),Ze([rt()],rF.prototype,"indirectDiffuse",void 0),Ze([rt()],rF.prototype,"albedo",void 0),Ze([rt()],rF.prototype,"specular",void 0),Ze([rt()],rF.prototype,"shininess",void 0),Ze([rt()],rF.prototype,"sharpness",void 0),Ze([rt()],rF.prototype,"subsurface",void 0),Ze([rt()],rF.prototype,"leftGradientColor",void 0),Ze([rt()],rF.prototype,"rightGradientColor",void 0),Ze([rt()],rF.prototype,"reflection",void 0),Ze([rt()],rF.prototype,"frontReflect",void 0),Ze([rt()],rF.prototype,"edgeReflect",void 0),Ze([rt()],rF.prototype,"power",void 0),Ze([rt()],rF.prototype,"skyColor",void 0),Ze([rt()],rF.prototype,"horizonColor",void 0),Ze([rt()],rF.prototype,"groundColor",void 0),Ze([rt()],rF.prototype,"horizonPower",void 0),Ze([rt()],rF.prototype,"width",void 0),Ze([rt()],rF.prototype,"fuzz",void 0),Ze([rt()],rF.prototype,"minFuzz",void 0),Ze([rt()],rF.prototype,"clipFade",void 0),Ze([rt()],rF.prototype,"hueShift",void 0),Ze([rt()],rF.prototype,"saturationShift",void 0),Ze([rt()],rF.prototype,"valueShift",void 0),Ze([rt()],rF.prototype,"blobPosition",void 0),Ze([rt()],rF.prototype,"blobIntensity",void 0),Ze([rt()],rF.prototype,"blobNearSize",void 0),Ze([rt()],rF.prototype,"blobFarSize",void 0),Ze([rt()],rF.prototype,"blobNearDistance",void 0),Ze([rt()],rF.prototype,"blobFarDistance",void 0),Ze([rt()],rF.prototype,"blobFadeLength",void 0),Ze([rt()],rF.prototype,"blobPulse",void 0),Ze([rt()],rF.prototype,"blobFade",void 0),Ze([rt()],rF.prototype,"blobPosition2",void 0),Ze([rt()],rF.prototype,"blobNearSize2",void 0),Ze([rt()],rF.prototype,"blobPulse2",void 0),Ze([rt()],rF.prototype,"blobFade2",void 0),Ze([rt()],rF.prototype,"blobTexture",void 0),Ze([rt()],rF.prototype,"leftIndexPosition",void 0),Ze([rt()],rF.prototype,"rightIndexPosition",void 0),Ze([rt()],rF.prototype,"leftIndexMiddlePosition",void 0),Ze([rt()],rF.prototype,"rightIndexMiddlePosition",void 0),Ze([rt()],rF.prototype,"decalScaleXY",void 0),Ze([rt()],rF.prototype,"decalFrontOnly",void 0),Ze([rt()],rF.prototype,"rimIntensity",void 0),Ze([rt()],rF.prototype,"rimHueShift",void 0),Ze([rt()],rF.prototype,"rimSaturationShift",void 0),Ze([rt()],rF.prototype,"rimValueShift",void 0),Ze([rt()],rF.prototype,"iridescenceIntensity",void 0),z("BABYLON.GUI.MRDLSliderThumbMaterial",rF);Bi.ShadersStore.mrdlBackplatePixelShader="uniform vec3 cameraPosition;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vExtra1;varying vec4 vExtra2;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Filter_Width_;uniform vec4 _Base_Color_;uniform vec4 _Line_Color_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform float _Rate_;uniform vec4 _Highlight_Color_;uniform float _Highlight_Width_;uniform vec4 _Highlight_Transform_;uniform float _Highlight_;uniform float _Iridescence_Intensity_;uniform float _Iridescence_Edge_Intensity_;uniform vec4 _Iridescence_Tint_;uniform sampler2D _Iridescent_Map_;uniform float _Angle_;uniform bool _Reflected_;uniform float _Frequency_;uniform float _Vertical_Offset_;uniform vec4 _Gradient_Color_;uniform vec4 _Top_Left_;uniform vec4 _Top_Right_;uniform vec4 _Bottom_Left_;uniform vec4 _Bottom_Right_;uniform float _Edge_Width_;uniform float _Edge_Power_;uniform float _Line_Gradient_Blend_;uniform float _Fade_Out_;void FastLinearTosRGB_B353(\nvec4 Linear,\nout vec4 sRGB)\n{sRGB.rgb=sqrt(clamp(Linear.rgb,0.0,1.0));sRGB.a=Linear.a;}\nvoid Round_Rect_Fragment_B332(\nfloat Radius,\nfloat Line_Width,\nvec4 Line_Color,\nfloat Filter_Width,\nvec2 UV,\nfloat Line_Visibility,\nvec4 Rect_Parms,\nvec4 Fill_Color,\nout vec4 Color)\n{float d=length(max(abs(UV)-Rect_Parms.xy,0.0));float dx=max(fwidth(d)*Filter_Width,0.00001);float g=min(Rect_Parms.z,Rect_Parms.w);float dgrad=max(fwidth(g)*Filter_Width,0.00001);float Inside_Rect=clamp(g/dgrad,0.0,1.0);float inner=clamp((d+dx*0.5-max(Radius-Line_Width,d-dx*0.5))/dx,0.0,1.0);Color=clamp(mix(Fill_Color,Line_Color,inner),0.0,1.0)*Inside_Rect;}\nvoid Iridescence_B343(\nvec3 Position,\nvec3 Normal,\nvec2 UV,\nvec3 Axis,\nvec3 Eye,\nvec4 Tint,\nsampler2D Texture,\nbool Reflected,\nfloat Frequency,\nfloat Vertical_Offset,\nout vec4 Color)\n{vec3 i=normalize(Position-Eye);vec3 r=reflect(i,Normal);float idota=dot(i,Axis);float idotr=dot(i,r);float x=Reflected ? idotr : idota;vec2 xy;xy.x=fract((x*Frequency+1.0)*0.5+UV.y*Vertical_Offset);xy.y=0.5;Color=texture(Texture,xy);Color.rgb*=Tint.rgb;}\nvoid Scale_RGB_B346(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Scale_RGB_B344(\nfloat Scalar,\nvec4 Color,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Line_Fragment_B362(\nvec4 Base_Color,\nvec4 Highlight_Color,\nfloat Highlight_Width,\nvec3 Line_Vertex,\nfloat Highlight,\nout vec4 Line_Color)\n{float k2=1.0-clamp(abs(Line_Vertex.y/Highlight_Width),0.0,1.0);Line_Color=mix(Base_Color,Highlight_Color,Highlight*k2);}\nvoid Edge_B356(\nvec4 RectParms,\nfloat Radius,\nfloat Line_Width,\nvec2 UV,\nfloat Edge_Width,\nfloat Edge_Power,\nout float Result)\n{float d=length(max(abs(UV)-RectParms.xy,0.0));float edge=1.0-clamp((1.0-d/(Radius-Line_Width))/Edge_Width,0.0,1.0);Result=pow(edge,Edge_Power);}\nvoid Gradient_B355(\nvec4 Gradient_Color,\nvec4 Top_Left,\nvec4 Top_Right,\nvec4 Bottom_Left,\nvec4 Bottom_Right,\nvec2 UV,\nout vec4 Result)\n{vec3 top=Top_Left.rgb+(Top_Right.rgb-Top_Left.rgb)*UV.x;vec3 bottom=Bottom_Left.rgb+(Bottom_Right.rgb-Bottom_Left.rgb)*UV.x;Result.rgb=Gradient_Color.rgb*(bottom+(top-bottom)*UV.y);Result.a=1.0;}\nvoid main()\n{float X_Q338;float Y_Q338;float Z_Q338;float W_Q338;X_Q338=vExtra2.x;Y_Q338=vExtra2.y;Z_Q338=vExtra2.z;W_Q338=vExtra2.w;vec4 Color_Q343;\n#if IRIDESCENCE_ENABLE\nIridescence_B343(vPosition,vNormal,vUV,vBinormal,cameraPosition,_Iridescence_Tint_,_Iridescent_Map_,_Reflected_,_Frequency_,_Vertical_Offset_,Color_Q343);\n#else\nColor_Q343=vec4(0,0,0,0);\n#endif\nvec4 Result_Q344;Scale_RGB_B344(_Iridescence_Intensity_,Color_Q343,Result_Q344);vec4 Line_Color_Q362;Line_Fragment_B362(_Line_Color_,_Highlight_Color_,_Highlight_Width_,vTangent,_Highlight_,Line_Color_Q362);float Result_Q356;\n#if EDGE_ONLY\nEdge_B356(vExtra1,Z_Q338,W_Q338,vUV,_Edge_Width_,_Edge_Power_,Result_Q356);\n#else\nResult_Q356=1.0;\n#endif\nvec2 Vec2_Q339=vec2(X_Q338,Y_Q338);vec4 Result_Q355;Gradient_B355(_Gradient_Color_,_Top_Left_,_Top_Right_,_Bottom_Left_,_Bottom_Right_,Vec2_Q339,Result_Q355);vec4 Linear_Q348;Linear_Q348.rgb=clamp(Result_Q355.rgb*Result_Q355.rgb,0.0,1.0);Linear_Q348.a=Result_Q355.a;vec4 Result_Q346;Scale_RGB_B346(Linear_Q348,Result_Q356,Result_Q346);vec4 Sum_Q345=Result_Q346+Result_Q344;vec4 Color_At_T_Q347=mix(Line_Color_Q362,Result_Q346,_Line_Gradient_Blend_);vec4 Base_And_Iridescent_Q350;Base_And_Iridescent_Q350=_Base_Color_+vec4(Sum_Q345.rgb,0.0);vec4 Sum_Q349=Color_At_T_Q347+_Iridescence_Edge_Intensity_*Color_Q343;vec4 Result_Q351=Sum_Q349; Result_Q351.a=1.0;vec4 Color_Q332;Round_Rect_Fragment_B332(Z_Q338,W_Q338,Result_Q351,_Filter_Width_,vUV,1.0,vExtra1,Base_And_Iridescent_Q350,Color_Q332);vec4 Result_Q354=_Fade_Out_*Color_Q332;vec4 sRGB_Q353;FastLinearTosRGB_B353(Result_Q354,sRGB_Q353);vec4 Out_Color=sRGB_Q353;float Clip_Threshold=0.001;bool To_sRGB=false;gl_FragColor=Out_Color;}";Bi.ShadersStore.mrdlBackplateVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec3 tangent;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Filter_Width_;uniform vec4 _Base_Color_;uniform vec4 _Line_Color_;uniform float _Radius_Top_Left_;uniform float _Radius_Top_Right_;uniform float _Radius_Bottom_Left_;uniform float _Radius_Bottom_Right_;uniform float _Rate_;uniform vec4 _Highlight_Color_;uniform float _Highlight_Width_;uniform vec4 _Highlight_Transform_;uniform float _Highlight_;uniform float _Iridescence_Intensity_;uniform float _Iridescence_Edge_Intensity_;uniform vec4 _Iridescence_Tint_;uniform sampler2D _Iridescent_Map_;uniform float _Angle_;uniform bool _Reflected_;uniform float _Frequency_;uniform float _Vertical_Offset_;uniform vec4 _Gradient_Color_;uniform vec4 _Top_Left_;uniform vec4 _Top_Right_;uniform vec4 _Bottom_Left_;uniform vec4 _Bottom_Right_;uniform float _Edge_Width_;uniform float _Edge_Power_;uniform float _Line_Gradient_Blend_;uniform float _Fade_Out_;varying vec3 vPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec3 vBinormal;varying vec4 vExtra1;varying vec4 vExtra2;void Object_To_World_Pos_B314(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Round_Rect_Vertex_B357(\nvec2 UV,\nfloat Radius,\nfloat Margin,\nfloat Anisotropy,\nfloat Gradient1,\nfloat Gradient2,\nvec3 Normal,\nvec4 Color_Scale_Translate,\nout vec2 Rect_UV,\nout vec4 Rect_Parms,\nout vec2 Scale_XY,\nout vec2 Line_UV,\nout vec2 Color_UV_Info)\n{Scale_XY=vec2(Anisotropy,1.0);Line_UV=(UV-vec2(0.5,0.5));Rect_UV=Line_UV*Scale_XY;Rect_Parms.xy=Scale_XY*0.5-vec2(Radius,Radius)-vec2(Margin,Margin);Rect_Parms.z=Gradient1; \nRect_Parms.w=Gradient2;Color_UV_Info=(Line_UV+vec2(0.5,0.5))*Color_Scale_Translate.xy+Color_Scale_Translate.zw;}\nvoid Line_Vertex_B333(\nvec2 Scale_XY,\nvec2 UV,\nfloat Time,\nfloat Rate,\nvec4 Highlight_Transform,\nout vec3 Line_Vertex)\n{float angle2=(Rate*Time)*2.0*3.1416;float sinAngle2=sin(angle2);float cosAngle2=cos(angle2);vec2 xformUV=UV*Highlight_Transform.xy+Highlight_Transform.zw;Line_Vertex.x=0.0;Line_Vertex.y=cosAngle2*xformUV.x-sinAngle2*xformUV.y;Line_Vertex.z=0.0; }\nvoid PickDir_B334(\nfloat Degrees,\nvec3 DirX,\nvec3 DirY,\nout vec3 Dir)\n{float a=Degrees*3.14159/180.0;Dir=cos(a)*DirX+sin(a)*DirY;}\nvoid Move_Verts_B327(\nfloat Anisotropy,\nvec3 P,\nfloat Radius,\nout vec3 New_P,\nout vec2 New_UV,\nout float Radial_Gradient,\nout vec3 Radial_Dir)\n{vec2 UV=P.xy*2.0+0.5;vec2 center=clamp(UV,0.0,1.0);vec2 delta=UV-center;vec2 r2=2.0*vec2(Radius/Anisotropy,Radius);New_UV=center+r2*(UV-2.0*center+0.5);New_P=vec3(New_UV-0.5,P.z);Radial_Gradient=1.0-length(delta)*2.0;Radial_Dir=vec3(delta*r2,0.0);}\nvoid Pick_Radius_B336(\nfloat Radius,\nfloat Radius_Top_Left,\nfloat Radius_Top_Right,\nfloat Radius_Bottom_Left,\nfloat Radius_Bottom_Right,\nvec3 Position,\nout float Result)\n{bool whichY=Position.y>0.0;Result=Position.x<0.0 ? (whichY ? Radius_Top_Left : Radius_Bottom_Left) : (whichY ? Radius_Top_Right : Radius_Bottom_Right);Result*=Radius;}\nvoid Edge_AA_Vertex_B328(\nvec3 Position_World,\nvec3 Position_Object,\nvec3 Normal_Object,\nvec3 Eye,\nfloat Radial_Gradient,\nvec3 Radial_Dir,\nvec3 Tangent,\nout float Gradient1,\nout float Gradient2)\n{vec3 I=(Eye-Position_World);vec3 T=(vec4(Tangent,0.0)).xyz;float g=(dot(T,I)<0.0) ? 0.0 : 1.0;if (Normal_Object.z==0.0) { \nGradient1=Position_Object.z>0.0 ? g : 1.0;Gradient2=Position_Object.z>0.0 ? 1.0 : g;} else {Gradient1=g+(1.0-g)*(Radial_Gradient);Gradient2=1.0;}}\nvoid Object_To_World_Dir_B330(\nvec3 Dir_Object,\nout vec3 Binormal_World,\nout vec3 Binormal_World_N,\nout float Binormal_Length)\n{Binormal_World=(world*vec4(Dir_Object,0.0)).xyz;Binormal_Length=length(Binormal_World);Binormal_World_N=Binormal_World/Binormal_Length;}\nvoid RelativeOrAbsoluteDetail_B341(\nfloat Nominal_Radius,\nfloat Nominal_LineWidth,\nbool Absolute_Measurements,\nfloat Height,\nout float Radius,\nout float Line_Width)\n{float scale=Absolute_Measurements ? 1.0/Height : 1.0;Radius=Nominal_Radius*scale;Line_Width=Nominal_LineWidth*scale;}\nvoid main()\n{vec3 Nrm_World_Q326;Nrm_World_Q326=normalize((world*vec4(normal,0.0)).xyz);vec3 Tangent_World_Q329;vec3 Tangent_World_N_Q329;float Tangent_Length_Q329;Tangent_World_Q329=(world*vec4(vec3(1,0,0),0.0)).xyz;Tangent_Length_Q329=length(Tangent_World_Q329);Tangent_World_N_Q329=Tangent_World_Q329/Tangent_Length_Q329;vec3 Binormal_World_Q330;vec3 Binormal_World_N_Q330;float Binormal_Length_Q330;Object_To_World_Dir_B330(vec3(0,1,0),Binormal_World_Q330,Binormal_World_N_Q330,Binormal_Length_Q330);float Radius_Q341;float Line_Width_Q341;RelativeOrAbsoluteDetail_B341(_Radius_,_Line_Width_,_Absolute_Sizes_,Binormal_Length_Q330,Radius_Q341,Line_Width_Q341);vec3 Dir_Q334;PickDir_B334(_Angle_,Tangent_World_N_Q329,Binormal_World_N_Q330,Dir_Q334);float Result_Q336;Pick_Radius_B336(Radius_Q341,_Radius_Top_Left_,_Radius_Top_Right_,_Radius_Bottom_Left_,_Radius_Bottom_Right_,position,Result_Q336);float Anisotropy_Q331=Tangent_Length_Q329/Binormal_Length_Q330;vec4 Out_Color_Q337=vec4(Result_Q336,Line_Width_Q341,0,1);vec3 New_P_Q327;vec2 New_UV_Q327;float Radial_Gradient_Q327;vec3 Radial_Dir_Q327;Move_Verts_B327(Anisotropy_Q331,position,Result_Q336,New_P_Q327,New_UV_Q327,Radial_Gradient_Q327,Radial_Dir_Q327);vec3 Pos_World_Q314;Object_To_World_Pos_B314(New_P_Q327,Pos_World_Q314);float Gradient1_Q328;float Gradient2_Q328;\n#if SMOOTH_EDGES\nEdge_AA_Vertex_B328(Pos_World_Q314,position,normal,cameraPosition,Radial_Gradient_Q327,Radial_Dir_Q327,tangent,Gradient1_Q328,Gradient2_Q328);\n#else\nGradient1_Q328=1.0;Gradient2_Q328=1.0;\n#endif\nvec2 Rect_UV_Q357;vec4 Rect_Parms_Q357;vec2 Scale_XY_Q357;vec2 Line_UV_Q357;vec2 Color_UV_Info_Q357;Round_Rect_Vertex_B357(New_UV_Q327,Result_Q336,0.0,Anisotropy_Q331,Gradient1_Q328,Gradient2_Q328,normal,vec4(1,1,0,0),Rect_UV_Q357,Rect_Parms_Q357,Scale_XY_Q357,Line_UV_Q357,Color_UV_Info_Q357);vec3 Line_Vertex_Q333;Line_Vertex_B333(Scale_XY_Q357,Line_UV_Q357,(20.0),_Rate_,_Highlight_Transform_,Line_Vertex_Q333);float X_Q359;float Y_Q359;X_Q359=Color_UV_Info_Q357.x;Y_Q359=Color_UV_Info_Q357.y;vec4 Vec4_Q358=vec4(X_Q359,Y_Q359,Result_Q336,Line_Width_Q341);vec3 Position=Pos_World_Q314;vec3 Normal=Nrm_World_Q326;vec2 UV=Rect_UV_Q357;vec3 Tangent=Line_Vertex_Q333;vec3 Binormal=Dir_Q334;vec4 Color=Out_Color_Q337;vec4 Extra1=Rect_Parms_Q357;vec4 Extra2=Vec4_Q358;vec4 Extra3=vec4(0,0,0,0);gl_Position=viewProjection*vec4(Position,1);vPosition=Position;vNormal=Normal;vUV=UV;vTangent=Tangent;vBinormal=Binormal;vExtra1=Extra1;vExtra2=Extra2;}";class nF extends xl{constructor(){super(),this.IRIDESCENCE_ENABLE=!0,this.SMOOTH_EDGES=!0,this._needNormals=!0,this.rebuild()}}class oF extends ml{constructor(e,t){super(e,t),this.radius=.3,this.lineWidth=.003,this.absoluteSizes=!1,this._filterWidth=1,this.baseColor=new Ae(0,0,0,1),this.lineColor=new Ae(.2,.262745,.4,1),this.radiusTopLeft=1,this.radiusTopRight=1,this.radiusBottomLeft=1,this.radiusBottomRight=1,this._rate=0,this.highlightColor=new Ae(.239216,.435294,.827451,1),this.highlightWidth=0,this._highlightTransform=new pe(1,1,0,0),this._highlight=1,this.iridescenceIntensity=.45,this.iridescenceEdgeIntensity=1,this.iridescenceTint=new Ae(1,1,1,1),this._angle=-45,this.fadeOut=1,this._reflected=!0,this._frequency=1,this._verticalOffset=0,this.gradientColor=new Ae(.74902,.74902,.74902,1),this.topLeftGradientColor=new Ae(.00784314,.294118,.580392,1),this.topRightGradientColor=new Ae(.305882,0,1,1),this.bottomLeftGradientColor=new Ae(.133333,.258824,.992157,1),this.bottomRightGradientColor=new Ae(.176471,.176471,.619608,1),this.edgeWidth=.5,this.edgePower=1,this.edgeLineGradientBlend=.5,this.alphaMode=N_.ALPHA_DISABLE,this.backFaceCulling=!1,this._iridescentMapTexture=new Pa(oF.IRIDESCENT_MAP_TEXTURE_URL,this.getScene(),!0,!1,Pa.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new nF);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="mrdlBackplate",a=s.toString(),l=["world","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Absolute_Sizes_","_Filter_Width_","_Base_Color_","_Line_Color_","_Radius_Top_Left_","_Radius_Top_Right_","_Radius_Bottom_Left_","_Radius_Bottom_Right_","_Rate_","_Highlight_Color_","_Highlight_Width_","_Highlight_Transform_","_Highlight_","_Iridescence_Intensity_","_Iridescence_Edge_Intensity_","_Iridescence_Tint_","_Iridescent_Map_","_Angle_","_Reflected_","_Frequency_","_Vertical_Offset_","_Gradient_Color_","_Top_Left_","_Top_Right_","_Bottom_Left_","_Bottom_Right_","_Edge_Width_","_Edge_Power_","_Line_Gradient_Blend_","_Fade_Out_"],h=["_Iridescent_Map_"],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){if(!i.materialDefines)return;const s=i.effect;s&&(this._activeEffect=s,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",this.getScene().getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",this.getScene().activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Base_Color_",this.baseColor),this._activeEffect.setDirectColor4("_Line_Color_",this.lineColor),this._activeEffect.setFloat("_Radius_Top_Left_",this.radiusTopLeft),this._activeEffect.setFloat("_Radius_Top_Right_",this.radiusTopRight),this._activeEffect.setFloat("_Radius_Bottom_Left_",this.radiusBottomLeft),this._activeEffect.setFloat("_Radius_Bottom_Right_",this.radiusBottomRight),this._activeEffect.setFloat("_Rate_",this._rate),this._activeEffect.setDirectColor4("_Highlight_Color_",this.highlightColor),this._activeEffect.setFloat("_Highlight_Width_",this.highlightWidth),this._activeEffect.setVector4("_Highlight_Transform_",this._highlightTransform),this._activeEffect.setFloat("_Highlight_",this._highlight),this._activeEffect.setFloat("_Iridescence_Intensity_",this.iridescenceIntensity),this._activeEffect.setFloat("_Iridescence_Edge_Intensity_",this.iridescenceEdgeIntensity),this._activeEffect.setDirectColor4("_Iridescence_Tint_",this.iridescenceTint),this._activeEffect.setTexture("_Iridescent_Map_",this._iridescentMapTexture),this._activeEffect.setFloat("_Angle_",this._angle),this._activeEffect.setFloat("_Reflected_",this._reflected?1:0),this._activeEffect.setFloat("_Frequency_",this._frequency),this._activeEffect.setFloat("_Vertical_Offset_",this._verticalOffset),this._activeEffect.setDirectColor4("_Gradient_Color_",this.gradientColor),this._activeEffect.setDirectColor4("_Top_Left_",this.topLeftGradientColor),this._activeEffect.setDirectColor4("_Top_Right_",this.topRightGradientColor),this._activeEffect.setDirectColor4("_Bottom_Left_",this.bottomLeftGradientColor),this._activeEffect.setDirectColor4("_Bottom_Right_",this.bottomRightGradientColor),this._activeEffect.setFloat("_Edge_Width_",this.edgeWidth),this._activeEffect.setFloat("_Edge_Power_",this.edgePower),this._activeEffect.setFloat("_Line_Gradient_Blend_",this.edgeLineGradientBlend),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new oF(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MRDLBackplateMaterial",e}getClassName(){return"MRDLBackplateMaterial"}static Parse(e,t,i){return St.Parse((()=>new oF(e.name,t)),e,t,i)}}oF.IRIDESCENT_MAP_TEXTURE_URL="https://assets.babylonjs.com/meshes/MRTK/MRDL/mrtk-mrdl-backplate-iridescence.png",Ze([rt()],oF.prototype,"radius",void 0),Ze([rt()],oF.prototype,"lineWidth",void 0),Ze([rt()],oF.prototype,"absoluteSizes",void 0),Ze([rt()],oF.prototype,"baseColor",void 0),Ze([rt()],oF.prototype,"lineColor",void 0),Ze([rt()],oF.prototype,"radiusTopLeft",void 0),Ze([rt()],oF.prototype,"radiusTopRight",void 0),Ze([rt()],oF.prototype,"radiusBottomLeft",void 0),Ze([rt()],oF.prototype,"radiusBottomRight",void 0),Ze([rt()],oF.prototype,"highlightColor",void 0),Ze([rt()],oF.prototype,"highlightWidth",void 0),Ze([rt()],oF.prototype,"iridescenceIntensity",void 0),Ze([rt()],oF.prototype,"iridescenceEdgeIntensity",void 0),Ze([rt()],oF.prototype,"iridescenceTint",void 0),Ze([rt()],oF.prototype,"fadeOut",void 0),Ze([rt()],oF.prototype,"gradientColor",void 0),Ze([rt()],oF.prototype,"topLeftGradientColor",void 0),Ze([rt()],oF.prototype,"topRightGradientColor",void 0),Ze([rt()],oF.prototype,"bottomLeftGradientColor",void 0),Ze([rt()],oF.prototype,"bottomRightGradientColor",void 0),Ze([rt()],oF.prototype,"edgeWidth",void 0),Ze([rt()],oF.prototype,"edgePower",void 0),Ze([rt()],oF.prototype,"edgeLineGradientBlend",void 0),z("BABYLON.GUI.MRDLBackplateMaterial",oF);class aF extends CN{constructor(e,t){super(e),this.onValueChangedObservable=new K,this._sliderBackplateVisible=t||!1,this._minimum=0,this._maximum=100,this._step=0,this._value=50}get mesh(){return this.node?this._sliderThumb:null}get minimum(){return this._minimum}set minimum(e){this._minimum!==e&&(this._minimum=Math.max(e,0),this._value=Math.max(Math.min(this._value,this._maximum),this._minimum))}get maximum(){return this._maximum}set maximum(e){this._maximum!==e&&(this._maximum=Math.max(e,this._minimum),this._value=Math.max(Math.min(this._value,this._maximum),this._minimum))}get step(){return this._step}set step(e){this._step!==e&&(this._step=Math.max(Math.min(e,this._maximum-this._minimum),0))}get value(){return this._value}set value(e){this._value!==e&&(this._value=Math.max(Math.min(e,this._maximum),this._minimum),this._sliderThumb&&(this._sliderThumb.position.x=this._convertToPosition(this.value)),this.onValueChangedObservable.notifyObservers(this._value))}get start(){return this.node?this._sliderBar.position.x-this._sliderBar.scaling.x/2:-.5}get end(){return this.node?this._sliderBar.position.x+this._sliderBar.scaling.x/2:.5}get sliderBarMaterial(){return this._sliderBarMaterial}get sliderThumbMaterial(){return this._sliderThumbMaterial}get sliderBackplateMaterial(){return this._sliderBackplateMaterial}get sliderBar(){return this._sliderBar}get sliderThumb(){return this._sliderThumb}get sliderBackplate(){return this._sliderBackplate}set isVisible(e){this._isVisible!==e&&(this._isVisible=e,this.node?.setEnabled(e))}_createNode(e){const t=cd(`${this.name}_sliderbackplate`,{width:1,height:1,depth:1},e);return t.isPickable=!1,t.visibility=0,t.scaling=new _e(1,.5,.8),fl.ImportMeshAsync(void 0,aF.MODEL_BASE_URL,aF.MODEL_FILENAME,e).then((e=>{e.meshes.forEach((e=>{e.isPickable=!1}));const i=e.meshes[1],s=e.meshes[1].clone(`${this.name}_sliderbar`,t),r=e.meshes[1].clone(`${this.name}_sliderthumb`,t);i.visibility=0,this._sliderBackplateVisible&&(i.visibility=1,i.name=`${this.name}_sliderbackplate`,i.scaling.x=1,i.scaling.z=.2,i.parent=t,this._sliderBackplateMaterial&&(i.material=this._sliderBackplateMaterial),this._sliderBackplate=i),s&&(s.parent=t,s.position.z=-.1,s.scaling=new _e(.8,.04,.3),this._sliderBarMaterial&&(s.material=this._sliderBarMaterial),this._sliderBar=s),r&&(r.parent=t,r.isPickable=!0,r.position.z=-.115,r.scaling=new _e(.025,.3,.6),r.position.x=this._convertToPosition(this.value),r.addBehavior(this._createBehavior()),this._sliderThumbMaterial&&(r.material=this._sliderThumbMaterial),this._sliderThumb=r),this._injectGUI3DReservedDataStore(t).control=this,t.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this}))})),this._affectMaterial(t),t}_affectMaterial(e){this._sliderBackplateMaterial=this._sliderBackplateMaterial??new oF(`${this.name}_sliderbackplate_material`,e.getScene()),this._sliderBarMaterial=this._sliderBarMaterial??new iF(`${this.name}_sliderbar_material`,e.getScene()),this._sliderThumbMaterial=this._sliderThumbMaterial??new rF(`${this.name}_sliderthumb_material`,e.getScene())}_createBehavior(){const e=new Xa({dragAxis:_e.Right()});return e.moveAttached=!1,e.onDragStartObservable.add((()=>{this._draggedPosition=this._sliderThumb.position.x})),e.onDragObservable.add((e=>{this._draggedPosition+=e.dragDistance/this.scaling.x,this.value=this._convertToValue(this._draggedPosition)})),e}_convertToPosition(e){const t=(e-this.minimum)/(this.maximum-this.minimum)*(this.end-this.start)+this.start;return Math.min(Math.max(t,this.start),this.end)}_convertToValue(e){let t=(e-this.start)/(this.end-this.start)*(this.maximum-this.minimum);return t=this.step?Math.round(t/this.step)*this.step:t,Math.max(Math.min(this.minimum+t,this._maximum),this._minimum)}dispose(){super.dispose(),this._sliderBar?.dispose(),this._sliderThumb?.dispose(),this._sliderBarMaterial?.dispose(),this._sliderThumbMaterial?.dispose(),this._sliderBackplate?.dispose(),this._sliderBackplateMaterial?.dispose()}}aF.MODEL_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",aF.MODEL_FILENAME="mrtk-fluent-backplate.glb";class lF extends RN{constructor(){super(...arguments),this._radius=5}get radius(){return this._radius}set radius(e){this._radius!==e&&(this._radius=e,Ds.SetImmediate((()=>{this._arrangeChildren()})))}_mapGridNode(e,t){const i=e.mesh;if(!i)return;const s=this._sphericalMapping(t);switch(e.position=s,this.orientation){case IN.FACEORIGIN_ORIENTATION:i.lookAt(new _e(2*s.x,2*s.y,2*s.z));break;case IN.FACEORIGINREVERSED_ORIENTATION:i.lookAt(new _e(-s.x,-s.y,-s.z));break;case IN.FACEFORWARD_ORIENTATION:break;case IN.FACEFORWARDREVERSED_ORIENTATION:i.rotate(Xr.Y,Math.PI,Ur.LOCAL)}}_sphericalMapping(e){const t=new _e(0,0,this._radius),i=e.y/this._radius,s=-e.x/this._radius;return me.RotationYawPitchRollToRef(s,i,0,ve.Matrix[0]),_e.TransformNormal(t,ve.Matrix[0])}}class hF extends IN{get isVertical(){return this._isVertical}set isVertical(e){this._isVertical!==e&&(this._isVertical=e,Ds.SetImmediate((()=>{this._arrangeChildren()})))}constructor(e=!1){super(),this._isVertical=!1,this.margin=.1,this._isVertical=e}_arrangeChildren(){let e=0,t=0,i=0;const s=[],r=me.Invert(this.node.computeWorldMatrix(!0));for(const n of this._children){if(!n.mesh)continue;i++,n.mesh.computeWorldMatrix(!0),n.mesh.getWorldMatrix().multiplyToRef(r,ve.Matrix[0]);const o=n.mesh.getBoundingInfo().boundingBox,a=_e.TransformNormal(o.extendSize,ve.Matrix[0]);s.push(a),this._isVertical?t+=a.y:e+=a.x}let n;this._isVertical?t+=(i-1)*this.margin/2:e+=(i-1)*this.margin/2,n=this._isVertical?-t:-e;let o=0;for(const e of this._children){if(!e.mesh)continue;i--;const t=s[o++];this._isVertical?(e.position.y=n+t.y,e.position.x=0,n+=2*t.y):(e.position.x=n+t.x,e.position.y=0,n+=2*t.x),n+=i>0?this.margin:0}}}class cF extends GN{constructor(e,t){super(t,e),this._currentMesh=e,this.pointerEnterAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1.1)},this.pointerOutAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/1.1)},this.pointerDownAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(.95)},this.pointerUpAnimation=()=>{this.mesh&&this.mesh.scaling.scaleInPlace(1/.95)}}_getTypeName(){return"TouchMeshButton3D"}_createNode(){return this._currentMesh.getChildMeshes().forEach((e=>{this._injectGUI3DReservedDataStore(e).control=this})),this._currentMesh}_affectMaterial(e){}}Bi.ShadersStore.mrdlBackglowPixelShader="uniform vec3 cameraPosition;varying vec3 vNormal;varying vec2 vUV;uniform float _Bevel_Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Tuning_Motion_;uniform float _Motion_;uniform float _Max_Intensity_;uniform float _Intensity_Fade_In_Exponent_;uniform float _Outer_Fuzz_Start_;uniform float _Outer_Fuzz_End_;uniform vec4 _Color_;uniform vec4 _Inner_Color_;uniform float _Blend_Exponent_;uniform float _Falloff_;uniform float _Bias_;float BiasFunc(float b,float v) {return pow(v,log(clamp(b,0.001,0.999))/log(0.5));}\nvoid Fuzzy_Round_Rect_B33(\nfloat Size_X,\nfloat Size_Y,\nfloat Radius_X,\nfloat Radius_Y,\nfloat Line_Width,\nvec2 UV,\nfloat Outer_Fuzz,\nfloat Max_Outer_Fuzz,\nout float Rect_Distance,\nout float Inner_Distance)\n{vec2 halfSize=vec2(Size_X,Size_Y)*0.5;vec2 r=max(min(vec2(Radius_X,Radius_Y),halfSize),vec2(0.001,0.001));float radius=min(r.x,r.y)-Max_Outer_Fuzz;vec2 v=abs(UV);vec2 nearestp=min(v,halfSize-r);float d=distance(nearestp,v);Inner_Distance=clamp(1.0-(radius-d)/Line_Width,0.0,1.0);Rect_Distance=clamp(1.0-(d-radius)/Outer_Fuzz,0.0,1.0)*Inner_Distance;}\nvoid main()\n{float X_Q42;float Y_Q42;X_Q42=vNormal.x;Y_Q42=vNormal.y;float MaxAB_Q24=max(_Tuning_Motion_,_Motion_);float Sqrt_F_Q27=sqrt(MaxAB_Q24);float Power_Q43=pow(MaxAB_Q24,_Intensity_Fade_In_Exponent_);float Value_At_T_Q26=mix(_Outer_Fuzz_Start_,_Outer_Fuzz_End_,Sqrt_F_Q27);float Product_Q23=_Max_Intensity_*Power_Q43;float Rect_Distance_Q33;float Inner_Distance_Q33;Fuzzy_Round_Rect_B33(X_Q42,Y_Q42,_Bevel_Radius_,_Bevel_Radius_,_Line_Width_,vUV,Value_At_T_Q26,_Outer_Fuzz_Start_,Rect_Distance_Q33,Inner_Distance_Q33);float Power_Q44=pow(Inner_Distance_Q33,_Blend_Exponent_);float Result_Q45=pow(BiasFunc(_Bias_,Rect_Distance_Q33),_Falloff_);vec4 Color_At_T_Q25=mix(_Inner_Color_,_Color_,Power_Q44);float Product_Q22=Result_Q45*Product_Q23;vec4 Result_Q28=Product_Q22*Color_At_T_Q25;vec4 Out_Color=Result_Q28;float Clip_Threshold=0.0;gl_FragColor=Out_Color;}";Bi.ShadersStore.mrdlBackglowVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;uniform float _Bevel_Radius_;uniform float _Line_Width_;uniform bool _Absolute_Sizes_;uniform float _Tuning_Motion_;uniform float _Motion_;uniform float _Max_Intensity_;uniform float _Intensity_Fade_In_Exponent_;uniform float _Outer_Fuzz_Start_;uniform float _Outer_Fuzz_End_;uniform vec4 _Color_;uniform vec4 _Inner_Color_;uniform float _Blend_Exponent_;uniform float _Falloff_;uniform float _Bias_;varying vec3 vNormal;varying vec2 vUV;void main()\n{vec3 Dir_World_Q41=(world*vec4(tangent,0.0)).xyz;vec3 Dir_World_Q40=(world*vec4((cross(normal,tangent)),0.0)).xyz;float MaxAB_Q24=max(_Tuning_Motion_,_Motion_);float Length_Q16=length(Dir_World_Q41);float Length_Q17=length(Dir_World_Q40);bool Greater_Than_Q37=MaxAB_Q24>0.0;vec3 Sizes_Q35;vec2 XY_Q35;Sizes_Q35=(_Absolute_Sizes_ ? vec3(Length_Q16,Length_Q17,0) : vec3(Length_Q16/Length_Q17,1,0));XY_Q35=(uv-vec2(0.5,0.5))*Sizes_Q35.xy;vec3 Result_Q38=Greater_Than_Q37 ? position : vec3(0,0,0);vec3 Pos_World_Q39=(world*vec4(Result_Q38,1.0)).xyz;vec3 Position=Pos_World_Q39;vec3 Normal=Sizes_Q35;vec2 UV=XY_Q35;vec3 Tangent=vec3(0,0,0);vec3 Binormal=vec3(0,0,0);vec4 Color=vec4(1,1,1,1);gl_Position=viewProjection*vec4(Position,1);vNormal=Normal;vUV=UV;}";class uF extends xl{constructor(){super(),this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class dF extends ml{constructor(e,t){super(e,t),this.bevelRadius=.16,this.lineWidth=.16,this.absoluteSizes=!1,this.tuningMotion=0,this.motion=1,this.maxIntensity=.7,this.intensityFadeInExponent=2,this.outerFuzzStart=.04,this.outerFuzzEnd=.04,this.color=new Ae(.682353,.698039,1,1),this.innerColor=new Ae(.356863,.392157,.796078,1),this.blendExponent=1.5,this.falloff=2,this.bias=.5,this.alphaMode=N_.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new uF);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="mrdlBackglow",a=s.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Bevel_Radius_","_Line_Width_","_Absolute_Sizes_","_Tuning_Motion_","_Motion_","_Max_Intensity_","_Intensity_Fade_In_Exponent_","_Outer_Fuzz_Start_","_Outer_Fuzz_End_","_Color_","_Inner_Color_","_Blend_Exponent_","_Falloff_","_Bias_"],h=[],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setFloat("_Bevel_Radius_",this.bevelRadius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Absolute_Sizes_",this.absoluteSizes?1:0),this._activeEffect.setFloat("_Tuning_Motion_",this.tuningMotion),this._activeEffect.setFloat("_Motion_",this.motion),this._activeEffect.setFloat("_Max_Intensity_",this.maxIntensity),this._activeEffect.setFloat("_Intensity_Fade_In_Exponent_",this.intensityFadeInExponent),this._activeEffect.setFloat("_Outer_Fuzz_Start_",this.outerFuzzStart),this._activeEffect.setFloat("_Outer_Fuzz_End_",this.outerFuzzEnd),this._activeEffect.setDirectColor4("_Color_",this.color),this._activeEffect.setDirectColor4("_Inner_Color_",this.innerColor),this._activeEffect.setFloat("_Blend_Exponent_",this.blendExponent),this._activeEffect.setFloat("_Falloff_",this.falloff),this._activeEffect.setFloat("_Bias_",this.bias),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new dF(e,this.getScene())),this)}serialize(){const e=St.Serialize(this);return e.customType="BABYLON.MRDLBackglowMaterial",e}getClassName(){return"MRDLBackglowMaterial"}static Parse(e,t,i){return St.Parse((()=>new dF(e.name,t)),e,t,i)}}Ze([rt()],dF.prototype,"bevelRadius",void 0),Ze([rt()],dF.prototype,"lineWidth",void 0),Ze([rt()],dF.prototype,"absoluteSizes",void 0),Ze([rt()],dF.prototype,"tuningMotion",void 0),Ze([rt()],dF.prototype,"motion",void 0),Ze([rt()],dF.prototype,"maxIntensity",void 0),Ze([rt()],dF.prototype,"intensityFadeInExponent",void 0),Ze([rt()],dF.prototype,"outerFuzzStart",void 0),Ze([rt()],dF.prototype,"outerFuzzEnd",void 0),Ze([rt()],dF.prototype,"color",void 0),Ze([rt()],dF.prototype,"innerColor",void 0),Ze([rt()],dF.prototype,"blendExponent",void 0),Ze([rt()],dF.prototype,"falloff",void 0),Ze([rt()],dF.prototype,"bias",void 0),z("BABYLON.GUI.MRDLBackglowMaterial",dF);Bi.ShadersStore.mrdlFrontplatePixelShader="uniform vec3 cameraPosition;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Relative_To_Height_;uniform float _Filter_Width_;uniform vec4 _Edge_Color_;uniform float _Fade_Out_;uniform bool _Smooth_Edges_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform float _Blob_Pulse_Max_Size_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform float _Gaze_Intensity_;uniform float _Gaze_Focus_;uniform sampler2D _Blob_Texture_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform bool _Use_Global_Left_Index_;uniform bool _Use_Global_Right_Index_;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;void Scale_Color_B54(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=Scalar*Color;}\nvoid Scale_RGB_B50(\nvec4 Color,\nfloat Scalar,\nout vec4 Result)\n{Result=vec4(Scalar,Scalar,Scalar,1)*Color;}\nvoid Proximity_Fragment_B51(\nfloat Proximity_Max_Intensity,\nfloat Proximity_Near_Radius,\nvec4 Deltas,\nfloat Show_Selection,\nfloat Distance_Fade1,\nfloat Distance_Fade2,\nfloat Strength,\nout float Proximity)\n{float proximity1=(1.0-clamp(length(Deltas.xy)/Proximity_Near_Radius,0.0,1.0))*Distance_Fade1;float proximity2=(1.0-clamp(length(Deltas.zw)/Proximity_Near_Radius,0.0,1.0))*Distance_Fade2;Proximity=Strength*(Proximity_Max_Intensity*max(proximity1,proximity2) *(1.0-Show_Selection)+Show_Selection);}\nvoid Blob_Fragment_B56(\nvec2 UV,\nvec3 Blob_Info,\nsampler2D Blob_Texture,\nout vec4 Blob_Color)\n{float k=dot(UV,UV);Blob_Color=Blob_Info.y*texture(Blob_Texture,vec2(vec2(sqrt(k),Blob_Info.x).x,1.0-vec2(sqrt(k),Blob_Info.x).y))*(1.0-clamp(k,0.0,1.0));}\nvoid Round_Rect_Fragment_B61(\nfloat Radius,\nvec4 Line_Color,\nfloat Filter_Width,\nfloat Line_Visibility,\nvec4 Fill_Color,\nbool Smooth_Edges,\nvec4 Rect_Parms,\nout float Inside_Rect)\n{float d=length(max(abs(Rect_Parms.zw)-Rect_Parms.xy,0.0));float dx=max(fwidth(d)*Filter_Width,0.00001);Inside_Rect=Smooth_Edges ? clamp((Radius-d)/dx,0.0,1.0) : 1.0-step(Radius,d);}\nvoid main()\n{float Is_Quad_Q53;Is_Quad_Q53=vNormal.z;vec4 Blob_Color_Q56;Blob_Fragment_B56(vUV,vTangent,_Blob_Texture_,Blob_Color_Q56);float X_Q52;float Y_Q52;float Z_Q52;float W_Q52;X_Q52=vExtra3.x;Y_Q52=vExtra3.y;Z_Q52=vExtra3.z;W_Q52=vExtra3.w;float Proximity_Q51;Proximity_Fragment_B51(_Proximity_Max_Intensity_,_Proximity_Near_Radius_,vExtra2,X_Q52,Y_Q52,Z_Q52,1.0,Proximity_Q51);float Inside_Rect_Q61;Round_Rect_Fragment_B61(W_Q52,vec4(1,1,1,1),_Filter_Width_,1.0,vec4(0,0,0,0),_Smooth_Edges_,vExtra1,Inside_Rect_Q61);vec4 Result_Q50;Scale_RGB_B50(_Edge_Color_,Proximity_Q51,Result_Q50);vec4 Result_Q47=Inside_Rect_Q61*Blob_Color_Q56;vec4 Color_At_T_Q48=mix(Result_Q50,Result_Q47,Is_Quad_Q53);vec4 Result_Q54;Scale_Color_B54(Color_At_T_Q48,_Fade_Out_,Result_Q54);vec4 Out_Color=Result_Q54;float Clip_Threshold=0.001;bool To_sRGB=false;gl_FragColor=Out_Color;}";Bi.ShadersStore.mrdlFrontplateVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform float _Radius_;uniform float _Line_Width_;uniform bool _Relative_To_Height_;uniform float _Filter_Width_;uniform vec4 _Edge_Color_;uniform float _Fade_Out_;uniform bool _Smooth_Edges_;uniform bool _Blob_Enable_;uniform vec3 _Blob_Position_;uniform float _Blob_Intensity_;uniform float _Blob_Near_Size_;uniform float _Blob_Far_Size_;uniform float _Blob_Near_Distance_;uniform float _Blob_Far_Distance_;uniform float _Blob_Fade_Length_;uniform float _Blob_Inner_Fade_;uniform float _Blob_Pulse_;uniform float _Blob_Fade_;uniform float _Blob_Pulse_Max_Size_;uniform bool _Blob_Enable_2_;uniform vec3 _Blob_Position_2_;uniform float _Blob_Near_Size_2_;uniform float _Blob_Inner_Fade_2_;uniform float _Blob_Pulse_2_;uniform float _Blob_Fade_2_;uniform float _Gaze_Intensity_;uniform float _Gaze_Focus_;uniform sampler2D _Blob_Texture_;uniform float _Selection_Fuzz_;uniform float _Selected_;uniform float _Selection_Fade_;uniform float _Selection_Fade_Size_;uniform float _Selected_Distance_;uniform float _Selected_Fade_Length_;uniform float _Proximity_Max_Intensity_;uniform float _Proximity_Far_Distance_;uniform float _Proximity_Near_Radius_;uniform float _Proximity_Anisotropy_;uniform bool _Use_Global_Left_Index_;uniform bool _Use_Global_Right_Index_;uniform vec4 Global_Left_Index_Tip_Position;uniform vec4 Global_Right_Index_Tip_Position;varying vec3 vNormal;varying vec2 vUV;varying vec3 vTangent;varying vec4 vExtra1;varying vec4 vExtra2;varying vec4 vExtra3;void Blob_Vertex_B40(\nvec3 Position,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nvec3 Blob_Position,\nfloat Intensity,\nfloat Blob_Near_Size,\nfloat Blob_Far_Size,\nfloat Blob_Near_Distance,\nfloat Blob_Far_Distance,\nvec4 Vx_Color,\nvec2 UV,\nvec3 Face_Center,\nvec2 Face_Size,\nvec2 In_UV,\nfloat Blob_Fade_Length,\nfloat Selection_Fade,\nfloat Selection_Fade_Size,\nfloat Inner_Fade,\nfloat Blob_Pulse,\nfloat Blob_Fade,\nfloat Blob_Enabled,\nfloat DistanceOffset,\nout vec3 Out_Position,\nout vec2 Out_UV,\nout vec3 Blob_Info,\nout vec2 Blob_Relative_UV)\n{float blobSize,fadeIn;vec3 Hit_Position;Blob_Info=vec3(0.0,0.0,0.0);float Hit_Distance=dot(Blob_Position-Face_Center,Normal)+DistanceOffset*Blob_Far_Distance;Hit_Position=Blob_Position-Hit_Distance*Normal;float absD=abs(Hit_Distance);float lerpVal=clamp((absD-Blob_Near_Distance)/(Blob_Far_Distance-Blob_Near_Distance),0.0,1.0);fadeIn=1.0-clamp((absD-Blob_Far_Distance)/Blob_Fade_Length,0.0,1.0);float innerFade=1.0-clamp(-Hit_Distance/Inner_Fade,0.0,1.0);float farClip=clamp(1.0-step(Blob_Far_Distance+Blob_Fade_Length,absD),0.0,1.0);float size=mix(Blob_Near_Size,Blob_Far_Size,lerpVal)*farClip;blobSize=mix(size,Selection_Fade_Size,Selection_Fade)*innerFade*Blob_Enabled;Blob_Info.x=lerpVal*0.5+0.5;Blob_Info.y=fadeIn*Intensity*(1.0-Selection_Fade)*Blob_Fade;Blob_Info.x*=(1.0-Blob_Pulse);vec3 delta=Hit_Position-Face_Center;vec2 blobCenterXY=vec2(dot(delta,Tangent),dot(delta,Bitangent));vec2 quadUVin=2.0*UV-1.0; \nvec2 blobXY=blobCenterXY+quadUVin*blobSize;vec2 blobClipped=clamp(blobXY,-Face_Size*0.5,Face_Size*0.5);vec2 blobUV=(blobClipped-blobCenterXY)/max(blobSize,0.0001)*2.0;vec3 blobCorner=Face_Center+blobClipped.x*Tangent+blobClipped.y*Bitangent;Out_Position=mix(Position,blobCorner,Vx_Color.rrr);Out_UV=mix(In_UV,blobUV,Vx_Color.rr);Blob_Relative_UV=blobClipped/Face_Size.y;}\nvoid Round_Rect_Vertex_B36(\nvec2 UV,\nvec3 Tangent,\nvec3 Binormal,\nfloat Radius,\nfloat Anisotropy,\nvec2 Blob_Center_UV,\nout vec2 Rect_UV,\nout vec2 Scale_XY,\nout vec4 Rect_Parms)\n{Scale_XY=vec2(Anisotropy,1.0);Rect_UV=(UV-vec2(0.5,0.5))*Scale_XY;Rect_Parms.xy=Scale_XY*0.5-vec2(Radius,Radius);Rect_Parms.zw=Blob_Center_UV;}\nvec2 ProjectProximity(\nvec3 blobPosition,\nvec3 position,\nvec3 center,\nvec3 dir,\nvec3 xdir,\nvec3 ydir,\nout float vdistance\n)\n{vec3 delta=blobPosition-position;vec2 xy=vec2(dot(delta,xdir),dot(delta,ydir));vdistance=abs(dot(delta,dir));return xy;}\nvoid Proximity_Vertex_B33(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec3 Position,\nfloat Proximity_Far_Distance,\nfloat Relative_Scale,\nfloat Proximity_Anisotropy,\nvec3 Normal,\nvec3 Tangent,\nvec3 Binormal,\nout vec4 Extra,\nout float Distance_To_Face,\nout float Distance_Fade1,\nout float Distance_Fade2)\n{float distz1,distz2;Extra.xy=ProjectProximity(Blob_Position,Position,Face_Center,Normal,Tangent*Proximity_Anisotropy,Binormal,distz1)/Relative_Scale;Extra.zw=ProjectProximity(Blob_Position_2,Position,Face_Center,Normal,Tangent*Proximity_Anisotropy,Binormal,distz2)/Relative_Scale;Distance_To_Face=dot(Normal,Position-Face_Center);Distance_Fade1=1.0-clamp(distz1/Proximity_Far_Distance,0.0,1.0);Distance_Fade2=1.0-clamp(distz2/Proximity_Far_Distance,0.0,1.0);}\nvoid Object_To_World_Pos_B12(\nvec3 Pos_Object,\nout vec3 Pos_World)\n{Pos_World=(world*vec4(Pos_Object,1.0)).xyz;}\nvoid Choose_Blob_B27(\nvec4 Vx_Color,\nvec3 Position1,\nvec3 Position2,\nbool Blob_Enable_1,\nbool Blob_Enable_2,\nfloat Near_Size_1,\nfloat Near_Size_2,\nfloat Blob_Inner_Fade_1,\nfloat Blob_Inner_Fade_2,\nfloat Blob_Pulse_1,\nfloat Blob_Pulse_2,\nfloat Blob_Fade_1,\nfloat Blob_Fade_2,\nout vec3 Position,\nout float Near_Size,\nout float Inner_Fade,\nout float Blob_Enable,\nout float Fade,\nout float Pulse)\n{Position=Position1*(1.0-Vx_Color.g)+Vx_Color.g*Position2;float b1=Blob_Enable_1 ? 1.0 : 0.0;float b2=Blob_Enable_2 ? 1.0 : 0.0;Blob_Enable=b1+(b2-b1)*Vx_Color.g;Pulse=Blob_Pulse_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Pulse_2;Fade=Blob_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Fade_2;Near_Size=Near_Size_1*(1.0-Vx_Color.g)+Vx_Color.g*Near_Size_2;Inner_Fade=Blob_Inner_Fade_1*(1.0-Vx_Color.g)+Vx_Color.g*Blob_Inner_Fade_2;}\nvoid Move_Verts_B32(\nvec2 UV,\nfloat Radius,\nfloat Anisotropy,\nfloat Line_Width,\nfloat Visible,\nout vec3 New_P,\nout vec2 New_UV)\n{vec2 xy=2.0*UV-vec2(0.5,0.5);vec2 center=clamp(xy,0.0,1.0);vec2 delta=2.0*(xy-center);float deltaLength=length(delta);vec2 aniso=vec2(1.0/Anisotropy,1.0);center=(center-vec2(0.5,0.5))*(1.0-2.0*Radius*aniso);New_UV=vec2((2.0-2.0*deltaLength)*Visible,0.0);float deltaRadius= (Radius-Line_Width*New_UV.x);New_P.xy=(center+deltaRadius/deltaLength *aniso*delta);New_P.z=0.0;}\nvoid Object_To_World_Dir_B14(\nvec3 Dir_Object,\nout vec3 Binormal_World)\n{Binormal_World=(world*vec4(Dir_Object,0.0)).xyz;}\nvoid Proximity_Visibility_B55(\nfloat Selection,\nvec3 Proximity_Center,\nvec3 Proximity_Center_2,\nfloat Proximity_Far_Distance,\nfloat Proximity_Radius,\nvec3 Face_Center,\nvec3 Normal,\nvec2 Face_Size,\nfloat Gaze,\nout float Width)\n{float boxMaxSize=length(Face_Size)*0.5;float d1=dot(Proximity_Center-Face_Center,Normal);vec3 blob1=Proximity_Center-d1*Normal;float d2=dot(Proximity_Center_2-Face_Center,Normal);vec3 blob2=Proximity_Center_2-d2*Normal;vec3 delta1=blob1-Face_Center;vec3 delta2=blob2-Face_Center;float dist1=dot(delta1,delta1);float dist2=dot(delta2,delta2);float nearestProxDist=sqrt(min(dist1,dist2));Width=(1.0-step(boxMaxSize+Proximity_Radius,nearestProxDist))*(1.0-step(Proximity_Far_Distance,min(d1,d2))*(1.0-step(0.0001,Selection)));Width=max(Gaze,Width);}\nvec2 ramp2(vec2 start,vec2 end,vec2 x)\n{return clamp((x-start)/(end-start),vec2(0.0,0.0),vec2(1.0,1.0));}\nfloat computeSelection(\nvec3 blobPosition,\nvec3 normal,\nvec3 tangent,\nvec3 bitangent,\nvec3 faceCenter,\nvec2 faceSize,\nfloat selectionFuzz,\nfloat farDistance,\nfloat fadeLength\n)\n{vec3 delta=blobPosition-faceCenter;float absD=abs(dot(delta,normal));float fadeIn=1.0-clamp((absD-farDistance)/fadeLength,0.0,1.0);vec2 blobCenterXY=vec2(dot(delta,tangent),dot(delta,bitangent));vec2 innerFace=faceSize*(1.0-selectionFuzz)*0.5;vec2 selectPulse=ramp2(-faceSize*0.5,-innerFace,blobCenterXY)-ramp2(innerFace,faceSize*0.5,blobCenterXY);return selectPulse.x*selectPulse.y*fadeIn;}\nvoid Selection_Vertex_B31(\nvec3 Blob_Position,\nvec3 Blob_Position_2,\nvec3 Face_Center,\nvec2 Face_Size,\nvec3 Normal,\nvec3 Tangent,\nvec3 Bitangent,\nfloat Selection_Fuzz,\nfloat Selected,\nfloat Far_Distance,\nfloat Fade_Length,\nvec3 Active_Face_Dir,\nout float Show_Selection)\n{float select1=computeSelection(Blob_Position,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);float select2=computeSelection(Blob_Position_2,Normal,Tangent,Bitangent,Face_Center,Face_Size,Selection_Fuzz,Far_Distance,Fade_Length);Show_Selection=mix(max(select1,select2),1.0,Selected);}\nvoid main()\n{vec3 Vec3_Q29=vec3(vec2(0,0).x,vec2(0,0).y,color.r);vec3 Nrm_World_Q24;Nrm_World_Q24=normalize((world*vec4(normal,0.0)).xyz);vec3 Face_Center_Q30;Face_Center_Q30=(world*vec4(vec3(0,0,0),1.0)).xyz;vec3 Tangent_World_Q13;Tangent_World_Q13=(world*vec4(tangent,0.0)).xyz;vec3 Result_Q42;Result_Q42=_Use_Global_Left_Index_ ? Global_Left_Index_Tip_Position.xyz : _Blob_Position_;vec3 Result_Q43;Result_Q43=_Use_Global_Right_Index_ ? Global_Right_Index_Tip_Position.xyz : _Blob_Position_2_;float Value_At_T_Q58=mix(_Blob_Near_Size_,_Blob_Pulse_Max_Size_,_Blob_Pulse_);float Value_At_T_Q59=mix(_Blob_Near_Size_2_,_Blob_Pulse_Max_Size_,_Blob_Pulse_2_);vec3 Cross_Q70=cross(normal,tangent);float Product_Q45=_Gaze_Intensity_*_Gaze_Focus_;float Step_Q46=step(0.0001,Product_Q45);vec3 Tangent_World_N_Q15=normalize(Tangent_World_Q13);vec3 Position_Q27;float Near_Size_Q27;float Inner_Fade_Q27;float Blob_Enable_Q27;float Fade_Q27;float Pulse_Q27;Choose_Blob_B27(color,Result_Q42,Result_Q43,_Blob_Enable_,_Blob_Enable_2_,Value_At_T_Q58,Value_At_T_Q59,_Blob_Inner_Fade_,_Blob_Inner_Fade_2_,_Blob_Pulse_,_Blob_Pulse_2_,_Blob_Fade_,_Blob_Fade_2_,Position_Q27,Near_Size_Q27,Inner_Fade_Q27,Blob_Enable_Q27,Fade_Q27,Pulse_Q27);vec3 Binormal_World_Q14;Object_To_World_Dir_B14(Cross_Q70,Binormal_World_Q14);float Anisotropy_Q21=length(Tangent_World_Q13)/length(Binormal_World_Q14);vec3 Binormal_World_N_Q16=normalize(Binormal_World_Q14);vec2 Face_Size_Q35;float ScaleY_Q35;Face_Size_Q35=vec2(length(Tangent_World_Q13),length(Binormal_World_Q14));ScaleY_Q35=Face_Size_Q35.y;float Out_Radius_Q38;float Out_Line_Width_Q38;Out_Radius_Q38=_Relative_To_Height_ ? _Radius_ : _Radius_/ScaleY_Q35;Out_Line_Width_Q38=_Relative_To_Height_ ? _Line_Width_ : _Line_Width_/ScaleY_Q35;float Show_Selection_Q31;Selection_Vertex_B31(Result_Q42,Result_Q43,Face_Center_Q30,Face_Size_Q35,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,_Selection_Fuzz_,_Selected_,_Selected_Distance_,_Selected_Fade_Length_,vec3(0,0,-1),Show_Selection_Q31);float MaxAB_Q41=max(Show_Selection_Q31,Product_Q45);float Width_Q55;Proximity_Visibility_B55(Show_Selection_Q31,Result_Q42,Result_Q43,_Proximity_Far_Distance_,_Proximity_Near_Radius_,Face_Center_Q30,Nrm_World_Q24,Face_Size_Q35,Step_Q46,Width_Q55);vec3 New_P_Q32;vec2 New_UV_Q32;Move_Verts_B32(uv,Out_Radius_Q38,Anisotropy_Q21,Out_Line_Width_Q38,Width_Q55,New_P_Q32,New_UV_Q32);vec3 Pos_World_Q12;Object_To_World_Pos_B12(New_P_Q32,Pos_World_Q12);vec3 Out_Position_Q40;vec2 Out_UV_Q40;vec3 Blob_Info_Q40;vec2 Blob_Relative_UV_Q40;Blob_Vertex_B40(Pos_World_Q12,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,Position_Q27,_Blob_Intensity_,Near_Size_Q27,_Blob_Far_Size_,_Blob_Near_Distance_,_Blob_Far_Distance_,color,uv,Face_Center_Q30,Face_Size_Q35,New_UV_Q32,_Blob_Fade_Length_,_Selection_Fade_,_Selection_Fade_Size_,Inner_Fade_Q27,Pulse_Q27,Fade_Q27,Blob_Enable_Q27,0.0,Out_Position_Q40,Out_UV_Q40,Blob_Info_Q40,Blob_Relative_UV_Q40);vec2 Rect_UV_Q36;vec2 Scale_XY_Q36;vec4 Rect_Parms_Q36;Round_Rect_Vertex_B36(New_UV_Q32,Tangent_World_Q13,Binormal_World_Q14,Out_Radius_Q38,Anisotropy_Q21,Blob_Relative_UV_Q40,Rect_UV_Q36,Scale_XY_Q36,Rect_Parms_Q36);vec4 Extra_Q33;float Distance_To_Face_Q33;float Distance_Fade1_Q33;float Distance_Fade2_Q33;Proximity_Vertex_B33(Result_Q42,Result_Q43,Face_Center_Q30,Pos_World_Q12,_Proximity_Far_Distance_,1.0,_Proximity_Anisotropy_,Nrm_World_Q24,Tangent_World_N_Q15,Binormal_World_N_Q16,Extra_Q33,Distance_To_Face_Q33,Distance_Fade1_Q33,Distance_Fade2_Q33);vec4 Vec4_Q37=vec4(MaxAB_Q41,Distance_Fade1_Q33,Distance_Fade2_Q33,Out_Radius_Q38);vec3 Position=Out_Position_Q40;vec3 Normal=Vec3_Q29;vec2 UV=Out_UV_Q40;vec3 Tangent=Blob_Info_Q40;vec3 Binormal=vec3(0,0,0);vec4 Color=vec4(1,1,1,1);vec4 Extra1=Rect_Parms_Q36;vec4 Extra2=Extra_Q33;vec4 Extra3=Vec4_Q37;gl_Position=viewProjection*vec4(Position,1);vNormal=Normal;vUV=UV;vTangent=Tangent;vExtra1=Extra1;vExtra2=Extra2;vExtra3=Extra3;}";class _F extends xl{constructor(){super(),this.SMOOTH_EDGES=!0,this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class pF extends ml{constructor(e,t){super(e,t),this.radius=.12,this.lineWidth=.01,this.relativeToHeight=!1,this._filterWidth=1,this.edgeColor=new Ae(.53,.53,.53,1),this.blobEnable=!0,this.blobPosition=new _e(100,100,100),this.blobIntensity=.5,this.blobNearSize=.032,this.blobFarSize=.048,this.blobNearDistance=.008,this.blobFarDistance=.064,this.blobFadeLength=.04,this.blobInnerFade=.01,this.blobPulse=0,this.blobFade=1,this.blobPulseMaxSize=.05,this.blobEnable2=!0,this.blobPosition2=new _e(10,10.1,-.6),this.blobNearSize2=.008,this.blobInnerFade2=.1,this.blobPulse2=0,this.blobFade2=1,this.gazeIntensity=.8,this.gazeFocus=0,this.selectionFuzz=.5,this.selected=1,this.selectionFade=.2,this.selectionFadeSize=0,this.selectedDistance=.08,this.selectedFadeLength=.08,this.proximityMaxIntensity=.45,this.proximityFarDistance=.16,this.proximityNearRadius=.016,this.proximityAnisotropy=1,this.useGlobalLeftIndex=!0,this.useGlobalRightIndex=!0,this.fadeOut=1,this.alphaMode=N_.ALPHA_ADD,this.disableDepthWrite=!0,this.backFaceCulling=!1,this._blobTexture=new Pa(pF.BLOB_TEXTURE_URL,t,!0,!1,Pa.NEAREST_SAMPLINGMODE)}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new _F);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!1,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="mrdlFrontplate",a=s.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Radius_","_Line_Width_","_Relative_To_Height_","_Filter_Width_","_Edge_Color_","_Fade_Out_","_Smooth_Edges_","_Blob_Enable_","_Blob_Position_","_Blob_Intensity_","_Blob_Near_Size_","_Blob_Far_Size_","_Blob_Near_Distance_","_Blob_Far_Distance_","_Blob_Fade_Length_","_Blob_Inner_Fade_","_Blob_Pulse_","_Blob_Fade_","_Blob_Pulse_Max_Size_","_Blob_Enable_2_","_Blob_Position_2_","_Blob_Near_Size_2_","_Blob_Inner_Fade_2_","_Blob_Pulse_2_","_Blob_Fade_2_","_Gaze_Intensity_","_Gaze_Focus_","_Blob_Texture_","_Selection_Fuzz_","_Selected_","_Selection_Fade_","_Selection_Fade_Size_","_Selected_Distance_","_Selected_Fade_Length_","_Proximity_Max_Intensity_","_Proximity_Far_Distance_","_Proximity_Near_Radius_","_Proximity_Anisotropy_","Global_Left_Index_Tip_Position","Global_Right_Index_Tip_Position","_Use_Global_Left_Index_","_Use_Global_Right_Index_"],h=[],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Line_Width_",this.lineWidth),this._activeEffect.setFloat("_Relative_To_Height_",this.relativeToHeight?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setDirectColor4("_Edge_Color_",this.edgeColor),this._activeEffect.setFloat("_Fade_Out_",this.fadeOut),this._activeEffect.setFloat("_Blob_Enable_",this.blobEnable?1:0),this._activeEffect.setVector3("_Blob_Position_",this.blobPosition),this._activeEffect.setFloat("_Blob_Intensity_",this.blobIntensity),this._activeEffect.setFloat("_Blob_Near_Size_",this.blobNearSize),this._activeEffect.setFloat("_Blob_Far_Size_",this.blobFarSize),this._activeEffect.setFloat("_Blob_Near_Distance_",this.blobNearDistance),this._activeEffect.setFloat("_Blob_Far_Distance_",this.blobFarDistance),this._activeEffect.setFloat("_Blob_Fade_Length_",this.blobFadeLength),this._activeEffect.setFloat("_Blob_Inner_Fade_",this.blobInnerFade),this._activeEffect.setFloat("_Blob_Pulse_",this.blobPulse),this._activeEffect.setFloat("_Blob_Fade_",this.blobFade),this._activeEffect.setFloat("_Blob_Pulse_Max_Size_",this.blobPulseMaxSize),this._activeEffect.setFloat("_Blob_Enable_2_",this.blobEnable2?1:0),this._activeEffect.setVector3("_Blob_Position_2_",this.blobPosition2),this._activeEffect.setFloat("_Blob_Near_Size_2_",this.blobNearSize2),this._activeEffect.setFloat("_Blob_Inner_Fade_2_",this.blobInnerFade2),this._activeEffect.setFloat("_Blob_Pulse_2_",this.blobPulse2),this._activeEffect.setFloat("_Blob_Fade_2_",this.blobFade2),this._activeEffect.setFloat("_Gaze_Intensity_",this.gazeIntensity),this._activeEffect.setFloat("_Gaze_Focus_",this.gazeFocus),this._activeEffect.setTexture("_Blob_Texture_",this._blobTexture),this._activeEffect.setFloat("_Selection_Fuzz_",this.selectionFuzz),this._activeEffect.setFloat("_Selected_",this.selected),this._activeEffect.setFloat("_Selection_Fade_",this.selectionFade),this._activeEffect.setFloat("_Selection_Fade_Size_",this.selectionFadeSize),this._activeEffect.setFloat("_Selected_Distance_",this.selectedDistance),this._activeEffect.setFloat("_Selected_Fade_Length_",this.selectedFadeLength),this._activeEffect.setFloat("_Proximity_Max_Intensity_",this.proximityMaxIntensity),this._activeEffect.setFloat("_Proximity_Far_Distance_",this.proximityFarDistance),this._activeEffect.setFloat("_Proximity_Near_Radius_",this.proximityNearRadius),this._activeEffect.setFloat("_Proximity_Anisotropy_",this.proximityAnisotropy),this._activeEffect.setFloat("_Use_Global_Left_Index_",this.useGlobalLeftIndex?1:0),this._activeEffect.setFloat("_Use_Global_Right_Index_",this.useGlobalRightIndex?1:0),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new pF(e,this.getScene())),this)}serialize(){const e=St.Serialize(this);return e.customType="BABYLON.MRDLFrontplateMaterial",e}getClassName(){return"MRDLFrontplateMaterial"}static Parse(e,t,i){return St.Parse((()=>new pF(e.name,t)),e,t,i)}}pF.BLOB_TEXTURE_URL="",Ze([rt()],pF.prototype,"radius",void 0),Ze([rt()],pF.prototype,"lineWidth",void 0),Ze([rt()],pF.prototype,"relativeToHeight",void 0),Ze([rt()],pF.prototype,"edgeColor",void 0),Ze([rt()],pF.prototype,"blobEnable",void 0),Ze([rt()],pF.prototype,"blobPosition",void 0),Ze([rt()],pF.prototype,"blobIntensity",void 0),Ze([rt()],pF.prototype,"blobNearSize",void 0),Ze([rt()],pF.prototype,"blobFarSize",void 0),Ze([rt()],pF.prototype,"blobNearDistance",void 0),Ze([rt()],pF.prototype,"blobFarDistance",void 0),Ze([rt()],pF.prototype,"blobFadeLength",void 0),Ze([rt()],pF.prototype,"blobInnerFade",void 0),Ze([rt()],pF.prototype,"blobPulse",void 0),Ze([rt()],pF.prototype,"blobFade",void 0),Ze([rt()],pF.prototype,"blobPulseMaxSize",void 0),Ze([rt()],pF.prototype,"blobEnable2",void 0),Ze([rt()],pF.prototype,"blobPosition2",void 0),Ze([rt()],pF.prototype,"blobNearSize2",void 0),Ze([rt()],pF.prototype,"blobInnerFade2",void 0),Ze([rt()],pF.prototype,"blobPulse2",void 0),Ze([rt()],pF.prototype,"blobFade2",void 0),Ze([rt()],pF.prototype,"gazeIntensity",void 0),Ze([rt()],pF.prototype,"gazeFocus",void 0),Ze([rt()],pF.prototype,"selectionFuzz",void 0),Ze([rt()],pF.prototype,"selected",void 0),Ze([rt()],pF.prototype,"selectionFade",void 0),Ze([rt()],pF.prototype,"selectionFadeSize",void 0),Ze([rt()],pF.prototype,"selectedDistance",void 0),Ze([rt()],pF.prototype,"selectedFadeLength",void 0),Ze([rt()],pF.prototype,"proximityMaxIntensity",void 0),Ze([rt()],pF.prototype,"proximityFarDistance",void 0),Ze([rt()],pF.prototype,"proximityNearRadius",void 0),Ze([rt()],pF.prototype,"proximityAnisotropy",void 0),Ze([rt()],pF.prototype,"useGlobalLeftIndex",void 0),Ze([rt()],pF.prototype,"useGlobalRightIndex",void 0),z("BABYLON.GUI.MRDLFrontplateMaterial",pF);Bi.ShadersStore.mrdlInnerquadPixelShader="uniform vec3 cameraPosition;varying vec2 vUV;varying vec3 vTangent;uniform vec4 _Color_;uniform float _Radius_;uniform bool _Fixed_Radius_;uniform float _Filter_Width_;uniform float _Glow_Fraction_;uniform float _Glow_Max_;uniform float _Glow_Falloff_;float FilterStep_Bid194(float edge,float x,float filterWidth)\n{float dx=max(1.0E-5,fwidth(x)*filterWidth);return max((x+dx*0.5-max(edge,x-dx*0.5))/dx,0.0);}\nvoid Round_Rect_B194(\nfloat Size_X,\nfloat Size_Y,\nfloat Radius,\nvec4 Rect_Color,\nfloat Filter_Width,\nvec2 UV,\nfloat Glow_Fraction,\nfloat Glow_Max,\nfloat Glow_Falloff,\nout vec4 Color)\n{vec2 halfSize=vec2(Size_X,Size_Y)*0.5;vec2 r=max(min(vec2(Radius,Radius),halfSize),vec2(0.01,0.01));vec2 v=abs(UV);vec2 nearestp=min(v,halfSize-r);vec2 delta=(v-nearestp)/max(vec2(0.01,0.01),r);float Distance=length(delta);float insideRect=1.0-FilterStep_Bid194(1.0-Glow_Fraction,Distance,Filter_Width);float glow=clamp((1.0-Distance)/Glow_Fraction,0.0,1.0);glow=pow(glow,Glow_Falloff);Color=Rect_Color*max(insideRect,glow*Glow_Max);}\nvoid main()\n{float X_Q192;float Y_Q192;float Z_Q192;X_Q192=vTangent.x;Y_Q192=vTangent.y;Z_Q192=vTangent.z;vec4 Color_Q194;Round_Rect_B194(X_Q192,1.0,Y_Q192,_Color_,_Filter_Width_,vUV,_Glow_Fraction_,_Glow_Max_,_Glow_Falloff_,Color_Q194);vec4 Out_Color=Color_Q194;float Clip_Threshold=0.0;gl_FragColor=Out_Color;}\n";Bi.ShadersStore.mrdlInnerquadVertexShader="uniform mat4 world;uniform mat4 viewProjection;uniform vec3 cameraPosition;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;attribute vec3 tangent;attribute vec4 color;uniform vec4 _Color_;uniform float _Radius_;uniform bool _Fixed_Radius_;uniform float _Filter_Width_;uniform float _Glow_Fraction_;uniform float _Glow_Max_;uniform float _Glow_Falloff_;varying vec2 vUV;varying vec3 vTangent;void main()\n{vec3 Pos_World_Q189;Pos_World_Q189=(world*vec4(position,1.0)).xyz;vec3 Dir_World_Q190;Dir_World_Q190=(world*vec4(tangent,0.0)).xyz;vec3 Dir_World_Q191;Dir_World_Q191=(world*vec4((cross(normal,tangent)),0.0)).xyz;float Length_Q180=length(Dir_World_Q190);float Length_Q181=length(Dir_World_Q191);float Quotient_Q184=Length_Q180/Length_Q181;float Quotient_Q195=_Radius_/Length_Q181;vec2 Result_Q193;Result_Q193=vec2((uv.x-0.5)*Length_Q180/Length_Q181,(uv.y-0.5));float Result_Q198=_Fixed_Radius_ ? Quotient_Q195 : _Radius_;vec3 Vec3_Q183=vec3(Quotient_Q184,Result_Q198,0);vec3 Position=Pos_World_Q189;vec3 Normal=vec3(0,0,0);vec2 UV=Result_Q193;vec3 Tangent=Vec3_Q183;vec3 Binormal=vec3(0,0,0);vec4 Color=color;gl_Position=viewProjection*vec4(Position,1);vUV=UV;vTangent=Tangent;}\n";class fF extends xl{constructor(){super(),this._needNormals=!0,this._needUVs=!0,this.rebuild()}}class mF extends ml{constructor(e,t){super(e,t),this.color=new Ae(1,1,1,.05),this.radius=.12,this.fixedRadius=!0,this._filterWidth=1,this.glowFraction=0,this.glowMax=.5,this.glowFalloff=2,this.alphaMode=N_.ALPHA_COMBINE,this.backFaceCulling=!1}needAlphaBlending(){return!0}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new fF);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;const n=r.getEngine();if(jo(e,s,!0,!1),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),Vo(s,e),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess;const i=[er.PositionKind];s.NORMAL&&i.push(er.NormalKind),s.UV1&&i.push(er.UVKind),s.UV2&&i.push(er.UV2Kind),s.VERTEXCOLOR&&i.push(er.ColorKind),s.TANGENT&&i.push(er.TangentKind),ko(i,s);const o="mrdlInnerquad",a=s.toString(),l=["world","worldView","worldViewProjection","view","projection","viewProjection","cameraPosition","_Color_","_Radius_","_Fixed_Radius_","_Filter_Width_","_Glow_Fraction_","_Glow_Max_","_Glow_Falloff_"],h=[],c=[];ea({uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:s,maxSimultaneousLights:4}),t.setEffect(r.getEngine().createEffect(o,{attributes:i,uniformsNames:l,uniformBuffersNames:c,samplers:h,defines:a,fallbacks:e,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},n),s)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene();if(!i.materialDefines)return;const r=i.effect;r&&(this._activeEffect=r,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._activeEffect.setVector3("cameraPosition",s.activeCamera.position),this._activeEffect.setDirectColor4("_Color_",this.color),this._activeEffect.setFloat("_Radius_",this.radius),this._activeEffect.setFloat("_Fixed_Radius_",this.fixedRadius?1:0),this._activeEffect.setFloat("_Filter_Width_",this._filterWidth),this._activeEffect.setFloat("_Glow_Fraction_",this.glowFraction),this._activeEffect.setFloat("_Glow_Max_",this.glowMax),this._activeEffect.setFloat("_Glow_Falloff_",this.glowFalloff),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new mF(e,this.getScene())),this)}serialize(){const e=St.Serialize(this);return e.customType="BABYLON.MRDLInnerquadMaterial",e}getClassName(){return"MRDLInnerquadMaterial"}static Parse(e,t,i){return St.Parse((()=>new mF(e.name,t)),e,t,i)}}Ze([rt()],mF.prototype,"color",void 0),Ze([rt()],mF.prototype,"radius",void 0),Ze([rt()],mF.prototype,"fixedRadius",void 0),Ze([rt()],mF.prototype,"glowFraction",void 0),Ze([rt()],mF.prototype,"glowMax",void 0),Ze([rt()],mF.prototype,"glowFalloff",void 0),z("BABYLON.GUI.MRDLInnerquadMaterial",mF);class gF extends GN{_disposeTooltip(){this._tooltipFade=null,this._tooltipTextBlock&&this._tooltipTextBlock.dispose(),this._tooltipTexture&&this._tooltipTexture.dispose(),this._tooltipMesh&&this._tooltipMesh.dispose(),this.onPointerEnterObservable.remove(this._tooltipHoverObserver),this.onPointerOutObservable.remove(this._tooltipOutObserver)}set renderingGroupId(e){this._backPlate.renderingGroupId=e,this._textPlate.renderingGroupId=e,this._frontPlate.renderingGroupId=e,this._backGlow.renderingGroupId=e,this._innerQuad.renderingGroupId=e,this._tooltipMesh&&(this._tooltipMesh.renderingGroupId=e)}get renderingGroupId(){return this._backPlate.renderingGroupId}get mesh(){return this._backPlate}set tooltipText(e){if(e){if(!this._tooltipFade){const e=this._backPlate._scene.useRightHandedSystem;this._tooltipMesh=Wa("",{size:1},this._backPlate._scene),this._tooltipMesh.position=_e.Down().scale(.7).add(_e.Forward(e).scale(-.15)),this._tooltipMesh.isPickable=!1,this._tooltipMesh.parent=this._frontPlateCollisionMesh,this._tooltipTexture=xN.CreateForMesh(this._tooltipMesh);const t=new ww;t.height=.25,t.width=.8,t.cornerRadius=25,t.color="#ffffff",t.thickness=20,t.background="#060668",this._tooltipTexture.addControl(t),this._tooltipTextBlock=new Fw,this._tooltipTextBlock.color="white",this._tooltipTextBlock.fontSize=100,this._tooltipTexture.addControl(this._tooltipTextBlock),this._tooltipFade=new Va,this._tooltipFade.delay=500,this._tooltipMesh.addBehavior(this._tooltipFade),this._tooltipHoverObserver=this.onPointerEnterObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!0)})),this._tooltipOutObserver=this.onPointerOutObservable.add((()=>{this._tooltipFade&&this._tooltipFade.fadeIn(!1)}))}this._tooltipTextBlock&&(this._tooltipTextBlock.text=e)}else this._disposeTooltip()}get tooltipText(){return this._tooltipTextBlock?.text||null}get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this._rebuildContent())}get subtext(){return this._subtext}set subtext(e){this._subtext!==e&&(this._subtext=e,this._rebuildContent())}get imageUrl(){return this._imageUrl}set imageUrl(e){this._imageUrl!==e&&(this._imageUrl=e,this._rebuildContent())}get backMaterial(){return this._backMaterial}get frontMaterial(){return this._frontMaterial}get backGlowMaterial(){return this._backGlowMaterial}get innerQuadMaterial(){return this._innerQuadMaterial}get plateMaterial(){return this._plateMaterial}get shareMaterials(){return this._shareMaterials}set isBackplateVisible(e){this.mesh&&this._backMaterial&&(e&&!this._isBackplateVisible?this._backPlate.visibility=1:!e&&this._isBackplateVisible&&(this._backPlate.visibility=0)),this._isBackplateVisible=e}constructor(e,t=!0){super(e),this.width=1,this.height=1,this.radius=.14,this.textSizeInPixels=18,this.imageSizeInPixels=40,this.plateMaterialColor=new Ee(.4,.4,.4),this.frontPlateDepth=.2,this.backPlateDepth=.04,this.backGlowOffset=.1,this.flatPlaneDepth=.001,this.innerQuadRadius=this.radius-.04,this.innerQuadColor=new Ae(0,0,0,0),this.innerQuadToggledColor=new Ae(.5197843,.6485234,.9607843,.6),this.innerQuadHoverColor=new Ae(1,1,1,.05),this.innerQuadToggledHoverColor=new Ae(.5197843,.6485234,.9607843,1),this._isBackplateVisible=!0,this._shareMaterials=!0,this._shareMaterials=t,this.pointerEnterAnimation=()=>{this._frontPlate&&this._textPlate&&!this.isToggleButton&&this._performEnterExitAnimation(1),this.isToggleButton&&this._innerQuadMaterial&&(this.isToggled?this._innerQuadMaterial.color=this.innerQuadToggledHoverColor:this._innerQuadMaterial.color=this.innerQuadHoverColor)},this.pointerOutAnimation=()=>{this._frontPlate&&this._textPlate&&!this.isToggleButton&&this._performEnterExitAnimation(-.8),this.isToggleButton&&this._innerQuadMaterial&&this._onToggle(this.isToggled)},this.pointerDownAnimation=()=>{},this.pointerUpAnimation=()=>{},this._pointerClickObserver=this.onPointerClickObservable.add((()=>{this._frontPlate&&this._backGlow&&!this.isActiveNearInteraction&&this._performClickAnimation(),this.isToggleButton&&this._innerQuadMaterial&&this._onToggle(this.isToggled)})),this._pointerEnterObserver=this.onPointerEnterObservable.add((()=>{this.pointerEnterAnimation()})),this._pointerOutObserver=this.onPointerOutObservable.add((()=>{this.pointerOutAnimation()})),this._toggleObserver=this.onToggleObservable.add((e=>{this._innerQuadMaterial.color=e?this.innerQuadToggledColor:this.innerQuadColor}))}_getTypeName(){return"TouchHolographicButton"}_rebuildContent(){let e;e=this._getAspectRatio()<=1?this._alignContentVertically():this._alignContentHorizontally(),this.content=e}_getAspectRatio(){return this.width/this.height}_alignContentVertically(){const e=new kw;if(e.isVertical=!0,Ut()&&document.createElement&&this._imageUrl){const t=new Lw;t.source=this._imageUrl,t.heightInPixels=180,t.widthInPixels=100,t.paddingTopInPixels=40,t.paddingBottomInPixels=40,e.addControl(t)}if(this._text){const t=new Fw;t.text=this._text,t.color="white",t.heightInPixels=30,t.fontSize=24,e.addControl(t)}return e}_alignContentHorizontally(){let e=240;const t=15,i=new ww;i.widthInPixels=e,i.heightInPixels=e,i.color="transparent",i.setPaddingInPixels(t,t,t,t),e-=30;const s=new kw;if(s.isVertical=!1,s.scaleY=this._getAspectRatio(),Ut()&&document.createElement&&this._imageUrl){const t=new ww(`${this.name}_image`);t.widthInPixels=this.imageSizeInPixels,t.heightInPixels=this.imageSizeInPixels,t.color="transparent",e-=this.imageSizeInPixels;const i=new Lw;i.source=this._imageUrl,t.addControl(i),s.addControl(t)}if(this._text){const i=new Fw(`${this.name}_text`);if(i.text=this._text,i.color="white",i.fontSize=this.textSizeInPixels,i.widthInPixels=e,this._imageUrl&&(i.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,i.paddingLeftInPixels=t),this._subtext){const r=new zw;r.addColumnDefinition(1),r.addRowDefinition(.5),r.addRowDefinition(.5),r.widthInPixels=e,r.heightInPixels=45;const n=new Fw(`${this.name}_subtext`);n.text=this._subtext,n.color="#EEEEEEAB",n.fontSize=.75*this.textSizeInPixels,n.fontWeight="600",this._imageUrl&&(n.textHorizontalAlignment=Ow.HORIZONTAL_ALIGNMENT_LEFT,n.paddingLeftInPixels=t),r.addControl(i,0),r.addControl(n,1),s.addControl(r)}else s.addControl(i)}return i.addControl(s),i}_createNode(e){this.name=this.name??"TouchHolographicButton";const t=this._createBackPlate(e),i=this._createFrontPlate(e),s=this._createInnerQuad(e),r=this._createBackGlow(e);this._frontPlateCollisionMesh=i,this._textPlate=super._createNode(e),this._textPlate.name=`${this.name}_textPlate`,this._textPlate.isPickable=!1,this._textPlate.scaling.x=this.width,this._textPlate.parent=i,this._backPlate=t,this._backPlate.position=_e.Forward(e.useRightHandedSystem).scale(this.backPlateDepth/2),this._backPlate.isPickable=!1,this._backPlate.addChild(i),this._backPlate.addChild(s),r&&this._backPlate.addChild(r);const n=new lo(`${this.name}_root`,e);return this._backPlate.setParent(n),this.collisionMesh=i,this.collidableFrontDirection=this._backPlate.forward.negate(),n}_createBackPlate(e){const t=cd(`${this.name}_backPlate`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=.2,fl.ImportMeshAsync(void 0,gF.MRTK_ASSET_BASE_URL,gF.BACKPLATE_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.visibility=0,this._isBackplateVisible&&(i.visibility=1,i.name=`${this.name}_backPlate`,i.isPickable=!1,i.scaling.x=this.width,i.scaling.y=this.height,i.parent=t),this._backMaterial&&(i.material=this._backMaterial),this._backPlate=i})),t}_createFrontPlate(e){const t=cd(`${this.name}_frontPlate`,{width:this.width,height:this.height,depth:this.frontPlateDepth},e);return t.isPickable=!0,t.isNearPickable=!0,t.visibility=0,t.position=_e.Forward(e.useRightHandedSystem).scale((this.backPlateDepth-this.frontPlateDepth)/2),fl.ImportMeshAsync(void 0,gF.MRTK_ASSET_BASE_URL,gF.FRONTPLATE_MODEL_FILENAME,e).then((i=>{const s=cd(`${this.name}_collisionPlate`,{width:this.width,height:this.height},e);s.isPickable=!1,s.scaling.z=this.frontPlateDepth,s.visibility=0,s.parent=t,this._collisionPlate=s;const r=i.meshes[1];r.name=`${this.name}_frontPlate`,r.isPickable=!1,r.scaling.x=this.width-this.backGlowOffset,r.scaling.y=this.height-this.backGlowOffset,r.position=_e.Forward(e.useRightHandedSystem).scale(-.5),r.parent=s,this.isToggleButton&&(r.visibility=0),this._frontMaterial&&(r.material=this._frontMaterial),this._textPlate.scaling.x=1,this._textPlate.parent=r,this._frontPlate=r})),t}_createInnerQuad(e){const t=cd(`${this.name}_innerQuad`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=this.flatPlaneDepth,t.position.z+=this.backPlateDepth/2-this.flatPlaneDepth,fl.ImportMeshAsync(void 0,gF.MRTK_ASSET_BASE_URL,gF.INNERQUAD_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_innerQuad`,i.isPickable=!1,i.scaling.x=this.width-this.backGlowOffset,i.scaling.y=this.height-this.backGlowOffset,i.parent=t,this._innerQuadMaterial&&(i.material=this._innerQuadMaterial),this._innerQuad=i})),t}_createBackGlow(e){if(this.isToggleButton)return;const t=cd(`${this.name}_backGlow`,{},e);return t.isPickable=!1,t.visibility=0,t.scaling.z=this.flatPlaneDepth,t.position.z+=this.backPlateDepth/2-2*this.flatPlaneDepth,fl.ImportMeshAsync(void 0,gF.MRTK_ASSET_BASE_URL,gF.BACKGLOW_MODEL_FILENAME,e).then((e=>{const i=e.meshes[1];i.name=`${this.name}_backGlow`,i.isPickable=!1,i.scaling.x=this.width-this.backGlowOffset,i.scaling.y=this.height-this.backGlowOffset,i.parent=t,this._backGlowMaterial&&(i.material=this._backGlowMaterial),this._backGlow=i})),t}_applyFacade(e){this._plateMaterial.emissiveTexture=e,this._plateMaterial.opacityTexture=e,this._plateMaterial.diffuseColor=this.plateMaterialColor}_performClickAnimation(){const e=new gn("Click Animation Group"),t=[{name:"backGlowMotion",mesh:this._backGlow,property:"material.motion",keys:[{frame:0,values:[0,0,0]},{frame:20,values:[1,.0144,.0144]},{frame:40,values:[.0027713229489760476,0,0]},{frame:45,values:[.0027713229489760476]}]},{name:"_collisionPlateZSlide",mesh:this._collisionPlate,property:"position.z",keys:[{frame:0,values:[0,0,0]},{frame:20,values:[_e.Forward(this._collisionPlate._scene.useRightHandedSystem).scale(this.frontPlateDepth/2).z,0,0]},{frame:40,values:[0,.005403332496794331]},{frame:45,values:[0]}]},{name:"_collisionPlateZScale",mesh:this._collisionPlate,property:"scaling.z",keys:[{frame:0,values:[this.frontPlateDepth,0,0]},{frame:20,values:[this.backPlateDepth,0,0]},{frame:40,values:[this.frontPlateDepth,.0054]},{frame:45,values:[this.frontPlateDepth]}]}];for(const i of t){const t=new Ft(i.name,i.property,60,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CYCLE),s=[];for(const e of i.keys)s.push({frame:e.frame,value:e.values[0],inTangent:e.values[1],outTangent:e.values[2],interpolation:e.values[3]});t.setKeys(s),i.mesh&&e.addTargetedAnimation(t,i.mesh)}e.normalize(0,45),e.speedRatio=1,e.play()}_performEnterExitAnimation(e){const t=new gn("Enter Exit Animation Group"),i=[{name:"frontPlateFadeOut",mesh:this._frontPlate,property:"material.fadeOut",keys:[{frame:0,values:[0,0,.025045314830017686,0]},{frame:40,values:[1.00205599570012,.025045314830017686,0,0]}]},{name:"textPlateZSlide",mesh:this._textPlate,property:"position.z",keys:[{frame:0,values:[0,0,0]},{frame:40,values:[_e.Forward(this._textPlate._scene.useRightHandedSystem).scale(-.15).z,0,0]}]}];for(const e of i){const i=new Ft(e.name,e.property,60,Ft.ANIMATIONTYPE_FLOAT,Ft.ANIMATIONLOOPMODE_CYCLE),s=[];for(const t of e.keys)s.push({frame:t.frame,value:t.values[0],inTangent:t.values[1],outTangent:t.values[2],interpolation:t.values[3]});i.setKeys(s),e.mesh&&t.addTargetedAnimation(i,e.mesh)}t.normalize(0,45),t.speedRatio=e,t.play()}_createBackMaterial(e){this._backMaterial=this._backMaterial??new oF(this.name+"backPlateMaterial",e.getScene()),this._backMaterial.absoluteSizes=!0,this._backMaterial.radius=this.radius,this._backMaterial.lineWidth=.02}_createFrontMaterial(e){this._frontMaterial=this._frontMaterial??new pF(this.name+"Front Material",e.getScene()),this.frontMaterial.radius=this.innerQuadRadius,this.frontMaterial.fadeOut=0}_createBackGlowMaterial(e){const t=this.radius+.04;this._backGlowMaterial=this._backGlowMaterial??new dF(this.name+"Back Glow Material",e.getScene()),this._backGlowMaterial.bevelRadius=t,this._backGlowMaterial.lineWidth=t,this._backGlowMaterial.motion=0}_createInnerQuadMaterial(e){this._innerQuadMaterial=this._innerQuadMaterial??new mF("inner_quad",e.getScene()),this._innerQuadMaterial.radius=this.innerQuadRadius,this.isToggleButton&&(this._innerQuadMaterial.color=this.innerQuadColor)}_createPlateMaterial(e){this._plateMaterial=this._plateMaterial??new cu(this.name+"Plate Material",e.getScene()),this._plateMaterial.specularColor=Ee.Black()}_onToggle(e){super._onToggle(e)}_affectMaterial(e){this._shareMaterials?(this._host._touchSharedMaterials.mrdlBackplateMaterial?this._backMaterial=this._host._touchSharedMaterials.mrdlBackplateMaterial:(this._createBackMaterial(e),this._host._touchSharedMaterials.mrdlBackplateMaterial=this._backMaterial),this._host._touchSharedMaterials.mrdlFrontplateMaterial?this._frontMaterial=this._host._touchSharedMaterials.mrdlFrontplateMaterial:(this._createFrontMaterial(e),this._host._touchSharedMaterials.mrdlFrontplateMaterial=this._frontMaterial),this._host._touchSharedMaterials.mrdlBackglowMaterial?this._backGlowMaterial=this._host._touchSharedMaterials.mrdlBackglowMaterial:(this._createBackGlowMaterial(e),this._host._touchSharedMaterials.mrdlBackglowMaterial=this._backGlowMaterial),this._host._touchSharedMaterials.mrdlInnerQuadMaterial?this._innerQuadMaterial=this._host._touchSharedMaterials.mrdlInnerQuadMaterial:(this._createInnerQuadMaterial(e),this._host._touchSharedMaterials.mrdlInnerQuadMaterial=this._innerQuadMaterial)):(this._createBackMaterial(e),this._createFrontMaterial(e),this._createBackGlowMaterial(e),this._createInnerQuadMaterial(e)),this._createPlateMaterial(e),this._backPlate.material=this._backMaterial,this._textPlate.material=this._plateMaterial,this._isBackplateVisible||(this._backPlate.visibility=0),this._frontPlate&&(this._frontPlate.material=this._frontMaterial),this._backGlow&&(this._backGlow.material=this._backGlowMaterial),this._innerQuad&&(this._innerQuad.material=this._innerQuadMaterial),this._rebuildContent()}dispose(){super.dispose(),this._disposeTooltip(),this.onPointerClickObservable.remove(this._pointerClickObserver),this.onPointerEnterObservable.remove(this._pointerEnterObserver),this.onPointerOutObservable.remove(this._pointerOutObserver),this.onToggleObservable.remove(this._toggleObserver),this.shareMaterials||(this._backMaterial.dispose(),this._frontMaterial.dispose(),this._plateMaterial.dispose(),this._backGlowMaterial.dispose(),this._innerQuadMaterial.dispose(),this._pickedPointObserver&&(this._host.onPickedPointChangedObservable.remove(this._pickedPointObserver),this._pickedPointObserver=null))}}gF.MRTK_ASSET_BASE_URL="https://assets.babylonjs.com/meshes/MRTK/",gF.FRONTPLATE_MODEL_FILENAME="mrtk-fluent-frontplate.glb",gF.BACKPLATE_MODEL_FILENAME="mrtk-fluent-backplate.glb",gF.BACKGLOW_MODEL_FILENAME="mrtk-fluent-button.glb",gF.INNERQUAD_MODEL_FILENAME="SlateProximity.glb";class vF{get scene(){return this._scene}get utilityLayer(){return this._utilityLayer}get controlScaling(){return this._customControlScaling}set controlScaling(e){if(this._customControlScaling!==e&&e>0){const t=e/this._customControlScaling;this._customControlScaling=e,this._rootContainer.children.forEach((i=>{i.scaling.scaleInPlace(t),1!==e&&(i._isScaledByManager=!0)}))}}get useRealisticScaling(){return this.controlScaling===vF.MRTK_REALISTIC_SCALING}set useRealisticScaling(e){this.controlScaling=e?vF.MRTK_REALISTIC_SCALING:1}constructor(e){this._customControlScaling=1,this._lastControlOver={},this._lastControlDown={},this.onPickedPointChangedObservable=new K,this.onPickingObservable=new K,this._sharedMaterials={},this._touchSharedMaterials={},this._scene=e||re.LastCreatedScene,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>{this._sceneDisposeObserver=null,this._utilityLayer=null,this.dispose()})),this._utilityLayer=Ju._CreateDefaultUtilityLayerFromScene(this._scene),this._utilityLayer.onlyCheckPointerDownEvents=!1,this._utilityLayer.pickUtilitySceneFirst=!1,this._utilityLayer.mainSceneTrackerPredicate=e=>e&&e.reservedDataStore?.GUI3D?.control?._node,this._rootContainer=new IN("RootContainer"),this._rootContainer._host=this;const t=this._utilityLayer.utilityLayerScene;this._pointerOutObserver=this._utilityLayer.onPointerOutObservable.add((e=>{this._handlePointerOut(e,!0)})),this._pointerObserver=t.onPointerObservable.add((e=>{this._doPicking(e)})),this._utilityLayer.utilityLayerScene.autoClear=!1,this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,new Zu("hemi",_e.Up(),this._utilityLayer.utilityLayerScene)}_handlePointerOut(e,t){const i=this._lastControlOver[e];i&&(i._onPointerOut(i),delete this._lastControlOver[e]),t&&this._lastControlDown[e]&&(this._lastControlDown[e].forcePointerUp(),delete this._lastControlDown[e]),this.onPickedPointChangedObservable.notifyObservers(null)}_doPicking(e){if(!this._utilityLayer||!this._utilityLayer.shouldRender||!this._utilityLayer.utilityLayerScene.activeCamera)return!1;const t=e.event,i=t.pointerId||0,s=t.button,r=e.pickInfo;if(r&&this.onPickingObservable.notifyObservers(r.pickedMesh),!r||!r.hit)return this._handlePointerOut(i,e.type===lr.POINTERUP),!1;r.pickedPoint&&this.onPickedPointChangedObservable.notifyObservers(r.pickedPoint);const n=r.pickedMesh.reservedDataStore?.GUI3D?.control;return n&&!n._processObservables(e.type,r.pickedPoint,r.originMesh?.position||null,i,s)&&e.type===lr.POINTERMOVE&&(this._lastControlOver[i]&&this._lastControlOver[i]._onPointerOut(this._lastControlOver[i]),delete this._lastControlOver[i]),e.type===lr.POINTERUP&&(this._lastControlDown[t.pointerId]&&(this._lastControlDown[t.pointerId].forcePointerUp(),delete this._lastControlDown[t.pointerId]),("touch"===t.pointerType||"xr"===t.pointerType&&this._scene.getEngine().hostInformation.isMobile)&&this._handlePointerOut(i,!1)),!0}get rootContainer(){return this._rootContainer}containsControl(e){return this._rootContainer.containsControl(e)}addControl(e){return this._rootContainer.addControl(e),1!==this._customControlScaling&&(e.scaling.scaleInPlace(this._customControlScaling),e._isScaledByManager=!0),this}removeControl(e){return this._rootContainer.removeControl(e),e._isScaledByManager&&(e.scaling.scaleInPlace(1/this._customControlScaling),e._isScaledByManager=!1),this}dispose(){this._rootContainer.dispose();for(const e in this._sharedMaterials)Object.prototype.hasOwnProperty.call(this._sharedMaterials,e)&&this._sharedMaterials[e].dispose();this._sharedMaterials={};for(const e in this._touchSharedMaterials)Object.prototype.hasOwnProperty.call(this._touchSharedMaterials,e)&&this._touchSharedMaterials[e].dispose();this._touchSharedMaterials={},this._pointerOutObserver&&this._utilityLayer&&(this._utilityLayer.onPointerOutObservable.remove(this._pointerOutObserver),this._pointerOutObserver=null),this.onPickedPointChangedObservable.clear(),this.onPickingObservable.clear();const e=this._utilityLayer?this._utilityLayer.utilityLayerScene:null;e&&this._pointerObserver&&(e.onPointerObservable.remove(this._pointerObserver),this._pointerObserver=null),this._scene&&this._sceneDisposeObserver&&(this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null),this._utilityLayer&&this._utilityLayer.dispose()}}function xF(e,t,i,s){const r={externalResourceFunction:s};return i&&(r.uri="file:"===t?i:t+i),ArrayBuffer.isView(e)?GLTFValidator.validateBytes(e,r):GLTFValidator.validateString(e,r)}function bF(){const e=[];onmessage=t=>{const i=t.data;switch(i.id){case"init":importScripts(i.url);break;case"validate":xF(i.data,i.rootUrl,i.fileName,(t=>new Promise(((i,s)=>{const r=e.length;e.push({resolve:i,reject:s}),postMessage({id:"getExternalResource",index:r,uri:t})})))).then((e=>{postMessage({id:"validate.resolve",value:e})}),(e=>{postMessage({id:"validate.reject",reason:e})}));break;case"getExternalResource.resolve":e[i.index].resolve(i.value);break;case"getExternalResource.reject":e[i.index].reject(i.reason)}}}vF.MRTK_REALISTIC_SCALING=.032;class TF{static ValidateAsync(e,t,i,s){return"function"==typeof Worker?new Promise(((r,n)=>{const o=`${xF}(${bF})()`,a=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),l=new Worker(a),h=e=>{l.removeEventListener("error",h),l.removeEventListener("message",c),n(e)},c=e=>{const t=e.data;switch(t.id){case"getExternalResource":s(t.uri).then((e=>{l.postMessage({id:"getExternalResource.resolve",index:t.index,value:e},[e.buffer])}),(e=>{l.postMessage({id:"getExternalResource.reject",index:t.index,reason:e})}));break;case"validate.resolve":l.removeEventListener("error",h),l.removeEventListener("message",c),r(t.value),l.terminate();break;case"validate.reject":l.removeEventListener("error",h),l.removeEventListener("message",c),n(t.reason),l.terminate()}};if(l.addEventListener("error",h),l.addEventListener("message",c),l.postMessage({id:"init",url:Ds.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const s=e.slice();l.postMessage({id:"validate",data:s,rootUrl:t,fileName:i},[s.buffer])}else l.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})})):(this._LoadScriptPromise||(this._LoadScriptPromise=Ds.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then((()=>xF(e,t,i,s))))}}function yF(e,t,i){try{return Promise.resolve(new Uint8Array(e,t,i))}catch(e){return Promise.reject(e)}}var SF,CF,EF,AF,PF,IF,RF,MF,OF,DF,wF,NF;TF.Configuration={url:`${Ds._DefaultCdnUrl}/gltf_validator.js`},function(e){e[e.AUTO=0]="AUTO",e[e.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"}(SF||(SF={})),function(e){e[e.NONE=0]="NONE",e[e.FIRST=1]="FIRST",e[e.ALL=2]="ALL"}(CF||(CF={})),function(e){e[e.LOADING=0]="LOADING",e[e.READY=1]="READY",e[e.COMPLETE=2]="COMPLETE"}(EF||(EF={}));class FF{constructor(){this.onParsedObservable=new K,this.coordinateSystemMode=SF.AUTO,this.animationStartMode=CF.FIRST,this.compileMaterials=!1,this.useClipPlane=!1,this.compileShadowGenerators=!1,this.transparencyAsCoverage=!1,this.useRangeRequests=!1,this.createInstances=!0,this.alwaysComputeBoundingBox=!1,this.loadAllMaterials=!1,this.loadOnlyMaterials=!1,this.skipMaterials=!1,this.useSRGBBuffers=!0,this.targetFps=60,this.alwaysComputeSkeletonRootNode=!1,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable=new K,this.onSkinLoadedObservable=new K,this.onTextureLoadedObservable=new K,this.onMaterialLoadedObservable=new K,this.onCameraLoadedObservable=new K,this.onCompleteObservable=new K,this.onErrorObservable=new K,this.onDisposeObservable=new K,this.onExtensionLoadedObservable=new K,this.validate=!1,this.onValidatedObservable=new K,this._loader=null,this._state=null,this._requests=new Array,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new K,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),this._onParsedObserver=this.onParsedObservable.add(e)}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e)}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e)}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e)}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e)}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,i,s,r,n,o,a){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,s,o,a),null;this._progressCallback=r;const l=t.name||Ds.GetFilename(t);if(n){if(this.useRangeRequests){this.validate&&Ne.Warn("glTF validation is not supported when range requests are enabled");const i={abort:()=>{},onCompleteObservable:new K},r={readAsync:(i,s)=>new Promise(((r,n)=>{this._loadFile(e,t,(e=>{r(new Uint8Array(e))}),!0,(e=>{n(e)}),(e=>{e.setRequestHeader("Range",`bytes=${i}-${i+s-1}`)}))})),byteLength:0};return this._unpackBinaryAsync(new mR(r)).then((e=>{i.onCompleteObservable.notifyObservers(i),s(e)}),o?e=>o(void 0,e):void 0),i}return this._loadFile(e,t,(t=>{this._validate(e,new Uint8Array(t,0,t.byteLength),i,l),this._unpackBinaryAsync(new mR({readAsync:(e,i)=>yF(t,e,i),byteLength:t.byteLength})).then((e=>{s(e)}),o?e=>o(void 0,e):void 0)}),!0,o)}return this._loadFile(e,t,(t=>{this._validate(e,t,i,l),s({json:this._parseJson(t)})}),!1,o)}_loadBinary(e,t,i,s,r,n){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i,n),this._unpackBinaryAsync(new mR({readAsync:(e,i)=>function(e,t,i){try{if(t<0||t>=e.byteLength)throw new RangeError("Offset is out of range.");if(t+i>e.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(e.buffer,e.byteOffset+t,i))}catch(e){return Promise.reject(e)}}(t,e,i),byteLength:t.byteLength})).then((e=>{s(e)}),r?e=>r(void 0,e):void 0)}importMeshAsync(e,t,i,s,r,n){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${n||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,s,r,n))))}loadAsync(e,t,i,s,r){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,s,r))))}loadAssetContainerAsync(e,t,i,s,r){return Promise.resolve().then((()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t);const n=new pa(e),o=[];this.onMaterialLoadedObservable.add((e=>{o.push(e)}));const a=[];this.onTextureLoadedObservable.add((e=>{a.push(e)}));const l=[];this.onCameraLoadedObservable.add((e=>{l.push(e)}));const h=[];return this.onMeshLoadedObservable.add((e=>{e.morphTargetManager&&h.push(e.morphTargetManager)})),this._loader.importMeshAsync(null,e,n,t,i,s,r).then((e=>(Array.prototype.push.apply(n.geometries,e.geometries),Array.prototype.push.apply(n.meshes,e.meshes),Array.prototype.push.apply(n.particleSystems,e.particleSystems),Array.prototype.push.apply(n.skeletons,e.skeletons),Array.prototype.push.apply(n.animationGroups,e.animationGroups),Array.prototype.push.apply(n.materials,o),Array.prototype.push.apply(n.textures,a),Array.prototype.push.apply(n.lights,e.lights),Array.prototype.push.apply(n.transformNodes,e.transformNodes),Array.prototype.push.apply(n.cameras,l),Array.prototype.push.apply(n.morphTargetManagers,h),n)))}))}canDirectLoad(e){return-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+FF._MagicBase64Encoded)||e.startsWith("data:;base64,"+FF._MagicBase64Encoded)||e.startsWith("data:application/octet-stream;base64,"+FF._MagicBase64Encoded)||e.startsWith("data:model/gltf-binary;base64,"+FF._MagicBase64Encoded)}directLoad(e,t){if(t.startsWith("base64,"+FF._MagicBase64Encoded)||t.startsWith(";base64,"+FF._MagicBase64Encoded)||t.startsWith("application/octet-stream;base64,"+FF._MagicBase64Encoded)||t.startsWith("model/gltf-binary;base64,"+FF._MagicBase64Encoded)){const i=xs(t);return this._validate(e,new Uint8Array(i,0,i.byteLength)),this._unpackBinaryAsync(new mR({readAsync:(e,t)=>yF(i,e,t),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(){return new FF}get loaderState(){return this._state}whenCompleteAsync(){return new Promise(((e,t)=>{this.onCompleteObservable.addOnce((()=>{e()})),this.onErrorObservable.addOnce((e=>{t(e)}))}))}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(EF[this._state]))}_loadFile(e,t,i,s,r,n){const o=e._loadFile(t,i,(e=>{this._onProgress(e,o)}),!0,s,r,n);return o.onCompleteObservable.add((()=>{o._lengthComputable=!0,o._total=o._loaded})),this._requests.push(o),o}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,s=0,r=0;for(const e of this._requests){if(void 0===e._lengthComputable||void 0===e._loaded||void 0===e._total)return;i=i&&e._lengthComputable,s+=e._loaded,r+=e._total}this._progressCallback({lengthComputable:i,loaded:s,total:i?r:0})}_validate(e,t,i="",s=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),TF.ValidateAsync(t,i,s,(t=>this.preprocessUrlAsync(i+t).then((t=>e._loadFileAsync(t,void 0,!0,!0).then((e=>new Uint8Array(e,0,e.byteLength))))))).then((e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()}),(e=>{this._endPerformanceCounter("Validate JSON"),Ds.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 i=FF._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=FF._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(FF._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const s={1:FF._CreateGLTF1Loader,2:FF._CreateGLTF2Loader}[i.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 t=e.readUint32();if(1179937895!==t)throw new jt("Unexpected magic: "+t,Qt.GLTFLoaderUnexpectedMagicError);const i=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${i}`);const s=e.readUint32();let r;switch(this.useRangeRequests||s===e.buffer.byteLength||Ne.Warn(`Length in header does not match actual data length: ${s} != ${e.buffer.byteLength}`),i){case 1:r=this._unpackBinaryV1Async(e,s);break;case 2:r=this._unpackBinaryV2Async(e,s);break;default:throw new Error("Unsupported version: "+i)}return this._endPerformanceCounter("Unpack Binary"),r}))}_unpackBinaryV1Async(e,t){const i=e.readUint32(),s=e.readUint32();if(0!==s)throw new Error(`Unexpected content format: ${s}`);const r=t-e.byteOffset,n={json:this._parseJson(e.readString(i)),bin:null};if(0!==r){const t=e.byteOffset;n.bin={readAsync:(i,s)=>e.buffer.readAsync(t+i,s),byteLength:r}}return Promise.resolve(n)}_unpackBinaryV2Async(e,t){const i=1313821514,s=e.readUint32();if(e.readUint32()!==i)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 r={json:this._parseJson(e.readString(s)),bin:null},n=()=>{const s=e.readUint32();switch(e.readUint32()){case i:throw new Error("Unexpected JSON chunk");case 5130562:{const t=e.byteOffset;r.bin={readAsync:(i,s)=>e.buffer.readAsync(t+i,s),byteLength:s},e.skipBytes(s);break}default:e.skipBytes(s)}return e.byteOffset!==t?e.loadAsync(8).then(n):Promise.resolve(r)};return n()}))}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.majort.minor?1:e.minorn.byteLength)throw new Error("Buffer access is out of range");const o=n.buffer;switch(i+=n.byteOffset,r){case AF.BYTE:return new Int8Array(o,i,s);case AF.UNSIGNED_BYTE:return new Uint8Array(o,i,s);case AF.SHORT:return new Int16Array(o,i,s);case AF.UNSIGNED_SHORT:return new Uint16Array(o,i,s);default:return new Float32Array(o,i,s)}}static GetBufferFromAccessor(e,t){const i=e.bufferViews[t.bufferView],s=t.count*LF.GetByteStrideFromType(t);return LF.GetBufferFromBufferView(e,i,t.byteOffset,s,t.componentType)}static DecodeBufferToText(e){let t="";const i=e.byteLength;for(let s=0;s=this._maxPos}}const kF=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],VF=["world","view","projection","worldView","worldViewProjection","mBones"],UF=["translation","rotation","scale"],GF=["position","rotationQuaternion","scaling"],zF=(e,t,i)=>{for(const s in e){const r=e[s];i[t][s]=r}},WF=e=>{if(e)for(let t=0;t{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},XF=e=>{let t=null;if(e.translation||e.rotation||e.scale){const i=_e.FromArray(e.scale||[1,1,1]),s=fe.FromArray(e.rotation||[0,0,0,1]),r=_e.FromArray(e.translation||[0,0,0]);t=me.Compose(i,s,r)}else t=me.FromArray(e.matrix);return t},YF=(e,t,i,s)=>{for(let e=0;e{for(let i=0;i{const i=e.nodes;let s=i[t];if(s)return{node:s,id:t};for(const e in i)if(s=i[e],s.jointName===t)return{node:s,id:e};return null},KF=(e,t)=>{for(let i=0;i{if(r||(e.scene._blockEntityCollection=!!e.assetContainer,(r=new ha(t.name||"",e.scene))._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,r.id=s),!t.babylonNode)return r;const n=[];let o=null;const a=[],l=[],h=[],c=[];for(let t=0;t1?(u=new ia("multimat"+s,e.scene),u.subMaterials=n):u=new cu("multimat"+s,e.scene),1===n.length&&(u=n[0]),u._parentContainer=e.assetContainer,r.material||(r.material=u),new Yn(s,e.scene,o,!1,r),r.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,r.subMeshes=[];let d=0;for(let t=0;t{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=i),e.scaling&&(e.scaling=s)},ZF=(e,t,i)=>{let s=null;if(e.importOnlyMeshes&&(t.skin||t.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&-1===e.importMeshesNames.indexOf(t.name||""))return null;if(t.skin){if(t.meshes){const r=e.skins[t.skin],n=$F(e,t,t.meshes,i,t.babylonNode);n.skeleton=e.scene.getLastSkeletonById(t.skin),null===n.skeleton&&(n.skeleton=((e,t,i,s)=>{if(s||(s=new Da(t.name||"","",e.scene)),!t.babylonSkeleton)return s;const r=[],n=[];((e,t,i,s)=>{for(const r in e.nodes){const n=e.nodes[r],o=r;if(!n.jointName||KF(i,n.jointName))continue;const a=XF(n),l=new Yr(n.name||"",t,null,a);l.id=o,s.push({bone:l,node:n,id:o})}for(let e=0;e0&&(u=QF(r,l),u&&-1===n.indexOf(u)&&n.push(u)),new Yr(a.jointName||"",s,u,d).id=l}const o=s.bones;s.bones=[];for(let i=0;i{if(t.matrix){const i=new _e(0,0,0),s=new fe,r=new _e(0,0,0);me.FromArray(t.matrix).decompose(r,s,i),qF(e,i,s,r)}else t.translation&&t.rotation&&t.scale&&qF(e,_e.FromArray(t.translation),fe.FromArray(t.rotation),_e.FromArray(t.scale));e.computeWorldMatrix(!0)})(s,t);else{const e=t.translation||[0,0,0],i=t.rotation||[0,0,0,1],r=t.scale||[1,1,1];qF(s,_e.FromArray(e),fe.FromArray(i),_e.FromArray(r))}s.updateCache(!0),t.babylonNode=s}return s},JF=(e,t,i,s=!1)=>{const r=e.nodes[t];let n=null;if(s=!(e.importOnlyMeshes&&!s&&e.importMeshesNames)||-1!==e.importMeshesNames.indexOf(r.name||"")||0===e.importMeshesNames.length,!r.jointName&&s&&(n=ZF(e,r,t),null!==n&&(n.id=t,n.parent=i)),r.children)for(let t=0;t{let t=e.currentScene;if(t)for(let i=0;i{for(const t in e.animations){const i=e.animations[t];if(!i.channels||!i.samplers)continue;let s=null;for(let r=0;r{for(const s in t.uniforms){const r=t.uniforms[s],n=t.parameters[r];if(e.currentIdentifier===s&&n.semantic&&!n.source&&!n.node){const e=kF.indexOf(n.semantic);if(-1!==e)return delete i[s],VF[e]}}return e.currentIdentifier},iL=e=>{for(const t in e.materials)nL.LoadMaterialAsync(e,t,(()=>{}),(()=>{}))};class sL{static CreateRuntime(e,t,i){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:i,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&zF(e.extensions,"extensions",s),e.extensionsUsed&&zF(e.extensionsUsed,"extensionsUsed",s),e.buffers&&((e,t)=>{for(const i in e){const s=e[i];t.buffers[i]=s,t.buffersCount++}})(e.buffers,s),e.bufferViews&&zF(e.bufferViews,"bufferViews",s),e.accessors&&zF(e.accessors,"accessors",s),e.meshes&&zF(e.meshes,"meshes",s),e.lights&&zF(e.lights,"lights",s),e.cameras&&zF(e.cameras,"cameras",s),e.nodes&&zF(e.nodes,"nodes",s),e.images&&zF(e.images,"images",s),e.textures&&zF(e.textures,"textures",s),e.shaders&&((e,t)=>{for(const i in e){const s=e[i];t.shaders[i]=s,t.shaderscount++}})(e.shaders,s),e.programs&&zF(e.programs,"programs",s),e.samplers&&zF(e.samplers,"samplers",s),e.techniques&&zF(e.techniques,"techniques",s),e.materials&&zF(e.materials,"materials",s),e.animations&&zF(e.animations,"animations",s),e.skins&&zF(e.skins,"skins",s),e.scenes&&(s.scenes=e.scenes),e.scene&&e.scenes&&(s.currentScene=e.scenes[e.scene]),s}static LoadBufferAsync(e,t,i,s,r){const n=e.buffers[t];Ds.IsBase64(n.uri)?setTimeout((()=>i(new Uint8Array(Ds.DecodeBase64(n.uri))))):Ds.LoadFile(e.rootUrl+n.uri,(e=>i(new Uint8Array(e))),r,void 0,!0,(e=>{e&&s(e.status+" "+e.statusText)}))}static LoadTextureBufferAsync(e,t,i,s){const r=e.textures[t];if(!r||!r.source)return void s("");if(r.babylonTexture)return void i(null);const n=e.images[r.source];Ds.IsBase64(n.uri)?setTimeout((()=>i(new Uint8Array(Ds.DecodeBase64(n.uri))))):Ds.LoadFile(e.rootUrl+n.uri,(e=>i(new Uint8Array(e))),void 0,void 0,!0,(e=>{e&&s(e.status+" "+e.statusText)}))}static CreateTextureAsync(e,t,i,s){const r=e.textures[t];if(r.babylonTexture)return void s(r.babylonTexture);const n=e.samplers[r.sampler],o=n.minFilter===MF.NEAREST_MIPMAP_NEAREST||n.minFilter===MF.NEAREST_MIPMAP_LINEAR||n.minFilter===MF.LINEAR_MIPMAP_NEAREST||n.minFilter===MF.LINEAR_MIPMAP_LINEAR,a=Pa.BILINEAR_SAMPLINGMODE,l=null==i?new Blob:new Blob([i]),h=URL.createObjectURL(l),c=()=>URL.revokeObjectURL(h),u=new Pa(h,e.scene,!o,!0,a,c,c);void 0!==n.wrapS&&(u.wrapU=LF.GetWrapMode(n.wrapS)),void 0!==n.wrapT&&(u.wrapV=LF.GetWrapMode(n.wrapT)),u.name=t,r.babylonTexture=u,s(u)}static LoadShaderStringAsync(e,t,i,s){const r=e.shaders[t];if(Ds.IsBase64(r.uri)){const e=atob(r.uri.split(",")[1]);i&&i(e)}else Ds.LoadFile(e.rootUrl+r.uri,i,void 0,void 0,!1,(e=>{e&&s&&s(e.status+" "+e.statusText)}))}static LoadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r.technique)return void(s&&s("No technique found."));const n=e.techniques[r.technique];if(!n){e.scene._blockEntityCollection=!!e.assetContainer;const s=new cu(t,e.scene);return s._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,s.diffuseColor=new Ee(.5,.5,.5),s.sideOrientation=ta.CounterClockWiseSideOrientation,void i(s)}const o=e.programs[n.program],a=n.states,l=$i.ShadersStore[o.vertexShader+"VertexShader"],h=$i.ShadersStore[o.fragmentShader+"PixelShader"];let c="",u="";const d=new BF(l),_=new BF(h),p={},f=[],m=[],g=[];for(const e in n.uniforms){const t=n.uniforms[e],i=n.parameters[t];if(p[e]=i,!i.semantic||i.node||i.source)i.type===IF.SAMPLER_2D?g.push(e):f.push(e);else{const t=kF.indexOf(i.semantic);-1!==t?(f.push(VF[t]),delete p[e]):f.push(e)}}for(const e in n.attributes){const t=n.attributes[e],i=n.parameters[t];if(i.semantic){const e=HF(i);e&&m.push(e)}}for(;!d.isEnd()&&d.getNextToken();){if(d.currentToken!==NF.IDENTIFIER){c+=d.currentString;continue}let e=!1;for(const t in n.attributes){const i=n.attributes[t],s=n.parameters[i];if(d.currentIdentifier===t&&s.semantic){c+=HF(s),e=!0;break}}e||(c+=tL(d,n,p))}for(;!_.isEnd()&&_.getNextToken();)_.currentToken===NF.IDENTIFIER?u+=tL(_,n,p):u+=_.currentString;const v={vertex:o.vertexShader+t,fragment:o.fragmentShader+t},x={attributes:m,uniforms:f,samplers:g,needAlphaBlending:a&&a.enable&&-1!==a.enable.indexOf(3042)};$i.ShadersStore[o.vertexShader+t+"VertexShader"]=c,$i.ShadersStore[o.fragmentShader+t+"PixelShader"]=u;const b=new Nd(t,e.scene,v,x);if(b.onError=((e,t,i)=>(s,r)=>{t.dispose(!0),i("Cannot compile program named "+e.name+". Error: "+r+". Default material will be applied")})(o,b,s),b.onCompiled=((e,t,i,s,r,n)=>o=>{((e,t,i,s,r)=>{const n=s.values||i.parameters,o=i.uniforms;for(const i in r){const a=r[i],l=a.type;let h=n[o[i]];if(void 0===h&&(h=a.value),!h)continue;const c=e=>i=>{a.value&&e&&(t.setTexture(e,i),delete r[e])};l===IF.SAMPLER_2D?nL.LoadTextureAsync(e,s.values?h:a.value,c(i),(()=>c(null))):a.value&&LF.SetUniform(t,i,s.values?h:a.value,l)&&delete r[i]}})(e,t,i,s,r),t.onBind=o=>{((e,t,i,s,r,n,o)=>{const a=n.values||r.parameters;for(const o in i){const l=i[o],h=l.type;if(h===IF.FLOAT_MAT2||h===IF.FLOAT_MAT3||h===IF.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;LF.SetMatrix(t.scene,e,l,o,s.getEffect())}}else LF.SetMatrix(t.scene,e,l,o,s.getEffect());else{const e=a[r.uniforms[o]];if(!e)continue;if(h===IF.SAMPLER_2D){const i=t.textures[n.values?e:l.value].babylonTexture;if(null==i)continue;s.getEffect().setTexture(o,i)}else LF.SetUniform(s.getEffect(),o,e,h)}}o(s)})(o,e,r,t,i,s,n)}})(e,b,n,r,p,i),b.sideOrientation=ta.CounterClockWiseSideOrientation,a&&a.functions){const e=a.functions;e.cullFace&&e.cullFace[0]!==DF.BACK&&(b.backFaceCulling=!1);const t=e.blendFuncSeparate;t&&(t[0]===wF.SRC_ALPHA&&t[1]===wF.ONE_MINUS_SRC_ALPHA&&t[2]===wF.ONE&&t[3]===wF.ONE?b.alphaMode=N_.ALPHA_COMBINE:t[0]===wF.ONE&&t[1]===wF.ONE&&t[2]===wF.ZERO&&t[3]===wF.ONE?b.alphaMode=N_.ALPHA_ONEONE:t[0]===wF.SRC_ALPHA&&t[1]===wF.ONE&&t[2]===wF.ZERO&&t[3]===wF.ONE?b.alphaMode=N_.ALPHA_ADD:t[0]===wF.ZERO&&t[1]===wF.ONE_MINUS_SRC_COLOR&&t[2]===wF.ONE&&t[3]===wF.ONE?b.alphaMode=N_.ALPHA_SUBTRACT:t[0]===wF.DST_COLOR&&t[1]===wF.ZERO&&t[2]===wF.ONE&&t[3]===wF.ONE?b.alphaMode=N_.ALPHA_MULTIPLY:t[0]===wF.SRC_ALPHA&&t[1]===wF.ONE_MINUS_SRC_COLOR&&t[2]===wF.ONE&&t[3]===wF.ONE&&(b.alphaMode=N_.ALPHA_MAXIMIZED))}}}class rL{static RegisterExtension(e){rL.Extensions[e.name]?Ds.Error('Tool with the same name "'+e.name+'" already exists'):rL.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,s,r,n,o,a){return t.useRightHandedSystem=!0,nL.LoadRuntimeAsync(t,i,s,(t=>{t.assetContainer=r,t.importOnlyMeshes=!0,""===e?t.importMeshesNames=[]:"string"==typeof e?t.importMeshesNames=[e]:!e||e instanceof Array?(t.importMeshesNames=[],Ds.Warn("Argument meshesNames must be of type string or string[]")):t.importMeshesNames=[e],this._createNodes(t);const i=[],s=[];for(const e in t.nodes){const s=t.nodes[e];s.babylonNode instanceof _o&&i.push(s.babylonNode)}for(const e in t.skins){const i=t.skins[e];i.babylonSkeleton instanceof Da&&s.push(i.babylonSkeleton)}this._loadBuffersAsync(t,(()=>{this._loadShadersAsync(t,(()=>{iL(t),eL(t),!FF.IncrementalLoading&&n&&n(i,s)}))})),FF.IncrementalLoading&&n&&n(i,s)}),a),!0}importMeshAsync(e,t,i,s,r,n){return new Promise(((o,a)=>{this._importMeshAsync(e,t,s,r,i,((e,t)=>{o({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})}),n,(e=>{a(new Error(e))}))}))}_loadAsync(e,t,i,s,r,n){e.useRightHandedSystem=!0,nL.LoadRuntimeAsync(e,t,i,(e=>{nL.LoadRuntimeExtensionsAsync(e,(()=>{this._createNodes(e),this._loadBuffersAsync(e,(()=>{this._loadShadersAsync(e,(()=>{iL(e),eL(e),FF.IncrementalLoading||s()}))})),FF.IncrementalLoading&&s()}),n)}),n)}loadAsync(e,t,i,s){return new Promise(((r,n)=>{this._loadAsync(e,t,i,(()=>{r()}),s,(e=>{n(new Error(e))}))}))}_loadShadersAsync(e,t){let i=!1;const s=(i,s)=>{nL.LoadShaderStringAsync(e,i,(r=>{r instanceof ArrayBuffer||(e.loadedShaderCount++,r&&($i.ShadersStore[i+(s.type===PF.VERTEX?"VertexShader":"PixelShader")]=r),e.loadedShaderCount===e.shaderscount&&t())}),(()=>{Ds.Error("Error when loading shader program named "+i+" located at "+s.uri)}))};for(const t in e.shaders){i=!0;const r=e.shaders[t];r?s.bind(this,t,r)():Ds.Error("No shader named: "+t)}i||t()}_loadBuffersAsync(e,t){let i=!1;const s=(i,s)=>{nL.LoadBufferAsync(e,i,(r=>{e.loadedBufferCount++,r&&(r.byteLength!=e.buffers[i].byteLength&&Ds.Error("Buffer named "+i+" is length "+r.byteLength+". Expected: "+s.byteLength),e.loadedBufferViews[i]=r),e.loadedBufferCount===e.buffersCount&&t()}),(()=>{Ds.Error("Error when loading buffer named "+i+" located at "+s.uri)}))};for(const t in e.buffers){i=!0;const r=e.buffers[t];r?s.bind(this,t,r)():Ds.Error("No buffer named: "+t)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;in.loadRuntimeAsync(e,t,i,s,r)),(()=>{setTimeout((()=>{s&&s(sL.CreateRuntime(t.json,e,i))}))}))}static LoadRuntimeExtensionsAsync(e,t,i){nL._ApplyExtensions((s=>s.loadRuntimeExtensionsAsync(e,t,i)),(()=>{setTimeout((()=>{t()}))}))}static LoadBufferAsync(e,t,i,s,r){nL._ApplyExtensions((n=>n.loadBufferAsync(e,t,i,s,r)),(()=>{sL.LoadBufferAsync(e,t,i,s,r)}))}static LoadTextureAsync(e,t,i,s){nL._LoadTextureBufferAsync(e,t,(r=>{r&&nL._CreateTextureAsync(e,t,r,i,s)}),s)}static LoadShaderStringAsync(e,t,i,s){nL._ApplyExtensions((r=>r.loadShaderStringAsync(e,t,i,s)),(()=>{sL.LoadShaderStringAsync(e,t,i,s)}))}static LoadMaterialAsync(e,t,i,s){nL._ApplyExtensions((r=>r.loadMaterialAsync(e,t,i,s)),(()=>{sL.LoadMaterialAsync(e,t,i,s)}))}static _LoadTextureBufferAsync(e,t,i,s){nL._ApplyExtensions((r=>r.loadTextureBufferAsync(e,t,i,s)),(()=>{sL.LoadTextureBufferAsync(e,t,i,s)}))}static _CreateTextureAsync(e,t,i,s,r){nL._ApplyExtensions((n=>n.createTextureAsync(e,t,i,s,r)),(()=>{sL.CreateTextureAsync(e,t,i,s)}))}static _ApplyExtensions(e,t){for(const t in rL.Extensions)if(e(rL.Extensions[t]))return;t()}}function oL(e,t,i,s){return _e.FromArray(t,i).scaleInPlace(s)}FF._CreateGLTF1Loader=()=>new rL,rL.RegisterExtension(new class extends nL{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,s){const r=t.json.extensionsUsed;return!(!r||-1===r.indexOf(this.name)||!t.bin||(this._bin=t.bin,s(sL.CreateRuntime(t.json,e,i)),0))}loadBufferAsync(e,t,i,s){return-1!==e.extensionsUsed.indexOf(this.name)&&"binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(i,(e=>s(e.message))),!0)}loadTextureBufferAsync(e,t,i){const s=e.textures[t],r=e.images[s.source];if(!r.extensions||!(this.name in r.extensions))return!1;const n=r.extensions[this.name],o=e.bufferViews[n.bufferView];return i(LF.GetBufferFromBufferView(e,o,0,o.byteLength,AF.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,i){const s=e.shaders[t];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],n=e.bufferViews[r.bufferView],o=LF.GetBufferFromBufferView(e,n,0,n.byteLength,AF.UNSIGNED_BYTE);return setTimeout((()=>{const e=LF.DecodeBufferToText(o);i(e)})),!0}}),rL.RegisterExtension(new class extends nL{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const t=e.extensions[this.name];if(!t)return!1;const i=t.lights;if(i)for(const t in i){const s=i[t];switch(s.type){case"ambient":{const t=new Zu(s.name,new _e(0,1,0),e.scene),i=s.ambient;i&&(t.diffuse=Ee.FromArray(i.color||[1,1,1]));break}case"point":{const t=new ex(s.name,new _e(10,10,10),e.scene),i=s.point;i&&(t.diffuse=Ee.FromArray(i.color||[1,1,1]));break}case"directional":{const t=new cg(s.name,new _e(0,-1,0),e.scene),i=s.directional;i&&(t.diffuse=Ee.FromArray(i.color||[1,1,1]));break}case"spot":{const t=s.spot;t&&(new _g(s.name,new _e(0,10,0),new _e(0,-1,0),t.fallOffAngle||Math.PI,t.fallOffExponent||0,e.scene).diffuse=Ee.FromArray(t.color||[1,1,1]));break}default:Ds.Warn('GLTF Material Common extension: light type "'+s.type+"” not supported")}}return!1}loadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r||!r.extensions)return!1;const n=r.extensions[this.name];if(!n)return!1;const o=new cu(t,e.scene);return o.sideOrientation=ta.CounterClockWiseSideOrientation,"CONSTANT"===n.technique&&(o.disableLighting=!0),o.backFaceCulling=void 0!==n.doubleSided&&!n.doubleSided,o.alpha=void 0===n.values.transparency?1:n.values.transparency,o.specularPower=void 0===n.values.shininess?0:n.values.shininess,"string"==typeof n.values.ambient?this._loadTexture(e,n.values.ambient,o,"ambientTexture",s):o.ambientColor=Ee.FromArray(n.values.ambient||[0,0,0]),"string"==typeof n.values.diffuse?this._loadTexture(e,n.values.diffuse,o,"diffuseTexture",s):o.diffuseColor=Ee.FromArray(n.values.diffuse||[0,0,0]),"string"==typeof n.values.emission?this._loadTexture(e,n.values.emission,o,"emissiveTexture",s):o.emissiveColor=Ee.FromArray(n.values.emission||[0,0,0]),"string"==typeof n.values.specular?this._loadTexture(e,n.values.specular,o,"specularTexture",s):o.specularColor=Ee.FromArray(n.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,s,r){sL.LoadTextureBufferAsync(e,t,(r=>{sL.CreateTextureAsync(e,t,r,(e=>i[s]=e))}),r)}});class aL{constructor(e,t,i,s){this.type=e,this.name=t,this.getValue=i,this.getStride=s}_buildAnimation(e,t,i){const s=new Ft(e,this.name,t,this.type);return s.setKeys(i),s}}class lL extends aL{buildAnimations(e,t,i,s,r){r(e._babylonTransformNode,this._buildAnimation(t,i,s))}}const hL={translation:[new lL(Ft.ANIMATIONTYPE_VECTOR3,"position",oL,(()=>3))],rotation:[new lL(Ft.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",(function(e,t,i,s){return fe.FromArray(t,i).scaleInPlace(s)}),(()=>4))],scale:[new lL(Ft.ANIMATIONTYPE_VECTOR3,"scaling",oL,(()=>3))],weights:[new class extends aL{buildAnimations(e,t,i,s,r){if(e._numMorphTargets)for(let n=0;n({frame:e.frame,inTangent:e.inTangent?e.inTangent[n]:void 0,value:e.value[n],outTangent:e.outTangent?e.outTangent[n]:void 0,interpolation:e.interpolation})))),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(n),i=o.clone();e.animations.push(i),r(e,i)}}}}(Ft.ANIMATIONTYPE_FLOAT,"influence",(function(e,t,i,s){const r=new Array(e._numMorphTargets);for(let e=0;ee._numMorphTargets))]};function cL(...e){const t=e=>e&&"object"==typeof e;return e.reduce(((e,i)=>(Object.keys(i).forEach((s=>{const r=e[s],n=i[s];Array.isArray(r)&&Array.isArray(n)?e[s]=r.concat(...n):t(r)&&t(n)?e[s]=cL(r,n):e[s]=n})),e)),{})}class uL{static Get(e,t,i){if(!t||null==i||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static TryGet(e,t){return e&&null!=t&&e[t]?e[t]:null}static Assign(e){if(e)for(let t=0;te.dispose&&e.dispose())),this._extensions.length=0,this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,i,s,r,n,o=""){return Promise.resolve().then((()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(s);let n=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);n=(e instanceof Array?e:[e]).map((e=>{const i=t[e];if(void 0===i)throw new Error(`Failed to find node '${e}'`);return i}))}return this._loadAsync(r,o,n,(()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]})))}))}loadAsync(e,t,i,s,r=""){return Promise.resolve().then((()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,r,null,(()=>{})))))}_loadAsync(e,t,i,s){return Promise.resolve().then((()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,this._loadExtensions(),this._checkExtensions();const r=`${EF[EF.LOADING]} => ${EF[EF.READY]}`,n=`${EF[EF.LOADING]} => ${EF[EF.COMPLETE]}`;this._parent._startPerformanceCounter(r),this._parent._startPerformanceCounter(n),this._parent._setState(EF.LOADING),this._extensionsOnLoading();const o=new Array,a=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=uL.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${e.index}`,e))}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let e=0;e{})))}return this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=a:this._babylonScene._forceBlockMaterialDirtyMechanism(a),this._parent.compileMaterials&&o.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&o.push(this._compileShadowGeneratorsAsync()),Promise.all(o).then((()=>(this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(EF.READY),this._startAnimations(),s()))).then((e=>(this._parent._endPerformanceCounter(r),Ds.SetImmediate((()=>{this._disposed||Promise.all(this._completePromises).then((()=>{this._parent._endPerformanceCounter(n),this._parent._setState(EF.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()}),(e=>{this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()}))})),e)))})).catch((e=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()),e}))}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){const i=t[0];(i.byteLengthe.bin.byteLength)&&Ne.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else Ne.Warn("Unexpected BIN chunk")}}_setupData(){if(uL.Assign(this._gltf.accessors),uL.Assign(this._gltf.animations),uL.Assign(this._gltf.buffers),uL.Assign(this._gltf.bufferViews),uL.Assign(this._gltf.cameras),uL.Assign(this._gltf.images),uL.Assign(this._gltf.materials),uL.Assign(this._gltf.meshes),uL.Assign(this._gltf.nodes),uL.Assign(this._gltf.samplers),uL.Assign(this._gltf.scenes),uL.Assign(this._gltf.skins),uL.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const t of this._gltf.nodes)if(t.children)for(const i of t.children)e[i]=t.index;const t=this._createRootNode();for(const i of this._gltf.nodes){const s=e[i.index];i.parent=void 0===s?t:this._gltf.nodes[s]}}}_loadExtensions(){for(const e in dL._RegisteredExtensions){const t=dL._RegisteredExtensions[e].factory(this);t.name!==e&&Ne.Warn(`The name of the glTF loader extension instance does not match the registered name: ${t.name} !== ${e}`),this._extensions.push(t),this._parent.onExtensionLoadedObservable.notifyObservers(t)}this._extensions.sort(((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE))),this._parent.onExtensionLoadedObservable.clear()}_checkExtensions(){if(this._gltf.extensionsRequired)for(const e of this._gltf.extensionsRequired)if(!this._extensions.some((t=>t.name===e&&t.enabled)))throw new Error(`Required extension ${e} 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 e=new ha("__root__",this._babylonScene);this._rootBabylonMesh=e,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const t={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case SF.AUTO:this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],dL._LoadTransform(t,this._rootBabylonMesh));break;case SF.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(e),t}loadSceneAsync(e,t){const i=this._extensionsLoadSceneAsync(e,t);if(i)return i;const s=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const i of t.nodes){const t=uL.Get(`${e}/nodes/${i}`,this._gltf.nodes,i);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 i of e._primitiveBabylonMeshes)t(i)}_getGeometries(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,(t=>{const i=t.geometry;i&&-1===e.indexOf(i)&&e.push(i)}));return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof _o&&e.push(this._rootBabylonMesh);const t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,(t=>{e.push(t)}));return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)i._babylonTransformNode&&"TransformNode"===i._babylonTransformNode.getClassName()&&e.push(i._babylonTransformNode),i._babylonTransformNodeForSkin&&e.push(i._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=[],t=this._gltf.skins;if(t)for(const i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){const e=[],t=this._gltf.animations;if(t)for(const i of t)i._babylonAnimationGroup&&e.push(i._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case CF.NONE:break;case CF.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case CF.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void Ne.Error(`Invalid animation start mode (${this._parent.animationStartMode})`)}}loadNodeAsync(e,t,i=(()=>{})){const s=this._extensionsLoadNodeAsync(e,t,i);if(s)return s;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const r=new Array;this.logOpen(`${e} ${t.name||""}`);const n=s=>{if(dL.AddPointerMetadata(s,e),dL._LoadTransform(t,s),null!=t.camera){const i=uL.Get(`${e}/camera`,this._gltf.cameras,t.camera);r.push(this.loadCameraAsync(`/cameras/${i.index}`,i,(e=>{e.parent=s})))}if(t.children)for(const i of t.children){const t=uL.Get(`${e}/children/${i}`,this._gltf.nodes,i);r.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=s})))}i(s)};if(null==t.mesh||null!=t.skin){const e=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new lo(e,this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==t.mesh?t._babylonTransformNode=i:t._babylonTransformNodeForSkin=i,n(i)}if(null!=t.mesh)if(null==t.skin){const i=uL.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,n))}else{const i=uL.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,(i=>{const s=t._babylonTransformNodeForSkin;i.metadata=cL(s.metadata,i.metadata||{});const n=uL.Get(`${e}/skin`,this._gltf.skins,t.skin);r.push(this._loadSkinAsync(`/skins/${n.index}`,t,n,(e=>{this._forEachPrimitive(t,(t=>{t.skeleton=e})),this._postSceneLoadActions.push((()=>{if(null!=n.skeleton){const e=uL.Get(`/skins/${n.index}/skeleton`,this._gltf.nodes,n.skeleton).parent;t.index===e.index?i.parent=s.parent:i.parent=e._babylonTransformNode}else i.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:s,skinnedNode:i})}))})))})))}return this.logClose(),Promise.all(r).then((()=>(this._forEachPrimitive(t,(e=>{e.geometry&&e.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0,!0)})),t._babylonTransformNode)))}_loadMeshAsync(e,t,i,s){const r=i.primitives;if(!r||!r.length)throw new Error(`${e}: Primitives are missing`);null==r[0].index&&uL.Assign(r);const n=new Array;this.logOpen(`${e} ${i.name||""}`);const o=t.name||`node${t.index}`;if(1===r.length){const s=i.primitives[0];n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${s.index}`,o,t,i,s,(e=>{t._babylonTransformNode=e,t._primitiveBabylonMeshes=[e]})))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new lo(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const s of r)n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${s.index}`,`${o}_primitive${s.index}`,t,i,s,(e=>{e.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(e)})))}return s(t._babylonTransformNode),this.logClose(),Promise.all(n).then((()=>t._babylonTransformNode))}_loadMeshPrimitiveAsync(e,t,i,s,r,n){const o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n);if(o)return o;this.logOpen(`${e}`);const a=0===this._disableInstancedMesh&&this._parent.createInstances&&null==i.skin&&!s.primitives[0].targets;let l,h;if(a&&r._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,l=r._instanceData.babylonSourceMesh.createInstance(t),l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,h=r._instanceData.promise;else{const n=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new ha(t,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.overrideMaterialSideOrientation=this._babylonScene.useRightHandedSystem?ta.CounterClockWiseSideOrientation:ta.ClockWiseSideOrientation,this._createMorphTargets(e,i,s,r,o),n.push(this._loadVertexDataAsync(e,r,o).then((t=>this._loadMorphTargetsAsync(e,r,o,t).then((()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(o),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})))));const c=dL._GetDrawMode(e,r.mode);if(null==r.material){let e=this._defaultBabylonMaterialData[c];e||(e=this._createDefaultMaterial("__GLTFLoader._default",c),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[c]=e),o.material=e}else if(!this.parent.skipMaterials){const t=uL.Get(`${e}/material`,this._gltf.materials,r.material);n.push(this._loadMaterialAsync(`/materials/${t.index}`,t,o,c,(e=>{o.material=e})))}h=Promise.all(n),a&&(r._instanceData={babylonSourceMesh:o,promise:h}),l=o}return dL.AddPointerMetadata(l,e),this._parent.onMeshLoadedObservable.notifyObservers(l),n(l),this.logClose(),h.then((()=>l))}_loadVertexDataAsync(e,t,i){const s=this._extensionsLoadVertexDataAsync(e,t,i);if(s)return s;const r=t.attributes;if(!r)throw new Error(`${e}: Attributes are missing`);const n=new Array,o=new Yn(i.name,this._babylonScene);if(null==t.indices)i.isUnIndexed=!0;else{const i=uL.Get(`${e}/indices`,this._gltf.accessors,t.indices);n.push(this._loadIndicesAccessorAsync(`/accessors/${i.index}`,i).then((e=>{o.setIndices(e)})))}const a=(t,s,a)=>{if(null==r[t])return;i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(s)&&i._delayInfo.push(s);const l=uL.Get(`${e}/attributes/${t}`,this._gltf.accessors,r[t]);n.push(this._loadVertexAccessorAsync(`/accessors/${l.index}`,l,s).then((e=>{if(e.getKind()===er.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&l.min&&l.max){const e=ve.Vector3[0].copyFromFloats(...l.min),t=ve.Vector3[1].copyFromFloats(...l.max);if(l.normalized&&5126!==l.componentType){let i=1;switch(l.componentType){case 5120:i=127;break;case 5121:i=255;break;case 5122:i=32767;break;case 5123:i=65535}const s=1/i;e.scaleInPlace(s),t.scaleInPlace(s)}o._boundingInfo=new Ln(e,t),o.useBoundingInfoFromGeometry=!0}o.setVerticesBuffer(e,l.count)}))),s==er.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),a&&a(l)};return a("POSITION",er.PositionKind),a("NORMAL",er.NormalKind),a("TANGENT",er.TangentKind),a("TEXCOORD_0",er.UVKind),a("TEXCOORD_1",er.UV2Kind),a("TEXCOORD_2",er.UV3Kind),a("TEXCOORD_3",er.UV4Kind),a("TEXCOORD_4",er.UV5Kind),a("TEXCOORD_5",er.UV6Kind),a("JOINTS_0",er.MatricesIndicesKind),a("WEIGHTS_0",er.MatricesWeightsKind),a("JOINTS_1",er.MatricesIndicesExtraKind),a("WEIGHTS_1",er.MatricesWeightsExtraKind),a("COLOR_0",er.ColorKind,(e=>{"VEC4"===e.type&&(i.hasVertexAlpha=!0)})),Promise.all(n).then((()=>o))}_createMorphTargets(e,t,i,s,r){if(!s.targets)return;if(null==t._numMorphTargets)t._numMorphTargets=s.targets.length;else if(s.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const n=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,r.morphTargetManager=new lx(this._babylonScene),r.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e{n.areUpdatesFrozen=!1}))}_loadMorphTargetVertexDataAsync(e,t,i,s){const r=new Array,n=(s,n,o)=>{if(null==i[s])return;const a=t.getVertexBuffer(n);if(!a)return;const l=uL.Get(`${e}/${s}`,this._gltf.accessors,i[s]);r.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then((e=>{o(a,e)})))};return n("POSITION",er.PositionKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(t.length,((e,s)=>{i[s]=t[s]+e})),s.setPositions(i)})),n("NORMAL",er.NormalKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(i.length,((e,s)=>{i[s]=t[s]+e})),s.setNormals(i)})),n("TANGENT",er.TangentKind,((e,t)=>{const i=new Float32Array(t.length/3*4);let r=0;e.forEach(t.length/3*4,((e,s)=>{(s+1)%4!=0&&(i[r]=t[r]+e,r++)})),s.setTangents(i)})),Promise.all(r).then((()=>{}))}static _LoadTransform(e,t){if(null!=e.skin)return;let i=_e.Zero(),s=fe.Identity(),r=_e.One();e.matrix?me.FromArray(e.matrix).decompose(r,s,i):(e.translation&&(i=_e.FromArray(e.translation)),e.rotation&&(s=fe.FromArray(e.rotation)),e.scale&&(r=_e.FromArray(e.scale))),t.position=i,t.rotationQuaternion=s,t.scaling=r}_loadSkinAsync(e,t,i,s){const r=this._extensionsLoadSkinAsync(e,t,i);if(r)return r;if(i._data)return s(i._data.babylonSkeleton),i._data.promise;const n=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new Da(i.name||n,n,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);const a=this._loadSkinInverseBindMatricesDataAsync(e,i).then((e=>{this._updateBoneMatrices(o,e)}));return i._data={babylonSkeleton:o,promise:a},s(o),a}_loadBones(e,t,i){if(null==t.skeleton||this._parent.alwaysComputeSkeletonRootNode){const i=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(i)if(void 0===t.skeleton)t.skeleton=i.index;else{const s=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},r=uL.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);r===i||s(r,i)||(Ne.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=i.index)}else Ne.Warn(`${e}: Failed to find common root`)}const s={};for(const r of t.joints){const n=uL.Get(`${e}/joints/${r}`,this._gltf.nodes,r);this._loadBone(n,t,i,s)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const i={};for(const s of t){const t=[];let r=uL.Get(`${e}/${s}`,this._gltf.nodes,s);for(;-1!==r.index;)t.unshift(r),r=r.parent;i[s]=t}let s=null;for(let e=0;;++e){let r=i[t[0]];if(e>=r.length)return s;const n=r[e];for(let o=1;o=r.length||n!==r[e])return s;s=n}}_loadBone(e,t,i,s){let r=s[e.index];if(r)return r;let n=null;e.index!==t.skeleton&&(e.parent&&-1!==e.parent.index?n=this._loadBone(e.parent,t,i,s):void 0!==t.skeleton&&Ne.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const o=t.joints.indexOf(e.index);return r=new Yr(e.name||`joint${e.index}`,i,n,this._getNodeMatrix(e),null,null,o),s[e.index]=r,this._postSceneLoadActions.push((()=>{r.linkTransformNode(e._babylonTransformNode)})),r}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const i=uL.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${i.index}`,i)}_updateBoneMatrices(e,t){for(const i of e.bones){const e=me.Identity(),s=i._index;t&&-1!==s&&(me.FromArrayToRef(t,16*s,e),e.invertToRef(e));const r=i.getParent();r&&e.multiplyToRef(r.getAbsoluteInverseBindMatrix(),e),i.updateMatrix(e,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?me.FromArray(e.matrix):me.Compose(e.scale?_e.FromArray(e.scale):_e.One(),e.rotation?fe.FromArray(e.rotation):fe.Identity(),e.translation?_e.FromArray(e.translation):_e.Zero())}loadCameraAsync(e,t,i=(()=>{})){const s=this._extensionsLoadCameraAsync(e,t,i);if(s)return s;const r=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new ac(t.name||`camera${t.index}`,_e.Zero(),this._babylonScene,!1);switch(n._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n.ignoreParentScaling=!0,t._babylonCamera=n,n.rotation.set(0,Math.PI,0),t.type){case"perspective":{const i=t.perspective;if(!i)throw new Error(`${e}: Camera perspective properties are missing`);n.fov=i.yfov,n.minZ=i.znear,n.maxZ=i.zfar||0;break}case"orthographic":if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);n.mode=In.ORTHOGRAPHIC_CAMERA,n.orthoLeft=-t.orthographic.xmag,n.orthoRight=t.orthographic.xmag,n.orthoBottom=-t.orthographic.ymag,n.orthoTop=t.orthographic.ymag,n.minZ=t.orthographic.znear,n.maxZ=t.orthographic.zfar;break;default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return dL.AddPointerMetadata(n,e),this._parent.onCameraLoadedObservable.notifyObservers(n),i(n),this.logClose(),Promise.all(r).then((()=>n))}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i{0===e.targetedAnimations.length&&e.dispose()})))}return Promise.all(t).then((()=>{}))}loadAnimationAsync(e,t){const i=this._extensionsLoadAnimationAsync(e,t);if(i)return i;this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new gn(t.name||`animation${t.index}`,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=s;const r=new Array;uL.Assign(t.channels),uL.Assign(t.samplers);for(const i of t.channels)r.push(this._loadAnimationChannelAsync(`${e}/channels/${i.index}`,e,t,i,((e,t)=>{e.animations=e.animations||[],e.animations.push(t),s.addTargetedAnimation(t,e)})));return Promise.all(r).then((()=>(s.normalize(0),s)))}_loadAnimationChannelAsync(e,t,i,s,r){const n=this._extensionsLoadAnimationChannelAsync(e,t,i,s,r);if(n)return n;if(null==s.target.node)return Promise.resolve();const o=uL.Get(`${e}/target/node`,this._gltf.nodes,s.target.node);if("weights"===s.target.path&&!o._numMorphTargets||"weights"!==s.target.path&&!o._babylonTransformNode)return Promise.resolve();let a;switch(s.target.path){case"translation":a=hL.translation;break;case"rotation":a=hL.rotation;break;case"scale":a=hL.scale;break;case"weights":a=hL.weights;break;default:throw new Error(`${e}/target/path: Invalid value (${s.target.path})`)}const l={object:o,info:a};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,l,r)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,s,r,n){const o=this.parent.targetFps,a=1/o,l=uL.Get(`${e}/sampler`,i.samplers,s.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${s.sampler}`,l).then((e=>{let t=0;const l=r.object,h=r.info;for(const r of h){const h=r.getStride(l),c=e.input,u=e.output,d=new Array(c.length);let _=0;switch(e.interpolation){case"STEP":for(let e=0;e0){const e=`${i.name||`animation${i.index}`}_channel${s.index}_${t}`;r.buildAnimations(l,e,o,d,((e,i)=>{++t,n(e,i)}))}}}))}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const i=t.interpolation||"LINEAR";switch(i){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const s=uL.Get(`${e}/input`,this._gltf.accessors,t.input),r=uL.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${s.index}`,s),this._loadFloatAccessorAsync(`/accessors/${r.index}`,r)]).then((([e,t])=>({input:e,interpolation:i,output:t}))),t._data}loadBufferAsync(e,t,i,s){const r=this._extensionsLoadBufferAsync(e,t,i,s);if(r)return r;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+i,s)}catch(t){throw new Error(`${e}: ${t.message}`)}}))}loadBufferViewAsync(e,t){const i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;const s=uL.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,t,i){if(t._data)return t._data;const s=dL._GetNumComponents(e,t.type),r=s*er.GetTypeByteLength(t.componentType),n=s*t.count;if(null==t.bufferView)t._data=Promise.resolve(new i(n));else{const o=uL.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then((a=>{if(5126!==t.componentType||t.normalized||o.byteStride&&o.byteStride!==r){const e=new i(n);return er.ForEach(a,t.byteOffset||0,o.byteStride||r,s,t.componentType,e.length,t.normalized||!1,((t,i)=>{e[i]=t})),e}return dL._GetTypedArray(e,t.componentType,a,t.byteOffset,n)}))}if(t.sparse){const n=t.sparse;t._data=t._data.then((o=>{const a=o,l=uL.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,n.indices.bufferView),h=uL.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,n.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${l.index}`,l),this.loadBufferViewAsync(`/bufferViews/${h.index}`,h)]).then((([o,l])=>{const h=dL._GetTypedArray(`${e}/sparse/indices`,n.indices.componentType,o,n.indices.byteOffset,n.count),c=s*n.count;let u;if(5126!==t.componentType||t.normalized){const o=dL._GetTypedArray(`${e}/sparse/values`,t.componentType,l,n.values.byteOffset,c);u=new i(c),er.ForEach(o,0,r,s,t.componentType,u.length,t.normalized||!1,((e,t)=>{u[t]=e}))}else u=dL._GetTypedArray(`${e}/sparse/values`,t.componentType,l,n.values.byteOffset,c);let d=0;for(let e=0;edL._GetTypedArray(e,t.componentType,i,t.byteOffset,t.count)))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then((e=>new Js(t,e,!1))),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){if(t._babylonVertexBuffer?.[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const s=this._babylonScene.getEngine();if(t.sparse||null==t.bufferView)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new er(s,e,i,!1)));else{const r=uL.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(r).then((n=>{const o=dL._GetNumComponents(e,t.type);return new er(s,n,i,!1,void 0,r.byteStride,void 0,t.byteOffset,o,t.componentType,t.normalized,!0,void 0,!0)}))}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return t&&(t.baseColorFactor?(i.albedoColor=Ee.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=Ee.White(),i.metallic=null==t.metallicFactor?1:t.metallicFactor,i.roughness=null==t.roughnessFactor?1:t.roughnessFactor,t.baseColorTexture&&s.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e}))),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,(e=>{e.name=`${i.name} (Metallic Roughness)`,i.metallicTexture=e}))),i.useMetallnessFromMetallicTextureBlue=!0,i.useRoughnessFromMetallicTextureGreen=!0,i.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(s).then((()=>{}))}_loadMaterialAsync(e,t,i,s,r=(()=>{})){const n=this._extensionsLoadMaterialAsync(e,t,i,s,r);if(n)return n;t._data=t._data||{};let o=t._data[s];if(!o){this.logOpen(`${e} ${t.name||""}`);const i=this.createMaterial(e,t,s);o={babylonMaterial:i,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,i)},t._data[s]=o,dL.AddPointerMetadata(i,e),this._parent.onMaterialLoadedObservable.notifyObservers(i),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce((()=>{const e=o.babylonMeshes.indexOf(i);-1!==e&&o.babylonMeshes.splice(e,1)}))),r(o.babylonMaterial),o.promise.then((()=>o.babylonMaterial))}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new zg(e,this._babylonScene);return i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,i.fillMode=t,i.enableSpecularAntiAliasing=!0,i.useRadianceOverAlpha=!this._parent.transparencyAsCoverage,i.useSpecularOverAlpha=!this._parent.transparencyAsCoverage,i.transparencyMode=zg.PBRMATERIAL_OPAQUE,i.metallic=1,i.roughness=1,i}createMaterial(e,t,i){const s=this._extensionsCreateMaterial(e,t,i);if(s)return s;const r=t.name||`material${t.index}`;return this._createDefaultMaterial(r,i)}loadMaterialPropertiesAsync(e,t,i){const s=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(s)return s;const r=new Array;return r.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&r.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then((()=>{}))}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.emissiveColor=t.emissiveFactor?Ee.FromArray(t.emissiveFactor):new Ee(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,(e=>{e.name=`${i.name} (Normal)`,i.bumpTexture=e}))),i.invertNormalMapX=!this._babylonScene.useRightHandedSystem,i.invertNormalMapY=this._babylonScene.useRightHandedSystem,null!=t.normalTexture.scale&&i.bumpTexture&&(i.bumpTexture.level=t.normalTexture.scale),i.forceIrradianceInFragment=!0),t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,(e=>{e.name=`${i.name} (Occlusion)`,i.ambientTexture=e}))),i.useAmbientInGrayScale=!0,null!=t.occlusionTexture.strength&&(i.ambientTextureStrength=t.occlusionTexture.strength)),t.emissiveTexture&&s.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,(e=>{e.name=`${i.name} (Emissive)`,i.emissiveTexture=e}))),Promise.all(s).then((()=>{}))}loadMaterialAlphaProperties(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":i.transparencyMode=zg.PBRMATERIAL_OPAQUE,i.alpha=1;break;case"MASK":i.transparencyMode=zg.PBRMATERIAL_ALPHATEST,i.alphaCutOff=null==t.alphaCutoff?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break;case"BLEND":i.transparencyMode=zg.PBRMATERIAL_ALPHABLEND,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0,i.useAlphaFromAlbedoTexture=!0);break;default:throw new Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(e,t,i=(()=>{})){const s=this._extensionsLoadTextureInfoAsync(e,t,i);if(s)return s;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const r=uL.Get(`${e}/index`,this._gltf.textures,t.index);r._textureInfo=t;const n=this._loadTextureAsync(`/textures/${t.index}`,r,(s=>{s.coordinatesIndex=t.texCoord||0,dL.AddPointerMetadata(s,e),this._parent.onTextureLoadedObservable.notifyObservers(s),i(s)}));return this.logClose(),n}_loadTextureAsync(e,t,i=(()=>{})){const s=this._extensionsLoadTextureAsync(e,t,i);if(s)return s;this.logOpen(`${e} ${t.name||""}`);const r=null==t.sampler?dL.DefaultSampler:uL.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),n=uL.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,r,n,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,s=(()=>{}),r,n){const o=this._loadSampler(`/samplers/${t.index}`,t),a=new Array,l=new VI;this._babylonScene._blockEntityCollection=!!this._assetContainer;const h={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||l.resolve()},onError:(t,i)=>{this._disposed||l.reject(new Error(`${e}: ${i&&i.message?i.message:t||"Failed to load texture"}`))},mimeType:i.mimeType,loaderOptions:r,useSRGBBuffer:!!n&&this._parent.useSRGBBuffers},c=new Pa(null,this._babylonScene,h);return c._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.push(l.promise),a.push(this.loadImageAsync(`/images/${i.index}`,i).then((e=>{const t=i.uri||`${this._fileName}#image${i.index}`,s=`data:${this._uniqueRootUrl}${t}`;c.updateURL(s,e)}))),c.wrapU=o.wrapU,c.wrapV=o.wrapV,s(c),Promise.all(a).then((()=>c))}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:dL._GetTextureSamplingMode(e,t),wrapU:dL._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:dL._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 i=uL.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}this.logClose()}return t._data}loadUriAsync(e,t,i){const s=this._extensionsLoadUriAsync(e,t,i);if(s)return s;if(!dL._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if(gs(i)){const t=new Uint8Array(xs(i));return this.log(`${e}: Decoded ${i.substr(0,64)}... (${t.length} bytes)`),Promise.resolve(t)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then((t=>new Promise(((s,r)=>{this._parent._loadFile(this._babylonScene,t,(t=>{this._disposed||(this.log(`${e}: Loaded ${i} (${t.byteLength} bytes)`),s(new Uint8Array(t)))}),!0,(t=>{r(new as(`${e}: Failed to load '${i}'${t?": "+t.status+" "+t.statusText:""}`,t))}))}))))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const i=e._internalMetadata=e._internalMetadata||{},s=i.gltf=i.gltf||{};(s.pointers=s.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=null==t?10497:t){case 33071:return Pa.CLAMP_ADDRESSMODE;case 33648:return Pa.MIRROR_ADDRESSMODE;case 10497:return Pa.WRAP_ADDRESSMODE;default:return Ne.Warn(`${e}: Invalid value (${t})`),Pa.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const i=null==t.magFilter?9729:t.magFilter,s=null==t.minFilter?9987:t.minFilter;if(9729===i)switch(s){case 9728:return Pa.LINEAR_NEAREST;case 9729:return Pa.LINEAR_LINEAR;case 9984:return Pa.LINEAR_NEAREST_MIPNEAREST;case 9985:return Pa.LINEAR_LINEAR_MIPNEAREST;case 9986:return Pa.LINEAR_NEAREST_MIPLINEAR;case 9987:return Pa.LINEAR_LINEAR_MIPLINEAR;default:return Ne.Warn(`${e}/minFilter: Invalid value (${s})`),Pa.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==i&&Ne.Warn(`${e}/magFilter: Invalid value (${i})`),s){case 9728:return Pa.NEAREST_NEAREST;case 9729:return Pa.NEAREST_LINEAR;case 9984:return Pa.NEAREST_NEAREST_MIPNEAREST;case 9985:return Pa.NEAREST_LINEAR_MIPNEAREST;case 9986:return Pa.NEAREST_NEAREST_MIPLINEAR;case 9987:return Pa.NEAREST_LINEAR_MIPLINEAR;default:return Ne.Warn(`${e}/minFilter: Invalid value (${s})`),Pa.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){switch(t){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`${e}: Invalid component type ${t}`)}}static _GetTypedArray(e,t,i,s,r){const n=i.buffer;s=i.byteOffset+(s||0);const o=dL._GetTypedArrayConstructor(`${e}/componentType`,t),a=er.GetTypeByteLength(t);return s%a!=0?(Ne.Warn(`${e}: Copying buffer as byte offset (${s}) is not a multiple of component type byte length (${a})`),new o(n.slice(s,s+r*a),0)):new o(n,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 Ds.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,t){switch(null==t&&(t=4),t){case 0:return ta.PointListDrawMode;case 1:return ta.LineListDrawMode;case 2:return ta.LineLoopDrawMode;case 3:return ta.LineStripDrawMode;case 4:return ta.TriangleFillMode;case 5:return ta.TriangleStripDrawMode;case 6:return ta.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${t})`)}_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 i in t._data){const s=t._data[i];for(const t of s.babylonMeshes){t.computeWorldMatrix(!0);const i=s.babylonMaterial;e.push(i.forceCompilationAsync(t)),e.push(i.forceCompilationAsync(t,{useInstances:!0})),this._parent.useClipPlane&&(e.push(i.forceCompilationAsync(t,{clipPlane:!0})),e.push(i.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 i of t){const t=i.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,i){for(const s of this._extensions)if(s.enabled){const r=`${s.name}.${t}`,n=e;n._activeLoaderExtensionFunctions=n._activeLoaderExtensionFunctions||{};const o=n._activeLoaderExtensionFunctions;if(!o[r]){o[r]=!0;try{const e=i(s);if(e)return e}finally{delete o[r]}}}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",(i=>i.loadSceneAsync&&i.loadSceneAsync(e,t)))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",(s=>s.loadNodeAsync&&s.loadNodeAsync(e,t,i)))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",(s=>s.loadCameraAsync&&s.loadCameraAsync(e,t,i)))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",(s=>s._loadVertexDataAsync&&s._loadVertexDataAsync(e,t,i)))}_extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n){return this._applyExtensions(r,"loadMeshPrimitive",(o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,s,r,n)))}_extensionsLoadMaterialAsync(e,t,i,s,r){return this._applyExtensions(t,"loadMaterial",(n=>n._loadMaterialAsync&&n._loadMaterialAsync(e,t,i,s,r)))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",(s=>s.createMaterial&&s.createMaterial(e,t,i)))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",(s=>s.loadMaterialPropertiesAsync&&s.loadMaterialPropertiesAsync(e,t,i)))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",(s=>s.loadTextureInfoAsync&&s.loadTextureInfoAsync(e,t,i)))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",(s=>s._loadTextureAsync&&s._loadTextureAsync(e,t,i)))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",(i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t)))}_extensionsLoadAnimationChannelAsync(e,t,i,s,r){return this._applyExtensions(i,"loadAnimationChannel",(n=>n._loadAnimationChannelAsync&&n._loadAnimationChannelAsync(e,t,i,s,r)))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",(s=>s._loadSkinAsync&&s._loadSkinAsync(e,t,i)))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",(s=>s._loadUriAsync&&s._loadUriAsync(e,t,i)))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",(i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t)))}_extensionsLoadBufferAsync(e,t,i,s){return this._applyExtensions(t,"loadBuffer",(r=>r.loadBufferAsync&&r.loadBufferAsync(e,t,i,s)))}static LoadExtensionAsync(e,t,i,s){if(!t.extensions)return null;const r=t.extensions[i];return r?s(`${e}/extensions/${i}`,r):null}static LoadExtraAsync(e,t,i,s){if(!t.extras)return null;const r=t.extras[i];return r?s(`${e}/extras/${i}`,r):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)}}dL._RegisteredExtensions={},dL.DefaultSampler={index:-1},FF._CreateGLTF2Loader=e=>new dL(e);const _L="EXT_lights_image_based";class pL{constructor(e){this.name=_L,this._loader=e,this.enabled=this._loader.isExtensionUsed(_L)}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 dL.LoadExtensionAsync(e,t,this.name,((i,s)=>{this._loader._allMaterialsDirtyRequired=!0;const r=new Array;r.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const n=uL.Get(`${i}/light`,this._lights,s.light);return r.push(this._loadLightAsync(`/extensions/${this.name}/lights/${s.light}`,n).then((e=>{this._loader.babylonScene.environmentTexture=e}))),this._loader.logClose(),Promise.all(r).then((()=>{}))}))}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const s=new Array(t.specularImages.length);for(let r=0;r{s[r][t]=e}))),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then((()=>{const i=new Cb(this._loader.babylonScene,null,t.specularImageSize);if(i.name=t.name||"environment",t._babylonTexture=i,null!=t.intensity&&(i.level=t.intensity),t.rotation){let e=fe.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(e=fe.Inverse(e)),me.FromQuaternionToRef(e,i.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const r=Q_.FromArray(t.irradianceCoefficients);r.scaleInPlace(t.intensity),r.convertIrradianceToLambertianRadiance();const n=j_.FromHarmonics(r),o=(s.length-1)/be.Log2(t.specularImageSize);return i.updateRGBDAsync(s,n,o)}))}return t._loaded.then((()=>t._babylonTexture))}}dL.RegisterExtension(_L,(e=>new pL(e)));const fL="EXT_mesh_gpu_instancing";class mL{constructor(e){this.name=fL,this._loader=e,this.enabled=this._loader.isExtensionUsed(fL)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((e,s)=>{this._loader._disableInstancedMesh++;const r=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return r;const n=new Array;let o=0;const a=t=>{if(null==s.attributes[t])return void n.push(Promise.resolve(null));const i=uL.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,s.attributes[t]);if(n.push(this._loader._loadFloatAccessorAsync(`/accessors/${i.bufferView}`,i)),0===o)o=i.count;else if(o!==i.count)throw new Error(`${e}/attributes: Instance buffer accessors do not have the same count.`)};return a("TRANSLATION"),a("ROTATION"),a("SCALE"),r.then((e=>Promise.all(n).then((([i,s,r])=>{const n=new Float32Array(16*o);ve.Vector3[0].copyFromFloats(0,0,0),ve.Quaternion[0].copyFromFloats(0,0,0,1),ve.Vector3[1].copyFromFloats(1,1,1);for(let e=0;enew mL(e)));const gL="EXT_meshopt_compression";class vL{constructor(e){this.name=gL,this.enabled=e.isExtensionUsed(gL),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return dL.LoadExtensionAsync(e,t,this.name,((i,s)=>{const r=t;if(r._meshOptData)return r._meshOptData;const n=uL.Get(`${e}/buffer`,this._loader.gltf.buffers,s.buffer);return r._meshOptData=this._loader.loadBufferAsync(`/buffers/${n.index}`,n,s.byteOffset||0,s.byteLength).then((e=>Ky.Default.decodeGltfBufferAsync(e,s.count,s.byteStride,s.mode,s.filter))),r._meshOptData}))}}dL.RegisterExtension(gL,(e=>new vL(e)));const xL="EXT_texture_webp";class bL{constructor(e){this.name=xL,this._loader=e,this.enabled=e.isExtensionUsed(xL)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=null==t.sampler?dL.DefaultSampler:uL.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=uL.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}dL.RegisterExtension(xL,(e=>new bL(e)));const TL="EXT_texture_avif";class yL{constructor(e){this.name=TL,this._loader=e,this.enabled=e.isExtensionUsed(TL)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=null==t.sampler?dL.DefaultSampler:uL.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=uL.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}dL.RegisterExtension(TL,(e=>new yL(e)));const SL="KHR_draco_mesh_compression";class CL{constructor(e){this.name=SL,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=jy.DecoderAvailable&&this._loader.isExtensionUsed(SL)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{if(null!=t.mode&&4!==t.mode&&5!==t.mode)throw new Error(`${e}: Unsupported mode ${t.mode}`);const n={},o={},a=(e,s)=>{const a=r.attributes[e];if(null!=a&&(i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(s)&&i._delayInfo.push(s),n[s]=a,this.useNormalizedFlagFromAccessor)){const i=uL.TryGet(this._loader.gltf.accessors,t.attributes[e]);i&&(o[s]=i.normalized||!1)}};a("POSITION",er.PositionKind),a("NORMAL",er.NormalKind),a("TANGENT",er.TangentKind),a("TEXCOORD_0",er.UVKind),a("TEXCOORD_1",er.UV2Kind),a("TEXCOORD_2",er.UV3Kind),a("TEXCOORD_3",er.UV4Kind),a("TEXCOORD_4",er.UV5Kind),a("TEXCOORD_5",er.UV6Kind),a("JOINTS_0",er.MatricesIndicesKind),a("WEIGHTS_0",er.MatricesWeightsKind),a("COLOR_0",er.ColorKind);const l=uL.Get(s,this._loader.gltf.bufferViews,r.bufferView);return l._dracoBabylonGeometry||(l._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${l.index}`,l).then((t=>(this.dracoCompression||jy.Default)._decodeMeshToGeometryForGltfAsync(i.name,this._loader.babylonScene,t,n,o).catch((t=>{throw new Error(`${e}: ${t.message}`)}))))),l._dracoBabylonGeometry}))}}dL.RegisterExtension(SL,(e=>new CL(e)));const EL="KHR_lights_punctual";class AL{constructor(e){this.name=EL,this._loader=e,this.enabled=this._loader.isExtensionUsed(EL)}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,uL.Assign(this._lights)}}loadNodeAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>(this._loader._allMaterialsDirtyRequired=!0,this._loader.loadNodeAsync(e,t,(e=>{let t;const n=uL.Get(s,this._lights,r.light),o=n.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,n.type){case"directional":{const e=new cg(o,_e.Backward(),this._loader.babylonScene);e.position.setAll(0),t=e;break}case"point":t=new ex(o,_e.Zero(),this._loader.babylonScene);break;case"spot":{const e=new _g(o,_e.Zero(),_e.Backward(),0,1,this._loader.babylonScene);e.angle=2*(n.spot&&n.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(n.spot&&n.spot.innerConeAngle||0),t=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${s}: Invalid light type (${n.type})`)}t._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,n._babylonLight=t,t.falloffType=ua.FALLOFF_GLTF,t.diffuse=n.color?Ee.FromArray(n.color):Ee.White(),t.intensity=null==n.intensity?1:n.intensity,t.range=null==n.range?Number.MAX_VALUE:n.range,t.parent=e,this._loader._babylonLights.push(t),dL.AddPointerMetadata(t,s),i(e)})))))}}dL.RegisterExtension(EL,(e=>new AL(e)));const PL="KHR_materials_pbrSpecularGlossiness";class IL{constructor(e){this.name=PL,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(PL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loadSpecularGlossinessPropertiesAsync(s,r,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(n).then((()=>{}))}))}_loadSpecularGlossinessPropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.metallic=null,i.roughness=null,t.diffuseFactor?(i.albedoColor=Ee.FromArray(t.diffuseFactor),i.alpha=t.diffuseFactor[3]):i.albedoColor=Ee.White(),i.reflectivityColor=t.specularFactor?Ee.FromArray(t.specularFactor):Ee.White(),i.microSurface=null==t.glossinessFactor?1:t.glossinessFactor,t.diffuseTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,t.diffuseTexture,(e=>{e.name=`${i.name} (Diffuse)`,i.albedoTexture=e}))),t.specularGlossinessTexture&&(s.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,t.specularGlossinessTexture,(e=>{e.name=`${i.name} (Specular Glossiness)`,i.reflectivityTexture=e,i.reflectivityTexture.hasAlpha=!0}))),i.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(s).then((()=>{}))}}dL.RegisterExtension(PL,(e=>new IL(e)));const RL="KHR_materials_unlit";class ML{constructor(e){this.name=RL,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(RL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,(()=>this._loadUnlitPropertiesAsync(e,t,i)))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;i.unlit=!0;const r=t.pbrMetallicRoughness;return r&&(r.baseColorFactor?(i.albedoColor=Ee.FromArray(r.baseColorFactor),i.alpha=r.baseColorFactor[3]):i.albedoColor=Ee.White(),r.baseColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,r.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e})))),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then((()=>{}))}}dL.RegisterExtension(RL,(e=>new ML(e)));const OL="KHR_materials_clearcoat";class DL{constructor(e){this.name=OL,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(OL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadClearCoatPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.clearCoat.isEnabled=!0,i.clearCoat.useRoughnessFromMainTexture=!1,i.clearCoat.remapF0OnInterfaceChange=!1,null!=t.clearcoatFactor?i.clearCoat.intensity=t.clearcoatFactor:i.clearCoat.intensity=0,t.clearcoatTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,(e=>{e.name=`${i.name} (ClearCoat Intensity)`,i.clearCoat.texture=e}))),null!=t.clearcoatRoughnessFactor?i.clearCoat.roughness=t.clearcoatRoughnessFactor:i.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,(e=>{e.name=`${i.name} (ClearCoat Roughness)`,i.clearCoat.textureRoughness=e})))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,(e=>{e.name=`${i.name} (ClearCoat Normal)`,i.clearCoat.bumpTexture=e}))),i.invertNormalMapX=!i.getScene().useRightHandedSystem,i.invertNormalMapY=i.getScene().useRightHandedSystem,null!=t.clearcoatNormalTexture.scale&&(i.clearCoat.bumpTexture.level=t.clearcoatNormalTexture.scale)),Promise.all(s).then((()=>{}))}}dL.RegisterExtension(OL,(e=>new DL(e)));const wL="KHR_materials_iridescence";class NL{constructor(e){this.name=wL,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(wL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.iridescence.isEnabled=!0,i.iridescence.intensity=t.iridescenceFactor??0,i.iridescence.indexOfRefraction=t.iridescenceIor??t.iridescenceIOR??1.3,i.iridescence.minimumThickness=t.iridescenceThicknessMinimum??100,i.iridescence.maximumThickness=t.iridescenceThicknessMaximum??400,t.iridescenceTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,(e=>{e.name=`${i.name} (Iridescence Intensity)`,i.iridescence.texture=e}))),t.iridescenceThicknessTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,(e=>{e.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=e}))),Promise.all(s).then((()=>{}))}}dL.RegisterExtension(wL,(e=>new NL(e)));const FL="KHR_materials_anisotropy";class LL{constructor(e){this.name=FL,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(FL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.anisotropy.isEnabled=!0,i.anisotropy.intensity=t.anisotropyStrength??0,i.anisotropy.angle=t.anisotropyRotation??0,t.anisotropyTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,(e=>{e.name=`${i.name} (Anisotropy Intensity)`,i.anisotropy.texture=e}))),Promise.all(s).then((()=>{}))}}dL.RegisterExtension(FL,(e=>new LL(e)));const BL="KHR_materials_emissive_strength";class kL{constructor(e){this.name=BL,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(BL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then((()=>{this._loadEmissiveProperties(s,r,i)}))))}_loadEmissiveProperties(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);void 0!==t.emissiveStrength&&(i.emissiveIntensity=t.emissiveStrength)}}dL.RegisterExtension(BL,(e=>new kL(e)));const VL="KHR_materials_sheen";class UL{constructor(e){this.name=VL,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(VL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSheenPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.sheen.isEnabled=!0,i.sheen.intensity=1,null!=t.sheenColorFactor?i.sheen.color=Ee.FromArray(t.sheenColorFactor):i.sheen.color=Ee.Black(),t.sheenColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,t.sheenColorTexture,(e=>{e.name=`${i.name} (Sheen Color)`,i.sheen.texture=e}))),void 0!==t.sheenRoughnessFactor?i.sheen.roughness=t.sheenRoughnessFactor:i.sheen.roughness=0,t.sheenRoughnessTexture&&(t.sheenRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,t.sheenRoughnessTexture,(e=>{e.name=`${i.name} (Sheen Roughness)`,i.sheen.textureRoughness=e})))),i.sheen.albedoScaling=!0,i.sheen.useRoughnessFromMainTexture=!1,Promise.all(s).then((()=>{}))}}dL.RegisterExtension(VL,(e=>new UL(e)));const GL="KHR_materials_specular";class zL{constructor(e){this.name=GL,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(GL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSpecularPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const s=new Array;return void 0!==t.specularFactor&&(i.metallicF0Factor=t.specularFactor),void 0!==t.specularColorFactor&&(i.metallicReflectanceColor=Ee.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,(e=>{e.name=`${i.name} (Specular F0 Strength)`,i.metallicReflectanceTexture=e,i.useOnlyMetallicFromMetallicReflectanceTexture=!0})))),t.specularColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,(e=>{e.name=`${i.name} (Specular F0 Color)`,i.reflectanceTexture=e}))),Promise.all(s).then((()=>{}))}}dL.RegisterExtension(GL,(e=>new zL(e)));const WL="KHR_materials_ior";class HL{constructor(e){this.name=WL,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(WL)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIorPropertiesAsync(s,r,i)),Promise.all(n).then((()=>{}))}))}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);return void 0!==t.ior?i.indexOfRefraction=t.ior:i.indexOfRefraction=HL._DEFAULT_IOR,Promise.resolve()}}HL._DEFAULT_IOR=1.5,dL.RegisterExtension(WL,(e=>new HL(e)));const XL="KHR_materials_variants";class YL{constructor(e){this.name=XL,this._loader=e,this.enabled=this._loader.isExtensionUsed(XL)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return YL.GetAvailableVariants(e)}static SelectVariant(e,t){const i=this._GetExtensionMetadata(e);if(!i)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${XL} extension`);const s=e=>{const t=i.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);i.lastSelected=t}selectVariant(e,t){YL.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 ${XL} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(e){YL.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 ${XL} extension`);return t.lastSelected}getLastSelectedVariant(e){return YL.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){return e?._internalMetadata?.gltf?.[XL]||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}_loadMeshPrimitiveAsync(e,t,i,s,r,n){return dL.LoadExtensionAsync(e,r,this.name,((o,a)=>{const l=new Array;return l.push(this._loader._loadMeshPrimitiveAsync(e,t,i,s,r,(t=>{if(n(t),t instanceof ha){const i=dL._GetDrawMode(e,r.mode),s=this._loader.rootBabylonMesh,n=s?s._internalMetadata=s._internalMetadata||{}:{},h=n.gltf=n.gltf||{},c=h[XL]=h[XL]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:t,material:t.material});for(let e=0;e{for(let i=0;i{const i=e;let r=null,n=i;do{if(n=n.parent,!n)return;r=YL._GetExtensionMetadata(n)}while(null===r);if(s&&r===YL._GetExtensionMetadata(s)){n._internalMetadata={};for(const e in s._internalMetadata)n._internalMetadata[e]=s._internalMetadata[e];n._internalMetadata.gltf=[];for(const e in s._internalMetadata.gltf)n._internalMetadata.gltf[e]=s._internalMetadata.gltf[e];n._internalMetadata.gltf[XL]={lastSelected:null,original:[],variants:{}};for(const e of r.original)n._internalMetadata.gltf[XL].original.push({mesh:e.mesh,material:e.material});for(const e in r.variants)if(Object.prototype.hasOwnProperty.call(r.variants,e)){n._internalMetadata.gltf[XL].variants[e]=[];for(const t of r.variants[e])n._internalMetadata.gltf[XL].variants[e].push({mesh:t.mesh,material:t.material})}r=n._internalMetadata.gltf[XL]}for(const e of r.original)e.mesh===t&&(e.mesh=i);for(const e of r.variants[o.name])e.mesh===t&&(e.mesh=i)}))}})))}}}))),Promise.all(l).then((([e])=>e))}))}}dL.RegisterExtension(XL,(e=>new YL(e)));class QL{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:N_.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...QL._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new K,this._scene.onDisposeObservable.addOnce((()=>{this.dispose()})),this._parseScene(),this._setupRenderTargets()}updateOptions(e){if(!Object.keys(e).filter((t=>this._options[t]!==e[t])).length)return;const t={...this._options,...e},i=this._options;this._options=t,t.renderSize===i.renderSize&&t.renderTargetTextureType===i.renderTargetTextureType&&t.generateMipmaps===i.generateMipmaps&&this._opaqueRenderTarget?(this._opaqueRenderTarget.samples=t.samples,this._opaqueRenderTarget.lodGenerationScale=t.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=t.lodGenerationOffset):this._setupRenderTargets()}getOpaqueTarget(){return this._opaqueRenderTarget}_shouldRenderAsTransmission(e){return!!e&&!!(e instanceof zg&&e.subSurface.isRefractionEnabled)}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),Ds.SetImmediate((()=>{this._shouldRenderAsTransmission(e.material)?(e.material.refractionTexture=this._opaqueRenderTarget,-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)}_parseScene(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))}_onMeshMaterialChanged(e){const t=this._transparentMeshesCache.indexOf(e),i=this._opaqueMeshesCache.indexOf(e);this._shouldRenderAsTransmission(e.material)?(e.material instanceof zg&&(e.material.subSurface.refractionTexture=this._opaqueRenderTarget),-1!==i?(this._opaqueMeshesCache.splice(i,1),this._transparentMeshesCache.push(e)):-1===t&&this._transparentMeshesCache.push(e)):-1!==t?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):-1===i&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){return null!==this._opaqueRenderTarget?.getInternalTexture()}_setupRenderTargets(){let e,t;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new ih("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.clearColor=this._options.clearColor?.clone()??this._scene.clearColor.clone(),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.onBeforeBindObservable.add((i=>{t=this._scene.environmentIntensity,this._scene.environmentIntensity=1,e=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?i.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(i.clearColor,this._scene.getEngine().useExactSrgbConversions),this._scene.imageProcessingConfiguration._applyByPostProcess=!0})),this._opaqueRenderTarget.onAfterUnbindObservable.add((()=>{this._scene.environmentIntensity=t,this._scene.imageProcessingConfiguration._applyByPostProcess=e})),this._transparentMeshesCache.forEach((e=>{this._shouldRenderAsTransmission(e.material)&&(e.material.refractionTexture=this._opaqueRenderTarget)}))}dispose(){this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[]}}const jL="KHR_materials_transmission";class KL{constructor(e){this.name=jL,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(jL),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTransparentPropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadTransparentPropertiesAsync(e,t,i,s){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isRefractionEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.useAlbedoToTintRefraction=!0,void 0===s.transmissionFactor)return r.subSurface.refractionIntensity=0,r.subSurface.isRefractionEnabled=!1,Promise.resolve();{r.subSurface.refractionIntensity=s.transmissionFactor;const e=r.getScene();r.subSurface.refractionIntensity&&!e._transmissionHelper?new QL({},r.getScene()):r.subSurface.refractionIntensity&&!e._transmissionHelper?._isRenderTargetValid()&&e._transmissionHelper?._setupRenderTargets()}return r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,s.transmissionTexture?(s.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,s.transmissionTexture,void 0).then((e=>{r.subSurface.refractionIntensityTexture=e,r.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}dL.RegisterExtension(jL,(e=>new KL(e)));const $L="KHR_materials_diffuse_transmission";class qL{constructor(e){this.name=$L,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed($L),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTranslucentPropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadTranslucentPropertiesAsync(e,t,i,s){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isTranslucencyEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,r.subSurface.useAlbedoToTintTranslucency=!1,void 0===s.diffuseTransmissionFactor)return r.subSurface.translucencyIntensity=0,r.subSurface.isTranslucencyEnabled=!1,Promise.resolve();r.subSurface.translucencyIntensity=s.diffuseTransmissionFactor;const n=new Array;return r.subSurface.useGltfStyleTextures=!0,s.diffuseTransmissionTexture&&(s.diffuseTransmissionTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,s.diffuseTransmissionTexture).then((e=>{r.subSurface.translucencyIntensityTexture=e})))),void 0!==s.diffuseTransmissionColorFactor?r.subSurface.translucencyColor=Ee.FromArray(s.diffuseTransmissionColorFactor):r.subSurface.translucencyColor=Ee.White(),s.diffuseTransmissionColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,s.diffuseTransmissionColorTexture).then((e=>{r.subSurface.translucencyColorTexture=e}))),Promise.all(n).then((()=>{}))}}dL.RegisterExtension($L,(e=>new qL(e)));const ZL="KHR_materials_volume";class JL{constructor(e){this.name=ZL,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(ZL),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadVolumePropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadVolumePropertiesAsync(e,t,i,s){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);if(!i.subSurface.isRefractionEnabled&&!i.subSurface.isTranslucencyEnabled||!s.thicknessFactor)return Promise.resolve();i.subSurface.volumeIndexOfRefraction=i.indexOfRefraction;const r=void 0!==s.attenuationDistance?s.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=r,void 0!==s.attenuationColor&&3==s.attenuationColor.length&&i.subSurface.tintColor.copyFromFloats(s.attenuationColor[0],s.attenuationColor[1],s.attenuationColor[2]),i.subSurface.minimumThickness=0,i.subSurface.maximumThickness=s.thicknessFactor,i.subSurface.useThicknessAsDepth=!0,s.thicknessTexture?(s.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,s.thicknessTexture).then((e=>{i.subSurface.thicknessTexture=e,i.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}dL.RegisterExtension(ZL,(e=>new JL(e)));const eB="KHR_materials_dispersion";class tB{constructor(e){this.name=eB,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(eB)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadDispersionPropertiesAsync(s,t,i,r)),Promise.all(n).then((()=>{}))}))}_loadDispersionPropertiesAsync(e,t,i,s){if(!(i instanceof zg))throw new Error(`${e}: Material type not supported`);return i.subSurface.isRefractionEnabled&&s.dispersion?(i.subSurface.isDispersionEnabled=!0,i.subSurface.dispersion=s.dispersion,Promise.resolve()):Promise.resolve()}}dL.RegisterExtension(eB,(e=>new tB(e)));const iB="KHR_mesh_quantization";class sB{constructor(e){this.name=iB,this.enabled=e.isExtensionUsed(iB)}dispose(){}}dL.RegisterExtension(iB,(e=>new sB(e)));const rB="KHR_texture_basisu";class nB{constructor(e){this.name=rB,this._loader=e,this.enabled=e.isExtensionUsed(rB)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>{const n=null==t.sampler?dL.DefaultSampler:uL.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=uL.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,(e=>{i(e)}),t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}}dL.RegisterExtension(rB,(e=>new nB(e)));const oB="KHR_texture_transform";class aB{constructor(e){this.name=oB,this._loader=e,this.enabled=this._loader.isExtensionUsed(oB)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((s,r)=>this._loader.loadTextureInfoAsync(e,t,(e=>{if(!(e instanceof Pa))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),i(e)}))))}}dL.RegisterExtension(oB,(e=>new aB(e)));const lB="KHR_xmp_json_ld";class hB{constructor(e){this.name=lB,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(lB)}dispose(){this._loader=null}onLoading(){if(null===this._loader.rootBabylonMesh)return;const e=this._loader.gltf.extensions?.KHR_xmp_json_ld,t=this._loader.gltf.asset?.extensions?.KHR_xmp_json_ld;if(e&&t){const i=+t.packet;e.packets&&i2)),new gB(Ft.ANIMATIONTYPE_FLOAT,`${e}.vScale`,_B,(()=>2))],offset:[new gB(Ft.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,uB,(()=>2)),new gB(Ft.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,_B,(()=>2))],rotation:[new gB(Ft.ANIMATIONTYPE_FLOAT,`${e}.wAng`,dB,(()=>1))]}}dL.RegisterExtension(lB,(e=>new hB(e)));class mB extends aL{buildAnimations(e,t,i,s,r){r(e._babylonCamera,this._buildAnimation(t,i,s))}}class gB extends aL{buildAnimations(e,t,i,s,r){for(const n in e._data)r(e._data[n].babylonMaterial,this._buildAnimation(t,i,s))}}class vB extends aL{buildAnimations(e,t,i,s,r){r(e._babylonLight,this._buildAnimation(t,i,s))}}const xB={__array__:{__target__:!0,...hL}},bB={__array__:{__target__:!0,orthographic:{xmag:[new mB(Ft.ANIMATIONTYPE_FLOAT,"orthoLeft",dB,(()=>1)),new mB(Ft.ANIMATIONTYPE_FLOAT,"orthoRight",_B,(()=>1))],ymag:[new mB(Ft.ANIMATIONTYPE_FLOAT,"orthoBottom",dB,(()=>1)),new mB(Ft.ANIMATIONTYPE_FLOAT,"orthoTop",_B,(()=>1))],zfar:[new mB(Ft.ANIMATIONTYPE_FLOAT,"maxZ",uB,(()=>1))],znear:[new mB(Ft.ANIMATIONTYPE_FLOAT,"minZ",uB,(()=>1))]},perspective:{yfov:[new mB(Ft.ANIMATIONTYPE_FLOAT,"fov",uB,(()=>1))],zfar:[new mB(Ft.ANIMATIONTYPE_FLOAT,"maxZ",uB,(()=>1))],znear:[new mB(Ft.ANIMATIONTYPE_FLOAT,"minZ",uB,(()=>1))]}}},TB={nodes:xB,materials:{__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new gB(Ft.ANIMATIONTYPE_COLOR3,"albedoColor",cB,(()=>4)),new gB(Ft.ANIMATIONTYPE_FLOAT,"alpha",(function(e,t,i,s){return t[i+3]*s}),(()=>4))],metallicFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"metallic",uB,(()=>1))],roughnessFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"roughness",uB,(()=>1))],baseColorTexture:{extensions:{KHR_texture_transform:fB("albedoTexture")}},metallicRoughnessTexture:{extensions:{KHR_texture_transform:fB("metallicTexture")}}},emissiveFactor:[new gB(Ft.ANIMATIONTYPE_COLOR3,"emissiveColor",cB,(()=>3))],normalTexture:{scale:[new gB(Ft.ANIMATIONTYPE_FLOAT,"bumpTexture.level",uB,(()=>1))],extensions:{KHR_texture_transform:fB("bumpTexture")}},occlusionTexture:{strength:[new gB(Ft.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",uB,(()=>1))],extensions:{KHR_texture_transform:fB("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:fB("emissiveTexture")}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:[new gB(Ft.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",uB,(()=>1))],anisotropyRotation:[new gB(Ft.ANIMATIONTYPE_FLOAT,"anisotropy.angle",uB,(()=>1))],anisotropyTexture:{extensions:{KHR_texture_transform:fB("anisotropy.texture")}}},KHR_materials_clearcoat:{clearcoatFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",uB,(()=>1))],clearcoatRoughnessFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",uB,(()=>1))],clearcoatTexture:{extensions:{KHR_texture_transform:fB("clearCoat.texture")}},clearcoatNormalTexture:{scale:[new gB(Ft.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",uB,(()=>1))],extensions:{KHR_texture_transform:fB("clearCoat.bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:fB("clearCoat.textureRoughness")}}},KHR_materials_dispersion:{dispersion:[new gB(Ft.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",uB,(()=>1))]},KHR_materials_emissive_strength:{emissiveStrength:[new gB(Ft.ANIMATIONTYPE_FLOAT,"emissiveIntensity",uB,(()=>1))]},KHR_materials_ior:{ior:[new gB(Ft.ANIMATIONTYPE_FLOAT,"indexOfRefraction",uB,(()=>1))]},KHR_materials_iridescence:{iridescenceFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"iridescence.intensity",uB,(()=>1))],iridescenceIor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",uB,(()=>1))],iridescenceThicknessMinimum:[new gB(Ft.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",uB,(()=>1))],iridescenceThicknessMaximum:[new gB(Ft.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",uB,(()=>1))],iridescenceTexture:{extensions:{KHR_texture_transform:fB("iridescence.texture")}},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:fB("iridescence.thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:[new gB(Ft.ANIMATIONTYPE_COLOR3,"sheen.color",cB,(()=>3))],sheenRoughnessFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"sheen.roughness",uB,(()=>1))],sheenColorTexture:{extensions:{KHR_texture_transform:fB("sheen.texture")}},sheenRoughnessTexture:{extensions:{KHR_texture_transform:fB("sheen.textureRoughness")}}},KHR_materials_specular:{specularFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"metallicF0Factor",uB,(()=>1))],specularColorFactor:[new gB(Ft.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",cB,(()=>3))],specularTexture:{extensions:{KHR_texture_transform:fB("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:fB("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",uB,(()=>1))],transmissionTexture:{extensions:{KHR_texture_transform:fB("subSurface.refractionIntensityTexture")}}},KHR_materials_volume:{attenuationColor:[new gB(Ft.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",cB,(()=>3))],attenuationDistance:[new gB(Ft.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",uB,(()=>1))],thicknessFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",uB,(()=>1))],thicknessTexture:{extensions:{KHR_texture_transform:fB("subSurface.thicknessTexture")}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:[new gB(Ft.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",uB,(()=>1))],diffuseTransmissionTexture:{extensions:{KHR_texture_transform:fB("subSurface.translucencyIntensityTexture")}},diffuseTransmissionColorFactor:[new gB(Ft.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",cB,(()=>3))],diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:fB("subSurface.translucencyColorTexture")}}}}}},cameras:bB,extensions:{KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new vB(Ft.ANIMATIONTYPE_COLOR3,"diffuse",cB,(()=>3))],intensity:[new vB(Ft.ANIMATIONTYPE_FLOAT,"intensity",uB,(()=>1))],range:[new vB(Ft.ANIMATIONTYPE_FLOAT,"range",uB,(()=>1))],spot:{innerConeAngle:[new vB(Ft.ANIMATIONTYPE_FLOAT,"innerAngle",pB,(()=>1))],outerConeAngle:[new vB(Ft.ANIMATIONTYPE_FLOAT,"angle",pB,(()=>1))]}}}}}};class yB{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t,i=this._gltf,s=this._infoTree;if(!e.startsWith("/"))throw new Error("Path must start with a /");const r=e.split("/");r.shift();for(const n of r){if(s.__array__)s=s.__array__;else if(s=s[n],!s)throw new Error(`Path ${e} is invalid`);if(void 0===i)throw new Error(`Path ${e} is invalid`);i=i[n],s.__target__&&(t=i)}return{object:t,info:s}}}const SB="KHR_animation_pointer";class CB extends yB{constructor(e){super(e,TB)}}class EB{constructor(e){this.name=SB,this._loader=e,this._pathToObjectConverter=new CB(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(SB)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,t,i,s,r){const n=s.target.extensions?.KHR_animation_pointer;if(!n||!this._pathToObjectConverter)return null;"pointer"!==s.target.path&&Ne.Warn(`${e}/target/path: Value (${s.target.path}) must be (pointer) when using the ${this.name} extension`),null!=s.target.node&&Ne.Warn(`${e}/target/node: Value (${s.target.node}) must not be present when using the ${this.name} extension`);const o=`${e}/extensions/${this.name}`,a=n.pointer;if(!a)throw new Error(`${o}: Pointer is missing`);try{const n=this._pathToObjectConverter.convert(a);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,n,r)}catch(e){return Ne.Warn(`${o}/pointer: Invalid pointer (${a}) skipped`),null}}}dL.RegisterExtension(SB,(e=>new EB(e)));const AB="MSFT_audio_emitter";class PB{constructor(e){this.name=AB,this._loader=e,this.enabled=this._loader.isExtensionUsed(AB)}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,uL.Assign(this._clips),uL.Assign(this._emitters)}}loadSceneAsync(e,t){return dL.LoadExtensionAsync(e,t,this.name,((i,s)=>{const r=new Array;r.push(this._loader.loadSceneAsync(e,t));for(const e of s.emitters){const t=uL.Get(`${i}/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(`${i}: Direction or Distance properties are not allowed on emitters attached to a scene`);r.push(this._loadEmitterAsync(`${i}/emitters/${t.index}`,t))}return Promise.all(r).then((()=>{}))}))}loadNodeAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((e,s)=>{const r=new Array;return this._loader.loadNodeAsync(e,t,(t=>{for(const i of s.emitters){const s=uL.Get(`${e}/emitters`,this._emitters,i);r.push(this._loadEmitterAsync(`${e}/emitters/${s.index}`,s).then((()=>{for(const e of s._babylonSounds)e.attachToMesh(t),null==s.innerAngle&&null==s.outerAngle||(e.setLocalDirectionToMesh(_e.Forward()),e.setDirectionalCone(2*Ds.ToDegrees(null==s.innerAngle?Math.PI:s.innerAngle),2*Ds.ToDegrees(null==s.outerAngle?Math.PI:s.outerAngle),0))})))}i(t)})).then((e=>Promise.all(r).then((()=>e))))}))}loadAnimationAsync(e,t){return dL.LoadExtensionAsync(e,t,this.name,((i,s)=>this._loader.loadAnimationAsync(e,t).then((r=>{const n=new Array;uL.Assign(s.events);for(const o of s.events)n.push(this._loadAnimationEventAsync(`${i}/events/${o.index}`,e,t,o,r));return Promise.all(n).then((()=>r))}))))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const s=uL.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);i=this._loader.loadBufferViewAsync(`/bufferViews/${s.index}`,s)}return t._objectURL=i.then((e=>URL.createObjectURL(new Blob([e],{type:t.mimeType})))),t._objectURL}_loadEmitterAsync(e,t){if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){const e=new Array,i=t.name||`emitter${t.index}`,s={loop:!1,autoplay:!1,volume:null==t.volume?1:t.volume};for(let r=0;r{const n=t._babylonSounds[r]=new ma(i,e,this._loader.babylonScene,null,s);n.refDistance=t.refDistance||1,n.maxDistance=t.maxDistance||256,n.rolloffFactor=t.rolloffFactor||1,n.distanceModel=t.distanceModel||"exponential"})))}const r=Promise.all(e).then((()=>{const e=t.clips.map((e=>e.weight||1)),i=new xa(t.loop||!1,t._babylonSounds,e);t.innerAngle&&(i.directionalConeInnerAngle=2*Ds.ToDegrees(t.innerAngle)),t.outerAngle&&(i.directionalConeOuterAngle=2*Ds.ToDegrees(t.outerAngle)),t.volume&&(i.volume=t.volume),t._babylonData.sound=i}));t._babylonData={loaded:r}}return t._babylonData.loaded}_getEventAction(e,t,i,s,r){switch(i){case"play":return e=>{const i=(r||0)+(e-s);t.play(i)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${i}`)}}_loadAnimationEventAsync(e,t,i,s,r){if(0==r.targetedAnimations.length)return Promise.resolve();const n=r.targetedAnimations[0],o=s.emitter,a=uL.Get(`/extensions/${this.name}/emitters`,this._emitters,o);return this._loadEmitterAsync(e,a).then((()=>{const t=a._babylonData.sound;if(t){const i=new fn(s.time,this._getEventAction(e,t,s.action,s.time,s.startOffset));n.animation.addEvent(i),r.onAnimationGroupEndObservable.add((()=>{t.stop()})),r.onAnimationGroupPauseObservable.add((()=>{t.pause()}))}}))}}dL.RegisterExtension(AB,(e=>new PB(e)));const IB="MSFT_lod";class RB{constructor(e){this.name=IB,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new K,this.onMaterialLODsLoadedObservable=new K,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.enabled=this._loader.isExtensionUsed(IB)}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{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{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 i=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),i}loadNodeAsync(e,t,i){return dL.LoadExtensionAsync(e,t,this.name,((e,s)=>{let r;const n=this._getLODs(e,t,this._loader.gltf.nodes,s.ids);this._loader.logOpen(`${e}`);for(let e=0;e{i(e),e.setEnabled(!1)},o=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,s).then((t=>{if(0!==e){const t=n[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=o:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(o))}return this._loader.logClose(),r}))}_loadMaterialAsync(e,t,i,s,r){return this._nodeIndexLOD?null:dL.LoadExtensionAsync(e,t,this.name,((e,n)=>{let o;const a=this._getLODs(e,t,this._loader.gltf.materials,n.ids);this._loader.logOpen(`${e}`);for(let e=0;e{0===e&&r(t)})).then((t=>{if(0!==e){r(t);const i=a[e-1]._data;i[s]&&(this._disposeMaterials([i[s].babylonMaterial]),delete i[s])}return t}));this._materialPromiseLODs[e]=this._materialPromiseLODs[e]||[],0===e?o=n:(this._materialIndexLOD=null,this._materialPromiseLODs[e].push(n))}return this._loader.logClose(),o}))}_loadUriAsync(e,t,i){if(null!==this._nodeIndexLOD){this._loader.log("deferred");const s=this._nodeIndexLOD-1;return this._nodeSignalLODs[s]=this._nodeSignalLODs[s]||new VI,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const s=this._materialIndexLOD-1;return this._materialSignalLODs[s]=this._materialSignalLODs[s]||new VI,this._materialSignalLODs[s].promise.then((()=>this._loader.loadUriAsync(e,t,i)))}return null}loadBufferAsync(e,t,i,s){if(this._loader.parent.useRangeRequests&&!t.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const t=(e,t)=>{const r=i,n=r+s-1;let o=e[t];return o?(o.start=Math.min(o.start,r),o.end=Math.max(o.end,n)):(o={start:r,end:n,loaded:new VI},e[t]=o),o.loaded.promise.then((e=>new Uint8Array(e.buffer,e.byteOffset+i-o.start,s)))};return this._loader.log("deferred"),null!==this._nodeIndexLOD?t(this._nodeBufferLODs,this._nodeIndexLOD):null!==this._materialIndexLOD?t(this._materialBufferLODs,this._materialIndexLOD):t(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const i=e[t];i&&(this._loader.log(`Loading buffer range [${i.start}-${i.end}]`),this._loader.bin.readAsync(i.start,i.end-i.start+1).then((e=>{i.loaded.resolve(e)}),(e=>{i.loaded.reject(e)})))}_getLODs(e,t,i,s){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const r=[];for(let t=s.length-1;t>=0;t--)if(r.push(uL.Get(`${e}/ids/${s[t]}`,i,s[t])),r.length===this.maxLODsToLoad)return r;return r.push(t),r}_disposeTransformNode(e){const t=[],i=e.material;i&&t.push(i);for(const i of e.getChildMeshes())i.material&&t.push(i.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 i of e){for(const e of i.getActiveTextures())t[e.uniqueId]=e;i.dispose()}for(const e in t)for(const i of this._loader.babylonScene.materials)i.hasTexture(t[e])&&delete t[e];for(const e in t)t[e].dispose()}}dL.RegisterExtension(IB,(e=>new RB(e)));const MB="MSFT_minecraftMesh";class OB{constructor(e){this.name=MB,this._loader=e,this.enabled=this._loader.isExtensionUsed(MB)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtraAsync(e,t,this.name,((s,r)=>{if(r){if(!(i instanceof zg))throw new Error(`${s}: Material type not supported`);const r=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,r}return null}))}}dL.RegisterExtension(MB,(e=>new OB(e)));const DB="MSFT_sRGBFactors";class wB{constructor(e){this.name=DB,this._loader=e,this.enabled=this._loader.isExtensionUsed(DB)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return dL.LoadExtraAsync(e,t,this.name,((s,r)=>{if(r){if(!(i instanceof zg))throw new Error(`${s}: Material type not supported`);const r=this._loader.loadMaterialPropertiesAsync(e,t,i),n=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,n),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,n),r}return null}))}}dL.RegisterExtension(DB,(e=>new wB(e)));const NB={"lifecycle/onStart":xw.ClassName,"lifecycle/onTick":Tw.ClassName,log:oO.ClassName,"flow/delay":mO.ClassName,"customEvent/send":uO.ClassName,"customEvent/receive":bw.ClassName,"flow/sequence":CO.ClassName,"world/get":DO.ClassName,"world/set":cO.ClassName,"flow/doN":_O.ClassName,"variable/get":RO.ClassName,"variable/set":aO.ClassName,"flow/whileLoop":TO.ClassName,"math/random":tD.ClassName,"math/e":sD.ClassName,"math/pi":rD.ClassName,"math/inf":nD.ClassName,"math/nan":oD.ClassName,"math/abs":lD.ClassName,"math/sign":hD.ClassName,"math/trunc":cD.ClassName,"math/floor":uD.ClassName,"math/ceil":dD.ClassName,"math/fract":_D.ClassName,"math/neg":pD.ClassName,"math/add":qO.ClassName,"math/sub":ZO.ClassName,"math/mul":JO.ClassName,"math/div":eD.ClassName,"math/rem":mD.ClassName,"math/min":gD.ClassName,"math/max":vD.ClassName,"math/clamp":TD.ClassName,"math/saturate":SD.ClassName,"math/mix":CD.ClassName,"math/eq":ED.ClassName,"math/lt":PD.ClassName,"math/le":ID.ClassName,"math/gt":RD.ClassName,"math/ge":MD.ClassName,"math/isnan":OD.ClassName,"math/isinf":DD.ClassName,"math/rad":wD.ClassName,"math/deg":ND.ClassName,"math/sin":FD.ClassName,"math/cos":LD.ClassName,"math/tan":BD.ClassName,"math/asin":kD.ClassName,"math/acos":VD.ClassName,"math/atan":UD.ClassName,"math/atan2":GD.ClassName,"math/sinh":zD.ClassName,"math/cosh":WD.ClassName,"math/tanh":HD.ClassName,"math/asinh":XD.ClassName,"math/acosh":YD.ClassName,"math/atanh":QD.ClassName,"math/exp":jD.ClassName,"math/log":KD.ClassName,"math/log2":$D.ClassName,"math/log10":qD.ClassName,"math/sqrt":ZD.ClassName,"math/cbrt":JD.ClassName,"math/pow":ew.ClassName,"math/length":tw.ClassName,"math/normalize":iw.ClassName,"math/dot":iD.ClassName,"math/cross":sw.ClassName,"math/rotate2d":rw.ClassName,"math/rotate3d":nw.ClassName,"math/transpose":ow.ClassName,"math/determinant":aw.ClassName,"math/inverse":lw.ClassName,"math/matmul":hw.ClassName,"math/not":cw.ClassName,"math/and":uw.ClassName,"math/or":dw.ClassName,"math/xor":_w.ClassName,"math/asr":fw.ClassName,"math/lsl":pw.ClassName,"math/clz":mw.ClassName,"math/ctz":gw.ClassName,"math/popcnt":vw.ClassName},FB={float2:"Vector2",float3:"Vector3",float4:"Vector4",float4x4:"Matrix",int:"FlowGraphInteger"};function LB(e,t,i){if(void 0!==e.type){const s=t.types&&t.types[e.type];if(!s)throw new Error(`${i}: Unknown type: ${e.type}`);const r=s.signature;if(!r)throw new Error(`${i}: Type ${e.type} has no signature`);const n=FB[r];return{value:e.value,className:n}}return e.value}function BB(e,t,i){const s=NB[t.type];if(!s)throw new Error(`/extensions/KHR_interactivity/nodes/${e}: Unknown block type: ${t.type}`);const r=e.toString(),n=function(e,t,i){const s={},r=e.configuration??[];for(const e of r)if("customEvent"===e.id){const r=t.customEvents&&t.customEvents[e.value];if(!r)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown custom event: ${e.value}`);s.eventId=r.id,s.eventData=r.values.map((e=>e.id))}else if("variable"===e.id){const r=t.variables&&t.variables[e.value];if(!r)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Unknown variable: ${e.value}`);s.variableName=r.id}else if("path"===e.id){const t=e.value;s.path=t}else s[e.id]=LB(e,t,`/extensions/KHR_interactivity/nodes/${i}`);return s}(t,i,r);return{className:s,config:n,uniqueId:r,metadata:t.metadata,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[]}}class kB extends yB{constructor(e){super(e,VB)}}const VB={nodes:{__array__:{__target__:!0,translation:{type:"Vector3",get:e=>e._babylonTransformNode.position,set:(e,t)=>{t._babylonTransformNode.position=e},getObject:e=>e._babylonTransformNode}}}},UB="KHR_interactivity";class GB{constructor(e){this._loader=e,this.name=UB,this.enabled=this._loader.isExtensionUsed(UB),this._pathConverter=new kB(this._loader.gltf)}dispose(){this._loader=null,delete this._pathConverter}onReady(){if(!this._loader.babylonScene||!this._pathConverter)return;const e=this._loader.babylonScene,t=this._loader.gltf.extensions?.KHR_interactivity,i=function(e){const t={uniqueId:Cs(),_userVariables:{},_connectionValues:{}},i=[t],s=[];for(let t=0;te.name===a));h||(h={uniqueId:Cs(),name:a,_connectionType:EM.Input,connectedPointIds:[]},l.signalInputs.push(h)),h.connectedPointIds.push(r.uniqueId),r.connectedPointIds.push(h.uniqueId)}const a=r.values??[];for(const r of a){const o=r.id,a={uniqueId:Cs(),name:o,_connectionType:EM.Input,connectedPointIds:[]};if(n.dataInputs.push(a),void 0!==r.value){const s=LB(r,e,`/extensions/KHR_interactivity/nodes/${i}`);t._connectionValues[a.uniqueId]=s}else{if(void 0===r.node||void 0===r.socket)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Invalid socket ${o} in node ${i}`);{const e=r.node,t=r.socket,n=s[e];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${i}: Could not find node with id ${e} that connects its output with node${i}'s input ${o}`);let l=n.dataOutputs.find((e=>e.name===t));l||(l={uniqueId:Cs(),name:t,_connectionType:EM.Output,connectedPointIds:[]},n.dataOutputs.push(l)),a.connectedPointIds.push(l.uniqueId),l.connectedPointIds.push(a.uniqueId)}}}}const r=e.variables??[];for(let i=0;inew GB(e)));const zB="ExtrasAsMetadata";class WB{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const i=e.metadata=e.metadata||{};(i.gltf=i.gltf||{}).extras=t.extras}}constructor(e){this.name=zB,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,(e=>{this._assignExtras(e,t),i(e)}))}createMaterial(e,t,i){const s=this._loader.createMaterial(e,t,i);return this._assignExtras(s,t),s}}dL.RegisterExtension(zB,(e=>new WB(e)));class HB{constructor(){this.materials=[]}parseMTL(e,t,i,s){if(t instanceof ArrayBuffer)return;const r=t.split("\n"),n=/\s+/;let o,a=null;for(let t=0;t=0?l.substring(0,h):l;c=c.toLowerCase();const u=h>=0?l.substring(h+1).trim():"";if("newmtl"===c)a&&this.materials.push(a),e._blockEntityCollection=!!s,a=new cu(u,e),a._parentContainer=s,e._blockEntityCollection=!1;else if("kd"===c&&a)o=u.split(n,3).map(parseFloat),a.diffuseColor=Ee.FromArray(o);else if("ka"===c&&a)o=u.split(n,3).map(parseFloat),a.ambientColor=Ee.FromArray(o);else if("ks"===c&&a)o=u.split(n,3).map(parseFloat),a.specularColor=Ee.FromArray(o);else if("ke"===c&&a)o=u.split(n,3).map(parseFloat),a.emissiveColor=Ee.FromArray(o);else if("ns"===c&&a)a.specularPower=parseFloat(u);else if("d"===c&&a)a.alpha=parseFloat(u);else if("map_ka"===c&&a)a.ambientTexture=HB._GetTexture(i,u,e);else if("map_kd"===c&&a)a.diffuseTexture=HB._GetTexture(i,u,e);else if("map_ks"===c&&a)a.specularTexture=HB._GetTexture(i,u,e);else if("map_ns"===c);else if("map_bump"===c&&a){const t=u.split(n),s=t.indexOf("-bm");let r=null;s>=0&&(r=t[s+1],t.splice(s,2)),a.bumpTexture=HB._GetTexture(i,t.join(" "),e),a.bumpTexture&&null!==r&&(a.bumpTexture.level=parseFloat(r))}else"map_d"===c&&a&&(a.opacityTexture=HB._GetTexture(i,u,e))}a&&this.materials.push(a)}static _GetTexture(e,t,i){if(!t)return null;let s=e;if("file:"===e){let e=t.lastIndexOf("\\");-1===e&&(e=t.lastIndexOf("/")),s+=e>-1?t.substr(e+1):t}else s+=t;return new Pa(s,i,!1,HB.INVERT_TEXTURE_Y)}}HB.INVERT_TEXTURE_Y=!0;class XB{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],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 Ae(.5,.5,.5,1),this._materialToUse=e,this._babylonMeshesArray=t,this._loadingOptions=i}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});const i=e[t[0]].normals.indexOf(t[1]);return-1===i?-1:e[t[0]].idx[i]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});const i=e[t[0]].normals.indexOf(t[1]);return 1!=i&&t[2]===e[t[0]].uv[i]?e[t[0]].idx[i]:-1}_setData(e,t,i,s,r,n,o){let a;a=this._loadingOptions.optimizeWithUV?this._isInArrayUV(this._tuplePosNorm,[e,i,t]):this._isInArray(this._tuplePosNorm,[e,i]),-1===a?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(s),this._wrappedUvsForBabylon.push(r),this._wrappedNormalsForBabylon.push(n),void 0!==o&&this._wrappedColorsForBabylon.push(o),this._tuplePosNorm[e].normals.push(i),this._tuplePosNorm[e].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e].uv.push(t)):this._indicesForBabylon.push(a)}_unwrapData(){for(let e=0;e0&&(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._handledMesh.normals=this._unwrappedNormalsForBabylon.slice(),this._handledMesh.uvs=this._unwrappedUVForBabylon.slice(),this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0)}_optimizeNormals(e){const t=e.getVerticesData(er.PositionKind),i=e.getVerticesData(er.NormalKind),s={};if(!t||!i)return;for(let e=0;ethis._triangles.push(e[0],e[t],e[t+1]),this._handednessSign=1):i.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 n=t.split("\n");for(let e=0;e=7){const e=parseFloat(i[4]),t=parseFloat(i[5]),s=parseFloat(i[6]);this._colors.push(new Ae(e>1?e/255:e,t>1?t/255:t,s>1?s/255:s,7===i.length||void 0===i[7]?1:parseFloat(i[7])))}else this._colors.push(this._grayColor)}else if(null!==(i=XB.NormalPattern.exec(t)))this._normals.push(new _e(parseFloat(i[1]),parseFloat(i[2]),parseFloat(i[3])));else if(null!==(i=XB.UVPattern.exec(t)))this._uvs.push(new de(parseFloat(i[1])*this._loadingOptions.UVScaling.x,parseFloat(i[2])*this._loadingOptions.UVScaling.y));else if(null!==(i=XB.FacePattern3.exec(t)))this._setDataForCurrentFaceWithPattern3(i[1].trim().split(" "),1);else if(null!==(i=XB.FacePattern4.exec(t)))this._setDataForCurrentFaceWithPattern4(i[1].trim().split(" "),1);else if(null!==(i=XB.FacePattern5.exec(t)))this._setDataForCurrentFaceWithPattern5(i[1].trim().split(" "),1);else if(null!==(i=XB.FacePattern2.exec(t)))this._setDataForCurrentFaceWithPattern2(i[1].trim().split(" "),1);else if(null!==(i=XB.FacePattern1.exec(t)))this._setDataForCurrentFaceWithPattern1(i[1].trim().split(" "),1);else if(null!==(i=XB.LinePattern1.exec(t)))this._setDataForCurrentFaceWithPattern1(i[1].trim().split(" "),0);else if(null!==(i=XB.LinePattern2.exec(t)))this._setDataForCurrentFaceWithPattern2(i[1].trim().split(" "),0);else if(null!==(i=XB.LinePattern3.exec(t)))this._setDataForCurrentFaceWithPattern3(i[1].trim().split(" "),0);else if(XB.GroupDescriptor.test(t)||XB.ObjectDescriptor.test(t)){const e={name:t.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:XB.ObjectDescriptor.test(t)};this._addPreviousObjMesh(),this._meshesFromObj.push(e),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(XB.UseMtlDescriptor.test(t)){if(this._materialNameFromObj=t.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 XB.MtlLibGroupDescriptor.test(t)?r(t.substring(7).trim()):XB.SmoothDescriptor.test(t)||Ne.Log("Unhandled expression at line : "+t)}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._handledMesh.normals=this._unwrappedNormalsForBabylon,this._handledMesh.uvs=this._unwrappedUVForBabylon,this._loadingOptions.importVertexColors&&(this._handledMesh.colors=this._unwrappedColorsForBabylon)),!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._colors.length)for(const e of this._colors)this._unwrappedColorsForBabylon.push(e.r,e.g,e.b,e.a);this._materialNameFromObj||(e=new cu(Yn.RandomId(),i),e.pointsCloud=!0,this._materialNameFromObj=e.name,this._normals.length||(e.disableLighting=!0,e.emissiveColor=Ee.White()))}this._meshesFromObj.push({name:Yn.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:e,isObject:!0})}for(let t=0;t=0;--e)if(this._meshesFromObj[e].isObject&&this._meshesFromObj[e]._babylonMesh){r.parent=this._meshesFromObj[e]._babylonMesh;break}if(this._materialToUse.push(this._meshesFromObj[t].materialName),0===this._handledMesh.positions?.length){this._babylonMeshesArray.push(r);continue}const n=new Wn;if(n.uvs=this._handledMesh.uvs,n.indices=this._handledMesh.indices,n.positions=this._handledMesh.positions,this._loadingOptions.computeNormals){const e=new Array;Wn.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,e),n.normals=e}else n.normals=this._handledMesh.normals;this._loadingOptions.importVertexColors&&(n.colors=this._handledMesh.colors),n.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)}}}XB.ObjectDescriptor=/^o/,XB.GroupDescriptor=/^g/,XB.MtlLibGroupDescriptor=/^mtllib /,XB.UseMtlDescriptor=/^usemtl /,XB.SmoothDescriptor=/^s /,XB.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/,XB.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,XB.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/,XB.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/,XB.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,XB.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,XB.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/,XB.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/,XB.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/,XB.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/,XB.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;class YB{static get INVERT_TEXTURE_Y(){return HB.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){HB.INVERT_TEXTURE_Y=e}constructor(e){this.name="obj",this.extensions=".obj",this._assetContainer=null,this._loadingOptions=e||YB._DefaultLoadingOptions}static get _DefaultLoadingOptions(){return{computeNormals:YB.COMPUTE_NORMALS,optimizeNormals:YB.OPTIMIZE_NORMALS,importVertexColors:YB.IMPORT_VERTEX_COLORS,invertY:YB.INVERT_Y,invertTextureY:YB.INVERT_TEXTURE_Y,UVScaling:YB.UV_SCALING,materialLoadingFailsSilently:YB.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:YB.OPTIMIZE_WITH_UV,skipMaterials:YB.SKIP_MATERIALS,useLegacyBehavior:YB.USE_LEGACY_BEHAVIOR}}_loadMTL(e,t,i,s){const r=t+e;Ds.LoadFile(r,i,void 0,void 0,!1,((e,t)=>{s(r,t)}))}createPlugin(){return new YB(YB._DefaultLoadingOptions)}canDirectLoad(){return!1}importMeshAsync(e,t,i,s){return this._parseSolid(e,t,i,s).then((e=>({meshes:e,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]})))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then((()=>{}))}loadAssetContainerAsync(e,t,i){const s=new pa(e);return this._assetContainer=s,this.importMeshAsync(null,e,t,i).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}))}_parseSolid(e,t,i,s){let r="";const n=new HB,o=[],a=[];new XB(o,a,this._loadingOptions).parse(e,i,t,this._assetContainer,(e=>{r=e}));const l=[];return""===r||this._loadingOptions.skipMaterials||l.push(new Promise(((e,i)=>{this._loadMTL(r,s,(l=>{try{n.parseMTL(t,l,s,this._assetContainer);for(let e=0;e-1;)i.push(s),t=s+1;if(-1===s&&0===i.length)n.materials[e].dispose();else for(let t=0;t{Ds.Warn(`Error downloading MTL file: '${r}'`),this._loadingOptions.materialLoadingFailsSilently?e():i(s)}))}))),Promise.all(l).then((()=>a))}}YB.OPTIMIZE_WITH_UV=!0,YB.INVERT_Y=!1,YB.IMPORT_VERTEX_COLORS=!1,YB.COMPUTE_NORMALS=!1,YB.OPTIMIZE_NORMALS=!1,YB.UV_SCALING=new de(1,1),YB.SKIP_MATERIALS=!1,YB.MATERIAL_LOADING_FAILS_SILENTLY=!0,YB.USE_LEGACY_BEHAVIOR=!1,fl&&fl.RegisterPlugin(new YB);class QB{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="stl",this.extensions={".stl":{isBinary:!0}}}importMesh(e,t,i,s,r){let n;if("string"!=typeof i){if(this._isBinary(i)){const e=new ha("stlmesh",t);return this._parseBinary(e,i),r&&r.push(e),!0}i=(new TextDecoder).decode(new Uint8Array(i))}for(;n=this.solidPattern.exec(i);){let i=n[1];const s=n[3];if(s&&i!=s)return Ds.Error("Error in STL, solid name != endsolid name"),!1;if(e&&i)if(e instanceof Array){if(!e.indexOf(i))continue}else if(i!==e)continue;i=i||"stlmesh";const o=new ha(i,t);this._parseASCII(o,n[2]),r&&r.push(o)}return!0}load(e,t,i){return this.importMesh(null,e,t,i,null)}loadAssetContainer(e,t,i){const s=new pa(e);return e._blockEntityCollection=!0,this.importMesh(null,e,t,i,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 i=[115,111,108,105,100];for(let e=0;e<5;e++)if(t.getUint8(e)!==i[e])return!0;return!1}_parseBinary(e,t){const i=new DataView(t),s=i.getUint32(80,!0);let r=0;const n=new Float32Array(3*s*3),o=new Float32Array(3*s*3),a=new Uint32Array(3*s);let l=0;for(let e=0;e{if(e.tryDownload&&document){const i=new Blob([t],{type:"text/plain"}),s=URL.createObjectURL(i),r=e.fileName?e.fileName:"bitbybit-dev.step",n=document.createElement("a");n.href=s,n.target="_self",n.download=r,n.click(),n.remove()}return t}))}}class qB{constructor(e){this.occWorkerManager=e}makeCompound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.compound.makeCompound",e)}}class ZB{constructor(e){this.occWorkerManager=e}line(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.line",e)}arcThroughThreePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcThroughThreePoints",e)}arcThroughTwoPointsAndTangent(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcThroughTwoPointsAndTangent",e)}arcFromCircleAndTwoPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCircleAndTwoPoints",e)}arcFromCircleAndTwoAngles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCircleAndTwoAngles",e)}arcFromCirclePointAndAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.arcFromCirclePointAndAngle",e)}createCircleEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.createCircleEdge",e)}createEllipseEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.createEllipseEdge",e)}removeInternalEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.removeInternalEdges",e)}makeEdgeFromGeom2dCurveAndSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.makeEdgeFromGeom2dCurveAndSurface",e)}getEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdge",e)}getEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdges",e)}getEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesAlongWire",e)}getCircularEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgesAlongWire",e)}getLinearEdgesAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getLinearEdgesAlongWire",e)}getCornerPointsOfEdgesForShape(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCornerPointsOfEdgesForShape",e)}getEdgeLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgeLength",e)}getEdgesLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesLengths",e)}getEdgeCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgeCenterOfMass",e)}getEdgesCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getEdgesCentersOfMass",e)}getCircularEdgeCenterPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgeCenterPoint",e)}getCircularEdgeRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgeRadius",e)}getCircularEdgePlaneDirection(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.getCircularEdgePlaneDirection",e)}pointOnEdgeAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.pointOnEdgeAtParam",e)}edgesToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.edgesToPoints",e)}reversedEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.reversedEdge",e)}tangentOnEdgeAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.tangentOnEdgeAtParam",e)}pointOnEdgeAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.pointOnEdgeAtLength",e)}tangentOnEdgeAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.tangentOnEdgeAtLength",e)}startPointOnEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.startPointOnEdge",e)}endPointOnEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.endPointOnEdge",e)}divideEdgeByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.divideEdgeByParamsToPoints",e)}divideEdgeByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.divideEdgeByEqualDistanceToPoints",e)}constraintTanLinesFromTwoPtsToCircle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesFromTwoPtsToCircle",e)}constraintTanLinesFromPtToCircle(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesFromPtToCircle",e)}constraintTanLinesOnTwoCircles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanLinesOnTwoCircles",e)}constraintTanCirclesOnTwoCircles(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanCirclesOnTwoCircles",e)}constraintTanCirclesOnCircleAndPnt(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.edge.constraintTanCirclesOnCircleAndPnt",e)}}class JB{constructor(e){this.occWorkerManager=e}createFaceFromWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWire",e)}createFaceFromWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromWires",e)}createFacesFromWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFacesFromWires",e)}createFaceFromMultipleCircleTanWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromMultipleCircleTanWires",e)}createFaceFromMultipleCircleTanWireCollections(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createFaceFromMultipleCircleTanWireCollections",e)}faceFromSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.faceFromSurface",e)}faceFromSurfaceAndWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.faceFromSurfaceAndWire",e)}createPolygonFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createPolygonFace",e)}createCircleFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createCircleFace",e)}createEllipseFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createEllipseFace",e)}createSquareFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createSquareFace",e)}createRectangleFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.createRectangleFace",e)}getFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFace",e)}getFaces(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaces",e)}reversedFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.reversedFace",e)}subdivideToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPoints",e)}subdivideToPointsControlled(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPointsControlled",e)}subdivideToNormals(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToNormals",e)}subdivideToUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToUV",e)}pointOnUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.pointOnUV",e)}normalOnUV(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.normalOnUV",e)}pointsOnUVs(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.pointsOnUVs",e)}normalsOnUVs(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.normalsOnUVs",e)}subdivideToPointsOnParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.subdivideToPointsOnParam",e)}getUMinBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getUMinBound",e)}getUMaxBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getUMaxBound",e)}getVMinBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getVMinBound",e)}getVMaxBound(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getVMaxBound",e)}getFaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaceArea",e)}getFacesAreas(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFacesAreas",e)}getFaceCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFaceCenterOfMass",e)}getFacesCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.getFacesCentersOfMass",e)}filterFacePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.face.filterFacePoints",e)}}class ek{constructor(e){this.occWorkerManager=e}fromClosedShell(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.fromClosedShell",e)}createBox(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createBox",e)}createCube(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCube",e)}createBoxFromCorner(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createBoxFromCorner",e)}createCylinder(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCylinder",e)}createCylindersOnLines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCylindersOnLines",e)}createSphere(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createSphere",e)}createCone(e){return e.angle=e.angle*(Math.PI/180),this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.createCone",e)}getSolidSurfaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidSurfaceArea",e)}getSolidVolume(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidVolume",e)}getSolidsVolumes(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidsVolumes",e)}getSolidCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidCenterOfMass",e)}getSolidsCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolidsCentersOfMass",e)}getSolids(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.getSolids",e)}filterSolidPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.solid.filterSolidPoints",e)}}class tk{constructor(e){this.occWorkerManager=e}createPolygonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolygonWire",e)}createPolygons(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolygons",e)}createLineWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLineWire",e)}createLines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLines",e)}splitOnPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.splitOnPoints",e)}wiresToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.wiresToPoints",e)}createPolylineWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolylineWire",e)}createZigZagBetweenTwoWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createZigZagBetweenTwoWires",e)}createWireFromTwoCirclesTan(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createWireFromTwoCirclesTan",e)}createPolylines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createPolylines",e)}createBezier(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBezier",e)}createBezierWeights(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBezierWeights",e)}createBezierWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBezierWires",e)}interpolatePoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.interpolatePoints",e)}interpolateWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.interpolateWires",e)}createBSpline(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBSpline",e)}createBSplines(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createBSplines",e)}combineEdgesAndWiresIntoAWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.combineEdgesAndWiresIntoAWire",e)}createWireFromEdge(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createWireFromEdge",e)}addEdgesAndWiresToWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.addEdgesAndWiresToWire",e)}divideWireByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWireByParamsToPoints",e)}divideWiresByParamsToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWiresByParamsToPoints",e)}divideWireByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWireByEqualDistanceToPoints",e)}divideWiresByEqualDistanceToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.divideWiresByEqualDistanceToPoints",e)}pointOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointOnWireAtParam",e)}pointOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.pointOnWireAtLength",e)}tangentOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.tangentOnWireAtParam",e)}tangentOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.tangentOnWireAtLength",e)}derivativesOnWireAtLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.derivativesOnWireAtLength",e)}derivativesOnWireAtParam(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.derivativesOnWireAtParam",e)}startPointOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.startPointOnWire",e)}endPointOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.endPointOnWire",e)}createCircleWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createCircleWire",e)}createSquareWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createSquareWire",e)}createStarWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createStarWire",e)}createChristmasTreeWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createChristmasTreeWire",e)}createNGonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createNGonWire",e)}createParallelogramWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createParallelogramWire",e)}createHeartWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createHeartWire",e)}createRectangleWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createRectangleWire",e)}createLPolygonWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createLPolygonWire",e)}createEllipseWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.createEllipseWire",e)}getWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWire",e)}getWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWires",e)}getWireCenterOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWireCenterOfMass",e)}getWiresCentersOfMass(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWiresCentersOfMass",e)}reversedWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.reversedWire",e)}reversedWireFromReversedEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.reversedWireFromReversedEdges",e)}getWireLength(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWireLength",e)}getWiresLengths(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.getWiresLengths",e)}placeWireOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.placeWireOnFace",e)}placeWiresOnFace(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.placeWiresOnFace",e)}closeOpenWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.closeOpenWire",e)}project(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.project",e)}projectWires(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.wire.projectWires",e)}}class ik{constructor(e){this.occWorkerManager=e}sewFaces(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shell.sewFaces",e)}getShellSurfaceArea(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shell.getShellSurfaceArea",e)}}class sk{constructor(e){this.occWorkerManager=e}purgeInternalEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.purgeInternalEdges",e)}unifySameDomain(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.unifySameDomain",e)}isClosed(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isClosed",e)}isConvex(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isConvex",e)}isChecked(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isChecked",e)}isFree(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isFree",e)}isInfinite(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isInfinite",e)}isModified(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isModified",e)}isLocked(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isLocked",e)}isNull(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isNull",e)}isEqual(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isEqual",e)}isNotEqual(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isNotEqual",e)}isPartner(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isPartner",e)}isSame(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.isSame",e)}getOrientation(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.getOrientation",e)}getShapeType(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.shape.getShapeType",e)}}class rk{constructor(e){this.occWorkerManager=e}vertexFromPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.vertexFromPoint",e)}verticesFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesFromPoints",e)}verticesCompoundFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesCompoundFromPoints",e)}getVertices(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.getVertices",e)}getVerticesAsPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.getVerticesAsPoints",e)}verticesToPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.verticesToPoints",e)}vertexToPoint(e){return this.occWorkerManager.genericCallToWorkerPromise("shapes.vertex.vertexToPoint",e)}}class nk{constructor(e){this.vertex=new rk(e),this.edge=new ZB(e),this.wire=new tk(e),this.face=new JB(e),this.shell=new ik(e),this.solid=new ek(e),this.compound=new qB(e),this.shape=new sk(e)}}class ok{constructor(e){this.occWorkerManager=e}transform(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.transform",e)}rotate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotate",e)}rotateAroundCenter(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateAroundCenter",e)}align(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.align",e)}alignAndTranslate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignAndTranslate",e)}translate(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.translate",e)}scale(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale",e)}scale3d(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale3d",e)}mirror(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirror",e)}mirrorAlongNormal(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorAlongNormal",e)}transformShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.transformShapes",e)}rotateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateShapes",e)}rotateAroundCenterShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.rotateAroundCenterShapes",e)}alignShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignShapes",e)}alignAndTranslateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.alignAndTranslateShapes",e)}translateShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.translateShapes",e)}scaleShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scaleShapes",e)}scale3dShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.scale3dShapes",e)}mirrorShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorShapes",e)}mirrorAlongNormalShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("transforms.mirrorAlongNormalShapes",e)}}class ak{constructor(e){this.occWorkerManager=e}loft(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.loft",e)}loftAdvanced(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.loftAdvanced",e)}closestPointsBetweenTwoShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsBetweenTwoShapes",e)}closestPointsOnShapeFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsOnShapeFromPoints",e)}closestPointsOnShapesFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.closestPointsOnShapesFromPoints",e)}distancesToShapeFromPoints(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.distancesToShapeFromPoints",e)}extrude(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.extrude",e)}extrudeShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.extrudeShapes",e)}splitShapeWithShapes(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.splitShapeWithShapes",e)}revolve(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.revolve",e)}rotatedExtrude(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.rotatedExtrude",e)}pipe(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipe",e)}pipePolylineWireNGon(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipePolylineWireNGon",e)}pipeWiresCylindrical(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipeWiresCylindrical",e)}pipeWireCylindrical(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.pipeWireCylindrical",e)}offset(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offset",e)}offsetAdv(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offsetAdv",e)}makeThickSolidSimple(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.makeThickSolidSimple",e)}makeThickSolidByJoin(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.makeThickSolidByJoin",e)}slice(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.slice",e)}sliceInStepPattern(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.sliceInStepPattern",e)}offset3DWire(e){return this.occWorkerManager.genericCallToWorkerPromise("operations.offset3DWire",e)}}class lk{constructor(e){this.occWorkerManager=e}union(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.union",e)}difference(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.difference",e)}intersection(e){return this.occWorkerManager.genericCallToWorkerPromise("booleans.intersection",e)}}class hk{constructor(e){this.occWorkerManager=e}geom2dEllipse(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dEllipse",e)}geom2dTrimmedCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dTrimmedCurve",e)}geom2dSegment(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geom2dSegment",e)}get2dPointFrom2dCurveOnParam(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.get2dPointFrom2dCurveOnParam",e)}geomCircleCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geomCircleCurve",e)}geomEllipseCurve(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.curves.geomEllipseCurve",e)}}class ck{constructor(e){this.occWorkerManager=e}cylindricalSurface(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.surfaces.cylindricalSurface",e)}surfaceFromFace(e){return this.occWorkerManager.genericCallToWorkerPromise("geom.surfaces.surfaceFromFace",e)}}class uk{constructor(e){this.curves=new hk(e),this.surfaces=new ck(e)}}class dk{constructor(e){this.occWorkerManager=e}filletEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdges",e)}filletEdgesList(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesList",e)}filletEdgesListOneRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesListOneRadius",e)}filletEdgeVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgeVariableRadius",e)}filletEdgesSameVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesSameVariableRadius",e)}filletEdgesVariableRadius(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletEdgesVariableRadius",e)}fillet3DWire(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.fillet3DWire",e)}chamferEdges(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdges",e)}chamferEdgesList(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesList",e)}chamferEdgeTwoDistances(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgeTwoDistances",e)}chamferEdgesTwoDistances(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesTwoDistances",e)}chamferEdgesTwoDistancesLists(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesTwoDistancesLists",e)}chamferEdgeDistAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgeDistAngle",e)}chamferEdgesDistAngle(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesDistAngle",e)}chamferEdgesDistsAngles(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.chamferEdgesDistsAngles",e)}fillet2d(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.fillet2d",e)}filletTwoEdgesInPlaneIntoAWire(e){return this.occWorkerManager.genericCallToWorkerPromise("fillets.filletTwoEdgesInPlaneIntoAWire",e)}}class _k{constructor(e){this.occWorkerManager=e}basicShapeRepair(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.basicShapeRepair",e)}fixSmallEdgeOnWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.fixSmallEdgeOnWire",e)}fixEdgeOrientationsAlongWire(e){return this.occWorkerManager.genericCallToWorkerPromise("shapeFix.fixEdgeOrientationsAlongWire",e)}}var pk=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class fk{constructor(e){this.occWorkerManager=e,this.shapes=new nk(e),this.geom=new uk(e),this.transforms=new ok(e),this.operations=new ak(e),this.booleans=new lk(e),this.fillets=new dk(e),this.shapeFix=new _k(e),this.io=new $B(e)}shapeToMesh(e){return pk(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",e)}))}shapesToMeshes(e){return pk(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e)}))}deleteShape(e){return pk(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("deleteShape",e)}))}deleteShapes(e){return pk(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("deleteShapes",e)}))}cleanAllCache(){return pk(this,void 0,void 0,(function*(){return yield this.occWorkerManager.genericCallToWorkerPromise("cleanAllCache",{})}))}}var mk=function(e,t){return mk=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},mk(e,t)};function gk(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}mk(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function vk(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],s=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function xk(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var s,r,n=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(e){r={error:e}}finally{try{s&&!s.done&&(i=n.return)&&i.call(n)}finally{if(r)throw r.error}}return o}function bk(e,t,i){if(i||2===arguments.length)for(var s,r=0,n=t.length;r0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,i=this,s=i.hasError,r=i.isStopped,n=i.observers;return s||r?Ak:(this.currentObservers=null,n.push(e),new Ek((function(){t.currentObservers=null,Ck(n,e)})))},t.prototype._checkFinalizedStatuses=function(e){var t=this,i=t.hasError,s=t.thrownError,r=t.isStopped;i?e.error(s):r&&e.complete()},t.prototype.asObservable=function(){var e=new $k;return e.source=this,e},t.create=function(e,t){return new sV(e,t)},t}($k),sV=function(e){function t(t,i){var s=e.call(this)||this;return s.destination=t,s.source=i,s}return gk(t,e),t.prototype.next=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===i||i.call(t,e)},t.prototype.error=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===i||i.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,i;return null!==(i=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==i?i:Ak},t}(iV);!function(e){e.loading="loading",e.loaded="loaded",e.initialised="initialised",e.computing="computing"}(Zk||(Zk={}));class rV{constructor(){this.occWorkerState$=new iV,this.promisesMade=[]}occWorkerAlreadyInitialised(){return!!this.occWorker}setOccWorker(e){this.occWorker=e,this.occWorker.onmessage=({data:e})=>{if("occ-initialised"===e)this.occWorkerState$.next({state:Zk.initialised});else if("busy"===e)this.occWorkerState$.next({state:Zk.computing});else{const t=this.promisesMade.find((t=>t.uid===e.uid));t&&void 0!==e.result&&!e.error?t.resolve(e.result):e.error&&(this.errorCallback&&this.errorCallback(e.error),t.reject(e.error)),this.promisesMade=this.promisesMade.filter((t=>t.uid!==e.uid)),0===this.promisesMade.length?this.occWorkerState$.next({state:Zk.loaded}):this.occWorkerState$.next({state:Zk.computing})}}}cleanPromisesMade(){this.promisesMade=[]}genericCallToWorkerPromise(e,t){const i=`call${Math.random()}${Date.now()}`,s={uid:i},r=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return s.promise=r,this.promisesMade.push(s),this.occWorker.postMessage({action:{functionName:e,inputs:t},uid:i}),r}startedTheRun(){return this.genericCallToWorkerPromise("startedTheRun",{})}cleanAllCache(){return this.genericCallToWorkerPromise("cleanAllCache",{})}}!function(e){let t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m;!function(e){e.arc="arc",e.intersection="intersection",e.tangent="tangent"}(t=e.joinTypeEnum||(e.joinTypeEnum={})),function(e){e.skin="skin",e.pipe="pipe",e.rectoVerso="rectoVerso"}(i=e.bRepOffsetModeEnum||(e.bRepOffsetModeEnum={})),function(e){e.approxChordLength="approxChordLength",e.approxCentripetal="approxCentripetal",e.approxIsoParametric="approxIsoParametric"}(s=e.approxParametrizationTypeEnum||(e.approxParametrizationTypeEnum={})),function(e){e.outside="outside",e.inside="inside",e.middle="middle"}(r=e.directionEnum||(e.directionEnum={})),function(e){e.iges="iges",e.step="step"}(n=e.fileTypeEnum||(e.fileTypeEnum={})),function(e){e.forward="forward",e.reversed="reversed",e.internal="internal",e.external="external"}(o=e.topAbsOrientationEnum||(e.topAbsOrientationEnum={})),function(e){e.in="in",e.out="out",e.on="on",e.unknown="unknown"}(a=e.topAbsStateEnum||(e.topAbsStateEnum={})),function(e){e.unknown="unknown",e.vertex="vertex",e.edge="edge",e.wire="wire",e.face="face",e.shell="shell",e.solid="solid",e.compSolid="compSolid",e.compound="compound",e.shape="shape"}(l=e.shapeTypeEnum||(e.shapeTypeEnum={})),function(e){e.unqualified="unqualified",e.enclosing="enclosing",e.enclosed="enclosed",e.outside="outside",e.noqualifier="noqualifier"}(h=e.gccEntPositionEnum||(e.gccEntPositionEnum={})),function(e){e.keepSide1="keepSide1",e.keepSide2="keepSide2",e.all="all"}(c=e.positionResultEnum||(e.positionResultEnum={})),function(e){e.none="none",e.keepSide1="keepSide1",e.keepSide2="keepSide2"}(u=e.circleInclusionEnum||(e.circleInclusionEnum={})),function(e){e.none="none",e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(d=e.twoCircleInclusionEnum||(e.twoCircleInclusionEnum={})),function(e){e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(_=e.fourSidesStrictEnum||(e.fourSidesStrictEnum={})),function(e){e.outside="outside",e.inside="inside"}(p=e.twoSidesStrictEnum||(e.twoSidesStrictEnum={})),function(e){e.allWithAll="allWithAll",e.inOrder="inOrder",e.inOrderClosed="inOrderClosed"}(f=e.combinationCirclesForFaceEnum||(e.combinationCirclesForFaceEnum={})),function(e){e[e.curve=0]="curve",e[e.edge=1]="edge",e[e.wire=2]="wire",e[e.face=3]="face"}(m=e.typeSpecificityEnum||(e.typeSpecificityEnum={})),e.DecomposedMeshDto=class{constructor(e,t){void 0!==e&&(this.faceList=e),void 0!==t&&(this.edgeList=t)}},e.DecomposedFaceDto=class{},e.DecomposedEdgeDto=class{},e.ShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.PointDto=class{constructor(e){this.point=[0,0,0],void 0!==e&&(this.point=e)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.ConstraintTanLinesFromPtToCircleDto=class{constructor(e,t,i,s,r){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.positionResult=s),void 0!==r&&(this.circleRemainder=r)}},e.ConstraintTanLinesFromTwoPtsToCircleDto=class{constructor(e,t,i,s,r,n){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point1=t),void 0!==i&&(this.point1=i),void 0!==s&&(this.tolerance=s),void 0!==r&&(this.positionResult=r),void 0!==n&&(this.circleRemainder=n)}},e.ConstraintTanLinesOnTwoCirclesDto=class{constructor(e,t,i,s,r){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainders=d.none,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.positionResult=s),void 0!==r&&(this.circleRemainders=r)}},e.ConstraintTanCirclesOnTwoCirclesDto=class{constructor(e,t,i,s){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.radius=s)}},e.ConstraintTanCirclesOnCircleAndPntDto=class{constructor(e,t,i,s){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.radius=s)}},e.CurveAndSurfaceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t)}},e.FilletTwoEdgesInPlaneDto=class{constructor(e,t,i,s,r,n){this.planeOrigin=[0,0,0],this.planeDirection=[0,1,0],this.radius=.3,this.solution=-1,void 0!==e&&(this.edge1=e),void 0!==t&&(this.edge2=t),void 0!==i&&(this.planeOrigin=i),void 0!==s&&(this.planeDirection=s),void 0!==r&&(this.radius=r),void 0!==n&&(this.solution=n)}},e.ClosestPointsOnShapeFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.SplitWireOnPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.ClosestPointsOnShapesFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shapes=e),void 0!==t&&(this.points=t)}},e.ClosestPointsBetweenTwoShapesDto=class{constructor(e,t){void 0!==e&&(this.shape1=e),void 0!==t&&(this.shape2=t)}},e.FaceFromSurfaceAndWireDto=class{constructor(e,t,i){this.inside=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.wire=t),void 0!==i&&(this.inside=i)}},e.WireOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wire=e),void 0!==t&&(this.face=t)}},e.DrawShapeDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shape=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdgeIndexes=_),void 0!==p&&(this.edgeIndexHeight=p),void 0!==f&&(this.edgeIndexColour=f),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.DrawShapesDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shapes=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdgeIndexes=_),void 0!==p&&(this.edgeIndexHeight=p),void 0!==f&&(this.edgeIndexColour=f),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.FaceSubdivisionDto=class{constructor(e,t,i,s,r,n,o,a,l){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepU=!1,this.removeStartEdgeU=!1,this.removeEndEdgeU=!1,this.shiftHalfStepV=!1,this.removeStartEdgeV=!1,this.removeEndEdgeV=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==s&&(this.shiftHalfStepU=s),void 0!==r&&(this.removeStartEdgeU=r),void 0!==n&&(this.removeEndEdgeU=n),void 0!==o&&(this.shiftHalfStepV=o),void 0!==a&&(this.removeStartEdgeV=a),void 0!==l&&(this.removeEndEdgeV=l)}},e.FaceSubdivisionControlledDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepNthU=0,this.shiftHalfStepUOffsetN=0,this.removeStartEdgeNthU=0,this.removeStartEdgeUOffsetN=0,this.removeEndEdgeNthU=0,this.removeEndEdgeUOffsetN=0,this.shiftHalfStepNthV=0,this.shiftHalfStepVOffsetN=0,this.removeStartEdgeNthV=0,this.removeStartEdgeVOffsetN=0,this.removeEndEdgeNthV=0,this.removeEndEdgeVOffsetN=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==s&&(this.shiftHalfStepNthU=s),void 0!==r&&(this.shiftHalfStepUOffsetN=r),void 0!==n&&(this.removeStartEdgeNthU=n),void 0!==o&&(this.removeStartEdgeUOffsetN=o),void 0!==a&&(this.removeEndEdgeNthU=a),void 0!==l&&(this.removeEndEdgeUOffsetN=l),void 0!==h&&(this.shiftHalfStepNthV=h),void 0!==c&&(this.shiftHalfStepVOffsetN=c),void 0!==u&&(this.removeStartEdgeNthV=u),void 0!==d&&(this.removeStartEdgeVOffsetN=d),void 0!==_&&(this.removeEndEdgeNthV=_),void 0!==p&&(this.removeEndEdgeVOffsetN=p)}},e.FaceLinearSubdivisionDto=class{constructor(e,t,i,s,r,n,o){this.isU=!0,this.param=.5,this.nrPoints=10,this.shiftHalfStep=!1,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==i&&(this.param=i),void 0!==s&&(this.nrPoints=s),void 0!==r&&(this.shiftHalfStep=r),void 0!==n&&(this.removeStartPoint=n),void 0!==o&&(this.removeEndPoint=o)}},e.DataOnUVDto=class{constructor(e,t,i){this.paramU=.5,this.paramV=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.paramU=t),void 0!==i&&(this.paramV=i)}},e.DataOnUVsDto=class{constructor(e,t){this.paramsUV=[[.5,.5]],void 0!==e&&(this.shape=e),void 0!==t&&(this.paramsUV=t)}},e.PolygonDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolygonsDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polygons=e),void 0!==t&&(this.returnCompound=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolylinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.returnCompound=t)}},e.SquareDto=class{constructor(e,t,i){this.size=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.RectangleDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.center=i),void 0!==s&&(this.direction=s)}},e.LPolygonDto=class{constructor(e,t,i,s,n,o,a,l){this.widthFirst=1,this.lengthFirst=2,this.widthSecond=.5,this.lengthSecond=2,this.align=r.outside,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.widthFirst=e),void 0!==t&&(this.lengthFirst=t),void 0!==i&&(this.widthSecond=i),void 0!==s&&(this.lengthSecond=s),void 0!==n&&(this.align=n),void 0!==o&&(this.rotation=o),void 0!==a&&(this.center=a),void 0!==l&&(this.direction=l)}},e.BoxDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.height=3,this.center=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==s&&(this.center=s)}},e.CubeDto=class{constructor(e,t){this.size=1,this.center=[0,0,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t)}},e.BoxFromCornerDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.height=3,this.corner=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==s&&(this.corner=s)}},e.SphereDto=class{constructor(e,t){this.radius=1,this.center=[0,0,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.ConeDto=class{constructor(e,t,i,s,r,n){this.radius1=2,this.radius2=1,this.height=2,this.angle=360,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius1=e),void 0!==t&&(this.radius2=t),void 0!==i&&(this.height=i),void 0!==s&&(this.angle=s),void 0!==r&&(this.center=r),void 0!==n&&(this.direction=n)}},e.LineDto=class{constructor(e,t){this.start=[0,0,0],this.end=[0,1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.returnCompound=t)}},e.ArcEdgeTwoPointsTangentDto=class{constructor(e,t,i){this.start=[0,0,0],this.tangentVec=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.tangentVec=t),void 0!==i&&(this.end=i)}},e.ArcEdgeCircleTwoPointsDto=class{constructor(e,t,i,s){this.start=[0,0,0],this.end=[0,0,1],this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.start=t),void 0!==i&&(this.end=i),void 0!==s&&(this.sense=s)}},e.ArcEdgeCircleTwoAnglesDto=class{constructor(e,t,i,s){this.alphaAngle1=0,this.alphaAngle2=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle1=t),void 0!==i&&(this.alphaAngle2=i),void 0!==s&&(this.sense=s)}},e.ArcEdgeCirclePointAngleDto=class{constructor(e,t,i,s){this.alphaAngle=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle=t),void 0!==s&&(this.sense=s)}},e.ArcEdgeThreePointsDto=class{constructor(e,t,i){this.start=[0,0,0],this.middle=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.middle=t),void 0!==i&&(this.end=i)}},e.CylinderDto=class{constructor(e,t,i,s){this.radius=1,this.height=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.height=t),void 0!==i&&(this.center=i),void 0!==s&&(this.direction=s)}},e.CylindersOnLinesDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.lines=t)}},e.FilletDto=class{constructor(e,t,i,s){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.indexes=s)}},e.FilletEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i)}},e.FilletEdgesListOneRadiusDto=class{constructor(e,t,i){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radius=i)}},e.FilletEdgeVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.paramsU=s)}},e.FilletEdgesVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusLists=i),void 0!==s&&(this.paramsULists=s)}},e.FilletEdgesSameVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.paramsU=s)}},e.Fillet3DWireDto=class{constructor(e,t,i,s,r){this.radius=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.direction=i),void 0!==s&&(this.radiusList=s),void 0!==r&&(this.indexes=r)}},e.ChamferDto=class{constructor(e,t,i,s){this.distance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.distance=t),void 0!==i&&(this.distanceList=i),void 0!==s&&(this.indexes=s)}},e.ChamferEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.distanceList=i)}},e.ChamferEdgeDistAngleDto=class{constructor(e,t,i,s,r){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.angle=r)}},e.ChamferEdgeTwoDistancesDto=class{constructor(e,t,i,s,r){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==s&&(this.distance1=s),void 0!==r&&(this.distance2=r)}},e.ChamferEdgesTwoDistancesListsDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distances1=s),void 0!==r&&(this.distances2=r)}},e.ChamferEdgesTwoDistancesDto=class{constructor(e,t,i,s,r){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distance1=s),void 0!==r&&(this.distance2=r)}},e.ChamferEdgesDistsAnglesDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distances=s),void 0!==r&&(this.angles=r)}},e.ChamferEdgesDistAngleDto=class{constructor(e,t,i,s,r){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.angle=r)}},e.BSplineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BSplinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bSplines=e),void 0!==t&&(this.returnCompound=t)}},e.WireFromTwoCirclesTanDto=class{constructor(e,t,i,s,r){this.keepLines=p.outside,this.circleRemainders=_.outside,this.tolerance=1e-7,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.keepLines=i),void 0!==s&&(this.circleRemainders=s),void 0!==r&&(this.tolerance=r)}},e.FaceFromMultipleCircleTanWiresDto=class{constructor(e,t,i,s){this.combination=f.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.circles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==s&&(this.tolerance=s)}},e.FaceFromMultipleCircleTanWireCollectionsDto=class{constructor(e,t,i,s){this.combination=f.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.listsOfCircles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==s&&(this.tolerance=s)}},e.ZigZagBetweenTwoWiresDto=class{constructor(e,t,i,s,r,n){this.nrZigZags=20,this.divideByEqualDistance=!1,this.zigZagsPerEdge=!0,void 0!==e&&(this.wire1=e),void 0!==t&&(this.wire2=t),void 0!==i&&(this.nrZigZags=i),void 0!==s&&(this.inverse=s),void 0!==r&&(this.divideByEqualDistance=r),void 0!==n&&(this.zigZagsPerEdge=n)}},e.InterpolationDto=class{constructor(e,t,i){this.periodic=!1,this.tolerance=1e-7,void 0!==e&&(this.points=e),void 0!==t&&(this.periodic=t),void 0!==i&&(this.tolerance=i)}},e.InterpolateWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.interpolations=e),void 0!==t&&(this.returnCompound=t)}},e.BezierDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BezierWeightsDto=class{constructor(e,t,i){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.weights=t),void 0!==i&&(this.closed=i)}},e.BezierWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bezierWires=e),void 0!==t&&(this.returnCompound=t)}},e.DivideDto=class{constructor(e,t,i,s){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==s&&(this.removeEndPoint=s)}},e.ProjectWireDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wire=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.WiresToPointsDto=class{constructor(e,t,i,s,r,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==s&&(this.minimumOfPoints=s),void 0!==r&&(this.uTolerance=r),void 0!==n&&(this.minimumLength=n)}},e.EdgesToPointsDto=class{constructor(e,t,i,s,r,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==s&&(this.minimumOfPoints=s),void 0!==r&&(this.uTolerance=r),void 0!==n&&(this.minimumLength=n)}},e.ProjectWiresDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wires=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.DivideShapesDto=class{constructor(e,t,i,s){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==s&&(this.removeEndPoint=s)}},e.DataOnGeometryAtParamDto=class{constructor(e,t){this.param=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t)}},e.PointInFaceDto=class{constructor(e,t,i,s){this.tEdgeParam=.5,this.distance2DParam=.5,void 0!==e&&(this.face=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.tEdgeParam=i),void 0!==s&&(this.distance2DParam=s)}},e.DataOnGeometryAtLengthDto=class{constructor(e,t){this.length=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.length=t)}},e.CircleDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.LoftDto=class{constructor(e,t){this.makeSolid=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t)}},e.LoftAdvancedDto=class{constructor(e,t,i,r,n,o,a,l,h,c,u,d){this.makeSolid=!1,this.closed=!1,this.periodic=!1,this.straight=!1,this.nrPeriodicSections=10,this.useSmoothing=!1,this.maxUDegree=3,this.tolerance=1e-7,this.parType=s.approxCentripetal,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t),void 0!==i&&(this.closed=i),void 0!==r&&(this.periodic=r),void 0!==n&&(this.straight=n),void 0!==o&&(this.nrPeriodicSections=o),void 0!==a&&(this.useSmoothing=a),void 0!==l&&(this.maxUDegree=l),void 0!==h&&(this.tolerance=h),void 0!==c&&(this.parType=c),void 0!==u&&(this.startVertex=u),void 0!==d&&(this.endVertex=d)}},e.OffsetDto=class{constructor(e,t,i,s){this.distance=.2,this.tolerance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.face=t),void 0!==i&&(this.distance=i),void 0!==s&&(this.tolerance=s)}},e.OffsetAdvancedDto=class{constructor(e,i,s,r,n,o){this.distance=.2,this.tolerance=.1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.face=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.tolerance=r),void 0!==n&&(this.joinType=n),void 0!==o&&(this.removeIntEdges=o)}},e.RevolveDto=class{constructor(e,t,i,s){this.angle=360,this.direction=[0,1,0],this.copy=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.direction=i),void 0!==s&&(this.copy=s)}},e.ShapeShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.WiresOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t)}},e.PipeWiresCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.radius=t)}},e.PipeWireCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t)}},e.PipePolygonWireNGonDto=class{constructor(e,t,i){this.radius=.1,this.nrCorners=6,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.nrCorners=i)}},e.ExtrudeDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t)}},e.ExtrudeShapesDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.direction=t)}},e.SplitDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.UnionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.DifferenceDto=class{constructor(e,t,i){this.keepEdges=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t),void 0!==i&&(this.keepEdges=i)}},e.IntersectionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.ShapeDto=class{constructor(e){void 0!==e&&(this.shape=e)}},e.CompareShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.otherShape=t)}},e.FixSmallEdgesInWireDto=class{constructor(e,t,i){this.lockvtx=!1,this.precsmall=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.lockvtx=t),void 0!==i&&(this.precsmall=i)}},e.BasicShapeRepairDto=class{constructor(e,t,i,s){this.precision=.001,this.maxTolerance=.01,this.minTolerance=1e-4,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.maxTolerance=i),void 0!==s&&(this.minTolerance=s)}},e.FixClosedDto=class{constructor(e,t){this.precision=-.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t)}},e.ShapesWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.ShapeWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.tolerance=t)}},e.ShapeIndexDto=class{constructor(e,t){this.index=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.EdgeIndexDto=class{constructor(e,t){this.index=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.RotationExtrudeDto=class{constructor(e,t,i){this.height=1,this.angle=360,void 0!==e&&(this.shape=e),void 0!==t&&(this.height=t),void 0!==i&&(this.angle=i)}},e.ThickSolidByJoinDto=class{constructor(e,i,s,r,n,o,a,l){this.offset=1,this.tolerance=.001,this.intersection=!1,this.selfIntersection=!1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.shapes=i),void 0!==s&&(this.offset=s),void 0!==r&&(this.tolerance=r),void 0!==n&&(this.intersection=n),void 0!==o&&(this.selfIntersection=o),void 0!==a&&(this.joinType=a),void 0!==l&&(this.removeIntEdges=l)}},e.TransformDto=class{constructor(e,t,i,s,r){this.translation=[0,0,0],this.rotationAxis=[0,1,0],this.rotationAngle=0,this.scaleFactor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t),void 0!==i&&(this.rotationAxis=i),void 0!==s&&(this.rotationAngle=s),void 0!==r&&(this.scaleFactor=r)}},e.TransformShapesDto=class{constructor(e,t,i,s,r){this.translations=[[0,0,0]],this.rotationAxes=[[0,1,0]],this.rotationAngles=[0],this.scaleFactors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t),void 0!==i&&(this.rotationAxes=i),void 0!==s&&(this.rotationAngles=s),void 0!==r&&(this.scaleFactors=r)}},e.TranslateDto=class{constructor(e,t){this.translation=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t)}},e.TranslateShapesDto=class{constructor(e,t){this.translations=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t)}},e.AlignDto=class{constructor(e,t,i,s,r){this.fromOrigin=[0,0,0],this.fromDirection=[0,0,1],this.toOrigin=[0,1,0],this.toDirection=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.fromOrigin=t),void 0!==i&&(this.fromDirection=i),void 0!==s&&(this.toOrigin=s),void 0!==r&&(this.toDirection=r)}},e.AlignShapesDto=class{constructor(e,t,i,s,r){this.fromOrigins=[[0,0,0]],this.fromDirections=[[0,0,1]],this.toOrigins=[[0,1,0]],this.toDirections=[[0,1,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.fromOrigins=t),void 0!==i&&(this.fromDirections=i),void 0!==s&&(this.toOrigins=s),void 0!==r&&(this.toDirections=r)}},e.MirrorDto=class{constructor(e,t,i){this.origin=[0,0,0],this.direction=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.direction=i)}},e.MirrorShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.directions=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.directions=i)}},e.MirrorAlongNormalDto=class{constructor(e,t,i){this.origin=[0,0,0],this.normal=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.normal=i)}},e.MirrorAlongNormalShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.normals=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.normals=i)}},e.AlignAndTranslateDto=class{constructor(e,t,i){this.direction=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.center=i)}},e.UnifySameDomainDto=class{constructor(e,t,i,s){this.unifyEdges=!0,this.unifyFaces=!0,this.concatBSplines=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.unifyEdges=t),void 0!==i&&(this.unifyFaces=i),void 0!==s&&(this.concatBSplines=s)}},e.FilterFacePointsDto=class{constructor(e,t,i,s,r,n,o,a,l){this.tolerance=1e-4,this.useBndBox=!1,this.gapTolerance=.1,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.useBndBox=s),void 0!==r&&(this.gapTolerance=r),void 0!==n&&(this.keepIn=n),void 0!==o&&(this.keepOn=o),void 0!==a&&(this.keepOut=a),void 0!==l&&(this.keepUnknown=l)}},e.FilterSolidPointsDto=class{constructor(e,t,i,s,r,n,o){this.tolerance=1e-4,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.keepIn=s),void 0!==r&&(this.keepOn=r),void 0!==n&&(this.keepOut=n),void 0!==o&&(this.keepUnknown=o)}},e.AlignAndTranslateShapesDto=class{constructor(e,t,i){this.directions=[[0,1,0]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.directions=t),void 0!==i&&(this.centers=i)}},e.RotateDto=class{constructor(e,t,i){this.axis=[0,0,1],this.angle=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.angle=i)}},e.RotateAroundCenterDto=class{constructor(e,t,i,s){this.angle=0,this.center=[0,0,0],this.axis=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.center=i),void 0!==s&&(this.axis=s)}},e.RotateShapesDto=class{constructor(e,t,i){this.angles=[0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.axes=t),void 0!==i&&(this.angles=i)}},e.RotateAroundCenterShapesDto=class{constructor(e,t,i,s){this.angles=[0],this.centers=[[0,0,0]],this.axes=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.angles=t),void 0!==i&&(this.centers=i),void 0!==s&&(this.axes=s)}},e.ScaleDto=class{constructor(e,t){this.factor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.factor=t)}},e.ScaleShapesDto=class{constructor(e,t){this.factors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.factors=t)}},e.Scale3DDto=class{constructor(e,t,i){this.scale=[1,1,1],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.scale=t),void 0!==i&&(this.center=i)}},e.Scale3DShapesDto=class{constructor(e,t,i){this.scales=[[1,1,1]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.scales=t),void 0!==i&&(this.centers=i)}},e.ShapeToMeshDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.ShapesToMeshesDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.SaveStepDto=class{constructor(e,t,i,s){this.fileName="shape.step",this.adjustYtoZ=!1,this.tryDownload=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustYtoZ=i),void 0!==s&&(this.tryDownload=s)}},e.SaveStlDto=class{constructor(e,t,i,s,r,n){this.fileName="shape.stl",this.precision=.01,this.adjustYtoZ=!1,this.tryDownload=!0,this.binary=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.precision=i),void 0!==s&&(this.adjustYtoZ=s),void 0!==r&&(this.tryDownload=r),void 0!==n&&(this.binary=n)}},e.ImportStepIgesFromTextDto=class{constructor(e,t,i){this.fileType=n.step,this.adjustZtoY=!0,void 0!==e&&(this.text=e),void 0!==t&&(this.fileType=t),void 0!==i&&(this.adjustZtoY=i)}},e.ImportStepIgesDto=class{constructor(e,t){this.adjustZtoY=!0,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.adjustZtoY=t)}},e.LoadStepOrIgesDto=class{constructor(e,t,i){this.fileName="shape.igs",this.adjustZtoY=!0,void 0!==e&&(this.filetext=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustZtoY=i)}},e.CompoundShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.ThisckSolidSimpleDto=class{constructor(e,t){this.offset=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t)}},e.Offset3DWireDto=class{constructor(e,t,i){this.offset=1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t),void 0!==i&&(this.direction=i)}},e.FaceFromWireDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.planar=t)}},e.FaceFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.FacesFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.SewDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.FaceIsoCurveAtParamDto=class{constructor(e,t,i){this.dir="u",void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t),void 0!==i&&(this.dir=i)}},e.DivideFaceToUVPointsDto=class{constructor(e,t,i,s){this.nrOfPointsU=10,this.nrOfPointsV=10,this.flat=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfPointsU=t),void 0!==i&&(this.nrOfPointsV=i),void 0!==s&&(this.flat=s)}},e.Geom2dEllipseDto=class{constructor(e,t,i,s,r){this.center=[0,0],this.direction=[1,0],this.radiusMinor=1,this.radiusMajor=2,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==s&&(this.radiusMajor=s),void 0!==r&&(this.sense=r)}},e.Geom2dCircleDto=class{constructor(e,t,i,s){this.center=[0,0],this.direction=[1,0],this.radius=1,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.sense=s)}},e.ChristmasTreeDto=class{constructor(e,t,i,s,r,n,o,a,l,h){this.height=6,this.innerDist=1.5,this.outerDist=3,this.nrSkirts=5,this.trunkHeight=1,this.trunkWidth=1,this.half=!1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.innerDist=t),void 0!==i&&(this.outerDist=i),void 0!==s&&(this.nrSkirts=s),void 0!==r&&(this.trunkHeight=r),void 0!==n&&(this.trunkWidth=n),void 0!==o&&(this.half=o),void 0!==a&&(this.rotation=a),void 0!==l&&(this.origin=l),void 0!==h&&(this.direction=h)}},e.StarDto=class{constructor(e,t,i,s,r,n,o){this.center=[0,0,0],this.direction=[0,1,0],this.numRays=7,this.half=!1,void 0!==e&&(this.outerRadius=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.numRays=i),void 0!==s&&(this.center=s),void 0!==r&&(this.direction=r),void 0!==n&&(this.offsetOuterEdges=n),void 0!==o&&(this.half=o)}},e.ParallelogramDto=class{constructor(e,t,i,s,r,n){this.center=[0,0,0],this.direction=[0,1,0],this.aroundCenter=!0,this.width=2,this.height=1,this.angle=15,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.aroundCenter=i),void 0!==s&&(this.width=s),void 0!==r&&(this.height=r),void 0!==n&&(this.angle=n)}},e.Heart2DDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.rotation=0,this.sizeApprox=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.rotation=i),void 0!==s&&(this.sizeApprox=s)}},e.NGonWireDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.nrCorners=6,this.radius=1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.nrCorners=i),void 0!==s&&(this.radius=s)}},e.EllipseDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.radiusMinor=1,this.radiusMajor=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==s&&(this.radiusMajor=s)}},e.GeomCylindricalSurfaceDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.Geom2dTrimmedCurveDto=class{constructor(e,t,i,s,r){this.u1=0,this.u2=1,this.sense=!0,this.adjustPeriodic=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.u1=t),void 0!==i&&(this.u2=i),void 0!==s&&(this.sense=s),void 0!==r&&(this.adjustPeriodic=r)}},e.Geom2dSegmentDto=class{constructor(e,t){this.start=[0,0],this.end=[1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.SliceDto=class{constructor(e,t,i){this.step=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.step=t),void 0!==i&&(this.direction=i)}},e.SliceInStepPatternDto=class{constructor(e,t,i){this.steps=[.1,.2],this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.steps=t),void 0!==i&&(this.direction=i)}}}(Jk||(Jk={})),function(e){let t;!function(e){e.default="default",e.clearSky="clearSky",e.city="city"}(t=e.skyboxEnum||(e.skyboxEnum={}))}(eV||(eV={})),"undefined"!=typeof document&&document.currentScript&&document.currentScript.src;class nV{constructor(e){this.context=e}create(e){const t=new _e(e.target[0],e.target[1],e.target[2]),i=new hc(`arcRotateCamera${Math.random()}`,this.getRadians(e.alpha),this.getRadians(e.beta),e.radius,t,this.context.scene);void 0!==e.angularSensibilityX&&(i.angularSensibilityX=e.angularSensibilityX),void 0!==e.angularSensibilityY&&(i.angularSensibilityY=e.angularSensibilityY),void 0!==e.lowerBetaLimit&&(i.lowerBetaLimit=this.getRadians(e.lowerBetaLimit)),void 0!==e.upperBetaLimit&&(i.upperBetaLimit=this.getRadians(e.upperBetaLimit)),void 0!==e.panningSensibility&&(i.panningSensibility=e.panningSensibility),void 0!==e.wheelPrecision&&(i.wheelPrecision=e.wheelPrecision),void 0!==e.maxZ&&(i.maxZ=e.maxZ),i.minZ=0;const s=document.getElementById("renderCanvas");return i.attachControl(s,!0),i}getRadians(e){let t=$r.FromDegrees(e).radians();return e<0&&(t=-t),t}}class oV{constructor(e){this.context=e}create(e){const t=new _e(e.position[0],e.position[1],e.position[2]),i=new ac(`freeCamera${Math.random()}`,t,this.context.scene),s=new _e(e.target[0],e.target[1],e.target[2]);i.setTarget(s);const r=document.getElementById("renderCanvas");return i.attachControl(r,!0),i.minZ=0,i.maxZ=1e3,i}}class aV{constructor(e){this.context=e}create(e){const t=new _e(e.position[0],e.position[1],e.position[2]),i=new oc(`freeCamera${Math.random()}`,t,this.context.scene),s=new _e(e.target[0],e.target[1],e.target[2]);i.setTarget(s);const r=document.getElementById("renderCanvas");return i.attachControl(r,!0),i.minZ=0,i.maxZ=1e3,i}}class lV{constructor(e){this.context=e,this.free=new oV(this.context),this.arcRotate=new nV(this.context),this.target=new aV(this.context)}freezeProjectionMatrix(e){e.camera.freezeProjectionMatrix()}unfreezeProjectionMatrix(e){e.camera.unfreezeProjectionMatrix()}setPosition(e){const t=new _e(e.position[0],e.position[1],e.position[2]);e.camera.position=t}getPosition(e){return[e.camera.position.x,e.camera.position.y,e.camera.position.z]}setTarget(e){const t=new _e(e.target[0],e.target[1],e.target[2]);e.camera.setTarget(t)}getTarget(e){return[e.camera.target.x,e.camera.target.y,e.camera.target.z]}setSpeed(e){e.camera.speed=e.speed}getSpeed(e){return[e.camera.target.x,e.camera.target.y,e.camera.target.z]}setMinZ(e){e.camera.minZ=e.minZ}setMaxZ(e){e.camera.maxZ=e.maxZ}makeCameraOrthographic(e){e.camera.mode=In.ORTHOGRAPHIC_CAMERA,e.camera.orthoBottom=e.orthoBottom||-1,e.camera.orthoTop=e.orthoTop||1,e.camera.orthoLeft=e.orthoLeft||-1,e.camera.orthoRight=e.orthoRight||1}makeCameraPerspective(e){e.camera.mode=In.PERSPECTIVE_CAMERA}}class hV{constructor(e,t){this.context=e,this.color=t}create(e){const t=new Lx(e.name,this.context.scene);return t.baseColor=Ee.FromHexString(e.baseColor),t.metallic=e.metallic,t.roughness=e.roughness,t.alpha=e.alpha,t.backFaceCulling=e.backFaceCulling,t.zOffset=e.zOffset,t.alphaMode=1,e.emissiveColor&&(t.emissiveColor=Ee.FromHexString(e.emissiveColor)),t}setBaseColor(e){e.material.baseColor=Ee.FromHexString(e.baseColor)}setMetallic(e){e.material.metallic=e.metallic}setRoughness(e){e.material.roughness=e.roughness}setAlpha(e){e.material.alpha=e.alpha}setBackFaceCulling(e){e.material.backFaceCulling=e.backFaceCulling}setBaseTexture(e){e.material.baseTexture=e.baseTexture}getBaseColor(e){const t=e.material,i=this.context.remap(t.baseColor.r,0,1,0,255),s=this.context.remap(t.baseColor.g,0,1,0,255),r=this.context.remap(t.baseColor.b,0,1,0,255);return this.color.rgbToHex({r:i,g:s,b:r})}getMetallic(e){return e.material.metallic}getRoughness(e){return e.material.roughness}getAlpha(e){return e.material.alpha}getBackFaceCulling(e){return e.material.backFaceCulling}getBaseTexture(e){return e.material.baseTexture}}class cV{constructor(e,t){this.context=e,this.color=t,this.pbrMetallicRoughness=new hV(e,t)}}var uV=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class dV{constructor(e){this.context=e}createDefaultXRExperienceWithTeleportation(e){return uV(this,void 0,void 0,(function*(){const t=yield this.context.scene.createDefaultXRExperienceAsync();this.context.scene.metadata?this.context.scene.metadata.xr=t:this.context.scene.metadata={xr:t};const i=[];e.groundMeshes.forEach((e=>{e.getChildMeshes&&(null==e||e.getChildMeshes().forEach((e=>{e.isPickable=!0,i.push(e)}))),i.push(e),e.isPickable=!0}));const s=t.baseExperience.featuresManager,r=new Lx("teleportation");r.baseColor=new Ee(0,0,1),r.metallic=0,r.roughness=1,s.enableFeature(qa.TELEPORTATION,"stable",{xrInput:t.input,floorMeshes:i,defaultTargetMeshOptions:{torusArrowMaterial:r,disableLighting:!1}});const n=new vF(this.context.scene);this.context.scene.metadata.guiManager=n,n.useRealisticScaling=!0;const o=new ZN("near");n.addControl(o);const a=new zN("button1"),l=new Fw;l.text="Exit VR",l.color="white",l.fontSize="48px",a.onPointerClickObservable.add((()=>uV(this,void 0,void 0,(function*(){yield t.baseExperience.exitXRAsync()})))),o.addButton(a),a.content=l}))}}class _V{constructor(e){this.context=e}getEngine(){return this.context.engine}getRenderingCanvas(){return this.context.engine.getRenderingCanvas()}}var pV;class fV{constructor(e){this.context=e}create(e){return t=this,i=void 0,r=function*(){const t=new aE(`gaussian-splatting-${Math.random()}`,void 0,this.context.scene);return yield t.loadFileAsync(e.url),t},new((s=void 0)||(s=Promise))((function(e,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,a)}l((r=r.apply(t,i||[])).next())}));var t,i,s,r}}class mV{static _CreateBufferView(e,t,i,s,r){const n={buffer:e,byteLength:i};return t&&(n.byteOffset=t),r&&(n.name=r),s&&(n.byteStride=s),n}static _CreateAccessor(e,t,i,s,r,n,o,a){const l={name:t,bufferView:e,componentType:s,count:r,type:i};return null!=o&&(l.min=o),null!=a&&(l.max=a),null!=n&&(l.byteOffset=n),l}static _CalculateMinMaxPositions(e,t,i){const s=[1/0,1/0,1/0],r=[-1/0,-1/0,-1/0];let n,o,a;if(i)for(let l=t,h=t+i;lr[e]&&(r[e]=t),++n}}return{min:s,max:r}}static _NormalizeTangentFromRef(e){const t=Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z);t>0&&(e.x/=t,e.y/=t,e.z/=t)}static _GetDataAccessorElementCount(e){switch(e){case"MAT2":case"VEC4":return 4;case"MAT3":return 9;case"MAT4":return 16;case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3}}}!function(e){e[e.INTANGENT=0]="INTANGENT",e[e.OUTTANGENT=1]="OUTTANGENT"}(pV||(pV={}));class gV{static _IsTransformable(e){return e&&(e instanceof lo||e instanceof In||e instanceof ua)}static _CreateNodeAnimation(e,t,i,s,r){if(this._IsTransformable(e)){const n=[],o=[],a=t.getKeys(),l=gV._CalculateMinMaxKeyFrames(a),h=gV._DeduceInterpolation(a,i,s),c=h.interpolationType,u=h.shouldBakeAnimation;if(u?gV._CreateBakedAnimation(e,t,i,l.min,l.max,t.framePerSecond,r,n,o,l,s):"LINEAR"===c||"STEP"===c?gV._CreateLinearOrStepAnimation(e,t,i,n,o,s):"CUBICSPLINE"===c?gV._CreateCubicSplineAnimation(e,t,i,n,o,s):gV._CreateBakedAnimation(e,t,i,l.min,l.max,t.framePerSecond,r,n,o,l,s),n.length&&o.length)return{inputs:n,outputs:o,samplerInterpolation:c,inputsMin:u?l.min:Ds.FloatRound(l.min/t.framePerSecond),inputsMax:u?l.max:Ds.FloatRound(l.max/t.framePerSecond)}}return null}static _DeduceAnimationInfo(e){let t=null,i="VEC3",s=!1;const r=e.targetProperty.split(".");switch(r[0]){case"scaling":t="scale";break;case"position":t="translation";break;case"rotation":i="VEC4",t="rotation";break;case"rotationQuaternion":i="VEC4",s=!0,t="rotation";break;case"influence":i="SCALAR",t="weights";break;default:Ds.Error(`Unsupported animatable property ${r[0]}`)}return t?{animationChannelTargetPath:t,dataAccessorType:i,useQuaternion:s}:(Ds.Error("animation channel target path and data accessor type could be deduced"),null)}static _CreateNodeAnimationFromNodeAnimations(e,t,i,s,r,n,o,a,l,h){let c;if(gV._IsTransformable(e)&&e.animations)for(const r of e.animations){if(h&&!h(r))continue;const u=gV._DeduceAnimationInfo(r);u&&(c={name:r.name,samplers:[],channels:[]},gV._AddAnimation(`${r.name}`,r.hasRunningRuntimeAnimations?t:c,e,r,u.dataAccessorType,u.animationChannelTargetPath,s,n,o,a,u.useQuaternion,l),c.samplers.length&&c.channels.length&&i.push(c))}}static _CreateMorphTargetAnimationFromMorphTargetAnimations(e,t,i,s,r,n,o,a,l,h){let c;if(e instanceof ha){const r=e.morphTargetManager;if(r)for(let u=0;u{for(let i=0;ie.morphTargetManager===i));s&&(h.has(s)||h.set(s,new Map),h.get(s)?.set(t,f),d.add(s),u.set(s,f))}}}}d.forEach((e=>{const t=e.morphTargetManager;let a=null;const d=[],p=u.get(e).getKeys(),f=p.length;for(let i=0;i0;)t=_.inputs.shift(),e%d==0&&i.push(t),e++;_.inputs=i}const s=o[i.uniqueId];let c=4*_.inputs.length;p=mV._CreateBufferView(0,a.getByteOffset(),c,void 0,`${e} keyframe data view`),l.push(p),_.inputs.forEach((function(e){a.setFloat32(e)})),f=mV._CreateAccessor(l.length-1,`${e} keyframes`,"SCALAR",5126,_.inputs.length,null,[_.inputsMin],[_.inputsMax]),h.push(f),m=h.length-1,v=_.outputs.length,c=4*mV._GetDataAccessorElementCount(r)*_.outputs.length,p=mV._CreateBufferView(0,a.getByteOffset(),c,void 0,`${e} data view`),l.push(p),_.outputs.forEach((function(e){e.forEach((function(e){a.setFloat32(e)}))})),f=mV._CreateAccessor(l.length-1,`${e} data`,r,5126,v,null,null,null),h.push(f),g=h.length-1,x={interpolation:_.samplerInterpolation,input:m,output:g},t.samplers.push(x),b={sampler:t.samplers.length-1,target:{node:s,path:n}},t.channels.push(b)}}static _CreateBakedAnimation(e,t,i,s,r,n,o,a,l,h,c){let u;const d=fe.Identity();let _,p=null,f=null,m=null,g=null,v=null,x=null;h.min=Ds.FloatRound(s/n);const b=t.getKeys();for(let s=0,h=b.length;s{"StandardMaterial"===e.getClassName()?s.push(this._convertStandardMaterialAsync(e,t,i)):-1!==e.getClassName().indexOf("PBR")?s.push(this._convertPBRMaterialAsync(e,t,i)):Ds.Warn(`Unsupported material type: ${e.name}`)})),Promise.all(s).then((()=>{}))}_stripTexturesFromMaterial(e){const t={};if(e){t.name=e.name,t.doubleSided=e.doubleSided,t.alphaMode=e.alphaMode,t.alphaCutoff=e.alphaCutoff,t.emissiveFactor=e.emissiveFactor;const i=e.pbrMetallicRoughness;i&&(t.pbrMetallicRoughness={},t.pbrMetallicRoughness.baseColorFactor=i.baseColorFactor,t.pbrMetallicRoughness.metallicFactor=i.metallicFactor,t.pbrMetallicRoughness.roughnessFactor=i.roughnessFactor)}return t}_hasTexturesPresent(e){if(e.emissiveTexture||e.normalTexture||e.occlusionTexture)return!0;const t=e.pbrMetallicRoughness;if(t&&(t.baseColorTexture||t.metallicRoughnessTexture))return!0;if(e.extensions)for(const t in e.extensions){const i=e.extensions[t];if(i)return i.hasTextures?.()}return!1}_getTextureInfo(e){if(e){const t=e.uid;if(t in this._textureMap)return this._textureMap[t]}return null}_convertToGLTFPBRMetallicRoughness(e){const t=new de(0,1),i=new de(0,.1),s=new de(0,.1),r=new de(1300,.1),n=e.diffuseColor.toLinearSpace(e.getScene().getEngine().useExactSrgbConversions).scale(.5),o=e.alpha,a=(l=be.Clamp(e.specularPower,0,xV._MaxSpecularPower),h=Math.pow(l/r.x,.333333),c=t.y,u=i.y,d=s.y,_=r.y,(1-h)*(1-h)*(1-h)*c+3*(1-h)*(1-h)*h*u+3*(1-h)*h*h*d+h*h*h*_);var l,h,c,u,d,_;return{baseColorFactor:[n.r,n.g,n.b,o],metallicFactor:0,roughnessFactor:a}}static _SolveMetallic(e,t,i){if(t{e&&(o.baseColorTexture=e)})));const i=e.bumpTexture;i&&n.push(this._exportTextureAsync(i,t).then((e=>{e&&(a.normalTexture=e,1!==i.level&&(a.normalTexture.scale=i.level))}))),e.emissiveTexture&&(a.emissiveFactor=[1,1,1],n.push(this._exportTextureAsync(e.emissiveTexture,t).then((e=>{e&&(a.emissiveTexture=e)})))),e.ambientTexture&&n.push(this._exportTextureAsync(e.ambientTexture,t).then((e=>{if(e){const t={index:e.index};a.occlusionTexture=t}})))}return(e.alpha<1||e.opacityTexture)&&(e.alphaMode===N_.ALPHA_COMBINE?a.alphaMode="BLEND":Ds.Warn(e.name+": glTF 2.0 does not support alpha mode: "+e.alphaMode.toString())),e.emissiveColor&&!xV._FuzzyEquals(e.emissiveColor,Ee.Black(),xV._Epsilon)&&(a.emissiveFactor=e.emissiveColor.asArray()),a.pbrMetallicRoughness=o,xV._SetAlphaMode(a,e),r.push(a),s[e.uniqueId]=r.length-1,this._finishMaterial(n,a,e,t)}_finishMaterial(e,t,i,s){return Promise.all(e).then((()=>{const e=this._exporter._extensionsPostExportMaterialAdditionalTextures("exportMaterial",t,i);let r=null;for(const t of e)r||(r=[]),r.push(this._exportTextureAsync(t,s));return r||(r=[Promise.resolve(null)]),Promise.all(r).then((()=>{const e=this._exporter._extensionsPostExportMaterialAsync("exportMaterial",t,i);return e?e.then((()=>t)):t}))}))}async _getImageDataAsync(e,t,i,s){const r=N_.TEXTURETYPE_UNSIGNED_INT,n=this._exporter._babylonScene,o=n.getEngine(),a=o.createRawTexture(e,t,i,N_.TEXTUREFORMAT_RGBA,!1,!0,Pa.NEAREST_SAMPLINGMODE,null,r);await np.ApplyPostProcess("pass",a,n,r,N_.TEXTURE_NEAREST_SAMPLINGMODE,N_.TEXTUREFORMAT_RGBA);const l=await o._readTexturePixels(a,t,i);return await th.DumpDataAsync(t,i,l,s,void 0,!0,!0)}_createWhiteTexture(e,t,i){const s=new Uint8Array(e*t*4);for(let e=0;er.width?(o=t&&t instanceof Pa?np.CreateResizedCopy(t,s.width,s.height,!0):this._createWhiteTexture(s.width,s.height,i),n=e):(n=e,o=t),{texture1:n,texture2:o}}_convertPixelArrayToFloat32(e){if(e instanceof Uint8Array){const t=e.length,i=new Float32Array(e.length);for(let s=0;sxV._Epsilon?T.baseColor.r:1,m[i+1]/=T.baseColor.g>xV._Epsilon?T.baseColor.g:1,m[i+2]/=T.baseColor.b>xV._Epsilon?T.baseColor.b:1;const s=Ee.FromInts(m[i],m[i+1],m[i+2]).toGammaSpace(n.getEngine().useExactSrgbConversions);m[i]=255*s.r,m[i+1]=255*s.g,m[i+2]=255*s.b,xV._FuzzyEquals(s,Ee.White(),xV._Epsilon)||(S=!0),f[i+1]/=T.roughness>xV._Epsilon?T.roughness:1,f[i+2]/=T.metallic>xV._Epsilon?T.metallic:1;const r=Ee.FromInts(255,f[i+1],f[i+2]);xV._FuzzyEquals(r,Ee.White(),xV._Epsilon)||(y=!0)}return y&&r.push(this._getImageDataAsync(f,c,u,s).then((e=>{T.metallicRoughnessTextureData=e}))),S&&r.push(this._getImageDataAsync(m,c,u,s).then((e=>{T.baseColorTextureData=e}))),Promise.all(r).then((()=>T))}return Promise.reject("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!")}_convertSpecularGlossinessToMetallicRoughness(e){const t=this._getPerceivedBrightness(e.diffuseColor),i=this._getPerceivedBrightness(e.specularColor),s=1-this._getMaxComponent(e.specularColor),r=xV._SolveMetallic(t,i,s),n=e.diffuseColor.scale(s/(1-xV._DielectricSpecular.r)/Math.max(1-r,xV._Epsilon)),o=e.specularColor.subtract(xV._DielectricSpecular.scale(1-r)).scale(1/Math.max(r,xV._Epsilon));let a=Ee.Lerp(n,o,r*r);return a=a.clampToRef(0,1,a),{baseColor:a,metallic:r,roughness:1-e.glossiness}}_getPerceivedBrightness(e){return e?Math.sqrt(.299*e.r*e.r+.587*e.g*e.g+.114*e.b*e.b):0}_getMaxComponent(e){return e?Math.max(e.r,Math.max(e.g,e.b)):0}_convertMetalRoughFactorsToMetallicRoughnessAsync(e,t,i,s){const r=[],n={baseColor:e._albedoColor,metallic:e._metallic,roughness:e._roughness};if(s){e._albedoTexture&&r.push(this._exportTextureAsync(e._albedoTexture,t).then((e=>{e&&(i.baseColorTexture=e)})));const s=e._metallicTexture;s&&r.push(this._exportTextureAsync(s,t).then((e=>{e&&(i.metallicRoughnessTexture=e)})))}return Promise.all(r).then((()=>n))}_getTextureSampler(e){const t={};if(!(e&&e instanceof Pa))return t;const i=this._getGLTFTextureWrapMode(e.wrapU);10497!==i&&(t.wrapS=i);const s=this._getGLTFTextureWrapMode(e.wrapV);switch(10497!==s&&(t.wrapT=s),e.samplingMode){case Pa.LINEAR_LINEAR:t.magFilter=9729,t.minFilter=9729;break;case Pa.LINEAR_NEAREST:t.magFilter=9729,t.minFilter=9728;break;case Pa.NEAREST_LINEAR:t.magFilter=9728,t.minFilter=9729;break;case Pa.NEAREST_LINEAR_MIPLINEAR:t.magFilter=9728,t.minFilter=9987;break;case Pa.NEAREST_NEAREST:t.magFilter=9728,t.minFilter=9728;break;case Pa.NEAREST_LINEAR_MIPNEAREST:t.magFilter=9728,t.minFilter=9985;break;case Pa.LINEAR_NEAREST_MIPNEAREST:t.magFilter=9729,t.minFilter=9984;break;case Pa.LINEAR_NEAREST_MIPLINEAR:t.magFilter=9729,t.minFilter=9986;break;case Pa.NEAREST_NEAREST_MIPLINEAR:t.magFilter=9728,t.minFilter=9986;break;case Pa.LINEAR_LINEAR_MIPLINEAR:t.magFilter=9729,t.minFilter=9987;break;case Pa.LINEAR_LINEAR_MIPNEAREST:t.magFilter=9729,t.minFilter=9985;break;case Pa.NEAREST_NEAREST_MIPNEAREST:t.magFilter=9728,t.minFilter=9984}return t}_getGLTFTextureWrapMode(e){switch(e){case Pa.WRAP_ADDRESSMODE:return 10497;case Pa.CLAMP_ADDRESSMODE:return 33071;case Pa.MIRROR_ADDRESSMODE:return 33648;default:return Ds.Error(`Unsupported Texture Wrap Mode ${e}!`),10497}}_convertSpecGlossFactorsToMetallicRoughnessAsync(e,t,i,s){return Promise.resolve().then((()=>{const r={diffuseColor:e._albedoColor,specularColor:e._reflectivityColor,glossiness:e._microSurface},n=e._albedoTexture,o=e._reflectivityTexture,a=e._useMicroSurfaceFromReflectivityMapAlpha;if(o&&!a)return Promise.reject("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture are currently not supported");if((n||o)&&s){const e=this._exportTextureSampler(n||o);return this._convertSpecularGlossinessTexturesToMetallicRoughnessAsync(n,o,r,t).then((s=>{const r=this._exporter._textures;if(s.baseColorTextureData){const o=this._exportImage(`baseColor${r.length}`,t,s.baseColorTextureData);i.baseColorTexture=this._exportTextureInfo(o,e,n?.coordinatesIndex)}if(s.metallicRoughnessTextureData){const n=this._exportImage(`metallicRoughness${r.length}`,t,s.metallicRoughnessTextureData);i.metallicRoughnessTexture=this._exportTextureInfo(n,e,o?.coordinatesIndex)}return s}))}return this._convertSpecularGlossinessToMetallicRoughness(r)}))}_convertPBRMaterialAsync(e,t,i){const s={},r={name:e.name};if(e.isMetallicWorkflow()){const n=e._albedoColor,o=e.alpha;return n&&(s.baseColorFactor=[n.r,n.g,n.b,o]),this._convertMetalRoughFactorsToMetallicRoughnessAsync(e,t,s,i).then((n=>this._setMetallicRoughnessPbrMaterial(n,e,r,s,t,i)))}return this._convertSpecGlossFactorsToMetallicRoughnessAsync(e,t,s,i).then((n=>this._setMetallicRoughnessPbrMaterial(n,e,r,s,t,i)))}_setMetallicRoughnessPbrMaterial(e,t,i,s,r,n){const o=this._exporter._materialMap,a=this._exporter._materials,l=[];if(e){if(xV._SetAlphaMode(i,t),xV._FuzzyEquals(e.baseColor,Ee.White(),xV._Epsilon)&&t.alpha>=xV._Epsilon||(s.baseColorFactor=[e.baseColor.r,e.baseColor.g,e.baseColor.b,t.alpha]),null!=e.metallic&&1!==e.metallic&&(s.metallicFactor=e.metallic),null!=e.roughness&&1!==e.roughness&&(s.roughnessFactor=e.roughness),null==t.backFaceCulling||t.backFaceCulling||(t._twoSidedLighting||Ds.Warn(t.name+": Back-face culling disabled and two-sided lighting disabled is not supported in glTF."),i.doubleSided=!0),n){const e=t._bumpTexture;if(e){const t=this._exportTextureAsync(e,r).then((t=>{t&&(i.normalTexture=t,1!==e.level&&(i.normalTexture.scale=e.level))}));l.push(t)}const s=t._ambientTexture;if(s){const e=this._exportTextureAsync(s,r).then((e=>{if(e){const s={index:e.index,texCoord:e.texCoord,extensions:e.extensions};i.occlusionTexture=s;const r=t._ambientTextureStrength;r&&(s.strength=r)}}));l.push(e)}const n=t._emissiveTexture;if(n){const e=this._exportTextureAsync(n,r).then((e=>{e&&(i.emissiveTexture=e)}));l.push(e)}}const h=t._emissiveColor;xV._FuzzyEquals(h,Ee.Black(),xV._Epsilon)||(i.emissiveFactor=h.asArray()),i.pbrMetallicRoughness=s,a.push(i),o[t.uniqueId]=a.length-1}return this._finishMaterial(l,i,t,r)}_getPixelsFromTexture(e){return e.textureType,N_.TEXTURETYPE_UNSIGNED_INT,e.readPixels()}_exportTextureAsync(e,t){const i=this._exporter._extensionsPreExportTextureAsync("exporter",e,t);return i?i.then((i=>i?this._exportTextureInfoAsync(i,t):this._exportTextureInfoAsync(e,t))):this._exportTextureInfoAsync(e,t)}async _exportTextureInfoAsync(e,t){const i=e.uid;if(!(i in this._textureMap)){const s=await this._getPixelsFromTexture(e);if(!s)return null;const r=this._exportTextureSampler(e),n=e.mimeType;if(n)switch(n){case"image/jpeg":case"image/png":case"image/webp":t=n;break;default:Ds.Warn(`Unsupported media type: ${n}`)}const o=this._internalTextureToImage,a=e.getInternalTexture().uniqueId;o[a]||(o[a]={});let l=o[a][t];if(void 0===l){const i=e.getSize();l=(async()=>{const r=await this._getImageDataAsync(s,i.width,i.height,t);return this._exportImage(e.name,t,r)})(),o[a][t]=l}const h=this._exportTextureInfo(await l,r,e.coordinatesIndex);this._textureMap[i]=h,this._exporter._extensionsPostExportTextures("exporter",this._textureMap[i],e)}return this._textureMap[i]}_exportImage(e,t,i){const s=this._exporter._imageData,r=e.replace(/\.\/|\/|\.\\|\\/g,"_"),n=function(e){switch(e){case"image/jpeg":return".jpg";case"image/png":return".png";case"image/webp":return".webp";case"image/avif":return".avif"}}(t);let o=r+n;o in s&&(o=`${r}_${Ds.RandomId()}${n}`),s[o]={data:i,mimeType:t};const a=this._exporter._images;return a.push({name:e,uri:o}),a.length-1}_exportTextureInfo(e,t,i){const s=this._exporter._textures;let r=s.findIndex((i=>i.sampler==t&&i.source===e));-1===r&&(r=s.length,s.push({source:e,sampler:t}));const n={index:r};return i&&(n.texCoord=i),n}_exportTextureSampler(e){const t=this._getTextureSampler(e),i=this._exporter._samplers,s=i.findIndex((e=>e.minFilter===t.minFilter&&e.magFilter===t.magFilter&&e.wrapS===t.wrapS&&e.wrapT===t.wrapT));return-1!==s?s:(i.push(t),i.length-1)}}xV._DielectricSpecular=new Ee(.04,.04,.04),xV._MaxSpecularPower=1024,xV._Epsilon=1e-6;const bV=me.Compose(new _e(-1,1,1),fe.Identity(),_e.Zero()),TV=new fe(0,1,0,0);function yV(e,t){if(!(e instanceof lo))return!1;if(t){if(!e.getWorldMatrix().isIdentity())return!1}else if(!e.getWorldMatrix().multiplyToRef(bV,ve.Matrix[0]).isIdentity())return!1;return!(e instanceof ha&&e.geometry||e instanceof ca&&e.sourceMesh.geometry)}function SV(e){const t=_e.FromArrayToRef(e.translation||[0,0,0],0,ve.Vector3[0]),i=fe.FromArrayToRef(e.rotation||[0,0,0,1],0,ve.Quaternion[0]),s=_e.FromArrayToRef(e.scale||[1,1,1],0,ve.Vector3[1]);me.ComposeToRef(s,i,t,ve.Matrix[0]).multiplyToRef(bV,ve.Matrix[0]).decompose(s,i,t),t.equalsToFloats(0,0,0)?delete e.translation:e.translation=t.asArray(),fe.IsIdentity(i)?delete e.rotation:e.rotation=i.asArray(),s.equalsToFloats(1,1,1)?delete e.scale:e.scale=s.asArray()}class CV{_applyExtension(e,t,i,s){if(i>=t.length)return Promise.resolve(e);const r=s(t[i],e);return r?r.then((e=>this._applyExtension(e,t,i+1,s))):this._applyExtension(e,t,i+1,s)}_applyExtensions(e,t){const i=[];for(const e of CV._ExtensionNames)i.push(this._extensions[e]);return this._applyExtension(e,i,0,t)}_extensionsPreExportTextureAsync(e,t,i){return this._applyExtensions(t,((t,s)=>t.preExportTextureAsync&&t.preExportTextureAsync(e,s,i)))}_extensionsPostExportMeshPrimitiveAsync(e,t,i,s){return this._applyExtensions(t,((t,r)=>t.postExportMeshPrimitiveAsync&&t.postExportMeshPrimitiveAsync(e,r,i,s)))}_extensionsPostExportNodeAsync(e,t,i,s,r){return this._applyExtensions(t,((t,n)=>t.postExportNodeAsync&&t.postExportNodeAsync(e,n,i,s,r)))}_extensionsPostExportMaterialAsync(e,t,i){return this._applyExtensions(t,((t,s)=>t.postExportMaterialAsync&&t.postExportMaterialAsync(e,s,i)))}_extensionsPostExportMaterialAdditionalTextures(e,t,i){const s=[];for(const r of CV._ExtensionNames){const n=this._extensions[r];n.postExportMaterialAdditionalTextures&&s.push(...n.postExportMaterialAdditionalTextures(e,t,i))}return s}_extensionsPostExportTextures(e,t,i){for(const s of CV._ExtensionNames){const r=this._extensions[s];r.postExportTexture&&r.postExportTexture(e,t,i)}}_forEachExtensions(e){for(const t of CV._ExtensionNames){const i=this._extensions[t];i.enabled&&e(i)}}_extensionsOnExporting(){this._forEachExtensions((e=>{e.wasUsed&&(null==this._glTF.extensionsUsed&&(this._glTF.extensionsUsed=[]),-1===this._glTF.extensionsUsed.indexOf(e.name)&&this._glTF.extensionsUsed.push(e.name),e.required&&(null==this._glTF.extensionsRequired&&(this._glTF.extensionsRequired=[]),-1===this._glTF.extensionsRequired.indexOf(e.name)&&this._glTF.extensionsRequired.push(e.name)),null==this._glTF.extensions&&(this._glTF.extensions={}),e.onExporting&&e.onExporting())}))}_loadExtensions(){for(const e of CV._ExtensionNames){const t=CV._ExtensionFactories[e](this);this._extensions[e]=t}}constructor(e,t){this._extensions={},this._glTF={asset:{generator:`Babylon.js v${oo.Version}`,version:"2.0"}},(e=e||re.LastCreatedScene)&&(this._babylonScene=e,this._bufferViews=[],this._accessors=[],this._meshes=[],this._scenes=[],this._cameras=[],this._nodes=[],this._images=[],this._materials=[],this._materialMap=[],this._textures=[],this._samplers=[],this._skins=[],this._animations=[],this._imageData={},this._orderedImageData=[],this._options=t||{},this._animationSampleRate=this._options.animationSampleRate||1/60,this._glTFMaterialExporter=new xV(this),this._loadExtensions())}dispose(){for(const e in this._extensions)this._extensions[e].dispose()}get options(){return this._options}static RegisterExtension(e,t){CV.UnregisterExtension(e)&&Ds.Warn(`Extension with the name ${e} already exists`),CV._ExtensionFactories[e]=t,CV._ExtensionNames.push(e)}static UnregisterExtension(e){if(!CV._ExtensionFactories[e])return!1;delete CV._ExtensionFactories[e];const t=CV._ExtensionNames.indexOf(e);return-1!==t&&CV._ExtensionNames.splice(t,1),!0}_reorderIndicesBasedOnPrimitiveMode(e,t,i,s,r){switch(t){case ta.TriangleFillMode:s||(s=0);for(let t=e.indexStart,i=e.indexStart+e.indexCount;t=n;--t)r.setUInt32(i[t],s),s+=4;break;case ta.TriangleStripDrawMode:e.indexCount>=3&&(r.setUInt32(i[e.indexStart+2],s+4),r.setUInt32(i[e.indexStart+1],s+8))}}_reorderVertexAttributeDataBasedOnPrimitiveMode(e,t,i,s,r,n){switch(t){case ta.TriangleFillMode:this._reorderTriangleFillMode(e,i,s,r,n);break;case ta.TriangleStripDrawMode:this._reorderTriangleStripDrawMode(e,i,s,r,n);break;case ta.TriangleFanDrawMode:this._reorderTriangleFanMode(e,i,s,r,n)}}_reorderTriangleFillMode(e,t,i,s,r){const n=this._getVertexBufferFromMesh(t,e.getMesh());if(n){const o=n.byteStride/er.GetTypeByteLength(n.type);if(e.verticesCount%3!=0)Ds.Error("The submesh vertices for the triangle fill mode is not divisible by 3!");else{const a=[];let l=0;switch(t){case er.PositionKind:case er.NormalKind:for(let t=e.verticesStart;t=e.verticesStart;--t)l=t*o,a.push(pe.FromArray(i,l));break;case er.ColorKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,4===n.getSize()?a.push(pe.FromArray(i,l)):a.push(_e.FromArray(i,l));break;case er.UVKind:case er.UV2Kind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(de.FromArray(i,l));break;default:Ds.Error(`Unsupported Vertex Buffer type: ${t}`)}this._writeVertexAttributeData(a,s+12,t,r)}else Ds.Warn(`reorderTriangleStripDrawMode: Vertex buffer kind ${t} not present!`)}_reorderTriangleFanMode(e,t,i,s,r){const n=this._getVertexBufferFromMesh(t,e.getMesh());if(n){const o=n.byteStride/er.GetTypeByteLength(n.type),a=[];let l=0;switch(t){case er.PositionKind:case er.NormalKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(_e.FromArray(i,l));break;case er.TangentKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(pe.FromArray(i,l));break;case er.ColorKind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(pe.FromArray(i,l)),4===n.getSize()?a.push(pe.FromArray(i,l)):a.push(_e.FromArray(i,l));break;case er.UVKind:case er.UV2Kind:for(let t=e.verticesStart+e.verticesCount-1;t>=e.verticesStart;--t)l=t*o,a.push(de.FromArray(i,l));break;default:Ds.Error(`Unsupported Vertex Buffer type: ${t}`)}this._writeVertexAttributeData(a,s,t,r)}else Ds.Warn(`reorderTriangleFanMode: Vertex buffer kind ${t} not present!`)}_writeVertexAttributeData(e,t,i,s){for(const r of e){i===er.NormalKind?r.normalize():i===er.TangentKind&&r instanceof pe&&mV._NormalizeTangentFromRef(r);for(const e of r.asArray())s.setFloat32(e,t),t+=4}}_writeAttributeData(e,t,i,s,r,n){let o,a,l=[];switch(e){case er.PositionKind:for(let e=0,t=i.length/s;e{e.uri&&(n=this._imageData[e.uri],this._orderedImageData.push(n),r=e.uri.split(".")[0]+" image",o=mV._CreateBufferView(0,a,n.data.byteLength,void 0,r),a+=n.data.byteLength,this._bufferViews.push(o),e.bufferView=this._bufferViews.length-1,e.name=r,e.mimeType=n.mimeType,e.uri=void 0,this._glTF.images||(this._glTF.images=[]),this._glTF.images.push(e))})),s.byteLength=a):this._glTF.images=this._images),e||(s.uri=t+".bin"),i?JSON.stringify(this._glTF,null,2):JSON.stringify(this._glTF)}_generateGLTFAsync(e,t=!0){return this._generateBinaryAsync().then((i=>{this._extensionsOnExporting();const s=this._generateJSON(!1,e,!0),r=new Blob([i],{type:"application/octet-stream"}),n=e+".gltf",o=e+".bin",a=new vV;if(a.glTFFiles[n]=s,a.glTFFiles[o]=r,this._imageData)for(const e in this._imageData)a.glTFFiles[e]=new Blob([this._imageData[e].data],{type:this._imageData[e].mimeType});return t&&this.dispose(),a}))}_generateBinaryAsync(){const e=new EV(4);return this._createSceneAsync(e).then((()=>(this._localEngine&&this._localEngine.dispose(),e.getArrayBuffer())))}_getPadding(e){const t=e%4;return 0===t?t:4-t}_generateGLBAsync(e,t=!0){return this._generateBinaryAsync().then((i=>{this._extensionsOnExporting();const s=this._generateJSON(!0),r=e+".glb";let n,o=s.length,a=0;"undefined"!=typeof TextEncoder&&(n=(new TextEncoder).encode(s),o=n.length);for(let e=0;e0){if((null!==o.overrideMaterialSideOrientation?o.overrideMaterialSideOrientation:d.sideOrientation)===(this._babylonScene.useRightHandedSystem?ta.ClockWiseSideOrientation:ta.CounterClockWiseSideOrientation)){let e=null!=l?this._bufferViews[l].byteOffset:null;null==e&&(e=0);let t=null;if(null!=l&&(t=o.getIndices()),t)this._reorderIndicesBasedOnPrimitiveMode(r,h,t,e,i);else for(const e of a){const t=o.getVerticesData(e.kind,void 0,void 0,!0);if(t){const s=this._bufferViews[c[e.kind]].byteOffset||0;this._reorderVertexAttributeDataBasedOnPrimitiveMode(r,h,e.kind,t,s,i)}}}null!=_&&(f.material=_)}if(u){e.extras||(e.extras={}),e.extras.targetNames=[];for(let t=0;t{}))}_createSceneAsync(e){const t={nodes:[]};let i,s,r;const n=[...this._babylonScene.transformNodes,...this._babylonScene.meshes,...this._babylonScene.lights,...this._babylonScene.cameras],o=new Set;if(this._babylonScene.metadata&&(this._options.metadataSelector?t.extras=this._options.metadataSelector(this._babylonScene.metadata):this._babylonScene.metadata.gltf&&(t.extras=this._babylonScene.metadata.gltf.extras)),(this._options.removeNoopRootNodes??1)&&!this._options.includeCoordinateSystemConversionNodes)for(const e of this._babylonScene.rootNodes)yV(e,this._babylonScene.useRightHandedSystem)&&(o.add(e),n.splice(n.indexOf(e),1));const a=new Map;this._babylonScene.cameras.forEach((e=>{if(this._options.shouldExportNode&&!this._options.shouldExportNode(e))return;const t={type:e.mode===In.PERSPECTIVE_CAMERA?"perspective":"orthographic"};if(e.name&&(t.name=e.name),"perspective"===t.type)t.perspective={aspectRatio:e.getEngine().getAspectRatio(e),yfov:e.fovMode===In.FOVMODE_VERTICAL_FIXED?e.fov:e.fov*e.getEngine().getAspectRatio(e),znear:e.minZ,zfar:e.maxZ};else if("orthographic"===t.type){const i=e.orthoLeft&&e.orthoRight?.5*(e.orthoRight-e.orthoLeft):.5*e.getEngine().getRenderWidth(),s=e.orthoBottom&&e.orthoTop?.5*(e.orthoTop-e.orthoBottom):.5*e.getEngine().getRenderHeight();t.orthographic={xmag:i,ymag:s,znear:e.minZ,zfar:e.maxZ}}a.set(e,this._cameras.length),this._cameras.push(t)}));const[l,h]=this._getExportNodes(n);return this._glTFMaterialExporter._convertMaterialsToGLTFAsync(h,"image/png",!0).then((()=>this._createNodeMapAndAnimationsAsync(l,e).then((l=>this._createSkinsAsync(l,e).then((h=>{if(this._nodeMap=l,this._totalByteLength=e.getByteOffset(),null==this._totalByteLength)throw new Error("undefined byte length!");for(const e of n)if(i=this._nodeMap[e.uniqueId],void 0!==i&&(s=this._nodes[i],e.metadata&&(this._options.metadataSelector?s.extras=this._options.metadataSelector(e.metadata):e.metadata.gltf&&(s.extras=e.metadata.gltf.extras)),e instanceof In&&(s.camera=a.get(e)),this._options.shouldExportNode&&!this._options.shouldExportNode(e)?Ds.Log("Omitting "+e.name+" from scene."):(e.parent||this._babylonScene.useRightHandedSystem||SV(s),e.parent&&!o.has(e.parent)||t.nodes.push(i)),e instanceof ha&&e.skeleton&&(s.skin=h[e.skeleton.uniqueId]),r=e.getDescendants(!0),!s.children&&r&&r.length)){const e=[];for(const t of r)null!=this._nodeMap[t.uniqueId]&&e.push(this._nodeMap[t.uniqueId]);e.length&&(s.children=e)}t.nodes.length&&this._scenes.push(t)}))))))}_getExportNodes(e){const t=[],i=new Set;for(const s of e)if(!this._options.shouldExportNode||this._options.shouldExportNode(s)){t.push(s);const e=s;if(e.subMeshes&&e.subMeshes.length>0){const t=e.material||e.getScene().defaultMaterial;if(t instanceof ia)for(const e of t.subMaterials)e&&i.add(e);else i.add(t)}}else s.name;return[t,i]}_createNodeMapAndAnimationsAsync(e,t){let i=Promise.resolve();const s={};let r;const n={name:"runtime animations",channels:[],samplers:[]},o=[];for(const a of e)i=i.then((()=>this._createNodeAsync(a,t).then((e=>{const i=this._extensionsPostExportNodeAsync("createNodeAsync",e,a,s,t);return null==i?(Ds.Warn(`Not exporting node ${a.name}`),Promise.resolve()):i.then((e=>{e&&(this._nodes.push(e),r=this._nodes.length-1,s[a.uniqueId]=r,this._babylonScene.animationGroups.length||(gV._CreateMorphTargetAnimationFromMorphTargetAnimations(a,n,o,s,this._nodes,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation),a.animations.length&&gV._CreateNodeAnimationFromNodeAnimations(a,n,o,s,this._nodes,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation)))}))}))));return i.then((()=>(n.channels.length&&n.samplers.length&&this._animations.push(n),o.forEach((e=>{e.channels.length&&e.samplers.length&&this._animations.push(e)})),this._babylonScene.animationGroups.length&&gV._CreateNodeAndMorphAnimationFromAnimationGroups(this._babylonScene,this._animations,s,t,this._bufferViews,this._accessors,this._animationSampleRate,this._options.shouldExportAnimation),s)))}_createNodeAsync(e,t){return Promise.resolve().then((()=>{const i={},s={primitives:[]};if(e.name&&(i.name=e.name),e instanceof lo){if(this._setNodeTransformation(i,e),e instanceof ha){const t=e.morphTargetManager;if(t&&t.numTargets>0){s.weights=[];for(let e=0;e(s.primitives.length&&(this._meshes.push(s),i.mesh=this._meshes.length-1),i)))}return e instanceof In?(this._setCameraTransformation(i,e),i):i}))}_createSkinsAsync(e,t){const i=Promise.resolve(),s={};for(const i of this._babylonScene.skeletons){if(i.bones.length<=0)continue;const r={joints:[]},n=[],o={};let a=-1;for(let e=0;ea&&(a=s))}for(let t=0;t<=a;++t){const i=o[t];n.push(i.getInvertedAbsoluteTransform());const s=i.getTransformNode();s&&null!==e[s.uniqueId]&&void 0!==e[s.uniqueId]?r.joints.push(e[s.uniqueId]):Ds.Warn("Exporting a bone without a linked transform node is currently unsupported")}if(r.joints.length>0){const e=64,o=n.length*e,a=t.getByteOffset(),l=mV._CreateBufferView(0,a,o,void 0,"InverseBindMatrices - "+i.name);this._bufferViews.push(l);const h=this._bufferViews.length-1,c=mV._CreateAccessor(h,"InverseBindMatrices - "+i.name,"MAT4",5126,n.length,null,null,null),u=this._accessors.push(c)-1;r.inverseBindMatrices=u,this._skins.push(r),s[i.uniqueId]=this._skins.length-1,n.forEach((e=>{e.m.forEach((e=>{t.setFloat32(e)}))}))}}return i.then((()=>s))}}CV._ExtensionNames=new Array,CV._ExtensionFactories={};class EV{constructor(e){this._arrayBuffer=new ArrayBuffer(e),this._dataView=new DataView(this._arrayBuffer),this._byteOffset=0}_resizeBuffer(e){const t=new ArrayBuffer(e),i=Math.min(this._arrayBuffer.byteLength,e),s=new Uint8Array(this._arrayBuffer,0,i);return new Uint8Array(t).set(s,0),this._arrayBuffer=t,this._dataView=new DataView(this._arrayBuffer),t}getArrayBuffer(){return this._resizeBuffer(this.getByteOffset())}getByteOffset(){if(null==this._byteOffset)throw new Error("Byte offset is undefined!");return this._byteOffset}setUInt8(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint8(this._byteOffset,e),this._byteOffset+=1)}setUInt16(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint16(this._byteOffset,e,!0),this._byteOffset+=2)}getUInt32(e){if(ethis._byteOffset?Ds.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(e.x=this._dataView.getFloat32(t,!0),e.y=this._dataView.getFloat32(t+4,!0),e.z=this._dataView.getFloat32(t+8,!0))}setVector3Float32FromRef(e,t){t+8>this._byteOffset?Ds.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._dataView.setFloat32(t,e.x,!0),this._dataView.setFloat32(t+4,e.y,!0),this._dataView.setFloat32(t+8,e.z,!0))}getVector4Float32FromRef(e,t){t+12>this._byteOffset?Ds.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(e.x=this._dataView.getFloat32(t,!0),e.y=this._dataView.getFloat32(t+4,!0),e.z=this._dataView.getFloat32(t+8,!0),e.w=this._dataView.getFloat32(t+12,!0))}setVector4Float32FromRef(e,t){t+12>this._byteOffset?Ds.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!"):(this._dataView.setFloat32(t,e.x,!0),this._dataView.setFloat32(t+4,e.y,!0),this._dataView.setFloat32(t+8,e.z,!0),this._dataView.setFloat32(t+12,e.w,!0))}setFloat32(e,t){isNaN(e)&&Ds.Error("Invalid data being written!"),null!=t&&(tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setFloat32(this._byteOffset,e,!0),this._byteOffset+=4}setUInt32(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setUint32(this._byteOffset,e,!0),this._byteOffset+=4)}setInt16(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setInt16(this._byteOffset,e,!0),this._byteOffset+=2)}setByte(e,t){null!=t?tthis._arrayBuffer.byteLength&&this._resizeBuffer(2*this._arrayBuffer.byteLength),this._dataView.setInt8(this._byteOffset,e),this._byteOffset++)}}class AV{static GLTFAsync(e,t,i){return e.whenReadyAsync().then((()=>{const s=t.replace(/\.[^/.]+$/,"");return new CV(e,i)._generateGLTFAsync(s)}))}static _PreExportAsync(e,t){return Promise.resolve().then((()=>t&&t.exportWithoutWaitingForScene?Promise.resolve():e.whenReadyAsync()))}static _PostExportAsync(e,t,i){return Promise.resolve().then((()=>(i&&i.exportWithoutWaitingForScene,t)))}static GLBAsync(e,t,i){return this._PreExportAsync(e,i).then((()=>{const s=t.replace(/\.[^/.]+$/,"");return new CV(e,i)._generateGLBAsync(s).then((t=>this._PostExportAsync(e,t,i)))}))}}const PV="KHR_texture_transform";class IV{constructor(){this.name=PV,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}postExportTexture(e,t,i){if(i&&(0===i.uAng&&0===i.wAng&&0===i.vAng||0===i.uRotationCenter&&0===i.vRotationCenter)){const e={};let s=!1;if(0===i.uOffset&&0===i.vOffset||(e.offset=[i.uOffset,i.vOffset],s=!0),1===i.uScale&&1===i.vScale||(e.scale=[i.uScale,i.vScale],s=!0),0!==i.wAng&&(e.rotation=-i.wAng,s=!0),0!==i.coordinatesIndex&&(e.texCoord=i.coordinatesIndex,s=!0),!s)return;this._wasUsed=!0,t.extensions||(t.extensions={}),t.extensions[PV]=e}}preExportTextureAsync(e,t){return new Promise(((i,s)=>{t.getScene()?0!==t.uAng||0!==t.vAng?(Ds.Warn(`${e}: Texture ${t.name} with rotation in the u or v axis is not supported in glTF.`),i(null)):0===t.wAng||0===t.uRotationCenter&&0===t.vRotationCenter?i(t):(Ds.Warn(`${e}: Texture ${t.name} with rotation not centered at the origin cannot be exported with ${PV}`),i(null)):s(`${e}: "scene" is not defined for Babylon texture ${t.name}!`)}))}}CV.RegisterExtension(PV,(()=>new IV));const RV="KHR_lights_punctual";class MV{constructor(e){this.name=RV,this.enabled=!0,this.required=!1,this._exporter=e}dispose(){this._lights=null}get wasUsed(){return!!this._lights}onExporting(){this._exporter._glTF.extensions[RV]=this._lights}postExportNodeAsync(e,t,i,s){return new Promise((r=>{if(t&&i instanceof hg){let n;const o=i.getTypeID()==ua.LIGHTTYPEID_POINTLIGHT?"point":i.getTypeID()==ua.LIGHTTYPEID_DIRECTIONALLIGHT?"directional":i.getTypeID()==ua.LIGHTTYPEID_SPOTLIGHT?"spot":null;if(null==o)Ne.Warn(`${e}: Light ${i.name} is not supported in ${RV}`);else{if(i.position.equalsToFloats(0,0,0)||(t.translation=i.position.asArray()),"point"!==o){const e=i.direction,s=-Math.atan2(e.z,e.x)+Math.PI/2,r=Math.sqrt(e.x*e.x+e.z*e.z),n=-Math.atan2(e.y,r),o=fe.RotationYawPitchRoll(s+Math.PI,n,0);fe.IsIdentity(o)||(t.rotation=o.asArray())}if(i.falloffType!==ua.FALLOFF_GLTF&&Ne.Warn(`${e}: Light falloff for ${i.name} does not match the ${RV} specification!`),n={type:o},i.diffuse.equals(Ee.White())||(n.color=i.diffuse.asArray()),1!==i.intensity&&(n.intensity=i.intensity),i.range!==Number.MAX_VALUE&&(n.range=i.range),"spot"===o){const e=i;e.angle!==Math.PI/2&&(null==n.spot&&(n.spot={}),n.spot.outerConeAngle=e.angle/2),0!==e.innerAngle&&(null==n.spot&&(n.spot={}),n.spot.innerConeAngle=e.innerAngle/2)}this._lights||(this._lights={lights:[]}),this._lights.lights.push(n);const a={light:this._lights.lights.length-1},l=i.parent;if(l&&1==l.getChildren().length){const e=this._exporter._nodes[s[l.uniqueId]];if(e){const i=_e.FromArrayToRef(e.translation||[0,0,0],0,ve.Vector3[0]),s=fe.FromArrayToRef(e.rotation||[0,0,0,1],0,ve.Quaternion[0]),n=_e.FromArrayToRef(e.scale||[1,1,1],0,ve.Vector3[1]),o=me.ComposeToRef(n,s,i,ve.Matrix[0]),l=_e.FromArrayToRef(t.translation||[0,0,0],0,ve.Vector3[2]),h=fe.FromArrayToRef(t.rotation||[0,0,0,1],0,ve.Quaternion[1]),c=me.ComposeToRef(_e.OneReadOnly,h,l,ve.Matrix[1]);return o.multiplyToRef(c,c),c.decompose(n,s,i),i.equalsToFloats(0,0,0)?delete e.translation:e.translation=i.asArray(),fe.IsIdentity(s)?delete e.rotation:e.rotation=s.asArray(),n.equalsToFloats(1,1,1)?delete e.scale:e.scale=n.asArray(),e.extensions||(e.extensions={}),e.extensions[RV]=a,void r(null)}}t.extensions||(t.extensions={}),t.extensions[RV]=a}}r(t)}))}}CV.RegisterExtension(RV,(e=>new MV(e)));const OV="KHR_materials_clearcoat";class DV{constructor(e){this.name=OV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Gg&&i.clearCoat.isEnabled?(i.clearCoat.texture&&s.push(i.clearCoat.texture),!i.clearCoat.useRoughnessFromMainTexture&&i.clearCoat.textureRoughness&&s.push(i.clearCoat.textureRoughness),i.clearCoat.bumpTexture&&s.push(i.clearCoat.bumpTexture),s):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Gg){if(!i.clearCoat.isEnabled)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const s=this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.texture);let r;r=i.clearCoat.useRoughnessFromMainTexture?this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.texture):this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.textureRoughness),i.clearCoat.isTintEnabled&&Ds.Warn(`Clear Color tint is not supported for glTF export. Ignoring for: ${i.name}`),i.clearCoat.remapF0OnInterfaceChange&&Ds.Warn(`Clear Color F0 remapping is not supported for glTF export. Ignoring for: ${i.name}`);const n=this._exporter._glTFMaterialExporter._getTextureInfo(i.clearCoat.bumpTexture),o={clearcoatFactor:i.clearCoat.intensity,clearcoatTexture:s??void 0,clearcoatRoughnessFactor:i.clearCoat.roughness,clearcoatRoughnessTexture:r??void 0,clearcoatNormalTexture:n??void 0,hasTextures:()=>null!==o.clearcoatTexture||null!==o.clearcoatRoughnessTexture||null!==o.clearcoatRoughnessTexture};t.extensions[OV]=o}e(t)}))}}CV.RegisterExtension(OV,(e=>new DV(e)));const wV="KHR_materials_iridescence";class NV{constructor(e){this.name=wV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Gg&&i.iridescence.isEnabled?(i.iridescence.texture&&s.push(i.iridescence.texture),i.iridescence.thicknessTexture&&i.iridescence.thicknessTexture!==i.iridescence.texture&&s.push(i.iridescence.thicknessTexture),s):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Gg){if(!i.iridescence.isEnabled)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const s=this._exporter._glTFMaterialExporter._getTextureInfo(i.iridescence.texture),r=this._exporter._glTFMaterialExporter._getTextureInfo(i.iridescence.thicknessTexture),n={iridescenceFactor:i.iridescence.intensity,iridescenceIor:i.iridescence.indexOfRefraction,iridescenceThicknessMinimum:i.iridescence.minimumThickness,iridescenceThicknessMaximum:i.iridescence.maximumThickness,iridescenceTexture:s??void 0,iridescenceThicknessTexture:r??void 0,hasTextures:()=>null!==n.iridescenceTexture||null!==n.iridescenceThicknessTexture};t.extensions[wV]=n}e(t)}))}}CV.RegisterExtension(wV,(e=>new NV(e)));const FV="KHR_materials_anisotropy";class LV{constructor(e){this.name=FV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof Gg&&i.anisotropy.isEnabled&&!i.anisotropy.legacy?(i.anisotropy.texture&&s.push(i.anisotropy.texture),s):[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof Gg){if(!i.anisotropy.isEnabled||i.anisotropy.legacy)return void e(t);this._wasUsed=!0,t.extensions=t.extensions||{};const s=this._exporter._glTFMaterialExporter._getTextureInfo(i.anisotropy.texture),r={anisotropyStrength:i.anisotropy.intensity,anisotropyRotation:i.anisotropy.angle,anisotropyTexture:s??void 0,hasTextures:()=>null!==r.anisotropyTexture};t.extensions[FV]=r}e(t)}))}}CV.RegisterExtension(FV,(e=>new LV(e)));const BV="KHR_materials_sheen";class kV{constructor(e){this.name=BV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){return i instanceof zg&&i.sheen.isEnabled&&i.sheen.texture?[i.sheen.texture]:[]}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zg){if(!i.sheen.isEnabled)return void e(t);this._wasUsed=!0,null==t.extensions&&(t.extensions={});const s={sheenColorFactor:i.sheen.color.asArray(),sheenRoughnessFactor:i.sheen.roughness??0,hasTextures:()=>null!==s.sheenColorTexture||null!==s.sheenRoughnessTexture};i.sheen.texture&&(s.sheenColorTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.texture)??void 0),i.sheen.textureRoughness&&!i.sheen.useRoughnessFromMainTexture?s.sheenRoughnessTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.textureRoughness)??void 0:i.sheen.texture&&i.sheen.useRoughnessFromMainTexture&&(s.sheenRoughnessTexture=this._exporter._glTFMaterialExporter._getTextureInfo(i.sheen.texture)??void 0),t.extensions[BV]=s}e(t)}))}}CV.RegisterExtension(BV,(e=>new kV(e)));const VV="KHR_materials_unlit";class UV{constructor(){this.name=VV,this.enabled=!0,this.required=!1,this._wasUsed=!1}get wasUsed(){return this._wasUsed}dispose(){}postExportMaterialAsync(e,t,i){return new Promise((e=>{let s=!1;i instanceof zg?s=i.unlit:i instanceof cu&&(s=i.disableLighting),s&&(this._wasUsed=!0,null==t.extensions&&(t.extensions={}),t.extensions[VV]={}),e(t)}))}}CV.RegisterExtension(VV,(()=>new UV));const GV="KHR_materials_ior";class zV{constructor(){this.name=GV,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}_isExtensionEnabled(e){return!e.unlit&&null!=e.indexOfRefraction&&1.5!=e.indexOfRefraction}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zg&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e={ior:i.indexOfRefraction};t.extensions=t.extensions||{},t.extensions[GV]=e}e(t)}))}}CV.RegisterExtension(GV,(e=>new zV));const WV="KHR_materials_specular";class HV{constructor(e){this.name=WV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof zg&&this._isExtensionEnabled(i)?(i.metallicReflectanceTexture&&s.push(i.metallicReflectanceTexture),i.reflectanceTexture&&s.push(i.reflectanceTexture),s):s}_isExtensionEnabled(e){return!e.unlit&&(null!=e.metallicF0Factor&&1!=e.metallicF0Factor||null!=e.metallicReflectanceColor&&!e.metallicReflectanceColor.equalsFloats(1,1,1)||this._hasTexturesExtension(e))}_hasTexturesExtension(e){return null!=e.metallicReflectanceTexture||null!=e.reflectanceTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zg&&this._isExtensionEnabled(i)){this._wasUsed=!0,t.extensions=t.extensions||{};const e=this._exporter._glTFMaterialExporter._getTextureInfo(i.metallicReflectanceTexture)??void 0,s=this._exporter._glTFMaterialExporter._getTextureInfo(i.reflectanceTexture)??void 0,r={specularFactor:1==i.metallicF0Factor?void 0:i.metallicF0Factor,specularTexture:e,specularColorFactor:i.metallicReflectanceColor.equalsFloats(1,1,1)?void 0:i.metallicReflectanceColor.asArray(),specularColorTexture:s,hasTextures:()=>this._hasTexturesExtension(i)};t.extensions[WV]=r}e(t)}))}}CV.RegisterExtension(WV,(e=>new HV(e)));const XV="KHR_materials_volume";class YV{constructor(e){this.name=XV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof zg&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&s.push(i.subSurface.thicknessTexture),s):s}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!(!t.isRefractionEnabled&&!t.isTranslucencyEnabled)&&(null!=t.maximumThickness&&0!=t.maximumThickness||null!=t.tintColorAtDistance&&t.tintColorAtDistance!=Number.POSITIVE_INFINITY||null!=t.tintColor&&t.tintColor!=Ee.White()||this._hasTexturesExtension(e))}_hasTexturesExtension(e){return null!=e.subSurface.thicknessTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zg&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e=i.subSurface,s={thicknessFactor:0==e.maximumThickness?void 0:e.maximumThickness,thicknessTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.thicknessTexture)??void 0,attenuationDistance:e.tintColorAtDistance==Number.POSITIVE_INFINITY?void 0:e.tintColorAtDistance,attenuationColor:e.tintColor.equalsFloats(1,1,1)?void 0:e.tintColor.asArray(),hasTextures:()=>this._hasTexturesExtension(i)};t.extensions=t.extensions||{},t.extensions[XV]=s}e(t)}))}}CV.RegisterExtension(XV,(e=>new YV(e)));const QV="KHR_materials_dispersion";class jV{constructor(){this.name=QV,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!(!t.isRefractionEnabled&&!t.isDispersionEnabled)}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zg&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e={dispersion:i.subSurface.dispersion};t.extensions=t.extensions||{},t.extensions[QV]=e}e(t)}))}}CV.RegisterExtension(QV,(()=>new jV));const KV="KHR_materials_transmission";class $V{constructor(e){this.name=KV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof zg&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&s.push(i.subSurface.thicknessTexture),s):s}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return t.isRefractionEnabled&&null!=t.refractionIntensity&&0!=t.refractionIntensity||this._hasTexturesExtension(e)}_hasTexturesExtension(e){return null!=e.subSurface.refractionIntensityTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zg&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e=i.subSurface,s={transmissionFactor:0===e.refractionIntensity?void 0:e.refractionIntensity,transmissionTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.refractionIntensityTexture)??void 0,hasTextures:()=>this._hasTexturesExtension(i)};t.extensions=t.extensions||{},t.extensions[KV]=s}e(t)}))}}CV.RegisterExtension(KV,(e=>new $V(e)));const qV="EXT_mesh_gpu_instancing";class ZV{constructor(e){this.name=qV,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportNodeAsync(e,t,i,s,r){return new Promise((e=>{if(t&&i instanceof ha&&i.hasThinInstances&&r){this._wasUsed=!0;const e=_e.Zero(),s=fe.Identity(),n=_e.One(),o=i.thinInstanceGetWorldMatrices(),a=ve.Vector3[2],l=ve.Quaternion[1],h=ve.Vector3[3];let c=!1,u=!1,d=!1;const _=new Float32Array(3*i.thinInstanceCount),p=new Float32Array(4*i.thinInstanceCount),f=new Float32Array(3*i.thinInstanceCount);let m=0;for(const t of o)t.decompose(h,l,a),_.set(a.asArray(),3*m),p.set(l.normalize().asArray(),4*m),f.set(h.asArray(),3*m),c=c||!a.equalsWithEpsilon(e),u=u||!l.equalsWithEpsilon(s),d=d||!h.equalsWithEpsilon(n),m++;const g={attributes:{}};if(c&&(g.attributes.TRANSLATION=this._buildAccessor(_,"VEC3",i.thinInstanceCount,r,5126)),u){const e=5126;g.attributes.ROTATION=this._buildAccessor(p,"VEC4",i.thinInstanceCount,r,e)}d&&(g.attributes.SCALE=this._buildAccessor(f,"VEC3",i.thinInstanceCount,r,5126)),t.extensions=t.extensions||{},t.extensions[qV]=g}e(t)}))}_buildAccessor(e,t,i,s,r){const n=s.getByteOffset();switch(r){case 5126:for(let t=0;t!=e.length;t++)s.setFloat32(e[t]);break;case 5120:for(let t=0;t!=e.length;t++)s.setByte(127*e[t]);break;case 5122:for(let t=0;t!=e.length;t++)s.setInt16(32767*e[t])}const o={buffer:0,byteOffset:n,byteLength:e.length*er.GetTypeByteLength(r)},a=this._exporter._bufferViews.length;this._exporter._bufferViews.push(o);const l=this._exporter._accessors.length,h={bufferView:a,componentType:r,count:i,type:t,normalized:5120==r||5122==r};return this._exporter._accessors.push(h),l}}CV.RegisterExtension(qV,(e=>new ZV(e)));const JV="KHR_materials_emissive_strength";class eU{constructor(){this.name=JV,this.enabled=!0,this.required=!1,this._wasUsed=!1}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(!(i instanceof zg))return e(t);const s=i.emissiveColor.asArray(),r=Math.max(...s);if(r>1){this._wasUsed=!0,t.extensions||(t.extensions={});const e={emissiveStrength:r},s=i.emissiveColor.scale(1/e.emissiveStrength);t.emissiveFactor=s.asArray(),t.extensions[JV]=e}return e(t)}))}}CV.RegisterExtension(JV,(e=>new eU));const tU="KHR_materials_diffuse_transmission";class iU{constructor(e){this.name=tU,this.enabled=!0,this.required=!1,this._wasUsed=!1,this._exporter=e}dispose(){}get wasUsed(){return this._wasUsed}postExportMaterialAdditionalTextures(e,t,i){const s=[];return i instanceof zg&&this._isExtensionEnabled(i)?(i.subSurface.thicknessTexture&&s.push(i.subSurface.thicknessTexture),s):s}_isExtensionEnabled(e){if(e.unlit)return!1;const t=e.subSurface;return!!t.isTranslucencyEnabled&&!e.unlit&&!t.useAlbedoToTintTranslucency&&t.useGltfStyleTextures&&1===t.volumeIndexOfRefraction&&0===t.minimumThickness&&0===t.maximumThickness}_hasTexturesExtension(e){return null!=e.subSurface.translucencyIntensityTexture||null!=e.subSurface.translucencyColorTexture}postExportMaterialAsync(e,t,i){return new Promise((e=>{if(i instanceof zg&&this._isExtensionEnabled(i)){this._wasUsed=!0;const e=i.subSurface,s={diffuseTransmissionFactor:1==e.translucencyIntensity?void 0:e.translucencyIntensity,diffuseTransmissionTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.translucencyIntensityTexture)??void 0,diffuseTransmissionColorFactor:!e.translucencyColor||e.translucencyColor.equalsFloats(1,1,1)?void 0:e.translucencyColor.asArray(),diffuseTransmissionColorTexture:this._exporter._glTFMaterialExporter._getTextureInfo(e.translucencyColorTexture)??void 0,hasTextures:()=>this._hasTexturesExtension(i)};t.extensions=t.extensions||{},t.extensions[tU]=s}e(t)}))}}CV.RegisterExtension(tU,(e=>new iU(e)));class sU{static CreateSTL(e,t=!0,i="stlmesh",s=!1,r=!0,n=!1,o=!1,a=!1){const l=function(e,t,i){const s=[3*e[i],3*e[i+1],3*e[i+2]],r=[new _e(t[s[0]],t[s[0]+2],t[s[0]+1]),new _e(t[s[1]],t[s[1]+2],t[s[1]+1]),new _e(t[s[2]],t[s[2]+2],t[s[2]+1])],n=r[0].subtract(r[1]),o=r[2].subtract(r[1]);return{v:r,n:_e.Cross(o,n).normalize()}},h=function(e,t,i,s){return t=c(e,t,i.x,s),t=c(e,t,i.y,s),c(e,t,i.z,s)},c=function(e,t,i,s){return e.setFloat32(t,i,s),t+4},u=function(e){if(o){let t=e;e instanceof ca&&(t=e.sourceMesh);const i=t.getVerticesData(er.PositionKind,!0,!0);if(!i)return[];const s=_e.Zero();let r;for(r=0;r"bitbybit-hdrSkyBox"!==e.name&&!e.name.includes("bitbybit-ground")}),AV.GLBAsync(this.context.scene,e.fileName,t).then((e=>{e.downloadFiles()}))}exportMeshToStl(e){return NU(this,void 0,void 0,(function*(){const t=e.mesh.getChildMeshes();let i=[];t&&t.length>0&&(i=t.filter((e=>!(e instanceof Fd||e instanceof MS))));let s=[e.mesh,...i];return s=s.filter((e=>e.isVisible)),sU.CreateSTL(s,!0,e.fileName,!0,!0,!0),Promise.resolve({})}))}exportMeshesToStl(e){return NU(this,void 0,void 0,(function*(){let t;return e.meshes.forEach((e=>{const i=e.getChildMeshes();let s=[];i&&i.length>0&&(s=i.filter((e=>!(e instanceof Fd||e instanceof MS)))),t.push(e),s.length>0&&t.push(...s)})),sU.CreateSTL(t,!0,e.fileName,!0,!0,!0),Promise.resolve({})}))}loadAsset(e,t,i,s){return NU(this,void 0,void 0,(function*(){const e=yield fl.ImportMeshAsync("",t,i,this.context.scene),r=this.context.scene.metadata.shadowGenerators,n=new ha("ImportedMeshContainer"+Math.random(),this.context.scene);return r.length>0&&e.meshes.forEach((e=>{if(e.isPickable=!1,s&&(e.isVisible=!1),e.getChildMeshes().forEach((e=>{e.isPickable=!1,s&&(e.isVisible=!1)})),this.context.scene.metadata.shadowGenerators.length>0){try{e.receiveShadows=!0}catch(e){}r.forEach((t=>{t.addShadowCaster(e)})),e.getChildMeshes().forEach((e=>{try{e.receiveShadows=!0}catch(e){}r.forEach((t=>{t.addShadowCaster(e)}))}))}})),e.meshes.forEach((e=>{e.parent=n})),n}))}}!function(e){e.GetAssetDto=class{constructor(e){void 0!==e&&(this.fileName=e)}},e.FileDto=class{constructor(e){void 0!==e&&(this.file=e)}},e.FetchDto=class{constructor(e,t){void 0!==e&&(this.url=e),void 0!==t&&(this.options=t)}},e.FilesDto=class{constructor(e){void 0!==e&&(this.files=e)}},e.AssetFileDto=class{constructor(e,t){this.hidden=!1,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.hidden=t)}},e.AssetFileByUrlDto=class{constructor(e,t,i){this.hidden=!1,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.rootUrl=t),void 0!==i&&(this.hidden=i)}}}(rU||(rU={})),function(e){e.ArcRotateCameraDto=class{constructor(e,t,i,s,r,n,o,a,l,h){this.radius=20,this.target=[0,0,0],this.alpha=45,this.beta=70,this.lowerBetaLimit=1,this.upperBetaLimit=179,this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.panningSensibility=1e3,this.wheelPrecision=3,this.maxZ=1e3,void 0!==e&&(this.radius=e),void 0!==t&&(this.alpha=t),void 0!==i&&(this.beta=i),void 0!==s&&(this.lowerBetaLimit=s),void 0!==r&&(this.upperBetaLimit=r),void 0!==n&&(this.angularSensibilityX=n),void 0!==o&&(this.angularSensibilityY=o),void 0!==a&&(this.panningSensibility=a),void 0!==l&&(this.wheelPrecision=l),void 0!==h&&(this.maxZ=h)}},e.FreeCameraDto=class{constructor(e,t){this.position=[20,20,20],this.target=[0,0,0],void 0!==e&&(this.position=e),void 0!==t&&(this.target=t)}},e.TargetCameraDto=class{constructor(e,t){this.position=[20,20,20],this.target=[0,0,0],void 0!==e&&(this.position=e),void 0!==t&&(this.target=t)}},e.PositionDto=class{constructor(e,t){this.position=[20,20,20],void 0!==e&&(this.camera=e),void 0!==t&&(this.position=t)}},e.SpeedDto=class{constructor(e,t){this.speed=1,void 0!==e&&(this.camera=e),void 0!==t&&(this.speed=t)}},e.TargetDto=class{constructor(e,t){this.target=[0,0,0],void 0!==e&&(this.camera=e),void 0!==t&&(this.target=t)}},e.MinZDto=class{constructor(e,t){this.minZ=0,void 0!==e&&(this.camera=e),void 0!==t&&(this.minZ=t)}},e.MaxZDto=class{constructor(e,t){this.maxZ=1e3,void 0!==e&&(this.camera=e),void 0!==t&&(this.maxZ=t)}},e.OrthographicDto=class{constructor(e,t,i,s,r){this.orthoLeft=-1,this.orthoRight=1,this.orthoBottom=-1,this.orthoTop=1,void 0!==e&&(this.camera=e),void 0!==t&&(this.orthoLeft=t),void 0!==i&&(this.orthoRight=i),void 0!==s&&(this.orthoTop=s),void 0!==r&&(this.orthoBottom=r)}},e.CameraDto=class{constructor(e){void 0!==e&&(this.camera=e)}}}(nU||(nU={})),function(e){e.ExportSceneGlbDto=class{constructor(e,t){this.fileName="bitbybit-scene",this.discardSkyboxAndGrid=!1,void 0!==e&&(this.fileName=e),void 0!==t&&(this.discardSkyboxAndGrid=t)}},e.ExportSceneDto=class{constructor(e){this.fileName="bitbybit-scene",void 0!==e&&(this.fileName=e)}},e.ExportMeshToStlDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.fileName=t)}},e.ExportMeshesToStlDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.fileName=t)}}}(oU||(oU={})),function(e){e.PBRMetallicRoughnessDto=class{constructor(e,t,i,s,r,n,o,a){this.name="Custom Material",this.baseColor="#0000ff",this.emissiveColor="#000000",this.metallic=.6,this.roughness=.5,this.alpha=1,this.backFaceCulling=!1,this.zOffset=0,void 0!==e&&(this.name=e),void 0!==t&&(this.baseColor=t),void 0!==i&&(this.emissiveColor=i),void 0!==s&&(this.metallic=s),void 0!==r&&(this.roughness=r),void 0!==n&&(this.alpha=n),void 0!==o&&(this.backFaceCulling=o),void 0!==a&&(this.zOffset=a)}},e.BaseColorDto=class{constructor(e,t){this.baseColor="#0000ff",void 0!==e&&(this.material=e),void 0!==t&&(this.baseColor=t)}},e.MaterialPropDto=class{constructor(e){void 0!==e&&(this.material=e)}},e.MetallicDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.metallic=t)}},e.RoughnessDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.roughness=t)}},e.AlphaDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.alpha=t)}},e.BackFaceCullingDto=class{constructor(e,t){this.backFaceCulling=!0,void 0!==e&&(this.material=e),void 0!==t&&(this.backFaceCulling=t)}},e.BaseTextureDto=class{constructor(e,t){void 0!==e&&(this.material=e),void 0!==t&&(this.baseTexture=t)}}}(aU||(aU={})),function(e){e.CreateGaussianSplattingMeshDto=class{constructor(e){void 0!==e&&(this.url=e)}}}(lU||(lU={})),function(e){let t;!function(e){e.frontside="frontside",e.backside="backside",e.doubleside="doubleside"}(t=e.sideOrientationEnum||(e.sideOrientationEnum={})),e.UpdateDrawnBabylonMesh=class{constructor(e,t,i,s,r){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.rotation=i),void 0!==s&&(this.scaling=s),void 0!==r&&(this.colours=r)}},e.SetParentDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.parentMesh=t)}},e.UpdateDrawnBabylonMeshPositionDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.position=t)}},e.UpdateDrawnBabylonMeshRotationDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.rotation=t)}},e.UpdateDrawnBabylonMeshScaleDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.scale=t)}},e.IntersectsMeshDto=class{constructor(e,t,i,s){this.precise=!1,this.includeDescendants=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.babylonMesh2=t),void 0!==i&&(this.precise=i),void 0!==s&&(this.includeDescendants=s)}},e.IntersectsPointDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.point=t)}},e.BabylonMeshDto=class{constructor(e){void 0!==e&&(this.babylonMesh=e)}},e.ShowHideMeshDto=class{constructor(e,t){this.includeChildren=!0,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.includeChildren=t)}},e.CloneBabylonMeshDto=class{constructor(e){void 0!==e&&(this.babylonMesh=e)}},e.ChildMeshesBabylonMeshDto=class{constructor(e,t){this.directDescendantsOnly=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.directDescendantsOnly=t)}},e.TranslateBabylonMeshDto=class{constructor(e,t){this.distance=0,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.distance=t)}},e.NameBabylonMeshDto=class{constructor(e,t,i){this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.name=t),void 0!==i&&(this.includeChildren=i)}},e.ByNameBabylonMeshDto=class{constructor(e){void 0!==e&&(this.name=e)}},e.MaterialBabylonMeshDto=class{constructor(e,t,i){this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.material=t),void 0!==i&&(this.includeChildren=i)}},e.IdBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.id=t)}},e.ByIdBabylonMeshDto=class{constructor(e){void 0!==e&&(this.id=e)}},e.UniqueIdBabylonMeshDto=class{constructor(e){void 0!==e&&(this.uniqueId=e)}},e.PickableBabylonMeshDto=class{constructor(e,t,i){this.pickable=!1,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.pickable=t),void 0!==i&&(this.includeChildren=i)}},e.CheckCollisionsBabylonMeshDto=class{constructor(e,t,i){this.checkCollisions=!1,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.checkCollisions=t),void 0!==i&&(this.includeChildren=i)}},e.RotateBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.rotate=t)}},e.SetMeshVisibilityDto=class{constructor(e,t,i){this.visibility=0,this.includeChildren=!1,void 0!==e&&(this.babylonMesh=e),void 0!==t&&(this.visibility=t),void 0!==i&&(this.includeChildren=i)}},e.MeshInstanceAndTransformDto=class{constructor(e,t,i,s){void 0!==e&&(this.mesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.rotation=i),void 0!==s&&(this.scaling=s)}},e.MeshInstanceDto=class{constructor(e){void 0!==e&&(this.mesh=e)}},e.RotateAroundAxisNodeDto=class{constructor(e,t,i,s){this.position=[0,0,0],this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.mesh=e),void 0!==t&&(this.position=t),void 0!==i&&(this.axis=i),void 0!==s&&(this.angle=s)}}}(hU||(hU={})),function(e){e.RayDto=class{constructor(e){void 0!==e&&(this.ray=e)}},e.PickInfo=class{constructor(e){void 0!==e&&(this.pickInfo=e)}}}(cU||(cU={})),function(e){e.BaseRayDto=class{constructor(e,t,i){void 0!==e&&(this.origin=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.length=i)}},e.RayDto=class{constructor(e){void 0!==e&&(this.ray=e)}},e.FromToDto=class{constructor(e,t){void 0!==e&&(this.from=e),void 0!==t&&(this.to=t)}}}(uU||(uU={})),function(e){e.CreateBoxDto=class{constructor(e,t,i,s){this.width=1,this.depth=1,this.height=1,this.sideOrientation=hU.sideOrientationEnum.frontside,void 0!==e&&(this.width=e),void 0!==t&&(this.depth=t),void 0!==i&&(this.height=i),void 0!==s&&(this.sideOrientation=s)}},e.CreateCubeDto=class{constructor(e,t){this.size=1,this.sideOrientation=hU.sideOrientationEnum.frontside,void 0!==e&&(this.size=e),void 0!==t&&(this.sideOrientation=t)}},e.CreateSquarePlaneDto=class{constructor(e,t){this.size=1,this.sideOrientation=hU.sideOrientationEnum.frontside,void 0!==e&&(this.size=e),void 0!==t&&(this.sideOrientation=t)}},e.CreateRectanglePlaneDto=class{constructor(e,t,i){this.width=1,this.height=1,this.sideOrientation=hU.sideOrientationEnum.frontside,void 0!==e&&(this.width=e),void 0!==t&&(this.height=t),void 0!==i&&(this.sideOrientation=i)}}}(dU||(dU={})),function(e){let t;!function(e){e.nearest="nearest",e.bilinear="bilinear",e.trilinear="trilinear"}(t=e.samplingModeEnum||(e.samplingModeEnum={})),e.TextureSimpleDto=class{constructor(t,i,s,r,n,o,a,l,h,c){this.name="Custom Texture",this.invertY=!1,this.invertZ=!1,this.wAng=0,this.uScale=1,this.vScale=1,this.uOffset=0,this.vOffset=0,this.samplingMode=e.samplingModeEnum.nearest,void 0!==t&&(this.name=t),void 0!==i&&(this.url=i),void 0!==s&&(this.invertY=s),void 0!==r&&(this.invertZ=r),void 0!==n&&(this.wAng=n),void 0!==o&&(this.uScale=o),void 0!==a&&(this.vScale=a),void 0!==l&&(this.uOffset=l),void 0!==h&&(this.vOffset=h),void 0!==c&&(this.samplingMode=c)}}}(_U||(_U={})),function(e){e.DefaultWebXRWithTeleportationDto=class{constructor(e){void 0!==e&&(this.groundMeshes=e)}}}(pU||(pU={})),function(e){e.HexDto=class{constructor(e){this.color="#0000ff",void 0!==e&&(this.color=e)}},e.HexDtoMapped=class{constructor(e,t,i){this.color="#0000ff",this.from=0,this.to=255,void 0!==e&&(this.color=e),void 0!==t&&(this.from=t),void 0!==i&&(this.to=i)}},e.RGBDto=class{constructor(e,t,i){this.r=255,this.g=255,this.b=255,void 0!==e&&(this.r=e),void 0!==t&&(this.g=t),void 0!==i&&(this.b=i)}},e.RGBObjectDto=class{constructor(e){void 0!==e&&(this.rgb=e)}}}(fU||(fU={})),function(e){let t;e.DrawAny=class{constructor(e,t,i){void 0!==e&&(this.entity=e),void 0!==t&&(this.options=t),void 0!==i&&(this.babylonMesh=i)}},e.SceneDrawGridMeshDto=class{constructor(e,t,i,s,r,n,o,a,l,h){this.width=400,this.height=400,this.subdivisions=10,this.majorUnitFrequency=10,this.minorUnitVisibility=.45,this.gridRatio=.5,this.opacity=.5,this.backFaceCulling=!1,this.mainColor="#ffffff",this.secondaryColor="#ffffff",void 0!==e&&(this.width=e),void 0!==t&&(this.height=t),void 0!==i&&(this.subdivisions=i),void 0!==s&&(this.majorUnitFrequency=s),void 0!==r&&(this.minorUnitVisibility=r),void 0!==n&&(this.gridRatio=n),void 0!==o&&(this.opacity=o),void 0!==a&&(this.backFaceCulling=a),void 0!==l&&(this.mainColor=l),void 0!==h&&(this.secondaryColor=h)}},e.DrawBasicGeometryOptions=class{constructor(e,t,i,s,r){this.colours="#ff0000",this.size=.1,this.opacity=1,this.updatable=!1,this.hidden=!1,void 0!==e&&(this.colours=e),void 0!==t&&(this.size=t),void 0!==i&&(this.opacity=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r)}},e.DrawNodeOptions=class{constructor(e,t,i,s){this.colorX="#0000ff",this.colorY="#00ff00",this.colorZ="#ff0000",this.size=2,void 0!==e&&(this.colorX=e),void 0!==t&&(this.colorY=t),void 0!==i&&(this.colorZ=i),void 0!==s&&(this.size=s)}},e.DrawOcctShapeOptions=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.vertexColour="#ffaaff",this.edgeWidth=2,this.vertexSize=.03,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.faceOpacity=e),void 0!==t&&(this.edgeOpacity=t),void 0!==i&&(this.edgeColour=i),void 0!==s&&(this.faceMaterial=s),void 0!==r&&(this.faceColour=r),void 0!==h&&(this.vertexColour=h),void 0!==c&&(this.vertexSize=c),void 0!==n&&(this.edgeWidth=n),void 0!==o&&(this.drawEdges=o),void 0!==a&&(this.drawFaces=a),void 0!==l&&(this.drawVertices=l),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdgeIndexes=d),void 0!==_&&(this.edgeIndexHeight=_),void 0!==p&&(this.edgeIndexColour=p),void 0!==f&&(this.drawFaceIndexes=f),void 0!==m&&(this.faceIndexHeight=m),void 0!==g&&(this.faceIndexColour=g)}},e.DrawOcctShapeSimpleOptions=class{constructor(e,t,i,s,r,n){this.precision=.01,this.drawFaces=!0,this.faceColour="#ff0000",this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=2,void 0!==e&&(this.precision=e),void 0!==t&&(this.drawFaces=t),void 0!==i&&(this.faceColour=i),void 0!==s&&(this.drawEdges=s),void 0!==r&&(this.edgeColour=r),void 0!==n&&(this.edgeWidth=n)}},e.DrawOcctShapeMaterialOptions=class{constructor(e,t,i,s,r){this.precision=.01,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=2,void 0!==e&&(this.precision=e),void 0!==t&&(this.faceMaterial=t),void 0!==i&&(this.drawEdges=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.edgeWidth=r)}},function(e){e[e.point=0]="point",e[e.points=1]="points",e[e.line=2]="line",e[e.lines=3]="lines",e[e.node=4]="node",e[e.nodes=5]="nodes",e[e.polyline=6]="polyline",e[e.polylines=7]="polylines",e[e.verbCurve=8]="verbCurve",e[e.verbCurves=9]="verbCurves",e[e.verbSurface=10]="verbSurface",e[e.verbSurfaces=11]="verbSurfaces",e[e.jscadMesh=12]="jscadMesh",e[e.jscadMeshes=13]="jscadMeshes",e[e.occt=14]="occt",e[e.tag=15]="tag",e[e.tags=16]="tags"}(t=e.drawingTypes||(e.drawingTypes={}))}(mU||(mU={})),function(e){let t,i;!function(e){e.edge="edge",e.round="round",e.chamfer="chamfer"}(t=e.solidCornerTypeEnum||(e.solidCornerTypeEnum={})),function(e){e.left="left",e.center="center",e.right="right"}(i=e.jscadTextAlignEnum||(e.jscadTextAlignEnum={})),e.DrawSolidMeshDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.mesh=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.jscadMesh=n)}},e.DrawSolidMeshesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.meshes=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.jscadMesh=n)}},e.DrawPathDto=class{constructor(e,t,i,s,r,n){this.colour="#444444",this.opacity=1,this.width=10,this.updatable=!1,void 0!==e&&(this.path=e),void 0!==t&&(this.colour=t),void 0!==i&&(this.opacity=i),void 0!==s&&(this.width=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.pathMesh=n)}},e.TransformSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.transformation=t)}},e.TransformSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.transformation=t)}},e.DownloadSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.fileName=t)}},e.DownloadGeometryDto=class{constructor(e,t){void 0!==e&&(this.geometry=e),void 0!==t&&(this.fileName=t)}},e.DownloadSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.fileName=t)}},e.ColorizeDto=class{constructor(e,t){this.color="#0000ff",void 0!==e&&(this.geometry=e),void 0!==t&&(this.color=t)}},e.BooleanObjectsDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.BooleanTwoObjectsDto=class{constructor(e,t){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.BooleanObjectsFromDto=class{constructor(e,t){void 0!==e&&(this.from=e),void 0!==t&&(this.meshes=t)}},e.ExpansionDto=class{constructor(e,i,s,r){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==s&&(this.corners=s),void 0!==r&&(this.segments=r)}},e.OffsetDto=class{constructor(e,i,s,r){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==s&&(this.corners=s),void 0!==r&&(this.segments=r)}},e.ExtrudeLinearDto=class{constructor(e,t,i,s){this.height=1,this.twistAngle=90,this.twistSteps=15,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.twistAngle=i),void 0!==s&&(this.twistSteps=s)}},e.HullDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.ExtrudeRectangularDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRectangularPointsDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.points=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRotateDto=class{constructor(e,t,i,s){this.angle=90,this.startAngle=0,this.segments=24,void 0!==e&&(this.polygon=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.startAngle=i),void 0!==s&&(this.segments=s)}},e.PathDto=class{constructor(e){void 0!==e&&(this.path=e)}},e.PathFromPointsDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.PathsFromPointsDto=class{constructor(e){void 0!==e&&(this.pointsLists=e)}},e.PathFromPolylineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.polyline=e),void 0!==t&&(this.closed=t)}},e.PathAppendCurveDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.path=t)}},e.PathAppendPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.path=t)}},e.PathAppendPolylineDto=class{constructor(e,t){void 0!==e&&(this.polyline=e),void 0!==t&&(this.path=t)}},e.PathAppendArcDto=class{constructor(e,t,i,s,r,n,o,a){this.endPoint=[1,1],this.xAxisRotation=90,this.clockwise=!0,this.large=!1,this.segments=24,this.radiusX=1,this.radiusY=1,void 0!==e&&(this.path=e),void 0!==t&&(this.endPoint=t),void 0!==i&&(this.xAxisRotation=i),void 0!==s&&(this.clockwise=s),void 0!==r&&(this.large=r),void 0!==n&&(this.segments=n),void 0!==o&&(this.radiusX=o),void 0!==a&&(this.radiusY=a)}},e.CircleDto=class{constructor(e,t,i){this.center=[0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipseDto=class{constructor(e,t,i){this.center=[0,0],this.radius=[1,2],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SquareDto=class{constructor(e,t){this.center=[0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.RectangleDto=class{constructor(e,t,i){this.center=[0,0],this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i)}},e.RoundedRectangleDto=class{constructor(e,t,i,s,r){this.center=[0,0],this.roundRadius=.2,this.segments=24,this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.segments=i),void 0!==s&&(this.width=s),void 0!==r&&(this.length=r)}},e.StarDto=class{constructor(e,t,i,s,r,n){this.center=[0,0],this.vertices=10,this.density=1,this.outerRadius=2,this.innerRadius=1,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.vertices=t),void 0!==i&&(this.density=i),void 0!==s&&(this.outerRadius=s),void 0!==r&&(this.innerRadius=r),void 0!==n&&(this.startAngle=n)}},e.CubeDto=class{constructor(e,t){this.center=[0,0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.CubeCentersDto=class{constructor(e,t){this.size=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.size=t)}},e.CuboidDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.width=1,this.length=1,this.height=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.height=s)}},e.CuboidCentersDto=class{constructor(e,t,i,s){this.width=1,this.length=1,this.height=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.height=s)}},e.RoundedCuboidDto=class{constructor(e,t,i,s,r,n){this.center=[0,0,0],this.roundRadius=1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==s&&(this.length=s),void 0!==r&&(this.height=r),void 0!==n&&(this.segments=n)}},e.RoundedCuboidCentersDto=class{constructor(e,t,i,s,r,n){this.roundRadius=.1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==s&&(this.length=s),void 0!==r&&(this.height=r),void 0!==n&&(this.segments=n)}},e.CylidnerEllipticDto=class{constructor(e,t,i,s,r){this.center=[0,0,0],this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==s&&(this.endRadius=s),void 0!==r&&(this.segments=r)}},e.CylidnerCentersEllipticDto=class{constructor(e,t,i,s,r){this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==s&&(this.endRadius=s),void 0!==r&&(this.segments=r)}},e.CylidnerDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.segments=s)}},e.RoundedCylidnerDto=class{constructor(e,t,i,s,r){this.center=[0,0,0],this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==s&&(this.radius=s),void 0!==r&&(this.segments=r)}},e.EllipsoidDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipsoidCentersDto=class{constructor(e,t,i){this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.GeodesicSphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.frequency=12,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.GeodesicSphereCentersDto=class{constructor(e,t,i){this.radius=1,this.frequency=12,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.CylidnerCentersDto=class{constructor(e,t,i,s){this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.segments=s)}},e.RoundedCylidnerCentersDto=class{constructor(e,t,i,s,r){this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==s&&(this.radius=s),void 0!==r&&(this.segments=r)}},e.SphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SphereCentersDto=class{constructor(e,t,i){this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.TorusDto=class{constructor(e,t,i,s,r,n,o,a){this.center=[0,0,0],this.innerRadius=1,this.outerRadius=2,this.innerSegments=24,this.outerSegments=24,this.innerRotation=0,this.outerRotation=360,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.outerRadius=i),void 0!==s&&(this.innerSegments=s),void 0!==r&&(this.outerSegments=r),void 0!==n&&(this.innerRotation=n),void 0!==o&&(this.outerRotation=o),void 0!==a&&(this.startAngle=a)}},e.TextDto=class{constructor(e,t,s,r,n,o,a,l,h){this.text="Hello World",this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.segments=t),void 0!==s&&(this.xOffset=s),void 0!==r&&(this.yOffset=r),void 0!==n&&(this.height=n),void 0!==o&&(this.lineSpacing=o),void 0!==a&&(this.letterSpacing=a),void 0!==l&&(this.align=l),void 0!==h&&(this.extrudeOffset=h)}},e.CylinderTextDto=class{constructor(e,t,s,r,n,o,a,l,h,c,u){this.text="Hello World",this.extrusionHeight=.5,this.extrusionSize=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.extrusionHeight=t),void 0!==s&&(this.extrusionSize=s),void 0!==r&&(this.segments=r),void 0!==n&&(this.xOffset=n),void 0!==o&&(this.yOffset=o),void 0!==a&&(this.height=a),void 0!==l&&(this.lineSpacing=l),void 0!==h&&(this.letterSpacing=h),void 0!==c&&(this.align=c),void 0!==u&&(this.extrudeOffset=u)}},e.SphereTextDto=class{constructor(e,t,s,r,n,o,a,l,h,c){this.text="Hello World",this.radius=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.radius=t),void 0!==s&&(this.segments=s),void 0!==r&&(this.xOffset=r),void 0!==n&&(this.yOffset=n),void 0!==o&&(this.height=o),void 0!==a&&(this.lineSpacing=a),void 0!==l&&(this.letterSpacing=l),void 0!==h&&(this.align=h),void 0!==c&&(this.extrudeOffset=c)}},e.FromPolygonPoints=class{constructor(e){void 0!==e&&(this.polygonPoints=e)}}}(gU||(gU={})),function(e){e.StringifyDto=class{constructor(e){void 0!==e&&(this.json=e)}},e.ParseDto=class{constructor(e){void 0!==e&&(this.text=e)}},e.QueryDto=class{constructor(e,t){void 0!==e&&(this.json=e),void 0!==t&&(this.query=t)}},e.SetValueDto=class{constructor(e,t,i){void 0!==e&&(this.json=e),void 0!==t&&(this.value=t),void 0!==i&&(this.path=i)}},e.SetValuesOnPathsDto=class{constructor(e,t,i){void 0!==e&&(this.json=e),void 0!==t&&(this.values=t),void 0!==i&&(this.paths=i)}},e.PathsDto=class{constructor(e,t){void 0!==e&&(this.json=e),void 0!==t&&(this.query=t)}},e.JsonDto=class{constructor(e){void 0!==e&&(this.json=e)}}}(vU||(vU={})),function(e){e.LinePointsDto=class{constructor(e,t){void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LineStartEndPointsDto=class{constructor(e,t){void 0!==e&&(this.startPoints=e),void 0!==t&&(this.endPoints=t)}},e.DrawLineDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.line=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.lineMesh=n)}},e.DrawLinesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.linesMesh=n)}},e.PointsLinesDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.LineDto=class{constructor(e){void 0!==e&&(this.line=e)}},e.LinesDto=class{constructor(e){void 0!==e&&(this.lines=e)}},e.PointOnLineDto=class{constructor(e,t){void 0!==e&&(this.line=e),void 0!==t&&(this.param=t)}},e.TransformLineDto=class{constructor(e,t){void 0!==e&&(this.line=e),void 0!==t&&(this.transformation=t)}},e.TransformsLinesDto=class{constructor(e,t){void 0!==e&&(this.lines=e),void 0!==t&&(this.transformation=t)}},e.TransformLinesDto=class{constructor(e,t){void 0!==e&&(this.lines=e),void 0!==t&&(this.transformation=t)}}}(xU||(xU={})),function(e){let t;!function(e){e.first="first",e.last="last"}(t=e.firstLastEnum||(e.firstLastEnum={})),e.ListItemDto=class{constructor(e,t,i){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.index=t),void 0!==i&&(this.clone=i)}},e.SubListDto=class{constructor(e,t,i,s){this.indexStart=0,this.indexEnd=1,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.indexStart=t),void 0!==i&&(this.indexEnd=i),void 0!==s&&(this.clone=s)}},e.ListDto=class{constructor(e,t){this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.clone=t)}},e.GroupListDto=class{constructor(e,t,i){this.nrElements=2,this.keepRemainder=!1,void 0!==e&&(this.list=e),void 0!==t&&(this.nrElements=t),void 0!==i&&(this.keepRemainder=i)}},e.MultiplyItemDto=class{constructor(e,t){void 0!==e&&(this.item=e),void 0!==t&&(this.times=t)}},e.AddItemAtIndexDto=class{constructor(e,t,i,s){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.item=t),void 0!==i&&(this.index=i),void 0!==s&&(this.clone=s)}},e.AddItemAtIndexesDto=class{constructor(e,t,i,s){this.indexes=[0],this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.item=t),void 0!==i&&(this.indexes=i),void 0!==s&&(this.clone=s)}},e.AddItemsAtIndexesDto=class{constructor(e,t,i,s){this.indexes=[0],this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.items=t),void 0!==i&&(this.indexes=i),void 0!==s&&(this.clone=s)}},e.RemoveItemAtIndexDto=class{constructor(e,t,i){this.index=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.index=t),void 0!==i&&(this.clone=i)}},e.RemoveNthItemDto=class{constructor(e,t,i,s){this.nth=2,this.offset=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.nth=t),void 0!==i&&(this.offset=i),void 0!==s&&(this.clone=s)}},e.GetByPatternDto=class{constructor(e,t){this.pattern=[!0,!0,!1],void 0!==e&&(this.list=e),void 0!==t&&(this.pattern=t)}},e.GetNthItemDto=class{constructor(e,t,i,s){this.nth=2,this.offset=0,this.clone=!0,void 0!==e&&(this.list=e),void 0!==t&&(this.nth=t),void 0!==i&&(this.offset=i),void 0!==s&&(this.clone=s)}},e.GetLongestListLength=class{constructor(e){void 0!==e&&(this.lists=e)}},e.MergeElementsOfLists=class{constructor(e,t){this.level=0,void 0!==e&&(this.lists=e),void 0!==t&&(this.level=t)}},e.AddItemFirstLastDto=class{constructor(e,i,s,r){this.position=t.last,this.clone=!0,void 0!==e&&(this.list=e),void 0!==i&&(this.item=i),void 0!==s&&(this.position=s),void 0!==r&&(this.clone=r)}}}(bU||(bU={})),function(e){let t;!function(e){e.less="<",e.lessOrEqual="<=",e.greater=">",e.greaterOrEqual=">=",e.tripleEqual="===",e.tripleNotEqual="!==",e.equal="==",e.notEqual="!="}(t=e.BooleanOperatorsEnum||(e.BooleanOperatorsEnum={})),e.ComparisonDto=class{constructor(e,t,i){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t),void 0!==i&&(this.operator=i)}},e.BooleanDto=class{constructor(e){this.boolean=!1,void 0!==e&&(this.boolean=e)}},e.BooleanListDto=class{constructor(e){void 0!==e&&(this.booleans=e)}},e.ValueGateDto=class{constructor(e,t){this.boolean=!1,void 0!==e&&(this.value=e),void 0!==t&&(this.boolean=t)}},e.TwoValueGateDto=class{constructor(e,t){void 0!==e&&(this.value1=e),void 0!==t&&(this.value2=t)}},e.RandomBooleansDto=class{constructor(e){this.length=10,void 0!==e&&(this.length=e)}},e.TwoThresholdRandomGradientDto=class{},e.ThresholdBooleanListDto=class{},e.ThresholdGapsBooleanListDto=class{}}(TU||(TU={})),function(e){let t,i;!function(e){e.add="add",e.subtract="subtract",e.multiply="multiply",e.divide="divide",e.power="power",e.modulus="modulus"}(t=e.mathTwoNrOperatorEnum||(e.mathTwoNrOperatorEnum={})),function(e){e.absolute="absolute",e.negate="negate",e.ln="ln",e.log10="log10",e.tenPow="tenPow",e.round="round",e.floor="floor",e.ceil="ceil",e.sqrt="sqrt",e.sin="sin",e.cos="cos",e.tan="tan",e.asin="asin",e.acos="acos",e.atan="atan",e.log="log",e.exp="exp",e.radToDeg="radToDeg",e.degToRad="degToRad"}(i=e.mathOneNrOperatorEnum||(e.mathOneNrOperatorEnum={})),e.NumberDto=class{constructor(e){this.number=0,void 0!==e&&(this.number=e)}},e.ModulusDto=class{constructor(e,t){this.number=1,this.modulus=2,void 0!==e&&(this.number=e),void 0!==t&&(this.modulus=t)}},e.RoundToDecimalsDto=class{constructor(e,t){this.number=1.123456,this.decimalPlaces=2,void 0!==e&&(this.number=e),void 0!==t&&(this.decimalPlaces=t)}},e.ActionOnTwoNumbersDto=class{constructor(e,t,i){this.first=1,this.second=1,void 0!==e&&(this.first=e),void 0!==t&&(this.second=t),void 0!==i&&(this.operation=i)}},e.ActionOnOneNumberDto=class{constructor(e,t){this.number=1,void 0!==e&&(this.number=e),void 0!==t&&(this.operation=t)}},e.RemapNumberDto=class{constructor(e,t,i,s,r){this.number=.5,this.fromLow=0,this.fromHigh=1,this.toLow=1,this.toHigh=2,void 0!==e&&(this.number=e),void 0!==t&&(this.fromLow=t),void 0!==i&&(this.fromHigh=i),void 0!==s&&(this.toLow=s),void 0!==r&&(this.toHigh=r)}},e.RandomNumberDto=class{constructor(e,t){this.low=0,this.high=1,void 0!==e&&(this.low=e),void 0!==t&&(this.high=t)}},e.RandomNumbersDto=class{constructor(e,t,i){this.low=0,this.high=1,this.count=10,void 0!==e&&(this.low=e),void 0!==t&&(this.high=t),void 0!==i&&(this.count=i)}}}(yU||(yU={})),function(e){e.NodeDto=class{constructor(e){void 0!==e&&(this.node=e)}},e.NodeTranslationDto=class{constructor(e,t,i){void 0!==e&&(this.node=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.distance=i)}},e.NodeParentDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.parentNode=t)}},e.NodeDirectionDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.direction=t)}},e.NodePositionDto=class{constructor(e,t){void 0!==e&&(this.node=e),void 0!==t&&(this.position=t)}},e.RotateNodeDto=class{constructor(e,t,i){this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.node=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.angle=i)}},e.RotateAroundAxisNodeDto=class{constructor(e,t,i,s){this.position=[0,0,0],this.axis=[0,1,0],this.angle=0,void 0!==e&&(this.node=e),void 0!==t&&(this.position=t),void 0!==i&&(this.axis=i),void 0!==s&&(this.angle=s)}},e.CreateNodeFromRotationDto=class{constructor(e,t,i){this.origin=[0,0,0],this.rotation=[0,0,0],void 0!==e&&(this.parent=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.rotation=i)}},e.DrawNodeDto=class{constructor(e,t,i,s,r){this.colorX="#ff0000",this.colorY="#00ff00",this.colorZ="#0000ff",this.size=2,void 0!==e&&(this.node=e),void 0!==t&&(this.colorX=t),void 0!==i&&(this.colorY=i),void 0!==s&&(this.colorZ=s),void 0!==r&&(this.size=r)}},e.DrawNodesDto=class{constructor(e,t,i,s,r){this.colorX="#ff0000",this.colorY="#00ff00",this.colorZ="#0000ff",this.size=2,void 0!==e&&(this.nodes=e),void 0!==t&&(this.colorX=t),void 0!==i&&(this.colorY=i),void 0!==s&&(this.colorZ=s),void 0!==r&&(this.size=r)}}}(SU||(SU={})),function(e){e.PointDto=class{constructor(e){void 0!==e&&(this.point=e)}},e.PointXYZDto=class{constructor(e,t,i){this.x=0,this.y=0,this.z=0,void 0!==e&&(this.x=e),void 0!==t&&(this.y=t),void 0!==i&&(this.z=i)}},e.PointXYDto=class{constructor(e,t){this.x=0,this.y=0,void 0!==e&&(this.x=e),void 0!==t&&(this.y=t)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.DrawPointDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.size=3,this.colours="#444444",this.updatable=!1,void 0!==e&&(this.point=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.size=i),void 0!==s&&(this.colours=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.pointMesh=n)}},e.DrawPointsDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.size=.1,this.colours="#444444",this.updatable=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.size=i),void 0!==s&&(this.colours=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.pointsMesh=n)}},e.TransformPointDto=class{constructor(e,t){void 0!==e&&(this.point=e),void 0!==t&&(this.transformation=t)}},e.TransformPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.transformation=t)}},e.TransformsForPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.transformation=t)}},e.ClosestPointFromPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.point=t)}},e.StartEndPointsDto=class{constructor(e,t){void 0!==e&&(this.startPoint=e),void 0!==t&&(this.endPoint=t)}},e.StartEndPointsListDto=class{constructor(e,t){void 0!==e&&(this.startPoint=e),void 0!==t&&(this.endPoints=t)}},e.MultiplyPointDto=class{constructor(e,t){void 0!==e&&(this.point=e),void 0!==t&&(this.amountOfPoints=t)}},e.SpiralDto=class{constructor(e,t,i,s,r){this.phi=.9,this.numberPoints=200,this.widening=3,this.radius=6,this.factor=1,void 0!==e&&(this.radius=e),void 0!==t&&(this.numberPoints=t),void 0!==i&&(this.widening=i),void 0!==s&&(this.factor=s),void 0!==r&&(this.phi=r)}},e.HexGridCentersDto=class{constructor(e,t,i,s,r){this.nrHexagonsY=21,this.nrHexagonsX=21,this.orientOnCenter=!1,this.pointsOnGround=!1,void 0!==e&&(this.nrHexagonsX=e),void 0!==t&&(this.nrHexagonsY=t),void 0!==i&&(this.radiusHexagon=i),void 0!==s&&(this.orientOnCenter=s),void 0!==r&&(this.pointsOnGround=r)}}}(CU||(CU={})),function(e){e.PolylinePropertiesDto=class{constructor(e,t){this.isClosed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.isClosed=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.polyline=e)}},e.PolylinesDto=class{constructor(e){void 0!==e&&(this.polylines=e)}},e.TransformPolylineDto=class{constructor(e,t){void 0!==e&&(this.polyline=e),void 0!==t&&(this.transformation=t)}},e.DrawPolylineDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.polyline=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.polylineMesh=n)}},e.DrawPolylinesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.polylinesMesh=n)}}}(EU||(EU={})),function(e){let t,i;!function(e){e.default="default",e.clearSky="clearSky",e.city="city"}(t=e.skyboxEnum||(e.skyboxEnum={})),function(e){e.none="none",e.exponential="exponential",e.exponentialSquared="exponentialSquared",e.linear="linear"}(i=e.fogModeEnum||(e.fogModeEnum={}))}(AU||(AU={})),function(e){e.SceneBackgroundColourDto=class{constructor(e){this.colour="#ffffff",void 0!==e&&(this.colour=e)}},e.SceneDto=class{constructor(e){void 0!==e&&(this.scene=e)}},e.EnablePhysicsDto=class{constructor(e){this.vector=[0,-9.81,0],void 0!==e&&(this.vector=e)}},e.PointLightDto=class{constructor(e,t,i,s,r,n,o,a){this.position=[0,0,0],this.intensity=2e3,this.diffuse="#ffffff",this.specular="#ffffff",this.radius=.1,this.shadowGeneratorMapSize=1024,this.enableShadows=!0,this.shadowDarkness=0,void 0!==e&&(this.position=e),void 0!==t&&(this.intensity=t),void 0!==i&&(this.diffuse=i),void 0!==s&&(this.specular=s),void 0!==r&&(this.radius=r),void 0!==n&&(this.shadowGeneratorMapSize=n),void 0!==o&&(this.enableShadows=o),void 0!==a&&(this.shadowDarkness=a)}},e.ActiveCameraDto=class{constructor(e){void 0!==e&&(this.camera=e)}},e.UseRightHandedSystemDto=class{constructor(e){this.use=!0,void 0!==e&&(this.use=e)}},e.DirectionalLightDto=class{constructor(e,t,i,s,r,n,o){this.direction=[-100,-100,-100],this.intensity=.5,this.diffuse="#ffffff",this.specular="#ffffff",this.shadowGeneratorMapSize=1024,this.enableShadows=!0,this.shadowDarkness=0,void 0!==e&&(this.direction=e),void 0!==t&&(this.intensity=t),void 0!==i&&(this.diffuse=i),void 0!==s&&(this.specular=s),void 0!==r&&(this.shadowGeneratorMapSize=r),void 0!==n&&(this.enableShadows=n),void 0!==o&&(this.shadowDarkness=o)}},e.CameraConfigurationDto=class{constructor(e,t,i,s,r,n,o,a,l){this.position=[10,10,10],this.lookAt=[0,0,0],this.lowerBetaLimit=1,this.upperBetaLimit=179,this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.maxZ=1e3,this.panningSensibility=1e3,this.wheelPrecision=3,void 0!==e&&(this.position=e),void 0!==t&&(this.lookAt=t),void 0!==i&&(this.lowerBetaLimit=i),void 0!==s&&(this.upperBetaLimit=s),void 0!==r&&(this.angularSensibilityX=r),void 0!==n&&(this.angularSensibilityY=n),void 0!==o&&(this.maxZ=o),void 0!==a&&(this.panningSensibility=a),void 0!==l&&(this.wheelPrecision=l)}},e.SkyboxDto=class{constructor(e,t,i,s){this.skybox=AU.skyboxEnum.clearSky,this.size=1e3,this.blur=.1,this.environmentIntensity=.7,void 0!==e&&(this.skybox=e),void 0!==t&&(this.size=t),void 0!==i&&(this.blur=i),void 0!==s&&(this.environmentIntensity=s)}},e.PointerDto=class{},e.FogDto=class{constructor(e,t,i,s,r){this.color="#ffffff",this.density=.1,void 0!==e&&(this.mode=e),void 0!==t&&(this.color=t),void 0!==i&&(this.density=i),void 0!==s&&(this.start=s),void 0!==r&&(this.end=r)}}}(PU||(PU={})),function(e){e.DrawTagDto=class{constructor(e,t,i){this.updatable=!1,void 0!==e&&(this.tag=e),void 0!==t&&(this.updatable=t),void 0!==i&&(this.tagVariable=i)}},e.DrawTagsDto=class{constructor(e,t,i){this.updatable=!1,void 0!==e&&(this.tags=e),void 0!==t&&(this.updatable=t),void 0!==i&&(this.tagsVariable=i)}},e.TagDto=class{constructor(e,t,i,s,r,n,o){this.position=[0,0,0],this.colour="#444444",this.size=12,this.adaptDepth=!1,void 0!==e&&(this.text=e),void 0!==t&&(this.position=t),void 0!==i&&(this.colour=i),void 0!==s&&(this.size=s),void 0!==r&&(this.adaptDepth=r),void 0!==n&&(this.needsUpdate=n),void 0!==o&&(this.id=o)}}}(IU||(IU={})),function(e){e.TextDto=class{constructor(e){this.text="Hello World",void 0!==e&&(this.text=e)}},e.TextSplitDto=class{constructor(e,t){this.text="a,b,c",this.separator=",",void 0!==e&&(this.text=e),void 0!==t&&(this.separator=t)}},e.TextReplaceDto=class{constructor(e,t,i){this.text="a-c",this.search="-",this.replaceWith="b",void 0!==e&&(this.text=e),void 0!==t&&(this.search=t),void 0!==i&&(this.replaceWith=i)}},e.TextJoinDto=class{constructor(e,t){this.separator=",",void 0!==e&&(this.list=e),void 0!==t&&(this.separator=t)}},e.ToStringDto=class{constructor(e){void 0!==e&&(this.item=e)}},e.ToStringEachDto=class{constructor(e){void 0!==e&&(this.list=e)}}}(RU||(RU={})),function(e){e.PostFromIframe=class{constructor(e,t){void 0!==e&&(this.data=e),void 0!==t&&(this.targetOrigin=t)}}}(MU||(MU={})),function(e){e.RotationCenterAxisDto=class{constructor(e,t,i){this.angle=90,this.axis=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.center=i)}},e.TransformBabylonMeshDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.transformation=t)}},e.RotationCenterDto=class{constructor(e,t){this.angle=90,this.center=[0,0,0],void 0!==e&&(this.angle=e),void 0!==t&&(this.center=t)}},e.RotationCenterYawPitchRollDto=class{constructor(e,t,i,s){this.yaw=0,this.pitch=0,this.roll=0,this.center=[0,0,0],void 0!==e&&(this.yaw=e),void 0!==t&&(this.pitch=t),void 0!==i&&(this.roll=i),void 0!==s&&(this.center=s)}},e.ScaleXYZDto=class{constructor(e){this.scaleXyz=[1,1,1],void 0!==e&&(this.scaleXyz=e)}},e.ScaleCenterXYZDto=class{constructor(e,t){this.center=[0,0,0],this.scaleXyz=[1,1,1],void 0!==e&&(this.center=e),void 0!==t&&(this.scaleXyz=t)}},e.UniformScaleDto=class{constructor(e){this.scale=1,void 0!==e&&(this.scale=e)}},e.UniformScaleFromCenterDto=class{constructor(e,t){this.scale=1,this.center=[0,0,0],void 0!==e&&(this.scale=e),void 0!==t&&(this.center=t)}},e.TranslationXYZDto=class{constructor(e){this.translation=[0,0,0],void 0!==e&&(this.translation=e)}},e.TranslationsXYZDto=class{constructor(e){void 0!==e&&(this.translations=e)}}}(OU||(OU={})),function(e){e.TwoVectorsDto=class{constructor(e,t){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.VectorBoolDto=class{constructor(e){void 0!==e&&(this.vector=e)}},e.VectorDto=class{constructor(e){void 0!==e&&(this.vector=e)}},e.RangeMaxDto=class{constructor(e){void 0!==e&&(this.max=e)}},e.VectorXYZDto=class{constructor(e,t,i){void 0!==e&&(this.x=e),void 0!==t&&(this.y=t),void 0!==i&&(this.z=i)}},e.VectorXYDto=class{constructor(e,t){void 0!==e&&(this.x=e),void 0!==t&&(this.y=t)}},e.SpanDto=class{constructor(e,t,i){this.step=.1,this.min=0,this.max=1,void 0!==e&&(this.step=e),void 0!==t&&(this.min=t),void 0!==i&&(this.max=i)}},e.RayPointDto=class{constructor(e,t,i){void 0!==e&&(this.point=e),void 0!==t&&(this.distance=t),void 0!==i&&(this.vector=i)}},e.VectorsDto=class{constructor(e){void 0!==e&&(this.vectors=e)}},e.FractionTwoVectorsDto=class{constructor(e,t,i){this.fraction=.5,void 0!==e&&(this.fraction=e),void 0!==t&&(this.first=t),void 0!==i&&(this.second=i)}},e.VectorScalarDto=class{constructor(e,t){void 0!==e&&(this.scalar=e),void 0!==t&&(this.vector=t)}},e.TwoVectorsReferenceDto=class{constructor(e,t,i){void 0!==e&&(this.reference=e),void 0!==t&&(this.first=t),void 0!==i&&(this.second=i)}}}(DU||(DU={})),function(e){e.CurveDto=class{constructor(e){void 0!==e&&(this.curve=e)}},e.CurvesDto=class{constructor(e){void 0!==e&&(this.curves=e)}},e.ClosestPointDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.point=t)}},e.ClosestPointsDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.points=t)}},e.BezierCurveDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.weights=t)}},e.DrawCurveDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.curve=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.curveMesh=n)}},e.CurveParameterDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.parameter=t)}},e.CurvesParameterDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.parameter=t)}},e.CurveTransformDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.transformation=t)}},e.CurvesTransformDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.transformation=t)}},e.CurveToleranceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.tolerance=t)}},e.CurveLengthToleranceDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.length=t),void 0!==i&&(this.tolerance=i)}},e.CurveDerivativesDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.parameter=t),void 0!==i&&(this.numDerivatives=i)}},e.CurveSubdivisionsDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.subdivision=t)}},e.CurvesSubdivisionsDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.subdivision=t)}},e.CurvesDivideLengthDto=class{constructor(e,t){void 0!==e&&(this.curves=e),void 0!==t&&(this.length=t)}},e.CurveDivideLengthDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.length=t)}},e.DrawCurvesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.size=3,this.updatable=!1,void 0!==e&&(this.curves=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.size=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.curvesMesh=n)}},e.CurveNurbsDataDto=class{constructor(e,t,i,s){void 0!==e&&(this.degree=e),void 0!==t&&(this.weights=t),void 0!==i&&(this.knots=i),void 0!==s&&(this.points=s)}},e.CurvePathDataDto=class{constructor(e,t){void 0!==e&&(this.degree=e),void 0!==t&&(this.points=t)}},e.EllipseDto=class{constructor(e){void 0!==e&&(this.ellipse=e)}},e.CircleDto=class{constructor(e){void 0!==e&&(this.circle=e)}},e.ArcDto=class{constructor(e){void 0!==e&&(this.arc=e)}},e.EllipseParametersDto=class{constructor(e,t,i){void 0!==e&&(this.xAxis=e),void 0!==t&&(this.yAxis=t),void 0!==i&&(this.center=i)}},e.CircleParametersDto=class{constructor(e,t,i,s){void 0!==e&&(this.xAxis=e),void 0!==t&&(this.yAxis=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.center=s)}},e.ArcParametersDto=class{constructor(e,t,i,s,r,n){void 0!==e&&(this.minAngle=e),void 0!==t&&(this.maxAngle=t),void 0!==i&&(this.xAxis=i),void 0!==s&&(this.yAxis=s),void 0!==r&&(this.radius=r),void 0!==n&&(this.center=n)}},e.EllipseArcParametersDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.minAngle=e),void 0!==t&&(this.maxAngle=t),void 0!==i&&(this.xAxis=i),void 0!==s&&(this.yAxis=s),void 0!==r&&(this.center=r)}},e.SurfaceDto=class{constructor(e){void 0!==e&&(this.surface=e)}},e.SurfaceTransformDto=class{constructor(e,t){void 0!==e&&(this.surface=e),void 0!==t&&(this.transformation=t)}},e.SurfaceParameterDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.parameter=t),void 0!==i&&(this.useV=i)}},e.IsocurvesParametersDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.parameters=t),void 0!==i&&(this.useV=i)}},e.IsocurveSubdivisionDto=class{constructor(e,t,i,s,r){this.useV=!1,this.includeLast=!0,this.includeFirst=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.useV=t),void 0!==i&&(this.includeLast=i),void 0!==s&&(this.includeFirst=s),void 0!==r&&(this.isocurveSegments=r)}},e.DerivativesDto=class{constructor(e,t,i,s){void 0!==e&&(this.surface=e),void 0!==t&&(this.u=t),void 0!==i&&(this.v=i),void 0!==s&&(this.numDerivatives=s)}},e.SurfaceLocationDto=class{constructor(e,t,i){void 0!==e&&(this.surface=e),void 0!==t&&(this.u=t),void 0!==i&&(this.v=i)}},e.CornersDto=class{constructor(e,t,i,s){void 0!==e&&(this.point1=e),void 0!==t&&(this.point2=t),void 0!==i&&(this.point3=i),void 0!==s&&(this.point4=s)}},e.SurfaceParamDto=class{constructor(e,t){void 0!==e&&(this.surface=e),void 0!==t&&(this.point=t)}},e.KnotsControlPointsWeightsDto=class{constructor(e,t,i,s,r,n){void 0!==e&&(this.degreeU=e),void 0!==t&&(this.degreeV=t),void 0!==i&&(this.knotsU=i),void 0!==s&&(this.knotsV=s),void 0!==r&&(this.points=r),void 0!==n&&(this.weights=n)}},e.LoftCurvesDto=class{constructor(e,t){void 0!==e&&(this.degreeV=e),void 0!==t&&(this.curves=t)}},e.DrawSurfaceDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surface=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.surfaceMesh=n)}},e.DrawSurfacesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surfaces=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.surfacesMesh=n)}},e.DrawSurfacesColoursDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.updatable=!1,this.hidden=!1,void 0!==e&&(this.surfaces=e),void 0!==t&&(this.colours=t),void 0!==i&&(this.opacity=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.surfacesMesh=n)}},e.ConeAndCylinderParametersDto=class{constructor(e,t,i,s,r){this.axis=[0,1,0],this.xAxis=[1,0,0],this.base=[0,0,0],this.height=2,this.radius=1,void 0!==e&&(this.axis=e),void 0!==t&&(this.xAxis=t),void 0!==i&&(this.base=i),void 0!==s&&(this.height=s),void 0!==r&&(this.radius=r)}},e.ConeDto=class{constructor(e){void 0!==e&&(this.cone=e)}},e.CylinderDto=class{constructor(e){void 0!==e&&(this.cylinder=e)}},e.ExtrusionParametersDto=class{constructor(e,t){void 0!==e&&(this.profile=e),void 0!==t&&(this.direction=t)}},e.ExtrusionDto=class{constructor(e){void 0!==e&&(this.extrusion=e)}},e.SphericalParametersDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.SphereDto=class{constructor(e){void 0!==e&&(this.sphere=e)}},e.RevolutionParametersDto=class{constructor(e,t,i,s){void 0!==e&&(this.profile=e),void 0!==t&&(this.center=t),void 0!==i&&(this.axis=i),void 0!==s&&(this.angle=s)}},e.RevolutionDto=class{constructor(e){void 0!==e&&(this.revolution=e)}},e.SweepParametersDto=class{constructor(e,t){void 0!==e&&(this.profile=e),void 0!==t&&(this.rail=t)}},e.SweepDto=class{constructor(e){void 0!==e&&(this.sweep=e)}},e.CurveCurveDto=class{constructor(e,t,i){void 0!==e&&(this.firstCurve=e),void 0!==t&&(this.secondCurve=t),void 0!==i&&(this.tolerance=i)}},e.CurveSurfaceDto=class{constructor(e,t,i){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t),void 0!==i&&(this.tolerance=i)}},e.SurfaceSurfaceDto=class{constructor(e,t,i){void 0!==e&&(this.firstSurface=e),void 0!==t&&(this.secondSurface=t),void 0!==i&&(this.tolerance=i)}},e.CurveCurveIntersectionsDto=class{constructor(e){void 0!==e&&(this.intersections=e)}},e.CurveSurfaceIntersectionsDto=class{constructor(e){void 0!==e&&(this.intersections=e)}}}(wU||(wU={}));class LU{constructor(e){this.context=e}dispose(e){e.babylonMesh&&(e.babylonMesh.getScene().removeMesh(e.babylonMesh,!0),e.babylonMesh.dispose())}updateDrawn(e){const t=e.babylonMesh.metadata.type;e.babylonMesh.position=new _e(e.position[0],e.position[1],e.position[2]),e.babylonMesh.rotation=new _e(e.rotation[0],e.rotation[1],e.rotation[2]),e.babylonMesh.scaling=new _e(e.scaling[0],e.scaling[1],e.scaling[2]);const i=Array.isArray(e.colours);let s;if(e.babylonMesh.getChildMeshes&&(s=e.babylonMesh.getChildMeshes()),s&&s.length>0)i&&e.colours.length===s.length?s.forEach(((t,i)=>{const s=Ee.FromHexString(e.colours[i]);this.assignColorToMesh(t,s)})):i?s.forEach((t=>{const i=Ee.FromHexString(e.colours[0]);this.assignColorToMesh(t,i)})):s.forEach((t=>{const i=Ee.FromHexString(e.colours);this.assignColorToMesh(t,i)}));else{const t=i?Ee.FromHexString(e.colours[0]):Ee.FromHexString(e.colours);this.assignColorToMesh(e.babylonMesh,t)}if(null!==e.babylonMesh.edgesRenderer){const t=i?Ee.FromHexString(e.colours[0]):Ee.FromHexString(e.colours);e.babylonMesh.edgesColor=Ae.FromColor3(t)}if([mU.drawingTypes.point,mU.drawingTypes.points,mU.drawingTypes.line,mU.drawingTypes.lines,mU.drawingTypes.polyline,mU.drawingTypes.polylines].includes(t)){const t=e.babylonMesh.getVerticesData(er.ColorKind).length/4,s=[];if(i&&t===e.colours.length)for(let i=0;i{t.visibility=e.visibility}))}hide(e){e.babylonMesh.isVisible=!1,e.includeChildren&&e.babylonMesh.getChildMeshes&&e.babylonMesh.getChildMeshes().forEach((e=>{e.isVisible=!1}))}show(e){e.babylonMesh.isVisible=!0,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((e=>{e.isVisible=!0}))}setParent(e){e.babylonMesh.parent=e.parentMesh}getParent(e){return e.babylonMesh.parent}setCheckCollisions(e){e.babylonMesh.checkCollisions=e.checkCollisions,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.checkCollisions=e.checkCollisions}))}getCheckCollisions(e){return e.babylonMesh.checkCollisions}setPickable(e){e.babylonMesh.isPickable=e.pickable,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.isPickable=e.pickable}))}getPickable(e){return e.babylonMesh.isPickable}getMeshesWhereNameContains(e){return this.context.scene.meshes.filter((t=>t.name.includes(e.name)))}getChildMeshes(e){return e.babylonMesh.getChildMeshes(e.directDescendantsOnly)}getMeshesOfId(e){return this.context.scene.getMeshesById(e.id)}getMeshOfId(e){return this.context.scene.getMeshById(e.id)}getMeshOfUniqueId(e){return this.context.scene.getMeshByUniqueId(e.uniqueId)}clone(e){var t,i;const s=e.babylonMesh.clone(),r=null===(i=null===(t=this.context.scene)||void 0===t?void 0:t.metadata)||void 0===i?void 0:i.shadowGenerators;return r.length>0&&(s.getChildMeshes().forEach((e=>{e.receiveShadows=!0,r.forEach((t=>t.addShadowCaster(e)))})),s.receiveShadows=!0,r.forEach((e=>e.addShadowCaster(s)))),s}setId(e){e.babylonMesh.id=e.id}getId(e){return e.babylonMesh.id}getUniqueId(e){return e.babylonMesh.uniqueId}setName(e){e.babylonMesh.name=e.name,e.includeChildren&&e.babylonMesh.getChildMeshes().forEach((t=>{t.name=e.name}))}getVerticesAsPolygonPoints(e){const t=e.babylonMesh.getVerticesData(er.PositionKind),i=e.babylonMesh.getIndices(),s=[];for(let e=0;e{t.material=e.material}))}getMaterial(e){return e.babylonMesh.material}getPosition(e){const t=e.babylonMesh;return[t.position.x,t.position.y,t.position.z]}getAbsolutePosition(e){const t=e.babylonMesh;return[t.absolutePosition.x,t.absolutePosition.y,t.absolutePosition.z]}getRotation(e){const t=e.babylonMesh;return[t.rotation.x,t.rotation.y,t.rotation.z]}getScale(e){const t=e.babylonMesh;return[t.scaling.x,t.scaling.y,t.scaling.z]}moveForward(e){const t=e.babylonMesh;t.translate(t.forward,e.distance,1)}moveBackward(e){const t=e.babylonMesh;t.translate(t.forward.negate(),e.distance,1)}moveUp(e){const t=e.babylonMesh;t.translate(t.up,e.distance,1)}moveDown(e){const t=e.babylonMesh;t.translate(t.up.negate(),e.distance,1)}moveRight(e){const t=e.babylonMesh;t.translate(t.right,e.distance,1)}moveLeft(e){const t=e.babylonMesh;t.translate(t.right.negate(),e.distance,1)}yaw(e){const t=e.babylonMesh,i=$r.FromDegrees(e.rotate).radians();t.rotate(Xr.Y,i,0)}pitch(e){const t=e.babylonMesh,i=$r.FromDegrees(e.rotate).radians();t.rotate(Xr.X,i,0)}roll(e){const t=e.babylonMesh,i=$r.FromDegrees(e.rotate).radians();t.rotate(Xr.Z,i,0)}rotateAroundAxisWithPosition(e){e.mesh.rotateAround(new _e(e.position[0],e.position[1],e.position[2]),new _e(e.axis[0],e.axis[1],e.axis[2]),$r.FromDegrees(e.angle).radians())}setPosition(e){e.babylonMesh.position=new _e(e.position[0],e.position[1],e.position[2])}setRotation(e){const t=$r.FromDegrees(e.rotation[0]).radians(),i=$r.FromDegrees(e.rotation[1]).radians(),s=$r.FromDegrees(e.rotation[2]).radians();e.babylonMesh.rotation=new _e(t,i,s)}setScale(e){e.babylonMesh.scaling=new _e(e.scale[0],e.scale[1],e.scale[2])}intersectsMesh(e){return e.babylonMesh.intersectsMesh(e.babylonMesh2,e.precise,e.includeDescendants)}intersectsPoint(e){const t=new _e(e.point[0],e.point[1],e.point[2]);return e.babylonMesh.intersectsPoint(t)}createMeshInstanceAndTransformNoReturn(e){this.createMeshInstanceAndTransform(e)}createMeshInstanceAndTransform(e){var t,i;const s=new ha("instanceContainer"+Math.random(),this.context.scene),r=null===(i=null===(t=this.context.scene)||void 0===t?void 0:t.metadata)||void 0===i?void 0:i.shadowGenerators;if(e.mesh&&e.mesh.getChildMeshes&&e.mesh.getChildMeshes().length>0)e.mesh.getChildMeshes(!1).forEach((t=>{const i=t.getTotalVertices();if(t.createInstance&&i>0){t.disableEdgesRendering();const i=t.createInstance(`InstanceMesh${Math.random()}`);i.position=new _e(e.position[0],e.position[1],e.position[2]),i.rotation=new _e(e.rotation[0],e.rotation[1],e.rotation[2]),i.scaling=new _e(e.scaling[0],e.scaling[1],e.scaling[2]),r.length>0&&r.forEach((e=>{e.addShadowCaster(i)})),i.parent=s}})),e.mesh.isVisible=!1;else if(e.mesh){e.mesh.isVisible=!1;const t=e.mesh.createInstance(`InstanceMesh${Math.random()}`);t.position=new _e(e.position[0],e.position[1],e.position[2]),t.rotation=new _e($r.FromDegrees(e.rotation[0]).radians(),$r.FromDegrees(e.rotation[1]).radians(),$r.FromDegrees(e.rotation[2]).radians()),t.scaling=new _e(e.scaling[0],e.scaling[1],e.scaling[2]),t.parent=s,r.length>0&&r.forEach((e=>{e.addShadowCaster(t)}))}return s}createMeshInstance(e){let t;if(e.mesh&&e.mesh.getChildMeshes&&e.mesh.getChildMeshes().length>0){e.mesh.setParent(null);const i=new ha("meshCloneContainer"+Math.random());e.mesh.getChildMeshes(!1).forEach((e=>{e.createInstance&&e.getTotalVertices()>0&&e.getTotalIndices()>0&&(e.createInstance(`InstanceMesh${Math.random()}`).parent=i)})),t=i;const s=this.context.scene.metadata.shadowGenerators;s.length>0&&(t.getChildMeshes().forEach((e=>{s.forEach((t=>t.addShadowCaster(e)))})),s.forEach((e=>e.addShadowCaster(t))))}else if(e.mesh&&(e.mesh.setParent(null),e.mesh.getTotalVertices()>0)){const i=new ha("meshCloneContainer"+Math.random());e.mesh.createInstance(`InstanceMesh${Math.random()}`).parent=i,t=i}return t}getSideOrientation(e){switch(e){case hU.sideOrientationEnum.frontside:return ha.FRONTSIDE;case hU.sideOrientationEnum.backside:return ha.BACKSIDE;case hU.sideOrientationEnum.doubleside:return ha.DOUBLESIDE;default:return ha.FRONTSIDE}}assignColorToMesh(e,t){const i=e.material;i instanceof Lx?i.baseColor=t:i instanceof cu&&(i.diffuseColor=t)}}class BU{constructor(e,t){this.context=e,this.mesh=t}createBox(e){const t=R_.CreateBox("BabylonMesh"+Math.random(),{width:e.width,height:e.height,depth:e.depth,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}createCube(e){const t=R_.CreateBox("BabylonMesh"+Math.random(),{size:e.size,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}createSquarePlane(e){const t=R_.CreatePlane("BabylonMesh"+Math.random(),{size:e.size,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}createRectanglePlane(e){const t=R_.CreatePlane("BabylonMesh"+Math.random(),{width:e.width,height:e.height,sideOrientation:this.mesh.getSideOrientation(e.sideOrientation)},this.context.scene);return this.enableShadows(t),t}enableShadows(e){this.context.scene.metadata.shadowGenerators&&(e.receiveShadows=!0,this.context.scene.metadata.shadowGenerators.forEach((t=>{t.addShadowCaster(e)})))}}class kU{constructor(e,t){this.context=e,this.geometryHelper=t}drawNode(e){this.geometryHelper.localAxes(e.size,this.context.scene,e.colorX,e.colorY,e.colorZ).parent=e.node}drawNodes(e){e.nodes.forEach((t=>{this.geometryHelper.localAxes(e.size,this.context.scene,e.colorX,e.colorY,e.colorZ).parent=t}))}createNodeFromRotation(e){const t=new lo(`node${Math.random()}`,this.context.scene);return e.parent&&(t.parent=e.parent),t.position=new _e(e.origin[0],e.origin[1],e.origin[2]),t.rotation=new _e($r.FromDegrees(e.rotation[0]).radians(),$r.FromDegrees(e.rotation[1]).radians(),$r.FromDegrees(e.rotation[2]).radians()),t}createWorldNode(){const e=new lo(`root${Math.random()}`,this.context.scene);return e.parent=this.context.scene.getTransformNodeByID("root"),e}getAbsoluteForwardVector(e){const t=e.node.forward;return[t.x,t.y,t.z]}getAbsoluteRightVector(e){const t=e.node.right;return[t.x,t.y,t.z]}getAbsoluteUpVector(e){const t=e.node.up;return[t.x,t.y,t.z]}getAbsolutePosition(e){const t=e.node.getAbsolutePosition();return[t.x,t.y,t.z]}getAbsoluteRotationTransformation(e){const t=new me;return e.node.absoluteRotationQuaternion.toRotationMatrix(t),[...t.toArray()]}getRotationTransformation(e){const t=new me;return e.node.rotationQuaternion.toRotationMatrix(t),[...t.toArray()]}getChildren(e){return e.node.getChildren()}getParent(e){return e.node.parent}getPositionExpressedInLocalSpace(e){const t=e.node.getPositionExpressedInLocalSpace();return[t.x,t.y,t.z]}getRootNode(){return this.context.scene.getTransformNodeByID("root")}getRotation(e){const t=e.node.rotation;return[$r.FromRadians(t.x).degrees(),$r.FromRadians(t.y).degrees(),$r.FromRadians(t.z).degrees()]}rotateAroundAxisWithPosition(e){e.node.rotateAround(new _e(e.position[0],e.position[1],e.position[2]),new _e(e.axis[0],e.axis[1],e.axis[2]),$r.FromDegrees(e.angle).radians())}rotate(e){e.node.rotate(new _e(e.axis[0],e.axis[1],e.axis[2]),$r.FromDegrees(e.angle).radians())}setAbsolutePosition(e){e.node.setAbsolutePosition(new _e(e.position[0],e.position[1],e.position[2]))}setDirection(e){e.node.setDirection(new _e(e.direction[0],e.direction[1],e.direction[2]))}setParent(e){e.node.setParent(e.parentNode)}translate(e){e.node.translate(new _e(e.direction[0],e.direction[1],e.direction[2]),e.distance)}}class VU{constructor(e){this.context=e}pickWithRay(e){return this.context.scene.pickWithRay(e.ray)}pickWithPickingRay(){const e=this.context.scene,t=e.createPickingRay(e.pointerX,e.pointerY,me.Identity(),this.context.scene.activeCamera,!1);return e.pickWithRay(t)}getDistance(e){return e.pickInfo.distance}getPickedMesh(e){return e.pickInfo.pickedMesh}getPickedPoint(e){const t=e.pickInfo.pickedPoint;return[t.x,t.y,t.z]}hit(e){return e.pickInfo.hit}getSubMeshId(e){return e.pickInfo.subMeshId}getSubMeshFaceId(e){return e.pickInfo.subMeshFaceId}getBU(e){return e.pickInfo.bu}getBV(e){return e.pickInfo.bv}getPickedSprite(e){return e.pickInfo.pickedSprite}}class UU{constructor(e){this.context=e}createPickingRay(){const e=this.context.scene;return e.createPickingRay(e.pointerX,e.pointerY,me.Identity(),this.context.scene.activeCamera,!1)}createRay(e){const t=new _e(e.origin[0],e.origin[1],e.origin[2]),i=new _e(e.direction[0],e.direction[1],e.direction[2]);let s;return 0!==e.length&&(s=e.length),new Ua(t,i,s)}createRayFromTo(e){const t=new _e(e.from[0],e.from[1],e.from[2]),i=new _e(e.to[0],e.to[1],e.to[2]);return Ua.CreateNewFromTo(t,i)}getOrigin(e){const t=e.ray.origin;return[t.x,t.y,t.z]}getDirection(e){const t=e.ray.direction;return[t.x,t.y,t.z]}getLength(e){return e.ray.length}}class GU{constructor(e){this.context=e}getScene(){return this.context.scene}setAndAttachScene(e){return e.scene.metadata={shadowGenerators:[]},new lo("root",this.context.scene),this.context.scene=e.scene}backgroundColour(e){this.context.scene.clearColor=Ae.FromColor3(Ee.FromHexString(e.colour))}activateCamera(e){this.context.scene.activeCamera.detachControl(),this.context.scene.activeCamera=e.camera}useRightHandedSystem(e){this.context.scene.useRightHandedSystem=e.use,this.context.scene.activeCamera.getViewMatrix(!0),this.context.scene.activeCamera.getProjectionMatrix(!0)}drawPointLightNoReturn(e){this.drawPointLight(e)}getShadowGenerators(){return this.context.scene.metadata&&this.context.scene.metadata.shadowGenerators?this.context.scene.metadata.shadowGenerators:[]}drawPointLight(e){const t=new _e(e.position[0],e.position[1],e.position[2]),i=new ex(`pointLight${Math.random()}`,t,this.context.scene);if(e.enableShadows){i.shadowEnabled=!0;const t=new Wv(e.shadowGeneratorMapSize,i);t.darkness=e.shadowDarkness,t.usePercentageCloserFiltering=!0,t.contactHardeningLightSizeUVRatio=.2,t.bias=1e-4,t.normalBias=.002,i.shadowMaxZ=1e3,i.shadowMinZ=.01,this.context.scene.metadata.shadowGenerators.push(t),this.context.scene.meshes.forEach((e=>{"bitbybit-hdrSkyBox"===e.name||e.name.includes("bitbybit-ground")||(t.addShadowCaster(e,!0),e.receiveShadows=!0)}))}if(i.diffuse=Ee.FromHexString(e.diffuse),i.specular=Ee.FromHexString(e.specular),i.intensityMode=ua.INTENSITYMODE_LUMINOUSPOWER,i.intensity=e.intensity,e.radius>0){const t=R_.CreateSphere(`PointLightSphere${Math.random()}`,{diameter:2*e.radius},this.context.scene),s=new cu(`LightMaterial${Math.random()}`,this.context.scene);s.diffuseColor=i.diffuse,s.specularColor=i.diffuse,s.emissiveColor=i.diffuse,t.material=s,t.parent=i}return i}drawDirectionalLightNoReturn(e){this.drawDirectionalLight(e)}drawDirectionalLight(e){const t=new _e(e.direction[0],e.direction[1],e.direction[2]),i=new cg(`directionalLight${Math.random()}`,t,this.context.scene);if(e.enableShadows){i.shadowEnabled=!0;const t=new Wv(e.shadowGeneratorMapSize,i);t.darkness=e.shadowDarkness,t.usePercentageCloserFiltering=!0,t.contactHardeningLightSizeUVRatio=.2,t.bias=1e-4,t.normalBias=.002,i.shadowMaxZ=1e3,i.shadowMinZ=0,this.context.scene.metadata.shadowGenerators.push(t),this.context.scene.meshes.forEach((e=>{"bitbybit-hdrSkyBox"===e.name||e.name.includes("bitbybit-ground")||(t.addShadowCaster(e,!0),e.receiveShadows=!0)}))}return i.diffuse=Ee.FromHexString(e.diffuse),i.specular=Ee.FromHexString(e.specular),i.intensity=e.intensity,i.shadowMaxZ=1e3,i}getActiveCamera(){return this.context.scene.activeCamera}adjustActiveArcRotateCamera(e){const t=this.context.scene.getCameraByName("Camera");t.position=new _e(e.position[0],e.position[1],e.position[2]),t.target=new _e(e.lookAt[0],e.lookAt[1],e.lookAt[2]);const i=_e.Distance(t.position,t.target);t.radius=i,void 0!==e.lowerBetaLimit&&(t.lowerBetaLimit=this.getRadians(e.lowerBetaLimit)),void 0!==e.upperBetaLimit&&(t.upperBetaLimit=this.getRadians(e.upperBetaLimit)),void 0!==e.angularSensibilityX&&(t.angularSensibilityX=e.angularSensibilityX),void 0!==e.angularSensibilityY&&(t.angularSensibilityY=e.angularSensibilityY),void 0!==e.panningSensibility&&(t.panningSensibility=e.panningSensibility),void 0!==e.wheelPrecision&&(t.wheelPrecision=e.wheelPrecision),void 0!==e.maxZ&&(t.maxZ=e.maxZ)}clearAllDrawn(){const e=this.context.scene;if(e&&(e.environmentTexture&&e.environmentTexture.dispose(),e.environmentTexture=null,e.fogMode=Hr.FOGMODE_NONE,e.meshes.forEach((e=>e.dispose())),e.meshes=[],e.materials.forEach((e=>e.dispose())),e.textures.forEach((e=>e.dispose())),e.materials=[],e.textures=[],e.useRightHandedSystem=!1,e.geometries.forEach((e=>{e.meshes&&e.meshes.forEach((e=>e.dispose())),e.dispose&&e.dispose()})),e.geometries=[],e.lights.forEach((e=>{"HemiLight"!==e.name&&e.dispose()})),e.lights=e.lights.filter((e=>"HemiLight"===e.name)),e.transformNodes&&e.transformNodes.forEach((e=>{e&&"root"!==e.name&&e.dispose()})),e.metadata&&(e.metadata.shadowGenerators.length>0&&(e.metadata.shadowGenerators.forEach((e=>e.dispose())),e.metadata.shadowGenerators=[]),e.metadata.xr&&e.metadata.xr.dispose(),e.metadata.guiManager&&e.metadata.guiManager.dispose()),e.transformNodes=[e.getTransformNodeByName("root")],e.activeCamera&&"Camera"!==e.activeCamera.name)){e.cameras.forEach((e=>e.dispose()));const t=new hc("Camera",0,10,10,new _e(0,0,0),e);t.lowerRadiusLimit=0,e.setActiveCameraByName(t.name),t.setPosition(new _e(0,10,20));const i=document.getElementById("renderCanvas");t.attachControl(i,!0),t.minZ=0}}enableSkybox(e){let t;e.skybox===AU.skyboxEnum.default?t=new vg("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.15.13/textures/skybox/default_skybox/skybox",this.context.scene):e.skybox===AU.skyboxEnum.clearSky?t=vg.CreateFromPrefilteredData("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.15.13/textures/skybox/clear_sky/environment.env",this.context.scene,!1,!1):e.skybox===AU.skyboxEnum.city&&(t=vg.CreateFromPrefilteredData("https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.15.13/textures/skybox/city/environmentSpecular.env",this.context.scene,!1,!1)),this.context.scene.createDefaultSkybox(t,!0,e.size,e.blur,!0).name="bitbybit-hdrSkyBox",this.context.scene.environmentIntensity=e.environmentIntensity}onPointerDown(e){this.context.scene.onPointerDown=e.statement_update}onPointerUp(e){this.context.scene.onPointerUp=e.statement_update}onPointerMove(e){this.context.scene.onPointerMove=e.statement_update}fog(e){switch(e.mode){case AU.fogModeEnum.none:this.context.scene.fogMode=0;break;case AU.fogModeEnum.exponential:this.context.scene.fogMode=1;break;case AU.fogModeEnum.exponentialSquared:this.context.scene.fogMode=2;break;case AU.fogModeEnum.linear:this.context.scene.fogMode=3}this.context.scene.fogDensity=e.density,this.context.scene.fogStart=e.start,this.context.scene.fogEnd=e.end,this.context.scene.fogColor=Ee.FromHexString(e.color)}enablePhysics(e){this.context.scene.enablePhysics(new _e(e.vector[0],e.vector[1],e.vector[2]),this.context.havokPlugin)}getRadians(e){let t=$r.FromDegrees(e).radians();return e<0&&(t=-t),t}}class zU{constructor(e){this.context=e}createSimple(e){const t=new Pa(e.url,this.context.scene,void 0,e.invertY,this.getSamplingMode(e.samplingMode));return t.uScale=e.uScale,t.vScale=e.vScale,t.wAng=e.wAng,t.invertZ=e.invertZ,t.uOffset=e.uOffset,t.vOffset=e.vOffset,t}getSamplingMode(e){switch(e){case _U.samplingModeEnum.nearest:return Pa.NEAREST_SAMPLINGMODE;case _U.samplingModeEnum.bilinear:return Pa.BILINEAR_SAMPLINGMODE;case _U.samplingModeEnum.trilinear:return Pa.TRILINEAR_SAMPLINGMODE;default:return Pa.NEAREST_SAMPLINGMODE}}}class WU{rotationCenterAxis(e){return[[...me.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...me.RotationAxis(new _e(e.axis[0],e.axis[1],e.axis[2]),$r.FromDegrees(e.angle).radians()).toArray()],[...me.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterX(e){return[[...me.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...me.RotationX($r.FromDegrees(e.angle).radians()).toArray()],[...me.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterY(e){return[[...me.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...me.RotationY($r.FromDegrees(e.angle).radians()).toArray()],[...me.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterZ(e){return[[...me.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...me.RotationZ($r.FromDegrees(e.angle).radians()).toArray()],[...me.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}rotationCenterYawPitchRoll(e){return[[...me.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...me.RotationYawPitchRoll($r.FromDegrees(e.yaw).radians(),$r.FromDegrees(e.pitch).radians(),$r.FromDegrees(e.roll).radians()).toArray()],[...me.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}scaleCenterXYZ(e){return[[...me.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...me.Scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2]).toArray()],[...me.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}scaleXYZ(e){return[[...me.Scaling(e.scaleXyz[0],e.scaleXyz[1],e.scaleXyz[2]).toArray()]]}uniformScale(e){return[[...me.Scaling(e.scale,e.scale,e.scale).toArray()]]}uniformScaleFromCenter(e){return[[...me.Translation(-e.center[0],-e.center[1],-e.center[2]).toArray()],[...me.Scaling(e.scale,e.scale,e.scale).toArray()],[...me.Translation(e.center[0],e.center[1],e.center[2]).toArray()]]}translationXYZ(e){return[[...me.Translation(e.translation[0],e.translation[1],e.translation[2]).toArray()]]}translationsXYZ(e){return e.translations.map((e=>[[...me.Translation(e[0],e[1],e[2]).toArray()]]))}}class HU{constructor(e,t,i){this.mesh=new LU(e),this.camera=new lV(e),this.gaussianSplatting=new fV(e),this.node=new kU(e,t),this.scene=new GU(e),this.webxr=new dV(e),this.transforms=new WU,this.io=new FU(e),this.ray=new UU(e),this.pick=new VU(e),this.material=new cV(e,i),this.texture=new zU(e),this.meshBuilder=new BU(e,this.mesh),this.engine=new _V(e)}}var XU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class YU{constructor(e){this.jscadWorkerManager=e}intersect(e){return XU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.intersect",e)}))}subtract(e){return XU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.subtract",e)}))}union(e){return XU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.union",e)}))}intersectTwo(e){return XU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.intersectTwo",e)}))}subtractTwo(e){return XU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.subtractTwo",e)}))}unionTwo(e){return XU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.unionTwo",e)}))}subtractFrom(e){return XU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("booleans.subtractFrom",e)}))}}var QU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class jU{constructor(e){this.jscadWorkerManager=e}expand(e){return QU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("expansions.expand",e)}))}offset(e){return QU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("expansions.offset",e)}))}}var KU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class $U{constructor(e){this.jscadWorkerManager=e}extrudeLinear(e){return KU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeLinear",e)}))}extrudeRectangular(e){return KU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeRectangular",e)}))}extrudeRectangularPoints(e){return KU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeRectangularPoints",e)}))}extrudeRotate(e){return KU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("extrusions.extrudeRotate",e)}))}}var qU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class ZU{constructor(e){this.jscadWorkerManager=e}hullChain(e){return qU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("hulls.hullChain",e)}))}hull(e){return qU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("hulls.hullChain",e)}))}}var JU=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class eG{constructor(e){this.jscadWorkerManager=e}createFromPoints(e){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createFromPoints",e)}))}createPathsFromPoints(e){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createPathsFromPoints",e)}))}createFromPolyline(e){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createFromPolyline",e)}))}createEmpty(){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.createEmpty",{})}))}close(e){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.close",e)}))}appendPoints(e){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.appendPoints",e)}))}appendPolyline(e){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.appendPolyline",e)}))}appendArc(e){return JU(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("path.appendArc",e)}))}}var tG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class iG{constructor(e){this.jscadWorkerManager=e}createFromPoints(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromPoints",e)}))}createFromPolyline(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromPolyline",e)}))}createFromCurve(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromCurve",e)}))}createFromPath(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.createFromPath",e)}))}circle(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.circle",e)}))}ellipse(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.ellipse",e)}))}rectangle(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.rectangle",e)}))}roundedRectangle(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.roundedRectangle",e)}))}square(e){return tG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("polygon.square",e)}))}star(e){return tG(this,void 0,void 0,(function*(){return yield this.jscadWorkerManager.genericCallToWorkerPromise("polygon.star",e)}))}}var sG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class rG{constructor(e){this.jscadWorkerManager=e}cube(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cube",e)}))}cubesOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cubesOnCenterPoints",e)}))}cuboid(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cuboid",e)}))}cuboidsOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cuboidsOnCenterPoints",e)}))}cylinderElliptic(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylinderElliptic",e)}))}cylinderEllipticOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylinderEllipticOnCenterPoints",e)}))}cylinder(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylinder",e)}))}cylindersOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.cylindersOnCenterPoints",e)}))}ellipsoid(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.ellipsoid",e)}))}ellipsoidsOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.ellipsoidsOnCenterPoints",e)}))}geodesicSphere(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.geodesicSphere",e)}))}geodesicSpheresOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.geodesicSpheresOnCenterPoints",e)}))}roundedCuboid(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCuboid",e)}))}roundedCuboidsOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCuboidsOnCenterPoints",e)}))}roundedCylinder(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCylinder",e)}))}roundedCylindersOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.roundedCylindersOnCenterPoints",e)}))}sphere(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.sphere",e)}))}spheresOnCenterPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.spheresOnCenterPoints",e)}))}torus(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.torus",e)}))}fromPolygonPoints(e){return sG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapes.fromPolygonPoints",e)}))}}var nG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class oG{constructor(e){this.jscadWorkerManager=e}cylindricalText(e){return nG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("text.cylindricalText",e)}))}sphericalText(e){return nG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("text.sphericalText",e)}))}createVectorText(e){return nG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("text.createVectorText",e)}))}}class aG{constructor(e){this.jscadWorkerManager=e}colorize(e){return t=this,i=void 0,r=function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("colors.colorize",e)},new((s=void 0)||(s=Promise))((function(e,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof s?i:new s((function(e){e(i)}))).then(o,a)}l((r=r.apply(t,i||[])).next())}));var t,i,s,r}}var lG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class hG{constructor(e,t,i){this.jscadWorkerManager=e,this.context=t,this.geometryHelper=i,this.booleans=new YU(e),this.expansions=new jU(e),this.extrusions=new $U(e),this.hulls=new ZU(e),this.path=new eG(e),this.polygon=new iG(e),this.shapes=new rG(e),this.text=new oG(e),this.colors=new aG(e)}drawSolidOrPolygonMesh(e){return lG(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("shapeToMesh",e);let i,s;i=e.jscadMesh&&e.updatable?e.jscadMesh:new ha(`jscadMesh${Math.random()}`,this.context.scene),s=e.mesh.color&&e.mesh.color.length>0?Ee.FromArray(e.mesh.color).toHexString():Array.isArray(e.colours)?e.colours[0]:e.colours;const r=this.makeMesh(Object.assign(Object.assign({},e),{colour:s}),i,t);return e.jscadMesh=r,r}))}makeMesh(e,t,i){this.createMesh(i.positions,i.indices,i.normals,t,i.transforms,e.updatable),t.material=new Lx(`jscadMaterial${Math.random()}`,this.context.scene),t.flipFaces(!1);const s=t.material;return s.baseColor=Ee.FromHexString(e.colour),s.metallic=1,s.roughness=.6,s.alpha=e.opacity,s.alphaMode=1,s.backFaceCulling=!0,s.zOffset=0,t.isPickable=!1,e.hidden&&(t.isVisible=!1),t}drawSolidOrPolygonMeshes(e){return lG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e).then((t=>{let i;e.jscadMesh&&e.updatable?(i=e.jscadMesh,i.getChildMeshes().forEach((e=>{e.dispose(),i.removeChild(e)}))):i=new ha("local_origin"+Math.random(),this.context.scene),i.isVisible=!1;const s=Array.isArray(e.colours)&&e.colours.length===t.length,r=Array.isArray(e.colours);return t.map(((t,n)=>{const o=new ha(`jscadMesh${Math.random()}`,this.context.scene);let a;a=t.color?Ee.FromArray(t.color).toHexString():s?e.colours[n]:r?e.colours[0]:e.colours,this.makeMesh(Object.assign(Object.assign({},e),{colour:a}),o,t).parent=i})),e.jscadMesh=i,i}))}))}drawPath(e){return lG(this,void 0,void 0,(function*(){return new Promise((t=>{if(e.path.points&&e.path.isClosed){const t=e.path.points[0];e.path.points.push([t[0],0,t[1]])}let i=e.colour;e.path.color&&(i=Ee.FromArray(e.path.color).toHexString()),t(this.geometryHelper.drawPolyline(e.pathMesh,e.path.points,e.updatable,e.width,e.opacity,i))}))}))}transformSolids(e){return lG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("transformSolids",e)}))}transformSolid(e){return lG(this,void 0,void 0,(function*(){return this.jscadWorkerManager.genericCallToWorkerPromise("transformSolid",e)}))}downloadSolidSTL(e){return lG(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("downloadSolidSTL",e);this.downloadFile(t.blob,e.fileName,"stl")}))}downloadSolidsSTL(e){return lG(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("downloadSolidsSTL",e);this.downloadFile(t.blob,e.fileName,"stl")}))}downloadGeometryDxf(e){return lG(this,void 0,void 0,(function*(){const t=yield this.jscadWorkerManager.genericCallToWorkerPromise("downloadGeometryDxf",e);this.downloadFile(t.blob,e.fileName,"dxf")}))}downloadFile(e,t,i){const s=URL.createObjectURL(e),r=document.createElement("a");r.href=s,r.target="_self",r.download=t+"."+i,r.click(),r.remove()}createMesh(e,t,i,s,r,n){const o=new Wn;o.positions=e,o.indices=t,Wn.ComputeNormals(e,t,i,{useRightHandedSystem:!0}),o.normals=i,o.applyToMesh(s,n),s.setPreTransformMatrix(me.FromArray(r))}}var cG=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class uG extends $B{constructor(e,t,i){super(e),this.occWorkerManager=e,this.context=t,this.geometryHelper=i}loadSTEPorIGES(e){return this.context.getFile(e.assetFile).then((t=>this.occWorkerManager.genericCallToWorkerPromise("io.loadSTEPorIGES",new Jk.LoadStepOrIgesDto(t,e.assetFile.name,e.adjustZtoY))))}loadSTEPorIGESFromText(e){return this.occWorkerManager.genericCallToWorkerPromise("io.loadSTEPorIGES",new Jk.LoadStepOrIgesDto(e.text,`fake.${e.fileType}`,e.adjustZtoY))}saveShapeStl(e){return cG(this,void 0,void 0,(function*(){this.saveStl(e)}))}saveShapeStlAndReturn(e){return cG(this,void 0,void 0,(function*(){return this.saveStl(e)}))}saveStl(e){return cG(this,void 0,void 0,(function*(){const t=new Jk.DrawShapeDto;t.drawEdges=!1,t.shape=e.shape,t.precision=e.precision;const i=(yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",t)).faceList.map((e=>this.geometryHelper.createOrUpdateSurfaceMesh({positions:e.vertex_coord,normals:e.normal_coord,indices:e.tri_indexes},void 0,!1,void 0,!0,!1)));let s;return e.fileName.includes(".stl")&&(e.fileName=e.fileName.replace(".stl","")),s=document&&e.tryDownload?sU.CreateSTL(i,!0,e.fileName,e.binary,!0,!0):sU.CreateSTL(i,!1,e.fileName,e.binary,!0,!0),i.forEach((e=>e.dispose())),s}))}}var dG,_G=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class pG extends fk{constructor(e,t,i,s,r){super(t),this.context=e,this.occWorkerManager=t,this.geometryHelper=i,this.solidText=s,this.vector=r,this.usedMaterials=[],this.io=new uG(t,e,i)}drawShape(e){return _G(this,void 0,void 0,(function*(){const t=Object.assign({},e);e.faceMaterial&&delete e.faceMaterial;const i=yield this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh",e);return this.handleDecomposedMesh(e,i,t)}))}drawShapes(e){return _G(this,void 0,void 0,(function*(){const t=Object.assign({},e);e.faceMaterial&&delete e.faceMaterial;const i=yield this.occWorkerManager.genericCallToWorkerPromise("shapesToMeshes",e),s=yield Promise.all(i.map((i=>_G(this,void 0,void 0,(function*(){return this.handleDecomposedMesh(e,i,t)}))))),r=new ha("shapesMeshContainer"+Math.random(),this.context.scene);return s.forEach((e=>{e.parent=r})),r}))}handleDecomposedMesh(e,t,i){return _G(this,void 0,void 0,(function*(){const s=new ha("brepMesh"+Math.random(),this.context.scene);let r;if(s.isVisible=!1,e.drawFaces&&t&&t.faceList&&t.faceList.length){let n;if(i.faceMaterial)n=i.faceMaterial;else{const t=Array.isArray(e.faceColour)?e.faceColour[0]:e.faceColour,i=e.faceOpacity,s=e.drawEdges?2:0,r=this.usedMaterials.find((e=>e.sceneId===this.context.scene.uid&&e.hex===t&&e.alpha===i&&e.zOffset===s));if(this.usedMaterials=this.usedMaterials.filter((e=>e.sceneId===this.context.scene.uid)),r)n=r.material;else{const e=new Lx("pbr"+Math.random(),this.context.scene);e.baseColor=Ee.FromHexString(t),e.metallic=1,e.roughness=.6,e.alpha=i,e.alphaMode=1,e.backFaceCulling=!0,e.doubleSided=!1,e.zOffset=s,this.usedMaterials.push({sceneId:this.context.scene.uid,hex:t,alpha:i,zOffset:s,material:e}),n=e}}const o=t.faceList.map((e=>({positions:e.vertex_coord,normals:e.normal_coord,indices:e.tri_indexes,uvs:e.uvs})));this.geometryHelper.createOrUpdateSurfacesMesh(o,r,!1,n,!0,!1).parent=s}if(e.drawEdges&&t&&t.edgeList&&t.edgeList.length){const i=[];t.edgeList.forEach((e=>{const t=e.vertex_coord.filter((e=>void 0!==e));i.push(t)})),this.geometryHelper.drawPolylines(r,i,!1,e.edgeWidth,e.edgeOpacity,e.edgeColour).parent=s}if(e.drawVertices&&t&&t.pointsList&&t.pointsList.length&&(this.geometryHelper.drawPoints({pointsMesh:r,points:t.pointsList,opacity:1,size:e.vertexSize,colours:e.vertexColour,updatable:!1}).parent=s),e.drawEdgeIndexes){const i=t.edgeList.map((t=>_G(this,void 0,void 0,(function*(){const i=this.computeEdgeMiddlePos(t),s=new gU.TextDto;return s.text=`${t.edge_index+1}`,s.height=e.edgeIndexHeight,s.lineSpacing=1.5,(yield this.solidText.createVectorText(s)).map((e=>e.map((e=>[e[0],e[1]+.05,0])).map((e=>this.vector.add({first:e,second:i})))))})))),r=yield Promise.all(i),n=this.geometryHelper.drawPolylines(null,r.flat(),!1,.2,1,e.edgeIndexColour);n.parent=s,n.material.zOffset=-2}if(e.drawFaceIndexes){const i=t.faceList.map((t=>_G(this,void 0,void 0,(function*(){const i=this.computeFaceMiddlePos(t.vertex_coord_vec),s=new gU.TextDto;return s.text=`${t.face_index}`,s.height=e.faceIndexHeight,s.lineSpacing=1.5,(yield this.solidText.createVectorText(s)).map((e=>e.map((e=>[e[0],e[1]+.05,0])).map((e=>this.vector.add({first:e,second:i})))))})))),r=yield Promise.all(i),n=this.geometryHelper.drawPolylines(null,r.flat(),!1,.2,1,e.faceIndexColour);n.parent=s,e.drawEdges&&(n.material.zOffset=-2)}return s}))}computeFaceMiddlePos(e){let t=0,i=0,s=0,r=0;return e.forEach((e=>{t+=e[0],i+=e[1],s+=e[2],r++})),[t/r,i/r,s/r]}computeEdgeMiddlePos(e){let t;if(2===e.vertex_coord.length){const i=e.vertex_coord[0],s=e.vertex_coord[1];t=this.vector.lerp({first:i,second:s,fraction:.5})}else if(3===e.vertex_coord.length)t=e.vertex_coord[1];else{const i=e.vertex_coord[Math.floor(e.vertex_coord.length/2)],s=e.vertex_coord[Math.floor(e.vertex_coord.length/2+1)];t=this.vector.lerp({first:i,second:s,fraction:.5})}return t}}class fG{constructor(e){this.context=e}createCircle(e){return new this.context.verb.geom.Circle(e.center,e.xAxis,e.yAxis,e.radius)}createArc(e){return new this.context.verb.geom.Arc(e.center,e.xAxis,e.yAxis,e.radius,$r.FromDegrees(e.minAngle).radians(),$r.FromDegrees(e.maxAngle).radians())}center(e){return e.circle.center()}radius(e){return e.circle.radius()}maxAngle(e){return $r.FromRadians(e.circle.maxAngle()).degrees()}minAngle(e){return $r.FromRadians(e.circle.minAngle()).degrees()}xAxis(e){return e.circle.xaxis()}yAxis(e){return e.circle.yaxis()}}class mG{constructor(e){this.context=e}createEllipse(e){return new this.context.verb.geom.Ellipse(e.center,e.xAxis,e.yAxis)}createArc(e){return new this.context.verb.geom.EllipseArc(e.center,e.xAxis,e.yAxis,$r.FromDegrees(e.minAngle).radians(),$r.FromDegrees(e.maxAngle).radians())}center(e){return e.ellipse.center()}maxAngle(e){return $r.FromRadians(e.ellipse.maxAngle()).degrees()}minAngle(e){return $r.FromRadians(e.ellipse.minAngle()).degrees()}xAxis(e){return e.ellipse.xaxis()}yAxis(e){return e.ellipse.yaxis()}}class gG{constructor(e,t){this.context=e,this.geometryHelper=t,this.circle=new fG(e),this.ellipse=new mG(e)}drawCurve(e){const t=e.curve.tessellate();return this.geometryHelper.drawPolyline(e.curveMesh,t,e.updatable,e.size,e.opacity,e.colours)}drawCurves(e){const t=e.curves.map((e=>e.tessellate()));return this.geometryHelper.drawPolylines(e.curvesMesh,t,e.updatable,e.size,e.opacity,e.colours)}createCurveByKnotsControlPointsWeights(e){return this.context.verb.geom.NurbsCurve.byKnotsControlPointsWeights(e.degree,e.knots,e.points,e.weights)}createCurveByPoints(e){return this.context.verb.geom.NurbsCurve.byPoints(e.points,e.degree)}createBezierCurve(e){return new this.context.verb.geom.BezierCurve(e.points,e.weights)}clone(e){return e.curve.clone()}closestParam(e){return e.curve.closestParam(e.point)}closestParams(e){return e.points.map((t=>e.curve.closestParam(t)))}closestPoint(e){return e.curve.closestPoint(e.point)}closestPoints(e){return e.points.map((t=>e.curve.closestPoint(t)))}controlPoints(e){return e.curve.controlPoints()}degree(e){return e.curve.degree()}derivatives(e){return e.curve.derivatives(e.parameter,e.numDerivatives)}divideByEqualArcLengthToParams(e){return e.curve.divideByEqualArcLength(e.subdivision).map((e=>e.u))}divideByEqualArcLengthToPoints(e){return e.curve.divideByEqualArcLength(e.subdivision).map((t=>e.curve.point(t.u)))}divideByArcLengthToParams(e){return e.curve.divideByArcLength(e.length).map((e=>e.u))}divideByArcLengthToPoints(e){return e.curve.divideByArcLength(e.length).map((t=>e.curve.point(t.u)))}divideCurvesByEqualArcLengthToPoints(e){return e.curves.map((t=>this.divideByEqualArcLengthToPoints({curve:t,subdivision:e.subdivision})))}divideCurvesByArcLengthToPoints(e){return e.curves.map((t=>this.divideByArcLengthToPoints({curve:t,length:e.length})))}domain(e){return e.curve.domain()}startPoint(e){return e.curve.point(e.curve.domain().min)}endPoint(e){return e.curve.point(e.curve.domain().max)}startPoints(e){return e.curves.map((e=>this.startPoint({curve:e})))}endPoints(e){return e.curves.map((e=>this.endPoint({curve:e})))}knots(e){return e.curve.knots()}lengthAtParam(e){return e.curve.lengthAtParam(e.parameter)}length(e){return e.curve.length()}paramAtLength(e){return e.curve.paramAtLength(e.length,e.tolerance)}pointAtParam(e){return e.curve.point(e.parameter)}pointsAtParam(e){return e.curves.map((t=>this.pointAtParam({curve:t,parameter:e.parameter})))}reverse(e){return e.curve.reverse()}split(e){return e.curve.split(e.parameter)}tangent(e){return e.curve.tangent(e.parameter)}tessellate(e){return e.curve.tessellate(e.tolerance)}transform(e){const t=e.curve.controlPoints(),i=this.geometryHelper.transformControlPoints(e.transformation,t);return this.context.verb.geom.NurbsCurve.byKnotsControlPointsWeights(e.curve.degree(),e.curve.knots(),i,e.curve.weights())}transformCurves(e){return e.curves.map((t=>this.transform({curve:t,transformation:e.transformation})))}weights(e){return e.curve.weights()}}class vG{constructor(e){this.context=e}create(e){return new this.context.verb.geom.RevolvedSurface(e.profile,e.center,e.axis,$r.FromDegrees(e.angle).radians())}profile(e){return e.revolution.profile()}center(e){return e.revolution.center()}axis(e){return e.revolution.axis()}angle(e){return $r.FromRadians(e.revolution.angle()).degrees()}}class xG{constructor(e){this.context=e}create(e){return new this.context.verb.geom.ConicalSurface(e.axis,e.xAxis,e.base,e.height,e.radius)}axis(e){return e.cone.axis()}base(e){return e.cone.base()}height(e){return e.cone.height()}radius(e){return e.cone.radius()}xAxis(e){return e.cone.xaxis()}}class bG{constructor(e){this.context=e}create(e){return new this.context.verb.geom.CylindricalSurface(e.axis,e.xAxis,e.base,e.height,e.radius)}axis(e){return e.cylinder.axis()}base(e){return e.cylinder.base()}height(e){return e.cylinder.height()}radius(e){return e.cylinder.radius()}xAxis(e){return e.cylinder.xaxis()}}class TG{constructor(e){this.context=e}create(e){return new this.context.verb.geom.ExtrudedSurface(e.profile,e.direction)}direction(e){return e.extrusion.direction()}profile(e){return e.extrusion.profile()}}class yG{constructor(e){this.context=e}create(e){return new this.context.verb.geom.SphericalSurface(e.center,e.radius)}radius(e){return e.sphere.radius()}center(e){return e.sphere.center()}}class SG{constructor(e){this.context=e}create(e){return new this.context.verb.geom.SweptSurface(e.profile,e.rail)}profile(e){return e.sweep.profile()}rail(e){return e.sweep.rail()}}class CG{constructor(e,t){this.context=e,this.geometryHelper=t,this.cone=new xG(e),this.cylinder=new bG(e),this.extrusion=new TG(e),this.sphere=new yG(e),this.revolved=new vG(e),this.sweep=new SG(e)}drawSurface(e){const t=e.surface.tessellate(),i={positions:[],indices:[],normals:[]};let s=0;t.faces.forEach((e=>{s=this.parseFaces(e,t,i,s)}));const r=new Lx("pbr"+Math.random(),this.context.scene);return r.baseColor=Ee.FromHexString(Array.isArray(e.colours)?e.colours[0]:e.colours),r.metallic=1,r.roughness=.6,r.alpha=e.opacity,r.alphaMode=1,r.backFaceCulling=!1,r.doubleSided=!0,this.geometryHelper.createOrUpdateSurfaceMesh(i,e.surfaceMesh,e.updatable,r,!0,e.hidden)}drawSurfaces(e){const t=[];e.surfaces.forEach((e=>{t.push(e.tessellate())}));const i={positions:[],indices:[],normals:[]};let s=0;t.forEach((e=>{e.faces.forEach((t=>{s=this.parseFaces(t,e,i,s)}))}));const r=new Lx("pbr"+Math.random(),this.context.scene);return r.baseColor=Ee.FromHexString(Array.isArray(e.colours)?e.colours[0]:e.colours),r.metallic=1,r.roughness=.6,r.alpha=e.opacity,r.alphaMode=1,r.backFaceCulling=!0,r.doubleSided=!1,this.geometryHelper.createOrUpdateSurfaceMesh(i,e.surfacesMesh,e.updatable,r,!0,e.hidden)}drawSurfacesMultiColour(e){return e.surfacesMesh&&e.updatable&&e.surfacesMesh.getChildren().forEach((e=>e.dispose())),e.surfacesMesh=new ha(`ColouredSurfaces${Math.random()}`,this.context.scene),Array.isArray(e.colours)?e.surfaces.forEach(((t,i)=>{const s=this.drawSurface({surface:t,colours:e.colours[i]?e.colours[i]:e.colours[0],updatable:e.updatable,opacity:e.opacity,hidden:e.hidden});e.surfacesMesh.addChild(s)})):e.surfaces.forEach(((t,i)=>{const s=this.drawSurface({surface:t,colours:e.colours,updatable:e.updatable,opacity:e.opacity,hidden:e.hidden});e.surfacesMesh.addChild(s)})),e.surfacesMesh}boundaries(e){return e.surface.boundaries()}createSurfaceByCorners(e){return this.context.verb.geom.NurbsSurface.byCorners(e.point1,e.point2,e.point3,e.point4)}createSurfaceByKnotsControlPointsWeights(e){return this.context.verb.geom.NurbsSurface.byKnotsControlPointsWeights(e.degreeU,e.degreeV,e.knotsU,e.knotsV,e.points,e.weights)}createSurfaceByLoftingCurves(e){return this.context.verb.geom.NurbsSurface.byLoftingCurves(e.curves,e.degreeV)}clone(e){return e.surface.clone()}closestParam(e){return e.surface.closestParam(e.point)}closestPoint(e){return e.surface.closestPoint(e.point)}controlPoints(e){return e.surface.controlPoints()}degreeU(e){return e.surface.degreeU()}degreeV(e){return e.surface.degreeV()}derivatives(e){return e.surface.derivatives(e.u,e.v,e.numDerivatives)}domainU(e){return e.surface.domainU()}domainV(e){return e.surface.domainV()}isocurve(e){return e.surface.isocurve(e.parameter,e.useV)}isocurvesSubdivision(e){const t=.999999/e.isocurveSegments,i=this.context.verb.core.Vec.span(1e-7,.9999999,t);return e.includeLast||i.pop(),e.includeFirst||i.shift(),i.map((t=>e.surface.isocurve(t,e.useV)))}isocurvesAtParams(e){return e.parameters.map((t=>e.surface.isocurve(t,e.useV)))}knotsU(e){return e.surface.knotsU()}knotsV(e){return e.surface.knotsV()}normal(e){return e.surface.normal(e.u,e.v)}point(e){return e.surface.point(e.u,e.v)}reverse(e){return e.surface.reverse()}split(e){return e.surface.split(e.parameter,e.useV)}transformSurface(e){const t=e.surface.controlPoints(),i=e.transformation,s=[];return t.forEach((e=>{let t=e;t=this.geometryHelper.transformControlPoints(i,t),s.push(t)})),this.context.verb.geom.NurbsSurface.byKnotsControlPointsWeights(e.surface.degreeU(),e.surface.degreeV(),e.surface.knotsU(),e.surface.knotsV(),s,e.surface.weights())}weights(e){return e.surface.weights()}parseFaces(e,t,i,s){return e.reverse().forEach((e=>{const r=t.normals[e];i.normals.push(r[0],r[1],r[2]);const n=t.points[e];i.positions.push(n[0],n[1],n[2]),i.indices.push(s),s++})),s}}class EG{constructor(e,t){this.context=e,this.geometryHelper=t}curves(e){return this.context.verb.geom.Intersect.curves(e.firstCurve,e.secondCurve,e.tolerance)}curveAndSurface(e){return this.context.verb.geom.Intersect.curveAndSurface(e.curve,e.surface,e.tolerance)}surfaces(e){return this.context.verb.geom.Intersect.surfaces(e.firstSurface,e.secondSurface)}curveCurveFirstParams(e){return e.intersections.filter((e=>e.u0>=0&&e.u0<=1)).map((e=>e.u0))}curveCurveSecondParams(e){return e.intersections.filter((e=>e.u1>=0&&e.u1<=1)).map((e=>e.u1))}curveCurveFirstPoints(e){return e.intersections.filter((e=>e.u0>=0&&e.u0<=1)).map((e=>e.point0))}curveCurveSecondPoints(e){return e.intersections.filter((e=>e.u1>=0&&e.u1<=1)).map((e=>e.point1))}curveSurfaceCurveParams(e){return e.intersections.filter((e=>e.u>=0&&e.u<=1)).map((e=>e.u))}curveSurfaceSurfaceParams(e){return e.intersections.map((e=>e.uv))}curveSurfaceCurvePoints(e){return e.intersections.filter((e=>e.u>=0&&e.u<=1)).map((e=>e.curvePoint))}curveSurfaceSurfacePoints(e){return e.intersections.map((e=>e.surfacePoint))}}class AG{constructor(e,t){this.curve=new gG(e,t),this.surface=new CG(e,t),this.intersect=new EG(e,t)}}!function(e){e.IntervalDto=class{constructor(){this.min=0,this.max=1}},e.UVDto=class{constructor(){this.u=0,this.v=0}},e.CurveCurveIntersection=class{},e.CurveSurfaceIntersection=class{},e.SurfaceSurfaceIntersectionPoint=class{}}(dG||(dG={}));Bi.ShadersStore.cellPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nvec3 computeCustomDiffuseLighting(lightingInfo info,vec3 diffuseBase,float shadow)\n{diffuseBase=info.diffuse*shadow;\n#ifdef CELLBASIC\nfloat level=1.0;if (info.ndl<0.5)\nlevel=0.5;diffuseBase.rgb*vec3(level,level,level);\n#else\nfloat ToonThresholds[4];ToonThresholds[0]=0.95;ToonThresholds[1]=0.5;ToonThresholds[2]=0.2;ToonThresholds[3]=0.03;float ToonBrightnessLevels[5];ToonBrightnessLevels[0]=1.0;ToonBrightnessLevels[1]=0.8;ToonBrightnessLevels[2]=0.6;ToonBrightnessLevels[3]=0.35;ToonBrightnessLevels[4]=0.2;if (info.ndl>ToonThresholds[0])\n{diffuseBase.rgb*=ToonBrightnessLevels[0];}\nelse if (info.ndl>ToonThresholds[1])\n{diffuseBase.rgb*=ToonBrightnessLevels[1];}\nelse if (info.ndl>ToonThresholds[2])\n{diffuseBase.rgb*=ToonBrightnessLevels[2];}\nelse if (info.ndl>ToonThresholds[3])\n{diffuseBase.rgb*=ToonBrightnessLevels[3];}\nelse\n{diffuseBase.rgb*=ToonBrightnessLevels[4];}\n#endif\nreturn max(diffuseBase,vec3(0.2));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nlightingInfo info;vec3 diffuseBase=vec3(0.,0.,0.);float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.cellVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class PG extends xl{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.NDOTL=!0,this.CUSTOMUSERLIGHTING=!0,this.CELLBASIC=!0,this.DEPTHPREPASS=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class IG extends ml{constructor(e,t){super(e,t),this.diffuseColor=new Ee(1,1,1),this._computeHighLevel=!1,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new PG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&$c.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(r.CELLBASIC=!this.computeHighLevel,Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=zo(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),Ho(n,o,this,r,!!i),jo(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),Vo(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="cell",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights-1}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&$c.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),xo(this._activeEffect,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this._maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}getClassName(){return"CellMaterial"}clone(e){return St.Clone((()=>new IG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.CellMaterial",e}static Parse(e,t,i){return St.Parse((()=>new IG(e.name,t)),e,t,i)}}Ze([nt("diffuseTexture")],IG.prototype,"_diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],IG.prototype,"diffuseTexture",void 0),Ze([ot("diffuse")],IG.prototype,"diffuseColor",void 0),Ze([rt("computeHighLevel")],IG.prototype,"_computeHighLevel",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],IG.prototype,"computeHighLevel",void 0),Ze([rt("disableLighting")],IG.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],IG.prototype,"disableLighting",void 0),Ze([rt("maxSimultaneousLights")],IG.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],IG.prototype,"maxSimultaneousLights",void 0),z("BABYLON.CellMaterial",IG);class RG{constructor(){}}class MG extends cu{AttachAfterBind(e,t){if(this._newUniformInstances)for(const e in this._newUniformInstances){const i=e.toString().split("-");"vec2"==i[0]?t.setVector2(i[1],this._newUniformInstances[e]):"vec3"==i[0]?this._newUniformInstances[e]instanceof Ee?t.setColor3(i[1],this._newUniformInstances[e]):t.setVector3(i[1],this._newUniformInstances[e]):"vec4"==i[0]?(this._newUniformInstances[e]instanceof Ae?t.setDirectColor4(i[1],this._newUniformInstances[e]):t.setVector4(i[1],this._newUniformInstances[e]),t.setVector4(i[1],this._newUniformInstances[e])):"mat4"==i[0]?t.setMatrix(i[1],this._newUniformInstances[e]):"float"==i[0]&&t.setFloat(i[1],this._newUniformInstances[e])}if(this._newSamplerInstances)for(const e in this._newSamplerInstances){const i=e.toString().split("-");"sampler2D"==i[0]&&this._newSamplerInstances[e].isReady&&this._newSamplerInstances[e].isReady()&&t.setTexture(i[1],this._newSamplerInstances[e])}}ReviewUniform(e,t){if("uniform"==e&&this._newUniforms)for(let e=0;e0&&n.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",s);const o=this._createdShaderName;return $i.ShadersStore[o+"VertexShader"]&&$i.ShadersStore[o+"PixelShader"]||($i.ShadersStore[o+"VertexShader"]=this._injectCustomCode(this.VertexShader,"vertex"),$i.ShadersStore[o+"PixelShader"]=this._injectCustomCode(this.FragmentShader,"fragment")),o}_injectCustomCode(e,t){const i=this._getCustomCode(t);for(const t in i){const s=i[t];if(s&&s.length>0){const i="#define "+t;e=e.replace(i,"\n"+s+"\n"+i)}}return e}_getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_BEGIN:this.CustomParts.Vertex_Begin,CUSTOM_VERTEX_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Vertex_Definitions||""),CUSTOM_VERTEX_MAIN_BEGIN:this.CustomParts.Vertex_MainBegin,CUSTOM_VERTEX_UPDATE_POSITION:this.CustomParts.Vertex_Before_PositionUpdated,CUSTOM_VERTEX_UPDATE_NORMAL:this.CustomParts.Vertex_Before_NormalUpdated,CUSTOM_VERTEX_MAIN_END:this.CustomParts.Vertex_MainEnd,CUSTOM_VERTEX_UPDATE_WORLDPOS:this.CustomParts.Vertex_After_WorldPosComputed}:{CUSTOM_FRAGMENT_BEGIN:this.CustomParts.Fragment_Begin,CUSTOM_FRAGMENT_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Fragment_Definitions||""),CUSTOM_FRAGMENT_MAIN_BEGIN:this.CustomParts.Fragment_MainBegin,CUSTOM_FRAGMENT_UPDATE_DIFFUSE:this.CustomParts.Fragment_Custom_Diffuse,CUSTOM_FRAGMENT_UPDATE_ALPHA:this.CustomParts.Fragment_Custom_Alpha,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.CustomParts.Fragment_Before_Lights,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:this.CustomParts.Fragment_Before_FragColor,CUSTOM_FRAGMENT_MAIN_END:this.CustomParts.Fragment_MainEnd,CUSTOM_FRAGMENT_BEFORE_FOG:this.CustomParts.Fragment_Before_Fog}}constructor(e,t){super(e,t),this.CustomParts=new RG,this.customShaderNameResolve=this.Builder,this.FragmentShader=$i.ShadersStore.defaultPixelShader,this.VertexShader=$i.ShadersStore.defaultVertexShader,MG.ShaderIndexer++,this._createdShaderName="custom_"+MG.ShaderIndexer}_afterBind(e,t=null,i){if(t){this.AttachAfterBind(e,t);try{super._afterBind(e,t,i)}catch(e){}}}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(-1!=t.indexOf("sampler")?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Fragment_Custom_Diffuse(e){return this.CustomParts.Fragment_Custom_Diffuse=e.replace("result","diffuseColor"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}MG.ShaderIndexer=1,z("BABYLON.CustomMaterial",MG);class OG{constructor(){}}class DG extends zg{AttachAfterBind(e,t){if(this._newUniformInstances)for(const e in this._newUniformInstances){const i=e.toString().split("-");"vec2"==i[0]?t.setVector2(i[1],this._newUniformInstances[e]):"vec3"==i[0]?this._newUniformInstances[e]instanceof Ee?t.setColor3(i[1],this._newUniformInstances[e]):t.setVector3(i[1],this._newUniformInstances[e]):"vec4"==i[0]?(this._newUniformInstances[e]instanceof Ae?t.setDirectColor4(i[1],this._newUniformInstances[e]):t.setVector4(i[1],this._newUniformInstances[e]),t.setVector4(i[1],this._newUniformInstances[e])):"mat4"==i[0]?t.setMatrix(i[1],this._newUniformInstances[e]):"float"==i[0]&&t.setFloat(i[1],this._newUniformInstances[e])}if(this._newSamplerInstances)for(const e in this._newSamplerInstances){const i=e.toString().split("-");"sampler2D"==i[0]&&this._newSamplerInstances[e].isReady&&this._newSamplerInstances[e].isReady()&&t.setTexture(i[1],this._newSamplerInstances[e])}}ReviewUniform(e,t){if("uniform"==e&&this._newUniforms)for(let e=0;e{if("vertex"===t)return e?e(t,i):i;const s=new Bp(i);return s.inlineToken="#define pbr_inline",s.processCode(),e?e(t,s.code):s.code}}n&&this._customAttributes&&this._customAttributes.length>0&&n.push(...this._customAttributes),this.ReviewUniform("uniform",t),this.ReviewUniform("sampler",s);const a=this._createdShaderName;return $i.ShadersStore[a+"VertexShader"]&&$i.ShadersStore[a+"PixelShader"]||($i.ShadersStore[a+"VertexShader"]=this._injectCustomCode(this.VertexShader,"vertex"),$i.ShadersStore[a+"PixelShader"]=this._injectCustomCode(this.FragmentShader,"fragment")),a}_injectCustomCode(e,t){const i=this._getCustomCode(t);for(const t in i){const s=i[t];if(s&&s.length>0){const i="#define "+t;e=e.replace(i,"\n"+s+"\n"+i)}}return e}_getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_BEGIN:this.CustomParts.Vertex_Begin,CUSTOM_VERTEX_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Vertex_Definitions||""),CUSTOM_VERTEX_MAIN_BEGIN:this.CustomParts.Vertex_MainBegin,CUSTOM_VERTEX_UPDATE_POSITION:this.CustomParts.Vertex_Before_PositionUpdated,CUSTOM_VERTEX_UPDATE_NORMAL:this.CustomParts.Vertex_Before_NormalUpdated,CUSTOM_VERTEX_MAIN_END:this.CustomParts.Vertex_MainEnd,CUSTOM_VERTEX_UPDATE_WORLDPOS:this.CustomParts.Vertex_After_WorldPosComputed}:{CUSTOM_FRAGMENT_BEGIN:this.CustomParts.Fragment_Begin,CUSTOM_FRAGMENT_MAIN_BEGIN:this.CustomParts.Fragment_MainBegin,CUSTOM_FRAGMENT_DEFINITIONS:(this._customUniform?.join("\n")||"")+(this.CustomParts.Fragment_Definitions||""),CUSTOM_FRAGMENT_UPDATE_ALBEDO:this.CustomParts.Fragment_Custom_Albedo,CUSTOM_FRAGMENT_UPDATE_ALPHA:this.CustomParts.Fragment_Custom_Alpha,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.CustomParts.Fragment_Before_Lights,CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS:this.CustomParts.Fragment_Custom_MetallicRoughness,CUSTOM_FRAGMENT_UPDATE_MICROSURFACE:this.CustomParts.Fragment_Custom_MicroSurface,CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:this.CustomParts.Fragment_Before_FinalColorComposition,CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:this.CustomParts.Fragment_Before_FragColor,CUSTOM_FRAGMENT_MAIN_END:this.CustomParts.Fragment_MainEnd,CUSTOM_FRAGMENT_BEFORE_FOG:this.CustomParts.Fragment_Before_Fog}}constructor(e,t){super(e,t),this.CustomParts=new OG,this.customShaderNameResolve=this.Builder,this.FragmentShader=$i.ShadersStore.pbrPixelShader,this.VertexShader=$i.ShadersStore.pbrVertexShader,this.FragmentShader=this.FragmentShader.replace(/#include/g,$i.IncludesShadersStore.pbrBlockAlbedoOpacity),this.FragmentShader=this.FragmentShader.replace(/#include/g,$i.IncludesShadersStore.pbrBlockReflectivity),this.FragmentShader=this.FragmentShader.replace(/#include/g,$i.IncludesShadersStore.pbrBlockFinalColorComposition),DG.ShaderIndexer++,this._createdShaderName="custompbr_"+DG.ShaderIndexer}_afterBind(e,t=null,i){if(t){this.AttachAfterBind(e,t);try{super._afterBind(e,t,i)}catch(e){}}}AddUniform(e,t,i){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances={},this._newUniformInstances={}),i&&(-1!=t.indexOf("sampler")?this._newSamplerInstances[t+"-"+e]=i:this._newUniformInstances[t+"-"+e]=i),this._customUniform.push("uniform "+t+" "+e+";"),this._newUniforms.push(e),this}AddAttribute(e){return this._customAttributes||(this._customAttributes=[]),this._customAttributes.push(e),this}Fragment_Begin(e){return this.CustomParts.Fragment_Begin=e,this}Fragment_Definitions(e){return this.CustomParts.Fragment_Definitions=e,this}Fragment_MainBegin(e){return this.CustomParts.Fragment_MainBegin=e,this}Fragment_Custom_Albedo(e){return this.CustomParts.Fragment_Custom_Albedo=e.replace("result","surfaceAlbedo"),this}Fragment_Custom_Alpha(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this}Fragment_Before_Lights(e){return this.CustomParts.Fragment_Before_Lights=e,this}Fragment_Custom_MetallicRoughness(e){return this.CustomParts.Fragment_Custom_MetallicRoughness=e,this}Fragment_Custom_MicroSurface(e){return this.CustomParts.Fragment_Custom_MicroSurface=e,this}Fragment_Before_Fog(e){return this.CustomParts.Fragment_Before_Fog=e,this}Fragment_Before_FinalColorComposition(e){return this.CustomParts.Fragment_Before_FinalColorComposition=e,this}Fragment_Before_FragColor(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this}Fragment_MainEnd(e){return this.CustomParts.Fragment_MainEnd=e,this}Vertex_Begin(e){return this.CustomParts.Vertex_Begin=e,this}Vertex_Definitions(e){return this.CustomParts.Vertex_Definitions=e,this}Vertex_MainBegin(e){return this.CustomParts.Vertex_MainBegin=e,this}Vertex_Before_PositionUpdated(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this}Vertex_Before_NormalUpdated(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this}Vertex_After_WorldPosComputed(e){return this.CustomParts.Vertex_After_WorldPosComputed=e,this}Vertex_MainEnd(e){return this.CustomParts.Vertex_MainEnd=e,this}}DG.ShaderIndexer=1,z("BABYLON.PBRCustomMaterial",DG);Bi.ShadersStore.firePixelShader="precision highp float;uniform vec4 vEyePosition;varying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\nuniform sampler2D distortionSampler;uniform sampler2D opacitySampler;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nvec4 bx2(vec4 x)\n{return vec4(2.0)*x-vec4(1.0);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);float alpha=1.0;\n#ifdef DIFFUSE\nconst float distortionAmount0 =0.092;const float distortionAmount1 =0.092;const float distortionAmount2 =0.092;vec2 heightAttenuation=vec2(0.3,0.39);vec4 noise0=texture2D(distortionSampler,vDistortionCoords1);vec4 noise1=texture2D(distortionSampler,vDistortionCoords2);vec4 noise2=texture2D(distortionSampler,vDistortionCoords3);vec4 noiseSum=bx2(noise0)*distortionAmount0+bx2(noise1)*distortionAmount1+bx2(noise2)*distortionAmount2;vec4 perturbedBaseCoords=vec4(vDiffuseUV,0.0,1.0)+noiseSum*(vDiffuseUV.y*heightAttenuation.x+heightAttenuation.y);vec4 opacityColor=texture2D(opacitySampler,perturbedBaseCoords.xy);\n#ifdef ALPHATEST\nif (opacityColor.r<0.1)\ndiscard;\n#endif\n#include\nbaseColor=texture2D(diffuseSampler,perturbedBaseCoords.xy)*2.0;baseColor*=opacityColor;baseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(1.0,1.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec4 color=vec4(baseColor.rgb,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.fireVertexShader="precision highp float;attribute vec3 position;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\nuniform float time;uniform float speed;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;varying vec2 vDistortionCoords2;varying vec2 vDistortionCoords3;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef DIFFUSE\nvDiffuseUV=uv;vDiffuseUV.y-=0.2;\n#endif\n#include\n#include\n#include\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#ifdef DIFFUSE\nvec3 layerSpeed=vec3(-0.2,-0.52,-0.1)*speed;vDistortionCoords1.x=uv.x;vDistortionCoords1.y=uv.y+layerSpeed.x*time/1000.0;vDistortionCoords2.x=uv.x;vDistortionCoords2.y=uv.y+layerSpeed.y*time/1000.0;vDistortionCoords3.x=uv.x;vDistortionCoords3.y=uv.y+layerSpeed.z*time/1000.0;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class wG extends xl{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.UV1=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.BonesPerMesh=0,this.NUM_BONE_INFLUENCERS=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class NG extends ml{constructor(e,t){super(e,t),this.diffuseColor=new Ee(1,1,1),this.speed=1,this._scaledDiffuse=new Ee,this._lastTime=0}needAlphaBlending(){return!1}needAlphaTesting(){return!0}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new wG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,this._diffuseTexture&&$c.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(r.ALPHATEST=!!this._opacityTexture,r._areMiscDirty&&(r.POINTSIZE=this.pointsCloud||n.forcePointsCloud,r.FOG=n.fogEnabled&&e.applyFog&&n.fogMode!==Hr.FOGMODE_NONE&&this.fogEnabled,r.LOGARITHMICDEPTH=this._useLogarithmicDepth),Ho(n,o,this,r,!!i),jo(e,r,!1,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.UV1&&s.push(er.UVKind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="fire",l=["world","view","viewProjection","vEyePosition","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","time","speed"];mo(l);const h=r.toString();t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:l,uniformBuffersNames:[],samplers:["diffuseSampler","distortionSampler","opacitySampler"],defines:h,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:null,maxSimultaneousLights:4,transformFeedbackVaryings:null},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&$c.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix()),this._activeEffect.setTexture("distortionSampler",this._distortionTexture),this._activeEffect.setTexture("opacitySampler",this._opacityTexture)),xo(this._activeEffect,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._lastTime+=s.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime),this._activeEffect.setFloat("speed",this.speed),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._distortionTexture&&this._distortionTexture.animations&&this._distortionTexture.animations.length>0&&e.push(this._distortionTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._distortionTexture&&e.push(this._distortionTexture),this._opacityTexture&&e.push(this._opacityTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._distortionTexture===e||this._opacityTexture===e}getClassName(){return"FireMaterial"}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),this._distortionTexture&&this._distortionTexture.dispose(),super.dispose(e)}clone(e){return St.Clone((()=>new NG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FireMaterial",e.diffuseColor=this.diffuseColor.asArray(),e.speed=this.speed,this._diffuseTexture&&(e._diffuseTexture=this._diffuseTexture.serialize()),this._distortionTexture&&(e._distortionTexture=this._distortionTexture.serialize()),this._opacityTexture&&(e._opacityTexture=this._opacityTexture.serialize()),e}static Parse(e,t,i){const s=new NG(e.name,t);return s.diffuseColor=Ee.FromArray(e.diffuseColor),s.speed=e.speed,s.alpha=e.alpha,s.id=e.id,Tt.AddTagsTo(s,e.tags),s.backFaceCulling=e.backFaceCulling,s.wireframe=e.wireframe,e._diffuseTexture&&(s._diffuseTexture=Pa.Parse(e._diffuseTexture,t,i)),e._distortionTexture&&(s._distortionTexture=Pa.Parse(e._distortionTexture,t,i)),e._opacityTexture&&(s._opacityTexture=Pa.Parse(e._opacityTexture,t,i)),s}}Ze([nt("diffuseTexture")],NG.prototype,"_diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],NG.prototype,"diffuseTexture",void 0),Ze([nt("distortionTexture")],NG.prototype,"_distortionTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],NG.prototype,"distortionTexture",void 0),Ze([nt("opacityTexture")],NG.prototype,"_opacityTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],NG.prototype,"opacityTexture",void 0),Ze([ot("diffuse")],NG.prototype,"diffuseColor",void 0),Ze([rt()],NG.prototype,"speed",void 0),z("BABYLON.FireMaterial",NG);Bi.ShadersStore.furPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 furColor;uniform float furLength;varying vec3 vPositionW;varying float vfur_length;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef HIGHLEVEL\nuniform float furOffset;uniform float furOcclusion;uniform sampler2D furTexture;varying vec2 vFurUV;\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#include\n#include\nfloat Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=furColor;vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor*=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef HIGHLEVEL\nvec4 furTextureColor=texture2D(furTexture,vec2(vFurUV.x,vFurUV.y));if (furTextureColor.a<=0.0 || furTextureColor.g[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase.rgb*baseColor.rgb,0.0,1.0);\n#ifdef HIGHLEVEL\nvec4 color=vec4(finalDiffuse,alpha);\n#else\nfloat r=vfur_length/furLength*0.5;vec4 color=vec4(finalDiffuse*(0.5+r),alpha);\n#endif\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.furVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\nuniform float furLength;uniform float furAngle;\n#ifdef HIGHLEVEL\nuniform float furOffset;uniform vec3 furGravity;uniform float furTime;uniform float furSpacing;uniform float furDensity;\n#endif\n#ifdef HEIGHTMAP\nuniform sampler2D heightTexture;\n#endif\n#ifdef HIGHLEVEL\nvarying vec2 vFurUV;\n#endif\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\nvarying float vfur_length;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nfloat Rand(vec3 rv) {float x=dot(rv,vec3(12.9898,78.233,24.65487));return fract(sin(x)*43758.5453);}\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nfloat r=Rand(position);\n#ifdef HEIGHTMAP\n#if __VERSION__>100\nvfur_length=furLength*texture(heightTexture,uv).x;\n#else\nvfur_length=furLength*texture2D(heightTexture,uv).r;\n#endif\n#else \nvfur_length=(furLength*r);\n#endif\nvec3 tangent1=vec3(normal.y,-normal.x,0);vec3 tangent2=vec3(-normal.z,0,normal.x);r=Rand(tangent1*r);float J=(2.0+4.0*r);r=Rand(tangent2*r);float K=(2.0+2.0*r);tangent1=tangent1*J+tangent2*K;tangent1=normalize(tangent1);vec3 newPosition=position+normal*vfur_length*cos(furAngle)+tangent1*vfur_length*sin(furAngle);\n#ifdef HIGHLEVEL\nvec3 forceDirection=vec3(0.0,0.0,0.0);forceDirection.x=sin(furTime+position.x*0.05)*0.2;forceDirection.y=cos(furTime*0.7+position.y*0.04)*0.2;forceDirection.z=sin(furTime*0.7+position.z*0.04)*0.2;vec3 displacement=vec3(0.0,0.0,0.0);displacement=furGravity+forceDirection;float displacementFactor=pow(furOffset,3.0);vec3 aNormal=normal;aNormal.xyz+=displacement*displacementFactor;newPosition=vec3(newPosition.x,newPosition.y,newPosition.z)+(normalize(aNormal)*furOffset*furSpacing);\n#endif\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\ngl_Position=viewProjection*finalWorld*vec4(newPosition,1.0);vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos);\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#ifdef HIGHLEVEL\nvFurUV=vDiffuseUV*furDensity;\n#endif\n#else\n#ifdef HIGHLEVEL\nvFurUV=uv*furDensity;\n#endif\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class FG extends xl{constructor(){super(),this.DIFFUSE=!1,this.HEIGHTMAP=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.HIGHLEVEL=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class LG extends ml{constructor(e,t){super(e,t),this.diffuseColor=new Ee(1,1,1),this.furLength=1,this.furAngle=0,this.furColor=new Ee(.44,.21,.02),this.furOffset=0,this.furSpacing=12,this.furGravity=new _e(0,0,0),this.furSpeed=100,this.furDensity=20,this.furOcclusion=0,this._disableLighting=!1,this._maxSimultaneousLights=4,this.highLevelFur=!0,this._furTime=0}get furTime(){return this._furTime}set furTime(e){this._furTime=e}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}updateFur(){for(let e=1;e0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="fur",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","furLength","furAngle","furColor","furOffset","furGravity","furTime","furSpacing","furDensity","furOcclusion"];mo(h);const c=["diffuseSampler","heightTexture","furTexture"],u=[];ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&$c.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),this._heightTexture&&this._activeEffect.setTexture("heightTexture",this._heightTexture),xo(this._activeEffect,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._activeEffect.setFloat("furLength",this.furLength),this._activeEffect.setFloat("furAngle",this.furAngle),this._activeEffect.setColor4("furColor",this.furColor,1),this.highLevelFur&&(this._activeEffect.setVector3("furGravity",this.furGravity),this._activeEffect.setFloat("furOffset",this.furOffset),this._activeEffect.setFloat("furSpacing",this.furSpacing),this._activeEffect.setFloat("furDensity",this.furDensity),this._activeEffect.setFloat("furOcclusion",this.furOcclusion),this._furTime+=this.getScene().getEngine().getDeltaTime()/this.furSpeed,this._activeEffect.setFloat("furTime",this._furTime),this._activeEffect.setTexture("furTexture",this.furTexture)),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.heightTexture&&this.heightTexture.animations&&this.heightTexture.animations.length>0&&e.push(this.heightTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._heightTexture&&e.push(this._heightTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e||this._heightTexture===e}dispose(e){if(this.diffuseTexture&&this.diffuseTexture.dispose(),this._meshes)for(let t=1;tnew LG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.FurMaterial",this._meshes&&(e.sourceMeshName=this._meshes[0].name,e.quality=this._meshes.length),e}getClassName(){return"FurMaterial"}static Parse(e,t,i){const s=St.Parse((()=>new LG(e.name,t)),e,t,i);return e.sourceMeshName&&s.highLevelFur&&t.executeWhenReady((()=>{const i=t.getMeshByName(e.sourceMeshName);if(i){const r=LG.GenerateTexture("Fur Texture",t);s.furTexture=r,LG.FurifyMesh(i,e.quality)}})),s}static GenerateTexture(e,t){const i=new uu("FurTexture "+e,256,t,!0),s=i.getContext();for(let e=0;e<2e4;++e)s.fillStyle="rgba(255, "+Math.floor(255*Math.random())+", "+Math.floor(255*Math.random())+", 1)",s.fillRect(Math.random()*i.getSize().width,Math.random()*i.getSize().height,2,2);return i.update(!1),i.wrapU=Pa.WRAP_ADDRESSMODE,i.wrapV=Pa.WRAP_ADDRESSMODE,i}static FurifyMesh(e,t){const i=[e],s=e.material;let r;if(!(s instanceof LG))throw"The material of the source mesh must be a Fur Material";for(r=1;r0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="gradient",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","logarithmicDepthConstant","topColor","bottomColor","offset","smoothness","scale"];mo(h);const c=[],u=[];ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:4}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,n),this._mustRebind(s,n,i)&&(xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._activeEffect.setColor4("topColor",this.topColor,this.topColorAlpha),this._activeEffect.setColor4("bottomColor",this.bottomColor,this.bottomColorAlpha),this._activeEffect.setFloat("offset",this.offset),this._activeEffect.setFloat("scale",this.scale),this._activeEffect.setFloat("smoothness",this.smoothness),this._afterBind(t,this._activeEffect,i))}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new kG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GradientMaterial",e}getClassName(){return"GradientMaterial"}static Parse(e,t,i){return St.Parse((()=>new kG(e.name,t)),e,t,i)}}Ze([rt("maxSimultaneousLights")],kG.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],kG.prototype,"maxSimultaneousLights",void 0),Ze([ot()],kG.prototype,"topColor",void 0),Ze([rt()],kG.prototype,"topColorAlpha",void 0),Ze([ot()],kG.prototype,"bottomColor",void 0),Ze([rt()],kG.prototype,"bottomColorAlpha",void 0),Ze([rt()],kG.prototype,"offset",void 0),Ze([rt()],kG.prototype,"scale",void 0),Ze([rt()],kG.prototype,"smoothness",void 0),Ze([rt("disableLighting")],kG.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],kG.prototype,"disableLighting",void 0),z("BABYLON.GradientMaterial",kG);Bi.ShadersStore.gridPixelShader="#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;uniform float visibility;uniform vec3 mainColor;uniform vec3 lineColor;uniform vec4 gridControl;uniform vec3 gridOffset;varying vec3 vPosition;varying vec3 vNormal;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#ifdef OPACITY\nvarying vec2 vOpacityUV;uniform sampler2D opacitySampler;uniform vec2 vOpacityInfos;\n#endif\nfloat getDynamicVisibility(float position) {float majorGridFrequency=gridControl.y;if (floor(position+0.5)==floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{return 1.0;}\nreturn gridControl.z;}\nfloat getAnisotropicAttenuation(float differentialLength) {const float maxNumberOfLines=10.0;return clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);}\nfloat isPointOnLine(float position,float differentialLength) {float fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \n#ifdef ANTIALIAS\nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);float result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result;\n#else\nreturn abs(fractionPartOfPosition)\n#endif\nfloat opacity=1.0;\n#ifdef TRANSPARENT\nopacity=clamp(grid,0.08,gridControl.w*grid);\n#endif\n#ifdef OPACITY\nopacity*=texture2D(opacitySampler,vOpacityUV).a;\n#endif\ngl_FragColor=vec4(color.rgb,opacity*visibility);\n#ifdef TRANSPARENT\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Bi.ShadersStore.gridVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#include\nuniform mat4 projection;uniform mat4 view;varying vec3 vPosition;varying vec3 vNormal;\n#include\n#include\n#ifdef OPACITY\nvarying vec2 vOpacityUV;uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\nvec4 cameraSpacePosition=view*worldPos;gl_Position=projection*cameraSpacePosition;\n#ifdef OPACITY\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\nif (vOpacityInfos.x==0.)\n{vOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));}\nelse\n{vOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));}\n#endif \n#include\nvPosition=position;vNormal=normal;\n#define CUSTOM_VERTEX_MAIN_END\n}";class VG extends xl{constructor(){super(),this.OPACITY=!1,this.ANTIALIAS=!1,this.TRANSPARENT=!1,this.FOG=!1,this.PREMULTIPLYALPHA=!1,this.MAX_LINE=!1,this.UV1=!1,this.UV2=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class UG extends ml{constructor(e,t){super(e,t),this.mainColor=Ee.Black(),this.lineColor=Ee.Teal(),this.gridRatio=1,this.gridOffset=_e.Zero(),this.majorUnitFrequency=10,this.minorUnitVisibility=.33,this.opacity=1,this.antialias=!0,this.preMultiplyAlpha=!1,this.useMaxLine=!1,this._gridControl=new pe(this.gridRatio,this.majorUnitFrequency,this.minorUnitVisibility,this.opacity)}needAlphaBlending(){return this.opacity<1||this._opacityTexture&&this._opacityTexture.isReady()}needAlphaBlendingForMesh(e){return e.visibility<1||this.needAlphaBlending()}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new VG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;if(r.TRANSPARENT!==this.opacity<1&&(r.TRANSPARENT=!r.TRANSPARENT,r.markAsUnprocessed()),r.PREMULTIPLYALPHA!=this.preMultiplyAlpha&&(r.PREMULTIPLYALPHA=!r.PREMULTIPLYALPHA,r.markAsUnprocessed()),r.MAX_LINE!==this.useMaxLine&&(r.MAX_LINE=!r.MAX_LINE,r.markAsUnprocessed()),r.ANTIALIAS!==this.antialias&&(r.ANTIALIAS=!r.ANTIALIAS,r.markAsUnprocessed()),r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._opacityTexture&&$c.OpacityTextureEnabled)){if(!this._opacityTexture.isReady())return!1;r._needUVs=!0,r.OPACITY=!0}if(Go(e,n,this._useLogarithmicDepth,!1,this.fogEnabled,!1,r),Ho(n,n.getEngine(),this,r,!!i),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial(),jo(e,r,!1,!1);const i=[er.PositionKind,er.NormalKind];r.UV1&&i.push(er.UVKind),r.UV2&&i.push(er.UV2Kind),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess,ko(i,r);const s=r.toString();t.setEffect(n.getEngine().createEffect("grid",i,["projection","mainColor","lineColor","gridControl","gridOffset","vFogInfos","vFogColor","world","view","opacityMatrix","vOpacityInfos","visibility","logarithmicDepthConstant"],["opacitySampler"],s,void 0,this.onCompiled,this.onError),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this._activeEffect.setFloat("visibility",t.visibility),r.INSTANCES&&!r.THIN_INSTANCE||this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("view",s.getViewMatrix()),this._activeEffect.setMatrix("projection",s.getProjectionMatrix()),this._mustRebind(s,n,i)&&(this._activeEffect.setColor3("mainColor",this.mainColor),this._activeEffect.setColor3("lineColor",this.lineColor),this._activeEffect.setVector3("gridOffset",this.gridOffset),this._gridControl.x=this.gridRatio,this._gridControl.y=Math.round(this.majorUnitFrequency),this._gridControl.z=this.minorUnitVisibility,this._gridControl.w=this.opacity,this._activeEffect.setVector4("gridControl",this._gridControl),this._opacityTexture&&$c.OpacityTextureEnabled&&(this._activeEffect.setTexture("opacitySampler",this._opacityTexture),this._activeEffect.setFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),this._activeEffect.setMatrix("opacityMatrix",this._opacityTexture.getTextureMatrix())),this._useLogarithmicDepth&&So(r,n,s)),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new UG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GridMaterial",e}getClassName(){return"GridMaterial"}static Parse(e,t,i){return St.Parse((()=>new UG(e.name,t)),e,t,i)}}Ze([ot()],UG.prototype,"mainColor",void 0),Ze([ot()],UG.prototype,"lineColor",void 0),Ze([rt()],UG.prototype,"gridRatio",void 0),Ze([ht()],UG.prototype,"gridOffset",void 0),Ze([rt()],UG.prototype,"majorUnitFrequency",void 0),Ze([rt()],UG.prototype,"minorUnitVisibility",void 0),Ze([rt()],UG.prototype,"opacity",void 0),Ze([rt()],UG.prototype,"antialias",void 0),Ze([rt()],UG.prototype,"preMultiplyAlpha",void 0),Ze([rt()],UG.prototype,"useMaxLine",void 0),Ze([nt("opacityTexture")],UG.prototype,"_opacityTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],UG.prototype,"opacityTexture",void 0),z("BABYLON.GridMaterial",UG);Bi.ShadersStore.lavaPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;uniform float time;uniform float speed;uniform float movingSpeed;uniform vec3 fogColor;uniform sampler2D noiseTexture;uniform float fogDensity;varying float noise;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nfloat random( vec3 scale,float seed ){return fract( sin( dot( gl_FragCoord.xyz+seed,scale ) )*43758.5453+seed ) ;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nvec4 noiseTex=texture2D( noiseTexture,vDiffuseUV );vec2 T1=vDiffuseUV+vec2( 1.5,-1.5 )*time *0.02;vec2 T2=vDiffuseUV+vec2( -0.5,2.0 )*time*0.01*speed;T1.x+=noiseTex.x*2.0;T1.y+=noiseTex.y*2.0;T2.x-=noiseTex.y*0.2+time*0.001*movingSpeed;T2.y+=noiseTex.z*0.2+time*0.002*movingSpeed;float p=texture2D( noiseTexture,T1*3.0 ).a;vec4 lavaColor=texture2D( diffuseSampler,T2*4.0);vec4 temp=lavaColor*( vec4( p,p,p,p )*2. )+( lavaColor*lavaColor-0.1 );baseColor=temp;float depth=gl_FragCoord.z*4.0;const float LOG2=1.442695;float fogFactor=exp2(-fogDensity*fogDensity*depth*depth*LOG2 );fogFactor=1.0-clamp( fogFactor,0.0,1.0 );baseColor=mix( baseColor,vec4( fogColor,baseColor.w ),fogFactor );diffuseColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0]\n#include[1]\n#include[2]\n#include[3]\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.lavaVertexShader="precision highp float;uniform float time;uniform float lowFrequencySpeed;varying float noise;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n/* NOISE FUNCTIONS */\nvec3 mod289(vec3 x)\n{return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x)\n{return x-floor(x*(1.0/289.0))*289.0;}\nvec4 permute(vec4 x)\n{return mod289(((x*34.0)+1.0)*x);}\nvec4 taylorInvSqrt(vec4 r)\n{return 1.79284291400159-0.85373472095314*r;}\nvec3 fade(vec3 t) {return t*t*t*(t*(t*6.0-15.0)+10.0);}\nfloat pnoise(vec3 P,vec3 rep)\n{vec3 Pi0=mod(floor(P),rep); \nvec3 Pi1=mod(Pi0+vec3(1.0),rep); \nPi0=mod289(Pi0);Pi1=mod289(Pi1);vec3 Pf0=fract(P); \nvec3 Pf1=Pf0-vec3(1.0); \nvec4 ix=vec4(Pi0.x,Pi1.x,Pi0.x,Pi1.x);vec4 iy=vec4(Pi0.yy,Pi1.yy);vec4 iz0=Pi0.zzzz;vec4 iz1=Pi1.zzzz;vec4 ixy=permute(permute(ix)+iy);vec4 ixy0=permute(ixy+iz0);vec4 ixy1=permute(ixy+iz1);vec4 gx0=ixy0*(1.0/7.0);vec4 gy0=fract(floor(gx0)*(1.0/7.0))-0.5;gx0=fract(gx0);vec4 gz0=vec4(0.5)-abs(gx0)-abs(gy0);vec4 sz0=step(gz0,vec4(0.0));gx0-=sz0*(step(0.0,gx0)-0.5);gy0-=sz0*(step(0.0,gy0)-0.5);vec4 gx1=ixy1*(1.0/7.0);vec4 gy1=fract(floor(gx1)*(1.0/7.0))-0.5;gx1=fract(gx1);vec4 gz1=vec4(0.5)-abs(gx1)-abs(gy1);vec4 sz1=step(gz1,vec4(0.0));gx1-=sz1*(step(0.0,gx1)-0.5);gy1-=sz1*(step(0.0,gy1)-0.5);vec3 g000=vec3(gx0.x,gy0.x,gz0.x);vec3 g100=vec3(gx0.y,gy0.y,gz0.y);vec3 g010=vec3(gx0.z,gy0.z,gz0.z);vec3 g110=vec3(gx0.w,gy0.w,gz0.w);vec3 g001=vec3(gx1.x,gy1.x,gz1.x);vec3 g101=vec3(gx1.y,gy1.y,gz1.y);vec3 g011=vec3(gx1.z,gy1.z,gz1.z);vec3 g111=vec3(gx1.w,gy1.w,gz1.w);vec4 norm0=taylorInvSqrt(vec4(dot(g000,g000),dot(g010,g010),dot(g100,g100),dot(g110,g110)));g000*=norm0.x;g010*=norm0.y;g100*=norm0.z;g110*=norm0.w;vec4 norm1=taylorInvSqrt(vec4(dot(g001,g001),dot(g011,g011),dot(g101,g101),dot(g111,g111)));g001*=norm1.x;g011*=norm1.y;g101*=norm1.z;g111*=norm1.w;float n000=dot(g000,Pf0);float n100=dot(g100,vec3(Pf1.x,Pf0.yz));float n010=dot(g010,vec3(Pf0.x,Pf1.y,Pf0.z));float n110=dot(g110,vec3(Pf1.xy,Pf0.z));float n001=dot(g001,vec3(Pf0.xy,Pf1.z));float n101=dot(g101,vec3(Pf1.x,Pf0.y,Pf1.z));float n011=dot(g011,vec3(Pf0.x,Pf1.yz));float n111=dot(g111,Pf1);vec3 fade_xyz=fade(Pf0);vec4 n_z=mix(vec4(n000,n100,n010,n110),vec4(n001,n101,n011,n111),fade_xyz.z);vec2 n_yz=mix(n_z.xy,n_z.zw,fade_xyz.y);float n_xyz=mix(n_yz.x,n_yz.y,fade_xyz.x);return 2.2*n_xyz;}\n/* END FUNCTION */\nfloat turbulence( vec3 p ) {float w=100.0;float t=-.5;for (float f=1.0 ; f<=10.0 ; f++ ){float power=pow( 2.0,f );t+=abs( pnoise( vec3( power*p ),vec3( 10.0,10.0,10.0 ) )/power );}\nreturn t;}\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\n#ifdef NORMAL\nnoise=10.0* -.10*turbulence( .5*normal+time*1.15 );float b=lowFrequencySpeed*5.0*pnoise( 0.05*position +vec3(time*1.025),vec3( 100.0 ) );float displacement=- 1.5*noise+b;vec3 newPosition=position+normal*displacement;gl_Position=viewProjection*finalWorld*vec4( newPosition,1.0 );vec4 worldPos=finalWorld*vec4(newPosition,1.0);vPositionW=vec3(worldPos);vNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class GG extends xl{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.UNLIT=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class zG extends ml{constructor(e,t){super(e,t),this.speed=1,this.movingSpeed=1,this.lowFrequencySpeed=1,this.fogDensity=.15,this._lastTime=0,this.diffuseColor=new Ee(1,1,1),this._disableLighting=!1,this._unlit=!1,this._maxSimultaneousLights=4,this._scaledDiffuse=new Ee}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new GG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&$c.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=!0,zo(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),Ho(n,o,this,r,!!i),jo(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),Vo(r,i),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="lava",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant","time","speed","movingSpeed","fogColor","fogDensity","lowFrequencySpeed"];mo(h);const c=["diffuseSampler","noiseTexture"],u=[];ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,r.UNLIT=this._unlit,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.diffuseTexture&&$c.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),this.noiseTexture&&this._activeEffect.setTexture("noiseTexture",this.noiseTexture),xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._lastTime+=s.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime*this.speed/1e3),this.fogColor||(this.fogColor=Ee.Black()),this._activeEffect.setColor3("fogColor",this.fogColor),this._activeEffect.setFloat("fogDensity",this.fogDensity),this._activeEffect.setFloat("lowFrequencySpeed",this.lowFrequencySpeed),this._activeEffect.setFloat("movingSpeed",this.movingSpeed),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.noiseTexture&&this.noiseTexture.animations&&this.noiseTexture.animations.length>0&&e.push(this.noiseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),this.noiseTexture&&this.noiseTexture.dispose(),super.dispose(e)}clone(e){return St.Clone((()=>new zG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.LavaMaterial",e}getClassName(){return"LavaMaterial"}static Parse(e,t,i){return St.Parse((()=>new zG(e.name,t)),e,t,i)}}Ze([nt("diffuseTexture")],zG.prototype,"_diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],zG.prototype,"diffuseTexture",void 0),Ze([nt()],zG.prototype,"noiseTexture",void 0),Ze([ot()],zG.prototype,"fogColor",void 0),Ze([rt()],zG.prototype,"speed",void 0),Ze([rt()],zG.prototype,"movingSpeed",void 0),Ze([rt()],zG.prototype,"lowFrequencySpeed",void 0),Ze([rt()],zG.prototype,"fogDensity",void 0),Ze([ot()],zG.prototype,"diffuseColor",void 0),Ze([rt("disableLighting")],zG.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],zG.prototype,"disableLighting",void 0),Ze([rt("unlit")],zG.prototype,"_unlit",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],zG.prototype,"unlit",void 0),Ze([rt("maxSimultaneousLights")],zG.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],zG.prototype,"maxSimultaneousLights",void 0),z("BABYLON.LavaMaterial",zG);Bi.ShadersStore.mixPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform sampler2D mixMap1Sampler;uniform vec2 vTextureInfos;\n#ifdef MIXMAP2\nuniform sampler2D mixMap2Sampler;\n#endif\nuniform sampler2D diffuse1Sampler;uniform sampler2D diffuse2Sampler;uniform sampler2D diffuse3Sampler;uniform sampler2D diffuse4Sampler;uniform vec2 diffuse1Infos;uniform vec2 diffuse2Infos;uniform vec2 diffuse3Infos;uniform vec2 diffuse4Infos;\n#ifdef MIXMAP2\nuniform sampler2D diffuse5Sampler;uniform sampler2D diffuse6Sampler;uniform sampler2D diffuse7Sampler;uniform sampler2D diffuse8Sampler;uniform vec2 diffuse5Infos;uniform vec2 diffuse6Infos;uniform vec2 diffuse7Infos;uniform vec2 diffuse8Infos;\n#endif\n#endif\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 finalMixColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef MIXMAP2\nvec4 mixColor2=vec4(1.,1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec4 mixColor=texture2D(mixMap1Sampler,vTextureUV);\n#include\nmixColor.rgb*=vTextureInfos.y;vec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);vec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);vec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);vec4 diffuse4Color=texture2D(diffuse4Sampler,vTextureUV*diffuse4Infos);diffuse1Color.rgb*=mixColor.r;diffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,mixColor.g);diffuse3Color.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,mixColor.b);finalMixColor.rgb=mix(diffuse3Color.rgb,diffuse4Color.rgb,1.0-mixColor.a);\n#ifdef MIXMAP2\nmixColor=texture2D(mixMap2Sampler,vTextureUV);mixColor.rgb*=vTextureInfos.y;vec4 diffuse5Color=texture2D(diffuse5Sampler,vTextureUV*diffuse5Infos);vec4 diffuse6Color=texture2D(diffuse6Sampler,vTextureUV*diffuse6Infos);vec4 diffuse7Color=texture2D(diffuse7Sampler,vTextureUV*diffuse7Infos);vec4 diffuse8Color=texture2D(diffuse8Sampler,vTextureUV*diffuse8Infos);diffuse5Color.rgb=mix(finalMixColor.rgb,diffuse5Color.rgb,mixColor.r);diffuse6Color.rgb=mix(diffuse5Color.rgb,diffuse6Color.rgb,mixColor.g);diffuse7Color.rgb=mix(diffuse6Color.rgb,diffuse7Color.rgb,mixColor.b);finalMixColor.rgb=mix(diffuse7Color.rgb,diffuse8Color.rgb,1.0-mixColor.a);\n#endif\n#endif\n#ifdef VERTEXCOLOR\nfinalMixColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*finalMixColor.rgb,0.0,1.0);vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Bi.ShadersStore.mixVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x==0.)\n{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));}\nelse\n{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class WG extends xl{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.MIXMAP2=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class HG extends ml{constructor(e,t){super(e,t),this.diffuseColor=new Ee(1,1,1),this.specularColor=new Ee(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new WG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(n.texturesEnabled){if(!this._mixTexture1||!this._mixTexture1.isReady())return!1;if(r._needUVs=!0,$c.DiffuseTextureEnabled){if(!this._diffuseTexture1||!this._diffuseTexture1.isReady())return!1;if(r.DIFFUSE=!0,!this._diffuseTexture2||!this._diffuseTexture2.isReady())return!1;if(!this._diffuseTexture3||!this._diffuseTexture3.isReady())return!1;if(!this._diffuseTexture4||!this._diffuseTexture4.isReady())return!1;if(this._mixTexture2){if(!this._mixTexture2.isReady())return!1;if(r.MIXMAP2=!0,!this._diffuseTexture5||!this._diffuseTexture5.isReady())return!1;if(!this._diffuseTexture6||!this._diffuseTexture6.isReady())return!1;if(!this._diffuseTexture7||!this._diffuseTexture7.isReady())return!1;if(!this._diffuseTexture8||!this._diffuseTexture8.isReady())return!1}}}if(Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=zo(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),Ho(n,o,this,r,!!i),jo(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),Vo(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="mix",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","logarithmicDepthConstant","diffuse1Infos","diffuse2Infos","diffuse3Infos","diffuse4Infos","diffuse5Infos","diffuse6Infos","diffuse7Infos","diffuse8Infos"],c=["mixMap1Sampler","mixMap2Sampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","diffuse4Sampler","diffuse5Sampler","diffuse6Sampler","diffuse7Sampler","diffuse8Sampler"],u=[];mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._mixTexture1&&(this._activeEffect.setTexture("mixMap1Sampler",this._mixTexture1),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture1.coordinatesIndex,this._mixTexture1.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture1.getTextureMatrix()),$c.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale)),this._diffuseTexture4&&(this._activeEffect.setTexture("diffuse4Sampler",this._diffuseTexture4),this._activeEffect.setFloat2("diffuse4Infos",this._diffuseTexture4.uScale,this._diffuseTexture4.vScale)))),this._mixTexture2&&(this._activeEffect.setTexture("mixMap2Sampler",this._mixTexture2),$c.DiffuseTextureEnabled&&(this._diffuseTexture5&&(this._activeEffect.setTexture("diffuse5Sampler",this._diffuseTexture5),this._activeEffect.setFloat2("diffuse5Infos",this._diffuseTexture5.uScale,this._diffuseTexture5.vScale)),this._diffuseTexture6&&(this._activeEffect.setTexture("diffuse6Sampler",this._diffuseTexture6),this._activeEffect.setFloat2("diffuse6Infos",this._diffuseTexture6.uScale,this._diffuseTexture6.vScale)),this._diffuseTexture7&&(this._activeEffect.setTexture("diffuse7Sampler",this._diffuseTexture7),this._activeEffect.setFloat2("diffuse7Infos",this._diffuseTexture7.uScale,this._diffuseTexture7.vScale)),this._diffuseTexture8&&(this._activeEffect.setTexture("diffuse8Sampler",this._diffuseTexture8),this._activeEffect.setFloat2("diffuse8Infos",this._diffuseTexture8.uScale,this._diffuseTexture8.vScale)))),xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._mixTexture1&&this._mixTexture1.animations&&this._mixTexture1.animations.length>0&&e.push(this._mixTexture1),this._mixTexture2&&this._mixTexture2.animations&&this._mixTexture2.animations.length>0&&e.push(this._mixTexture2),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture1&&e.push(this._mixTexture1),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._diffuseTexture4&&e.push(this._diffuseTexture4),this._mixTexture2&&e.push(this._mixTexture2),this._diffuseTexture5&&e.push(this._diffuseTexture5),this._diffuseTexture6&&e.push(this._diffuseTexture6),this._diffuseTexture7&&e.push(this._diffuseTexture7),this._diffuseTexture8&&e.push(this._diffuseTexture8),e}hasTexture(e){return!!super.hasTexture(e)||this._mixTexture1===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._diffuseTexture4===e||this._mixTexture2===e||this._diffuseTexture5===e||this._diffuseTexture6===e||this._diffuseTexture7===e||this._diffuseTexture8===e}dispose(e){this._mixTexture1&&this._mixTexture1.dispose(),super.dispose(e)}clone(e){return St.Clone((()=>new HG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.MixMaterial",e}getClassName(){return"MixMaterial"}static Parse(e,t,i){return St.Parse((()=>new HG(e.name,t)),e,t,i)}}Ze([nt("mixTexture1")],HG.prototype,"_mixTexture1",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"mixTexture1",void 0),Ze([nt("mixTexture2")],HG.prototype,"_mixTexture2",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"mixTexture2",void 0),Ze([nt("diffuseTexture1")],HG.prototype,"_diffuseTexture1",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture1",void 0),Ze([nt("diffuseTexture2")],HG.prototype,"_diffuseTexture2",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture2",void 0),Ze([nt("diffuseTexture3")],HG.prototype,"_diffuseTexture3",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture3",void 0),Ze([nt("diffuseTexture4")],HG.prototype,"_diffuseTexture4",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture4",void 0),Ze([nt("diffuseTexture1")],HG.prototype,"_diffuseTexture5",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture5",void 0),Ze([nt("diffuseTexture2")],HG.prototype,"_diffuseTexture6",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture6",void 0),Ze([nt("diffuseTexture3")],HG.prototype,"_diffuseTexture7",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture7",void 0),Ze([nt("diffuseTexture4")],HG.prototype,"_diffuseTexture8",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],HG.prototype,"diffuseTexture8",void 0),Ze([ot()],HG.prototype,"diffuseColor",void 0),Ze([ot()],HG.prototype,"specularColor",void 0),Ze([rt()],HG.prototype,"specularPower",void 0),Ze([rt("disableLighting")],HG.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],HG.prototype,"disableLighting",void 0),Ze([rt("maxSimultaneousLights")],HG.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],HG.prototype,"maxSimultaneousLights",void 0),z("BABYLON.MixMaterial",HG);Bi.ShadersStore.normalPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef LIGHTING\n#include\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef NORMAL\nbaseColor=mix(baseColor,vec4(vNormalW,1.0),0.5);\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef LIGHTING\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0]\n#include[1]\n#include[2]\n#include[3]\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse= baseColor.rgb;\n#endif\nvec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.normalVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class XG extends xl{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.LIGHT0=!1,this.LIGHT1=!1,this.LIGHT2=!1,this.LIGHT3=!1,this.SPOTLIGHT0=!1,this.SPOTLIGHT1=!1,this.SPOTLIGHT2=!1,this.SPOTLIGHT3=!1,this.HEMILIGHT0=!1,this.HEMILIGHT1=!1,this.HEMILIGHT2=!1,this.HEMILIGHT3=!1,this.DIRLIGHT0=!1,this.DIRLIGHT1=!1,this.DIRLIGHT2=!1,this.DIRLIGHT3=!1,this.POINTLIGHT0=!1,this.POINTLIGHT1=!1,this.POINTLIGHT2=!1,this.POINTLIGHT3=!1,this.SHADOW0=!1,this.SHADOW1=!1,this.SHADOW2=!1,this.SHADOW3=!1,this.SHADOWS=!1,this.SHADOWESM0=!1,this.SHADOWESM1=!1,this.SHADOWESM2=!1,this.SHADOWESM3=!1,this.SHADOWPOISSON0=!1,this.SHADOWPOISSON1=!1,this.SHADOWPOISSON2=!1,this.SHADOWPOISSON3=!1,this.SHADOWPCF0=!1,this.SHADOWPCF1=!1,this.SHADOWPCF2=!1,this.SHADOWPCF3=!1,this.SHADOWPCSS0=!1,this.SHADOWPCSS1=!1,this.SHADOWPCSS2=!1,this.SHADOWPCSS3=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.LIGHTING=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class YG extends ml{constructor(e,t){super(e,t),this.diffuseColor=new Ee(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaBlendingForMesh(e){return this.needAlphaBlending()||e.visibility<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new XG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&$c.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=!0,zo(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),Ho(n,o,this,r,!!i),r.LIGHTING=!this._disableLighting,jo(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),Vo(r,i),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),Bo(s,e,r,i),ko(s,r);const a="normal",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:4}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.diffuseTexture&&$c.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this.diffuseTexture&&this.diffuseTexture.dispose(),super.dispose(e)}clone(e){return St.Clone((()=>new YG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.NormalMaterial",e}getClassName(){return"NormalMaterial"}static Parse(e,t,i){return St.Parse((()=>new YG(e.name,t)),e,t,i)}}Ze([nt("diffuseTexture")],YG.prototype,"_diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],YG.prototype,"diffuseTexture",void 0),Ze([ot()],YG.prototype,"diffuseColor",void 0),Ze([rt("disableLighting")],YG.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],YG.prototype,"disableLighting",void 0),Ze([rt("maxSimultaneousLights")],YG.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],YG.prototype,"maxSimultaneousLights",void 0),z("BABYLON.NormalMaterial",YG);Bi.ShadersStore.shadowOnlyPixelShader="precision highp float;uniform vec4 vEyePosition;uniform float alpha;uniform vec3 shadowColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#include[0..1]\nvec4 color=vec4(shadowColor,(1.0-clamp(shadow,0.,1.))*alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.shadowOnlyVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class QG extends xl{constructor(){super(),this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class jG extends ml{constructor(e,t){super(e,t),this._needAlphaBlending=!0,this.shadowColor=Ee.Black()}needAlphaBlending(){return this._needAlphaBlending}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}get activeLight(){return this._activeLight}set activeLight(e){this._activeLight=e}_getFirstShadowLightForMesh(e){for(const t of e.lightSources)if(t.shadowEnabled)return t;return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new QG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(this._activeLight)for(const t of e.lightSources)if(t.shadowEnabled){if(this._activeLight===t)break;const i=e.lightSources.indexOf(this._activeLight);-1!==i&&(e.lightSources.splice(i,1),e.lightSources.splice(0,0,this._activeLight));break}Ho(n,o,this,r,!!i),Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=zo(n,e,r,!1,1);const a=this._getFirstShadowLightForMesh(e)?.getShadowGenerator();if(this._needAlphaBlending=!0,a&&a.getClassName&&"CascadedShadowGenerator"===a.getClassName()){const e=a;this._needAlphaBlending=!e.autoCalcDepthBounds}if(jo(e,r,!1,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),Vo(r,i,1),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),Bo(s,e,r,i),ko(s,r);const a="shadowOnly",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","alpha","shadowColor","mBones","logarithmicDepthConstant"],c=[],u=[];mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:1}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:1}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(n){if(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setFloat("alpha",this.alpha),this._activeEffect.setColor3("shadowColor",this.shadowColor),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),s.lightsEnabled){Lo(s,t,this._activeEffect,r,1);const e=this._getFirstShadowLightForMesh(t);e&&(e._renderId=-1)}(s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE||r.SHADOWCSM0)&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i)}}clone(e){return St.Clone((()=>new jG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.ShadowOnlyMaterial",e}getClassName(){return"ShadowOnlyMaterial"}static Parse(e,t,i){return St.Parse((()=>new jG(e.name,t)),e,t,i)}}z("BABYLON.ShadowOnlyMaterial",jG);Bi.ShadersStore.simplePixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform sampler2D diffuseSampler;uniform vec2 vDiffuseInfos;\n#endif\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float glossiness=0.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Bi.ShadersStore.simpleVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class KG extends xl{constructor(){super(),this.DIFFUSE=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class $G extends ml{constructor(e,t){super(e,t),this.diffuseColor=new Ee(1,1,1),this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new KG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled&&this._diffuseTexture&&$c.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;r._needUVs=!0,r.DIFFUSE=!0}if(Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=zo(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),Ho(n,o,this,r,!!i),jo(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),Vo(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="simple",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","diffuseMatrix","logarithmicDepthConstant"],c=["diffuseSampler"],u=[];mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights-1}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this._diffuseTexture&&$c.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),e}hasTexture(e){return!!super.hasTexture(e)||this.diffuseTexture===e}dispose(e){this._diffuseTexture&&this._diffuseTexture.dispose(),super.dispose(e)}clone(e){return St.Clone((()=>new $G(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SimpleMaterial",e}getClassName(){return"SimpleMaterial"}static Parse(e,t,i){return St.Parse((()=>new $G(e.name,t)),e,t,i)}}Ze([nt("diffuseTexture")],$G.prototype,"_diffuseTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],$G.prototype,"diffuseTexture",void 0),Ze([ot("diffuse")],$G.prototype,"diffuseColor",void 0),Ze([rt("disableLighting")],$G.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],$G.prototype,"disableLighting",void 0),Ze([rt("maxSimultaneousLights")],$G.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],$G.prototype,"maxSimultaneousLights",void 0),z("BABYLON.SimpleMaterial",$G);Bi.ShadersStore.skyPixelShader="precision highp float;varying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\nuniform vec3 cameraPosition;uniform vec3 cameraOffset;uniform vec3 up;uniform float luminance;uniform float turbidity;uniform float rayleigh;uniform float mieCoefficient;uniform float mieDirectionalG;uniform vec3 sunPosition;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\nconst float e=2.71828182845904523536028747135266249775724709369995957;const float pi=3.141592653589793238462643383279502884197169;const float n=1.0003;const float N=2.545E25;const float pn=0.035;const vec3 lambda=vec3(680E-9,550E-9,450E-9);const vec3 K=vec3(0.686,0.678,0.666);const float v=4.0;const float rayleighZenithLength=8.4E3;const float mieZenithLength=1.25E3;const float EE=1000.0;const float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;const float cutoffAngle=pi/1.95;const float steepness=1.5;vec3 totalRayleigh(vec3 lambda)\n{return (8.0*pow(pi,3.0)*pow(pow(n,2.0)-1.0,2.0)*(6.0+3.0*pn))/(3.0*N*pow(lambda,vec3(4.0))*(6.0-7.0*pn));}\nvec3 simplifiedRayleigh()\n{return 0.0005/vec3(94,40,18);}\nfloat rayleighPhase(float cosTheta)\n{ \nreturn (3.0/(16.0*pi))*(1.0+pow(cosTheta,2.0));}\nvec3 totalMie(vec3 lambda,vec3 K,float T)\n{float c=(0.2*T )*10E-18;return 0.434*c*pi*pow((2.0*pi)/lambda,vec3(v-2.0))*K;}\nfloat hgPhase(float cosTheta,float g)\n{return (1.0/(4.0*pi))*((1.0-pow(g,2.0))/pow(1.0-2.0*g*cosTheta+pow(g,2.0),1.5));}\nfloat sunIntensity(float zenithAngleCos)\n{return EE*max(0.0,1.0-exp((-(cutoffAngle-acos(zenithAngleCos))/steepness)));}\nfloat A=0.15;float B=0.50;float C=0.10;float D=0.20;float EEE=0.02;float F=0.30;float W=1000.0;vec3 Uncharted2Tonemap(vec3 x)\n{return ((x*(A*x+C*B)+D*EEE)/(x*(A*x+B)+D*F))-EEE/F;}\n#if DITHER\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n/**\n*--------------------------------------------------------------------------------------------------\n* Sky Color\n*--------------------------------------------------------------------------------------------------\n*/\nfloat sunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);float rayleighCoefficient=rayleigh-(1.0*(1.0-sunfade));vec3 sunDirection=normalize(sunPosition);float sunE=sunIntensity(dot(sunDirection,up));vec3 betaR=simplifiedRayleigh()*rayleighCoefficient;vec3 betaM=totalMie(lambda,K,turbidity)*mieCoefficient;float zenithAngle=acos(max(0.0,dot(up,normalize(vPositionW-cameraPosition+cameraOffset))));float sR=rayleighZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));float sM=mieZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));vec3 Fex=exp(-(betaR*sR+betaM*sM));float cosTheta=dot(normalize(vPositionW-cameraPosition),sunDirection);float rPhase=rayleighPhase(cosTheta*0.5+0.5);vec3 betaRTheta=betaR*rPhase;float mPhase=hgPhase(cosTheta,mieDirectionalG);vec3 betaMTheta=betaM*mPhase;vec3 Lin=pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*(1.0-Fex),vec3(1.5));Lin*=mix(vec3(1.0),pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,sunDirection),5.0),0.0,1.0));vec3 direction=normalize(vPositionW-cameraPosition);float theta=acos(direction.y);float phi=atan(direction.z,direction.x);vec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);vec3 L0=vec3(0.1)*Fex;float sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);L0+=(sunE*19000.0*Fex)*sundisk;vec3 whiteScale=1.0/Uncharted2Tonemap(vec3(W));vec3 texColor=(Lin+L0);texColor*=0.04 ;texColor+=vec3(0.0,0.001,0.0025)*0.3;float g_fMaxLuminance=1.0;float fLumScaled=0.1/luminance; \nfloat fLumCompressed=(fLumScaled*(1.0+(fLumScaled/(g_fMaxLuminance*g_fMaxLuminance))))/(1.0+fLumScaled); \nfloat ExposureBias=fLumCompressed;vec3 curr=Uncharted2Tonemap((log2(2.0/pow(luminance,4.0)))*texColor);vec3 retColor=curr*whiteScale;/**\n*--------------------------------------------------------------------------------------------------\n* Sky Color\n*--------------------------------------------------------------------------------------------------\n*/\nfloat alpha=1.0;\n#ifdef VERTEXCOLOR\nretColor.rgb*=vColor.rgb;\n#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#if DITHER\nretColor.rgb+=dither(gl_FragCoord.xy,0.5);\n#endif\nvec4 color=clamp(vec4(retColor.rgb,alpha),0.0,1.0);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Bi.ShadersStore.skyVertexShader="precision highp float;attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\nuniform mat4 world;uniform mat4 view;uniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\ngl_Position=viewProjection*world*vec4(position,1.0);vec4 worldPos=world*vec4(position,1.0);vPositionW=vec3(worldPos);\n#include\n#include\n#include\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class qG extends xl{constructor(){super(),this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.DITHER=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class ZG extends ml{constructor(e,t){super(e,t),this.luminance=1,this.turbidity=10,this.rayleigh=2,this.mieCoefficient=.005,this.mieDirectionalG=.8,this.distance=500,this.inclination=.49,this.azimuth=.25,this.sunPosition=new _e(0,100,0),this.useSunPosition=!1,this.cameraOffset=_e.Zero(),this.up=_e.Up(),this.dithering=!1,this._cameraPosition=_e.Zero(),this._skyOrientation=new fe}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t){const i=t._drawWrapper;if(this.isFrozen&&i.effect&&i._wasPreviouslyReady)return!0;t.materialDefines||(t.materialDefines=new qG);const s=t.materialDefines,r=this.getScene();if(this._isReadyForSubMesh(t))return!0;if(Go(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,!1,s),jo(e,s,!0,!1),s.IMAGEPROCESSINGPOSTPROCESS!==r.imageProcessingConfiguration.applyByPostProcess&&s.markAsMiscDirty(),s.DITHER!==this.dithering&&s.markAsMiscDirty(),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();const e=new Ll;s.FOG&&e.addFallback(1,"FOG"),s.IMAGEPROCESSINGPOSTPROCESS=r.imageProcessingConfiguration.applyByPostProcess,s.DITHER=this.dithering;const i=[er.PositionKind];s.VERTEXCOLOR&&i.push(er.ColorKind);const n="sky",o=["world","viewProjection","view","vFogInfos","vFogColor","logarithmicDepthConstant","pointSize","luminance","turbidity","rayleigh","mieCoefficient","mieDirectionalG","sunPosition","cameraPosition","cameraOffset","up"];mo(o);const a=s.toString();t.setEffect(r.getEngine().createEffect(n,i,o,[],a,e,this.onCompiled,this.onError),s,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(s._renderId=r.getRenderId(),i._wasPreviouslyReady=!0,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),this._mustRebind(s,n,i)&&(xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s)),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect);const o=s.activeCamera;if(o){const e=o.getWorldMatrix();this._cameraPosition.x=e.m[12],this._cameraPosition.y=e.m[13],this._cameraPosition.z=e.m[14],this._activeEffect.setVector3("cameraPosition",this._cameraPosition)}if(this._activeEffect.setVector3("cameraOffset",this.cameraOffset),this._activeEffect.setVector3("up",this.up),this.luminance>0&&this._activeEffect.setFloat("luminance",this.luminance),this._activeEffect.setFloat("turbidity",this.turbidity),this._activeEffect.setFloat("rayleigh",this.rayleigh),this._activeEffect.setFloat("mieCoefficient",this.mieCoefficient),this._activeEffect.setFloat("mieDirectionalG",this.mieDirectionalG),!this.useSunPosition){const e=Math.PI*(this.inclination-.5),t=2*Math.PI*(this.azimuth-.5);this.sunPosition.x=this.distance*Math.cos(t)*Math.cos(e),this.sunPosition.y=this.distance*Math.sin(-e),this.sunPosition.z=this.distance*Math.sin(t)*Math.cos(e),fe.FromUnitVectorsToRef(_e.UpReadOnly,this.up,this._skyOrientation),this.sunPosition.rotateByQuaternionToRef(this._skyOrientation,this.sunPosition)}this._activeEffect.setVector3("sunPosition",this.sunPosition),this._afterBind(t,this._activeEffect,i)}getAnimatables(){return[]}dispose(e){super.dispose(e)}clone(e){return St.Clone((()=>new ZG(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.SkyMaterial",e}getClassName(){return"SkyMaterial"}static Parse(e,t,i){return St.Parse((()=>new ZG(e.name,t)),e,t,i)}}Ze([rt()],ZG.prototype,"luminance",void 0),Ze([rt()],ZG.prototype,"turbidity",void 0),Ze([rt()],ZG.prototype,"rayleigh",void 0),Ze([rt()],ZG.prototype,"mieCoefficient",void 0),Ze([rt()],ZG.prototype,"mieDirectionalG",void 0),Ze([rt()],ZG.prototype,"distance",void 0),Ze([rt()],ZG.prototype,"inclination",void 0),Ze([rt()],ZG.prototype,"azimuth",void 0),Ze([ht()],ZG.prototype,"sunPosition",void 0),Ze([rt()],ZG.prototype,"useSunPosition",void 0),Ze([ht()],ZG.prototype,"cameraOffset",void 0),Ze([ht()],ZG.prototype,"up",void 0),Ze([rt()],ZG.prototype,"dithering",void 0),z("BABYLON.SkyMaterial",ZG);Bi.ShadersStore.terrainPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform sampler2D textureSampler;uniform vec2 vTextureInfos;uniform sampler2D diffuse1Sampler;uniform sampler2D diffuse2Sampler;uniform sampler2D diffuse3Sampler;uniform vec2 diffuse1Infos;uniform vec2 diffuse2Infos;uniform vec2 diffuse3Infos;\n#endif\n#ifdef BUMP\nuniform sampler2D bump1Sampler;uniform sampler2D bump2Sampler;uniform sampler2D bump3Sampler;\n#endif\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;float invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));return mat3(tangent*invmax,binormal*invmax,normal);}\nvec3 perturbNormal(vec3 viewDir,vec3 mixColor)\n{vec3 bump1Color=texture2D(bump1Sampler,vTextureUV*diffuse1Infos).xyz;vec3 bump2Color=texture2D(bump2Sampler,vTextureUV*diffuse2Infos).xyz;vec3 bump3Color=texture2D(bump3Sampler,vTextureUV*diffuse3Infos).xyz;bump1Color.rgb*=mixColor.r;bump2Color.rgb=mix(bump1Color.rgb,bump2Color.rgb,mixColor.g);vec3 map=mix(bump2Color.rgb,bump3Color.rgb,mixColor.b);map=map*255./127.-128./127.;mat3 TBN=cotangent_frame(vNormalW*vTextureInfos.y,-viewDir,vTextureUV);return normalize(TBN*map);}\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\nfloat alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(textureSampler,vTextureUV);\n#if defined(BUMP) && defined(DIFFUSE)\nnormalW=perturbNormal(viewDirectionW,baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\nbaseColor.rgb*=vTextureInfos.y;vec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);vec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);vec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);diffuse1Color.rgb*=baseColor.r;diffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,baseColor.g);baseColor.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,baseColor.b);\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*baseColor.rgb,0.0,1.0);vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Bi.ShadersStore.terrainVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;uniform mat4 textureMatrix;uniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vTextureInfos.x==0.)\n{vTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));}\nelse\n{vTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class JG extends xl{constructor(){super(),this.DIFFUSE=!1,this.BUMP=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class ez extends ml{constructor(e,t){super(e,t),this.diffuseColor=new Ee(1,1,1),this.specularColor=new Ee(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new JG);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(n.texturesEnabled){if(!this.mixTexture||!this.mixTexture.isReady())return!1;if(r._needUVs=!0,$c.DiffuseTextureEnabled){if(!this.diffuseTexture1||!this.diffuseTexture1.isReady())return!1;if(!this.diffuseTexture2||!this.diffuseTexture2.isReady())return!1;if(!this.diffuseTexture3||!this.diffuseTexture3.isReady())return!1;r.DIFFUSE=!0}if(this.bumpTexture1&&this.bumpTexture2&&this.bumpTexture3&&$c.BumpTextureEnabled){if(!this.bumpTexture1.isReady())return!1;if(!this.bumpTexture2.isReady())return!1;if(!this.bumpTexture3.isReady())return!1;r._needNormals=!0,r.BUMP=!0}}if(Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._needNormals=zo(n,e,r,!1,this._maxSimultaneousLights,this._disableLighting),Ho(n,o,this,r,!!i),jo(e,r,!0,!0),r.isDirty){r.markAsProcessed(),n.resetCachedMaterial();const i=new Ll;r.FOG&&i.addFallback(1,"FOG"),Vo(r,i,this.maxSimultaneousLights),r.NUM_BONE_INFLUENCERS>0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="terrain",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","textureMatrix","diffuse1Infos","diffuse2Infos","diffuse3Infos"],c=["textureSampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","bump1Sampler","bump2Sampler","bump3Sampler","logarithmicDepthConstant"],u=[];mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.mixTexture&&(this._activeEffect.setTexture("textureSampler",this._mixTexture),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture.coordinatesIndex,this._mixTexture.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture.getTextureMatrix()),$c.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale))),$c.BumpTextureEnabled&&s.getEngine().getCaps().standardDerivatives&&(this._bumpTexture1&&this._activeEffect.setTexture("bump1Sampler",this._bumpTexture1),this._bumpTexture2&&this._activeEffect.setTexture("bump2Sampler",this._bumpTexture2),this._bumpTexture3&&this._activeEffect.setTexture("bump3Sampler",this._bumpTexture3))),xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._mixTexture&&e.push(this._mixTexture),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._bumpTexture1&&e.push(this._bumpTexture1),this._bumpTexture2&&e.push(this._bumpTexture2),this._bumpTexture3&&e.push(this._bumpTexture3),e}hasTexture(e){return!!super.hasTexture(e)||this._mixTexture===e||this._diffuseTexture1===e||this._diffuseTexture2===e||this._diffuseTexture3===e||this._bumpTexture1===e||this._bumpTexture2===e||this._bumpTexture3===e}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return St.Clone((()=>new ez(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TerrainMaterial",e}getClassName(){return"TerrainMaterial"}static Parse(e,t,i){return St.Parse((()=>new ez(e.name,t)),e,t,i)}}Ze([nt("mixTexture")],ez.prototype,"_mixTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],ez.prototype,"mixTexture",void 0),Ze([nt("diffuseTexture1")],ez.prototype,"_diffuseTexture1",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],ez.prototype,"diffuseTexture1",void 0),Ze([nt("diffuseTexture2")],ez.prototype,"_diffuseTexture2",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],ez.prototype,"diffuseTexture2",void 0),Ze([nt("diffuseTexture3")],ez.prototype,"_diffuseTexture3",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],ez.prototype,"diffuseTexture3",void 0),Ze([nt("bumpTexture1")],ez.prototype,"_bumpTexture1",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],ez.prototype,"bumpTexture1",void 0),Ze([nt("bumpTexture2")],ez.prototype,"_bumpTexture2",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],ez.prototype,"bumpTexture2",void 0),Ze([nt("bumpTexture3")],ez.prototype,"_bumpTexture3",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],ez.prototype,"bumpTexture3",void 0),Ze([ot()],ez.prototype,"diffuseColor",void 0),Ze([ot()],ez.prototype,"specularColor",void 0),Ze([rt()],ez.prototype,"specularPower",void 0),Ze([rt("disableLighting")],ez.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],ez.prototype,"disableLighting",void 0),Ze([rt("maxSimultaneousLights")],ez.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],ez.prototype,"maxSimultaneousLights",void 0),z("BABYLON.TerrainMaterial",ez);Bi.ShadersStore.triplanarPixelShader="precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;uniform sampler2D diffuseSamplerX;\n#ifdef BUMPX\nuniform sampler2D normalSamplerX;\n#endif\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;uniform sampler2D diffuseSamplerY;\n#ifdef BUMPY\nuniform sampler2D normalSamplerY;\n#endif\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;uniform sampler2D diffuseSamplerZ;\n#ifdef BUMPZ\nuniform sampler2D normalSamplerZ;\n#endif\n#endif\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(0.,0.,0.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef NORMAL\nvec3 normalW=tangentSpace[2];\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec4 baseNormal=vec4(0.0,0.0,0.0,1.0);normalW*=normalW;\n#ifdef DIFFUSEX\nbaseColor+=texture2D(diffuseSamplerX,vTextureUVX)*normalW.x;\n#ifdef BUMPX\nbaseNormal+=texture2D(normalSamplerX,vTextureUVX)*normalW.x;\n#endif\n#endif\n#ifdef DIFFUSEY\nbaseColor+=texture2D(diffuseSamplerY,vTextureUVY)*normalW.y;\n#ifdef BUMPY\nbaseNormal+=texture2D(normalSamplerY,vTextureUVY)*normalW.y;\n#endif\n#endif\n#ifdef DIFFUSEZ\nbaseColor+=texture2D(diffuseSamplerZ,vTextureUVZ)*normalW.z;\n#ifdef BUMPZ\nbaseNormal+=texture2D(normalSamplerZ,vTextureUVZ)*normalW.z;\n#endif\n#endif\n#ifdef NORMAL\nnormalW=normalize((2.0*baseNormal.xyz-1.0)*tangentSpace);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;vec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Bi.ShadersStore.triplanarVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\n#endif\nuniform float tileSize;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);gl_Position=viewProjection*worldPos;vPositionW=vec3(worldPos);\n#ifdef DIFFUSEX\nvTextureUVX=worldPos.zy/tileSize;\n#endif\n#ifdef DIFFUSEY\nvTextureUVY=worldPos.xz/tileSize;\n#endif\n#ifdef DIFFUSEZ\nvTextureUVZ=worldPos.xy/tileSize;\n#endif\n#ifdef NORMAL\nvec3 xtan=vec3(0,0,1);vec3 xbin=vec3(0,1,0);vec3 ytan=vec3(1,0,0);vec3 ybin=vec3(0,0,1);vec3 ztan=vec3(1,0,0);vec3 zbin=vec3(0,1,0);vec3 normalizedNormal=normalize(normal);normalizedNormal*=normalizedNormal;vec3 worldBinormal=normalize(xbin*normalizedNormal.x+ybin*normalizedNormal.y+zbin*normalizedNormal.z);vec3 worldTangent=normalize(xtan*normalizedNormal.x+ytan*normalizedNormal.y+ztan*normalizedNormal.z);mat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nworldTangent=normalize((normalWorld*worldTangent).xyz);worldBinormal=normalize((normalWorld*worldBinormal).xyz);vec3 worldNormal=normalize((normalWorld*normalize(normal)).xyz);tangentSpace[0]=worldTangent;tangentSpace[1]=worldBinormal;tangentSpace[2]=worldNormal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class tz extends xl{constructor(){super(),this.DIFFUSEX=!1,this.DIFFUSEY=!1,this.DIFFUSEZ=!1,this.BUMPX=!1,this.BUMPY=!1,this.BUMPZ=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.NORMAL=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.NONUNIFORMSCALING=!1,this.LOGARITHMICDEPTH=!1,this.rebuild()}}class iz extends ml{constructor(e,t){super(e,t),this.tileSize=1,this.diffuseColor=new Ee(1,1,1),this.specularColor=new Ee(.2,.2,.2),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new tz);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&n.texturesEnabled){if($c.DiffuseTextureEnabled){const e=[this.diffuseTextureX,this.diffuseTextureY,this.diffuseTextureZ],t=["DIFFUSEX","DIFFUSEY","DIFFUSEZ"];for(let i=0;i0&&i.addCPUSkinningFallback(0,e),r.IMAGEPROCESSINGPOSTPROCESS=n.imageProcessingConfiguration.applyByPostProcess;const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="triplanar",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","mBones","tileSize"],c=["diffuseSamplerX","diffuseSamplerY","diffuseSamplerZ","normalSamplerX","normalSamplerY","normalSamplerZ","logarithmicDepthConstant"],u=[];mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;n&&(this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._activeEffect.setFloat("tileSize",this.tileSize),this._mustRebind(s,n,i)&&(this.diffuseTextureX&&this._activeEffect.setTexture("diffuseSamplerX",this.diffuseTextureX),this.diffuseTextureY&&this._activeEffect.setTexture("diffuseSamplerY",this.diffuseTextureY),this.diffuseTextureZ&&this._activeEffect.setTexture("diffuseSamplerZ",this.diffuseTextureZ),this.normalTextureX&&this._activeEffect.setTexture("normalSamplerX",this.normalTextureX),this.normalTextureY&&this._activeEffect.setTexture("normalSamplerY",this.normalTextureY),this.normalTextureZ&&this._activeEffect.setTexture("normalSamplerZ",this.normalTextureZ),xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),this._afterBind(t,this._activeEffect,i))}getAnimatables(){const e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTextureX&&e.push(this._diffuseTextureX),this._diffuseTextureY&&e.push(this._diffuseTextureY),this._diffuseTextureZ&&e.push(this._diffuseTextureZ),this._normalTextureX&&e.push(this._normalTextureX),this._normalTextureY&&e.push(this._normalTextureY),this._normalTextureZ&&e.push(this._normalTextureZ),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTextureX===e||this._diffuseTextureY===e||this._diffuseTextureZ===e||this._normalTextureX===e||this._normalTextureY===e||this._normalTextureZ===e}dispose(e){this.mixTexture&&this.mixTexture.dispose(),super.dispose(e)}clone(e){return St.Clone((()=>new iz(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.TriPlanarMaterial",e}getClassName(){return"TriPlanarMaterial"}static Parse(e,t,i){return St.Parse((()=>new iz(e.name,t)),e,t,i)}}Ze([nt()],iz.prototype,"mixTexture",void 0),Ze([nt("diffuseTextureX")],iz.prototype,"_diffuseTextureX",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],iz.prototype,"diffuseTextureX",void 0),Ze([nt("diffuseTexturY")],iz.prototype,"_diffuseTextureY",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],iz.prototype,"diffuseTextureY",void 0),Ze([nt("diffuseTextureZ")],iz.prototype,"_diffuseTextureZ",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],iz.prototype,"diffuseTextureZ",void 0),Ze([nt("normalTextureX")],iz.prototype,"_normalTextureX",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],iz.prototype,"normalTextureX",void 0),Ze([nt("normalTextureY")],iz.prototype,"_normalTextureY",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],iz.prototype,"normalTextureY",void 0),Ze([nt("normalTextureZ")],iz.prototype,"_normalTextureZ",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],iz.prototype,"normalTextureZ",void 0),Ze([rt()],iz.prototype,"tileSize",void 0),Ze([ot()],iz.prototype,"diffuseColor",void 0),Ze([ot()],iz.prototype,"specularColor",void 0),Ze([rt()],iz.prototype,"specularPower",void 0),Ze([rt("disableLighting")],iz.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],iz.prototype,"disableLighting",void 0),Ze([rt("maxSimultaneousLights")],iz.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],iz.prototype,"maxSimultaneousLights",void 0),z("BABYLON.TriPlanarMaterial",iz);Bi.ShadersStore.waterPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform sampler2D normalSampler;uniform vec2 vNormalInfos;\n#endif\nuniform sampler2D refractionSampler;uniform sampler2D reflectionSampler;const float LOG2=1.442695;uniform vec3 cameraPosition;uniform vec4 waterColor;uniform float colorBlendFactor;uniform vec4 waterColor2;uniform float colorBlendFactor2;uniform float bumpHeight;uniform float time;varying vec3 vRefractionMapTexCoord;varying vec3 vReflectionMapTexCoord;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a;\n#ifdef BUMP\n#ifdef BUMPSUPERIMPOSE\nbaseColor=0.6*texture2D(normalSampler,vNormalUV)+0.4*texture2D(normalSampler,vec2(vNormalUV2.x,vNormalUV2.y));\n#else\nbaseColor=texture2D(normalSampler,vNormalUV);\n#endif\nvec3 bumpColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vNormalInfos.y;\n#else\nvec3 bumpColor=vec3(1.0);\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef NORMAL\nvec2 perturbation=bumpHeight*(baseColor.rg-0.5);\n#ifdef BUMPAFFECTSREFLECTION\nvec3 normalW=normalize(vNormalW+vec3(perturbation.x*8.0,0.0,perturbation.y*8.0));if (normalW.y<0.0) {normalW.y=-normalW.y;}\n#else\nvec3 normalW=normalize(vNormalW);\n#endif\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);vec2 perturbation=bumpHeight*(vec2(1.0,1.0)-0.5);\n#endif\n#ifdef FRESNELSEPARATE\n#ifdef REFLECTION\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation*0.5,0.0,1.0);vec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vec2(\nvReflectionMapTexCoord.x/vReflectionMapTexCoord.z+perturbation.x*0.3,\nvReflectionMapTexCoord.y/vReflectionMapTexCoord.z+perturbation.y\n),0.0,1.0);vec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);float fresnelTerm=clamp(abs(pow(dot(viewDirectionW,upVector),3.0)),0.05,0.65);float IfresnelTerm=1.0-fresnelTerm;refractiveColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*refractiveColor;reflectiveColor=IfresnelTerm*colorBlendFactor2*waterColor+(1.0-colorBlendFactor2*IfresnelTerm)*reflectiveColor;vec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*IfresnelTerm;baseColor=combinedColor;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#else \n#ifdef REFLECTION\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation,0.0,1.0);vec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\n#ifdef IS_REFRACTION_LINEAR\nrefractiveColor.rgb=toGammaSpace(refractiveColor.rgb);\n#endif\nvec2 projectedReflectionTexCoords=clamp(vReflectionMapTexCoord.xy/vReflectionMapTexCoord.z+perturbation,0.0,1.0);vec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\n#ifdef IS_REFLECTION_LINEAR\nreflectiveColor.rgb=toGammaSpace(reflectiveColor.rgb);\n#endif\nvec3 upVector=vec3(0.0,1.0,0.0);float fresnelTerm=max(dot(viewDirectionW,upVector),0.0);vec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*(1.0-fresnelTerm);baseColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*combinedColor;\n#endif\nvec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info;float shadow=1.;float aggShadow=0.;float numLights=0.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;vec3 specularBase=vec3(0.,0.,0.);vec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#endif\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#elif defined(IMAGEPROCESSING)\ncolor.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Bi.ShadersStore.waterVertexShader="precision highp float;attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\nuniform mat4 view;uniform mat4 viewProjection;\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform mat4 normalMatrix;uniform vec2 vNormalInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\nuniform mat4 reflectionViewProjection;uniform vec2 windDirection;uniform float waveLength;uniform float time;uniform float windForce;uniform float waveHeight;uniform float waveSpeed;uniform float waveCount;varying vec3 vRefractionMapTexCoord;varying vec3 vReflectionMapTexCoord;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef BUMP\nif (vNormalInfos.x==0.)\n{vNormalUV=vec2(normalMatrix*vec4((uv*1.0)/waveLength+time*windForce*windDirection,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv*0.721)/waveLength+time*1.2*windForce*windDirection,1.0,0.0));\n#endif\n}\nelse\n{vNormalUV=vec2(normalMatrix*vec4((uv2*1.0)/waveLength+time*windForce*windDirection ,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv2*0.721)/waveLength+time*1.2*windForce*windDirection ,1.0,0.0));\n#endif\n}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\nfloat finalWaveCount=1.0/(waveCount*0.5);\n#ifdef USE_WORLD_COORDINATES\nvec3 p=worldPos.xyz;\n#else\nvec3 p=position;\n#endif\nfloat newY=(sin(((p.x/finalWaveCount)+time*waveSpeed))*waveHeight*windDirection.x*5.0)\n+ (cos(((p.z/finalWaveCount)+ time*waveSpeed))*waveHeight*windDirection.y*5.0);p.y+=abs(newY);\n#ifdef USE_WORLD_COORDINATES\ngl_Position=viewProjection*vec4(p,1.0);\n#else\ngl_Position=viewProjection*finalWorld*vec4(p,1.0);\n#endif\n#ifdef REFLECTION\nvRefractionMapTexCoord.x=0.5*(gl_Position.w+gl_Position.x);vRefractionMapTexCoord.y=0.5*(gl_Position.w+gl_Position.y);vRefractionMapTexCoord.z=gl_Position.w;worldPos=reflectionViewProjection*finalWorld*vec4(position,1.0);vReflectionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);vReflectionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);vReflectionMapTexCoord.z=worldPos.w;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class sz extends xl{constructor(){super(),this.BUMP=!1,this.REFLECTION=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.SPECULARTERM=!1,this.LOGARITHMICDEPTH=!1,this.USE_REVERSE_DEPTHBUFFER=!1,this.FRESNELSEPARATE=!1,this.BUMPSUPERIMPOSE=!1,this.BUMPAFFECTSREFLECTION=!1,this.USE_WORLD_COORDINATES=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class rz extends ml{get hasRenderTargetTextures(){return!0}constructor(e,t,i=new de(512,512)){super(e,t),this.renderTargetSize=i,this.diffuseColor=new Ee(1,1,1),this.specularColor=new Ee(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4,this.windForce=6,this.windDirection=new de(0,1),this.waveHeight=.4,this.bumpHeight=.4,this._bumpSuperimpose=!1,this._fresnelSeparate=!1,this._bumpAffectsReflection=!1,this.waterColor=new Ee(.1,.1,.6),this.colorBlendFactor=.2,this.waterColor2=new Ee(.1,.1,.6),this.colorBlendFactor2=.2,this.waveLength=.1,this.waveSpeed=1,this.waveCount=20,this.disableClipPlane=!1,this._useWorldCoordinatesForWaveDeformation=!1,this._renderTargets=new Fs(16),this._mesh=null,this._reflectionTransform=me.Zero(),this._lastTime=0,this._lastDeltaTime=0,this._createRenderTargets(this.getScene(),i),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._renderTargets.push(this._reflectionRTT),this._renderTargets.push(this._refractionRTT),this._renderTargets),this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get refractionTexture(){return this._refractionRTT}get reflectionTexture(){return this._reflectionRTT}addToRenderList(e){this._refractionRTT&&this._refractionRTT.renderList&&this._refractionRTT.renderList.push(e),this._reflectionRTT&&this._reflectionRTT.renderList&&this._reflectionRTT.renderList.push(e)}removeFromRenderList(e){if(this._refractionRTT&&this._refractionRTT.renderList){const t=this._refractionRTT.renderList.indexOf(e);-1!==t&&this._refractionRTT.renderList.splice(t,1)}if(this._reflectionRTT&&this._reflectionRTT.renderList){const t=this._reflectionRTT.renderList.indexOf(e);-1!==t&&this._reflectionRTT.renderList.splice(t,1)}}enableRenderTargets(e){const t=e?1:0;this._refractionRTT&&(this._refractionRTT.refreshRate=t),this._reflectionRTT&&(this._reflectionRTT.refreshRate=t)}getRenderList(){return this._refractionRTT?this._refractionRTT.renderList:[]}get renderTargetsEnabled(){return!(this._refractionRTT&&0===this._refractionRTT.refreshRate)}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new sz);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled)){if(this.bumpTexture&&$c.BumpTextureEnabled){if(!this.bumpTexture.isReady())return!1;r._needUVs=!0,r.BUMP=!0}$c.ReflectionTextureEnabled&&(r.REFLECTION=!0)}if(Ho(n,o,this,r,!!i),Go(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._areMiscDirty&&(r.FRESNELSEPARATE=this._fresnelSeparate,r.BUMPSUPERIMPOSE=this._bumpSuperimpose,r.BUMPAFFECTSREFLECTION=this._bumpAffectsReflection,r.USE_WORLD_COORDINATES=this._useWorldCoordinatesForWaveDeformation),r._needNormals=zo(n,e,r,!0,this._maxSimultaneousLights,this._disableLighting),r._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(r),r.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,r.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}if(jo(e,r,!0,!0),this._mesh=e,this._waitingRenderList){for(let e=0;e0&&i.addCPUSkinningFallback(0,e);const s=[er.PositionKind];r.NORMAL&&s.push(er.NormalKind),r.UV1&&s.push(er.UVKind),r.UV2&&s.push(er.UV2Kind),r.VERTEXCOLOR&&s.push(er.ColorKind),Bo(s,e,r,i),ko(s,r);const a="water",l=r.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vNormalInfos","mBones","normalMatrix","logarithmicDepthConstant","reflectionViewProjection","windDirection","waveLength","time","windForce","cameraPosition","bumpHeight","waveHeight","waterColor","waterColor2","colorBlendFactor","colorBlendFactor2","waveSpeed","waveCount"],c=["normalSampler","refractionSampler","reflectionSampler"],u=[];zs&&(zs.PrepareUniforms(h,r),zs.PrepareSamplers(c,r)),mo(h),ea({uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(a,{attributes:s,uniformsNames:h,uniformBuffersNames:u,samplers:c,defines:l,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o),r,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,0))}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n||!this._mesh)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),wo(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.bumpTexture&&$c.BumpTextureEnabled&&(this._activeEffect.setTexture("normalSampler",this.bumpTexture),this._activeEffect.setFloat2("vNormalInfos",this.bumpTexture.coordinatesIndex,this.bumpTexture.level),this._activeEffect.setMatrix("normalMatrix",this.bumpTexture.getTextureMatrix())),xo(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&So(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Lo(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==Hr.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Co(s,t,this._activeEffect),So(r,this._activeEffect,s),$c.ReflectionTextureEnabled&&(this._activeEffect.setTexture("refractionSampler",this._refractionRTT),this._activeEffect.setTexture("reflectionSampler",this._reflectionRTT));const o=this._reflectionTransform.multiply(s.getProjectionMatrix()),a=s.getEngine().getDeltaTime();a!==this._lastDeltaTime&&(this._lastDeltaTime=a,this._lastTime+=this._lastDeltaTime),this._activeEffect.setMatrix("reflectionViewProjection",o),this._activeEffect.setVector2("windDirection",this.windDirection),this._activeEffect.setFloat("waveLength",this.waveLength),this._activeEffect.setFloat("time",this._lastTime/1e5),this._activeEffect.setFloat("windForce",this.windForce),this._activeEffect.setFloat("waveHeight",this.waveHeight),this._activeEffect.setFloat("bumpHeight",this.bumpHeight),this._activeEffect.setColor4("waterColor",this.waterColor,1),this._activeEffect.setFloat("colorBlendFactor",this.colorBlendFactor),this._activeEffect.setColor4("waterColor2",this.waterColor2,1),this._activeEffect.setFloat("colorBlendFactor2",this.colorBlendFactor2),this._activeEffect.setFloat("waveSpeed",this.waveSpeed),this._activeEffect.setFloat("waveCount",this.waveCount),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect),this._afterBind(t,this._activeEffect,i)}_createRenderTargets(e,t){this._refractionRTT=new ih(name+"_refraction",{width:t.x,height:t.y},e,!1,!0),this._refractionRTT.wrapU=N_.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.wrapV=N_.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.ignoreCameraViewport=!0;let i,s=!1;this._refractionRTT.onBeforeRenderObservable.add((()=>{s=e.getBoundingBoxRenderer().enabled,e.getBoundingBoxRenderer().enabled=!1})),this._refractionRTT.onAfterRenderObservable.add((()=>{e.getBoundingBoxRenderer().enabled=s})),this._reflectionRTT=new ih(name+"_reflection",{width:t.x,height:t.y},e,!1,!0),this._reflectionRTT.wrapU=N_.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.wrapV=N_.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.ignoreCameraViewport=!0;let r,n=null;const o=me.Zero();this._refractionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){n=e.clipPlane;const t=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=Nr.FromPositionAndNormal(new _e(0,t+.05,0),new _e(0,1,0))}},this._refractionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),this.disableClipPlane||(e.clipPlane=n)},this._reflectionRTT.onBeforeRender=()=>{if(this._mesh&&(i=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){n=e.clipPlane;const t=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=Nr.FromPositionAndNormal(new _e(0,t-.05,0),new _e(0,-1,0)),me.ReflectionToRef(e.clipPlane,o)}r=e.getViewMatrix(),o.multiplyToRef(r,this._reflectionTransform),e.setTransformMatrix(this._reflectionTransform,e.getProjectionMatrix()),e._mirroredCameraPosition=_e.TransformCoordinates(e.activeCamera.position,o)},this._reflectionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=i),e.clipPlane=n,e.setTransformMatrix(r,e.getProjectionMatrix()),e._mirroredCameraPosition=null}}getAnimatables(){const e=[];return this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this._reflectionRTT&&this._reflectionRTT.animations&&this._reflectionRTT.animations.length>0&&e.push(this._reflectionRTT),this._refractionRTT&&this._refractionRTT.animations&&this._refractionRTT.animations.length>0&&e.push(this._refractionRTT),e}getActiveTextures(){const e=super.getActiveTextures();return this._bumpTexture&&e.push(this._bumpTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._bumpTexture===e}dispose(e){this.bumpTexture&&this.bumpTexture.dispose();let t=this.getScene().customRenderTargets.indexOf(this._refractionRTT);-1!=t&&this.getScene().customRenderTargets.splice(t,1),t=-1,t=this.getScene().customRenderTargets.indexOf(this._reflectionRTT),-1!=t&&this.getScene().customRenderTargets.splice(t,1),this._reflectionRTT&&this._reflectionRTT.dispose(),this._refractionRTT&&this._refractionRTT.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return St.Clone((()=>new rz(e,this.getScene())),this)}serialize(){const e=super.serialize();if(e.customType="BABYLON.WaterMaterial",e.renderList=[],this._refractionRTT&&this._refractionRTT.renderList)for(let t=0;tnew rz(e.name,t)),e,t,i);return s._waitingRenderList=e.renderList,s}static CreateDefaultMesh(e,t){return Iu(e,{width:512,height:512,subdivisions:32,updatable:!1},t)}}Ze([nt("bumpTexture")],rz.prototype,"_bumpTexture",void 0),Ze([st("_markAllSubMeshesAsTexturesDirty")],rz.prototype,"bumpTexture",void 0),Ze([ot()],rz.prototype,"diffuseColor",void 0),Ze([ot()],rz.prototype,"specularColor",void 0),Ze([rt()],rz.prototype,"specularPower",void 0),Ze([rt("disableLighting")],rz.prototype,"_disableLighting",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],rz.prototype,"disableLighting",void 0),Ze([rt("maxSimultaneousLights")],rz.prototype,"_maxSimultaneousLights",void 0),Ze([st("_markAllSubMeshesAsLightsDirty")],rz.prototype,"maxSimultaneousLights",void 0),Ze([rt()],rz.prototype,"windForce",void 0),Ze([lt()],rz.prototype,"windDirection",void 0),Ze([rt()],rz.prototype,"waveHeight",void 0),Ze([rt()],rz.prototype,"bumpHeight",void 0),Ze([rt("bumpSuperimpose")],rz.prototype,"_bumpSuperimpose",void 0),Ze([st("_markAllSubMeshesAsMiscDirty")],rz.prototype,"bumpSuperimpose",void 0),Ze([rt("fresnelSeparate")],rz.prototype,"_fresnelSeparate",void 0),Ze([st("_markAllSubMeshesAsMiscDirty")],rz.prototype,"fresnelSeparate",void 0),Ze([rt("bumpAffectsReflection")],rz.prototype,"_bumpAffectsReflection",void 0),Ze([st("_markAllSubMeshesAsMiscDirty")],rz.prototype,"bumpAffectsReflection",void 0),Ze([ot()],rz.prototype,"waterColor",void 0),Ze([rt()],rz.prototype,"colorBlendFactor",void 0),Ze([ot()],rz.prototype,"waterColor2",void 0),Ze([rt()],rz.prototype,"colorBlendFactor2",void 0),Ze([rt()],rz.prototype,"waveLength",void 0),Ze([rt()],rz.prototype,"waveSpeed",void 0),Ze([rt()],rz.prototype,"waveCount",void 0),Ze([rt()],rz.prototype,"disableClipPlane",void 0),Ze([rt("useWorldCoordinatesForWaveDeformation")],rz.prototype,"_useWorldCoordinatesForWaveDeformation",void 0),Ze([st("_markAllSubMeshesAsMiscDirty")],rz.prototype,"useWorldCoordinatesForWaveDeformation",void 0),z("BABYLON.WaterMaterial",rz);var nz,oz=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class az{constructor(e,t,i,s,r,n,o,a,l,h){this.point=e,this.line=t,this.polyline=i,this.node=s,this.verbCurve=r,this.verbSurface=n,this.jscad=o,this.occt=a,this.tag=l,this.context=h,this.defaultBasicOptions=new mU.DrawBasicGeometryOptions,this.defaultNodeOptions={colorX:"#ff0000",colorY:"#00ff00",colorZ:"#0000ff",size:2}}drawAnyAsyncNoReturn(e){return oz(this,void 0,void 0,(function*(){this.drawAnyAsync(e)}))}drawAnyAsync(e){return oz(this,void 0,void 0,(function*(){const t=e.entity;return void 0===t||Array.isArray(t)&&0===t.length?Promise.resolve(void 0):this.detectJscadMesh(t)?this.handleJscadMesh(e):this.detectOcctShape(t)?this.handleOcctShape(e):this.detectOcctShapes(t)?this.handleOcctShapes(e):this.detectJscadMeshes(t)?this.handleJscadMeshes(e):Promise.resolve(this.drawAny(e))}))}updateAny(e){let t;if(e.babylonMesh&&e.babylonMesh.metadata)switch(e.babylonMesh.metadata.type){case mU.drawingTypes.point:t=this.handlePoint(e);break;case mU.drawingTypes.points:t=this.handlePoints(e);break;case mU.drawingTypes.line:t=this.handleLine(e);break;case mU.drawingTypes.lines:t=this.handleLines(e);break;case mU.drawingTypes.polyline:t=this.handlePolyline(e);break;case mU.drawingTypes.polylines:t=this.handlePolylines(e);break;case mU.drawingTypes.verbCurve:t=this.handleVerbCurve(e);break;case mU.drawingTypes.verbCurves:t=this.handleVerbCurves(e);break;case mU.drawingTypes.verbSurface:t=this.handleVerbSurface(e);break;case mU.drawingTypes.verbSurfaces:t=this.handleVerbSurfaces(e);break;case mU.drawingTypes.tag:t=this.handleTag(e);break;case mU.drawingTypes.tags:t=this.handleTags(e);break;case mU.drawingTypes.node:t=this.handleNode(e);break;case mU.drawingTypes.nodes:t=this.handleNodes(e)}return t}drawAnyNoReturn(e){this.drawAny(e)}drawAny(e){let t;const i=e.entity;return e.babylonMesh?t=this.updateAny(e):this.detectLine(i)?t=this.handleLine(e):this.detectPoint(i)?t=this.handlePoint(e):this.detectPolyline(i)?t=this.handlePolyline(e):this.detectNode(i)?t=this.handleNode(e):this.detectVerbCurve(i)?t=this.handleVerbCurve(e):this.detectVerbSurface(i)?t=this.handleVerbSurface(e):this.detectPolylines(i)?t=this.handlePolylines(e):this.detectLines(i)?t=this.handleLines(e):this.detectPoints(i)?t=this.handlePoints(e):this.detectNodes(i)?t=this.handleNodes(e):this.detectVerbCurves(i)?t=this.handleVerbCurves(e):this.detectVerbSurfaces(i)?t=this.handleVerbSurfaces(e):this.detectTag(i)?t=this.handleTag(e):this.detectTags(i)&&(t=this.handleTags(e)),t}drawGridMeshNoReturn(e){this.drawGridMesh(e)}drawGridMesh(e){try{const t=new UG(`groundMaterial${Math.random()}`,this.context.scene);t.majorUnitFrequency=e.majorUnitFrequency,t.minorUnitVisibility=e.minorUnitVisibility,t.gridRatio=e.gridRatio,t.backFaceCulling=e.backFaceCulling,t.mainColor=Ee.FromHexString(e.mainColor),t.lineColor=Ee.FromHexString(e.secondaryColor),t.opacity=e.opacity;const i=R_.CreateGround(`bitbybit-ground${Math.random()}`,{width:e.width,height:e.height,subdivisions:e.subdivisions,updatable:!1},this.context.scene);return i.material=t,i}catch(e){return console.log("Error happened: ",e),new ha("error-ground",this.context.scene)}}optionsSimple(e){return e}optionsOcctShape(e){return e}optionsOcctShapeSimple(e){return e}optionsOcctShapeMaterial(e){return e}optionsBabylonNode(e){return e}handleTags(e){const t=e.options?e.options:{updatable:!1},i=this.tag.drawTags(Object.assign({tagsVariable:e.babylonMesh,tags:e.entity},t));return i.metadata={type:mU.drawingTypes.tags,options:t},i}handleTag(e){let t=e.options?e.options:{updatable:!1};!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.tag.drawTag(Object.assign({tagVariable:e.babylonMesh,tag:e.entity},t));return i.metadata={type:mU.drawingTypes.tag,options:t},i}handleVerbSurfaces(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbSurface.drawSurfacesMultiColour(Object.assign({surfacesMesh:e.babylonMesh,surfaces:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.verbSurfaces,t,i),i}handleVerbCurves(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbCurve.drawCurves(Object.assign({curvesMesh:e.babylonMesh,curves:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.verbCurves,t,i),i}handleNodes(e){let t=e.options?e.options:this.defaultNodeOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity;return this.node.drawNodes(Object.assign({nodes:e.entity},t)),this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.nodes,t,i),i}handlePoints(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.point.drawPoints(Object.assign({pointsMesh:e.babylonMesh,points:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.points,t,i),i}handleLines(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolylines(Object.assign({polylinesMesh:e.babylonMesh,polylines:e.entity.map((e=>({points:[e.start,e.end]})))},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.lines,t,i),i}handlePolylines(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolylines(Object.assign({polylinesMesh:e.babylonMesh,polylines:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.polylines,t,i),i}handleVerbSurface(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbSurface.drawSurface(Object.assign({surfaceMesh:e.babylonMesh,surface:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.verbSurface,t,i),i}handleVerbCurve(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.verbCurve.drawCurve(Object.assign({curveMesh:e.babylonMesh,curve:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.verbCurve,t,i),i}handleNode(e){let t=e.options?e.options:this.defaultNodeOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=e.entity;return this.node.drawNode(Object.assign({node:e.entity},t)),this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.node,t,i),i}handlePolyline(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolyline(Object.assign({polylineMesh:e.babylonMesh,polyline:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.polyline,t,i),i}handlePoint(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.point.drawPoint(Object.assign({pointMesh:e.babylonMesh,point:e.entity},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.point,t,i),i}handleLine(e){let t=e.options?e.options:this.defaultBasicOptions;!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options);const i=this.polyline.drawPolylines(Object.assign({polylinesMesh:e.babylonMesh,polylines:[{points:[e.entity.start,e.entity.end]}]},t));return this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.line,t,i),i}handleJscadMeshes(e){let t=e.options?e.options:this.defaultBasicOptions;return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.jscad.drawSolidOrPolygonMeshes(Object.assign({jscadMesh:e.babylonMesh,meshes:e.entity},t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.jscadMeshes,t,e),e)))}handleOcctShape(e){let t=e.options?e.options:new Jk.DrawShapeDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.occt.drawShape(Object.assign(Object.assign({shape:e.entity},new mU.DrawOcctShapeOptions),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.occt,t,e),e)))}handleOcctShapes(e){let t=e.options?e.options:new Jk.DrawShapeDto(e.entity);return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.occt.drawShapes(Object.assign(Object.assign({shapes:e.entity},new mU.DrawOcctShapeOptions),t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.occt,t,e),e)))}handleJscadMesh(e){let t=e.options?e.options:this.defaultBasicOptions;return!e.options&&e.babylonMesh&&e.babylonMesh.metadata.options&&(t=e.babylonMesh.metadata.options),this.jscad.drawSolidOrPolygonMesh(Object.assign({jscadMesh:e.babylonMesh,mesh:e.entity},t)).then((e=>(this.applyGlobalSettingsAndMetadataAndShadowCasting(mU.drawingTypes.jscadMesh,t,e),e)))}applyGlobalSettingsAndMetadataAndShadowCasting(e,t,i){const s={type:e,options:t},r=this.context.scene.metadata.shadowGenerators;i.isPickable=!1,i.getChildMeshes().forEach((e=>{e.isPickable=!1})),r.length>0&&(i.receiveShadows=!0,r.forEach((e=>e.addShadowCaster(i))),i.getChildMeshes().forEach((e=>{e.receiveShadows=!0,r.forEach((t=>t.addShadowCaster(e)))}))),i.metadata=i.metadata?Object.assign(Object.assign({},i.metadata),s):s}detectPoint(e){return Array.isArray(e)&&3===e.length&&this.checkIfElementsInArrayAreNumbers(e)}detectPoints(e){return Array.isArray(e)&&this.checkIfElementsInArrayAreArrays(e)&&this.arraysInChildrenArraysContainNumbers(e)&&this.arraysInChildrenArraysAreOfLength3(e)}detectLine(e){return e.start&&e.end&&Array.isArray(e.start)&&Array.isArray(e.end)}detectLines(e){return Array.isArray(e)&&!e.some((e=>!this.detectLine(e)))}detectPolyline(e){return e.points&&Array.isArray(e.points)}detectPolylines(e){return Array.isArray(e)&&!e.some((e=>!this.detectPolyline(e)))}detectNode(e){return!Array.isArray(e)&&e.id&&e.id.includes("node")}detectNodes(e){return Array.isArray(e)&&!e.some((e=>!this.detectNode(e)))}detectVerbCurve(e){return!Array.isArray(e)&&e._data&&e._data.controlPoints&&e._data.knots&&e._data.degree}detectVerbSurface(e){return!Array.isArray(e)&&e._data&&e._data.controlPoints&&e._data.degreeU&&e._data.degreeV&&e._data.knotsU&&e._data.knotsV}detectVerbCurves(e){return Array.isArray(e)&&!e.some((e=>!this.detectVerbCurve(e)))}detectVerbSurfaces(e){return Array.isArray(e)&&!e.some((e=>!this.detectVerbSurface(e)))}detectJscadMesh(e){return!Array.isArray(e)&&(e.sides||e.polygons)}detectJscadMeshes(e){return Array.isArray(e)&&!e.some((e=>!this.detectJscadMesh(e)))}detectOcctShape(e){return"occ-shape"===(null==e?void 0:e.type)}detectOcctShapes(e){return Array.isArray(e)&&!e.some((e=>!this.detectOcctShape(e)))}detectTag(e){return!Array.isArray(e)&&e.text}detectTags(e){return Array.isArray(e)&&!e.some((e=>!this.detectTag(e)))}checkIfElementsInArrayAreNumbers(e){return!e.some((e=>isNaN(e)))}checkIfElementsInArrayAreArrays(e){return!e.some((e=>!Array.isArray(e)))}arraysInChildrenArraysContainNumbers(e){return!e.some((e=>!this.checkIfElementsInArrayAreNumbers(e)))}arraysInChildrenArraysAreOfLength3(e){return!e.some((e=>3!==e.length))}}class lz{constructor(e,t){this.context=e,this.geometryHelper=t}drawLines(e){const t=[],i=[];return e.lines.forEach(((s,r)=>{let n;t.push([new _e(s.start[0],s.start[1],s.start[2]),new _e(s.end[0],s.end[1],s.end[2])]),n=Array.isArray(e.colours)&&e.colours.length===e.lines.length?Ee.FromHexString(e.colours[r]):Array.isArray(e.colours)?Ee.FromHexString(e.colours[0]):Ee.FromHexString(e.colours),i.push([new Ae(n.r,n.g,n.b,e.opacity),new Ae(n.r,n.g,n.b,e.opacity)])})),e.linesMesh&&e.updatable?e.linesMesh.getTotalVertices()/2===t.length?e.linesMesh=R_.CreateLineSystem(null,{lines:t,instance:e.linesMesh,colors:i,useVertexAlpha:!0,updatable:e.updatable},null):(e.linesMesh.dispose(),e.linesMesh=this.createLineSystemMesh(e.updatable,t,i)):e.linesMesh=this.createLineSystemMesh(e.updatable,t,i),this.geometryHelper.edgesRendering(e.linesMesh,e.size,e.opacity,e.colours),e.linesMesh}convertToNurbsCurve(e){return new this.context.verb.geom.Line(e.line.start,e.line.end)}convertLinesToNurbsCurves(e){return e.lines.map((e=>new this.context.verb.geom.Line(e.start,e.end)))}getStartPoint(e){return e.line.start}getEndPoint(e){return e.line.end}length(e){return this.context.verb.core.Vec.dist(e.line.start,e.line.end)}reverse(e){return{start:e.line.end,end:e.line.start}}transformLine(e){const t=e.transformation;let i=[e.line.start,e.line.end];return i=this.geometryHelper.transformControlPoints(t,i),{start:i[0],end:i[1]}}transformsForLines(e){return e.lines.map(((t,i)=>{const s=e.transformation[i];let r=[t.start,t.end];return r=this.geometryHelper.transformControlPoints(s,r),{start:r[0],end:r[1]}}))}create(e){return{start:e.start,end:e.end}}createAsync(e){return Promise.resolve({start:e.start,end:e.end})}getPointOnLine(e){const t=e.line.start,i=e.line.end,s=e.param,r=[i[0]-t[0],i[1]-t[1],i[2]-t[2]];return[t[0]+s*r[0],t[1]+s*r[1],t[2]+s*r[2]]}linesBetweenPoints(e){const t=[];for(let i=1;i({start:t,end:e.endPoints[i]}))).filter((e=>0!==this.context.verb.core.Vec.dist(e.start,e.end)))}linesBetweenStartAndEndPointsAsync(e){return Promise.resolve(this.linesBetweenStartAndEndPoints(e))}createLineSystemMesh(e,t,i){return R_.CreateLineSystem(`lines${Math.random()}`,{lines:t,colors:i,useVertexAlpha:!0,updatable:e},this.context.scene)}}class hz{getItem(e){if(e.index<0||e.index>=e.list.length)throw new Error("Index out of bounds");let t;return t=e.clone?structuredClone(e.list[e.index]):e.list[e.index],t}getSubList(e){let t;return t=e.clone?structuredClone(e.list.slice(e.indexStart,e.indexEnd)):e.list.slice(e.indexStart,e.indexEnd),t}getNthItem(e){let t=e.list;e.clone&&(t=structuredClone(e.list));const i=[];for(let s=0;s=r)t.forEach(((e,t)=>{!0===i[t]&&n.push(e)}));else{const e=[],o=Math.ceil(r/s);for(let t=0;t{!0===e[i]&&n.push(t)}))}return n}mergeElementsOfLists(e){const t=e.lists,i=e.level,s=[],r=[];t.forEach((e=>{const t=e.flat(i);s.push(t)}));const n=this.getLongestListLength({lists:s});for(let e=0;e0&&r.push(t)}let o=[];if(i>0)for(let e=0;e{e.length>t&&(t=e.length)})),t):void 0}reverse(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),t.reverse()}flipLists(e){if(e.list.length>0){const t=e.list[0].length;let i=!0;if(e.list.forEach((e=>{e.length!==t&&(i=!1)})),i){const i=[];for(let s=0;s{t.push(e[s])})),i.push(t)}return i}throw new Error("Lists are not of the same length")}throw new Error("List is empty")}groupNth(e){return(e=>{const{nrElements:t,list:i,keepRemainder:s}=e,r=t,n=[];let o=[];return i.forEach(((e,t)=>{o.push(e),(t+1)%r==0&&(n.push(o),o=[]),s&&t===i.length-1&&n.push(o)})),n})(e)}getListDepth(e){let t=0,i=!0,s=e.list;for(;i;){let e=!1;for(let t=0;t=0&&e.index<=t.length&&t.splice(e.index,0,e.item),t}addItemAtIndexes(e){let t=e.list;e.clone&&(t=structuredClone(e.list));let i=[...e.indexes];return i=i.filter((e=>e>=0&&e<=t.length)),i.sort(((e,t)=>e-t)),i.forEach(((i,s)=>{i>=0&&i+s<=t.length&&t.splice(i+s,0,e.item)})),t}addItemsAtIndexes(e){if(e.items.length!==e.indexes.length)throw new Error("Items and indexes must have the same length");for(let t=0;t0&&e.indexes[t-1]>e.indexes[t])throw new Error("Indexes must be in ascending order");let t=e.list;return e.clone&&(t=structuredClone(e.list)),[...e.indexes].forEach(((i,s)=>{i>=0&&i+s<=t.length&&t.splice(i+s,0,e.items[s])})),t}removeItemAtIndex(e){let t=e.list;return e.clone&&(t=structuredClone(e.list)),e.index>=0&&e.index<=t.length&&t.splice(e.index,1),t}removeNthItem(e){let t=e.list;e.clone&&(t=structuredClone(e.list));const i=[];for(let s=0;s{const s=e.points;return e.isClosed&&s.push(s[0]),e.color&&(Array.isArray(t)||(t=[]),Array.isArray(e.color)?t[i]=Ee.FromArray(e.color).toHexString():t[i]=e.color),s}));return this.geometryHelper.drawPolylines(e.polylinesMesh,i,e.updatable,e.size,e.opacity,t)}convertToNurbsCurve(e){return this.context.verb.geom.NurbsCurve.byPoints(e.polyline.points,1)}length(e){let t=0;for(let i=1;it.id===e.tagVariable.id));Object.keys(e.tag).forEach((i=>{t[i]=e.tag[i]})),t.needsUpdate=!0}else{const t=document.createElement("span"),i="_tag"+(new Date).getTime()+this.context.tagBag.length;e.tag.id=i,t.id=i,t.textContent=e.tag.text,document.querySelector("."+this.context.canvasZoneClass).appendChild(t),e.tag.needsUpdate=!0,this.context.tagBag.push(e.tag)}return e.tag}drawTags(e){if(e.tagsVariable&&e.updatable){if(e.tagsVariable.length{const s=this.context.tagBag.find((e=>e.id===t.id)),r=e.tags[i];if(r)Object.keys(r).forEach((e=>{s[e]=r[e]})),s.needsUpdate=!0;else{this.context.tagBag=this.context.tagBag.filter((e=>e.id!==s.id));const e=document.getElementById(s.id);e.parentNode.removeChild(e)}}))}else{const t=[];e.tags.forEach(((i,s)=>{const r=document.createElement("span"),n="_tag"+(new Date).getTime()+this.context.tagBag.length;i.id=n,r.id=n,r.textContent=i.text,document.querySelector("."+this.context.canvasZoneClass).appendChild(r),i.needsUpdate=!0,this.context.tagBag.push(i),t.push(i),e.tagsVariable=t}))}return e.tagsVariable}}class _z{constructor(e){this.context=e}angleBetween(e){return $r.FromRadians(this.context.verb.core.Vec.angleBetween(e.first,e.second)).degrees()}angleBetweenNormalized2d(e){return $r.FromRadians(this.context.verb.core.Vec.angleBetweenNormalized2d(e.first,e.second)).degrees()}positiveAngleBetween(e){return $r.FromRadians(this.context.verb.core.Vec.positiveAngleBetween(e.first,e.second,e.reference)).degrees()}addAll(e){return this.context.verb.core.Vec.addAll(e.vectors)}add(e){return this.context.verb.core.Vec.add(e.first,e.second)}all(e){return this.context.verb.core.Vec.all(e.vector)}cross(e){return this.context.verb.core.Vec.cross(e.first,e.second)}distSquared(e){return this.context.verb.core.Vec.distSquared(e.first,e.second)}dist(e){return this.context.verb.core.Vec.dist(e.first,e.second)}div(e){return this.context.verb.core.Vec.div(e.vector,e.scalar)}domain(e){return this.context.verb.core.Vec.domain(e.vector)}dot(e){return this.context.verb.core.Vec.dot(e.first,e.second)}finite(e){return this.context.verb.core.Vec.finite(e.vector)}isZero(e){return this.context.verb.core.Vec.isZero(e.vector)}lerp(e){return this.context.verb.core.Vec.lerp(e.fraction,e.first,e.second)}max(e){return this.context.verb.core.Vec.max(e.vector)}min(e){return this.context.verb.core.Vec.min(e.vector)}mul(e){return e.vector.map((t=>t*e.scalar))}neg(e){return this.context.verb.core.Vec.neg(e.vector)}normSquared(e){return this.context.verb.core.Vec.normSquared(e.vector)}norm(e){return this.context.verb.core.Vec.norm(e.vector)}normalized(e){return this.context.verb.core.Vec.normalized(e.vector)}onRay(e){return this.context.verb.core.Vec.onRay(e.point,e.vector,e.distance)}vectorXYZ(e){return[e.x,e.y,e.z]}vectorXY(e){return[e.x,e.y]}range(e){return this.context.verb.core.Vec.range(e.max)}signedAngleBetween(e){return $r.FromRadians(this.context.verb.core.Vec.signedAngleBetween(e.first,e.second,e.reference)).degrees()}span(e){return this.context.verb.core.Vec.span(e.min,e.max,e.step)}sub(e){return this.context.verb.core.Vec.sub(e.first,e.second)}sum(e){return this.context.verb.core.Vec.sum(e.vector)}}class pz{constructor(e){this.context=e,this.tolerance=1e-5,this.getArrayDepth=e=>Array.isArray(e)?1+Math.max(...e.map(this.getArrayDepth)):0}createOrUpdateSurfaceMesh(e,t,i,s,r,n){const o=()=>{const s=new Wn;s.positions=e.positions,s.indices=e.indices,s.normals=e.normals,s.applyToMesh(t,i)};if(t&&i)t.dispose(),o(),t.flipFaces(!1);else{let e=null;r&&(e=this.context.scene),t=new ha(`surface${Math.random()}`,e),o(),t.flipFaces(!1),s&&(t.material=s)}return s&&(t.material=s),n&&(t.isVisible=!1),t.isPickable=!1,t}createOrUpdateSurfacesMesh(e,t,i,s,r,n){const o=()=>{const s=e.pop(),r=new Wn;r.positions=s.positions,r.indices=s.indices,r.normals=s.normals,r.uvs=s.uvs;const n=[];e.forEach((e=>{const t=new Wn;t.positions=e.positions,t.indices=e.indices,t.normals=e.normals,t.uvs=e.uvs,n.push(t)})),r.merge(n),r.applyToMesh(t,i)};if(t&&i)t.dispose(),o(),t.flipFaces(!1);else{let e=null;r&&(e=this.context.scene),t=new ha(`surface${Math.random()}`,e),o(),t.flipFaces(!1),s&&(t.material=s)}return s&&(t.material=s),n&&(t.isVisible=!1),t.isPickable=!1,t}transformControlPoints(e,t){return this.getFlatTransformations(e).forEach((e=>{t=this.transformPointsByMatrixArray(t,e)})),t}getFlatTransformations(e){let t=[];return 3===this.getArrayDepth(e)?e.forEach((e=>{t.push(...e)})):t=e,t}transformPointsByMatrixArray(e,t){const i=me.FromArray(t);return this.transformPointsByMatrix(e,i)}transformPointsByMatrix(e,t){const i=[];for(const s of e){const e=new _e(s[0],s[1],s[2]),r=_e.TransformCoordinates(e,t);i.push([r.x,r.y,r.z])}return i}edgesRendering(e,t,i,s){e.enableEdgesRendering(),e.edgesWidth=t;const r=Array.isArray(s)?Ee.FromHexString(s[0]):Ee.FromHexString(s);e.color=r,e.edgesColor=new Ae(r.r,r.g,r.b,i)}drawPolyline(e,t,i,s,r,n){return this.drawPolylines(e,[t],i,s,r,n)}drawPolylines(e,t,i,s,r,n){var o;const a=[];if(t&&t.length>0){t.forEach((e=>{const t=e.map((e=>2===e.length?[e[0],e[1],0]:e));a.push(t.flat())}));const l=s/100,h=Array.isArray(n)?Ee.FromHexString(n[0]):Ee.FromHexString(n);if(e&&i){if(!(null===(o=null==e?void 0:e.metadata)||void 0===o?void 0:o.linesForRenderLengths.some(((e,t)=>e!==a[t].length))))return e.setPoints(a),e;e.dispose(),(e=this.createGreasedPolylines(i,a,l,h,r)).metadata={linesForRenderLengths:a.map((e=>e.length))}}else(e=this.createGreasedPolylines(i,a,l,h,r)).metadata={linesForRenderLengths:a.map((e=>e.length))};return e}}createGreasedPolylines(e,t,i,s,r){const n=wS(`lineSystem${Math.random()}`,{points:t,updatable:e},{width:i,color:s},this.context.scene);return n.material.alpha=r,n}removeConsecutiveDuplicates(e,t=!0){const i=[];if(e.length>1){for(let t=1;ti[0])))):i=e.points.map((()=>e.colours)),e.pointsMesh&&e.updatable?e.pointsMesh.getChildMeshes().length===t.length?this.updatePointsInstances(e.pointsMesh,t):(e.pointsMesh.dispose(),e.pointsMesh=this.createPointSpheresMesh(`pointsMesh${Math.random()}`,t,i,e.opacity,e.size,e.updatable)):e.pointsMesh=this.createPointSpheresMesh(`pointsMesh${Math.random()}`,t,i,e.opacity,e.size,e.updatable),e.pointsMesh}updatePointsInstances(e,t){const i=e.getChildMeshes(),s={};t.forEach(((e,t)=>{s[t]=new _e(e[0],e[1],e[2])})),i.forEach((e=>{e.position=s[e.metadata.index]}))}setUpPositionsAndColours(e,t){const i=[],s=[];return t.length===e.length?e.forEach(((e,r)=>{i.push(...e),s.push(t[r].r,t[r].g,t[r].b,1)})):e.forEach(((e,r)=>{i.push(...e),s.push(t[0].r,t[0].g,t[0].b,1)})),{positions:i,colors:s}}createPointSpheresMesh(e,t,i,s,r,n){const o=t.map(((e,t)=>({position:e,color:i[t],index:t}))),a=Array.from(new Set(i)),l=a.map(((e,t)=>{const i=new cu(`mat${Math.random()}`,this.context.scene);i.disableLighting=!0,i.emissiveColor=Ee.FromHexString(e),i.alpha=s;const r=o.filter((t=>t.color===e));return{hex:a,material:i,positions:r}})),h=new ha(e,this.context.scene);return l.forEach((e=>{const t=R_.CreateSphere(`sphere${Math.random()}`,{diameter:r,segments:6,updatable:n},this.context.scene);t.material=e.material,t.isVisible=!1,e.positions.forEach(((e,i)=>{const s=t.createInstance(`sphere-${i}-${Math.random()}`);s.position=new _e(e.position[0],e.position[1],e.position[2]),s.metadata={index:e.index},s.parent=h,s.isVisible=!0}))})),h}}class fz{constructor(e,t,i){this.context=e,this.geometryHelper=t,this.line=i}drawPoint(e){return this.geometryHelper.drawPoint(e)}drawPoints(e){return this.geometryHelper.drawPoints(e)}drawPointsAsync(e){return Promise.resolve(this.drawPoints(e))}transformPoint(e){const t=e.transformation;let i=[e.point];return i=this.geometryHelper.transformControlPoints(t,i),i[0]}transformPoints(e){return this.geometryHelper.transformControlPoints(e.transformation,e.points)}transformsForPoints(e){if(e.points.length!==e.transformation.length)throw new Error("You must provide equal nr of points and transformations");return e.points.map(((t,i)=>this.geometryHelper.transformControlPoints(e.transformation[i],[t])[0]))}closestPointFromPointsDistance(e){return this.closestPointFromPointData(e).distance}closestPointFromPointsIndex(e){return this.closestPointFromPointData(e).index}closestPointFromPoints(e){return this.closestPointFromPointData(e).point}distance(e){const t=e.endPoint[0]-e.startPoint[0],i=e.endPoint[1]-e.startPoint[1],s=e.endPoint[2]-e.startPoint[2];return Math.sqrt(t*t+i*i+s*s)}distancesToPoints(e){return e.endPoints.map((t=>this.distance({startPoint:e.startPoint,endPoint:t})))}multiplyPoint(e){const t=[];for(let i=0;i{t.push(e[0]),i.push(e[1]),s.push(e[2])})),[t.reduce(((e,t)=>e+t),0)/e.points.length,i.reduce(((e,t)=>e+t),0)/e.points.length,s.reduce(((e,t)=>e+t),0)/e.points.length]}pointXYZ(e){return[e.x,e.y,e.z]}pointXY(e){return[e.x,e.y]}spiral(e){const t=e.phi,i=Math.log(t)/(Math.PI/e.widening),s=[],r=e.radius/e.numberPoints;for(let t=0;t{i[r]=[s[0]-e,s[1]-t,0]}))}return e.pointsOnGround&&i.forEach(((e,t)=>{i[t]=[e[0],0,e[1]]})),i}closestPointFromPointData(e){let t,i,s=Number.MAX_SAFE_INTEGER;for(let r=0;r{e(t)}))}}class gz{create(e){return e.text}split(e){return e.text.split(e.separator)}replaceAll(e){return e.text.split(e.search).join(e.replaceWith)}join(e){return e.list.join(e.separator)}toString(e){return e.item.toString()}toStringEach(e){return e.list.map((e=>e.toString()))}}class vz{constructor(){}}class xz{constructor(){this.assetManager=new vz}getFile(e){return this.assetManager.getAsset(e.fileName)}getLocalFile(e){return this.assetManager.getLocalAsset(e.fileName)}createObjectURL(e){return URL.createObjectURL(e.file)}createObjectURLs(e){return e.files.map((e=>URL.createObjectURL(e)))}}class bz{constructor(e){this.context=e}hexColor(e){return e.color}hexToRgb(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e.color);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:void 0}rgbToHex(e){const t=e.r,i=e.g,s=e.b;return`#${Number(16777216+65536*t+256*i+s).toString(16).substring(1,7)}`}hexToRgbMapped(e){const t=this.hexToRgb(e);return{r:this.context.remap(t.r,0,255,e.from,e.to),g:this.context.remap(t.g,0,255,e.from,e.to),b:this.context.remap(t.b,0,255,e.from,e.to)}}getRedParam(e){return this.hexToRgbMapped(e).r}getGreenParam(e){return this.hexToRgbMapped(e).g}getBlueParam(e){return this.hexToRgbMapped(e).b}rgbToRed(e){return e.rgb.r}rgbToGreen(e){return e.rgb.g}rgbToBlue(e){return e.rgb.b}}class Tz{constructor(){this.canvasZoneClass="canvasZone",this.tolerance=1e-5,this.snapTolerance=1e-5,this.tagBag=[],this.timeoutBag=[],this.intervalBag=[],this.renderLoopBag=[],this.keyDownBag=[],this.keyUpBag=[],this.keyPressBag=[],this.currentlyPressedKeys=[]}getFile(e){return new Promise(((t,i)=>{if(e){const s=new FileReader;s.readAsText(e,"UTF-8"),s.onload=e=>{const i=e.target.result;t(i)},s.onerror=e=>{i()}}else i()}))}remap(e,t,i,s,r){return(e-t)/(i-t)*(r-s)+s}}!function(e){e[e.loading=0]="loading",e[e.loaded=1]="loaded",e[e.initialised=2]="initialised",e[e.computing=3]="computing"}(nz||(nz={}));class yz{constructor(){this.jscadWorkerState=new iV,this.promisesMade=[]}jscadWorkerAlreadyInitialised(){return!!this.jscadWorker}setJscadWorker(e){this.jscadWorker=e,this.jscadWorker.onmessage=({data:e})=>{if("jscad-initialised"===e)this.jscadWorkerState.next({state:nz.initialised});else if("busy"===e)this.jscadWorkerState.next({state:nz.computing});else{const t=this.promisesMade.find((t=>t.uid===e.uid));t&&e.result&&!e.error?t.resolve(e.result):e.error&&(this.errorCallback&&this.errorCallback(e.error),t.reject(e.error)),this.promisesMade=this.promisesMade.filter((t=>t.uid!==e.uid)),0===this.promisesMade.length?this.jscadWorkerState.next({state:nz.loaded}):this.jscadWorkerState.next({state:nz.computing})}}}cleanPromisesMade(){this.promisesMade=[]}genericCallToWorkerPromise(e,t){const i=`call${Math.random()}${Date.now()}`,s={uid:i},r=new Promise(((e,t)=>{s.resolve=e,s.reject=t}));return s.promise=r,this.promisesMade.push(s),this.jscadWorker.postMessage({action:{functionName:e,inputs:t},uid:i}),r}startedTheRun(){return this.genericCallToWorkerPromise("startedTheRun",{})}cleanAllCache(){return this.genericCallToWorkerPromise("cleanAllCache",{})}}var Sz=i(258);class Cz{constructor(e){this.context=e}stringify(e){return JSON.stringify(e.json)}parse(e){return JSON.parse(e.text)}query(e){return this.context.jsonpath.query(e.json,e.query)}setValue(e){const t=Object.assign({},structuredClone(e.json));return this.context.jsonpath.value(t,e.path,e.value),t}setValuesOnPaths(e){const t=Object.assign({},structuredClone(e.json));return e.paths.forEach(((i,s)=>{this.context.jsonpath.value(t,i,e.values[s])})),t}paths(e){return this.context.jsonpath.paths(e.json,e.query)}pathsAsStrings(e){return this.context.jsonpath.paths(e.json,e.query).map((e=>this.context.jsonpath.stringify(e)))}createEmpty(){return{}}previewAndSaveJson(e){e.json&&this.context.promptPrintSave({text:e.json,isJson:!0,hidden:!1})}previewJson(e){e.json&&this.context.promptPrint({text:e.json,isJson:!0,hidden:!1})}}var Ez=i(615);class Az{boolean(e){return e.boolean}randomBooleans(e){const t=[];for(let i=0;i{if(ie.thresholdTotalFalse)t.push(!1);else{const s=i-e.thresholdTotalTrue,r=(e.thresholdTotalFalse-e.thresholdTotalTrue)/e.nrLevels,n=Math.ceil(s/r)/e.nrLevels;Math.random()>n?t.push(!0):t.push(!1)}})),t}thresholdBooleanList(e){const t=[];return e.numbers.forEach((i=>{i!e)):t}thresholdGapsBooleanList(e){const t=[];return e.numbers.forEach((i=>{let s=!1;e.gapThresholds.forEach((e=>{const r=e[0],n=e[1];i>=r&&i<=n&&(t.push(!0),s=!0)})),s||t.push(!1)})),e.inverse?t.map((e=>!e)):t}not(e){return!e.boolean}notList(e){return e.booleans.map((e=>!e))}compare(e){switch(e.operator){case"==":return e.first==e.second;case"!=":return e.first!=e.second;case"===":return e.first===e.second;case"!==":return e.first!==e.second;case"<":return e.first":return e.first>e.second;case">=":return e.first>=e.second;default:return!1}}valueGate(e){return e.boolean?e.value:void 0}firstDefinedValueGate(e){let t;return t=void 0!==e.value1?e.value1:void 0!==e.value2?e.value2:void 0,t}}class Pz{constructor(){this.context=new Tz,this.jscadWorkerManager=new yz,this.occtWorkerManager=new rV;const e=new pz(this.context);this.color=new bz(this.context),this.babylon=new HU(this.context,e,this.color),this.vector=new _z(this.context),this.line=new lz(this.context,e),this.point=new fz(this.context,e,this.line),this.polyline=new uz(this.context,e),this.verb=new AG(this.context,e),this.jscad=new hG(this.jscadWorkerManager,this.context,e),this.tag=new dz(this.context),this.time=new mz(this.context),this.occt=new pG(this.context,this.occtWorkerManager,e,this.jscad.text,this.vector),this.asset=new xz,this.math=new cz,this.logic=new Az,this.json=new Cz(this.context),this.text=new gz,this.lists=new hz,this.draw=new az(this.point,this.line,this.polyline,this.babylon.node,this.verb.curve,this.verb.surface,this.jscad,this.occt,this.tag,this.context)}init(e,t,i,s){this.context.scene=e,s&&(this.context.havokPlugin=s);const r={geom:Sz.geom,core:Sz.core};this.context.verb=r,this.context.jsonpath=Ez,t&&this.occtWorkerManager.setOccWorker(t),i&&this.jscadWorkerManager.setJscadWorker(i)}}const Iz="assets/textures";class Rz{constructor(e){this.name="",this.scene=void 0,this.wAng=0,this.uScale=1,this.vScale=1,this.color=void 0,this.albedoTextureUrl=void 0,this.microSurfaceTextureUrl=void 0,this.bumpTextureUrl=void 0,this.metallic=.1,this.roughness=.9,this.zOffset=2,Object.keys(this).forEach((t=>this[t]=e[t]))}}class Mz{static simpleBlackMaterial(e){const t=new zg("blackMaterial"+Math.random(),e);return t.albedoColor=new Ee(0,0,0),t.metallic=0,t.roughness=.7,t.zOffset=2,t}static rock1Material(e,t,i){const s=new Rz({name:"wood1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.rock1.default.albedo,bumpTextureUrl:Mz.textures.rock1.microSurfaceTexture,microSurfaceTextureUrl:Mz.textures.rock1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(s)}static wood1Material(e,t,i){const s=new Rz({name:"wood1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.wood1.light.albedo,bumpTextureUrl:Mz.textures.wood1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(s)}static wood2Material(e,t,i){const s=new Rz({name:"wood2",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.wood2.light.albedo,microSurfaceTextureUrl:Mz.textures.wood2.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(s)}static wood3Material(e,t,i){const s=new Rz({name:"wood3",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.wood1.dark.albedo,microSurfaceTextureUrl:Mz.textures.wood1.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(s)}static brownPlanks(e,t,i){const s=new Rz({name:"brownPlanks",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.brownPlanks.light.albedo,microSurfaceTextureUrl:Mz.textures.brownPlanks.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(s)}static woodenPlanks(e,t,i){const s=new Rz({name:"woodenPlanks",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.woodenPlanks.light.albedo,microSurfaceTextureUrl:Mz.textures.woodenPlanks.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(s)}static glass(e,t){const i=new zg("faceGlassMaterial"+Math.random(),e);return i.albedoColor=Ee.FromHexString(t),i.ambientColor=Ee.FromHexString("#ffffff"),i.metallic=.8,i.roughness=.1,i.zOffset=1,i.alpha=.5,i}static brushedConcrete(e,t,i){const s=new Rz({name:"brushedConcrete",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.brushedConcrete.grey.albedo,microSurfaceTextureUrl:Mz.textures.brushedConcrete.microSurfaceTexture,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(s)}static metal1(e,t,i){const s=new Rz({name:"metal1",scene:e,wAng:t,uScale:i,vScale:i,albedoTextureUrl:Mz.textures.metal1.light.albedo,microSurfaceTextureUrl:Mz.textures.metal1.microSurfaceTexture,bumpTextureUrl:Mz.textures.metal1.light.roughness,metallic:.3,roughness:.6,zOffset:2});return Mz.createMaterial(s)}static roughPlastic(e,t){const i=new Rz({name:"roughPlastic-"+t,color:t,scene:e,metallic:.1,roughness:.9,zOffset:2});return Mz.createMaterial(i)}static createMaterial(e){const t=new zg(e.name,e.scene);return e.color&&(t.albedoColor=Ee.FromHexString(e.color)),e.albedoTextureUrl&&(t.albedoTexture=Mz.createTexture(e.albedoTextureUrl,e)),e.microSurfaceTextureUrl&&(t.microSurfaceTexture=Mz.createTexture(e.microSurfaceTextureUrl,e)),e.bumpTextureUrl&&(t.bumpTexture=Mz.createTexture(e.bumpTextureUrl,e)),t.metallic=e.metallic,t.roughness=e.roughness,t.zOffset=e.zOffset,t}static createTexture(e,t){const i=new Pa(e,t.scene);return i.uScale=t.uScale,i.vScale=t.vScale,i.wAng=t.wAng,i}}Mz.textures={wood1:{microSurfaceTexture:`${Iz}/Wood048_1K/Wood048_1K_NormalGL.jpg`,light:{albedo:`${Iz}/Wood048_1K/Wood048_1K_Light.jpg`},dark:{albedo:`${Iz}/Wood048_1K/Wood048_1K_Color_Dark.jpg`}},wood2:{microSurfaceTexture:`${Iz}/Wood084_1K/Wood084A_1K_NormalGL.jpg`,light:{albedo:`${Iz}/Wood084_1K/Wood084A_1K_Color.jpg`}},metal1:{microSurfaceTexture:`${Iz}/metal_1/Metal029_1K_Displacement.jpg`,light:{albedo:`${Iz}/metal_1/Metal029_1K_Color.jpg`,normalGL:`${Iz}/metal_1/Metal029_1K_NormalGL.jpg`,roughness:`${Iz}/metal_1/Metal029_1K_Roughness.jpg`,metalness:`${Iz}/metal_1/Metal029_1K_Metalness.jpg`}},brownPlanks:{microSurfaceTexture:`${Iz}/brown_planks/brown_planks_05_nor_gl_1k.jpg`,light:{albedo:`${Iz}/brown_planks/brown_planks_05_diff_1k.jpg`}},woodenPlanks:{microSurfaceTexture:`${Iz}/wooden_planks/wooden_planks_nor_gl_1k.jpg`,light:{albedo:`${Iz}/wooden_planks/wooden_planks_diff_1k.jpg`}},brushedConcrete:{microSurfaceTexture:`${Iz}/brushed_concrete/brushed_concrete_03_nor_gl_1k.jpg`,sand:{albedo:`${Iz}/brushed_concrete/brushed_concrete_03_diff_1k.jpg`},grey:{albedo:`${Iz}/brushed_concrete/brushed_concrete_03_diff_grey_1k.jpg`}},rock1:{microSurfaceTexture:`${Iz}/Rock044_1K/Rock044_1K_NormalGL.jpg`,default:{albedo:`${Iz}/Rock044_1K/Rock044_1K_Color.jpg`,roughness:`${Iz}/Rock044_1K/Rock044_1K_Roughness.jpg`}}};var Oz=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class Dz{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return Oz(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.wingtipVilla",e);if(t){const e=t.shapes.find((e=>e.id===t.data.roof.compound)),i=t.shapes.find((e=>e.id===t.data.walls.compound));return{type:t.data.type,name:t.data.name,compound:t.compound,roof:{compound:e.shape,shapes:t.shapes.filter((e=>t.data.roof.shapes.includes(e.id))).map((e=>e.shape))},walls:{compound:i.shape,shapes:t.shapes.filter((e=>t.data.walls.shapes.includes(e.id))).map((e=>e.shape))},stick:{shape:t.shapes.find((e=>e.id===t.data.stick.shape)).shape},floor:{shape:t.shapes.find((e=>e.id===t.data.floor.shape)).shape},chimney:{shape:t.shapes.find((e=>e.id===t.data.chimney.shape)).shape},basicPoints:t.data.basicPoints}}}))}drawModel(e){return Oz(this,void 0,void 0,(function*(){const t=new ha("brepMesh"+Math.random(),this.context.scene),i=new mU.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#ffffff";const s=yield this.draw.drawAnyAsync({entity:e.roof.compound,options:i}),r=s.getChildMeshes(),n=r[0],o=r[1],a=yield this.draw.drawAnyAsync({entity:e.walls.compound,options:i}),l=a.getChildMeshes(),h=l[0],c=l[1],u=yield this.draw.drawAnyAsync({entity:e.floor.shape,options:i}),d=u.getChildMeshes(),_=d[0],p=d[1],f=yield this.draw.drawAnyAsync({entity:e.stick.shape,options:i}),m=f.getChildMeshes(),g=m[0],v=m[1],x=yield this.draw.drawAnyAsync({entity:e.chimney.shape,options:i}),b=x.getChildMeshes(),T=b[0],y=b[1],S=new Pa("assets/textures/Wood048_1K/Wood048_1K_Red.jpg",this.context.scene),C=new Pa("assets/textures/Wood048_1K/Wood048_1K_Color_Dark.jpg",this.context.scene),E=new Pa("assets/textures/Wood048_1K/Wood048_1K_NormalGL.jpg",this.context.scene);S.uScale=.3,S.vScale=.3,S.wAng=Math.PI/2,C.uScale=.3,C.vScale=.3,C.wAng=Math.PI/2,E.uScale=.3,E.vScale=.3,E.wAng=Math.PI/2;const A=new zg("wood-red",this.context.scene);A.albedoTexture=S,A.microSurfaceTexture=E,A.metallic=0,A.roughness=1,A.zOffset=2;const P=new zg("wood-dark",this.context.scene);return P.albedoTexture=C,P.microSurfaceTexture=E,P.metallic=0,P.roughness=1,P.zOffset=2,n.material=A,h.material=Mz.wood1Material(this.context.scene,Math.PI/2,.3),_.material=A,g.material=A,T.material=P,n.parent=t,h.parent=t,_.parent=t,g.parent=t,T.parent=t,o.parent=t,c.parent=t,p.parent=t,v.parent=t,y.parent=t,s.dispose(),u.dispose(),a.dispose(),f.dispose(),x.dispose(),t}))}dispose(e){return Oz(this,void 0,void 0,(function*(){const t=[e.compound,e.chimney.shape,e.floor.shape,...e.roof.shapes,...e.walls.shapes,e.stick.shape];yield this.occt.deleteShapes({shapes:t})}))}}var wz=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class Nz{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}dispose(e){return wz(this,void 0,void 0,(function*(){const t=[e.compound,e.floor.shape,...e.roof.shapes,...e.walls.shapes,e.stick.shape];yield this.occt.deleteShapes({shapes:t})}))}create(e){return wz(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.chirpyChalet",e);if(t){const e=t.shapes.find((e=>e.id===t.data.roof.compound)),i=t.shapes.find((e=>e.id===t.data.walls.compound));return{type:t.data.type,name:t.data.name,compound:t.compound,roof:{compound:e.shape,shapes:t.shapes.filter((e=>t.data.roof.shapes.includes(e.id))).map((e=>e.shape))},walls:{compound:i.shape,shapes:t.shapes.filter((e=>t.data.walls.shapes.includes(e.id))).map((e=>e.shape))},stick:{shape:t.shapes.find((e=>e.id===t.data.stick.shape)).shape},floor:{shape:t.shapes.find((e=>e.id===t.data.floor.shape)).shape},basicPoints:t.data.basicPoints}}}))}drawModel(e){return wz(this,void 0,void 0,(function*(){const t=new ha("brepMesh"+Math.random(),this.context.scene),i=new mU.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#ffffff";const s=yield this.draw.drawAnyAsync({entity:e.roof.compound,options:i}),r=s.getChildMeshes()[0],n=yield this.draw.drawAnyAsync({entity:e.walls.compound,options:i}),o=n.getChildMeshes()[0],a=yield this.draw.drawAnyAsync({entity:e.floor.shape,options:i}),l=a.getChildMeshes()[0],h=yield this.draw.drawAnyAsync({entity:e.stick.shape,options:i}),c=h.getChildMeshes()[0],u=new Pa("assets/textures/Wood048_1K/Wood048_1K_Color.jpg",this.context.scene),d=new Pa("assets/textures/Wood048_1K/Wood048_1K_Light.jpg",this.context.scene),_=new Pa("assets/textures/Wood048_1K/Wood048_1K_NormalGL.jpg",this.context.scene);d.uScale=.3,d.vScale=.3,d.wAng=Math.PI/2,u.uScale=.3,u.vScale=.3,u.wAng=Math.PI/2,_.uScale=.3,_.vScale=.3,_.wAng=Math.PI/2;const p=new zg("roof",this.context.scene);p.albedoTexture=u,p.microSurfaceTexture=_,p.metallic=0,p.roughness=1,p.zOffset=2;const f=new zg("walls",this.context.scene);return f.albedoTexture=d,f.microSurfaceTexture=_,f.metallic=0,f.roughness=1,f.zOffset=2,r.material=p,o.material=f,l.material=p,c.material=p,s.setParent(t),a.setParent(t),n.setParent(t),h.setParent(t),t}))}}class Fz{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.wingtipVilla=new Dz(this.occWorkerManager,this.context,this.draw,this.occt),this.chirpyChalet=new Nz(this.occWorkerManager,this.context,this.draw,this.occt)}}class Lz{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.birdhouses=new Fz(this.occWorkerManager,this.context,this.draw,this.occt)}}var Bz,kz,Vz,Uz,Gz,zz,Wz=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class Hz{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return Wz(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.serenitySwirl",e);return t?{type:t.data.type,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e,t=.003){return Wz(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s}),n=new zg("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new Ee(1,1,1),n.ambientColor=Ee.FromHexString("#ffffff"),n.metallic=0,n.roughness=.7,n.zOffset=1,r.getChildMeshes()[0].material=n,r.material=n,r.parent=i,i}))}dispose(e){return Wz(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}!function(e){e.low="low",e.middle="middle",e.high="high"}(Bz||(Bz={}));class Xz{constructor(){this.lod=Bz.low}}class Yz{}class Qz{constructor(e,t,i,s,r,n,o,a,l){this.swirl=.6,this.nrOfDivisions=10,this.addRadiusNarrow=.4,this.addRadiusWide=.2,this.addMiddleHeight=1.6,this.addTopHeight=1.5,this.thickness=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.swirl=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.addRadiusNarrow=i),void 0!==s&&(this.addRadiusWide=s),void 0!==r&&(this.addMiddleHeight=r),void 0!==n&&(this.addTopHeight=n),void 0!==o&&(this.thickness=o),void 0!==a&&(this.rotation=a),void 0!==l&&(this.origin=l)}}class jz{constructor(){this.type="parametric-model",this.name="serenitySwirl"}}class Kz{}class $z{constructor(e,t,i,s,r,n,o,a,l,h,c,u){this.profilePoints=[[2,0,0],[4,5,0],[1.5,10,0],[3,14,0]],this.nrOfSides=6,this.nrOfVerticalArches=4,this.archCenterThickness=.8,this.edgesThickness=.2,this.thickness=1,this.baseHeight=.4,this.patchHoles=!0,this.lod=Bz.high,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],this.scale=[1,1,1],void 0!==e&&(this.nrOfSides=e),void 0!==t&&(this.nrOfVerticalArches=t),void 0!==i&&(this.archCenterThickness=i),void 0!==s&&(this.edgesThickness=s),void 0!==r&&(this.thickness=r),void 0!==n&&(this.baseHeight=n),void 0!==o&&(this.patchHoles=o),void 0!==a&&(this.lod=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.origin=h),void 0!==c&&(this.direction=c),void 0!==u&&(this.scale=u)}}class qz{constructor(){this.type="parametric-model",this.name="arabicArchway"}}class Zz{}class Jz{}class eW{}class tW{constructor(e,t,i,s,r,n,o,a){this.textHeading="LOVE YOU",this.textName="NORA",this.fullModel=!0,this.thickness=6,this.decorationThickness=1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textHeading=e),void 0!==t&&(this.textName=t),void 0!==i&&(this.fullModel=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.decorationThickness=r),void 0!==n&&(this.rotation=n),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a)}}class iW{constructor(){this.type="parametric-model",this.name="eternalLove"}}class sW{}class rW{constructor(e,t,i,s,r,n,o,a,l,h,c,u){this.height=6,this.radiusBottom=4,this.radiusTopOffset=2,this.thickness=.6,this.fillet=.2,this.nrOfHandles=1,this.handleDist=2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==i&&(this.radiusTopOffset=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.fillet=r),void 0!==n&&(this.nrOfHandles=n),void 0!==o&&(this.handleDist=o),void 0!==a&&(this.precision=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.scale=h),void 0!==c&&(this.origin=c),void 0!==u&&(this.direction=u)}}class nW{constructor(){this.type="parametric-model",this.name="calmCup"}}class oW{}class aW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v,x,b){this.height=8,this.radiusBottom=4,this.radiusTopOffset=2,this.radiusMidOffset=2,this.rotationTopAngle=20,this.rotationMidAngle=20,this.nrSkinCellsVertical=5,this.nrSkinCellsHorizontal=10,this.nrSkinCellDivisionsTop=1,this.nrSkinCellDivisionsBottom=3,this.skinCellOuterHeight=.4,this.skinCellInnerHeight=.3,this.skinCellBottomHeight=.4,this.skinCellTopHeight=.4,this.thickness=.6,this.bottomThickness=1,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==i&&(this.radiusTopOffset=i),void 0!==s&&(this.radiusMidOffset=s),void 0!==r&&(this.rotationTopAngle=r),void 0!==n&&(this.rotationMidAngle=n),void 0!==o&&(this.nrSkinCellsVertical=o),void 0!==a&&(this.nrSkinCellsHorizontal=a),void 0!==l&&(this.nrSkinCellDivisionsTop=l),void 0!==h&&(this.nrSkinCellDivisionsBottom=h),void 0!==c&&(this.skinCellOuterHeight=c),void 0!==u&&(this.skinCellInnerHeight=u),void 0!==d&&(this.skinCellBottomHeight=d),void 0!==_&&(this.skinCellTopHeight=_),void 0!==p&&(this.thickness=p),void 0!==f&&(this.bottomThickness=f),void 0!==m&&(this.precision=m),void 0!==g&&(this.rotation=g),void 0!==v&&(this.scale=v),void 0!==x&&(this.origin=x),void 0!==b&&(this.direction=b)}}class lW{constructor(){this.type="parametric-model",this.name="dragonCup"}}class hW{}class cW{}class uW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g){this.heightBottom=5,this.heightTop=16,this.widthBack=25,this.widthFront=10,this.length=16,this.backOffset=6,this.thickness=.4,this.applyOrnaments=!1,this.filletRadius=2,this.phoneHeight=16.8,this.phoneWidth=7.8,this.phoneThickness=.7,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.heightBottom=e),void 0!==t&&(this.heightTop=t),void 0!==i&&(this.widthBack=i),void 0!==s&&(this.widthFront=s),void 0!==r&&(this.length=r),void 0!==n&&(this.backOffset=n),void 0!==o&&(this.thickness=o),void 0!==a&&(this.applyOrnaments=a),void 0!==l&&(this.filletRadius=l),void 0!==h&&(this.phoneHeight=h),void 0!==c&&(this.phoneWidth=c),void 0!==u&&(this.phoneThickness=u),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdges=_),void 0!==p&&(this.rotation=p),void 0!==f&&(this.scale=f),void 0!==m&&(this.origin=m),void 0!==g&&(this.direction=g)}}class dW{constructor(){this.type="parametric-model",this.name="phoneNest"}}class _W extends Yz{}class pW{}class fW extends Yz{}class mW{}class gW{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class vW{}class xW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v){this.textTop="Pepper",this.textFront="For Your Spicy Needs",this.nrSides=4,this.nrOffsets=1,this.height=6,this.radiusBase=4,this.radiusOffset=2,this.coverHeight=1,this.baseHeight=1,this.thickness=.6,this.ornamentalThickness=.1,this.nrOrnamnetsPerSide=10,this.invertOrnaments=!1,this.fillet=.2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textTop=e),void 0!==t&&(this.textFront=t),void 0!==i&&(this.nrSides=i),void 0!==s&&(this.nrOffsets=s),void 0!==r&&(this.height=r),void 0!==n&&(this.coverHeight=n),void 0!==o&&(this.baseHeight=o),void 0!==a&&(this.radiusBase=a),void 0!==l&&(this.radiusOffset=l),void 0!==h&&(this.thickness=h),void 0!==c&&(this.ornamentalThickness=c),void 0!==u&&(this.nrOrnamnetsPerSide=u),void 0!==d&&(this.invertOrnaments=d),void 0!==_&&(this.fillet=_),void 0!==p&&(this.precision=p),void 0!==f&&(this.rotation=f),void 0!==m&&(this.scale=m),void 0!==g&&(this.origin=g),void 0!==v&&(this.direction=v)}}class bW{constructor(){this.type="parametric-model",this.name="spicyBox"}}class TW{}class yW{}class SW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g,v,x,b,T,y,S,C,E,A,P,I,R){this.widthFirstWing=4,this.lengthFirstWing=10,this.terraceWidth=3,this.widthSecondWing=5,this.lengthSecondWing=10,this.heightWalls=3,this.roofAngleFirstWing=15,this.roofAngleSecondWing=25,this.roofOffset=.5,this.roofInsideOverhang=.5,this.roofMaxDistAttachmentBeams=.8,this.roofAttachmentBeamWidth=.2,this.roofAttachmentBeamHeight=.05,this.roofOutsideOverhang=.5,this.columnSize=.3,this.ceilingBeamHeight=.25,this.ceilingBeamWidth=.1,this.nrCeilingBeamsBetweenColumns=3,this.distBetweenColumns=2,this.floorHeight=.1,this.groundLevel=.6,this.facadePanelThickness=.05,this.windowWidthOffset=.1,this.windowHeightOffset=.2,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05,this.lod=Bz.high,this.skinOpacity=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.widthFirstWing=e),void 0!==t&&(this.lengthFirstWing=t),void 0!==i&&(this.terraceWidth=i),void 0!==s&&(this.widthSecondWing=s),void 0!==r&&(this.lengthSecondWing=r),void 0!==n&&(this.heightWalls=n),void 0!==o&&(this.roofAngleFirstWing=o),void 0!==a&&(this.roofAngleSecondWing=a),void 0!==l&&(this.roofOffset=l),void 0!==h&&(this.roofInsideOverhang=h),void 0!==c&&(this.roofMaxDistAttachmentBeams=c),void 0!==u&&(this.roofAttachmentBeamWidth=u),void 0!==d&&(this.roofAttachmentBeamHeight=d),void 0!==_&&(this.roofOutsideOverhang=_),void 0!==p&&(this.columnSize=p),void 0!==f&&(this.ceilingBeamHeight=f),void 0!==m&&(this.ceilingBeamWidth=m),void 0!==g&&(this.nrCeilingBeamsBetweenColumns=g),void 0!==v&&(this.distBetweenColumns=v),void 0!==x&&(this.floorHeight=x),void 0!==b&&(this.groundLevel=b),void 0!==T&&(this.facadePanelThickness=T),void 0!==y&&(this.windowWidthOffset=y),void 0!==S&&(this.windowHeightOffset=S),void 0!==C&&(this.windowFrameThickness=C),void 0!==E&&(this.windowGlassFrameThickness=E),void 0!==A&&(this.lod=A),void 0!==P&&(this.skinOpacity=P),void 0!==I&&(this.rotation=I),void 0!==R&&(this.origin=R)}}class CW{constructor(){this.type="parametric-model",this.name="zenHideout"}}class EW{}class AW{}class PW{constructor(){this.wallThickness=.4,this.facadePanelThickness=.05,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThckness=.05,this.height=3,this.lengthFirst=1,this.lengthSecond=2,this.rotation=0}}class IW{constructor(){this.thickness=.3,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThickness=.05,this.height=3,this.width=1,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0]}}class RW extends IW{}class MW extends PW{}class OW{constructor(){this.name="sandwitch-panel",this.createWindow=!0,this.createInnerPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelWidth=.4,this.exteriorPanelHeight=3,this.exteriorPanelThickness=.05,this.exteriorPanelBottomOffset=0,this.interiorPanelWidth=.4,this.interiorPanelHeight=3,this.interiorPanelThickness=.05,this.interiorPanelBottomOffset=0,this.windowWidthOffset=0,this.windowHeightOffset=0,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05}}class DW{constructor(){this.name="sandwitch-panel-flex",this.createInteriorPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelThickness=.05,this.interiorPanelThickness=.05,this.interiorPanelPolygonPoints=[],this.exteriorPanelPolygonPoints=[]}}class wW extends OW{}class NW extends DW{}class FW{}class LW{}class BW{}class kW{}class VW{}class UW{}class GW{constructor(){this.invert=!1,this.widthFirstLanding=1,this.widthSecondLanding=1,this.lengthFirstWing=2,this.lengthSecondWing=1,this.maxWishedStepHeight=.25,this.stepHeightWidthProportion=1.35,this.totalHeight=1,this.rotation=0,this.origin=[0,0,0]}}class zW extends GW{}class WW{}class HW{constructor(){this.name="roof-cover",this.roofAngle=15,this.roofLength=3,this.roofWidth=3,this.roofOutsideOverhang=.5,this.roofInsideOverhang=1,this.roofOverhangFacade=.1,this.roofThickness=.05,this.roofCoverHeight=.3,this.rotation=0,this.lod=Bz.high,this.center=[0,0,0],this.direction=[0,1,0]}}class XW extends HW{}class YW{}class QW{}class jW{constructor(){this.widthFirstWing=1,this.widthSecondWing=2,this.lengthStairFirstWing=2,this.lengthStairSecondWing=1,this.lengthWallFirstWing=2,this.lengthWallSecondWing=1,this.facadePanelThickness=.05,this.wallThickness=3,this.wallHeightExterior=3,this.wallHeightInterior=3,this.windowFrameOffsetTop=.3,this.windowFrameThickness=.1,this.glassFrameThickness=.05,this.doorWidth=1,this.windowWidthOffset=.3,this.stairTotalHeight=1,this.createStair=!1,this.flipDirection=!1,this.rotation=0,this.origin=[0,0,0]}}class KW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.5,this.holeDiameter=1.5,this.holeDistToBottom=2.5,this.stickLength=1.2,this.stickDiameter=.5,this.baseAttachmentHeight=2,this.roofOverhang=1,this.rotation=0,this.chimneyHeight=1,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==i&&(this.interiorHeight=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.holeDiameter=r),void 0!==n&&(this.holeDistToBottom=n),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==l&&(this.baseAttachmentHeight=l),void 0!==h&&(this.roofOverhang=h),void 0!==c&&(this.rotation=c),void 0!==u&&(this.chimneyHeight=u),void 0!==d&&(this.origin=d)}}class $W{constructor(){this.type="parametric-model",this.name="wingtipVilla"}}class qW{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.3,this.holeDiameter=1.2,this.holeDistToBottom=2.5,this.stickLength=.9,this.stickDiameter=.3,this.baseAttachmentHeight=2,this.roofOverhang=.5,this.roofAngle=20,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==i&&(this.interiorHeight=i),void 0!==s&&(this.thickness=s),void 0!==r&&(this.holeDiameter=r),void 0!==n&&(this.holeDistToBottom=n),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==l&&(this.baseAttachmentHeight=l),void 0!==h&&(this.roofOverhang=h),void 0!==c&&(this.roofAngle=c),void 0!==u&&(this.rotation=u),void 0!==d&&(this.origin=d)}}class ZW{constructor(){this.type="parametric-model",this.name="chirpyChalet"}}class JW{}class eH{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p){this.sittingHeight=.45,this.backRestOffset=.1,this.backRestHeight=.7,this.width=.45,this.length=.45,this.thickness=.05,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.sittingHeight=e),void 0!==t&&(this.backRestOffset=t),void 0!==i&&(this.backRestHeight=i),void 0!==s&&(this.width=s),void 0!==r&&(this.length=r),void 0!==n&&(this.thickness=n),void 0!==o&&(this.nrOrnamentPlanks=o),void 0!==a&&(this.ornamentDepth=a),void 0!==l&&(this.filletRadius=l),void 0!==h&&(this.precision=h),void 0!==c&&(this.drawEdges=c),void 0!==u&&(this.rotation=u),void 0!==d&&(this.scale=d),void 0!==_&&(this.origin=_),void 0!==p&&(this.direction=p)}}class tH{constructor(){this.type="parametric-model",this.name="snakeChair"}}class iH extends Yz{}class sH{}class rH extends Yz{}class nH{}class oH{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class aH{}class lH{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f){this.height=.74,this.width=1,this.length=2,this.topThickness=.02,this.topOffset=.03,this.bottomThickness=.05,this.minFillet=.2,this.radiusLegTop=.03,this.radiusLegBottom=.01,this.nrLegPairs=2,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.topThickness=s),void 0!==r&&(this.topOffset=r),void 0!==n&&(this.bottomThickness=n),void 0!==o&&(this.minFillet=o),void 0!==a&&(this.radiusLegTop=a),void 0!==l&&(this.radiusLegBottom=l),void 0!==h&&(this.nrLegPairs=h),void 0!==c&&(this.precision=c),void 0!==u&&(this.drawEdges=u),void 0!==d&&(this.rotation=d),void 0!==_&&(this.scale=_),void 0!==p&&(this.origin=p),void 0!==f&&(this.direction=f)}}class hH{constructor(){this.type="parametric-model",this.name="elegantTable"}}class cH extends Yz{}class uH{}class dH extends Yz{}class _H extends Yz{}class pH{constructor(){this.index=0}}class fH{}class mH{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class gH{}class vH{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m,g){this.height=.4,this.width=1,this.length=1.2,this.chamfer=.01,this.topThickness=.05,this.topGlassOffset=.2,this.glassThickness=.005,this.glassHolderLength=.02,this.shelfTopOffset=.15,this.shelfThickness=.03,this.legWidth=.1,this.legDepth=.05,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.chamfer=s),void 0!==r&&(this.topThickness=r),void 0!==n&&(this.topGlassOffset=n),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassHolderLength=a),void 0!==l&&(this.shelfTopOffset=l),void 0!==h&&(this.shelfThickness=h),void 0!==c&&(this.legWidth=c),void 0!==u&&(this.legDepth=u),void 0!==d&&(this.precision=d),void 0!==_&&(this.drawEdges=_),void 0!==p&&(this.rotation=p),void 0!==f&&(this.scale=f),void 0!==m&&(this.origin=m),void 0!==g&&(this.direction=g)}}class xH{constructor(){this.type="parametric-model",this.name="goodCoffeeTable"}}class bH extends Yz{}class TH{}class yH extends Yz{}class SH extends Yz{}class CH extends Yz{}class EH{constructor(){this.index=0}}class AH{}class PH{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class IH{}class RH{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,_,p,f,m){this.height=.74,this.width=1,this.length=2,this.supportLength=.5,this.shelfHeight=.2,this.thickness=.05,this.glassThickness=.005,this.glassOffset=0,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.supportLength=s),void 0!==r&&(this.shelfHeight=r),void 0!==n&&(this.thickness=n),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassOffset=a),void 0!==l&&(this.nrOrnamentPlanks=l),void 0!==h&&(this.ornamentDepth=h),void 0!==c&&(this.filletRadius=c),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdges=d),void 0!==_&&(this.rotation=_),void 0!==p&&(this.scale=p),void 0!==f&&(this.origin=f),void 0!==m&&(this.direction=m)}}class MH{constructor(){this.type="parametric-model",this.name="snakeTable"}}class OH extends Yz{}class DH{}class wH extends Yz{}class NH{}class FH{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}!function(e){e.Aboreto="Aboreto",e.Bungee="Bungee",e.IndieFlower="IndieFlower",e.Lugrasimo="Lugrasimo",e.Orbitron="Orbitron",e.Roboto="Roboto",e.RobotoSlab="RobotoSlab",e.Silkscreen="Silkscreen",e.Tektur="Tektur",e.Workbench="Workbench"}(kz||(kz={})),function(e){e.Regular="Regular",e.Black="Black",e.Bold="Bold",e.ExtraBold="ExtraBold",e.Medium="Medium",e.SemiBold="SemiBold",e.BlackItalic="BlackItalic",e.BoldItalic="BoldItalic",e.Italic="Italic",e.Light="Light",e.LightItalic="LightItalic",e.MediumItalic="MediumItalic",e.Thin="Thin",e.ThinItalic="ThinItalic",e.ExtraLight="ExtraLight"}(Vz||(Vz={})),function(e){e.separatedExtrusion="separatedExtrusion",e.integratedExtrusion="integratedExtrusion",e.cutout="cutout"}(Uz||(Uz={})),function(e){e.compound="compound",e.cutout="originalCutout",e.cutoutInsideCharacter="cutoutInsideCharacter"}(Gz||(Gz={})),function(e){e.leftTop="leftTop",e.leftMiddle="leftMiddle",e.leftBottom="leftBottom",e.centerTop="centerTop",e.centerMiddle="centerMiddle",e.centerBottom="centerBottom",e.rightTop="rightTop",e.rightMiddle="rightMiddle",e.rightBottom="rightBottom"}(zz||(zz={}));const LH=[{key:"Aboreto",variants:["Regular"]},{key:"Bungee",variants:["Regular"]},{key:"IndieFlower",variants:["Regular"]},{key:"Lugrasimo",variants:["Regular"]},{key:"Orbitron",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Roboto",variants:["Black","BlackItalic","Bold","BoldItalic","Italic","Light","LightItalic","Medium","MediumItalic","Regular","Thin","ThinItalic"]},{key:"RobotoSlab",variants:["Black","Bold","ExtraBold","ExtraLight","Light","Medium","Regular","SemiBold","Thin"]},{key:"Silkscreen",variants:["Bold","Regular"]},{key:"Tektur",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Workbench",variants:["Regular"]}];class BH{constructor(e,t,i,s,r,n,o,a,l){this.text="bitbybit.dev",this.fontType=kz.Roboto,this.fontVariant=Vz.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.origin=[0,0,0],this.direction=[0,1,0],this.originAlignment=zz.centerMiddle,void 0!==e&&(this.text=e),void 0!==t&&(this.fontType=t),void 0!==i&&(this.fontVariant=i),void 0!==s&&(this.fontSize=s),void 0!==r&&(this.height=r),void 0!==n&&(this.rotation=n),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a),void 0!==l&&(this.originAlignment=l)}}class kH{constructor(e,t,i,s,r,n,o,a,l,h,c,u){this.facePlanar=!1,this.faceTextVar=Uz.separatedExtrusion,this.text="bitbybit.dev",this.fontType=kz.Roboto,this.fontVariant=Vz.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=zz.centerMiddle,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==i&&(this.faceTextVar=i),void 0!==s&&(this.text=s),void 0!==r&&(this.fontType=r),void 0!==n&&(this.fontVariant=n),void 0!==o&&(this.fontSize=o),void 0!==a&&(this.height=a),void 0!==l&&(this.rotation=l),void 0!==h&&(this.originParamU=h),void 0!==c&&(this.originParamV=c),void 0!==u&&(this.originAlignment=u)}}class VH{constructor(){this.type="parametric-model",this.name="text3d"}}class UH{constructor(){this.index=0}}class GH{}class zH{}class WH{constructor(e,t,i,s,r,n,o,a,l,h){this.faceTextVar=Uz.separatedExtrusion,this.text="bitbybit.dev",this.fontType=kz.Roboto,this.fontVariant=Vz.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=zz.centerMiddle,void 0!==e&&(this.faceTextVar=e),void 0!==t&&(this.text=t),void 0!==i&&(this.fontType=i),void 0!==s&&(this.fontVariant=s),void 0!==r&&(this.fontSize=r),void 0!==n&&(this.height=n),void 0!==o&&(this.rotation=o),void 0!==a&&(this.originParamU=a),void 0!==l&&(this.originParamV=l),void 0!==h&&(this.originAlignment=h)}}class HH{constructor(e,t,i){this.facePlanar=!1,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==i&&(this.definitions=i)}}class XH{constructor(e,t,i,s){this.uNumber=10,this.vNumber=10,this.height=.2,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==s&&(this.height=s)}}class YH{constructor(e,t,i,s,r,n,o){this.uNumber=10,this.vNumber=5,this.defaultHeight=.2,this.affectMinHeight=0,this.affectMaxHeight=1,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==t&&(this.affectorPoints=t),void 0!==i&&(this.uNumber=i),void 0!==s&&(this.vNumber=s),void 0!==r&&(this.affectMinHeight=r),void 0!==n&&(this.affectMaxHeight=n),void 0!==o&&(this.precision=o)}}class QH{constructor(){this.type="parametric-model",this.name="patternsFacePatternPyramidSimple"}}class jH{constructor(){this.index=0}}class KH{}class $H{}class qH{}class ZH{}class JH{constructor(){this.faceIndex=0}}class eX{constructor(){this.faceIndex=0,this.uIndex=0,this.vIndex=0}}class tX{constructor(){this.faceIndex=0,this.uIndex=0}}class iX{constructor(){this.faceIndex=0,this.vIndex=0}}class sX{}class rX{}var nX;!function(e){e.wire="wire",e.face="face",e.solid="solid"}(nX||(nX={}));class oX{static parse(e,t){var i;const s=[e],r=new Set;for(;s.length>0;){const e=s.pop();if("object"==typeof e&&null!==e&&!r.has(e))if(r.add(e),Array.isArray(e))for(let t=0;tt.id===e.shapes[r])))||void 0===i?void 0:i.shape)}for(const t in e)s.push(e[t])}}return e}}var aX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class lX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return aX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.arabicArchway",e);if(t){const e=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},e),{type:t.data.type,name:t.data.name,compound:t.compound,shapes:t.shapes,originalInputs:t.data.originalInputs})}}))}drawModel(e,t=.003){return aX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;this.materials||(this.materials=this.createMaterials(e.originalInputs.lod)),s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?e.originalInputs.lod===Bz.high&&"compound"===t?i(void 0):this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,t)=>{const s=o[t];if(s){if(s.parent=i,void 0!==this.materials[e]){const t=s.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}s.name=e,s.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=s}})),i}))}dispose(e){return aX(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}disposeMaterials(){this.materials&&Object.keys(this.materials).forEach((e=>{const t=this.materials[e];t&&t.dispose()}))}createMaterials(e){const t=new Jz;return e===Bz.high?t.compound=this.createBaseMaterial():t.compound=this.createOpaqueMaterial(),t.vasePartsCompound=this.createBaseMaterial(),t.glassPartsCompound=this.createGlassMaterial(),t.vaseBaseCompound=this.createBaseMaterial(),t}createOpaqueMaterial(){const e=new zg("opaqueMat"+Math.random(),this.context.scene);return e.albedoColor=new Ee(1,1,1),e.ambientColor=Ee.FromHexString("#ffffff"),e.metallic=0,e.roughness=.7,e.zOffset=1,e.backFaceCulling=!1,e.alpha=.3,e}createBaseMaterial(){const e=new zg("faceMaterial"+Math.random(),this.context.scene);return e.albedoColor=new Ee(1,1,1),e.ambientColor=Ee.FromHexString("#ffffff"),e.metallic=0,e.roughness=.7,e.zOffset=1,e}createGlassMaterial(){const e=new zg("faceGlassMaterial"+Math.random(),this.context.scene);return e.albedoColor=new Ee(0,0,.05),e.ambientColor=Ee.FromHexString("#ffffff"),e.metallic=.8,e.roughness=.1,e.zOffset=1,e.alpha=.5,e}}class hX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.serenitySwirl=new Hz(this.occWorkerManager,this.context,this.draw,this.occt),this.arabicArchway=new lX(this.occWorkerManager,this.context,this.draw,this.occt)}}var cX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class uX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return cX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.eternalLove",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e,t=.003){return cX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s}),n=new zg("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new Ee(1,.9,1),n.ambientColor=Ee.FromHexString("#ff00ff"),n.metallic=.8,n.roughness=.7,n.zOffset=1,r.getChildMeshes()[0].material=n,r.material=n,r.parent=i,i}))}dispose(e){return cX(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}class dX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.eternalLove=new uX(this.occWorkerManager,this.context,this.draw,this.occt)}}var _X=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class pX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return _X(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.calmCup",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}drawModel(e){return _X(this,void 0,void 0,(function*(){const t=new ha("brepMesh"+Math.random(),this.context.scene),i=new mU.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#bc7e5b",i.edgeWidth=.6*e.originalInputs.scale,i.precision=e.originalInputs.precision*e.originalInputs.scale;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),r=new zg("brepMaterial"+Math.random(),this.context.scene);return r.albedoColor=new Ee(1,1,1),r.ambientColor=Ee.FromHexString("#ffffff"),r.metallic=.8,r.roughness=.7,r.zOffset=2,s.getChildMeshes()[0].material=r,s.material=r,s.parent=t,t}))}dispose(e){return _X(this,void 0,void 0,(function*(){const t=[e.compound];yield this.occt.deleteShapes({shapes:t})}))}}var fX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class mX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return fX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.dragonCup",e);return t?{type:t.data.type,originalInputs:t.data.originalInputs,name:t.data.name,compound:t.compound}:void 0}))}getCompoundShape(e){return e.model.compound}drawModel(e){return fX(this,void 0,void 0,(function*(){const t=new ha("brepMesh"+Math.random(),this.context.scene),i=new mU.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#617bff",i.edgeWidth=.6*e.originalInputs.scale,i.precision=e.originalInputs.precision*e.originalInputs.scale;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),r=new zg("brepMaterial"+Math.random(),this.context.scene);return r.albedoColor=Ee.FromHexString("#2b00ff"),r.ambientColor=Ee.FromHexString("#ffffff"),r.metallic=.9,r.roughness=.3,r.zOffset=2,s.getChildMeshes()[0].material=r,s.material=r,s.parent=t,t}))}}class gX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.calmCup=new pX(this.occWorkerManager,this.context,this.draw,this.occt),this.dragonCup=new mX(this.occWorkerManager,this.context,this.draw,this.occt)}}var vX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class xX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return vX(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.phoneNest",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}drawOptions(e){return e}drawModel(e,t){return vX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#ffffff",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?("phone"===t&&(s.edgeColour="#000000"),this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)}))):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return vX(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="phone-nest-",t=new pW,i=Mz.wood3Material(this.context.scene,Math.PI/2,1);i.name=e+i.name,t.main=i;const s=Mz.glass(this.context.scene,"#000000");return s.name=e+s.name,t.phone=s,t}}class bX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.phoneNest=new xX(this.occWorkerManager,this.context,this.draw,this.occt)}}class TX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.vases=new hX(this.occWorkerManager,this.context,this.draw,this.occt),this.cups=new gX(this.occWorkerManager,this.context,this.draw,this.occt),this.medals=new dX(this.occWorkerManager,this.context,this.draw,this.occt),this.desktop=new bX(this.occWorkerManager,this.context,this.draw,this.occt)}}var yX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class SX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return yX(this,void 0,void 0,(function*(){void 0===this.materials&&(this.materials=this.createMaterials()),void 0===this.skin&&(this.skin=this.createSkin());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.zenHideout",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}drawModel(e,t=.003){return yX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;if(s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.06,s.precision=t,e.originalInputs.lod===Bz.high&&e.drawingPart){const t={},r=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((s=>{s.isVisible=!1,s.getChildMeshes().forEach((e=>e.isVisible=!1)),!0===this.skin[t]&&(s.visibility=e.originalInputs.skinOpacity,s.getChildMeshes().forEach((t=>t.visibility=e.originalInputs.skinOpacity))),i(s)}),(()=>{i(void 0)})):i(void 0)})))),n=yield Promise.all(r);Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const r=n[s];if(r){if(r.parent=i,void 0!==this.materials[e]){const t=r.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}r.name=e,r.isVisible=!0,r.getChildMeshes().forEach((e=>e.isVisible=!0)),t[e]=r}}))}else if(e.originalInputs.lod===Bz.middle){const t=new zg("brepMaterial"+Math.random(),this.context.scene);t.albedoColor=new Ee(0,0,0),t.metallic=0,t.roughness=.7,t.zOffset=2;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s});r.getChildMeshes()[0].material=t,r.material=t,r.parent=i}else e.originalInputs.lod===Bz.low&&(s.edgeColour="#e89668",s.edgeWidth=10,(yield this.draw.drawAnyAsync({entity:e.compound,options:s})).parent=i);return i}))}dispose(e){return yX(this,void 0,void 0,(function*(){const t=e.shapes.map((e=>e.shape));yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="zen-hideout-",t=new AW,i=new Lx(e+"windowGlassCompound",this.context.scene);i.alpha=.2,i.metallic=.9,i.roughness=.1,i.baseColor=new Ee(.9,.9,1),i.zOffset=2,t.windowGlassCompound=i;const s=new Lx(e+"windowGlassCompound",this.context.scene);s.metallic=.1,s.roughness=.8,s.baseColor=new Ee(.05,.05,.05),s.zOffset=2,t.windowFrameCompound=s;const r=new Lx(e+"glassFramesCompound",this.context.scene);r.metallic=.1,r.roughness=.8,r.baseColor=new Ee(0,0,0),r.zOffset=2,t.glassFramesCompound=r;const n=Mz.metal1(this.context.scene,0,.3);t.roofCoverFirstCompound=n,t.roofCoverSecondCompound=n;const o=Mz.wood1Material(this.context.scene,0,1);t.beamsCompound=o,t.columnsCompound=o;const a=Mz.woodenPlanks(this.context.scene,0,1);t.firstFloorExteriorPanelsCompound=a;const l=new Lx(e+"firstFloorInteriorPanelsCompound",this.context.scene);l.metallic=.1,l.roughness=.8,l.baseColor=new Ee(.1,.1,.1),l.zOffset=2,t.firstFloorInteriorPanelsCompound=l;const h=Mz.wood3Material(this.context.scene,Math.PI/2,1);t.roofExteriorPanelsCompound=h;const c=new Lx(e+"roofInteriorPanelsCompound",this.context.scene);c.metallic=.1,c.roughness=.8,c.baseColor=new Ee(.3,.3,.3),c.zOffset=2,t.roofInteriorPanelsCompound=c;const u=Mz.wood2Material(this.context.scene,0,.5);t.floorCompound=u;const d=new Lx(e+"ceilingCompound",this.context.scene);d.metallic=.3,d.roughness=.7,d.baseColor=new Ee(1,1,1),d.zOffset=2,t.ceilingCompound=d;const _=Mz.brushedConcrete(this.context.scene,0,1);return t.stairsCompound=_,t}createSkin(){return{windowGlassCompound:!0,glassFramesCompound:!1,windowFrameCompound:!1,beamsCompound:!1,columnsCompound:!1,firstFloorExteriorPanelsCompound:!0,firstFloorInteriorPanelsCompound:!0,roofExteriorPanelsCompound:!0,roofInteriorPanelsCompound:!0,roofCoverFirstCompound:!0,roofCoverSecondCompound:!0,floorCompound:!0,ceilingCompound:!0,stairsCompound:!1}}}class CX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.zenHideout=new SX(this.occWorkerManager,this.context,this.draw,this.occt)}}class EX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.houses=new CX(this.occWorkerManager,this.context,this.draw,this.occt)}}class AX{lodEnum(e){return e.lod}}var PX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class IX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return PX(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.top.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.elegantTable",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getLegShapes(e){return e.model.legParts.map((e=>e.shapes.leg))}getLegShapeByIndex(e){return e.index>=0&&e.indexe.bottomCenter))}getLegTopPoints(e){return e.model.legParts.map((e=>e.topCenter))}drawOptions(e){return e}drawModel(e,t){return PX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#bc7e5b",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return PX(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="elegant-table-",t=new uH,i=Mz.wood3Material(this.context.scene,Math.PI/2,2);i.name=e+i.name,t.top=i;const s=Mz.wood1Material(this.context.scene,Math.PI/2,2);s.name=e+i.name,t.topBase=s;const r=Mz.wood1Material(this.context.scene,0,1);return r.name=e+i.name,t.legs=r,t}}var RX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class MX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return RX(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.top.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.goodCoffeeTable",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getLegShapes(e){return e.model.legParts.map((e=>e.shapes.leg))}getLegShapeByIndex(e){return e.index>=0&&e.indexe.bottomCenter))}getLegTopPoints(e){return e.model.legParts.map((e=>e.topCenter))}drawOptions(e){return e}drawModel(e,t){return RX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#bc7e5b",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return RX(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="good-coffee-table-",t=new TH,i=Mz.wood3Material(this.context.scene,Math.PI/2,2);i.name=e+i.name,t.top=i,t.legs=i,t.shelf=i;const s=Mz.glass(this.context.scene,"#000000");return s.name=e+i.name,t.topGlass=s,t}}var OX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class DX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return OX(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.snakeTable",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getGlassShape(e){return e.model.mainPart.shapes.glass}getMainShape(e){return e.model.mainPart.shapes.main}getTopCenterPoint(e){return e.model.mainPart.topCenter}drawOptions(e){return e}drawModel(e,t){return OX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#000000",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return OX(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e="snake-table-",t=new DH,i=Mz.roughPlastic(this.context.scene,"#ffffff");i.name=e+i.name,t.main=i;const s=Mz.glass(this.context.scene,"#000000");return s.name=e+s.name,t.glass=s,t}}class wX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.elegantTable=new IX(this.occWorkerManager,this.context,this.draw,this.occt),this.goodCoffeeTable=new MX(this.occWorkerManager,this.context,this.draw,this.occt),this.snakeTable=new DX(this.occWorkerManager,this.context,this.draw,this.occt)}}var NX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class FX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return NX(this,void 0,void 0,(function*(){void 0!==this.materials&&void 0!==this.context.scene.materials.find((e=>e.name===this.materials.main.name))||(this.materials=this.createMaterials());const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.things.snakeChair",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}getCompoundShape(e){return e.model.compound}getSittingWireShape(e){return e.model.mainPart.shapes.sittingWire}getSittingAreaCenterPoint(e){return e.model.mainPart.sittingCenter}drawOptions(e){return e}drawModel(e,t){return NX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;t?(s.drawEdges=t.drawEdges,s.drawFaces=t.drawFaces,s.edgeColour=t.edgeColour,s.edgeWidth=t.edgeWidth,s.precision=t.precision):(s.faceOpacity=0,s.drawEdges=e.originalInputs.drawEdges,s.edgeColour="#000000",s.edgeWidth=.06*e.originalInputs.scale,s.precision=e.originalInputs.precision*e.originalInputs.scale);const r={},n=Object.keys(e.drawingPart.shapes).map((t=>new Promise((i=>{e.drawingPart.shapes[t]?this.draw.drawAnyAsync({entity:e.drawingPart.shapes[t],options:s}).then((e=>{e.isVisible=!1,e.getChildMeshes().forEach((e=>e.isVisible=!1)),i(e)}),(()=>{i(void 0)})):i(void 0)})))),o=yield Promise.all(n);return Object.keys(e.drawingPart.shapes).forEach(((e,s)=>{const n=o[s];if(n){if(n.parent=i,t&&t.drawFaces){const i=n.getChildMeshes()[0];void 0!==i&&(i.material=this.materials[e]),t[e+"Material"]&&(i.material=t[e+"Material"])}else if(!t&&void 0!==this.materials[e]){const t=n.getChildMeshes()[0];void 0!==t&&(t.material=this.materials[e])}n.name=e,n.isVisible=!0,n.getChildMeshes().forEach((e=>e.isVisible=!0)),r[e]=n}})),i}))}dispose(e){return NX(this,void 0,void 0,(function*(){const t=[...e.shapes.map((e=>e.shape))];yield this.occt.deleteShapes({shapes:t})}))}createMaterials(){const e=new sH,t=Mz.roughPlastic(this.context.scene,"#ffffff");return t.name="snake-chair-"+t.name,e.main=t,e}}class LX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.snakeChair=new FX(this.occWorkerManager,this.context,this.draw,this.occt)}}class BX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.chairs=new LX(this.occWorkerManager,this.context,this.draw,this.occt),this.tables=new wX(this.occWorkerManager,this.context,this.draw,this.occt)}}class kX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s,this.kidsCorner=new Lz(this.occWorkerManager,this.context,this.draw,this.occt),this.threeDPrinting=new TX(this.occWorkerManager,this.context,this.draw,this.occt),this.architecture=new EX(this.occWorkerManager,this.context,this.draw,this.occt),this.furniture=new BX(this.occWorkerManager,this.context,this.draw,this.occt),this.enums=new AX}}var VX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class UX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}create(e){return VX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.text3d",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createTextOnFace(e){return VX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.text3dFace",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createTextsOnFace(e){return VX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.texts3dFace",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}definition3dTextOnFace(e){return e}drawModel(e,t=.003){return VX(this,void 0,void 0,(function*(){const i=new ha("brepMesh"+Math.random(),this.context.scene),s=new mU.DrawOcctShapeOptions;s.faceOpacity=0,s.edgeColour="#bc7e5b",s.edgeWidth=.6,s.precision=t;const r=yield this.draw.drawAnyAsync({entity:e.compound,options:s}),n=new zg("brepMaterial"+Math.random(),this.context.scene);return n.albedoColor=new Ee(1,1,1),n.ambientColor=Ee.FromHexString("#ffffff"),n.metallic=0,n.roughness=.7,n.zOffset=1,r.getChildMeshes()[0].material=n,r.material=n,r.parent=i,i}))}getCompoundShape(e){return e.model.compound}getCharacterShape(e){if(e.index<0||e.index>=e.model.characterParts.length)throw new Error("Index is out of bounds.");return e.model.characterParts[e.index].shapes.compound}getCharacterShapes(e){return e.model.characterParts.map((e=>e.shapes.compound))}getCharacterCenterCoordinates(e){return e.model.characterCenterCoordinates}getFaceCutout(e){if(e.model.faceParts){const t=e.model.faceParts.filter((e=>e.type===Gz.cutout)).map((e=>e.shapes.face));if(t.length>0)return t[0];throw new Error("No cutout was found.")}throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getAllFacesOfCutout(e){if(e.model.faceParts)return e.model.faceParts.filter((e=>e.type===Gz.cutout||e.type===Gz.cutoutInsideCharacter)).map((e=>e.shapes.face));throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getCutoutsInsideCharacters(e){if(e.model.faceParts)return e.model.faceParts.filter((e=>e.type===Gz.cutoutInsideCharacter)).map((e=>e.shapes.face));throw new Error("It seems this text was not created on the face, so there is no face cutout.")}getAdvanceWidth(e){return e.model.advanceWidth}}var GX,zX=function(e,t,i,s){return new(i||(i=Promise))((function(r,n){function o(e){try{l(s.next(e))}catch(e){n(e)}}function a(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(o,a)}l((s=s.apply(e,t||[])).next())}))};class WX{constructor(e,t,i,s){this.occWorkerManager=e,this.context=t,this.draw=i,this.occt=s}createPyramidSimple(e){return zX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.pyramidSimple",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}createPyramidSimpleAffectors(e){return zX(this,void 0,void 0,(function*(){const t=yield this.occWorkerManager.genericCallToWorkerPromise("plugins.advanced.pyramidSimpleAffectors",e),i=oX.parse(t.data,t.shapes);return Object.assign(Object.assign({},i),{type:t.data.type,name:t.data.name,shapes:t.shapes,compound:t.compound})}))}drawModel(e){return zX(this,void 0,void 0,(function*(){const t=new ha("brepMesh"+Math.random(),this.context.scene),i=new mU.DrawOcctShapeOptions;i.faceOpacity=0,i.edgeColour="#bc7e5b",i.edgeWidth=1,i.precision=e.originalInputs.precision;const s=yield this.draw.drawAnyAsync({entity:e.compound,options:i}),r=new zg("brepMaterial"+Math.random(),this.context.scene);return r.albedoColor=new Ee(1,1,1),r.ambientColor=Ee.FromHexString("#ffffff"),r.metallic=.3,r.roughness=.6,r.zOffset=2,s.getChildMeshes()[0].material=r,s.material=r,s.parent=t,t}))}getCompoundShape(e){return e.model.compound}getCompoundShapeOnFace(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex&&t.vIndex===e.vIndex));if(t)return t.shapes.compound;throw new Error("Cell does not exist on the face")}throw new Error("Cell u or v index is out of range")}throw new Error("Face index is out of range")}getAllPyramidCells(e){return e.model.faceParts.map((e=>e.cells)).flat()}getAllPyramidCellsOnFace(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex));throw new Error("Face index is out of range")}getAllPyramidUCellsOnFaceAtV(e){if(e.model.faceParts&&e.faceIndext.vIndex===e.vIndex));throw new Error("Face index is out of range")}getCellOnIndex(e){if(e.model.faceParts&&e.faceIndext.uIndex===e.uIndex&&t.vIndex===e.vIndex));if(t)return t;throw new Error("Cell does not exist on the face")}throw new Error("Cell u or v index is out of range")}throw new Error("Face index is out of range")}getTopPointsOfCells(e){return e.cells.map((e=>e.topPoint))}getCenterPointsOfCells(e){return e.cells.map((e=>e.centerPoint))}getCornerPointsOfCells(e){return e.cells.map((e=>[e.cornerPoint1,e.cornerPoint2,e.cornerPoint3,e.cornerPoint4].filter((e=>void 0!==e))))}getCornerPointOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.cornerPoint1:1===e.index?t.cornerPoint2:2===e.index?t.cornerPoint3:3===e.index?t.cornerPoint4:void 0));throw new Error("Corner index is out of range")}getCornerNormalOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.cornerNormal1:1===e.index?t.cornerNormal2:2===e.index?t.cornerNormal3:3===e.index?t.cornerNormal4:void 0));throw new Error("Corner index is out of range")}getCornerNormalsOfCells(e){return e.cells.map((e=>[e.cornerNormal1,e.cornerNormal2,e.cornerNormal3,e.cornerNormal4].filter((e=>void 0!==e))))}getCompoundShapesOfCells(e){return e.cells.map((e=>e.shapes.compound))}getFaceShapesOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.shapes.face1:1===e.index?t.shapes.face2:2===e.index?t.shapes.face3:3===e.index?t.shapes.face4:void 0));throw new Error("Face index is out of range")}getWireShapesOfCells(e){if(e.index>=0&&e.index<=3)return e.cells.map((t=>0===e.index?t.shapes.wire1:1===e.index?t.shapes.wire2:2===e.index?t.shapes.wire3:3===e.index?t.shapes.wire4:void 0));throw new Error("Wire index is out of range")}getStartPolylineWireU(e){if(e.faceIndex>=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex=0&&e.faceIndex0&&r[r.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]0&&"string"!=typeof t[e])for(var i=function(i){var s=t[e][i];"object"==typeof s&&null!==s&&s.then&&(s.then((function(s){return t[e][i]=s,s})),n.push(t[e][i]))},s=0;s0&&e.startedAsyncTask(i,s,"#eeeeff"),n.length>0?[2,Promise.all(n).then((function(t){return e.finishedAsyncTask(i,s),t}))]:[2,null]}))}))},e.finishedAsyncTask=function(e,t){},e.startedAsyncTask=function(e,t,i){},e.runtimeValidation=function(e,t){},e.validate=function(e,t,i){},e.handleBlockException=function(e,t){},e.errorHappened=function(e,t,i){},e.updateListInputs=function(e){Object.keys(e).forEach((function(t){if(Array.isArray(e[t])){var i=[];e[t].forEach((function(e){if(e&&e.result){var t=e.result;e.transformers&&e.transformers.length&&e.transformers.forEach((function(e){e.type===KX.flat&&(t=t.flat())})),t instanceof Array?i.push.apply(i,t):i.push(t)}})),e[t]=i}}))},e.executeBasedOnTypeAsync=function(e,t,i){return qX(this,void 0,void 0,(function(){var s,r,n,o,a,l,h,c,u;return ZX(this,(function(d){switch(d.label){case 0:if(t)return[3,5];l=this.performActionOnAllVariationsSimplified(e,i),d.label=1;case 1:return d.trys.push([1,3,,4]),[4,Promise.all(l)];case 2:return s=d.sent(),[3,4];case 3:throw r=d.sent(),new Error(r);case 4:return[3,9];case 5:if(!t)return[3,9];for(n=Object.keys(e),o=n.map((function(t){return e[t]})),a=this.normalizeListsToEqualLength(o),l=[],h=function(e){var t={};n.forEach((function(i,s){t[i]=o[s][e]})),l.push(i(t))},c=0;ct&&(t=e.length)})),t},e.drawNodeMeshes=function(e,t){return qX(this,void 0,void 0,(function(){var i,s=this;return ZX(this,(function(r){switch(r.label){case 0:return i=e.map((function(e){return qX(s,void 0,void 0,(function(){var i,s,r;return ZX(this,(function(n){switch(n.label){case 0:return i=e.result,s=[],i instanceof Array&&i.length>0&&i[0]&&i[0].hash?i.forEach((function(e){var i=t.draw.drawAnyAsync({entity:e,options:void 0});s.push(i)})):(r=t.draw.drawAnyAsync({entity:i,options:void 0}),s.push(r)),[4,Promise.all(s)];case 1:return[2,n.sent()]}}))}))})),[4,Promise.all(i)];case 1:return r.sent(),[2]}}))}))},e}(),iY=function(){function e(e){this.context=e}return e.prototype.handleTags=function(e,t,i,s){var r=this;!t&&this.context.tagBag.length>0&&this.context.tagBag.find((function(e){return e.needsUpdate}))&&(t=!0),t&&this.context.tagBag.length>0&&this.context.tagBag.forEach((function(t){var n=document.querySelector("#"+t.id),o=new _e(t.position[0],t.position[1],t.position[2]);n.textContent=t.text;var a=i.getRenderWidth()/2,l=i.getRenderHeight()/2,h=_e.Project(o,me.IdentityReadOnly,s.getTransformMatrix(),e.viewport.toGlobal(a,l)),c=_e.Distance(e.position,o),u=t.adaptDepth?Math.ceil(r.context.remap(c,0,100,t.size,3)):t.size;h.x>0&&h.x0&&h.y0&&h.z<1&&u>3?n.style="".concat("position: absolute; transform: translate(-50%, -50%); font-weight: 400;"," font-size: ").concat(u,"px; color: ").concat(t.colour,"; left: ").concat(h.x,"px; top: ").concat(h.y,"px; display: inline;"):n.style="display: none;"}))},e.prototype.removeTagsIfNeeded=function(){this.tagsExist()&&this.context.tagBag.forEach((function(e){var t=document.getElementById(e.id);t.parentNode.removeChild(t)})),this.context.tagBag=[]},e.prototype.tagsExist=function(){return this.context.tagBag.length>0},e}(),sY=function(){return sY=Object.assign||function(e){for(var t,i=1,s=arguments.length;i0&&r[r.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]0?JSON.stringify(s):"{}",';\n let bitbybitRunnerResult = {};\n const runContext = "runner";\n const mockBitbybitRunnerInputs = (inputs) => {\n }\n const getBitbybitRunnerInputs = () => {\n return bitbybitRunnerInputs;\n }\n const setBitbybitRunnerResult = (result) => {\n bitbybitRunnerResult = result;\n }\n const setBitbybitRunnerResultValue = (prop, value) => {\n bitbybitRunnerResult[prop] = value;\n }\n \n const bitbybit = this.bitbybit;\n const Bit = this.Bit;\n Bit.mockBitbybitRunnerInputs = mockBitbybitRunnerInputs;\n Bit.getBitbybitRunnerInputs = getBitbybitRunnerInputs;\n Bit.setBitbybitRunnerResult = setBitbybitRunnerResult;\n Bit.setBitbybitRunnerResultValue = setBitbybitRunnerResultValue;\n \n const BitByBit = this.BitByBit;\n const errorHandle = this.errorHandle;\n const BABYLON = this.BABYLON;\n BABYLON.GUI = this.GUI;\n const resolve = this.resolve;\n \n await ').concat(r.script,"\n if(bitbybitRunnerResult !== undefined){\n resolve(bitbybitRunnerResult);\n } else {\n resolve(undefined);\n }\n }\n \n bitbybitRunnerStart();\n "),a={HS:tY,BitByBitContextHelperService:this.bitbybit.context},l={bitbybit:this.bitbybit,BABYLON:e,GUI:t,Bit:aY,BitByBit:a,errorHandle:n},[2,new Promise((function(e){return l.resolve=e,new Function(o).apply(l)}))]}))}))},i.prototype.resetRunnerContext=function(){if(this.bitbybit.context.scene.dispose(),this.options.enablePhysics){var e=new BA(!0,this.havok);this.bitbybit.context.havokPlugin=e}var t=document.getElementById(this.options.canvasId),i=this.bitbybit.context.engine;this.initScene(i,t),this.tagService.removeTagsIfNeeded(),this.bitbybit.context.intervalBag.forEach((function(e){return clearInterval(e)})),this.bitbybit.context.timeoutBag.forEach((function(e){return clearTimeout(e)})),this.bitbybit.context.intervalBag.length=0,this.bitbybit.context.timeoutBag.length=0,this.bitbybit.context.renderLoopBag.length=0,this.bitbybit.context.keyPressBag.length=0,this.bitbybit.context.keyDownBag.length=0,this.bitbybit.context.keyUpBag.length=0},i.prototype.cleanOCCTCache=function(){return rY(this,void 0,void 0,(function(){return nY(this,(function(e){return[2,this.bitbybit.occtWorkerManager.cleanAllCache()]}))}))},i.prototype.cleanJSCADCache=function(){return rY(this,void 0,void 0,(function(){return nY(this,(function(e){return[2,this.bitbybit.jscadWorkerManager.cleanAllCache()]}))}))},i}()})(),s})())); \ No newline at end of file diff --git a/wasm/bitbybit-dev-occt.06080bd9.wasm b/wasm/bitbybit-dev-occt.c3039273.wasm similarity index 71% rename from wasm/bitbybit-dev-occt.06080bd9.wasm rename to wasm/bitbybit-dev-occt.c3039273.wasm index d242694..b8b611a 100644 Binary files a/wasm/bitbybit-dev-occt.06080bd9.wasm and b/wasm/bitbybit-dev-occt.c3039273.wasm differ diff --git a/workers/bitbybit-jscad-webworker.js b/workers/bitbybit-jscad-webworker.js index c1e688e..44e8ad1 100644 --- a/workers/bitbybit-jscad-webworker.js +++ b/workers/bitbybit-jscad-webworker.js @@ -1 +1 @@ -(()=>{var e={263:(e,t,i)=>{"use strict";let s;function r(){return s}i.r(t),i.d(t,{default:()=>r}),function e(t,i,s){function r(o,a){if(!i[o]){if(!t[o]){if(n)return n(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var h=i[o]={exports:{}};t[o][0].call(h.exports,(function(e){return r(t[o][1][e]||e)}),h,h.exports,e,t,i,s)}return i[o].exports}for(var n=void 0,o=0;oe.reduce(((e,t)=>Array.isArray(t)?e.concat(s(t)):e.concat(t)),[]);t.exports=s},{}],3:[function(e,t,i){t.exports=(e,t)=>e-t},{}],4:[function(e,t,i){t.exports=e=>{if(Array.isArray(e)&&0!==e.length)return e[0]}},{}],5:[function(e,t,i){t.exports={flatten:e("./flatten"),fnNumberSort:e("./fnNumberSort"),head:e("./head"),insertSorted:e("./insertSorted"),nth:e("./nth"),padToLength:e("./padToLength"),toArray:e("./toArray")}},{"./flatten":2,"./fnNumberSort":3,"./head":4,"./insertSorted":6,"./nth":7,"./padToLength":8,"./toArray":9}],6:[function(e,t,i){t.exports=(e,t,i)=>{let s=0,r=e.length;for(;r>s;){const n=Math.floor((s+r)/2);i(t,e[n])>0?s=n+1:r=n}return e.splice(s,0,t),e}},{}],7:[function(e,t,i){t.exports=(e,t)=>{if(Array.isArray(e)&&!(e.length{for(e=e.slice();e.lengthArray.isArray(e)?e:null==e?[]:[e]},{}],10:[function(e,t,i){t.exports={dxfHeaders:function(){return" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1027\n 9\n$ACADMAINTVER\n 70\n8\n 9\n$DWGCODEPAGE\n 3\nANSI_1252\n 9\n$LASTSAVEDBY\n 1\nunknown\n 9\n$REQUIREDVERSIONS\n160\n0\n 9\n$INSBASE\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$EXTMIN\n 10\n1e+20\n 20\n1e+20\n 30\n1e+20\n 9\n$EXTMAX\n 10\n-1e+20\n 20\n-1e+20\n 30\n-1e+20\n 9\n$LIMMIN\n 10\n0.0\n 20\n0.0\n 9\n$LIMMAX\n 10\n12.0\n 20\n9.0\n 9\n$ORTHOMODE\n 70\n0\n 9\n$REGENMODE\n 70\n1\n 9\n$FILLMODE\n 70\n1\n 9\n$QTEXTMODE\n 70\n0\n 9\n$MIRRTEXT\n 70\n0\n 9\n$LTSCALE\n 40\n1.0\n 9\n$ATTMODE\n 70\n1\n 9\n$TEXTSIZE\n 40\n0.2\n 9\n$TRACEWID\n 40\n0.05\n 9\n$TEXTSTYLE\n 7\nNotes\n 9\n$CLAYER\n 8\n0\n 9\n$CELTYPE\n 6\nByLayer\n 9\n$CECOLOR\n 62\n256\n 9\n$CELTSCALE\n 40\n1.0\n 9\n$DISPSILH\n 70\n0\n 9\n$DIMSCALE\n 40\n1.0\n 9\n$DIMASZ\n 40\n3.0\n 9\n$DIMEXO\n 40\n1.5\n 9\n$DIMDLI\n 40\n6.0\n 9\n$DIMRND\n 40\n0.0\n 9\n$DIMDLE\n 40\n0.0\n 9\n$DIMEXE\n 40\n3.0\n 9\n$DIMTP\n 40\n0.0\n 9\n$DIMTM\n 40\n0.0\n 9\n$DIMTXT\n 40\n3.0\n 9\n$DIMCEN\n 40\n3.0\n 9\n$DIMTSZ\n 40\n0.0\n 9\n$DIMTOL\n 70\n0\n 9\n$DIMLIM\n 70\n0\n 9\n$DIMTIH\n 70\n0\n 9\n$DIMTOH\n 70\n0\n 9\n$DIMSE1\n 70\n0\n 9\n$DIMSE2\n 70\n0\n 9\n$DIMTAD\n 70\n1\n 9\n$DIMZIN\n 70\n3\n 9\n$DIMBLK\n 1\n\n 9\n$DIMASO\n 70\n1\n 9\n$DIMSHO\n 70\n1\n 9\n$DIMPOST\n 1\n\n 9\n$DIMAPOST\n 1\n\n 9\n$DIMALT\n 70\n0\n 9\n$DIMALTD\n 70\n2\n 9\n$DIMALTF\n 40\n25.4\n 9\n$DIMLFAC\n 40\n1.0\n 9\n$DIMTOFL\n 70\n0\n 9\n$DIMTVP\n 40\n0.0\n 9\n$DIMTIX\n 70\n0\n 9\n$DIMSOXD\n 70\n0\n 9\n$DIMSAH\n 70\n0\n 9\n$DIMBLK1\n 1\n\n 9\n$DIMBLK2\n 1\n\n 9\n$DIMSTYLE\n 2\nCivil-Metric\n 9\n$DIMCLRD\n 70\n0\n 9\n$DIMCLRE\n 70\n0\n 9\n$DIMCLRT\n 70\n0\n 9\n$DIMTFAC\n 40\n1.0\n 9\n$DIMGAP\n 40\n2.0\n 9\n$DIMJUST\n 70\n0\n 9\n$DIMSD1\n 70\n0\n 9\n$DIMSD2\n 70\n0\n 9\n$DIMTOLJ\n 70\n1\n 9\n$DIMTZIN\n 70\n0\n 9\n$DIMALTZ\n 70\n0\n 9\n$DIMALTTZ\n 70\n0\n 9\n$DIMUPT\n 70\n0\n 9\n$DIMDEC\n 70\n2\n 9\n$DIMTDEC\n 70\n2\n 9\n$DIMALTU\n 70\n2\n 9\n$DIMALTTD\n 70\n2\n 9\n$DIMTXSTY\n 7\nStandard\n 9\n$DIMAUNIT\n 70\n0\n 9\n$DIMADEC\n 70\n2\n 9\n$DIMALTRND\n 40\n0.0\n 9\n$DIMAZIN\n 70\n2\n 9\n$DIMDSEP\n 70\n46\n 9\n$DIMATFIT\n 70\n3\n 9\n$DIMFRAC\n 70\n1\n 9\n$DIMLDRBLK\n 1\n\n 9\n$DIMLUNIT\n 70\n2\n 9\n$DIMLWD\n 70\n-2\n 9\n$DIMLWE\n 70\n-2\n 9\n$DIMTMOVE\n 70\n0\n 9\n$DIMFXL\n 40\n1.0\n 9\n$DIMFXLON\n 70\n0\n 9\n$DIMJOGANG\n 40\n0.785398163397\n 9\n$DIMTFILL\n 70\n0\n 9\n$DIMTFILLCLR\n 70\n0\n 9\n$DIMARCSYM\n 70\n0\n 9\n$DIMLTYPE\n 6\n\n 9\n$DIMLTEX1\n 6\n\n 9\n$DIMLTEX2\n 6\n\n 9\n$DIMTXTDIRECTION\n 70\n0\n 9\n$LUNITS\n 70\n2\n 9\n$LUPREC\n 70\n4\n 9\n$SKETCHINC\n 40\n0.1\n 9\n$FILLETRAD\n 40\n0.0\n 9\n$AUNITS\n 70\n4\n 9\n$AUPREC\n 70\n5\n 9\n$MENU\n 1\n.\n 9\n$ELEVATION\n 40\n0.0\n 9\n$PELEVATION\n 40\n0.0\n 9\n$THICKNESS\n 40\n0.0\n 9\n$LIMCHECK\n 70\n0\n 9\n$CHAMFERA\n 40\n0.0\n 9\n$CHAMFERB\n 40\n0.0\n 9\n$CHAMFERC\n 40\n0.0\n 9\n$CHAMFERD\n 40\n0.0\n 9\n$SKPOLY\n 70\n0\n 9\n$TDCREATE\n 40\n2457986.69756\n 9\n$TDUCREATE\n 40\n2455631.2632\n 9\n$TDUPDATE\n 40\n2457986.69756\n 9\n$TDUUPDATE\n 40\n2456436.43179\n 9\n$TDINDWG\n 40\n0.0003490741\n 9\n$TDUSRTIMER\n 40\n0.0003487153\n 9\n$USRTIMER\n 70\n1\n 9\n$ANGBASE\n 50\n0.0\n 9\n$ANGDIR\n 70\n0\n 9\n$PDMODE\n 70\n0\n 9\n$PDSIZE\n 40\n0.0\n 9\n$PLINEWID\n 40\n0.0\n 9\n$SPLFRAME\n 70\n0\n 9\n$SPLINETYPE\n 70\n6\n 9\n$SPLINESEGS\n 70\n8\n 9\n$HANDSEED\n 5\n5C7\n 9\n$SURFTAB1\n 70\n6\n 9\n$SURFTAB2\n 70\n6\n 9\n$SURFTYPE\n 70\n6\n 9\n$SURFU\n 70\n6\n 9\n$SURFV\n 70\n6\n 9\n$UCSBASE\n 2\n\n 9\n$UCSNAME\n 2\n\n 9\n$UCSORG\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSXDIR\n 10\n1.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSYDIR\n 10\n0.0\n 20\n1.0\n 30\n0.0\n 9\n$UCSORTHOREF\n 2\n\n 9\n$UCSORTHOVIEW\n 70\n0\n 9\n$UCSORGTOP\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGBOTTOM\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGLEFT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGRIGHT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGFRONT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGBACK\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSBASE\n 2\n\n 9\n$PUCSNAME\n 2\n\n 9\n$PUCSORG\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSXDIR\n 10\n1.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSYDIR\n 10\n0.0\n 20\n1.0\n 30\n0.0\n 9\n$PUCSORTHOREF\n 2\n\n 9\n$PUCSORTHOVIEW\n 70\n0\n 9\n$PUCSORGTOP\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGBOTTOM\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGLEFT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGRIGHT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGFRONT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGBACK\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$USERI1\n 70\n0\n 9\n$USERI2\n 70\n0\n 9\n$USERI3\n 70\n0\n 9\n$USERI4\n 70\n0\n 9\n$USERI5\n 70\n0\n 9\n$USERR1\n 40\n0.0\n 9\n$USERR2\n 40\n0.0\n 9\n$USERR3\n 40\n0.0\n 9\n$USERR4\n 40\n0.0\n 9\n$USERR5\n 40\n0.0\n 9\n$WORLDVIEW\n 70\n1\n 9\n$SHADEDGE\n 70\n3\n 9\n$SHADEDIF\n 70\n70\n 9\n$TILEMODE\n 70\n1\n 9\n$MAXACTVP\n 70\n64\n 9\n$PINSBASE\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PLIMCHECK\n 70\n0\n 9\n$PEXTMIN\n 10\n0.628866766397\n 20\n0.799999952316\n 30\n0.0\n 9\n$PEXTMAX\n 10\n9.02886638493\n 20\n7.19999957085\n 30\n0.0\n 9\n$PLIMMIN\n 10\n-0.700541819174\n 20\n-0.228100386192\n 9\n$PLIMMAX\n 10\n10.2994579405\n 20\n8.27189937351\n 9\n$UNITMODE\n 70\n0\n 9\n$VISRETAIN\n 70\n1\n 9\n$PLINEGEN\n 70\n0\n 9\n$PSLTSCALE\n 70\n1\n 9\n$TREEDEPTH\n 70\n3020\n 9\n$CMLSTYLE\n 2\nStandard\n 9\n$CMLJUST\n 70\n0\n 9\n$CMLSCALE\n 40\n1.0\n 9\n$PROXYGRAPHICS\n 70\n1\n 9\n$MEASUREMENT\n 70\n1\n 9\n$CELWEIGHT\n370\n-1\n 9\n$ENDCAPS\n280\n0\n 9\n$JOINSTYLE\n280\n0\n 9\n$LWDISPLAY\n290\n0\n 9\n$INSUNITS\n 70\n4\n 9\n$HYPERLINKBASE\n 1\n\n 9\n$STYLESHEET\n 1\n\n 9\n$XEDIT\n290\n1\n 9\n$CEPSNTYPE\n380\n0\n 9\n$PSTYLEMODE\n290\n1\n 9\n$FINGERPRINTGUID\n 2\n{39DB1BDD-BC6C-46D3-A333-DFCC0DC4782D}\n 9\n$VERSIONGUID\n 2\n{69EEBB2D-7039-498F-9366-3F994E4A07E7}\n 9\n$EXTNAMES\n290\n1\n 9\n$PSVPSCALE\n 40\n0.0\n 9\n$OLESTARTUP\n290\n0\n 9\n$SORTENTS\n280\n127\n 9\n$INDEXCTL\n280\n0\n 9\n$HIDETEXT\n280\n1\n 9\n$XCLIPFRAME\n280\n0\n 9\n$HALOGAP\n280\n0\n 9\n$OBSCOLOR\n 70\n257\n 9\n$OBSLTYPE\n280\n0\n 9\n$INTERSECTIONDISPLAY\n280\n0\n 9\n$INTERSECTIONCOLOR\n 70\n257\n 9\n$DIMASSOC\n280\n2\n 9\n$PROJECTNAME\n 1\n\n 9\n$CAMERADISPLAY\n290\n0\n 9\n$LENSLENGTH\n 40\n50.0\n 9\n$CAMERAHEIGHT\n 40\n0.0\n 9\n$STEPSPERSEC\n 40\n2.0\n 9\n$STEPSIZE\n 40\n6.0\n 9\n$3DDWFPREC\n 40\n2.0\n 9\n$PSOLWIDTH\n 40\n0.25\n 9\n$PSOLHEIGHT\n 40\n4.0\n 9\n$LOFTANG1\n 40\n1.57079632679\n 9\n$LOFTANG2\n 40\n1.57079632679\n 9\n$LOFTMAG1\n 40\n0.0\n 9\n$LOFTMAG2\n 40\n0.0\n 9\n$LOFTPARAM\n 70\n7\n 9\n$LOFTNORMALS\n280\n1\n 9\n$LATITUDE\n 40\n37.795\n 9\n$LONGITUDE\n 40\n-122.394\n 9\n$NORTHDIRECTION\n 40\n0.0\n 9\n$TIMEZONE\n 70\n-8000\n 9\n$LIGHTGLYPHDISPLAY\n280\n1\n 9\n$TILEMODELIGHTSYNCH\n280\n1\n 9\n$CMATERIAL\n347\n96\n 9\n$SOLIDHIST\n280\n1\n 9\n$SHOWHIST\n280\n1\n 9\n$DWFFRAME\n280\n2\n 9\n$DGNFRAME\n280\n0\n 9\n$REALWORLDSCALE\n290\n1\n 9\n$INTERFERECOLOR\n 62\n1\n 9\n$INTERFEREOBJVS\n345\nA3\n 9\n$INTERFEREVPVS\n346\nA0\n 9\n$CSHADOW\n280\n0\n 9\n$SHADOWPLANELOCATION\n 40\n0.0\n 0\nENDSEC"},dxfClasses:function(){return' 0\nSECTION\n 2\nCLASSES\n 0\nCLASS\n 1\nACDBDICTIONARYWDFLT\n 2\nAcDbDictionaryWithDefault\n 3\nObjectDBX Classes\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nDICTIONARYVAR\n 2\nAcDbDictionaryVar\n 3\nObjectDBX Classes\n 90\n0\n 91\n15\n280\n0\n281\n0\n 0\nCLASS\n 1\nTABLESTYLE\n 2\nAcDbTableStyle\n 3\nObjectDBX Classes\n 90\n4095\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nMATERIAL\n 2\nAcDbMaterial\n 3\nObjectDBX Classes\n 90\n1153\n 91\n3\n280\n0\n281\n0\n 0\nCLASS\n 1\nVISUALSTYLE\n 2\nAcDbVisualStyle\n 3\nObjectDBX Classes\n 90\n4095\n 91\n26\n280\n0\n281\n0\n 0\nCLASS\n 1\nSCALE\n 2\nAcDbScale\n 3\nObjectDBX Classes\n 90\n1153\n 91\n17\n280\n0\n281\n0\n 0\nCLASS\n 1\nMLEADERSTYLE\n 2\nAcDbMLeaderStyle\n 3\nACDB_MLEADERSTYLE_CLASS\n 90\n4095\n 91\n3\n280\n0\n281\n0\n 0\nCLASS\n 1\nCELLSTYLEMAP\n 2\nAcDbCellStyleMap\n 3\nObjectDBX Classes\n 90\n1152\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nEXACXREFPANELOBJECT\n 2\nExAcXREFPanelObject\n 3\nEXAC_ESW\n 90\n1025\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nNPOCOLLECTION\n 2\nAcDbImpNonPersistentObjectsCollection\n 3\nObjectDBX Classes\n 90\n1153\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nLAYER_INDEX\n 2\nAcDbLayerIndex\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nSPATIAL_INDEX\n 2\nAcDbSpatialIndex\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nIDBUFFER\n 2\nAcDbIdBuffer\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nDIMASSOC\n 2\nAcDbDimAssoc\n 3\n"AcDbDimAssoc|Product Desc: AcDim ARX App For Dimension|Company: Autodesk, Inc.|WEB Address: www.autodesk.com"\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nACDBSECTIONVIEWSTYLE\n 2\nAcDbSectionViewStyle\n 3\nObjectDBX Classes\n 90\n1025\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nACDBDETAILVIEWSTYLE\n 2\nAcDbDetailViewStyle\n 3\nObjectDBX Classes\n 90\n1025\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGEDEF\n 2\nAcDbRasterImageDef\n 3\nISM\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nRASTERVARIABLES\n 2\nAcDbRasterVariables\n 3\nISM\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGEDEF_REACTOR\n 2\nAcDbRasterImageDefReactor\n 3\nISM\n 90\n1\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGE\n 2\nAcDbRasterImage\n 3\nISM\n 90\n2175\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nPDFDEFINITION\n 2\nAcDbPdfDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nPDFUNDERLAY\n 2\nAcDbPdfReference\n 3\nObjectDBX Classes\n 90\n4095\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nDWFDEFINITION\n 2\nAcDbDwfDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nDWFUNDERLAY\n 2\nAcDbDwfReference\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nDGNDEFINITION\n 2\nAcDbDgnDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nDGNUNDERLAY\n 2\nAcDbDgnReference\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n1\n 0\nENDSEC'},dxfTables:function(){return" 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nVPORT\n 5\n8\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nLTYPE\n 5\n5F\n330\n0\n100\nAcDbSymbolTable\n 70\n7\n 0\nLTYPE\n 5\n14\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nByBlock\n 70\n0\n 3\n\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n15\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nByLayer\n 70\n0\n 3\n\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n16\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nContinuous\n 70\n0\n 3\nSolid line\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n1B1\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nCENTER\n 70\n0\n 3\nCenter ____ _ ____ _ ____ _ ____ _ ____ _ ____\n 72\n65\n 73\n4\n 40\n2.0\n 49\n1.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n1B2\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nDASHED\n 70\n0\n 3\nDashed __ __ __ __ __ __ __ __ __ __ __ __ __ _\n 72\n65\n 73\n2\n 40\n0.75\n 49\n0.5\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n1B3\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nPHANTOM\n 70\n0\n 3\nPhantom ______ __ __ ______ __ __ ______\n 72\n65\n 73\n6\n 40\n2.5\n 49\n1.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n39E\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nHIDDEN\n 70\n0\n 3\nHidden __ __ __ __ __ __ __ __ __ __ __ __ __ __\n 72\n65\n 73\n2\n 40\n9.525\n 49\n6.35\n 74\n0\n 49\n-3.175\n 74\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nLAYER\n 5\n2\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n 0\nLAYER\n 5\n10\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\n0\n 70\n0\n 6\nContinuous\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nLAYER\n 5\n1B4\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\nView Port\n 70\n0\n 6\nContinuous\n290\n0\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nLAYER\n 5\n21D\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\nDefpoints\n 70\n0\n 6\nContinuous\n290\n0\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nSTYLE\n 5\n3\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n 0\nSTYLE\n 5\n11\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nStandard\n 70\n0\n 40\n0.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nSTYLE\n 5\nDC\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nAnnotative\n 70\n0\n 40\n0.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nSTYLE\n 5\n178\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nNotes\n 70\n0\n 40\n3.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nENDTAB\n 0\nTABLE\n 2\nVIEW\n 5\n6\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nUCS\n 5\n7\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nAPPID\n 5\n9\n330\n0\n100\nAcDbSymbolTable\n 70\n12\n 0\nAPPID\n 5\n12\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD\n 70\n0\n 0\nAPPID\n 5\nDD\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcadAnnoPO\n 70\n0\n 0\nAPPID\n 5\nDE\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcadAnnotative\n 70\n0\n 0\nAPPID\n 5\nDF\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMJAG\n 70\n0\n 0\nAPPID\n 5\nE0\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMTALN\n 70\n0\n 0\nAPPID\n 5\n107\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_MLEADERVER\n 70\n0\n 0\nAPPID\n 5\n1B5\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcAecLayerStandard\n 70\n0\n 0\nAPPID\n 5\n1BA\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_EXEMPT_FROM_CAD_STANDARDS\n 70\n0\n 0\nAPPID\n 5\n237\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMBREAK\n 70\n0\n 0\nAPPID\n 5\n28E\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_PSEXT\n 70\n0\n 0\nAPPID\n 5\n4B0\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_NAV_VCDISPLAY\n 70\n0\n 0\nAPPID\n 5\n4E3\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nHATCHBACKGROUNDCOLOR\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nDIMSTYLE\n 5\nA\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n100\nAcDbDimStyleTable\n 71\n3\n340\n242\n340\n27\n340\nE1\n 0\nDIMSTYLE\n105\n27\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nStandard\n 70\n0\n 41\n3.0\n 42\n2.0\n 43\n9.0\n 44\n5.0\n140\n3.0\n141\n2.0\n147\n2.0\n340\n11\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n90.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nDIMSTYLE\n105\nE1\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nAnnotative\n 70\n0\n 40\n0.0\n 41\n3.0\n 42\n2.5\n 43\n10.0\n 44\n5.0\n140\n3.0\n141\n2.0\n147\n2.0\n340\n11\n1001\nAcadAnnotative\n1000\nAnnotativeData\n1002\n{\n1070\n1\n1070\n1\n1002\n}\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n90.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nDIMSTYLE\n105\n242\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nCivil-Metric\n 70\n0\n 41\n3.0\n 42\n1.5\n 43\n6.0\n 44\n3.0\n 73\n0\n 74\n0\n 77\n1\n 78\n3\n 79\n2\n140\n3.0\n141\n3.0\n147\n2.0\n179\n2\n271\n2\n272\n2\n276\n1\n340\n11\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n3.0\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nBLOCK_RECORD\n 5\n1\n330\n0\n100\nAcDbSymbolTable\n 70\n4\n 0\nBLOCK_RECORD\n 5\n1F\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n*Model_Space\n340\n530\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n58\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n*Paper_Space\n340\n531\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n238\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n_ArchTick\n340\n0\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n23C\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n_Open30\n340\n0\n 70\n0\n280\n1\n281\n0\n 0\nENDTAB\n 0\nENDSEC"},dxfBlocks:function(){return" 0\nSECTION\n 2\nBLOCKS\n 0\nBLOCK\n 5\n23A\n330\n238\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n_ArchTick\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n_ArchTick\n 1\n\n 0\nENDBLK\n 5\n23B\n330\n238\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n20\n330\n1F\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n*Model_Space\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n*Model_Space\n 1\n\n 0\nENDBLK\n 5\n21\n330\n1F\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n5A\n330\n58\n100\nAcDbEntity\n 67\n1\n 8\n0\n100\nAcDbBlockBegin\n 2\n*Paper_Space\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n*Paper_Space\n 1\n\n 0\nENDBLK\n 5\n5B\n330\n58\n100\nAcDbEntity\n 67\n1\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n240\n330\n23C\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n_Open30\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n_Open30\n 1\n\n 0\nENDBLK\n 5\n241\n330\n23C\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nENDSEC"},dxfObjects:function(){return" 0\nSECTION\n 2\nOBJECTS\n 0\nDICTIONARY\n 5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n 3\nACAD_COLOR\n350\n524\n 3\nACAD_GROUP\n350\n525\n 3\nACAD_LAYOUT\n350\n526\n 3\nACAD_MATERIAL\n350\n527\n 3\nACAD_MLEADERSTYLE\n350\n528\n 3\nACAD_MLINESTYLE\n350\n529\n 3\nACAD_PLOTSETTINGS\n350\n52A\n 3\nACAD_PLOTSTYLENAME\n350\n52C\n 3\nACAD_SCALELIST\n350\n52D\n 3\nACAD_TABLESTYLE\n350\n52E\n 3\nACAD_VISUALSTYLE\n350\n52F\n 0\nDICTIONARY\n 5\n524\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n525\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n526\n330\nC\n100\nAcDbDictionary\n281\n1\n 3\nModel\n350\n530\n 3\nLayout1\n350\n531\n 0\nDICTIONARY\n 5\n527\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n528\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n529\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52A\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nACDBPLACEHOLDER\n 5\n52B\n330\n52C\n 0\nACDBDICTIONARYWDFLT\n 5\n52C\n330\nC\n100\nAcDbDictionary\n281\n1\n 3\nNormal\n350\n52B\n100\nAcDbDictionaryWithDefault\n340\n52B\n 0\nDICTIONARY\n 5\n52D\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52E\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52F\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nLAYOUT\n 5\n530\n330\n526\n100\nAcDbPlotSettings\n 1\n\n 2\nDWFx ePlot (XPS Compatible).pc3\n 4\nANSI_A_(8.50_x_11.00_Inches)\n 6\n\n 40\n5.8\n 41\n17.8\n 42\n5.8\n 43\n17.8\n 44\n215.9\n 45\n279.4\n 46\n0.0\n 47\n0.0\n 48\n0.0\n 49\n0.0\n140\n0.0\n141\n0.0\n142\n1.0\n143\n14.53\n 70\n11952\n 72\n0\n 73\n1\n 74\n0\n 7\n\n 75\n0\n147\n0.069\n148\n114.98\n149\n300.29\n100\nAcDbLayout\n 1\nModel\n 70\n1\n 71\n0\n 10\n0.0\n 20\n0.0\n 11\n12.0\n 21\n9.0\n 12\n0.0\n 22\n0.0\n 32\n0.0\n 14\n0.0\n 24\n0.0\n 34\n0.0\n 15\n0.0\n 25\n0.0\n 35\n0.0\n146\n0.0\n 13\n0.0\n 23\n0.0\n 33\n0.0\n 16\n1.0\n 26\n0.0\n 36\n0.0\n 17\n0.0\n 27\n1.0\n 37\n0.0\n 76\n0\n330\n1F\n 0\nLAYOUT\n 5\n531\n330\n526\n100\nAcDbPlotSettings\n 1\n\n 2\nDWFx ePlot (XPS Compatible).pc3\n 4\nANSI_A_(8.50_x_11.00_Inches)\n 6\n\n 40\n5.8\n 41\n17.8\n 42\n5.8\n 43\n17.8\n 44\n215.9\n 45\n279.4\n 46\n0.0\n 47\n0.0\n 48\n0.0\n 49\n0.0\n140\n0.0\n141\n0.0\n142\n1.0\n143\n1.0\n 70\n688\n 72\n0\n 73\n1\n 74\n5\n 7\nacad.ctb\n 75\n16\n147\n1.0\n148\n0.0\n149\n0.0\n100\nAcDbLayout\n 1\nLayout1\n 70\n1\n 71\n1\n 10\n-0.7\n 20\n-0.23\n 11\n10.3\n 21\n8.27\n 12\n0.0\n 22\n0.0\n 32\n0.0\n 14\n0.63\n 24\n0.8\n 34\n0.0\n 15\n9.0\n 25\n7.2\n 35\n0.0\n146\n0.0\n 13\n0.0\n 23\n0.0\n 33\n0.0\n 16\n1.0\n 26\n0.0\n 36\n0.0\n 17\n0.0\n 27\n1.0\n 37\n0.0\n 76\n0\n330\n58\n 0\nENDSEC"}}},{}],11:[function(e,t,i){t.exports=[[0,0,0,255],[255,0,0,255],[255,255,0,255],[0,255,0,255],[0,255,255,255],[0,0,255,255],[255,0,255,255],[255,255,255,255],[128,128,128,255],[192,192,192,255],[255,0,0,255],[255,127,127,255],[165,0,0,255],[165,82,82,255],[127,0,0,255],[127,63,63,255],[76,0,0,255],[76,38,38,255],[38,0,0,255],[38,19,19,255],[255,63,0,255],[255,159,127,255],[165,41,0,255],[165,103,82,255],[127,31,0,255],[127,79,63,255],[76,19,0,255],[76,47,38,255],[38,9,0,255],[38,28,19,255],[255,127,0,255],[255,191,127,255],[165,82,0,255],[165,124,82,255],[127,63,0,255],[127,95,63,255],[76,38,0,255],[76,57,38,255],[38,19,0,255],[38,28,19,255],[255,191,0,255],[255,223,127,255],[165,124,0,255],[165,145,82,255],[127,95,0,255],[127,111,63,255],[76,57,0,255],[76,66,38,255],[38,28,0,255],[38,33,19,255],[255,255,0,255],[255,255,127,255],[165,165,0,255],[165,165,82,255],[127,127,0,255],[127,127,63,255],[76,76,0,255],[76,76,38,255],[38,38,0,255],[38,38,19,255],[191,255,0,255],[223,255,127,255],[124,165,0,255],[145,165,82,255],[95,127,0,255],[111,127,63,255],[57,76,0,255],[66,76,38,255],[28,38,0,255],[33,38,19,255],[127,255,0,255],[191,255,127,255],[82,165,0,255],[124,165,82,255],[63,127,0,255],[95,127,63,255],[38,76,0,255],[57,76,38,255],[19,38,0,255],[28,38,19,255],[63,255,0,255],[159,255,127,255],[41,165,0,255],[103,165,82,255],[31,127,0,255],[79,127,63,255],[19,76,0,255],[47,76,38,255],[9,38,0,255],[23,38,19,255],[0,255,0,255],[125,255,127,255],[0,165,0,255],[82,165,82,255],[0,127,0,255],[63,127,63,255],[0,76,0,255],[38,76,38,255],[0,38,0,255],[19,38,19,255],[0,255,63,255],[127,255,159,255],[0,165,41,255],[82,165,103,255],[0,127,31,255],[63,127,79,255],[0,76,19,255],[38,76,47,255],[0,38,9,255],[19,88,23,255],[0,255,127,255],[127,255,191,255],[0,165,82,255],[82,165,124,255],[0,127,63,255],[63,127,95,255],[0,76,38,255],[38,76,57,255],[0,38,19,255],[19,88,28,255],[0,255,191,255],[127,255,223,255],[0,165,124,255],[82,165,145,255],[0,127,95,255],[63,127,111,255],[0,76,57,255],[38,76,66,255],[0,38,28,255],[19,88,88,255],[0,255,255,255],[127,255,255,255],[0,165,165,255],[82,165,165,255],[0,127,127,255],[63,127,127,255],[0,76,76,255],[38,76,76,255],[0,38,38,255],[19,88,88,255],[0,191,255,255],[127,223,255,255],[0,124,165,255],[82,145,165,255],[0,95,127,255],[63,111,217,255],[0,57,76,255],[38,66,126,255],[0,28,38,255],[19,88,88,255],[0,127,255,255],[127,191,255,255],[0,82,165,255],[82,124,165,255],[0,63,127,255],[63,95,127,255],[0,38,76,255],[38,57,126,255],[0,19,38,255],[19,28,88,255],[0,63,255,255],[127,159,255,255],[0,41,165,255],[82,103,165,255],[0,31,127,255],[63,79,127,255],[0,19,76,255],[38,47,126,255],[0,9,38,255],[19,23,88,255],[0,0,255,255],[127,127,255,255],[0,0,165,255],[82,82,165,255],[0,0,127,255],[63,63,127,255],[0,0,76,255],[38,38,126,255],[0,0,38,255],[19,19,88,255],[63,0,255,255],[159,127,255,255],[41,0,165,255],[103,82,165,255],[31,0,127,255],[79,63,127,255],[19,0,76,255],[47,38,126,255],[9,0,38,255],[23,19,88,255],[127,0,255,255],[191,127,255,255],[165,0,82,255],[124,82,165,255],[63,0,127,255],[95,63,127,255],[38,0,76,255],[57,38,126,255],[19,0,38,255],[28,19,88,255],[191,0,255,255],[223,127,255,255],[124,0,165,255],[142,82,165,255],[95,0,127,255],[111,63,127,255],[57,0,76,255],[66,38,76,255],[28,0,38,255],[88,19,88,255],[255,0,255,255],[255,127,255,255],[165,0,165,255],[165,82,165,255],[127,0,127,255],[127,63,127,255],[76,0,76,255],[76,38,76,255],[38,0,38,255],[88,19,88,255],[255,0,191,255],[255,127,223,255],[165,0,124,255],[165,82,145,255],[127,0,95,255],[127,63,111,255],[76,0,57,255],[76,38,66,255],[38,0,28,255],[88,19,88,255],[255,0,127,255],[255,127,191,255],[165,0,82,255],[165,82,124,255],[127,0,63,255],[127,63,95,255],[76,0,38,255],[76,38,57,255],[38,0,19,255],[88,19,28,255],[255,0,63,255],[255,127,159,255],[165,0,41,255],[165,82,103,255],[127,0,31,255],[127,63,79,255],[76,0,19,255],[76,38,47,255],[38,0,9,255],[88,19,23,255],[0,0,0,255],[101,101,101,255],[102,102,102,255],[153,153,153,255],[204,204,204,255],[255,255,255,255]]},{}],12:[function(e,t,i){const{geometries:s,modifiers:r}=e("@jscad/modeling"),{geom3:n,geom2:o,path2:a}=s,{flatten:l,toArray:h}=e("@jscad/array-utils"),{dxfHeaders:c,dxfClasses:u,dxfTables:d,dxfBlocks:p,dxfObjects:f}=e("./autocad_AC2017"),_=e("./colorindex2017"),m=(e,t)=>{const i=e.map(((e,i)=>{if(o.isA(e)){const i=e.color,s=e.name,r=o.toOutlines(e).map((e=>({closed:!0,points:e,color:i,name:s})));return"polyline"===t.geom2To?v(r,t):g(r,t)}if(n.isA(e))return"polyline"===t.geom3To?E(e,t):x(e,t);if(a.isA(e)){const i=e.color,s=e.name,r={closed:e.isClosed,points:a.toPoints(e),color:i,name:s};return g([r],t)}return""}));let s=" 0\nSECTION\n 2\nENTITIES\n";return i.forEach((e=>{e&&(s+=e)})),s+=" 0\nENDSEC",s},g=(e,t)=>{t.statusCallback&&t.statusCallback({progress:0});let i="";return e.forEach(((s,r)=>{if(s.points.length<1)return;const n=s.points.length+(s.closed?1:0);i+=` 0\nLWPOLYLINE\n 5\n${C(t)}\n 100\nAcDbEntity\n 3\n${y(s,t)}\n 8\n0\n 67\n0\n 62\n${A(s,t)}\n 100\nAcDbPolyline\n 90\n${n}\n 70\n${s.closed?1:0}\n`;for(let e=0;e=s.points.length&&(t-=s.points.length);const r=s.points[t];i+=` 10\n${r[0]}\n 20\n${r[1]}\n`}t.statusCallback&&t.statusCallback({progress:100*r/e.length})})),t.statusCallback&&t.statusCallback({progress:100}),[i]},v=(e,t)=>{t.statusCallback&&t.statusCallback({progress:0});let i="";return e.forEach(((s,r)=>{const n=s.points.length+(s.closed?1:0);i+=` 0\nPOLYLINE\n 5\n${C(t)}\n 100\nAcDbEntity\n 3\n${y(s,t)}\n 8\n0\n 62\n${A(s,t)}\n 100\nAcDb2dPolyline\n`;for(let e=0;e=s.points.length&&(r-=s.points.length);const n=s.points[r];i+=` 0\nVERTEX\n 5\n${C(t)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb2dVertex\n 10\n${n[0]}\n 20\n${n[1]}\n`}i+=` 0\nSEQEND\n 5\n${C(t)}\n 100\nAcDbEntity\n`,t.statusCallback&&t.statusCallback({progress:100*r/e.length})})),t.statusCallback&&t.statusCallback({progress:100}),[i]},x=(e,t)=>{t.statusCallback&&t.statusCallback({progress:0});let i="";const s=n.toPolygons(e),r=A(e,t);return s.forEach(((e,s)=>{const n=e.color?A(e,t):r;T(e).forEach(((e,s)=>{i+=S(e,t,n)}))})),t.statusCallback&&t.statusCallback({progress:100}),[i]},T=e=>{const t=e.vertices.length-2;if(t<1)return[];const i=e.vertices[0],s=[];for(let r=0;r{const s=e[0],r=e[1],n=e[2],o=e[2];return` 0\n3DFACE\n 5\n${C(t)}\n 100\nAcDbEntity\n 8\n0\n 62\n${i}\n 100\nAcDbFace\n 70\n0\n 10\n${s[0]}\n 20\n${s[1]}\n 30\n${s[2]}\n 11\n${r[0]}\n 21\n${r[1]}\n 31\n${r[2]}\n 12\n${n[0]}\n 22\n${n[1]}\n 32\n${n[2]}\n 13\n${o[0]}\n 23\n${o[1]}\n 33\n${o[2]}\n`},E=(e,t)=>{let i="";const s=b(n.toPolygons(e));return s.faces.length>0&&(i+=` 0\nPOLYLINE\n 5\n${C(t)}\n 100\nAcDbEntity\n 3\n${y(e,t)}\n 8\n0\n 62\n${A(e,t)}\n 100\nAcDb3dPolyline\n 70\n64\n 71\n${s.vertices.length}\n 72\n${s.faces.length}\n`,s.vertices.forEach((e=>{i+=` 0\nVERTEX\n 5\n${C(t)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb3dPolylineVertex\n 10\n${e[0]}\n 20\n${e[1]}\n 30\n${e[2]}\n 70\n192\n`})),s.faces.forEach((e=>{i+=` 0\nVERTEX\n 5\n${C(t)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb3dPolylineVertex\n 10\n0\n 20\n0\n 30\n0\n 70\n128\n 71\n${e[0]}\n 72\n${e[1]}\n 73\n${e[2]}\n 74\n${e[3]}\n`}))),[i]},b=e=>{const t=[],i=[];for(let s=0;s{e.entityId++;const t="00000"+e.entityId.toString(16).toUpperCase();return"CAD"+t.substr(t.length-5)},y=(e,t)=>{if(e.name)return e.name;const i="00000"+t.entityId.toString(16).toUpperCase();return"CAD"+i.substr(i.length-5)},A=(e,t)=>{let i=256;if(e.color){const s=Math.floor(255*e.color[0]),r=Math.floor(255*e.color[1]),n=Math.floor(255*e.color[2]),o=t.colorIndex;let a=765;for(let e=1;e{const i={geom2To:"lwpolyline",geom3To:"3dface",pathTo:"lwpolyline",statusCallback:null,colorIndex:_};if((e=Object.assign({},i,e)).entityId=0,0===(t=(t=l(t)).filter((e=>n.isA(e)||o.isA(e)||a.isA(e)))).length)throw new Error("only JSCAD geometries can be serialized to DXF");return t=h(r.generalize({snap:!0,triangulate:!0},t)),[`999\nCreated by JSCAD\n${c(e)}\n${u(e)}\n${d(e)}\n${p(e)}\n${m(t,e)}\n${f(e)}\n 0\nEOF\n`]},mimeType:"application/dxf"}},{"./autocad_AC2017":10,"./colorindex2017":11,"@jscad/array-utils":5,"@jscad/modeling":108}],13:[function(e,t,i){t.exports=class{constructor(e){this._buffer=e,this._pos=0}readInt8(){return this._decodeInt(8,!0)}readUInt8(){return this._decodeInt(8,!1)}readInt16(){return this._decodeInt(16,!0)}readUInt16(){return this._decodeInt(16,!1)}readInt32(){return this._decodeInt(32,!0)}readUInt32(){return this._decodeInt(32,!1)}readFloat(){return this._decodeFloat(23,8)}readDouble(){return this._decodeFloat(52,11)}readChar(){return this.readString(1)}readString(e){this._checkSize(8*e);const t=this._buffer.substr(this._pos,e);return this._pos+=e,t}seek(e){this._pos=e,this._checkSize(0)}getPosition(){return this._pos}getSize(){return this._buffer.length}_decodeFloat(e,t){const i=e+t+1,s=i>>3;this._checkSize(i);const r=Math.pow(2,t-1)-1,n=this._readBits(e+t,1,s),o=this._readBits(e,t,s);let a=0,l=2,h=0,c=0;do{const t=this._readByte(++h,s);c=e%8||8;let i=1<>=1;)t&i&&(a+=1/l),l*=2}while(e-=c);return this._pos+=s,o===1+(r<<1)?a?NaN:n?-1/0:1/0:(1+-2*n)*(o||a?o?Math.pow(2,o-r)*(1+a):Math.pow(2,1-r)*a:0)}_decodeInt(e,t){const i=this._readBits(0,e,e/8),s=Math.pow(2,e),r=t&&i>=s/2?i-s:i;return this._pos+=e/8,r}_shl(e,t){for(++t;--t;e=1073741824&~(e%=2147483648)?2*(e-1073741824)+2147483647+1:2*e);return e}_readByte(e,t){return 255&this._buffer.charCodeAt(this._pos+t-e-1)}_readBits(e,t,i){const s=(e+t)%8,r=e%8,n=i-(e>>3)-1;let o=i+(-(e+t)>>3),a=n-o,l=this._readByte(n,i)>>r&(1<<(a?8-r:t))-1;for(a&&s&&(l+=(this._readByte(o++,i)&(1<{"string"==typeof e?this.length+=e.length:e instanceof ArrayBuffer&&(this.length+=e.byteLength)})),i.type&&(this.type=i.type.toLowerCase()),i.endings,i.encoding&&(this.encoding=i.encoding.toLowerCase()),i.length&&(this.length=i.length),this.buffer=e.allocUnsafe(this.length);for(let e=0;e{const{data:t,mimeType:i}=e;return new s(t,{type:i})}},{"./makeBlob":17}],16:[function(e,t,i){t.exports={convertToBlob:e("./convertToBlob"),makeBlob:e("./makeBlob"),BinaryReader:e("./BinaryReader"),Blob:e("./Blob")}},{"./BinaryReader":13,"./Blob":14,"./convertToBlob":15,"./makeBlob":17}],17:[function(e,t,i){const s=e("./Blob.js");t.exports=()=>"undefined"!=typeof window?window.Blob:s},{"./Blob.js":14}],18:[function(e,t,i){const s=e("./cssColors");t.exports=e=>s[e.toLowerCase()]},{"./cssColors":20}],19:[function(e,t,i){const s=e("../utils/flatten"),r=e("../geometries/geom2"),n=e("../geometries/geom3"),o=e("../geometries/path2"),a=e("../geometries/poly3");t.exports=(e,...t)=>{if(!Array.isArray(e))throw new Error("color must be an array");if(e.length<3)throw new Error("color must contain R, G and B values");if(3===e.length&&(e=[e[0],e[1],e[2],1]),0===(t=s(t)).length)throw new Error("wrong number of arguments");const i=t.map((t=>r.isA(t)?((e,t)=>{const i=r.clone(t);return i.color=e,i})(e,t):n.isA(t)?((e,t)=>{const i=n.clone(t);return i.color=e,i})(e,t):o.isA(t)?((e,t)=>{const i=o.clone(t);return i.color=e,i})(e,t):a.isA(t)?((e,t)=>{const i=a.clone(t);return i.color=e,i})(e,t):(t.color=e,t)));return 1===i.length?i[0]:i}},{"../geometries/geom2":42,"../geometries/geom3":57,"../geometries/path2":78,"../geometries/poly3":95,"../utils/flatten":412}],20:[function(e,t,i){t.exports={black:[0,0,0],silver:[192/255,192/255,192/255],gray:[128/255,128/255,128/255],white:[1,1,1],maroon:[128/255,0,0],red:[1,0,0],purple:[128/255,0,128/255],fuchsia:[1,0,1],green:[0,128/255,0],lime:[0,1,0],olive:[128/255,128/255,0],yellow:[1,1,0],navy:[0,0,128/255],blue:[0,0,1],teal:[0,128/255,128/255],aqua:[0,1,1],aliceblue:[240/255,248/255,1],antiquewhite:[250/255,235/255,215/255],aquamarine:[127/255,1,212/255],azure:[240/255,1,1],beige:[245/255,245/255,220/255],bisque:[1,228/255,196/255],blanchedalmond:[1,235/255,205/255],blueviolet:[138/255,43/255,226/255],brown:[165/255,42/255,42/255],burlywood:[222/255,184/255,135/255],cadetblue:[95/255,158/255,160/255],chartreuse:[127/255,1,0],chocolate:[210/255,105/255,30/255],coral:[1,127/255,80/255],cornflowerblue:[100/255,149/255,237/255],cornsilk:[1,248/255,220/255],crimson:[220/255,20/255,60/255],cyan:[0,1,1],darkblue:[0,0,139/255],darkcyan:[0,139/255,139/255],darkgoldenrod:[184/255,134/255,11/255],darkgray:[169/255,169/255,169/255],darkgreen:[0,100/255,0],darkgrey:[169/255,169/255,169/255],darkkhaki:[189/255,183/255,107/255],darkmagenta:[139/255,0,139/255],darkolivegreen:[85/255,107/255,47/255],darkorange:[1,140/255,0],darkorchid:[.6,50/255,.8],darkred:[139/255,0,0],darksalmon:[233/255,150/255,122/255],darkseagreen:[143/255,188/255,143/255],darkslateblue:[72/255,61/255,139/255],darkslategray:[47/255,79/255,79/255],darkslategrey:[47/255,79/255,79/255],darkturquoise:[0,206/255,209/255],darkviolet:[148/255,0,211/255],deeppink:[1,20/255,147/255],deepskyblue:[0,191/255,1],dimgray:[105/255,105/255,105/255],dimgrey:[105/255,105/255,105/255],dodgerblue:[30/255,144/255,1],firebrick:[178/255,34/255,34/255],floralwhite:[1,250/255,240/255],forestgreen:[34/255,139/255,34/255],gainsboro:[220/255,220/255,220/255],ghostwhite:[248/255,248/255,1],gold:[1,215/255,0],goldenrod:[218/255,165/255,32/255],greenyellow:[173/255,1,47/255],grey:[128/255,128/255,128/255],honeydew:[240/255,1,240/255],hotpink:[1,105/255,180/255],indianred:[205/255,92/255,92/255],indigo:[75/255,0,130/255],ivory:[1,1,240/255],khaki:[240/255,230/255,140/255],lavender:[230/255,230/255,250/255],lavenderblush:[1,240/255,245/255],lawngreen:[124/255,252/255,0],lemonchiffon:[1,250/255,205/255],lightblue:[173/255,216/255,230/255],lightcoral:[240/255,128/255,128/255],lightcyan:[224/255,1,1],lightgoldenrodyellow:[250/255,250/255,210/255],lightgray:[211/255,211/255,211/255],lightgreen:[144/255,238/255,144/255],lightgrey:[211/255,211/255,211/255],lightpink:[1,182/255,193/255],lightsalmon:[1,160/255,122/255],lightseagreen:[32/255,178/255,170/255],lightskyblue:[135/255,206/255,250/255],lightslategray:[119/255,136/255,.6],lightslategrey:[119/255,136/255,.6],lightsteelblue:[176/255,196/255,222/255],lightyellow:[1,1,224/255],limegreen:[50/255,205/255,50/255],linen:[250/255,240/255,230/255],magenta:[1,0,1],mediumaquamarine:[.4,205/255,170/255],mediumblue:[0,0,205/255],mediumorchid:[186/255,85/255,211/255],mediumpurple:[147/255,112/255,219/255],mediumseagreen:[60/255,179/255,113/255],mediumslateblue:[123/255,104/255,238/255],mediumspringgreen:[0,250/255,154/255],mediumturquoise:[72/255,209/255,.8],mediumvioletred:[199/255,21/255,133/255],midnightblue:[25/255,25/255,112/255],mintcream:[245/255,1,250/255],mistyrose:[1,228/255,225/255],moccasin:[1,228/255,181/255],navajowhite:[1,222/255,173/255],oldlace:[253/255,245/255,230/255],olivedrab:[107/255,142/255,35/255],orange:[1,165/255,0],orangered:[1,69/255,0],orchid:[218/255,112/255,214/255],palegoldenrod:[238/255,232/255,170/255],palegreen:[152/255,251/255,152/255],paleturquoise:[175/255,238/255,238/255],palevioletred:[219/255,112/255,147/255],papayawhip:[1,239/255,213/255],peachpuff:[1,218/255,185/255],peru:[205/255,133/255,63/255],pink:[1,192/255,203/255],plum:[221/255,160/255,221/255],powderblue:[176/255,224/255,230/255],rosybrown:[188/255,143/255,143/255],royalblue:[65/255,105/255,225/255],saddlebrown:[139/255,69/255,19/255],salmon:[250/255,128/255,114/255],sandybrown:[244/255,164/255,96/255],seagreen:[46/255,139/255,87/255],seashell:[1,245/255,238/255],sienna:[160/255,82/255,45/255],skyblue:[135/255,206/255,235/255],slateblue:[106/255,90/255,205/255],slategray:[112/255,128/255,144/255],slategrey:[112/255,128/255,144/255],snow:[1,250/255,250/255],springgreen:[0,1,127/255],steelblue:[70/255,130/255,180/255],tan:[210/255,180/255,140/255],thistle:[216/255,191/255,216/255],tomato:[1,99/255,71/255],turquoise:[64/255,224/255,208/255],violet:[238/255,130/255,238/255],wheat:[245/255,222/255,179/255],whitesmoke:[245/255,245/255,245/255],yellowgreen:[154/255,205/255,50/255]}},{}],21:[function(e,t,i){t.exports=e=>{if((e=e.replace("#","")).length<6)throw new Error("the given notation must contain 3 or more hex values");const t=parseInt(e.substring(0,2),16)/255,i=parseInt(e.substring(2,4),16)/255,s=parseInt(e.substring(4,6),16)/255;return e.length>=8?[t,i,s,parseInt(e.substring(6,8),16)/255]:[t,i,s]}},{}],22:[function(e,t,i){const s=e("../utils/flatten"),r=e("./hueToColorComponent");t.exports=(...e)=>{if((e=s(e)).length<3)throw new Error("values must contain H, S and L values");const t=e[0],i=e[1],n=e[2];let o=n,a=n,l=n;if(0!==i){const e=n<.5?n*(1+i):n+i-n*i,s=2*n-e;o=r(s,e,t+1/3),a=r(s,e,t),l=r(s,e,t-1/3)}return e.length>3?[o,a,l,e[3]]:[o,a,l]}},{"../utils/flatten":412,"./hueToColorComponent":24}],23:[function(e,t,i){const s=e("../utils/flatten");t.exports=(...e)=>{if((e=s(e)).length<3)throw new Error("values must contain H, S and V values");const t=e[0],i=e[1],r=e[2];let n=0,o=0,a=0;const l=Math.floor(6*t),h=6*t-l,c=r*(1-i),u=r*(1-h*i),d=r*(1-(1-h)*i);switch(l%6){case 0:n=r,o=d,a=c;break;case 1:n=u,o=r,a=c;break;case 2:n=c,o=r,a=d;break;case 3:n=c,o=u,a=r;break;case 4:n=d,o=c,a=r;break;case 5:n=r,o=c,a=u}return e.length>3?[n,o,a,e[3]]:[n,o,a]}},{"../utils/flatten":412}],24:[function(e,t,i){t.exports=(e,t,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e)},{}],25:[function(e,t,i){t.exports={colorize:e("./colorize"),colorNameToRgb:e("./colorNameToRgb"),cssColors:e("./cssColors"),hexToRgb:e("./hexToRgb"),hslToRgb:e("./hslToRgb"),hsvToRgb:e("./hsvToRgb"),hueToColorComponent:e("./hueToColorComponent"),rgbToHex:e("./rgbToHex"),rgbToHsl:e("./rgbToHsl"),rgbToHsv:e("./rgbToHsv")}},{"./colorNameToRgb":18,"./colorize":19,"./cssColors":20,"./hexToRgb":21,"./hslToRgb":22,"./hsvToRgb":23,"./hueToColorComponent":24,"./rgbToHex":26,"./rgbToHsl":27,"./rgbToHsv":28}],26:[function(e,t,i){const s=e("../utils/flatten");t.exports=(...e)=>{if((e=s(e)).length<3)throw new Error("values must contain R, G and B values");const t=255*e[0],i=255*e[1],r=255*e[2];let n=`#${Number(16777216+65536*t+256*i+r).toString(16).substring(1,7)}`;return e.length>3&&(n+=Number(255*e[3]).toString(16)),n}},{"../utils/flatten":412}],27:[function(e,t,i){const s=e("../utils/flatten");t.exports=(...e)=>{if((e=s(e)).length<3)throw new Error("values must contain R, G and B values");const t=e[0],i=e[1],r=e[2],n=Math.max(t,i,r),o=Math.min(t,i,r);let a,l;const h=(n+o)/2;if(n===o)a=l=0;else{const e=n-o;switch(l=h>.5?e/(2-n-o):e/(n+o),n){case t:a=(i-r)/e+(i3?[a,l,h,e[3]]:[a,l,h]}},{"../utils/flatten":412}],28:[function(e,t,i){const s=e("../utils/flatten");t.exports=(...e)=>{if((e=s(e)).length<3)throw new Error("values must contain R, G and B values");const t=e[0],i=e[1],r=e[2],n=Math.max(t,i,r),o=Math.min(t,i,r);let a;const l=n,h=n-o,c=0===n?0:h/n;if(n===o)a=0;else{switch(n){case t:a=(i-r)/h+(i3?[a,c,l,e[3]]:[a,c,l]}},{"../utils/flatten":412}],29:[function(e,t,i){const s=e("./lengths");t.exports=(e,t)=>{const{distance:i,segments:r}=Object.assign({},{distance:0,segments:100},e),n=s(r,t);let o=0,a=r;for(;o<=a;){const e=Math.floor(o+(a-o)/2),t=n[e]-i;if(t<0)o=e+1;else{if(!(t>0)){a=e;break}a=e-1}}const l=a;if(n[l]===i)return l/r;const h=n[l];return(l+(i-h)/(n[l+1]-h))/r}},{"./lengths":33}],30:[function(e,t,i){const s=function(e){const t=[];for(let i=0;i<=e;i++)t.push(r(e)/(r(i)*r(e-i)));return t},r=function(e){let t=1;for(let i=2;i<=e;i++)t*=i;return t};t.exports=e=>{if(!Array.isArray(e))throw new Error("Bezier points must be a valid array/");if(e.length<2)throw new Error("Bezier points must contain at least 2 values.");const t=function(e){let t=null;return e.forEach((e=>{let i="";if(Number.isFinite(e))i="float_single";else{if(!Array.isArray(e))throw new Error("Bezier points must all be numbers or arrays of number.");e.forEach((e=>{if(!Number.isFinite(e))throw new Error("Bezier point values must all be numbers.")})),i="float_"+e.length}if(null==t)t=i;else if(t!==i)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),t}(e);return{points:e,pointType:t,dimensions:"float_single"===t?0:e[0].length,permutations:s(e.length-1),tangentPermutations:s(e.length-2)}}},{}],31:[function(e,t,i){t.exports={create:e("./create"),valueAt:e("./valueAt"),tangentAt:e("./tangentAt"),lengths:e("./lengths"),length:e("./length"),arcLengthToT:e("./arcLengthToT")}},{"./arcLengthToT":29,"./create":30,"./length":32,"./lengths":33,"./tangentAt":34,"./valueAt":35}],32:[function(e,t,i){const s=e("./lengths");t.exports=(e,t)=>s(e,t)[e]},{"./lengths":33}],33:[function(e,t,i){const s=e("./valueAt"),r=(e,t)=>{if(Number.isFinite(e)&&Number.isFinite(t))return Math.abs(e-t);if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)throw new Error("The operands must have the same number of dimensions.");let i=0;for(let s=0;s{let i=0;const n=[0];let o=s(0,t);for(let a=1;a<=e;a++){const l=s(a/e,t);i+=r(l,o),n.push(i),o=l}return n}},{"./valueAt":35}],34:[function(e,t,i){const s=function(e,t,i){const s=t.length-1;let r=0;for(let n=0;n{if(e<0||e>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===t.pointType)return s(t,t.points,e);{const i=[];for(let r=0;r{if(e<0||e>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===t.pointType)return s(t,t.points,e);{const i=[];for(let r=0;r(s.isIdentity(e.transforms)||(e.sides=e.sides.map((t=>[r.transform(r.create(),t[0],e.transforms),r.transform(r.create(),t[1],e.transforms)])),e.transforms=s.create()),e)},{"../../maths/mat4":159,"../../maths/vec2":206}],38:[function(e,t,i){t.exports=e=>Object.assign({},e)},{}],39:[function(e,t,i){const s=e("../../maths/mat4");t.exports=e=>(void 0===e&&(e=[]),{sides:e,transforms:s.create()})},{"../../maths/mat4":159}],40:[function(e,t,i){const s=e("../../maths/mat4"),r=e("../../maths/vec2"),n=e("./create");t.exports=e=>{if(0!==e[0])throw new Error("invalid compact binary data");const t=n();t.transforms=s.clone(e.slice(1,17));for(let i=21;i=0&&(t.color=[e[17],e[18],e[19],e[20]]),t}},{"../../maths/mat4":159,"../../maths/vec2":206,"./create":39}],41:[function(e,t,i){const s=e("../../maths/vec2"),r=e("./create");t.exports=e=>{if(!Array.isArray(e))throw new Error("the given points must be an array");let t=e.length;if(t<3)throw new Error("the given points must define a closed geometry with three or more points");s.equals(e[0],e[t-1])&&--t;const i=[];let n=e[t-1];for(let r=0;r!!(e&&"object"==typeof e&&"sides"in e&&"transforms"in e&&Array.isArray(e.sides)&&"length"in e.transforms)},{}],44:[function(e,t,i){const s=e("./create"),r=e("./toSides");t.exports=e=>{const t=r(e).map((e=>[e[1],e[0]]));return t.reverse(),s(t)}},{"./create":39,"./toSides":48}],45:[function(e,t,i){t.exports=e=>{const t=e.sides,i=e.transforms;let s=[-1,-1,-1,-1];e.color&&(s=e.color);const r=new Float32Array(21+4*t.length);r[0]=0,r[1]=i[0],r[2]=i[1],r[3]=i[2],r[4]=i[3],r[5]=i[4],r[6]=i[5],r[7]=i[6],r[8]=i[7],r[9]=i[8],r[10]=i[9],r[11]=i[10],r[12]=i[11],r[13]=i[12],r[14]=i[13],r[15]=i[14],r[16]=i[15],r[17]=s[0],r[18]=s[1],r[19]=s[2],r[20]=s[3];for(let e=0;e{if(1===t.length)return t.pop();const i=s.create(),r=s.angleDegrees(s.subtract(i,e[1],e[0]));let n,o;t.forEach(((e,t)=>{let a=s.angleDegrees(s.subtract(i,e[1],e[0]))-r;a<-180&&(a+=360),a>=180&&(a-=360),(void 0===o||a>n)&&(o=t,n=a)}));const a=t[o];return t.splice(o,1),a};t.exports=e=>{const t=(e=>{const t=new Map;return(e=>{const t=new Map,i=e=>{const i=e.toString();return t.has(i)?t.get(i):(t.set(i,e),e)};return e.map((e=>e.map(i)))})(e).forEach((e=>{t.has(e[0])?t.get(e[0]).push(e):t.set(e[0],[e])})),t})(r(e)),i=[];for(;;){let e;for(const[i,s]of t){if(e=s.shift(),e)break;t.delete(i)}if(void 0===e)break;const s=[],r=e[0];for(;;){s.push(e[0]);const i=e[1];if(i===r)break;const o=t.get(i);if(!o)throw new Error(`geometry is not closed at vertex ${i}`);const a=n(e,o);0===o.length&&t.delete(i),e=a}s.length>0&&s.push(s.shift()),i.push(s)}return t.clear(),i}},{"../../maths/vec2":206,"./toSides":48}],47:[function(e,t,i){const s=e("./toSides");t.exports=e=>{const t=s(e).map((e=>e[0]));return t.length>0&&t.push(t.shift()),t}},{"./toSides":48}],48:[function(e,t,i){const s=e("./applyTransforms");t.exports=e=>s(e).sides},{"./applyTransforms":37}],49:[function(e,t,i){const s=e("../../maths/vec2"),r=e("./toSides");t.exports=e=>{const t=r(e);let i="geom2 ("+t.length+" sides):\n[\n";return t.forEach((e=>{i+=" ["+s.toString(e[0])+", "+s.toString(e[1])+"]\n"})),i+="]\n",i}},{"../../maths/vec2":206,"./toSides":48}],50:[function(e,t,i){const s=e("../../maths/mat4");t.exports=(e,t)=>{const i=s.multiply(s.create(),e,t.transforms);return Object.assign({},t,{transforms:i})}},{"../../maths/mat4":159}],51:[function(e,t,i){const s=e("../../maths/vec2"),r=e("./isA"),n=e("./toOutlines");t.exports=e=>{if(!r(e))throw new Error("invalid geom2 structure");if(n(e),e.sides.forEach((e=>{if(s.equals(e[0],e[1]))throw new Error(`geom2 self-edge ${e[0]}`)})),!e.transforms.every(Number.isFinite))throw new Error(`geom2 invalid transforms ${e.transforms}`)}},{"../../maths/vec2":206,"./isA":43,"./toOutlines":46}],52:[function(e,t,i){const s=e("../../maths/mat4"),r=e("../poly3");t.exports=e=>(s.isIdentity(e.transforms)||(e.polygons=e.polygons.map((t=>r.transform(e.transforms,t))),e.transforms=s.create()),e)},{"../../maths/mat4":159,"../poly3":95}],53:[function(e,t,i){t.exports=e=>Object.assign({},e)},{}],54:[function(e,t,i){const s=e("../../maths/mat4");t.exports=e=>(void 0===e&&(e=[]),{polygons:e,transforms:s.create()})},{"../../maths/mat4":159}],55:[function(e,t,i){const s=e("../../maths/vec3"),r=e("../../maths/mat4"),n=e("../poly3"),o=e("./create");t.exports=e=>{if(1!==e[0])throw new Error("invalid compact binary data");const t=o();t.transforms=r.clone(e.slice(1,17));const i=e[21];let a=22,l=e.length-3*i;for(;l=0&&(t.color=[e[17],e[18],e[19],e[20]]),t}},{"../../maths/mat4":159,"../../maths/vec3":237,"../poly3":95,"./create":54}],56:[function(e,t,i){const s=e("../poly3"),r=e("./create");t.exports=e=>{if(!Array.isArray(e))throw new Error("the given points must be an array");const t=e.map(((e,t)=>s.create(e)));return r(t)}},{"../poly3":95,"./create":54}],57:[function(e,t,i){t.exports={clone:e("./clone"),create:e("./create"),fromPoints:e("./fromPoints"),fromCompactBinary:e("./fromCompactBinary"),invert:e("./invert"),isA:e("./isA"),toPoints:e("./toPoints"),toPolygons:e("./toPolygons"),toString:e("./toString"),toCompactBinary:e("./toCompactBinary"),transform:e("./transform"),validate:e("./validate")}},{"./clone":53,"./create":54,"./fromCompactBinary":55,"./fromPoints":56,"./invert":58,"./isA":59,"./toCompactBinary":60,"./toPoints":61,"./toPolygons":62,"./toString":63,"./transform":64,"./validate":65}],58:[function(e,t,i){const s=e("../poly3"),r=e("./create"),n=e("./toPolygons");t.exports=e=>{const t=n(e).map((e=>s.invert(e)));return r(t)}},{"../poly3":95,"./create":54,"./toPolygons":62}],59:[function(e,t,i){t.exports=e=>!!(e&&"object"==typeof e&&"polygons"in e&&"transforms"in e&&Array.isArray(e.polygons)&&"length"in e.transforms)},{}],60:[function(e,t,i){const s=e("../poly3");t.exports=e=>{const t=e.polygons,i=e.transforms,r=t.length,n=t.reduce(((e,t)=>e+t.vertices.length),0);let o=[-1,-1,-1,-1];e.color&&(o=e.color);const a=new Float32Array(22+r+3*n);a[0]=1,a[1]=i[0],a[2]=i[1],a[3]=i[2],a[4]=i[3],a[5]=i[4],a[6]=i[5],a[7]=i[6],a[8]=i[7],a[9]=i[8],a[10]=i[9],a[11]=i[10],a[12]=i[11],a[13]=i[12],a[14]=i[13],a[15]=i[14],a[16]=i[15],a[17]=o[0],a[18]=o[1],a[19]=o[2],a[20]=o[3],a[21]=n;let l=22,h=l+r;return t.forEach((e=>{const t=s.toPoints(e);a[l]=t.length,l++;for(let e=0;er(e).map((e=>s.toPoints(e)))},{"../poly3":95,"./toPolygons":62}],62:[function(e,t,i){const s=e("./applyTransforms");t.exports=e=>s(e).polygons},{"./applyTransforms":52}],63:[function(e,t,i){const s=e("../poly3"),r=e("./toPolygons");t.exports=e=>{const t=r(e);let i="geom3 ("+t.length+" polygons):\n";return t.forEach((e=>{i+=" "+s.toString(e)+"\n"})),i}},{"../poly3":95,"./toPolygons":62}],64:[function(e,t,i){const s=e("../../maths/mat4");t.exports=(e,t)=>{const i=s.multiply(s.create(),e,t.transforms);return Object.assign({},t,{transforms:i})}},{"../../maths/mat4":159}],65:[function(e,t,i){const s=e("../poly3"),r=e("./isA");t.exports=e=>{if(!r(e))throw new Error("invalid geom3 structure");if(e.polygons.forEach(s.validate),(e=>{const t=new Map;e.polygons.forEach((({vertices:e})=>{e.forEach(((i,s)=>{const r=`${i}/${e[(s+1)%e.length]}`,n=t.has(r)?t.get(r):0;t.set(r,n+1)}))}));const i=[];if(t.forEach(((e,s)=>{const r=s.split("/").reverse().join("/");e!==t.get(r)&&i.push(s.replace("/"," -> "))})),i.length>0)throw new Error(`non-manifold edges ${i.length}\n${i.join("\n")}`)})(e),!e.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${e.transforms}`)}},{"../poly3":95,"./isA":59}],66:[function(e,t,i){t.exports={geom2:e("./geom2"),geom3:e("./geom3"),path2:e("./path2"),poly2:e("./poly2"),poly3:e("./poly3")}},{"./geom2":42,"./geom3":57,"./path2":78,"./poly2":89,"./poly3":95}],67:[function(e,t,i){const{TAU:s}=e("../../maths/constants"),r=e("../../maths/vec2"),n=e("./fromPoints"),o=e("./toPoints");t.exports=(e,t)=>{let{endpoint:i,radius:a,xaxisrotation:l,clockwise:h,large:c,segments:u}=Object.assign({},{radius:[0,0],xaxisrotation:0,clockwise:!1,large:!1,segments:16},e);if(!Array.isArray(i))throw new Error("endpoint must be an array of X and Y values");if(i.length<2)throw new Error("endpoint must contain X and Y values");if(i=r.clone(i),!Array.isArray(a))throw new Error("radius must be an array of X and Y values");if(a.length<2)throw new Error("radius must contain X and Y values");if(u<4)throw new Error("segments must be four or more");const d=1e5;if(t.isClosed)throw new Error("the given path cannot be closed");const p=o(t);if(p.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let f=a[0],_=a[1];const m=p[p.length-1];f=Math.round(f*d)/d,_=Math.round(_*d)/d,i=r.fromValues(Math.round(i[0]*d)/d,Math.round(i[1]*d)/d);const g=!h;let v=[];if(0===f||0===_)v.push(i);else{f=Math.abs(f),_=Math.abs(_);const t=l,n=Math.cos(t),o=Math.sin(t),a=r.subtract(r.create(),m,i);r.scale(a,a,.5);const h=Math.round((n*a[0]+o*a[1])*d)/d,p=Math.round((-o*a[0]+n*a[1])*d)/d,x=r.fromValues(h,p),T=x[0]*x[0]/(f*f)+x[1]*x[1]/(_*_);if(T>1){const e=Math.sqrt(T);f*=e,_*=e,f=Math.round(f*d)/d,_=Math.round(_*d)/d}let S=Math.sqrt((f*f*_*_-f*f*x[1]*x[1]-_*_*x[0]*x[0])/(f*f*x[1]*x[1]+_*_*x[0]*x[0]));g===c&&(S=-S);const E=r.fromValues(f*x[1]/_,-_*x[0]/f);r.scale(E,E,S);let b=r.fromValues(n*E[0]-o*E[1],o*E[0]+n*E[1]);b=r.add(b,b,r.scale(r.create(),r.add(r.create(),m,i),.5));const C=r.fromValues((x[0]-E[0])/f,(x[1]-E[1])/_),y=r.fromValues((-x[0]-E[0])/f,(-x[1]-E[1])/_),A=r.angleRadians(C);let R=r.angleRadians(y)-A;R%=s,!g&&R>0?R-=s:g&&R<0&&(R+=s);let I=Math.ceil(Math.abs(R)/s*u)+1;I<1&&(I=1);for(let e=1;e{let{controlPoints:i,segments:l}=Object.assign({},{segments:16},e);if(!Array.isArray(i))throw new Error("controlPoints must be an array of one or more points");if(i.length<1)throw new Error("controlPoints must be an array of one or more points");if(l<4)throw new Error("segments must be four or more");if(t.isClosed)throw new Error("the given geometry cannot be closed");const h=a(t);if(h.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(i=i.slice(),null===i[0]){if(i.length<2)throw new Error("a null control point must be passed with one more control points");let e=h[h.length-2];if("lastBezierControlPoint"in t&&(e=t.lastBezierControlPoint),!Array.isArray(e))throw new Error("the given path must contain TWO or more points if given a null control point");const s=r.scale(r.create(),h[h.length-1],2);r.subtract(s,s,e),i[0]=s}i.unshift(h[h.length-1]);const c=i.length-1,u=[];let d=1;for(let e=0;e<=c;++e)e>0&&(d*=e),u.push(d);const p=[];for(let e=0;e<=c;++e){const t=u[c]/(u[e]*u[c-e]);p.push(t)}const f=r.create(),_=r.create(),m=n.create(),g=e=>{let t=1,s=Math.pow(1-e,c);const n=1!==e?1/(1-e):1,o=r.create();for(let a=0;a<=c;++a){a===c&&(s=1);const l=p[a]*t*s,h=r.scale(f,i[a],l);r.add(o,o,h),t*=e,s*=n}return o},v=[],x=[],T=c+1;for(let e=0;eb){const e=x[S-1],t=x[S+1],i=e+1*(t-e)/3,s=e+2*(t-e)/3,r=g(i),n=g(s);v.splice(S,1,r,n),x.splice(S,1,i,s),S--,S<1&&(S=1)}else++S}v.shift();const C=o(v,t);return C.lastBezierControlPoint=i[i.length-2],C}},{"../../maths/constants":110,"../../maths/vec2":206,"./appendPoints":69,"./toPoints":82}],69:[function(e,t,i){const s=e("./concat"),r=e("./create");t.exports=(e,t)=>s(t,r(e))},{"./concat":73,"./create":74}],70:[function(e,t,i){const s=e("../../maths/mat4"),r=e("../../maths/vec2");t.exports=e=>(s.isIdentity(e.transforms)||(e.points=e.points.map((t=>r.transform(r.create(),t,e.transforms))),e.transforms=s.create()),e)},{"../../maths/mat4":159,"../../maths/vec2":206}],71:[function(e,t,i){t.exports=e=>Object.assign({},e)},{}],72:[function(e,t,i){const{EPS:s}=e("../../maths/constants"),r=e("../../maths/vec2"),n=e("./clone");t.exports=e=>{if(e.isClosed)return e;const t=n(e);if(t.isClosed=!0,t.points.length>1){const e=t.points,i=e[0];let n=e[e.length-1];for(;r.distance(i,n){let t=!1,i=[];return e.forEach(((e,s)=>{const o=r(e).slice();if(i.length>0&&o.length>0&&n(o[0],i[i.length-1])&&o.shift(),o.length>0&&t)throw new Error(`Cannot concatenate to a closed path; check the ${s}th path`);t=e.isClosed,i=i.concat(o)})),s({closed:t},i)}},{"../../maths/vec2":206,"./fromPoints":77,"./toPoints":82}],74:[function(e,t,i){const s=e("../../maths/mat4");t.exports=e=>(void 0===e&&(e=[]),{points:e,isClosed:!1,transforms:s.create()})},{"../../maths/mat4":159}],75:[function(e,t,i){const s=e("../../maths/vec2"),r=e("./toPoints");t.exports=(e,t)=>{if(e.isClosed!==t.isClosed)return!1;if(e.points.length!==t.points.length)return!1;const i=r(e),n=r(t),o=i.length;let a=0;do{let t=!1;for(let e=0;e{if(2!==e[0])throw new Error("invalid compact binary data");const t=n();t.transforms=s.clone(e.slice(1,17)),t.isClosed=!!e[17];for(let i=22;i=0&&(t.color=[e[18],e[19],e[20],e[21]]),t}},{"../../maths/mat4":159,"../../maths/vec2":206,"./create":74}],77:[function(e,t,i){const{EPS:s}=e("../../maths/constants"),r=e("../../maths/vec2"),n=e("./close"),o=e("./create");t.exports=(e,t)=>{let{closed:i}=Object.assign({},{closed:!1},e),a=o();if(a.points=t.map((e=>r.clone(e))),a.points.length>1){const e=a.points[0],t=a.points[a.points.length-1];r.distance(e,t)!!(e&&"object"==typeof e&&"points"in e&&"transforms"in e&&"isClosed"in e&&Array.isArray(e.points)&&"length"in e.transforms)},{}],80:[function(e,t,i){const s=e("./clone");t.exports=e=>{const t=s(e);return t.points=e.points.slice().reverse(),t}},{"./clone":71}],81:[function(e,t,i){t.exports=e=>{const t=e.points,i=e.transforms;let s=[-1,-1,-1,-1];e.color&&(s=e.color);const r=new Float32Array(22+2*t.length);r[0]=2,r[1]=i[0],r[2]=i[1],r[3]=i[2],r[4]=i[3],r[5]=i[4],r[6]=i[5],r[7]=i[6],r[8]=i[7],r[9]=i[8],r[10]=i[9],r[11]=i[10],r[12]=i[11],r[13]=i[12],r[14]=i[13],r[15]=i[14],r[16]=i[15],r[17]=e.isClosed?1:0,r[18]=s[0],r[19]=s[1],r[20]=s[2],r[21]=s[3];for(let e=0;es(e).points},{"./applyTransforms":70}],83:[function(e,t,i){const s=e("../../maths/vec2"),r=e("./toPoints");t.exports=e=>{const t=r(e);let i="path ("+t.length+" points, "+e.isClosed+"):\n[\n";return t.forEach((e=>{i+=" "+s.toString(e)+",\n"})),i+="]\n",i}},{"../../maths/vec2":206,"./toPoints":82}],84:[function(e,t,i){const s=e("../../maths/mat4");t.exports=(e,t)=>{const i=s.multiply(s.create(),e,t.transforms);return Object.assign({},t,{transforms:i})}},{"../../maths/mat4":159}],85:[function(e,t,i){const s=e("../../maths/vec2"),r=e("./isA");t.exports=e=>{if(!r(e))throw new Error("invalid path2 structure");if(e.points.length>1)for(let t=0;t{if(!e.every(Number.isFinite))throw new Error(`path2 invalid point ${e}`)})),!e.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${e.transforms}`)}},{"../../maths/vec2":206,"./isA":79}],86:[function(e,t,i){const s=e("./measureArea"),r=e("./flip");t.exports=(e,t)=>{if(0===e.length)return 0;const i=t.vertices;return i.length<3?0:(s(t)<0&&(t=r(t)),e.reduce(((e,t)=>e+((e,t)=>{const i=t.length,s=e[0],r=e[1];let n=t[i-1],o=t[0],a=n[1]>r,l=0,h=0;for(let e=i+1;--e;){const e=o[1]>r;if(a!==e){const e=n[0]>s,t=o[0]>s;(e&&t||o[0]-(o[1]-r)*(n[0]-o[0])/(n[1]-o[1])>=s)&&(l=!l)}a=e,n=o,o=t[++h]}return l})(t,i)),0)===e.length?1:0)}},{"./flip":88,"./measureArea":90}],87:[function(e,t,i){t.exports=e=>((void 0===e||e.length<3)&&(e=[]),{vertices:e})},{}],88:[function(e,t,i){const s=e("./create");t.exports=e=>{const t=e.vertices.slice().reverse();return s(t)}},{"./create":87}],89:[function(e,t,i){t.exports={arePointsInside:e("./arePointsInside"),create:e("./create"),flip:e("./flip"),measureArea:e("./measureArea")}},{"./arePointsInside":86,"./create":87,"./flip":88,"./measureArea":90}],90:[function(e,t,i){const s=e("../../maths/utils/area");t.exports=e=>s(e.vertices)},{"../../maths/utils/area":183}],91:[function(e,t,i){const s=e("./create"),r=e("../../maths/vec3");t.exports=(...e)=>{let t,i;return 1===e.length?(t=s(),i=e[0]):(t=e[0],i=e[1]),t.vertices=i.vertices.map((e=>r.clone(e))),t}},{"../../maths/vec3":237,"./create":92}],92:[function(e,t,i){t.exports=e=>((void 0===e||e.length<3)&&(e=[]),{vertices:e})},{}],93:[function(e,t,i){const s=e("../../maths/vec3"),r=e("./create");t.exports=e=>{const t=e.map((e=>s.clone(e)));return r(t)}},{"../../maths/vec3":237,"./create":92}],94:[function(e,t,i){const s=e("./create");t.exports=(e,t)=>{const i=s(e);return i.plane=t,i}},{"./create":92}],95:[function(e,t,i){t.exports={clone:e("./clone"),create:e("./create"),fromPoints:e("./fromPoints"),fromPointsAndPlane:e("./fromPointsAndPlane"),invert:e("./invert"),isA:e("./isA"),isConvex:e("./isConvex"),measureArea:e("./measureArea"),measureBoundingBox:e("./measureBoundingBox"),measureBoundingSphere:e("./measureBoundingSphere"),measureSignedVolume:e("./measureSignedVolume"),plane:e("./plane"),toPoints:e("./toPoints"),toString:e("./toString"),transform:e("./transform"),validate:e("./validate")}},{"./clone":91,"./create":92,"./fromPoints":93,"./fromPointsAndPlane":94,"./invert":96,"./isA":97,"./isConvex":98,"./measureArea":99,"./measureBoundingBox":100,"./measureBoundingSphere":101,"./measureSignedVolume":102,"./plane":103,"./toPoints":104,"./toString":105,"./transform":106,"./validate":107}],96:[function(e,t,i){const s=e("../../maths/plane"),r=e("./create");t.exports=e=>{const t=e.vertices.slice().reverse(),i=r(t);return e.plane&&(i.plane=s.flip(s.create(),e.plane)),i}},{"../../maths/plane":178,"./create":92}],97:[function(e,t,i){t.exports=e=>!!(e&&"object"==typeof e&&"vertices"in e&&Array.isArray(e.vertices))},{}],98:[function(e,t,i){const s=e("../../maths/plane"),r=e("../../maths/vec3"),n=(e,t,i,s)=>{const n=r.cross(r.create(),r.subtract(r.create(),t,e),r.subtract(r.create(),i,t));return r.dot(n,s)>=0};t.exports=e=>(e=>{const t=e.length;if(t>2){const i=s.fromPoints(s.create(),...e);let r=e[t-2],o=e[t-1];for(let s=0;s{const t=e.vertices.length;if(t<3)return 0;const i=e.vertices,r=s(e),n=Math.abs(r[0]),o=Math.abs(r[1]),a=Math.abs(r[2]);if(n+o+a===0)return 0;let l=3;n>o&&n>a?l=1:o>a&&(l=2);let h=0,c=0,u=1,d=2;switch(l){case 1:for(u=1;u{const t=e.vertices,i=t.length,r=0===i?s.create():s.clone(t[0]),n=s.clone(r);for(let e=1;e{const t=r.get(e);if(t)return t;const i=e.vertices,n=s.create();if(0===i.length)return n[0]=0,n[1]=0,n[2]=0,n[3]=0,n;let o=i[0],a=o,l=o,h=o,c=o,u=o;i.forEach((e=>{o[0]>e[0]&&(o=e),a[1]>e[1]&&(a=e),l[2]>e[2]&&(l=e),h[0]{let t=0;const i=e.vertices,r=s.create();for(let e=0;e(e.plane||(e.plane=s.fromPoints(s.create(),...e.vertices)),e.plane)},{"../../maths/plane/":178}],104:[function(e,t,i){t.exports=e=>e.vertices},{}],105:[function(e,t,i){const s=e("../../maths/vec3/");t.exports=e=>{let t="poly3: vertices: [";return e.vertices.forEach((e=>{t+=`${s.toString(e)}, `})),t+="]",t}},{"../../maths/vec3/":237}],106:[function(e,t,i){const s=e("../../maths/mat4"),r=e("../../maths/vec3"),n=e("./create");t.exports=(e,t)=>{const i=t.vertices.map((t=>r.transform(r.create(),t,e)));return s.isMirroring(e)&&i.reverse(),n(i)}},{"../../maths/mat4":159,"../../maths/vec3":237,"./create":92}],107:[function(e,t,i){const s=e("../../maths/plane/signedDistanceToPoint"),{NEPS:r}=e("../../maths/constants"),n=e("../../maths/vec3"),o=e("./isA"),a=e("./isConvex"),l=e("./measureArea"),h=e("./plane");t.exports=e=>{if(!o(e))throw new Error("invalid poly3 structure");if(e.vertices.length<3)throw new Error(`poly3 not enough vertices ${e.vertices.length}`);if(l(e)<=0)throw new Error("poly3 area must be greater than zero");for(let t=0;t{if(!e.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${e}`)})),e.vertices.length>3){const t=h(e);e.vertices.forEach((e=>{const i=Math.abs(s(t,e));if(i>r)throw new Error(`poly3 must be coplanar: vertex ${e} distance ${i}`)}))}}},{"../../maths/constants":110,"../../maths/plane/signedDistanceToPoint":180,"../../maths/vec3":237,"./isA":97,"./isConvex":98,"./measureArea":99,"./plane":103}],108:[function(e,t,i){t.exports={colors:e("./colors"),curves:e("./curves"),geometries:e("./geometries"),maths:e("./maths"),measurements:e("./measurements"),primitives:e("./primitives"),text:e("./text"),utils:e("./utils"),booleans:e("./operations/booleans"),expansions:e("./operations/expansions"),extrusions:e("./operations/extrusions"),hulls:e("./operations/hulls"),modifiers:e("./operations/modifiers"),transforms:e("./operations/transforms")}},{"./colors":25,"./curves":36,"./geometries":66,"./maths":111,"./measurements":267,"./operations/booleans":281,"./operations/expansions":310,"./operations/extrusions":333,"./operations/hulls":355,"./operations/modifiers":366,"./operations/transforms":376,"./primitives":392,"./text":406,"./utils":414}],109:[function(e,t,i){const s=e("./mat4"),r=e("./vec2"),n=e("./vec3"),o=function(e,t){arguments.length<2&&(t=n.orthogonal(n.create(),e)),this.v=n.normalize(n.create(),n.cross(n.create(),e,t)),this.u=n.cross(n.create(),this.v,e),this.plane=e,this.planeorigin=n.scale(n.create(),e,e[3])};o.GetCartesian=function(e,t){const i=e+"/"+t;let s,r;if("X/Y"===i)s=[0,0,1],r=[1,0,0];else if("Y/-X"===i)s=[0,0,1],r=[0,1,0];else if("-X/-Y"===i)s=[0,0,1],r=[-1,0,0];else if("-Y/X"===i)s=[0,0,1],r=[0,-1,0];else if("-X/Y"===i)s=[0,0,-1],r=[-1,0,0];else if("-Y/-X"===i)s=[0,0,-1],r=[0,-1,0];else if("X/-Y"===i)s=[0,0,-1],r=[1,0,0];else if("Y/X"===i)s=[0,0,-1],r=[0,1,0];else if("X/Z"===i)s=[0,-1,0],r=[1,0,0];else if("Z/-X"===i)s=[0,-1,0],r=[0,0,1];else if("-X/-Z"===i)s=[0,-1,0],r=[-1,0,0];else if("-Z/X"===i)s=[0,-1,0],r=[0,0,-1];else if("-X/Z"===i)s=[0,1,0],r=[-1,0,0];else if("-Z/-X"===i)s=[0,1,0],r=[0,0,-1];else if("X/-Z"===i)s=[0,1,0],r=[1,0,0];else if("Z/X"===i)s=[0,1,0],r=[0,0,1];else if("Y/Z"===i)s=[1,0,0],r=[0,1,0];else if("Z/-Y"===i)s=[1,0,0],r=[0,0,1];else if("-Y/-Z"===i)s=[1,0,0],r=[0,-1,0];else if("-Z/Y"===i)s=[1,0,0],r=[0,0,-1];else if("-Y/Z"===i)s=[-1,0,0],r=[0,-1,0];else if("-Z/-Y"===i)s=[-1,0,0],r=[0,0,-1];else if("Y/-Z"===i)s=[-1,0,0],r=[0,1,0];else{if("Z/Y"!==i)throw new Error("OrthoNormalBasis.GetCartesian: invalid combination of axis identifiers. Should pass two string arguments from [X,Y,Z,-X,-Y,-Z], being two different axes.");s=[-1,0,0],r=[0,0,1]}return new o(new Plane(new Vector3D(s),0),new Vector3D(r))},o.Z0Plane=function(){const e=new Plane(new Vector3D([0,0,1]),0);return new o(e,new Vector3D([1,0,0]))},o.prototype={getProjectionMatrix:function(){return s.fromValues(this.u[0],this.v[0],this.plane[0],0,this.u[1],this.v[1],this.plane[1],0,this.u[2],this.v[2],this.plane[2],0,0,0,-this.plane[3],1)},getInverseProjectionMatrix:function(){const e=n.scale(n.create(),this.plane,this.plane[3]);return s.fromValues(this.u[0],this.u[1],this.u[2],0,this.v[0],this.v[1],this.v[2],0,this.plane[0],this.plane[1],this.plane[2],0,e[0],e[1],e[2],1)},to2D:function(e){return r.fromValues(n.dot(e,this.u),n.dot(e,this.v))},to3D:function(e){const t=n.scale(n.create(),this.u,e[0]),i=n.scale(n.create(),this.v,e[1]),s=n.add(t,t,this.planeorigin);return n.add(i,i,s)},line3Dto2D:function(e){const t=e.point,i=e.direction.plus(t),s=this.to2D(t),r=this.to2D(i);return Line2D.fromPoints(s,r)},line2Dto3D:function(e){const t=e.origin(),i=e.direction().plus(t),s=this.to3D(t),r=this.to3D(i);return Line3D.fromPoints(s,r)},transform:function(e){const t=this.plane.transform(e),i=this.u.transform(e),s=new Vector3D(0,0,0).transform(e),r=i.minus(s);return new o(t,r)}},t.exports=o},{"./mat4":159,"./vec2":206,"./vec3":237}],110:[function(e,t,i){const s=2*Math.PI;t.exports={EPS:1e-5,NEPS:1e-13,TAU:s,spatialResolution:1e5}},{}],111:[function(e,t,i){t.exports={constants:e("./constants"),line2:e("./line2"),line3:e("./line3"),mat4:e("./mat4"),plane:e("./plane"),utils:e("./utils"),vec2:e("./vec2"),vec3:e("./vec3"),vec4:e("./vec4")}},{"./constants":110,"./line2":121,"./line3":138,"./mat4":159,"./plane":178,"./utils":184,"./vec2":206,"./vec3":237,"./vec4":263}],112:[function(e,t,i){const s=e("./create");t.exports=e=>{const t=s();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}},{"./create":115}],113:[function(e,t,i){const s=e("../vec2"),r=e("./direction"),n=e("./origin");t.exports=(e,t)=>{const i=n(e),o=r(e),a=s.subtract(s.create(),t,i),l=s.dot(a,o);return s.scale(a,o,l),s.add(a,a,i),a}},{"../vec2":206,"./direction":116,"./origin":123}],114:[function(e,t,i){t.exports=(e,t)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],e)},{}],115:[function(e,t,i){t.exports=()=>[0,1,0]},{}],116:[function(e,t,i){const s=e("../vec2");t.exports=e=>{const t=s.normal(s.create(),e);return s.negate(t,t),t}},{"../vec2":206}],117:[function(e,t,i){const s=e("../vec2");t.exports=(e,t)=>{let i=s.dot(t,e);return i=Math.abs(i-e[2]),i}},{"../vec2":206}],118:[function(e,t,i){t.exports=(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]},{}],119:[function(e,t,i){const s=e("../vec2");t.exports=(e,t,i)=>{const r=s.subtract(s.create(),i,t);s.normal(r,r),s.normalize(r,r);const n=s.dot(t,r);return e[0]=r[0],e[1]=r[1],e[2]=n,e}},{"../vec2":206}],120:[function(e,t,i){const s=e("./create");t.exports=(e,t,i)=>{const r=s();return r[0]=e,r[1]=t,r[2]=i,r}},{"./create":115}],121:[function(e,t,i){t.exports={clone:e("./clone"),closestPoint:e("./closestPoint"),copy:e("./copy"),create:e("./create"),direction:e("./direction"),distanceToPoint:e("./distanceToPoint"),equals:e("./equals"),fromPoints:e("./fromPoints"),fromValues:e("./fromValues"),intersectPointOfLines:e("./intersectPointOfLines"),origin:e("./origin"),reverse:e("./reverse"),toString:e("./toString"),transform:e("./transform"),xAtY:e("./xAtY")}},{"./clone":112,"./closestPoint":113,"./copy":114,"./create":115,"./direction":116,"./distanceToPoint":117,"./equals":118,"./fromPoints":119,"./fromValues":120,"./intersectPointOfLines":122,"./origin":123,"./reverse":124,"./toString":125,"./transform":126,"./xAtY":127}],122:[function(e,t,i){const s=e("../vec2"),{solve2Linear:r}=e("../utils");t.exports=(e,t)=>{const i=r(e[0],e[1],t[0],t[1],e[2],t[2]);return s.clone(i)}},{"../utils":184,"../vec2":206}],123:[function(e,t,i){const s=e("../vec2");t.exports=e=>s.scale(s.create(),e,e[2])},{"../vec2":206}],124:[function(e,t,i){const s=e("../vec2"),r=e("./copy"),n=e("./fromValues");t.exports=(e,t)=>{const i=s.negate(s.create(),t),o=-t[2];return r(e,n(i[0],i[1],o))}},{"../vec2":206,"./copy":114,"./fromValues":120}],125:[function(e,t,i){t.exports=e=>`line2: (${e[0].toFixed(7)}, ${e[1].toFixed(7)}, ${e[2].toFixed(7)})`},{}],126:[function(e,t,i){const s=e("../vec2"),r=e("./fromPoints"),n=e("./origin"),o=e("./direction");t.exports=(e,t,i)=>{const a=n(t),l=o(t);return s.transform(a,a,i),s.transform(l,l,i),r(e,a,l)}},{"../vec2":206,"./direction":116,"./fromPoints":119,"./origin":123}],127:[function(e,t,i){const s=e("./origin");t.exports=(e,t)=>{let i=(e[2]-e[1]*t)/e[0];return Number.isNaN(i)&&(i=s(e)[0]),i}},{"./origin":123}],128:[function(e,t,i){const s=e("../vec3"),r=e("./create");t.exports=e=>{const t=r();return s.copy(t[0],e[0]),s.copy(t[1],e[1]),t}},{"../vec3":237,"./create":131}],129:[function(e,t,i){const s=e("../vec3");t.exports=(e,t)=>{const i=e[0],r=e[1],n=s.dot(s.subtract(s.create(),t,i),r)/s.dot(r,r),o=s.scale(s.create(),r,n);return s.add(o,o,i),o}},{"../vec3":237}],130:[function(e,t,i){const s=e("../vec3");t.exports=(e,t)=>(s.copy(e[0],t[0]),s.copy(e[1],t[1]),e)},{"../vec3":237}],131:[function(e,t,i){const s=e("../vec3");t.exports=()=>[s.fromValues(0,0,0),s.fromValues(0,0,1)]},{"../vec3":237}],132:[function(e,t,i){t.exports=e=>e[1]},{}],133:[function(e,t,i){const s=e("../vec3"),r=e("./closestPoint");t.exports=(e,t)=>{const i=r(e,t),n=s.subtract(s.create(),t,i);return s.length(n)}},{"../vec3":237,"./closestPoint":129}],134:[function(e,t,i){const s=e("../vec3");t.exports=(e,t)=>!!s.equals(e[1],t[1])&&!!s.equals(e[0],t[0])},{"../vec3":237}],135:[function(e,t,i){const s=e("../vec3"),{solve2Linear:r}=e("../utils"),{EPS:n}=e("../constants"),o=e("./fromPointAndDirection");t.exports=(e,t,i)=>{let a=s.cross(s.create(),t,i),l=s.length(a);if(l=c&&h>=u?(p=r(t[1],t[2],i[1],i[2],t[3],i[3]),d=s.fromValues(0,p[0],p[1])):c>=h&&c>=u?(p=r(t[0],t[2],i[0],i[2],t[3],i[3]),d=s.fromValues(p[0],0,p[1])):(p=r(t[0],t[1],i[0],i[1],t[3],i[3]),d=s.fromValues(p[0],p[1],0)),o(e,d,a)}},{"../constants":110,"../utils":184,"../vec3":237,"./fromPointAndDirection":136}],136:[function(e,t,i){const s=e("../vec3");t.exports=(e,t,i)=>{const r=s.normalize(s.create(),i);return s.copy(e[0],t),s.copy(e[1],r),e}},{"../vec3":237}],137:[function(e,t,i){const s=e("../vec3"),r=e("./fromPointAndDirection");t.exports=(e,t,i)=>{const n=s.subtract(s.create(),i,t);return r(e,t,n)}},{"../vec3":237,"./fromPointAndDirection":136}],138:[function(e,t,i){t.exports={clone:e("./clone"),closestPoint:e("./closestPoint"),copy:e("./copy"),create:e("./create"),direction:e("./direction"),distanceToPoint:e("./distanceToPoint"),equals:e("./equals"),fromPlanes:e("./fromPlanes"),fromPointAndDirection:e("./fromPointAndDirection"),fromPoints:e("./fromPoints"),intersectPointOfLineAndPlane:e("./intersectPointOfLineAndPlane"),origin:e("./origin"),reverse:e("./reverse"),toString:e("./toString"),transform:e("./transform")}},{"./clone":128,"./closestPoint":129,"./copy":130,"./create":131,"./direction":132,"./distanceToPoint":133,"./equals":134,"./fromPlanes":135,"./fromPointAndDirection":136,"./fromPoints":137,"./intersectPointOfLineAndPlane":139,"./origin":140,"./reverse":141,"./toString":142,"./transform":143}],139:[function(e,t,i){const s=e("../vec3");t.exports=(e,t)=>{const i=t,r=t[3],n=e[0],o=e[1],a=(r-s.dot(i,n))/s.dot(i,o);return s.add(s.create(),n,s.scale(s.create(),o,a))}},{"../vec3":237}],140:[function(e,t,i){t.exports=e=>e[0]},{}],141:[function(e,t,i){const s=e("../vec3"),r=e("./fromPointAndDirection");t.exports=(e,t)=>{const i=s.clone(t[0]),n=s.negate(s.create(),t[1]);return r(e,i,n)}},{"../vec3":237,"./fromPointAndDirection":136}],142:[function(e,t,i){t.exports=e=>{const t=e[0],i=e[1];return`line3: point: (${t[0].toFixed(7)}, ${t[1].toFixed(7)}, ${t[2].toFixed(7)}) direction: (${i[0].toFixed(7)}, ${i[1].toFixed(7)}, ${i[2].toFixed(7)})`}},{}],143:[function(e,t,i){const s=e("../vec3"),r=e("./fromPointAndDirection");t.exports=(e,t,i)=>{const n=t[0],o=t[1],a=s.add(s.create(),n,o),l=s.transform(s.create(),n,i),h=s.transform(a,a,i),c=s.subtract(h,h,l);return r(e,l,c)}},{"../vec3":237,"./fromPointAndDirection":136}],144:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]+i[0],e[1]=t[1]+i[1],e[2]=t[2]+i[2],e[3]=t[3]+i[3],e[4]=t[4]+i[4],e[5]=t[5]+i[5],e[6]=t[6]+i[6],e[7]=t[7]+i[7],e[8]=t[8]+i[8],e[9]=t[9]+i[9],e[10]=t[10]+i[10],e[11]=t[11]+i[11],e[12]=t[12]+i[12],e[13]=t[13]+i[13],e[14]=t[14]+i[14],e[15]=t[15]+i[15],e)},{}],145:[function(e,t,i){const s=e("./create");t.exports=e=>{const t=s();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}},{"./create":147}],146:[function(e,t,i){t.exports=(e,t)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e)},{}],147:[function(e,t,i){t.exports=()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]},{}],148:[function(e,t,i){t.exports=(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15]},{}],149:[function(e,t,i){const{EPS:s}=e("../constants"),{sin:r,cos:n}=e("../utils/trigonometry"),o=e("./identity");t.exports=(e,t,i)=>{let[a,l,h]=i;const c=a*a+l*l+h*h;if(Math.abs(c)(e[0]=t[0],e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=t[1],e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=t[2],e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e)},{}],151:[function(e,t,i){const{sin:s,cos:r}=e("../utils/trigonometry");t.exports=(e,t,i,n)=>{const o=s(t),a=r(t),l=s(i),h=r(i),c=s(n),u=r(n);return e[0]=h*a,e[1]=h*o,e[2]=-l,e[3]=0,e[4]=c*l*a-u*o,e[5]=u*a+c*l*o,e[6]=c*h,e[7]=0,e[8]=c*o+u*l*a,e[9]=u*l*o-c*a,e[10]=u*h,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}},{"../utils/trigonometry":188}],152:[function(e,t,i){t.exports=(e,t)=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=t[0],e[13]=t[1],e[14]=t[2],e[15]=1,e)},{}],153:[function(e,t,i){const s=e("./create");t.exports=(e,t,i,r,n,o,a,l,h,c,u,d,p,f,_,m)=>{const g=s();return g[0]=e,g[1]=t,g[2]=i,g[3]=r,g[4]=n,g[5]=o,g[6]=a,g[7]=l,g[8]=h,g[9]=c,g[10]=u,g[11]=d,g[12]=p,g[13]=f,g[14]=_,g[15]=m,g}},{"./create":147}],154:[function(e,t,i){const s=e("../vec3"),r=e("./fromRotation");t.exports=(e,t,i)=>{const n=s.normalize(s.create(),t),o=s.normalize(s.create(),i),a=s.cross(s.create(),o,n),l=s.dot(o,n);if(-1===l)return r(e,Math.PI,s.orthogonal(a,n));const h=1/(1+l);return e[0]=a[0]*a[0]*h+l,e[1]=a[1]*a[0]*h-a[2],e[2]=a[2]*a[0]*h+a[1],e[3]=0,e[4]=a[0]*a[1]*h+a[2],e[5]=a[1]*a[1]*h+l,e[6]=a[2]*a[1]*h-a[0],e[7]=0,e[8]=a[0]*a[2]*h-a[1],e[9]=a[1]*a[2]*h+a[0],e[10]=a[2]*a[2]*h+l,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}},{"../vec3":237,"./fromRotation":149}],155:[function(e,t,i){const{sin:s,cos:r}=e("../utils/trigonometry");t.exports=(e,t)=>{const i=s(t),n=r(t);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=n,e[6]=i,e[7]=0,e[8]=0,e[9]=-i,e[10]=n,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}},{"../utils/trigonometry":188}],156:[function(e,t,i){const{sin:s,cos:r}=e("../utils/trigonometry");t.exports=(e,t)=>{const i=s(t),n=r(t);return e[0]=n,e[1]=0,e[2]=-i,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=i,e[9]=0,e[10]=n,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}},{"../utils/trigonometry":188}],157:[function(e,t,i){const{sin:s,cos:r}=e("../utils/trigonometry");t.exports=(e,t)=>{const i=s(t),n=r(t);return e[0]=n,e[1]=i,e[2]=0,e[3]=0,e[4]=-i,e[5]=n,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}},{"../utils/trigonometry":188}],158:[function(e,t,i){t.exports=e=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e)},{}],159:[function(e,t,i){t.exports={add:e("./add"),clone:e("./clone"),copy:e("./copy"),create:e("./create"),invert:e("./invert"),equals:e("./equals"),fromRotation:e("./fromRotation"),fromScaling:e("./fromScaling"),fromTaitBryanRotation:e("./fromTaitBryanRotation"),fromTranslation:e("./fromTranslation"),fromValues:e("./fromValues"),fromVectorRotation:e("./fromVectorRotation"),fromXRotation:e("./fromXRotation"),fromYRotation:e("./fromYRotation"),fromZRotation:e("./fromZRotation"),identity:e("./identity"),isIdentity:e("./isIdentity"),isOnlyTransformScale:e("./isOnlyTransformScale"),isMirroring:e("./isMirroring"),mirrorByPlane:e("./mirrorByPlane"),multiply:e("./multiply"),rotate:e("./rotate"),rotateX:e("./rotateX"),rotateY:e("./rotateY"),rotateZ:e("./rotateZ"),scale:e("./scale"),subtract:e("./subtract"),toString:e("./toString"),translate:e("./translate")}},{"./add":144,"./clone":145,"./copy":146,"./create":147,"./equals":148,"./fromRotation":149,"./fromScaling":150,"./fromTaitBryanRotation":151,"./fromTranslation":152,"./fromValues":153,"./fromVectorRotation":154,"./fromXRotation":155,"./fromYRotation":156,"./fromZRotation":157,"./identity":158,"./invert":160,"./isIdentity":161,"./isMirroring":162,"./isOnlyTransformScale":163,"./mirrorByPlane":164,"./multiply":165,"./rotate":166,"./rotateX":167,"./rotateY":168,"./rotateZ":169,"./scale":170,"./subtract":171,"./toString":172,"./translate":173}],160:[function(e,t,i){t.exports=(e,t)=>{const i=t[0],s=t[1],r=t[2],n=t[3],o=t[4],a=t[5],l=t[6],h=t[7],c=t[8],u=t[9],d=t[10],p=t[11],f=t[12],_=t[13],m=t[14],g=t[15],v=i*a-s*o,x=i*l-r*o,T=i*h-n*o,S=s*l-r*a,E=s*h-n*a,b=r*h-n*l,C=c*_-u*f,y=c*m-d*f,A=c*g-p*f,R=u*m-d*_,I=u*g-p*_,P=d*g-p*m;let M=v*P-x*I+T*R+S*A-E*y+b*C;return M?(M=1/M,e[0]=(a*P-l*I+h*R)*M,e[1]=(r*I-s*P-n*R)*M,e[2]=(_*b-m*E+g*S)*M,e[3]=(d*E-u*b-p*S)*M,e[4]=(l*A-o*P-h*y)*M,e[5]=(i*P-r*A+n*y)*M,e[6]=(m*T-f*b-g*x)*M,e[7]=(c*b-d*T+p*x)*M,e[8]=(o*I-a*A+h*C)*M,e[9]=(s*A-i*I-n*C)*M,e[10]=(f*E-_*T+g*v)*M,e[11]=(u*T-c*E-p*v)*M,e[12]=(a*y-o*R-l*C)*M,e[13]=(i*R-s*y+r*C)*M,e[14]=(_*x-f*S-m*v)*M,e[15]=(c*S-u*x+d*v)*M,e):null}},{}],161:[function(e,t,i){t.exports=e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]},{}],162:[function(e,t,i){t.exports=e=>{const t=e[4]*e[9]-e[8]*e[5],i=e[8]*e[1]-e[0]*e[9],s=e[0]*e[5]-e[4]*e[1];return t*e[2]+i*e[6]+s*e[10]<0}},{}],163:[function(e,t,i){const s=e=>Math.abs(e)s(e[1])&&s(e[2])&&s(e[3])&&s(e[4])&&s(e[6])&&s(e[7])&&s(e[8])&&s(e[9])&&s(e[11])&&1===e[15]},{}],164:[function(e,t,i){t.exports=(e,t)=>{const[i,s,r,n]=t;return e[0]=1-2*i*i,e[1]=-2*s*i,e[2]=-2*r*i,e[3]=0,e[4]=-2*i*s,e[5]=1-2*s*s,e[6]=-2*r*s,e[7]=0,e[8]=-2*i*r,e[9]=-2*s*r,e[10]=1-2*r*r,e[11]=0,e[12]=2*i*n,e[13]=2*s*n,e[14]=2*r*n,e[15]=1,e}},{}],165:[function(e,t,i){t.exports=(e,t,i)=>{const s=t[0],r=t[1],n=t[2],o=t[3],a=t[4],l=t[5],h=t[6],c=t[7],u=t[8],d=t[9],p=t[10],f=t[11],_=t[12],m=t[13],g=t[14],v=t[15];let x=i[0],T=i[1],S=i[2],E=i[3];return e[0]=x*s+T*a+S*u+E*_,e[1]=x*r+T*l+S*d+E*m,e[2]=x*n+T*h+S*p+E*g,e[3]=x*o+T*c+S*f+E*v,x=i[4],T=i[5],S=i[6],E=i[7],e[4]=x*s+T*a+S*u+E*_,e[5]=x*r+T*l+S*d+E*m,e[6]=x*n+T*h+S*p+E*g,e[7]=x*o+T*c+S*f+E*v,x=i[8],T=i[9],S=i[10],E=i[11],e[8]=x*s+T*a+S*u+E*_,e[9]=x*r+T*l+S*d+E*m,e[10]=x*n+T*h+S*p+E*g,e[11]=x*o+T*c+S*f+E*v,x=i[12],T=i[13],S=i[14],E=i[15],e[12]=x*s+T*a+S*u+E*_,e[13]=x*r+T*l+S*d+E*m,e[14]=x*n+T*h+S*p+E*g,e[15]=x*o+T*c+S*f+E*v,e}},{}],166:[function(e,t,i){const{EPS:s}=e("../constants"),{sin:r,cos:n}=e("../utils/trigonometry"),o=e("./copy");t.exports=(e,t,i,a)=>{let[l,h,c]=a;const u=l*l+h*h+c*c;if(Math.abs(u){const n=s(i),o=r(i),a=t[4],l=t[5],h=t[6],c=t[7],u=t[8],d=t[9],p=t[10],f=t[11];return t!==e&&(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[4]=a*o+u*n,e[5]=l*o+d*n,e[6]=h*o+p*n,e[7]=c*o+f*n,e[8]=u*o-a*n,e[9]=d*o-l*n,e[10]=p*o-h*n,e[11]=f*o-c*n,e}},{"../utils/trigonometry":188}],168:[function(e,t,i){const{sin:s,cos:r}=e("../utils/trigonometry");t.exports=(e,t,i)=>{const n=s(i),o=r(i),a=t[0],l=t[1],h=t[2],c=t[3],u=t[8],d=t[9],p=t[10],f=t[11];return t!==e&&(e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=a*o-u*n,e[1]=l*o-d*n,e[2]=h*o-p*n,e[3]=c*o-f*n,e[8]=a*n+u*o,e[9]=l*n+d*o,e[10]=h*n+p*o,e[11]=c*n+f*o,e}},{"../utils/trigonometry":188}],169:[function(e,t,i){const{sin:s,cos:r}=e("../utils/trigonometry");t.exports=(e,t,i)=>{const n=s(i),o=r(i),a=t[0],l=t[1],h=t[2],c=t[3],u=t[4],d=t[5],p=t[6],f=t[7];return t!==e&&(e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=a*o+u*n,e[1]=l*o+d*n,e[2]=h*o+p*n,e[3]=c*o+f*n,e[4]=u*o-a*n,e[5]=d*o-l*n,e[6]=p*o-h*n,e[7]=f*o-c*n,e}},{"../utils/trigonometry":188}],170:[function(e,t,i){t.exports=(e,t,i)=>{const s=i[0],r=i[1],n=i[2];return e[0]=t[0]*s,e[1]=t[1]*s,e[2]=t[2]*s,e[3]=t[3]*s,e[4]=t[4]*r,e[5]=t[5]*r,e[6]=t[6]*r,e[7]=t[7]*r,e[8]=t[8]*n,e[9]=t[9]*n,e[10]=t[10]*n,e[11]=t[11]*n,e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}},{}],171:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]-i[0],e[1]=t[1]-i[1],e[2]=t[2]-i[2],e[3]=t[3]-i[3],e[4]=t[4]-i[4],e[5]=t[5]-i[5],e[6]=t[6]-i[6],e[7]=t[7]-i[7],e[8]=t[8]-i[8],e[9]=t[9]-i[9],e[10]=t[10]-i[10],e[11]=t[11]-i[11],e[12]=t[12]-i[12],e[13]=t[13]-i[13],e[14]=t[14]-i[14],e[15]=t[15]-i[15],e)},{}],172:[function(e,t,i){t.exports=e=>e.map((e=>e.toFixed(7))).toString()},{}],173:[function(e,t,i){t.exports=(e,t,i)=>{const s=i[0],r=i[1],n=i[2];let o,a,l,h,c,u,d,p,f,_,m,g;return t===e?(e[12]=t[0]*s+t[4]*r+t[8]*n+t[12],e[13]=t[1]*s+t[5]*r+t[9]*n+t[13],e[14]=t[2]*s+t[6]*r+t[10]*n+t[14],e[15]=t[3]*s+t[7]*r+t[11]*n+t[15]):(o=t[0],a=t[1],l=t[2],h=t[3],c=t[4],u=t[5],d=t[6],p=t[7],f=t[8],_=t[9],m=t[10],g=t[11],e[0]=o,e[1]=a,e[2]=l,e[3]=h,e[4]=c,e[5]=u,e[6]=d,e[7]=p,e[8]=f,e[9]=_,e[10]=m,e[11]=g,e[12]=o*s+c*r+f*n+t[12],e[13]=a*s+u*r+_*n+t[13],e[14]=l*s+d*r+m*n+t[14],e[15]=h*s+p*r+g*n+t[15]),e}},{}],174:[function(e,t,i){t.exports=(e,t)=>(e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e[3]=-t[3],e)},{}],175:[function(e,t,i){const s=e("../vec3");t.exports=(e,t,i)=>{const r=s.normalize(s.create(),t),n=s.dot(i,r);return e[0]=r[0],e[1]=r[1],e[2]=r[2],e[3]=n,e}},{"../vec3":237}],176:[function(e,t,i){const s=e("../vec3");t.exports=(e,...t)=>{const i=t.length,r=s.create(),n=s.create(),o=e=>{const o=t[e],a=t[(e+1)%i],l=t[(e+2)%i];return s.subtract(r,a,o),s.subtract(n,l,o),s.cross(r,r,n),s.normalize(r,r),r};return e[0]=0,e[1]=0,e[2]=0,3===i?s.copy(e,o(0)):(t.forEach(((t,i)=>{s.add(e,e,o(i))})),s.normalize(e,e)),e[3]=s.dot(e,t[0]),e}},{"../vec3":237}],177:[function(e,t,i){const{EPS:s}=e("../constants"),r=e("../vec3");t.exports=(e,t,i,n)=>{let o=r.subtract(r.create(),i,t),a=r.subtract(r.create(),n,t);r.length(o){const i=t[0]*e[0]+t[1]*e[1]+t[2]*e[2]-e[3],r=t[0]-i*e[0],n=t[1]-i*e[1],o=t[2]-i*e[2];return s.fromValues(r,n,o)}},{"../vec3":237}],180:[function(e,t,i){const s=e("../vec3");t.exports=(e,t)=>s.dot(e,t)-e[3]},{"../vec3":237}],181:[function(e,t,i){const s=e("../mat4"),r=e("../vec3"),n=e("./fromPoints"),o=e("./flip");t.exports=(e,t,i)=>{const a=s.isMirroring(i),l=r.orthogonal(r.create(),t),h=r.cross(l,t,l),c=r.cross(r.create(),t,h);let u=r.fromScalar(r.create(),t[3]);r.multiply(u,u,t);let d=r.add(r.create(),u,h),p=r.add(r.create(),u,c);return u=r.transform(u,u,i),d=r.transform(d,d,i),p=r.transform(p,p,i),n(e,u,d,p),a&&o(e,e),e}},{"../mat4":159,"../vec3":237,"./flip":174,"./fromPoints":176}],182:[function(e,t,i){const{NEPS:s}=e("../constants");t.exports=(e,t)=>Math.abs(e[0]-t[0])<=s&&Math.abs(e[1]-t[1])<=s&&Math.abs(e[2]-t[2])<=s},{"../constants":110}],183:[function(e,t,i){t.exports=e=>{let t=0;for(let i=0;i{let s,r=i-e[1],n=t[1]-e[1];return n<0&&(r=-r,n=-n),s=r<=0?0:r>=n?1:n<1e-10?.5:r/n,e[0]+s*(t[0]-e[0])}},{}],186:[function(e,t,i){t.exports=(e,t,i,s)=>{if(e[0]===t[0]&&e[1]===t[1]||i[0]===s[0]&&i[1]===s[1])return;const r=(s[1]-i[1])*(t[0]-e[0])-(s[0]-i[0])*(t[1]-e[1]);if(Math.abs(r)1||o<0||o>1?void 0:[e[0]+n*(t[0]-e[0]),e[1]+n*(t[1]-e[1])]}},{}],187:[function(e,t,i){t.exports=(e,t,i,s,r,n)=>{const o=1/(e*s-t*i);let a=r*s-t*n,l=-r*i+e*n;return a*=o,l*=o,[a,l]}},{}],188:[function(e,t,i){const{NEPS:s}=e("../constants"),r=e=>Math.abs(e)r(Math.sin(e)),cos:e=>r(Math.cos(e))}},{"../constants":110}],189:[function(e,t,i){t.exports=(e,t)=>(e[0]=Math.abs(t[0]),e[1]=Math.abs(t[1]),e)},{}],190:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]+i[0],e[1]=t[1]+i[1],e)},{}],191:[function(e,t,i){t.exports=e("./angleRadians")},{"./angleRadians":193}],192:[function(e,t,i){const s=e("./angleRadians");t.exports=e=>57.29577951308232*s(e)},{"./angleRadians":193}],193:[function(e,t,i){t.exports=e=>Math.atan2(e[1],e[0])},{}],194:[function(e,t,i){const s=e("./create");t.exports=e=>{const t=s();return t[0]=e[0],t[1]=e[1],t}},{"./create":196}],195:[function(e,t,i){t.exports=(e,t)=>(e[0]=t[0],e[1]=t[1],e)},{}],196:[function(e,t,i){t.exports=()=>[0,0]},{}],197:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=0,e[1]=0,e[2]=t[0]*i[1]-t[1]*i[0],e)},{}],198:[function(e,t,i){t.exports=(e,t)=>{const i=t[0]-e[0],s=t[1]-e[1];return Math.sqrt(i*i+s*s)}},{}],199:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]/i[0],e[1]=t[1]/i[1],e)},{}],200:[function(e,t,i){t.exports=(e,t)=>e[0]*t[0]+e[1]*t[1]},{}],201:[function(e,t,i){t.exports=(e,t)=>e[0]===t[0]&&e[1]===t[1]},{}],202:[function(e,t,i){const s=e("./fromAngleRadians");t.exports=(e,t)=>s(e,.017453292519943295*t)},{"./fromAngleRadians":203}],203:[function(e,t,i){const{sin:s,cos:r}=e("../utils/trigonometry");t.exports=(e,t)=>(e[0]=r(t),e[1]=s(t),e)},{"../utils/trigonometry":188}],204:[function(e,t,i){t.exports=(e,t)=>(e[0]=t,e[1]=t,e)},{}],205:[function(e,t,i){const s=e("./create");t.exports=(e,t)=>{const i=s();return i[0]=e,i[1]=t,i}},{"./create":196}],206:[function(e,t,i){t.exports={abs:e("./abs"),add:e("./add"),angle:e("./angle"),angleDegrees:e("./angleDegrees"),angleRadians:e("./angleRadians"),clone:e("./clone"),copy:e("./copy"),create:e("./create"),cross:e("./cross"),distance:e("./distance"),divide:e("./divide"),dot:e("./dot"),equals:e("./equals"),fromAngleDegrees:e("./fromAngleDegrees"),fromAngleRadians:e("./fromAngleRadians"),fromScalar:e("./fromScalar"),fromValues:e("./fromValues"),length:e("./length"),lerp:e("./lerp"),max:e("./max"),min:e("./min"),multiply:e("./multiply"),negate:e("./negate"),normal:e("./normal"),normalize:e("./normalize"),rotate:e("./rotate"),scale:e("./scale"),snap:e("./snap"),squaredDistance:e("./squaredDistance"),squaredLength:e("./squaredLength"),subtract:e("./subtract"),toString:e("./toString"),transform:e("./transform")}},{"./abs":189,"./add":190,"./angle":191,"./angleDegrees":192,"./angleRadians":193,"./clone":194,"./copy":195,"./create":196,"./cross":197,"./distance":198,"./divide":199,"./dot":200,"./equals":201,"./fromAngleDegrees":202,"./fromAngleRadians":203,"./fromScalar":204,"./fromValues":205,"./length":207,"./lerp":208,"./max":209,"./min":210,"./multiply":211,"./negate":212,"./normal":213,"./normalize":214,"./rotate":215,"./scale":216,"./snap":217,"./squaredDistance":218,"./squaredLength":219,"./subtract":220,"./toString":221,"./transform":222}],207:[function(e,t,i){t.exports=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1])},{}],208:[function(e,t,i){t.exports=(e,t,i,s)=>{const r=t[0],n=t[1];return e[0]=r+s*(i[0]-r),e[1]=n+s*(i[1]-n),e}},{}],209:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=Math.max(t[0],i[0]),e[1]=Math.max(t[1],i[1]),e)},{}],210:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=Math.min(t[0],i[0]),e[1]=Math.min(t[1],i[1]),e)},{}],211:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]*i[0],e[1]=t[1]*i[1],e)},{}],212:[function(e,t,i){t.exports=(e,t)=>(e[0]=-t[0],e[1]=-t[1],e)},{}],213:[function(e,t,i){const{TAU:s}=e("../constants"),r=e("./create"),n=e("./rotate");t.exports=(e,t)=>n(e,t,r(),s/4)},{"../constants":110,"./create":196,"./rotate":215}],214:[function(e,t,i){t.exports=(e,t)=>{const i=t[0],s=t[1];let r=i*i+s*s;return r>0&&(r=1/Math.sqrt(r)),e[0]=i*r,e[1]=s*r,e}},{}],215:[function(e,t,i){t.exports=(e,t,i,s)=>{const r=t[0]-i[0],n=t[1]-i[1],o=Math.cos(s),a=Math.sin(s);return e[0]=r*o-n*a+i[0],e[1]=r*a+n*o+i[1],e}},{}],216:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]*i,e[1]=t[1]*i,e)},{}],217:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=Math.round(t[0]/i)*i+0,e[1]=Math.round(t[1]/i)*i+0,e)},{}],218:[function(e,t,i){t.exports=(e,t)=>{const i=t[0]-e[0],s=t[1]-e[1];return i*i+s*s}},{}],219:[function(e,t,i){t.exports=e=>{const t=e[0],i=e[1];return t*t+i*i}},{}],220:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]-i[0],e[1]=t[1]-i[1],e)},{}],221:[function(e,t,i){t.exports=e=>`[${e[0].toFixed(7)}, ${e[1].toFixed(7)}]`},{}],222:[function(e,t,i){t.exports=(e,t,i)=>{const s=t[0],r=t[1];return e[0]=i[0]*s+i[4]*r+i[12],e[1]=i[1]*s+i[5]*r+i[13],e}},{}],223:[function(e,t,i){t.exports=(e,t)=>(e[0]=Math.abs(t[0]),e[1]=Math.abs(t[1]),e[2]=Math.abs(t[2]),e)},{}],224:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]+i[0],e[1]=t[1]+i[1],e[2]=t[2]+i[2],e)},{}],225:[function(e,t,i){const s=e("./dot");t.exports=(e,t)=>{const i=e[0],r=e[1],n=e[2],o=t[0],a=t[1],l=t[2],h=Math.sqrt(i*i+r*r+n*n)*Math.sqrt(o*o+a*a+l*l),c=h&&s(e,t)/h;return Math.acos(Math.min(Math.max(c,-1),1))}},{"./dot":232}],226:[function(e,t,i){const s=e("./create");t.exports=e=>{const t=s();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}},{"./create":228}],227:[function(e,t,i){t.exports=(e,t)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],e)},{}],228:[function(e,t,i){t.exports=()=>[0,0,0]},{}],229:[function(e,t,i){t.exports=(e,t,i)=>{const s=t[0],r=t[1],n=t[2],o=i[0],a=i[1],l=i[2];return e[0]=r*l-n*a,e[1]=n*o-s*l,e[2]=s*a-r*o,e}},{}],230:[function(e,t,i){t.exports=(e,t)=>{const i=t[0]-e[0],s=t[1]-e[1],r=t[2]-e[2];return Math.sqrt(i*i+s*s+r*r)}},{}],231:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]/i[0],e[1]=t[1]/i[1],e[2]=t[2]/i[2],e)},{}],232:[function(e,t,i){t.exports=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]},{}],233:[function(e,t,i){t.exports=(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]},{}],234:[function(e,t,i){t.exports=(e,t)=>(e[0]=t,e[1]=t,e[2]=t,e)},{}],235:[function(e,t,i){const s=e("./create");t.exports=(e,t,i)=>{const r=s();return r[0]=e,r[1]=t,r[2]=i,r}},{"./create":228}],236:[function(e,t,i){t.exports=(e,t,i=0)=>(e[0]=t[0],e[1]=t[1],e[2]=i,e)},{}],237:[function(e,t,i){t.exports={abs:e("./abs"),add:e("./add"),angle:e("./angle"),clone:e("./clone"),copy:e("./copy"),create:e("./create"),cross:e("./cross"),distance:e("./distance"),divide:e("./divide"),dot:e("./dot"),equals:e("./equals"),fromScalar:e("./fromScalar"),fromValues:e("./fromValues"),fromVec2:e("./fromVec2"),length:e("./length"),lerp:e("./lerp"),max:e("./max"),min:e("./min"),multiply:e("./multiply"),negate:e("./negate"),normalize:e("./normalize"),orthogonal:e("./orthogonal"),rotateX:e("./rotateX"),rotateY:e("./rotateY"),rotateZ:e("./rotateZ"),scale:e("./scale"),snap:e("./snap"),squaredDistance:e("./squaredDistance"),squaredLength:e("./squaredLength"),subtract:e("./subtract"),toString:e("./toString"),transform:e("./transform")}},{"./abs":223,"./add":224,"./angle":225,"./clone":226,"./copy":227,"./create":228,"./cross":229,"./distance":230,"./divide":231,"./dot":232,"./equals":233,"./fromScalar":234,"./fromValues":235,"./fromVec2":236,"./length":238,"./lerp":239,"./max":240,"./min":241,"./multiply":242,"./negate":243,"./normalize":244,"./orthogonal":245,"./rotateX":246,"./rotateY":247,"./rotateZ":248,"./scale":249,"./snap":250,"./squaredDistance":251,"./squaredLength":252,"./subtract":253,"./toString":254,"./transform":255}],238:[function(e,t,i){t.exports=e=>{const t=e[0],i=e[1],s=e[2];return Math.sqrt(t*t+i*i+s*s)}},{}],239:[function(e,t,i){t.exports=(e,t,i,s)=>(e[0]=t[0]+s*(i[0]-t[0]),e[1]=t[1]+s*(i[1]-t[1]),e[2]=t[2]+s*(i[2]-t[2]),e)},{}],240:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=Math.max(t[0],i[0]),e[1]=Math.max(t[1],i[1]),e[2]=Math.max(t[2],i[2]),e)},{}],241:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=Math.min(t[0],i[0]),e[1]=Math.min(t[1],i[1]),e[2]=Math.min(t[2],i[2]),e)},{}],242:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]*i[0],e[1]=t[1]*i[1],e[2]=t[2]*i[2],e)},{}],243:[function(e,t,i){t.exports=(e,t)=>(e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e)},{}],244:[function(e,t,i){t.exports=(e,t)=>{const i=t[0],s=t[1],r=t[2];let n=i*i+s*s+r*r;return n>0&&(n=1/Math.sqrt(n)),e[0]=i*n,e[1]=s*n,e[2]=r*n,e}},{}],245:[function(e,t,i){const s=e("./abs"),r=e("./create"),n=e("./cross");t.exports=(e,t)=>{const i=s(r(),t),o=0+(i[0]{const r=[],n=[];return r[0]=t[0]-i[0],r[1]=t[1]-i[1],r[2]=t[2]-i[2],n[0]=r[0],n[1]=r[1]*Math.cos(s)-r[2]*Math.sin(s),n[2]=r[1]*Math.sin(s)+r[2]*Math.cos(s),e[0]=n[0]+i[0],e[1]=n[1]+i[1],e[2]=n[2]+i[2],e}},{}],247:[function(e,t,i){t.exports=(e,t,i,s)=>{const r=[],n=[];return r[0]=t[0]-i[0],r[1]=t[1]-i[1],r[2]=t[2]-i[2],n[0]=r[2]*Math.sin(s)+r[0]*Math.cos(s),n[1]=r[1],n[2]=r[2]*Math.cos(s)-r[0]*Math.sin(s),e[0]=n[0]+i[0],e[1]=n[1]+i[1],e[2]=n[2]+i[2],e}},{}],248:[function(e,t,i){t.exports=(e,t,i,s)=>{const r=[],n=[];return r[0]=t[0]-i[0],r[1]=t[1]-i[1],n[0]=r[0]*Math.cos(s)-r[1]*Math.sin(s),n[1]=r[0]*Math.sin(s)+r[1]*Math.cos(s),e[0]=n[0]+i[0],e[1]=n[1]+i[1],e[2]=t[2],e}},{}],249:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]*i,e[1]=t[1]*i,e[2]=t[2]*i,e)},{}],250:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=Math.round(t[0]/i)*i+0,e[1]=Math.round(t[1]/i)*i+0,e[2]=Math.round(t[2]/i)*i+0,e)},{}],251:[function(e,t,i){t.exports=(e,t)=>{const i=t[0]-e[0],s=t[1]-e[1],r=t[2]-e[2];return i*i+s*s+r*r}},{}],252:[function(e,t,i){t.exports=e=>{const t=e[0],i=e[1],s=e[2];return t*t+i*i+s*s}},{}],253:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]-i[0],e[1]=t[1]-i[1],e[2]=t[2]-i[2],e)},{}],254:[function(e,t,i){t.exports=e=>`[${e[0].toFixed(7)}, ${e[1].toFixed(7)}, ${e[2].toFixed(7)}]`},{}],255:[function(e,t,i){t.exports=(e,t,i)=>{const s=t[0],r=t[1],n=t[2];let o=i[3]*s+i[7]*r+i[11]*n+i[15];return o=o||1,e[0]=(i[0]*s+i[4]*r+i[8]*n+i[12])/o,e[1]=(i[1]*s+i[5]*r+i[9]*n+i[13])/o,e[2]=(i[2]*s+i[6]*r+i[10]*n+i[14])/o,e}},{}],256:[function(e,t,i){const s=e("./create");t.exports=e=>{const t=s();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}},{"./create":258}],257:[function(e,t,i){t.exports=(e,t)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e)},{}],258:[function(e,t,i){t.exports=()=>[0,0,0,0]},{}],259:[function(e,t,i){t.exports=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]},{}],260:[function(e,t,i){t.exports=(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]},{}],261:[function(e,t,i){t.exports=(e,t)=>(e[0]=t,e[1]=t,e[2]=t,e[3]=t,e)},{}],262:[function(e,t,i){const s=e("./create");t.exports=(e,t,i,r)=>{const n=s();return n[0]=e,n[1]=t,n[2]=i,n[3]=r,n}},{"./create":258}],263:[function(e,t,i){t.exports={clone:e("./clone"),copy:e("./copy"),create:e("./create"),dot:e("./dot"),equals:e("./equals"),fromScalar:e("./fromScalar"),fromValues:e("./fromValues"),toString:e("./toString"),transform:e("./transform")}},{"./clone":256,"./copy":257,"./create":258,"./dot":259,"./equals":260,"./fromScalar":261,"./fromValues":262,"./toString":264,"./transform":265}],264:[function(e,t,i){t.exports=e=>`(${e[0].toFixed(9)}, ${e[1].toFixed(9)}, ${e[2].toFixed(9)}, ${e[3].toFixed(9)})`},{}],265:[function(e,t,i){t.exports=(e,t,i)=>{const[s,r,n,o]=t;return e[0]=i[0]*s+i[4]*r+i[8]*n+i[12]*o,e[1]=i[1]*s+i[5]*r+i[9]*n+i[13]*o,e[2]=i[2]*s+i[6]*r+i[10]*n+i[14]*o,e[3]=i[3]*s+i[7]*r+i[11]*n+i[15]*o,e}},{}],266:[function(e,t,i){const{EPS:s}=e("../maths/constants");t.exports=(e,t)=>{let i=0;for(let s=0;s{if(0===(e=s(e)).length)throw new Error("measureAggregateArea: no geometries supplied");const t=r(e);return 1===e.length?t:t.reduce(((e,t)=>e+t),0)}},{"../utils/flatten":412,"./measureArea":272}],269:[function(e,t,i){const s=e("../utils/flatten"),r=e("../maths/vec3/min"),n=e("../maths/vec3/max"),o=e("./measureBoundingBox");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("measureAggregateBoundingBox: no geometries supplied");const t=o(e);if(1===e.length)return t;const i=[[Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE],[-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE]];return t.reduce(((e,t)=>[r(e[0],e[0],t[0]),n(e[1],e[1],t[1])]),i)}},{"../maths/vec3/max":240,"../maths/vec3/min":241,"../utils/flatten":412,"./measureBoundingBox":273}],270:[function(e,t,i){const s=e("../utils/flatten"),r=e("./measureAggregateBoundingBox"),n=e("./calculateEpsilonFromBounds"),{geom2:o,geom3:a,path2:l}=e("../geometries");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("measureAggregateEpsilon: no geometries supplied");const t=r(e);let i=0;return i=e.reduce(((e,t)=>l.isA(t)||o.isA(t)?Math.max(e,2):a.isA(t)?Math.max(e,3):0),i),n(t,i)}},{"../geometries":66,"../utils/flatten":412,"./calculateEpsilonFromBounds":266,"./measureAggregateBoundingBox":269}],271:[function(e,t,i){const s=e("../utils/flatten"),r=e("./measureVolume");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("measureAggregateVolume: no geometries supplied");const t=r(e);return 1===e.length?t:t.reduce(((e,t)=>e+t),0)}},{"../utils/flatten":412,"./measureVolume":279}],272:[function(e,t,i){const s=e("../utils/flatten"),r=e("../geometries/geom2"),n=e("../geometries/geom3"),o=e("../geometries/path2"),a=e("../geometries/poly3"),l=new WeakMap;t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>o.isA(e)?0:r.isA(e)?(e=>{let t=l.get(e);return t||(t=r.toSides(e).reduce(((e,t)=>e+(t[0][0]*t[1][1]-t[0][1]*t[1][0])),0),t*=.5,l.set(e,t),t)})(e):n.isA(e)?(e=>{let t=l.get(e);return t||(t=n.toPolygons(e).reduce(((e,t)=>e+a.measureArea(t)),0),l.set(e,t),t)})(e):0));return 1===t.length?t[0]:t}},{"../geometries/geom2":42,"../geometries/geom3":57,"../geometries/path2":78,"../geometries/poly3":95,"../utils/flatten":412}],273:[function(e,t,i){const s=e("../utils/flatten"),r=e("../maths/vec2"),n=e("../maths/vec3"),o=e("../geometries/geom2"),a=e("../geometries/geom3"),l=e("../geometries/path2"),h=e("../geometries/poly3"),c=new WeakMap;t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>l.isA(e)?(e=>{let t=c.get(e);if(t)return t;const i=l.toPoints(e);let s;s=0===i.length?r.create():r.clone(i[0]);let n=r.clone(s);return i.forEach((e=>{r.min(s,s,e),r.max(n,n,e)})),s=[s[0],s[1],0],n=[n[0],n[1],0],t=[s,n],c.set(e,t),t})(e):o.isA(e)?(e=>{let t=c.get(e);if(t)return t;const i=o.toPoints(e);let s;s=0===i.length?r.create():r.clone(i[0]);let n=r.clone(s);return i.forEach((e=>{r.min(s,s,e),r.max(n,n,e)})),s=[s[0],s[1],0],n=[n[0],n[1],0],t=[s,n],c.set(e,t),t})(e):a.isA(e)?(e=>{let t=c.get(e);if(t)return t;const i=a.toPolygons(e);let s=n.create();if(i.length>0){const e=h.toPoints(i[0]);n.copy(s,e[0])}let r=n.clone(s);return i.forEach((e=>{h.toPoints(e).forEach((e=>{n.min(s,s,e),n.max(r,r,e)}))})),s=[s[0],s[1],s[2]],r=[r[0],r[1],r[2]],t=[s,r],c.set(e,t),t})(e):[[0,0,0],[0,0,0]]));return 1===t.length?t[0]:t}},{"../geometries/geom2":42,"../geometries/geom3":57,"../geometries/path2":78,"../geometries/poly3":95,"../maths/vec2":206,"../maths/vec3":237,"../utils/flatten":412}],274:[function(e,t,i){const s=e("../utils/flatten"),r=e("../maths/vec2"),n=e("../maths/vec3"),o=e("../geometries/geom2"),a=e("../geometries/geom3"),l=e("../geometries/path2"),h=e("../geometries/poly3"),c=new WeakMap;t.exports=(...e)=>{const t=(e=s(e)).map((e=>l.isA(e)?(e=>{let t=c.get(e);if(void 0!==t)return t;const i=n.create();let s=0;const o=l.toPoints(e);if(o.length>0){let e=0;const t=n.create();o.forEach((s=>{n.add(i,i,n.fromVec2(t,s,0)),e++})),n.scale(i,i,1/e),o.forEach((e=>{s=Math.max(s,r.squaredDistance(i,e))})),s=Math.sqrt(s)}return t=[i,s],c.set(e,t),t})(e):o.isA(e)?(e=>{let t=c.get(e);if(void 0!==t)return t;const i=n.create();let s=0;const a=o.toSides(e);if(a.length>0){let e=0;const t=n.create();a.forEach((s=>{n.add(i,i,n.fromVec2(t,s[0],0)),e++})),n.scale(i,i,1/e),a.forEach((e=>{s=Math.max(s,r.squaredDistance(i,e[0]))})),s=Math.sqrt(s)}return t=[i,s],c.set(e,t),t})(e):a.isA(e)?(e=>{let t=c.get(e);if(void 0!==t)return t;const i=n.create();let s=0;const r=a.toPolygons(e);if(r.length>0){let e=0;r.forEach((t=>{h.toPoints(t).forEach((t=>{n.add(i,i,t),e++}))})),n.scale(i,i,1/e),r.forEach((e=>{h.toPoints(e).forEach((e=>{s=Math.max(s,n.squaredDistance(i,e))}))})),s=Math.sqrt(s)}return t=[i,s],c.set(e,t),t})(e):[[0,0,0],0]));return 1===t.length?t[0]:t}},{"../geometries/geom2":42,"../geometries/geom3":57,"../geometries/path2":78,"../geometries/poly3":95,"../maths/vec2":206,"../maths/vec3":237,"../utils/flatten":412}],275:[function(e,t,i){const s=e("../utils/flatten"),r=e("./measureBoundingBox");t.exports=(...e)=>{const t=(e=s(e)).map((e=>{const t=r(e);return[t[0][0]+(t[1][0]-t[0][0])/2,t[0][1]+(t[1][1]-t[0][1])/2,t[0][2]+(t[1][2]-t[0][2])/2]}));return 1===t.length?t[0]:t}},{"../utils/flatten":412,"./measureBoundingBox":273}],276:[function(e,t,i){const s=e("../utils/flatten"),r=e("../maths/vec3"),n=e("../geometries/geom2"),o=e("../geometries/geom3"),a=new WeakMap;t.exports=(...e)=>{const t=(e=s(e)).map((e=>n.isA(e)?(e=>{let t=a.get(e);if(void 0!==t)return t;const i=n.toSides(e);let s=0,o=0,l=0;if(i.length>0){for(let e=0;e{let t=a.get(e);if(void 0!==t)return t;t=r.create();const i=o.toPolygons(e);if(0===i.length)return t;let s=0;const n=r.create();return i.forEach((e=>{const i=e.vertices;for(let e=0;e{const t=(e=s(e)).map((e=>{const t=r(e);return[t[1][0]-t[0][0],t[1][1]-t[0][1],t[1][2]-t[0][2]]}));return 1===t.length?t[0]:t}},{"../utils/flatten":412,"./measureBoundingBox":273}],278:[function(e,t,i){const s=e("../utils/flatten"),{geom2:r,geom3:n,path2:o}=e("../geometries"),a=e("./calculateEpsilonFromBounds"),l=e("./measureBoundingBox");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>o.isA(e)||r.isA(e)?(e=>a(l(e),2))(e):n.isA(e)?(e=>a(l(e),3))(e):0));return 1===t.length?t[0]:t}},{"../geometries":66,"../utils/flatten":412,"./calculateEpsilonFromBounds":266,"./measureBoundingBox":273}],279:[function(e,t,i){const s=e("../utils/flatten"),r=e("../geometries/geom2"),n=e("../geometries/geom3"),o=e("../geometries/path2"),a=e("../geometries/poly3"),l=new WeakMap;t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>o.isA(e)||r.isA(e)?0:n.isA(e)?(e=>{let t=l.get(e);return t||(t=n.toPolygons(e).reduce(((e,t)=>e+a.measureSignedVolume(t)),0),l.set(e,t),t)})(e):0));return 1===t.length?t[0]:t}},{"../geometries/geom2":42,"../geometries/geom3":57,"../geometries/path2":78,"../geometries/poly3":95,"../utils/flatten":412}],280:[function(e,t,i){const s=e("../../maths/vec2"),r=e("../../geometries/geom2");t.exports=(e,t)=>{const i=t.map((t=>((e,t)=>{if(t.vertices.length<4)return null;const i=[],r=t.vertices.filter(((e,t)=>e[2]>0&&(i.push(t),!0)));if(2!==r.length)throw new Error("Assertion failed: fromFakePolygon: not enough points found");const n=r.map((t=>{const i=Math.round(t[0]/e)*e+0,r=Math.round(t[1]/e)*e+0;return s.fromValues(i,r)}));if(s.equals(n[0],n[1]))return null;const o=i[1]-i[0];if(1!==o&&3!==o)throw new Error("Assertion failed: fromFakePolygon: unknown index ordering");return 1===o&&n.reverse(),n})(e,t))).filter((e=>null!==e));return r.create(i)}},{"../../geometries/geom2":42,"../../maths/vec2":206}],281:[function(e,t,i){t.exports={intersect:e("./intersect"),scission:e("./scission"),subtract:e("./subtract"),union:e("./union")}},{"./intersect":282,"./scission":287,"./subtract":289,"./union":300}],282:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../utils/areAllShapesTheSameType"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("./intersectGeom2"),l=e("./intersectGeom3");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");if(!r(e))throw new Error("only intersect of the types are supported");const t=e[0];return n.isA(t)?a(e):o.isA(t)?l(e):t}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../utils/areAllShapesTheSameType":410,"../../utils/flatten":412,"./intersectGeom2":283,"./intersectGeom3":284}],283:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom3"),n=e("../../measurements/measureEpsilon"),o=e("./fromFakePolygons"),a=e("./to3DWalls"),l=e("./intersectGeom3");t.exports=(...e)=>{const t=(e=s(e)).map((e=>a({z0:-1,z1:1},e))),i=l(t),h=n(i);return o(h,r.toPolygons(i))}},{"../../geometries/geom3":57,"../../measurements/measureEpsilon":278,"../../utils/flatten":412,"./fromFakePolygons":280,"./intersectGeom3":284,"./to3DWalls":293}],284:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../modifiers/retessellate"),n=e("./intersectGeom3Sub");t.exports=(...e)=>{let t=(e=s(e)).shift();return e.forEach((e=>{t=n(t,e)})),t=r(t),t}},{"../../utils/flatten":412,"../modifiers/retessellate":370,"./intersectGeom3Sub":285}],285:[function(e,t,i){const s=e("../../geometries/geom3"),r=e("./mayOverlap"),{Tree:n}=e("./trees");t.exports=(e,t)=>{if(!r(e,t))return s.create();const i=new n(s.toPolygons(e)),o=new n(s.toPolygons(t));i.invert(),o.clipTo(i),o.invert(),i.clipTo(o),o.clipTo(i),i.addPolygons(o.allPolygons()),i.invert();const a=i.allPolygons();return s.create(a)}},{"../../geometries/geom3":57,"./mayOverlap":286,"./trees":297}],286:[function(e,t,i){const{EPS:s}=e("../../maths/constants"),r=e("../../measurements/measureBoundingBox");t.exports=(e,t)=>{if(0===e.polygons.length||0===t.polygons.length)return!1;const i=r(e),n=i[0],o=i[1],a=r(t),l=a[0],h=a[1];return!(l[0]-o[0]>s||n[0]-h[0]>s||l[1]-o[1]>s||n[1]-h[1]>s||l[2]-o[2]>s||n[2]-h[2]>s)}},{"../../maths/constants":110,"../../measurements/measureBoundingBox":273}],287:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom3"),n=e("./scissionGeom3");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>r.isA(e)?n(e):e));return 1===t.length?t[0]:t}},{"../../geometries/geom3":57,"../../utils/flatten":412,"./scissionGeom3":288}],288:[function(e,t,i){const s=e("../../maths/vec3"),r=e("../../measurements/measureEpsilon"),n=e("../../geometries/geom3");t.exports=e=>{const t=r(e),i=n.toPolygons(e),o=i.length,a=new Map,l=s.create();i.forEach(((e,i)=>{e.vertices.forEach((e=>{((e,t,i)=>{const s=`${t}`,r=e.get(s);void 0===r?e.set(s,[i]):r.push(i)})(a,s.snap(l,e,t),i)}))}));const h=i.map((e=>{let i=[];return e.vertices.forEach((e=>{i=i.concat(((e,t)=>{const i=`${t}`;return e.get(i)})(a,s.snap(l,e,t)))})),{e:1,d:(r=i,r.sort(((e,t)=>e-t)).filter(((e,t,i)=>!t||e!==i[t-1])))};var r}));a.clear();let c=0;const u=h.length;for(let e=0;e0){const i=new Array(o);i[e]=!0;do{c=0,i.forEach(((e,t)=>{const s=h[t];if(s.e>0){s.e=-1;for(let e=0;e0);t.indexes=i}}const d=[];for(let e=0;et.push(i[s]))),d.push(n.create(t))}return d}},{"../../geometries/geom3":57,"../../maths/vec3":237,"../../measurements/measureEpsilon":278}],289:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../utils/areAllShapesTheSameType"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("./subtractGeom2"),l=e("./subtractGeom3");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");if(!r(e))throw new Error("only subtract of the types are supported");const t=e[0];return n.isA(t)?a(e):o.isA(t)?l(e):t}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../utils/areAllShapesTheSameType":410,"../../utils/flatten":412,"./subtractGeom2":290,"./subtractGeom3":291}],290:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom3"),n=e("../../measurements/measureEpsilon"),o=e("./fromFakePolygons"),a=e("./to3DWalls"),l=e("./subtractGeom3");t.exports=(...e)=>{const t=(e=s(e)).map((e=>a({z0:-1,z1:1},e))),i=l(t),h=n(i);return o(h,r.toPolygons(i))}},{"../../geometries/geom3":57,"../../measurements/measureEpsilon":278,"../../utils/flatten":412,"./fromFakePolygons":280,"./subtractGeom3":291,"./to3DWalls":293}],291:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../modifiers/retessellate"),n=e("./subtractGeom3Sub");t.exports=(...e)=>{let t=(e=s(e)).shift();return e.forEach((e=>{t=n(t,e)})),t=r(t),t}},{"../../utils/flatten":412,"../modifiers/retessellate":370,"./subtractGeom3Sub":292}],292:[function(e,t,i){const s=e("../../geometries/geom3"),r=e("./mayOverlap"),{Tree:n}=e("./trees");t.exports=(e,t)=>{if(!r(e,t))return s.clone(e);const i=new n(s.toPolygons(e)),o=new n(s.toPolygons(t));i.invert(),i.clipTo(o),o.clipTo(i,!0),i.addPolygons(o.allPolygons()),i.invert();const a=i.allPolygons();return s.create(a)}},{"../../geometries/geom3":57,"./mayOverlap":286,"./trees":297}],293:[function(e,t,i){const s=e("../../maths/vec3"),r=e("../../geometries/geom2"),n=e("../../geometries/geom3"),o=e("../../geometries/poly3");t.exports=(e,t)=>{const i=r.toSides(t).map((t=>((e,t,i)=>{const r=[s.fromVec2(s.create(),i[0],e),s.fromVec2(s.create(),i[1],e),s.fromVec2(s.create(),i[1],t),s.fromVec2(s.create(),i[0],t)];return o.create(r)})(e.z0,e.z1,t)));return n.create(i)}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/poly3":95,"../../maths/vec3":237}],294:[function(e,t,i){const s=e("../../../maths/plane"),r=e("../../../geometries/poly3");class n{constructor(e){this.plane=null,this.front=null,this.back=null,this.polygontreenodes=[],this.parent=e}invert(){const e=[this];let t;for(let i=0;i0&&r.push({node:i.front,polygontreenodes:o});const h=n.length;if(i.back&&h>0)r.push({node:i.back,polygontreenodes:n});else for(let e=0;e0&&e.rootnode.clipPolygons(i.polygontreenodes,t),i.front&&s.push(i.front),i.back&&s.push(i.back),i=s.pop()}while(void 0!==i)}addPolygonTreeNodes(e){let t={node:this,polygontreenodes:e};const i=[];do{const e=t.node,s=t.polygontreenodes;if(0===s.length){t=i.pop();continue}if(!e.plane){let t=0;t=Math.floor(s.length/2);const i=s[t].getPolygon();e.plane=r.plane(i)}const o=[],a=[],l=s.length;for(let t=0;t0&&(e.front||(e.front=new n(e)),l===o.length&&0===a.length?e.front.polygontreenodes=o:i.push({node:e.front,polygontreenodes:o})),a.length>0&&(e.back||(e.back=new n(e)),l===a.length&&0===o.length?e.back.polygontreenodes=a:i.push({node:e.back,polygontreenodes:a})),t=i.pop()}while(void 0!==t)}}t.exports=n},{"../../../geometries/poly3":95,"../../../maths/plane":178}],295:[function(e,t,i){const{EPS:s}=e("../../../maths/constants"),r=e("../../../maths/vec3"),n=e("../../../geometries/poly3"),o=e("./splitPolygonByPlane");class a{constructor(e,t){this.parent=e,this.children=[],this.polygon=t,this.removed=!1}addPolygons(e){if(!this.isRootNode())throw new Error("Assertion failed");const t=this;e.forEach((e=>{t.addChild(e)}))}remove(){if(!this.removed){this.removed=!0,this.polygon=null;const e=this.parent.children,t=e.indexOf(this);if(t<0)throw new Error("Assertion failed");e.splice(t,1),this.parent.recursivelyInvalidatePolygon()}}isRemoved(){return this.removed}isRootNode(){return!this.parent}invert(){if(!this.isRootNode())throw new Error("Assertion failed");this.invertSub()}getPolygon(){if(!this.polygon)throw new Error("Assertion failed");return this.polygon}getPolygons(e){let t=[this];const i=[t];let s,r,n,o;for(s=0;s0&&i.push(o.children)}splitByPlane(e,t,i,s,r){if(this.children.length){const n=[this.children];let o,a,l,h,c;for(o=0;o0?n.push(h.children):h._splitByPlane(e,t,i,s,r)}else this._splitByPlane(e,t,i,s,r)}_splitByPlane(e,t,i,a,l){const h=this.polygon;if(h){const c=n.measureBoundingSphere(h),u=c[3]+s,d=c,p=r.dot(e,d)-e[3];if(p>u)a.push(this);else if(p<-u)l.push(this);else{const s=o(e,h);switch(s.type){case 0:t.push(this);break;case 1:i.push(this);break;case 2:a.push(this);break;case 3:l.push(this);break;case 4:if(s.front){const e=this.addChild(s.front);a.push(e)}if(s.back){const e=this.addChild(s.back);l.push(e)}}}}}addChild(e){const t=new a(this,e);return this.children.push(t),t}invertSub(){let e=[this];const t=[e];let i,s,r,o;for(i=0;i0&&t.push(o.children)}recursivelyInvalidatePolygon(){this.polygon=null,this.parent&&this.parent.recursivelyInvalidatePolygon()}clear(){let e=[this];const t=[e];for(let i=0;i0&&t.push(s.children),s.children=[]}}}toString(){let e="",t=[this];const i=[t];let s,r,n,o;for(s=0;s0&&i.push(o.children)}return e}}t.exports=a},{"../../../geometries/poly3":95,"../../../maths/constants":110,"../../../maths/vec3":237,"./splitPolygonByPlane":299}],296:[function(e,t,i){const s=e("./Node"),r=e("./PolygonTreeNode");t.exports=class{constructor(e){this.polygonTree=new r,this.rootnode=new s(null),e&&this.addPolygons(e)}invert(){this.polygonTree.invert(),this.rootnode.invert()}clipTo(e,t=!1){this.rootnode.clipTo(e,t)}allPolygons(){const e=[];return this.polygonTree.getPolygons(e),e}addPolygons(e){const t=new Array(e.length);for(let i=0;i{const r=s.subtract(s.create(),i,t);let n=(e[3]-s.dot(e,t))/s.dot(e,r);return Number.isNaN(n)&&(n=0),n>1&&(n=1),n<0&&(n=0),s.scale(r,r,n),s.add(r,t,r),r}},{"../../../maths/vec3":237}],299:[function(e,t,i){const{EPS:s}=e("../../../maths/constants"),r=e("../../../maths/plane"),n=e("../../../maths/vec3"),o=e("../../../geometries/poly3"),a=e("./splitLineSegmentByPlane");t.exports=(e,t)=>{const i={type:null,front:null,back:null},l=t.vertices,h=l.length,c=o.plane(t);if(r.equals(c,e))i.type=0;else{let t=!1,r=!1;const u=[],d=-s;for(let i=0;is&&(t=!0),o=h&&(n=0);const o=u[n];if(d===o)d?r.push(s):t.push(s);else{const i=l[n],o=a(e,s,i);d?(r.push(s),r.push(o),t.push(o)):(t.push(s),t.push(o),r.push(o))}d=o}const p=s*s;if(r.length>=3){let e=r[r.length-1];for(let t=0;t=3){let e=t[t.length-1];for(let i=0;i=3&&(i.front=o.fromPointsAndPlane(t,c)),r.length>=3&&(i.back=o.fromPointsAndPlane(r,c))}else i.type=3;else i.type=2;else{const t=n.dot(e,c);i.type=t>=0?0:1}}return i}},{"../../../geometries/poly3":95,"../../../maths/constants":110,"../../../maths/plane":178,"../../../maths/vec3":237,"./splitLineSegmentByPlane":298}],300:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../utils/areAllShapesTheSameType"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("./unionGeom2"),l=e("./unionGeom3");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");if(!r(e))throw new Error("only unions of the same type are supported");const t=e[0];return n.isA(t)?a(e):o.isA(t)?l(e):t}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../utils/areAllShapesTheSameType":410,"../../utils/flatten":412,"./unionGeom2":301,"./unionGeom3":302}],301:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom3"),n=e("../../measurements/measureEpsilon"),o=e("./fromFakePolygons"),a=e("./to3DWalls"),l=e("./unionGeom3");t.exports=(...e)=>{const t=(e=s(e)).map((e=>a({z0:-1,z1:1},e))),i=l(t),h=n(i);return o(h,r.toPolygons(i))}},{"../../geometries/geom3":57,"../../measurements/measureEpsilon":278,"../../utils/flatten":412,"./fromFakePolygons":280,"./to3DWalls":293,"./unionGeom3":302}],302:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../modifiers/retessellate"),n=e("./unionGeom3Sub");t.exports=(...e)=>{let t;for(e=s(e),t=1;t{if(!r(e,t))return((e,t)=>{let i=s.toPolygons(e);return i=i.concat(s.toPolygons(t)),s.create(i)})(e,t);const i=new n(s.toPolygons(e)),o=new n(s.toPolygons(t));i.clipTo(o,!1),o.clipTo(i),o.invert(),o.clipTo(i),o.invert();const a=i.allPolygons().concat(o.allPolygons());return s.create(a)}},{"../../geometries/geom3":57,"./mayOverlap":286,"./trees":297}],304:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom2"),n=e("../../geometries/geom3"),o=e("../../geometries/path2"),a=e("./expandGeom2"),l=e("./expandGeom3"),h=e("./expandPath2");t.exports=(e,...t)=>{if(0===(t=s(t)).length)throw new Error("wrong number of arguments");const i=t.map((t=>o.isA(t)?h(e,t):r.isA(t)?a(e,t):n.isA(t)?l(e,t):t));return 1===i.length?i[0]:i}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../utils/flatten":412,"./expandGeom2":305,"./expandGeom3":306,"./expandPath2":307}],305:[function(e,t,i){const s=e("../../geometries/geom2"),r=e("./offsetFromPoints");t.exports=(e,t)=>{const{delta:i,corners:n,segments:o}=Object.assign({},{delta:1,corners:"edge",segments:16},e);if("edge"!==n&&"chamfer"!==n&&"round"!==n)throw new Error('corners must be "edge", "chamfer", or "round"');const a=s.toOutlines(t).map((t=>r(e={delta:i,corners:n,closed:!0,segments:o},t))).reduce(((e,t)=>e.concat(s.toSides(s.fromPoints(t)))),[]);return s.create(a)}},{"../../geometries/geom2":42,"./offsetFromPoints":312}],306:[function(e,t,i){const s=e("../../geometries/geom3"),r=e("../booleans/union"),n=e("./expandShell");t.exports=(e,t)=>{const{delta:i,corners:o,segments:a}=Object.assign({},{delta:1,corners:"round",segments:12},e);if("round"!==o)throw new Error('corners must be "round" for 3D geometries');if(0===s.toPolygons(t).length)throw new Error("the given geometry cannot be empty");const l=n(e={delta:i,corners:o,segments:a},t);return r(t,l)}},{"../../geometries/geom3":57,"../booleans/union":300,"./expandShell":308}],307:[function(e,t,i){const s=e("../../maths/utils/area"),r=e("../../maths/vec2"),n=e("../../geometries/geom2"),o=e("../../geometries/path2"),a=e("./offsetFromPoints");t.exports=(e,t)=>{e=Object.assign({},{delta:1,corners:"edge",segments:16},e);const{delta:i,corners:l,segments:h}=e;if(i<=0)throw new Error("the given delta must be positive for paths");if("edge"!==l&&"chamfer"!==l&&"round"!==l)throw new Error('corners must be "edge", "chamfer", or "round"');const c=t.isClosed,u=o.toPoints(t);if(0===u.length)throw new Error("the given geometry cannot be empty");const d={points:u,external:a({delta:i,corners:l,segments:h,closed:c},u),internal:a({delta:-i,corners:l,segments:h,closed:c},u)};return t.isClosed?(e=>{let{external:t,internal:i}=e;s(t)<0?t=t.reverse():i=i.reverse();const r=o.fromPoints({closed:!0},t),a=o.fromPoints({closed:!0},i),l=n.toSides(n.fromPoints(o.toPoints(r))),h=n.toSides(n.fromPoints(o.toPoints(a)));return l.push(...h),n.create(l)})(d):((e,t,i,s)=>{const{points:o,external:a,internal:l}=e,h=Math.floor(t/2),c=[],u=[];if("round"===i&&h>0){const e=Math.PI/h,t=o[o.length-1],i=r.angle(r.subtract(r.create(),a[a.length-1],t)),n=o[0],d=r.angle(r.subtract(r.create(),l[0],n));for(let o=1;o{const s=t.toString();if(e.has(s))e.get(s)[1].push(i);else{const r=[t,[i]];e.set(s,r)}},_=(e,t,i)=>{const s=t[0].toString(),r=t[1].toString(),n=s{e.findIndex((e=>e===t))<0&&e.push(t)};t.exports=(e,t)=>{const{delta:i,segments:g}=Object.assign({},{delta:1,segments:12},e);let v=l.create();const x=new Map,T=new Map,S=o.create(),E=o.create();return l.toPolygons(t).forEach(((e,t)=>{const s=o.scale(o.create(),h.plane(e),2*i),r=h.transform(n.fromTranslation(n.create(),o.scale(o.create(),s,-.5)),e),a=p(s,r);v=d(v,a);const l=e.vertices;for(let t=0;t{const t=e[0],n=e[1],c=t[0],u=t[1],p=o.subtract(o.create(),u,c);o.normalize(p,p);const f=n[0],_=o.cross(o.create(),f,p);let x=[];for(let e=0;e=0&&o.distance(a,b)=0){y.push(a),A.push(l);const e=[C,l,a,b],t=h.create(e);R.push(t)}b=a,C=l}}A.reverse(),R.push(h.create(y)),R.push(h.create(A));const I=l.create(R);v=d(v,I)})),x.forEach((e=>{const t=e[0],s=e[1],r=s[0];let n=null,a=0;for(let e=1;e.05&&l>a&&(a=l,n=t)}n||(n=o.orthogonal(S,r));const l=o.cross(S,r,n);o.normalize(l,l);const h=o.cross(E,l,r),u=c({center:[t[0],t[1],t[2]],radius:i,segments:g,axes:[r,l,h]});v=d(v,u)})),u(v)}},{"../../geometries/geom3":57,"../../geometries/poly3":95,"../../maths/constants":110,"../../maths/mat4":159,"../../maths/vec3":237,"../../primitives/sphere":400,"../../utils/fnNumberSort":413,"../booleans/unionGeom3Sub":303,"../modifiers/retessellate":370,"./extrudePolygon":309}],309:[function(e,t,i){const s=e("../../maths/mat4"),r=e("../../maths/vec3"),n=e("../../geometries/geom3"),o=e("../../geometries/poly3");t.exports=(e,t)=>{r.dot(o.plane(t),e)>0&&(t=o.invert(t));const i=[t],a=o.transform(s.fromTranslation(s.create(),e),t),l=t.vertices.length;for(let e=0;e{if(0===(t=s(t)).length)throw new Error("wrong number of arguments");const i=t.map((t=>n.isA(t)?a(e,t):r.isA(t)?o(e,t):t));return 1===i.length?i[0]:i}},{"../../geometries/geom2":42,"../../geometries/path2":78,"../../utils/flatten":412,"./offsetGeom2":313,"./offsetPath2":314}],312:[function(e,t,i){const{EPS:s,TAU:r}=e("../../maths/constants"),n=e("../../maths/utils/intersect"),o=e("../../maths/line2"),a=e("../../maths/vec2"),l=e("../../maths/utils/area");t.exports=(e,t)=>{let{delta:i,corners:h,closed:c,segments:u}=Object.assign({},{delta:1,corners:"edge",closed:!1,segments:16},e);if(Math.abs(i)0&&i>=0||d<0&&i<0;i=Math.abs(i);let f=null,_=[];const m=[],g=a.create(),v=t.length;for(let e=0;ee.set(t,i)));const t=o.create(),i=o.create();m.forEach((s=>{o.fromPoints(t,s.s0[0],s.s0[1]),o.fromPoints(i,s.s1[0],s.s1[1]);const r=o.intersectPointOfLines(t,i);if(Number.isFinite(r[0])&&Number.isFinite(r[1])){const t=s.s0[1],i=e.get(t);_[i]=r,_[(i+1)%_.length]=void 0}else{const t=s.s1[0],i=e.get(t);_[i]=void 0}})),_=_.filter((e=>void 0!==e))}if("round"===h){let e=Math.floor(u/4);const t=a.create();m.forEach((s=>{let n=a.angle(a.subtract(t,s.s1[0],s.c));if(n-=a.angle(a.subtract(t,s.s0[1],s.c)),p&&n<0&&(n+=Math.PI,n<0&&(n+=Math.PI)),!p&&n>0&&(n-=Math.PI,n>0&&(n-=Math.PI)),0!==n){e=Math.floor(u*(Math.abs(n)/r));const o=n/e,l=a.angle(a.subtract(t,s.s0[1],s.c)),h=[];for(let t=1;t0){const e=s.s0[1];let t=_.findIndex((t=>a.equals(e,t)));t=(t+1)%_.length,_.splice(t,0,...h)}}else{const e=s.s1[0],t=_.findIndex((t=>a.equals(e,t)));_.splice(t,1)}}))}return _}},{"../../maths/constants":110,"../../maths/line2":121,"../../maths/utils/area":183,"../../maths/utils/intersect":186,"../../maths/vec2":206}],313:[function(e,t,i){const s=e("../../geometries/geom2"),r=e("../../geometries/poly2"),n=e("./offsetFromPoints");t.exports=(e,t)=>{const{delta:i,corners:o,segments:a}=Object.assign({},{delta:1,corners:"edge",segments:0},e);if("edge"!==o&&"chamfer"!==o&&"round"!==o)throw new Error('corners must be "edge", "chamfer", or "round"');const l=s.toOutlines(t),h=l.map((t=>{const s=l.reduce(((e,i)=>e+r.arePointsInside(t,r.create(i))),0);return n(e={delta:s%2==0?i:-i,corners:o,closed:!0,segments:a},t)})).reduce(((e,t)=>e.concat(s.toSides(s.fromPoints(t)))),[]);return s.create(h)}},{"../../geometries/geom2":42,"../../geometries/poly2":89,"./offsetFromPoints":312}],314:[function(e,t,i){const s=e("../../geometries/path2"),r=e("./offsetFromPoints");t.exports=(e,t)=>{const i={delta:1,corners:"edge",closed:t.isClosed,segments:16},{delta:n,corners:o,closed:a,segments:l}=Object.assign({},i,e);if("edge"!==o&&"chamfer"!==o&&"round"!==o)throw new Error('corners must be "edge", "chamfer", or "round"');const h=r(e={delta:n,corners:o,closed:a,segments:l},s.toPoints(t));return s.fromPoints({closed:a},h)}},{"../../geometries/path2":78,"./offsetFromPoints":312}],315:[function(e,t,i){const{area:s}=e("../../../maths/utils"),{toOutlines:r}=e("../../../geometries/geom2"),{arePointsInside:n}=e("../../../geometries/poly2");t.exports=e=>{const t=r(e),i=[],o=[];t.forEach(((e,t)=>{const r=s(e);r<0?o.push(t):r>0&&i.push(t)}));const a=[],l=[];return i.forEach(((e,i)=>{const s=t[e];a[i]=[],o.forEach(((e,r)=>{const o=t[e];n([o[0]],{vertices:s})&&(a[i].push(e),l[r]||(l[r]=[]),l[r].push(i))}))})),o.forEach(((e,t)=>{if(l[t]&&l[t].length>1){const i=((e,t)=>{let i,s;return e.forEach(((e,r)=>{const n=t(e);(void 0===s||na[e].length));l[t].forEach(((t,s)=>{s!==i&&(a[t]=a[t].filter((t=>t!==e)))}))}})),a.map(((e,s)=>({solid:t[i[s]],holes:e.map((e=>t[e]))})))}},{"../../../geometries/geom2":42,"../../../geometries/poly2":89,"../../../maths/utils":184}],316:[function(e,t,i){const{filterPoints:s,linkedPolygon:r,locallyInside:n,splitPolygon:o}=e("./linkedPolygon"),{area:a,pointInTriangle:l}=e("./triangle"),h=(e,t)=>{const i=c(e,t);if(!i)return t;const r=o(i,e),n=s(i,i.next);return s(r,r.next),t===i?n:t},c=(e,t)=>{let i=t;const s=e.x,r=e.y;let o,a=-1/0;do{if(r<=i.y&&r>=i.next.y&&i.next.y!==i.y){const e=i.x+(r-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(e<=s&&e>a){if(a=e,e===s){if(r===i.y)return i;if(r===i.next.y)return i.next}o=i.x=i.x&&i.x>=c&&s!==i.x&&l(ro.x||i.x===o.x&&u(o,i)))&&(o=i,p=t)}i=i.next}while(i!==h);return o},u=(e,t)=>a(e.prev,e,t.prev)<0&&a(t.next,e,e.next)<0,d=e=>{let t=e,i=e;do{(t.x{const o=[];for(let i=0,s=t.length;ie.x-t.x));for(let e=0;e{if(!e)return;!h&&l&&g(e,s,n,l);let c,u,d=e;for(;e.prev!==e.next;)if(c=e.prev,u=e.next,l?_(e,s,n,l):f(e))t.push(c.i/i),t.push(e.i/i),t.push(u.i/i),r(e),e=u.next,d=u.next;else if((e=u)===d){h?1===h?(e=o(a(e),t,i),p(e,t,i,s,n,l,2)):2===h&&m(e,t,i,s,n,l):p(a(e),t,i,s,n,l,1);break}},f=e=>{const t=e.prev,i=e,s=e.next;if(u(t,i,s)>=0)return!1;let r=e.next.next;for(;r!==e.prev;){if(d(t.x,t.y,i.x,i.y,s.x,s.y,r.x,r.y)&&u(r.prev,r,r.next)>=0)return!1;r=r.next}return!0},_=(e,t,i,s)=>{const r=e.prev,n=e,o=e.next;if(u(r,n,o)>=0)return!1;const a=r.xn.x?r.x>o.x?r.x:o.x:n.x>o.x?n.x:o.x,c=r.y>n.y?r.y>o.y?r.y:o.y:n.y>o.y?n.y:o.y,p=v(a,l,t,i,s),f=v(h,c,t,i,s);let _=e.prevZ,m=e.nextZ;for(;_&&_.z>=p&&m&&m.z<=f;){if(_!==e.prev&&_!==e.next&&d(r.x,r.y,n.x,n.y,o.x,o.y,_.x,_.y)&&u(_.prev,_,_.next)>=0)return!1;if(_=_.prevZ,m!==e.prev&&m!==e.next&&d(r.x,r.y,n.x,n.y,o.x,o.y,m.x,m.y)&&u(m.prev,m,m.next)>=0)return!1;m=m.nextZ}for(;_&&_.z>=p;){if(_!==e.prev&&_!==e.next&&d(r.x,r.y,n.x,n.y,o.x,o.y,_.x,_.y)&&u(_.prev,_,_.next)>=0)return!1;_=_.prevZ}for(;m&&m.z<=f;){if(m!==e.prev&&m!==e.next&&d(r.x,r.y,n.x,n.y,o.x,o.y,m.x,m.y)&&u(m.prev,m,m.next)>=0)return!1;m=m.nextZ}return!0},m=(e,t,i,s,r,n)=>{let o=e;do{let e=o.next.next;for(;e!==o.prev;){if(o.i!==e.i&&l(o,e)){let l=c(o,e);return o=a(o,o.next),l=a(l,l.next),p(o,t,i,s,r,n),void p(l,t,i,s,r,n)}e=e.next}o=o.next}while(o!==e)},g=(e,t,i,s)=>{let r=e;do{null===r.z&&(r.z=v(r.x,r.y,t,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,n(r,(e=>e.z))},v=(e,t,i,s,r)=>(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-i)*r)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-s)*r)|t<<8))|t<<4))|t<<2))|t<<1))<<1;t.exports=(e,t,i=2)=>{const r=t&&t.length,n=r?t[0]*i:e.length;let o=h(e,0,n,i,!0);const a=[];if(!o||o.next===o.prev)return a;let l,c,u,d,f;if(r&&(o=s(e,t,o,i)),e.length>80*i){l=u=e[0],c=d=e[1];for(let t=i;tu&&(u=i),s>d&&(d=s)}f=Math.max(u-l,d-c),f=0!==f?1/f:0}return p(o,a,i,l,c,f),a}},{"./eliminateHoles":316,"./linkedList":318,"./linkedPolygon":320,"./triangle":322}],318:[function(e,t,i){const s=e("./linkedListSort");class r{constructor(e,t,i){this.i=e,this.x=t,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}t.exports={Node:r,insertNode:(e,t,i,s)=>{const n=new r(e,t,i);return s?(n.next=s.next,n.prev=s,s.next.prev=n,s.next=n):(n.prev=n,n.next=n),n},removeNode:e=>{e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)},sortLinked:s}},{"./linkedListSort":319}],319:[function(e,t,i){t.exports=(e,t)=>{let i,s,r,n,o,a=1;do{s=e,e=null;let l=null;for(o=0;s;){o++,r=s;let h=0;for(i=0;i0||c>0&&r;)0!==h&&(0===c||!r||t(s)<=t(r))?(n=s,s=s.nextZ,h--):(n=r,r=r.nextZ,c--),l?l.nextZ=n:e=n,n.prevZ=l,l=n;s=r}l.nextZ=null,a*=2}while(o>1);return e}},{}],320:[function(e,t,i){const{Node:s,insertNode:r,removeNode:n}=e("./linkedList"),{area:o}=e("./triangle"),a=(e,t)=>{if(!e)return e;t||(t=e);let i,s=e;do{if(i=!1,s.steiner||!u(s,s.next)&&0!==o(s.prev,s,s.next))s=s.next;else{if(n(s),s=t=s.prev,s===s.next)break;i=!0}}while(i||s!==t);return t},l=(e,t)=>o(e.prev,e,e.next)<0?o(e,t,e.next)>=0&&o(e,e.prev,t)>=0:o(e,t,e.prev)<0||o(e,e.next,t)<0,h=(e,t,i,s)=>{const r=Math.sign(o(e,t,i)),n=Math.sign(o(e,t,s)),a=Math.sign(o(i,s,e)),l=Math.sign(o(i,s,t));return r!==n&&a!==l||!(0!==r||!c(e,i,t))||!(0!==n||!c(e,s,t))||!(0!==a||!c(i,e,s))||!(0!==l||!c(i,t,s))},c=(e,t,i)=>t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y),u=(e,t)=>e.x===t.x&&e.y===t.y;t.exports={cureLocalIntersections:(e,t,i)=>{let s=e;do{const r=s.prev,o=s.next.next;!u(r,o)&&h(r,s,s.next,o)&&l(r,o)&&l(o,r)&&(t.push(r.i/i),t.push(s.i/i),t.push(o.i/i),n(s),n(s.next),s=e=o),s=s.next}while(s!==e);return a(s)},filterPoints:a,isValidDiagonal:(e,t)=>e.next.i!==t.i&&e.prev.i!==t.i&&!((e,t)=>{let i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&h(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1})(e,t)&&(l(e,t)&&l(t,e)&&((e,t)=>{let i=e,s=!1;const r=(e.x+t.x)/2,n=(e.y+t.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&r<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==e);return s})(e,t)&&(o(e.prev,e,t.prev)||o(e,t.prev,t))||u(e,t)&&o(e.prev,e,e.next)>0&&o(t.prev,t,t.next)>0),linkedPolygon:(e,t,i,s,o)=>{let a;if(o===((e,t,i,s)=>{let r=0;for(let n=t,o=i-s;n0)for(let n=t;n=t;n-=s)a=r(n,e[n],e[n+1],a);return a&&u(a,a.next)&&(n(a),a=a.next),a},locallyInside:l,splitPolygon:(e,t)=>{const i=new s(e.i,e.x,e.y),r=new s(t.i,t.x,t.y),n=e.next,o=t.prev;return e.next=t,t.prev=e,i.next=n,n.prev=i,r.next=i,i.prev=r,o.next=r,r.prev=o,r}}},{"./linkedList":318,"./triangle":322}],321:[function(e,t,i){const s=e("../../../geometries/geom2"),r=e("../../../maths/plane"),n=e("../../../maths/vec2"),o=e("../../../maths/vec3"),a=e("../slice/calculatePlane"),l=e("./assignHoles");t.exports=class{constructor(e){this.plane=a(e);const t=o.orthogonal(o.create(),this.plane),i=o.cross(o.create(),this.plane,t);this.v=o.normalize(i,i),this.u=o.cross(o.create(),this.v,this.plane),this.basisMap=new Map;const r=e.edges.map((e=>e.map((e=>this.to2D(e))))),n=s.create(r);this.roots=l(n)}to2D(e){const t=n.fromValues(o.dot(e,this.u),o.dot(e,this.v));return this.basisMap.set(t,e),t}to3D(e){const t=this.basisMap.get(e);if(t)return t;{console.log("Warning: point not in original slice");const t=o.scale(o.create(),this.u,e[0]),i=o.scale(o.create(),this.v,e[1]),s=o.scale(o.create(),r,r[3]),n=o.add(t,t,s);return o.add(i,i,n)}}}},{"../../../geometries/geom2":42,"../../../maths/plane":178,"../../../maths/vec2":206,"../../../maths/vec3":237,"../slice/calculatePlane":335,"./assignHoles":315}],322:[function(e,t,i){t.exports={area:(e,t,i)=>(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y),pointInTriangle:(e,t,i,s,r,n,o,a)=>(r-o)*(t-a)-(e-o)*(n-a)>=0&&(e-o)*(s-a)-(i-o)*(t-a)>=0&&(i-o)*(n-a)-(r-o)*(s-a)>=0}},{}],323:[function(e,t,i){const s=e("../../maths/mat4"),r=e("../../geometries/geom2"),n=e("../../geometries/geom3"),o=e("../../geometries/poly3"),a=e("./slice"),l=e("./slice/repair"),h=e("./extrudeWalls"),c=(e,t,i)=>{let n=null;return r.isA(i)&&(n=a.fromSides(r.toSides(i))),o.isA(i)&&(n=a.fromPoints(o.toPoints(i))),0===e||1===e?a.transform(s.fromTranslation(s.create(),[0,0,e]),n):null};t.exports=(e,t)=>{const i={numberOfSlices:2,capStart:!0,capEnd:!0,close:!1,repair:!0,callback:c},{numberOfSlices:s,capStart:r,capEnd:u,close:d,repair:p,callback:f}=Object.assign({},i,e);if(s<2)throw new Error("numberOfSlices must be 2 or more");p&&(t=l(t));const _=s-1;let m=null,g=null,v=null,x=[];for(let e=0;e{const i={angle:s,startAngle:0,pitch:10,endOffset:0,segmentsPerRotation:32},{angle:l,endOffset:h,segmentsPerRotation:c,startAngle:u}=Object.assign({},i,e);let d;if(d=!e.pitch&&e.height?e.height/(l/s):e.pitch?e.pitch:i.pitch,c<3)throw new Error("The number of segments per rotation needs to be at least 3.");const p=a.toSides(t);if(0===p.length)throw new Error("the given geometry cannot be empty");const f=p.filter((e=>e[0][0]>=0));let _=r.fromSides(p);0===f.length&&(_=r.reverse(_));const m=Math.round(c/s*Math.abs(l)),g=m>=2?m:2,v=n.create();let x;return o({numberOfSlices:g+1,callback:(e,t,i)=>{const o=u+l/g*t,a=h/g*t,c=(o-u)/s*d;return n.multiply(v,n.fromTranslation(n.create(),[a,0,c*Math.sign(l)]),n.fromXRotation(n.create(),-s/4*Math.sign(l))),x=n.create(),n.multiply(x,n.fromZRotation(n.create(),o),v),r.transform(x,i)}},_)}},{"../../geometries/geom2":42,"../../maths/constants":110,"../../maths/mat4":159,"./extrudeFromSlices":323,"./slice":341}],325:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom2"),n=e("../../geometries/path2"),o=e("./extrudeLinearGeom2"),a=e("./extrudeLinearPath2");t.exports=(e,...t)=>{const{height:i,twistAngle:l,twistSteps:h,repair:c}=Object.assign({},{height:1,twistAngle:0,twistSteps:1,repair:!0},e);if(0===(t=s(t)).length)throw new Error("wrong number of arguments");e={offset:[0,0,i],twistAngle:l,twistSteps:h,repair:c};const u=t.map((t=>n.isA(t)?a(e,t):r.isA(t)?o(e,t):t));return 1===u.length?u[0]:u}},{"../../geometries/geom2":42,"../../geometries/path2":78,"../../utils/flatten":412,"./extrudeLinearGeom2":326,"./extrudeLinearPath2":327}],326:[function(e,t,i){const s=e("../../maths/mat4"),r=e("../../maths/vec3"),n=e("../../geometries/geom2"),o=e("./slice"),a=e("./extrudeFromSlices");t.exports=(e,t)=>{let{offset:i,twistAngle:l,twistSteps:h,repair:c}=Object.assign({},{offset:[0,0,1],twistAngle:0,twistSteps:12,repair:!0},e);if(h<1)throw new Error("twistSteps must be 1 or more");0===l&&(h=1);const u=r.clone(i),d=n.toSides(t);if(0===d.length)throw new Error("the given geometry cannot be empty");const p=o.fromSides(d);u[2]<0&&o.reverse(p,p);const f=s.create();return a(e={numberOfSlices:h+1,capStart:!0,capEnd:!0,repair:c,callback:(e,t,i)=>{const n=t/h*l,a=r.scale(r.create(),u,t/h);return s.multiply(f,s.fromZRotation(f,n),s.fromTranslation(s.create(),a)),o.transform(f,i)}},p)}},{"../../geometries/geom2":42,"../../maths/mat4":159,"../../maths/vec3":237,"./extrudeFromSlices":323,"./slice":341}],327:[function(e,t,i){const s=e("../../geometries/geom2"),r=e("../../geometries/path2"),n=e("./extrudeLinearGeom2");t.exports=(e,t)=>{if(!t.isClosed)throw new Error("extruded path must be closed");const i=r.toPoints(t),o=s.fromPoints(i);return n(e,o)}},{"../../geometries/geom2":42,"../../geometries/path2":78,"./extrudeLinearGeom2":326}],328:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom2"),n=e("../../geometries/path2"),o=e("./extrudeRectangularPath2"),a=e("./extrudeRectangularGeom2");t.exports=(e,...t)=>{const{size:i,height:l}=Object.assign({},{size:1,height:1},e);if(0===(t=s(t)).length)throw new Error("wrong number of arguments");if(i<=0)throw new Error("size must be positive");if(l<=0)throw new Error("height must be positive");const h=t.map((t=>n.isA(t)?o(e,t):r.isA(t)?a(e,t):t));return 1===h.length?h[0]:h}},{"../../geometries/geom2":42,"../../geometries/path2":78,"../../utils/flatten":412,"./extrudeRectangularGeom2":329,"./extrudeRectangularPath2":330}],329:[function(e,t,i){const{area:s}=e("../../maths/utils"),r=e("../../geometries/geom2"),n=e("../../geometries/path2"),o=e("../expansions/expand"),a=e("./extrudeLinearGeom2");t.exports=(e,t)=>{const{size:i,height:l}=Object.assign({},{size:1,height:1},e);e.delta=i,e.offset=[0,0,l];const h=r.toOutlines(t);if(0===h.length)throw new Error("the given geometry cannot be empty");const c=h.map((t=>(s(t)<0&&t.reverse(),o(e,n.fromPoints({closed:!0},t))))).reduce(((e,t)=>e.concat(r.toSides(t))),[]),u=r.create(c);return a(e,u)}},{"../../geometries/geom2":42,"../../geometries/path2":78,"../../maths/utils":184,"../expansions/expand":304,"./extrudeLinearGeom2":326}],330:[function(e,t,i){const s=e("../../geometries/path2"),r=e("../expansions/expand"),n=e("./extrudeLinearGeom2");t.exports=(e,t)=>{const{size:i,height:o}=Object.assign({},{size:1,height:1},e);if(e.delta=i,e.offset=[0,0,o],0===s.toPoints(t).length)throw new Error("the given geometry cannot be empty");const a=r(e,t);return n(e,a)}},{"../../geometries/path2":78,"../expansions/expand":304,"./extrudeLinearGeom2":326}],331:[function(e,t,i){const{TAU:s}=e("../../maths/constants"),r=e("../../maths/mat4"),{mirrorX:n}=e("../transforms/mirror"),o=e("../../geometries/geom2"),a=e("./slice"),l=e("./extrudeFromSlices");t.exports=(e,t)=>{const i={segments:12,startAngle:0,angle:s,overflow:"cap"};let{segments:h,startAngle:c,angle:u,overflow:d}=Object.assign({},i,e);if(h<3)throw new Error("segments must be greater then 3");c=Math.abs(c)>s?c%s:c,u=Math.abs(u)>s?u%s:u;let p=c+u;if(p=Math.abs(p)>s?p%s:p,ph*e&&h++}let _=o.toSides(t);if(0===_.length)throw new Error("the given geometry cannot be empty");const m=_.filter((e=>e[0][0]<0)),g=_.filter((e=>e[0][0]>=0));m.length>0&&g.length>0&&"cap"===d&&(m.length>g.length?(_=_.map((e=>{let t=e[0],i=e[1];return t=[Math.min(t[0],0),t[1]],i=[Math.min(i[0],0),i[1]],[t,i]})),t=o.reverse(o.create(_)),t=n(t)):g.length>=m.length&&(_=_.map((e=>{let t=e[0],i=e[1];return t=[Math.max(t[0],0),t[1]],i=[Math.max(i[0],0),i[1]],[t,i]})),t=o.create(_)));const v=f/h,x=Math.abs(f){let n=v*t+c;return f===s&&t===h&&(n=c),r.multiply(S,r.fromZRotation(S,n),r.fromXRotation(r.create(),s/4)),a.transform(S,i)}},T)}},{"../../geometries/geom2":42,"../../maths/constants":110,"../../maths/mat4":159,"../transforms/mirror":377,"./extrudeFromSlices":323,"./slice":341}],332:[function(e,t,i){const{EPS:s}=e("../../maths/constants"),r=e("../../maths/vec3"),n=e("../../geometries/poly3"),o=e("./slice"),a=(e,t)=>e===t?e:e{const i=e/t.length;if(1===i)return t;const s=r.fromValues(i,i,i),n=[];return t.forEach((e=>{const t=r.subtract(r.create(),e[1],e[0]);r.divide(t,t,s);let o=e[0];for(let e=1;e<=i;++e){const e=r.add(r.create(),o,t);n.push([o,e]),o=e}})),n},h=s*s/2*Math.sin(Math.PI/3);t.exports=(e,t)=>{let i=o.toEdges(e),s=o.toEdges(t);if(i.length!==s.length){const e=(r=i.length)*(c=s.length)/a(r,c);e!==i.length&&(i=l(e,i)),e!==s.length&&(s=l(e,s))}var r,c;const u=[];return i.forEach(((e,t)=>{const i=s[t],r=n.create([e[0],e[1],i[1]]),o=n.measureArea(r);Number.isFinite(o)&&o>h&&u.push(r);const a=n.create([e[0],i[1],i[0]]),l=n.measureArea(a);Number.isFinite(l)&&l>h&&u.push(a)})),u}},{"../../geometries/poly3":95,"../../maths/constants":110,"../../maths/vec3":237,"./slice":341}],333:[function(e,t,i){t.exports={extrudeFromSlices:e("./extrudeFromSlices"),extrudeLinear:e("./extrudeLinear"),extrudeRectangular:e("./extrudeRectangular"),extrudeRotate:e("./extrudeRotate"),extrudeHelical:e("./extrudeHelical"),project:e("./project"),slice:e("./slice")}},{"./extrudeFromSlices":323,"./extrudeHelical":324,"./extrudeLinear":325,"./extrudeRectangular":328,"./extrudeRotate":331,"./project":334,"./slice":341}],334:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../maths/utils/aboutEqualNormals"),n=e("../../maths/plane"),o=e("../../maths/mat4"),a=e("../../geometries/geom2"),l=e("../../geometries/geom3"),h=e("../../geometries/poly3"),c=e("../../measurements/measureEpsilon"),u=e("../booleans/unionGeom2");t.exports=(e,...t)=>{const{axis:i,origin:d}=Object.assign({},{axis:[0,0,1],origin:[0,0,0]},e);if(0===(t=s(t)).length)throw new Error("wrong number of arguments");e={axis:i,origin:d};const p=t.map((t=>l.isA(t)?((e,t)=>{const i=n.fromNormalAndPoint(n.create(),e.axis,e.origin);if(Number.isNaN(i[0])||Number.isNaN(i[1])||Number.isNaN(i[2])||Number.isNaN(i[3]))throw new Error("project: invalid axis or origin");const s=c(t),d=s*s*Math.sqrt(3)/4;if(0===s)return a.create();const p=l.toPolygons(t);let f=[];for(let e=0;en.projectionOfPoint(i,e))),s=h.create(t),o=h.plane(s);r(i,o)&&(h.measureArea(s)h.transform(e,t)))}f=f.sort(((e,t)=>h.measureArea(t)-h.measureArea(e)));const _=f.map((e=>a.fromPoints(e.vertices)));return u(_)})(e,t):t));return 1===p.length?p[0]:p}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/poly3":95,"../../maths/mat4":159,"../../maths/plane":178,"../../maths/utils/aboutEqualNormals":182,"../../measurements/measureEpsilon":278,"../../utils/flatten":412,"../booleans/unionGeom2":301}],335:[function(e,t,i){const s=e("../../../maths/plane"),r=e("../../../maths/vec3");t.exports=e=>{const t=e.edges;if(t.length<3)throw new Error("slices must have 3 or more edges to calculate a plane");const i=t.reduce(((e,t)=>r.add(r.create(),e,t[0])),r.create());let n;r.scale(i,i,1/t.length);let o=0;t.forEach((e=>{if(!r.equals(e[0],e[1])){const t=r.squaredDistance(i,e[0]);t>o&&(n=e,o=t)}}));const a=t.find((e=>r.equals(e[1],n[0])));return s.fromPoints(s.create(),a[0],n[0],n[1])}},{"../../../maths/plane":178,"../../../maths/vec3":237}],336:[function(e,t,i){const s=e("./create"),r=e("../../../maths/vec3");t.exports=(...e)=>{let t,i;return 1===e.length?(t=s(),i=e[0]):(t=e[0],i=e[1]),t.edges=i.edges.map((e=>[r.clone(e[0]),r.clone(e[1])])),t}},{"../../../maths/vec3":237,"./create":337}],337:[function(e,t,i){t.exports=e=>(e||(e=[]),{edges:e})},{}],338:[function(e,t,i){const s=e("../../../maths/vec3");t.exports=(e,t)=>{const i=e.edges,r=t.edges;return i.length===r.length&&i.reduce(((e,t,i)=>{const n=r[i],o=s.squaredDistance(t[0],n[0]);return e&&o{if(!Array.isArray(e))throw new Error("the given points must be an array");if(e.length<3)throw new Error("the given points must contain THREE or more points");const t=[];let i=e[e.length-1];return e.forEach((e=>{2===e.length&&t.push([s.fromVec2(s.create(),i),s.fromVec2(s.create(),e)]),3===e.length&&t.push([i,e]),i=e})),r(t)}},{"../../../maths/vec3":237,"./create":337}],340:[function(e,t,i){const s=e("../../../maths/vec3"),r=e("./create");t.exports=e=>{if(!Array.isArray(e))throw new Error("the given sides must be an array");const t=[];return e.forEach((e=>{t.push([s.fromVec2(s.create(),e[0]),s.fromVec2(s.create(),e[1])])})),r(t)}},{"../../../maths/vec3":237,"./create":337}],341:[function(e,t,i){t.exports={calculatePlane:e("./calculatePlane"),clone:e("./clone"),create:e("./create"),equals:e("./equals"),fromPoints:e("./fromPoints"),fromSides:e("./fromSides"),isA:e("./isA"),reverse:e("./reverse"),toEdges:e("./toEdges"),toPolygons:e("./toPolygons"),toString:e("./toString"),transform:e("./transform")}},{"./calculatePlane":335,"./clone":336,"./create":337,"./equals":338,"./fromPoints":339,"./fromSides":340,"./isA":342,"./reverse":344,"./toEdges":345,"./toPolygons":346,"./toString":347,"./transform":348}],342:[function(e,t,i){t.exports=e=>!!(e&&"object"==typeof e&&"edges"in e&&Array.isArray(e.edges))},{}],343:[function(e,t,i){const s=e("../../../maths/vec3"),r=e("./create");t.exports=e=>{if(!e.edges)return e;let t=e.edges;const i=new Map,n=new Map;t=t.filter((e=>!s.equals(e[0],e[1]))),t.forEach((e=>{const t=e[0].toString(),s=e[1].toString();i.set(t,e[0]),i.set(s,e[1]),n.set(t,(n.get(t)||0)+1),n.set(s,(n.get(s)||0)-1)}));const o=[],a=[];return n.forEach(((e,t)=>{e<0&&o.push(t),e>0&&a.push(t)})),o.forEach((e=>{const r=i.get(e);let n,o=1/0;a.forEach((e=>{const t=i.get(e),a=s.distance(r,t);at[0].toString()===e?[n,t[1]]:t[1].toString()===e?[t[0],n]:t))})),r(t)}},{"../../../maths/vec3":237,"./create":337}],344:[function(e,t,i){const s=e("./create");t.exports=(...e)=>{let t,i;return 1===e.length?(t=s(),i=e[0]):(t=e[0],i=e[1]),t.edges=i.edges.map((e=>[e[1],e[0]])),t}},{"./create":337}],345:[function(e,t,i){t.exports=e=>e.edges},{}],346:[function(e,t,i){const s=e("../../../geometries/poly3"),r=e("../earcut"),n=e("../earcut/polygonHierarchy");t.exports=e=>{const t=new n(e),i=[];return t.roots.forEach((({solid:e,holes:n})=>{let o=e.length;const a=[];n.forEach(((e,t)=>{a.push(o),o+=e.length}));const l=[e,...n].flat(),h=l.flat(),c=e=>t.to3D(l[e]),u=r(h,a);for(let e=0;e{return`[${t=e.edges,t.reduce(((e,t)=>e+`[${s.toString(t[0])}, ${s.toString(t[1])}], `),"")}]`;var t}},{"../../../maths/vec3":237}],348:[function(e,t,i){const s=e("../../../maths/vec3"),r=e("./create");t.exports=(e,t)=>{const i=t.edges.map((t=>[s.transform(s.create(),t[0],e),s.transform(s.create(),t[1],e)]));return r(i)}},{"../../../maths/vec3":237,"./create":337}],349:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../utils/areAllShapesTheSameType"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("../../geometries/path2"),l=e("./hullPath2"),h=e("./hullGeom2"),c=e("./hullGeom3");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");if(!r(e))throw new Error("only hulls of the same type are supported");const t=e[0];return a.isA(t)?l(e):n.isA(t)?h(e):o.isA(t)?c(e):t}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../utils/areAllShapesTheSameType":410,"../../utils/flatten":412,"./hullGeom2":351,"./hullGeom3":352,"./hullPath2":353}],350:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../booleans/union"),n=e("./hull");t.exports=(...e)=>{if((e=s(e)).length<2)throw new Error("wrong number of arguments");const t=[];for(let i=1;i{e=s(e);const t=o(e),i=n(t);return i.length<3?r.create():r.fromPoints(i)}},{"../../geometries/geom2":42,"../../utils/flatten":412,"./hullPoints2":354,"./toUniquePoints":364}],352:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom3"),n=e("../../geometries/poly3"),o=e("./quickhull"),a=e("./toUniquePoints");t.exports=(...e)=>{if(1===(e=s(e)).length)return e[0];const t=a(e),i=o(t,{skipTriangulation:!0}).map((e=>{const i=e.map((e=>t[e]));return n.create(i)}));return r.create(i)}},{"../../geometries/geom3":57,"../../geometries/poly3":95,"../../utils/flatten":412,"./quickhull":362,"./toUniquePoints":364}],353:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/path2"),n=e("./hullPoints2"),o=e("./toUniquePoints");t.exports=(...e)=>{e=s(e);const t=o(e),i=n(t);return r.fromPoints({closed:!0},i)}},{"../../geometries/path2":78,"../../utils/flatten":412,"./hullPoints2":354,"./toUniquePoints":364}],354:[function(e,t,i){const s=e("../../maths/vec2");t.exports=e=>{let t=s.fromValues(1/0,1/0);e.forEach((e=>{(e[1]{const r=(o=e[1]-t[1],a=e[0]-t[0],0===o&&0===a?-1/0:-a/o),n=s.squaredDistance(e,t);var o,a;i.push({point:e,angle:r,distSq:n})})),i.sort(((e,t)=>e.angle!==t.angle?e.angle-t.angle:e.distSq-t.distSq));const r=[];return i.forEach((e=>{let t=r.length;for(;t>1&&(i=r[t-2],s=r[t-1],n=e.point,(s[0]-i[0])*(n[1]-i[1])-(s[1]-i[1])*(n[0]-i[0])<=Number.EPSILON);)r.pop(),t=r.length;var i,s,n;r.push(e.point)})),r}},{"../../maths/vec2":206}],355:[function(e,t,i){t.exports={hull:e("./hull"),hullChain:e("./hullChain")}},{"./hull":349,"./hullChain":350}],356:[function(e,t,i){const s=e("../../../maths/vec3/add"),r=e("../../../maths/vec3/copy"),n=e("../../../maths/vec3/cross"),o=e("../../../maths/vec3/dot"),a=e("../../../maths/vec3/length"),l=e("../../../maths/vec3/normalize"),h=e("../../../maths/vec3/scale"),c=e("../../../maths/vec3/subtract"),u=e("./HalfEdge");class d{constructor(){this.normal=[],this.centroid=[],this.offset=0,this.outside=null,this.mark=0,this.edge=null,this.nVertices=0}getEdge(e){if("number"!=typeof e)throw Error("requires a number");let t=this.edge;for(;e>0;)t=t.next,e-=1;for(;e<0;)t=t.prev,e+=1;return t}computeNormal(){const e=this.edge,t=e.next;let i=t.next;const o=c([],t.head().point,e.head().point),l=[],u=[];for(this.nVertices=2,this.normal=[0,0,0];i!==e;)r(u,o),c(o,i.head().point,e.head().point),s(this.normal,this.normal,n(l,u,o)),i=i.next,this.nVertices+=1;this.area=a(this.normal),this.normal=h(this.normal,this.normal,1/this.area)}computeNormalMinArea(e){if(this.computeNormal(),this.areat&&(e=i,t=s),i=i.next}while(i!==this.edge);const r=e.tail().point,n=e.head().point,a=c([],n,r),u=Math.sqrt(t);h(a,a,1/u);const d=o(this.normal,a);h(a,a,-d),s(this.normal,this.normal,a),l(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let e=this.edge;do{s(this.centroid,this.centroid,e.head().point),e=e.next}while(e!==this.edge);h(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(e){void 0!==e?this.computeNormalMinArea(e):this.computeNormal(),this.computeCentroid(),this.offset=o(this.normal,this.centroid)}distanceToPlane(e){return o(this.normal,e)-this.offset}connectHalfEdges(e,t){let i;if(e.opposite.face===t.opposite.face){const s=t.opposite.face;let r;e===this.edge&&(this.edge=t),3===s.nVertices?(r=t.opposite.prev.opposite,s.mark=2,i=s):(r=t.opposite.next,s.edge===r.prev&&(s.edge=r),r.prev=r.prev.prev,r.prev.next=r),t.prev=e.prev,t.prev.next=t,t.setOpposite(r),s.computeNormalAndCentroid()}else e.next=t,t.prev=e;return i}mergeAdjacentFaces(e,t){const i=e.opposite,s=i.face;t.push(s),s.mark=2;let r,n,o=e.prev,a=e.next,l=i.prev,h=i.next;for(;o.opposite.face===s;)o=o.prev,h=h.next;for(;a.opposite.face===s;)a=a.next,l=l.prev;for(r=h;r!==l.next;r=r.next)r.face=this;return this.edge=a,n=this.connectHalfEdges(l,a),n&&t.push(n),n=this.connectHalfEdges(o,h),n&&t.push(n),this.computeNormalAndCentroid(),t}collectIndices(){const e=[];let t=this.edge;do{e.push(t.head().index),t=t.next}while(t!==this.edge);return e}static createTriangle(e,t,i,s=0){const r=new d,n=new u(e,r),o=new u(t,r),a=new u(i,r);return n.next=a.prev=o,o.next=n.prev=a,a.next=o.prev=n,r.edge=n,r.computeNormalAndCentroid(s),r}}t.exports={VISIBLE:0,NON_CONVEX:1,DELETED:2,Face:d}},{"../../../maths/vec3/add":224,"../../../maths/vec3/copy":227,"../../../maths/vec3/cross":229,"../../../maths/vec3/dot":232,"../../../maths/vec3/length":238,"../../../maths/vec3/normalize":244,"../../../maths/vec3/scale":249,"../../../maths/vec3/subtract":253,"./HalfEdge":357}],357:[function(e,t,i){const s=e("../../../maths/vec3/distance"),r=e("../../../maths/vec3/squaredDistance");t.exports=class{constructor(e,t){this.vertex=e,this.face=t,this.next=null,this.prev=null,this.opposite=null}head(){return this.vertex}tail(){return this.prev?this.prev.vertex:null}length(){return this.tail()?s(this.tail().point,this.head().point):-1}lengthSquared(){return this.tail()?r(this.tail().point,this.head().point):-1}setOpposite(e){this.opposite=e,e.opposite=this}}},{"../../../maths/vec3/distance":230,"../../../maths/vec3/squaredDistance":251}],358:[function(e,t,i){const s=e("../../../maths/vec3/dot"),r=e("./point-line-distance"),n=e("./get-plane-normal"),o=e("./VertexList"),a=e("./Vertex"),{Face:l,VISIBLE:h,NON_CONVEX:c,DELETED:u}=e("./Face");t.exports=class{constructor(e){if(!Array.isArray(e))throw TypeError("input is not a valid array");if(e.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=e.length,this.faces=[],this.newFaces=[],this.claimed=new o,this.unclaimed=new o,this.vertices=[];for(let t=0;tthis.tolerance?this.addVertexToFace(s,t):this.unclaimed.add(s)}else this.unclaimed.addAll(i)}resolveUnclaimedPoints(e){let t=this.unclaimed.first();for(let i=t;i;i=t){t=i.next;let s,r=this.tolerance;for(let t=0;tr&&(r=e,s=n),r>1e3*this.tolerance)break}}s&&this.addVertexToFace(i,s)}}computeExtremes(){const e=[],t=[],i=[],s=[];let r,n;for(r=0;r<3;r+=1)i[r]=s[r]=this.vertices[0];for(r=0;r<3;r+=1)e[r]=t[r]=this.vertices[0].point[r];for(r=1;rt[n]&&(t[n]=a[n],s[n]=o)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(e[0]),Math.abs(t[0]))+Math.max(Math.abs(e[1]),Math.abs(t[1]))+Math.max(Math.abs(e[2]),Math.abs(t[2]))),[i,s]}createInitialSimplex(){const e=this.vertices,[t,i]=this.computeExtremes();let o,a,h,c,u=0,d=0;for(h=0;h<3;h+=1){const e=i[h].point[h]-t[h].point[h];e>u&&(u=e,d=h)}const p=t[d],f=i[d];for(u=0,h=0;hu&&(u=t,o=e)}}const _=n([],p.point,f.point,o.point),m=s(p.point,_);for(u=-1,h=0;hu&&(u=t,a=e)}}const g=[];if(s(a.point,_)-m<0)for(g.push(l.createTriangle(p,f,o),l.createTriangle(a,f,p),l.createTriangle(a,o,f),l.createTriangle(a,p,o)),h=0;h<3;h+=1){const e=(h+1)%3;g[h+1].getEdge(2).setOpposite(g[0].getEdge(e)),g[h+1].getEdge(1).setOpposite(g[e+1].getEdge(0))}else for(g.push(l.createTriangle(p,o,f),l.createTriangle(a,p,f),l.createTriangle(a,f,o),l.createTriangle(a,o,p)),h=0;h<3;h+=1){const e=(h+1)%3;g[h+1].getEdge(2).setOpposite(g[0].getEdge((3-h)%3)),g[h+1].getEdge(0).setOpposite(g[e+1].getEdge(1))}for(h=0;h<4;h+=1)this.faces.push(g[h]);for(h=0;hu&&(u=i,e=g[c])}e&&this.addVertexToFace(t,e)}}}reindexFaceAndVertices(){const e=[];for(let t=0;ti&&(i=r,e=t)}return e}}computeHorizon(e,t,i,s){let r;this.deleteFaceVertices(i),i.mark=u,r=t?t.next:t=i.getEdge(0);do{const t=r.opposite,i=t.face;i.mark===h&&(i.distanceToPlane(e)>this.tolerance?this.computeHorizon(e,t,i,s):s.push(r)),r=r.next}while(r!==t)}addAdjoiningFace(e,t){const i=l.createTriangle(e,t.tail(),t.head());return this.faces.push(i),i.getEdge(-1).setOpposite(t.opposite),i.getEdge(0)}addNewFaces(e,t){let i,s;this.newFaces=[];for(let r=0;r=e.nVertices)throw Error("merge recursion limit exceeded");const n=i.opposite.face;let o=!1;if(2===t?(this.oppositeFaceDistance(i)>-this.tolerance||this.oppositeFaceDistance(i.opposite)>-this.tolerance)&&(o=!0):e.area>n.area?this.oppositeFaceDistance(i)>-this.tolerance?o=!0:this.oppositeFaceDistance(i.opposite)>-this.tolerance&&(s=!1):this.oppositeFaceDistance(i.opposite)>-this.tolerance?o=!0:this.oppositeFaceDistance(i)>-this.tolerance&&(s=!1),o){const t=e.mergeAdjacentFaces(i,[]);for(let i=0;i{const a=[0,0,0];return n(e,t,i),n(a,i,o),s(e,e,a),r(e,e)}},{"../../../maths/vec3/cross":229,"../../../maths/vec3/normalize":244,"../../../maths/vec3/subtract":253}],362:[function(e,t,i){const s=e("./QuickHull");t.exports=(e,t={})=>{const i=new s(e);return i.build(),i.collectFaces(t.skipTriangulation)}},{"./QuickHull":358}],363:[function(e,t,i){const s=e("../../../maths/vec3/cross"),r=e("../../../maths/vec3/subtract"),n=e("../../../maths/vec3/squaredLength");t.exports=(e,t,i)=>Math.sqrt(((e,t,i)=>{const o=[],a=[];r(o,i,t),r(a,e,t);const l=n(s([],a,o)),h=n(o);if(0===h)throw Error("a and b are the same point");return l/h})(e,t,i))},{"../../../maths/vec3/cross":229,"../../../maths/vec3/squaredLength":252,"../../../maths/vec3/subtract":253}],364:[function(e,t,i){const s=e("../../geometries/geom2"),r=e("../../geometries/geom3"),n=e("../../geometries/path2");t.exports=e=>{const t=new Set,i=[],o=e=>{const s=e.toString();t.has(s)||(i.push(e),t.add(s))};return e.forEach((e=>{s.isA(e)?s.toPoints(e).forEach(o):r.isA(e)?r.toPoints(e).forEach((e=>e.forEach(o))):n.isA(e)&&n.toPoints(e).forEach(o)})),i}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78}],365:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../measurements/measureEpsilon"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("../../geometries/path2"),l=e("./snapPolygons"),h=e("./mergePolygons"),c=e("./insertTjunctions"),u=e("./triangulatePolygons");t.exports=(e,...t)=>{if(0===(t=s(t)).length)throw new Error("wrong number of arguments");const i=t.map((t=>{if(a.isA(t))return((e,t)=>t)(0,t);if(n.isA(t))return((e,t)=>t)(0,t);if(o.isA(t))return((e,t)=>{const{snap:i,simplify:s,triangulate:n}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},e),a=r(t);let d=o.toPolygons(t);i&&(d=l(a,d)),s&&(d=h(a,d)),n&&(d=c(d),d=u(a,d));const p=Object.assign({},t);return p.polygons=d,p})(e,t);throw new Error("invalid geometry")}));return 1===i.length?i[0]:i}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../measurements/measureEpsilon":278,"../../utils/flatten":412,"./insertTjunctions":367,"./mergePolygons":368,"./snapPolygons":372,"./triangulatePolygons":373}],366:[function(e,t,i){t.exports={generalize:e("./generalize"),snap:e("./snap"),retessellate:e("./retessellate")}},{"./generalize":365,"./retessellate":370,"./snap":371}],367:[function(e,t,i){const s=e("../../maths/constants"),r=e("../../maths/vec3"),n=e("../../geometries/poly3"),o=e=>`${e}`,a=(e,t,i,s,r,n)=>{const a=o(s),h=o(r),c=`${a}/${h}`,u=`${h}/${a}`;if(e.has(u))return l(e,t,i,r,s,null),null;const d={vertex0:s,vertex1:r,polygonindex:n};return e.has(c)?e.get(c).push(d):e.set(c,[d]),t.has(a)?t.get(a).push(c):t.set(a,[c]),i.has(h)?i.get(h).push(c):i.set(h,[c]),c},l=(e,t,i,s,r,n)=>{const a=o(s),l=o(r),h=`${a}/${l}`;let c=-1;const u=e.get(h);for(let e=0;e{const t=new Map;for(let i=0;i=3){let e=s.vertices[0],n=o(e);for(let a=0;a0){const i=new Map,h=new Map,c=new Map;for(const[e,s]of t)c.set(e,!0),s.forEach((t=>{const s=o(t.vertex0),r=o(t.vertex1);i.has(s)?i.get(s).push(e):i.set(s,[e]),h.has(r)?h.get(r).push(e):h.set(r,[e])}));const u=e.slice(0);for(;0!==t.size;){for(const e of t.keys())c.set(e,!0);let e=!1;for(;;){const d=Array.from(c.keys());if(0===d.length)break;const p=d[0];let f=!0;if(t.has(p)){const d=t.get(p)[0];for(let p=0;p<2;p++){const _=0===p?d.vertex0:d.vertex1,m=0===p?d.vertex1:d.vertex0,g=o(_),v=o(m);let x=[];0===p?h.has(g)&&(x=h.get(g)):i.has(g)&&(x=i.get(g));for(let d=0;d0&&E<1){const _=r.scale(r.create(),x,E);if(r.add(_,_,d),r.squaredDistance(_,g){const t=n.toPoints(e),i=[];for(let e=0;e{const i=`${t.v1}:${t.v2}`;e.set(i,t)},l=(e,t)=>{const i=`${t.v1}:${t.v2}`;e.delete(i)},h=(e,t)=>{const i=`${t.v2}:${t.v1}`;return e.get(i)},c=(e,t,i)=>{let s=e.prev.v1,r=e.prev.v2,n=t.next.v2;const o=p(s,r,n,i);return s=t.prev.v1,r=t.prev.v2,n=e.next.v2,[o,p(s,r,n,i)]},u=r.create(),d=r.create(),p=(e,t,i,s)=>{const n=r.subtract(u,t,e),o=r.subtract(d,i,t);return r.cross(n,n,o),r.dot(n,s)};t.exports=(e,t)=>{const i=[];t.forEach((e=>{const t=i.find((t=>{return i=t[0],r=n.plane(e),Math.abs(i[3]-r[3])<15e-8&&s(i,r);var i,r}));t?t[1].push(e):i.push([n.plane(e),[e]])}));let r=[];return i.forEach((e=>{const t=(e=>{if(e.length<2)return e;const t=e[0].plane,i=e.slice(),s=new Map;for(;i.length>0;){const e=i.shift(),r=o(e);for(let e=0;e=0&&e[1]>=0){const t=n.next,r=i.next;i.prev.next=n.next,i.next.prev=n.prev,n.prev.next=i.next,n.next.prev=i.prev,i.v1=null,i.v2=null,i.next=null,i.prev=null,l(s,n),n.v1=null,n.v2=null,n.next=null,n.prev=null;const o=(e,t,i)=>{const s={v1:i.v1,v2:t.v2,next:t.next,prev:i.prev};i.prev.next=s,t.next.prev=s,l(e,t),t.v1=null,t.v2=null,t.next=null,t.prev=null,l(e,i),i.v1=null,i.v2=null,i.next=null,i.prev=null};0===e[0]&&o(s,t,t.prev),0===e[1]&&o(s,r,r.prev)}}else i.next&&a(s,i)}}const r=[];return s.forEach((e=>{const t=(e=>{let t;const i=[];for(;e.next;){const t=e.next;i.push(e.v1),e.v1=null,e.v2=null,e.next=null,e.prev=null,e=t}return i.length>0&&(t=n.create(i)),t})(e);t&&r.push(t)})),s.clear(),r})(e[1]);r=r.concat(t)})),r}},{"../../geometries/poly3":95,"../../maths/utils/aboutEqualNormals":182,"../../maths/vec3":237}],369:[function(e,t,i){const{EPS:s}=e("../../maths/constants"),r=e("../../maths/line2"),n=e("../../maths/vec2"),o=e("../../maths/OrthoNormalBasis"),a=e("../../maths/utils/interpolateBetween2DPointsForY"),{insertSorted:l,fnNumberSort:h}=e("../../utils"),c=e("../../geometries/poly3");t.exports=e=>{if(e.length<2)return e;const t=[],i=e.length,u=c.plane(e[0]),d=new o(u),p=[],f=[],_=new Map,m=new Map,g=new Map,v=10/s;for(let t=0;t0){let e,a;for(let l=0;la)&&(a=u);let p=m.get(u);p||(p={},m.set(u,p)),p[t]=!0}if(e>=a)s=[],r=0,o=-1;else{let i=_.get(e);i||(i=[],_.set(e,i)),i.push(t)}}s.reverse(),o=r-o-1,p.push(s),f.push(o)}const x=[];m.forEach(((e,t)=>x.push(t))),x.sort(h);let T=[],S=[];for(let e=0;e=r&&(e=0),s[e][1]!==o)break;n=e}let l=a-1;if(l<0&&(l=r-1),s[l][1]===o&&(a=l),n!==t.leftvertexindex&&n===a)T.splice(e,1),--e;else{t.leftvertexindex=n,t.rightvertexindex=a,t.topleft=s[n],t.topright=s[a];let e=n+1;e>=r&&(e=0),t.bottomleft=s[e];let i=a-1;i<0&&(i=r-1),t.bottomright=s[i]}}}let g;if(e>=x.length-1)T=[],g=null;else{g=Number(x[e+1]);const t=.5*(o+g),i=_.get(o);for(const e in i){const s=i[e],r=p[s],n=r.length,h=f[s];let c=h;for(;;){let e=c+1;if(e>=n&&(e=0),r[e][1]!==o)break;if(e===h)break;c=e}let u=h;for(;;){let e=u-1;if(e<0&&(e=n-1),r[e][1]!==o)break;if(e===c)break;u=e}let d=c+1;d>=n&&(d=0);let _=u-1;_<0&&(_=n-1);const m={polygonindex:s,leftvertexindex:c,rightvertexindex:u,topleft:r[c],topright:r[u],bottomleft:r[d],bottomright:r[_]};l(T,m,((e,i)=>{const s=a(e.topleft,e.bottomleft,t),r=a(i.topleft,i.bottomleft,t);return s>r?1:s0){const e=i[i.length-1],t=n.distance(p.topleft,e.topright),r=n.distance(p.bottomleft,e.bottomright);t0){const e=new Set,o=new Set;for(let t=0;t=0)&&(f||d>=0)&&(a.outpolygon=i.outpolygon,a.leftlinecontinues=p,a.rightlinecontinues=f,e.add(t));break}}}for(let i=0;is&&e.outpolygon.leftpoints.push(e.bottomleft),e.outpolygon.leftpoints.reverse();const r=e.outpolygon.rightpoints.concat(e.outpolygon.leftpoints).map((e=>d.to3D(e))),o=c.fromPointsAndPlane(r,u);o.vertices.length&&t.push(o)}}for(let e=0;es&&t.outpolygon.rightpoints.push(t.topright))}S=i}return t}},{"../../geometries/poly3":95,"../../maths/OrthoNormalBasis":109,"../../maths/constants":110,"../../maths/line2":121,"../../maths/utils/interpolateBetween2DPointsForY":185,"../../maths/vec2":206,"../../utils":414}],370:[function(e,t,i){const s=e("../../geometries/geom3"),r=e("../../geometries/poly3"),{NEPS:n}=e("../../maths/constants"),o=e("./reTesselateCoplanarPolygons"),a=(e,t)=>(i,s)=>i.plane[e]-s.plane[e]>t?1:s.plane[e]-i.plane[e]>t?-1:0;t.exports=e=>{if(e.isRetesselated)return e;const t=(e=>{let t=[e];const i=[];for(let e=3;e>=0;e--){const s=[],r=3===e?15e-9:n;t.forEach((t=>{t.sort(a(e,r));let n=0;for(let o=1;or&&(o-n==1?i.push(t[n]):s.push(t.slice(n,o)),n=o);t.length-n==1?i.push(t[n]):s.push(t.slice(n))})),t=s}const s=[];return t.forEach((e=>{e[0]&&(s[e[0].index]=e)})),i.forEach((e=>{s[e.index]=e})),s})(s.toPolygons(e).map(((e,t)=>({vertices:e.vertices,plane:r.plane(e),index:t})))),i=[];t.forEach((e=>{if(Array.isArray(e)){const t=o(e);i.push(...t)}else i.push(e)}));const l=s.create(i);return l.isRetesselated=!0,l}},{"../../geometries/geom3":57,"../../geometries/poly3":95,"../../maths/constants":110,"./reTesselateCoplanarPolygons":369}],371:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../maths/vec2"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("../../geometries/path2"),l=e("../../measurements/measureEpsilon"),h=e("./snapPolygons");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>a.isA(e)?(e=>{const t=l(e),i=a.toPoints(e).map((e=>r.snap(r.create(),e,t)));return a.create(i)})(e):n.isA(e)?(e=>{const t=l(e);let i=n.toSides(e).map((e=>[r.snap(r.create(),e[0],t),r.snap(r.create(),e[1],t)]));return i=i.filter((e=>!r.equals(e[0],e[1]))),n.create(i)})(e):o.isA(e)?(e=>{const t=l(e),i=o.toPolygons(e),s=h(t,i);return o.create(s)})(e):e));return 1===t.length?t[0]:t}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../maths/vec2":206,"../../measurements/measureEpsilon":278,"../../utils/flatten":412,"./snapPolygons":372}],372:[function(e,t,i){const s=e("../../maths/vec3"),r=e("../../geometries/poly3");t.exports=(e,t)=>{let i=t.map((t=>{const i=t.vertices.map((t=>s.snap(s.create(),t,e))),n=[];for(let e=0;e((e,t)=>{const i=Math.abs(r.measureArea(t));return Number.isFinite(i)&&i>e})(n,e))),i}},{"../../geometries/poly3":95,"../../maths/vec3":237}],373:[function(e,t,i){const s=e("../../maths/vec3"),r=e("../../geometries/poly3");t.exports=(e,t)=>{const i=[];return t.forEach((t=>{((e,t,i)=>{const n=t.vertices.length;if(n>3){if(n>4){const o=[0,0,0];t.vertices.forEach((e=>s.add(o,o,e))),s.snap(o,s.divide(o,o,[n,n,n]),e);for(let e=0;e{const s=n(e),r=[0,0,0];for(let e=0;e<3;e++)"center"===t[e]?r[e]=i[e]-(s[0][e]+s[1][e])/2:"max"===t[e]?r[e]=i[e]-s[1][e]:"min"===t[e]&&(r[e]=i[e]-s[0][e]);return o(r,e)};t.exports=(e,...t)=>{e=(e=>{if(!Array.isArray(e.modes)||e.modes.length>3)throw new Error("align(): modes must be an array of length <= 3");if(e.modes=r(e.modes,"none",3),3!==e.modes.filter((e=>["center","max","min","none"].includes(e))).length)throw new Error('align(): all modes must be one of "center", "max" or "min"');if(!Array.isArray(e.relativeTo)||e.relativeTo.length>3)throw new Error("align(): relativeTo must be an array of length <= 3");if(e.relativeTo=r(e.relativeTo,0,3),3!==e.relativeTo.filter((e=>Number.isFinite(e)||null==e)).length)throw new Error("align(): all relativeTo values must be a number, or null.");if("boolean"!=typeof e.grouped)throw new Error("align(): grouped must be a boolean value.");return e})(e=Object.assign({},{modes:["center","center","min"],relativeTo:[0,0,0],grouped:!1},e));let{modes:i,relativeTo:o,grouped:l}=e;if(0===(t=s(t)).length)throw new Error("align(): No geometries were provided to act upon");if(o.filter((e=>null==e)).length){const e=n(t);o=((e,t,i)=>{for(let s=0;s<3;s++)null==e[s]&&("center"===t[s]?e[s]=(i[0][s]+i[1][s])/2:"max"===t[s]?e[s]=i[1][s]:"min"===t[s]&&(e[s]=i[0][s]));return e})(o,i,e)}return 1===(t=l?a(t,i,o):t.map((e=>a(e,i,o)))).length?t[0]:t}},{"../../measurements/measureAggregateBoundingBox":269,"../../utils/flatten":412,"../../utils/padArrayToLength":416,"./translate":381}],375:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom2"),n=e("../../geometries/geom3"),o=e("../../geometries/path2"),a=e("../../measurements/measureBoundingBox"),{translate:l}=e("./translate"),h=(e,...t)=>{const{axes:i,relativeTo:h}=Object.assign({},{axes:[!0,!0,!0],relativeTo:[0,0,0]},e);if(0===(t=s(t)).length)throw new Error("wrong number of arguments");if(3!==h.length)throw new Error("relativeTo must be an array of length 3");e={axes:i,relativeTo:h};const c=t.map((t=>o.isA(t)||r.isA(t)||n.isA(t)?((e,t)=>{const{axes:i,relativeTo:s}=Object.assign({},{axes:[!0,!0,!0],relativeTo:[0,0,0]},e),r=a(t),n=[0,0,0];return i[0]&&(n[0]=s[0]-(r[0][0]+(r[1][0]-r[0][0])/2)),i[1]&&(n[1]=s[1]-(r[0][1]+(r[1][1]-r[0][1])/2)),i[2]&&(n[2]=s[2]-(r[0][2]+(r[1][2]-r[0][2])/2)),l(n,t)})(e,t):t));return 1===c.length?c[0]:c};t.exports={center:h,centerX:(...e)=>h({axes:[!0,!1,!1]},e),centerY:(...e)=>h({axes:[!1,!0,!1]},e),centerZ:(...e)=>h({axes:[!1,!1,!0]},e)}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../measurements/measureBoundingBox":273,"../../utils/flatten":412,"./translate":381}],376:[function(e,t,i){t.exports={align:e("./align"),center:e("./center").center,centerX:e("./center").centerX,centerY:e("./center").centerY,centerZ:e("./center").centerZ,mirror:e("./mirror").mirror,mirrorX:e("./mirror").mirrorX,mirrorY:e("./mirror").mirrorY,mirrorZ:e("./mirror").mirrorZ,rotate:e("./rotate").rotate,rotateX:e("./rotate").rotateX,rotateY:e("./rotate").rotateY,rotateZ:e("./rotate").rotateZ,scale:e("./scale").scale,scaleX:e("./scale").scaleX,scaleY:e("./scale").scaleY,scaleZ:e("./scale").scaleZ,transform:e("./transform"),translate:e("./translate").translate,translateX:e("./translate").translateX,translateY:e("./translate").translateY,translateZ:e("./translate").translateZ}},{"./align":374,"./center":375,"./mirror":377,"./rotate":378,"./scale":379,"./transform":380,"./translate":381}],377:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../maths/mat4"),n=e("../../maths/plane"),o=e("../../geometries/geom2"),a=e("../../geometries/geom3"),l=e("../../geometries/path2"),h=(e,...t)=>{const{origin:i,normal:h}=Object.assign({},{origin:[0,0,0],normal:[0,0,1]},e);if(0===(t=s(t)).length)throw new Error("wrong number of arguments");const c=n.fromNormalAndPoint(n.create(),h,i);if(Number.isNaN(c[0]))throw new Error("the given origin and normal do not define a proper plane");const u=r.mirrorByPlane(r.create(),c),d=t.map((e=>l.isA(e)?l.transform(u,e):o.isA(e)?o.transform(u,e):a.isA(e)?a.transform(u,e):e));return 1===d.length?d[0]:d};t.exports={mirror:h,mirrorX:(...e)=>h({normal:[1,0,0]},e),mirrorY:(...e)=>h({normal:[0,1,0]},e),mirrorZ:(...e)=>h({normal:[0,0,1]},e)}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../maths/mat4":159,"../../maths/plane":178,"../../utils/flatten":412}],378:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../maths/mat4"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("../../geometries/path2"),l=(e,...t)=>{if(!Array.isArray(e))throw new Error("angles must be an array");if(0===(t=s(t)).length)throw new Error("wrong number of arguments");for(e=e.slice();e.length<3;)e.push(0);const i=e[2],l=e[1],h=e[0],c=r.fromTaitBryanRotation(r.create(),i,l,h),u=t.map((e=>a.isA(e)?a.transform(c,e):n.isA(e)?n.transform(c,e):o.isA(e)?o.transform(c,e):e));return 1===u.length?u[0]:u};t.exports={rotate:l,rotateX:(e,...t)=>l([e,0,0],t),rotateY:(e,...t)=>l([0,e,0],t),rotateZ:(e,...t)=>l([0,0,e],t)}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../maths/mat4":159,"../../utils/flatten":412}],379:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../maths/mat4"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("../../geometries/path2"),l=(e,...t)=>{if(!Array.isArray(e))throw new Error("factors must be an array");if(0===(t=s(t)).length)throw new Error("wrong number of arguments");for(e=e.slice();e.length<3;)e.push(1);if(e[0]<=0||e[1]<=0||e[2]<=0)throw new Error("factors must be positive");const i=r.fromScaling(r.create(),e),l=t.map((e=>a.isA(e)?a.transform(i,e):n.isA(e)?n.transform(i,e):o.isA(e)?o.transform(i,e):e));return 1===l.length?l[0]:l};t.exports={scale:l,scaleX:(e,...t)=>l([e,1,1],t),scaleY:(e,...t)=>l([1,e,1],t),scaleZ:(e,...t)=>l([1,1,e],t)}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../maths/mat4":159,"../../utils/flatten":412}],380:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom2"),n=e("../../geometries/geom3"),o=e("../../geometries/path2");t.exports=(e,...t)=>{if(0===(t=s(t)).length)throw new Error("wrong number of arguments");const i=t.map((t=>o.isA(t)?o.transform(e,t):r.isA(t)?r.transform(e,t):n.isA(t)?n.transform(e,t):t));return 1===i.length?i[0]:i}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../utils/flatten":412}],381:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../maths/mat4"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("../../geometries/path2"),l=(e,...t)=>{if(!Array.isArray(e))throw new Error("offset must be an array");if(0===(t=s(t)).length)throw new Error("wrong number of arguments");for(e=e.slice();e.length<3;)e.push(0);const i=r.fromTranslation(r.create(),e),l=t.map((e=>a.isA(e)?a.transform(i,e):n.isA(e)?n.transform(i,e):o.isA(e)?o.transform(i,e):e));return 1===l.length?l[0]:l};t.exports={translate:l,translateX:(e,...t)=>l([e,0,0],t),translateY:(e,...t)=>l([0,e,0],t),translateZ:(e,...t)=>l([0,0,e],t)}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../maths/mat4":159,"../../utils/flatten":412}],382:[function(e,t,i){const{EPS:s,TAU:r}=e("../maths/constants"),n=e("../maths/vec2"),o=e("../geometries/path2"),{isGT:a,isGTE:l,isNumberArray:h}=e("./commonChecks");t.exports=e=>{const t={center:[0,0],radius:1,startAngle:0,endAngle:r,makeTangent:!1,segments:32};let{center:i,radius:c,startAngle:u,endAngle:d,makeTangent:p,segments:f}=Object.assign({},t,e);if(!h(i,2))throw new Error("center must be an array of X and Y values");if(!a(c,0))throw new Error("radius must be greater than zero");if(!l(u,0))throw new Error("startAngle must be positive");if(!l(d,0))throw new Error("endAngle must be positive");if(!l(f,4))throw new Error("segments must be four or more");u%=r,d%=r;let _=r;ud&&(_=d+(r-u));const m=Math.acos((c*c+c*c-s*s)/(2*c*c)),g=n.clone(i);let v;const x=[];if(_.25&&(t=.25);const i=p?e+2:e;for(let s=0;s<=i;s++){let i=s;p&&(i=(s-1)*(e-2*t)/e+t,i<0&&(i=0),i>e&&(i=e));const r=u+i*(_/e);v=n.fromAngleRadians(n.create(),r),n.scale(v,v,c),n.add(v,v,g),x.push(v)}}return o.fromPoints({closed:!1},x)}},{"../geometries/path2":78,"../maths/constants":110,"../maths/vec2":206,"./commonChecks":384}],383:[function(e,t,i){const{TAU:s}=e("../maths/constants"),r=e("./ellipse"),{isGTE:n}=e("./commonChecks");t.exports=e=>{const t={center:[0,0],radius:1,startAngle:0,endAngle:s,segments:32};let{center:i,radius:o,startAngle:a,endAngle:l,segments:h}=Object.assign({},t,e);if(!n(o,0))throw new Error("radius must be positive");return o=[o,o],r({center:i,radius:o,startAngle:a,endAngle:l,segments:h})}},{"../maths/constants":110,"./commonChecks":384,"./ellipse":389}],384:[function(e,t,i){t.exports={isNumberArray:(e,t)=>!!(Array.isArray(e)&&e.length>=t)&&e.every((e=>Number.isFinite(e))),isGT:(e,t)=>Number.isFinite(e)&&e>t,isGTE:(e,t)=>Number.isFinite(e)&&e>=t}},{}],385:[function(e,t,i){const s=e("./cuboid"),{isGTE:r}=e("./commonChecks");t.exports=e=>{let{center:t,size:i}=Object.assign({},{center:[0,0,0],size:2},e);if(!r(i,0))throw new Error("size must be positive");return i=[i,i,i],s({center:t,size:i})}},{"./commonChecks":384,"./cuboid":386}],386:[function(e,t,i){const s=e("../geometries/geom3"),r=e("../geometries/poly3"),{isNumberArray:n}=e("./commonChecks");t.exports=e=>{const{center:t,size:i}=Object.assign({},{center:[0,0,0],size:[2,2,2]},e);if(!n(t,3))throw new Error("center must be an array of X, Y and Z values");if(!n(i,3))throw new Error("size must be an array of width, depth and height values");if(!i.every((e=>e>=0)))throw new Error("size values must be positive");return 0===i[0]||0===i[1]||0===i[2]?s.create():s.create([[[0,4,6,2],[-1,0,0]],[[1,3,7,5],[1,0,0]],[[0,1,5,4],[0,-1,0]],[[2,6,7,3],[0,1,0]],[[0,2,3,1],[0,0,-1]],[[4,5,7,6],[0,0,1]]].map((e=>{const s=e[0].map((e=>[t[0]+i[0]/2*(2*!!(1&e)-1),t[1]+i[1]/2*(2*!!(2&e)-1),t[2]+i[2]/2*(2*!!(4&e)-1)]));return r.create(s)})))}},{"../geometries/geom3":57,"../geometries/poly3":95,"./commonChecks":384}],387:[function(e,t,i){const s=e("../geometries/geom3"),r=e("./cylinderElliptic"),{isGTE:n}=e("./commonChecks");t.exports=e=>{const{center:t,height:i,radius:o,segments:a}=Object.assign({},{center:[0,0,0],height:2,radius:1,segments:32},e);if(!n(o,0))throw new Error("radius must be positive");return 0===i||0===o?s.create():r({center:t,height:i,startRadius:[o,o],endRadius:[o,o],segments:a})}},{"../geometries/geom3":57,"./commonChecks":384,"./cylinderElliptic":388}],388:[function(e,t,i){const{EPS:s,TAU:r}=e("../maths/constants"),n=e("../maths/vec3"),o=e("../geometries/geom3"),a=e("../geometries/poly3"),{sin:l,cos:h}=e("../maths/utils/trigonometry"),{isGT:c,isGTE:u,isNumberArray:d}=e("./commonChecks");t.exports=e=>{const t={center:[0,0,0],height:2,startRadius:[1,1],startAngle:0,endRadius:[1,1],endAngle:r,segments:32};let{center:i,height:p,startRadius:f,startAngle:_,endRadius:m,endAngle:g,segments:v}=Object.assign({},t,e);if(!d(i,3))throw new Error("center must be an array of X, Y and Z values");if(!c(p,0))throw new Error("height must be greater then zero");if(!d(f,2))throw new Error("startRadius must be an array of X and Y values");if(!f.every((e=>e>=0)))throw new Error("startRadius values must be positive");if(!d(m,2))throw new Error("endRadius must be an array of X and Y values");if(!m.every((e=>e>=0)))throw new Error("endRadius values must be positive");if(m.every((e=>0===e))&&f.every((e=>0===e)))throw new Error("at least one radius must be positive");if(!u(_,0))throw new Error("startAngle must be positive");if(!u(g,0))throw new Error("endAngle must be positive");if(!u(v,4))throw new Error("segments must be four or more");_%=r,g%=r;let x=r;_g&&(x=g+(r-_));const T=Math.min(f[0],f[1],m[0],m[1]),S=Math.acos((T*T+T*T-s*s)/(2*T*T));if(x{const s=t*x+_;return n.scale(I,A,i[0]*h(s)),n.scale(P,R,i[1]*l(s)),n.add(I,I,P),n.scale(M,y,e),n.add(M,M,b),n.add(n.create(),I,M)},O=(...e)=>{const t=e.map((e=>n.add(n.create(),e,i)));return a.create(t)},N=[];for(let e=0;e0&&f[1]>0&&N.push(O(b,D(0,i,f),D(0,t,f))),(f[0]>0||f[1]>0)&&N.push(O(D(0,t,f),D(0,i,f),D(1,t,m))),m[0]>0&&m[1]>0&&N.push(O(C,D(1,t,m),D(1,i,m))),(m[0]>0||m[1]>0)&&N.push(O(D(1,t,m),D(0,i,f),D(1,i,m))))}return x{const t={center:[0,0],radius:[1,1],startAngle:0,endAngle:r,segments:32};let{center:i,radius:u,startAngle:d,endAngle:p,segments:f}=Object.assign({},t,e);if(!c(i,2))throw new Error("center must be an array of X and Y values");if(!c(u,2))throw new Error("radius must be an array of X and Y values");if(!u.every((e=>e>=0)))throw new Error("radius values must be positive");if(!h(d,0))throw new Error("startAngle must be positive");if(!h(p,0))throw new Error("endAngle must be positive");if(!h(f,3))throw new Error("segments must be three or more");if(0===u[0]||0===u[1])return o.create();d%=r,p%=r;let _=r;dp&&(_=p+(r-d));const m=Math.min(u[0],u[1]);if(_{const{center:t,radius:i,segments:u,axes:d}=Object.assign({},{center:[0,0,0],radius:[1,1,1],segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},e);if(!c(t,3))throw new Error("center must be an array of X, Y and Z values");if(!c(i,3))throw new Error("radius must be an array of X, Y and Z values");if(!i.every((e=>e>=0)))throw new Error("radius values must be positive");if(!h(u,4))throw new Error("segments must be four or more");if(0===i[0]||0===i[1]||0===i[2])return n.create();const p=r.scale(r.create(),r.normalize(r.create(),d[0]),i[0]),f=r.scale(r.create(),r.normalize(r.create(),d[1]),i[1]),_=r.scale(r.create(),r.normalize(r.create(),d[2]),i[2]),m=Math.round(u/4);let g;const v=[],x=r.create(),T=r.create();for(let e=0;e<=u;e++){const i=s*e/u,n=r.add(r.create(),r.scale(x,p,l(i)),r.scale(T,f,a(i)));if(e>0){let e,i;for(let h=0;h<=m;h++){const c=s/4*h/m,u=l(c),d=a(c);if(h>0){let s,a=[];s=r.subtract(r.create(),r.scale(x,g,e),r.scale(T,_,i)),a.push(r.add(s,s,t)),s=r.subtract(r.create(),r.scale(x,n,e),r.scale(T,_,i)),a.push(r.add(s,s,t)),h{let{radius:t,frequency:i}=Object.assign({},{radius:1,frequency:6},e);if(!a(t,0))throw new Error("radius must be positive");if(!a(i,6))throw new Error("frequency must be six or more");if(0===t)return n.create();i=Math.floor(i/6);const l=[[.850651,0,-.525731],[.850651,-0,.525731],[-.850651,-0,.525731],[-.850651,0,-.525731],[0,-.525731,.850651],[0,.525731,.850651],[0,.525731,-.850651],[0,-.525731,-.850651],[-.525731,-.850651,-0],[.525731,-.850651,-0],[.525731,.850651,0],[-.525731,.850651,0]],h=[[0,9,1],[1,10,0],[6,7,0],[10,6,0],[7,9,0],[5,1,4],[4,1,9],[5,10,1],[2,8,3],[3,11,2],[2,5,4],[4,8,2],[2,11,5],[3,7,6],[6,11,3],[8,7,3],[9,8,4],[11,10,5],[10,11,6],[8,9,7]],c=(e,t,i)=>{const s=e[0],n=e[1],o=e[2];let a=i;const l=[],h=[];for(let e=0;e{const s=1-i,r=[];for(let n=0;n<3;n++)r[n]=e[n]*s+t[n]*i;return r};let d=[],p=[],f=0;for(let e=0;e{if(!Array.isArray(e))throw new Error("points must be an array");return s.fromPoints({},e)}},{"../geometries/path2":78}],394:[function(e,t,i){const s=e("../geometries/geom2");t.exports=e=>{const{points:t,paths:i}=Object.assign({},{points:[],paths:[]},e);if(!Array.isArray(t)||!Array.isArray(i))throw new Error("points and paths must be arrays");let r=t;Array.isArray(t[0])&&(Array.isArray(t[0][0])||(r=[t])),r.forEach(((e,t)=>{if(!Array.isArray(e))throw new Error("list of points "+t+" must be an array");if(e.length<3)throw new Error("list of points "+t+" must contain three or more points");e.forEach(((e,i)=>{if(!Array.isArray(e))throw new Error("list of points "+t+", point "+i+" must be an array");if(e.length<2)throw new Error("list of points "+t+", point "+i+" must contain by X and Y values")}))}));let n=i;if(0===i.length){let e=0;n=r.map((t=>t.map((t=>e++))))}const o=[];r.forEach((e=>e.forEach((e=>o.push(e)))));let a=[];return n.forEach((e=>{const t=e.map((e=>o[e])),i=s.fromPoints(t);a=a.concat(s.toSides(i))})),s.create(a)}},{"../geometries/geom2":42}],395:[function(e,t,i){const s=e("../geometries/geom3"),r=e("../geometries/poly3"),{isNumberArray:n}=e("./commonChecks");t.exports=e=>{const{points:t,faces:i,colors:o,orientation:a}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},e);if(!Array.isArray(t)||!Array.isArray(i))throw new Error("points and faces must be arrays");if(t.length<3)throw new Error("three or more points are required");if(i.length<1)throw new Error("one or more faces are required");if(o){if(!Array.isArray(o))throw new Error("colors must be an array");if(o.length!==i.length)throw new Error("faces and colors must have the same length")}t.forEach(((e,t)=>{if(!n(e,3))throw new Error(`point ${t} must be an array of X, Y, Z values`)})),i.forEach(((e,t)=>{if(e.length<3)throw new Error(`face ${t} must contain 3 or more indexes`);if(!n(e,e.length))throw new Error(`face ${t} must be an array of numbers`)})),"outward"!==a&&i.forEach((e=>e.reverse()));const l=i.map(((e,i)=>{const s=r.create(e.map((e=>t[e])));return o&&o[i]&&(s.color=o[i]),s}));return s.create(l)}},{"../geometries/geom3":57,"../geometries/poly3":95,"./commonChecks":384}],396:[function(e,t,i){const s=e("../maths/vec2"),r=e("../geometries/geom2"),{isNumberArray:n}=e("./commonChecks");t.exports=e=>{const{center:t,size:i}=Object.assign({},{center:[0,0],size:[2,2]},e);if(!n(t,2))throw new Error("center must be an array of X and Y values");if(!n(i,2))throw new Error("size must be an array of X and Y values");if(!i.every((e=>e>=0)))throw new Error("size values must be positive");if(0===i[0]||0===i[1])return r.create();const o=[i[0]/2,i[1]/2],a=[o[0],-o[1]],l=[s.subtract(s.create(),t,o),s.add(s.create(),t,a),s.add(s.create(),t,o),s.subtract(s.create(),t,a)];return r.fromPoints(l)}},{"../geometries/geom2":42,"../maths/vec2":206,"./commonChecks":384}],397:[function(e,t,i){const{EPS:s,TAU:r}=e("../maths/constants"),n=e("../maths/vec2"),o=e("../maths/vec3"),a=e("../geometries/geom3"),l=e("../geometries/poly3"),{sin:h,cos:c}=e("../maths/utils/trigonometry"),{isGTE:u,isNumberArray:d}=e("./commonChecks"),p=e("./cuboid"),f=(e,t,i,a,l,u)=>{const d=r/4*l/a,p=c(d),f=h(d),_=a-l;let m=i*p,g=t[2]-(i-i*f);u||(g=i-i*f-t[2]),m=m>s?m:0;const v=o.add(o.create(),e,[t[0]-i,t[1]-i,g]),x=o.add(o.create(),e,[i-t[0],t[1]-i,g]),T=o.add(o.create(),e,[i-t[0],i-t[1],g]),S=o.add(o.create(),e,[t[0]-i,i-t[1],g]),E=[],b=[],C=[],y=[];for(let e=0;e<=_;e++){const t=_>0?r/4*e/_:0,i=n.fromAngleRadians(n.create(),t);n.scale(i,i,m);const s=o.fromVec2(o.create(),i);E.push(o.add(o.create(),v,s)),o.rotateZ(s,s,[0,0,0],r/4),b.push(o.add(o.create(),x,s)),o.rotateZ(s,s,[0,0,0],r/4),C.push(o.add(o.create(),T,s)),o.rotateZ(s,s,[0,0,0],r/4),y.push(o.add(o.create(),S,s))}return u?[E,b,C,y]:(E.reverse(),b.reverse(),C.reverse(),y.reverse(),[y,C,b,E])},_=(e,t)=>{const i=[];for(let s=0;s{const i=[];for(let s=0;s{e=(e=[e[3],e[2],e[1],e[0]]).map((e=>e.slice().reverse()));const i=[];e.forEach((e=>{e.forEach((e=>i.push(e)))}));const s=[];t.forEach((e=>{e.forEach((e=>s.push(e)))}));const r=[];for(let e=0;e{let{center:t,size:i,roundRadius:r,segments:n}=Object.assign({},{center:[0,0,0],size:[2,2,2],roundRadius:.2,segments:32},e);if(!d(t,3))throw new Error("center must be an array of X, Y and Z values");if(!d(i,3))throw new Error("size must be an array of X, Y and Z values");if(!i.every((e=>e>=0)))throw new Error("size values must be positive");if(!u(r,0))throw new Error("roundRadius must be positive");if(!u(n,4))throw new Error("segments must be four or more");if(0===i[0]||0===i[1]||0===i[2])return a.create();if(0===r)return p({center:t,size:i});if(i=i.map((e=>e/2)),r>i[0]-s||r>i[1]-s||r>i[2]-s)throw new Error("roundRadius must be smaller then the radius of all dimensions");n=Math.floor(n/4);let o=null,h=null,c=[];for(let e=0;e<=n;e++){const s=f(t,i,r,n,e,!0),a=f(t,i,r,n,e,!1);if(0===e&&(c=c.concat(g(a,s))),o&&(c=c.concat(_(o,s),m(o,s))),h&&(c=c.concat(_(h,a),m(h,a))),e===n){let e=s.map((e=>e[0]));c.push(l.create(e)),e=a.map((e=>e[0])),c.push(l.create(e))}o=s,h=a}return a.create(c)}},{"../geometries/geom3":57,"../geometries/poly3":95,"../maths/constants":110,"../maths/utils/trigonometry":188,"../maths/vec2":206,"../maths/vec3":237,"./commonChecks":384,"./cuboid":386}],398:[function(e,t,i){const{EPS:s,TAU:r}=e("../maths/constants"),n=e("../maths/vec3"),o=e("../geometries/geom3"),a=e("../geometries/poly3"),{sin:l,cos:h}=e("../maths/utils/trigonometry"),{isGTE:c,isNumberArray:u}=e("./commonChecks"),d=e("./cylinder");t.exports=e=>{const{center:t,height:i,radius:p,roundRadius:f,segments:_}=Object.assign({},{center:[0,0,0],height:2,radius:1,roundRadius:.2,segments:32},e);if(!u(t,3))throw new Error("center must be an array of X, Y and Z values");if(!c(i,0))throw new Error("height must be positive");if(!c(p,0))throw new Error("radius must be positive");if(!c(f,0))throw new Error("roundRadius must be positive");if(f>p)throw new Error("roundRadius must be smaller then the radius");if(!c(_,4))throw new Error("segments must be four or more");if(0===i||0===p)return o.create();if(0===f)return d({center:t,height:i,radius:p});const m=[0,0,-i/2],g=[0,0,i/2],v=n.subtract(n.create(),g,m);if(2*f>n.length(v)-s)throw new Error("height must be larger than twice roundRadius");let x;x=Math.abs(v[0])>Math.abs(v[1])?n.fromValues(0,1,0):n.fromValues(1,0,0);const T=n.scale(n.create(),n.normalize(n.create(),v),f),S=n.scale(n.create(),n.normalize(n.create(),n.cross(n.create(),T,x)),p),E=n.scale(n.create(),n.normalize(n.create(),n.cross(n.create(),S,T)),p);n.add(m,m,T),n.subtract(g,g,T);const b=Math.floor(.25*_),C=e=>{const i=e.map((e=>n.add(e,e,t)));return a.create(i)},y=[],A=n.create(),R=n.create();let I;for(let e=0;e<=_;e++){const t=r*e/_,i=n.add(n.create(),n.scale(A,S,h(t)),n.scale(R,E,l(t)));if(e>0){let e,t,s=[];s.push(n.add(n.create(),m,i)),s.push(n.add(n.create(),m,I)),s.push(n.add(n.create(),g,I)),s.push(n.add(n.create(),g,i)),y.push(C(s));for(let o=0;o<=b;o++){const a=r/4*o/b,c=h(a),u=l(a);if(o>0){let r;s=[],r=n.add(n.create(),m,n.subtract(A,n.scale(A,I,e),n.scale(R,T,t))),s.push(r),r=n.add(n.create(),m,n.subtract(A,n.scale(A,i,e),n.scale(R,T,t))),s.push(r),o{let{center:t,size:i,roundRadius:c,segments:u}=Object.assign({},{center:[0,0],size:[2,2],roundRadius:.2,segments:32},e);if(!l(t,2))throw new Error("center must be an array of X and Y values");if(!l(i,2))throw new Error("size must be an array of X and Y values");if(!i.every((e=>e>=0)))throw new Error("size values must be positive");if(!a(c,0))throw new Error("roundRadius must be positive");if(!a(u,4))throw new Error("segments must be four or more");if(0===i[0]||0===i[1])return o.create();if(0===c)return h({center:t,size:i});if(i=i.map((e=>e/2)),c>i[0]-s||c>i[1]-s)throw new Error("roundRadius must be smaller then the radius of all dimensions");const d=Math.floor(u/4),p=n.add(n.create(),t,[i[0]-c,i[1]-c]),f=n.add(n.create(),t,[c-i[0],i[1]-c]),_=n.add(n.create(),t,[c-i[0],c-i[1]]),m=n.add(n.create(),t,[i[0]-c,c-i[1]]),g=[],v=[],x=[],T=[];for(let e=0;e<=d;e++){const t=r/4*e/d,i=n.fromAngleRadians(n.create(),t);n.scale(i,i,c),g.push(n.add(n.create(),p,i)),n.rotate(i,i,n.create(),r/4),v.push(n.add(n.create(),f,i)),n.rotate(i,i,n.create(),r/4),x.push(n.add(n.create(),_,i)),n.rotate(i,i,n.create(),r/4),T.push(n.add(n.create(),m,i))}return o.fromPoints(g.concat(v,x,T))}},{"../geometries/geom2":42,"../maths/constants":110,"../maths/vec2":206,"./commonChecks":384,"./rectangle":396}],400:[function(e,t,i){const s=e("./ellipsoid"),{isGTE:r}=e("./commonChecks");t.exports=e=>{let{center:t,radius:i,segments:n,axes:o}=Object.assign({},{center:[0,0,0],radius:1,segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},e);if(!r(i,0))throw new Error("radius must be positive");return i=[i,i,i],s({center:t,radius:i,segments:n,axes:o})}},{"./commonChecks":384,"./ellipsoid":390}],401:[function(e,t,i){const s=e("./rectangle"),{isGTE:r}=e("./commonChecks");t.exports=e=>{let{center:t,size:i}=Object.assign({},{center:[0,0],size:2},e);if(!r(i,0))throw new Error("size must be positive");return i=[i,i],s({center:t,size:i})}},{"./commonChecks":384,"./rectangle":396}],402:[function(e,t,i){const{TAU:s}=e("../maths/constants"),r=e("../maths/vec2"),n=e("../geometries/geom2"),{isGT:o,isGTE:a,isNumberArray:l}=e("./commonChecks"),h=(e,t,i,n)=>{const o=s/e,a=[];for(let s=0;s{let{center:t,vertices:i,outerRadius:c,innerRadius:u,density:d,startAngle:p}=Object.assign({},{center:[0,0],vertices:5,outerRadius:1,innerRadius:0,density:2,startAngle:0},e);if(!l(t,2))throw new Error("center must be an array of X and Y values");if(!a(i,2))throw new Error("vertices must be two or more");if(!o(c,0))throw new Error("outerRadius must be greater than zero");if(!a(u,0))throw new Error("innerRadius must be greater than zero");if(!a(p,0))throw new Error("startAngle must be greater than zero");if(i=Math.floor(i),d=Math.floor(d),p%=s,0===u){if(!a(d,2))throw new Error("density must be two or more");u=c*((e,t)=>e>0&&t>1&&t{const t={innerRadius:1,innerSegments:32,outerRadius:4,outerSegments:32,innerRotation:0,startAngle:0,outerRotation:s},{innerRadius:i,innerSegments:c,outerRadius:u,outerSegments:d,innerRotation:p,startAngle:f,outerRotation:_}=Object.assign({},t,e);if(!l(i,0))throw new Error("innerRadius must be greater than zero");if(!h(c,3))throw new Error("innerSegments must be three or more");if(!l(u,0))throw new Error("outerRadius must be greater than zero");if(!h(d,3))throw new Error("outerSegments must be three or more");if(!h(f,0))throw new Error("startAngle must be positive");if(!l(_,0))throw new Error("outerRotation must be greater than zero");if(i>=u)throw new Error("inner circle is two large to rotate about the outer circle");let m=a({radius:i,segments:c});return 0!==p&&(m=n([0,0,p],m)),m=o([u,0],m),r({startAngle:f,angle:_,segments:d},m)}},{"../maths/constants":110,"../operations/extrusions/extrudeRotate":331,"../operations/transforms/rotate":378,"../operations/transforms/translate":381,"./circle":383,"./commonChecks":384}],404:[function(e,t,i){const{NEPS:s}=e("../maths/constants"),r=e("../maths/vec2"),n=e("../geometries/geom2"),{isNumberArray:o}=e("./commonChecks"),a=(e,t,i)=>Math.acos((e*e+t*t-i*i)/(2*e*t)),l=(e,t,i,s,o,a)=>{const l=r.fromValues(0,0),h=r.fromValues(a,0),c=r.fromValues(s,0);return r.add(c,r.rotate(c,c,[0,0],Math.PI-t),h),n.fromPoints([l,h,c])};t.exports=e=>{let{type:t,values:i}=Object.assign({},{type:"SSS",values:[1,1,1]},e);if("string"!=typeof t)throw new Error("triangle type must be a string");if(t=t.toUpperCase(),"A"!==t[0]&&"S"!==t[0]||"A"!==t[1]&&"S"!==t[1]||"A"!==t[2]&&"S"!==t[2])throw new Error("triangle type must contain three letters; A or S");if(!o(i,3))throw new Error("triangle values must contain three values");if(!i.every((e=>e>0)))throw new Error("triangle values must be greater than zero");switch(t){case"AAA":return(e=>{if(Math.abs(e[0]+e[1]+e[2]-Math.PI)>s)throw new Error("AAA triangles require angles that sum to PI");const t=e[0],i=e[1],r=Math.PI-t-i,n=1/Math.sin(r)*Math.sin(t),o=1/Math.sin(r)*Math.sin(i);return l(t,i,r,n,o,1)})(i);case"AAS":return(e=>{const t=e[0],i=e[1],r=Math.PI+s-t-i;if(r{const t=e[0],i=e[2],r=Math.PI+s-t-i;if(r{const t=e[0],i=e[1],r=e[2],n=((e,t,i)=>t>s?Math.sqrt(e*e+i*i-2*e*i*Math.cos(t)):Math.sqrt((e-i)*(e-i)+e*i*t*t*(1-t*t/12)))(t,i,r),o=a(n,t,r),h=Math.PI-o-i;return l(o,i,h,r,n,t)})(i);case"SSA":return(e=>{const t=e[0],i=e[1],s=e[2],r=Math.asin(i*Math.sin(s)/t),n=Math.PI-r-s,o=t/Math.sin(s)*Math.sin(n);return l(r,n,s,i,o,t)})(i);case"SSS":return(e=>{const t=e[1],i=e[2],s=e[0];if(t+i<=s||i+s<=t||s+t<=i)throw new Error("SSS triangle is incorrect, as the longest side is longer than the sum of the other sides");const r=a(i,s,t),n=a(s,t,i),o=Math.PI-r-n;return l(r,n,o,t,i,s)})(i);default:throw new Error("invalid triangle type, try again")}}},{"../geometries/geom2":42,"../maths/constants":110,"../maths/vec2":206,"./commonChecks":384}],405:[function(e,t,i){t.exports={height:14,32:[16],33:[10,5,21,5,7,void 0,5,2,4,1,5,0,6,1,5,2],34:[16,4,21,4,14,void 0,12,21,12,14],35:[21,11,25,4,-7,void 0,17,25,10,-7,void 0,4,12,18,12,void 0,3,6,17,6],36:[20,8,25,8,-4,void 0,12,25,12,-4,void 0,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3],37:[24,21,21,3,0,void 0,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4,20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,void 0,17,7,15,6,14,4,14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7],38:[26,23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5,1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21,9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2],39:[10,5,19,4,20,5,21,6,20,6,18,5,16,4,15],40:[14,11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7],41:[14,3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7],42:[16,8,21,8,9,void 0,3,18,13,12,void 0,13,18,3,12],43:[26,13,18,13,0,void 0,4,9,22,9],44:[10,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4],45:[26,4,9,22,9],46:[10,5,2,4,1,5,0,6,1,5,2],47:[22,20,25,2,-7],48:[20,9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17,9,17,12,16,17,14,20,11,21,9,21],49:[20,6,17,8,18,11,21,11,0],50:[20,4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13,10,3,0,17,0],51:[20,5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4],52:[20,13,21,3,7,18,7,void 0,13,21,13,0],53:[20,15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4],54:[20,16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11,0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7],55:[20,17,21,7,0,void 0,3,21,17,21],56:[20,8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16,2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13,15,14,16,16,16,18,15,20,12,21,8,21],57:[20,16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9,21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3],58:[10,5,14,4,13,5,12,6,13,5,14,void 0,5,2,4,1,5,0,6,1,5,2],59:[10,5,14,4,13,5,12,6,13,5,14,void 0,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4],60:[24,20,18,4,9,20,0],61:[26,4,12,22,12,void 0,4,6,22,6],62:[24,4,18,20,9,4,0],63:[18,3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,void 0,9,2,8,1,9,0,10,1,9,2],64:[27,18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,void 0,12,16,10,14,9,11,9,8,10,6,11,5,void 0,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,void 0,19,16,18,8,18,6,19,5],65:[18,9,21,1,0,void 0,9,21,17,0,void 0,4,7,14,7],66:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,void 0,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0],67:[21,18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5],68:[21,4,21,4,0,void 0,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0],69:[19,4,21,4,0,void 0,4,21,17,21,void 0,4,11,12,11,void 0,4,0,17,0],70:[18,4,21,4,0,void 0,4,21,17,21,void 0,4,11,12,11],71:[21,18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,void 0,13,8,18,8],72:[22,4,21,4,0,void 0,18,21,18,0,void 0,4,11,18,11],73:[8,4,21,4,0],74:[16,12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7],75:[21,4,21,4,0,void 0,18,21,4,7,void 0,9,12,18,0],76:[17,4,21,4,0,void 0,4,0,16,0],77:[24,4,21,4,0,void 0,4,21,12,0,void 0,20,21,12,0,void 0,20,21,20,0],78:[22,4,21,4,0,void 0,4,21,18,0,void 0,18,21,18,0],79:[22,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21],80:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10],81:[22,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,void 0,12,4,18,-2],82:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,void 0,11,11,18,0],83:[20,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3],84:[16,8,21,8,0,void 0,1,21,15,21],85:[22,4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21],86:[18,1,21,9,0,void 0,17,21,9,0],87:[24,2,21,7,0,void 0,12,21,7,0,void 0,12,21,17,0,void 0,22,21,17,0],88:[20,3,21,17,0,void 0,17,21,3,0],89:[18,1,21,9,11,9,0,void 0,17,21,9,11],90:[20,17,21,3,0,void 0,3,21,17,21,void 0,3,0,17,0],91:[14,4,25,4,-7,void 0,5,25,5,-7,void 0,4,25,11,25,void 0,4,-7,11,-7],92:[14,0,21,14,-3],93:[14,9,25,9,-7,void 0,10,25,10,-7,void 0,3,25,10,25,void 0,3,-7,10,-7],94:[16,6,15,8,18,10,15,void 0,3,12,8,17,13,12,void 0,8,17,8,0],95:[16,0,-2,16,-2],96:[10,6,21,5,20,4,18,4,16,5,15,6,16,5,17],97:[19,15,14,15,0,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],98:[19,4,21,4,0,void 0,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3],99:[18,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],100:[19,15,21,15,0,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],101:[18,3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],102:[12,10,21,8,21,6,20,5,17,5,0,void 0,2,14,9,14],103:[19,15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],104:[19,4,21,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0],105:[8,3,21,4,20,5,21,4,22,3,21,void 0,4,14,4,0],106:[10,5,21,6,20,7,21,6,22,5,21,void 0,6,14,6,-3,5,-6,3,-7,1,-7],107:[17,4,21,4,0,void 0,14,14,4,4,void 0,8,8,15,0],108:[8,4,21,4,0],109:[30,4,14,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0,void 0,15,10,18,13,20,14,23,14,25,13,26,10,26,0],110:[19,4,14,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0],111:[19,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14],112:[19,4,14,4,-7,void 0,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3],113:[19,15,14,15,-7,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],114:[13,4,14,4,0,void 0,4,8,5,11,7,13,9,14,12,14],115:[17,14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3],116:[12,5,21,5,4,6,1,8,0,10,0,void 0,2,14,9,14],117:[19,4,14,4,4,5,1,7,0,10,0,12,1,15,4,void 0,15,14,15,0],118:[16,2,14,8,0,void 0,14,14,8,0],119:[22,3,14,7,0,void 0,11,14,7,0,void 0,11,14,15,0,void 0,19,14,15,0],120:[17,3,14,14,0,void 0,14,14,3,0],121:[16,2,14,8,0,void 0,14,14,8,0,6,-4,4,-6,2,-7,1,-7],122:[17,14,14,3,0,void 0,3,14,14,14,void 0,3,0,14,0],123:[14,9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,void 0,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,void 0,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7],124:[8,4,25,4,-7],125:[14,5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,void 0,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,void 0,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7],126:[24,3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,void 0,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]}},{}],406:[function(e,t,i){t.exports={vectorChar:e("./vectorChar"),vectorText:e("./vectorText")}},{"./vectorChar":407,"./vectorText":409}],407:[function(e,t,i){const s=e("./vectorParams");t.exports=(e,t)=>{const{xOffset:i,yOffset:r,input:n,font:o,height:a,extrudeOffset:l}=s(e,t);let h=n.charCodeAt(0);h&&o[h]||(h=63);const c=[].concat(o[h]),u=(a-l)/o.height,d=l/2,p=c.shift()*u,f=[];let _=[];for(let e=0,t=c.length;e{t||"string"!=typeof e||(e={input:e}),e=e||{};const i=Object.assign({},s,e);return i.input=t||i.input,i}},{"./fonts/single-line/hershey/simplex.js":405}],409:[function(e,t,i){const s=e("./vectorChar"),r=e("./vectorParams"),n=(e,t)=>{const{x:i,y:s}=Object.assign({x:0,y:0},e||{}),r=t.segments;let n=null,o=null;for(let e=0,t=r.length;e{const{xOffset:i,yOffset:o,input:a,font:l,height:h,align:c,extrudeOffset:u,lineSpacing:d,letterSpacing:p}=r(e,t);let f,_,m,g,v,x,[T,S]=[i,o],E={width:0,segments:[]};const b=[];let C=[],y=0;const A=T,R=()=>{b.push(E),y=Math.max(y,E.width),E={width:0,segments:[]}};for(f=0,_=a.length;f<_;f++)m=a[f],g=s({xOffset:T,yOffset:S,font:l,height:h,extrudeOffset:u},m),"\n"!==m?(v=g.width*p,E.width+=v,T+=v," "!==m&&(E.segments=E.segments.concat(g.segments))):(T=A,S-=g.height*d,R());for(E.segments.length&&R(),f=0,_=b.length;f<_;f++)E=b[f],y>E.width&&(x=y-E.width,"right"===c?E=n({x},E):"center"===c&&(E=n({x:x/2},E))),C=C.concat(E.segments);return C}},{"./vectorChar":407,"./vectorParams":408}],410:[function(e,t,i){const s=e("../geometries/geom2"),r=e("../geometries/geom3"),n=e("../geometries/path2");t.exports=e=>{let t;for(const i of e){let e=0;if(s.isA(i)&&(e=1),r.isA(i)&&(e=2),n.isA(i)&&(e=3),t&&e!==t)return!1;t=e}return!0}},{"../geometries/geom2":42,"../geometries/geom3":57,"../geometries/path2":78}],411:[function(e,t,i){t.exports=e=>.017453292519943295*e},{}],412:[function(e,t,i){const s=e=>e.reduce(((e,t)=>Array.isArray(t)?e.concat(s(t)):e.concat(t)),[]);t.exports=s},{}],413:[function(e,t,i){t.exports=(e,t)=>e-t},{}],414:[function(e,t,i){t.exports={areAllShapesTheSameType:e("./areAllShapesTheSameType"),degToRad:e("./degToRad"),flatten:e("./flatten"),fnNumberSort:e("./fnNumberSort"),insertSorted:e("./insertSorted"),radiusToSegments:e("./radiusToSegments"),radToDeg:e("./radToDeg")}},{"./areAllShapesTheSameType":410,"./degToRad":411,"./flatten":412,"./fnNumberSort":413,"./insertSorted":415,"./radToDeg":417,"./radiusToSegments":418}],415:[function(e,t,i){t.exports=(e,t,i)=>{let s=0,r=e.length;for(;r>s;){const n=Math.floor((s+r)/2);i(t,e[n])>0?s=n+1:r=n}e.splice(s,0,t)}},{}],416:[function(e,t,i){t.exports=(e,t,i)=>{for(e=e.slice();e.length57.29577951308232*e},{}],418:[function(e,t,i){const{TAU:s}=e("../maths/constants");t.exports=(e,t,i)=>{const r=t>0?e*s/t:0,n=i>0?s/i:0;return Math.ceil(Math.max(r,n,4))}},{"../maths/constants":110}],419:[function(e,t,i){const{geometries:s}=e("@jscad/modeling"),r=(e,t)=>{const i=[];return s.geom3.toPolygons(e).forEach(((e,t)=>{i.push(a(e))})),i.join("\n")},n=e=>`${e[0]} ${e[1]} ${e[2]}`,o=e=>`vertex ${n(e)}`,a=e=>{const t=[];if(e.vertices.length>=3){const i=o(e.vertices[0]);for(let r=0;r{t.statusCallback&&t.statusCallback({progress:0});const i=`solid JSCAD\n${((e,t)=>{const i=[];return e.forEach(((s,n)=>{i.push(r(s,t)),t.statusCallback&&t.statusCallback({progress:100*n/e.length})})),i.join("\n")})(e,t)}\nendsolid JSCAD\n`;return t.statusCallback&&t.statusCallback({progress:100}),[i]}}},{"@jscad/modeling":108}],420:[function(e,t,i){const{geometries:s}=e("@jscad/modeling");t.exports={serializeBinary:(e,t)=>{t.statusCallback&&t.statusCallback({progress:0});const i=new ArrayBuffer(4),r=new Int32Array(i,0,1),n=new Int8Array(i,0,4);if(r[0]=287454020,68!==n[0])throw new Error("Binary STL output is currently only supported on little-endian (Intel) processors");let o=0,a=0;e.forEach(((e,t)=>{s.geom3.toPolygons(e).forEach((e=>{const t=e.vertices.length;o+=t>=3?t-2:0,a+=1}))}));const l=new Uint8Array(80);for(let e=0;e<80;e++)l[e]=65;const h=new Uint32Array(1);h[0]=o;const c=new ArrayBuffer(50*o),u=new Int8Array(c),d=new ArrayBuffer(50),p=new Int8Array(d),f=new Float32Array(d,0,12),_=new Uint16Array(d,48,1);let m=0;return e.forEach((e=>{s.geom3.toPolygons(e).forEach(((e,i)=>{const r=e.vertices,n=r.length,o=s.poly3.plane(e);for(let e=0;e0?e:0)];f[t++]=s[0],f[t++]=s[1],f[t++]=s[2]}_[0]=0,u.set(p,m),m+=50}t.statusCallback&&t.statusCallback({progress:100*i/a})}))})),t.statusCallback&&t.statusCallback({progress:100}),[l.buffer,h.buffer,c]}}},{"@jscad/modeling":108}],421:[function(e,t,i){const{geometries:s,modifiers:r}=e("@jscad/modeling"),{flatten:n,toArray:o}=e("@jscad/array-utils"),{serializeBinary:a}=e("./CSGToStlb"),{serializeText:l}=e("./CSGToStla");t.exports={mimeType:"application/sla",serialize:(e,...t)=>{e=Object.assign({},{binary:!0,statusCallback:null},e);let i=(t=n(t)).filter((e=>s.geom3.isA(e)));if(0===i.length)throw new Error("only 3D geometries can be serialized to STL");return t.length!==i.length&&console.warn("some objects could not be serialized to STL"),i=o(r.generalize({snap:!0,triangulate:!0},i)),e.binary?a(i,e):l(i,e)}}},{"./CSGToStla":419,"./CSGToStlb":420,"@jscad/array-utils":5,"@jscad/modeling":108}],422:[function(e,t,i){i.byteLength=function(e){var t=l(e),i=t[0],s=t[1];return 3*(i+s)/4-s},i.toByteArray=function(e){var t,i,s=l(e),o=s[0],a=s[1],h=new n(function(e,t,i){return 3*(t+i)/4-i}(0,o,a)),c=0,u=a>0?o-4:o;for(i=0;i>16&255,h[c++]=t>>8&255,h[c++]=255&t;return 2===a&&(t=r[e.charCodeAt(i)]<<2|r[e.charCodeAt(i+1)]>>4,h[c++]=255&t),1===a&&(t=r[e.charCodeAt(i)]<<10|r[e.charCodeAt(i+1)]<<4|r[e.charCodeAt(i+2)]>>2,h[c++]=t>>8&255,h[c++]=255&t),h},i.fromByteArray=function(e){for(var t,i=e.length,r=i%3,n=[],o=16383,a=0,l=i-r;al?l:a+o));return 1===r?(t=e[i-1],n.push(s[t>>2]+s[t<<4&63]+"==")):2===r&&(t=(e[i-2]<<8)+e[i-1],n.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"=")),n.join("")};for(var s=[],r=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)s[a]=o[a],r[o.charCodeAt(a)]=a;function l(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var i=e.indexOf("=");return-1===i&&(i=t),[i,i===t?0:4-i%4]}function h(e,t,i){for(var r,n,o=[],a=t;a>18&63]+s[n>>12&63]+s[n>>6&63]+s[63&n]);return o.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},{}],423:[function(e,t,i){(function(t){var s=e("base64-js"),r=e("ieee754");i.Buffer=t,i.SlowBuffer=function(e){return+e!=e&&(e=0),t.alloc(+e)},i.INSPECT_MAX_BYTES=50;var n=2147483647;function o(e){if(e>n)throw new RangeError('The value "'+e+'" is invalid for option "size"');var i=new Uint8Array(e);return i.__proto__=t.prototype,i}function t(e,t,i){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return h(e)}return a(e,t,i)}function a(e,i,s){if("string"==typeof e)return function(e,i){if("string"==typeof i&&""!==i||(i="utf8"),!t.isEncoding(i))throw new TypeError("Unknown encoding: "+i);var s=0|d(e,i),r=o(s),n=r.write(e,i);return n!==s&&(r=r.slice(0,n)),r}(e,i);if(ArrayBuffer.isView(e))return c(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(U(e,ArrayBuffer)||e&&U(e.buffer,ArrayBuffer))return function(e,i,s){if(i<0||e.byteLength=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return 0|e}function d(e,i){if(t.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||U(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var s=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===s)return 0;for(var n=!1;;)switch(i){case"ascii":case"latin1":case"binary":return s;case"utf8":case"utf-8":return L(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*s;case"hex":return s>>>1;case"base64":return B(e).length;default:if(n)return r?-1:L(e).length;i=(""+i).toLowerCase(),n=!0}}function p(e,t,i){var s=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if((i>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return I(this,t,i);case"utf8":case"utf-8":return C(this,t,i);case"ascii":return A(this,t,i);case"latin1":case"binary":return R(this,t,i);case"base64":return b(this,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,t,i);default:if(s)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),s=!0}}function f(e,t,i){var s=e[t];e[t]=e[i],e[i]=s}function _(e,i,s,r,n){if(0===e.length)return-1;if("string"==typeof s?(r=s,s=0):s>2147483647?s=2147483647:s<-2147483648&&(s=-2147483648),k(s=+s)&&(s=n?0:e.length-1),s<0&&(s=e.length+s),s>=e.length){if(n)return-1;s=e.length-1}else if(s<0){if(!n)return-1;s=0}if("string"==typeof i&&(i=t.from(i,r)),t.isBuffer(i))return 0===i.length?-1:m(e,i,s,r,n);if("number"==typeof i)return i&=255,"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(e,i,s):Uint8Array.prototype.lastIndexOf.call(e,i,s):m(e,[i],s,r,n);throw new TypeError("val must be string, number or Buffer")}function m(e,t,i,s,r){var n,o=1,a=e.length,l=t.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(e.length<2||t.length<2)return-1;o=2,a/=2,l/=2,i/=2}function h(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(r){var c=-1;for(n=i;na&&(i=a-l),n=i;n>=0;n--){for(var u=!0,d=0;dr&&(s=r):s=r;var n=t.length;s>n/2&&(s=n/2);for(var o=0;o>8,r=i%256,n.push(r),n.push(s);return n}(t,e.length-i),e,i,s)}function b(e,t,i){return 0===t&&i===e.length?s.fromByteArray(e):s.fromByteArray(e.slice(t,i))}function C(e,t,i){i=Math.min(e.length,i);for(var s=[],r=t;r239?4:h>223?3:h>191?2:1;if(r+u<=i)switch(u){case 1:h<128&&(c=h);break;case 2:128==(192&(n=e[r+1]))&&(l=(31&h)<<6|63&n)>127&&(c=l);break;case 3:n=e[r+1],o=e[r+2],128==(192&n)&&128==(192&o)&&(l=(15&h)<<12|(63&n)<<6|63&o)>2047&&(l<55296||l>57343)&&(c=l);break;case 4:n=e[r+1],o=e[r+2],a=e[r+3],128==(192&n)&&128==(192&o)&&128==(192&a)&&(l=(15&h)<<18|(63&n)<<12|(63&o)<<6|63&a)>65535&&l<1114112&&(c=l)}null===c?(c=65533,u=1):c>65535&&(c-=65536,s.push(c>>>10&1023|55296),c=56320|1023&c),s.push(c),r+=u}return function(e){var t=e.length;if(t<=y)return String.fromCharCode.apply(String,e);for(var i="",s=0;st&&(e+=" ... "),""},t.prototype.compare=function(e,i,s,r,n){if(U(e,Uint8Array)&&(e=t.from(e,e.offset,e.byteLength)),!t.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===i&&(i=0),void 0===s&&(s=e?e.length:0),void 0===r&&(r=0),void 0===n&&(n=this.length),i<0||s>e.length||r<0||n>this.length)throw new RangeError("out of range index");if(r>=n&&i>=s)return 0;if(r>=n)return-1;if(i>=s)return 1;if(this===e)return 0;for(var o=(n>>>=0)-(r>>>=0),a=(s>>>=0)-(i>>>=0),l=Math.min(o,a),h=this.slice(r,n),c=e.slice(i,s),u=0;u>>=0,isFinite(i)?(i>>>=0,void 0===s&&(s="utf8")):(s=i,i=void 0)}var r=this.length-t;if((void 0===i||i>r)&&(i=r),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");s||(s="utf8");for(var n=!1;;)switch(s){case"hex":return g(this,e,t,i);case"utf8":case"utf-8":return v(this,e,t,i);case"ascii":return x(this,e,t,i);case"latin1":case"binary":return T(this,e,t,i);case"base64":return S(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,i);default:if(n)throw new TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),n=!0}},t.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var y=4096;function A(e,t,i){var s="";i=Math.min(e.length,i);for(var r=t;rr)&&(i=r);for(var n="",o=t;oi)throw new RangeError("Trying to access beyond buffer length")}function D(e,i,s,r,n,o){if(!t.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(i>n||ie.length)throw new RangeError("Index out of range")}function O(e,t,i,s,r,n){if(i+s>e.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function N(e,t,i,s,n){return t=+t,i>>>=0,n||O(e,0,i,4),r.write(e,t,i,s,23,4),i+4}function w(e,t,i,s,n){return t=+t,i>>>=0,n||O(e,0,i,8),r.write(e,t,i,s,52,8),i+8}t.prototype.slice=function(e,i){var s=this.length;(e=~~e)<0?(e+=s)<0&&(e=0):e>s&&(e=s),(i=void 0===i?s:~~i)<0?(i+=s)<0&&(i=0):i>s&&(i=s),i>>=0,t>>>=0,i||M(e,t,this.length);for(var s=this[e],r=1,n=0;++n>>=0,t>>>=0,i||M(e,t,this.length);for(var s=this[e+--t],r=1;t>0&&(r*=256);)s+=this[e+--t]*r;return s},t.prototype.readUInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),this[e]},t.prototype.readUInt16LE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]|this[e+1]<<8},t.prototype.readUInt16BE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]<<8|this[e+1]},t.prototype.readUInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},t.prototype.readUInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},t.prototype.readIntLE=function(e,t,i){e>>>=0,t>>>=0,i||M(e,t,this.length);for(var s=this[e],r=1,n=0;++n=(r*=128)&&(s-=Math.pow(2,8*t)),s},t.prototype.readIntBE=function(e,t,i){e>>>=0,t>>>=0,i||M(e,t,this.length);for(var s=t,r=1,n=this[e+--s];s>0&&(r*=256);)n+=this[e+--s]*r;return n>=(r*=128)&&(n-=Math.pow(2,8*t)),n},t.prototype.readInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},t.prototype.readInt16LE=function(e,t){e>>>=0,t||M(e,2,this.length);var i=this[e]|this[e+1]<<8;return 32768&i?4294901760|i:i},t.prototype.readInt16BE=function(e,t){e>>>=0,t||M(e,2,this.length);var i=this[e+1]|this[e]<<8;return 32768&i?4294901760|i:i},t.prototype.readInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},t.prototype.readInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},t.prototype.readFloatLE=function(e,t){return e>>>=0,t||M(e,4,this.length),r.read(this,e,!0,23,4)},t.prototype.readFloatBE=function(e,t){return e>>>=0,t||M(e,4,this.length),r.read(this,e,!1,23,4)},t.prototype.readDoubleLE=function(e,t){return e>>>=0,t||M(e,8,this.length),r.read(this,e,!0,52,8)},t.prototype.readDoubleBE=function(e,t){return e>>>=0,t||M(e,8,this.length),r.read(this,e,!1,52,8)},t.prototype.writeUIntLE=function(e,t,i,s){e=+e,t>>>=0,i>>>=0,s||D(this,e,t,i,Math.pow(2,8*i)-1,0);var r=1,n=0;for(this[t]=255&e;++n>>=0,i>>>=0,s||D(this,e,t,i,Math.pow(2,8*i)-1,0);var r=i-1,n=1;for(this[t+r]=255&e;--r>=0&&(n*=256);)this[t+r]=e/n&255;return t+i},t.prototype.writeUInt8=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,1,255,0),this[t]=255&e,t+1},t.prototype.writeUInt16LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeUInt16BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeUInt32LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},t.prototype.writeUInt32BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeIntLE=function(e,t,i,s){if(e=+e,t>>>=0,!s){var r=Math.pow(2,8*i-1);D(this,e,t,i,r-1,-r)}var n=0,o=1,a=0;for(this[t]=255&e;++n>>=0,!s){var r=Math.pow(2,8*i-1);D(this,e,t,i,r-1,-r)}var n=i-1,o=1,a=0;for(this[t+n]=255&e;--n>=0&&(o*=256);)e<0&&0===a&&0!==this[t+n+1]&&(a=1),this[t+n]=(e/o|0)-a&255;return t+i},t.prototype.writeInt8=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},t.prototype.writeInt16LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeInt16BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeInt32LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},t.prototype.writeInt32BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeFloatLE=function(e,t,i){return N(this,e,t,!0,i)},t.prototype.writeFloatBE=function(e,t,i){return N(this,e,t,!1,i)},t.prototype.writeDoubleLE=function(e,t,i){return w(this,e,t,!0,i)},t.prototype.writeDoubleBE=function(e,t,i){return w(this,e,t,!1,i)},t.prototype.copy=function(e,i,s,r){if(!t.isBuffer(e))throw new TypeError("argument should be a Buffer");if(s||(s=0),r||0===r||(r=this.length),i>=e.length&&(i=e.length),i||(i=0),r>0&&r=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-i=0;--o)e[o+i]=this[o+s];else Uint8Array.prototype.set.call(e,this.subarray(s,r),i);return n},t.prototype.fill=function(e,i,s,r){if("string"==typeof e){if("string"==typeof i?(r=i,i=0,s=this.length):"string"==typeof s&&(r=s,s=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!t.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var n=e.charCodeAt(0);("utf8"===r&&n<128||"latin1"===r)&&(e=n)}}else"number"==typeof e&&(e&=255);if(i<0||this.length>>=0,s=void 0===s?this.length:s>>>0,e||(e=0),"number"==typeof e)for(o=i;o55295&&i<57344){if(!r){if(i>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(o+1===s){(t-=3)>-1&&n.push(239,191,189);continue}r=i;continue}if(i<56320){(t-=3)>-1&&n.push(239,191,189),r=i;continue}i=65536+(r-55296<<10|i-56320)}else r&&(t-=3)>-1&&n.push(239,191,189);if(r=null,i<128){if((t-=1)<0)break;n.push(i)}else if(i<2048){if((t-=2)<0)break;n.push(i>>6|192,63&i|128)}else if(i<65536){if((t-=3)<0)break;n.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return n}function B(e){return s.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(F,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function V(e,t,i,s){for(var r=0;r=t.length||r>=e.length);++r)t[r+i]=e[r];return r}function U(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function k(e){return e!=e}}).call(this,e("buffer").Buffer)},{"base64-js":422,buffer:423,ieee754:424}],424:[function(e,t,i){i.read=function(e,t,i,s,r){var n,o,a=8*r-s-1,l=(1<>1,c=-7,u=i?r-1:0,d=i?-1:1,p=e[t+u];for(u+=d,n=p&(1<<-c)-1,p>>=-c,c+=a;c>0;n=256*n+e[t+u],u+=d,c-=8);for(o=n&(1<<-c)-1,n>>=-c,c+=s;c>0;o=256*o+e[t+u],u+=d,c-=8);if(0===n)n=1-h;else{if(n===l)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,s),n-=h}return(p?-1:1)*o*Math.pow(2,n-s)},i.write=function(e,t,i,s,r,n){var o,a,l,h=8*n-r-1,c=(1<>1,d=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,p=s?0:n-1,f=s?1:-1,_=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-o))<1&&(o--,l*=2),(t+=o+u>=1?d/l:d*Math.pow(2,1-u))*l>=2&&(o++,l/=2),o+u>=c?(a=0,o=c):o+u>=1?(a=(t*l-1)*Math.pow(2,r),o+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,r),o=0));r>=8;e[i+p]=255&a,p+=f,a/=256,r-=8);for(o=o<0;e[i+p]=255&o,p+=f,o/=256,h-=8);e[i+p-f]|=128*_}},{}]},{},[1])},568:(e,t,i)=>{"use strict";class s{constructor(e){this.jscad=e,this.hashesFromPreviousRun={},this.usedHashes={},this.argCache={}}cleanAllCache(){Object.keys(this.usedHashes).forEach((e=>{if(this.argCache[e])try{this.argCache[e].delete()}catch(e){}})),this.argCache={},this.usedHashes={},this.hashesFromPreviousRun={}}cleanUpCache(){}cacheOp(e,t){let i=null;const s=this.computeHash(e);this.usedHashes[s]=s,this.hashesFromPreviousRun[s]=s;const r=this.checkCache(s);return r?(i=r,i.hash=r.hash):(i=t(),i.hash=s,this.addToCache(s,i)),i}checkCache(e){return this.argCache[e]||null}addToCache(e,t){const i=t;return i.hash=e,this.argCache[e]=i,e}computeHash(e,t){let i=JSON.stringify(e);i=i.replace(/(\"ptr\"\:(-?[0-9]*?)\,)/g,""),i=i.replace(/(\"ptr\"\:(-?[0-9]*))/g,""),i.includes("ptr")&&console.error("YOU DONE MESSED UP YOUR REGEX.");const s=Math.random.toString()+i;return t?s:this.stringToHash(s)}stringToHash(e){let t=0;if(0===e.length)return t;for(let i=0;ie.hash!==t.hash||e.ptr!==t.ptr))}dupShape(e){return e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_WIRE?this.jscad.TopoDS.Wire_1(e):e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_SHELL?this.jscad.TopoDS.Shell_1(e):e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_EDGE?this.jscad.TopoDS.Edge_1(e):e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_SOLID?this.jscad.TopoDS.Solid_1(e):e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_FACE?this.jscad.TopoDS.Face_1(e):e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_COMPOUND?this.jscad.TopoDS.Compound_1(e):e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_COMPSOLID?this.jscad.TopoDS.CompSolid_1(e):e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_VERTEX?this.jscad.TopoDS.Vertex_1(e):void 0}}class r{constructor(){this.tolerance=1e-5}degToRad(e){return e*(Math.PI/180)}remap(e,t,i,s,r){return(e-t)/(i-t)*(r-s)+s}removeAllDuplicateVectors(e,t=1e-7){const i=[];return e.forEach((e=>{i.some((i=>this.vectorsTheSame(e,i,t)))||i.push(e)})),i}removeConsecutiveDuplicates(e,t=!0){const i=[];if(e.length>1){for(let t=1;te.map(((e,i)=>e+t[i]))),[0,0,0]).map((t=>t/e.length))}magnitude(e){return Math.sqrt(e.reduce(((e,t)=>e+t*t),0))}normalize(e){const t=this.magnitude(e);return e.map((e=>e/t))}translatePoint(e,t,i){return[e[0]+t[0]*i,e[1]+t[1]*i,e[2]+t[2]*i]}distanceBetweenPoints(e,t){const i=t[0]-e[0],s=t[1]-e[1],r=t[2]-e[2];return Math.sqrt(i*i+s*s+r*r)}}var n,o,a;!function(e){let t,i,s,r,n,o,a,l,h,c,u,d,p,f,_,m;!function(e){e.arc="arc",e.intersection="intersection",e.tangent="tangent"}(t=e.joinTypeEnum||(e.joinTypeEnum={})),function(e){e.skin="skin",e.pipe="pipe",e.rectoVerso="rectoVerso"}(i=e.bRepOffsetModeEnum||(e.bRepOffsetModeEnum={})),function(e){e.approxChordLength="approxChordLength",e.approxCentripetal="approxCentripetal",e.approxIsoParametric="approxIsoParametric"}(s=e.approxParametrizationTypeEnum||(e.approxParametrizationTypeEnum={})),function(e){e.outside="outside",e.inside="inside",e.middle="middle"}(r=e.directionEnum||(e.directionEnum={})),function(e){e.iges="iges",e.step="step"}(n=e.fileTypeEnum||(e.fileTypeEnum={})),function(e){e.forward="forward",e.reversed="reversed",e.internal="internal",e.external="external"}(o=e.topAbsOrientationEnum||(e.topAbsOrientationEnum={})),function(e){e.in="in",e.out="out",e.on="on",e.unknown="unknown"}(a=e.topAbsStateEnum||(e.topAbsStateEnum={})),function(e){e.unknown="unknown",e.vertex="vertex",e.edge="edge",e.wire="wire",e.face="face",e.shell="shell",e.solid="solid",e.compSolid="compSolid",e.compound="compound",e.shape="shape"}(l=e.shapeTypeEnum||(e.shapeTypeEnum={})),function(e){e.unqualified="unqualified",e.enclosing="enclosing",e.enclosed="enclosed",e.outside="outside",e.noqualifier="noqualifier"}(h=e.gccEntPositionEnum||(e.gccEntPositionEnum={})),function(e){e.keepSide1="keepSide1",e.keepSide2="keepSide2",e.all="all"}(c=e.positionResultEnum||(e.positionResultEnum={})),function(e){e.none="none",e.keepSide1="keepSide1",e.keepSide2="keepSide2"}(u=e.circleInclusionEnum||(e.circleInclusionEnum={})),function(e){e.none="none",e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(d=e.twoCircleInclusionEnum||(e.twoCircleInclusionEnum={})),function(e){e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(p=e.fourSidesStrictEnum||(e.fourSidesStrictEnum={})),function(e){e.outside="outside",e.inside="inside"}(f=e.twoSidesStrictEnum||(e.twoSidesStrictEnum={})),function(e){e.allWithAll="allWithAll",e.inOrder="inOrder",e.inOrderClosed="inOrderClosed"}(_=e.combinationCirclesForFaceEnum||(e.combinationCirclesForFaceEnum={})),function(e){e[e.curve=0]="curve",e[e.edge=1]="edge",e[e.wire=2]="wire",e[e.face=3]="face"}(m=e.typeSpecificityEnum||(e.typeSpecificityEnum={})),e.DecomposedMeshDto=class{constructor(e,t){void 0!==e&&(this.faceList=e),void 0!==t&&(this.edgeList=t)}},e.DecomposedFaceDto=class{},e.DecomposedEdgeDto=class{},e.ShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.PointDto=class{constructor(e){this.point=[0,0,0],void 0!==e&&(this.point=e)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.ConstraintTanLinesFromPtToCircleDto=class{constructor(e,t,i,s,r){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.positionResult=s),void 0!==r&&(this.circleRemainder=r)}},e.ConstraintTanLinesFromTwoPtsToCircleDto=class{constructor(e,t,i,s,r,n){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point1=t),void 0!==i&&(this.point1=i),void 0!==s&&(this.tolerance=s),void 0!==r&&(this.positionResult=r),void 0!==n&&(this.circleRemainder=n)}},e.ConstraintTanLinesOnTwoCirclesDto=class{constructor(e,t,i,s,r){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainders=d.none,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.positionResult=s),void 0!==r&&(this.circleRemainders=r)}},e.ConstraintTanCirclesOnTwoCirclesDto=class{constructor(e,t,i,s){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.radius=s)}},e.ConstraintTanCirclesOnCircleAndPntDto=class{constructor(e,t,i,s){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.radius=s)}},e.CurveAndSurfaceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t)}},e.FilletTwoEdgesInPlaneDto=class{constructor(e,t,i,s,r,n){this.planeOrigin=[0,0,0],this.planeDirection=[0,1,0],this.radius=.3,this.solution=-1,void 0!==e&&(this.edge1=e),void 0!==t&&(this.edge2=t),void 0!==i&&(this.planeOrigin=i),void 0!==s&&(this.planeDirection=s),void 0!==r&&(this.radius=r),void 0!==n&&(this.solution=n)}},e.ClosestPointsOnShapeFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.SplitWireOnPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.ClosestPointsOnShapesFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shapes=e),void 0!==t&&(this.points=t)}},e.ClosestPointsBetweenTwoShapesDto=class{constructor(e,t){void 0!==e&&(this.shape1=e),void 0!==t&&(this.shape2=t)}},e.FaceFromSurfaceAndWireDto=class{constructor(e,t,i){this.inside=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.wire=t),void 0!==i&&(this.inside=i)}},e.WireOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wire=e),void 0!==t&&(this.face=t)}},e.DrawShapeDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,p,f,_,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shape=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdgeIndexes=p),void 0!==f&&(this.edgeIndexHeight=f),void 0!==_&&(this.edgeIndexColour=_),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.DrawShapesDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,p,f,_,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shapes=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdgeIndexes=p),void 0!==f&&(this.edgeIndexHeight=f),void 0!==_&&(this.edgeIndexColour=_),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.FaceSubdivisionDto=class{constructor(e,t,i,s,r,n,o,a,l){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepU=!1,this.removeStartEdgeU=!1,this.removeEndEdgeU=!1,this.shiftHalfStepV=!1,this.removeStartEdgeV=!1,this.removeEndEdgeV=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==s&&(this.shiftHalfStepU=s),void 0!==r&&(this.removeStartEdgeU=r),void 0!==n&&(this.removeEndEdgeU=n),void 0!==o&&(this.shiftHalfStepV=o),void 0!==a&&(this.removeStartEdgeV=a),void 0!==l&&(this.removeEndEdgeV=l)}},e.FaceSubdivisionControlledDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,p,f){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepNthU=0,this.shiftHalfStepUOffsetN=0,this.removeStartEdgeNthU=0,this.removeStartEdgeUOffsetN=0,this.removeEndEdgeNthU=0,this.removeEndEdgeUOffsetN=0,this.shiftHalfStepNthV=0,this.shiftHalfStepVOffsetN=0,this.removeStartEdgeNthV=0,this.removeStartEdgeVOffsetN=0,this.removeEndEdgeNthV=0,this.removeEndEdgeVOffsetN=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==s&&(this.shiftHalfStepNthU=s),void 0!==r&&(this.shiftHalfStepUOffsetN=r),void 0!==n&&(this.removeStartEdgeNthU=n),void 0!==o&&(this.removeStartEdgeUOffsetN=o),void 0!==a&&(this.removeEndEdgeNthU=a),void 0!==l&&(this.removeEndEdgeUOffsetN=l),void 0!==h&&(this.shiftHalfStepNthV=h),void 0!==c&&(this.shiftHalfStepVOffsetN=c),void 0!==u&&(this.removeStartEdgeNthV=u),void 0!==d&&(this.removeStartEdgeVOffsetN=d),void 0!==p&&(this.removeEndEdgeNthV=p),void 0!==f&&(this.removeEndEdgeVOffsetN=f)}},e.FaceLinearSubdivisionDto=class{constructor(e,t,i,s,r,n,o){this.isU=!0,this.param=.5,this.nrPoints=10,this.shiftHalfStep=!1,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==i&&(this.param=i),void 0!==s&&(this.nrPoints=s),void 0!==r&&(this.shiftHalfStep=r),void 0!==n&&(this.removeStartPoint=n),void 0!==o&&(this.removeEndPoint=o)}},e.DataOnUVDto=class{constructor(e,t,i){this.paramU=.5,this.paramV=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.paramU=t),void 0!==i&&(this.paramV=i)}},e.DataOnUVsDto=class{constructor(e,t){this.paramsUV=[[.5,.5]],void 0!==e&&(this.shape=e),void 0!==t&&(this.paramsUV=t)}},e.PolygonDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolygonsDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polygons=e),void 0!==t&&(this.returnCompound=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolylinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.returnCompound=t)}},e.SquareDto=class{constructor(e,t,i){this.size=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.RectangleDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.center=i),void 0!==s&&(this.direction=s)}},e.LPolygonDto=class{constructor(e,t,i,s,n,o,a,l){this.widthFirst=1,this.lengthFirst=2,this.widthSecond=.5,this.lengthSecond=2,this.align=r.outside,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.widthFirst=e),void 0!==t&&(this.lengthFirst=t),void 0!==i&&(this.widthSecond=i),void 0!==s&&(this.lengthSecond=s),void 0!==n&&(this.align=n),void 0!==o&&(this.rotation=o),void 0!==a&&(this.center=a),void 0!==l&&(this.direction=l)}},e.BoxDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.height=3,this.center=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==s&&(this.center=s)}},e.CubeDto=class{constructor(e,t){this.size=1,this.center=[0,0,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t)}},e.BoxFromCornerDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.height=3,this.corner=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==s&&(this.corner=s)}},e.SphereDto=class{constructor(e,t){this.radius=1,this.center=[0,0,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.ConeDto=class{constructor(e,t,i,s,r,n){this.radius1=2,this.radius2=1,this.height=2,this.angle=360,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius1=e),void 0!==t&&(this.radius2=t),void 0!==i&&(this.height=i),void 0!==s&&(this.angle=s),void 0!==r&&(this.center=r),void 0!==n&&(this.direction=n)}},e.LineDto=class{constructor(e,t){this.start=[0,0,0],this.end=[0,1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.returnCompound=t)}},e.ArcEdgeTwoPointsTangentDto=class{constructor(e,t,i){this.start=[0,0,0],this.tangentVec=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.tangentVec=t),void 0!==i&&(this.end=i)}},e.ArcEdgeCircleTwoPointsDto=class{constructor(e,t,i,s){this.start=[0,0,0],this.end=[0,0,1],this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.start=t),void 0!==i&&(this.end=i),void 0!==s&&(this.sense=s)}},e.ArcEdgeCircleTwoAnglesDto=class{constructor(e,t,i,s){this.alphaAngle1=0,this.alphaAngle2=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle1=t),void 0!==i&&(this.alphaAngle2=i),void 0!==s&&(this.sense=s)}},e.ArcEdgeCirclePointAngleDto=class{constructor(e,t,i,s){this.alphaAngle=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle=t),void 0!==s&&(this.sense=s)}},e.ArcEdgeThreePointsDto=class{constructor(e,t,i){this.start=[0,0,0],this.middle=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.middle=t),void 0!==i&&(this.end=i)}},e.CylinderDto=class{constructor(e,t,i,s){this.radius=1,this.height=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.height=t),void 0!==i&&(this.center=i),void 0!==s&&(this.direction=s)}},e.CylindersOnLinesDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.lines=t)}},e.FilletDto=class{constructor(e,t,i,s){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.indexes=s)}},e.FilletEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i)}},e.FilletEdgesListOneRadiusDto=class{constructor(e,t,i){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radius=i)}},e.FilletEdgeVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.paramsU=s)}},e.FilletEdgesVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusLists=i),void 0!==s&&(this.paramsULists=s)}},e.FilletEdgesSameVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.paramsU=s)}},e.Fillet3DWireDto=class{constructor(e,t,i,s,r){this.radius=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.direction=i),void 0!==s&&(this.radiusList=s),void 0!==r&&(this.indexes=r)}},e.ChamferDto=class{constructor(e,t,i,s){this.distance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.distance=t),void 0!==i&&(this.distanceList=i),void 0!==s&&(this.indexes=s)}},e.ChamferEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.distanceList=i)}},e.ChamferEdgeDistAngleDto=class{constructor(e,t,i,s,r){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.angle=r)}},e.ChamferEdgeTwoDistancesDto=class{constructor(e,t,i,s,r){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==s&&(this.distance1=s),void 0!==r&&(this.distance2=r)}},e.ChamferEdgesTwoDistancesListsDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distances1=s),void 0!==r&&(this.distances2=r)}},e.ChamferEdgesTwoDistancesDto=class{constructor(e,t,i,s,r){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distance1=s),void 0!==r&&(this.distance2=r)}},e.ChamferEdgesDistsAnglesDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distances=s),void 0!==r&&(this.angles=r)}},e.ChamferEdgesDistAngleDto=class{constructor(e,t,i,s,r){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.angle=r)}},e.BSplineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BSplinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bSplines=e),void 0!==t&&(this.returnCompound=t)}},e.WireFromTwoCirclesTanDto=class{constructor(e,t,i,s,r){this.keepLines=f.outside,this.circleRemainders=p.outside,this.tolerance=1e-7,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.keepLines=i),void 0!==s&&(this.circleRemainders=s),void 0!==r&&(this.tolerance=r)}},e.FaceFromMultipleCircleTanWiresDto=class{constructor(e,t,i,s){this.combination=_.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.circles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==s&&(this.tolerance=s)}},e.FaceFromMultipleCircleTanWireCollectionsDto=class{constructor(e,t,i,s){this.combination=_.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.listsOfCircles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==s&&(this.tolerance=s)}},e.ZigZagBetweenTwoWiresDto=class{constructor(e,t,i,s,r,n){this.nrZigZags=20,this.divideByEqualDistance=!1,this.zigZagsPerEdge=!0,void 0!==e&&(this.wire1=e),void 0!==t&&(this.wire2=t),void 0!==i&&(this.nrZigZags=i),void 0!==s&&(this.inverse=s),void 0!==r&&(this.divideByEqualDistance=r),void 0!==n&&(this.zigZagsPerEdge=n)}},e.InterpolationDto=class{constructor(e,t,i){this.periodic=!1,this.tolerance=1e-7,void 0!==e&&(this.points=e),void 0!==t&&(this.periodic=t),void 0!==i&&(this.tolerance=i)}},e.InterpolateWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.interpolations=e),void 0!==t&&(this.returnCompound=t)}},e.BezierDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BezierWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bezierWires=e),void 0!==t&&(this.returnCompound=t)}},e.DivideDto=class{constructor(e,t,i,s){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==s&&(this.removeEndPoint=s)}},e.ProjectWireDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wire=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.WiresToPointsDto=class{constructor(e,t,i,s,r,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==s&&(this.minimumOfPoints=s),void 0!==r&&(this.uTolerance=r),void 0!==n&&(this.minimumLength=n)}},e.EdgesToPointsDto=class{constructor(e,t,i,s,r,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==s&&(this.minimumOfPoints=s),void 0!==r&&(this.uTolerance=r),void 0!==n&&(this.minimumLength=n)}},e.ProjectWiresDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wires=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.DivideShapesDto=class{constructor(e,t,i,s){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==s&&(this.removeEndPoint=s)}},e.DataOnGeometryAtParamDto=class{constructor(e,t){this.param=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t)}},e.PointInFaceDto=class{constructor(e,t,i,s){this.tEdgeParam=.5,this.distance2DParam=.5,void 0!==e&&(this.face=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.tEdgeParam=i),void 0!==s&&(this.distance2DParam=s)}},e.DataOnGeometryAtLengthDto=class{constructor(e,t){this.length=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.length=t)}},e.CircleDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.LoftDto=class{constructor(e,t){this.makeSolid=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t)}},e.LoftAdvancedDto=class{constructor(e,t,i,r,n,o,a,l,h,c,u,d){this.makeSolid=!1,this.closed=!1,this.periodic=!1,this.straight=!1,this.nrPeriodicSections=10,this.useSmoothing=!1,this.maxUDegree=3,this.tolerance=1e-7,this.parType=s.approxCentripetal,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t),void 0!==i&&(this.closed=i),void 0!==r&&(this.periodic=r),void 0!==n&&(this.straight=n),void 0!==o&&(this.nrPeriodicSections=o),void 0!==a&&(this.useSmoothing=a),void 0!==l&&(this.maxUDegree=l),void 0!==h&&(this.tolerance=h),void 0!==c&&(this.parType=c),void 0!==u&&(this.startVertex=u),void 0!==d&&(this.endVertex=d)}},e.OffsetDto=class{constructor(e,t,i,s){this.distance=.2,this.tolerance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.face=t),void 0!==i&&(this.distance=i),void 0!==s&&(this.tolerance=s)}},e.OffsetAdvancedDto=class{constructor(e,i,s,r,n,o){this.distance=.2,this.tolerance=.1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.face=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.tolerance=r),void 0!==n&&(this.joinType=n),void 0!==o&&(this.removeIntEdges=o)}},e.RevolveDto=class{constructor(e,t,i,s){this.angle=360,this.direction=[0,1,0],this.copy=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.direction=i),void 0!==s&&(this.copy=s)}},e.ShapeShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.WiresOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t)}},e.PipeWiresCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.radius=t)}},e.PipeWireCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t)}},e.PipePolygonWireNGonDto=class{constructor(e,t,i){this.radius=.1,this.nrCorners=6,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.nrCorners=i)}},e.ExtrudeDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t)}},e.ExtrudeShapesDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.direction=t)}},e.SplitDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.UnionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.DifferenceDto=class{constructor(e,t,i){this.keepEdges=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t),void 0!==i&&(this.keepEdges=i)}},e.IntersectionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.ShapeDto=class{constructor(e){void 0!==e&&(this.shape=e)}},e.CompareShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.otherShape=t)}},e.FixSmallEdgesInWireDto=class{constructor(e,t,i){this.lockvtx=!1,this.precsmall=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.lockvtx=t),void 0!==i&&(this.precsmall=i)}},e.BasicShapeRepairDto=class{constructor(e,t,i,s){this.precision=.001,this.maxTolerance=.01,this.minTolerance=1e-4,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.maxTolerance=i),void 0!==s&&(this.minTolerance=s)}},e.FixClosedDto=class{constructor(e,t){this.precision=-.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t)}},e.ShapesWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.ShapeWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.tolerance=t)}},e.ShapeIndexDto=class{constructor(e,t){this.index=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.EdgeIndexDto=class{constructor(e,t){this.index=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.RotationExtrudeDto=class{constructor(e,t,i){this.height=1,this.angle=360,void 0!==e&&(this.shape=e),void 0!==t&&(this.height=t),void 0!==i&&(this.angle=i)}},e.ThickSolidByJoinDto=class{constructor(e,i,s,r,n,o,a,l){this.offset=1,this.tolerance=.001,this.intersection=!1,this.selfIntersection=!1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.shapes=i),void 0!==s&&(this.offset=s),void 0!==r&&(this.tolerance=r),void 0!==n&&(this.intersection=n),void 0!==o&&(this.selfIntersection=o),void 0!==a&&(this.joinType=a),void 0!==l&&(this.removeIntEdges=l)}},e.TransformDto=class{constructor(e,t,i,s,r){this.translation=[0,0,0],this.rotationAxis=[0,1,0],this.rotationAngle=0,this.scaleFactor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t),void 0!==i&&(this.rotationAxis=i),void 0!==s&&(this.rotationAngle=s),void 0!==r&&(this.scaleFactor=r)}},e.TransformShapesDto=class{constructor(e,t,i,s,r){this.translations=[[0,0,0]],this.rotationAxes=[[0,1,0]],this.rotationAngles=[0],this.scaleFactors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t),void 0!==i&&(this.rotationAxes=i),void 0!==s&&(this.rotationAngles=s),void 0!==r&&(this.scaleFactors=r)}},e.TranslateDto=class{constructor(e,t){this.translation=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t)}},e.TranslateShapesDto=class{constructor(e,t){this.translations=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t)}},e.AlignDto=class{constructor(e,t,i,s,r){this.fromOrigin=[0,0,0],this.fromDirection=[0,0,1],this.toOrigin=[0,1,0],this.toDirection=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.fromOrigin=t),void 0!==i&&(this.fromDirection=i),void 0!==s&&(this.toOrigin=s),void 0!==r&&(this.toDirection=r)}},e.AlignShapesDto=class{constructor(e,t,i,s,r){this.fromOrigins=[[0,0,0]],this.fromDirections=[[0,0,1]],this.toOrigins=[[0,1,0]],this.toDirections=[[0,1,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.fromOrigins=t),void 0!==i&&(this.fromDirections=i),void 0!==s&&(this.toOrigins=s),void 0!==r&&(this.toDirections=r)}},e.MirrorDto=class{constructor(e,t,i){this.origin=[0,0,0],this.direction=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.direction=i)}},e.MirrorShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.directions=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.directions=i)}},e.MirrorAlongNormalDto=class{constructor(e,t,i){this.origin=[0,0,0],this.normal=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.normal=i)}},e.MirrorAlongNormalShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.normals=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.normals=i)}},e.AlignAndTranslateDto=class{constructor(e,t,i){this.direction=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.center=i)}},e.UnifySameDomainDto=class{constructor(e,t,i,s){this.unifyEdges=!0,this.unifyFaces=!0,this.concatBSplines=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.unifyEdges=t),void 0!==i&&(this.unifyFaces=i),void 0!==s&&(this.concatBSplines=s)}},e.FilterFacePointsDto=class{constructor(e,t,i,s,r,n,o,a,l){this.tolerance=1e-4,this.useBndBox=!1,this.gapTolerance=.1,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.useBndBox=s),void 0!==r&&(this.gapTolerance=r),void 0!==n&&(this.keepIn=n),void 0!==o&&(this.keepOn=o),void 0!==a&&(this.keepOut=a),void 0!==l&&(this.keepUnknown=l)}},e.FilterSolidPointsDto=class{constructor(e,t,i,s,r,n,o){this.tolerance=1e-4,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.keepIn=s),void 0!==r&&(this.keepOn=r),void 0!==n&&(this.keepOut=n),void 0!==o&&(this.keepUnknown=o)}},e.AlignAndTranslateShapesDto=class{constructor(e,t,i){this.directions=[[0,1,0]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.directions=t),void 0!==i&&(this.centers=i)}},e.RotateDto=class{constructor(e,t,i){this.axis=[0,0,1],this.angle=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.angle=i)}},e.RotateAroundCenterDto=class{constructor(e,t,i,s){this.angle=0,this.center=[0,0,0],this.axis=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.center=i),void 0!==s&&(this.axis=s)}},e.RotateShapesDto=class{constructor(e,t,i){this.angles=[0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.axes=t),void 0!==i&&(this.angles=i)}},e.RotateAroundCenterShapesDto=class{constructor(e,t,i,s){this.angles=[0],this.centers=[[0,0,0]],this.axes=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.angles=t),void 0!==i&&(this.centers=i),void 0!==s&&(this.axes=s)}},e.ScaleDto=class{constructor(e,t){this.factor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.factor=t)}},e.ScaleShapesDto=class{constructor(e,t){this.factors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.factors=t)}},e.Scale3DDto=class{constructor(e,t,i){this.scale=[1,1,1],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.scale=t),void 0!==i&&(this.center=i)}},e.Scale3DShapesDto=class{constructor(e,t,i){this.scales=[[1,1,1]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.scales=t),void 0!==i&&(this.centers=i)}},e.ShapeToMeshDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.ShapesToMeshesDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.SaveStepDto=class{constructor(e,t,i,s){this.fileName="shape.step",this.adjustYtoZ=!1,this.tryDownload=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustYtoZ=i),void 0!==s&&(this.tryDownload=s)}},e.SaveStlDto=class{constructor(e,t,i,s,r,n){this.fileName="shape.stl",this.precision=.01,this.adjustYtoZ=!1,this.tryDownload=!0,this.binary=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.precision=i),void 0!==s&&(this.adjustYtoZ=s),void 0!==r&&(this.tryDownload=r),void 0!==n&&(this.binary=n)}},e.ImportStepIgesFromTextDto=class{constructor(e,t,i){this.fileType=n.step,this.adjustZtoY=!0,void 0!==e&&(this.text=e),void 0!==t&&(this.fileType=t),void 0!==i&&(this.adjustZtoY=i)}},e.ImportStepIgesDto=class{constructor(e,t){this.adjustZtoY=!0,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.adjustZtoY=t)}},e.LoadStepOrIgesDto=class{constructor(e,t,i){this.fileName="shape.igs",this.adjustZtoY=!0,void 0!==e&&(this.filetext=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustZtoY=i)}},e.CompoundShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.ThisckSolidSimpleDto=class{constructor(e,t){this.offset=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t)}},e.Offset3DWireDto=class{constructor(e,t,i){this.offset=1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t),void 0!==i&&(this.direction=i)}},e.FaceFromWireDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.planar=t)}},e.FaceFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.FacesFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.SewDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.FaceIsoCurveAtParamDto=class{constructor(e,t,i){this.dir="u",void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t),void 0!==i&&(this.dir=i)}},e.DivideFaceToUVPointsDto=class{constructor(e,t,i,s){this.nrOfPointsU=10,this.nrOfPointsV=10,this.flat=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfPointsU=t),void 0!==i&&(this.nrOfPointsV=i),void 0!==s&&(this.flat=s)}},e.Geom2dEllipseDto=class{constructor(e,t,i,s,r){this.center=[0,0],this.direction=[1,0],this.radiusMinor=1,this.radiusMajor=2,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==s&&(this.radiusMajor=s),void 0!==r&&(this.sense=r)}},e.Geom2dCircleDto=class{constructor(e,t,i,s){this.center=[0,0],this.direction=[1,0],this.radius=1,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.sense=s)}},e.ChristmasTreeDto=class{constructor(e,t,i,s,r,n,o,a,l,h){this.height=6,this.innerDist=1.5,this.outerDist=3,this.nrSkirts=5,this.trunkHeight=1,this.trunkWidth=1,this.half=!1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.innerDist=t),void 0!==i&&(this.outerDist=i),void 0!==s&&(this.nrSkirts=s),void 0!==r&&(this.trunkHeight=r),void 0!==n&&(this.trunkWidth=n),void 0!==o&&(this.half=o),void 0!==a&&(this.rotation=a),void 0!==l&&(this.origin=l),void 0!==h&&(this.direction=h)}},e.StarDto=class{constructor(e,t,i,s,r,n,o){this.center=[0,0,0],this.direction=[0,1,0],this.numRays=7,this.half=!1,void 0!==e&&(this.outerRadius=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.numRays=i),void 0!==s&&(this.center=s),void 0!==r&&(this.direction=r),void 0!==n&&(this.offsetOuterEdges=n),void 0!==o&&(this.half=o)}},e.ParallelogramDto=class{constructor(e,t,i,s,r,n){this.center=[0,0,0],this.direction=[0,1,0],this.aroundCenter=!0,this.width=2,this.height=1,this.angle=15,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.aroundCenter=i),void 0!==s&&(this.width=s),void 0!==r&&(this.height=r),void 0!==n&&(this.angle=n)}},e.Heart2DDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.rotation=0,this.sizeApprox=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.rotation=i),void 0!==s&&(this.sizeApprox=s)}},e.NGonWireDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.nrCorners=6,this.radius=1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.nrCorners=i),void 0!==s&&(this.radius=s)}},e.EllipseDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.radiusMinor=1,this.radiusMajor=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==s&&(this.radiusMajor=s)}},e.GeomCylindricalSurfaceDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.Geom2dTrimmedCurveDto=class{constructor(e,t,i,s,r){this.u1=0,this.u2=1,this.sense=!0,this.adjustPeriodic=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.u1=t),void 0!==i&&(this.u2=i),void 0!==s&&(this.sense=s),void 0!==r&&(this.adjustPeriodic=r)}},e.Geom2dSegmentDto=class{constructor(e,t){this.start=[0,0],this.end=[1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.SliceDto=class{constructor(e,t,i){this.step=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.step=t),void 0!==i&&(this.direction=i)}},e.SliceInStepPatternDto=class{constructor(e,t,i){this.steps=[.1,.2],this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.steps=t),void 0!==i&&(this.direction=i)}}}(n||(n={})),function(e){let t;!function(e){e.default="default",e.clearSky="clearSky",e.city="city"}(t=e.skyboxEnum||(e.skyboxEnum={}))}(o||(o={})),"undefined"!=typeof document&&document.currentScript&&document.currentScript.src,function(e){let t,i;!function(e){e.edge="edge",e.round="round",e.chamfer="chamfer"}(t=e.solidCornerTypeEnum||(e.solidCornerTypeEnum={})),function(e){e.left="left",e.center="center",e.right="right"}(i=e.jscadTextAlignEnum||(e.jscadTextAlignEnum={})),e.DrawSolidMeshDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.mesh=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.jscadMesh=n)}},e.DrawSolidMeshesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.meshes=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.jscadMesh=n)}},e.DrawPathDto=class{constructor(e,t,i,s,r,n){this.colour="#444444",this.opacity=1,this.width=10,this.updatable=!1,void 0!==e&&(this.path=e),void 0!==t&&(this.colour=t),void 0!==i&&(this.opacity=i),void 0!==s&&(this.width=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.pathMesh=n)}},e.TransformSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.transformation=t)}},e.TransformSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.transformation=t)}},e.DownloadSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.fileName=t)}},e.DownloadGeometryDto=class{constructor(e,t){void 0!==e&&(this.geometry=e),void 0!==t&&(this.fileName=t)}},e.DownloadSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.fileName=t)}},e.ColorizeDto=class{constructor(e,t){this.color="#0000ff",void 0!==e&&(this.geometry=e),void 0!==t&&(this.color=t)}},e.BooleanObjectsDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.BooleanTwoObjectsDto=class{constructor(e,t){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.BooleanObjectsFromDto=class{constructor(e,t){void 0!==e&&(this.from=e),void 0!==t&&(this.meshes=t)}},e.ExpansionDto=class{constructor(e,i,s,r){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==s&&(this.corners=s),void 0!==r&&(this.segments=r)}},e.OffsetDto=class{constructor(e,i,s,r){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==s&&(this.corners=s),void 0!==r&&(this.segments=r)}},e.ExtrudeLinearDto=class{constructor(e,t,i,s){this.height=1,this.twistAngle=90,this.twistSteps=15,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.twistAngle=i),void 0!==s&&(this.twistSteps=s)}},e.HullDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.ExtrudeRectangularDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRectangularPointsDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.points=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRotateDto=class{constructor(e,t,i,s){this.angle=90,this.startAngle=0,this.segments=24,void 0!==e&&(this.polygon=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.startAngle=i),void 0!==s&&(this.segments=s)}},e.PathDto=class{constructor(e){void 0!==e&&(this.path=e)}},e.PathFromPointsDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.PathsFromPointsDto=class{constructor(e){void 0!==e&&(this.pointsLists=e)}},e.PathFromPolylineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.polyline=e),void 0!==t&&(this.closed=t)}},e.PathAppendCurveDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.path=t)}},e.PathAppendPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.path=t)}},e.PathAppendPolylineDto=class{constructor(e,t){void 0!==e&&(this.polyline=e),void 0!==t&&(this.path=t)}},e.PathAppendArcDto=class{constructor(e,t,i,s,r,n,o,a){this.endPoint=[1,1],this.xAxisRotation=90,this.clockwise=!0,this.large=!1,this.segments=24,this.radiusX=1,this.radiusY=1,void 0!==e&&(this.path=e),void 0!==t&&(this.endPoint=t),void 0!==i&&(this.xAxisRotation=i),void 0!==s&&(this.clockwise=s),void 0!==r&&(this.large=r),void 0!==n&&(this.segments=n),void 0!==o&&(this.radiusX=o),void 0!==a&&(this.radiusY=a)}},e.CircleDto=class{constructor(e,t,i){this.center=[0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipseDto=class{constructor(e,t,i){this.center=[0,0],this.radius=[1,2],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SquareDto=class{constructor(e,t){this.center=[0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.RectangleDto=class{constructor(e,t,i){this.center=[0,0],this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i)}},e.RoundedRectangleDto=class{constructor(e,t,i,s,r){this.center=[0,0],this.roundRadius=.2,this.segments=24,this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.segments=i),void 0!==s&&(this.width=s),void 0!==r&&(this.length=r)}},e.StarDto=class{constructor(e,t,i,s,r,n){this.center=[0,0],this.vertices=10,this.density=1,this.outerRadius=2,this.innerRadius=1,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.vertices=t),void 0!==i&&(this.density=i),void 0!==s&&(this.outerRadius=s),void 0!==r&&(this.innerRadius=r),void 0!==n&&(this.startAngle=n)}},e.CubeDto=class{constructor(e,t){this.center=[0,0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.CubeCentersDto=class{constructor(e,t){this.size=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.size=t)}},e.CuboidDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.width=1,this.length=1,this.height=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.height=s)}},e.CuboidCentersDto=class{constructor(e,t,i,s){this.width=1,this.length=1,this.height=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.height=s)}},e.RoundedCuboidDto=class{constructor(e,t,i,s,r,n){this.center=[0,0,0],this.roundRadius=1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==s&&(this.length=s),void 0!==r&&(this.height=r),void 0!==n&&(this.segments=n)}},e.RoundedCuboidCentersDto=class{constructor(e,t,i,s,r,n){this.roundRadius=.1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==s&&(this.length=s),void 0!==r&&(this.height=r),void 0!==n&&(this.segments=n)}},e.CylidnerEllipticDto=class{constructor(e,t,i,s,r){this.center=[0,0,0],this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==s&&(this.endRadius=s),void 0!==r&&(this.segments=r)}},e.CylidnerCentersEllipticDto=class{constructor(e,t,i,s,r){this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==s&&(this.endRadius=s),void 0!==r&&(this.segments=r)}},e.CylidnerDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.segments=s)}},e.RoundedCylidnerDto=class{constructor(e,t,i,s,r){this.center=[0,0,0],this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==s&&(this.radius=s),void 0!==r&&(this.segments=r)}},e.EllipsoidDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipsoidCentersDto=class{constructor(e,t,i){this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.GeodesicSphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.frequency=12,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.GeodesicSphereCentersDto=class{constructor(e,t,i){this.radius=1,this.frequency=12,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.CylidnerCentersDto=class{constructor(e,t,i,s){this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.segments=s)}},e.RoundedCylidnerCentersDto=class{constructor(e,t,i,s,r){this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==s&&(this.radius=s),void 0!==r&&(this.segments=r)}},e.SphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SphereCentersDto=class{constructor(e,t,i){this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.TorusDto=class{constructor(e,t,i,s,r,n,o,a){this.center=[0,0,0],this.innerRadius=1,this.outerRadius=2,this.innerSegments=24,this.outerSegments=24,this.innerRotation=0,this.outerRotation=360,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.outerRadius=i),void 0!==s&&(this.innerSegments=s),void 0!==r&&(this.outerSegments=r),void 0!==n&&(this.innerRotation=n),void 0!==o&&(this.outerRotation=o),void 0!==a&&(this.startAngle=a)}},e.TextDto=class{constructor(e,t,s,r,n,o,a,l,h){this.text="Hello World",this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.segments=t),void 0!==s&&(this.xOffset=s),void 0!==r&&(this.yOffset=r),void 0!==n&&(this.height=n),void 0!==o&&(this.lineSpacing=o),void 0!==a&&(this.letterSpacing=a),void 0!==l&&(this.align=l),void 0!==h&&(this.extrudeOffset=h)}},e.CylinderTextDto=class{constructor(e,t,s,r,n,o,a,l,h,c,u){this.text="Hello World",this.extrusionHeight=.5,this.extrusionSize=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.extrusionHeight=t),void 0!==s&&(this.extrusionSize=s),void 0!==r&&(this.segments=r),void 0!==n&&(this.xOffset=n),void 0!==o&&(this.yOffset=o),void 0!==a&&(this.height=a),void 0!==l&&(this.lineSpacing=l),void 0!==h&&(this.letterSpacing=h),void 0!==c&&(this.align=c),void 0!==u&&(this.extrudeOffset=u)}},e.SphereTextDto=class{constructor(e,t,s,r,n,o,a,l,h,c){this.text="Hello World",this.radius=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.radius=t),void 0!==s&&(this.segments=s),void 0!==r&&(this.xOffset=r),void 0!==n&&(this.yOffset=n),void 0!==o&&(this.height=o),void 0!==a&&(this.lineSpacing=a),void 0!==l&&(this.letterSpacing=l),void 0!==h&&(this.align=h),void 0!==c&&(this.extrudeOffset=c)}},e.FromPolygonPoints=class{constructor(e){void 0!==e&&(this.polygonPoints=e)}}}(a||(a={}));class l{constructor(e){this.jscad=e}expand(e){const t=e.geometry.length&&e.geometry.length>0?e.geometry:[e.geometry];return e.corners||(e.corners=a.solidCornerTypeEnum.round),this.jscad.expansions.expand({delta:e.delta,corners:e.corners,segments:e.segments},...t)}offset(e){const t=e.geometry.length&&e.geometry.length>0?e.geometry:[e.geometry];return e.corners||(e.corners=a.solidCornerTypeEnum.edge),this.jscad.expansions.offset({delta:e.delta,corners:e.corners,segments:e.segments},...t)}}class h{constructor(e){this.jscad=e}intersect(e){return this.jscad.booleans.intersect(...e.meshes)}subtract(e){return this.jscad.booleans.subtract(...e.meshes)}union(e){return this.jscad.booleans.union(...e.meshes)}intersectTwo(e){const t=[e.first,e.second];return this.jscad.booleans.intersect(...t)}subtractTwo(e){const t=[e.first,e.second];return this.jscad.booleans.subtract(...t)}unionTwo(e){const t=[e.first,e.second];return this.jscad.booleans.union(...t)}subtractFrom(e){const t=[e.from,...e.meshes];return this.jscad.booleans.subtract(...t)}}const c={};function u(e,t){c[e]=t}function d(e){return c[e]}class p{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,s){for(const r in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,r)&&this._BabylonFileParsers[r](e,t,i,s)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach((t=>e=e.concat(t.bones))),e}}p._BabylonFileParsers={},p._IndividualBabylonFileParsers={},u("BABYLON.AbstractScene",p);class f{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(const e in f.Triggers)if(Object.prototype.hasOwnProperty.call(f.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in f.Triggers)if(Object.prototype.hasOwnProperty.call(f.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in f.Triggers)if(Object.prototype.hasOwnProperty.call(f.Triggers,t)&&parseInt(t)===e)return!0;return!1}}f.Triggers={};class _{constructor(e,t=!1,i,s){this.initialize(e,t,i,s)}initialize(e,t=!1,i,s){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=s,this}}class m{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class g{static FromPromise(e,t){const i=new g;return e.then((e=>{i.notifyObservers(e)})).catch((e=>{if(!t)throw e;t.notifyObservers(e)})),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new _(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,r=!1){if(!e)return null;const n=new m(e,t,s);return n.unregisterOnNextCall=r,i?this._observers.unshift(n):this._observers.push(n),this._onObserverAdded&&this._onObserverAdded(n),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(n,this._lastNotifiedValue),n._remove=()=>{this.remove(n)},n}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return!!e&&(e._remove=null,-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))}removeCallback(e,t){for(let i=0;i{this._remove(e)}),0))}_remove(e,t=!0){if(!e)return!1;const i=this._observers.indexOf(e);return-1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,s,r){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const n=this._eventState;n.mask=t,n.target=i,n.currentTarget=s,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=r;for(const i of this._observers)if(!i._willBeUnregistered&&(i.mask&t&&(i.unregisterOnNextCall&&this._deferUnregister(i),i.scope?n.lastReturnValue=i.callback.apply(i.scope,[e,n]):n.lastReturnValue=i.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const s=this._eventState;s.mask=i,s.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,s)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new g;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}const v=1/2.2,x=2.2,T=(Math.sqrt(5),.001);class S{static BuildArray(e,t){const i=[];for(let s=0;sfunction(e,t,i){const s=e[t];if("function"!=typeof s)return null;const r=function(){const s=e.length,n=r.previous.apply(e,arguments);return i(t,s),n};return s.next=r,r.previous=s,e[t]=r,()=>{const i=r.previous;if(!i)return;const s=r.next;s?(i.next=s,s.previous=i):(i.next=void 0,e[t]=i),r.next=void 0,r.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{e?.()}))}}class C{static SetMatrixPrecision(e){if(C.MatrixTrackPrecisionChange=!1,e&&!C.MatrixUse64Bits&&C.MatrixTrackedMatrices)for(let e=0;eparseInt(e.toString().replace(/\W/g,""));class N{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=O(this.x);return e=397*e^O(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return N.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new N(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new N(this.x+e.x,this.y+e.y)}subtract(e){return new N(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new N(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new N(this.x*e,this.y*t)}divide(e){return new N(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new N(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.x=this.x-e,i.y=this.y-t,i}negate(){return new N(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new N(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=T){return e&&A(this.x,e.x,t)&&A(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new N(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new N(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotateToRef(e,t){const i=Math.cos(e),s=Math.sin(e),r=i*this.x-s*this.y,n=s*this.x+i*this.y;return t.x=r,t.y=n,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new N;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new N(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new N(0,0)}static One(){return new N(1,1)}static Random(e=0,t=1){return new N(R(e,t),R(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(R(e,t),R(e,t))}static get ZeroReadOnly(){return N._ZeroReadOnly}static FromArray(e,t=0){return new N(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,a=.5*(2*t.x+(-e.x+i.x)*r+(2*e.x-5*t.x+4*i.x-s.x)*n+(-e.x+3*t.x-3*i.x+s.x)*o),l=.5*(2*t.y+(-e.y+i.y)*r+(2*e.y-5*t.y+4*i.y-s.y)*n+(-e.y+3*t.y-3*i.y+s.y)*o);return new N(a,l)}static ClampToRef(e,t,i,s){return s.x=P(e.x,t.x,i.x),s.y=P(e.y,t.y,i.y),s}static Clamp(e,t,i){const s=P(e.x,t.x,i.x),r=P(e.y,t.y,i.y);return new N(s,r)}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.x*a+i.x*l+t.x*h+s.x*c,d=e.y*a+i.y*l+t.y*h+s.y*c;return new N(u,d)}static Hermite1stDerivative(e,t,i,s,r){return this.Hermite1stDerivativeToRef(e,t,i,s,r,new N)}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n.x=6*(o-r)*e.x+(3*o-4*r+1)*t.x+6*(-o+r)*i.x+(3*o-2*r)*s.x,n.y=6*(o-r)*e.y+(3*o-4*r+1)*t.y+6*(-o+r)*i.y+(3*o-2*r)*s.y,n}static Lerp(e,t,i){const s=e.x+(t.x-e.x)*i,r=e.y+(t.y-e.y)*i;return new N(s,r)}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return N.NormalizeToRef(e,new N)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.xt.x?e.x:t.x,s=e.y>t.y?e.y:t.y;return new N(i,s)}static Transform(e,t){return N.TransformToRef(e,t,new N)}static TransformToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+s[12],n=e.x*s[1]+e.y*s[5]+s[13];return i.x=r,i.y=n,i}static PointInTriangle(e,t,i,s){const r=.5*(-i.y*s.x+t.y*(-i.x+s.x)+t.x*(i.y-s.y)+i.x*s.y),n=r<0?-1:1,o=(t.y*s.x-t.x*s.y+(s.y-t.y)*e.x+(t.x-s.x)*e.y)*n,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*n;return o>0&&a>0&&o+a<2*r*n}static Distance(e,t){return Math.sqrt(N.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y;return i*i+s*s}static Center(e,t){return N.CenterToRef(e,t,new N)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const s=N.DistanceSquared(t,i);if(0===s)return N.Distance(e,t);const r=i.subtract(t),n=Math.max(0,Math.min(1,N.Dot(e.subtract(t),r)/s)),o=t.add(r.multiplyByFloats(n,n));return N.Distance(e,o)}}N._ZeroReadOnly=N.Zero(),Object.defineProperties(N.prototype,{dimension:{value:[2]},rank:{value:1}});class w{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=O(this._x);return e=397*e^O(this._y),e=397*e^O(this._z),e}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return w.FromArrayToRef(e,t,this),this}toQuaternion(){return L.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new w(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new w(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new w(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new w(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new w(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const s=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const r=t*Math.sin(i)*Math.cos(s),n=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(s);return e.set(r,n,o),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,r=this._z,n=e._x,o=e._y,a=e._z,l=e._w,h=2*(o*r-a*s),c=2*(a*i-n*r),u=2*(n*s-o*i);return t._x=i+l*h+o*u-a*c,t._y=s+l*c+a*h-n*u,t._z=r+l*u+n*c-o*h,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new w)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new w)}projectOnPlaneToRef(e,t,i){const s=e.normal,r=e.d,n=V.Vector3[0];this.subtractToRef(t,n),n.normalize();const o=w.Dot(n,s);if(Math.abs(o)<1e-10)i.setAll(1/0);else{const e=-(w.Dot(t,s)+r)/o,a=n.scaleInPlace(e);t.addToRef(a,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=T){return e&&A(this._x,e._x,t)&&A(this._y,e._y,t)&&A(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new w(this._x*e,this._y*t,this._z*i)}divide(e){return new w(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!A(t,i,e))return!0;const s=Math.abs(this._z);return!A(t,s,e)||!A(i,s,e)}get isNonUniform(){const e=Math.abs(this._x);return e!==Math.abs(this._y)||e!==Math.abs(this._z)}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new w(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))}fractToRef(e){return e._x=this.x-Math.floor(this._x),e._y=this.y-Math.floor(this._y),e._z=this.z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new w(this.x-Math.floor(this._x),this.y-Math.floor(this._y),this.z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z==0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if("xyz"===(e=e.toLowerCase()))return this;const t=V.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(V.Matrix[0]),w.TransformCoordinatesToRef(this,V.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,V.Vector3[0]),V.Vector3[0].rotateByQuaternionToRef(e,V.Vector3[0]),t.addToRef(V.Vector3[0],i),i}cross(e){return w.CrossToRef(this,e,new w)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new w)}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new w(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,s){const r=w.Dot(e,i);return(r-s)/(r-w.Dot(t,i))}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(V.Vector3[1]),r=t.normalizeToRef(V.Vector3[2]);let n=w.Dot(s,r);n=P(n,-1,1);const o=Math.acos(n),a=V.Vector3[3];return w.CrossToRef(s,r,a),w.Dot(a,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){V.Vector3[0].copyFrom(e);const s=V.Vector3[0];V.Vector3[1].copyFrom(t);const r=V.Vector3[1];V.Vector3[2].copyFrom(i);const n=V.Vector3[2],o=V.Vector3[3],a=V.Vector3[4];return s.normalize(),r.normalize(),n.normalize(),w.CrossToRef(n,s,o),w.CrossToRef(o,n,a),M(Math.atan2(w.Dot(r,o),w.Dot(r,a)))}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=U.Vector3[0];return t.subtractToRef(e,s),i._y=Math.atan2(s.x,s.z)||0,i._x=Math.atan2(Math.sqrt(s.x**2+s.z**2),s.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=w.Zero();return w.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=P(i,0,1);const r=V.Vector3[0],n=V.Vector3[1];r.copyFrom(e);const o=r.length();r.normalizeFromLength(o),n.copyFrom(t);const a=n.length();n.normalizeFromLength(a);const l=w.Dot(r,n);let h,c;if(l<1-T){const e=Math.acos(l),t=1/Math.sin(e);h=Math.sin((1-i)*e)*t,c=Math.sin(i*e)*t}else h=1-i,c=i;return r.scaleInPlace(h),n.scaleInPlace(c),s.copyFrom(r).addInPlace(n),s.scaleInPlace(I(o,a,i)),s}static SmoothToRef(e,t,i,s,r){return w.SlerpToRef(e,t,0===s?1:i/s,r),r}static FromArray(e,t=0){return new w(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return w.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return w.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new w(0,0,0)}static One(){return new w(1,1,1)}static Up(){return new w(0,1,0)}static get UpReadOnly(){return w._UpReadOnly}static get DownReadOnly(){return w._DownReadOnly}static get RightReadOnly(){return w._RightReadOnly}static get LeftReadOnly(){return w._LeftReadOnly}static get LeftHandedForwardReadOnly(){return w._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return w._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return w._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return w._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return w._ZeroReadOnly}static get OneReadOnly(){return w._OneReadOnly}static Down(){return new w(0,-1,0)}static Forward(e=!1){return new w(0,0,e?-1:1)}static Backward(e=!1){return new w(0,0,e?1:-1)}static Right(){return new w(1,0,0)}static Left(){return new w(-1,0,0)}static Random(e=0,t=1){return new w(R(e,t),R(e,t),R(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(R(e,t),R(e,t),R(e,t))}static TransformCoordinates(e,t){const i=w.Zero();return w.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return w.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=1/(e*n[3]+t*n[7]+i*n[11]+n[15]);return r._x=o*h,r._y=a*h,r._z=l*h,r._isDirty=!0,r}static TransformNormal(e,t){const i=w.Zero();return w.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,s,r){const n=s.m;return r._x=e*n[0]+t*n[4]+i*n[8],r._y=e*n[1]+t*n[5]+i*n[9],r._z=e*n[2]+t*n[6]+i*n[10],r._isDirty=!0,r}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,a=.5*(2*t._x+(-e._x+i._x)*r+(2*e._x-5*t._x+4*i._x-s._x)*n+(-e._x+3*t._x-3*i._x+s._x)*o),l=.5*(2*t._y+(-e._y+i._y)*r+(2*e._y-5*t._y+4*i._y-s._y)*n+(-e._y+3*t._y-3*i._y+s._y)*o),h=.5*(2*t._z+(-e._z+i._z)*r+(2*e._z-5*t._z+4*i._z-s._z)*n+(-e._z+3*t._z-3*i._z+s._z)*o);return new w(a,l,h)}static Clamp(e,t,i){const s=new w;return w.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let r=e._x;r=r>i._x?i._x:r,r=ri._y?i._y:n,n=ni._z?i._z:o,o=o0&&A<0?(I.copyFrom(n),M=t,D=i):A>0&&R<0?(I.copyFrom(a),M=i,D=s):(I.copyFrom(o).scaleInPlace(-1),M=s,D=t);const O=V.Vector3[9],N=V.Vector3[4];if(M.subtractToRef(g,E),D.subtractToRef(g,O),w.CrossToRef(E,O,N),!(w.Dot(N,l)<0))return r.copyFrom(g),Math.abs(f*_);const F=V.Vector3[5];w.CrossToRef(I,N,F),F.normalize();const L=V.Vector3[9];L.copyFrom(M).subtractInPlace(g);const B=L.length();if(Bthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,s){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(s,this.w),this}maximizeInPlaceFromFloats(e,t,i,s){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(s,this.w),this}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e}floor(){return new F(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e.z=this.z-Math.floor(this.z),e.w=this.w-Math.floor(this.w),e}fract(){return new F(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new F)}normalizeToRef(e){const t=this.length();return 0===t||1===t?(e.x=this.x,e.y=this.y,e.z=this.z,e.w=this.w,e):this.scaleToRef(1/t,e)}toVector3(){return new w(this.x,this.y,this.z)}clone(){return new F(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}static FromArray(e,t){return t||(t=0),new F(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return F.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,s,r){return r.x=e,r.y=t,r.z=i,r.w=s,r}static Zero(){return new F(0,0,0,0)}static One(){return new F(1,1,1,1)}static Random(e=0,t=1){return new F(R(e,t),R(e,t),R(e,t),R(e,t))}static RandomToRef(e=0,t=1,i){return i.x=R(e,t),i.y=R(e,t),i.z=R(e,t),i.w=R(e,t),i}static Clamp(e,t,i){return F.ClampToRef(e,t,i,new F)}static ClampToRef(e,t,i,s){return s.x=P(e.x,t.x,i.x),s.y=P(e.y,t.y,i.y),s.z=P(e.z,t.z,i.z),s.w=P(e.w,t.w,i.w),s}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return F._ZeroReadOnly}static Normalize(e){return F.NormalizeToRef(e,new F)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new F;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new F;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(F.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return F.CenterToRef(e,t,new F)}static CenterToRef(e,t,i){return i.x=(e.x+t.x)/2,i.y=(e.y+t.y)/2,i.z=(e.z+t.z)/2,i.w=(e.w+t.w)/2,i}static TransformCoordinates(e,t){return F.TransformCoordinatesToRef(e,t,new F)}static TransformCoordinatesToRef(e,t,i){return F.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=e*n[3]+t*n[7]+i*n[11]+n[15];return r.x=o,r.y=a,r.z=l,r.w=h,r}static TransformNormal(e,t){return F.TransformNormalToRef(e,t,new F)}static TransformNormalToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+e.z*s[8],n=e.x*s[1]+e.y*s[5]+e.z*s[9],o=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=r,i.y=n,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,r,n){const o=r.m;return n.x=e*o[0]+t*o[4]+i*o[8],n.y=e*o[1]+t*o[5]+i*o[9],n.z=e*o[2]+t*o[6]+i*o[10],n.w=s,n}static FromVector3(e,t=0){return new F(e._x,e._y,e._z,t)}static Dot(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w}}F._ZeroReadOnly=F.Zero(),Object.defineProperties(F.prototype,{dimension:{value:[4]},rank:{value:1}});class L{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,s=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=O(this._x);return e=397*e^O(this._y),e=397*e^O(this._z),e=397*e^O(this._w),e}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return L.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=T){return e&&A(this._x,e._x,t)&&A(this._y,e._y,t)&&A(this._z,e._z,t)&&A(this._w,e._w,t)}clone(){return new L(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._isDirty=!0,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new L(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,s){return this._x+=e,this._y+=t,this._z+=i,this._w+=s,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,s){return this.subtractFromFloatsToRef(e,t,i,s,new L)}subtractFromFloatsToRef(e,t,i,s,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._w=this._w-s,r._isDirty=!0,r}subtract(e){return new L(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new L(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){const t=new L(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,s=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,n=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,s,r,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,s){return this._x*=e,this._y*=t,this._z*=i,this._w*=s,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new L)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,s){return this._x===e&&this._y===t&&this._z===i&&this._w===s}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new L(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return 0==e||1==e||this.scaleInPlace(1/e),this}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new L(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=w.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,s=this._y,r=this._w,n=s*t-i*r,o=.4999999;if(n<-o)e._y=2*Math.atan2(s,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>o)e._y=2*Math.atan2(s,r),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const o=r*r,a=t*t,l=i*i,h=s*s;e._z=Math.atan2(2*(i*s+t*r),-a-l+h+o),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*i+s*r),a-l-h+o),e._isDirty=!0}return e}toRotationMatrix(e){return B.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return L.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}static FromRotationMatrix(e){const t=new L;return L.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[1],a=i[5],l=i[9],h=i[2],c=i[6],u=i[10],d=s+a+u;let p;return d>0?(p=.5/Math.sqrt(d+1),t._w=.25/p,t._x=(c-l)*p,t._y=(n-h)*p,t._z=(o-r)*p,t._isDirty=!0):s>a&&s>u?(p=2*Math.sqrt(1+s-a-u),t._w=(c-l)/p,t._x=.25*p,t._y=(r+o)/p,t._z=(n+h)/p,t._isDirty=!0):a>u?(p=2*Math.sqrt(1+a-s-u),t._w=(n-h)/p,t._x=(r+o)/p,t._y=.25*p,t._z=(l+c)/p,t._isDirty=!0):(p=2*Math.sqrt(1+u-s-a),t._w=(o-r)/p,t._x=(n+h)/p,t._y=(l+c)/p,t._z=.25*p,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const s=L.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,r){let n=0===s?1:i/s;return n=P(n,0,1),L.SlerpToRef(e,t,n,r),r}static Zero(){return new L(0,0,0,0)}static Inverse(e){return new L(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new L(0,0,0,1)}static IsIdentity(e){return e&&0===e._x&&0===e._y&&0===e._z&&1===e._w}static RotationAxis(e,t){return L.RotationAxisToRef(e,t,new L)}static RotationAxisToRef(e,t,i){const s=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*s,i._y=e._y*s,i._z=e._z*s,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new L(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,s,r){return r.copyFromFloats(e,t,i,s),r}static FromEulerAngles(e,t,i){const s=new L;return L.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return L.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new L;return L.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return L.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=T){const r=w.Dot(e,t)+1;return rMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(w.CrossToRef(e,t,U.Vector3[0]),i.set(U.Vector3[0].x,U.Vector3[0].y,U.Vector3[0].z,r)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new L;return L.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const r=.5*i,n=.5*t,o=.5*e,a=Math.sin(r),l=Math.cos(r),h=Math.sin(n),c=Math.cos(n),u=Math.sin(o),d=Math.cos(o);return s._x=d*h*l+u*c*a,s._y=u*c*l-d*h*a,s._z=d*c*a-u*h*l,s._w=d*c*l+u*h*a,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new L;return L.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const r=.5*(i+e),n=.5*(i-e),o=.5*t;return s._x=Math.cos(n)*Math.sin(o),s._y=Math.sin(n)*Math.sin(o),s._z=Math.sin(r)*Math.cos(o),s._w=Math.cos(r)*Math.cos(o),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new L(0,0,0,0);return L.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const r=V.Matrix[0];return B.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),r),L.FromRotationMatrixToRef(r,s),s}static FromLookDirectionLH(e,t){const i=new L;return L.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=V.Matrix[0];return B.LookDirectionLHToRef(e,t,s),L.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new L;return L.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=V.Matrix[0];return B.LookDirectionRHToRef(e,t,s),L.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=L.Identity();return L.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let r,n,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,a=!1;if(o<0&&(a=!0,o=-o),o>.999999)n=1-i,r=a?-i:i;else{const e=Math.acos(o),t=1/Math.sin(e);n=Math.sin((1-i)*e)*t,r=a?-Math.sin(i*e)*t:Math.sin(i*e)*t}return s._x=n*e._x+r*t._x,s._y=n*e._y+r*t._y,s._z=n*e._z+r*t._z,s._w=n*e._w+r*t._w,s._isDirty=!0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e._x*a+i._x*l+t._x*h+s._x*c,d=e._y*a+i._y*l+t._y*h+s._y*c,p=e._z*a+i._z*l+t._z*h+s._z*c,f=e._w*a+i._w*l+t._w*h+s._w*c;return new L(u,d,p,f)}static Hermite1stDerivative(e,t,i,s,r){const n=new L;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n._x=6*(o-r)*e._x+(3*o-4*r+1)*t._x+6*(-o+r)*i._x+(3*o-2*r)*s._x,n._y=6*(o-r)*e._y+(3*o-4*r+1)*t._y+6*(-o+r)*i._y+(3*o-2*r)*s._y,n._z=6*(o-r)*e._z+(3*o-4*r+1)*t._z+6*(-o+r)*i._z+(3*o-2*r)*s._z,n._w=6*(o-r)*e._w+(3*o-4*r+1)*t._w+6*(-o+r)*i._w+(3*o-2*r)*s._w,n._isDirty=!0,n}static Normalize(e){const t=L.Zero();return L.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const s=new L;return L.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(P(e.x,t.x,i.x),P(e.y,t.y,i.y),P(e.z,t.z,i.z),P(e.w,t.w,i.w))}static Random(e=0,t=1){return new L(R(e,t),R(e,t),R(e,t),R(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(R(e,t),R(e,t),R(e,t),R(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(L.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return L.CenterToRef(e,t,L.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}Object.defineProperties(L.prototype,{dimension:{value:[4]},rank:{value:1}});class B{static get Use64Bits(){return C.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=B._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,s=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&s}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,C.MatrixTrackPrecisionChange&&C.MatrixTrackedMatrices.push(this),this._m=new C.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]||0!==this._m[1]||0!==this._m[2]||0!==this._m[3]||0!==this._m[4]||0!==this._m[6]||0!==this._m[7]||0!==this._m[8]||0!==this._m[9]||0!==this._m[10]||0!==this._m[11]||0!==this._m[12]||0!==this._m[13]||0!==this._m[14]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;const e=this._m,t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],o=e[5],a=e[6],l=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],f=e[13],_=e[14],m=e[15],g=u*m-_*d,v=c*m-f*d,x=c*_-f*u,T=h*m-p*d,S=h*_-u*p,E=h*f-p*c;return t*+(o*g-a*v+l*x)+i*-(n*g-a*T+l*S)+s*+(n*v-o*T+l*E)+r*-(n*x-o*S+a*E)}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}\n${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}\n${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}\n${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let s=0;s<16;s++)e[t+s]=i[s];return this}asArray(){return this._m}fromArray(e,t=0){return B.FromArrayToRef(e,t,this)}copyFromFloats(...e){return B.FromArrayToRef(e,0,this)}set(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){const t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return B.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){const t=new B;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,s=t._m,r=e.m;for(let e=0;e<16;e++)s[e]=i[e]+r[e];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]-s[e];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new B)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let e=0;e<16;e++)s[e]=i[e]-r[e];return t.markAsUpdated(),t}invertToRef(e){if(!0===this._isIdentity)return B.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],r=t[2],n=t[3],o=t[4],a=t[5],l=t[6],h=t[7],c=t[8],u=t[9],d=t[10],p=t[11],f=t[12],_=t[13],m=t[14],g=t[15],v=d*g-m*p,x=u*g-_*p,T=u*m-_*d,S=c*g-f*p,E=c*m-d*f,b=c*_-f*u,C=+(a*v-l*x+h*T),y=-(o*v-l*S+h*E),A=+(o*x-a*S+h*b),R=-(o*T-a*E+l*b),I=i*C+s*y+r*A+n*R;if(0===I)return e.copyFrom(this),e;const P=1/I,M=l*g-m*h,D=a*g-_*h,O=a*m-_*l,N=o*g-f*h,w=o*m-f*l,F=o*_-f*a,L=l*p-d*h,V=a*p-u*h,U=a*d-u*l,k=o*p-c*h,G=o*d-c*l,z=o*u-c*a,W=-(s*v-r*x+n*T),H=+(i*v-r*S+n*E),X=-(i*x-s*S+n*b),Y=+(i*T-s*E+r*b),j=+(s*M-r*D+n*O),$=-(i*M-r*N+n*w),K=+(i*D-s*N+n*F),q=-(i*O-s*w+r*F),Q=-(s*L-r*V+n*U),Z=+(i*L-r*k+n*G),J=-(i*V-s*k+n*z),ee=+(i*U-s*G+r*z);return B.FromValuesToRef(C*P,W*P,j*P,Q*P,y*P,H*P,$*P,Z*P,A*P,X*P,K*P,J*P,R*P,Y*P,q*P,ee*P,e),e}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new w(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){const e=this.m;return B.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]),this}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){const i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiply(e){const t=new B;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]*=i[e];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let e=0;e<16;e++)s[e]=i[e]*r[e];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const s=this._m,r=e.m,n=s[0],o=s[1],a=s[2],l=s[3],h=s[4],c=s[5],u=s[6],d=s[7],p=s[8],f=s[9],_=s[10],m=s[11],g=s[12],v=s[13],x=s[14],T=s[15],S=r[0],E=r[1],b=r[2],C=r[3],y=r[4],A=r[5],R=r[6],I=r[7],P=r[8],M=r[9],D=r[10],O=r[11],N=r[12],w=r[13],F=r[14],L=r[15];return t[i]=n*S+o*y+a*P+l*N,t[i+1]=n*E+o*A+a*M+l*w,t[i+2]=n*b+o*R+a*D+l*F,t[i+3]=n*C+o*I+a*O+l*L,t[i+4]=h*S+c*y+u*P+d*N,t[i+5]=h*E+c*A+u*M+d*w,t[i+6]=h*b+c*R+u*D+d*F,t[i+7]=h*C+c*I+u*O+d*L,t[i+8]=p*S+f*y+_*P+m*N,t[i+9]=p*E+f*A+_*M+m*w,t[i+10]=p*b+f*R+_*D+m*F,t[i+11]=p*C+f*I+_*O+m*L,t[i+12]=g*S+v*y+x*P+T*N,t[i+13]=g*E+v*A+x*M+T*w,t[i+14]=g*b+v*R+x*D+T*F,t[i+15]=g*C+v*I+x*O+T*L,this}divide(e){return this.divideToRef(e,new B)}divideToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]/s[e];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]/=i[e];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new B)}negateInPlace(){const e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=-t[e];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,s=t.m;return i[0]===s[0]&&i[1]===s[1]&&i[2]===s[2]&&i[3]===s[3]&&i[4]===s[4]&&i[5]===s[5]&&i[6]===s[6]&&i[7]===s[7]&&i[8]===s[8]&&i[9]===s[9]&&i[10]===s[10]&&i[11]===s[11]&&i[12]===s[12]&&i[13]===s[13]&&i[14]===s[14]&&i[15]===s[15]}equalsWithEpsilon(e,t=0){const i=this._m,s=e.m;for(let e=0;e<16;e++)if(!A(i[e],s[e],t))return!1;return!0}equalsToFloats(...e){const t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new B)}floorToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=Math.floor(t[e]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new B)}fractToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=t[e]-Math.floor(t[e]);return e.markAsUpdated(),e}clone(){const e=new B;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=O(this._m[0]);for(let t=1;t<16;t++)e=397*e^O(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new L,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,s,r=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const n=this._m;if(i&&i.copyFromFloats(n[12],n[13],n[14]),(e=e||V.Vector3[0]).x=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),e.y=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),e.z=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]),s){const t=(r?s.absoluteScaling.x:s.scaling.x)<0?-1:1,i=(r?s.absoluteScaling.y:s.scaling.y)<0?-1:1,n=(r?s.absoluteScaling.z:s.scaling.z)<0?-1:1;e.x*=t,e.y*=i,e.z*=n}else this.determinant()<=0&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const i=1/e._x,s=1/e._y,r=1/e._z;B.FromValuesToRef(n[0]*i,n[1]*i,n[2]*i,0,n[4]*s,n[5]*s,n[6]*s,0,n[8]*r,n[9]*r,n[10]*r,0,0,0,0,1,V.Matrix[0]),L.FromRotationMatrixToRef(V.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new F(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){const i=4*e;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){const e=new B;return B.TransposeToRef(this,e),e}transposeToRef(e){return B.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,s,r){if(e<0||e>3)return this;const n=4*e;return this._m[n+0]=t,this._m[n+1]=i,this._m[n+2]=s,this._m[n+3]=r,this.markAsUpdated(),this}scale(e){const t=new B;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){const t=V.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return B.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){const e=new B;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=V.Vector3[0];if(!this.decompose(t))return B.IdentityToRef(e),e;const i=this._m,s=1/t._x,r=1/t._y,n=1/t._z;return B.FromValuesToRef(i[0]*s,i[1]*s,i[2]*s,0,i[4]*r,i[5]*r,i[6]*r,0,i[8]*n,i[9]*n,i[10]*n,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){const i=new B;return B.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let s=0;s<16;s++)i._m[s]=e[s+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,s){for(let r=0;r<16;r++)s._m[r]=e[r+t]*i;return s.markAsUpdated(),s}static get IdentityReadOnly(){return B._IdentityReadOnly}static FromValuesToRef(e,t,i,s,r,n,o,a,l,h,c,u,d,p,f,_,m){const g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=s,g[4]=r,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=p,g[14]=f,g[15]=_,m.markAsUpdated()}static FromValues(e,t,i,s,r,n,o,a,l,h,c,u,d,p,f,_){const m=new B,g=m._m;return g[0]=e,g[1]=t,g[2]=i,g[3]=s,g[4]=r,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=p,g[14]=f,g[15]=_,m.markAsUpdated(),m}static Compose(e,t,i){const s=new B;return B.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const r=s._m,n=t._x,o=t._y,a=t._z,l=t._w,h=n+n,c=o+o,u=a+a,d=n*h,p=n*c,f=n*u,_=o*c,m=o*u,g=a*u,v=l*h,x=l*c,T=l*u,S=e._x,E=e._y,b=e._z;return r[0]=(1-(_+g))*S,r[1]=(p+T)*S,r[2]=(f-x)*S,r[3]=0,r[4]=(p-T)*E,r[5]=(1-(d+g))*E,r[6]=(m+v)*E,r[7]=0,r[8]=(f+x)*b,r[9]=(m-v)*b,r[10]=(1-(d+_))*b,r[11]=0,r[12]=i._x,r[13]=i._y,r[14]=i._z,r[15]=1,s.markAsUpdated(),s}static Identity(){const e=B.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return B.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){const e=B.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){const t=new B;return B.RotationXToRef(e,t),t}static Invert(e){const t=new B;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return B.FromValuesToRef(1,0,0,0,0,s,i,0,0,-i,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationY(e){const t=new B;return B.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return B.FromValuesToRef(s,0,-i,0,0,1,0,0,i,0,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationZ(e){const t=new B;return B.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return B.FromValuesToRef(s,i,0,0,-i,s,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationAxis(e,t){const i=new B;return B.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),r=Math.cos(-t),n=1-r;e.normalize();const o=i._m;return o[0]=e._x*e._x*n+r,o[1]=e._x*e._y*n-e._z*s,o[2]=e._x*e._z*n+e._y*s,o[3]=0,o[4]=e._y*e._x*n+e._z*s,o[5]=e._y*e._y*n+r,o[6]=e._y*e._z*n-e._x*s,o[7]=0,o[8]=e._z*e._x*n-e._y*s,o[9]=e._z*e._y*n+e._x*s,o[10]=e._z*e._z*n+r,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const r=w.Dot(t,e),n=i._m;if(r<-1+T)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=s?1:-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=s?-1:1,n[11]=0;else{const i=w.Cross(t,e),s=1/(1+r);n[0]=i._x*i._x*s+r,n[1]=i._y*i._x*s-i._z,n[2]=i._z*i._x*s+i._y,n[3]=0,n[4]=i._x*i._y*s+i._z,n[5]=i._y*i._y*s+r,n[6]=i._z*i._y*s-i._x,n[7]=0,n[8]=i._x*i._z*s-i._y,n[9]=i._y*i._z*s+i._x,n[10]=i._z*i._z*s+r,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const s=new B;return B.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return L.RotationYawPitchRollToRef(e,t,i,V.Quaternion[0]),V.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new B;return B.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return B.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,s),s._updateIdentityStatus(1===e&&1===t&&1===i),s}static Translation(e,t,i){const s=new B;return B.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return B.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,s),s._updateIdentityStatus(0===e&&0===t&&0===i),s}static Lerp(e,t,i){const s=new B;return B.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const r=s._m,n=e.m,o=t.m;for(let e=0;e<16;e++)r[e]=n[e]*(1-i)+o[e]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new B;return B.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const r=V.Vector3[0],n=V.Quaternion[0],o=V.Vector3[1];e.decompose(r,n,o);const a=V.Vector3[2],l=V.Quaternion[1],h=V.Vector3[3];t.decompose(a,l,h);const c=V.Vector3[4];w.LerpToRef(r,a,i,c);const u=V.Quaternion[2];L.SlerpToRef(n,l,i,u);const d=V.Vector3[5];return w.LerpToRef(o,h,i,d),B.ComposeToRef(c,u,d,s),s}static LookAtLH(e,t,i){const s=new B;return B.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const r=V.Vector3[0],n=V.Vector3[1],o=V.Vector3[2];t.subtractToRef(e,o),o.normalize(),w.CrossToRef(i,o,r);const a=r.lengthSquared();0===a?r.x=1:r.normalizeFromLength(Math.sqrt(a)),w.CrossToRef(o,r,n),n.normalize();const l=-w.Dot(r,e),h=-w.Dot(n,e),c=-w.Dot(o,e);return B.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,l,h,c,1,s),s}static LookAtRH(e,t,i){const s=new B;return B.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const r=V.Vector3[0],n=V.Vector3[1],o=V.Vector3[2];e.subtractToRef(t,o),o.normalize(),w.CrossToRef(i,o,r);const a=r.lengthSquared();0===a?r.x=1:r.normalizeFromLength(Math.sqrt(a)),w.CrossToRef(o,r,n),n.normalize();const l=-w.Dot(r,e),h=-w.Dot(n,e),c=-w.Dot(o,e);return B.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,l,h,c,1,s),s}static LookDirectionLH(e,t){const i=new B;return B.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=V.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const r=V.Vector3[1];return w.CrossToRef(t,s,r),B.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new B;return B.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=V.Vector3[2];return w.CrossToRef(t,e,s),B.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,s,r){const n=new B;return B.OrthoLHToRef(e,t,i,s,n,r),n}static OrthoLHToRef(e,t,i,s,r,n){const o=2/e,a=2/t,l=2/(s-i),h=-(s+i)/(s-i);return B.FromValuesToRef(o,0,0,0,0,a,0,0,0,0,l,0,0,0,h,1,r),n&&r.multiplyToRef(k,r),r._updateIdentityStatus(1===o&&1===a&&1===l&&0===h),r}static OrthoOffCenterLH(e,t,i,s,r,n,o){const a=new B;return B.OrthoOffCenterLHToRef(e,t,i,s,r,n,a,o),a}static OrthoOffCenterLHToRef(e,t,i,s,r,n,o,a){const l=2/(t-e),h=2/(s-i),c=2/(n-r),u=-(n+r)/(n-r),d=(e+t)/(e-t),p=(s+i)/(i-s);return B.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,0,d,p,u,1,o),a&&o.multiplyToRef(k,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,s,r,n,o,a,l,h,c){const u=-o*Math.cos(a),d=-o*Math.sin(a);return B.TranslationToRef(0,0,-l,V.Matrix[1]),B.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,V.Matrix[0]),V.Matrix[1].multiplyToRef(V.Matrix[0],V.Matrix[0]),B.TranslationToRef(0,0,l,V.Matrix[1]),V.Matrix[0].multiplyToRef(V.Matrix[1],V.Matrix[0]),B.OrthoOffCenterLHToRef(e,t,i,s,r,n,h,c),V.Matrix[0].multiplyToRef(h,h),h}static OrthoOffCenterRH(e,t,i,s,r,n,o){const a=new B;return B.OrthoOffCenterRHToRef(e,t,i,s,r,n,a,o),a}static OrthoOffCenterRHToRef(e,t,i,s,r,n,o,a){return B.OrthoOffCenterLHToRef(e,t,i,s,r,n,o,a),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,s,r,n,o,a,l,h,c){const u=o*Math.cos(a),d=o*Math.sin(a);return B.TranslationToRef(0,0,l,V.Matrix[1]),B.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,V.Matrix[0]),V.Matrix[1].multiplyToRef(V.Matrix[0],V.Matrix[0]),B.TranslationToRef(0,0,-l,V.Matrix[1]),V.Matrix[0].multiplyToRef(V.Matrix[1],V.Matrix[0]),B.OrthoOffCenterRHToRef(e,t,i,s,r,n,h,c),V.Matrix[0].multiplyToRef(h,h),h}static PerspectiveLH(e,t,i,s,r,n=0){const o=new B,a=2*i/e,l=2*i/t,h=(s+i)/(s-i),c=-2*s*i/(s-i),u=Math.tan(n);return B.FromValuesToRef(a,0,0,0,0,l,0,u,0,0,h,1,0,0,c,0,o),r&&o.multiplyToRef(k,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,s,r,n=0,o=!1){const a=new B;return B.PerspectiveFovLHToRef(e,t,i,s,a,!0,r,n,o),a}static PerspectiveFovLHToRef(e,t,i,s,r,n=!0,o,a=0,l=!1){const h=i,c=s,u=1/Math.tan(.5*e),d=n?u/t:u,p=n?u:u*t,f=l&&0===h?-1:0!==c?(c+h)/(c-h):1,_=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,m=Math.tan(a);return B.FromValuesToRef(d,0,0,0,0,p,0,m,0,0,f,1,0,0,_,0,r),o&&r.multiplyToRef(k,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,s,r,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return B.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,1,0,0,1,0,r),o&&r.multiplyToRef(k,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,s,r,n=0,o=!1){const a=new B;return B.PerspectiveFovRHToRef(e,t,i,s,a,!0,r,n,o),a}static PerspectiveFovRHToRef(e,t,i,s,r,n=!0,o,a=0,l=!1){const h=i,c=s,u=1/Math.tan(.5*e),d=n?u/t:u,p=n?u:u*t,f=l&&0===h?1:0!==c?-(c+h)/(c-h):-1,_=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,m=Math.tan(a);return B.FromValuesToRef(d,0,0,0,0,p,0,m,0,0,f,-1,0,0,_,0,r),o&&r.multiplyToRef(k,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,s,r,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return B.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,-1,0,0,-1,0,r),o&&r.multiplyToRef(k,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,i,s,r,n){const o=e.width,a=e.height,l=e.x,h=e.y,c=B.FromValues(o/2,0,0,0,0,-a/2,0,0,0,0,n-r,0,l+o/2,a/2+h,r,1),u=new B;return t.multiplyToRef(i,u),u.multiplyToRef(s,u),u.multiplyToRef(c,u)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return C.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){const t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return C.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new B;return B.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[12],a=i[1],l=i[5],h=i[9],c=i[13],u=i[2],d=i[6],p=i[10],f=i[14],_=i[3],m=i[7],g=i[11],v=i[15],x=t._m;return x[0]=s,x[1]=r,x[2]=n,x[3]=o,x[4]=a,x[5]=l,x[6]=h,x[7]=c,x[8]=u,x[9]=d,x[10]=p,x[11]=f,x[12]=_,x[13]=m,x[14]=g,x[15]=v,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new B;return B.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,s=e.normal.y,r=e.normal.z,n=-2*i,o=-2*s,a=-2*r;return B.FromValuesToRef(n*i+1,o*i,a*i,0,n*s,o*s+1,a*s,0,n*r,o*r,a*r+1,0,n*e.d,o*e.d,a*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return B.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,s),s}static FromQuaternionToRef(e,t){const i=e._x*e._x,s=e._y*e._y,r=e._z*e._z,n=e._x*e._y,o=e._z*e._w,a=e._z*e._x,l=e._y*e._w,h=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(s+r),t._m[1]=2*(n+o),t._m[2]=2*(a-l),t._m[3]=0,t._m[4]=2*(n-o),t._m[5]=1-2*(r+i),t._m[6]=2*(h+c),t._m[7]=0,t._m[8]=2*(a+l),t._m[9]=2*(h-c),t._m[10]=1-2*(s+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}B._UpdateFlagSeed=0,B._IdentityReadOnly=B.Identity(),Object.defineProperties(B.prototype,{dimension:{value:[4,4]},rank:{value:2}});class V{}V.Vector3=S.BuildTuple(11,w.Zero),V.Matrix=S.BuildTuple(2,B.Identity),V.Quaternion=S.BuildTuple(3,L.Zero);class U{}U.Vector2=S.BuildTuple(3,N.Zero),U.Vector3=S.BuildTuple(13,w.Zero),U.Vector4=S.BuildTuple(3,F.Zero),U.Quaternion=S.BuildTuple(2,L.Zero),U.Matrix=S.BuildTuple(8,B.Identity),u("BABYLON.Vector2",N),u("BABYLON.Vector3",w),u("BABYLON.Vector4",F),u("BABYLON.Matrix",B);const k=B.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class G{static Sign(e){return 0==(e=+e)||isNaN(e)?e:e>0?1:-1}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(0===e)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e*=2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=G.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=G.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=G.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return s=Math.abs(t-e)<=i?t:e+G.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=G.DeltaAngle(e,t);let r=0;return-i180&&(s-=360),e+s*P(i)}static InverseLerp(e,t,i){let s=0;return s=e!=t?P((i-e)/(t-e)):0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n;return e*(2*o-3*n+1)+i*(-2*o+3*n)+t*(o-2*n+r)+s*(o-n)}static Hermite1stDerivative(e,t,i,s,r){const n=r*r;return 6*(n-r)*e+(3*n-4*r+1)*t+6*(-n+r)*i+(3*n-2*r)*s}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static HCF(e,t){const i=e%t;return 0===i?t:G.HCF(t,i)}}function z(e){return Math.pow(e,x)}function W(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function H(e){return Math.pow(e,v)}function X(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}G.TwoPi=2*Math.PI,G.WithinEpsilon=A,G.ToHex=D,G.Clamp=P,G.Lerp=I,G.RandomRange=R,G.NormalizeRadians=M;class Y{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return Y.FromArrayToRef(e,t,this),this}toColor4(e=1){return new j(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return.3*this.r+.59*this.g+.11*this.b}multiply(e){return new Y(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,i){return new Y(this.r*e,this.g*t,this.b*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=T){return G.WithinEpsilon(this.r,e.r,t)&&G.WithinEpsilon(this.g,e.g,t)&&G.WithinEpsilon(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new Y(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,i){return i.r=P(this.r,e,t),i.g=P(this.g,e,t),i.b=P(this.b,e,t),i}add(e){return new Y(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new Y(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,i){return new Y(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,s){return s.r=this.r-e,s.g=this.g-t,s.b=this.b-i,s}clone(){return new Y(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){const e=Math.round(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+D(e)+D(t)+D(i)}toHSV(){return this.toHSVToRef(new Y)}toHSVToRef(e){const t=this.r,i=this.g,s=this.b,r=Math.max(t,i,s),n=Math.min(t,i,s);let o=0,a=0;const l=r,h=r-n;return 0!==r&&(a=h/r),r!=n&&(r==t?(o=(i-s)/h,i=0&&n<=1?(a=r,l=o):n>=1&&n<=2?(a=o,l=r):n>=2&&n<=3?(l=r,h=o):n>=3&&n<=4?(l=o,h=r):n>=4&&n<=5?(a=o,h=r):n>=5&&n<=6&&(a=r,h=o);const c=i-r;return s.r=a+c,s.g=l+c,s.b=h+c,s}static FromHSV(e,t,i){const s=new Y(0,0,0);return Y.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new Y(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16);return Y.FromInts(t,i,s)}static FromArray(e,t=0){return new Y(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new Y(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new Y(0,0,0);return Y.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.r*a+i.r*l+t.r*h+s.r*c,d=e.g*a+i.g*l+t.g*h+s.g*c,p=e.b*a+i.b*l+t.b*h+s.b*c;return new Y(u,d,p)}static Hermite1stDerivative(e,t,i,s,r){const n=Y.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=6*(o-r)*e.r+(3*o-4*r+1)*t.r+6*(-o+r)*i.r+(3*o-2*r)*s.r,n.g=6*(o-r)*e.g+(3*o-4*r+1)*t.g+6*(-o+r)*i.g+(3*o-2*r)*s.g,n.b=6*(o-r)*e.b+(3*o-4*r+1)*t.b+6*(-o+r)*i.b+(3*o-2*r)*s.b}static Red(){return new Y(1,0,0)}static Green(){return new Y(0,1,0)}static Blue(){return new Y(0,0,1)}static Black(){return new Y(0,0,0)}static get BlackReadOnly(){return Y._BlackReadOnly}static White(){return new Y(1,1,1)}static Purple(){return new Y(.5,0,.5)}static Magenta(){return new Y(1,0,1)}static Yellow(){return new Y(1,1,0)}static Gray(){return new Y(.5,.5,.5)}static Teal(){return new Y(0,1,1)}static Random(){return new Y(Math.random(),Math.random(),Math.random())}}Y._BlackReadOnly=Y.Black(),Object.defineProperties(Y.prototype,{dimension:{value:[3]},rank:{value:1}});class j{constructor(e=0,t=0,i=0,s=1){this.r=e,this.g=t,this.b=i,this.a=s}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new j(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,s){return this.r+=e,this.g+=t,this.b+=i,this.a+=s,this}subtract(e){return new j(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,s){return new j(this.r-e,this.g-t,this.b-i,this.a-s)}subtractFromFloatsToRef(e,t,i,s,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r.a=this.a-s,r}scale(e){return new j(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,i){return i.r=P(this.r,e,t),i.g=P(this.g,e,t),i.b=P(this.b,e,t),i.a=P(this.a,e,t),i}multiply(e){return new j(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,s){return new j(this.r*e,this.g*t,this.b*i,this.a*s)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,s){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(s,this.a),this}maximizeInPlaceFromFloats(e,t,i,s){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(s,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=T){return G.WithinEpsilon(this.r,e.r,t)&&G.WithinEpsilon(this.g,e.g,t)&&G.WithinEpsilon(this.b,e.b,t)&&G.WithinEpsilon(this.a,e.a,t)}equalsToFloats(e,t,i,s){return this.r===e&&this.g===t&&this.b===i&&this.a===s}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e=397*e^255*this.a,e}clone(){return(new j).copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,s){return this.r=e,this.g=t,this.b=i,this.a=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+D(t)+D(i)+D(s);const r=Math.round(255*this.a);return"#"+D(t)+D(i)+D(s)+D(r)}toLinearSpace(e=!1){const t=new j;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=W(this.r),e.g=W(this.g),e.b=W(this.b)):(e.r=z(this.r),e.g=z(this.g),e.b=z(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new j;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=X(this.r),e.g=X(this.g),e.b=X(this.b)):(e.r=H(this.r),e.g=H(this.g),e.b=H(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new j(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16),r=9===e.length?parseInt(e.substring(7,9),16):255;return j.FromInts(t,i,s,r)}static Lerp(e,t,i){return j.LerpToRef(e,t,i,new j)}static LerpToRef(e,t,i,s){return s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i,s.a=e.a+(t.a-e.a)*i,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.r*a+i.r*l+t.r*h+s.r*c,d=e.g*a+i.g*l+t.g*h+s.g*c,p=e.b*a+i.b*l+t.b*h+s.b*c,f=e.a*a+i.a*l+t.a*h+s.a*c;return new j(u,d,p,f)}static Hermite1stDerivative(e,t,i,s,r){const n=new j;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=6*(o-r)*e.r+(3*o-4*r+1)*t.r+6*(-o+r)*i.r+(3*o-2*r)*s.r,n.g=6*(o-r)*e.g+(3*o-4*r+1)*t.g+6*(-o+r)*i.g+(3*o-2*r)*s.g,n.b=6*(o-r)*e.b+(3*o-4*r+1)*t.b+6*(-o+r)*i.b+(3*o-2*r)*s.b,n.a=6*(o-r)*e.a+(3*o-4*r+1)*t.a+6*(-o+r)*i.a+(3*o-2*r)*s.a}static FromColor3(e,t=1){return new j(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new j(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,s){return new j(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;inew j(0,0,0,0))),u("BABYLON.Color3",Y),u("BABYLON.Color4",j);class K{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new g,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}_prepare(){}getTriggerParameter(){return this._triggerParameter}setTriggerParameter(e){this._triggerParameter=e}_evaluateConditionForCurrentFrame(){const e=this._condition;if(!e)return!0;const t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){this._evaluateConditionForCurrentFrame()&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())}execute(e){}skipToNextActiveAction(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this}then(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(e){return null}_serialize(e,t){const i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){const e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}}K._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof N?e.x+", "+e.y:e instanceof w?e.x+", "+e.y+", "+e.z:e instanceof Y?e.r+", "+e.g+", "+e.b:e instanceof j?e.r+", "+e.g+", "+e.b+", "+e.a:e,K._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),u("BABYLON.Action",K);class q{constructor(e,t,i,s,r,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=s,this.sourceEvent=r,this.additionalData=n}static CreateNew(e,t,i){const s=e.getScene();return new q(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new q(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new q(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new q(e,t.x,t.y,null,i,s)}}class Q{constructor(e){this._actionManager=e}isValid(){return!0}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(){}_serialize(e){return{type:2,children:[],name:e.name,properties:e.properties}}}class Z extends Q{static get IsEqual(){return Z._IsEqual}static get IsDifferent(){return Z._IsDifferent}static get IsGreater(){return Z._IsGreater}static get IsLesser(){return Z._IsLesser}constructor(e,t,i,s,r=Z.IsEqual){super(e),this.propertyPath=i,this.value=s,this.operator=r,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case Z.IsGreater:return this._effectiveTarget[this._property]>this.value;case Z.IsLesser:return this._effectiveTarget[this._property]e<10?"0"+e:""+e,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){const s=Array.isArray(t)?t[0]:t;if(void 0!==i&&!J._CheckLimit(s,i))return;const r=J._FormatMessage(s),n=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];n.logFunc&&n.logFunc("BJS - "+r,...o);const a=`
${r}

`;J._AddLogEntry(a),J._GenerateLimitMessage(s,e)}static get LogCache(){return J._LogCache}static ClearLogCache(){J._LogCache="",J._LogLimitOutputs={},J.errorsCount=0}static set LogLevels(e){J.Log=J._LogDisabled,J.Warn=J._LogDisabled,J.Error=J._LogDisabled,[J.MessageLogLevel,J.WarningLogLevel,J.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];J[e.name]=J._LogEnabled.bind(J,t)}}))}}J.NoneLogLevel=0,J.MessageLogLevel=1,J.WarningLogLevel=2,J.ErrorLogLevel=4,J.AllLogLevel=7,J.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",J._LogCache="",J._LogLimitOutputs={},J._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],J.errorsCount=0,J.Log=J._LogEnabled.bind(J,J.MessageLogLevel),J.Warn=J._LogEnabled.bind(J,J.WarningLogLevel),J.Error=J._LogEnabled.bind(J,J.ErrorLogLevel);class ee extends K{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class te extends K{constructor(e,t,i,s){super(e,s),this._target=t,this._parent=i}_prepare(){}execute(){if(this._target.parent===this._parent)return;const e=this._parent.getWorldMatrix().clone();e.invert(),this._target.position=w.TransformCoordinates(this._target.position,e),this._target.parent=this._parent}serialize(e){return super._serialize({name:"SetParentAction",properties:[K._GetTargetProperty(this._target),K._GetTargetProperty(this._parent)]},e)}}u("BABYLON.SetParentAction",te),u("BABYLON.ExecuteCodeAction",class extends K{constructor(e,t,i){super(e,i),this.func=t}execute(e){this.func(e)}}),u("BABYLON.DoNothingAction",ee),u("BABYLON.StopAnimationAction",class extends K{constructor(e,t,i){super(e,i),this._target=t}_prepare(){}execute(){this._actionManager.getScene().stopAnimation(this._target)}serialize(e){return super._serialize({name:"StopAnimationAction",properties:[K._GetTargetProperty(this._target)]},e)}}),u("BABYLON.PlayAnimationAction",class extends K{constructor(e,t,i,s,r,n){super(e,n),this.from=i,this.to=s,this.loop=r,this._target=t}_prepare(){}execute(){this._actionManager.getScene().beginAnimation(this._target,this.from,this.to,this.loop)}serialize(e){return super._serialize({name:"PlayAnimationAction",properties:[K._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:K._SerializeValueAsString(this.loop)||!1}]},e)}}),u("BABYLON.IncrementValueAction",class extends K{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&J.Warn("Warning: IncrementValueAction can only be used with number values")}execute(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"IncrementValueAction",properties:[K._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:K._SerializeValueAsString(this.value)}]},e)}}),u("BABYLON.SetValueAction",class extends K{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"SetValueAction",properties:[K._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:K._SerializeValueAsString(this.value)}]},e)}}),u("BABYLON.SetStateAction",class extends K{constructor(e,t,i,s){super(e,s),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[K._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}),u("BABYLON.SetParentAction",te),u("BABYLON.SwitchBooleanAction",class extends K{constructor(e,t,i,s){super(e,s),this.propertyPath=i,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]}serialize(e){return super._serialize({name:"SwitchBooleanAction",properties:[K._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}),u("BABYLON.CombineAction",class extends K{constructor(e,t,i,s=!0){super(e,i),this.children=t,this.enableChildrenConditions=s}_prepare(){for(let e=0;ee?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?{...e}:null:e.clone(t):null;class se{static DeepCopy(e,t,i,s,r=!1){const n=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const o of n){if("_"===o[0]&&(!s||-1===s.indexOf(o)))continue;if(o.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(o))continue;const n=e[o],a=typeof n;if("function"!==a)try{if("object"===a)if(n instanceof Uint8Array)t[o]=Uint8Array.from(n);else if(n instanceof Array){if(t[o]=[],n.length>0)if("object"==typeof n[0])for(let e=0;e-1&&this._scene.actionManagers.splice(e,1);const t=this._scene.meshes.filter((e=>e.actionManager===this));for(const e of t)e.actionManager=null}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=re.OnPickTrigger&&t.trigger<=re.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=re.OnPickTrigger&&t.trigger<=re.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===re.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(J.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,re.Triggers[e.trigger]?re.Triggers[e.trigger]++:re.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){const t=this.actions.indexOf(e);return-1!==t&&(this.actions.splice(t,1),re.Triggers[e.trigger]-=1,0===re.Triggers[e.trigger]&&delete re.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i{if(null===s){const e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}const r=s.split("."),n=t.split(",");for(let e=0;e{if(e.detached)return;const h=[];let c=null,u=null;const p=e.combine&&e.combine.length>0;if(2===e.type?h.push(s):h.push(t),p){const t=[];for(let i=0;i{const i=d("BABYLON."+e);return i&&new i(...t)})(e.name,h);if(f instanceof Q&&null!==o){const e=new ee(t,o);a?a.then(e):s.registerAction(e),a=e}null===l?f instanceof Q?(o=f,f=a):(o=null,a?a.then(f):s.registerAction(f)):l.push(f);for(let i=0;i0){const e=r.properties[0].value,t=null===r.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),s={trigger:re[r.name],parameter:t}}else s=re[r.name];for(let e=0;e=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o}Object.create,Object.create;const le={},he={};function ce(e){const t=e.getClassName();if(le[t])return le[t];le[t]={};const i=le[t];let s=e,r=t;for(;r;){const e=he[r];for(const t in e)i[t]=e[t];let t,n=!1;do{if(t=Object.getPrototypeOf(s),!t.getClassName){n=!0;break}if(t.getClassName()!==r)break;s=t}while(t);if(n)break;r=t.getClassName(),s=t}return i}function ue(e,t){return(i,s)=>{const r=function(e){const t=e.getClassName();return he[t]||(he[t]={}),he[t]}(i);r[s]||(r[s]={type:e,sourceName:t})}}function de(e,t=null){return function(e,t=null){return(i,s)=>{const r=t||"_"+s;Object.defineProperty(i,s,{get:function(){return this[r]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[r]!==t&&(this[r]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function pe(e){return ue(0,e)}function fe(e){return ue(1,e)}function _e(e){return ue(2,e)}function me(e){return ue(3,e)}function ge(e){return ue(4,e)}function ve(e){return ue(5,e)}function xe(e){return ue(6,e)}function Te(e){return ue(8,e)}function Se(e){return ue(9,e)}function Ee(e){return ue(12,e)}function be(e,t,i,s){const r=i.value;i.value=(...i)=>{let n=r;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];n=s?(...t)=>s(...t)?e(...t):r(...t):e}return e[t]=n,n(...i)}}be.filter=function(e){return(t,i,s)=>be(t,i,s,e)};const Ce={};function ye(e,t=!1){if(!t||!Ce[e])return Ce[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}class Ae{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),Ae._HandleParenthesisContent(e,t)))):Ae._HandleParenthesisContent(e,t))||"false"!==e&&Ae.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const s=e.split("||");for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){let r=Ae._SimplifyNegation(s[e].trim());const n=r.split("&&");if(n.length>1)for(let e=0;e(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}class Re{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>Re.HasTags(e),e.addTags=t=>Re.AddTagsTo(e,t),e.removeTags=t=>Re.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>Re.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;const t=e._tags;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const t=[];for(const i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}return e._tags}static AddTagsTo(e,t){t&&"string"==typeof t&&t.split(" ").forEach((function(t){Re._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(Re.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!Re.HasTags(e))return;const i=t.split(" ");for(const t in i)Re._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?Re.HasTags(e):Ae.Eval(t,(t=>Re.HasTags(e)&&e._tags[t])))}}const Ie=function(e,t,i,s={}){const r=e();Re&&Re.HasTags(t)&&Re.AddTagsTo(r,Re.GetTags(t,!0));const n=ce(r),o={};for(const e in n){const a=n[e],l=t[e],h=a.type;if(null!=l&&("uniqueId"!==e||Pe.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:r[e]=l;break;case 1:s.cloneTexturesOnlyOnce&&o[l.uniqueId]?r[e]=o[l.uniqueId]:(r[e]=i||l.isRenderTarget?l:l.clone(),o[l.uniqueId]=r[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:r[e]=i?l:l.clone()}}return r};class Pe{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw ye("ImageProcessingConfiguration")},Pe._FresnelParametersParser=e=>{throw ye("FresnelParameters")},Pe._ColorCurvesParser=e=>{throw ye("ColorCurves")},Pe._TextureParser=(e,t,i)=>{throw ye("Texture")};class Me{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new g,this._onClonedObservable=new g}}class De{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,s){const r=this._NodeConstructors[e];return r?r(t,i,s):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;const t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){const t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){-1===this._nodeDataStorage._sceneRootNodesIndex&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(-1!==this._nodeDataStorage._sceneRootNodesIndex){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null,i=!0){this._isDirty=!1,this._nodeDataStorage=new Me,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new g,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=B.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new g,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||y.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),i&&this._addToSceneRootNodes()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return-1!==this._behaviors.indexOf(e)||(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce((()=>{e.attach(this)})):e.attach(this),this._behaviors.push(e)),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),this}get behaviors(){return this._behaviors}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={}}updateCache(e){!e&&this.isSynchronized()||this._updateCache()}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return!this._parentNode||!this._parentNode._isDirty&&this._parentUpdateId===this._parentNode._childUpdateId&&this._parentNode.isSynchronized()}isSynchronized(){return!(this._parentNode&&!this.isSynchronizedWithParent())&&this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return!1===e?this._nodeDataStorage._isEnabled:!!this._nodeDataStorage._isEnabled&&this._nodeDataStorage._isParentEnabled}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),this._children&&this._children.forEach((e=>{e._syncParentEnabledState()}))}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return!!this.parent&&(this.parent===e||this.parent.isDescendantOf(e))}_getDescendants(e,t=!1,i){if(this._children)for(let s=0;s(!t||t(e))&&void 0!==e.cullingStrategy)),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)}getAnimationByName(e){for(let t=0;tnew De(e,this.getScene())),this);if(t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i{throw ye("AnimationRange")},De._NodeConstructors={},ae([pe()],De.prototype,"name",void 0),ae([pe()],De.prototype,"id",void 0),ae([pe()],De.prototype,"uniqueId",void 0),ae([pe()],De.prototype,"state",void 0),ae([pe()],De.prototype,"metadata",void 0);class Oe{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=0|this.width;return e=397*e^this.height,e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new Oe(this.width*e,this.height*t)}clone(){return new Oe(this.width,this.height)}equals(e){return!!e&&this.width===e.width&&this.height===e.height}get surface(){return this.width*this.height}static Zero(){return new Oe(0,0)}add(e){return new Oe(this.width+e.width,this.height+e.height)}subtract(e){return new Oe(this.width-e.width,this.height-e.height)}scale(e){return new Oe(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,r=e.height+(t.height-e.height)*i;return new Oe(s,r)}}class Ne{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(Ne.CustomRequestHeaders).length>0||Ne.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in Ne.CustomRequestHeaders){const t=Ne.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return Ne.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){Ne.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const e of Ne.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}t=(t=t.replace("file:http:","http:")).replace("file:https:","https:"),this._requestURL=t,this._xhr.open(e,t,!0)}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}Ne.CustomRequestHeaders={},Ne.CustomRequestModifiers=new Array,Ne.SkipRequestModificationForBabylonCDN=!0;const we=Object.freeze(new L(0,0,0,0)),Fe=Object.freeze(w.Zero()),Le=Object.freeze(N.Zero()),Be=Object.freeze(Oe.Zero()),Ve=Object.freeze(Y.Black()),Ue=Object.freeze(new j(0,0,0,0)),ke={key:0,repeatCount:0,loopMode:2};class Ge{static _PrepareAnimation(e,t,i,s,r,n,o,a){let l;if(!isNaN(parseFloat(r))&&isFinite(r)?l=Ge.ANIMATIONTYPE_FLOAT:r instanceof L?l=Ge.ANIMATIONTYPE_QUATERNION:r instanceof w?l=Ge.ANIMATIONTYPE_VECTOR3:r instanceof N?l=Ge.ANIMATIONTYPE_VECTOR2:r instanceof Y?l=Ge.ANIMATIONTYPE_COLOR3:r instanceof j?l=Ge.ANIMATIONTYPE_COLOR4:r instanceof Oe&&(l=Ge.ANIMATIONTYPE_SIZE),null==l)return null;const h=new Ge(e,t,i,l,o),c=[{frame:0,value:r},{frame:s,value:n}];return h.setKeys(c),void 0!==a&&h.setEasingFunction(a),h}static CreateAnimation(e,t,i,s){const r=new Ge(e+"Animation",e,i,t,Ge.ANIMATIONLOOPMODE_CONSTANT);return r.setEasingFunction(s),r}static CreateAndStartAnimation(e,t,i,s,r,n,o,a,l,h,c){const u=Ge._PrepareAnimation(e,i,s,r,n,o,a,l);return u?(t.getScene&&(c=t.getScene()),c?c.beginDirectAnimation(t,[u],0,r,1===u.loopMode,1,h):null):null}static CreateAndStartHierarchyAnimation(e,t,i,s,r,n,o,a,l,h,c){const u=Ge._PrepareAnimation(e,s,r,n,o,a,l,h);return u?t.getScene().beginDirectHierarchyAnimation(t,i,[u],0,n,1===u.loopMode,1,c):null}static CreateMergeAndStartAnimation(e,t,i,s,r,n,o,a,l,h){const c=Ge._PrepareAnimation(e,i,s,r,n,o,a,l);return c?(t.animations.push(c),t.getScene().beginAnimation(t,0,r,1===c.loopMode,1,h)):null}static MakeAnimationAdditive(e,t,i,s=!1,r){let n;n="object"==typeof t?t:{referenceFrame:t??0,range:i,cloneOriginalAnimation:s,clonedAnimationName:r};let o=e;if(n.cloneOriginalAnimation&&(o=e.clone(),o.name=n.clonedAnimationName||o.name),!o._keys.length)return o;const a=n.referenceFrame&&n.referenceFrame>=0?n.referenceFrame:0;let l=0;const h=o._keys[0];let c=o._keys.length-1;const u=o._keys[c],d={referenceValue:h.value,referencePosition:U.Vector3[0],referenceQuaternion:U.Quaternion[0],referenceScaling:U.Vector3[1],keyPosition:U.Vector3[2],keyQuaternion:U.Quaternion[1],keyScaling:U.Vector3[3]};let p=h.frame,f=u.frame;if(n.range){const e=o.getRange(n.range);e&&(p=e.from,f=e.to)}else p=n.fromFrame??p,f=n.toFrame??f;if(p!==h.frame&&(l=o.createKeyForFrame(p)),f!==u.frame&&(c=o.createKeyForFrame(f)),1===o._keys.length){const e=o._getKeyValue(o._keys[0]);d.referenceValue=e.clone?e.clone():e}else if(a<=h.frame){const e=o._getKeyValue(h.value);d.referenceValue=e.clone?e.clone():e}else if(a>=u.frame){const e=o._getKeyValue(u.value);d.referenceValue=e.clone?e.clone():e}else{ke.key=0;const e=o._interpolate(a,ke);d.referenceValue=e.clone?e.clone():e}o.dataType===Ge.ANIMATIONTYPE_QUATERNION?d.referenceValue.normalize().conjugateInPlace():o.dataType===Ge.ANIMATIONTYPE_MATRIX&&(d.referenceValue.decompose(d.referenceScaling,d.referenceQuaternion,d.referencePosition),d.referenceQuaternion.normalize().conjugateInPlace());let _=Number.MAX_VALUE;const m=n.clipKeys?[]:null;for(let e=l;e<=c;e++){let t=o._keys[e];if((m||n.cloneOriginalAnimation)&&(t={frame:t.frame,value:t.value.clone?t.value.clone():t.value,inTangent:t.inTangent,outTangent:t.outTangent,interpolation:t.interpolation,lockedTangent:t.lockedTangent},m&&(_===Number.MAX_VALUE&&(_=t.frame),t.frame-=_,m.push(t))),!e||o.dataType===Ge.ANIMATIONTYPE_FLOAT||t.value!==h.value)switch(o.dataType){case Ge.ANIMATIONTYPE_MATRIX:t.value.decompose(d.keyScaling,d.keyQuaternion,d.keyPosition),d.keyPosition.subtractInPlace(d.referencePosition),d.keyScaling.divideInPlace(d.referenceScaling),d.referenceQuaternion.multiplyToRef(d.keyQuaternion,d.keyQuaternion),B.ComposeToRef(d.keyScaling,d.keyQuaternion,d.keyPosition,t.value);break;case Ge.ANIMATIONTYPE_QUATERNION:d.referenceValue.multiplyToRef(t.value,t.value);break;case Ge.ANIMATIONTYPE_VECTOR2:case Ge.ANIMATIONTYPE_VECTOR3:case Ge.ANIMATIONTYPE_COLOR3:case Ge.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(d.referenceValue,t.value);break;case Ge.ANIMATIONTYPE_SIZE:t.value.width-=d.referenceValue.width,t.value.height-=d.referenceValue.height;break;default:t.value-=d.referenceValue}}return m&&o.setKeys(m,!0),o}static TransitionTo(e,t,i,s,r,n,o,a=null){if(o<=0)return i[e]=t,a&&a(),null;const l=r*(o/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);const h=s.beginAnimation(i,0,l,!1);return h.onAnimationEnd=a,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,s,r,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=s,this.loopMode=r,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=s,this.loopMode=void 0===r?Ge.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=Ge._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort(((e,t)=>e.frame-t.frame))}removeEvents(e){for(let t=0;t=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const s=this._keys,r=s.length;let n=t.key;for(;n>=0&&e=s[n+1].frame;)++n;if(t.key=n,n<0)return i?void 0:this._getKeyValue(s[0].value);if(n+1>r-1)return i?void 0:this._getKeyValue(s[r-1].value);const o=s[n],a=s[n+1];if(i&&(e===o.frame||e===a.frame))return;const l=this._getKeyValue(o.value),h=this._getKeyValue(a.value);if(o.interpolation===ne.STEP)return a.frame>e?l:h;const c=void 0!==o.outTangent&&void 0!==a.inTangent,u=a.frame-o.frame;let d=(e-o.frame)/u;const p=o.easingFunction||this.getEasingFunction();switch(null!==p&&(d=p.ease(d)),this.dataType){case Ge.ANIMATIONTYPE_FLOAT:{const e=c?this.floatInterpolateFunctionWithTangents(l,o.outTangent*u,h,a.inTangent*u,d):this.floatInterpolateFunction(l,h,d);switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return e;case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+e}break}case Ge.ANIMATIONTYPE_QUATERNION:{const e=c?this.quaternionInterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.quaternionInterpolateFunction(l,h,d);switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return e;case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||we).scale(t.repeatCount))}return e}case Ge.ANIMATIONTYPE_VECTOR3:{const e=c?this.vector3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.vector3InterpolateFunction(l,h,d);switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return e;case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Fe).scale(t.repeatCount))}break}case Ge.ANIMATIONTYPE_VECTOR2:{const e=c?this.vector2InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.vector2InterpolateFunction(l,h,d);switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return e;case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Le).scale(t.repeatCount))}break}case Ge.ANIMATIONTYPE_SIZE:switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,h,d);case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(l,h,d).add((t.offsetValue||Be).scale(t.repeatCount))}break;case Ge.ANIMATIONTYPE_COLOR3:{const e=c?this.color3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.color3InterpolateFunction(l,h,d);switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return e;case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Ve).scale(t.repeatCount))}break}case Ge.ANIMATIONTYPE_COLOR4:{const e=c?this.color4InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.color4InterpolateFunction(l,h,d);switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return e;case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Ue).scale(t.repeatCount))}break}case Ge.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return Ge.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,h,d,t.workValue):l;case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return l}}return 0}matrixInterpolateFunction(e,t,i,s){return Ge.AllowMatrixDecomposeForInterpolation?s?(B.DecomposeLerpToRef(e,t,i,s),s):B.DecomposeLerp(e,t,i):s?(B.LerpToRef(e,t,i,s),s):B.Lerp(e,t,i)}clone(){const e=new Ge(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(const t in this._ranges){const i=this._ranges[t];i&&(e._ranges[t]=i.clone())}}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){ke.key=0;const t=this._interpolate(e,ke,!0);if(!t)return this._keys[ke.key].frame===e?ke.key:ke.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(ke.key+1,0,i),ke.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let s=0;s=2&&(o=t.values[1]),t.values.length>=3&&(a=t.values[2]),t.values.length>=4&&(l=t.values[3]);break;case Ge.ANIMATIONTYPE_QUATERNION:if(r=L.FromArray(t.values),t.values.length>=8){const e=L.FromArray(t.values.slice(4,8));e.equals(L.Zero())||(o=e)}if(t.values.length>=12){const e=L.FromArray(t.values.slice(8,12));e.equals(L.Zero())||(a=e)}t.values.length>=13&&(l=t.values[12]);break;case Ge.ANIMATIONTYPE_MATRIX:r=B.FromArray(t.values),t.values.length>=17&&(l=t.values[16]);break;case Ge.ANIMATIONTYPE_COLOR3:r=Y.FromArray(t.values),t.values[3]&&(o=Y.FromArray(t.values[3])),t.values[4]&&(a=Y.FromArray(t.values[4])),t.values[5]&&(l=t.values[5]);break;case Ge.ANIMATIONTYPE_COLOR4:r=j.FromArray(t.values),t.values[4]&&(o=j.FromArray(t.values[4])),t.values[5]&&(a=j.FromArray(t.values[5])),t.values[6]&&(l=j.FromArray(t.values[6]));break;case Ge.ANIMATIONTYPE_VECTOR3:default:r=w.FromArray(t.values),t.values[3]&&(o=w.FromArray(t.values[3])),t.values[4]&&(a=w.FromArray(t.values[4])),t.values[5]&&(l=t.values[5])}const h={};h.frame=t.frame,h.value=r,null!=o&&(h.inTangent=o),null!=a&&(h.outTangent=a),null!=l&&(h.interpolation=l),s.push(h)}if(t.setKeys(s),e.ranges)for(n=0;n{const r=new Ne;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){let t=JSON.parse(r.responseText);if(t.animations&&(t=t.animations),t.length){const e=[];for(const i of t)e.push(this.Parse(i));i(e)}else{const s=this.Parse(t);e&&(s.name=e),i(s)}}else s("Unable to load the animation")})),r.open("GET",t),r.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const s=new Ne;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){const i=JSON.parse(JSON.parse(s.responseText).jsonPayload);if(i.animations){const s=JSON.parse(i.animations),r=[];for(const t of s.animations){const i=this.Parse(t);i.snippetId=e,r.push(i)}t(r)}else{const s=JSON.parse(i.animation),r=this.Parse(s);r.snippetId=e,t(r)}}else i("Unable to load the snippet "+e)})),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()}))}}Ge._UniqueIdGenerator=0,Ge.AllowMatricesInterpolation=!1,Ge.AllowMatrixDecomposeForInterpolation=!0,Ge.SnippetUrl="https://snippet.babylonjs.com",Ge.ANIMATIONTYPE_FLOAT=0,Ge.ANIMATIONTYPE_VECTOR3=1,Ge.ANIMATIONTYPE_QUATERNION=2,Ge.ANIMATIONTYPE_MATRIX=3,Ge.ANIMATIONTYPE_COLOR3=4,Ge.ANIMATIONTYPE_COLOR4=7,Ge.ANIMATIONTYPE_VECTOR2=5,Ge.ANIMATIONTYPE_SIZE=6,Ge.ANIMATIONLOOPMODE_RELATIVE=0,Ge.ANIMATIONLOOPMODE_CYCLE=1,Ge.ANIMATIONLOOPMODE_CONSTANT=2,Ge.ANIMATIONLOOPMODE_YOYO=4,Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,Ge.CreateFromSnippetAsync=Ge.ParseFromSnippetAsync,u("BABYLON.Animation",Ge),De._AnimationRangeFactory=(e,t,i)=>new oe(e,t,i),u("BABYLON.InterpolateValueAction",class extends K{constructor(e,t,i,s,r=1e3,n,o,a){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new g,this.propertyPath=i,this.value=s,this.duration=r,this.stopOtherAnimations=o,this.onInterpolationDone=a,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){const e=this._actionManager.getScene(),t=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];let i;if("number"==typeof this.value)i=Ge.ANIMATIONTYPE_FLOAT;else if(this.value instanceof Y)i=Ge.ANIMATIONTYPE_COLOR3;else if(this.value instanceof w)i=Ge.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof B)i=Ge.ANIMATIONTYPE_MATRIX;else{if(!(this.value instanceof L))return void J.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");i=Ge.ANIMATIONTYPE_QUATERNION}const s=new Ge("InterpolateValueAction",this._property,1e3/this.duration*100,i,Ge.ANIMATIONLOOPMODE_CONSTANT);s.setKeys(t),this.stopOtherAnimations&&e.stopAnimation(this._effectiveTarget),e.beginDirectAnimation(this._effectiveTarget,[s],0,100,!1,1,(()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()}))}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[K._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:K._SerializeValueAsString(this.value)},{name:"duration",value:K._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:K._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}});class ze{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,i,s){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._yoyoDirection=1,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=s,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===Ge.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=B.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,0!==this._minFrame){const e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(const t of this._target)this._preparePath(t,e),this._getOriginalValues(e),e++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const r=t.getEvents();r&&r.length>0&&r.forEach((e=>{this._events.push(e._clone())})),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){const i=this._animation.targetPropertyPath;if(i.length>1){let s=e;for(let e=0;e-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray)for(let i=0;ii[i.length-1].frame&&(e=i[i.length-1].frame);const s=this._events;if(s.length)for(let t=0;tthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const h=i-t;let c,u=e*(o.framePerSecond*r)/1e3+this._absoluteFrameOffset,d=0,p=!1;const f=s&&this._animationState.loopMode===Ge.ANIMATIONLOOPMODE_YOYO;if(f){const e=(u-t)/h,i=Math.sin(e*Math.PI);u=Math.abs(i)*h+t;const s=i>=0?1:-1;this._yoyoDirection!==s&&(p=!0),this._yoyoDirection=s}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=u,!s&&i>=t&&(u>=h&&r>0||u<=0&&r<0))l=!1,d=o._getKeyValue(this._maxValue);else if(!s&&t>=i&&(u<=h&&r<0||u>=0&&r>0))l=!1,d=o._getKeyValue(this._minValue);else if(this._animationState.loopMode!==Ge.ANIMATIONLOOPMODE_CYCLE){const e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=Ge.ANIMATIONLOOPMODE_CYCLE;const s=o._interpolate(t,this._animationState),r=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case Ge.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=r-s;break;case Ge.ANIMATIONTYPE_QUATERNION:case Ge.ANIMATIONTYPE_VECTOR3:case Ge.ANIMATIONTYPE_VECTOR2:case Ge.ANIMATIONTYPE_SIZE:case Ge.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=r.subtract(s)}this._highLimitsCache[e]=r}d=this._highLimitsCache[e],c=this._offsetsCache[e]}if(void 0===c)switch(o.dataType){case Ge.ANIMATIONTYPE_FLOAT:c=0;break;case Ge.ANIMATIONTYPE_QUATERNION:c=we;break;case Ge.ANIMATIONTYPE_VECTOR3:c=Fe;break;case Ge.ANIMATIONTYPE_VECTOR2:c=Le;break;case Ge.ANIMATIONTYPE_SIZE:c=Be;break;case Ge.ANIMATIONTYPE_COLOR3:c=Ve;break;case Ge.ANIMATIONTYPE_COLOR4:c=Ue}let _;if(this._host&&this._host.syncRoot){const e=this._host.syncRoot;_=t+h*((e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame))}else _=u>0&&t>i||u<0&&t0&&this.currentFrame>_||r<0&&this.currentFrame<_)||f&&p){this._onLoop();for(let e=0;e0?0:o.getKeys().length-1}this._currentFrame=_,this._animationState.repeatCount=0===h?0:u/h|0,this._animationState.highLimitValue=d,this._animationState.offsetValue=c;const g=o._interpolate(_,this._animationState);if(this.setValue(g,n),m.length)for(let e=0;e=0&&_>=m[e].frame&&m[e].frame>=t||h<0&&_<=m[e].frame&&m[e].frame<=t){const t=m[e];t.isDone||(t.onlyOnce&&(m.splice(e,1),e--),t.isDone=!0,t.action(_))}return l||(this._stopped=!0),l}}function We(){return"undefined"!=typeof window}function He(){return"undefined"!=typeof navigator}function Xe(){return"undefined"!=typeof document}function Ye(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}class je{static get Now(){return We()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class $e{}$e.FilesToLoad={};class Ke extends Error{}Ke._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));const qe=3e3;class Qe extends Ke{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",Ke._setPrototypeOf(this,Qe.prototype)}}const Ze=e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,s,r,n,o,a,l,h="",c=0;const u=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c>2,o=(3&i)<<4|s>>4,a=(15&s)<<2|r>>6,l=63&r,isNaN(s)?a=l=64:isNaN(r)&&(l=64),h+=t.charAt(n)+t.charAt(o)+t.charAt(a)+t.charAt(l);return h},Je=e=>atob(e);class et{constructor(){this.children=[]}isValid(e){return!0}process(e,t){let i="";if(this.line){let s=this.line;const r=t.processor;if(r){r.lineProcessor&&(s=r.lineProcessor(s,t.isFragment,t.processingContext));const i=t.processor?.attributeKeywordName??"attribute",n=t.isFragment&&t.processor?.varyingFragmentKeywordName?t.processor?.varyingFragmentKeywordName:!t.isFragment&&t.processor?.varyingVertexKeywordName?t.processor?.varyingVertexKeywordName:"varying";!t.isFragment&&r.attributeProcessor&&this.line.startsWith(i)?s=r.attributeProcessor(this.line,e,t.processingContext):r.varyingProcessor&&(r.varyingCheck?.(this.line,t.isFragment)||!r.varyingCheck&&this.line.startsWith(n))?s=r.varyingProcessor(this.line,t.isFragment,e,t.processingContext):r.uniformProcessor&&r.uniformRegexp&&r.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(s=r.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):r.uniformBufferProcessor&&r.uniformBufferRegexp&&r.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(s=r.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):r.textureProcessor&&r.textureRegexp&&r.textureRegexp.test(this.line)?s=r.textureProcessor(this.line,t.isFragment,e,t.processingContext):(r.uniformProcessor||r.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?r.uniformProcessor&&(s=r.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):r.uniformBufferProcessor&&(s=r.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,r.endOfUniformBufferProcessor&&(s=r.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}i+=s+"\n"}return this.children.forEach((s=>{i+=s.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class tt{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(e);else{const e=t.split(";");for(let t=0;t{h=h.trim(),""!==h&&(i.push(h),h="")},n=e=>{srt._Stack[s],a=()=>-1===s?"!!INVALID EXPRESSION!!":rt._Stack[s--];let l=0,h="";for(;l1){for(r();-1!==s&&rt._OperatorPriority[o()]>=rt._OperatorPriority[c];)i.push(a());n(c),l++}else h+=t;l++}for(r();-1!==s;)"("===o()?a():i.push(a());return rt._InfixToPostfixCache.size>=rt.InfixToPostfixCacheLimitSize&&rt.ClearCache(),rt._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(rt._InfixToPostfixCache.entries()).sort(((e,t)=>e[1].accessTime-t[1].accessTime));for(let t=0;t":i=s>r;break;case"<":i=s=":i=s>=r;break;case"==":i=s===r;break;case"!=":i=s!==r}return i}}var ht,ct;(ct=ht||(ht={}))[ct.GLSL=0]="GLSL",ct[ct.WGSL=1]="WGSL";const ut={};function dt(e,t,i=""){return i+(t?t+"\n":"")+e}function pt(e,t,i,s,r,n,o){const a=o||ut.loadFile;if(a)return a(e,t,i,s,r,n);throw ye("FileTools")}function ft(e,t,i,s){if(e)return t?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,i?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(s?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return t&&(e+="#define IS_NDC_HALF_ZRANGE"),i&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),s&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}const _t=/defined\s*?\((.+?)\)/g,mt=/defined\s*?\[(.+?)\]/g,gt=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,vt=/__decl__/,xt=/light\{X\}.(\w*)/g,Tt=/\{X\}/g,St=[],Et=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function bt(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}function Ct(e,t,i,s){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),Ot(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const r=function(e,t,i){let s=function(e,t){if(t.processor?.noPrecision)return e;const i=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=i?"precision highp float;\n"+e:"precision mediump float;\n"+e:i||(e=e.replace("precision highp float","precision mediump float")),e}(e,t);if(!t.processor)return s;if(t.processor.shaderLanguage===ht.GLSL&&-1!==s.indexOf("#version 3")&&(s=s.replace("#version 300 es",""),!t.processor.parseGLES3))return s;const r=t.defines,n=Dt(t,i);return t.processor.preProcessor&&(s=t.processor.preProcessor(s,r,n,t.isFragment,t.processingContext)),s=Mt(s,n,t),t.processor.postProcessor&&(s=t.processor.postProcessor(s,r,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),i?._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}(e,t,s);i(r,e)}))}function yt(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}function At(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new nt(t[1].trim(),"!"===e[0]);const i=["==","!=",">=","<=","<",">"];let s="",r=0;for(s of i)if(r=e.indexOf(s),r>-1)break;if(-1===r)return new nt(e);const n=e.substring(0,r).trim(),o=e.substring(r+s.length).trim();return new lt(n,s,o)}function Rt(e,t){const i=new st,s=e.substring(0,t);let r=e.substring(t);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),i.testExpression="#ifdef"===s?new nt(r):"#ifndef"===s?new nt(r,!0):function(e){e=e.replace(_t,"defined[$1]");const t=rt.infixToPostfix(e),i=[];for(const e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],s=i[i.length-2];i.length-=2;const r="&&"==e?new at:new ot;"string"==typeof t&&(t=t.replace(mt,"defined($1)")),"string"==typeof s&&(s=s.replace(mt,"defined($1)")),r.leftOperand="string"==typeof s?At(s):s,r.rightOperand="string"==typeof t?At(t):t,i.push(r)}let s=i[i.length-1];return"string"==typeof s&&(s=s.replace(mt,"defined($1)")),"string"==typeof s?At(s):s}(r),i}function It(e,t,i){let s=e.currentLine;for(;Pt(e,i);){s=e.currentLine;const r=s.substring(0,5).toLowerCase();if("#else"===r){const i=new et;return t.children.push(i),void Pt(e,i)}if("#elif"===r){const e=Rt(s,5);t.children.push(e),i=e}}}function Pt(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const s=Et.exec(i);if(s&&s.length){switch(s[0]){case"#ifdef":{const s=new it;t.children.push(s);const r=Rt(i,6);s.children.push(r),It(e,s,r);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const s=new it;t.children.push(s);const r=Rt(i,7);s.children.push(r),It(e,s,r);break}case"#if":{const s=new it,r=Rt(i,3);t.children.push(s),s.children.push(r),It(e,s,r);break}}continue}}const s=new et;if(s.line=i,t.children.push(s),"#"===i[0]&&"d"===i[1]){const e=i.replace(";","").split(" ");s.additionalDefineKey=e[1],3===e.length&&(s.additionalDefineValue=e[2])}}return!1}function Mt(e,t,i){const s=new et,r=new tt;return r.lineIndex=-1,r.lines=e.split("\n"),Pt(r,s),s.process(t,i)}function Dt(e,t){const i=e.defines,s={};for(const e of i){const t=e.replace("#define","").replace(";","").trim().split(" ");s[t[0]]=t.length>1?t[1]:""}return e.processor?.shaderLanguage===ht.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",ft(s,t?.isNDCHalfZRange,t?.useReverseDepthBuffer,t?.useExactSrgbConversions),s}function Ot(e,t,i){let s;for(St.length=0;null!==(s=gt.exec(e));)St.push(s);let r=String(e),n=[e],o=!1;for(const e of St){let s=e[1];if(-1!==s.indexOf("__decl__")&&(s=s.replace(vt,""),t.supportsUniformBuffers&&(s=s.replace("Vertex","Ubo").replace("Fragment","Ubo")),s+="Declaration"),!t.includesShadersStore[s]){const e=t.shadersRepository+"ShadersInclude/"+s+".fx";return void Nt.loadFile(e,(e=>{t.includesShadersStore[s]=e,Ot(n.join(""),t,i)}))}{let i=t.includesShadersStore[s];if(e[2]){const t=e[3].split(",");for(let e=0;et+"{X}"))),i+=o.replace(Tt,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(xt,((e,t)=>t+"{X}"))),i=i.replace(Tt,s)}const r=[];for(const t of n){const s=t.split(e[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}}St.length=0,r=n.join(""),o?Ot(r.toString(),t,i):i(r)}const Nt={loadFile:(e,t,i,s,r,n)=>{throw ye("FileTools")}};class wt{static SetImmediate(e){We()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}class Ft{static GetShadersRepository(e=ht.GLSL){return e===ht.GLSL?Ft.ShadersRepository:Ft.ShadersRepositoryWGSL}static GetShadersStore(e=ht.GLSL){return e===ht.GLSL?Ft.ShadersStore:Ft.ShadersStoreWGSL}static GetIncludesShadersStore(e=ht.GLSL){return e===ht.GLSL?Ft.IncludesShadersStore:Ft.IncludesShadersStoreWGSL}}Ft.ShadersRepository="src/Shaders/",Ft.ShadersStore={},Ft.IncludesShadersStore={},Ft.ShadersRepositoryWGSL="src/ShadersWGSL/",Ft.ShadersStoreWGSL={},Ft.IncludesShadersStoreWGSL={};class Lt{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,i,s,r,n,o,a){const l=this.engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this.engine.getUniforms(this,i).forEach(((e,t)=>{s[i[t]]=e})),this._uniforms=s,h=0;h{n[e]=t}));for(const e of l.getAttributes(this,o))a.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s||2!==s.length)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r||3!==r.length)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}const Bt=new WeakMap,Vt={_webGLVersion:2,cachedPipelines:{}};function Ut(e){let t=Bt.get(e);if(!t){if(!e)return Vt;t={_webGLVersion:e.TEXTURE_BINDING_3D?2:1,_context:e,cachedPipelines:{}},Bt.set(e,t)}return t}function kt(e,t,i,s,r,n){const o=Ut(s);return n||(n=o._createShaderProgramInjection??zt),n(e,Xt(t,"vertex",s,o._contextWasLost),Xt(i,"fragment",s,o._contextWasLost),s,r,o.validateShaderPrograms)}function Gt(e,t,i,s,r,n=null,o){const a=Ut(r);o||(o=a._createShaderProgramInjection??zt);const l=a._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"";return o(e,Ht(t,"vertex",s,l,r,a._contextWasLost),Ht(i,"fragment",s,l,r,a._contextWasLost),r,n,a.validateShaderPrograms)}function zt(e,t,i,s,r=null,n){const o=s.createProgram();if(e.program=o,!o)throw new Error("Unable to create program");return s.attachShader(o,t),s.attachShader(o,i),s.linkProgram(o),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||Wt(e,s,n),o}function Wt(e,t,i){const s=e.context,r=e.vertexShader,n=e.fragmentShader,o=e.program;if(!s.getProgramParameter(o,s.LINK_STATUS)){if(!t.getShaderParameter(r,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(r);if(i)throw e.vertexCompilationError=i,new Error("VERTEX SHADER "+i)}if(!t.getShaderParameter(n,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(n);if(i)throw e.fragmentCompilationError=i,new Error("FRAGMENT SHADER "+i)}const i=s.getProgramInfoLog(o);if(i)throw e.programLinkError=i,new Error(i)}if(i&&(s.validateProgram(o),!s.getProgramParameter(o,s.VALIDATE_STATUS))){const t=s.getProgramInfoLog(o);if(t)throw e.programValidationError=t,new Error(t)}s.deleteShader(r),s.deleteShader(n),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}function Ht(e,t,i,s,r,n){return Xt(dt(e,i,s),t,r,n)}function Xt(e,t,i,s){const r=i.createShader("vertex"===t?i.VERTEX_SHADER:i.FRAGMENT_SHADER);if(!r){let e=i.NO_ERROR,r=i.NO_ERROR;for(;(r=i.getError())!==i.NO_ERROR;)e=r;throw new Error(`Something went wrong while creating a gl ${t} shader object. gl error=${e}, gl isContextLost=${i.isContextLost()}, _contextWasLost=${s}`)}return i.shaderSource(r,e),i.compileShader(r),r}function Yt(e){const t=e._name,i=e.context;if(t&&i){const e=Ut(i),s=e.cachedPipelines[t];s?.dispose(),delete e.cachedPipelines[t]}}function jt(e,t,i,s,r,n){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void s(Ye(e));if("source:"===e.substr(0,7))return void s(e.substr(7));if("base64:"===e.substr(0,7))return void s(window.atob(e.substr(7)));const o=Ft.GetShadersStore(r);if(o[e+t+"Shader"])return void s(o[e+t+"Shader"]);if(i&&o[e+i+"Shader"])return void s(o[e+i+"Shader"]);let a;if(a="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:Ft.GetShadersRepository(r)+e,!(n=n||pt))throw new Error("loadFileInjection is not defined");n(a+"."+t.toLowerCase()+".fx",s)}class $t{static get ShadersRepository(){return Ft.ShadersRepository}static set ShadersRepository(e){Ft.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new g),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,s=null,r,n=null,o=null,a=null,l=null,h,c="",u=ht.GLSL){this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new g,this.onErrorObservable=new g,this._onBindObservable=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=c;const d=this._key.replace(/\r/g,"").replace(/\n/g,"|");let p;if(t.attributes){const e=t;if(this._engine=i,this._attributesNames=e.attributes,this._uniformsNames=e.uniformsNames.concat(e.samplers),this._samplerList=e.samplers.slice(),this.defines=e.defines,this.onError=e.onError,this.onCompiled=e.onCompiled,this._fallbacks=e.fallbacks,this._indexParameters=e.indexParameters,this._transformFeedbackVaryings=e.transformFeedbackVaryings||null,this._multiTarget=!!e.multiTarget,this._shaderLanguage=e.shaderLanguage??ht.GLSL,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t{if(c[0]&&c[1]){e.isFragment=!0;const[a,l]=c;Ct(l,e,((n,l)=>{o&&(o._fragmentSourceCodeBeforeMigration=l),i&&(n=i("fragment",n));const h=yt(a,n,e);e=null;const c=function(e,t,i,s){if(i){const r=i.vertexElement||i.vertex||i.spectorName||i,n=i.fragmentElement||i.fragment||i.spectorName||i;return{vertexSourceCode:(s===ht.WGSL?"//":"")+"#define SHADER_NAME vertex:"+r+"\n"+e,fragmentSourceCode:(s===ht.WGSL?"//":"")+"#define SHADER_NAME fragment:"+n+"\n"+t}}return{vertexSourceCode:e,fragmentSourceCode:t}}(h.vertexCode,h.fragmentCode,t,r);s?.(c.vertexSourceCode,c.fragmentSourceCode)}),n)}};jt(a,"Vertex","",(t=>{bt(e),Ct(t,e,((e,s)=>{o&&(o._rawVertexSourceCode=t,o._vertexSourceCodeBeforeMigration=s),i&&(e=i("vertex",e)),c[0]=e,u()}),n)}),r),jt(l,"Fragment","Pixel",(e=>{o&&(o._rawFragmentSourceCode=e),c[1]=e,u()}),r)}({defines:this.defines.split("\n"),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:e??this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Ft.GetShadersRepository(this._shaderLanguage),includesShadersStore:Ft.GetIncludesShadersStore(this._shaderLanguage),version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:this._processCodeAfterIncludes},this.name,this._processFinalCode,((e,i)=>{this._vertexSourceCode=e,this._fragmentSourceCode=i,this._prepareEffect(t)}),this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getAttributesNames(){return this._attributesNames}getAttributeLocation(e){return this._attributes[e]}getAttributeLocationByName(e){return this._attributeLocationByName[e]}getAttributesCount(){return this._attributes.length}getUniformIndex(e){return this._uniformsNames.indexOf(e)}getUniform(e){return this._uniforms[e]}getSamplers(){return this._samplerList}getUniformNames(){return this._uniformsNames}getUniformBuffersNames(){return this._uniformBuffersNamesList}getIndexParameters(){return this._indexParameters}getCompilationError(){return this._compilationError}allFallbacksProcessed(){return this._allFallbacksProcessed}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}this._isDisposed||setTimeout((()=>{this._checkIsReady(e)}),16)}get vertexSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:this._pipelineContext?._getVertexShaderCode()??this._vertexSourceCode}get fragmentSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:this._pipelineContext?._getFragmentShaderCode()??this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}getPipelineGenerationOptions(){return{platformName:this._engine.shaderPlatformName,shaderLanguage:this._shaderLanguage,shaderNameOrContent:this.name,key:this._key,defines:this.defines.split("\n"),addGlobalDefines:!1,extendedProcessingOptions:{indexParameters:this._indexParameters,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,supportsUniformBuffers:this._engine.supportsUniformBuffers},extendedCreatePipelineOptions:{transformFeedbackVaryings:this._transformFeedbackVaryings,createAsRaw:!(!this._vertexSourceCodeOverride||!this._fragmentSourceCodeOverride)}}}_rebuildProgram(e,t,i,s){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{s&&s(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;t{try{const r=e.existingPipelineContext||t(e.shaderProcessingContext);return r._name=e.name,e.name&&e.context&&(Ut(e.context).cachedPipelines[e.name]=r),i(r,e.vertex,e.fragment,!!e.createAsRaw,"","",e.rebuildRebind,e.defines,e.transformFeedbackVaryings,""),s(r,(()=>{e.onRenderingStateCompiled?.(r)})),r}catch(e){throw J.Error("Error compiling effect"),e}})({existingPipelineContext:e?t:null,vertex:r,fragment:n,context:"WEBGL2"===o.shaderPlatformName?o._gl:void 0,rebuildRebind:(e,t,i,s)=>this._rebuildProgram(e,t,i,s),defines:s,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:i,parallelShaderCompile:o._caps.parallelShaderCompile,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:i=>{t&&!e&&this._engine._deletePipelineContext(t),i&&this._onRenderingStateCompiled(i)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContext.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t,i){const s=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let r=null;if(t&&e){const n=t.match(s);if(n&&2===n.length){const t=parseInt(n[1]),s=e.split("\n",-1);s.length>=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${s[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){this._compilationError=e.message;const i=this._attributesNames,s=this._fallbacks;if(J.Error("Unable to compile effect:"),J.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),J.Error("Attributes: "+i.map((function(e){return" "+e}))),J.Error("Defines:\n"+this.defines),$t.LogShaderCodeOnCompilationError){let e=null,t=null,i=null;this._pipelineContext?._getVertexShaderCode()&&([i,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),i&&(J.Error("Vertex code:"),J.Error(i))),this._pipelineContext?._getFragmentShaderCode()&&([i,t]=this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(),this._compilationError,!0),i&&(J.Error("Fragment code:"),J.Error(i))),e&&J.Error(e),t&&J.Error(t)}J.Error("Error: "+this._compilationError);const r=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,r()),s?(this._pipelineContext=null,s.hasMoreFallbacks?(this._allFallbacksProcessed=!1,J.Error("Trying next fallback."),this.defines=s.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,r(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||r())}get isSupported(){return""===this._compilationError}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){const s=this._samplerList.indexOf(e);for(let e=1;e{t._swapAndDie(this,!1),this.isReady=e.isReady};return void(e.isAsync?e.proxy.then(t):t(e.proxy))}let e;switch(this.source){case ei.Temp:break;case ei.Url:return void(e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,(e=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer));case ei.Raw:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case ei.Raw3D:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case ei.Raw2DArray:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case ei.Dynamic:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case ei.Cube:return void(e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,(()=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer));case ei.CubeRaw:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case ei.CubeRawRGBD:return;case ei.CubePrefiltered:return e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,(e=>{e&&e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension),void(e._sphericalPolynomial=this._sphericalPolynomial);case ei.DepthStencil:case ei.Depth:}}_swapAndDie(e,t=!0){this._hardwareTexture?.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const i=this._engine.getLoadedTexturesCache();let s=i.indexOf(this);-1!==s&&i.splice(s,1),s=i.indexOf(e),-1===s&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}function ii(e,t){if(We()){const{requestAnimationFrame:i}=t||window;if("function"==typeof i)return i(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}ti._Counter=0;class si{get frameId(){return this._frameId}get isWebGPU(){return this._isWebGPU}_getShaderProcessor(e){return this._shaderProcessor}get shaderPlatformName(){return this._shaderPlatformName}_clearEmptyResources(){this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,this._depthCullingState.depthFunc=e?518:515)}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}_getGlobalDefines(e){if(e)return this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return this.isNDCHalfZRange&&(e+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}_rebuildInternalTextures(){const e=this._internalTexturesCache.slice();for(const t of e)t._rebuild()}_rebuildRenderTargetWrappers(){const e=this._renderTargetWrapperCache.slice();for(const t of e)t._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}$t.ResetCache()}_rebuildGraphicsResources(){this.wipeCaches(!0),this._rebuildEffects(),this._rebuildComputeEffects?.(),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){J.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout((async()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=r,this._flagContextRestored()}),0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return 0}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){const e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get activeRenderLoops(){return this._activeRenderLoops}stopRenderLoop(e){if(!e)return this._activeRenderLoops.length=0,void this._cancelFrame();const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(0!==this._frameHandler){const e=this._frameHandler;if(this._frameHandler=0,We()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if("function"==typeof t)return t(e)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(e);return clearTimeout(e)}}beginFrame(){this.onBeginFrameObservable.notifyObservers(this)}endFrame(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e-1?e.substring(S).toLowerCase():""),b=null;E.indexOf("?")>-1&&(E=E.split("?")[0]);for(const e of si._TextureLoaders)if(e.canLoad(E,p)){b=e;break}s&&s.addPendingData(x),x.url=e,x.generateMipMaps=!t,x.samplingMode=r,x.invertY=i,x._useSRGBBuffer=this._getUseSRGBBuffer(!!_,t),this._doNotHandleContextLost||(x._buffer=h);let C=null;n&&!c&&(C=x.onLoadedObservable.add(n)),c||this._internalTexturesCache.push(x);const A=(i,c)=>{s&&s.removePendingData(x),e===T?(C&&x.onLoadedObservable.remove(C),y.UseFallbackTexture&&e!==y.FallbackTexture&&this._createTextureBase(y.FallbackTexture,t,x.invertY,s,r,null,o,a,l,h,x),i=(i||"Unknown error")+(y.UseFallbackTexture?" - Fallback texture was used":""),x.onErrorObservable.notifyObservers({message:i,exception:c}),o&&o(i,c)):(J.Warn(`Failed to load ${e}, falling back to ${T}`),this._createTextureBase(T,t,x.invertY,s,r,n,o,a,l,h,x,u,d,p,f,_))};if(b){const t=e=>{b.loadData(e,x,((e,t,i,n,o,l)=>{l?A("TextureLoader failed to load data"):a(x,E,s,{width:e,height:t},x.invertY,!i,n,(()=>(o(),!1)),r)}),f)};h?h instanceof ArrayBuffer?t(new Uint8Array(h)):ArrayBuffer.isView(h)?t(h):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,s?s.offlineProvider:void 0,!0,((e,t)=>{A("Unable to load "+(e&&e.responseURL,t))}))}else{const i=e=>{g&&!this._doNotHandleContextLost&&(x._buffer=e),a(x,E,s,e,x.invertY,t,!1,l,r)};!m||v?h&&("string"==typeof h.decoding||h.close)?i(h):si._FileToolsLoadImage(e||"",i,A,s?s.offlineProvider:null,p,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof h||h instanceof ArrayBuffer||ArrayBuffer.isView(h)||h instanceof Blob?si._FileToolsLoadImage(h,i,A,s?s.offlineProvider:null,p,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):h&&i(h)}return x}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuildAfterContextLost()}get _shouldUseHighPrecisionShader(){return!(!this._caps.highPrecisionShaderSupported||!this._highPrecisionShadersAllowed)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:Xe()?document:null}getLoadedTexturesCache(){return this._internalTexturesCache}clearInternalTexturesCache(){this._internalTexturesCache.length=0}getCaps(){return this._caps}resetTextureCache(){for(const e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}get name(){return this._name}set name(e){this._name=e}static get NpmPackage(){return"babylonjs@7.9.0"}static get Version(){return"7.9.0"}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get isStencilEnable(){return this._isStencilEnable}getCreationOptions(){return this._creationOptions}constructor(e,t,i){this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new Kt,this._stencilStateComposer=new qt,this._stencilState=new Qt,this._alphaState=new Zt,this._alphaMode=1,this._alphaEquation=0,this._activeRequests=[],this._badOS=!1,this._badDesktopOS=!1,this._compatibilityMode=!0,this._internalTexturesCache=new Array,this._currentRenderTarget=null,this._boundTexturesCache={},this._activeChannel=0,this._currentTextureChannel=-1,this._viewportCached={x:0,y:0,z:0,w:0},this._isWebGPU=!1,this.onCanvasBlurObservable=new g,this.onCanvasFocusObservable=new g,this.onNewSceneAddedObservable=new g,this.onResizeObservable=new g,this.onCanvasPointerOutObservable=new g,this.disablePerformanceMonitorInBackground=!1,this.disableVertexArrayObjects=!1,this._frameId=0,this.hostInformation={isMobile:!1},this.isFullscreen=!1,this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.currentRenderPassId=0,this.isPointerLock=!1,this.postProcesses=[],this.canvasTabIndex=1,this._contextWasLost=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this._renderTargetWrapperCache=new Array,this._compiledEffects={},this._isDisposed=!1,this.scenes=[],this._virtualScenes=new Array,this.onBeforeTextureInitObservable=new g,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new g,this.onAfterShaderCompilationObservable=new g,this.onBeginFrameObservable=new g,this.onEndFrameObservable=new g,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new g,this.onContextRestoredObservable=new g,this._name="",this.premultipliedAlpha=!0,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._doNotHandleContextLost=!1,this.cullBackFaces=null,this._renderPassNames=["main"],this._fps=60,this._deltaTime=0,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this.onDisposeObservable=new g,y.Instances.push(this),this.startTime=je.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,C.SetMatrixPrecision(!!t.useHighPrecisionMatrix),He()&&navigator.userAgent&&(this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),this.adaptToDeviceRatio=i??!1,t.antialias=e??t.antialias,t.deterministicLockstep=t.deterministicLockstep??!1,t.lockstepMaxSteps=t.lockstepMaxSteps??4,t.timeStep=t.timeStep??1/60,t.audioEngine=t.audioEngine??!0,t.stencil=t.stencil??!0,this._audioContext=t.audioEngineOptions?.audioContext??null,this._audioDestination=t.audioEngineOptions?.audioDestination??null,this.premultipliedAlpha=t.premultipliedAlpha??!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=t.useExactSrgbConversions??!1;const s=We()&&window.devicePixelRatio||1,r=t.limitDeviceRatio||s;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(r,s):1,this._lastDevicePixelRatio=s,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const e=We()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if(We()&&Xe())if(this._renderingCanvas){const e=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||e.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||e.height||this._renderingCanvas.height||100}else t=window.innerWidth,i=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){if(!this._renderingCanvas)return!1;if(e|=0,t|=0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t)return!1;if(this._renderingCanvas.width=e,this._renderingCanvas.height=t,this.scenes){for(let e=0;e{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&Xe()&&"ontouchend"in document},this._checkForMobile(),We()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){this._drawCalls?.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}_createImageBitmapFromSource(e,t){throw new Error("createImageBitmapFromSource is not implemented")}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){throw new Error("resizeImageBitmap is not implemented")}getFontOffset(e){throw new Error("getFontOffset is not implemented")}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return si._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,s,r,n){throw ye("FileTools")}_loadFile(e,t,i,s,r,n){const o=pt(e,t,i,s,r,n);return this._activeRequests.push(o),o.onCompleteObservable.add((()=>{const e=this._activeRequests.indexOf(o);-1!==e&&this._activeRequests.splice(e,1)})),o}static _FileToolsLoadFile(e,t,i,s,r,n){if(ut.loadFile)return ut.loadFile(e,t,i,s,r,n);throw ye("FileTools")}dispose(){for(this.hideLoadingUI(),this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();this.releaseComputeEffects?.(),$t.ResetCache();for(const e of this._activeRequests)e.abort();this._boundRenderFunction=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onNewSceneAddedObservable.clear(),We()&&window.removeEventListener("resize",this._checkForMobile);const e=y.Instances.indexOf(this);e>=0&&y.Instances.splice(e,1),y.Instances.length||(y.OnEnginesDisposedObservable.notifyObservers(this),y.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw ye("LoadingScreen")}}si._TextureLoaders=[],si._RenderPassIdCounter=0,si._RescalePostProcessFactory=null;const ri=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class ni extends Qe{constructor(e,t){super(e,4e3),this.name="LoadFileError",Ke._setPrototypeOf(this,ni.prototype),t instanceof Ne?this.request=t:this.file=t}}class oi extends Qe{constructor(e,t){super(e,4001),this.request=t,this.name="RequestFileError",Ke._setPrototypeOf(this,oi.prototype)}}class ai extends Qe{constructor(e,t){super(e,4002),this.file=t,this.name="ReadFileError",Ke._setPrototypeOf(this,ai.prototype)}}const li={DefaultRetryStrategy:class{static ExponentialBackoff(e=3,t=500){return(i,s,r)=>0!==s.status||r>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,r)*t}}.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e,CleanUrl:e=>e.replace(/#/gm,"%23")},hi=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&li.CorsBehavior)if("string"==typeof li.CorsBehavior||li.CorsBehavior instanceof String)t.crossOrigin=li.CorsBehavior;else{const i=li.CorsBehavior(e);i&&(t.crossOrigin=i)}},ci=(e,t,i,s,r="",n)=>{const o=y.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!o?._features.forceBitmapOverHTMLImageElement)return i("LoadImage is only supported in web or BabylonNative environments."),null;let a,l=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(a=URL.createObjectURL(new Blob([e],{type:r})),l=!0):a=`data:${r};base64,`+Ze(e):e instanceof Blob?(a=URL.createObjectURL(e),l=!0):(a=li.CleanUrl(e),a=li.PreprocessUrl(e));const h=t=>{if(i){const s=a||e.toString();i(`Error while trying to load image: ${0===s.indexOf("http")||s.length<=128?s:s.slice(0,128)+"..."}`,t)}};if(o?._features.forceBitmapOverHTMLImageElement)return di(a,(s=>{o.createImageBitmap(new Blob([s],{type:r}),{premultiplyAlpha:"none",...n}).then((e=>{t(e),l&&URL.revokeObjectURL(a)})).catch((t=>{i&&i("Error while trying to load image: "+e,t)}))}),void 0,s||void 0,!0,((e,t)=>{h(t)})),null;const c=new Image;hi(a,c);const u=[],d=()=>{u.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),u.length=0};u.push({target:c,name:"load",handler:()=>{d(),t(c),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:c,name:"error",handler:e=>{d(),h(e),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==c.src)return;d();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);y.UseFallbackTexture=!1,h(t),l&&c.src&&URL.revokeObjectURL(c.src),c.src=""}}),u.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const p="blob:"===a.substring(0,5),f="data:"===a.substring(0,5),_=()=>{p||f||!Ne.IsCustomRequestAvailable?c.src=a:di(a,((e,t,i)=>{const s=new Blob([e],{type:!r&&i?i:r}),n=URL.createObjectURL(s);l=!0,c.src=n}),void 0,s||void 0,!0,((e,t)=>{h(t)}))};if(!p&&!f&&s&&s.enableTexturesOffline)s.open((()=>{s&&s.loadImage(a,c)}),_);else{if(-1!==a.indexOf("file:")){const e=decodeURIComponent(a.substring(5).toLowerCase());if($e.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL($e.FilesToLoad[e])}catch(i){t=URL.createObjectURL($e.FilesToLoad[e])}c.src=t,l=!0}catch(e){c.src=""}return c}}_()}return c},ui=(e,t,i,s,r)=>{const n=new FileReader,o={onCompleteObservable:new g,abort:()=>n.abort()};return n.onloadend=()=>o.onCompleteObservable.notifyObservers(o),r&&(n.onerror=()=>{r(new ai(`Unable to read ${e.name}`,e))}),n.onload=e=>{t(e.target.result)},i&&(n.onprogress=i),s?n.readAsArrayBuffer(e):n.readAsText(e),o},di=(e,t,i,s,r,n,o)=>{if(e.name)return ui(e,t,i,r,n?e=>{n(void 0,e)}:void 0);const a=e;if(-1!==a.indexOf("file:")){let e=decodeURIComponent(a.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const s=$e.FilesToLoad[e];if(s)return ui(s,t,i,r,n?e=>n(void 0,new ni(e.message,e.file)):void 0)}const{match:l,type:h}=mi(a);if(l){const e={onCompleteObservable:new g,abort:()=>()=>{}};try{const e=r?gi(a):vi(a);t(e,void 0,h)}catch(e){n?n(void 0,e):J.Error(e.message||"Failed to parse the Data URL")}return wt.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return pi(a,((e,i)=>{t(e,i?.responseURL,i?.getResponseHeader("content-type"))}),i,s,r,n?e=>{n(e.request,new ni(e.message,e.request))}:void 0,o)},pi=(e,t,i,s,r,n,o)=>{e=li.CleanUrl(e),e=li.PreprocessUrl(e);const a=li.BaseUrl+e;let l=!1;const h={onCompleteObservable:new g,abort:()=>l=!0},c=()=>{let e,s=new Ne,c=null;const u=()=>{s&&(i&&s.removeEventListener("progress",i),e&&s.removeEventListener("readystatechange",e),s.removeEventListener("loadend",d))};let d=()=>{u(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),i=void 0,e=null,d=null,n=void 0,o=void 0,t=void 0};h.abort=()=>{l=!0,d&&d(),s&&s.readyState!==(XMLHttpRequest.DONE||4)&&s.abort(),null!==c&&(clearTimeout(c),c=null),s=null};const p=e=>{const t=e.message||"Unknown error";n&&s?n(new oi(t,s)):J.Error(t)},f=h=>{if(s){if(s.open("GET",a),o)try{o(s)}catch(e){return void p(e)}r&&(s.responseType="arraybuffer"),i&&s.addEventListener("progress",i),d&&s.addEventListener("loadend",d),e=()=>{if(!l&&s&&s.readyState===(XMLHttpRequest.DONE||4)){if(e&&s.removeEventListener("readystatechange",e),s.status>=200&&s.status<300||0===s.status&&(!We()||fi())){try{t&&t(r?s.response:s.responseText,s)}catch(e){p(e)}return}const i=li.DefaultRetryStrategy;if(i){const e=i(a,s,h);if(-1!==e)return u(),s=new Ne,void(c=setTimeout((()=>f(h+1)),e))}const o=new oi("Error status: "+s.status+" "+s.statusText+" - Unable to load "+a,s);n&&n(o)}},s.addEventListener("readystatechange",e),s.send()}};f(0)};if(s&&s.enableSceneOffline){const o=e=>{e&&e.status>400?n&&n(e):c()},a=()=>{s&&s.loadFile(li.BaseUrl+e,(e=>{!l&&t&&t(e),h.onCompleteObservable.notifyObservers(h)}),i?e=>{!l&&i&&i(e)}:void 0,o,r)};s.open(a,o)}else c();return h},fi=()=>"undefined"!=typeof location&&"file:"===location.protocol,_i=e=>ri.test(e),mi=e=>{const t=ri.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function gi(e){return(e=>{const t=Je(e),i=t.length,s=new Uint8Array(new ArrayBuffer(i));for(let e=0;eJe(e.split(",")[1]);let xi;si._FileToolsLoadImage=ci,ut.loadFile=di,Nt.loadFile=di,((e,t,i,s,r,n,o,a,l,h)=>{xi={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:s,IsFileURL:r,LoadFile:n,LoadImage:o,ReadFile:a,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(xi,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(xi,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(xi,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(xi,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})})(gi,vi,li,_i,fi,di,ci,ui,pi,hi);class Ti{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=d(e);if(t)return t;J.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let e=0,t=i.length;e{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}function Ei(e){let t=1;do{t*=2}while(te-i?i:t}function yi(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}function Ai(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}function Ri(e,t,i=2){let s;switch(i){case 1:s=Ai(e);break;case 2:s=Ci(e);break;default:s=yi(e)}return Math.min(s,t)}Ti.RegisteredExternalClasses={};class Ii{static get BaseUrl(){return li.BaseUrl}static set BaseUrl(e){li.BaseUrl=e}static get CleanUrl(){return li.CleanUrl}static set CleanUrl(e){li.CleanUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||-1!==e.indexOf("://")&&-1!==e.indexOf(".")&&-1!==e.indexOf("/")&&!(e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://"){di(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{s(t)}))}))}static GetBabylonScriptURL(e,t){if(!e)return"";if(Ii.ScriptBaseUrl&&e.startsWith(Ii._DefaultCdnUrl)){const t="/"===Ii.ScriptBaseUrl[Ii.ScriptBaseUrl.length-1]?Ii.ScriptBaseUrl.substring(0,Ii.ScriptBaseUrl.length-1):Ii.ScriptBaseUrl;e=e.replace(Ii._DefaultCdnUrl,t)}return e=Ii.ScriptPreprocessUrl(e),t&&(e=Ii.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=Ii.GetBabylonScriptURL(e),Ii.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=Ii.GetBabylonScriptURL(e),Ii.LoadScriptAsync(e)}static LoadScript(e,t,i,s){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){i?.(`Unable to load script '${e}' in worker`,t)}return}if(!We())return void i?.(`Cannot load script '${e}' outside of a window or a worker`);const r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("src",e),s&&(n.id=s),n.onload=()=>{t&&t()},n.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},r.appendChild(n)}static LoadScriptAsync(e,t){return new Promise(((i,s)=>{this.LoadScript(e,(()=>{i()}),((e,t)=>{s(t||new Error(e))}),t)}))}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new g,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,s,r){return ui(e,t,i,s,r)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,s){se.DeepCopy(e,t,i,s)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{const s=atob(this.toDataURL(t,i).split(",")[1]),r=s.length,n=new Uint8Array(r);for(let e=0;et(e))):e.toBlob((function(e){t(e)}),i,s)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const e=new Date;t="screenshot_"+(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2)+".png"}Ii.Download(e,t)}else if(e&&"undefined"!=typeof URL){const t=URL.createObjectURL(e),i=window.open("");if(!i)return;const s=i.document.createElement("img");s.onload=function(){URL.revokeObjectURL(t)},s.src=t,i.document.body.appendChild(s)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,r){if("string"!=typeof s&&t){if(t){if(Ii._IsOffScreenCanvas(e))return void e.convertToBlob({type:i,quality:r}).then((e=>{const i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{const e=i.result;t(e)}}));const s=e.toDataURL(i,r);t(s)}}else this.ToBlob(e,(function(e){e&&Ii.DownloadBlob(e,s),t&&t("")}),i,r)}static Download(e,t){if("undefined"==typeof URL)return;const i=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.style.display="none",s.href=i,s.download=t,s.addEventListener("click",(()=>{s.parentElement&&s.parentElement.removeChild(s)})),s.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,s,r="image/png",n=!1,o){throw ye("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",r){throw ye("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,o=!1,a,l=!1,h=!1,c=!0,u){throw ye("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,o,a=!1,l=!1,h=!0,c){throw ye("ScreenshotTools")}static RandomId(){return Si()}static IsBase64(e){return _i(e)}static DecodeBase64(e){return gi(e)}static get errorsCount(){return J.errorsCount}static Log(e){J.Log(e)}static Warn(e){J.Warn(e)}static Error(e){J.Error(e)}static get LogCache(){return J.LogCache}static ClearLogCache(){J.ClearLogCache()}static set LogLevels(e){J.LogLevels=e}static set PerformanceLogLevel(e){return(e&Ii.PerformanceUserMarkLogLevel)===Ii.PerformanceUserMarkLogLevel?(Ii.StartPerformanceCounter=Ii._StartUserMark,void(Ii.EndPerformanceCounter=Ii._EndUserMark)):(e&Ii.PerformanceConsoleLogLevel)===Ii.PerformanceConsoleLogLevel?(Ii.StartPerformanceCounter=Ii._StartPerformanceConsole,void(Ii.EndPerformanceCounter=Ii._EndPerformanceConsole)):(Ii.StartPerformanceCounter=Ii._StartPerformanceCounterDisabled,void(Ii.EndPerformanceCounter=Ii._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Ii._Performance){if(!We())return;Ii._Performance=window.performance}t&&Ii._Performance.mark&&Ii._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&Ii._Performance.mark&&(Ii._Performance.mark(e+"-End"),Ii._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Ii._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Ii._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return je.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,s=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,s=r.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=s?s+".":"")+i:null}static DelayAsync(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}static IsSafari(){return!!He()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}Ii.UseCustomRequestHeaders=!1,Ii.CustomRequestHeaders=Ne.CustomRequestHeaders,Ii.GetDOMTextContent=Ye,Ii._DefaultCdnUrl="https://cdn.babylonjs.com",Ii.GetAbsoluteUrl="object"==typeof document?e=>{const t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},Ii.NoneLogLevel=J.NoneLogLevel,Ii.MessageLogLevel=J.MessageLogLevel,Ii.WarningLogLevel=J.WarningLogLevel,Ii.ErrorLogLevel=J.ErrorLogLevel,Ii.AllLogLevel=J.AllLogLevel,Ii.IsWindowObjectExist=We,Ii.PerformanceNoneLogLevel=0,Ii.PerformanceUserMarkLogLevel=1,Ii.PerformanceConsoleLogLevel=2,Ii.StartPerformanceCounter=Ii._StartPerformanceCounterDisabled,Ii.EndPerformanceCounter=Ii._EndPerformanceCounterDisabled;class Pi{constructor(e,t,i,s=0){this.iterations=e,this.index=s-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{r&&r()?s.breakLoop():setTimeout((()=>{for(let n=0;n=e)break;if(i(o),r&&r()){s.breakLoop();break}}s.executeNext()}),n)}),s)}}Ii.Mix=bi,Ii.IsExponentOfTwo=Ei,y.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";class Mi{constructor(e){this.length=0,this.data=new Array(e),this._id=Mi._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}Mi._GlobalId=0;class Di extends Mi{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return!(e.__smartArrayFlags&&e.__smartArrayFlags[this._id]===this._duplicateId||(this.push(e),0))}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;tthis.add(e,t)))}get(e){const t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let i=this.get(e);return void 0!==i||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return void 0!==i?i:(this.add(e,t),t)}contains(e){return void 0!==this._data[e]}add(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)}set(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null}remove(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data)e(t,this._data[t])}first(e){for(const t in this._data){const i=e(t,this._data[t]);if(i)return i}return null}}function Ni(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class wi{constructor(){this._dirty=!0,this._tempColor=new j(0,0,0,0),this._globalCurve=new j(0,0,0,0),this._highlightsCurve=new j(0,0,0,0),this._midtonesCurve=new j(0,0,0,0),this._shadowsCurve=new j(0,0,0,0),this._positiveCurve=new j(0,0,0,0),this._negativeCurve=new j(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",s="vCameraColorCurveNeutral",r="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(s,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(r,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,s,r){null!=e&&(e=wi._Clamp(e,0,360),t=wi._Clamp(t,-100,100),i=wi._Clamp(i,-100,100),s=wi._Clamp(s,-100,100),t=wi._ApplyColorGradingSliderNonlinear(t),t*=.5,s=wi._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),wi._FromHSBToRef(e,t,50+.25*s,r),r.scaleToRef(2,r),r.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,s){let r=wi._Clamp(e,0,360);const n=wi._Clamp(t/100,0,1),o=wi._Clamp(i/100,0,1);if(0===n)s.r=o,s.g=o,s.b=o;else{r/=60;const e=Math.floor(r),t=r-e,i=o*(1-n),a=o*(1-n*t),l=o*(1-n*(1-t));switch(e){case 0:s.r=o,s.g=l,s.b=i;break;case 1:s.r=a,s.g=o,s.b=i;break;case 2:s.r=i,s.g=o,s.b=l;break;case 3:s.r=i,s.g=a,s.b=o;break;case 4:s.r=l,s.g=i,s.b=o;break;default:s.r=o,s.g=i,s.b=a}}s.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return Pe.Clone((()=>new wi),this)}serialize(){return Pe.Serialize(this)}static Parse(e){return Pe.Parse((()=>new wi),e,null,null)}}function Fi(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&Ni(e),t.DITHER&&e.push("ditherIntensity")}function Li(e,t){t.COLORGRADING&&e.push("txColorTransform")}wi.PrepareUniforms=Ni,ae([pe()],wi.prototype,"_globalHue",void 0),ae([pe()],wi.prototype,"_globalDensity",void 0),ae([pe()],wi.prototype,"_globalSaturation",void 0),ae([pe()],wi.prototype,"_globalExposure",void 0),ae([pe()],wi.prototype,"_highlightsHue",void 0),ae([pe()],wi.prototype,"_highlightsDensity",void 0),ae([pe()],wi.prototype,"_highlightsSaturation",void 0),ae([pe()],wi.prototype,"_highlightsExposure",void 0),ae([pe()],wi.prototype,"_midtonesHue",void 0),ae([pe()],wi.prototype,"_midtonesDensity",void 0),ae([pe()],wi.prototype,"_midtonesSaturation",void 0),ae([pe()],wi.prototype,"_midtonesExposure",void 0),Pe._ColorCurvesParser=wi.Parse;class Bi{constructor(){this.colorCurves=new wi,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=Bi.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new j(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=Bi.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new g}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled)return e.VIGNETTE=!1,e.TONEMAPPING=0,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,void(e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===Bi._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,this._toneMappingEnabled)switch(this._toneMappingType){case Bi.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case Bi.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1}else e.TONEMAPPING=0;e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||!!e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&wi.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),s=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,s),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=null!=t?t:s/i;let n=Math.tan(.5*this.vignetteCameraFov),o=n*r;const a=Math.sqrt(o*n);o=bi(o,a,this.vignetteStretch),n=bi(n,a,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,n,-o*this.vignetteCenterX,-n*this.vignetteCenterY);const l=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,l)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return Pe.Clone((()=>new Bi),this)}serialize(){return Pe.Serialize(this)}static Parse(e){const t=Pe.Parse((()=>new Bi),e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}function Vi(e){return void 0===e.getPipelineContext}Bi.TONEMAPPING_STANDARD=0,Bi.TONEMAPPING_ACES=1,Bi.TONEMAPPING_KHR_PBR_NEUTRAL=2,Bi.PrepareUniforms=Fi,Bi.PrepareSamplers=Li,Bi._VIGNETTEMODE_MULTIPLY=0,Bi._VIGNETTEMODE_OPAQUE=1,ae([ue(7,undefined)],Bi.prototype,"colorCurves",void 0),ae([pe()],Bi.prototype,"_colorCurvesEnabled",void 0),ae([fe("colorGradingTexture")],Bi.prototype,"_colorGradingTexture",void 0),ae([pe()],Bi.prototype,"_colorGradingEnabled",void 0),ae([pe()],Bi.prototype,"_colorGradingWithGreenDepth",void 0),ae([pe()],Bi.prototype,"_colorGradingBGR",void 0),ae([pe()],Bi.prototype,"_exposure",void 0),ae([pe()],Bi.prototype,"_toneMappingEnabled",void 0),ae([pe()],Bi.prototype,"_toneMappingType",void 0),ae([pe()],Bi.prototype,"_contrast",void 0),ae([pe()],Bi.prototype,"vignetteStretch",void 0),ae([pe()],Bi.prototype,"vignetteCenterX",void 0),ae([pe()],Bi.prototype,"vignetteCenterY",void 0),ae([pe()],Bi.prototype,"vignetteWeight",void 0),ae([Te()],Bi.prototype,"vignetteColor",void 0),ae([pe()],Bi.prototype,"vignetteCameraFov",void 0),ae([pe()],Bi.prototype,"_vignetteBlendMode",void 0),ae([pe()],Bi.prototype,"_vignetteEnabled",void 0),ae([pe()],Bi.prototype,"_ditheringEnabled",void 0),ae([pe()],Bi.prototype,"_ditheringIntensity",void 0),ae([pe()],Bi.prototype,"_skipFinalColorClamp",void 0),ae([pe()],Bi.prototype,"_applyByPostProcess",void 0),ae([pe()],Bi.prototype,"_isEnabled",void 0),Pe._ImageProcessingConfigurationParser=Bi.Parse,u("BABYLON.ImageProcessingConfiguration",Bi);class Ui{constructor(){this.shaderLanguage=ht.GLSL}postProcessor(e,t,i,s,r){if(r.drawBuffersExtensionDisabled){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}const ki=/(flat\s)?\s*varying\s*.*/;class Gi{constructor(){this.shaderLanguage=ht.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return ki.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(s||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}class zi{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=zi._Counter++}}zi._Counter=0;class Wi extends zi{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class Hi{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){return this._MSAARenderBuffers?.[e]??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}class Xi{}class Yi extends si{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return $t.ShadersRepository}static set ShadersRepository(e){$t.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}snapshotRenderingReset(){this.snapshotRendering=!1}constructor(e,t,i,s){if(i=i||{},super(t??i.antialias,i,s),this._name="WebGL",this.forcePOTTextures=!1,this.validateShaderPrograms=!1,this.disableUniformBuffers=!1,this._webGLVersion=1,this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},!e)return;let r=null;if(e.getContext){if(r=e,this._renderingCanvas=r,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();const e=navigator.userAgent;for(const t of Yi.ExceptionList){const s=t.key,r=t.targets;if(new RegExp(s).test(e)){if(t.capture&&t.captureConstraint){const i=t.capture,s=t.captureConstraint,r=new RegExp(i).exec(e);if(r&&r.length>0&&parseInt(r[r.length-1])>=s)continue}for(const e of r)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,J.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost((()=>this._initGLContext()))},r.addEventListener("webglcontextlost",this._onContextLost,!1),r.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=r.getContext("webgl2",i)||r.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!r)throw new Error("The provided canvas is null or undefined.");try{this._gl=r.getContext("webgl",i)||r.getContext("experimental-webgl",i)}catch(e){throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";const t=this._gl.getContextAttributes();t&&(i.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==i.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e1?new Gi:new Ui;const n=`Babylon.js v${Yi.Version}`;J.Log(n+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",n);const o=Ut(this._gl);o.validateShaderPrograms=this.validateShaderPrograms,o.parallelShaderCompile=this._caps.parallelShaderCompile}_clearEmptyResources(){this._dummyFramebuffer=null,super._clearEmptyResources()}_getShaderProcessingContext(e){return null}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_initGLContext(){this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||null!==this._gl.getExtension("OES_standard_derivatives"),maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:1!==this._webGLVersion,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=e&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)??0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!(!this._creationOptions||!this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);this._gl.uniformBlockBinding(s,r,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,s,r,n,o){const a=this._currentBufferPointers[t];if(!a)return;let l=!1;a.active?(a.buffer!==e&&(a.buffer=e,l=!0),a.size!==i&&(a.size=i,l=!0),a.type!==s&&(a.type=s,l=!0),a.normalized!==r&&(a.normalized=r,l=!0),a.stride!==n&&(a.stride=n,l=!0),a.offset!==o&&(a.offset=o,l=!0)):(l=!0,a.active=!0,a.index=t,a.size=i,a.type=s,a.normalized=r,a.stride=n,a.offset=o,a.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),s===this._gl.UNSIGNED_INT||s===this._gl.INT?this._gl.vertexAttribIPointer(t,i,s,n,o):this._gl.vertexAttribPointer(t,i,s,r,n,o))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const s=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let r=0;r=0){const t=s[r];let o=null;if(i&&(o=i[t]),o||(o=e[t]),!o)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const a=o.getBuffer();a&&(this._vertexAttribPointer(a,n,o.getSize(),o.type,o.normalized,o.byteStride,o.byteOffset),o.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,o.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(a))))}}}recordVertexArrayObject(e,t,i,s){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,s),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,s,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const t=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let o=0;o=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[o],this._gl.FLOAT,!1,s,n)),n+=4*i[o]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,s){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,s)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t{s?.(),t(e)}}(e,t)}getUniforms(e,t){const i=new Array,s=e;for(let e=0;e1||this.isWebGPU)),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(a=1),1!==o||this._caps.textureFloat||(o=0,J.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=this._gl,d=new ti(this,s),p=e.width||e,f=e.height||e,_=e.depth||0,m=e.layers||0,g=this._getSamplingParameters(a,n),v=0!==m?u.TEXTURE_2D_ARRAY:0!==_?u.TEXTURE_3D:u.TEXTURE_2D,x=this._getRGBABufferInternalSizedFormat(o,l,h),T=this._getInternalFormat(l),S=this._getWebGLTextureType(o);return this._bindTextureDirectly(v,d),0!==m?(d.is2DArray=!0,u.texImage3D(v,0,x,p,f,m,0,T,S,null)):0!==_?(d.is3D=!0,u.texImage3D(v,0,x,p,f,_,0,T,S,null)):u.texImage2D(v,0,x,p,f,0,T,S,null),u.texParameteri(v,u.TEXTURE_MAG_FILTER,g.mag),u.texParameteri(v,u.TEXTURE_MIN_FILTER,g.min),u.texParameteri(v,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(v,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(v),this._bindTextureDirectly(v,null),d._useSRGBBuffer=h,d.baseWidth=p,d.baseHeight=f,d.width=p,d.height=f,d.depth=m,d.isReady=!0,d.samples=c,d.generateMipMaps=n,d.samplingMode=a,d.type=o,d.format=l,d.label=r,this._internalTexturesCache.push(d),d}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,p,f){return this._createTextureBase(e,t,i,s,r,n,o,((...e)=>this._prepareWebGLTexture(...e,h)),((e,t,i,r,n,o)=>{const a=this._gl,l=i.width===e&&i.height===t;n._creationFlags=p??0;const h=this._getTexImageParametersForCreateTexture(n.format,n._useSRGBBuffer);if(l)return a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,i),!1;const c=this._caps.maxTextureSize;if(i.width>c||i.height>c||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!(!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,this._workingCanvas),n.width=e,n.height=t,1));{const e=new ti(this,ei.Temp);this._bindTextureDirectly(a.TEXTURE_2D,e,!0),a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,i),this._rescaleTexture(e,n,s,h.format,(()=>{this._releaseTexture(e),this._bindTextureDirectly(a.TEXTURE_2D,n,!0),o()}))}return!0}),a,l,h,c,u,d,f)}_getTexImageParametersForCreateTexture(e,t){let i,s;return 1===this.webGLVersion?(i=this._getInternalFormat(e,t),s=i):(i=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(0,e,t)),{internalFormat:s,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,s,r){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const s=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,r.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),t.samplingMode=e}updateTextureDimensions(e,t,i,s=1){}updateTextureWrappingMode(e,t,i=null,s=null){const r=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==s&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(r,null)}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){const a=this._gl;let l=a.TEXTURE_2D;if(e.isCube&&(l=a.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=a.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(l,o,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const o=this._gl,a=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=void 0===r?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=o.TEXTURE_2D;e.isCube&&(c=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);const u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),p=n?e.width:Math.pow(2,Math.max(u-s,0)),f=n?e.height:Math.pow(2,Math.max(d-s,0));o.texImage2D(c,s,h,p,f,0,l,a,t)}updateTextureData(e,t,i,s,r,n,o=0,a=0,l=!1){const h=this._gl,c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,p=h.TEXTURE_2D;e.isCube&&(p=h.TEXTURE_CUBE_MAP_POSITIVE_X+o,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(p,a,i,s,r,n,u,c,t),l&&this._gl.generateMipmap(p),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const r=this._gl,n=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,r){const n=this._gl;if(!n)return;const o=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,o.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,o.min),i||s||n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,r,n,o,a,l,h){const c=this.getCaps().maxTextureSize,u=Math.min(c,this.needPOTTextures?Ri(s.width,c):s.width),d=Math.min(c,this.needPOTTextures?Ri(s.height,c):s.height),p=this._gl;p&&(e._hardwareTexture?(this._bindTextureDirectly(p.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),e.baseWidth=s.width,e.baseHeight=s.height,e.width=u,e.height=d,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:h??(".jpg"!==t||e._useSRGBBuffer?5:4),a(u,d,s,t,e,(()=>{this._prepareWebGLTextureContinuation(e,i,n,o,l)}))||this._prepareWebGLTextureContinuation(e,i,n,o,l)):i&&i.removePendingData(e))}_setupFramebufferDepthAttachments(e,t,i,s,r=1){const n=this._gl;if(e&&t)return this._createRenderBuffer(i,s,r,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let e=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=n.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,r,e,e,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,r,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,r,n,o=!0){const a=this._gl.createRenderbuffer();return this._updateRenderBuffer(a,e,t,i,s,r,n,o)}_updateRenderBuffer(e,t,i,s,r,n,o,a=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),s>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,s,n,t,i):l.renderbufferStorage(l.RENDERBUFFER,r,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,o,l.RENDERBUFFER,e),a&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture?.underlyingResource),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);-1!==t&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(function(e,t){t.useProgram(e)}(e,this._gl),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t-1;if(i&&n&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw J.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,t?._hardwareTexture?.underlyingResource??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(r=!0,this._activateCurrentTexture());return n&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),r}_bindTexture(e,t,i){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;const s=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(s,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,s=!1,r=""){if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;const i=t.getInternalTexture();i&&(i._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;n=s?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&n&&(n._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),o=!1),this._activeChannel=e;const a=this._getTextureTarget(n);if(o&&this._bindTextureDirectly(a,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(a,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,s){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){var e;super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},We()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&this._gl.getExtension("WEBGL_lose_context")?.loseContext(),e=this._gl,Bt.delete(e)}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const s=t.createTexture();t.bindTexture(t.TEXTURE_2D,s),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const n=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&n===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);const e=t.RGBA,s=t.UNSIGNED_BYTE,r=new Uint8Array(4);t.readPixels(0,0,1,1,e,s,r),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(r),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:i=this._gl.RED;break;case 7:i=this._gl.RG;break;case 4:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,s,r=!0,n=!0){const o=r?4:3,a=r?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(s*i*o);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,a,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{const e=si._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{const e=si._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}}Yi._TempClearColorUint32=new Uint32Array(4),Yi._TempClearColorInt32=new Int32Array(4),Yi.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],Yi.CollisionsEpsilon=.001,Yi._ConcatenateShader=dt,Yi._IsSupported=null,Yi._HasMajorPerformanceCaveat=null,Yi.CeilingPOT=yi,Yi.FloorPOT=Ai,Yi.NearestPOT=Ci,Yi.GetExponentOfTwo=Ri,Yi.QueueNewFrame=ii,Yi.prototype.createUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create uniform buffer");const s=new Wi(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},Yi.prototype.createDynamicUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create dynamic uniform buffer");const s=new Wi(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},Yi.prototype.updateUniformBuffer=function(e,t,i,s){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===s?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+s)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+s)),this.bindUniformBuffer(null)},Yi.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},Yi.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},Yi.prototype.bindUniformBlock=function(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);4294967295!==r&&this._gl.uniformBlockBinding(s,r,i)};class ji{constructor(e,t,i,s,r=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,this._dynamic=i,this._name=s??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){const e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const i=this._uniformLocationPointer-e;for(let e=0;e0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t?t*=i:t=t*i+(4-t)*i,s=[];for(let e=0;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(ji._UpdatedUbosInFrame[this._name]||(ji._UpdatedUbosInFrame[this._name]=0),ji._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.trackUbosInFrame;else this.create()}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let s=this._uniformLocations[e];if(void 0===s){if(this._buffer)return void J.Error("Cannot add an uniform after UBO has been created. uniformName="+e);this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e0)return void(this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label));J.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,s=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,s?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),this._data=0===t&&void 0===i?e:null)}_increaseReferences(){this._buffer&&(this._isAlreadyOwned?this._buffer.references++:this._isAlreadyOwned=!0)}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class Ki{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,s,r,n,o,a,l,h,c=!1,u=!1,d=1,p=!1){this._isDisposed=!1;let f=!1;if(this.engine=e,"object"==typeof s&&null!==s?(f=s.updatable??!1,r=s.postponeInternalCreation,n=s.stride,o=s.instanced,a=s.offset,l=s.size,h=s.type,c=s.normalized??!1,u=s.useBytes??!1,d=s.divisor??1,p=s.takeBufferOwnership??!1,this._label=s.label):f=!!s,t instanceof $i?(this._buffer=t,this._ownsBuffer=p):(this._buffer=new $i(e,t,f,n,r,o,u,d,this._label),this._ownsBuffer=!0),this.uniqueId=Ki._Counter++,this._kind=i,void 0===h){const e=this.getData();this.type=e?Ki.GetDataType(e):Ki.FLOAT}else this.type=h;const _=Ki.GetTypeByteLength(this.type);u?(this._size=l||(n?n/_:Ki.DeduceStride(i)),this.byteStride=n||this._buffer.byteStride||this._size*_,this.byteOffset=a||0):(this._size=l||n||Ki.DeduceStride(i),this.byteStride=n?n*_:this._buffer.byteStride||this._size*_,this.byteOffset=(a||0)*_),this.normalized=c,this._instanced=void 0!==o&&o,this._instanceDivisor=o?d:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120|0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){this._buffer?._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?Ki.GetFloatData(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Ki.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/Ki.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*Ki.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){Ki.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case Ki.UVKind:case Ki.UV2Kind:case Ki.UV3Kind:case Ki.UV4Kind:case Ki.UV5Kind:case Ki.UV6Kind:return 2;case Ki.NormalKind:case Ki.PositionKind:return 3;case Ki.ColorKind:case Ki.ColorInstanceKind:case Ki.MatricesIndicesKind:case Ki.MatricesIndicesExtraKind:case Ki.MatricesWeightsKind:case Ki.MatricesWeightsExtraKind:case Ki.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?Ki.BYTE:e instanceof Uint8Array?Ki.UNSIGNED_BYTE:e instanceof Int16Array?Ki.SHORT:e instanceof Uint16Array?Ki.UNSIGNED_SHORT:e instanceof Int32Array?Ki.INT:e instanceof Uint32Array?Ki.UNSIGNED_INT:Ki.FLOAT}static GetTypeByteLength(e){switch(e){case Ki.BYTE:case Ki.UNSIGNED_BYTE:return 1;case Ki.SHORT:case Ki.UNSIGNED_SHORT:return 2;case Ki.INT:case Ki.UNSIGNED_INT:case Ki.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,s,r,n,o,a){if(e instanceof Array){let r=t/4;const o=i/4;for(let t=0;to[t]=e)),o}if(!(e instanceof Array||e instanceof Float32Array)||0!==s||e.length!==h){if(e instanceof Array){const t=s/4;return e.slice(t,t+h)}if(e instanceof ArrayBuffer)return new Float32Array(e,s,h);{let t=e.byteOffset+s;if(a){const i=new Float32Array(h),s=new Float32Array(e.buffer,t,h);return i.set(s),i}const i=t%4;return i&&(t=Math.max(0,t-i)),new Float32Array(e.buffer,t,h)}}return a?e.slice():e}}Ki._Counter=0,Ki.BYTE=5120,Ki.UNSIGNED_BYTE=5121,Ki.SHORT=5122,Ki.UNSIGNED_SHORT=5123,Ki.INT=5124,Ki.UNSIGNED_INT=5125,Ki.FLOAT=5126,Ki.PositionKind="position",Ki.NormalKind="normal",Ki.TangentKind="tangent",Ki.UVKind="uv",Ki.UV2Kind="uv2",Ki.UV3Kind="uv3",Ki.UV4Kind="uv4",Ki.UV5Kind="uv5",Ki.UV6Kind="uv6",Ki.ColorKind="color",Ki.ColorInstanceKind="instanceColor",Ki.MatricesIndicesKind="matricesIndices",Ki.MatricesWeightsKind="matricesWeights",Ki.MatricesIndicesExtraKind="matricesIndicesExtra",Ki.MatricesWeightsExtraKind="matricesWeightsExtra";class qi{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(Ki.NormalKind))return null;let i,s=this.pickedMesh.getIndices();0===s?.length&&(s=null);const r=U.Vector3[0],n=U.Vector3[1],o=U.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(Ki.NormalKind);let t=s?w.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),a=s?w.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=s?w.FromArrayToRef(e,3*s[3*this.faceId+2],o):o.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]);t=t.scale(this.bu),a=a.scale(this.bv),l=l.scale(1-this.bu-this.bv),i=new w(t.x+a.x+l.x,t.y+a.y+l.y,t.z+a.z+l.z)}else{const e=this.pickedMesh.getVerticesData(Ki.PositionKind),t=s?w.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),a=s?w.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=s?w.FromArrayToRef(e,3*s[3*this.faceId+2],o):o.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),h=t.subtract(a),c=l.subtract(a);i=w.Cross(h,c)}const a=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(U.Matrix[0].copyFrom(i),i=U.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(U.Matrix[1]),i=U.Matrix[1]),w.TransformNormalToRef(t,i,t)};if(e&&a(this.pickedMesh,i),this.ray){const t=U.Vector3[0].copyFrom(i);e||a(this.pickedMesh,t),w.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=Ki.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const i=this.pickedMesh.getVerticesData(e);if(!i)return null;let s=N.FromArray(i,2*t[3*this.faceId]),r=N.FromArray(i,2*t[3*this.faceId+1]),n=N.FromArray(i,2*t[3*this.faceId+2]);return s=s.scale(this.bu),r=r.scale(this.bv),n=n.scale(1-this.bu-this.bv),new N(s.x+r.x+n.x,s.y+r.y+n.y)}}class Qi{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[Ki.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[Ki.PositionKind]=new Ki(this._scene.getEngine(),e,Ki.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}_rebuild(){const e=this._vertexBuffers[Ki.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!(!i||!(t=t||i._postProcesses.filter((e=>null!=e)))||0===t.length||!this._scene.postProcessesEnabled||(t[0].activate(i,e,null!=t),0))}directRender(e,t=null,i=!1,s=0,r=0,n=!1){const o=this._scene.getEngine();for(let a=0;anull!=e))).length||!this._scene.postProcessesEnabled)return;const o=this._scene.getEngine();for(let a=0,l=s.length;at._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),s=t.getMesh();return i.material&&s.material?i.material.uniqueId-s.material.uniqueId:i.uniqueId-s.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t.isEnabled()&&t.isVisible&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(0===this._particleSystems.length)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i=us.LeftClick&&i<=us.RightClick&&(a.type=1===s?"pointerdown":"pointerup",a.button=i-2),a}static _CreateWheelEvent(e,t,i,s,r,n){const o=this._CreateMouseEvent(e,t,i,s,r,n);switch(o.pointerId=1,o.type="wheel",o.deltaMode=vs.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case us.MouseWheelX:o.deltaX=s;break;case us.MouseWheelY:o.deltaY=s;break;case us.MouseWheelZ:o.deltaZ=s}return o}static _CreateMouseEvent(e,t,i,s,r,n){const o=this._CreateEvent(n),a=r.pollInput(e,t,us.Horizontal),l=r.pollInput(e,t,us.Vertical);return n?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-n.getBoundingClientRect().x,o.offsetY=o.movementY-n.getBoundingClientRect().y):(o.movementX=r.pollInput(e,t,ds.DeltaHorizontal),o.movementY=r.pollInput(e,t,ds.DeltaVertical),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,r),o.clientX=a,o.clientY=l,o.x=a,o.y=l,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=cs.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=1===t?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(cs.Keyboard),s=i&&1===t.pollInput(cs.Keyboard,0,18),r=i&&1===t.pollInput(cs.Keyboard,0,17),n=i&&(1===t.pollInput(cs.Keyboard,0,91)||1===t.pollInput(cs.Keyboard,0,92)||1===t.pollInput(cs.Keyboard,0,93)),o=i&&1===t.pollInput(cs.Keyboard,0,16);e.altKey=s,e.ctrlKey=r,e.metaKey=n,e.shiftKey=o}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class Ts{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,s,r)=>{const n=xs.CreateDeviceEvent(e,t,s,r,this);i(e,t,n)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===cs.Mouse||e===cs.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const Ss=Object.keys(us).length/2;class Es{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Ii.IsSafari(),this._usingMacOS=He()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=e=>{},this._keyboardUpEvent=e=>{},this._keyboardBlurEvent=e=>{},this._pointerMoveEvent=e=>{},this._pointerDownEvent=e=>{},this._pointerUpEvent=e=>{},this._pointerCancelEvent=e=>{},this._pointerWheelEvent=e=>{},this._pointerBlurEvent=e=>{},this._pointerMacOSChromeOutEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=He()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=He()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=Ii.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=s,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){const s=this._inputs[e][t];if(!s)throw`Unable to find device ${cs[e]}`;e>=cs.DualShock&&e<=cs.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(void 0===r)throw`Unable to find input ${i} for device ${cs[e]} in slot ${t}`;return i===us.Move&&Ii.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this?._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(const e of this._inputs)if(e)for(const t in e){const i=e[+t];if(i)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(cs.Keyboard,0,255));const t=this._inputs[cs.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(cs.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(cs.Keyboard,0,255));const t=this._inputs[cs.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const i=xs.CreateDeviceEvent(cs.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(cs.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(cs.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[cs.Keyboard][0];for(let t=0;t{const t=this._getPointerType(e);let i=t===cs.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===cs.Touch&&-1===i){const s=this._activeTouchIds.indexOf(-1);if(!(s>=0))return void Ii.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=s,this._activeTouchIds[s]=e.pointerId,this._onDeviceConnected(t,i)}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=e;r.inputIndex=us.Move,s[us.Horizontal]=e.clientX,s[us.Vertical]=e.clientY,t===cs.Touch&&0===s[us.LeftClick]&&(s[us.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,r),this._usingSafari||-1===e.button||(r.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,r))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===cs.Mouse?0:e.pointerId;if(t===cs.Touch){let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t&&(t=this._activeTouchIds.indexOf(-1)),!(t>=0))return void Ii.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=t,this._activeTouchIds[t]=e.pointerId}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===cs.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=s[us.Horizontal],n=s[us.Vertical];if(t===cs.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}s[us.Horizontal]=e.clientX,s[us.Vertical]=e.clientY,s[e.button+2]=1;const o=e;o.inputIndex=e.button+2,this._onInputChanged(t,i,o),r===e.clientX&&n===e.clientY||(o.inputIndex=us.Move,this._onInputChanged(t,i,o))}},this._pointerUpEvent=e=>{const t=this._getPointerType(e),i=t===cs.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===cs.Touch){if(-1===i)return;this._activeTouchIds[i]=-1}const s=this._inputs[t]?.[i];if(s&&0!==s[e.button+2]){const r=s[us.Horizontal],n=s[us.Vertical];s[us.Horizontal]=e.clientX,s[us.Vertical]=e.clientY,s[e.button+2]=0;const o=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),r===e.clientX&&n===e.clientY||(o.inputIndex=us.Move,this._onInputChanged(t,i,o)),o.inputIndex=e.button+2,t===cs.Mouse&&this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(t,i,o),t===cs.Touch&&this._onDeviceDisconnected(t,i)}},this._pointerCancelEvent=e=>{if("mouse"===e.pointerType){const e=this._inputs[cs.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=us.LeftClick;t<=us.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=xs.CreateDeviceEvent(cs.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(cs.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[cs.Touch][t][us.LeftClick]=0;const i=xs.CreateDeviceEvent(cs.Touch,t,us.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(cs.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(cs.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1;const t=function(){};try{const i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch(e){}this._pointerBlurEvent=()=>{if(this.isDeviceAvailable(cs.Mouse)){const e=this._inputs[cs.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=us.LeftClick;t<=us.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=xs.CreateDeviceEvent(cs.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(cs.Mouse,0,i)}}if(this.isDeviceAvailable(cs.Touch)){const e=this._inputs[cs.Touch];for(let t=0;t{const t=cs.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,Ss));const i=this._inputs[t][0];if(i){i[us.MouseWheelX]=e.deltaX||0,i[us.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[us.MouseWheelZ]=e.deltaZ||0;const s=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[us.MouseWheelX]&&(s.inputIndex=us.MouseWheelX,this._onInputChanged(t,0,s)),0!==i[us.MouseWheelY]&&(s.inputIndex=us.MouseWheelY,this._onInputChanged(t,0,s)),0!==i[us.MouseWheelZ]&&(s.inputIndex=us.MouseWheelZ,this._onInputChanged(t,0,s))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=e=>{e.buttons>1&&this._pointerCancelEvent(e)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,!!e&&{passive:!1}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add((()=>{if(this.isDeviceAvailable(cs.Mouse)){const e=this._inputs[cs.Mouse][0];e[us.MouseWheelX]=0,e[us.MouseWheelY]=0,e[us.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const s=navigator.getGamepads()[t];if(s&&e===this._gamepads[t]){const r=this._inputs[e][t];i>=s.buttons.length?r[i]=s.axes[i-s.buttons.length].valueOf():r[i]=s.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?cs.DualSense:cs.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?cs.Xbox:-1!==e.indexOf("057e")?cs.Switch:cs.Generic}_getPointerType(e){let t=cs.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=cs.Touch),t}}class bs{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new g,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class Cs{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(cs).length/2;this._devices=new Array(t);const i=(e,t)=>{this._devices[e]||(this._devices[e]=new Array),this._devices[e][t]||(this._devices[e][t]=t);for(const i of this._registeredManagers){const s=new bs(this._deviceInputSystem,e,t);i._addDevice(s)}},s=(e,t)=>{this._devices[e]?.[t]&&delete this._devices[e][t];for(const i of this._registeredManagers)i._removeDevice(e,t)},r=(e,t,i)=>{if(i)for(const s of this._registeredManagers)s._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new Ts(i,s,r):this._deviceInputSystem=new Es(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class ys{getDeviceSource(e,t){if(void 0===t){if(void 0===this._firstDevice[e])return null;t=this._firstDevice[e]}return this._devices[e]&&void 0!==this._devices[e][t]?this._devices[e][t]:null}getDeviceSources(e){return this._devices[e]?this._devices[e].filter((e=>!!e)):[]}constructor(e){const t=Object.keys(cs).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new Cs(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new g((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new g,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){const i=this._devices[e]?.[t];this.onDeviceDisconnectedObservable.notifyObservers(i),this._devices[e]?.[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){this._devices[e]?.[t]?.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case cs.Keyboard:case cs.Mouse:this._firstDevice[e]=0;break;case cs.Touch:case cs.DualSense:case cs.DualShock:case cs.Xbox:case cs.Switch:case cs.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i=us.MouseWheelX&&t.inputIndex<=us.MouseWheelZ?ss.POINTERWHEEL:ss.POINTERMOVE;let o;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n)),e?(o=new os(n,t,e),this._setRayOnPointerInfo(e,t)):(o=new os(n,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,B.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const s=this._scene,r=new ns(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,"xr-near"===t.pointerType&&e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const s=i.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(s.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=us.Move,this._checkPrePointerObservable(e,i,ss.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,ss.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const s=e.pickedMesh._getActionManagerForTrigger();if(s){if(s.hasPickTriggers)switch(s.processTrigger(5,q.CreateNew(e.pickedMesh,t,e)),t.button){case 0:s.processTrigger(2,q.CreateNew(e.pickedMesh,t,e));break;case 1:s.processTrigger(4,q.CreateNew(e.pickedMesh,t,e));break;case 2:s.processTrigger(3,q.CreateNew(e.pickedMesh,t,e))}s.hasSpecificTrigger(8)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);e?.pickedMesh&&s&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>Rs.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,s.processTrigger(8,q.CreateNew(e.pickedMesh,t)))}),Rs.LongPressDelay)}}else for(const s of i._pointerDownStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=ss.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new os(r,t,e),this._setRayOnPointerInfo(e,t)):s=new os(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=us.Move;const r=new As;i?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,s,ss.POINTERUP)||this._processPointerUp(e,s,r)}_processPointerUp(e,t,i){const s=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){const i=ss.POINTERPICK,r=new os(i,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,i)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,q.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,q.CreateNew(e.pickedMesh,t,e));const s=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&s&&s.processTrigger(6,q.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,q.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new os(ss.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,ss.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,ss.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(i.singleClick?r=ss.POINTERTAP:i.doubleClick&&(r=ss.POINTERDOUBLETAP),r){const i=new os(r,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(r)&&s.onPointerObservable.notifyObservers(i,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const r=this._scene,n=r.getEngine();s||(s=n.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new ys(n),this._initActionManager=e=>{if(!this._meshPickProceed){const t=r.skipPointerUpPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers,r.pointerUpTrianglePredicate);this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>Rs.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){const t=this._delayedClicks[e].evt,i=ss.POINTERTAP,s=new os(i,t,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(i)&&r.onPointerObservable.notifyObservers(s,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,s)=>{const r=new As;this._currentPickResult=null;let n=null,o=e.hasSpecificMask(ss.POINTERPICK)||t.hasSpecificMask(ss.POINTERPICK)||e.hasSpecificMask(ss.POINTERTAP)||t.hasSpecificMask(ss.POINTERTAP)||e.hasSpecificMask(ss.POINTERDOUBLETAP)||t.hasSpecificMask(ss.POINTERDOUBLETAP);!o&&f&&(n=this._initActionManager(n,r),n&&(o=n.hasPickTriggers));let a=!1;if(o){const o=i.button;if(r.hasSwiped=this._isPointerSwiping(),!r.hasSwiped){let l=!Rs.ExclusiveDoubleClickMode;if(l||(l=!e.hasSpecificMask(ss.POINTERDOUBLETAP)&&!t.hasSpecificMask(ss.POINTERDOUBLETAP),l&&!f.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(l=!n.hasSpecificTrigger(6)))),l)(Date.now()-this._previousStartingPointerTime>Rs.DoubleClickDelay||o!==this._previousButtonPressed)&&(r.singleClick=!0,s(r,this._currentPickResult),a=!0);else{const e={evt:i,clickInfo:r,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,o,r,s),Rs.DoubleClickDelay)};this._delayedClicks[o]=e}let h=e.hasSpecificMask(ss.POINTERDOUBLETAP)||t.hasSpecificMask(ss.POINTERDOUBLETAP);!h&&f.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(h=n.hasSpecificTrigger(6))),h&&(o===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>Rs.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>Rs.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=us.MouseWheelX&&e.inputIndex<=us.MouseWheelZ?ss.POINTERWHEEL:ss.POINTERMOVE))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking)return void this._processPointerMove(new qi,e);r.pointerMovePredicate||(r.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask)));const t=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,Rs.ExclusiveDoubleClickMode)for(let t=0;te.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,t=r.skipPointerDownPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerDown?new qi:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers,r.pointerDownTrianglePredicate),this._processPointerDown(t,e)},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),r.preventDefaultOnPointerUp&&s&&(e.preventDefault(),s.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,e,((t,i)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,ss.POINTERUP))return this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),void(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1));t.hasSwiped||(t.singleClick&&r.onPrePointerObservable.hasSpecificMask(ss.POINTERTAP)&&this._checkPrePointerObservable(null,e,ss.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&r.onPrePointerObservable.hasSpecificMask(ss.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,ss.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(r.cameraToUseForPointers||r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(f&&f.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))):this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1)})))},this._onKeyDown=e=>{const t=as.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const i=new hs(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new ls(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(14,q.CreateNewFromScene(r,e))},this._onKeyUp=e=>{const t=as.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const i=new hs(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new ls(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(15,q.CreateNewFromScene(r,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((s=>{s.deviceType===cs.Mouse?s.onInputChangedObservable.add((r=>{this._originMouseEvent=r,r.inputIndex===us.LeftClick||r.inputIndex===us.MiddleClick||r.inputIndex===us.RightClick||r.inputIndex===us.BrowserBack||r.inputIndex===us.BrowserForward?t&&1===s.getInput(r.inputIndex)?this._onPointerDown(r):e&&0===s.getInput(r.inputIndex)&&this._onPointerUp(r):i&&(r.inputIndex===us.Move?this._onPointerMove(r):r.inputIndex!==us.MouseWheelX&&r.inputIndex!==us.MouseWheelY&&r.inputIndex!==us.MouseWheelZ||this._onPointerMove(r))})):s.deviceType===cs.Touch?s.onInputChangedObservable.add((r=>{r.inputIndex===us.LeftClick&&(t&&1===s.getInput(r.inputIndex)?(this._onPointerDown(r),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===s.getInput(r.inputIndex)&&(this._onPointerUp(r),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&r.inputIndex===us.Move&&this._onPointerMove(r)})):s.deviceType===cs.Keyboard&&s.onInputChangedObservable.add((e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)}))})),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,s){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const r=this._meshUnderPointerId[t];let n;r&&(n=r._getActionManagerForTrigger(10),n&&n.processTrigger(10,q.CreateNew(r,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,q.CreateNew(e,s,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(const t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}Rs.DragMovementThreshold=10,Rs.LongPressDelay=500,Rs.DoubleClickDelay=300,Rs.ExclusiveDoubleClickMode=!1;class Is{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){Is.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){Is.Enabled&&(this._startMonitoringTime=je.Now)}endMonitoring(e=!0){if(!Is.Enabled)return;e&&this.fetchNewFrame();const t=je.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;const e=je.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}Is.Enabled=!0;class Ps{constructor(e,t,i,s){this.normal=new w(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new Ps(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^this.d,e}normalize(){const e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z);let t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=Ps._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,o=this.d,a=s*i[0]+r*i[1]+n*i[2]+o*i[3],l=s*i[4]+r*i[5]+n*i[6]+o*i[7],h=s*i[8]+r*i[9]+n*i[10]+o*i[11],c=s*i[12]+r*i[13]+n*i[14]+o*i[15];return new Ps(a,l,h,c)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const s=t.x-e.x,r=t.y-e.y,n=t.z-e.z,o=i.x-e.x,a=i.y-e.y,l=i.z-e.z,h=r*l-n*a,c=n*o-s*l,u=s*a-r*o,d=Math.sqrt(h*h+c*c+u*u);let p;return p=0!==d?1/d:0,this.normal.x=h*p,this.normal.y=c*p,this.normal.z=u*p,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return w.Dot(this.normal,e)<=t}signedDistanceTo(e){return w.Dot(e,this.normal)+this.d}static FromArray(e){return new Ps(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new Ps(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new Ps(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return w.Dot(i,t)+s}}Ps._TmpMatrix=B.Identity();class Ms{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new Ps(0,0,0,0));return Ms.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){Ms.GetNearPlaneToRef(e,t[0]),Ms.GetFarPlaneToRef(e,t[1]),Ms.GetLeftPlaneToRef(e,t[2]),Ms.GetRightPlaneToRef(e,t[3]),Ms.GetTopPlaneToRef(e,t[4]),Ms.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}class Ds{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}Ds._UniqueIdCounter=1;class Os{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}Os.FALLOFF_DEFAULT=0,Os.FALLOFF_PHYSICAL=1,Os.FALLOFF_GLTF=2,Os.FALLOFF_STANDARD=3,Os.LIGHTMAP_DEFAULT=0,Os.LIGHTMAP_SPECULAR=1,Os.LIGHTMAP_SHADOWSONLY=2,Os.INTENSITYMODE_AUTOMATIC=0,Os.INTENSITYMODE_LUMINOUSPOWER=1,Os.INTENSITYMODE_LUMINOUSINTENSITY=2,Os.INTENSITYMODE_ILLUMINANCE=3,Os.INTENSITYMODE_LUMINANCE=4,Os.LIGHTTYPEID_POINTLIGHT=0,Os.LIGHTTYPEID_DIRECTIONALLIGHT=1,Os.LIGHTTYPEID_SPOTLIGHT=2,Os.LIGHTTYPEID_HEMISPHERICLIGHT=3;class Ns{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var ws,Fs,Ls,Bs,Vs,Us;!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(ws||(ws={}));class ks extends p{static DefaultMaterialFactory(e){throw ye("StandardMaterial")}static CollisionCoordinatorFactory(){throw ye("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case ws.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case ws.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case ws.Aggressive:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return Rs.DragMovementThreshold}static set DragMovementThreshold(e){Rs.DragMovementThreshold=e}static get LongPressDelay(){return Rs.LongPressDelay}static set LongPressDelay(e){Rs.LongPressDelay=e}static get DoubleClickDelay(){return Rs.DoubleClickDelay}static set DoubleClickDelay(e){Rs.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return Rs.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){Rs.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const s=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return U.Vector4[0].set(s.x,s.y,s.z,r?-1:1),e&&(i?e.setFloat3(t,U.Vector4[0].x,U.Vector4[0].y,U.Vector4[0].z):e.setVector4(t,U.Vector4[0])),U.Vector4[0]}finalizeSceneUbo(){const e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=b(e,(()=>{this.onActiveCamerasChanged.notifyObservers(this)}))),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=ks.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=ks.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new Rs(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new j(.2,.2,.3,1),this.ambientColor=new Y(0,0,0),this.environmentIntensity=1,this._performancePriority=ws.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new g,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new g,this._onDisposeObserver=null,this.onBeforeRenderObservable=new g,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new g,this.onAfterRenderCameraObservable=new g,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new g,this.onAfterAnimationsObservable=new g,this.onBeforeDrawPhaseObservable=new g,this.onAfterDrawPhaseObservable=new g,this.onReadyObservable=new g,this.onBeforeCameraRenderObservable=new g,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new g,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new g,this.onAfterActiveMeshesEvaluationObservable=new g,this.onBeforeParticlesRenderingObservable=new g,this.onAfterParticlesRenderingObservable=new g,this.onDataLoadedObservable=new g,this.onNewCameraAddedObservable=new g,this.onCameraRemovedObservable=new g,this.onNewLightAddedObservable=new g,this.onLightRemovedObservable=new g,this.onNewGeometryAddedObservable=new g,this.onGeometryRemovedObservable=new g,this.onNewTransformNodeAddedObservable=new g,this.onTransformNodeRemovedObservable=new g,this.onNewMeshAddedObservable=new g,this.onMeshRemovedObservable=new g,this.onNewSkeletonAddedObservable=new g,this.onSkeletonRemovedObservable=new g,this.onNewMaterialAddedObservable=new g,this.onNewMultiMaterialAddedObservable=new g,this.onMaterialRemovedObservable=new g,this.onMultiMaterialRemovedObservable=new g,this.onNewTextureAddedObservable=new g,this.onTextureRemovedObservable=new g,this.onBeforeRenderTargetsRenderObservable=new g,this.onAfterRenderTargetsRenderObservable=new g,this.onBeforeStepObservable=new g,this.onAfterStepObservable=new g,this.onActiveCameraChanged=new g,this.onActiveCamerasChanged=new g,this.onBeforeRenderingGroupObservable=new g,this.onAfterRenderingGroupObservable=new g,this.onMeshImportedObservable=new g,this.onAnimationFileImportedObservable=new g,this._registeredForLateAnimationBindings=new Di(256),this._pointerPickingConfiguration=new Ns,this.onPrePointerObservable=new g,this.onPointerObservable=new g,this.onPreKeyboardObservable=new g,this.onKeyboardObservable=new g,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=ks.FOGMODE_NONE,this.fogColor=new Y(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new w(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new Di(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new Is,this._activeIndices=new Is,this._activeParticles=new Is,this._activeBones=new Is,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=new Array(256),this._activeRequests=new Array,this._pendingData=new Array,this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new Mi(256),this._processedMaterials=new Mi(256),this._renderTargets=new Di(256),this._materialsRenderTargets=new Di(256),this._activeParticleSystems=new Mi(256),this._activeSkeletons=new Di(32),this._softwareSkinnedMeshes=new Di(32),this._activeAnimatables=new Array,this._transformMatrix=B.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=is.Create(),this._beforeClearStage=is.Create(),this._beforeRenderTargetClearStage=is.Create(),this._gatherRenderTargetsStage=is.Create(),this._gatherActiveCameraRenderTargetsStage=is.Create(),this._isReadyForMeshStage=is.Create(),this._beforeEvaluateActiveMeshStage=is.Create(),this._evaluateSubMeshStage=is.Create(),this._preActiveMeshStage=is.Create(),this._cameraDrawRenderTargetStage=is.Create(),this._beforeCameraDrawStage=is.Create(),this._beforeRenderTargetDrawStage=is.Create(),this._beforeRenderingGroupDrawStage=is.Create(),this._beforeRenderingMeshStage=is.Create(),this._afterRenderingMeshStage=is.Create(),this._afterRenderingGroupDrawStage=is.Create(),this._afterCameraDrawStage=is.Create(),this._afterCameraPostProcessStage=is.Create(),this._afterRenderTargetDrawStage=is.Create(),this._afterRenderTargetPostProcessStage=is.Create(),this._afterRenderStage=is.Create(),this._pointerMoveStage=is.Create(),this._pointerDownStage=is.Create(),this._pointerUpStage=is.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];const i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};e=this._engine=e||y.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(y._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new es(this),Qi&&(this.postProcessManager=new Qi(this)),We()&&this.attachControl(),this._createUbo(),Bi&&(this._imageProcessingConfiguration=new Bi),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,t&&t.virtual||e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return void 0!==this._animationRatio?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){if(this._isDisposed)return!1;let t;const i=this.getEngine(),s=i.currentRenderPassId;i.currentRenderPassId=this.activeCamera?.renderPassId??s;let r=!0;for(this._pendingData.length>0&&(r=!1),this.prePassRenderer?.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&r&&(r=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const e of this._isReadyForMeshStage)e.action(s,n)||(r=!1);if(!e)continue;const o=s.material||this.defaultMaterial;if(o)if(o._storeEffectOnSubMeshes)for(const e of s.subMeshes){const t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else o.hasRenderTargetTextures&&null!=o.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(o)&&(this._processedMaterials.push(o),this._materialsRenderTargets.concatWithNoDuplicate(o.getRenderTargetTextures()))}if(e)for(t=0;t0)for(const e of this.activeCameras)e.isReady(!0)||(r=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(r=!1));for(const e of this.particleSystems)e.isReady()||(r=!1);if(this.layers)for(const e of this.layers)e.isReady()||(r=!1);return i.areAllEffectsReady()||(r=!1),i.currentRenderPassId=s,r}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout((()=>{this.unregisterBeforeRender(t)}))};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){void 0!==t?setTimeout((()=>{this._executeOnceBeforeRender(e)}),t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){const t=this.isLoading,i=this._pendingData.indexOf(e);-1!==i&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise((t=>{this.executeWhenReady((()=>{t()}),e)}))}_checkIsReady(e=!1){return this._registerTransientComponents(),this.isReady(e)?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):void(this._executeWhenReadyTimeoutId=setTimeout((()=>{this.incrementRenderId(),this._checkIsReady(e)}),100))}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=je.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,s){i||s||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?Ms.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Ms.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,s):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new ji(this._engine,void 0,!1,e??"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return Ds.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.addMesh(e)})))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return-1!==i&&(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.removeMesh(e)})),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){const e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){const t=this.skeletons.indexOf(e);return-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(-1!==t){for(const t of this.meshes)t._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t}removeCamera(e){const t=this.cameras.indexOf(e);if(-1!==t&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){const t=this.particleSystems.indexOf(e);return-1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(-1!==t&&tt.uniqueId===e))}getMaterialById(e,t=!1){return this._getMaterial(t,(t=>t.id===e))}getMaterialByName(e,t=!1){return this._getMaterial(t,(t=>t.name===e))}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t)for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t];return null}getTextureByUniqueId(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const s=this.getLightById(e);if(s)return s;const r=this.getCameraById(e);if(r)return r;return this.getBoneById(e)||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const s=this.getLightByName(e);if(s)return s;const r=this.getCameraByName(e);if(r)return r;return this.getBoneByName(e)||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(this.activeCamera){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,s)for(let e=0;ee.dispose()))}_evaluateActiveMeshes(){if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode)return void(this._activeMeshes.length>0&&(this.activeCamera?._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset()));if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const e=this._activeMeshes.length;for(let t=0;t0&&t.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||t.alwaysSelectAsActiveMesh||t.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(t),this.activeCamera._activeMeshes.push(t),s!==t&&s._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(t);t._activate(this._renderId,!1)&&(t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(s=t):s._internalAbstractMeshDataInfo._onlyForInstances=!1,s._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(t,s)),t._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e0){const s=this.getActiveSubMeshCandidates(t),r=s.length;i=i||1===r;for(let n=0;n0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const e of this._gatherActiveCameraRenderTargetsStage)e.action(this._renderTargets);let r=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Ii.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e0),this._renderId++}for(const e of this._cameraDrawRenderTargetStage)r=e.action(this.activeCamera)||r;this._intermediateRendering=!1}this._engine.currentRenderPassId=e.outputRenderTarget?.renderPassId??e.renderPassId??0,r&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame();for(const e of this._beforeCameraDrawStage)e.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),s.snapshotRendering&&1===s.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const e of this._afterCameraDrawStage)e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(const e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview)return e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t-1&&(13===i.trigger&&i._executeCurrent(q.CreateNew(t,void 0,s)),t.actionManager.hasSpecificTrigger(13,(e=>{const t=e.mesh?e.mesh:e;return s===t}))&&13!==i.trigger||t._intersectionsInProgress.splice(n,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(ks.MinDeltaTime,Math.min(this._engine.getDeltaTime(),ks.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&s0)for(let e=0;e0),this._intermediateRendering=!0;for(let e=0;e0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=s?.renderPassId??0,this.activeCamera=s,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const e of this._beforeClearStage)e.action();this._clearFrameBuffer(this.activeCamera);for(const e of this._gatherRenderTargetsStage)e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const e of this._afterRenderStage)e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e{e.onAnimationEndObservable.clear(),e.onAnimationEnd=null})),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;const e=this._activeRequests.slice();for(const t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){J.Error("An error occurred while calling onDisposeObservable!",e)}if(this.detachControl(),this._engine.getInputElement())for(let e=0;ee.dispose(!0))),this._disposeList(this.transformNodes,(e=>e.dispose(!0)));const t=this.cameras;this._disposeList(t),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),y._LastCreatedScene===this&&(this._engine.scenes.length>0?y._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:y._LastCreatedScene=null),i=this._engine._virtualScenes.indexOf(this),i>-1&&this._engine._virtualScenes.splice(i,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const i=e.slice(0);t=t??(e=>e.dispose());for(const e of i)t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach((e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;const s=e.getBoundingInfo(),r=s.boundingBox.minimumWorld,n=s.boundingBox.maximumWorld;w.CheckExtends(r,t,i),w.CheckExtends(n,t,i)})),{min:t,max:i}}createPickingRay(e,t,i,s,r=!1){throw ye("Ray")}createPickingRayToRef(e,t,i,s,r,n=!1,o=!1){throw ye("Ray")}createPickingRayInCameraSpace(e,t,i){throw ye("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw ye("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,r,n){const o=ye("Ray",!0);return o&&J.Warn(o),new qi}pickWithBoundingInfo(e,t,i,s,r){const n=ye("Ray",!0);return n&&J.Warn(n),new qi}pickWithRay(e,t,i,s){throw ye("Ray")}multiPick(e,t,i,s,r){throw ye("Ray")}multiPickWithRay(e,t,i){throw ye("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(void 0===t)return e;const s=[];for(const r in e){const n=e[r];Re&&Re.MatchesQuery(n,t)&&(!i||i(n))&&s.push(n)}return s}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,s)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,s,r,n,o){const a=di(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_loadFileAsync(e,t,i,s,r){return new Promise(((n,o)=>{this._loadFile(e,(e=>{n(e)}),t,i,s,((e,t)=>{o(t)}),r)}))}_requestFile(e,t,i,s,r,n,o){const a=pi(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_requestFileAsync(e,t,i,s,r){return new Promise(((n,o)=>{this._requestFile(e,(e=>{n(e)}),t,i,s,(e=>{o(e)}),r)}))}_readFile(e,t,i,s,r){const n=ui(e,t,i,s,r);return this._activeRequests.push(n),n.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),n}_readFileAsync(e,t,i){return new Promise(((s,r)=>{this._readFile(e,(e=>{s(e)}),t,i,(e=>{r(e)}))}))}getPerfCollector(){throw ye("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}ks.FOGMODE_NONE=0,ks.FOGMODE_EXP=1,ks.FOGMODE_EXP2=2,ks.FOGMODE_LINEAR=3,ks.MinDeltaTime=1,ks.MaxDeltaTime=1e3,u("BABYLON.Scene",ks),(Us=Fs||(Fs={}))[Us.LOCAL=0]="LOCAL",Us[Us.WORLD=1]="WORLD",Us[Us.BONE=2]="BONE";class Gs{}Gs.X=new w(1,0,0),Gs.Y=new w(0,1,0),Gs.Z=new w(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Ls||(Ls={}));class zs extends De{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){(e.updateFlag!==this._localMatrix.updateFlag||this._needToCompose)&&(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,s=null,r=null,n=null,o=null){super(e,t.getScene(),!1),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=s?.clone()??B.Identity(),this._restMatrix=r??this._localMatrix.clone(),this._bindMatrix=n??this._localMatrix.clone(),this._index=o,this._absoluteMatrix=new B,this._absoluteBindMatrix=new B,this._absoluteInverseBindMatrix=new B,this._finalMatrix=new B,t.bones.push(this),this.setParent(i,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return null===this._index?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){const e=this.parent.children.indexOf(this);-1!==e&&this.parent.children.splice(e,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){if(this._linkedTransformNode){const e=U.Vector3[0],t=U.Quaternion[0],i=U.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??L.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(t),this._linkedTransformNode.scaling.copyFrom(e)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._absoluteMatrix}getAbsoluteTransform(){return this._absoluteMatrix}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=w.Zero(),this._localRotation=L.Zero(),this._localPosition=w.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,B.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let e=0;e-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(r)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const r=this._runtimeAnimations;for(let i=r.length-1;i>=0;i--){const s=r[i];e&&s.animation.name!=e||t&&!t(s.target)||(s.dispose(),r.splice(i,1))}0==r.length&&(i||this._scene._activeAnimatables.splice(s,1),this._raiseOnAnimationEnd())}}else{const e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);const t=this._runtimeAnimations;for(let e=0;e{this.onAnimationEndObservable.add((()=>{e(this)}),void 0,void 0,this,!0)}))}_animate(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),null!==this._manualJumpDelay&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,0===this._weight)return!0;let t=!1;const i=this._runtimeAnimations;let s;for(s=0;s0)return;this._animationTimeLast=t}this.deltaTime=void 0!==e?e:this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=t;const i=this._activeAnimatables;if(0===i.length)return;this._animationTime+=this.deltaTime;const s=this._animationTime;for(let e=0;ee.playOrder-t.playOrder))},ks.prototype.beginWeightedAnimation=function(e,t,i,s=1,r,n=1,o,a,l,h,c=!1){const u=this.beginAnimation(e,t,i,r,n,o,a,!1,l,h,c);return u.weight=s,u},ks.prototype.beginAnimation=function(e,t,i,s,r=1,n,o,a=!0,l,h,c=!1){t>i&&r>0&&(r*=-1),a&&this.stopAnimation(e,void 0,l),o||(o=new Ws(this,e,t,i,s,r,n,void 0,h,c));const u=!l||l(e);if(e.animations&&u&&o.appendAnimations(e,e.animations),e.getAnimatables){const c=e.getAnimatables();for(let e=0;es&&n>0)n*=-1;else if(s>i&&n<0){const e=s;s=i,i=e}return new Ws(this,e,i,s,r,n,o,t,a,l)},ks.prototype.beginDirectHierarchyAnimation=function(e,t,i,s,r,n,o,a,l,h=!1){const c=e.getDescendants(t),u=[];u.push(this.beginDirectAnimation(e,i,s,r,n,o,a,l,h));for(const e of c)u.push(this.beginDirectAnimation(e,i,s,r,n,o,a,l,h));return u},ks.prototype.getAnimatableByTarget=function(e){for(let t=0;t0?l:-l,r),a.scaleAndAddToRef(l,i)}r.normalize()}for(let t=0;t0)r.copyFrom(s);else if(1===e.animations.length){if(L.SlerpToRef(s,i.currentValue,Math.min(1,e.totalWeight),r),0===e.totalAdditiveWeight)return r}else if(e.animations.length>1){let i,n,o=1;if(e.totalWeight<1){const t=1-e.totalWeight;i=[],n=[],i.push(s),n.push(t)}else{if(2===e.animations.length&&(L.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],n=[],o=e.totalWeight}for(let t=0;t=o&&m.frame<=a&&(s?(v=m.value.clone(),d?(g=v.getTranslation(),v.setTranslation(g.scaleInPlace(p))):f&&r?(g=v.getTranslation(),v.setTranslation(g.multiplyInPlace(r))):v=m.value):v=m.value,_.push({frame:m.frame+i,value:v}));return this.animations[0].createRange(t,o+i,a+i),!0},function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(Bs||(Bs={}));class Hs{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return 180*this._radians/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),s=Math.atan2(i.y,i.x);return new Hs(s)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(0===i)return new Hs(Math.PI/2);i=Math.sqrt(i);let s=e.dot(t)/i;s=G.Clamp(s,-1,1);const r=Math.acos(s);return new Hs(r)}static FromRadians(e){return new Hs(e)}static FromDegrees(e){return new Hs(e*Math.PI/180)}}class Xs{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const s=Math.pow(t.x,2)+Math.pow(t.y,2),r=(Math.pow(e.x,2)+Math.pow(e.y,2)-s)/2,n=(s-Math.pow(i.x,2)-Math.pow(i.y,2))/2,o=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new N((r*(t.y-i.y)-n*(e.y-t.y))/o,((e.x-t.x)*n-(t.x-i.x)*r)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=Hs.BetweenTwoPoints(this.centerPoint,this.startPoint);const a=this.startAngle.degrees();let l=Hs.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=Hs.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-a>180&&(l-=360),l-a<-180&&(l+=360),h-l>180&&(h-=360),h-l<-180&&(h+=360),this.orientation=l-a<0?Bs.CW:Bs.CCW,this.angle=Hs.FromDegrees(this.orientation===Bs.CW?a-h:h-a)}}class Ys{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new N(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new N(e,t),s=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(s).length(),this}addArcTo(e,t,i,s,r=36){if(this.closed)return this;const n=this._points[this._points.length-1],o=new N(e,t),a=new N(i,s),l=new Xs(n,o,a);let h=l.angle.radians()/r;l.orientation===Bs.CW&&(h*=-1);let c=l.startAngle.radians()+h;for(let e=0;e(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*s,o=this._points[this._points.length-1];for(let a=0;a<=r;a++){const l=a/r,h=n(l,o.x,e,i),c=n(l,o.y,t,s);this.addLineTo(h,c)}return this}addBezierCurveTo(e,t,i,s,r,n,o=36){if(this.closed)return this;const a=(e,t,i,s,r)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*s+e*e*e*r,l=this._points[this._points.length-1];for(let h=0;h<=o;h++){const c=h/o,u=a(c,l.x,e,i,r),d=a(c,l.y,t,s,n);this.addLineTo(u,d)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let s=i-1,r=0;rNumber.EPSILON){if(a<0&&(i=this._points[r],o=-o,n=this._points[s],a=-a),e.yn.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{const s=a*(e.x-i.x)-o*(e.y-i.y);if(0===s)return!0;if(s<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(n.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=n.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1];e+=this._points[0].subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,s=0;s1)return N.Zero();const t=e*this.length();let i=0;for(let e=0;e=i&&t<=o){const e=n.normalize(),s=t-i;return new N(r.x+e.x*s,r.y+e.y*s)}i=o}return N.Zero()}static StartingAt(e,t){return new Ys(e,t)}}class js{constructor(e,t=null,i,s=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:w.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:B.Identity()};for(let t=0;tt){const i=e;e=t,t=i}const i=this.getCurve(),s=this.getPointAt(e);let r=this.getPreviousPointIndexAt(e);const n=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,a=[];return 0!==e&&(r++,a.push(s)),a.push(...i.slice(r,o)),1===t&&1!==e||a.push(n),new js(a,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;tt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,s=e.length();if(0===s&&(s=1),null==t){let t;t=G.WithinEpsilon(Math.abs(e.y)/s,1,T)?G.WithinEpsilon(Math.abs(e.x)/s,1,T)?G.WithinEpsilon(Math.abs(e.z)/s,1,T)?w.Zero():new w(0,0,1):new w(1,0,0):new w(0,-1,0),i=w.Cross(e,t)}else i=w.Cross(e,t),w.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;const i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let s,r=i[0],n=0;const o=e*this.length();for(let a=1;ao){const i=(n-o)/l,h=r.subtract(s),c=s.add(h.scaleInPlace(i));return this._setPointAtData(e,1-i,c,a-1,t)}r=s}return this._pointAtData}_setPointAtData(e,t,i,s,r){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=s,this._pointAtData.interpolateReady=r,r&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=B.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),s=this._normals[e].clone(),r=this._binormals[e].clone(),n=this._tangents[t].clone(),o=this._normals[t].clone(),a=this._binormals[t].clone(),l=L.RotationQuaternionFromAxis(s,r,i),h=L.RotationQuaternionFromAxis(o,a,n);L.Slerp(l,h,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class $s{static CreateQuadraticBezier(e,t,i,s){s=s>2?s:3;const r=[],n=(e,t,i,s)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*s;for(let o=0;o<=s;o++)r.push(new w(n(o/s,e.x,t.x,i.x),n(o/s,e.y,t.y,i.y),n(o/s,e.z,t.z,i.z)));return new $s(r)}static CreateCubicBezier(e,t,i,s,r){r=r>3?r:4;const n=[],o=(e,t,i,s,r)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*s+e*e*e*r;for(let a=0;a<=r;a++)n.push(new w(o(a/r,e.x,t.x,i.x,s.x),o(a/r,e.y,t.y,i.y,s.y),o(a/r,e.z,t.z,i.z,s.z)));return new $s(n)}static CreateHermiteSpline(e,t,i,s,r){const n=[],o=1/r;for(let a=0;a<=r;a++)n.push(w.Hermite(e,t,i,s,a*o));return new $s(n)}static CreateCatmullRomSpline(e,t,i){const s=[],r=1/t;let n=0;if(i){const i=e.length;for(let o=0;o=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}Ks.EASINGMODE_EASEIN=0,Ks.EASINGMODE_EASEOUT=1,Ks.EASINGMODE_EASEINOUT=2;class qs extends Ks{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class Qs extends Ks{easeInCore(e){return e*e}}class Zs extends Ks{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class Js{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class er{get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this.syncWithMask(!0))}syncWithMask(e=!1){if(this.mask||e){this._numActiveAnimatables=0;for(let e=0;e0)){for(let e=0;en&&(n=t.to);const o=new er(e[0].name+"_merged",e[0]._scene,s);for(const s of e){i&&s.normalize(r,n);for(const e of s.targetedAnimations)o.addTargetedAnimation(e.animation,e.target);t&&s.dispose()}return o}constructor(e,t=null,i=-1,s=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._parentContainer=null,this.onAnimationEndObservable=new g,this.onAnimationLoopObservable=new g,this.onAnimationGroupLoopObservable=new g,this.onAnimationGroupEndObservable=new g,this.onAnimationGroupPauseObservable=new g,this.onAnimationGroupPlayObservable=new g,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||y.LastCreatedScene,this._weight=i,this._playOrder=s,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new Js;i.animation=e,i.target=t;const s=e.getKeys();return this._from>s[0].frame&&(this._from=s[0].frame),this._to-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;ie){const t={frame:e,value:r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation};s.splice(0,0,t)}if(n.frame{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,s,r){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(a)},this._processLoop(a,o,n),this._animatables.push(a)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e0&&(this._scene._activeAnimatables[t++]=i)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const e=this._parentContainer.animationGroups.indexOf(this);e>-1&&this._parentContainer.animationGroups.splice(e,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e){const t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const s=new er(e||this.name,this._scene,this._weight,this._playOrder);s._from=this.from,s._to=this.to,s._speedRatio=this.speedRatio,s._loopAnimation=this.loopAnimation,s._isAdditive=this.isAdditive,s._enableBlending=this.enableBlending,s._blendingSpeed=this.blendingSpeed,s.metadata=this.metadata,s.mask=this.mask;for(const e of this._targetedAnimations)s.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return s}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;tr[0].frame&&(e=r[0].frame),t=t&&e<=i||r&&s.frame>=t&&s.frame<=i){const e={frame:s.frame,value:s.value.clone?s.value.clone():s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation,lockedTangent:s.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,u.push(e)}}0!==u.length?(n>u[0].frame&&(n=u[0].frame),o{s.value=void 0,t(s)}),i):t(s)}catch(e){i(e)}}function ir(e,t,i,s,r){const n=()=>{let o;const a=e=>{e.done?i(e.value):void 0===o?o=!0:n()};do{o=void 0,r&&r.aborted?s(new Error("Aborted")):t(e,a,s),void 0===o&&(o=!1)}while(o)};n()}function sr(e,t){let i;return ir(e,tr,(e=>i=e),(e=>{throw e}),t),i}function rr(e,t,i){return new Promise(((s,r)=>{ir(e,t,s,r,i)}))}!function(e){e[e.Include=0]="Include",e[e.Exclude=1]="Exclude"}(Vs||(Vs={}));class nr{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new nr(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new nr(this.x,this.y,this.width,this.height)}}class or extends De{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){let e=0,t=0;if(this.mode===or.PERSPECTIVE_CAMERA)this.fovMode===or.FOVMODE_VERTICAL_FIXED?(t=2*this.minZ*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=2*this.minZ*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const i=this.getEngine().getRenderWidth()/2,s=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??s)-(this.orthoBottom??-s)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,s=!0){super(e,i,!1),this._position=w.Zero(),this._upVector=w.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=or.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new nr(0,0,1,1),this.layerMask=268435455,this.fovMode=or.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=or.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new g,this.onProjectionMatrixChangedObservable=new g,this.onAfterCheckInputsObservable=new g,this.onRestoreStateObservable=new g,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new B,this._postProcesses=new Array,this._activeMeshes=new Mi(256),this._globalPosition=w.Zero(),this._computedViewMatrix=B.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=B.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=L.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),s&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i-1?(J.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))}detachPostProcess(e){const t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()||this.getViewMatrix(),this._worldMatrix}_getViewMatrix(){return B.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix)),this._computedViewMatrix}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const t=this.getEngine(),i=this.getScene(),s=t.useReverseDepthBuffer;if(this.mode===or.PERSPECTIVE_CAMERA){let e;this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=t.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),e=i.useRightHandedSystem?B.PerspectiveFovRHToRef:B.PerspectiveFovLHToRef,e(this.fov,t.getAspectRatio(this),s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===or.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{const e=t.getRenderWidth()/2,r=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?B.ObliqueOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):B.OrthoOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?B.ObliqueOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):B.OrthoOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=this.oblique?.angle,this._cache.obliqueLength=this.oblique?.length,this._cache.obliqueOffset=this.oblique?.offset,this._cache.renderWidth=t.getRenderWidth(),this._cache.renderHeight=t.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){return(this.radius||(this.target?w.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?Ms.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Ms.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;return this.rigCameras.forEach((i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)})),t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw ye("Ray")}getForwardRayToRef(e,t=100,i,s){throw ye("Ray")}dispose(e,t=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){const e=this._parentContainer.cameras.indexOf(this);e>-1&&this._parentContainer.cameras.splice(e,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==or.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){const t=this._postProcesses[e];t&&t.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),super.dispose(e,t)}get isLeftCamera(){return this._isLeftCamera}get isRightCamera(){return this._isRightCamera}get leftCamera(){return this._rigCameras.length<1?null:this._rigCameras[0]}get rightCamera(){return this._rigCameras.length<2?null:this._rigCameras[1]}getLeftTarget(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()}getRightTarget(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()}setCameraRigMode(e,t){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=Ii.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==or.RIG_MODE_NONE){const e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);const t=this.createRigCamera(this.name+"_R",1);t&&(t._isRightCamera=!0),e&&t&&(this._rigCameras.push(e),this._rigCameras.push(t))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return B.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=Ii.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eor._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=or.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=Pe.Parse(s,e,t);if(void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=w.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(w.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(w.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t{throw ye("UniversalCamera")},or.PERSPECTIVE_CAMERA=0,or.ORTHOGRAPHIC_CAMERA=1,or.FOVMODE_VERTICAL_FIXED=0,or.FOVMODE_HORIZONTAL_FIXED=1,or.RIG_MODE_NONE=0,or.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,or.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,or.RIG_MODE_STEREOSCOPIC_INTERLACED=14,or.RIG_MODE_VR=20,or.RIG_MODE_CUSTOM=22,or.ForceAttachControlToAlwaysPreventDefault=!1,ae([ve("position")],or.prototype,"_position",void 0),ae([ve("upVector")],or.prototype,"_upVector",void 0),ae([pe()],or.prototype,"orthoLeft",null),ae([pe()],or.prototype,"orthoRight",null),ae([pe()],or.prototype,"orthoBottom",null),ae([pe()],or.prototype,"orthoTop",null),ae([pe()],or.prototype,"fov",void 0),ae([pe()],or.prototype,"projectionPlaneTilt",void 0),ae([pe()],or.prototype,"minZ",void 0),ae([pe()],or.prototype,"maxZ",void 0),ae([pe()],or.prototype,"inertia",void 0),ae([pe()],or.prototype,"mode",null),ae([pe()],or.prototype,"layerMask",void 0),ae([pe()],or.prototype,"fovMode",void 0),ae([pe()],or.prototype,"cameraRigMode",void 0),ae([pe()],or.prototype,"interaxialDistance",void 0),ae([pe()],or.prototype,"isStereoscopicSideBySide",void 0);class ar{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class lr{constructor(e,t,i){this.vectors=S.BuildArray(8,w.Zero),this.center=w.Zero(),this.centerWorld=w.Zero(),this.extendSize=w.Zero(),this.extendSizeWorld=w.Zero(),this.directions=S.BuildArray(3,w.Zero),this.vectorsWorld=S.BuildArray(8,w.Zero),this.minimumWorld=w.Zero(),this.maximumWorld=w.Zero(),this.minimum=w.Zero(),this.maximum=w.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,r=e.y,n=e.z,o=t.x,a=t.y,l=t.z,h=this.vectors;this.minimum.copyFromFloats(s,r,n),this.maximum.copyFromFloats(o,a,l),h[0].copyFromFloats(s,r,n),h[1].copyFromFloats(o,a,l),h[2].copyFromFloats(o,r,n),h[3].copyFromFloats(s,a,n),h[4].copyFromFloats(s,r,l),h[5].copyFromFloats(o,a,n),h[6].copyFromFloats(s,a,l),h[7].copyFromFloats(o,r,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||B.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=lr._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const r=s*e,n=i.scaleInPlace(.5*r),o=this.center.subtractToRef(n,t[1]),a=this.center.addToRef(n,t[2]);return this.reConstruct(o,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,s=this.directions,r=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)r[e].copyFrom(n[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let s=0;s<8;++s){const o=r[s];w.TransformCoordinatesToRef(n[s],e,o),t.minimizeInPlace(o),i.maximizeInPlace(o)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}w.FromArrayToRef(e.m,0,s[0]),w.FromArrayToRef(e.m,4,s[1]),w.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return lr.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return lr.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,r=t.y,n=t.z,o=i.x,a=i.y,l=i.z,h=e.x,c=e.y,u=e.z,d=-T;return!(o-hh-s||a-cc-r||l-uu-n)}intersectsSphere(e){return lr.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,r=i.x,n=i.y,o=i.z,a=s.x,l=s.y,h=s.z,c=e.x,u=e.y,d=e.z,p=t.x,f=t.y,_=t.z;return!(ap||lf||h_)}dispose(){this._drawWrapperFront?.dispose(),this._drawWrapperBack?.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const r=lr._TmpVector3[0];return w.ClampToRef(i,e,t,r),w.DistanceSquared(i,r)<=s*s}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let s=!0;const r=t[i];for(let t=0;t<8;++t)if(r.dotCoordinate(e[t])>=0){s=!1;break}if(s)return!1}return!0}}lr._TmpVector3=S.BuildArray(3,w.Zero);class hr{constructor(e,t,i){this.center=w.Zero(),this.centerWorld=w.Zero(),this.minimum=w.Zero(),this.maximum=w.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=w.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*s,this._update(i||B.IdentityReadOnly)}scale(e){const t=this.radius*e,i=hr._TmpVector3,s=i[0].setAll(t),r=this.center.subtractToRef(s,i[1]),n=this.center.addToRef(s,i[2]);return this.reConstruct(r,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{w.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=hr._TmpVector3[0];w.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,i=this.radiusWorld;for(let s=0;s<6;s++)if(e[s].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=w.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const s=w.Dot(t.centerWorld,e),r=Math.abs(w.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(w.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(w.Dot(t.directions[2],e))*t.extendSize.z;i.min=s-r,i.max=s+r},pr=(e,t,i)=>(dr(e,t,cr),dr(e,i,ur),!(cr.min>ur.max||ur.min>cr.max));class fr{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new lr(e,t,i),this.boundingSphere=new hr(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}get minimum(){return this.boundingBox.minimum}get maximum(){return this.boundingBox.maximum}get isLocked(){return this._isLocked}set isLocked(e){this._isLocked=e}update(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))}centerOn(e,t){const i=fr._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=fr._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=w.Minimize(this.minimum,e),i=w.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=U.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=U.Vector3[0];return w.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),w.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return!(2!==t&&3!==t||!this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(!(1!==t&&3!==t)||this.boundingBox.isInFrustum(e))}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,fr._TmpVector3[0]).length()}isCompletelyInFrustum(e){return this.boundingBox.isCompletelyInFrustum(e)}_checkCollision(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)}intersectsPoint(e){return!!this.boundingSphere.centerWorld&&!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e)}intersects(e,t){if(!hr.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!lr.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!!(pr(i.directions[0],i,s)&&pr(i.directions[1],i,s)&&pr(i.directions[2],i,s)&&pr(s.directions[0],i,s)&&pr(s.directions[1],i,s)&&pr(s.directions[2],i,s)&&pr(w.Cross(i.directions[0],s.directions[0]),i,s)&&pr(w.Cross(i.directions[0],s.directions[1]),i,s)&&pr(w.Cross(i.directions[0],s.directions[2]),i,s)&&pr(w.Cross(i.directions[1],s.directions[0]),i,s)&&pr(w.Cross(i.directions[1],s.directions[1]),i,s)&&pr(w.Cross(i.directions[1],s.directions[2]),i,s)&&pr(w.Cross(i.directions[2],s.directions[0]),i,s)&&pr(w.Cross(i.directions[2],s.directions[1]),i,s)&&pr(w.Cross(i.directions[2],s.directions[2]),i,s))}}fr._TmpVector3=S.BuildArray(2,w.Zero);class _r{static extractMinAndMaxIndexed(e,t,i,s,r,n){for(let o=i;o!Array.isArray(e)&&!Array.isArray(t)))],_r,"extractMinAndMaxIndexed",null),ae([be.filter(((...[e])=>!Array.isArray(e)))],_r,"extractMinAndMax",null);class gr{static GetEffect(e){return void 0===e.getPipelineContext?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){this.effect=e,void 0!==t&&(this.defines=t),i&&this.drawContext?.reset()}dispose(){this.drawContext?.dispose()}}class vr{get materialDefines(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:this._getDrawWrapper()?.defines}set materialDefines(e){(this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new gr(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){t&&this._drawWrappers[e]?.dispose(),this._drawWrappers[e]=void 0}get effect(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:this._getDrawWrapper()?.effect??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,s=!0){const r=this._drawWrapper;r.setEffect(e,t,s),void 0!==i&&(r.materialContext=i),e||(r.defines=null,r.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)e?.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,s,r,n,o,a=!0){return new vr(e,t,i,s,r,n,o,a)}constructor(e,t,i,s,r,n,o,a=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=s,this.indexCount=r,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=o||n,l&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,a&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){return(this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null)||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(!t)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(t)){const e=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return t}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(Ki.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();i={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else i=function(e,t,i,s,r=null){const n=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new w(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return _r.extractMinAndMaxIndexed(e,t,i,s,n,o),r&&(n.x-=n.x*r.x+r.y,n.y-=n.y*r.x+r.y,n.z-=n.z*r.x+r.y,o.x+=o.x*r.x+r.y,o.y+=o.y*r.x+r.y,o.z+=o.z*r.x+r.y),{minimum:n,maximum:o}}(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new fr(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const i=[];for(let t=this.indexStart;ta&&(a=t)}return new vr(e,o,a-o+1,t,i,s,r,n)}}class xr{}class Tr{constructor(){var e;this.uniqueId=0,this.metadata={},this._applyTo=(e=this._applyToCoroutine.bind(this),(...t)=>sr(e(...t),undefined)),this.uniqueId=Tr._UniqueIDGenerator,Tr._UniqueIDGenerator++}set(e,t){switch(e.length||J.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case Ki.PositionKind:this.positions=e;break;case Ki.NormalKind:this.normals=e;break;case Ki.TangentKind:this.tangents=e;break;case Ki.UVKind:this.uvs=e;break;case Ki.UV2Kind:this.uvs2=e;break;case Ki.UV3Kind:this.uvs3=e;break;case Ki.UV4Kind:this.uvs4=e;break;case Ki.UV5Kind:this.uvs5=e;break;case Ki.UV6Kind:this.uvs6=e;break;case Ki.ColorKind:this.colors=e;break;case Ki.MatricesIndicesKind:this.matricesIndices=e;break;case Ki.MatricesWeightsKind:this.matricesWeights=e;break;case Ki.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case Ki.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){if(this.positions&&(e.setVerticesData(Ki.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(Ki.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(Ki.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(Ki.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(Ki.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(Ki.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(Ki.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(Ki.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(Ki.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(Ki.ColorKind,this.colors,t),this.hasVertexAlpha&&void 0!==e.hasVertexAlpha&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(Ki.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(Ki.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(Ki.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(Ki.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){const t=e;t.subMeshes=[];for(const e of this.materialInfos)new vr(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,t)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(Ki.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(Ki.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(Ki.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(Ki.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(Ki.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(Ki.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(Ki.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(Ki.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(Ki.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(Ki.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(Ki.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(Ki.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(Ki.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(Ki.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const r=U.Vector3[0],n=U.Vector3[1];for(let o=i;o({vertexData:e}))):[{vertexData:e}];return sr(this._mergeCoroutine(void 0,n,t,!1,i,s,r))}*_mergeCoroutine(e,t,i=!1,s,r,n=!1,o=!1){this._validate();let a=t.map((e=>e.vertexData)),l=this;if(o)for(const e of a)e&&(e._validate(),!this.normals&&e.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&e.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&e.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&e.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&e.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&e.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&e.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&e.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&e.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&e.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&e.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&e.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&e.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const e of a)if(e)if(o)this.normals&&!e.normals&&(e.normals=new Float32Array(e.positions.length)),this.tangents&&!e.tangents&&(e.tangents=new Float32Array(e.positions.length/3*4)),this.uvs&&!e.uvs&&(e.uvs=new Float32Array(e.positions.length/3*2)),this.uvs2&&!e.uvs2&&(e.uvs2=new Float32Array(e.positions.length/3*2)),this.uvs3&&!e.uvs3&&(e.uvs3=new Float32Array(e.positions.length/3*2)),this.uvs4&&!e.uvs4&&(e.uvs4=new Float32Array(e.positions.length/3*2)),this.uvs5&&!e.uvs5&&(e.uvs5=new Float32Array(e.positions.length/3*2)),this.uvs6&&!e.uvs6&&(e.uvs6=new Float32Array(e.positions.length/3*2)),this.colors&&!e.colors&&(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)),this.matricesIndices&&!e.matricesIndices&&(e.matricesIndices=new Float32Array(e.positions.length/3*4)),this.matricesWeights&&!e.matricesWeights&&(e.matricesWeights=new Float32Array(e.positions.length/3*4)),this.matricesIndicesExtra&&!e.matricesIndicesExtra&&(e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4)),this.matricesWeightsExtra&&!e.matricesWeightsExtra&&(e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4));else if(e._validate(),!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");if(n){let i=0,s=0,r=0;const n=[];let o=null;const h=[];for(const t of this.splitBasedOnMaterialID())h.push({vertexData:t,transform:e});for(const e of t)if(e.vertexData)for(const t of e.vertexData.splitBasedOnMaterialID())h.push({vertexData:t,transform:e.transform});h.sort(((e,t)=>{const i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,s=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>s?1:i===s?0:-1}));for(const e of h){const t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,o&&o.materialIndex===i)o.indexCount+=t.indices.length,o.verticesCount+=t.positions.length/3;else{const e=new xr;e.materialIndex=i,e.indexStart=s,e.indexCount=t.indices.length,e.verticesStart=r,e.verticesCount=t.positions.length/3,n.push(e),o=e}s+=t.indices.length,r+=t.positions.length/3}const c=h.splice(0,1)[0];l=c.vertexData,e=c.transform,a=h.map((e=>e.vertexData)),t=h,this.materialInfos=n}const h=a.reduce(((e,t)=>e+(t.indices?.length??0)),l.indices?.length??0);let c=r||a.some((e=>e.indices===l.indices))?l.indices?.slice():l.indices;if(h>0){let r=c?.length??0;if(c||(c=new Array(h)),c.length!==h){if(Array.isArray(c))c.length=h;else{const e=i||c instanceof Uint32Array?new Uint32Array(h):new Uint16Array(h);e.set(c),c=e}e&&e.determinant()<0&&Tr._FlipFaces(c,0,r)}let n=l.positions?l.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t[e.vertexData.positions,e.transform]))),s&&(yield),l.normals&&(this.normals=Tr._MergeElement(Ki.NormalKind,l.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),s&&(yield)),l.tangents&&(this.tangents=Tr._MergeElement(Ki.TangentKind,l.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),s&&(yield)),l.uvs&&(this.uvs=Tr._MergeElement(Ki.UVKind,l.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),s&&(yield)),l.uvs2&&(this.uvs2=Tr._MergeElement(Ki.UV2Kind,l.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),s&&(yield)),l.uvs3&&(this.uvs3=Tr._MergeElement(Ki.UV3Kind,l.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),s&&(yield)),l.uvs4&&(this.uvs4=Tr._MergeElement(Ki.UV4Kind,l.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),s&&(yield)),l.uvs5&&(this.uvs5=Tr._MergeElement(Ki.UV5Kind,l.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),s&&(yield)),l.uvs6&&(this.uvs6=Tr._MergeElement(Ki.UV6Kind,l.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),s&&(yield)),l.colors&&(this.colors=Tr._MergeElement(Ki.ColorKind,l.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),(void 0!==l.hasVertexAlpha||t.some((e=>void 0!==e.vertexData.hasVertexAlpha)))&&(this.hasVertexAlpha=l.hasVertexAlpha||t.some((e=>e.vertexData.hasVertexAlpha))),s&&(yield)),l.matricesIndices&&(this.matricesIndices=Tr._MergeElement(Ki.MatricesIndicesKind,l.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),s&&(yield)),l.matricesWeights&&(this.matricesWeights=Tr._MergeElement(Ki.MatricesWeightsKind,l.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),s&&(yield)),l.matricesIndicesExtra&&(this.matricesIndicesExtra=Tr._MergeElement(Ki.MatricesIndicesExtraKind,l.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),s&&(yield)),l.matricesWeightsExtra&&(this.matricesWeightsExtra=Tr._MergeElement(Ki.MatricesWeightsExtraKind,l.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform])))),this}static _MergeElement(e,t,i,s){const r=s.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==r.length)return t;if(!t)return this._MergeElement(e,r[0][0],r[0][1],r.slice(1));const n=r.reduce(((e,t)=>e+t[0].length),t.length),o=e===Ki.PositionKind?Tr._TransformVector3Coordinates:e===Ki.NormalKind?Tr._TransformVector3Normals:e===Ki.TangentKind?Tr._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(n);e.set(t),i&&o(e,i,0,t.length);let s=t.length;for(const[t,i]of r)e.set(t,s),i&&o(e,i,s,t.length),s+=t.length;return e}{const e=new Array(n);for(let i=0;i{const i=Ki.DeduceStride(e);if(t.length%i!=0)throw new Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(Ki.PositionKind,this.positions),i=(i,s)=>{const r=e(i,s);if(r!==t)throw new Error("The "+i+"s element count ("+r+") does not match the positions count ("+t+")")};this.normals&&i(Ki.NormalKind,this.normals),this.tangents&&i(Ki.TangentKind,this.tangents),this.uvs&&i(Ki.UVKind,this.uvs),this.uvs2&&i(Ki.UV2Kind,this.uvs2),this.uvs3&&i(Ki.UV3Kind,this.uvs3),this.uvs4&&i(Ki.UV4Kind,this.uvs4),this.uvs5&&i(Ki.UV5Kind,this.uvs5),this.uvs6&&i(Ki.UV6Kind,this.uvs6),this.colors&&i(Ki.ColorKind,this.colors),this.matricesIndices&&i(Ki.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(Ki.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(Ki.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(Ki.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return Tr.Parse(e)}serialize(){const e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos){e.materialInfos=[];for(const t of this.materialInfos){const i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return Tr._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return Tr._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new Tr;return e.isVerticesDataPresent(Ki.PositionKind)&&(s.positions=e.getVerticesData(Ki.PositionKind,t,i)),e.isVerticesDataPresent(Ki.NormalKind)&&(s.normals=e.getVerticesData(Ki.NormalKind,t,i)),e.isVerticesDataPresent(Ki.TangentKind)&&(s.tangents=e.getVerticesData(Ki.TangentKind,t,i)),e.isVerticesDataPresent(Ki.UVKind)&&(s.uvs=e.getVerticesData(Ki.UVKind,t,i)),e.isVerticesDataPresent(Ki.UV2Kind)&&(s.uvs2=e.getVerticesData(Ki.UV2Kind,t,i)),e.isVerticesDataPresent(Ki.UV3Kind)&&(s.uvs3=e.getVerticesData(Ki.UV3Kind,t,i)),e.isVerticesDataPresent(Ki.UV4Kind)&&(s.uvs4=e.getVerticesData(Ki.UV4Kind,t,i)),e.isVerticesDataPresent(Ki.UV5Kind)&&(s.uvs5=e.getVerticesData(Ki.UV5Kind,t,i)),e.isVerticesDataPresent(Ki.UV6Kind)&&(s.uvs6=e.getVerticesData(Ki.UV6Kind,t,i)),e.isVerticesDataPresent(Ki.ColorKind)&&(s.colors=e.getVerticesData(Ki.ColorKind,t,i)),e.isVerticesDataPresent(Ki.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(Ki.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(Ki.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(Ki.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(Ki.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(Ki.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(Ki.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(Ki.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw ye("ribbonBuilder")}static CreateBox(e){throw ye("boxBuilder")}static CreateTiledBox(e){throw ye("tiledBoxBuilder")}static CreateTiledPlane(e){throw ye("tiledPlaneBuilder")}static CreateSphere(e){throw ye("sphereBuilder")}static CreateCylinder(e){throw ye("cylinderBuilder")}static CreateTorus(e){throw ye("torusBuilder")}static CreateLineSystem(e){throw ye("linesBuilder")}static CreateDashedLines(e){throw ye("linesBuilder")}static CreateGround(e){throw ye("groundBuilder")}static CreateTiledGround(e){throw ye("groundBuilder")}static CreateGroundFromHeightMap(e){throw ye("groundBuilder")}static CreatePlane(e){throw ye("planeBuilder")}static CreateDisc(e){throw ye("discBuilder")}static CreatePolygon(e,t,i,s,r,n,o){throw ye("polygonBuilder")}static CreateIcoSphere(e){throw ye("icoSphereBuilder")}static CreatePolyhedron(e){throw ye("polyhedronBuilder")}static CreateCapsule(e={orientation:w.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw ye("capsuleBuilder")}static CreateTorusKnot(e){throw ye("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let r=0,n=0,o=0,a=0,l=0,h=0,c=0,u=0,d=0,p=0,f=0,_=0,m=0,g=0,v=0,x=0,T=0,S=0,E=0,b=0,C=!1,y=!1,A=!1,R=!1,I=1,P=0,M=null;s&&(C=!!s.facetNormals,y=!!s.facetPositions,A=!!s.facetPartitioning,I=!0===s.useRightHandedSystem?-1:1,P=s.ratio||0,R=!!s.depthSort,M=s.distanceTo,R&&void 0===M&&(M=w.Zero()));let D=0,O=0,N=0,F=0;for(A&&s&&s.bbSize&&(D=s.subDiv.X*P/s.bbSize.x,O=s.subDiv.Y*P/s.bbSize.y,N=s.subDiv.Z*P/s.bbSize.z,F=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),r=0;r!Array.isArray(e)))],Tr,"_TransformVector3Coordinates",null),ae([be.filter(((...[e])=>!Array.isArray(e)))],Tr,"_TransformVector3Normals",null),ae([be.filter(((...[e])=>!Array.isArray(e)))],Tr,"_TransformVector4Normals",null),ae([be.filter(((...[e])=>!Array.isArray(e)))],Tr,"_FlipFaces",null);class Sr{static get ForceFullSceneLoadingForIncremental(){return Sr._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Sr._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Sr._ShowLoadingScreen}static set ShowLoadingScreen(e){Sr._ShowLoadingScreen=e}static get loggingLevel(){return Sr._LoggingLevel}static set loggingLevel(e){Sr._LoggingLevel=e}static get CleanBoneMatrixWeights(){return Sr._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Sr._CleanBoneMatrixWeights=e}}Sr._ForceFullSceneLoadingForIncremental=!1,Sr._ShowLoadingScreen=!0,Sr._CleanBoneMatrixWeights=!1,Sr._LoggingLevel=0;class Er{}Er.UseOpenGLOrientationForUV=!1;class br{get boundingBias(){return this._boundingBias}set boundingBias(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)}static CreateGeometryForMesh(e){const t=new br(br.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,s=!1,r=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||y.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=s,i?this.setAllVerticesData(i,s):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e{e._rebuild()}))}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,s){i&&Array.isArray(t)&&(t=new Float32Array(t));const r=new Ki(this._engine,t,e,{updatable:i,postponeInternalCreation:0===this._meshes.length,stride:s,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(r)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const s=e.getKind();this._vertexBuffers[s]&&i&&this._vertexBuffers[s].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[s]=e;const r=this._meshes,n=r.length;if(s===Ki.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const i=this._extend&&this._extend.minimum||new w(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),s=this._extend&&this._extend.maximum||new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e65535);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),null!=t&&(this._totalVertices=t);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?void 0!==this._totalIndices?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){e&&this._vertexArrayObjects&&this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const i=this._meshes,s=i.indexOf(e);-1!==s&&(i.splice(s,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;const t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();const i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&!(e=this.getVerticesData(Ki.PositionKind)))return;this._extend=mr(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===Ki.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const e of this._meshes)e._markSubMeshesAsAttributesDirty()}load(e,t){2!==this.delayLoadState&&(this.isReady()?t&&t():(this.delayLoadState=2,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const s=this._meshes,r=s.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new Tr;t.indices=[];const i=this.getIndices();if(i)for(let e=0;e0){const s=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(Ki.PositionKind,s,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const s=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(Ki.NormalKind,s,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const s=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(Ki.TangentKind,s,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const s=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(Er.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(Er.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(Er.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(Er.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(Er.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(Er.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(Ki.ColorKind,s,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(Ki.MatricesIndicesKind,r,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(Ki.MatricesIndicesExtraKind,r,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const s=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(Ki.MatricesWeightsKind,s,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){const s=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(s,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){const s=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(Ki.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(Ki.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(Ki.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(br._CleanMatricesWeights(e,t),t.setVerticesData(Ki.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(Ki.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;s=i.bones.length}const r=t.getVerticesData(Ki.MatricesIndicesKind),n=t.getVerticesData(Ki.MatricesIndicesExtraKind),o=e.matricesWeights,a=e.matricesWeightsExtra,l=e.numBoneInfluencer,h=o.length;for(let e=0;el-1)&&(h=l-1),t>i){const i=1/t;for(let t=0;t<4;t++)o[e+t]*=i;if(a)for(let t=0;t<4;t++)a[e+t]*=i}else h>=4?(a[e+h-4]=1-t,n[e+h-4]=s):(o[e+h]=1-t,r[e+h]=s)}t.setVerticesData(Ki.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(Ki.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const s=new br(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,Re&&Re.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new fr(w.FromArray(e.boundingBoxMinimum),w.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(Ki.UVKind),e.hasUVs2&&s._delayInfo.push(Ki.UV2Kind),e.hasUVs3&&s._delayInfo.push(Ki.UV3Kind),e.hasUVs4&&s._delayInfo.push(Ki.UV4Kind),e.hasUVs5&&s._delayInfo.push(Ki.UV5Kind),e.hasUVs6&&s._delayInfo.push(Ki.UV6Kind),e.hasColors&&s._delayInfo.push(Ki.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(Ki.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(Ki.MatricesWeightsKind),s._delayLoadingFunction=Tr.ImportVertexData):Tr.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}class Cr{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new yr(e)}sampleFrame(e=je.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){const t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}}get averageFrameTime(){return this._rollingFrameTime.average}get averageFrameTimeVariance(){return this._rollingFrameTime.variance}get instantaneousFrameTime(){return this._rollingFrameTime.history(0)}get averageFPS(){return 1e3/this._rollingFrameTime.average}get instantaneousFPS(){const e=this._rollingFrameTime.history(0);return 0===e?0:1e3/e}get isSaturated(){return this._rollingFrameTime.isSaturated()}enable(){this._enabled=!0}disable(){this._enabled=!1,this._lastFrameTimeMs=null}get isEnabled(){return this._enabled}reset(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()}}class yr{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const e=this._samples[this._pos];t=e-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(e-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length}history(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;const t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]}isSaturated(){return this._sampleCount>=this._samples.length}reset(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0}_wrapPosition(e){const t=this._samples.length;return(e%t+t)%t}}function Ar(e,t,i=!1,s){switch(e){case 3:{const e=(ArrayBuffer,new Int8Array(t));return s&&e.set(new Int8Array(s)),e}case 0:{const e=(ArrayBuffer,new Uint8Array(t));return s&&e.set(new Uint8Array(s)),e}case 4:{const e=t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);return s&&e.set(new Int16Array(s)),e}case 5:case 8:case 9:case 10:case 2:{const e=t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);return s&&e.set(new Uint16Array(s)),e}case 6:{const e=t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);return s&&e.set(new Int32Array(s)),e}case 7:case 11:case 12:case 13:case 14:case 15:{const e=t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);return s&&e.set(new Uint32Array(s)),e}case 1:{const e=t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t);return s&&e.set(new Float32Array(s)),e}}const r=(ArrayBuffer,new Uint8Array(t));return s&&r.set(new Uint8Array(s)),r}function Rr(e,t,i){e._onCanvasFocus=()=>{e.onCanvasFocusObservable.notifyObservers(e)},e._onCanvasBlur=()=>{e.onCanvasBlurObservable.notifyObservers(e)},e._onCanvasContextMenu=t=>{e.disableContextMenu&&t.preventDefault()},t.addEventListener("focus",e._onCanvasFocus),t.addEventListener("blur",e._onCanvasBlur),t.addEventListener("contextmenu",e._onCanvasContextMenu),e._onBlur=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.disable(),e._windowIsBackground=!0},e._onFocus=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.enable(),e._windowIsBackground=!1},e._onCanvasPointerOut=i=>{document.elementFromPoint(i.clientX,i.clientY)!==t&&e.onCanvasPointerOutObservable.notifyObservers(i)};const s=e.getHostWindow();s&&"function"==typeof s.addEventListener&&(s.addEventListener("blur",e._onBlur),s.addEventListener("focus",e._onFocus)),t.addEventListener("pointerout",e._onCanvasPointerOut),i.doNotHandleTouchAction||function(e){e&&e.setAttribute&&(e.setAttribute("touch-action","none"),e.style.touchAction="none",e.style.webkitTapHighlightColor="transparent")}(t),!si.audioEngine&&i.audioEngine&&si.AudioEngineFactory&&(si.audioEngine=si.AudioEngineFactory(e.getRenderingCanvas(),e.getAudioContext(),e.getAudioDestination())),Xe()&&(e._onFullscreenChange=()=>{e.isFullscreen=!!document.fullscreenElement,e.isFullscreen&&e._pointerLockRequested&&t&&wr(t)},document.addEventListener("fullscreenchange",e._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",e._onFullscreenChange,!1),e._onPointerLockChange=()=>{e.isPointerLock=document.pointerLockElement===t},document.addEventListener("pointerlockchange",e._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",e._onPointerLockChange,!1)),e.enableOfflineSupport=void 0!==si.OfflineProviderFactory,e._deterministicLockstep=!!i.deterministicLockstep,e._lockstepMaxSteps=i.lockstepMaxSteps||0,e._timeStep=i.timeStep||1/60}function Ir(e,t){1===y.Instances.length&&si.audioEngine&&(si.audioEngine.dispose(),si.audioEngine=null);const i=e.getHostWindow();i&&"function"==typeof i.removeEventListener&&(i.removeEventListener("blur",e._onBlur),i.removeEventListener("focus",e._onFocus)),t&&(t.removeEventListener("focus",e._onCanvasFocus),t.removeEventListener("blur",e._onCanvasBlur),t.removeEventListener("pointerout",e._onCanvasPointerOut),t.removeEventListener("contextmenu",e._onCanvasContextMenu)),Xe()&&(document.removeEventListener("fullscreenchange",e._onFullscreenChange),document.removeEventListener("mozfullscreenchange",e._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",e._onFullscreenChange),document.removeEventListener("msfullscreenchange",e._onFullscreenChange),document.removeEventListener("pointerlockchange",e._onPointerLockChange),document.removeEventListener("mspointerlockchange",e._onPointerLockChange),document.removeEventListener("mozpointerlockchange",e._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",e._onPointerLockChange))}function Pr(e){const t=document.createElement("span");t.textContent="Hg",t.style.font=e;const i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";const s=document.createElement("div");s.style.whiteSpace="nowrap",s.appendChild(t),s.appendChild(i),document.body.appendChild(s);let r=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",r=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(s)}return{ascent:r,height:n,descent:n-r}}function Mr(e,t,i){return new Promise(((s,r)=>{const n=new Image;n.onload=()=>{n.decode().then((()=>{e.createImageBitmap(n,i).then((e=>{s(e)}))}))},n.onerror=()=>{r(`Error loading image ${n.src}`)},n.src=t}))}function Dr(e,t,i,s){const r=e.createCanvas(i,s).getContext("2d");if(!r)throw new Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(t,0,0),r.getImageData(0,0,i,s).data}function Or(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}function Nr(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}function wr(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}function Fr(){document.exitPointerLock&&document.exitPointerLock()}Yi.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode!==e){switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0}t||(this.depthCullingState.depthMask=0===e),this._alphaMode=e}else if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}},Yi.prototype._readTexturePixelsSync=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=c.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),s>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+s,e._hardwareTexture?.underlyingResource,r):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,e._hardwareTexture?.underlyingResource,r);let u=void 0!==e.type?this._getWebGLTextureType(e.type):c.UNSIGNED_BYTE;return a?n||(n=Ar(e.type,4*t*i)):u===c.UNSIGNED_BYTE?(n||(n=new Uint8Array(4*t*i)),u=c.UNSIGNED_BYTE):(n||(n=new Float32Array(4*t*i)),u=c.FLOAT),o&&this.flushFramebuffer(),c.readPixels(l,h,t,i,c.RGBA,u,n),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),n},Yi.prototype._readTexturePixels=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,s,r,n,o,a,l,h))},Yi.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let s;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),s=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,s,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},Yi.prototype.updateDynamicVertexBuffer=function(e,t,i,s){this.bindArrayBuffer(e),void 0===i&&(i=0);const r=t.byteLength||t.length;void 0===s||s>=r&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+s)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,s):new Uint8Array(t.buffer,t.byteOffset+i,s),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()},si.prototype.displayLoadingUI=function(){if(!We())return;const e=this.loadingScreen;e&&e.displayLoadingUI()},si.prototype.hideLoadingUI=function(){if(!We())return;const e=this._loadingScreen;e&&e.hideLoadingUI()},Object.defineProperty(si.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=si.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(si.prototype,"loadingUIText",{set:function(e){this.loadingScreen.loadingUIText=e},enumerable:!0,configurable:!0}),Object.defineProperty(si.prototype,"loadingUIBackgroundColor",{set:function(e){this.loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),si.prototype.getInputElement=function(){return this._renderingCanvas},si.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null},si.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null},si.prototype.getAspectRatio=function(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)},si.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)},si.prototype._verifyPointerLock=function(){this._onPointerLockChange?.()},si.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774)}this._alphaEquation=e}},si.prototype.getInputElement=function(){return this._renderingCanvas},si.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},si.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},si.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)},si.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)},si.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)},si.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)},si.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},si.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},si.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},si.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},si.prototype.getStencilMask=function(){return this._stencilState.stencilMask},si.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},si.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},si.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},si.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},si.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},si.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},si.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},si.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},si.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},si.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},si.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},si.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},si.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},si.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()},si.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)},si.prototype.setAlphaConstants=function(e,t,i,s){this._alphaState.setAlphaBlendConstants(e,t,i,s)},si.prototype.getAlphaMode=function(){return this._alphaMode},si.prototype.getAlphaEquation=function(){return this._alphaEquation},si.prototype.getRenderPassNames=function(){return this._renderPassNames},si.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]},si.prototype.createRenderPassId=function(e){const t=++si._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t},si.prototype.releaseRenderPassId=function(e){this._renderPassNames[e]=void 0;for(let t=0;tnew Lr(e,t,i);class Lr{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new g,this.onAudioLockedObservable=new g,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!We())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);const s=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{s&&s.canPlayType&&(s.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||s.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{s&&s.canPlayType&&s.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){if("running"===this._audioContext?.state)return this._hideMuteButton(),void(this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)));this._tryToRun?this._audioContext?.suspend().then((()=>{this._tryToRun=!1,this._triggerRunningState()})):this._triggerRunningState()}_resumeAudioContext(){return this._audioContext?.resume?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,J.Error("Web Audio: "+e.message)}}_triggerRunningState(){this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then((()=>{this._tryToRun=!1,this._muteButton&&this._hideMuteButton(),this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)})).catch((()=>{this._tryToRun=!1,this.unlocked=!1})))}_triggerSuspendedState(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()}_displayMuteButton(){if(this.useCustomUnlockedButton||this._muteButton)return;this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";const e=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",(()=>{this._triggerRunningState()}),!0),this._muteButton.addEventListener("click",(()=>{this.unlock()}),!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}}class Br extends Yi{static get NpmPackage(){return si.NpmPackage}static get Version(){return si.Version}static get Instances(){return y.Instances}static get LastCreatedEngine(){return y.LastCreatedEngine}static get LastCreatedScene(){return y.LastCreatedScene}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{this._loadFile(e,(e=>{s(e)}),void 0,t,i,((e,t)=>{r(t)}))}))}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return Pr(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(0!==this._frameHandler){this._frameHandler=0;const{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}enterPointerlock(){this._renderingCanvas&&wr(this._renderingCanvas)}exitPointerlock(){Fr()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){const t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,s,r,n=null){r=r||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const o=super.createShaderProgram(e,t,i,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),o}_createShaderProgram(e,t,i,s,r=null){const n=s.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");if(s.attachShader(n,t),s.attachShader(n,i),this.webGLVersion>1&&r){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=t}return s.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach((t=>{t.postProcesses.forEach((t=>{t._outputTexture===e&&(t._outputTexture=null)})),t.cameras.forEach((t=>{t._postProcesses.forEach((t=>{t&&t._outputTexture===e&&(t._outputTexture=null)}))}))}))}_rescaleTexture(e,t,i,s,r){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);const n=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&Br._RescalePostProcessFactory&&(this._rescalePostProcess=Br._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled((()=>{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let o=i;o||(o=this.scenes[this.scenes.length-1]),o.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()})))}wrapWebGLTexture(e,t=!1,i=3,s=0,r=0){const n=new Hi(e,this._gl),o=new ti(this,ei.Unknown,!0);return o._hardwareTexture=n,o.baseWidth=s,o.baseHeight=r,o.width=s,o.height=r,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,s=0){const r=this._gl,n=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,o),l=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=r.TEXTURE_2D;e.isCube&&(h=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(h,s,a,o,n,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void J.Error("WebGL 1 does not support texture comparison.");const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");const i=new Wi(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const s=this._gl;return new Promise(((r,n)=>{const o=()=>{const a=s.clientWaitSync(e,t,0);a!=s.WAIT_FAILED?a!=s.TIMEOUT_EXPIRED?r():setTimeout(o,i):n()};o()}))}_readPixelsAsync(e,t,i,s,r,n,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const a=this._gl,l=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.bufferData(a.PIXEL_PACK_BUFFER,o.byteLength,a.STREAM_READ),a.readPixels(e,t,i,s,r,n,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null);const h=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(a.flush(),this._clientWaitAsync(h,0,10).then((()=>(a.deleteSync(h),a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,o),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.deleteBuffer(l),o)))):null}dispose(){this._rescalePostProcess&&this._rescalePostProcess.dispose(),Ir(this,this._renderingCanvas),super.dispose()}}Br.ALPHA_DISABLE=0,Br.ALPHA_ADD=1,Br.ALPHA_COMBINE=2,Br.ALPHA_SUBTRACT=3,Br.ALPHA_MULTIPLY=4,Br.ALPHA_MAXIMIZED=5,Br.ALPHA_ONEONE=6,Br.ALPHA_PREMULTIPLIED=7,Br.ALPHA_PREMULTIPLIED_PORTERDUFF=8,Br.ALPHA_INTERPOLATE=9,Br.ALPHA_SCREENMODE=10,Br.DELAYLOADSTATE_NONE=0,Br.DELAYLOADSTATE_LOADED=1,Br.DELAYLOADSTATE_LOADING=2,Br.DELAYLOADSTATE_NOTLOADED=4,Br.NEVER=512,Br.ALWAYS=519,Br.LESS=513,Br.EQUAL=514,Br.LEQUAL=515,Br.GREATER=516,Br.GEQUAL=518,Br.NOTEQUAL=517,Br.KEEP=7680,Br.REPLACE=7681,Br.INCR=7682,Br.DECR=7683,Br.INVERT=5386,Br.INCR_WRAP=34055,Br.DECR_WRAP=34056,Br.TEXTURE_CLAMP_ADDRESSMODE=0,Br.TEXTURE_WRAP_ADDRESSMODE=1,Br.TEXTURE_MIRROR_ADDRESSMODE=2,Br.TEXTUREFORMAT_ALPHA=0,Br.TEXTUREFORMAT_LUMINANCE=1,Br.TEXTUREFORMAT_LUMINANCE_ALPHA=2,Br.TEXTUREFORMAT_RGB=4,Br.TEXTUREFORMAT_RGBA=5,Br.TEXTUREFORMAT_RED=6,Br.TEXTUREFORMAT_R=6,Br.TEXTUREFORMAT_RG=7,Br.TEXTUREFORMAT_RED_INTEGER=8,Br.TEXTUREFORMAT_R_INTEGER=8,Br.TEXTUREFORMAT_RG_INTEGER=9,Br.TEXTUREFORMAT_RGB_INTEGER=10,Br.TEXTUREFORMAT_RGBA_INTEGER=11,Br.TEXTURETYPE_UNSIGNED_BYTE=0,Br.TEXTURETYPE_UNSIGNED_INT=0,Br.TEXTURETYPE_FLOAT=1,Br.TEXTURETYPE_HALF_FLOAT=2,Br.TEXTURETYPE_BYTE=3,Br.TEXTURETYPE_SHORT=4,Br.TEXTURETYPE_UNSIGNED_SHORT=5,Br.TEXTURETYPE_INT=6,Br.TEXTURETYPE_UNSIGNED_INTEGER=7,Br.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,Br.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,Br.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,Br.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,Br.TEXTURETYPE_UNSIGNED_INT_24_8=12,Br.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,Br.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,Br.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,Br.TEXTURE_NEAREST_SAMPLINGMODE=1,Br.TEXTURE_BILINEAR_SAMPLINGMODE=2,Br.TEXTURE_TRILINEAR_SAMPLINGMODE=3,Br.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,Br.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,Br.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,Br.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,Br.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,Br.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,Br.TEXTURE_NEAREST_LINEAR=7,Br.TEXTURE_NEAREST_NEAREST=1,Br.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,Br.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,Br.TEXTURE_LINEAR_LINEAR=2,Br.TEXTURE_LINEAR_NEAREST=12,Br.TEXTURE_EXPLICIT_MODE=0,Br.TEXTURE_SPHERICAL_MODE=1,Br.TEXTURE_PLANAR_MODE=2,Br.TEXTURE_CUBIC_MODE=3,Br.TEXTURE_PROJECTION_MODE=4,Br.TEXTURE_SKYBOX_MODE=5,Br.TEXTURE_INVCUBIC_MODE=6,Br.TEXTURE_EQUIRECTANGULAR_MODE=7,Br.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,Br.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Br.SCALEMODE_FLOOR=1,Br.SCALEMODE_NEAREST=2,Br.SCALEMODE_CEILING=3;const Vr=B.Compose(w.One(),L.FromEulerAngles(0,Math.PI,0),w.Zero());class Ur extends De{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=!!(this._billboardMode&Ur.BILLBOARDMODE_USE_POSITION),this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==Ur.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t,!1),this._forward=new w(0,0,1),this._up=new w(0,1,0),this._right=new w(1,0,0),this._position=w.Zero(),this._rotation=w.Zero(),this._rotationQuaternion=null,this._scaling=w.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=Ur.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=B.Zero(),this._usePivotMatrix=!1,this._absolutePosition=w.Zero(),this._absoluteScaling=w.Zero(),this._absoluteRotationQuaternion=L.Identity(),this._pivotMatrix=B.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new g,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return w.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return w.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return w.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()}updatePoseMatrix(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=B.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==Ur.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this._infiniteDistance||this._position._isDirty||this._scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)}_initCache(){super._initCache();const e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1,e.useBillboardPath=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=B.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const s=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);s&&i&&i(this,s);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(s,t,i);return s}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||L.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,s;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],s=arguments[2]}else t=e.x,i=e.y,s=e.z;if(this.parent){const e=U.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),w.TransformCoordinatesFromFloatsToRef(t,i,s,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=s;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=w.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=U.Matrix[0];return this._localMatrix.invertToRef(e),w.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=w.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,r=Fs.LOCAL){const n=Ur._LookAtVectorCache,o=r===Fs.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,n),this.setDirection(n,t,i,s),r===Fs.WORLD&&this.parent)if(this.rotationQuaternion){const e=U.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=U.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=U.Quaternion[0];L.FromEulerVectorToRef(this.rotation,e);const t=U.Matrix[0];e.toRotationMatrix(t);const i=U.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=w.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return w.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,n);return this.rotationQuaternion?L.RotationYawPitchRollToRef(r+t,o+i,s,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=r+t,this.rotation.z=s),this}setPivotPoint(e,t=Fs.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==Fs.WORLD){const t=U.Matrix[0];i.invertToRef(t),e=w.TransformCoordinates(e,t)}return this.setPivotMatrix(B.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=w.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){const e=w.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),w.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;const s=U.Quaternion[0],r=U.Vector3[0],n=U.Vector3[1],o=U.Matrix[1];B.IdentityToRef(o);const a=U.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=Ur._TmpRotation,L.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),B.ComposeToRef(this.scaling,l,this.position,a),this.parent&&a.multiplyToRef(this.parent.computeWorldMatrix(!0),a),e&&(e.computeWorldMatrix(!0).invertToRef(o),a.multiplyToRef(o,a)),a.decompose(n,s,r,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(r),this.parent=e,i&&this.setPivotMatrix(B.Identity()),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=e?this._currentParentWhenAttachingToBone:null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){let s;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==Fs.LOCAL){if(this.parent){const i=this.parent.getWorldMatrix(),s=U.Matrix[0];i.invertToRef(s),e=w.TransformNormal(e,s),i.determinant()<0&&(t*=-1)}s=L.RotationAxisToRef(e,t,Ur._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else s=L.RotationAxisToRef(e,t,Ur._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=L.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=U.Vector3[0],r=U.Vector3[1],n=U.Vector3[2],o=U.Quaternion[0],a=U.Matrix[0],l=U.Matrix[1],h=U.Matrix[2],c=U.Matrix[3];return e.subtractToRef(this.position,s),B.TranslationToRef(s.x,s.y,s.z,a),B.TranslationToRef(-s.x,-s.y,-s.z,l),B.RotationAxisToRef(t,i,h),l.multiplyToRef(h,c),c.multiplyToRef(a,c),c.decompose(r,o,n),this.position.addInPlace(n),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(i&&i!==Fs.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(s));else{const e=this.getPositionExpressedInLocalSpace().add(s);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let s;this.rotationQuaternion?s=this.rotationQuaternion:(s=U.Quaternion[1],L.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const r=U.Quaternion[0];return L.RotationYawPitchRollToRef(t,e,i,r),s.multiplyInPlace(r),this.rotationQuaternion||s.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==Ur.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const r=this._getEffectiveParent(),n=Ur._TmpScaling;let o,a=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new w(e.m[12],e.m[13],e.m[14]);a=Ur._TmpTranslation,a.copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,o=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(L.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(o=Ur._TmpRotation,L.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,o)),this._usePivotMatrix){const e=U.Matrix[1];B.ScalingToRef(n.x,n.y,n.z,e);const t=U.Matrix[0];o.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,U.Matrix[4]),U.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(a.x,a.y,a.z)}else B.ComposeToRef(n,o,a,this._localMatrix);if(r&&r.getWorldMatrix){if(e&&r.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),U.Matrix[7])}else U.Matrix[7].copyFrom(r.getWorldMatrix());const e=U.Vector3[5],t=U.Vector3[6],i=U.Quaternion[0];U.Matrix[7].decompose(t,i,e),B.ScalingToRef(t.x,t.y,t.z,U.Matrix[7]),U.Matrix[7].setTranslation(e),Ur.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(U.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),U.Matrix[6]),U.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(r.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){const e=U.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),U.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&U.Matrix[1].multiplyToRef(Vr,U.Matrix[1]),U.Matrix[1].setTranslationFromFloats(0,0,0),U.Matrix[1].invertToRef(U.Matrix[0]),(this.billboardMode&Ur.BILLBOARDMODE_ALL)!==Ur.BILLBOARDMODE_ALL){U.Matrix[0].decompose(void 0,U.Quaternion[0],void 0);const e=U.Vector3[1];U.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Ur.BILLBOARDMODE_X)!==Ur.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Ur.BILLBOARDMODE_Y)!==Ur.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Ur.BILLBOARDMODE_Z)!==Ur.BILLBOARDMODE_Z&&(e.z=0),B.RotationYawPitchRollToRef(e.y,e.x,e.z,U.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(U.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(U.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const e=U.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(U.Matrix[1]);const s=U.Vector3[1];w.TransformCoordinatesToRef(i,U.Matrix[1],s),s.normalize();const r=-Math.atan2(s.z,s.x)+Math.PI/2,n=Math.sqrt(s.x*s.x+s.z*s.z),o=-Math.atan2(s.y,n);if(L.RotationYawPitchRollToRef(r,o,0,U.Quaternion[0]),(this.billboardMode&Ur.BILLBOARDMODE_ALL)!==Ur.BILLBOARDMODE_ALL){const e=U.Vector3[1];U.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Ur.BILLBOARDMODE_X)!==Ur.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Ur.BILLBOARDMODE_Y)!==Ur.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Ur.BILLBOARDMODE_Z)!==Ur.BILLBOARDMODE_Z&&(e.z=0),B.RotationYawPitchRollToRef(e.y,e.x,e.z,U.Matrix[0])}else B.FromQuaternionToRef(U.Quaternion[0],U.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(U.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(U.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):r&&r._nonUniformScaling?this._updateNonUniformScalingState(r._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=B.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;tnew Ur(e,this.getScene())),this);if(s.name=e,s.id=e,t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;inew Ur(e.name,t)),e,t,i);if(e.localMatrix?s.setPreTransformMatrix(B.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(B.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let t=0;t(!t||t(e))&&e instanceof Ur)),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const e=this.getChildTransformNodes(!0);for(const t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let s=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),o=n.max.subtract(n.min),a=Math.max(o.x,o.y,o.z);if(0===a)return this;const l=1/a;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&s&&this.rotation.copyFrom(s)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}Ur.BILLBOARDMODE_NONE=0,Ur.BILLBOARDMODE_X=1,Ur.BILLBOARDMODE_Y=2,Ur.BILLBOARDMODE_Z=4,Ur.BILLBOARDMODE_ALL=7,Ur.BILLBOARDMODE_USE_POSITION=128,Ur.BillboardUseParentOrientation=!1,Ur._TmpRotation=L.Zero(),Ur._TmpScaling=w.Zero(),Ur._TmpTranslation=w.Zero(),Ur._LookAtVectorCache=new w(0,0,0),Ur._RotationAxisCache=new L,ae([ve("position")],Ur.prototype,"_position",void 0),ae([ve("rotation")],Ur.prototype,"_rotation",void 0),ae([ue(10,"rotationQuaternion")],Ur.prototype,"_rotationQuaternion",void 0),ae([ve("scaling")],Ur.prototype,"_scaling",void 0),ae([pe("billboardMode")],Ur.prototype,"_billboardMode",void 0),ae([pe()],Ur.prototype,"scalingDeterminant",void 0),ae([pe("infiniteDistance")],Ur.prototype,"_infiniteDistance",void 0),ae([pe()],Ur.prototype,"ignoreNonUniformScaling",void 0),ae([pe()],Ur.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class kr{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new w(0,0,0),this._diffPositionForCollisions=new w(0,0,0),this._collisionResponse=!0}}class Gr{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=w.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class zr{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Gr,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=null,this._currentLODIsUpToDate=!1,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new kr,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class Wr extends Ur{static get BILLBOARDMODE_NONE(){return Ur.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return Ur.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return Ur.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return Ur.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return Ur.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return Ur.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return!!super._updateNonUniformScalingState(e)&&(this._markSubMeshesAsMiscDirty(),!0)}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;const t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty((e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()}))}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){return this._internalAbstractMeshDataInfo._materialForRenderPass?.[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}get _positions(){return null}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new zr,this._waitingMaterialId=null,this.cullingStrategy=Wr.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new g,this.onCollisionPositionChangeObservable=new g,this.onMaterialChangedObservable=new g,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this.isVisible=!0,this.isPickable=!0,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=Y.Red(),this.outlineWidth=.02,this.overlayColor=Y.Red(),this.overlayAlpha=.5,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.alwaysSelectAsActiveMesh=!1,this.doNotSyncBoundingInfo=!1,this.actionManager=null,this.ellipsoid=new w(.5,1,.5),this.ellipsoidOffset=new w(0,0,0),this.edgesWidth=1,this.edgesColor=new j(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new g,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Br.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new ji(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case ws.Aggressive:this.doNotSyncBoundingInfo=!0;case ws.Intermediate:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){const t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()}getMeshUniformBuffer(){return this._uniformBuffer}getClassName(){return"AbstractMesh"}toString(e){let t="Name: "+this.name+", isInstance: "+("InstancedMesh"!==this.getClassName()?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);const i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==Ur.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),null!==this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes){for(const e of this.subMeshes)e._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let s=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;s=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(s)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;it.markAsLightDirty(e)))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty((e=>e.markAsAttributesDirty()))}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty((e=>e.markAsMiscDirty()))}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,s){return this}updateVerticesData(e,t,i,s){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new fr(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(Ki.MatricesIndicesKind)&&this.isVerticesDataPresent(Ki.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===Ur.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){const s=new B;(this.rotationQuaternion?this.rotationQuaternion:L.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const r=w.Zero(),n=this.definedFacingForward?-1:1;return w.TransformCoordinatesFromFloatsToRef(e*n,t,i*n,s,r),r}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const s=this.definedFacingForward?1:-1;return new w(e*s,t,i*s)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){const i=mr(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new fr(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t4,n=r?this.getVerticesData(Ki.MatricesIndicesExtraKind):null,o=r?this.getVerticesData(Ki.MatricesWeightsExtraKind):null,a=this.skeleton.getTransformMatrices(this),l=U.Vector3[0],h=U.Matrix[0],c=U.Matrix[1];let u=0;for(let d=0;d0&&(B.FromFloat32ArrayToRefScaled(a,Math.floor(16*e[u+p]),f,c),h.addToSelf(c));if(r)for(p=0;p<4;p++)f=o[u+p],f>0&&(B.FromFloat32ArrayToRefScaled(a,Math.floor(16*n[u+p]),f,c),h.addToSelf(c));s===Ki.NormalKind?w.TransformNormalFromFloatsToRef(i[d],i[d+1],i[d+2],h,l):w.TransformCoordinatesFromFloatsToRef(i[d],i[d+1],i[d+2],h,l),l.toArray(i,d),s===Ki.PositionKind&&this._positions&&this._positions[d/3].copyFrom(l)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,Ki.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,Ki.PositionKind)}_getPositionData(e,t){let i=this.getVerticesData(Ki.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),i&&(e&&this.skeleton||t&&this.morphTargetManager)){if(i=i.slice(),this._generatePointsArray(),this._positions){const e=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(e.length);for(let t=0;t1||!s.IsGlobal)&&s.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const s=this.getBoundingInfo(),r=e.getBoundingInfo();if(s.intersects(r,t))return!0;if(i)for(const i of this.getChildMeshes())if(i.intersectsMesh(e,t,!0))return!0;return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);const t=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=t.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,t.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const i=e.verticesStart,s=e.verticesStart+e.verticesCount;for(let r=i;r1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=U.Matrix[0],i=U.Matrix[1];return B.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,s=!1,r,n=!1){const o=new qi,a=this.getClassName(),l="InstancedLinesMesh"===a||"LinesMesh"===a||"GreasedLineMesh"===a?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes)return o;if(!(n||e.intersectsSphere(h.boundingSphere,l)&&e.intersectsBox(h.boundingBox,l)))return o;if(s)return o.hit=!n,o.pickedMesh=n?null:this,o.distance=n?0:w.Distance(e.origin,h.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let c=null;const u=this._scene.getIntersectingSubMeshCandidates(this,e),d=u.length;let p=!1;for(let e=0;e1&&!n&&!r.canIntersects(e))continue;const o=r.intersects(e,this._positions,this.getIndices(),t,i);if(o&&(t||!c||o.distancee!==this&&e.actionManager===this.actionManager))||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(this),-1!==t&&e.excludedMeshes.splice(t,1);const i=e.getShadowGenerators();if(i){const e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){const e=i.value.getShadowMap();e&&e.renderList&&(t=e.renderList.indexOf(this),-1!==t&&e.renderList.splice(t,1))}}})),"InstancedMesh"===this.getClassName()&&"InstancedLinesMesh"===this.getClassName()||this.releaseSubMeshes();const r=s.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,r.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),r.wipeCaches(),s.removeMesh(this),this._parentContainer){const e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:w.Zero()}e.depthSortedFacets=[];for(let t=0;tT?r.maximum.x-r.minimum.x:T,e.bbSize.y=r.maximum.y-r.minimum.y>T?r.maximum.y-r.minimum.y:T,e.bbSize.z=r.maximum.z-r.minimum.z>T?r.maximum.z-r.minimum.z:T;let n=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(n=n>e.bbSize.z?n:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/n),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/n),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/n),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=r,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),w.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&Tr.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let s=0;sr.subDiv.max||o<0||o>r.subDiv.max||a<0||a>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*o+r.subDiv.max*r.subDiv.max*a]}getClosestFacetAtCoordinates(e,t,i,s,r=!1,n=!0){const o=this.getWorldMatrix(),a=U.Matrix[5];o.invertToRef(a);const l=U.Vector3[8];w.TransformCoordinatesFromFloatsToRef(e,t,i,a,l);const h=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,s,r,n);return s&&w.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,o,s),h}getClosestFacetAtLocalCoordinates(e,t,i,s,r=!1,n=!0){let o=null,a=0,l=0,h=0,c=0,u=0,d=0,p=0,f=0;const _=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;let v,x,T,S=Number.MAX_VALUE,E=S;for(let b=0;b=0||r&&!n&&c<=0)&&(c=x.x*T.x+x.y*T.y+x.z*T.z,u=-(x.x*e+x.y*t+x.z*i-c)/(x.x*x.x+x.y*x.y+x.z*x.z),d=e+x.x*u,p=t+x.y*u,f=i+x.z*u,a=d-e,l=p-t,h=f-i,E=a*a+l*l+h*h,Ee.emitter===this))}}Wr.OCCLUSION_TYPE_NONE=0,Wr.OCCLUSION_TYPE_OPTIMISTIC=1,Wr.OCCLUSION_TYPE_STRICT=2,Wr.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,Wr.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,Wr.CULLINGSTRATEGY_STANDARD=0,Wr.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Wr.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Wr.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,u("BABYLON.AbstractMesh",Wr);class Hr{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681}get func(){return this._func}set func(e){this._func=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){Pe.Clone((()=>e),this)}serialize(){return Pe.Serialize(this)}parse(e,t,i){Pe.Parse((()=>this),e,t,i)}}var Xr,Yr;function jr(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}function $r(e,t,i){const s=!!(e.clipPlane??t.clipPlane),r=!!(e.clipPlane2??t.clipPlane2),n=!!(e.clipPlane3??t.clipPlane3),o=!!(e.clipPlane4??t.clipPlane4),a=!!(e.clipPlane5??t.clipPlane5),l=!!(e.clipPlane6??t.clipPlane6);s&&i.push("#define CLIPPLANE"),r&&i.push("#define CLIPPLANE2"),n&&i.push("#define CLIPPLANE3"),o&&i.push("#define CLIPPLANE4"),a&&i.push("#define CLIPPLANE5"),l&&i.push("#define CLIPPLANE6")}function Kr(e,t,i){let s=t.clipPlane??i.clipPlane;qr(e,"vClipPlane",s),s=t.clipPlane2??i.clipPlane2,qr(e,"vClipPlane2",s),s=t.clipPlane3??i.clipPlane3,qr(e,"vClipPlane3",s),s=t.clipPlane4??i.clipPlane4,qr(e,"vClipPlane4",s),s=t.clipPlane5??i.clipPlane5,qr(e,"vClipPlane5",s),s=t.clipPlane6??i.clipPlane6,qr(e,"vClipPlane6",s)}function qr(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}ae([pe()],Hr.prototype,"func",null),ae([pe()],Hr.prototype,"funcRef",null),ae([pe()],Hr.prototype,"funcMask",null),ae([pe()],Hr.prototype,"opStencilFail",null),ae([pe()],Hr.prototype,"opDepthFail",null),ae([pe()],Hr.prototype,"opStencilDepthPass",null),ae([pe()],Hr.prototype,"mask",null),ae([pe()],Hr.prototype,"enabled",null),(Yr=Xr||(Xr={}))[Yr.Created=1]="Created",Yr[Yr.Disposed=2]="Disposed",Yr[Yr.GetDefineNames=4]="GetDefineNames",Yr[Yr.PrepareUniformBuffer=8]="PrepareUniformBuffer",Yr[Yr.IsReadyForSubMesh=16]="IsReadyForSubMesh",Yr[Yr.PrepareDefines=32]="PrepareDefines",Yr[Yr.BindForSubMesh=64]="BindForSubMesh",Yr[Yr.PrepareEffect=128]="PrepareEffect",Yr[Yr.GetAnimatables=256]="GetAnimatables",Yr[Yr.GetActiveTextures=512]="GetActiveTextures",Yr[Yr.HasTexture=1024]="HasTexture",Yr[Yr.FillRenderTargetTextures=2048]="FillRenderTargetTextures",Yr[Yr.HasRenderTargetTextures=4096]="HasRenderTargetTextures",Yr[Yr.HardBindForSubMesh=8192]="HardBindForSubMesh";const Qr=Y.Black(),Zr={NUM_MORPH_INFLUENCERS:0};function Jr(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=i.activeCamera;1===e.mode&&J.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}function en(e,t,i,s=!1){i&&e.fogEnabled&&(!t||t.applyFog)&&0!==e.fogMode&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),s?(e.fogColor.toLinearSpaceToRef(Qr,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",Qr)):i.setColor3("vFogColor",e.fogColor))}function tn(e,t,i){Zr.NUM_MORPH_INFLUENCERS=i,sn(e,t,Zr)}function sn(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&y.LastCreatedEngine){const r=y.LastCreatedEngine.getCaps().maxVertexAttribs,n=t.morphTargetManager;if(n?.isUsingTextureForTargets)return;const o=n&&n.supportsNormals&&i.NORMAL,a=n&&n.supportsTangents&&i.TANGENT,l=n&&n.supportsUVs&&i.UV1;for(let i=0;ir&&J.Error("Cannot add more vertex attributes for mesh "+t.name)}}function rn(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}function nn(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}function on(e,t){t.bindToEffect(e,"Scene")}function an(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}function ln(e,t,i){const s=e.getTextureMatrix();t.updateMatrix(i+"Matrix",s)}function hn(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}function cn(e,t,i){var s;if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const r=e.skeleton;if(r.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){const i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{const n=r.getTransformMatrices(e);n&&(t.setMatrices("mBones",n),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=n.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),s=n,i.previousBones[e.uniqueId].set(s)))}}}function un(e,t,i,s,r,n=!0){e._bindLight(t,i,s,r,n)}function dn(e,t,i,s,r=4){const n=Math.min(t.lightSources.length,r);for(let r=0;r0&&(s.addCPUSkinningFallback(0,t),e.push("matricesIndices"),e.push("matricesWeights"),i.NUM_BONE_INFLUENCERS>4&&(e.push("matricesIndicesExtra"),e.push("matricesWeightsExtra")))}function fn(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&rn(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push("instanceColor")}function _n(e,t,i=4,s=0){let r=0;for(let n=0;n0&&(r=s+n,t.addFallback(r,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(s,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(s,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(s,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(s,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(s,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(s,"SHADOWCLOSEESM"+n));return r++}function mn(e,t){return t.fogEnabled&&e.applyFog&&0!==t.fogMode}function gn(e,t,i,s,r,n,o,a=!1){o._areMiscDirty&&(o.LOGARITHMICDEPTH=i,o.POINTSIZE=s,o.FOG=r&&mn(e,t),o.NONUNIFORMSCALING=e.nonUniformScaling,o.ALPHATEST=n,o.DECAL_AFTER_DETAIL=a)}function vn(e,t,i,s,r=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let o=0;const a={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n)for(const n of t.lightSources)if(xn(e,t,n,o,i,s,a),o++,o===r)break;i.SPECULARTERM=a.specularEnabled,i.SHADOWS=a.shadowEnabled;for(let e=o;e0&&(o.shadowEnabled=!0,t.prepareDefines(r,s))}}i.lightmapMode!=Os.LIGHTMAP_DEFAULT?(o.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+s]=!0,r["LIGHTMAPNOSPECULAR"+s]=i.lightmapMode==Os.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+s]=!1,r["LIGHTMAPNOSPECULAR"+s]=!1)}function Tn(e,t,i,s,r,n=null,o=!1){let a=In(e,s);!1!==n&&(a=function(e,t,i){let s=!1;const r=!!(e.clipPlane??t.clipPlane),n=!!(e.clipPlane2??t.clipPlane2),o=!!(e.clipPlane3??t.clipPlane3),a=!!(e.clipPlane4??t.clipPlane4),l=!!(e.clipPlane5??t.clipPlane5),h=!!(e.clipPlane6??t.clipPlane6);return i.CLIPPLANE!==r&&(i.CLIPPLANE=r,s=!0),i.CLIPPLANE2!==n&&(i.CLIPPLANE2=n,s=!0),i.CLIPPLANE3!==o&&(i.CLIPPLANE3=o,s=!0),i.CLIPPLANE4!==a&&(i.CLIPPLANE4=a,s=!0),i.CLIPPLANE5!==l&&(i.CLIPPLANE5=l,s=!0),i.CLIPPLANE6!==h&&(i.CLIPPLANE6=h,s=!0),s}(i,e,s)),s.DEPTHPREPASS!==!t.getColorWrite()&&(s.DEPTHPREPASS=!s.DEPTHPREPASS,a=!0),s.INSTANCES!==r&&(s.INSTANCES=r,a=!0),s.THIN_INSTANCES!==o&&(s.THIN_INSTANCES=o,a=!0),a&&s.markAsUnprocessed()}function Sn(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;const s=e.getScene().prePassRenderer;if(s&&s.enabled){const i=-1===s.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}function En(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.NUM_MORPH_INFLUENCERS=i.numMaxInfluencers||i.numInfluencers,t.MORPHTARGETS=t.NUM_MORPH_INFLUENCERS>0,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}function bn(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}function Cn(e,t,i,s,r=!1,n=!0,o=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent("normal"),t._needNormals&&e.isVerticesDataPresent("tangent")&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){const i=e.useVertexColors&&e.isVerticesDataPresent("color");t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&n}return e.isVerticesDataPresent("instanceColor")&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),s&&Sn(e,t),r&&En(e,t),o&&bn(e,t),!0}function yn(e,t){if(e.activeCamera){const i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}function An(e,t,i){const s=t.ORDER_INDEPENDENT_TRANSPARENCY,r=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,s===t.ORDER_INDEPENDENT_TRANSPARENCY&&r===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}function Rn(e,t,i){const s=t.PREPASS;if(!t._arePrePassDirty)return;const r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let i=0;i{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const s=t||y.LastCreatedScene;s&&(this._scene=s,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||Ii.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new gr(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=Dn.ClockWiseSideOrientation:this.sideOrientation=Dn.CounterClockWiseSideOrientation,this._uniformBuffer=new ji(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),Dn.OnEventObservable.notifyObservers(this,Xr.Created))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const s=t.materialDefines;return!!s&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===Dn.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===Dn.MATERIAL_OPAQUE||this._transparencyMode===Dn.MATERIAL_ALPHATEST}needAlphaBlending(){return!this._disableAlphaBlending&&this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1||!this._disableAlphaBlending&&(e.hasVertexAlpha||this.needAlphaBlending())}needAlphaTesting(){return!!this._forceAlphaTest}_shouldTurnAlphaTestOn(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)if(t.getMaterial()===this)for(const i of t._drawWrappers)i&&this._materialContext===i.materialContext&&(i._wasPreviouslyReady=!1,i._wasPreviouslyUsingInstances=null,i._forceRebindOnNextCall=e);e&&this.markAsDirty(Dn.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),s=(null==t?this.sideOrientation:t)===Dn.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(Xr.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const s=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),s._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,on(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),this._scene._cachedVisibility=e?e.visibility:1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){const e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){const e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(Xr.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(Xr.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(Xr.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),Dn._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const t of this.pluginManager._plugins){const i=e.pluginManager.getPlugin(t.name);i&&t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}return this._scene.meshes.filter((e=>e.material===this))}forceCompilation(e,t,i,s){const r={clipPlane:!1,useInstances:!1,...i},n=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const a=()=>{if(!this._scene||!this._scene.getEngine())return;const i=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new Ps(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,n=null;if(e.subMeshes){const t=new vr(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,r.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?n=t.effect.getCompilationError():(i=!1,setTimeout(a,16)))}i&&(this.allowShaderHotSwapping=o,n&&s&&s(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(a,16);r.clipPlane&&(n.clipPlane=i)};a()}forceCompilationAsync(e,t){return new Promise(((i,s)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{s(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(Dn._DirtyCallbackArray.length=0,e&Dn.TextureDirtyFlag&&Dn._DirtyCallbackArray.push(Dn._TextureDirtyCallBack),e&Dn.LightDirtyFlag&&Dn._DirtyCallbackArray.push(Dn._LightsDirtyCallBack),e&Dn.FresnelDirtyFlag&&Dn._DirtyCallbackArray.push(Dn._FresnelDirtyCallBack),e&Dn.AttributesDirtyFlag&&Dn._DirtyCallbackArray.push(Dn._AttributeDirtyCallBack),e&Dn.MiscDirtyFlag&&Dn._DirtyCallbackArray.push(Dn._MiscDirtyCallBack),e&Dn.PrePassDirtyFlag&&Dn._DirtyCallbackArray.push(Dn._PrePassDirtyCallBack),Dn._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(Dn._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const e of t.subMeshes)e.getMaterial()===this&&e.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)if(t.getMaterial(!1)===this)for(const i of t._drawWrappers)i&&i.defines&&i.defines.markAllAsDirty&&this._materialContext===i.materialContext&&e(i.defines)}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(Dn._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(Dn._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(Dn._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(Dn._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(Dn._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(Dn._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(Dn._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(Dn._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(Dn._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(Dn._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==ws.BackwardCompatible){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce((()=>{this.checkReadyOnlyOnce=!1}));this.onDisposeObservable.add((()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)}))}}setPrePassRenderer(e){return!1}dispose(e,t,i){const s=this.getScene();if(s.stopAnimation(this),s.freeProcessedMaterials(),s.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(Xr.Disposed,this._eventInfo),this._parentContainer){const e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i)if(this.meshMap)for(const t in this.meshMap){const i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{const t=s.meshes;for(const i of t)i.material!==this||i.sourceMesh||(i.material=null,this.releaseVertexArrayObject(i,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const s of e.subMeshes)i._releaseVertexArrayObject(s.effect),t&&s.effect&&s.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=Pe.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(const t of this.pluginManager._plugins)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,i){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return J.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else e.customType="BABYLON.StandardMaterial";const s=Ii.Instantiate(e.customType).Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _ParsePlugins(e,t,i,s){if(e.plugins)for(const r in e.plugins){const n=e.plugins[r];let o=t.pluginManager?.getPlugin(n.name);if(!o){const e=Ii.Instantiate("BABYLON."+r);e&&(o=new e(t))}o?.parse(n,i,s)}}}Dn.TriangleFillMode=0,Dn.WireFrameFillMode=1,Dn.PointFillMode=2,Dn.PointListDrawMode=3,Dn.LineListDrawMode=4,Dn.LineLoopDrawMode=5,Dn.LineStripDrawMode=6,Dn.TriangleStripDrawMode=7,Dn.TriangleFanDrawMode=8,Dn.ClockWiseSideOrientation=0,Dn.CounterClockWiseSideOrientation=1,Dn.TextureDirtyFlag=1,Dn.LightDirtyFlag=2,Dn.FresnelDirtyFlag=4,Dn.AttributesDirtyFlag=8,Dn.MiscDirtyFlag=16,Dn.PrePassDirtyFlag=32,Dn.AllDirtyFlag=63,Dn.MATERIAL_OPAQUE=0,Dn.MATERIAL_ALPHATEST=1,Dn.MATERIAL_ALPHABLEND=2,Dn.MATERIAL_ALPHATESTANDBLEND=3,Dn.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,Dn.MATERIAL_NORMALBLENDMETHOD_RNM=1,Dn.OnEventObservable=new g,Dn._AllDirtyCallBack=e=>e.markAllAsDirty(),Dn._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),Dn._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),Dn._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),Dn._MiscDirtyCallBack=e=>e.markAsMiscDirty(),Dn._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),Dn._LightsDirtyCallBack=e=>e.markAsLightDirty(),Dn._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),Dn._FresnelAndMiscDirtyCallBack=e=>{Dn._FresnelDirtyCallBack(e),Dn._MiscDirtyCallBack(e)},Dn._TextureAndMiscDirtyCallBack=e=>{Dn._TextureDirtyCallBack(e),Dn._MiscDirtyCallBack(e)},Dn._DirtyCallbackArray=[],Dn._RunDirtyCallBacks=e=>{for(const t of Dn._DirtyCallbackArray)t(e)},ae([pe()],Dn.prototype,"id",void 0),ae([pe()],Dn.prototype,"uniqueId",void 0),ae([pe()],Dn.prototype,"name",void 0),ae([pe()],Dn.prototype,"metadata",void 0),ae([pe()],Dn.prototype,"checkReadyOnEveryCall",void 0),ae([pe()],Dn.prototype,"checkReadyOnlyOnce",void 0),ae([pe()],Dn.prototype,"state",void 0),ae([pe("alpha")],Dn.prototype,"_alpha",void 0),ae([pe("backFaceCulling")],Dn.prototype,"_backFaceCulling",void 0),ae([pe("cullBackFaces")],Dn.prototype,"_cullBackFaces",void 0),ae([pe()],Dn.prototype,"sideOrientation",void 0),ae([pe("alphaMode")],Dn.prototype,"_alphaMode",void 0),ae([pe()],Dn.prototype,"_needDepthPrePass",void 0),ae([pe()],Dn.prototype,"disableDepthWrite",void 0),ae([pe()],Dn.prototype,"disableColorWrite",void 0),ae([pe()],Dn.prototype,"forceDepthWrite",void 0),ae([pe()],Dn.prototype,"depthFunction",void 0),ae([pe()],Dn.prototype,"separateCullingPass",void 0),ae([pe("fogEnabled")],Dn.prototype,"_fogEnabled",void 0),ae([pe()],Dn.prototype,"pointSize",void 0),ae([pe()],Dn.prototype,"zOffset",void 0),ae([pe()],Dn.prototype,"zOffsetUnits",void 0),ae([pe()],Dn.prototype,"pointsCloud",null),ae([pe()],Dn.prototype,"fillMode",null),ae([pe()],Dn.prototype,"useLogarithmicDepth",null),ae([pe()],Dn.prototype,"transparencyMode",null);class On extends Dn{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);return this._markAllSubMeshesAsTexturesDirty(),r}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map((e=>e?e.getActiveTextures():[])))}hasTexture(e){if(super.hasTexture(e))return!0;for(let t=0;t=0&&s.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new On(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,Re&&Re.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}u("BABYLON.MultiMaterial",On);class Nn{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class wn{}class Fn{constructor(){this.visibleInstances={},this.batchCache=new Ln,this.batchCacheReplacementModeInFrozenMode=new Ln,this.instancesBufferSize=2048}}class Ln{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class Bn{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class Vn{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}}class Un extends Wr{static _GetDefaultSideOrientation(e){return e||Un.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(Ki.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(Ki.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new g),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new g),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new g),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new g),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new g),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}constructor(e,t=null,i=null,s=null,r,n=!0){if(super(e,t),this._internalMeshDataInfo=new Vn,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new Fn,this._thinInstanceDataStorage=new Bn,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=Un.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,i)=>{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},s){if(s._geometry&&s._geometry.applyToMesh(this),se.DeepCopy(s,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=s,t.useClonedMeshMap&&(s._internalMeshDataInfo.meshMap||(s._internalMeshDataInfo.meshMap={}),s._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=s._originalBuilderSideOrientation,this._creationDataStorage=s._creationDataStorage,s._ranges){const e=s._ranges;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,Re&&Re.HasTags(s)&&Re.AddTagsTo(this,Re.GetTags(s,!0)),this.setEnabled(s.isEnabled(!1)),this.parent=s.parent,this.setPivotMatrix(s.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=e+"."+s.id,this.material=s.material,!r){const t=s.getDescendants(!0);for(let i=0;i{e.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add((()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))})))},this.onMeshReadyObservable=new g(this._internalMeshDataInfo._onMeshReadyObserverAdded),s&&s.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const s=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));s.parent=e||this.parent,s.position=this.position.clone(),s.scaling=this.scaling.clone(),this.rotationQuaternion?s.rotationQuaternion=this.rotationQuaternion.clone():s.rotation=this.rotation.clone(),i&&i(this,s);for(const e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===s.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(s,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:s},i):e.instantiateHierarchy(s,t,i);return s}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort(((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0))}addLODLevel(e,t){if(t&&t._masterMesh)return J.Warn("You cannot use a mesh as LOD level twice"),this;const i=new Nn(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let i=0;io*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let e=0;e0||this.hasThinInstances);this.computeWorldMatrix();const n=this.material||s.defaultMaterial;if(n)if(n._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,r))return!1}else if(!t.isReady(this,r))return!1}else if(!n.isReady(this,r))return!1;const o=i.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const s=t.values();for(let e=s.next();!0!==e.done;e=s.next()){const t=e.value;if(t&&(!t.getShadowMap()?.renderList||t.getShadowMap()?.renderList&&-1!==t.getShadowMap()?.renderList?.indexOf(this))){const e=t.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let s=0;s0){const i=this.getIndices();if(!i)return null;const s=i.length;let r=!1;if(e)r=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>s){r=!0;break}if(e.verticesStart+e.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new vr(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,s=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let r=0;r=t);r++)vr.CreateFromIndices(0,s,r===e-1?t-s:i,this,void 0,!1),s+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,s){if(this._geometry)this._geometry.setVerticesData(e,t,i,s);else{const s=new Tr;s.set(t,e);const r=this.getScene();new br(br.RandomId(),r,s,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=br.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,s){return this._geometry?(s?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(Ki.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(Ki.PositionKind,i,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(Ki.NormalKind);if(!t)return this;Tr.ComputeNormals(i,e,t),this.updateVerticesData(Ki.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(1===this._geometry.meshes.length)return this;const e=this._geometry,t=this._geometry.copy(br.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let s=this._geometry;s||(s=new br(br.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const t=new Tr;t.indices=e;const s=this.getScene();new br(br.RandomId(),s,t,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,s=!0){if(!this._geometry)return this;const r=this.getScene().getEngine();let n;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)n=null;else switch(this._getRenderingFillMode(i)){case Dn.PointFillMode:n=null;break;case Dn.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case Dn.TriangleFillMode:n=this._geometry.getIndexBuffer()}return s&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,n,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,n),this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const s=this.getScene().getEngine();return this._unIndexed||t==Dn.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Dn.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):s.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const i=this.getScene(),s=i._isInIntermediateRendering(),r=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,r=i.getRenderId(),o=s?t.intermediateDefaultRenderId:t.defaultRenderId;n.visibleInstances[e]=t[r],!n.visibleInstances[e]&&o&&(n.visibleInstances[e]=t[o])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==n.visibleInstances[e]&&void 0!==n.visibleInstances[e],this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,i,s,r){const n=i.visibleInstances[e._id],o=n?n.length:0,a=this._instanceDataStorage,l=a.instancesBufferSize;let h=a.instancesBuffer,c=a.instancesPreviousBuffer;const u=16*(o+1)*4;for(;a.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera1&&s.activeCamera===s.activeCameras[0]||r<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const n=this._getInstancesRenderList(e._id,!!i);if(n.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const o=s.getEngine();let a=0,l=null;this.ignoreCameraMaxZ&&s.activeCamera&&!s._isInIntermediateRendering()&&(a=s.activeCamera.maxZ,l=s.activeCamera,s.activeCamera.maxZ=0,s.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const h=e.getRenderingMesh(),c=n.hardwareInstancedRendering[e._id]||h.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,u=this._instanceDataStorage,d=e.getMaterial();if(!d)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;if(u.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===d){if(d._storeEffectOnSubMeshes&&!e._drawWrapper?._wasPreviouslyReady||!d._storeEffectOnSubMeshes&&!d._getDrawWrapper()._wasPreviouslyReady)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this}else{if(d._storeEffectOnSubMeshes){if(!d.isReadyForSubMesh(this,e,c))return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this}else if(!d.isReady(this,c))return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=d}let p;t&&o.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),p=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const f=p?.effect??null;for(const t of s._beforeRenderingMeshStage)t.action(this,e,n,f);if(!p||!f)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;const _=i||this;let m;if(u.isFrozen||!this._internalMeshDataInfo._effectiveMaterial.backFaceCulling&&null===this.overrideMaterialSideOrientation&&!this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)m=u.sideOrientation;else{const e=_._getWorldMatrixDeterminant();m=this.overrideMaterialSideOrientation,null==m&&(m=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(m=m===Dn.ClockWiseSideOrientation?Dn.CounterClockWiseSideOrientation:Dn.ClockWiseSideOrientation),u.sideOrientation=m}const g=this._internalMeshDataInfo._effectiveMaterial._preBind(p,m);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&o.setDepthWrite(!0);const v=this._internalMeshDataInfo._effectiveMaterial,x=v.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),c||this._bind(e,f,x,!1);const T=_.getWorldMatrix();v._storeEffectOnSubMeshes?v.bindForSubMesh(T,this,e):v.bind(T,this),!v.backFaceCulling&&v.separateCullingPass&&(o.setState(!0,v.zOffset,!1,!g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._processRendering(this,e,f,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),o.setState(!0,v.zOffset,!1,g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,f,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const t of s._afterRenderingMeshStage)t.action(this,e,n,f);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),l&&(l.maxZ=a,s.updateTransformMatrix(!0)),s.performancePriority!==ws.Aggressive||u.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(Ki.MatricesWeightsKind)&&(this.isVerticesDataPresent(Ki.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(Ki.MatricesWeightsKind),t=e.length;for(let i=0;ii&&s++,0!==n&&u++,c+=n,i=n}if(l[u]++,u>n&&(n=u),0===c)r++;else{const i=1/c;let s=0;for(let r=0;r.001&&o++}}const h=this.skeleton.bones.length,c=this.getVerticesData(Ki.MatricesIndicesKind),u=this.getVerticesData(Ki.MatricesIndicesExtraKind);let d=0;for(let e=0;e=h||i<0)&&d++}return{skinned:!0,valid:0===r&&0===o&&0===d,report:"Number of Weights = "+i/4+"\nMaximum influences = "+n+"\nMissing Weights = "+r+"\nNot Sorted = "+s+"\nNot Normalized = "+o+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+d}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return Ii.LoadFile(this.delayLoadingFile,(t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach((e=>{e.refreshBoundingInfo(),e._syncSubMeshes()})),this.delayLoadState=1,e.removePendingData(this)}),(()=>{}),e.offlineProvider,t),this}isInFrustum(e){return 2!==this.delayLoadState&&!!super.isInFrustum(e)&&(this._checkDelayState(),!0)}setMaterialById(e){const t=this.getScene().materials;let i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;const s=this.getScene().multiMaterials;for(i=s.length-1;i>-1;i--)if(s[i].id===e)return this.material=s[i],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(Ki.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(Ki.PositionKind);const s=w.Zero();let r;for(r=0;r{const a=e.width,l=e.height,h=this.getEngine().createCanvas(a,l).getContext("2d");h.drawImage(e,0,0);const c=h.getImageData(0,0,a,l).data;this.applyDisplacementMapFromBuffer(c,a,l,t,i,r,n,o),s&&s(this)}),a||(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,r,n,o,a=!1){if(!this.isVerticesDataPresent(Ki.PositionKind)||!this.isVerticesDataPresent(Ki.NormalKind)||!this.isVerticesDataPresent(Ki.UVKind))return J.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(Ki.PositionKind,!0,!0),h=this.getVerticesData(Ki.NormalKind),c=this.getVerticesData(Ki.UVKind);let u=w.Zero();const d=w.Zero(),p=N.Zero();n=n||N.Zero(),o=o||new N(1,1);for(let a=0;a{const s=new Float32Array(i.length*t);let r=0;for(let n=0;n{const t=s.length-1-e,i=s[t];for(let e=0;e{for(let e=0;e-1&&(s.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(s.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(s.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t4,l=a?this.getVerticesData(Ki.MatricesIndicesExtraKind):null,h=a?this.getVerticesData(Ki.MatricesWeightsExtraKind):null,c=e.getTransformMatrices(this),u=w.Zero(),d=new B,p=new B;let f,_=0;for(let e=0;e0&&(B.FromFloat32ArrayToRefScaled(c,Math.floor(16*n[_+f]),m,p),d.addToSelf(p));if(a)for(f=0;f<4;f++)m=h[_+f],m>0&&(B.FromFloat32ArrayToRefScaled(c,Math.floor(16*l[_+f]),m,p),d.addToSelf(p));w.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],d,u),u.toArray(s,e),t&&(w.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],d,u),u.toArray(r,e)),d.reset()}return this.updateVerticesData(Ki.PositionKind,s),t&&this.updateVerticesData(Ki.NormalKind,r),this}static MinMax(e){let t=null,i=null;return e.forEach((function(e){const s=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(s.minimumWorld),i.maximizeInPlace(s.maximumWorld)):(t=s.minimumWorld,i=s.maximumWorld)})),t&&i?{min:t,max:i}:{min:w.Zero(),max:w.Zero()}}static Center(e){const t=e instanceof Array?Un.MinMax(e):e;return w.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,r,n){return sr(Un._MergeMeshesCoroutine(e,t,i,s,r,n,!1))}static MergeMeshesAsync(e,t=!0,i,s,r,n){return rr(Un._MergeMeshesCoroutine(e,t,i,s,r,n,!0),function(e=25){let t;return(i,s,r)=>{const n=performance.now();void 0===t||n-t>e?(t=n,setTimeout((()=>{tr(i,s,r)}),0)):tr(i,s,r)}}())}static*_MergeMeshesCoroutine(e,t=!0,i,s,r,n,o){if(0===(e=e.filter(Boolean)).length)return null;let a;if(!i){let t=0;for(a=0;a=65536)return J.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(r=!1);const l=new Array,h=new Array,c=new Array,u=e[0].overrideMaterialSideOrientation;for(a=0;a{const t=e.computeWorldMatrix(!0);return{vertexData:Tr.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:f,transform:_}=p(d);o&&(yield);const m=new Array(e.length-1);for(let t=1;t{throw ye("GroundMesh")},Un._GoldbergMeshParser=(e,t)=>{throw ye("GoldbergMesh")},Un._LinesMeshParser=(e,t)=>{throw ye("LinesMesh")},Un._GreasedLineMeshParser=(e,t)=>{throw ye("GreasedLineMesh")},Un._GreasedLineRibbonMeshParser=(e,t)=>{throw ye("GreasedLineRibbonMesh")},Un._TrailMeshParser=(e,t)=>{throw ye("TrailMesh")},u("BABYLON.Mesh",Un),Un._instancedMeshFactory=(e,t)=>{const i=new kn(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class kn extends Wr{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const e of t.getAnimationRanges())null!=e&&this.createAnimationRange(e.name,e.from,e.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){this._sourceMesh?.receiveShadows!==e&&Ii.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){this._sourceMesh?.material!==e&&Ii.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){this._sourceMesh?.visibility!==e&&Ii.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){this._sourceMesh?.skeleton!==e&&Ii.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){this._sourceMesh&&e!==this._sourceMesh.renderingGroupId&&J.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,s),this.sourceMesh}updateVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,s),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||J.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),t){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1}_postActivate(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)}getWorldMatrix(){if(this._currentLOD&&this._currentLOD.billboardMode!==Ur.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new B);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,U.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(U.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;const t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){const t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e0&&-1===this.includedOnlyMeshes.indexOf(e)||this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)||!(0===this.includeOnlyWithLayerMask||this.includeOnlyWithLayerMask&e.layerMask)||0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(const e of this.getScene().meshes)e._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){const i=Gn.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=Pe.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=Pe.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0&&(e.excludedMeshesIds=[],this.excludedMeshes.forEach((t=>{e.excludedMeshesIds.push(t.id)}))),this.includedOnlyMeshes.length>0&&(e.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((t=>{e.includedOnlyMeshesIds.push(t.id)}))),Pe.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){return De.Construct("Light_Type_"+e,t,i)||null}static Parse(e,t){const i=Gn.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=Pe.Parse(i,e,t);if(e.excludedMeshesIds&&(s._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(s._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(s.falloffType=e.falloffType),void 0!==e.lightmapMode&&(s.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t{const s=t.apply(e,i);for(const e of i)e._resyncLightSource(this);return s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);for(const e of r)e._resyncLightSource(this);return r};for(const t of e)t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);return this._resyncMeshes(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);return this._resyncMeshes(),r},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===Gn.INTENSITYMODE_AUTOMATIC&&(i=t===Gn.LIGHTTYPEID_DIRECTIONALLIGHT?Gn.INTENSITYMODE_ILLUMINANCE:Gn.INTENSITYMODE_LUMINOUSINTENSITY),t){case Gn.LIGHTTYPEID_POINTLIGHT:case Gn.LIGHTTYPEID_SPOTLIGHT:switch(i){case Gn.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Gn.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Gn.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case Gn.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case Gn.INTENSITYMODE_ILLUMINANCE:e=1;break;case Gn.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001),e=2*Math.PI*(1-Math.cos(t));break}}break;case Gn.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Gn.FALLOFF_DEFAULT=Os.FALLOFF_DEFAULT,Gn.FALLOFF_PHYSICAL=Os.FALLOFF_PHYSICAL,Gn.FALLOFF_GLTF=Os.FALLOFF_GLTF,Gn.FALLOFF_STANDARD=Os.FALLOFF_STANDARD,Gn.LIGHTMAP_DEFAULT=Os.LIGHTMAP_DEFAULT,Gn.LIGHTMAP_SPECULAR=Os.LIGHTMAP_SPECULAR,Gn.LIGHTMAP_SHADOWSONLY=Os.LIGHTMAP_SHADOWSONLY,Gn.INTENSITYMODE_AUTOMATIC=Os.INTENSITYMODE_AUTOMATIC,Gn.INTENSITYMODE_LUMINOUSPOWER=Os.INTENSITYMODE_LUMINOUSPOWER,Gn.INTENSITYMODE_LUMINOUSINTENSITY=Os.INTENSITYMODE_LUMINOUSINTENSITY,Gn.INTENSITYMODE_ILLUMINANCE=Os.INTENSITYMODE_ILLUMINANCE,Gn.INTENSITYMODE_LUMINANCE=Os.INTENSITYMODE_LUMINANCE,Gn.LIGHTTYPEID_POINTLIGHT=Os.LIGHTTYPEID_POINTLIGHT,Gn.LIGHTTYPEID_DIRECTIONALLIGHT=Os.LIGHTTYPEID_DIRECTIONALLIGHT,Gn.LIGHTTYPEID_SPOTLIGHT=Os.LIGHTTYPEID_SPOTLIGHT,Gn.LIGHTTYPEID_HEMISPHERICLIGHT=Os.LIGHTTYPEID_HEMISPHERICLIGHT,ae([_e()],Gn.prototype,"diffuse",void 0),ae([_e()],Gn.prototype,"specular",void 0),ae([pe()],Gn.prototype,"falloffType",void 0),ae([pe()],Gn.prototype,"intensity",void 0),ae([pe()],Gn.prototype,"range",null),ae([pe()],Gn.prototype,"intensityMode",null),ae([pe()],Gn.prototype,"radius",null),ae([pe()],Gn.prototype,"_renderPriority",void 0),ae([de("_reorderLightsInScene")],Gn.prototype,"renderPriority",void 0),ae([pe("shadowEnabled")],Gn.prototype,"_shadowEnabled",void 0),ae([pe("excludeWithLayerMask")],Gn.prototype,"_excludeWithLayerMask",void 0),ae([pe("includeOnlyWithLayerMask")],Gn.prototype,"_includeOnlyWithLayerMask",void 0),ae([pe("lightmapMode")],Gn.prototype,"_lightmapMode",void 0);class zn extends p{}class Wn{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){this.rootNodes.slice(0).forEach((e=>{e.dispose()})),this.rootNodes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0}}class Hn extends p{constructor(e){super(),this._wasAddedToScene=!1,(e=e||y.LastCreatedScene)&&(this.scene=e,this.sounds=[],this.effectLayers=[],this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.reflectionProbes=[],e.onDisposeObservable.add((()=>{this._wasAddedToScene||this.dispose()})),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();for(const e of this.particleSystems)e.rebuild();for(const e of this.textures)e._rebuild()})))}_topologicalSort(e){const t=new Map;for(const i of e)t.set(i.uniqueId,i);const i={dependsOn:new Map,dependedBy:new Map};for(const t of e){const e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(const s of e){const e=s.uniqueId,r=i.dependsOn.get(e);if(s instanceof kn){const n=s.sourceMesh;t.has(n.uniqueId)&&(r.add(n.uniqueId),i.dependedBy.get(n.uniqueId).add(e))}const n=i.dependedBy.get(e);for(const r of s.getDescendants()){const s=r.uniqueId;t.has(s)&&(n.add(s),i.dependsOn.get(s).add(e))}}const s=[],r=[];for(const s of e){const e=s.uniqueId;0===i.dependsOn.get(e).size&&(r.push(s),t.delete(e))}const n=r;for(;n.length>0;){const e=n.shift();s.push(e);const r=i.dependedBy.get(e.uniqueId);for(const s of Array.from(r.values())){const r=i.dependsOn.get(s);r.delete(e.uniqueId),0===r.size&&t.get(s)&&(n.push(t.get(s)),t.delete(s))}}return t.size>0&&(J.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>J.Error(e.name)))),s}_addNodeAndDescendantsToList(e,t,i,s){if(i&&(!s||s(i))&&!t.has(i.uniqueId)){e.push(i),t.add(i.uniqueId);for(const r of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,r,s)}}_isNodeInContainer(e){return e instanceof Wr&&-1!==this.meshes.indexOf(e)||e instanceof Ur&&-1!==this.transformNodes.indexOf(e)||e instanceof Gn&&-1!==this.lights.indexOf(e)||e instanceof or&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return J.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return J.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return J.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return J.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Ii.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},r={},n=new Wn,o=[],a=[],l={doNotInstantiate:!0,...i},h=[],c=new Set;for(const e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);for(const e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);const u=this._topologicalSort(h),d=(i,o)=>{if(((t,i)=>{if(s[t.uniqueId]=i.uniqueId,r[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof Un){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;te&&r[s[e.uniqueId]]))}}"InstancedMesh"!==n.getClassName()&&(n.material=r[s[t.uniqueId]])}else"MultiMaterial"===n.material.getClassName()?-1===this.scene.multiMaterials.indexOf(n.material)&&this.scene.addMultiMaterial(n.material):-1===this.scene.materials.indexOf(n.material)&&this.scene.addMaterial(n.material)}null===o.parent&&n.rootNodes.push(o)};return u.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,n=s[i.uniqueId],o=("number"==typeof n?r[n]:i).createInstance(t.name);d(t,o)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);const i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw new Error(`Could not clone or instantiate node on Asset Container ${e.name}`);d(e,i)}})),this.skeletons.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name);for(const e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){const t=r[s[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=i,-1!==o.indexOf(i))continue;o.push(i);for(const e of i.bones)e._linkedTransformNode&&(e._linkedTransformNode=r[s[e._linkedTransformNode.uniqueId]])}n.skeletons.push(i)})),this.animationGroups.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name,(e=>r[s[e.uniqueId]]||e));n.animationGroups.push(i)})),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Ii.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(const e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){const t=[];this.cameras.forEach((i=>{e&&!e(i)||(this.scene.addCamera(i),t.push(i))})),this.lights.forEach((i=>{e&&!e(i)||(this.scene.addLight(i),t.push(i))})),this.meshes.forEach((i=>{e&&!e(i)||(this.scene.addMesh(i),t.push(i))})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.addSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.addAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.addAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.addMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.addMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.addMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.addGeometry(t)})),this.transformNodes.forEach((i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.addActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.addTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.addReflectionProbe(t)}));for(const e of t)e.parent&&-1===this.scene.getNodes().indexOf(e.parent)&&(e.setParent?e.setParent(null):e.parent=null)}removeAllFromScene(){this._isValidHierarchy()||Ii.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach((t=>{e&&!e(t)||this.scene.removeCamera(t)})),this.lights.forEach((t=>{e&&!e(t)||this.scene.removeLight(t)})),this.meshes.forEach((t=>{e&&!e(t)||this.scene.removeMesh(t,!0)})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.removeSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.removeAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.removeMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.removeGeometry(t)})),this.transformNodes.forEach((t=>{e&&!e(t)||this.scene.removeTransformNode(t)})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.removeActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.removeTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)}))}dispose(){this.cameras.slice(0).forEach((e=>{e.dispose()})),this.cameras.length=0,this.lights.slice(0).forEach((e=>{e.dispose()})),this.lights.length=0,this.meshes.slice(0).forEach((e=>{e.dispose()})),this.meshes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach((e=>{e.dispose()})),this.multiMaterials.length=0,this.materials.slice(0).forEach((e=>{e.dispose()})),this.materials.length=0,this.geometries.slice(0).forEach((e=>{e.dispose()})),this.geometries.length=0,this.transformNodes.slice(0).forEach((e=>{e.dispose()})),this.transformNodes.length=0,this.actionManagers.slice(0).forEach((e=>{e.dispose()})),this.actionManagers.length=0,this.textures.slice(0).forEach((e=>{e.dispose()})),this.textures.length=0,this.reflectionProbes.slice(0).forEach((e=>{e.dispose()})),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach((e=>{e.dispose()})),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(e&&t)for(const s of e){let e=!0;if(i)for(const t of i)if(s===t){e=!1;break}e&&(t.push(s),s._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,void 0===e&&(e=new zn);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||("_environmentTexture"===t?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new Un("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=y.LastCreatedScene,t,i=null){if(!e)return J.Error("No scene available to merge animations to"),[];const s=i||(t=>{let i=null;const s=t.animations.length?t.animations[0].targetProperty:"",r=t.name.split(".").join("").split("_primitive")[0];switch(s){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(r);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(r);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(r)}return i});this.getNodes().forEach((e=>{const t=s(e);if(null!==t){for(const i of e.animations){const e=t.animations.filter((e=>e.targetProperty===i.targetProperty));for(const i of e){const e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}}));const r=[];return this.animationGroups.slice().forEach((e=>{r.push(e.clone(e.name,s)),e.animatables.forEach((e=>{e.stop()}))})),t.forEach((t=>{const i=s(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))})),r}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.transformNodes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.lights.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.cameras.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}))}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const e=t.pop();if(e instanceof Un?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof Ur?this.transformNodes.push(e):e instanceof Gn?this.lights.push(e):e instanceof or&&this.cameras.push(e),e instanceof Wr){if(e.material&&-1===this.materials.indexOf(e.material)){this.materials.push(e.material);for(const t of e.material.getActiveTextures())-1===this.textures.indexOf(t)&&this.textures.push(t)}e.skeleton&&-1===this.skeletons.indexOf(e.skeleton)&&this.skeletons.push(e.skeleton),e.morphTargetManager&&-1===this.morphTargetManagers.indexOf(e.morphTargetManager)&&this.morphTargetManagers.push(e.morphTargetManager)}for(const s of e.getChildren())i.has(s)||t.push(s);i.add(e)}this.populateRootNodes()}}class Xn{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if(Br.audioEngine?.audioContext&&(this.isPlaying||this.isPaused)){const e=this.isPaused?0:Br.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;const t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,s=null,r){if(this.autoplay=!1,this._loop=!1,this.useCustomAttenuation=!1,this.isPlaying=!1,this.isPaused=!1,this.refDistance=1,this.rolloffFactor=1,this.maxDistance=100,this.distanceModel="linear",this.metadata=null,this.onEndedObservable=new g,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=w.Zero(),this._localDirection=new w(1,0,0),this._volume=1,this._isReadyToPlay=!1,this._isDirectional=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._coneOuterGain=0,this._isOutputConnected=!1,this._urlType="Unknown",this.name=e,i=i||y.LastCreatedScene)if(this._scene=i,Xn._SceneComponentInitialization(i),this._readyToPlayCallback=s,this._customAttenuationFunction=(e,t,i,s,r)=>t0&&(s=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()})),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(t,(e=>{this._soundLoaded(e)}),void 0,!0,!0,(e=>{e&&J.Error("XHR "+e.status+" error on: "+t+"."),J.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}));break}}break;default:e=!1}e?s||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)):J.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){J.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),Br.audioEngine&&!Br.audioEngine.WarnedWebAudioUnsupported&&(J.Error("Web Audio is not supported by your browser."),Br.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)}dispose(){Br.audioEngine?.canUseWebAudio&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,-1===this.soundTrackId?this._scene.mainSoundTrack.removeSound(this):this._scene.soundTracks&&this._scene.soundTracks[this.soundTrackId].removeSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._streamingSource&&this._streamingSource.disconnect(),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){Br.audioEngine?.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){Br.audioEngine?.audioContext&&Br.audioEngine.audioContext.decodeAudioData(e,(e=>{this._audioBufferLoaded(e)}),(e=>{J.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)}))}setAudioBuffer(e){Br.audioEngine?.canUseWebAudio&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){e&&(this.loop=e.loop??this.loop,this.maxDistance=e.maxDistance??this.maxDistance,this.useCustomAttenuation=e.useCustomAttenuation??this.useCustomAttenuation,this.rolloffFactor=e.rolloffFactor??this.rolloffFactor,this.refDistance=e.refDistance??this.refDistance,this.distanceModel=e.distanceModel??this.distanceModel,this._playbackRate=e.playbackRate??this._playbackRate,this._length=e.length??void 0,this.spatialSound=e.spatialSound??this._spatialSound,this._setOffset(e.offset??void 0),this.setVolume(e.volume??this._volume),this._updateSpatialParameters(),this.isPlaying&&(this._streaming&&this._htmlAudioElement?(this._htmlAudioElement.playbackRate=this._playbackRate,this._htmlAudioElement.loop!==this.loop&&(this._htmlAudioElement.loop=this.loop)):this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.loop!==this.loop&&(this._soundSource.loop=this.loop),void 0!==this._offset&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),void 0!==this._length&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(0|this._offset)+this._length))))}_createSpatialParameters(){Br.audioEngine?.canUseWebAudio&&Br.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??Br.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){this._spatialSound&&(this._inputAudioNode=this._soundGain,this._soundPanner?.disconnect(),this._soundPanner=null,this._spatialSound=!1)}_updateSpatialParameters(){this._spatialSound&&(this._soundPanner?this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel):this._createSpatialParameters())}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){Br.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){Br.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const e=()=>{if(Br.audioEngine?.unlocked){const t=this._htmlAudioElement.play();void 0!==t&&t.catch((()=>{Br.audioEngine?.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Br.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))}))}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Br.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))};e()}}else{const r=()=>{if(Br.audioEngine?.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){const e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=Br.audioEngine?.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,void 0!==t&&(this._soundSource.loopStart=t),void 0!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},s=e?Br.audioEngine?.audioContext.currentTime+e:Br.audioEngine.audioContext.currentTime;const r=((this.isPaused?this.currentTime:0)+(this._offset??0))%this._soundSource.buffer.duration;this._soundSource.start(s,r,this.loop?void 0:i)}}};"suspended"===Br.audioEngine?.audioContext.state?this._tryToPlayTimeout=setTimeout((()=>{"suspended"===Br.audioEngine?.audioContext.state?(Br.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Br.audioEngine.onAudioUnlockedObservable.addOnce((()=>{r()})))):r()}),500):r()}this._startTime=s,this.isPlaying=!0,this.isPaused=!1}catch(e){J.Error("Error while trying to play audio: "+this.name+", "+e.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){if(this.isPlaying)if(this._clearTimeoutsAndObservers(),this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if(Br.audioEngine?.audioContext&&this._soundSource){const t=e?Br.audioEngine.audioContext.currentTime+e:void 0;this._soundSource.onended=()=>{this.isPlaying=!1,this.isPaused=!1,this._startTime=0,this._currentTime=0,this._soundSource&&(this._soundSource.onended=()=>{}),this._onended()},this._soundSource.stop(t)}else this.isPlaying=!1;else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):Br.audioEngine?.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=Br.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){Br.audioEngine?.canUseWebAudio&&this._soundGain&&(t&&Br.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(Br.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,Br.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,Br.audioEngine.audioContext.currentTime+t)):this._soundGain.gain.value=e),this._volume=e}setPlaybackRate(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))}getPlaybackRate(){return this._playbackRate}getVolume(){return this._volume}attachToMesh(e){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=e,this._spatialSound||(this._spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=e=>this._onRegisterAfterWorldMatrixUpdate(e),this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)}detachFromMesh(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)}_onRegisterAfterWorldMatrixUpdate(e){if(e.getBoundingInfo){const t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);Br.audioEngine?.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{const e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},i=new Xn(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){const e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,s){const r=e.name;let n;n=e.url?i+e.url:i+r;const o={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};let a;if(s){const e=()=>{s._isReadyToPlay?(a._audioBuffer=s.getAudioBuffer(),a._isReadyToPlay=!0,a.autoplay&&a.play(0,a._offset,a._length)):setTimeout(e,300)};a=new Xn(r,new ArrayBuffer(0),t,null,o),e()}else a=new Xn(r,n,t,(()=>{t.removePendingData(a)}),o),t.addPendingData(a);if(e.position){const t=w.FromArray(e.position);a.setPosition(t)}if(e.isDirectional&&(a.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const t=w.FromArray(e.localDirectionToMesh);a.setLocalDirectionToMesh(t)}if(e.connectedMeshId){const i=t.getMeshById(e.connectedMeshId);i&&a.attachToMesh(i)}return e.metadata&&(a.metadata=e.metadata),a}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(Br.audioEngine?.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}Xn._SceneComponentInitialization=e=>{throw ye("AudioSceneComponent")},u("BABYLON.Sound",Xn);class Yn{constructor(e,t={}){this.id=-1,this._isInitialized=!1,(e=e||y.LastCreatedScene)&&(this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1))}_initializeSoundTrackAudioGraph(){Br.audioEngine?.canUseWebAudio&&Br.audioEngine.audioContext&&(this._outputAudioNode=Br.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(Br.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(Br.audioEngine&&Br.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(e){this._isInitialized||this._initializeSoundTrackAudioGraph(),Br.audioEngine?.canUseWebAudio&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){const t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){Br.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){if(Br.audioEngine?.canUseWebAudio)for(let e=0;e{let r,n=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let o=0,a=e.sounds.length;o{e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)}))}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach((e=>{e.stop(),e.autoplay=!1,this.scene.mainSoundTrack.removeSound(e),t&&e.dispose()}))}dispose(){const e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(s=t.activeCameras[0]),this.audioListenerPositionProvider){const e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else s?this._cachedCameraPosition.equals(s.globalPosition)||(this._cachedCameraPosition.copyFrom(s.globalPosition),i.audioContext.listener.setPosition(s.globalPosition.x,s.globalPosition.y,s.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else s?(s.rigCameras&&s.rigCameras.length>0&&(s=s.rigCameras[0]),s.getViewMatrix().invertToRef(this._invertMatrixTemp),w.TransformNormalToRef(jn._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),isNaN(this._cameraDirectionTemp.x)||isNaN(this._cameraDirectionTemp.y)||isNaN(this._cameraDirectionTemp.z)||this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);for(e=0;e{let t=e._getComponent(ts.NAME_AUDIO);t||(t=new jn(e),e._addComponent(t))};class $n{constructor(e){this._texture=null,this._isEnabled=!0,this.isEnabled=!0,this.time=0,(e=e||y.LastCreatedScene)&&(this._scene=e,this.animationParameters=new F(0,0,0,30))}_markSubMeshesAsAttributesDirty(){for(const e of this._scene.meshes)e.bakedVertexAnimationManager===this&&e._markSubMeshesAsAttributesDirty()}bind(e,t=!1){if(!this._texture||!this._isEnabled)return;const i=this._texture.getSize();e.setFloat2("bakedVertexAnimationTextureSizeInverted",1/i.width,1/i.height),e.setFloat("bakedVertexAnimationTime",this.time),t||e.setVector4("bakedVertexAnimationSettings",this.animationParameters),e.setTexture("bakedVertexAnimationTexture",this._texture)}clone(){const e=new $n(this._scene);return this.copyTo(e),e}setAnimationParameters(e,t,i=0,s=30){this.animationParameters=new F(e,t,i,s)}dispose(e){e&&this._texture?.dispose()}getClassName(){return"BakedVertexAnimationManager"}copyTo(e){Pe.Clone((()=>e),this)}serialize(){return Pe.Serialize(this)}parse(e,t,i){Pe.Parse((()=>this),e,t,i)}}ae([fe(),de("_markSubMeshesAsAttributesDirty")],$n.prototype,"texture",void 0),ae([pe(),de("_markSubMeshesAsAttributesDirty")],$n.prototype,"isEnabled",void 0),ae([pe()],$n.prototype,"animationParameters",void 0),ae([pe()],$n.prototype,"time",void 0);class Kn{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return!!this._texture&&this._texture.isCube}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return void 0!==e?.shareDepth}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=Oe.Zero(),this._cachedBaseSize=Oe.Zero(),this._initialSamplingMode=2,this._texture=Kn._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return this.isReady()&&this._texture?this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}class qn extends Kn{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return!!this._texture&&this._texture._linearSpecularLOD}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=Si()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=qn.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new g,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?qn._IsScene(e)?this._scene=e:this._engine=e:this._scene=y.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}getTextureMatrix(){return B.IdentityReadOnly}getReflectionTextureMatrix(){return B.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,s,r,n){const o=this._getEngine();if(!o)return null;const a=o._getUseSRGBBuffer(!!r,t),l=o.getLoadedTexturesCache();for(let o=0;o=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const e=this._parentContainer.textures.indexOf(this);e>-1&&this._parentContainer.textures.splice(e,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;const t=Pe.Serialize(this);return Pe.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let s=0;s{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}function Qn(e,t,i=!1){const s=t.width,r=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let s=e[t];s<0?s=0:s>1&&(s=1),i[t]=255*s}e=i}const n=document.createElement("canvas");n.width=s,n.height=r;const o=n.getContext("2d");if(!o)return null;const a=o.createImageData(s,r);if(a.data.set(e),o.putImageData(a,0,0),i){const e=document.createElement("canvas");e.width=s,e.height=r;const t=e.getContext("2d");return t?(t.translate(0,r),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}qn.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,ae([pe()],qn.prototype,"uniqueId",void 0),ae([pe()],qn.prototype,"name",void 0),ae([pe()],qn.prototype,"metadata",void 0),ae([pe("hasAlpha")],qn.prototype,"_hasAlpha",void 0),ae([pe("getAlphaFromRGB")],qn.prototype,"_getAlphaFromRGB",void 0),ae([pe()],qn.prototype,"level",void 0),ae([pe("coordinatesIndex")],qn.prototype,"_coordinatesIndex",void 0),ae([pe()],qn.prototype,"optimizeUVAllocation",void 0),ae([pe("coordinatesMode")],qn.prototype,"_coordinatesMode",void 0),ae([pe()],qn.prototype,"wrapU",null),ae([pe()],qn.prototype,"wrapV",null),ae([pe()],qn.prototype,"wrapR",void 0),ae([pe()],qn.prototype,"anisotropicFilteringLevel",void 0),ae([pe()],qn.prototype,"isCube",null),ae([pe()],qn.prototype,"is3D",null),ae([pe()],qn.prototype,"is2DArray",null),ae([pe()],qn.prototype,"gammaSpace",null),ae([pe()],qn.prototype,"invertZ",void 0),ae([pe()],qn.prototype,"lodLevelInAlpha",void 0),ae([pe()],qn.prototype,"lodGenerationOffset",null),ae([pe()],qn.prototype,"lodGenerationScale",null),ae([pe()],qn.prototype,"linearSpecularLOD",null),ae([fe()],qn.prototype,"irradianceTexture",null),ae([pe()],qn.prototype,"isRenderTarget",void 0);class Zn extends qn{static _CreateVideoTexture(e,t,i,s=!1,r=!1,n=Zn.TRILINEAR_SAMPLINGMODE,o={},a,l=5){throw ye("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,s,r=Zn.TRILINEAR_SAMPLINGMODE,n=null,o=null,a=null,l=!1,h,c,u,d,p){let f;super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=null,this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedIdentity3x2=!0,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new g,this._isBlocking=!0,this.name=e||"",this.url=e;let _=!1,m=null,v=!0;"object"==typeof i&&null!==i?(f=i.noMipmap??!1,s=i.invertY??!Er.UseOpenGLOrientationForUV,r=i.samplingMode??Zn.TRILINEAR_SAMPLINGMODE,n=i.onLoad??null,o=i.onError??null,a=i.buffer??null,l=i.deleteBuffer??!1,h=i.format,c=i.mimeType,u=i.loaderOptions,d=i.creationFlags,_=i.useSRGBBuffer??!1,m=i.internalTexture??null,v=i.gammaSpace??v):f=!!i,this._gammaSpace=v,this._noMipmap=f,this._invertY=void 0===s?!Er.UseOpenGLOrientationForUV:s,this._initialSamplingMode=r,this._buffer=a,this._deleteBuffer=l,this._mimeType=c,this._loaderOptions=u,this._creationFlags=d,this._useSRGBBuffer=_,this._forcedExtension=p,h&&(this._format=h);const x=this.getScene(),T=this._getEngine();if(!T)return;T.onBeforeTextureInitObservable.notifyObservers(this);const S=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),n&&n(),!this.isBlocking&&x&&x.resetCachedMaterial()},E=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},o&&o(e,t),Zn.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!m)return this._delayedOnLoad=S,void(this._delayedOnError=E);if(this._texture=m??this._getFromCache(this.url,f,r,this._invertY,_,this.isCube),this._texture)if(this._texture.isReady)wt.SetImmediate((()=>S()));else{const e=this._texture.onLoadedObservable.add(S);this._texture.onErrorObservable.add((t=>{E(t.message,t.exception),this._texture?.onLoadedObservable.remove(e)}))}else if(x&&x.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=S,this._delayedOnError=E;else{try{this._texture=T.createTexture(this.url,f,this._invertY,x,r,S,E,this._buffer,void 0,this._format,this._forcedExtension,c,u,d,_)}catch(e){throw E("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,i,s){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=s,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;const e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?wt.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,s){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,w.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,s),s.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,s.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,s.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,this._cachedTextureMatrix&&this._rowGenerationMatrix||(this._cachedTextureMatrix=B.Zero(),this._rowGenerationMatrix=new B,this._t0=w.Zero(),this._t1=w.Zero(),this._t2=w.Zero()),B.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(B.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,U.Matrix[0]),B.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,U.Matrix[1]),B.ScalingToRef(this._cachedUScale,this._cachedVScale,0,U.Matrix[2]),B.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,U.Matrix[3]),U.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(U.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(U.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(U.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),B.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));const t=this.getScene();if(!t)return this._cachedTextureMatrix;const i=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&i!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedTextureMatrix}getReflectionTextureMatrix(){const e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode){if(this.coordinatesMode!==Zn.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=B.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=B.Zero());const t=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case Zn.PLANAR_MODE:B.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break;case Zn.PROJECTION_MODE:{B.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:B.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedReflectionTextureMatrix}clone(){const e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return Pe.Clone((()=>new Zn(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){const e=this.name;Zn.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(Zn._SerializeInternalTextureUniqueId);return t?((Zn.SerializeBuffers||Zn.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(t.base64String=this._buffer,t.name=t.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?t.base64String="data:image/png;base64,"+Ze(this._buffer):(Zn.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?function(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=e._readPixelsSync(t,i);return r?Qn(r,e.getSize(),s.invertY):null}(this):async function(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=await e.readPixels(t,i);return r?Qn(r,e.getSize(),s.invertY):null}(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,Zn._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=this._texture?.uniqueId??void 0),t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const s=Ti.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&s.updateSamplingMode&&s._samplingMode&&s._samplingMode!==e.samplingMode&&s.updateSamplingMode(e.samplingMode),s}if(e.isCube&&!e.isRenderTarget)return Zn._CubeTextureParser(e,t,i);const s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;let r;if(s){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}const n=t=>{if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){const i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i{let s=!0;if(e.noMipmap&&(s=!1),e.mirrorPlane){const i=Zn._CreateMirror(e.name,e.renderTargetSize,t,s);return i._waitingRenderList=e.renderList,i.mirrorPlane=Ps.FromArray(e.mirrorPlane),n(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{n(o)}),e._creationFlags??0,e._useSRGBBuffer??!1),o.name=e.name;else{let a;a=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||Zn.UseSerializedUrlIfAny)&&(a=e.url);const l={noMipmap:!s,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(o)},internalTexture:r};o=new Zn(a,t,l)}return o}}),e,t)}static CreateFromBase64String(e,t,i,s,r,n=Zn.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=5,h,c){return new Zn("data:"+t,i,s,r,n,o,a,e,!1,l,void 0,void 0,h,c)}static LoadFromDataString(e,t,i,s=!1,r,n=!0,o=Zn.TRILINEAR_SAMPLINGMODE,a=null,l=null,h=5,c,u){return"data:"!==e.substr(0,5)&&(e="data:"+e),new Zn(e,i,r,n,o,a,l,t,s,h,void 0,void 0,c,u)}}function Jn(e,t,i,s){let r,n=1;1===s?r=new Float32Array(t*i*4):2===s?(r=new Uint16Array(t*i*4),n=15360):r=7===s?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let s=0;s{throw ye("CubeTexture")},Zn._CreateMirror=(e,t,i,s)=>{throw ye("MirrorTexture")},Zn._CreateRenderTargetTexture=(e,t,i,s,r)=>{throw ye("RenderTargetTexture")},Zn.NEAREST_SAMPLINGMODE=1,Zn.NEAREST_NEAREST_MIPLINEAR=8,Zn.BILINEAR_SAMPLINGMODE=2,Zn.LINEAR_LINEAR_MIPNEAREST=11,Zn.TRILINEAR_SAMPLINGMODE=3,Zn.LINEAR_LINEAR_MIPLINEAR=3,Zn.NEAREST_NEAREST_MIPNEAREST=4,Zn.NEAREST_LINEAR_MIPNEAREST=5,Zn.NEAREST_LINEAR_MIPLINEAR=6,Zn.NEAREST_LINEAR=7,Zn.NEAREST_NEAREST=1,Zn.LINEAR_NEAREST_MIPNEAREST=9,Zn.LINEAR_NEAREST_MIPLINEAR=10,Zn.LINEAR_LINEAR=2,Zn.LINEAR_NEAREST=12,Zn.EXPLICIT_MODE=0,Zn.SPHERICAL_MODE=1,Zn.PLANAR_MODE=2,Zn.CUBIC_MODE=3,Zn.PROJECTION_MODE=4,Zn.SKYBOX_MODE=5,Zn.INVCUBIC_MODE=6,Zn.EQUIRECTANGULAR_MODE=7,Zn.FIXED_EQUIRECTANGULAR_MODE=8,Zn.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Zn.CLAMP_ADDRESSMODE=0,Zn.WRAP_ADDRESSMODE=1,Zn.MIRROR_ADDRESSMODE=2,Zn.UseSerializedUrlIfAny=!1,ae([pe()],Zn.prototype,"url",void 0),ae([pe()],Zn.prototype,"uOffset",void 0),ae([pe()],Zn.prototype,"vOffset",void 0),ae([pe()],Zn.prototype,"uScale",void 0),ae([pe()],Zn.prototype,"vScale",void 0),ae([pe()],Zn.prototype,"uAng",void 0),ae([pe()],Zn.prototype,"vAng",void 0),ae([pe()],Zn.prototype,"wAng",void 0),ae([pe()],Zn.prototype,"uRotationCenter",void 0),ae([pe()],Zn.prototype,"vRotationCenter",void 0),ae([pe()],Zn.prototype,"wRotationCenter",void 0),ae([pe()],Zn.prototype,"homogeneousRotationInUVTransform",void 0),ae([pe()],Zn.prototype,"isBlocking",null),u("BABYLON.Texture",Zn),Pe._TextureParser=Zn.Parse,Yi.prototype.updateRawTexture=function(e,t,i,s,r=null,n=0,o=!1){if(!e)return;const a=this._getRGBABufferInternalSizedFormat(n,i,o),l=this._getInternalFormat(i),h=this._getWebGLTextureType(n);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=n,e.invertY=s,e._compression=r),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[r],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,e.width,e.height,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0},Yi.prototype.createRawTexture=function(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new ti(this,ei.Raw);u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u._compression=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!r),this._doNotHandleContextLost||(u._bufferView=e),this.updateRawTexture(u,e,s,n,a,l,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);const d=this._getSamplingParameters(o,r);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),r&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u},Yi.prototype.createRawCubeTexture=function(e,t,i,s,r,n,o,a=null){const l=this._gl,h=new ti(this,ei.CubeRaw);h.isCube=!0,h.format=i,h.type=s,this._doNotHandleContextLost||(h._bufferViewArray=e);const c=this._getWebGLTextureType(s);let u=this._getInternalFormat(i);u===l.RGB&&(u=l.RGBA),c!==l.FLOAT||this._caps.textureFloatLinearFiltering?c!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?c!==l.FLOAT||this._caps.textureFloatRender?c!==l.HALF_FLOAT||this._caps.colorBufferFloat||(r=!1,J.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(r=!1,J.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(r=!1,o=1,J.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(r=!1,o=1,J.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."));const d=t,p=d;if(h.width=d,h.height=p,h.invertY=n,h._compression=a,!this.needPOTTextures||Ei(h.width)&&Ei(h.height)||(r=!1),e)this.updateRawCubeTexture(h,e,i,s,n,a);else{const e=this._getRGBABufferInternalSizedFormat(s),t=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let i=0;i<6;i++)a?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,this.getCaps().s3tc[a],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,e,h.width,h.height,0,u,c,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),e&&r&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const f=this._getSamplingParameters(o,r);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,f.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,f.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),h.generateMipMaps=r,h.samplingMode=o,h.isReady=!0,h},Yi.prototype.updateRawCubeTexture=function(e,t,i,s,r,n=null,o=0){e._bufferViewArray=t,e.format=i,e.type=s,e.invertY=r,e._compression=n;const a=this._gl,l=this._getWebGLTextureType(s);let h=this._getInternalFormat(i);const c=this._getRGBABufferInternalSizedFormat(s);let u=!1;h===a.RGB&&(h=a.RGBA,u=!0),this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===r||!!r),e.width%4!=0&&a.pixelStorei(a.UNPACK_ALIGNMENT,1);for(let i=0;i<6;i++){let r=t[i];n?a.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+i,o,this.getCaps().s3tc[n],e.width,e.height,0,r):(u&&(r=Jn(r,e.width,e.height,s)),a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+i,o,c,e.width,e.height,0,h,l,r))}(!this.needPOTTextures||Ei(e.width)&&Ei(e.height))&&e.generateMipMaps&&0===o&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},Yi.prototype.createRawCubeTextureFromUrl=function(e,t,i,s,r,n,o,a,l=null,h=null,c=3,u=!1){const d=this._gl,p=this.createRawCubeTexture(null,i,s,r,!n,u,c,null);t?.addPendingData(p),p.url=e,p.isReady=!1,this._internalTexturesCache.push(p);const f=e=>{const i=p.width,n=o(e);if(n){if(a){const e=this._getWebGLTextureType(r);let t=this._getInternalFormat(s);const o=this._getRGBABufferInternalSizedFormat(r);let l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,p,!0),this._unpackFlipY(!1);const h=a(n);for(let s=0;s>s;for(let i=0;i<6;i++){let a=h[s][i];l&&(a=Jn(a,n,n,r)),d.texImage2D(i,s,o,n,n,0,t,e,a)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(p,n,s,r,u);p.isReady=!0,t?.removePendingData(p),p.onLoadedObservable.notifyObservers(p),p.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,(e=>{f(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(p),h&&e&&h(e.status+" "+e.statusText,i)})),p},Yi.prototype.createRawTexture2DArray=eo(!1),Yi.prototype.createRawTexture3D=eo(!0),Yi.prototype.updateRawTexture2DArray=to(!1),Yi.prototype.updateRawTexture3D=to(!0);class io extends Zn{constructor(e,t,i,s,r,n=!0,o=!1,a=3,l=0,h,c){super(null,r,!n,o,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=s,this._engine&&(this._engine._caps.textureFloatLinearFiltering||1!==l||(a=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(a=1),this._texture=this._engine.createRawTexture(e,t,i,s,n,o,a,null,l,h??0,c??!1),this.wrapU=Zn.CLAMP_ADDRESSMODE,this.wrapV=Zn.CLAMP_ADDRESSMODE)}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}static CreateLuminanceTexture(e,t,i,s,r=!0,n=!1,o=3){return new io(e,t,i,1,s,r,n,o)}static CreateLuminanceAlphaTexture(e,t,i,s,r=!0,n=!1,o=3){return new io(e,t,i,2,s,r,n,o)}static CreateAlphaTexture(e,t,i,s,r=!0,n=!1,o=3){return new io(e,t,i,0,s,r,n,o)}static CreateRGBTexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=0,h=!1){return new io(e,t,i,4,s,r,n,o,a,l,h)}static CreateRGBATexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=0,h=!1){return new io(e,t,i,5,s,r,n,o,a,l,h)}static CreateRGBAStorageTexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=!1){return new io(e,t,i,5,s,r,n,o,a,1,l)}static CreateRTexture(e,t,i,s,r=!0,n=!1,o=Zn.TRILINEAR_SAMPLINGMODE,a=1){return new io(e,t,i,6,s,r,n,o,a)}static CreateRStorageTexture(e,t,i,s,r=!0,n=!1,o=Zn.TRILINEAR_SAMPLINGMODE,a=1){return new io(e,t,i,6,s,r,n,o,a,1)}}class so{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=B.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new g,this.bones=[],this._scene=i||y.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const s=this._scene.getEngine().getCaps();this._canUseTextureForBones=s.textureFloat&&s.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter((e=>!e.getParent()))}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return this._transformMatrices&&!this._isDirty||this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0)for(const e of this.bones)if(e._linkedTransformNode){const t=e._linkedTransformNode;e.position=t.position,t.rotationQuaternion?e.rotationQuaternion=t.rotationQuaternion:e.rotation=t.rotation,e.scaling=t.scaling}if(this.needInitialSkinMatrix)for(const e of this._meshesWithPoseMatrix){const t=e.getPoseMatrix();let i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){this._synchronizedWithMesh=e;for(const e of this.bones)e.getParent()||(e.getBindMatrix().multiplyToRef(t,U.Matrix[1]),e._updateAbsoluteBindMatrices(U.Matrix[1]));if(this.isUsingTextureForMatrices){const t=4*(this.bones.length+1);e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=io.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(e._bonesTransformMatrices,t),this.isUsingTextureForMatrices&&e._transformMatrixTexture&&e._transformMatrixTexture.update(e._bonesTransformMatrices)}}else{if(!this._isDirty)return;this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=io.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e{t.animations.forEach((t=>{t.enableBlending=!0,t.blendingSpeed=e}))}))}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){const e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){const e={};e.name=this.name,e.id=this.id,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let t=0;t0&&(r.animation=i.animations[0].serialize()),e.ranges=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const s={};s.name=t,s.from=i.from,s.to=i.to,e.ranges.push(s)}}return e}static Parse(e,t){const i=new so(e.name,e.id,t);let s;for(e.dimensionsAtRest&&(i.dimensionsAtRest=w.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,s=0;s-1&&(n=i.bones[t.parentBoneIndex]);const o=t.rest?B.FromArray(t.rest):null,a=new zs(t.name,i,n,B.FromArray(t.matrix),o,null,r);void 0!==t.id&&null!==t.id&&(a.id=t.id),t.length&&(a.length=t.length),t.metadata&&(a.metadata=t.metadata),t.animation&&a.animations.push(Ge.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,a._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(s=0;s0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()}))}}class ro{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==ss.POINTERDOWN?e.type===ss.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=je.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const i=e-this._lastInteractionTime-this._idleRotationWaitTime,s=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*s,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=e??je.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(e&&(e.computeWorldMatrix(!0),e.getBoundingInfo)){const t=e.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=.05*t,this.upperRadiusTransitionRange=.05*t}})):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))}))}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return!!this._attachedCamera&&this._attachedCamera.radius===e&&!this._radiusIsAnimating}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(no.EasingFunction.setEasingMode(no.EasingMode),this._radiusBounceTransition=Ge.CreateAnimation("radius",Ge.ANIMATIONTYPE_FLOAT,60,no.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=Ge.TransitionTo("radius",this._attachedCamera.radius+e,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,(()=>this._clearAnimationLocks()));t&&this._animatables.push(t)}_clearAnimationLocks(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()}}no.EasingFunction=new class extends Ks{constructor(e=1){super(),this.amplitude=e}easeInCore(e){const t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}}(.3),no.EasingMode=Ks.EASINGMODE_EASEOUT;class oo{constructor(){this.onTargetFramingAnimationEndObservable=new g,this._mode=oo.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}get name(){return"Framing"}set mode(e){this._mode=e}get mode(){return this._mode}set radiusScale(e){this._radiusScale=e}get radiusScale(){return this._radiusScale}set positionScale(e){this._positionScale=e}get positionScale(){return this._positionScale}set defaultElevation(e){this._defaultElevation=e}get defaultElevation(){return this._defaultElevation}set elevationReturnTime(e){this._elevationReturnTime=e}get elevationReturnTime(){return this._elevationReturnTime}set elevationReturnWaitTime(e){this._elevationReturnWaitTime=e}get elevationReturnWaitTime(){return this._elevationReturnWaitTime}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set framingTime(e){this._framingTime=e}get framingTime(){return this._framingTime}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();oo.EasingFunction.setEasingMode(oo.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==ss.POINTERDOWN?e.type===ss.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add((e=>{e&&e.getBoundingInfo&&this.zoomOnMesh(e,void 0,(()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()}))})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(s.minimumWorld,s.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(s.min,s.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const s=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new w(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t{this.stopAllAnimations(),s&&s(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),l&&this._animatables.push(l),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let s=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===oo.IgnoreBoundsSizeMode&&(s=si.upperRadiusLimit?i.upperRadiusLimit:s),s}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=je.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation,i=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=Ge.CreateAnimation("beta",Ge.ANIMATIONTYPE_FLOAT,60,oo.EasingFunction));const e=Ge.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(()=>{this._clearAnimationLocks(),this.stopAllAnimations()}));e&&this._animatables.push(e)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=je.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}oo.EasingFunction=new class extends Ks{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}},oo.EasingMode=Ks.EASINGMODE_EASEINOUT,oo.IgnoreBoundsSizeMode=0,oo.FitFrustumSidesMode=1;class ao{constructor(e,t,i=Number.MAX_VALUE,s=T){this.origin=e,this.direction=t,this.length=i,this.epsilon=s}clone(){return new ao(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const s=ao._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),r=ao._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let n,o,a,l,h=0,c=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xr.x)return!1}else if(n=1/this.direction.x,o=(s.x-this.origin.x)*n,a=(r.x-this.origin.x)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yr.y)return!1}else if(n=1/this.direction.y,o=(s.y-this.origin.y)*n,a=(r.y-this.origin.y)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zr.z)return!1}else if(n=1/this.direction.z,o=(s.z-this.origin.z)*n,a=(r.z-this.origin.z)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){const i=e.center.x-this.origin.x,s=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=i*i+s*s+r*r,o=e.radius+t,a=o*o;if(n<=a)return!0;const l=i*this.direction.x+s*this.direction.y+r*this.direction.z;return!(l<0)&&n-l*l<=a}intersectsTriangle(e,t,i){const s=ao._TmpVector3[0],r=ao._TmpVector3[1],n=ao._TmpVector3[2],o=ao._TmpVector3[3],a=ao._TmpVector3[4];t.subtractToRef(e,s),i.subtractToRef(e,r),w.CrossToRef(this.direction,r,n);const l=w.Dot(s,n);if(0===l)return null;const h=1/l;this.origin.subtractToRef(e,o);const c=w.Dot(o,n)*h;if(c<-this.epsilon||c>1+this.epsilon)return null;w.CrossToRef(o,s,a);const u=w.Dot(this.direction,a)*h;if(u<-this.epsilon||c+u>1+this.epsilon)return null;const d=w.Dot(r,a)*h;return d>this.length?null:new ar(1-c-u,c,d)}intersectsPlane(e){let t;const i=w.Dot(e.normal,this.direction);if(Math.abs(i)<9.99999997475243e-7)return null;{const s=w.Dot(e.normal,this.origin);return t=(-e.d-s)/i,t<0?t<-9.99999997475243e-7?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const e=(this.origin.y-t)/this.direction.y;return e>0?null:new w(this.origin.x+this.direction.x*-e,t,this.origin.z+this.direction.z*-e)}case"x":{const e=(this.origin.x-t)/this.direction.x;return e>0?null:new w(t,this.origin.y+this.direction.y*-e,this.origin.z+this.direction.z*-e)}case"z":{const e=(this.origin.z-t)/this.direction.z;return e>0?null:new w(this.origin.x+this.direction.x*-e,this.origin.y+this.direction.y*-e,t)}default:return null}}intersectsMesh(e,t,i,s=!1,r,n=!1){const o=U.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?ao.TransformToRef(this,o,this._tmpRay):this._tmpRay=ao.Transform(this,o),e.intersects(this._tmpRay,t,i,s,r,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let s=0;st.distance?1:0}intersectionSegment(e,t,i){const s=this.origin,r=U.Vector3[0],n=U.Vector3[1],o=U.Vector3[2],a=U.Vector3[3];t.subtractToRef(e,r),this.direction.scaleToRef(ao._Rayl,o),s.addToRef(o,n),e.subtractToRef(s,a);const l=w.Dot(r,r),h=w.Dot(r,o),c=w.Dot(o,o),u=w.Dot(r,a),d=w.Dot(o,a),p=l*c-h*h;let f,_,m=p,g=p;pm&&(f=m,_=d+h,g=c)),_<0?(_=0,-u<0?f=0:-u>l?f=m:(f=-u,m=l)):_>g&&(_=g,-u+h<0?f=0:-u+h>l?f=m:(f=-u+h,m=l));const v=Math.abs(f)0&&x<=this.length&&E.lengthSquared()=e.distance?null:h:null},ks.prototype._internalPick=function(e,t,i,s,r){let n=null;const o=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),a=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),n=this.cameraToUseForPointers||this.activeCamera;for(let o=0;o(this._tempPickingRay||(this._tempPickingRay=ao.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,r||null),this._tempPickingRay)),i,s,!0);return n&&(n.ray=this.createPickingRay(e,t,B.Identity(),r||null)),n},Object.defineProperty(ks.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),ks.prototype.pick=function(e,t,i,s,r,n,o=!1){const a=this._internalPick(((i,s)=>(this._tempPickingRay||(this._tempPickingRay=ao.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,r||null,!1,s),this._tempPickingRay)),i,s,!1,n);return a&&(a.ray=this.createPickingRay(e,t,B.Identity(),r||null)),a},ks.prototype.pickWithRay=function(e,t,i,s){const r=this._internalPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=B.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=ao.Zero()),ao.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i,!1,s);return r&&(r.ray=e),r},ks.prototype.multiPick=function(e,t,i,s,r){return this._internalMultiPick((i=>this.createPickingRay(e,t,i,s||null)),i,r)},ks.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=B.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=ao.Zero()),ao.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i)},or.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new ao(w.Zero(),w.Zero(),e),e,t,i)},or.prototype.getForwardRayToRef=function(e,t=100,i,s){i||(i=this.getWorldMatrix()),e.length=t,s?e.origin.copyFrom(s):e.origin.copyFrom(this.position);const r=U.Vector3[2];r.set(0,0,this._scene.useRightHandedSystem?-1:1);const n=U.Vector3[3];return w.TransformNormalToRef(r,i,n),w.NormalizeToRef(n,e.direction),e};class lo{static _RemoveAndStorePivotPoint(e){e&&0===lo._PivotCached&&(e.getPivotPointToRef(lo._OldPivotPoint),lo._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,lo._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(B.IdentityReadOnly),lo._OldPivotPoint.subtractToRef(e.getPivotPoint(),lo._PivotTranslation),lo._PivotTmpVector.copyFromFloats(1,1,1),lo._PivotTmpVector.subtractInPlace(e.scaling),lo._PivotTmpVector.multiplyInPlace(lo._PivotTranslation),e.position.addInPlace(lo._PivotTmpVector))),lo._PivotCached++}static _RestorePivotPoint(e){e&&!lo._OldPivotPoint.equalsToFloats(0,0,0)&&1===lo._PivotCached&&(e.setPivotPoint(lo._OldPivotPoint),e._postMultiplyPivotMatrix=lo._PivotPostMultiplyPivotMatrix,lo._PivotTmpVector.copyFromFloats(1,1,1),lo._PivotTmpVector.subtractInPlace(e.scaling),lo._PivotTmpVector.multiplyInPlace(lo._PivotTranslation),e.position.subtractInPlace(lo._PivotTmpVector)),this._PivotCached--}}function ho(e){const t=[],i=[],s=[],r=[],n=e.width||e.size||1,o=e.height||e.size||1,a=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE,l=n/2,h=o/2;i.push(-l,-h,0),s.push(0,0,-1),r.push(0,Er.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),s.push(0,0,-1),r.push(1,Er.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),s.push(0,0,-1),r.push(1,Er.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),s.push(0,0,-1),r.push(0,Er.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),Tr._ComputeSides(a,i,t,s,r,e.frontUVs,e.backUVs);const c=new Tr;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function co(e,t={},i=null){const s=new Un(e,i);return t.sideOrientation=Un._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,ho(t).applyToMesh(s,t.updatable),t.sourcePlane&&(s.translate(t.sourcePlane.normal,-t.sourcePlane.d),s.setDirection(t.sourcePlane.normal.scale(-1))),s}lo._PivotCached=0,lo._OldPivotPoint=new w,lo._PivotTranslation=new w,lo._PivotTmpVector=new w,lo._PivotPostMultiplyPivotMatrix=!1,Tr.CreatePlane=ho,Un.CreatePlane=(e,t,i,s,r)=>co(e,{size:t,width:t,height:t,sideOrientation:r,updatable:s},i);class uo{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new g,this.onDragStartObservable=new g,this.onDragEndObservable=new g,this.onEnabledObservable=new g,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new w(0,0,0),this._alternatePickedPoint=new w(0,0,0),this._worldDragAxis=new w(0,0,0),this._targetPosition=new w(0,0,0),this._attachedToElement=!1,this._startDragRay=new ao(new w,new w),this._lastPointerRay={},this._dragDelta=new w,this._pointA=new w(0,0,0),this._pointC=new w(0,0,0),this._localAxis=new w(0,0,0),this._lookAt=new w(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,uo._PlaneScene||(this._debugMode?uo._PlaneScene=this._scene:(uo._PlaneScene=new ks(this._scene.getEngine(),{virtual:!0}),uo._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce((()=>{uo._PlaneScene.dispose(),uo._PlaneScene=null})))),this._dragPlane=co("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:Un.DOUBLESIDE},uo._PlaneScene),this.lastDragPosition=new w(0,0,0);const i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add((e=>{if(this.enabled){if(e.type==ss.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&i(e.pickInfo.pickedMesh)&&-1===this._activeDragButton&&-1!==this.dragButtons.indexOf(e.event.button)&&(this._activeDragButton=e.event.button,this._activePointerInfo=e,this._startDrag(e.event.pointerId,e.pickInfo.ray,e.pickInfo.pickedPoint));else if(e.type==ss.POINTERUP)!this.startAndReleaseDragOnPointerEvents||this.currentDraggingPointerId!=e.event.pointerId||this._activeDragButton!==e.event.button&&-1!==this._activeDragButton||this.releaseDrag();else if(e.type==ss.POINTERMOVE){const t=e.event.pointerId;if(this.currentDraggingPointerId===uo._AnyMouseId&&t!==uo._AnyMouseId){const i=e.event;("mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[t]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=t)}this._lastPointerRay[t]||(this._lastPointerRay[t]=new ao(new w,new w)),e.pickInfo&&e.pickInfo.ray&&(this._lastPointerRay[t].origin.copyFrom(e.pickInfo.ray.origin),this._lastPointerRay[t].direction.copyFrom(e.pickInfo.ray.direction),this.currentDraggingPointerId==t&&this.dragging&&this._moveDrag(e.pickInfo.ray))}}else this._attachedToElement&&this.releaseDrag()})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{if(this._moving&&this.moveAttached){let e=!1;lo._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),e=!0),lo._RestorePivotPoint(this.attachedNode),e&&this.attachedNode.computeWorldMatrix()}}))}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){const e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}}startDrag(e=uo._AnyMouseId,t,i){this._startDrag(e,t,i);let s=this._lastPointerRay[e];e===uo._AnyMouseId&&(s=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),s&&this._moveDrag(s)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;lo._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);const s=this._pickWithRayOnDragPlane(this._startDragRay);s?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(s),this.onDragStartObservable.notifyObservers({dragPlanePoint:s,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),lo._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;const t=this._pickWithRayOnDragPlane(e);if(t){lo._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?w.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=w.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),lo._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(w.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*w.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);const t=w.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-t,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}return null}const i=this._dragPlane.forward,s=this._dragPlane.position,r=e.direction.dot(i);if(Math.abs(r).999?Math.abs(w.Dot(w.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(w.Right()):this._lookAt.copyFrom(w.UpReadOnly):(w.CrossToRef(this._localAxis,this._pointC,this._lookAt),w.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?w.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}}uo._AnyMouseId=-2;class po{}po.ANCHOR_SYSTEM="xr-anchor-system",po.BACKGROUND_REMOVER="xr-background-remover",po.HIT_TEST="xr-hit-test",po.MESH_DETECTION="xr-mesh-detection",po.PHYSICS_CONTROLLERS="xr-physics-controller",po.PLANE_DETECTION="xr-plane-detection",po.POINTER_SELECTION="xr-controller-pointer-selection",po.TELEPORTATION="xr-controller-teleportation",po.FEATURE_POINTS="xr-feature-points",po.HAND_TRACKING="xr-hand-tracking",po.IMAGE_TRACKING="xr-image-tracking",po.NEAR_INTERACTION="xr-near-interaction",po.DOM_OVERLAY="xr-dom-overlay",po.MOVEMENT="xr-controller-movement",po.LIGHT_ESTIMATION="xr-light-estimation",po.EYE_TRACKING="xr-eye-tracking",po.WALKING_LOCOMOTION="xr-walking-locomotion",po.LAYERS="xr-layers",po.DEPTH_SENSING="xr-depth-sensing",po.SPACE_WARP="xr-space-warp",po.RAW_CAMERA_ACCESS="xr-raw-camera-access";class fo{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)}))})),this._xrSessionManager.onXRSessionEnded.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)}))}))}static AddWebXRFeature(e,t,i=1,s=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),s&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,s){const r=this._AvailableFeatures[e][t];if(!r)throw new Error("feature not found");return r(i,s)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){const t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&(t.featureImplementation.attach()||Ii.Warn(`Feature ${e} failed to attach`))}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&(t.featureImplementation.detach()||Ii.Warn(`Feature ${e} failed to detach`))}disableFeature(e){const t="string"==typeof e?e:e.Name,i=this._features[t];return!(!i||!i.enabled||(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],0))}dispose(){this.getEnabledFeatures().forEach((e=>{this.disableFeature(e)}))}enableFeature(e,t="latest",i={},s=!0,r=!0){const n="string"==typeof e?e:e.Name;let o=0;if("string"==typeof t){if(!t)throw new Error(`Error in provided version - ${n} (${t})`);if(o="stable"===t?fo.GetStableVersionOfFeature(n):"latest"===t?fo.GetLatestVersionOfFeature(n):+t,-1===o||isNaN(o))throw new Error(`feature not found - ${n} (${t})`)}else o=t;const a=fo._ConflictingFeatures[n];if(void 0!==a&&-1!==this.getEnabledFeatures().indexOf(a))throw new Error(`Feature ${n} cannot be enabled while ${a} is enabled.`);const l=this._features[n],h=fo.ConstructFeature(n,o,this._xrSessionManager,i);if(!h)throw new Error(`feature not found - ${n}`);l&&this.disableFeature(n);const c=h();if(c.dependsOn){const e=c.dependsOn.every((e=>!!this._features[e]));if(!e)throw new Error(`Dependant features missing. Make sure the following features are enabled - ${c.dependsOn.join(", ")}`)}if(c.isCompatible())return this._features[n]={featureImplementation:c,enabled:!0,version:o,required:r},s?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(r)throw new Error("required feature not compatible");return Ii.Warn(`Feature ${n} not compatible with the current environment/browser and was not enabled.`),c}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){const t=this.getEnabledFeatures();for(const i of t){const t=this._features[i],s=t.featureImplementation.xrNativeFeatureName;if(s&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(s)&&e.requiredFeatures.push(s)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(s)&&e.optionalFeatures.push(s))),t.featureImplementation.getXRSessionInitExtension){const i=await t.featureImplementation.getXRSessionInitExtension();e={...e,...i}}}return e}}fo._AvailableFeatures={},fo._ConflictingFeatures={[po.TELEPORTATION]:po.MOVEMENT,[po.MOVEMENT]:po.TELEPORTATION};class _o{get xrNativeFeatureName(){return this._xrNativeFeatureName}set xrNativeFeatureName(e){!this._xrSessionManager.isNative&&e&&this._xrSessionManager.inXRSession&&-1===this._xrSessionManager.enabledFeatures?.indexOf(e)&&J.Warn(`The feature ${e} needs to be enabled before starting the XR session. Note - It is still possible it is not supported.`),this._xrNativeFeatureName=e}constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this._xrNativeFeatureName="",this.onFeatureAttachObservable=new g,this.onFeatureDetachObservable=new g}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;if(this._xrSessionManager.enabledFeatures){if(!this._xrSessionManager.isNative&&this.xrNativeFeatureName&&-1===this._xrSessionManager.enabledFeatures.indexOf(this.xrNativeFeatureName))return!1}else J.Warn("session.enabledFeatures is not available on this device. It is possible that this feature is not supported.");return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,(e=>this._onXRFrame(e))),this.onFeatureAttachObservable.notifyObservers(this),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach((e=>{e.observable.remove(e.observer)})),this.onFeatureDetachObservable.notifyObservers(this),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0,this.onFeatureAttachObservable.clear(),this.onFeatureDetachObservable.clear()}isCompatible(){return!0}_addNewAttachObserver(e,t,i){this._removeOnDetach.push({observable:e,observer:e.add(t,void 0,i)})}}class mo{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint,this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}mo.DistanceJoint=0,mo.HingeJoint=1,mo.BallAndSocketJoint=2,mo.WheelJoint=3,mo.SliderJoint=4,mo.PrismaticJoint=5,mo.UniversalJoint=6,mo.Hinge2Joint=mo.WheelJoint,mo.PointToPointJoint=8,mo.SpringJoint=9,mo.LockJoint=10,Un._PhysicsImpostorParser=function(e,t,i){return new go(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};class go{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},s){this.object=e,this.type=t,this._options=i,this._scene=s,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=w.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new L,this._tmpQuat2=new L,this.beforeStep=()=>{this._physicsEngine&&(this.object.translate(this._deltaPosition,-1),this._deltaRotationConjugated&&this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated,this.object.rotationQuaternion),this.object.computeWorldMatrix(!1),this.object.parent&&this.object.rotationQuaternion?(this.getParentsRotation(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this._tmpQuat)):this._tmpQuat.copyFrom(this.object.rotationQuaternion||new L),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach((e=>{e(this)})))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach((e=>{e(this)})),this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this),this.object.parent&&this.object.rotationQuaternion&&(this.getParentsRotation(),this._tmpQuat.conjugateInPlace(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this.object.rotationQuaternion)),this.object.setAbsolutePosition(this.object.position),this._deltaRotation?(this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotation,this.object.rotationQuaternion),this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation,go._TmpVecs[0]),this.object.translate(go._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=e=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent)return;if(!this._physicsEngine)return;const t=this._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(this.onCollideEvent&&this.onCollideEvent(this,t),this._onPhysicsCollideCallbacks.filter((e=>-1!==e.otherImpostors.indexOf(t))).forEach((i=>{i.callback(this,t,e.point,e.distance,e.impulse,e.normal)})))},this.object?(this.object.parent&&0!==i.mass&&J.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),this._scene&&(this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=L.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new L),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&J.Warn("You must affect impostors to children before affecting impostor to parent.")):J.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):J.Error("No object was provided. A physics object is obligatory")}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))}_getPhysicsParent(){return this.object.parent instanceof Wr?this.object.parent.physicsImpostor:null}isBodyInitRequired(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)}setScalingUpdated(){this.forceUpdate()}forceUpdate(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()}get physicsBody(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody}get parent(){return!this._options.ignoreParent&&this._parent?this._parent:null}set parent(e){this._parent=e}set physicsBody(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()}resetUpdateFlags(){this._bodyUpdateRequired=!1}getObjectExtents(){if(this.object.getBoundingInfo){const e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=go.IDENTITY_QUATERNION;const i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);const s=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return s.x=Math.abs(s.x),s.y=Math.abs(s.y),s.z=Math.abs(s.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),s}return go.DEFAULT_OBJECT_SIZE}getObjectCenter(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.centerWorld:this.object.position}getParam(e){return this._options[e]}setParam(e,t){this._options[e]=t,this._bodyUpdateRequired=!0}setMass(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)}getLinearVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):w.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):w.Zero()}setAngularVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)}executeNativeFunction(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)}registerBeforePhysicsStep(e){this._onBeforePhysicsStepCallbacks.push(e)}unregisterBeforePhysicsStep(e){const t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):J.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){const t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):J.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];let s=-1;this._onPhysicsCollideCallbacks.some(((e,r)=>{if(e.callback===t&&e.otherImpostors.length===i.length){const t=e.otherImpostors.every((e=>i.indexOf(e)>-1));return t&&(s=r),t}return!1}))?this._onPhysicsCollideCallbacks.splice(s,1):J.Warn("Function to remove was not found")}getParentsRotation(){let e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):L.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){const s=new mo(t,i);return this.addJoint(e,s),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,s,r){if(!this._physicsEngine)return this;const n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor?(this._physicsEngine&&n.appendAnchor(this,e,t,i,s,r),this):this}addHook(e,t,i,s){if(!this._physicsEngine)return this;const r=this._physicsEngine.getPhysicsPlugin();return r.appendAnchor?(this._physicsEngine&&r.appendHook(this,e,t,i,s),this):this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new go(e,this.type,this._options,this._scene):null}dispose(){this._physicsEngine&&(this._joints.forEach((e=>{this._physicsEngine&&this._physicsEngine.removeJoint(this,e.otherImpostor,e.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)}setDeltaPosition(e){this._deltaPosition.copyFrom(e)}setDeltaRotation(e){this._deltaRotation||(this._deltaRotation=new L),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,s,r){const n=go._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(r){const i=go._TmpQuat;o.rotationQuaternion.multiplyToRef(r,i),e.setRotationQuaternion(i,Fs.WORLD,t)}else e.setRotationQuaternion(o.rotationQuaternion,Fs.WORLD,t);n.x=0,n.y=0,n.z=0,i&&(n.x=i.x,n.y=i.y,n.z=i.z,e.getDirectionToRef(n,t,n),null==s&&(s=i.length()),n.x*=s,n.y*=s,n.z*=s),e.getParent()?(n.addInPlace(o.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(o.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,s,r,n){const o=this.object;if(o.rotationQuaternion)if(r){const i=go._TmpQuat;e.getRotationQuaternionToRef(Fs.WORLD,t,i),i.multiplyToRef(r,o.rotationQuaternion)}else e.getRotationQuaternionToRef(Fs.WORLD,t,o.rotationQuaternion);const a=go._TmpVecs[0],l=go._TmpVecs[1];n||((n=go._TmpVecs[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,a),null==s&&i&&(s=i.length()),null!=s&&(a.x+=l.x*s,a.y+=l.y*s,a.z+=l.z*s),o.setAbsolutePosition(a)}}var vo,xo,To,So,Eo,bo,Co,yo,Ao;go.DEFAULT_OBJECT_SIZE=new w(1,1,1),go.IDENTITY_QUATERNION=L.Identity(),go._TmpVecs=S.BuildArray(3,w.Zero),go._TmpQuat=L.Identity(),go.NoImpostor=0,go.SphereImpostor=1,go.BoxImpostor=2,go.PlaneImpostor=3,go.MeshImpostor=4,go.CapsuleImpostor=6,go.CylinderImpostor=7,go.ParticleImpostor=8,go.HeightmapImpostor=9,go.ConvexHullImpostor=10,go.CustomImpostor=100,go.RopeImpostor=101,go.ClothImpostor=102,go.SoftbodyImpostor=103,function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(vo||(vo={}));class Ro{static get ForceFullSceneLoadingForIncremental(){return Sr.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Sr.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Sr.ShowLoadingScreen}static set ShowLoadingScreen(e){Sr.ShowLoadingScreen=e}static get loggingLevel(){return Sr.loggingLevel}static set loggingLevel(e){Sr.loggingLevel=e}static get CleanBoneMatrixWeights(){return Sr.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Sr.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return Ro._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){return Ro._RegisteredPlugins[e]||(J.Warn("Unable to find a plugin to load "+e+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),Ro.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in Ro._RegisteredPlugins){const i=Ro._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return Ro._RegisteredPlugins[t]}return Ro.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const i=e.lastIndexOf("."),s=e.substring(i,e.length).toLowerCase();return Ro._GetPluginForExtension(s)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let s="Unable to load from "+(e.rawData?"binary data":e.url);return t?s+=`: ${t}`:i&&(s+=`: ${i}`),s}static _LoadData(e,t,i,s,r,n,o,a){const l=Ro._GetDirectLoad(e.url);if(e.rawData&&!o)throw"When using ArrayBufferView to load data the file extension must be provided.";const h=o?Ro._GetPluginForExtension(o):l?Ro._GetPluginForDirectLoad(e.url):Ro._GetPluginForFilename(e.url);if(e.rawData&&!h.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";let c;if(c=void 0!==h.plugin.createPlugin?h.plugin.createPlugin():h.plugin,!c)throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(Ro.OnPluginActivatedObservable.notifyObservers(c),l&&(c.canDirectLoad&&c.canDirectLoad(e.url)||!_i(e.url))){if(c.directLoad){const e=c.directLoad(t,l);e.then?e.then((e=>{i(c,e)})).catch((e=>{r("Error in directLoad of _loadData: "+e,e)})):i(c,e)}else i(c,l);return c}const u=h.isBinary,d=(e,s)=>{t.isDisposed?r("Scene has been disposed"):i(c,e,s)};let p=null,f=!1;const _=c.onDisposeObservable;_&&_.add((()=>{f=!0,p&&(p.abort(),p=null),n()}));const m=()=>{if(f)return;const i=(e,t)=>{r(e?.statusText,t)};if(!c.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";p=c.loadFile?c.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,d,s,u,i,a):t._loadFile(e.file||e.url,d,s,!0,u,i)},g=t.getEngine();let v=g.enableOfflineSupport;if(v){let i=!1;for(const s of t.disableOfflineSupportExceptionRules)if(s.test(e.url)){i=!0;break}v=!i}return v&&Br.OfflineProviderFactory?t.offlineProvider=Br.OfflineProviderFactory(e.url,m,g.disableManifestCheck):m(),c}static _GetFileInfo(e,t){let i,s,r=null,n=null;if(t)if(t.name){const e=t;i=`file:${e.name}`,s=e.name,r=e}else if(ArrayBuffer.isView(t))i="",s=Si(),n=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,s="";else{const r=t;if("/"===r.substr(0,1))return Ii.Error("Wrong sceneFilename parameter"),null;i=e+r,s=r}else i=e,s=Ii.GetFilename(e),e=Ii.GetFolderPath(e);return{url:i,rootUrl:e,name:s,file:r,rawData:n}}static GetPluginForExtension(e){return Ro._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!Ro._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){const t=e.extensions;Ro._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{Ro._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}}))}}static ImportMesh(e,t,i="",s=y.LastCreatedScene,r=null,n=null,o=null,a=null,l=""){if(!s)return J.Error("No scene available to import mesh to"),null;const h=Ro._GetFileInfo(t,i);if(!h)return null;const c={};s.addPendingData(c);const u=()=>{s.removePendingData(c)},d=(e,t)=>{const i=Ro._FormatErrorMessage(h,e,t);o?o(s,i,new Qe(i,qe,t)):J.Error(i),u()},p=n?e=>{try{n(e)}catch(e){d("Error in onProgress callback: "+e,e)}}:void 0,f=(e,t,i,n,o,a,l,u)=>{if(s.importedMeshesFiles.push(h.url),r)try{r(e,t,i,n,o,a,l,u)}catch(e){d("Error in onSuccess callback: "+e,e)}s.removePendingData(c)};return Ro._LoadData(h,s,((t,i,r)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,r)),t.importMesh){const r=[],n=[],o=[];if(!t.importMesh(e,s,i,h.rootUrl,r,n,o,d))return;s.loadingPluginName=t.name,f(r,n,o,[],[],[],[],[])}else t.importMeshAsync(e,s,i,h.rootUrl,p,h.name).then((e=>{s.loadingPluginName=t.name,f(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights,e.spriteManagers)})).catch((e=>{d(e.message,e)}))}),p,d,u,a,l)}static ImportMeshAsync(e,t,i="",s=y.LastCreatedScene,r=null,n=null,o=""){return new Promise(((a,l)=>{Ro.ImportMesh(e,t,i,s,((e,t,i,s,r,n,o,l)=>{a({meshes:e,particleSystems:t,skeletons:i,animationGroups:s,transformNodes:r,geometries:n,lights:o,spriteManagers:l})}),r,((e,t,i)=>{l(i||new Error(t))}),n,o)}))}static Load(e,t="",i=y.LastCreatedEngine,s=null,r=null,n=null,o=null,a=""){return i?Ro.Append(e,t,new ks(i),s,r,n,o,a):(Ii.Error("No engine available"),null)}static LoadAsync(e,t="",i=y.LastCreatedEngine,s=null,r=null,n=""){return new Promise(((o,a)=>{Ro.Load(e,t,i,(e=>{o(e)}),s,((e,t,i)=>{a(i||new Error(t))}),r,n)}))}static Append(e,t="",i=y.LastCreatedScene,s=null,r=null,n=null,o=null,a=""){if(!i)return J.Error("No scene available to append to"),null;const l=Ro._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)};Ro.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1})));const u=(e,t)=>{const s=Ro._FormatErrorMessage(l,e,t);n?n(i,s,new Qe(s,qe,t)):J.Error(s),c()},d=r?e=>{try{r(e)}catch(e){u("Error in onProgress callback",e)}}:void 0,p=()=>{if(s)try{s(i)}catch(e){u("Error in onSuccess callback",e)}i.removePendingData(h)};return Ro._LoadData(l,i,((e,t)=>{if(e.load){if(!e.load(i,t,l.rootUrl,u))return;i.loadingPluginName=e.name,p()}else e.loadAsync(i,t,l.rootUrl,d,l.name).then((()=>{i.loadingPluginName=e.name,p()})).catch((e=>{u(e.message,e)}))}),d,u,c,o,a)}static AppendAsync(e,t="",i=y.LastCreatedScene,s=null,r=null,n=""){return new Promise(((o,a)=>{Ro.Append(e,t,i,(e=>{o(e)}),s,((e,t,i)=>{a(i||new Error(t))}),r,n)}))}static LoadAssetContainer(e,t="",i=y.LastCreatedScene,s=null,r=null,n=null,o=null,a=""){if(!i)return J.Error("No scene available to load asset container to"),null;const l=Ro._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)},u=(e,t)=>{const s=Ro._FormatErrorMessage(l,e,t);n?n(i,s,new Qe(s,qe,t)):J.Error(s),c()},d=r?e=>{try{r(e)}catch(e){u("Error in onProgress callback",e)}}:void 0,p=e=>{if(s)try{s(e)}catch(e){u("Error in onSuccess callback",e)}i.removePendingData(h)};return Ro._LoadData(l,i,((e,t)=>{if(e.loadAssetContainer){const s=e.loadAssetContainer(i,t,l.rootUrl,u);if(!s)return;s.populateRootNodes(),i.loadingPluginName=e.name,p(s)}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,l.rootUrl,d,l.name).then((t=>{t.populateRootNodes(),i.loadingPluginName=e.name,p(t)})).catch((e=>{u(e.message,e)})):u("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),d,u,c,o,a)}static LoadAssetContainerAsync(e,t="",i=y.LastCreatedScene,s=null,r=null){return new Promise(((n,o)=>{Ro.LoadAssetContainer(e,t,i,(e=>{n(e)}),s,((e,t,i)=>{o(i||new Error(t))}),r)}))}static ImportAnimations(e,t="",i=y.LastCreatedScene,s=!0,r=vo.Clean,n=null,o=null,a=null,l=null,h=null){if(!i)return void J.Error("No scene available to load animations to");if(s){for(const e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach((e=>{e.dispose()})),i.getNodes().forEach((e=>{e.animations&&(e.animations=[])}))}else switch(r){case vo.Clean:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case vo.Stop:i.animationGroups.forEach((e=>{e.stop()}));break;case vo.Sync:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case vo.NoSync:break;default:return void J.Error("Unknown animation group loading mode value '"+r+"'")}const c=i.animatables.length;this.LoadAssetContainer(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(c),n),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)}),a,l,h)}static ImportAnimationsAsync(e,t="",i=y.LastCreatedScene,s=!0,r=vo.Clean,n=null,o=null,a=null,l=null,h=null){return new Promise(((o,l)=>{Ro.ImportAnimations(e,t,i,s,r,n,(e=>{o(e)}),a,((e,t,i)=>{l(i||new Error(t))}),h)}))}}Ro.NO_LOGGING=0,Ro.MINIMAL_LOGGING=1,Ro.SUMMARY_LOGGING=2,Ro.DETAILED_LOGGING=3,Ro.OnPluginActivatedObservable=new g,Ro._RegisteredPlugins={},Ro._ShowingLoadingScreen=!1;class Io extends Dn{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new B,this._storeEffectOnSubMeshes=i}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return!!e&&(!this._storeEffectOnSubMeshes||!e.subMeshes||0===e.subMeshes.length||this.isReadyForSubMesh(e,e.subMeshes[0],t))}_isReadyForSubMesh(e){const t=e.materialDefines;return!(this.checkReadyOnEveryCall||!e.effect||!t||t._renderId!==this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,i){super._afterBind(e,t,i),this.getScene()._cachedEffect=t,i?i._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,i,s=1){return i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,s)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}!function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.Object=256]="Object",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.All=4095]="All"}(xo||(xo={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(To||(To={}));class Po{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}get shaderLanguage(){return this.sharedData.nodeMaterial.shaderLanguage}get fSuffix(){return this.shaderLanguage===ht.WGSL?"f":""}finalize(e){const t=e.sharedData.emitComments,i=this.target===To.Fragment;this.shaderLanguage===ht.WGSL?this.compilationString=i?`\n${t?"//Entry point\n":""}@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${this.compilationString}`:`\n${t?"//Entry point\n":""}@vertex\nfn main(input: VertexInputs) -> FragmentInputs{\n${this.compilationString}`:this.compilationString=`\n${t?"//Entry point\n":""}void main(void) {\n${this.compilationString}`,this._constantDeclaration&&(this.compilationString=`\n${t?"//Constants\n":""}${this._constantDeclaration}\n${this.compilationString}`);let s="";for(const e in this.functions)s+=this.functions[e]+"\n";if(this.compilationString=`\n${s}\n${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString}\n${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString}\n${this._injectAtEnd}`),this.compilationString=`${this.compilationString}\n}`,this.sharedData.varyingDeclaration&&(this.compilationString=`\n${t?"//Varyings\n":""}${this.sharedData.varyingDeclaration}\n${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=`\n${t?"//Samplers\n":""}${this._samplerDeclaration}\n${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=`\n${t?"//Uniforms\n":""}${this._uniformDeclaration}\n${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=`\n${t?"//Attributes\n":""}${this._attributeDeclaration}\n${this.compilationString}`),this.shaderLanguage!==ht.WGSL){this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defines(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,i&&(this.compilationString="#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n"+this.compilationString);for(const e in this.extensions){const t=this.extensions[e];this.compilationString=`\n${t}\n${this.compilationString}`}}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e]?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){this.samplers.indexOf(e)<0&&(this.shaderLanguage===ht.WGSL?(this._samplerDeclaration+=`var ${e+"Sampler"}: sampler;\n`,this._samplerDeclaration+=`var ${e}: texture_2d;\n`):this._samplerDeclaration+=`uniform sampler2D ${e};\n`,this.samplers.push(e))}_emit2DArraySampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2DArray ${e};\n`,this.samplers.push(e))}_getGLType(e){switch(e){case xo.Float:return"float";case xo.Int:return"int";case xo.Vector2:return"vec2";case xo.Color3:case xo.Vector3:return"vec3";case xo.Color4:case xo.Vector4:return"vec4";case xo.Matrix:return"mat4"}return""}_getShaderType(e){const t=this.shaderLanguage===ht.WGSL;switch(e){case xo.Float:return t?"f32":"float";case xo.Int:return t?"i32":"int";case xo.Vector2:return t?"vec2f":"vec2";case xo.Color3:case xo.Vector3:return t?"vec3f":"vec3";case xo.Color4:case xo.Vector4:return t?"vec4f":"vec4";case xo.Matrix:return t?"mat4x4f":"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i}\n${t}\n#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+"\n"+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`;let s=Ft.GetIncludesShadersStore(this.shaderLanguage)[e]+"\n";if(this.sharedData.emitComments&&(s=t+"\n"+s),!i)return s;if(i.replaceStrings)for(let e=0;e${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`:this.functions[r]=`#include<${e}>${i?.substitutionVars?"("+i?.substitutionVars+")":""}\n`,void(this.sharedData.emitComments&&(this.functions[r]=t+"\n"+this.functions[r]));const n=Ft.GetIncludesShadersStore(this.shaderLanguage);if(this.functions[r]=n[e],this.sharedData.emitComments&&(this.functions[r]=t+"\n"+this.functions[r]),i.removeIfDef&&(this.functions[r]=this.functions[r].replace(/^\s*?#ifdef.+$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#endif.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#else.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[r]=this.functions[r].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[r]=this.functions[r].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[r]=this.functions[r].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(let e=0;e")}_convertTernaryOperandsToWGSL(e){return e.replace(new RegExp("\\[(.*?)\\?(.*?):(.*)\\]","g"),((e,t,i,s)=>`select(${s}, ${i}, ${t})`))}_convertModOperatorsToWGSL(e){return e.replace(new RegExp("mod\\((.+?),\\s*(.+?)\\)","g"),((e,t,i)=>`((${t})%(${i}))`))}_convertConstToWGSL(e){return e.replace(new RegExp("const var","g"),"const")}_convertInnerFunctionsToWGSL(e){return e.replace(new RegExp("inversesqrt","g"),"inverseSqrt")}_convertFunctionsToWGSL(e){const t=/var\s+(\w+)\s*:\s*(\w+)\((.*)\)/g;let i;for(;null!==(i=t.exec(e));){const t=i[1],s=i[2],r=i[3].replace(/var\s/g,"");e=e.replace(i[0],`fn ${t}(${r}) -> ${s}`)}return e}_babylonSLtoWGSL(e){return e=this._convertVariableDeclarationToWGSL("void","voidnull",e),e=this._convertVariableDeclarationToWGSL("bool","bool",e),e=this._convertVariableDeclarationToWGSL("int","i32",e),e=this._convertVariableDeclarationToWGSL("uint","u32",e),e=this._convertVariableDeclarationToWGSL("float","f32",e),e=this._convertVariableDeclarationToWGSL("vec2","vec2f",e),e=this._convertVariableDeclarationToWGSL("vec3","vec3f",e),e=this._convertVariableDeclarationToWGSL("vec4","vec4f",e),e=this._convertVariableDeclarationToWGSL("mat2","mat2x2f",e),e=this._convertVariableDeclarationToWGSL("mat3","mat3x3f",e),e=this._convertVariableDeclarationToWGSL("mat4","mat4x4f",e),e=this._convertVariableConstructorsToWGSL("float","f32",e),e=this._convertVariableConstructorsToWGSL("vec2","vec2f",e),e=this._convertVariableConstructorsToWGSL("vec3","vec3f",e),e=this._convertVariableConstructorsToWGSL("vec4","vec4f",e),e=this._convertVariableConstructorsToWGSL("mat2","mat2x2f",e),e=this._convertVariableConstructorsToWGSL("mat3","mat3x3f",e),e=this._convertVariableConstructorsToWGSL("mat4","mat4x4f",e),e=this._convertTernaryOperandsToWGSL(e),e=this._convertModOperatorsToWGSL(e),e=this._convertConstToWGSL(e),e=this._convertInnerFunctionsToWGSL(e),e=(e=this._convertOutParametersToWGSL(e)).replace(/\[\*\]/g,"*"),(e=(e=(e=this._convertFunctionsToWGSL(e)).replace(/\s->\svoidnull/g,"")).replace(/dFdx/g,"dpdx")).replace(/dFdy/g,"dpdy")}_convertTernaryOperandsToGLSL(e){return e.replace(new RegExp("\\[(.+?)\\?(.+?):(.+)\\]","g"),((e,t,i,s)=>`${t} ? ${i} : ${s}`))}_babylonSLtoGLSL(e){return e=e.replace(/\[\*\]/g,""),this._convertTernaryOperandsToGLSL(e)}}class Mo{constructor(){this.temps=[],this.varyings=[],this.varyingDeclaration="",this.inputBlocks=[],this.textureBlocks=[],this.bindableBlocks=[],this.forcedBindableBlocks=[],this.blocksWithFallbacks=[],this.blocksWithDefines=[],this.repeatableContentBlocks=[],this.dynamicUniformBlocks=[],this.blockingBlocks=[],this.animatedInputs=[],this.variableNames={},this.defineNames={},this.hints={needWorldViewMatrix:!1,needWorldViewProjectionMatrix:!1,needAlphaBlending:!1,needAlphaTesting:!1},this.checks={emitVertex:!1,emitFragment:!1,notConnectedNonOptionalInputs:new Array},this.allowEmptyVertexProgram=!1,this.variableNames.position=0,this.variableNames.normal=0,this.variableNames.tangent=0,this.variableNames.uv=0,this.variableNames.uv2=0,this.variableNames.uv3=0,this.variableNames.uv4=0,this.variableNames.uv5=0,this.variableNames.uv6=0,this.variableNames.color=0,this.variableNames.matricesIndices=0,this.variableNames.matricesWeights=0,this.variableNames.matricesIndicesExtra=0,this.variableNames.matricesWeightsExtra=0,this.variableNames.diffuseBase=0,this.variableNames.specularBase=0,this.variableNames.worldPos=0,this.variableNames.shadow=0,this.variableNames.view=0,this.variableNames.vTBN=0,this.defineNames.MAINUV0=0,this.defineNames.MAINUV1=0,this.defineNames.MAINUV2=0,this.defineNames.MAINUV3=0,this.defineNames.MAINUV4=0,this.defineNames.MAINUV5=0,this.defineNames.MAINUV6=0,this.defineNames.MAINUV7=0}emitErrors(){let e="";this.checks.emitVertex||this.allowEmptyVertexProgram||(e+="NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.\n"),this.checks.emitFragment||(e+="NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\n");for(const t of this.checks.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional.\n`;if(e)throw"Build of NodeMaterial failed:\n"+e}}class Do{constructor(e){if(this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!1,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)-1===this._keys.indexOf(e)&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;tthis._setDefaultValue(e)))}_setDefaultValue(e){const t=this._externalProperties?.[e]?.type??typeof this[e],i=this._externalProperties?.[e]?.default;switch(t){case"number":this[e]=i??0;break;case"string":this[e]=i??"";break;default:this[e]=i??!1}}toString(){let e="";for(let t=0;tthis._connectedPointBackingField=e)),this._connectedPointBackingField&&(this._connectedPointTypeChangedObserver=this._connectedPointBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get _typeConnectionSource(){return this._typeConnectionSourceBackingField}set _typeConnectionSource(e){this._typeConnectionSourceBackingField!==e&&(this._typeConnectionSourceTypeChangedObserver?.remove(),this._updateTypeDependentState((()=>this._typeConnectionSourceBackingField=e)),this._typeConnectionSourceBackingField&&(this._typeConnectionSourceTypeChangedObserver=this._typeConnectionSourceBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get _defaultConnectionPointType(){return this._defaultConnectionPointTypeBackingField}set _defaultConnectionPointType(e){this._updateTypeDependentState((()=>this._defaultConnectionPointTypeBackingField=e))}get _linkedConnectionSource(){return this._linkedConnectionSourceBackingField}set _linkedConnectionSource(e){this._linkedConnectionSourceBackingField!==e&&(this._linkedConnectionSourceTypeChangedObserver?.remove(),this._updateTypeDependentState((()=>this._linkedConnectionSourceBackingField=e)),this._linkedConnectionSourceBackingField&&(this._linkedConnectionSourceTypeChangedObserver=this._linkedConnectionSourceBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get direction(){return this._direction}get declarationVariableName(){return this._ownerBlock.isInput?this._ownerBlock.declarationVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.declarationVariableName}get associatedVariableName(){return this._ownerBlock.isInput?this._ownerBlock.associatedVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}get type(){if(this._type===xo.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===xo.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._updateTypeDependentState((()=>this._type=e))}get target(){return this._prioritizeVertex&&this._ownerBlock?this._target!==To.VertexAndFragment?this._target:this._ownerBlock.target===To.Fragment?To.Fragment:To.Vertex:this._target}set target(e){this._target=e}get isConnected(){return null!==this.connectedPoint||this.hasEndpoints}get isConnectedToInputBlock(){return null!==this.connectedPoint&&this.connectedPoint.ownerBlock.isInput}get connectInputBlock(){return this.isConnectedToInputBlock?this.connectedPoint.ownerBlock:null}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return 0===this._endpoints.length?[]:this._endpoints.map((e=>e.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===To.Vertex)return!0;if((e.ownerBlock.target===To.Neutral||e.ownerBlock.target===To.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isDirectlyConnectedToVertexOutput)))return!0}return!1}get isConnectedInVertexShader(){if(this.target===To.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===To.Vertex)return!0;if(e.target===To.Vertex)return!0;if((e.ownerBlock.target===To.Neutral||e.ownerBlock.target===To.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInVertexShader)))return!0}return!1}get isConnectedInFragmentShader(){if(this.target===To.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===To.Fragment)return!0;if((e.ownerBlock.target===To.Neutral||e.ownerBlock.target===To.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0}return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPointBackingField=null,this._endpoints=new Array,this._typeConnectionSourceBackingField=null,this._defaultConnectionPointTypeBackingField=null,this._linkedConnectionSourceBackingField=null,this._acceptedConnectionPointType=null,this._type=xo.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new g,this.onDisconnectionObservable=new g,this.onTypeChangedObservable=new g,this._isTypeChangeObservableNotifying=!1,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=To.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===So.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===To.Fragment){if(i.target===To.Vertex)return So.TargetIncompatible;for(const e of i.outputs)if(e.ownerBlock.target!=To.Neutral&&e.isConnectedInVertexShader)return So.TargetIncompatible}if(this.type!==e.type&&e.innerType!==xo.AutoDetect)return Oo.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&Oo.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?So.Compatible:So.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return So.TypeIncompatible;let s=i,r=t;return this.direction===Eo.Input&&(s=t,r=i),s.isAnAncestorOf(r)?So.HierarchyIssue:So.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear(),this.onTypeChangedObservable.clear(),this._connectedPoint=null,this._typeConnectionSource=null,this._linkedConnectionSource=null}_updateTypeDependentState(e){const t=this.type;e(),this.type!==t&&this._notifyTypeChanged()}_notifyTypeChanged(){this._isTypeChangeObservableNotifying||(this._isTypeChangeObservableNotifying=!0,this.onTypeChangedObservable.notifyObservers(this.type),this._isTypeChangeObservableNotifying=!1)}}class No{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){this._target&e||(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}constructor(e,t=To.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===To.Neutral,this._isFinalMerger=i,this._isInput="InputBlock"===this.getClassName(),this._isTeleportOut="NodeMaterialTeleportOutBlock"===this.getClassName(),this._isTeleportIn="NodeMaterialTeleportInBlock"===this.getClassName(),this._name=e,this.uniqueId=Ds.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===To.Neutral}initialize(e){}bind(e,t,i,s){}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return-1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some((e=>e.isConnectedInFragmentShader))}registerInput(e,t,i=!1,s,r){return(r=r??new Oo(e,this,Eo.Input)).type=t,r.isOptional=i,s&&(r.target=s),this._inputs.push(r),this}registerOutput(e,t,i,s){return(s=s??new Oo(e,this,Eo.Output)).type=t,i&&(s.target=i),this._outputs.push(s),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!(t.connectedPoint||e&&e.type!==t.type&&t.type!==xo.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===To.Neutral||e.target&t.target)return t;return null}getSiblingOutput(e){const t=this._outputs.indexOf(e);return-1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){if(i.ownerBlock===e)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),s=!0;for(;s;){const r=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&r&&i.canConnectTo(r))i.connectTo(r),s=!1;else{if(!i)throw"Unable to find a compatible match";i=this.getSiblingOutput(i)}}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,s){}provideFallbacks(e,t){}initializeDefines(e,t,i,s=!1){}prepareDefines(e,t,i,s=!1,r){}autoConfigure(e,t=(()=>!0)){}replaceRepeatableContent(e,t,i,s){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some((e=>e.isDirectlyConnectedToVertexOutput))||this.target===To.Vertex||this.target!==To.VertexAndFragment&&this.target!==To.Neutral||!this._outputs.some((e=>e.isConnectedInVertexShader)))}isReady(e,t,i,s=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,s){e.build(t,s);const r=null!=t._vertexState,n=e._buildTarget===To.Vertex&&e.target!==To.VertexAndFragment;if(r&&(!(e.target&e._buildTarget)||!(e.target&i.target)||this.target!==To.VertexAndFragment&&n)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){const e=i.connectedPoint;if(t._vertexState._emitVaryingFromString("v_"+e.declarationVariableName,e.type)){const i=t.shaderLanguage===ht.WGSL?"vertexOutputs.":"";t._vertexState.compilationString+=`${i}${"v_"+e.declarationVariableName} = ${e.associatedVariableName};\n`}const s=t.shaderLanguage===ht.WGSL?"fragmentInputs.":"";i.associatedVariableName=s+"v_"+e.declarationVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){const t=["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"];for(const i of t)if(e===i)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(const t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==To.Neutral){if(!(i.target&this.target))continue;if(!(i.target&e.target))continue}const s=i.connectedPoint.ownerBlock;s&&s!==this&&this._processBuild(s,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&J.Log(`${e.target===To.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case To.Vertex:e.sharedData.checks.emitVertex=!0;break;case To.Fragment:e.sharedData.checks.emitFragment=!0}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=`\n//${this.name}\n`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(const i of this._outputs)if(i.target&e.target)for(const s of i.endpoints){const i=s.ownerBlock;i&&i.target&e.target&&-1!==t.indexOf(i)&&this._processBuild(i,e,s,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector};\n${e}.visibleOnFrame = ${this.visibleOnFrame};\n${e}.target = ${this.target};\n`}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let s=`\n// ${this.getClassName()}\n`;this.comments&&(s+=`// ${this.comments}\n`),s+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\n`,s+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint.ownerBlock;-1===t.indexOf(r)&&(s+=r._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const r of i.endpoints){const i=r.ownerBlock;i&&-1===t.indexOf(i)&&(s+=i._dumpCode(e,t))}return s}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}return t}clone(e,t=""){const i=this.serialize(),s=d(i.customType);if(s){const r=new s;return r._deserialize(i,e,t),r}return null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i,s){this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=e.target??this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach(((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class wo extends No{constructor(e){super(e,To.Neutral),this.complementW=1,this.complementZ=0,this.target=To.Vertex,this.registerInput("vector",xo.AutoDetect),this.registerInput("transform",xo.Matrix),this.registerOutput("output",xo.Vector4),this.registerOutput("xyz",xo.Vector3),this._inputs[0].onConnectionObservable.add((e=>{if(e.ownerBlock.isInput){const t=e.ownerBlock;"normal"!==t.name&&"tangent"!==t.name||(this.complementW=0)}}))}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.transform,s=e._getShaderType(xo.Vector4),r=e._getShaderType(xo.Vector3);if(t.connectedPoint){if(0===this.complementW){const n=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",n),e.sharedData.blocksWithDefines.push(this);const o=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.shaderLanguage===ht.WGSL?e.compilationString+=`var ${o}: mat3x3f = mat3x3f(${i.associatedVariableName}[0].xyz, ${i.associatedVariableName}[1].xyz, ${i.associatedVariableName}[2].xyz);\n`:e.compilationString+=`mat3 ${o} = mat3(${i.associatedVariableName});\n`,e.compilationString+="#ifdef NONUNIFORMSCALING\n",e.compilationString+=`${o} = transposeMat3(inverseMat3(${o}));\n`,e.compilationString+="#endif\n",t.connectedPoint.type){case xo.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${s}(${o} * ${r}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\n`;break;case xo.Vector3:case xo.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${s}(${o} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${s}(${o} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\n`}}else{const r=i.associatedVariableName;switch(t.connectedPoint.type){case xo.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${r} * ${s}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\n`;break;case xo.Vector3:case xo.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${r} * ${s}(${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${r} * ${t.associatedVariableName};\n`}}this.xyz.hasEndpoints&&(e.compilationString+=e._declareOutput(this.xyz)+` = ${this.output.associatedVariableName}.xyz;\n`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){const e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ};\n`;return e+=`${this._codeVariableName}.complementW = ${this.complementW};\n`,e}}u("BABYLON.TransformBlock",wo);class Fo extends No{constructor(e){super(e,To.Vertex,!0),this.registerInput("vector",xo.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e,t){if(t)return!0;for(const t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);const t=this.vector;return e.shaderLanguage===ht.WGSL?e.compilationString+=`vertexOutputs.position = ${t.associatedVariableName};\n`:e.compilationString+=`gl_Position = ${t.associatedVariableName};\n`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes,e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant",xo.Float),e._emitVaryingFromString("vFragmentDepth",xo.Float),e.compilationString+="vFragmentDepth = 1.0 + gl_Position.w;\n",e.compilationString+="gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\n"),this}}function Lo(e,t=bo.Boolean,i="PROPERTIES",s){return(r,n)=>{let o=r._propStore;o||(o=[],r._propStore=o),o.push({propertyName:n,displayName:e,type:t,groupName:i,options:s??{}})}}u("BABYLON.VertexOutputBlock",Fo),function(e){e[e.Boolean=0]="Boolean",e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=3]="Vector2",e[e.List=4]="List"}(bo||(bo={}));class Bo extends No{constructor(e){super(e,To.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",xo.Color4,!0),this.registerInput("rgb",xo.AutoDetect,!0),this.registerInput("a",xo.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){(this.useLogarithmicDepth||t.useLogarithmicDepth)&&i&&Jr(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,s=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||s.isConnected,e.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant",xo.Float),e._emitVaryingFromString("vFragmentDepth",xo.Float),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r);let n="gl_FragColor";e.shaderLanguage===ht.WGSL&&(n="fragmentOutputs.color");const o=e._getShaderType(xo.Vector4);if(t.connectedPoint)s.isConnected?e.compilationString+=`${n} = ${o}(${t.associatedVariableName}.rgb, ${s.associatedVariableName});\n`:e.compilationString+=`${n} = ${t.associatedVariableName};\n`;else if(i.connectedPoint){let t="1.0";s.connectedPoint&&(t=s.associatedVariableName),i.connectedPoint.type===xo.Float?e.compilationString+=`${n} = ${o}(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t});\n`:e.compilationString+=`${n} = ${o}(${i.associatedVariableName}, ${t});\n`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${n} = toLinearSpace(${n});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${n} = toGammaSpace(${n});\n`,e.compilationString+="#endif\n",(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e.compilationString+="gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\n"),e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+="gl_FragData[0] = gl_FragColor;\r\n",e.compilationString+="#endif\r\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\n`,e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.useLogarithmicDepth=e.useLogarithmicDepth??!1}}ae([Lo("Convert to gamma space",bo.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Bo.prototype,"convertToGammaSpace",void 0),ae([Lo("Convert to linear space",bo.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Bo.prototype,"convertToLinearSpace",void 0),ae([Lo("Use logarithmic depth",bo.Boolean,"PROPERTIES")],Bo.prototype,"useLogarithmicDepth",void 0),u("BABYLON.FragmentOutputBlock",Bo),function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(Co||(Co={})),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime",e[e.CameraParameters=10]="CameraParameters",e[e.MaterialAlpha=11]="MaterialAlpha"}(yo||(yo={})),function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime",e[e.MouseInfo=3]="MouseInfo"}(Ao||(Ao={}));const Vo={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},Uo={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},ko={particle_texturemask:!0};class Go extends No{get type(){if(this._type===xo.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=xo.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=xo.Vector2,this._type;case"Vector3":return this._type=xo.Vector3,this._type;case"Vector4":return this._type=xo.Vector4,this._type;case"Color3":return this._type=xo.Color3,this._type;case"Color4":return this._type=xo.Color4,this._type;case"Matrix":return this._type=xo.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=xo.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=xo.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=xo.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=xo.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case yo.World:case yo.WorldView:case yo.WorldViewProjection:case yo.View:case yo.ViewProjection:case yo.Projection:return this._type=xo.Matrix,this._type;case yo.CameraPosition:return this._type=xo.Vector3,this._type;case yo.FogColor:return this._type=xo.Color3,this._type;case yo.DeltaTime:case yo.MaterialAlpha:return this._type=xo.Float,this._type;case yo.CameraParameters:return this._type=xo.Vector4,this._type}}return this._type}constructor(e,t=To.Vertex,i=xo.AutoDetect){super(e,t,!1),this._mode=Co.Undefined,this._animationType=Ao.None,this._prefix="",this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new g,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=Co.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===xo.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=Co.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=Co.Uniform}get declarationVariableName(){return this._associatedVariableName}get associatedVariableName(){return this._prefix+this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===Co.Undefined}get isUniform(){return this._mode===Co.Uniform}set isUniform(e){this._mode=e?Co.Uniform:Co.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===Co.Attribute}set isAttribute(e){this._mode=e?Co.Attribute:Co.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===Co.Varying}set isVarying(e){this._mode=e?Co.Varying:Co.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=Co.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case Ao.Time:this.type===xo.Float&&(this.value+=.01*e.getAnimationRatio());break;case Ao.RealTime:this.type===xo.Float&&(this.value=(je.Now-e.getEngine().startTime)/1e3);break;case Ao.MouseInfo:if(this.type===xo.Vector4){const t=e._inputManager._originMouseEvent;if(t){const e=t.offsetX,i=t.offsetY,s=1&t.buttons?1:0,r=2&t.buttons?1:0;this.value=new F(e,i,s,r)}else this.value=new F(0,0,0,0)}}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)}\n`:`#ifdef ${e}\n`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case xo.Float:this.value=0;break;case xo.Vector2:this.value=N.Zero();break;case xo.Vector3:this.value=w.Zero();break;case xo.Vector4:this.value=F.Zero();break;case xo.Color3:this.value=Y.White();break;case xo.Color4:this.value=new j(1,1,1,1);break;case xo.Matrix:this.value=B.Identity()}}_emitConstant(e){switch(this.type){case xo.Float:return`${e._emitFloat(this.value)}`;case xo.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case xo.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case xo.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case xo.Color3:return $.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&$.Color3[0].toGammaSpaceToRef($.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&$.Color3[0].toLinearSpaceToRef($.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${$.Color3[0].r}, ${$.Color3[0].g}, ${$.Color3[0].b})`;case xo.Color4:return $.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&$.Color4[0].toGammaSpaceToRef($.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&$.Color4[0].toLinearSpaceToRef($.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${$.Color4[0].r}, ${$.Color4[0].g}, ${$.Color4[0].b}, ${$.Color4[0].a})`}return""}get _noContextSwitch(){return Uo[this.name]}_emit(e,t){if(this.isUniform){if(this._associatedVariableName||(this._associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;return e.constants.push(this.associatedVariableName),void(e._constantDeclaration+=e._declareOutput(this.output,!0)+` = ${this._emitConstant(e)};\n`)}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t));const i=e._getShaderType(this.type);e.shaderLanguage===ht.WGSL?(e._uniformDeclaration+=`uniform ${this._associatedVariableName}: ${i};\n`,this._prefix="uniforms."):e._uniformDeclaration+=`uniform ${i} ${this.associatedVariableName};\n`,t&&(e._uniformDeclaration+="#endif\n");const s=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case yo.WorldView:s.needWorldViewMatrix=!0;break;case yo.WorldViewProjection:s.needWorldViewProjectionMatrix=!0}else this._animationType!==Ao.None&&e.sharedData.animatedInputs.push(this)}else if(this.isAttribute){if(this.associatedVariableName=Vo[this.name]??this.name,this.target===To.Vertex&&e._vertexState)return void(Uo[this.name]?ko[this.name]?(e._emitUniformFromString(this.associatedVariableName,this.type,t),e.shaderLanguage===ht.WGSL&&(this._prefix="vertexInputs.")):e._emitVaryingFromString(this.associatedVariableName,this.type,t):this._emit(e._vertexState,t));if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),Uo[this.name]?ko[this.name]?e._emitUniformFromString(this.associatedVariableName,this.type,t):e._emitVaryingFromString(this.associatedVariableName,this.type,t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e.shaderLanguage===ht.WGSL?(e._attributeDeclaration+=`attribute ${this.associatedVariableName}: ${e._getShaderType(this.type)};\n`,this._prefix="vertexInputs."):e._attributeDeclaration+=`attribute ${e._getShaderType(this.type)} ${this.associatedVariableName};\n`,t&&(e._attributeDeclaration+="#endif\n"))}}_transmitWorld(e,t,i,s){if(!this._systemValue)return;const r=this._associatedVariableName;switch(this._systemValue){case yo.World:e.setMatrix(r,t);break;case yo.WorldView:e.setMatrix(r,i);break;case yo.WorldViewProjection:e.setMatrix(r,s)}}_transmit(e,t,i){if(this.isAttribute)return;const s=this._associatedVariableName;if(this._systemValue){switch(this._systemValue){case yo.World:case yo.WorldView:case yo.WorldViewProjection:return;case yo.View:e.setMatrix(s,t.getViewMatrix());break;case yo.Projection:e.setMatrix(s,t.getProjectionMatrix());break;case yo.ViewProjection:e.setMatrix(s,t.getTransformMatrix());break;case yo.CameraPosition:t.bindEyePosition(e,s,!0);break;case yo.FogColor:e.setColor3(s,t.fogColor);break;case yo.DeltaTime:e.setFloat(s,t.deltaTime/1e3);break;case yo.CameraParameters:t.activeCamera&&e.setFloat4(s,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case yo.MaterialAlpha:e.setFloat(s,i.alpha)}return}const r=this._valueCallback?this._valueCallback():this._storedValue;if(null!==r)switch(this.type){case xo.Float:e.setFloat(s,r);break;case xo.Int:e.setInt(s,r);break;case xo.Color3:$.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&$.Color3[0].toGammaSpaceToRef($.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&$.Color3[0].toLinearSpaceToRef($.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(s,$.Color3[0]);break;case xo.Color4:$.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&$.Color4[0].toGammaSpaceToRef($.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&$.Color4[0].toLinearSpaceToRef($.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(s,$.Color4[0]);break;case xo.Vector2:e.setVector2(s,r);break;case xo.Vector3:e.setVector3(s,r);break;case xo.Vector4:e.setVector4(s,r);break;case xo.Matrix:e.setMatrix(s,r)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}");\n`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${yo[this._systemValue]});\n`;if(this.isUniform){const t=[];let i="";switch(this.type){case xo.Float:i=`${this.value}`;break;case xo.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case xo.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case xo.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case xo.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case xo.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case xo.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===xo.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${Ao[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){const e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,null!=this._storedValue&&this._mode===Co.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,"tangent"===e.name&&e.mode===Co.Attribute&&e.type===xo.Vector3&&(this._type=xo.Vector4),e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=d(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}u("BABYLON.InputBlock",Go);class zo extends No{constructor(e){super(e,To.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",xo.AutoDetect,!1,To.VertexAndFragment),this.registerOutput("rgba",xo.Color4,To.Neutral),this.registerOutput("rgb",xo.Color3,To.Neutral),this.registerOutput("r",xo.Float,To.Neutral),this.registerOutput("g",xo.Float,To.Neutral),this.registerOutput("b",xo.Float,To.Neutral),this.registerOutput("a",xo.Float,To.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Vector2|xo.Vector3|xo.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?To.VertexAndFragment:To.Fragment:To.VertexAndFragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,xo.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,xo.Vector2),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===To.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\n`}else this.uv.ownerBlock.target!==To.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\n`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===To.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target!==To.Fragment?(e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"):e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.blockingBlocks.indexOf(this)<0&&e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.indexOf(this)<0&&e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.indexOf(this)<0&&e.sharedData.blocksWithDefines.push(this),e.target!==To.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Zn.Parse(e.texture,t,i))}}u("BABYLON.CurrentScreenBlock",zo);class Wo extends No{constructor(e){super(e,To.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",xo.AutoDetect,!1,To.VertexAndFragment),this.registerOutput("rgba",xo.Color4,To.Neutral),this.registerOutput("rgb",xo.Color3,To.Neutral),this.registerOutput("r",xo.Float,To.Neutral),this.registerOutput("g",xo.Float,To.Neutral),this.registerOutput("b",xo.Float,To.Neutral),this.registerOutput("a",xo.Float,To.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Vector2|xo.Vector3|xo.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"particle_uv"===e.name&&t(e)));i||(i=new Go("uv"),i.setAsAttribute("particle_uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_writeOutput(e,t,i){e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"}_buildBlock(e){if(super._buildBlock(e),e.target===To.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName});\n`;for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Zn.Parse(e.texture,t,i))}}u("BABYLON.ParticleTextureBlock",Wo);class Ho extends No{constructor(e){super(e,To.Fragment),this._isUnique=!0,this.registerInput("color",xo.Color4,!1,To.Fragment),this.registerOutput("rampColor",xo.Color4,To.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==To.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges",xo.Vector4,"RAMPGRADIENT"),e.compilationString+=`\n #ifdef RAMPGRADIENT\n vec4 baseColor = ${this.color.associatedVariableName};\n float alpha = ${this.color.associatedVariableName}.a;\n\n float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\n\n vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));\n baseColor.rgb *= rampColor.rgb;\n\n // Remapped alpha\n float finalAlpha = baseColor.a;\n baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);\n\n ${e._declareOutput(this.rampColor)} = baseColor;\n #else\n ${e._declareOutput(this.rampColor)} = ${this.color.associatedVariableName};\n #endif\n `,this}}u("BABYLON.ParticleRampGradientBlock",Ho);class Xo extends No{constructor(e){super(e,To.Fragment),this._isUnique=!0,this.registerInput("color",xo.Color4,!1,To.Fragment),this.registerInput("alphaTexture",xo.Float,!1,To.Fragment),this.registerInput("alphaColor",xo.Float,!1,To.Fragment),this.registerOutput("blendColor",xo.Color4,To.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==To.Vertex)return e.compilationString+=`\n #ifdef BLENDMULTIPLYMODE\n ${e._declareOutput(this.blendColor)};\n float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};\n ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);\n ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a;\n #else\n ${e._declareOutput(this.blendColor)} = ${this.color.associatedVariableName};\n #endif\n `,this}}u("BABYLON.ParticleBlendMultiplyBlock",Xo);class Yo{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let e=0;e0&&(s.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;i0}get is3D(){return this.depth>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){return this._textures?.[0]??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}constructor(e,t,i,s,r){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=s,this._depthStencilTexture=null,this.label=r}setTextures(e){Array.isArray(e)?this._textures=e:this._textures=e?[e]:null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){return this._depthStencilTexture?.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:s,depthTextureFormat:r,label:n},this),this._depthStencilTexture}_shareDepth(e){this.shareDepth(e)}shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){let e=null;if(this._isMulti){const t=this.textures;if(t&&t.length>0){let i=!1,s=t.length,r=-1;const n=t[t.length-1]._source;n!==ei.Depth&&n!==ei.DepthStencil||(i=!0,r=t[t.length-1].format,s--);const o=[],a=[],l=[],h=[],c=[],u=[],d=[],p={};for(let e=0;e1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e1){const r=this._context,n=r["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??this.layerIndices?.[t]??0,r.framebufferTextureLayer(r.FRAMEBUFFER,n,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=i??this.faceIndices?.[t]??0,r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const r=this._context,n=r["COLOR_ATTACHMENT"+t+"_WEBGL"],o=void 0!==i?r.TEXTURE_CUBE_MAP_POSITIVE_X+i:r.TEXTURE_2D;r.framebufferTexture2D(r.FRAMEBUFFER,n,o,e._hardwareTexture.underlyingResource,s)}n._bindUnboundFramebuffer(o)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=this._attachments?.length??this.textures.length;for(let e=0;e1&&(15===o.format?u=i.DEPTH_COMPONENT16:16===o.format?u=i.DEPTH_COMPONENT24:17===o.format||13===o.format?u=i.DEPTH24_STENCIL8:14===o.format?u=i.DEPTH_COMPONENT32F:18===o.format&&(u=i.DEPTH32F_STENCIL8)),o.is2DArray?i.texImage3D(n,0,u,o.width,o.height,s,0,c,h,null):o.is3D?i.texImage3D(n,0,u,o.width,o.height,r,0,c,h,null):i.texImage2D(n,0,u,o.width,o.height,0,c,h,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(o),o},Yi.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);const s=e.texture._hardwareTexture;if(s.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){const r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBABufferInternalSizedFormat(e.texture.type,e.texture.format,e.texture._useSRGBBuffer),i.COLOR_ATTACHMENT0,!1);if(!n)throw new Error("Unable to create multi sampled framebuffer");s.addMSAARenderBuffer(n)}else this._bindUnboundFramebuffer(e._framebuffer);return e.texture.samples=t,e._samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t),this._bindUnboundFramebuffer(null),t},Yi.prototype._setupDepthStencilTexture=function(e,t,i,s,r,n=1){const o=t.width||t,a=t.height||t,l=t.layers||0,h=t.depth||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.depth=l||h,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=0,e._comparisonFunction=r;const c=this._gl,u=this._getTextureTarget(e),d=this._getSamplingParameters(e.samplingMode,!1);c.texParameteri(u,c.TEXTURE_MAG_FILTER,d.mag),c.texParameteri(u,c.TEXTURE_MIN_FILTER,d.min),c.texParameteri(u,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(u,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===r?(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,515),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,r),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))},si.prototype.setTextureFromPostProcess=function(e,t,i){let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,s?.texture??null,i)},si.prototype.setTextureFromPostProcessOutput=function(e,t,i){this._bindTexture(e,t?._outputTexture?.texture??null,i)},$t.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)},$t.prototype.setTextureFromPostProcessOutput=function(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)};class Ko{static RegisterShaderCodeProcessing(e,t){t?Ko._CustomShaderCodeProcessing[e??""]=t:delete Ko._CustomShaderCodeProcessing[e??""]}static _GetShaderCodeProcessing(e){return Ko._CustomShaderCodeProcessing[e]??Ko._CustomShaderCodeProcessing[""]}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach((e=>{e.setSamples(this._samples)}))}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,s,r,n,o=1,a,l,h=null,c=0,u="postprocess",d,p=!1,f=5,_=ht.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new Mi(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new N(1,1),this._texelSize=N.Zero(),this.onActivateObservable=new g,this.onSizeChangedObservable=new g,this.onApplyObservable=new g,this.onBeforeRenderObservable=new g,this.onAfterRenderObservable=new g,this.name=e;let m=1,v=null;if(i&&!Array.isArray(i)){const e=i;i=e.uniforms??null,s=e.samplers??null,m=e.size??1,n=e.camera??null,o=e.samplingMode??1,a=e.engine,l=e.reusable,h=e.defines??null,c=e.textureType??0,u=e.vertexUrl??"postprocess",d=e.indexParameters,p=e.blockCompilation??!1,f=e.textureFormat??5,_=e.shaderLanguage??ht.GLSL,v=e.uniformBuffers??null}else r&&(m="number"==typeof r?r:{width:r.width,height:r.height});null!=n?(this._camera=n,this._scene=n.getScene(),n.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):a&&(this._engine=a,this._engine.postProcesses.push(this)),this._options=m,this.renderTargetSamplingMode=o||1,this._reusable=l||!1,this._textureType=c,this._textureFormat=f,this._shaderLanguage=_,this._samplers=s||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=u,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=v||[],this._indexParameters=d,this._drawWrapper=new gr(this._engine),p||this.updateEffect(h)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){0==this._textures.length&&(this._textures=new Mi(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,r,n,o,a){const l=Ko._GetShaderCodeProcessing(this.name);if(l?.defineCustomBindings){const s=t?.slice()??[];s.push(...this._parameters);const r=i?.slice()??[];r.push(...this._samplers),e=l.defineCustomBindings(this.name,e,s,r),t=s,i=r}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:o??this._vertexUrl,fragment:a??this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:r??null,onError:n??null,indexParameters:s||this._indexParameters,processCodeAfterIncludes:l?.processCodeAfterIncludes?(e,t)=>l.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:l?.processFinalCode?(e,t)=>l.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let s=0;s=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i)for(let e=0;e{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}return u||(u=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/l,a/h),this._engine.bindFramebuffer(u,0,o,a,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(u,0,void 0,void 0,this.forceFullscreenViewport)),this._engine._debugInsertMarker?.(`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:s.clearColor,s._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),u}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._drawWrapper.effect?.isReady()??!1}apply(){if(!this._drawWrapper.effect?.isReady())return null;let e;return this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),e=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e?.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),Ko._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name,this._drawWrapper.effect),this._drawWrapper.effect}_disposeTextures(){this._shareOutputWithPostProcess||this._forcedOutputTexture?this._disposeTextureCache():(this._disposeTextureCache(),this._textures.dispose())}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return!!this._prePassEffectConfiguration&&(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0)}dispose(e){let t;if(e=e||this._camera,this._disposeTextures(),this._scene&&(t=this._scene.postProcesses.indexOf(this),-1!==t&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),-1!==t&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),0===t&&e._postProcesses.length>0){const e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){const e=Pe.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const e=this.serialize();e._engine=this._engine,e.cameraId=null;const t=Ko.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const s=d(e.customType);if(!s||!s._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return s._Parse(e,r,t,i)}static _Parse(e,t,i,s){return Pe.Parse((()=>new Ko(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat)),e,i,s)}}Ko._CustomShaderCodeProcessing={},ae([pe()],Ko.prototype,"uniqueId",void 0),ae([pe()],Ko.prototype,"name",void 0),ae([pe()],Ko.prototype,"width",void 0),ae([pe()],Ko.prototype,"height",void 0),ae([pe()],Ko.prototype,"renderTargetSamplingMode",void 0),ae([Te()],Ko.prototype,"clearColor",void 0),ae([pe()],Ko.prototype,"autoClear",void 0),ae([pe()],Ko.prototype,"forceAutoClearInAlphaMode",void 0),ae([pe()],Ko.prototype,"alphaMode",void 0),ae([pe()],Ko.prototype,"alphaConstants",void 0),ae([pe()],Ko.prototype,"enablePixelPerfectMode",void 0),ae([pe()],Ko.prototype,"forceFullscreenViewport",void 0),ae([pe()],Ko.prototype,"scaleMode",void 0),ae([pe()],Ko.prototype,"alwaysForcePOT",void 0),ae([pe("samples")],Ko.prototype,"_samples",void 0),ae([pe()],Ko.prototype,"adaptScaleToCurrentViewport",void 0),u("BABYLON.PostProcess",Ko);class qo extends No{constructor(e){super(e,To.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",xo.Vector4,!0),this.registerInput("xyz ",xo.Vector3,!0),this.registerInput("xy ",xo.Vector2,!0),this.registerInput("zw ",xo.Vector2,!0),this.registerInput("x",xo.Float,!0),this.registerInput("y",xo.Float,!0),this.registerInput("z",xo.Float,!0),this.registerInput("w",xo.Float,!0),this.registerOutput("xyzw",xo.Vector4),this.registerOutput("xyz",xo.Vector3),this.registerOutput("xy",xo.Vector2),this.registerOutput("zw",xo.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.x,i=this.y,s=this.z,r=this.w,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],c=this._outputs[1],u=this._outputs[2],d=this._outputs[3],p=e._getShaderType(xo.Vector4),f=e._getShaderType(xo.Vector3),_=e._getShaderType(xo.Vector2);return l.isConnected?(h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${l.associatedVariableName}${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${l.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${l.associatedVariableName}${this._buildSwizzle(2)};\n`)):a.isConnected?(h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${p}(${a.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${a.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${a.associatedVariableName}${this._buildSwizzle(2)};\n`)):n.isConnected?(h.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(h)+` = ${p}(${n.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=e._declareOutput(h)+` = ${p}(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${f}(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${n.associatedVariableName}${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(d)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=e._declareOutput(d)+` = ${_}(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};\n`)):(h.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(h)+` = ${p}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=e._declareOutput(h)+` = ${p}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${f}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${_}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(d)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=e._declareOutput(d)+` = ${_}(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};\n`)),this}serialize(){const e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.xSwizzle=e.xSwizzle??"x",this.ySwizzle=e.ySwizzle??"y",this.zSwizzle=e.zSwizzle??"z",this.wSwizzle=e.wSwizzle??"w"}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}";\n`,e+=`${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";\n`,e+=`${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";\n`,e+=`${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";\n`,e}}u("BABYLON.VectorMergerBlock",qo);class Qo extends No{constructor(e){super(e,To.Neutral),this.sourceRange=new N(-1,1),this.targetRange=new N(0,1),this.registerInput("input",xo.AutoDetect),this.registerInput("sourceMin",xo.Float,!0),this.registerInput("sourceMax",xo.Float,!0),this.registerInput("targetMin",xo.Float,!0),this.registerInput("targetMax",xo.Float,!0),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),s=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),r=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),n=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=e._declareOutput(t)+` = ${r} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${r}) / (${s} - ${i});\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\n`;return e+=`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\n`,e}serialize(){const e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=N.FromArray(e.sourceRange),this.targetRange=N.FromArray(e.targetRange)}}ae([Lo("From",bo.Vector2)],Qo.prototype,"sourceRange",void 0),ae([Lo("To",bo.Vector2)],Qo.prototype,"targetRange",void 0),u("BABYLON.RemapBlock",Qo);class Zo extends No{constructor(e){super(e,To.Neutral),this.registerInput("left",xo.AutoDetect),this.registerInput("right",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this.output._typeConnectionSource=this.left,this._linkConnectionTypes(0,1,!0),this.left.acceptedConnectionPointTypes.push(xo.Float),this.right.acceptedConnectionPointTypes.push(xo.Float),this._connectionObservers=[this.left.onTypeChangedObservable.add((()=>this._updateInputOutputTypes())),this.right.onTypeChangedObservable.add((()=>this._updateInputOutputTypes()))]}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===xo.Int||this.left.type===xo.Float&&this.right.type!==xo.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(const[e,t]of[[this.left,this.right],[this.right,this.left]])e.acceptedConnectionPointTypes=[xo.Int,xo.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==xo.Int&&t.type!==xo.Float||e.acceptedConnectionPointTypes.push(xo.Vector2,xo.Vector3,xo.Vector4,xo.Color3,xo.Color4,xo.Matrix))}dispose(){super.dispose(),this._connectionObservers.forEach((e=>e.remove())),this._connectionObservers.length=0}}class Jo extends Zo{constructor(e){super(e)}getClassName(){return"MultiplyBlock"}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};\n`,this}}var ea;u("BABYLON.MultiplyBlock",Jo),function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture"}(ea||(ea={}));class ta extends Do{constructor(){super(),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class ia{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:w.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:w.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:w.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:w.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let s=0;for(const i of t){if(i.gradient===e){t.splice(s,1);break}s++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=w.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this.applyFog=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new w(10,10,10),this.onAnimationEnd=null,this.blendMode=ia.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new N(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new w(0,0,0),this._useLogarithmicDepth=!1,this.gravity=w.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new j(1,1,1,1),this.color2=new j(1,1,1,1),this.colorDead=new j(0,0,0,1),this.textureMask=new j(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new ta,this.id=e,this.name=e}createPointEmitter(e,t){throw new Error("Method not implemented.")}createHemisphericEmitter(e=1,t=1){throw new Error("Method not implemented.")}createSphereEmitter(e=1,t=1){throw new Error("Method not implemented.")}createDirectedSphereEmitter(e=1,t=new w(0,1,0),i=new w(0,1,0)){throw new Error("Method not implemented.")}createCylinderEmitter(e=1,t=1,i=1,s=0){throw new Error("Method not implemented.")}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new w(0,1,0),r=new w(0,1,0)){throw new Error("Method not implemented.")}createConeEmitter(e=1,t=Math.PI/4){throw new Error("Method not implemented.")}createBoxEmitter(e,t,i,s){throw new Error("Method not implemented.")}}ia.BLENDMODE_ONEONE=0,ia.BLENDMODE_STANDARD=1,ia.BLENDMODE_ADD=2,ia.BLENDMODE_MULTIPLY=3,ia.BLENDMODE_MULTIPLYADD=4,u("BABYLON.BaseParticleSystem",ia);class sa extends No{constructor(e){super(e,To.Neutral),this.registerInput("rgba",xo.Color4,!0),this.registerInput("rgb ",xo.Color3,!0),this.registerOutput("rgb",xo.Color3),this.registerOutput("r",xo.Float),this.registerOutput("g",xo.Float),this.registerOutput("b",xo.Float),this.registerOutput("a",xo.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);const t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;const i=this._outputs[0],s=this._outputs[1],r=this._outputs[2],n=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${t.associatedVariableName}.rgb;\n`),s.hasEndpoints&&(e.compilationString+=e._declareOutput(s)+` = ${t.associatedVariableName}.r;\n`),r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = ${t.associatedVariableName}.g;\n`),n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = ${t.associatedVariableName}.b;\n`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = ${t.associatedVariableName}.a;\n`),this}}u("BABYLON.ColorSplitterBlock",sa),Yi.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,(1!==s.type||this._caps.textureFloatLinearFiltering)&&(2!==s.type||this._caps.textureHalfFloatLinearFiltering)||(s.samplingMode=1);const r=this._gl,n=new ti(this,ei.RenderTarget);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,n,!0);const o=this._getSamplingParameters(s.samplingMode,s.generateMipMaps);1!==s.type||this._caps.textureFloat||(s.type=0,J.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,o.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,o.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let t=0;t<6;t++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(s.type,s.format),e,e,0,this._getInternalFormat(s.format),this._getWebGLTextureType(s.type),null);const a=r.createFramebuffer();return this._bindUnboundFramebuffer(a),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(s.generateStencilBuffer,s.generateDepthBuffer,e,e),s.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=a,i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=s.generateMipMaps,n.samplingMode=s.samplingMode,n.type=s.type,n.format=s.format,this._internalTexturesCache.push(n),i.setTextures(n),i},Yi.prototype.setDepthStencilTexture=function(e,t,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,s):this._setTexture(e,null,void 0,void 0,s))};const ra={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class na{constructor(e,t=ra){this._fullscreenViewport=new nr(0,0,1,1);const i=t.positions??ra.positions,s=t.indices??ra.indices;this.engine=e,this._vertexBuffers={[Ki.PositionKind]:new Ki(e,i,Ki.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(s),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(s);for(const e in this._vertexBuffers)this._vertexBuffers[e]._rebuild()}))}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=null===t?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){const e=this._vertexBuffers[Ki.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[Ki.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class oa{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new g;const i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add((()=>{this.effect.setFloat2("scale",1,1)})));const s=e.defines?e.defines.join("\n"):"";this._drawWrapper=new gr(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],i,e.samplerNames,s,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new $t(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,s,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add((()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const aa="passPixelShader",la="varying vec2 vUV;uniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);}";Ft.ShadersStore[aa]=la;const ha=aa,ca=la;class ua{static _CreateDumpRenderer(){if(!ua._DumpToolsEngine){let e,t=null;const i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new Yi(e,!1,i)}catch(s){e=document.createElement("canvas"),t=new Yi(e,!1,i)}y.Instances.pop(),y.OnEnginesDisposedObservable.add((e=>{t&&e!==t&&!t.isDisposed&&0===y.Instances.length&&ua.Dispose()})),t.getCaps().parallelShaderCompile=void 0;const s=new na(t),r=new oa({engine:t,name:ha,fragmentShader:ca,samplerNames:["textureSampler"]});ua._DumpToolsEngine={canvas:e,engine:t,renderer:s,wrapper:r}}return ua._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,r="image/png",n,o){const a=await i.readPixels(0,0,e,t),l=new Uint8Array(a.buffer);ua.DumpData(e,t,l,s,r,n,!0,void 0,o)}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,o=!1,a){return new Promise((l=>{ua.DumpData(e,t,i,(e=>l(e)),s,r,n,o,a)}))}static DumpData(e,t,i,s,r="image/png",n,o=!1,a=!1,l){const h=ua._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){const e=new Uint8Array(i.length);let t=i.length;for(;t--;){const s=i[t];e[t]=Math.round(255*G.Clamp(s))}i=e}const c=h.engine.createRawTexture(i,e,t,5,!1,!o,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",c),h.renderer.draw(),a?Ii.ToBlob(h.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;s&&s(t)},t.readAsArrayBuffer(e)}),r,l):Ii.EncodeScreenshotCanvasData(h.canvas,s,r,n,l),c.dispose()}static Dispose(){ua._DumpToolsEngine&&(ua._DumpToolsEngine.wrapper.dispose(),ua._DumpToolsEngine.renderer.dispose(),ua._DumpToolsEngine.engine.dispose()),ua._DumpToolsEngine=null}}Ii.DumpData=ua.DumpData,Ii.DumpDataAsync=ua.DumpDataAsync,Ii.DumpFramebuffer=ua.DumpFramebuffer,$t.prototype.setDepthStencilTexture=function(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)};class da extends Zn{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=b(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;i=Array.isArray(e)?e:[e];for(let e=0;e{const i=this._renderList?this._renderList.length:0;(0===t&&i>0||0===i)&&this.getScene()?.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new g,this.onAfterUnbindObservable=new g,this.onBeforeRenderObservable=new g,this.onAfterRenderObservable=new g,this.onClearObservable=new g,this.onResizeObservable=new g,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=w.Zero(),!(i=this.getScene()))return;const T=this.getScene().getEngine();this._gammaSpace=x,this._coordinatesMode=Zn.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=o,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=T.onResizeObservable.add((()=>{})),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=r,this._renderingManager=new es(i),this._renderingManager._useSceneAutoClearSetup=!0,c||(this._renderTargetOptions={generateMipMaps:s,type:n,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:h,samples:p,creationFlags:f,noColorAttachment:_,useSRGBBuffer:m,colorAttachment:v,label:this.name},this.samplingMode===Zn.NEAREST_SAMPLINGMODE&&(this.wrapU=Zn.CLAMP_ADDRESSMODE,this.wrapV=Zn.CLAMP_ADDRESSMODE),d||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=Zn.INVCUBIC_MODE,this._textureMatrix=B.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==p&&(this.samples=p)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){this._renderTarget?.createDepthStencilTexture(e,t,i,s,r,n)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;if(e)return e;return this._size.depth||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){const t=this.isCube;this._renderTarget?.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e,!1),this._renderTarget=t?i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==this._renderTargetOptions.samples&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){const s=this.getScene();if(!s)return i;const r=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let e=0;e{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):s&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0,r=null){const n=this.getScene();if(!n)return;const o=n.getEngine();if(o._debugPushGroup?.(`render to face #${e} layer #${s}`,1),this._prepareFrame(n,e,s,t),this.is2DArray||this.is3D?(o.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(o.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),o.snapshotRendering&&1===o.snapshotRenderingMode)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||n.clearColor,!0,!0,!0);else{let a=null;const l=this.renderList?this.renderList:n.getActiveMeshes().data,h=this.renderList?this.renderList.length:n.getActiveMeshes().length;this.getCustomRenderList&&(a=this.getCustomRenderList(this.is2DArray||this.is3D?s:e,l,h)),a?this._prepareRenderingManager(a,a.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(l,h,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),a=l);for(const t of n._beforeRenderTargetClearStage)t.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||n.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0);for(const t of n._beforeRenderTargetDrawStage)t.action(this,e,s);this._renderingManager.render(this.customRenderFunction,a,this.renderParticles,this.renderSprites);for(const t of n._afterRenderTargetDrawStage)t.action(this,e,s);const c=this._texture?.generateMipMaps??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&n.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e);for(const t of n._afterRenderTargetPostProcessStage)t.action(this,e,s);this._texture&&(this._texture.generateMipMaps=c),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0),i&&ua.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),o)}this._unbindFrameBuffer(o,e),this._texture&&this.isCube&&5===e&&o.generateMipMapsForCubemap(this._texture,!0),o._debugPopGroup?.(1)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new da(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&e.customRenderTargets.splice(t,1);for(const i of e.cameras)t=i.customRenderTargets.indexOf(this),t>=0&&i.customRenderTargets.splice(t,1);this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===da.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=da.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}da.REFRESHRATE_RENDER_ONCE=0,da.REFRESHRATE_RENDER_ONEVERYFRAME=1,da.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,Zn._CreateRenderTargetTexture=(e,t,i,s,r)=>new da(e,t,i,s);class pa{constructor(e){this.name=ts.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(ts.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){Ii.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}Ft.ShadersStore.proceduralVertexShader="attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class fa extends Zn{constructor(e,t,i,s,r=null,n=!0,o=!1,a=0){super(null,s,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new g,this.onBeforeGenerationObservable=new g,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._vectors4={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null,null===r||r instanceof Zn?(this._options={},this._fallbackTexture=r):(this._options=r,this._fallbackTexture=r.fallbackTexture??null);let l=(s=this.getScene()||y.LastCreatedScene)._getComponent(ts.NAME_PROCEDURALTEXTURE);l||(l=new pa(s),s._addComponent(l)),s.proceduralTextures.push(this),this._fullEngine=s.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=a,this._generateMipMaps=n,this._drawWrapper=new gr(this._fullEngine),this.setFragment(i);const h=this._createRtWrapper(o,t,n,a);this._texture=h.texture;const c=[];c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1),this._vertexBuffers[Ki.PositionKind]=new Ki(this._fullEngine,c,Ki.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,s){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.then((e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId})):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId)),this._contentData}_createIndexBuffer(){const e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[Ki.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===da.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=da.REFRESHRATE_RENDER_ONCE)}reset(){this._drawWrapper.effect?.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}executeWhenReady(e){if(this.isReady())return void e(this);const t=this.getEffect();t&&t.executeWhenCompiled((()=>{e(this)}))}isReady(){const e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;const t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;const i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:"string"==typeof this._fragment?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[Ki.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,(()=>{this._rtWrapper?.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0}))),this._drawWrapper.effect.isReady()}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;const i=this._texture.isCube;this._rtWrapper.dispose();const s=this._createRtWrapper(i,e,t,this._textureType);this._texture=s.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){const t=this.getScene();if(!t)return;const i=this._fullEngine;if(i.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),i.setState(!1),!this.nodeMaterialSource){for(const e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(const e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(const e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(const e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(const e in this._colors4){const t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(const e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)this._drawWrapper.effect.setVector4(e,this._vectors4[e]);for(const e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;i._debugPushGroup?.(`procedural texture generation for ${this.name}`,1);const s=i.currentViewport;if(this.isCube)for(let e=0;e<6;e++)i.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(Dn.TriangleFillMode,0,6);else{let e=1;this._rtWrapper.is3D?e=this._rtWrapper.depth:this._rtWrapper.is2DArray&&(e=this._rtWrapper.layers);for(let s=0;s=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[Ki.PositionKind];i&&(i.dispose(),this._vertexBuffers[Ki.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}var _a;ae([pe()],fa.prototype,"isEnabled",void 0),ae([pe()],fa.prototype,"autoClear",void 0),ae([pe()],fa.prototype,"_generateMipMaps",void 0),ae([pe()],fa.prototype,"_size",void 0),ae([pe()],fa.prototype,"refreshRate",null),u("BABYLON.ProceduralTexture",fa),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees",e[e.Set=18]="Set"}(_a||(_a={}));class ma extends No{constructor(e){super(e,To.Neutral),this.operation=_a.Cos,this.registerInput("input",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="";switch(this.operation){case _a.Cos:i="cos";break;case _a.Sin:i="sin";break;case _a.Abs:i="abs";break;case _a.Exp:i="exp";break;case _a.Exp2:i="exp2";break;case _a.Round:i="round";break;case _a.Floor:i="floor";break;case _a.Ceiling:i="ceil";break;case _a.Sqrt:i="sqrt";break;case _a.Log:i="log";break;case _a.Tan:i="tan";break;case _a.ArcTan:i="atan";break;case _a.ArcCos:i="acos";break;case _a.ArcSin:i="asin";break;case _a.Fract:i="fract";break;case _a.Sign:i="sign";break;case _a.Radians:i="radians";break;case _a.Degrees:i="degrees";break;case _a.Set:i=""}return e.compilationString+=e._declareOutput(t)+` = ${i}(${this.input.associatedVariableName});\n`,this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${_a[this.operation]};\n`}}u("BABYLON.TrigonometryBlock",ma);const ga={effect:null,subMesh:null};class va extends Do{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class xa extends Io{static _BlockIsTextureBlock(e){return"TextureBlock"===e.getClassName()||"ReflectionTextureBaseBlock"===e.getClassName()||"ReflectionTextureBlock"===e.getClassName()||"ReflectionBlock"===e.getClassName()||"RefractionBlock"===e.getClassName()||"CurrentScreenBlock"===e.getClassName()||"ParticleTextureBlock"===e.getClassName()||"ImageSourceBlock"===e.getClassName()||"TriPlanarBlock"===e.getClassName()||"BiPlanarBlock"===e.getClassName()||"PrePassTextureBlock"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get shaderLanguage(){return this._options.shaderLanguage}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){if(super(e,t||y.LastCreatedScene),this._buildId=xa._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new B,this._cachedWorldViewProjectionMatrix=new B,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new g,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=[],this._mode=ea.Material,this.forceAlphaBlending=!1,i&&i.shaderLanguage===ht.WGSL&&!this.getScene().getEngine().isWebGPU)throw new Error("WebGPU shader language is only supported with WebGPU engine");this._options={emitComments:!1,shaderLanguage:xa.DefaultShaderLanguage,...i},this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return Ii.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(const t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){const t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return e.target&To.Vertex&&this._addVertexOutputNode(e),e.target&To.Fragment&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||(e.target&To.Vertex&&this._removeVertexOutputNode(e),e.target&To.Fragment&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=To.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){const t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=To.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){const t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,s=!0){(e.target===To.VertexAndFragment||t.target===To.Fragment&&e.target===To.Vertex&&e._preparationId!==this._buildId)&&i.push(e),this._initializeBlock(e,t,i,s)}_initializeBlock(e,t,i,s=!0){if(e.initialize(t),s&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){const t=e.getClassName();for(const e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const r of e.inputs){r.associatedVariableName="";const n=r.connectedPoint;if(n){const r=n.ownerBlock;r!==e&&this._processInitializeOnLink(r,t,i,s)}}if(e.isTeleportOut){const r=e;r.entryPoint&&this._processInitializeOnLink(r.entryPoint,t,i,s)}for(const t of e.outputs)t.associatedVariableName=""}_resetDualBlocks(e,t){e.target===To.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._resetDualBlocks(i.entryPoint,t)}}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){this._vertexCompilationState||i||(i=!0),this._buildWasSuccessful=!1;const s=this.getScene().getEngine(),r=this._mode===ea.Particle;if(0===this._vertexOutputNodes.length&&!r)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new Po,this._vertexCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._vertexCompilationState.target=To.Vertex,this._fragmentCompilationState=new Po,this._fragmentCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._fragmentCompilationState.target=To.Fragment,this._sharedData=new Mo,this._sharedData.nodeMaterial=this,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=r;const n=[],o=[];for(const e of this._vertexOutputNodes)n.push(e),this._initializeBlock(e,this._vertexCompilationState,o,i);for(const e of this._fragmentOutputNodes)o.push(e),this._initializeBlock(e,this._fragmentCompilationState,n,i);this.optimize();for(const e of n)e.build(this._vertexCompilationState,n);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(const e of o)this._resetDualBlocks(e,this._buildId-1);for(const e of o)e.build(this._fragmentCompilationState,o);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=xa._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(J.Log("Vertex shader:"),J.Log(this._vertexCompilationState.compilationString),J.Log("Fragment shader:"),J.Log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const a=this.getScene().meshes;for(const e of a)if(e.subMeshes)for(const t of e.subMeshes){if(t.getMaterial()!==this)continue;if(!t.materialDefines)continue;const e=t.materialDefines;e.markAllAsDirty(),e.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();const l=this.getScene().prePassRenderer;l&&l.markAsDirty()}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,s=t.TANGENT,r=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(Ki.NormalKind),t.TANGENT=e.isVerticesDataPresent(Ki.TangentKind);const n=e.useVertexColors&&e.isVerticesDataPresent(Ki.ColorKind);t.VERTEXCOLOR_NME=n;let o=!1;for(let i=1;i<=6;++i){const s=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),o=o||t["UV"+i]!==s}const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;Rn(this.getScene(),t,!a),(i!==t.NORMAL||s!==t.TANGENT||r!==t.VERTEXCOLOR_NME||o)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){const e=this.getBlockByPredicate((e=>"PrePassOutputBlock"===e.getClassName())),t=[4];return e?(this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t):t}get prePassTextureInputs(){const e=this.getAllTextureBlocks().filter((e=>"PrePassTextureBlock"===e.getClassName())),t=[];for(const i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){const t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]}));for(const e of t)i.texturesRequired.includes(e)||i.texturesRequired.push(e);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,s,r,n=0,o=5){return this.mode!==ea.PostProcess?(J.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,s,r,n,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,s=1,r,n,o=0,a=5){let l=this.name+this._buildId;const h=new va,c=new Wr(l+"PostProcess",this.getScene());let u=this._buildId;return this._processDefines(c,h),$t.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new Ko(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,s,r,n,h.toString(),o,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,a),e.nodeMaterialSource=this,e.onApplyObservable.add((t=>{u!==this._buildId&&(delete $t.ShadersStore[l+"VertexShader"],delete $t.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),u=this._buildId),this._processDefines(c,h)&&($t.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),wt.SetImmediate((()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l)))),this._checkInternals(t)})),e}createProceduralTexture(e,t){if(this.mode!==ea.ProceduralTexture)return J.Log("Incompatible material mode"),null;let i=this.name+this._buildId;const s=new fa(i,e,null,t),r=new Wr(i+"Procedural",this.getScene());r.reservedDataStore={hidden:!0};const n=new va,o=this._processDefines(r,n);$t.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[Ki.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),o?.fallbacks,void 0);s.nodeMaterialSource=this,s._setEffect(a);let l=this._buildId;return s.onBeforeGenerationObservable.add((()=>{l!==this._buildId&&(delete $t.ShadersStore[i+"VertexShader"],delete $t.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),l=this._buildId);const e=this._processDefines(r,n);e&&($t.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),wt.SetImmediate((()=>{a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[Ki.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),e?.fallbacks,void 0),s._setEffect(a)}))),this._checkInternals(a)})),s}_createEffectForParticles(e,t,i,s,r,n,o,a=""){let l=this.name+this._buildId+"_"+t;n||(n=new va),o||(o=this.getScene().getMeshByName(this.name+"Particle"))||((o=new Wr(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId;const c=[];let u=a;if(!r){const a=this._processDefines(o,n);$t.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(c,t,!1),u=c.join("\n"),r=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,a?.fallbacks,i,s,e),e.setCustomEffect(r,t)}r.onBindObservable.add((r=>{h!==this._buildId&&(delete $t.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,n.markAllAsDirty(),h=this._buildId),c.length=0,e.fillDefines(c,t,!1);const d=c.join("\n");d!==u&&(n.markAllAsDirty(),u=d);const p=this._processDefines(o,n);if(p)return $t.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),r=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,p?.fallbacks,i,s,e),e.setCustomEffect(r,t),void this._createEffectForParticles(e,t,i,s,r,n,o,a);this._checkInternals(r)}))}_checkInternals(e){if(this._sharedData.animatedInputs){const e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(const t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(const t of this._sharedData.bindableBlocks)t.bind(e,this);for(const t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){this.mode===ea.Particle?(this._createEffectForParticles(e,ia.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,ia.BLENDMODE_MULTIPLY,t,i)):J.Log("Incompatible material mode")}createAsShadowDepthWrapper(e){this.mode===ea.Material?e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene()):J.Log("Incompatible material mode")}_processDefines(e,t,i=!1,s){let r=null;if(In(this.getScene(),t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach((s=>{s.initializeDefines(e,this,t,i)})),this._sharedData.blocksWithDefines.forEach((r=>{r.prepareDefines(e,this,t,i,s)})),t.isDirty){const i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach((i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)}));const s=[];this._sharedData.dynamicUniformBlocks.forEach((e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,s)}));const n=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach((e=>{-1===n.indexOf(e)&&n.push(e)}));const o=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach((e=>{-1===o.indexOf(e)&&o.push(e)}));const a=new Yo;this._sharedData.blocksWithFallbacks.forEach((t=>{t.provideFallbacks(e,a)})),r={lightDisposed:i,uniformBuffers:s,mergedUniforms:n,mergedSamplers:o,fallbacks:a}}return r}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const s=this.getScene();if(this._sharedData.animatedInputs){const e=s.getFrameId();if(this._animationFrame!==e){for(const e of this._sharedData.animatedInputs)e.animate(s);this._animationFrame=e}}const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new va);const n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=s.getEngine();if(this._prepareDefinesForAttributes(e,n),this._sharedData.blockingBlocks.some((t=>!t.isReady(e,this,n,i))))return!1;const a=this._processDefines(e,n,i,t);if(a){const e=t.effect,i=n.toString();let r=o.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:i,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:n.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS},shaderLanguage:this.shaderLanguage},o);if(r)if(this._onEffectCreatedObservable&&(ga.effect=r,ga.subMesh=t,this._onEffectCreatedObservable.notifyObservers(ga)),this.allowShaderHotSwapping&&e&&!r.isReady()){if(r=e,n.markAsUnprocessed(),a.lightDisposed)return n._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(r,n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}get compiledShaders(){return`// Vertex shader\n${this._vertexCompilationState.compilationString}\n\n// Fragment shader\n${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){const t=this.getScene();if(!this._activeEffect)return;const i=this._sharedData.hints;i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(const t of this._sharedData.inputBlocks)t._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.effect;if(!r)return;this._activeEffect=r,this.bindOnlyWorldMatrix(e);const n=this._mustRebind(s,r,i,t.visibility),o=this._sharedData;if(n){for(const e of o.bindableBlocks)e.bind(r,this,t,i);for(const e of o.forcedBindableBlocks)e.bind(r,this,t,i);for(const e of o.inputBlocks)e._transmit(r,s,this)}else if(!this.isFrozen)for(const e of o.forcedBindableBlocks)e.bind(r,this,t,i);this._afterBind(t,this._activeEffect,i)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter((e=>e.texture)).map((e=>e.texture))),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)xa._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(const t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(const e of this.getTextureBlocks().filter((e=>e.texture)).map((e=>e.texture)))e.dispose();for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){const t={nodeMaterial:this,...e};this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise((t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),void 0===this.BJSNODEMATERIALEDITOR){const i=e&&e.editorURL?e.editorURL:xa.EditorURL;Ii.LoadBabylonScript(i,(()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(e?.nodeEditorConfig),t()}))}else this._createNodeEditor(e?.nodeEditorConfig),t()}))}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;const e=new Go("Position");e.setAsAttribute("position");const t=new Go("World");t.setAsSystemValue(yo.World);const i=new wo("WorldPos");e.connectTo(i),t.connectTo(i);const s=new Go("ViewProjection");s.setAsSystemValue(yo.ViewProjection);const r=new wo("WorldPos * ViewProjectionTransform");i.connectTo(r),s.connectTo(r);const n=new Fo("VertexOutput");r.connectTo(n);const o=new Go("color");o.value=new j(.8,.8,.8,1);const a=new Bo("FragmentOutput");o.connectTo(a),this.addOutputNode(n),this.addOutputNode(a),this._mode=ea.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Go("Position");e.setAsAttribute("position2d");const t=new Go("Constant1");t.isConstant=!0,t.value=1;const i=new qo("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new Fo("VertexOutput");i.connectTo(s);const r=new Go("Scale");r.visibleInInspector=!0,r.value=new N(1,1);const n=new Qo("uv0");e.connectTo(n);const o=new Jo("UV scale");n.connectTo(o),r.connectTo(o);const a=new zo("CurrentScreen");o.connectTo(a),a.texture=new Zn("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const l=new Bo("FragmentOutput");a.connectTo(l,{output:"rgba"}),this.addOutputNode(s),this.addOutputNode(l),this._mode=ea.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Go("Position");e.setAsAttribute("position2d");const t=new Go("Constant1");t.isConstant=!0,t.value=1;const i=new qo("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new Fo("VertexOutput");i.connectTo(s);const r=new Go("Time");r.value=0,r.min=0,r.max=0,r.isBoolean=!1,r.matrixMode=0,r.animationType=Ao.Time,r.isConstant=!1;const n=new Go("Color3");n.value=new Y(1,1,1),n.isConstant=!1;const o=new Bo("FragmentOutput"),a=new qo("VectorMerger");a.visibleInInspector=!1;const l=new ma("Cos");l.operation=_a.Cos,e.connectTo(a),r.output.connectTo(l.input),l.output.connectTo(a.z),a.xyzOut.connectTo(o.rgb),this.addOutputNode(s),this.addOutputNode(o),this._mode=ea.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Go("uv");e.setAsAttribute("particle_uv");const t=new Wo("ParticleTexture");e.connectTo(t);const i=new Go("Color");i.setAsAttribute("particle_color");const s=new Jo("Texture * Color");t.connectTo(s),i.connectTo(s);const r=new Ho("ParticleRampGradient");s.connectTo(r);const n=new sa("ColorSplitter");i.connectTo(n);const o=new Xo("ParticleBlendMultiply");r.connectTo(o),t.connectTo(o,{output:"a"}),n.connectTo(o,{output:"a"});const a=new Bo("FragmentOutput");o.connectTo(a),this.addOutputNode(a),this._mode=ea.Particle}async loadAsync(e,t=""){return xa.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,t);const s=[];for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,s);let r=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}");\n`;r+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${ea[this.mode]};\n`;for(const s of t)s.isInput&&-1===e.indexOf(s)&&(r+=s._dumpCode(i,e));for(const t of s)t.isInput&&-1===e.indexOf(t)&&(r+=t._dumpCode(i,e));e=[],r+="\n// Connections\n";for(const t of this._vertexOutputNodes)r+=t._dumpCodeForOutputConnections(e);for(const t of this._fragmentOutputNodes)r+=t._dumpCodeForOutputConnections(e);r+="\n// Output nodes\n";for(const e of this._vertexOutputNodes)r+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;for(const e of this._fragmentOutputNodes)r+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;return r+="nodeMaterial.build();\n",r}serialize(e){const t=e?{}:Pe.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{t.customType="BABYLON.NodeMaterial",t.outputNodes=[];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n)for(const o of r.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==s.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;s.connectTo(e,!0),this._restoreConnections(n,t,i)}}}parseSerializedObject(e,t="",i=!1,s){i||this.clear();const r={};for(const i of e.blocks){const e=d(i.customType);if(e){const n=new e;n._deserialize(i,this.getScene(),t,s),r[i.id]=n,this.attachedBlocks.push(n)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,i=t._tempEntryPointUniqueId;i&&r[i].attachToEndpoint(t)}for(let t=0;tnew xa(e,this.getScene(),this.options)),this);return s.id=e,s.name=e,s.parseSerializedObject(i),s._buildId=this._buildId,s.build(!1,!t),s}whenTexturesReadyAsync(){const e=[];return this.getActiveTextures().forEach((t=>{const i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise(((e,t)=>{i.onLoadedObservable.addOnce((()=>{e()})),i.onErrorObservable.addOnce((e=>{t(e)}))})))})),Promise.all(e)}static Parse(e,t,i="",s=ht.GLSL){const r=Pe.Parse((()=>new xa(e.name,t,{shaderLanguage:s})),e,t,i);return r.parseSerializedObject(e,i),r.build(),r}static async ParseFromFileAsync(e,t,i,s="",r=!1,n,o){const a=n??new xa(e,i),l=await i._loadFileAsync(t),h=JSON.parse(l);return a.parseSerializedObject(h,s,void 0,o),r||a.build(),a}static ParseFromSnippetAsync(e,t=y.LastCreatedScene,i="",s,r=!1,n=!1,o){return"_BLANK"===e?Promise.resolve(xa.CreateDefault("blank",t)):new Promise(((a,l)=>{const h=new Ne;h.addEventListener("readystatechange",(()=>{if(4==h.readyState)if(200==h.status){const c=JSON.parse(JSON.parse(h.responseText).jsonPayload),u=JSON.parse(c.nodeMaterial);s||((s=Pe.Parse((()=>new xa(e,t)),u,t,i)).uniqueId=t.getUniqueId()),s.parseSerializedObject(u,void 0,void 0,o),s.snippetId=e;try{r||s.build()}catch(e){l(e)}n?s.whenTexturesReadyAsync().then((()=>{a(s)})).catch((e=>{l(e)})):a(s)}else l("Unable to load the snippet "+e)})),h.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),h.send()}))}static CreateDefault(e,t){const i=new xa(e,t);return i.setToDefault(),i.build(),i}}function Ta(e){const t=e.sideOrientation||Tr.DEFAULTSIDE,i=e.radius||1,s=void 0===e.flat||e.flat,r=0|(e.subdivisions||4),n=e.radiusX||i,o=e.radiusY||i,a=e.radiusZ||i,l=(1+Math.sqrt(5))/2,h=[-1,l,-0,1,l,0,-1,-l,0,1,-l,0,0,-1,-l,0,1,-l,0,-1,l,0,1,l,l,0,1,l,0,-1,-l,0,1,-l,0,-1],c=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],u=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],d=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],p=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],f=[],_=[],m=[],g=[];let v=0;const x=new Array(3),T=new Array(3);let S;for(S=0;S<3;S++)x[S]=w.Zero(),T[S]=N.Zero();for(let e=0;e<20;e++){for(S=0;S<3;S++){const t=c[3*e+S];x[S].copyFromFloats(h[3*u[t]],h[3*u[t]+1],h[3*u[t]+2]),x[S].normalize(),T[S].copyFromFloats(.134765625*d[2*t]+.05859375+-.0390625*p[e],.2333984375*d[2*t+1]+.025390625+.01953125*p[e])}const t=(e,t,i,l)=>{const h=w.Lerp(x[0],x[2],t/r),c=w.Lerp(x[1],x[2],t/r),u=r===t?x[2]:w.Lerp(h,c,e/(r-t));let d;if(u.normalize(),s){const e=w.Lerp(x[0],x[2],l/r),t=w.Lerp(x[1],x[2],l/r);d=w.Lerp(e,t,i/(r-l))}else d=new w(u.x,u.y,u.z);d.x/=n,d.y/=o,d.z/=a,d.normalize();const p=N.Lerp(T[0],T[2],t/r),S=N.Lerp(T[1],T[2],t/r),E=r===t?T[2]:N.Lerp(p,S,e/(r-t));_.push(u.x*n,u.y*o,u.z*a),m.push(d.x,d.y,d.z),g.push(E.x,Er.UseOpenGLOrientationForUV?1-E.y:E.y),f.push(v),v++};for(let e=0;eSa(e,t,i),function(e){e.WRIST="wrist",e.THUMB="thumb",e.INDEX="index",e.MIDDLE="middle",e.RING="ring",e.LITTLE="little"}(Ea||(Ea={})),(Ca=ba||(ba={})).WRIST="wrist",Ca.THUMB_METACARPAL="thumb-metacarpal",Ca.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",Ca.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",Ca.THUMB_TIP="thumb-tip",Ca.INDEX_FINGER_METACARPAL="index-finger-metacarpal",Ca.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",Ca.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",Ca.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",Ca.INDEX_FINGER_TIP="index-finger-tip",Ca.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",Ca.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",Ca.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",Ca.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",Ca.MIDDLE_FINGER_TIP="middle-finger-tip",Ca.RING_FINGER_METACARPAL="ring-finger-metacarpal",Ca.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",Ca.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",Ca.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",Ca.RING_FINGER_TIP="ring-finger-tip",Ca.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",Ca.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",Ca.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",Ca.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",Ca.PINKY_FINGER_TIP="pinky-finger-tip";const ya=[ba.WRIST,ba.THUMB_METACARPAL,ba.THUMB_PHALANX_PROXIMAL,ba.THUMB_PHALANX_DISTAL,ba.THUMB_TIP,ba.INDEX_FINGER_METACARPAL,ba.INDEX_FINGER_PHALANX_PROXIMAL,ba.INDEX_FINGER_PHALANX_INTERMEDIATE,ba.INDEX_FINGER_PHALANX_DISTAL,ba.INDEX_FINGER_TIP,ba.MIDDLE_FINGER_METACARPAL,ba.MIDDLE_FINGER_PHALANX_PROXIMAL,ba.MIDDLE_FINGER_PHALANX_INTERMEDIATE,ba.MIDDLE_FINGER_PHALANX_DISTAL,ba.MIDDLE_FINGER_TIP,ba.RING_FINGER_METACARPAL,ba.RING_FINGER_PHALANX_PROXIMAL,ba.RING_FINGER_PHALANX_INTERMEDIATE,ba.RING_FINGER_PHALANX_DISTAL,ba.RING_FINGER_TIP,ba.PINKY_FINGER_METACARPAL,ba.PINKY_FINGER_PHALANX_PROXIMAL,ba.PINKY_FINGER_PHALANX_INTERMEDIATE,ba.PINKY_FINGER_PHALANX_DISTAL,ba.PINKY_FINGER_TIP],Aa={[Ea.WRIST]:[ba.WRIST],[Ea.THUMB]:[ba.THUMB_METACARPAL,ba.THUMB_PHALANX_PROXIMAL,ba.THUMB_PHALANX_DISTAL,ba.THUMB_TIP],[Ea.INDEX]:[ba.INDEX_FINGER_METACARPAL,ba.INDEX_FINGER_PHALANX_PROXIMAL,ba.INDEX_FINGER_PHALANX_INTERMEDIATE,ba.INDEX_FINGER_PHALANX_DISTAL,ba.INDEX_FINGER_TIP],[Ea.MIDDLE]:[ba.MIDDLE_FINGER_METACARPAL,ba.MIDDLE_FINGER_PHALANX_PROXIMAL,ba.MIDDLE_FINGER_PHALANX_INTERMEDIATE,ba.MIDDLE_FINGER_PHALANX_DISTAL,ba.MIDDLE_FINGER_TIP],[Ea.RING]:[ba.RING_FINGER_METACARPAL,ba.RING_FINGER_PHALANX_PROXIMAL,ba.RING_FINGER_PHALANX_INTERMEDIATE,ba.RING_FINGER_PHALANX_DISTAL,ba.RING_FINGER_TIP],[Ea.LITTLE]:[ba.PINKY_FINGER_METACARPAL,ba.PINKY_FINGER_PHALANX_PROXIMAL,ba.PINKY_FINGER_PHALANX_INTERMEDIATE,ba.PINKY_FINGER_PHALANX_DISTAL,ba.PINKY_FINGER_TIP]};class Ra{get handMesh(){return this._handMesh}getHandPartMeshes(e){return Aa[e].map((e=>this._jointMeshes[ya.indexOf(e)]))}getJointMesh(e){return this._jointMeshes[ya.indexOf(e)]}constructor(e,t,i,s,r=!1,n=!1,o=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=s,this._leftHandedMeshes=r,this._jointsInvisible=n,this._jointScaleFactor=o,this.onHandMeshSetObservable=new g,this._jointTransforms=new Array(ya.length),this._jointTransformMatrices=new Float32Array(16*ya.length),this._tempJointMatrix=new B,this._jointRadii=new Float32Array(ya.length),this._scene=t[0].getScene();for(let e=0;e{e._doNotLoadControllerMesh=!0}))}setHandMesh(e,t,i){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach((e=>{e.alwaysSelectAsActiveMesh=!0})),this._handMesh.skeleton){const e=this._handMesh.skeleton;ya.forEach(((i,s)=>{const r=e.getBoneIndexByName(t?t[i]:i);-1!==r&&e.bones[r].linkTransformNode(this._jointTransforms[s])}))}this.onHandMeshSetObservable.notifyObservers(this)}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const s=i,r=ya.map((e=>s[e]||i.get(e)));let n=!1;if(e.fillPoses&&e.fillJointRadii)n=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){n=!0;for(let i=0;i{const i=this._jointTransforms[t];B.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);const s=this._jointRadii[t]*this._jointScaleFactor,r=this._jointMeshes[t];r.isVisible=!this._handMesh&&!this._jointsInvisible,r.position.copyFrom(i.position),r.rotationQuaternion.copyFrom(i.rotationQuaternion),r.scaling.setAll(s),this._scene.useRightHandedSystem||(r.position.z*=-1,r.rotationQuaternion.z*=-1,r.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))})),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(e=!1){this._handMesh&&(e?(this._handMesh.skeleton?.dispose(),this._handMesh.dispose(!1,!0)):this._handMesh.isVisible=!1)}}class Ia extends _o{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map((i=>{const s=[],r=e.jointMeshes?.sourceMesh||Sa("jointParent",Ia._ICOSPHERE_PARAMS);r.isVisible=!!e.jointMeshes?.keepOriginalVisible;for(let t=0;t{const r={};Ia._RightHandGLB?.meshes[1]?.isDisposed()&&(Ia._RightHandGLB=null),Ia._LeftHandGLB?.meshes[1]?.isDisposed()&&(Ia._LeftHandGLB=null);const n=!(!Ia._RightHandGLB||!Ia._LeftHandGLB),o=await Promise.all([Ia._RightHandGLB||Ro.ImportMeshAsync("",Ia.DEFAULT_HAND_MODEL_BASE_URL,Ia.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),Ia._LeftHandGLB||Ro.ImportMeshAsync("",Ia.DEFAULT_HAND_MODEL_BASE_URL,Ia.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);Ia._RightHandGLB=o[0],Ia._LeftHandGLB=o[1];const a=await xa.ParseFromFileAsync("handShader",Ia.DEFAULT_HAND_MODEL_SHADER_URL,e);a.needDepthPrePass=!0,a.transparencyMode=Dn.MATERIAL_ALPHABLEND,a.alphaMode=2,a.build(!1);const l={base:Y.FromInts(116,63,203),fresnel:Y.FromInts(149,102,229),fingerColor:Y.FromInts(177,130,255),tipFresnel:Y.FromInts(220,200,255),...i?.handMeshes?.customColors},h={base:a.getBlockByName("baseColor"),fresnel:a.getBlockByName("fresnelColor"),fingerColor:a.getBlockByName("fingerColor"),tipFresnel:a.getBlockByName("tipFresnelColor")};h.base.value=l.base,h.fresnel.value=l.fresnel,h.fingerColor.value=l.fingerColor,h.tipFresnel.value=l.tipFresnel;const c=t._getBaseLayerWrapper()?.isMultiview;["left","right"].forEach((t=>{const i="left"==t?Ia._LeftHandGLB:Ia._RightHandGLB;if(!i)throw new Error("Could not load hand model");const s=i.meshes[1];s._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,c||(s.material=a.clone(`${t}HandShaderClone`,!0)),s.isVisible=!1,r[t]=s,n||e.useRightHandedSystem||i.meshes[1].rotate(Gs.Y,Math.PI)})),a.dispose(),s({left:r.left,right:r.right})}))}static _GenerateDefaultHandMeshRigMapping(e){const t="right"==e?"R":"L";return{[ba.WRIST]:`wrist_${t}`,[ba.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[ba.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[ba.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[ba.THUMB_TIP]:`thumb_tip_${t}`,[ba.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[ba.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[ba.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[ba.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[ba.INDEX_FINGER_TIP]:`index_tip_${t}`,[ba.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[ba.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[ba.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[ba.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[ba.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[ba.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[ba.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[ba.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[ba.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[ba.RING_FINGER_TIP]:`ring_tip_${t}`,[ba.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[ba.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[ba.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[ba.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[ba.PINKY_FINGER_TIP]:`little_tip_${t}`}}isCompatible(){return"undefined"!=typeof XRHand}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return"none"==e?null:this._trackingHands[e]}constructor(e,t){super(e),this.options=t,this._attachedHands={},this._trackingHands={left:null,right:null},this._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},this._worldScaleObserver=null,this.onHandAddedObservable=new g,this.onHandRemovedObservable=new g,this._attachHand=e=>{if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;const t=e.inputSource.handedness,i=new Ra(e,this._handResources.jointMeshes[t],this._handResources.handMeshes&&this._handResources.handMeshes[t],this._handResources.rigMappings&&this._handResources.rigMappings[t],this.options.handMeshes?.meshesUseLeftHandedCoordinates,this.options.jointMeshes?.invisible,this.options.jointMeshes?.scaleFactor);this._attachedHands[e.uniqueId]=i,this._trackingHands[t]=i,this.onHandAddedObservable.notifyObservers(i)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";const i=t.jointMeshes;if(i&&(void 0!==i.disableDefaultHandMesh&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=i.disableDefaultHandMesh),void 0!==i.handMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=i.handMeshes),void 0!==i.leftHandedSystemMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=i.leftHandedSystemMeshes),void 0!==i.rigMapping)){t.handMeshes=t.handMeshes||{};const e={},s={};[[i.rigMapping.left,e],[i.rigMapping.right,s]].forEach((e=>{const t=e[0],i=e[1];t.forEach(((e,t)=>{i[ya[t]]=e}))})),t.handMeshes.customRigMappings={left:e,right:s}}}attach(){return!!super.attach()&&(this._handResources={jointMeshes:Ia._GenerateTrackedJointMeshes(this.options),handMeshes:this.options.handMeshes?.customMeshes||null,rigMappings:this.options.handMeshes?.customRigMappings||null},this.options.handMeshes?.customMeshes||this.options.handMeshes?.disableDefaultMeshes||(Ia._GenerateDefaultHandMeshesAsync(y.LastCreatedScene,this._xrSessionManager,this.options).then((e=>{this._handResources.handMeshes=e,this._handResources.rigMappings={left:Ia._GenerateDefaultHandMeshRigMapping("left"),right:Ia._GenerateDefaultHandMeshRigMapping("right")},this._trackingHands.left?.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left,this._xrSessionManager),this._trackingHands.right?.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right,this._xrSessionManager),this._handResources.handMeshes.left.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._handResources.handMeshes.right.scaling.setAll(this._xrSessionManager.worldScalingFactor)})),this._worldScaleObserver=this._xrSessionManager.onWorldScaleFactorChangedObservable.add((e=>{this._handResources.handMeshes&&(this._handResources.handMeshes.left.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor),this._handResources.handMeshes.right.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor))}))),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0)}_onXRFrame(e){this._trackingHands.left?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),this._trackingHands.right?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e,t){const i=this.getHandByControllerId(e);if(i){const s="left"==i.xrController.inputSource.handedness?"left":"right";this._trackingHands[s]?.xrController.uniqueId===e&&(this._trackingHands[s]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(t),delete this._attachedHands[e]}}detach(){return!!super.detach()&&(Object.keys(this._attachedHands).forEach((e=>this._detachHandById(e,this.options.handMeshes?.disposeOnSessionEnd))),this.options.handMeshes?.disposeOnSessionEnd&&this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose()))),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver),!0)}dispose(){super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!this.options.handMeshes?.customMeshes&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),Ia._RightHandGLB=null,Ia._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose())))}}var Pa,Ma,Da;Ia.Name=po.HAND_TRACKING,Ia.Version=1,Ia.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",Ia.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",Ia.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",Ia.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",Ia._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},Ia._RightHandGLB=null,Ia._LeftHandGLB=null,fo.AddWebXRFeature(Ia.Name,((e,t)=>()=>new Ia(e,t)),Ia.Version,!1),function(e){e[e.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",e[e.RADIAL_SIDE=1]="RADIAL_SIDE",e[e.ULNAR_SIDE=2]="ULNAR_SIDE",e[e.BELOW_WRIST=3]="BELOW_WRIST"}(Pa||(Pa={})),function(e){e[e.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",e[e.HAND_ROTATION=1]="HAND_ROTATION"}(Ma||(Ma={})),function(e){e[e.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",e[e.PALM_UP=1]="PALM_UP",e[e.GAZE_FOCUS=2]="GAZE_FOCUS",e[e.PALM_AND_GAZE=3]="PALM_AND_GAZE"}(Da||(Da={}));class Oa{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=w.Zero(),this.poleTargetPosition=w.Zero(),this.poleTargetLocalOffset=w.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=L.Identity(),this._bone1Mat=B.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=w.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;const s=t.getParent();if(!s)return this._notEnoughInformation=!0,void J.Error("BoneIKController: bone must have a parent for IK to work.");if(this._bone1=s,0===this._bone2.children.length&&!this._bone2.length)return this._notEnoughInformation=!0,void J.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();const r=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,r.x>r.y&&r.x>r.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){const e=this._bone1.getScale(),t=this._bone2.getScale();this._bone1Length=this._bone1.length*e.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);const t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),s=this._bone1.getAbsolutePosition(e);this._bone2Length=w.Distance(t,i),this._bone1Length=w.Distance(i,s)}else{e.computeWorldMatrix(!0);const t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;const i=this._bone2.getAbsolutePosition(e),s=this._bone1.getAbsolutePosition(e);this._bone1Length=w.Distance(i,s)}this._bone1.getRotationMatrixToRef(Fs.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||null==e)&&(e=Math.PI),this._maxAngle=e;const t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;const e=this.targetPosition,t=this.poleTargetPosition,i=Oa._TmpMats[0],s=Oa._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&w.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);const r=Oa._TmpVecs[0],n=Oa._TmpVecs[1],o=Oa._TmpVecs[2],a=Oa._TmpVecs[3],l=Oa._TmpVecs[4],h=Oa._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,r),t.subtractToRef(r,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),e.subtractToRef(r,a),a.normalize(),w.CrossToRef(a,l,n),n.normalize(),w.CrossToRef(a,n,o),o.normalize(),B.FromXYZAxesToRef(o,a,n,i);const c=this._bone1Length,u=this._bone2Length;let d=w.Distance(r,e);this._maxReach>0&&(d=Math.min(this._maxReach,d));let p=(u*u+d*d-c*c)/(2*u*d),f=(d*d+c*c-u*u)/(2*d*c);p>1&&(p=1),f>1&&(f=1),p<-1&&(p=-1),f<-1&&(f=-1);const _=Math.acos(p),m=Math.acos(f);let g=-_-m;if(this._rightHandedSystem)B.RotationYawPitchRollToRef(0,0,this._adjustRoll,s),s.multiplyToRef(i,i),B.RotationAxisToRef(this._bendAxis,m,s),s.multiplyToRef(i,i);else{const e=Oa._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,B.RotationAxisToRef(e,-m,s),s.multiplyToRef(i,i)}this.poleAngle&&(B.RotationAxisToRef(a,this.poleAngle,s),i.multiplyToRef(s,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||L.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),L.FromRotationMatrixToRef(i,h),L.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),g=this._bone2Ang*(1-this.slerpAmount)+g*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,Fs.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,Fs.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,g,Fs.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=g}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new L),e.getRotationQuaternionToRef(Fs.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}Oa._TmpVecs=[w.Zero(),w.Zero(),w.Zero(),w.Zero(),w.Zero(),w.Zero()],Oa._TmpQuat=L.Identity(),Oa._TmpMats=[B.Identity(),B.Identity()];class Na{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,s){if(this.upAxis=w.Up(),this.upAxisSpace=Fs.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=L.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=w.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,s){if(s.adjustYaw&&(this.adjustYaw=s.adjustYaw),s.adjustPitch&&(this.adjustPitch=s.adjustPitch),s.adjustRoll&&(this.adjustRoll=s.adjustRoll),null!=s.maxYaw?this.maxYaw=s.maxYaw:this.maxYaw=Math.PI,null!=s.minYaw?this.minYaw=s.minYaw:this.minYaw=-Math.PI,null!=s.maxPitch?this.maxPitch=s.maxPitch:this.maxPitch=Math.PI,null!=s.minPitch?this.minPitch=s.minPitch:this.minPitch=-Math.PI,null!=s.slerpAmount&&(this.slerpAmount=s.slerpAmount),null!=s.upAxis&&(this.upAxis=s.upAxis),null!=s.upAxisSpace&&(this.upAxisSpace=s.upAxisSpace),null!=s.yawAxis||null!=s.pitchAxis){let e=Gs.Y,t=Gs.X;null!=s.yawAxis&&(e=s.yawAxis.clone(),e.normalize()),null!=s.pitchAxis&&(t=s.pitchAxis.clone(),t.normalize());const i=w.Cross(t,e);this._transformYawPitch=B.Identity(),B.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==s.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=s.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=Fs.BONE||(this.upAxisSpace=Fs.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped)return void(this._firstFrameSkipped=!0);const e=this.bone,t=Na._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target;const s=Na._TmpMats[0],r=Na._TmpMats[1],n=this.mesh,o=e.getParent(),a=Na._TmpVecs[1];a.copyFrom(this.upAxis),this.upAxisSpace==Fs.BONE&&o?(this._transformYawPitch&&w.TransformCoordinatesToRef(a,this._transformYawPitchInv,a),o.getDirectionToRef(a,this.mesh,a)):this.upAxisSpace==Fs.LOCAL&&(n.getDirectionToRef(a,a),1==n.scaling.x&&1==n.scaling.y&&1==n.scaling.z||a.normalize());let l=!1,h=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(l=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(h=!0),l||h){const e=Na._TmpMats[2],s=Na._TmpMats[3];if(this.upAxisSpace==Fs.BONE&&1==a.y&&o)o.getRotationMatrixToRef(Fs.WORLD,this.mesh,e);else if(this.upAxisSpace!=Fs.LOCAL||1!=a.y||o){let t=Na._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&w.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),o?o.getDirectionToRef(t,this.mesh,t):n.getDirectionToRef(t,t);const i=w.Cross(a,t);i.normalize(),t=w.Cross(i,a),B.FromXYZAxesToRef(i,a,t,e)}else e.copyFrom(n.getWorldMatrix());e.invertToRef(s);let r=null;if(h){const n=Na._TmpVecs[3];i.subtractToRef(t,n),w.TransformCoordinatesToRef(n,s,n),r=Math.sqrt(n.x*n.x+n.z*n.z);const o=Math.atan2(n.y,r);let a=o;o>this._maxPitch?(n.y=this._maxPitchTan*r,a=this._maxPitch):othis._maxYaw||aMath.PI?this._isAngleBetween(o,this._maxYaw,this._midYawConstraint)?(n.z=this._maxYawCos*r,n.x=this._maxYawSin*r,l=this._maxYaw):this._isAngleBetween(o,this._midYawConstraint,this._minYaw)&&(n.z=this._minYawCos*r,n.x=this._minYawSin*r,l=this._minYaw):a>this._maxYaw?(n.z=this._maxYawCos*r,n.x=this._maxYawSin*r,o<0&&this.useAbsoluteValueForYaw&&(n.x*=-1),l=this._maxYaw):aMath.PI){const e=Na._TmpVecs[8];e.copyFrom(Gs.Z),this._transformYawPitch&&w.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);const t=Na._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),w.TransformCoordinatesToRef(e,t,e),w.TransformCoordinatesToRef(e,s,e);const i=Math.atan2(e.x,e.z);if(this._getAngleBetween(i,o)>this._getAngleBetween(i,this._midYawConstraint)){null==r&&(r=Math.sqrt(n.x*n.x+n.z*n.z));const e=this._getAngleBetween(i,this._maxYaw);this._getAngleBetween(i,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){let i=0;return i=(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)<(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)?t-e:e-t,i>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e=(e%=2*Math.PI)<0?e+2*Math.PI:e,(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)<(i=(i%=2*Math.PI)<0?i+2*Math.PI:i)){if(e>t&&ei&&e{const e=new Uint8Array(4);return!!((new Uint32Array(e.buffer)[0]=1)&e[0])})();Object.defineProperty(Ki.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0}),Object.defineProperty(Ki.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0}),Object.defineProperty(Ki.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0}),Ki.prototype._rebuild=function(){this._buffer?._rebuild(),this._alignedBuffer?._rebuild()},Ki.prototype.dispose=function(){this._ownsBuffer&&this._buffer.dispose(),this._alignedBuffer?.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0},Ki.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer},Ki.prototype._alignBuffer=function(){const e=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes||this.byteStride%4==0&&this.byteOffset%4==0||!e)return;const t=Ki.GetTypeByteLength(this.type),i=this.byteStride+3&-4,s=i/t,r=this._maxVerticesCount,n=r*i/t;let o,a;if(Array.isArray(e)){const t=new Float32Array(e);o=new DataView(t.buffer,t.byteOffset,t.byteLength)}else o=e instanceof ArrayBuffer?new DataView(e,0,e.byteLength):new DataView(e.buffer,e.byteOffset,e.byteLength);a=this.type===Ki.BYTE?new Int8Array(n):this.type===Ki.UNSIGNED_BYTE?new Uint8Array(n):this.type===Ki.SHORT?new Int16Array(n):this.type===Ki.UNSIGNED_SHORT?new Uint16Array(n):this.type===Ki.INT?new Int32Array(n):this.type===Ki.UNSIGNED_INT?new Uint32Array(n):new Float32Array(n);const l=this.getSize();let h=this.byteOffset;for(let e=0;e{if(t.type!==ss.POINTERWHEEL)return;const i=t.event,s=i.deltaMode===vs.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*s*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*s*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*s*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,ss.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}ae([pe()],La.prototype,"wheelPrecisionX",void 0),ae([pe()],La.prototype,"wheelPrecisionY",void 0),ae([pe()],La.prototype,"wheelPrecisionZ",void 0);class Ba{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let s=0,r=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=n=>{const o=n.event,a="touch"===o.pointerType;if(n.type!==ss.POINTERMOVE&&-1===this.buttons.indexOf(o.button))return;const l=o.target;if(this._altKey=o.altKey,this._ctrlKey=o.ctrlKey,this._metaKey=o.metaKey,this._shiftKey=o.shiftKey,this._buttonsPressed=o.buttons,t.isPointerLock){const e=o.movementX,t=o.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(n.type!==ss.POINTERDOWN&&n.type!==ss.POINTERDOUBLETAP&&a&&this._pointA?.pointerId!==o.pointerId&&this._pointB?.pointerId!==o.pointerId)return;if(n.type!==ss.POINTERDOWN||-1!==this._currentActiveButton&&!a)if(n.type===ss.POINTERDOUBLETAP)this.onDoubleTap(o.pointerType);else if(n.type!==ss.POINTERUP||this._currentActiveButton!==o.button&&!a){if(n.type===ss.POINTERMOVE)if(e||o.preventDefault(),this._pointA&&null===this._pointB){const e=o.clientX-this._pointA.x,t=o.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=o.clientX,this._pointA.y=o.clientY}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===o.pointerId?this._pointA:this._pointB;e.x=o.clientX,e.y=o.clientY;const t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,a=t*t+i*i,l={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:o.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,s,a,r,l),r=l,s=a}}else{try{l?.releasePointerCapture(o.pointerId)}catch(e){}a||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==o.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==o.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==s||r)&&(this.onMultiTouch(this._pointA,this._pointB,s,0,r,null),s=0,r=null),this._currentActiveButton=-1,this.onButtonUp(o),e||o.preventDefault()}else{try{l?.setPointerCapture(o.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType};else{if(null!==this._pointB)return;this._pointB={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType}}-1!==this._currentActiveButton||a||(this._currentActiveButton=o.button),this.onButtonDown(o),e||(o.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,ss.POINTERDOWN|ss.POINTERUP|ss.POINTERMOVE|ss.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,r=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&Ii.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Ii.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,s,r,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}ae([pe()],Ba.prototype,"buttons",void 0);var Va,Ua,ka,Ga,za,Wa,Ha={};class Xa{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();this.attached[t]?J.Warn("camera input of type "+t+" already exists on camera"):(this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault))}remove(e){for(const t in this.attached){const i=this.attached[t];if(i===e)return i.detachControl(),i.camera=null,delete this.attached[t],void this.rebuildInputCheck()}}removeByType(e){for(const t in this.attached){const i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){const t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=!or.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e;for(const t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(const t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(const e in this.attached){const t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){const t={};for(const e in this.attached){const i=this.attached[e],s=Pe.Serialize(i);t[i.getClassName()]=s}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=Ha[e];if(i){const s=t[e],r=Pe.Parse((()=>new i),s,null);this.add(r)}}}else for(const t in this.attached){const i=Ha[this.attached[t].getClassName()];if(i){const s=Pe.Parse((()=>new i),e,null);this.remove(this.attached[t]),this.add(s)}}}}class Ya{get isConnected(){return this._isConnected}constructor(e,t,i,s=0,r=1,n=2,o=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=Ya.GAMEPAD,this._leftStickAxisX=s,this._leftStickAxisY=r,this._rightStickAxisX=n,this._rightStickAxisY=o,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}}Ya.GAMEPAD=0,Ya.GENERIC=1,Ya.XBOX=2,Ya.POSE_ENABLED=3,Ya.DUALSHOCK=4;class ja extends Ya{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new g,this.onButtonUpObservable=new g,this.type=Ya.GENERIC,this._buttons=new Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{e.type!==Ya.POSE_ENABLED&&(this.gamepad&&e.type!==Ya.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(Ya.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){const e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){const i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){const i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}const i=this.gamepad.leftStick;if(i&&0!=i.y){const e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}ae([pe()],$a.prototype,"gamepadRotationSensibility",void 0),ae([pe()],$a.prototype,"gamepadMoveSensibility",void 0),Ha.ArcRotateCameraGamepadInput=$a;class Ka{constructor(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===as.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t0?s/(1+this.wheelDeltaPercentage):s*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==ss.POINTERWHEEL)return;const i=t.event;let s=0;const r=i.deltaMode===vs.DOM_DELTA_LINE?40:1,n=-i.deltaY*r;if(this.customComputeDeltaFromMouseWheel)s=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if(s=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius),s>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+s;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=G.Clamp(e,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else s=n/(40*this.wheelPrecision);s&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(s)):this.camera.inertialRadiusOffset+=s),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,ss.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}checkInputs(){if(!this.zoomToMouseLocation)return;const e=this.camera;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){const e=this.camera,t=e.target.subtract(e.position);this._hitPlane=Ps.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,B.Identity(),e,!1);0===e.targetScreenOffset.x&&0===e.targetScreenOffset.y||(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=w.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(s))}_zoomToMouse(e){const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const s=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/is&&(e=(t.radius-s)*i-t.inertialRadiusOffset)}const s=e/i/t.radius,r=this._getPosition(),n=U.Vector3[6];r.subtractToRef(t.target,n),n.scaleInPlace(s),n.scaleInPlace(i),this._inertialPanning.addInPlace(n),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,s),this._isPinching=!0):this._computeMultiTouchPanning(r,n)):this.multiTouchPanning?this._computeMultiTouchPanning(r,n):this.pinchZoom&&this._computePinchZoom(i,s))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}Qa.MinimumRadiusForPinch=.001,ae([pe()],Qa.prototype,"buttons",void 0),ae([pe()],Qa.prototype,"angularSensibilityX",void 0),ae([pe()],Qa.prototype,"angularSensibilityY",void 0),ae([pe()],Qa.prototype,"pinchPrecision",void 0),ae([pe()],Qa.prototype,"pinchDeltaPercentage",void 0),ae([pe()],Qa.prototype,"useNaturalPinchZoom",void 0),ae([pe()],Qa.prototype,"pinchZoom",void 0),ae([pe()],Qa.prototype,"panningSensibility",void 0),ae([pe()],Qa.prototype,"multiTouchPanning",void 0),ae([pe()],Qa.prototype,"multiTouchPanAndZoom",void 0),Ha.ArcRotateCameraPointersInput=Qa;class Za extends Xa{constructor(e){super(e)}addMouseWheel(){return this.add(new qa),this}addPointers(){return this.add(new Qa),this}addKeyboard(){return this.add(new Ka),this}}Za.prototype.addVRDeviceOrientation=function(){return this.add(new Ja),this};class Ja{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=e=>this._onOrientationEvent(e)}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);const t=this.camera.getScene().getEngine().getHostWindow();t&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t.addEventListener("deviceorientation",this._deviceOrientationHandler):Ii.Warn("Permission not granted.")})).catch((e=>{Ii.Error(e)})):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*this.gammaCorrection),this._dirty=!0}checkInputs(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)}detachControl(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)}getClassName(){return"ArcRotateCameraVRDeviceOrientationInput"}getSimpleName(){return"VRDeviceOrientation"}}Ha.ArcRotateCameraVRDeviceOrientationInput=Ja;class el{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=new Array}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(t.type===as.KEYDOWN)-1===this.keysForward.indexOf(i.keyCode)&&-1===this.keysBackward.indexOf(i.keyCode)&&-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{this._pointerInput(e)}),ss.POINTERDOWN|ss.POINTERUP|ss.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add((()=>{this.camera.rollCorrect&&this.camera.restoreRoll(this.camera.rollCorrect)}))}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)}getClassName(){return"FlyCameraMouseInput"}getSimpleName(){return"mouse"}_pointerInput(e){const t=e.event,i=this.camera.getEngine();if(!this.touchEnabled&&"touch"===t.pointerType)return;if(e.type!==ss.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;const s=t.target;if(e.type===ss.POINTERDOWN){try{s?.setPointerCapture(t.pointerId)}catch(t){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),i.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===ss.POINTERUP){try{s?.releasePointerCapture(t.pointerId)}catch(t){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===ss.POINTERMOVE){if(!this._previousPosition)return void(i.isPointerLock&&this._onMouseMove(e.event));const s=t.clientX-this._previousPosition.x,r=t.clientY-this._previousPosition.y;this._rotateCamera(s,r),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){if(!this.camera.getEngine().isPointerLock)return;const t=e.movementX,i=e.movementY;this._rotateCamera(t,i),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera,s=(e*=i._calculateHandednessMultiplier())/this.angularSensibility,r=t/this.angularSensibility,n=L.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let o;if(this.buttonsPitch.some((e=>e===this.activeButton))&&(o=L.RotationAxis(Gs.X,r),n.multiplyInPlace(o)),this.buttonsYaw.some((e=>e===this.activeButton))){o=L.RotationAxis(Gs.Y,s),n.multiplyInPlace(o);const e=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-ee===this.activeButton))&&(o=L.RotationAxis(Gs.Z,-s),i._trackRoll-=s,n.multiplyInPlace(o)),n.toEulerAnglesToRef(i.rotation)}}ae([pe()],tl.prototype,"buttons",void 0),ae([pe()],tl.prototype,"angularSensibility",void 0),Ha.FlyCameraMouseInput=tl;class il{constructor(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=new Array}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===as.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){this._onKeyboardObserver&&this._keys.forEach((e=>{-1!==this.keysHeightOffsetIncr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:-1!==this.keysHeightOffsetDecr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:-1!==this.keysRotationOffsetIncr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRotationOffsetDecr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRadiusIncr.indexOf(e)&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:-1!==this.keysRadiusDecr.indexOf(e)&&this._modifierRadius()&&(this.camera.radius-=this.radiusSensibility)}))}getClassName(){return"FollowCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}_modifierHeightOffset(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed}_modifierRotationOffset(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed}_modifierRadius(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed}}ae([pe()],il.prototype,"keysHeightOffsetIncr",void 0),ae([pe()],il.prototype,"keysHeightOffsetDecr",void 0),ae([pe()],il.prototype,"keysHeightOffsetModifierAlt",void 0),ae([pe()],il.prototype,"keysHeightOffsetModifierCtrl",void 0),ae([pe()],il.prototype,"keysHeightOffsetModifierShift",void 0),ae([pe()],il.prototype,"keysRotationOffsetIncr",void 0),ae([pe()],il.prototype,"keysRotationOffsetDecr",void 0),ae([pe()],il.prototype,"keysRotationOffsetModifierAlt",void 0),ae([pe()],il.prototype,"keysRotationOffsetModifierCtrl",void 0),ae([pe()],il.prototype,"keysRotationOffsetModifierShift",void 0),ae([pe()],il.prototype,"keysRadiusIncr",void 0),ae([pe()],il.prototype,"keysRadiusDecr",void 0),ae([pe()],il.prototype,"keysRadiusModifierAlt",void 0),ae([pe()],il.prototype,"keysRadiusModifierCtrl",void 0),ae([pe()],il.prototype,"keysRadiusModifierShift",void 0),ae([pe()],il.prototype,"heightSensibility",void 0),ae([pe()],il.prototype,"rotationSensibility",void 0),ae([pe()],il.prototype,"radiusSensibility",void 0),Ha.FollowCameraKeyboardMoveInput=il;class sl{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==ss.POINTERWHEEL)return;const i=t.event;let s=0;const r=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(+this.axisControlRadius+ +this.axisControlHeight+ +this.axisControlRotation&&J.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?s=.01*r*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?s=.01*r*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(s=.01*r*this.wheelDeltaPercentage*this.camera.rotationOffset)):s=r*this.wheelPrecision,s&&(this.axisControlRadius?this.camera.radius+=s:this.axisControlHeight?this.camera.heightOffset-=s:this.axisControlRotation&&(this.camera.rotationOffset-=s)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,ss.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}ae([pe()],sl.prototype,"axisControlRadius",void 0),ae([pe()],sl.prototype,"axisControlHeight",void 0),ae([pe()],sl.prototype,"axisControlRotation",void 0),ae([pe()],sl.prototype,"wheelPrecision",void 0),ae([pe()],sl.prototype,"wheelDeltaPercentage",void 0),Ha.FollowCameraMouseWheelInput=sl;class rl extends Ba{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,s,r,n){if(0===i&&null===r)return;if(0===s&&null===n)return;let o=(s-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(o*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=o*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=o*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=o*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=o),this.axisPinchControlHeight&&(this.camera.heightOffset+=o),this.axisPinchControlRadius&&(this.camera.radius-=o))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;const e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";+this.axisXControlRotation+ +this.axisXControlHeight+ +this.axisXControlRadius<=1&&J.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&J.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&J.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}ae([pe()],rl.prototype,"angularSensibilityX",void 0),ae([pe()],rl.prototype,"angularSensibilityY",void 0),ae([pe()],rl.prototype,"pinchPrecision",void 0),ae([pe()],rl.prototype,"pinchDeltaPercentage",void 0),ae([pe()],rl.prototype,"axisXControlRadius",void 0),ae([pe()],rl.prototype,"axisXControlHeight",void 0),ae([pe()],rl.prototype,"axisXControlRotation",void 0),ae([pe()],rl.prototype,"axisYControlRadius",void 0),ae([pe()],rl.prototype,"axisYControlHeight",void 0),ae([pe()],rl.prototype,"axisYControlRotation",void 0),ae([pe()],rl.prototype,"axisPinchControlRadius",void 0),ae([pe()],rl.prototype,"axisPinchControlHeight",void 0),ae([pe()],rl.prototype,"axisPinchControlRotation",void 0),Ha.FollowCameraPointersInput=rl;class nl{constructor(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===as.KEYDOWN)-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)&&-1===this.keysUpward.indexOf(i.keyCode)&&-1===this.keysDownward.indexOf(i.keyCode)&&-1===this.keysRotateLeft.indexOf(i.keyCode)&&-1===this.keysRotateRight.indexOf(i.keyCode)&&-1===this.keysRotateUp.indexOf(i.keyCode)&&-1===this.keysRotateDown.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysUpward.indexOf(i.keyCode)||-1!==this.keysDownward.indexOf(i.keyCode)||-1!==this.keysRotateLeft.indexOf(i.keyCode)||-1!==this.keysRotateRight.indexOf(i.keyCode)||-1!==this.keysRotateUp.indexOf(i.keyCode)||-1!==this.keysRotateDown.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{const r=s.event,n="touch"===r.pointerType;if(!this.touchEnabled&&n)return;if(s.type!==ss.POINTERMOVE&&-1===this.buttons.indexOf(r.button))return;const o=r.target;if(s.type===ss.POINTERDOWN){if(n&&-1!==this._activePointerId||!n&&-1!==this._currentActiveButton)return;this._activePointerId=r.pointerId;try{o?.setPointerCapture(r.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=r.button),this._previousPosition={x:r.clientX,y:r.clientY},e||(r.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(s.event)}else if(s.type===ss.POINTERUP){if(n&&this._activePointerId!==r.pointerId||!n&&this._currentActiveButton!==r.button)return;try{o?.releasePointerCapture(r.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||r.preventDefault(),this._activePointerId=-1}else if(s.type===ss.POINTERMOVE&&(this._activePointerId===r.pointerId||!n))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(s.event);else if(this._previousPosition){const t=this.camera._calculateHandednessMultiplier(),i=(r.clientX-this._previousPosition.x)*t,s=r.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=s/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:s}),this._previousPosition={x:r.clientX,y:r.clientY},e||r.preventDefault()}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;const s=this.camera._calculateHandednessMultiplier(),r=i.movementX*s;this.camera.cameraRotation.y+=r/this.angularSensibility;const n=i.movementY;this.camera.cameraRotation.x+=n/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,ss.POINTERDOWN|ss.POINTERUP|ss.POINTERMOVE),i&&(this._contextMenuBind=e=>this.onContextMenu(e),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}ae([pe()],ol.prototype,"buttons",void 0),ae([pe()],ol.prototype,"angularSensibility",void 0),Ha.FreeCameraMouseInput=ol,function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(Va||(Va={}));class al extends La{constructor(){super(...arguments),this._moveRelative=w.Zero(),this._rotateRelative=w.Zero(),this._moveScene=w.Zero(),this._wheelXAction=Va.MoveRelative,this._wheelXActionCoordinate=Ls.X,this._wheelYAction=Va.MoveRelative,this._wheelYActionCoordinate=Ls.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){null===e&&this._wheelXAction!==Va.MoveRelative||(this._wheelXAction=Va.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Va.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){null===e&&this._wheelYAction!==Va.MoveRelative||(this._wheelYAction=Va.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Va.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){null===e&&this._wheelZAction!==Va.MoveRelative||(this._wheelZAction=Va.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Va.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){null===e&&this._wheelXAction!==Va.RotateRelative||(this._wheelXAction=Va.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Va.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){null===e&&this._wheelYAction!==Va.RotateRelative||(this._wheelYAction=Va.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Va.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){null===e&&this._wheelZAction!==Va.RotateRelative||(this._wheelZAction=Va.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Va.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){null===e&&this._wheelXAction!==Va.MoveScene||(this._wheelXAction=Va.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Va.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){null===e&&this._wheelYAction!==Va.MoveScene||(this._wheelYAction=Va.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Va.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){null===e&&this._wheelZAction!==Va.MoveScene||(this._wheelZAction=Va.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Va.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(0===this._wheelDeltaX&&0===this._wheelDeltaY&&0==this._wheelDeltaZ)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);const e=B.Zero();this.camera.getViewMatrix().invertToRef(e);const t=w.Zero();w.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,i){if(0===e)return;if(null===t||null===i)return;let s=null;switch(t){case Va.MoveRelative:s=this._moveRelative;break;case Va.RotateRelative:s=this._rotateRelative;break;case Va.MoveScene:s=this._moveScene}switch(i){case Ls.X:s.set(e,0,0);break;case Ls.Y:s.set(0,e,0);break;case Ls.Z:s.set(0,0,e)}}}ae([pe()],al.prototype,"wheelXMoveRelative",null),ae([pe()],al.prototype,"wheelYMoveRelative",null),ae([pe()],al.prototype,"wheelZMoveRelative",null),ae([pe()],al.prototype,"wheelXRotateRelative",null),ae([pe()],al.prototype,"wheelYRotateRelative",null),ae([pe()],al.prototype,"wheelZRotateRelative",null),ae([pe()],al.prototype,"wheelXMoveScene",null),ae([pe()],al.prototype,"wheelYMoveScene",null),ae([pe()],al.prototype,"wheelZMoveScene",null),Ha.FreeCameraMouseWheelInput=al;class ll{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=Ii.IsSafari()}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const s=i.event,r="mouse"===s.pointerType||this._isSafari&&void 0===s.pointerType;if(this.allowMouse||!r)if(i.type===ss.POINTERDOWN){if(e||s.preventDefault(),this._pointerPressed.push(s.pointerId),1!==this._pointerPressed.length)return;t={x:s.clientX,y:s.clientY}}else if(i.type===ss.POINTERUP){e||s.preventDefault();const i=this._pointerPressed.indexOf(s.pointerId);if(-1===i)return;if(this._pointerPressed.splice(i,1),0!=i)return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===ss.POINTERMOVE){if(e||s.preventDefault(),!t)return;if(0!=this._pointerPressed.indexOf(s.pointerId))return;this._offsetX=s.clientX-t.x,this._offsetY=-(s.clientY-t.y)}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,ss.POINTERDOWN|ss.POINTERUP|ss.POINTERMOVE),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(null===this._offsetX||null===this._offsetY)return;if(0===this._offsetX&&0===this._offsetY)return;const e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility,this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{const t=e._computeLocalCameraSpeed(),i=new w(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);B.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(w.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}ae([pe()],ll.prototype,"touchAngularSensibility",void 0),ae([pe()],ll.prototype,"touchMoveSensibility",void 0),Ha.FreeCameraTouchInput=ll;class hl extends Xa{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new nl),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new ol(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new al,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new ll),this}clear(){super.clear(),this._mouseInput=null}}hl.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new cl,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};class cl{static WaitForOrientationChangeAsync(e){return new Promise(((t,i)=>{let s=!1;const r=()=>{window.removeEventListener("deviceorientation",r),s=!0,t()};e&&setTimeout((()=>{s||(window.removeEventListener("deviceorientation",r),i("WaitForOrientationChangeAsync timed out"))}),e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"==e?window.addEventListener("deviceorientation",r):Ii.Warn("Permission not granted.")})).catch((e=>{Ii.Error(e)})):window.addEventListener("deviceorientation",r)}))}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new L,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new g,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-Ii.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?Ii.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?Ii.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?Ii.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new L(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new L),this._camera&&this._camera.onDisposeObservable.add((()=>{this._onDeviceOrientationChangedObservable.clear()}))}attachControl(){const e=this.camera.getScene().getEngine().getHostWindow();if(e){const t=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t():Ii.Warn("Permission not granted.")})).catch((e=>{Ii.Error(e)})):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(L.RotationYawPitchRollToRef(Ii.ToRadians(this._alpha),Ii.ToRadians(this._beta),-Ii.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}Ha.FreeCameraDeviceOrientationInput=cl;class ul{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=B.Identity(),this._deltaTransform=w.Zero(),this._vector3=w.Zero(),this._vector2=N.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{e.type!==Ya.POSE_ENABLED&&(this.gamepad&&e.type!==Ya.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(Ya.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){const e=this.camera,t=this.gamepad.leftStick;0!==this.gamepadMoveSensibility&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&0!==this.gamepadAngularSensibility?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):B.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const s=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*s,0,-t.y*s),w.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}}ae([pe()],ul.prototype,"gamepadAngularSensibility",void 0),ae([pe()],ul.prototype,"gamepadMoveSensibility",void 0),Ha.FreeCameraGamepadInput=ul,function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Ua||(Ua={}));class dl{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;const i={...dl._GetDefaultOptions(),...t};if(this._leftJoystick=!!e,dl._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=Ua.X,this._axisTargetedByUpAndDown=Ua.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new Oi,this.deltaPosition=w.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{dl._VJCanvasWidth=window.innerWidth,dl._VJCanvasHeight=window.innerHeight,dl.Canvas&&(dl.Canvas.width=dl._VJCanvasWidth,dl.Canvas.height=dl._VJCanvasHeight),dl._HalfWidth=dl._VJCanvasWidth/2},!dl.Canvas){window.addEventListener("resize",this._onResize,!1),dl.Canvas=document.createElement("canvas"),dl._VJCanvasWidth=window.innerWidth,dl._VJCanvasHeight=window.innerHeight,dl.Canvas.width=window.innerWidth,dl.Canvas.height=window.innerHeight,dl.Canvas.style.width="100%",dl.Canvas.style.height="100%",dl.Canvas.style.position="absolute",dl.Canvas.style.backgroundColor="transparent",dl.Canvas.style.top="0px",dl.Canvas.style.left="0px",dl.Canvas.style.zIndex="5",dl.Canvas.style.touchAction="none",dl.Canvas.setAttribute("touch-action","none");const e=dl.Canvas.getContext("2d");if(!e)throw new Error("Unable to create canvas for virtual joystick");dl._VJCanvasContext=e,dl._VJCanvasContext.strokeStyle="#ffffff",dl._VJCanvasContext.lineWidth=2,document.body.appendChild(dl.Canvas)}dl._HalfWidth=dl.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&dl._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new N(0,0),this._joystickPreviousPointerPos=new N(0,0),this._joystickPointerStartPos=new N(0,0),this._deltaJoystickVector=new N(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},dl.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),dl.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),dl.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),dl.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),dl.Canvas.addEventListener("contextmenu",(e=>{e.preventDefault()}),!1),requestAnimationFrame((()=>{this._drawVirtualJoystick()}))}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){let t;e.preventDefault(),t=!0===this._leftJoystick?e.clientXdl._HalfWidth,t&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):dl._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){const t=new N(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0this._containerImage=t}setPuckImage(e){const t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){const e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?dl._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(dl._VJCanvasContext.beginPath(),dl._VJCanvasContext.strokeStyle=this._joystickColor,dl._VJCanvasContext.lineWidth=2,dl._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),dl._VJCanvasContext.stroke(),dl._VJCanvasContext.closePath(),dl._VJCanvasContext.beginPath(),dl._VJCanvasContext.lineWidth=6,dl._VJCanvasContext.strokeStyle=this._joystickColor,dl._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),dl._VJCanvasContext.stroke(),dl._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?dl._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(dl._VJCanvasContext.beginPath(),dl._VJCanvasContext.strokeStyle=this._joystickColor,dl._VJCanvasContext.lineWidth=2,dl._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),dl._VJCanvasContext.stroke(),dl._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach(((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(dl._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),dl._VJCanvasContext.beginPath(),dl._VJCanvasContext.fillStyle="white",dl._VJCanvasContext.beginPath(),dl._VJCanvasContext.strokeStyle="red",dl._VJCanvasContext.lineWidth=6,dl._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),dl._VJCanvasContext.stroke(),dl._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)})),requestAnimationFrame((()=>{this._drawVirtualJoystick()})))}releaseCanvas(){dl.Canvas&&(dl.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),dl.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),dl.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),dl.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(dl.Canvas),dl.Canvas=null),this._released=!0}}dl._GlobalJoystickIndex=0,dl._AlwaysVisibleSticks=0,hl.prototype.addVirtualJoystick=function(){return this.add(new pl),this};class pl{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=50*e._computeLocalCameraSpeed(),i=B.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),s=w.TransformCoordinates(new w(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(s),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new dl(!0),this._leftjoystick.setAxisForUpDown(Ua.Z),this._leftjoystick.setAxisForLeftRight(Ua.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new dl(!1),this._rightjoystick.setAxisForUpDown(Ua.X),this._rightjoystick.setAxisForLeftRight(Ua.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}}Ha.FreeCameraVirtualJoystickInput=pl,De.AddNodeConstructor("TargetCamera",((e,t)=>()=>new fl(e,w.Zero(),t)));class fl extends or{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=w.Zero(),this._tmpTargetVector=w.Zero(),this.cameraDirection=new w(0,0,0),this.cameraRotation=new N(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new L,this.rotation=new w(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=w.Zero(),this._initialFocalDistance=1,this._viewMatrix=B.Zero(),this._camMatrix=B.Zero(),this._cameraTransformMatrix=B.Zero(),this._cameraRotationMatrix=B.Zero(),this._referencePoint=new w(0,0,1),this._transformedReferencePoint=w.Zero(),this._deferredPositionUpdate=new w,this._deferredRotationQuaternionUpdate=new L,this._deferredRotationUpdate=new w,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=w.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();const t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){const e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)}_initCache(){super._initCache(),this._cache.lockedTarget=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new L(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();const t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;const e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){const e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=T),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),B.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);const t=e.subtract(this.position);t.x>=0?this.rotation.y=-Math.atan(t.z/t.x)+Math.PI/2:this.rotation.y=-Math.atan(t.z/t.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&L.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(U.Matrix[0]),w.TransformNormalToRef(this.cameraDirection,U.Matrix[0],U.Vector3[0]),this._deferredPositionUpdate.addInPlace(U.Vector3[0]),void(this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate));this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint){const e=1.570796;this._deferredRotationUpdate.x>e&&(this._deferredRotationUpdate.x=e),this._deferredRotationUpdate.x<-e&&(this._deferredRotationUpdate.x=-e)}this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(L.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))}t&&(Math.abs(this.cameraDirection.x){this._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>Br.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new hl(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ii.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new w(0,0,0),this.cameraRotation=new N(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?w.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=w.Zero(),this._transformedDirection=w.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}}ae([ve()],_l.prototype,"ellipsoid",void 0),ae([ve()],_l.prototype,"ellipsoidOffset",void 0),ae([pe()],_l.prototype,"checkCollisions",void 0),ae([pe()],_l.prototype,"applyGravity",void 0),u("BABYLON.FreeCamera",_l),De.AddNodeConstructor("TouchCamera",((e,t)=>()=>new ml(e,w.Zero(),t)));class ml extends _l{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!e:e.allowMouse=!t}}De.AddNodeConstructor("ArcRotateCamera",((e,t)=>()=>new gl(e,0,0,1,w.Zero(),t)));class gl extends fl{get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new B,this._upToYMatrix=new B,this._upVector=w.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){B.RotationAlignToRef(w.UpReadOnly,this._upVector,this._yToUpMatrix),B.RotationAlignToRef(this._upVector,w.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){const e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){const t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){const e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){const t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){const e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){const t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){const e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){const t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){const e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){const e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){const t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){const e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return null!=this._bouncingBehavior}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new no,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return null!=this._framingBehavior}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new oo,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return null!=this._autoRotationBehavior}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new ro,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,r,n,o=!0){super(e,w.Zero(),n,o),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=w.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=N.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new B,this.panningAxis=new w(1,1,0),this._transformedDirection=new w,this.mapPanning=!1,this.onMeshTargetChangedObservable=new g,this.checkCollisions=!1,this.collisionRadius=new w(.5,.5,.5),this._previousPosition=w.Zero(),this._collisionVelocity=w.Zero(),this._newPosition=w.Zero(),this._computationVector=w.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);const s=Math.cos(this.alpha),r=Math.sin(this.alpha),n=Math.cos(this.beta);let o=Math.sin(this.beta);0===o&&(o=1e-4);const a=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*s*o,this.radius*n,this.radius*r*o),a.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=l.clone(),l=l.negate()),this._computeViewMatrix(this._position,a,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=w.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new Za(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=N.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){const e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}return this._getLockedTargetPosition()||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)}_isSynchronizedViewMatrix(){return!!super._isSynchronizedViewMatrix()&&this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset)}attachControl(e,t,i=!0,s=2){const r=arguments;t=Ii.BackCompatCameraNoPreventDefault(r),this._useCtrlForPanning=i,this._panningMouseButton=s,"boolean"==typeof r[0]&&(r.length>1&&(this._useCtrlForPanning=r[1]),r.length>2&&(this._panningMouseButton=r[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){const e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier();let i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||w.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);const e=this.alpha;0===this._computationVector.x&&0===this._computationVector.z?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,s=!1){if(s=this.overrideCloneAlphaBetaRadius??s,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const t=e,s=this._getTargetPosition();if(s&&!i&&s.equals(t))return;this._targetHost=null,this._target=t,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}s||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let s=Math.sin(this.beta);0===s&&(s=1e-4),0===this.radius&&(this.radius=1e-4);const r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*s,this.radius*i,this.radius*t*s),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||w.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),r.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&s<0&&(e=e.negate()),this._computeViewMatrix(this._position,r,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=Un.MinMax(e);let s=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);s=Math.max(Math.min(s,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=s*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:s},t)}focusOn(e,t=!1){let i,s;if(void 0===e.min){const t=e||this.getScene().meshes;i=Un.MinMax(t),s=w.Distance(i.min,i.max)}else i=e,s=e.distance;this._target=Un.Center(i),t||(this.maxZ=2*s)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case or.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case or.RIG_MODE_STEREOSCOPIC_OVERUNDER:case or.RIG_MODE_STEREOSCOPIC_INTERLACED:case or.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const s=new gl(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return s._cameraRigParams={},s.isRigCamera=!0,s.rigParent=this,s.upVector=this.upVector,s.mode=this.mode,s.orthoLeft=this.orthoLeft,s.orthoRight=this.orthoRight,s.orthoBottom=this.orthoBottom,s.orthoTop=this.orthoTop,s}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case or.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case or.RIG_MODE_STEREOSCOPIC_OVERUNDER:case or.RIG_MODE_STEREOSCOPIC_INTERLACED:case or.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const s=w.Distance(e,t),r=this.getScene().getEngine().getAspectRatio(this),n=Math.tan(this.fov/2),o=n*r,a=.5*s*i,l=a*Math.sqrt(1+1/(o*o)),h=a*Math.sqrt(1+1/(n*n));return Math.max(l,h)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}ae([pe()],gl.prototype,"alpha",void 0),ae([pe()],gl.prototype,"beta",void 0),ae([pe()],gl.prototype,"radius",void 0),ae([pe()],gl.prototype,"overrideCloneAlphaBetaRadius",void 0),ae([ve("target")],gl.prototype,"_target",void 0),ae([xe("targetHost")],gl.prototype,"_targetHost",void 0),ae([pe()],gl.prototype,"inertialAlphaOffset",void 0),ae([pe()],gl.prototype,"inertialBetaOffset",void 0),ae([pe()],gl.prototype,"inertialRadiusOffset",void 0),ae([pe()],gl.prototype,"lowerAlphaLimit",void 0),ae([pe()],gl.prototype,"upperAlphaLimit",void 0),ae([pe()],gl.prototype,"lowerBetaLimit",void 0),ae([pe()],gl.prototype,"upperBetaLimit",void 0),ae([pe()],gl.prototype,"lowerRadiusLimit",void 0),ae([pe()],gl.prototype,"upperRadiusLimit",void 0),ae([pe()],gl.prototype,"inertialPanningX",void 0),ae([pe()],gl.prototype,"inertialPanningY",void 0),ae([pe()],gl.prototype,"pinchToPanMaxDistance",void 0),ae([pe()],gl.prototype,"panningDistanceLimit",void 0),ae([ve()],gl.prototype,"panningOriginTarget",void 0),ae([pe()],gl.prototype,"panningInertia",void 0),ae([pe()],gl.prototype,"zoomToMouseLocation",null),ae([pe()],gl.prototype,"zoomOnFactor",void 0),ae([ge()],gl.prototype,"targetScreenOffset",void 0),ae([pe()],gl.prototype,"allowUpsideDown",void 0),ae([pe()],gl.prototype,"useInputToRestoreState",void 0),u("BABYLON.ArcRotateCamera",gl),De.AddNodeConstructor("DeviceOrientationCamera",((e,t)=>()=>new vl(e,w.Zero(),t)));class vl extends _l{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new L,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new L,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce((()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add((e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new L),L.FromEulerAnglesToRef(0,e.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))})))}))}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=Gs.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new L),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}}class xl extends Xa{constructor(e){super(e)}addKeyboard(){return this.add(new el),this}addMouse(){return this.add(new tl),this}}class Tl extends fl{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){const e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){const t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){const e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){const t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,s=!0){super(e,t,i,s),this.ellipsoid=new w(1,1,1),this.ellipsoidOffset=new w(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=w.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=w.Zero(),this._diffPosition=w.Zero(),this._newPosition=w.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>Br.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new xl(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ii.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new w(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?w.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=w.Zero(),this._transformedDirection=w.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}restoreRoll(e){const t=this._trackRoll,i=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,Math.abs(t-this.rotation.z)<=.001&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}ae([ve()],Tl.prototype,"ellipsoid",void 0),ae([ve()],Tl.prototype,"ellipsoidOffset",void 0),ae([pe()],Tl.prototype,"checkCollisions",void 0),ae([pe()],Tl.prototype,"applyGravity",void 0),u("BABYLON.FlyCamera",Tl);class Sl extends Xa{constructor(e){super(e)}addKeyboard(){return this.add(new il),this}addMouseWheel(){return this.add(new sl),this}addPointers(){return this.add(new rl),this}addVRDeviceOrientation(){return J.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}De.AddNodeConstructor("FollowCamera",((e,t)=>()=>new El(e,w.Zero(),t))),De.AddNodeConstructor("ArcFollowCamera",((e,t)=>()=>new bl(e,0,0,1,null,t)));class El extends fl{constructor(e,t,i,s=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=s,this.inputs=new Sl(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=U.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),s=Ii.ToRadians(this.rotationOffset)+i,r=e.getAbsolutePosition(),n=r.x+Math.sin(s)*this.radius,o=r.z+Math.cos(s)*this.radius,a=n-this.position.x,l=r.y+this.heightOffset-this.position.y,h=o-this.position.z;let c=a*this.cameraAcceleration*2,u=l*this.cameraAcceleration,d=h*this.cameraAcceleration*2;(c>this.maxCameraSpeed||c<-this.maxCameraSpeed)&&(c=c<1?-this.maxCameraSpeed:this.maxCameraSpeed),(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new w(this.position.x+c,this.position.y+u,this.position.z+d),this.setTarget(r)}attachControl(e,t){t=Ii.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=()=>{}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){this.inputs.checkInputs(),this._checkLimits(),super._checkInputs(),this.lockedTarget&&this._follow(this.lockedTarget)}_checkLimits(){null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}ae([pe()],El.prototype,"radius",void 0),ae([pe()],El.prototype,"lowerRadiusLimit",void 0),ae([pe()],El.prototype,"upperRadiusLimit",void 0),ae([pe()],El.prototype,"rotationOffset",void 0),ae([pe()],El.prototype,"lowerRotationOffsetLimit",void 0),ae([pe()],El.prototype,"upperRotationOffsetLimit",void 0),ae([pe()],El.prototype,"heightOffset",void 0),ae([pe()],El.prototype,"lowerHeightOffsetLimit",void 0),ae([pe()],El.prototype,"upperHeightOffsetLimit",void 0),ae([pe()],El.prototype,"cameraAcceleration",void 0),ae([pe()],El.prototype,"maxCameraSpeed",void 0),ae([xe("lockedTargetId")],El.prototype,"lockedTarget",void 0);class bl extends fl{constructor(e,t,i,s,r,n){super(e,w.Zero(),n),this.alpha=t,this.beta=i,this.radius=s,this._cartesianCoordinates=w.Zero(),this.setMeshTarget(r)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);const e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}u("BABYLON.FollowCamera",El),u("BABYLON.ArcFollowCamera",bl),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(ka||(ka={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Ga||(Ga={}));class Cl extends Ya{constructor(e,t,i,s=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new g,this.onButtonUpObservable=new g,this.onPadDownObservable=new g,this.onPadUpObservable=new g,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this.type=Ya.XBOX,this._isXboxOnePad=s}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,ka.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,ka.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,ka.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,ka.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,ka.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,ka.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,ka.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,ka.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,ka.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,ka.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Ga.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Ga.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Ga.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Ga.Right)}update(){super.update(),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}!function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(za||(za={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Wa||(Wa={}));class yl extends Ya{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new g,this.onButtonUpObservable=new g,this.onPadDownObservable=new g,this.onPadUpObservable=new g,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=Ya.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,za.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,za.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,za.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,za.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,za.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,za.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,za.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,za.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,za.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,za.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Wa.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Wa.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Wa.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Wa.Right)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class Al{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new g,We()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new g((e=>{for(const t in this._babylonGamepads){const i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}})),this._onGamepadConnectedEvent=e=>{const t=e.gamepad;if(t.index in this._babylonGamepads&&this._babylonGamepads[t.index].isConnected)return;let i;this._babylonGamepads[t.index]?(i=this._babylonGamepads[t.index],i.browserGamepad=t,i._isConnected=!0):i=this._addNewGamepad(t),this.onGamepadConnectedObservable.notifyObservers(i),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=e=>{const t=e.gamepad;for(const e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){const t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){const e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}get gamepads(){return this._babylonGamepads}getGamepadByType(e=Ya.XBOX){for(const t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach((e=>{e.dispose()})),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);const i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),s=-1!==e.id.search("Xbox One");return t=s||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new Cl(e.id,e.index,e,s):i?new yl(e.id,e.index,e):new ja(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){this._updateGamepadObjects();for(const e in this._babylonGamepads){const t=this._babylonGamepads[e];if(t&&t.isConnected)try{t.update()}catch{-1===this._loggedErrors.indexOf(t.index)&&(Ii.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&Br.QueueNewFrame((()=>{this._checkGamepadsStatus()}))}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new Il(e,w.Zero(),t)));class Il extends ml{get gamepadAngularSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}}or._CreateDefaultParsedCamera=(e,t)=>new Il(e,w.Zero(),t),De.AddNodeConstructor("GamepadCamera",((e,t)=>()=>new Pl(e,w.Zero(),t)));class Pl extends Il{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}Ft.ShadersStore.passCubePixelShader="varying vec2 vUV;uniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";class Ml extends Ko{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,r,n,o=0,a=!1){super(e,"pass",null,null,t,i,s,r,n,void 0,o,void 0,null,a)}static _Parse(e,t,i,s){return Pe.Parse((()=>new Ml(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,s)}}u("BABYLON.PassPostProcess",Ml),si._RescalePostProcessFactory=e=>new Ml("rescale",1,null,2,e,!1,0);Ft.ShadersStore.anaglyphPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}";class Dl extends Ko{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,s,r,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],s,r,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)}))}}function Ol(e){e._rigCameras[0]._rigPostProcess=new Ml(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new Dl(e.name+"_anaglyph",1,e._rigCameras)}u("BABYLON.AnaglyphPostProcess",Dl),De.AddNodeConstructor("AnaglyphArcRotateCamera",((e,t,i)=>()=>new Nl(e,0,0,1,w.Zero(),i.interaxial_distance,t)));class Nl extends gl{constructor(e,t,i,s,r,n,o){super(e,t,i,s,r,o),this._setRigMode=()=>Ol(this),this.interaxialDistance=n,this.setCameraRigMode(or.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}De.AddNodeConstructor("AnaglyphFreeCamera",((e,t,i)=>()=>new wl(e,w.Zero(),i.interaxial_distance,t)));class wl extends _l{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Ol(this),this.interaxialDistance=i,this.setCameraRigMode(or.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}De.AddNodeConstructor("AnaglyphGamepadCamera",((e,t,i)=>()=>new Fl(e,w.Zero(),i.interaxial_distance,t)));class Fl extends Pl{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Ol(this),this.interaxialDistance=i,this.setCameraRigMode(or.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}De.AddNodeConstructor("AnaglyphUniversalCamera",((e,t,i)=>()=>new Ll(e,w.Zero(),i.interaxial_distance,t)));class Ll extends Il{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Ol(this),this.interaxialDistance=i,this.setCameraRigMode(or.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}Ft.ShadersStore.stereoscopicInterlacePixelShader="const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\n#ifdef IS_STEREOSCOPIC_INTERLACED\nfloat rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n#endif\nif (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);}\n";class Bl extends Ko{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,s,r,n,o){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],r,n,o,s?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new N(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new N(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}function Vl(e){const t=e.cameraRigMode===or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;e.cameraRigMode===or.RIG_MODE_STEREOSCOPIC_INTERLACED?(e._rigCameras[0]._rigPostProcess=new Ml(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new Bl(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new nr(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new nr(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}De.AddNodeConstructor("StereoscopicArcRotateCamera",((e,t,i)=>()=>new Ul(e,0,0,1,w.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Ul extends gl{constructor(e,t,i,s,r,n,o,a){super(e,t,i,s,r,a),this._setRigMode=()=>Vl(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:or.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}De.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new kl(e,w.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class kl extends _l{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Vl(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:or.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}De.AddNodeConstructor("StereoscopicGamepadCamera",((e,t,i)=>()=>new Gl(e,w.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Gl extends Pl{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Vl(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:or.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}De.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new zl(e,w.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class zl extends Il{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Vl(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:or.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}De.AddNodeConstructor("VirtualJoysticksCamera",((e,t)=>()=>new Wl(e,w.Zero(),t)));class Wl extends _l{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class Hl{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return B.Translation(e,0,0)}get rightHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return B.Translation(-e,0,0)}get leftPreViewMatrix(){return B.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return B.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new Hl;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}Ft.ShadersStore.vrDistortionCorrectionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}";class Xl extends Ko{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,s){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,s.postProcessScaleFactor,t,Zn.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=s.distortionK,this._postProcessScaleFactor=s.postProcessScaleFactor,this._lensCenterOffset=s.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add((()=>{this._scaleIn=new N(2,2/this.aspectRatio),this._scaleFactor=new N(1/this._postProcessScaleFactor*.5,1/this._postProcessScaleFactor*.5*this.aspectRatio),this._lensCenter=new N(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)})),this.onApplyObservable.add((e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])}))}}Ft.ShadersStore.vrMultiviewToSingleviewPixelShader="precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}";class Yl extends da{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}}function jl(e,t){const i=new ji(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}Br.prototype.createMultiviewRenderTargetTexture=function(e,t,i,s){const r=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const n=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});n._framebuffer=r.createFramebuffer();const o=new ti(this,ei.Unknown,!0);return o.width=e,o.height=t,o.isMultiview=!0,i||(i=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,i),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.RGBA8,e,t,2)),n._colorTextureArray=i,s||(s=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,s),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.DEPTH24_STENCIL8,e,t,2)),n._depthStencilTextureArray=s,o.isReady=!0,n.setTextures(o),n._depthStencilTexture=o,n},Br.prototype.bindMultiviewFramebuffer=function(e){const t=e,i=this._gl,s=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw"Invalid multiview frame buffer";this.getCaps().oculusMultiview?(s.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,t.samples,0,2),s.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,t.samples,0,2)):(s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,0,2))},Br.prototype.bindSpaceWarpFramebuffer=function(e){const t=e,i=this._gl,s=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw new Error("Invalid Space Warp framebuffer");s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_ATTACHMENT,t._depthStencilTextureArray,0,0,2)},or.prototype._useMultiviewToSingleView=!1,or.prototype._multiviewTexture=null,or.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==e&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new Yl(this.getScene(),{width:e,height:t})):this._multiviewTexture=new Yl(this.getScene(),{width:e,height:t})};const $l=ks.prototype.createSceneUniformBuffer;ks.prototype._transformMatrixR=B.Zero(),ks.prototype._multiviewSceneUbo=null,ks.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=jl(this.getEngine(),"scene_multiview")},ks.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?jl(this.getEngine(),e):$l.bind(this)(e)},ks.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,U.Matrix[0]),Ms.GetRightPlaneToRef(U.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))},ks.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t{})),this.onApplyObservable.add((e=>{s._scene.activeCamera&&s._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",s._multiviewTexture)}))}}function ql(e,t){const i=t.vrCameraMetrics||Hl.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new nr(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new B,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new nr(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new B,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new Kl("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(J.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new Xl("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new Xl("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}De.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",((e,t)=>()=>new Ql(e,0,0,1,w.Zero(),t)));class Ql extends gl{constructor(e,t,i,s,r,n,o=!0,a=Hl.GetDefault()){super(e,t,i,s,r,n),this._setRigMode=e=>ql(this,e),a.compensateDistortion=o,this.setCameraRigMode(or.RIG_MODE_VR,{vrCameraMetrics:a}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}De.AddNodeConstructor("VRDeviceOrientationFreeCamera",((e,t)=>()=>new Zl(e,w.Zero(),t)));class Zl extends vl{constructor(e,t,i,s=!0,r=Hl.GetDefault()){super(e,t,i),this._setRigMode=e=>ql(this,e),r.compensateDistortion=s,this.setCameraRigMode(or.RIG_MODE_VR,{vrCameraMetrics:r})}getClassName(){return"VRDeviceOrientationFreeCamera"}}De.AddNodeConstructor("VRDeviceOrientationGamepadCamera",((e,t)=>()=>new Jl(e,w.Zero(),t)));class Jl extends Zl{constructor(e,t,i,s=!0,r=Hl.GetDefault()){super(e,t,i,s,r),this._setRigMode=e=>ql(this,e),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}class eh{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,s,r){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(2)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=s.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const r=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==r.frameId&&(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=s.clone()}}}class th{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,Br.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._TranslucencyIntensityTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get TranslucencyColorTextureEnabled(){return this._TranslucencyColorTextureEnabled}static set TranslucencyColorTextureEnabled(e){this._TranslucencyColorTextureEnabled!==e&&(this._TranslucencyColorTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}}th._DiffuseTextureEnabled=!0,th._DetailTextureEnabled=!0,th._DecalMapEnabled=!0,th._AmbientTextureEnabled=!0,th._OpacityTextureEnabled=!0,th._ReflectionTextureEnabled=!0,th._EmissiveTextureEnabled=!0,th._SpecularTextureEnabled=!0,th._BumpTextureEnabled=!0,th._LightmapTextureEnabled=!0,th._RefractionTextureEnabled=!0,th._ColorGradingTextureEnabled=!0,th._FresnelEnabled=!0,th._ClearCoatTextureEnabled=!0,th._ClearCoatBumpTextureEnabled=!0,th._ClearCoatTintTextureEnabled=!0,th._SheenTextureEnabled=!0,th._AnisotropicTextureEnabled=!0,th._ThicknessTextureEnabled=!0,th._RefractionIntensityTextureEnabled=!0,th._TranslucencyIntensityTextureEnabled=!0,th._TranslucencyColorTextureEnabled=!0,th._IridescenceTextureEnabled=!0;Ft.IncludesShadersStore.decalFragmentDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;\n#endif\n";Ft.IncludesShadersStore.defaultFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;uniform vec4 refractionRightColor;\n#endif\n#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)\nuniform mat4 reflectionMatrix;\n#endif\n#ifndef REFLECTIONMAP_SKYBOX\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";Ft.IncludesShadersStore.sceneUboDeclaration="layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \nmat4 view;mat4 projection;vec4 vEyePosition;};\n";Ft.IncludesShadersStore.meshUboDeclaration="#ifdef WEBGL2\nuniform mat4 world;uniform float visibility;\n#else\nlayout(std140,column_major) uniform;uniform Mesh\n{mat4 world;float visibility;};\n#endif\n#define WORLD_UBO\n";Ft.IncludesShadersStore.defaultUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";Ft.IncludesShadersStore.prePassDeclaration="#ifdef PREPASS\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor;\n#ifdef PREPASS_DEPTH\nvarying highp vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nvarying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;\n#endif\n#endif\n";Ft.IncludesShadersStore.oitDeclaration="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out vec2 depth; \nlayout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor;\n#define MAX_DEPTH 99999.0\nhighp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler;\n#endif\n";Ft.IncludesShadersStore.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vec2 vMainUV{X};\n#endif\n";Ft.IncludesShadersStore.helperFunctions="const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; \nconst float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\n#define absEps(x) abs(x)+Epsilon\n#define maxEps(x) max(x,Epsilon)\n#define saturateEps(x) clamp(x,Epsilon,1.0)\nmat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nmat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;}\n#if USE_EXACT_SRGB_CONVERSIONS\nvec3 toLinearSpaceExact(vec3 color)\n{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));\n#else\nreturn\nvec3(\ncolor.r<=0.04045 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.04045 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.04045 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\nvec3 toGammaSpaceExact(vec3 color)\n{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));\n#else\nreturn\nvec3(\ncolor.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\n#endif\nfloat toLinearSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,LinearEncodePowerApprox);\n#endif\n}\nvec3 toLinearSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nvec4 toLinearSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfloat toGammaSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,GammaEncodePowerApprox);\n#endif\n}\nvec3 toGammaSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nvec4 toGammaSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfloat square(float value)\n{return value*value;}\nvec3 square(vec3 value)\n{return value*value;}\nfloat pow5(float value) {float sq=value*value;return sq*sq*value;}\nfloat getLuminance(vec3 color)\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfloat getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfloat dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;}\nconst float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); }\nvec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;}\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";Ft.IncludesShadersStore.lightFragmentDeclaration="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};\n#else\nuniform highp sampler2DArray shadowTexture{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowTexture{X};\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowTexture{X};\n#else\nuniform sampler2D shadowTexture{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};\n#endif\n#endif\n";Ft.IncludesShadersStore.lightUboDeclaration="#ifdef LIGHT{X}\nuniform Light{X}\n{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;vec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;vec2 depthValues;} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};\n#else\nuniform highp sampler2DArray shadowTexture{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowTexture{X}; \n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowTexture{X};\n#else\nuniform sampler2D shadowTexture{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";Ft.IncludesShadersStore.lightsFragmentFunctions="struct lightingInfo\n{vec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.)\n{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}";Ft.IncludesShadersStore.shadowsFragmentFunctions="#ifdef SHADOWS\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}\n#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\n#define inline\nfloat computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nreturn depth>shadow ? darkness : 1.0;}\n#define inline\nfloat computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}\n#endif\n#define inline\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}}\n#define inline\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#ifdef IS_NDC_HALF_ZRANGE\n#define ZINCLIP clipSpace.z\n#else\n#define ZINCLIP uvDepth.z\n#endif\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define GREATEST_LESS_THAN_ONE 0.99999994\n#define DISABLE_UNIFORMITY_ANALYSIS\n#define inline\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.)\n);const vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n#define inline\nfloat computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; ithis._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort(((e,t)=>e.priority-t.priority)),this._codeInjectionPoints={};const i={};i[sh._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const e of this._plugins)e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t0&&e.uniforms.push(...this._uniformList),this._samplerList.length>0&&e.samplers.push(...this._samplerList),this._uboList.length>0&&e.uniformBuffersNames.push(...this._uboList),e.customCode=this._injectCustomCode(e,e.customCode);break}case Xr.PrepareUniformBuffer:{const e=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const t of this._plugins){const i=t.getUniforms();if(i){if(i.ubo)for(const t of i.ubo){if(t.size&&t.type){const i=t.arraySize??0;e.ubo.addUniform(t.name,t.size,i),this._uboDeclaration+=`${t.type} ${t.name}${i>0?`[${i}]`:""};\n`}this._uniformList.push(t.name)}i.vertex&&(this._vertexDeclaration+=i.vertex+"\n"),i.fragment&&(this._fragmentDeclaration+=i.fragment+"\n")}t.getSamplers(this._samplerList),t.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,s)=>{t&&(s=t(i,s)),this._uboDeclaration&&(s=s.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(s=s.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(s=s.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const r=this._codeInjectionPoints?.[i];if(!r)return s;let n=null;for(let t in r){let r="";for(const s of this._activePlugins){let o=s.getCustomCode(i)?.[t];if(o){if(s.resolveIncludes){if(null===n){const t=ht.GLSL;n={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Ft.GetShadersRepository(t),includesShadersStore:Ft.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}n.isFragment="fragment"===i,Ot(o,n,(e=>o=e))}r+=o+"\n"}}if(r.length>0)if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{const i=ih.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}e.indexOf("g")<0&&(e+="g");const i=s,n=new RegExp(t,e);let o=n.exec(i);for(;null!==o;){let e=r;for(let t=0;t{rh.length=0,nh=!1,Dn.OnEventObservable.remove(oh),oh=null}));const rh=[];let nh=!1,oh=null;class ah{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,s,r=!0,n=!1,o=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=o,e.pluginManager||(e.pluginManager=new sh(e),e.onDisposeObservable.add((()=>{e.pluginManager=void 0}))),this._pluginDefineNames=s,this._pluginManager=e.pluginManager,r&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,s){return!0}hardBindForSubMesh(e,t,i,s){}bindForSubMesh(e,t,i,s){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;const i=typeof this._pluginDefineNames[t];e[t]={type:"number"===i?"number":"string"===i?"string":"boolean"===i?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(){return{}}copyTo(e){Pe.Clone((()=>e),this)}serialize(){return Pe.Serialize(this)}parse(e,t,i){Pe.Parse((()=>this),e,t,i)}}ae([pe()],ah.prototype,"name",void 0),ae([pe()],ah.prototype,"priority",void 0),ae([pe()],ah.prototype,"resolveIncludes",void 0),ae([pe()],ah.prototype,"registerForExtraEvents",void 0),u("BABYLON.MaterialPluginBase",ah);class lh extends Do{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class hh extends ah{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new lh,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Dn.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&th.DetailTextureEnabled&&!this._texture.isReady())}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&th.DetailTextureEnabled&&this._isEnabled?(an(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||this._texture&&th.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),ln(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&th.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture?.dispose()}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}ae([fe("detailTexture"),de("_markAllSubMeshesAsTexturesDirty")],hh.prototype,"texture",void 0),ae([pe()],hh.prototype,"diffuseBlendLevel",void 0),ae([pe()],hh.prototype,"roughnessBlendLevel",void 0),ae([pe()],hh.prototype,"bumpLevel",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],hh.prototype,"normalBlendMethod",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],hh.prototype,"isEnabled",void 0);const ch={effect:null,subMesh:null};class uh extends Do{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){const t=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];for(const i of t)this[i]=i===e}}class dh extends Io{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new Y(0,0,0),this.diffuseColor=new Y(1,1,1),this.specularColor=new Y(1,1,1),this.emissiveColor=new Y(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._renderTargets=new Mi(16),this._worldViewProjectionMatrix=B.Zero(),this._globalAmbientColor=new Y(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new hh(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new eh,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),dh.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),dh.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return!!(dh.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||!!(dh.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Dn.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Dn.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Xr.GetDefineNames,this._eventInfo),t.materialDefines=new uh(this._eventInfo.defineNames));const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();n._needNormals=vn(r,e,n,!0,this._maxSimultaneousLights,this._disableLighting),yn(r,n);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Rn(r,n,this.canRenderToMRT&&!a),An(r,n,a),n._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n._needUVs=!1;for(let e=1;e<=6;++e)n["MAINUV"+e]=!1;if(r.texturesEnabled){if(n.DIFFUSEDIRECTUV=0,n.BUMPDIRECTUV=0,n.AMBIENTDIRECTUV=0,n.OPACITYDIRECTUV=0,n.EMISSIVEDIRECTUV=0,n.SPECULARDIRECTUV=0,n.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&dh.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;an(this._diffuseTexture,n,"DIFFUSE")}else n.DIFFUSE=!1;if(this._ambientTexture&&dh.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;an(this._ambientTexture,n,"AMBIENT")}else n.AMBIENT=!1;if(this._opacityTexture&&dh.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;an(this._opacityTexture,n,"OPACITY"),n.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else n.OPACITY=!1;if(this._reflectionTexture&&dh.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(n._needNormals=!0,n.REFLECTION=!0,n.ROUGHNESS=this._roughness>0,n.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,n.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===Zn.INVCUBIC_MODE,n.REFLECTIONMAP_3D=this._reflectionTexture.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,n.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case Zn.EXPLICIT_MODE:n.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case Zn.PLANAR_MODE:n.setReflectionMode("REFLECTIONMAP_PLANAR");break;case Zn.PROJECTION_MODE:n.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case Zn.SKYBOX_MODE:n.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case Zn.SPHERICAL_MODE:n.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case Zn.EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case Zn.FIXED_EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case Zn.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case Zn.CUBIC_MODE:case Zn.INVCUBIC_MODE:default:n.setReflectionMode("REFLECTIONMAP_CUBIC")}n.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else n.REFLECTION=!1,n.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&dh.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;an(this._emissiveTexture,n,"EMISSIVE")}else n.EMISSIVE=!1;if(this._lightmapTexture&&dh.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;an(this._lightmapTexture,n,"LIGHTMAP"),n.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,n.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else n.LIGHTMAP=!1;if(this._specularTexture&&dh.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;an(this._specularTexture,n,"SPECULAR"),n.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else n.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&dh.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;an(this._bumpTexture,n,"BUMP"),n.PARALLAX=this._useParallax,n.PARALLAX_RHS=r.useRightHandedSystem,n.PARALLAXOCCLUSION=this._useParallaxOcclusion,n.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else n.BUMP=!1,n.PARALLAX=!1,n.PARALLAX_RHS=!1,n.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&dh.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;n._needUVs=!0,n.REFRACTION=!0,n.REFRACTIONMAP_3D=this._refractionTexture.isCube,n.RGBDREFRACTION=this._refractionTexture.isRGBD,n.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else n.REFRACTION=!1;n.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else n.DIFFUSE=!1,n.AMBIENT=!1,n.OPACITY=!1,n.REFLECTION=!1,n.EMISSIVE=!1,n.LIGHTMAP=!1,n.BUMP=!1,n.REFRACTION=!1;n.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),n.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,n.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,n.SPECULAROVERALPHA=this._useSpecularOverAlpha,n.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,n.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,n.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n),n.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,n.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}n._areFresnelDirty&&(dh.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(n.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,n.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,n.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,n.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,n.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,n.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,n._needNormals=!0,n.FRESNEL=!0):n.FRESNEL=!1),gn(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,n,this._applyDecalMapAfterDetailMap),Tn(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=n,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),Cn(e,n,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let l=!1;if(n.isDirty){const i=n._areLightsDisposed;n.markAsProcessed();const s=new Yo;n.REFLECTION&&s.addFallback(0,"REFLECTION"),n.SPECULAR&&s.addFallback(0,"SPECULAR"),n.BUMP&&s.addFallback(0,"BUMP"),n.PARALLAX&&s.addFallback(1,"PARALLAX"),n.PARALLAX_RHS&&s.addFallback(1,"PARALLAX_RHS"),n.PARALLAXOCCLUSION&&s.addFallback(0,"PARALLAXOCCLUSION"),n.SPECULAROVERALPHA&&s.addFallback(0,"SPECULAROVERALPHA"),n.FOG&&s.addFallback(1,"FOG"),n.POINTSIZE&&s.addFallback(0,"POINTSIZE"),n.LOGARITHMICDEPTH&&s.addFallback(0,"LOGARITHMICDEPTH"),_n(n,s,this._maxSimultaneousLights),n.SPECULARTERM&&s.addFallback(0,"SPECULARTERM"),n.DIFFUSEFRESNEL&&s.addFallback(1,"DIFFUSEFRESNEL"),n.OPACITYFRESNEL&&s.addFallback(2,"OPACITYFRESNEL"),n.REFLECTIONFRESNEL&&s.addFallback(3,"REFLECTIONFRESNEL"),n.EMISSIVEFRESNEL&&s.addFallback(4,"EMISSIVEFRESNEL"),n.FRESNEL&&s.addFallback(4,"FRESNEL"),n.MULTIVIEW&&s.addFallback(0,"MULTIVIEW");const a=[Ki.PositionKind];n.NORMAL&&a.push(Ki.NormalKind),n.TANGENT&&a.push(Ki.TangentKind);for(let e=1;e<=6;++e)n["UV"+e]&&a.push(`uv${1===e?"":e}`);n.VERTEXCOLOR&&a.push(Ki.ColorKind),pn(a,e,n,s),fn(a,n),sn(a,e,n),hn(a,0,n);let h="default";const c=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],u=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],d=["Material","Scene","Mesh"],p={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=s,this._eventInfo.fallbackRank=0,this._eventInfo.defines=n,this._eventInfo.uniforms=c,this._eventInfo.attributes=a,this._eventInfo.samplers=u,this._eventInfo.uniformBuffersNames=d,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=p,this._callbackPluginEventGeneric(Xr.PrepareEffect,this._eventInfo),eh.AddUniforms(c),eh.AddSamplers(u),Bi&&(Bi.PrepareUniforms(c,n),Bi.PrepareSamplers(u,n)),Mn({uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:n,maxSimultaneousLights:this._maxSimultaneousLights}),jr(c);const f={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,c,d,u,n,a,f));const _=n.toString(),m=t.effect;let g=r.getEngine().createEffect(h,{attributes:a,uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:_,fallbacks:s,onCompiled:this.onCompiled,onError:this.onError,indexParameters:p,processFinalCode:f.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:n.PREPASS},o);if(this._eventInfo.customCode=void 0,g)if(this._onEffectCreatedObservable&&(ch.effect=g,ch.subMesh=t,this._onEffectCreatedObservable.notifyObservers(ch)),this.allowShaderHotSwapping&&m&&!g.isReady()){if(g=m,n.markAsUnprocessed(),l=this.isFrozen,i)return n._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(g,n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!l,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(s,n,i,t.visibility);cn(t,n);const a=this._uniformBuffer;if(o){if(this.bindViewProjection(n),!a.useUbo||!this.isFrozen||!a.isSync||i._drawWrapper._forceRebindOnNextCall){if(dh.FresnelEnabled&&r.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(a.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),a.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&a.updateColor4("opacityParts",new Y(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(a.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),a.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(a.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),a.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(a.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),a.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&dh.DiffuseTextureEnabled&&(a.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),ln(this._diffuseTexture,a,"diffuse")),this._ambientTexture&&dh.AmbientTextureEnabled&&(a.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),ln(this._ambientTexture,a,"ambient")),this._opacityTexture&&dh.OpacityTextureEnabled&&(a.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),ln(this._opacityTexture,a,"opacity")),this._hasAlphaChannel()&&a.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&dh.ReflectionTextureEnabled&&(a.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),a.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const e=this._reflectionTexture;a.updateVector3("vReflectionPosition",e.boundingBoxPosition),a.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&dh.EmissiveTextureEnabled&&(a.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),ln(this._emissiveTexture,a,"emissive")),this._lightmapTexture&&dh.LightmapTextureEnabled&&(a.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),ln(this._lightmapTexture,a,"lightmap")),this._specularTexture&&dh.SpecularTextureEnabled&&(a.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),ln(this._specularTexture,a,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&dh.BumpTextureEnabled&&(a.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),ln(this._bumpTexture,a,"bump"),s._mirroredCameraPosition?a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&dh.RefractionTextureEnabled){let e=1;if(this._refractionTexture.isCube||(a.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),a.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const e=this._refractionTexture;a.updateVector3("vRefractionPosition",e.boundingBoxPosition),a.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&a.updateFloat("pointSize",this.pointSize),r.SPECULARTERM&&a.updateColor4("vSpecularColor",this.specularColor,this.specularPower),a.updateColor3("vEmissiveColor",dh.EmissiveTextureEnabled?this.emissiveColor:Y.BlackReadOnly),a.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),a.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&dh.DiffuseTextureEnabled&&n.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&dh.AmbientTextureEnabled&&n.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&dh.OpacityTextureEnabled&&n.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&dh.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?n.setTexture("reflectionCubeSampler",this._reflectionTexture):n.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&dh.EmissiveTextureEnabled&&n.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&dh.LightmapTextureEnabled&&n.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&dh.SpecularTextureEnabled&&n.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&dh.BumpTextureEnabled&&n.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&dh.RefractionTextureEnabled&&(this._refractionTexture.isCube?n.setTexture("refractionCubeSampler",this._refractionTexture):n.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Kr(n,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!o&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&dn(s,t,n,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==ks.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),en(s,t,n),r.NUM_MORPH_INFLUENCERS&&nn(t,n),r.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,r.INSTANCES),this.useLogarithmicDepth&&Jr(r,n,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),a.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e}dispose(e,t){t&&(this._diffuseTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._specularTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._refractionTexture?.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=Pe.Clone((()=>new dh(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return s.name=e,s.id=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}static Parse(e,t,i){const s=Pe.Parse((()=>new dh(e.name,t)),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),Dn._ParsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return th.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){th.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return th.DetailTextureEnabled}static set DetailTextureEnabled(e){th.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return th.AmbientTextureEnabled}static set AmbientTextureEnabled(e){th.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return th.OpacityTextureEnabled}static set OpacityTextureEnabled(e){th.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return th.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){th.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return th.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){th.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return th.SpecularTextureEnabled}static set SpecularTextureEnabled(e){th.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return th.BumpTextureEnabled}static set BumpTextureEnabled(e){th.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return th.LightmapTextureEnabled}static set LightmapTextureEnabled(e){th.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return th.RefractionTextureEnabled}static set RefractionTextureEnabled(e){th.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return th.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){th.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return th.FresnelEnabled}static set FresnelEnabled(e){th.FresnelEnabled=e}}ae([fe("diffuseTexture")],dh.prototype,"_diffuseTexture",void 0),ae([de("_markAllSubMeshesAsTexturesAndMiscDirty")],dh.prototype,"diffuseTexture",void 0),ae([fe("ambientTexture")],dh.prototype,"_ambientTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"ambientTexture",void 0),ae([fe("opacityTexture")],dh.prototype,"_opacityTexture",void 0),ae([de("_markAllSubMeshesAsTexturesAndMiscDirty")],dh.prototype,"opacityTexture",void 0),ae([fe("reflectionTexture")],dh.prototype,"_reflectionTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"reflectionTexture",void 0),ae([fe("emissiveTexture")],dh.prototype,"_emissiveTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"emissiveTexture",void 0),ae([fe("specularTexture")],dh.prototype,"_specularTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"specularTexture",void 0),ae([fe("bumpTexture")],dh.prototype,"_bumpTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"bumpTexture",void 0),ae([fe("lightmapTexture")],dh.prototype,"_lightmapTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"lightmapTexture",void 0),ae([fe("refractionTexture")],dh.prototype,"_refractionTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"refractionTexture",void 0),ae([_e("ambient")],dh.prototype,"ambientColor",void 0),ae([_e("diffuse")],dh.prototype,"diffuseColor",void 0),ae([_e("specular")],dh.prototype,"specularColor",void 0),ae([_e("emissive")],dh.prototype,"emissiveColor",void 0),ae([pe()],dh.prototype,"specularPower",void 0),ae([pe("useAlphaFromDiffuseTexture")],dh.prototype,"_useAlphaFromDiffuseTexture",void 0),ae([de("_markAllSubMeshesAsTexturesAndMiscDirty")],dh.prototype,"useAlphaFromDiffuseTexture",void 0),ae([pe("useEmissiveAsIllumination")],dh.prototype,"_useEmissiveAsIllumination",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useEmissiveAsIllumination",void 0),ae([pe("linkEmissiveWithDiffuse")],dh.prototype,"_linkEmissiveWithDiffuse",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"linkEmissiveWithDiffuse",void 0),ae([pe("useSpecularOverAlpha")],dh.prototype,"_useSpecularOverAlpha",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useSpecularOverAlpha",void 0),ae([pe("useReflectionOverAlpha")],dh.prototype,"_useReflectionOverAlpha",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useReflectionOverAlpha",void 0),ae([pe("disableLighting")],dh.prototype,"_disableLighting",void 0),ae([de("_markAllSubMeshesAsLightsDirty")],dh.prototype,"disableLighting",void 0),ae([pe("useObjectSpaceNormalMap")],dh.prototype,"_useObjectSpaceNormalMap",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useObjectSpaceNormalMap",void 0),ae([pe("useParallax")],dh.prototype,"_useParallax",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useParallax",void 0),ae([pe("useParallaxOcclusion")],dh.prototype,"_useParallaxOcclusion",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useParallaxOcclusion",void 0),ae([pe()],dh.prototype,"parallaxScaleBias",void 0),ae([pe("roughness")],dh.prototype,"_roughness",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"roughness",void 0),ae([pe()],dh.prototype,"indexOfRefraction",void 0),ae([pe()],dh.prototype,"invertRefractionY",void 0),ae([pe()],dh.prototype,"alphaCutOff",void 0),ae([pe("useLightmapAsShadowmap")],dh.prototype,"_useLightmapAsShadowmap",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useLightmapAsShadowmap",void 0),ae([me("diffuseFresnelParameters")],dh.prototype,"_diffuseFresnelParameters",void 0),ae([de("_markAllSubMeshesAsFresnelDirty")],dh.prototype,"diffuseFresnelParameters",void 0),ae([me("opacityFresnelParameters")],dh.prototype,"_opacityFresnelParameters",void 0),ae([de("_markAllSubMeshesAsFresnelAndMiscDirty")],dh.prototype,"opacityFresnelParameters",void 0),ae([me("reflectionFresnelParameters")],dh.prototype,"_reflectionFresnelParameters",void 0),ae([de("_markAllSubMeshesAsFresnelDirty")],dh.prototype,"reflectionFresnelParameters",void 0),ae([me("refractionFresnelParameters")],dh.prototype,"_refractionFresnelParameters",void 0),ae([de("_markAllSubMeshesAsFresnelDirty")],dh.prototype,"refractionFresnelParameters",void 0),ae([me("emissiveFresnelParameters")],dh.prototype,"_emissiveFresnelParameters",void 0),ae([de("_markAllSubMeshesAsFresnelDirty")],dh.prototype,"emissiveFresnelParameters",void 0),ae([pe("useReflectionFresnelFromSpecular")],dh.prototype,"_useReflectionFresnelFromSpecular",void 0),ae([de("_markAllSubMeshesAsFresnelDirty")],dh.prototype,"useReflectionFresnelFromSpecular",void 0),ae([pe("useGlossinessFromSpecularMapAlpha")],dh.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useGlossinessFromSpecularMapAlpha",void 0),ae([pe("maxSimultaneousLights")],dh.prototype,"_maxSimultaneousLights",void 0),ae([de("_markAllSubMeshesAsLightsDirty")],dh.prototype,"maxSimultaneousLights",void 0),ae([pe("invertNormalMapX")],dh.prototype,"_invertNormalMapX",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"invertNormalMapX",void 0),ae([pe("invertNormalMapY")],dh.prototype,"_invertNormalMapY",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"invertNormalMapY",void 0),ae([pe("twoSidedLighting")],dh.prototype,"_twoSidedLighting",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"twoSidedLighting",void 0),ae([pe("applyDecalMapAfterDetailMap")],dh.prototype,"_applyDecalMapAfterDetailMap",void 0),ae([de("_markAllSubMeshesAsMiscDirty")],dh.prototype,"applyDecalMapAfterDetailMap",void 0),u("BABYLON.StandardMaterial",dh),ks.DefaultMaterialFactory=e=>new dh("default material",e),Yi.prototype.createDynamicTexture=function(e,t,i,s){const r=new ti(this,ei.Dynamic);return r.baseWidth=e,r.baseHeight=t,i&&(e=this.needPOTTextures?Ri(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?Ri(t,this._caps.maxTextureSize):t),r.width=e,r.height=t,r.isReady=!1,r.generateMipMaps=i,r.samplingMode=s,this.updateTextureSamplingMode(s,r),this._internalTexturesCache.push(r),r},Yi.prototype.updateDynamicTexture=function(e,t,i,s=!1,r,n=!1,o=!1){if(!e)return;const a=this._gl,l=a.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,n);this._unpackFlipY(void 0===i?e.invertY:i),s&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(r||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,u);a.texImage2D(l,0,d,u,c,t),e.generateMipMaps&&a.generateMipmap(l),h||this._bindTextureDirectly(l,null),s&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),r&&(e.format=r),e._dynamicTextureSource=t,e._premulAlpha=s,e.invertY=i||!1,e.isReady=!0};class ph extends Zn{constructor(e,t,i=null,s=!1,r=3,n=5,o){super(null,i,!s,o,r,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=Zn.CLAMP_ADDRESSMODE,this.wrapV=Zn.CLAMP_ADDRESSMODE,this._generateMipMaps=s;const a=this._getEngine();if(!a)return;t.getContext?(this._canvas=t,this._ownCanvas=!1,this._texture=a.createDynamicTexture(t.width,t.height,s,r)):(this._canvas=a.createCanvas(1,1),this._ownCanvas=!0,t.width||0===t.width?this._texture=a.createDynamicTexture(t.width,t.height,s,r):this._texture=a.createDynamicTexture(t,t,s,r));const l=this.getSize();this._canvas.width!==l.width&&(this._canvas.width=l.width),this._canvas.height!==l.height&&(this._canvas.height=l.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){const t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){const i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){const t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0,void 0,i)}drawText(e,t,i,s,r,n,o,a=!0){const l=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,l.width,l.height)),this._context.font=s,null==t){const i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){const e=parseInt(s.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=r||"",this._context.fillText(e,t,i),a&&this.update(o)}dispose(){super.dispose(),this._ownCanvas&&this._canvas?.remove?.(),this._canvas=null,this._context=null}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new ph(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){const e=this.getScene();e&&!e.isReady()&&J.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return ph._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return void 0!==e.toDataURL}_rebuild(){this.update()}}class fh{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){if(this.isFixedFoveationSupported){const t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}}createRenderTargetTextureProvider(e){return this._rttWrapper=this._createRenderTargetTextureProvider(e),this._rttWrapper}dispose(){this._rttWrapper&&(this._rttWrapper.dispose(),this._rttWrapper=null)}constructor(e,t,i,s,r){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this._createRenderTargetTextureProvider=r,this._rttWrapper=null}}class _h{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new ti(this._engine,ei.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new Hi(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,s,r,n){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},a=n?new Yl(this._scene,o):new da("XR renderTargetTexture",o,this._scene),l=a.renderTarget;if(l._samples=a.samples,!i&&s||(l._framebuffer=i),s)if(n)l._colorTextureArray=s;else{const e=this._createInternalTexture(o,s);l.setTexture(e,0),a._texture=e}return r&&(n?l._depthStencilTextureArray=r:l._depthStencilTexture=this._createInternalTexture(o,r)),a.disableRescaling(),this._renderTargetTextures.push(a),a}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.length=0}}class mh extends fh{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new gh(e.scene,this))),this.layer=e}}class gh extends _h{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){const i=this._layer.getViewport(t);if(!i)return!1;const s=this._framebufferDimensions.framebufferWidth,r=this._framebufferDimensions.framebufferHeight;return e.x=i.x/s,e.y=i.y/r,e.width=i.width/s,e.height=i.height/r,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,s=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&s===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,s),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=s),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class vh{static GetDefaults(e){const t=new vh;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class xh{constructor(e,t=vh.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new g,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{const e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add((()=>{this._addCanvas()})),e.onXRSessionEnded.add((()=>{this._removeCanvas()})),this._makeCanvasCompatibleAsync()}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}_makeCanvasCompatibleAsync(){this._canvasCompatiblePromise=new Promise((e=>{this.canvasContext&&this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then((()=>{e()})):e()}))}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new mh(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this._canvasCompatiblePromise.then((()=>{}),(()=>{Ii.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")})).then((()=>t()))}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce((()=>{this._setCanvasSize(!0)}))}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class Th extends fh{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new Sh(e,this))),this.layer=e}}class Sh extends _h{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}}class Eh{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}}class bh{get worldScalingFactor(){return this._worldScalingFactor}set worldScalingFactor(e){const t=this._worldScalingFactor;this._worldScalingFactor=e,this.onWorldScaleFactorChangedObservable.notifyObservers({previousScaleFactor:t,newScaleFactor:e})}constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new g,this.onXRReferenceSpaceChanged=new g,this.onXRSessionEnded=new g,this.onXRSessionInit=new g,this.onXRReferenceSpaceInitialized=new g,this.onXRReady=new g,this.inXRFrameLoop=!1,this.inXRSession=!1,this._worldScalingFactor=1,this.onWorldScaleFactorChangedObservable=new g(void 0,!0),this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),this.onWorldScaleFactorChangedObservable.clear(),this._engine?.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}async exitXRAsync(){if(this.session&&this.inXRSession){this.inXRSession=!1;try{return await this.session.end()}catch{J.Warn("Could not end XR session.")}}return Promise.resolve()}trySetViewportForView(e,t){return this._baseLayerRTTProvider?.trySetViewportForView(e,t)||!1}getRenderTargetTextureForEye(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForEye(e)||null}getRenderTargetTextureForView(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForView(e)||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new Eh(this):((e=e||vh.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new xh(this,e))}initializeAsync(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then((t=>(this.session=t,this._sessionMode=e,this.inXRSession=!0,this.onXRSessionInit.notifyObservers(t),this.session.addEventListener("end",(()=>{this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&this._baseLayerRTTProvider?.dispose(),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null}),{once:!0}),this.session)))}isSessionSupportedAsync(e){return bh.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:e=>this.session.requestAnimationFrame(e),renderFunction:(e,t)=>{if(this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t)){this.inXRFrameLoop=!0;const e=this._baseLayerRTTProvider?.getFramebufferDimensions()||null;this._engine.framebufferDimensionsObject!==e&&(this._engine.framebufferDimensionsObject=e),this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1}}},this._engine.framebufferDimensionsObject=this._baseLayerRTTProvider?.getFramebufferDimensions()||null,this.onXRFrameObservable.addOnce((()=>{this.onXRReady.notifyObservers(this)})),"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then((e=>e),(e=>(J.Error("XR.requestReferenceSpace failed for the following reason: "),J.Error(e),J.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then((e=>{const t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)}),(e=>{throw J.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))))).then((e=>this.session.requestReferenceSpace("viewer").then((t=>(this.viewerReferenceSpace=t,e))))).then((e=>(this.referenceSpace=this.baseReferenceSpace=e,this.onXRReferenceSpaceInitialized.notifyObservers(e),this.referenceSpace)))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){this.isNative&&this._baseLayerRTTProvider?.dispose(),this._baseLayerWrapper=e,this._baseLayerRTTProvider=this._baseLayerWrapper?.createRenderTargetTextureProvider(this)||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new Th(e.baseLayer):new mh(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);const t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then((e=>{const t=void 0===e||e;return Promise.resolve(t)})).catch((e=>(J.Warn(e),Promise.resolve(!1)))):Promise.resolve(!1)}get isNative(){return this._xrNavigator.xr.native??!1}get currentFrameRate(){return this.session?.frameRate}get supportedFrameRates(){return this.session?.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():!this.inXRSession&&t||this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){return this._baseLayerWrapper?.isFixedFoveationSupported||!1}get fixedFoveation(){return this._baseLayerWrapper?.fixedFoveation||null}set fixedFoveation(e){const t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)}get enabledFeatures(){return this.session?.enabledFeatures??null}}var Ch,yh;!function(e){e[e.ENTERING_XR=0]="ENTERING_XR",e[e.EXITING_XR=1]="EXITING_XR",e[e.IN_XR=2]="IN_XR",e[e.NOT_IN_XR=3]="NOT_IN_XR"}(Ch||(Ch={})),function(e){e[e.NOT_TRACKING=0]="NOT_TRACKING",e[e.TRACKING_LOST=1]="TRACKING_LOST",e[e.TRACKING=2]="TRACKING"}(yh||(yh={})),Un._GroundMeshParser=(e,t)=>Ah.Parse(e,t);class Ah extends Un{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),s=U.Matrix[5];i.invertToRef(s);const r=U.Vector3[8];if(w.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const n=this._getFacetAt(e,t),o=-(n.x*e+n.z*t+n.w)/n.y;return w.TransformCoordinatesFromFloatsToRef(0,o,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new w(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),r=U.Matrix[5];s.invertToRef(r);const n=U.Vector3[8];if(w.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t);return w.TransformNormalFromFloatsToRef(o.x,o.y,o.z,s,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),s=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[s*this._subdivisionsX+i];let n;return n=te.maxHeight){h=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(n=0;n<=e.subdivisions;n++)for(o=0;o<=e.subdivisions;o++){const t=new w(o*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-n)*e.height/e.subdivisions-e.height/2),c=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let u=e.buffer[c]/255,d=e.buffer[c+1]/255,p=e.buffer[c+2]/255;const f=e.buffer[c+3]/255;h&&(u=1-u,d=1-d,p=1-p);const _=u*a.r+d*a.g+p*a.b;t.y=f>=l?e.minHeight+(e.maxHeight-e.minHeight)*_:e.minHeight-T,e.heightBuffer&&(e.heightBuffer[n*(e.subdivisions+1)+o]=t.y),i.push(t.x,t.y,t.z),s.push(0,0,0),r.push(o/e.subdivisions,1-n/e.subdivisions)}for(n=0;n=e.minHeight,c=i[3*r+1]>=e.minHeight,u=i[3*a+1]>=e.minHeight;h&&c&&u&&(t.push(s),t.push(r),t.push(a)),i[3*l+1]>=e.minHeight&&h&&u&&(t.push(l),t.push(s),t.push(a))}Tr.ComputeNormals(i,t,s);const c=new Tr;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function Mh(e,t={},i){const s=new Ah(e,i);return s._setReady(!1),s._subdivisionsX=t.subdivisionsX||t.subdivisions||1,s._subdivisionsY=t.subdivisionsY||t.subdivisions||1,s._width=t.width||1,s._height=t.height||1,s._maxX=s._width/2,s._maxZ=s._height/2,s._minX=-s._maxX,s._minZ=-s._maxZ,Rh(t).applyToMesh(s,t.updatable),s._setReady(!0),s}function Dh(e){const t=[],i=[],s=[],r=[],n=e.diameter||1,o=e.thickness||.5,a=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE,h=a+1;for(let e=0;e<=a;e++){const l=e/a,c=e*Math.PI*2/a-Math.PI/2,u=B.Translation(n/2,0,0).multiply(B.RotationY(c));for(let n=0;n<=a;n++){const c=1-n/a,d=n*Math.PI*2/a+Math.PI,p=Math.cos(d),f=Math.sin(d);let _=new w(p,f,0),m=_.scale(o/2);const g=new N(l,c);m=w.TransformCoordinates(m,u),_=w.TransformNormal(_,u),i.push(m.x,m.y,m.z),s.push(_.x,_.y,_.z),r.push(g.x,Er.UseOpenGLOrientationForUV?1-g.y:g.y);const v=(e+1)%h,x=(n+1)%h;t.push(e*h+n),t.push(e*h+x),t.push(v*h+n),t.push(e*h+x),t.push(v*h+x),t.push(v*h+n)}}Tr._ComputeSides(l,i,t,s,r,e.frontUVs,e.backUVs);const c=new Tr;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function Oh(e,t={},i){const s=new Un(e,i);return t.sideOrientation=Un._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,Dh(t).applyToMesh(s,t.updatable),s}Tr.CreateGround=Rh,Tr.CreateTiledGround=Ih,Tr.CreateGroundFromHeightMap=Ph,Un.CreateGround=(e,t,i,s,r,n)=>Mh(e,{width:t,height:i,subdivisions:s,updatable:n},r),Un.CreateTiledGround=(e,t,i,s,r,n,o,a,l)=>function(e,t,i=null){const s=new Un(e,i);return Ih(t).applyToMesh(s,t.updatable),s}(e,{xmin:t,zmin:i,xmax:s,zmax:r,subdivisions:n,precision:o,updatable:l},a),Un.CreateGroundFromHeightMap=(e,t,i,s,r,n,o,a,l,h,c)=>function(e,t,i={},s=null){const r=i.width||10,n=i.height||10,o=i.subdivisions||1,a=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new Y(.3,.59,.11),c=i.alphaFilter||0,u=i.updatable,d=i.onReady;s=s||y.LastCreatedScene;const p=new Ah(e,s);let f;p._subdivisionsX=o,p._subdivisionsY=o,p._width=r,p._height=n,p._maxX=p._width/2,p._maxZ=p._height/2,p._minX=-p._maxX,p._minZ=-p._maxZ,p._setReady(!1),i.passHeightBufferInCallback&&(f=new Float32Array((o+1)*(o+1)));const _=(e,t,i)=>{Ph({width:r,height:n,subdivisions:o,minHeight:a,maxHeight:l,colorFilter:h,buffer:e,bufferWidth:t,bufferHeight:i,alphaFilter:c,heightBuffer:f}).applyToMesh(p,u),d&&d(p,f),p._setReady(!0)};if("string"==typeof t){const e=e=>{const t=e.width,i=e.height;if(s.isDisposed)return;const r=s?.getEngine().resizeImageBitmap(e,t,i);_(r,t,i)};Ii.LoadImage(t,e,i.onError?i.onError:()=>{},s.offlineProvider)}else _(t.data,t.width,t.height);return p}(e,t,{width:i,height:s,subdivisions:r,minHeight:n,maxHeight:o,updatable:l,onReady:h,alphaFilter:c},a),Tr.CreateTorus=Dh,Un.CreateTorus=(e,t,i,s,r,n,o)=>Oh(e,{diameter:t,thickness:i,tessellation:s,sideOrientation:o,updatable:n},r);class Nh{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=Nh._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=Oh("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const t=new dh("targetMat",e);t.specularColor=Y.Black(),t.emissiveColor=new Y(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new ao(w.Zero(),new w(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}}Nh._IdCounter=0;class wh extends Nh{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new ao(w.Zero(),w.Forward())}}class Fh{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._scene.activeCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated}constructor(e,t={}){if(this.webVROptions=t,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new g,this.onAfterEnteringVRObservable=new g,this.onExitingVRObservable=new g,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=Fh.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new w(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new w(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new Y(.2,.2,1),this._pickedGazeColor=new Y(0,0,1),this.onNewMeshSelected=new g,this.onNewMeshPicked=new g,this.onBeforeCameraTeleport=new g,this.onAfterCameraTeleport=new g,this.onSelectedMeshUnselected=new g,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock||(this._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=e=>{e.type!==Ya.POSE_ENABLED&&(e.leftStick&&e.onleftstickchanged((e=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))})),e.rightStick&&e.onrightstickchanged((e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)})),e.type===Ya.XBOX&&(e.onbuttondown((e=>{this._interactionsEnabled&&e===ka.A&&this._cameraGazer._selectionPointerDown()})),e.onbuttonup((e=>{this._interactionsEnabled&&e===ka.A&&this._cameraGazer._selectionPointerUp()}))))},this._workingVector=w.Zero(),this._workingQuaternion=L.Identity(),this._workingMatrix=B.Identity(),J.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement(),"getVRDisplays"in navigator||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new w(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new vl("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof fl&&this._scene.activeCamera.rotation)){const e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(L.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?bh.IsSessionSupportedAsync("immersive-vr").then((i=>{i?(J.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then((t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new wh((()=>this.xr.baseExperience.camera),e),this.xr.baseExperience.onStateChangedObservable.add((e=>{switch(e){case Ch.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case Ch.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case Ch.IN_XR:this._hasEnteredVR=!0;break;case Ch.NOT_IN_XR:this._hasEnteredVR=!1}}))}))):this._completeVRInit(e,t)})):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new Zl("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new wh((()=>this.currentVRCamera),e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let e=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";e+=".babylonVRicon.vrdisplaypresenting { display: none; }";const t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",(()=>{this.isInVRMode||this.enterVR()}));const i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add((()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())}),ss.POINTERDOUBLETAP,!1),e.onDisposeObservable.add((()=>{this.dispose()})),this._updateButtonVisibility(),this._circleEase=new qs,this._circleEase.setEasingMode(Ks.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add((t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===ss.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===ss.POINTERUP&&this._cameraGazer._selectionPointerUp())})),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===Ch.IN_XR||this._fullscreenVRpresenting}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){const e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))}enterVR(){if(this.xr)this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);else{if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){J.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=L.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce((()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})}))),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}}exitVR(){if(this.xr)this.xr.baseExperience.exitXRAsync();else if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){J.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this.xr)return void(this.xr.baseExperience.state===Ch.IN_XR&&this.xr.pointerSelection.attach());this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>!!(this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}_isTeleportationFloor(e){for(let t=0;t-1||this._floorMeshesCollection.push(e))}removeFloorMesh(e){if(!this._floorMeshesCollection)return;const t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const t=e.floorMeshes||[];if(!t.length){const i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr)return t.forEach((e=>{this.xr.teleportation.addFloorMesh(e)})),void(this.xr.teleportation.attached||this.xr.teleportation.attach());if(!this.xrTestDone){const t=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(t),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};return void this._scene.registerBeforeRender(t)}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction);const t=new Bi;t.vignetteColor=new j(0,0,0,0),t.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}}_checkTeleportWithRay(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;const e=L.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,L.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),w.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const s=new ao(i,this._workingVector),r=this._scene.pickWithRay(s,this._raySelectionPredicate);r&&r.pickedPoint&&r.pickedMesh&&this._isTeleportationFloor(r.pickedMesh)&&r.distance<5&&this.teleportCamera(r.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_createTeleportationCircles(){this._teleportationTarget=Mh("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=new ph("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;const t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();const i=new dh("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;const s=Oh("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);s.isPickable=!1,s.parent=this._teleportationTarget;const r=new Ge("animationInnerCircle","position.y",30,Ge.ANIMATIONTYPE_FLOAT,Ge.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),r.setKeys(n);const o=new Zs;o.setEasingMode(Ks.EASINGMODE_EASEINOUT),r.setEasingFunction(o),s.animations=[],s.animations.push(r),this._scene.beginAnimation(s,0,60,!0),this._hideTeleportationTarget()}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof _l))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=L.FromRotationMatrix(B.RotationY(Math.PI/4*this._rotationAngle)),i=new Ge("animationRotation","rotationQuaternion",90,Ge.ANIMATIONTYPE_QUATERNION,Ge.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),s.push({frame:6,value:t}),i.setKeys(s),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const r=new Ge("animationPP","vignetteWeight",90,Ge.ANIMATIONTYPE_FLOAT,Ge.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),r.setKeys(n),r.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(r);const o=new Ge("animationPP2","vignetteStretch",90,Ge.ANIMATIONTYPE_FLOAT,Ge.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:10}),a.push({frame:6,value:0}),o.setKeys(a),o.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(o),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}teleportCamera(e){if(!(this.currentVRCamera instanceof _l))return;let t,i;if(this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==Fh.TELEPORTATIONMODE_CONSTANTSPEED){i=90;const e=w.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];const s=new Ge("animationCameraTeleportation","position",90,Ge.ANIMATIONTYPE_VECTOR3,Ge.ANIMATIONLOOPMODE_CONSTANT),r=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];s.setKeys(r),s.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(s),this._postProcessMove.animations=[];const n=Math.round(i/2),o=new Ge("animationPP","vignetteWeight",90,Ge.ANIMATIONTYPE_FLOAT,Ge.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:n,value:8}),a.push({frame:i,value:0}),o.setKeys(a),this._postProcessMove.animations.push(o);const l=new Ge("animationPP2","vignetteStretch",90,Ge.ANIMATIONTYPE_FLOAT,Ge.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:n,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,(()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)})),this._hideTeleportationTarget()}setLaserColor(e,t=this._pickedLaserColor){this._pickedLaserColor=t}setLaserLightingState(e=!0){}setGazeColor(e,t=this._pickedGazeColor){this._pickedGazeColor=t}changeLaserColor(e){this.updateControllerLaserColor}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}}Fh.TELEPORTATIONMODE_CONSTANTTIME=0,Fh.TELEPORTATIONMODE_CONSTANTSPEED=1;const Lh=function(){const e={root:0,found:!1};return function(t,i,s,r){e.root=0,e.found=!1;const n=i*i-4*t*s;if(n<0)return e;const o=Math.sqrt(n);let a=(-i-o)/(2*t),l=(-i+o)/(2*t);if(a>l){const e=l;l=a,a=e}return a>0&&a0&&l=0))}_canDoCollision(e,t,i,s){const r=w.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(r>this._velocityWorldLength+n+t||!((e,t,i,s)=>!(e.x>i.x+s||i.x-s>t.x||e.y>i.y+s||i.y-s>t.y||e.z>i.z+s||i.z-s>t.z))(i,s,this._basePointWorld,this._velocityWorldLength+n))}_testTriangle(e,t,i,s,r,n,o){let a,l=!1;t||(t=[]),t[e]||(t[e]=new Ps(0,0,0,0),t[e].copyFromPoints(i,s,r));const h=t[e];if(!n&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;const c=h.signedDistanceTo(this._basePoint),u=w.Dot(h.normal,this._velocity);if(Bh.DoubleSidedCheck&&u>1e-4)return;if(0==u){if(Math.abs(c)>=1)return;l=!0,a=0}else{a=(-1-c)/u;let e=(1-c)/u;if(a>e){const t=e;e=a,a=t}if(a>1||e<0)return;a<0&&(a=0),a>1&&(a=1)}this._collisionPoint.copyFromFloats(0,0,0);let d=!1,p=1;if(l||(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(a,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,s,r,h.normal)&&(d=!0,p=a,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!d){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*w.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=Lh(e,t,n,p);o.found&&(p=o.root,d=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(s,this._tempVector),t=2*w.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=Lh(e,t,n,p),o.found&&(p=o.root,d=!0,this._collisionPoint.copyFrom(s)),this._basePoint.subtractToRef(r,this._tempVector),t=2*w.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=Lh(e,t,n,p),o.found&&(p=o.root,d=!0,this._collisionPoint.copyFrom(r)),s.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let a=this._edge.lengthSquared(),l=w.Dot(this._edge,this._velocity),h=w.Dot(this._edge,this._baseToVertex);if(e=a*-this._velocitySquaredLength+l*l,t=2*(a*w.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=Lh(e,t,n,p),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(p=o.root,d=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(r.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=w.Dot(this._edge,this._velocity),h=w.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*w.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=Lh(e,t,n,p),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(p=o.root,d=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=w.Dot(this._edge,this._velocity),h=w.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*w.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=Lh(e,t,n,p),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(p=o.root,d=!0,this._edge.scaleInPlace(e),r.addToRef(this._edge,this._collisionPoint))}}if(d){const e=p*p*this._velocitySquaredLength;(!this.collisionFound||e=s)return void r.copyFrom(e);const a=n?n.collisionMask:i.collisionMask;i._initialize(e,t,o);const l=n&&n.surroundingMeshes||this._scene.meshes;for(let e=0;enew Vh;class Uh{constructor(e,t,i,s=""){let r;this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new g,this.onErrorObservable=new g,this.onBindObservable=new g,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=ht.WGSL,this.name=e,this._key=s,this._engine=i,this.uniqueId=Uh._UniqueIdSeed++,this.defines=t.defines??"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=t.entryPoint??"main",this._shaderStore=Ft.GetShadersStore(this._shaderLanguage),this._shaderRepository=Ft.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=Ft.GetIncludesShadersStore(this._shaderLanguage);const n=We()?this._engine.getHostDocument():null;r="string"==typeof e?e:e.computeSource?"source:"+e.computeSource:e.computeElement?n?.getElementById(e.computeElement)||e.computeElement:e.compute||e;const o={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(r,"Compute","",(i=>{bt(o),function(e,t,i,s){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),Ot(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const r=function(e,t,i){let s=e;const r=t.defines,n=Dt(t,i);return t.processor?.preProcessor&&(s=t.processor.preProcessor(s,r,n,t.isFragment,t.processingContext)),s=Mt(s,n,t),t.processor?.postProcessor&&(s=t.processor.postProcessor(s,r,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),i._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}(e,t,s);i(r,e)}))}(i,o,(s=>{this._rawComputeSourceCode=i,t.processFinalCode&&(s=t.processFinalCode(s));const r=yt(s,"",o);this._useFinalCode(r.vertexCode,e)}),this._engine)}))}_useFinalCode(e,t){if(t){const i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}setTimeout((()=>{this._checkIsReady(e)}),16)}_loadShader(e,t,i,s){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void s(Ye(e));if("source:"===e.substr(0,7))return void s(e.substr(7));if("base64:"===e.substr(0,7))return void s(window.atob(e.substr(7)));if(this._shaderStore[e+t+"Shader"])return void s(this._shaderStore[e+t+"Shader"]);if(i&&this._shaderStore[e+i+"Shader"])return void s(this._shaderStore[e+i+"Shader"]);let r;r="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(r+"."+t.toLowerCase()+".fx",s)}get computeSourceCode(){return this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._pipelineContext?._getComputeShaderCode()??this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){const e=this.defines,t=this._pipelineContext;this._isReady=!1;try{const i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,(e=>{e&&e.numErrors>0?this._processCompilationErrors(e,t):(this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t))})),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_processCompilationErrors(e,t=null){if(this._compilationError="",J.Error("Unable to compile compute effect:"),this.defines&&J.Error("Defines:\n"+this.defines),Uh.LogShaderCodeOnCompilationError){const e=this._pipelineContext?._getComputeShaderCode();e&&(J.Error("Compute code:"),J.Error(e))}if("string"==typeof e)this._compilationError=e,J.Error("Error: "+this._compilationError);else for(const t of e.messages){let e="";void 0!==t.line&&(e+="Line "+t.line+", "),void 0!==t.offset&&(e+="Offset "+t.offset+", "),void 0!==t.length&&(e+="Length "+t.length+", "),e+=t.type+": "+t.text,this._compilationError&&(this._compilationError+="\n"),this._compilationError+=e,J.Error(e)}t&&(this._pipelineContext=t,this._isReady=!0),this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){Ft.GetShadersStore(ht.WGSL)[`${e}ComputeShader`]=t}}var kh,Gh,zh,Wh,Hh;Uh._UniqueIdSeed=0,Uh.LogShaderCodeOnCompilationError=!0,function(e){e[e.Texture=0]="Texture",e[e.StorageTexture=1]="StorageTexture",e[e.UniformBuffer=2]="UniformBuffer",e[e.StorageBuffer=3]="StorageBuffer",e[e.TextureWithoutSampler=4]="TextureWithoutSampler",e[e.Sampler=5]="Sampler",e[e.ExternalTexture=6]="ExternalTexture",e[e.DataBuffer=7]="DataBuffer"}(kh||(kh={})),Yi.prototype.createComputeEffect=function(e,t){throw new Error("createComputeEffect: This engine does not support compute shaders!")},Yi.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")},Yi.prototype.createComputeContext=function(){},Yi.prototype.computeDispatch=function(e,t,i,s,r,n,o){throw new Error("computeDispatch: This engine does not support compute shaders!")},Yi.prototype.computeDispatchIndirect=function(e,t,i,s,r,n){throw new Error("computeDispatchIndirect: This engine does not support compute shaders!")},Yi.prototype.areAllComputeEffectsReady=function(){return!0},Yi.prototype.releaseComputeEffects=function(){},Yi.prototype._prepareComputePipelineContext=function(e,t,i,s,r){},Yi.prototype._rebuildComputeEffects=function(){},si.prototype._executeWhenComputeStateIsCompiled=function(e,t){t(null)},Yi.prototype._releaseComputeEffect=function(e){},Yi.prototype._deleteComputePipelineContext=function(e){};class Xh{constructor(){this._gpuTimeInFrameId=-1,this.counter=new Is}_addDuration(e,t){e{const n=()=>{this.dispatch(e,t,i)?r():setTimeout(n,s)};n()}))}serialize(){const e=Pe.Serialize(this);e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={};for(const t in this._bindings){const i=this._bindings[t],s=i.object;switch(i.type){case kh.Texture:case kh.TextureWithoutSampler:case kh.StorageTexture:{const r=s.serialize();r&&(e.textures[t]=r,e.bindings[t]={type:i.type});break}case kh.UniformBuffer:}}return e}static Parse(e,t,i){const s=Pe.Parse((()=>new Yh(e.name,t.getEngine(),e.shaderPath,e.options)),e,t,i);for(const r in e.textures){const n=e.bindings[r],o=Zn.Parse(e.textures[r],t,i);n.type===kh.Texture?s.setTexture(r,o):n.type===kh.TextureWithoutSampler?s.setTexture(r,o,!1):s.setStorageTexture(r,o)}return s}static _BufferIsDataBuffer(e){return void 0!==e.underlyingResource}}ae([pe()],Yh.prototype,"name",void 0),ae([pe()],Yh.prototype,"fastMode",void 0),u("BABYLON.ComputeShader",Yh);class jh{constructor(e,t,i,s,r,n){this.entries=[],this._boundingVectors=new Array,this._capacity=i,this._depth=s,this._maxDepth=r,this._creationFunc=n,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks)for(let t=0;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{const i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},$h.CreationFuncForSubMeshes=(e,t)=>{e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},ks.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(ts.NAME_OCTREE);i||(i=new Kh(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new $h($h.CreationFuncForMeshes,e,t));const s=this.getWorldExtends();return this._selectionOctree.update(s.min,s.max,this.meshes),this._selectionOctree},Object.defineProperty(ks.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),Wr.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){const i=this.getScene();let s=i._getComponent(ts.NAME_OCTREE);s||(s=new Kh(i),i._addComponent(s)),this._submeshesOctree||(this._submeshesOctree=new $h($h.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);const r=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(r.minimumWorld,r.maximumWorld,this.subMeshes),this._submeshesOctree};class Kh{constructor(e){this.name=ts.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new ao(w.Zero(),new w(1,1,1)),(e=e||y.LastCreatedScene)&&(this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=e=>this.getActiveSubMeshCandidates(e),this.scene.getCollidingSubMeshCandidates=(e,t)=>this.getCollidingSubMeshCandidates(e,t),this.scene.getIntersectingSubMeshCandidates=(e,t)=>this.getIntersectingSubMeshCandidates(e,t))}register(){this.scene.onMeshRemovedObservable.add((e=>{const t=this.scene.selectionOctree;if(null!=t){const i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}})),this.scene.onMeshImportedObservable.add((e=>{const t=this.scene.selectionOctree;null!=t&&t.addMesh(e)}))}getActiveMeshCandidates(){return this.scene._selectionOctree?.select(this.scene.frustumPlanes)||this.scene._getDefaultMeshCandidates()}getActiveSubMeshCandidates(e){return e._submeshesOctree&&e.useOctreeForRenderingSelection?e._submeshesOctree.select(this.scene.frustumPlanes):this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){return e._submeshesOctree&&e.useOctreeForPicking?(ao.TransformToRef(t,e.getWorldMatrix(),this._tempRay),e._submeshesOctree.intersectsRay(this._tempRay)):this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){const i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z);return e._submeshesOctree.intersects(t._basePointWorld,i)}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}}function qh(e){const t=e.height||2;let i=0===e.diameterTop?0:e.diameterTop||e.diameter||1,s=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;i=i||1e-5,s=s||1e-5;const r=0|(e.tessellation||24),n=0|(e.subdivisions||1),o=!!e.hasRings,a=!!e.enclose,l=0===e.cap?0:e.cap||Un.CAP_ALL,h=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,c=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE,u=e.faceUV||new Array(3),d=e.faceColors,p=2+(1+(1!==h&&a?2:0))*(o?n:1);let f;for(f=0;f{const n=e?i/2:s/2;if(0===n)return;let o,a,l;const c=e?u[p-1]:u[0];let f=null;d&&(f=e?d[p-1]:d[0]);const T=m.length/3,S=e?t/2:-t/2,E=new w(0,S,0);m.push(E.x,E.y,E.z),g.push(0,e?1:-1,0);const b=c.y+.5*(c.w-c.y);v.push(c.x+.5*(c.z-c.x),Er.UseOpenGLOrientationForUV?1-b:b),f&&x.push(f.r,f.g,f.b,f.a);const C=new N(.5,.5);for(l=0;l<=r;l++){o=2*Math.PI*l*h/r;const t=Math.cos(-o),i=Math.sin(-o);a=new w(t*n,S,i*n);const s=new N(t*C.x+.5,i*C.y+.5);m.push(a.x,a.y,a.z),g.push(0,e?1:-1,0);const u=c.y+(c.w-c.y)*s.y;v.push(c.x+(c.z-c.x)*s.x,Er.UseOpenGLOrientationForUV?1-u:u),f&&x.push(f.r,f.g,f.b,f.a)}for(l=0;l(void 0!==o&&o instanceof ks||(void 0!==o&&(l=a||Un.DEFAULTSIDE,a=o),o=n,n=1),Qh(e,{height:t,diameterTop:i,diameterBottom:s,tessellation:r,subdivisions:n,sideOrientation:l,updatable:a},o)),De.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new Zh(e,w.Zero(),t)));class Zh extends Gn{constructor(e,t,i){super(e,i),this.groundColor=new Y(0,0,0),this.direction=t||w.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=w.Normalize(e.subtract(w.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=w.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){const i=w.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=B.Identity()),this._worldMatrix}getTypeID(){return Gn.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}ae([_e()],Zh.prototype,"groundColor",void 0),ae([ve()],Zh.prototype,"direction",void 0),u("BABYLON.HemisphericLight",Zh);class Jh{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new Zh("shared gizmo light",new w(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=Y.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==Jh._DefaultUtilityLayer?Jh._CreateDefaultUtilityLayerFromScene(y.LastCreatedScene):Jh._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return Jh._DefaultUtilityLayer=new Jh(e),Jh._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{Jh._DefaultUtilityLayer=null})),Jh._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==Jh._DefaultKeepDepthUtilityLayer&&(Jh._DefaultKeepDepthUtilityLayer=new Jh(y.LastCreatedScene),Jh._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,Jh._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{Jh._DefaultKeepDepthUtilityLayer=null}))),Jh._DefaultKeepDepthUtilityLayer}constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new g,this.utilityLayerScene=new ks(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add((t=>{if(!this.utilityLayerScene.activeCamera)return;if(!this.pickingEnabled)return;if(!this.processAllEvents&&t.type!==ss.POINTERMOVE&&t.type!==ss.POINTERUP&&t.type!==ss.POINTERDOWN&&t.type!==ss.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const i=t.event;if(e.isPointerCaptured(i.pointerId))return void(this._pointerCaptures[i.pointerId]=!1);const s=i=>{let s=null;if(t.nearInteractionPickingInfo)s=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new qi;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)s=t.originalPickingInfo;else{let r=null;this._renderCamera&&(r=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),s=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),r&&(i._activeCamera=r)}return s},r=s(this.utilityLayerScene);if(!t.ray&&r&&(t.ray=r.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=ss.POINTERDOWN)return t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new os(t.type,t.event,r),t.type),void(t.type===ss.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1));if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)r&&r.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new os(t.type,t.event,r),t.type),t.skipOnPointerObservable=!0);else{const i=s(e),n=t.event;i&&r&&(0===r.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):t.type===ss.POINTERDOWN?this._pointerCaptures[n.pointerId]=!0:t.type!==ss.POINTERMOVE&&t.type!==ss.POINTERUP||(this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,i,n)):!this._pointerCaptures[n.pointerId]&&(r.distance0)):!this._pointerCaptures[n.pointerId]&&r.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):(t.type!==ss.POINTERMOVE&&t.type!==ss.POINTERUP||this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,r,n))),t.type===ss.POINTERUP&&this._pointerCaptures[n.pointerId]&&(this._pointerCaptures[n.pointerId]=!1))}})),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add((e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add((()=>{this.dispose()})),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new os(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){const e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}}Jh._DefaultUtilityLayer=null,Jh._DefaultKeepDepthUtilityLayer=null,function(e){e[e.Origin=0]="Origin",e[e.Pivot=1]="Pivot"}(Gh||(Gh={})),(Hh=zh||(zh={}))[Hh.World=0]="World",Hh[Hh.Local=1]="Local";class ec{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach((e=>{e.dispose()})),e.parent=this._rootMesh,this._customMeshSet=!0}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){this._additionalTransformNode=e}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;const t=e==zh.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=Jh.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=Gh.Origin,this._updateScale=!0,this._coordinatesMode=zh.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=B.RotationY(Math.PI),this._rootMesh=new Un("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=L.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add((()=>{this._update()}))}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh)if(this.anchorPoint==Gh.Pivot&&e.getAbsolutePivotPoint){const t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{const t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new w(0,0,0);this._rootMesh.position.copyFrom(i)}if(this.updateGizmoRotationToMatchAttachedMesh){const t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName()?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,ec.PreserveScaling?t:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){const t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,U.Vector3[0]);let s=this.scaleRatio;if(t.mode==or.ORTHOGRAPHIC_CAMERA)t.orthoTop&&t.orthoBottom&&(s*=t.orthoTop-t.orthoBottom);else{const e=t.getScene().useRightHandedSystem?w.RightHandedForwardReadOnly:w.LeftHandedForwardReadOnly,i=t.getDirection(e);s*=w.Dot(U.Vector3[0],i)}this._rootMesh.scaling.setAll(s),e._getWorldMatrixDeterminant()<0&&!ec.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}this.additionalTransformNode&&(this._rootMesh.computeWorldMatrix(!0),this._rootMesh.getWorldMatrix().multiplyToRef(this.additionalTransformNode.getWorldMatrix(),U.Matrix[0]),U.Matrix[0].decompose(this._rootMesh.scaling,this._rootMesh.rotationQuaternion,this._rootMesh.position))}_handlePivotMatrixInverse(e,t,i){if(e.isUsingPivotMatrix()&&!e.isUsingPostMultiplyPivotMatrix())return e.getPivotMatrix().invertToRef(U.Matrix[5]),void U.Matrix[5].multiplyToRef(t,i);i.copyFrom(t)}_matrixChanged(){if(this._attachedNode)if(this._attachedNode._isCamera){const e=this._attachedNode;let t,i;if(e.parent){const i=U.Matrix[1];e.parent._worldMatrix.invertToRef(i),this._attachedNode._worldMatrix.multiplyToRef(i,U.Matrix[0]),t=U.Matrix[0]}else t=this._attachedNode._worldMatrix;if(e.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(t,U.Matrix[1]),i=U.Matrix[1]):i=t,i.decompose(U.Vector3[1],U.Quaternion[0],U.Vector3[0]),"FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName()){const e=this._attachedNode;e.rotation=U.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(U.Quaternion[0]),e.rotationQuaternion.normalize())}e.position.copyFrom(U.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){const e=this._attachedNode;if(e.parent){const t=U.Matrix[0],i=U.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i);const s=U.Matrix[4];if(this._handlePivotMatrixInverse(e,i,s),s.decompose(U.Vector3[0],U.Quaternion[0],e.position,ec.PreserveScaling?e:void 0,ec.UseAbsoluteScaling),U.Quaternion[0].normalize(),e.isUsingPivotMatrix()){const t=U.Quaternion[1];L.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,t);const i=U.Matrix[2];B.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,i);const s=U.Matrix[2];t.toRotationMatrix(s);const r=e.getPivotMatrix(),n=U.Matrix[3];r.invertToRef(n),r.multiplyToRef(i,U.Matrix[4]),U.Matrix[4].multiplyToRef(s,U.Matrix[5]),U.Matrix[5].multiplyToRef(n,U.Matrix[6]),U.Matrix[6].getTranslationToRef(U.Vector3[1]),e.position.subtractInPlace(U.Vector3[1])}}else{const t=U.Matrix[4];this._handlePivotMatrixInverse(e,this._attachedNode._worldMatrix,t),t.decompose(U.Vector3[0],U.Quaternion[0],e.position,ec.PreserveScaling?e:void 0,ec.UseAbsoluteScaling)}U.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(U.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(U.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=U.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){const e=this._attachedNode,t=e.getParent();if(t){const i=U.Matrix[0],s=U.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,s),e.getLocalMatrix().copyFrom(s)}else e.getLocalMatrix().copyFrom(e.getFinalMatrix());e.markAsDirty()}else{const e=this._attachedNode;if(e.getTypeID){const t=e.getTypeID();if(t===Gn.LIGHTTYPEID_DIRECTIONALLIGHT||t===Gn.LIGHTTYPEID_SPOTLIGHT||t===Gn.LIGHTTYPEID_POINTLIGHT){const t=e.parent;if(t){const i=U.Matrix[0],s=U.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,s),s.decompose(void 0,U.Quaternion[0],U.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,U.Quaternion[0],U.Vector3[0]);e.position=new w(U.Vector3[0].x,U.Vector3[0].y,U.Vector3[0].z),e.direction&&(e.direction=new w(e.direction.x,e.direction.y,e.direction.z))}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach((e=>{e.material=t,e.color&&(e.color=t.diffuseColor)}))}static GizmoAxisPointerObserver(e,t){let i=!1;return e.utilityLayerScene.onPointerObservable.add((e=>{if(e.pickInfo){if(e.type===ss.POINTERMOVE){if(i)return;t.forEach((t=>{if(t.colliderMeshes&&t.gizmoMeshes){const i=-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh),s=t.dragBehavior.enabled?i||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=s,e.color&&(e.color=s.diffuseColor)}))}}))}e.type===ss.POINTERDOWN&&t.has(e.pickInfo.pickedMesh?.parent)&&(i=!0,t.get(e.pickInfo.pickedMesh?.parent).active=!0,t.forEach((t=>{const i=(-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh)||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=i,e.color&&(e.color=i.diffuseColor)}))}))),e.type===ss.POINTERUP&&t.forEach((e=>{e.active=!1,i=!1,e.gizmoMeshes.forEach((t=>{t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)}))}))}}))}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}ec.PreserveScaling=!1,ec.UseAbsoluteScaling=!0,Object.defineProperty(ks.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new tc(this)),this._debugLayer},enumerable:!0,configurable:!0}),function(e){e[e.Properties=0]="Properties",e[e.Debug=1]="Debug",e[e.Statistics=2]="Statistics",e[e.Tools=3]="Tools",e[e.Settings=4]="Settings"}(Wh||(Wh={}));class tc{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new g),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new g),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||y.LastCreatedScene,this._scene&&this._scene.onDisposeObservable.add((()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()}))}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(const e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(const e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}const t={...tc.Config,...e};this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise((t=>{if(void 0===this.BJSINSPECTOR){const i=e&&e.inspectorURL?e.inspectorURL:tc.InspectorURL;Ii.LoadBabylonScript(i,(()=>{this._createInspector(e),t(this)}))}else this._createInspector(e),t(this)}))}}function ic(e){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],s=[];let r=[];const n=e.width||e.size||1,o=e.height||e.size||1,a=e.depth||e.size||1,l=e.wrap||!1;let h=void 0===e.topBaseAt?1:e.topBaseAt,c=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,c=(c+4)%4;let u=[2,0,3,1][h],d=[2,0,1,3][c],p=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(l){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],p=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let e=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],i=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const s=[17,18,19,16],r=[22,23,20,21];for(;u>0;)e.unshift(e.pop()),s.unshift(s.pop()),u--;for(;d>0;)i.unshift(i.pop()),r.unshift(r.pop()),d--;e=e.flat(),i=i.flat(),p=p.concat(e).concat(i),t.push(s[0],s[2],s[3],s[0],s[1],s[2]),t.push(r[0],r[2],r[3],r[0],r[1],r[2])}const f=[n/2,o/2,a/2];r=p.reduce(((e,t,i)=>e.concat(t*f[i%3])),[]);const _=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE,m=e.faceUV||new Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new F(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new j(1,1,1,1));for(let e=0;e<6;e++)if(s.push(m[e].z,Er.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),s.push(m[e].x,Er.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),s.push(m[e].x,Er.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),s.push(m[e].z,Er.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);Tr._ComputeSides(_,r,t,i,s,e.frontUVs,e.backUVs);const x=new Tr;if(x.indices=t,x.positions=r,x.normals=i,x.uvs=s,g){const e=_===Tr.DOUBLESIDE?v.concat(v):v;x.colors=e}return x}function sc(e,t={},i=null){const s=new Un(e,i);return t.sideOrientation=Un._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,ic(t).applyToMesh(s,t.updatable),s}function rc(e){const t=0|(e.segments||32),i=e.diameterX||e.diameter||1,s=e.diameterY||e.diameter||1,r=e.diameterZ||e.diameter||1,n=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,o=e.slice&&e.slice<=0?1:e.slice||1,a=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new w(i/2,s/2,r/2),c=2+t,u=2*c,d=[],p=[],f=[],_=[];for(let e=0;e<=c;e++){const t=e/c,i=t*Math.PI*o;for(let e=0;e<=u;e++){const s=e/u,r=s*Math.PI*2*n,o=B.RotationZ(-i),a=B.RotationY(r),l=w.TransformCoordinates(w.Up(),o),c=w.TransformCoordinates(l,a),d=c.multiply(h),m=c.divide(h).normalize();p.push(d.x,d.y,d.z),f.push(m.x,m.y,m.z),_.push(s,Er.UseOpenGLOrientationForUV?1-t:t)}if(e>0){const t=p.length/3;for(let i=t-2*(u+1);i+u+21&&(d.push(i),d.push(i+1),d.push(i+u+1)),(en?n:Math.floor(o);const a=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE,l=e.uvs,h=e.colors,c=[],u=[],d=[],p=[],f=[],_=[],m=[],g=[];let v;const x=[],T=[];let S,E,b;if(t.length<2){const e=[],i=[];for(E=0;E0&&(P=R[b].subtract(R[b-1]).length(),M=P+m[S],f[S].push(M),m[S]=M),b++;s&&(b--,c.push(R[0].x,R[0].y,R[0].z),P=R[b].subtract(R[0]).length(),M=P+m[S],f[S].push(M),m[S]=M),x[S]=I+y,T[S]=C,C+=I+y}let N,w,F=null,L=null;for(E=0;E{let r=s[0].length;const n=a;let o=0;const l=n._originalBuilderSideOrientation===Un.DOUBLESIDE?2:1;for(let a=1;a<=l;++a)for(let a=0;a1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE;t.push(0,0,0),r.push(.5,.5);const h=2*Math.PI*a,c=1===a?h/o:h/(o-1);let u=0;for(let e=0;e0||u>0){switch(m=-d,g=-p,v=d,x=p,r){case Un.CENTER:l/=2,m-=l,v+=l;break;case Un.LEFT:v+=l,f=-l/2;break;case Un.RIGHT:m-=l,f=l/2}switch(n){case Un.CENTER:u/=2,g-=u,x+=u;break;case Un.BOTTOM:x+=u,_=-u/2;break;case Un.TOP:g-=u,_=u/2}}const T=[],S=[],E=[];E[0]=[0,0,1,0,1,1,0,1],E[1]=[0,0,1,0,1,1,0,1],t!==Un.ROTATE_TILE&&t!==Un.ROTATE_ROW||(E[1]=[1,1,0,1,0,0,1,0]),t!==Un.FLIP_TILE&&t!==Un.FLIP_ROW||(E[1]=[1,0,0,0,0,1,1,1]),t!==Un.FLIP_N_ROTATE_TILE&&t!==Un.FLIP_N_ROTATE_ROW||(E[1]=[0,1,1,1,1,0,0,0]);let b=[];const C=[],y=[];let A=0;for(let e=0;e0||u>0){const e=u>0&&(n===Un.CENTER||n===Un.TOP),o=u>0&&(n===Un.CENTER||n===Un.BOTTOM),h=l>0&&(r===Un.CENTER||r===Un.RIGHT),E=l>0&&(r===Un.CENTER||r===Un.LEFT);let R,I,P,M,D=[];if(e&&h&&(T.push(m+f,g+_,0),T.push(-d+f,g+_,0),T.push(-d+f,g+u+_,0),T.push(m+f,g+u+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=1-l/i,I=1-u/s,P=1,M=1,D=[R,I,P,I,P,M,R,M],t===Un.ROTATE_ROW&&(D=[1-R,1-I,1-P,1-I,1-P,1-M,1-R,1-M]),t===Un.FLIP_ROW&&(D=[1-R,I,1-P,I,1-P,M,1-R,M]),t===Un.FLIP_N_ROTATE_ROW&&(D=[R,1-I,P,1-I,P,1-M,R,1-M]),b=b.concat(D),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e&&E&&(T.push(d+f,g+_,0),T.push(v+f,g+_,0),T.push(v+f,g+u+_,0),T.push(d+f,g+u+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=0,I=1-u/s,P=l/i,M=1,D=[R,I,P,I,P,M,R,M],(t===Un.ROTATE_ROW||t===Un.ROTATE_TILE&&a%2==0)&&(D=[1-R,1-I,1-P,1-I,1-P,1-M,1-R,1-M]),(t===Un.FLIP_ROW||t===Un.FLIP_TILE&&a%2==0)&&(D=[1-R,I,1-P,I,1-P,M,1-R,M]),(t===Un.FLIP_N_ROTATE_ROW||t===Un.FLIP_N_ROTATE_TILE&&a%2==0)&&(D=[R,1-I,P,1-I,P,1-M,R,1-M]),b=b.concat(D),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&h&&(T.push(m+f,p+_,0),T.push(-d+f,p+_,0),T.push(-d+f,x+_,0),T.push(m+f,x+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=1-l/i,I=0,P=1,M=u/s,D=[R,I,P,I,P,M,R,M],(t===Un.ROTATE_ROW&&c%2==1||t===Un.ROTATE_TILE&&c%1==0)&&(D=[1-R,1-I,1-P,1-I,1-P,1-M,1-R,1-M]),(t===Un.FLIP_ROW&&c%2==1||t===Un.FLIP_TILE&&c%2==0)&&(D=[1-R,I,1-P,I,1-P,M,1-R,M]),(t===Un.FLIP_N_ROTATE_ROW&&c%2==1||t===Un.FLIP_N_ROTATE_TILE&&c%2==0)&&(D=[R,1-I,P,1-I,P,1-M,R,1-M]),b=b.concat(D),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&E&&(T.push(d+f,p+_,0),T.push(v+f,p+_,0),T.push(v+f,x+_,0),T.push(d+f,x+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=0,I=0,P=l/i,M=u/s,D=[R,I,P,I,P,M,R,M],(t===Un.ROTATE_ROW&&c%2==1||t===Un.ROTATE_TILE&&(c+a)%2==1)&&(D=[1-R,1-I,1-P,1-I,1-P,1-M,1-R,1-M]),(t===Un.FLIP_ROW&&c%2==1||t===Un.FLIP_TILE&&(c+a)%2==1)&&(D=[1-R,I,1-P,I,1-P,M,1-R,M]),(t===Un.FLIP_N_ROTATE_ROW&&c%2==1||t===Un.FLIP_N_ROTATE_TILE&&(c+a)%2==1)&&(D=[R,1-I,P,1-I,P,1-M,R,1-M]),b=b.concat(D),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e){const e=[];R=0,I=1-u/s,P=1,M=1,e[0]=[R,I,P,I,P,M,R,M],e[1]=[R,I,P,I,P,M,R,M],t!==Un.ROTATE_TILE&&t!==Un.ROTATE_ROW||(e[1]=[1-R,1-I,1-P,1-I,1-P,1-M,1-R,1-M]),t!==Un.FLIP_TILE&&t!==Un.FLIP_ROW||(e[1]=[1-R,I,1-P,I,1-P,M,1-R,M]),t!==Un.FLIP_N_ROTATE_TILE&&t!==Un.FLIP_N_ROTATE_ROW||(e[1]=[R,1-I,P,1-I,P,1-M,R,1-M]);for(let s=0;s{const t=Math.cos(e),i=Math.sin(e),s=c/h*e,r=Math.cos(s),o=n*(2+r)*.5*t,a=n*(2+r)*i*.5,l=n*Math.sin(s)*.5;return new w(o,a,l)};let p,f;for(p=0;p<=a;p++){const e=p%a/a*2*h*Math.PI,t=d(e),s=d(e+.01),n=s.subtract(t);let c=s.add(t);const u=w.Cross(n,c);for(c=w.Cross(u,n),u.normalize(),c.normalize(),f=0;fsc(e,{size:t,sideOrientation:r,updatable:s},i),Tr.CreateSphere=rc,Un.CreateSphere=(e,t,i,s,r,n)=>nc(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:n,updatable:r},s),Un.CreateCapsule=(e,t,i)=>function(e,t={orientation:w.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6,updatable:!1},i=null){const s=new Un(e,i);return oc(t).applyToMesh(s,t.updatable),s}(e,t,i),Tr.CreateCapsule=oc,Tr.CreateRibbon=ac,Un.CreateRibbon=(e,t,i=!1,s,r,n,o=!1,a,l)=>lc(e,{pathArray:t,closeArray:i,closePath:s,offset:r,updatable:o,sideOrientation:a,instance:l},n),Tr.CreateDisc=hc,Un.CreateDisc=(e,t,i,s=null,r,n)=>cc(e,{radius:t,tessellation:i,sideOrientation:n,updatable:r},s),Tr.CreateTiledPlane=uc,Tr.CreateTiledBox=function(e){const t=e.faceUV||new Array(6),i=e.faceColors,s=e.pattern||Un.NO_FLIP,r=e.width||e.size||1,n=e.height||e.size||1,o=e.depth||e.size||1,a=e.tileWidth||e.tileSize||1,l=e.tileHeight||e.tileSize||1,h=e.alignHorizontal||0,c=e.alignVertical||0,u=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE;for(let e=0;e<6;e++)void 0===t[e]&&(t[e]=new F(0,0,1,1)),i&&void 0===i[e]&&(i[e]=new j(1,1,1,1));const d=r/2,p=n/2,f=o/2,_=[];for(let e=0;e<2;e++)_[e]=uc({pattern:s,tileWidth:a,tileHeight:l,width:r,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});for(let e=2;e<4;e++)_[e]=uc({pattern:s,tileWidth:a,tileHeight:l,width:o,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});let m=c;c===Un.BOTTOM?m=Un.TOP:c===Un.TOP&&(m=Un.BOTTOM);for(let e=4;e<6;e++)_[e]=uc({pattern:s,tileWidth:a,tileHeight:l,width:r,height:o,alignVertical:m,alignHorizontal:h,sideOrientation:u});let g=[],v=[],x=[],T=[];const S=[],E=[],b=[],C=[];let y=0,A=0;for(let e=0;e<6;e++){const s=_[e].positions.length;E[e]=[],b[e]=[];for(let t=0;te+A))),A+=E[e].length,i)for(let t=0;t<4;t++)S.push(i[e].r,i[e].g,i[e].b,i[e].a)}const R=new w(0,0,f),I=B.RotationY(Math.PI);g=E[0].map((e=>w.TransformNormal(e,I).add(R))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),v=b[0].map((e=>w.TransformNormal(e,I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),g=g.concat(E[1].map((e=>e.subtract(R))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(b[1].map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const P=new w(d,0,0),M=B.RotationY(-Math.PI/2);g=g.concat(E[2].map((e=>w.TransformNormal(e,M).add(P))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(b[2].map((e=>w.TransformNormal(e,M))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const D=B.RotationY(Math.PI/2);g=g.concat(E[3].map((e=>w.TransformNormal(e,D).subtract(P))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(b[3].map((e=>w.TransformNormal(e,D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const O=new w(0,p,0),N=B.RotationX(Math.PI/2);g=g.concat(E[4].map((e=>w.TransformNormal(e,N).add(O))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(b[4].map((e=>w.TransformNormal(e,N))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const L=B.RotationX(-Math.PI/2);g=g.concat(E[5].map((e=>w.TransformNormal(e,L).subtract(O))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(b[5].map((e=>w.TransformNormal(e,L))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),Tr._ComputeSides(u,g,T,v,x);const V=new Tr;if(V.indices=T,V.positions=g,V.normals=v,V.uvs=x,i){const e=u===Tr.DOUBLESIDE?S.concat(S):S;V.colors=e}return V},Tr.CreateTorusKnot=dc,Un.CreateTorusKnot=(e,t,i,s,r,n,o,a,l,h)=>function(e,t={},i){const s=new Un(e,i);return t.sideOrientation=Un._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,dc(t).applyToMesh(s,t.updatable),s}(e,{radius:t,tube:i,radialSegments:s,tubularSegments:r,p:n,q:o,sideOrientation:h,updatable:l},a);const pc={effect:null,subMesh:null};class fc extends Io{constructor(e,t,i,s={},r=!0){super(e,t,r),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new B,this._cachedWorldViewProjectionMatrix=new B,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...s}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return-1===this._options.externalTextures.indexOf(e)&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(16*t.length);for(let e=0;et===e||t.startsWith(i)));return s>=0&&this.options.defines.splice(s,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){const s=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const e=s?i._drawWrapper:this._drawWrapper;if(e.effect&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}const r=this.getScene(),n=r.getEngine(),o=[],a=[],l=new Yo;let h=this._shaderPath,c=this._options.uniforms,u=this._options.uniformBuffers,d=this._options.samplers;n.getCaps().multiview&&r.activeCamera&&r.activeCamera.outputRenderTarget&&r.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),-1!==c.indexOf("viewProjection")&&-1===c.indexOf("viewProjectionR")&&c.push("viewProjectionR"));for(let e=0;e4&&(a.push(Ki.MatricesIndicesExtraKind),a.push(Ki.MatricesWeightsExtraKind));const t=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),l.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),-1===c.indexOf("boneTextureWidth")&&c.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(t.bones.length+1)),-1===c.indexOf("mBones")&&c.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let p=0;const f=e?e.morphTargetManager:null;if(f){const e=f.supportsUVs&&-1!==o.indexOf("#define UV1"),t=f.supportsTangents&&-1!==o.indexOf("#define TANGENT"),i=f.supportsNormals&&-1!==o.indexOf("#define NORMAL");p=f.numMaxInfluencers||f.numInfluencers,e&&o.push("#define MORPHTARGETS_UV"),t&&o.push("#define MORPHTARGETS_TANGENT"),i&&o.push("#define MORPHTARGETS_NORMAL"),p>0&&o.push("#define MORPHTARGETS"),f.isUsingTextureForTargets&&(o.push("#define MORPHTARGETS_TEXTURE"),-1===c.indexOf("morphTargetTextureIndices")&&c.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),o.push("#define NUM_MORPH_INFLUENCERS "+p);for(let s=0;s0&&(c=c.slice(),c.push("morphTargetInfluences"),c.push("morphTargetCount"),c.push("morphTargetTextureInfo"),c.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===c.indexOf("bakedVertexAnimationSettings")&&c.push("bakedVertexAnimationSettings"),-1===c.indexOf("bakedVertexAnimationTextureSizeInverted")&&c.push("bakedVertexAnimationTextureSizeInverted"),-1===c.indexOf("bakedVertexAnimationTime")&&c.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),hn(a,0,o)}for(const e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&o.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&(jr(c),$r(this,r,o)),r.fogEnabled&&e?.applyFog&&r.fogMode!==ks.FOGMODE_NONE&&(o.push("#define FOG"),-1===c.indexOf("view")&&c.push("view"),-1===c.indexOf("vFogInfos")&&c.push("vFogInfos"),-1===c.indexOf("vFogColor")&&c.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),-1===c.indexOf("logarithmicDepthConstant")&&c.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(c=c.slice(),u=u.slice(),d=d.slice(),h=this.customShaderNameResolve(this.name,c,u,d,o,a));const _=s?i._getDrawWrapper(void 0,!0):this._drawWrapper,m=_?.effect??null,g=_?.defines??null,v=o.join("\n");let x=m;return g!==v&&(x=n.createEffect(h,{attributes:a,uniformsNames:c,uniformBuffersNames:u,samplers:d,defines:v,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:p},shaderLanguage:this._options.shaderLanguage},n),s?i.setEffect(x,v,this._materialContext):_&&_.setEffect(x,v),this._onEffectCreatedObservable&&(pc.effect=x,pc.subMesh=i??e?.subMeshes[0]??null,this._onEffectCreatedObservable.notifyObservers(pc))),_._wasPreviouslyUsingInstances=!!t,!(!x?.isReady()??1)&&(m!==x&&r.resetCachedMaterial(),_._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),s=t??this.getEffect();s&&(-1!==this._options.uniforms.indexOf("world")&&s.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),s.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),s.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),-1!==this._options.uniforms.indexOf("view")&&s.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){this.bind(e,t,i._drawWrapperOverride?.effect,i)}bind(e,t,i,s){const r=s&&this._storeEffectOnSubMeshes,n=i??(r?s.effect:this.getEffect());if(!n)return;const o=this.getScene();this._activeEffect=n,this.bindOnlyWorldMatrix(e,i);const a=this._options.uniformBuffers;let l=!1;if(n&&a&&a.length>0&&o.getEngine().supportsUniformBuffers)for(let i=0;i0&&nn(t,n);const i=t.bakedVertexAnimationManager;if(i&&i.isEnabled){const e=r?s._drawWrapper:this._drawWrapper;t.bakedVertexAnimationManager?.bind(n,!!e._wasPreviouslyUsingInstances)}}this._afterBind(t,n,s)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let t=0;tnew fc(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes)),this);t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach((e=>{const t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))})),this.stencil.copyTo(t.stencil);for(const e in this._textures)t.setTexture(e,this._textures[e]);for(const e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(const e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(const e in this._ints)t.setInt(e,this._ints[e]);for(const e in this._uints)t.setUInt(e,this._uints[e]);for(const e in this._floats)t.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(const e in this._colors3)t.setColor3(e,this._colors3[e]);for(const e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(const e in this._colors4)t.setColor4(e,this._colors4[e]);for(const e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(const e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(const e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(const e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(const e in this._matrices)t.setMatrix(e,this._matrices[e]);for(const e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(const e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(const e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(const e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(const e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(const e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(const e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(const e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(const e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){const t=this._textureArrays[e];for(let e=0;enew fc(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes)),e,t,i);let r;for(r in e.stencil&&s.stencil.parse(e.stencil,t,i),e.textures)s.setTexture(r,Zn.Parse(e.textures[r],t,i));for(r in e.textureArrays){const n=e.textureArrays[r],o=[];for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>Y.FromArray(e)));s.setColor3Array(r,t)}for(r in e.colors4)s.setColor4(r,j.FromArray(e.colors4[r]));for(r in e.colors4Arrays){const t=e.colors4Arrays[r].reduce(((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>j.FromArray(e)));s.setColor4Array(r,t)}for(r in e.vectors2)s.setVector2(r,N.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,w.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,F.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,L.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,B.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise(((r,n)=>{const o=new Ne;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=this.Parse(t,i||y.LastCreatedScene,s);e&&(n.name=e),r(n)}else n("Unable to load the ShaderMaterial")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return new Promise(((s,r)=>{const n=new Ne;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const r=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(r.shaderMaterial),a=this.Parse(o,t||y.LastCreatedScene,i);a.snippetId=e,s(a)}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}fc.SnippetUrl="https://snippet.babylonjs.com",fc.CreateFromSnippetAsync=fc.ParseFromSnippetAsync,u("BABYLON.ShaderMaterial",fc);Ft.ShadersStore.colorPixelShader="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n#include(color,gl_FragColor)\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.colorVertexShader="attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\n#ifdef FOG\nuniform mat4 view;\n#endif\n#include\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}",Un._LinesMeshParser=(e,t)=>_c.Parse(e,t);class _c extends Un{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,s=null,r,n,o,a){super(e,t,i,s,r),this.useVertexColor=n,this.useVertexAlpha=o,this.color=new Y(1,1,1),this.alpha=1,s&&(this.color=s.color.clone(),this.alpha=s.alpha,this.useVertexColor=s.useVertexColor,this.useVertexAlpha=s.useVertexAlpha),this.intersectionThreshold=.1;const l={attributes:[Ki.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===o?l.needAlphaBlending=!1:l.defines.push("#define VERTEXALPHA"),n?(l.defines.push("#define VERTEXCOLOR"),l.attributes.push(Ki.ColorKind)):(l.uniforms.push("color"),this._color4=new j),a?this.material=a:(this.material=new fc("colorShader",this.getScene(),"color",l,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=Dn.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;const i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const s=this.getScene().getEngine();return this._unIndexed?s.drawArraysType(Dn.LineListDrawMode,e.verticesStart,e.verticesCount,i):s.drawElementsType(Dn.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new _c(e,this.getScene(),t,this,i)}createInstance(e){const t=new mc(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const e in this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new _c(e.name,t);return i.color=Y.FromArray(e.color),i.alpha=e.alpha,i}}class mc extends kn{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function gc(e){const t=[],i=[],s=e.lines,r=e.colors,n=[];let o=0;for(let e=0;e0&&(t.push(o-1),t.push(o)),o++}}const a=new Tr;return a.indices=t,a.positions=i,r&&(a.colors=n),a}function vc(e){const t=e.dashSize||3,i=e.gapSize||1,s=e.dashNb||200,r=e.points,n=[],o=[],a=w.Zero();let l=0,h=0,c=0,u=0,d=0,p=0,f=0;for(f=0;fTc(e,{points:t,updatable:s,instance:r},i),Un.CreateDashedLines=(e,t,i,s,r,n=null,o,a)=>function(e,t,i=null){const s=t.points,r=t.instance,n=t.gapSize||1,o=t.dashSize||3;if(r){const e=e=>{const t=w.Zero(),i=e.length/6;let n=0,o=0,a=0,l=0,h=0,c=0,u=0,d=0;for(u=0;u{const i=new Sc(e,this.elements.length);t.push(i),this.elements.push(i)})),t}computeBounds(){const e=new N(this.elements[0].x,this.elements[0].y),t=new N(this.elements[0].x,this.elements[0].y);return this.elements.forEach((i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)})),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class bc{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,s=earcut){let r;this._points=new Ec,this._outlinepoints=new Ec,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=e,this._scene=i||y.LastCreatedScene,r=t instanceof Ys?t.getPoints():t,this._addToepoint(r),this._points.add(r),this._outlinepoints.add(r),void 0===this.bjsEarcut&&J.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new Ec;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){const s=new Un(this._name,this._scene),r=this.buildVertexData(t,i);return s.setVerticesData(Ki.PositionKind,r.positions,e),s.setVerticesData(Ki.NormalKind,r.normals,e),s.setVerticesData(Ki.UVKind,r.uvs,e),s.setIndices(r.indices),s}buildVertexData(e=0,t=2){const i=new Tr,s=[],r=[],n=[],o=this._points.computeBounds();this._points.elements.forEach((e=>{s.push(0,1,0),r.push(e.x,0,e.y),n.push((e.x-o.min.x)/o.width,(e.y-o.min.y)/o.height)}));const a=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e0){const i=r.length/3;this._points.elements.forEach((t=>{s.push(0,-1,0),r.push(t.x,-e,t.y),n.push(1-(t.x-o.min.x)/o.width,1-(t.y-o.min.y)/o.height)}));const l=a.length;for(let e=0;e{this._addSide(r,s,n,a,o,i,e,!0,t)}))}return i.indices=a,i.positions=r,i.normals=s,i.uvs=n,i}_addSide(e,t,i,s,r,n,o,a,l){let h=e.length/3,c=0;for(let u=0;ul?bl?C1),o=t.rotationFunction||(()=>0),a=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||Un.NO_CAP,c=t.updatable,u=t.firstNormal||null,d=t.adjustFrame||!1;return Ic(e,r,s,null,null,n,o,a,l,h,!0,i,!!c,Un._GetDefaultSideOrientation(t.sideOrientation),t.instance||null,t.invertUV||!1,t.frontUVs||null,t.backUVs||null,u,d)}function Ic(e,t,i,s,r,n,o,a,l,h,c,u,d,p,f,_,m,g,v,x){const T=(e,t,i,s,r,n,o,a,l,h,c)=>{const u=i.getTangents(),d=i.getNormals(),p=i.getBinormals(),f=i.getDistances();if(c)for(let e=0;e0){let t=u[e-1];w.Dot(t,u[e])<0&&u[e].scaleInPlace(-1),t=d[e-1],w.Dot(t,d[e])<0&&d[e].scaleInPlace(-1),t=p[e-1],w.Dot(t,p[e])<0&&p[e].scaleInPlace(-1)}let _=0;const m=h&&a?a:()=>null!==n?n:0,g=h&&o?o:()=>null!==r?r:1;let v=l===Un.NO_CAP||l===Un.CAP_END?0:2;const x=U.Matrix[0];for(let i=0;i{const t=Array(),i=w.Zero();let s;for(s=0;s3?0:h,c,x);const b=lc(e,{pathArray:E,closeArray:a,closePath:l,updatable:d,sideOrientation:p,invertUV:_,frontUVs:m||void 0,backUVs:g||void 0},u);return b._creationDataStorage.pathArray=E,b._creationDataStorage.path3D=S,b._creationDataStorage.cap=h,b}function Pc(e){const t=[];t[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},t[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},t[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},t[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},t[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},t[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},t[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},t[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},t[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},t[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},t[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},t[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},t[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},t[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},t[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};const i=e.type&&(e.type<0||e.type>=t.length)?0:e.type||0,s=e.size,r=e.sizeX||s||1,n=e.sizeY||s||1,o=e.sizeZ||s||1,a=e.custom||t[i],l=a.face.length,h=e.faceUV||new Array(l),c=e.faceColors,u=void 0===e.flat||e.flat,d=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE,p=[],f=[],_=[],m=[],g=[];let v=0,x=0;const T=[];let S,E,b,C,y,A,R=0,I=0;if(u)for(I=0;Iyc(e,{shape:t,holes:s,updatable:r,sideOrientation:n},i,o),Un.ExtrudePolygon=(e,t,i,s,r,n,o,a=earcut)=>function(e,t,i=null,s=earcut){return yc(e,t,i,s)}(e,{shape:t,holes:r,depth:i,updatable:n,sideOrientation:o},s,a),Un.ExtrudeShape=(e,t,i,s,r,n,o=null,a,l,h)=>Ac(e,{shape:t,path:i,scale:s,rotation:r,cap:0===n?0:n||Un.NO_CAP,sideOrientation:l,instance:h,updatable:a},o),Un.ExtrudeShapeCustom=(e,t,i,s,r,n,o,a,l,h,c,u)=>Rc(e,{shape:t,path:i,scaleFunction:s,rotationFunction:r,ribbonCloseArray:n,ribbonClosePath:o,cap:0===a?0:a||Un.NO_CAP,sideOrientation:c,instance:u,updatable:h},l),Un.CreateLathe=(e,t,i,s,r,n,o)=>function(e,t,i=null){const s=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,r=void 0===t.closed||t.closed,n=t.shape,o=t.radius||1,a=t.tessellation||64,l=t.clip||0,h=t.updatable,c=Un._GetDefaultSideOrientation(t.sideOrientation),u=t.cap||Un.NO_CAP,d=2*Math.PI,p=[],f=t.invertUV||!1;let _=0,m=0;const g=d/a*s;let v,x;for(_=0;_<=a-l;_++){for(x=[],u!=Un.CAP_START&&u!=Un.CAP_ALL||(x.push(new w(0,n[0].y,0)),x.push(new w(Math.cos(_*g)*n[0].x*o,n[0].y,Math.sin(_*g)*n[0].x*o))),m=0;mfunction(e,t,i=null){const s=t.path;let r=t.instance,n=1;void 0!==t.radius?n=t.radius:r&&(n=r._creationDataStorage.radius);const o=t.tessellation||64,a=t.radiusFunction||null;let l=t.cap||Un.NO_CAP;const h=t.invertUV||!1,c=t.updatable,u=Un._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;const d=(e,t,i,s,r,n,o,a)=>{const l=t.getTangents(),h=t.getNormals(),c=t.getDistances(),u=2*Math.PI/r*a,d=n||(()=>s);let p,f,_,m;const g=U.Matrix[0];let v=o===Un.NO_CAP||o===Un.CAP_END?0:2;for(let t=0;t{const s=Array();for(let r=0;r3?0:l,f=d(s,p,new Array,n,o,a,l,t.arc);const _=lc(e,{pathArray:f,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:h,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return _._creationDataStorage.pathArray=f,_._creationDataStorage.path3D=p,_._creationDataStorage.tessellation=o,_._creationDataStorage.cap=l,_._creationDataStorage.arc=t.arc,_._creationDataStorage.radius=n,_}(e,{path:t,radius:i,tessellation:s,radiusFunction:r,arc:1,cap:n,updatable:a,sideOrientation:l,instance:h},o),Tr.CreatePolyhedron=Pc,Un.CreatePolyhedron=(e,t,i)=>function(e,t={},i=null){const s=new Un(e,i);return t.sideOrientation=Un._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,Pc(t).applyToMesh(s,t.updatable),s}(e,t,i);const Mc=new w(1,0,0),Dc=new w(-1,0,0),Oc=new w(0,1,0),Nc=new w(0,-1,0),wc=new w(0,0,1),Fc=new w(0,0,-1);class Lc{constructor(e=w.Zero(),t=w.Up(),i=N.Zero(),s=0,r=0,n=null,o=null,a=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=s,this.vertexIdxForBones=r,this.localPositionOverride=n,this.localNormalOverride=o,this.matrixIndicesOverride=a,this.matrixWeightsOverride=l}clone(){return new Lc(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,this.localPositionOverride?.slice(),this.localNormalOverride?.slice(),this.matrixIndicesOverride?.slice(),this.matrixWeightsOverride?.slice())}}Un.CreateDecal=(e,t,i,s,r,n)=>function(e,t,i){const s=!!t.skeleton,r=i.localMode||s,n=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,o=t.getIndices(),a=s?t.getPositionData(!0,!0):t.getVerticesData(Ki.PositionKind),l=s?t.getNormalsData(!0,!0):t.getVerticesData(Ki.NormalKind),h=r?s?t.getVerticesData(Ki.PositionKind):a:null,c=r?s?t.getVerticesData(Ki.NormalKind):l:null,u=t.getVerticesData(Ki.UVKind),d=s?t.getVerticesData(Ki.MatricesIndicesKind):null,p=s?t.getVerticesData(Ki.MatricesWeightsKind):null,f=s?t.getVerticesData(Ki.MatricesIndicesExtraKind):null,_=s?t.getVerticesData(Ki.MatricesWeightsExtraKind):null,m=i.position||w.Zero();let g=i.normal||w.Up();const v=i.size||w.One(),x=i.angle||0;if(!g){const e=new w(0,0,1),i=t.getScene().activeCamera,s=w.TransformCoordinates(e,i.getWorldMatrix());g=i.globalPosition.subtract(s)}const T=-Math.atan2(g.z,g.x)-Math.PI/2,S=Math.sqrt(g.x*g.x+g.z*g.z),E=Math.atan2(g.y,S),b=new Tr;b.indices=[],b.positions=[],b.normals=[],b.uvs=[],b.matricesIndices=s?[]:null,b.matricesWeights=s?[]:null,b.matricesIndicesExtra=f?[]:null,b.matricesWeightsExtra=_?[]:null;let C=0;const y=(e,t)=>{const s=new Lc;if(!o||!a||!l)return s;const r=o[e];if(s.vertexIdx=3*r,s.vertexIdxForBones=4*r,s.position=new w(a[3*r],a[3*r+1],a[3*r+2]),w.TransformCoordinatesToRef(s.position,t,s.position),s.normal=new w(l[3*r],l[3*r+1],l[3*r+2]),w.TransformNormalToRef(s.normal,t,s.normal),i.captureUVS&&u){const e=u[2*r+1];s.uv=new N(u[2*r],Er.UseOpenGLOrientationForUV?1-e:e)}return s},A=[0,0,0,0],R=(e,t)=>{if(0===e.length)return e;const i=.5*Math.abs(w.Dot(v,t)),s=(e,t,i,s)=>{for(let r=0;r{const n=w.GetClipFactor(e.position,r.position,t,i);let o=A,a=A;if(d&&p){const t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=e.matrixIndicesOverride??d,l=e.matrixWeightsOverride??p,h=r.matrixIndicesOverride?0:r.vertexIdxForBones,c=r.matrixIndicesOverride??d,u=r.matrixWeightsOverride??p;o=[0,0,0,0],a=[0,0,0,0];let f=0;for(let e=0;e<4;++e)if(l[t+e]>0){const r=s(c,i[t+e],h,4);o[f]=i[t+e],a[f]=G.Lerp(l[t+e],r>=0?u[r]:0,n),f++}for(let e=0;e<4&&f<4;++e){const r=c[h+e];-1===s(i,r,t,4)&&(o[f]=r,a[f]=G.Lerp(0,u[h+e],n),f++)}const _=a[0]+a[1]+a[2]+a[3];a[0]/=_,a[1]/=_,a[2]/=_,a[3]/=_}const l=e.localPositionOverride?e.localPositionOverride[0]:h?.[e.vertexIdx]??0,u=e.localPositionOverride?e.localPositionOverride[1]:h?.[e.vertexIdx+1]??0,f=e.localPositionOverride?e.localPositionOverride[2]:h?.[e.vertexIdx+2]??0,_=r.localPositionOverride?r.localPositionOverride[0]:h?.[r.vertexIdx]??0,m=r.localPositionOverride?r.localPositionOverride[1]:h?.[r.vertexIdx+1]??0,g=r.localPositionOverride?r.localPositionOverride[2]:h?.[r.vertexIdx+2]??0,v=e.localNormalOverride?e.localNormalOverride[0]:c?.[e.vertexIdx]??0,x=e.localNormalOverride?e.localNormalOverride[1]:c?.[e.vertexIdx+1]??0,T=e.localNormalOverride?e.localNormalOverride[2]:c?.[e.vertexIdx+2]??0,S=v+((r.localNormalOverride?r.localNormalOverride[0]:c?.[r.vertexIdx]??0)-v)*n,E=x+((r.localNormalOverride?r.localNormalOverride[1]:c?.[r.vertexIdx+1]??0)-x)*n,b=T+((r.localNormalOverride?r.localNormalOverride[2]:c?.[r.vertexIdx+2]??0)-T)*n,C=Math.sqrt(S*S+E*E+b*b);return new Lc(w.Lerp(e.position,r.position,n),w.Lerp(e.normal,r.normal,n).normalize(),N.Lerp(e.uv,r.uv,n),-1,-1,h?[l+(_-l)*n,u+(m-u)*n,f+(g-f)*n]:null,c?[S/C,E/C,b/C]:null,o,a)};let n=null;e.length>3&&(n=[]);for(let s=0;s0,d=w.Dot(e[s+1].position,t)-i>0,p=w.Dot(e[s+2].position,t)-i>0;switch(o=(u?1:0)+(d?1:0)+(p?1:0),o){case 0:e.length>3?(n.push(e[s]),n.push(e[s+1]),n.push(e[s+2])):n=e;break;case 1:if(n=n??new Array,u&&(a=e[s+1],l=e[s+2],h=r(e[s],a),c=r(e[s],l)),d){a=e[s],l=e[s+2],h=r(e[s+1],a),c=r(e[s+1],l),n.push(h),n.push(l.clone()),n.push(a.clone()),n.push(l.clone()),n.push(h.clone()),n.push(c);break}p&&(a=e[s],l=e[s+1],h=r(e[s+2],a),c=r(e[s+2],l)),a&&l&&h&&c&&(n.push(a.clone()),n.push(l.clone()),n.push(h),n.push(c),n.push(h.clone()),n.push(l.clone()));break;case 2:n=n??new Array,u||(a=e[s].clone(),l=r(a,e[s+1]),h=r(a,e[s+2]),n.push(a),n.push(l),n.push(h)),d||(a=e[s+1].clone(),l=r(a,e[s+2]),h=r(a,e[s]),n.push(a),n.push(l),n.push(h)),p||(a=e[s+2].clone(),l=r(a,e[s]),h=r(a,e[s+1]),n.push(a),n.push(l),n.push(h))}}return n},I=t instanceof Un?t:null,P=I?._thinInstanceDataStorage.matrixData,M=I?.thinInstanceCount||1,D=U.Matrix[0];D.copyFrom(B.IdentityReadOnly);for(let e=0;eBc.Parse(e,t);class Bc extends Un{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(J.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(J.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(J.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let t=0;t1&&(c=1),l.push(c,u);for(let e=0;e<6;e++)c=n.x+o*Math.cos(a+e*Math.PI/3),u=n.y+o*Math.sin(a+e*Math.PI/3),c<0&&(c=0),c>1&&(c=1),h.push(c,u);for(let e=s;ej.FromArray(e))),i.faceCenters=i.faceCenters.map((e=>w.FromArray(e))),i.faceZaxis=i.faceZaxis.map((e=>w.FromArray(e))),i.faceXaxis=i.faceXaxis.map((e=>w.FromArray(e))),i.faceYaxis=i.faceYaxis.map((e=>w.FromArray(e)));const s=new Bc(e.name,t);return s.goldbergData=i,s}}class Vc{constructor(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}moveTo(e,t){this._currentPath=new Ys(e,t),this._tempPaths.push(this._currentPath)}lineTo(e,t){this._currentPath.addLineTo(e,t)}quadraticCurveTo(e,t,i,s){this._currentPath.addQuadraticCurveTo(e,t,i,s,this._resolution)}bezierCurveTo(e,t,i,s,r,n){this._currentPath.addBezierCurveTo(e,t,i,s,r,n,this._resolution)}extractHoles(){for(const e of this._tempPaths)e.area()>0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function Uc(e,t,i,s,r,n){const o=n.glyphs[e]||n.glyphs["?"];if(!o)return null;const a=new Vc(r);if(o.o){const e=o.o.split(" ");for(let r=0,n=e.length;r\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n\n #include\n\n varying vec3 vColor;\n\n uniform vec3 colorBase;\n uniform vec3 colorZero;\n uniform vec3 colorQuarter;\n uniform vec3 colorHalf;\n uniform vec3 colorFull;\n\n uniform float targetBoneIndex;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n vec3 color = colorBase;\n float totalWeight = 0.;\n if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){\n totalWeight += matricesWeights[0];\n }\n if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){\n totalWeight += matricesWeights[1];\n }\n if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){\n totalWeight += matricesWeights[2];\n }\n if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){\n totalWeight += matricesWeights[3];\n }\n\n color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));\n color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));\n color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));\n color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));\n vColor = color;\n\n gl_Position = projection * view * worldPos;\n }",$t.ShadersStore["boneWeights:"+i.name+"FragmentShader"]="\n precision highp float;\n varying vec3 vPosition;\n\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4(vColor, 1.0);\n gl_FragColor = color;\n }\n ";const h=new fc("boneWeight:"+i.name,t,{vertex:"boneWeights:"+i.name,fragment:"boneWeights:"+i.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return h.setColor3("colorBase",s),h.setColor3("colorZero",r),h.setColor3("colorQuarter",n),h.setColor3("colorHalf",o),h.setColor3("colorFull",a),h.setFloat("targetBoneIndex",l),h.getClassName=()=>"BoneWeightShader",h.transparencyMode=Dn.MATERIAL_OPAQUE,h}static CreateSkeletonMapShader(e,t){const i=e.skeleton,s=e.colorMap??[{color:new Y(1,.38,.18),location:0},{color:new Y(.59,.18,1),location:.2},{color:new Y(.59,1,.18),location:.4},{color:new Y(1,.87,.17),location:.6},{color:new Y(1,.17,.42),location:.8},{color:new Y(.17,.68,1),location:1}],r=i.bones.length+1,n=kc._CreateBoneMapColorBuffer(r,s,t),o=new fc("boneWeights:"+i.name,t,{vertexSource:"precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n uniform float colorMap["+4*i.bones.length+"];\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n #include\n\n varying vec3 vColor;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec3 color = vec3(0.);\n bool first = true;\n\n for (int i = 0; i < 4; i++) {\n int boneIdx = int(matricesIndices[i]);\n float boneWgt = matricesWeights[i];\n\n vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);\n\n if (boneWgt > 0.) {\n if (first) {\n first = false;\n color = c;\n } else {\n color = mix(color, c, boneWgt);\n }\n }\n }\n\n vColor = color;\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n gl_Position = projection * view * worldPos;\n }",fragmentSource:"\n precision highp float;\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4( vColor, 1.0 );\n gl_FragColor = color;\n }\n "},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",n),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=Dn.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){const s=new ph("temp",{width:e,height:1},i,!1),r=s.getContext(),n=r.createLinearGradient(0,0,e,0);t.forEach((e=>{n.addColorStop(e.location,e.color.toHexString())})),r.fillStyle=n,r.fillRect(0,0,e,1),s.update();const o=[],a=r.getImageData(0,0,e,1).data,l=1/255;for(let e=0;ekc.DISPLAY_SPHERE_AND_SPURS&&(e=kc.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,s=!0,r=3,n={}){if(this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=s,this.renderingGroupId=r,this.options=n,this.color=Y.White(),this._debugLines=new Array,this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,n.pauseAnimations=n.pauseAnimations??!0,n.returnToRest=n.returnToRest??!1,n.displayMode=n.displayMode??kc.DISPLAY_LINES,n.displayOptions=n.displayOptions??{},n.displayOptions.midStep=n.displayOptions.midStep??.235,n.displayOptions.midStepFactor=n.displayOptions.midStepFactor??.155,n.displayOptions.sphereBaseSize=n.displayOptions.sphereBaseSize??.15,n.displayOptions.sphereScaleUnit=n.displayOptions.sphereScaleUnit??2,n.displayOptions.sphereFactor=n.displayOptions.sphereFactor??.865,n.displayOptions.spurFollowsChild=n.displayOptions.spurFollowsChild??!1,n.displayOptions.showLocalAxes=n.displayOptions.showLocalAxes??!1,n.displayOptions.localAxesSize=n.displayOptions.localAxesSize??.075,n.computeBonesUsingShaders=n.computeBonesUsingShaders??!0,n.useAllBones=n.useAllBones??!0,this._boneIndices=new Set,!n.useAllBones){const e=t?.getVerticesData(Ki.MatricesIndicesKind),i=t?.getVerticesData(Ki.MatricesWeightsKind);if(e&&i)for(let t=0;tkc.DISPLAY_SPHERE_AND_SPURS&&(o=kc.DISPLAY_LINES),this.displayMode=o,this.update(),this._bindObs()}_bindObs(){this.displayMode===kc.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add((()=>{this._displayLinesUpdate()})))}update(){switch(this.displayMode){case kc.DISPLAY_LINES:this._displayLinesUpdate();break;case kc.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case kc.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,s=0,r=0,n=0){const o=U.Matrix[0],a=t.getParent();if(o.copyFrom(t.getLocalMatrix()),0!==s||0!==r||0!==n){const e=U.Matrix[1];B.IdentityToRef(e),e.setTranslationFromFloats(s,r,n),e.multiplyToRef(o,o)}a&&o.multiplyToRef(a.getAbsoluteMatrix(),o),o.multiplyToRef(i,o),e.x=o.m[12],e.y=o.m[13],e.z=o.m[14]}_getLinesForBonesWithLength(e,t){const i=e.length;let s,r;t?(s=t.getWorldMatrix(),r=t.position):(s=new B,r=e[0].position);let n=0;for(let t=0;t=0;s--){const t=e[s],o=t.getParent();if(!o||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let a=this._debugLines[i];a||(a=[w.Zero(),w.Zero()],this._debugLines[i]=a),t.getAbsolutePositionToRef(r,a[0]),o.getAbsolutePositionToRef(r,a[1]),a[0].subtractInPlace(n),a[1].subtractInPlace(n),i++}s||r.dispose()}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){null!==e&&-1!==e._index?(this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)):t.copyFrom(B.Identity())}_createSpur(e,t,i,s,r,n){const o=i.subtract(e),a=o.length(),l=o.normalize().scale(a),h=r.midStep||.165,c=r.midStepFactor||.215,u=l.scale(h),d=Rc("skeletonViewer",{shape:[new w(1,-1,0),new w(1,1,0),new w(-1,1,0),new w(-1,-1,0),new w(1,-1,0)],path:[w.Zero(),u,l],scaleFunction:e=>{switch(e){case 0:case 2:return 0;case 1:return a*c}return 0},sideOrientation:Un.DEFAULTSIDE,updatable:!1},n),p=d.getTotalVertices(),f=[],_=[];for(let e=0;e9?_.push(s.getIndex(),0,0,0):_.push(t.getIndex(),0,0,0);return d.position=e.clone(),d.setVerticesData(Ki.MatricesWeightsKind,f,!1),d.setVerticesData(Ki.MatricesIndicesKind,_,!1),d.convertToFlatShadedMesh(),d}_getBoundingSphereForBone(e){if(!this.mesh)return null;const t=this.mesh.getVerticesData(Ki.PositionKind),i=this.mesh.getIndices(),s=this.mesh.getVerticesData(Ki.MatricesWeightsKind),r=this.mesh.getVerticesData(Ki.MatricesIndicesKind);if(!(t&&i&&s&&r))return null;const n=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new w(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);let a=0;for(let l=0;l1e-5){w.FromArrayToRef(t,3*h,U.Vector3[0]),n.minimizeInPlace(U.Vector3[0]),o.maximizeInPlace(U.Vector3[0]),a++;break}}}return a>1?{center:w.Center(n,o),radius:w.Distance(n,o)/2}:null}_buildSpheresAndSpurs(e=!0){this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;const t=this.utilityLayer?.utilityLayerScene,i=this.skeleton.bones,s=[],r=[],n=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,t.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let o=Number.NEGATIVE_INFINITY;const a=this.options.displayOptions||{};for(let n=0;n0)l.children.forEach((i=>{const s=new B;i.getLocalMatrix().multiplyToRef(h,s);const n=new w;s.decompose(void 0,void 0,n);const u=w.Distance(c,n);u>o&&(o=u),e||r.push(this._createSpur(c,l,n,i,a,t))}));else{const i=this._getBoundingSphereForBone(l.getIndex());if(i&&(i.radius>o&&(o=i.radius),!e)){let e;const s=l.getParent();s?(this._getAbsoluteBindPoseToRef(s,h),h.decompose(void 0,void 0,U.Vector3[0]),e=c.subtract(U.Vector3[0]).normalize().scale(i.radius).add(c)):e=i.center.subtract(c).normalize().scale(i.radius).add(c),r.push(this._createSpur(c,l,e,null,a,t))}}const u=nc("skeletonViewer",{segments:6,diameter:a.sphereBaseSize||.2,updatable:!0},t),d=u.getTotalVertices(),p=[],f=[];for(let e=0;e{i[t]=e,i._internalCount++,6===i._internalCount&&s(i)}),void 0,void 0,!0,((e,t)=>{r&&e&&r(e.status+" "+e.statusText,t)}))},si.prototype._cascadeLoadFiles=function(e,t,i,s=null){const r=[];r._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,r,t,s)},si.prototype._cascadeLoadImgs=function(e,t,i,s,r=null,n){const o=[];o._internalCount=0;for(let a=0;a<6;a++)this._partialLoadImg(s[a],a,o,e,t,i,r,n)},si.prototype._partialLoadImg=function(e,t,i,s,r,n,o=null,a){const l=Si();ci(e,(e=>{i[t]=e,i._internalCount++,s&&s.removePendingData(l),6===i._internalCount&&n&&n(r,i)}),((e,t)=>{s&&s.removePendingData(l),o&&o(e,t)}),s?s.offlineProvider:null,a),s&&s.addPendingData(l)},si.prototype.createCubeTextureBase=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d=null,p=null,f=!1){const _=u||new ti(this,ei.Cube);_.isCube=!0,_.url=e,_.generateMipMaps=!s,_._lodGenerationScale=h,_._lodGenerationOffset=c,_._useSRGBBuffer=!!f&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!s),_!==u&&(_.label=e.substring(0,60)),this._doNotHandleContextLost||(_._extension=a,_._files=i);const m=e;this._transformTextureUrl&&!u&&(e=this._transformTextureUrl(e));const g=e.split("?")[0],v=g.lastIndexOf("."),x=a||(v>-1?g.substring(v).toLowerCase():"");let T=null;for(const e of si._TextureLoaders)if(e.canLoad(x)){T=e;break}const S=(u,g)=>{e===m?n&&u&&n(u.status+" "+u.statusText,g):(J.Warn(`Failed to load ${e}, falling back to the ${m}`),this.createCubeTextureBase(m,t,i,!!s,r,n,o,a,l,h,c,_,d,p,f))};if(T){const s=e=>{d&&d(_,e),T.loadCubeData(e,_,l,r,n)};i&&6===i.length?T.supportCascades?this._cascadeLoadFiles(t,(e=>s(e.map((e=>new Uint8Array(e))))),i,n):n?n("Textures type does not support cascades."):J.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>s(new Uint8Array(e))),void 0,void 0,!0,S)}else{if(!i||0===i.length)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(t,_,((e,t)=>{p&&p(e,t)}),i,n)}return this._internalTexturesCache.push(_),_};class zc{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=Wr.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=Wr.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}si.prototype.getGPUFrameTimeCounter=function(){return null},si.prototype.captureGPUFrameTime=function(e){},si.prototype.createQuery=function(){return null},si.prototype.deleteQuery=function(e){return this},si.prototype.isQueryResultAvailable=function(e){return!1},si.prototype.getQueryResult=function(e){return 0},si.prototype.beginOcclusionQuery=function(e,t){return!1},si.prototype.endOcclusionQuery=function(e){return this},Object.defineProperty(Wr.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(Wr.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new zc),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(Wr.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(Wr.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Wr.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Wr.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(Wr.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),Wr.prototype._checkOcclusionQuery=function(){const e=this._occlusionDataStorage;if(e.occlusionType===Wr.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;const t=this.getEngine();if(!t.getCaps().supportOcclusionQuery)return e.isOccluded=!1,!1;if(!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&null!==this._occlusionQuery&&void 0!==this._occlusionQuery)if(t.isQueryResultAvailable(this._occlusionQuery)){const i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,!(-1!==e.occlusionRetryCount&&e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==Wr.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==Wr.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}const i=this.getScene();if(i.getBoundingBoxRenderer){const s=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),this._occlusionQuery&&t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(s.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded};const Wc=new g,Hc=new g;Object.defineProperty(si.prototype,"onBeforeViewRenderObservable",{get:function(){return Wc}}),Object.defineProperty(si.prototype,"onAfterViewRenderObservable",{get:function(){return Hc}}),Object.defineProperty(si.prototype,"inputElement",{get:function(){return this._inputElement},set:function(e){this._inputElement!==e&&(this._inputElement=e,this._onEngineViewChanged?.())}}),si.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},si.prototype.registerView=function(e,t,i){this.views||(this.views=[]);for(const t of this.views)if(t.target===e)return t;const s=this.getRenderingCanvas();s&&(e.width=s.width,e.height=s.height);const r={target:e,camera:t,clearBeforeCopy:i,enabled:!0,id:(1e5*Math.random()).toFixed()};return this.views.push(r),t&&!Array.isArray(t)&&t.onDisposeObservable.add((()=>{this.unRegisterView(e)})),r},si.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(const t of this.views)if(t.target===e){const e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},si.prototype._renderViewStep=function(e){const t=e.target,i=t.getContext("2d");if(!i)return!0;const s=this.getRenderingCanvas();Wc.notifyObservers(e);const r=e.camera;let n=null,o=null,a=null;if(r&&(a=Array.isArray(r)?r[0].getScene():r.getScene(),n=a.activeCamera,o=a.activeCameras,this.activeView=e,Array.isArray(r)?a.activeCameras=r:(a.activeCamera=r,a.activeCameras=null)),e.customResize)e.customResize(t);else{const e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),r=e!==t.width||s.width!==t.width||i!==t.height||s.height!==t.height;t.clientWidth&&t.clientHeight&&r&&(t.width=e,t.height=i,this.setSize(e,i))}return!(!s.width||!s.height||(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,s.width,s.height),i.drawImage(s,0,0),a&&(a.activeCameras=o,a.activeCamera=n),Hc.notifyObservers(e),0))},si.prototype._renderViews=function(){if(!this.views||0===this.views.length)return!1;if(!this.getRenderingCanvas())return!1;let e;for(const t of this.views)if(t.enabled)if(t.target!==this.inputElement){if(!this._renderViewStep(t))return!1}else e=t;return!(e&&!this._renderViewStep(e)||(this.activeView=null,0))},si.prototype._debugPushGroup=function(e,t){},si.prototype._debugPopGroup=function(e){},si.prototype._debugInsertMarker=function(e,t){},si.prototype._debugFlushPendingCommands=function(){};class Xc{constructor(){this._timeElapsedQueryEnded=!1}}Br.prototype.createQuery=function(){const e=this._gl.createQuery();if(!e)throw new Error("Unable to create Occlusion Query");return e},Br.prototype.deleteQuery=function(e){return this._gl.deleteQuery(e),this},Br.prototype.isQueryResultAvailable=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT_AVAILABLE)},Br.prototype.getQueryResult=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT)},Br.prototype.beginOcclusionQuery=function(e,t){const i=this._getGlAlgorithmType(e);return this._gl.beginQuery(i,t),!0},Br.prototype.endOcclusionQuery=function(e){const t=this._getGlAlgorithmType(e);return this._gl.endQuery(t),this},Br.prototype._createTimeQuery=function(){const e=this.getCaps().timerQuery;return e.createQueryEXT?e.createQueryEXT():this.createQuery()},Br.prototype._deleteTimeQuery=function(e){const t=this.getCaps().timerQuery;t.deleteQueryEXT?t.deleteQueryEXT(e):this.deleteQuery(e)},Br.prototype._getTimeQueryResult=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT):this.getQueryResult(e)},Br.prototype._getTimeQueryAvailability=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(e)},Br.prototype.startTimeQuery=function(){const e=this.getCaps(),t=e.timerQuery;if(!t)return null;const i=new Xc;if(this._gl.getParameter(t.GPU_DISJOINT_EXT),e.canUseTimestampForTimerQuery)i._startTimeQuery=this._createTimeQuery(),i._startTimeQuery&&t.queryCounterEXT(i._startTimeQuery,t.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;i._timeElapsedQuery=this._createTimeQuery(),i._timeElapsedQuery&&(t.beginQueryEXT?t.beginQueryEXT(t.TIME_ELAPSED_EXT,i._timeElapsedQuery):this._gl.beginQuery(t.TIME_ELAPSED_EXT,i._timeElapsedQuery)),this._currentNonTimestampToken=i}return i},Br.prototype.endTimeQuery=function(e){const t=this.getCaps(),i=t.timerQuery;if(!i||!e)return-1;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery)return-1;e._endTimeQuery||(e._endTimeQuery=this._createTimeQuery(),e._endTimeQuery&&i.queryCounterEXT(e._endTimeQuery,i.TIMESTAMP_EXT))}else if(!e._timeElapsedQueryEnded){if(!e._timeElapsedQuery)return-1;i.endQueryEXT?i.endQueryEXT(i.TIME_ELAPSED_EXT):(this._gl.endQuery(i.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),e._timeElapsedQueryEnded=!0}const s=this._gl.getParameter(i.GPU_DISJOINT_EXT);let r=!1;if(e._endTimeQuery?r=this._getTimeQueryAvailability(e._endTimeQuery):e._timeElapsedQuery&&(r=this._getTimeQueryAvailability(e._timeElapsedQuery)),r&&!s){let i=0;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery||!e._endTimeQuery)return-1;const t=this._getTimeQueryResult(e._startTimeQuery);i=this._getTimeQueryResult(e._endTimeQuery)-t,this._deleteTimeQuery(e._startTimeQuery),this._deleteTimeQuery(e._endTimeQuery),e._startTimeQuery=null,e._endTimeQuery=null}else{if(!e._timeElapsedQuery)return-1;i=this._getTimeQueryResult(e._timeElapsedQuery),this._deleteTimeQuery(e._timeElapsedQuery),e._timeElapsedQuery=null,e._timeElapsedQueryEnded=!1}return i}return-1},Br.prototype._captureGPUFrameTime=!1,Br.prototype._gpuFrameTime=new Is,Br.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime},Br.prototype.captureGPUFrameTime=function(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.onBeginFrameObservable.add((()=>{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())})),this._onEndFrameObserver=this.onEndFrameObservable.add((()=>{if(!this._gpuFrameTimeToken)return;const e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))}))):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},Br.prototype._getGlAlgorithmType=function(e){return e===Wr.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED},Br.prototype.createTransformFeedback=function(){const e=this._gl.createTransformFeedback();if(!e)throw new Error("Unable to create Transform Feedback");return e},Br.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},Br.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},Br.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},Br.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},Br.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},Br.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},Yi.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;const s=this._getInternalFormat(e.format),r=this._getRGBABufferInternalSizedFormat(0,e.format),n=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);const t=e._workingCanvas.getContext("2d");if(!t)throw new Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},Yi.prototype.restoreSingleAttachment=function(){const e=this._gl;this.bindAttachments([e.BACK])},Yi.prototype.restoreSingleAttachmentForRenderTarget=function(){const e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},Yi.prototype.buildTextureLayout=function(e){const t=this._gl,i=[];for(let s=0;s1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],s.readBuffer(r[t]),s.drawBuffers(r),s.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,s.COLOR_BUFFER_BIT,s.NEAREST)}for(let e=0;e1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];s.drawBuffers(r)}for(let i=0;i1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(a=t.depthTextureFormat)),g.label=t?.label??"MultiRenderTargetWrapper";const v=this._gl,x=v.createFramebuffer();this._bindUnboundFramebuffer(x);const T=e.width||e,S=e.height||e,E=[],b=[],C=this.webGLVersion>1&&o&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),y=this._setupFramebufferDepthAttachments(!C&&n,!o&&r,T,S);g._framebuffer=x,g._depthStencilBuffer=y,g._generateDepthBuffer=!o&&r,g._generateStencilBuffer=!C&&n,g._attachments=b;for(let e=0;e1||this.isWebGPU);const f=this.webGLVersion>1,_=v[f?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(b.push(_),-1===o)continue;const g=new ti(this,ei.MultiRenderTarget);E[e]=g,v.activeTexture(v["TEXTURE"+e]),v.bindTexture(o,g._hardwareTexture.underlyingResource),v.texParameteri(o,v.TEXTURE_MAG_FILTER,l.mag),v.texParameteri(o,v.TEXTURE_MIN_FILTER,l.min),v.texParameteri(o,v.TEXTURE_WRAP_S,v.CLAMP_TO_EDGE),v.texParameteri(o,v.TEXTURE_WRAP_T,v.CLAMP_TO_EDGE);const x=this._getRGBABufferInternalSizedFormat(i,n,r),C=this._getInternalFormat(n),y=this._getWebGLTextureType(i);if(!f||35866!==o&&32879!==o)if(34067===o){for(let e=0;e<6;e++)v.texImage2D(v.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,x,T,S,0,C,y,null);g.isCube=!0}else v.texImage2D(v.TEXTURE_2D,0,x,T,S,0,C,y,null);else 35866===o?g.is2DArray=!0:g.is3D=!0,g.baseDepth=g.depth=a,v.texImage3D(o,0,x,T,S,a,0,C,y,null);s&&v.generateMipmap(o),this._bindTextureDirectly(o,null),g.baseWidth=T,g.baseHeight=S,g.width=T,g.height=S,g.isReady=!0,g.samples=1,g.generateMipMaps=s,g.samplingMode=t,g.type=i,g._useSRGBBuffer=r,g.format=n,this._internalTexturesCache.push(g)}if(o&&this._caps.depthTextureExtension){const e=new ti(this,ei.Depth);let t=5,i=v.DEPTH_COMPONENT16,r=v.DEPTH_COMPONENT,n=v.UNSIGNED_SHORT,o=v.DEPTH_ATTACHMENT;this.webGLVersion<2?i=v.DEPTH_COMPONENT:14===a?(t=1,n=v.FLOAT,i=v.DEPTH_COMPONENT32F):18===a?(t=0,n=v.FLOAT_32_UNSIGNED_INT_24_8_REV,i=v.DEPTH32F_STENCIL8,r=v.DEPTH_STENCIL,o=v.DEPTH_STENCIL_ATTACHMENT):16===a?(t=0,n=v.UNSIGNED_INT,i=v.DEPTH_COMPONENT24,o=v.DEPTH_ATTACHMENT):13!==a&&17!==a||(t=12,n=v.UNSIGNED_INT_24_8,i=v.DEPTH24_STENCIL8,r=v.DEPTH_STENCIL,o=v.DEPTH_STENCIL_ATTACHMENT),v.activeTexture(v.TEXTURE0),v.bindTexture(v.TEXTURE_2D,e._hardwareTexture.underlyingResource),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_MAG_FILTER,v.NEAREST),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_MIN_FILTER,v.NEAREST),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_WRAP_S,v.CLAMP_TO_EDGE),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_WRAP_T,v.CLAMP_TO_EDGE),v.texImage2D(v.TEXTURE_2D,0,i,T,S,0,r,n,null),v.framebufferTexture2D(v.FRAMEBUFFER,o,v.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=T,e.baseHeight=S,e.width=T,e.height=S,e.isReady=!0,e.samples=1,e.generateMipMaps=s,e.samplingMode=1,e.format=a,e.type=t,E[l]=e,this._internalTexturesCache.push(e)}return g.setTextures(E),i&&v.drawBuffers(b),this._bindUnboundFramebuffer(null),g.setLayerAndFaceIndices(_,f),this.resetTextureCache(),g},Yi.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const s=e._attachments.length;if(0===s)return 1;const r=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);const n=!!e._depthStencilBuffer;if(n&&(r.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(r.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof r.renderbufferStorageMultisample){const n=r.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);const o=[];for(let t=0;t1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(s.width,s.height,t,-1,this._getRGBABufferInternalSizedFormat(s.type,s.format,s._useSRGBBuffer),a);if(!l)throw new Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(l),s.samples=t,o.push(a)}i&&r.drawBuffers(o)}else this._bindUnboundFramebuffer(e._framebuffer);return n&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},Yi.prototype._createDepthStencilCubeTexture=function(e,t){const i=new ti(this,ei.DepthStencil);if(i.isCube=!0,1===this.webGLVersion)return J.Error("Depth cube texture is not supported by WebGL 1."),i;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t},r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction);for(let t=0;t<6;t++)s.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH24_STENCIL8,e,e,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH_COMPONENT24,e,e,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(i),i},Yi.prototype._setCubeMapTextureParams=function(e,t,i){const s=this._gl;s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,t?s.LINEAR_MIPMAP_LINEAR:s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null)},Yi.prototype.createCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,p=!1){const f=this._gl;return this.createCubeTextureBase(e,t,i,!!s,r,n,o,a,l,h,c,u,(e=>this._bindTextureDirectly(f.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const i=this.needPOTTextures?Ri(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,n=i,a=[f.TEXTURE_CUBE_MAP_POSITIVE_X,f.TEXTURE_CUBE_MAP_POSITIVE_Y,f.TEXTURE_CUBE_MAP_POSITIVE_Z,f.TEXTURE_CUBE_MAP_NEGATIVE_X,f.TEXTURE_CUBE_MAP_NEGATIVE_Y,f.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(f.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const l=o?this._getInternalFormat(o,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:f.RGBA;let h=o?this._getInternalFormat(o):f.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(h=l);for(let e=0;e1,e=>e.y,e=>e.z,e=>e.x,e=>e.x*e.y,e=>e.y*e.z,e=>3*e.z*e.z-1,e=>e.x*e.z,e=>e.x*e.x-e.y*e.y],$c=(e,t)=>Yc[e]*jc[e](t),Kc=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4];class qc{constructor(){this.preScaled=!1,this.l00=w.Zero(),this.l1_1=w.Zero(),this.l10=w.Zero(),this.l11=w.Zero(),this.l2_2=w.Zero(),this.l2_1=w.Zero(),this.l20=w.Zero(),this.l21=w.Zero(),this.l22=w.Zero()}addLight(e,t,i){U.Vector3[0].set(t.r,t.g,t.b);const s=U.Vector3[0],r=U.Vector3[1];s.scaleToRef(i,r),r.scaleToRef($c(0,e),U.Vector3[2]),this.l00.addInPlace(U.Vector3[2]),r.scaleToRef($c(1,e),U.Vector3[2]),this.l1_1.addInPlace(U.Vector3[2]),r.scaleToRef($c(2,e),U.Vector3[2]),this.l10.addInPlace(U.Vector3[2]),r.scaleToRef($c(3,e),U.Vector3[2]),this.l11.addInPlace(U.Vector3[2]),r.scaleToRef($c(4,e),U.Vector3[2]),this.l2_2.addInPlace(U.Vector3[2]),r.scaleToRef($c(5,e),U.Vector3[2]),this.l2_1.addInPlace(U.Vector3[2]),r.scaleToRef($c(6,e),U.Vector3[2]),this.l20.addInPlace(U.Vector3[2]),r.scaleToRef($c(7,e),U.Vector3[2]),this.l21.addInPlace(U.Vector3[2]),r.scaleToRef($c(8,e),U.Vector3[2]),this.l22.addInPlace(U.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(Kc[0]),this.l1_1.scaleInPlace(Kc[1]),this.l10.scaleInPlace(Kc[2]),this.l11.scaleInPlace(Kc[3]),this.l2_2.scaleInPlace(Kc[4]),this.l2_1.scaleInPlace(Kc[5]),this.l20.scaleInPlace(Kc[6]),this.l21.scaleInPlace(Kc[7]),this.l22.scaleInPlace(Kc[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(Yc[0]),this.l1_1.scaleInPlace(Yc[1]),this.l10.scaleInPlace(Yc[2]),this.l11.scaleInPlace(Yc[3]),this.l2_2.scaleInPlace(Yc[4]),this.l2_1.scaleInPlace(Yc[5]),this.l20.scaleInPlace(Yc[6]),this.l21.scaleInPlace(Yc[7]),this.l22.scaleInPlace(Yc[8])}updateFromArray(e){return w.FromArrayToRef(e[0],0,this.l00),w.FromArrayToRef(e[1],0,this.l1_1),w.FromArrayToRef(e[2],0,this.l10),w.FromArrayToRef(e[3],0,this.l11),w.FromArrayToRef(e[4],0,this.l2_2),w.FromArrayToRef(e[5],0,this.l2_1),w.FromArrayToRef(e[6],0,this.l20),w.FromArrayToRef(e[7],0,this.l21),w.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return w.FromFloatsToRef(e[0],e[1],e[2],this.l00),w.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),w.FromFloatsToRef(e[6],e[7],e[8],this.l10),w.FromFloatsToRef(e[9],e[10],e[11],this.l11),w.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),w.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),w.FromFloatsToRef(e[18],e[19],e[20],this.l20),w.FromFloatsToRef(e[21],e[22],e[23],this.l21),w.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new qc).updateFromArray(e)}static FromPolynomial(e){const t=new qc;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}}class Qc{constructor(){this.x=w.Zero(),this.y=w.Zero(),this.z=w.Zero(),this.xx=w.Zero(),this.yy=w.Zero(),this.zz=w.Zero(),this.xy=w.Zero(),this.yz=w.Zero(),this.zx=w.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=qc.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){U.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=U.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),U.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),U.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(U.Vector3[0]).addInPlace(U.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(U.Vector3[0]).subtractInPlace(U.Vector3[1]),this.zz.copyFrom(e.l00),U.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(U.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return(new Qc).updateFromHarmonics(e)}static FromArray(e){const t=new Qc;return w.FromArrayToRef(e[0],0,t.x),w.FromArrayToRef(e[1],0,t.y),w.FromArrayToRef(e[2],0,t.z),w.FromArrayToRef(e[3],0,t.xx),w.FromArrayToRef(e[4],0,t.yy),w.FromArrayToRef(e[5],0,t.zz),w.FromArrayToRef(e[6],0,t.yz),w.FromArrayToRef(e[7],0,t.zx),w.FromArrayToRef(e[8],0,t.xy),t}}class Zc{constructor(e,t,i,s){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=s}}class Jc{static ConvertCubeMapTextureToSphericalPolynomial(e){if(!e.isCube)return null;e.getScene()?.getEngine().flushFramebuffer();const t=e.getSize().width,i=e.readPixels(0,void 0,void 0,!1),s=e.readPixels(1,void 0,void 0,!1);let r,n;e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),n=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),n=e.readPixels(3,void 0,void 0,!1));const o=e.readPixels(4,void 0,void 0,!1),a=e.readPixels(5,void 0,void 0,!1),l=e.gammaSpace;let h=0;return 1!=e.textureType&&2!=e.textureType||(h=1),new Promise((e=>{Promise.all([s,i,r,n,o,a]).then((([i,s,r,n,o,a])=>{const c={size:t,right:s,left:i,up:r,down:n,front:o,back:a,format:5,type:h,gammaSpace:l};e(this.ConvertCubeMapToSphericalPolynomial(c))}))}))}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new qc;let i=0;const s=2/e.size,r=s,n=.5*s,o=n-1;for(let a=0;a<6;a++){const l=this._FileFaces[a],h=e[l.name];let c=o;const u=5===e.format?4:3;for(let a=0;ag){const t=g/e;f*=t,_*=t,m*=t}}else f=G.Clamp(f,0,g),_=G.Clamp(_,0,g),m=G.Clamp(m,0,g);const v=new Y(f,_,m);t.addLight(o,v,p),i+=p,d+=s}c+=r}}const a=4*Math.PI*6/6/i;return t.scaleInPlace(a),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),Qc.FromHarmonics(t)}}Jc._FileFaces=[new Zc("right",new w(1,0,0),new w(0,0,-1),new w(0,-1,0)),new Zc("left",new w(-1,0,0),new w(0,0,1),new w(0,-1,0)),new Zc("up",new w(0,1,0),new w(1,0,0),new w(0,0,1)),new Zc("down",new w(0,-1,0),new w(1,0,0),new w(0,0,-1)),new Zc("front",new w(0,0,1),new w(1,0,0),new w(0,-1,0)),new Zc("back",new w(0,0,-1),new w(-1,0,0),new w(0,-1,0))],Jc.MAX_HDRI_VALUE=4096,Jc.PRESERVE_CLAMPED_COLORS=!1;Ft.ShadersStore.lodPixelShader="#extension GL_EXT_shader_texture_lod : enable\nprecision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform sampler2D textureSampler;uniform float lod;uniform vec2 texSize;uniform bool gamma;void main(void)\n{gl_FragColor=textureLod(textureSampler,vUV,lod);if (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";function eu(e,t,i,s,r,n,o,a){const l=t.getEngine();return t.isReady=!1,r=r??t.samplingMode,s=s??t.type,n=n??t.format,o=o??t.width,a=a??t.height,-1===s&&(s=0),new Promise((h=>{const c=new Ko("postprocess",e,null,null,1,null,r,l,!1,void 0,s,void 0,null,!1,n);c.externalTextureSamplerBinding=!0;const u=l.createRenderTargetTexture({width:o,height:a},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:r,type:s,format:n});c.getEffect().executeWhenCompiled((()=>{c.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([c],u,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),c&&c.dispose(),u._swapAndDie(t),t.type=s,t.format=5,t.isReady=!0,h(t)}))}))}let tu,iu;function su(e){tu||(tu=new Float32Array(1),iu=new Int32Array(tu.buffer)),tu[0]=e;const t=iu[0];let i=t>>16&32768,s=t>>12&2047;const r=t>>23&255;return r<103?i:r>142?(i|=31744,i|=(255==r?0:1)&&8388607&t,i):r<113?(s|=2048,i|=(s>>114-r)+(s>>113-r&1),i):(i|=r-112<<10|s>>1,i+=1&s,i)}function ru(e){const t=(32768&e)>>15,i=(31744&e)>>10,s=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(s/Math.pow(2,10)):31==i?s?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+s/Math.pow(2,10))}Ft.ShadersStore.lodCubePixelShader="precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform samplerCube textureSampler;uniform float lod;uniform bool gamma;void main(void)\n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x),lod);\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x),lod);\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x),lod);\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x),lod);\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001),lod);\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001),lod);\n#endif\nif (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";const nu=async function(e,t,i,s=0,r=0){return!e.isReady()&&e._texture&&await new Promise(((t,i)=>{null!==e._texture?e._texture.onLoadedObservable.addOnce((()=>{t(0)})):i(0)})),await(async(e,t,i,s,r)=>{const n=e.getScene(),o=n.getEngine();let a;if(e.isCube){const e=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];a=new Ko("lodCube","lodCube",["lod","gamma"],null,1,null,Zn.NEAREST_NEAREST_MIPNEAREST,o,!1,e[s])}else a=new Ko("lod","lod",["lod","gamma"],null,1,null,Zn.NEAREST_NEAREST_MIPNEAREST,o);await new Promise((e=>{a.getEffect().executeWhenCompiled((()=>{e(0)}))}));const l=new da("temp",{width:t,height:i},n,!1);a.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",r),t.setBool("gamma",e.gammaSpace)};const h=e.getInternalTexture();try{if(l.renderTarget&&h){const s=h.samplingMode;0!==r?e.updateSamplingMode(Zn.NEAREST_NEAREST_MIPNEAREST):e.updateSamplingMode(Zn.NEAREST_NEAREST),n.postProcessManager.directRender([a],l.renderTarget,!0),e.updateSamplingMode(s);const c=await o.readPixels(0,0,t,i),u=new Uint8Array(c.buffer,0,c.byteLength);return o.unBindFramebuffer(l.renderTarget),u}throw Error("Render to texture failed.")}finally{l.dispose(),a.dispose()}})(e,t,i,s,r)},ou=131072,au=131072;function lu(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}const hu=lu("DXT1"),cu=lu("DXT3"),uu=lu("DXT5"),du=lu("DX10");class pu{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35);let s=1;t[2]&ou&&(s=Math.max(1,t[7]));const r=t[21],n=r===du?i[32]:0;let o=0;switch(r){case 113:o=2;break;case 116:o=1;break;case du:if(10===n){o=2;break}if(2===n){o=1;break}}return{width:t[4],height:t[3],mipmapCount:s,isFourCC:!(4&~t[20]),isRGB:!(64&~t[20]),isLuminance:(t[20]&au)===au,isCube:!(512&~t[28]),isCompressed:r===hu||r===cu||r===uu,dxgiFormat:n,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,s,r,n){const o=new Float32Array(s),a=new Uint16Array(r,i);let l=0;for(let i=0;i>8)}static _GetRGBArrayBuffer(e,t,i,s,r,n,o,a){const l=new Uint8Array(s),h=new Uint8Array(r,i);let c=0;for(let i=0;i>8&255,C>>16&255,C>>24&255))])}var C;const y=pu._ExtractLongWordOrder(u[23]),A=pu._ExtractLongWordOrder(u[24]),R=pu._ExtractLongWordOrder(u[25]),I=pu._ExtractLongWordOrder(u[26]);b&&(T=e._getRGBABufferInternalSizedFormat(s.textureType)),g=1,u[2]&ou&&!1!==r&&(g=Math.max(1,u[7]));const P=a||0,M=e.getCaps();for(let r=P;r0?s.sphericalPolynomial=Jc.ConvertCubeMapToSphericalPolynomial({size:u[4],right:h[0],left:h[1],up:h[2],down:h[3],front:h[4],back:h[5],format:5,type:1,gammaSpace:!1}):s.sphericalPolynomial=void 0}}function fu(e){if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some((t=>{const i="\\b"+t+"\\b";return e&&(e===t||e.match(new RegExp(i,"g")))})))return e;const t=e.lastIndexOf("."),i=e.lastIndexOf("?"),s=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+s}pu.StoreLODInAlphaChannel=!1,Yi.prototype.createPrefilteredCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(r&&r(null));const n=e.texture;if(l?e.info.sphericalPolynomial&&(n._sphericalPolynomial=e.info.sphericalPolynomial):n._sphericalPolynomial=new Qc,n._source=ei.CubePrefiltered,this.getCaps().textureLOD)return void(r&&r(n));const o=this._gl,a=e.width;if(!a)return;const h=[];for(let r=0;r<3;r++){const l=1-r/2,c=s,u=G.Log2(a)*i+s,d=c+(u-c)*l,p=Math.round(Math.min(Math.max(d,0),u)),f=new ti(this,ei.Temp);if(f.type=n.type,f.format=n.format,f.width=Math.pow(2,Math.max(G.Log2(a)-p,0)),f.height=f.width,f.isCube=!0,f._cachedWrapU=0,f._cachedWrapV=0,this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,f,!0),f.samplingMode=2,o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),e.isDDS){const t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),pu.UploadDDSLevels(this,f,i,t,!0,6,p)}else J.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null);const _=new qn(t);_._isCube=!0,_._texture=f,f.isReady=!0,h.push(_)}n._lodTextureHigh=h[2],n._lodTextureMid=h[1],n._lodTextureLow=h[0],r&&r(n)}),n,o,a,l,i,s)},Object.defineProperty(Br.prototype,"texturesSupported",{get:function(){const e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(Br.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),Br.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},Br.prototype.setTextureFormatToUse=function(e){const t=this.texturesSupported;for(let i=0,s=t.length;i{this._flush()}))}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}}_u.DEFAULT_BUFFER_SIZE=65536;Ft.ShadersStore.rgbdDecodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}";class mu{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),s=i.getCaps(),r=t.isReady;let n=!1;s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?(n=!0,t.type=2):s.textureFloatRender&&s.textureFloatLinearFiltering&&(n=!0,t.type=1),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const o=()=>{const s=new Ko("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);s.externalTextureSamplerBinding=!0;const r=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});s.getEffect().executeWhenCompiled((()=>{s.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([s],r,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),s&&s.dispose(),r._swapAndDie(t),t.isReady=!0}))};n&&(r?o():e.onLoadObservable.addOnce(o))}static EncodeTextureToRGBD(e,t,i=0){return eu("rgbdEncode",e,t,i,1,5)}}qn.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(qn.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=Jc.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then((e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))),null}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});Ft.ShadersStore.rgbdEncodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}";const gu="image/png",vu=2,xu=[134,22,135,150,246,214,150,54];function Tu(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;for(let e=0;evu)throw new Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "${vu}".`);return 2===e.version?e:e={...e,version:2,imageType:gu}}function Eu(e,t){const i=(t=Su(t)).specular;let s=G.Log2(t.width);if(s=Math.round(s)+1,i.mipmaps.length!==6*s)throw new Error(`Unsupported specular mipmaps number "${i.mipmaps.length}"`);const r=new Array(s);for(let t=0;tCu(t,r,n,a,f,c,s,o,h,l,e)));else{const t=new Image;t.src=f,_=new Promise(((i,u)=>{t.onload=()=>{Cu(t,r,n,a,f,c,s,o,h,l,e).then((()=>i())).catch((e=>{u(e)}))},t.onerror=e=>{u(e)}}))}u.push(_)}if(t.length{l&&(r._releaseTexture(e),l._swapAndDie(e)),a&&a.dispose(),o&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))}))}(e,Eu(t,i),i.imageType)):Promise.resolve()}function Cu(e,t,i,s,r,n,o,a,l,h,c){return new Promise(((u,d)=>{if(i){const i=t.createTexture(null,!0,!0,null,1,null,(e=>{d(e)}),e);s.getEffect().executeWhenCompiled((()=>{s.externalTextureSamplerBinding=!0,s.onApply=s=>{s._bindTexture("textureSampler",i),s.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([s],h,!0,n,o),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(r),u())}))}else{if(t._uploadImageToTexture(c,e,n,o),a){const i=l[o];i&&t._uploadImageToTexture(i._texture,e,n,0)}u()}}))}function yu(e,t){const i=(t=Su(t)).irradiance;if(!i)return;const s=new Qc;w.FromArrayToRef(i.x,0,s.x),w.FromArrayToRef(i.y,0,s.y),w.FromArrayToRef(i.z,0,s.z),w.FromArrayToRef(i.xx,0,s.xx),w.FromArrayToRef(i.yy,0,s.yy),w.FromArrayToRef(i.zz,0,s.zz),w.FromArrayToRef(i.yz,0,s.yz),w.FromArrayToRef(i.zx,0,s.zx),w.FromArrayToRef(i.xy,0,s.xy),e._sphericalPolynomial=s}function Au(e,t,i,s){let r=s,n=0,o="";for(;r=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function Pu(e){let t=0,i="",s=!1;const r=[];for(;t=0&&e.charAt(t)!==i&&(!s||e.charAt(t)!==s);)t--;return t}function Du(e,t,i,s){let r=e.indexOf(t);if(r<0)return e;if(i){for(;r++=0&&d.push(t.substring(i+1))}"void"!==r&&d.push("return"),this._functionDescr.push({name:n,type:r,parameters:d,body:c,callIndex:0}),e=h+1;const p=t>0?this._sourceCode.substring(0,t):"",f=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&J.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:s,parameters:r,body:n}=t;let o=0;for(;o{const t=[];let i=0,s=0;for(;i0?this._sourceCode.substring(0,a):"";const g=h+1{const a=r[0];return Iu(e.charAt(a-1))||Iu(e.charAt(a+n))?t[s]:o}))}return e}}Ou._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;const Nu=/(flat\s)?\s*varying\s*.*/;class wu{constructor(){this.shaderLanguage=ht.GLSL}initializeShaders(e){this._nativeProcessingContext=e,this._nativeProcessingContext&&(this._nativeProcessingContext.remappedAttributeNames={},this._nativeProcessingContext.injectInVertexMain="")}attributeProcessor(e){if(!this._nativeProcessingContext)return e.replace("attribute","in");const t=/\s*(?:attribute|in)\s+(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==t){const i=t[1],s=t[2],r=this._nativeProcessingContext.vertexBufferKindToNumberOfComponents[s];if(void 0!==r){const n=r<0?-1===r?"int":"ivec"+-r:1===r?"uint":"uvec"+r,o=`_int_${s}_`;e=e.replace(t[0],`in ${n} ${o}; ${i} ${s};`),this._nativeProcessingContext.injectInVertexMain+=`${s} = ${i}(${o});\n`,this._nativeProcessingContext.remappedAttributeNames[s]=o}else e=e.replace(t[0],`in ${i} ${s};`)}return e}varyingCheck(e,t){return Nu.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(s||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(this._nativeProcessingContext?.injectInVertexMain&&(e=Du(e,"void main",this._nativeProcessingContext.injectInVertexMain)),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}class Fu{get isReady(){if(this.compilationError){const e=this.compilationError.message;throw new Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}constructor(e,t,i){this.isCompiled=!1,this.vertexBufferKindToType={},this._valueCache={},this._engine=e,this.isAsync=t,this.shaderProcessingContext=i}_fillEffectInformation(e,t,i,s,r,n,o,a){const l=this._engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this._engine.getUniforms(this,i).forEach(((e,t)=>{s[i[t]]=e})),this._uniforms=s,h=0;h{n[e]=t})),a.push(...l.getAttributes(this,o))}setEngine(e){this._engine=e}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this._engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this._engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this._engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this._engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}}class Lu extends jo{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,s){super(e,t,i,s),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=s}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class Bu{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}}function Vu(e,t){switch(e){case 15:return _native.Engine.TEXTURE_FORMAT_D16;case 16:return _native.Engine.TEXTURE_FORMAT_D24;case 13:return _native.Engine.TEXTURE_FORMAT_D24S8;case 14:return _native.Engine.TEXTURE_FORMAT_D32F;case 36492:return _native.Engine.TEXTURE_FORMAT_BC7;case 36494:return _native.Engine.TEXTURE_FORMAT_BC6H;case 33779:return _native.Engine.TEXTURE_FORMAT_BC3;case 33778:return _native.Engine.TEXTURE_FORMAT_BC2;case 33777:case 33776:return _native.Engine.TEXTURE_FORMAT_BC1;case 37808:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case 36196:return _native.Engine.TEXTURE_FORMAT_ETC1;case 37492:return _native.Engine.TEXTURE_FORMAT_ETC2;case 37496:return _native.Engine.TEXTURE_FORMAT_ETC2A;case 4:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGB8;case 3:return _native.Engine.TEXTURE_FORMAT_RGB8S;case 6:return _native.Engine.TEXTURE_FORMAT_RGB8I;case 7:return _native.Engine.TEXTURE_FORMAT_RGB8U}break;case 5:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGBA8;case 1:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case 2:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case 3:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case 4:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case 5:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case 6:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case 7:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break;case 6:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_R8;case 1:return _native.Engine.TEXTURE_FORMAT_R32F;case 2:return _native.Engine.TEXTURE_FORMAT_R16F;case 3:return _native.Engine.TEXTURE_FORMAT_R8S;case 4:return _native.Engine.TEXTURE_FORMAT_R16S;case 5:return _native.Engine.TEXTURE_FORMAT_R16U;case 6:return _native.Engine.TEXTURE_FORMAT_R32I;case 7:return _native.Engine.TEXTURE_FORMAT_R32U}break;case 7:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RG8;case 1:return _native.Engine.TEXTURE_FORMAT_RG32F;case 2:return _native.Engine.TEXTURE_FORMAT_RG16F;case 3:return _native.Engine.TEXTURE_FORMAT_RG8S;case 4:return _native.Engine.TEXTURE_FORMAT_RG16S;case 5:return _native.Engine.TEXTURE_FORMAT_RG16U;case 6:return _native.Engine.TEXTURE_FORMAT_RG32I;case 7:return _native.Engine.TEXTURE_FORMAT_RG32U}break;case 12:if(0===t)return _native.Engine.TEXTURE_FORMAT_BGRA8}throw new Qe(`Unsupported texture format or type: format ${e}, type ${t}.`,1e3)}function Uu(e){switch(e){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw new Error(`Unsupported sampling mode: ${e}.`)}}function ku(e){switch(e){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw new Error("Unexpected wrap mode: "+e+".")}}function Gu(e){switch(e){case Ki.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case Ki.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case Ki.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case Ki.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case Ki.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${e}.`)}}const zu={[Ki.PositionKind]:!0,[Ki.NormalKind]:!0,[Ki.TangentKind]:!0,[Ki.UVKind]:!0,[Ki.UV2Kind]:!0,[Ki.UV3Kind]:!0,[Ki.UV4Kind]:!0,[Ki.UV5Kind]:!0,[Ki.UV6Kind]:!0,[Ki.ColorKind]:!0,[Ki.ColorInstanceKind]:!0,[Ki.MatricesIndicesKind]:!0,[Ki.MatricesWeightsKind]:!0,[Ki.MatricesIndicesExtraKind]:!0,[Ki.MatricesWeightsExtraKind]:!0};function Wu(e){switch(e){case Ki.BYTE:case Ki.SHORT:case Ki.INT:case Ki.FLOAT:return!0;case Ki.UNSIGNED_BYTE:case Ki.UNSIGNED_SHORT:case Ki.UNSIGNED_INT:return!1;default:throw new Error(`Invalid type '${e}'`)}}function Hu(e,t){const i=t.getEngine(),s=t._pipelineContext;if(!s?.vertexBufferKindToType)return;let r=null;for(const n in e){const o=e[n];if(!o||!zu[n])continue;const a=o.normalized?Ki.FLOAT:o.type,l=s.vertexBufferKindToType[n];(a!==Ki.FLOAT&&void 0===l||void 0!==l&&l!==a)&&(r||(r=i._getShaderProcessingContext(t.shaderLanguage)),s.vertexBufferKindToType[n]=a,a!==Ki.FLOAT&&(r.vertexBufferKindToNumberOfComponents[n]=Ki.DeduceStride(n),Wu(a)&&(r.vertexBufferKindToNumberOfComponents[n]*=-1)))}if(r){const e=i._caps.parallelShaderCompile;i._caps.parallelShaderCompile=void 0,t._processShaderCode(null,i._features._checkNonFloatVertexBuffersDontRecreatePipelineContext,r),i._caps.parallelShaderCompile=e}}class Xu{constructor(){this.vertexBufferKindToNumberOfComponents={},this.remappedAttributeNames={},this.injectInVertexMain=""}}const Yu=new g;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{e=t,e&&Yu.notifyObservers(e)}})}class ju extends zi{}class $u{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=qu._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw new Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw new Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}}const Ku=[];class qu extends Br{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine({version:Br.Version,nonFloatVertexBuffers:!0}),this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new $u(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==qu.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${qu.PROTOCOL_VERSION} (JS)`);this._engine.setDeviceLostCallback&&this._engine.setDeviceLostCallback((()=>{this.onContextLostObservable.notifyObservers(this),this._contextWasLost=!0,this._restoreEngineAfterContextLost()})),this._webGLVersion=2,this.disableUniformBuffers=!0,this._shaderPlatformName="NATIVE",this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!0,textureFloatLinearFiltering:!0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1,parallelShaderCompile:{COMPLETION_STATUS_KHR:0}},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1},Ii.Log("Babylon Native (v"+Br.Version+") launched"),Ii.LoadScript=function(e,t,i,s){Ii.LoadFile(e,(e=>{Function(e).apply(null),t&&t()}),void 0,void 0,!1,((e,t)=>{i&&i("LoadScript Error",t)}))},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(){const t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,(function(i,s){return Array.isArray(s)?i.push.apply(i,e.call(s,t-1)):i.push(s),i}),[]):Array.prototype.slice.call(this)},writable:!0});const t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();const i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new wu,this.onNewSceneAddedObservable.add((e=>{const t=e.render;e.render=(...i)=>{this._commandBufferEncoder.beginCommandScope(),t.apply(e,i),this._commandBufferEncoder.endCommandScope()}}))}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new _u}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_restoreEngineAfterContextLost(){this._clearEmptyResources();const e=this._depthCullingState.depthTest,t=this._depthCullingState.depthFunc,i=this._depthCullingState.depthMask,s=this._stencilState.stencilTest;this._rebuildGraphicsResources(),this._depthCullingState.depthTest=e,this._depthCullingState.depthFunc=t,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=s,this._flagContextRestored()}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,s=!1){if(this.useReverseDepthBuffer)throw new Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(s?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){const s=this._normalizeIndexData(e),r=new ju;return r.references=1,r.is32Bits=4===s.BYTES_PER_ELEMENT,s.byteLength&&(r.nativeIndexBuffer=this._engine.createIndexBuffer(s.buffer,s.byteOffset,s.byteLength,r.is32Bits,t??!1)),r}createVertexBuffer(e,t,i){const s=ArrayBuffer.isView(e)?e:new Float32Array(e),r=new ju;return r.references=1,s.byteLength&&(r.nativeVertexBuffer=this._engine.createVertexBuffer(s.buffer,s.byteOffset,s.byteLength,t??!1)),r}_recordVertexArrayObject(e,t,i,s,r){Hu(t,s),i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const n=s.getAttributesNames();for(let i=0;i=0){const s=n[i];let a=null;if(r&&(a=r[s]),a||(a=t[s]),a){const t=a.effectiveBuffer;t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,o,a.effectiveByteOffset,a.effectiveByteStride,a.getSize(),Gu(a.type),a.normalized,a.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,s){const r=this._engine.createVertexArray();return this._recordVertexArrayObject(r,e,t,i,s),r}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){const i=e,s=i.shaderProcessingContext;Ku.length=0;for(let e=0;e{e(),t()}}else i.onCompiled=t;else t()}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,s){const r=e;this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=new Ou(t);n.processCode(),t=n.code;const o=new Ou(i);o.processCode(),i=o.code,t=Yi._ConcatenateShader(t,s),i=Yi._ConcatenateShader(i,s);const a=()=>{r.isCompiled=!0,r.onCompiled?.(),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(e.isAsync)r.program=this._engine.createProgramAsync(t,i,a,(e=>{r.compilationError=e}));else try{r.program=this._engine.createProgram(t,i),a()}catch(e){const t=e?.message;throw new Error("SHADER ERROR"+("string"==typeof t?"\n"+t:""))}return r.program}inlineShaderCode(e){const t=new Ou(e);return t.debug=!1,t.processCode(),t.code}_setProgram(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)}_deletePipelineContext(e){const t=e;t&&t.program&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(t.program),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){const i=e;return this._engine.getUniforms(i.program,t)}bindUniformBlock(e,t,i){throw new Error("Not Implemented")}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t{}}}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()}setDepthWrite(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}setColorWrite(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}getColorWrite(){return this._colorWrite}applyStencil(){this._setStencil(this._stencilMask,function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw new Error(`Unsupported stencil OpFail mode: ${e}.`)}}(this._stencilOpStencilFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw new Error(`Unsupported stencil depthFail mode: ${e}.`)}}(this._stencilOpDepthFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw new Error(`Unsupported stencil opPass mode: ${e}.`)}}(this._stencilOpStencilDepthPass),function(e){switch(e){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw new Error(`Unsupported stencil func mode: ${e}.`)}}(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,s,r,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,s){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=function(e){switch(e){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw new Error(`Unsupported alpha mode: ${e}.`)}}(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(0===e),this._alphaMode=e}setInt(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setArray(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))}setArray2(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))}setArray3(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))}setArray4(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))}setMatrices(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix3x3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix2x2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat2(e,t,i){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat3(e,t,i,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,s,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,s=!1,r){if(void 0===s&&(s=!1),e&&e._hardwareTexture){const i=t.getCanvasTexture(),s=e._hardwareTexture.underlyingResource;this._engine.copyTexture(s,i),e.isReady=!0}}createDynamicTexture(e,t,i,s){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,s)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const s=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(s,t,i)}}createRawTexture(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new ti(this,ei.Raw);if(u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u.baseWidth=t,u.baseHeight=i,u.width=u.baseWidth,u.height=u.baseHeight,u._compression=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!r),this.updateRawTexture(u,e,s,n,a,l,u._useSRGBBuffer),u._hardwareTexture){const e=u._hardwareTexture.underlyingResource,t=Uu(o);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(u),u}createRawTexture2DArray(e,t,i,s,r,n,o,a,l=null,h=0){const c=new ti(this,ei.Raw2DArray);if(c.baseWidth=t,c.baseHeight=i,c.baseDepth=s,c.width=t,c.height=i,c.depth=s,c.format=r,c.type=h,c.generateMipMaps=n,c.samplingMode=a,c.is2DArray=!0,c._hardwareTexture){const l=c._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,s,Vu(r,h),n,o);const u=Uu(a);this._setTextureSampling(l,u)}return c.isReady=!0,this._internalTexturesCache.push(c),c}updateRawTexture(e,t,i,s,r=null,n=0,o=!1){if(e){if(t&&e._hardwareTexture){const s=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(s,t,e.width,e.height,Vu(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,p,f=!1){const _="data:"===(e=e||"").substr(0,5),m=_&&-1!==e.indexOf(";base64,"),g=l||new ti(this,ei.Url),v=e;!this._transformTextureUrl||m||l||a||(e=this._transformTextureUrl(e));const x=e.lastIndexOf("."),T=c||(x>-1?e.substring(x).toLowerCase():"");let S=null;for(const e of si._TextureLoaders)if(e.canLoad(T)){S=e;break}s&&s.addPendingData(g),g.url=e,g.generateMipMaps=!t,g.samplingMode=r,g.invertY=i,g._useSRGBBuffer=this._getUseSRGBBuffer(f,t),this.doNotHandleContextLost||(g._buffer=a);let E=null;n&&!l&&(E=g.onLoadedObservable.add(n)),l||this._internalTexturesCache.push(g);const b=(i,l)=>{s&&s.removePendingData(g),e===v?(E&&g.onLoadedObservable.remove(E),y.UseFallbackTexture&&this.createTexture(y.FallbackTexture,t,g.invertY,s,r,null,o,a,g),o&&o((i||"Unknown error")+(y.UseFallbackTexture?" - Fallback texture was used":""),l)):(J.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,g.invertY,s,r,n,o,a,g,h,c,u,d))};if(S)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const n=e=>{if(!g._hardwareTexture)return void(s&&s.removePendingData(g));const n=g._hardwareTexture.underlyingResource;this._engine.loadTexture(n,e,!t,i,g._useSRGBBuffer,(()=>{g.baseWidth=this._engine.getTextureWidth(n),g.baseHeight=this._engine.getTextureHeight(n),g.width=g.baseWidth,g.height=g.baseHeight,g.isReady=!0;const e=Uu(r);this._setTextureSampling(n,e),s&&s.removePendingData(g),g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()}),(()=>{throw new Error("Could not load a native texture.")}))};if(_&&a)if(a instanceof ArrayBuffer)n(new Uint8Array(a));else if(ArrayBuffer.isView(a))n(a);else{if("string"!=typeof a)throw new Error("Unsupported buffer type");n(new Uint8Array(Ii.DecodeBase64(a)))}else m?n(new Uint8Array(Ii.DecodeBase64(e))):this._loadFile(e,(e=>n(new Uint8Array(e))),void 0,void 0,!0,((e,t)=>{b("Unable to load "+(e&&e.responseURL,t))}))}return g}wrapNativeTexture(e,t=!1,i=3){const s=new Bu(e,this._engine),r=new ti(this,ei.Unknown,!0);return r._hardwareTexture=s,r.baseWidth=this._engine.getTextureWidth(e),r.baseHeight=this._engine.getTextureHeight(e),r.width=r.baseWidth,r.height=r.baseHeight,r.isReady=!0,r.useMipMaps=t,this.updateTextureSamplingMode(i,r),r}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const s=t.generateStencil||!1,r=t.samples||1,n=i,o=new ti(this,ei.DepthStencil),a=e.width??e,l=e.height??e,h=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,a,l,s,!0,r);return n._framebufferDepthStencil=h,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){return new Promise(((t,i)=>{const s=this.createCanvasImage();s.onload=()=>{try{const e=this._engine.createImageBitmap(s);t(e)}catch(e){i(`Error loading image ${s.src} with exception: ${e}`)}},s.onerror=e=>{i(`Error loading image ${s.src} with exception: ${e}`)},s.src=e}))}createImageBitmap(e,t){return new Promise(((t,i)=>{if(Array.isArray(e)){const i=e;if(i.length){const e=this._engine.createImageBitmap(i[0]);if(e)return void t(e)}}i("Unsupported data for createImageBitmap.")}))}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,p=!1){const f=u||new ti(this,ei.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!s,f._lodGenerationScale=h,f._lodGenerationOffset=c,f._useSRGBBuffer=this._getUseSRGBBuffer(p,!!s),this._doNotHandleContextLost||(f._extension=a,f._files=i);const _=e.lastIndexOf(".");if(".env"===(a||(_>-1?e.substring(_).toLowerCase():""))){const t=e=>{const t=Tu(e);f.width=t.width,f.height=t.width,yu(f,t);const i=t.specular;if(!i)throw new Error("Nothing else parsed so far");f._lodGenerationScale=i.lodGenerationScale;const s=Eu(e,t);f.format=5,f.type=0,f.generateMipMaps=!0,f.getEngine().updateTextureSamplingMode(Zn.TRILINEAR_SAMPLINGMODE,f),f._isRGBD=!0,f.invertY=!0,this._engine.loadCubeTextureWithMips(f._hardwareTexture.underlyingResource,s,!1,f._useSRGBBuffer,(()=>{f.isReady=!0,r&&r()}),(()=>{throw new Error("Could not load a native cube texture.")}))};if(i&&6===i.length)throw new Error("Multi-file loading not allowed on env files.");{const i=(e,t)=>{n&&e&&n(e.status+" "+e.statusText,t)};this._loadFile(e,(e=>{t(new Uint8Array(e,0,e.byteLength))}),void 0,void 0,!0,i)}}else{if(!i||6!==i.length)throw new Error("Cannot load cubemap because 6 files were not defined");const e=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(e.map((e=>this._loadFileAsync(e,void 0,!0).then((e=>new Uint8Array(e,0,e.byteLength)))))).then((e=>new Promise(((t,i)=>{this._engine.loadCubeTexture(f._hardwareTexture.underlyingResource,e,!s,!0,f._useSRGBBuffer,t,i)})))).then((()=>{f.isReady=!0,r&&r()}),(e=>{n&&n(`Failed to load cubemap: ${e.message}`,e)}))}return this._internalTexturesCache.push(f),f}_createHardwareTexture(){return new Bu(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const s=new Lu(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}_createInternalTexture(e,t,i=!0,s=ei.Unknown){let r,n=!1,o=0,a=3,l=5,h=!1,c=1;void 0!==t&&"object"==typeof t?(n=!!t.generateMipMaps,o=void 0===t.type?0:t.type,a=void 0===t.samplingMode?3:t.samplingMode,l=void 0===t.format?5:t.format,h=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,c=t.samples??1,r=t.label):n=!!t,h=this._getUseSRGBBuffer(h,!n),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(a=1),1!==o||this._caps.textureFloat||(o=0,J.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=new ti(this,s),d=e.width??e,p=e.height??e,f=e.layers||0;if(0!==f)throw new Error("Texture layers are not supported in Babylon Native");const _=u._hardwareTexture.underlyingResource,m=Vu(l,o);return this._engine.initializeTexture(_,d,p,n,m,!0,h,c),this._setTextureSampling(_,Uu(a)),u._useSRGBBuffer=h,u.baseWidth=d,u.baseHeight=p,u.width=d,u.height=p,u.depth=f,u.isReady=!0,u.samples=c,u.generateMipMaps=n,u.samplingMode=a,u.type=o,u.format=l,u.label=r,this._internalTexturesCache.push(u),u}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e);let s,r=!0,n=!1,o=!1,a=1;void 0!==t&&"object"==typeof t&&(r=t.generateDepthBuffer??!0,n=!!t.generateStencilBuffer,o=!!t.noColorAttachment,s=t.colorAttachment,a=t.samples??1);const l=s||(o?null:this._createInternalTexture(e,t,!0,ei.RenderTarget)),h=e.width??e,c=e.height??e,u=this._engine.createFrameBuffer(l?l._hardwareTexture.underlyingResource:null,h,c,n,r,a);return i._framebuffer=u,i._generateDepthBuffer=r,i._generateStencilBuffer=n,i._samples=a,i.setTextures(l),i}updateRenderTargetTextureSampleCount(e,t){return J.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=Uu(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,s,r){const n=e;if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||s)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");n._framebufferDepthStencil?this._bindUnboundFramebuffer(n._framebufferDepthStencil):this._bindUnboundFramebuffer(n._framebuffer)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e,!0)}updateDynamicIndexBuffer(e,t,i=0){const s=e,r=this._normalizeIndexData(t);s.is32Bits=4===r.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(s.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i=0,s){const r=e,n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,o=new Uint8Array(n.buffer,n.byteOffset,s??n.byteLength);this._engine.updateDynamicVertexBuffer(r.nativeVertexBuffer,o.buffer,o.byteOffset,o.byteLength,i)}_setTexture(e,t,i=!1,s=!1){const r=this._boundUniforms[e];if(!r)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null,this._unsetNativeTexture(r)),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;return n=s?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!(!n||!n._hardwareTexture||(this._setTextureWrapMode(n._hardwareTexture.underlyingResource,ku(t.wrapU),ku(t.wrapV),ku(t.wrapR)),this._updateAnisotropicLevel(t),this._setNativeTexture(r,n._hardwareTexture.underlyingResource),0))}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,s){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.finishEncodingCommand()}_setNativeTexture(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_unsetNativeTexture(e){_native.Engine.COMMAND_UNSETTEXTURE&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNSETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_updateAnisotropicLevel(e){const t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){const i=this._boundUniforms[e];if(i)if(t&&t._hardwareTexture){const e=t._hardwareTexture.underlyingResource;this._setNativeTexture(i,e)}else this._unsetNativeTexture(i)}unbindAllTextures(){_native.Engine.COMMAND_DISCARDALLTEXTURES&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DISCARDALLTEXTURES),this._commandBufferEncoder.finishEncodingCommand())}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");const i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");return new _native.Image}updateTextureData(e,t,i,s,r,n,o=0,a=0,l=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,s=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}flushFramebuffer(){}_readTexturePixels(e,t,i,s,r,n,o,a,l,h){if(void 0!==s&&-1!==s)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${s}.`);return this._engine.readTexture(e._hardwareTexture?.underlyingResource,r??0,l??0,h??0,t,i,n?.buffer??null,n?.byteOffset??0,n?.byteLength??0).then((e=>(n||(n=new Uint8Array(e)),n)))}}qu.PROTOCOL_VERSION=8,qu._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new Qu:new _u};class Qu extends _u{constructor(){super()}writeUint32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32),super.writeUint32(e)}writeInt32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32),super.writeInt32(e)}writeFloat32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32),super.writeFloat32(e)}writeUint32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),super.writeUint32Array(e)}writeInt32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY),super.writeInt32Array(e)}writeFloat32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),super.writeFloat32Array(e)}writeNativeData(e){super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA),super.writeNativeData(e)}writeBoolean(e){super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN),super.writeBoolean(e)}}var Zu,Ju,ed,td,id,sd,rd,nd,od,ad,ld,hd,cd,ud,dd,pd,fd,_d,md,gd,vd,xd,Td,Sd,Ed,bd,Cd,yd,Ad,Rd,Id,Pd,Md,Dd,Od,Nd,wd,Fd,Ld,Bd;!function(e){e.LowPower="low-power",e.HighPerformance="high-performance"}(Zu||(Zu={})),function(e){e.DepthClipControl="depth-clip-control",e.Depth32FloatStencil8="depth32float-stencil8",e.TextureCompressionBC="texture-compression-bc",e.TextureCompressionETC2="texture-compression-etc2",e.TextureCompressionASTC="texture-compression-astc",e.TimestampQuery="timestamp-query",e.IndirectFirstInstance="indirect-first-instance",e.ShaderF16="shader-f16",e.RG11B10UFloatRenderable="rg11b10ufloat-renderable",e.BGRA8UnormStorage="bgra8unorm-storage",e.Float32Filterable="float32-filterable"}(Ju||(Ju={})),function(e){e.Unmapped="unmapped",e.Pending="pending",e.Mapped="mapped"}(ed||(ed={})),function(e){e[e.MapRead=1]="MapRead",e[e.MapWrite=2]="MapWrite",e[e.CopySrc=4]="CopySrc",e[e.CopyDst=8]="CopyDst",e[e.Index=16]="Index",e[e.Vertex=32]="Vertex",e[e.Uniform=64]="Uniform",e[e.Storage=128]="Storage",e[e.Indirect=256]="Indirect",e[e.QueryResolve=512]="QueryResolve"}(td||(td={})),function(e){e[e.Read=1]="Read",e[e.Write=2]="Write"}(id||(id={})),function(e){e.E1d="1d",e.E2d="2d",e.E3d="3d"}(sd||(sd={})),function(e){e[e.CopySrc=1]="CopySrc",e[e.CopyDst=2]="CopyDst",e[e.TextureBinding=4]="TextureBinding",e[e.StorageBinding=8]="StorageBinding",e[e.RenderAttachment=16]="RenderAttachment"}(rd||(rd={})),function(e){e.E1d="1d",e.E2d="2d",e.E2dArray="2d-array",e.Cube="cube",e.CubeArray="cube-array",e.E3d="3d"}(nd||(nd={})),function(e){e.All="all",e.StencilOnly="stencil-only",e.DepthOnly="depth-only"}(od||(od={})),function(e){e.R8Unorm="r8unorm",e.R8Snorm="r8snorm",e.R8Uint="r8uint",e.R8Sint="r8sint",e.R16Uint="r16uint",e.R16Sint="r16sint",e.R16Float="r16float",e.RG8Unorm="rg8unorm",e.RG8Snorm="rg8snorm",e.RG8Uint="rg8uint",e.RG8Sint="rg8sint",e.R32Uint="r32uint",e.R32Sint="r32sint",e.R32Float="r32float",e.RG16Uint="rg16uint",e.RG16Sint="rg16sint",e.RG16Float="rg16float",e.RGBA8Unorm="rgba8unorm",e.RGBA8UnormSRGB="rgba8unorm-srgb",e.RGBA8Snorm="rgba8snorm",e.RGBA8Uint="rgba8uint",e.RGBA8Sint="rgba8sint",e.BGRA8Unorm="bgra8unorm",e.BGRA8UnormSRGB="bgra8unorm-srgb",e.RGB9E5UFloat="rgb9e5ufloat",e.RGB10A2UINT="rgb10a2uint",e.RGB10A2Unorm="rgb10a2unorm",e.RG11B10UFloat="rg11b10ufloat",e.RG32Uint="rg32uint",e.RG32Sint="rg32sint",e.RG32Float="rg32float",e.RGBA16Uint="rgba16uint",e.RGBA16Sint="rgba16sint",e.RGBA16Float="rgba16float",e.RGBA32Uint="rgba32uint",e.RGBA32Sint="rgba32sint",e.RGBA32Float="rgba32float",e.Stencil8="stencil8",e.Depth16Unorm="depth16unorm",e.Depth24Plus="depth24plus",e.Depth24PlusStencil8="depth24plus-stencil8",e.Depth32Float="depth32float",e.BC1RGBAUnorm="bc1-rgba-unorm",e.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",e.BC2RGBAUnorm="bc2-rgba-unorm",e.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",e.BC3RGBAUnorm="bc3-rgba-unorm",e.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",e.BC4RUnorm="bc4-r-unorm",e.BC4RSnorm="bc4-r-snorm",e.BC5RGUnorm="bc5-rg-unorm",e.BC5RGSnorm="bc5-rg-snorm",e.BC6HRGBUFloat="bc6h-rgb-ufloat",e.BC6HRGBFloat="bc6h-rgb-float",e.BC7RGBAUnorm="bc7-rgba-unorm",e.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",e.ETC2RGB8Unorm="etc2-rgb8unorm",e.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",e.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",e.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",e.ETC2RGBA8Unorm="etc2-rgba8unorm",e.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",e.EACR11Unorm="eac-r11unorm",e.EACR11Snorm="eac-r11snorm",e.EACRG11Unorm="eac-rg11unorm",e.EACRG11Snorm="eac-rg11snorm",e.ASTC4x4Unorm="astc-4x4-unorm",e.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",e.ASTC5x4Unorm="astc-5x4-unorm",e.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",e.ASTC5x5Unorm="astc-5x5-unorm",e.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",e.ASTC6x5Unorm="astc-6x5-unorm",e.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",e.ASTC6x6Unorm="astc-6x6-unorm",e.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",e.ASTC8x5Unorm="astc-8x5-unorm",e.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",e.ASTC8x6Unorm="astc-8x6-unorm",e.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",e.ASTC8x8Unorm="astc-8x8-unorm",e.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",e.ASTC10x5Unorm="astc-10x5-unorm",e.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",e.ASTC10x6Unorm="astc-10x6-unorm",e.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",e.ASTC10x8Unorm="astc-10x8-unorm",e.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",e.ASTC10x10Unorm="astc-10x10-unorm",e.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",e.ASTC12x10Unorm="astc-12x10-unorm",e.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",e.ASTC12x12Unorm="astc-12x12-unorm",e.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",e.Depth32FloatStencil8="depth32float-stencil8"}(ad||(ad={})),function(e){e.ClampToEdge="clamp-to-edge",e.Repeat="repeat",e.MirrorRepeat="mirror-repeat"}(ld||(ld={})),function(e){e.Nearest="nearest",e.Linear="linear"}(hd||(hd={})),function(e){e.Nearest="nearest",e.Linear="linear"}(cd||(cd={})),function(e){e.Never="never",e.Less="less",e.Equal="equal",e.LessEqual="less-equal",e.Greater="greater",e.NotEqual="not-equal",e.GreaterEqual="greater-equal",e.Always="always"}(ud||(ud={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Compute=4]="Compute"}(dd||(dd={})),function(e){e.Uniform="uniform",e.Storage="storage",e.ReadOnlyStorage="read-only-storage"}(pd||(pd={})),function(e){e.Filtering="filtering",e.NonFiltering="non-filtering",e.Comparison="comparison"}(fd||(fd={})),function(e){e.Float="float",e.UnfilterableFloat="unfilterable-float",e.Depth="depth",e.Sint="sint",e.Uint="uint"}(_d||(_d={})),function(e){e.WriteOnly="write-only",e.ReadOnly="read-only",e.ReadWrite="read-write"}(md||(md={})),function(e){e.Error="error",e.Warning="warning",e.Info="info"}(gd||(gd={})),function(e){e.Validation="validation",e.Internal="internal"}(vd||(vd={})),function(e){e.Auto="auto"}(xd||(xd={})),function(e){e.PointList="point-list",e.LineList="line-list",e.LineStrip="line-strip",e.TriangleList="triangle-list",e.TriangleStrip="triangle-strip"}(Td||(Td={})),function(e){e.CCW="ccw",e.CW="cw"}(Sd||(Sd={})),function(e){e.None="none",e.Front="front",e.Back="back"}(Ed||(Ed={})),function(e){e[e.Red=1]="Red",e[e.Green=2]="Green",e[e.Blue=4]="Blue",e[e.Alpha=8]="Alpha",e[e.All=15]="All"}(bd||(bd={})),function(e){e.Zero="zero",e.One="one",e.Src="src",e.OneMinusSrc="one-minus-src",e.SrcAlpha="src-alpha",e.OneMinusSrcAlpha="one-minus-src-alpha",e.Dst="dst",e.OneMinusDst="one-minus-dst",e.DstAlpha="dst-alpha",e.OneMinusDstAlpha="one-minus-dst-alpha",e.SrcAlphaSaturated="src-alpha-saturated",e.Constant="constant",e.OneMinusConstant="one-minus-constant"}(Cd||(Cd={})),function(e){e.Add="add",e.Subtract="subtract",e.ReverseSubtract="reverse-subtract",e.Min="min",e.Max="max"}(yd||(yd={})),function(e){e.Keep="keep",e.Zero="zero",e.Replace="replace",e.Invert="invert",e.IncrementClamp="increment-clamp",e.DecrementClamp="decrement-clamp",e.IncrementWrap="increment-wrap",e.DecrementWrap="decrement-wrap"}(Ad||(Ad={})),function(e){e.Uint16="uint16",e.Uint32="uint32"}(Rd||(Rd={})),function(e){e.Uint8x2="uint8x2",e.Uint8x4="uint8x4",e.Sint8x2="sint8x2",e.Sint8x4="sint8x4",e.Unorm8x2="unorm8x2",e.Unorm8x4="unorm8x4",e.Snorm8x2="snorm8x2",e.Snorm8x4="snorm8x4",e.Uint16x2="uint16x2",e.Uint16x4="uint16x4",e.Sint16x2="sint16x2",e.Sint16x4="sint16x4",e.Unorm16x2="unorm16x2",e.Unorm16x4="unorm16x4",e.Snorm16x2="snorm16x2",e.Snorm16x4="snorm16x4",e.Float16x2="float16x2",e.Float16x4="float16x4",e.Float32="float32",e.Float32x2="float32x2",e.Float32x3="float32x3",e.Float32x4="float32x4",e.Uint32="uint32",e.Uint32x2="uint32x2",e.Uint32x3="uint32x3",e.Uint32x4="uint32x4",e.Sint32="sint32",e.Sint32x2="sint32x2",e.Sint32x3="sint32x3",e.Sint32x4="sint32x4",e.UNORM10x10x10x2="unorm10-10-10-2"}(Id||(Id={})),function(e){e.Vertex="vertex",e.Instance="instance"}(Pd||(Pd={})),function(e){e.Beginning="beginning",e.End="end"}(Md||(Md={})),function(e){e.Beginning="beginning",e.End="end"}(Dd||(Dd={})),function(e){e.Load="load",e.Clear="clear"}(Od||(Od={})),function(e){e.Store="store",e.Discard="discard"}(Nd||(Nd={})),function(e){e.Occlusion="occlusion",e.Timestamp="timestamp"}(wd||(wd={})),function(e){e.Opaque="opaque",e.Premultiplied="premultiplied"}(Fd||(Fd={})),function(e){e.Unknown="unknown",e.Destroyed="destroyed"}(Ld||(Ld={})),function(e){e.Validation="validation",e.OutOfMemory="out-of-memory",e.Internal="internal"}(Bd||(Bd={}));class Vd{constructor(){this.shaderLanguage=ht.GLSL}_addUniformToLeftOverUBO(e,t,i){let s=0;[e,t,s]=this._getArraySize(e,t,i);for(let t=0;t=0&&(u.push(o[c]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=u,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new ji(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=Vd.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}setEngine(e){this.engine=e}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,s)}setInt4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,s,r)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,s)}setUInt4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,s,r)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,s)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,s,r)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){return this.sources?.vertex}_getFragmentShaderCode(){return this.sources?.fragment}}const kd={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class Gd{static get KnownUBOs(){return Gd._SimplifiedKnownBindings?Gd._SimplifiedKnownUBOs:Gd._KnownUBOs}constructor(e){this.vertexBufferKindToNumberOfComponents={},this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=Gd.KnownUBOs,t=[];for(const i in e){const s=e[i].binding;-1!==s.groupIndex&&(void 0===t[s.groupIndex]?t[s.groupIndex]=s.bindingIndex:t[s.groupIndex]=Math.max(t[s.groupIndex],s.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){const i=this._attributeNextLocation;return this._attributeNextLocation+=(kd[e]??1)*(t||1),i}getVaryingNextLocation(e,t=0){const i=this._varyingNextLocation;return this._varyingNextLocation+=(kd[e]??1)*(t||1),i}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";const t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}Gd._SimplifiedKnownBindings=!0,Gd._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}},Gd._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};class zd extends Vd{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=ht.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let s=0;const r=e.indexOf("["),n=e.indexOf("]");if(r>0&&n>0){const t=e.substring(r+1,n);s=+t,isNaN(s)&&(s=+i[t.trim()]),e=e.substr(0,r)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){const i=`// Internals UBO\nuniform ${Vd.InternalsUBOName} {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n`,s=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),s?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),s?e:i+e)}varyingCheck(e,t){return(t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/).test(e)}varyingProcessor(e,t,i){this._preProcessors=i;const s=(t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==s){const r=s[1]??"",n=s[2],o=s[3];let a;t?(a=this._webgpuProcessingContext.availableVaryings[o],this._missingVaryings[a]="",void 0===a&&J.Warn(`Invalid fragment shader: The varying named "${o}" is not declared in the vertex shader! This declaration will be ignored.`)):(a=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(o,n,i)[2]),this._webgpuProcessingContext.availableVaryings[o]=a,this._missingVaryings[a]=`layout(location = ${a}) ${r} in ${n} ${o};`),e=e.replace(s[0],void 0===a?"":`layout(location = ${a}) ${r} ${t?"in":"out"} ${n} ${o};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=(this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==i){const s=i[1],r=i[2],n=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(r,s,t)[2]);this._webgpuProcessingContext.availableAttributes[r]=n,this._webgpuProcessingContext.orderedAttributes[n]=r;const o=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[r];if(void 0!==o){const t=o<0?-1===o?"int":"ivec"+-o:1===o?"uint":"uvec"+o,a=`_int_${r}_`;e=e.replace(i[0],`layout(location = ${n}) in ${t} ${a}; ${s} ${r} = ${s}(${a});`)}else e=e.replace(i[0],`layout(location = ${n}) in ${s} ${r};`)}return e}uniformProcessor(e,t,i){this._preProcessors=i;const s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let r=s[1],n=s[2];if(0===r.indexOf("sampler")||1===r.indexOf("sampler")){let s=0;[n,r,s]=this._getArraySize(n,r,i);let o=this._webgpuProcessingContext.availableTextures[n];if(!o){o={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:_d.Float};for(let e=0;e<(s||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const a=Vd._SamplerTypeByWebGLSamplerType[r]??"sampler",l=!!Vd._IsComparisonSamplerByWebGPUSamplerType[a],h=l?fd.Comparison:fd.Filtering,c=n+"Sampler";let u=this._webgpuProcessingContext.availableSamplers[c];u||(u={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:h});const d="u"===r.charAt(0)?"u":"i"===r.charAt(0)?"i":"";d&&(r=r.substr(1));const p=l?_d.Depth:"u"===d?_d.Uint:"i"===d?_d.Sint:_d.Float;o.sampleType=p;const f=s>0,_=u.binding.groupIndex,m=u.binding.bindingIndex,g=Vd._SamplerFunctionByWebGLSamplerType[r],v=Vd._TextureTypeByWebGLSamplerType[r],x=Vd._GpuTextureViewDimensionByWebGPUTextureType[v];if(f){const t=[];t.push(`layout(set = ${_}, binding = ${m}) uniform ${d}${a} ${c};`),e="\n";for(let i=0;i0?"\n":""}#define ${n}${i} ${d}${g}(${n}Texture${i}, ${c})`}e=t.join("\n")+e,this._textureArrayProcessing.push(n)}else s=1,e=`layout(set = ${_}, binding = ${m}) uniform ${a} ${c};\n layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${d}${v} ${n}Texture;\n #define ${n} ${d}${g}(${n}Texture, ${c})`;this._webgpuProcessingContext.availableTextures[n]=o,this._webgpuProcessingContext.availableSamplers[c]=u,this._addSamplerBindingDescription(c,u,!t);for(let e=0;e=0,i="\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n ",s=t?"vec4 glFragCoord_;\n":"",r=-1!==e.search(/layout *\(location *= *0\) *out/g);if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){const t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(n||r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",s),t&&(e=Du(e,"void main",i))}else if(e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex"),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;if(!i){const t=e.lastIndexOf("}");e=e.substring(0,t),e+="gl_Position.y *= yFactor_;\n",e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let s=i.exec(e);for(;null!==s;){const r=s[1];let n=+r;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[r.trim()]),e=e.replace(s[0],t+n),s=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} {\n `;for(const e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}];\n`:i+=` ${e.type} ${e.name};\n`;return i+="};\n\n",i}finalizeShaders(e,t){for(let i=0;i0&&(t=i+"\n"+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}Ft.IncludesShadersStoreWGSL.bonesDeclaration="#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4;attribute matricesWeights : vec4;\n#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d;uniform boneTextureWidth : f32;\n#else\nuniform mBones : array;\n#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array;\n#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\n{let offset=i32(index) *4; \nlet m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);}\n#endif\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.bonesVertex="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\n#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\n#endif \n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4\n{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);}\n#endif\n";Ft.IncludesShadersStoreWGSL.bakedVertexAnimation="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\n#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\n#endif\nlet totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;}\n#endif\n";Ft.IncludesShadersStoreWGSL.clipPlaneFragment="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fragmentInputs.fClipDistance>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\n{discard;}\n#endif\n";Ft.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration="#ifdef CLIPPLANE\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nvarying fClipDistance6: f32;\n#endif\n";Ft.IncludesShadersStoreWGSL.clipPlaneVertex="#ifdef CLIPPLANE\nvertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nvertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nvertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nvertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nvertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nvertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);\n#endif\n";Ft.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration="#ifdef CLIPPLANE\nuniform vClipPlane: vec4;varying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4;varying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4;varying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4;varying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4;varying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4;varying fClipDistance6: f32;\n#endif\n";Ft.IncludesShadersStoreWGSL.instancesDeclaration="#ifdef INSTANCES\nattribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4;\n#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4;\n#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform previousWorld : mat4x4;\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.instancesVertex="#ifdef INSTANCES\nvar finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\n#if !defined(WORLD_UBO)\nfinalWorld=uniforms.world*finalWorld;\n#else\nfinalWorld=mesh.world*finalWorld;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nvar finalWorld=uniforms.world;\n#else\nvar finalWorld=mesh.world;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=previousWorld;\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.helperFunctions="const PI: f32=3.1415926535897932384626433832795;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const HALF_MIN: f32=5.96046448e-08; \nconst LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3=vec3 (0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\nfn transposeMat3(inMatrix: mat3x3f)->mat3x3f {let i0: vec3=inMatrix[0];let i1: vec3=inMatrix[1];let i2: vec3=inMatrix[2];let outMatrix:mat3x3f=mat3x3f(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nfn inverseMat3(inMatrix: mat3x3f)->mat3x3f {let a00: f32=inMatrix[0][0];let a01: f32=inMatrix[0][1];let a02: f32=inMatrix[0][2];let a10: f32=inMatrix[1][0];let a11: f32=inMatrix[1][1];let a12: f32=inMatrix[1][2];let a20: f32=inMatrix[2][0];let a21: f32=inMatrix[2][1];let a22: f32=inMatrix[2][2];let b01: f32=a22*a11-a12*a21;let b11: f32=-a22*a10+a12*a20;let b21: f32=a21*a10-a11*a20;let det: f32=a00*b01+a01*b11+a02*b21;return mat3x3f(b01/det,(-a22*a01+a02*a21)/det,(a12*a01-a02*a11)/det,\nb11/det,(a22*a00-a02*a20)/det,(-a12*a00+a02*a10)/det,\nb21/det,(-a21*a00+a01*a20)/det,(a11*a00-a01*a10)/det);}\n#if USE_EXACT_SRGB_CONVERSIONS\nfn toLinearSpaceExact(color: vec3)->vec3\n{let nearZeroSection: vec3=0.0773993808*color;let remainingSection: vec3=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));}\nfn toGammaSpaceExact(color: vec3)->vec3\n{let nearZeroSection: vec3=12.92*color;let remainingSection: vec3=1.055*pow(color,vec3(0.41666))-vec3(0.055);return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));}\n#endif\nfn toLinearSpace(color: vec4)->vec4\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfn toLinearSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nfn toGammaSpace(color: vec4)->vec4\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfn toGammaSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nfn square(value: vec3)->vec3\n{return value*value;}\nfn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;}\nfn getLuminance(color: vec3)->f32\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfn getRand(seed: vec2)->f32 {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfn dither(seed: vec2,varianceAmount: f32)->f32 {let rand: f32=getRand(seed);let normVariance: f32=varianceAmount/255.0;let dither: f32=mix(-normVariance,normVariance,rand);return dither;}\nconst rgbdMaxRange: f32=255.0;fn toRGBD(color: vec3)->vec4 {let maxRGB: f32=max(max(color.r,max(color.g,color.b)),Epsilon);var D: f32 =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);var rgb: vec3 =color.rgb*D;rgb=toGammaSpaceVec3(rgb);return vec4(clamp(rgb,vec3(0.,0.,0.),vec3(1.,1.,1.)),D); }\nfn fromRGBD(rgbd: vec4)->vec3 {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;}\nfn parallaxCorrectNormal(vertexPos: vec3,origVec: vec3,cubeSize: vec3,cubePos: vec3)->vec3 {let invOrigVec: vec3=vec3(1.0,1.0,1.0)/origVec;let halfSize: vec3=cubeSize*0.5;let intersecAtMaxPlane: vec3=(cubePos+halfSize-vertexPos)*invOrigVec;let intersecAtMinPlane: vec3=(cubePos-halfSize-vertexPos)*invOrigVec;let largestIntersec: vec3=max(intersecAtMaxPlane,intersecAtMinPlane);let distance: f32=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);let intersectPositionWS: vec3=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";Ft.IncludesShadersStoreWGSL.fresnelFunction="#ifdef FRESNEL\nfn computeFresnelTerm(viewDirection: vec3f,worldNormal: vec3f,bias: f32,power: f32)->f32\n{let fresnelTerm: f32=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}\n#endif\n";Ft.IncludesShadersStoreWGSL.meshUboDeclaration="struct Mesh {world : mat4x4,\nvisibility : f32,};var mesh : Mesh;\n#define WORLD_UBO\n";Ft.IncludesShadersStoreWGSL.morphTargetsVertex="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (var i=0; i=uniforms.morphTargetCount) {break;}\nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n}\n#endif\n#else\npositionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3;\n#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2;\n#endif\n#elif {X}==0\nuniform morphTargetCount: i32;\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.morphTargetsVertexGlobal="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration="#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array;\n#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3\n{ \nlet y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;}\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.sceneUboDeclaration="struct Scene {viewProjection : mat4x4,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4,\n#endif \nview : mat4x4,\nprojection : mat4x4,\nvEyePosition : vec4,};var scene : Scene;\n";Ft.IncludesShadersStoreWGSL.lightsFragmentFunctions="struct lightingInfo\n{diffuse: vec3f,\n#ifdef SPECULARTERM\nspecular: vec3f,\n#endif\n#ifdef NDOTL\nndl: f32,\n#endif\n};fn computeLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var lightVectorW: vec3f;var attenuation: f32=1.0;if (lightData.w==0.)\n{var direction: vec3f=lightData.xyz-vPositionW;var attenuation: f32=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nvar ndl: f32=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nfn computeSpotLighting(viewDirectionW: vec3f,vNormal: vec3f ,lightData: vec4f,lightDirection: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var direction: vec3f=lightData.xyz-vPositionW;var lightVectorW: vec3f=normalize(direction);var attenuation: f32=max(0.,1.0-length(direction)/range);var cosAngle: f32=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;var ndl: f32=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3f(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3f(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nfn computeHemisphericLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,groundColor: vec3f,glossiness: f32)->lightingInfo {var result: lightingInfo;var ndl: f32=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightData.xyz);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\nfn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f)->vec3f {var strq: vec4f=textureProjectionMatrix*vec4f(vPositionW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return textureColor;}";Ft.IncludesShadersStoreWGSL.lightFragment="#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(POINTLIGHT{X})\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(HEMILIGHT{X})\npreInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(DIRLIGHT{X})\npreInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#endif\npreInfo.NdotV=NdotV;\n#ifdef SPOTLIGHT{X}\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\n#elif defined(POINTLIGHT{X})\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\n#else\npreInfo.attenuation=1.0;\n#endif\n#ifdef HEMILIGHT{X}\npreInfo.roughness=roughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#ifdef IRIDESCENCE\npreInfo.iridescenceIntensity=iridescenceIntensity;\n#endif\n#ifdef HEMILIGHT{X}\ninfo.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround);\n#elif defined(SS_TRANSLUCENCY)\ninfo.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance);\n#else\ninfo.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef SPECULARTERM\n#ifdef ANISOTROPIC\ninfo.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#else\ninfo.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#endif\n#ifdef SHEEN\n#ifdef SHEEN_LINKWITHALBEDO\npreInfo.roughness=sheenOut.sheenIntensity;\n#else\n#ifdef HEMILIGHT{X}\npreInfo.roughness=sheenOut.sheenRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#endif\ninfo.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef CLEARCOAT\n#ifdef HEMILIGHT{X}\npreInfo.roughness=clearcoatOut.clearCoatRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\ninfo.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb);\n#ifdef CLEARCOAT_TINT\nabsorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;\n#ifdef SPECULARTERM\ninfo.specular*=absorption;\n#endif\n#endif\ninfo.diffuse*=info.clearCoat.w;\n#ifdef SPECULARTERM\ninfo.specular*=info.clearCoat.w;\n#endif\n#ifdef SHEEN\ninfo.sheen*=info.clearCoat.w;\n#endif\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},projectionLightTexture{X}Sampler,textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSMDEBUG{X} \nvar shadowDebug{X}: vec3f;\n#endif\n#ifdef SHADOWCSM{X}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nvar index{X}: i32=-1;\n#else\nvar index{X}: i32=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nvar diff{X}: f32=0.;vPositionFromLight{X}[0]=fragmentInputs.vPositionFromLight{X}_0;vPositionFromLight{X}[1]=fragmentInputs.vPositionFromLight{X}_1;vPositionFromLight{X}[2]=fragmentInputs.vPositionFromLight{X}_2;vPositionFromLight{X}[3]=fragmentInputs.vPositionFromLight{X}_3;vDepthMetric{X}[0]=fragmentInputs.vDepthMetric{X}_0;vDepthMetric{X}[1]=fragmentInputs.vDepthMetric{X}_1;vDepthMetric{X}[2]=fragmentInputs.vDepthMetric{X}_2;vDepthMetric{X}[3]=fragmentInputs.vDepthMetric{X}_3;for (var i:i32=0; i=0.) {index{X}=i;break;}}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nif (index{X}>=0)\n#endif\n{\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#else\nshadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#endif\n#else\nshadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=vec3f(shadow)*vCascadeColorsMultiplier{X}[index{X}];\n#endif\n#ifndef SHADOWCSMNOBLEND{X}\nvar frustumLength:f32=uniforms.frustumLengths{X}[index{X}];var diffRatio:f32=clamp(diff{X}/frustumLength,0.,1.)*uniforms.cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)\n{index{X}+=1;var nextShadow: f32=0.;\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nnextShadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#else\nnextShadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#endif\n#else\nnextShadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\nshadow=mix(nextShadow,shadow,diffRatio);\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);\n#endif\n}\n#endif\n}\n#elif defined(SHADOWCLOSEESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;shadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\naggShadow+=shadow;numLights+=1.0;\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor.rgb*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifndef LIGHTMAPNOSPECULAR{X}\nclearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef SHEEN\n#ifndef LIGHTMAPNOSPECULAR{X}\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#else\n#ifdef SHADOWCSMDEBUG{X}\ndiffuseBase+=info.diffuse*shadowDebug{X};\n#else \ndiffuseBase+=info.diffuse*shadow;\n#endif\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#ifdef CLEARCOAT\nclearCoatBase+=info.clearCoat.rgb*shadow;\n#endif\n#ifdef SHEEN\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.lightUboDeclaration="#ifdef LIGHT{X}\nstruct Light{X}\n{vLightData: vec4f,\nvLightDiffuse: vec4f,\nvLightSpecular: vec4f,\n#ifdef SPOTLIGHT{X}\nvLightDirection: vec4f,\nvLightFalloff: vec4f,\n#elif defined(POINTLIGHT{X})\nvLightFalloff: vec4f,\n#elif defined(HEMILIGHT{X})\nvLightGround: vec3f,\n#endif\nshadowsInfo: vec4f,\ndepthValues: vec2f} ;var light{X} : Light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform textureProjectionMatrix{X}: mat4x4f;var projectionLightTexture{X}sampler: sampler;var projectionLightTexture{X}: texture_2d;\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array;uniform viewFrustumZ{X}: array;uniform frustumLengths{X}: array;uniform cascadeBlendFactor{X}: f32;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;var vPositionFromLight{X}: array;var vDepthMetric{X} : array;\n#if defined(SHADOWPCSS{X})\nvar shadowTexture{X}Sampler: sampler_comparison; \nvar shadowTexture{X}: texture_depth_2d_array;var depthTexture{X}Sampler: sampler;var depthTexture{X}: texture_2d_array;uniform lightSizeUVCorrection{X}: array;uniform depthCorrection{X}: array;uniform penumbraDarkness{X}: f32;\n#elif defined(SHADOWPCF{X})\nvar shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d_array;\n#else \nvar shadowTexture{X}Sampler: sampler; \nvar shadowTexture{X}: texture_2d_array;\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vCascadeColorsMultiplier{X}: array=array\n(\nvec3f ( 1.5,0.0,0.0 ),\nvec3f ( 0.0,1.5,0.0 ),\nvec3f ( 0.0,0.0,5.5 ),\nvec3f ( 1.5,0.0,5.5 ),\nvec3f ( 1.5,1.5,0.0 ),\nvec3f ( 1.0,1.0,1.0 ),\nvec3f ( 0.0,1.0,5.5 ),\nvec3f ( 0.5,3.5,0.75 )\n);\n#endif\n#elif defined(SHADOWCUBE{X})\nvar shadowTexture{X}Sampler: sampler;var shadowTexture{X}: texture_cube;\n#else\nvarying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;\n#if defined(SHADOWPCSS{X})\nvar shadowTexture{X}Sampler: sampler_comparison; \nvar shadowTexture{X}: texture_depth_2d;var depthTexture{X}Sampler: sampler; \nvar depthTexture{X}: texture_2d;\n#elif defined(SHADOWPCF{X})\nvar shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d;\n#else\nvar shadowTexture{X}Sampler: sampler; \nvar shadowTexture{X}: texture_2d;\n#endif\nuniform lightMatrix{X}: mat4x4f;\n#endif\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.lightVxUboDeclaration="#ifdef LIGHT{X}\nstruct Light{X}\n{vLightData: vec4f,\nvLightDiffuse: vec4f,\nvLightSpecular: vec4f,\n#ifdef SPOTLIGHT{X}\nvLightDirection: vec4f,\nvLightFalloff: vec4f,\n#elif defined(POINTLIGHT{X})\nvLightFalloff: vec4f,\n#elif defined(HEMILIGHT{X})\nvLightGround: vec3f,\n#endif\nshadowsInfo: vec4f,\ndepthValues: vec2f} ;var light{X} : Light{X};\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f;\n#endif\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.shadowsFragmentFunctions="#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfn unpack(color: vec4f)->f32\n{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}\n#endif\nfn computeFallOff(value: f32,clipSpace: vec2f,frustumEdgeFalloff: f32)->f32\n{var mask: f32=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\nfn computeShadowCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadow: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nreturn select(darkness,1.0,depth>shadow);}\nfn computeShadowWithPoissonSamplingCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,mapSize: f32,darkness: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec3f(-1.0,1.0,-1.0);poissonDisk[1]= vec3f(1.0,-1.0,-1.0);poissonDisk[2]= vec3f(-1.0,-1.0,-1.0);poissonDisk[3]= vec3f(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[0]*mapSize)),shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nvar esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;}\nfn computeShadowWithCloseESMCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nvar esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;}\nfn computeShadowCSM(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d_array,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,uv,layer));\n#else\nvar shadow: f32=textureSample(shadowTexture,shadowSampler,uv,layer).x;\n#endif\nreturn select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}\nfn computeShadow(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadow: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nreturn select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}}\nfn computeShadowWithPoissonSampling(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,mapSize: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec2f(-0.94201624,-0.39906216);poissonDisk[1]= vec2f(0.94558609,-0.76890725);poissonDisk[2]= vec2f(-0.094184101,-0.92938870);poissonDisk[3]= vec2f(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[0]*mapSize,0.)),shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nvar esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithCloseESM(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nvar esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\nfn getZInClip(clipSpace: vec3f,uvDepth: vec3f)->f32\n{\n#ifdef IS_NDC_HALF_ZRANGE\nreturn clipSpace.z;\n#else\nreturn uvDepth.z;\n#endif\n}\nconst GREATEST_LESS_THAN_ONE: f32=0.99999994;\n#define DIAGNOSTIC_OFF\nfn computeShadowWithCSMPCF1(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var shadow: f32=textureSampleCompare(shadowTexture,shadowSampler,uvDepth.xy,layer,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithCSMPCF3(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithCSMPCF5(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),layer,uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),layer,uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),layer,uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),layer,uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithPCF1(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var shadow: f32=textureSampleCompareLevel(shadowTexture,shadowSampler,uvDepth.xy,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithPCF3(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithPCF5(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nconst PoissonSamplers32: array=array (\nvec3f(0.06407013,0.05409927,0.),\nvec3f(0.7366577,0.5789394,0.),\nvec3f(-0.6270542,-0.5320278,0.),\nvec3f(-0.4096107,0.8411095,0.),\nvec3f(0.6849564,-0.4990818,0.),\nvec3f(-0.874181,-0.04579735,0.),\nvec3f(0.9989998,0.0009880066,0.),\nvec3f(-0.004920578,-0.9151649,0.),\nvec3f(0.1805763,0.9747483,0.),\nvec3f(-0.2138451,0.2635818,0.),\nvec3f(0.109845,0.3884785,0.),\nvec3f(0.06876755,-0.3581074,0.),\nvec3f(0.374073,-0.7661266,0.),\nvec3f(0.3079132,-0.1216763,0.),\nvec3f(-0.3794335,-0.8271583,0.),\nvec3f(-0.203878,-0.07715034,0.),\nvec3f(0.5912697,0.1469799,0.),\nvec3f(-0.88069,0.3031784,0.),\nvec3f(0.5040108,0.8283722,0.),\nvec3f(-0.5844124,0.5494877,0.),\nvec3f(0.6017799,-0.1726654,0.),\nvec3f(-0.5554981,0.1559997,0.),\nvec3f(-0.3016369,-0.3900928,0.),\nvec3f(-0.5550632,-0.1723762,0.),\nvec3f(0.925029,0.2995041,0.),\nvec3f(-0.2473137,0.5538505,0.),\nvec3f(0.9183037,-0.2862392,0.),\nvec3f(0.2469421,0.6718712,0.),\nvec3f(0.3916397,-0.4328209,0.),\nvec3f(-0.03576927,-0.6220032,0.),\nvec3f(-0.04661255,0.7995201,0.),\nvec3f(0.4402924,0.3640312,0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.)\n);const PoissonSamplers64: array=array (\nvec3f(-0.613392,0.617481,0.),\nvec3f(0.170019,-0.040254,0.),\nvec3f(-0.299417,0.791925,0.),\nvec3f(0.645680,0.493210,0.),\nvec3f(-0.651784,0.717887,0.),\nvec3f(0.421003,0.027070,0.),\nvec3f(-0.817194,-0.271096,0.),\nvec3f(-0.705374,-0.668203,0.),\nvec3f(0.977050,-0.108615,0.),\nvec3f(0.063326,0.142369,0.),\nvec3f(0.203528,0.214331,0.),\nvec3f(-0.667531,0.326090,0.),\nvec3f(-0.098422,-0.295755,0.),\nvec3f(-0.885922,0.215369,0.),\nvec3f(0.566637,0.605213,0.),\nvec3f(0.039766,-0.396100,0.),\nvec3f(0.751946,0.453352,0.),\nvec3f(0.078707,-0.715323,0.),\nvec3f(-0.075838,-0.529344,0.),\nvec3f(0.724479,-0.580798,0.),\nvec3f(0.222999,-0.215125,0.),\nvec3f(-0.467574,-0.405438,0.),\nvec3f(-0.248268,-0.814753,0.),\nvec3f(0.354411,-0.887570,0.),\nvec3f(0.175817,0.382366,0.),\nvec3f(0.487472,-0.063082,0.),\nvec3f(-0.084078,0.898312,0.),\nvec3f(0.488876,-0.783441,0.),\nvec3f(0.470016,0.217933,0.),\nvec3f(-0.696890,-0.549791,0.),\nvec3f(-0.149693,0.605762,0.),\nvec3f(0.034211,0.979980,0.),\nvec3f(0.503098,-0.308878,0.),\nvec3f(-0.016205,-0.872921,0.),\nvec3f(0.385784,-0.393902,0.),\nvec3f(-0.146886,-0.859249,0.),\nvec3f(0.643361,0.164098,0.),\nvec3f(0.634388,-0.049471,0.),\nvec3f(-0.688894,0.007843,0.),\nvec3f(0.464034,-0.188818,0.),\nvec3f(-0.440840,0.137486,0.),\nvec3f(0.364483,0.511704,0.),\nvec3f(0.034028,0.325968,0.),\nvec3f(0.099094,-0.308023,0.),\nvec3f(0.693960,-0.366253,0.),\nvec3f(0.678884,-0.204688,0.),\nvec3f(0.001801,0.780328,0.),\nvec3f(0.145177,-0.898984,0.),\nvec3f(0.062655,-0.611866,0.),\nvec3f(0.315226,-0.604297,0.),\nvec3f(-0.780145,0.486251,0.),\nvec3f(-0.371868,0.882138,0.),\nvec3f(0.200476,0.494430,0.),\nvec3f(-0.494552,-0.711051,0.),\nvec3f(0.612476,0.705252,0.),\nvec3f(-0.578845,-0.768792,0.),\nvec3f(-0.772454,-0.090976,0.),\nvec3f(0.504440,0.372295,0.),\nvec3f(0.155736,0.065157,0.),\nvec3f(0.391522,0.849605,0.),\nvec3f(-0.620106,-0.328104,0.),\nvec3f(0.789239,-0.419965,0.),\nvec3f(-0.545396,0.538133,0.),\nvec3f(-0.178564,-0.596057,0.)\n);fn computeShadowWithCSMPCSS(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uvDepthLayer: vec4f= vec4f(uvDepth.x,uvDepth.y,f32(layer),uvDepth.z);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;var exitCondition: bool=depthMetric>1.0 || depthMetric<0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);}\nfn computeShadowWithPCSS32(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);}\nfn computeShadowWithPCSS64(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);}\nfn computeShadowWithCSMPCSS16(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\nfn computeShadowWithCSMPCSS32(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\nfn computeShadowWithCSMPCSS64(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#endif\n";Ft.IncludesShadersStoreWGSL.shadowsVertex="#ifdef SHADOWS\n#if defined(SHADOWCSM{X})\nvertexOutputs.vPositionFromCamera{X}=view*worldPos;\n#if SHADOWCSMNUM_CASCADES{X}>0\nvertexOutputs.vPositionFromLight{X}_0=uniforms.lightMatrix{X}[0]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_0=(-vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_0= (vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#if SHADOWCSMNUM_CASCADES{X}>1\nvertexOutputs.vPositionFromLight{X}_1=uniforms.lightMatrix{X}[1]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_1=(-vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_1= (vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#if SHADOWCSMNUM_CASCADES{X}>2\nvertexOutputs.vPositionFromLight{X}_2=uniforms.lightMatrix{X}[2]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_2=(-vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_2= (vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#if SHADOWCSMNUM_CASCADES{X}>3\nvertexOutputs.vPositionFromLight{X}_3=uniforms.lightMatrix{X}[3]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_3=(-vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_3= (vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvertexOutputs.vPositionFromLight{X}=uniforms.lightMatrix{X}*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}=(-vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}=(vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.fogFragmentDeclaration="#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vFogInfos: vec4f;uniform vFogColor: vec3f;varying vFogDistance: vec3f;fn CalcFogFactor()->f32\n{var fogCoeff: f32=1.0;var fogStart: f32=uniforms.vFogInfos.y;var fogEnd: f32=uniforms.vFogInfos.z;var fogDensity: f32=uniforms.vFogInfos.w;var fogDistance: f32=length(fragmentInputs.vFogDistance);if (FOGMODE_LINEAR==uniforms.vFogInfos.x)\n{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);}\nelse if (FOGMODE_EXP==uniforms.vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDensity);}\nelse if (FOGMODE_EXP2==uniforms.vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);}\nreturn clamp(fogCoeff,0.0,1.0);}\n#endif\n";Ft.IncludesShadersStoreWGSL.bumpFragment="var uvOffset: vec2f= vec2f(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)\n#ifdef NORMALXYSCALE\nvar normalScale: f32=1.0;\n#elif defined(BUMP)\nvar normalScale: f32=vBumpInfos.y;\n#else\nvar normalScale: f32=1.0;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nvar TBN: mat3x3f=vTBN;\n#elif defined(BUMP)\nvar TBNUV: vec2f=select(-vBumpUV,vBumpUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);\n#else\nvar TBNUV: vec2f=select(-vDetailUV,vDetailUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,vPositionW,TBNUV, vec2f(1.,1.));\n#endif\n#elif defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvar TBN: mat3x3f=vTBN;\n#else\nvar TBNUV: vec2f=select( -vMainUV1,vMainUV1,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW,vPositionW,TBNUV, vec2f(1.,1.));\n#endif\n#endif\n#ifdef PARALLAX\nvar invTBN: mat3x3f=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef DETAIL\nvar detailColor: vec4f=textureSample(detail,detailSampler,vDetailUV+uvOffset);var detailNormalRG: vec2f=detailColor.wy*2.0-1.0;var detailNormalB: f32=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));var detailNormal: vec3f= vec3f(detailNormalRG,detailNormalB);\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\n#define CUSTOM_FRAGMENT_BUMP_FRAGMENT\nnormalW=normalize(textureSample(bump,bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize( mat3x3f(normalMatrix)*normalW);\n#elif !defined(DETAIL)\nnormalW=perturbNormal(TBN,textureSample(bump,bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);\n#else\nvar bumpNormal: vec3f=textureSample(bump,bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;\n#if DETAIL_NORMALBLENDMETHOD==0 \ndetailNormal.xy*=vDetailInfos.z;var blendedNormal: vec3f=normalize( vec3f(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));\n#elif DETAIL_NORMALBLENDMETHOD==1 \ndetailNormal.xy*=vDetailInfos.z;bumpNormal+= vec3f(0.0,0.0,1.0);detailNormal*= vec3f(-1.0,-1.0,1.0);var blendedNormal: vec3f=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;\n#endif\nnormalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);\n#endif\n#elif defined(DETAIL)\ndetailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);\n#endif\n";Ft.IncludesShadersStoreWGSL.bumpFragmentMainFunctions="#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)\n#if defined(TANGENT) && defined(NORMAL) \nvarying vTBN: mat3x3f;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform normalMatrix: mat4x4f;\n#if defined(WEBGL2) || defined(WEBGPU)\nfn toNormalMatrix(wMatrix: mat4x4f)->mat4x4f\n{var ret: mat4x4f=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]= vec4f(0.,0.,0.,1.);return ret;}\n#else\nfn toNormalMatrix(m: mat4x4f)->mat4x4f\n{var a00: f32=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3],\na10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3],\na20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3],\na30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3],\nb00=a00*a11-a01*a10,\nb01=a00*a12-a02*a10,\nb02=a00*a13-a03*a10,\nb03=a01*a12-a02*a11,\nb04=a01*a13-a03*a11,\nb05=a02*a13-a03*a12,\nb06=a20*a31-a21*a30,\nb07=a20*a32-a22*a30,\nb08=a20*a33-a23*a30,\nb09=a21*a32-a22*a31,\nb10=a21*a33-a23*a31,\nb11=a22*a33-a23*a32,\ndet=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;var mi: mat4x4f= mat4x4f(\na11*b11-a12*b10+a13*b09,\na02*b10-a01*b11-a03*b09,\na31*b05-a32*b04+a33*b03,\na22*b04-a21*b05-a23*b03,\na12*b08-a10*b11-a13*b07,\na00*b11-a02*b08+a03*b07,\na32*b02-a30*b05-a33*b01,\na20*b05-a22*b02+a23*b01,\na10*b10-a11*b08+a13*b06,\na01*b08-a00*b10-a03*b06,\na30*b04-a31*b02+a33*b00,\na21*b02-a20*b04-a23*b00,\na11*b07-a10*b09-a12*b06,\na00*b09-a01*b07+a02*b06,\na31*b01-a30*b03-a32*b00,\na20*b03-a21*b01+a22*b00)/det;return mat4x4f(mi[0][0],mi[1][0],mi[2][0],mi[3][0],\nmi[0][1],mi[1][1],mi[2][1],mi[3][1],\nmi[0][2],mi[1][2],mi[2][2],mi[3][2],\nmi[0][3],mi[1][3],mi[2][3],mi[3][3]);}\n#endif\n#endif\nfn perturbNormalBase(cotangentFrame: mat3x3f,normal: vec3f,scale: f32)->vec3f\n{\n#ifdef NORMALXYSCALE\nnormal=normalize(normal* vec3f(scale,scale,1.0));\n#endif\nreturn normalize(cotangentFrame*normal);}\nfn perturbNormal(cotangentFrame: mat3x3f,textureSample: vec3f,scale: f32)->vec3f\n{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}\nfn cotangent_frame(normal: vec3f,p: vec3f,uv: vec2f,tangentSpaceParams: vec2f)->mat3x3f\n{var dp1: vec3f=dpdx(p);var dp2: vec3f=dpdy(p);var duv1: vec2f=dpdx(uv);var duv2: vec2f=dpdy(uv);var dp2perp: vec3f=cross(dp2,normal);var dp1perp: vec3f=cross(normal,dp1);var tangent: vec3f=dp2perp*duv1.x+dp1perp*duv2.x;var bitangent: vec3f=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;var det: f32=max(dot(tangent,tangent),dot(bitangent,bitangent));var invmax: f32=select(inverseSqrt(det),0.0,det==0.0);return mat3x3f(tangent*invmax,bitangent*invmax,normal);}\n#endif\n";Ft.IncludesShadersStoreWGSL.samplerFragmentDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying v_VARYINGNAME_UV: vec2f;\n#endif\nuniform _SAMPLERNAME_Sampler: sampler;uniform _SAMPLERNAME_: texture_2d;\n#endif\n";Ft.IncludesShadersStoreWGSL.bumpFragmentFunctions="#if defined(BUMP)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)\n#endif\n#if defined(DETAIL)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)\n#endif\n#if defined(BUMP) && defined(PARALLAX)\nconst minSamples: f32=4.;const maxSamples: f32=15.;const iMaxSamples: i32=15;fn parallaxOcclusion(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32)->vec2f {var parallaxLimit: f32=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;var vOffsetDir: vec2f=normalize(vViewDirCoT.xy);var vMaxOffset: vec2f=vOffsetDir*parallaxLimit;var numSamples: f32=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));var stepSize: f32=1.0/numSamples;var currRayHeight: f32=1.0;var vCurrOffset: vec2f= vec2f(0,0);var vLastOffset: vec2f= vec2f(0,0);var lastSampledHeight: f32=1.0;var currSampledHeight: f32=1.0;var keepWorking: bool=true;for (var i: i32=0; icurrRayHeight)\n{var delta1: f32=currSampledHeight-currRayHeight;var delta2: f32=(currRayHeight+stepSize)-lastSampledHeight;var ratio: f32=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}\nelse\n{currRayHeight-=stepSize;vLastOffset=vCurrOffset;\n#ifdef PARALLAX_RHS\nvCurrOffset-=stepSize*vMaxOffset;\n#else\nvCurrOffset+=stepSize*vMaxOffset;\n#endif\nlastSampledHeight=currSampledHeight;}}\nreturn vCurrOffset;}\nfn parallaxOffset(viewDir: vec3f,heightScale: f32)->vec2f\n{var height: f32=textureSample(bump,bumpSampler,vBumpUV).w;var texCoordOffset: vec2f=heightScale*viewDir.xy*height;\n#ifdef PARALLAX_RHS\nreturn texCoordOffset;\n#else\nreturn -texCoordOffset;\n#endif\n}\n#endif\n";const Wd={texture_1d:nd.E1d,texture_2d:nd.E2d,texture_2d_array:nd.E2dArray,texture_3d:nd.E3d,texture_cube:nd.Cube,texture_cube_array:nd.CubeArray,texture_multisampled_2d:nd.E2d,texture_depth_2d:nd.E2d,texture_depth_2d_array:nd.E2dArray,texture_depth_cube:nd.Cube,texture_depth_cube_array:nd.CubeArray,texture_depth_multisampled_2d:nd.E2d,texture_storage_1d:nd.E1d,texture_storage_2d:nd.E2d,texture_storage_2d_array:nd.E2dArray,texture_storage_3d:nd.E3d,texture_external:null};class Hd extends Vd{constructor(){super(...arguments),this.shaderLanguage=ht.WGSL,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0}preProcessor(e,t,i,s,r){for(const t in i){if("__VERSION__"===t)continue;const s=i[t];isNaN(parseInt(s))&&isNaN(parseFloat(s))||(e=`const ${t} = ${s};\n`+e)}return e}_getArraySize(e,t,i){let s=0;const r=t.lastIndexOf(">");if(t.indexOf("array")>=0&&r>0){let e=r;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;const n=t.substring(e+1,r);for(s=+n,isNaN(s)&&(s=+i[n.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){const t=`struct ${Vd.InternalsUBOName} {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar internals : ${Vd.InternalsUBOName};\n`;return-1!==e.indexOf(t)?e:t+Pu(e)}varyingCheck(e,t){return/(flat|linear|perspective)?\s*(center|centroid|sample)?\s*\bvarying\b/.test(e)}varyingProcessor(e,t,i){const s=/\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==s){const r=s[1]??"perspective",n=s[2]??"center",o=s[4],a=s[3],l="flat"===r?`@interpolate(${r})`:`@interpolate(${r}, ${n})`;let h;t?(h=this._webgpuProcessingContext.availableVaryings[a],void 0===h&&J.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`)):(h=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(a,o,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=h,this._varyingsWGSL.push(` @location(${h}) ${l} ${a} : ${o},`),this._varyingNamesWGSL.push(a)),e=""}return e}attributeProcessor(e,t){const i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){const s=i[2],r=i[1],n=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(r,s,t)[2]);this._webgpuProcessingContext.availableAttributes[r]=n,this._webgpuProcessingContext.orderedAttributes[n]=r;const o=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[r];if(void 0!==o){const e=o<0?-1===o?"i32":"vec"+-o+"":1===o?"u32":"vec"+o+"",t=`_int_${r}_`;this._attributesInputWGSL.push(`@location(${n}) ${t} : ${e},`),this._attributesWGSL.push(`${r} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${r} = ${s}(vertexInputs_.${t});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${n}) ${r} : ${s},`),this._attributesWGSL.push(`${r} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${r} = vertexInputs_.${r};`);e=""}return e}uniformProcessor(e,t,i){const s=this.uniformRegexp.exec(e);if(null!==s){const t=s[2],r=s[1];this._addUniformToLeftOverUBO(r,t,i),e=""}return e}textureProcessor(e,t,i){const s=this.textureRegexp.exec(e);if(null!==s){const r=s[1],n=s[2],o=!!s[3],a=s[4],l=a.indexOf("storage")>0,h=s[6],c=l?h.substring(0,h.indexOf(",")).trim():null;let u=o?this._getArraySize(r,n,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[r];if(d)u=d.textures.length;else{d={isTextureArray:u>0,isStorageTexture:l,textures:[],sampleType:_d.Float},u=u||1;for(let e=0;e0,f=Wd[a],_=p?_d.Depth:"u32"===h?_d.Uint:"i32"===h?_d.Sint:_d.Float;if(d.sampleType=_,void 0===f)throw`Can't get the texture dimension corresponding to the texture function "${a}"!`;for(let i=0;i=0?"\n if (internals.yFactor_ == 1.) {\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\n }\n ":"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);const s=this._buildLeftOverUBO();t=s+t,e=(e=(e=s+e).replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;")).replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let r="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesInputWGSL.length>0&&(r+=this._attributesInputWGSL.join("\n")),r+="\n};\nvar vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(r+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n",r+=this._attributesWGSL.join("\n"),r+="\n};\nvar vertexInputs : VertexInputs_;\n");let n="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join("\n")),n+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=r+n+e;let o=`\n vertexInputs${this._hasNonFloatAttribute?"_":""} = input;\n`;this._hasNonFloatAttribute&&(o+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n",o+=this._attributesConversionCodeWGSL.join("\n"),o+="\n");let a=-1!==e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS");e=(a?"diagnostic(off, derivative_uniformity);\n":"")+Du(e,"fn main",o," vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;"),t=(t=t.replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;")).replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let l="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(l+=this._varyingsWGSL.join("\n")),l+="\n};\nvar fragmentInputs : FragmentInputs;\n";let h="struct FragmentOutputs {\n @location(0) color : vec4,\n",c=!1,u=0;for(;!(c||(u=t.indexOf("fragmentOutputs.fragDepth",u),u<0));){const e=u;for(c=!0;u>1&&"\n"!==t.charAt(u);){if("/"===t.charAt(u)&&"/"===t.charAt(u-1)){c=!1;break}u--}u=e+25}c&&(h+=" @builtin(frag_depth) fragDepth: f32,\n"),h+="};\nvar fragmentOutputs : FragmentOutputs;\n";const d=" fragmentInputs = input;\n "+i;return a=-1!==(t=l+h+t).indexOf("#define DISABLE_UNIFORMITY_ANALYSIS"),t=(a?"diagnostic(off, derivative_uniformity);\n":"")+Du(t,"fn main",d," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",s=`struct ${e} {\n`;for(const t of this._webgpuProcessingContext.leftOverUniforms){const r=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),n=Vd.UniformSizes[r];if(t.length>0)if(n<=2){const n=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${n} {\n @size(16)\n el: ${r},\n }`,this._stridedUniformArrays.push(t.name),s+=` @align(16) ${t.name} : array<${n}, ${t.length}>,\n`}else s+=` ${t.name} : array<${t.type}, ${t.length}>,\n`;else s+=` ${t.name} : ${t.type},\n`}return s+="};\n",s=`${i}\n${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var uniforms : ${e};\n`,s}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const s=i.exec(e);if(null===s)break;const r=s[1],n=s[2],o=r.indexOf("Sampler")===r.length-7?r.substring(0,r.indexOf("Sampler")):null,a="sampler_comparison"===n?fd.Comparison:fd.Filtering;if(o){const e=this._webgpuProcessingContext.availableTextures[o];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[r];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:a},this._webgpuProcessingContext.availableSamplers[r]=l),this._addSamplerBindingDescription(r,l,t);const h=e.substring(0,s.index),c=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `,u=e.substring(s.index);e=h+c+u,i.lastIndex+=c.length}return e}_processCustomBuffers(e,t){const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const s=i.exec(e);if(null===s)break;const r=s[1],n=s[3];let o=s[4];const a=s[5];let l=this._webgpuProcessingContext.availableBuffers[o];if(!l){const e="uniform"===r?Gd.KnownUBOs[a]:null;let t;e?(o=a,t=e.binding,-1===t.groupIndex&&(t=this._webgpuProcessingContext.availableBuffers[o]?.binding,t||(t=this._webgpuProcessingContext.getNextFreeUBOBinding()))):t=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:t},this._webgpuProcessingContext.availableBuffers[o]=l}this._addBufferBindingDescription(o,this._webgpuProcessingContext.availableBuffers[o],"read_write"===n?pd.Storage:"storage"===r?pd.ReadOnlyStorage:pd.Uniform,t);const h=l.binding.groupIndex,c=l.binding.bindingIndex,u=e.substring(0,s.index),d=`@group(${h}) @binding(${c}) `,p=e.substring(s.index);e=u+d+p,i.lastIndex+=d.length}return e}_processStridedUniformArrays(e){for(const t of this._stridedUniformArrays)e=e.replace(new RegExp(`${t}\\s*\\[(.*?)\\]`,"g"),`${t}[$1].el`);return e}}class Xd{static ComputeNumMipmapLevels(e,t){return G.ILog2(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case ad.R8Unorm:case ad.R8Snorm:case ad.R8Uint:case ad.R8Sint:case ad.RG8Unorm:case ad.RG8Snorm:case ad.RG8Uint:case ad.RG8Sint:case ad.RGBA8Unorm:case ad.RGBA8UnormSRGB:case ad.RGBA8Snorm:case ad.RGBA8Uint:case ad.RGBA8Sint:case ad.BGRA8Unorm:case ad.BGRA8UnormSRGB:case ad.RGB10A2UINT:case ad.RGB10A2Unorm:case ad.RGB9E5UFloat:case ad.RG11B10UFloat:case ad.BC7RGBAUnorm:case ad.BC7RGBAUnormSRGB:case ad.BC6HRGBUFloat:case ad.BC6HRGBFloat:case ad.BC5RGUnorm:case ad.BC5RGSnorm:case ad.BC3RGBAUnorm:case ad.BC3RGBAUnormSRGB:case ad.BC2RGBAUnorm:case ad.BC2RGBAUnormSRGB:case ad.BC4RUnorm:case ad.BC4RSnorm:case ad.BC1RGBAUnorm:case ad.BC1RGBAUnormSRGB:case ad.ETC2RGB8Unorm:case ad.ETC2RGB8UnormSRGB:case ad.ETC2RGB8A1Unorm:case ad.ETC2RGB8A1UnormSRGB:case ad.ETC2RGBA8Unorm:case ad.ETC2RGBA8UnormSRGB:case ad.EACR11Unorm:case ad.EACR11Snorm:case ad.EACRG11Unorm:case ad.EACRG11Snorm:case ad.ASTC4x4Unorm:case ad.ASTC4x4UnormSRGB:case ad.ASTC5x4Unorm:case ad.ASTC5x4UnormSRGB:case ad.ASTC5x5Unorm:case ad.ASTC5x5UnormSRGB:case ad.ASTC6x5Unorm:case ad.ASTC6x5UnormSRGB:case ad.ASTC6x6Unorm:case ad.ASTC6x6UnormSRGB:case ad.ASTC8x5Unorm:case ad.ASTC8x5UnormSRGB:case ad.ASTC8x6Unorm:case ad.ASTC8x6UnormSRGB:case ad.ASTC8x8Unorm:case ad.ASTC8x8UnormSRGB:case ad.ASTC10x5Unorm:case ad.ASTC10x5UnormSRGB:case ad.ASTC10x6Unorm:case ad.ASTC10x6UnormSRGB:case ad.ASTC10x8Unorm:case ad.ASTC10x8UnormSRGB:case ad.ASTC10x10Unorm:case ad.ASTC10x10UnormSRGB:case ad.ASTC12x10Unorm:case ad.ASTC12x10UnormSRGB:case ad.ASTC12x12Unorm:case ad.ASTC12x12UnormSRGB:case ad.Stencil8:return 0;case ad.R16Uint:case ad.R16Sint:case ad.RG16Uint:case ad.RG16Sint:case ad.RGBA16Uint:case ad.RGBA16Sint:case ad.Depth16Unorm:return 5;case ad.R16Float:case ad.RG16Float:case ad.RGBA16Float:return 2;case ad.R32Uint:case ad.R32Sint:case ad.RG32Uint:case ad.RG32Sint:case ad.RGBA32Uint:case ad.RGBA32Sint:return 7;case ad.R32Float:case ad.RG32Float:case ad.RGBA32Float:case ad.Depth32Float:case ad.Depth32FloatStencil8:case ad.Depth24Plus:case ad.Depth24PlusStencil8:return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case ad.R8Unorm:case ad.R8Snorm:case ad.R8Uint:case ad.R8Sint:return{width:1,height:1,length:1};case ad.R16Uint:case ad.R16Sint:case ad.R16Float:case ad.RG8Unorm:case ad.RG8Snorm:case ad.RG8Uint:case ad.RG8Sint:return{width:1,height:1,length:2};case ad.R32Uint:case ad.R32Sint:case ad.R32Float:case ad.RG16Uint:case ad.RG16Sint:case ad.RG16Float:case ad.RGBA8Unorm:case ad.RGBA8UnormSRGB:case ad.RGBA8Snorm:case ad.RGBA8Uint:case ad.RGBA8Sint:case ad.BGRA8Unorm:case ad.BGRA8UnormSRGB:case ad.RGB9E5UFloat:case ad.RGB10A2UINT:case ad.RGB10A2Unorm:case ad.RG11B10UFloat:return{width:1,height:1,length:4};case ad.RG32Uint:case ad.RG32Sint:case ad.RG32Float:case ad.RGBA16Uint:case ad.RGBA16Sint:case ad.RGBA16Float:return{width:1,height:1,length:8};case ad.RGBA32Uint:case ad.RGBA32Sint:case ad.RGBA32Float:return{width:1,height:1,length:16};case ad.Stencil8:throw"No fixed size for Stencil8 format!";case ad.Depth16Unorm:return{width:1,height:1,length:2};case ad.Depth24Plus:throw"No fixed size for Depth24Plus format!";case ad.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case ad.Depth32Float:return{width:1,height:1,length:4};case ad.Depth32FloatStencil8:return{width:1,height:1,length:5};case ad.BC7RGBAUnorm:case ad.BC7RGBAUnormSRGB:case ad.BC6HRGBUFloat:case ad.BC6HRGBFloat:case ad.BC5RGUnorm:case ad.BC5RGSnorm:case ad.BC3RGBAUnorm:case ad.BC3RGBAUnormSRGB:case ad.BC2RGBAUnorm:case ad.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case ad.BC4RUnorm:case ad.BC4RSnorm:case ad.BC1RGBAUnorm:case ad.BC1RGBAUnormSRGB:case ad.ETC2RGB8Unorm:case ad.ETC2RGB8UnormSRGB:case ad.ETC2RGB8A1Unorm:case ad.ETC2RGB8A1UnormSRGB:case ad.EACR11Unorm:case ad.EACR11Snorm:return{width:4,height:4,length:8};case ad.ETC2RGBA8Unorm:case ad.ETC2RGBA8UnormSRGB:case ad.EACRG11Unorm:case ad.EACRG11Snorm:case ad.ASTC4x4Unorm:case ad.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case ad.ASTC5x4Unorm:case ad.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case ad.ASTC5x5Unorm:case ad.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case ad.ASTC6x5Unorm:case ad.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case ad.ASTC6x6Unorm:case ad.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case ad.ASTC8x5Unorm:case ad.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case ad.ASTC8x6Unorm:case ad.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case ad.ASTC8x8Unorm:case ad.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case ad.ASTC10x5Unorm:case ad.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case ad.ASTC10x6Unorm:case ad.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case ad.ASTC10x8Unorm:case ad.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case ad.ASTC10x10Unorm:case ad.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case ad.ASTC12x10Unorm:case ad.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case ad.ASTC12x12Unorm:case ad.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}static IsCompressedFormat(e){switch(e){case ad.BC7RGBAUnormSRGB:case ad.BC7RGBAUnorm:case ad.BC6HRGBFloat:case ad.BC6HRGBUFloat:case ad.BC5RGSnorm:case ad.BC5RGUnorm:case ad.BC4RSnorm:case ad.BC4RUnorm:case ad.BC3RGBAUnormSRGB:case ad.BC3RGBAUnorm:case ad.BC2RGBAUnormSRGB:case ad.BC2RGBAUnorm:case ad.BC1RGBAUnormSRGB:case ad.BC1RGBAUnorm:case ad.ETC2RGB8Unorm:case ad.ETC2RGB8UnormSRGB:case ad.ETC2RGB8A1Unorm:case ad.ETC2RGB8A1UnormSRGB:case ad.ETC2RGBA8Unorm:case ad.ETC2RGBA8UnormSRGB:case ad.EACR11Unorm:case ad.EACR11Snorm:case ad.EACRG11Unorm:case ad.EACRG11Snorm:case ad.ASTC4x4Unorm:case ad.ASTC4x4UnormSRGB:case ad.ASTC5x4Unorm:case ad.ASTC5x4UnormSRGB:case ad.ASTC5x5Unorm:case ad.ASTC5x5UnormSRGB:case ad.ASTC6x5Unorm:case ad.ASTC6x5UnormSRGB:case ad.ASTC6x6Unorm:case ad.ASTC6x6UnormSRGB:case ad.ASTC8x5Unorm:case ad.ASTC8x5UnormSRGB:case ad.ASTC8x6Unorm:case ad.ASTC8x6UnormSRGB:case ad.ASTC8x8Unorm:case ad.ASTC8x8UnormSRGB:case ad.ASTC10x5Unorm:case ad.ASTC10x5UnormSRGB:case ad.ASTC10x6Unorm:case ad.ASTC10x6UnormSRGB:case ad.ASTC10x8Unorm:case ad.ASTC10x8UnormSRGB:case ad.ASTC10x10Unorm:case ad.ASTC10x10UnormSRGB:case ad.ASTC12x10Unorm:case ad.ASTC12x10UnormSRGB:case ad.ASTC12x12Unorm:case ad.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return ad.Depth16Unorm;case 16:return ad.Depth24Plus;case 13:return ad.Depth24PlusStencil8;case 14:return ad.Depth32Float;case 18:return ad.Depth32FloatStencil8;case 19:return ad.Stencil8;case 36492:return i?ad.BC7RGBAUnormSRGB:ad.BC7RGBAUnorm;case 36495:return ad.BC6HRGBUFloat;case 36494:return ad.BC6HRGBFloat;case 33779:return i?ad.BC3RGBAUnormSRGB:ad.BC3RGBAUnorm;case 33778:return i?ad.BC2RGBAUnormSRGB:ad.BC2RGBAUnorm;case 33777:case 33776:return i?ad.BC1RGBAUnormSRGB:ad.BC1RGBAUnorm;case 37808:return i?ad.ASTC4x4UnormSRGB:ad.ASTC4x4Unorm;case 36196:case 37492:return i?ad.ETC2RGB8UnormSRGB:ad.ETC2RGB8Unorm;case 37496:return i?ad.ETC2RGBA8UnormSRGB:ad.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return ad.R8Snorm;case 7:return ad.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return ad.R8Sint;case 9:return ad.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return ad.RGBA8Sint;default:return ad.RGBA8Snorm}case 0:switch(t){case 6:return ad.R8Unorm;case 7:return ad.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?ad.RGBA8UnormSRGB:ad.RGBA8Unorm;case 12:return i?ad.BGRA8UnormSRGB:ad.BGRA8Unorm;case 8:return ad.R8Uint;case 9:return ad.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return ad.RGBA8Uint;case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return ad.RGBA8Unorm}case 4:switch(t){case 8:return ad.R16Sint;case 9:return ad.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ad.RGBA16Sint}case 5:switch(t){case 8:return ad.R16Uint;case 9:return ad.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ad.RGBA16Uint}case 6:switch(t){case 8:return ad.R32Sint;case 9:return ad.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ad.RGBA32Sint}case 7:switch(t){case 8:return ad.R32Uint;case 9:return ad.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ad.RGBA32Uint}case 1:switch(t){case 6:return ad.R32Float;case 7:return ad.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return ad.RGBA32Float}case 2:switch(t){case 6:return ad.R16Float;case 7:return ad.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return ad.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return ad.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"}case 14:switch(t){case 5:default:return ad.RGB9E5UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:default:return ad.RGB10A2Unorm;case 11:return ad.RGB10A2UINT}}return i?ad.RGBA8UnormSRGB:ad.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case ad.R8Unorm:case ad.R8Snorm:case ad.R8Uint:case ad.R8Sint:case ad.BC4RUnorm:case ad.BC4RSnorm:case ad.R16Uint:case ad.R16Sint:case ad.Depth16Unorm:case ad.R16Float:case ad.R32Uint:case ad.R32Sint:case ad.R32Float:case ad.Depth32Float:case ad.Stencil8:case ad.Depth24Plus:case ad.EACR11Unorm:case ad.EACR11Snorm:return 1;case ad.RG8Unorm:case ad.RG8Snorm:case ad.RG8Uint:case ad.RG8Sint:case ad.Depth32FloatStencil8:case ad.BC5RGUnorm:case ad.BC5RGSnorm:case ad.RG16Uint:case ad.RG16Sint:case ad.RG16Float:case ad.RG32Uint:case ad.RG32Sint:case ad.RG32Float:case ad.Depth24PlusStencil8:case ad.EACRG11Unorm:case ad.EACRG11Snorm:return 2;case ad.RGB9E5UFloat:case ad.RG11B10UFloat:case ad.BC6HRGBUFloat:case ad.BC6HRGBFloat:case ad.ETC2RGB8Unorm:case ad.ETC2RGB8UnormSRGB:return 3;case ad.RGBA8Unorm:case ad.RGBA8UnormSRGB:case ad.RGBA8Snorm:case ad.RGBA8Uint:case ad.RGBA8Sint:case ad.BGRA8Unorm:case ad.BGRA8UnormSRGB:case ad.RGB10A2UINT:case ad.RGB10A2Unorm:case ad.BC7RGBAUnorm:case ad.BC7RGBAUnormSRGB:case ad.BC3RGBAUnorm:case ad.BC3RGBAUnormSRGB:case ad.BC2RGBAUnorm:case ad.BC2RGBAUnormSRGB:case ad.BC1RGBAUnorm:case ad.BC1RGBAUnormSRGB:case ad.RGBA16Uint:case ad.RGBA16Sint:case ad.RGBA16Float:case ad.RGBA32Uint:case ad.RGBA32Sint:case ad.RGBA32Float:case ad.ETC2RGB8A1Unorm:case ad.ETC2RGB8A1UnormSRGB:case ad.ETC2RGBA8Unorm:case ad.ETC2RGBA8UnormSRGB:case ad.ASTC4x4Unorm:case ad.ASTC4x4UnormSRGB:case ad.ASTC5x4Unorm:case ad.ASTC5x4UnormSRGB:case ad.ASTC5x5Unorm:case ad.ASTC5x5UnormSRGB:case ad.ASTC6x5Unorm:case ad.ASTC6x5UnormSRGB:case ad.ASTC6x6Unorm:case ad.ASTC6x6UnormSRGB:case ad.ASTC8x5Unorm:case ad.ASTC8x5UnormSRGB:case ad.ASTC8x6Unorm:case ad.ASTC8x6UnormSRGB:case ad.ASTC8x8Unorm:case ad.ASTC8x8UnormSRGB:case ad.ASTC10x5Unorm:case ad.ASTC10x5UnormSRGB:case ad.ASTC10x6Unorm:case ad.ASTC10x6UnormSRGB:case ad.ASTC10x8Unorm:case ad.ASTC10x8UnormSRGB:case ad.ASTC10x10Unorm:case ad.ASTC10x10UnormSRGB:case ad.ASTC12x10Unorm:case ad.ASTC12x10UnormSRGB:case ad.ASTC12x12Unorm:case ad.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case ad.Stencil8:case ad.Depth32FloatStencil8:case ad.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case ad.Depth32FloatStencil8:case ad.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case ad.Depth16Unorm:return ad.Depth16Unorm;case ad.Depth24Plus:case ad.Depth24PlusStencil8:return ad.Depth24Plus;case ad.Depth32Float:case ad.Depth32FloatStencil8:return ad.Depth32Float}return e}static GetSample(e){return e>1?4:1}}class Yd{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){return this._webgpuMSAATexture?.[e]??null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),-1===t&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(const e of this._webgpuMSAATexture)e?.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this._originalFormatIsRGB=!1,this.format=ad.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,s,r,n,o,a){let l=nd.E2d,h=1;s?(l=i?nd.CubeArray:nd.Cube,h=6*(a||1)):r?(l=nd.E3d,h=1):i&&(l=nd.E2dArray,h=a);const c=Xd.GetDepthFormatOnly(this.format),u=Xd.HasDepthAndStencilAspects(this.format)?od.DepthOnly:od.All;this.createView({label:`TextureView${r?"3D":s?"Cube":"2D"}${i?"_Array"+h:""}_${n}x${o}_${t?"wmips":"womips"}_${this.format}_${l}`,format:c,dimension:l,mipLevelCount:t?G.ILog2(Math.max(n,o))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:h,aspect:u})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){this._webgpuTexture?.destroy(),this.releaseMSAATexture(),this._copyInvertYTempTexture?.destroy(),this.reset()}}const jd="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) out flat ivec2 vTextureSize;\n #endif\n\n void main() {\n #ifdef INVERTY\n vTextureSize = textureSize(img, 0);\n #endif\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",$d=jd;var Kd,qd;!function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"}(Kd||(Kd={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(qd||(qd={}));const Qd=[{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(location = 0) out vec2 vTex;\n\n void main() {\n vTex = tex[gl_VertexIndex];\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform sampler imgSampler;\n layout(set = 0, binding = 1) uniform texture2D img;\n\n layout(location = 0) in vec2 vTex;\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = texture(sampler2D(img, imgSampler), vTex);\n }\n "},{vertex:jd,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "},{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n\n void main() {\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform Uniforms {\n uniform vec4 color;\n };\n\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = color;\n }\n "},{vertex:$d,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n layout(set = 0, binding = 1) uniform Params {\n float ofstX;\n float ofstY;\n float width;\n float height;\n };\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) {\n discard;\n }\n if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) {\n discard;\n }\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "}],Zd={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};class Jd{constructor(e,t,i,s,r,n){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._glslang=i,this._tintWASM=s,this._bufferManager=r,-1!==n.indexOf(Ju.RG11B10UFloatRenderable)){const e=Object.keys(Zd);Zd[ad.RG11B10UFloat]=Zd[e[e.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:hd.Linear}),this._videoSampler=t.createSampler({minFilter:hd.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,td.Uniform|td.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(ad.RGBA8Unorm),this._getVideoPipeline(ad.RGBA8Unorm)}_getPipeline(e,t=Kd.MipMap,i){const s=t===Kd.MipMap?1:t===Kd.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===Kd.Clear?8:t===Kd.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let r=this._pipelines[e][s];if(!r){let n="#version 450\n";t!==Kd.InvertYPremultiplyAlpha&&t!==Kd.InvertYPremultiplyAlphaWithOfst||(i.invertY&&(n+="#define INVERTY\n"),i.premultiplyAlpha&&(n+="#define PREMULTIPLYALPHA\n"));let o=this._compiledShaders[s];if(!o){let e=this._glslang.compileGLSL(n+Qd[t].vertex,"vertex"),i=this._glslang.compileGLSL(n+Qd[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));const r=this._device.createShaderModule({code:e}),a=this._device.createShaderModule({code:i});o=this._compiledShaders[s]=[r,a]}const a=this._device.createRenderPipeline({layout:xd.Auto,vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Td.TriangleStrip,stripIndexFormat:Rd.Uint16}});r=this._pipelines[e][s]=[a,a.getBindGroupLayout(0)]}return r}_getVideoPipeline(e,t=qd.DontInvertY){const i=t===qd.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let s=this._videoPipelines[e][i];if(!s){let t=this._videoCompiledShaders[i];if(!t){const e=this._device.createShaderModule({code:"\n struct VertexOutput {\n @builtin(position) Position : vec4,\n @location(0) fragUV : vec2\n }\n\n @vertex\n fn main(\n @builtin(vertex_index) VertexIndex : u32\n ) -> VertexOutput {\n var pos = array, 4>(\n vec2(-1.0, 1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, -1.0)\n );\n var tex = array, 4>(\n vec2(0.0, 0.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(1.0, 1.0)\n );\n\n var output: VertexOutput;\n\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = tex[VertexIndex];\n\n return output;\n }\n "}),s=this._device.createShaderModule({code:0===i?"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\n }\n ":"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y));\n }\n "});t=this._videoCompiledShaders[i]=[e,s]}const r=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:xd.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Td.TriangleStrip,stripIndexFormat:Rd.Uint16}});s=this._videoPipelines[e][i]=[r,r.getBindGroupLayout(0)]}return s}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,s=!1,r){const n=void 0===r,[o,a]=this._getVideoPipeline(i,s?qd.InvertY:qd.DontInvertY);n&&(r=this._device.createCommandEncoder({})),r.pushDebugGroup?.(`copy video to texture - invertY=${s}`);const l=t._hardwareTexture,h={label:`BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${i}_${s?"InvertY":"DontInvertY"}${t.label?"_"+t.label:""}`,colorAttachments:[{view:l.underlyingResource.createView({format:i,dimension:nd.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:od.All}),loadOp:Od.Load,storeOp:Nd.Store}]},c=r.beginRenderPass(h),u={layout:a,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},d=this._device.createBindGroup(u);c.setPipeline(o),c.setBindGroup(0,d),c.draw(4,1,0,0),c.end(),r.popDebugGroup?.(),n&&(this._device.queue.submit([r.finish()]),r=null)}invertYPreMultiplyAlpha(e,t,i,s,r=!1,n=!1,o=0,a=0,l=1,h=0,c=0,u=0,d=0,p,f){const _=0!==u,m=void 0===p,[g,v]=this._getPipeline(s,_?Kd.InvertYPremultiplyAlphaWithOfst:Kd.InvertYPremultiplyAlpha,{invertY:r,premultiplyAlpha:n});let x;if(o=Math.max(o,0),m&&(p=this._device.createCommandEncoder({})),p.pushDebugGroup?.(`internal process texture - invertY=${r} premultiplyAlpha=${n}`),Xd.IsHardwareTexture(e)?(x=e.underlyingResource,r&&!n&&1===l&&0===o||(e=void 0)):(x=e,e=void 0),!x)return;_&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,c,u,d]),0,16);const T=e,S=T?._copyInvertYTempTexture??this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,s,1,p,rd.CopySrc|rd.RenderAttachment|rd.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),E=T?._copyInvertYRenderPassDescr??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${s}_${r?"InvertY":"DontInvertY"}_${n?"PremultiplyAlpha":"DontPremultiplyAlpha"}`,colorAttachments:[{view:S.createView({format:s,dimension:nd.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:Od.Load,storeOp:Nd.Store}]},b=p.beginRenderPass(E);let C=_?T?._copyInvertYBindGroupWithOfst:T?._copyInvertYBindGroup;if(!C){const e={layout:v,entries:[{binding:0,resource:x.createView({format:s,dimension:nd.E2d,baseMipLevel:a,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:o})}]};_&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),C=this._device.createBindGroup(e)}b.setPipeline(g),b.setBindGroup(0,C),b.draw(4,1,0,0),b.end(),p.copyTextureToTexture({texture:S},{texture:x,mipLevel:a,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),T?(T._copyInvertYTempTexture=S,T._copyInvertYRenderPassDescr=E,_?T._copyInvertYBindGroupWithOfst=C:T._copyInvertYBindGroup=C):this._deferredReleaseTextures.push([S,null]),p.popDebugGroup?.(),m&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,s){const r=void 0===s,[n,o]=this._getPipeline(t,Kd.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});r&&(s=this._device.createCommandEncoder({})),s.pushDebugGroup?.("internal copy texture with invertY");const a=s.beginRenderPass(i),l=this._device.createBindGroup({layout:o,entries:[{binding:0,resource:e}]});a.setPipeline(n),a.setBindGroup(0,l),a.draw(4,1,0,0),a.end(),s.popDebugGroup?.(),r&&(this._device.queue.submit([s.finish()]),s=null)}createTexture(e,t=!1,i=!1,s=!1,r=!1,n=!1,o=ad.RGBA8Unorm,a=1,l,h=-1,c=0,u){a=Xd.GetSample(a);const d=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:d},f=Zd[o]?rd.RenderAttachment:0,_=Xd.IsCompressedFormat(o),m=t?Xd.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:rd.CopySrc|rd.CopyDst|rd.TextureBinding;c|=t&&!_?rd.CopySrc|f:0,_||n||(c|=f|rd.CopyDst);const v=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_Texture${n?"3D":"2D"}_${u?u+"_":""}${p.width}x${p.height}x${p.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${a}`,size:p,dimension:n?sd.E3d:sd.E2d,format:o,usage:g|c,sampleCount:a,mipLevelCount:m});return Xd.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,o,0,0,s,r,0,0),t&&i&&this.generateMipmaps(v,o,m,0,n,l)),v}createCubeTexture(e,t=!1,i=!1,s=!1,r=!1,n=ad.RGBA8Unorm,o=1,a,l=-1,h=0,c){o=Xd.GetSample(o);const u=Xd.IsImageBitmapArray(e)?e[0].width:e.width,d=Xd.IsImageBitmapArray(e)?e[0].height:e.height,p=Zd[n]?rd.RenderAttachment:0,f=Xd.IsCompressedFormat(n),_=t?Xd.ComputeNumMipmapLevels(u,d):1,m=l>=0?l:rd.CopySrc|rd.CopyDst|rd.TextureBinding;h|=t&&!f?rd.CopySrc|p:0,f||(h|=p|rd.CopyDst);const g=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${c?c+"_":""}${u}x${d}x6_${t?"wmips":"womips"}_${n}_samples${o}`,size:{width:u,height:d,depthOrArrayLayers:6},dimension:sd.E2d,format:n,usage:m|h,sampleCount:o,mipLevelCount:_});return Xd.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,u,d,n,s,r,0,0),t&&i&&this.generateCubeMipmaps(g,n,_,a)),g}generateCubeMipmaps(e,t,i,s){const r=void 0===s;r&&(s=this._device.createCommandEncoder({})),s.pushDebugGroup?.(`create cube mipmaps - ${i} levels`);for(let r=0;r<6;++r)this.generateMipmaps(e,t,i,r,!1,s);s.popDebugGroup?.(),r&&(this._device.queue.submit([s.finish()]),s=null)}generateMipmaps(e,t,i,s=0,r=!1,n){const o=void 0===n,[a,l]=this._getPipeline(t);let h;if(s=Math.max(s,0),o&&(n=this._device.createCommandEncoder({})),n.pushDebugGroup?.(`create mipmaps for face #${s} - ${i} levels`),Xd.IsHardwareTexture(e)?(h=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(h=e,e=void 0),!h)return;const c=e;for(let e=1;eh;)this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,h),c+=h;this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,r-c)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const s=new Uint16Array(t);for(;e--;)i[e]=ru(s[e]);return i}readDataFromBuffer(e,t,i,s,r,n,o=0,a=0,l=null,h=!0,c=!1){const u=1===o?2:2===o?1:0,d=this._engine.uniqueId;return new Promise(((i,p)=>{e.mapAsync(id.Read,a,t).then((()=>{const d=e.getMappedRange(a,t);let p=l;if(c)p=null===p?Ar(o,t,!0,d):Ar(o,p.buffer,void 0,d);else if(null===p)switch(u){case 0:p=new Uint8Array(t),p.set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:p=new Float32Array(t/4),p.set(new Float32Array(d))}else switch(u){case 0:p=new Uint8Array(p.buffer),p.set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:p=new Float32Array(p.buffer),p.set(new Float32Array(d))}if(r!==n){1!==u||c||(r*=2,n*=2);const e=new Uint8Array(p.buffer);let t=r,i=0;for(let o=1;o{this._engine.isDisposed||this._engine.uniqueId!==d?i(new Uint8Array):p(e)}))}))}releaseBuffer(e){return tp._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e1?4:1;return ip[e.samplingMode]+sp[(e._comparisonFunction||514)-512+1]+rp[e.samplingMode]+((e._cachedWrapU??1)<<8)+((e._cachedWrapV??1)<<10)+((e._cachedWrapR??1)<<12)+((e.useMipMaps?1:0)<<14)+(t<<15)}static _GetSamplerFilterDescriptor(e,t){let i,s,r,n,o;const a=e.useMipMaps;switch(e.samplingMode){case 11:i=hd.Linear,s=hd.Linear,r=hd.Nearest,a||(n=o=0);break;case 3:case 3:i=hd.Linear,s=hd.Linear,a?r=hd.Linear:(r=hd.Nearest,n=o=0);break;case 8:i=hd.Nearest,s=hd.Nearest,a?r=hd.Linear:(r=hd.Nearest,n=o=0);break;case 4:i=hd.Nearest,s=hd.Nearest,r=hd.Nearest,a||(n=o=0);break;case 5:i=hd.Nearest,s=hd.Linear,r=hd.Nearest,a||(n=o=0);break;case 6:i=hd.Nearest,s=hd.Linear,a?r=hd.Linear:(r=hd.Nearest,n=o=0);break;case 7:i=hd.Nearest,s=hd.Linear,r=hd.Nearest,n=o=0;break;case 1:case 1:default:i=hd.Nearest,s=hd.Nearest,r=hd.Nearest,n=o=0;break;case 9:i=hd.Linear,s=hd.Nearest,r=hd.Nearest,a||(n=o=0);break;case 10:i=hd.Linear,s=hd.Nearest,a?r=hd.Linear:(r=hd.Nearest,n=o=0);break;case 2:case 2:i=hd.Linear,s=hd.Linear,r=hd.Nearest,n=o=0;break;case 12:i=hd.Linear,s=hd.Nearest,r=hd.Nearest,n=o=0}return t>1&&(0!==n||0!==o)&&r!==hd.Nearest?{magFilter:hd.Linear,minFilter:hd.Linear,mipmapFilter:hd.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:s,mipmapFilter:r,lodMinClamp:n,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return ld.Repeat;case 0:return ld.ClampToEdge;case 2:return ld.MirrorRepeat}return ld.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,t){const i=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,s=this._GetSamplerFilterDescriptor(e,i);return{label:t,...s,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?np.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:s.anisotropyEnabled?i:1}}static GetCompareFunction(e){switch(e){case 519:return ud.Always;case 514:return ud.Equal;case 516:return ud.Greater;case 518:return ud.GreaterEqual;case 513:default:return ud.Less;case 515:return ud.LessEqual;case 512:return ud.Never;case 517:return ud.NotEqual}}getSampler(e,t=!1,i=0,s){if(this.disabled)return this._device.createSampler(np._GetSamplerDescriptor(e,s));t?i=0:0===i&&(i=np.GetSamplerHashCode(e));let r=t?void 0:this._samplers[i];return r||(r=this._device.createSampler(np._GetSamplerDescriptor(e,s)),t||(this._samplers[i]=r)),r}}var op;!function(e){e[e.StencilReadMask=0]="StencilReadMask",e[e.StencilWriteMask=1]="StencilWriteMask",e[e.DepthBias=2]="DepthBias",e[e.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",e[e.DepthStencilState=4]="DepthStencilState",e[e.MRTAttachments1=5]="MRTAttachments1",e[e.MRTAttachments2=6]="MRTAttachments2",e[e.RasterizationState=7]="RasterizationState",e[e.ColorStates=8]="ColorStates",e[e.ShaderStage=9]="ShaderStage",e[e.TextureStage=10]="TextureStage",e[e.VertexState=11]="VertexState",e[e.NumStates=12]="NumStates"}(op||(op={}));const ap={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},lp={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class hp{constructor(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[ad.BGRA8Unorm],this.setColorFormat(ad.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(ad.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,s=0){if(i=Xd.GetSample(i),this.disabled){const r=hp._GetTopology(e);return this._setVertexState(t),this._setTextureState(s),this._parameter.pipeline=this._createRenderPipeline(t,r,i),hp.NumCacheMiss++,hp._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(s),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,hp.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return hp.NumCacheHitWithHash++,this._parameter.pipeline;const r=hp._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,r,i),this._setRenderPipeline(this._parameter),hp.NumCacheMiss++,hp._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){hp.NumPipelineCreationLastFrame=hp._NumPipelineCreationCurrentFrame,hp._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,s,r,n,o,a){this._depthWriteEnabled=o,this._depthTestEnabled=n,this._depthCompare=(a??519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(s),this.setDepthBias(r)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[op.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[op.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=Zd[e??""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const i=[0,0];let s=0,r=0,n=0;for(let o=0;o=32&&(r=0,s++)}this._mrtFormats.length=n,this._mrtAttachments1===i[0]&&this._mrtAttachments2===i[1]||(this._mrtAttachments1=i[0],this._mrtAttachments2=i[1],this._states[op.MRTAttachments1]=i[0],this._states[op.MRTAttachments2]=i[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=void 0===e?0:Zd[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(e??519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(e??519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=null===e?1:lp[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:lp[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:lp[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[op.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[op.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,s,r,n,o){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=null===i?1:lp[i],this._stencilFrontPassOp=null===s?2:lp[s],this._stencilFrontFailOp=null===r?1:lp[r],this.setStencilReadMask(n),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return Td.TriangleList;case 2:case 3:return Td.PointList;case 1:case 4:return Td.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return Td.LineStrip;case 7:return Td.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return yd.Add;case 32778:return yd.Subtract;case 32779:return yd.ReverseSubtract;case 32775:return yd.Min;case 32776:return yd.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return Cd.Zero;case 1:default:return Cd.One;case 768:return Cd.Src;case 769:return Cd.OneMinusSrc;case 770:return Cd.SrcAlpha;case 771:return Cd.OneMinusSrcAlpha;case 772:return Cd.DstAlpha;case 773:return Cd.OneMinusDstAlpha;case 774:return Cd.Dst;case 775:return Cd.OneMinusDst;case 776:return Cd.SrcAlphaSaturated;case 32769:case 32771:return Cd.Constant;case 32770:case 32772:return Cd.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:return ud.Never;case 1:return ud.Less;case 2:return ud.Equal;case 3:return ud.LessEqual;case 4:return ud.Greater;case 5:return ud.NotEqual;case 6:return ud.GreaterEqual;case 7:return ud.Always}return ud.Never}static _GetStencilOpFunction(e){switch(e){case 0:return Ad.Zero;case 1:return Ad.Keep;case 2:return Ad.Replace;case 3:return Ad.IncrementClamp;case 4:return Ad.DecrementClamp;case 5:return Ad.Invert;case 6:return Ad.IncrementWrap;case 7:return Ad.DecrementWrap}return Ad.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,s=e.getSize();switch(t){case Ki.BYTE:switch(s){case 1:case 2:return i?Id.Snorm8x2:Id.Sint8x2;case 3:case 4:return i?Id.Snorm8x4:Id.Sint8x4}break;case Ki.UNSIGNED_BYTE:switch(s){case 1:case 2:return i?Id.Unorm8x2:Id.Uint8x2;case 3:case 4:return i?Id.Unorm8x4:Id.Uint8x4}break;case Ki.SHORT:switch(s){case 1:case 2:return i?Id.Snorm16x2:Id.Sint16x2;case 3:case 4:return i?Id.Snorm16x4:Id.Sint16x4}break;case Ki.UNSIGNED_SHORT:switch(s){case 1:case 2:return i?Id.Unorm16x2:Id.Uint16x2;case 3:case 4:return i?Id.Unorm16x4:Id.Uint16x4}break;case Ki.INT:switch(s){case 1:return Id.Sint32;case 2:return Id.Sint32x2;case 3:return Id.Sint32x3;case 4:return Id.Sint32x4}break;case Ki.UNSIGNED_INT:switch(s){case 1:return Id.Uint32;case 2:return Id.Uint32x2;case 3:return Id.Uint32x3;case 4:return Id.Uint32x4}break;case Ki.FLOAT:switch(s){case 1:return Id.Float32;case 2:return Id.Float32x2;case 3:return Id.Float32x3;case 4:return Id.Float32x4}}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${s}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:hp._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:hp._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:hp._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:hp._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:hp._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:hp._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[op.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace-1+((this._cullEnabled?this._cullFace:0)<<1)+((this._clampDepth?1:0)<<3)+((this._alphaToCoverageEnabled?1:0)<<4)+(e<<5)+(t<<8);this._rasterizationState!==i&&(this._rasterizationState=i,this._states[op.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=(0|(null===this._alphaBlendFuncParams[0]?2:ap[this._alphaBlendFuncParams[0]]))+((null===this._alphaBlendFuncParams[1]?2:ap[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:ap[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:ap[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[op.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.ColorStates))}_setDepthStencilState(){const e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[op.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.DepthStencilState))}_setVertexState(e){const t=this._statesLength;let i=op.VertexState;const s=e._pipelineContext,r=s.shaderProcessingContext.attributeNamesFromEffect,n=s.shaderProcessingContext.attributeLocationsFromEffect;let o,a=0;for(let e=0;e0)for(let e=0;e=this._video.HAVE_CURRENT_DATA}dispose(){}}class _p{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=_p._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],s=-1;i?s=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?np.GetSamplerHashCode(t):0;const r=s!==i.hashCode;r&&this.updateId++,this.isDirty||(this.isDirty=r)}setTexture(e,t){let i=this.textures[e],s=-1;i?s=i.texture?.uniqueId??-1:this.textures[e]=i={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},i.isExternalTexture&&this._numExternalTextures--,i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(i.isFloatOrDepthTexture=1===t.type||t.format>=13&&t.format<=18,i.isExternalTexture=fp.IsExternalTexture(t),i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,i.isExternalTexture&&this._numExternalTextures++):(i.isFloatOrDepthTexture=!1,i.isExternalTexture=!1),i.texture=t;const r=s!==(t?.uniqueId??-1);r&&this.updateId++,this.isDirty||(this.isDirty=r)}}_p._Counter=0;class mp{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,td.CopyDst|td.Indirect|td.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=mp._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){this._isDirty||(this._isDirty=t?.uniqueId!==this.buffers[e]?.uniqueId),this.buffers[e]=t}setIndirectData(e,t,i){t!==this._currentInstanceCount&&this.indirectDrawBuffer&&this._indirectDrawData&&(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}}mp._Counter=0;class gp{constructor(){this.values={}}}class vp{static get Statistics(){return{totalCreated:vp.NumBindGroupsCreatedTotal,lastFrameCreated:vp.NumBindGroupsCreatedLastFrame,lookupLastFrame:vp.NumBindGroupsLookupLastFrame,noLookupLastFrame:vp.NumBindGroupsNoLookupLastFrame}}static ResetCache(){vp._Cache=new gp,vp.NumBindGroupsCreatedTotal=0,vp.NumBindGroupsCreatedLastFrame=0,vp.NumBindGroupsLookupLastFrame=0,vp.NumBindGroupsNoLookupLastFrame=0,vp._NumBindGroupsCreatedCurrentFrame=0,vp._NumBindGroupsLookupCurrentFrame=0,vp._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){vp.NumBindGroupsCreatedLastFrame=vp._NumBindGroupsCreatedCurrentFrame,vp.NumBindGroupsLookupLastFrame=vp._NumBindGroupsLookupCurrentFrame,vp.NumBindGroupsNoLookupLastFrame=vp._NumBindGroupsNoLookupCurrentFrame,vp._NumBindGroupsCreatedCurrentFrame=0,vp._NumBindGroupsLookupCurrentFrame=0,vp._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){let s,r=vp._Cache;const n=this.disabled||i.forceBindGroupCreation;if(!n){if(!t.isDirty(i.updateId)&&!i.isDirty)return vp._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const i of e.shaderProcessingContext.bufferNames){const e=t.buffers[i]?.uniqueId??0;let s=r.values[e];s||(s=new gp,r.values[e]=s),r=s}for(const t of e.shaderProcessingContext.samplerNames){const e=i.samplers[t]?.hashCode??0;let s=r.values[e];s||(s=new gp,r.values[e]=s),r=s}for(const t of e.shaderProcessingContext.textureNames){const e=i.textures[t]?.texture?.uniqueId??0;let s=r.values[e];s||(s=new gp,r.values[e]=s),r=s}s=r.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,s)return t.bindGroups=s,vp._NumBindGroupsLookupCurrentFrame++,s;s=[],t.bindGroups=s,n||(r.bindGroups=s),vp.NumBindGroupsCreatedTotal++,vp._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[i.textureState];for(let r=0;r"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=this._cacheSampler.getSampler(t,!1,e.hashCode,t.label)}else J.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.texture||n.storageTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){J.Error(`Trying to bind a null texture! entry=${JSON.stringify(n)}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||n.texture&&!t.view||n.storageTexture&&!t.viewForWriting)){J.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=n.storageTexture?t.viewForWriting:t.view}else J.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.externalTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){J.Error(`Trying to bind a null external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){J.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=this._device.importExternalTexture({source:t})}else J.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.buffer){const e=t.buffers[l];if(e){const t=e.underlyingResource;a[s].resource.buffer=t,a[s].resource.size=e.capacity}else J.Error(`Can't find buffer "${l}". entry=${JSON.stringify(n)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const l=o[r];s[r]=this._device.createBindGroup({layout:l,entries:a})}return s}}vp.NumBindGroupsCreatedTotal=0,vp.NumBindGroupsCreatedLastFrame=0,vp.NumBindGroupsLookupLastFrame=0,vp.NumBindGroupsNoLookupLastFrame=0,vp._Cache=new gp,vp._NumBindGroupsCreatedCurrentFrame=0,vp._NumBindGroupsLookupCurrentFrame=0,vp._NumBindGroupsNoLookupCurrentFrame=0;Ft.ShadersStoreWGSL.clearQuadVertexShader="uniform depthValue: f32;const pos=array(\nvec2f(-1.0,1.0),\nvec2f(1.0,1.0),\nvec2f(-1.0,-1.0),\nvec2f(1.0,-1.0)\n);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.position=vec4f(pos[input.vertexIndex],uniforms.depthValue,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";Ft.ShadersStoreWGSL.clearQuadPixelShader="uniform color: vec4f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;}\n";class xp{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new up(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"],void 0,void 0,void 0,void 0,void 0,void 0,ht.WGSL)}clear(e,t,i,s,r=1){let n,o,a=null;const l=!!this._engine._currentRenderTarget;if(e)n=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t1?2**36:0)+h*2**37,o=this._keyTemp.join("_"),a=this._bundleCache[o],a)return a;n=this._device.createRenderBundleEncoder({label:"clearQuadRenderBundle",colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:Xd.GetSample(r)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!s&&!!this._depthTextureFormat&&Xd.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(s?255:0),this._cacheRenderPipeline.setStencilCompare(s?519:512),this._cacheRenderPipeline.setStencilPassOp(s?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const h=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,r),c=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),c.uniformBuffer.update();const u=l?this._engine._ubInvertY:this._engine._ubDontInvertY,d=c.uniformBuffer.getBuffer(),p=d.uniqueId+"-"+u.uniqueId;let f=this._bindGroups[p];if(!f){const e=c.bindGroupLayouts[0];f=this._bindGroups[p]=[],f.push(this._device.createBindGroup({label:`clearQuadBindGroup0-${p}`,layout:e[0],entries:[]})),Gd._SimplifiedKnownBindings||f.push(this._device.createBindGroup({label:`clearQuadBindGroup1-${p}`,layout:e[1],entries:[]})),f.push(this._device.createBindGroup({label:`clearQuadBindGroup${Gd._SimplifiedKnownBindings?1:2}-${p}`,layout:e[Gd._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:u.underlyingResource,size:u.capacity}},{binding:1,resource:{buffer:d.underlyingResource,size:d.capacity}}]}))}n.setPipeline(h);for(let e=0;e{const e=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,e}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==s)return null;throw e}))}async readValue(e=0){const t=this._getBuffer(e,1);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(id.Read).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(id.Read).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[1]-e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0})))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;const i=this._engine.frameId;this._measureDuration.stopPass(e).then((e=>{t._addDuration(i,null!==e&&e>0?e:0)}))}dispose(){this._measureDuration?.dispose()}}class Mp{constructor(e,t,i,s=2,r){this._count=s,this._querySet=new Ip(e,s,wd.Timestamp,t,i,!0,r)}start(e){e.writeTimestamp?.(this._querySet.querySet,0)}async stop(e){return e.writeTimestamp?.(this._querySet.querySet,1),e.writeTimestamp?this._querySet.readTwoValuesAndSubtract(0):0}startPass(e,t){if(t+3>this._count)throw new Error("WebGPUDurationMeasure: index out of range ("+t+")");e.timestampWrites={querySet:this._querySet.querySet,beginningOfPassWriteIndex:t+2,endOfPassWriteIndex:t+3}}async stopPass(e){return this._querySet.readTwoValuesAndSubtract(e+2)}dispose(){this._querySet.dispose()}}class Dp{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;const t=void 0!==this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,s=50,r=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=r,this._allocateNewIndices(s)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();const e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e})))}_allocateNewIndices(e){e=e??this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose),1e3)}dispose(){this._querySet?.dispose(),this._availableIndices.length=0}}class Op{async initTwgsl(e){if(!Op._Twgsl)return e=e||{},(e={...Op._TWgslDefaultOptions,...e}).twgsl?(Op._Twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await Ii.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(Op._Twgsl=await self.twgsl(Ii.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=Op._Twgsl.convertSpirV2WGSL(e,Op.DisableUniformityAnalysis||t);return Op.ShowWGSLShaderCode&&(J.Log(i),J.Log("***********************************************")),Op.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}Op._TWgslDefaultOptions={jsPath:`${Ii._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${Ii._DefaultCdnUrl}/twgsl/twgsl.wasm`},Op.ShowWGSLShaderCode=!1,Op.DisableUniformityAnalysis=!1,Op._Twgsl=null;class Np{constructor(e,t,i){this._record=!1,this._play=!1,this._playBundleListIndex=0,this._allBundleLists=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._allBundleLists.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endRenderPass(e){if(!this._record&&!this._play)return!1;let t;if(this._record)t=this._bundleList.clone(),this._allBundleLists.push(t),this._bundleList.reset();else{if(this._playBundleListIndex>=this._allBundleLists.length)throw new Error(`Invalid playBundleListIndex! Your snapshot is no longer valid for the current frame, you should recreate a new one. playBundleListIndex=${this._playBundleListIndex}, allBundleLists.length=${this._allBundleLists.length}}`);t=this._allBundleLists[this._playBundleListIndex++]}return t.run(e),1===this._mode&&this._engine._reportDrawCall(t.numDrawCalls),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0}reset(){this.enabled=!1,this.enabled=!0}}Ft.ShadersStoreWGSL.postprocessVertexShader="attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class wp extends fp{constructor(e){super(e)}}const Fp={label:"TextureView_SwapChain_ResolveTarget",dimension:sd.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Lp={label:"TextureView_SwapChain",dimension:sd.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Bp=new j;class Vp extends si{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return!!this._cacheSampler&&this._cacheSampler.disabled}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}areAllEffectsReady(){return!0}getFontOffset(e){return Pr(e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then((e=>!!e),(()=>!1)).catch((()=>!1)):Promise.resolve(!1)}static get IsSupported(){return J.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){return this.name+this.version}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get enableGPUTimingMeasurements(){return this._timestampQuery.enable}set enableGPUTimingMeasurements(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new Xh:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new Vp(e,t);return new Promise((e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then((()=>e(i)))}))}constructor(e,t={}){super(t.antialias??!0,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._timestampIndex=0,this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this.scenes=[],this._virtualScenes=new Array,this._commandBuffers=[null,null],this._currentRenderPass=null,this._mainRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._rttRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._pendingDebugCommands=[],this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this._snapshotRenderingMode=0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._performanceMonitor=new Cr,this._name="WebGPU",this._drawCalls=new Is,t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=t.enableGPUDebugMarkers??!1,J.Log(`Babylon.js v${Br.Version} - ${this.description} engine`),navigator.gpu?(t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,navigator&&navigator.userAgent&&this._setupMobileChecks(),this._sharedInit(this._renderingCanvas),this._shaderProcessor=new zd,this._shaderProcessorWGSL=new Hd):J.Error("WebGPU is not supported by your browser.")}initAsync(e,t){return this.uniqueId=Vp._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,this._initGlslang(e??this._options?.glslangOptions).then((e=>(this._glslang=e,this._tintWASM=Vp.UseTWGSL?new Op:null,this._tintWASM?this._tintWASM.initTwgsl(t??this._options?.twgslOptions).then((()=>navigator.gpu.requestAdapter(this._options))):navigator.gpu.requestAdapter(this._options)))).then((e=>{if(e){this._adapter=e,this._adapterSupportedExtensions=[],this._adapter.features?.forEach((e=>this._adapterSupportedExtensions.push(e))),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then((e=>{this._adapterInfo=e}));const t=this._options.deviceDescriptor??{},i=t?.requiredFeatures??(this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0);if(i){const e=i,s=[];for(const t of e)-1!==this._adapterSupportedExtensions.indexOf(t)&&s.push(t);t.requiredFeatures=s}if(this._options.setMaximumLimits&&!t.requiredLimits){t.requiredLimits={};for(const e in this._adapterSupportedLimits)"minSubgroupSize"!==e&&"maxSubgroupSize"!==e&&(t.requiredLimits[e]=this._adapterSupportedLimits[e])}return t.label=`BabylonWebGPUDevice${this.uniqueId}`,this._adapter.requestDevice(t)}throw"Could not retrieve a WebGPU adapter (adapter is null)."})).then((e=>{this._device=e,this._deviceEnabledExtensions=[],this._device.features?.forEach((e=>this._deviceEnabledExtensions.push(e))),this._deviceLimits=e.limits;let t=-1;this._device.addEventListener("uncapturederror",(e=>{++t{this._isDisposed||(this._contextWasLost=!0,J.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost((async()=>{const e=this.snapshotRenderingMode,t=this.snapshotRendering,i=this.disableCacheSamplers,s=this.disableCacheRenderPipelines,r=this.disableCacheBindGroups,n=this.enableGPUTimingMeasurements;await this.initAsync(this._glslangOptions??this._options?.glslangOptions,this._twgslOptions??this._options?.twgslOptions),this.snapshotRenderingMode=e,this.snapshotRendering=t,this.disableCacheSamplers=i,this.disableCacheRenderPipelines=s,this.disableCacheBindGroups=r,this.enableGPUTimingMeasurements=n,this._currentRenderPass=null})))}))})).then((()=>{this._bufferManager=new tp(this,this._device),this._textureHelper=new Jd(this,this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new np(this._device),this._cacheBindGroups=new vp(this._device,this._cacheSampler,this),this._timestampQuery=new Pp(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new Dp(this,this._device,this._bufferManager):void 0,this._bundleList=new Rp(this._device),this._snapshotRendering=new Np(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),td.Uniform|td.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),td.Uniform|td.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&void 0===this._count&&(this._count=0,J.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._initializeLimits(),this._emptyVertexBuffer=new Ki(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new up(this._device,this._emptyVertexBuffer),this._depthCullingState=new pp(this._cacheRenderPipeline),this._stencilStateComposer=new dp(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new xp(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()})).catch((e=>{throw J.Error("A fatal error occurred during WebGPU creation/initialization."),e}))}_initGlslang(e){return e=e||{},(e={...Vp._GLSLslangDefaultOptions,...e}).glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?Ii.LoadBabylonScriptAsync(e.jsPath).then((()=>self.glslang(Ii.GetBabylonScriptURL(e.wasmPath)))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(Ju.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(Ju.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(Ju.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(Ju.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf(Ju.RG11B10UFloatRenderable)>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(Ju.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf(Ju.TimestampQuery)||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new Yd],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._setColorFormat(this._mainRenderPassWrapper)}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};const e=new Float32Array([this.getRenderHeight(!0)]);let t;if(this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e),this._options.antialias){const e={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:sd.E2d,format:this._options.swapChainFormat,usage:rd.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(e),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:sd.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new j(0,0,0,1),loadOp:Od.Clear,storeOp:Nd.Store}]}else t=[{view:void 0,clearValue:new j(0,0,0,1),loadOp:Od.Clear,storeOp:Nd.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?ad.Depth24PlusStencil8:ad.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);const i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:sd.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:rd.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const s={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:sd.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:Od.Clear,depthStoreOp:Nd.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?Od.Clear:void 0,stencilStoreOp:this.isStencilEnable?Nd.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:s}}_sharedInit(e){super._sharedInit(e),Rr(this,e,this._creationOptions)}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:rd.RenderAttachment|rd.CopySrc,alphaMode:this.premultipliedAlpha?Fd.Premultiplied:Fd.Opaque})}resizeImageBitmap(e,t,i){return Dr(this,e,t,i)}_createImageBitmapFromSource(e,t){return Mr(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&Or(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&Nr()}enterPointerlock(){this._renderingCanvas&&wr(this._renderingCanvas)}exitPointerlock(){Fr()}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){up.ResetCache(),vp.ResetCache();const t=e=>{for(const t of e){for(const e of t.meshes){const t=e.subMeshes;if(t)for(const e of t)e._drawWrappers=[]}for(const e of t.materials)e._materialContext?.reset()}};t(this.scenes),t(this._virtualScenes);const i=[];for(const e of this._uniformBuffers)e.name.indexOf("leftOver")<0&&i.push(e);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setSize(e,t,i=!1){return!!super.setSize(e,t,i)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0,r=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,n=i===ht.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===ht.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,o,i,s,r)}_compilePipelineStageDescriptor(e,t,i,s){this.onBeforeShaderCompilationObservable.notifyObservers(this);const r=e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,n=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,o="#version 450\n",a=s===ht.GLSL?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),l=s===ht.GLSL?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(a,l,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new Ou(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new Ud(e,this)}createMaterialContext(){return new _p}createDrawContext(){return new mp(this._bufferManager)}_preparePipelineContext(e,t,i,s,r,n,o,a){const l=e,h=l.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(J.Log(["defines",a]),J.Log(t),J.Log(i),J.Log("***********************************************")),l.sources={fragment:i,vertex:t,rawVertex:r,rawFragment:n},l.stages=s?this._compileRawPipelineStageDescriptor(t,i,h):this._compilePipelineStageDescriptor(t,i,a,h)}getAttributes(e,t){const i=new Array(t.length),s=e;for(let e=0;e0,n.is3D=l>0,n._cachedWrapU=0,n._cachedWrapV=0,n._useSRGBBuffer=r.useSRGBBuffer,n.label=r.label,this._internalTexturesCache.push(n),i||this._textureHelper.createGPUTextureForInternalTexture(n,o,a,h||1,r.creationFlags),n}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,p,f){return this._createTextureBase(e,t,i,s,r,n,o,((e,t,i,s,r,n,o,a)=>{const l=s;if(e.baseWidth=l.width,e.baseHeight=l.height,e.width=l.width,e.height=l.height,e.format=-1!==e.format?e.format:h??5,e.type=-1!==e.type?e.type:0,e._creationFlags=p??0,a(e.width,e.height,l,t,e,(()=>{})),e._hardwareTexture?.underlyingResource)n||o||this._generateMipmaps(e,this._uploadEncoder);else{const t=this._textureHelper.createGPUTextureForInternalTexture(e,l.width,l.height,void 0,p);Xd.IsImageBitmap(l)&&(this._textureHelper.updateTexture(l,e,l.width,l.height,e.depth,t.format,0,0,r,!1,0,0),n||o||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}),(()=>!1),a,l,h,c,u,d,f)}wrapWebGPUTexture(e){const t=new Yd(e),i=new ti(this,ei.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers}_unpackFlipY(e){}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,s=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==s&&(e._cachedWrapR=s)}updateTextureDimensions(e,t,i,s=1){if(!e._hardwareTexture)return;if(e.width===t&&e.height===i&&e.depth===s)return;const r=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,s,r)}_setInternalTexture(e,t,i){if(i=i??e,this._currentEffect){const s=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),s&&s.autoBindSampler){const e=i+"Sampler";this._currentMaterialContext.setSampler(e,t)}}}createPrefilteredCubeTexture(e,t,i,s,r=null,n=null,o,a=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(r&&r(null));const t=e.texture;l?e.info.sphericalPolynomial&&(t._sphericalPolynomial=e.info.sphericalPolynomial):t._sphericalPolynomial=new Qc,t._source=ei.CubePrefiltered,r&&r(t)}),n,o,a,l,i,s)}setTexture(e,t,i,s){this._setTexture(e,i,!1,!1,s,s)}setTextureArray(e,t,i,s){for(let e=0;e{const o=()=>{n.mapAsync(id.Read,0,i).then((()=>{const t=n.getMappedRange(0,i);let r=s;if(void 0===r)r=new Uint8Array(i),r.set(new Uint8Array(t));else{const e=r.constructor;r=new e(r.buffer),r.set(new e(t))}n.unmap(),this._bufferManager.releaseBuffer(n),e(r)}),(i=>{this.isDisposed?e(new Uint8Array):t(i)}))};r?(this.flushFramebuffer(),o()):this.onEndFrameObservable.addOnce((()=>{o()}))}))}setStorageBuffer(e,t){this._currentDrawContext?.setBuffer(e,t?.getBuffer()??null)}}Vp._GLSLslangDefaultOptions={jsPath:`${Ii._DefaultCdnUrl}/glslang/glslang.js`,wasmPath:`${Ii._DefaultCdnUrl}/glslang/glslang.wasm`},Vp._InstanceId=0,Vp.UseTWGSL=!0,Vp.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode===e&&(0===e&&!this._alphaState.alphaBlend||0!==e&&this._alphaState.alphaBlend)){if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.setDepthWrite(t),this._cacheRenderPipeline.setDepthWriteEnabled(t))}}else{switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,1),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,1),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(1,1,0,1),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(770,1,0,1),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(0,769,1,1),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(774,0,1,1),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(770,769,1,1),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(32769,32770,32771,32772),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(1,769,1,771),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,1),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(772,1,0,0),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(775,769,773,771),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,0),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(775,769,0,1),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,771),this._alphaState.alphaBlend=!0}t||(this.setDepthWrite(0===e),this._cacheRenderPipeline.setDepthWriteEnabled(0===e)),this._alphaMode=e,this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)}},Vp.prototype.setAlphaEquation=function(e){si.prototype.setAlphaEquation.call(this,e),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};class Up{getBindGroups(e,t,i){if(!i)throw new Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");if(0===this._bindGroups.length){const s=this._bindGroupEntries.length>0;for(const t in e){const r=e[t],n=i[t],o=n.group,a=n.binding,l=r.type,h=r.object;let c=r.indexInGroupEntries,u=this._bindGroupEntries[o];switch(u||(u=this._bindGroupEntries[o]=[]),l){case kh.Sampler:{const e=h;void 0!==c&&s?u[c].resource=this._cacheSampler.getSampler(e):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:this._cacheSampler.getSampler(e)}));break}case kh.Texture:case kh.TextureWithoutSampler:{const e=h,t=e._texture._hardwareTexture;void 0!==c&&s?(l===kh.Texture&&(u[c++].resource=this._cacheSampler.getSampler(e._texture)),u[c].resource=t.view):(r.indexInGroupEntries=u.length,l===kh.Texture&&u.push({binding:a-1,resource:this._cacheSampler.getSampler(e._texture)}),u.push({binding:a,resource:t.view}));break}case kh.StorageTexture:{const e=h,t=e._texture._hardwareTexture;t.textureAdditionalUsages&rd.StorageBinding||J.Error(`computeDispatch: The texture (name=${e.name}, uniqueId=${e.uniqueId}) is not a storage texture!`,50),void 0!==c&&s?u[c].resource=t.viewForWriting:(r.indexInGroupEntries=u.length,u.push({binding:a,resource:t.viewForWriting}));break}case kh.ExternalTexture:{const e=h.underlyingResource;void 0!==c&&s?u[c].resource=this._device.importExternalTexture({source:e}):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:this._device.importExternalTexture({source:e})}));break}case kh.UniformBuffer:case kh.StorageBuffer:case kh.DataBuffer:{const e=l===kh.DataBuffer?h:(kh.UniformBuffer,h.getBuffer()),t=e.underlyingResource;void 0!==c&&s?(u[c].resource.buffer=t,u[c].resource.size=e.capacity):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:{buffer:t,offset:0,size:e.capacity}}));break}}}for(let e=0;e0&&d.dispatchWorkgroups(s,r,n),d.end(),h&&(this._timestampQuery.endPass(this._timestampIndex,h),this._timestampIndex+=2)},Vp.prototype.releaseComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e].getPipelineContext();this._deleteComputePipelineContext(t)}this._compiledComputeEffects={}},Vp.prototype._prepareComputePipelineContext=function(e,t,i,s,r){const n=e;this.dbgShowShaderCode&&(J.Log(s),J.Log(t)),n.sources={compute:t,rawCompute:i},n.stage=this._createComputePipelineStageDescriptor(t,s,r)},Vp.prototype._releaseComputeEffect=function(e){this._compiledComputeEffects[e._key]&&(delete this._compiledComputeEffects[e._key],this._deleteComputePipelineContext(e.getPipelineContext()))},Vp.prototype._rebuildComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}},Vp.prototype._executeWhenComputeStateIsCompiled=function(e,t){e.stage.module.getCompilationInfo().then((e=>{const i={numErrors:0,messages:[]};for(const t of e.messages)"error"===t.type&&i.numErrors++,i.messages.push({type:t.type,text:t.message,line:t.lineNum,column:t.linePos,length:t.length,offset:t.offset});t(i)}))},Vp.prototype._deleteComputePipelineContext=function(e){e&&e.dispose()},Vp.prototype._createComputePipelineStageDescriptor=function(e,t,i){return t=t?"//"+t.split("\n").join("\n//")+"\n":"",{module:this._device.createShaderModule({code:t+e}),entryPoint:i}},Vp.prototype._createDepthStencilCubeTexture=function(e,t){const i=new ti(this,t.generateStencil?ei.DepthStencil:ei.Depth);i.isCube=!0,i.label=t.label;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t};i.format=s.depthTextureFormat,this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction,s.samples),this._textureHelper.createGPUTextureForInternalTexture(i);const r=i._hardwareTexture;return i.type=Xd.GetTextureTypeFromFormat(r.format),this._internalTexturesCache.push(i),i},Vp.prototype.createCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d=!1){return this.createCubeTextureBase(e,t,i,!!s,r,n,o,a,l,h,c,u,null,((e,t)=>{const i=t,n=i[0].width,a=n;this._setCubeMapTextureParams(e,!s),e.format=o??-1;const l=this._textureHelper.createGPUTextureForInternalTexture(e,n,a);this._textureHelper.updateCubeTextures(i,l.underlyingResource,n,a,l.format,!1,!1,0,0),s||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),r&&r()}),!!d)},Vp.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},Vp.prototype.generateMipMapsForCubemap=function(e){if(e.generateMipMaps){const t=e._hardwareTexture?.underlyingResource;t||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e)}},Vp.prototype._debugPushGroup=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.pushDebugGroup(e):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e]))},Vp.prototype._debugPopGroup=function(e){this._options.enableGPUDebugMarkers&&(0===e||1===e?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))},Vp.prototype._debugInsertMarker=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.insertDebugMarker(e):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e]))},Vp.prototype._debugFlushPendingCommands=function(){for(let e=0;e{const i=d.width,n=o(e);if(n){if(a){const e=4===s,t=a(n),o=d._hardwareTexture,l=[0,1,2,3,4,5];for(let s=0;s>s,a=[];for(let i=0;i<6;i++){let o=t[s][l[i]];e&&(o=zp(o,n,n,r)),a.push(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}this._textureHelper.updateCubeTextures(a,o.underlyingResource,n,n,o.format,u,!1,0,0)}}else this.updateRawCubeTexture(d,n,s,r,u);d.isReady=!0,t?.removePendingData(d),l&&l()}};return this._loadFile(e,(e=>{p(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)})),d},Vp.prototype.createRawTexture3D=function(e,t,i,s,r,n,o,a,l=null,h=0,c=0){const u=ei.Raw3D,d=new ti(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=s,d.width=t,d.height=i,d.depth=s,d.format=r,d.type=h,d.generateMipMaps=n,d.samplingMode=a,d.is3D=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,void 0,c),this.updateRawTexture3D(d,e,r,o,l,h),this._internalTexturesCache.push(d),d},Vp.prototype.updateRawTexture3D=function(e,t,i,s,r=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r),t){const r=e._hardwareTexture;4===i&&(t=zp(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,r.format,0,0,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Vp.prototype.createRawTexture2DArray=function(e,t,i,s,r,n,o,a,l=null,h=0,c=0){const u=ei.Raw2DArray,d=new ti(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=s,d.width=t,d.height=i,d.depth=s,d.format=r,d.type=h,d.generateMipMaps=n,d.samplingMode=a,d.is2DArray=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,s,c),this.updateRawTexture2DArray(d,e,r,o,l,h),this._internalTexturesCache.push(d),d},Vp.prototype.updateRawTexture2DArray=function(e,t,i,s,r=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r),t){const r=e._hardwareTexture;4===i&&(t=zp(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,r.format,0,0,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Vp.prototype._readTexturePixels=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){const c=e._hardwareTexture;return o&&this.flushFramebuffer(),this._textureHelper.readPixels(c.underlyingResource,l,h,t,i,c.format,s,r,n,a)},Vp.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};class Wp extends jo{constructor(e,t,i,s,r){super(e,t,i,s,r),s.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new Xh)}}Vp.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const s=new Wp(e,t,i,this);return this._renderTargetWrapperCache.push(s),s},Vp.prototype.createRenderTargetTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),s={};void 0!==t&&"object"==typeof t?(s.generateMipMaps=t.generateMipMaps,s.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,s.generateStencilBuffer=s.generateDepthBuffer&&t.generateStencilBuffer,s.samplingMode=void 0===t.samplingMode?3:t.samplingMode,s.creationFlags=t.creationFlags??0,s.noColorAttachment=!!t.noColorAttachment,s.samples=t.samples,s.label=t.label):(s.generateMipMaps=t,s.generateDepthBuffer=!0,s.generateStencilBuffer=!1,s.samplingMode=3,s.creationFlags=0,s.noColorAttachment=!1);const r=s.noColorAttachment?null:this._createInternalTexture(e,t,!0,ei.RenderTarget);return i.label=s.label??"RenderTargetWrapper",i._samples=s.samples??1,i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer,i.setTextures(r),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,!1,i._generateStencilBuffer,i.samples,s.generateStencilBuffer?13:14,s.label?s.label+"-DepthStencil":void 0),r&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r,void 0,void 0,void 0,s.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!1)),i},Vp.prototype._createDepthStencilTexture=function(e,t){const i=new ti(this,t.generateStencil?ei.DepthStencil:ei.Depth);i.label=t.label;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t};i.format=s.depthTextureFormat,this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction,s.samples),this._textureHelper.createGPUTextureForInternalTexture(i);const r=i._hardwareTexture;return i.type=Xd.GetTextureTypeFromFormat(r.format),this._internalTexturesCache.push(i),i},Vp.prototype._setupDepthStencilTexture=function(e,t,i,s,r,n=1){const o=t.width||t,a=t.height||t,l=t.layers||0,h=t.depth||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.is3D=h>0,e.depth=l||h,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=1,e._comparisonFunction=r,e._cachedWrapU=0,e._cachedWrapV=0},Vp.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t?(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t,t):t},Vp.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,i.label=s.label??"RenderTargetWrapper",i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer;const r=new ti(this,ei.RenderTarget);return r.width=e,r.height=e,r.depth=0,r.isReady=!0,r.isCube=!0,r.samples=s.samples,r.generateMipMaps=s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,r.format=s.format,this._internalTexturesCache.push(r),i.setTextures(r),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,void 0===s.samplingMode||2===s.samplingMode||2===s.samplingMode||3===s.samplingMode||3===s.samplingMode||5===s.samplingMode||6===s.samplingMode||7===s.samplingMode||11===s.samplingMode,i._generateStencilBuffer,i.samples),t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r),t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!1),i},Vp.prototype.setDepthStencilTexture=function(e,t,i,s){i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,s):this._setTexture(e,null,void 0,void 0,s)},Vp.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;e._hardwareTexture?.underlyingResource||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),function(e){return!(!e||void 0===e.underlyingResource)}(t)?(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0):t&&this.createImageBitmap(t).then((t=>{this._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,s.format,0,0,!i,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0})).catch((()=>{e.isReady=!0}))};class Hp{}Hp.COPY=1,Hp.CUT=2,Hp.PASTE=3;class Xp extends ec{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=Y.Gray(),i=Jh.DefaultUtilityLayer,s=null,r=1,n=Y.Yellow(),o=Y.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new g,this.uniformScaling=!1,this.sensitivity=1,this.dragScale=1,this.incrementalSnap=!1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._tmpVector=new w(0,0,0),this._incrementalStartupValue=w.Zero(),this._parent=s,this._coloredMaterial=new dh("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Y(.1,.1,.1)),this._hoverMaterial=new dh("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new dh("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4,this._gizmoMesh=new Un("axis",i.utilityLayerScene);const{arrowMesh:a,arrowTail:l}=this._createGizmoMesh(this._gizmoMesh,r),h=this._createGizmoMesh(this._gizmoMesh,r+4,!0);this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,ec.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3);const c=a.position.clone(),u=l.position.clone(),d=l.scaling.clone(),p=e=>{const t=e*(3/this._rootMesh.scaling.length())*6;a.position.z+=t/3.5,l.scaling.y+=t,this.dragScale=l.scaling.y,l.position.z=a.position.z/2},f=()=>{a.position.set(c.x,c.y,c.z),l.position.set(u.x,u.y,u.z),l.scaling.set(d.x,d.y,d.z),this.dragScale=l.scaling.y,this._dragging=!1};this.dragBehavior=new uo({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior);let _=0,m=0;const v={snapDistance:0};this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const i=this.sensitivity*t.dragDistance*(3*this.scaleRatio/this._rootMesh.scaling.length()),s=this._tmpVector;let r=!1,n=0;if(this.uniformScaling?s.setAll(.57735):s.copyFrom(e),0==this.snapDistance)s.scaleToRef(i,s);else{_+=i,m+=i;const e=this.incrementalSnap?m:_;Math.abs(e)>this.snapDistance?(n=Math.floor(Math.abs(e)/this.snapDistance),e<0&&(n*=-1),_%=this.snapDistance,s.scaleToRef(this.snapDistance*n,s),r=!0):s.scaleInPlace(0)}s.addInPlaceFromFloats(1,1,1),s.x=Math.abs(s.x)0&&this.incrementalSnap?(this.attachedNode.getWorldMatrix().decompose(void 0,U.Quaternion[0],U.Vector3[2],ec.PreserveScaling?o:void 0),s.addInPlace(this._incrementalStartupValue),s.addInPlaceFromFloats(-1,-1,-1),s.x=Math.abs(s.x)*(this._incrementalStartupValue.x>0?1:-1),s.y=Math.abs(s.y)*(this._incrementalStartupValue.y>0?1:-1),s.z=Math.abs(s.z)*(this._incrementalStartupValue.z>0?1:-1),B.ComposeToRef(s,U.Quaternion[0],U.Vector3[2],U.Matrix[1])):(B.ScalingToRef(s.x,s.y,s.z,U.Matrix[2]),U.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(),U.Matrix[1])),U.Matrix[1].decompose(U.Vector3[1],void 0,void 0,ec.PreserveScaling?o:void 0);const a=1e5;Math.abs(U.Vector3[1].x){this._dragging=!0;const e=this.attachedNode._isMesh?this.attachedNode:void 0;this.attachedNode?.getWorldMatrix().decompose(this._incrementalStartupValue,void 0,void 0,ec.PreserveScaling?e:void 0),_=0,m=0})),this.dragBehavior.onDragObservable.add((e=>p(e.dragDistance))),this.dragBehavior.onDragEndObservable.add(f),s?.uniformScaleGizmo?.dragBehavior?.onDragObservable?.add((e=>p(e.delta.y))),s?.uniformScaleGizmo?.dragBehavior?.onDragEndObservable?.add(f);const x={gizmoMeshes:[a,l],colliderMeshes:[h.arrowMesh,h.arrowTail],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,x),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(this._customMeshSet)return;let t=this._parent?.getAxisCache(this._gizmoMesh);if(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),t=this._parent?.getAxisCache(this._rootMesh),this._isHovered||(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh))),!this._parent){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(x.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(x.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}));const T=i._getSharedGizmoLight();T.includedOnlyMeshes=T.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes())}_createGizmoMesh(e,t,i=!1){const s=sc("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),r=Qh("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return s.scaling.scaleInPlace(.1),s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,s.position.z+=.3,r.material=this._coloredMaterial,r.position.z+=.1375,r.rotation.x=Math.PI/2,i&&(s.visibility=0,r.visibility=0),e.addChild(s),e.addChild(r),{arrowMesh:s,arrowTail:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}setCustomMesh(e,t=!1){super.setCustomMesh(e),t&&(this._rootMesh.getChildMeshes().forEach((e=>{e.material=this._coloredMaterial,e.color&&(e.color=this._coloredMaterial.diffuseColor)})),this._customMeshSet=!1)}}Xp.MinimumAbsoluteScale=T;class Yp extends ec{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}set rotationColor(e){this._rotationShaderMaterial.setColor3("rotationColor",e)}get disableMaterial(){return this._disableMaterial}constructor(e,t=Y.Gray(),i=Jh.DefaultUtilityLayer,s=32,r=null,n=!1,o=1,a=Y.Yellow(),l=Y.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new g,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new w,this._parent=r,this._coloredMaterial=new dh("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Y(.1,.1,.1)),this._hoverMaterial=new dh("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a,this._hoverMaterial.specularColor=a,this._disableMaterial=new dh("",i.utilityLayerScene),this._disableMaterial.diffuseColor=l,this._disableMaterial.alpha=.4,this._gizmoMesh=new Un("",i.utilityLayerScene);const{rotationMesh:h,collider:c}=this._createGizmoMesh(this._gizmoMesh,o,s);this._rotationDisplayPlane=co("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),$t.ShadersStore.rotationGizmoVertexShader=Yp._RotationGizmoVertexShader,$t.ShadersStore.rotationGizmoFragmentShader=Yp._RotationGizmoFragmentShader,this._rotationShaderMaterial=new fc("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles","rotationColor"]}),this._rotationShaderMaterial.backFaceCulling=!1,this.rotationColor=a,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,ec.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new uo({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=Yp.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);const u=new w,d=new B,p=new w;let f=new w;this.dragBehavior.onDragStartObservable.add((e=>{this.attachedNode&&(u.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(d),w.TransformCoordinatesToRef(e.dragPlanePoint,d,u),this._angles.x=Math.atan2(u.y,u.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,u.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)}));const _={snapDistance:0};let m=0;const v=new B,x=new L;this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const s=new w(1,1,1),r=new L(0,0,0,1),n=new w(0,0,0);if(this.attachedNode.getWorldMatrix().decompose(s,r,n),!(Math.abs(Math.abs(s.x)-Math.abs(s.y))<=T&&Math.abs(Math.abs(s.x)-Math.abs(s.z))<=T)&&this.updateGizmoRotationToMatchAttachedMesh)return void J.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");r.normalize();const o=this.updateGizmoPositionToMatchAttachedMesh?n:this._rootMesh.absolutePosition,a=t.dragPlanePoint.subtract(o).normalize(),l=u.subtract(o).normalize(),h=w.Cross(a,l),c=w.Dot(a,l);let g=Math.atan2(h.length(),c)*this.sensitivity;p.copyFrom(e),f.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(r.toRotationMatrix(d),f=w.TransformCoordinates(p,d));let S=!1;if(i.utilityLayerScene.activeCamera){const e=i.utilityLayerScene.activeCamera.position.subtract(o).normalize();w.Dot(e,f)>0&&(p.scaleInPlace(-1),f.scaleInPlace(-1),S=!0)}w.Dot(f,h)>0&&(g=-g),U.Vector3[0].set(g,0,0),this.dragBehavior.validateDrag(U.Vector3[0])||(g=0);let E=!1;if(0!=this.snapDistance)if(m+=g,Math.abs(m)>this.snapDistance){let e=Math.floor(Math.abs(m)/this.snapDistance);m<0&&(e*=-1),m%=this.snapDistance,g=this.snapDistance*e,E=!0}else g=0;const b=Math.sin(g/2);if(x.set(p.x*b,p.y*b,p.z*b,Math.cos(g/2)),v.determinant()>0){const e=new w;x.toEulerAnglesToRef(e),L.RotationYawPitchRollToRef(e.y,-e.x,-e.z,x)}if(this.updateGizmoRotationToMatchAttachedMesh)r.multiplyToRef(x,r),r.normalize(),B.ComposeToRef(s,r,n,this.attachedNode.getWorldMatrix());else{x.toRotationMatrix(U.Matrix[0]);const e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(U.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}u.copyFrom(t.dragPlanePoint),E&&(_.snapDistance=g,this.onSnapObservable.notifyObservers(_)),this._angles.y+=g,this.angle+=S?-g:g,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}}));const S=i._getSharedGizmoLight();S.includedOnlyMeshes=S.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const E={colliderMeshes:[c],gizmoMeshes:[h],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,E),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=Yp.MaxDragAngle,this._isHovered=!(-1==E.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=E.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(E.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(E.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_createGizmoMesh(e,t,i){const s=Oh("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);s.visibility=0;const r=Oh("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return r.material=this._coloredMaterial,r.rotation.x=Math.PI/2,s.rotation.x=Math.PI/2,e.addChild(r,ec.PreserveScaling),e.addChild(s,ec.PreserveScaling),{rotationMesh:r,collider:s}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}Yp.MaxDragAngle=9*Math.PI/20,Yp._RotationGizmoVertexShader="\n precision highp float;\n attribute vec3 position;\n attribute vec2 uv;\n uniform mat4 worldViewProjection;\n varying vec3 vPosition;\n varying vec2 vUV;\n\n void main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n vUV = uv;\n }",Yp._RotationGizmoFragmentShader="\n precision highp float;\n varying vec2 vUV;\n varying vec3 vPosition;\n uniform vec3 angles;\n uniform vec3 rotationColor;\n\n #define twopi 6.283185307\n\n void main(void) {\n vec2 uv = vUV - vec2(0.5);\n float angle = atan(uv.y, uv.x) + 3.141592;\n float delta = gl_FrontFacing ? angles.y : -angles.y;\n float begin = angles.x - delta * angles.z;\n float start = (begin < (begin + delta)) ? begin : (begin + delta);\n float end = (begin > (begin + delta)) ? begin : (begin + delta);\n float len = sqrt(dot(uv,uv));\n float opacity = 1. - step(0.5, len);\n\n float base = abs(floor(start / twopi)) * twopi;\n start += base;\n end += base;\n\n float intensity = 0.;\n for (int i = 0; i < 5; i++)\n {\n intensity += max(step(start, angle) - step(end, angle), 0.);\n angle += twopi;\n }\n gl_FragColor = vec4(rotationColor, min(intensity * 0.25, 0.8)) * opacity;\n }\n ";class jp extends Gn{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=B.Identity(),this._projectionMatrix=B.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return!(!this.parent||!this.parent.getWorldMatrix||(this.transformedPosition||(this.transformedPosition=w.Zero()),w.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=w.Zero()),w.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),0))}getDepthScale(){return 50}getShadowDirection(e){return this.transformedDirection?this.transformedDirection:this.direction}getAbsolutePosition(){return this.transformedPosition?this.transformedPosition:this.position}setDirectionToTarget(e){return this.direction=w.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=w.Cross(this.direction,Gs.Y),t=w.Cross(e,this.direction);return w.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=w.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=B.Identity()),B.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),this.parent&&this.parent.getWorldMatrix||(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){const t=U.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),w.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(w.Dot(t,w.Up()))&&(t.z=1e-13);const s=U.Vector3[1];return i.addToRef(t,s),B.LookAtLHToRef(i,s,w.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}ae([ve()],jp.prototype,"position",null),ae([ve()],jp.prototype,"direction",null),ae([pe()],jp.prototype,"shadowMinZ",null),ae([pe()],jp.prototype,"shadowMaxZ",null),De.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new $p(e,w.Zero(),t)));class $p extends jp{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,i){super(e,i),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return Gn.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){const t=this.getScene().activeCamera;t&&B.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=w.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let s=Number.MAX_VALUE,r=-Number.MAX_VALUE;for(let n=0;nthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zr&&(r=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=s,this._shadowMaxZ=r)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,o=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;B.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,l?a:o,l?o:a,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}function Kp(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);const s=nc("",{slice:.5,diameter:t.diameter,segments:t.segments},i),r=cc("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);r.rotation.x=-Math.PI/2,r.parent=s;const n=Un.MergeMeshes([r,s],!0);return n.name=e,n}ae([pe()],$p.prototype,"shadowFrustumSize",null),ae([pe()],$p.prototype,"shadowOrthoScale",null),ae([pe()],$p.prototype,"autoUpdateExtends",void 0),ae([pe()],$p.prototype,"autoCalcShadowZBounds",void 0),ae([pe("orthoLeft")],$p.prototype,"_orthoLeft",void 0),ae([pe("orthoRight")],$p.prototype,"_orthoRight",void 0),ae([pe("orthoTop")],$p.prototype,"_orthoTop",void 0),ae([pe("orthoBottom")],$p.prototype,"_orthoBottom",void 0),u("BABYLON.DirectionalLight",$p),Un.CreateHemisphere=(e,t,i,s)=>Kp(e,{segments:t,diameter:i},s),De.AddNodeConstructor("Light_Type_2",((e,t)=>()=>new qp(e,w.Zero(),w.Zero(),0,0,t)));class qp extends jp{get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(.5*e),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()}get innerAngle(){return this._innerAngle}set innerAngle(e){this._innerAngle=e,this._computeAngleValues()}get shadowAngleScale(){return this._shadowAngleScale}set shadowAngleScale(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()}get projectionTextureMatrix(){return this._projectionTextureMatrix}get projectionTextureLightNear(){return this._projectionTextureLightNear}set projectionTextureLightNear(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureLightFar(){return this._projectionTextureLightFar}set projectionTextureLightFar(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureUpDirection(){return this._projectionTextureUpDirection}set projectionTextureUpDirection(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0}get projectionTexture(){return this._projectionTexture}set projectionTexture(e){this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(qp._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((()=>{this._markMeshesAsLightDirty()})):qp._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce((()=>{this._markMeshesAsLightDirty()}))))}static _IsProceduralTexture(e){return void 0!==e.onGeneratedObservable}static _IsTexture(e){return void 0!==e.onLoadObservable}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,s,r,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=B.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=w.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=w.Zero(),this._projectionTextureViewLightMatrix=B.Zero(),this._projectionTextureProjectionLightMatrix=B.Zero(),this._projectionTextureScalingMatrix=B.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=s,this.exponent=r}getClassName(){return"SpotLight"}getTypeID(){return Gn.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;this._shadowAngleScale=this._shadowAngleScale||1;const r=this._shadowAngleScale*this._angle,n=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;B.PerspectiveFovLHToRef(r,1,a?o:n,a?n:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,a)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),B.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),s=-i*t,r=1/Math.tan(this._angle/2);B.FromValuesToRef(r/1,0,0,0,0,r,0,0,0,0,i,1,0,0,s,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof Zn){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;B.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}_computeAngleValues(){this._lightAngleScale=1/Math.max(.001,Math.cos(.5*this._innerAngle)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightTexture"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=w.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=w.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return i=this.computeTransformedInformation()?w.Normalize(this.transformedDirection):w.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!(!this.projectionTexture||!this.projectionTexture.isReady())}}ae([pe()],qp.prototype,"angle",null),ae([pe()],qp.prototype,"innerAngle",null),ae([pe()],qp.prototype,"shadowAngleScale",null),ae([pe()],qp.prototype,"exponent",void 0),ae([pe()],qp.prototype,"projectionTextureLightNear",null),ae([pe()],qp.prototype,"projectionTextureLightFar",null),ae([pe()],qp.prototype,"projectionTextureUpDirection",null),ae([fe("projectedLightTexture")],qp.prototype,"_projectionTexture",void 0),u("BABYLON.SpotLight",qp);class Qp extends ec{constructor(e=Jh.DefaultUtilityLayer){super(e),this._cachedPosition=new w,this._cachedForward=new w(0,0,1),this._pointerObserver=null,this.onClickedObservable=new g,this._light=null,this.attachedMesh=new Wr("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new Ur("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new dh("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new Y(.5,.5,.5),this._material.specularColor=new Y(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._light&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._light))}),ss.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){J.Warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),this._lightMesh=e instanceof Zh?Qp._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof $p?Qp._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof qp?Qp._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):Qp._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._lightMesh.parent=this._rootMesh;const t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new L,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction){this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0);const t=this._getMeshForward();this._cachedForward.copyFrom(t)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(U.Vector3[0]),e=U.Vector3[0]),e}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position)if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{const e=this.attachedMesh.position;this._light.position=new w(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction){const e=this._getMeshForward();if(w.DistanceSquared(e,this._cachedForward)>1e-4){const t=e;this._light.direction=new w(t.x,t.y,t.z),this._cachedForward.copyFrom(e)}else w.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){const t=new Un("hemisphereLight",e),i=Kp(t.name,{segments:10,diameter:1},e);return i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(3,e).parent=t,t.scaling.scaleInPlace(Qp._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){const t=new Un("pointLight",e),i=nc(t.name,{segments:10,diameter:1},e);return i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(5,e).parent=t,t.scaling.scaleInPlace(Qp._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){const t=new Un("spotLight",e);nc(t.name,{segments:10,diameter:1},e).parent=t;const i=Kp(t.name,{segments:10,diameter:2},e);return i.parent=t,i.rotation.x=-Math.PI/2,this._CreateLightLines(2,e).parent=t,t.scaling.scaleInPlace(Qp._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){const t=new Un("directionalLight",e),i=new Un(t.name,e);i.parent=t,nc(t.name,{diameter:1.2,segments:10},e).parent=i;const s=Qh(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);s.parent=i;let r=s.clone(t.name);r.scaling.y=.5,r.position.x+=1.25;let n=s.clone(t.name);n.scaling.y=.5,n.position.x+=-1.25;const o=Qh(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,r=o.clone(t.name),r.position.y=1.5,r.position.x+=1.25,n=o.clone(t.name),n.position.y=1.5,n.position.x+=-1.25,i.scaling.scaleInPlace(Qp._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}Qp._Scale=.007,Qp._CreateLightLines=(e,t)=>{const i=new Un("root",t);i.rotation.x=Math.PI/2;const s=new Un("linePivot",t);s.parent=i;const r=Qh("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(r.position.y=r.scaling.y/2+1.2,r.parent=s,e<2)return s;for(let e=0;e<4;e++){const t=s.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){const t=s.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){const t=s.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}return e<5||(s.clone("linePivotClone").rotation.z=Math.PI),i};class Zp extends ec{constructor(e=Jh.DefaultUtilityLayer,t,i){super(e),this._pointerObserver=null,this.onClickedObservable=new g,this._camera=null,this._invProjection=new B,this._material=new dh("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._frustumLinesColor=i,this._material.diffuseColor=t??new Y(.5,.5,.5),this._material.specularColor=new Y(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._camera&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._camera))}),ss.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){if(this._camera=e,this.attachedNode=e,e){this._customMeshSet||(this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=Zp._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._cameraMesh.parent=this._rootMesh),this._cameraLinesMesh&&this._cameraLinesMesh.dispose();const t=this._frustumLinesColor?.toColor4(1)??new j(1,1,1,1);this._cameraLinesMesh=Zp._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene,t),this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;const i=this.gizmoLayer._getSharedGizmoLight();i.includedOnlyMeshes=i.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}}get camera(){return this._camera}get material(){return this._material}_update(){super._update(),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=e,this._cameraMesh.parent=this._rootMesh,this._customMeshSet=!0}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),super.dispose()}static _CreateCameraMesh(e){const t=new Un("rootCameraGizmo",e),i=new Un(t.name,e);i.parent=t,sc(t.name,{width:1,height:.8,depth:.5},e).parent=i;const s=Qh(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);s.parent=i,s.position.y=.3,s.position.x=-.6,s.rotation.x=.5*Math.PI;const r=Qh(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);r.parent=i,r.position.y=.5,r.position.x=.4,r.rotation.x=.5*Math.PI;const n=Qh(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return n.parent=i,n.position.y=0,n.position.x=.6,n.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(Zp._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e,t){const i=new Un("rootCameraGizmo",e),s=new Un(i.name,e);s.parent=i;for(let i=0;i<4;i+=2)for(let r=0;r<4;r+=2){let n=Tc("lines",{points:[new w(-1+r,-1+i,-1),new w(-1+r,-1+i,1)],colors:[t,t]},e);n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Tc("lines",{points:[new w(-1,-1+r,-1+i),new w(1,-1+r,-1+i)],colors:[t,t]},e),n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Tc("lines",{points:[new w(-1+r,-1,-1+i),new w(-1+r,1,-1+i)],colors:[t,t]},e),n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1}return i}}Zp._Scale=.05;Ft.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";Ft.IncludesShadersStore.packingFunctions="vec4 pack(float depth)\n{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}";Ft.IncludesShadersStore.kernelBlurFragment="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif\n";Ft.IncludesShadersStore.kernelBlurFragment2="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";Ft.ShadersStore.kernelBlurPixelShader="uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";Ft.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";Ft.ShadersStore.kernelBlurVertexShader="attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class Jp extends Ko{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,s,r,n=Zn.BILINEAR_SAMPLINGMODE,o,a,l=0,h="",c=!1,u=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],s,r,n,o,a,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,u),this._blockCompilation=c,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add((e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)})),this.kernel=i}updateEffect(e=null,t=null,i=null,s,r,n){this._updateParameters(r,n)}_updateParameters(e,t){const i=this._kernel,s=(i-1)/2;let r=[],n=[],o=0;for(let e=0;e0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){const t=1/3,i=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(i)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,s){return Pe.Parse((()=>new Jp(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)),e,i,s)}}ae([pe("kernel")],Jp.prototype,"_kernel",void 0),ae([pe("packedFloat")],Jp.prototype,"_packedFloat",void 0),ae([ge()],Jp.prototype,"direction",void 0),u("BABYLON.BlurPostProcess",Jp);class ef extends da{set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){const e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){const e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,s,r=0,n=Zn.BILINEAR_SAMPLINGMODE,o=!0){if(super(e,t,i,s,!0,r,!1,n,o),this.mirrorPlane=new Ps(0,1,0,1),this._transformMatrix=B.Zero(),this._mirrorMatrix=B.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateGammaSpace()}));const a=i.getEngine();let l;a.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add((()=>{a._debugPushGroup?.(`mirror generation for ${e}`,1)})),this.onAfterUnbindObservable.add((()=>{a._debugPopGroup?.(1)})),this.onBeforeRenderObservable.add((()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),B.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),l=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=w.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)})),this.onAfterRenderObservable.add((()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=l}))}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){const e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new Jp("horizontal blur",new N(1,0),this._blurKernelX,this._blurRatio,null,Zn.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new Jp("vertical blur",new N(0,1),this._blurKernelY,this._blurRatio,null,Zn.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new ef(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){super.dispose();const e=this.getScene();e&&e.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),this._sceneUBO?.dispose()}}Zn._CreateMirror=(e,t,i,s)=>new ef(e,t,i,s);class tf extends qn{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(B.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let s="";return e.forEach((e=>s+=e)),new tf(s,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,s=!0){const r=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const n=new tf(e,t,null,!1,null,null,null,void 0,!0,i,s);return t.useDelayedTextureLoading=r,n}constructor(e,t,i=null,s=!1,r=null,n=null,o=null,a=5,l=!1,h=null,c=!1,u=.8,d=0,p,f){super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new g,this.boundingBoxPosition=w.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new B,this.name=e,this.url=e,this._noMipmap=s,this.hasAlpha=!1,this._format=a,this.isCube=!0,this._textureMatrix=B.Identity(),this._createPolynomials=c,this.coordinatesMode=Zn.CUBIC_MODE,this._extensions=i,this._files=r,this._forcedExtension=h,this._loaderOptions=p,this._useSRGBBuffer=f,this._lodScale=u,this._lodOffset=d,(e||r)&&this.updateURL(e,h,n,l,o,i,this.getScene()?.useDelayedTextureLoading,r)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,s=!1,r=null,n=null,o=!1,a=null){this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,t&&(this._forcedExtension=t);const l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),c=0===h.indexOf(".dds"),u=0===h.indexOf(".env"),d=0===h.indexOf(".basis");if(u?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=s,s&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),a)this._files=a;else if(d||u||c||n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,n){for(let t=0;t-1!==e.getActiveTextures().indexOf(this))),this._textureMatrix=e,!this.getScene()?.useRightHandedSystem)return;const t=U.Vector3[0],i=U.Quaternion[0],s=U.Vector3[1];this._textureMatrix.decompose(t,i,s),i.z*=-1,i.w*=-1,B.ComposeToRef(t,i,s,this._textureMatrixRefraction)}getRefractionTextureMatrix(){return this.getScene()?.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){const i=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const r=()=>{this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),this.getScene()?.markAllMaterialsAsDirty(1)),e&&e()},n=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),Zn.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Ii.SetImmediate((()=>r())):this._texture.onLoadedObservable.add((()=>r())):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,i,this._lodScale,this._lodOffset,e,n,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,i,this._files,this._noMipmap,e,n,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),this._texture?.onLoadedObservable.add((()=>this.onLoadObservable.notifyObservers(this))))}static Parse(e,t,i){const s=Pe.Parse((()=>{let s=!1;return e.prefiltered&&(s=e.prefiltered),new tf(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(s.boundingBoxPosition=w.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=w.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t{const t=new tf(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}ae([pe()],tf.prototype,"url",void 0),ae([ve()],tf.prototype,"boundingBoxPosition",void 0),ae([ve()],tf.prototype,"boundingBoxSize",null),ae([pe("rotationY")],tf.prototype,"rotationY",null),ae([pe("files")],tf.prototype,"_files",void 0),ae([pe("forcedExtension")],tf.prototype,"_forcedExtension",void 0),ae([pe("extensions")],tf.prototype,"_extensions",void 0),ae([Ee("textureMatrix")],tf.prototype,"_textureMatrix",void 0),ae([Ee("textureMatrixRefraction")],tf.prototype,"_textureMatrixRefraction",void 0),Zn._CubeTextureParser=tf.Parse,u("BABYLON.CubeTexture",tf);Ft.IncludesShadersStore.backgroundFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;uniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef PROJECTED_GROUND\nuniform vec2 projectedGroundInfos;\n#endif\n";Ft.IncludesShadersStore.backgroundUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;};\n#include\n";Ft.ShadersStore.backgroundPixelShader="#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#include\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#ifdef PROJECTED_GROUND\nfloat diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; }\nvec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q)\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\nfloat shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.;\n#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n#ifndef BACKMAT_SHADOWONLY\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\n#ifdef PROJECTED_GROUND\nvec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.));\n#else\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);} else {reflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\nvec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor;\n#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\nvec4 color=vec4(finalColor,finalAlpha);\n#else\nvec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);\n#endif\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#endif\n#else\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Ft.IncludesShadersStore.backgroundVertexDeclaration="uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";Ft.ShadersStore.backgroundVertexShader="precision highp float;\n#include<__decl__backgroundVertex>\n#include\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vec2 vDiffuseUV;\n#endif\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif\n#include\n#include\n#include\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);}\n#else\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#endif\nvec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class sf extends Do{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.PROJECTED_GROUND=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}}class rf extends Io{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t*=2,this.reflectionReflectance0=rf.StandardReflectance0*t,this.reflectionReflectance90=rf.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=rf.StandardReflectance0+(1-rf.StandardReflectance0)*t,this.reflectionReflectance90=rf.StandardReflectance90+(1-rf.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()}))))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.primaryColor=Y.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=w.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._enableGroundProjection=!1,this.enableGroundProjection=!1,this.projectedGroundRadius=1e3,this.projectedGroundHeight=10,this._renderTargets=new Mi(16),this._reflectionControls=F.Zero(),this._white=Y.White(),this._primaryShadowColor=Y.Black(),this._primaryHighlightColor=Y.Black(),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!(!this._diffuseTexture||!this._diffuseTexture.isRenderTarget)||!(!this._reflectionTexture||!this._reflectionTexture.isRenderTarget)}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new sf);const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(vn(r,e,n,!1,this._maxSimultaneousLights),n._needNormals=!0,yn(r,n),n._areTexturesDirty){if(n._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(n.TEXTURELODSUPPORT=!0),this._diffuseTexture&&th.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;an(this._diffuseTexture,n,"DIFFUSE"),n.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,n.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,n.OPACITYFRESNEL=this._opacityFresnel}else n.DIFFUSE=!1,n.DIFFUSEDIRECTUV=0,n.DIFFUSEHASALPHA=!1,n.GAMMADIFFUSE=!1,n.OPACITYFRESNEL=!1;const e=this._reflectionTexture;if(e&&th.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(n.REFLECTION=!0,n.GAMMAREFLECTION=e.gammaSpace,n.RGBDREFLECTION=e.isRGBD,n.REFLECTIONBLUR=this._reflectionBlur>0,n.LODINREFLECTIONALPHA=e.lodLevelInAlpha,n.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,n.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===Zn.INVCUBIC_MODE&&(n.INVERTCUBICMAP=!0),n.REFLECTIONMAP_3D=e.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case Zn.EXPLICIT_MODE:n.REFLECTIONMAP_EXPLICIT=!0;break;case Zn.PLANAR_MODE:n.REFLECTIONMAP_PLANAR=!0;break;case Zn.PROJECTION_MODE:n.REFLECTIONMAP_PROJECTION=!0;break;case Zn.SKYBOX_MODE:n.REFLECTIONMAP_SKYBOX=!0;break;case Zn.SPHERICAL_MODE:n.REFLECTIONMAP_SPHERICAL=!0;break;case Zn.EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Zn.FIXED_EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Zn.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Zn.CUBIC_MODE:case Zn.INVCUBIC_MODE:default:n.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(n.REFLECTIONFRESNEL=!0,n.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1)}else n.REFLECTION=!1,n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1,n.REFLECTIONBLUR=!1,n.REFLECTIONMAP_3D=!1,n.REFLECTIONMAP_SPHERICAL=!1,n.REFLECTIONMAP_PLANAR=!1,n.REFLECTIONMAP_CUBIC=!1,n.REFLECTIONMAP_PROJECTION=!1,n.REFLECTIONMAP_SKYBOX=!1,n.REFLECTIONMAP_EXPLICIT=!1,n.REFLECTIONMAP_EQUIRECTANGULAR=!1,n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,n.INVERTCUBICMAP=!1,n.REFLECTIONMAP_OPPOSITEZ=!1,n.LODINREFLECTIONALPHA=!1,n.GAMMAREFLECTION=!1,n.RGBDREFLECTION=!1}n.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,n.USERGBCOLOR=this._useRGBColor,n.NOISE=this._enableNoise}if(n._areLightsDirty&&(n.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),n.BACKMAT_SHADOWONLY=this._shadowOnly),n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n)}if(n._areMiscDirty&&(n.REFLECTIONMAP_3D&&this._enableGroundProjection?(n.PROJECTED_GROUND=!0,n.REFLECTIONMAP_SKYBOX=!0):n.PROJECTED_GROUND=!1),gn(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),Tn(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),Cn(e,n,!1,!0,!1)&&e&&(r.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(Ki.NormalKind)||(e.createNormals(!0),J.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),n.isDirty){n.markAsProcessed(),r.resetCachedMaterial();const i=new Yo;n.FOG&&i.addFallback(0,"FOG"),n.POINTSIZE&&i.addFallback(1,"POINTSIZE"),n.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),_n(n,i,this._maxSimultaneousLights);const s=[Ki.PositionKind];n.NORMAL&&s.push(Ki.NormalKind),n.UV1&&s.push(Ki.UVKind),n.UV2&&s.push(Ki.UV2Kind),pn(s,e,n,i),fn(s,n);const a=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];jr(a);const l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];Bi&&(Bi.PrepareUniforms(a,n),Bi.PrepareSamplers(l,n)),Mn({uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:n,maxSimultaneousLights:this._maxSimultaneousLights});const c=n.toString(),u=r.getEngine().createEffect("background",{attributes:s,uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:c,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o);t.setEffect(u,n,this._materialContext),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady()||(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),cn(t,this._activeEffect);const o=this._mustRebind(s,n,i,t.visibility);if(o){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);const e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync&&!i._drawWrapper._forceRebindOnNextCall||(s.texturesEnabled&&(this._diffuseTexture&&th.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),ln(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&th.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),r.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),s.texturesEnabled&&(this._diffuseTexture&&th.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&th.ReflectionTextureEnabled&&(r.REFLECTIONBLUR&&r.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):r.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),r.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),r.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),Kr(this._activeEffect,this,s),s.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);!o&&this.isFrozen||(s.lightsEnabled&&dn(s,t,this._activeEffect,r,this._maxSimultaneousLights),this.bindView(n),en(s,t,this._activeEffect,!0),this._useLogarithmicDepth&&Jr(r,n,s),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return Pe.Clone((()=>new rf(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return Pe.Parse((()=>new rf(e.name,t)),e,t,i)}}rf.StandardReflectance0=.05,rf.StandardReflectance90=.5,ae([_e()],rf.prototype,"_primaryColor",void 0),ae([de("_markAllSubMeshesAsLightsDirty")],rf.prototype,"primaryColor",void 0),ae([_e()],rf.prototype,"__perceptualColor",void 0),ae([pe()],rf.prototype,"_primaryColorShadowLevel",void 0),ae([pe()],rf.prototype,"_primaryColorHighlightLevel",void 0),ae([de("_markAllSubMeshesAsLightsDirty")],rf.prototype,"primaryColorHighlightLevel",null),ae([fe()],rf.prototype,"_reflectionTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"reflectionTexture",void 0),ae([pe()],rf.prototype,"_reflectionBlur",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"reflectionBlur",void 0),ae([fe()],rf.prototype,"_diffuseTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"diffuseTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"shadowLights",void 0),ae([pe()],rf.prototype,"_shadowLevel",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"shadowLevel",void 0),ae([ve()],rf.prototype,"_sceneCenter",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"sceneCenter",void 0),ae([pe()],rf.prototype,"_opacityFresnel",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"opacityFresnel",void 0),ae([pe()],rf.prototype,"_reflectionFresnel",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"reflectionFresnel",void 0),ae([pe()],rf.prototype,"_reflectionFalloffDistance",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"reflectionFalloffDistance",void 0),ae([pe()],rf.prototype,"_reflectionAmount",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"reflectionAmount",void 0),ae([pe()],rf.prototype,"_reflectionReflectance0",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"reflectionReflectance0",void 0),ae([pe()],rf.prototype,"_reflectionReflectance90",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"reflectionReflectance90",void 0),ae([pe()],rf.prototype,"_useRGBColor",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"useRGBColor",void 0),ae([pe()],rf.prototype,"_enableNoise",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"enableNoise",void 0),ae([pe()],rf.prototype,"_maxSimultaneousLights",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"maxSimultaneousLights",void 0),ae([pe()],rf.prototype,"_shadowOnly",void 0),ae([de("_markAllSubMeshesAsLightsDirty")],rf.prototype,"shadowOnly",void 0),ae([Se()],rf.prototype,"_imageProcessingConfiguration",void 0),ae([pe(),de("_markAllSubMeshesAsMiscDirty")],rf.prototype,"enableGroundProjection",void 0),ae([pe()],rf.prototype,"projectedGroundRadius",void 0),ae([pe()],rf.prototype,"projectedGroundHeight",void 0),u("BABYLON.BackgroundMaterial",rf);class nf{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new Y(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new Y(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:w.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}constructor(e,t){this._errorHandler=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options={...nf._GetDefaultOptions(t),...e},this._scene=t,this.onErrorObservable=new g,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){const t={...this._options,...e};this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new j(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof qn)return void(this._scene.environmentTexture=this._options.environmentTexture);const e=tf.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new Un("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;const e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};const s=this._scene.getWorldExtends((e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox)),r=s.max.subtract(s.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof gl&&this._scene.activeCamera.upperRadiusLimit&&(e=2*this._scene.activeCamera.upperRadiusLimit,t=e);const n=r.length();n>e&&(e=2*n,t=e),e*=1.1,t*=1.5,i=s.min.add(r.scale(.5)),i.y=s.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){this._ground&&!this._ground.isDisposed()||(this._ground=co("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((()=>{this._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new rf("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){this._groundMaterial&&(this._groundTexture||(this._options.groundTexture instanceof qn?this._groundMaterial.diffuseTexture=this._options.groundTexture:(this._groundTexture=new Zn(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture)))}_setupGroundMirrorTexture(e){const t=Zn.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new ef("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,Zn.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new Ps(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e{this._skybox=null}))),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new rf("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){this._skyboxMaterial&&(this._skyboxTexture||(this._options.skyboxTexture instanceof qn?this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture:(this._skyboxTexture=new tf(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=Zn.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture)))}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}}nf._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",nf._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",nf._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class of extends Ur{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=Zn.CLAMP_ADDRESSMODE,this._texture.wrapV=Zn.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=Zn.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=Zn.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,s,r=null){super(e,s),this.onError=r,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=of.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new g,this.onLoadObservable=new g,s=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=Boolean(i.clickToPlay),i.autoPlay=void 0===i.autoPlay||Boolean(i.autoPlay),i.loop=void 0===i.loop||Boolean(i.loop),i.size=Math.abs(i.size)||(s.activeCamera?.48*s.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=nc(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:Un.BACKSIDE},s);const n=this._material=new rf(e+"_material",s);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;const o=this._initTexture(t,s,i);if(this.texture=o,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=nc("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:Un.BACKSIDE},s),this._halfDomeMask.rotate(Gs.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce((()=>{this._setReady(!0)})),i.faceForward&&s.activeCamera){const e=s.activeCamera,t=w.Forward(),i=w.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(w.Dot(t,i))}this._changeTextureMode(this._textureMode)}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case of.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case of.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;const e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((i=>{let s=i.isRightCamera;this._crossEye&&(s=!s),this._texture.uOffset=s?e:t}));break}case of.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0}))}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}}of.MODE_MONOSCOPIC=0,of.MODE_TOPBOTTOM=1,of.MODE_SIDEBYSIDE=2;class af extends of{get photoTexture(){return this.texture}set photoTexture(e){this.texture=e}get imageMode(){return this.textureMode}set imageMode(e){this.textureMode=e}_initTexture(e,t,i){return new Zn(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,(()=>{this.onLoadObservable.notifyObservers()}),((e,t)=>{this.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),this.onError&&this.onError(e,t)}))}}af.MODE_MONOSCOPIC=of.MODE_MONOSCOPIC,af.MODE_TOPBOTTOM=of.MODE_TOPBOTTOM,af.MODE_SIDEBYSIDE=of.MODE_SIDEBYSIDE;let lf=0;const hf=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const i=e._blockEntityCollection;e._blockEntityCollection=!1;const s=Zn.CreateFromBase64String("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==","EnvironmentBRDFTexture"+lf++,e,!0,!1,Zn.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;const r=e.getEngine().getLoadedTexturesCache(),n=r.indexOf(s.getInternalTexture());-1!==n&&r.splice(n,1),s.isRGBD=!0,s.wrapU=Zn.CLAMP_ADDRESSMODE,s.wrapV=Zn.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=s,e.useDelayedTextureLoading=t,mu.ExpandRGBDTexture(s);const o=e.getEngine().onContextRestoredObservable.add((()=>{s.isRGBD=!0;const t=e.onBeforeRenderObservable.add((()=>{s.isReady()&&(e.onBeforeRenderObservable.remove(t),mu.ExpandRGBDTexture(s))}))}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(o)}))}return e.environmentBRDFTexture};class cf extends Do{constructor(){super(...arguments),this.BRDF_V_HEIGHT_CORRELATED=!1,this.MS_BRDF_ENERGY_CONSERVATION=!1,this.SPHERICAL_HARMONICS=!1,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1}}class uf extends ah{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new cf,t),this._useEnergyConservation=uf.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=uf.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=uf.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=uf.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=uf.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=uf.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=uf.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=uf.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation}getClassName(){return"PBRBRDFConfiguration"}}uf.DEFAULT_USE_ENERGY_CONSERVATION=!0,uf.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,uf.DEFAULT_USE_SPHERICAL_HARMONICS=!0,uf.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,ae([pe(),de("_markAllSubMeshesAsMiscDirty")],uf.prototype,"useEnergyConservation",void 0),ae([pe(),de("_markAllSubMeshesAsMiscDirty")],uf.prototype,"useSmithVisibilityHeightCorrelated",void 0),ae([pe(),de("_markAllSubMeshesAsMiscDirty")],uf.prototype,"useSphericalHarmonics",void 0),ae([pe(),de("_markAllSubMeshesAsMiscDirty")],uf.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);Ft.IncludesShadersStore.pbrFragmentDeclaration="uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor;\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REALTIME_FILTERING\nuniform vec2 vReflectionFilteringInfo;\n#endif\nuniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams;\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#endif\n#ifdef IRIDESCENCE\nuniform vec4 vIridescenceParams;\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\nuniform vec4 vSheenColor;\n#ifdef SHEEN_ROUGHNESS\nuniform float vSheenRoughness;\n#endif\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;\n#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\n#endif\n#ifdef SS_DISPERSION\nuniform float dispersion;\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;\n#endif\nuniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity;uniform vec4 vTranslucencyColor;\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nuniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;\n#endif\n#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\n#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;\n#else\nuniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;\n#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";Ft.IncludesShadersStore.pbrUboDeclaration="layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";Ft.IncludesShadersStore.pbrFragmentExtraDeclaration="varying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#include[1..7]\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n";Ft.IncludesShadersStore.samplerFragmentAlternateDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n#endif\n";Ft.IncludesShadersStore.pbrFragmentSamplersDeclaration="#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform sampler2D clearCoatRoughnessSampler;\n#endif\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform sampler2D sheenRoughnessSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh;\n#endif\n#endif\n#endif\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)\n#endif\n";Ft.IncludesShadersStore.subSurfaceScatteringFunctions="bool testLightingForSSS(float diffusionProfile)\n{return diffusionProfile<1.;}";Ft.IncludesShadersStore.importanceSampling="vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { \nfloat phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}";Ft.IncludesShadersStore.pbrHelperFunctions="#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{return square(roughness)+MINIMUMVARIANCE;}\nfloat fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}\n#else\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;}\n#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);}\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);return clearCoatAbsorption;}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;}\n#endif\n";Ft.IncludesShadersStore.harmonicsFunctions="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nvec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00\n+ vSphericalL1_1*(normal.y)\n+ vSphericalL10*(normal.z)\n+ vSphericalL11*(normal.x)\n+ vSphericalL2_2*(normal.y*normal.x)\n+ vSphericalL2_1*(normal.y*normal.z)\n+ vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+ vSphericalL21*(normal.z*normal.x)\n+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}\n#else\nvec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;}\n#endif\n#endif\n";Ft.IncludesShadersStore.pbrDirectLightingSetupFunctions="struct preLightingInfo\n{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness;\n#ifdef IRIDESCENCE\nfloat iridescenceIntensity;\n#endif\n};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;}";Ft.IncludesShadersStore.pbrDirectLightingFalloffFunctions="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{return max(0.,1.0-length(lightOffset)/range);}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{return 1.0/maxEps(lightDistanceSquared);}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)\n{falloff=max(0.,pow(cosAngle,exponent));}\nreturn falloff;}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}";Ft.IncludesShadersStore.pbrBRDFFunctions="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;\n#endif\nreturn reflectance;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#endif\nreturn reflectance;}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfloat getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)\n{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\n/**\n* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.\n* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table\n*/\nvec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}\n#endif\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\n#ifdef CLEARCOAT\nvec3 getR0RemappedForClearCoat(vec3 f0) {\n#ifdef CLEARCOAT_DEFAULTIOR\n#ifdef MOBILE\nreturn saturate(f0*(f0*0.526868+0.529324)-0.0482256);\n#else\nreturn saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);\n#endif\n#else\nvec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t);\n#endif\n}\n#endif\n#ifdef IRIDESCENCE\nconst mat3 XYZ_TO_REC709=mat3(\n3.2404542,-0.9692660, 0.0556434,\n-1.5371385, 1.8760108,-0.2040259,\n-0.4985314, 0.0415560, 1.0572252\n);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}\nvec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));}\nfloat getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));}\nvec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;}\nvec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;}\nfloat cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose(),this._bumpTexture?.dispose(),this._tintTexture?.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}}pf._DefaultIndexOfRefraction=1.5,ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"isEnabled",void 0),ae([pe()],pf.prototype,"intensity",void 0),ae([pe()],pf.prototype,"roughness",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"indexOfRefraction",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"texture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"useRoughnessFromMainTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"textureRoughness",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"remapF0OnInterfaceChange",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"bumpTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"isTintEnabled",void 0),ae([_e()],pf.prototype,"tintColor",void 0),ae([pe()],pf.prototype,"tintColorAtDistance",void 0),ae([pe()],pf.prototype,"tintThickness",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"tintTexture",void 0);class ff extends Do{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0}}class _f extends ah{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new ff,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=_f._DefaultMinimumThickness,this.maximumThickness=_f._DefaultMaximumThickness,this.indexOfRefraction=_f._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&th.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&th.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&th.IridescenceTextureEnabled?an(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&th.IridescenceTextureEnabled?an(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||((this._texture||this._thicknessTexture)&&th.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._thicknessTexture?.coordinatesIndex??0,this._thicknessTexture?.level??0),this._texture&&ln(this._texture,e,"iridescence"),this._thicknessTexture&&ln(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&th.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&th.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){e&&(this._texture?.dispose(),this._thicknessTexture?.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}}_f._DefaultMinimumThickness=100,_f._DefaultMaximumThickness=400,_f._DefaultIndexOfRefraction=1.3,ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],_f.prototype,"isEnabled",void 0),ae([pe()],_f.prototype,"intensity",void 0),ae([pe()],_f.prototype,"minimumThickness",void 0),ae([pe()],_f.prototype,"maximumThickness",void 0),ae([pe()],_f.prototype,"indexOfRefraction",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],_f.prototype,"texture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],_f.prototype,"thicknessTexture",void 0);class mf extends Do{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class gf extends ah{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new mf,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new N(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&th.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(Ki.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&th.AnisotropicTextureEnabled?an(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1),e._areMiscDirty&&(e.ANISOTROPIC_LEGACY=this._legacy)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.ANISOTROPIC_LEGACY=!1)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&th.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),ln(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&th.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,i){super.parse(e,t,i),void 0===e.legacy&&(this.legacy=!0)}}ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],gf.prototype,"isEnabled",void 0),ae([pe()],gf.prototype,"intensity",void 0),ae([ge()],gf.prototype,"direction",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],gf.prototype,"texture",void 0),ae([pe(),de("_markAllSubMeshesAsMiscDirty")],gf.prototype,"legacy",void 0);class vf extends Do{constructor(){super(...arguments),this.SHEEN=!1,this.SHEEN_TEXTURE=!1,this.SHEEN_GAMMATEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS=!1,this.SHEEN_TEXTUREDIRECTUV=0,this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,this.SHEEN_LINKWITHALBEDO=!1,this.SHEEN_ROUGHNESS=!1,this.SHEEN_ALBEDOSCALING=!1,this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1}}class xf extends ah{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new vf,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=Y.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&th.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&th.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=null!==this._roughness,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&th.SheenTextureEnabled?(an(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&th.SheenTextureEnabled?an(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,s){if(!this._isEnabled)return;const r=s.materialDefines,n=this._material.isFrozen;e.useUbo&&n&&e.isSync||((this._texture||this._textureRoughness)&&th.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&ln(this._texture,e,"sheen"),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&ln(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),null!==this._roughness&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&th.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&th.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}}ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],xf.prototype,"isEnabled",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],xf.prototype,"linkSheenWithAlbedo",void 0),ae([pe()],xf.prototype,"intensity",void 0),ae([_e()],xf.prototype,"color",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],xf.prototype,"texture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],xf.prototype,"useRoughnessFromMainTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],xf.prototype,"roughness",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],xf.prototype,"textureRoughness",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],xf.prototype,"albedoScaling",void 0);class Tf extends Do{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_SCATTERING=!1,this.SS_DISPERSION=!1,this.SS_THICKNESSANDMASK_TEXTURE=!1,this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,this.SS_HAS_THICKNESS=!1,this.SS_REFRACTIONINTENSITY_TEXTURE=!1,this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,this.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0,this.SS_REFRACTIONMAP_3D=!1,this.SS_REFRACTIONMAP_OPPOSITEZ=!1,this.SS_LODINREFRACTIONALPHA=!1,this.SS_GAMMAREFRACTION=!1,this.SS_RGBDREFRACTION=!1,this.SS_LINEARSPECULARREFRACTION=!1,this.SS_LINKREFRACTIONTOTRANSPARENCY=!1,this.SS_ALBEDOFORREFRACTIONTINT=!1,this.SS_ALBEDOFORTRANSLUCENCYTINT=!1,this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.SS_USE_THICKNESS_AS_DEPTH=!1,this.SS_USE_GLTF_TEXTURES=!1}}class Sf extends ah{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){this._volumeIndexOfRefraction=e>=1?e:-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new Tf,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isDispersionEnabled=!1,this.isDispersionEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this.useAlbedoToTintRefraction=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=Y.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=Y.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this.translucencyColor=null,this._translucencyColorTexture=null,this.translucencyColorTexture=null,this._useGltfStyleTextures=!0,this.useGltfStyleTextures=!0,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&th.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;if(this._translucencyColorTexture&&th.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&th.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return e.SUBSURFACE=!1,e.SS_DISPERSION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,void(e.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0);if(e._areTexturesDirty){if(e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&th.ThicknessTextureEnabled&&an(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&th.RefractionIntensityTextureEnabled&&an(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&th.TranslucencyIntensityTextureEnabled&&an(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&&th.TranslucencyColorTextureEnabled&&an(this._translucencyColorTexture,e,"SS_TRANSLUCENCYCOLOR_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._refractionIntensityTexture,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._translucencyIntensityTexture,this._isRefractionEnabled&&t.texturesEnabled){const i=this._getRefractionTexture(t);i&&th.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;s.getRenderingMesh().getWorldMatrix().decompose(U.Vector3[0]);const r=Math.max(Math.abs(U.Vector3[0].x),Math.abs(U.Vector3[0].y),Math.abs(U.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*r,(this.maximumThickness-this.minimumThickness)*r)}bindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const r=s.materialDefines,n=this._material.isFrozen,o=this._material.realTimeFiltering,a=r.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&th.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),ln(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&th.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),ln(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&&th.TranslucencyColorTextureEnabled&&r.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),ln(this._translucencyColorTexture,e,"translucencyColor")),l&&th.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;l.isCube||l.depth&&(t=l.depth);const i=l.getSize().width,s=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",l.level,1/s,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",i,G.Log2(i)),l.boundingBoxSize){const t=l;e.updateVector3("vRefractionPosition",t.boundingBoxPosition),e.updateVector3("vRefractionSize",t.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateColor4("vTranslucencyColor",this.translucencyColor??this.tintColor,0),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&th.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&th.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&th.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&&th.TranslucencyColorTextureEnabled&&r.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),l&&th.RefractionTextureEnabled&&(a?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){th.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e||this._refractionIntensityTexture===e||this._translucencyIntensityTexture===e||this._translucencyColorTexture===e}hasRenderTargetTextures(){return!!(th.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture),this._translucencyColorTexture&&e.push(this._translucencyColorTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),this._translucencyColorTexture&&this._translucencyColorTexture.animations&&this._translucencyColorTexture.animations.length>0&&e.push(this._translucencyColorTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose(),this._translucencyColorTexture&&this._translucencyColorTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","translucencyColorSampler")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"},{name:"vTranslucencyColor",size:4,type:"vec4"},{name:"vTranslucencyColorInfos",size:2,type:"vec2"},{name:"translucencyColorMatrix",size:16,type:"mat4"}]}}}ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"isRefractionEnabled",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"isTranslucencyEnabled",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"isDispersionEnabled",void 0),ae([pe(),de("_markScenePrePassDirty")],Sf.prototype,"isScatteringEnabled",void 0),ae([pe()],Sf.prototype,"_scatteringDiffusionProfileIndex",void 0),ae([pe()],Sf.prototype,"refractionIntensity",void 0),ae([pe()],Sf.prototype,"translucencyIntensity",void 0),ae([pe()],Sf.prototype,"useAlbedoToTintRefraction",void 0),ae([pe()],Sf.prototype,"useAlbedoToTintTranslucency",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"thicknessTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"refractionTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"indexOfRefraction",void 0),ae([pe()],Sf.prototype,"_volumeIndexOfRefraction",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"volumeIndexOfRefraction",null),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"invertRefractionY",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"linkRefractionWithTransparency",void 0),ae([pe()],Sf.prototype,"minimumThickness",void 0),ae([pe()],Sf.prototype,"maximumThickness",void 0),ae([pe()],Sf.prototype,"useThicknessAsDepth",void 0),ae([_e()],Sf.prototype,"tintColor",void 0),ae([pe()],Sf.prototype,"tintColorAtDistance",void 0),ae([pe()],Sf.prototype,"dispersion",void 0),ae([_e()],Sf.prototype,"diffusionDistance",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"useMaskFromThicknessTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"refractionIntensityTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"translucencyIntensityTexture",void 0),ae([_e()],Sf.prototype,"translucencyColor",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"translucencyColorTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"useGltfStyleTextures",void 0);const Ef={effect:null,subMesh:null};class bf extends Do{constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class Cf extends Io{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new F(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=Cf.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._reflectivityTexture=null,this._metallicTexture=null,this._metallic=null,this._roughness=null,this._metallicF0Factor=1,this._metallicReflectanceColor=Y.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new Y(0,0,0),this._albedoColor=new Y(1,1,1),this._reflectivityColor=new Y(1,1,1),this._reflectionColor=new Y(1,1,1),this._emissiveColor=new Y(0,0,0),this._microSurface=.9,this._useLightmapAsShadowmap=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromAlbedoTexture=!1,this._useSpecularOverAlpha=!0,this._useMicroSurfaceFromReflectivityMapAlpha=!1,this._useRoughnessFromMetallicTextureAlpha=!0,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallnessFromMetallicTextureBlue=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useAmbientInGrayScale=!1,this._useAutoMicroSurfaceFromReflectivityMap=!1,this._lightFalloff=Cf.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._forceAlphaTest=!1,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new Mi(16),this._globalAmbientColor=new Y(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new uf(this),this.clearCoat=new pf(this),this.iridescence=new _f(this),this.anisotropy=new gf(this),this.sheen=new xf(this),this.subSurface=new Sf(this),this.detailMap=new hh(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),th.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=hf(this.getScene()),this.prePassConfiguration=new eh}get hasRenderTargetTextures(){return!!(th.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){return this._transparencyMode===Cf.PBRMATERIAL_OPAQUE||this._transparencyMode===Cf.PBRMATERIAL_ALPHATEST||this.subSurface?.disableAlphaBlending}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){return!!this._forceAlphaTest||!this.subSurface?.disableAlphaBlending&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Cf.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==Cf.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Xr.GetDefineNames,this._eventInfo),t.materialDefines=new bf(this._eventInfo.defineNames));const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=this.getScene(),o=n.getEngine();if(r._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&th.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&th.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&th.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&th.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&e.getInternalTexture()?._sphericalPolynomialPromise)return!1}if(this._lightmapTexture&&th.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&th.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(th.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking())return!1;if(this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&th.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&th.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(r._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;o.getCaps().standardDerivatives||e.isVerticesDataPresent(Ki.NormalKind)||(e.createNormals(!0),J.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const a=t.effect,l=r._areLightsDisposed;let h=this._prepareEffect(e,r,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),c=!1;if(h)if(this._onEffectCreatedObservable&&(Ef.effect=h,Ef.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Ef)),this.allowShaderHotSwapping&&a&&!h.isReady()){if(h=a,r.markAsUnprocessed(),c=this.isFrozen,l)return r._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(h,r,this._materialContext);return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!c,s._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),0))}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,i=null,s=null,r=null,n=null,o){if(this._prepareDefines(e,t,r,n,o),!t.isDirty)return null;t.markAsProcessed();const a=this.getScene().getEngine(),l=new Yo;let h=0;t.USESPHERICALINVERTEX&&l.addFallback(h++,"USESPHERICALINVERTEX"),t.FOG&&l.addFallback(h,"FOG"),t.SPECULARAA&&l.addFallback(h,"SPECULARAA"),t.POINTSIZE&&l.addFallback(h,"POINTSIZE"),t.LOGARITHMICDEPTH&&l.addFallback(h,"LOGARITHMICDEPTH"),t.PARALLAX&&l.addFallback(h,"PARALLAX"),t.PARALLAX_RHS&&l.addFallback(h,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&l.addFallback(h++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&l.addFallback(h++,"ENVIRONMENTBRDF"),t.TANGENT&&l.addFallback(h++,"TANGENT"),t.BUMP&&l.addFallback(h++,"BUMP"),h=_n(t,l,this._maxSimultaneousLights,h++),t.SPECULARTERM&&l.addFallback(h++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&l.addFallback(h++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&l.addFallback(h++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&l.addFallback(h++,"LIGHTMAP"),t.NORMAL&&l.addFallback(h++,"NORMAL"),t.AMBIENT&&l.addFallback(h++,"AMBIENT"),t.EMISSIVE&&l.addFallback(h++,"EMISSIVE"),t.VERTEXCOLOR&&l.addFallback(h++,"VERTEXCOLOR"),t.MORPHTARGETS&&l.addFallback(h++,"MORPHTARGETS"),t.MULTIVIEW&&l.addFallback(0,"MULTIVIEW");const c=[Ki.PositionKind];t.NORMAL&&c.push(Ki.NormalKind),t.TANGENT&&c.push(Ki.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&c.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&c.push(Ki.ColorKind),pn(c,e,t,l),fn(c,t),sn(c,e,t),hn(c,0,t);let u="pbr";const d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],p=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],f=["Material","Scene","Mesh"],_={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=l,this._eventInfo.fallbackRank=h,this._eventInfo.defines=t,this._eventInfo.uniforms=d,this._eventInfo.attributes=c,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=f,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=_,this._callbackPluginEventGeneric(Xr.PrepareEffect,this._eventInfo),eh.AddUniforms(d),eh.AddSamplers(p),jr(d),Bi&&(Bi.PrepareUniforms(d,t),Bi.PrepareSamplers(p,t)),Mn({uniformsNames:d,uniformBuffersNames:f,samplers:p,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const m={};this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,d,f,p,t,c,m));const g=t.toString(),v=a.createEffect(u,{attributes:c,uniformsNames:d,uniformBuffersNames:f,samplers:p,defines:g,fallbacks:l,onCompiled:i,onError:s,indexParameters:_,processFinalCode:m.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},a);return this._eventInfo.customCode=void 0,v}_prepareDefines(e,t,i=null,s=null,r=!1){const n=this.getScene(),o=n.getEngine();vn(n,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,yn(n,t);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Rn(n,t,this.canRenderToMRT&&!a),An(n,t,a),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!1;if(n.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&th.DiffuseTextureEnabled?(an(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&th.AmbientTextureEnabled?(an(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&th.OpacityTextureEnabled?(an(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&th.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(t.NUM_SAMPLES=""+this.realTimeFilteringQuality,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===Zn.INVCUBIC_MODE,t.REFLECTIONMAP_3D=e.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.coordinatesMode){case Zn.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case Zn.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case Zn.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case Zn.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case Zn.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case Zn.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Zn.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Zn.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Zn.CUBIC_MODE:case Zn.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==Zn.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||o.getCaps().maxVaryingVectors<=8?t.USESPHERICALINVERTEX=!1:t.USESPHERICALINVERTEX=!0))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;this._lightmapTexture&&th.LightmapTextureEnabled?(an(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&th.EmissiveTextureEnabled?(an(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,th.SpecularTextureEnabled?(this._metallicTexture?(an(this._metallicTexture,t,"REFLECTIVITY"),t.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,t.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,t.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,t.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,t.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(an(this._reflectivityTexture,t,"REFLECTIVITY"),t.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,t.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,t.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):t.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture?(t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture,this._metallicReflectanceTexture?(an(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(an(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1):(t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1),this._microSurfaceTexture?an(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1):(t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1),o.getCaps().standardDerivatives&&this._bumpTexture&&th.BumpTextureEnabled&&!this._disableBumpMap?(an(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&th.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=n.useRightHandedSystem,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAX_RHS=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&th.ReflectionTextureEnabled?(t.ENVIRONMENTBRDF=!0,t.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(t.ENVIRONMENTBRDF=!1,t.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?t.ALPHAFROMALBEDO=!0:t.ALPHAFROMALBEDO=!1}t.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===Cf.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Cf.LIGHTFALLOFF_GLTF?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!0):(t.USEPHYSICALLIGHTFALLOFF=!0,t.USEGLTFLIGHTFALLOFF=!1),t.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?t.TWOSIDEDLIGHTING=!0:t.TWOSIDEDLIGHTING=!1,t.SPECULARAA=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(gn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(Ki.NormalKind),t.DEBUGMODE=this._debugMode),Tn(n,o,this,t,!!i,s,r),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),Cn(e,t,!0,!0,!0,this._transparencyMode!==Cf.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const s={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(Xr.GetDefineNames,this._eventInfo);const r=new bf(this._eventInfo.defineNames),n=this._prepareEffect(e,r,void 0,void 0,s.useInstances,s.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(Ef.effect=n,Ef.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Ef)),n.isReady()?t&&t(this):n.onCompileObservable.add((()=>{t&&t(this)}))}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionFilteringInfo",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("reflectionMatrix",16),e.addUniform("vReflectionColor",3),e.addUniform("vAlbedoColor",4),e.addUniform("vLightingIntensity",4),e.addUniform("vReflectionMicrosurfaceInfos",3),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),e.addUniform("vSphericalL00",3),e.addUniform("vSphericalL1_1",3),e.addUniform("vSphericalL10",3),e.addUniform("vSphericalL11",3),e.addUniform("vSphericalL2_2",3),e.addUniform("vSphericalL2_1",3),e.addUniform("vSphericalL20",3),e.addUniform("vSphericalL21",3),e.addUniform("vSphericalL22",3),e.addUniform("vSphericalX",3),e.addUniform("vSphericalY",3),e.addUniform("vSphericalZ",3),e.addUniform("vSphericalXX_ZZ",3),e.addUniform("vSphericalYY_ZZ",3),e.addUniform("vSphericalZZ",3),e.addUniform("vSphericalXY",3),e.addUniform("vSphericalYZ",3),e.addUniform("vSphericalZX",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e);const o=s.getEngine();this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const a=this._mustRebind(s,n,i,t.visibility);cn(t,this._activeEffect,this.prePassConfiguration);let l=null;const h=this._uniformBuffer;if(a){if(this.bindViewProjection(n),l=this._getReflectionTexture(),!h.useUbo||!this.isFrozen||!h.isSync||i._drawWrapper._forceRebindOnNextCall){if(s.texturesEnabled){if(this._albedoTexture&&th.DiffuseTextureEnabled&&(h.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),ln(this._albedoTexture,h,"albedo")),this._ambientTexture&&th.AmbientTextureEnabled&&(h.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),ln(this._ambientTexture,h,"ambient")),this._opacityTexture&&th.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),ln(this._opacityTexture,h,"opacity")),l&&th.ReflectionTextureEnabled){if(h.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),h.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){const e=l;h.updateVector3("vReflectionPosition",e.boundingBoxPosition),h.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=l.getSize().width;h.updateFloat2("vReflectionFilteringInfo",e,G.Log2(e))}if(!r.USEIRRADIANCEMAP){const e=l.sphericalPolynomial;if(r.USESPHERICALFROMREFLECTIONMAP&&e)if(r.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;h.updateVector3("vSphericalL00",t.l00),h.updateVector3("vSphericalL1_1",t.l1_1),h.updateVector3("vSphericalL10",t.l10),h.updateVector3("vSphericalL11",t.l11),h.updateVector3("vSphericalL2_2",t.l2_2),h.updateVector3("vSphericalL2_1",t.l2_1),h.updateVector3("vSphericalL20",t.l20),h.updateVector3("vSphericalL21",t.l21),h.updateVector3("vSphericalL22",t.l22)}else h.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),h.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),h.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),h.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),h.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),h.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),h.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),h.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),h.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}h.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}this._emissiveTexture&&th.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),ln(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&th.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),ln(this._lightmapTexture,h,"lightmap")),th.SpecularTextureEnabled&&(this._metallicTexture?(h.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),ln(this._metallicTexture,h,"reflectivity")):this._reflectivityTexture&&(h.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),ln(this._reflectivityTexture,h,"reflectivity")),this._metallicReflectanceTexture&&(h.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),ln(this._metallicReflectanceTexture,h,"metallicReflectance")),this._reflectanceTexture&&r.REFLECTANCE&&(h.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),ln(this._reflectanceTexture,h,"reflectance")),this._microSurfaceTexture&&(h.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),ln(this._microSurfaceTexture,h,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&&th.BumpTextureEnabled&&!this._disableBumpMap&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),ln(this._bumpTexture,h,"bump"),s._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),r.METALLICWORKFLOW){$.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,$.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,h.updateColor4("vReflectivityColor",$.Color3[0],1);const e=this.subSurface?._indexOfRefraction??1.5,t=1,i=Math.pow((e-t)/(e+t),2);this._metallicReflectanceColor.scaleToRef(i*this._metallicF0Factor,$.Color3[0]);const s=this._metallicF0Factor;h.updateColor4("vMetallicReflectanceFactors",$.Color3[0],s)}else h.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);h.updateColor3("vEmissiveColor",th.EmissiveTextureEnabled?this._emissiveColor:Y.BlackReadOnly),h.updateColor3("vReflectionColor",this._reflectionColor),!r.SS_REFRACTION&&this.subSurface?._linkRefractionWithTransparency?h.updateColor4("vAlbedoColor",this._albedoColor,1):h.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*s.environmentIntensity,this._lightingInfos.w=this._specularIntensity,h.updateVector4("vLightingIntensity",this._lightingInfos),s.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor),h.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}s.texturesEnabled&&(this._albedoTexture&&th.DiffuseTextureEnabled&&h.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&th.AmbientTextureEnabled&&h.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&th.OpacityTextureEnabled&&h.setTexture("opacitySampler",this._opacityTexture),l&&th.ReflectionTextureEnabled&&(r.LODBASEDMICROSFURACE?h.setTexture("reflectionSampler",l):(h.setTexture("reflectionSampler",l._lodTextureMid||l),h.setTexture("reflectionSamplerLow",l._lodTextureLow||l),h.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)),r.USEIRRADIANCEMAP&&h.setTexture("irradianceSampler",l.irradianceTexture)),r.ENVIRONMENTBRDF&&h.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&th.EmissiveTextureEnabled&&h.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&th.LightmapTextureEnabled&&h.setTexture("lightmapSampler",this._lightmapTexture),th.SpecularTextureEnabled&&(this._metallicTexture?h.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&h.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&h.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&r.REFLECTANCE&&h.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&h.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&&th.BumpTextureEnabled&&!this._disableBumpMap&&h.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Kr(this._activeEffect,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!a&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&dn(s,t,this._activeEffect,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==ks.FOGMODE_NONE||l||this.subSurface.refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),en(s,t,this._activeEffect,!0),r.NUM_MORPH_INFLUENCERS&&nn(t,this._activeEffect),r.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,r.INSTANCES),this._imageProcessingConfiguration.bind(this._activeEffect),Jr(r,this._activeEffect,s)),this._afterBind(t,this._activeEffect,i),h.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._albedoTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e}setPrePassRenderer(){if(!this.subSurface?.isScatteringEnabled)return!1;const e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._albedoTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._metallicTexture?.dispose(),this._reflectivityTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._metallicReflectanceTexture?.dispose(),this._reflectanceTexture?.dispose(),this._microSurfaceTexture?.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}Cf.PBRMATERIAL_OPAQUE=Dn.MATERIAL_OPAQUE,Cf.PBRMATERIAL_ALPHATEST=Dn.MATERIAL_ALPHATEST,Cf.PBRMATERIAL_ALPHABLEND=Dn.MATERIAL_ALPHABLEND,Cf.PBRMATERIAL_ALPHATESTANDBLEND=Dn.MATERIAL_ALPHATESTANDBLEND,Cf.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,Cf.LIGHTFALLOFF_PHYSICAL=0,Cf.LIGHTFALLOFF_GLTF=1,Cf.LIGHTFALLOFF_STANDARD=2,ae([Se()],Cf.prototype,"_imageProcessingConfiguration",void 0),ae([de("_markAllSubMeshesAsMiscDirty")],Cf.prototype,"debugMode",void 0);class yf extends Cf{get refractionTexture(){return this.subSurface.refractionTexture}set refractionTexture(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)}get indexOfRefraction(){return this.subSurface.indexOfRefraction}set indexOfRefraction(e){this.subSurface.indexOfRefraction=e}get invertRefractionY(){return this.subSurface.invertRefractionY}set invertRefractionY(e){this.subSurface.invertRefractionY=e}get linkRefractionWithTransparency(){return this.subSurface.linkRefractionWithTransparency}set linkRefractionWithTransparency(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)}get usePhysicalLightFalloff(){return this._lightFalloff===Cf.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Cf.LIGHTFALLOFF_PHYSICAL:Cf.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Cf.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Cf.LIGHTFALLOFF_GLTF:Cf.LIGHTFALLOFF_STANDARD)}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=yf.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=Y.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new Y(0,0,0),this.albedoColor=new Y(1,1,1),this.reflectivityColor=new Y(1,1,1),this.reflectionColor=new Y(1,1,1),this.emissiveColor=new Y(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=hf(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const s=Pe.Clone((()=>new yf(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return s.id=e,s.name=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const s=Pe.Parse((()=>new yf(e.name,t)),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),Dn._ParsePlugins(e,s,t,i),e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}yf.PBRMATERIAL_OPAQUE=Cf.PBRMATERIAL_OPAQUE,yf.PBRMATERIAL_ALPHATEST=Cf.PBRMATERIAL_ALPHATEST,yf.PBRMATERIAL_ALPHABLEND=Cf.PBRMATERIAL_ALPHABLEND,yf.PBRMATERIAL_ALPHATESTANDBLEND=Cf.PBRMATERIAL_ALPHATESTANDBLEND,yf.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Cf.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"directIntensity",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"emissiveIntensity",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"environmentIntensity",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"specularIntensity",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"disableBumpMap",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"albedoTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"ambientTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"ambientTextureStrength",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesAndMiscDirty")],yf.prototype,"opacityTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"reflectionTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"emissiveTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"reflectivityTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"metallicTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"metallic",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"roughness",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"metallicF0Factor",void 0),ae([_e(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"metallicReflectanceColor",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"metallicReflectanceTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"reflectanceTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"microSurfaceTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"bumpTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty",null)],yf.prototype,"lightmapTexture",void 0),ae([_e("ambient"),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"ambientColor",void 0),ae([_e("albedo"),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"albedoColor",void 0),ae([_e("reflectivity"),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"reflectivityColor",void 0),ae([_e("reflection"),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"reflectionColor",void 0),ae([_e("emissive"),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"emissiveColor",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"microSurface",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useLightmapAsShadowmap",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesAndMiscDirty")],yf.prototype,"useAlphaFromAlbedoTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesAndMiscDirty")],yf.prototype,"forceAlphaTest",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesAndMiscDirty")],yf.prototype,"alphaCutOff",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useSpecularOverAlpha",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useRoughnessFromMetallicTextureGreen",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useMetallnessFromMetallicTextureBlue",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useAmbientInGrayScale",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),ae([pe()],yf.prototype,"usePhysicalLightFalloff",null),ae([pe()],yf.prototype,"useGLTFLightFalloff",null),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useRadianceOverAlpha",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useObjectSpaceNormalMap",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useParallax",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useParallaxOcclusion",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"parallaxScaleBias",void 0),ae([pe(),de("_markAllSubMeshesAsLightsDirty")],yf.prototype,"disableLighting",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"forceIrradianceInFragment",void 0),ae([pe(),de("_markAllSubMeshesAsLightsDirty")],yf.prototype,"maxSimultaneousLights",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"invertNormalMapX",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"invertNormalMapY",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"twoSidedLighting",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useAlphaFresnel",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useLinearAlphaFresnel",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"environmentBRDFTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"forceNormalForward",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"enableSpecularAntiAliasing",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useHorizonOcclusion",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useRadianceOcclusion",void 0),ae([pe(),de("_markAllSubMeshesAsMiscDirty")],yf.prototype,"unlit",void 0),ae([pe(),de("_markAllSubMeshesAsMiscDirty")],yf.prototype,"applyDecalMapAfterDetailMap",void 0),u("BABYLON.PBRMaterial",yf),Br._TextureLoaders.push(new class{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,s){const r=t.getEngine();let n,o=!1,a=1e3;if(Array.isArray(e))for(let i=0;i1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),pu.UploadDDSLevels(r,t,s,n,o,6,-1,i),n.isFourCC||1!==n.mipmapCount?a=n.mipmapCount-1:r.generateMipMapsForCubemap(t)}else{const s=e;n=pu.GetDDSInfo(s),t.width=n.width,t.height=n.height,i&&(n.sphericalPolynomial=new Qc),o=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),pu.UploadDDSLevels(r,t,s,n,o,6),n.isFourCC||1!==n.mipmapCount?a=n.mipmapCount-1:r.generateMipMapsForCubemap(t,!1)}r._setCubeMapTextureParams(t,o,a),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s({isDDS:!0,width:t.width,info:n,data:e,texture:t})}loadData(e,t,i){const s=pu.GetDDSInfo(e),r=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps&&s.width>>s.mipmapCount-1==1;i(s.width,s.height,r,s.isFourCC,(()=>{pu.UploadDDSLevels(t.getEngine(),t,e,s,r,1)}))}}),Br._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=Tu(e);if(n){t.width=n.width,t.height=n.width;try{yu(t,n),bu(t,e,n).then((()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}),(e=>{r?.("Can not upload environment levels",e)}))}catch(e){r?.("Can not upload environment file",e)}}else r&&r("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}});class Af{constructor(e,t){if(this.data=e,this.isInvalid=!1,!Af.IsValid(e))return this.isInvalid=!0,void J.Error("texture missing KTX identifier");const i=Uint32Array.BYTES_PER_ELEMENT,s=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),r=67305985===s.getUint32(0,!0);return this.glType=s.getUint32(1*i,r),this.glTypeSize=s.getUint32(2*i,r),this.glFormat=s.getUint32(3*i,r),this.glInternalFormat=s.getUint32(4*i,r),this.glBaseInternalFormat=s.getUint32(5*i,r),this.pixelWidth=s.getUint32(6*i,r),this.pixelHeight=s.getUint32(7*i,r),this.pixelDepth=s.getUint32(8*i,r),this.numberOfArrayElements=s.getUint32(9*i,r),this.numberOfFaces=s.getUint32(10*i,r),this.numberOfMipmapLevels=s.getUint32(11*i,r),this.bytesOfKeyValueData=s.getUint32(12*i,r),0!==this.glType?(J.Error("only compressed formats currently supported"),void(this.isInvalid=!0)):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?(J.Error("only 2D textures currently supported"),void(this.isInvalid=!0)):0!==this.numberOfArrayElements?(J.Error("texture arrays not currently supported"),void(this.isInvalid=!0)):this.numberOfFaces!==t?(J.Error("number of faces expected"+t+", but found "+this.numberOfFaces),void(this.isInvalid=!0)):void(this.loadType=Af.COMPRESSED_2D))}uploadLevels(e,t){switch(this.loadType){case Af.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case Af.TEX_2D:case Af.COMPRESSED_3D:case Af.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=Af.HEADER_LEN+this.bytesOfKeyValueData,s=this.pixelWidth,r=this.pixelHeight;const n=t?this.numberOfMipmapLevels:1;for(let t=0;t=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}Af.HEADER_LEN=64,Af.COMPRESSED_2D=0,Af.COMPRESSED_3D=1,Af.TEX_2D=2,Af.TEX_3D=3;class Rf{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map((e=>({workerPromise:Promise.resolve(e),idle:!0})))}dispose(){for(const e of this._workerInfos)e.workerPromise.then((e=>{e.terminate()}));this._workerInfos.length=0,this._pendingActions.length=0}push(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)}_executeOnIdleWorker(e){for(const t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then((i=>{t(i,(()=>{const t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0}))}))}}class If extends Rf{constructor(e,t,i=If.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,(()=>{s(),e.idle&&(e.timeoutId=setTimeout((()=>{e.workerPromise.then((e=>{e.terminate()}));const t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)}),this._options.idleTimeElapsedBeforeRelease))}))}))}}var Pf,Mf,Df;function Of(e,t){const i=t?.jsDecoderModule||KTX2DECODER;e&&(e.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(i.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(i.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)),t&&(t.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmBinary=t.wasmUASTCToASTC),t.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmBinary=t.wasmUASTCToBC7),t.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary=t.wasmUASTCToRGBA_UNORM),t.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary=t.wasmUASTCToRGBA_SRGB),t.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmBinary=t.wasmUASTCToR8_UNORM),t.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary=t.wasmUASTCToRG8_UNORM),t.jsMSCTranscoder&&(i.MSCTranscoder.JSModule=t.jsMSCTranscoder),t.wasmMSCTranscoder&&(i.MSCTranscoder.WasmBinary=t.wasmMSCTranscoder),t.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmBinary=t.wasmZSTDDecoder))}function Nf(e){let t;void 0===e&&"undefined"!=typeof KTX2DECODER&&(e=KTX2DECODER),onmessage=i=>{if(i.data)switch(i.data.action){case"init":{const s=i.data.urls;s&&(s.jsDecoderModule&&void 0===e&&(importScripts(s.jsDecoderModule),e=KTX2DECODER),Of(s)),i.data.wasmBinaries&&Of(void 0,{...i.data.wasmBinaries,jsDecoderModule:e}),t=new e.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":e.KTX2Decoder.DefaultDecoderOptions=i.data.options;break;case"decode":t.decode(i.data.data,i.data.caps,i.data.options).then((e=>{const t=[];for(let i=0;i{postMessage({action:"decoded",success:!1,msg:e})}))}}}If.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(Pf||(Pf={})),function(e){e[e.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",e[e.BC7_RGBA=1]="BC7_RGBA",e[e.BC3_RGBA=2]="BC3_RGBA",e[e.BC1_RGB=3]="BC1_RGB",e[e.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",e[e.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",e[e.ETC2_RGBA=6]="ETC2_RGBA",e[e.ETC1_RGB=7]="ETC1_RGB",e[e.RGBA32=8]="RGBA32",e[e.R8=9]="R8",e[e.RG8=10]="RG8"}(Mf||(Mf={})),function(e){e[e.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",e[e.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",e[e.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",e[e.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",e[e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",e[e.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",e[e.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",e[e.RGBA8Format=32856]="RGBA8Format",e[e.R8Format=33321]="R8Format",e[e.RG8Format=33323]="RG8Format"}(Df||(Df={}));class wf{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(wf._WorkerPoolPromise||wf._DecoderModulePromise)return;const t={jsDecoderModule:Ii.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:Ii.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:Ii.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:Ii.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:Ii.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:Ii.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:Ii.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:Ii.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:Ii.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:Ii.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?wf._WorkerPoolPromise=new Promise((i=>{const s=`${Of}(${Nf})()`,r=URL.createObjectURL(new Blob([s],{type:"application/javascript"}));i(new If(e,(()=>function(e,t,i){return new Promise(((t,s)=>{const r=t=>{e.removeEventListener("error",r),e.removeEventListener("message",n),s(t)},n=i=>{"init"===i.data.action&&(e.removeEventListener("error",r),e.removeEventListener("message",n),t(e))};e.addEventListener("error",r),e.addEventListener("message",n),e.postMessage({action:"init",urls:i,wasmBinaries:undefined})}))}(new Worker(r),0,t))))})):void 0===wf._KTX2DecoderModule?wf._DecoderModulePromise=Ii.LoadBabylonScriptAsync(t.jsDecoderModule).then((()=>(wf._KTX2DecoderModule=KTX2DECODER,wf._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,wf._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,Of(t,wf._KTX2DecoderModule),new wf._KTX2DecoderModule.KTX2Decoder))):(wf._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,wf._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,wf._DecoderModulePromise=Promise.resolve(new wf._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=wf.DefaultNumWorkers){this._engine=e;const i="object"==typeof t&&t.workerPool||wf.WorkerPool;if(i)wf._WorkerPoolPromise=Promise.resolve(i);else{"object"==typeof t?wf._KTX2DecoderModule=t?.binariesAndModulesContainer?.jsDecoderModule:"undefined"!=typeof KTX2DECODER&&(wf._KTX2DecoderModule=KTX2DECODER);const e="number"==typeof t?t:t.numWorkers??wf.DefaultNumWorkers;wf._Initialize(e)}}_uploadAsync(e,t,i){const s=this._engine.getCaps(),r={astc:!!s.astc,bptc:!!s.bptc,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,etc1:!!s.etc1};if(wf._WorkerPoolPromise)return wf._WorkerPoolPromise.then((s=>new Promise(((n,o)=>{s.push(((s,a)=>{const l=e=>{s.removeEventListener("error",l),s.removeEventListener("message",h),o(e),a()},h=e=>{if("decoded"===e.data.action){if(s.removeEventListener("error",l),s.removeEventListener("message",h),e.data.success)try{this._createTexture(e.data.decodedData,t,i),n()}catch(e){o({message:e})}else o({message:e.data.msg});a()}};s.addEventListener("error",l),s.addEventListener("message",h),s.postMessage({action:"setDefaultDecoderOptions",options:wf.DefaultDecoderOptions._getKTX2DecoderOptions()});const c=new Uint8Array(e.byteLength);c.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),s.postMessage({action:"decode",data:c,caps:r,options:i},[c.buffer])}))}))));if(wf._DecoderModulePromise)return wf._DecoderModulePromise.then((i=>(wf.DefaultDecoderOptions.isDirty&&(wf._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=wf.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise(((r,n)=>{i.decode(e,s).then((e=>{this._createTexture(e,t),r()})).catch((e=>{n({message:e})}))})))));throw new Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let s=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,s=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw new Error("KTX2 container - could not transcode the data. "+e.errors);for(let i=0;i=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}wf.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null},wf.DefaultNumWorkers=wf.GetDefaultNumWorkers(),wf.DefaultDecoderOptions=new class{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;const e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[Mf.BC1_RGB,Mf.BC3_RGBA],yes:{transcodeFormat:Mf.RGBA32,engineFormat:Df.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}},Br._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,s){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const r=t.getEngine(),n=new Af(e,6),o=n.numberOfMipmapLevels>1&&t.generateMipMaps;r._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,r._setCubeMapTextureParams(t,o,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}loadData(e,t,i,s){if(Af.IsValid(e)){t._invertVScale=!t.invertY;const s=new Af(e,1),r=function(e){switch(e){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}(s.glInternalFormat);r?(t.format=r,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=s.glInternalFormat,i(s.pixelWidth,s.pixelHeight,t.generateMipMaps,!0,(()=>{s.uploadLevels(t,t.generateMipMaps)}),s.isInvalid)}else wf.IsValid(e)?new wf(t.getEngine())._uploadAsync(e,t,s).then((()=>{i(t.width,t.height,t.generateMipMaps,!0,(()=>{}),!1)}),(e=>{J.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,(()=>{}),!0)})):(J.Error("texture missing KTX identifier"),i(0,0,!1,!1,(()=>{}),!0))}});class Ff extends _l{constructor(e,t,i){super(e,w.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=L.Identity(),this._referencedPosition=new w,this._trackingState=yh.NOT_TRACKING,this.onXRCameraInitializedObservable=new g,this.onBeforeCameraTeleport=new g,this.onAfterCameraTeleport=new g,this.onTrackingStateChanged=new g,this.compensateOnFirstFrame=!0,this._rotate180=new L(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new L,this.cameraRigMode=or.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add((()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame,this._xrSessionManager.onWorldScaleFactorChangedObservable.add((()=>{this._xrSessionManager.currentFrame&&this._updateDepthNearFar()}))})),this._xrSessionManager.onXRFrameObservable.add((()=>{this._firstFrame&&this._updateFromXRSession(),this.onXRCameraInitializedObservable.hasObservers()&&(this.onXRCameraInitializedObservable.notifyObservers(this),this.onXRCameraInitializedObservable.clear()),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()}),void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y*this._xrSessionManager.worldScalingFactor:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new nr(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new nr(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){e&&e!==this&&(e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,L.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace())}getClassName(){return"WebXRCamera"}setTarget(e){const t=U.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),L.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateDepthNearFar(){const e=(this.maxZ||1e4)*this._xrSessionManager.worldScalingFactor,t={depthFar:e,depthNear:this.minZ};this._xrSessionManager.updateRenderState(t),this._cache.minZ=this.minZ,this._cache.maxZ=e}_updateFromXRSession(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e)return void this._setTrackingState(yh.NOT_TRACKING);const t=e.emulatedPosition?yh.TRACKING_LOST:yh.TRACKING;if(this._setTrackingState(t),this.minZ===this._cache.minZ&&this.maxZ===this._cache.maxZ||this._updateDepthNearFar(),e.transform){const t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;const i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._referenceQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach(((e,t)=>{const i=this.rigCameras[t];i.isLeftCamera||i.isRightCamera||("right"===e.eye?i._isRightCamera=!0:"left"===e.eye&&(i._isLeftCamera=!0));const s=this.getScene().customRenderTargets;for(let e=0;ee;){const e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=U.Matrix[0],t=U.Matrix[1],i=U.Matrix[2];B.ComposeToRef(Ff._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),B.ComposeToRef(Ff._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);const s=new XRRigidTransform({x:this._referencedPosition.x/this._xrSessionManager.worldScalingFactor,y:this._referencedPosition.y/this._xrSessionManager.worldScalingFactor,z:this._referencedPosition.z/this._xrSessionManager.worldScalingFactor},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(s)}}}Ff._ScaleReadOnly=w.One();class Lf{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new g,this.onStateChangedObservable=new g,this.state=Ch.NOT_IN_XR,this.sessionManager=new bh(e),this.camera=new Ff("webxr",e,this.sessionManager),this.featuresManager=new fo(this.sessionManager),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}static CreateAsync(e){const t=new Lf(e);return t.sessionManager.initializeAsync().then((()=>(t._supported=!0,t))).catch((e=>{throw t._setState(Ch.NOT_IN_XR),t.dispose(),e}))}dispose(){this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),this._spectatorCamera?.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),s={}){if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(Ch.ENTERING_XR),"viewer"!==t&&"local"!==t&&(s.optionalFeatures=s.optionalFeatures||[],s.optionalFeatures.push(t)),s=await this.featuresManager._extendXRSessionInitObject(s),"immersive-ar"===e&&"unbounded"!==t&&J.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,s),await this.sessionManager.setReferenceSpaceTypeAsync(t);const r={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};if(!this.featuresManager.getEnabledFeature(po.LAYERS)){const e=await i.initializeXRLayerAsync(this.sessionManager.session);r.baseLayer=e}return this.sessionManager.updateRenderState(r),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!this._nonVRCamera?.inputs?.attachedToElement,this._nonVRCamera?.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),this.sessionManager.onXRSessionEnded.addOnce((()=>{this.state!==Ch.EXITING_XR&&this._setState(Ch.EXITING_XR),this.camera.rigCameras.forEach((e=>{e.outputRenderTarget=null})),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(Ch.NOT_IN_XR)})),this.sessionManager.onXRFrameObservable.addOnce((()=>{this._setState(Ch.IN_XR)})),this.sessionManager}catch(e){throw J.Log(e),J.Log(e.message),this._setState(Ch.NOT_IN_XR),e}}exitXRAsync(){return this.state!==Ch.IN_XR?Promise.resolve():(this._setState(Ch.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){const t=1/(e?.fps?e.fps:1e3)*1e3,i=e?.preferredCameraIndex?e?.preferredCameraIndex:0,s=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=t&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[i].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[i].absoluteRotation))};if(this._spectatorMode){if(i>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const e=()=>{this.state===Ch.IN_XR?(this._spectatorCamera=new Il("webxr-spectator",w.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new L,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(s),this._scene.onAfterRenderCameraObservable.add((e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)}))):this.state===Ch.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=null)};this.onStateChangedObservable.add(e),e()}else this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class Bf{constructor(e,t,i=-1,s=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=s,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new g,this.onButtonStateChangedObservable=new g}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return 0!==this._axesIndices.length}isButton(){return-1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){const i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}}Bf.BUTTON_TYPE="button",Bf.SQUEEZE_TYPE="squeeze",Bf.THUMBSTICK_TYPE="thumbstick",Bf.TOUCHPAD_TYPE="touchpad",Bf.TRIGGER_TYPE="trigger";class Vf{constructor(e,t,i,s,r=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=s,this._doNotLoadControllerMesh=r,this._controllerCache=n,this._initComponent=e=>{if(!e)return;const t=this.layout.components[e],i=t.type,s=t.gamepadIndices.button,r=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&r.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new Bf(e,i,s,r)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new g,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach((e=>this.getComponent(e).dispose())),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach((e=>{e.setEnabled(!1)})),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map((e=>this.components[e])).filter((t=>t.type===e))}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){const e=!this._getModelLoadingConstraints();let t=this._getGenericFilenameAndPath();return e?J.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise(((i,s)=>{const r=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const e=this._controllerCache.filter((e=>e.filename===t.filename&&e.path===t.path));if(e[0])return e[0].meshes.forEach((e=>e.setEnabled(!0))),void r(e[0].meshes)}Ro.ImportMesh("",t.path,t.filename,this.scene,(e=>{this._controllerCache&&this._controllerCache.push({...t,meshes:e}),r(e)}),null,((e,i)=>{J.Log(i),J.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),s(i)}))}))}updateFromXRFrame(e){this.getComponentIds().forEach((e=>this.getComponent(e).update(this.gamepadObject))),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren((e=>e.name===t),!1)[0]}_getImmediateChildByName(e,t){return e.getChildren((e=>e.name==t),!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh)return;if(!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;const s=i?.5*t+.5:t;L.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,s,e.valueMesh.rotationQuaternion),w.LerpToRef(e.minMesh.position,e.maxMesh.position,s,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new Un(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))})),this.rootMesh.rotationQuaternion=L.FromEulerAngles(0,Math.PI,0)}}class Uf extends Vf{constructor(e,t,i){super(e,kf[i],t,i),this.profileId=Uf.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new Un(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)})),this.rootMesh.rotationQuaternion=L.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}Uf.ProfileId="generic-trigger";const kf={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};class Gf extends Vf{constructor(e,t,i,s,r){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,r),this._repositoryUrl=s,this.controllerCache=r,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach((e=>{this._touchDots[e].dispose()}))}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){const e=Ro.IsPluginForExtensionAvailable(".glb");return e||J.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach((i=>{const s=t.visualResponses[i];if("transform"===s.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s.valueNodeName),minMesh:this._getChildByName(this.rootMesh,s.minNodeName),maxMesh:this._getChildByName(this.rootMesh,s.maxNodeName)};else{const r=t.type===Bf.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:s.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r)},t.type===Bf.TOUCHPAD_TYPE&&!this._touchDots[i]){const t=nc(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new dh(i+"mat",this.scene),t.material.diffuseColor=Y.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}}))}))}_setRootMesh(e){let t;this.rootMesh=new Un(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i{const t=this.getComponent(e);if(!t.hasChanges)return;const i=this._buttonMeshMapping[e],s=this.layout.components[e];Object.keys(s.visualResponses).forEach((e=>{const r=s.visualResponses[e];let n=t.value;if("xAxis"===r.componentProperty?n=t.axes.x:"yAxis"===r.componentProperty&&(n=t.axes.y),"transform"===r.valueNodeProperty)this._lerpTransform(i.states[e],n,"button"!==r.componentProperty);else{const s=i.states[e].valueMesh;s&&(s.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}}))}))}}const zf=[];class Wf{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){const t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){const s=[];i&&s.push(i),s.push(...e.profiles||[]),s.length&&!s[0]&&s.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&s.push("oculus-touch-v2");const r=s.indexOf("windows-mixed-reality");if(-1!==r&&s.splice(r,0,"microsoft-mixed-reality"),s.length||s.push("generic-trigger"),this.UseOnlineRepository){const i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,r=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,s,e,t).catch((()=>r.call(this,s,e,t)))}return this._LoadProfilesFromAvailableControllers(s,e,t)}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=Ii.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then((e=>JSON.parse(e))),this._ProfilesList}static ClearControllerCache(){zf.forEach((e=>{e.meshes.forEach((e=>{e.dispose(!1,!0)}))})),zf.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then((()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList())).then((t=>{for(let i=0;i(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=Ii.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then((e=>JSON.parse(e)))),this._ProfileLoadingPromises[e]))).then((e=>new Gf(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:zf)))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let s=0;snew Uf(t,e.gamepad,e.handedness))),Wf.DefaultFallbacks();let Hf=0;class Xf{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new w,this._disposed=!1,this.onDisposeObservable=new g,this.onMeshLoadedObservable=new g,this.onMotionControllerInitObservable=new g,this._uniqueId=`controller-${Hf++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new Wr(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new L,this.inputSource.gripSpace&&(this.grip=new Wr(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new L),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&Wf.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then((e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then((e=>{e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach((e=>e.renderingGroupId=this._options.renderingGroupId))),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&this.motionController?.dispose()}))}),(()=>{Ii.Warn("Could not find a matching motion controller for the registered input source")}))}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){const i=t&&this.grip?this.grip:this.pointer;w.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i,s){const r=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=r,r){const e=r.transform.position;this.pointer.position.set(e.x,e.y,e.z).scaleInPlace(s.worldScalingFactor);const t=r.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent,this.pointer.scaling.setAll(s.worldScalingFactor)}if(this.inputSource.gripSpace&&this.grip){const r=e.getPose(this.inputSource.gripSpace,t);if(r){const e=r.transform.position,t=r.transform.orientation;this.grip.position.set(e.x,e.y,e.z).scaleInPlace(s.worldScalingFactor),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent,this.grip.scaling.setAll(s.worldScalingFactor)}this.motionController&&this.motionController.updateFromXRFrame(e)}}class Yf{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new g,this.onControllerRemovedObservable=new g,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add((()=>{this._addAndRemoveControllers([],this.controllers.map((e=>e.inputSource)))})),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add((e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)})),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add((e=>{this.controllers.forEach((t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera,this.xrSessionManager)}))})),this._options.customControllersRepositoryURL&&(Wf.BaseRepositoryUrl=this._options.customControllersRepositoryURL),Wf.UseOnlineRepository=!this._options.disableOnlineControllerRepository,Wf.UseOnlineRepository)try{Wf.UpdateProfilesList().catch((()=>{Wf.UseOnlineRepository=!1}))}catch(e){Wf.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map((e=>e.inputSource));for(const t of e)if(-1===i.indexOf(t)){const e=new Xf(this.xrSessionManager.scene,t,{...this._options.controllerOptions||{},forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation});this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}const s=[],r=[];this.controllers.forEach((e=>{-1===t.indexOf(e.inputSource)?s.push(e):r.push(e)})),this.controllers=s,r.forEach((e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()}))}dispose(){this.controllers.forEach((e=>{e.dispose()})),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),Wf.ClearControllerCache()}}class jf extends _o{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;const{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(this._options.forceGripIfAvailable&&e.grip?e.grip:e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new ao(new w,new w),disabledByNearInteraction:!1,id:jf._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":case"transient-pointer":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new w,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new Y(.9,.9,.9),this.laserPointerDefaultColor=new Y(.7,.7,.7),this.selectionMeshDefaultColor=new Y(.8,.8,.8),this.selectionMeshPickedColor=new Y(.3,.3,1),this._identityMatrix=B.Identity(),this._screenCoordinatesRef=w.Zero(),this._viewportRef=new nr(0,0,0,0),this._scene=this._xrSessionManager.scene,void 0===this._options.lookAndPickMode&&(this._scene.getEngine()._badDesktopOS||this._scene.getEngine()._badOS)&&(this._options.lookAndPickMode=!0),this._options.lookAndPickMode&&(this._options.enablePointerSelectionOnAllControllers=!0,this.displayLaserPointer=!1)}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController,!0),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)}),!0),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){const e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new ao(new w,new w),disabledByNearInteraction:!1,id:jf._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i{const t=this._controllers[e];if(this._options.lookAndPickMode&&"transient-pointer"!==t.xrController?.inputSource.targetRayMode)return;if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||t.disabledByNearInteraction)return t.selectionMesh.isVisible=!1,t.laserPointer.isVisible=!1,void(t.pick=null);let i;if(t.laserPointer.isVisible=this.displayLaserPointer,t.xrController)i=this._options.forceGripIfAvailable&&t.xrController.grip?t.xrController.grip.position:t.xrController.pointer.position,t.xrController.getWorldPointerRayToRef(t.tmpRay,this._options.forceGripIfAvailable);else{if(!t.webXRCamera)return;i=t.webXRCamera.position,t.webXRCamera.getForwardRayToRef(t.tmpRay)}if(this._options.maxPointerDistance&&(t.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&i){const e=this._xrSessionManager.scene,s=this._options.xrInput.xrCamera;s&&(s.viewport.toGlobalToRef(e.getEngine().getRenderWidth()/s.rigCameras.length,e.getEngine().getRenderHeight(),this._viewportRef),w.ProjectToRef(i,this._identityMatrix,s.getTransformationMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||this._screenCoordinatesRef.x===1/0||this._screenCoordinatesRef.y===1/0||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,t.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let s=null;this._utilityLayerScene&&(s=this._utilityLayerScene.pickWithRay(t.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const r=this._scene.pickWithRay(t.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);s&&s.hit?r&&r.hit?s.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit)if(this._pickingMoved(r,t.pick))a&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,l)),a=!1,o=0;else if(o>i/10&&(n.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,l),a=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),n.isVisible=!1;else{const e=1-o/i;n.scaling.set(e,e,e)}else a=!1,o=0;this._scene.simulatePointerMove(t.pick,l),r=t.pick}})),void 0!==this._options.renderingGroupId&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce((()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&a&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),n.dispose()}))}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const s={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),!t.pick||this._options.disablePointerUpOnTouchOut&&i||(i?this._scene.simulatePointerMove(t.pick,s):(this._scene.simulatePointerDown(t.pick,s),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,s)))})),e.onDisposeObservable.addOnce((()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame((()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,s),t.finalPointerUpTriggered=!0)}))}))}_attachTrackedPointerRayMode(e){const t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);const i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))})),e.inputSource.gamepad){const s=s=>{this._options.overrideButtonId&&(t.selectionComponent=s.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=s.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((s=>{if(s.changes.pressed){const r=s.changes.pressed.current;if(t.pick)(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),r?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor));else if(r&&!this._options.enablePointerSelectionOnAllControllers&&!this._options.disableSwitchOnClick){const t=this._controllers[this._attachedController];t&&t.pointerDownTriggered&&!t.finalPointerUpTriggered&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerUp(new qi,{pointerId:t.id,pointerType:"xr"}),t.finalPointerUpTriggered=!0),this._attachedController=e.uniqueId}}}))};e.motionController?s(e.motionController):e.onMotionControllerInitObservable.add(s)}else{const e=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)}))},s=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)}))};t.eventListeners={selectend:s,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",s)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(w.Dot(e,t.direction)){const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),!t.finalPointerUpTriggered&&t.pointerDownTriggered){const e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame((()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new qi,e),t.finalPointerUpTriggered=!0}))}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce((()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){Ii.Warn("controller already detached.")}}))}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Jh.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():Qh("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const s=new dh("laserPointerMat",t);s.emissiveColor=this.laserPointerDefaultColor,s.alpha=.7,i.material=s,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const r=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():Oh("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);r.bakeCurrentTransformIntoVertices(),r.isPickable=!1,r.isVisible=!1;const n=new dh("targetMat",t);return n.specularColor=Y.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,r.material=n,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:r}}_pickingMoved(e,t){if(!e.hit||!t.hit)return!0;if(!(e.pickedMesh&&e.pickedPoint&&t.pickedMesh&&t.pickedPoint))return!0;if(e.pickedMesh!==t.pickedMesh)return!0;e.pickedPoint?.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const i=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance;return this._tmpVectorForPickCompare.length()>i}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}}var $f,Kf,qf;jf._IdCounter=200,jf.Name=po.POINTER_SELECTION,jf.Version=1,fo.AddWebXRFeature(jf.Name,((e,t)=>()=>new jf(e,t)),jf.Version,!0),vr.prototype._projectOnTrianglesToRef=function(e,t,i,s,r,n){const o=U.Vector3[0],a=U.Vector3[1];let l=1/0;for(let n=this.indexStart;n{if(this._controllers[e.uniqueId])return;const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s}=this._generateNewTouchPointMesh(),r=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s,currentAnimationState:$f.DEHYDRATED,grabRay:new ao(new w,new w),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,downTriggered:!1,id:Qf._IdCounter++,pickedPointVisualCue:r},this._controllers[e.uniqueId]._worldScaleObserver=this._controllers[e.uniqueId]._worldScaleObserver||this._xrSessionManager.onWorldScaleFactorChangedObservable.add((t=>{if(t.newScaleFactor!==t.previousScaleFactor){this._controllers[e.uniqueId].touchCollisionMesh.dispose(),this._controllers[e.uniqueId].pickedPointVisualCue.dispose();const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s}=this._generateNewTouchPointMesh();this._controllers[e.uniqueId].touchCollisionMesh=t,this._controllers[e.uniqueId].touchCollisionMeshFunction=i,this._controllers[e.uniqueId].hydrateCollisionMeshFunction=s,this._controllers[e.uniqueId].pickedPointVisualCue=this._generateVisualCue()}})),this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new Y(.8,.8,.8),this.selectionMeshPickedColor=new Y(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=Kf.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;ie.currentAnimationState)switch(e.currentAnimationState){case $f.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===$f.HOVER)break;case $f.HOVER:if(e.touchCollisionMeshFunction(!0),t===$f.TOUCH)break}else switch(e.currentAnimationState){case $f.TOUCH:if(e.touchCollisionMeshFunction(!1),t===$f.HOVER)break;case $f.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===$f.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){const s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(U.Vector3[0]),s.grabRay.direction.copyFrom(U.Vector3[0]),this._options.nearInteractionControllerMode!==Kf.CENTERED_IN_FRONT||s.xrController?.inputSource.hand||(s.xrController.getWorldPointerRayToRef(this._tmpRay),s.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),s.grabRay.length=this._nearGrabLengthScale*this._hoverRadius*this._xrSessionManager.worldScalingFactor,s.touchCollisionMesh.position.copyFrom(s.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor)}_onXRFrame(e){Object.keys(this._controllers).forEach((t=>{const i=this._controllers[t],s=i.xrController?.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!i.xrController||!s&&(!this._options.nearInteractionControllerMode||!i.xrController.inputSource.gamepad))return void(i.pick=null);if(i.hoverInteraction=!1,i.nearInteraction=!1,!i.xrController)return;if(s){const i=s.get("index-finger-tip");if(i){const s=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(s&&s.transform){const e=this._scene.useRightHandedSystem?1:-1;U.Vector3[0].set(s.transform.position.x,s.transform.position.y,s.transform.position.z*e),U.Quaternion[0].set(s.transform.orientation.x,s.transform.orientation.y,s.transform.orientation.z*e,s.transform.orientation.w*e),this._processTouchPoint(t,U.Vector3[0],U.Quaternion[0])}}}else if(i.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==Kf.DISABLED){let e=i.xrController.pointer;i.xrController.grip&&this._options.nearInteractionControllerMode===Kf.CENTERED_ON_CONTROLLER&&(e=i.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}const r=(e,t)=>{let i=null;return i=t&&t.hit?e&&e.hit?t.distance{let t=new qi,i=!1;const s=e&&e.pickedPoint&&e.hit;return e?.pickedPoint&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),s&&!i&&(t=e),t};if(!i.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._utilityLayerScene,(e=>this._nearInteractionPredicate(e))));const o=r(this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._scene,(e=>this._nearInteractionPredicate(e))),t);if(o&&o.hit&&(e=n(o),e.hit&&(i.hoverInteraction=!0)),i.hoverInteraction){let t=null;const o=(s?this._pickRadius:this._controllerPickRadius)*this._xrSessionManager.worldScalingFactor;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,o,this._utilityLayerScene,(e=>this._nearPickPredicate(e))));const a=n(r(this._pickWithSphere(i,o,this._scene,(e=>this._nearPickPredicate(e))),t));a.hit&&(e=a,i.nearInteraction=!0)}i.stalePick=i.pick,i.pick=e,i.pick&&i.pick.pickedPoint&&i.pick.hit?(i.meshUnderPointer=i.pick.pickedMesh,i.pickedPointVisualCue.position.copyFrom(i.pick.pickedPoint),i.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!0)):(i.meshUnderPointer=null,i.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!1))}let o=$f.DEHYDRATED;i.grabInteraction||i.nearInteraction?o=$f.TOUCH:i.hoverInteraction&&(o=$f.HOVER),this._handleTransitionAnimation(i,o)}))}get _utilityLayerScene(){return this._options.customUtilityLayerScene||Jh.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Jh.DefaultUtilityLayer.utilityLayerScene:this._scene,t=nc("nearInteraction",{diameter:.0105*this._xrSessionManager.worldScalingFactor},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=L.Identity();const i=new dh("targetMat",e);return i.specularColor=Y.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer,t.downTriggered=!0):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.downTriggered=!1,t.nearInteractionTargetMesh=null))}));const s=s=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),s&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0):!s&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.downTriggered=!1,t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!s||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const i=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;s(t)}})):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;s(t)}})))};e.motionController?i(e.motionController):e.onMotionControllerInitObservable.add(i)}else{const e=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0)},s=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0,t.downTriggered=!1)};t.eventListeners={selectend:s,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",s)}}_detachController(e){const t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach((e=>{const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame((()=>{if(!t.downTriggered)return;const e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new qi,e)})),t._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(t._worldScaleObserver),delete this._controllers[e],this._attachedController===e)){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){const e=this._xrSessionManager.worldScalingFactor,t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Jh.DefaultUtilityLayer.utilityLayerScene:this._scene,i=nc("PickSphere",{diameter:1*e},t);if(i.isVisible=!1,this._options.motionControllerOrbMaterial)i.material=this._options.motionControllerOrbMaterial;else{let e;e=this._options.motionControllerTouchMaterialSnippetUrl?xa.ParseFromFileAsync("motionControllerTouchMaterial",this._options.motionControllerTouchMaterialSnippetUrl,t):xa.ParseFromSnippetAsync("8RUNKL#3",t),e.then((e=>{i.material=e})).catch((e=>{J.Warn(`Error creating touch material in WebXRNearInteraction: ${e}`)}))}const s=new Qs;s.setEasingMode(Ks.EASINGMODE_EASEINOUT);const r=new w(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius).scaleInPlace(e),n=this._controllerPickRadius*(4/3),o=new w(n,n,n).scaleInPlace(e),a=this._controllerPickRadius*(7/6),l=new w(a,a,a).scaleInPlace(e),h=.8*this._controllerPickRadius,c=new w(h,h,h).scaleInPlace(e),u=1.5*this._controllerPickRadius,d=[{frame:0,value:r},{frame:10,value:new w(u,u,u).scaleInPlace(e)},{frame:18,value:o}],p=[{frame:0,value:o},{frame:10,value:c},{frame:18,value:r}],f=[{frame:0,value:w.ZeroReadOnly},{frame:12,value:l},{frame:15,value:r}],_=[{frame:0,value:r},{frame:10,value:w.ZeroReadOnly},{frame:15,value:w.ZeroReadOnly}],m=new Ge("touch","scaling",60,Ge.ANIMATIONTYPE_VECTOR3,Ge.ANIMATIONLOOPMODE_CONSTANT),g=new Ge("release","scaling",60,Ge.ANIMATIONTYPE_VECTOR3,Ge.ANIMATIONLOOPMODE_CONSTANT),v=new Ge("hydrate","scaling",60,Ge.ANIMATIONTYPE_VECTOR3,Ge.ANIMATIONLOOPMODE_CONSTANT),x=new Ge("dehydrate","scaling",60,Ge.ANIMATIONTYPE_VECTOR3,Ge.ANIMATIONLOOPMODE_CONSTANT);return m.setEasingFunction(s),g.setEasingFunction(s),v.setEasingFunction(s),x.setEasingFunction(s),m.setKeys(d),g.setKeys(p),v.setKeys(f),x.setKeys(_),{touchCollisionMesh:i,touchCollisionMeshFunction:e=>{const s=e?m:g;t.beginDirectAnimation(i,[s],0,18,!1,1)},hydrateCollisionMeshFunction:e=>{const s=e?v:x;e&&(i.isVisible=!0),t.beginDirectAnimation(i,[s],0,15,!1,1,(()=>{e||(i.isVisible=!1)}))}}}_pickWithSphere(e,t,i,s){const r=new qi;if(r.distance=1/0,e.touchCollisionMesh&&e.xrController){const n=e.touchCollisionMesh.position,o=hr.CreateFromCenterAndRadius(n,t);for(let t=0;tc&&(h=0,a.copyFrom(t.center)),-1!==h&&h()=>new Qf(e,t)),Qf.Version,!0);class Zf{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class Jf{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new g,this._onSessionGranted=e=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw Ii.Warn("WebXR can only be served over HTTPS"),new Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";const e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor";let s=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+("undefined"==typeof SVGSVGElement?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";s+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const r=document.createElement("style");r.appendChild(document.createTextNode(s)),document.getElementsByTagName("head")[0].appendChild(r);const n=document.createElement("button");n.className="babylonVRicon",n.title=`${e} - ${i}`,this._buttons.push(new Zf(n,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",n.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}const i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce((()=>{this.dispose()})))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;const i=this._buttons.map((t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode)));e.onStateChangedObservable.add((e=>{e==Ch.NOT_IN_XR&&this._updateButtons(null)})),(await Promise.all(i)).forEach(((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):Ii.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)}))}static async CreateAsync(e,t,i){const s=new Jf(e,i);return await s.setHelperAsync(t,i.renderTarget||void 0),s}async _enterXRWithButtonIndex(e=0){if(this._helper.state==Ch.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==Ch.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(t){this._updateButtons(null);const i=this._buttons[e].element,s=i.title;i.title="Error entering XR session : "+s,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t)}}dispose(){const e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach((e=>{e.update(this._activeButton)})),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}function e_(e){let t=0;const i=Date.now();e.observableParameters=e.observableParameters??{};const s=e.contextObservable.add((r=>{const n=Date.now();t=n-i;const o={startTime:i,currentTime:n,deltaTime:t,completeRate:t/e.timeout,payload:r};e.onTick&&e.onTick(o),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(o)),t>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(o))}),e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return s}!function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(qf||(qf={}));class t_{constructor(e){this.onEachCountObservable=new g,this.onTimerAbortedObservable=new g,this.onTimerEndedObservable=new g,this.onStateChangedObservable=new g,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{const t=Date.now();this._timer=t-this._startTime;const i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},s=this._breakOnNextTick||this._breakCondition(i);s||this._timer>=this._timeToEnd?this._stop(i,s):this.onEachCountObservable.notifyObservers(i)},this._setState(qf.INIT),this._contextObservable=e.contextObservable,this._observableParameters=e.observableParameters??{},this._breakCondition=e.breakCondition??(()=>!1),this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}set breakCondition(e){this._breakCondition=e}clearObservables(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()}start(e=this._timeToEnd){if(this._state===qf.STARTED)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(qf.STARTED)}stop(){this._state===qf.STARTED&&(this._breakOnNextTick=!0)}dispose(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()}_setState(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)}_stop(e,t=!1){this._contextObservable.remove(this._observer),this._setState(qf.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class i_ extends _o{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){const t=this._options.teleportationTargetMesh.getChildMeshes(!1,(e=>"rotationCone"===e.name));t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new j(1,1,1,1),this._tmpRay=new ao(new w,new w),this._tmpVector=new w,this._tmpQuaternion=new L,this._worldScaleObserver=null,this.skipNextTeleportation=!1,this.backwardsMovementEnabled=!0,this.backwardsTeleportationDistance=.7,this.parabolicCheckRadius=5,this.parabolicRayEnabled=!0,this.straightRayEnabled=!0,this.rotationAngle=Math.PI/8,this.onTargetMeshPositionUpdatedObservable=new g,this.teleportationEnabled=!0,this._rotationEnabled=!0,this.onBeforeCameraTeleportRotation=new g,this.onAfterCameraTeleportRotation=new g,this._attachController=e=>{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1,initialHit:!1,mainComponentUsed:!1}};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController){const i=e.motionController.getComponentOfType(Bf.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(Bf.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){const i=e.motionController.getMainComponent();if(!i)return;t.teleportationState.mainComponentUsed=!0,t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add((()=>{if(!this.teleportationEnabled)return;const s=()=>{t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,e_({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};i.changes.pressed&&(i.changes.pressed.current?this._options.timeToTeleportStart?e_({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{i.pressed&&s()}}):s():(t.teleportationState.forward=!1,this._currentTeleportationControllerId=""))}))}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add((i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,L.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);const e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,(e=>-1!==this._floorMeshes.indexOf(e)));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout((()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))})):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;const e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this.onBeforeCameraTeleportRotation.notifyObservers(e),L.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),t.teleportationState.forward&&this._teleportForward(e.uniqueId))}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}else{t.teleportationState.mainComponentUsed=!0;let i=!1;const s=()=>{this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,e_({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};this._xrSessionManager.scene.onPointerObservable.add((e=>{e.type===ss.POINTERDOWN?(i=!1,this._options.timeToTeleportStart?e_({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&s()},breakCondition:()=>!!i&&(i=!1,!0)}):s()):e.type===ss.POINTERUP&&(i=!0,t.teleportationState.forward=!1,this._currentTeleportationControllerId="")}))}},this._colorArray=Array(24).fill(this._cachedColor4White),this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new j(1,0,0,.75),this._setTargetMeshVisibility(!1),this.onBeforeCameraTeleport=t.xrInput.xrCamera.onBeforeCameraTeleport,this.onAfterCameraTeleport=t.xrInput.xrCamera.onAfterCameraTeleport,this.parabolicCheckRadius*=this._xrSessionManager.worldScalingFactor,this._worldScaleObserver=e.onWorldScaleFactorChangedObservable.add((e=>{this.parabolicCheckRadius=this.parabolicCheckRadius/e.previousScaleFactor*e.newScaleFactor,this._options.teleportationTargetMesh?.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor)}))}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return!!super.attach()&&(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver)}removeFloorMesh(e){const t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];const t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){const t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(-1===t)for(let i=0;i{if(this._options.blockerMeshesPredicate&&this._options.blockerMeshesPredicate(e))return!0;if(this._options.blockAllPickableMeshes&&e.isPickable)return!0;if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;const t=this._floorMeshes.indexOf(e);return-1!==t&&this._floorMeshes[t].absolutePosition.y!(!this._options.blockerMeshesPredicate||!this._options.blockerMeshesPredicate(e))||!(!this._options.blockAllPickableMeshes||!e.isPickable)||!(!this._options.pickBlockerMeshes||-1===this._options.pickBlockerMeshes.indexOf(e))||-1!==this._floorMeshes.indexOf(e))),l=a&&a.pickedMesh&&-1!==this._floorMeshes.indexOf(a.pickedMesh);if(a&&a.pickedMesh&&!l)return e.teleportationState.mainComponentUsed&&!e.teleportationState.initialHit?void(e.teleportationState.forward=!1):(e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,r),void this._showParabolicPath(a));a&&a.pickedPoint&&(e.teleportationState.initialHit=!0,e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(a),this._setTargetMeshVisibility(!0,!1,r),this._showParabolicPath(a))}this._setTargetMeshVisibility(t,!1,r)}else this._setTargetMeshVisibility(!1,!1,!0)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1,!1,!0)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Jh.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=Mh("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const i=512,s=new ph("teleportationPlaneDynamicTexture",i,e,!0);s.hasAlpha=!0;const r=s.getContext(),n=i/2,o=i/2,a=200;r.beginPath(),r.arc(n,o,a,0,2*Math.PI,!1),r.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",r.fill(),r.lineWidth=10,r.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",r.stroke(),r.closePath(),s.update();const l=new dh("teleportationPlaneMaterial",e);l.diffuseTexture=s,t.material=l}const i=Oh("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const t=new Ge("animationInnerCircle","position.y",30,Ge.ANIMATIONTYPE_FLOAT,Ge.ANIMATIONLOOPMODE_CYCLE),s=[];s.push({frame:0,value:0}),s.push({frame:30,value:.4}),s.push({frame:60,value:0}),t.setKeys(s);const r=new Zs;r.setEasingMode(Ks.EASINGMODE_EASEINOUT),t.setEasingFunction(r),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}const s=Qh("rotationCone",{diameterTop:0,tessellation:4},e);if(s.isPickable=!1,s.scaling.set(.5,.12,.2),s.rotate(Gs.X,Math.PI/2),s.position.z=.6,s.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,s.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const t=new dh("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new Y(.3,.3,1):t.diffuseColor=new Y(.3,.3,1),t.alpha=.9,i.material=t,s.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._options.teleportationTargetMesh.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._setTargetMeshVisibility(!1)}_detachController(e){const t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,s=Number.MAX_VALUE;if(this._snapToPositions.length){const r=t*t;this._snapToPositions.forEach((t=>{const n=w.DistanceSquared(t,e);n<=r&&n{t.isVisible=e})),e?this._selectionFeature&&i&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&i&&this._selectionFeature.attach()))}_disposeBezierCurve(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Jh.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],s=$s.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),r=i.teleportationState.blocked?this._blockedRayColor:void 0,n=this._colorArray.fill(r||this._cachedColor4White),o=s.getPoints();o.shift(),o.shift(),this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(s.getPoints(),e):this._quadraticBezierCurve=Tc("teleportation path line",{points:o,instance:this._quadraticBezierCurve,updatable:!0,colors:n},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){const t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint))if(this.skipNextTeleportation)this.skipNextTeleportation=!1;else if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){const e=this._options.xrInput.xrCamera.realWorldHeight;this.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=e,L.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}i_.Name=po.TELEPORTATION,i_.Version=1,fo.AddWebXRFeature(i_.Name,((e,t)=>()=>new i_(e,t)),i_.Version,!0);class s_{constructor(){}static CreateAsync(e,t={}){const i=new s_;if(e.onDisposeObservable.addOnce((()=>{i.dispose()})),!t.disableDefaultUI){const s={renderTarget:i.renderTarget,...t.uiOptions||{}};t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?s.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:s.optionalFeatures=t.optionalFeatures),i.enterExitUI=new Jf(e,s)}return Lf.CreateAsync(e).then((e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new Yf(e.sessionManager,e.camera,{controllerOptions:{renderingGroupId:t.renderingGroupId},...t.inputOptions||{}}),!t.disablePointerSelection){const e={...t.pointerSelectionOptions,xrInput:i.input,renderingGroupId:t.renderingGroupId};i.pointerSelection=i.baseExperience.featuresManager.enableFeature(jf.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(i_.Name,t.useStablePlugins?"stable":"latest",{floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId,...t.teleportationOptions}),i.teleportation.setSelectionFeature(i.pointerSelection))}return t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(Qf.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0,...t.nearInteractionOptions})),t.disableHandTracking||i.baseExperience.featuresManager.enableFeature(Ia.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,...t.handSupportOptions},void 0,!1),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)})).then((()=>i)).catch((e=>(J.Error("Error initializing XR"),J.Error(e),i)))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}function r_(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}ks.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;ee.isVisible&&e.isEnabled())),s=t.max.subtract(t.min),r=t.min.add(s.scale(.5));let n,o=1.5*s.length();if(isFinite(o)||(o=1,r.copyFromFloats(0,0,0)),e){const e=new gl("default camera",-Math.PI/2,Math.PI/2,o,r,this);e.lowerRadiusLimit=.01*o,e.wheelPrecision=100/o,n=e}else{const e=new _l("default camera",new w(r.x,r.y,-o),this);e.setTarget(r),n=e}n.minZ=.01*o,n.maxZ=1e3*o,n.speed=.2*o,this.activeCamera=n,i&&n.attachControl()}},ks.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},ks.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,s=0,r=!0){if(!e)return J.Warn("Can not create default skybox without environment texture."),null;r&&e&&(this.environmentTexture=e);const n=sc("hdrSkyBox",{size:i},this);if(t){const t=new yf("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Zn.SKYBOX_MODE),t.microSurface=1-s,t.disableLighting=!0,t.twoSidedLighting=!0,n.material=t}else{const t=new dh("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Zn.SKYBOX_MODE),t.disableLighting=!0,n.material=t}return n.isPickable=!1,n.infiniteDistance=!0,n.ignoreCameraMaxZ=!0,n},ks.prototype.createDefaultEnvironment=function(e){return nf?new nf(e,this):null},ks.prototype.createDefaultVRExperience=function(e={}){return new Fh(this,e)},ks.prototype.createDefaultXRExperienceAsync=function(e={}){return s_.CreateAsync(this,e).then((e=>e))};class n_ extends Zn{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new g),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e?.message):J.Error(e?.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch((e=>{if("NotAllowedError"===e?.name){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers())return void this._onUserActionRequestedObservable.notifyObservers(this);if(!this.video.muted)return J.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,void this.video.play().catch((e=>{this._processError(e)}))}this._processError(e)}))}constructor(e,t,i,s=!1,r=!1,n=Zn.TRILINEAR_SAMPLINGMODE,o={},a,l=5){super(null,i,!s,r),this._externalTexture=null,this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||Ii.IsExponentOfTwo(this.video.videoWidth)&&Ii.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=Zn.WRAP_ADDRESSMODE,this.wrapV=Zn.WRAP_ADDRESSMODE):(this.wrapU=Zn.CLAMP_ADDRESSMODE,this.wrapV=Zn.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=this._format??5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(null!=this._texture){if(!this._displayingPosterTexture)return;this._displayingPosterTexture=!1}if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{const e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture)return;if(this.video.readyState=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&u?u&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return Ii.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return"string"==typeof e?(Ii.SetCorsBehavior(e,t),t.src=e):(Ii.SetCorsBehavior(e[0],t),e.forEach((e=>{const i=document.createElement("source");i.src=e,t.appendChild(i)}))),this.onDisposeObservable.addOnce((()=>{r_(t)})),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))}get externalTexture(){return this._externalTexture}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new n_(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("loadeddata",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),this._externalTexture?.dispose()}static CreateFromStreamAsync(e,t,i,s=!0){const r=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(r),r.style.transform="scale(0.0001, 0.0001)",r.style.opacity="0",r.style.position="fixed",r.style.bottom="0px",r.style.right="0px"),r.setAttribute("autoplay",""),r.setAttribute("muted","true"),r.setAttribute("playsinline",""),r.muted=!0,r.isNative||(void 0!==r.mozSrcObject?r.mozSrcObject=t:"object"==typeof r.srcObject?r.srcObject=t:r.src=window.URL&&window.URL.createObjectURL(t)),new Promise((t=>{const i=()=>{const n=new n_("video",r,e,!0,s,void 0,void 0,void 0,4);e.getEngine()._badOS&&n.onDisposeObservable.addOnce((()=>{r.remove()})),n.onDisposeObservable.addOnce((()=>{r_(r)})),t(n),r.removeEventListener("playing",i)};r.addEventListener("playing",i),r.play()}))}static async CreateFromWebCamAsync(e,t,i=!1,s=!0){if(navigator.mediaDevices){const r=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,r,t,s);return n.onDisposeObservable.addOnce((()=>{r.getTracks().forEach((e=>{e.stop()}))})),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,s=!1,r=!0){this.CreateFromWebCamAsync(e,i,s,r).then((function(e){t&&t(e)})).catch((function(e){J.Error(e.name)}))}}ae([pe("settings")],n_.prototype,"_settings",void 0),ae([pe("src")],n_.prototype,"_currentSrc",void 0),ae([pe()],n_.prototype,"isVideo",void 0),Zn._CreateVideoTexture=(e,t,i,s=!1,r=!1,n=Zn.TRILINEAR_SAMPLINGMODE,o={},a,l=5)=>new n_(e,t,i,s,r,n,o,a,l),u("BABYLON.VideoTexture",n_);class o_ extends of{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const s={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},r=new n_((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,Zn.TRILINEAR_SAMPLINGMODE,s);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add((e=>{e.pickInfo?.pickedMesh===this.mesh&&this._texture.video.play()}),ss.POINTERDOWN)),this._textureObserver=r.onLoadObservable.add((()=>{this.onLoadObservable.notifyObservers()})),r}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}o_.MODE_MONOSCOPIC=of.MODE_MONOSCOPIC,o_.MODE_TOPBOTTOM=of.MODE_TOPBOTTOM,o_.MODE_SIDEBYSIDE=of.MODE_SIDEBYSIDE;Ft.ShadersStore.glowMapGenerationPixelShader="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;uniform float glowIntensity;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;varying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform mat4 diffuseMatrix;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform mat4 opacityMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform mat4 emissiveMatrix;\n#endif\n#ifdef VERTEXALPHA\nattribute vec4 color;varying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef CUBEMAP\nvPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*worldPos;gl_Position=vPosition;\n#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef OPACITYUV2\nvUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef VERTEXALPHA\nvColor=color;\n#endif\n#include\n}";class a_{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||0===t)&&e.subMeshes)for(let t=0;t{let r;this.onBeforeRenderMainTextureObservable.notifyObservers(this);const n=this._scene.getEngine();if(s.length){for(n.setColorWrite(!1),r=0;r{e.clear(this.neutralColor,!0,!0,!0)})),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e})),this._mainTexture.onAfterUnbindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=e}))}}_addCustomEffectDefines(e){}_isReady(e,t,i){const s=this._scene.getEngine(),r=e.getMesh(),n=r._internalAbstractMeshDataInfo._materialForRenderPass?.[s.currentRenderPassId];if(n)return n.isReadyForSubMesh(r,e,t);const o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);const a=[],l=[Ki.PositionKind];let h=!1,c=!1;if(o){const e=o.needAlphaTesting(),t=o.getAlphaTestTexture(),i=t&&t.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);t&&(e||i)&&(a.push("#define DIFFUSE"),r.isVerticesDataPresent(Ki.UV2Kind)&&1===t.coordinatesIndex?(a.push("#define DIFFUSEUV2"),c=!0):r.isVerticesDataPresent(Ki.UVKind)&&(a.push("#define DIFFUSEUV1"),h=!0),e&&(a.push("#define ALPHATEST"),a.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||a.push("#define DIFFUSE_ISLINEAR"));const s=o.opacityTexture;s&&(a.push("#define OPACITY"),r.isVerticesDataPresent(Ki.UV2Kind)&&1===s.coordinatesIndex?(a.push("#define OPACITYUV2"),c=!0):r.isVerticesDataPresent(Ki.UVKind)&&(a.push("#define OPACITYUV1"),h=!0))}i&&(a.push("#define EMISSIVE"),r.isVerticesDataPresent(Ki.UV2Kind)&&1===i.coordinatesIndex?(a.push("#define EMISSIVEUV2"),c=!0):r.isVerticesDataPresent(Ki.UVKind)&&(a.push("#define EMISSIVEUV1"),h=!0),i.gammaSpace||a.push("#define EMISSIVE_ISLINEAR")),r.useVertexColors&&r.isVerticesDataPresent(Ki.ColorKind)&&r.hasVertexAlpha&&o.transparencyMode!==Dn.MATERIAL_OPAQUE&&(l.push(Ki.ColorKind),a.push("#define VERTEXALPHA")),h&&(l.push(Ki.UVKind),a.push("#define UV1")),c&&(l.push(Ki.UV2Kind),a.push("#define UV2"));const u=new Yo;if(r.useBones&&r.computeBonesUsingShaders){l.push(Ki.MatricesIndicesKind),l.push(Ki.MatricesWeightsKind),r.numBoneInfluencers>4&&(l.push(Ki.MatricesIndicesExtraKind),l.push(Ki.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers);const e=r.skeleton;e&&e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),r.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,r)}else a.push("#define NUM_BONE_INFLUENCERS 0");const d=r.morphTargetManager;let p=0;d&&(p=d.numMaxInfluencers||d.numInfluencers,p>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+p),d.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),tn(l,r,p))),t&&(a.push("#define INSTANCES"),rn(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),$r(o,this._scene,a),this._addCustomEffectDefines(a);const f=e._getDrawWrapper(void 0,!0),_=f.defines,m=a.join("\n");if(_!==m){const e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];jr(e),f.setEffect(this._engine.createEffect("glowMapGeneration",l,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],m,u,void 0,void 0,{maxSimultaneousMorphTargets:p}),m)}return f.effect.isReady()}render(){for(let e=0;eh.setMatrix("world",t)))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(s)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[Ki.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return Ii.Instantiate(e.customType).Parse(e,t,i)}}a_._SceneComponentInitialization=e=>{throw ye("EffectLayerSceneComponent")},ae([pe()],a_.prototype,"name",void 0),ae([Te()],a_.prototype,"neutralColor",void 0),ae([pe()],a_.prototype,"isEnabled",void 0),ae([ue(11,void 0)],a_.prototype,"camera",null),ae([pe()],a_.prototype,"renderingGroupId",null),ae([pe()],a_.prototype,"disableBoundingBoxesFromEffectLayer",void 0),p.AddParser(ts.NAME_EFFECTLAYER,((e,t,i,s)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let r=0;r{this.scene.addEffectLayer(e)}))}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach((e=>{this.scene.removeEffectLayer(e),t&&e.dispose()}))}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,s=this.scene.effectLayers;for(const r of s){if(!r.hasMesh(e))continue;const s=r._mainTexture;this._engine.currentRenderPassId=s.renderPassId;for(const s of e.subMeshes)if(!r.isReady(s,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const s of i)if(s.shouldRender()&&(!s.camera||s.camera.cameraRigMode===or.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==or.RIG_MODE_NONE&&s.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||s.needStencil();const e=s._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i{let t=e._getComponent(ts.NAME_EFFECTLAYER);t||(t=new l_(e),e._addComponent(t))};Ft.ShadersStore.glowMapMergePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);baseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.glowMapMergeVertexShader="attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}",p.prototype.getGlowLayerByName=function(e){for(let t=0;t{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess1=new Jp("GlowLayerVBP1",new N(0,1),n,{width:e,height:t},null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new Jp("GlowLayerHBP2",new N(1,0),n,{width:s,height:r},null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=s,this._horizontalBlurPostprocess2.height=r,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._blurTexture1)})),this._verticalBlurPostprocess2=new Jp("GlowLayerVBP2",new N(0,1),n,{width:s,height:r},null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add((()=>{const e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);const t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(t??e,!0)}})),this._postProcesses.map((e=>{e.autoClear=!1}))}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s)return!1;const r=i.emissiveTexture;return super._isReady(e,t,r)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(Dn.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let s=1;this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector?this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color):i.emissiveColor?(s*=i.emissiveIntensity??1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){const e=Pe.Serialize(this);let t;if(e.customType="BABYLON.GlowLayer",e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew h_(e.name,t,e.options)),e,t,i);let r;for(r=0;r{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)}))}}class u_ extends a_{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new g,this.onAfterBlurObservable=new g,this._instanceGlowingMeshStencilReference=u_.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=u_.NeutralColor,this._engine.isStencilEnable||J.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return u_.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[Ki.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?Ri(e,this._maxSize):e,t=this._engine.needPOTTextures?Ri(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new da("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=Zn.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=Zn.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(Zn.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new Ml("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._horizontalBlurPostprocess=new c_("HighlightLayerHBP",new N(1,0),this._options.blurHorizontalSize,1,null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._verticalBlurPostprocess=new c_("HighlightLayerVBP",new N(0,1),this._options.blurVerticalSize,1,null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new Jp("HighlightLayerHBP",new N(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess=new Jp("HighlightLayerVBP",new N(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add((()=>{this.onBeforeBlurObservable.notifyObservers(this);const e=this._blurTexture.renderTarget;e&&(this._scene.postProcessManager.directRender(this._postProcesses,e,!0),this._engine.unBindFramebuffer(e,!0)),this.onAfterBlurObservable.notifyObservers(this)})),this._postProcesses.map((e=>{e.autoClear=!1}))}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s||!this._meshes)return!1;let r=null;const n=this._meshes[s.uniqueId];return n&&n.glowEmissiveOnly&&i&&(r=i.emissiveTexture),super._isReady(e,t,r)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);const i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(Dn.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(Dn.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return!!super.shouldRender()&&!!this._meshes}_shouldRenderMesh(e){return!(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]||!super.hasMesh(e))}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){const s=this._meshes[e.uniqueId];s?this._emissiveTextureAndColor.color.set(s.color.r,s.color.g,s.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),s&&s.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(this._excludedMeshes&&!this._excludedMeshes[e.uniqueId]){const t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add((e=>{t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)})),t.afterRender=e.onAfterRenderObservable.add((e=>{e.getEngine().setStencilBuffer(t.stencilState)})),this._excludedMeshes[e.uniqueId]=t}}removeExcludedMesh(e){if(!this._excludedMeshes)return;const t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!!this._meshes&&!!super.hasMesh(e)&&void 0!==this._meshes[e.uniqueId]&&null!==this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;const s=this._meshes[e.uniqueId];s?s.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add((e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))})),observerDefault:e.onAfterRenderObservable.add((e=>{this.isEnabled&&this._defaultStencilReference(e)})),glowEmissiveOnly:i},e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;const t=this._meshes[e.uniqueId];t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(const e in this._meshes)if(this._meshes[e]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes)for(const e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){const t=this._meshes[e];t&&this.removeMesh(t.mesh)}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(u_.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(const e in this._meshes){const t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(const e in this._excludedMeshes){const t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){const e=Pe.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(const t in this._meshes){const i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(const t in this._excludedMeshes){const i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){const s=Pe.Parse((()=>new u_(e.name,t,e.options)),e,t,i);let r;for(r=0;rthis._drawCameraPredicate(t,!0,!0,e.layerMask)))}_drawCameraForegroundWithPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!0,e.layerMask)))}_drawCameraForegroundWithoutPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!1,e.layerMask)))}_drawRenderTargetPredicate(e,t,i,s,r){return e.renderTargetTextures.length>0&&e.isBackground===t&&e.applyPostProcess===i&&e.renderTargetTextures.indexOf(r)>-1&&!!(e.layerMask&s)}_drawRenderTargetBackground(e){this._draw((t=>this._drawRenderTargetPredicate(t,!0,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithoutPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!1,this.scene.activeCamera.layerMask,e)))}addFromContainer(e){e.layers&&e.layers.forEach((e=>{this.scene.layers.push(e)}))}removeFromContainer(e,t=!1){e.layers&&e.layers.forEach((e=>{const i=this.scene.layers.indexOf(e);-1!==i&&this.scene.layers.splice(i,1),t&&e.dispose()}))}}Ft.ShadersStore.layerPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef LINEAR\nbaseColor.rgb=toGammaSpace(baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.layerVertexShader="attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class p_{set applyPostProcess(e){this._applyPostProcess=e}get applyPostProcess(){return this.isBackground||this._applyPostProcess}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}constructor(e,t,i,s,r){this.name=e,this._applyPostProcess=!0,this.scale=new N(1,1),this.offset=new N(0,0),this.alphaBlendingMode=2,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this.isEnabled=!0,this._vertexBuffers={},this.onDisposeObservable=new g,this.onBeforeRenderObservable=new g,this.onAfterRenderObservable=new g,this.texture=t?new Zn(t,i,!0):null,this.isBackground=void 0===s||s,this.color=void 0===r?new j(1,1,1,1):r,this._scene=i||y.LastCreatedScene;let n=this._scene._getComponent(ts.NAME_LAYER);n||(n=new d_(this._scene),this._scene._addComponent(n)),this._scene.layers.push(this);const o=this._scene.getEngine();this._drawWrapper=new gr(o);const a=[];a.push(1,1),a.push(-1,1),a.push(-1,-1),a.push(1,-1);const l=new Ki(o,a,Ki.PositionKind,!1,!1,2);this._vertexBuffers[Ki.PositionKind]=l,this._createIndexBuffer()}_createIndexBuffer(){const e=this._scene.getEngine(),t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[Ki.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}isReady(){const e=this._scene.getEngine();let t="";this.alphaTest&&(t="#define ALPHATEST"),this.texture&&!this.texture.gammaSpace&&(t+="\n#define LINEAR"),this._previousDefines!==t&&(this._previousDefines=t,this._drawWrapper.effect=e.createEffect("layer",[Ki.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],t));const i=this._drawWrapper.effect;return i?.isReady()&&this.texture?.isReady()}render(){if(!this.isEnabled)return;const e=this._scene.getEngine();if(!this.isReady())return;const t=this._drawWrapper.effect;this.onBeforeRenderObservable.notifyObservers(this),e.enableEffect(this._drawWrapper),e.setState(!1),t.setTexture("textureSampler",this.texture),t.setMatrix("textureMatrix",this.texture.getTextureMatrix()),t.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),t.setVector2("offset",this.offset),t.setVector2("scale",this.scale),e.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.alphaTest?e.drawElementsType(Dn.TriangleFillMode,0,6):(e.setAlphaMode(this.alphaBlendingMode),e.drawElementsType(Dn.TriangleFillMode,0,6),e.setAlphaMode(0)),this.onAfterRenderObservable.notifyObservers(this)}dispose(){const e=this._vertexBuffers[Ki.PositionKind];e&&(e.dispose(),this._vertexBuffers[Ki.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null),this.renderTargetTextures=[];const t=this._scene.layers.indexOf(this);this._scene.layers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()}}class f_{static AddFlare(e,t,i,s,r){return new f_(e,t,i,s,r)}constructor(e,t,i,s,r){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new Y(1,1,1),this.texture=s?new Zn(s,r.getScene(),!0):null,this._system=r;const n=r.scene.getEngine();this._drawWrapper=new gr(n),this._drawWrapper.effect=n.createEffect("lensFlare",[Ki.PositionKind],["color","viewportMatrix"],["textureSampler"],""),r.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();const e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}Ft.ShadersStore.lensFlarePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.lensFlareVertexShader="attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class __{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||y.LastCreatedScene,__._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&!!(e.layerMask&i.activeCamera.layerMask);const s=i.getEngine(),r=[];r.push(1,1),r.push(-1,1),r.push(-1,-1),r.push(1,-1),this._vertexBuffers[Ki.PositionKind]=new Ki(s,r,Ki.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=w.Project(t,B.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=w.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);const i=this._scene.useRightHandedSystem;return!!(t.z>0&&!i||t.z<0&&i)&&(this._positionX>e.x&&this._positionXe.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;const e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();const i=new ao(this._scene.activeCamera.globalPosition,e),s=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!s||!s.hit||s.distance>t}render(){if(!this._scene.activeCamera)return!1;const e=this._scene.getEngine(),t=this._scene.activeCamera.viewport.toGlobal(e.getRenderWidth(!0),e.getRenderHeight(!0));if(!this.computeEffectivePosition(t))return!1;if(!this._isVisible())return!1;let i,s;i=this._positionXt.x+t.width-this.borderLimit?this._positionX-t.x-t.width+this.borderLimit:0,s=this._positionYt.y+t.height-this.borderLimit?this._positionY-t.y-t.height+this.borderLimit:0;let r=i>s?i:s;r-=this.viewportBorder,r>this.borderLimit&&(r=this.borderLimit);let n=1-G.Clamp(r/this.borderLimit,0,1);if(n<0)return!1;n>1&&(n=1),this.viewportBorder>0&&(t.x+=this.viewportBorder,t.y+=this.viewportBorder,t.width-=2*this.viewportBorder,t.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);const o=t.x+t.width/2,a=t.y+t.height/2,l=o-this._positionX,h=a-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let i=0;i{throw ye("LensFlareSystemSceneComponent")},p.AddParser(ts.NAME_LENSFLARESYSTEM,((e,t,i,s)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(let r=0,n=e.lensFlareSystems.length;r{this.scene.addLensFlareSystem(e)}))}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach((e=>{this.scene.removeLensFlareSystem(e),t&&e.dispose()}))}serialize(e){e.lensFlareSystems=[];const t=this.scene.lensFlareSystems;for(const i of t)e.lensFlareSystems.push(i.serialize())}dispose(){const e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){const t=this.scene.lensFlareSystems;Ii.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)e.layerMask&i.layerMask&&i.render();Ii.EndPerformanceCounter("Lens flares",t.length>0)}}}__._SceneComponentInitialization=e=>{let t=e._getComponent(ts.NAME_LENSFLARESYSTEM);t||(t=new m_(e),e._addComponent(t))};Ft.IncludesShadersStore.bayerDitherFunctions="float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);}\nfloat bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5*mod(_P,4.0)); \nreturn 4.0*bayerDither2(P1)+bayerDither2(P2);}\nfloat bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5 *mod(_P,4.0)); \nvec2 P4=floor(0.25*mod(_P,8.0)); \nreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}\n";Ft.IncludesShadersStore.shadowMapFragmentExtraDeclaration="#if SM_FLOAT==0\n#include\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include\nuniform float softTransparentShadowSM;\n#endif\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nuniform vec3 lightDataSM;varying vec3 vPositionWSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";Ft.IncludesShadersStore.shadowMapFragment="float depthSM=vDepthMetricSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\ndepthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_FragDepth=clamp(1.0-depthSM,0.0,1.0);\n#else\ngl_FragDepth=clamp(depthSM,0.0,1.0); \n#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);\n#endif\n#if SM_FLOAT==1\ngl_FragColor=vec4(depthSM,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depthSM);\n#endif\nreturn;";Ft.ShadersStore.shadowMapPixelShader="#include\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEXTURE\nfloat alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;\n#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard;\n#else\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;\n#endif\n#endif\n#include\n}";Ft.IncludesShadersStore.sceneVertexDeclaration="uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\nuniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition;\n";Ft.IncludesShadersStore.meshVertexDeclaration="uniform mat4 world;uniform float visibility;\n";Ft.IncludesShadersStore.shadowMapVertexDeclaration="#include\n#include\n";Ft.IncludesShadersStore.shadowMapUboDeclaration="layout(std140,column_major) uniform;\n#include\n#include\n";Ft.IncludesShadersStore.shadowMapVertexExtraDeclaration="#if SM_NORMALBIAS==1\nuniform vec3 lightDataSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nvarying vec3 vPositionWSM;\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";Ft.IncludesShadersStore.shadowMapVertexNormalBias="#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvec3 worldLightDirSM=normalize(-lightDataSM.xyz);\n#else\nvec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM);\n#endif\nfloat ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM;\n#endif\n";Ft.IncludesShadersStore.shadowMapVertexMetric="#if SM_USEDISTANCE==1\nvPositionWSM=worldPos.xyz;\n#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#else\ngl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nzSM=gl_Position.z;gl_Position.z=0.0;\n#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\nvDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n";Ft.ShadersStore.shadowMapVertexShader="attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;\n#endif\n#include\n#include<__decl__shadowMapVertex>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normWorldSM=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvec3 vNormalW=normalize(normWorldSM*normalUpdated);\n#endif\n#endif\n#include\ngl_Position=viewProjection*worldPos;\n#include\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}";Ft.ShadersStore.depthBoxBlurPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}";Ft.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow="#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;\n#endif\n";class g_{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===g_.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(e===g_.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(e===g_.FILTER_PCF||e===g_.FILTER_PCSS)return void(this.usePoissonSampling=!0)}e!==g_.FILTER_PCF&&e!==g_.FILTER_PCSS||this._scene.getEngine()._features.supportShadowSamplers?this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0}get usePoissonSampling(){return this.filter===g_.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(g_.FILTER_POISSONSAMPLING);(e||this.filter===g_.FILTER_POISSONSAMPLING)&&(this.filter=e?t:g_.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===g_.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(g_.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===g_.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:g_.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===g_.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(g_.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===g_.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:g_.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===g_.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(g_.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===g_.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:g_.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===g_.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(g_.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===g_.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:g_.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===g_.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(g_.FILTER_PCF);(e||this.filter===g_.FILTER_PCF)&&(this.filter=e?t:g_.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===g_.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(g_.FILTER_PCSS);(e||this.filter===g_.FILTER_PCSS)&&(this.filter=e?t:g_.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return this._darkness=e>=1?1:e<=0?0:e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return g_.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(const t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(const t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}_getCamera(){return this._camera??this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,s,r){this.onBeforeShadowMapRenderObservable=new g,this.onAfterShadowMapRenderObservable=new g,this.onBeforeShadowMapRenderMeshObservable=new g,this.onAfterShadowMapRenderMeshObservable=new g,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=g_.FILTER_NONE,this._filteringQuality=g_.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=w.Zero(),this._viewMatrix=B.Zero(),this._projectionMatrix=B.Zero(),this._transformMatrix=B.Zero(),this._cachedPosition=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=B.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=s??null,this._useRedTextureType=!!r;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),g_._SceneComponentInitialization(this._scene);const o=this._scene.getEngine().getCaps();i?o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new da(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForShadowGenerator-${this._light.name}`)):this._shadowMap=new da(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=Zn.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=Zn.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(Zn.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,s)=>this._renderForShadowMap(e,t,i,s),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`shadow map generation for pass id ${e.currentRenderPassId}`,1)})),this._shadowMap.onBeforeRenderObservable.add((t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===g_.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onAfterUnbindObservable.add((()=>{if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===g_.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap)return void e._debugPopGroup?.(1);const t=this.getShadowMapForRendering();t&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,t.renderTarget,!0),e.unBindFramebuffer(t.renderTarget,!0),e._debugPopGroup?.(1))}));const t=new j(0,0,0,0),i=new j(1,1,1,1);this._shadowMap.onClearObservable.add((e=>{this._filter===g_.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)})),this._shadowMap.onResizeObservable.add((e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}));for(let e=es.MIN_RENDERINGGROUPS;e{e.setTexture("textureSampler",this._shadowMap)})),this._kernelBlurYPostprocess=new Jp(this._light.name+"KernelBlurY",new N(0,1),this.blurKernel,1,null,Zn.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new Ko(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,Zn.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add((e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,s){let r;if(s.length)for(r=0;r{s===i||e?(s.getMeshUniformBuffer().bindToEffect(h,"Mesh"),s.transferToEffect(e?t:p)):(i.getMeshUniformBuffer().bindToEffect(h,"Mesh"),i.transferToEffect(t))})),this.forceBackFacesOnly&&n.setState(!0,0,!1,!1,o.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(h),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===g_.FILTER_NONE||this.filter===g_.FILTER_PCSS?this._shadowMap.updateSamplingMode(Zn.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(Zn.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},s=this.getShadowMap();if(!s)return void(e&&e(this));const r=s.renderList;if(!r)return void(e&&e(this));const n=[];for(const e of r)n.push(...e.subMeshes);if(0===n.length)return void(e&&e(this));let o=0;const a=()=>{if(this._scene&&this._scene.getEngine()){for(;this.isReady(n[o],i.useInstances,n[o].getMaterial()?.needAlphaBlendingForMesh(n[o].getMesh())??!1);)if(o++,o>=n.length)return void(e&&e(this));setTimeout(a,16)}};a()}forceCompilationAsync(e){return new Promise((t=>{this.forceCompilation((()=>{t()}),e)}))}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,s){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const r=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&r.isVerticesDataPresent(Ki.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Gn.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&s?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){const s=e.getMaterial(),r=s?.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;const n=[];if(this._prepareShadowDefines(e,t,n,i),r){if(!r.isReadyForSubMesh(e,n,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const i=e._getDrawWrapper(void 0,!0);let r=i.effect,o=i.defines;const a=[Ki.PositionKind],l=e.getMesh();this.normalBias&&l.isVerticesDataPresent(Ki.NormalKind)&&(a.push(Ki.NormalKind),n.push("#define NORMAL"),l.nonUniformScaling&&n.push("#define NONUNIFORMSCALING"));const h=s.needAlphaTesting();if((h||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const e=s.alphaCutOff??g_.DEFAULT_ALPHA_CUTOFF;n.push("#define ALPHATEXTURE"),h&&n.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),l.isVerticesDataPresent(Ki.UVKind)&&(a.push(Ki.UVKind),n.push("#define UV1")),l.isVerticesDataPresent(Ki.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(a.push(Ki.UV2Kind),n.push("#define UV2"))}const c=new Yo;if(l.useBones&&l.computeBonesUsingShaders&&l.skeleton){a.push(Ki.MatricesIndicesKind),a.push(Ki.MatricesWeightsKind),l.numBoneInfluencers>4&&(a.push(Ki.MatricesIndicesExtraKind),a.push(Ki.MatricesWeightsExtraKind));const e=l.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+l.numBoneInfluencers),l.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,l),e.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(e.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");const u=l.morphTargetManager;let d=0;if(u&&(d=u.numMaxInfluencers||u.numInfluencers,d>0&&(n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+d),u.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),tn(a,l,d))),$r(s,this._scene,n),t&&(n.push("#define INSTANCES"),rn(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const e of this.customShaderOptions.defines)-1===n.indexOf(e)&&n.push(e);const p=l.bakedVertexAnimationManager;t&&p&&p.isEnabled&&(n.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),a.push("bakedVertexAnimationSettingsInstanced"));const f=n.join("\n");if(o!==f){o=f;let e="shadowMap";const t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],s=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],n=["Scene","Mesh"];if(jr(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const e of this.customShaderOptions.attributes)-1===a.indexOf(e)&&a.push(e);if(this.customShaderOptions.uniforms)for(const e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(const e of this.customShaderOptions.samplers)-1===s.indexOf(e)&&s.push(e)}const l=this._scene.getEngine();r=l.createEffect(e,{attributes:a,uniformsNames:t,uniformBuffersNames:n,samplers:s,defines:f,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:d}},l),i.setEffect(r,o)}if(!r.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){const i=this._scene,s=this._light;i.shadowsEnabled&&s.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===g_.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===g_.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===g_.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===g_.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),s.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();if(!r)return;i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix());const n=this.getShadowMapForRendering();this._filter===g_.FILTER_PCF?(t.setDepthStencilTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),r.getSize().width,1/r.getSize().width,this.frustumEdgeFalloff,e)):this._filter===g_.FILTER_PCSS?(t.setDepthStencilTexture("shadowTexture"+e,n),t.setTexture("depthTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/r.getSize().width,this._contactHardeningLightSizeUVRatio*r.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/r.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e)}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){const e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),w.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(w.Dot(this._lightDirection,w.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),B.LookAtLHToRef(t,t.add(this._lightDirection),w.Up(),this._viewMatrix);const e=this.getShadowMap();if(e){const t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){const e=this._shadowMap;if(!e)return;const t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(const e of t)this._shadowMap.renderList.push(e)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){const e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){const e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=this._camera?.id,e.id=this.id,e.mapSize=t.getRenderSize(),e.forceBackFacesOnly=this.forceBackFacesOnly,e.darkness=this.getDarkness(),e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.filteringQuality=this.filteringQuality,e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.depthScale=this.depthScale,e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.renderList=[],t.renderList)for(let i=0;i{throw ye("ShadowGeneratorSceneComponent")};Ft.ShadersStore.depthPixelShader="#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\nvarying float vDepthMetric;\n#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\n#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\n#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\n#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";Ft.IncludesShadersStore.pointCloudVertexDeclaration="#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";Ft.ShadersStore.depthVertexShader="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;uniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;varying vec4 vViewPos;\n#endif\n#include\nvarying float vDepthMetric;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#include\ngl_Position=viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\n#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}\n";class v_{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,s=!1,r=Zn.TRILINEAR_SAMPLINGMODE,n=!1,o){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=s,this._storeCameraSpaceZ=n,this.isPacked=0===t,this.isPacked?this.clearColor=new j(1,1,1,1):this.clearColor=new j(n?1e8:1,0,0,1),v_._SceneComponentInitialization(this._scene);const a=e.getEngine();this._camera=i,r!==Zn.NEAREST_SAMPLINGMODE&&(1!==t||a._caps.textureFloatLinearFiltering||(r=Zn.NEAREST_SAMPLINGMODE),2!==t||a._caps.textureHalfFloatLinearFiltering||(r=Zn.NEAREST_SAMPLINGMODE));const l=this.isPacked||!a._features.supportExtendedTextureFormats?5:6;this._depthMap=new da(o??"DepthRenderer",{width:a.getRenderWidth(),height:a.getRenderHeight()},this._scene,!1,!0,t,!1,r,void 0,void 0,void 0,l),this._depthMap.wrapU=Zn.CLAMP_ADDRESSMODE,this._depthMap.wrapV=Zn.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((e=>{e.clear(this.clearColor,!0,!0,!0)})),this._depthMap.onBeforeBindObservable.add((()=>{a._debugPushGroup?.("depth renderer",1)})),this._depthMap.onAfterUnbindObservable.add((()=>{a._debugPopGroup?.(1)})),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),s=this._scene,r=s.getEngine(),n=e.getMaterial();if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!n||i.infiniteDistance||n.disableDepthWrite||0===e.verticesCount||e._renderId===s.getRenderId())return;const o=i._getWorldMatrixDeterminant()<0;let a=t.overrideMaterialSideOrientation??n.sideOrientation;o&&(a=0===a?1:0);const l=0===a;r.setState(n.backFaceCulling,0,!1,l,this.reverseCulling?!n.cullBackFaces:n.cullBackFaces);const h=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(h.mustReturn)return;const c=r.getCaps().instancedArrays&&(null!==h.visibleInstances[e._id]&&void 0!==h.visibleInstances[e._id]||t.hasThinInstances),u=this._camera||s.activeCamera;if(this.isReady(e,c)&&u){e._renderId=s.getRenderId();const o=i._internalAbstractMeshDataInfo._materialForRenderPass?.[r.currentRenderPassId];let a=e._getDrawWrapper();!a&&o&&(a=o._getDrawWrapper());const l=u.mode===or.ORTHOGRAPHIC_CAMERA;if(!a)return;const d=a.effect;let p,f;if(r.enableEffect(a),c||t._bind(e,d,n.fillMode),o?o.bindForSubMesh(i.getWorldMatrix(),i,e):(d.setMatrix("viewProjection",s.getTransformMatrix()),d.setMatrix("world",i.getWorldMatrix()),this._storeCameraSpaceZ&&d.setMatrix("view",s.getViewMatrix())),l?(p=!r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1,f=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1):(p=r.useReverseDepthBuffer&&r.isNDCHalfZRange?u.minZ:r.isNDCHalfZRange?0:u.minZ,f=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:u.maxZ),d.setFloat2("depthValues",p,p+f),!o){if(n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(d.setTexture("diffuseSampler",e),d.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices){const i=e.getTransformMatrixTexture(t);if(!i)return;d.setTexture("boneSampler",i),d.setFloat("boneTextureWidth",4*(e.bones.length+1))}else d.setMatrices("mBones",e.getTransformMatrices(t))}Kr(d,n,s),nn(t,d),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(d),n.pointsCloud&&d.setFloat("pointSize",n.pointSize)}t._processRendering(i,e,d,n.fillMode,h,c,((e,t)=>d.setMatrix("world",t)))}};this._depthMap.customRenderFunction=(e,t,i,s)=>{let r;if(s.length)for(r=0;r4&&(l.push(Ki.MatricesIndicesExtraKind),l.push(Ki.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),a.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));const t=e.getRenderingMesh().skeleton;t?.isUsingTextureForMatrices&&a.push("#define BONETEXTURE")}else a.push("#define NUM_BONE_INFLUENCERS 0");const h=s.morphTargetManager;let c=0;h&&(c=h.numMaxInfluencers||h.numInfluencers,c>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+c),h.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),tn(l,s,c))),o.pointsCloud&&a.push("#define POINTSIZE"),t&&(a.push("#define INSTANCES"),rn(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&a.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&a.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&a.push("#define PACKED"),$r(o,r,a);const u=e._getDrawWrapper(void 0,!0),d=u.defines,p=a.join("\n");if(d!==p){const e=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];jr(e),u.setEffect(i.createEffect("depth",l,e,["diffuseSampler","morphTargets","boneSampler"],p,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),p)}return u.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}v_._SceneComponentInitialization=e=>{throw ye("DepthRendererSceneComponent")};Ft.ShadersStore.minmaxReduxPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#if defined(INITIAL)\nuniform sampler2D sourceTexture;uniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4);\n#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\n#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\n#endif\nglFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(MAIN)\nuniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(LAST)\nvoid main(void)\n{glFragColor=vec4(0.);if (true) { \ndiscard;}}\n#endif\n";class x_{constructor(e){this.onAfterReductionPerformed=new g,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new Qi(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{this._postProcessManager._rebuild()}))}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,s=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=s;const r=this._camera.getScene(),n=new Ko("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,r.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);n.autoClear=!1,n.forceFullscreenViewport=s;let o=this._sourceTexture.getRenderWidth(),a=this._sourceTexture.getRenderHeight();n.onApply=((e,t)=>i=>{i.setTexture("sourceTexture",this._sourceTexture),i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(n);let l=1;for(;o>1||a>1;){o=Math.max(Math.round(o/2),1),a=Math.max(Math.round(a/2),1);const e=new Ko("Reduction phase "+l,"minmaxRedux",["texSize"],null,{width:o,height:a},null,1,r.getEngine(),!1,"#define "+(1==o&&1==a?"LAST":1==o||1==a?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=s,e.onApply=((e,t)=>i=>{1==e||1==t?i.setInt2("texSize",e,t):i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(e),l++,1==o&&1==a){const t=(e,t,i)=>{const s=new Float32Array(4*e*t),n={min:0,max:0};return()=>{r.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,s,!1),n.min=s[0],n.max=s[1],this.onAfterReductionPerformed.notifyObservers(n)}};e.onAfterRenderObservable.add(t(o,a,e))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add((()=>{const e=this._camera.getScene().getEngine();e._debugPushGroup?.("min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),e.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),e._debugPopGroup?.(1)})),this._activated=!0)}deactivate(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let e=0;ethis._computeShadowCastersBoundingInfo()))),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){const e=this._shadowMap.renderList;for(let t=0;tt&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return A_.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let t=e.min,i=e.max;t>=i&&(t=0,i=1),t==this._minDistance&&i==this._maxDistance||this.setMinMaxDistance(t,i)})),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate??-1}set autoCalcDepthBoundsRefreshRate(e){this._depthReducer?.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,s=i-t,r=this._minDistance,n=t+r*s,o=t+(this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance)*s,a=o-n,l=o/n;for(let e=0;e{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===g_.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()})),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==g_.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,s=this._light;if(!i.shadowsEnabled||!s.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const r=this._getCamera();r&&this._shadowMaxZ<=(r.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();if(!r)return;const n=r.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===g_.FILTER_PCF)t.setDepthStencilTexture("shadowTexture"+e,r),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n,1/n,this.frustumEdgeFalloff,e);else if(this._filter===g_.FILTER_PCSS){for(let e=0;enew A_(e,t,void 0,i)));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}A_._FrustumCornersNDCSpace=[new w(-1,1,-1),new w(1,1,-1),new w(1,-1,-1),new w(-1,-1,-1),new w(-1,1,1),new w(1,1,1),new w(1,-1,1),new w(-1,-1,1)],A_.CLASSNAME="CascadedShadowGenerator",A_.DEFAULT_CASCADES_COUNT=4,A_.MIN_CASCADES_COUNT=2,A_.MAX_CASCADES_COUNT=4,A_._SceneComponentInitialization=e=>{throw ye("ShadowGeneratorSceneComponent")},p.AddParser(ts.NAME_SHADOWGENERATOR,((e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,s=e.shadowGenerators.length;i{let t=e._getComponent(ts.NAME_SHADOWGENERATOR);t||(t=new R_(e),e._addComponent(t))},De.AddNodeConstructor("Light_Type_0",((e,t)=>()=>new I_(e,w.Zero(),t)));class I_ extends jp{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){const t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return Gn.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new w(1,0,0);case 1:return new w(-1,0,0);case 2:return new w(0,-1,0);case 3:return new w(0,1,0);case 4:return new w(0,0,1);case 5:return new w(0,0,-1)}return w.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;const r=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;B.PerspectiveFovLHToRef(this.shadowAngle,1,o?n:r,o?r:n,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}}ae([pe()],I_.prototype,"shadowAngle",null),u("BABYLON.PointLight",I_);class P_{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css",this._style.innerHTML="@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }",document.getElementsByTagName("head")[0].appendChild(this._style);const e=!!window.SVGSVGElement,t=new Image;P_.DefaultLogoUrl?t.src=P_.DefaultLogoUrl:t.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",t.style.width="150px",t.style.gridColumn="1",t.style.gridRow="1",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.position="absolute";const i=document.createElement("div");i.style.width="300px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const s=new Image;if(P_.DefaultSpinnerUrl?s.src=P_.DefaultSpinnerUrl:s.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!e){const e={w:16,h:18.5},i={w:30,h:30};t.style.width=`${e.w}vh`,t.style.height=`${e.h}vh`,t.style.left=`calc(50% - ${e.w/2}vh)`,t.style.top=`calc(50% - ${e.h/2}vh)`,s.style.width=`${i.w}vh`,s.style.height=`${i.h}vh`,s.style.left=`calc(50% - ${i.w/2}vh)`,s.style.top=`calc(50% - ${i.h/2}vh)`}i.appendChild(s),this._loadingDiv.appendChild(t),this._loadingDiv.appendChild(i),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",(()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)})))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}P_.DefaultLogoUrl="",P_.DefaultSpinnerUrl="",si.DefaultLoadingScreenFactory=e=>new P_(e);class M_{static ConvertPanoramaToCubemap(e,t,i,s,r=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(s,this.FACE_FRONT,e,t,i,r),back:this.CreateCubemapTexture(s,this.FACE_BACK,e,t,i,r),left:this.CreateCubemapTexture(s,this.FACE_LEFT,e,t,i,r),right:this.CreateCubemapTexture(s,this.FACE_RIGHT,e,t,i,r),up:this.CreateCubemapTexture(s,this.FACE_UP,e,t,i,r),down:this.CreateCubemapTexture(s,this.FACE_DOWN,e,t,i,r),size:s,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,s,r,n=!1){const o=new ArrayBuffer(e*e*4*3),a=new Float32Array(o),l=n?Math.max(1,Math.round(s/4/e)):1,h=1/l,c=h*h,u=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),p=1/e;let f=0;for(let n=0;nMath.PI;)r-=2*Math.PI;let o=r/Math.PI;const a=n/Math.PI;o=.5*o+.5;let l=Math.round(o*i);l<0?l=0:l>=i&&(l=i-1);let h=Math.round(a*s);h<0?h=0:h>=s&&(h=s-1);const c=s-h-1;return{r:t[c*i*3+3*l+0],g:t[c*i*3+3*l+1],b:t[c*i*3+3*l+2]}}}M_.FACE_LEFT=[new w(-1,-1,-1),new w(1,-1,-1),new w(-1,1,-1),new w(1,1,-1)],M_.FACE_RIGHT=[new w(1,-1,1),new w(-1,-1,1),new w(1,1,1),new w(-1,1,1)],M_.FACE_FRONT=[new w(1,-1,-1),new w(1,-1,1),new w(1,1,-1),new w(1,1,1)],M_.FACE_BACK=[new w(-1,-1,1),new w(-1,-1,-1),new w(-1,1,1),new w(-1,1,-1)],M_.FACE_DOWN=[new w(1,1,-1),new w(1,1,1),new w(-1,1,-1),new w(-1,1,1)],M_.FACE_UP=[new w(-1,-1,-1),new w(-1,-1,1),new w(1,-1,-1),new w(1,-1,1)];class D_{static _Ldexp(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,s,r,n){r>0?(r=this._Ldexp(1,r-136),e[n+0]=t*r,e[n+1]=i*r,e[n+2]=s*r):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}static _ReadStringLine(e,t){let i="",s="";for(let r=t;r32767)throw"HDR Bad header format, unsupported size";return o+=s.length+1,{height:t,width:i,dataPosition:o}}static GetCubeMapTextureData(e,t,i=!1){const s=new Uint8Array(e),r=this.RGBE_ReadHeader(s),n=this.RGBE_ReadPixels(s,r);return M_.ConvertPanoramaToCubemap(n,r.width,r.height,t,i)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i=t.height;const s=t.width;let r,n,o,a,l,h=t.dataPosition,c=0,u=0,d=0;const p=new ArrayBuffer(4*s),f=new Uint8Array(p),_=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(_);for(;i>0;){if(r=e[h++],n=e[h++],o=e[h++],a=e[h++],2!=r||2!=n||128&o||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((o<<8|a)!=s)throw"HDR Bad header format, wrong scan line width";for(c=0,d=0;d<4;d++)for(u=(d+1)*s;c128){if(l=r-128,0==l||l>u-c)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)f[c++]=n}else{if(l=r,0==l||l>u-c)throw"HDR Bad Format, bad scanline data (non-run)";if(f[c++]=n,--l>0)for(let t=0;t0;){for(l=0;l{this._effectRenderer=new na(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled((()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()}))})):(J.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}}class N_ extends qn{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(B.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,s=!1,r=!0,n=!1,o=!1,a=null,l=null,h=!1){super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=w.Zero(),this.onLoadObservable=new g,e&&(this._coordinatesMode=Zn.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=B.Identity(),this._prefilterOnLoad=o,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),a&&a()},this._onError=l,this.gammaSpace=n,this._noMipmap=s,this._size=i,this._supersample=h,this._generateHarmonics=r,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?Ii.SetImmediate((()=>this._onLoad())):this._texture.onLoadedObservable.add(this._onLoad):this.getScene()?.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture())}getClassName(){return"HDRCubeTexture"}_loadTexture(){const e=this._getEngine(),t=e.getCaps();let i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const t=this._onLoad,i=new O_(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,(e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const t=D_.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){const e=Jc.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}const s=[];let r=null,n=null;for(let e=0;e<6;e++){2===i?n=new Uint16Array(this._size*this._size*3):0===i&&(r=new Uint8Array(this._size*this._size*3));const o=t[N_._FacesMapping[e]];if(this.gammaSpace||n||r)for(let e=0;e255){const e=255/n;t*=e,i*=e,s*=e}r[3*e+0]=t,r[3*e+1]=i,r[3*e+2]=s}n?s.push(n):r?s.push(r):s.push(o)}return s}),null,this._onLoad,this._onError)}clone(){const e=new N_(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&this.getScene()?.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(this)))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let s=null;return e.name&&!e.isRenderTarget&&(s=new N_(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),s.name=e.name,s.hasAlpha=e.hasAlpha,s.level=e.level,s.coordinatesMode=e.coordinatesMode,s.isBlocking=e.isBlocking),s&&(e.boundingBoxPosition&&(s.boundingBoxPosition=w.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=w.FromArray(e.boundingBoxSize)),e.rotationY&&(s.rotationY=e.rotationY)),s}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}N_._FacesMapping=["right","left","up","down","front","back"],u("BABYLON.HDRCubeTexture",N_);class w_{get influence(){return this._influence}set influence(e){if(this._influence===e)return;const t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new g,this._onDataLayoutChanged=new g,this._animationPropertiesOverride=null,this._scene=i||y.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}setPositions(e){const t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){const t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){const t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){const t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){const e=Pe.Clone((()=>new w_(this.name,this.influence,this._scene)),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e}serialize(){const e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),null!=this.id&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),Pe.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new w_(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Mi(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=y.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._syncActiveTargets(!0))}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get numTargets(){return this._targets.length}get numInfluencers(){return this._activeTargets.length}get influences(){return this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets=e}get isUsingTextureForTargets(){return L_.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!this._scene?.getEngine().getCaps().disableMorphTargetTexture}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}getTargetByName(e){for(const t of this._targets)if(t.name===e)return t;return null}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add((e=>{this._syncActiveTargets(e)}))),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add((()=>{this._syncActiveTargets(!0)}))),this._syncActiveTargets(!0)}removeTarget(e){const t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0)),this._scene&&this._scene.stopAnimation(e)}_bind(e){e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setInt("morphTargetCount",this.numInfluencers)}clone(){const e=new L_(this._scene);for(const t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){const e={};e.id=this.uniqueId,e.targets=[];for(const t of this._targets)e.targets.push(t.serialize());return e}_syncActiveTargets(e){if(this.areUpdatesFrozen)return;let t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),this._morphTargetTextureIndices&&this._morphTargetTextureIndices.length===this._targets.length||(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let i=-1;for(const e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=L_.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;const s=e.getPositions();if(s){const e=s.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e)return void J.Error("Incompatible target. Targets must all have the same vertices count.")}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e0)){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;const e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){const e=this._targetStoreTexture.getSize();e.width===this._textureWidth&&e.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4);let i=0;for(let s=0;s-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(const e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){const i=new L_(t);i._uniqueId=e.id;for(const s of e.targets)i.addTarget(w_.Parse(s,t));return i}}L_.EnableTextureStorage=!0,L_.MaxActiveMorphTargetsInVertexAttributeMode=8;class B_{constructor(){this._hasHit=!1,this._hitNormal=w.Zero(),this._hitPoint=w.Zero(),this._triangleIndex=-1}get hitPoint(){return this._hitPoint}get hitNormal(){return this._hitNormal}get hasHit(){return this._hasHit}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormal.set(e.x,e.y,e.z),this._hitPoint.set(t.x,t.y,t.z),this._triangleIndex=i??-1}reset(){this._hasHit=!1,this._hitNormal.setAll(0),this._hitPoint.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0,this.shape=void 0}}class V_ extends B_{constructor(){super(...arguments),this._hitDistance=0,this._rayFromWorld=w.Zero(),this._rayToWorld=w.Zero()}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormal}get hitPointWorld(){return this._hitPoint}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=w.Distance(this._rayFromWorld,this._hitPoint)}reset(e=w.Zero(),t=w.Zero()){super.reset(),this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hitDistance=0}}class U_{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw ye("CannonJSPlugin")}constructor(e,t=U_.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new w(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){const t=this._impostors.indexOf(e);t>-1&&this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)}addJoint(e,t,i){const s={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(s),this._physicsPlugin.generateJoint(s)}removeJoint(e,t,i){const s=this._joints.filter((function(s){return s.connectedImpostor===t&&s.joint===i&&s.mainImpostor===e}));s.length&&this._physicsPlugin.removeJoint(s[0])}_step(e){this._impostors.forEach((e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t0&&(this._physicsBodiesToRemoveAfterStep.forEach((e=>{"function"==typeof this.world.removeBody?this.world.removeBody(e):this.world.remove(e)})),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(r,s)}applyForce(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(r,s)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const t=this._createShape(e);if(!t)return void J.Warn("It was not possible to create a physics body for this object.");const i=e.physicsBody;i&&this.removePhysicsBody(e);const s=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),r={mass:e.getParam("mass"),material:s},n=e.getParam("nativeOptions");for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(r[e]=n[e]);e.physicsBody=new this.BJSCANNON.Body(r),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){const s=i[t];e.physicsBody[t].set(s.x,s.y,s.z)})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}}_processChildMeshes(e){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],i=e.object.rotationQuaternion;if(i?i.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),t.length){const i=t=>{if(!t.rotationQuaternion)return;const s=t.getPhysicsImpostor();if(s&&s.parent!==e&&t.parent){const i=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),r=t.rotationQuaternion.multiply(this._tmpQuaternion);s.physicsBody&&(this.removePhysicsBody(s),s.physicsBody=null),s.parent=e,s.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(s),new this.BJSCANNON.Vec3(i.x,i.y,i.z),new this.BJSCANNON.Quaternion(r.x,r.y,r.z,r.w)),e.physicsBody.mass+=s.getParam("mass")}t.getChildMeshes(!0).filter((e=>!!e.physicsImpostor)).forEach(i)};t.filter((e=>!!e.physicsImpostor)).forEach(i)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;let s;const r=e.joint.jointData,n={pivotA:r.mainPivot?(new this.BJSCANNON.Vec3).set(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z):null,pivotB:r.connectedPivot?(new this.BJSCANNON.Vec3).set(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z):null,axisA:r.mainAxis?(new this.BJSCANNON.Vec3).set(r.mainAxis.x,r.mainAxis.y,r.mainAxis.z):null,axisB:r.connectedAxis?(new this.BJSCANNON.Vec3).set(r.connectedAxis.x,r.connectedAxis.y,r.connectedAxis.z):null,maxForce:r.nativeParams.maxForce,collideConnected:!!r.collision};switch(e.joint.type){case mo.HingeJoint:case mo.Hinge2Joint:s=new this.BJSCANNON.HingeConstraint(t,i,n);break;case mo.DistanceJoint:s=new this.BJSCANNON.DistanceConstraint(t,i,r.maxDistance||2);break;case mo.SpringJoint:{const e=r;s=new this.BJSCANNON.Spring(t,i,{restLength:e.length,stiffness:e.stiffness,damping:e.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break}case mo.LockJoint:s=new this.BJSCANNON.LockConstraint(t,i,n);break;case mo.PointToPointJoint:case mo.BallAndSocketJoint:default:s=new this.BJSCANNON.PointToPointConstraint(t,n.pivotA,i,n.pivotB,n.maxForce)}s.collideConnected=!!r.collision,e.joint.physicsJoint=s,e.joint.type!==mo.SpringJoint?this.world.addConstraint(s):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){s.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==mo.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let s,r;for(s=0;s1e3*i));e++);this.time+=s;const a=this.time%i/i,l=e,h=this.bodies;for(let e=0;e!==h.length;e++){const i=h[e];i.type!==t.Body.STATIC&&i.sleepState!==t.Body.SLEEPING?(i.position.vsub(i.previousPosition,l),l.scale(a,l),i.position.vadd(l,i.interpolatedPosition)):(i.interpolatedPosition.set(i.position.x,i.position.y,i.position.z),i.interpolatedQuaternion.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w))}}}}raycast(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))}}U_.DefaultPluginFactory=()=>new k_;class G_{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=w.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new V_}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this.world.timeStep=e}getTimeStep(){return this.world.timeStep}executeStep(e,t){t.forEach((function(e){e.beforeStep()})),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach((e=>{e.afterStep(),this._tmpImpostorsArray[e.uniqueId]=e}));let i=this.world.contacts;for(;null!==i;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];e&&t?(e.onCollide({body:t.physicsBody,point:null,distance:0,impulse:0,normal:null}),t.onCollide({body:e.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next):i=i.next}}applyImpulse(e,t,i){const s=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*s))}applyForce(e,t,i){J.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},s=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach((function(e){e.physicsImpostor&&s.push(e.physicsImpostor)}));const r=e=>Math.max(e,T),n=new L;s.forEach((t=>{if(!t.object.rotationQuaternion)return;const s=t.object.rotationQuaternion;n.copyFrom(s),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);const o=n.toEulerAngles(),a=t.getObjectExtents(),l=57.29577951308232;if(t===e){const t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{const e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(o.x*l,o.y*l,o.z*l)}switch(t.object.rotationQuaternion.copyFrom(n),t.type){case go.ParticleImpostor:J.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case go.SphereImpostor:{const e=a.x,t=a.y,s=a.z,n=Math.max(r(e),r(t),r(s))/2;i.type.push("sphere"),i.size.push(n),i.size.push(n),i.size.push(n);break}case go.CylinderImpostor:{const e=r(a.x)/2,t=r(a.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case go.PlaneImpostor:case go.BoxImpostor:default:{const e=r(a.x),t=r(a.y),s=r(a.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(s);break}}t.object.rotationQuaternion=s})),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(n),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}var t}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const s=e.joint.jointData,r=s.nativeParams||{};let n;const o={body1:t,body2:i,axe1:r.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:r.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:r.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:r.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:r.min,max:r.max,collision:r.collision||s.collision,spring:r.spring,world:this.world};switch(e.joint.type){case mo.BallAndSocketJoint:n="jointBall";break;case mo.SpringJoint:{J.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const e=s;o.min=e.length||o.min,o.max=Math.max(o.min,o.max)}case mo.DistanceJoint:n="jointDistance",o.max=s.maxDistance;break;case mo.PrismaticJoint:n="jointPrisme";break;case mo.SliderJoint:n="jointSlide";break;case mo.WheelJoint:n="jointWheel";break;case mo.HingeJoint:default:n="jointHinge"}o.type=n,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){J.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{const t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){const t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){const s=e.physicsBody;e.physicsBody.shapes.next||(s.position.set(t.x,t.y,t.z),s.orientation.set(i.x,i.y,i.z,i.w),s.syncShapes(),s.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){const t=e.physicsBody.linearVelocity;return t?new w(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new w(t.x,t.y,t.z):null}setBodyMass(e,t){const i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,s){void 0!==i?J.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setMotor(t,i)}setLimit(e,t,i,s){const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setLimit(t,void 0===i?-t:i)}syncMeshWithImpostor(e,t){const i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)}getRadius(e){return e.physicsBody.shapes.radius}getBoxSizeToRef(e,t){const i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth}dispose(){this.world.clear()}raycast(e,t){return J.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){J.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class z_{constructor(e=!0,t=Ammo,i=null){this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new L,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new w,this._tmpContactNormal=new w,this._tmpVec3=new w,this._tmpMatrix=new B,"function"!=typeof t?(this.bjsAMMO=t,this.isSupported()?(this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=e=>{const t=(e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint)).getPositionWorldOnA(),i=e.m_normalWorldOnB;this._tmpContactPoint.x=t.x(),this._tmpContactPoint.y=t.y(),this._tmpContactPoint.z=t.z(),this._tmpContactNormal.x=i.x(),this._tmpContactNormal.y=i.y(),this._tmpContactNormal.z=i.z(),this._tmpContactImpulse=e.getAppliedImpulse(),this._tmpContactDistance=e.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new V_,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)):J.Error("AmmoJS is not available. Please make sure you included the js file.")):J.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.")}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(e))for(const t of e._onPhysicsCollideCallbacks)for(const i of t.otherImpostors)(e.physicsBody.isActive()||i.physicsBody.isActive())&&this._isImpostorPairInContact(e,i)&&(e.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),i.onCollide({body:e.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===go.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let s,r,n,o,a;const l=new Array;for(let e=0;e{this.bjsAMMO.destroy(e)})),e._pluginData.toDispose=[]))}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;if(e.joint.physicsJoint)return;const s=e.joint.jointData;let r;switch(s.mainPivot||(s.mainPivot=new w(0,0,0)),s.connectedPivot||(s.connectedPivot=new w(0,0,0)),e.joint.type){case mo.DistanceJoint:{const e=s.maxDistance;e&&(s.mainPivot=new w(0,-e/2,0),s.connectedPivot=new w(0,e/2,0));const n=this._tmpAmmoVectorA;n.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const o=this._tmpAmmoVectorB;o.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,n,o);break}case mo.HingeJoint:{s.mainAxis||(s.mainAxis=new w(0,0,0)),s.connectedAxis||(s.connectedAxis=new w(0,0,0));const e=this._tmpAmmoVectorA;e.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z);const o=this._tmpAmmoVectorC;o.setValue(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z);const a=this._tmpAmmoVectorD;a.setValue(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z),r=new this.bjsAMMO.btHingeConstraint(t,i,e,n,o,a);break}case mo.BallAndSocketJoint:{const e=this._tmpAmmoVectorA;e.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,e,n);break}default:{J.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint");const e=this._tmpAmmoVectorA;e.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,e,n);break}}this.world.addConstraint(r,!e.joint.jointData.collision),e.joint.physicsJoint=r}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint),this.bjsAMMO.destroy(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n,o=i.getVerticesData(Ki.PositionKind);if(o||(o=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?L.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):L.Identity(),B.Compose(w.One(),e,t.position).invertToRef(this._tmpMatrix),n=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else B.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),n=this._tmpMatrix;const a=r.length/3;for(let t=0;t{s+=this._addMeshVerts(e,t,i)}))}return s}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(Ki.PositionKind);i||(i=[]);let s=t.getVerticesData(Ki.NormalKind);s||(s=[]),t.computeWorldMatrix(!1);const r=[],n=[];for(let e=0;ee*e)).reduce(((e,t)=>e+t)))t=r.length,i=t/3-1,this._tmpAmmoVectorA.setValue(r[0],r[1],r[2]),this._tmpAmmoVectorB.setValue(r[t-3],r[t-2],r[t-1]);else{e._isFromLine=!1;const s=e.getParam("path");if(null===e.getParam("shape"))return J.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;t=s.length,i=t-1,this._tmpAmmoVectorA.setValue(s[0].x,s[0].y,s[0].z),this._tmpAmmoVectorB.setValue(s[t-1].x,s[t-1].y,s[t-1].z)}e.segments=i;let o=e.getParam("fixedPoints");o=o>3?3:o;const a=(new this.bjsAMMO.btSoftBodyHelpers).CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,o);return a.get_m_cfg().set_collisions(17),a}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n=i.getVerticesData(Ki.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);const o=r.length/3;for(let t=0;t{s+=this._addHullVerts(e,t,i)}))}return s}_createShape(e,t=!1){const i=e.object;let s;const r=e.getObjectExtents();if(!t){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];s=new this.bjsAMMO.btCompoundShape;let i=0;if(t.forEach((e=>{const t=e.getPhysicsImpostor();if(t){if(t.type==go.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const r=this._createShape(t),n=e.parent.getWorldMatrix().clone(),o=new w;n.decompose(o),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*o.x,e.position.y*o.y,e.position.z*o.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,r),t.dispose(),i++}})),i>0){if(e.type!=go.NoImpostor){const t=this._createShape(e,!0);t&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,t))}return s}this.bjsAMMO.destroy(s),s=null}switch(e.type){case go.SphereImpostor:if(G.WithinEpsilon(r.x,r.y,1e-4)&&G.WithinEpsilon(r.x,r.z,1e-4))s=new this.bjsAMMO.btSphereShape(r.x/2);else{this._tmpAmmoVectorA.setValue(0,0,0);const e=[this._tmpAmmoVectorA],t=[1];s=new this.bjsAMMO.btMultiSphereShape(e,t,1),this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s.setLocalScaling(this._tmpAmmoVectorA)}break;case go.CapsuleImpostor:{const e=r.x/2;s=new this.bjsAMMO.btCapsuleShape(e,r.y-2*e)}break;case go.CylinderImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case go.PlaneImpostor:case go.BoxImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case go.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)s=this.onCreateCustomMeshImpostor(e);else{const t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);const r=this._addMeshVerts(t,i,i);s=0==r?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case go.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)s=this.onCreateCustomConvexHullImpostor(e);else{const t=new this.bjsAMMO.btConvexHullShape;0==this._addHullVerts(t,i,i)?(e._pluginData.toDispose.push(t),s=new this.bjsAMMO.btCompoundShape):s=t}break;case go.NoImpostor:s=new this.bjsAMMO.btSphereShape(r.x/2);break;case go.CustomImpostor:s=this._createCustom(e);break;case go.SoftbodyImpostor:s=this._createSoftbody(e);break;case go.ClothImpostor:s=this._createCloth(e);break;case go.RopeImpostor:s=this._createRope(e);break;default:J.Warn("The impostor type is not currently supported by the ammo plugin.")}return s}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){const s=e.physicsBody.getWorldTransform();if(Math.abs(s.getOrigin().x()-t.x)>T||Math.abs(s.getOrigin().y()-t.y)>T||Math.abs(s.getOrigin().z()-t.z)>T||Math.abs(s.getRotation().x()-i.x)>T||Math.abs(s.getRotation().y()-i.y)>T||Math.abs(s.getRotation().z()-i.z)>T||Math.abs(s.getRotation().w()-i.w)>T)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),s.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),s.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(s),0==e.mass){const t=e.physicsBody.getMotionState();t&&t.setWorldTransform(s)}else e.physicsBody.activate()}isSupported(){return void 0!==this.bjsAMMO}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity(),!t)return null;const i=new w(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity(),!t)return null;const i=new w(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}setBodyMass(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t}getBodyMass(e){return e._pluginData.mass||0}getBodyFriction(e){return e._pluginData.friction||0}setBodyFriction(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t}getBodyRestitution(e){return e._pluginData.restitution||0}setBodyRestitution(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t}getBodyPressure(e){return e.soft?e._pluginData.pressure||0:(J.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===go.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):J.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(J.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):J.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(J.Warn("Velocity iterations is not a property of a rigid body"),0)}setBodyVelocityIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):J.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(J.Warn("Position iterations is not a property of a rigid body"),0)}setBodyPositionIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):J.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,s,r=1,n=!1){const o=e.segments,a=Math.round((o-1)*i)+o*(o-1-Math.round((o-1)*s));e.physicsBody.appendAnchor(a,t.physicsBody,n,r)}appendHook(e,t,i,s=1,r=!1){const n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,r,s)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){J.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){J.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){return e.getObjectExtents().x/2}getBoxSizeToRef(e,t){const i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._softBodySolver),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoVectorD),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);const s=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,s),i.reset(e,t),s.hasHit()&&(i.setHitData({x:s.get_m_hitNormalWorld().x(),y:s.get_m_hitNormalWorld().y(),z:s.get_m_hitNormalWorld().z()},{x:s.get_m_hitPointWorld().x(),y:s.get_m_hitPointWorld().y(),z:s.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(s),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}z_._DISABLE_COLLISION_FLAG=4,z_._KINEMATIC_FLAG=2,z_._DISABLE_DEACTIVATION_FLAG=4,p.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return-1;const t=this.reflectionProbes.indexOf(e);return-1!==t&&this.reflectionProbes.splice(t,1),t},p.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};class W_{constructor(e,t,i,s=!0,r=!1,n=!1){if(this.name=e,this._viewMatrix=B.Identity(),this._target=w.Zero(),this._add=w.Zero(),this._invertYAxis=!1,this.position=w.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(r){const e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?o=2:e.textureFloatRender&&(o=1)}this._renderTargetTexture=new da(e,t,i,s,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const a=i.getEngine().useReverseDepthBuffer;let l;this._renderTargetTexture.onBeforeRenderObservable.add((e=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){case 0:this._add.copyFromFloats(1,0,0);break;case 1:this._add.copyFromFloats(-1,0,0);break;case 2:this._add.copyFromFloats(0,this._invertYAxis?1:-1,0);break;case 3:this._add.copyFromFloats(0,this._invertYAxis?-1:1,0);break;case 4:this._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:this._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1)}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);const t=i.useRightHandedSystem?B.LookAtRHToRef:B.LookAtLHToRef,s=i.useRightHandedSystem?B.PerspectiveFovRH:B.PerspectiveFovLH;t(this.position,this._target,w.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=s(Math.PI/2,1,a?i.activeCamera.maxZ:i.activeCamera.minZ,a?i.activeCamera.minZ:i.activeCamera.maxZ,this._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(this._viewMatrix,this._projectionMatrix),i.activeCamera.isRigCamera&&!this._renderTargetTexture.activeCamera&&(this._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=this.position})),this._renderTargetTexture.onBeforeBindObservable.add((()=>{this._currentSceneUBO=i.getSceneUniformBuffer(),i.getEngine()._debugPushGroup?.(`reflection probe generation for ${e}`,1),l=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)})),this._renderTargetTexture.onAfterUnbindObservable.add((()=>{i.imageProcessingConfiguration.applyByPostProcess=l,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),i.getEngine()._debugPopGroup?.(1)}))}get samples(){return this._renderTargetTexture.samples}set samples(e){this._renderTargetTexture.samples=e}get refreshRate(){return this._renderTargetTexture.refreshRate}set refreshRate(e){this._renderTargetTexture.refreshRate=e}getScene(){return this._scene}get cubeTexture(){return this._renderTargetTexture}get renderList(){return this._renderTargetTexture.renderList}set renderList(e){this._renderTargetTexture.renderList=e}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){const e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){const e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}toString(e){let t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t}getClassName(){return"ReflectionProbe"}serialize(){const e=Pe.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let s=null;if(t.reflectionProbes)for(let i=0;is||new W_(e.name,e.renderTargetSize,t,e._generateMipMaps)),e,t,i),s.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&s.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(s.metadata=e.metadata),s}}ae([xe()],W_.prototype,"_attachedMesh",void 0),ae([ve()],W_.prototype,"position",void 0);class H_{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,s,r){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=s||1,this._animationStarted=!0,this._onBaseAnimationEnd=r,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class X_ extends H_{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=new Array,this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new g,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new j(1,1,1,1),this.position=w.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,s,r=null){this._onAnimationEnd=r,super.playAnimation(e,t,i,s,this._endAnimation)}dispose(){for(let e=0;e0)for(let n=0;n=r.distance))&&(r=a,i))break}return r||new qi},ks.prototype._internalMultiPickSprites=function(e,t,i){if(!qi)return null;let s=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let r=0;r!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(ts.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(ts.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(ts.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();const e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,s,r){const n=this.scene.pickSprite(t,i,this._spritePredicate,s,r);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,s,r){const n=this.scene;return s?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&r&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?r.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:r.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null),i}_pointerDown(e,t,i,s){const r=this.scene;if(r._pickedDownSprite=null,r.spriteManagers&&r.spriteManagers.length>0&&(i=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(r._pickedDownSprite=i.pickedSprite,s.button){case 0:i.pickedSprite.actionManager.processTrigger(2,q.CreateNewFromSprite(i.pickedSprite,r,s));break;case 1:i.pickedSprite.actionManager.processTrigger(4,q.CreateNewFromSprite(i.pickedSprite,r,s));break;case 2:i.pickedSprite.actionManager.processTrigger(3,q.CreateNewFromSprite(i.pickedSprite,r,s))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,q.CreateNewFromSprite(i.pickedSprite,r,s))}return i}_pointerUp(e,t,i,s,r){const n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){const i=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,q.CreateNewFromSprite(i.pickedSprite,n,s)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,q.CreateNewFromSprite(i.pickedSprite,n,s)),r&&i.pickedSprite.actionManager.processTrigger(6,q.CreateNewFromSprite(i.pickedSprite,n,s)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==i.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,q.CreateNewFromSprite(n._pickedDownSprite,n,s)))}return i}}Ft.IncludesShadersStore.imageProcessingCompatibility="#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));\n#endif\n";Ft.ShadersStore.spritesPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler;\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nvec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;}\n#endif\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvec2 uv=uvPixelPerfect(vUV);\n#else\nvec2 uv=vUV;\n#endif\nvec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.)\n{if (color.a<0.95)\ndiscard;}\ncolor*=vColor;\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.spritesVertexShader="attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor;\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); \nvColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y;\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";class j_{get fogEnabled(){return this._fogEnabled}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this._createEffects())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=!!this._scene?.getEngine().getCaps().fragmentDepthSupported;e&&!t&&J.Warn("Logarithmic depth has been requested for a sprite renderer on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._createEffects()}get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,s=null){this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this._fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=s,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new $i(e,this._vertexData,!0,this._vertexBufferSize);const r=this._buffer.createVertexBuffer(Ki.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),n=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing);let o,a=6;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new $i(e,t,!1,2),o=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else o=this._buffer.createVertexBuffer("offsets",a,2,this._vertexBufferSize,this._useInstancing),a+=2;const l=this._buffer.createVertexBuffer("inverts",a,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",a+2,4,this._vertexBufferSize,this._useInstancing),c=this._buffer.createVertexBuffer(Ki.ColorKind,a+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[Ki.PositionKind]=r,this._vertexBuffers.options=n,this._vertexBuffers.offsets=o,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[Ki.ColorKind]=c,this._createEffects()}_createEffects(){this._drawWrapperBase?.dispose(),this._drawWrapperDepth?.dispose(),this._drawWrapperBase=new gr(this._engine),this._drawWrapperDepth=new gr(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing);let e="";this._pixelPerfect&&(e+="#define PIXEL_PERFECT\n"),this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&this._fogEnabled&&(e+="#define FOG\n"),this._useLogarithmicDepth&&(e+="#define LOGARITHMICDEPTH\n"),this._drawWrapperBase.effect=this._engine.createEffect("sprites",[Ki.PositionKind,"options","offsets","inverts","cellInfo",Ki.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor","logarithmicDepthConstant"],["diffuseSampler"],e),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext}render(e,t,i,s,r=null){if(!this.texture||!this.texture.isReady()||!e.length)return;const n=this._drawWrapperBase,o=this._drawWrapperDepth,a=this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode,l=n.effect;if(!l.isReady())return;const h=this._engine,c=!(!this._scene||!this._scene.useRightHandedSystem),u=this.texture.getBaseSize(),d=Math.min(this._capacity,e.length);let p=0,f=!0;for(let i=0;i{e.cellRef||(e.cellIndex=0);const i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=this._spriteMap[e.cellIndex]),e._xOffset=this._cellData[e.cellRef].frame.x/t.width,e._yOffset=this._cellData[e.cellRef].frame.y/t.height,e._xSize=this._cellData[e.cellRef].frame.w,e._ySize=this._cellData[e.cellRef].frame.h},r||(r=y.LastCreatedScene),r._getComponent(ts.NAME_SPRITE)||r._addComponent(new Y_(r)),this._fromPacked=a,this._scene=r;const h=this._scene.getEngine();if(this._spriteRenderer=new j_(h,i,n,r),s.width&&s.height)this.cellWidth=s.width,this.cellHeight=s.height;else{if(void 0===s)return void(this._spriteRenderer=null);this.cellWidth=s,this.cellHeight=s}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new Zn(t,r,!0,!1,o)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if(e="string"==typeof t?JSON.parse(t):t,e.frames.length){const t={};for(let i=0;i0);const s=e.substring(0,i-1)+".json",r=()=>{J.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},n=e=>{try{const t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};Ii.LoadFile(s,n,void 0,void 0,!1,r)}}_checkTextureAlpha(e,t,i,s,r){if(!e.useAlphaForPicking||!this.texture)return!0;const n=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(n.width*n.height*4),this.texture.readPixels(0,0,this._textureContent));const o=U.Vector3[0];o.copyFrom(t.direction),o.normalize(),o.scaleInPlace(i),o.addInPlace(t.origin);const a=(o.x-s.x)/(r.x-s.x),l=1-(o.y-s.y)/(r.y-s.y),h=e._xOffset*n.width+a*e._xSize|0,c=e._yOffset*n.height+l*e._ySize|0;return this._textureContent[4*(h+c*n.width)+3]>.5}intersects(e,t,i,s){const r=Math.min(this.capacity,this.sprites.length),n=w.Zero(),o=w.Zero();let a=Number.MAX_VALUE,l=null;const h=U.Vector3[0],c=U.Vector3[1],u=t.getViewMatrix();let d=e,p=e;for(let t=0;te){if(!this._checkTextureAlpha(r,d,e,n,o))continue;if(p=d,a=e,l=r,s)break}}}}if(l){const e=new qi;u.invertToRef(U.Matrix[0]),e.hit=!0,e.pickedSprite=l,e.distance=a;const t=U.Vector3[2];return t.copyFrom(p.direction),t.normalize(),t.scaleInPlace(a),p.origin.addToRef(t,h),e.pickedPoint=w.TransformCoordinates(h,U.Matrix[0]),e}return null}multiIntersects(e,t,i){const s=Math.min(this.capacity,this.sprites.length),r=w.Zero(),n=w.Zero();let o;const a=[],l=U.Vector3[0].copyFromFloats(0,0,0),h=U.Vector3[1].copyFromFloats(0,0,0),c=t.getViewMatrix();for(let t=0;t{const o=new Ne;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=$_.Parse(t,i||y.LastCreatedScene,s);e&&(n.name=e),r(n)}else n("Unable to load the sprite manager")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new $_("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise(((s,r)=>{const n=new Ne;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const r=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(r.spriteManager),a=$_.Parse(o,t||y.LastCreatedScene,i);a.snippetId=e,s(a)}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}$_.SnippetUrl="https://snippet.babylonjs.com",$_.CreateFromSnippetAsync=$_.ParseFromSnippetAsync;class K_{}K_.LoaderInjectedPhysicsEngine=void 0;let q_={},Q_={};const Z_=(e,t,i,s)=>{if(!t.materials)return null;for(let r=0,n=t.materials.length;r{for(const s in t)if(e.name===t[s])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},em=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),tm=(e,t)=>{const i=t;if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){const s=t._waitingData.lods.ids,r=i.isEnabled(!1);if(t._waitingData.lods.distances){const n=t._waitingData.lods.distances;if(n.length>=s.length){const t=n.length>s.length?n[n.length-1]:0;i.setEnabled(!1);for(let t=0;t0&&i.addLODLevel(t,null),!0===r&&i.setEnabled(!0)}else Ii.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},im=(e,t,i)=>{if("number"!=typeof e){const s=i.getLastEntryById(e);return s&&null!=t?s.instances[parseInt(t)]:s}const s=q_[e];return s&&null!=t?s.instances[parseInt(t)]:s},sm=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):Q_[e],rm=(e,t,i,s,r=!1)=>{const n=new Hn(e);let o="importScene has failed JSON parse";try{var a=JSON.parse(t);o="";const s=Ro.loggingLevel===Ro.DETAILED_LOGGING;let r,l;if(void 0!==a.environmentTexture&&null!==a.environmentTexture){const t=void 0===a.isPBR||a.isPBR;if(a.environmentTextureType&&"BABYLON.HDRCubeTexture"===a.environmentTextureType){const s=a.environmentTextureSize?a.environmentTextureSize:128,r=new N_((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,s,!0,!t,void 0,a.environmentTexturePrefilterOnLoad);a.environmentTextureRotationY&&(r.rotationY=a.environmentTextureRotationY),e.environmentTexture=r}else if("object"==typeof a.environmentTexture){const t=tf.Parse(a.environmentTexture,e,i);e.environmentTexture=t}else if(a.environmentTexture.endsWith(".env")){const t=new tf((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}else{const t=tf.CreateFromPrefilteredData((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}if(!0===a.createDefaultSkybox){const i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,s=a.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,s)}n.environmentTexture=e.environmentTexture}if(void 0!==a.environmentIntensity&&null!==a.environmentIntensity&&(e.environmentIntensity=a.environmentIntensity),void 0!==a.lights&&null!==a.lights)for(r=0,l=a.lights.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})))}if(void 0!==a.multiMaterials&&null!==a.multiMaterials)for(r=0,l=a.multiMaterials.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)}))}if(void 0!==a.morphTargetManagers&&null!==a.morphTargetManagers)for(const t of a.morphTargetManagers){const i=L_.Parse(t,e);n.morphTargetManagers.push(i),i._parentContainer=n}if(void 0!==a.skeletons&&null!==a.skeletons)for(r=0,l=a.skeletons.length;r{e&&(n.geometries.push(e),e._parentContainer=n)}))}if(void 0!==a.transformNodes&&null!==a.transformNodes)for(r=0,l=a.transformNodes.length;r{t._waitingSubMaterialsUniqueIds.forEach((i=>{t.subMaterials.push(sm(i,e))})),t._waitingSubMaterialsUniqueIds=[]})),e.meshes.forEach((t=>{null!==t._waitingMaterialId&&(t.material=sm(t._waitingMaterialId,e),t._waitingMaterialId=null)})),r=0,l=e.skeletons.length;r{if(t._waitingTransformNodeId){const i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}})),t._hasWaitingData=null)}for(r=0,l=e.meshes.length;r0){for(let i=0;i0){for(let i=0;i{e._loadedUniqueId=""})),p.Parse(a,e,n,i),r=0,l=e.meshes.length;r-1!==e.indexOf("babylon"),importMesh:(e,t,i,s,r,n,o,a)=>{let l="importMesh has failed JSON parse";try{var h=JSON.parse(i);l="";const a=Ro.loggingLevel===Ro.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;const c=[],u=new Map,d=[];if(void 0!==h.transformNodes&&null!==h.transformNodes)for(let e=0,i=h.transformNodes.length;e{!0!==e&&h.geometries[i]&&Array.isArray(h.geometries[i])&&h.geometries[i].forEach((r=>{r.id===_.geometryId&&("vertexData"===i&&br.Parse(r,t,s),e=!0)}))})),!1===e&&J.Warn("Geometry not found for mesh "+_.id)}if(_.materialUniqueId||_.materialId){const e=_.materialUniqueId?p:n;let i=-1!==e.indexOf(_.materialUniqueId||_.materialId);if(!1===i&&void 0!==h.multiMaterials&&null!==h.multiMaterials){const r=(i,r)=>{e.push(i);const n=Z_(r,h,t,s);n&&n.material&&(Q_[n.parsedMaterial.uniqueId||n.parsedMaterial.id]=n.material,l+="\n\tMaterial "+n.material.toString(a))};for(let s=0,n=h.multiMaterials.length;sr(e,(t=>t.uniqueId===e)))):n.materials.forEach((e=>r(e,(t=>t.id===e)))),e.push(n.uniqueId||n.id);const s=On.ParseMultiMaterial(n,t);Q_[n.uniqueId||n.id]=s,s&&(i=!0,l+="\n\tMulti-Material "+s.toString(a));break}}}if(!1===i){e.push(_.materialUniqueId||_.materialId);const i=Z_((e=>_.materialUniqueId&&e.uniqueId===_.materialUniqueId||e.id===_.materialId),h,t,s);i&&i.material?(Q_[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,l+="\n\tMaterial "+i.material.toString(a)):J.Warn("Material not found for mesh "+_.id)}}if(null!==_.skeletonId&&void 0!==_.skeletonId&&-1!==h.skeletonId&&void 0!==h.skeletons&&null!==h.skeletons&&!(i.indexOf(_.skeletonId)>-1))for(let e=0,s=h.skeletons.length;e-1&&void 0!==h.morphTargetManagers&&null!==h.morphTargetManagers&&!(f.indexOf(_.morphTargetManagerId)>-1))for(let e=0,i=h.morphTargetManagers.length;e{e._waitingSubMaterialsUniqueIds.forEach((i=>{e.subMaterials.push(sm(i,t))})),e._waitingSubMaterialsUniqueIds=[]})),t.meshes.forEach((e=>{null!==e._waitingMaterialId&&(e.material=sm(e._waitingMaterialId,t),e._waitingMaterialId=null)}));for(let e=0,i=t.transformNodes.length;e-1&&d.splice(e,1)}_._waitingParentId=null}_._waitingData.lods&&tm(t,_)}for(const e of d)e.dispose();for(let e=0,i=t.skeletons.length;e{if(e._waitingTransformNodeId){const i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}})),i._hasWaitingData=null)}for(let e=0,i=t.meshes.length;e{e._loadedUniqueId=""})),!0}catch(e){const t=em("importMesh",h?h.producer:"Unknown")+l;if(!a)throw J.Log(t),e;a(t,e)}finally{null!==l&&Ro.loggingLevel!==Ro.NO_LOGGING&&J.Log(em("importMesh",h?h.producer:"Unknown")+(Ro.loggingLevel!==Ro.MINIMAL_LOGGING?l:"")),Q_={}}return!1},load:(e,t,i,s)=>{let r="importScene has failed JSON parse";try{var n=JSON.parse(t);switch(r="",void 0!==n.useDelayedTextureLoading&&null!==n.useDelayedTextureLoading&&(e.useDelayedTextureLoading=n.useDelayedTextureLoading&&!Ro.ForceFullSceneLoadingForIncremental),void 0!==n.autoClear&&null!==n.autoClear&&(e.autoClear=n.autoClear),void 0!==n.clearColor&&null!==n.clearColor&&(e.clearColor=j.FromArray(n.clearColor)),void 0!==n.ambientColor&&null!==n.ambientColor&&(e.ambientColor=Y.FromArray(n.ambientColor)),void 0!==n.gravity&&null!==n.gravity&&(e.gravity=w.FromArray(n.gravity)),void 0!==n.useRightHandedSystem&&(e.useRightHandedSystem=!!n.useRightHandedSystem),void 0!==n.fogMode&&null!==n.fogMode&&(e.fogMode=n.fogMode),void 0!==n.fogColor&&null!==n.fogColor&&(e.fogColor=Y.FromArray(n.fogColor)),void 0!==n.fogStart&&null!==n.fogStart&&(e.fogStart=n.fogStart),void 0!==n.fogEnd&&null!==n.fogEnd&&(e.fogEnd=n.fogEnd),void 0!==n.fogDensity&&null!==n.fogDensity&&(e.fogDensity=n.fogDensity),r+="\tFog mode for scene: ",e.fogMode){case 0:r+="none\n";break;case 1:r+="exp\n";break;case 2:r+="exp2\n";break;case 3:r+="linear\n"}if(n.physicsEnabled){let t;"cannon"===n.physicsEngine||n.physicsEngine===k_.name?t=new k_(void 0,void 0,K_.LoaderInjectedPhysicsEngine):"oimo"===n.physicsEngine||n.physicsEngine===G_.name?t=new G_(void 0,K_.LoaderInjectedPhysicsEngine):"ammo"!==n.physicsEngine&&n.physicsEngine!==z_.name||(t=new z_(void 0,K_.LoaderInjectedPhysicsEngine,void 0)),r="\tPhysics engine "+(n.physicsEngine?n.physicsEngine:"oimo")+" enabled\n";const i=n.physicsGravity?w.FromArray(n.physicsGravity):null;e.enablePhysics(i,t)}return void 0!==n.metadata&&null!==n.metadata&&(e.metadata=n.metadata),void 0!==n.collisionsEnabled&&null!==n.collisionsEnabled&&(e.collisionsEnabled=n.collisionsEnabled),!!rm(e,t,i,s,!0)&&(n.autoAnimate&&e.beginAnimation(e,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1),void 0!==n.activeCameraID&&null!==n.activeCameraID&&e.setActiveCameraById(n.activeCameraID),!0)}catch(e){const t=em("importScene",n?n.producer:"Unknown")+r;if(!s)throw J.Log(t),e;s(t,e)}finally{null!==r&&Ro.loggingLevel!==Ro.NO_LOGGING&&J.Log(em("importScene",n?n.producer:"Unknown")+(Ro.loggingLevel!==Ro.MINIMAL_LOGGING?r:""))}return!1},loadAssetContainer:(e,t,i,s)=>rm(e,t,i,s)});class nm{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,Br.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||Y.White(),this.rightColor=e.rightColor||Y.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){const e=new nm;return se.DeepCopy(this,e),e}equals(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled}serialize(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}}static Parse(e){return new nm({isEnabled:e.isEnabled,leftColor:Y.FromArray(e.leftColor),rightColor:Y.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}Pe._FresnelParametersParser=nm.Parse;class om{}om.BindSceneUniformBuffer=on,om.PrepareDefinesForMergedUV=an,om.BindTextureMatrix=ln,om.GetFogState=mn,om.PrepareDefinesForMisc=gn,om.PrepareDefinesForCamera=In,om.PrepareDefinesForFrameBoundValues=Tn,om.PrepareDefinesForBones=Sn,om.PrepareDefinesForMorphTargets=En,om.PrepareDefinesForBakedVertexAnimation=bn,om.PrepareDefinesForAttributes=Cn,om.PrepareDefinesForMultiview=yn,om.PrepareDefinesForOIT=An,om.PrepareDefinesForPrePass=Rn,om.PrepareDefinesForLight=xn,om.PrepareDefinesForLights=vn,om.PrepareUniformsAndSamplersForLight=Pn,om.PrepareUniformsAndSamplersList=Mn,om.HandleFallbacksForShadows=_n,om.PrepareAttributesForMorphTargetsInfluencers=tn,om.PrepareAttributesForMorphTargets=sn,om.PrepareAttributesForBakedVertexAnimation=hn,om.PrepareAttributesForBones=pn,om.PrepareAttributesForInstances=fn,om.PushAttributesForInstances=rn,om.BindLightProperties=function(e,t,i){e.transferToEffect(t,i+"")},om.BindLight=un,om.BindLights=dn,om.BindFogParameters=en,om.BindBonesParameters=cn,om.BindMorphTargetParameters=nn,om.BindLogDepth=Jr;class am extends Cf{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new Y(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}ae([pe(),de("_markAllSubMeshesAsLightsDirty")],am.prototype,"maxSimultaneousLights",void 0),ae([pe(),de("_markAllSubMeshesAsLightsDirty")],am.prototype,"disableLighting",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],am.prototype,"environmentTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],am.prototype,"invertNormalMapX",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],am.prototype,"invertNormalMapY",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],am.prototype,"normalTexture",void 0),ae([_e("emissive"),de("_markAllSubMeshesAsTexturesDirty")],am.prototype,"emissiveColor",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],am.prototype,"emissiveTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],am.prototype,"occlusionStrength",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],am.prototype,"occlusionTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],am.prototype,"alphaCutOff",void 0),ae([pe()],am.prototype,"doubleSided",null),ae([fe(),de("_markAllSubMeshesAsTexturesDirty",null)],am.prototype,"lightmapTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],am.prototype,"useLightmapAsShadowmap",void 0);class lm extends am{constructor(e,t){super(e,t),this._useRoughnessFromMetallicTextureAlpha=!1,this._useRoughnessFromMetallicTextureGreen=!0,this._useMetallnessFromMetallicTextureBlue=!0,this.metallic=1,this.roughness=1}getClassName(){return"PBRMetallicRoughnessMaterial"}clone(e){const t=Pe.Clone((()=>new lm(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=Pe.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const s=Pe.Parse((()=>new lm(e.name,t)),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}ae([_e(),de("_markAllSubMeshesAsTexturesDirty","_albedoColor")],lm.prototype,"baseColor",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],lm.prototype,"baseTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],lm.prototype,"metallic",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],lm.prototype,"roughness",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],lm.prototype,"metallicRoughnessTexture",void 0),u("BABYLON.PBRMetallicRoughnessMaterial",lm);class hm extends am{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=Pe.Clone((()=>new hm(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=Pe.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const s=Pe.Parse((()=>new hm(e.name,t)),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}ae([_e("diffuse"),de("_markAllSubMeshesAsTexturesDirty","_albedoColor")],hm.prototype,"diffuseColor",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],hm.prototype,"diffuseTexture",void 0),ae([_e("specular"),de("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],hm.prototype,"specularColor",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty","_microSurface")],hm.prototype,"glossiness",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],hm.prototype,"specularGlossinessTexture",void 0),u("BABYLON.PBRSpecularGlossinessMaterial",hm);class cm extends qn{constructor(e,t,i=null){if(super(t),e)if(this._textureMatrix=B.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){const e=this._getEngine();let t;t=e._features.support3DTextures?e.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):e.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=t,this._texture.isReady=!1,this.isCube=!1,this.is3D=e._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;const i=i=>{if("string"!=typeof i)return;let s,r=null,n=null;const o=i.split("\n");let a=0,l=0,h=0,c=0,u=0;for(let e=0;e0&&(e+1)%4==0)r[e]=255;else{const t=n[e];r[e]=t/u*255}t.is3D?(t.updateSize(a,a,a),e.updateRawTexture3D(t,r,5,!1)):(t.updateSize(a*a,a),e.updateRawTexture(t,r,5,!1)),t.isReady=!0,this._triggerOnLoad()},s=this.getScene();return s?s._loadFile(this.url,i):e._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){const e=new cm(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())}static Parse(e,t){let i=null;return e.name&&!e.isRenderTarget&&(i=new cm(e.name,t),i.name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}}cm._NoneEmptyLineRegex=/\S+/,u("BABYLON.ColorGradingTexture",cm);class um extends qn{constructor(e,t,i,s=!1,r=!0,n=null,o=null,a=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=Zn.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=a,this._noMipmap=s,this.gammaSpace=r,this._onLoad=n,this._onError=o,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?n&&(this._texture.isReady?Ii.SetImmediate((()=>n())):this._texture.onLoadedObservable.add(n)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage((()=>this._loadTexture()),this._onError)}_loadImage(e,t){const i=this.getScene();if(!i)return;const s=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,!this._noMipmap,!1,3);s.generateMipMaps=!this._noMipmap,i.addPendingData(s),s.url=this.url,s.isReady=!1,i.getEngine()._internalTexturesCache.push(s),this._texture=s;const r=document.createElement("canvas");ci(this.url,(t=>{this._width=t.width,this._height=t.height,r.width=this._width,r.height=this._height;const i=r.getContext("2d");i.drawImage(t,0,0);const s=i.getImageData(0,0,t.width,t.height);this._buffer=s.data.buffer,r.remove(),e()}),((e,r)=>{i.removePendingData(s),t&&t(`${this.getClassName()} could not be loaded`,r)}),i?i.offlineProvider:null)}_loadTexture(){const e=this.getScene();if(!e)return;const t=(()=>{const e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=M_.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){const s=t[um._FacesMapping[e]];i.push(s)}return i})(),i=this._texture;e.getEngine().updateRawCubeTexture(i,t,i.format,i.type,i.invertY),i.isReady=!0,e.removePendingData(i),i.onLoadedObservable.notifyObservers(i),i.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(3*e.byteLength/4);let s=0;for(let r=0;rt.length)return void J.Error("Unable to load TGA file - Not enough data");i+=s.id_length;let r,n=!1,o=!1,a=!1;switch(s.image_type){case 9:n=!0;case 1:o=!0;break;case 10:n=!0;case 2:break;case 11:n=!0;case 3:a=!0}const l=s.pixel_size>>3,h=s.width*s.height*l;let c,u,d,p,f,_,m;if(o&&(c=t.subarray(i,i+=s.colormap_length*(s.colormap_size>>3))),n){let e,s,n;r=new Uint8Array(h);let o=0;const a=new Uint8Array(l);for(;i>4){default:case 2:u=0,p=1,m=s.width,d=0,f=1,_=s.height;break;case 0:u=0,p=1,m=s.width,d=s.height-1,f=-1,_=-1;break;case 3:u=s.width-1,p=-1,m=-1,d=0,f=1,_=s.height;break;case 1:u=s.width-1,p=-1,m=-1,d=s.height-1,f=-1,_=-1}const g="_getImageData"+(a?"Grey":"")+s.pixel_size+"bits",v=_m[g](s,c,r,d,f,_,u,p,m);e.getEngine()._uploadDataToTextureDirectly(e,v)}dm._DefaultOptions={generateMipMaps:!1,samplingMode:2,format:5,engine:null,scene:null};const _m={GetTGAHeader:pm,UploadContent:fm,_getImageData8bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=t,u=e.width,d=e.height;let p,f,_,m=0;const g=new Uint8Array(u*d*4);for(_=s;_!==n;_+=r)for(f=o;f!==l;f+=a,m++)p=h[m],g[4*(f+u*_)+3]=255,g[4*(f+u*_)+2]=c[3*p+0],g[4*(f+u*_)+1]=c[3*p+1],g[4*(f+u*_)+0]=c[3*p+2];return g},_getImageData16bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,p,f,_=0;const m=new Uint8Array(c*u*4);for(f=s;f!==n;f+=r)for(p=o;p!==l;p+=a,_+=2){d=h[_+0]+(h[_+1]<<8);const e=255*((31744&d)>>10)/31|0,t=255*((992&d)>>5)/31|0,i=255*(31&d)/31|0;m[4*(p+c*f)+0]=e,m[4*(p+c*f)+1]=t,m[4*(p+c*f)+2]=i,m[4*(p+c*f)+3]=32768&d?0:255}return m},_getImageData24bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,p,f=0;const _=new Uint8Array(c*u*4);for(p=s;p!==n;p+=r)for(d=o;d!==l;d+=a,f+=3)_[4*(d+c*p)+3]=255,_[4*(d+c*p)+2]=h[f+0],_[4*(d+c*p)+1]=h[f+1],_[4*(d+c*p)+0]=h[f+2];return _},_getImageData32bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,p,f=0;const _=new Uint8Array(c*u*4);for(p=s;p!==n;p+=r)for(d=o;d!==l;d+=a,f+=4)_[4*(d+c*p)+2]=h[f+0],_[4*(d+c*p)+1]=h[f+1],_[4*(d+c*p)+0]=h[f+2],_[4*(d+c*p)+3]=h[f+3];return _},_getImageDataGrey8bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,p,f,_=0;const m=new Uint8Array(c*u*4);for(f=s;f!==n;f+=r)for(p=o;p!==l;p+=a,_++)d=h[_],m[4*(p+c*f)+0]=d,m[4*(p+c*f)+1]=d,m[4*(p+c*f)+2]=d,m[4*(p+c*f)+3]=255;return m},_getImageDataGrey16bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,p,f=0;const _=new Uint8Array(c*u*4);for(p=s;p!==n;p+=r)for(d=o;d!==l;d+=a,f+=2)_[4*(d+c*p)+0]=h[f+0],_[4*(d+c*p)+1]=h[f+0],_[4*(d+c*p)+2]=h[f+0],_[4*(d+c*p)+3]=h[f+1];return _}};function mm(){let e=null;function t(e,t,i,s,r){const n=e.getImageTranscodedSizeInBytes(t,i,s);let o=new Uint8Array(n);return e.transcodeImage(o,t,i,s,1,0)?(r&&(o=function(e,t,i,s){const r=new Uint16Array(4),n=new Uint16Array(i*s),o=i/4,a=s/4;for(let t=0;t>2&3],n[h++]=r[l>>4&3],n[h++]=r[l>>6&3]}}return n}(o,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)),o):null}onmessage=i=>{if("init"===i.data.action){if(i.data.url)try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}e||(e=BASIS({wasmBinary:i.data.wasmBinary})),null!==e&&e.then((e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})}))}else if("transcode"===i.data.action){const e=i.data.config,s=i.data.imageData,r=new BASIS.BasisFile(s),n=function(e){const t=e.getHasAlpha(),i=e.getNumImages(),s=[];for(let t=0;t{fm(t,s)}))}}),Br._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=D_.RGBE_ReadHeader(s),n=D_.RGBE_ReadPixels(s,r),o=r.width*r.height,a=new Float32Array(4*o);for(let e=0;e{const e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,a)}))}}),function(e){e[e.cTFETC1=0]="cTFETC1",e[e.cTFETC2=1]="cTFETC2",e[e.cTFBC1=2]="cTFBC1",e[e.cTFBC3=3]="cTFBC3",e[e.cTFBC4=4]="cTFBC4",e[e.cTFBC5=5]="cTFBC5",e[e.cTFBC7=6]="cTFBC7",e[e.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",e[e.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",e[e.cTFASTC_4x4=10]="cTFASTC_4x4",e[e.cTFATC_RGB=11]="cTFATC_RGB",e[e.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",e[e.cTFRGBA32=13]="cTFRGBA32",e[e.cTFRGB565=14]="cTFRGB565",e[e.cTFBGR565=15]="cTFBGR565",e[e.cTFRGBA4444=16]="cTFRGBA4444",e[e.cTFFXT1_RGB=17]="cTFFXT1_RGB",e[e.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",e[e.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",e[e.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",e[e.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"}(gm||(gm={}));const vm={JSModuleURL:`${Ii._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${Ii._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`};let xm=null,Tm=null,Sm=0;const Em=(e,t)=>{const i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise(((e,s)=>{(xm||(xm=new Promise(((e,t)=>{Tm?e(Tm):Ii.LoadFileAsync(Ii.GetBabylonScriptURL(vm.WasmModuleURL)).then((i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");const s=URL.createObjectURL(new Blob([`(${mm})()`],{type:"application/javascript"}));Tm=new Worker(s),function(e,t,i){return new Promise(((s,r)=>{const n=t=>{"init"===t.data.action?(e.removeEventListener("message",n),s(e)):"error"===t.data.action&&r(t.data.error||"error initializing worker")};e.addEventListener("message",n),e.postMessage({action:"init",url:i?Ii.GetBabylonScriptURL(i):void 0,wasmBinary:t},[t])}))}(Tm,i,vm.JSModuleURL).then(e,t)})).catch(t)}))),xm).then((()=>{const r=Sm++,n=t=>{"transcode"===t.data.action&&t.data.id===r&&(Tm.removeEventListener("message",n),t.data.success?e(t.data):s("Transcode is not supported on this device"))};Tm.addEventListener("message",n);const o=new Uint8Array(i.byteLength);o.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),Tm.postMessage({action:"transcode",id:r,imageData:o,config:t,ignoreSupportedFormats:!1},[o.buffer])}),(e=>{s(e)}))}))},bm=(e,t)=>{let i=t._gl?.TEXTURE_2D;e.isCube&&(i=t._gl?.TEXTURE_CUBE_MAP),t._bindTextureDirectly(i,e,!0)},Cm=(e,t)=>{const i=e.getEngine();for(let s=0;s{i._releaseTexture(t),bm(e,i)}))}else{e.width=r.width,e.height=r.height,e.generateMipMaps=t.fileInfo.images[s].levels.length>1;const n=ym.GetInternalFormatFromBasisFormat(t.format,i);e.format=n,bm(e,i),t.fileInfo.images[s].levels.forEach(((t,r)=>{i._uploadCompressedDataToTextureDirectly(e,n,t.width,t.height,t.transcodedPixels,s,r)})),!i._features.basisNeedsPOT||G.Log2(e.width)%1==0&&G.Log2(e.height)%1==0||(Ii.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),e._cachedWrapU=Zn.CLAMP_ADDRESSMODE,e._cachedWrapV=Zn.CLAMP_ADDRESSMODE)}}},ym={JSModuleURL:vm.JSModuleURL,WasmModuleURL:vm.WasmModuleURL,GetInternalFormatFromBasisFormat:(e,t)=>{let i;switch(e){case gm.cTFETC1:i=36196;break;case gm.cTFBC1:i=33776;break;case gm.cTFBC4:i=33779;break;case gm.cTFASTC_4x4:i=37808;break;case gm.cTFETC2:i=37496;break;case gm.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i},TranscodeAsync:Em,LoadTextureFromTranscodeResult:Cm};Object.defineProperty(ym,"JSModuleURL",{get:function(){return vm.JSModuleURL},set:function(e){vm.JSModuleURL=e}}),Object.defineProperty(ym,"WasmModuleURL",{get:function(){return vm.WasmModuleURL},set:function(e){vm.WasmModuleURL=e}}),si._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=t.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};Em(e,o).then((e=>{const i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;Cm(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()})).catch((e=>{Ii.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,r&&r(e)}))}loadData(e,t,i){const s=t.getEngine().getCaps(),r={supportedCompressionFormats:{etc1:!!s.etc1,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,astc:!!s.astc,bc7:!!s.bptc}};Em(e,r).then((e=>{const s=e.fileInfo.images[0].levels[0],r=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(s.width,s.height,r,-1!==e.format,(()=>{Cm(t,e)}))})).catch((e=>{Ii.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),Ii.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,(()=>{}),!0)}))}});class Am extends da{get isSupported(){return this._engine?.getCaps().drawBuffersExtension??!1}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,s,r,n,o,a,l,h){for(let c=0;c{this.onAfterRenderObservable.notifyObservers(t)}))}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){const e=this._renderTarget?.textures;if(e){for(let t=e.length-1;t>=0;t--)this._textures[t]._texture=null;this._renderTarget?.dispose(),this._renderTarget=null}}}class Rm{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class Im{constructor(e,t,i,s){return this.name=e,this.meshes=t,this.scene=s,this.options=i,this.options.map=this.options.map??["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=this.options.uvsIn??Ki.UVKind,this.options.uvsOut=this.options.uvsOut??Ki.UVKind,this.options.layout=this.options.layout??Im.LAYOUT_STRIP,this.options.layout===Im.LAYOUT_COLNUM&&(this.options.colnum=this.options.colnum??8),this.options.updateInputMeshes=this.options.updateInputMeshes??!0,this.options.disposeSources=this.options.disposeSources??!0,this._expecting=0,this.options.fillBlanks=this.options.fillBlanks??!0,!0===this.options.fillBlanks&&(this.options.customFillColor=this.options.customFillColor??"black"),this.options.frameSize=this.options.frameSize??256,this.options.paddingRatio=this.options.paddingRatio??.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=this.options.paddingMode??Im.SUBUV_WRAP,this.options.paddingMode===Im.SUBUV_COLOR&&(this.options.paddingColor=this.options.paddingColor??new j(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){const t=this._calculateSize(),i=new N(1,1).divide(t);let s=0;const r=this._expecting,n=this.meshes.length,o=Object.keys(this.sets);for(let e=0;e{this._calculateMeshUVFrames(a,l,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i{s++,d.update(!1);const i=p.getImageData(0,0,h,h),n=this.sets[m];if(n.getContext().putImageData(i,t.x*f.x,t.y*f.y),d.dispose(),n.update(!1),s==r)return c(),void e()},m=o[u]||"_blank";if(n&&null!==n[m]){const e=n[m],t=new Image;t.src=e instanceof ph?e.getContext().canvas.toDataURL("image/png"):e.url,Ii.SetCorsBehavior(t.src,t),t.onload=()=>{p.fillStyle="rgba(0,0,0,0)",p.fillRect(0,0,h,h),d.update(!1),p.setTransform(1,0,0,-1,0,0);const e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let i=0;i<9;i++)p.drawImage(t,0,0,t.width,t.height,l+a*e[i],l+a*e[i+1]-h,a,a);break;case 1:for(let i=0;i{e.dispose&&e.dispose()};for(let e=0;e{try{if(0===this.meshes.length)return void e();let t=0;const i=i=>{if(t++,this.options.map){for(let e=0;e{i(n)}));else if(t++,t===this.meshes.length)return this._createFrames(e)}}catch(e){return t(e)}}))}dispose(){const e=Object.keys(this.sets);for(let t=0;t{const i={name:this.name,sets:{},options:{},frames:[]},s=Object.keys(this.sets),r=Object.keys(this.options);try{for(let r=0;r!0)){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesIndices"===e.name&&t(e)));i||(i=new Go("matricesIndices"),i.setAsAttribute("matricesIndices")),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesWeights"===e.name&&t(e)));i||(i=new Go("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.World&&t(e)));i||(i=new Go("world"),i.setAsSystemValue(yo.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){cn(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&Sn(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");const t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});const i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});const s=this._outputs[0],r=this.world;return e.compilationString+="#if NUM_BONE_INFLUENCERS>0\n",e.compilationString+=e._declareOutput(s)+` = ${r.associatedVariableName} * ${i};\n`,e.compilationString+="#else\n",e.compilationString+=e._declareOutput(s)+` = ${r.associatedVariableName};\n`,e.compilationString+="#endif\n",this}}),u("BABYLON.InstancesBlock",class extends No{constructor(e){super(e,To.Vertex),this.registerInput("world0",xo.Vector4),this.registerInput("world1",xo.Vector4),this.registerInput("world2",xo.Vector4),this.registerInput("world3",xo.Vector4),this.registerInput("world",xo.Matrix,!0),this.registerOutput("output",xo.Matrix),this.registerOutput("instanceID",xo.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e,t=(()=>!0)){if(!this.world0.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world0"===e.name&&t(e)));i||(i=new Go("world0"),i.setAsAttribute("world0")),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world1"===e.name&&t(e)));i||(i=new Go("world1"),i.setAsAttribute("world1")),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world2"===e.name&&t(e)));i||(i=new Go("world2"),i.setAsAttribute("world2")),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world3"===e.name&&t(e)));i||(i=new Go("world3"),i.setAsAttribute("world3")),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world"===e.name&&t(e)));i||(i=new Go("world"),i.setAsSystemValue(yo.World)),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,s=!1,r){let n=!1;i.INSTANCES!==s&&(i.setValue("INSTANCES",s),n=!0),r&&i.THIN_INSTANCES!==!!r?.getRenderingMesh().hasThinInstances&&(i.setValue("THIN_INSTANCES",!!r?.getRenderingMesh().hasThinInstances),n=!0),n&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);const t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);const i=this._outputs[0],s=this._outputs[1],r=this.world0,n=this.world1,o=this.world2,a=this.world3;let l="mat4",h="gl_InstanceID",c="float";return e.shaderLanguage===ht.WGSL&&(l="mat4x4f",h="vertexInputs.instanceIndex",c="f32"),e.compilationString+="#ifdef INSTANCES\n",e.compilationString+=e._declareOutput(i)+` = ${l}(${r.associatedVariableName}, ${n.associatedVariableName}, ${o.associatedVariableName}, ${a.associatedVariableName});\n`,e.compilationString+="#ifdef THIN_INSTANCES\n",e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName};\n`,e.compilationString+="#endif\n",t._caps.canUseGLInstanceID?e.compilationString+=e._declareOutput(s)+` = ${c}(${h});\n`:e.compilationString+=e._declareOutput(s)+" = 0.0;\n",e.compilationString+="#else\n",e.compilationString+=e._declareOutput(i)+` = ${this.world.associatedVariableName};\n`,e.compilationString+=e._declareOutput(s)+" = 0.0;\n",e.compilationString+="#endif\n",this}});class Dm extends No{constructor(e){super(e,To.Vertex),this.registerInput("position",xo.Vector3),this.registerInput("normal",xo.Vector3),this.registerInput("tangent",xo.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(xo.Color4|xo.Vector4|xo.Vector3),this.registerInput("uv",xo.Vector2),this.registerOutput("positionOutput",xo.Vector3),this.registerOutput("normalOutput",xo.Vector3),this.registerOutput("tangentOutput",xo.Vector4),this.registerOutput("uvOutput",xo.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Go("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Go("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&t(e)));i||(i=new Go("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Go("uv"),i.setAsAttribute("uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const t=e.morphTargetManager;t?.isUsingTextureForTargets&&(t.numMaxInfluencers||t.numInfluencers)!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&En(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(nn(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,s){const r=this.position,n=this.normal,o=this.tangent,a=this.uv,l=this.positionOutput,h=this.normalOutput,c=this.tangentOutput,u=this.uvOutput,d=e,p=s.NUM_MORPH_INFLUENCERS,f=i.morphTargetManager,_=f&&f.supportsNormals&&s.NORMAL,m=f&&f.supportsTangents&&s.TANGENT,g=f&&f.supportsUVs&&s.UV1;let v="";f?.isUsingTextureForTargets&&p>0&&(v+=`${d._declareLocalVar("vertexID",xo.Float)};\n`),v+="#ifdef MORPHTARGETS\n";const x=d.shaderLanguage===ht.WGSL,T=x?"uniforms.":"";if(f?.isUsingTextureForTargets)v+=`for (${x?"var":"int"} i = 0; i < NUM_MORPH_INFLUENCERS; i++) {\n`,v+=`if (i >= ${T}morphTargetCount) { break; }\n`,v+=`vertexID = ${x?"f32(vertexInputs.vertexIndex":"float(gl_VertexID"}) * ${T}morphTargetTextureInfo.x;\n`,v+=`${l.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${r.associatedVariableName}) * ${T}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",_&&(v+="#ifdef MORPHTARGETS_NORMAL\n",v+=`${h.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${n.associatedVariableName}) * ${T}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),g&&(v+="#ifdef MORPHTARGETS_UV\n",v+=`${u.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${a.associatedVariableName}) * ${T}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\n",v+=`${c.associatedVariableName}.xyz += (readVector3FromRawSampler(i, vertexID) - ${o.associatedVariableName}.xyz) * ${T}morphTargetInfluences[i];\n`,o.type===xo.Vector4?v+=`${c.associatedVariableName}.w = ${o.associatedVariableName}.w;\n`:v+=`${c.associatedVariableName}.w = 1.;\n`,v+="#endif\n"),v+="}\n";else for(let e=0;e0)for(let e=0;e!0)){if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.isSystemValue&&e.systemValue===yo.World&&t(e)));i||(i=new Go("world"),i.setAsSystemValue(yo.World)),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Go("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&e.type===xo.Vector4&&t(e)));i||(i=new Go("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){const s=this.normal,r=this.tangent;let n=s.isConnected;s.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(s.connectInputBlock?.name)&&(n=!1);let o=r.isConnected;r.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(r.connectInputBlock?.name)&&(o=!1);const a=n&&o;i.setValue("TBNBLOCK",a,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,s=this.world,r=this.TBN,n=this.row0,o=this.row1,a=this.row2,l=e.shaderLanguage===ht.WGSL,h=l?"mat3x3f":"mat3",c=l?"f":"";return e.target===To.Fragment&&(e.compilationString+=`\n // ${this.name}\n ${e._declareLocalVar("tbnNormal",xo.Vector3)} = normalize(${t.associatedVariableName}).xyz;\n ${e._declareLocalVar("tbnTangent",xo.Vector3)} = normalize(${i.associatedVariableName}.xyz);\n ${e._declareLocalVar("tbnBitangent",xo.Vector3)} = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w;\n ${l?"var":"mat3"} ${r.associatedVariableName} = ${h}(${s.associatedVariableName}[0].xyz, ${s.associatedVariableName}[1].xyz, ${s.associatedVariableName}[2].xyz) * ${h}(tbnTangent, tbnBitangent, tbnNormal);\n `,n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = vec3${c}(${r.associatedVariableName}[0][0], ${r.associatedVariableName}[0][1], ${r.associatedVariableName}[0][2]);\n`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = vec3${c}(${r.associatedVariableName}[1[0], ${r.associatedVariableName}[1][1], ${r.associatedVariableName}[1][2]);\n`),a.hasEndpoints&&(e.compilationString+=e._declareOutput(a)+` = vec3${c}(${r.associatedVariableName}[2][0], ${r.associatedVariableName}[2][1], ${r.associatedVariableName}[2][2]);\n`),e.sharedData.blocksWithDefines.push(this)),this}}u("BABYLON.TBNBlock",Nm);class wm extends No{constructor(e){super(e,To.Fragment),this._tangentSpaceParameterName="",this._tangentCorrectionFactorName="",this._worldMatrixName="",this.invertX=!1,this.invertY=!1,this.useParallaxOcclusion=!1,this.useObjectSpaceNormalMap=!1,this._isUnique=!0,this.registerInput("worldPosition",xo.Vector4,!1),this.registerInput("worldNormal",xo.Vector4,!1),this.registerInput("worldTangent",xo.Vector4,!0),this.registerInput("uv",xo.Vector2,!1),this.registerInput("normalMapColor",xo.Color3,!1),this.registerInput("strength",xo.Float,!1),this.registerInput("viewDirection",xo.Vector3,!0),this.registerInput("parallaxScale",xo.Float,!0),this.registerInput("parallaxHeight",xo.Float,!0),this.registerInput("TBN",xo.Object,!0,To.VertexAndFragment,new Mm("TBN",this,Eo.Input,Nm,"TBNBlock")),this.registerInput("world",xo.Matrix,!0),this.registerOutput("output",xo.Vector4),this.registerOutput("uvOffset",xo.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}prepareDefines(e,t,i){const s=this.normalMapColor.connectedPoint._ownerBlock.samplerName,r=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&s||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",r,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Go("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const e=new Go("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,s=this.worldPosition,r=this.worldNormal,n=this.worldTangent,o=e.shaderLanguage===ht.WGSL,a=o?"mat3x3f":"mat3",l=o?"f":"",h=o?"uniforms.":"";e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,xo.Vector2),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,xo.Float),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,xo.Matrix);let c=null;this.normalMapColor.connectedPoint&&(c=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const u=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&c||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),d=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",p=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${e._emitFloat(this.strength.connectInputBlock.value)}`:`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${this.strength.associatedVariableName}`;o||e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const f={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},_=this.TBN;_.isConnected?e.compilationString+=`\n #ifdef TBNBLOCK\n ${o?"var":"mat3"} vTBN = ${_.associatedVariableName};\n #endif\n `:n.isConnected&&(e.compilationString+=`${e._declareLocalVar("tbnNormal",xo.Vector3)} = normalize(${r.associatedVariableName}.xyz);\n`,e.compilationString+=`${e._declareLocalVar("tbnTangent",xo.Vector3)} = normalize(${n.associatedVariableName}.xyz);\n`,e.compilationString+=`${e._declareLocalVar("tbnBitangent",xo.Vector3)} = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\n`,e.compilationString+=`${o?"var":"mat3"} vTBN = ${a}(tbnTangent, tbnBitangent, tbnNormal);\n`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[f,{search:/varying mat3 vTBN;/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]});const m=o?"fn parallaxOcclusion(vViewDirCoT: vec3f, vNormalCoT: vec3f, texCoord: vec2f, parallaxScale:f32, bump: texture_2d, bumpSampler: sampler)":"#define inline\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)",g=o?/fn parallaxOcclusion\(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32\)/g:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,v=o?"fn parallaxOffset(viewDir: vec3f, heightScale: f32, height_: f32)":"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)",x=o?/fn parallaxOffset\(viewDir: vec3f,heightScale: f32\)/g:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g;e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:g,replace:m},{search:x,replace:v},{search:/texture.+?bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const T=u&&c?`${o?`textureSample(${c}, ${c+"Sampler"}`:`texture2D(${c}`}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName,S=e._getFreeVariableName("tempOutput");return e.compilationString+=e._declareLocalVar(S,xo.Vector3)+` = vec3${l}(0.);\n`,e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture.+?bumpSampler,vBumpUV\)/g,replace:`${T}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`${e._declareLocalVar("normalMatrix",xo.Matrix)} = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture.+?bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${T}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${o?u&&this.useParallaxOcclusion?`${c}, ${c+"Sampler"}`:"bump, bumpSampler":u&&this.useParallaxOcclusion?c:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${u?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:h+this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:p},{search:/vBumpInfos.z/g,replace:d},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:s.associatedVariableName+".xyz"},{search:/normalW=/g,replace:S+" = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:`${a}(normalMatrix) * `+S},{search:/normalW/g,replace:r.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:u?this.viewDirection.associatedVariableName:`vec3${l}(0.)`},f]}),e.compilationString+=e._declareOutput(this.output)+` = vec4${l}(${S}, 0.);\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX};\n`;return e+=`${this._codeVariableName}.invertY = ${this.invertY};\n`,e+=`${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};\n`,e+=`${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};\n`,e}serialize(){const e=super.serialize();return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!e.useObjectSpaceNormalMap}}ae([Lo("Invert X axis",bo.Boolean,"PROPERTIES",{notifiers:{update:!1}})],wm.prototype,"invertX",void 0),ae([Lo("Invert Y axis",bo.Boolean,"PROPERTIES",{notifiers:{update:!1}})],wm.prototype,"invertY",void 0),ae([Lo("Use parallax occlusion",bo.Boolean)],wm.prototype,"useParallaxOcclusion",void 0),ae([Lo("Object Space Mode",bo.Boolean,"PROPERTIES",{notifiers:{update:!1}})],wm.prototype,"useObjectSpaceNormalMap",void 0),u("BABYLON.PerturbNormalBlock",wm),u("BABYLON.DiscardBlock",class extends No{constructor(e){super(e,To.Fragment,!0),this.registerInput("value",xo.Float,!0),this.registerInput("cutoff",xo.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) { discard; }\n`,this}}),u("BABYLON.FrontFacingBlock",class extends No{constructor(e){super(e,To.Fragment),this.registerOutput("output",xo.Float,To.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===To.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary("1.0","0.0",e.shaderLanguage===ht.GLSL?"gl_FrontFacing":"fragmentInputs.frontFacing")};\n`,this}}),u("BABYLON.DerivativeBlock",class extends No{constructor(e){super(e,To.Fragment),this.registerInput("input",xo.AutoDetect,!1),this.registerOutput("dx",xo.BasedOnInput),this.registerOutput("dy",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._outputs[1];e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let s="dFdx",r="dFdy";return e.shaderLanguage===ht.WGSL&&(s="dpdx",r="dpdy"),t.hasEndpoints&&(e.compilationString+=e._declareOutput(t)+` = ${s}(${this.input.associatedVariableName});\n`),i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${r}(${this.input.associatedVariableName});\n`),this}}),u("BABYLON.FragCoordBlock",class extends No{constructor(e){super(e,To.Fragment),this.registerOutput("xy",xo.Vector2,To.Fragment),this.registerOutput("xyz",xo.Vector3,To.Fragment),this.registerOutput("xyzw",xo.Vector4,To.Fragment),this.registerOutput("x",xo.Float,To.Fragment),this.registerOutput("y",xo.Float,To.Fragment),this.registerOutput("z",xo.Float,To.Fragment),this.registerOutput("w",xo.Float,To.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";const i=e.shaderLanguage===ht.WGSL?"fragmentInputs.position":"gl_FragCoord";for(const s of this._outputs)s.hasEndpoints&&(t+=`${e._declareOutput(s)} = ${i}.${s.name};\n`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===To.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}),u("BABYLON.ScreenSizeBlock",class extends No{constructor(e){super(e,To.Fragment),this.registerOutput("xy",xo.Vector2,To.Fragment),this.registerOutput("x",xo.Float,To.Fragment),this.registerOutput("y",xo.Float,To.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){const t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(const s of this._outputs)s.hasEndpoints&&(i+=`${e._declareOutput(s)} = ${t}.${s.name};\n`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===To.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,xo.Vector2);const t=e.shaderLanguage===ht.WGSL?"uniforms.":"";return e.compilationString+=this.writeOutputs(e,t+this._varName),this}}),u("BABYLON.ScreenSpaceBlock",class extends No{constructor(e){super(e,To.Fragment),this.registerInput("vector",xo.AutoDetect),this.registerInput("worldViewProjection",xo.Matrix),this.registerOutput("output",xo.Vector2),this.registerOutput("x",xo.Float),this.registerOutput("y",xo.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e,t=(()=>!0)){if(!this.worldViewProjection.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.WorldViewProjection&&t(e)));i||(i=new Go("worldViewProjection"),i.setAsSystemValue(yo.WorldViewProjection)),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const s=i.associatedVariableName,r=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case xo.Vector3:e.compilationString+=`${e._declareLocalVar(r,xo.Vector4)} = ${s} * vec4${e.fSuffix}(${t.associatedVariableName}, 1.0);\n`;break;case xo.Vector4:e.compilationString+=`${e._declareLocalVar(r,xo.Vector4)} = ${s} * ${t.associatedVariableName};\n`}return e.compilationString+=`${r} = vec4${e.fSuffix}(${r}.xy / ${r}.w, ${r}.zw);`,e.compilationString+=`${r} = vec4${e.fSuffix}(${r}.xy * 0.5 + vec2${e.fSuffix}(0.5, 0.5), ${r}.zw);`,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${r}.xy;\n`),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${r}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${r}.y;\n`),this}}),u("BABYLON.TwirlBlock",class extends No{constructor(e){super(e,To.Fragment),this.registerInput("input",xo.Vector2),this.registerInput("strength",xo.Float),this.registerInput("center",xo.Vector2),this.registerInput("offset",xo.Vector2),this.registerOutput("output",xo.Vector2),this.registerOutput("x",xo.Float),this.registerOutput("y",xo.Float)}getClassName(){return"TwirlBlock"}get input(){return this._inputs[0]}get strength(){return this._inputs[1]}get center(){return this._inputs[2]}get offset(){return this._inputs[3]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(){if(!this.center.isConnected){const e=new Go("center");e.value=new N(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new Go("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new Go("offset");e.value=new N(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),s=e._getFreeVariableName("x"),r=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=` \n ${e._declareLocalVar(t,xo.Vector2)} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName};\n ${e._declareLocalVar(i,xo.Float)} = ${this.strength.associatedVariableName} * length(${t});\n ${e._declareLocalVar(s,xo.Float)} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y;\n ${e._declareLocalVar(r,xo.Float)} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y;\n ${e._declareLocalVar(n,xo.Vector2)} = vec2(${s} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${r} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y);\n `,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${n};\n`),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${n}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${n}.y;\n`),this}});class Fm extends No{constructor(e){super(e,To.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",xo.Float),this.registerInput("worldPosition",xo.Vector3),this.registerInput("worldNormal",xo.Vector3),this.registerInput("worldTangent",xo.AutoDetect,!0),this.registerOutput("output",xo.Vector4),this.registerOutput("xyz",xo.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e.shaderLanguage===ht.WGSL,s=e.fSuffix;this.generateInWorldSpace||this.worldTangent.isConnected||J.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const r=this.generateInWorldSpace?"":"\n vec3 biTangent = cross(norm, tgt);\n mat3 TBN = mat3(tgt, biTangent, norm);\n ",n=this.generateInWorldSpace?"":"\n result = TBN * result;\n result = result * vec3(0.5) + vec3(0.5);\n ";let o=`\n vec4 heightToNormal(float height, vec3 position, vec3 tangent, vec3 normal) {\n vec3 tgt = ${this.automaticNormalizationTangent?"normalize(tangent);":"tangent;"}\n vec3 norm = ${this.automaticNormalizationNormal?"normalize(normal);":"normal;"}\n ${r}\n vec3 worlddX = dFdx(position);\n vec3 worlddY = dFdy(position);\n vec3 crossX = cross(norm, worlddX);\n vec3 crossY = cross(norm, worlddY);\n float d = abs(dot(crossY, worlddX));\n vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));\n inToNormal.y *= -1.0;\n vec3 result = normalize((d * norm) - inToNormal);\n ${n}\n return vec4(result, 0.);\n }`;return i?o=e._babylonSLtoWGSL(o):e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",o,"// heightToNormal"),e.compilationString+=e._declareOutput(t)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:`vec3${s}(0.)`}.xyz, ${this.worldNormal.associatedVariableName});\n`,this.xyz.hasEndpoints&&(e.compilationString+=e._declareOutput(this.xyz)+` = ${this.output.associatedVariableName}.xyz;\n`),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};\n`,e+=`${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};\n`,e+=`${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};\n`,e}serialize(){const e=super.serialize();return e.generateInWorldSpace=this.generateInWorldSpace,e.automaticNormalizationNormal=this.automaticNormalizationNormal,e.automaticNormalizationTangent=this.automaticNormalizationTangent,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.generateInWorldSpace=e.generateInWorldSpace,this.automaticNormalizationNormal=e.automaticNormalizationNormal,this.automaticNormalizationTangent=e.automaticNormalizationTangent}}ae([Lo("Generate in world space instead of tangent space",bo.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Fm.prototype,"generateInWorldSpace",void 0),ae([Lo("Force normalization for the worldNormal input",bo.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Fm.prototype,"automaticNormalizationNormal",void 0),ae([Lo("Force normalization for the worldTangent input",bo.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Fm.prototype,"automaticNormalizationTangent",void 0),u("BABYLON.HeightToNormalBlock",Fm),u("BABYLON.FragDepthBlock",class extends No{constructor(e){super(e,To.Fragment,!0),this.registerInput("depth",xo.Float,!0),this.registerInput("worldPos",xo.Vector4,!0),this.registerInput("viewProjection",xo.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){super._buildBlock(e);const t=e.shaderLanguage===ht.GLSL?"gl_FragDepth":"fragmentOutputs.fragDepth";return this.depth.isConnected?e.compilationString+=`${t} = ${this.depth.associatedVariableName};\n`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=`\n ${e._declareLocalVar("p",xo.Vector4)} = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName};\n ${e._declareLocalVar("v",xo.Vector4)} = p.z / p.w;\n #ifndef IS_NDC_HALF_ZRANGE\n v = v * 0.5 + 0.5;\n #endif\n ${t} = v;\n \n `:J.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}),u("BABYLON.ShadowMapBlock",class extends No{constructor(e){super(e,To.Fragment),this.registerInput("worldPosition",xo.Vector4,!1),this.registerInput("viewProjection",xo.Matrix,!1),this.registerInput("worldNormal",xo.AutoDetect,!0),this.registerOutput("depth",xo.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM")}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitUniformFromString("biasAndScaleSM",xo.Vector3),e._emitUniformFromString("lightDataSM",xo.Vector3),e._emitUniformFromString("depthValuesSM",xo.Vector3),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`vec4 worldPos = ${this.worldPosition.associatedVariableName};\n`,e.compilationString+="vec3 vPositionWSM;\n",e.compilationString+="float vDepthMetricSM = 0.0;\n",e.compilationString+="float zSM;\n",this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+="\n #if SM_DEPTHTEXTURE == 1\n #ifdef IS_NDC_HALF_ZRANGE\n gl_FragDepth = (clipPos.z / clipPos.w);\n #else\n gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5;\n #endif\n #endif\n ",e.compilationString+=`${e._declareOutput(this.depth)} = vec3(depthSM, 1., 1.);\n`,this}}),u("BABYLON.PrePassOutputBlock",class extends No{constructor(e){super(e,To.Fragment,!0),this.registerInput("viewDepth",xo.Float,!0),this.registerInput("worldPosition",xo.AutoDetect,!0),this.registerInput("viewNormal",xo.AutoDetect,!0),this.registerInput("reflectivity",xo.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(xo.Vector3|xo.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(xo.Vector3|xo.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(xo.Vector3|xo.Vector4|xo.Color3|xo.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}get reflectivity(){return this._inputs[3]}_buildBlock(e){super._buildBlock(e);const t=this.worldPosition,i=this.viewNormal,s=this.viewDepth,r=this.reflectivity;e.sharedData.blocksWithDefines.push(this);const n=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",n),e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+="#ifdef PREPASS_DEPTH\r\n",s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${s.associatedVariableName}, 0.0, 0.0, 1.0);\r\n`:e.compilationString+=" gl_FragData[PREPASS_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_POSITION\r\n",t.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===xo.Vector4?t.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_NORMAL\r\n",i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===xo.Vector4?i.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_REFLECTIVITY\r\n",r.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(${r.associatedVariableName}.rgb, ${r.connectedPoint.type===xo.Vector4?r.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#endif\r\n",this}}),u("BABYLON.FogBlock",class extends No{constructor(e){super(e,To.VertexAndFragment,!1),this.registerInput("worldPosition",xo.Vector4,!1,To.Vertex),this.registerInput("view",xo.Matrix,!1,To.Vertex),this.registerInput("input",xo.AutoDetect,!1,To.Fragment),this.registerInput("fogColor",xo.AutoDetect,!1,To.Fragment),this.registerOutput("output",xo.Color3,To.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e,t=(()=>!0)){if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.View&&t(e)));i||(i=new Go("view"),i.setAsSystemValue(yo.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.FogColor&&t(e)));i||(i=new Go("fogColor",void 0,xo.Color3),i.setAsSystemValue(yo.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const s=e.getScene();i.setValue("FOG",t.fogEnabled&&mn(e,s))}bind(e,t,i){if(!i)return;const s=i.getScene();e.setFloat4(this._fogParameters,s.fogMode,s.fogStart,s.fogEnd,s.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===To.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=[],i="",s="";e.shaderLanguage===ht.WGSL?(t=[{search:/fn CalcFogFactor\(\)/,replace:"fn CalcFogFactor(vFogDistance: vec3f, vFogInfos: vec4f)"},{search:/uniforms.vFogInfos/g,replace:"vFogInfos"},{search:/fragmentInputs.vFogDistance/g,replace:"vFogDistance"}],i="fragmentInputs.",s="uniforms."):t=[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}],e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:t});const r=e._getFreeVariableName("fog"),n=this.input,o=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const a=this._outputs[0];e._emitUniformFromString(this._fogParameters,xo.Vector4),e.compilationString+="#ifdef FOG\n",e.compilationString+=`${e._declareLocalVar(r,xo.Float)} = CalcFogFactor(${i}${this._fogDistanceName}, ${s}${this._fogParameters});\n`,e.compilationString+=e._declareOutput(a)+` = ${r} * ${n.associatedVariableName}.rgb + (1.0 - ${r}) * ${o.associatedVariableName}.rgb;\n`,e.compilationString+=`#else\n${e._declareOutput(a)} = ${n.associatedVariableName}.rgb;\n`,e.compilationString+="#endif\n"}else{const t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,xo.Vector3);const s=e.shaderLanguage===ht.WGSL?"vertexOutputs.":"";e.compilationString+=`${s}${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz;\n`}return this}});class Lm extends No{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,J.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?To.Fragment:To.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?To.Fragment:To.Vertex}constructor(e){super(e,To.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",xo.Vector4,!1,To.Vertex),this.registerInput("worldNormal",xo.Vector4,!1,To.Fragment),this.registerInput("cameraPosition",xo.Vector3,!1,To.Fragment),this.registerInput("glossiness",xo.Float,!0,To.Fragment),this.registerInput("glossPower",xo.Float,!0,To.Fragment),this.registerInput("diffuseColor",xo.Color3,!0,To.Fragment),this.registerInput("specularColor",xo.Color3,!0,To.Fragment),this.registerInput("view",xo.Matrix,!0),this.registerOutput("diffuseOutput",xo.Color3,To.Fragment),this.registerOutput("specularOutput",xo.Color3,To.Fragment),this.registerOutput("shadow",xo.Float,To.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.CameraPosition&&t(e)));i||(i=new Go("cameraPosition"),i.setAsSystemValue(yo.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const s=e.getScene();if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};xn(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else vn(s,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;Pn(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,t)}}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?un(this.light,this._lightId,s,e,!0):dn(s,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,xo.Vector4)&&(e.compilationString+=(e.shaderLanguage===ht.WGSL?"vertexOutputs.":"")+`${s} = ${t.associatedVariableName};\n`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`${e._declareLocalVar("worldPos",xo.Vector4)} = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`${e._declareLocalVar("view",xo.Matrix)} = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_injectUBODeclaration(e){const t=`//${this.name}`;this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0})}_buildBlock(e){super._buildBlock(e);const t=e.shaderLanguage===ht.WGSL,i=t?"f":"",s=`//${this.name}`;if(e.target!==To.Fragment)return void this._injectVertexCode(e);this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const r=e.shaderLanguage===ht.WGSL?"fragmentInputs.":"";e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const n=this.worldPosition;let o=n.associatedVariableName;this.generateOnlyFragmentCode?(o=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`${e._declareLocalVar(o,xo.Vector3)};\n`,s),e.compilationString+=`${o} = ${n.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${n.associatedVariableName}`:void 0})):o=r+"v_"+o+".xyz",e._emitFunctionFromInclude("helperFunctions",s),e._emitFunctionFromInclude("lightsFragmentFunctions",s,{replaceStrings:[{search:/vPositionW/g,replace:o}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",s,{replaceStrings:[{search:/vPositionW/g,replace:o}]}),this._injectUBODeclaration(e),0===this._lightId&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`${e._declareLocalVar("viewDirectionW",xo.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${o});\n`),e.compilationString+=t?"var info: lightingInfo;\n":"lightingInfo info;\n",e.compilationString+=`${e._declareLocalVar("shadow",xo.Float)} = 1.;\n`,e.compilationString+=`${e._declareLocalVar("aggShadow",xo.Float)} = 0.;\n`,e.compilationString+=`${e._declareLocalVar("numLights",xo.Float)} = 0.;\n`,e.compilationString+=`${e._declareLocalVar("glossiness",xo.Float)} = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"};\n`,e.compilationString+=`${e._declareLocalVar("diffuseBase",xo.Vector3)} = vec3${i}(0., 0., 0.);\n`,e.compilationString+=`${e._declareLocalVar("specularBase",xo.Vector3)} = vec3${i}(0., 0., 0.);\n`,e.compilationString+=`${e._declareLocalVar("normalW",xo.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz;\n`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:o+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",s,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${o}.xyz`}),0===this._lightId&&(e.compilationString+="aggShadow = aggShadow / numLights;\n");const a=this.diffuseOutput,l=this.specularOutput;return e.compilationString+=e._declareOutput(a)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""};\n`,l.hasEndpoints&&(e.compilationString+=e._declareOutput(l)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""};\n`),this.shadow.hasEndpoints&&(e.compilationString+=e._declareOutput(this.shadow)+" = aggShadow;\n"),this}serialize(){const e=super.serialize();return e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}ae([Lo("Generate only fragment code",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Lm._OnGenerateOnlyFragmentCodeChanged}})],Lm.prototype,"generateOnlyFragmentCode",void 0),u("BABYLON.LightBlock",Lm);class Bm extends No{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??y.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get samplerName(){return this._samplerName}constructor(e){super(e,To.VertexAndFragment),this.registerOutput("source",xo.Object,To.VertexAndFragment,new Mm("source",this,Eo.Output,Bm,"ImageSourceBlock"))}bind(e){this.texture&&e.setTexture(this._samplerName,this.texture)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}getClassName(){return"ImageSourceBlock"}get source(){return this._outputs[0]}_buildBlock(e){return super._buildBlock(e),e.target===To.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Texture"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i,s){super._deserialize(e,t,i,s),e.texture&&!xa.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(0===e.texture.url.indexOf("data:")?i="":s&&(e.texture.url=s(e.texture.url),e.texture.name=e.texture.url),this.texture=Zn.Parse(e.texture,t,i))}}u("BABYLON.ImageSourceBlock",Bm);class Vm extends No{get texture(){return this.source.isConnected?(this.source.connectedPoint?.ownerBlock).texture:this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??y.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _IsPrePassTextureBlock(e){return"PrePassTextureBlock"===e?.getClassName()}get _isSourcePrePass(){return Vm._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!Vm._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=this.texture.getScene()??y.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??y.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?To.Fragment:To.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",xo.AutoDetect,!1,To.VertexAndFragment),this.registerInput("source",xo.Object,!0,To.VertexAndFragment,new Mm("source",this,Eo.Input,Bm,"ImageSourceBlock")),this.registerInput("layer",xo.Float,!0),this.registerInput("lod",xo.Float,!0),this.registerOutput("rgba",xo.Color4,To.Neutral),this.registerOutput("rgb",xo.Color3,To.Neutral),this.registerOutput("r",xo.Float,To.Neutral),this.registerOutput("g",xo.Float,To.Neutral),this.registerOutput("b",xo.Float,To.Neutral),this.registerOutput("a",xo.Float,To.Neutral),this.registerOutput("level",xo.Float,To.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Vector2|xo.Vector3|xo.Vector4),this._inputs[0]._prioritizeVertex=!t}getClassName(){return"TextureBlock"}get uv(){return this._inputs[0]}get source(){return this._inputs[1]}get layer(){return this._inputs[2]}get lod(){return this._inputs[3]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}get target(){if(this._fragmentOnly)return To.Fragment;if(!this.uv.isConnected)return To.VertexAndFragment;if(this.uv.sourceBlock.isInput)return To.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===To.Fragment)return To.Fragment;if(e.target===To.Vertex)return To.VertexAndFragment;if(e.target===To.Neutral||e.target===To.VertexAndFragment){const t=e.ownerBlock;if(t.target===To.Fragment)return To.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return To.VertexAndFragment}set target(e){}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected)if(e.mode===ea.PostProcess){const i=e.getBlockByPredicate((e=>"uv"===e.name&&t(e)));i&&i.connectTo(this)}else{const i=e.mode===ea.Particle?"particle_uv":"uv";let s=e.getInputBlockByPredicate((e=>e.isAttribute&&e.name===i&&t(e)));s||(s=new Go("uv"),s.setAsAttribute(i)),s.output.connectTo(this.uv)}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix)return void(this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)));const s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),null==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!!this._isSourcePrePass||!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==To.Fragment}_injectVertexCode(e){const t=this.uv;this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.declarationVariableName.toUpperCase(),this._mainUVName="vMain"+t.declarationVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,xo.Vector2,this._defineName),e._emitVaryingFromString(this._mainUVName,xo.Vector2,this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,xo.Matrix,this._defineName);const i=e._getShaderType(xo.Vector4),s=e._getShaderType(xo.Vector2);if(e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`${e._getVaryingName(this._transformedUVName)} = ${s}(${this._textureTransformName} * ${i}(${t.associatedVariableName}.xy, 1.0, 0.0));\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`,e.compilationString+=`${e._getVaryingName(this._mainUVName)} = ${t.associatedVariableName}.xy;\n`,e.compilationString+="#endif\n",this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}}_getUVW(e){let t=e;const i=this._texture?._texture?.is2DArray??!1,s=this._texture?._texture?.is3D??!1;return(i||s)&&(t=`vec3(${e}, ${this.layer.isConnected?this.layer.associatedVariableName:"0"})`),t}_samplerFunc(e){return e.shaderLanguage===ht.WGSL?e.target===To.Vertex?"textureSampleLevel":"textureSample":this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureSample(e,t){if(t.shaderLanguage===ht.WGSL){const i=t.target===To.Vertex;return`${this._samplerFunc(t)}(${this.samplerName},${this.samplerName+"Sampler"}, ${this._getUVW(e)}${this._samplerLodSuffix}${i?", 0":""})`}return`${this._samplerFunc(t)}(${this.samplerName}, ${this._getUVW(e)}${this._samplerLodSuffix})`}_generateTextureLookup(e){e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,xo.Vector4)} = ${this._generateTextureSample(e._getVaryingName(this._transformedUVName),e)};\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,xo.Vector4)} = ${this._generateTextureSample(this._mainUVName?e._getVaryingName(this._mainUVName):this.uv.associatedVariableName,e)}${this._samplerLodSuffix};\n`,e.compilationString+="#endif\n"}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===To.Fragment)return;this._generateTextureLookup(e)}else this.uv.ownerBlock.target!==To.Fragment?this._generateTextureLookup(e):e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,xo.Vector4)} = ${this._generateTextureSample(i.associatedVariableName,e)}${this._samplerLodSuffix};\n`}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i,s=!1){if(s){if(e.target===To.Fragment)return;return e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i)}if(this.uv.ownerBlock.target===To.Fragment)return e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i);let r="";this.disableLevelMultiplication||(r=" * "+(e.shaderLanguage===ht.WGSL?"uniforms.":"")+this._textureInfoName),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${r};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===To.Vertex||this._fragmentOnly||e.target===To.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),!this._isMixed&&e.target===To.Fragment||this._isMixed&&e.target===To.Vertex){if(!this._imageSource){const t=e._getFreeVariableName(this.name);this._samplerName=t+"Texture",this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)}e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)}if(e.target!==To.Fragment)return void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;this._isMixed&&!this._imageSource&&(this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._isMixed&&e._emitUniformFromString(this._textureInfoName,xo.Float),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i,s){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!xa.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(0===e.texture.url.indexOf("data:")?i="":s&&(e.texture.url=s(e.texture.url),e.texture.name=e.texture.url),this.texture=Zn.Parse(e.texture,t,i))}}u("BABYLON.TextureBlock",Vm);class Um extends No{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??y.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?To.Fragment:To.VertexAndFragment)}constructor(e){super(e,To.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Go("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.World&&t(e)));i||(i=new Go("world"),i.setAsSystemValue(yo.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.View&&t(e)));i||(i=new Go("view"),i.setAsSystemValue(yo.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this._getTexture();s&&s.getTextureMatrix&&(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLocalCubicName,!!s.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===s.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===s.coordinatesMode,!0),i.setValue(this._defineCubicName,3===s.coordinatesMode||6===s.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===s.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===s.coordinatesMode,!0),i.setValue(this._definePlanarName,2===s.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===s.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===s.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===s.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===s.coordinatesMode,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i,s){const r=this._getTexture();if(i&&r&&(e.setMatrix(this._reflectionMatrixName,r.getReflectionTextureMatrix()),r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),r.boundingBoxSize)){const t=r;e.setVector3(this._reflectionPositionName,t.boundingBoxPosition),e.setVector3(this._reflectionSizeName,t.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===To.Vertex)return"";this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,xo.Matrix);let t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");const i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,xo.Vector4))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName};\n`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,xo.Vector3,this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName}\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\n`,t+="#endif\n"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,xo.Vector3,`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0)));\n`,t+="#endif\n"),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\n`,e._samplerDeclaration+="#else\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\n`,e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,xo.Vector3),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,xo.Vector3)}handleFragmentSideCodeReflectionCoords(e,t,i=!1,s=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const r=this._reflectionMatrixName,n=`normalize(${this._directionWName})`,o=`${this._positionUVWName}`,a=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=`\n #ifdef ${this._defineMirroredEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${n});\n #endif\n\n #ifdef ${this._defineEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${n});\n #endif\n\n #ifdef ${this._defineEquirectangularName}\n vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n\n #ifdef ${this._defineSphericalName}\n vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${r});\n #endif\n\n #ifdef ${this._definePlanarName}\n vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n\n #ifdef ${this._defineCubicName}\n #ifdef ${this._defineLocalCubicName}\n vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${a}.xyz, ${r}, ${this._reflectionSizeName}, ${this._reflectionPositionName});\n #else\n vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n #endif\n\n #ifdef ${this._defineProjectionName}\n vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${r});\n #endif\n\n #ifdef ${this._defineSkyboxName}\n vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${o}, ${r});\n #endif\n\n #ifdef ${this._defineExplicitName}\n vec3 ${this._reflectionVectorName} = vec3(0, 0, 0);\n #endif\n`;return s||(h+=`#ifdef ${this._defineOppositeZ}\n ${this._reflectionVectorName}.z *= -1.0;\n #endif\n`),i||(h+=`\n #ifdef ${this._define3DName}\n vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName};\n #else\n vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy;\n #ifdef ${this._defineProjectionName}\n ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;\n #endif\n ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;\n #endif\n`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i=`${"vec"+(0===t.length?"4":t.length-1)} ${this._reflectionColorName};\n #ifdef ${this._define3DName}\n`;return i+=e?`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t};\n`:`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t};\n`,i+="\n #else\n",i+=e?`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t};\n`:`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t};\n`,i+="#endif\n",i}writeOutputs(e,t){let i="";if(e.target===To.Fragment)for(const s of this._outputs)s.hasEndpoints&&(i+=`${e._declareOutput(s)} = ${t}.${s.name};\n`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){const t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"});\n`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);\n`;return e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!xa.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=tf.Parse(e.texture,t,i):this.texture=Zn.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}ae([Lo("Generate only fragment code",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Um._OnGenerateOnlyFragmentCodeChanged}})],Um.prototype,"generateOnlyFragmentCode",void 0),u("BABYLON.ReflectionTextureBaseBlock",Um),u("BABYLON.ReflectionTextureBlock",class extends Um{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,J.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,J.Error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?To.Fragment:To.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?To.Fragment:To.Vertex}constructor(e){super(e),this.registerInput("position",xo.AutoDetect,!1,To.Vertex),this.registerInput("worldPosition",xo.Vector4,!1,To.Vertex),this.registerInput("worldNormal",xo.Vector4,!1,To.Fragment),this.registerInput("world",xo.Matrix,!1,To.Vertex),this.registerInput("cameraPosition",xo.Vector3,!1,To.Fragment),this.registerInput("view",xo.Matrix,!1,To.Fragment),this.registerOutput("rgb",xo.Color3,To.Fragment),this.registerOutput("rgba",xo.Color4,To.Fragment),this.registerOutput("r",xo.Float,To.Fragment),this.registerOutput("g",xo.Float,To.Fragment),this.registerOutput("b",xo.Float,To.Fragment),this.registerOutput("a",xo.Float,To.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e,t=(()=>!0)){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.CameraPosition&&t(e)));i||(i=new Go("cameraPosition"),i.setAsSystemValue(yo.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==To.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);const t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName});\n`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}});class km extends No{constructor(e){super(e,To.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",xo.AutoDetect,!1,To.VertexAndFragment),this.registerOutput("depth",xo.Float,To.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Vector2|xo.Vector3|xo.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"SceneDepthBlock"}get uv(){return this._inputs[0]}get depth(){return this._outputs[0]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?To.VertexAndFragment:To.Fragment:To.VertexAndFragment}_getTexture(e){return e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ).getDepthMap()}bind(e,t){const i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,t.type===xo.Vector3?xo.Vector3:t.type===xo.Vector4?xo.Vector4:xo.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,xo.Vector2),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===To.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\n`}else this.uv.ownerBlock.target!==To.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\n`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===To.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target,To.Fragment,e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.bindableBlocks.indexOf(this)<0&&e.sharedData.bindableBlocks.push(this),e.target!==To.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(this._outputs.some((e=>e.isConnectedInFragmentShader))){e._emit2DSampler(this._samplerName),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){const e=super.serialize();return e.useNonLinearDepth=this.useNonLinearDepth,e.storeCameraSpaceZ=this.storeCameraSpaceZ,e.force32itsFloat=this.force32itsFloat,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useNonLinearDepth=e.useNonLinearDepth,this.storeCameraSpaceZ=!!e.storeCameraSpaceZ,this.force32itsFloat=e.force32itsFloat}}ae([Lo("Use non linear depth",bo.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let s=!1;return i.useNonLinearDepth&&(i.storeCameraSpaceZ=!1,s=!0),e&&e.disableDepthRenderer(),s}}})],km.prototype,"useNonLinearDepth",void 0),ae([Lo("Store Camera space Z",bo.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let s=!1;return i.storeCameraSpaceZ&&(i.useNonLinearDepth=!1,s=!0),e&&e.disableDepthRenderer(),s}}})],km.prototype,"storeCameraSpaceZ",void 0),ae([Lo("Force 32 bits float",bo.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>e?.disableDepthRenderer()}})],km.prototype,"force32itsFloat",void 0),u("BABYLON.SceneDepthBlock",km),u("BABYLON.ClipPlanesBlock",class extends No{constructor(e){super(e,To.VertexAndFragment,!0),this.registerInput("worldPosition",xo.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6")}get worldPosition(){return this._inputs[0]}get target(){return To.VertexAndFragment}set target(e){}prepareDefines(e,t,i){const s=e.getScene(),r=!!(t.clipPlane??s.clipPlane),n=!!(t.clipPlane2??s.clipPlane2),o=!!(t.clipPlane3??s.clipPlane3),a=!!(t.clipPlane4??s.clipPlane4),l=!!(t.clipPlane5??s.clipPlane5),h=!!(t.clipPlane6??s.clipPlane6);i.setValue("CLIPPLANE",r,!0),i.setValue("CLIPPLANE2",n,!0),i.setValue("CLIPPLANE3",o,!0),i.setValue("CLIPPLANE4",a,!0),i.setValue("CLIPPLANE5",l,!0),i.setValue("CLIPPLANE6",h,!0)}bind(e,t,i){i&&Kr(e,t,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==To.Fragment){const i=this.worldPosition;return e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane",xo.Vector4),e._emitUniformFromString("vClipPlane2",xo.Vector4),e._emitUniformFromString("vClipPlane3",xo.Vector4),e._emitUniformFromString("vClipPlane4",xo.Vector4),e._emitUniformFromString("vClipPlane5",xo.Vector4),void e._emitUniformFromString("vClipPlane6",xo.Vector4)}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}),u("BABYLON.PrePassTextureBlock",class extends No{get texture(){return null}set texture(e){}constructor(e,t=To.VertexAndFragment){super(e,t,!1),this.registerOutput("position",xo.Object,To.VertexAndFragment,new Mm("position",this,Eo.Output,Bm,"ImageSourceBlock")),this.registerOutput("depth",xo.Object,To.VertexAndFragment,new Mm("depth",this,Eo.Output,Bm,"ImageSourceBlock")),this.registerOutput("normal",xo.Object,To.VertexAndFragment,new Mm("normal",this,Eo.Output,Bm,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==To.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){const i=t.getScene().enablePrePassRenderer();if(!i)return;const s=i.defaultRT;s.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,s.textures[i.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,s.textures[i.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,s.textures[i.getIndex(6)]))}}),u("BABYLON.NodeMaterialTeleportInBlock",class extends No{get endpoints(){return this._endpoints}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==To.VertexAndFragment)return t.target;if(e.connectedPoint.target!==To.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}constructor(e){super(e,To.Neutral),this._endpoints=[],this.registerInput("input",xo.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some((e=>e.output.isConnectedInFragmentShader))}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)-1===t.indexOf(s)&&(i+=s._dumpCode(e,t));return i}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(t.isAnAncestorOf(e))return!0}return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){super.dispose();for(const e of this._endpoints)this.detachFromEndpoint(e);this._endpoints=[]}}),u("BABYLON.NodeMaterialTeleportOutBlock",class extends No{constructor(e){super(e,To.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",xo.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){this._target&e||(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=e._declareOutput(this.output)+` = ${this.entryPoint.input.associatedVariableName};\n`)}clone(e,t=""){const i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}),u("BABYLON.AddBlock",class extends Zo{constructor(e){super(e)}getClassName(){return"AddBlock"}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName};\n`,this}}),u("BABYLON.ScaleBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("input",xo.AutoDetect),this.registerInput("factor",xo.Float),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ScaleBlock"}get input(){return this._inputs[0]}get factor(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName};\n`,this}});class Gm extends No{constructor(e){super(e,To.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e.shaderLanguage===ht.WGSL?e._getShaderType(this.value.type):"";return e.compilationString+=e._declareOutput(t)+` = clamp(${this.value.associatedVariableName}, ${i}(${this._writeFloat(this.minimum)}), ${i}(${this._writeFloat(this.maximum)}));\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.minimum=e.minimum,this.maximum=e.maximum}}ae([Lo("Minimum",bo.Float)],Gm.prototype,"minimum",void 0),ae([Lo("Maximum",bo.Float)],Gm.prototype,"maximum",void 0),u("BABYLON.ClampBlock",Gm),u("BABYLON.CrossBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("left",xo.AutoDetect),this.registerInput("right",xo.AutoDetect),this.registerOutput("output",xo.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(xo.Float),this._inputs[0].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[0].excludedConnectionPointTypes.push(xo.Vector2),this._inputs[1].excludedConnectionPointTypes.push(xo.Float),this._inputs[1].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xo.Vector2)}getClassName(){return"CrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz);\n`,this}}),u("BABYLON.CustomBlock",class extends No{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach((s=>{const r=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),n=e._getGLType(s.type);t=t.replace(r,n),i=i.replace(r,n)})),this._outputs.forEach((s=>{const r=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),n=e._getGLType(s.type);t=t.replace(r,n),i=i.replace(r,n)})),e._emitFunction(i,t,""),this._outputs.forEach((t=>{e.compilationString+=e._declareOutput(t)+";\n"})),e.compilationString+=i+"(";let s=!1;return this._inputs.forEach(((t,i)=>{i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=t.connectedPoint?.ownerBlock?.samplerName??t.associatedVariableName:e.compilationString+=t.associatedVariableName,s=!0})),this._outputs.forEach(((t,i)=>{(i>0||s)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName})),e.compilationString+=");\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.options = ${JSON.stringify(this._options)};\n`,e}serialize(){const e=super.serialize();return e.options=this._options,e}_deserialize(e,t,i){this._deserializeOptions(e.options),super._deserialize(e,t,i)}_deserializeOptions(e){this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=To[e.target],e.inParameters?.forEach(((e,t)=>{const i=xo[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,xo.Object,!0,To.VertexAndFragment,new Mm(e.name,this,Eo.Input,Bm,"ImageSourceBlock"))):this.registerInput(e.name,i),Object.defineProperty(this,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})})),e.outParameters?.forEach(((e,t)=>{this.registerOutput(e.name,xo[e.type]),Object.defineProperty(this,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(this._outputs[t]._typeConnectionSource=this._findInputByName(e.typeFromInput)[0])})),e.inLinkedConnectionTypes?.forEach((e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])}))}_findInputByName(e){if(!e)return null;for(let t=0;t!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.CameraPosition&&t(e)));i||(i=new Go("cameraPosition"),i.setAsSystemValue(yo.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz);\n`,this}}var Hm;u("BABYLON.ViewDirectionBlock",Wm),u("BABYLON.FresnelBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("worldNormal",xo.Vector4),this.registerInput("viewDirection",xo.Vector3),this.registerInput("bias",xo.Float),this.registerInput("power",xo.Float),this.registerOutput("fresnel",xo.Float)}getClassName(){return"FresnelBlock"}get worldNormal(){return this._inputs[0]}get viewDirection(){return this._inputs[1]}get bias(){return this._inputs[2]}get power(){return this._inputs[3]}get fresnel(){return this._outputs[0]}autoConfigure(e){if(!this.viewDirection.isConnected){const t=new Wm("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const e=new Go("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){const e=new Go("power");e.value=1,e.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitFunctionFromInclude("fresnelFunction",t,{removeIfDef:!0}),e.compilationString+=e._declareOutput(this.fresnel)+` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName});\n`,this}}),u("BABYLON.MaxBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("left",xo.AutoDetect),this.registerInput("right",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MaxBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`,this}}),u("BABYLON.MinBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("left",xo.AutoDetect),this.registerInput("right",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MinBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`,this}}),u("BABYLON.DistanceBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("left",xo.AutoDetect),this.registerInput("right",xo.AutoDetect),this.registerOutput("output",xo.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(xo.Float),this._inputs[0].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xo.Float),this._inputs[1].excludedConnectionPointTypes.push(xo.Matrix)}getClassName(){return"DistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName});\n`,this}}),u("BABYLON.LengthBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("value",xo.AutoDetect),this.registerOutput("output",xo.Float),this._inputs[0].excludedConnectionPointTypes.push(xo.Float),this._inputs[0].excludedConnectionPointTypes.push(xo.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = length(${this.value.associatedVariableName});\n`,this}}),u("BABYLON.NegateBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("value",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NegateBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = -1.0 * ${this.value.associatedVariableName};\n`,this}}),u("BABYLON.PowBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("value",xo.AutoDetect),this.registerInput("power",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"PowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName});\n`,this}}),u("BABYLON.RandomNumberBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("seed",xo.AutoDetect),this.registerOutput("output",xo.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Vector2|xo.Vector3|xo.Vector4|xo.Color3|xo.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=e._declareOutput(t)+` = getRand(${this.seed.associatedVariableName}.xy);\n`,this}}),u("BABYLON.ArcTan2Block",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("x",xo.Float),this.registerInput("y",xo.Float),this.registerOutput("output",xo.Float)}getClassName(){return"ArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e.shaderLanguage===ht.WGSL?"atan2":"atan";return e.compilationString+=e._declareOutput(t)+` = ${i}(${this.x.associatedVariableName}, ${this.y.associatedVariableName});\n`,this}}),u("BABYLON.SmoothStepBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("value",xo.AutoDetect),this.registerInput("edge0",xo.Float),this.registerInput("edge1",xo.Float),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"SmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e._getShaderType(this.value.type);return e.compilationString+=e._declareOutput(t)+` = smoothstep(${i}(${this.edge0.associatedVariableName}), ${i}(${this.edge1.associatedVariableName}), ${this.value.associatedVariableName});\n`,this}}),u("BABYLON.ReciprocalBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("input",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ReciprocalBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return this.input.type===xo.Matrix?e.compilationString+=e._declareOutput(t)+` = inverse(${this.input.associatedVariableName});\n`:e.compilationString+=e._declareOutput(t)+` = 1. / ${this.input.associatedVariableName};\n`,this}}),u("BABYLON.ReplaceColorBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("value",xo.AutoDetect),this.registerInput("reference",xo.AutoDetect),this.registerInput("distance",xo.Float),this.registerInput("replacement",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(xo.Float),this._inputs[0].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xo.Float),this._inputs[1].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[3].excludedConnectionPointTypes.push(xo.Float),this._inputs[3].excludedConnectionPointTypes.push(xo.Matrix)}getClassName(){return"ReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+";\n",e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {\n`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName};\n`,e.compilationString+="} else {\n",e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName};\n`,e.compilationString+="}\n",this}}),u("BABYLON.PosterizeBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("value",xo.AutoDetect),this.registerInput("steps",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(xo.Float)}getClassName(){return"PosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName});\n`,this}}),function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(Hm||(Hm={})),u("BABYLON.WaveBlock",class extends No{constructor(e){super(e,To.Neutral),this.kind=Hm.SawTooth,this.registerInput("input",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(xo.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];switch(this.kind){case Hm.SawTooth:e.compilationString+=e._declareOutput(t)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\n`;break;case Hm.Square:e.compilationString+=e._declareOutput(t)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\n`;break;case Hm.Triangle:e.compilationString+=e._declareOutput(t)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\n`}return this}serialize(){const e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}});class Xm{get step(){return this._step}set step(e){this._step=e}get color(){return this._color}set color(e){this._color=e}constructor(e,t){this.step=e,this.color=t}}u("BABYLON.GradientBlock",class extends No{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,To.Neutral),this.colorSteps=[new Xm(0,Y.Black()),new Xm(1,Y.White())],this.onValueChangedObservable=new g,this.registerInput("gradient",xo.AutoDetect),this.registerOutput("output",xo.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Float|xo.Vector2|xo.Vector3|xo.Vector4|xo.Color3|xo.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e,t){const i=this.colorSteps[e];return`${t}(${i.color.r}, ${i.color.g}, ${i.color.b})`}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e._getShaderType(xo.Vector3);if(!this.colorSteps.length||!this.gradient.connectedPoint)return void(e.compilationString+=e._declareOutput(t)+` = ${i}(0., 0., 0.);\n`);const s=e._getFreeVariableName("gradientTempColor"),r=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`${e._declareLocalVar(s,xo.Vector3)} = ${this._writeColorConstant(0,i)};\n`,e.compilationString+=`${e._declareLocalVar(r,xo.Float)};\n`;let n=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==xo.Float&&(n+=".x");for(let t=1;t!0)){if(!this.intensity.isConnected){const e=new Go("Refraction intensity",To.Fragment,xo.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.View&&t(e)));i||(i=new Go("view"),i.setAsSystemValue(yo.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this._getTexture(),r=s&&s.getTextureMatrix;i.setValue("SS_REFRACTION",r,!0),r&&(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLODRefractionAlpha,s.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,s.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&s.isCube?!s.invertZ:s.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",s.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",s.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!s.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){super.bind(e,t,i);const s=this._getTexture();if(!s)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s),e.setMatrix(this._refractionMatrixName,s.getRefractionTextureMatrix());let r=1;s.isCube||s.depth&&(r=s.depth);const n=this.volumeIndexOfRefraction.connectInputBlock?.value??this.indexOfRefractionConnectionPoint.connectInputBlock?.value??1.5;e.setFloat4(this._vRefractionInfosName,s.level,1/n,r,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,s.getSize().width,s.lodGenerationScale,s.lodGenerationOffset,1/n);const o=s.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,o,G.Log2(o)),s.boundingBoxSize){const t=s;e.setVector3("vRefractionPosition",t.boundingBoxPosition),e.setVector3("vRefractionSize",t.boundingBoxSize)}}getCode(e){return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\n`,e._samplerDeclaration+="#else\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\n`,e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,xo.Matrix),e._emitFunction("sampleRefraction",`\n #ifdef ${this._define3DName}\n #define sampleRefraction(s, c) textureCube(s, c)\n #else\n #define sampleRefraction(s, c) texture2D(s, c)\n #endif\n`,`//${this.name}`),e._emitFunction("sampleRefractionLod",`\n #ifdef ${this._define3DName}\n #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\n`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,xo.Vector4),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,xo.Vector4),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,xo.Vector2),e._emitUniformFromString("vRefractionPosition",xo.Vector3),e._emitUniformFromString("vRefractionSize",xo.Vector3),""}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e=this.texture.isCube?`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\n`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\n`,e+=`${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\n`,e+=`${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=tf.Parse(e.texture,t,i):this.texture=Zn.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}ae([Lo("Link refraction to transparency",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],Zm.prototype,"linkRefractionWithTransparency",void 0),ae([Lo("Invert refraction Y",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],Zm.prototype,"invertRefractionY",void 0),ae([Lo("Use thickness as depth",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],Zm.prototype,"useThicknessAsDepth",void 0),u("BABYLON.RefractionBlock",Zm);class Jm extends No{constructor(e){super(e,To.Fragment),this._isUnique=!0,this.registerInput("thickness",xo.Float,!1,To.Fragment),this.registerInput("tintColor",xo.Color3,!0,To.Fragment),this.registerInput("translucencyIntensity",xo.Float,!0,To.Fragment),this.registerInput("translucencyDiffusionDist",xo.Color3,!0,To.Fragment),this.registerInput("refraction",xo.Object,!0,To.Fragment,new Mm("refraction",this,Eo.Input,Zm,"RefractionBlock")),this.registerInput("dispersion",xo.Float,!0,To.Fragment),this.registerOutput("subsurface",xo.Object,To.Fragment,new Mm("subsurface",this,Eo.Output,Jm,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vTranslucencyColor"),e._excludeVariableName("vSubSurfaceIntensity"),e._excludeVariableName("dispersion")}getClassName(){return"SubSurfaceBlock"}get thickness(){return this._inputs[0]}get tintColor(){return this._inputs[1]}get translucencyIntensity(){return this._inputs[2]}get translucencyDiffusionDist(){return this._inputs[3]}get refraction(){return this._inputs[4]}get dispersion(){return this._inputs[5]}get subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){const e=new Go("SubSurface thickness",To.Fragment,xo.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",s||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",s,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0),i.setValue("SS_DISPERSION",this.dispersion.isConnected,!0)}static GetCode(e,t,i,s){let r="";const n=t?.thickness.isConnected?t.thickness.associatedVariableName:"0.",o=t?.tintColor.isConnected?t.tintColor.associatedVariableName:"vec3(1.)",a=t?.translucencyIntensity.isConnected?t?.translucencyIntensity.associatedVariableName:"1.",l=t?.translucencyDiffusionDist.isConnected?t?.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",h=t?.refraction.isConnected?t?.refraction.connectedPoint?.ownerBlock:null,c=h?.tintAtDistance.isConnected?h.tintAtDistance.associatedVariableName:"1.",u=h?.intensity.isConnected?h.intensity.associatedVariableName:"1.",d=h?.view.isConnected?h.view.associatedVariableName:"",p=t?.dispersion.isConnected?t?.dispersion.associatedVariableName:"0.0";return r+=h?.getCode(e)??"",r+=`subSurfaceOutParams subSurfaceOut;\n\n #ifdef SUBSURFACE\n vec2 vThicknessParam = vec2(0., ${n});\n vec4 vTintColor = vec4(${o}, ${c});\n vec3 vSubSurfaceIntensity = vec3(${u}, ${a}, 0.);\n float dispersion = ${p};\n subSurfaceBlock(\n vSubSurfaceIntensity,\n vThicknessParam,\n vTintColor,\n normalW,\n specularEnvironmentReflectance,\n #ifdef SS_THICKNESSANDMASK_TEXTURE\n vec4(0.),\n #endif\n #ifdef REFLECTION\n #ifdef SS_TRANSLUCENCY\n ${i?._reflectionMatrixName},\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n reflectionOut.irradianceVector,\n #endif\n #if defined(REALTIME_FILTERING)\n ${i?._cubeSamplerName},\n ${i?._vReflectionFilteringInfoName},\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n irradianceSampler,\n #endif\n #endif\n #endif\n #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n surfaceAlbedo,\n #endif\n #ifdef SS_REFRACTION\n ${s}.xyz,\n viewDirectionW,\n ${d},\n ${h?._vRefractionInfosName??""},\n ${h?._refractionMatrixName??""},\n ${h?._vRefractionMicrosurfaceInfosName??""},\n vLightingIntensity,\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha,\n #endif\n #ifdef ${h?._defineLODRefractionAlpha??"IGNORE"}\n NdotVUnclamped,\n #endif\n #ifdef ${h?._defineLinearSpecularRefraction??"IGNORE"}\n roughness,\n #endif\n alphaG,\n #ifdef ${h?._define3DName??"IGNORE"}\n ${h?._cubeSamplerName??""},\n #else\n ${h?._2DSamplerName??""},\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${h?._define3DName??"IGNORE"}\n ${h?._cubeSamplerName??""},\n ${h?._cubeSamplerName??""},\n #else\n ${h?._2DSamplerName??""},\n ${h?._2DSamplerName??""},\n #endif\n #endif\n #ifdef ANISOTROPIC\n anisotropicOut,\n #endif\n #ifdef REALTIME_FILTERING\n ${h?._vRefractionFilteringInfoName??""},\n #endif\n #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n vRefractionPosition,\n vRefractionSize,\n #endif\n #ifdef SS_DISPERSION\n dispersion,\n #endif\n #endif\n #ifdef SS_TRANSLUCENCY\n ${l},\n vTintColor,\n #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\n vec4(0.),\n #endif\n #endif\n subSurfaceOut\n );\n\n #ifdef SS_REFRACTION\n surfaceAlbedo = subSurfaceOut.surfaceAlbedo;\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha = subSurfaceOut.alpha;\n #endif\n #endif\n #else\n subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;\n #endif\n`,r}_buildBlock(e){return e.target===To.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}u("BABYLON.SubSurfaceBlock",Jm);const eg={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]};class tg extends No{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,J.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?To.Fragment:To.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?To.Fragment:To.Vertex}constructor(e){super(e,To.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=Y.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",xo.Vector4,!1,To.Vertex),this.registerInput("worldNormal",xo.Vector4,!1,To.Fragment),this.registerInput("view",xo.Matrix,!1),this.registerInput("cameraPosition",xo.Vector3,!1,To.Fragment),this.registerInput("perturbedNormal",xo.Vector4,!0,To.Fragment),this.registerInput("baseColor",xo.Color3,!0,To.Fragment),this.registerInput("metallic",xo.Float,!1,To.Fragment),this.registerInput("roughness",xo.Float,!1,To.Fragment),this.registerInput("ambientOcc",xo.Float,!0,To.Fragment),this.registerInput("opacity",xo.Float,!0,To.Fragment),this.registerInput("indexOfRefraction",xo.Float,!0,To.Fragment),this.registerInput("ambientColor",xo.Color3,!0,To.Fragment),this.registerInput("reflection",xo.Object,!0,To.Fragment,new Mm("reflection",this,Eo.Input,Km,"ReflectionBlock")),this.registerInput("clearcoat",xo.Object,!0,To.Fragment,new Mm("clearcoat",this,Eo.Input,qm,"ClearCoatBlock")),this.registerInput("sheen",xo.Object,!0,To.Fragment,new Mm("sheen",this,Eo.Input,jm,"SheenBlock")),this.registerInput("subsurface",xo.Object,!0,To.Fragment,new Mm("subsurface",this,Eo.Input,Jm,"SubSurfaceBlock")),this.registerInput("anisotropy",xo.Object,!0,To.Fragment,new Mm("anisotropy",this,Eo.Input,$m,"AnisotropyBlock")),this.registerInput("iridescence",xo.Object,!0,To.Fragment,new Mm("iridescence",this,Eo.Input,Qm,"IridescenceBlock")),this.registerOutput("ambientClr",xo.Color3,To.Fragment),this.registerOutput("diffuseDir",xo.Color3,To.Fragment),this.registerOutput("specularDir",xo.Color3,To.Fragment),this.registerOutput("clearcoatDir",xo.Color3,To.Fragment),this.registerOutput("sheenDir",xo.Color3,To.Fragment),this.registerOutput("diffuseInd",xo.Color3,To.Fragment),this.registerOutput("specularInd",xo.Color3,To.Fragment),this.registerOutput("clearcoatInd",xo.Color3,To.Fragment),this.registerOutput("sheenInd",xo.Color3,To.Fragment),this.registerOutput("refraction",xo.Color3,To.Fragment),this.registerOutput("lighting",xo.Color3,To.Fragment),this.registerOutput("shadow",xo.Float,To.Fragment),this.registerOutput("alpha",xo.Float,To.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.CameraPosition&&t(e)));i||(i=new Go("cameraPosition"),i.setAsSystemValue(yo.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.View&&t(e)));i||(i=new Go("view"),i.setAsSystemValue(yo.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===Cf.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===Cf.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const s=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",s.indexOf(".")<0?s+".":s,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);const r=e.getScene();if(r.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&th.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),i._areLightsDirty)if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};xn(r,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else vn(r,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,yn(r,i)}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;Pn(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,t)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?un(this.light,this._lightId,s,e,!0):dn(s,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const r=this._scene.ambientColor;r&&e.setColor3("ambientFromScene",r);const n=s.useRightHandedSystem===(null!=s._mirroredCameraPosition);e.setFloat(this._invertNormalName,n?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const o=this.indexOfRefraction.connectInputBlock?.value??1.5,a=Math.pow((o-1)/(o+1),2);this._metallicReflectanceColor.scaleToRef(a*this._metallicF0Factor,$.Color3[0]);const l=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,$.Color3[0],l),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,xo.Vector4)&&(e.compilationString+=`${s} = ${t.associatedVariableName};\n`);const r=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;r&&(r.viewConnectionPoint=this.view),e.compilationString+=r?.handleVertexSide(e)??"",e._emitVaryingFromString("vClipSpacePosition",xo.Vector4,"defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+="#if DEBUGMODE > 0\n",e._injectAtEnd+="vClipSpacePosition = gl_Position;\n",e._injectAtEnd+="#endif\n"),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e="albedoOpacityOutParams albedoOpacityOut;\n";return e+=`albedoOpacityBlock(\n vec4(${this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)"}, 1.),\n #ifdef ALBEDO\n vec4(1.),\n vec2(1., 1.),\n #endif\n #ifdef OPACITY\n vec4(${this.opacity.isConnected?this.opacity.associatedVariableName:"1."}),\n vec2(1., 1.),\n #endif\n albedoOpacityOut\n );\n\n vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;\n float alpha = albedoOpacityOut.alpha;\n`,e}_getAmbientOcclusionCode(){let e="ambientOcclusionOutParams aoOut;\n";return e+=`ambientOcclusionBlock(\n #ifdef AMBIENT\n vec3(${this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1."}),\n vec4(0., 1.0, 1.0, 0.),\n #endif\n aoOut\n );\n`,e}_getReflectivityCode(e){let t="reflectivityOutParams reflectivityOut;\n";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,xo.Vector4),t+=`vec3 baseColor = surfaceAlbedo;\n\n reflectivityBlock(\n vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.),\n #ifdef METALLICWORKFLOW\n surfaceAlbedo,\n ${this._vMetallicReflectanceFactorsName},\n #endif\n #ifdef REFLECTIVITY\n vec3(0., 0., 1.),\n vec4(1.),\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor,\n #endif\n #ifdef MICROSURFACEMAP\n microSurfaceTexel, <== not handled!\n #endif\n reflectivityOut\n );\n\n float microSurface = reflectivityOut.microSurface;\n float roughness = reflectivityOut.roughness;\n\n #ifdef METALLICWORKFLOW\n surfaceAlbedo = reflectivityOut.surfaceAlbedo;\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;\n #endif\n`,t}_buildBlock(e){super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=hf(this._scene));const t=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;if(t&&(t.worldPositionConnectionPoint=this.worldPosition,t.cameraPositionConnectionPoint=this.cameraPosition,t.worldNormalConnectionPoint=this.worldNormal,t.viewConnectionPoint=this.view),e.target!==To.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const i=`//${this.name}`,s=this.perturbedNormal;let r=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${r};\n`,i),e.compilationString+=`${r} = ${this.worldPosition.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+="#if DEBUGMODE > 0\n",e.compilationString+="vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0);\n",e.compilationString+="#endif\n"):r="v_"+r,this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode",xo.Vector2,"defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene",xo.Vector3),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",i),e._emitFunctionFromInclude("importanceSampling",i),e._emitFunctionFromInclude("pbrHelperFunctions",i),e._emitFunctionFromInclude("imageProcessingDeclaration",i),e._emitFunctionFromInclude("imageProcessingFunctions",i),e._emitFunctionFromInclude("shadowsFragmentFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",i),e._emitFunctionFromInclude("pbrBRDFFunctions",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",i),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",i),e._emitFunctionFromInclude("pbrBlockReflectivity",i),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",i),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",i),e._emitFunctionFromInclude("pbrBlockAnisotropic",i),e._emitUniformFromString("vLightingIntensity",xo.Vector4),t?.generateOnlyFragmentCode&&(e.compilationString+=t.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName});\n`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${r}.xyz);\n`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz;\n`,e.compilationString+=`vec3 normalW = ${s.isConnected?"normalize("+s.associatedVariableName+".xyz)":"geometricNormalW"};\n`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,xo.Float),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",i),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",i),e.compilationString+="#ifdef UNLIT\n vec3 diffuseBase = vec3(1., 1., 1.);\n #else\n",e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"}]});const n=this.anisotropy.isConnected?this.anisotropy.connectedPoint?.ownerBlock:null;n&&(n.worldPositionConnectionPoint=this.worldPosition,n.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=n.getCode(e,!this.perturbedNormal.isConnected)),t&&t.hasTexture&&(e.compilationString+=t.getCode(e,n?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:t?._vReflectionFilteringInfoName??"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",i,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});const o=this.sheen.isConnected?this.sheen.connectedPoint?.ownerBlock:null;o&&(e.compilationString+=o.getCode(t)),e._emitFunctionFromInclude("pbrBlockSheen",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"}]});const a=this.iridescence.isConnected?this.iridescence.connectedPoint?.ownerBlock:null;e.compilationString+=Qm.GetCode(a),e._emitFunctionFromInclude("pbrBlockIridescence",i,{replaceStrings:[]});const l=this.clearcoat.isConnected?this.clearcoat.connectedPoint?.ownerBlock:null,h=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,c=this.perturbedNormal.isConnected&&(this.perturbedNormal.connectedPoint?.ownerBlock).worldTangent?.isConnected,u=this.anisotropy.isConnected&&(this.anisotropy.connectedPoint?.ownerBlock).worldTangent.isConnected;let d=c||!this.perturbedNormal.isConnected&&u;e.compilationString+=qm.GetCode(e,l,t,r,h,d,this.worldNormal.associatedVariableName),h&&(d=l?.worldTangent.isConnected??!1),e._emitFunctionFromInclude("pbrBlockClearcoat",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:d?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"}]});const p=this.subsurface.isConnected?this.subsurface.connectedPoint?.ownerBlock:null,f=this.subsurface.isConnected?(this.subsurface.connectedPoint?.ownerBlock).refraction.connectedPoint?.ownerBlock:null;f&&(f.viewConnectionPoint=this.view,f.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=Jm.GetCode(e,p,t,r),e._emitFunctionFromInclude("pbrBlockSubSurface",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:f?._define3DName??"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:f?._defineLODRefractionAlpha??"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:f?._defineLinearSpecularRefraction??"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:f?._defineOppositeZ??"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",i),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:r+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${r}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",i),e.compilationString+="#endif\n";const _=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)";let m=Cf.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();-1===m.indexOf(".")&&(m+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",i,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:_+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:m}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",i,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",i,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",i,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:r},{search:/albedoTexture\.rgb;/g,replace:"vec3(1.);\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\n"}]});for(const t of this._outputs)if(t.hasEndpoints){const i=eg[t.name];if(i){const[s,r]=i;r&&(e.compilationString+=`#if ${r}\n`),e.compilationString+=`${e._declareOutput(t)} = ${s};\n`,r&&(e.compilationString+="#else\n",e.compilationString+=`${e._declareOutput(t)} = vec3(0.);\n`,e.compilationString+="#endif\n")}else J.Error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.lightFalloff = ${this.lightFalloff};\n`,e+=`${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};\n`,e+=`${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};\n`,e+=`${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};\n`,e+=`${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};\n`,e+=`${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};\n`,e+=`${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};\n`,e+=`${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};\n`,e+=`${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};\n`,e+=`${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};\n`,e+=`${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};\n`,e+=`${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};\n`,e+=`${this._codeVariableName}.unlit = ${this.unlit};\n`,e+=`${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};\n`,e+=`${this._codeVariableName}.debugMode = ${this.debugMode};\n`,e+=`${this._codeVariableName}.debugLimit = ${this.debugLimit};\n`,e+=`${this._codeVariableName}.debugFactor = ${this.debugFactor};\n`,e}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=e.lightFalloff??0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=e.realTimeFilteringQuality??8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor,this.generateOnlyFragmentCode=!!e.generateOnlyFragmentCode,this._setTarget()}}var ig,sg,rg,ng,og,ag,lg;ae([Lo("Direct lights",bo.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],tg.prototype,"directIntensity",void 0),ae([Lo("Environment lights",bo.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],tg.prototype,"environmentIntensity",void 0),ae([Lo("Specular highlights",bo.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],tg.prototype,"specularIntensity",void 0),ae([Lo("Light falloff",bo.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:Cf.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:Cf.LIGHTFALLOFF_GLTF},{label:"Standard",value:Cf.LIGHTFALLOFF_STANDARD}]})],tg.prototype,"lightFalloff",void 0),ae([Lo("Alpha Testing",bo.Boolean,"OPACITY")],tg.prototype,"useAlphaTest",void 0),ae([Lo("Alpha CutOff",bo.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],tg.prototype,"alphaTestCutoff",void 0),ae([Lo("Alpha blending",bo.Boolean,"OPACITY")],tg.prototype,"useAlphaBlending",void 0),ae([Lo("Radiance over alpha",bo.Boolean,"RENDERING",{notifiers:{update:!0}})],tg.prototype,"useRadianceOverAlpha",void 0),ae([Lo("Specular over alpha",bo.Boolean,"RENDERING",{notifiers:{update:!0}})],tg.prototype,"useSpecularOverAlpha",void 0),ae([Lo("Specular anti-aliasing",bo.Boolean,"RENDERING",{notifiers:{update:!0}})],tg.prototype,"enableSpecularAntiAliasing",void 0),ae([Lo("Realtime filtering",bo.Boolean,"RENDERING",{notifiers:{update:!0}})],tg.prototype,"realTimeFiltering",void 0),ae([Lo("Realtime filtering quality",bo.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],tg.prototype,"realTimeFilteringQuality",void 0),ae([Lo("Energy Conservation",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],tg.prototype,"useEnergyConservation",void 0),ae([Lo("Radiance occlusion",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],tg.prototype,"useRadianceOcclusion",void 0),ae([Lo("Horizon occlusion",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],tg.prototype,"useHorizonOcclusion",void 0),ae([Lo("Unlit",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],tg.prototype,"unlit",void 0),ae([Lo("Force normal forward",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],tg.prototype,"forceNormalForward",void 0),ae([Lo("Generate only fragment code",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:tg._OnGenerateOnlyFragmentCodeChanged}})],tg.prototype,"generateOnlyFragmentCode",void 0),ae([Lo("Debug mode",bo.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87},{label:"Albedo color",value:88},{label:"Ambient occlusion color",value:89}]})],tg.prototype,"debugMode",void 0),ae([Lo("Split position",bo.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],tg.prototype,"debugLimit",void 0),ae([Lo("Output factor",bo.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],tg.prototype,"debugFactor",void 0),u("BABYLON.PBRMetallicRoughnessBlock",tg),u("BABYLON.ModBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("left",xo.AutoDetect),this.registerInput("right",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[1].acceptedConnectionPointTypes.push(xo.Float)}getClassName(){return"ModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.shaderLanguage===ht.GLSL?e.compilationString+=e._declareOutput(t)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`:e.compilationString+=e._declareOutput(t)+` = (${this.left.associatedVariableName} % ${this.right.associatedVariableName});\n`,this}}),u("BABYLON.MatrixBuilder",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("row0",xo.Vector4),this.registerInput("row1",xo.Vector4),this.registerInput("row2",xo.Vector4),this.registerInput("row3",xo.Vector4),this.registerOutput("output",xo.Matrix)}getClassName(){return"MatrixBuilder"}get row0(){return this._inputs[0]}get row1(){return this._inputs[1]}get row2(){return this._inputs[2]}get row3(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(){if(!this.row0.isConnected){const e=new Go("row0");e.value=new F(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new Go("row1");e.value=new F(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new Go("row2");e.value=new F(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new Go("row3");e.value=new F(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,s=this.row1,r=this.row2,n=this.row3,o=e.shaderLanguage===ht.WGSL?"mat4x4f":"mat4";return e.compilationString+=e._declareOutput(t)+` = ${o}(${i.associatedVariableName}, ${s.associatedVariableName}, ${r.associatedVariableName}, ${n.associatedVariableName});\n`,this}}),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(ig||(ig={})),u("BABYLON.ConditionalBlock",class extends No{constructor(e){super(e,To.Neutral),this.condition=ig.LessThan,this.registerInput("a",xo.Float),this.registerInput("b",xo.Float),this.registerInput("true",xo.AutoDetect,!0),this.registerInput("false",xo.AutoDetect,!0),this.registerOutput("output",xo.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=xo.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",s=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case ig.Equal:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} == ${this.b.associatedVariableName}`)};\n`;break;case ig.NotEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} != ${this.b.associatedVariableName}`)};\n`;break;case ig.LessThan:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} < ${this.b.associatedVariableName}`)};\n`;break;case ig.LessOrEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} <= ${this.b.associatedVariableName}`)};\n`;break;case ig.GreaterThan:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} > ${this.b.associatedVariableName}`)};\n`;break;case ig.GreaterOrEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} >= ${this.b.associatedVariableName}`)};\n`;break;case ig.Xor:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`(((${this.a.associatedVariableName} + ${this.b.associatedVariableName}) % 2.0) > 0.0)`)};\n`;break;case ig.Or:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`(min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0)`)};\n`;break;case ig.And:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`(${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0)`)};\n`}return this}serialize(){const e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${ig[this.condition]};\n`}});class hg extends No{constructor(e){super(e,To.Neutral),this.octaves=6,this.registerInput("seed",xo.AutoDetect),this.registerInput("chaos",xo.AutoDetect,!0),this.registerInput("offsetX",xo.Float,!0),this.registerInput("offsetY",xo.Float,!0),this.registerInput("offsetZ",xo.Float,!0),this.registerOutput("output",xo.Float),this._inputs[0].acceptedConnectionPointTypes.push(xo.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(xo.Vector3),this._linkConnectionTypes(0,1)}getClassName(){return"CloudBlock"}get seed(){return this._inputs[0]}get chaos(){return this._inputs[1]}get offsetX(){return this._inputs[2]}get offsetY(){return this._inputs[3]}get offsetZ(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;if(!this._outputs[0].hasEndpoints)return;let t="\n\n float cloudRandom(float p) { \n float temp = fract(p * 0.011); \n temp *= temp + 7.5; \n temp *= temp + temp; \n return fract(temp); \n }\n\n // Based on Morgan McGuire @morgan3d\n // https://www.shadertoy.com/view/4dS3Wd\n float cloudNoise2(vec2 x, vec2 chaos) {\n vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);\n\n vec2 i = floor(x);\n vec2 f = fract(x);\n\n float n = dot(i, step);\n\n vec2 u = f * f * (3.0 - 2.0 * f);\n return mix(\n mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),\n mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),\n u.y\n );\n }\n\n float cloudNoise3(vec3 x, vec3 chaos) {\n vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);\n\n vec3 i = floor(x);\n vec3 f = fract(x);\n\n float n = dot(i, step);\n\n vec3 u = f * f * (3.0 - 2.0 * f);\n return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),\n mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);\n }",i="\n float fbm2(vec2 st, vec2 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = .5;\n float frequency = 0.;\n\n // Loop of octaves\n vec2 tempST = st;\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise2(tempST, chaos);\n tempST *= 2.0;\n amplitude *= 0.5;\n }\n return value;\n }\n\n float fbm3(vec3 x, vec3 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = 0.5;\n vec3 tempX = x;\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise3(tempX, chaos);\n tempX = tempX * 2.0;\n amplitude *= 0.5;\n }\n return value;\n }";e.shaderLanguage===ht.WGSL&&(t=e._babylonSLtoWGSL(t),i=e._babylonSLtoWGSL(i));const s=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",t,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,i.replace(/fbm/gi,s).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");const r=e._getFreeVariableName("st"),n=this.seed.connectedPoint?.type||xo.Vector3;e.compilationString+=`${e._declareLocalVar(r,n)} = ${this.seed.associatedVariableName};\n`,this.offsetX.isConnected&&(e.compilationString+=`${r}.x += 0.1 * ${this.offsetX.associatedVariableName};\n`),this.offsetY.isConnected&&(e.compilationString+=`${r}.y += 0.1 * ${this.offsetY.associatedVariableName};\n`),this.offsetZ.isConnected&&n===xo.Vector3&&(e.compilationString+=`${r}.z += 0.1 * ${this.offsetZ.associatedVariableName};\n`);let o="";if(this.chaos.isConnected)o=this.chaos.associatedVariableName;else{const t=e.fSuffix;o=this.seed.connectedPoint?.type===xo.Vector2?`vec2${t}(0., 0.)`:`vec3${t}(0., 0., 0.)`}return e.compilationString+=e._declareOutput(this._outputs[0])+` = ${s}${this.seed.connectedPoint?.type===xo.Vector2?"2":"3"}(${r}, ${o});\n`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves};\n`}serialize(){const e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}ae([Lo("Octaves",bo.Int)],hg.prototype,"octaves",void 0),u("BABYLON.CloudBlock",hg),u("BABYLON.VoronoiNoiseBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("seed",xo.Vector2),this.registerInput("offset",xo.Float),this.registerInput("density",xo.Float),this.registerOutput("output",xo.Float),this.registerOutput("cells",xo.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t="vec2 voronoiRandom(vec2 p){\n p = vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3)));\n return fract(sin(p)*18.5453);\n }\n ";e.shaderLanguage===ht.WGSL&&(t=e._babylonSLtoWGSL(t)),e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t="void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){\n vec2 n = floor(seed * density);\n vec2 f = fract(seed * density);\n vec3 m = vec3( 8.0 );\n for( int j=-1; j<=1; j++ ){\n for( int i=-1; i<=1; i++ ){\n vec2 g = vec2( float(i), float(j) );\n vec2 o = voronoiRandom( n + g);\n vec2 r = g - f + (0.5+0.5*sin(offset+6.2831*o));\n float d = dot( r, r );\n if( de.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get textureY(){return this.sourceY.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}get textureZ(){return this.sourceZ?.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}_getImageSourceBlock(e){return e?.isConnected?e.connectedPoint.ownerBlock:null}get samplerName(){const e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){return this._getImageSourceBlock(this.sourceY)?.samplerName??null}get samplerZName(){return this._getImageSourceBlock(this.sourceZ)?.samplerName??null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=this.texture.getScene()??y.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??y.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,To.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",xo.AutoDetect,!1),this.registerInput("normal",xo.AutoDetect,!1),this.registerInput("sharpness",xo.Float,!0),this.registerInput("source",xo.Object,!0,To.VertexAndFragment,new Mm("source",this,Eo.Input,Bm,"ImageSourceBlock")),this.registerInput("sourceY",xo.Object,!0,To.VertexAndFragment,new Mm("sourceY",this,Eo.Input,Bm,"ImageSourceBlock")),t||this.registerInput("sourceZ",xo.Object,!0,To.VertexAndFragment,new Mm("sourceZ",this,Eo.Input,Bm,"ImageSourceBlock")),this.registerOutput("rgba",xo.Color4,To.Neutral),this.registerOutput("rgb",xo.Color3,To.Neutral),this.registerOutput("r",xo.Float,To.Neutral),this.registerOutput("g",xo.Float,To.Neutral),this.registerOutput("b",xo.Float,To.Neutral),this.registerOutput("a",xo.Float,To.Neutral),this.registerOutput("level",xo.Float,To.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_samplerFunc(e){return e.shaderLanguage===ht.WGSL?"textureSample":"texture2D"}_generateTextureSample(e,t,i){return i.shaderLanguage===ht.WGSL?`${this._samplerFunc(i)}(${e},${e+"Sampler"}, ${t})`:`${this._samplerFunc(i)}(${e}, ${t})`}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??t,s=this.samplerZName??t,r=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("x"),o=e._getFreeVariableName("y"),a=e._getFreeVariableName("z"),l=e._getFreeVariableName("w"),h=e._getFreeVariableName("n"),c=e._getFreeVariableName("uvx"),u=e._getFreeVariableName("uvy"),d=e._getFreeVariableName("uvz");e.compilationString+=`\n ${e._declareLocalVar(h,xo.Vector3)} = ${this.normal.associatedVariableName}.xyz;\n\n ${e._declareLocalVar(c,xo.Vector2)} = ${this.position.associatedVariableName}.yz;\n ${e._declareLocalVar(u,xo.Vector2)} = ${this.position.associatedVariableName}.zx;\n ${e._declareLocalVar(d,xo.Vector2)} = ${this.position.associatedVariableName}.xy;\n `,this.projectAsCube&&(e.compilationString+=`\n ${c}.xy = ${c}.yx;\n\n if (${h}.x >= 0.0) {\n ${c}.x = -${c}.x;\n }\n if (${h}.y < 0.0) {\n ${u}.y = -${u}.y;\n }\n if (${h}.z < 0.0) {\n ${d}.x = -${d}.x;\n }\n `);const p=e.fSuffix;e.compilationString+=`\n ${e._declareLocalVar(n,xo.Vector4)} = ${this._generateTextureSample(t,c,e)};\n ${e._declareLocalVar(o,xo.Vector4)} = ${this._generateTextureSample(i,u,e)};\n ${e._declareLocalVar(a,xo.Vector4)} = ${this._generateTextureSample(s,d,e)};\n \n // blend weights\n ${e._declareLocalVar(l,xo.Vector3)} = pow(abs(${h}), vec3${p}(${r}));\n\n // blend and return\n ${e._declareLocalVar(this._tempTextureRead,xo.Vector4)} = (${n}*${l}.x + ${o}*${l}.y + ${a}*${l}.z) / (${l}.x + ${l}.y + ${l}.z); \n `}_generateConversionCode(e,t,i){let s="";e.shaderLanguage!==ht.WGSL||t.type!==xo.Vector3&&t.type!==xo.Color3||(s="Vec3"),"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace${s}(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace${s}(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i){let s="";this.disableLevelMultiplication||(s=` * ${e.shaderLanguage===ht.WGSL?"uniforms.":""}${this._textureInfoName}`),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${s};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=(e.shaderLanguage===ht.WGSL?"uniforms.":"")+this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Texture"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,xo.Float),this._generateTextureLookup(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,e+=`${this._codeVariableName}.projectAsCube = ${this.projectAsCube};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!xa.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Zn.Parse(e.texture,t,i))}}ae([Lo("Project as cube",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],cg.prototype,"projectAsCube",void 0),u("BABYLON.TriPlanarBlock",cg),u("BABYLON.BiPlanarBlock",class extends cg{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_declareLocalVarAsVec3I(e,t){return t.shaderLanguage===ht.WGSL?`var ${e}: vec3`:`ivec3 ${e}`}_getTextureGrad(e,t){return e.shaderLanguage===ht.WGSL?`textureSampleGrad(${t},${t+"Sampler"}`:`textureGrad(${t}`}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",r=e._getFreeVariableName("dxValue"),n=e._getFreeVariableName("dyValue"),o=e._getFreeVariableName("n"),a=e._getFreeVariableName("ma"),l=e._getFreeVariableName("mi"),h=e._getFreeVariableName("me"),c=e._getFreeVariableName("x"),u=e._getFreeVariableName("y"),d=e._getFreeVariableName("w");let p="ivec3",f="dFdx",_="dFdy";const m=e.fSuffix;e.shaderLanguage===ht.WGSL&&(p="vec3",f="dpdx",_="dpdy"),e.compilationString+=`\n // grab coord derivatives for texturing\n ${e._declareLocalVar(r,xo.Vector3)} = ${f}(${this.position.associatedVariableName}.xyz);\n ${e._declareLocalVar(n,xo.Vector3)} = ${_}(${this.position.associatedVariableName}.xyz);\n ${e._declareLocalVar(o,xo.Vector3)} = abs(${this.normal.associatedVariableName}.xyz);\n \n // determine major axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(a,e)} = ${e._generateTernary(`${p}(0,1,2)`,`${e._generateTernary(`${p}(1,2,0)`,`${p}(2,0,1)`,`(${o}.y>${o}.z)`)}`,`(${o}.x>${o}.y && ${o}.x>${o}.z)`)}; \n\n // determine minor axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(l,e)} = ${e._generateTernary(`${p}(0,1,2)`,`${e._generateTernary(`${p}(1,2,0)`,`${p}(2,0,1)`,`(${o}.y<${o}.z)`)}`,`(${o}.x<${o}.y && ${o}.x<${o}.z)`)}; \n \n // determine median axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(h,e)} = ${p}(3) - ${l} - ${a};\n \n // project+fetch\n ${e._declareLocalVar(c,xo.Vector4)} = ${this._getTextureGrad(e,t)}, vec2${m}(${this.position.associatedVariableName}[${a}.y], ${this.position.associatedVariableName}[${a}.z]), \n vec2${m}(${r}[${a}.y],${r}[${a}.z]), \n vec2${m}(${n}[${a}.y],${n}[${a}.z]));\n ${e._declareLocalVar(u,xo.Vector4)} = ${this._getTextureGrad(e,i)}, vec2${m}(${this.position.associatedVariableName}[${h}.y], ${this.position.associatedVariableName}[${h}.z]), \n vec2${m}(${r}[${h}.y],${r}[${h}.z]),\n vec2${m}(${n}[${h}.y],${n}[${h}.z]));\n \n // blend factors\n ${e._declareLocalVar(d,xo.Vector2)} = vec2${m}(${o}[${a}.x],${o}[${h}.x]);\n // make local support\n ${d} = clamp( (${d}-0.5773)/(1.0-0.5773), vec2${m}(0.0), vec2${m}(1.0) );\n // shape transition\n ${d} = pow( ${d}, vec2${m}(${s}/8.0) );\n // blend and return\n ${e._declareLocalVar(this._tempTextureRead,xo.Vector4)} = (${c}*${d}.x + ${u}*${d}.y) / (${d}.x + ${d}.y);\n `}}),u("BABYLON.MatrixDeterminantBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("input",xo.Matrix),this.registerOutput("output",xo.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=e._declareOutput(t)+` = determinant(${i.associatedVariableName});\n`,this}}),u("BABYLON.MatrixTransposeBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("input",xo.Matrix),this.registerOutput("output",xo.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=e._declareOutput(t)+` = transpose(${i.associatedVariableName});\n`,this}}),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Tangent=2]="Tangent",e[e.VertexColor=3]="VertexColor",e[e.UV1=4]="UV1",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6"}(sg||(sg={}));class ug extends No{constructor(e){super(e,To.Neutral),this.attributeType=sg.None,this.registerInput("input",xo.AutoDetect),this.registerInput("fallback",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add((e=>{if(this.attributeType)return;const t=e.ownerBlock;if(t instanceof Go&&t.isAttribute)switch(t.name){case"color":this.attributeType=sg.VertexColor;break;case"normal":this.attributeType=sg.Normal;break;case"tangent":this.attributeType=sg.Tangent;break;case"uv":this.attributeType=sg.UV1;break;case"uv2":this.attributeType=sg.UV2;break;case"uv3":this.attributeType=sg.UV3;break;case"uv4":this.attributeType=sg.UV4;break;case"uv5":this.attributeType=sg.UV5;break;case"uv6":this.attributeType=sg.UV6}else if(t instanceof Dm)switch(this.input.connectedPoint?.name){case"normalOutput":this.attributeType=sg.Normal;break;case"tangentOutput":this.attributeType=sg.Tangent;break;case"uvOutput":this.attributeType=sg.UV1}}))}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case sg.VertexColor:t="VERTEXCOLOR_NME";break;case sg.Normal:t="NORMAL";break;case sg.Tangent:t="TANGENT";break;case sg.UV1:t="UV1";break;case sg.UV2:t="UV2";break;case sg.UV3:t="UV3";break;case sg.UV4:t="UV4";break;case sg.UV5:t="UV5";break;case sg.UV6:t="UV6"}const i=e._declareOutput(this.output);return t&&(e.compilationString+=`#ifdef ${t}\n`),e.compilationString+=`${i} = ${this.input.associatedVariableName};\n`,t&&(e.compilationString+="#else\n",e.compilationString+=`${i} = ${this.fallback.associatedVariableName};\n`,e.compilationString+="#endif\n"),this}serialize(){const e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.attributeType=e.attributeType??sg.None}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType};\n`,e}}ae([Lo("Attribute lookup",bo.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:sg.None},{label:"Normal",value:sg.Normal},{label:"Tangent",value:sg.Tangent},{label:"Vertex Color",value:sg.VertexColor},{label:"UV1",value:sg.UV1},{label:"UV2",value:sg.UV2},{label:"UV3",value:sg.UV3},{label:"UV4",value:sg.UV4},{label:"UV5",value:sg.UV5},{label:"UV6",value:sg.UV6}]})],ug.prototype,"attributeType",void 0),u("BABYLON.MeshAttributeExistsBlock",ug),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(rg||(rg={})),u("BABYLON.CurveBlock",class extends No{constructor(e){super(e,To.Neutral),this.type=rg.EaseInOutSine,this.registerInput("input",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[0].excludedConnectionPointTypes.push(xo.Object),this._inputs[0].excludedConnectionPointTypes.push(xo.Int)}getClassName(){return"CurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_duplicateEntry(e,t){return`ret.${t} = ${e.replace(/VAL/g,"v."+t)}`}_duplicateEntryDirect(e){return`return ${e.replace(/VAL/g,"v")}`}_duplicateVector(e,t,i){if("float"===t||"f32"===t)return this._duplicateEntryDirect(e);const s=parseInt(t.replace("vec",""));let r=i?`\n var ret: vec${s}f = vec${s}f(0.0);\n `:`\n vec${s} ret = vec${s}(0.0);\n `;for(let t=1;t<=s;t++)r+=this._duplicateEntry(e,1===t?"x":2===t?"y":3===t?"z":"w")+";\n";return r+="return ret;\n",r}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",s="";const r=e._getShaderType(this.input.type),n=e.shaderLanguage===ht.WGSL;switch(s=rg[this.type]+"_"+r.replace("<","").replace(">",""),this.type){case rg.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case rg.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case rg.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case rg.EaseInQuad:i="return v * v";break;case rg.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case rg.EaseInOutQuad:{const t=e._generateTernary("2.0 * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case rg.EaseInCubic:i="return v * v * v";break;case rg.EaseOutCubic:{const e="1.0 - pow(1.0 - VAL, 3.0)";i=this._duplicateVector(e,r,n);break}case rg.EaseInOutCubic:{const t=e._generateTernary("4.0 * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case rg.EaseInQuart:i="return v * v * v * v";break;case rg.EaseOutQuart:{const e="1.0 - pow(1.0 - VAL, 4.0)";i=this._duplicateVector(e,r,n);break}case rg.EaseInOutQuart:{const t=e._generateTernary("8.0 * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case rg.EaseInQuint:i="return v * v * v * v * v";break;case rg.EaseOutQuint:{const e="1.0 - pow(1.0 - VAL, 5.0)";i=this._duplicateVector(e,r,n);break}case rg.EaseInOutQuint:{const t=e._generateTernary("16.0 * VAL * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case rg.EaseInExpo:{const t=e._generateTernary("0.0","pow(2.0, 10.0 * VAL - 10.0)","VAL == 0.0");i=this._duplicateVector(t,r,n);break}case rg.EaseOutExpo:{const t=e._generateTernary("1.0","1.0 - pow(2.0, -10.0 * VAL)","VAL == 1.0");i=this._duplicateVector(t,r,n);break}case rg.EaseInOutExpo:{const t=e._generateTernary("0.0",e._generateTernary("1.0",e._generateTernary("pow(2.0, 20.0 * VAL - 10.0) / 2.0","(2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}case rg.EaseInCirc:{const e="1.0 - sqrt(1.0 - pow(VAL, 2.0))";i=this._duplicateVector(e,r,n);break}case rg.EaseOutCirc:{const e="sqrt(1.0 - pow(VAL - 1.0, 2.0))";i=this._duplicateVector(e,r,n);break}case rg.EaseInOutCirc:{const t=e._generateTernary("(1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0","(sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case rg.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case rg.EaseOutBack:{const e="2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)";i=this._duplicateVector(e,r,n);break}case rg.EaseInOutBack:{const t=e._generateTernary("(pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0","(pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case rg.EaseInElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0","-pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))","VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}case rg.EaseOutElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0","pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0","VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}case rg.EaseInOutElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0",e._generateTernary("-(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0","(pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}}return n?e._emitFunction(s,`fn ${s}(v: ${r}) -> ${r} {${i};}\n`,""):e._emitFunction(s,`${r} ${s}(${r} v) {${i};}\n`,""),e.compilationString+=e._declareOutput(t)+` = ${s}(${this.input.associatedVariableName});\n`,this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${rg[this.type]};\n`}});class dg extends Do{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}}class pg extends ah{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new dg,t),this._isEnabled=!1,this.isEnabled=!1,this._smoothAlpha=!1,this.smoothAlpha=!1,this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i,s){const r=s.getMesh().decalMap;return!(this._isEnabled&&r?.texture&&th.DecalMapEnabled&&t.texturesEnabled)||r.isReady()}prepareDefines(e,t,i){const s=i.decalMap;this._isEnabled&&s?.texture&&th.DecalMapEnabled&&t.texturesEnabled?((!e.DECAL||e.GAMMADECAL!==s.texture.gammaSpace)&&e.markAsTexturesDirty(),e.DECAL=!0,e.GAMMADECAL=s.texture.gammaSpace,e.DECAL_SMOOTHALPHA=this._smoothAlpha,an(s.texture,e,"DECAL")):(e.DECAL&&e.markAsTexturesDirty(),e.DECAL=!1)}hardBindForSubMesh(e,t,i,s){const r=s.getMesh().decalMap;if(!(this._isEnabled&&r?.texture&&th.DecalMapEnabled&&t.texturesEnabled))return;const n=this._material.isFrozen,o=r.texture;e.useUbo&&n&&e.isSync||(e.updateFloat4("vDecalInfos",o.coordinatesIndex,0,0,0),ln(o,e,"decal")),e.setTexture("decalSampler",o)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}}ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],pg.prototype,"isEnabled",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],pg.prototype,"smoothAlpha",void 0),u("BABYLON.DecalMapConfiguration",pg),(lg=ng||(ng={}))[lg.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",lg[lg.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",lg[lg.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE",function(e){e[e.COLOR_MODE_SET=0]="COLOR_MODE_SET",e[e.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",e[e.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY"}(og||(og={})),function(e){e[e.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",e[e.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"}(ag||(ag={}));class fg{}fg.DEFAULT_COLOR=Y.White(),fg.DEFAULT_WIDTH_ATTENUATED=1,fg.DEFAULT_WIDTH=.1;class _g{static ConvertPoints(e){if(e.length&&Array.isArray(e)&&"number"==typeof e[0])return[e];if(e.length&&Array.isArray(e[0])&&"number"==typeof e[0][0])return e;if(e.length&&!Array.isArray(e[0])&&e[0]instanceof w){const t=[];for(let i=0;i0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof w){const t=[];return e.forEach((e=>{t.push(e.flatMap((e=>[e.x,e.y,e.z])))})),t}if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){const t=[];return e.forEach((e=>{t.push(Array.from(e))})),t}return[]}static OmitZeroLengthPredicate(e,t,i){const s=[];return t.subtract(e).lengthSquared()>0&&s.push([e,t]),i.subtract(t).lengthSquared()>0&&s.push([t,i]),e.subtract(i).lengthSquared()>0&&s.push([i,e]),0===s.length?null:s}static OmitDuplicatesPredicate(e,t,i,s){const r=[];return _g._SearchInPoints(e,t,s)||r.push([e,t]),_g._SearchInPoints(t,i,s)||r.push([t,i]),_g._SearchInPoints(i,e,s)||r.push([i,e]),0===r.length?null:r}static _SearchInPoints(e,t,i){for(const s of i)for(let i=0;i{const r=e.getVerticesData(Ki.PositionKind),n=e.getIndices();if(r&&n)for(let o=0,a=0;o[e.x,e.y,e.z]))}static GetPointsCountInfo(e){const t=new Array(e.length);let i=0;for(let s=e.length;s--;)t[s]=e[s].length/3,i+=t[s];return{total:i,counts:t}}static GetLineLength(e){if(0===e.length)return 0;let t;t="number"==typeof e[0]?_g.ToVector3Array(e):e;const i=U.Vector3[0];let s=0;for(let e=0;e{e.length>t?_g.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t)).forEach((e=>{s.push(e)})):(s.push(e.point1),s.push(e.point2))})),s}static SegmentizeLineBySegmentCount(e,t){const i="number"==typeof e[0]?_g.ToVector3Array(e):e,s=_g.GetLineLength(i)/t;return _g.SegmentizeLineBySegmentLength(i,s)}static GetLineSegments(e){const t=[];for(let i=0;ie.length));return{min:t[0].length,max:t[t.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,s=!1){const r=t*i;let n=0,o=0;const a=e.length;for(let t=0;t[e.x,e.y,e.z]))}static GetArrowCap(e,t,i,s,r,n=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[s,r,n,o]}}static GetPointsFromText(e,t,i,s,r=0,n=!0){const o=[],a=function(e,t,i,s){const r=Array.from(e),n=t/s.resolution,o=(s.boundingBox.yMax-s.boundingBox.yMin+s.underlineThickness)*n,a=[];let l=0,h=0;for(let e=0;er?r:t.length,o=Math.ceil(t.length/r);o>1&&(t=[...t,...Array(n*o-t.length).fill(t[0])]);const a=_g.Color3toRGBAUint8(t),l=new io(a,n,o,Br.TEXTUREFORMAT_RGBA,s,!1,!0,i);return l.name=e,l}static PrepareEmptyColorsTexture(e){if(!fg.EmptyColorsTexture){const t=new Uint8Array(4);fg.EmptyColorsTexture=new io(t,1,1,Br.TEXTUREFORMAT_RGBA,e,!1,!1,io.NEAREST_NEAREST),fg.EmptyColorsTexture.name="grlEmptyColorsTexture"}return fg.EmptyColorsTexture}static DisposeEmptyColorsTexture(){fg.EmptyColorsTexture?.dispose(),fg.EmptyColorsTexture=null}static BooleanToNumber(e){return e?1:0}}class mg extends Do{constructor(){super(...arguments),this.GREASED_LINE_HAS_COLOR=!1,this.GREASED_LINE_SIZE_ATTENUATION=!1,this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=!1,this.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=!1,this.GREASED_LINE_CAMERA_FACING=!0}}class gg extends ah{constructor(e,t,i){i=i||{color:fg.DEFAULT_COLOR};const s=new mg;s.GREASED_LINE_HAS_COLOR=!!i.color&&!i.useColors,s.GREASED_LINE_SIZE_ATTENUATION=i.sizeAttenuation??!1,s.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=i.colorDistributionType===ag.COLOR_DISTRIBUTION_TYPE_LINE,s.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=(t??e.getScene()).useRightHandedSystem,s.GREASED_LINE_CAMERA_FACING=i.cameraFacing??!0,super(e,gg.GREASED_LINE_MATERIAL_NAME,200,s),this.colorsTexture=null,this._scene=t??e.getScene(),this._engine=this._scene.getEngine(),this._cameraFacing=i.cameraFacing??!0,this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.width=i.width?i.width:i.sizeAttenuation?fg.DEFAULT_WIDTH_ATTENUATED:fg.DEFAULT_WIDTH,this._sizeAttenuation=i.sizeAttenuation??!1,this.colorMode=i.colorMode??og.COLOR_MODE_SET,this._color=i.color??null,this.useColors=i.useColors??!1,this._colorsDistributionType=i.colorDistributionType??ag.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=i.colorsSampling??io.NEAREST_NEAREST,this._colors=i.colors??null,this.dashCount=i.dashCount??1,this.resolution=i.resolution??new N(this._engine.getRenderWidth(),this._engine.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this._colors?this.colorsTexture=_g.CreateColorsTexture(`${e.name}-colors-texture`,this._colors,this.colorsSampling,this._scene):(this._color=this._color??fg.DEFAULT_COLOR,_g.PrepareEmptyColorsTexture(this._scene)),this._engine.onDisposeObservable.add((()=>{_g.DisposeEmptyColorsTexture()})),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this.colorsTexture&&e.push(this.colorsTexture)}getUniforms(){const e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_textureSize",size:2,type:"vec2"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?"\n uniform vec4 grl_aspect_resolution_lineWidth;\n uniform mat4 grl_projection;\n ":"",fragment:"\n uniform vec4 grl_dashOptions;\n uniform vec2 grl_textureSize;\n uniform vec4 grl_colorMode_visibility_colorsWidth_useColors;\n uniform vec3 grl_singleColor;\n "}}get isEnabled(){return!0}bindForSubMesh(e){if(this._cameraFacing){const t=this._scene.activeCamera;if(!t)throw Error("GreasedLinePluginMaterial requires an active camera.");{const i=t.getProjectionMatrix();e.updateMatrix("grl_projection",i)}const i=U.Vector4[0];i.x=this._aspect,i.y=this._resolution.x,i.z=this._resolution.y,i.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",i)}const t=U.Vector4[0];t.x=_g.BooleanToNumber(this.useDash),t.y=this._dashArray,t.z=this.dashOffset,t.w=this.dashRatio,e.updateVector4("grl_dashOptions",t);const i=U.Vector4[1];i.x=this.colorMode,i.y=this.visibility,i.z=this.colorsTexture?this.colorsTexture.getSize().width:0,i.w=_g.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",i),this._color&&e.updateColor3("grl_singleColor",this._color);const s=this.colorsTexture??fg.EmptyColorsTexture;e.setTexture("grl_colors",s),e.updateFloat2("grl_textureSize",s?.getSize().width??1,s?.getSize().height??1)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===ag.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return gg.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if("vertex"===e){const e={CUSTOM_VERTEX_DEFINITIONS:"\n attribute float grl_widths;\n attribute vec3 grl_offsets;\n attribute float grl_colorPointers;\n varying float grlCounters;\n varying float grlColorPointer;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n attribute vec4 grl_previousAndSide;\n attribute vec4 grl_nextAndCounters;\n\n vec2 grlFix( vec4 i, float aspect ) {\n vec2 res = i.xy / i.w;\n res.x *= aspect;\n return res;\n }\n #else\n attribute vec3 grl_slopes;\n attribute float grl_counters;\n #endif\n ",CUSTOM_VERTEX_UPDATE_POSITION:"\n #ifdef GREASED_LINE_CAMERA_FACING\n vec3 grlPositionOffset = grl_offsets;\n positionUpdated += grlPositionOffset;\n #else\n positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths);\n #endif\n ",CUSTOM_VERTEX_MAIN_END:"\n grlColorPointer = grl_colorPointers;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n\n float grlAspect = grl_aspect_resolution_lineWidth.x;\n float grlBaseWidth = grl_aspect_resolution_lineWidth.w;\n\n\n vec3 grlPrevious = grl_previousAndSide.xyz;\n float grlSide = grl_previousAndSide.w;\n\n vec3 grlNext = grl_nextAndCounters.xyz;\n grlCounters = grl_nextAndCounters.w;\n\n mat4 grlMatrix = viewProjection * finalWorld;\n vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 );\n vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 );\n vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 );\n\n vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect );\n vec2 grlPrevP = grlFix( grlPrevPos, grlAspect );\n vec2 grlNextP = grlFix( grlNextPos, grlAspect );\n\n float grlWidth = grlBaseWidth * grl_widths;\n\n vec2 grlDir;\n if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP );\n else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP );\n else {\n vec2 grlDir1 = normalize( grlCurrentP - grlPrevP );\n vec2 grlDir2 = normalize( grlNextP - grlCurrentP );\n grlDir = normalize( grlDir1 + grlDir2 );\n }\n vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. );\n #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\n grlNormal.xy *= -.5 * grlWidth;\n #else\n grlNormal.xy *= .5 * grlWidth;\n #endif\n\n grlNormal *= grl_projection;\n\n #ifdef GREASED_LINE_SIZE_ATTENUATION\n grlNormal.xy *= grlFinalPosition.w;\n grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy;\n #endif\n\n grlFinalPosition.xy += grlNormal.xy * grlSide;\n gl_Position = grlFinalPosition;\n\n vPositionW = vec3(grlFinalPosition);\n #else\n grlCounters = grl_counters;\n #endif\n "};return this._cameraFacing&&(e["!gl_Position\\=viewProjection\\*worldPos;"]="//"),e}return"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:"\n varying float grlCounters;\n varying float grlColorPointer;\n uniform sampler2D grl_colors;\n ",CUSTOM_FRAGMENT_MAIN_END:`\n float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x;\n float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y;\n float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z;\n float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w;\n\n float grlUseDash = grl_dashOptions.x;\n float grlDashArray = grl_dashOptions.y;\n float grlDashOffset = grl_dashOptions.z;\n float grlDashRatio = grl_dashOptions.w;\n\n gl_FragColor.a *= step(grlCounters, grlVisibility);\n if( gl_FragColor.a == 0. ) discard;\n\n if(grlUseDash == 1.){\n gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio));\n if (gl_FragColor.a == 0.) discard;\n }\n\n #ifdef GREASED_LINE_HAS_COLOR\n if (grlColorMode == ${og.COLOR_MODE_SET}.) {\n gl_FragColor.rgb = grl_singleColor;\n } else if (grlColorMode == ${og.COLOR_MODE_ADD}.) {\n gl_FragColor.rgb += grl_singleColor;\n } else if (grlColorMode == ${og.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor.rgb *= grl_singleColor;\n }\n #else\n if (grlUseColors == 1.) {\n #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE\n vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.);\n #else\n vec2 lookup = vec2(fract(grlColorPointer / grl_textureSize.x), 1.0 - floor(grlColorPointer / grl_textureSize.x) / max(grl_textureSize.y - 1.0, 1.0));\n vec4 grlColor = texture2D(grl_colors, lookup, 0.0);\n #endif\n if (grlColorMode == ${og.COLOR_MODE_SET}.) {\n gl_FragColor = grlColor;\n } else if (grlColorMode == ${og.COLOR_MODE_ADD}.) {\n gl_FragColor += grlColor;\n } else if (grlColorMode == ${og.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor *= grlColor;\n }\n }\n #endif\n\n `}:null}dispose(){this.colorsTexture?.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){const s=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this.colorsTexture&&s===e.length&&!i){const t=_g.Color3toRGBAUint8(e);this.colorsTexture.update(t)}else this.colorsTexture?.dispose(),this.colorsTexture=_g.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}else this.colorsTexture?.dispose()}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){null===this._color&&null!==e||null!==this._color&&null===e?(this._color=e,!t&&this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){super.parse(e,t,i);const s=e.greasedLineMaterialOptions;this.colorsTexture?.dispose(),s.color&&this.setColor(s.color,!0),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colors&&(this.colors=s.colors),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),this.colors?this.colorsTexture=_g.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):_g.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){const t=e;t.colorsTexture?.dispose(),this._colors&&(t.colorsTexture=_g.CreateColorsTexture(`${t._material.name}-colors-texture`,this._colors,t.colorsSampling,this._scene)),t.setColor(this.color,!0),t.colorsDistributionType=this.colorsDistributionType,t.colorsSampling=this.colorsSampling,t.colorMode=this.colorMode,t.useColors=this.useColors,t.visibility=this.visibility,t.useDash=this.useDash,t.dashCount=this.dashCount,t.dashRatio=this.dashRatio,t.dashOffset=this.dashOffset,t.width=this.width,t.sizeAttenuation=this.sizeAttenuation,t.resolution=this.resolution,t.markAllDefinesAsDirty()}}gg.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",u(`BABYLON.${gg.GREASED_LINE_MATERIAL_NAME}`,gg);Ft.ShadersStore.greasedLinePixelShader="precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;}\nif (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { \ntextureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);}\nif (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}}\n";Ft.ShadersStore.greasedLineVertexShader="precision highp float;\n#include\nattribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer;\n#ifdef GREASED_LINE_CAMERA_FACING\nattribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;}\n#else\nattribute vec3 grl_slopes;attribute float grl_counters;\n#endif\nvoid main() {\n#include\ngrlColorPointer=grl_colorPointers;mat4 grlMatrix=viewProjection*finalWorld ;\n#ifdef GREASED_LINE_CAMERA_FACING\nfloat grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );}\nvec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. );\n#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\ngrlNormal.xy*=-.5*grlWidth;\n#else\ngrlNormal.xy*=.5*grlWidth;\n#endif\ngrlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;}\ngrlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition;\n#else\ngrlCounters=grl_counters;vec4 grlFinalPosition=grlMatrix*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition;\n#endif\n}\n";class vg extends fc{constructor(e,t,i){const s=[`COLOR_DISTRIBUTION_TYPE_LINE ${ag.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${ag.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${og.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${og.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${og.COLOR_MODE_MULTIPLY}.`],r=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&s.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(s.push("GREASED_LINE_CAMERA_FACING"),r.push("grl_previousAndSide","grl_nextAndCounters")):(r.push("grl_slopes"),r.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:r,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:s}),this._color=Y.White(),this._colorsDistributionType=ag.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:fg.DEFAULT_COLOR};const n=t.getEngine();this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.dashCount=i.dashCount??1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?fg.DEFAULT_WIDTH_ATTENUATED:fg.DEFAULT_WIDTH,this.sizeAttenuation=i.sizeAttenuation??!1,this.color=i.color??Y.White(),this.useColors=i.useColors??!1,this.colorsDistributionType=i.colorDistributionType??ag.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=i.colorsSampling??io.NEAREST_NEAREST,this.colorMode=i.colorMode??og.COLOR_MODE_SET,this._colors=i.colors??null,this._cameraFacing=i.cameraFacing??!0,this.resolution=i.resolution??new N(n.getRenderWidth(),n.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=_g.PrepareEmptyColorsTexture(t),this._colors&&this.setColors(this._colors),n.onDisposeObservable.add((()=>{_g.DisposeEmptyColorsTexture()}))}dispose(){this._colorsTexture?.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new N(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){const s=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this._colorsTexture&&s===e.length&&!i){const t=_g.Color3toRGBAUint8(e);this._colorsTexture.update(t)}else this._colorsTexture?.dispose(),this.colorsTexture=_g.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}else this._colorsTexture?.dispose()}get colorsTexture(){return this._colorsTexture??null}set colorsTexture(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",_g.BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",_g.BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",_g.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=e??fg.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){const s=e.greasedLineMaterialOptions;this._colorsTexture?.dispose(),s.color&&(this.color=s.color),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),s.colors?this.colorsTexture=_g.CreateColorsTexture(`${this.name}-colors-texture`,s.colors,this.colorsSampling,this.getScene()):this.colorsTexture=_g.PrepareEmptyColorsTexture(t),this._cameraFacing=s.cameraFacing??!0,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}const xg=[new Y(.98,.26,.38),new Y(.47,.75,.3),new Y(0,.26,.77),new Y(.97,.6,.76),new Y(.19,.63,.78),new Y(.98,.8,.6),new Y(.65,.43,.15),new Y(.15,.47,.22),new Y(.67,.71,.86),new Y(.09,.46,.56),new Y(.8,.98,.02),new Y(.39,.29,.13),new Y(.53,.63,.06),new Y(.95,.96,.41),new Y(1,.72,.94),new Y(.63,.08,.31),new Y(.66,.96,.95),new Y(.22,.14,.19),new Y(.14,.65,.59),new Y(.93,1,.68),new Y(.93,.14,.44),new Y(.47,.86,.67),new Y(.85,.07,.78),new Y(.53,.64,.98),new Y(.43,.37,.56),new Y(.71,.65,.25),new Y(.66,.19,.01),new Y(.94,.53,.12),new Y(.41,.44,.44),new Y(.24,.71,.96),new Y(.57,.28,.56),new Y(.44,.98,.42)];var Tg;!function(e){e[e.NONE=0]="NONE",e[e.TRIANGLES=1]="TRIANGLES",e[e.VERTICES=2]="VERTICES",e[e.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",e[e.UV0=4]="UV0",e[e.UV1=5]="UV1",e[e.VERTEXCOLORS=6]="VERTEXCOLORS",e[e.MATERIALIDS=7]="MATERIALIDS"}(Tg||(Tg={}));class Sg extends Do{constructor(){super(...arguments),this.DBG_MODE=Tg.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class Eg extends ah{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){const i=new Sg;i.DBG_MODE=t.mode??i.DBG_MODE,i.DBG_MULTIPLY=t.multiply??i.DBG_MULTIPLY,super(e,"MeshDebug",200,i,!0,!0),this._mode=i.DBG_MODE,this._multiply=i.DBG_MULTIPLY,this.shadedDiffuseColor=t.shadedDiffuseColor??new Y(1,1,1),this.shadedSpecularColor=t.shadedSpecularColor??new Y(.8,.8,.8),this.shadedSpecularPower=t.shadedSpecularPower??10,this.wireframeThickness=t.wireframeThickness??.7,this.wireframeTrianglesColor=t.wireframeTrianglesColor??new Y(0,0,0),this.wireframeVerticesColor=t.wireframeVerticesColor??new Y(.8,.8,.8),this.vertexColor=t.vertexColor??new Y(0,0,0),this.vertexRadius=t.vertexRadius??1.2,this.uvScale=t.uvScale??20,this.uvPrimaryColor=t.uvPrimaryColor??new Y(1,1,1),this.uvSecondaryColor=t.uvSecondaryColor??new Y(.5,.5,.5),this._materialColor=Eg.MaterialColors[Eg._PluginCount++%Eg.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&1==this._material.getScene().getEngine().version)return J.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),void(this._isEnabled=!1);this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){this._mode!=Tg.VERTICES&&this._mode!=Tg.TRIANGLES&&this._mode!=Tg.TRIANGLES_VERTICES||i.isVerticesDataPresent("dbg_initialPass")||J.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:"#if defined(DBG_ENABLED)\nuniform vec3 dbg_shadedDiffuseColor;\nuniform vec4 dbg_shadedSpecularColorPower;\nuniform vec3 dbg_thicknessRadiusScale;\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n uniform vec3 dbg_vertexColor;\n#endif\n\n#if DBG_MODE == 1\n uniform vec3 dbg_wireframeTrianglesColor;\n#elif DBG_MODE == 3\n uniform vec3 dbg_wireframeVerticesColor;\n#elif DBG_MODE == 4 || DBG_MODE == 5\n uniform vec3 dbg_uvPrimaryColor;\n uniform vec3 dbg_uvSecondaryColor;\n#elif DBG_MODE == 7\n uniform vec3 dbg_materialColor;\n#endif\n#endif"}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:"#if defined(DBG_ENABLED)\nattribute float dbg_initialPass;\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n#endif",CUSTOM_VERTEX_MAIN_END:"#if defined(DBG_ENABLED)\nfloat dbg_vertexIndex = mod(float(gl_VertexID), 3.);\nif (dbg_vertexIndex == 0.0) { \n dbg_vBarycentric = vec3(1.,0.,0.); \n}\nelse if (dbg_vertexIndex == 1.0) { \n dbg_vBarycentric = vec3(0.,1.,0.); \n}\nelse { \n dbg_vBarycentric = vec3(0.,0.,1.); \n}\n\ndbg_vVertexWorldPos = vPositionW;\ndbg_vPass = dbg_initialPass;\n#endif"}:{CUSTOM_FRAGMENT_DEFINITIONS:"#if defined(DBG_ENABLED)\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n\n#if !defined(DBG_MULTIPLY)\n vec3 dbg_applyShading(vec3 color) {\n vec3 N = vNormalW.xyz;\n vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz);\n vec3 H = normalize(L + L);\n float LdotN = clamp(dot(L,N), 0., 1.);\n float HdotN = clamp(dot(H,N), 0., 1.);\n float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w);\n color *= (LdotN / PI);\n color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI);\n return color;\n }\n#endif\n\n#if DBG_MODE == 1 || DBG_MODE == 3\n float dbg_edgeFactor() {\n vec3 d = fwidth(dbg_vBarycentric);\n vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric);\n return min(min(a3.x, a3.y), a3.z);\n }\n#endif\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor() {\n vec3 worldPos = vPositionW;\n float dist = length(worldPos - dbg_vVertexWorldPos);\n float camDist = length(worldPos - vEyePosition.xyz);\n float d = sqrt(camDist) * .001;\n return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist);\n }\n#endif\n\n#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2))\n float dbg_checkerboardFactor(vec2 uv) {\n vec2 f = fract(uv * dbg_thicknessRadiusScale.z);\n f -= .5;\n return (f.x * f.y) > 0. ? 1. : 0.;\n }\n#endif\n#endif",CUSTOM_FRAGMENT_MAIN_END:"#if defined(DBG_ENABLED)\nvec3 dbg_color = vec3(1.);\n#if DBG_MODE == 1\n dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor());\n#elif DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor = dbg_cornerFactor();\n if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard;\n dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor);\n #if DBG_MODE == 3\n dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor());\n #endif\n#elif DBG_MODE == 4 && defined(MAINUV1)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1));\n#elif DBG_MODE == 5 && defined(MAINUV2)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2));\n#elif DBG_MODE == 6 && defined(VERTEXCOLOR)\n dbg_color = vColor.rgb;\n#elif DBG_MODE == 7\n dbg_color = dbg_materialColor;\n#endif\n\n#if defined(DBG_MULTIPLY)\n gl_FragColor *= vec4(dbg_color, 1.);\n#else\n #if DBG_MODE != 6\n gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.);\n #else\n gl_FragColor = vec4(dbg_color, 1.);\n #endif\n#endif\n#endif"}}static Reset(){this._PluginCount=0,this.MaterialColors=xg}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(0==e.getTotalIndices())return i;if(t){const t=e.getVerticesDataKinds(),s=e.getIndices(),r={};for(const i of t)r[i]=e.getVerticesData(i);i=function(){e.setIndices(s);for(const i of t){const t=e.getVertexBuffer(i).getStrideSize();e.setVerticesData(i,r[i],void 0,t)}e.removeVerticesData("dbg_initialPass")}}let s=Array.from(e.getIndices());const r=[];for(let e=0;enew Cg(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GaussianSplattingMaterial",e}getClassName(){return"GaussianSplattingMaterial"}static Parse(e,t,i){return Pe.Parse((()=>new Cg(e.name,t)),e,t,i)}}u("BABYLON.GaussianSplattingMaterial",Cg),Object.defineProperty(dh.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new pg(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(Cf.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new pg(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(Wr.prototype,"decalMap",{get:function(){return this._decalMap},set:function(e){this._decalMap=e},enumerable:!0,configurable:!0});class yg{constructor(e,t=2,i=3,s=1,r=1){this._curIndex=0,this._sequence=[],this._numSamples=0,this.x=0,this.y=0,this._width=s,this._height=r,this._baseX=t,this._baseY=i,this._generateSequence(e),this.next()}regenerate(e){this._generateSequence(e),this.next()}setDimensions(e,t){this._width=e,this._height=t}next(){this.x=this._sequence[this._curIndex]/this._width,this.y=this._sequence[this._curIndex+1]/this._height,this._curIndex+=2,this._curIndex>=2*this._numSamples&&(this._curIndex=0)}_generateSequence(e){this._sequence=[],this._curIndex=0,this._numSamples=e;for(let t=1;t<=e;++t)this._sequence.push(this._halton(t,this._baseX)-.5,this._halton(t,this._baseY)-.5)}_halton(e,t){let i=1,s=0;for(;e>0;)i/=t,s+=i*(e%t),e=~~(e/t);return s}}function Ag(e,t){return`{X: ${e._x.toFixed(t)} Y: ${e._y.toFixed(t)} Z: ${e._z.toFixed(t)}}`}function Rg(e,t){return`{X: ${e.x.toFixed(t)} Y: ${e.y.toFixed(t)} Z: ${e.z.toFixed(t)} W: ${e.w.toFixed(t)}}`}function Ig(e,t,i,s,r){let n=null,o=null,a=null;try{let l;n=new e.Decoder,o=new e.DecoderBuffer,o.Init(t,t.byteLength);const h=n.GetEncodedGeometryType(o);switch(h){case e.TRIANGULAR_MESH:{const t=new e.Mesh;if(l=n.DecodeBufferToMesh(o,t),!l.ok()||0===t.ptr)throw new Error(l.error_msg());const i=3*t.num_faces(),r=4*i,h=e._malloc(r);try{n.GetTrianglesUInt32Array(t,r,h);const o=new Uint32Array(i);o.set(new Uint32Array(e.HEAPF32.buffer,h,i)),s(o)}finally{e._free(h)}a=t;break}case e.POINT_CLOUD:{const t=new e.PointCloud;if(l=n.DecodeBufferToPointCloud(o,t),!l.ok()||!t.ptr)throw new Error(l.error_msg());a=t;break}default:throw new Error(`Invalid geometry type ${h}`)}const c=a.num_points(),u=(t,i,s,n)=>{const o=n.data_type(),a=n.num_components(),l=n.normalized(),h=n.byte_stride(),u=n.byte_offset(),d={[e.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:e.HEAPF32},[e.DT_INT8]:{typedArrayConstructor:Int8Array,heap:e.HEAP8},[e.DT_INT16]:{typedArrayConstructor:Int16Array,heap:e.HEAP16},[e.DT_INT32]:{typedArrayConstructor:Int32Array,heap:e.HEAP32},[e.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:e.HEAPU8},[e.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:e.HEAPU16},[e.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:e.HEAPU32}}[o];if(!d)throw new Error(`Invalid data type ${o}`);const p=c*a,f=p*d.typedArrayConstructor.BYTES_PER_ELEMENT,_=e._malloc(f);try{t.GetAttributeDataArrayForAllPoints(i,n,o,f,_);const e=new d.typedArrayConstructor(d.heap.buffer,_,p);r(s,e.slice(),a,u,h,l)}finally{e._free(_)}};if(i)for(const e in i){const t=i[e],s=n.GetAttributeByUniqueId(a,t);u(n,a,e,s)}else{const t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(const e in t){const i=n.GetAttributeId(a,t[e]);if(-1!==i){const t=n.GetAttribute(a,i);u(n,a,e,t)}}}return c}finally{a&&e.destroy(a),o&&e.destroy(o),n&&e.destroy(n)}}function Pg(){let e;onmessage=t=>{const i=t.data;switch(i.id){case"init":{const t=i.decoder;t.url&&importScripts(t.url);const s=t.wasmBinary?{wasmBinary:t.wasmBinary}:{};e=DracoDecoderModule(s),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((e=>{const t=Ig(e,i.dataView,i.attributes,(e=>{postMessage({id:"indices",data:e},[e.buffer])}),((e,t,i,s,r,n)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:s,byteStride:r,normalized:n},[t.buffer])}));postMessage({id:"decodeMeshDone",totalVertices:t})}))}}}class Mg{static get DecoderAvailable(){const e=Mg.Configuration.decoder;return!!(e.wasmUrl&&e.wasmBinaryUrl&&"object"==typeof WebAssembly||e.fallbackUrl)}static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static get Default(){return Mg._Default||(Mg._Default=new Mg),Mg._Default}static ResetDefault(e){Mg._Default&&(e||Mg._Default.dispose(),Mg._Default=null)}constructor(e=Mg.DefaultNumWorkers){const t=Mg.Configuration.decoder;if(t.workerPool||"object"==typeof e&&e.workerPool)this._workerPoolPromise=Promise.resolve(t.workerPool||e.workerPool);else{const i=t.wasmBinary||"object"==typeof e&&e.wasmBinary,s="number"==typeof e?e:e.numWorkers,r=s&&"function"==typeof Worker&&"function"==typeof URL,n=r||!r&&!t.jsModule,o=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:n?Ii.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:i?Promise.resolve(i):Ii.LoadFileAsync(Ii.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:n?Ii.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};r?this._workerPoolPromise=o.wasmBinaryPromise.then((e=>{const t=`${Ig}(${Pg})()`,i=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));return new If(s,(()=>function(e,t,i){return new Promise(((s,r)=>{const n=t=>{e.removeEventListener("error",n),e.removeEventListener("message",o),r(t)},o=t=>{"initDone"===t.data.id&&(e.removeEventListener("error",n),e.removeEventListener("message",o),s(e))};if(e.addEventListener("error",n),e.addEventListener("message",o),t){const s=t.slice(0);e.postMessage({id:"init",decoder:{url:i,wasmBinary:s}},[s])}else e.postMessage({id:"init",decoder:{url:i}})}))}(new Worker(i),e,o.url)))})):this._decoderModulePromise=o.wasmBinaryPromise.then((async e=>{if("undefined"==typeof DracoDecoderModule&&!t.jsModule){if(!o.url)throw new Error("Draco decoder module is not available");await Ii.LoadBabylonScriptAsync(o.url)}return await(i=e,s=t.jsModule,new Promise((e=>{(s||DracoDecoderModule)({wasmBinary:i}).then((t=>{e({module:t})}))})));var i,s}))}}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then((e=>{e.dispose()})),delete this._workerPoolPromise,delete this._decoderModulePromise}async whenReadyAsync(){this._workerPoolPromise?await this._workerPoolPromise:this._decoderModulePromise&&await this._decoderModulePromise}decodeMeshToMeshDataAsync(e,t,i){const s=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength);if(this._workerPoolPromise)return this._workerPoolPromise.then((e=>new Promise(((r,n)=>{e.push(((e,o)=>{let a=null;const l=[],h=t=>{e.removeEventListener("error",h),e.removeEventListener("message",c),n(t),o()},c=t=>{const s=t.data;switch(s.id){case"decodeMeshDone":e.removeEventListener("error",h),e.removeEventListener("message",c),r({indices:a,attributes:l,totalVertices:s.totalVertices}),o();break;case"indices":a=s.data;break;case"attribute":l.push({kind:s.kind,data:s.data,size:s.size,byteOffset:s.byteOffset,byteStride:s.byteStride,normalized:(n=s.kind,u=s.normalized,i&&void 0!==i[n]?(u!==i[n]&&J.Warn(`Normalized flag from Draco data (${u}) does not match normalized flag from glTF accessor (${i[n]}). Using flag from glTF accessor.`),i[n]):u)})}var n,u};e.addEventListener("error",h),e.addEventListener("message",c);const u=s.slice();e.postMessage({id:"decodeMesh",dataView:u,attributes:t},[u.buffer])}))}))));if(this._decoderModulePromise)return this._decoderModulePromise.then((e=>{let i=null;const r=[],n=Ig(e.module,s,t,(e=>{i=e}),((e,t,i,s,n,o)=>{r.push({kind:e,data:t,size:i,byteOffset:s,byteStride:n,normalized:o})}));return{indices:i,attributes:r,totalVertices:n}}));throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,i,s){const r=await this.decodeMeshToMeshDataAsync(i,s),n=new br(e,t);r.indices&&n.setIndices(r.indices);for(const e of r.attributes)n.setVerticesBuffer(new Ki(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),r.totalVertices);return n}async _decodeMeshToGeometryForGltfAsync(e,t,i,s,r){const n=await this.decodeMeshToMeshDataAsync(i,s,r),o=new br(e,t);n.indices&&o.setIndices(n.indices);for(const e of n.attributes)o.setVerticesBuffer(new Ki(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),n.totalVertices);return o}async decodeMeshAsync(e,t){const i=await this.decodeMeshToMeshDataAsync(e,t),s=new Tr;i.indices&&(s.indices=i.indices);for(const e of i.attributes){const t=Ki.GetFloatData(e.data,e.size,Ki.GetDataType(e.data),e.byteOffset,e.byteStride,e.normalized,i.totalVertices);s.set(t,e.kind)}return s}}Mg.Configuration={decoder:{wasmUrl:`${Ii._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${Ii._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${Ii._DefaultCdnUrl}/draco_decoder_gltf.js`}},Mg.DefaultNumWorkers=Mg.GetDefaultNumWorkers(),Mg._Default=null;class Dg{static get Default(){return Dg._Default||(Dg._Default=new Dg),Dg._Default}constructor(){const e=Dg.Configuration.decoder;this._decoderModulePromise=Ii.LoadBabylonScriptAsync(e.url).then((()=>MeshoptDecoder.ready))}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,s,r){return this._decoderModulePromise.then((async()=>{MeshoptDecoder.useWorkers(1);const n=await MeshoptDecoder.decodeGltfBufferAsync(t,i,e,s,r);return MeshoptDecoder.useWorkers(0),n}))}}Dg.Configuration={decoder:{url:`${Ii._DefaultCdnUrl}/meshopt_decoder.js`}},Dg._Default=null;let Og=0;class Ng{constructor(e,t,i,s){this.pos=e,this.normal=t,this.uv=i,this.vertColor=s}clone(){return new Ng(this.pos.clone(),this.normal.clone(),this.uv?.clone(),this.vertColor?.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new Ng(w.Lerp(this.pos,e.pos,t),w.Lerp(this.normal,e.normal,t),this.uv&&e.uv?N.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?j.Lerp(this.vertColor,e.vertColor,t):void 0)}}class wg{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const s=i.subtract(e),r=t.subtract(e);if(0===s.lengthSquared()||0===r.lengthSquared())return null;const n=w.Normalize(w.Cross(s,r));return new wg(n,w.Dot(n,e))}clone(){return new wg(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,s,r){let n=0;const o=[];let a,l;for(a=0;awg.EPSILON?1:0;n|=t,o.push(t)}switch(n){case 0:(w.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:s.push(e);break;case 2:r.push(e);break;case 3:{const t=[],i=[];for(a=0;a=3&&(n=new Fg(t,e.shared),n.plane&&s.push(n)),i.length>=3&&(n=new Fg(i,e.shared),n.plane&&r.push(n));break}}}}wg.EPSILON=1e-5;class Fg{constructor(e,t){this.vertices=e,this.shared=t,this.plane=wg.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map((e=>e.clone()));return new Fg(e,this.shared)}flip(){this.vertices.reverse().map((e=>{e.flip()})),this.plane.flip()}}class Lg{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new Lg;return e._plane=this._plane&&this._plane.clone(),e._front=this._front&&this._front.clone(),e._back=this._back&&this._back.clone(),e._polygons=this._polygons.map((e=>e.clone())),e}invert(){for(let e=0;ee.clone())),e.copyTransformAttributes(this),e}union(e){const t=new Lg(this.clone()._polygons),i=new Lg(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),Bg._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new Lg(this._polygons),i=new Lg(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()}subtract(e){const t=new Lg(this.clone()._polygons),i=new Lg(e.clone()._polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),Bg._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new Lg(this._polygons),i=new Lg(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}intersect(e){const t=new Lg(this.clone()._polygons),i=new Lg(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),Bg._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new Lg(this._polygons),i=new Lg(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){const e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map((e=>{e.flip()}))}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){const i=this.matrix.clone();i.invert();const s=this._polygons,r=[],n=[],o=[];let a=null,l=null;const h=w.Zero(),c=w.Zero(),u=N.Zero(),d=new j(0,0,0,0),p=[0,0,0],f={};let _;for(let m=0,g=s.length;me.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId)),this.toVertexData((e=>{o[e.shared.meshId]||(o[e.shared.meshId]={}),o[e.shared.meshId][e.shared.subMeshId]||(o[e.shared.meshId][e.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:e.shared.materialIndex}),a=o[e.shared.meshId][e.shared.subMeshId]}),(()=>{a.indexStart=Math.min(n,a.indexStart),a.indexEnd=Math.max(n,a.indexEnd),n++})).applyToMesh(s),i){let e,t=0;s.subMeshes=[];for(const i in o){e=-1;for(const r in o[i])a=o[i][r],vr.CreateFromIndices(a.materialIndex+t,a.indexStart,a.indexEnd-a.indexStart+1,s),e=Math.max(a.materialIndex,e);t+=++e}}return s}toMesh(e,t=null,i,s){const r=this.buildMeshGeometry(e,i,s);return r.material=t,r.position.copyFrom(this.position),r.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(r.rotationQuaternion=this.rotationQuaternion.clone()),r.scaling.copyFrom(this.scaling),r.computeWorldMatrix(!0),r}}Ft.ShadersStore.meshUVSpaceRendererVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nvoid main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW;\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\n#endif\nvec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);}";Ft.ShadersStore.meshUVSpaceRendererPixelShader="precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;}\ngl_FragColor=texture2D(textureSampler,vDecalTC);}\n";Ft.ShadersStore.meshUVSpaceRendererMaskerVertexShader="attribute vec2 uv;varying vec2 vUV;void main(void) {gl_Position=vec4(vec2(uv.x,uv.y)*2.0-1.0,0.,1.0);vUV=uv;}";Ft.ShadersStore.meshUVSpaceRendererMaskerPixelShader="varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);}\n";Ft.ShadersStore.meshUVSpaceRendererFinaliserPixelShader="precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D maskTextureSampler;uniform vec2 textureSize;void main() {vec4 mask=texture2D(maskTextureSampler,vUV).rgba;if (mask.r>0.5) {gl_FragColor=texture2D(textureSampler,vUV);} else {vec2 texelSize=4.0/textureSize;vec2 uv_p01=vUV+vec2(-1.0,0.0)*texelSize;vec2 uv_p21=vUV+vec2(1.0,0.0)*texelSize;vec2 uv_p10=vUV+vec2(0.0,-1.0)*texelSize;vec2 uv_p12=vUV+vec2(0.0,1.0)*texelSize;float mask_p01=texture2D(maskTextureSampler,uv_p01).r;float mask_p21=texture2D(maskTextureSampler,uv_p21).r;float mask_p10=texture2D(maskTextureSampler,uv_p10).r;float mask_p12=texture2D(maskTextureSampler,uv_p12).r;vec4 col=vec4(0.0,0.0,0.0,0.0);float total_weight=0.0;if (mask_p01>0.5) {col+=texture2D(textureSampler,uv_p01);total_weight+=1.0;}\nif (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;}\nif (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;}\nif (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;}\nif (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}}\n";Ft.ShadersStore.meshUVSpaceRendererFinaliserVertexShader="precision highp float;attribute vec3 position;attribute vec2 uv;uniform mat4 worldViewProjection;varying vec2 vUV;void main() {gl_Position=worldViewProjection*vec4(position,1.0);vUV=uv;}\n",Un._TrailMeshParser=(e,t)=>Vg.Parse(e,t);class Vg extends Un{constructor(e,t,i,s,r=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._generator=t,"object"==typeof s&&null!==s?(this.diameter=s.diameter||1,this._length=s.length||60,this._segments=s.segments?s.segments>this._length?this._length:s.segments:this._length,this._sectionPolygonPointsCount=s.sections||4,this._doNotTaper=s.doNotTaper||!1,this._autoStart=s.autoStart||!0):(this.diameter=s||1,this._length=r,this._segments=this._length,this._doNotTaper=!1,this._autoStart=n),this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e<=this._sectionPolygonPointsCount;e++)this._sectionVectors[e]=w.Zero(),this._sectionNormalVectors[e]=w.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){const e=new Tr,t=[],i=[],s=[],r=[];let n=w.Zero();n=this._generator instanceof Wr&&this._generator.hasBoundingInfo?this._generator.getBoundingInfo().boundingBox.centerWorld:this._generator.absolutePosition;const o=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<=this._sectionPolygonPointsCount;e++){const i=e!==this._sectionPolygonPointsCount?e*o:0;t.push(n.x+Math.cos(i)*this.diameter,n.y+Math.sin(i)*this.diameter,n.z),r.push(e/this._sectionPolygonPointsCount,0)}for(let e=1;e<=this._segments;e++){for(let i=0;i<=this._sectionPolygonPointsCount;i++){const s=i!==this._sectionPolygonPointsCount?i*o:0;t.push(n.x+Math.cos(s)*this.diameter,n.y+Math.sin(s)*this.diameter,n.z),r.push(i/this._sectionPolygonPointsCount,e/this._segments)}const i=t.length/3-2*(this._sectionPolygonPointsCount+1);for(let e=0;e<=this._sectionPolygonPointsCount;e++)s.push(i+e,i+e+this._sectionPolygonPointsCount,i+e+this._sectionPolygonPointsCount+1),s.push(i+e,i+e+this._sectionPolygonPointsCount+1,i+e+1)}Tr.ComputeNormals(t,s,i),e.positions=t,e.normals=i,e.indices=s,e.uvs=r,e.applyToMesh(this,!0),this._autoStart&&this.start()}start(){this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add((()=>{this.update()})))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){const e=this.getVerticesData(Ki.PositionKind),t=this.getVerticesData(Ki.NormalKind),i=this._generator.getWorldMatrix(),s=3*(this._sectionPolygonPointsCount+1);if(e&&t){if(this._doNotTaper)for(let t=s;t{this._getSimplifier(e).simplify(t,(i=>{void 0!==t.distance&&e.mesh.addLODLevel(t.distance,i),i.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()}))}));else{const t=this._getSimplifier(e),i=(i,s)=>{t.simplify(i,(t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,s()}))};Pi.Run(e.settings.length,(t=>{i(e.settings[t.index],(()=>{t.executeNext()}))}),(()=>{e.successCallback&&e.successCallback(),this.executeNext()}))}}_getSimplifier(e){return e.simplificationType,kg.QUADRATIC,new cv(e.mesh)}}var kg,Gg,zg,Wg,Hg,Xg,Yg,jg,$g,Kg,qg,Qg,Zg,Jg,ev,tv,iv,sv,rv,nv;!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(kg||(kg={}));class ov{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class av{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new lv,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class lv{constructor(e){this.data=new Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,s,r,n,o,a,l){return this.data[e]*this.data[r]*this.data[l]+this.data[i]*this.data[s]*this.data[a]+this.data[t]*this.data[n]*this.data[o]-this.data[i]*this.data[r]*this.data[o]-this.data[e]*this.data[n]*this.data[a]-this.data[t]*this.data[s]*this.data[l]}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){const t=new lv;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,s){return new lv(lv.DataFromNumbers(e,t,i,s))}static DataFromNumbers(e,t,i,s){return[e*e,e*t,e*i,e*s,t*t,t*i,t*s,i*i,i*s,s*s]}}class hv{constructor(e,t){this.vertexId=e,this.triangleId=t}}class cv{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=T}simplify(e,t){this._initDecimatedMesh(),Pi.Run(this._mesh.subMeshes.length,(t=>{this._initWithMesh(t.index,(()=>{this._runDecimation(e,t.index,(()=>{t.executeNext()}))}),e.optimizeMesh)}),(()=>{setTimeout((()=>{t(this._reconstructedMesh)}),0)}))}_runDecimation(e,t,i){const s=~~(this._triangles.length*e.quality);let r=0;const n=this._triangles.length,o=(e,t)=>{setTimeout((()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e{const t=~~((this._triangles.length/2+e)%this._triangles.length),s=this._triangles[t];if(s&&!(s.error[3]>i||s.deleted||s.isDirty))for(let e=0;e<3;++e)if(s.error[e]{-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))})),h.length%2!=0)continue;n.q=o.q.add(n.q),n.updatePosition(a);const c=this._references.length;r=this._updateTriangles(n,n,t,r),r=this._updateTriangles(n,o,i,r);const u=this._references.length-c;if(u<=n.triangleCount){if(u)for(let e=0;en-r<=s))}),0)};Pi.Run(this.decimationIterations,(e=>{n-r<=s?e.breakLoop():o(e.index,(()=>{e.executeNext()}))}),(()=>{setTimeout((()=>{this._reconstructMesh(t),i()}),0)}))}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const s=this._mesh.getVerticesData(Ki.PositionKind),r=this._mesh.getIndices(),n=this._mesh.subMeshes[e],o=e=>{if(i)for(let t=0;t{if(!s)return;const t=e+n.verticesStart,i=w.FromArray(s,3*t),r=o(i)||new av(i,this._vertices.length);r.originalOffsets.push(t),r.id===this._vertices.length&&this._vertices.push(r),a.push(r.id)}),(()=>{Pi.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,(e=>{if(!r)return;const t=3*(n.indexStart/3+e),i=r[t+0],s=r[t+1],o=r[t+2],l=this._vertices[a[i-n.verticesStart]],h=this._vertices[a[s-n.verticesStart]],c=this._vertices[a[o-n.verticesStart]],u=new ov([l,h,c]);u.originalOffset=t,this._triangles.push(u)}),(()=>{this._init(t)}))}))}_init(e){Pi.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];t.normal=w.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(lv.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-w.Dot(t.normal,t._vertices[0].position)))}),(()=>{Pi.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])}),(()=>{e()}))}))}_reconstructMesh(e){const t=[];let i,s,r;for(i=0;i{n.push(e.position.x),n.push(e.position.y),n.push(e.position.z),h&&h.length&&(o.push(h[3*t]),o.push(h[3*t+1]),o.push(h[3*t+2])),c&&c.length&&(a.push(c[2*t]),a.push(c[2*t+1])),u&&u.length&&(l.push(u[4*t]),l.push(u[4*t+1]),l.push(u[4*t+2]),l.push(u[4*t+3])),++d}))}const p=this._reconstructedMesh.getTotalIndices(),f=this._reconstructedMesh.getTotalVertices(),_=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(i=0;i{const t=g[s.originalOffset+e];let i=s._vertices[e].originalOffsets.indexOf(t);i<0&&(i=0),m.push(s._vertices[e].id+i+f)}));this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(Ki.PositionKind,n),o.length>0&&this._reconstructedMesh.setVerticesData(Ki.NormalKind,o),a.length>0&&this._reconstructedMesh.setVerticesData(Ki.UVKind,a),l.length>0&&this._reconstructedMesh.setVerticesData(Ki.ColorKind,l);const v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],_.forEach((e=>{vr.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())})),vr.AddToMesh(v.materialIndex,f,d,p,3*t.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new Un(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,s,r){for(let n=0;n.999)return!0;const d=w.Cross(c,u).normalize();if(s[n]=!1,w.Dot(d,o.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,s){let r=s;for(let s=0;spv.Parse(e,t);class pv extends dv{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(_g.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[],this._points.forEach((t=>{for(let i=0;i{i+=2*e.length,s+=2*(e.length-3),r+=4*e.length/3,n+=8*e.length/3}));const o=new Float32Array(i),a=i>65535?new Uint32Array(s):new Uint16Array(s),l=new Float32Array(r),h=new Float32Array(n),c=new Float32Array(n);let u=0,d=0,p=0,f=0,_=0;e.forEach((e=>{const i=_g.GetLineLengthArray(e),s=i[i.length-1];for(let i=0,s=0;s>1]/s;if(this._options.uvs)for(let e=0;efv.Parse(e,t);class fv extends dv{constructor(e,t,i,s){if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=i.widths??[],this._ribbonWidths=[],this._pathsOptions=s??[],i.points&&this.addPoints(_g.ConvertPoints(i.points),i,!!s)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t{const r=fv._ConvertToRibbonPath(e,n.ribbonOptions,this._scene.useRightHandedSystem,i?i[t]:i);s=this._preprocess(r,s,n)}))}}this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:new Array(e).fill(t)}static _CreateRibbonVertexData(e,t){const i=e.length;if(i<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";const s=[],r=[],n=e[0];for(let t=0;t2)for(let e=0;e0&&(o[0]+=1,o[1]+=1),r.push(o[1]+(e%2!=0?i:0),o[0],o[2]),a&&r.push(o[0],o[1]+(e%2!=0?i:0),o[2])}else for(let e=0;ee.y&&e.x>e.z?i?fv._RightHandedForwardReadOnlyQuaternion:fv._LeftHandedForwardReadOnlyQuaternion:fv._LeftReadOnlyQuaternion),l=e.normalize()}h=l.multiplyByFloats(o,o,o),r.push(c.add(h)),n.push(c.subtract(h))}s||(r.push(a[a.length-1].add(h)),n.push(a[a.length-1].subtract(h)))}return[r,n]}static _GetDirectionFromPoints(e,t,i){return e.x!==t.x||i&&1!==i?.x?e.y===t.y?fv.DIRECTION_XZ:e.z===t.z?fv.DIRECTION_XY:fv.DIRECTION_XZ:fv.DIRECTION_YZ}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),s={},r=[];se.DeepCopy(this._pathsOptions,r,void 0,void 0,!0),se.DeepCopy(i,s,["instance"],void 0,!0);const n=new fv(e,this._scene,s,r);return t&&(n.parent=t),n.material=this.material,n}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions(),e.pathsOptions=this._pathsOptions}static Parse(e,t){const i=e.lineOptions,s=e.name,r=e.pathOptions;return new fv(s,t,i,r)}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){const t=e.length;this._vSegmentLengths=new Array(t),this._vTotalLengths=new Array(t);let i=0;for(let s=0;s=this._thinInstanceDataStorage.instancesCount)return!1;const s=this._thinInstanceDataStorage.matrixData;return t.copyToArray(s,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},Un.prototype.thinInstanceSetAttributeAt=function(e,t,i,s=!0){return e===Ki.ColorKind&&(e=Ki.ColorInstanceKind),!(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[e]||t>=this._thinInstanceDataStorage.instancesCount||(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),s&&this.thinInstanceBufferUpdated(e),0))},Object.defineProperty(Un.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){const t=this._thinInstanceDataStorage.matrixData??this.source?._thinInstanceDataStorage.matrixData;e<=(t?t.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),Un.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!0){const s=new $i(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(s.createVertexBuffer(e+t,4*t,4));return s},Un.prototype.thinInstanceSetBuffer=function(e,t,i=0,s=!0){i=i||16,"matrix"===e?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*i,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/i,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,s),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,s))):(e===Ki.ColorKind&&(e=Ki.ColorInstanceKind),null===t?this._userThinInstanceBuffersStorage?.data[e]&&(this.removeVerticesData(e),delete this._userThinInstanceBuffersStorage.data[e],delete this._userThinInstanceBuffersStorage.strides[e],delete this._userThinInstanceBuffersStorage.sizes[e],delete this._userThinInstanceBuffersStorage.vertexBuffers[e]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[e]=t,this._userThinInstanceBuffersStorage.strides[e]=i,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new Ki(this.getEngine(),t,e,!s,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},Un.prototype.thinInstanceBufferUpdated=function(e){"matrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.matrixBuffer?.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):"previousMatrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.previousMatrixBuffer?.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(e===Ki.ColorKind&&(e=Ki.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[e].isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0)))},Un.prototype.thinInstancePartialBufferUpdate=function(e,t,i){"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===Ki.ColorKind&&(e=Ki.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},Un.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;te.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}_resetCounters(){this._callCount=0,this._executionCount=0}get callCount(){return this._callCount}get executionCount(){return this._executionCount}getConnectedValue(e){return this.isConnected?this._connectedPoint?._storedFunction?(this._connectedPoint._callCount++,this._connectedPoint._executionCount++,this._connectedPoint._storedFunction(e)):(this._connectedPoint._callCount++,this._connectedPoint._executionCount=1,this._connectedPoint._storedValue):(this._callCount++,this._executionCount=1,this.value)}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=new Array,this._type=Yg.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new g,this.onDisconnectionObservable=new g,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._callCount=0,this._executionCount=0,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===jg.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==Yg.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?jg.Compatible:jg.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return jg.TypeIncompatible;let s=i,r=t;return this.direction===$g.Input&&(s=t,r=i),s.isAnAncestorOf(r)?jg.HierarchyIssue:jg.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear()}}class mv{get buildExecutionTime(){return this._buildExecutionTime}get inputs(){return this._inputs}get outputs(){return this._outputs}get name(){return this._name}set name(e){this._name=e}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get isDebug(){return this._isDebug}get isUnique(){return this._isUnique}getClassName(){return"NodeGeometryBlock"}_inputRename(e){return e}_outputRename(e){return e}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){if(i.ownerBlock===e)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints)if(i.ownerBlock.isAnAncestorOfType(e))return!0;return!1}getDescendantOfPredicate(e){if(e(this))return this;for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){const t=i.ownerBlock.getDescendantOfPredicate(e);if(t)return t}return null}constructor(e){this._name="",this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._isDebug=!1,this._isUnique=!1,this._buildExecutionTime=0,this.onBuildObservable=new g,this._inputs=new Array,this._outputs=new Array,this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this.uniqueId=Ds.UniqueId}registerInput(e,t,i=!1,s,r,n){const o=new _v(e,this,$g.Input);return o.type=t,o.isOptional=i,o.defaultValue=s,o.value=s,o.valueMin=r,o.valueMax=n,this._inputs.push(o),this}registerOutput(e,t,i){return(i=i??new _v(e,this,$g.Output)).type=t,this._outputs.push(i),this}_buildBlock(e){}_customBuildStep(e){}build(e){if(this._buildId===e.buildId)return!0;if(this._outputs.length>0){if(!this._outputs.some((e=>e.hasEndpoints))&&!this.isDebug)return!1;this.outputs.forEach((e=>e._resetCounters()))}this._buildId=e.buildId;for(const t of this._inputs){if(!t.connectedPoint){t.isOptional||e.notConnectedNonOptionalInputs.push(t);continue}const i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}this._customBuildStep(e),e.verbose&&J.Log(`Building ${this.name} [${this.getClassName()}]`);const t=je.Now;this._buildBlock(e),this._buildExecutionTime=je.Now-t;for(const t of this._outputs)for(const i of t.endpoints){const t=i.ownerBlock;t&&t.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.visibleOnFrame=this.visibleOnFrame,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach((e=>{const t=this.inputs.find((t=>t.name===e.name));if(t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value))if("number"===e.valueType)t.value=e.value;else{const i=d(e.valueType);i&&(t.value=i.FromArray(e.value))}})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}_dumpPropertiesCode(){return`${this._codeVariableName}.visibleOnFrame = ${this.visibleOnFrame};\n`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}return t}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let s=`\n// ${this.getClassName()}\n`;this.comments&&(s+=`// ${this.comments}\n`);const r=this.getClassName();if("GeometryInputBlock"===r){const e=this.type;s+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${e});\n`}else s+=`var ${this._codeVariableName} = new BABYLON.${r}("${this.name}");\n`;s+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint.ownerBlock;-1===t.indexOf(r)&&(s+=r._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const r of i.endpoints){const i=r.ownerBlock;i&&-1===t.indexOf(i)&&(s+=i._dumpCode(e,t))}return s}clone(){const e=this.serialize(),t=d(e.customType);if(t){const i=new t;return i._deserialize(e),i}return null}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose();this.onBuildObservable.clear()}}ae([pe("comment")],mv.prototype,"comments",void 0);class gv extends mv{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",Yg.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}u("BABYLON.GeometryOutputBlock",gv),function(e){e[e.None=0]="None",e[e.Positions=1]="Positions",e[e.Normals=2]="Normals",e[e.Tangents=3]="Tangents",e[e.UV=4]="UV",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6",e[e.Colors=10]="Colors",e[e.VertexID=11]="VertexID",e[e.FaceID=12]="FaceID",e[e.GeometryID=13]="GeometryID",e[e.CollectionID=14]="CollectionID",e[e.LoopID=15]="LoopID",e[e.InstanceID=16]="InstanceID"}(Kg||(Kg={}));class vv{constructor(){this._rotationMatrix=new B,this._scalingMatrix=new B,this._positionMatrix=new B,this._scalingRotationMatrix=new B,this._transformMatrix=new B,this._tempVector3=new w,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}get geometryContext(){return this._geometryContext}get executionContext(){return this._executionContext}get instancingContext(){return this._instancingContext}pushGeometryContext(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)}pushExecutionContext(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)}pushInstancingContext(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)}restoreGeometryContext(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null}restoreExecutionContext(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null}restoreInstancingContext(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null}getContextualValue(e,t=!1){if(!this.executionContext)return t||this.noContextualData.push(e),null;const i=this.executionContext.getExecutionIndex();switch(e){case Kg.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():this.geometryContext&&this.geometryContext.positions?w.FromArray(this.geometryContext.positions,3*i):w.Zero();case Kg.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():this.geometryContext&&this.geometryContext.normals?w.FromArray(this.geometryContext.normals,3*i):w.Zero();case Kg.Colors:return this.geometryContext&&this.geometryContext.colors?F.FromArray(this.geometryContext.colors,4*i):F.Zero();case Kg.Tangents:return this.geometryContext&&this.geometryContext.tangents?F.FromArray(this.geometryContext.tangents,4*i):F.Zero();case Kg.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():this.geometryContext&&this.geometryContext.uvs?N.FromArray(this.geometryContext.uvs,2*i):N.Zero();case Kg.UV2:return this.geometryContext&&this.geometryContext.uvs2?N.FromArray(this.geometryContext.uvs2,2*i):N.Zero();case Kg.UV3:return this.geometryContext&&this.geometryContext.uvs3?N.FromArray(this.geometryContext.uvs3,2*i):N.Zero();case Kg.UV4:return this.geometryContext&&this.geometryContext.uvs4?N.FromArray(this.geometryContext.uvs4,2*i):N.Zero();case Kg.UV5:return this.geometryContext&&this.geometryContext.uvs5?N.FromArray(this.geometryContext.uvs5,2*i):N.Zero();case Kg.UV6:return this.geometryContext&&this.geometryContext.uvs6?N.FromArray(this.geometryContext.uvs6,2*i):N.Zero();case Kg.VertexID:return i;case Kg.FaceID:return this.executionContext.getExecutionFaceIndex();case Kg.LoopID:return this.executionContext.getExecutionLoopIndex();case Kg.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case Kg.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case Kg.CollectionID:return this.geometryContext&&this.geometryContext.metadata&&this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){const i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case Yg.Vector2:return new N(i,i);case Yg.Vector3:return new w(i,i,i);case Yg.Vector4:return new F(i,i,i,i)}return null}adaptInput(e,t,i){if(!e.isConnected)return e.value||i;const s=e.getConnectedValue(this);if(e._connectedPoint?.type===t)return s;switch(t){case Yg.Vector2:return new N(s,s);case Yg.Vector3:return new w(s,s,s);case Yg.Vector4:return new F(s,s,s,s)}return null}emitErrors(){let e="";for(const t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional.\n`;for(const t of this.noContextualData)e+=`Contextual input ${Kg[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block).\n`;if(e)throw"Build of NodeGeometry failed:\n"+e}_instantiate(e,t,i,s,r){B.ScalingToRef(s.x,s.y,s.z,this._scalingMatrix),B.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),B.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let t=0;te.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${Kg[this._contextualSource]};\n`;const t=[];let i="";switch(this.type){case Yg.Float:case Yg.Int:i=`${this.value}`;break;case Yg.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case Yg.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case Yg.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`}return t.push(`${e}.value = ${i}`),this.type!==Yg.Float&&this.type!==Yg.Int||t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}serialize(){const e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,null===this._storedValue||this.isContextual||(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=d(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}u("BABYLON.GeometryInputBlock",xv);class Tv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",Yg.Float,!0,1),this.registerInput("width",Yg.Float,!0,0),this.registerInput("height",Yg.Float,!0,0),this.registerInput("depth",Yg.Float,!0,0),this.registerInput("subdivisions",Yg.Int,!0,1),this.registerInput("subdivisionsX",Yg.Int,!0,0),this.registerInput("subdivisionsY",Yg.Int,!0,0),this.registerInput("subdivisionsZ",Yg.Int,!0,0),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){const e=new xv("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){const e=new xv("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new xv("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new xv("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){const t={},i=e=>{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.depth=this.depth.getConnectedValue(e);const i=this.subdivisions.getConnectedValue(e),s=this.subdivisionsX.getConnectedValue(e),r=this.subdivisionsY.getConnectedValue(e),n=this.subdivisionsZ.getConnectedValue(e);return i&&(t.segments=i),s&&(t.widthSegments=s),r&&(t.heightSegments=r),n&&(t.depthSegments=n),function(e){const t=e.width||e.size||1,i=e.height||e.size||1,s=e.depth||e.size||1,r=0|(e.widthSegments||e.segments||1),n=0|(e.heightSegments||e.segments||1),o=0|(e.depthSegments||e.segments||1),a=new B,l=new B,h=new B,c=Rh({width:t,height:s,subdivisionsX:r,subdivisionsY:o});B.TranslationToRef(0,-i/2,0,l),B.RotationZToRef(Math.PI,a),a.multiplyToRef(l,h),c.transform(h);const u=Rh({width:t,height:s,subdivisionsX:r,subdivisionsY:o});B.TranslationToRef(0,i/2,0,h),u.transform(h);const d=Rh({width:i,height:s,subdivisionsX:n,subdivisionsY:o});B.TranslationToRef(-t/2,0,0,l),B.RotationZToRef(Math.PI/2,a),a.multiplyToRef(l,h),d.transform(h);const p=Rh({width:i,height:s,subdivisionsX:n,subdivisionsY:o});B.TranslationToRef(t/2,0,0,l),B.RotationZToRef(-Math.PI/2,a),a.multiplyToRef(l,h),p.transform(h);const f=Rh({width:t,height:i,subdivisionsX:r,subdivisionsY:n});B.TranslationToRef(0,0,-s/2,l),B.RotationXToRef(-Math.PI/2,a),a.multiplyToRef(l,h),f.transform(h);const _=Rh({width:t,height:i,subdivisionsX:r,subdivisionsY:n});return B.TranslationToRef(0,0,s/2,l),B.RotationXToRef(Math.PI/2,a),a.multiplyToRef(l,h),_.transform(h),c.merge([u,p,d,f,_],!0),c}(t)};if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Tv.prototype,"evaluateContext",void 0),u("BABYLON.BoxBlock",Tv);class Sv{_getGlobalNodeGeometryEditor(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=Sv._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new g,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return Ii.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise((t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),void 0===this.BJSNODEGEOMETRYEDITOR){const i=e&&e.editorURL?e.editorURL:Sv.EditorURL;Ii.LoadBabylonScript(i,(()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}else this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}_createNodeEditor(e){const t={nodeGeometry:this,...e};this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";const s=je.Now;this._initializeBlock(this.outputBlock,i);const r=new vv;r.buildId=this._buildId,r.verbose=e,this.outputBlock.build(r),t&&(this._buildId=Sv._BuildIdGenerator++),this._buildExecutionTime=je.Now-s,r.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=r.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;const i=new Un(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),!!this._vertexData&&(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e)}_initializeBlock(e,t=!0){e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._initializeBlock(i,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();const i={};for(const t of e.blocks){const e=d(t.customType);if(e){const s=new e;s._deserialize(t),i[t.id]=s,this.attachedBlocks.push(s)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,s=t._tempEntryPointUniqueId;if(s){const e=i[s];e&&e.attachToEndpoint(t)}}for(let s=0;se.targetConnectionName))&&!t||this._restoreConnections(n,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const s=e.locations||e.editorData.locations;for(const e of s)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&s.concat(this.editorData.locations),e.locations?this.editorData={locations:s}:(this.editorData=e.editorData,this.editorData.locations=s);const r=[];for(const e in i)r[e]=i[e].uniqueId;this.editorData.map=r}this.comment=e.comment}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n)for(const o of r.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==s.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;s.connectTo(e,!0),this._restoreConnections(n,t,i)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let s=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}");\n`;for(const r of t)r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));return this.outputBlock&&(e=[],s+="// Connections\n",s+=this.outputBlock._dumpCodeForOutputConnections(e),s+="// Output nodes\n",s+=`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName};\n`,s+="nodeGeometry.build();\n"),s}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new Tv("Box");e.autoConfigure();const t=new gv("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=Pe.Clone((()=>new Sv(e)),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){const t=e?{}:Pe.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}dispose(){for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){const t=new Sv(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=Pe.Parse((()=>new Sv(e.name)),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return"_BLANK"===e?Promise.resolve(Sv.CreateDefault("blank")):new Promise(((s,r)=>{const n=new Ne;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(o.nodeGeometry);t||(t=Pe.Parse((()=>new Sv(e)),a,null)),t.parseSerializedObject(a),t.snippetId=e;try{i||t.build(),s(t)}catch(e){r(e)}}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}Sv._BuildIdGenerator=0,Sv.EditorURL=`${Ii._DefaultCdnUrl}/v${Br.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`,Sv.SnippetUrl="https://snippet.babylonjs.com",ae([pe()],Sv.prototype,"name",void 0),ae([pe("comment")],Sv.prototype,"comment",void 0);class Ev extends mv{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=T,this.registerInput("geometry",Yg.Geometry),this.registerOutput("output",Yg.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e),i=[],s={};for(let e=0;es[e])),r};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`;return e+=`${this._codeVariableName}.epsilon = ${this.epsilon};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Ev.prototype,"evaluateContext",void 0),ae([Lo("Epsilon",bo.Float,"ADVANCED",{notifiers:{rebuild:!0}})],Ev.prototype,"epsilon",void 0),u("BABYLON.GeometryOptimizeBlock",Ev);class bv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",Yg.Float,!0,1),this.registerInput("width",Yg.Float,!0,0),this.registerInput("height",Yg.Float,!0,0),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){const e=new xv("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){const e=new xv("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new xv("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){const t={},i=e=>(t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),ho(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],bv.prototype,"evaluateContext",void 0),u("BABYLON.PlaneBlock",bv);class Cv extends mv{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.reverseWindingOrder=!1,this.serializedCachedData=!1,this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}cleanData(){this._mesh=null,this._cachedVertexData=null}_buildBlock(){if(!this._mesh)return void(this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null);const e=Tr.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;te.clone()}serialize(){const e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=Tr.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(e.cachedVertexData=this._cachedVertexData.serialize())),e.reverseWindingOrder=this.reverseWindingOrder,e}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=Tr.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}ae([Lo("Serialize cached data",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Cv.prototype,"serializedCachedData",void 0),u("BABYLON.MeshBlock",Cv);class yv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",Yg.Float,!0,1),this.registerInput("radiusX",Yg.Float,!0,0),this.registerInput("radiusY",Yg.Float,!0,0),this.registerInput("radiusZ",Yg.Float,!0,0),this.registerInput("subdivisions",Yg.Int,!0,4),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new xv("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.radiusX=this.radiusX.getConnectedValue(e),t.radiusY=this.radiusY.getConnectedValue(e),t.radiusZ=this.radiusZ.getConnectedValue(e),Ta(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],yv.prototype,"evaluateContext",void 0),u("BABYLON.IcoSphereBlock",yv);class Av extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",Yg.Int,!0,32),this.registerInput("diameter",Yg.Float,!0,1),this.registerInput("diameterX",Yg.Float,!0,0),this.registerInput("diameterY",Yg.Float,!0,0),this.registerInput("diameterZ",Yg.Float,!0,0),this.registerInput("arc",Yg.Float,!0,1),this.registerInput("slice",Yg.Float,!0,1),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new xv("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.segments=this.segments.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterX=this.diameterX.getConnectedValue(e),t.diameterY=this.diameterY.getConnectedValue(e),t.diameterZ=this.diameterZ.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),t.slice=this.slice.getConnectedValue(e),rc(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Av.prototype,"evaluateContext",void 0),u("BABYLON.SphereBlock",Av);class Rv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",Yg.Float,!0,1),this.registerInput("height",Yg.Float,!0,1),this.registerInput("subdivisions",Yg.Int,!0,1),this.registerInput("subdivisionsX",Yg.Int,!0,0),this.registerInput("subdivisionsY",Yg.Int,!0,0),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){const e=new xv("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new xv("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.subdivisionsX=this.subdivisionsX.getConnectedValue(e),t.subdivisionsY=this.subdivisionsY.getConnectedValue(e),Rh(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Rv.prototype,"evaluateContext",void 0),u("BABYLON.GridBlock",Rv);class Iv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",Yg.Float,!0,1),this.registerInput("thickness",Yg.Float,!0,.5),this.registerInput("tessellation",Yg.Int,!0,16),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new xv("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.thickness=this.thickness.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),Dh(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Iv.prototype,"evaluateContext",void 0),u("BABYLON.TorusBlock",Iv);class Pv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",Yg.Float,!0,25),this.registerInput("diameter",Yg.Float,!0,1),this.registerInput("diameterTop",Yg.Float,!0,-1),this.registerInput("diameterBottom",Yg.Float,!0,-1),this.registerInput("subdivisions",Yg.Int,!0,1),this.registerInput("tessellation",Yg.Int,!0,24),this.registerInput("arc",Yg.Float,!0,1),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new xv("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new xv("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterTop=this.diameterTop.getConnectedValue(e),t.diameterBottom=this.diameterBottom.getConnectedValue(e),-1===t.diameterTop&&(t.diameterTop=t.diameter),-1===t.diameterBottom&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),qh(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Pv.prototype,"evaluateContext",void 0),u("BABYLON.CylinderBlock",Pv);class Mv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",Yg.Float,!0,1),this.registerInput("radius",Yg.Float,!0,.25),this.registerInput("tessellation",Yg.Int,!0,16),this.registerInput("subdivisions",Yg.Int,!0,2),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){const e=new xv("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new xv("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),oc(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Mv.prototype,"evaluateContext",void 0),u("BABYLON.CapsuleBlock",Mv);class Dv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",Yg.Float,!0,.5),this.registerInput("tessellation",Yg.Int,!0,64),this.registerInput("arc",Yg.Float,!0,1),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new xv("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),hc(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Dv.prototype,"evaluateContext",void 0),u("BABYLON.DiscBlock",Dv),u("BABYLON.NullBlock",class extends mv{constructor(e){super(e),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}});class Ov extends mv{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",Yg.Geometry),this.registerInput("positions",Yg.Vector3),this.registerOutput("output",Yg.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.normals.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.normals||(this._vertexData.normals=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.uvs.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);const t=[],i=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.colors.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.colors||(this._vertexData.colors=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.tangents.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.tangents||(this._vertexData.tangents=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndexthis._updateInputOutputTypes())),this.left.onDisconnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onConnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onDisconnectionObservable.add((()=>this._updateInputOutputTypes()))]}getClassName(){return"MathBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){let e;const t=this.left,i=this.right;if(!t.isConnected||!i.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const s=t.type===Yg.Float||t.type===Yg.Int,r=i.type===Yg.Float||i.type===Yg.Int,n=s&&r;switch(this.operation){case qg.Add:e=n?e=>t.getConnectedValue(e)+i.getConnectedValue(e):s?e=>e.adapt(t,i.type).add(i.getConnectedValue(e)):e=>t.getConnectedValue(e).add(e.adapt(i,t.type));break;case qg.Subtract:e=n?e=>t.getConnectedValue(e)-i.getConnectedValue(e):s?e=>e.adapt(t,i.type).subtract(i.getConnectedValue(e)):e=>t.getConnectedValue(e).subtract(e.adapt(i,t.type));break;case qg.Multiply:e=n?e=>t.getConnectedValue(e)*i.getConnectedValue(e):s?e=>e.adapt(t,i.type).multiply(i.getConnectedValue(e)):e=>t.getConnectedValue(e).multiply(e.adapt(i,t.type));break;case qg.Divide:e=n?e=>t.getConnectedValue(e)/i.getConnectedValue(e):s?e=>e.adapt(t,i.type).divide(i.getConnectedValue(e)):e=>t.getConnectedValue(e).divide(e.adapt(i,t.type));break;case qg.Min:if(n)e=e=>Math.min(t.getConnectedValue(e),i.getConnectedValue(e));else{const[r,n]=s?[i,t]:[t,i];switch(r.type){case Yg.Vector2:e=e=>N.Minimize(r.getConnectedValue(e),e.adapt(n,r.type));break;case Yg.Vector3:e=e=>w.Minimize(r.getConnectedValue(e),e.adapt(n,r.type));break;case Yg.Vector4:e=e=>F.Minimize(r.getConnectedValue(e),e.adapt(n,r.type))}}break;case qg.Max:if(!n){const[r,n]=s?[i,t]:[t,i];switch(r.type){case Yg.Vector2:e=e=>N.Maximize(r.getConnectedValue(e),e.adapt(n,r.type));break;case Yg.Vector3:e=e=>w.Maximize(r.getConnectedValue(e),e.adapt(n,r.type));break;case Yg.Vector4:e=e=>F.Maximize(r.getConnectedValue(e),e.adapt(n,r.type))}break}e=e=>Math.max(t.getConnectedValue(e),i.getConnectedValue(e))}this.output._storedFunction=i=>t.type===Yg.Int?0|e(i):e(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${qg[this.operation]};\n`}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===Yg.Int||this.left.type===Yg.Float&&this.right.type!==Yg.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(const[e,t]of[[this.left,this.right],[this.right,this.left]])e.acceptedConnectionPointTypes=[Yg.Int,Yg.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==Yg.Int&&t.type!==Yg.Float||e.acceptedConnectionPointTypes.push(Yg.Vector2,Yg.Vector3,Yg.Vector4))}dispose(){super.dispose(),this._connectionObservers.forEach((e=>e.remove())),this._connectionObservers.length=0}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}}ae([Lo("Operation",bo.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:qg.Add},{label:"Subtract",value:qg.Subtract},{label:"Multiply",value:qg.Multiply},{label:"Divide",value:qg.Divide},{label:"Max",value:qg.Max},{label:"Min",value:qg.Min}]})],Bv.prototype,"operation",void 0),u("BABYLON.MathBlock",Bv),u("BABYLON.MapRangeBlock",class extends mv{constructor(e){super(e),this.registerInput("value",Yg.AutoDetect),this.registerInput("fromMin",Yg.Float,!0,0),this.registerInput("fromMax",Yg.Float,!0,1),this.registerInput("toMin",Yg.Float,!0,0),this.registerInput("toMax",Yg.Float,!0,1),this.registerOutput("output",Yg.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(Yg.Vector2),this._inputs[0].excludedConnectionPointTypes.push(Yg.Vector3),this._inputs[0].excludedConnectionPointTypes.push(Yg.Vector4),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),s=this.fromMax.getConnectedValue(e),r=this.toMin.getConnectedValue(e),n=(t-i)/(s-i)*(this.toMax.getConnectedValue(e)-r)+r;return this.output.type===Yg.Int?Math.floor(n):n}}}),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(Qg||(Qg={}));class Vv extends mv{constructor(e){super(e),this.test=Qg.Equal,this.registerInput("left",Yg.Float),this.registerInput("right",Yg.Float,!0,0),this.registerInput("ifTrue",Yg.AutoDetect,!0,1),this.registerInput("ifFalse",Yg.AutoDetect,!0,0),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=Yg.Float,this._inputs[0].acceptedConnectionPointTypes.push(Yg.Int),this._inputs[1].acceptedConnectionPointTypes.push(Yg.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);let s=!1;switch(this.test){case Qg.Equal:s=G.WithinEpsilon(t,i,T);break;case Qg.NotEqual:s=t!==i;break;case Qg.LessThan:s=ti;break;case Qg.LessOrEqual:s=t<=i;break;case Qg.GreaterOrEqual:s=t>=i;break;case Qg.Xor:s=!!t&&!i||!t&&!!i;break;case Qg.Or:s=!!t||!!i;break;case Qg.And:s=!!t&&!!i}return s};this.output._storedFunction=t=>e(t)?this.ifTrue.getConnectedValue(t):this.ifFalse.getConnectedValue(t)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${Qg[this.test]};\n`}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}ae([Lo("Test",bo.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:Qg.Equal},{label:"NotEqual",value:Qg.NotEqual},{label:"LessThan",value:Qg.LessThan},{label:"GreaterThan",value:Qg.GreaterThan},{label:"LessOrEqual",value:Qg.LessOrEqual},{label:"GreaterOrEqual",value:Qg.GreaterOrEqual},{label:"Xor",value:Qg.Xor},{label:"Or",value:Qg.Or},{label:"And",value:Qg.And}]})],Vv.prototype,"test",void 0),u("BABYLON.ConditionBlock",Vv),function(e){e[e.None=0]="None",e[e.LoopID=1]="LoopID",e[e.InstanceID=2]="InstanceID"}(Zg||(Zg={}));class Uv extends mv{constructor(e){super(e),this._currentLockId=-1,this.lockMode=Zg.None,this.registerInput("min",Yg.AutoDetect),this.registerInput("max",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture),this._inputs[1].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[1].excludedConnectionPointTypes.push(Yg.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){const e=new xv("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new xv("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case Yg.Int:case Yg.Float:e=e=>{const t=this.min.getConnectedValue(e)||0,i=this.max.getConnectedValue(e)||0;return t+Math.random()*(i-t)};break;case Yg.Vector2:e=e=>{const t=this.min.getConnectedValue(e)||N.Zero(),i=this.max.getConnectedValue(e)||N.Zero();return new N(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y))};break;case Yg.Vector3:e=e=>{const t=this.min.getConnectedValue(e)||w.Zero(),i=this.max.getConnectedValue(e)||w.Zero();return new w(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z))};break;case Yg.Vector4:e=e=>{const t=this.min.getConnectedValue(e)||F.Zero(),i=this.max.getConnectedValue(e)||F.Zero();return new F(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z),t.w+Math.random()*(i.w-t.w))}}this.lockMode!==Zg.None&&e?this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case Zg.InstanceID:i=t.getContextualValue(Kg.InstanceID,!0)||0;break;case Zg.LoopID:i=t.getContextualValue(Kg.LoopID,!0)||0}return this._currentLockId===i&&this.lockMode!==Zg.None||(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}:this.output._storedFunction=e}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${Zg[this.lockMode]};\n`}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}ae([Lo("LockMode",bo.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:Zg.None},{label:"LoopID",value:Zg.LoopID},{label:"InstanceID",value:Zg.InstanceID}]})],Uv.prototype,"lockMode",void 0),u("BABYLON.RandomBlock",Uv),u("BABYLON.NoiseBlock",class extends mv{constructor(e){super(e),this.registerInput("offset",Yg.Vector3,!0,w.Zero()),this.registerInput("scale",Yg.Float,!0,1),this.registerInput("octaves",Yg.Float,!0,2,0,16),this.registerInput("roughness",Yg.Float,!0,.5,0,1),this.registerOutput("output",Yg.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return 0!==t?-e:e}_noiseGrad(e,t,i,s){const r=15&e,n=r<8?t:i,o=r<4?i:12===r||14==r?t:s;return this._negateIf(n,r&n)+this._negateIf(o,2&r)}_fade(e){return e*e*e*(e*(6*e-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let s,r,n;return s=r=n=3735928584,n+=i,r+=t,s+=e,n^=r,n-=this._hashBitRotate(r,14),s^=n,s-=this._hashBitRotate(n,11),r^=s,r-=this._hashBitRotate(s,25),n^=r,n-=this._hashBitRotate(r,16),s^=n,s-=this._hashBitRotate(n,4),r^=s,r-=this._hashBitRotate(s,14),n^=r,n-=this._hashBitRotate(r,24),n}_mix(e,t,i,s,r,n,o,a,l,h,c){const u=1-l,d=1-h;return(1-c)*(d*(e*u+t*l)+h*(i*u+s*l))+c*(d*(r*u+n*l)+h*(o*u+a*l))}_perlinNoise(e){const t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),s=(0|e.z)-(e.z<0?1:0),r=e.x-t,n=e.y-i,o=e.z-s,a=this._fade(r),l=this._fade(n),h=this._fade(o);return this._mix(this._noiseGrad(this._hash(t,i,s),r,n,o),this._noiseGrad(this._hash(t+1,i,s),r-1,n,o),this._noiseGrad(this._hash(t,i+1,s),r,n-1,o),this._noiseGrad(this._hash(t+1,i+1,s),r-1,n-1,o),this._noiseGrad(this._hash(t,i,s+1),r,n,o-1),this._noiseGrad(this._hash(t+1,i,s+1),r-1,n,o-1),this._noiseGrad(this._hash(t,i+1,s+1),r,n-1,o-1),this._noiseGrad(this._hash(t+1,i+1,s+1),r-1,n-1,o-1),a,l,h)}_perlinSigned(e){return.982*this._perlinNoise(e)}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,s,r){const n=new w(i.x*r+s.x,i.y*r+s.y,i.z*r+s.z);let o=1,a=1,l=0,h=0;const c=0|(e=G.Clamp(e,0,15));for(let e=0;e<=c;e++)h+=this._perlin(n.scale(o))*a,l+=a,a*=G.Clamp(t,0,1),o*=2;const u=e-Math.floor(e);if(0==u)return h/l;let d=h+this._perlin(n.scale(o))*a;return h/=l,d/=l+a,(1-u)*h+u*d}_buildBlock(){this.output._storedFunction=e=>{const t=e.getContextualValue(Kg.Positions),i=this.octaves.getConnectedValue(e),s=this.roughness.getConnectedValue(e),r=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,s,t,r,n)}}});class kv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",Yg.Geometry),this.registerInput("geometry1",Yg.Geometry,!0),this.registerInput("geometry2",Yg.Geometry,!0),this.registerInput("geometry3",Yg.Geometry,!0),this.registerInput("geometry4",Yg.Geometry,!0),this.registerOutput("output",Yg.Geometry)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{let t=this.geometry0.getConnectedValue(e);const i=[];if(!t)return null;if(t=t.clone(),this.geometry1.isConnected){const t=this.geometry1.getConnectedValue(e);t&&i.push(t)}if(this.geometry2.isConnected){const t=this.geometry2.getConnectedValue(e);t&&i.push(t)}if(this.geometry3.isConnected){const t=this.geometry3.getConnectedValue(e);t&&i.push(t)}if(this.geometry4.isConnected){const t=this.geometry4.getConnectedValue(e);t&&i.push(t)}return i.length&&t&&(t=t.merge(i,!0,!1,!0,!0)),t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],kv.prototype,"evaluateContext",void 0),u("BABYLON.MergeGeometryBlock",kv);class Gv extends mv{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",Yg.Geometry,!0),this.registerInput("geometry1",Yg.Geometry,!0),this.registerInput("geometry2",Yg.Geometry,!0),this.registerInput("geometry3",Yg.Geometry,!0),this.registerInput("geometry4",Yg.Geometry,!0),this.registerInput("geometry5",Yg.Geometry,!0),this.registerInput("geometry6",Yg.Geometry,!0),this.registerInput("geometry7",Yg.Geometry,!0),this.registerInput("geometry8",Yg.Geometry,!0),this.registerInput("geometry9",Yg.Geometry,!0),this.registerOutput("output",Yg.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,s){if(e.isConnected){const r=e.getConnectedValue(t);if(!r)return;r.metadata=r.metadata||{},r.metadata.collectionId=i,s.push(r)}}_buildBlock(e){const t=e=>{const t=[];return this._storeGeometry(this.geometry0,e,0,t),this._storeGeometry(this.geometry1,e,1,t),this._storeGeometry(this.geometry2,e,2,t),this._storeGeometry(this.geometry3,e,3,t),this._storeGeometry(this.geometry4,e,4,t),this._storeGeometry(this.geometry5,e,5,t),this._storeGeometry(this.geometry6,e,6,t),this._storeGeometry(this.geometry7,e,7,t),this._storeGeometry(this.geometry8,e,8,t),this._storeGeometry(this.geometry9,e,9,t),t.length?t[Math.round(Math.random()*(t.length-1))]:null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Gv.prototype,"evaluateContext",void 0),u("BABYLON.GeometryCollectionBlock",Gv),u("BABYLON.GeometryElbowBlock",class extends mv{constructor(e){super(e),this.registerInput("input",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];t._storedFunction=e=>i.getConnectedValue(e)}}),u("BABYLON.ComputeNormalsBlock",class extends mv{constructor(e){super(e),this.registerInput("geometry",Yg.Geometry),this.registerOutput("output",Yg.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),Tr.ComputeNormals(t.positions,t.indices,t.normals),t}}}),u("BABYLON.VectorConverterBlock",class extends mv{constructor(e){super(e),this.registerInput("xyzw ",Yg.Vector4,!0),this.registerInput("xyz ",Yg.Vector3,!0),this.registerInput("xy ",Yg.Vector2,!0),this.registerInput("zw ",Yg.Vector2,!0),this.registerInput("x ",Yg.Float,!0),this.registerInput("y ",Yg.Float,!0),this.registerInput("z ",Yg.Float,!0),this.registerInput("w ",Yg.Float,!0),this.registerOutput("xyzw",Yg.Vector4),this.registerOutput("xyz",Yg.Vector3),this.registerOutput("xy",Yg.Vector2),this.registerOutput("zw",Yg.Vector2),this.registerOutput("x",Yg.Float),this.registerOutput("y",Yg.Float),this.registerOutput("z",Yg.Float),this.registerOutput("w",Yg.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);const t=this.xIn,i=this.yIn,s=this.zIn,r=this.wIn,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,c=this.xyzOut,u=this.xyOut,d=this.zwOut,p=this.xOut,f=this.yOut,_=this.zOut,m=this.wOut,g=e=>{if(l.isConnected)return l.getConnectedValue(e);let h=0,c=0,u=0,d=0;if(t.isConnected&&(h=t.getConnectedValue(e)),i.isConnected&&(c=i.getConnectedValue(e)),s.isConnected&&(u=s.getConnectedValue(e)),r.isConnected&&(d=r.getConnectedValue(e)),n.isConnected){const t=n.getConnectedValue(e);t&&(h=t.x,c=t.y)}if(o.isConnected){const t=o.getConnectedValue(e);t&&(u=t.x,d=t.y)}if(a.isConnected){const t=a.getConnectedValue(e);t&&(h=t.x,c=t.y,u=t.z)}return new F(h,c,u,d)};h._storedFunction=e=>g(e),c._storedFunction=e=>{const t=g(e);return new w(t.x,t.y,t.z)},u._storedFunction=e=>{const t=g(e);return new N(t.x,t.y)},d._storedFunction=e=>{const t=g(e);return new N(t.z,t.w)},p._storedFunction=e=>g(e).x,f._storedFunction=e=>g(e).y,_._storedFunction=e=>g(e).z,m._storedFunction=e=>g(e).w}}),u("BABYLON.NormalizeVectorBlock",class extends mv{constructor(e){super(e),this.registerInput("input",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(Yg.Float),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.output._storedFunction=null,this.input.isConnected?this.output._storedFunction=e=>this.input.getConnectedValue(e).normalize():this.output._storedValue=null}});class zv extends mv{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",Yg.Geometry),this.registerInput("id",Yg.Int,!0,0),this.registerOutput("output",Yg.Geometry),this.id.acceptedConnectionPointTypes.push(Yg.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.geometry.getConnectedValue(e);if(!t||!t.indices||!t.positions)return t;const i=new xr;return i.materialIndex=0|this.id.getConnectedValue(e),i.indexStart=0,i.indexCount=t.indices.length,i.verticesStart=0,i.verticesCount=t.positions.length/3,t.materialInfos=[i],t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],zv.prototype,"evaluateContext",void 0),u("BABYLON.SetMaterialIDBlock",zv),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Round=4]="Round",e[e.Floor=5]="Floor",e[e.Ceiling=6]="Ceiling",e[e.Sqrt=7]="Sqrt",e[e.Log=8]="Log",e[e.Tan=9]="Tan",e[e.ArcTan=10]="ArcTan",e[e.ArcCos=11]="ArcCos",e[e.ArcSin=12]="ArcSin",e[e.Sign=13]="Sign",e[e.Negate=14]="Negate",e[e.OneMinus=15]="OneMinus",e[e.Reciprocal=16]="Reciprocal",e[e.ToDegrees=17]="ToDegrees",e[e.ToRadians=18]="ToRadians",e[e.Fract=19]="Fract",e[e.Exp2=20]="Exp2"}(Jg||(Jg={}));class Wv extends mv{constructor(e){super(e),this.operation=Jg.Cos,this.registerInput("input",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case Jg.Cos:t=e=>Math.cos(e);break;case Jg.Sin:t=e=>Math.sin(e);break;case Jg.Abs:t=e=>Math.abs(e);break;case Jg.Exp:t=e=>Math.exp(e);break;case Jg.Exp2:t=e=>Math.pow(2,e);break;case Jg.Round:t=e=>Math.round(e);break;case Jg.Floor:t=e=>Math.floor(e);break;case Jg.Ceiling:t=e=>Math.ceil(e);break;case Jg.Sqrt:t=e=>Math.sqrt(e);break;case Jg.Log:t=e=>Math.log(e);break;case Jg.Tan:t=e=>Math.tan(e);break;case Jg.ArcTan:t=e=>Math.atan(e);break;case Jg.ArcCos:t=e=>Math.acos(e);break;case Jg.ArcSin:t=e=>Math.asin(e);break;case Jg.Sign:t=e=>Math.sign(e);break;case Jg.Negate:t=e=>-e;break;case Jg.OneMinus:t=e=>1-e;break;case Jg.Reciprocal:t=e=>1/e;break;case Jg.ToRadians:t=e=>e*Math.PI/180;break;case Jg.ToDegrees:t=e=>180*e/Math.PI;break;case Jg.Fract:t=e=>e>=0?e-Math.floor(e):e-Math.ceil(e)}if(!t)return this.output._storedFunction=null,void(this.output._storedValue=null);switch(this.input.type){case Yg.Int:case Yg.Float:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return t(i)};break;case Yg.Vector2:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new N(t(i.x),t(i.y))};break;case Yg.Vector3:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new w(t(i.x),t(i.y),t(i.z))};break;case Yg.Vector4:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new F(t(i.x),t(i.y),t(i.z),t(i.w))}}return this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${Jg[this.operation]};\n`}}ae([Lo("Operation",bo.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:Jg.Cos},{label:"Sin",value:Jg.Sin},{label:"Abs",value:Jg.Abs},{label:"Exp",value:Jg.Exp},{label:"Exp2",value:Jg.Exp2},{label:"Round",value:Jg.Round},{label:"Floor",value:Jg.Floor},{label:"Ceiling",value:Jg.Ceiling},{label:"Sqrt",value:Jg.Sqrt},{label:"Log",value:Jg.Log},{label:"Tan",value:Jg.Tan},{label:"ArcTan",value:Jg.ArcTan},{label:"ArcCos",value:Jg.ArcCos},{label:"ArcSin",value:Jg.ArcSin},{label:"Sign",value:Jg.Sign},{label:"Negate",value:Jg.Negate},{label:"OneMinus",value:Jg.OneMinus},{label:"Reciprocal",value:Jg.Reciprocal},{label:"ToDegrees",value:Jg.ToDegrees},{label:"ToRadians",value:Jg.ToRadians},{label:"Fract",value:Jg.Fract}]})],Wv.prototype,"operation",void 0),u("BABYLON.GeometryTrigonometryBlock",Wv);class Hv extends mv{constructor(e){super(e),this._rotationMatrix=new B,this._scalingMatrix=new B,this._translationMatrix=new B,this._scalingRotationMatrix=new B,this._transformMatrix=new B,this.evaluateContext=!0,this.registerInput("value",Yg.AutoDetect),this.registerInput("matrix",Yg.Matrix,!0),this.registerInput("translation",Yg.Vector3,!0,w.Zero()),this.registerInput("rotation",Yg.Vector3,!0,w.Zero()),this.registerInput("scaling",Yg.Vector3,!0,w.One()),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Yg.Float),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.value.getConnectedValue(e);if(!t)return null;let i;if(this.matrix.isConnected)i=this.matrix.getConnectedValue(e);else{const t=this.scaling.getConnectedValue(e),s=this.rotation.getConnectedValue(e),r=this.translation.getConnectedValue(e);B.ScalingToRef(t.x,t.y,t.z,this._scalingMatrix),B.RotationYawPitchRollToRef(s.y,s.x,s.z,this._rotationMatrix),B.TranslationToRef(r.x,r.y,r.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),i=this._transformMatrix}switch(this.value.type){case Yg.Geometry:{const e=t.clone();return e.transform(i),e}case Yg.Vector2:return N.Transform(t,i);case Yg.Vector3:return w.TransformCoordinates(t,i);case Yg.Vector4:return F.TransformCoordinates(t,i)}return null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Hv.prototype,"evaluateContext",void 0),u("BABYLON.GeometryTransformBlock",Hv),u("BABYLON.RotationXBlock",class extends mv{constructor(e){super(e),this.registerInput("angle",Yg.Float,!1,0),this.registerOutput("matrix",Yg.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new xv("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>B.RotationX(this.angle.getConnectedValue(e))}}),u("BABYLON.RotationYBlock",class extends mv{constructor(e){super(e),this.registerInput("angle",Yg.Float,!1,0),this.registerOutput("matrix",Yg.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new xv("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>B.RotationY(this.angle.getConnectedValue(e))}}),u("BABYLON.RotationZBlock",class extends mv{constructor(e){super(e),this.registerInput("angle",Yg.Float,!1,0),this.registerOutput("matrix",Yg.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new xv("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>B.RotationZ(this.angle.getConnectedValue(e))}}),u("BABYLON.ScalingBlock",class extends mv{constructor(e){super(e),this.registerInput("scale",Yg.Vector3,!1,w.One()),this.registerOutput("matrix",Yg.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new xv("Scale");e.value=new w(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.scale.getConnectedValue(e);return B.Scaling(t.x,t.y,t.z)}}}),u("BABYLON.AlignBlock",class extends mv{constructor(e){super(e),this.registerInput("source",Yg.Vector3,!0,w.Up()),this.registerInput("target",Yg.Vector3,!0,w.Left()),this.registerOutput("matrix",Yg.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.source.getConnectedValue(e).clone(),i=this.target.getConnectedValue(e).clone(),s=new B;return t.normalize(),i.normalize(),B.RotationAlignToRef(t,i,s,!0),s}}}),u("BABYLON.TranslationBlock",class extends mv{constructor(e){super(e),this.registerInput("translation",Yg.Vector3,!1,w.Zero()),this.registerOutput("matrix",Yg.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new xv("Translation");e.value=new w(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.translation.getConnectedValue(e);return B.Translation(t.x,t.y,t.z)}}});class Xv extends mv{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",Yg.Geometry),this.registerInput("instance",Yg.Geometry,!0),this.registerInput("density",Yg.Float,!0,1,0,1),this.registerInput("matrix",Yg.Matrix,!0),this.registerInput("rotation",Yg.Vector3,!0,w.Zero()),this.registerInput("scaling",Yg.Vector3,!0,w.One()),this.scaling.acceptedConnectionPointTypes.push(Yg.Float),this.registerOutput("output",Yg.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get density(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected)return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=this._vertexData.positions.length/3;const i=[],s=new w,r=[];let n=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexr)continue;s.fromArray(n,3*this._currentIndex);const o=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(o,s,t,i)}else{const t=e.adaptInput(this.scaling,Yg.Vector3,w.OneReadOnly),r=this.rotation.getConnectedValue(e)||w.ZeroReadOnly;e._instantiate(o,s,r,t,i)}this._currentLoopIndex++}if(e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),!i.length)return null;if(1===i.length)this._vertexData=i[0];else{const e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}return this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"};\n`;return e+=`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`,e}serialize(){const e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Xv.prototype,"evaluateContext",void 0),ae([Lo("Remove duplicated positions",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],Xv.prototype,"removeDuplicatedPositions",void 0),u("BABYLON.InstantiateOnVerticesBlock",Xv);class Yv extends mv{constructor(e){super(e),this._currentPosition=new w,this._currentUV=new N,this._vertex0=new w,this._vertex1=new w,this._vertex2=new w,this._tempVector0=new w,this._tempVector1=new w,this._uv0=new N,this._uv1=new N,this._uv2=new N,this.evaluateContext=!0,this.registerInput("geometry",Yg.Geometry),this.registerInput("instance",Yg.Geometry,!0),this.registerInput("count",Yg.Int,!0,256),this.registerInput("matrix",Yg.Matrix,!0),this.registerInput("rotation",Yg.Vector3,!0,w.Zero()),this.registerInput("scaling",Yg.Vector3,!0,w.One()),this.scaling.acceptedConnectionPointTypes.push(Yg.Float),this.registerOutput("output",Yg.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),w.Cross(this._tempVector1,this._tempVector0)}getOverrideUVs1ContextualValue(){return this._currentUV}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),s=this._vertexData.indices.length/3,r=i/s;let n=0;const o=[];let a=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=i);l++){let i=Math.random(),s=Math.random();if(i>s){const e=i;i=s,s=e}const l=i,h=s-i,c=1-l-h;if(this._currentPosition.set(l*this._vertex0.x+h*this._vertex1.x+c*this._vertex2.x,l*this._vertex0.y+h*this._vertex1.y+c*this._vertex2.y,l*this._vertex0.z+h*this._vertex1.z+c*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(l*this._uv0.x+h*this._uv1.x+c*this._uv2.x,l*this._uv0.y+h*this._uv1.y+c*this._uv2.y),t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length){n-=r;continue}const u=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(u,this._currentPosition,t,o)}else{const t=e.adaptInput(this.scaling,Yg.Vector3,w.OneReadOnly),i=this.rotation.getConnectedValue(e)||w.ZeroReadOnly;e._instantiate(u,this._currentPosition,i,t,o)}a++,this._currentLoopIndex++}}if(o.length)if(1===o.length)this._vertexData=o[0];else{const e=o.splice(0,1)[0];this._vertexData=e.merge(o,!0,!1,!0,!0)}return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Yv.prototype,"evaluateContext",void 0),u("BABYLON.InstantiateOnFacesBlock",Yv);class jv extends mv{constructor(e){super(e),this._currentPosition=new w,this._vertex0=new w,this._vertex1=new w,this._vertex2=new w,this.evaluateContext=!0,this.registerInput("geometry",Yg.Geometry),this.registerInput("instance",Yg.Geometry,!0),this.registerInput("count",Yg.Int,!0,256),this.registerInput("matrix",Yg.Matrix,!0),this.registerInput("rotation",Yg.Vector3,!0,w.Zero()),this.registerInput("scaling",Yg.Vector3,!0,w.One()),this.scaling.acceptedConnectionPointTypes.push(Yg.Float),this.registerOutput("output",Yg.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),s=[],r=mr(this._vertexData.positions,0,this._vertexData.positions.length/3),n=r.minimum,o=r.maximum,a=new w(1,0,0),l=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let r=0;r0&&h++}if(h%2==0){r--;continue}if(t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length)continue;const c=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(c,this._currentPosition,t,s)}else{const t=e.adaptInput(this.scaling,Yg.Vector3,w.OneReadOnly),i=this.rotation.getConnectedValue(e)||w.ZeroReadOnly;e._instantiate(c,this._currentPosition,i,t,s)}this._currentLoopIndex++}if(s.length)if(1===s.length)this._vertexData=s[0];else{const e=s.splice(0,1)[0];this._vertexData=e.merge(s,!0,!1,!0,!0)}return e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],jv.prototype,"evaluateContext",void 0),u("BABYLON.InstantiateOnVolumeBlock",jv);class $v extends mv{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",Yg.Geometry,!0),this.registerInput("count",Yg.Int,!0,1),this.registerOutput("output",Yg.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBaseBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get output(){return this._outputs[0]}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],$v.prototype,"evaluateContext",void 0),u("BABYLON.InstantiateBlock",class extends $v{constructor(e){super(e),this.registerInput("matrix",Yg.Matrix,!0),this.registerInput("position",Yg.Vector3,!0,w.Zero()),this.registerInput("rotation",Yg.Vector3,!0,w.Zero()),this.registerInput("scaling",Yg.Vector3,!0,w.One()),this.scaling.acceptedConnectionPointTypes.push(Yg.Float)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get matrix(){return this._inputs[2]}get position(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}_buildBlock(e){const t=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[];for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],s=B.Identity(),r=w.Zero(),n=w.Zero(),o=w.Zero();for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],s=B.Identity(),r=B.Identity(),n=B.Identity(),o=w.Zero(),a=w.Zero(),l=w.Zero();for(this._currentIndex=0;this._currentIndexthis.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?Math.floor(this.floatIn.getConnectedValue(e)):this.intIn.isConnected?Math.floor(this.intIn.getConnectedValue(e)):0}}),u("BABYLON.DebugBlock",class extends mv{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.log=[];const t=e=>{const t=this.input.getConnectedValue(e);if(null==t)return this.log.push(["null",""]),t;switch(this.input.type){case Yg.Vector2:this.log.push([(i=t,4,`{X: ${i.x.toFixed(4)} Y: ${i.y.toFixed(4)}}`),t.toString()]);break;case Yg.Vector3:this.log.push([Ag(t,4),t.toString()]);break;case Yg.Vector4:this.log.push([Rg(t,4),t.toString()]);break;default:this.log.push([t.toString(),t.toString()])}var i;return t};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}),u("BABYLON.GeometryInfoBlock",class extends mv{constructor(e){super(e),this.registerInput("geometry",Yg.Geometry),this.registerOutput("output",Yg.Geometry),this.registerOutput("id",Yg.Int),this.registerOutput("collectionId",Yg.Int),this.registerOutput("verticesCount",Yg.Int),this.registerOutput("facesCount",Yg.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected)return this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,void(this.output._storedFunction=null);this.output._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData),this.id._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}}),function(e){e[e.Spherical=0]="Spherical",e[e.Cylindrical=1]="Cylindrical",e[e.Cubic=2]="Cubic"}(ev||(ev={}));class Kv extends mv{constructor(e){super(e),this.mapping=ev.Spherical,this.registerInput("position",Yg.Vector3),this.registerInput("normal",Yg.Vector3),this.registerInput("center",Yg.Vector3,!0,w.Zero()),this.registerOutput("uv",Yg.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get center(){return this._inputs[2]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected)return this.uv._storedFunction=null,void(this.uv._storedValue=null);const e=w.Zero(),t=t=>{const i=this.position.getConnectedValue(t)||w.Zero(),s=this.normal.getConnectedValue(t)||w.Zero(),r=this.center.getConnectedValue(t),n=N.Zero();switch(this.mapping){case ev.Spherical:{i.subtractToRef(r,e);const t=e.length();t>0&&(n.x=Math.acos(e.y/t)/Math.PI,0===e.x&&0===e.z||(n.y=Math.atan2(e.x,e.z)/(2*Math.PI)));break}case ev.Cylindrical:{i.subtractToRef(r,e);const t=e.length();t>0&&(n.x=Math.atan2(e.x/t,e.z/t)/(2*Math.PI),n.y=(e.y+1)/2);break}case ev.Cubic:{const e=Math.abs(s.x),t=Math.abs(s.y),o=Math.abs(s.z),a=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z));let l=0,h=0;e>=t&&e>=o?(l=i.y/a-r.y,h=i.z/a-r.z):t>=e&&t>=o?(l=i.x/a-r.x,h=i.z/a-r.z):(l=i.x/a-r.x,h=i.y/a-r.y),n.x=(l+1)/2,n.y=(h+1)/2}}return n};this.uv._storedFunction=e=>t(e)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${ev[this.mapping]};\n`}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}ae([Lo("Mapping",bo.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:ev.Spherical},{label:"Cylindrical",value:ev.Cylindrical},{label:"Cubic",value:ev.Cubic}]})],Kv.prototype,"mapping",void 0),u("BABYLON.MappingBlock",Kv),u("BABYLON.MatrixComposeBlock",class extends mv{constructor(e){super(e),this.registerInput("matrix0",Yg.Matrix),this.registerInput("matrix1",Yg.Matrix),this.registerOutput("output",Yg.Matrix)}getClassName(){return"MatrixComposeBlock"}get matrix0(){return this._inputs[0]}get matrix1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.matrix0.isConnected||!this.matrix1.isConnected)return null;const t=this.matrix0.getConnectedValue(e),i=this.matrix1.getConnectedValue(e);return t&&i?t.multiply(i):null}}}),u("BABYLON.TeleportInBlock",class extends mv{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",Yg.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)-1===t.indexOf(s)&&(i+=s._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(t.isAnAncestorOf(e))return!0}return!1}getDescendantOfPredicate(e){if(e(this))return this;for(const t of this.endpoints){const i=t.getDescendantOfPredicate(e);if(i)return i}return null}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(const e of this._endpoints)e.output._storedFunction=e=>this.input.getConnectedValue(e)}}),u("BABYLON.TeleportOutBlock",class extends mv{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",Yg.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){const e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}});class qv extends mv{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.serializedCachedData=!1,this.registerOutput("texture",Yg.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise(((t,i)=>{const s=new Image,r=document.createElement("canvas"),n=r.getContext("2d");s.onload=()=>{r.width=s.width,r.height=s.height,n.drawImage(s,0,0);const e=n.getImageData(0,0,s.width,s.height).data,i=new Float32Array(e.length);for(let t=0;t{this._data=null,i()},s.src=e}))}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise(((t,i)=>{if(!e.isReady())return void e.onLoadObservable.addOnce((()=>this.extractFromTextureAsync(e).then(t).catch(i)));const s=e.getSize();nu(e,s.width,s.height).then((async e=>{const i=new Float32Array(e.length);for(let t=0;t=0?e%1:1-Math.abs(e)%1}_buildBlock(){const e=e=>{const t=this.texture.getConnectedValue(e);if(!t||!t.data)return null;const i=this.coordinates.getConnectedValue(e);if(!i)return null;const s=this.clampCoordinates?Math.max(0,Math.min(i.x,1)):this._repeatClamp(i.x),r=this.clampCoordinates?Math.max(0,Math.min(i.y,1)):this._repeatClamp(i.y),n=Math.floor(s*(t.width-1)),o=Math.floor(r*(t.height-1)),a=n+t.width*o;return F.FromArray(t.data,4*a)};this.rgba._storedFunction=t=>e(t),this.rgb._storedFunction=t=>{const i=e(t);return i?i.toVector3():null},this.r._storedFunction=t=>{const i=e(t);return i?i.x:null},this.g._storedFunction=t=>{const i=e(t);return i?i.y:null},this.b._storedFunction=t=>{const i=e(t);return i?i.z:null},this.a._storedFunction=t=>{const i=e(t);return i?i.w:null}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates};\n`}serialize(){const e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}}ae([Lo("Clamp Coordinates",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Qv.prototype,"clampCoordinates",void 0),u("BABYLON.GeometryTextureFetchBlock",Qv),u("BABYLON.BoundingBlock",class extends mv{constructor(e){super(e),this.registerInput("geometry",Yg.Geometry),this.registerOutput("min",Yg.Vector3),this.registerOutput("max",Yg.Vector3)}getClassName(){return"BoundingBlock"}get geometry(){return this._inputs[0]}get min(){return this._outputs[0]}get max(){return this._outputs[1]}_buildBlock(){this.min._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?mr(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?mr(t.positions,0,t.positions.length/3).maximum:null}}}),function(e){e[e.Intersect=0]="Intersect",e[e.Subtract=1]="Subtract",e[e.Union=2]="Union"}(tv||(tv={}));class Zv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.operation=tv.Intersect,this.registerInput("geometry0",Yg.Geometry),this.registerInput("geometry1",Yg.Geometry),this.registerOutput("output",Yg.Geometry)}getClassName(){return"BooleanGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{const t=this.geometry0.getConnectedValue(e),i=this.geometry1.getConnectedValue(e);if(!t||!i)return null;const s=t.positions.length/3;!t.normals&&i.normals&&(t.normals=new Array(t.positions.length)),!i.normals&&t.normals&&(i.normals=new Array(i.positions.length)),!t.uvs&&i.uvs&&(t.uvs=new Array(2*s)),!i.uvs&&t.uvs&&(i.uvs=new Array(2*s)),!t.colors&&i.colors&&(t.colors=new Array(4*s)),!i.colors&&t.colors&&(i.colors=new Array(4*s));const r=Bg.FromVertexData(t),n=Bg.FromVertexData(i);let o;switch(this.operation){case tv.Intersect:o=r.intersect(n);break;case tv.Subtract:o=r.subtract(n);break;case tv.Union:o=r.union(n)}return o.toVertexData()};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`;return e+=`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${tv[this.operation]};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation)}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Zv.prototype,"evaluateContext",void 0),ae([Lo("Operation",bo.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:tv.Intersect},{label:"Subtract",value:tv.Subtract},{label:"Union",value:tv.Union}]})],Zv.prototype,"operation",void 0),u("BABYLON.BooleanGeometryBlock",Zv),u("BABYLON.GeometryArcTan2Block",class extends mv{constructor(e){super(e),this.registerInput("x",Yg.AutoDetect),this.registerInput("y",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.x.isConnected||!this.y.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.atan2(e,t);this.output._storedFunction=t=>{const i=this.x.getConnectedValue(t),s=this.y.getConnectedValue(t);switch(this.x.type){case Yg.Int:case Yg.Float:return e(i,s);case Yg.Vector2:return new N(e(i.x,s.x),e(i.y,s.y));case Yg.Vector3:return new w(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case Yg.Vector4:return new F(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0}}}),u("BABYLON.GeometryLerpBlock",class extends mv{constructor(e){super(e),this.registerInput("left",Yg.AutoDetect),this.registerInput("right",Yg.AutoDetect),this.registerInput("gradient",Yg.Float),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case Yg.Int:case Yg.Float:return e(r,i,s);case Yg.Vector2:return new N(e(r,i.x,s.x),e(r,i.y,s.y));case Yg.Vector3:return new w(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));case Yg.Vector4:return new F(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w))}return 0},this}}),u("BABYLON.GeometryNLerpBlock",class extends mv{constructor(e){super(e),this.registerInput("left",Yg.AutoDetect),this.registerInput("right",Yg.AutoDetect),this.registerInput("gradient",Yg.Float),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryNLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case Yg.Int:case Yg.Float:return e(r,i,s);case Yg.Vector2:{const t=new N(e(r,i.x,s.x),e(r,i.y,s.y));return t.normalize(),t}case Yg.Vector3:{const t=new w(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));return t.normalize(),t}case Yg.Vector4:{const t=new F(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w));return t.normalize(),t}}return 0},this}}),u("BABYLON.GeometryStepBlock",class extends mv{constructor(e){super(e),this.registerInput("value",Yg.AutoDetect),this.registerInput("edge",Yg.Float),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryStepBlock"}get value(){return this._inputs[0]}get edge(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e{const i=this.value.getConnectedValue(t),s=this.edge.getConnectedValue(t);switch(this.value.type){case Yg.Int:case Yg.Float:return e(i,s);case Yg.Vector2:return new N(e(i.x,s),e(i.y,s));case Yg.Vector3:return new w(e(i.x,s),e(i.y,s),e(i.z,s));case Yg.Vector4:return new F(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}}),u("BABYLON.GeometrySmoothStepBlock",class extends mv{constructor(e){super(e),this.registerInput("value",Yg.AutoDetect),this.registerInput("edge0",Yg.Float),this.registerInput("edge1",Yg.Float),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometrySmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge0.isConnected||!this.edge1.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>{const s=Math.max(0,Math.min((e-t)/(i-t),1));return s*s*(3-2*s)};return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.edge0.getConnectedValue(t),r=this.edge1.getConnectedValue(t);switch(this.value.type){case Yg.Int:case Yg.Float:return e(i,s,r);case Yg.Vector2:return new N(e(i.x,s,r),e(i.y,s,r));case Yg.Vector3:return new w(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r));case Yg.Vector4:return new F(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r),e(i.w,s,r))}return 0},this}}),u("BABYLON.GeometryModBlock",class extends mv{constructor(e){super(e),this.registerInput("left",Yg.AutoDetect),this.registerInput("right",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e-Math.floor(e/t)*t;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t);switch(this.left.type){case Yg.Int:case Yg.Float:return e(i,s);case Yg.Vector2:return new N(e(i.x,s.x),e(i.y,s.y));case Yg.Vector3:return new w(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case Yg.Vector4:return new F(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0},this}}),u("BABYLON.GeometryPowBlock",class extends mv{constructor(e){super(e),this.registerInput("value",Yg.AutoDetect),this.registerInput("power",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryPowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.power.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.pow(e,t);return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.power.getConnectedValue(t);switch(this.value.type){case Yg.Int:case Yg.Float:return e(i,s);case Yg.Vector2:return new N(e(i.x,s),e(i.y,s));case Yg.Vector3:return new w(e(i.x,s),e(i.y,s),e(i.z,s));case Yg.Vector4:return new F(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}});class Jv extends mv{constructor(e){super(e),this.minimum=0,this.maximum=1,this.registerInput("value",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=e=>Math.max(this.minimum,Math.min(e,this.maximum));return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t);switch(this.value.type){case Yg.Int:case Yg.Float:return e(i);case Yg.Vector2:return new N(e(i.x),e(i.y));case Yg.Vector3:return new w(e(i.x),e(i.y),e(i.z));case Yg.Vector4:return new F(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e){super._deserialize(e),this.minimum=e.minimum,this.maximum=e.maximum}}ae([Lo("Minimum",bo.Float)],Jv.prototype,"minimum",void 0),ae([Lo("Maximum",bo.Float)],Jv.prototype,"maximum",void 0),u("BABYLON.GeometryClampBlock",Jv),u("BABYLON.GeometryCrossBlock",class extends mv{constructor(e){super(e),this.registerInput("left",Yg.AutoDetect),this.registerInput("right",Yg.AutoDetect),this.registerOutput("output",Yg.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Int),this._inputs[0].excludedConnectionPointTypes.push(Yg.Float),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Vector2),this._inputs[1].excludedConnectionPointTypes.push(Yg.Int),this._inputs[1].excludedConnectionPointTypes.push(Yg.Float),this._inputs[1].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Yg.Vector2)}getClassName(){return"GeometryCrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);switch(this.left.type){case Yg.Vector3:return w.Cross(t,i);case Yg.Vector4:return w.Cross(t.toVector3(),i.toVector3())}return 0},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(iv||(iv={}));class ex extends mv{constructor(e){super(e),this.type=iv.EaseInOutSine,this.registerInput("input",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Int)}getClassName(){return"GeometryCurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);let e;switch(this.type){case iv.EaseInSine:e=e=>1-Math.cos(3.1415*e/2);break;case iv.EaseOutSine:e=e=>Math.sin(3.1415*e/2);break;case iv.EaseInOutSine:e=e=>-(Math.cos(3.1415*e)-1)/2;break;case iv.EaseInQuad:e=e=>e*e;break;case iv.EaseOutQuad:e=e=>(1-e)*(1-e);break;case iv.EaseInOutQuad:e=e=>e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;break;case iv.EaseInCubic:e=e=>e*e*e;break;case iv.EaseOutCubic:e=e=>1-Math.pow(1-e,3);break;case iv.EaseInOutCubic:e=e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;break;case iv.EaseInQuart:e=e=>e*e*e*e;break;case iv.EaseOutQuart:e=e=>1-Math.pow(1-e,4);break;case iv.EaseInOutQuart:e=e=>e<.5?8*e*e*e*e:1-Math.pow(-2*e+2,4)/2;break;case iv.EaseInQuint:e=e=>e*e*e*e*e;break;case iv.EaseOutQuint:e=e=>1-Math.pow(1-e,5);break;case iv.EaseInOutQuint:e=e=>e<.5?16*e*e*e*e*e:1-Math.pow(-2*e+2,5)/2;break;case iv.EaseInExpo:e=e=>0===e?0:Math.pow(2,10*e-10);break;case iv.EaseOutExpo:e=e=>1===e?1:1-Math.pow(2,-10*e);break;case iv.EaseInOutExpo:e=e=>0===e?0:1===e?1:e<.5?Math.pow(2,20*e-10)/2:(2-Math.pow(2,-20*e+10))/2;break;case iv.EaseInCirc:e=e=>1-Math.sqrt(1-Math.pow(e,2));break;case iv.EaseOutCirc:e=e=>Math.sqrt(1-Math.pow(e-1,2));break;case iv.EaseInOutCirc:e=e=>e<.5?(1-Math.sqrt(1-Math.pow(2*e,2)))/2:(Math.sqrt(1-Math.pow(-2*e+2,2))+1)/2;break;case iv.EaseInBack:e=e=>2.70158*e*e*e-1.70158*e*e;break;case iv.EaseOutBack:e=e=>2.70158*Math.pow(e-1,3)+1.70158*Math.pow(e-1,2);break;case iv.EaseInOutBack:e=e=>e<.5?Math.pow(2*e,2)*(7.189819*e-2.5949095)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+3.5949095)+2)/2;break;case iv.EaseInElastic:e=e=>0===e?0:1===e?1:-Math.pow(2,10*e-10)*Math.sin(6.283/3*(10*e-10.75));break;case iv.EaseOutElastic:e=e=>0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(6.283/3*(10*e-.75))+1;break;case iv.EaseInOutElastic:e=e=>0===e?0:1==e?1:e<.5?-Math.pow(2,20*e-10)*Math.sin(6.283/4.5*(20*e-11.125))/2:Math.pow(2,-20*e+10)*Math.sin(6.283/4.5*(20*e-11.125))/2+1}return this.output._storedFunction=t=>{const i=this.input.getConnectedValue(t);switch(this.input.type){case Yg.Float:return e(i);case Yg.Vector2:return new N(e(i.x),e(i.y));case Yg.Vector3:return new w(e(i.x),e(i.y),e(i.z));case Yg.Vector4:return new F(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e){super._deserialize(e),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.GeometryCurveBlockTypes.${iv[this.type]};\n`}}ae([Lo("Type",bo.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"EaseInSine",value:iv.EaseInSine},{label:"EaseOutSine",value:iv.EaseOutSine},{label:"EaseInOutSine",value:iv.EaseInOutSine},{label:"EaseInQuad",value:iv.EaseInQuad},{label:"EaseOutQuad",value:iv.EaseOutQuad},{label:"EaseInOutQuad",value:iv.EaseInOutQuad},{label:"EaseInCubic",value:iv.EaseInCubic},{label:"EaseOutCubic",value:iv.EaseOutCubic},{label:"EaseInOutCubic",value:iv.EaseInOutCubic},{label:"EaseInQuart",value:iv.EaseInQuart},{label:"EaseOutQuart",value:iv.EaseOutQuart},{label:"EaseInOutQuart",value:iv.EaseInOutQuart},{label:"EaseInQuint",value:iv.EaseInQuint},{label:"EaseOutQuint",value:iv.EaseOutQuint},{label:"EaseInOutQuint",value:iv.EaseInOutQuint},{label:"EaseInExpo",value:iv.EaseInExpo},{label:"EaseOutExpo",value:iv.EaseOutExpo},{label:"EaseInOutExpo",value:iv.EaseInOutExpo},{label:"EaseInCirc",value:iv.EaseInCirc},{label:"EaseOutCirc",value:iv.EaseOutCirc},{label:"EaseInOutCirc",value:iv.EaseInOutCirc},{label:"EaseInBack",value:iv.EaseInBack},{label:"EaseOutBack",value:iv.EaseOutBack},{label:"EaseInOutBack",value:iv.EaseInOutBack},{label:"EaseInElastic",value:iv.EaseInElastic},{label:"EaseOutElastic",value:iv.EaseOutElastic},{label:"EaseInOutElastic",value:iv.EaseInOutElastic}]})],ex.prototype,"type",void 0),u("BABYLON.GeometryCurveBlock",ex),u("BABYLON.GeometryDesaturateBlock",class extends mv{constructor(e){super(e),this.registerInput("color",Yg.Vector3),this.registerInput("level",Yg.Float,!0,0),this.registerOutput("output",Yg.Vector3)}getClassName(){return"GeometryDesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.color.isConnected?(this.output._storedFunction=e=>{const t=this.color.getConnectedValue(e),i=this.level.getConnectedValue(e),s=.5*(Math.min(t.x,t.y,t.z)+Math.max(t.x,t.y,t.z));return new w(t.x*(1-i)+s*i,t.y*(1-i)+s*i,t.z*(1-i)+s*i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}),u("BABYLON.GeometryPosterizeBlock",class extends mv{constructor(e){super(e),this.registerInput("value",Yg.AutoDetect),this.registerInput("steps",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(Yg.Float)}getClassName(){return"GeometryPosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected&&this.steps.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.steps.getConnectedValue(e);let s=i;if(this.steps.type===Yg.Float)switch(this.value.type){case Yg.Vector2:s=new N(i,i);break;case Yg.Vector3:s=new w(i,i,i);break;case Yg.Vector4:s=new F(i,i,i,i)}switch(this.value.type){case Yg.Vector2:return new N(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y));case Yg.Vector3:return new w(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z));case Yg.Vector4:return new F(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z),t.w/(1/s.w)*(1/s.w));default:return Math.floor(t/(1/i)*(1/i))}},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}),u("BABYLON.GeometryReplaceColorBlock",class extends mv{constructor(e){super(e),this.registerInput("value",Yg.AutoDetect),this.registerInput("reference",Yg.AutoDetect),this.registerInput("distance",Yg.Float),this.registerInput("replacement",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(Yg.Float),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Yg.Float),this._inputs[1].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[3].excludedConnectionPointTypes.push(Yg.Float),this._inputs[3].excludedConnectionPointTypes.push(Yg.Matrix)}getClassName(){return"GeometryReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected&&this.reference.isConnected&&this.distance.isConnected&&this.replacement.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.reference.getConnectedValue(e),s=this.distance.getConnectedValue(e),r=this.replacement.getConnectedValue(e);return t.subtract(i).length(){const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.subtract(i).length()},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}),u("BABYLON.GeometryDotBlock",class extends mv{constructor(e){super(e),this.registerInput("left",Yg.AutoDetect),this.registerInput("right",Yg.AutoDetect),this.registerOutput("output",Yg.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Int),this._inputs[0].excludedConnectionPointTypes.push(Yg.Float),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Yg.Float),this._inputs[1].excludedConnectionPointTypes.push(Yg.Matrix)}getClassName(){return"GeometryDotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.dot(i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}),u("BABYLON.GeometryLengthBlock",class extends mv{constructor(e){super(e),this.registerInput("value",Yg.AutoDetect),this.registerOutput("output",Yg.Float),this._inputs[0].excludedConnectionPointTypes.push(Yg.Int),this._inputs[0].excludedConnectionPointTypes.push(Yg.Float),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix)}getClassName(){return"GeometryLengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected?(this.output._storedFunction=e=>this.value.getConnectedValue(e).length(),this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}),u("BABYLON.GeometryRotate2dBlock",class extends mv{constructor(e){super(e),this.registerInput("input",Yg.Vector2),this.registerInput("angle",Yg.Float),this.registerOutput("output",Yg.Vector2)}getClassName(){return"GeometryRotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.angle.isConnected&&this.input.isConnected?(this.output._storedFunction=e=>{const t=this.input.getConnectedValue(e),i=this.angle.getConnectedValue(e);return new N(Math.cos(i)*t.x-Math.sin(i)*t.y,Math.sin(i)*t.x+Math.cos(i)*t.y)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}});class tx extends Un{get covariancesATexture(){return this._covariancesATexture}get covariancesBTexture(){return this._covariancesBTexture}get centersTexture(){return this._centersTexture}get colorsTexture(){return this._colorsTexture}constructor(e,t=null,i=null){super(e,i),this._vertexCount=0,this._worker=null,this._frameIdLastUpdate=-1,this._modelViewMatrix=B.Identity(),this._material=null,this._canPostToWorker=!0,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null;const s=new Tr;s.positions=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],s.indices=[0,1,2,0,2,3],s.applyToMesh(this),this.subMeshes=[],new vr(0,0,4,0,6,this),this.doNotSyncBoundingInfo=!0,this.setEnabled(!1),this._lastProj=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t&&this.loadFileAsync(t)}getClassName(){return"GaussianSplattingMesh"}getTotalVertices(){return this._vertexCount}render(e,t,i){this.material||(this._material=new Cg(this.name+"_material",this._scene),this.material=this._material);const s=this.getScene().getFrameId();if(s!==this._frameIdLastUpdate&&this._worker&&this._scene.activeCamera&&this._canPostToWorker){this.getWorldMatrix().multiplyToRef(this._scene.activeCamera.getViewMatrix(),this._modelViewMatrix);const e=this._lastProj[2]*this._modelViewMatrix.m[2]+this._lastProj[6]*this._modelViewMatrix.m[6]+this._lastProj[10]*this._modelViewMatrix.m[10];Math.abs(e-1)>=.01&&(this._frameIdLastUpdate=s,this._canPostToWorker=!1,this._lastProj=this._modelViewMatrix.m.slice(0),this._worker.postMessage({view:this._modelViewMatrix.m,depthMix:this._depthMix,useRightHandedSystem:this._scene.useRightHandedSystem},[this._depthMix.buffer]))}return super.render(e,t,i)}static ConvertPLYToSplat(e){const t=new Uint8Array(e),i=(new TextDecoder).decode(t.slice(0,10240)),s=i.indexOf("end_header\n");if(s<0||!i)return e;const r=parseInt(/element vertex (\d+)\n/.exec(i)[1]);let n=0;const o={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1},a=[],l=i.slice(0,s).split("\n").filter((e=>e.startsWith("property ")));for(const e of l){const[,t,i]=e.split(" ");if(a.push({name:i,type:t,offset:n}),!o[t])return J.Error(`Unsupported property type: ${t}. Are you sure it's a valid Gaussian Splatting file?`),new ArrayBuffer(0);n+=o[t]}const h=.28209479177387814,c=new DataView(e,s+11),u=new ArrayBuffer(32*r),d=new L;for(let e=0;e{this._loadData(tx.ConvertPLYToSplat(e))}))}dispose(e){this._covariancesATexture?.dispose(),this._covariancesBTexture?.dispose(),this._centersTexture?.dispose(),this._colorsTexture?.dispose(),this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._material?.dispose(!1,!0),this._material=null,this._worker?.terminate(),this._worker=null,super.dispose(e)}_loadData(e){if(!e.byteLength)return;const t=new Uint8Array(e),i=new Float32Array(t.buffer),s=t.length/32;this._vertexCount=s;const r=this._getTextureSize(s),n=r.x*r.y,o=new Float32Array(3*n),a=new Float32Array(3*n),l=new Float32Array(3*n),h=U.Matrix[0],c=U.Matrix[1],u=U.Quaternion[0],d=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),p=new w(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let e=0;enew io(e,t,i,s,this._scene,!1,!1,2,1),g=e=>{const t=e.length/3,i=new Float32Array(4*t);for(let s=0;s{this._depthMix=e.data.depthMix;const t=new Uint32Array(e.data.depthMix.buffer);for(let e=0;ei&&(J.Error("GaussianSplatting texture size: ("+i+", "+s+"), maxTextureSize: "+i),s=i),new N(i,s)}}tx._CreateWorker=function(e){let t,i,s,r,n=0;e.onmessage=o=>{if(o.data.positions)t=o.data.positions,n=o.data.vertexCount;else{const a=o.data.view;if(!t||!a)throw new Error("positions or view is not defined!");i=o.data.depthMix,s=new Uint32Array(i.buffer),r=new Float32Array(i.buffer);for(let e=0;enew ix(e,t,i);class ix{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=ix._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,ix.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,Ii.SetImmediate((()=>{t(!0)}))):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){const t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){const e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`};let s=!1,r=i();const n=new Ne;navigator.onLine&&(s=!0,r=r+(null==r.match(/\?/)?"?":"&")+Date.now()),n.open("GET",r),n.addEventListener("load",(()=>{if(200===n.status||ix._ValidateXHRData(n,1))try{const t=JSON.parse(n.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&ix._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){t()}else t()}),!1),n.addEventListener("error",(()=>{if(s){s=!1;const e=i();n.open("GET",e),n.send()}else t()}),!1);try{n.send()}catch(t){J.Error("Error on XHR send request."),e(!1)}}open(e,t){const i=()=>{this._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline))if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;const t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{i()},t.onblocked=()=>{J.Error("IDB request blocked. Please reload the page."),i()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){J.Error("Error while creating object stores. Exception: "+e.message),i()}}}else this._isSupported=!1,t&&t()}loadImage(e,t){const i=ix._ReturnFullUrlLocation(e),s=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?s():this._loadImageFromDBAsync(i,t,s)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let s;const r=this._db.transaction(["textures"]);r.onabort=()=>{t.src=e},r.oncomplete=()=>{let r;s&&"function"==typeof URL?(r=URL.createObjectURL(s.data),t.onerror=()=>{J.Error("Error loading image from blob URL: "+r+" switching back to web url: "+e),t.src=e},t.src=r):i()};const n=r.objectStore("textures").get(e);n.onsuccess=e=>{s=e.target.result},n.onerror=()=>{J.Error("Error loading texture "+e+" from DB."),t.src=e}}else J.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){const s=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(ix._IsUASupportingBlobStorage){const r=new Ne;r.open("GET",e),r.responseType="blob",r.addEventListener("load",(()=>{if(200===r.status&&this._db){i=r.response;const n=this._db.transaction(["textures"],"readwrite");n.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}s()},n.oncomplete=()=>{s()};const o={textureUrl:e,data:i};try{const e=n.objectStore("textures").put(o);e.onsuccess=()=>{},e.onerror=()=>{s()}}catch(i){25===i.code&&(ix._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e}),!1),r.addEventListener("error",(()=>{J.Error("Error in XHR request in BABYLON.Database."),t.src=e}),!1),r.send()}else t.src=e}else J.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,(()=>{this._saveVersionIntoDBAsync(e,t)}))}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let s;try{const r=this._db.transaction(["versions"]);r.oncomplete=()=>{s?this._manifestVersionFound!==s.data?(this._mustUpdateRessources=!0,i()):t(s.data):(this._mustUpdateRessources=!0,i())},r.onabort=()=>{t(-1)};const n=r.objectStore("versions").get(e);n.onsuccess=e=>{s=e.target.result},n.onerror=()=>{J.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){J.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else J.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)}_saveVersionIntoDBAsync(e,t){if(this._isSupported&&!this._hasReachedQuota&&this._db)try{const i=this._db.transaction(["versions"],"readwrite");i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const s={sceneUrl:e,data:this._manifestVersionFound},r=i.objectStore("versions").put(s);r.onsuccess=()=>{},r.onerror=()=>{J.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){J.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,s,r){const n=ix._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(n,t,i,r,s)};this._checkVersionFromDB(n,(e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(n,t,i,r,s):this._loadFileAsync(n,t,o):s&&s()}))}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let s,r;s=-1!==e.indexOf(".babylon")?"scenes":"textures";const n=this._db.transaction([s]);n.oncomplete=()=>{r?t(r.data):i()},n.onabort=()=>{i()};const o=n.objectStore(s).get(e);o.onsuccess=e=>{r=e.target.result},o.onerror=()=>{J.Error("Error loading file "+e+" from DB."),i()}}else J.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,s,r){if(this._isSupported){let n;n=-1!==e.indexOf(".babylon")?"scenes":"textures";const o=new Ne;let a;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),s&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",(()=>{if(200===o.status||o.status<400&&ix._ValidateXHRData(o,s?6:1))if(a=s?o.response:o.responseText,!this._hasReachedQuota&&this._db){const i=this._db.transaction([n],"readwrite");let s;i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(a)},i.oncomplete=()=>{t(a)},s="scenes"===n?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{const e=i.objectStore(n).put(s);e.onsuccess=()=>{},e.onerror=()=>{J.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(a)}}else t(a);else o.status>=400&&r?r(o):t()}),!1),o.addEventListener("error",(()=>{J.Error("error on XHR request."),r&&r()}),!1),o.send()}else J.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),r&&r()}static _ValidateXHRData(e,t=7){try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){const i=pm(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){const t=new Uint8Array(e.response,0,3);return 68===t[0]&&68===t[1]&&83===t[2]}}catch(e){}return!1}}ix._IsUASupportingBlobStorage=!0,ix.IDBStorageEnabled=!1,ix._ParseURL=e=>{document.createElement("a").href=e;const t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},ix._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?ix._ParseURL(window.location.href)+e:e;class sx{constructor(){this.direction1=new w(0,1,0),this.direction2=new w(0,1,0),this.minEmitBox=new w(-.5,-.5,-.5),this.maxEmitBox=new w(.5,.5,.5)}startDirectionFunction(e,t,i,s){const r=R(this.direction1.x,this.direction2.x),n=R(this.direction1.y,this.direction2.y),o=R(this.direction1.z,this.direction2.z);if(s)return t.x=r,t.y=n,void(t.z=o);w.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){const r=R(this.minEmitBox.x,this.maxEmitBox.x),n=R(this.minEmitBox.y,this.maxEmitBox.y),o=R(this.minEmitBox.z,this.maxEmitBox.z);if(s)return t.x=r,t.y=n,void(t.z=o);w.TransformCoordinatesFromFloatsToRef(r,n,o,e,t)}clone(){const e=new sx;return se.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){w.FromArrayToRef(e.direction1,0,this.direction1),w.FromArrayToRef(e.direction2,0,this.direction2),w.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),w.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class rx{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,s){s?U.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),U.Vector3[0]).normalize();const r=G.RandomRange(0,this.directionRandomizer),n=G.RandomRange(0,this.directionRandomizer),o=G.RandomRange(0,this.directionRandomizer);t.x=U.Vector3[0].x+r,t.y=U.Vector3[0].y+n,t.z=U.Vector3[0].z+o,t.normalize()}startPositionFunction(e,t,i,s){const r=G.RandomRange(0,2*Math.PI);let n;this.emitFromSpawnPointOnly?n=1e-4:(n=G.RandomRange(0,this.heightRange),n=1-n*n);let o=this._radius-G.RandomRange(0,this._radius*this.radiusRange);o*=n;const a=o*Math.sin(r),l=o*Math.cos(r),h=n*this._height;if(s)return t.x=a,t.y=h,void(t.z=l);w.TransformCoordinatesFromFloatsToRef(a,h,l,e,t)}clone(){const e=new rx(this._radius,this._angle,this.directionRandomizer);return se.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e}getClassName(){return"ConeParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}}class nx{constructor(e=1,t=1,i=1,s=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=s,this._tempVector=w.Zero()}startDirectionFunction(e,t,i,s,r){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),w.TransformNormalToRef(this._tempVector,r,this._tempVector);const n=G.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let o=Math.atan2(this._tempVector.x,this._tempVector.z);o+=G.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=n,this._tempVector.x=Math.sin(o),this._tempVector.z=Math.cos(o),this._tempVector.normalize(),s?t.copyFrom(this._tempVector):w.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,s){const r=G.RandomRange(-this.height/2,this.height/2),n=G.RandomRange(0,2*Math.PI),o=G.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),a=Math.sqrt(o)*this.radius,l=a*Math.cos(n),h=a*Math.sin(n);s?t.copyFromFloats(l,r,h):w.TransformCoordinatesFromFloatsToRef(l,r,h,e,t)}clone(){const e=new nx(this.radius,this.directionRandomizer);return se.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class ox extends nx{constructor(e=1,t=1,i=1,s=new w(0,1,0),r=new w(0,1,0)){super(e,t,i),this.direction1=s,this.direction2=r}startDirectionFunction(e,t,i,s){const r=G.RandomRange(this.direction1.x,this.direction2.x),n=G.RandomRange(this.direction1.y,this.direction2.y),o=G.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):w.TransformNormalFromFloatsToRef(r,n,o,e,t)}clone(){const e=new ox(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return se.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),w.FromArrayToRef(e.direction1,0,this.direction1),w.FromArrayToRef(e.direction2,0,this.direction2)}}class ax{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=G.RandomRange(0,this.directionRandomizer),o=G.RandomRange(0,this.directionRandomizer),a=G.RandomRange(0,this.directionRandomizer);r.x+=n,r.y+=o,r.z+=a,r.normalize(),s?t.copyFrom(r):w.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-G.RandomRange(0,this.radius*this.radiusRange),n=G.RandomRange(0,1),o=G.RandomRange(0,2*Math.PI),a=Math.acos(2*n-1),l=r*Math.cos(o)*Math.sin(a),h=r*Math.cos(a),c=r*Math.sin(o)*Math.sin(a);s?t.copyFromFloats(l,Math.abs(h),c):w.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),c,e,t)}clone(){const e=new ax(this.radius,this.directionRandomizer);return se.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class lx{constructor(){this.direction1=new w(0,1,0),this.direction2=new w(0,1,0)}startDirectionFunction(e,t,i,s){const r=G.RandomRange(this.direction1.x,this.direction2.x),n=G.RandomRange(this.direction1.y,this.direction2.y),o=G.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):w.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){s?t.copyFromFloats(0,0,0):w.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new lx;return se.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){w.FromArrayToRef(e.direction1,0,this.direction1),w.FromArrayToRef(e.direction2,0,this.direction2)}}class hx{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=G.RandomRange(0,this.directionRandomizer),o=G.RandomRange(0,this.directionRandomizer),a=G.RandomRange(0,this.directionRandomizer);r.x+=n,r.y+=o,r.z+=a,r.normalize(),s?t.copyFrom(r):w.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-G.RandomRange(0,this.radius*this.radiusRange),n=G.RandomRange(0,1),o=G.RandomRange(0,2*Math.PI),a=Math.acos(2*n-1),l=r*Math.cos(o)*Math.sin(a),h=r*Math.cos(a),c=r*Math.sin(o)*Math.sin(a);s?t.copyFromFloats(l,h,c):w.TransformCoordinatesFromFloatsToRef(l,h,c,e,t)}clone(){const e=new hx(this.radius,this.directionRandomizer);return se.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class cx extends hx{constructor(e=1,t=new w(0,1,0),i=new w(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=G.RandomRange(this.direction1.x,this.direction2.x),s=G.RandomRange(this.direction1.y,this.direction2.y),r=G.RandomRange(this.direction1.z,this.direction2.z);w.TransformNormalFromFloatsToRef(i,s,r,e,t)}clone(){const e=new cx(this.radius,this.direction1,this.direction2);return se.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class ux{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,s){const r=U.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,r);const e=U.Vector3[1];r.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,r)}else r.set(0,0,0);s?t.copyFrom(r):w.TransformNormalToRef(r,e,t)}startPositionFunction(e,t,i,s){const r=U.Vector3[0];this.particlePositionGenerator?this.particlePositionGenerator(-1,i,r):r.set(0,0,0),s?t.copyFrom(r):w.TransformCoordinatesToRef(r,e,t)}clone(){const e=new ux;return se.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.particlePositionGenerator=this.particlePositionGenerator,e.particleDestinationGenerator=this.particleDestinationGenerator,e}parse(e){e.particlePositionGenerator&&(this.particlePositionGenerator=e.particlePositionGenerator),e.particleDestinationGenerator&&(this.particleDestinationGenerator=e.particleDestinationGenerator)}}class dx{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(Ki.PositionKind),this._normals=e.getVerticesData(Ki.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=w.Zero(),this._mesh=null,this.direction1=new w(0,1,0),this.direction2=new w(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,s){if(this.useMeshNormalsForDirection&&this._normals)return void w.TransformNormalToRef(this._storedNormal,e,t);const r=G.RandomRange(this.direction1.x,this.direction2.x),n=G.RandomRange(this.direction1.y,this.direction2.y),o=G.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):w.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){if(!this._indices||!this._positions)return;const r=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),o=Math.random()*(1-n),a=1-n-o,l=this._indices[r],h=this._indices[r+1],c=this._indices[r+2],u=U.Vector3[0],d=U.Vector3[1],p=U.Vector3[2],f=U.Vector3[3];w.FromArrayToRef(this._positions,3*l,u),w.FromArrayToRef(this._positions,3*h,d),w.FromArrayToRef(this._positions,3*c,p),f.x=n*u.x+o*d.x+a*p.x,f.y=n*u.y+o*d.y+a*p.y,f.z=n*u.z+o*d.z+a*p.z,s?t.copyFromFloats(f.x,f.y,f.z):w.TransformCoordinatesFromFloatsToRef(f.x,f.y,f.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(w.FromArrayToRef(this._normals,3*l,u),w.FromArrayToRef(this._normals,3*h,d),w.FromArrayToRef(this._normals,3*c,p),this._storedNormal.x=n*u.x+o*d.x+a*p.x,this._storedNormal.y=n*u.y+o*d.y+a*p.y,this._storedNormal.z=n*u.z+o*d.z+a*p.z)}clone(){const e=new dx(this.mesh);return se.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.meshId=this.mesh?.id,e.useMeshNormalsForDirection=this.useMeshNormalsForDirection,e}parse(e,t){w.FromArrayToRef(e.direction1,0,this.direction1),w.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class px{_isUbo(e){return void 0!==e.addUniform}constructor(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}}Ft.ShadersStore.gpuUpdateParticlesPixelShader="#version 300 es\nvoid main() {discard;}\n";Ft.ShadersStore.gpuUpdateParticlesVertexShader="#version 300 es\n#define PI 3.14159\nuniform float currentCount;uniform float timeDelta;uniform float stopFactor;\n#ifndef LOCAL\nuniform mat4 emitterWM;\n#endif\nuniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;uniform vec4 color2;\n#endif\nuniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;uniform float radiusRange;uniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;uniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;uniform float height;uniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer;\n#endif\nin vec3 position;\n#ifdef CUSTOMEMITTER\nin vec3 initialPosition;\n#endif\nin float age;in float life;in vec4 seed;in vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;in vec3 noiseCoordinates2;\n#endif\nout vec3 outPosition;\n#ifdef CUSTOMEMITTER\nout vec3 outInitialPosition;\n#endif\nout float outAge;out float outLife;out vec4 outSeed;out vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;uniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec4 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;}\nvec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));}\nvoid main() {float newAge=age+timeDelta; \nif (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed;\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(direction1+(direction2-direction1)*randoms3);\n#else\nnewDirection=normalize(newPosition+directionRandomizer*randoms3);\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\nangle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.0001;\n#else\nfloat h=randoms2.y*height.y;h=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); \nif (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); }\n#elif defined(CUSTOMEMITTER)\nnewPosition=initialPosition;outInitialPosition=initialPosition;\n#else \nnewPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\n#ifdef LOCAL\noutPosition=newPosition;\n#else\noutPosition=(emitterWM*vec4(newPosition,1.)).xyz;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#ifndef BILLBOARD \noutInitialDirection=direction;\n#endif\n#else\n#ifdef LOCAL\nvec3 initial=newDirection;\n#else \nvec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;\n#endif\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#if defined(CUSTOMEMITTER)\noutPosition=position+(direction-position)*ageGradient; \noutInitialPosition=initialPosition;\n#else\noutPosition=position+direction*directionScale;\n#endif\noutLife=life;outSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#else\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;float dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset;\n#else\nfloat cellStartOffset=0.;\n#endif \nfloat ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);}\nelse {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);}\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}}",u("BABYLON.WebGL2ParticleSystem",class{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){return this._updateEffect?.isReady()??!1}createUpdateBuffer(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof ux&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new $t("gpuUpdateParticles",this._updateEffectOptions,this._engine),new px(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){const e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);const s=this._engine;s.bindTransformFeedbackBuffer(t.getBuffer()),s.setRasterizerState(!1),s.beginTransformFeedback(!0),s.drawArraysType(3,0,i),s.endTransformFeedback(),s.setRasterizerState(!0),s.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;ee)return void i(t[0],t[0],1);for(let s=0;s=r.gradient&&e<=n.gradient)return void i(r,n,(e-r.gradient)/(n.gradient-r.gradient))}const s=t.length-1;i(t[s],t[s],1)}}class vx{constructor(e){this.particleSystem=e,this.position=w.Zero(),this.direction=w.Zero(),this.color=new j(0,0,0,0),this.colorStep=new j(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new N(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new j(0,0,0,0),this._currentColor2=new j(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=vx._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===t?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);const i=this._initialEndSpriteCellID-this._initialStartSpriteCellID+1;let s;s=this._initialSpriteCellLoop?P(e*t%this.lifeTime/this.lifeTime):P(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+s*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const e=U.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,U.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(U.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach((e=>{this._inheritParticleInfoToSubEmitter(e)}))}_reset(){this.age=0,this.id=vx._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new F(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}}vx._Count=0;Ft.ShadersStore.particlesPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler;\n#include\n#include\n#include\n#include\n#include\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;uniform sampler2D rampSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n#include\n#include(color,baseColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.particlesVertexShader="attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos; \n#endif\nvarying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#include\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvec3 row1=direction;\n#else\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nmat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size;\n#ifdef BILLBOARD\nvec3 rotatedCorner;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\ngl_Position=projection*vec4(viewPos,1.0);\n#else\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0);\n#endif\nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";class xx extends ia{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new gr(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new g),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,s=null,r=!1,n=.01){super(e),this._emitterInverseWorldMatrix=B.Identity(),this._inheritedVelocityOffset=new w,this.onDisposeObservable=new g,this.onStoppedObservable=new g,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new j(0,0,0,0),this._colorDiff=new j(0,0,0,0),this._scaledDirection=w.Zero(),this._scaledGravity=w.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this._emitFromParticle=e=>{},this.recycleParticle=e=>{const t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;return 0!==this._stockParticles.length?(e=this._stockParticles.pop(),e._reset()):e=new vx(this),this._prepareParticle(e),e},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=r,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=B.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||y.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new gr(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new sx;let o=null;this.updateFunction=e=>{let t=null;this.noiseTexture&&(t=this.noiseTexture.getSize(),this.noiseTexture.getContent()?.then((e=>{o=e})));const i=e===this._particles;for(let s=0;sr.lifeTime){const e=r.age-a;n=(r.lifeTime-a)*n/e,r.age=r.lifeTime}const l=r.age/r.lifeTime;this._colorGradients&&this._colorGradients.length>0?gx.GetCurrentGradient(l,this._colorGradients,((e,t,i)=>{e!==r._currentColorGradient&&(r._currentColor1.copyFrom(r._currentColor2),t.getColorToRef(r._currentColor2),r._currentColorGradient=e),j.LerpToRef(r._currentColor1,r._currentColor2,i,r.color)})):(r.colorStep.scaleToRef(n,this._scaledColorStep),r.color.addInPlace(this._scaledColorStep),r.color.a<0&&(r.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&gx.GetCurrentGradient(l,this._angularSpeedGradients,((e,t,i)=>{e!==r._currentAngularSpeedGradient&&(r._currentAngularSpeed1=r._currentAngularSpeed2,r._currentAngularSpeed2=t.getFactor(),r._currentAngularSpeedGradient=e),r.angularSpeed=I(r._currentAngularSpeed1,r._currentAngularSpeed2,i)})),r.angle+=r.angularSpeed*n;let h=n;if(this._velocityGradients&&this._velocityGradients.length>0&&gx.GetCurrentGradient(l,this._velocityGradients,((e,t,i)=>{e!==r._currentVelocityGradient&&(r._currentVelocity1=r._currentVelocity2,r._currentVelocity2=t.getFactor(),r._currentVelocityGradient=e),h*=I(r._currentVelocity1,r._currentVelocity2,i)})),r.direction.scaleToRef(h,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&gx.GetCurrentGradient(l,this._limitVelocityGradients,((e,t,i)=>{e!==r._currentLimitVelocityGradient&&(r._currentLimitVelocity1=r._currentLimitVelocity2,r._currentLimitVelocity2=t.getFactor(),r._currentLimitVelocityGradient=e);const s=I(r._currentLimitVelocity1,r._currentLimitVelocity2,i);r.direction.length()>s&&r.direction.scaleInPlace(this.limitVelocityDamping)})),this._dragGradients&&this._dragGradients.length>0&&gx.GetCurrentGradient(l,this._dragGradients,((e,t,i)=>{e!==r._currentDragGradient&&(r._currentDrag1=r._currentDrag2,r._currentDrag2=t.getFactor(),r._currentDragGradient=e);const s=I(r._currentDrag1,r._currentDrag2,i);this._scaledDirection.scaleInPlace(1-s)})),this.isLocal&&r._localPosition?(r._localPosition.addInPlace(this._scaledDirection),w.TransformCoordinatesToRef(r._localPosition,this._emitterWorldMatrix,r.position)):r.position.addInPlace(this._scaledDirection),o&&t&&r._randomNoiseCoordinates1){const e=this._fetchR(r._randomNoiseCoordinates1.x,r._randomNoiseCoordinates1.y,t.width,t.height,o),i=this._fetchR(r._randomNoiseCoordinates1.z,r._randomNoiseCoordinates2.x,t.width,t.height,o),s=this._fetchR(r._randomNoiseCoordinates2.y,r._randomNoiseCoordinates2.z,t.width,t.height,o),a=U.Vector3[0],l=U.Vector3[1];a.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*i-1)*this.noiseStrength.y,(2*s-1)*this.noiseStrength.z),a.scaleToRef(n,l),r.direction.addInPlace(l)}this.gravity.scaleToRef(n,this._scaledGravity),r.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&gx.GetCurrentGradient(l,this._sizeGradients,((e,t,i)=>{e!==r._currentSizeGradient&&(r._currentSize1=r._currentSize2,r._currentSize2=t.getFactor(),r._currentSizeGradient=e),r.size=I(r._currentSize1,r._currentSize2,i)})),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&gx.GetCurrentGradient(l,this._colorRemapGradients,((e,t,i)=>{const s=I(e.factor1,t.factor1,i),n=I(e.factor2,t.factor2,i);r.remapData.x=s,r.remapData.y=n-s})),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&gx.GetCurrentGradient(l,this._alphaRemapGradients,((e,t,i)=>{const s=I(e.factor1,t.factor1,i),n=I(e.factor2,t.factor2,i);r.remapData.z=s,r.remapData.w=n-s}))),this._isAnimationSheetEnabled&&r.updateCellIndex(),r._inheritParticleInfoToSubEmitters(),r.age>=r.lifeTime&&(this._emitFromParticle(r),r._attachedSubEmitters&&(r._attachedSubEmitters.forEach((e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()})),r._attachedSubEmitters=null),this.recycleParticle(r),i&&s--)}}}serialize(e){throw new Error("Method not implemented.")}clone(e,t,i=!1){throw new Error("Method not implemented.")}_addFactorGradient(e,t,i,s){const r=new mx(t,i,s);e.push(r),e.sort(((e,t)=>e.gradientt.gradient?1:0))}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const s of e){if(s.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;const e=new Uint8Array(4*this._rawTextureWidth),t=$.Color3[0];for(let i=0;i{Y.LerpToRef(s.color,r.color,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255}))}this._rampGradientsTexture=io.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);const i=new _x(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);const s=new fx(e,t,i);return this._colorGradients.push(s),this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(const i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(const e of this._drawWrappers)if(e)for(const t of e)t?.dispose();this._drawWrappers=[]}_fetchR(e,t,i,s,r){return r[4*(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*s%s|0)*i)]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&8!==this.billboardMode&&9!==this.billboardMode||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);const e=this._engine,t=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*t),this._vertexBuffer=new $i(e,this._vertexData,!0,t);let i=0;const s=this._vertexBuffer.createVertexBuffer(Ki.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[Ki.PositionKind]=s,i+=3;const r=this._vertexBuffer.createVertexBuffer(Ki.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[Ki.ColorKind]=r,i+=4;const n=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=n,i+=1;const o=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,i+=2,this._isAnimationSheetEnabled){const e=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,i+=1}if(!this._isBillboardBased||8===this.billboardMode||9===this.billboardMode){const e=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,i+=3}if(this._useRampGradients){const e=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,i+=4}let a;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new $i(e,t,!1,2),a=this._spriteBuffer.createVertexBuffer("offset",0,2)}else a=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=a,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing)return void(this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3])));const e=[],t=[];let i=0;for(let s=0;s{this.start(0)}),e);else{if(this._started=!0,this._stopped=!1,this._actualFrame=0,this._preStart(),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){-1!==this.emitter?.getClassName().indexOf("Mesh")&&this.emitter.computeWorldMatrix(!0);const e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce((()=>{setTimeout((()=>{for(let t=0;t0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,this._postStop(e))}_postStop(e){}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,s){let r=e*this._vertexBufferSize;if(this._vertexData[r++]=t.position.x+this.worldOffset.x,this._vertexData[r++]=t.position.y+this.worldOffset.y,this._vertexData[r++]=t.position.z+this.worldOffset.z,this._vertexData[r++]=t.color.r,this._vertexData[r++]=t.color.g,this._vertexData[r++]=t.color.b,this._vertexData[r++]=t.color.a,this._vertexData[r++]=t.angle,this._vertexData[r++]=t.scale.x*t.size,this._vertexData[r++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[r++]=t.cellIndex),this._isBillboardBased)8!==this.billboardMode&&9!==this.billboardMode||(this._vertexData[r++]=t.direction.x,this._vertexData[r++]=t.direction.y,this._vertexData[r++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(w.TransformNormalToRef(e,this._emitterWorldMatrix,U.Vector3[0]),e=U.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[r++]=e.x,this._vertexData[r++]=e.y,this._vertexData[r++]=e.z}else{let e=t.direction;this.isLocal&&(w.TransformNormalToRef(e,this._emitterWorldMatrix,U.Vector3[0]),e=U.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[r++]=e.x,this._vertexData[r++]=e.y,this._vertexData[r++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[r++]=t.remapData.x,this._vertexData[r++]=t.remapData.y,this._vertexData[r++]=t.remapData.z,this._vertexData[r++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===s?s=this._epsilon:1===s&&(s=1-this._epsilon)),this._vertexData[r++]=i,this._vertexData[r++]=s)}_prepareParticle(e){}_update(e){if(this._alive=this._particles.length>0,this.emitter.position){const e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{const e=this.emitter;this._emitterWorldMatrix=B.Translation(e.x,e.y,e.z)}let t;this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i0){const e=P(this._actualFrame/this.targetStopDuration);gx.GetCurrentGradient(e,this._lifeTimeGradients,((i,s)=>{const r=i,n=s,o=r.getFactor(),a=n.getFactor(),l=(e-r.gradient)/(n.gradient-r.gradient);t.lifeTime=I(o,a,l)}))}else t.lifeTime=R(this.minLifeTime,this.maxLifeTime);const e=R(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),w.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=R(this.minSize,this.maxSize),t.scale.copyFromFloats(R(this.minScaleX,this.maxScaleX),R(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const e=this._actualFrame/this.targetStopDuration;gx.GetCurrentGradient(e,this._startSizeGradients,((e,i,s)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);const r=I(this._currentStartSize1,this._currentStartSize2,s);t.scale.scaleInPlace(r)}))}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=R(this.minAngularSpeed,this.maxAngularSpeed),t.angle=R(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),this._colorGradients&&0!==this._colorGradients.length)t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);else{const e=R(0,1);j.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new F(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new w(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new w(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const s=[Ki.PositionKind,Ki.ColorKind,"angle","offset","size"];return e&&s.push("cellIndex"),t||s.push("direction"),i&&s.push("remapData"),s}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["invView","view","projection","textureMask","translationPivot","eyePosition"];return jr(s),e&&s.push("particlesInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t,i=!0){if(this._scene&&($r(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&0!==this._scene.fogMode&&e.push("#define FOG")),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===ia.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case 2:e.push("#define BILLBOARDY");break;case 8:case 9:e.push("#define BILLBOARDSTRETCHED"),9===this.billboardMode&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case 7:e.push("#define BILLBOARDMODE_ALL")}i&&this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...xx._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&8!==this.billboardMode&&9!==this.billboardMode,this._useRampGradients)),e.push(...xx._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(Fi(e,this._imageProcessingConfigurationDefines),Li(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);const s=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let r=this._drawWrappers[s];r||(r=this._drawWrappers[s]=[]);let n=r[e];n||(n=new gr(this._engine),n.drawContext&&(n.drawContext.useInstancing=this._useInstancing),r[e]=n);const o=i.join("\n");if(n.defines!==o){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("particles",e,t,i,o),o)}return n}animate(e=!1){if(!this._started)return;if(!e&&this._scene){if(!this.isReady())return;if(this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}let t;if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this.manualEmitCount>-1)t=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const t=this._actualFrame/this.targetStopDuration;gx.GetCurrentGradient(t,this._emitRateGradients,((t,i,s)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=I(this._currentEmitRate1,this._currentEmitRate2,s)}))}t=e*this._scaledUpdateSpeed|0,this._newPartsExcess+=e*this._scaledUpdateSpeed-t}if(this._newPartsExcess>1&&(t+=0|this._newPartsExcess,this._newPartsExcess-=0|this._newPartsExcess),this._alive=!1,this._stopped?t=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(t),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){let e=0;for(let t=0;t=0&&(r.invertToRef(U.Matrix[0]),i.setMatrix("invView",U.Matrix[0])),void 0!==this._vertexArrayObject?this._scene?.forceWireframe?s.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,i):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,i)),this._engine.bindVertexArrayObject(this._vertexArrayObject,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?s.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBuffer:this._indexBuffer,i):s.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null,i),this.useLogarithmicDepth&&this._scene&&Jr(n,i,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(i),e){case ia.BLENDMODE_ADD:s.setAlphaMode(1);break;case ia.BLENDMODE_ONEONE:s.setAlphaMode(6);break;case ia.BLENDMODE_STANDARD:s.setAlphaMode(2);break;case ia.BLENDMODE_MULTIPLY:s.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(i),this._useInstancing?this._scene?.forceWireframe?s.drawElementsType(6,0,10,this._particles.length):s.drawArraysType(7,0,4,this._particles.length):this._scene?.forceWireframe?s.drawElementsType(1,0,10*this._particles.length):s.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;const e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===ia.BLENDMODE_MULTIPLYADD?this._render(ia.BLENDMODE_MULTIPLY)+this._render(ia.BLENDMODE_ADD):this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}_onDispose(e=!1,t=!1){}dispose(e=!0,t=!1,i=!1){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._onDispose(t,i),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.clear(),this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}}var Tx;!function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(Tx||(Tx={}));class Sx{constructor(e){if(this.particleSystem=e,this.type=Tx.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=d("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;e?e instanceof w?e=e.clone():-1!==e.getClassName().indexOf("Mesh")&&(e=new(d("BABYLON.Mesh"))("",e.getScene()),e.isVisible=!1):e=new w;const t=new Sx(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){const t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,s=!1){throw ye("ParseParticle")}static Parse(e,t,i){const s=e.particleSystem,r=new Sx(Sx._ParseParticleSystem(s,t,i,!0));return r.type=e.type,r.inheritDirection=e.inheritDirection,r.inheritedVelocityAmount=e.inheritedVelocityAmount,r.particleSystem._isSubEmitter=!0,r}dispose(){this.particleSystem.dispose()}}function Ex(e,t){const i=new lx;return i.direction1=e,i.direction2=t,i}function bx(e=1,t=1){return new ax(e,t)}function Cx(e=1,t=1){return new hx(e,t)}function yx(e=1,t=new w(0,1,0),i=new w(0,1,0)){return new cx(e,t,i)}function Ax(e=1,t=1,i=1,s=0){return new nx(e,t,i,s)}function Rx(e=1,t=1,i=1,s=new w(0,1,0),r=new w(0,1,0)){return new ox(e,t,i,s,r)}function Ix(e=1,t=Math.PI/4){return new rx(e,t)}class Px extends xx{constructor(){super(...arguments),this._disposeEmitterOnDispose=!1,this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;const t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach((t=>{if(t.type===Tx.END){const i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}}))}}createPointEmitter(e,t){const i=Ex(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=bx(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=Cx(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new w(0,1,0),i=new w(0,1,0)){const s=yx(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=Ax(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new w(0,1,0),r=new w(0,1,0)){const n=Rx(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=Ix(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new sx;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}_prepareSubEmitterInternalArray(){this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach((e=>{e instanceof Px?this._subEmitters.push([new Sx(e)]):e instanceof Sx?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)}))}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach((e=>{e.stop(!0)})),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;const e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_preStart(){this._prepareSubEmitterInternalArray(),this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=[])}_postStop(e){e&&this._stopSubEmitters()}_prepareParticle(e){if(this._subEmitters&&this._subEmitters.length>0){const t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach((t=>{if(t.type===Tx.ATTACHED){const i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}}))}}_onDispose(e=!1,t=!1){if(this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),e&&this.particles?.forEach((e=>{if(e._attachedSubEmitters)for(let t=e._attachedSubEmitters.length-1;t>=0;t-=1)e._attachedSubEmitters[t].dispose()})),t&&this.activeSubSystems)for(let e=this.activeSubSystems.length-1;e>=0;e-=1)this.activeSubSystems[e].dispose();if(this._subEmitters&&this._subEmitters.length){for(let e=0;e0?h.shaderOptions.defines.join("\n"):"";l=o.createEffectForParticles(h.shaderPath.fragmentElement,h.shaderOptions.uniforms,h.shaderOptions.samplers,t)}const c=new Px(n,r||e.capacity,t,l,e.isAnimationSheetEnabled);if(c.customShader=h,c._rootUrl=i,e.id&&(c.id=e.id),e.subEmitters){c.subEmitters=[];for(const s of e.subEmitters){const e=[];for(const r of s)e.push(Sx.Parse(r,t,i));c.subEmitters.push(e)}}return Px._Parse(e,c,t,i),e.textureMask&&(c.textureMask=j.FromArray(e.textureMask)),e.worldOffset&&(c.worldOffset=w.FromArray(e.worldOffset)),e.preventAutoStart&&(c.preventAutoStart=e.preventAutoStart),s||c.preventAutoStart||c.start(),c}serialize(e=!1){const t={};if(Px._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,t.worldOffset=this.worldOffset.asArray(),this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const s=[];for(const t of i)s.push(t.serialize(e));t.subEmitters.push(s)}}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){const i=t.emitter;e.emitterId=i.id}else{const i=t.emitter;e.emitter=i.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,Pe.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;const s=t.getColorGradients();if(s){e.colorGradients=[];for(const t of s){const i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}}const r=t.getRampGradients();if(r){e.rampGradients=[];for(const t of r){const i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}const n=t.getColorRemapGradients();if(n){e.colorRemapGradients=[];for(const t of n){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const t of o){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}}const a=t.getSizeGradients();if(a){e.sizeGradients=[];for(const t of a){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}}const l=t.getAngularSpeedGradients();if(l){e.angularSpeedGradients=[];for(const t of l){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}}const h=t.getVelocityGradients();if(h){e.velocityGradients=[];for(const t of h){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}}const c=t.getDragGradients();if(c){e.dragGradients=[];for(const t of c){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}}const u=t.getEmitRateGradients();if(u){e.emitRateGradients=[];for(const t of u){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}}const d=t.getStartSizeGradients();if(d){e.startSizeGradients=[];for(const t of d){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}}const p=t.getLifeTimeGradients();if(p){e.lifeTimeGradients=[];for(const t of p){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}}const f=t.getLimitVelocityGradients();if(f){e.limitVelocityGradients=[];for(const t of f){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}clone(e,t,i=!1){const s={...this._customWrappers};let r=null;const n=this._engine;if(n.createEffectForParticles&&null!=this.customShader){r=this.customShader;const e=r.shaderOptions.defines.length>0?r.shaderOptions.defines.join("\n"):"",t=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,e);s[0]?s[0].effect=t:this.setCustomEffect(t,0)}const o=this.serialize(i),a=Px.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=r,a._customWrappers=s,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,this.preventAutoStart||a.start(),a}}Px.BILLBOARDMODE_Y=2,Px.BILLBOARDMODE_ALL=7,Px.BILLBOARDMODE_STRETCHED=8,Px.BILLBOARDMODE_STRETCHED_LOCAL=9,Sx._ParseParticleSystem=Px.Parse;Ft.IncludesShadersStore.clipPlaneFragmentDeclaration2="#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nin float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nin float fClipDistance6;\n#endif\n";Ft.ShadersStore.gpuRenderParticlesPixelShader="precision highp float;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor;\n#include \n#include\n#include\n#include\n#include\n#include\nvoid main() {\n#include \nvec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha);\n#endif \n#include\n#include(color,gl_FragColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor);\n#endif\n#endif\n}\n";Ft.IncludesShadersStore.clipPlaneVertexDeclaration2="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;out float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;out float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;out float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;out float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;out float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;out float fClipDistance6;\n#endif\n";Ft.ShadersStore.gpuRenderParticlesVertexShader="precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset;\n#ifdef LOCAL\nuniform mat4 emitterWM;\n#endif\nattribute vec3 position;attribute float age;attribute float life;attribute vec3 size;\n#ifndef BILLBOARD\nattribute vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\nattribute float angle;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\nattribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#include\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;attribute vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture2D(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x;\n#ifdef BILLBOARD\nvec4 rotatedCorner;rotatedCorner.w=0.;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;\n#ifdef LOCAL\nvec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner;\n#else\nvec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner;\n#endif\nvPositionW=(invView*viewPosition).xyz;\n#endif\n#else\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0);\n#endif\ngl_Position=projection*viewPosition;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#include\n}";class Mx extends ia{static get IsSupported(){if(!y.LastCreatedEngine)return!1;const e=y.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]),void 0,"GPUParticleSystemLinesIndexBuffer")}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}createPointEmitter(e,t){const i=Ex(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=bx(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=Cx(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new w(0,1,0),i=new w(0,1,0)){const s=yx(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=Ax(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new w(0,1,0),r=new w(0,1,0)){const n=Rx(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=Ix(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new sx;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady()||this._rebuildingAfterContextLost)return!1;if(this.blendMode!==Px.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else{if(!this._getWrapper(Px.BLENDMODE_MULTIPLY).effect.isReady())return!1;if(!this._getWrapper(Px.BLENDMODE_ADD).effect.isReady())return!1}return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";e?setTimeout((()=>{this.start(0)}),e):(this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop))}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new gr(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new g),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[1^this._targetIndex]}get indexBuffer(){return null}_removeGradientAndTexture(e,t,i){return super._removeGradientAndTexture(e,t,i),this._releaseBuffers(),this}addColorGradient(e,t){this._colorGradients||(this._colorGradients=[]);const i=new fx(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))}forceRefreshGradients(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()}removeColorGradient(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this}resetDrawCache(){for(const e in this._drawWrappers){const t=this._drawWrappers[e];t.drawContext?.reset()}}_addFactorGradient(e,t,i){const s=new mx(t,i);e.push(s),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){if(!e)return;i&&e.sort(((e,t)=>e.gradientt.gradient?1:0));const s=this;s[t]&&(s[t].dispose(),s[t]=null)}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,s=null,r=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this._rebuildingAfterContextLost=!1,this.onDisposeObservable=new g,this.onStoppedObservable=new g,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=B.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||y.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!d("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new(d("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!d("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new(d("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new gr(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers={0:new gr(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),(t=t??{}).randomTextureSize||delete t.randomTextureSize;const n={capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize,...t},o=t;isFinite(o)&&(n.capacity=o),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=r,this.particleEmitterType=new sx;const a=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize);let l=[];for(let e=0;e0;)i.push(0)}const o=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),a=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new $i(t,a,!1,this._attributesStrideSize),this._buffer1=new $i(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new $i(t,o,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}_recreateUpdateEffect(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();let e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e)),this._platform.isUpdateBufferReady()}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);let s=this._drawWrappers[e];s||(s=new gr(this._engine),s.drawContext&&(s.drawContext.useInstancing=!0),this._drawWrappers[e]=s);const r=i.join("\n");if(s.defines!==r){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),s.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,r),r)}return s}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,s=!1){const r=[Ki.PositionKind,"age","life","size","angle"];return e||r.push(Ki.ColorKind),t&&r.push("cellIndex"),i||r.push("initialDirection"),s&&r.push("direction"),r.push("offset",Ki.UVKind),r}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return jr(s),e&&s.push("sheetInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t=0,i=!0){if(this._scene&&($r(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==ks.FOGMODE_NONE&&e.push("#define FOG")),t===Px.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case Px.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case Px.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case Px.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),i&&this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...Mx._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===Px.BILLBOARDMODE_STRETCHED)),e.push(...Mx._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(Bi.PrepareUniforms(e,this._imageProcessingConfigurationDefines),Bi.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){const i=this[t];if(!e||!e.length||i)return;const s=new Float32Array(this._rawTextureWidth);for(let t=0;t{s[t]=G.Lerp(e.factor1,i.factor1,r)}))}this[t]=io.CreateRTexture(s,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;const e=new Uint8Array(4*this._rawTextureWidth),t=$.Color4[0];for(let i=0;i{j.LerpToRef(s.color1,r.color1,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a}))}this._colorGradientsTexture=io.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){const i=this._getWrapper(e),s=i.effect;this._engine.enableEffect(i);const r=this._scene?.getViewMatrix()||B.IdentityReadOnly;if(s.setMatrix("view",r),s.setMatrix("projection",this.defaultProjectionMatrix??this._scene.getProjectionMatrix()),s.setTexture("diffuseSampler",this.particleTexture),s.setVector2("translationPivot",this.translationPivot),s.setVector3("worldOffset",this.worldOffset),this.isLocal&&s.setMatrix("emitterWM",t),this._colorGradientsTexture?s.setTexture("colorGradientSampler",this._colorGradientsTexture):s.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const e=this.particleTexture.getBaseSize();s.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const e=this._scene.activeCamera;s.setVector3("eyePosition",e.globalPosition)}const n=s.defines;if(this._scene&&(Kr(s,this,this._scene),this.applyFog&&en(this._scene,void 0,s)),n.indexOf("#define BILLBOARDMODE_ALL")>=0){const e=r.clone();e.invert(),s.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&Jr(n,s,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(s),e){case Px.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case Px.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case Px.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case Px.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,s,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(s),this._scene?.forceWireframe?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),this._scene?.forceWireframe&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer)return;if(!this._recreateUpdateEffect()||this._rebuildingAfterContextLost)return;if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{const t=this.emitter;e=U.Matrix[0],B.TranslationToRef(t.x,t.y,t.z,e)}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,2===this._targetIndex&&(this._targetIndex=0);const t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){if(!this._started)return 0;if(!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e1){const e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount+=e}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;let i;if(this.emitter.position)i=this.emitter.getWorldMatrix();else{const e=this.emitter;i=U.Matrix[0],B.TranslationToRef(e.x,e.y,e.z,i)}const s=this._engine;this.updateInAnimate||this._update(i);let r=0;return e||t||(s.setState(!1),this.forceDepthWrite&&s.setDepthWrite(!0),r=this.blendMode===Px.BLENDMODE_MULTIPLYADD?this._render(Px.BLENDMODE_MULTIPLY,i)+this._render(Px.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),r}rebuild(){const e=()=>{this._recreateUpdateEffect()&&this._platform.isUpdateBufferReady()?(this._initialize(!0),this._rebuildingAfterContextLost=!1):setTimeout(e,10)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),this._rebuildingAfterContextLost=!0,e()}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(const e in this._drawWrappers)this._drawWrappers[e].dispose();if(this._drawWrappers={},this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e0?r.shaderOptions.defines.join("\n"):"";s[0]=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,e,void 0,void 0,void 0,this)}const o=this.serialize(i),a=Mx.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=r,a._customWrappers=s,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,a}serialize(e=!1){const t={};return Px._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,s=!1,r){const n=e.name;let o,a;t instanceof si?o=t:(a=t,o=a.getEngine());const l=new Mx(n,{capacity:r||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(l._rootUrl=i,e.customShader&&o.createEffectForParticles){const t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",s=o.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,l);l.setCustomEffect(s,0),l.customShader=t}return e.id&&(l.id=e.id),e.activeParticleCount&&(l.activeParticleCount=e.activeParticleCount),Px._Parse(e,l,t,i),e.preventAutoStart&&(l.preventAutoStart=e.preventAutoStart),s||l.preventAutoStart||l.start(),l}}class Dx{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1);for(const t of this.systems)t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};const s=nc("emitterSphere",{diameter:e.diameter,segments:e.segments},i);s.renderingGroupId=t;const r=new dh("emitterSphereMaterial",i);r.emissiveColor=e.color,s.material=r;for(const e of this.systems)e.emitter=s;this._emitterNode=s}start(e){for(const t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(const e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){const t={systems:[]};for(const i of this.systems)t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,s){const r=new Dx,n=this.BaseAssetsUrl+"/textures/";t=t||y.LastCreatedScene;for(const o of e.systems)r.systems.push(i?Mx.Parse(o,t,n,!0,s):Px.Parse(o,t,n,!0,s));if(e.emitter){const i=e.emitter.options;"Sphere"===e.emitter.kind&&r.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:Y.FromArray(i.color)},e.emitter.renderingGroupId,t)}return r}}Dx.BaseAssetsUrl="https://assets.babylonjs.com/particles";class Ox{static CreateDefault(e,t=500,i,s=!1){let r;return r=s?new Mx("default system",{capacity:t},i):new Px("default system",t,i),r.emitter=e,r.particleTexture=new Zn("https://assets.babylonjs.com/textures/flare.png",r.getScene()),r.createConeEmitter(.1,Math.PI/4),r.color1=new j(1,1,1,1),r.color2=new j(1,1,1,1),r.colorDead=new j(1,1,1,0),r.minSize=.1,r.maxSize=.1,r.minEmitPower=2,r.maxEmitPower=2,r.updateSpeed=1/60,r.emitRate=30,r}static CreateAsync(e,t,i=!1,s){t||(t=y.LastCreatedScene);const r={};return t.addPendingData(r),new Promise(((n,o)=>{if(i&&!Mx.IsSupported)return t.removePendingData(r),o("Particle system with GPU is not supported.");Ii.LoadFile(`${Ox.BaseAssetsUrl}/systems/${e}.json`,(e=>{t.removePendingData(r);const o=JSON.parse(e.toString());return n(Dx.Parse(o,t,i,s))}),void 0,void 0,void 0,(()=>(t.removePendingData(r),o(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`))))}))}static ExportSet(e){const t=new Dx;for(const i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,s=!1,r="",n){return new Promise(((o,a)=>{const l=new Ne;l.addEventListener("readystatechange",(()=>{if(4==l.readyState)if(200==l.status){const t=JSON.parse(l.responseText);let a;a=s?Mx.Parse(t,i,r,!1,n):Px.Parse(t,i,r,!1,n),e&&(a.name=e),o(a)}else a("Unable to load the particle system")})),l.open("GET",t),l.send()}))}static ParseFromSnippetAsync(e,t,i=!1,s="",r){if("_BLANK"===e){const e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise(((n,o)=>{const a=new Ne;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.particleSystem);let h;h=i?Mx.Parse(l,t,s,!1,r):Px.Parse(l,t,s,!1,r),h.snippetId=e,n(h)}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}}var Nx,wx,Fx,Lx,Bx,Vx,Ux,kx,Gx,zx,Wx,Hx,Xx,Yx,jx,$x,Kx,qx,Qx,Zx,Jx;Ox.BaseAssetsUrl=Dx.BaseAssetsUrl,Ox.SnippetUrl="https://snippet.babylonjs.com",Ox.CreateFromSnippetAsync=Ox.ParseFromSnippetAsync,p.AddParser(ts.NAME_PARTICLESYSTEM,((e,t,i,s)=>{const r=p.GetIndividualParser(ts.NAME_PARTICLESYSTEM);if(r&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,o=e.particleSystems.length;ne.activeParticleCount?Mx.Parse(e,t,i):Px.Parse(e,t,i))),si.prototype.createEffectForParticles=function(e,t=[],i=[],s="",r,n,o,a){let l=[],h=[];const c=[];return a?a.fillUniformsAttributesAndSamplerNames(h,l,c):(l=Px._GetAttributeNamesOrOptions(),h=Px._GetEffectCreationOptions()),-1===s.indexOf(" BILLBOARD")&&(s+="\n#define BILLBOARD\n"),a?.isAnimationSheetEnabled&&-1===s.indexOf(" ANIMATESHEET")&&(s+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:a?.vertexShaderName??"particles",fragmentElement:e},l,h.concat(t),c.concat(i),s,r,n,o)},Un.prototype.getEmittedParticleSystems=function(){const e=[];for(let t=0;t{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)}))))},enumerable:!0,configurable:!0}),Wr.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},Wr.prototype.applyImpulse=function(e,t){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(e,t),this):this},Wr.prototype.setPhysicsLinkWith=function(e,t,i,s){return this.physicsImpostor&&e.physicsImpostor?(this.physicsImpostor.createJoint(e.physicsImpostor,mo.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:s}),this):this};class eT{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw ye("")}constructor(e,t=eT.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new w(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){const t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,s){this._physicsPlugin.raycast(e,t,i,s)}raycast(e,t,i){const s=new V_;return this._physicsPlugin.raycast(e,t,s,i),s}}(Zx=wx||(wx={}))[Zx.FREE=0]="FREE",Zx[Zx.LIMITED=1]="LIMITED",Zx[Zx.LOCKED=2]="LOCKED",(Qx=Fx||(Fx={}))[Qx.LINEAR_X=0]="LINEAR_X",Qx[Qx.LINEAR_Y=1]="LINEAR_Y",Qx[Qx.LINEAR_Z=2]="LINEAR_Z",Qx[Qx.ANGULAR_X=3]="ANGULAR_X",Qx[Qx.ANGULAR_Y=4]="ANGULAR_Y",Qx[Qx.ANGULAR_Z=5]="ANGULAR_Z",Qx[Qx.LINEAR_DISTANCE=6]="LINEAR_DISTANCE",(qx=Lx||(Lx={}))[qx.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",qx[qx.DISTANCE=2]="DISTANCE",qx[qx.HINGE=3]="HINGE",qx[qx.SLIDER=4]="SLIDER",qx[qx.LOCK=5]="LOCK",qx[qx.PRISMATIC=6]="PRISMATIC",qx[qx.SIX_DOF=7]="SIX_DOF",(Kx=Bx||(Bx={}))[Kx.SPHERE=0]="SPHERE",Kx[Kx.CAPSULE=1]="CAPSULE",Kx[Kx.CYLINDER=2]="CYLINDER",Kx[Kx.BOX=3]="BOX",Kx[Kx.CONVEX_HULL=4]="CONVEX_HULL",Kx[Kx.CONTAINER=5]="CONTAINER",Kx[Kx.MESH=6]="MESH",Kx[Kx.HEIGHTFIELD=7]="HEIGHTFIELD",($x=Vx||(Vx={}))[$x.NONE=0]="NONE",$x[$x.VELOCITY=1]="VELOCITY",$x[$x.POSITION=2]="POSITION",(jx=Ux||(Ux={})).COLLISION_STARTED="COLLISION_STARTED",jx.COLLISION_CONTINUED="COLLISION_CONTINUED",jx.COLLISION_FINISHED="COLLISION_FINISHED",jx.TRIGGER_ENTERED="TRIGGER_ENTERED",jx.TRIGGER_EXITED="TRIGGER_EXITED",(Yx=kx||(kx={}))[Yx.STATIC=0]="STATIC",Yx[Yx.ANIMATED=1]="ANIMATED",Yx[Yx.DYNAMIC=2]="DYNAMIC",(Xx=Gx||(Gx={}))[Xx.SIMULATION_CONTROLLED=0]="SIMULATION_CONTROLLED",Xx[Xx.ALWAYS_ACTIVE=1]="ALWAYS_ACTIVE",Xx[Xx.ALWAYS_INACTIVE=2]="ALWAYS_INACTIVE",(Jx=zx||(zx={}))[Jx.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",Jx[Jx.MINIMUM=1]="MINIMUM",Jx[Jx.MAXIMUM=2]="MAXIMUM",Jx[Jx.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",Jx[Jx.MULTIPLY=4]="MULTIPLY",ks.prototype.getPhysicsEngine=function(){return this._physicsEngine},ks.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(ts.NAME_PHYSICSENGINE);i||(i=new tT(this),this._addComponent(i));try{if(t&&1!==t?.getPluginVersion()){if(2!==t?.getPluginVersion())throw new Error("Unsupported Physics plugin version.");this._physicsEngine=new eT(e,t)}else this._physicsEngine=new U_(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return J.Error(e.message),!1}},ks.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},ks.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},ks.prototype.deleteCompoundImpostor=function(e){const t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},ks.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){const t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class tT{constructor(e){this.name=ts.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new g,this.scene.onAfterPhysicsObservable=new g,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?1e3*this.scene._physicsEngine.getTimeStep():1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(Ur.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)}))))},enumerable:!0,configurable:!0}),Ur.prototype.getPhysicsBody=function(){return this.physicsBody},Ur.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this},Ur.prototype.applyAngularImpulse=function(e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyAngularImpulse(e),this};class iT{static GetContactPointToRef(e,t,i,s,r){const n=e.getScene().getPhysicsEngine(),o=n?.getPluginVersion();if(1===o){const r=new ao(t,i).intersectsMesh(e);if(r.hit&&r.pickedPoint)return s.copyFrom(r.pickedPoint),!0}else if(2===o)return e.physicsBody.getObjectCenterWorldToRef(s,r),!0;return!1}static HasAppliedForces(e,t){return e.getMotionType(t)===kx.STATIC||0===(e.getMassProperties(t)?.mass??0)||0===e.transformNode?.getTotalVertices()}static IsInsideCylinder(e,t,i,s){const r=U.Vector3[0];return e.subtractToRef(t,r),Math.abs(r.x)<=i&&Math.abs(r.z)<=i&&r.y>=0&&r.y<=s}}class sT{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=w.Zero(),this._originDirection=w.Zero(),this._cylinderPosition=w.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new nT,...this._options},this._origin.addToRef(new w(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new w(0,this._options.height,0),this._originTop),this._options.updraftMode===Hx.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout((()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)}),0))}_getHitData(e,t){let i;i=this._options.updraftMode===Hx.Perpendicular?this._originDirection:e.subtract(this._originTop);const s=w.Distance(this._origin,e),r=-1*this._options.strength,n=i.multiplyByFloats(r,r,r);t.force.copyFrom(n),t.contactPoint.copyFrom(e),t.distanceFromOrigin=s}_getBodyHitData(e,t,i){if(iT.HasAppliedForces(e))return!1;const s=e.getObjectCenterWorld(i);return!!iT.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(s,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const s=e.getObjectCenter();return this._getHitData(s,t),!0}_tick(){const e=sT._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=Qh("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))}}sT._HitData={force:new w,contactPoint:new w,distanceFromOrigin:0};class rT{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=w.Zero(),this._cylinderPosition=w.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new oT,...this._options},this._origin.addToRef(new w(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new w(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout((()=>{this._dataFetched||this._cylinder.dispose()}),0))}_getHitData(e,t,i){const s=rT._OriginOnPlane;s.set(this._origin.x,t.y,this._origin.z);const r=U.Vector3[0];t.subtractToRef(s,r);const n=U.Vector3[1];if(!iT.GetContactPointToRef(e,s,r,n,i.instanceIndex))return!1;const o=w.Distance(n,s)/this._options.radius,a=U.Vector3[2];let l,h,c;if(n.normalizeToRef(a),o>this._options.centripetalForceThreshold&&a.negateInPlace(),o>this._options.centripetalForceThreshold)l=a.x*this._options.centripetalForceMultiplier,h=a.y*this._options.updraftForceMultiplier,c=a.z*this._options.centripetalForceMultiplier;else{const e=w.Cross(s,t).normalize();l=(e.x+a.x)*this._options.centrifugalForceMultiplier,h=this._originTop.y*this._options.updraftForceMultiplier,c=(e.z+a.z)*this._options.centrifugalForceMultiplier}const u=U.Vector3[3];return u.set(l,h,c),u.scaleInPlace(this._options.strength),i.force.copyFrom(u),i.contactPoint.copyFrom(t),i.distanceFromOrigin=o,!0}_getBodyHitData(e,t,i){if(iT.HasAppliedForces(e,i))return!1;const s=e.transformNode,r=e.getObjectCenterWorld(i);return!!iT.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(s,r,t))}_getImpostorHitData(e,t){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const s=e.getObjectCenter();return this._getHitData(i,s,t),!0}_tick(){const e=rT._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=Qh("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}}rT._OriginOnPlane=w.Zero(),rT._HitData={force:new w,contactPoint:new w,distanceFromOrigin:0};class nT{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=Hx.Center}}class oT{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}!function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"}(Wx||(Wx={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(Hx||(Hx={}));Ft.ShadersStore.blackAndWhitePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}";class aT extends Ko{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,s,r,n){super(e,"blackAndWhite",["degree"],null,t,i,s,r,n),this.degree=1,this.onApplyObservable.add((e=>{e.setFloat("degree",this.degree)}))}static _Parse(e,t,i,s){return Pe.Parse((()=>new aT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}ae([pe()],aT.prototype,"degree",void 0),u("BABYLON.BlackAndWhitePostProcess",aT);class lT{constructor(e,t,i,s){this._name=t,this._singleInstance=s||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let e=0;e{const t=s.attachPostProcess(e);this._indicesForCamera[r].push(t)})),this._cameras[r]||(this._cameras[r]=s)}}_detachCameras(e){const t=Ii.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)})),this._cameras[s]&&(this._cameras[s]=null),delete this._indicesForCamera[s]}}_enable(e){const t=Ii.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)}))}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}Ft.ShadersStore.extractHighlightsPixelShader="#include\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}";class hT extends Ko{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,s,r,n,null,o,void 0,null,a),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add((e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess),e.setFloat("threshold",Math.pow(this.threshold,v)),e.setFloat("exposure",this._exposure)}))}}ae([pe()],hT.prototype,"threshold",void 0),u("BABYLON.ExtractHighlightsPostProcess",hT);Ft.ShadersStore.bloomMergePixelShader="uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); }\n";class cT extends Ko{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,s,r,n,o,a,l,h=0,c=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],r,n,o,a,l,null,h,void 0,null,!0),this.weight=1,this.weight=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)})),c||this.updateEffect()}}ae([pe()],cT.prototype,"weight",void 0),u("BABYLON.BloomMergePostProcess",cT);class uT extends lT{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,s,r=0,n=!1){super(e.getEngine(),"bloom",(()=>this._effects),!0),this._bloomScale=t,this._effects=[],this._downscale=new hT("highlights",1,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._blurX=new Jp("horizontal blur",new N(1,0),10,t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new Jp("vertical blur",new N(0,1),10,t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=s,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new cT("bloomMerge",this._downscale,this._blurY,i,t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)}))}static _Parse(e,t,i,s){return Pe.Parse((()=>new dT(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,s)}}ae([pe()],dT.prototype,"aberrationAmount",void 0),ae([pe()],dT.prototype,"radialIntensity",void 0),ae([pe()],dT.prototype,"direction",void 0),ae([pe()],dT.prototype,"centerPosition",void 0),ae([pe()],dT.prototype,"screenWidth",void 0),ae([pe()],dT.prototype,"screenHeight",void 0),u("BABYLON.ChromaticAberrationPostProcess",dT);Ft.ShadersStore.circleOfConfusionPixelShader="uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float depth=texture2D(depthSampler,vUV).r;\n#define CUSTOM_COC_DEPTH\nfloat pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; \n#define CUSTOM_COC_PIXELDISTANCE\nfloat coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);}\n";class pT extends Ko{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,s,r,n,o,a=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,s,r,n,o,null,a,void 0,null,l),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add((e=>{if(!this._depthTexture)return void J.Warn("No depth texture set on CircleOfConfusionPostProcess");e.setTexture("depthSampler",this._depthTexture);const t=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",t);const i=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",i.minZ,i.maxZ-i.minZ)}))}set depthTexture(e){this._depthTexture=e}}ae([pe()],pT.prototype,"lensSize",void 0),ae([pe()],pT.prototype,"fStop",void 0),ae([pe()],pT.prototype,"focusDistance",void 0),ae([pe()],pT.prototype,"focalLength",void 0),u("BABYLON.CircleOfConfusionPostProcess",pT);Ft.ShadersStore.colorCorrectionPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D colorTable; \nvarying vec2 vUV;const float SLICE_COUNT=16.0; \nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}";class fT extends Ko{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"colorCorrection",null,["colorTable"],i,s,r,n,o);const a=s?.getScene()||null;this._colorTableTexture=new Zn(t,a,!0,!1,Zn.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=Zn.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=Zn.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,s){return Pe.Parse((()=>new fT(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}ae([pe()],fT.prototype,"colorTableUrl",void 0),u("BABYLON.ColorCorrectionPostProcess",fT);Ft.ShadersStore.convolutionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9];\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}";class _T extends Ko{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,s,r,n,o,a=0){super(e,"convolution",["kernel","screenSize"],null,i,s,r,n,o,null,a),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,s){return Pe.Parse((()=>new _T(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType)),e,i,s)}}_T.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],_T.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],_T.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],_T.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],_T.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],_T.GaussianKernel=[0,1,0,1,1,1,0,1,0],ae([pe()],_T.prototype,"kernel",void 0),u("BABYLON.ConvolutionPostProcess",_T);class mT extends Jp{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,s,r,n,o,a=null,l=Zn.BILINEAR_SAMPLINGMODE,h,c,u=0,d=!1,p=5){super(e,i,s,r,n,2,h,c,u,"#define DOF 1\n",d,p),this.direction=i,this.externalTextureSamplerBinding=!!a,this.onApplyObservable.add((e=>{null!=a&&e.setTextureFromPostProcess("textureSampler",a),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)}))}}ae([pe()],mT.prototype,"direction",void 0),u("BABYLON.DepthOfFieldBlurPostProcess",mT);Ft.ShadersStore.depthOfFieldMergePixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;\n#if BLUR_LEVEL==0\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);}\n#endif\n#if BLUR_LEVEL==2\nif(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);}\n#endif\n}\n";class gT extends Ko{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,s,r,n,o,a,l,h=0,c=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],r,n,o,a,l,null,h,void 0,null,!0),this._blurSteps=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),s.forEach(((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(s.length-i-1),t)}))})),c||this.updateEffect()}updateEffect(e=null,t=null,i=null,s,r,n){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,s,r,n)}}var vT;!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(vT||(vT={}));class xT extends lT{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=vT.Low,s=0,r=!1){super(e.getEngine(),"depth of field",(()=>this._effects),!0),this._effects=[];const n=e.getEngine(),o=n.isWebGPU||n.version>1?6:5;this._circleOfConfusion=new pT("circleOfConfusion",t,1,null,Zn.BILINEAR_SAMPLINGMODE,n,!1,s,r),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let a=1,l=15;switch(i){case vT.High:a=3,l=51;break;case vT.Medium:a=2,l=31;break;default:l=15,a=1}const h=l/Math.pow(2,a-1);let c=1;for(let t=0;tnew TT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}u("BABYLON.DisplayPassPostProcess",TT);Ft.ShadersStore.filterPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}";class ST extends Ko{getClassName(){return"FilterPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"filter",["kernelMatrix"],null,i,s,r,n,o),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,s){return Pe.Parse((()=>new ST(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}ae([Ee()],ST.prototype,"kernelMatrix",void 0),u("BABYLON.FilterPostProcess",ST);Ft.ShadersStore.fxaaPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)\n{lumaN=lumaW;}\nif (!horzSpan) \n{lumaS=lumaE;}\nif (horzSpan) \n{lengthSign=texelSize.y;}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN)\n{lengthSign=-lengthSign;}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) \n{posB.x+=lengthSign*0.5;}\nif (horzSpan)\n{posB.y+=lengthSign*0.5;}\nvec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) \n{lumaNN=lumaSS;}\nfloat gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) \n{posN.x-=offNP.x*3.0;}\nif (!doneN) \n{posN.y-=offNP.y*3.0;}\nbool doneNP=(!doneN) || (!doneP);if (!doneP) \n{posP.x+=offNP.x*3.0;}\nif (!doneP)\n{posP.y+=offNP.y*3.0;}\nif (doneNP)\n{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;}\nfloat dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan)\n{dstN=posM.y-posN.y;}\nif (!horzSpan) \n{dstP=posP.y-posM.y;}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{const t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)}))}_getDefines(){const e=this.getEngine();return e&&e.extractDriverInfo().toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,s){return Pe.Parse((()=>new ET(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}u("BABYLON.FxaaPostProcess",ET);Ft.ShadersStore.grainPixelShader="#include\nuniform sampler2D textureSampler; \nuniform float intensity;uniform float animatedSeed;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}";class bT extends Ko{getClassName(){return"GrainPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,s,r,n,null,o,void 0,null,a),this.intensity=30,this.animated=!1,this.onApplyObservable.add((e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)}))}static _Parse(e,t,i,s){return Pe.Parse((()=>new bT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}ae([pe()],bT.prototype,"intensity",void 0),ae([pe()],bT.prototype,"animated",void 0),u("BABYLON.GrainPostProcess",bT);Ft.ShadersStore.highlightsPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }";Ft.ShadersStore.imageProcessingPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;}";class CT extends Ko{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null;const t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){const i=t.scenes;e=i[i.length-1]}else e=y.LastCreatedScene;this._imageProcessingConfiguration=e?e.imageProcessingConfiguration:new Bi}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateParameters()}))),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,s,r,n,o=0,a){super(e,"imageProcessing",[],[],t,i,s,r,n,null,o,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:0,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},a?(a.applyByPostProcess=!0,this._attachImageProcessingConfiguration(a,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const t in this._defines){const i=this._defines[t];switch(typeof i){case"number":case"string":e+=`#define ${t} ${i};\n`;break;default:i&&(e+=`#define ${t};\n`)}}const t=["textureSampler"],i=["scale"];Bi&&(Bi.PrepareSamplers(t,this._defines),Bi.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}ae([pe()],CT.prototype,"_fromLinearSpace",void 0);Ft.IncludesShadersStore.mrtFragmentDeclaration="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n";Ft.ShadersStore.geometryPixelShader="#extension GL_EXT_draw_buffers : require\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\nprecision highp float;\n#ifdef BUMP\nvarying mat4 vWorldView;varying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nvarying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#ifdef NEED_UV\nvarying vec2 vUV;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIVITY)\n#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nuniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV;\n#endif\n#ifdef ALBEDOTEXTURE\nvarying vec2 vAlbedoUV;uniform sampler2D albedoSampler;\n#endif\n#ifdef REFLECTIVITYCOLOR\nuniform vec3 reflectivityColor;\n#endif\n#ifdef ALBEDOCOLOR\nuniform vec3 albedoColor;\n#endif\n#ifdef METALLIC\nuniform float metallic;\n#endif\n#if defined(ROUGHNESS) || defined(GLOSSINESS)\nuniform float glossiness;\n#endif\n#endif\n#if defined(ALPHATEST) && defined(NEED_UV)\nuniform sampler2D diffuseSampler;\n#endif\n#include\n#include[RENDER_TARGET_COUNT]\n#include\n#include\n#include\nvoid main() {\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nvec3 normalOutput;\n#ifdef BUMP\nvec3 normalW=normalize(vNormalW);\n#include\n#ifdef NORMAL_WORLDSPACE\nnormalOutput=normalW;\n#else\nnormalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0)));\n#endif\n#else\nnormalOutput=normalize(vNormalV);\n#endif\n#ifdef ENCODE_NORMAL\nnormalOutput=normalOutput*0.5+0.5;\n#endif\n#ifdef PREPASS\n#ifdef PREPASS_DEPTH\ngl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n#endif\n#ifdef PREPASS_NORMAL\ngl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0);\n#endif\n#else\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0);\n#endif\n#ifdef POSITION\ngl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);\n#endif\n#ifdef REFLECTIVITY\nvec4 reflectivity=vec4(0.0,0.0,0.0,1.0);\n#ifdef METALLICWORKFLOW\nfloat metal=1.0;float roughness=1.0;\n#ifdef ORMTEXTURE\nmetal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g;\n#endif\n#ifdef METALLIC\nmetal*=metallic;\n#endif\n#ifdef ROUGHNESS\nroughness*=(1.0-glossiness); \n#endif\nreflectivity.a-=roughness;vec3 color=vec3(1.0);\n#ifdef ALBEDOTEXTURE\ncolor=texture2D(albedoSampler,vAlbedoUV).rgb;\n#ifdef GAMMAALBEDO\ncolor=toLinearSpace(color);\n#endif\n#endif\n#ifdef ALBEDOCOLOR\ncolor*=albedoColor.xyz;\n#endif\nreflectivity.rgb=mix(vec3(0.04),color,metal);\n#else\n#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nreflectivity=texture2D(reflectivitySampler,vReflectivityUV);\n#ifdef GAMMAREFLECTIVITYTEXTURE\nreflectivity.rgb=toLinearSpace(reflectivity.rgb);\n#endif\n#else \n#ifdef REFLECTIVITYCOLOR\nreflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0;\n#endif\n#endif\n#ifdef GLOSSINESSS\nreflectivity.a*=glossiness; \n#endif\n#endif\ngl_FragData[REFLECTIVITY_INDEX]=reflectivity;\n#endif\n}\n";Ft.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;";Ft.IncludesShadersStore.geometryUboDeclaration="#include\n";Ft.ShadersStore.geometryVertexShader="precision highp float;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include<__decl__geometryVertex>\n#include\nattribute vec3 position;attribute vec3 normal;\n#ifdef NEED_UV\nvarying vec2 vUV;\n#ifdef ALPHATEST\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef BUMP\nuniform mat4 bumpMatrix;varying vec2 vBumpUV;\n#endif\n#ifdef REFLECTIVITY\nuniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef BUMP\nvarying mat4 vWorldView;\n#endif\n#ifdef BUMP\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nuniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include\n#include\nvec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0));\n#ifdef BUMP\nvWorldView=view*finalWorld;vNormalW=normalUpdated;\n#else\n#ifdef NORMAL_WORLDSPACE\nvNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#else\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));\n#endif\n#endif\nvViewPos=view*worldPos;\n#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n#if defined(POSITION) || defined(BUMP)\nvPositionW=worldPos.xyz/worldPos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#include\n#ifdef NEED_UV\n#ifdef UV1\n#if defined(ALPHATEST) && defined(ALPHATEST_UV1)\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#else\nvUV=uv;\n#endif\n#ifdef BUMP_UV1\nvBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV1\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV1\nvAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#endif\n#ifdef UV2\n#if defined(ALPHATEST) && defined(ALPHATEST_UV2)\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#else\nvUV=uv2;\n#endif\n#ifdef BUMP_UV2\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV2\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV2\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#endif\n#include\n}\n";const yT=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];jr(yT);class AT{get normalsAreUnsigned(){return this._normalsAreUnsigned}_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add((()=>{})))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===AT.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===AT.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===AT.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===AT.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===AT.NORMAL_TEXTURE_TYPE&&(this._normalIndex=t)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case AT.POSITION_TEXTURE_TYPE:return this._positionIndex;case AT.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case AT.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case AT.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case AT.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return-1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return"object"==typeof this._ratioOrDimensions?1:this._ratioOrDimensions}constructor(e,t=1,i=15,s){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new j(0,0,0,0),this._clearDepthColor=new j(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=s||{},AT._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const s=[],r=[Ki.PositionKind,Ki.NormalKind],n=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(s.push("#define ALPHATEST"),s.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&th.BumpTextureEnabled&&(s.push("#define BUMP"),s.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(i.metallicRoughnessTexture&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!=i.metallic&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),t=!0),null!=i.roughness&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),t=!0),t&&(i.baseTexture&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),e=!0),i.baseColor&&s.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(i.specularGlossinessTexture?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor&&s.push("#define REFLECTIVITYCOLOR"),null!=i.glossiness&&s.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(i.metallicTexture&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!=i.metallic&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),t=!0),null!=i.roughness&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),t=!0),t?(i.albedoTexture&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),e=!0),i.albedoColor&&s.push("#define ALBEDOCOLOR")):(i.reflectivityTexture?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):i.reflectivityColor&&s.push("#define REFLECTIVITYCOLOR"),null!=i.microSurface&&s.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(i.specularTexture&&(s.push("#define REFLECTIVITYTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),i.specularColor&&s.push("#define REFLECTIVITYCOLOR"))}e&&(s.push("#define NEED_UV"),n.isVerticesDataPresent(Ki.UVKind)&&(r.push(Ki.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(Ki.UV2Kind)&&(r.push(Ki.UV2Kind),s.push("#define UV2")))}this._linkedWithPrePass&&(s.push("#define PREPASS"),-1!==this._depthIndex&&(s.push("#define DEPTH_INDEX "+this._depthIndex),s.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(s.push("#define NORMAL_INDEX "+this._normalIndex),s.push("#define PREPASS_NORMAL"))),this._enablePosition&&(s.push("#define POSITION"),s.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(s.push("#define VELOCITY"),s.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(n)&&s.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(s.push("#define REFLECTIVITY"),s.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&s.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&s.push("#define ENCODE_NORMAL"),n.useBones&&n.computeBonesUsingShaders&&n.skeleton?(r.push(Ki.MatricesIndicesKind),r.push(Ki.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(Ki.MatricesIndicesExtraKind),r.push(Ki.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BONETEXTURE "+n.skeleton.isUsingTextureForMatrices),s.push("#define BonesPerMesh "+(n.skeleton.bones.length+1))):(s.push("#define NUM_BONE_INFLUENCERS 0"),s.push("#define BONETEXTURE false"),s.push("#define BonesPerMesh 0"));const o=n.morphTargetManager;let a=0;o&&(a=o.numMaxInfluencers||o.numInfluencers,a>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+a),o.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),tn(r,n,a))),t&&(s.push("#define INSTANCES"),rn(r,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES")),this._linkedWithPrePass?s.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):s.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),$r(i,this._scene,s);const l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),c=h.defines,u=s.join("\n");return c!==u&&h.setEffect(l.createEffect("geometry",{attributes:r,uniformsNames:yT,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler"],defines:u,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:a}},l),u),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.getGBuffer().dispose()}_assignRenderTargetIndices(){const e=[],t=[];let i=2;return e.push("gBuffer_Depth","gBuffer_Normal"),t.push(this._textureTypesAndFormats[AT.DEPTH_TEXTURE_TYPE]),t.push(this._textureTypesAndFormats[AT.NORMAL_TEXTURE_TYPE]),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[AT.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[AT.VELOCITY_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[AT.REFLECTIVITY_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i,s]=this._assignRenderTargetIndices();let r=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?r=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(r=2);const n=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],a=[];for(const e of s)e?(o.push(e.textureType),a.push(e.textureFormat)):(o.push(r),a.push(5));if(this._normalsAreUnsigned=11===o[AT.NORMAL_TEXTURE_TYPE]||13===o[AT.NORMAL_TEXTURE_TYPE],this._multiRenderTarget=new Am("gBuffer",n,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:o,formats:a,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=Zn.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=Zn.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const l=[!0],h=[!1],c=[!0];for(let e=1;e{e.bindAttachments(this.useSpecificClearForDepthTexture?d:u),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(p),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(u)})),this._resizeObserver=e.onResizeObservable.add((()=>{if(this._multiRenderTarget){const t=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(t)}}));const f=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),s=this._scene,r=s.getEngine(),n=e.getMaterial();if(!n)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:B.Identity(),viewProjection:s.getTransformMatrix()},t.skeleton)){const e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=r.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances),l=i.getWorldMatrix();if(this.isReady(e,a)){const h=e._getDrawWrapper();if(!h)return;const c=h.effect;let u;r.enableEffect(h),a||t._bind(e,c,n.fillMode),this._useUbo?(on(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",s.getTransformMatrix()),c.setMatrix("view",s.getViewMatrix()));const d=t._instanceDataStorage;if(d.isFrozen||!n.backFaceCulling&&null===t.overrideMaterialSideOrientation)u=d.sideOrientation;else{const e=i._getWorldMatrixDeterminant();u=t.overrideMaterialSideOrientation,null===u&&(u=n.sideOrientation),e<0&&(u=u===Dn.ClockWiseSideOrientation?Dn.CounterClockWiseSideOrientation:Dn.ClockWiseSideOrientation)}if(n._preBind(h,u),n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(n.bumpTexture&&s.getEngine().getCaps().standardDerivatives&&th.BumpTextureEnabled&&(c.setFloat3("vBumpInfos",n.bumpTexture.coordinatesIndex,1/n.bumpTexture.level,n.parallaxScaleBias),c.setMatrix("bumpMatrix",n.bumpTexture.getTextureMatrix()),c.setTexture("bumpSampler",n.bumpTexture),c.setFloat2("vTangentSpaceParams",n.invertNormalMapX?-1:1,n.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===n.getClassName()?(null!==n.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",n.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",n.metallicRoughnessTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.baseTexture&&(c.setTexture("albedoSampler",n.baseTexture),c.setMatrix("albedoMatrix",n.baseTexture.getTextureMatrix())),null!==n.baseColor&&c.setColor3("albedoColor",n.baseColor)):"PBRSpecularGlossinessMaterial"===n.getClassName()?(null!==n.specularGlossinessTexture?(c.setTexture("reflectivitySampler",n.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",n.specularGlossinessTexture.getTextureMatrix())):null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor),null!==n.glossiness&&c.setFloat("glossiness",n.glossiness)):"PBRMaterial"===n.getClassName()?(null!==n.metallicTexture&&(c.setTexture("reflectivitySampler",n.metallicTexture),c.setMatrix("reflectivityMatrix",n.metallicTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.roughness||null!==n.metallic||null!==n.metallicTexture?(null!==n.albedoTexture&&(c.setTexture("albedoSampler",n.albedoTexture),c.setMatrix("albedoMatrix",n.albedoTexture.getTextureMatrix())),null!==n.albedoColor&&c.setColor3("albedoColor",n.albedoColor)):(null!==n.reflectivityTexture?(c.setTexture("reflectivitySampler",n.reflectivityTexture),c.setMatrix("reflectivityMatrix",n.reflectivityTexture.getTextureMatrix())):null!==n.reflectivityColor&&c.setColor3("reflectivityColor",n.reflectivityColor),null!==n.microSurface&&c.setFloat("glossiness",n.microSurface))):"StandardMaterial"===n.getClassName()&&(null!==n.specularTexture&&(c.setTexture("reflectivitySampler",n.specularTexture),c.setMatrix("reflectivityMatrix",n.specularTexture.getTextureMatrix())),null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor))),Kr(c,n,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices&&c.getUniformIndex("boneTextureWidth")>-1){const i=e.getTransformMatrixTexture(t);c.setTexture("boneSampler",i),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",t.skeleton.getTransformMatrices(t));this._enableVelocity&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])}nn(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c),this._enableVelocity&&(c.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),c.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),a&&t.hasThinInstances&&c.setMatrix("world",l),t._processRendering(i,e,c,n.fillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=l.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,s)=>{if((s||0===i)&&t.subMeshes)for(let i=0;i{let n;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(r.length){for(e.setColorWrite(!1),n=0;n{throw ye("GeometryBufferRendererSceneComponent")};class RT{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(ks.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),ks.prototype.enableGeometryBufferRenderer=function(e=1,t=15,i){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new AT(this,e,t,i),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},ks.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class IT{constructor(e){this.name=ts.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ts.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}AT._SceneComponentInitialization=e=>{let t=e._getComponent(ts.NAME_GEOMETRYBUFFERRENDERER);t||(t=new IT(e),e._addComponent(t))};Ft.ShadersStore.motionBlurPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize;\n#ifdef OBJECT_BASED\nuniform sampler2D velocitySampler;\n#else\nuniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\n#ifdef OBJECT_BASED\nvec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=samplesCount)\nbreak;vec2 offset=vUV+velocity*(hlim+float(i));\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset,0.0);\n#else\nresult+=texture2D(textureSampler,offset);\n#endif\n}\ngl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0;\n#else\nvec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; \nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=nSamples)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset1,0.0);\n#else\nresult+=texture2D(textureSampler,offset1);\n#endif\n}\ngl_FragColor=result/float(nSamples);\n#endif\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";class PT extends Ko{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,s,r,n,o,a=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,s,r,n,o,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",a,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new RT)),this._applyMode()}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}const i=t.indexOf(e);-1!==i&&t.splice(i,1)}}dispose(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),super.dispose(e)}_applyMode(){if(!this._geometryBufferRenderer&&!this._prePassRenderer)return J.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=B.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=5),this.onApply=e=>this._onApplyScreenBased(e))}_onApplyObjectBased(e){if(e.setVector2("screenSize",new N(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(AT.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){const t=U.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new N(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(AT.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){const e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}}static _Parse(e,t,i,s){return Pe.Parse((()=>new PT(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,s)}}ae([pe()],PT.prototype,"motionStrength",void 0),ae([pe()],PT.prototype,"motionBlurSamples",null),ae([pe()],PT.prototype,"isObjectBased",null),u("BABYLON.MotionBlurPostProcess",PT);Ft.ShadersStore.refractionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";class MT extends Ko{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,s,r,n,o,a,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,o,a,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=s,this.colorLevel=r,this.refractionTextureUrl=t,this.onActivateObservable.add((e=>{this._refTexture=this._refTexture||new Zn(t,e.getScene())})),this.onApplyObservable.add((e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)}))}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,s){return Pe.Parse((()=>new MT(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}ae([pe()],MT.prototype,"color",void 0),ae([pe()],MT.prototype,"depth",void 0),ae([pe()],MT.prototype,"colorLevel",void 0),ae([pe()],MT.prototype,"refractionTextureUrl",void 0),u("BABYLON.RefractionPostProcess",MT);Ft.ShadersStore.sharpenPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}";class DT extends Ko{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,s,r,n,null,o,void 0,null,a),this.colorAmount=1,this.edgeAmount=.3,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,s){return Pe.Parse((()=>new DT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}ae([pe()],DT.prototype,"colorAmount",void 0),ae([pe()],DT.prototype,"edgeAmount",void 0),u("BABYLON.SharpenPostProcess",DT);class OT{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(const e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){const i=this._renderEffects[e];i&&i._enable(Ii.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(Ii.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=Ii.MakeArray(e||this._cameras);if(!i)return;const s=[];let r;for(r=0;r0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){const e=Object.keys(this._renderEffects);for(const t of e){const e=this._renderEffects[t].getPostProcesses();if(e)for(const t of e)t.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}ae([pe()],OT.prototype,"_name",void 0);class NT{constructor(){this._renderPipelines={}}get supportedPipelines(){const e=[];for(const t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){const i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){const s=this._renderPipelines[e];s&&s._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._disableEffect(t,i)}update(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){const t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e]._rebuild()}dispose(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e].dispose()}}Object.defineProperty(ks.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(ts.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new wT(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new NT}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class wT{constructor(e){this.name=ts.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ts.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}}class FT extends OT{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){const e=this.bloom;this.bloom=new uT(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen),!0),this.depthOfField=new xT(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=o.getHardwareScalingLevel(),this._resizeObserver=o.onResizeObservable.add((()=>{this._hardwareScaleLevel=o.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel})),this.bloom=new uT(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new dT("ChromaticAberration",o.getRenderWidth(),o.getRenderHeight(),1,null,Zn.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new lT(o,this.ChromaticAberrationPostProcessId,(()=>this.chromaticAberration),!0),this.grain=new bT("Grain",1,null,Zn.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new lT(o,this.GrainPostProcessId,(()=>this.grain),!0);let a=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add((()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,a?Ii.SetImmediate((()=>{this._buildPipeline()})):this._buildPipeline())})),this._buildPipeline(),a=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){const e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;const e=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(const e of this._cameras)this._scene.enableDepthRenderer(e).useOnlyInActiveCamera=!0;this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add((e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())}))}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new CT("imageProcessing",1,null,Zn.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new lT(e,this.ImageProcessingPostProcessId,(()=>this.imageProcessing),!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new ET("fxaa",1,null,Zn.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new lT(e,this.FxaaPostProcessId,(()=>this.fxaa),!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add((()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)}))),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add((()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)}))),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&J.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew FT(e._name,e._name._hdr,t)),e,t,i)}}ae([pe()],FT.prototype,"sharpenEnabled",null),ae([pe()],FT.prototype,"bloomKernel",null),ae([pe()],FT.prototype,"_bloomWeight",void 0),ae([pe()],FT.prototype,"_bloomThreshold",void 0),ae([pe()],FT.prototype,"_hdr",void 0),ae([pe()],FT.prototype,"bloomWeight",null),ae([pe()],FT.prototype,"bloomThreshold",null),ae([pe()],FT.prototype,"bloomScale",null),ae([pe()],FT.prototype,"bloomEnabled",null),ae([pe()],FT.prototype,"depthOfFieldEnabled",null),ae([pe()],FT.prototype,"depthOfFieldBlurLevel",null),ae([pe()],FT.prototype,"fxaaEnabled",null),ae([pe()],FT.prototype,"samples",null),ae([pe()],FT.prototype,"imageProcessingEnabled",null),ae([pe()],FT.prototype,"glowLayerEnabled",null),ae([pe()],FT.prototype,"chromaticAberrationEnabled",null),ae([pe()],FT.prototype,"grainEnabled",null),u("BABYLON.DefaultRenderingPipeline",FT);Ft.ShadersStore.lensHighlightsPixelShader="uniform sampler2D textureSampler; \nuniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;}\nfloat w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;gl_FragColor=blurred;}";Ft.ShadersStore.depthOfFieldPixelShader="uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; \nuniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV;\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \nvec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co)\n{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);}\nvec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;}\nfloat sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;}\nfloat getBlurLevel(float size) {return min(3.0,ceil(size/1.0));}\nvec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);}\nif (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);}\ncol/=total_weight; \nif (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);}\nreturn col;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; }\nfloat edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;}\nfloat blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);}\nelse {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;}\nif (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}}\nif (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}}\n";class LT{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}}Ft.ShadersStore.ssao2PixelShader="precision highp float;uniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSAO\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base;uniform float xViewport;uniform float yViewport;uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main()\n{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=sign(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;}\nfloat sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);}\n#endif\n#ifdef BLUR\nuniform float outSize;uniform float soften;uniform float tolerance;uniform int samples;\n#ifndef BLUR_BYPASS\nuniform sampler2D depthSampler;\n#ifdef BLUR_LEGACY\n#define inline\nfloat blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;}\n#endif\n#endif\nvoid main()\n{float result=0.0;\n#ifdef BLUR_BYPASS\nresult=textureLod(textureSampler,vUV,0.0).r;\n#else\n#ifdef BLUR_H\nvec2 step=vec2(1.0/outSize,0.0);\n#else\nvec2 step=vec2(0.0,1.0/outSize);\n#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,vUV,step);\n#else\nfloat compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; ithis._originalColorPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e{if(!this._scene.activeCamera)return;const t=n?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=n?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},o.samples=this.textureSamples,o.autoClear=!1,o}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,2.3283064365386963e-10*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){const i=2*t*Math.PI,s=1-.85*e,r=Math.sqrt(1-s*s);return new w(Math.cos(i)*r,Math.sin(i)*r,s)}_generateHemisphere(){const e=this.samples,t=[];let i,s=0;for(;s{if(this._scene.activeCamera){if(e.setArray3("sampleSphere",this._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/this.samples),e.setFloat("totalStrength",this.totalStrength),e.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),e.setFloat("radius",this.radius),e.setFloat("maxZ",this.maxZ),e.setFloat("minZAspect",this.minZAspect),e.setFloat("base",this.base),e.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===or.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",BT.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const t=this._scene.getEngine().getRenderWidth()/2,i=this._scene.getEngine().getRenderHeight()/2,s=this._scene.activeCamera.orthoLeft??-t,r=this._scene.activeCamera.orthoRight??t,n=this._scene.activeCamera.orthoBottom??-i,o=this._scene.activeCamera.orthoTop??i;e.setMatrix3x3("depthProjection",BT.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",.5*(r-s)),e.setFloat("yViewport",.5*(o-n))}e.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),e.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),e.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new LT)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new Ko("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{const t=this._scene.activeCamera.viewport;e.setVector4("viewport",U.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.autoClear=!1,this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){const e=new Uint8Array(65536),t=N.Zero();for(let i=0;inew BT(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType)),e,t,i)}}BT.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],BT.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],ae([pe()],BT.prototype,"totalStrength",void 0),ae([pe()],BT.prototype,"maxZ",void 0),ae([pe()],BT.prototype,"minZAspect",void 0),ae([pe("epsilon")],BT.prototype,"_epsilon",void 0),ae([pe("samples")],BT.prototype,"_samples",void 0),ae([pe("textureSamples")],BT.prototype,"_textureSamples",void 0),ae([pe()],BT.prototype,"_forceGeometryBuffer",void 0),ae([pe()],BT.prototype,"_ratio",void 0),ae([pe()],BT.prototype,"_textureType",void 0),ae([pe()],BT.prototype,"radius",void 0),ae([pe()],BT.prototype,"base",void 0),ae([pe("bypassBlur")],BT.prototype,"_bypassBlur",void 0),ae([pe("expensiveBlur")],BT.prototype,"_expensiveBlur",void 0),ae([pe()],BT.prototype,"bilateralSamples",void 0),ae([pe()],BT.prototype,"bilateralSoften",void 0),ae([pe()],BT.prototype,"bilateralTolerance",void 0),u("BABYLON.SSAO2RenderingPipeline",BT);Ft.ShadersStore.ssaoPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords)\n{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);}\nvoid main()\n{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; ithis._originalColorPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}_attachCameras(e,t){super._attachCameras(e,t);for(const e of this._cameras)this._scene.enableDepthRenderer(e).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e{const e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e})),this._blurVPostProcess.onActivateObservable.add((()=>{const e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e}))}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){const t=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271];this._ssaoPostProcess=new Ko("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=e=>{this._firstUpdate&&(e.setArray3("sampleSphere",t),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",this.totalStrength),e.setFloat("radius",this.radius),e.setFloat("area",this.area),e.setFloat("fallOff",this.fallOff),e.setFloat("base",this.base),e.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new Ko("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",U.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const e=new Uint8Array(1048576);for(let t=0;t0.0)\nhitCoord-=dir;else\nhitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;}\nprojectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;}\n/**\n* Tests the given world position (hitCoord) according to the given reflection vector (dir)\n* until it finds a collision (means that depth is enough close to say \"it's the pixel to sample!\").\n*/\nReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)\n{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i{const i=this._geometryBufferRenderer,s=this._prePassRenderer;if(!s&&!i)return;if(i){const t=i.getTextureIndex(AT.POSITION_TEXTURE_TYPE),s=i.getTextureIndex(AT.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[s])}else if(s){const t=s.getIndex(1),i=s.getIndex(3),r=s.getIndex(6);e.setTexture("normalSampler",s.getRenderTarget().textures[r]),e.setTexture("positionSampler",s.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",s.getRenderTarget().textures[i])}const r=t.activeCamera;if(!r)return;const n=r.getViewMatrix(!0),o=r.getProjectionMatrix(!0);e.setMatrix("projection",o),e.setMatrix("view",n),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(0|this._reflectionSamples)),e.push("#define SMOOTH_STEPS "+(0|this._smoothSteps)),this.updateEffect(e.join("\n"))}static _Parse(e,t,i,s){return Pe.Parse((()=>new kT(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}ae([pe()],kT.prototype,"threshold",void 0),ae([pe()],kT.prototype,"strength",void 0),ae([pe()],kT.prototype,"reflectionSpecularFalloffExponent",void 0),ae([pe()],kT.prototype,"step",void 0),ae([pe()],kT.prototype,"roughnessFactor",void 0),ae([pe()],kT.prototype,"enableSmoothReflections",null),ae([pe()],kT.prototype,"reflectionSamples",null),ae([pe()],kT.prototype,"smoothSteps",null),u("BABYLON.ScreenSpaceReflectionPostProcess",kT);Ft.ShadersStore.standardPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];void main(void)\n{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void)\n{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminanceshadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;}\naccumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;void main(void)\n{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];void main()\n{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++)\n{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));}\naverage=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];uniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\n#include\n#endif\nvoid main()\n{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++)\n{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;uniform float averageLuminance;void main()\n{vec4 color=texture2D(textureAdderSampler,vUV);\n#ifndef AUTO_EXPOSURE\nvec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0;\n#endif\ngl_FragColor=color;}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p)\n{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);}\nfloat noise(in vec2 p)\n{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);}\nfloat fbm(vec2 p)\n{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;}\nvec3 pattern(vec2 uv)\n{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);}\nfloat luminance(vec3 color)\n{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{return vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);}\nvoid main(void)\n{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i=nSamples)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);}\ngl_FragColor=result/float(nSamples);}\n#endif\n";class GT extends OT{get exposure(){return this._fixedExposure}set exposure(e){this._fixedExposure=e,this._currentExposure=e}get hdrAutoExposure(){return this._hdrAutoExposure}set hdrAutoExposure(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){const t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join("\n"))}}get motionStrength(){return this._motionStrength}set motionStrength(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)}get objectBasedMotionBlur(){return this._isObjectBasedMotionBlur}set objectBasedMotionBlur(e){const t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()}get BloomEnabled(){return this._bloomEnabled}set BloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get DepthOfFieldEnabled(){return this._depthOfFieldEnabled}set DepthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get LensFlareEnabled(){return this._lensFlareEnabled}set LensFlareEnabled(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())}get HDREnabled(){return this._hdrEnabled}set HDREnabled(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())}get VLSEnabled(){return this._vlsEnabled}set VLSEnabled(e){if(this._vlsEnabled!==e){if(e&&!this._scene.enableGeometryBufferRenderer())return void J.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,s=null,r){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=r||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=s,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){const e=this._ratio,t=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new kT("HDRPass",t,e,null,Zn.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess})),this.addEffect(new lT(t.getEngine(),"HDRScreenSpaceReflections",(()=>this.screenSpaceReflectionPostProcess),!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new Ko("HDRPass","standard",[],[],e,null,Zn.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.originalPostProcess})),this.addEffect(new lT(t.getEngine(),"HDRPassPostProcess",(()=>this.originalPostProcess),!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(t,e/4),this._createBrightPassPostProcess(t,e/4),this._createBlurPostProcesses(t,e/4,1),this._createTextureAdderPostProcess(t,e),this.textureAdderFinalPostProcess=new Ko("HDRDepthOfFieldSource","standard",[],[],e,null,Zn.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new lT(t.getEngine(),"HDRBaseDepthOfFieldSource",(()=>this.textureAdderFinalPostProcess),!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new Ko("HDRVLSFinal","standard",[],[],e,null,Zn.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new lT(t.getEngine(),"HDRVLSFinal",(()=>this.volumetricLightFinalPostProcess),!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new Ko("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,Zn.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new lT(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",(()=>this.lensFlareFinalPostProcess),!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new Ko("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,Zn.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new lT(t.getEngine(),"HDRPostHDReDepthOfFieldSource",(()=>this.hdrFinalPostProcess),!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(t,e/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(t,e)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(t,e),this._fxaaEnabled&&(this.fxaaPostProcess=new ET("fxaa",1,null,Zn.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new lT(t.getEngine(),"HDRFxaa",(()=>this.fxaaPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&J.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){const i=new Array(32);this.downSampleX4PostProcess=new Ko("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0;const s=this.downSampleX4PostProcess.width,r=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let n=-2;n<2;n++)i[t]=(e+.5)*(1/s),i[t+1]=(n+.5)*(1/r),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new lT(e.getEngine(),"HDRDownSampleX4",(()=>this.downSampleX4PostProcess),!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new Ko("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{const t=1/this.brightPassPostProcess.width,s=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*s,i[2]=.5*t,i[3]=.5*s,i[4]=-.5*t,i[5]=-.5*s,i[6]=.5*t,i[7]=-.5*s,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new lT(e.getEngine(),"HDRBrightPass",(()=>this.brightPassPostProcess),!0))}_createBlurPostProcesses(e,t,i,s="blurWidth"){const r=e.getEngine(),n=new Jp("HDRBlurH_"+i,new N(1,0),this[s],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),o=new Jp("HDRBlurV_"+i,new N(0,1),this[s],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add((()=>{const e=n.width/r.getRenderWidth();n.kernel=this[s]*e})),o.onActivateObservable.add((()=>{const e=o.height/r.getRenderHeight();o.kernel=this.horizontalBlur?64*e:this[s]*e})),this.addEffect(new lT(e.getEngine(),"HDRBlurH"+i,(()=>n),!0)),this.addEffect(new lT(e.getEngine(),"HDRBlurV"+i,(()=>o),!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(o)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new Ko("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),e.setTexture("lensSampler",this.lensTexture),e.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new lT(e.getEngine(),"HDRTextureAdder",(()=>this.textureAdderPostProcess),!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const s=i.getGBuffer();this.volumetricLightPostProcess=new Ko("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));const r=N.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",s.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),r.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),r.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",r)}},this.addEffect(new lT(e.getEngine(),"HDRVLS",(()=>this.volumetricLightPostProcess),!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new Ko("HDRVLSMerge","standard",[],["originalSampler"],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=e=>{e.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new lT(e.getEngine(),"HDRVLSMerge",(()=>this.volumetricLightMergePostProces),!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,GT.LuminanceSteps);this.luminancePostProcess=new Ko("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const s=[];this.luminancePostProcess.onApply=e=>{const t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;s[0]=-.5*t,s[1]=.5*i,s[2]=.5*t,s[3]=.5*i,s[4]=-.5*t,s[5]=-.5*i,s[6]=.5*t,s[7]=-.5*i,e.setArray2("lumOffsets",s)},this.addEffect(new lT(e.getEngine(),"HDRLuminance",(()=>this.luminancePostProcess),!0));for(let s=GT.LuminanceSteps-1;s>=0;s--){i=Math.pow(3,s);let r="#define LUMINANCE_DOWN_SAMPLE\n";0===s&&(r+="#define FINAL_DOWN_SAMPLER");const n=new Ko("HDRLuminanceDownSample"+s,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,t);this.luminanceDownSamplePostProcesses.push(n)}let r=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach(((t,i)=>{const s=new Array(18);t.onApply=e=>{if(!r)return;let n=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)s[n]=e/r.width,s[n+1]=t/r.height,n+=2;e.setArray2("dsOffsets",s),e.setFloat("halfDestPixelSize",.5/r.width),r=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{const t=e.getEngine().readPixels(0,0,1,1),i=new F(1/16581375,1/65025,1/255,1);t.then((e=>{const t=new Uint8Array(e.buffer);this._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100}))}),this.addEffect(new lT(e.getEngine(),"HDRLuminanceDownSample"+i,(()=>t),!0))}))}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new Ko("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let s=1,r=0,n=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),r+=e.getEngine().getDeltaTime(),s<0)s=this._hdrCurrentLuminance;else{const e=(n-r)/1e3;this._hdrCurrentLuminances-this.hdrIncreaseRate*e?s-=this.hdrIncreaseRate*e:s=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/s:(s=G.Clamp(s,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",s)),n=r,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new lT(e.getEngine(),"HDR",(()=>this.hdrPostProcess),!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new Ko("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new lT(e.getEngine(),"HDRLensFlare",(()=>this.lensFlarePostProcess),!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new Ko("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new lT(e.getEngine(),"HDRLensFlareCompose",(()=>this.lensFlareComposePostProcess),!0));const i=new N(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=e=>{e.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),e.setTexture("lensColorSampler",this.lensColorTexture),e.setFloat("strength",this.lensFlareStrength),e.setFloat("ghostDispersal",this.lensFlareGhostDispersal),e.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,e.setVector2("resolution",i),e.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const s=B.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),r=B.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=e=>{if(!this._scene.activeCamera)return;e.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),e.setTexture("lensDirtSampler",this.lensFlareDirtTexture),e.setTexture("lensStarSampler",this.lensStarTexture);const t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2);let n=w.Dot(t.toVector3(),new w(1,0,0))+w.Dot(i.toVector3(),new w(0,0,1));n*=4;const o=B.FromValues(.5*Math.cos(n),-Math.sin(n),0,0,Math.sin(n),.5*Math.cos(n),0,0,0,0,1,0,0,0,0,1),a=r.multiply(o).multiply(s);e.setMatrix("lensStarMatrix",a),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new Ko("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),e.setTexture("depthSampler",this._getDepthTexture()),e.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new lT(e.getEngine(),"HDRDepthOfField",(()=>this.depthOfFieldPostProcess),!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new PT("HDRMotionBlur",e,t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new Ko("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,s=B.Identity();const r=B.Identity();let n=B.Identity();const o=N.Zero();this.motionBlurPostProcess.onApply=t=>{n=e.getProjectionMatrix().multiply(e.getViewMatrix()),n.invertToRef(r),t.setMatrix("inverseViewProjection",r),t.setMatrix("prevViewProjection",s),s=n,o.x=this.motionBlurPostProcess.width,o.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",o),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new lT(e.getEngine(),"HDRMotionBlur",(()=>this.motionBlurPostProcess),!0))}_getDepthTexture(){return this._scene.getEngine().getCaps().drawBuffersExtension?this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]:this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;enew GT(e._name,t,e._ratio)),e,t,i);return e.sourceLightId&&(s.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&Pe.Parse((()=>s.screenSpaceReflectionPostProcess),e.screenSpaceReflectionPostProcess,t,i),s}}GT.LuminanceSteps=6,ae([pe()],GT.prototype,"brightThreshold",void 0),ae([pe()],GT.prototype,"blurWidth",void 0),ae([pe()],GT.prototype,"horizontalBlur",void 0),ae([pe()],GT.prototype,"exposure",null),ae([fe("lensTexture")],GT.prototype,"lensTexture",void 0),ae([pe()],GT.prototype,"volumetricLightCoefficient",void 0),ae([pe()],GT.prototype,"volumetricLightPower",void 0),ae([pe()],GT.prototype,"volumetricLightBlurScale",void 0),ae([pe()],GT.prototype,"hdrMinimumLuminance",void 0),ae([pe()],GT.prototype,"hdrDecreaseRate",void 0),ae([pe()],GT.prototype,"hdrIncreaseRate",void 0),ae([pe()],GT.prototype,"hdrAutoExposure",null),ae([fe("lensColorTexture")],GT.prototype,"lensColorTexture",void 0),ae([pe()],GT.prototype,"lensFlareStrength",void 0),ae([pe()],GT.prototype,"lensFlareGhostDispersal",void 0),ae([pe()],GT.prototype,"lensFlareHaloWidth",void 0),ae([pe()],GT.prototype,"lensFlareDistortionStrength",void 0),ae([pe()],GT.prototype,"lensFlareBlurWidth",void 0),ae([fe("lensStarTexture")],GT.prototype,"lensStarTexture",void 0),ae([fe("lensFlareDirtTexture")],GT.prototype,"lensFlareDirtTexture",void 0),ae([pe()],GT.prototype,"depthOfFieldDistance",void 0),ae([pe()],GT.prototype,"depthOfFieldBlurWidth",void 0),ae([pe()],GT.prototype,"motionStrength",null),ae([pe()],GT.prototype,"objectBasedMotionBlur",null),ae([pe()],GT.prototype,"_ratio",void 0),ae([pe()],GT.prototype,"BloomEnabled",null),ae([pe()],GT.prototype,"DepthOfFieldEnabled",null),ae([pe()],GT.prototype,"LensFlareEnabled",null),ae([pe()],GT.prototype,"HDREnabled",null),ae([pe()],GT.prototype,"VLSEnabled",null),ae([pe()],GT.prototype,"MotionBlurEnabled",null),ae([pe()],GT.prototype,"fxaaEnabled",null),ae([pe()],GT.prototype,"screenSpaceReflectionsEnabled",null),ae([pe()],GT.prototype,"volumetricLightStepsCount",null),ae([pe()],GT.prototype,"motionBlurSamples",null),ae([pe()],GT.prototype,"samples",null),u("BABYLON.StandardRenderingPipeline",GT);class zT{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}Ft.IncludesShadersStore.screenSpaceRayTrace="float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }\n/**\nparam csOrigin Camera-space ray origin,which must be \nwithin the view volume and must have z>0.01 and project within the valid screen rectangle\nparam csDirection Unit length camera-space ray direction\nparam projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \n(**not** [-1,+1] normalized device coordinates).\nparam csZBuffer The camera-space Z buffer\nparam csZBufferSize Dimensions of csZBuffer\nparam csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\nparam nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\nfor clipping rays headed towards the camera\nparam stride Step in horizontal or vertical pixels between samples. This is a float\nbecause integer math is slow on GPUs,but should be set to an integer>=1\nparam jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\nto conceal banding artifacts,plus the stride ray offset.\nparam maxSteps Maximum number of iterations. Higher gives better images but may be slow\nparam maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\nparam selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.\n1 is a reasonable value,depending on the scene you may need to set this value to 2\nparam hitPixel Pixel coordinates of the first intersection with the scene\nparam numIterations number of iterations performed\nparam csHitPoint Camera space location of the ray hit\n*/\n#define inline\nbool traceScreenSpaceRay1(\nvec3 csOrigin,\nvec3 csDirection,\nmat4 projectToPixelMatrix,\nsampler2D csZBuffer,\nvec2 csZBufferSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nsampler2D csZBackBuffer,\nfloat csZBackSizeFactor,\n#endif\nfloat csZThickness,\nfloat nearPlaneZ,\nfloat stride,\nfloat jitterFraction,\nfloat maxSteps,\nfloat maxRayTraceDistance,\nfloat selfCollisionNumSkip,\nout vec2 startPixel,\nout vec2 hitPixel,\nout vec3 csHitPoint,\nout float numIterations\n#ifdef SSRAYTRACE_DEBUG\n,out vec3 debugColor\n#endif\n)\n{\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\n#else\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);}\nif ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));}\nP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\n#endif\nP1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { \nfloat t=rayZMin; rayZMin=rayZMax; rayZMax=t;}\nsceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\n#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\n#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\n#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\n#endif\n#endif\n}\npqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;}\n#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 ||\n(refinementStepCount<=stride*1.4) &&\n(rayZMaxend) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);}\n#endif\nreturn hit;}\n/**\ntexCoord: in the [0,1] range\ndepth: depth in view space (range [znear,zfar]])\n*/\nvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef ORTHOGRAPHIC_CAMERA\nndc.z=-projection[2].z*depth+projection[3].z;\n#else\nndc.z=-projection[2].z-projection[3].z/depth;\n#endif\n#else\n#ifdef ORTHOGRAPHIC_CAMERA\nndc.z=projection[2].z*depth+projection[3].z;\n#else\nndc.z=projection[2].z+projection[3].z/depth;\n#endif\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\n";Ft.ShadersStore.screenSpaceReflection2PixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nuniform sampler2D backDepthSampler;uniform float backSizeFactor;\n#endif\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nuniform samplerCube envCubeSampler;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize;\n#endif\n#endif\nuniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold;\n#include\n#include\n#include\nvec3 hash(vec3 a)\n{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);}\nfloat computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0;\n#ifdef SSR_ATTENUATE_SCREEN_BORDERS\nvec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE\nattenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\nattenuation*=1.0-(numIterations/maxSteps);\n#endif\n#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION\nvec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation;\n#endif\nreturn attenuation;}\n#endif\nvoid main()\n{\n#ifdef SSR_SUPPORTED\nvec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {\n#ifdef SSR_USE_BLUR\ngl_FragColor=vec4(0.);\n#else\ngl_FragColor=colorFull;\n#endif\nreturn;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; \n#ifdef SSR_DECODE_NORMAL\ncsNormal=csNormal*2.0-1.0;\n#endif\n#ifdef SSR_NORMAL_IS_IN_WORLDSPACE\ncsNormal=(view*vec4(csNormal,0.0)).xyz;\n#endif\nfloat depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);\n#ifdef ORTHOGRAPHIC_CAMERA\nvec3 csViewDirection=vec3(0.,0.,1.);\n#else\nvec3 csViewDirection=normalize(csPosition);\n#endif\nvec3 csReflectedVector=reflect(csViewDirection,csNormal);\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0));\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nvec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition);\n#endif\n#ifdef SSR_INVERTCUBICMAP\nwReflectedVector.y*=-1.0;\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nwReflectedVector.z*=-1.0;\n#endif\nvec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz;\n#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\nenvColor=toLinearSpace(envColor);\n#endif\n#else\nvec3 envColor=color;\n#endif\nfloat reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations;\n#ifdef SSRAYTRACE_DEBUG\nvec3 debugColor;\n#endif\n#ifdef SSR_ATTENUATE_FACING_CAMERA\nreflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));\n#endif\nif (reflectionAttenuation>0.0) {\n#ifdef SSR_USE_BLUR\nvec3 jitt=vec3(0.);\n#else\nfloat roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; \n#endif\nvec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); \nrayHasHit=traceScreenSpaceRay1(\ncsPosition,\nnormalize(csReflectedVector+jitt),\nprojectionPixel,\ndepthSampler,\ntexSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nbackDepthSampler,\nbackSizeFactor,\n#endif\nthickness,\nnearPlaneZ,\nstepSize,\njitter,\nmaxSteps,\nmaxDistance,\nselfCollisionNumSkip,\nstartPixel,\nhitPixel,\nhitPoint,\nnumIterations\n#ifdef SSRAYTRACE_DEBUG\n,debugColor\n#endif\n);}\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=vec4(debugColor,1.);return;\n#endif\nvec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb;\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\nreflectedColor=toLinearSpace(reflectedColor);\n#endif\nreflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;}\n#ifndef SSR_BLEND_WITH_FRESNEL\nSSR*=fresnel;\n#endif\n#ifdef SSR_USE_BLUR\nfloat blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; \nfloat a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);}\ngl_FragColor=vec4(SSR,blur_radius/255.0); \n#else\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,colorFull.a);\n#endif\n#else\ngl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0);\n#endif\n}\n";Ft.ShadersStore.screenSpaceReflection2BlurPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator)\n{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;}\nvoid main()\n{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;}\nfloat blurRadius=colorFull.a*255.0; \nvec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);}\n";Ft.ShadersStore.screenSpaceReflection2BlurCombinerPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV;\n#include\n#ifdef SSR_BLEND_WITH_FRESNEL\n#include\n#include\nuniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#endif\nvoid main()\n{\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=texture2D(textureSampler,vUV);\n#else\nvec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,color.a);\n#endif\n}\n";const WT=B.Compose(new w(.5,.5,.5),L.Identity(),new w(.5,.5,.5)),HT=B.Compose(new w(.5,.5,1),L.Identity(),new w(.5,.5,0));class XT extends OT{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}get reflectivityThreshold(){return this._reflectivityThreshold}set reflectivityThreshold(e){e!==this._reflectivityThreshold&&(0===e&&0!==this._reflectivityThreshold||0!==e&&0===this._reflectivityThreshold?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)}get ssrDownsample(){return this._ssrDownsample}set ssrDownsample(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())}get blurDispersionStrength(){return this._blurDispersionStrength}set blurDispersionStrength(e){if(e===this._blurDispersionStrength)return;const t=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;this._blurDispersionStrength=e,t&&this._buildPipeline()}_useBlur(){return this._blurDispersionStrength>0}get blurDownsample(){return this._blurDownsample}set blurDownsample(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e,this._updateEffectDefines()}get environmentTextureIsProbe(){return this._environmentTextureIsProbe}set environmentTextureIsProbe(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()}get attenuateScreenBorders(){return this._attenuateScreenBorders}set attenuateScreenBorders(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())}get attenuateIntersectionDistance(){return this._attenuateIntersectionDistance}set attenuateIntersectionDistance(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())}get attenuateIntersectionIterations(){return this._attenuateIntersectionIterations}set attenuateIntersectionIterations(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())}get attenuateFacingCamera(){return this._attenuateFacingCamera}set attenuateFacingCamera(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())}get attenuateBackfaceReflection(){return this._attenuateBackfaceReflection}set attenuateBackfaceReflection(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())}get clipToFrustum(){return this._clipToFrustum}set clipToFrustum(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())}get useFresnel(){return this._useFresnel}set useFresnel(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())}get enableAutomaticThicknessComputation(){return this._enableAutomaticThicknessComputation}set enableAutomaticThicknessComputation(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())}get backfaceDepthRenderer(){return this._depthRenderer}get backfaceDepthTextureDownsample(){return this._backfaceDepthTextureDownsample}set backfaceDepthTextureDownsample(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())}get backfaceForceDepthWriteTransparentMeshes(){return this._backfaceForceDepthWriteTransparentMeshes}set backfaceForceDepthWriteTransparentMeshes(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){const e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,s=!1,r=0){if(super(t.getEngine(),e),this.SSRRenderEffect="SSRRenderEffect",this.SSRBlurRenderEffect="SSRBlurRenderEffect",this.SSRCombineRenderEffect="SSRCombineRenderEffect",this._samples=1,this.maxDistance=1e3,this.step=1,this.thickness=.5,this.strength=1,this.reflectionSpecularFalloffExponent=1,this.maxSteps=1e3,this.roughnessFactor=.2,this.selfCollisionNumSkip=1,this._reflectivityThreshold=.04,this._ssrDownsample=0,this._blurDispersionStrength=.03,this._blurDownsample=0,this._enableSmoothReflections=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=r,this._forceGeometryBuffer=s,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0)}else{const e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty())}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){const e=this._scene.getEngine(),t=this._prePassRenderer;let i={width:e.getRenderWidth(),height:e.getRenderHeight()};if(t&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const e=t.getRenderTarget();e&&e.textures&&(i=e.textures[t.getIndex(4)].getSize())}else this._ssrPostProcess?.inputTexture&&(i.width=this._ssrPostProcess.inputTexture.width,i.height=this._ssrPostProcess.inputTexture.height);return i}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&e.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(e.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&e.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&e.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&e.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&e.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&e.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&e.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&e.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&e.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&e.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&e.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&e.push("#define SSR_USE_BLUR"),this._debug&&e.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&e.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&e.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&e.push("#define SSR_BLEND_WITH_FRESNEL"),0===this._reflectivityThreshold&&e.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(this._geometryBufferRenderer?.generateNormalsInWorldSpace??this._prePassRenderer?.generateNormalsInWorldSpace)&&e.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),this._geometryBufferRenderer?.normalsAreUnsigned&&e.push("#define SSR_DECODE_NORMAL");const t=this._cameras?.[0];t&&1===t.mode&&e.push("#define ORTHOGRAPHIC_CAMERA"),this._ssrPostProcess?.updateEffect(e.join("\n"))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){const e=this._cameras?.[0];e&&(this._depthRendererCamera=e,this._depthRenderer=new v_(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),e.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new lT(e,this.SSRRenderEffect,(()=>this._ssrPostProcess),!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new lT(e,this.SSRBlurRenderEffect,(()=>[this._blurPostProcessX,this._blurPostProcessY]),!0)),this.addEffect(new lT(e,this.SSRCombineRenderEffect,(()=>this._blurCombinerPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;const e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),s=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));t.width===i&&t.height===s||this._depthRenderer.getDepthMap().resize({width:i,height:s})}_disposeDepthRenderer(){if(this._depthRenderer){if(this._depthRendererCamera){const e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap())??-1;-1!==e&&this._depthRendererCamera.customRenderTargets.splice(e,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){for(let e=0;e{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const i=t.getTextureIndex(AT.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){const t=i.getIndex(5),s=i.getIndex(3),r=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[r]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[s])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const s=this._scene.activeCamera;if(!s)return;const r=s.getViewMatrix(),n=s.getProjectionMatrix();n.invertToRef(U.Matrix[0]),r.invertToRef(U.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",r),e.setMatrix("invView",U.Matrix[1]),e.setMatrix("invProjectionMatrix",U.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",s.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const o=this._getTextureSize();B.ScalingToRef(o.width,o.height,1,U.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?HT:WT,U.Matrix[3]),U.Matrix[3].multiplyToRef(U.Matrix[2],U.Matrix[4]),e.setMatrix("projectionPixel",U.Matrix[4]),this._environmentTexture&&(e.setTexture("envCubeSampler",this._environmentTexture),this._environmentTexture.boundingBoxSize&&(e.setVector3("vReflectionPosition",this._environmentTexture.boundingBoxPosition),e.setVector3("vReflectionSize",this._environmentTexture.boundingBoxSize)))},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new zT)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new Ko("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add((e=>{const t=this._blurPostProcessX?.inputTexture.width??this._scene.getEngine().getRenderWidth();e.setFloat2("texelOffsetScale",this._blurDispersionStrength/t,0)})),this._blurPostProcessY=new Ko("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add((e=>{const t=this._blurPostProcessY?.inputTexture.height??this._scene.getEngine().getRenderHeight();e.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/t)}));const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"];let s="";this._debug&&(s+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(s+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(s+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(s+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(s+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new Ko("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,s,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add((e=>{const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(i||t){if(i&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const t=i.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[i.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(t){const i=t.getTextureIndex(AT.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),this.useFresnel&&(e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("depthSampler",t.getGBuffer().textures[0]))}else if(i){const t=i.getIndex(3);if(e.setTexture("reflectivitySampler",i.getRenderTarget().textures[t]),this.useFresnel){const t=i.getIndex(5),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const t=this._scene.activeCamera;if(t){const i=t.getProjectionMatrix();i.invertToRef(U.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",U.Matrix[0])}}}}))}serialize(){const e=Pe.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return Pe.Parse((()=>new XT(e._name,t,e._ratio)),e,t,i)}}ae([pe()],XT.prototype,"samples",null),ae([pe()],XT.prototype,"maxDistance",void 0),ae([pe()],XT.prototype,"step",void 0),ae([pe()],XT.prototype,"thickness",void 0),ae([pe()],XT.prototype,"strength",void 0),ae([pe()],XT.prototype,"reflectionSpecularFalloffExponent",void 0),ae([pe()],XT.prototype,"maxSteps",void 0),ae([pe()],XT.prototype,"roughnessFactor",void 0),ae([pe()],XT.prototype,"selfCollisionNumSkip",void 0),ae([pe()],XT.prototype,"_reflectivityThreshold",void 0),ae([pe("_ssrDownsample")],XT.prototype,"_ssrDownsample",void 0),ae([pe()],XT.prototype,"ssrDownsample",null),ae([pe("blurDispersionStrength")],XT.prototype,"_blurDispersionStrength",void 0),ae([pe("blurDownsample")],XT.prototype,"_blurDownsample",void 0),ae([pe("enableSmoothReflections")],XT.prototype,"_enableSmoothReflections",void 0),ae([pe("environmentTexture")],XT.prototype,"_environmentTexture",void 0),ae([pe("environmentTextureIsProbe")],XT.prototype,"_environmentTextureIsProbe",void 0),ae([pe("attenuateScreenBorders")],XT.prototype,"_attenuateScreenBorders",void 0),ae([pe("attenuateIntersectionDistance")],XT.prototype,"_attenuateIntersectionDistance",void 0),ae([pe("attenuateIntersectionIterations")],XT.prototype,"_attenuateIntersectionIterations",void 0),ae([pe("attenuateFacingCamera")],XT.prototype,"_attenuateFacingCamera",void 0),ae([pe("attenuateBackfaceReflection")],XT.prototype,"_attenuateBackfaceReflection",void 0),ae([pe("clipToFrustum")],XT.prototype,"_clipToFrustum",void 0),ae([pe("useFresnel")],XT.prototype,"_useFresnel",void 0),ae([pe("enableAutomaticThicknessComputation")],XT.prototype,"_enableAutomaticThicknessComputation",void 0),ae([pe("backfaceDepthTextureDownsample")],XT.prototype,"_backfaceDepthTextureDownsample",void 0),ae([pe("backfaceForceDepthWriteTransparentMeshes")],XT.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),ae([pe("isEnabled")],XT.prototype,"_isEnabled",void 0),ae([pe("inputTextureColorIsInGammaSpace")],XT.prototype,"_inputTextureColorIsInGammaSpace",void 0),ae([pe("generateOutputInGammaSpace")],XT.prototype,"_generateOutputInGammaSpace",void 0),ae([pe("debug")],XT.prototype,"_debug",void 0),u("BABYLON.SSRRenderingPipeline",XT);Ft.ShadersStore.taaPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D historySampler;uniform float factor;void main() {vec4 c=texelFetch(textureSampler,ivec2(gl_FragCoord.xy),0);vec4 h=texelFetch(historySampler,ivec2(gl_FragCoord.xy),0);gl_FragColor=mix(h,c,factor);}\n";class YT extends OT{set samples(e){this._samples!==e&&(this._samples=e,this._hs.regenerate(e))}get samples(){return this._samples}set msaaSamples(e){this._msaaSamples!==e&&(this._msaaSamples=e,this._taaPostProcess&&(this._taaPostProcess.samples=e))}get msaaSamples(){return this._msaaSamples}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&(this._firstUpdate=!0,this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras))):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get scene(){return this._scene}get isSupported(){return this._scene.getEngine().getCaps().texelFetch}constructor(e,t,i,s=0){const r=t.getEngine();super(r,e),this.TAARenderEffect="TAARenderEffect",this.TAAPassEffect="TAAPassEffect",this._samples=8,this._msaaSamples=1,this.factor=.05,this.disableOnCameraMove=!0,this._isEnabled=!0,this._isDirty=!1,this._camerasToBeAttached=[],this._pingpong=0,this._firstUpdate=!0,this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._hs=new yg(this.samples),this.isSupported&&(this._createPingPongTextures(r.getRenderWidth(),r.getRenderHeight()),t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline())}getClassName(){return"TAARenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._ping.dispose(),this._pong.dispose(),super.dispose()}_createPingPongTextures(e,t){const i=this._scene.getEngine();this._ping?.dispose(),this._pong?.dispose(),this._ping=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._pong=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._hs.setDimensions(e/2,t/2),this._firstUpdate=!0}_updateEffectDefines(){this._taaPostProcess?.updateEffect([].join("\n"))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._createTAAPostProcess(),this.addEffect(new lT(e,this.TAARenderEffect,(()=>this._taaPostProcess),!0)),this._createPassPostProcess(),this.addEffect(new lT(e,this.TAAPassEffect,(()=>this._passPostProcess),!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_disposePostProcesses(){for(let e=0;e{const e=this._scene.activeCamera;if(this._taaPostProcess?.width!==this._ping.width||this._taaPostProcess?.height!==this._ping.height){const e=this._scene.getEngine();this._createPingPongTextures(e.getRenderWidth(),e.getRenderHeight())}if(e&&!e.hasMoved)if(e.mode===or.PERSPECTIVE_CAMERA){const t=e.getProjectionMatrix();t.setRowFromFloats(2,this._hs.x,this._hs.y,t.m[10],t.m[11])}else{const t=e.getProjectionMatrix(!0);t.setRowFromFloats(3,this._hs.x+t.m[12],this._hs.y+t.m[13],t.m[14],t.m[15])}this._passPostProcess&&(this._passPostProcess.inputTexture=this._pingpong?this._ping:this._pong),this._pingpong=1^this._pingpong,this._hs.next()})),this._taaPostProcess.onApplyObservable.add((e=>{const t=this._scene.activeCamera;e._bindTexture("historySampler",this._pingpong?this._ping.texture:this._pong.texture),e.setFloat("factor",t?.hasMoved&&this.disableOnCameraMove||this._firstUpdate?1:this.factor),this._firstUpdate=!1}))}_createPassPostProcess(){const e=this._scene.getEngine();this._passPostProcess=new Ml("TAAPass",1,null,1,e),this._passPostProcess.inputTexture=this._ping,this._passPostProcess.autoClear=!1}serialize(){const e=Pe.Serialize(this);return e.customType="TAARenderingPipeline",e}static Parse(e,t,i){return Pe.Parse((()=>new YT(e._name,t,e._ratio)),e,t,i)}}ae([pe("samples")],YT.prototype,"_samples",void 0),ae([pe("msaaSamples")],YT.prototype,"_msaaSamples",void 0),ae([pe()],YT.prototype,"factor",void 0),ae([pe()],YT.prototype,"disableOnCameraMove",void 0),ae([pe("isEnabled")],YT.prototype,"_isEnabled",void 0),u("BABYLON.TAARenderingPipeline",YT);var jT;Ft.ShadersStore.tonemapPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{return dot(c,vec3(0.22,0.707,0.071));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);}",function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(jT||(jT={}));Ft.ShadersStore.volumetricLightScatteringPixelShader="uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add((e=>{this._updateMeshScreenCoordinates(l),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)}))}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){const i=e.getMesh();if(i===this.mesh&&i.material)return i.material.isReady(i);const s=i._internalAbstractMeshDataInfo._materialForRenderPass?.[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(i,e,t);const r=[],n=[Ki.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&r.push("#define ALPHATEST"),i.isVerticesDataPresent(Ki.UVKind)&&(n.push(Ki.UVKind),r.push("#define UV1")),i.isVerticesDataPresent(Ki.UV2Kind)&&(n.push(Ki.UV2Kind),r.push("#define UV2"))),i.useBones&&i.computeBonesUsingShaders?(n.push(Ki.MatricesIndicesKind),n.push(Ki.MatricesWeightsKind),r.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),r.push("#define BonesPerMesh "+(i.skeleton?i.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0"),t&&(r.push("#define INSTANCES"),rn(n),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));const a=e._getDrawWrapper(void 0,!0),l=a.defines,h=r.join("\n");return l!==h&&a.setEffect(i.getScene().getEngine().createEffect("volumetricLightScatteringPass",n,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],h,void 0,void 0,void 0,{maxSimultaneousMorphTargets:i.numBoneInfluencers}),h),a.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){const t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==t&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)}_createPass(e,t){const i=e.getEngine();this._volumetricLightScatteringRTT=new da("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=Zn.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=Zn.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const r=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh();if(this._meshExcluded(t))return;i._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const s=e.getMaterial();if(!s)return;const r=t.getScene(),n=r.getEngine();n.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=n.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances);if(this._isReady(e,a)){const l=i._internalAbstractMeshDataInfo._materialForRenderPass?.[n.currentRenderPassId];let h=e._getDrawWrapper();if(t!==this.mesh||h||(h=s._getDrawWrapper()),!h)return;const c=h.effect;if(n.enableEffect(h),a||t._bind(e,c,s.fillMode),t===this.mesh)s.bind(i.getWorldMatrix(),t);else if(l)l.bindForSubMesh(i.getWorldMatrix(),i,e);else{if(c.setMatrix("viewProjection",r.getTransformMatrix()),s&&s.needAlphaTesting()){const e=s.getAlphaTestTexture();c.setTexture("diffuseSampler",e),e&&c.setMatrix("diffuseMatrix",e.getTextureMatrix())}t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&c.setMatrices("mBones",t.skeleton.getTransformMatrices(t))}a&&t.hasThinInstances&&c.setMatrix("world",i.getWorldMatrix()),t._processRendering(i,e,c,Dn.TriangleFillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}};let n;const o=new j(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((()=>{n=e.clearColor,e.clearColor=o})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((()=>{e.clearColor=n})),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,s)=>{if((s||0===t)&&e.subMeshes)for(let t=0;t{const o=e.getEngine();let a;if(n.length){for(o.setColorWrite(!1),a=0;ae._alphaIndex>t._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0)),o.setAlphaMode(2),a=0;a{e.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));const t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}):J.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=y.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,s){return Pe.Parse((()=>new KT(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}ae([pe()],KT.prototype,"ridge",void 0),ae([pe()],KT.prototype,"valley",void 0),u("BABYLON.ScreenSpaceCurvaturePostProcess",KT);Ft.IncludesShadersStore.boundingBoxRendererFragmentDeclaration="uniform vec4 color;\n";Ft.IncludesShadersStore.boundingBoxRendererUboDeclaration="#ifdef WEBGL2\nuniform vec4 color;uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#else\nlayout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;};\n#endif\n";Ft.ShadersStore.boundingBoxRendererPixelShader="#include<__decl__boundingBoxRendererFragment>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.IncludesShadersStore.boundingBoxRendererVertexDeclaration="uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n";Ft.ShadersStore.boundingBoxRendererVertexShader="attribute vec3 position;\n#include<__decl__boundingBoxRendererVertex>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec4 worldPos=world*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n",Object.defineProperty(ks.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),ks.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new qT(this)),this._boundingBoxRenderer},Object.defineProperty(Wr.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class qT{constructor(e){this.name=ts.NAME_BOUNDINGBOXRENDERER,this.frontColor=new Y(1,1,1),this.backColor=new Y(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new g,this.onAfterBoxRenderingObservable=new g,this.onResourcesReadyObservable=new g,this.enabled=!0,this.renderList=new Mi(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new ji(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new ji(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(ts.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(ts.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(ts.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(ts.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){const i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){const t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new fc("colorShader",this.scene,"boundingBoxRenderer",{attributes:[Ki.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new fc("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[Ki.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=ic({size:1});this._vertexBuffers[Ki.PositionKind]=new Ki(e,t.positions,Ki.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){const e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){const e=this._vertexBuffers[Ki.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){if(0===this.renderList.length||!this.enabled)return;if(this._prepareResources(),!this._colorShader.isReady())return;const t=this.scene.getEngine();t.setDepthWrite(!1);const i=this.scene.getTransformMatrix();for(let s=0;s{let t=e._getComponent(ts.NAME_DEPTHRENDERER);t||(t=new QT(e),e._addComponent(t))};Ft.ShadersStore.oitFinalPixelShader="precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4(\nfrontColor.rgb+alphaMultiplier*backColor.rgb,\nfrontColor.a+backColor.a\n);}";Ft.ShadersStore.oitBackBlendPixelShader="precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { \ndiscard;}}";class ZT{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class JT{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new Mi(10),this._excludedSubMeshes=new Mi(10),this._excludedMeshes=[],this._colorCache=[new j(JT._DEPTH_CLEAR_VALUE,JT._DEPTH_CLEAR_VALUE,0,0),new j(-JT._MIN_DEPTH,JT._MAX_DEPTH,0,0),new j(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,e.enablePrePassRenderer()){for(let e=0;e\nuniform vec4 color;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.lineVertexShader="#include\n#include\nattribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio;\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nmat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}",Wr.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},Wr.prototype.enableEdgesRendering=function(e=.95,t=!1,i){return this.disableEdgesRendering(),this._edgesRenderer=new iS(this,e,t,!0,i),this},Object.defineProperty(Wr.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),_c.prototype.enableEdgesRendering=function(e=.95,t=!1){return this.disableEdgesRendering(),this._edgesRenderer=new sS(this,e,t),this},mc.prototype.enableEdgesRendering=function(e=.95,t=!1){return _c.prototype.enableEdgesRendering.apply(this,arguments),this};class tS{constructor(){this.edges=[],this.edgesConnectedCount=0}}class iS{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){const t=new fc("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,s=!0,r){this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new Mi(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=r??null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new gr(e.getEngine())),this._prepareRessources(),s&&(r?.useAlternateEdgeFinder??1?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add((()=>{this._rebuild()})),this._meshDisposeObserver=this._source.onDisposeObservable.add((()=>{this.dispose()}))}_prepareRessources(){this._lineShader||(this._lineShader=iS._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[Ki.PositionKind];e&&e._rebuild(),e=this._buffers[Ki.NormalKind],e&&e._rebuild();const t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)}dispose(){this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let e=this._buffers[Ki.PositionKind];e&&(e.dispose(),this._buffers[Ki.PositionKind]=null),e=this._buffers[Ki.NormalKind],e&&(e.dispose(),this._buffers[Ki.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),this._drawWrapper?.dispose()}_processEdgeForAdjacencies(e,t,i,s,r){return e===i&&t===s||e===s&&t===i?0:e===s&&t===r||e===r&&t===s?1:e===r&&t===i||e===i&&t===r?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,s,r){const n=1e-10;return e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(s,n)||e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(i,n)?0:e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(r,n)||e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(s,n)?1:e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(i,n)||e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(r,n)?2:-1}_checkEdge(e,t,i,s,r){let n;n=void 0===t||w.Dot(i[e],i[t]){i>=0&&t.push(i);for(let i=0;i=e[0].length&&e[1].length>=e[2].length?n=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(n=2);for(let t=0;t<3;++t)t===n?e[t].sort(((e,t)=>e[1]t[1]?1:0)):e[t].sort(((e,t)=>e[1]>t[1]?-1:e[1]=n+1;--o)r(e[o%3],a,o!==n+2?s[i[t+(o+1)%3]]:-1);const h=a.length;i.push(s[i[t+n]],o[0],a[0]),i.push(s[i[t+(n+1)%3]],a[h-1],o[l-1]);const c=l<=h,u=c?l:h,d=c?h:l,p=c?l-1:h-1,f=c?0:1;let _=l+h-2,m=0,g=0;const v=c?o:a,x=c?a:o;let T=0;for(;_-- >0;){let e;f?i.push(v[m],x[g]):i.push(x[g],v[m]),T+=u,T>=d&&ml){const e=a;a=l,l=e}const c=a+"_"+l,u=o[c];u?u.done||(w.Dot(s,u.normal)0||this._source.hasThinInstances)}render(){const e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera)return void this._lineShader._setDrawWrapper(t);const i=this._source.hasInstances&&this.customInstances.length>0,s=i||this._source.hasThinInstances;let r=0;if(s)if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){const e=this._source._instanceDataStorage;if(r=this.customInstances.length,!e.instancesData)return void(this._source.getScene()._activeMeshesFrozen||this.customInstances.reset());if(!e.isFrozen){let t=0;for(let i=0;i0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[r]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),s.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(s)}_resetLayout(){for(let e=0;enull!=e)),this._scene.autoClear=!0;const s=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!s&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const r=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||s,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?o=n:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:r&&(o=r),this._bindFrameBuffer(),this._linkInternalTexture(e,o)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;enull!=e)),e)){for(let s=0;s=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw ye("PrePassRendererSceneComponent")},nS.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}],Object.defineProperty(ks.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),ks.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new nS(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,J.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},ks.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class oS{constructor(e){this.name=ts.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(ts.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(ts.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(ts.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(ts.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(ts.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(ts.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(ts.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(ts.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,s){if(!s)return;const r=e.getScene();r.prePassRenderer&&r.prePassRenderer.bindAttachmentsForEffect(s,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){}dispose(){this.scene.disablePrePassRenderer()}}nS._SceneComponentInitialization=e=>{let t=e._getComponent(ts.NAME_PREPASSRENDERER);t||(t=new oS(e),e._addComponent(t))};Ft.IncludesShadersStore.fibonacci="#define rcp(x) 1./x\n#define GOLDEN_RATIO 1.618033988749895\n#define TWO_PI 6.2831855\nvec2 Golden2dSeq(int i,float n)\n{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));}\nvec2 SampleDiskGolden(int i,int sampleCount)\n{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}";Ft.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";Ft.ShadersStore.subSurfaceScatteringPixelShader="#include\n#include\n#include\n#include\nvarying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40;\n#define rcp(x) 1./x\n#define Sq(x) x*x\n#define SSS_BILATERAL_FILTER true\nvec3 EvalBurleyDiffusionProfile(float r,vec3 S)\n{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); \nvec3 expSum=exp_13*(1.+exp_13*exp_13); \nreturn (S*rcp(8.*PI))*expSum; }\nvec2 SampleBurleyDiffusionProfile(float u,float rcpS)\n{u=1.-u; \nfloat g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); \nfloat p=(g*n)*n; \nfloat c=1.+p+n; \nfloat d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); \nfloat x=(3./LOG2_E)*log2(c)-d; \nfloat rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; \nreturn vec2(r,rcpPdf);}\nvec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)\n{\n#ifndef SSS_BILATERAL_FILTER\nz=0.;\n#endif\nfloat r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf;\n#if SSS_CLAMP_ARTIFACT\nreturn clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);\n#else\nreturn EvalBurleyDiffusionProfile(r,S)*area;\n#endif\n}\nvoid EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,\nfloat phase,inout vec3 totalIrradiance,inout vec3 totalWeight)\n{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; \nfloat cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; \nvec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; \nfloat xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a))\n{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;}\nelse\n{}}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest)\n{centerDepth=texture2D(depthSampler,vUV).r;}\nif (!passedStencilTest) { \ngl_FragColor=inputColor;return;}\nfloat distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; \nvec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; \nfloat mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1)\n{\n#ifdef DEBUG_SSS_SAMPLES\nvec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return;\n#endif\ngl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;}\n#ifdef DEBUG_SSS_SAMPLES\nvec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return;\n#endif\nfloat phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); \nvec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration)return void J.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");const i=this.texelSize;e.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",i.x,i.y),e.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),e.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),e.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),e.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),e.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)}))}}class lS{get ssDiffusionS(){return this._ssDiffusionS}get ssDiffusionD(){return this._ssDiffusionD}get ssFilterRadii(){return this._ssFilterRadii}constructor(e){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=ts.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new Y(1,1,1)),this._scene=e,lS._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return J.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw ye("SubSurfaceSceneComponent")},p.AddParser(ts.NAME_SUBSURFACE,((e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,s=e.ssDiffusionProfileColors.length;i{let t=e._getComponent(ts.NAME_SUBSURFACE);t||(t=new hS(e),e._addComponent(t))};Ft.ShadersStore.outlinePixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.outlineVertexShader="attribute vec3 position;attribute vec3 normal;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n#include\n}\n",ks.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new cS(this)),this._outlineRenderer},Object.defineProperty(Un.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(Un.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});class cS{constructor(e){this.name=ts.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(ts.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(ts.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{p.setMatrix("world",t)})),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=i??this._passIdForDrawWrapper[0];const s=[],r=[Ki.PositionKind,Ki.NormalKind],n=e.getMesh(),o=e.getMaterial();if(!o)return!1;const a=n.getScene();o.needAlphaTesting()&&(s.push("#define ALPHATEST"),n.isVerticesDataPresent(Ki.UVKind)&&(r.push(Ki.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(Ki.UV2Kind)&&(r.push(Ki.UV2Kind),s.push("#define UV2"))),o.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),$r(o,a,s),n.useBones&&n.computeBonesUsingShaders?(r.push(Ki.MatricesIndicesKind),r.push(Ki.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(Ki.MatricesIndicesExtraKind),r.push(Ki.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):s.push("#define NUM_BONE_INFLUENCERS 0");const l=n.morphTargetManager;let h=0;l&&(h=l.numMaxInfluencers||l.numInfluencers,h>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),tn(r,n,h))),t&&(s.push("#define INSTANCES"),rn(r),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const c=e._getDrawWrapper(i,!0),u=c.defines,d=s.join("\n");if(u!==d){const e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];jr(e),c.setEffect(this.scene.getEngine().createEffect("outline",r,e,["diffuseSampler","morphTargets"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),d)}return c.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const s=t.getMaterial();s&&s.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(cS._StencilReference),this._engine.setStencilFunctionReference(cS._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),s&&s.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const e=this._engine.getAlphaMode(),s=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=s}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}cS._StencilReference=4;class uS{get particleSize(){return this._particleSize}set particleSize(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))}get useInstancing(){return!this.indexBuffer}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&this._hasVelocity()&&(this._useVelocity=e,this._effectsAreDirty=!0)}_hasVelocity(){return!!this.vertexBuffers?.velocity}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new g,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){const e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new oa({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new oa({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})}isReady(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;const e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){const e=this.numParticles;if(!this._depthEffectWrapper||0===e)return;const t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}renderThicknessTexture(){const e=this.numParticles;if(!this._thicknessEffectWrapper||0===e)return;const t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(6),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0)}renderDiffuseTexture(){}dispose(){this._depthEffectWrapper?.dispose(),this._thicknessEffectWrapper?.dispose()}}class dS extends uS{get particleSystem(){return this._particleSystem}getClassName(){return"FluidRenderingObjectParticleSystem"}get useTrueRenderingForDiffuseTexture(){return this._useTrueRenderingForDiffuseTexture}set useTrueRenderingForDiffuseTexture(e){this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add((()=>{this._engine.setAlphaMode(2)}))))}get vertexBuffers(){return this._particleSystem.vertexBuffers}get indexBuffer(){return this._particleSystem.indexBuffer}constructor(e,t){super(e),this._useTrueRenderingForDiffuseTexture=!0,this._particleSystem=t,this._originalRender=t.render.bind(t),this._blendMode=t.blendMode,this._onBeforeDrawParticleObserver=null,this._updateInAnimate=this._particleSystem.updateInAnimate,this._particleSystem.updateInAnimate=!0,this._particleSystem.render=()=>0,this.particleSize=(t.minSize+t.maxSize)/2,this.useTrueRenderingForDiffuseTexture=!1}isReady(){return super.isReady()&&this._particleSystem.isReady()}get numParticles(){return this._particleSystem.getActiveCount()}renderDiffuseTexture(){this._originalRender()}dispose(){super.dispose(),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate}}class pS{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){const e=this._blurPostProcesses[0],t=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let i=0;i<2*this._blurNumIterations;++i)this._blurPostProcesses[i]=1&i?t:e}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}constructor(e,t,i,s,r,n,o=1,a=6,l=1,h=6,c=!1,u=null,d=!0,p=1){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new g,this._name=e,this._scene=t,this._camera=u,this._engine=t.getEngine(),this._width=i,this._height=s,this._blurTextureSizeX=r,this._blurTextureSizeY=n,this._textureType=o,this._textureFormat=a,this._blurTextureType=l,this._blurTextureFormat=h,this._useStandardBlur=c,this._generateDepthBuffer=d,this._samples=p,this._postProcessRunningIndex=0,this.enableBlur=0!==r&&0!==n,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){const[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});const e=this._rt.texture;e.incrementReferences(),this._texture=new Zn(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=Zn.CLAMP_ADDRESSMODE,this._texture.wrapV=Zn.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,s,r,n=!1){const o=this._scene.getEngine(),a=new N(Math.floor(this._blurTextureSizeX/s),Math.floor(this._blurTextureSizeY/s)),l=1===t&&o.getCaps().textureFloatLinearFiltering||2===t&&o.getCaps().textureHalfFloatLinearFiltering,h=this._engine.createRenderTargetTexture({width:a.x,height:a.y},{generateMipMaps:!1,type:t,format:i,samplingMode:l?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${r}`}),c=h.texture;c.incrementReferences();const u=new Zn(null,this._scene);if(u.name="rttBlurred"+r,u._texture=c,u.wrapU=Zn.CLAMP_ADDRESSMODE,u.wrapV=Zn.CLAMP_ADDRESSMODE,u.anisotropicFilteringLevel=1,n){const s=new Ko("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",s.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++})),s.onSizeChangedObservable.add((()=>{s._textures.forEach((e=>{e.texture.wrapU=Zn.CLAMP_ADDRESSMODE,e.texture.wrapV=Zn.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(s);const r=new Ko("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.onApplyObservable.add((e=>{e.setInt("filterSize",this.blurFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++})),r.onSizeChangedObservable.add((()=>{r._textures.forEach((e=>{e.texture.wrapU=Zn.CLAMP_ADDRESSMODE,e.texture.wrapV=Zn.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(r),s.autoClear=!1,r.autoClear=!1;const n=[];for(let e=0;e<2*this._blurNumIterations;++e)n[e]=1&e?r:s;return[h,u,n]}{const s=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],r=new Ko("BilateralBlurX","fluidRenderingBilateralBlur",s,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",r.inputTexture.texture),t.setInt("maxFilterSize",this.blurMaxFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),t.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),r.onSizeChangedObservable.add((()=>{r._textures.forEach((e=>{e.texture.wrapU=Zn.CLAMP_ADDRESSMODE,e.texture.wrapV=Zn.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(r);const n=new Ko("BilateralBlurY","fluidRenderingBilateralBlur",s,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);n.samples=this._samples,n.onApplyObservable.add((e=>{e.setInt("maxFilterSize",this.blurMaxFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),e.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),e.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),n.onSizeChangedObservable.add((()=>{n._textures.forEach((e=>{e.texture.wrapU=Zn.CLAMP_ADDRESSMODE,e.texture.wrapV=Zn.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(n),r.autoClear=!1,n.autoClear=!1;const a=[];for(let e=0;e<2*this._blurNumIterations;++e)a[e]=1&e?n:r;return[h,u,a]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})),e.onApplyObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})))}_getProjectedParticleConstant(){return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((this._camera?.fov??45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),this._rt?.dispose(),this._rt=null,this._texture?.dispose(),this._texture=null,this._rtBlur?.dispose(),this._rtBlur=null,this._textureBlurred?.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}var fS;!function(e){e[e.DepthTexture=0]="DepthTexture",e[e.DepthBlurredTexture=1]="DepthBlurredTexture",e[e.ThicknessTexture=2]="ThicknessTexture",e[e.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",e[e.DiffuseTexture=4]="DiffuseTexture",e[e.Normals=5]="Normals",e[e.DiffuseRendering=6]="DiffuseRendering"}(fS||(fS={}));class _S{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get compositeMode(){return this._compositeMode}set compositeMode(e){this._compositeMode!==e&&(this._compositeMode=e,this._needInitialization=!0)}get camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new Y(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new w(-2,-1,1).normalize(),this._debugFeature=fS.DepthBlurredTexture,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new g,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._compositeMode=!1,this._scene=e,this._engine=e.getEngine(),this._camera=t??e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new B,this._depthClearColor=new j(1e6,1e6,1e6,1),this._thicknessClearColor=new j(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){this.dispose(),this._needInitialization=!1;const e=this._depthMapSize??this._engine.getRenderWidth(),t=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new pS("Depth",this._scene,e,t,e,t,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const e=this._diffuseMapSize??this._engine.getRenderWidth(),t=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new pS("Diffuse",this._scene,e,t,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const i=this._thicknessMapSize??this._engine.getRenderWidth(),s=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new pS("Thickness",this._scene,i,s,i,s,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){null!==e&&e!==this._depthRenderTarget||this._setBlurDepthParameters(),null!==e&&e!==this._thicknessRenderTarget||this._setBlurThicknessParameters()}_setBlurDepthParameters(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)}_setBlurThicknessParameters(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)}_initializeRenderTarget(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()}_createLiquidRenderingPostProcess(){const e=this._scene.getEngine(),t=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],i=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;const r=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,n=new N(1/r.getSize().width,1/r.getSize().height);this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap&&(this._environmentMap??this._scene.environmentTexture)&&(i.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(i.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):t.push("diffuseColor"),this._useVelocity&&(i.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(t.push("thickness"),i.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(t.push("minimumThickness"),i.push("thicknessSampler")),this._compositeMode&&s.push("#define FLUIDRENDERING_COMPOSITE_MODE"),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===fS.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===fS.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),i.push("debugSampler"),this._debugFeature!==fS.DepthTexture&&this._debugFeature!==fS.DepthBlurredTexture||s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new Ko("FluidRendering","fluidRenderingRender",t,i,1,null,2,e,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(s.join("\n")),this._renderPostProcess.samples=this._samples;const o=e,a=o.setTextureSampler;this._renderPostProcess.onApplyObservable.add((e=>{if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),a&&a.call(o,"textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(e.setTexture("depthSampler",this._depthRenderTarget.textureBlur),a&&a.call(o,"depthSamplerSampler",this._depthRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),a&&a.call(o,"depthSamplerSampler",this._depthRenderTarget.texture?.getInternalTexture()??null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),a&&a.call(o,"diffuseSamplerSampler",this._diffuseRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),a&&a.call(o,"diffuseSamplerSampler",this._diffuseRenderTarget.texture?.getInternalTexture()??null)):e.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(e.setFloat("thickness",this.minimumThickness),e._bindTexture("bgDepthSampler",this._bgDepthTexture),a&&a.call(o,"bgDepthSamplerSampler",this._bgDepthTexture??null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),a&&a.call(o,"thicknessSamplerSampler",this._thicknessRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),a&&a.call(o,"thicknessSamplerSampler",this._thicknessRenderTarget.texture?.getInternalTexture()??null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){const t=this._environmentMap??this._scene.environmentTexture;t&&(e.setTexture("reflectionSampler",t),a&&a.call(o,"reflectionSamplerSampler",t?.getInternalTexture()??null))}if(e.setMatrix("viewMatrix",this._scene.getViewMatrix()),e.setMatrix("invProjectionMatrix",this._invProjectionMatrix),e.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),e.setVector2("texelSize",n),e.setFloat("density",this.density),e.setFloat("refractionStrength",this.refractionStrength),e.setFloat("fresnelClamp",this.fresnelClamp),e.setFloat("specularPower",this.specularPower),e.setVector3("dirLight",this.dirLight),e.setFloat("cameraFar",this._camera.maxZ),this._debug){let t=null;switch(this._debugFeature){case fS.DepthTexture:t=this._depthRenderTarget.texture;break;case fS.DepthBlurredTexture:t=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case fS.ThicknessTexture:t=this._thicknessRenderTarget?.texture??null;break;case fS.ThicknessBlurredTexture:t=this._thicknessRenderTarget?.enableBlur?this._thicknessRenderTarget?.textureBlur??null:this._thicknessRenderTarget?.texture??null;break;case fS.DiffuseTexture:this._diffuseRenderTarget&&(t=this._diffuseRenderTarget.texture)}this._debugFeature!==fS.Normals&&(e.setTexture("debugSampler",t),a&&a.call(o,"debugSamplerSampler",t?.getInternalTexture()??null))}}))}_clearTargets(){this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){if(this._needInitialization||!e.isReady())return;const t=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0),this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),this._depthRenderTarget?.applyBlurPostProcesses(),this._diffuseRenderTarget?.applyBlurPostProcesses(),this._thicknessRenderTarget?.applyBlurPostProcesses(),t&&this._engine.bindFramebuffer(t)}dispose(e=!1){e||(this._depthRenderTarget?.dispose(),this._depthRenderTarget=null,this._diffuseRenderTarget?.dispose(),this._diffuseRenderTarget=null,this._thicknessRenderTarget?.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),this._renderPostProcess?.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class mS extends uS{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i){super(e),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(const t in e){let i,s=!0;switch(t){case"velocity":i=3;break;case"offset":s=!1}this._vertexBuffers[t]=new Ki(this._engine,e[t],t,!0,!1,i,s)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new oa({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[]})}isReady(){return this._vertexBuffers.offset||(this._vertexBuffers.offset=new Ki(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&(this._diffuseEffectWrapper?.effect.isReady()??!1)}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){const e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)return;const t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),null!==this._particleSize&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){super.dispose(),this._diffuseEffectWrapper?.dispose();for(const e in this._vertexBuffers)this._vertexBuffers[e].dispose();this._vertexBuffers={}}}var gS;Ft.ShadersStore.copyTextureToTexturePixelShader="uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV;\n#include\nvoid main(void) \n{vec4 color=texture2D(textureSampler,vUV);\n#ifdef DEPTH_TEXTURE\ngl_FragDepth=color.r;\n#else\nif (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);}\ngl_FragColor=color;\n#endif\n}\n",function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(gS||(gS={}));class vS{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new na(e),this._effectWrapper=new oa({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add((()=>{t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.depthCullingState.depthFunc=519),this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)}))}isReady(){return this._effectWrapper.effect.isReady()}copy(e,t,i=gS.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;const s=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&s&&(this._engine.depthCullingState.depthFunc=s),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class xS{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,s=1){this._engine=e,this._copyTextureToTexture=new vS(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:s,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil").label=`FluidDepthTextureCopy${t}x${i}x${s}`}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}Ft.ShadersStore.fluidRenderingParticleDepthVertexShader="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nattribute vec3 velocity;varying float velocityNorm;\n#endif\nvoid main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0;\n#ifdef FLUIDRENDERING_VELOCITY\nvelocityNorm=length(velocity);\n#endif\n}\n";Ft.ShadersStore.fluidRenderingParticleDepthPixelShader="uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nvarying float velocityNorm;\n#endif\nvoid main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2);\n#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\n#endif\nvec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos;\n#ifdef WEBGPU\ngl_FragDepth=clipSpacePos.z/clipSpacePos.w;\n#else\ngl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;\n#endif\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nglFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);\n#else\nglFragColor=vec4(realViewPos.z,0.,0.,1.);\n#endif\n}\n";Ft.ShadersStore.fluidRenderingParticleThicknessVertexShader="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;}\n";Ft.ShadersStore.fluidRenderingParticleThicknessPixelShader="uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);}\n";Ft.ShadersStore.fluidRenderingParticleDiffuseVertexShader="attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;}\n";Ft.ShadersStore.fluidRenderingParticleDiffusePixelShader="uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);}\n";Ft.ShadersStore.fluidRenderingBilateralBlurPixelShader="uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;}\nint filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;}\nglFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);}\n";Ft.ShadersStore.fluidRenderingStandardBlurPixelShader="uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;}\nfloat sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;}\nsum/=wsum;glFragColor=vec4(sum.rgb,1.);}\n";function TS(e){return!!e.particleSystem}function SS(e){return!!e.addBuffers}Ft.ShadersStore.fluidRenderingRenderPixelShader="#define DISABLE_UNIFORMITY_ANALYSIS\n#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nuniform sampler2D textureSampler;uniform sampler2D depthSampler;\n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nuniform sampler2D diffuseSampler;\n#else\nuniform vec3 diffuseColor;\n#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform float thickness;uniform sampler2D bgDepthSampler;\n#else\nuniform float minimumThickness;uniform sampler2D thicknessSampler;\n#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nuniform samplerCube reflectionSampler;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nuniform sampler2D debugSampler;\n#endif\nuniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef FLUIDRENDERING_RHS\nndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#else\nndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\nvec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);}\nvoid main(void) {vec2 texCoord=vUV;\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvec4 color=texture2D(debugSampler,texCoord);\n#ifdef FLUIDRENDERING_DEBUG_DEPTH\nglFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);}\n#else\nglFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);}\n#endif\nreturn;\n#endif\nvec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r;\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nfloat thickness=texture2D(thicknessSampler,texCoord).x;\n#else\nfloat bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5;\n#endif\nvec4 backColor=texture2D(textureSampler,texCoord);\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {\n#else\nif (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\n#endif\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nglFragColor.rgb=backColor.rgb*backColor.a;glFragColor.a=backColor.a;\n#else\nglFragColor=backColor;\n#endif\nreturn;}\nvec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;}\nvec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;}\nvec3 normal=normalize(cross(ddy,ddx));\n#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\n#endif\n#ifndef WEBGPU\nif(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);}\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nglFragColor=vec4(normal*0.5+0.5,1.0);return;\n#endif\nvec3 rayDir=normalize(viewPos); \n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;\n#endif\nvec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower);\n#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nfloat diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return;\n#endif\nvec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nif (transmitted.a==0.) transmitted.a=thickness;\n#endif\nvec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); \nvec3 refractionColor=transmitted.rgb*transmittance;\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular;\n#else\nvec3 finalColor=refractionColor+specular;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfloat velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));\n#endif\nglFragColor=vec4(finalColor,transmitted.a);}\n",Object.defineProperty(ks.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),ks.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new bS(this)),this._fluidRenderer},ks.prototype.disableFluidRenderer=function(){this._fluidRenderer?.dispose(),this._fluidRenderer=null};class ES{constructor(e){this.name=ts.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(ts.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(ts.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){this.scene.fluidRenderer?._prepareRendering()}_afterCameraDraw(e){this.scene.fluidRenderer?._render(e)}rebuild(){const e=this.scene.fluidRenderer;if(!e)return;const t=new Set;for(let i=0;i{e._rebuild()}))}dispose(){this.scene.disableFluidRenderer()}}class bS{static _SceneComponentInitialization(e){let t=e._getComponent(ts.NAME_FLUIDRENDERER);t||(t=new ES(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,bS._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add((()=>{this._initialize()}))}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){const t=this._getParticleSystemIndex(e);return-1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,s){const r=new dS(this._scene,e);r.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),i||(i=new _S(this._scene,s),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==t&&(i.generateDiffuseTexture=t);const n={object:r,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,s,r){const n=new mS(this._scene,e,t);n.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),s||(s=new _S(this._scene,r),this.targetRenderers.push(s)),s._onUseVelocityChanged.hasObservers()||s._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==i&&(s.generateDiffuseTexture=i);const o={object:n,targetRenderer:s};return this.renderObjects.push(o),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),o}removeRenderObject(e,t=!0){const i=this.renderObjects.indexOf(e);return-1!==i&&(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort(((e,t)=>e.object.priorityt.object.priority?1:0))}_removeUnusedTargetRenderers(){const e={};for(let t=0;t{r.inputTexture.depthStencilTexture||r.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,n[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${r.name}`);for(const e of n){const t=e._thicknessRenderTarget?.renderTarget,i=t?.texture;if(t&&i){const e=i.width+"_"+i.height;let s=o[e];s||(s=o[e]=new xS(this._engine,i.width,i.height)),s.depthRTWrapper.shareDepth(t)}}}))}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value,s=this._cameras.get(t)[1],r=e.get(t);if(r)for(const e in s)r[1][e]||s[e].dispose();else for(const e in s)s[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){const e=new Map;for(let t=0;t{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)}))}_setUseVelocityForRenderObject(){for(const e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(const e of this.targetRenderers)if(e.needInitialization)return void this._initialize()}_render(e){for(let t=0;t{const t=e[1];for(const e in t)t[e].dispose()})),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class CS extends Do{constructor(){super(...arguments),this.RSMCREATE=!1,this.RSMCREATE_PROJTEXTURE=!1,this.RSMCREATE_LIGHT_IS_SPOT=!1}}class yS extends ah{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,yS.Name,300,new CS),this._lightColor=new Y,this._hasProjectionTexture=!1,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._varAlbedoName=e instanceof Cf?"surfaceAlbedo":"baseColor.rgb"}prepareDefines(e){e.RSMCREATE=this._isEnabled,this._hasProjectionTexture=!1;const t=this.light.getTypeID()===Gn.LIGHTTYPEID_SPOTLIGHT;if(t){const e=this.light;this._hasProjectionTexture=!!e.projectionTexture&&e.projectionTexture.isReady()}e.RSMCREATE_PROJTEXTURE=this._hasProjectionTexture,e.RSMCREATE_LIGHT_IS_SPOT=t}getClassName(){return"RSMCreatePluginMaterial"}getUniforms(){return{ubo:[{name:"rsmTextureProjectionMatrix",size:16,type:"mat4"},{name:"rsmSpotInfo",size:4,type:"vec4"},{name:"rsmLightColor",size:3,type:"vec3"},{name:"rsmLightPosition",size:3,type:"vec3"}],fragment:"#ifdef RSMCREATE\n uniform mat4 rsmTextureProjectionMatrix;\n uniform vec4 rsmSpotInfo;\n uniform vec3 rsmLightColor;\n uniform vec3 rsmLightPosition;\n #endif"}}getSamplers(e){e.push("rsmTextureProjectionSampler")}bindForSubMesh(e){if(this._isEnabled&&(this.light.diffuse.scaleToRef(this.light.getScaledIntensity(),this._lightColor),e.updateColor3("rsmLightColor",this._lightColor),this.light.getTypeID()===Gn.LIGHTTYPEID_SPOTLIGHT)){const t=this.light;this._hasProjectionTexture&&(e.updateMatrix("rsmTextureProjectionMatrix",t.projectionTextureMatrix),e.setTexture("rsmTextureProjectionSampler",t.projectionTexture));const i=U.Vector3[0];t.computeTransformedInformation()?(e.updateFloat3("rsmLightPosition",this.light.transformedPosition.x,this.light.transformedPosition.y,this.light.transformedPosition.z),t.transformedDirection.normalizeToRef(i)):(e.updateFloat3("rsmLightPosition",this.light.position.x,this.light.position.y,this.light.position.z),t.direction.normalizeToRef(i)),e.updateFloat4("rsmSpotInfo",i.x,i.y,i.z,Math.cos(.5*t.angle))}}getCustomCode(e){return"vertex"===e?null:{CUSTOM_FRAGMENT_BEGIN:"\n #ifdef RSMCREATE\n #extension GL_EXT_draw_buffers : require\n #endif\n ",CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RSMCREATE\n #ifdef RSMCREATE_PROJTEXTURE\n uniform highp sampler2D rsmTextureProjectionSampler; \n #endif\n layout(location = 0) out highp vec4 glFragData[3];\n vec4 glFragColor;\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:`\n #ifdef RSMCREATE\n vec3 rsmColor = ${this._varAlbedoName} * rsmLightColor;\n #ifdef RSMCREATE_PROJTEXTURE\n {\n vec4 strq = rsmTextureProjectionMatrix * vec4(vPositionW, 1.0);\n strq /= strq.w;\n rsmColor *= texture2D(rsmTextureProjectionSampler, strq.xy).rgb;\n }\n #endif\n #ifdef RSMCREATE_LIGHT_IS_SPOT\n {\n float cosAngle = max(0., dot(rsmSpotInfo.xyz, normalize(vPositionW - rsmLightPosition)));\n rsmColor = sign(cosAngle - rsmSpotInfo.w) * rsmColor;\n }\n #endif\n glFragData[0] = vec4(vPositionW, 1.);\n glFragData[1] = vec4(normalize(normalW) * 0.5 + 0.5, 1.);\n glFragData[2] = vec4(rsmColor, 1.);\n #endif\n `}}}yS.Name="RSMCreate",ae([pe()],yS.prototype,"light",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yS.prototype,"isEnabled",void 0),u("BABYLON.RSMCreatePluginMaterial",yS);Ft.ShadersStore.bilateralBlurPixelShader="uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec3 sampleColor=textureLod(textureSampler,vUV+coords*blurDir,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords*blurDir,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords*blurDir,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat r=dot(coords,coords);float w=exp(-r/two_sigma2);float depthDelta=abs(sampleDepth-depth);float wd=step(depthDelta,depthThreshold);vec3 normalDelta=abs(sampleNormal-normal);float wn=step(normalDelta.x+normalDelta.y+normalDelta.z,normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}\nglFragColor=vec4(sum/wsum,1.);}\n";Ft.ShadersStore.bilateralBlurQualityPixelShader="uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {for (int y=-filterSize; y<=filterSize; ++y) {vec2 coords=vec2(x,y)*blurDir;vec3 sampleColor=textureLod(textureSampler,vUV+coords,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepth-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);float rNormal=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);float wn=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}}\nglFragColor=vec4(sum/wsum,1.);}\n";Ft.ShadersStore.rsmGlobalIlluminationPixelShader="/**\n* The implementation is an application of the formula found in http:\n* For better results,it also adds a random (noise) rotation to the RSM samples (the noise artifacts are easier to remove than the banding artifacts).\n*/\nprecision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform vec4 rsmInfo2;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;uniform sampler2D rsmSamples;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nfloat mod289(float x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 perm(vec4 x){return mod289(((x*34.0)+1.0)*x);}\nfloat noise(vec3 p){vec3 a=floor(p);vec3 d=p-a;d=d*d*(3.0-2.0*d);vec4 b=a.xxyy+vec4(0.0,1.0,0.0,1.0);vec4 k1=perm(b.xyxy);vec4 k2=perm(k1.xyxy+b.zzww);vec4 c=k2+a.zzzz;vec4 k3=perm(c);vec4 k4=perm(c+1.0);vec4 o1=fract(k3*(1.0/41.0));vec4 o2=fract(k4*(1.0/41.0));vec4 o3=o2*d.z+o1*(1.0-d.z);vec2 o4=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);}\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);int numSamples=int(rsmInfo.x);float radius=rsmInfo.y;float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;float angle=noise(p*rsmInfo2.x);float c=cos(angle);float s=sin(angle);for (int i=0; i1. || uv.y<0. || uv.y>1.) continue;vec3 vplPositionW=textureLod(rsmPositionW,uv,0.).xyz;vec3 vplNormalW=textureLod(rsmNormalW,uv,0.).xyz*2.0-1.0;vec3 vplFlux=textureLod(rsmFlux,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; \nfloat dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}\nreturn clamp(indirectDiffuse*intensity,0.0,1.0);}\nvoid main(void) \n{vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz;\n#ifdef DECODE_NORMAL\nnormalW=normalW*2.0-1.0;\n#endif\n#ifdef TRANSFORM_NORMAL\nnormalW=(invView*vec4(normalW,0.)).xyz;\n#endif\ngl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;}\n";Ft.ShadersStore.rsmFullGlobalIlluminationPixelShader="/**\n* The implementation is a direct application of the formula found in http:\n*/\nprecision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;int width=int(rsmInfo.x);int height=int(rsmInfo.y);for (int j=0; j{t.pluginManager&&(t.pluginManager.getPlugin(IS.Name).isEnabled=e)})),this.recreateResources(!e))}get enableBlur(){return this._enableBlur}set enableBlur(e){e!==this._enableBlur&&(this._enableBlur=e,this.recreateResources())}get useQualityBlur(){return this._useQualityBlur}set useQualityBlur(e){e!==this._useQualityBlur&&(this._useQualityBlur=e,this.recreateResources())}get fullSizeBlur(){return this._forceFullSizeBlur}set fullSizeBlur(e){this._forceFullSizeBlur!==e&&(this._forceFullSizeBlur=e,this.recreateResources())}get useQualityUpsampling(){return this._useQualityUpsampling}set useQualityUpsampling(e){e!==this._useQualityUpsampling&&(this._useQualityUpsampling=e,this.recreateResources())}get showOnlyGI(){return this._showOnlyGI}set showOnlyGI(e){this._showOnlyGI!==e&&(this._showOnlyGI=e,this._debugLayer.isEnabled=e)}get use32BitsDepthBuffer(){return this._use32BitsDepthBuffer}set use32BitsDepthBuffer(e){this._use32BitsDepthBuffer!==e&&(this._use32BitsDepthBuffer=e,this.recreateResources())}setOutputDimensions(e){this._outputDimensions=e,this.recreateResources()}setGITextureDimensions(e){this._giTextureDimensions=e,this.recreateResources()}get giTextureType(){return this._giTextureType}set giTextureType(e){this._giTextureType!==e&&(this._giTextureType=e,this.recreateResources())}get giRSM(){return this._giRSM}addGIRSM(e){Array.isArray(e)?this._giRSM.push(...e):this._giRSM.push(e),this.recreateResources()}removeGIRSM(e){if(Array.isArray(e))for(let t=0;t{e.getTotalVertices()>0&&e.isEnabled()&&e.material&&this._addGISupportToMaterial(e.material)}))}get countersGPU(){return this._counters}recreateResources(e=!1){this._disposePostProcesses(e),this._createPostProcesses(),this._setPluginParameters()}generateSampleTexture(e){this._sampleTexture?.dispose(),this._maxSamples=e;const t=new Float32Array(4*this._maxSamples);for(let e=0;e{const e=this._engine._currentRenderTarget;let t=!1;if(this._enable){this.pause||(this._scene.postProcessManager.directRender(this._ppGlobalIllumination,this._ppGlobalIllumination[0].inputTexture),this._engine.unBindFramebuffer(this._ppGlobalIllumination[0].inputTexture,!0),this._engine.setAlphaMode(0),t=!0,this.enableBlur&&this._blurPostProcesses&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,this._blurRTT.renderTarget,!0),this._engine.unBindFramebuffer(this._blurRTT.renderTarget,!0)));for(let e=0;e{if(e.pluginManager){const t=e.pluginManager.getPlugin(IS.Name);t.textureGIContrib=this.enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height}}))}_createPostProcesses(){if(!this._enable)return;const e=13===this._giTextureType?4:5;this._firstActivation&&(this._firstActivation=!1,this._geomBufferEnabled=!!this._scene.geometryBufferRenderer,this._geomBufferEnablePosition=this._scene.geometryBufferRenderer?.enablePosition??!1),this._geomBufferEnabled||this._scene.disableGeometryBufferRenderer();const t=this._scene.enableGeometryBufferRenderer(this._enableBlur?this._outputDimensions:this._giTextureDimensions,this._use32BitsDepthBuffer?14:15,AS.GeometryBufferTextureTypesAndFormats);if(!t)throw new Error("Geometry buffer renderer is not supported but is required for GIRSMManager.");t.enablePosition=!0,this._geomBufferEnabled||(t.generateNormalsInWorldSpace=!0);const i=t.normalsAreUnsigned,s=t.generateNormalsInWorldSpace;this._counters.push({name:"Geometry buffer renderer",value:0}),this._countersRTW.push([this._scene.geometryBufferRenderer.getGBuffer().renderTarget]);let r="";i&&(r+="#define DECODE_NORMAL\n"),s||(r+="#define TRANSFORM_NORMAL\n");for(let i=0;i{e.setTexture("textureSampler",t.getGBuffer().textures[t.getTextureIndex(AT.POSITION_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(AT.NORMAL_TEXTURE_TYPE)]),e.setTexture("rsmPositionW",o.positionWorldTexture),e.setTexture("rsmNormalW",o.normalWorldTexture),e.setTexture("rsmFlux",o.fluxTexture),e.setMatrix("rsmLightMatrix",o.lightTransformationMatrix),n.useFullTexture?e.setFloat4("rsmInfo",o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height,n.intensity,n.edgeArtifactCorrection):(e.setTexture("rsmSamples",this._sampleTexture),e.setFloat4("rsmInfo",n.numSamples,n.radius,n.intensity,n.edgeArtifactCorrection),e.setFloat4("rsmInfo2",n.noiseFactor,n.rotateSample?1:0,o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height)),s||(this._tempMatrix.copyFrom(this._scene.activeCamera.getViewMatrix()),this._tempMatrix.invert(),e.setMatrix("invView",this._tempMatrix))}))}for(const e of this._ppGlobalIllumination)e.inputTexture||e.resize(this._giTextureDimensions.width,this._giTextureDimensions.height);if(this._counters.push({name:"GI generation",value:0}),this._countersRTW.push([this._ppGlobalIllumination[0].inputTexture]),this._enableBlur){const s=this._forceFullSizeBlur?this._outputDimensions:this._giTextureDimensions;this._blurRTT=new da("GIRSMContribution",this._outputDimensions,this._scene,{type:this._giTextureType,format:e,generateDepthBuffer:!1}),this._blurRTT.wrapU=0,this._blurRTT.wrapV=0,this._blurRTT.updateSamplingMode(1),this._blurRTT.skipInitialClear=!0;const r=[];if(this._counters.push({name:"GI blur",value:0}),this._countersRTW.push(r),this._blurXPostprocess=new Ko(this._useQualityBlur?"BilateralBlur":"BilateralBlurX",this._useQualityBlur?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._blurXPostprocess.onApplyObservable.add((e=>{e._bindTexture("textureSampler",this._ppGlobalIllumination[0].inputTexture.texture),e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(AT.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(AT.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",1/this._giTextureDimensions.width,this._useQualityBlur?1/this._giTextureDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurXPostprocess.externalTextureSamplerBinding=!0,this._blurXPostprocess.autoClear=!1,this._useQualityBlur||(this._blurYPostprocess=new Ko("BilateralBlurY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._blurYPostprocess.autoClear=!1,this._blurYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(AT.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(AT.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",0,1/this._giTextureDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurYPostprocess.resize(s.width,s.height),r.push(this._blurYPostprocess.inputTexture)),this._blurPostProcesses=[this._blurXPostprocess],this._blurYPostprocess&&this._blurPostProcesses.push(this._blurYPostprocess),this._giTextureDimensions.width>=this._outputDimensions.width&&this._giTextureDimensions.height>=this._outputDimensions.height||this._forceFullSizeBlur)r.push(this._blurRTT.renderTarget);else{const n=[];this._counters.push({name:"GI upsampling",value:0}),this._countersRTW.push(n),this._upsamplingXPostprocess=new Ko(this._useQualityUpsampling?"BilateralUpsampling":"BilateralUpsamplingX",this._useQualityUpsampling?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._upsamplingXPostprocess.autoClear=!1,this._upsamplingXPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(AT.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(AT.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",1/this._outputDimensions.width,this._useQualityUpsampling?1/this._outputDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingXPostprocess.resize(s.width,s.height),r.push(this._upsamplingXPostprocess.inputTexture),this.useQualityUpsampling||(this._upsamplingYPostprocess=new Ko("BilateralUpsamplingY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:this._outputDimensions,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._upsamplingYPostprocess.autoClear=!1,this._upsamplingYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(AT.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(AT.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",0,1/this._outputDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingYPostprocess.resize(this._outputDimensions.width,this._outputDimensions.height),n.push(this._upsamplingYPostprocess.inputTexture)),n.push(this._blurRTT.renderTarget),this._blurPostProcesses.push(this._upsamplingXPostprocess),this._upsamplingYPostprocess&&this._blurPostProcesses.push(this._upsamplingYPostprocess)}}this._debugLayer.texture?.dispose(),this._debugLayer.texture=new qn(this._scene,this._enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture)}_addGISupportToMaterial(e){if(e.pluginManager?.getPlugin(IS.Name))return;const t=new IS(e);this._enable&&this._ppGlobalIllumination.length>0&&(t.textureGIContrib=this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height),t.isEnabled=this._enable,this._materialsWithRenderPlugin.push(e)}}AS.GeometryBufferTextureTypesAndFormats={0:{textureType:2,textureFormat:6},1:{textureType:11,textureFormat:5},2:{textureType:2,textureFormat:5}};class RS extends Do{constructor(){super(...arguments),this.RENDER_WITH_GIRSM=!1,this.RSMCREATE_PROJTEXTURE=!1}}class IS extends ah{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,IS.Name,310,new RS),this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._isPBR=e instanceof Cf}prepareDefines(e){e.RENDER_WITH_GIRSM=this._isEnabled}getClassName(){return"GIRSMRenderPluginMaterial"}getUniforms(){return{ubo:[{name:"girsmTextureOutputSize",size:2,type:"vec2"}],fragment:"#ifdef RENDER_WITH_GIRSM\n uniform vec2 girsmTextureOutputSize;\n #endif"}}getSamplers(e){e.push("girsmTextureGIContrib")}bindForSubMesh(e){this._isEnabled&&(e.bindTexture("girsmTextureGIContrib",this.textureGIContrib),e.updateFloat2("girsmTextureOutputSize",this.outputTextureWidth,this.outputTextureHeight))}getCustomCode(e){const t={CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RENDER_WITH_GIRSM\n uniform sampler2D girsmTextureGIContrib;\n\n vec3 computeIndirect() {\n vec2 uv = gl_FragCoord.xy / girsmTextureOutputSize;\n return texture2D(girsmTextureGIContrib, uv).rgb;\n }\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:"\n #ifdef RENDER_WITH_GIRSM\n finalDiffuse += computeIndirect() * surfaceAlbedo.rgb;\n #endif\n "};return this._isPBR||(t.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR="\n #ifdef RENDER_WITH_GIRSM\n color.rgb += computeIndirect() * baseColor.rgb;\n #endif\n "),"vertex"===e?null:t}}IS.Name="GIRSMRender",ae([pe()],IS.prototype,"textureGIContrib",void 0),ae([pe()],IS.prototype,"outputTextureWidth",void 0),ae([pe()],IS.prototype,"outputTextureHeight",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],IS.prototype,"isEnabled",void 0),u("BABYLON.GIRSMRenderPluginMaterial",IS);Ft.ShadersStore.spriteMapPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nprecision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4(\ntexture2D(frameMap,vec2(fX,0.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*1.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*2.),0.),\nvec4(0.)\n);}\nvoid main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV);\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\nvec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; fmt){frameID=animationData.x;break;}\nanimationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}}\nmat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;}\nvec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}}\ncolor.xyz*=colorMul;gl_FragColor=color;}";var PS;Ft.ShadersStore.spriteMapVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; \ngl_Position=worldViewProjection*p;}",function(e){e[e.INIT=0]="INIT",e[e.RUNNING=1]="RUNNING",e[e.DONE=2]="DONE",e[e.ERROR=3]="ERROR"}(PS||(PS={})),g.prototype.notifyObserversWithPromise=async function(e,t=-1,i,s,r){let n=Promise.resolve(e);if(!this.observers.length)return n;const o=this._eventState;return o.mask=t,o.target=i,o.currentTarget=s,o.skipNextObservers=!1,o.userInfo=r,this.observers.forEach((i=>{o.skipNextObservers||i._willBeUnregistered||i.mask&t&&(n=i.scope?n.then((t=>(o.lastReturnValue=t,i.callback.apply(i.scope,[e,o])))):n.then((t=>(o.lastReturnValue=t,i.callback(e,o)))),i.unregisterOnNextCall&&this._deferUnregister(i))})),await n,e};class MS{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class DS extends MS{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof Un))return!1;const t=e;return!(t.isDisposed()||!t.isVisible||!t.isEnabled()||t.instances.length>0||t.skeleton||t.hasLODLevels||0===t.getTotalVertices())}}static get UpdateSelectionTree(){return DS._UpdateSelectionTree}static set UpdateSelectionTree(e){DS._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const s=e.meshes.slice(0);let r=s.length;for(let e=0;e{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),OS[e.id]=!0)},wS=(e,t)=>{const i={},s=e._geometry;return s&&(e.getScene().getGeometryById(s.id)||NS(s,t.geometries)),e.serialize&&e.serialize(i),i};class FS{static ClearCache(){OS=[]}static Serialize(e){return FS._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&Zn.ForceSerializeBuffers&&J.Warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),FS.ClearCache(),i.useDelayedTextureLoading=e.useDelayedTextureLoading,i.autoClear=e.autoClear,i.clearColor=e.clearColor.asArray(),i.ambientColor=e.ambientColor.asArray(),i.gravity=e.gravity.asArray(),i.collisionsEnabled=e.collisionsEnabled,i.useRightHandedSystem=e.useRightHandedSystem,void 0!==e.fogMode&&null!==e.fogMode&&(i.fogMode=e.fogMode),void 0!==e.fogColor&&null!==e.fogColor&&(i.fogColor=e.fogColor.asArray()),void 0!==e.fogStart&&null!==e.fogStart&&(i.fogStart=e.fogStart),void 0!==e.fogEnd&&null!==e.fogEnd&&(i.fogEnd=e.fogEnd),void 0!==e.fogDensity&&null!==e.fogDensity&&(i.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){const t=e.getPhysicsEngine();t&&(i.physicsEnabled=!0,i.physicsGravity=t.gravity.asArray(),i.physicsEngine=t.getPhysicsPluginName())}e.metadata&&(i.metadata=e.metadata),i.morphTargetManagers=[];for(const t of e.meshes){const e=t.morphTargetManager;e&&i.morphTargetManagers.push(e.serialize())}let s,r,n;for(i.lights=[],s=0;s0){i.animationGroups=[];for(let t=0;t0)for(i.reflectionProbes=[],s=0;st))}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=t))):(s instanceof Object||Array.isArray(s))&&this._CollectPromises(s,t)}else if(e instanceof Object)for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const s=e[i];s instanceof Promise?t.push(s.then((t=>e[i]=t))):(s instanceof Object||Array.isArray(s))&&this._CollectPromises(s,t)}}static SerializeMesh(e,t=!1,i=!1){const s={meshes:[],transformNodes:[],cameras:[],lights:[]};if(FS.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let s=0;s{e.indexOf(t)<0&&!t.doNotSerialize&&e.push(t)})),t&&e[s].parent&&e.indexOf(e[s].parent)<0&&!e[s].parent.doNotSerialize&&e.push(e[s].parent);return e.forEach((e=>{((e,t)=>{if(e._isMesh){const i=e;if(1===i.delayLoadState||0===i.delayLoadState){const e=e=>{t.materials=t.materials||[],i.material&&!t.materials.some((e=>e.id===i.material.id))&&t.materials.push(e.serialize())};if(i.material&&!i.material.doNotSerialize)if(i.material instanceof On){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some((e=>e.id===i.material.id))){t.multiMaterials.push(i.material.serialize());for(const t of i.material.subMaterials)t&&e(t)}}else e(i.material);else i.material||e(i.getScene().defaultMaterial);const s=i._geometry;s&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),NS(s,t.geometries)),i.skeleton&&!i.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(i.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(wS(i,t))}}else if("TransformNode"===e.getClassName()){const i=e;t.transformNodes.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Camera")){const i=e;t.cameras.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Light")){const i=e;t.lights.push(i.serialize())}})(e,s)})),s}}class LS{static IsSupported(e,t){const i=t??e.getRenderingCanvas();return!!i&&"function"==typeof i.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!LS.IsSupported(e,t.canvas))throw"Your browser does not support recording so far.";const i=t.canvas??e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options={...LS._DefaultOptions,...t};const s=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const e of this._options.audioTracks)s.addTrack(e);this._mediaRecorder=new MediaRecorder(s,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=e=>this._handleDataAvailable(e),this._mediaRecorder.onerror=e=>this._handleError(e),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout((()=>{this.stopRecording()}),1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),!this._reject)throw new e.error;this._reject(e.error)}_handleStop(){this.stopRecording();const e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&Ii.Download(e,this._fileName)}}LS._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let BS=null;function VS(e,t,i,s,r="image/png",n=!1,o){const{height:a,width:l}=kS(e,t,i);if(!a||!l)return void J.Error("Invalid 'size' parameter !");BS||(BS=document.createElement("canvas")),BS.width=l,BS.height=a;const h=BS.getContext("2d"),c=e.getRenderWidth()/e.getRenderHeight();let u=l,d=u/c;d>a&&(d=a,u=d*c);const p=Math.max(0,l-u)/2,f=Math.max(0,a-d)/2;t.getScene().activeCamera!==t?US(e,t,i,(e=>{if(n){const t=new Blob([e]);Ii.DownloadBlob(t),s&&s("")}else s&&s(e)}),r,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,o):e.onEndFrameObservable.addOnce((()=>{const t=e.getRenderingCanvas();h&&t&&h.drawImage(t,p,f,u,d),BS&&(n?(Ii.EncodeScreenshotCanvasData(BS,void 0,r,void 0,o),s&&s("")):Ii.EncodeScreenshotCanvasData(BS,s,r,void 0,o))}))}function US(e,t,i,s,r="image/png",n=1,o=!1,a,l=!1,h=!1,c=!0,u,d){const{height:p,width:f,finalWidth:_,finalHeight:m}=kS(e,t,i),g={width:f,height:p};if(!p||!f)return void J.Error("Invalid 'size' parameter !");const v={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(f,p);const x=t.getScene(),T=new da("screenShot",g,x,!1,!1,0,!1,Zn.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,n);T.renderList=x.meshes.slice(),T.samples=n,T.renderSprites=l,T.activeCamera=t,T.forceLayerMaskCheck=c,d?.(T);const S=()=>{T.isReadyForRendering()&&t.isReady(!0)?(e.onEndFrameObservable.addOnce((()=>{_===f&&m===p?T.readPixels(void 0,void 0,void 0,!1).then((e=>{ua.DumpData(f,p,e,s,r,a,!0,void 0,u),T.dispose()})):eu("pass",T.getInternalTexture(),x,void 0,void 0,void 0,_,m).then((t=>{e._readTexturePixels(t,_,m,-1,0,null,!0,!1,0,0).then((e=>{ua.DumpData(_,m,e,s,r,a,!0,void 0,u),t.dispose()}))}))})),T.render(!0),x.incrementRenderId(),x.resetCachedMaterial(),e.setSize(v.width,v.height),t.getProjectionMatrix(!0),x.render()):setTimeout(S,16)},E=()=>{x.incrementRenderId(),x.resetCachedMaterial(),S()};if(o){const e=new ET("antialiasing",1,x.activeCamera);T.addPostProcess(e),e.getEffect().isReady()?E():e.getEffect().onCompiled=()=>{E()}}else E()}function kS(e,t,i){let s=0,r=0,n=0,o=0;if("object"==typeof i){const a=i.precision?Math.abs(i.precision):1;i.width&&i.height?(s=i.height*a,r=i.width*a):i.width&&!i.height?(r=i.width*a,s=Math.round(r/e.getAspectRatio(t))):i.height&&!i.width?(s=i.height*a,r=Math.round(s*e.getAspectRatio(t))):(r=Math.round(e.getRenderWidth()*a),s=Math.round(r/e.getAspectRatio(t))),i.finalWidth&&i.finalHeight?(o=i.finalHeight,n=i.finalWidth):i.finalWidth&&!i.finalHeight?(n=i.finalWidth,o=Math.round(n/e.getAspectRatio(t))):i.finalHeight&&!i.finalWidth?(o=i.finalHeight,n=Math.round(o*e.getAspectRatio(t))):(n=r,o=s)}else isNaN(i)||(s=i,r=i,n=i,o=i);return r&&(r=Math.floor(r)),s&&(s=Math.floor(s)),n&&(n=Math.floor(n)),o&&(o=Math.floor(o)),{height:0|s,width:0|r,finalWidth:0|n,finalHeight:0|o}}var GS,zS;Ii.CreateScreenshot=VS,Ii.CreateScreenshotAsync=function(e,t,i,s="image/png",r){return new Promise(((n,o)=>{VS(e,t,i,(e=>{void 0!==e?n(e):o(new Error("Data is undefined"))}),s,void 0,r)}))},Ii.CreateScreenshotUsingRenderTarget=US,Ii.CreateScreenshotUsingRenderTargetAsync=function(e,t,i,s="image/png",r=1,n=!1,o,a=!1,l=!1,h=!0,c){return new Promise(((u,d)=>{US(e,t,i,(e=>{void 0!==e?u(e):d(new Error("Data is undefined"))}),s,r,n,o,a,l,h,c)}))},function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String",e[e.Button=6]="Button",e[e.Options=7]="Options",e[e.Tab=8]="Tab",e[e.FileButton=9]="FileButton",e[e.Vector2=10]="Vector2"}(GS||(GS={}));class WS{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{const e={};return{getItem:t=>{const i=e[t];return void 0===i?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){const i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){const i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){const i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}WS._Storage=WS._GetStorage(),function(e){class t{serialize(){const e={},t=new Array(this._characterToIdx.size);return this._characterToIdx.forEach(((e,i)=>{t[e]=i})),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){const i=JSON.parse(e),s=new t(i.characters);return s._insertionCosts=i.insertionCosts,s._deletionCosts=i.deletionCosts,s._substitutionCosts=i.substitutionCosts,s}constructor(e,t=null,i=null,s=null){let r;t=t??(()=>1),i=i??(()=>1),s=s??((e,t)=>e===t?0:1),this._characterToIdx=new Map,this._insertionCosts=new Array(e.length),this._deletionCosts=new Array(e.length),this._substitutionCosts=new Array(e.length);for(let n=0;ni._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+i._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map((e=>this._alphabet.getCharacterIdx(e)))}distance(e){return i._Distance(this,e)}static _Distance(e,t){const s=e._alphabet;if(s!==t._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const r=e._characters,n=t._characters,o=r.length,a=n.length,l=i._CostMatrix;l[0][0]=0;for(let e=0;enew Array(i._MAX_SEQUENCE_LENGTH+1))),e.Sequence=i}(zS||(zS={}));class HS{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new HS(t._segmentLength);return i._points=t._points.map((e=>new w(e._x,e._y,e._z))),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{const i=()=>this._segmentLength/w.Distance(this._points[t-1],e);for(let s=i();s<=1;s=i()){const i=this._points[t-1].scale(1-s);e.scaleAndAddToRef(s,i),this._points.push(i),++t}}}resampleAtTargetResolution(e){const t=new HS(this.getLength()/e);return this._points.forEach((e=>{t.add(e)})),t}tokenize(e){const t=[],i=new w;for(let s=2;s.98||(w.CrossToRef(HS._ForwardDir,HS._InverseFromVec,HS._UpDir),HS._UpDir.normalize(),B.LookAtLHToRef(e,t,HS._UpDir,HS._LookMatrix),i.subtractToRef(t,HS._FromToVec),HS._FromToVec.normalize(),w.TransformNormalToRef(HS._FromToVec,HS._LookMatrix,s),0))}static _TokenizeSegment(e,t){HS._BestMatch=0,HS._Score=w.Dot(e,t[0]),HS._BestScore=HS._Score;for(let i=1;iHS._BestScore&&(HS._BestMatch=i,HS._BestScore=HS._Score);return HS._BestMatch}}HS._ForwardDir=new w,HS._InverseFromVec=new w,HS._UpDir=new w,HS._FromToVec=new w,HS._LookMatrix=new B;class XS{serialize(){return JSON.stringify(this._sequences.map((e=>e.serialize())))}static Deserialize(e,t){const i=new XS;return i._sequences=JSON.parse(e).map((e=>zS.Sequence.Deserialize(e,t))),i}static CreateFromTrajectory(e,t,i){return XS.CreateFromTokenizationPyramid(XS._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new XS;return i._sequences=e.map((e=>new zS.Sequence(e,t))),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=XS._FINEST_DESCRIPTOR_RESOLUTION){const s=[];for(let r=i;r>4;r=Math.floor(r/2))s.push(e.resampleAtTargetResolution(r).tokenize(t.chars));return s}distance(e){let t,i=0;for(let s=0;se.serialize())),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),s=new YS;return s._descriptors=i.descriptors.map((e=>XS.Deserialize(e,t))),s._centroidIdx=i.centroidIdx,s._averageDistance=i.averageDistance,s}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map((t=>t.distance(e))))}_refreshDescription(){let e;this._centroidIdx=-1;const t=this._descriptors.map((t=>(e=0,this._descriptors.forEach((i=>{e+=t.distance(i)})),e)));for(let e=0;e{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])})),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,YS._MIN_AVERAGE_DISTANCE))}}YS._MIN_AVERAGE_DISTANCE=1;class jS{constructor(e,t,i){this._scene=e,J.Log(`[Reflector] Connecting to ws://${t}:${i}`),this._webSocket=new WebSocket(`ws://${t}:${i}`),this._webSocket.onmessage=e=>{const t=e.data;if(t.startsWith(jS._SERVER_PREFIX)){const e=t.substr(jS._SERVER_PREFIX.length);return J.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),void this._handleServerMessage(e)}J.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{J.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&FS.SerializeAsync(this._scene).then((e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)}))}_handleClientMessage(){}}jS._SERVER_PREFIX="$$";class $S{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){const e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}}const KS=1800,qS="timestamp",QS="numPoints",ZS=/\r/g;class JS{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const e=je.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength;let s=0;if(i>0){const e=this.datasets.startingIndices.at(i-1);s=e+this.datasets.data.at(e+JS.NumberOfPointsOffset)+JS.SliceDataOffset}if(this.datasets.startingIndices.push(s),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach((e=>{const t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())})),this.datasetObservable.hasObservers()){const i=[e,t];for(let e=0;ee.callback(this._datasetMeta,new _(0)))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&(this._strategies.get(e)?.dispose(),this._strategies.delete(e));const s={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,s=0;const r=t.onAfterRenderObservable.add((()=>{s=i,i=0})),n=this._customEventObservable.add((t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)}));return{id:e,getData:()=>s,dispose:()=>{t.onAfterRenderObservable.remove(r),this._customEventObservable.remove(n)}}},category:i}),s}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach((e=>{this.registerEvent(e,!0)}))}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:s}of e){const e=t(this._scene);this._strategies.has(e.id)?e.dispose():(this.datasets.ids.push(e.id),i&&(i=i.replace(new RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:s}),this._strategies.set(e.id,e))}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i>e&255).toString(16)).substr(-2);return i}getCurrentSlice(){const e=[je.Now-this._startingTimestamp,this.datasets.ids.length];this.datasets.ids.forEach((t=>{const i=this._strategies.get(t);i&&this.datasetObservable.hasObservers()&&e.push(i.getData())})),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(e)}updateMetadata(e,t,i){const s=this._datasetMeta.get(e);s&&(s[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new $S(KS),this.datasets.ids.length=0,this.datasets.startingIndices=new $S(KS),this._datasetMeta.clear(),this._strategies.forEach((e=>e.dispose())),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){const i=e.replace(ZS,"").split("\n").map((e=>e.split(",").filter((e=>e.length>0)))).filter((e=>e.length>0)),s=JS.NumberOfPointsOffset;if(i.length<2)return!1;const r={ids:[],data:new $S(KS),startingIndices:new $S(KS)},[n,...o]=i;if(n.length<2||n[0]!==qS||n[s]!==QS)return!1;const a=new Map;for(let e=JS.SliceDataOffset;ee.dispose())),this._strategies.clear(),!t)for(const e of this.datasets.ids){const t=a.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${qS},${QS}`;for(let t=0;t{e.dispose()})),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}ks.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new JS(this)),this._perfCollector},g.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){const e=function(e){const t=new Array,i=new Array,s=new Array,r=e.add((()=>{const e=t.length;for(let r=0;r{t.push(e),i.push(r),s.push(n)},dispose:()=>{e.remove(r)}}}(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return rr(e,this._coroutineScheduler)},g.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};Ft.ShadersStore.equirectangularPanoramaPixelShader="#ifdef GL_ES\nprecision highp float;\n#endif\n#define M_PI 3.1415926535897932384626433832795\nvarying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3(\n- sin( longitude )*sin( latitude ),\ncos( latitude ),\n- cos( longitude )*sin( latitude )\n);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}";class eE extends _o{constructor(e,t={}){super(e),this.options=t,this._direction=new w(0,0,-1),this._mat=new B,this._onSelectEnabled=!1,this._origin=new w(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new g,this._onHitTestResults=e=>{const t=e.map((e=>{const t=B.FromArray(e.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&t.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}}));this.lastNativeXRHitResults=e,this.onHitTestResultObservable.notifyObservers(t)},this._onSelect=e=>{this._onSelectEnabled&&eE.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",Ii.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,s){return e.requestHitTest(t,i).then((e=>{const t=s||(e=>!!e.hitMatrix);return e.filter(t)}))}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const s=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,s,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;B.FromArrayToRef(t.transform.matrix,0,this._mat),w.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),w.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();const i=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});eE.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}eE.Name=po.HIT_TEST,eE.Version=1,fo.AddWebXRFeature(eE.Name,((e,t)=>()=>new eE(e,t)),eE.Version,!1);let tE=0;class iE extends _o{set referenceSpaceForFrameAnchors(e){this._referenceSpaceForFrameAnchors=e}constructor(e,t={}){super(e),this._options=t,this._lastFrameDetected=new Set,this._trackedAnchors=[],this._futureAnchors=[],this.onAnchorAddedObservable=new g,this.onAnchorRemovedObservable=new g,this.onAnchorUpdatedObservable=new g,this._tmpVector=new w,this._tmpQuaternion=new L,this.xrNativeFeatureName="anchors"}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new w,i=new L){this._populateTmpTransformation(t,i);const s=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(!e.xrHitResult.createAnchor)throw this.detach(),new Error("Anchors not enabled in this environment/browser");try{const t=await e.xrHitResult.createAnchor(s);return new Promise(((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:s,resolve:e,reject:i})}))}catch(e){throw new Error(e)}}async addAnchorAtPositionAndRotationAsync(e,t=new L,i=!1){this._populateTmpTransformation(e,t);const s=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),r=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(s,this._xrSessionManager.currentFrame):void 0;return new Promise(((e,t)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!1,xrTransformation:s,resolve:e,reject:t})}))}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){const e=this._trackedAnchors.pop();if(e){try{e.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(e)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;const t=e.trackedAnchors;if(t){const i=this._trackedAnchors.filter((e=>!t.has(e.xrAnchor))).map((e=>this._trackedAnchors.indexOf(e)));let s=0;i.forEach((e=>{const t=this._trackedAnchors.splice(e-s,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),s++})),t.forEach((t=>{if(this._lastFrameDetected.has(t)){const i=this._findIndexInAnchorArray(t),s=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,s,e),s.attachedNode&&(s.attachedNode.rotationQuaternion=s.attachedNode.rotationQuaternion||new L,s.transformationMatrix.decompose(s.attachedNode.scaling,s.attachedNode.rotationQuaternion,s.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(s)}catch(e){Ii.Warn("Anchor could not be updated")}}else{const i={id:tE++,xrAnchor:t,remove:()=>t.delete()},s=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(s),this.onAnchorAddedObservable.notifyObservers(s);const r=this._futureAnchors.filter((e=>e.nativeAnchor===t))[0];r&&(r.resolve(s),r.resolved=!0)}})),this._lastFrameDetected=t}this._futureAnchors.forEach((t=>{t.resolved||t.submitted||(this._createAnchorAtTransformation(t.xrTransformation,e).then((e=>{t.nativeAnchor=e}),(e=>{t.resolved=!0,t.reject(e)})),t.submitted=!0)}))}_findIndexInAnchorArray(e){for(let t=0;t()=>new iE(e,t)),iE.Version);let sE=0;class rE extends _o{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new g,this.onPlaneRemovedObservable=new g,this.onPlaneUpdatedObservable=new g,this.xrNativeFeatureName="plane-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){if(!super.detach())return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){const e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return"undefined"!=typeof XRPlane}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.detectedPlanes||e.worldInformation?.detectedPlanes;if(t){for(let e=0;e{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._findIndexInPlaneArray(t),s=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,s,e),this.onPlaneUpdatedObservable.notifyObservers(s)}}else{const i={id:sE++,xrPlane:t,polygonDefinition:[]},s=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(s),this.onPlaneAddedObservable.notifyObservers(s)}})),this._lastFrameDetected=t}}_init(){const e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),this._xrSessionManager.session.updateWorldTrackingState?(this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()):e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map((e=>{const t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new w(e.x,e.y,e.z*t)}));const s=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(s){const e=t.transformationMatrix||new B;B.FromArrayToRef(s.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new rE(e,t)),rE.Version);class nE extends _o{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new g}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){const t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper)if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){const i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){const i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{const i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach((t=>t.setEnabled(e))),this.onBackgroundStateChangedObservable.notifyObservers(e)}}nE.Name=po.BACKGROUND_REMOVER,nE.Version=1,fo.AddWebXRFeature(nE.Name,((e,t)=>()=>new nE(e,t)),nE.Version,!0);class oE extends _o{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||go.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,s=nc("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});s.isVisible=this._debugMode,s.isPickable=!1,s.rotationQuaternion=new L;const r=e.grip||e.pointer;s.position.copyFrom(r.position),s.rotationQuaternion.copyFrom(r.rotationQuaternion);const n=new go(s,t,{mass:0,...this._options.physicsProperties});this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:s}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||J.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce((t=>{t._doNotLoadControllerMesh?this._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce((()=>{const i=new go(t.rootMesh,go.MeshImpostor,{mass:0,...this._options.physicsProperties}),s=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:s.position.clone(),oldRotation:s.rotationQuaternion.clone()}}))})):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new L,this._tmpVector=new w,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e];t.impostorMesh&&(t.impostorMesh.isVisible=!0)}))}addController(e){this._attachController(e)}attach(){if(!super.attach())return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._options.enableHeadsetImpostor){const e=this._options.headsetImpostorParams||{impostorType:go.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=nc("headset-mesh",{diameterX:"number"==typeof t?t:t.width,diameterY:"number"==typeof t?t:t.height,diameterZ:"number"==typeof t?t:t.depth}),this._headsetMesh.rotationQuaternion=new L,this._headsetMesh.isVisible=!1,this._headsetImpostor=new go(this._headsetMesh,e.impostorType,{mass:0,...e})}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._headsetMesh&&this._headsetMesh.dispose(),!0)}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){const t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties={...this._options.physicsProperties,...e}}_onXRFrame(e){if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),this._options.xrInput.xrCamera._lastXRViewerPose?.linearVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(this._options.xrInput.xrCamera._lastXRViewerPose?.angularVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e],i=t.xrController.grip||t.xrController.pointer,s=t.oldPos||t.impostorMesh.position;if(t.xrController._lastXRPose?.linearVelocity){const e=t.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setLinearVelocity(this._tmpVector)}else i.position.subtractToRef(s,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),t.impostor.setLinearVelocity(this._tmpVector);s.copyFrom(i.position),this._debugMode&&J.Log([this._tmpVector,"linear"]);const r=t.oldRotation||t.impostorMesh.rotationQuaternion;if(t.xrController._lastXRPose?.angularVelocity){const e=t.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setAngularVelocity(this._tmpVector)}else if(!r.equalsWithEpsilon(i.rotationQuaternion)){r.conjugateInPlace().multiplyToRef(i.rotationQuaternion,this._tmpQuaternion);const e=Math.sqrt(this._tmpQuaternion.x*this._tmpQuaternion.x+this._tmpQuaternion.y*this._tmpQuaternion.y+this._tmpQuaternion.z*this._tmpQuaternion.z);if(this._tmpVector.set(this._tmpQuaternion.x,this._tmpQuaternion.y,this._tmpQuaternion.z),e<.001)this._tmpVector.scaleInPlace(2);else{const t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}t.impostor.setAngularVelocity(this._tmpVector)}r.copyFrom(i.rotationQuaternion),this._debugMode&&J.Log([this._tmpVector,this._tmpQuaternion,"angular"])}))}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}oE.Name=po.PHYSICS_CONTROLLERS,oE.Version=1,fo.AddWebXRFeature(oE.Name,((e,t)=>()=>new oE(e,t)),oE.Version,!0);class aE extends _o{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new B,this._tmpPos=new w,this._tmpQuat=new L,this._initHitTestSource=e=>{if(!e)return;const t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),i.space?this._xrSessionManager.session.requestHitTestSource(i).then((e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})):Ii.Warn("waiting for viewer reference space to initialize")},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new g,this.paused=!1,this.xrNativeFeatureName="hit-test",Ii.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach())return!1;if(!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){const e=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:e,entityTypes:this.options.entityTypes}).then((e=>{this._transientXrHitTestSource=e}))}return!0}detach(){return!!super.detach()&&(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(this.attached&&!this.paused){if(this._xrHitTestSource){const t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}this._transientXrHitTestSource&&e.getHitTestResultsForTransientInput(this._transientXrHitTestSource).forEach((e=>{this._processWebXRHitTestResult(e.results,e.inputSource)}))}}_processWebXRHitTestResult(e,t){const i=[];e.forEach((e=>{const s=e.getPose(this._xrSessionManager.referenceSpace);if(!s)return;const r=s.transform.position,n=s.transform.orientation;this._tmpPos.set(r.x,r.y,r.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._tmpQuat.set(n.x,n.y,n.z,n.w),B.FromFloat32ArrayToRefScaled(s.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());const o={position:this.autoCloneTransformation?this._tmpPos.clone():this._tmpPos,rotationQuaternion:this.autoCloneTransformation?this._tmpQuat.clone():this._tmpQuat,transformationMatrix:this.autoCloneTransformation?this._tmpMat.clone():this._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:e};i.push(o)})),this.onHitTestResultObservable.notifyObservers(i)}}aE.Name=po.HIT_TEST,aE.Version=2,fo.AddWebXRFeature(aE.Name,((e,t)=>()=>new aE(e,t)),aE.Version,!1);class lE extends _o{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new g,this.onFeaturePointsUpdatedObservable=new g,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this.featurePointCloud.length=0,!0)}dispose(){super.dispose(),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw new Error("Received malformed feature point cloud of length: "+t.length);const e=t.length/5,i=[],s=[];for(let r=0;r0&&this.onFeaturePointsAddedObservable.notifyObservers(s),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}}lE.Name=po.FEATURE_POINTS,lE.Version=1,fo.AddWebXRFeature(lE.Name,(e=>()=>new lE(e)),lE.Version);let hE=0;class cE extends _o{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new g,this.onMeshRemovedObservable=new g,this.onMeshUpdatedObservable=new g,this.xrNativeFeatureName="mesh-detection",this._options.generateMeshes&&(this._options.convertCoordinateSystems=!0),this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach((e=>{this.onMeshRemovedObservable.notifyObservers(e)})),this._detectedMeshes.clear()),!0)}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){try{if(!this.attached||!e)return;const t=e.detectedMeshes||e.worldInformation?.detectedMeshes;if(t){const i=new Set;this._detectedMeshes.forEach(((e,s)=>{t.has(s)||i.add(s)})),i.forEach((e=>{const t=this._detectedMeshes.get(e);t&&(this.onMeshRemovedObservable.notifyObservers(t),this._detectedMeshes.delete(e))})),t.forEach((t=>{if(this._detectedMeshes.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{const i={id:hE++,xrMesh:t},s=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,s),this.onMeshAddedObservable.notifyObservers(s)}}))}}catch(e){J.Log(e.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;const s=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=s,t.normals=e.normals;else{t.positions=new Float32Array(s.length);for(let e=0;e()=>new cE(e,t)),cE.Version,!1),function(e){e[e.NotReceived=0]="NotReceived",e[e.Waiting=1]="Waiting",e[e.Received=2]="Received"}(uE||(uE={}));class dE extends _o{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new g,this.onTrackableImageFoundObservable=new g,this.onTrackedImageUpdatedObservable=new g,this._trackableScoreStatus=uE.NotReceived,this._trackedImages=[],this.xrNativeFeatureName="image-tracking"}attach(){return super.attach()}detach(){return super.detach()}getTrackedImageById(e){return this._trackedImages[e]||null}dispose(){super.dispose(),this._trackedImages.forEach((e=>{e.originalBitmap.close()})),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()}async getXRSessionInitExtension(){if(!this.options.images||!this.options.images.length)return{};const e=this.options.images.map((e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src)));try{const t=await Promise.all(e);return this._originalTrackingRequest=t.map(((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth}))),{trackedImages:this._originalTrackingRequest}}catch(e){return Ii.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===uE.Waiting)return;if(this._trackableScoreStatus===uE.NotReceived)return void this._checkScoresAsync();const t=e.getImageTrackingResults();for(const i of t){let t=!1;const s=i.index,r=this._trackedImages[s];if(!r)continue;r.xrTrackingResult=i,r.realWorldWidth!==i.measuredWidthInMeters&&(r.realWorldWidth=i.measuredWidthInMeters,t=!0);const n=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(n){const e=r.transformationMatrix;B.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}const o="emulated"===i.trackingState;r.emulated!==o&&(r.emulated=o,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(r)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==uE.NotReceived)return;this._trackableScoreStatus=uE.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(e&&0!==e.length){for(let t=0;t0?uE.Received:uE.NotReceived}else this._trackableScoreStatus=uE.NotReceived}}dE.Name=po.IMAGE_TRACKING,dE.Version=1,fo.AddWebXRFeature(dE.Name,((e,t)=>()=>new dE(e,t)),dE.Version,!1);class pE extends _o{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",Ii.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!(!super.attach()||!this._xrSessionManager.session.domOverlayState||null===this._xrSessionManager.session.domOverlayState.type||(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),0))}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(void 0===this.options.element)return Ii.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){const e=document.querySelector(this.options.element);if(null===e)return Ii.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`),{};this._element=e}else this._element=this.options.element;return{domOverlay:{root:this._element}}}}pE.Name=po.DOM_OVERLAY,pE.Version=1,fo.AddWebXRFeature(pE.Name,((e,t)=>()=>new pE(e,t)),pE.Version,!1);class fE extends _o{get movementDirection(){return this._movementDirection}get movementEnabled(){return this._featureContext.movementEnabled}set movementEnabled(e){this._featureContext.movementEnabled=e}get movementOrientationFollowsViewerPose(){return this._featureContext.movementOrientationFollowsViewerPose}set movementOrientationFollowsViewerPose(e){this._featureContext.movementOrientationFollowsViewerPose=e}get movementSpeed(){return this._featureContext.movementSpeed}set movementSpeed(e){this._featureContext.movementSpeed=e}get movementThreshold(){return this._featureContext.movementThreshold}set movementThreshold(e){this._featureContext.movementThreshold=e}get rotationEnabled(){return this._featureContext.rotationEnabled}set rotationEnabled(e){this._featureContext.rotationEnabled=e}get rotationSpeed(){return this._featureContext.rotationSpeed}set rotationSpeed(e){this._featureContext.rotationSpeed=e}get rotationThreshold(){return this._featureContext.rotationThreshold}set rotationThreshold(e){this._featureContext.rotationThreshold=e}constructor(e,t){super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new L,this._tmpRotationMatrix=B.Identity(),this._tmpTranslationDirection=new w,this._tmpMovementTranslation=new w,this._tempCacheQuaternion=new L,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController)for(const i of this._currentRegistrationConfigurations){let s=null;if(i.allowedComponentTypes)for(const t of i.allowedComponentTypes){const i=e.motionController.getComponentOfType(t);if(null!==i){s=i;break}}if(i.mainComponentOnly){const t=e.motionController.getMainComponent();if(null===t)continue;s=t}if("function"==typeof i.componentSelectionPredicate&&(s=i.componentSelectionPredicate(e)),s&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness)continue;if(null===s)continue;const r={registrationConfiguration:i,component:s};t.registeredComponents.push(r),"axisChangedHandler"in i&&(r.onAxisChangedObserver=s.onAxisValueChangedObservable.add((e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)}))),"buttonChangedhandler"in i&&(r.onButtonChangedObserver=s.onButtonStateChangedObservable.add((()=>{s.changes.pressed&&i.buttonChangedhandler(s.changes.pressed,this._movementState,this._featureContext,this._xrInput)})))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}},t&&void 0!==t.xrInput?(Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=fE.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:t.movementOrientationFollowsViewerPose??!0,movementSpeed:t.movementSpeed??1,movementThreshold:t.movementThreshold??.25,rotationEnabled:t.rotationEnabled??!0,rotationSpeed:t.rotationSpeed??1,rotationThreshold:t.rotationThreshold??.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput):Ii.Error('WebXRControllerMovement feature requires "xrInput" option.')}attach(){return!!super.attach()&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._controllers={},!0)}_onXRFrame(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){const e=.001*this._xrSessionManager.scene.getEngine().getDeltaTime()*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=e,L.RotationYawPitchRollToRef(e,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(L.RotationYawPitchRollToRef(3*e,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(B.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),w.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}}_detachController(e){const t=this._controllers[e];if(t){for(const e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}}fE.Name=po.MOVEMENT,fE.REGISTRATIONS={default:[{allowedComponentTypes:[Bf.THUMBSTICK_TYPE,Bf.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(e,t,i)=>{t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[Bf.THUMBSTICK_TYPE,Bf.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(e,t,i)=>{t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},fE.Version=1,fo.AddWebXRFeature(fE.Name,((e,t)=>()=>new fE(e,t)),fE.Version,!0);class _E extends _o{constructor(e,t){super(e),this.options=t,this._canvasContext=null,this._reflectionCubeMap=null,this._xrLightEstimate=null,this._xrLightProbe=null,this._xrWebGLBinding=null,this._lightDirection=w.Up().negateInPlace(),this._lightColor=Y.White(),this._intensity=1,this._sphericalHarmonics=new qc,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new g,this._updateReflectionCubeMap=()=>{if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const e=Date.now();if(e-this._cubeMapPollTime{this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap)})))}},this.xrNativeFeatureName="light-estimation",this.options.createDirectionalLightSource&&(this.directionalLight=new $p("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new w(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=Os.FALLOFF_GLTF),this._hdrFilter=new O_(this._xrSessionManager.scene.getEngine()),Ii.Warn("light-estimation is an experimental and unstable feature.")}get reflectionCubeMapTexture(){return this._reflectionCubeMap}get xrLightingEstimate(){return this._xrLightEstimate?{lightColor:this._lightColor,lightDirection:this._lightDirection,lightIntensity:this._intensity,sphericalHarmonics:this._sphericalHarmonics}:this._xrLightEstimate}_getCanvasContext(){return null===this._canvasContext&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(null===this._xrWebGLBinding){const e=this._getCanvasContext();this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,e)}return this._xrWebGLBinding}attach(){if(!super.attach())return!1;const e=this.options.reflectionFormat??(this._xrSessionManager.session.preferredReflectionFormat||"srgba8");return this.options.reflectionFormat=e,this._xrSessionManager.session.requestLightProbe({reflectionFormat:e}).then((e=>{this._xrLightProbe=e,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new qn(this._xrSessionManager.scene),this._reflectionCubeMap._isCube=!0,this._reflectionCubeMap.coordinatesMode=3,this.options.setSceneEnvironmentTexture&&(this._xrSessionManager.scene.environmentTexture=this._reflectionCubeMap)),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap))})),!0}detach(){const e=super.detach();return null===this._xrLightProbe||this.options.disableCubeMapReflection||(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,e}dispose(){super.dispose(),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){const e=Date.now();if(e-this._lightEstimationPollTime()=>new _E(e,t)),_E.Version,!1);class mE extends _o{constructor(e){super(e),this.onEyeTrackingStartedObservable=new g,this.onEyeTrackingEndedObservable=new g,this.onEyeTrackingFrameUpdateObservable=new g,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new ao(w.Zero(),w.Forward()),this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay)},this._eyeTrackingEndListener=()=>{this._latestEyeSpace=null,this._gazeRay=null,this.onEyeTrackingEndedObservable.notifyObservers()},this.xrNativeFeatureName="eye-tracking",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}dispose(){super.dispose(),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()}get isEyeGazeValid(){return!!this._gazeRay}getEyeGaze(){return this._gazeRay}_onXRFrame(e){if(this.attached&&e&&this._latestEyeSpace&&this._gazeRay){const t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z).scaleInPlace(this._xrSessionManager.worldScalingFactor);const e=t.transform.orientation;U.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?w.RightHandedForwardReadOnly.rotateByQuaternionToRef(U.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,U.Quaternion[0].z*=-1,U.Quaternion[0].w*=-1,w.LeftHandedForwardReadOnly.rotateByQuaternionToRef(U.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))}}mE.Name=po.EYE_TRACKING,mE.Version=1,fo.AddWebXRFeature(mE.Name,(e=>()=>new mE(e)),mE.Version,!1);class gE{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw new Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class vE{constructor(){this._samples=new gE(20),this._entropy=0,this.onFirstStepDetected=new g}update(e,t,i,s){this._samples.push(e,t);const r=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=N.Distance(r,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let n;for(n=this._samePointCheckStartIdx;no&&(a=t,o=e);if(on*this._squaredProjectionDistanceThreshold)return;const f=U.Vector3[0];f.set(i,s,0);const _=U.Vector3[1];_.set(h.x,h.y,0);const m=w.Cross(f,_).z>0,g=r.clone(),v=r.clone();l.subtractToRef(r,h),m?(h.scaleAndAddToRef(this._axisToApexShrinkFactor,g),h.scaleAndAddToRef(this._axisToApexExtendFactor,v)):(h.scaleAndAddToRef(this._axisToApexExtendFactor,g),h.scaleAndAddToRef(this._axisToApexShrinkFactor,v)),this.onFirstStepDetected.notifyObservers({leftApex:g,rightApex:v,currentPosition:r,currentStepDirection:m?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),this._axisLength<.03))}get _vitalityThreshold(){return.1}get forward(){return this._forward}}class TE{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new vE,this._walker=null,this._movement=new N,this._millisecondsSinceLastUpdate=TE._MillisecondsPerUpdate,this.movementThisFrame=w.Zero(),this._engine=e,this._detector.onFirstStepDetected.add((e=>{this._walker||(this._walker=new xE(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),this._walker.onFootfall.add((()=>{J.Log("Footfall!")})),this._walker.onMovement.add((e=>{this._walker.forward.scaleAndAddToRef(.024*e.deltaT,this._movement)})))}))}update(e,t){t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=TE._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=TE._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker&&(this._walker.update(e.x,e.z)||(this._walker=null)),this._movement.scaleInPlace(.85)),this.movementThisFrame.set(this._movement.x,0,this._movement.y)}}class SE extends _o{static get Name(){return po.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()}constructor(e,t){super(e),this._up=new w,this._forward=new w,this._position=new w,this._movement=new w,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&J.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended")}isCompatible(){return void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!(!this.isCompatible||!super.attach()||(this._walker=new TE(this._sessionManager.scene.getEngine()),0))}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){const t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;const i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,s=t.transform.matrix;this._up.copyFromFloats(s[4],s[5],i*s[6]),this._forward.copyFromFloats(s[8],s[9],i*s[10]),this._position.copyFromFloats(s[12],s[13],i*s[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||w.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}fo.AddWebXRFeature(SE.Name,((e,t)=>()=>new SE(e,t)),SE.Version,!1);class EE extends fh{constructor(e,t,i,s,r,n,o=null){super(e,t,i,s,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this.isMultiview=r,this.createRTTProvider=n,this._originalInternalTexture=o}}class bE extends _h{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this.onRenderTargetTextureCreatedObservable=new g,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t="none"){const i=this._lastSubImages.get(t),s="right"==t?1:0,r=e.colorTextureWidth??e.textureWidth,n=e.colorTextureHeight??e.textureHeight;if(!this._renderTargetTextures[s]||i?.textureWidth!==r||i?.textureHeight!==n){let i;const o=e.depthStencilTextureWidth??r,a=e.depthStencilTextureHeight??n;r!==o&&n!==a||(i=e.depthStencilTexture),this._renderTargetTextures[s]=this._createRenderTargetTexture(r,n,null,e.colorTexture,i,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n},this.onRenderTargetTextureCreatedObservable.notifyObservers({texture:this._renderTargetTextures[s],eye:t})}return this._lastSubImages.set(t,e),this._renderTargetTextures[s]}_getSubImageForEye(e){const t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){const t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e?.eye)}_setViewportForSubImage(e,t){const i=t.colorTextureWidth??t.textureWidth,s=t.colorTextureHeight??t.textureHeight,r=t.viewport;e.x=r.x/i,e.y=r.y/s,e.width=r.width/i,e.height=r.height/s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}}class CE extends EE{constructor(e,t,i){super((()=>e.textureWidth),(()=>e.textureHeight),e,"XRProjectionLayer",t,(e=>new yE(e,i,this))),this.layer=e}}class yE extends bE{constructor(e,t,i){super(e,t,i),this.layerWrapper=i,this._projectionLayer=i.layer}_getSubImageForView(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)}getRenderTargetTextureForView(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)}getRenderTargetTextureForEye(e){const t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}}const AE={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1,clearOnAccess:!1},RE={};class IE extends _o{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this._isMultiviewEnabled=!1,this._projectionLayerInitialized=!1,this._compositionLayerTextureMapping=new WeakMap,this._layerToRTTProviderMapping=new WeakMap,this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;const t={...AE,...this._options.projectionLayerInit};return this._isMultiviewEnabled=this._options.preferMultiviewOnInit&&e.getCaps().multiview,this.createProjectionLayer(t),this._projectionLayerInitialized=!0,!0}detach(){return!!super.detach()&&(this._existingLayers.forEach((e=>{e.dispose()})),this._existingLayers.length=0,this._projectionLayerInitialized=!1,!0)}createXRWebGLLayer(e=RE){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new mh(t)}_validateLayerInit(e,t=this._isMultiviewEnabled){if(!this._xrSessionManager.inXRSession)throw new Error("Cannot create a layer outside of a WebXR session. Make sure the session has started before creating layers.");if(t&&"texture-array"!==e.textureType)throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)throw new Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.")}_extendXRLayerInit(e,t=this._isMultiviewEnabled){return t&&(e.textureType="texture-array"),e}createProjectionLayer(e=AE,t=this._isMultiviewEnabled){this._extendXRLayerInit(e,t),this._validateLayerInit(e,t);const i=this._xrWebGLBinding.createProjectionLayer(e),s=new CE(i,t,this._xrWebGLBinding);return this.addXRSessionLayer(s),s}_createQuadLayer(e={params:{}},t){this._extendXRLayerInit(e.params,!1);const i=this._existingLayers[0].layer.textureWidth,s=this._existingLayers[0].layer.textureHeight,r={space:this._xrSessionManager.referenceSpace,viewPixelWidth:i,viewPixelHeight:s,clearOnAccess:!0,...e.params};this._validateLayerInit(r,!1);const n=this._xrWebGLBinding.createQuadLayer(r);n.width=this._isMultiviewEnabled?1:2,n.height=1;const o=new EE((()=>n.width),(()=>n.height),n,"XRQuadLayer",!1,(e=>new bE(e,this._xrWebGLBinding,o)));t&&this._compositionLayerTextureMapping.set(n,t);const a=o.createRenderTargetTextureProvider(this._xrSessionManager);return this._layerToRTTProviderMapping.set(n,a),this.addXRSessionLayer(o),o}addFullscreenAdvancedDynamicTexture(e,t={distanceFromHeadset:1.5}){const i=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}},e),s=i.layer,r={x:0,y:0,z:-Math.max(.1,t.distanceFromHeadset)};s.transform=new XRRigidTransform(r,{x:0,y:0,z:0,w:1});const n=this._layerToRTTProviderMapping.get(s);if(!n)throw new Error("Could not find the RTT provider for the layer");const o=this._xrSessionManager.scene.layers.find((t=>t.texture===e));if(!o)throw new Error("Could not find the babylon layer for the texture");return n.onRenderTargetTextureCreatedObservable.add((e=>{e.eye&&"right"===e.eye||(e.texture.clearColor=new j(0,0,0,0),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.scene.onBeforeRenderObservable.add((()=>{e.texture.render()})),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.onXRSessionEnded.addOnce((()=>{o.renderTargetTextures.splice(o.renderTargetTextures.indexOf(e.texture),1),o.renderOnlyInRenderTargetTextures=!1})))})),i}_addLensFlareSystem(e){const t=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}}),i=t.layer;i.width=2,i.height=1;i.transform=new XRRigidTransform({x:0,y:0,z:-10},{x:0,y:0,z:0,w:1});const s=this._layerToRTTProviderMapping.get(i);if(!s)throw new Error("Could not find the RTT provider for the layer");return s.onRenderTargetTextureCreatedObservable.add((t=>{t.texture.clearColor=new j(0,0,0,0),t.texture.customRenderFunction=()=>{e.render()}})),this._xrSessionManager.onXRSessionInit.add((()=>{this._xrSessionManager.scene.lensFlareSystems.splice(this._xrSessionManager.scene.lensFlareSystems.indexOf(e),1)})),this._xrSessionManager.onXRSessionEnded.add((()=>{this._xrSessionManager.scene.lensFlareSystems.push(e)})),t}addXRSessionLayer(e){this._existingLayers.push(e),this.setXRSessionLayers(this._existingLayers)}setXRSessionLayers(e=this._existingLayers){const t={...this._xrSessionManager.session.renderState};t.baseLayer=void 0,t.layers=e.map((e=>e.layer)),this._xrSessionManager.updateRenderState(t),this._projectionLayerInitialized||this._xrSessionManager._setBaseLayerWrapper(e.length>0?e.at(0):null)}isCompatible(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){const t=this._existingLayers;for(let i=0;i()=>new IE(e,t)),IE.Version,!1);class PE extends _o{get width(){return this._width}get height(){return this._height}get rawValueToMeters(){return this._rawValueToMeters}get normDepthBufferFromNormView(){return this._normDepthBufferFromNormView}get depthUsage(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}}get depthDataFormat(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}}get latestInternalTexture(){if(!this._cachedWebGLTexture)return null;const e=this._xrSessionManager.scene.getEngine(),t=new ti(e,ei.Unknown);return t.isCube=!1,t.invertY=!1,t._useSRGBBuffer=!1,t.format="ushort"===this.depthDataFormat?2:5,t.generateMipMaps=!1,t.type="ushort"===this.depthDataFormat?5:1,t.samplingMode=7,t.width=this.width??0,t.height=this.height??0,t._cachedWrapU=1,t._cachedWrapV=1,t._hardwareTexture=new Hi(this._cachedWebGLTexture,e._gl),t}get latestDepthBuffer(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null}get latestDepthImageTexture(){return this._cachedDepthImageTexture}constructor(e,t){super(e),this.options=t,this._width=null,this._height=null,this._rawValueToMeters=null,this._normDepthBufferFromNormView=null,this._cachedDepthBuffer=null,this._cachedWebGLTexture=null,this._cachedDepthImageTexture=null,this.onGetDepthInMetersAvailable=new g,this.xrNativeFeatureName="depth-sensing",Ii.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){return!!super.attach(e)&&(null!=this._xrSessionManager.session.depthDataFormat&&null!=this._xrSessionManager.session.depthUsage&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0))}dispose(){this._cachedDepthImageTexture?.dispose()}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(const t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:Ii.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(null===s)return;const{data:r,width:n,height:o,rawValueToMeters:a,getDepthInMeters:l}=s;switch(this._width=n,this._height=o,this._rawValueToMeters=a,this._cachedDepthBuffer=r,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(s)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=io.CreateRTexture(null,n,o,this._xrSessionManager.scene,!1,!0,Zn.NEAREST_SAMPLINGMODE,Br.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(r)).map((e=>e*a)));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(r).map((e=>e*a)))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(null===s)return;const{texture:r,width:n,height:o}=s;this._width=n,this._height=o,this._cachedWebGLTexture=r;const a=this._xrSessionManager.scene,l=a.getEngine().wrapWebGLTexture(r);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=io.CreateRTexture(null,n,o,a,!1,!0,Zn.NEAREST_SAMPLINGMODE,"ushort"===i?Br.TEXTURETYPE_UNSIGNED_BYTE:Br.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=l}getXRSessionInitExtension(){const e=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,t=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise((i=>{i(e&&t?{depthSensing:{usagePreference:this.options.usagePreference.map((e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}})),dataFormatPreference:this.options.dataFormatPreference.map((e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}}))}}:{})}))}}PE.Name=po.DEPTH_SENSING,PE.Version=1,fo.AddWebXRFeature(PE.Name,((e,t)=>()=>new PE(e,t)),PE.Version,!1);Ft.ShadersStore.velocityPixelShader="precision highp float;\n#define CUSTOM_FRAGMENT_BEGIN\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nhighp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.velocityVertexShader="#define CUSTOM_VERTEX_BEGIN\n#define VELOCITY\nattribute vec3 position;\n#include\nuniform mat4 viewProjection;uniform mat4 previousViewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR;\n#endif\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;}\n#elif\nclipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class ME extends da{constructor(e,t,i,s=512){super("spacewarp rtt",s,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[B.Identity(),B.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new fc("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add((e=>{this._previousWorldMatrices[e.uniqueId]=this._previousWorldMatrices[e.uniqueId]||e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[e.uniqueId]),this._previousWorldMatrices[e.uniqueId]=e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)})),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;const i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach((e=>{this._originalPairing.push([e,e.material]),e.material=this._velocityMaterial})),super.render(e,t),this._originalPairing.forEach((e=>{e[0].material=e[1]}))}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}}class DE{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){const t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');const i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,s,r){if(!this._engine)throw new Error("Engine is disposed");const n={width:e,height:t},o=new ME(s,r,this._scene,n),a=o.renderTarget;return i&&(a._framebuffer=i),a._colorTextureArray=s,a._depthStencilTextureArray=r,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let s=this._renderTargetTextures.get(t.eye);const r=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return s&&i?.textureWidth===r&&i?.textureHeight==n||(s=this._createRenderTargetTexture(r,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,s),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n}),this._lastSubImages.set(t,e),s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}accessMotionVector(e){const t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){const t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.clear()}}class OE extends _o{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[po.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new DE(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add((()=>this._onAfterRender())),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;const i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}}OE.Name=po.SPACE_WARP,OE.Version=1,fo.AddWebXRFeature(OE.Name,(e=>()=>new OE(e)),OE.Version,!1);class NE extends _o{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new g,this.xrNativeFeatureName="camera-access"}attach(e){return!!super.attach(e)&&(this._glContext=this._xrSessionManager.scene.getEngine()._gl,this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),!0)}detach(){return!!super.detach()&&(this._glBinding=void 0,this.options.doNotDisposeOnDetach||(this._cachedInternalTextures.forEach((e=>e.dispose())),this.texturesData.forEach((e=>e.dispose())),this._cachedInternalTextures.length=0,this.texturesData.length=0,this.cameraIntrinsics.length=0),!0)}dispose(){super.dispose(),this.onTexturesUpdatedObservable.clear()}_updateCameraIntrinsics(e,t){const i={width:e.camera.width,height:e.camera.height,x:0,y:0},s=e.projectionMatrix,r=(1-s[8])*i.width/2+i.x,n=(1-s[9])*i.height/2+i.y,o=i.width/2*s[0],a=i.height/2*s[5],l=i.width/2*s[4];this.cameraIntrinsics[t]={u0:r,v0:n,ax:o,ay:a,gamma:l,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){if(!e.camera)return!1;this.viewIndex[t]=e.eye;const i=this._glBinding?.getCameraImage(e.camera);if(this._cachedInternalTextures[t])this._cachedInternalTextures[t]._hardwareTexture?.set(i);else{const s=new ti(this._xrSessionManager.scene.getEngine(),ei.Unknown,!0);s.isCube=!0,s.invertY=!1,s.format=5,s.generateMipMaps=!0,s.type=1,s.samplingMode=3,s.width=e.camera.width,s.height=e.camera.height,s._cachedWrapU=1,s._cachedWrapV=1,s._hardwareTexture=new Hi(i,this._glContext),this._cachedInternalTextures[t]=s;const r=new qn(this._xrSessionManager.scene);r.name=`WebXR Raw Camera Access (${t})`,r._texture=this._cachedInternalTextures[t],this.texturesData[t]=r,this._updateCameraIntrinsics(e,t)}return this._cachedInternalTextures[t].isReady=!0,!0}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(!i||!i.views)return;let s=!0;i.views.forEach(((e,t)=>{s=s&&this._updateInternalTextures(e,t)})),s&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}NE.Name=po.RAW_CAMERA_ACCESS,NE.Version=1,fo.AddWebXRFeature(NE.Name,((e,t)=>()=>new NE(e,t)),NE.Version,!1);class wE extends Vf{constructor(e,t,i){super(e,FE[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}}Wf.RegisterController("generic-hand-select-grasp",((e,t)=>new wE(t,e.gamepad,e.handedness)));const FE={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};class LE extends Vf{constructor(e,t,i){super(e,BE["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";return e="left"===this.handedness?LE.MODEL_LEFT_FILENAME:LE.MODEL_RIGHT_FILENAME,{filename:e,path:LE.MODEL_BASE_URL+"default/"}}_getModelLoadingConstraints(){const e=Ro.IsPluginForExtensionAvailable(".glb");return e||J.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach(((e,t)=>{if(!this.disableAnimation&&e&&this.rootMesh){const i=this._mapping.buttons[e],s=i.rootNodeName;if(!s)return void J.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);const r=this._getChildByName(this.rootMesh,s);if(!r)return void J.Warn("Missing button mesh with name: "+s);if(i.valueMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.valueNodeName),i.pressedMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.pressedNodeName),i.unpressedMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.unpressedNodeName),i.valueMesh&&i.pressedMesh&&i.unpressedMesh){const t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add((e=>{this._lerpTransform(i,e.value)}),void 0,!0)}else J.Warn("Missing button submesh under mesh with name: "+s)}})),this.getComponentIds().forEach((e=>{const t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach((i=>{if(!this.rootMesh)return;const s=this._mapping.axes[e][i],r=this._getChildByName(this.rootMesh,s.rootNodeName);r?(s.valueMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.valueNodeName),s.minMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.minNodeName),s.maxMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.maxNodeName),s.valueMesh&&s.minMesh&&s.maxMesh?t&&t.onAxisValueChangedObservable.add((e=>{const t="x-axis"===i?e.x:e.y;this._lerpTransform(s,t,!0)}),void 0,!0):J.Warn("Missing axis submesh under mesh with name: "+s.rootNodeName)):J.Warn("Missing axis mesh with name: "+s.rootNodeName)}))})))}_setRootMesh(e){let t;this.rootMesh=new Un(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;inew LE(t,e.gamepad,e.handedness)));const BE={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};class VE extends Vf{constructor(e,t,i,s=!1,r=!1){super(e,UE[i],t,i),this._forceLegacyControllers=r,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";return e="left"===this.handedness?VE.MODEL_LEFT_FILENAME:VE.MODEL_RIGHT_FILENAME,{filename:e,path:this._isQuest()?VE.QUEST_MODEL_BASE_URL:VE.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){const t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach((e=>{const s=e&&this.getComponent(e);s&&s.onButtonStateChangedObservable.add((s=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(t||(this._modelRootNode.getChildren()[3].rotation.x=.2*-s.value,this._modelRootNode.getChildren()[3].position.y=.005*-s.value,this._modelRootNode.getChildren()[3].position.z=.005*-s.value));case"xr-standard-squeeze":return void(t||(this._modelRootNode.getChildren()[4].position.x=i*s.value*.0035));case"xr-standard-thumbstick":return;case"a-button":case"x-button":return void(t||(s.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0));case"b-button":case"y-button":return void(t||(s.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0))}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new Un(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=L.FromEulerAngles(0,Math.PI,0)),e.forEach((e=>{e.isPickable=!1})),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}}VE.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",VE.MODEL_LEFT_FILENAME="left.babylon",VE.MODEL_RIGHT_FILENAME="right.babylon",VE.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",Wf.RegisterController("oculus-touch",((e,t)=>new VE(t,e.gamepad,e.handedness))),Wf.RegisterController("oculus-touch-legacy",((e,t)=>new VE(t,e.gamepad,e.handedness,!0)));const UE={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};class kE extends Vf{constructor(e,t,i){super(e,GE[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){return{filename:kE.MODEL_FILENAME,path:kE.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add((t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(this._modelRootNode.getChildren()[6].rotation.x=.15*-t.value);case"xr-standard-touchpad":case"xr-standard-squeeze":return}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new Un(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1})),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=L.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}kE.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",kE.MODEL_FILENAME="wand.babylon",Wf.RegisterController("htc-vive",((e,t)=>new kE(t,e.gamepad,e.handedness)));const GE={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};var zE;!async function(e,t){(await new Promise((e=>{"undefined"==typeof _native?Yu.addOnce((t=>e(t))):e(_native)}))).NativeXRFrame=class{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw new Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>this._nativeImpl._imageTrackingResults??[]}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;const i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];const s=this._xrTransform.orientation;return s.x=this._xrPoseVectorData[4],s.y=this._xrPoseVectorData[5],s.z=this._xrPoseVectorData[6],s.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw new Error("This function is not available in Babylon Native")}}}(),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(zE||(zE={}));class WE{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=Si(),this.connectedPointIds=[],this.name=e,this._connectionType=t}get connectionType(){return this._connectionType}_isSingularConnection(){return!0}isConnected(){return this._connectedPoint.length>0}connectTo(e){if(this._connectionType===e._connectionType)throw new Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw new Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName();for(const t of this._connectedPoint)e.connectedPointIds.push(t.uniqueId)}getClassName(){return"FGConnection"}deserialize(e){this.uniqueId=e.uniqueId,this.name=e.name,this._connectionType=e._connectionType,this.connectedPointIds=e.connectedPointIds}static Parse(e={},t){const i=new(Ii.Instantiate(e.className))(e.name,e._connectionType,t);return i.deserialize(e),i}}class HE{constructor(e){this.value=this._toInt(e)}_toInt(e){return 0|e}add(e){return new HE(this.value+e.value)}subtract(e){return new HE(this.value-e.value)}multiply(e){return new HE(Math.imul(this.value,e.value))}divide(e){return new HE(this.value/e.value)}getClassName(){return HE.ClassName}equals(e){return this.value===e.value}static Parse(e){return new HE(e.value)}}HE.ClassName="FlowGraphInteger",u("FlowGraphInteger",HE);class XE{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new XE(e.typeName,e.defaultValue)}}const YE=new XE("any",void 0),jE=new XE("string",""),$E=new XE("number",0),KE=new XE("boolean",!1),qE=new XE("Vector2",N.Zero()),QE=new XE("Vector3",w.Zero()),ZE=new XE("Vector4",F.Zero()),JE=new XE("Matrix",B.Identity()),eb=new XE("Color3",Y.Black()),tb=new XE("Color4",new j(0,0,0,0)),ib=new XE("Quaternion",L.Identity()),sb=new XE("FlowGraphInteger",new HE(0));class rb extends WE{constructor(e,t,i,s){super(e,t,i),this.richType=s}_isSingularConnection(){return this.connectionType===zE.Input}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===zE.Output?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){const i=WE.Parse(e,t);return i.richType=XE.Parse(e.richType),i}}function nb(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function ob(e){return"Vector2"===e||"Vector3"===e||"Vector4"===e||"Quaternion"===e||"Color3"===e||"Color4"===e}function ab(e,t,i){const s=t?.getClassName?.()??"";nb(s)?i[e]={name:t.name,className:s}:ob(s)?i[e]={value:t.asArray(),className:s}:i[e]=t}function lb(e,t,i){const s=t[e];let r;const n=s?.className;return r=nb(n)?i.getMeshByName(s.name):ob(n)?function(e,t){if("Vector2"===e)return N.FromArray(t);if("Vector3"===e)return w.FromArray(t);if("Vector4"===e)return F.FromArray(t);if("Quaternion"===e)return L.FromArray(t);if("Color3"===e)return new Y(t[0],t[1],t[2]);if("Color4"===e)return new j(t[0],t[1],t[2],t[3]);throw new Error(`Unknown vector class name ${e}`)}(n,s.value):"Matrix"===n?B.FromArray(s.value):n===HE.ClassName?HE.Parse(s):s&&void 0!==s.value?s.value:s,r}u("FGDataConnection",rb);class hb{constructor(e){this.config=e,this.uniqueId=Si(),this.name=this.config?.name??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new rb(e,zE.Input,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new rb(e,zE.Output,this,t);return this.dataOutputs.push(i),i}getDataInput(e){return this.dataInputs.find((t=>t.name===e))}getDataOutput(e){return this.dataOutputs.find((t=>t.name===e))}serialize(e={},t=ab){e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName();for(const t of this.dataInputs){const i={};t.serialize(i),e.dataInputs.push(i)}for(const t of this.dataOutputs){const i={};t.serialize(i),e.dataOutputs.push(i)}}getClassName(){return"FGBlock"}static Parse(e,t){const i=Ii.Instantiate(e.className),s={},r=t.valueParseFunction??lb;if(e.config)for(const i in e.config)s[i]=r(i,e.config,t.scene);var n;("FGSetPropertyBlock"===(n=e.className)||"FGGetPropertyBlock"===n||"FGPlayAnimationBlock"===n||"FGMeshPickEventBlock"===n)&&(s.pathConverter=t.pathConverter);const o=new i(s);o.uniqueId=e.uniqueId;for(let t=0;tt.name===e))}getSignalOutput(e){return this.signalOutputs.find((t=>t.name===e))}serialize(e={}){super.serialize(e),e.signalInputs=[],e.signalOutputs=[];for(const t of this.signalInputs){const i={};t.serialize(i),e.signalInputs.push(i)}for(const t of this.signalOutputs){const i={};t.serialize(i),e.signalOutputs.push(i)}}deserialize(e){for(let t=0;t{t.type===ss.POINTERPICK&&t.pickInfo?.pickedMesh&&(t.pickInfo?.pickedMesh===i||_b(t.pickInfo?.pickedMesh,i))&&this._execute(e)}));const s=i.onDisposeObservable.add((()=>this._onDispose));e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",s)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),s=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(s),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return mb.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}var gb;mb.ClassName="FGMeshPickEventBlock",u(mb.ClassName,mb),function(e){e[e.Stopped=0]="Stopped",e[e.Started=1]="Started"}(gb||(gb={}));class vb{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=gb.Stopped,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>this.dispose()))}createContext(){const e=new fb({scene:this._scene,coordinator:this._coordinator});return this._executionContexts.push(e),e}getContext(e){return this._executionContexts[e]}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==gb.Started){this.state=gb.Started,0===this._executionContexts.length&&this.createContext();for(const e of this._executionContexts){const t=this._getContextualOrder();for(const i of t)i._startPendingTasks(e)}}}_getContextualOrder(){const e=[];for(const t of this._eventBlocks)if(t.getClassName()===mb.ClassName){const i=t._getReferencedMesh();let s=0;for(;s0;){const s=t.pop();e(s);for(const e of s.dataInputs)for(const s of e._connectedPoint)i.has(s._ownerBlock.uniqueId)||(t.push(s._ownerBlock),i.add(s._ownerBlock.uniqueId));if(s instanceof ub)for(const e of s.signalOutputs)for(const s of e._connectedPoint)i.has(s._ownerBlock.uniqueId)||(t.push(s._ownerBlock),i.add(s._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks((t=>{const i={};t.serialize(i),e.allBlocks.push(i)})),e.executionContexts=[];for(const i of this._executionContexts){const s={};i.serialize(s,t),e.executionContexts.push(s)}}static GetDataOutConnectionByUniqueId(e,t){for(const i of e)for(const e of i.dataOutputs)if(e.uniqueId===t)return e;throw new Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(const i of e)if(i instanceof ub)for(const e of i.signalInputs)if(e.uniqueId===t)return e;throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const i=t.coordinator.createGraph(),s=[],r=t.valueParseFunction??lb;for(const n of e.allBlocks){const e=hb.Parse(n,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:r});s.push(e),e instanceof pb&&i.addEventBlock(e)}for(const e of s){for(const t of e.dataInputs)for(const e of t.connectedPointIds){const i=vb.GetDataOutConnectionByUniqueId(s,e);t.connectTo(i)}if(e instanceof ub)for(const t of e.signalOutputs)for(const e of t.connectedPointIds){const i=vb.GetSignalInConnectionByUniqueId(s,e);t.connectTo(i)}}for(const t of e.executionContexts)fb.Parse(t,{graph:i,valueParseFunction:r});return i}}class xb{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add((()=>{this.dispose()})),(xb.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new vb({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){const t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach((e=>e.start()))}dispose(){this._flowGraphs.forEach((e=>e.dispose())),this._flowGraphs.length=0;const e=xb.SceneCoordinators.get(this.config.scene)??[],t=e.indexOf(this);-1!==t&&e.splice(t,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach((i=>{const s={};i.serialize(s,t),e._flowGraphs.push(s)}))}static Parse(e,t){const i=t.valueParseFunction??lb,s=new xb({scene:t.scene});return e._flowGraphs?.forEach((e=>{vb.Parse(e,{coordinator:s,valueParseFunction:i,pathConverter:t.pathConverter})})),s}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new g,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}xb.SceneCoordinators=new Map;class Tb extends ub{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class Sb extends Tb{constructor(e){super(e),this.message=this.registerDataInput("message",YE)}_execute(e){const t=this.message.getValue(e);J.Log(t),this.out._activateSignal(e)}getClassName(){return Sb.ClassName}}Sb.ClassName="FGConsoleLogBlock",u(Sb.ClassName,Sb);class Eb extends Tb{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,YE)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return Eb.ClassName}}Eb.ClassName="FGSetVariableBlock",u(Eb.ClassName,Eb);const bb=new RegExp(/\{(\w+)\}/g);class Cb{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=bb.exec(e);for(;i;){const[,s]=i;this.templatedInputs.push(t.registerDataInput(s,sb)),i=bb.exec(e)}}getAccessor(e,t){let i=this.path;for(const e of this.templatedInputs){const s=e.getValue(t).value;i=i.replace(`{${e.name}}`,s.toString())}return e.convert(i)}}class yb extends Tb{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",YE),this.templateComponent=new Cb(e.path,this)}_execute(e){const t=this.a.getValue(e),i=this.templateComponent.getAccessor(this.config.pathConverter,e);i.info.set(t,i.object),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path}getClassName(){return yb.ClassName}}yb.ClassName="FGSetPropertyBlock",u("FGSetPropertyBlock",yb);class Ab extends Tb{constructor(e){super(e),this.config=e;for(let e=0;et.getValue(e)));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return Ab.ClassName}}Ab.ClassName="FGSendCustomEventBlock",u("FGSendCustomEventBlock",Ab),u("FGBranchBlock",class extends ub{constructor(e){super(e),this.condition=this.registerDataInput("condition",KE),this.onTrue=this._registerSignalOutput("onTrue"),this.onFalse=this._registerSignalOutput("onFalse")}_execute(e){this.condition.getValue(e)?this.onTrue._activateSignal(e):this.onFalse._activateSignal(e)}getClassName(){return"FGBranchBlock"}});class Rb extends Tb{constructor(e={startIndex:new HE(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",sb),this.value=this.registerDataOutput("value",sb)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const t=this.value.getValue(e);t.values)this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",r);else{const t=s-(r-i);this.timeRemaining.setValue(t,e)}}getClassName(){return"FGThrottleBlock"}});class Ib extends db{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",$E)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(void 0!==t&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],s=e.configuration.scene,r=new t_({timeout:t,contextObservable:s.onBeforeRenderObservable,onEnded:()=>this._onEnded(r,e)});r.start(),i.push(r),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],s=i.indexOf(e);-1!==s?i.splice(s,1):Ii.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningTimers")||[];for(const e of t)e.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return Ib.ClassName}}Ib.ClassName="FGTimerBlock",u("FGTimerBlock",Ib),u("FGMultiGateBlock",class extends ub{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",$E),this.config.startIndex=void 0!==this.config.startIndex?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let e=0;e=this.config.numberOutputFlows&&this.config.loop)r=0;else if(r>=this.config.numberOutputFlows&&!this.config.loop)return;if(s=s.filter((e=>e!==r)),0===s.length)for(let e=0;e=0&&(i[e+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every((e=>e))){this.out._activateSignal(e);for(let e=0;e=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}),u("FGFlipFlopBlock",class extends ub{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",KE)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}});class Mb extends ub{constructor(e){super(e),this.config=e,this.outFlows=[];for(let e=0;ethis._onAnimationEnd(t,e)));this.runningAnimatable.setValue(t,e),n.push(t)}e._setExecutionVariable(this,"runningAnimatables",n)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){const i=t._getExecutionVariable(this,"runningAnimatables")??[],s=i.indexOf(e);-1!==s&&i.splice(s,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningAnimatables")??[];for(const e of t)e.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return Db.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}Db.ClassName="FGPlayAnimationBlock",u(Db.ClassName,Db),u("FGStopAnimationBlock",class extends Tb{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",YE)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}),u("FGPauseAnimationBlock",class extends Tb{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",YE)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}),u("FGConditionalDataBlock",class extends hb{constructor(e){super(e),this.condition=this.registerDataInput("condition",KE),this.trueValue=this.registerDataInput("trueValue",YE),this.falseValue=this.registerDataInput("falseValue",YE),this.output=this.registerDataOutput("output",YE)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}});class Ob extends hb{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,YE)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return Ob.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}Ob.ClassName="FGGetVariableBlock",u(Ob.ClassName,Ob),u("FGCoordinateTransformBlock",class extends hb{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",YE),this.destinationSystem=this.registerDataInput("destinationSystem",YE),this.inputCoordinates=this.registerDataInput("inputCoordinates",QE),this.outputCoordinates=this.registerDataOutput("outputCoordinates",QE)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),s=this.inputCoordinates.getValue(e),r=t.getWorldMatrix(),n=i.getWorldMatrix(),o=U.Matrix[0].copyFrom(n);o.invert();const a=U.Matrix[1];o.multiplyToRef(r,a);const l=this.outputCoordinates.getValue(e);w.TransformCoordinatesToRef(s,a,l)}getClassName(){return"FGCoordinateTransformBlock"}}),u("FGConstantBlock",class extends hb{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",function(e){switch(typeof e){case"string":return jE;case"number":return $E;case"boolean":return KE;case"object":return e instanceof N?qE:e instanceof w?QE:e instanceof F?ZE:e instanceof Y?eb:e instanceof j?tb:e instanceof L?ib:e instanceof HE?sb:YE;default:return YE}}(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=ab){super.serialize(e),t("value",this.config.value,e.config)}});class Nb extends hb{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",YE),this.templateComponent=new Cb(e.path,this)}_updateOutputs(e){const t=this.templateComponent.getAccessor(this.config.pathConverter,e),i=t.info.get(t.object);this.value.setValue(i,e)}getClassName(){return Nb.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}Nb.ClassName="FGGetPropertyBlock",u(Nb.ClassName,Nb);const wb="cachedOperationValue",Fb="cachedExecutionId";class Lb extends hb{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,Fb),i=e._getExecutionVariable(this,wb);if(void 0!==i&&t===e.executionId)this.value.setValue(i,e);else{const t=this._doOperation(e);e._setExecutionVariable(this,wb,t),e._setExecutionVariable(this,Fb,e.executionId),this.value.setValue(t,e)}}}class Bb extends Lb{constructor(e,t,i,s,r,n){super(i,n),this._operation=s,this._className=r,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e))}getClassName(){return this._className}}class Vb extends Lb{constructor(e,t,i,s,r){super(t,r),this._operation=i,this._className=s,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}const Ub="FGLogic",kb="AndBlock",Gb="OrBlock",zb="NotBlock";u(`${Ub}${kb}`,class extends Bb{constructor(e){super(KE,KE,KE,((e,t)=>e&&t),`${Ub}${kb}`,e)}}),u(`${Ub}${Gb}`,class extends Bb{constructor(e){super(KE,KE,KE,((e,t)=>e||t),`${Ub}${Gb}`,e)}}),u(`${Ub}${zb}`,class extends Vb{constructor(e){super(KE,KE,(e=>!e),`${Ub}${zb}`,e)}});class Wb extends Lb{constructor(e,t,i,s){super(e,s),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class Hb extends Lb{constructor(e,t,i,s,r,n,o){super(s,o),this._operation=r,this._className=n,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t),this.c=this.registerDataInput("c",i)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e),this.c.getValue(e))}getClassName(){return this._className}}function Xb(e){return e.getClassName?e.getClassName():""}function Yb(e,t){return"Vector2"===e&&"Vector2"===t||"Vector3"===e&&"Vector3"===t||"Vector4"===e&&"Vector4"===t}function jb(e,t){return"Matrix"===e&&"Matrix"===t}function $b(e,t){return"FlowGraphInteger"===e&&"FlowGraphInteger"===t}class Kb extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicAdd(e,t)),Kb.ClassName,e)}_polymorphicAdd(e,t){const i=Xb(e),s=Xb(t);return Yb(i,s)||jb(i,s)||$b(i,s)?e.add(t):e+t}}Kb.ClassName="FGAddBlock",u(Kb.ClassName,Kb);class qb extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicAdd(e,t)),qb.ClassName,e)}_polymorphicAdd(e,t){const i=Xb(e),s=Xb(t);return Yb(i,s)||$b(i,s)?e.subtract(t):jb(i,s)?e.add(t.scale(-1)):e-t}}qb.ClassName="FGSubBlock",u(qb.ClassName,qb);class Qb extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicMultiply(e,t)),Qb.ClassName,e)}_polymorphicMultiply(e,t){const i=Xb(e),s=Xb(t);return Yb(i,s)||$b(i,s)?e.multiply(t):jb(i,s)?B.FromValues(e.m[0]*t.m[0],e.m[4]*t.m[4],e.m[8]*t.m[8],e.m[12]*t.m[12],e.m[1]*t.m[1],e.m[5]*t.m[5],e.m[9]*t.m[9],e.m[13]*t.m[13],e.m[2]*t.m[2],e.m[6]*t.m[6],e.m[10]*t.m[10],e.m[14]*t.m[14],e.m[3]*t.m[3],e.m[7]*t.m[7],e.m[11]*t.m[11],e.m[15]*t.m[15]):e*t}}Qb.ClassName="FGMultiplyBlock",u(Qb.ClassName,Qb);class Zb extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicDivide(e,t)),Zb.ClassName,e)}_polymorphicDivide(e,t){const i=Xb(e),s=Xb(t);return Yb(i,s)||$b(i,s)?e.divide(t):jb(i,s)?B.FromValues(e.m[0]/t.m[0],e.m[4]/t.m[4],e.m[8]/t.m[8],e.m[12]/t.m[12],e.m[1]/t.m[1],e.m[5]/t.m[5],e.m[9]/t.m[9],e.m[13]/t.m[13],e.m[2]/t.m[2],e.m[6]/t.m[6],e.m[10]/t.m[10],e.m[14]/t.m[14],e.m[3]/t.m[3],e.m[7]/t.m[7],e.m[11]/t.m[11],e.m[15]/t.m[15]):e/t}}Zb.ClassName="FGDivideBlock",u(Zb.ClassName,Zb);class Jb extends Wb{constructor(e){super($E,(()=>Math.random()),Jb.ClassName,e)}}Jb.ClassName="FGRandomBlock",u(Jb.ClassName,Jb);class eC extends Bb{constructor(e){super(YE,YE,$E,((e,t)=>this._polymorphicDot(e,t)),eC.ClassName,e)}_polymorphicDot(e,t){switch(Xb(e)){case"Vector2":return N.Dot(e,t);case"Vector3":return w.Dot(e,t);case"Vector4":return F.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}eC.ClassName="FGDotBlock",u(eC.ClassName,eC);class tC extends Wb{constructor(e){super($E,(()=>Math.E),tC.ClassName,e)}}tC.ClassName="FGEBlock",u(tC.ClassName,tC);class iC extends Wb{constructor(e){super($E,(()=>Math.PI),iC.ClassName,e)}}iC.ClassName="FGPIBlock",u(iC.ClassName,iC);class sC extends Wb{constructor(e){super($E,(()=>Number.POSITIVE_INFINITY),sC.ClassName,e)}}sC.ClassName="FGInfBlock",u(sC.ClassName,sC);class rC extends Wb{constructor(e){super($E,(()=>Number.NaN),rC.ClassName,e)}}function nC(e,t){switch(Xb(e)){case"FlowGraphInteger":return new HE(t(e.value));case"Vector2":return new N(t(e.x),t(e.y));case"Vector3":return new w(t(e.x),t(e.y),t(e.z));case"Vector4":return new F(t(e.x),t(e.y),t(e.z),t(e.w));case"Matrix":return B.FromValues(t(e.m[0]),t(e.m[4]),t(e.m[8]),t(e.m[12]),t(e.m[1]),t(e.m[5]),t(e.m[9]),t(e.m[13]),t(e.m[2]),t(e.m[6]),t(e.m[10]),t(e.m[14]),t(e.m[3]),t(e.m[7]),t(e.m[11]),t(e.m[15]));default:return t(e)}}rC.ClassName="FGNaNBlock",u(rC.ClassName,rC);class oC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicAbs(e)),oC.ClassName,e)}_polymorphicAbs(e){return nC(e,Math.abs)}}oC.ClassName="FGAbsBlock",u(oC.ClassName,oC);class aC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicSign(e)),aC.ClassName,e)}_polymorphicSign(e){return nC(e,Math.sign)}}aC.ClassName="FGSignBlock",u(aC.ClassName,aC);class lC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicTrunc(e)),lC.ClassName,e)}_polymorphicTrunc(e){return nC(e,Math.trunc)}}lC.ClassName="FGTruncBlock",u(lC.ClassName,lC);class hC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicFloor(e)),hC.ClassName,e)}_polymorphicFloor(e){return nC(e,Math.floor)}}hC.ClassName="FGFloorBlock",u(hC.ClassName,hC);class cC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicCeiling(e)),cC.ClassName,e)}_polymorphicCeiling(e){return nC(e,Math.ceil)}}cC.ClassName="FGCeilBlock",u(cC.ClassName,cC);class uC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicFract(e)),uC.ClassName,e)}_polymorphicFract(e){return nC(e,(e=>e-Math.floor(e)))}}uC.ClassName="FGFractBlock",u(uC.ClassName,uC);class dC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicNeg(e)),dC.ClassName,e)}_polymorphicNeg(e){return nC(e,(e=>-e))}}function pC(e,t,i){switch(Xb(e)){case"FlowGraphInteger":return new HE(i(e.value,t.value));case"Vector2":return new N(i(e.x,t.x),i(e.y,t.y));case"Vector3":return new w(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z));case"Vector4":return new F(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z),i(e.w,t.w));case"Matrix":return B.FromValues(i(e.m[0],t.m[0]),i(e.m[4],t.m[4]),i(e.m[8],t.m[8]),i(e.m[12],t.m[12]),i(e.m[1],t.m[1]),i(e.m[5],t.m[5]),i(e.m[9],t.m[9]),i(e.m[13],t.m[13]),i(e.m[2],t.m[2]),i(e.m[6],t.m[6]),i(e.m[10],t.m[10]),i(e.m[14],t.m[14]),i(e.m[3],t.m[3]),i(e.m[7],t.m[7]),i(e.m[11],t.m[11]),i(e.m[15],t.m[15]));default:return i(e,t)}}dC.ClassName="FGNegBlock",u(dC.ClassName,dC);class fC extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicRemainder(e,t)),fC.ClassName,e)}_polymorphicRemainder(e,t){return pC(e,t,((e,t)=>e%t))}}fC.ClassName="FGRemainderBlock",u(fC.ClassName,fC);class _C extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicMin(e,t)),_C.ClassName,e)}_polymorphicMin(e,t){return pC(e,t,Math.min)}}_C.ClassName="FGMinBlock",u(_C.ClassName,_C);class mC extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicMax(e,t)),mC.ClassName,e)}_polymorphicMax(e,t){return pC(e,t,Math.max)}}function gC(e,t,i){return Math.min(Math.max(e,Math.min(t,i)),Math.max(t,i))}function vC(e,t,i,s){switch(Xb(e)){case"FlowGraphInteger":return new HE(s(e.value,t.value,i.value));case"Vector2":return new N(s(e.x,t.x,i.x),s(e.y,t.y,i.y));case"Vector3":return new w(s(e.x,t.x,i.x),s(e.y,t.y,i.y),s(e.z,t.z,i.z));case"Vector4":return new F(s(e.x,t.x,i.x),s(e.y,t.y,i.y),s(e.z,t.z,i.z),s(e.w,t.w,i.w));case"Matrix":return B.FromValues(s(e.m[0],t.m[0],i.m[0]),s(e.m[4],t.m[4],i.m[4]),s(e.m[8],t.m[8],i.m[8]),s(e.m[12],t.m[12],i.m[12]),s(e.m[1],t.m[1],i.m[1]),s(e.m[5],t.m[5],i.m[5]),s(e.m[9],t.m[9],i.m[9]),s(e.m[13],t.m[13],i.m[13]),s(e.m[2],t.m[2],i.m[2]),s(e.m[6],t.m[6],i.m[6]),s(e.m[10],t.m[10],i.m[10]),s(e.m[14],t.m[14],i.m[14]),s(e.m[3],t.m[3],i.m[3]),s(e.m[7],t.m[7],i.m[7]),s(e.m[11],t.m[11],i.m[11]),s(e.m[15],t.m[15],i.m[15]));default:return s(e,t,i)}}mC.ClassName="FGMaxBlock",u(mC.ClassName,mC);class xC extends Hb{constructor(e){super(YE,YE,YE,YE,((e,t,i)=>this._polymorphicClamp(e,t,i)),xC.ClassName,e)}_polymorphicClamp(e,t,i){return vC(e,t,i,gC)}}function TC(e){return Math.min(Math.max(e,0),1)}xC.ClassName="FGClampBlock",u(xC.ClassName,xC);class SC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicSaturate(e)),SC.ClassName,e)}_polymorphicSaturate(e){return nC(e,TC)}}SC.ClassName="FGSaturateBlock",u(SC.ClassName,SC);class EC extends Hb{constructor(e){super(YE,YE,YE,YE,((e,t,i)=>this._polymorphicInterpolate(e,t,i)),EC.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return vC(e,t,i,this._interpolate)}}EC.ClassName="FGInterpolateBlock",u(EC.ClassName,EC);class bC extends Bb{constructor(e){super(YE,YE,KE,((e,t)=>this._polymorphicEq(e,t)),bC.ClassName,e)}_polymorphicEq(e,t){const i=Xb(e),s=Xb(t);return Yb(i,s)||jb(i,s)||$b(i,s)?e.equals(t):e===t}}function CC(e,t,i){const s=Xb(e);if(s===Xb(t)){if(""===s)return i(e,t);if("FlowGraphInteger"===s)return i(e.value,t.value);throw new Error(`Cannot compare ${e} and ${t}`)}throw new Error(`${e} and ${t} are of different types.`)}bC.ClassName="FGEqBlock",u(bC.ClassName,bC);class yC extends Bb{constructor(e){super(YE,YE,KE,((e,t)=>this._polymorphicLessThan(e,t)),yC.ClassName,e)}_polymorphicLessThan(e,t){return CC(e,t,((e,t)=>ethis._polymorphicLessThanOrEqual(e,t)),AC.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return CC(e,t,((e,t)=>e<=t))}}AC.ClassName="FGLessThanOrEqualBlock";class RC extends Bb{constructor(e){super(YE,YE,KE,((e,t)=>this._polymorphicGreaterThan(e,t)),RC.ClassName,e)}_polymorphicGreaterThan(e,t){return CC(e,t,((e,t)=>e>t))}}RC.ClassName="FGGreaterThanBlock",u(RC.ClassName,RC);class IC extends Bb{constructor(e){super(YE,YE,KE,((e,t)=>this._polymorphicGreaterThanOrEqual(e,t)),IC.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return CC(e,t,((e,t)=>e>=t))}}IC.ClassName="FGGreaterThanOrEqualBlock",u(IC.ClassName,IC);class PC extends Vb{constructor(e){super(YE,KE,(e=>this._polymorphicIsNan(e)),PC.ClassName,e)}_polymorphicIsNan(e){const t=Xb(e);if(""===t)return isNaN(e);if("FlowGraphInteger"===t)return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}PC.ClassName="FGIsNanBlock",u(PC.ClassName,PC);class MC extends Vb{constructor(e){super(YE,KE,(e=>this._polymorphicIsInf(e)),MC.ClassName,e)}_polymorphicIsInf(e){const t=Xb(e);if(""===t)return!isFinite(e);if("FlowGraphInteger"===t)return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}MC.ClassName="FGIsInfBlock";class DC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicDegToRad(e)),DC.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return nC(e,this._degToRad)}}DC.ClassName="FGDegToRadBlock",u(DC.ClassName,DC);class OC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicRadToDeg(e)),OC.ClassName,e)}_radToDeg(e){return 180*e/Math.PI}_polymorphicRadToDeg(e){return nC(e,this._radToDeg)}}OC.ClassName="FGRadToDegBlock",u(OC.ClassName,OC);class NC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicSin(e)),NC.ClassName,e)}_polymorphicSin(e){return nC(e,Math.sin)}}NC.ClassName="FGSinBlock",u(NC.ClassName,NC);class wC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicCos(e)),wC.ClassName,e)}_polymorphicCos(e){return nC(e,Math.cos)}}wC.ClassName="FGCosBlock",u(wC.ClassName,wC);class FC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicTan(e)),FC.ClassName,e)}_polymorphicTan(e){return nC(e,Math.tan)}}FC.ClassName="FGTanBlock",u(FC.ClassName,FC);class LC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicAsin(e)),LC.ClassName,e)}_polymorphicAsin(e){return nC(e,Math.asin)}}LC.ClassName="FGAsinBlock",u(LC.ClassName,LC);class BC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicAcos(e)),BC.ClassName,e)}_polymorphicAcos(e){return nC(e,Math.acos)}}BC.ClassName="FGAcosBlock",u(BC.ClassName,BC);class VC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicAtan(e)),VC.ClassName,e)}_polymorphicAtan(e){return nC(e,Math.atan)}}VC.ClassName="FGAtanBlock",u(VC.ClassName,VC);class UC extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicAtan2(e,t)),UC.ClassName,e)}_polymorphicAtan2(e,t){return pC(e,t,Math.atan2)}}UC.ClassName="FGAtan2Block",u(UC.ClassName,UC);class kC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicSinh(e)),kC.ClassName,e)}_polymorphicSinh(e){return nC(e,Math.sinh)}}kC.ClassName="FGSinhBlock",u(kC.ClassName,kC);class GC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicCosh(e)),GC.ClassName,e)}_polymorphicCosh(e){return nC(e,Math.cosh)}}GC.ClassName="FGCoshBlock",u(GC.ClassName,GC);class zC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicTanh(e)),zC.ClassName,e)}_polymorphicTanh(e){return nC(e,Math.tanh)}}zC.ClassName="FGTanhBlock",u(zC.ClassName,zC);class WC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicAsinh(e)),WC.ClassName,e)}_polymorphicAsinh(e){return nC(e,Math.asinh)}}WC.ClassName="FGAsinhBlock",u(WC.ClassName,WC);class HC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicAcosh(e)),HC.ClassName,e)}_polymorphicAcosh(e){return nC(e,Math.acosh)}}HC.ClassName="FGAcoshBlock",u(HC.ClassName,HC);class XC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicAtanh(e)),XC.ClassName,e)}_polymorphicAtanh(e){return nC(e,Math.atanh)}}XC.ClassName="FGAtanhBlock",u(XC.ClassName,XC);class YC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicExp(e)),YC.ClassName,e)}_polymorphicExp(e){return nC(e,Math.exp)}}YC.ClassName="FGExpBlock",u(YC.ClassName,YC);class jC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicLog(e)),jC.ClassName,e)}_polymorphicLog(e){return nC(e,Math.log)}}jC.ClassName="FGLogBlock",u(jC.ClassName,jC);class $C extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicLog2(e)),$C.ClassName,e)}_polymorphicLog2(e){return nC(e,Math.log2)}}$C.ClassName="FGLog2Block",u($C.ClassName,$C);class KC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicLog10(e)),KC.ClassName,e)}_polymorphicLog10(e){return nC(e,Math.log10)}}KC.ClassName="FGLog10Block",u(KC.ClassName,KC);class qC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicSqrt(e)),qC.ClassName,e)}_polymorphicSqrt(e){return nC(e,Math.sqrt)}}qC.ClassName="FGSqrtBlock",u(qC.ClassName,qC);class QC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicCubeRoot(e)),QC.ClassName,e)}_polymorphicCubeRoot(e){return nC(e,Math.cbrt)}}QC.ClassName="FGCubeRootBlock",u(QC.ClassName,QC);class ZC extends Bb{constructor(e){super(YE,$E,$E,((e,t)=>this._polymorphicPow(e,t)),ZC.ClassName,e)}_polymorphicPow(e,t){return pC(e,t,Math.pow)}}ZC.ClassName="FGPowBlock",u(ZC.ClassName,ZC);class JC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicLength(e)),JC.ClassName,e)}_polymorphicLength(e){switch(Xb(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}JC.ClassName="FGLengthBlock",u(JC.ClassName,JC);class ey extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicNormalize(e)),ey.ClassName,e)}_polymorphicNormalize(e){switch(Xb(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}ey.ClassName="FGNormalizeBlock",u(ey.ClassName,ey);class ty extends Bb{constructor(e){super(QE,QE,QE,((e,t)=>w.Cross(e,t)),ty.ClassName,e)}}ty.ClassName="FGCrossBlock",u(ty.ClassName,ty);class iy extends Bb{constructor(e){super(qE,$E,qE,((e,t)=>N.Transform(e,B.RotationZ(t))),iy.ClassName,e)}}iy.ClassName="FGRotate2DBlock",u(iy.ClassName,iy);class sy extends Hb{constructor(e){super(QE,QE,$E,QE,((e,t,i)=>w.TransformCoordinates(e,B.RotationAxis(t,i))),sy.ClassName,e)}}sy.ClassName="FGRotate3DBlock",u(sy.ClassName,sy);class ry extends Vb{constructor(e){super(JE,JE,(e=>B.Transpose(e)),ry.ClassName,e)}}ry.ClassName="FGTransposeBlock",u(ry.ClassName,ry);class ny extends Vb{constructor(e){super(JE,$E,(e=>e.determinant()),ny.ClassName,e)}}ny.ClassName="FGDeterminantBlock",u(ny.ClassName,ny);class oy extends Vb{constructor(e){super(JE,JE,(e=>B.Invert(e)),oy.ClassName,e)}}oy.ClassName="FGInvertMatrixBlock",u(oy.ClassName,oy);class ay extends Bb{constructor(e){super(JE,JE,JE,((e,t)=>t.multiply(e)),ay.ClassName,e)}}ay.ClassName="FGMatMulBlock",u(ay.ClassName,ay);class ly extends Vb{constructor(e){super(sb,sb,(e=>new HE(~e.value)),ly.ClassName,e)}}ly.ClassName="FGBitwiseNotBlock",u(ly.ClassName,ly);class hy extends Bb{constructor(e){super(sb,sb,sb,((e,t)=>new HE(e.value&t.value)),hy.ClassName,e)}}hy.ClassName="FGBitwiseAndBlock",u(hy.ClassName,hy);class cy extends Bb{constructor(e){super(sb,sb,sb,((e,t)=>new HE(e.value|t.value)),cy.ClassName,e)}}cy.ClassName="FGBitwiseOrBlock",u(cy.ClassName,cy);class uy extends Bb{constructor(e){super(sb,sb,sb,((e,t)=>new HE(e.value^t.value)),uy.ClassName,e)}}uy.ClassName="FGBitwiseXorBlock",u(uy.ClassName,uy);class dy extends Bb{constructor(e){super(sb,sb,sb,((e,t)=>new HE(e.value<new HE(e.value>>t.value)),py.ClassName,e)}}py.ClassName="FGBitwiseRightShiftBlock",u(py.ClassName,py);class fy extends Vb{constructor(e){super(sb,sb,(e=>new HE(Math.clz32(e.value))),fy.ClassName,e)}}fy.ClassName="FGCountLeadingZerosBlock",u(fy.ClassName,fy);class _y extends Vb{constructor(e){super(sb,sb,(e=>new HE(e.value?31-Math.clz32(e.value&-e.value):32)),_y.ClassName,e)}}_y.ClassName="FGCountTrailingZerosBlock",u(_y.ClassName,_y);class my extends Vb{constructor(e){super(sb,sb,(e=>new HE(function(e){let t=0;for(;e;)t+=1&e,e>>=1;return t}(e.value))),my.ClassName,e)}}my.ClassName="FGCountOneBitsBlock",u(my.ClassName,my);class gy extends pb{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const t=e.configuration.scene.onReadyObservable.add((()=>{this._execute(e)}));e._setExecutionVariable(this,"sceneReadyObserver",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return gy.ClassName}}gy.ClassName="FGSceneReadyEventBlock",u("FGSceneReadyEventBlock",gy);class vy extends pb{constructor(e){super(e),this.config=e;for(let e=0;e{for(let i=0;i{this._execute(e)}));e._setExecutionVariable(this,"sceneBeforeRender",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return xy.ClassName}}xy.ClassName="FGSceneTickEventBlock",u(xy.ClassName,xy);class Ty{constructor(e,t){this.jscad=e,this.vecHelper=t}extrudeLinear(e){const t=e.geometry.length&&e.geometry.length>0,i=t?e.geometry:[e.geometry];let s=this.jscad.extrusions.extrudeLinear({height:e.height,twistAngle:Hs.FromDegrees(e.twistAngle).radians(),twistSteps:e.twistSteps},...i);return t&&!s.length&&(s=[s]),s}extrudeRectangular(e){const t=e.geometry.length&&e.geometry.length>0,i=t?e.geometry:[e.geometry];let s=this.jscad.extrusions.extrudeRectangular({height:e.height,size:e.size},...i);return t&&!s.length&&(s=[s]),s}extrudeRectangularPoints(e){const t=e.points.map((e=>[e[0],e[1]])),i=this.vecHelper.removeConsecutiveDuplicates(t),s=this.jscad.geometries.path2.fromPoints({},i);return this.extrudeRectangular({height:e.height,size:e.size,geometry:s})}extrudeRotate(e){const t={angle:Hs.FromDegrees(e.angle).radians(),startAngle:Hs.FromDegrees(e.startAngle).radians(),overflow:"cap",segments:e.segments};return this.jscad.extrusions.extrudeRotate(t,e.polygon)}}class Sy{constructor(e,t){this.jscad=e,this.vecHelper=t}createFromPoints(e){const t=e.points.map((e=>[e[0],e[1]]));return this.removeDuplicatesAndCreateFromPoints(t,e.closed)}createPathsFromPoints(e){return e.pointsLists.map((e=>{const t=e.map((e=>[e[0],e[1]]));return t.length>1&&this.vecHelper.vectorsTheSame(t[0],t[t.length-1],1e-5)?this.removeDuplicatesAndCreateFromPoints(t,!0):this.removeDuplicatesAndCreateFromPoints(t,!1)}))}createFromPolyline(e){const t=e.polyline.points.map((e=>[e[0],e[1]]));return this.removeDuplicatesAndCreateFromPoints(t,e.closed)}createEmpty(){return this.jscad.geometries.path2.create()}close(e){return this.jscad.geometries.path2.close(e.path)}appendPoints(e){const t=e.points.map((e=>[e[0],e[1]])),i=this.vecHelper.removeConsecutiveDuplicates(t);return this.jscad.geometries.path2.appendPoints(i,e.path)}appendPolyline(e){const t=e.polyline.points.map((e=>[e[0],e[1]]));return this.appendPoints({points:t,path:e.path})}appendArc(e){const t=[e.endPoint[0],e.endPoint[1]],i=[e.radiusX,e.radiusY];return this.jscad.geometries.path2.appendArc({endpoint:t,radius:i,xaxisrotation:Hs.FromDegrees(e.xAxisRotation).radians(),clockwise:e.clockwise,large:e.large,segments:e.segments},e.path)}removeDuplicatesAndCreateFromPoints(e,t){const i=this.vecHelper.removeConsecutiveDuplicates(e);let s=this.jscad.geometries.path2.fromPoints({},i);return t&&(s=this.jscad.geometries.path2.close(s)),s}}class Ey{constructor(e,t){this.jscad=e,this.vecHelper=t}createFromPoints(e){const t=e.points.map((e=>[e[0],e[1]]));return this.removeDuplicatesAndCreateFromPoints(t)}createFromPolyline(e){const t=e.polyline.points.map((e=>[e[0],e[1]]));return this.removeDuplicatesAndCreateFromPoints(t)}createFromCurve(e){const t=e.curve.tessellate().map((e=>[e[0],e[1]]));return this.removeDuplicatesAndCreateFromPoints(t)}createFromPath(e){return this.removeDuplicatesAndCreateFromPoints(e.path.points)}circle(e){return this.jscad.primitives.circle({center:e.center,radius:e.radius,segments:e.segments})}ellipse(e){return this.jscad.primitives.ellipse({center:e.center,radius:[e.radius[0],e.radius[1]],segments:e.segments})}rectangle(e){return this.jscad.primitives.rectangle({center:[e.center[0],e.center[1]],size:[e.width,e.length]})}roundedRectangle(e){return this.jscad.primitives.roundedRectangle({center:[e.center[0],e.center[1]],size:[e.width,e.length],roundRadius:e.roundRadius,segments:e.segments})}square(e){return this.jscad.primitives.square({center:[e.center[0],e.center[1]],size:e.size})}star(e){return this.jscad.primitives.star({center:[e.center[0],e.center[1]],vertices:e.vertices,density:e.density,outerRadius:e.outerRadius,innerRadius:e.innerRadius,startAngle:Hs.FromDegrees(e.startAngle).radians()})}removeDuplicatesAndCreateFromPoints(e){const t=this.vecHelper.removeConsecutiveDuplicates(e);return this.jscad.primitives.polygon({points:t})}}class by{constructor(e){this.jscad=e}cube(e){return this.jscad.primitives.cube({center:[e.center[0],e.center[1],e.center[2]],size:e.size})}cubesOnCenterPoints(e){return e.centers.map((t=>this.cube({center:t,size:e.size})))}cuboid(e){return this.jscad.primitives.cuboid({center:[e.center[0],e.center[1],e.center[2]],size:[e.width,e.height,e.length]})}cuboidsOnCenterPoints(e){return e.centers.map((t=>this.cuboid({center:t,width:e.width,length:e.length,height:e.height})))}cylinderElliptic(e){return this.jscad.primitives.cylinderElliptic({center:[e.center[0],e.center[1],e.center[2]],height:e.height,startRadius:[e.startRadius[0],e.startRadius[1]],endRadius:[e.endRadius[0],e.endRadius[1]],segments:e.segments})}cylinderEllipticOnCenterPoints(e){return e.centers.map((t=>this.cylinderElliptic({center:t,height:e.height,startRadius:e.startRadius,endRadius:e.endRadius,segments:e.segments})))}cylinder(e){return this.jscad.primitives.cylinder({center:[e.center[0],e.center[1],e.center[2]],height:e.height,radius:e.radius,segments:e.segments})}cylindersOnCenterPoints(e){return e.centers.map((t=>this.cylinder({center:t,height:e.height,radius:e.radius,segments:e.segments})))}ellipsoid(e){return this.jscad.primitives.ellipsoid({center:[e.center[0],e.center[1],e.center[2]],radius:[e.radius[0],e.radius[1],e.radius[2]],segments:e.segments,axes:[[-1,0,0],[0,-1,0],[0,0,-1]]})}ellipsoidsOnCenterPoints(e){return e.centers.map((t=>this.ellipsoid({center:t,radius:e.radius,segments:e.segments})))}geodesicSphere(e){let t=this.jscad.primitives.geodesicSphere({radius:e.radius,frequency:e.frequency});return t=this.jscad.transforms.translate([e.center[0],e.center[1],e.center[2]],t),t}geodesicSpheresOnCenterPoints(e){return e.centers.map((t=>this.geodesicSphere({center:t,radius:e.radius,frequency:e.frequency})))}roundedCuboid(e){return this.jscad.primitives.roundedCuboid({center:[e.center[0],e.center[1],e.center[2]],size:[e.width,e.height,e.length],roundRadius:e.roundRadius,segments:e.segments})}roundedCuboidsOnCenterPoints(e){return e.centers.map((t=>this.roundedCuboid({center:t,width:e.width,height:e.height,length:e.length,roundRadius:e.roundRadius,segments:e.segments})))}roundedCylinder(e){return this.jscad.primitives.roundedCylinder({center:[e.center[0],e.center[1],e.center[2]],height:e.height,radius:e.radius,roundRadius:e.roundRadius,segments:e.segments})}roundedCylindersOnCenterPoints(e){return e.centers.map((t=>this.roundedCylinder({center:t,radius:e.radius,roundRadius:e.roundRadius,segments:e.segments,height:e.height})))}sphere(e){return this.jscad.primitives.sphere({center:[e.center[0],e.center[1],e.center[2]],radius:e.radius,segments:e.segments})}spheresOnCenterPoints(e){return e.centers.map((t=>this.sphere({center:t,radius:e.radius,segments:e.segments})))}torus(e){return this.jscad.primitives.torus({center:[e.center[0],e.center[1],e.center[2]],innerRadius:e.innerRadius,outerRadius:e.outerRadius,innerSegments:e.innerSegments,outerSegments:e.outerSegments,innerRotation:Hs.FromDegrees(e.innerRotation).radians(),outerRotation:Hs.FromDegrees(e.outerRotation).radians(),startAngle:Hs.FromDegrees(e.startAngle).radians()})}fromPolygonPoints(e){const t=e.polygonPoints.map((e=>e.reverse()));return this.jscad.geometries.geom3.fromPoints(t)}}class Cy{constructor(e){this.jscad=e}cylindricalText(e){const t=this.createVectorText(e);return this.adjustTextToBeOnCenter(t),t.map((t=>{const i=t.map((t=>this.jscad.primitives.cylinder({center:[t[0],t[1],0],height:e.extrusionHeight,radius:e.extrusionSize,segments:e.segments})));return this.jscad.hulls.hullChain(...i)}))}sphericalText(e){const t=this.createVectorText(e);return this.adjustTextToBeOnCenter(t),t.map((t=>{const i=t.map((t=>this.jscad.primitives.sphere({center:[t[0],t[1],0],radius:e.radius,segments:e.segments})));return this.jscad.hulls.hullChain(...i)}))}adjustTextToBeOnCenter(e){let t=0;e.forEach((e=>{e.forEach((e=>{e[0]>t&&(t=e[0])}))}));const i=t/2;e.forEach((e=>{e.forEach((e=>{let t=e[0];t-=i,e[0]=t}))}))}createVectorText(e){return this.jscad.text.vectorText({input:e.text,xOffset:e.xOffset,yOffset:e.yOffset,height:e.height,lineSpacing:e.lineSpacing,letterSpacing:e.letterSpacing,align:e.align,extrudeOffset:e.extrudeOffset})}}class yy{constructor(e){this.jscad=e}hullChain(e){return this.jscad.hulls.hullChain(...e.meshes)}hull(e){return this.jscad.hulls.hull(...e.meshes)}}class Ay{constructor(e){this.jscad=e}colorize(e){const t=e.geometry,i=e.color;return this.jscad.colors.colorize(this.jscad.colors.hexToRgb(i),t)}}class Ry{constructor(e){this.getArrayDepth=e=>Array.isArray(e)?1+Math.max(...e.map(this.getArrayDepth)):0;const t=new r;this.booleans=new h(e),this.expansions=new l(e),this.extrusions=new Ty(e,t),this.hulls=new yy(e),this.path=new Sy(e,t),this.polygon=new Ey(e,t),this.shapes=new by(e),this.text=new Cy(e),this.colors=new Ay(e),this.jscad=e}shapesToMeshes(e){return e.meshes.map((t=>this.shapeToMesh(Object.assign(Object.assign({},e),{mesh:t}))))}shapeToMesh(e){let t=[];if(e.mesh.toPolygons)t=e.mesh.toPolygons();else if(e.mesh.polygons)t=e.mesh.polygons;else if(e.mesh.sides||e.mesh.vertices){const i=this.extrusions.extrudeLinear({height:.001,twistAngle:0,twistSteps:1,geometry:e.mesh});i.toPolygons?t=i.toPolygons():i.polygons&&(t=i.polygons)}const i=[],s=[];let r=0;for(const e of t)if(3===e.vertices.length)e.vertices.forEach((e=>{i.push(e[0],e[1],e[2]),s.push(r),r++}));else{const t=[],n=e.vertices,o=n[0];for(let e=n.length-3;e>=0;e--)t.push([o,n[e+1],n[e+2]]);t.forEach(((e,t)=>{e.forEach((e=>{i.push(e[0],e[1],e[2]),s.push(r),r++}))}))}return{positions:i,normals:[],indices:s,transforms:e.mesh.transforms}}transformSolids(e){return e.meshes.map((t=>this.transformSolid({mesh:t,transformation:e.transformation})))}transformSolid(e){const t=e.transformation;let i=this.jscad.geometries.geom3.clone(e.mesh);return 2===this.getArrayDepth(t)?t.forEach((e=>{i=this.jscad.transforms.transform(e,i)})):3===this.getArrayDepth(t)?t.forEach((e=>{e.forEach((e=>{i=this.jscad.transforms.transform(e,i)}))})):i=this.jscad.transforms.transform(t,i),i}downloadSolidSTL(e){const t=this.jscad.STLSERIALIZER.serialize({binary:!0},e.mesh);return{blob:new Blob(t,{type:"application/sla"})}}downloadGeometryDxf(e){const t=this.jscad.DXFSERIALIZER.serialize({},e.geometry);return{blob:new Blob(t)}}downloadSolidsSTL(e){const t=this.jscad.STLSERIALIZER.serialize({binary:!0},...e.meshes);return{blob:new Blob(t,{type:"application/sla"})}}}let Iy,Py;Promise.resolve().then(i.bind(i,263)).then((function(e){var t;t=e.default(),Py=new s(t),Iy=new Ry(t),postMessage("jscad-initialised"),postMessage("jscad-initialised")})),addEventListener("message",(function(e){((e,t)=>{let i;t("busy");try{if("startedTheRun"!==e.action.functionName&&"cleanAllCache"!==e.action.functionName){const t=e.action.functionName.split(".");i=2===t.length?Py.cacheOp(e.action,(()=>Iy[t[0]][t[1]](e.action.inputs))):Py.cacheOp(e.action,(()=>Iy[e.action.functionName](e.action.inputs)))}"startedTheRun"===e.action.functionName&&(Py&&Object.keys(Py.usedHashes).length>1e4&&Py.cleanAllCache(),i={}),"cleanAllCache"===e.action.functionName&&(Py.cleanAllCache(),i={}),t({uid:e.uid,result:i})}catch(i){let s,r;e&&e.action&&e.action.inputs&&(s=`Input values were: {${Object.keys(e.action.inputs).map((t=>`${t}: ${e.action.inputs[t]}`)).join(",")}}. `),e&&e.action&&e.action.functionName&&(r=`- ${e.action.functionName}`),t({uid:e.uid,result:void 0,error:`JSCAD computation failed when executing function ${r}. ${s}Original message: ${i}`})}})(e.data,postMessage)}))},725:()=>{},439:()=>{},699:()=>{}},t={};function i(s){var r=t[s];if(void 0!==r)return r.exports;var n=t[s]={exports:{}};return e[s](n,n.exports,i),n.exports}i.d=(e,t)=>{for(var s in t)i.o(t,s)&&!i.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i(263),i(568)})(); \ No newline at end of file +(()=>{var e={263:(e,t,i)=>{"use strict";let s;function r(){return s}i.r(t),i.d(t,{default:()=>r}),function e(t,i,s){function r(o,a){if(!i[o]){if(!t[o]){if(n)return n(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var h=i[o]={exports:{}};t[o][0].call(h.exports,(function(e){return r(t[o][1][e]||e)}),h,h.exports,e,t,i,s)}return i[o].exports}for(var n=void 0,o=0;oe.reduce(((e,t)=>Array.isArray(t)?e.concat(s(t)):e.concat(t)),[]);t.exports=s},{}],3:[function(e,t,i){t.exports=(e,t)=>e-t},{}],4:[function(e,t,i){t.exports=e=>{if(Array.isArray(e)&&0!==e.length)return e[0]}},{}],5:[function(e,t,i){t.exports={flatten:e("./flatten"),fnNumberSort:e("./fnNumberSort"),head:e("./head"),insertSorted:e("./insertSorted"),nth:e("./nth"),padToLength:e("./padToLength"),toArray:e("./toArray")}},{"./flatten":2,"./fnNumberSort":3,"./head":4,"./insertSorted":6,"./nth":7,"./padToLength":8,"./toArray":9}],6:[function(e,t,i){t.exports=(e,t,i)=>{let s=0,r=e.length;for(;r>s;){const n=Math.floor((s+r)/2);i(t,e[n])>0?s=n+1:r=n}return e.splice(s,0,t),e}},{}],7:[function(e,t,i){t.exports=(e,t)=>{if(Array.isArray(e)&&!(e.length{for(e=e.slice();e.lengthArray.isArray(e)?e:null==e?[]:[e]},{}],10:[function(e,t,i){t.exports={dxfHeaders:function(){return" 0\nSECTION\n 2\nHEADER\n 9\n$ACADVER\n 1\nAC1027\n 9\n$ACADMAINTVER\n 70\n8\n 9\n$DWGCODEPAGE\n 3\nANSI_1252\n 9\n$LASTSAVEDBY\n 1\nunknown\n 9\n$REQUIREDVERSIONS\n160\n0\n 9\n$INSBASE\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$EXTMIN\n 10\n1e+20\n 20\n1e+20\n 30\n1e+20\n 9\n$EXTMAX\n 10\n-1e+20\n 20\n-1e+20\n 30\n-1e+20\n 9\n$LIMMIN\n 10\n0.0\n 20\n0.0\n 9\n$LIMMAX\n 10\n12.0\n 20\n9.0\n 9\n$ORTHOMODE\n 70\n0\n 9\n$REGENMODE\n 70\n1\n 9\n$FILLMODE\n 70\n1\n 9\n$QTEXTMODE\n 70\n0\n 9\n$MIRRTEXT\n 70\n0\n 9\n$LTSCALE\n 40\n1.0\n 9\n$ATTMODE\n 70\n1\n 9\n$TEXTSIZE\n 40\n0.2\n 9\n$TRACEWID\n 40\n0.05\n 9\n$TEXTSTYLE\n 7\nNotes\n 9\n$CLAYER\n 8\n0\n 9\n$CELTYPE\n 6\nByLayer\n 9\n$CECOLOR\n 62\n256\n 9\n$CELTSCALE\n 40\n1.0\n 9\n$DISPSILH\n 70\n0\n 9\n$DIMSCALE\n 40\n1.0\n 9\n$DIMASZ\n 40\n3.0\n 9\n$DIMEXO\n 40\n1.5\n 9\n$DIMDLI\n 40\n6.0\n 9\n$DIMRND\n 40\n0.0\n 9\n$DIMDLE\n 40\n0.0\n 9\n$DIMEXE\n 40\n3.0\n 9\n$DIMTP\n 40\n0.0\n 9\n$DIMTM\n 40\n0.0\n 9\n$DIMTXT\n 40\n3.0\n 9\n$DIMCEN\n 40\n3.0\n 9\n$DIMTSZ\n 40\n0.0\n 9\n$DIMTOL\n 70\n0\n 9\n$DIMLIM\n 70\n0\n 9\n$DIMTIH\n 70\n0\n 9\n$DIMTOH\n 70\n0\n 9\n$DIMSE1\n 70\n0\n 9\n$DIMSE2\n 70\n0\n 9\n$DIMTAD\n 70\n1\n 9\n$DIMZIN\n 70\n3\n 9\n$DIMBLK\n 1\n\n 9\n$DIMASO\n 70\n1\n 9\n$DIMSHO\n 70\n1\n 9\n$DIMPOST\n 1\n\n 9\n$DIMAPOST\n 1\n\n 9\n$DIMALT\n 70\n0\n 9\n$DIMALTD\n 70\n2\n 9\n$DIMALTF\n 40\n25.4\n 9\n$DIMLFAC\n 40\n1.0\n 9\n$DIMTOFL\n 70\n0\n 9\n$DIMTVP\n 40\n0.0\n 9\n$DIMTIX\n 70\n0\n 9\n$DIMSOXD\n 70\n0\n 9\n$DIMSAH\n 70\n0\n 9\n$DIMBLK1\n 1\n\n 9\n$DIMBLK2\n 1\n\n 9\n$DIMSTYLE\n 2\nCivil-Metric\n 9\n$DIMCLRD\n 70\n0\n 9\n$DIMCLRE\n 70\n0\n 9\n$DIMCLRT\n 70\n0\n 9\n$DIMTFAC\n 40\n1.0\n 9\n$DIMGAP\n 40\n2.0\n 9\n$DIMJUST\n 70\n0\n 9\n$DIMSD1\n 70\n0\n 9\n$DIMSD2\n 70\n0\n 9\n$DIMTOLJ\n 70\n1\n 9\n$DIMTZIN\n 70\n0\n 9\n$DIMALTZ\n 70\n0\n 9\n$DIMALTTZ\n 70\n0\n 9\n$DIMUPT\n 70\n0\n 9\n$DIMDEC\n 70\n2\n 9\n$DIMTDEC\n 70\n2\n 9\n$DIMALTU\n 70\n2\n 9\n$DIMALTTD\n 70\n2\n 9\n$DIMTXSTY\n 7\nStandard\n 9\n$DIMAUNIT\n 70\n0\n 9\n$DIMADEC\n 70\n2\n 9\n$DIMALTRND\n 40\n0.0\n 9\n$DIMAZIN\n 70\n2\n 9\n$DIMDSEP\n 70\n46\n 9\n$DIMATFIT\n 70\n3\n 9\n$DIMFRAC\n 70\n1\n 9\n$DIMLDRBLK\n 1\n\n 9\n$DIMLUNIT\n 70\n2\n 9\n$DIMLWD\n 70\n-2\n 9\n$DIMLWE\n 70\n-2\n 9\n$DIMTMOVE\n 70\n0\n 9\n$DIMFXL\n 40\n1.0\n 9\n$DIMFXLON\n 70\n0\n 9\n$DIMJOGANG\n 40\n0.785398163397\n 9\n$DIMTFILL\n 70\n0\n 9\n$DIMTFILLCLR\n 70\n0\n 9\n$DIMARCSYM\n 70\n0\n 9\n$DIMLTYPE\n 6\n\n 9\n$DIMLTEX1\n 6\n\n 9\n$DIMLTEX2\n 6\n\n 9\n$DIMTXTDIRECTION\n 70\n0\n 9\n$LUNITS\n 70\n2\n 9\n$LUPREC\n 70\n4\n 9\n$SKETCHINC\n 40\n0.1\n 9\n$FILLETRAD\n 40\n0.0\n 9\n$AUNITS\n 70\n4\n 9\n$AUPREC\n 70\n5\n 9\n$MENU\n 1\n.\n 9\n$ELEVATION\n 40\n0.0\n 9\n$PELEVATION\n 40\n0.0\n 9\n$THICKNESS\n 40\n0.0\n 9\n$LIMCHECK\n 70\n0\n 9\n$CHAMFERA\n 40\n0.0\n 9\n$CHAMFERB\n 40\n0.0\n 9\n$CHAMFERC\n 40\n0.0\n 9\n$CHAMFERD\n 40\n0.0\n 9\n$SKPOLY\n 70\n0\n 9\n$TDCREATE\n 40\n2457986.69756\n 9\n$TDUCREATE\n 40\n2455631.2632\n 9\n$TDUPDATE\n 40\n2457986.69756\n 9\n$TDUUPDATE\n 40\n2456436.43179\n 9\n$TDINDWG\n 40\n0.0003490741\n 9\n$TDUSRTIMER\n 40\n0.0003487153\n 9\n$USRTIMER\n 70\n1\n 9\n$ANGBASE\n 50\n0.0\n 9\n$ANGDIR\n 70\n0\n 9\n$PDMODE\n 70\n0\n 9\n$PDSIZE\n 40\n0.0\n 9\n$PLINEWID\n 40\n0.0\n 9\n$SPLFRAME\n 70\n0\n 9\n$SPLINETYPE\n 70\n6\n 9\n$SPLINESEGS\n 70\n8\n 9\n$HANDSEED\n 5\n5C7\n 9\n$SURFTAB1\n 70\n6\n 9\n$SURFTAB2\n 70\n6\n 9\n$SURFTYPE\n 70\n6\n 9\n$SURFU\n 70\n6\n 9\n$SURFV\n 70\n6\n 9\n$UCSBASE\n 2\n\n 9\n$UCSNAME\n 2\n\n 9\n$UCSORG\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSXDIR\n 10\n1.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSYDIR\n 10\n0.0\n 20\n1.0\n 30\n0.0\n 9\n$UCSORTHOREF\n 2\n\n 9\n$UCSORTHOVIEW\n 70\n0\n 9\n$UCSORGTOP\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGBOTTOM\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGLEFT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGRIGHT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGFRONT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$UCSORGBACK\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSBASE\n 2\n\n 9\n$PUCSNAME\n 2\n\n 9\n$PUCSORG\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSXDIR\n 10\n1.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSYDIR\n 10\n0.0\n 20\n1.0\n 30\n0.0\n 9\n$PUCSORTHOREF\n 2\n\n 9\n$PUCSORTHOVIEW\n 70\n0\n 9\n$PUCSORGTOP\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGBOTTOM\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGLEFT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGRIGHT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGFRONT\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PUCSORGBACK\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$USERI1\n 70\n0\n 9\n$USERI2\n 70\n0\n 9\n$USERI3\n 70\n0\n 9\n$USERI4\n 70\n0\n 9\n$USERI5\n 70\n0\n 9\n$USERR1\n 40\n0.0\n 9\n$USERR2\n 40\n0.0\n 9\n$USERR3\n 40\n0.0\n 9\n$USERR4\n 40\n0.0\n 9\n$USERR5\n 40\n0.0\n 9\n$WORLDVIEW\n 70\n1\n 9\n$SHADEDGE\n 70\n3\n 9\n$SHADEDIF\n 70\n70\n 9\n$TILEMODE\n 70\n1\n 9\n$MAXACTVP\n 70\n64\n 9\n$PINSBASE\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 9\n$PLIMCHECK\n 70\n0\n 9\n$PEXTMIN\n 10\n0.628866766397\n 20\n0.799999952316\n 30\n0.0\n 9\n$PEXTMAX\n 10\n9.02886638493\n 20\n7.19999957085\n 30\n0.0\n 9\n$PLIMMIN\n 10\n-0.700541819174\n 20\n-0.228100386192\n 9\n$PLIMMAX\n 10\n10.2994579405\n 20\n8.27189937351\n 9\n$UNITMODE\n 70\n0\n 9\n$VISRETAIN\n 70\n1\n 9\n$PLINEGEN\n 70\n0\n 9\n$PSLTSCALE\n 70\n1\n 9\n$TREEDEPTH\n 70\n3020\n 9\n$CMLSTYLE\n 2\nStandard\n 9\n$CMLJUST\n 70\n0\n 9\n$CMLSCALE\n 40\n1.0\n 9\n$PROXYGRAPHICS\n 70\n1\n 9\n$MEASUREMENT\n 70\n1\n 9\n$CELWEIGHT\n370\n-1\n 9\n$ENDCAPS\n280\n0\n 9\n$JOINSTYLE\n280\n0\n 9\n$LWDISPLAY\n290\n0\n 9\n$INSUNITS\n 70\n4\n 9\n$HYPERLINKBASE\n 1\n\n 9\n$STYLESHEET\n 1\n\n 9\n$XEDIT\n290\n1\n 9\n$CEPSNTYPE\n380\n0\n 9\n$PSTYLEMODE\n290\n1\n 9\n$FINGERPRINTGUID\n 2\n{39DB1BDD-BC6C-46D3-A333-DFCC0DC4782D}\n 9\n$VERSIONGUID\n 2\n{69EEBB2D-7039-498F-9366-3F994E4A07E7}\n 9\n$EXTNAMES\n290\n1\n 9\n$PSVPSCALE\n 40\n0.0\n 9\n$OLESTARTUP\n290\n0\n 9\n$SORTENTS\n280\n127\n 9\n$INDEXCTL\n280\n0\n 9\n$HIDETEXT\n280\n1\n 9\n$XCLIPFRAME\n280\n0\n 9\n$HALOGAP\n280\n0\n 9\n$OBSCOLOR\n 70\n257\n 9\n$OBSLTYPE\n280\n0\n 9\n$INTERSECTIONDISPLAY\n280\n0\n 9\n$INTERSECTIONCOLOR\n 70\n257\n 9\n$DIMASSOC\n280\n2\n 9\n$PROJECTNAME\n 1\n\n 9\n$CAMERADISPLAY\n290\n0\n 9\n$LENSLENGTH\n 40\n50.0\n 9\n$CAMERAHEIGHT\n 40\n0.0\n 9\n$STEPSPERSEC\n 40\n2.0\n 9\n$STEPSIZE\n 40\n6.0\n 9\n$3DDWFPREC\n 40\n2.0\n 9\n$PSOLWIDTH\n 40\n0.25\n 9\n$PSOLHEIGHT\n 40\n4.0\n 9\n$LOFTANG1\n 40\n1.57079632679\n 9\n$LOFTANG2\n 40\n1.57079632679\n 9\n$LOFTMAG1\n 40\n0.0\n 9\n$LOFTMAG2\n 40\n0.0\n 9\n$LOFTPARAM\n 70\n7\n 9\n$LOFTNORMALS\n280\n1\n 9\n$LATITUDE\n 40\n37.795\n 9\n$LONGITUDE\n 40\n-122.394\n 9\n$NORTHDIRECTION\n 40\n0.0\n 9\n$TIMEZONE\n 70\n-8000\n 9\n$LIGHTGLYPHDISPLAY\n280\n1\n 9\n$TILEMODELIGHTSYNCH\n280\n1\n 9\n$CMATERIAL\n347\n96\n 9\n$SOLIDHIST\n280\n1\n 9\n$SHOWHIST\n280\n1\n 9\n$DWFFRAME\n280\n2\n 9\n$DGNFRAME\n280\n0\n 9\n$REALWORLDSCALE\n290\n1\n 9\n$INTERFERECOLOR\n 62\n1\n 9\n$INTERFEREOBJVS\n345\nA3\n 9\n$INTERFEREVPVS\n346\nA0\n 9\n$CSHADOW\n280\n0\n 9\n$SHADOWPLANELOCATION\n 40\n0.0\n 0\nENDSEC"},dxfClasses:function(){return' 0\nSECTION\n 2\nCLASSES\n 0\nCLASS\n 1\nACDBDICTIONARYWDFLT\n 2\nAcDbDictionaryWithDefault\n 3\nObjectDBX Classes\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nDICTIONARYVAR\n 2\nAcDbDictionaryVar\n 3\nObjectDBX Classes\n 90\n0\n 91\n15\n280\n0\n281\n0\n 0\nCLASS\n 1\nTABLESTYLE\n 2\nAcDbTableStyle\n 3\nObjectDBX Classes\n 90\n4095\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nMATERIAL\n 2\nAcDbMaterial\n 3\nObjectDBX Classes\n 90\n1153\n 91\n3\n280\n0\n281\n0\n 0\nCLASS\n 1\nVISUALSTYLE\n 2\nAcDbVisualStyle\n 3\nObjectDBX Classes\n 90\n4095\n 91\n26\n280\n0\n281\n0\n 0\nCLASS\n 1\nSCALE\n 2\nAcDbScale\n 3\nObjectDBX Classes\n 90\n1153\n 91\n17\n280\n0\n281\n0\n 0\nCLASS\n 1\nMLEADERSTYLE\n 2\nAcDbMLeaderStyle\n 3\nACDB_MLEADERSTYLE_CLASS\n 90\n4095\n 91\n3\n280\n0\n281\n0\n 0\nCLASS\n 1\nCELLSTYLEMAP\n 2\nAcDbCellStyleMap\n 3\nObjectDBX Classes\n 90\n1152\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nEXACXREFPANELOBJECT\n 2\nExAcXREFPanelObject\n 3\nEXAC_ESW\n 90\n1025\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nNPOCOLLECTION\n 2\nAcDbImpNonPersistentObjectsCollection\n 3\nObjectDBX Classes\n 90\n1153\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nLAYER_INDEX\n 2\nAcDbLayerIndex\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nSPATIAL_INDEX\n 2\nAcDbSpatialIndex\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nIDBUFFER\n 2\nAcDbIdBuffer\n 3\nObjectDBX Classes\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nDIMASSOC\n 2\nAcDbDimAssoc\n 3\n"AcDbDimAssoc|Product Desc: AcDim ARX App For Dimension|Company: Autodesk, Inc.|WEB Address: www.autodesk.com"\n 90\n0\n 91\n0\n280\n0\n281\n0\n 0\nCLASS\n 1\nACDBSECTIONVIEWSTYLE\n 2\nAcDbSectionViewStyle\n 3\nObjectDBX Classes\n 90\n1025\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nACDBDETAILVIEWSTYLE\n 2\nAcDbDetailViewStyle\n 3\nObjectDBX Classes\n 90\n1025\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGEDEF\n 2\nAcDbRasterImageDef\n 3\nISM\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nRASTERVARIABLES\n 2\nAcDbRasterVariables\n 3\nISM\n 90\n0\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGEDEF_REACTOR\n 2\nAcDbRasterImageDefReactor\n 3\nISM\n 90\n1\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nIMAGE\n 2\nAcDbRasterImage\n 3\nISM\n 90\n2175\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nPDFDEFINITION\n 2\nAcDbPdfDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n0\n 0\nCLASS\n 1\nPDFUNDERLAY\n 2\nAcDbPdfReference\n 3\nObjectDBX Classes\n 90\n4095\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nDWFDEFINITION\n 2\nAcDbDwfDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nDWFUNDERLAY\n 2\nAcDbDwfReference\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n1\n 0\nCLASS\n 1\nDGNDEFINITION\n 2\nAcDbDgnDefinition\n 3\nObjectDBX Classes\n 90\n1153\n 91\n2\n280\n0\n281\n0\n 0\nCLASS\n 1\nDGNUNDERLAY\n 2\nAcDbDgnReference\n 3\nObjectDBX Classes\n 90\n1153\n 91\n1\n280\n0\n281\n1\n 0\nENDSEC'},dxfTables:function(){return" 0\nSECTION\n 2\nTABLES\n 0\nTABLE\n 2\nVPORT\n 5\n8\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nLTYPE\n 5\n5F\n330\n0\n100\nAcDbSymbolTable\n 70\n7\n 0\nLTYPE\n 5\n14\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nByBlock\n 70\n0\n 3\n\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n15\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nByLayer\n 70\n0\n 3\n\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n16\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nContinuous\n 70\n0\n 3\nSolid line\n 72\n65\n 73\n0\n 40\n0.0\n 0\nLTYPE\n 5\n1B1\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nCENTER\n 70\n0\n 3\nCenter ____ _ ____ _ ____ _ ____ _ ____ _ ____\n 72\n65\n 73\n4\n 40\n2.0\n 49\n1.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n1B2\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nDASHED\n 70\n0\n 3\nDashed __ __ __ __ __ __ __ __ __ __ __ __ __ _\n 72\n65\n 73\n2\n 40\n0.75\n 49\n0.5\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n1B3\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nPHANTOM\n 70\n0\n 3\nPhantom ______ __ __ ______ __ __ ______\n 72\n65\n 73\n6\n 40\n2.5\n 49\n1.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 49\n0.25\n 74\n0\n 49\n-0.25\n 74\n0\n 0\nLTYPE\n 5\n39E\n330\n5F\n100\nAcDbSymbolTableRecord\n100\nAcDbLinetypeTableRecord\n 2\nHIDDEN\n 70\n0\n 3\nHidden __ __ __ __ __ __ __ __ __ __ __ __ __ __\n 72\n65\n 73\n2\n 40\n9.525\n 49\n6.35\n 74\n0\n 49\n-3.175\n 74\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nLAYER\n 5\n2\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n 0\nLAYER\n 5\n10\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\n0\n 70\n0\n 6\nContinuous\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nLAYER\n 5\n1B4\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\nView Port\n 70\n0\n 6\nContinuous\n290\n0\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nLAYER\n 5\n21D\n330\n2\n100\nAcDbSymbolTableRecord\n100\nAcDbLayerTableRecord\n 2\nDefpoints\n 70\n0\n 6\nContinuous\n290\n0\n370\n-3\n390\nF\n347\n98\n348\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nSTYLE\n 5\n3\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n 0\nSTYLE\n 5\n11\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nStandard\n 70\n0\n 40\n0.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nSTYLE\n 5\nDC\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nAnnotative\n 70\n0\n 40\n0.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nSTYLE\n 5\n178\n330\n3\n100\nAcDbSymbolTableRecord\n100\nAcDbTextStyleTableRecord\n 2\nNotes\n 70\n0\n 40\n3.0\n 41\n1.0\n 50\n0.0\n 71\n0\n 42\n0.2\n 3\narial.ttf\n 4\n\n 0\nENDTAB\n 0\nTABLE\n 2\nVIEW\n 5\n6\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nUCS\n 5\n7\n330\n0\n100\nAcDbSymbolTable\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nAPPID\n 5\n9\n330\n0\n100\nAcDbSymbolTable\n 70\n12\n 0\nAPPID\n 5\n12\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD\n 70\n0\n 0\nAPPID\n 5\nDD\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcadAnnoPO\n 70\n0\n 0\nAPPID\n 5\nDE\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcadAnnotative\n 70\n0\n 0\nAPPID\n 5\nDF\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMJAG\n 70\n0\n 0\nAPPID\n 5\nE0\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMTALN\n 70\n0\n 0\nAPPID\n 5\n107\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_MLEADERVER\n 70\n0\n 0\nAPPID\n 5\n1B5\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nAcAecLayerStandard\n 70\n0\n 0\nAPPID\n 5\n1BA\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_EXEMPT_FROM_CAD_STANDARDS\n 70\n0\n 0\nAPPID\n 5\n237\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_DSTYLE_DIMBREAK\n 70\n0\n 0\nAPPID\n 5\n28E\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_PSEXT\n 70\n0\n 0\nAPPID\n 5\n4B0\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nACAD_NAV_VCDISPLAY\n 70\n0\n 0\nAPPID\n 5\n4E3\n330\n9\n100\nAcDbSymbolTableRecord\n100\nAcDbRegAppTableRecord\n 2\nHATCHBACKGROUNDCOLOR\n 70\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nDIMSTYLE\n 5\nA\n330\n0\n100\nAcDbSymbolTable\n 70\n3\n100\nAcDbDimStyleTable\n 71\n3\n340\n242\n340\n27\n340\nE1\n 0\nDIMSTYLE\n105\n27\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nStandard\n 70\n0\n 41\n3.0\n 42\n2.0\n 43\n9.0\n 44\n5.0\n140\n3.0\n141\n2.0\n147\n2.0\n340\n11\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n90.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nDIMSTYLE\n105\nE1\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nAnnotative\n 70\n0\n 40\n0.0\n 41\n3.0\n 42\n2.5\n 43\n10.0\n 44\n5.0\n140\n3.0\n141\n2.0\n147\n2.0\n340\n11\n1001\nAcadAnnotative\n1000\nAnnotativeData\n1002\n{\n1070\n1\n1070\n1\n1002\n}\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n90.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nDIMSTYLE\n105\n242\n330\nA\n100\nAcDbSymbolTableRecord\n100\nAcDbDimStyleTableRecord\n 2\nCivil-Metric\n 70\n0\n 41\n3.0\n 42\n1.5\n 43\n6.0\n 44\n3.0\n 73\n0\n 74\n0\n 77\n1\n 78\n3\n 79\n2\n140\n3.0\n141\n3.0\n147\n2.0\n179\n2\n271\n2\n272\n2\n276\n1\n340\n11\n1001\nACAD_DSTYLE_DIMBREAK\n1070\n391\n1040\n3.0\n1001\nACAD_DSTYLE_DIMJAG\n1070\n388\n1040\n38.0\n1001\nACAD_DSTYLE_DIMTALN\n1070\n392\n1070\n0\n 0\nENDTAB\n 0\nTABLE\n 2\nBLOCK_RECORD\n 5\n1\n330\n0\n100\nAcDbSymbolTable\n 70\n4\n 0\nBLOCK_RECORD\n 5\n1F\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n*Model_Space\n340\n530\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n58\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n*Paper_Space\n340\n531\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n238\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n_ArchTick\n340\n0\n 70\n0\n280\n1\n281\n0\n 0\nBLOCK_RECORD\n 5\n23C\n330\n1\n100\nAcDbSymbolTableRecord\n100\nAcDbBlockTableRecord\n 2\n_Open30\n340\n0\n 70\n0\n280\n1\n281\n0\n 0\nENDTAB\n 0\nENDSEC"},dxfBlocks:function(){return" 0\nSECTION\n 2\nBLOCKS\n 0\nBLOCK\n 5\n23A\n330\n238\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n_ArchTick\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n_ArchTick\n 1\n\n 0\nENDBLK\n 5\n23B\n330\n238\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n20\n330\n1F\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n*Model_Space\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n*Model_Space\n 1\n\n 0\nENDBLK\n 5\n21\n330\n1F\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n5A\n330\n58\n100\nAcDbEntity\n 67\n1\n 8\n0\n100\nAcDbBlockBegin\n 2\n*Paper_Space\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n*Paper_Space\n 1\n\n 0\nENDBLK\n 5\n5B\n330\n58\n100\nAcDbEntity\n 67\n1\n 8\n0\n100\nAcDbBlockEnd\n 0\nBLOCK\n 5\n240\n330\n23C\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockBegin\n 2\n_Open30\n 70\n0\n 10\n0.0\n 20\n0.0\n 30\n0.0\n 3\n_Open30\n 1\n\n 0\nENDBLK\n 5\n241\n330\n23C\n100\nAcDbEntity\n 8\n0\n100\nAcDbBlockEnd\n 0\nENDSEC"},dxfObjects:function(){return" 0\nSECTION\n 2\nOBJECTS\n 0\nDICTIONARY\n 5\nC\n330\n0\n100\nAcDbDictionary\n281\n1\n 3\nACAD_COLOR\n350\n524\n 3\nACAD_GROUP\n350\n525\n 3\nACAD_LAYOUT\n350\n526\n 3\nACAD_MATERIAL\n350\n527\n 3\nACAD_MLEADERSTYLE\n350\n528\n 3\nACAD_MLINESTYLE\n350\n529\n 3\nACAD_PLOTSETTINGS\n350\n52A\n 3\nACAD_PLOTSTYLENAME\n350\n52C\n 3\nACAD_SCALELIST\n350\n52D\n 3\nACAD_TABLESTYLE\n350\n52E\n 3\nACAD_VISUALSTYLE\n350\n52F\n 0\nDICTIONARY\n 5\n524\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n525\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n526\n330\nC\n100\nAcDbDictionary\n281\n1\n 3\nModel\n350\n530\n 3\nLayout1\n350\n531\n 0\nDICTIONARY\n 5\n527\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n528\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n529\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52A\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nACDBPLACEHOLDER\n 5\n52B\n330\n52C\n 0\nACDBDICTIONARYWDFLT\n 5\n52C\n330\nC\n100\nAcDbDictionary\n281\n1\n 3\nNormal\n350\n52B\n100\nAcDbDictionaryWithDefault\n340\n52B\n 0\nDICTIONARY\n 5\n52D\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52E\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nDICTIONARY\n 5\n52F\n330\nC\n100\nAcDbDictionary\n281\n1\n 0\nLAYOUT\n 5\n530\n330\n526\n100\nAcDbPlotSettings\n 1\n\n 2\nDWFx ePlot (XPS Compatible).pc3\n 4\nANSI_A_(8.50_x_11.00_Inches)\n 6\n\n 40\n5.8\n 41\n17.8\n 42\n5.8\n 43\n17.8\n 44\n215.9\n 45\n279.4\n 46\n0.0\n 47\n0.0\n 48\n0.0\n 49\n0.0\n140\n0.0\n141\n0.0\n142\n1.0\n143\n14.53\n 70\n11952\n 72\n0\n 73\n1\n 74\n0\n 7\n\n 75\n0\n147\n0.069\n148\n114.98\n149\n300.29\n100\nAcDbLayout\n 1\nModel\n 70\n1\n 71\n0\n 10\n0.0\n 20\n0.0\n 11\n12.0\n 21\n9.0\n 12\n0.0\n 22\n0.0\n 32\n0.0\n 14\n0.0\n 24\n0.0\n 34\n0.0\n 15\n0.0\n 25\n0.0\n 35\n0.0\n146\n0.0\n 13\n0.0\n 23\n0.0\n 33\n0.0\n 16\n1.0\n 26\n0.0\n 36\n0.0\n 17\n0.0\n 27\n1.0\n 37\n0.0\n 76\n0\n330\n1F\n 0\nLAYOUT\n 5\n531\n330\n526\n100\nAcDbPlotSettings\n 1\n\n 2\nDWFx ePlot (XPS Compatible).pc3\n 4\nANSI_A_(8.50_x_11.00_Inches)\n 6\n\n 40\n5.8\n 41\n17.8\n 42\n5.8\n 43\n17.8\n 44\n215.9\n 45\n279.4\n 46\n0.0\n 47\n0.0\n 48\n0.0\n 49\n0.0\n140\n0.0\n141\n0.0\n142\n1.0\n143\n1.0\n 70\n688\n 72\n0\n 73\n1\n 74\n5\n 7\nacad.ctb\n 75\n16\n147\n1.0\n148\n0.0\n149\n0.0\n100\nAcDbLayout\n 1\nLayout1\n 70\n1\n 71\n1\n 10\n-0.7\n 20\n-0.23\n 11\n10.3\n 21\n8.27\n 12\n0.0\n 22\n0.0\n 32\n0.0\n 14\n0.63\n 24\n0.8\n 34\n0.0\n 15\n9.0\n 25\n7.2\n 35\n0.0\n146\n0.0\n 13\n0.0\n 23\n0.0\n 33\n0.0\n 16\n1.0\n 26\n0.0\n 36\n0.0\n 17\n0.0\n 27\n1.0\n 37\n0.0\n 76\n0\n330\n58\n 0\nENDSEC"}}},{}],11:[function(e,t,i){t.exports=[[0,0,0,255],[255,0,0,255],[255,255,0,255],[0,255,0,255],[0,255,255,255],[0,0,255,255],[255,0,255,255],[255,255,255,255],[128,128,128,255],[192,192,192,255],[255,0,0,255],[255,127,127,255],[165,0,0,255],[165,82,82,255],[127,0,0,255],[127,63,63,255],[76,0,0,255],[76,38,38,255],[38,0,0,255],[38,19,19,255],[255,63,0,255],[255,159,127,255],[165,41,0,255],[165,103,82,255],[127,31,0,255],[127,79,63,255],[76,19,0,255],[76,47,38,255],[38,9,0,255],[38,28,19,255],[255,127,0,255],[255,191,127,255],[165,82,0,255],[165,124,82,255],[127,63,0,255],[127,95,63,255],[76,38,0,255],[76,57,38,255],[38,19,0,255],[38,28,19,255],[255,191,0,255],[255,223,127,255],[165,124,0,255],[165,145,82,255],[127,95,0,255],[127,111,63,255],[76,57,0,255],[76,66,38,255],[38,28,0,255],[38,33,19,255],[255,255,0,255],[255,255,127,255],[165,165,0,255],[165,165,82,255],[127,127,0,255],[127,127,63,255],[76,76,0,255],[76,76,38,255],[38,38,0,255],[38,38,19,255],[191,255,0,255],[223,255,127,255],[124,165,0,255],[145,165,82,255],[95,127,0,255],[111,127,63,255],[57,76,0,255],[66,76,38,255],[28,38,0,255],[33,38,19,255],[127,255,0,255],[191,255,127,255],[82,165,0,255],[124,165,82,255],[63,127,0,255],[95,127,63,255],[38,76,0,255],[57,76,38,255],[19,38,0,255],[28,38,19,255],[63,255,0,255],[159,255,127,255],[41,165,0,255],[103,165,82,255],[31,127,0,255],[79,127,63,255],[19,76,0,255],[47,76,38,255],[9,38,0,255],[23,38,19,255],[0,255,0,255],[125,255,127,255],[0,165,0,255],[82,165,82,255],[0,127,0,255],[63,127,63,255],[0,76,0,255],[38,76,38,255],[0,38,0,255],[19,38,19,255],[0,255,63,255],[127,255,159,255],[0,165,41,255],[82,165,103,255],[0,127,31,255],[63,127,79,255],[0,76,19,255],[38,76,47,255],[0,38,9,255],[19,88,23,255],[0,255,127,255],[127,255,191,255],[0,165,82,255],[82,165,124,255],[0,127,63,255],[63,127,95,255],[0,76,38,255],[38,76,57,255],[0,38,19,255],[19,88,28,255],[0,255,191,255],[127,255,223,255],[0,165,124,255],[82,165,145,255],[0,127,95,255],[63,127,111,255],[0,76,57,255],[38,76,66,255],[0,38,28,255],[19,88,88,255],[0,255,255,255],[127,255,255,255],[0,165,165,255],[82,165,165,255],[0,127,127,255],[63,127,127,255],[0,76,76,255],[38,76,76,255],[0,38,38,255],[19,88,88,255],[0,191,255,255],[127,223,255,255],[0,124,165,255],[82,145,165,255],[0,95,127,255],[63,111,217,255],[0,57,76,255],[38,66,126,255],[0,28,38,255],[19,88,88,255],[0,127,255,255],[127,191,255,255],[0,82,165,255],[82,124,165,255],[0,63,127,255],[63,95,127,255],[0,38,76,255],[38,57,126,255],[0,19,38,255],[19,28,88,255],[0,63,255,255],[127,159,255,255],[0,41,165,255],[82,103,165,255],[0,31,127,255],[63,79,127,255],[0,19,76,255],[38,47,126,255],[0,9,38,255],[19,23,88,255],[0,0,255,255],[127,127,255,255],[0,0,165,255],[82,82,165,255],[0,0,127,255],[63,63,127,255],[0,0,76,255],[38,38,126,255],[0,0,38,255],[19,19,88,255],[63,0,255,255],[159,127,255,255],[41,0,165,255],[103,82,165,255],[31,0,127,255],[79,63,127,255],[19,0,76,255],[47,38,126,255],[9,0,38,255],[23,19,88,255],[127,0,255,255],[191,127,255,255],[165,0,82,255],[124,82,165,255],[63,0,127,255],[95,63,127,255],[38,0,76,255],[57,38,126,255],[19,0,38,255],[28,19,88,255],[191,0,255,255],[223,127,255,255],[124,0,165,255],[142,82,165,255],[95,0,127,255],[111,63,127,255],[57,0,76,255],[66,38,76,255],[28,0,38,255],[88,19,88,255],[255,0,255,255],[255,127,255,255],[165,0,165,255],[165,82,165,255],[127,0,127,255],[127,63,127,255],[76,0,76,255],[76,38,76,255],[38,0,38,255],[88,19,88,255],[255,0,191,255],[255,127,223,255],[165,0,124,255],[165,82,145,255],[127,0,95,255],[127,63,111,255],[76,0,57,255],[76,38,66,255],[38,0,28,255],[88,19,88,255],[255,0,127,255],[255,127,191,255],[165,0,82,255],[165,82,124,255],[127,0,63,255],[127,63,95,255],[76,0,38,255],[76,38,57,255],[38,0,19,255],[88,19,28,255],[255,0,63,255],[255,127,159,255],[165,0,41,255],[165,82,103,255],[127,0,31,255],[127,63,79,255],[76,0,19,255],[76,38,47,255],[38,0,9,255],[88,19,23,255],[0,0,0,255],[101,101,101,255],[102,102,102,255],[153,153,153,255],[204,204,204,255],[255,255,255,255]]},{}],12:[function(e,t,i){const{geometries:s,modifiers:r}=e("@jscad/modeling"),{geom3:n,geom2:o,path2:a}=s,{flatten:l,toArray:h}=e("@jscad/array-utils"),{dxfHeaders:c,dxfClasses:u,dxfTables:d,dxfBlocks:p,dxfObjects:f}=e("./autocad_AC2017"),_=e("./colorindex2017"),m=(e,t)=>{const i=e.map(((e,i)=>{if(o.isA(e)){const i=e.color,s=e.name,r=o.toOutlines(e).map((e=>({closed:!0,points:e,color:i,name:s})));return"polyline"===t.geom2To?v(r,t):g(r,t)}if(n.isA(e))return"polyline"===t.geom3To?E(e,t):x(e,t);if(a.isA(e)){const i=e.color,s=e.name,r={closed:e.isClosed,points:a.toPoints(e),color:i,name:s};return g([r],t)}return""}));let s=" 0\nSECTION\n 2\nENTITIES\n";return i.forEach((e=>{e&&(s+=e)})),s+=" 0\nENDSEC",s},g=(e,t)=>{t.statusCallback&&t.statusCallback({progress:0});let i="";return e.forEach(((s,r)=>{if(s.points.length<1)return;const n=s.points.length+(s.closed?1:0);i+=` 0\nLWPOLYLINE\n 5\n${C(t)}\n 100\nAcDbEntity\n 3\n${y(s,t)}\n 8\n0\n 67\n0\n 62\n${A(s,t)}\n 100\nAcDbPolyline\n 90\n${n}\n 70\n${s.closed?1:0}\n`;for(let e=0;e=s.points.length&&(t-=s.points.length);const r=s.points[t];i+=` 10\n${r[0]}\n 20\n${r[1]}\n`}t.statusCallback&&t.statusCallback({progress:100*r/e.length})})),t.statusCallback&&t.statusCallback({progress:100}),[i]},v=(e,t)=>{t.statusCallback&&t.statusCallback({progress:0});let i="";return e.forEach(((s,r)=>{const n=s.points.length+(s.closed?1:0);i+=` 0\nPOLYLINE\n 5\n${C(t)}\n 100\nAcDbEntity\n 3\n${y(s,t)}\n 8\n0\n 62\n${A(s,t)}\n 100\nAcDb2dPolyline\n`;for(let e=0;e=s.points.length&&(r-=s.points.length);const n=s.points[r];i+=` 0\nVERTEX\n 5\n${C(t)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb2dVertex\n 10\n${n[0]}\n 20\n${n[1]}\n`}i+=` 0\nSEQEND\n 5\n${C(t)}\n 100\nAcDbEntity\n`,t.statusCallback&&t.statusCallback({progress:100*r/e.length})})),t.statusCallback&&t.statusCallback({progress:100}),[i]},x=(e,t)=>{t.statusCallback&&t.statusCallback({progress:0});let i="";const s=n.toPolygons(e),r=A(e,t);return s.forEach(((e,s)=>{const n=e.color?A(e,t):r;T(e).forEach(((e,s)=>{i+=S(e,t,n)}))})),t.statusCallback&&t.statusCallback({progress:100}),[i]},T=e=>{const t=e.vertices.length-2;if(t<1)return[];const i=e.vertices[0],s=[];for(let r=0;r{const s=e[0],r=e[1],n=e[2],o=e[2];return` 0\n3DFACE\n 5\n${C(t)}\n 100\nAcDbEntity\n 8\n0\n 62\n${i}\n 100\nAcDbFace\n 70\n0\n 10\n${s[0]}\n 20\n${s[1]}\n 30\n${s[2]}\n 11\n${r[0]}\n 21\n${r[1]}\n 31\n${r[2]}\n 12\n${n[0]}\n 22\n${n[1]}\n 32\n${n[2]}\n 13\n${o[0]}\n 23\n${o[1]}\n 33\n${o[2]}\n`},E=(e,t)=>{let i="";const s=b(n.toPolygons(e));return s.faces.length>0&&(i+=` 0\nPOLYLINE\n 5\n${C(t)}\n 100\nAcDbEntity\n 3\n${y(e,t)}\n 8\n0\n 62\n${A(e,t)}\n 100\nAcDb3dPolyline\n 70\n64\n 71\n${s.vertices.length}\n 72\n${s.faces.length}\n`,s.vertices.forEach((e=>{i+=` 0\nVERTEX\n 5\n${C(t)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb3dPolylineVertex\n 10\n${e[0]}\n 20\n${e[1]}\n 30\n${e[2]}\n 70\n192\n`})),s.faces.forEach((e=>{i+=` 0\nVERTEX\n 5\n${C(t)}\n 100\nAcDbEntity\n 8\n0\n 100\nAcDbVertex\n 100\nAcDb3dPolylineVertex\n 10\n0\n 20\n0\n 30\n0\n 70\n128\n 71\n${e[0]}\n 72\n${e[1]}\n 73\n${e[2]}\n 74\n${e[3]}\n`}))),[i]},b=e=>{const t=[],i=[];for(let s=0;s{e.entityId++;const t="00000"+e.entityId.toString(16).toUpperCase();return"CAD"+t.substr(t.length-5)},y=(e,t)=>{if(e.name)return e.name;const i="00000"+t.entityId.toString(16).toUpperCase();return"CAD"+i.substr(i.length-5)},A=(e,t)=>{let i=256;if(e.color){const s=Math.floor(255*e.color[0]),r=Math.floor(255*e.color[1]),n=Math.floor(255*e.color[2]),o=t.colorIndex;let a=765;for(let e=1;e{const i={geom2To:"lwpolyline",geom3To:"3dface",pathTo:"lwpolyline",statusCallback:null,colorIndex:_};if((e=Object.assign({},i,e)).entityId=0,0===(t=(t=l(t)).filter((e=>n.isA(e)||o.isA(e)||a.isA(e)))).length)throw new Error("only JSCAD geometries can be serialized to DXF");return t=h(r.generalize({snap:!0,triangulate:!0},t)),[`999\nCreated by JSCAD\n${c(e)}\n${u(e)}\n${d(e)}\n${p(e)}\n${m(t,e)}\n${f(e)}\n 0\nEOF\n`]},mimeType:"application/dxf"}},{"./autocad_AC2017":10,"./colorindex2017":11,"@jscad/array-utils":5,"@jscad/modeling":108}],13:[function(e,t,i){t.exports=class{constructor(e){this._buffer=e,this._pos=0}readInt8(){return this._decodeInt(8,!0)}readUInt8(){return this._decodeInt(8,!1)}readInt16(){return this._decodeInt(16,!0)}readUInt16(){return this._decodeInt(16,!1)}readInt32(){return this._decodeInt(32,!0)}readUInt32(){return this._decodeInt(32,!1)}readFloat(){return this._decodeFloat(23,8)}readDouble(){return this._decodeFloat(52,11)}readChar(){return this.readString(1)}readString(e){this._checkSize(8*e);const t=this._buffer.substr(this._pos,e);return this._pos+=e,t}seek(e){this._pos=e,this._checkSize(0)}getPosition(){return this._pos}getSize(){return this._buffer.length}_decodeFloat(e,t){const i=e+t+1,s=i>>3;this._checkSize(i);const r=Math.pow(2,t-1)-1,n=this._readBits(e+t,1,s),o=this._readBits(e,t,s);let a=0,l=2,h=0,c=0;do{const t=this._readByte(++h,s);c=e%8||8;let i=1<>=1;)t&i&&(a+=1/l),l*=2}while(e-=c);return this._pos+=s,o===1+(r<<1)?a?NaN:n?-1/0:1/0:(1+-2*n)*(o||a?o?Math.pow(2,o-r)*(1+a):Math.pow(2,1-r)*a:0)}_decodeInt(e,t){const i=this._readBits(0,e,e/8),s=Math.pow(2,e),r=t&&i>=s/2?i-s:i;return this._pos+=e/8,r}_shl(e,t){for(++t;--t;e=1073741824&~(e%=2147483648)?2*(e-1073741824)+2147483647+1:2*e);return e}_readByte(e,t){return 255&this._buffer.charCodeAt(this._pos+t-e-1)}_readBits(e,t,i){const s=(e+t)%8,r=e%8,n=i-(e>>3)-1;let o=i+(-(e+t)>>3),a=n-o,l=this._readByte(n,i)>>r&(1<<(a?8-r:t))-1;for(a&&s&&(l+=(this._readByte(o++,i)&(1<{"string"==typeof e?this.length+=e.length:e instanceof ArrayBuffer&&(this.length+=e.byteLength)})),i.type&&(this.type=i.type.toLowerCase()),i.endings,i.encoding&&(this.encoding=i.encoding.toLowerCase()),i.length&&(this.length=i.length),this.buffer=e.allocUnsafe(this.length);for(let e=0;e{const{data:t,mimeType:i}=e;return new s(t,{type:i})}},{"./makeBlob":17}],16:[function(e,t,i){t.exports={convertToBlob:e("./convertToBlob"),makeBlob:e("./makeBlob"),BinaryReader:e("./BinaryReader"),Blob:e("./Blob")}},{"./BinaryReader":13,"./Blob":14,"./convertToBlob":15,"./makeBlob":17}],17:[function(e,t,i){const s=e("./Blob.js");t.exports=()=>"undefined"!=typeof window?window.Blob:s},{"./Blob.js":14}],18:[function(e,t,i){const s=e("./cssColors");t.exports=e=>s[e.toLowerCase()]},{"./cssColors":20}],19:[function(e,t,i){const s=e("../utils/flatten"),r=e("../geometries/geom2"),n=e("../geometries/geom3"),o=e("../geometries/path2"),a=e("../geometries/poly3");t.exports=(e,...t)=>{if(!Array.isArray(e))throw new Error("color must be an array");if(e.length<3)throw new Error("color must contain R, G and B values");if(3===e.length&&(e=[e[0],e[1],e[2],1]),0===(t=s(t)).length)throw new Error("wrong number of arguments");const i=t.map((t=>r.isA(t)?((e,t)=>{const i=r.clone(t);return i.color=e,i})(e,t):n.isA(t)?((e,t)=>{const i=n.clone(t);return i.color=e,i})(e,t):o.isA(t)?((e,t)=>{const i=o.clone(t);return i.color=e,i})(e,t):a.isA(t)?((e,t)=>{const i=a.clone(t);return i.color=e,i})(e,t):(t.color=e,t)));return 1===i.length?i[0]:i}},{"../geometries/geom2":42,"../geometries/geom3":57,"../geometries/path2":78,"../geometries/poly3":95,"../utils/flatten":412}],20:[function(e,t,i){t.exports={black:[0,0,0],silver:[192/255,192/255,192/255],gray:[128/255,128/255,128/255],white:[1,1,1],maroon:[128/255,0,0],red:[1,0,0],purple:[128/255,0,128/255],fuchsia:[1,0,1],green:[0,128/255,0],lime:[0,1,0],olive:[128/255,128/255,0],yellow:[1,1,0],navy:[0,0,128/255],blue:[0,0,1],teal:[0,128/255,128/255],aqua:[0,1,1],aliceblue:[240/255,248/255,1],antiquewhite:[250/255,235/255,215/255],aquamarine:[127/255,1,212/255],azure:[240/255,1,1],beige:[245/255,245/255,220/255],bisque:[1,228/255,196/255],blanchedalmond:[1,235/255,205/255],blueviolet:[138/255,43/255,226/255],brown:[165/255,42/255,42/255],burlywood:[222/255,184/255,135/255],cadetblue:[95/255,158/255,160/255],chartreuse:[127/255,1,0],chocolate:[210/255,105/255,30/255],coral:[1,127/255,80/255],cornflowerblue:[100/255,149/255,237/255],cornsilk:[1,248/255,220/255],crimson:[220/255,20/255,60/255],cyan:[0,1,1],darkblue:[0,0,139/255],darkcyan:[0,139/255,139/255],darkgoldenrod:[184/255,134/255,11/255],darkgray:[169/255,169/255,169/255],darkgreen:[0,100/255,0],darkgrey:[169/255,169/255,169/255],darkkhaki:[189/255,183/255,107/255],darkmagenta:[139/255,0,139/255],darkolivegreen:[85/255,107/255,47/255],darkorange:[1,140/255,0],darkorchid:[.6,50/255,.8],darkred:[139/255,0,0],darksalmon:[233/255,150/255,122/255],darkseagreen:[143/255,188/255,143/255],darkslateblue:[72/255,61/255,139/255],darkslategray:[47/255,79/255,79/255],darkslategrey:[47/255,79/255,79/255],darkturquoise:[0,206/255,209/255],darkviolet:[148/255,0,211/255],deeppink:[1,20/255,147/255],deepskyblue:[0,191/255,1],dimgray:[105/255,105/255,105/255],dimgrey:[105/255,105/255,105/255],dodgerblue:[30/255,144/255,1],firebrick:[178/255,34/255,34/255],floralwhite:[1,250/255,240/255],forestgreen:[34/255,139/255,34/255],gainsboro:[220/255,220/255,220/255],ghostwhite:[248/255,248/255,1],gold:[1,215/255,0],goldenrod:[218/255,165/255,32/255],greenyellow:[173/255,1,47/255],grey:[128/255,128/255,128/255],honeydew:[240/255,1,240/255],hotpink:[1,105/255,180/255],indianred:[205/255,92/255,92/255],indigo:[75/255,0,130/255],ivory:[1,1,240/255],khaki:[240/255,230/255,140/255],lavender:[230/255,230/255,250/255],lavenderblush:[1,240/255,245/255],lawngreen:[124/255,252/255,0],lemonchiffon:[1,250/255,205/255],lightblue:[173/255,216/255,230/255],lightcoral:[240/255,128/255,128/255],lightcyan:[224/255,1,1],lightgoldenrodyellow:[250/255,250/255,210/255],lightgray:[211/255,211/255,211/255],lightgreen:[144/255,238/255,144/255],lightgrey:[211/255,211/255,211/255],lightpink:[1,182/255,193/255],lightsalmon:[1,160/255,122/255],lightseagreen:[32/255,178/255,170/255],lightskyblue:[135/255,206/255,250/255],lightslategray:[119/255,136/255,.6],lightslategrey:[119/255,136/255,.6],lightsteelblue:[176/255,196/255,222/255],lightyellow:[1,1,224/255],limegreen:[50/255,205/255,50/255],linen:[250/255,240/255,230/255],magenta:[1,0,1],mediumaquamarine:[.4,205/255,170/255],mediumblue:[0,0,205/255],mediumorchid:[186/255,85/255,211/255],mediumpurple:[147/255,112/255,219/255],mediumseagreen:[60/255,179/255,113/255],mediumslateblue:[123/255,104/255,238/255],mediumspringgreen:[0,250/255,154/255],mediumturquoise:[72/255,209/255,.8],mediumvioletred:[199/255,21/255,133/255],midnightblue:[25/255,25/255,112/255],mintcream:[245/255,1,250/255],mistyrose:[1,228/255,225/255],moccasin:[1,228/255,181/255],navajowhite:[1,222/255,173/255],oldlace:[253/255,245/255,230/255],olivedrab:[107/255,142/255,35/255],orange:[1,165/255,0],orangered:[1,69/255,0],orchid:[218/255,112/255,214/255],palegoldenrod:[238/255,232/255,170/255],palegreen:[152/255,251/255,152/255],paleturquoise:[175/255,238/255,238/255],palevioletred:[219/255,112/255,147/255],papayawhip:[1,239/255,213/255],peachpuff:[1,218/255,185/255],peru:[205/255,133/255,63/255],pink:[1,192/255,203/255],plum:[221/255,160/255,221/255],powderblue:[176/255,224/255,230/255],rosybrown:[188/255,143/255,143/255],royalblue:[65/255,105/255,225/255],saddlebrown:[139/255,69/255,19/255],salmon:[250/255,128/255,114/255],sandybrown:[244/255,164/255,96/255],seagreen:[46/255,139/255,87/255],seashell:[1,245/255,238/255],sienna:[160/255,82/255,45/255],skyblue:[135/255,206/255,235/255],slateblue:[106/255,90/255,205/255],slategray:[112/255,128/255,144/255],slategrey:[112/255,128/255,144/255],snow:[1,250/255,250/255],springgreen:[0,1,127/255],steelblue:[70/255,130/255,180/255],tan:[210/255,180/255,140/255],thistle:[216/255,191/255,216/255],tomato:[1,99/255,71/255],turquoise:[64/255,224/255,208/255],violet:[238/255,130/255,238/255],wheat:[245/255,222/255,179/255],whitesmoke:[245/255,245/255,245/255],yellowgreen:[154/255,205/255,50/255]}},{}],21:[function(e,t,i){t.exports=e=>{if((e=e.replace("#","")).length<6)throw new Error("the given notation must contain 3 or more hex values");const t=parseInt(e.substring(0,2),16)/255,i=parseInt(e.substring(2,4),16)/255,s=parseInt(e.substring(4,6),16)/255;return e.length>=8?[t,i,s,parseInt(e.substring(6,8),16)/255]:[t,i,s]}},{}],22:[function(e,t,i){const s=e("../utils/flatten"),r=e("./hueToColorComponent");t.exports=(...e)=>{if((e=s(e)).length<3)throw new Error("values must contain H, S and L values");const t=e[0],i=e[1],n=e[2];let o=n,a=n,l=n;if(0!==i){const e=n<.5?n*(1+i):n+i-n*i,s=2*n-e;o=r(s,e,t+1/3),a=r(s,e,t),l=r(s,e,t-1/3)}return e.length>3?[o,a,l,e[3]]:[o,a,l]}},{"../utils/flatten":412,"./hueToColorComponent":24}],23:[function(e,t,i){const s=e("../utils/flatten");t.exports=(...e)=>{if((e=s(e)).length<3)throw new Error("values must contain H, S and V values");const t=e[0],i=e[1],r=e[2];let n=0,o=0,a=0;const l=Math.floor(6*t),h=6*t-l,c=r*(1-i),u=r*(1-h*i),d=r*(1-(1-h)*i);switch(l%6){case 0:n=r,o=d,a=c;break;case 1:n=u,o=r,a=c;break;case 2:n=c,o=r,a=d;break;case 3:n=c,o=u,a=r;break;case 4:n=d,o=c,a=r;break;case 5:n=r,o=c,a=u}return e.length>3?[n,o,a,e[3]]:[n,o,a]}},{"../utils/flatten":412}],24:[function(e,t,i){t.exports=(e,t,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e)},{}],25:[function(e,t,i){t.exports={colorize:e("./colorize"),colorNameToRgb:e("./colorNameToRgb"),cssColors:e("./cssColors"),hexToRgb:e("./hexToRgb"),hslToRgb:e("./hslToRgb"),hsvToRgb:e("./hsvToRgb"),hueToColorComponent:e("./hueToColorComponent"),rgbToHex:e("./rgbToHex"),rgbToHsl:e("./rgbToHsl"),rgbToHsv:e("./rgbToHsv")}},{"./colorNameToRgb":18,"./colorize":19,"./cssColors":20,"./hexToRgb":21,"./hslToRgb":22,"./hsvToRgb":23,"./hueToColorComponent":24,"./rgbToHex":26,"./rgbToHsl":27,"./rgbToHsv":28}],26:[function(e,t,i){const s=e("../utils/flatten");t.exports=(...e)=>{if((e=s(e)).length<3)throw new Error("values must contain R, G and B values");const t=255*e[0],i=255*e[1],r=255*e[2];let n=`#${Number(16777216+65536*t+256*i+r).toString(16).substring(1,7)}`;return e.length>3&&(n+=Number(255*e[3]).toString(16)),n}},{"../utils/flatten":412}],27:[function(e,t,i){const s=e("../utils/flatten");t.exports=(...e)=>{if((e=s(e)).length<3)throw new Error("values must contain R, G and B values");const t=e[0],i=e[1],r=e[2],n=Math.max(t,i,r),o=Math.min(t,i,r);let a,l;const h=(n+o)/2;if(n===o)a=l=0;else{const e=n-o;switch(l=h>.5?e/(2-n-o):e/(n+o),n){case t:a=(i-r)/e+(i3?[a,l,h,e[3]]:[a,l,h]}},{"../utils/flatten":412}],28:[function(e,t,i){const s=e("../utils/flatten");t.exports=(...e)=>{if((e=s(e)).length<3)throw new Error("values must contain R, G and B values");const t=e[0],i=e[1],r=e[2],n=Math.max(t,i,r),o=Math.min(t,i,r);let a;const l=n,h=n-o,c=0===n?0:h/n;if(n===o)a=0;else{switch(n){case t:a=(i-r)/h+(i3?[a,c,l,e[3]]:[a,c,l]}},{"../utils/flatten":412}],29:[function(e,t,i){const s=e("./lengths");t.exports=(e,t)=>{const{distance:i,segments:r}=Object.assign({},{distance:0,segments:100},e),n=s(r,t);let o=0,a=r;for(;o<=a;){const e=Math.floor(o+(a-o)/2),t=n[e]-i;if(t<0)o=e+1;else{if(!(t>0)){a=e;break}a=e-1}}const l=a;if(n[l]===i)return l/r;const h=n[l];return(l+(i-h)/(n[l+1]-h))/r}},{"./lengths":33}],30:[function(e,t,i){const s=function(e){const t=[];for(let i=0;i<=e;i++)t.push(r(e)/(r(i)*r(e-i)));return t},r=function(e){let t=1;for(let i=2;i<=e;i++)t*=i;return t};t.exports=e=>{if(!Array.isArray(e))throw new Error("Bezier points must be a valid array/");if(e.length<2)throw new Error("Bezier points must contain at least 2 values.");const t=function(e){let t=null;return e.forEach((e=>{let i="";if(Number.isFinite(e))i="float_single";else{if(!Array.isArray(e))throw new Error("Bezier points must all be numbers or arrays of number.");e.forEach((e=>{if(!Number.isFinite(e))throw new Error("Bezier point values must all be numbers.")})),i="float_"+e.length}if(null==t)t=i;else if(t!==i)throw new Error("Bezier points must be either all numbers or all arrays of numbers of the same size.")})),t}(e);return{points:e,pointType:t,dimensions:"float_single"===t?0:e[0].length,permutations:s(e.length-1),tangentPermutations:s(e.length-2)}}},{}],31:[function(e,t,i){t.exports={create:e("./create"),valueAt:e("./valueAt"),tangentAt:e("./tangentAt"),lengths:e("./lengths"),length:e("./length"),arcLengthToT:e("./arcLengthToT")}},{"./arcLengthToT":29,"./create":30,"./length":32,"./lengths":33,"./tangentAt":34,"./valueAt":35}],32:[function(e,t,i){const s=e("./lengths");t.exports=(e,t)=>s(e,t)[e]},{"./lengths":33}],33:[function(e,t,i){const s=e("./valueAt"),r=(e,t)=>{if(Number.isFinite(e)&&Number.isFinite(t))return Math.abs(e-t);if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)throw new Error("The operands must have the same number of dimensions.");let i=0;for(let s=0;s{let i=0;const n=[0];let o=s(0,t);for(let a=1;a<=e;a++){const l=s(a/e,t);i+=r(l,o),n.push(i),o=l}return n}},{"./valueAt":35}],34:[function(e,t,i){const s=function(e,t,i){const s=t.length-1;let r=0;for(let n=0;n{if(e<0||e>1)throw new Error("Bezier tangentAt() input must be between 0 and 1");if("float_single"===t.pointType)return s(t,t.points,e);{const i=[];for(let r=0;r{if(e<0||e>1)throw new Error("Bezier valueAt() input must be between 0 and 1");if("float_single"===t.pointType)return s(t,t.points,e);{const i=[];for(let r=0;r(s.isIdentity(e.transforms)||(e.sides=e.sides.map((t=>[r.transform(r.create(),t[0],e.transforms),r.transform(r.create(),t[1],e.transforms)])),e.transforms=s.create()),e)},{"../../maths/mat4":159,"../../maths/vec2":206}],38:[function(e,t,i){t.exports=e=>Object.assign({},e)},{}],39:[function(e,t,i){const s=e("../../maths/mat4");t.exports=e=>(void 0===e&&(e=[]),{sides:e,transforms:s.create()})},{"../../maths/mat4":159}],40:[function(e,t,i){const s=e("../../maths/mat4"),r=e("../../maths/vec2"),n=e("./create");t.exports=e=>{if(0!==e[0])throw new Error("invalid compact binary data");const t=n();t.transforms=s.clone(e.slice(1,17));for(let i=21;i=0&&(t.color=[e[17],e[18],e[19],e[20]]),t}},{"../../maths/mat4":159,"../../maths/vec2":206,"./create":39}],41:[function(e,t,i){const s=e("../../maths/vec2"),r=e("./create");t.exports=e=>{if(!Array.isArray(e))throw new Error("the given points must be an array");let t=e.length;if(t<3)throw new Error("the given points must define a closed geometry with three or more points");s.equals(e[0],e[t-1])&&--t;const i=[];let n=e[t-1];for(let r=0;r!!(e&&"object"==typeof e&&"sides"in e&&"transforms"in e&&Array.isArray(e.sides)&&"length"in e.transforms)},{}],44:[function(e,t,i){const s=e("./create"),r=e("./toSides");t.exports=e=>{const t=r(e).map((e=>[e[1],e[0]]));return t.reverse(),s(t)}},{"./create":39,"./toSides":48}],45:[function(e,t,i){t.exports=e=>{const t=e.sides,i=e.transforms;let s=[-1,-1,-1,-1];e.color&&(s=e.color);const r=new Float32Array(21+4*t.length);r[0]=0,r[1]=i[0],r[2]=i[1],r[3]=i[2],r[4]=i[3],r[5]=i[4],r[6]=i[5],r[7]=i[6],r[8]=i[7],r[9]=i[8],r[10]=i[9],r[11]=i[10],r[12]=i[11],r[13]=i[12],r[14]=i[13],r[15]=i[14],r[16]=i[15],r[17]=s[0],r[18]=s[1],r[19]=s[2],r[20]=s[3];for(let e=0;e{if(1===t.length)return t.pop();const i=s.create(),r=s.angleDegrees(s.subtract(i,e[1],e[0]));let n,o;t.forEach(((e,t)=>{let a=s.angleDegrees(s.subtract(i,e[1],e[0]))-r;a<-180&&(a+=360),a>=180&&(a-=360),(void 0===o||a>n)&&(o=t,n=a)}));const a=t[o];return t.splice(o,1),a};t.exports=e=>{const t=(e=>{const t=new Map;return(e=>{const t=new Map,i=e=>{const i=e.toString();return t.has(i)?t.get(i):(t.set(i,e),e)};return e.map((e=>e.map(i)))})(e).forEach((e=>{t.has(e[0])?t.get(e[0]).push(e):t.set(e[0],[e])})),t})(r(e)),i=[];for(;;){let e;for(const[i,s]of t){if(e=s.shift(),e)break;t.delete(i)}if(void 0===e)break;const s=[],r=e[0];for(;;){s.push(e[0]);const i=e[1];if(i===r)break;const o=t.get(i);if(!o)throw new Error(`geometry is not closed at vertex ${i}`);const a=n(e,o);0===o.length&&t.delete(i),e=a}s.length>0&&s.push(s.shift()),i.push(s)}return t.clear(),i}},{"../../maths/vec2":206,"./toSides":48}],47:[function(e,t,i){const s=e("./toSides");t.exports=e=>{const t=s(e).map((e=>e[0]));return t.length>0&&t.push(t.shift()),t}},{"./toSides":48}],48:[function(e,t,i){const s=e("./applyTransforms");t.exports=e=>s(e).sides},{"./applyTransforms":37}],49:[function(e,t,i){const s=e("../../maths/vec2"),r=e("./toSides");t.exports=e=>{const t=r(e);let i="geom2 ("+t.length+" sides):\n[\n";return t.forEach((e=>{i+=" ["+s.toString(e[0])+", "+s.toString(e[1])+"]\n"})),i+="]\n",i}},{"../../maths/vec2":206,"./toSides":48}],50:[function(e,t,i){const s=e("../../maths/mat4");t.exports=(e,t)=>{const i=s.multiply(s.create(),e,t.transforms);return Object.assign({},t,{transforms:i})}},{"../../maths/mat4":159}],51:[function(e,t,i){const s=e("../../maths/vec2"),r=e("./isA"),n=e("./toOutlines");t.exports=e=>{if(!r(e))throw new Error("invalid geom2 structure");if(n(e),e.sides.forEach((e=>{if(s.equals(e[0],e[1]))throw new Error(`geom2 self-edge ${e[0]}`)})),!e.transforms.every(Number.isFinite))throw new Error(`geom2 invalid transforms ${e.transforms}`)}},{"../../maths/vec2":206,"./isA":43,"./toOutlines":46}],52:[function(e,t,i){const s=e("../../maths/mat4"),r=e("../poly3");t.exports=e=>(s.isIdentity(e.transforms)||(e.polygons=e.polygons.map((t=>r.transform(e.transforms,t))),e.transforms=s.create()),e)},{"../../maths/mat4":159,"../poly3":95}],53:[function(e,t,i){t.exports=e=>Object.assign({},e)},{}],54:[function(e,t,i){const s=e("../../maths/mat4");t.exports=e=>(void 0===e&&(e=[]),{polygons:e,transforms:s.create()})},{"../../maths/mat4":159}],55:[function(e,t,i){const s=e("../../maths/vec3"),r=e("../../maths/mat4"),n=e("../poly3"),o=e("./create");t.exports=e=>{if(1!==e[0])throw new Error("invalid compact binary data");const t=o();t.transforms=r.clone(e.slice(1,17));const i=e[21];let a=22,l=e.length-3*i;for(;l=0&&(t.color=[e[17],e[18],e[19],e[20]]),t}},{"../../maths/mat4":159,"../../maths/vec3":237,"../poly3":95,"./create":54}],56:[function(e,t,i){const s=e("../poly3"),r=e("./create");t.exports=e=>{if(!Array.isArray(e))throw new Error("the given points must be an array");const t=e.map(((e,t)=>s.create(e)));return r(t)}},{"../poly3":95,"./create":54}],57:[function(e,t,i){t.exports={clone:e("./clone"),create:e("./create"),fromPoints:e("./fromPoints"),fromCompactBinary:e("./fromCompactBinary"),invert:e("./invert"),isA:e("./isA"),toPoints:e("./toPoints"),toPolygons:e("./toPolygons"),toString:e("./toString"),toCompactBinary:e("./toCompactBinary"),transform:e("./transform"),validate:e("./validate")}},{"./clone":53,"./create":54,"./fromCompactBinary":55,"./fromPoints":56,"./invert":58,"./isA":59,"./toCompactBinary":60,"./toPoints":61,"./toPolygons":62,"./toString":63,"./transform":64,"./validate":65}],58:[function(e,t,i){const s=e("../poly3"),r=e("./create"),n=e("./toPolygons");t.exports=e=>{const t=n(e).map((e=>s.invert(e)));return r(t)}},{"../poly3":95,"./create":54,"./toPolygons":62}],59:[function(e,t,i){t.exports=e=>!!(e&&"object"==typeof e&&"polygons"in e&&"transforms"in e&&Array.isArray(e.polygons)&&"length"in e.transforms)},{}],60:[function(e,t,i){const s=e("../poly3");t.exports=e=>{const t=e.polygons,i=e.transforms,r=t.length,n=t.reduce(((e,t)=>e+t.vertices.length),0);let o=[-1,-1,-1,-1];e.color&&(o=e.color);const a=new Float32Array(22+r+3*n);a[0]=1,a[1]=i[0],a[2]=i[1],a[3]=i[2],a[4]=i[3],a[5]=i[4],a[6]=i[5],a[7]=i[6],a[8]=i[7],a[9]=i[8],a[10]=i[9],a[11]=i[10],a[12]=i[11],a[13]=i[12],a[14]=i[13],a[15]=i[14],a[16]=i[15],a[17]=o[0],a[18]=o[1],a[19]=o[2],a[20]=o[3],a[21]=n;let l=22,h=l+r;return t.forEach((e=>{const t=s.toPoints(e);a[l]=t.length,l++;for(let e=0;er(e).map((e=>s.toPoints(e)))},{"../poly3":95,"./toPolygons":62}],62:[function(e,t,i){const s=e("./applyTransforms");t.exports=e=>s(e).polygons},{"./applyTransforms":52}],63:[function(e,t,i){const s=e("../poly3"),r=e("./toPolygons");t.exports=e=>{const t=r(e);let i="geom3 ("+t.length+" polygons):\n";return t.forEach((e=>{i+=" "+s.toString(e)+"\n"})),i}},{"../poly3":95,"./toPolygons":62}],64:[function(e,t,i){const s=e("../../maths/mat4");t.exports=(e,t)=>{const i=s.multiply(s.create(),e,t.transforms);return Object.assign({},t,{transforms:i})}},{"../../maths/mat4":159}],65:[function(e,t,i){const s=e("../poly3"),r=e("./isA");t.exports=e=>{if(!r(e))throw new Error("invalid geom3 structure");if(e.polygons.forEach(s.validate),(e=>{const t=new Map;e.polygons.forEach((({vertices:e})=>{e.forEach(((i,s)=>{const r=`${i}/${e[(s+1)%e.length]}`,n=t.has(r)?t.get(r):0;t.set(r,n+1)}))}));const i=[];if(t.forEach(((e,s)=>{const r=s.split("/").reverse().join("/");e!==t.get(r)&&i.push(s.replace("/"," -> "))})),i.length>0)throw new Error(`non-manifold edges ${i.length}\n${i.join("\n")}`)})(e),!e.transforms.every(Number.isFinite))throw new Error(`geom3 invalid transforms ${e.transforms}`)}},{"../poly3":95,"./isA":59}],66:[function(e,t,i){t.exports={geom2:e("./geom2"),geom3:e("./geom3"),path2:e("./path2"),poly2:e("./poly2"),poly3:e("./poly3")}},{"./geom2":42,"./geom3":57,"./path2":78,"./poly2":89,"./poly3":95}],67:[function(e,t,i){const{TAU:s}=e("../../maths/constants"),r=e("../../maths/vec2"),n=e("./fromPoints"),o=e("./toPoints");t.exports=(e,t)=>{let{endpoint:i,radius:a,xaxisrotation:l,clockwise:h,large:c,segments:u}=Object.assign({},{radius:[0,0],xaxisrotation:0,clockwise:!1,large:!1,segments:16},e);if(!Array.isArray(i))throw new Error("endpoint must be an array of X and Y values");if(i.length<2)throw new Error("endpoint must contain X and Y values");if(i=r.clone(i),!Array.isArray(a))throw new Error("radius must be an array of X and Y values");if(a.length<2)throw new Error("radius must contain X and Y values");if(u<4)throw new Error("segments must be four or more");const d=1e5;if(t.isClosed)throw new Error("the given path cannot be closed");const p=o(t);if(p.length<1)throw new Error("the given path must contain one or more points (as the starting point for the arc)");let f=a[0],_=a[1];const m=p[p.length-1];f=Math.round(f*d)/d,_=Math.round(_*d)/d,i=r.fromValues(Math.round(i[0]*d)/d,Math.round(i[1]*d)/d);const g=!h;let v=[];if(0===f||0===_)v.push(i);else{f=Math.abs(f),_=Math.abs(_);const t=l,n=Math.cos(t),o=Math.sin(t),a=r.subtract(r.create(),m,i);r.scale(a,a,.5);const h=Math.round((n*a[0]+o*a[1])*d)/d,p=Math.round((-o*a[0]+n*a[1])*d)/d,x=r.fromValues(h,p),T=x[0]*x[0]/(f*f)+x[1]*x[1]/(_*_);if(T>1){const e=Math.sqrt(T);f*=e,_*=e,f=Math.round(f*d)/d,_=Math.round(_*d)/d}let S=Math.sqrt((f*f*_*_-f*f*x[1]*x[1]-_*_*x[0]*x[0])/(f*f*x[1]*x[1]+_*_*x[0]*x[0]));g===c&&(S=-S);const E=r.fromValues(f*x[1]/_,-_*x[0]/f);r.scale(E,E,S);let b=r.fromValues(n*E[0]-o*E[1],o*E[0]+n*E[1]);b=r.add(b,b,r.scale(r.create(),r.add(r.create(),m,i),.5));const C=r.fromValues((x[0]-E[0])/f,(x[1]-E[1])/_),y=r.fromValues((-x[0]-E[0])/f,(-x[1]-E[1])/_),A=r.angleRadians(C);let R=r.angleRadians(y)-A;R%=s,!g&&R>0?R-=s:g&&R<0&&(R+=s);let I=Math.ceil(Math.abs(R)/s*u)+1;I<1&&(I=1);for(let e=1;e{let{controlPoints:i,segments:l}=Object.assign({},{segments:16},e);if(!Array.isArray(i))throw new Error("controlPoints must be an array of one or more points");if(i.length<1)throw new Error("controlPoints must be an array of one or more points");if(l<4)throw new Error("segments must be four or more");if(t.isClosed)throw new Error("the given geometry cannot be closed");const h=a(t);if(h.length<1)throw new Error("the given path must contain one or more points (as the starting point for the bezier curve)");if(i=i.slice(),null===i[0]){if(i.length<2)throw new Error("a null control point must be passed with one more control points");let e=h[h.length-2];if("lastBezierControlPoint"in t&&(e=t.lastBezierControlPoint),!Array.isArray(e))throw new Error("the given path must contain TWO or more points if given a null control point");const s=r.scale(r.create(),h[h.length-1],2);r.subtract(s,s,e),i[0]=s}i.unshift(h[h.length-1]);const c=i.length-1,u=[];let d=1;for(let e=0;e<=c;++e)e>0&&(d*=e),u.push(d);const p=[];for(let e=0;e<=c;++e){const t=u[c]/(u[e]*u[c-e]);p.push(t)}const f=r.create(),_=r.create(),m=n.create(),g=e=>{let t=1,s=Math.pow(1-e,c);const n=1!==e?1/(1-e):1,o=r.create();for(let a=0;a<=c;++a){a===c&&(s=1);const l=p[a]*t*s,h=r.scale(f,i[a],l);r.add(o,o,h),t*=e,s*=n}return o},v=[],x=[],T=c+1;for(let e=0;eb){const e=x[S-1],t=x[S+1],i=e+1*(t-e)/3,s=e+2*(t-e)/3,r=g(i),n=g(s);v.splice(S,1,r,n),x.splice(S,1,i,s),S--,S<1&&(S=1)}else++S}v.shift();const C=o(v,t);return C.lastBezierControlPoint=i[i.length-2],C}},{"../../maths/constants":110,"../../maths/vec2":206,"./appendPoints":69,"./toPoints":82}],69:[function(e,t,i){const s=e("./concat"),r=e("./create");t.exports=(e,t)=>s(t,r(e))},{"./concat":73,"./create":74}],70:[function(e,t,i){const s=e("../../maths/mat4"),r=e("../../maths/vec2");t.exports=e=>(s.isIdentity(e.transforms)||(e.points=e.points.map((t=>r.transform(r.create(),t,e.transforms))),e.transforms=s.create()),e)},{"../../maths/mat4":159,"../../maths/vec2":206}],71:[function(e,t,i){t.exports=e=>Object.assign({},e)},{}],72:[function(e,t,i){const{EPS:s}=e("../../maths/constants"),r=e("../../maths/vec2"),n=e("./clone");t.exports=e=>{if(e.isClosed)return e;const t=n(e);if(t.isClosed=!0,t.points.length>1){const e=t.points,i=e[0];let n=e[e.length-1];for(;r.distance(i,n){let t=!1,i=[];return e.forEach(((e,s)=>{const o=r(e).slice();if(i.length>0&&o.length>0&&n(o[0],i[i.length-1])&&o.shift(),o.length>0&&t)throw new Error(`Cannot concatenate to a closed path; check the ${s}th path`);t=e.isClosed,i=i.concat(o)})),s({closed:t},i)}},{"../../maths/vec2":206,"./fromPoints":77,"./toPoints":82}],74:[function(e,t,i){const s=e("../../maths/mat4");t.exports=e=>(void 0===e&&(e=[]),{points:e,isClosed:!1,transforms:s.create()})},{"../../maths/mat4":159}],75:[function(e,t,i){const s=e("../../maths/vec2"),r=e("./toPoints");t.exports=(e,t)=>{if(e.isClosed!==t.isClosed)return!1;if(e.points.length!==t.points.length)return!1;const i=r(e),n=r(t),o=i.length;let a=0;do{let t=!1;for(let e=0;e{if(2!==e[0])throw new Error("invalid compact binary data");const t=n();t.transforms=s.clone(e.slice(1,17)),t.isClosed=!!e[17];for(let i=22;i=0&&(t.color=[e[18],e[19],e[20],e[21]]),t}},{"../../maths/mat4":159,"../../maths/vec2":206,"./create":74}],77:[function(e,t,i){const{EPS:s}=e("../../maths/constants"),r=e("../../maths/vec2"),n=e("./close"),o=e("./create");t.exports=(e,t)=>{let{closed:i}=Object.assign({},{closed:!1},e),a=o();if(a.points=t.map((e=>r.clone(e))),a.points.length>1){const e=a.points[0],t=a.points[a.points.length-1];r.distance(e,t)!!(e&&"object"==typeof e&&"points"in e&&"transforms"in e&&"isClosed"in e&&Array.isArray(e.points)&&"length"in e.transforms)},{}],80:[function(e,t,i){const s=e("./clone");t.exports=e=>{const t=s(e);return t.points=e.points.slice().reverse(),t}},{"./clone":71}],81:[function(e,t,i){t.exports=e=>{const t=e.points,i=e.transforms;let s=[-1,-1,-1,-1];e.color&&(s=e.color);const r=new Float32Array(22+2*t.length);r[0]=2,r[1]=i[0],r[2]=i[1],r[3]=i[2],r[4]=i[3],r[5]=i[4],r[6]=i[5],r[7]=i[6],r[8]=i[7],r[9]=i[8],r[10]=i[9],r[11]=i[10],r[12]=i[11],r[13]=i[12],r[14]=i[13],r[15]=i[14],r[16]=i[15],r[17]=e.isClosed?1:0,r[18]=s[0],r[19]=s[1],r[20]=s[2],r[21]=s[3];for(let e=0;es(e).points},{"./applyTransforms":70}],83:[function(e,t,i){const s=e("../../maths/vec2"),r=e("./toPoints");t.exports=e=>{const t=r(e);let i="path ("+t.length+" points, "+e.isClosed+"):\n[\n";return t.forEach((e=>{i+=" "+s.toString(e)+",\n"})),i+="]\n",i}},{"../../maths/vec2":206,"./toPoints":82}],84:[function(e,t,i){const s=e("../../maths/mat4");t.exports=(e,t)=>{const i=s.multiply(s.create(),e,t.transforms);return Object.assign({},t,{transforms:i})}},{"../../maths/mat4":159}],85:[function(e,t,i){const s=e("../../maths/vec2"),r=e("./isA");t.exports=e=>{if(!r(e))throw new Error("invalid path2 structure");if(e.points.length>1)for(let t=0;t{if(!e.every(Number.isFinite))throw new Error(`path2 invalid point ${e}`)})),!e.transforms.every(Number.isFinite))throw new Error(`path2 invalid transforms ${e.transforms}`)}},{"../../maths/vec2":206,"./isA":79}],86:[function(e,t,i){const s=e("./measureArea"),r=e("./flip");t.exports=(e,t)=>{if(0===e.length)return 0;const i=t.vertices;return i.length<3?0:(s(t)<0&&(t=r(t)),e.reduce(((e,t)=>e+((e,t)=>{const i=t.length,s=e[0],r=e[1];let n=t[i-1],o=t[0],a=n[1]>r,l=0,h=0;for(let e=i+1;--e;){const e=o[1]>r;if(a!==e){const e=n[0]>s,t=o[0]>s;(e&&t||o[0]-(o[1]-r)*(n[0]-o[0])/(n[1]-o[1])>=s)&&(l=!l)}a=e,n=o,o=t[++h]}return l})(t,i)),0)===e.length?1:0)}},{"./flip":88,"./measureArea":90}],87:[function(e,t,i){t.exports=e=>((void 0===e||e.length<3)&&(e=[]),{vertices:e})},{}],88:[function(e,t,i){const s=e("./create");t.exports=e=>{const t=e.vertices.slice().reverse();return s(t)}},{"./create":87}],89:[function(e,t,i){t.exports={arePointsInside:e("./arePointsInside"),create:e("./create"),flip:e("./flip"),measureArea:e("./measureArea")}},{"./arePointsInside":86,"./create":87,"./flip":88,"./measureArea":90}],90:[function(e,t,i){const s=e("../../maths/utils/area");t.exports=e=>s(e.vertices)},{"../../maths/utils/area":183}],91:[function(e,t,i){const s=e("./create"),r=e("../../maths/vec3");t.exports=(...e)=>{let t,i;return 1===e.length?(t=s(),i=e[0]):(t=e[0],i=e[1]),t.vertices=i.vertices.map((e=>r.clone(e))),t}},{"../../maths/vec3":237,"./create":92}],92:[function(e,t,i){t.exports=e=>((void 0===e||e.length<3)&&(e=[]),{vertices:e})},{}],93:[function(e,t,i){const s=e("../../maths/vec3"),r=e("./create");t.exports=e=>{const t=e.map((e=>s.clone(e)));return r(t)}},{"../../maths/vec3":237,"./create":92}],94:[function(e,t,i){const s=e("./create");t.exports=(e,t)=>{const i=s(e);return i.plane=t,i}},{"./create":92}],95:[function(e,t,i){t.exports={clone:e("./clone"),create:e("./create"),fromPoints:e("./fromPoints"),fromPointsAndPlane:e("./fromPointsAndPlane"),invert:e("./invert"),isA:e("./isA"),isConvex:e("./isConvex"),measureArea:e("./measureArea"),measureBoundingBox:e("./measureBoundingBox"),measureBoundingSphere:e("./measureBoundingSphere"),measureSignedVolume:e("./measureSignedVolume"),plane:e("./plane"),toPoints:e("./toPoints"),toString:e("./toString"),transform:e("./transform"),validate:e("./validate")}},{"./clone":91,"./create":92,"./fromPoints":93,"./fromPointsAndPlane":94,"./invert":96,"./isA":97,"./isConvex":98,"./measureArea":99,"./measureBoundingBox":100,"./measureBoundingSphere":101,"./measureSignedVolume":102,"./plane":103,"./toPoints":104,"./toString":105,"./transform":106,"./validate":107}],96:[function(e,t,i){const s=e("../../maths/plane"),r=e("./create");t.exports=e=>{const t=e.vertices.slice().reverse(),i=r(t);return e.plane&&(i.plane=s.flip(s.create(),e.plane)),i}},{"../../maths/plane":178,"./create":92}],97:[function(e,t,i){t.exports=e=>!!(e&&"object"==typeof e&&"vertices"in e&&Array.isArray(e.vertices))},{}],98:[function(e,t,i){const s=e("../../maths/plane"),r=e("../../maths/vec3"),n=(e,t,i,s)=>{const n=r.cross(r.create(),r.subtract(r.create(),t,e),r.subtract(r.create(),i,t));return r.dot(n,s)>=0};t.exports=e=>(e=>{const t=e.length;if(t>2){const i=s.fromPoints(s.create(),...e);let r=e[t-2],o=e[t-1];for(let s=0;s{const t=e.vertices.length;if(t<3)return 0;const i=e.vertices,r=s(e),n=Math.abs(r[0]),o=Math.abs(r[1]),a=Math.abs(r[2]);if(n+o+a===0)return 0;let l=3;n>o&&n>a?l=1:o>a&&(l=2);let h=0,c=0,u=1,d=2;switch(l){case 1:for(u=1;u{const t=e.vertices,i=t.length,r=0===i?s.create():s.clone(t[0]),n=s.clone(r);for(let e=1;e{const t=r.get(e);if(t)return t;const i=e.vertices,n=s.create();if(0===i.length)return n[0]=0,n[1]=0,n[2]=0,n[3]=0,n;let o=i[0],a=o,l=o,h=o,c=o,u=o;i.forEach((e=>{o[0]>e[0]&&(o=e),a[1]>e[1]&&(a=e),l[2]>e[2]&&(l=e),h[0]{let t=0;const i=e.vertices,r=s.create();for(let e=0;e(e.plane||(e.plane=s.fromPoints(s.create(),...e.vertices)),e.plane)},{"../../maths/plane/":178}],104:[function(e,t,i){t.exports=e=>e.vertices},{}],105:[function(e,t,i){const s=e("../../maths/vec3/");t.exports=e=>{let t="poly3: vertices: [";return e.vertices.forEach((e=>{t+=`${s.toString(e)}, `})),t+="]",t}},{"../../maths/vec3/":237}],106:[function(e,t,i){const s=e("../../maths/mat4"),r=e("../../maths/vec3"),n=e("./create");t.exports=(e,t)=>{const i=t.vertices.map((t=>r.transform(r.create(),t,e)));return s.isMirroring(e)&&i.reverse(),n(i)}},{"../../maths/mat4":159,"../../maths/vec3":237,"./create":92}],107:[function(e,t,i){const s=e("../../maths/plane/signedDistanceToPoint"),{NEPS:r}=e("../../maths/constants"),n=e("../../maths/vec3"),o=e("./isA"),a=e("./isConvex"),l=e("./measureArea"),h=e("./plane");t.exports=e=>{if(!o(e))throw new Error("invalid poly3 structure");if(e.vertices.length<3)throw new Error(`poly3 not enough vertices ${e.vertices.length}`);if(l(e)<=0)throw new Error("poly3 area must be greater than zero");for(let t=0;t{if(!e.every(Number.isFinite))throw new Error(`poly3 invalid vertex ${e}`)})),e.vertices.length>3){const t=h(e);e.vertices.forEach((e=>{const i=Math.abs(s(t,e));if(i>r)throw new Error(`poly3 must be coplanar: vertex ${e} distance ${i}`)}))}}},{"../../maths/constants":110,"../../maths/plane/signedDistanceToPoint":180,"../../maths/vec3":237,"./isA":97,"./isConvex":98,"./measureArea":99,"./plane":103}],108:[function(e,t,i){t.exports={colors:e("./colors"),curves:e("./curves"),geometries:e("./geometries"),maths:e("./maths"),measurements:e("./measurements"),primitives:e("./primitives"),text:e("./text"),utils:e("./utils"),booleans:e("./operations/booleans"),expansions:e("./operations/expansions"),extrusions:e("./operations/extrusions"),hulls:e("./operations/hulls"),modifiers:e("./operations/modifiers"),transforms:e("./operations/transforms")}},{"./colors":25,"./curves":36,"./geometries":66,"./maths":111,"./measurements":267,"./operations/booleans":281,"./operations/expansions":310,"./operations/extrusions":333,"./operations/hulls":355,"./operations/modifiers":366,"./operations/transforms":376,"./primitives":392,"./text":406,"./utils":414}],109:[function(e,t,i){const s=e("./mat4"),r=e("./vec2"),n=e("./vec3"),o=function(e,t){arguments.length<2&&(t=n.orthogonal(n.create(),e)),this.v=n.normalize(n.create(),n.cross(n.create(),e,t)),this.u=n.cross(n.create(),this.v,e),this.plane=e,this.planeorigin=n.scale(n.create(),e,e[3])};o.GetCartesian=function(e,t){const i=e+"/"+t;let s,r;if("X/Y"===i)s=[0,0,1],r=[1,0,0];else if("Y/-X"===i)s=[0,0,1],r=[0,1,0];else if("-X/-Y"===i)s=[0,0,1],r=[-1,0,0];else if("-Y/X"===i)s=[0,0,1],r=[0,-1,0];else if("-X/Y"===i)s=[0,0,-1],r=[-1,0,0];else if("-Y/-X"===i)s=[0,0,-1],r=[0,-1,0];else if("X/-Y"===i)s=[0,0,-1],r=[1,0,0];else if("Y/X"===i)s=[0,0,-1],r=[0,1,0];else if("X/Z"===i)s=[0,-1,0],r=[1,0,0];else if("Z/-X"===i)s=[0,-1,0],r=[0,0,1];else if("-X/-Z"===i)s=[0,-1,0],r=[-1,0,0];else if("-Z/X"===i)s=[0,-1,0],r=[0,0,-1];else if("-X/Z"===i)s=[0,1,0],r=[-1,0,0];else if("-Z/-X"===i)s=[0,1,0],r=[0,0,-1];else if("X/-Z"===i)s=[0,1,0],r=[1,0,0];else if("Z/X"===i)s=[0,1,0],r=[0,0,1];else if("Y/Z"===i)s=[1,0,0],r=[0,1,0];else if("Z/-Y"===i)s=[1,0,0],r=[0,0,1];else if("-Y/-Z"===i)s=[1,0,0],r=[0,-1,0];else if("-Z/Y"===i)s=[1,0,0],r=[0,0,-1];else if("-Y/Z"===i)s=[-1,0,0],r=[0,-1,0];else if("-Z/-Y"===i)s=[-1,0,0],r=[0,0,-1];else if("Y/-Z"===i)s=[-1,0,0],r=[0,1,0];else{if("Z/Y"!==i)throw new Error("OrthoNormalBasis.GetCartesian: invalid combination of axis identifiers. Should pass two string arguments from [X,Y,Z,-X,-Y,-Z], being two different axes.");s=[-1,0,0],r=[0,0,1]}return new o(new Plane(new Vector3D(s),0),new Vector3D(r))},o.Z0Plane=function(){const e=new Plane(new Vector3D([0,0,1]),0);return new o(e,new Vector3D([1,0,0]))},o.prototype={getProjectionMatrix:function(){return s.fromValues(this.u[0],this.v[0],this.plane[0],0,this.u[1],this.v[1],this.plane[1],0,this.u[2],this.v[2],this.plane[2],0,0,0,-this.plane[3],1)},getInverseProjectionMatrix:function(){const e=n.scale(n.create(),this.plane,this.plane[3]);return s.fromValues(this.u[0],this.u[1],this.u[2],0,this.v[0],this.v[1],this.v[2],0,this.plane[0],this.plane[1],this.plane[2],0,e[0],e[1],e[2],1)},to2D:function(e){return r.fromValues(n.dot(e,this.u),n.dot(e,this.v))},to3D:function(e){const t=n.scale(n.create(),this.u,e[0]),i=n.scale(n.create(),this.v,e[1]),s=n.add(t,t,this.planeorigin);return n.add(i,i,s)},line3Dto2D:function(e){const t=e.point,i=e.direction.plus(t),s=this.to2D(t),r=this.to2D(i);return Line2D.fromPoints(s,r)},line2Dto3D:function(e){const t=e.origin(),i=e.direction().plus(t),s=this.to3D(t),r=this.to3D(i);return Line3D.fromPoints(s,r)},transform:function(e){const t=this.plane.transform(e),i=this.u.transform(e),s=new Vector3D(0,0,0).transform(e),r=i.minus(s);return new o(t,r)}},t.exports=o},{"./mat4":159,"./vec2":206,"./vec3":237}],110:[function(e,t,i){const s=2*Math.PI;t.exports={EPS:1e-5,NEPS:1e-13,TAU:s,spatialResolution:1e5}},{}],111:[function(e,t,i){t.exports={constants:e("./constants"),line2:e("./line2"),line3:e("./line3"),mat4:e("./mat4"),plane:e("./plane"),utils:e("./utils"),vec2:e("./vec2"),vec3:e("./vec3"),vec4:e("./vec4")}},{"./constants":110,"./line2":121,"./line3":138,"./mat4":159,"./plane":178,"./utils":184,"./vec2":206,"./vec3":237,"./vec4":263}],112:[function(e,t,i){const s=e("./create");t.exports=e=>{const t=s();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}},{"./create":115}],113:[function(e,t,i){const s=e("../vec2"),r=e("./direction"),n=e("./origin");t.exports=(e,t)=>{const i=n(e),o=r(e),a=s.subtract(s.create(),t,i),l=s.dot(a,o);return s.scale(a,o,l),s.add(a,a,i),a}},{"../vec2":206,"./direction":116,"./origin":123}],114:[function(e,t,i){t.exports=(e,t)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],e)},{}],115:[function(e,t,i){t.exports=()=>[0,1,0]},{}],116:[function(e,t,i){const s=e("../vec2");t.exports=e=>{const t=s.normal(s.create(),e);return s.negate(t,t),t}},{"../vec2":206}],117:[function(e,t,i){const s=e("../vec2");t.exports=(e,t)=>{let i=s.dot(t,e);return i=Math.abs(i-e[2]),i}},{"../vec2":206}],118:[function(e,t,i){t.exports=(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]},{}],119:[function(e,t,i){const s=e("../vec2");t.exports=(e,t,i)=>{const r=s.subtract(s.create(),i,t);s.normal(r,r),s.normalize(r,r);const n=s.dot(t,r);return e[0]=r[0],e[1]=r[1],e[2]=n,e}},{"../vec2":206}],120:[function(e,t,i){const s=e("./create");t.exports=(e,t,i)=>{const r=s();return r[0]=e,r[1]=t,r[2]=i,r}},{"./create":115}],121:[function(e,t,i){t.exports={clone:e("./clone"),closestPoint:e("./closestPoint"),copy:e("./copy"),create:e("./create"),direction:e("./direction"),distanceToPoint:e("./distanceToPoint"),equals:e("./equals"),fromPoints:e("./fromPoints"),fromValues:e("./fromValues"),intersectPointOfLines:e("./intersectPointOfLines"),origin:e("./origin"),reverse:e("./reverse"),toString:e("./toString"),transform:e("./transform"),xAtY:e("./xAtY")}},{"./clone":112,"./closestPoint":113,"./copy":114,"./create":115,"./direction":116,"./distanceToPoint":117,"./equals":118,"./fromPoints":119,"./fromValues":120,"./intersectPointOfLines":122,"./origin":123,"./reverse":124,"./toString":125,"./transform":126,"./xAtY":127}],122:[function(e,t,i){const s=e("../vec2"),{solve2Linear:r}=e("../utils");t.exports=(e,t)=>{const i=r(e[0],e[1],t[0],t[1],e[2],t[2]);return s.clone(i)}},{"../utils":184,"../vec2":206}],123:[function(e,t,i){const s=e("../vec2");t.exports=e=>s.scale(s.create(),e,e[2])},{"../vec2":206}],124:[function(e,t,i){const s=e("../vec2"),r=e("./copy"),n=e("./fromValues");t.exports=(e,t)=>{const i=s.negate(s.create(),t),o=-t[2];return r(e,n(i[0],i[1],o))}},{"../vec2":206,"./copy":114,"./fromValues":120}],125:[function(e,t,i){t.exports=e=>`line2: (${e[0].toFixed(7)}, ${e[1].toFixed(7)}, ${e[2].toFixed(7)})`},{}],126:[function(e,t,i){const s=e("../vec2"),r=e("./fromPoints"),n=e("./origin"),o=e("./direction");t.exports=(e,t,i)=>{const a=n(t),l=o(t);return s.transform(a,a,i),s.transform(l,l,i),r(e,a,l)}},{"../vec2":206,"./direction":116,"./fromPoints":119,"./origin":123}],127:[function(e,t,i){const s=e("./origin");t.exports=(e,t)=>{let i=(e[2]-e[1]*t)/e[0];return Number.isNaN(i)&&(i=s(e)[0]),i}},{"./origin":123}],128:[function(e,t,i){const s=e("../vec3"),r=e("./create");t.exports=e=>{const t=r();return s.copy(t[0],e[0]),s.copy(t[1],e[1]),t}},{"../vec3":237,"./create":131}],129:[function(e,t,i){const s=e("../vec3");t.exports=(e,t)=>{const i=e[0],r=e[1],n=s.dot(s.subtract(s.create(),t,i),r)/s.dot(r,r),o=s.scale(s.create(),r,n);return s.add(o,o,i),o}},{"../vec3":237}],130:[function(e,t,i){const s=e("../vec3");t.exports=(e,t)=>(s.copy(e[0],t[0]),s.copy(e[1],t[1]),e)},{"../vec3":237}],131:[function(e,t,i){const s=e("../vec3");t.exports=()=>[s.fromValues(0,0,0),s.fromValues(0,0,1)]},{"../vec3":237}],132:[function(e,t,i){t.exports=e=>e[1]},{}],133:[function(e,t,i){const s=e("../vec3"),r=e("./closestPoint");t.exports=(e,t)=>{const i=r(e,t),n=s.subtract(s.create(),t,i);return s.length(n)}},{"../vec3":237,"./closestPoint":129}],134:[function(e,t,i){const s=e("../vec3");t.exports=(e,t)=>!!s.equals(e[1],t[1])&&!!s.equals(e[0],t[0])},{"../vec3":237}],135:[function(e,t,i){const s=e("../vec3"),{solve2Linear:r}=e("../utils"),{EPS:n}=e("../constants"),o=e("./fromPointAndDirection");t.exports=(e,t,i)=>{let a=s.cross(s.create(),t,i),l=s.length(a);if(l=c&&h>=u?(p=r(t[1],t[2],i[1],i[2],t[3],i[3]),d=s.fromValues(0,p[0],p[1])):c>=h&&c>=u?(p=r(t[0],t[2],i[0],i[2],t[3],i[3]),d=s.fromValues(p[0],0,p[1])):(p=r(t[0],t[1],i[0],i[1],t[3],i[3]),d=s.fromValues(p[0],p[1],0)),o(e,d,a)}},{"../constants":110,"../utils":184,"../vec3":237,"./fromPointAndDirection":136}],136:[function(e,t,i){const s=e("../vec3");t.exports=(e,t,i)=>{const r=s.normalize(s.create(),i);return s.copy(e[0],t),s.copy(e[1],r),e}},{"../vec3":237}],137:[function(e,t,i){const s=e("../vec3"),r=e("./fromPointAndDirection");t.exports=(e,t,i)=>{const n=s.subtract(s.create(),i,t);return r(e,t,n)}},{"../vec3":237,"./fromPointAndDirection":136}],138:[function(e,t,i){t.exports={clone:e("./clone"),closestPoint:e("./closestPoint"),copy:e("./copy"),create:e("./create"),direction:e("./direction"),distanceToPoint:e("./distanceToPoint"),equals:e("./equals"),fromPlanes:e("./fromPlanes"),fromPointAndDirection:e("./fromPointAndDirection"),fromPoints:e("./fromPoints"),intersectPointOfLineAndPlane:e("./intersectPointOfLineAndPlane"),origin:e("./origin"),reverse:e("./reverse"),toString:e("./toString"),transform:e("./transform")}},{"./clone":128,"./closestPoint":129,"./copy":130,"./create":131,"./direction":132,"./distanceToPoint":133,"./equals":134,"./fromPlanes":135,"./fromPointAndDirection":136,"./fromPoints":137,"./intersectPointOfLineAndPlane":139,"./origin":140,"./reverse":141,"./toString":142,"./transform":143}],139:[function(e,t,i){const s=e("../vec3");t.exports=(e,t)=>{const i=t,r=t[3],n=e[0],o=e[1],a=(r-s.dot(i,n))/s.dot(i,o);return s.add(s.create(),n,s.scale(s.create(),o,a))}},{"../vec3":237}],140:[function(e,t,i){t.exports=e=>e[0]},{}],141:[function(e,t,i){const s=e("../vec3"),r=e("./fromPointAndDirection");t.exports=(e,t)=>{const i=s.clone(t[0]),n=s.negate(s.create(),t[1]);return r(e,i,n)}},{"../vec3":237,"./fromPointAndDirection":136}],142:[function(e,t,i){t.exports=e=>{const t=e[0],i=e[1];return`line3: point: (${t[0].toFixed(7)}, ${t[1].toFixed(7)}, ${t[2].toFixed(7)}) direction: (${i[0].toFixed(7)}, ${i[1].toFixed(7)}, ${i[2].toFixed(7)})`}},{}],143:[function(e,t,i){const s=e("../vec3"),r=e("./fromPointAndDirection");t.exports=(e,t,i)=>{const n=t[0],o=t[1],a=s.add(s.create(),n,o),l=s.transform(s.create(),n,i),h=s.transform(a,a,i),c=s.subtract(h,h,l);return r(e,l,c)}},{"../vec3":237,"./fromPointAndDirection":136}],144:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]+i[0],e[1]=t[1]+i[1],e[2]=t[2]+i[2],e[3]=t[3]+i[3],e[4]=t[4]+i[4],e[5]=t[5]+i[5],e[6]=t[6]+i[6],e[7]=t[7]+i[7],e[8]=t[8]+i[8],e[9]=t[9]+i[9],e[10]=t[10]+i[10],e[11]=t[11]+i[11],e[12]=t[12]+i[12],e[13]=t[13]+i[13],e[14]=t[14]+i[14],e[15]=t[15]+i[15],e)},{}],145:[function(e,t,i){const s=e("./create");t.exports=e=>{const t=s();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}},{"./create":147}],146:[function(e,t,i){t.exports=(e,t)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e)},{}],147:[function(e,t,i){t.exports=()=>[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]},{}],148:[function(e,t,i){t.exports=(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15]},{}],149:[function(e,t,i){const{EPS:s}=e("../constants"),{sin:r,cos:n}=e("../utils/trigonometry"),o=e("./identity");t.exports=(e,t,i)=>{let[a,l,h]=i;const c=a*a+l*l+h*h;if(Math.abs(c)(e[0]=t[0],e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=t[1],e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=t[2],e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e)},{}],151:[function(e,t,i){const{sin:s,cos:r}=e("../utils/trigonometry");t.exports=(e,t,i,n)=>{const o=s(t),a=r(t),l=s(i),h=r(i),c=s(n),u=r(n);return e[0]=h*a,e[1]=h*o,e[2]=-l,e[3]=0,e[4]=c*l*a-u*o,e[5]=u*a+c*l*o,e[6]=c*h,e[7]=0,e[8]=c*o+u*l*a,e[9]=u*l*o-c*a,e[10]=u*h,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}},{"../utils/trigonometry":188}],152:[function(e,t,i){t.exports=(e,t)=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=t[0],e[13]=t[1],e[14]=t[2],e[15]=1,e)},{}],153:[function(e,t,i){const s=e("./create");t.exports=(e,t,i,r,n,o,a,l,h,c,u,d,p,f,_,m)=>{const g=s();return g[0]=e,g[1]=t,g[2]=i,g[3]=r,g[4]=n,g[5]=o,g[6]=a,g[7]=l,g[8]=h,g[9]=c,g[10]=u,g[11]=d,g[12]=p,g[13]=f,g[14]=_,g[15]=m,g}},{"./create":147}],154:[function(e,t,i){const s=e("../vec3"),r=e("./fromRotation");t.exports=(e,t,i)=>{const n=s.normalize(s.create(),t),o=s.normalize(s.create(),i),a=s.cross(s.create(),o,n),l=s.dot(o,n);if(-1===l)return r(e,Math.PI,s.orthogonal(a,n));const h=1/(1+l);return e[0]=a[0]*a[0]*h+l,e[1]=a[1]*a[0]*h-a[2],e[2]=a[2]*a[0]*h+a[1],e[3]=0,e[4]=a[0]*a[1]*h+a[2],e[5]=a[1]*a[1]*h+l,e[6]=a[2]*a[1]*h-a[0],e[7]=0,e[8]=a[0]*a[2]*h-a[1],e[9]=a[1]*a[2]*h+a[0],e[10]=a[2]*a[2]*h+l,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}},{"../vec3":237,"./fromRotation":149}],155:[function(e,t,i){const{sin:s,cos:r}=e("../utils/trigonometry");t.exports=(e,t)=>{const i=s(t),n=r(t);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=n,e[6]=i,e[7]=0,e[8]=0,e[9]=-i,e[10]=n,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}},{"../utils/trigonometry":188}],156:[function(e,t,i){const{sin:s,cos:r}=e("../utils/trigonometry");t.exports=(e,t)=>{const i=s(t),n=r(t);return e[0]=n,e[1]=0,e[2]=-i,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=i,e[9]=0,e[10]=n,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}},{"../utils/trigonometry":188}],157:[function(e,t,i){const{sin:s,cos:r}=e("../utils/trigonometry");t.exports=(e,t)=>{const i=s(t),n=r(t);return e[0]=n,e[1]=i,e[2]=0,e[3]=0,e[4]=-i,e[5]=n,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}},{"../utils/trigonometry":188}],158:[function(e,t,i){t.exports=e=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e)},{}],159:[function(e,t,i){t.exports={add:e("./add"),clone:e("./clone"),copy:e("./copy"),create:e("./create"),invert:e("./invert"),equals:e("./equals"),fromRotation:e("./fromRotation"),fromScaling:e("./fromScaling"),fromTaitBryanRotation:e("./fromTaitBryanRotation"),fromTranslation:e("./fromTranslation"),fromValues:e("./fromValues"),fromVectorRotation:e("./fromVectorRotation"),fromXRotation:e("./fromXRotation"),fromYRotation:e("./fromYRotation"),fromZRotation:e("./fromZRotation"),identity:e("./identity"),isIdentity:e("./isIdentity"),isOnlyTransformScale:e("./isOnlyTransformScale"),isMirroring:e("./isMirroring"),mirrorByPlane:e("./mirrorByPlane"),multiply:e("./multiply"),rotate:e("./rotate"),rotateX:e("./rotateX"),rotateY:e("./rotateY"),rotateZ:e("./rotateZ"),scale:e("./scale"),subtract:e("./subtract"),toString:e("./toString"),translate:e("./translate")}},{"./add":144,"./clone":145,"./copy":146,"./create":147,"./equals":148,"./fromRotation":149,"./fromScaling":150,"./fromTaitBryanRotation":151,"./fromTranslation":152,"./fromValues":153,"./fromVectorRotation":154,"./fromXRotation":155,"./fromYRotation":156,"./fromZRotation":157,"./identity":158,"./invert":160,"./isIdentity":161,"./isMirroring":162,"./isOnlyTransformScale":163,"./mirrorByPlane":164,"./multiply":165,"./rotate":166,"./rotateX":167,"./rotateY":168,"./rotateZ":169,"./scale":170,"./subtract":171,"./toString":172,"./translate":173}],160:[function(e,t,i){t.exports=(e,t)=>{const i=t[0],s=t[1],r=t[2],n=t[3],o=t[4],a=t[5],l=t[6],h=t[7],c=t[8],u=t[9],d=t[10],p=t[11],f=t[12],_=t[13],m=t[14],g=t[15],v=i*a-s*o,x=i*l-r*o,T=i*h-n*o,S=s*l-r*a,E=s*h-n*a,b=r*h-n*l,C=c*_-u*f,y=c*m-d*f,A=c*g-p*f,R=u*m-d*_,I=u*g-p*_,P=d*g-p*m;let M=v*P-x*I+T*R+S*A-E*y+b*C;return M?(M=1/M,e[0]=(a*P-l*I+h*R)*M,e[1]=(r*I-s*P-n*R)*M,e[2]=(_*b-m*E+g*S)*M,e[3]=(d*E-u*b-p*S)*M,e[4]=(l*A-o*P-h*y)*M,e[5]=(i*P-r*A+n*y)*M,e[6]=(m*T-f*b-g*x)*M,e[7]=(c*b-d*T+p*x)*M,e[8]=(o*I-a*A+h*C)*M,e[9]=(s*A-i*I-n*C)*M,e[10]=(f*E-_*T+g*v)*M,e[11]=(u*T-c*E-p*v)*M,e[12]=(a*y-o*R-l*C)*M,e[13]=(i*R-s*y+r*C)*M,e[14]=(_*x-f*S-m*v)*M,e[15]=(c*S-u*x+d*v)*M,e):null}},{}],161:[function(e,t,i){t.exports=e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]},{}],162:[function(e,t,i){t.exports=e=>{const t=e[4]*e[9]-e[8]*e[5],i=e[8]*e[1]-e[0]*e[9],s=e[0]*e[5]-e[4]*e[1];return t*e[2]+i*e[6]+s*e[10]<0}},{}],163:[function(e,t,i){const s=e=>Math.abs(e)s(e[1])&&s(e[2])&&s(e[3])&&s(e[4])&&s(e[6])&&s(e[7])&&s(e[8])&&s(e[9])&&s(e[11])&&1===e[15]},{}],164:[function(e,t,i){t.exports=(e,t)=>{const[i,s,r,n]=t;return e[0]=1-2*i*i,e[1]=-2*s*i,e[2]=-2*r*i,e[3]=0,e[4]=-2*i*s,e[5]=1-2*s*s,e[6]=-2*r*s,e[7]=0,e[8]=-2*i*r,e[9]=-2*s*r,e[10]=1-2*r*r,e[11]=0,e[12]=2*i*n,e[13]=2*s*n,e[14]=2*r*n,e[15]=1,e}},{}],165:[function(e,t,i){t.exports=(e,t,i)=>{const s=t[0],r=t[1],n=t[2],o=t[3],a=t[4],l=t[5],h=t[6],c=t[7],u=t[8],d=t[9],p=t[10],f=t[11],_=t[12],m=t[13],g=t[14],v=t[15];let x=i[0],T=i[1],S=i[2],E=i[3];return e[0]=x*s+T*a+S*u+E*_,e[1]=x*r+T*l+S*d+E*m,e[2]=x*n+T*h+S*p+E*g,e[3]=x*o+T*c+S*f+E*v,x=i[4],T=i[5],S=i[6],E=i[7],e[4]=x*s+T*a+S*u+E*_,e[5]=x*r+T*l+S*d+E*m,e[6]=x*n+T*h+S*p+E*g,e[7]=x*o+T*c+S*f+E*v,x=i[8],T=i[9],S=i[10],E=i[11],e[8]=x*s+T*a+S*u+E*_,e[9]=x*r+T*l+S*d+E*m,e[10]=x*n+T*h+S*p+E*g,e[11]=x*o+T*c+S*f+E*v,x=i[12],T=i[13],S=i[14],E=i[15],e[12]=x*s+T*a+S*u+E*_,e[13]=x*r+T*l+S*d+E*m,e[14]=x*n+T*h+S*p+E*g,e[15]=x*o+T*c+S*f+E*v,e}},{}],166:[function(e,t,i){const{EPS:s}=e("../constants"),{sin:r,cos:n}=e("../utils/trigonometry"),o=e("./copy");t.exports=(e,t,i,a)=>{let[l,h,c]=a;const u=l*l+h*h+c*c;if(Math.abs(u){const n=s(i),o=r(i),a=t[4],l=t[5],h=t[6],c=t[7],u=t[8],d=t[9],p=t[10],f=t[11];return t!==e&&(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[4]=a*o+u*n,e[5]=l*o+d*n,e[6]=h*o+p*n,e[7]=c*o+f*n,e[8]=u*o-a*n,e[9]=d*o-l*n,e[10]=p*o-h*n,e[11]=f*o-c*n,e}},{"../utils/trigonometry":188}],168:[function(e,t,i){const{sin:s,cos:r}=e("../utils/trigonometry");t.exports=(e,t,i)=>{const n=s(i),o=r(i),a=t[0],l=t[1],h=t[2],c=t[3],u=t[8],d=t[9],p=t[10],f=t[11];return t!==e&&(e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=a*o-u*n,e[1]=l*o-d*n,e[2]=h*o-p*n,e[3]=c*o-f*n,e[8]=a*n+u*o,e[9]=l*n+d*o,e[10]=h*n+p*o,e[11]=c*n+f*o,e}},{"../utils/trigonometry":188}],169:[function(e,t,i){const{sin:s,cos:r}=e("../utils/trigonometry");t.exports=(e,t,i)=>{const n=s(i),o=r(i),a=t[0],l=t[1],h=t[2],c=t[3],u=t[4],d=t[5],p=t[6],f=t[7];return t!==e&&(e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15]),e[0]=a*o+u*n,e[1]=l*o+d*n,e[2]=h*o+p*n,e[3]=c*o+f*n,e[4]=u*o-a*n,e[5]=d*o-l*n,e[6]=p*o-h*n,e[7]=f*o-c*n,e}},{"../utils/trigonometry":188}],170:[function(e,t,i){t.exports=(e,t,i)=>{const s=i[0],r=i[1],n=i[2];return e[0]=t[0]*s,e[1]=t[1]*s,e[2]=t[2]*s,e[3]=t[3]*s,e[4]=t[4]*r,e[5]=t[5]*r,e[6]=t[6]*r,e[7]=t[7]*r,e[8]=t[8]*n,e[9]=t[9]*n,e[10]=t[10]*n,e[11]=t[11]*n,e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}},{}],171:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]-i[0],e[1]=t[1]-i[1],e[2]=t[2]-i[2],e[3]=t[3]-i[3],e[4]=t[4]-i[4],e[5]=t[5]-i[5],e[6]=t[6]-i[6],e[7]=t[7]-i[7],e[8]=t[8]-i[8],e[9]=t[9]-i[9],e[10]=t[10]-i[10],e[11]=t[11]-i[11],e[12]=t[12]-i[12],e[13]=t[13]-i[13],e[14]=t[14]-i[14],e[15]=t[15]-i[15],e)},{}],172:[function(e,t,i){t.exports=e=>e.map((e=>e.toFixed(7))).toString()},{}],173:[function(e,t,i){t.exports=(e,t,i)=>{const s=i[0],r=i[1],n=i[2];let o,a,l,h,c,u,d,p,f,_,m,g;return t===e?(e[12]=t[0]*s+t[4]*r+t[8]*n+t[12],e[13]=t[1]*s+t[5]*r+t[9]*n+t[13],e[14]=t[2]*s+t[6]*r+t[10]*n+t[14],e[15]=t[3]*s+t[7]*r+t[11]*n+t[15]):(o=t[0],a=t[1],l=t[2],h=t[3],c=t[4],u=t[5],d=t[6],p=t[7],f=t[8],_=t[9],m=t[10],g=t[11],e[0]=o,e[1]=a,e[2]=l,e[3]=h,e[4]=c,e[5]=u,e[6]=d,e[7]=p,e[8]=f,e[9]=_,e[10]=m,e[11]=g,e[12]=o*s+c*r+f*n+t[12],e[13]=a*s+u*r+_*n+t[13],e[14]=l*s+d*r+m*n+t[14],e[15]=h*s+p*r+g*n+t[15]),e}},{}],174:[function(e,t,i){t.exports=(e,t)=>(e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e[3]=-t[3],e)},{}],175:[function(e,t,i){const s=e("../vec3");t.exports=(e,t,i)=>{const r=s.normalize(s.create(),t),n=s.dot(i,r);return e[0]=r[0],e[1]=r[1],e[2]=r[2],e[3]=n,e}},{"../vec3":237}],176:[function(e,t,i){const s=e("../vec3");t.exports=(e,...t)=>{const i=t.length,r=s.create(),n=s.create(),o=e=>{const o=t[e],a=t[(e+1)%i],l=t[(e+2)%i];return s.subtract(r,a,o),s.subtract(n,l,o),s.cross(r,r,n),s.normalize(r,r),r};return e[0]=0,e[1]=0,e[2]=0,3===i?s.copy(e,o(0)):(t.forEach(((t,i)=>{s.add(e,e,o(i))})),s.normalize(e,e)),e[3]=s.dot(e,t[0]),e}},{"../vec3":237}],177:[function(e,t,i){const{EPS:s}=e("../constants"),r=e("../vec3");t.exports=(e,t,i,n)=>{let o=r.subtract(r.create(),i,t),a=r.subtract(r.create(),n,t);r.length(o){const i=t[0]*e[0]+t[1]*e[1]+t[2]*e[2]-e[3],r=t[0]-i*e[0],n=t[1]-i*e[1],o=t[2]-i*e[2];return s.fromValues(r,n,o)}},{"../vec3":237}],180:[function(e,t,i){const s=e("../vec3");t.exports=(e,t)=>s.dot(e,t)-e[3]},{"../vec3":237}],181:[function(e,t,i){const s=e("../mat4"),r=e("../vec3"),n=e("./fromPoints"),o=e("./flip");t.exports=(e,t,i)=>{const a=s.isMirroring(i),l=r.orthogonal(r.create(),t),h=r.cross(l,t,l),c=r.cross(r.create(),t,h);let u=r.fromScalar(r.create(),t[3]);r.multiply(u,u,t);let d=r.add(r.create(),u,h),p=r.add(r.create(),u,c);return u=r.transform(u,u,i),d=r.transform(d,d,i),p=r.transform(p,p,i),n(e,u,d,p),a&&o(e,e),e}},{"../mat4":159,"../vec3":237,"./flip":174,"./fromPoints":176}],182:[function(e,t,i){const{NEPS:s}=e("../constants");t.exports=(e,t)=>Math.abs(e[0]-t[0])<=s&&Math.abs(e[1]-t[1])<=s&&Math.abs(e[2]-t[2])<=s},{"../constants":110}],183:[function(e,t,i){t.exports=e=>{let t=0;for(let i=0;i{let s,r=i-e[1],n=t[1]-e[1];return n<0&&(r=-r,n=-n),s=r<=0?0:r>=n?1:n<1e-10?.5:r/n,e[0]+s*(t[0]-e[0])}},{}],186:[function(e,t,i){t.exports=(e,t,i,s)=>{if(e[0]===t[0]&&e[1]===t[1]||i[0]===s[0]&&i[1]===s[1])return;const r=(s[1]-i[1])*(t[0]-e[0])-(s[0]-i[0])*(t[1]-e[1]);if(Math.abs(r)1||o<0||o>1?void 0:[e[0]+n*(t[0]-e[0]),e[1]+n*(t[1]-e[1])]}},{}],187:[function(e,t,i){t.exports=(e,t,i,s,r,n)=>{const o=1/(e*s-t*i);let a=r*s-t*n,l=-r*i+e*n;return a*=o,l*=o,[a,l]}},{}],188:[function(e,t,i){const{NEPS:s}=e("../constants"),r=e=>Math.abs(e)r(Math.sin(e)),cos:e=>r(Math.cos(e))}},{"../constants":110}],189:[function(e,t,i){t.exports=(e,t)=>(e[0]=Math.abs(t[0]),e[1]=Math.abs(t[1]),e)},{}],190:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]+i[0],e[1]=t[1]+i[1],e)},{}],191:[function(e,t,i){t.exports=e("./angleRadians")},{"./angleRadians":193}],192:[function(e,t,i){const s=e("./angleRadians");t.exports=e=>57.29577951308232*s(e)},{"./angleRadians":193}],193:[function(e,t,i){t.exports=e=>Math.atan2(e[1],e[0])},{}],194:[function(e,t,i){const s=e("./create");t.exports=e=>{const t=s();return t[0]=e[0],t[1]=e[1],t}},{"./create":196}],195:[function(e,t,i){t.exports=(e,t)=>(e[0]=t[0],e[1]=t[1],e)},{}],196:[function(e,t,i){t.exports=()=>[0,0]},{}],197:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=0,e[1]=0,e[2]=t[0]*i[1]-t[1]*i[0],e)},{}],198:[function(e,t,i){t.exports=(e,t)=>{const i=t[0]-e[0],s=t[1]-e[1];return Math.sqrt(i*i+s*s)}},{}],199:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]/i[0],e[1]=t[1]/i[1],e)},{}],200:[function(e,t,i){t.exports=(e,t)=>e[0]*t[0]+e[1]*t[1]},{}],201:[function(e,t,i){t.exports=(e,t)=>e[0]===t[0]&&e[1]===t[1]},{}],202:[function(e,t,i){const s=e("./fromAngleRadians");t.exports=(e,t)=>s(e,.017453292519943295*t)},{"./fromAngleRadians":203}],203:[function(e,t,i){const{sin:s,cos:r}=e("../utils/trigonometry");t.exports=(e,t)=>(e[0]=r(t),e[1]=s(t),e)},{"../utils/trigonometry":188}],204:[function(e,t,i){t.exports=(e,t)=>(e[0]=t,e[1]=t,e)},{}],205:[function(e,t,i){const s=e("./create");t.exports=(e,t)=>{const i=s();return i[0]=e,i[1]=t,i}},{"./create":196}],206:[function(e,t,i){t.exports={abs:e("./abs"),add:e("./add"),angle:e("./angle"),angleDegrees:e("./angleDegrees"),angleRadians:e("./angleRadians"),clone:e("./clone"),copy:e("./copy"),create:e("./create"),cross:e("./cross"),distance:e("./distance"),divide:e("./divide"),dot:e("./dot"),equals:e("./equals"),fromAngleDegrees:e("./fromAngleDegrees"),fromAngleRadians:e("./fromAngleRadians"),fromScalar:e("./fromScalar"),fromValues:e("./fromValues"),length:e("./length"),lerp:e("./lerp"),max:e("./max"),min:e("./min"),multiply:e("./multiply"),negate:e("./negate"),normal:e("./normal"),normalize:e("./normalize"),rotate:e("./rotate"),scale:e("./scale"),snap:e("./snap"),squaredDistance:e("./squaredDistance"),squaredLength:e("./squaredLength"),subtract:e("./subtract"),toString:e("./toString"),transform:e("./transform")}},{"./abs":189,"./add":190,"./angle":191,"./angleDegrees":192,"./angleRadians":193,"./clone":194,"./copy":195,"./create":196,"./cross":197,"./distance":198,"./divide":199,"./dot":200,"./equals":201,"./fromAngleDegrees":202,"./fromAngleRadians":203,"./fromScalar":204,"./fromValues":205,"./length":207,"./lerp":208,"./max":209,"./min":210,"./multiply":211,"./negate":212,"./normal":213,"./normalize":214,"./rotate":215,"./scale":216,"./snap":217,"./squaredDistance":218,"./squaredLength":219,"./subtract":220,"./toString":221,"./transform":222}],207:[function(e,t,i){t.exports=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1])},{}],208:[function(e,t,i){t.exports=(e,t,i,s)=>{const r=t[0],n=t[1];return e[0]=r+s*(i[0]-r),e[1]=n+s*(i[1]-n),e}},{}],209:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=Math.max(t[0],i[0]),e[1]=Math.max(t[1],i[1]),e)},{}],210:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=Math.min(t[0],i[0]),e[1]=Math.min(t[1],i[1]),e)},{}],211:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]*i[0],e[1]=t[1]*i[1],e)},{}],212:[function(e,t,i){t.exports=(e,t)=>(e[0]=-t[0],e[1]=-t[1],e)},{}],213:[function(e,t,i){const{TAU:s}=e("../constants"),r=e("./create"),n=e("./rotate");t.exports=(e,t)=>n(e,t,r(),s/4)},{"../constants":110,"./create":196,"./rotate":215}],214:[function(e,t,i){t.exports=(e,t)=>{const i=t[0],s=t[1];let r=i*i+s*s;return r>0&&(r=1/Math.sqrt(r)),e[0]=i*r,e[1]=s*r,e}},{}],215:[function(e,t,i){t.exports=(e,t,i,s)=>{const r=t[0]-i[0],n=t[1]-i[1],o=Math.cos(s),a=Math.sin(s);return e[0]=r*o-n*a+i[0],e[1]=r*a+n*o+i[1],e}},{}],216:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]*i,e[1]=t[1]*i,e)},{}],217:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=Math.round(t[0]/i)*i+0,e[1]=Math.round(t[1]/i)*i+0,e)},{}],218:[function(e,t,i){t.exports=(e,t)=>{const i=t[0]-e[0],s=t[1]-e[1];return i*i+s*s}},{}],219:[function(e,t,i){t.exports=e=>{const t=e[0],i=e[1];return t*t+i*i}},{}],220:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]-i[0],e[1]=t[1]-i[1],e)},{}],221:[function(e,t,i){t.exports=e=>`[${e[0].toFixed(7)}, ${e[1].toFixed(7)}]`},{}],222:[function(e,t,i){t.exports=(e,t,i)=>{const s=t[0],r=t[1];return e[0]=i[0]*s+i[4]*r+i[12],e[1]=i[1]*s+i[5]*r+i[13],e}},{}],223:[function(e,t,i){t.exports=(e,t)=>(e[0]=Math.abs(t[0]),e[1]=Math.abs(t[1]),e[2]=Math.abs(t[2]),e)},{}],224:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]+i[0],e[1]=t[1]+i[1],e[2]=t[2]+i[2],e)},{}],225:[function(e,t,i){const s=e("./dot");t.exports=(e,t)=>{const i=e[0],r=e[1],n=e[2],o=t[0],a=t[1],l=t[2],h=Math.sqrt(i*i+r*r+n*n)*Math.sqrt(o*o+a*a+l*l),c=h&&s(e,t)/h;return Math.acos(Math.min(Math.max(c,-1),1))}},{"./dot":232}],226:[function(e,t,i){const s=e("./create");t.exports=e=>{const t=s();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}},{"./create":228}],227:[function(e,t,i){t.exports=(e,t)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],e)},{}],228:[function(e,t,i){t.exports=()=>[0,0,0]},{}],229:[function(e,t,i){t.exports=(e,t,i)=>{const s=t[0],r=t[1],n=t[2],o=i[0],a=i[1],l=i[2];return e[0]=r*l-n*a,e[1]=n*o-s*l,e[2]=s*a-r*o,e}},{}],230:[function(e,t,i){t.exports=(e,t)=>{const i=t[0]-e[0],s=t[1]-e[1],r=t[2]-e[2];return Math.sqrt(i*i+s*s+r*r)}},{}],231:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]/i[0],e[1]=t[1]/i[1],e[2]=t[2]/i[2],e)},{}],232:[function(e,t,i){t.exports=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]},{}],233:[function(e,t,i){t.exports=(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]},{}],234:[function(e,t,i){t.exports=(e,t)=>(e[0]=t,e[1]=t,e[2]=t,e)},{}],235:[function(e,t,i){const s=e("./create");t.exports=(e,t,i)=>{const r=s();return r[0]=e,r[1]=t,r[2]=i,r}},{"./create":228}],236:[function(e,t,i){t.exports=(e,t,i=0)=>(e[0]=t[0],e[1]=t[1],e[2]=i,e)},{}],237:[function(e,t,i){t.exports={abs:e("./abs"),add:e("./add"),angle:e("./angle"),clone:e("./clone"),copy:e("./copy"),create:e("./create"),cross:e("./cross"),distance:e("./distance"),divide:e("./divide"),dot:e("./dot"),equals:e("./equals"),fromScalar:e("./fromScalar"),fromValues:e("./fromValues"),fromVec2:e("./fromVec2"),length:e("./length"),lerp:e("./lerp"),max:e("./max"),min:e("./min"),multiply:e("./multiply"),negate:e("./negate"),normalize:e("./normalize"),orthogonal:e("./orthogonal"),rotateX:e("./rotateX"),rotateY:e("./rotateY"),rotateZ:e("./rotateZ"),scale:e("./scale"),snap:e("./snap"),squaredDistance:e("./squaredDistance"),squaredLength:e("./squaredLength"),subtract:e("./subtract"),toString:e("./toString"),transform:e("./transform")}},{"./abs":223,"./add":224,"./angle":225,"./clone":226,"./copy":227,"./create":228,"./cross":229,"./distance":230,"./divide":231,"./dot":232,"./equals":233,"./fromScalar":234,"./fromValues":235,"./fromVec2":236,"./length":238,"./lerp":239,"./max":240,"./min":241,"./multiply":242,"./negate":243,"./normalize":244,"./orthogonal":245,"./rotateX":246,"./rotateY":247,"./rotateZ":248,"./scale":249,"./snap":250,"./squaredDistance":251,"./squaredLength":252,"./subtract":253,"./toString":254,"./transform":255}],238:[function(e,t,i){t.exports=e=>{const t=e[0],i=e[1],s=e[2];return Math.sqrt(t*t+i*i+s*s)}},{}],239:[function(e,t,i){t.exports=(e,t,i,s)=>(e[0]=t[0]+s*(i[0]-t[0]),e[1]=t[1]+s*(i[1]-t[1]),e[2]=t[2]+s*(i[2]-t[2]),e)},{}],240:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=Math.max(t[0],i[0]),e[1]=Math.max(t[1],i[1]),e[2]=Math.max(t[2],i[2]),e)},{}],241:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=Math.min(t[0],i[0]),e[1]=Math.min(t[1],i[1]),e[2]=Math.min(t[2],i[2]),e)},{}],242:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]*i[0],e[1]=t[1]*i[1],e[2]=t[2]*i[2],e)},{}],243:[function(e,t,i){t.exports=(e,t)=>(e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e)},{}],244:[function(e,t,i){t.exports=(e,t)=>{const i=t[0],s=t[1],r=t[2];let n=i*i+s*s+r*r;return n>0&&(n=1/Math.sqrt(n)),e[0]=i*n,e[1]=s*n,e[2]=r*n,e}},{}],245:[function(e,t,i){const s=e("./abs"),r=e("./create"),n=e("./cross");t.exports=(e,t)=>{const i=s(r(),t),o=0+(i[0]{const r=[],n=[];return r[0]=t[0]-i[0],r[1]=t[1]-i[1],r[2]=t[2]-i[2],n[0]=r[0],n[1]=r[1]*Math.cos(s)-r[2]*Math.sin(s),n[2]=r[1]*Math.sin(s)+r[2]*Math.cos(s),e[0]=n[0]+i[0],e[1]=n[1]+i[1],e[2]=n[2]+i[2],e}},{}],247:[function(e,t,i){t.exports=(e,t,i,s)=>{const r=[],n=[];return r[0]=t[0]-i[0],r[1]=t[1]-i[1],r[2]=t[2]-i[2],n[0]=r[2]*Math.sin(s)+r[0]*Math.cos(s),n[1]=r[1],n[2]=r[2]*Math.cos(s)-r[0]*Math.sin(s),e[0]=n[0]+i[0],e[1]=n[1]+i[1],e[2]=n[2]+i[2],e}},{}],248:[function(e,t,i){t.exports=(e,t,i,s)=>{const r=[],n=[];return r[0]=t[0]-i[0],r[1]=t[1]-i[1],n[0]=r[0]*Math.cos(s)-r[1]*Math.sin(s),n[1]=r[0]*Math.sin(s)+r[1]*Math.cos(s),e[0]=n[0]+i[0],e[1]=n[1]+i[1],e[2]=t[2],e}},{}],249:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]*i,e[1]=t[1]*i,e[2]=t[2]*i,e)},{}],250:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=Math.round(t[0]/i)*i+0,e[1]=Math.round(t[1]/i)*i+0,e[2]=Math.round(t[2]/i)*i+0,e)},{}],251:[function(e,t,i){t.exports=(e,t)=>{const i=t[0]-e[0],s=t[1]-e[1],r=t[2]-e[2];return i*i+s*s+r*r}},{}],252:[function(e,t,i){t.exports=e=>{const t=e[0],i=e[1],s=e[2];return t*t+i*i+s*s}},{}],253:[function(e,t,i){t.exports=(e,t,i)=>(e[0]=t[0]-i[0],e[1]=t[1]-i[1],e[2]=t[2]-i[2],e)},{}],254:[function(e,t,i){t.exports=e=>`[${e[0].toFixed(7)}, ${e[1].toFixed(7)}, ${e[2].toFixed(7)}]`},{}],255:[function(e,t,i){t.exports=(e,t,i)=>{const s=t[0],r=t[1],n=t[2];let o=i[3]*s+i[7]*r+i[11]*n+i[15];return o=o||1,e[0]=(i[0]*s+i[4]*r+i[8]*n+i[12])/o,e[1]=(i[1]*s+i[5]*r+i[9]*n+i[13])/o,e[2]=(i[2]*s+i[6]*r+i[10]*n+i[14])/o,e}},{}],256:[function(e,t,i){const s=e("./create");t.exports=e=>{const t=s();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}},{"./create":258}],257:[function(e,t,i){t.exports=(e,t)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e)},{}],258:[function(e,t,i){t.exports=()=>[0,0,0,0]},{}],259:[function(e,t,i){t.exports=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]},{}],260:[function(e,t,i){t.exports=(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]},{}],261:[function(e,t,i){t.exports=(e,t)=>(e[0]=t,e[1]=t,e[2]=t,e[3]=t,e)},{}],262:[function(e,t,i){const s=e("./create");t.exports=(e,t,i,r)=>{const n=s();return n[0]=e,n[1]=t,n[2]=i,n[3]=r,n}},{"./create":258}],263:[function(e,t,i){t.exports={clone:e("./clone"),copy:e("./copy"),create:e("./create"),dot:e("./dot"),equals:e("./equals"),fromScalar:e("./fromScalar"),fromValues:e("./fromValues"),toString:e("./toString"),transform:e("./transform")}},{"./clone":256,"./copy":257,"./create":258,"./dot":259,"./equals":260,"./fromScalar":261,"./fromValues":262,"./toString":264,"./transform":265}],264:[function(e,t,i){t.exports=e=>`(${e[0].toFixed(9)}, ${e[1].toFixed(9)}, ${e[2].toFixed(9)}, ${e[3].toFixed(9)})`},{}],265:[function(e,t,i){t.exports=(e,t,i)=>{const[s,r,n,o]=t;return e[0]=i[0]*s+i[4]*r+i[8]*n+i[12]*o,e[1]=i[1]*s+i[5]*r+i[9]*n+i[13]*o,e[2]=i[2]*s+i[6]*r+i[10]*n+i[14]*o,e[3]=i[3]*s+i[7]*r+i[11]*n+i[15]*o,e}},{}],266:[function(e,t,i){const{EPS:s}=e("../maths/constants");t.exports=(e,t)=>{let i=0;for(let s=0;s{if(0===(e=s(e)).length)throw new Error("measureAggregateArea: no geometries supplied");const t=r(e);return 1===e.length?t:t.reduce(((e,t)=>e+t),0)}},{"../utils/flatten":412,"./measureArea":272}],269:[function(e,t,i){const s=e("../utils/flatten"),r=e("../maths/vec3/min"),n=e("../maths/vec3/max"),o=e("./measureBoundingBox");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("measureAggregateBoundingBox: no geometries supplied");const t=o(e);if(1===e.length)return t;const i=[[Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE],[-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE]];return t.reduce(((e,t)=>[r(e[0],e[0],t[0]),n(e[1],e[1],t[1])]),i)}},{"../maths/vec3/max":240,"../maths/vec3/min":241,"../utils/flatten":412,"./measureBoundingBox":273}],270:[function(e,t,i){const s=e("../utils/flatten"),r=e("./measureAggregateBoundingBox"),n=e("./calculateEpsilonFromBounds"),{geom2:o,geom3:a,path2:l}=e("../geometries");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("measureAggregateEpsilon: no geometries supplied");const t=r(e);let i=0;return i=e.reduce(((e,t)=>l.isA(t)||o.isA(t)?Math.max(e,2):a.isA(t)?Math.max(e,3):0),i),n(t,i)}},{"../geometries":66,"../utils/flatten":412,"./calculateEpsilonFromBounds":266,"./measureAggregateBoundingBox":269}],271:[function(e,t,i){const s=e("../utils/flatten"),r=e("./measureVolume");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("measureAggregateVolume: no geometries supplied");const t=r(e);return 1===e.length?t:t.reduce(((e,t)=>e+t),0)}},{"../utils/flatten":412,"./measureVolume":279}],272:[function(e,t,i){const s=e("../utils/flatten"),r=e("../geometries/geom2"),n=e("../geometries/geom3"),o=e("../geometries/path2"),a=e("../geometries/poly3"),l=new WeakMap;t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>o.isA(e)?0:r.isA(e)?(e=>{let t=l.get(e);return t||(t=r.toSides(e).reduce(((e,t)=>e+(t[0][0]*t[1][1]-t[0][1]*t[1][0])),0),t*=.5,l.set(e,t),t)})(e):n.isA(e)?(e=>{let t=l.get(e);return t||(t=n.toPolygons(e).reduce(((e,t)=>e+a.measureArea(t)),0),l.set(e,t),t)})(e):0));return 1===t.length?t[0]:t}},{"../geometries/geom2":42,"../geometries/geom3":57,"../geometries/path2":78,"../geometries/poly3":95,"../utils/flatten":412}],273:[function(e,t,i){const s=e("../utils/flatten"),r=e("../maths/vec2"),n=e("../maths/vec3"),o=e("../geometries/geom2"),a=e("../geometries/geom3"),l=e("../geometries/path2"),h=e("../geometries/poly3"),c=new WeakMap;t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>l.isA(e)?(e=>{let t=c.get(e);if(t)return t;const i=l.toPoints(e);let s;s=0===i.length?r.create():r.clone(i[0]);let n=r.clone(s);return i.forEach((e=>{r.min(s,s,e),r.max(n,n,e)})),s=[s[0],s[1],0],n=[n[0],n[1],0],t=[s,n],c.set(e,t),t})(e):o.isA(e)?(e=>{let t=c.get(e);if(t)return t;const i=o.toPoints(e);let s;s=0===i.length?r.create():r.clone(i[0]);let n=r.clone(s);return i.forEach((e=>{r.min(s,s,e),r.max(n,n,e)})),s=[s[0],s[1],0],n=[n[0],n[1],0],t=[s,n],c.set(e,t),t})(e):a.isA(e)?(e=>{let t=c.get(e);if(t)return t;const i=a.toPolygons(e);let s=n.create();if(i.length>0){const e=h.toPoints(i[0]);n.copy(s,e[0])}let r=n.clone(s);return i.forEach((e=>{h.toPoints(e).forEach((e=>{n.min(s,s,e),n.max(r,r,e)}))})),s=[s[0],s[1],s[2]],r=[r[0],r[1],r[2]],t=[s,r],c.set(e,t),t})(e):[[0,0,0],[0,0,0]]));return 1===t.length?t[0]:t}},{"../geometries/geom2":42,"../geometries/geom3":57,"../geometries/path2":78,"../geometries/poly3":95,"../maths/vec2":206,"../maths/vec3":237,"../utils/flatten":412}],274:[function(e,t,i){const s=e("../utils/flatten"),r=e("../maths/vec2"),n=e("../maths/vec3"),o=e("../geometries/geom2"),a=e("../geometries/geom3"),l=e("../geometries/path2"),h=e("../geometries/poly3"),c=new WeakMap;t.exports=(...e)=>{const t=(e=s(e)).map((e=>l.isA(e)?(e=>{let t=c.get(e);if(void 0!==t)return t;const i=n.create();let s=0;const o=l.toPoints(e);if(o.length>0){let e=0;const t=n.create();o.forEach((s=>{n.add(i,i,n.fromVec2(t,s,0)),e++})),n.scale(i,i,1/e),o.forEach((e=>{s=Math.max(s,r.squaredDistance(i,e))})),s=Math.sqrt(s)}return t=[i,s],c.set(e,t),t})(e):o.isA(e)?(e=>{let t=c.get(e);if(void 0!==t)return t;const i=n.create();let s=0;const a=o.toSides(e);if(a.length>0){let e=0;const t=n.create();a.forEach((s=>{n.add(i,i,n.fromVec2(t,s[0],0)),e++})),n.scale(i,i,1/e),a.forEach((e=>{s=Math.max(s,r.squaredDistance(i,e[0]))})),s=Math.sqrt(s)}return t=[i,s],c.set(e,t),t})(e):a.isA(e)?(e=>{let t=c.get(e);if(void 0!==t)return t;const i=n.create();let s=0;const r=a.toPolygons(e);if(r.length>0){let e=0;r.forEach((t=>{h.toPoints(t).forEach((t=>{n.add(i,i,t),e++}))})),n.scale(i,i,1/e),r.forEach((e=>{h.toPoints(e).forEach((e=>{s=Math.max(s,n.squaredDistance(i,e))}))})),s=Math.sqrt(s)}return t=[i,s],c.set(e,t),t})(e):[[0,0,0],0]));return 1===t.length?t[0]:t}},{"../geometries/geom2":42,"../geometries/geom3":57,"../geometries/path2":78,"../geometries/poly3":95,"../maths/vec2":206,"../maths/vec3":237,"../utils/flatten":412}],275:[function(e,t,i){const s=e("../utils/flatten"),r=e("./measureBoundingBox");t.exports=(...e)=>{const t=(e=s(e)).map((e=>{const t=r(e);return[t[0][0]+(t[1][0]-t[0][0])/2,t[0][1]+(t[1][1]-t[0][1])/2,t[0][2]+(t[1][2]-t[0][2])/2]}));return 1===t.length?t[0]:t}},{"../utils/flatten":412,"./measureBoundingBox":273}],276:[function(e,t,i){const s=e("../utils/flatten"),r=e("../maths/vec3"),n=e("../geometries/geom2"),o=e("../geometries/geom3"),a=new WeakMap;t.exports=(...e)=>{const t=(e=s(e)).map((e=>n.isA(e)?(e=>{let t=a.get(e);if(void 0!==t)return t;const i=n.toSides(e);let s=0,o=0,l=0;if(i.length>0){for(let e=0;e{let t=a.get(e);if(void 0!==t)return t;t=r.create();const i=o.toPolygons(e);if(0===i.length)return t;let s=0;const n=r.create();return i.forEach((e=>{const i=e.vertices;for(let e=0;e{const t=(e=s(e)).map((e=>{const t=r(e);return[t[1][0]-t[0][0],t[1][1]-t[0][1],t[1][2]-t[0][2]]}));return 1===t.length?t[0]:t}},{"../utils/flatten":412,"./measureBoundingBox":273}],278:[function(e,t,i){const s=e("../utils/flatten"),{geom2:r,geom3:n,path2:o}=e("../geometries"),a=e("./calculateEpsilonFromBounds"),l=e("./measureBoundingBox");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>o.isA(e)||r.isA(e)?(e=>a(l(e),2))(e):n.isA(e)?(e=>a(l(e),3))(e):0));return 1===t.length?t[0]:t}},{"../geometries":66,"../utils/flatten":412,"./calculateEpsilonFromBounds":266,"./measureBoundingBox":273}],279:[function(e,t,i){const s=e("../utils/flatten"),r=e("../geometries/geom2"),n=e("../geometries/geom3"),o=e("../geometries/path2"),a=e("../geometries/poly3"),l=new WeakMap;t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>o.isA(e)||r.isA(e)?0:n.isA(e)?(e=>{let t=l.get(e);return t||(t=n.toPolygons(e).reduce(((e,t)=>e+a.measureSignedVolume(t)),0),l.set(e,t),t)})(e):0));return 1===t.length?t[0]:t}},{"../geometries/geom2":42,"../geometries/geom3":57,"../geometries/path2":78,"../geometries/poly3":95,"../utils/flatten":412}],280:[function(e,t,i){const s=e("../../maths/vec2"),r=e("../../geometries/geom2");t.exports=(e,t)=>{const i=t.map((t=>((e,t)=>{if(t.vertices.length<4)return null;const i=[],r=t.vertices.filter(((e,t)=>e[2]>0&&(i.push(t),!0)));if(2!==r.length)throw new Error("Assertion failed: fromFakePolygon: not enough points found");const n=r.map((t=>{const i=Math.round(t[0]/e)*e+0,r=Math.round(t[1]/e)*e+0;return s.fromValues(i,r)}));if(s.equals(n[0],n[1]))return null;const o=i[1]-i[0];if(1!==o&&3!==o)throw new Error("Assertion failed: fromFakePolygon: unknown index ordering");return 1===o&&n.reverse(),n})(e,t))).filter((e=>null!==e));return r.create(i)}},{"../../geometries/geom2":42,"../../maths/vec2":206}],281:[function(e,t,i){t.exports={intersect:e("./intersect"),scission:e("./scission"),subtract:e("./subtract"),union:e("./union")}},{"./intersect":282,"./scission":287,"./subtract":289,"./union":300}],282:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../utils/areAllShapesTheSameType"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("./intersectGeom2"),l=e("./intersectGeom3");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");if(!r(e))throw new Error("only intersect of the types are supported");const t=e[0];return n.isA(t)?a(e):o.isA(t)?l(e):t}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../utils/areAllShapesTheSameType":410,"../../utils/flatten":412,"./intersectGeom2":283,"./intersectGeom3":284}],283:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom3"),n=e("../../measurements/measureEpsilon"),o=e("./fromFakePolygons"),a=e("./to3DWalls"),l=e("./intersectGeom3");t.exports=(...e)=>{const t=(e=s(e)).map((e=>a({z0:-1,z1:1},e))),i=l(t),h=n(i);return o(h,r.toPolygons(i))}},{"../../geometries/geom3":57,"../../measurements/measureEpsilon":278,"../../utils/flatten":412,"./fromFakePolygons":280,"./intersectGeom3":284,"./to3DWalls":293}],284:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../modifiers/retessellate"),n=e("./intersectGeom3Sub");t.exports=(...e)=>{let t=(e=s(e)).shift();return e.forEach((e=>{t=n(t,e)})),t=r(t),t}},{"../../utils/flatten":412,"../modifiers/retessellate":370,"./intersectGeom3Sub":285}],285:[function(e,t,i){const s=e("../../geometries/geom3"),r=e("./mayOverlap"),{Tree:n}=e("./trees");t.exports=(e,t)=>{if(!r(e,t))return s.create();const i=new n(s.toPolygons(e)),o=new n(s.toPolygons(t));i.invert(),o.clipTo(i),o.invert(),i.clipTo(o),o.clipTo(i),i.addPolygons(o.allPolygons()),i.invert();const a=i.allPolygons();return s.create(a)}},{"../../geometries/geom3":57,"./mayOverlap":286,"./trees":297}],286:[function(e,t,i){const{EPS:s}=e("../../maths/constants"),r=e("../../measurements/measureBoundingBox");t.exports=(e,t)=>{if(0===e.polygons.length||0===t.polygons.length)return!1;const i=r(e),n=i[0],o=i[1],a=r(t),l=a[0],h=a[1];return!(l[0]-o[0]>s||n[0]-h[0]>s||l[1]-o[1]>s||n[1]-h[1]>s||l[2]-o[2]>s||n[2]-h[2]>s)}},{"../../maths/constants":110,"../../measurements/measureBoundingBox":273}],287:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom3"),n=e("./scissionGeom3");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>r.isA(e)?n(e):e));return 1===t.length?t[0]:t}},{"../../geometries/geom3":57,"../../utils/flatten":412,"./scissionGeom3":288}],288:[function(e,t,i){const s=e("../../maths/vec3"),r=e("../../measurements/measureEpsilon"),n=e("../../geometries/geom3");t.exports=e=>{const t=r(e),i=n.toPolygons(e),o=i.length,a=new Map,l=s.create();i.forEach(((e,i)=>{e.vertices.forEach((e=>{((e,t,i)=>{const s=`${t}`,r=e.get(s);void 0===r?e.set(s,[i]):r.push(i)})(a,s.snap(l,e,t),i)}))}));const h=i.map((e=>{let i=[];return e.vertices.forEach((e=>{i=i.concat(((e,t)=>{const i=`${t}`;return e.get(i)})(a,s.snap(l,e,t)))})),{e:1,d:(r=i,r.sort(((e,t)=>e-t)).filter(((e,t,i)=>!t||e!==i[t-1])))};var r}));a.clear();let c=0;const u=h.length;for(let e=0;e0){const i=new Array(o);i[e]=!0;do{c=0,i.forEach(((e,t)=>{const s=h[t];if(s.e>0){s.e=-1;for(let e=0;e0);t.indexes=i}}const d=[];for(let e=0;et.push(i[s]))),d.push(n.create(t))}return d}},{"../../geometries/geom3":57,"../../maths/vec3":237,"../../measurements/measureEpsilon":278}],289:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../utils/areAllShapesTheSameType"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("./subtractGeom2"),l=e("./subtractGeom3");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");if(!r(e))throw new Error("only subtract of the types are supported");const t=e[0];return n.isA(t)?a(e):o.isA(t)?l(e):t}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../utils/areAllShapesTheSameType":410,"../../utils/flatten":412,"./subtractGeom2":290,"./subtractGeom3":291}],290:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom3"),n=e("../../measurements/measureEpsilon"),o=e("./fromFakePolygons"),a=e("./to3DWalls"),l=e("./subtractGeom3");t.exports=(...e)=>{const t=(e=s(e)).map((e=>a({z0:-1,z1:1},e))),i=l(t),h=n(i);return o(h,r.toPolygons(i))}},{"../../geometries/geom3":57,"../../measurements/measureEpsilon":278,"../../utils/flatten":412,"./fromFakePolygons":280,"./subtractGeom3":291,"./to3DWalls":293}],291:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../modifiers/retessellate"),n=e("./subtractGeom3Sub");t.exports=(...e)=>{let t=(e=s(e)).shift();return e.forEach((e=>{t=n(t,e)})),t=r(t),t}},{"../../utils/flatten":412,"../modifiers/retessellate":370,"./subtractGeom3Sub":292}],292:[function(e,t,i){const s=e("../../geometries/geom3"),r=e("./mayOverlap"),{Tree:n}=e("./trees");t.exports=(e,t)=>{if(!r(e,t))return s.clone(e);const i=new n(s.toPolygons(e)),o=new n(s.toPolygons(t));i.invert(),i.clipTo(o),o.clipTo(i,!0),i.addPolygons(o.allPolygons()),i.invert();const a=i.allPolygons();return s.create(a)}},{"../../geometries/geom3":57,"./mayOverlap":286,"./trees":297}],293:[function(e,t,i){const s=e("../../maths/vec3"),r=e("../../geometries/geom2"),n=e("../../geometries/geom3"),o=e("../../geometries/poly3");t.exports=(e,t)=>{const i=r.toSides(t).map((t=>((e,t,i)=>{const r=[s.fromVec2(s.create(),i[0],e),s.fromVec2(s.create(),i[1],e),s.fromVec2(s.create(),i[1],t),s.fromVec2(s.create(),i[0],t)];return o.create(r)})(e.z0,e.z1,t)));return n.create(i)}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/poly3":95,"../../maths/vec3":237}],294:[function(e,t,i){const s=e("../../../maths/plane"),r=e("../../../geometries/poly3");class n{constructor(e){this.plane=null,this.front=null,this.back=null,this.polygontreenodes=[],this.parent=e}invert(){const e=[this];let t;for(let i=0;i0&&r.push({node:i.front,polygontreenodes:o});const h=n.length;if(i.back&&h>0)r.push({node:i.back,polygontreenodes:n});else for(let e=0;e0&&e.rootnode.clipPolygons(i.polygontreenodes,t),i.front&&s.push(i.front),i.back&&s.push(i.back),i=s.pop()}while(void 0!==i)}addPolygonTreeNodes(e){let t={node:this,polygontreenodes:e};const i=[];do{const e=t.node,s=t.polygontreenodes;if(0===s.length){t=i.pop();continue}if(!e.plane){let t=0;t=Math.floor(s.length/2);const i=s[t].getPolygon();e.plane=r.plane(i)}const o=[],a=[],l=s.length;for(let t=0;t0&&(e.front||(e.front=new n(e)),l===o.length&&0===a.length?e.front.polygontreenodes=o:i.push({node:e.front,polygontreenodes:o})),a.length>0&&(e.back||(e.back=new n(e)),l===a.length&&0===o.length?e.back.polygontreenodes=a:i.push({node:e.back,polygontreenodes:a})),t=i.pop()}while(void 0!==t)}}t.exports=n},{"../../../geometries/poly3":95,"../../../maths/plane":178}],295:[function(e,t,i){const{EPS:s}=e("../../../maths/constants"),r=e("../../../maths/vec3"),n=e("../../../geometries/poly3"),o=e("./splitPolygonByPlane");class a{constructor(e,t){this.parent=e,this.children=[],this.polygon=t,this.removed=!1}addPolygons(e){if(!this.isRootNode())throw new Error("Assertion failed");const t=this;e.forEach((e=>{t.addChild(e)}))}remove(){if(!this.removed){this.removed=!0,this.polygon=null;const e=this.parent.children,t=e.indexOf(this);if(t<0)throw new Error("Assertion failed");e.splice(t,1),this.parent.recursivelyInvalidatePolygon()}}isRemoved(){return this.removed}isRootNode(){return!this.parent}invert(){if(!this.isRootNode())throw new Error("Assertion failed");this.invertSub()}getPolygon(){if(!this.polygon)throw new Error("Assertion failed");return this.polygon}getPolygons(e){let t=[this];const i=[t];let s,r,n,o;for(s=0;s0&&i.push(o.children)}splitByPlane(e,t,i,s,r){if(this.children.length){const n=[this.children];let o,a,l,h,c;for(o=0;o0?n.push(h.children):h._splitByPlane(e,t,i,s,r)}else this._splitByPlane(e,t,i,s,r)}_splitByPlane(e,t,i,a,l){const h=this.polygon;if(h){const c=n.measureBoundingSphere(h),u=c[3]+s,d=c,p=r.dot(e,d)-e[3];if(p>u)a.push(this);else if(p<-u)l.push(this);else{const s=o(e,h);switch(s.type){case 0:t.push(this);break;case 1:i.push(this);break;case 2:a.push(this);break;case 3:l.push(this);break;case 4:if(s.front){const e=this.addChild(s.front);a.push(e)}if(s.back){const e=this.addChild(s.back);l.push(e)}}}}}addChild(e){const t=new a(this,e);return this.children.push(t),t}invertSub(){let e=[this];const t=[e];let i,s,r,o;for(i=0;i0&&t.push(o.children)}recursivelyInvalidatePolygon(){this.polygon=null,this.parent&&this.parent.recursivelyInvalidatePolygon()}clear(){let e=[this];const t=[e];for(let i=0;i0&&t.push(s.children),s.children=[]}}}toString(){let e="",t=[this];const i=[t];let s,r,n,o;for(s=0;s0&&i.push(o.children)}return e}}t.exports=a},{"../../../geometries/poly3":95,"../../../maths/constants":110,"../../../maths/vec3":237,"./splitPolygonByPlane":299}],296:[function(e,t,i){const s=e("./Node"),r=e("./PolygonTreeNode");t.exports=class{constructor(e){this.polygonTree=new r,this.rootnode=new s(null),e&&this.addPolygons(e)}invert(){this.polygonTree.invert(),this.rootnode.invert()}clipTo(e,t=!1){this.rootnode.clipTo(e,t)}allPolygons(){const e=[];return this.polygonTree.getPolygons(e),e}addPolygons(e){const t=new Array(e.length);for(let i=0;i{const r=s.subtract(s.create(),i,t);let n=(e[3]-s.dot(e,t))/s.dot(e,r);return Number.isNaN(n)&&(n=0),n>1&&(n=1),n<0&&(n=0),s.scale(r,r,n),s.add(r,t,r),r}},{"../../../maths/vec3":237}],299:[function(e,t,i){const{EPS:s}=e("../../../maths/constants"),r=e("../../../maths/plane"),n=e("../../../maths/vec3"),o=e("../../../geometries/poly3"),a=e("./splitLineSegmentByPlane");t.exports=(e,t)=>{const i={type:null,front:null,back:null},l=t.vertices,h=l.length,c=o.plane(t);if(r.equals(c,e))i.type=0;else{let t=!1,r=!1;const u=[],d=-s;for(let i=0;is&&(t=!0),o=h&&(n=0);const o=u[n];if(d===o)d?r.push(s):t.push(s);else{const i=l[n],o=a(e,s,i);d?(r.push(s),r.push(o),t.push(o)):(t.push(s),t.push(o),r.push(o))}d=o}const p=s*s;if(r.length>=3){let e=r[r.length-1];for(let t=0;t=3){let e=t[t.length-1];for(let i=0;i=3&&(i.front=o.fromPointsAndPlane(t,c)),r.length>=3&&(i.back=o.fromPointsAndPlane(r,c))}else i.type=3;else i.type=2;else{const t=n.dot(e,c);i.type=t>=0?0:1}}return i}},{"../../../geometries/poly3":95,"../../../maths/constants":110,"../../../maths/plane":178,"../../../maths/vec3":237,"./splitLineSegmentByPlane":298}],300:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../utils/areAllShapesTheSameType"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("./unionGeom2"),l=e("./unionGeom3");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");if(!r(e))throw new Error("only unions of the same type are supported");const t=e[0];return n.isA(t)?a(e):o.isA(t)?l(e):t}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../utils/areAllShapesTheSameType":410,"../../utils/flatten":412,"./unionGeom2":301,"./unionGeom3":302}],301:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom3"),n=e("../../measurements/measureEpsilon"),o=e("./fromFakePolygons"),a=e("./to3DWalls"),l=e("./unionGeom3");t.exports=(...e)=>{const t=(e=s(e)).map((e=>a({z0:-1,z1:1},e))),i=l(t),h=n(i);return o(h,r.toPolygons(i))}},{"../../geometries/geom3":57,"../../measurements/measureEpsilon":278,"../../utils/flatten":412,"./fromFakePolygons":280,"./to3DWalls":293,"./unionGeom3":302}],302:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../modifiers/retessellate"),n=e("./unionGeom3Sub");t.exports=(...e)=>{let t;for(e=s(e),t=1;t{if(!r(e,t))return((e,t)=>{let i=s.toPolygons(e);return i=i.concat(s.toPolygons(t)),s.create(i)})(e,t);const i=new n(s.toPolygons(e)),o=new n(s.toPolygons(t));i.clipTo(o,!1),o.clipTo(i),o.invert(),o.clipTo(i),o.invert();const a=i.allPolygons().concat(o.allPolygons());return s.create(a)}},{"../../geometries/geom3":57,"./mayOverlap":286,"./trees":297}],304:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom2"),n=e("../../geometries/geom3"),o=e("../../geometries/path2"),a=e("./expandGeom2"),l=e("./expandGeom3"),h=e("./expandPath2");t.exports=(e,...t)=>{if(0===(t=s(t)).length)throw new Error("wrong number of arguments");const i=t.map((t=>o.isA(t)?h(e,t):r.isA(t)?a(e,t):n.isA(t)?l(e,t):t));return 1===i.length?i[0]:i}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../utils/flatten":412,"./expandGeom2":305,"./expandGeom3":306,"./expandPath2":307}],305:[function(e,t,i){const s=e("../../geometries/geom2"),r=e("./offsetFromPoints");t.exports=(e,t)=>{const{delta:i,corners:n,segments:o}=Object.assign({},{delta:1,corners:"edge",segments:16},e);if("edge"!==n&&"chamfer"!==n&&"round"!==n)throw new Error('corners must be "edge", "chamfer", or "round"');const a=s.toOutlines(t).map((t=>r(e={delta:i,corners:n,closed:!0,segments:o},t))).reduce(((e,t)=>e.concat(s.toSides(s.fromPoints(t)))),[]);return s.create(a)}},{"../../geometries/geom2":42,"./offsetFromPoints":312}],306:[function(e,t,i){const s=e("../../geometries/geom3"),r=e("../booleans/union"),n=e("./expandShell");t.exports=(e,t)=>{const{delta:i,corners:o,segments:a}=Object.assign({},{delta:1,corners:"round",segments:12},e);if("round"!==o)throw new Error('corners must be "round" for 3D geometries');if(0===s.toPolygons(t).length)throw new Error("the given geometry cannot be empty");const l=n(e={delta:i,corners:o,segments:a},t);return r(t,l)}},{"../../geometries/geom3":57,"../booleans/union":300,"./expandShell":308}],307:[function(e,t,i){const s=e("../../maths/utils/area"),r=e("../../maths/vec2"),n=e("../../geometries/geom2"),o=e("../../geometries/path2"),a=e("./offsetFromPoints");t.exports=(e,t)=>{e=Object.assign({},{delta:1,corners:"edge",segments:16},e);const{delta:i,corners:l,segments:h}=e;if(i<=0)throw new Error("the given delta must be positive for paths");if("edge"!==l&&"chamfer"!==l&&"round"!==l)throw new Error('corners must be "edge", "chamfer", or "round"');const c=t.isClosed,u=o.toPoints(t);if(0===u.length)throw new Error("the given geometry cannot be empty");const d={points:u,external:a({delta:i,corners:l,segments:h,closed:c},u),internal:a({delta:-i,corners:l,segments:h,closed:c},u)};return t.isClosed?(e=>{let{external:t,internal:i}=e;s(t)<0?t=t.reverse():i=i.reverse();const r=o.fromPoints({closed:!0},t),a=o.fromPoints({closed:!0},i),l=n.toSides(n.fromPoints(o.toPoints(r))),h=n.toSides(n.fromPoints(o.toPoints(a)));return l.push(...h),n.create(l)})(d):((e,t,i,s)=>{const{points:o,external:a,internal:l}=e,h=Math.floor(t/2),c=[],u=[];if("round"===i&&h>0){const e=Math.PI/h,t=o[o.length-1],i=r.angle(r.subtract(r.create(),a[a.length-1],t)),n=o[0],d=r.angle(r.subtract(r.create(),l[0],n));for(let o=1;o{const s=t.toString();if(e.has(s))e.get(s)[1].push(i);else{const r=[t,[i]];e.set(s,r)}},_=(e,t,i)=>{const s=t[0].toString(),r=t[1].toString(),n=s{e.findIndex((e=>e===t))<0&&e.push(t)};t.exports=(e,t)=>{const{delta:i,segments:g}=Object.assign({},{delta:1,segments:12},e);let v=l.create();const x=new Map,T=new Map,S=o.create(),E=o.create();return l.toPolygons(t).forEach(((e,t)=>{const s=o.scale(o.create(),h.plane(e),2*i),r=h.transform(n.fromTranslation(n.create(),o.scale(o.create(),s,-.5)),e),a=p(s,r);v=d(v,a);const l=e.vertices;for(let t=0;t{const t=e[0],n=e[1],c=t[0],u=t[1],p=o.subtract(o.create(),u,c);o.normalize(p,p);const f=n[0],_=o.cross(o.create(),f,p);let x=[];for(let e=0;e=0&&o.distance(a,b)=0){y.push(a),A.push(l);const e=[C,l,a,b],t=h.create(e);R.push(t)}b=a,C=l}}A.reverse(),R.push(h.create(y)),R.push(h.create(A));const I=l.create(R);v=d(v,I)})),x.forEach((e=>{const t=e[0],s=e[1],r=s[0];let n=null,a=0;for(let e=1;e.05&&l>a&&(a=l,n=t)}n||(n=o.orthogonal(S,r));const l=o.cross(S,r,n);o.normalize(l,l);const h=o.cross(E,l,r),u=c({center:[t[0],t[1],t[2]],radius:i,segments:g,axes:[r,l,h]});v=d(v,u)})),u(v)}},{"../../geometries/geom3":57,"../../geometries/poly3":95,"../../maths/constants":110,"../../maths/mat4":159,"../../maths/vec3":237,"../../primitives/sphere":400,"../../utils/fnNumberSort":413,"../booleans/unionGeom3Sub":303,"../modifiers/retessellate":370,"./extrudePolygon":309}],309:[function(e,t,i){const s=e("../../maths/mat4"),r=e("../../maths/vec3"),n=e("../../geometries/geom3"),o=e("../../geometries/poly3");t.exports=(e,t)=>{r.dot(o.plane(t),e)>0&&(t=o.invert(t));const i=[t],a=o.transform(s.fromTranslation(s.create(),e),t),l=t.vertices.length;for(let e=0;e{if(0===(t=s(t)).length)throw new Error("wrong number of arguments");const i=t.map((t=>n.isA(t)?a(e,t):r.isA(t)?o(e,t):t));return 1===i.length?i[0]:i}},{"../../geometries/geom2":42,"../../geometries/path2":78,"../../utils/flatten":412,"./offsetGeom2":313,"./offsetPath2":314}],312:[function(e,t,i){const{EPS:s,TAU:r}=e("../../maths/constants"),n=e("../../maths/utils/intersect"),o=e("../../maths/line2"),a=e("../../maths/vec2"),l=e("../../maths/utils/area");t.exports=(e,t)=>{let{delta:i,corners:h,closed:c,segments:u}=Object.assign({},{delta:1,corners:"edge",closed:!1,segments:16},e);if(Math.abs(i)0&&i>=0||d<0&&i<0;i=Math.abs(i);let f=null,_=[];const m=[],g=a.create(),v=t.length;for(let e=0;ee.set(t,i)));const t=o.create(),i=o.create();m.forEach((s=>{o.fromPoints(t,s.s0[0],s.s0[1]),o.fromPoints(i,s.s1[0],s.s1[1]);const r=o.intersectPointOfLines(t,i);if(Number.isFinite(r[0])&&Number.isFinite(r[1])){const t=s.s0[1],i=e.get(t);_[i]=r,_[(i+1)%_.length]=void 0}else{const t=s.s1[0],i=e.get(t);_[i]=void 0}})),_=_.filter((e=>void 0!==e))}if("round"===h){let e=Math.floor(u/4);const t=a.create();m.forEach((s=>{let n=a.angle(a.subtract(t,s.s1[0],s.c));if(n-=a.angle(a.subtract(t,s.s0[1],s.c)),p&&n<0&&(n+=Math.PI,n<0&&(n+=Math.PI)),!p&&n>0&&(n-=Math.PI,n>0&&(n-=Math.PI)),0!==n){e=Math.floor(u*(Math.abs(n)/r));const o=n/e,l=a.angle(a.subtract(t,s.s0[1],s.c)),h=[];for(let t=1;t0){const e=s.s0[1];let t=_.findIndex((t=>a.equals(e,t)));t=(t+1)%_.length,_.splice(t,0,...h)}}else{const e=s.s1[0],t=_.findIndex((t=>a.equals(e,t)));_.splice(t,1)}}))}return _}},{"../../maths/constants":110,"../../maths/line2":121,"../../maths/utils/area":183,"../../maths/utils/intersect":186,"../../maths/vec2":206}],313:[function(e,t,i){const s=e("../../geometries/geom2"),r=e("../../geometries/poly2"),n=e("./offsetFromPoints");t.exports=(e,t)=>{const{delta:i,corners:o,segments:a}=Object.assign({},{delta:1,corners:"edge",segments:0},e);if("edge"!==o&&"chamfer"!==o&&"round"!==o)throw new Error('corners must be "edge", "chamfer", or "round"');const l=s.toOutlines(t),h=l.map((t=>{const s=l.reduce(((e,i)=>e+r.arePointsInside(t,r.create(i))),0);return n(e={delta:s%2==0?i:-i,corners:o,closed:!0,segments:a},t)})).reduce(((e,t)=>e.concat(s.toSides(s.fromPoints(t)))),[]);return s.create(h)}},{"../../geometries/geom2":42,"../../geometries/poly2":89,"./offsetFromPoints":312}],314:[function(e,t,i){const s=e("../../geometries/path2"),r=e("./offsetFromPoints");t.exports=(e,t)=>{const i={delta:1,corners:"edge",closed:t.isClosed,segments:16},{delta:n,corners:o,closed:a,segments:l}=Object.assign({},i,e);if("edge"!==o&&"chamfer"!==o&&"round"!==o)throw new Error('corners must be "edge", "chamfer", or "round"');const h=r(e={delta:n,corners:o,closed:a,segments:l},s.toPoints(t));return s.fromPoints({closed:a},h)}},{"../../geometries/path2":78,"./offsetFromPoints":312}],315:[function(e,t,i){const{area:s}=e("../../../maths/utils"),{toOutlines:r}=e("../../../geometries/geom2"),{arePointsInside:n}=e("../../../geometries/poly2");t.exports=e=>{const t=r(e),i=[],o=[];t.forEach(((e,t)=>{const r=s(e);r<0?o.push(t):r>0&&i.push(t)}));const a=[],l=[];return i.forEach(((e,i)=>{const s=t[e];a[i]=[],o.forEach(((e,r)=>{const o=t[e];n([o[0]],{vertices:s})&&(a[i].push(e),l[r]||(l[r]=[]),l[r].push(i))}))})),o.forEach(((e,t)=>{if(l[t]&&l[t].length>1){const i=((e,t)=>{let i,s;return e.forEach(((e,r)=>{const n=t(e);(void 0===s||na[e].length));l[t].forEach(((t,s)=>{s!==i&&(a[t]=a[t].filter((t=>t!==e)))}))}})),a.map(((e,s)=>({solid:t[i[s]],holes:e.map((e=>t[e]))})))}},{"../../../geometries/geom2":42,"../../../geometries/poly2":89,"../../../maths/utils":184}],316:[function(e,t,i){const{filterPoints:s,linkedPolygon:r,locallyInside:n,splitPolygon:o}=e("./linkedPolygon"),{area:a,pointInTriangle:l}=e("./triangle"),h=(e,t)=>{const i=c(e,t);if(!i)return t;const r=o(i,e),n=s(i,i.next);return s(r,r.next),t===i?n:t},c=(e,t)=>{let i=t;const s=e.x,r=e.y;let o,a=-1/0;do{if(r<=i.y&&r>=i.next.y&&i.next.y!==i.y){const e=i.x+(r-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(e<=s&&e>a){if(a=e,e===s){if(r===i.y)return i;if(r===i.next.y)return i.next}o=i.x=i.x&&i.x>=c&&s!==i.x&&l(ro.x||i.x===o.x&&u(o,i)))&&(o=i,p=t)}i=i.next}while(i!==h);return o},u=(e,t)=>a(e.prev,e,t.prev)<0&&a(t.next,e,e.next)<0,d=e=>{let t=e,i=e;do{(t.x{const o=[];for(let i=0,s=t.length;ie.x-t.x));for(let e=0;e{if(!e)return;!h&&l&&g(e,s,n,l);let c,u,d=e;for(;e.prev!==e.next;)if(c=e.prev,u=e.next,l?_(e,s,n,l):f(e))t.push(c.i/i),t.push(e.i/i),t.push(u.i/i),r(e),e=u.next,d=u.next;else if((e=u)===d){h?1===h?(e=o(a(e),t,i),p(e,t,i,s,n,l,2)):2===h&&m(e,t,i,s,n,l):p(a(e),t,i,s,n,l,1);break}},f=e=>{const t=e.prev,i=e,s=e.next;if(u(t,i,s)>=0)return!1;let r=e.next.next;for(;r!==e.prev;){if(d(t.x,t.y,i.x,i.y,s.x,s.y,r.x,r.y)&&u(r.prev,r,r.next)>=0)return!1;r=r.next}return!0},_=(e,t,i,s)=>{const r=e.prev,n=e,o=e.next;if(u(r,n,o)>=0)return!1;const a=r.xn.x?r.x>o.x?r.x:o.x:n.x>o.x?n.x:o.x,c=r.y>n.y?r.y>o.y?r.y:o.y:n.y>o.y?n.y:o.y,p=v(a,l,t,i,s),f=v(h,c,t,i,s);let _=e.prevZ,m=e.nextZ;for(;_&&_.z>=p&&m&&m.z<=f;){if(_!==e.prev&&_!==e.next&&d(r.x,r.y,n.x,n.y,o.x,o.y,_.x,_.y)&&u(_.prev,_,_.next)>=0)return!1;if(_=_.prevZ,m!==e.prev&&m!==e.next&&d(r.x,r.y,n.x,n.y,o.x,o.y,m.x,m.y)&&u(m.prev,m,m.next)>=0)return!1;m=m.nextZ}for(;_&&_.z>=p;){if(_!==e.prev&&_!==e.next&&d(r.x,r.y,n.x,n.y,o.x,o.y,_.x,_.y)&&u(_.prev,_,_.next)>=0)return!1;_=_.prevZ}for(;m&&m.z<=f;){if(m!==e.prev&&m!==e.next&&d(r.x,r.y,n.x,n.y,o.x,o.y,m.x,m.y)&&u(m.prev,m,m.next)>=0)return!1;m=m.nextZ}return!0},m=(e,t,i,s,r,n)=>{let o=e;do{let e=o.next.next;for(;e!==o.prev;){if(o.i!==e.i&&l(o,e)){let l=c(o,e);return o=a(o,o.next),l=a(l,l.next),p(o,t,i,s,r,n),void p(l,t,i,s,r,n)}e=e.next}o=o.next}while(o!==e)},g=(e,t,i,s)=>{let r=e;do{null===r.z&&(r.z=v(r.x,r.y,t,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,n(r,(e=>e.z))},v=(e,t,i,s,r)=>(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-i)*r)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-s)*r)|t<<8))|t<<4))|t<<2))|t<<1))<<1;t.exports=(e,t,i=2)=>{const r=t&&t.length,n=r?t[0]*i:e.length;let o=h(e,0,n,i,!0);const a=[];if(!o||o.next===o.prev)return a;let l,c,u,d,f;if(r&&(o=s(e,t,o,i)),e.length>80*i){l=u=e[0],c=d=e[1];for(let t=i;tu&&(u=i),s>d&&(d=s)}f=Math.max(u-l,d-c),f=0!==f?1/f:0}return p(o,a,i,l,c,f),a}},{"./eliminateHoles":316,"./linkedList":318,"./linkedPolygon":320,"./triangle":322}],318:[function(e,t,i){const s=e("./linkedListSort");class r{constructor(e,t,i){this.i=e,this.x=t,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}}t.exports={Node:r,insertNode:(e,t,i,s)=>{const n=new r(e,t,i);return s?(n.next=s.next,n.prev=s,s.next.prev=n,s.next=n):(n.prev=n,n.next=n),n},removeNode:e=>{e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)},sortLinked:s}},{"./linkedListSort":319}],319:[function(e,t,i){t.exports=(e,t)=>{let i,s,r,n,o,a=1;do{s=e,e=null;let l=null;for(o=0;s;){o++,r=s;let h=0;for(i=0;i0||c>0&&r;)0!==h&&(0===c||!r||t(s)<=t(r))?(n=s,s=s.nextZ,h--):(n=r,r=r.nextZ,c--),l?l.nextZ=n:e=n,n.prevZ=l,l=n;s=r}l.nextZ=null,a*=2}while(o>1);return e}},{}],320:[function(e,t,i){const{Node:s,insertNode:r,removeNode:n}=e("./linkedList"),{area:o}=e("./triangle"),a=(e,t)=>{if(!e)return e;t||(t=e);let i,s=e;do{if(i=!1,s.steiner||!u(s,s.next)&&0!==o(s.prev,s,s.next))s=s.next;else{if(n(s),s=t=s.prev,s===s.next)break;i=!0}}while(i||s!==t);return t},l=(e,t)=>o(e.prev,e,e.next)<0?o(e,t,e.next)>=0&&o(e,e.prev,t)>=0:o(e,t,e.prev)<0||o(e,e.next,t)<0,h=(e,t,i,s)=>{const r=Math.sign(o(e,t,i)),n=Math.sign(o(e,t,s)),a=Math.sign(o(i,s,e)),l=Math.sign(o(i,s,t));return r!==n&&a!==l||!(0!==r||!c(e,i,t))||!(0!==n||!c(e,s,t))||!(0!==a||!c(i,e,s))||!(0!==l||!c(i,t,s))},c=(e,t,i)=>t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y),u=(e,t)=>e.x===t.x&&e.y===t.y;t.exports={cureLocalIntersections:(e,t,i)=>{let s=e;do{const r=s.prev,o=s.next.next;!u(r,o)&&h(r,s,s.next,o)&&l(r,o)&&l(o,r)&&(t.push(r.i/i),t.push(s.i/i),t.push(o.i/i),n(s),n(s.next),s=e=o),s=s.next}while(s!==e);return a(s)},filterPoints:a,isValidDiagonal:(e,t)=>e.next.i!==t.i&&e.prev.i!==t.i&&!((e,t)=>{let i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&h(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1})(e,t)&&(l(e,t)&&l(t,e)&&((e,t)=>{let i=e,s=!1;const r=(e.x+t.x)/2,n=(e.y+t.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&r<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==e);return s})(e,t)&&(o(e.prev,e,t.prev)||o(e,t.prev,t))||u(e,t)&&o(e.prev,e,e.next)>0&&o(t.prev,t,t.next)>0),linkedPolygon:(e,t,i,s,o)=>{let a;if(o===((e,t,i,s)=>{let r=0;for(let n=t,o=i-s;n0)for(let n=t;n=t;n-=s)a=r(n,e[n],e[n+1],a);return a&&u(a,a.next)&&(n(a),a=a.next),a},locallyInside:l,splitPolygon:(e,t)=>{const i=new s(e.i,e.x,e.y),r=new s(t.i,t.x,t.y),n=e.next,o=t.prev;return e.next=t,t.prev=e,i.next=n,n.prev=i,r.next=i,i.prev=r,o.next=r,r.prev=o,r}}},{"./linkedList":318,"./triangle":322}],321:[function(e,t,i){const s=e("../../../geometries/geom2"),r=e("../../../maths/plane"),n=e("../../../maths/vec2"),o=e("../../../maths/vec3"),a=e("../slice/calculatePlane"),l=e("./assignHoles");t.exports=class{constructor(e){this.plane=a(e);const t=o.orthogonal(o.create(),this.plane),i=o.cross(o.create(),this.plane,t);this.v=o.normalize(i,i),this.u=o.cross(o.create(),this.v,this.plane),this.basisMap=new Map;const r=e.edges.map((e=>e.map((e=>this.to2D(e))))),n=s.create(r);this.roots=l(n)}to2D(e){const t=n.fromValues(o.dot(e,this.u),o.dot(e,this.v));return this.basisMap.set(t,e),t}to3D(e){const t=this.basisMap.get(e);if(t)return t;{console.log("Warning: point not in original slice");const t=o.scale(o.create(),this.u,e[0]),i=o.scale(o.create(),this.v,e[1]),s=o.scale(o.create(),r,r[3]),n=o.add(t,t,s);return o.add(i,i,n)}}}},{"../../../geometries/geom2":42,"../../../maths/plane":178,"../../../maths/vec2":206,"../../../maths/vec3":237,"../slice/calculatePlane":335,"./assignHoles":315}],322:[function(e,t,i){t.exports={area:(e,t,i)=>(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y),pointInTriangle:(e,t,i,s,r,n,o,a)=>(r-o)*(t-a)-(e-o)*(n-a)>=0&&(e-o)*(s-a)-(i-o)*(t-a)>=0&&(i-o)*(n-a)-(r-o)*(s-a)>=0}},{}],323:[function(e,t,i){const s=e("../../maths/mat4"),r=e("../../geometries/geom2"),n=e("../../geometries/geom3"),o=e("../../geometries/poly3"),a=e("./slice"),l=e("./slice/repair"),h=e("./extrudeWalls"),c=(e,t,i)=>{let n=null;return r.isA(i)&&(n=a.fromSides(r.toSides(i))),o.isA(i)&&(n=a.fromPoints(o.toPoints(i))),0===e||1===e?a.transform(s.fromTranslation(s.create(),[0,0,e]),n):null};t.exports=(e,t)=>{const i={numberOfSlices:2,capStart:!0,capEnd:!0,close:!1,repair:!0,callback:c},{numberOfSlices:s,capStart:r,capEnd:u,close:d,repair:p,callback:f}=Object.assign({},i,e);if(s<2)throw new Error("numberOfSlices must be 2 or more");p&&(t=l(t));const _=s-1;let m=null,g=null,v=null,x=[];for(let e=0;e{const i={angle:s,startAngle:0,pitch:10,endOffset:0,segmentsPerRotation:32},{angle:l,endOffset:h,segmentsPerRotation:c,startAngle:u}=Object.assign({},i,e);let d;if(d=!e.pitch&&e.height?e.height/(l/s):e.pitch?e.pitch:i.pitch,c<3)throw new Error("The number of segments per rotation needs to be at least 3.");const p=a.toSides(t);if(0===p.length)throw new Error("the given geometry cannot be empty");const f=p.filter((e=>e[0][0]>=0));let _=r.fromSides(p);0===f.length&&(_=r.reverse(_));const m=Math.round(c/s*Math.abs(l)),g=m>=2?m:2,v=n.create();let x;return o({numberOfSlices:g+1,callback:(e,t,i)=>{const o=u+l/g*t,a=h/g*t,c=(o-u)/s*d;return n.multiply(v,n.fromTranslation(n.create(),[a,0,c*Math.sign(l)]),n.fromXRotation(n.create(),-s/4*Math.sign(l))),x=n.create(),n.multiply(x,n.fromZRotation(n.create(),o),v),r.transform(x,i)}},_)}},{"../../geometries/geom2":42,"../../maths/constants":110,"../../maths/mat4":159,"./extrudeFromSlices":323,"./slice":341}],325:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom2"),n=e("../../geometries/path2"),o=e("./extrudeLinearGeom2"),a=e("./extrudeLinearPath2");t.exports=(e,...t)=>{const{height:i,twistAngle:l,twistSteps:h,repair:c}=Object.assign({},{height:1,twistAngle:0,twistSteps:1,repair:!0},e);if(0===(t=s(t)).length)throw new Error("wrong number of arguments");e={offset:[0,0,i],twistAngle:l,twistSteps:h,repair:c};const u=t.map((t=>n.isA(t)?a(e,t):r.isA(t)?o(e,t):t));return 1===u.length?u[0]:u}},{"../../geometries/geom2":42,"../../geometries/path2":78,"../../utils/flatten":412,"./extrudeLinearGeom2":326,"./extrudeLinearPath2":327}],326:[function(e,t,i){const s=e("../../maths/mat4"),r=e("../../maths/vec3"),n=e("../../geometries/geom2"),o=e("./slice"),a=e("./extrudeFromSlices");t.exports=(e,t)=>{let{offset:i,twistAngle:l,twistSteps:h,repair:c}=Object.assign({},{offset:[0,0,1],twistAngle:0,twistSteps:12,repair:!0},e);if(h<1)throw new Error("twistSteps must be 1 or more");0===l&&(h=1);const u=r.clone(i),d=n.toSides(t);if(0===d.length)throw new Error("the given geometry cannot be empty");const p=o.fromSides(d);u[2]<0&&o.reverse(p,p);const f=s.create();return a(e={numberOfSlices:h+1,capStart:!0,capEnd:!0,repair:c,callback:(e,t,i)=>{const n=t/h*l,a=r.scale(r.create(),u,t/h);return s.multiply(f,s.fromZRotation(f,n),s.fromTranslation(s.create(),a)),o.transform(f,i)}},p)}},{"../../geometries/geom2":42,"../../maths/mat4":159,"../../maths/vec3":237,"./extrudeFromSlices":323,"./slice":341}],327:[function(e,t,i){const s=e("../../geometries/geom2"),r=e("../../geometries/path2"),n=e("./extrudeLinearGeom2");t.exports=(e,t)=>{if(!t.isClosed)throw new Error("extruded path must be closed");const i=r.toPoints(t),o=s.fromPoints(i);return n(e,o)}},{"../../geometries/geom2":42,"../../geometries/path2":78,"./extrudeLinearGeom2":326}],328:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom2"),n=e("../../geometries/path2"),o=e("./extrudeRectangularPath2"),a=e("./extrudeRectangularGeom2");t.exports=(e,...t)=>{const{size:i,height:l}=Object.assign({},{size:1,height:1},e);if(0===(t=s(t)).length)throw new Error("wrong number of arguments");if(i<=0)throw new Error("size must be positive");if(l<=0)throw new Error("height must be positive");const h=t.map((t=>n.isA(t)?o(e,t):r.isA(t)?a(e,t):t));return 1===h.length?h[0]:h}},{"../../geometries/geom2":42,"../../geometries/path2":78,"../../utils/flatten":412,"./extrudeRectangularGeom2":329,"./extrudeRectangularPath2":330}],329:[function(e,t,i){const{area:s}=e("../../maths/utils"),r=e("../../geometries/geom2"),n=e("../../geometries/path2"),o=e("../expansions/expand"),a=e("./extrudeLinearGeom2");t.exports=(e,t)=>{const{size:i,height:l}=Object.assign({},{size:1,height:1},e);e.delta=i,e.offset=[0,0,l];const h=r.toOutlines(t);if(0===h.length)throw new Error("the given geometry cannot be empty");const c=h.map((t=>(s(t)<0&&t.reverse(),o(e,n.fromPoints({closed:!0},t))))).reduce(((e,t)=>e.concat(r.toSides(t))),[]),u=r.create(c);return a(e,u)}},{"../../geometries/geom2":42,"../../geometries/path2":78,"../../maths/utils":184,"../expansions/expand":304,"./extrudeLinearGeom2":326}],330:[function(e,t,i){const s=e("../../geometries/path2"),r=e("../expansions/expand"),n=e("./extrudeLinearGeom2");t.exports=(e,t)=>{const{size:i,height:o}=Object.assign({},{size:1,height:1},e);if(e.delta=i,e.offset=[0,0,o],0===s.toPoints(t).length)throw new Error("the given geometry cannot be empty");const a=r(e,t);return n(e,a)}},{"../../geometries/path2":78,"../expansions/expand":304,"./extrudeLinearGeom2":326}],331:[function(e,t,i){const{TAU:s}=e("../../maths/constants"),r=e("../../maths/mat4"),{mirrorX:n}=e("../transforms/mirror"),o=e("../../geometries/geom2"),a=e("./slice"),l=e("./extrudeFromSlices");t.exports=(e,t)=>{const i={segments:12,startAngle:0,angle:s,overflow:"cap"};let{segments:h,startAngle:c,angle:u,overflow:d}=Object.assign({},i,e);if(h<3)throw new Error("segments must be greater then 3");c=Math.abs(c)>s?c%s:c,u=Math.abs(u)>s?u%s:u;let p=c+u;if(p=Math.abs(p)>s?p%s:p,ph*e&&h++}let _=o.toSides(t);if(0===_.length)throw new Error("the given geometry cannot be empty");const m=_.filter((e=>e[0][0]<0)),g=_.filter((e=>e[0][0]>=0));m.length>0&&g.length>0&&"cap"===d&&(m.length>g.length?(_=_.map((e=>{let t=e[0],i=e[1];return t=[Math.min(t[0],0),t[1]],i=[Math.min(i[0],0),i[1]],[t,i]})),t=o.reverse(o.create(_)),t=n(t)):g.length>=m.length&&(_=_.map((e=>{let t=e[0],i=e[1];return t=[Math.max(t[0],0),t[1]],i=[Math.max(i[0],0),i[1]],[t,i]})),t=o.create(_)));const v=f/h,x=Math.abs(f){let n=v*t+c;return f===s&&t===h&&(n=c),r.multiply(S,r.fromZRotation(S,n),r.fromXRotation(r.create(),s/4)),a.transform(S,i)}},T)}},{"../../geometries/geom2":42,"../../maths/constants":110,"../../maths/mat4":159,"../transforms/mirror":377,"./extrudeFromSlices":323,"./slice":341}],332:[function(e,t,i){const{EPS:s}=e("../../maths/constants"),r=e("../../maths/vec3"),n=e("../../geometries/poly3"),o=e("./slice"),a=(e,t)=>e===t?e:e{const i=e/t.length;if(1===i)return t;const s=r.fromValues(i,i,i),n=[];return t.forEach((e=>{const t=r.subtract(r.create(),e[1],e[0]);r.divide(t,t,s);let o=e[0];for(let e=1;e<=i;++e){const e=r.add(r.create(),o,t);n.push([o,e]),o=e}})),n},h=s*s/2*Math.sin(Math.PI/3);t.exports=(e,t)=>{let i=o.toEdges(e),s=o.toEdges(t);if(i.length!==s.length){const e=(r=i.length)*(c=s.length)/a(r,c);e!==i.length&&(i=l(e,i)),e!==s.length&&(s=l(e,s))}var r,c;const u=[];return i.forEach(((e,t)=>{const i=s[t],r=n.create([e[0],e[1],i[1]]),o=n.measureArea(r);Number.isFinite(o)&&o>h&&u.push(r);const a=n.create([e[0],i[1],i[0]]),l=n.measureArea(a);Number.isFinite(l)&&l>h&&u.push(a)})),u}},{"../../geometries/poly3":95,"../../maths/constants":110,"../../maths/vec3":237,"./slice":341}],333:[function(e,t,i){t.exports={extrudeFromSlices:e("./extrudeFromSlices"),extrudeLinear:e("./extrudeLinear"),extrudeRectangular:e("./extrudeRectangular"),extrudeRotate:e("./extrudeRotate"),extrudeHelical:e("./extrudeHelical"),project:e("./project"),slice:e("./slice")}},{"./extrudeFromSlices":323,"./extrudeHelical":324,"./extrudeLinear":325,"./extrudeRectangular":328,"./extrudeRotate":331,"./project":334,"./slice":341}],334:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../maths/utils/aboutEqualNormals"),n=e("../../maths/plane"),o=e("../../maths/mat4"),a=e("../../geometries/geom2"),l=e("../../geometries/geom3"),h=e("../../geometries/poly3"),c=e("../../measurements/measureEpsilon"),u=e("../booleans/unionGeom2");t.exports=(e,...t)=>{const{axis:i,origin:d}=Object.assign({},{axis:[0,0,1],origin:[0,0,0]},e);if(0===(t=s(t)).length)throw new Error("wrong number of arguments");e={axis:i,origin:d};const p=t.map((t=>l.isA(t)?((e,t)=>{const i=n.fromNormalAndPoint(n.create(),e.axis,e.origin);if(Number.isNaN(i[0])||Number.isNaN(i[1])||Number.isNaN(i[2])||Number.isNaN(i[3]))throw new Error("project: invalid axis or origin");const s=c(t),d=s*s*Math.sqrt(3)/4;if(0===s)return a.create();const p=l.toPolygons(t);let f=[];for(let e=0;en.projectionOfPoint(i,e))),s=h.create(t),o=h.plane(s);r(i,o)&&(h.measureArea(s)h.transform(e,t)))}f=f.sort(((e,t)=>h.measureArea(t)-h.measureArea(e)));const _=f.map((e=>a.fromPoints(e.vertices)));return u(_)})(e,t):t));return 1===p.length?p[0]:p}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/poly3":95,"../../maths/mat4":159,"../../maths/plane":178,"../../maths/utils/aboutEqualNormals":182,"../../measurements/measureEpsilon":278,"../../utils/flatten":412,"../booleans/unionGeom2":301}],335:[function(e,t,i){const s=e("../../../maths/plane"),r=e("../../../maths/vec3");t.exports=e=>{const t=e.edges;if(t.length<3)throw new Error("slices must have 3 or more edges to calculate a plane");const i=t.reduce(((e,t)=>r.add(r.create(),e,t[0])),r.create());let n;r.scale(i,i,1/t.length);let o=0;t.forEach((e=>{if(!r.equals(e[0],e[1])){const t=r.squaredDistance(i,e[0]);t>o&&(n=e,o=t)}}));const a=t.find((e=>r.equals(e[1],n[0])));return s.fromPoints(s.create(),a[0],n[0],n[1])}},{"../../../maths/plane":178,"../../../maths/vec3":237}],336:[function(e,t,i){const s=e("./create"),r=e("../../../maths/vec3");t.exports=(...e)=>{let t,i;return 1===e.length?(t=s(),i=e[0]):(t=e[0],i=e[1]),t.edges=i.edges.map((e=>[r.clone(e[0]),r.clone(e[1])])),t}},{"../../../maths/vec3":237,"./create":337}],337:[function(e,t,i){t.exports=e=>(e||(e=[]),{edges:e})},{}],338:[function(e,t,i){const s=e("../../../maths/vec3");t.exports=(e,t)=>{const i=e.edges,r=t.edges;return i.length===r.length&&i.reduce(((e,t,i)=>{const n=r[i],o=s.squaredDistance(t[0],n[0]);return e&&o{if(!Array.isArray(e))throw new Error("the given points must be an array");if(e.length<3)throw new Error("the given points must contain THREE or more points");const t=[];let i=e[e.length-1];return e.forEach((e=>{2===e.length&&t.push([s.fromVec2(s.create(),i),s.fromVec2(s.create(),e)]),3===e.length&&t.push([i,e]),i=e})),r(t)}},{"../../../maths/vec3":237,"./create":337}],340:[function(e,t,i){const s=e("../../../maths/vec3"),r=e("./create");t.exports=e=>{if(!Array.isArray(e))throw new Error("the given sides must be an array");const t=[];return e.forEach((e=>{t.push([s.fromVec2(s.create(),e[0]),s.fromVec2(s.create(),e[1])])})),r(t)}},{"../../../maths/vec3":237,"./create":337}],341:[function(e,t,i){t.exports={calculatePlane:e("./calculatePlane"),clone:e("./clone"),create:e("./create"),equals:e("./equals"),fromPoints:e("./fromPoints"),fromSides:e("./fromSides"),isA:e("./isA"),reverse:e("./reverse"),toEdges:e("./toEdges"),toPolygons:e("./toPolygons"),toString:e("./toString"),transform:e("./transform")}},{"./calculatePlane":335,"./clone":336,"./create":337,"./equals":338,"./fromPoints":339,"./fromSides":340,"./isA":342,"./reverse":344,"./toEdges":345,"./toPolygons":346,"./toString":347,"./transform":348}],342:[function(e,t,i){t.exports=e=>!!(e&&"object"==typeof e&&"edges"in e&&Array.isArray(e.edges))},{}],343:[function(e,t,i){const s=e("../../../maths/vec3"),r=e("./create");t.exports=e=>{if(!e.edges)return e;let t=e.edges;const i=new Map,n=new Map;t=t.filter((e=>!s.equals(e[0],e[1]))),t.forEach((e=>{const t=e[0].toString(),s=e[1].toString();i.set(t,e[0]),i.set(s,e[1]),n.set(t,(n.get(t)||0)+1),n.set(s,(n.get(s)||0)-1)}));const o=[],a=[];return n.forEach(((e,t)=>{e<0&&o.push(t),e>0&&a.push(t)})),o.forEach((e=>{const r=i.get(e);let n,o=1/0;a.forEach((e=>{const t=i.get(e),a=s.distance(r,t);at[0].toString()===e?[n,t[1]]:t[1].toString()===e?[t[0],n]:t))})),r(t)}},{"../../../maths/vec3":237,"./create":337}],344:[function(e,t,i){const s=e("./create");t.exports=(...e)=>{let t,i;return 1===e.length?(t=s(),i=e[0]):(t=e[0],i=e[1]),t.edges=i.edges.map((e=>[e[1],e[0]])),t}},{"./create":337}],345:[function(e,t,i){t.exports=e=>e.edges},{}],346:[function(e,t,i){const s=e("../../../geometries/poly3"),r=e("../earcut"),n=e("../earcut/polygonHierarchy");t.exports=e=>{const t=new n(e),i=[];return t.roots.forEach((({solid:e,holes:n})=>{let o=e.length;const a=[];n.forEach(((e,t)=>{a.push(o),o+=e.length}));const l=[e,...n].flat(),h=l.flat(),c=e=>t.to3D(l[e]),u=r(h,a);for(let e=0;e{return`[${t=e.edges,t.reduce(((e,t)=>e+`[${s.toString(t[0])}, ${s.toString(t[1])}], `),"")}]`;var t}},{"../../../maths/vec3":237}],348:[function(e,t,i){const s=e("../../../maths/vec3"),r=e("./create");t.exports=(e,t)=>{const i=t.edges.map((t=>[s.transform(s.create(),t[0],e),s.transform(s.create(),t[1],e)]));return r(i)}},{"../../../maths/vec3":237,"./create":337}],349:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../utils/areAllShapesTheSameType"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("../../geometries/path2"),l=e("./hullPath2"),h=e("./hullGeom2"),c=e("./hullGeom3");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");if(!r(e))throw new Error("only hulls of the same type are supported");const t=e[0];return a.isA(t)?l(e):n.isA(t)?h(e):o.isA(t)?c(e):t}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../utils/areAllShapesTheSameType":410,"../../utils/flatten":412,"./hullGeom2":351,"./hullGeom3":352,"./hullPath2":353}],350:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../booleans/union"),n=e("./hull");t.exports=(...e)=>{if((e=s(e)).length<2)throw new Error("wrong number of arguments");const t=[];for(let i=1;i{e=s(e);const t=o(e),i=n(t);return i.length<3?r.create():r.fromPoints(i)}},{"../../geometries/geom2":42,"../../utils/flatten":412,"./hullPoints2":354,"./toUniquePoints":364}],352:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom3"),n=e("../../geometries/poly3"),o=e("./quickhull"),a=e("./toUniquePoints");t.exports=(...e)=>{if(1===(e=s(e)).length)return e[0];const t=a(e),i=o(t,{skipTriangulation:!0}).map((e=>{const i=e.map((e=>t[e]));return n.create(i)}));return r.create(i)}},{"../../geometries/geom3":57,"../../geometries/poly3":95,"../../utils/flatten":412,"./quickhull":362,"./toUniquePoints":364}],353:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/path2"),n=e("./hullPoints2"),o=e("./toUniquePoints");t.exports=(...e)=>{e=s(e);const t=o(e),i=n(t);return r.fromPoints({closed:!0},i)}},{"../../geometries/path2":78,"../../utils/flatten":412,"./hullPoints2":354,"./toUniquePoints":364}],354:[function(e,t,i){const s=e("../../maths/vec2");t.exports=e=>{let t=s.fromValues(1/0,1/0);e.forEach((e=>{(e[1]{const r=(o=e[1]-t[1],a=e[0]-t[0],0===o&&0===a?-1/0:-a/o),n=s.squaredDistance(e,t);var o,a;i.push({point:e,angle:r,distSq:n})})),i.sort(((e,t)=>e.angle!==t.angle?e.angle-t.angle:e.distSq-t.distSq));const r=[];return i.forEach((e=>{let t=r.length;for(;t>1&&(i=r[t-2],s=r[t-1],n=e.point,(s[0]-i[0])*(n[1]-i[1])-(s[1]-i[1])*(n[0]-i[0])<=Number.EPSILON);)r.pop(),t=r.length;var i,s,n;r.push(e.point)})),r}},{"../../maths/vec2":206}],355:[function(e,t,i){t.exports={hull:e("./hull"),hullChain:e("./hullChain")}},{"./hull":349,"./hullChain":350}],356:[function(e,t,i){const s=e("../../../maths/vec3/add"),r=e("../../../maths/vec3/copy"),n=e("../../../maths/vec3/cross"),o=e("../../../maths/vec3/dot"),a=e("../../../maths/vec3/length"),l=e("../../../maths/vec3/normalize"),h=e("../../../maths/vec3/scale"),c=e("../../../maths/vec3/subtract"),u=e("./HalfEdge");class d{constructor(){this.normal=[],this.centroid=[],this.offset=0,this.outside=null,this.mark=0,this.edge=null,this.nVertices=0}getEdge(e){if("number"!=typeof e)throw Error("requires a number");let t=this.edge;for(;e>0;)t=t.next,e-=1;for(;e<0;)t=t.prev,e+=1;return t}computeNormal(){const e=this.edge,t=e.next;let i=t.next;const o=c([],t.head().point,e.head().point),l=[],u=[];for(this.nVertices=2,this.normal=[0,0,0];i!==e;)r(u,o),c(o,i.head().point,e.head().point),s(this.normal,this.normal,n(l,u,o)),i=i.next,this.nVertices+=1;this.area=a(this.normal),this.normal=h(this.normal,this.normal,1/this.area)}computeNormalMinArea(e){if(this.computeNormal(),this.areat&&(e=i,t=s),i=i.next}while(i!==this.edge);const r=e.tail().point,n=e.head().point,a=c([],n,r),u=Math.sqrt(t);h(a,a,1/u);const d=o(this.normal,a);h(a,a,-d),s(this.normal,this.normal,a),l(this.normal,this.normal)}}computeCentroid(){this.centroid=[0,0,0];let e=this.edge;do{s(this.centroid,this.centroid,e.head().point),e=e.next}while(e!==this.edge);h(this.centroid,this.centroid,1/this.nVertices)}computeNormalAndCentroid(e){void 0!==e?this.computeNormalMinArea(e):this.computeNormal(),this.computeCentroid(),this.offset=o(this.normal,this.centroid)}distanceToPlane(e){return o(this.normal,e)-this.offset}connectHalfEdges(e,t){let i;if(e.opposite.face===t.opposite.face){const s=t.opposite.face;let r;e===this.edge&&(this.edge=t),3===s.nVertices?(r=t.opposite.prev.opposite,s.mark=2,i=s):(r=t.opposite.next,s.edge===r.prev&&(s.edge=r),r.prev=r.prev.prev,r.prev.next=r),t.prev=e.prev,t.prev.next=t,t.setOpposite(r),s.computeNormalAndCentroid()}else e.next=t,t.prev=e;return i}mergeAdjacentFaces(e,t){const i=e.opposite,s=i.face;t.push(s),s.mark=2;let r,n,o=e.prev,a=e.next,l=i.prev,h=i.next;for(;o.opposite.face===s;)o=o.prev,h=h.next;for(;a.opposite.face===s;)a=a.next,l=l.prev;for(r=h;r!==l.next;r=r.next)r.face=this;return this.edge=a,n=this.connectHalfEdges(l,a),n&&t.push(n),n=this.connectHalfEdges(o,h),n&&t.push(n),this.computeNormalAndCentroid(),t}collectIndices(){const e=[];let t=this.edge;do{e.push(t.head().index),t=t.next}while(t!==this.edge);return e}static createTriangle(e,t,i,s=0){const r=new d,n=new u(e,r),o=new u(t,r),a=new u(i,r);return n.next=a.prev=o,o.next=n.prev=a,a.next=o.prev=n,r.edge=n,r.computeNormalAndCentroid(s),r}}t.exports={VISIBLE:0,NON_CONVEX:1,DELETED:2,Face:d}},{"../../../maths/vec3/add":224,"../../../maths/vec3/copy":227,"../../../maths/vec3/cross":229,"../../../maths/vec3/dot":232,"../../../maths/vec3/length":238,"../../../maths/vec3/normalize":244,"../../../maths/vec3/scale":249,"../../../maths/vec3/subtract":253,"./HalfEdge":357}],357:[function(e,t,i){const s=e("../../../maths/vec3/distance"),r=e("../../../maths/vec3/squaredDistance");t.exports=class{constructor(e,t){this.vertex=e,this.face=t,this.next=null,this.prev=null,this.opposite=null}head(){return this.vertex}tail(){return this.prev?this.prev.vertex:null}length(){return this.tail()?s(this.tail().point,this.head().point):-1}lengthSquared(){return this.tail()?r(this.tail().point,this.head().point):-1}setOpposite(e){this.opposite=e,e.opposite=this}}},{"../../../maths/vec3/distance":230,"../../../maths/vec3/squaredDistance":251}],358:[function(e,t,i){const s=e("../../../maths/vec3/dot"),r=e("./point-line-distance"),n=e("./get-plane-normal"),o=e("./VertexList"),a=e("./Vertex"),{Face:l,VISIBLE:h,NON_CONVEX:c,DELETED:u}=e("./Face");t.exports=class{constructor(e){if(!Array.isArray(e))throw TypeError("input is not a valid array");if(e.length<4)throw Error("cannot build a simplex out of <4 points");this.tolerance=-1,this.nFaces=0,this.nPoints=e.length,this.faces=[],this.newFaces=[],this.claimed=new o,this.unclaimed=new o,this.vertices=[];for(let t=0;tthis.tolerance?this.addVertexToFace(s,t):this.unclaimed.add(s)}else this.unclaimed.addAll(i)}resolveUnclaimedPoints(e){let t=this.unclaimed.first();for(let i=t;i;i=t){t=i.next;let s,r=this.tolerance;for(let t=0;tr&&(r=e,s=n),r>1e3*this.tolerance)break}}s&&this.addVertexToFace(i,s)}}computeExtremes(){const e=[],t=[],i=[],s=[];let r,n;for(r=0;r<3;r+=1)i[r]=s[r]=this.vertices[0];for(r=0;r<3;r+=1)e[r]=t[r]=this.vertices[0].point[r];for(r=1;rt[n]&&(t[n]=a[n],s[n]=o)}return this.tolerance=3*Number.EPSILON*(Math.max(Math.abs(e[0]),Math.abs(t[0]))+Math.max(Math.abs(e[1]),Math.abs(t[1]))+Math.max(Math.abs(e[2]),Math.abs(t[2]))),[i,s]}createInitialSimplex(){const e=this.vertices,[t,i]=this.computeExtremes();let o,a,h,c,u=0,d=0;for(h=0;h<3;h+=1){const e=i[h].point[h]-t[h].point[h];e>u&&(u=e,d=h)}const p=t[d],f=i[d];for(u=0,h=0;hu&&(u=t,o=e)}}const _=n([],p.point,f.point,o.point),m=s(p.point,_);for(u=-1,h=0;hu&&(u=t,a=e)}}const g=[];if(s(a.point,_)-m<0)for(g.push(l.createTriangle(p,f,o),l.createTriangle(a,f,p),l.createTriangle(a,o,f),l.createTriangle(a,p,o)),h=0;h<3;h+=1){const e=(h+1)%3;g[h+1].getEdge(2).setOpposite(g[0].getEdge(e)),g[h+1].getEdge(1).setOpposite(g[e+1].getEdge(0))}else for(g.push(l.createTriangle(p,o,f),l.createTriangle(a,p,f),l.createTriangle(a,f,o),l.createTriangle(a,o,p)),h=0;h<3;h+=1){const e=(h+1)%3;g[h+1].getEdge(2).setOpposite(g[0].getEdge((3-h)%3)),g[h+1].getEdge(0).setOpposite(g[e+1].getEdge(1))}for(h=0;h<4;h+=1)this.faces.push(g[h]);for(h=0;hu&&(u=i,e=g[c])}e&&this.addVertexToFace(t,e)}}}reindexFaceAndVertices(){const e=[];for(let t=0;ti&&(i=r,e=t)}return e}}computeHorizon(e,t,i,s){let r;this.deleteFaceVertices(i),i.mark=u,r=t?t.next:t=i.getEdge(0);do{const t=r.opposite,i=t.face;i.mark===h&&(i.distanceToPlane(e)>this.tolerance?this.computeHorizon(e,t,i,s):s.push(r)),r=r.next}while(r!==t)}addAdjoiningFace(e,t){const i=l.createTriangle(e,t.tail(),t.head());return this.faces.push(i),i.getEdge(-1).setOpposite(t.opposite),i.getEdge(0)}addNewFaces(e,t){let i,s;this.newFaces=[];for(let r=0;r=e.nVertices)throw Error("merge recursion limit exceeded");const n=i.opposite.face;let o=!1;if(2===t?(this.oppositeFaceDistance(i)>-this.tolerance||this.oppositeFaceDistance(i.opposite)>-this.tolerance)&&(o=!0):e.area>n.area?this.oppositeFaceDistance(i)>-this.tolerance?o=!0:this.oppositeFaceDistance(i.opposite)>-this.tolerance&&(s=!1):this.oppositeFaceDistance(i.opposite)>-this.tolerance?o=!0:this.oppositeFaceDistance(i)>-this.tolerance&&(s=!1),o){const t=e.mergeAdjacentFaces(i,[]);for(let i=0;i{const a=[0,0,0];return n(e,t,i),n(a,i,o),s(e,e,a),r(e,e)}},{"../../../maths/vec3/cross":229,"../../../maths/vec3/normalize":244,"../../../maths/vec3/subtract":253}],362:[function(e,t,i){const s=e("./QuickHull");t.exports=(e,t={})=>{const i=new s(e);return i.build(),i.collectFaces(t.skipTriangulation)}},{"./QuickHull":358}],363:[function(e,t,i){const s=e("../../../maths/vec3/cross"),r=e("../../../maths/vec3/subtract"),n=e("../../../maths/vec3/squaredLength");t.exports=(e,t,i)=>Math.sqrt(((e,t,i)=>{const o=[],a=[];r(o,i,t),r(a,e,t);const l=n(s([],a,o)),h=n(o);if(0===h)throw Error("a and b are the same point");return l/h})(e,t,i))},{"../../../maths/vec3/cross":229,"../../../maths/vec3/squaredLength":252,"../../../maths/vec3/subtract":253}],364:[function(e,t,i){const s=e("../../geometries/geom2"),r=e("../../geometries/geom3"),n=e("../../geometries/path2");t.exports=e=>{const t=new Set,i=[],o=e=>{const s=e.toString();t.has(s)||(i.push(e),t.add(s))};return e.forEach((e=>{s.isA(e)?s.toPoints(e).forEach(o):r.isA(e)?r.toPoints(e).forEach((e=>e.forEach(o))):n.isA(e)&&n.toPoints(e).forEach(o)})),i}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78}],365:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../measurements/measureEpsilon"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("../../geometries/path2"),l=e("./snapPolygons"),h=e("./mergePolygons"),c=e("./insertTjunctions"),u=e("./triangulatePolygons");t.exports=(e,...t)=>{if(0===(t=s(t)).length)throw new Error("wrong number of arguments");const i=t.map((t=>{if(a.isA(t))return((e,t)=>t)(0,t);if(n.isA(t))return((e,t)=>t)(0,t);if(o.isA(t))return((e,t)=>{const{snap:i,simplify:s,triangulate:n}=Object.assign({},{snap:!1,simplify:!1,triangulate:!1},e),a=r(t);let d=o.toPolygons(t);i&&(d=l(a,d)),s&&(d=h(a,d)),n&&(d=c(d),d=u(a,d));const p=Object.assign({},t);return p.polygons=d,p})(e,t);throw new Error("invalid geometry")}));return 1===i.length?i[0]:i}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../measurements/measureEpsilon":278,"../../utils/flatten":412,"./insertTjunctions":367,"./mergePolygons":368,"./snapPolygons":372,"./triangulatePolygons":373}],366:[function(e,t,i){t.exports={generalize:e("./generalize"),snap:e("./snap"),retessellate:e("./retessellate")}},{"./generalize":365,"./retessellate":370,"./snap":371}],367:[function(e,t,i){const s=e("../../maths/constants"),r=e("../../maths/vec3"),n=e("../../geometries/poly3"),o=e=>`${e}`,a=(e,t,i,s,r,n)=>{const a=o(s),h=o(r),c=`${a}/${h}`,u=`${h}/${a}`;if(e.has(u))return l(e,t,i,r,s,null),null;const d={vertex0:s,vertex1:r,polygonindex:n};return e.has(c)?e.get(c).push(d):e.set(c,[d]),t.has(a)?t.get(a).push(c):t.set(a,[c]),i.has(h)?i.get(h).push(c):i.set(h,[c]),c},l=(e,t,i,s,r,n)=>{const a=o(s),l=o(r),h=`${a}/${l}`;let c=-1;const u=e.get(h);for(let e=0;e{const t=new Map;for(let i=0;i=3){let e=s.vertices[0],n=o(e);for(let a=0;a0){const i=new Map,h=new Map,c=new Map;for(const[e,s]of t)c.set(e,!0),s.forEach((t=>{const s=o(t.vertex0),r=o(t.vertex1);i.has(s)?i.get(s).push(e):i.set(s,[e]),h.has(r)?h.get(r).push(e):h.set(r,[e])}));const u=e.slice(0);for(;0!==t.size;){for(const e of t.keys())c.set(e,!0);let e=!1;for(;;){const d=Array.from(c.keys());if(0===d.length)break;const p=d[0];let f=!0;if(t.has(p)){const d=t.get(p)[0];for(let p=0;p<2;p++){const _=0===p?d.vertex0:d.vertex1,m=0===p?d.vertex1:d.vertex0,g=o(_),v=o(m);let x=[];0===p?h.has(g)&&(x=h.get(g)):i.has(g)&&(x=i.get(g));for(let d=0;d0&&E<1){const _=r.scale(r.create(),x,E);if(r.add(_,_,d),r.squaredDistance(_,g){const t=n.toPoints(e),i=[];for(let e=0;e{const i=`${t.v1}:${t.v2}`;e.set(i,t)},l=(e,t)=>{const i=`${t.v1}:${t.v2}`;e.delete(i)},h=(e,t)=>{const i=`${t.v2}:${t.v1}`;return e.get(i)},c=(e,t,i)=>{let s=e.prev.v1,r=e.prev.v2,n=t.next.v2;const o=p(s,r,n,i);return s=t.prev.v1,r=t.prev.v2,n=e.next.v2,[o,p(s,r,n,i)]},u=r.create(),d=r.create(),p=(e,t,i,s)=>{const n=r.subtract(u,t,e),o=r.subtract(d,i,t);return r.cross(n,n,o),r.dot(n,s)};t.exports=(e,t)=>{const i=[];t.forEach((e=>{const t=i.find((t=>{return i=t[0],r=n.plane(e),Math.abs(i[3]-r[3])<15e-8&&s(i,r);var i,r}));t?t[1].push(e):i.push([n.plane(e),[e]])}));let r=[];return i.forEach((e=>{const t=(e=>{if(e.length<2)return e;const t=e[0].plane,i=e.slice(),s=new Map;for(;i.length>0;){const e=i.shift(),r=o(e);for(let e=0;e=0&&e[1]>=0){const t=n.next,r=i.next;i.prev.next=n.next,i.next.prev=n.prev,n.prev.next=i.next,n.next.prev=i.prev,i.v1=null,i.v2=null,i.next=null,i.prev=null,l(s,n),n.v1=null,n.v2=null,n.next=null,n.prev=null;const o=(e,t,i)=>{const s={v1:i.v1,v2:t.v2,next:t.next,prev:i.prev};i.prev.next=s,t.next.prev=s,l(e,t),t.v1=null,t.v2=null,t.next=null,t.prev=null,l(e,i),i.v1=null,i.v2=null,i.next=null,i.prev=null};0===e[0]&&o(s,t,t.prev),0===e[1]&&o(s,r,r.prev)}}else i.next&&a(s,i)}}const r=[];return s.forEach((e=>{const t=(e=>{let t;const i=[];for(;e.next;){const t=e.next;i.push(e.v1),e.v1=null,e.v2=null,e.next=null,e.prev=null,e=t}return i.length>0&&(t=n.create(i)),t})(e);t&&r.push(t)})),s.clear(),r})(e[1]);r=r.concat(t)})),r}},{"../../geometries/poly3":95,"../../maths/utils/aboutEqualNormals":182,"../../maths/vec3":237}],369:[function(e,t,i){const{EPS:s}=e("../../maths/constants"),r=e("../../maths/line2"),n=e("../../maths/vec2"),o=e("../../maths/OrthoNormalBasis"),a=e("../../maths/utils/interpolateBetween2DPointsForY"),{insertSorted:l,fnNumberSort:h}=e("../../utils"),c=e("../../geometries/poly3");t.exports=e=>{if(e.length<2)return e;const t=[],i=e.length,u=c.plane(e[0]),d=new o(u),p=[],f=[],_=new Map,m=new Map,g=new Map,v=10/s;for(let t=0;t0){let e,a;for(let l=0;la)&&(a=u);let p=m.get(u);p||(p={},m.set(u,p)),p[t]=!0}if(e>=a)s=[],r=0,o=-1;else{let i=_.get(e);i||(i=[],_.set(e,i)),i.push(t)}}s.reverse(),o=r-o-1,p.push(s),f.push(o)}const x=[];m.forEach(((e,t)=>x.push(t))),x.sort(h);let T=[],S=[];for(let e=0;e=r&&(e=0),s[e][1]!==o)break;n=e}let l=a-1;if(l<0&&(l=r-1),s[l][1]===o&&(a=l),n!==t.leftvertexindex&&n===a)T.splice(e,1),--e;else{t.leftvertexindex=n,t.rightvertexindex=a,t.topleft=s[n],t.topright=s[a];let e=n+1;e>=r&&(e=0),t.bottomleft=s[e];let i=a-1;i<0&&(i=r-1),t.bottomright=s[i]}}}let g;if(e>=x.length-1)T=[],g=null;else{g=Number(x[e+1]);const t=.5*(o+g),i=_.get(o);for(const e in i){const s=i[e],r=p[s],n=r.length,h=f[s];let c=h;for(;;){let e=c+1;if(e>=n&&(e=0),r[e][1]!==o)break;if(e===h)break;c=e}let u=h;for(;;){let e=u-1;if(e<0&&(e=n-1),r[e][1]!==o)break;if(e===c)break;u=e}let d=c+1;d>=n&&(d=0);let _=u-1;_<0&&(_=n-1);const m={polygonindex:s,leftvertexindex:c,rightvertexindex:u,topleft:r[c],topright:r[u],bottomleft:r[d],bottomright:r[_]};l(T,m,((e,i)=>{const s=a(e.topleft,e.bottomleft,t),r=a(i.topleft,i.bottomleft,t);return s>r?1:s0){const e=i[i.length-1],t=n.distance(p.topleft,e.topright),r=n.distance(p.bottomleft,e.bottomright);t0){const e=new Set,o=new Set;for(let t=0;t=0)&&(f||d>=0)&&(a.outpolygon=i.outpolygon,a.leftlinecontinues=p,a.rightlinecontinues=f,e.add(t));break}}}for(let i=0;is&&e.outpolygon.leftpoints.push(e.bottomleft),e.outpolygon.leftpoints.reverse();const r=e.outpolygon.rightpoints.concat(e.outpolygon.leftpoints).map((e=>d.to3D(e))),o=c.fromPointsAndPlane(r,u);o.vertices.length&&t.push(o)}}for(let e=0;es&&t.outpolygon.rightpoints.push(t.topright))}S=i}return t}},{"../../geometries/poly3":95,"../../maths/OrthoNormalBasis":109,"../../maths/constants":110,"../../maths/line2":121,"../../maths/utils/interpolateBetween2DPointsForY":185,"../../maths/vec2":206,"../../utils":414}],370:[function(e,t,i){const s=e("../../geometries/geom3"),r=e("../../geometries/poly3"),{NEPS:n}=e("../../maths/constants"),o=e("./reTesselateCoplanarPolygons"),a=(e,t)=>(i,s)=>i.plane[e]-s.plane[e]>t?1:s.plane[e]-i.plane[e]>t?-1:0;t.exports=e=>{if(e.isRetesselated)return e;const t=(e=>{let t=[e];const i=[];for(let e=3;e>=0;e--){const s=[],r=3===e?15e-9:n;t.forEach((t=>{t.sort(a(e,r));let n=0;for(let o=1;or&&(o-n==1?i.push(t[n]):s.push(t.slice(n,o)),n=o);t.length-n==1?i.push(t[n]):s.push(t.slice(n))})),t=s}const s=[];return t.forEach((e=>{e[0]&&(s[e[0].index]=e)})),i.forEach((e=>{s[e.index]=e})),s})(s.toPolygons(e).map(((e,t)=>({vertices:e.vertices,plane:r.plane(e),index:t})))),i=[];t.forEach((e=>{if(Array.isArray(e)){const t=o(e);i.push(...t)}else i.push(e)}));const l=s.create(i);return l.isRetesselated=!0,l}},{"../../geometries/geom3":57,"../../geometries/poly3":95,"../../maths/constants":110,"./reTesselateCoplanarPolygons":369}],371:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../maths/vec2"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("../../geometries/path2"),l=e("../../measurements/measureEpsilon"),h=e("./snapPolygons");t.exports=(...e)=>{if(0===(e=s(e)).length)throw new Error("wrong number of arguments");const t=e.map((e=>a.isA(e)?(e=>{const t=l(e),i=a.toPoints(e).map((e=>r.snap(r.create(),e,t)));return a.create(i)})(e):n.isA(e)?(e=>{const t=l(e);let i=n.toSides(e).map((e=>[r.snap(r.create(),e[0],t),r.snap(r.create(),e[1],t)]));return i=i.filter((e=>!r.equals(e[0],e[1]))),n.create(i)})(e):o.isA(e)?(e=>{const t=l(e),i=o.toPolygons(e),s=h(t,i);return o.create(s)})(e):e));return 1===t.length?t[0]:t}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../maths/vec2":206,"../../measurements/measureEpsilon":278,"../../utils/flatten":412,"./snapPolygons":372}],372:[function(e,t,i){const s=e("../../maths/vec3"),r=e("../../geometries/poly3");t.exports=(e,t)=>{let i=t.map((t=>{const i=t.vertices.map((t=>s.snap(s.create(),t,e))),n=[];for(let e=0;e((e,t)=>{const i=Math.abs(r.measureArea(t));return Number.isFinite(i)&&i>e})(n,e))),i}},{"../../geometries/poly3":95,"../../maths/vec3":237}],373:[function(e,t,i){const s=e("../../maths/vec3"),r=e("../../geometries/poly3");t.exports=(e,t)=>{const i=[];return t.forEach((t=>{((e,t,i)=>{const n=t.vertices.length;if(n>3){if(n>4){const o=[0,0,0];t.vertices.forEach((e=>s.add(o,o,e))),s.snap(o,s.divide(o,o,[n,n,n]),e);for(let e=0;e{const s=n(e),r=[0,0,0];for(let e=0;e<3;e++)"center"===t[e]?r[e]=i[e]-(s[0][e]+s[1][e])/2:"max"===t[e]?r[e]=i[e]-s[1][e]:"min"===t[e]&&(r[e]=i[e]-s[0][e]);return o(r,e)};t.exports=(e,...t)=>{e=(e=>{if(!Array.isArray(e.modes)||e.modes.length>3)throw new Error("align(): modes must be an array of length <= 3");if(e.modes=r(e.modes,"none",3),3!==e.modes.filter((e=>["center","max","min","none"].includes(e))).length)throw new Error('align(): all modes must be one of "center", "max" or "min"');if(!Array.isArray(e.relativeTo)||e.relativeTo.length>3)throw new Error("align(): relativeTo must be an array of length <= 3");if(e.relativeTo=r(e.relativeTo,0,3),3!==e.relativeTo.filter((e=>Number.isFinite(e)||null==e)).length)throw new Error("align(): all relativeTo values must be a number, or null.");if("boolean"!=typeof e.grouped)throw new Error("align(): grouped must be a boolean value.");return e})(e=Object.assign({},{modes:["center","center","min"],relativeTo:[0,0,0],grouped:!1},e));let{modes:i,relativeTo:o,grouped:l}=e;if(0===(t=s(t)).length)throw new Error("align(): No geometries were provided to act upon");if(o.filter((e=>null==e)).length){const e=n(t);o=((e,t,i)=>{for(let s=0;s<3;s++)null==e[s]&&("center"===t[s]?e[s]=(i[0][s]+i[1][s])/2:"max"===t[s]?e[s]=i[1][s]:"min"===t[s]&&(e[s]=i[0][s]));return e})(o,i,e)}return 1===(t=l?a(t,i,o):t.map((e=>a(e,i,o)))).length?t[0]:t}},{"../../measurements/measureAggregateBoundingBox":269,"../../utils/flatten":412,"../../utils/padArrayToLength":416,"./translate":381}],375:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom2"),n=e("../../geometries/geom3"),o=e("../../geometries/path2"),a=e("../../measurements/measureBoundingBox"),{translate:l}=e("./translate"),h=(e,...t)=>{const{axes:i,relativeTo:h}=Object.assign({},{axes:[!0,!0,!0],relativeTo:[0,0,0]},e);if(0===(t=s(t)).length)throw new Error("wrong number of arguments");if(3!==h.length)throw new Error("relativeTo must be an array of length 3");e={axes:i,relativeTo:h};const c=t.map((t=>o.isA(t)||r.isA(t)||n.isA(t)?((e,t)=>{const{axes:i,relativeTo:s}=Object.assign({},{axes:[!0,!0,!0],relativeTo:[0,0,0]},e),r=a(t),n=[0,0,0];return i[0]&&(n[0]=s[0]-(r[0][0]+(r[1][0]-r[0][0])/2)),i[1]&&(n[1]=s[1]-(r[0][1]+(r[1][1]-r[0][1])/2)),i[2]&&(n[2]=s[2]-(r[0][2]+(r[1][2]-r[0][2])/2)),l(n,t)})(e,t):t));return 1===c.length?c[0]:c};t.exports={center:h,centerX:(...e)=>h({axes:[!0,!1,!1]},e),centerY:(...e)=>h({axes:[!1,!0,!1]},e),centerZ:(...e)=>h({axes:[!1,!1,!0]},e)}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../measurements/measureBoundingBox":273,"../../utils/flatten":412,"./translate":381}],376:[function(e,t,i){t.exports={align:e("./align"),center:e("./center").center,centerX:e("./center").centerX,centerY:e("./center").centerY,centerZ:e("./center").centerZ,mirror:e("./mirror").mirror,mirrorX:e("./mirror").mirrorX,mirrorY:e("./mirror").mirrorY,mirrorZ:e("./mirror").mirrorZ,rotate:e("./rotate").rotate,rotateX:e("./rotate").rotateX,rotateY:e("./rotate").rotateY,rotateZ:e("./rotate").rotateZ,scale:e("./scale").scale,scaleX:e("./scale").scaleX,scaleY:e("./scale").scaleY,scaleZ:e("./scale").scaleZ,transform:e("./transform"),translate:e("./translate").translate,translateX:e("./translate").translateX,translateY:e("./translate").translateY,translateZ:e("./translate").translateZ}},{"./align":374,"./center":375,"./mirror":377,"./rotate":378,"./scale":379,"./transform":380,"./translate":381}],377:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../maths/mat4"),n=e("../../maths/plane"),o=e("../../geometries/geom2"),a=e("../../geometries/geom3"),l=e("../../geometries/path2"),h=(e,...t)=>{const{origin:i,normal:h}=Object.assign({},{origin:[0,0,0],normal:[0,0,1]},e);if(0===(t=s(t)).length)throw new Error("wrong number of arguments");const c=n.fromNormalAndPoint(n.create(),h,i);if(Number.isNaN(c[0]))throw new Error("the given origin and normal do not define a proper plane");const u=r.mirrorByPlane(r.create(),c),d=t.map((e=>l.isA(e)?l.transform(u,e):o.isA(e)?o.transform(u,e):a.isA(e)?a.transform(u,e):e));return 1===d.length?d[0]:d};t.exports={mirror:h,mirrorX:(...e)=>h({normal:[1,0,0]},e),mirrorY:(...e)=>h({normal:[0,1,0]},e),mirrorZ:(...e)=>h({normal:[0,0,1]},e)}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../maths/mat4":159,"../../maths/plane":178,"../../utils/flatten":412}],378:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../maths/mat4"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("../../geometries/path2"),l=(e,...t)=>{if(!Array.isArray(e))throw new Error("angles must be an array");if(0===(t=s(t)).length)throw new Error("wrong number of arguments");for(e=e.slice();e.length<3;)e.push(0);const i=e[2],l=e[1],h=e[0],c=r.fromTaitBryanRotation(r.create(),i,l,h),u=t.map((e=>a.isA(e)?a.transform(c,e):n.isA(e)?n.transform(c,e):o.isA(e)?o.transform(c,e):e));return 1===u.length?u[0]:u};t.exports={rotate:l,rotateX:(e,...t)=>l([e,0,0],t),rotateY:(e,...t)=>l([0,e,0],t),rotateZ:(e,...t)=>l([0,0,e],t)}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../maths/mat4":159,"../../utils/flatten":412}],379:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../maths/mat4"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("../../geometries/path2"),l=(e,...t)=>{if(!Array.isArray(e))throw new Error("factors must be an array");if(0===(t=s(t)).length)throw new Error("wrong number of arguments");for(e=e.slice();e.length<3;)e.push(1);if(e[0]<=0||e[1]<=0||e[2]<=0)throw new Error("factors must be positive");const i=r.fromScaling(r.create(),e),l=t.map((e=>a.isA(e)?a.transform(i,e):n.isA(e)?n.transform(i,e):o.isA(e)?o.transform(i,e):e));return 1===l.length?l[0]:l};t.exports={scale:l,scaleX:(e,...t)=>l([e,1,1],t),scaleY:(e,...t)=>l([1,e,1],t),scaleZ:(e,...t)=>l([1,1,e],t)}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../maths/mat4":159,"../../utils/flatten":412}],380:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../geometries/geom2"),n=e("../../geometries/geom3"),o=e("../../geometries/path2");t.exports=(e,...t)=>{if(0===(t=s(t)).length)throw new Error("wrong number of arguments");const i=t.map((t=>o.isA(t)?o.transform(e,t):r.isA(t)?r.transform(e,t):n.isA(t)?n.transform(e,t):t));return 1===i.length?i[0]:i}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../utils/flatten":412}],381:[function(e,t,i){const s=e("../../utils/flatten"),r=e("../../maths/mat4"),n=e("../../geometries/geom2"),o=e("../../geometries/geom3"),a=e("../../geometries/path2"),l=(e,...t)=>{if(!Array.isArray(e))throw new Error("offset must be an array");if(0===(t=s(t)).length)throw new Error("wrong number of arguments");for(e=e.slice();e.length<3;)e.push(0);const i=r.fromTranslation(r.create(),e),l=t.map((e=>a.isA(e)?a.transform(i,e):n.isA(e)?n.transform(i,e):o.isA(e)?o.transform(i,e):e));return 1===l.length?l[0]:l};t.exports={translate:l,translateX:(e,...t)=>l([e,0,0],t),translateY:(e,...t)=>l([0,e,0],t),translateZ:(e,...t)=>l([0,0,e],t)}},{"../../geometries/geom2":42,"../../geometries/geom3":57,"../../geometries/path2":78,"../../maths/mat4":159,"../../utils/flatten":412}],382:[function(e,t,i){const{EPS:s,TAU:r}=e("../maths/constants"),n=e("../maths/vec2"),o=e("../geometries/path2"),{isGT:a,isGTE:l,isNumberArray:h}=e("./commonChecks");t.exports=e=>{const t={center:[0,0],radius:1,startAngle:0,endAngle:r,makeTangent:!1,segments:32};let{center:i,radius:c,startAngle:u,endAngle:d,makeTangent:p,segments:f}=Object.assign({},t,e);if(!h(i,2))throw new Error("center must be an array of X and Y values");if(!a(c,0))throw new Error("radius must be greater than zero");if(!l(u,0))throw new Error("startAngle must be positive");if(!l(d,0))throw new Error("endAngle must be positive");if(!l(f,4))throw new Error("segments must be four or more");u%=r,d%=r;let _=r;ud&&(_=d+(r-u));const m=Math.acos((c*c+c*c-s*s)/(2*c*c)),g=n.clone(i);let v;const x=[];if(_.25&&(t=.25);const i=p?e+2:e;for(let s=0;s<=i;s++){let i=s;p&&(i=(s-1)*(e-2*t)/e+t,i<0&&(i=0),i>e&&(i=e));const r=u+i*(_/e);v=n.fromAngleRadians(n.create(),r),n.scale(v,v,c),n.add(v,v,g),x.push(v)}}return o.fromPoints({closed:!1},x)}},{"../geometries/path2":78,"../maths/constants":110,"../maths/vec2":206,"./commonChecks":384}],383:[function(e,t,i){const{TAU:s}=e("../maths/constants"),r=e("./ellipse"),{isGTE:n}=e("./commonChecks");t.exports=e=>{const t={center:[0,0],radius:1,startAngle:0,endAngle:s,segments:32};let{center:i,radius:o,startAngle:a,endAngle:l,segments:h}=Object.assign({},t,e);if(!n(o,0))throw new Error("radius must be positive");return o=[o,o],r({center:i,radius:o,startAngle:a,endAngle:l,segments:h})}},{"../maths/constants":110,"./commonChecks":384,"./ellipse":389}],384:[function(e,t,i){t.exports={isNumberArray:(e,t)=>!!(Array.isArray(e)&&e.length>=t)&&e.every((e=>Number.isFinite(e))),isGT:(e,t)=>Number.isFinite(e)&&e>t,isGTE:(e,t)=>Number.isFinite(e)&&e>=t}},{}],385:[function(e,t,i){const s=e("./cuboid"),{isGTE:r}=e("./commonChecks");t.exports=e=>{let{center:t,size:i}=Object.assign({},{center:[0,0,0],size:2},e);if(!r(i,0))throw new Error("size must be positive");return i=[i,i,i],s({center:t,size:i})}},{"./commonChecks":384,"./cuboid":386}],386:[function(e,t,i){const s=e("../geometries/geom3"),r=e("../geometries/poly3"),{isNumberArray:n}=e("./commonChecks");t.exports=e=>{const{center:t,size:i}=Object.assign({},{center:[0,0,0],size:[2,2,2]},e);if(!n(t,3))throw new Error("center must be an array of X, Y and Z values");if(!n(i,3))throw new Error("size must be an array of width, depth and height values");if(!i.every((e=>e>=0)))throw new Error("size values must be positive");return 0===i[0]||0===i[1]||0===i[2]?s.create():s.create([[[0,4,6,2],[-1,0,0]],[[1,3,7,5],[1,0,0]],[[0,1,5,4],[0,-1,0]],[[2,6,7,3],[0,1,0]],[[0,2,3,1],[0,0,-1]],[[4,5,7,6],[0,0,1]]].map((e=>{const s=e[0].map((e=>[t[0]+i[0]/2*(2*!!(1&e)-1),t[1]+i[1]/2*(2*!!(2&e)-1),t[2]+i[2]/2*(2*!!(4&e)-1)]));return r.create(s)})))}},{"../geometries/geom3":57,"../geometries/poly3":95,"./commonChecks":384}],387:[function(e,t,i){const s=e("../geometries/geom3"),r=e("./cylinderElliptic"),{isGTE:n}=e("./commonChecks");t.exports=e=>{const{center:t,height:i,radius:o,segments:a}=Object.assign({},{center:[0,0,0],height:2,radius:1,segments:32},e);if(!n(o,0))throw new Error("radius must be positive");return 0===i||0===o?s.create():r({center:t,height:i,startRadius:[o,o],endRadius:[o,o],segments:a})}},{"../geometries/geom3":57,"./commonChecks":384,"./cylinderElliptic":388}],388:[function(e,t,i){const{EPS:s,TAU:r}=e("../maths/constants"),n=e("../maths/vec3"),o=e("../geometries/geom3"),a=e("../geometries/poly3"),{sin:l,cos:h}=e("../maths/utils/trigonometry"),{isGT:c,isGTE:u,isNumberArray:d}=e("./commonChecks");t.exports=e=>{const t={center:[0,0,0],height:2,startRadius:[1,1],startAngle:0,endRadius:[1,1],endAngle:r,segments:32};let{center:i,height:p,startRadius:f,startAngle:_,endRadius:m,endAngle:g,segments:v}=Object.assign({},t,e);if(!d(i,3))throw new Error("center must be an array of X, Y and Z values");if(!c(p,0))throw new Error("height must be greater then zero");if(!d(f,2))throw new Error("startRadius must be an array of X and Y values");if(!f.every((e=>e>=0)))throw new Error("startRadius values must be positive");if(!d(m,2))throw new Error("endRadius must be an array of X and Y values");if(!m.every((e=>e>=0)))throw new Error("endRadius values must be positive");if(m.every((e=>0===e))&&f.every((e=>0===e)))throw new Error("at least one radius must be positive");if(!u(_,0))throw new Error("startAngle must be positive");if(!u(g,0))throw new Error("endAngle must be positive");if(!u(v,4))throw new Error("segments must be four or more");_%=r,g%=r;let x=r;_g&&(x=g+(r-_));const T=Math.min(f[0],f[1],m[0],m[1]),S=Math.acos((T*T+T*T-s*s)/(2*T*T));if(x{const s=t*x+_;return n.scale(I,A,i[0]*h(s)),n.scale(P,R,i[1]*l(s)),n.add(I,I,P),n.scale(M,y,e),n.add(M,M,b),n.add(n.create(),I,M)},O=(...e)=>{const t=e.map((e=>n.add(n.create(),e,i)));return a.create(t)},N=[];for(let e=0;e0&&f[1]>0&&N.push(O(b,D(0,i,f),D(0,t,f))),(f[0]>0||f[1]>0)&&N.push(O(D(0,t,f),D(0,i,f),D(1,t,m))),m[0]>0&&m[1]>0&&N.push(O(C,D(1,t,m),D(1,i,m))),(m[0]>0||m[1]>0)&&N.push(O(D(1,t,m),D(0,i,f),D(1,i,m))))}return x{const t={center:[0,0],radius:[1,1],startAngle:0,endAngle:r,segments:32};let{center:i,radius:u,startAngle:d,endAngle:p,segments:f}=Object.assign({},t,e);if(!c(i,2))throw new Error("center must be an array of X and Y values");if(!c(u,2))throw new Error("radius must be an array of X and Y values");if(!u.every((e=>e>=0)))throw new Error("radius values must be positive");if(!h(d,0))throw new Error("startAngle must be positive");if(!h(p,0))throw new Error("endAngle must be positive");if(!h(f,3))throw new Error("segments must be three or more");if(0===u[0]||0===u[1])return o.create();d%=r,p%=r;let _=r;dp&&(_=p+(r-d));const m=Math.min(u[0],u[1]);if(_{const{center:t,radius:i,segments:u,axes:d}=Object.assign({},{center:[0,0,0],radius:[1,1,1],segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},e);if(!c(t,3))throw new Error("center must be an array of X, Y and Z values");if(!c(i,3))throw new Error("radius must be an array of X, Y and Z values");if(!i.every((e=>e>=0)))throw new Error("radius values must be positive");if(!h(u,4))throw new Error("segments must be four or more");if(0===i[0]||0===i[1]||0===i[2])return n.create();const p=r.scale(r.create(),r.normalize(r.create(),d[0]),i[0]),f=r.scale(r.create(),r.normalize(r.create(),d[1]),i[1]),_=r.scale(r.create(),r.normalize(r.create(),d[2]),i[2]),m=Math.round(u/4);let g;const v=[],x=r.create(),T=r.create();for(let e=0;e<=u;e++){const i=s*e/u,n=r.add(r.create(),r.scale(x,p,l(i)),r.scale(T,f,a(i)));if(e>0){let e,i;for(let h=0;h<=m;h++){const c=s/4*h/m,u=l(c),d=a(c);if(h>0){let s,a=[];s=r.subtract(r.create(),r.scale(x,g,e),r.scale(T,_,i)),a.push(r.add(s,s,t)),s=r.subtract(r.create(),r.scale(x,n,e),r.scale(T,_,i)),a.push(r.add(s,s,t)),h{let{radius:t,frequency:i}=Object.assign({},{radius:1,frequency:6},e);if(!a(t,0))throw new Error("radius must be positive");if(!a(i,6))throw new Error("frequency must be six or more");if(0===t)return n.create();i=Math.floor(i/6);const l=[[.850651,0,-.525731],[.850651,-0,.525731],[-.850651,-0,.525731],[-.850651,0,-.525731],[0,-.525731,.850651],[0,.525731,.850651],[0,.525731,-.850651],[0,-.525731,-.850651],[-.525731,-.850651,-0],[.525731,-.850651,-0],[.525731,.850651,0],[-.525731,.850651,0]],h=[[0,9,1],[1,10,0],[6,7,0],[10,6,0],[7,9,0],[5,1,4],[4,1,9],[5,10,1],[2,8,3],[3,11,2],[2,5,4],[4,8,2],[2,11,5],[3,7,6],[6,11,3],[8,7,3],[9,8,4],[11,10,5],[10,11,6],[8,9,7]],c=(e,t,i)=>{const s=e[0],n=e[1],o=e[2];let a=i;const l=[],h=[];for(let e=0;e{const s=1-i,r=[];for(let n=0;n<3;n++)r[n]=e[n]*s+t[n]*i;return r};let d=[],p=[],f=0;for(let e=0;e{if(!Array.isArray(e))throw new Error("points must be an array");return s.fromPoints({},e)}},{"../geometries/path2":78}],394:[function(e,t,i){const s=e("../geometries/geom2");t.exports=e=>{const{points:t,paths:i}=Object.assign({},{points:[],paths:[]},e);if(!Array.isArray(t)||!Array.isArray(i))throw new Error("points and paths must be arrays");let r=t;Array.isArray(t[0])&&(Array.isArray(t[0][0])||(r=[t])),r.forEach(((e,t)=>{if(!Array.isArray(e))throw new Error("list of points "+t+" must be an array");if(e.length<3)throw new Error("list of points "+t+" must contain three or more points");e.forEach(((e,i)=>{if(!Array.isArray(e))throw new Error("list of points "+t+", point "+i+" must be an array");if(e.length<2)throw new Error("list of points "+t+", point "+i+" must contain by X and Y values")}))}));let n=i;if(0===i.length){let e=0;n=r.map((t=>t.map((t=>e++))))}const o=[];r.forEach((e=>e.forEach((e=>o.push(e)))));let a=[];return n.forEach((e=>{const t=e.map((e=>o[e])),i=s.fromPoints(t);a=a.concat(s.toSides(i))})),s.create(a)}},{"../geometries/geom2":42}],395:[function(e,t,i){const s=e("../geometries/geom3"),r=e("../geometries/poly3"),{isNumberArray:n}=e("./commonChecks");t.exports=e=>{const{points:t,faces:i,colors:o,orientation:a}=Object.assign({},{points:[],faces:[],colors:void 0,orientation:"outward"},e);if(!Array.isArray(t)||!Array.isArray(i))throw new Error("points and faces must be arrays");if(t.length<3)throw new Error("three or more points are required");if(i.length<1)throw new Error("one or more faces are required");if(o){if(!Array.isArray(o))throw new Error("colors must be an array");if(o.length!==i.length)throw new Error("faces and colors must have the same length")}t.forEach(((e,t)=>{if(!n(e,3))throw new Error(`point ${t} must be an array of X, Y, Z values`)})),i.forEach(((e,t)=>{if(e.length<3)throw new Error(`face ${t} must contain 3 or more indexes`);if(!n(e,e.length))throw new Error(`face ${t} must be an array of numbers`)})),"outward"!==a&&i.forEach((e=>e.reverse()));const l=i.map(((e,i)=>{const s=r.create(e.map((e=>t[e])));return o&&o[i]&&(s.color=o[i]),s}));return s.create(l)}},{"../geometries/geom3":57,"../geometries/poly3":95,"./commonChecks":384}],396:[function(e,t,i){const s=e("../maths/vec2"),r=e("../geometries/geom2"),{isNumberArray:n}=e("./commonChecks");t.exports=e=>{const{center:t,size:i}=Object.assign({},{center:[0,0],size:[2,2]},e);if(!n(t,2))throw new Error("center must be an array of X and Y values");if(!n(i,2))throw new Error("size must be an array of X and Y values");if(!i.every((e=>e>=0)))throw new Error("size values must be positive");if(0===i[0]||0===i[1])return r.create();const o=[i[0]/2,i[1]/2],a=[o[0],-o[1]],l=[s.subtract(s.create(),t,o),s.add(s.create(),t,a),s.add(s.create(),t,o),s.subtract(s.create(),t,a)];return r.fromPoints(l)}},{"../geometries/geom2":42,"../maths/vec2":206,"./commonChecks":384}],397:[function(e,t,i){const{EPS:s,TAU:r}=e("../maths/constants"),n=e("../maths/vec2"),o=e("../maths/vec3"),a=e("../geometries/geom3"),l=e("../geometries/poly3"),{sin:h,cos:c}=e("../maths/utils/trigonometry"),{isGTE:u,isNumberArray:d}=e("./commonChecks"),p=e("./cuboid"),f=(e,t,i,a,l,u)=>{const d=r/4*l/a,p=c(d),f=h(d),_=a-l;let m=i*p,g=t[2]-(i-i*f);u||(g=i-i*f-t[2]),m=m>s?m:0;const v=o.add(o.create(),e,[t[0]-i,t[1]-i,g]),x=o.add(o.create(),e,[i-t[0],t[1]-i,g]),T=o.add(o.create(),e,[i-t[0],i-t[1],g]),S=o.add(o.create(),e,[t[0]-i,i-t[1],g]),E=[],b=[],C=[],y=[];for(let e=0;e<=_;e++){const t=_>0?r/4*e/_:0,i=n.fromAngleRadians(n.create(),t);n.scale(i,i,m);const s=o.fromVec2(o.create(),i);E.push(o.add(o.create(),v,s)),o.rotateZ(s,s,[0,0,0],r/4),b.push(o.add(o.create(),x,s)),o.rotateZ(s,s,[0,0,0],r/4),C.push(o.add(o.create(),T,s)),o.rotateZ(s,s,[0,0,0],r/4),y.push(o.add(o.create(),S,s))}return u?[E,b,C,y]:(E.reverse(),b.reverse(),C.reverse(),y.reverse(),[y,C,b,E])},_=(e,t)=>{const i=[];for(let s=0;s{const i=[];for(let s=0;s{e=(e=[e[3],e[2],e[1],e[0]]).map((e=>e.slice().reverse()));const i=[];e.forEach((e=>{e.forEach((e=>i.push(e)))}));const s=[];t.forEach((e=>{e.forEach((e=>s.push(e)))}));const r=[];for(let e=0;e{let{center:t,size:i,roundRadius:r,segments:n}=Object.assign({},{center:[0,0,0],size:[2,2,2],roundRadius:.2,segments:32},e);if(!d(t,3))throw new Error("center must be an array of X, Y and Z values");if(!d(i,3))throw new Error("size must be an array of X, Y and Z values");if(!i.every((e=>e>=0)))throw new Error("size values must be positive");if(!u(r,0))throw new Error("roundRadius must be positive");if(!u(n,4))throw new Error("segments must be four or more");if(0===i[0]||0===i[1]||0===i[2])return a.create();if(0===r)return p({center:t,size:i});if(i=i.map((e=>e/2)),r>i[0]-s||r>i[1]-s||r>i[2]-s)throw new Error("roundRadius must be smaller then the radius of all dimensions");n=Math.floor(n/4);let o=null,h=null,c=[];for(let e=0;e<=n;e++){const s=f(t,i,r,n,e,!0),a=f(t,i,r,n,e,!1);if(0===e&&(c=c.concat(g(a,s))),o&&(c=c.concat(_(o,s),m(o,s))),h&&(c=c.concat(_(h,a),m(h,a))),e===n){let e=s.map((e=>e[0]));c.push(l.create(e)),e=a.map((e=>e[0])),c.push(l.create(e))}o=s,h=a}return a.create(c)}},{"../geometries/geom3":57,"../geometries/poly3":95,"../maths/constants":110,"../maths/utils/trigonometry":188,"../maths/vec2":206,"../maths/vec3":237,"./commonChecks":384,"./cuboid":386}],398:[function(e,t,i){const{EPS:s,TAU:r}=e("../maths/constants"),n=e("../maths/vec3"),o=e("../geometries/geom3"),a=e("../geometries/poly3"),{sin:l,cos:h}=e("../maths/utils/trigonometry"),{isGTE:c,isNumberArray:u}=e("./commonChecks"),d=e("./cylinder");t.exports=e=>{const{center:t,height:i,radius:p,roundRadius:f,segments:_}=Object.assign({},{center:[0,0,0],height:2,radius:1,roundRadius:.2,segments:32},e);if(!u(t,3))throw new Error("center must be an array of X, Y and Z values");if(!c(i,0))throw new Error("height must be positive");if(!c(p,0))throw new Error("radius must be positive");if(!c(f,0))throw new Error("roundRadius must be positive");if(f>p)throw new Error("roundRadius must be smaller then the radius");if(!c(_,4))throw new Error("segments must be four or more");if(0===i||0===p)return o.create();if(0===f)return d({center:t,height:i,radius:p});const m=[0,0,-i/2],g=[0,0,i/2],v=n.subtract(n.create(),g,m);if(2*f>n.length(v)-s)throw new Error("height must be larger than twice roundRadius");let x;x=Math.abs(v[0])>Math.abs(v[1])?n.fromValues(0,1,0):n.fromValues(1,0,0);const T=n.scale(n.create(),n.normalize(n.create(),v),f),S=n.scale(n.create(),n.normalize(n.create(),n.cross(n.create(),T,x)),p),E=n.scale(n.create(),n.normalize(n.create(),n.cross(n.create(),S,T)),p);n.add(m,m,T),n.subtract(g,g,T);const b=Math.floor(.25*_),C=e=>{const i=e.map((e=>n.add(e,e,t)));return a.create(i)},y=[],A=n.create(),R=n.create();let I;for(let e=0;e<=_;e++){const t=r*e/_,i=n.add(n.create(),n.scale(A,S,h(t)),n.scale(R,E,l(t)));if(e>0){let e,t,s=[];s.push(n.add(n.create(),m,i)),s.push(n.add(n.create(),m,I)),s.push(n.add(n.create(),g,I)),s.push(n.add(n.create(),g,i)),y.push(C(s));for(let o=0;o<=b;o++){const a=r/4*o/b,c=h(a),u=l(a);if(o>0){let r;s=[],r=n.add(n.create(),m,n.subtract(A,n.scale(A,I,e),n.scale(R,T,t))),s.push(r),r=n.add(n.create(),m,n.subtract(A,n.scale(A,i,e),n.scale(R,T,t))),s.push(r),o{let{center:t,size:i,roundRadius:c,segments:u}=Object.assign({},{center:[0,0],size:[2,2],roundRadius:.2,segments:32},e);if(!l(t,2))throw new Error("center must be an array of X and Y values");if(!l(i,2))throw new Error("size must be an array of X and Y values");if(!i.every((e=>e>=0)))throw new Error("size values must be positive");if(!a(c,0))throw new Error("roundRadius must be positive");if(!a(u,4))throw new Error("segments must be four or more");if(0===i[0]||0===i[1])return o.create();if(0===c)return h({center:t,size:i});if(i=i.map((e=>e/2)),c>i[0]-s||c>i[1]-s)throw new Error("roundRadius must be smaller then the radius of all dimensions");const d=Math.floor(u/4),p=n.add(n.create(),t,[i[0]-c,i[1]-c]),f=n.add(n.create(),t,[c-i[0],i[1]-c]),_=n.add(n.create(),t,[c-i[0],c-i[1]]),m=n.add(n.create(),t,[i[0]-c,c-i[1]]),g=[],v=[],x=[],T=[];for(let e=0;e<=d;e++){const t=r/4*e/d,i=n.fromAngleRadians(n.create(),t);n.scale(i,i,c),g.push(n.add(n.create(),p,i)),n.rotate(i,i,n.create(),r/4),v.push(n.add(n.create(),f,i)),n.rotate(i,i,n.create(),r/4),x.push(n.add(n.create(),_,i)),n.rotate(i,i,n.create(),r/4),T.push(n.add(n.create(),m,i))}return o.fromPoints(g.concat(v,x,T))}},{"../geometries/geom2":42,"../maths/constants":110,"../maths/vec2":206,"./commonChecks":384,"./rectangle":396}],400:[function(e,t,i){const s=e("./ellipsoid"),{isGTE:r}=e("./commonChecks");t.exports=e=>{let{center:t,radius:i,segments:n,axes:o}=Object.assign({},{center:[0,0,0],radius:1,segments:32,axes:[[1,0,0],[0,-1,0],[0,0,1]]},e);if(!r(i,0))throw new Error("radius must be positive");return i=[i,i,i],s({center:t,radius:i,segments:n,axes:o})}},{"./commonChecks":384,"./ellipsoid":390}],401:[function(e,t,i){const s=e("./rectangle"),{isGTE:r}=e("./commonChecks");t.exports=e=>{let{center:t,size:i}=Object.assign({},{center:[0,0],size:2},e);if(!r(i,0))throw new Error("size must be positive");return i=[i,i],s({center:t,size:i})}},{"./commonChecks":384,"./rectangle":396}],402:[function(e,t,i){const{TAU:s}=e("../maths/constants"),r=e("../maths/vec2"),n=e("../geometries/geom2"),{isGT:o,isGTE:a,isNumberArray:l}=e("./commonChecks"),h=(e,t,i,n)=>{const o=s/e,a=[];for(let s=0;s{let{center:t,vertices:i,outerRadius:c,innerRadius:u,density:d,startAngle:p}=Object.assign({},{center:[0,0],vertices:5,outerRadius:1,innerRadius:0,density:2,startAngle:0},e);if(!l(t,2))throw new Error("center must be an array of X and Y values");if(!a(i,2))throw new Error("vertices must be two or more");if(!o(c,0))throw new Error("outerRadius must be greater than zero");if(!a(u,0))throw new Error("innerRadius must be greater than zero");if(!a(p,0))throw new Error("startAngle must be greater than zero");if(i=Math.floor(i),d=Math.floor(d),p%=s,0===u){if(!a(d,2))throw new Error("density must be two or more");u=c*((e,t)=>e>0&&t>1&&t{const t={innerRadius:1,innerSegments:32,outerRadius:4,outerSegments:32,innerRotation:0,startAngle:0,outerRotation:s},{innerRadius:i,innerSegments:c,outerRadius:u,outerSegments:d,innerRotation:p,startAngle:f,outerRotation:_}=Object.assign({},t,e);if(!l(i,0))throw new Error("innerRadius must be greater than zero");if(!h(c,3))throw new Error("innerSegments must be three or more");if(!l(u,0))throw new Error("outerRadius must be greater than zero");if(!h(d,3))throw new Error("outerSegments must be three or more");if(!h(f,0))throw new Error("startAngle must be positive");if(!l(_,0))throw new Error("outerRotation must be greater than zero");if(i>=u)throw new Error("inner circle is two large to rotate about the outer circle");let m=a({radius:i,segments:c});return 0!==p&&(m=n([0,0,p],m)),m=o([u,0],m),r({startAngle:f,angle:_,segments:d},m)}},{"../maths/constants":110,"../operations/extrusions/extrudeRotate":331,"../operations/transforms/rotate":378,"../operations/transforms/translate":381,"./circle":383,"./commonChecks":384}],404:[function(e,t,i){const{NEPS:s}=e("../maths/constants"),r=e("../maths/vec2"),n=e("../geometries/geom2"),{isNumberArray:o}=e("./commonChecks"),a=(e,t,i)=>Math.acos((e*e+t*t-i*i)/(2*e*t)),l=(e,t,i,s,o,a)=>{const l=r.fromValues(0,0),h=r.fromValues(a,0),c=r.fromValues(s,0);return r.add(c,r.rotate(c,c,[0,0],Math.PI-t),h),n.fromPoints([l,h,c])};t.exports=e=>{let{type:t,values:i}=Object.assign({},{type:"SSS",values:[1,1,1]},e);if("string"!=typeof t)throw new Error("triangle type must be a string");if(t=t.toUpperCase(),"A"!==t[0]&&"S"!==t[0]||"A"!==t[1]&&"S"!==t[1]||"A"!==t[2]&&"S"!==t[2])throw new Error("triangle type must contain three letters; A or S");if(!o(i,3))throw new Error("triangle values must contain three values");if(!i.every((e=>e>0)))throw new Error("triangle values must be greater than zero");switch(t){case"AAA":return(e=>{if(Math.abs(e[0]+e[1]+e[2]-Math.PI)>s)throw new Error("AAA triangles require angles that sum to PI");const t=e[0],i=e[1],r=Math.PI-t-i,n=1/Math.sin(r)*Math.sin(t),o=1/Math.sin(r)*Math.sin(i);return l(t,i,r,n,o,1)})(i);case"AAS":return(e=>{const t=e[0],i=e[1],r=Math.PI+s-t-i;if(r{const t=e[0],i=e[2],r=Math.PI+s-t-i;if(r{const t=e[0],i=e[1],r=e[2],n=((e,t,i)=>t>s?Math.sqrt(e*e+i*i-2*e*i*Math.cos(t)):Math.sqrt((e-i)*(e-i)+e*i*t*t*(1-t*t/12)))(t,i,r),o=a(n,t,r),h=Math.PI-o-i;return l(o,i,h,r,n,t)})(i);case"SSA":return(e=>{const t=e[0],i=e[1],s=e[2],r=Math.asin(i*Math.sin(s)/t),n=Math.PI-r-s,o=t/Math.sin(s)*Math.sin(n);return l(r,n,s,i,o,t)})(i);case"SSS":return(e=>{const t=e[1],i=e[2],s=e[0];if(t+i<=s||i+s<=t||s+t<=i)throw new Error("SSS triangle is incorrect, as the longest side is longer than the sum of the other sides");const r=a(i,s,t),n=a(s,t,i),o=Math.PI-r-n;return l(r,n,o,t,i,s)})(i);default:throw new Error("invalid triangle type, try again")}}},{"../geometries/geom2":42,"../maths/constants":110,"../maths/vec2":206,"./commonChecks":384}],405:[function(e,t,i){t.exports={height:14,32:[16],33:[10,5,21,5,7,void 0,5,2,4,1,5,0,6,1,5,2],34:[16,4,21,4,14,void 0,12,21,12,14],35:[21,11,25,4,-7,void 0,17,25,10,-7,void 0,4,12,18,12,void 0,3,6,17,6],36:[20,8,25,8,-4,void 0,12,25,12,-4,void 0,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3],37:[24,21,21,3,0,void 0,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4,20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,void 0,17,7,15,6,14,4,14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7],38:[26,23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5,1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21,9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2],39:[10,5,19,4,20,5,21,6,20,6,18,5,16,4,15],40:[14,11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7],41:[14,3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7],42:[16,8,21,8,9,void 0,3,18,13,12,void 0,13,18,3,12],43:[26,13,18,13,0,void 0,4,9,22,9],44:[10,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4],45:[26,4,9,22,9],46:[10,5,2,4,1,5,0,6,1,5,2],47:[22,20,25,2,-7],48:[20,9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17,9,17,12,16,17,14,20,11,21,9,21],49:[20,6,17,8,18,11,21,11,0],50:[20,4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13,10,3,0,17,0],51:[20,5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4],52:[20,13,21,3,7,18,7,void 0,13,21,13,0],53:[20,15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14,1,11,0,8,0,5,1,4,2,3,4],54:[20,16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11,0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7],55:[20,17,21,7,0,void 0,3,21,17,21],56:[20,8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16,2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13,15,14,16,16,16,18,15,20,12,21,8,21],57:[20,16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9,21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3],58:[10,5,14,4,13,5,12,6,13,5,14,void 0,5,2,4,1,5,0,6,1,5,2],59:[10,5,14,4,13,5,12,6,13,5,14,void 0,6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4],60:[24,20,18,4,9,20,0],61:[26,4,12,22,12,void 0,4,6,22,6],62:[24,4,18,20,9,4,0],63:[18,3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13,12,9,10,9,7,void 0,9,2,8,1,9,0,10,1,9,2],64:[27,18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16,6,17,8,void 0,12,16,10,14,9,11,9,8,10,6,11,5,void 0,18,16,17,8,17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12,21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0,15,0,18,1,20,2,21,3,void 0,19,16,18,8,18,6,19,5],65:[18,9,21,1,0,void 0,9,21,17,0,void 0,4,7,14,7],66:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,void 0,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0],67:[21,18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5],68:[21,4,21,4,0,void 0,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16,3,14,1,11,0,4,0],69:[19,4,21,4,0,void 0,4,21,17,21,void 0,4,11,12,11,void 0,4,0,17,0],70:[18,4,21,4,0,void 0,4,21,17,21,void 0,4,11,12,11],71:[21,18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,void 0,13,8,18,8],72:[22,4,21,4,0,void 0,18,21,18,0,void 0,4,11,18,11],73:[8,4,21,4,0],74:[16,12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7],75:[21,4,21,4,0,void 0,18,21,4,7,void 0,9,12,18,0],76:[17,4,21,4,0,void 0,4,0,16,0],77:[24,4,21,4,0,void 0,4,21,12,0,void 0,20,21,12,0,void 0,20,21,20,0],78:[22,4,21,4,0,void 0,4,21,18,0,void 0,18,21,18,0],79:[22,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21],80:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13,10,4,10],81:[22,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15,1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,void 0,12,4,18,-2],82:[21,4,21,4,0,void 0,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13,11,4,11,void 0,11,11,18,0],83:[20,17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3],84:[16,8,21,8,0,void 0,1,21,15,21],85:[22,4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21],86:[18,1,21,9,0,void 0,17,21,9,0],87:[24,2,21,7,0,void 0,12,21,7,0,void 0,12,21,17,0,void 0,22,21,17,0],88:[20,3,21,17,0,void 0,17,21,3,0],89:[18,1,21,9,11,9,0,void 0,17,21,9,11],90:[20,17,21,3,0,void 0,3,21,17,21,void 0,3,0,17,0],91:[14,4,25,4,-7,void 0,5,25,5,-7,void 0,4,25,11,25,void 0,4,-7,11,-7],92:[14,0,21,14,-3],93:[14,9,25,9,-7,void 0,10,25,10,-7,void 0,3,25,10,25,void 0,3,-7,10,-7],94:[16,6,15,8,18,10,15,void 0,3,12,8,17,13,12,void 0,8,17,8,0],95:[16,0,-2,16,-2],96:[10,6,21,5,20,4,18,4,16,5,15,6,16,5,17],97:[19,15,14,15,0,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],98:[19,4,21,4,0,void 0,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3],99:[18,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],100:[19,15,21,15,0,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],101:[18,3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],102:[12,10,21,8,21,6,20,5,17,5,0,void 0,2,14,9,14],103:[19,15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],104:[19,4,21,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0],105:[8,3,21,4,20,5,21,4,22,3,21,void 0,4,14,4,0],106:[10,5,21,6,20,7,21,6,22,5,21,void 0,6,14,6,-3,5,-6,3,-7,1,-7],107:[17,4,21,4,0,void 0,14,14,4,4,void 0,8,8,15,0],108:[8,4,21,4,0],109:[30,4,14,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0,void 0,15,10,18,13,20,14,23,14,25,13,26,10,26,0],110:[19,4,14,4,0,void 0,4,10,7,13,9,14,12,14,14,13,15,10,15,0],111:[19,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16,6,16,8,15,11,13,13,11,14,8,14],112:[19,4,14,4,-7,void 0,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15,3,13,1,11,0,8,0,6,1,4,3],113:[19,15,14,15,-7,void 0,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3],114:[13,4,14,4,0,void 0,4,8,5,11,7,13,9,14,12,14],115:[17,14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14,3,13,1,10,0,7,0,4,1,3,3],116:[12,5,21,5,4,6,1,8,0,10,0,void 0,2,14,9,14],117:[19,4,14,4,4,5,1,7,0,10,0,12,1,15,4,void 0,15,14,15,0],118:[16,2,14,8,0,void 0,14,14,8,0],119:[22,3,14,7,0,void 0,11,14,7,0,void 0,11,14,15,0,void 0,19,14,15,0],120:[17,3,14,14,0,void 0,14,14,3,0],121:[16,2,14,8,0,void 0,14,14,8,0,6,-4,4,-6,2,-7,1,-7],122:[17,14,14,3,0,void 0,3,14,14,14,void 0,3,0,14,0],123:[14,9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,void 0,7,24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3,8,1,7,0,6,-2,6,-4,7,-6,void 0,6,8,8,6,8,4,7,2,6,1,5,-1,5,-3,6,-5,7,-6,9,-7],124:[8,4,25,4,-7],125:[14,5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,void 0,7,24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3,6,1,7,0,8,-2,8,-4,7,-6,void 0,8,8,6,6,6,4,7,2,8,1,9,-1,9,-3,8,-5,7,-6,5,-7],126:[24,3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,void 0,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12]}},{}],406:[function(e,t,i){t.exports={vectorChar:e("./vectorChar"),vectorText:e("./vectorText")}},{"./vectorChar":407,"./vectorText":409}],407:[function(e,t,i){const s=e("./vectorParams");t.exports=(e,t)=>{const{xOffset:i,yOffset:r,input:n,font:o,height:a,extrudeOffset:l}=s(e,t);let h=n.charCodeAt(0);h&&o[h]||(h=63);const c=[].concat(o[h]),u=(a-l)/o.height,d=l/2,p=c.shift()*u,f=[];let _=[];for(let e=0,t=c.length;e{t||"string"!=typeof e||(e={input:e}),e=e||{};const i=Object.assign({},s,e);return i.input=t||i.input,i}},{"./fonts/single-line/hershey/simplex.js":405}],409:[function(e,t,i){const s=e("./vectorChar"),r=e("./vectorParams"),n=(e,t)=>{const{x:i,y:s}=Object.assign({x:0,y:0},e||{}),r=t.segments;let n=null,o=null;for(let e=0,t=r.length;e{const{xOffset:i,yOffset:o,input:a,font:l,height:h,align:c,extrudeOffset:u,lineSpacing:d,letterSpacing:p}=r(e,t);let f,_,m,g,v,x,[T,S]=[i,o],E={width:0,segments:[]};const b=[];let C=[],y=0;const A=T,R=()=>{b.push(E),y=Math.max(y,E.width),E={width:0,segments:[]}};for(f=0,_=a.length;f<_;f++)m=a[f],g=s({xOffset:T,yOffset:S,font:l,height:h,extrudeOffset:u},m),"\n"!==m?(v=g.width*p,E.width+=v,T+=v," "!==m&&(E.segments=E.segments.concat(g.segments))):(T=A,S-=g.height*d,R());for(E.segments.length&&R(),f=0,_=b.length;f<_;f++)E=b[f],y>E.width&&(x=y-E.width,"right"===c?E=n({x},E):"center"===c&&(E=n({x:x/2},E))),C=C.concat(E.segments);return C}},{"./vectorChar":407,"./vectorParams":408}],410:[function(e,t,i){const s=e("../geometries/geom2"),r=e("../geometries/geom3"),n=e("../geometries/path2");t.exports=e=>{let t;for(const i of e){let e=0;if(s.isA(i)&&(e=1),r.isA(i)&&(e=2),n.isA(i)&&(e=3),t&&e!==t)return!1;t=e}return!0}},{"../geometries/geom2":42,"../geometries/geom3":57,"../geometries/path2":78}],411:[function(e,t,i){t.exports=e=>.017453292519943295*e},{}],412:[function(e,t,i){const s=e=>e.reduce(((e,t)=>Array.isArray(t)?e.concat(s(t)):e.concat(t)),[]);t.exports=s},{}],413:[function(e,t,i){t.exports=(e,t)=>e-t},{}],414:[function(e,t,i){t.exports={areAllShapesTheSameType:e("./areAllShapesTheSameType"),degToRad:e("./degToRad"),flatten:e("./flatten"),fnNumberSort:e("./fnNumberSort"),insertSorted:e("./insertSorted"),radiusToSegments:e("./radiusToSegments"),radToDeg:e("./radToDeg")}},{"./areAllShapesTheSameType":410,"./degToRad":411,"./flatten":412,"./fnNumberSort":413,"./insertSorted":415,"./radToDeg":417,"./radiusToSegments":418}],415:[function(e,t,i){t.exports=(e,t,i)=>{let s=0,r=e.length;for(;r>s;){const n=Math.floor((s+r)/2);i(t,e[n])>0?s=n+1:r=n}e.splice(s,0,t)}},{}],416:[function(e,t,i){t.exports=(e,t,i)=>{for(e=e.slice();e.length57.29577951308232*e},{}],418:[function(e,t,i){const{TAU:s}=e("../maths/constants");t.exports=(e,t,i)=>{const r=t>0?e*s/t:0,n=i>0?s/i:0;return Math.ceil(Math.max(r,n,4))}},{"../maths/constants":110}],419:[function(e,t,i){const{geometries:s}=e("@jscad/modeling"),r=(e,t)=>{const i=[];return s.geom3.toPolygons(e).forEach(((e,t)=>{i.push(a(e))})),i.join("\n")},n=e=>`${e[0]} ${e[1]} ${e[2]}`,o=e=>`vertex ${n(e)}`,a=e=>{const t=[];if(e.vertices.length>=3){const i=o(e.vertices[0]);for(let r=0;r{t.statusCallback&&t.statusCallback({progress:0});const i=`solid JSCAD\n${((e,t)=>{const i=[];return e.forEach(((s,n)=>{i.push(r(s,t)),t.statusCallback&&t.statusCallback({progress:100*n/e.length})})),i.join("\n")})(e,t)}\nendsolid JSCAD\n`;return t.statusCallback&&t.statusCallback({progress:100}),[i]}}},{"@jscad/modeling":108}],420:[function(e,t,i){const{geometries:s}=e("@jscad/modeling");t.exports={serializeBinary:(e,t)=>{t.statusCallback&&t.statusCallback({progress:0});const i=new ArrayBuffer(4),r=new Int32Array(i,0,1),n=new Int8Array(i,0,4);if(r[0]=287454020,68!==n[0])throw new Error("Binary STL output is currently only supported on little-endian (Intel) processors");let o=0,a=0;e.forEach(((e,t)=>{s.geom3.toPolygons(e).forEach((e=>{const t=e.vertices.length;o+=t>=3?t-2:0,a+=1}))}));const l=new Uint8Array(80);for(let e=0;e<80;e++)l[e]=65;const h=new Uint32Array(1);h[0]=o;const c=new ArrayBuffer(50*o),u=new Int8Array(c),d=new ArrayBuffer(50),p=new Int8Array(d),f=new Float32Array(d,0,12),_=new Uint16Array(d,48,1);let m=0;return e.forEach((e=>{s.geom3.toPolygons(e).forEach(((e,i)=>{const r=e.vertices,n=r.length,o=s.poly3.plane(e);for(let e=0;e0?e:0)];f[t++]=s[0],f[t++]=s[1],f[t++]=s[2]}_[0]=0,u.set(p,m),m+=50}t.statusCallback&&t.statusCallback({progress:100*i/a})}))})),t.statusCallback&&t.statusCallback({progress:100}),[l.buffer,h.buffer,c]}}},{"@jscad/modeling":108}],421:[function(e,t,i){const{geometries:s,modifiers:r}=e("@jscad/modeling"),{flatten:n,toArray:o}=e("@jscad/array-utils"),{serializeBinary:a}=e("./CSGToStlb"),{serializeText:l}=e("./CSGToStla");t.exports={mimeType:"application/sla",serialize:(e,...t)=>{e=Object.assign({},{binary:!0,statusCallback:null},e);let i=(t=n(t)).filter((e=>s.geom3.isA(e)));if(0===i.length)throw new Error("only 3D geometries can be serialized to STL");return t.length!==i.length&&console.warn("some objects could not be serialized to STL"),i=o(r.generalize({snap:!0,triangulate:!0},i)),e.binary?a(i,e):l(i,e)}}},{"./CSGToStla":419,"./CSGToStlb":420,"@jscad/array-utils":5,"@jscad/modeling":108}],422:[function(e,t,i){i.byteLength=function(e){var t=l(e),i=t[0],s=t[1];return 3*(i+s)/4-s},i.toByteArray=function(e){var t,i,s=l(e),o=s[0],a=s[1],h=new n(function(e,t,i){return 3*(t+i)/4-i}(0,o,a)),c=0,u=a>0?o-4:o;for(i=0;i>16&255,h[c++]=t>>8&255,h[c++]=255&t;return 2===a&&(t=r[e.charCodeAt(i)]<<2|r[e.charCodeAt(i+1)]>>4,h[c++]=255&t),1===a&&(t=r[e.charCodeAt(i)]<<10|r[e.charCodeAt(i+1)]<<4|r[e.charCodeAt(i+2)]>>2,h[c++]=t>>8&255,h[c++]=255&t),h},i.fromByteArray=function(e){for(var t,i=e.length,r=i%3,n=[],o=16383,a=0,l=i-r;al?l:a+o));return 1===r?(t=e[i-1],n.push(s[t>>2]+s[t<<4&63]+"==")):2===r&&(t=(e[i-2]<<8)+e[i-1],n.push(s[t>>10]+s[t>>4&63]+s[t<<2&63]+"=")),n.join("")};for(var s=[],r=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0;a<64;++a)s[a]=o[a],r[o.charCodeAt(a)]=a;function l(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var i=e.indexOf("=");return-1===i&&(i=t),[i,i===t?0:4-i%4]}function h(e,t,i){for(var r,n,o=[],a=t;a>18&63]+s[n>>12&63]+s[n>>6&63]+s[63&n]);return o.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},{}],423:[function(e,t,i){(function(t){var s=e("base64-js"),r=e("ieee754");i.Buffer=t,i.SlowBuffer=function(e){return+e!=e&&(e=0),t.alloc(+e)},i.INSPECT_MAX_BYTES=50;var n=2147483647;function o(e){if(e>n)throw new RangeError('The value "'+e+'" is invalid for option "size"');var i=new Uint8Array(e);return i.__proto__=t.prototype,i}function t(e,t,i){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return h(e)}return a(e,t,i)}function a(e,i,s){if("string"==typeof e)return function(e,i){if("string"==typeof i&&""!==i||(i="utf8"),!t.isEncoding(i))throw new TypeError("Unknown encoding: "+i);var s=0|d(e,i),r=o(s),n=r.write(e,i);return n!==s&&(r=r.slice(0,n)),r}(e,i);if(ArrayBuffer.isView(e))return c(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(U(e,ArrayBuffer)||e&&U(e.buffer,ArrayBuffer))return function(e,i,s){if(i<0||e.byteLength=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return 0|e}function d(e,i){if(t.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||U(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var s=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===s)return 0;for(var n=!1;;)switch(i){case"ascii":case"latin1":case"binary":return s;case"utf8":case"utf-8":return L(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*s;case"hex":return s>>>1;case"base64":return B(e).length;default:if(n)return r?-1:L(e).length;i=(""+i).toLowerCase(),n=!0}}function p(e,t,i){var s=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if((i>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return I(this,t,i);case"utf8":case"utf-8":return C(this,t,i);case"ascii":return A(this,t,i);case"latin1":case"binary":return R(this,t,i);case"base64":return b(this,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,t,i);default:if(s)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),s=!0}}function f(e,t,i){var s=e[t];e[t]=e[i],e[i]=s}function _(e,i,s,r,n){if(0===e.length)return-1;if("string"==typeof s?(r=s,s=0):s>2147483647?s=2147483647:s<-2147483648&&(s=-2147483648),k(s=+s)&&(s=n?0:e.length-1),s<0&&(s=e.length+s),s>=e.length){if(n)return-1;s=e.length-1}else if(s<0){if(!n)return-1;s=0}if("string"==typeof i&&(i=t.from(i,r)),t.isBuffer(i))return 0===i.length?-1:m(e,i,s,r,n);if("number"==typeof i)return i&=255,"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(e,i,s):Uint8Array.prototype.lastIndexOf.call(e,i,s):m(e,[i],s,r,n);throw new TypeError("val must be string, number or Buffer")}function m(e,t,i,s,r){var n,o=1,a=e.length,l=t.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(e.length<2||t.length<2)return-1;o=2,a/=2,l/=2,i/=2}function h(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(r){var c=-1;for(n=i;na&&(i=a-l),n=i;n>=0;n--){for(var u=!0,d=0;dr&&(s=r):s=r;var n=t.length;s>n/2&&(s=n/2);for(var o=0;o>8,r=i%256,n.push(r),n.push(s);return n}(t,e.length-i),e,i,s)}function b(e,t,i){return 0===t&&i===e.length?s.fromByteArray(e):s.fromByteArray(e.slice(t,i))}function C(e,t,i){i=Math.min(e.length,i);for(var s=[],r=t;r239?4:h>223?3:h>191?2:1;if(r+u<=i)switch(u){case 1:h<128&&(c=h);break;case 2:128==(192&(n=e[r+1]))&&(l=(31&h)<<6|63&n)>127&&(c=l);break;case 3:n=e[r+1],o=e[r+2],128==(192&n)&&128==(192&o)&&(l=(15&h)<<12|(63&n)<<6|63&o)>2047&&(l<55296||l>57343)&&(c=l);break;case 4:n=e[r+1],o=e[r+2],a=e[r+3],128==(192&n)&&128==(192&o)&&128==(192&a)&&(l=(15&h)<<18|(63&n)<<12|(63&o)<<6|63&a)>65535&&l<1114112&&(c=l)}null===c?(c=65533,u=1):c>65535&&(c-=65536,s.push(c>>>10&1023|55296),c=56320|1023&c),s.push(c),r+=u}return function(e){var t=e.length;if(t<=y)return String.fromCharCode.apply(String,e);for(var i="",s=0;st&&(e+=" ... "),""},t.prototype.compare=function(e,i,s,r,n){if(U(e,Uint8Array)&&(e=t.from(e,e.offset,e.byteLength)),!t.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===i&&(i=0),void 0===s&&(s=e?e.length:0),void 0===r&&(r=0),void 0===n&&(n=this.length),i<0||s>e.length||r<0||n>this.length)throw new RangeError("out of range index");if(r>=n&&i>=s)return 0;if(r>=n)return-1;if(i>=s)return 1;if(this===e)return 0;for(var o=(n>>>=0)-(r>>>=0),a=(s>>>=0)-(i>>>=0),l=Math.min(o,a),h=this.slice(r,n),c=e.slice(i,s),u=0;u>>=0,isFinite(i)?(i>>>=0,void 0===s&&(s="utf8")):(s=i,i=void 0)}var r=this.length-t;if((void 0===i||i>r)&&(i=r),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");s||(s="utf8");for(var n=!1;;)switch(s){case"hex":return g(this,e,t,i);case"utf8":case"utf-8":return v(this,e,t,i);case"ascii":return x(this,e,t,i);case"latin1":case"binary":return T(this,e,t,i);case"base64":return S(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,i);default:if(n)throw new TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),n=!0}},t.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var y=4096;function A(e,t,i){var s="";i=Math.min(e.length,i);for(var r=t;rr)&&(i=r);for(var n="",o=t;oi)throw new RangeError("Trying to access beyond buffer length")}function D(e,i,s,r,n,o){if(!t.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(i>n||ie.length)throw new RangeError("Index out of range")}function O(e,t,i,s,r,n){if(i+s>e.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function N(e,t,i,s,n){return t=+t,i>>>=0,n||O(e,0,i,4),r.write(e,t,i,s,23,4),i+4}function w(e,t,i,s,n){return t=+t,i>>>=0,n||O(e,0,i,8),r.write(e,t,i,s,52,8),i+8}t.prototype.slice=function(e,i){var s=this.length;(e=~~e)<0?(e+=s)<0&&(e=0):e>s&&(e=s),(i=void 0===i?s:~~i)<0?(i+=s)<0&&(i=0):i>s&&(i=s),i>>=0,t>>>=0,i||M(e,t,this.length);for(var s=this[e],r=1,n=0;++n>>=0,t>>>=0,i||M(e,t,this.length);for(var s=this[e+--t],r=1;t>0&&(r*=256);)s+=this[e+--t]*r;return s},t.prototype.readUInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),this[e]},t.prototype.readUInt16LE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]|this[e+1]<<8},t.prototype.readUInt16BE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]<<8|this[e+1]},t.prototype.readUInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},t.prototype.readUInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},t.prototype.readIntLE=function(e,t,i){e>>>=0,t>>>=0,i||M(e,t,this.length);for(var s=this[e],r=1,n=0;++n=(r*=128)&&(s-=Math.pow(2,8*t)),s},t.prototype.readIntBE=function(e,t,i){e>>>=0,t>>>=0,i||M(e,t,this.length);for(var s=t,r=1,n=this[e+--s];s>0&&(r*=256);)n+=this[e+--s]*r;return n>=(r*=128)&&(n-=Math.pow(2,8*t)),n},t.prototype.readInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},t.prototype.readInt16LE=function(e,t){e>>>=0,t||M(e,2,this.length);var i=this[e]|this[e+1]<<8;return 32768&i?4294901760|i:i},t.prototype.readInt16BE=function(e,t){e>>>=0,t||M(e,2,this.length);var i=this[e+1]|this[e]<<8;return 32768&i?4294901760|i:i},t.prototype.readInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},t.prototype.readInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},t.prototype.readFloatLE=function(e,t){return e>>>=0,t||M(e,4,this.length),r.read(this,e,!0,23,4)},t.prototype.readFloatBE=function(e,t){return e>>>=0,t||M(e,4,this.length),r.read(this,e,!1,23,4)},t.prototype.readDoubleLE=function(e,t){return e>>>=0,t||M(e,8,this.length),r.read(this,e,!0,52,8)},t.prototype.readDoubleBE=function(e,t){return e>>>=0,t||M(e,8,this.length),r.read(this,e,!1,52,8)},t.prototype.writeUIntLE=function(e,t,i,s){e=+e,t>>>=0,i>>>=0,s||D(this,e,t,i,Math.pow(2,8*i)-1,0);var r=1,n=0;for(this[t]=255&e;++n>>=0,i>>>=0,s||D(this,e,t,i,Math.pow(2,8*i)-1,0);var r=i-1,n=1;for(this[t+r]=255&e;--r>=0&&(n*=256);)this[t+r]=e/n&255;return t+i},t.prototype.writeUInt8=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,1,255,0),this[t]=255&e,t+1},t.prototype.writeUInt16LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeUInt16BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeUInt32LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},t.prototype.writeUInt32BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeIntLE=function(e,t,i,s){if(e=+e,t>>>=0,!s){var r=Math.pow(2,8*i-1);D(this,e,t,i,r-1,-r)}var n=0,o=1,a=0;for(this[t]=255&e;++n>>=0,!s){var r=Math.pow(2,8*i-1);D(this,e,t,i,r-1,-r)}var n=i-1,o=1,a=0;for(this[t+n]=255&e;--n>=0&&(o*=256);)e<0&&0===a&&0!==this[t+n+1]&&(a=1),this[t+n]=(e/o|0)-a&255;return t+i},t.prototype.writeInt8=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},t.prototype.writeInt16LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},t.prototype.writeInt16BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},t.prototype.writeInt32LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},t.prototype.writeInt32BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},t.prototype.writeFloatLE=function(e,t,i){return N(this,e,t,!0,i)},t.prototype.writeFloatBE=function(e,t,i){return N(this,e,t,!1,i)},t.prototype.writeDoubleLE=function(e,t,i){return w(this,e,t,!0,i)},t.prototype.writeDoubleBE=function(e,t,i){return w(this,e,t,!1,i)},t.prototype.copy=function(e,i,s,r){if(!t.isBuffer(e))throw new TypeError("argument should be a Buffer");if(s||(s=0),r||0===r||(r=this.length),i>=e.length&&(i=e.length),i||(i=0),r>0&&r=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-i=0;--o)e[o+i]=this[o+s];else Uint8Array.prototype.set.call(e,this.subarray(s,r),i);return n},t.prototype.fill=function(e,i,s,r){if("string"==typeof e){if("string"==typeof i?(r=i,i=0,s=this.length):"string"==typeof s&&(r=s,s=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!t.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){var n=e.charCodeAt(0);("utf8"===r&&n<128||"latin1"===r)&&(e=n)}}else"number"==typeof e&&(e&=255);if(i<0||this.length>>=0,s=void 0===s?this.length:s>>>0,e||(e=0),"number"==typeof e)for(o=i;o55295&&i<57344){if(!r){if(i>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(o+1===s){(t-=3)>-1&&n.push(239,191,189);continue}r=i;continue}if(i<56320){(t-=3)>-1&&n.push(239,191,189),r=i;continue}i=65536+(r-55296<<10|i-56320)}else r&&(t-=3)>-1&&n.push(239,191,189);if(r=null,i<128){if((t-=1)<0)break;n.push(i)}else if(i<2048){if((t-=2)<0)break;n.push(i>>6|192,63&i|128)}else if(i<65536){if((t-=3)<0)break;n.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return n}function B(e){return s.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(F,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function V(e,t,i,s){for(var r=0;r=t.length||r>=e.length);++r)t[r+i]=e[r];return r}function U(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function k(e){return e!=e}}).call(this,e("buffer").Buffer)},{"base64-js":422,buffer:423,ieee754:424}],424:[function(e,t,i){i.read=function(e,t,i,s,r){var n,o,a=8*r-s-1,l=(1<>1,c=-7,u=i?r-1:0,d=i?-1:1,p=e[t+u];for(u+=d,n=p&(1<<-c)-1,p>>=-c,c+=a;c>0;n=256*n+e[t+u],u+=d,c-=8);for(o=n&(1<<-c)-1,n>>=-c,c+=s;c>0;o=256*o+e[t+u],u+=d,c-=8);if(0===n)n=1-h;else{if(n===l)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,s),n-=h}return(p?-1:1)*o*Math.pow(2,n-s)},i.write=function(e,t,i,s,r,n){var o,a,l,h=8*n-r-1,c=(1<>1,d=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,p=s?0:n-1,f=s?1:-1,_=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-o))<1&&(o--,l*=2),(t+=o+u>=1?d/l:d*Math.pow(2,1-u))*l>=2&&(o++,l/=2),o+u>=c?(a=0,o=c):o+u>=1?(a=(t*l-1)*Math.pow(2,r),o+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,r),o=0));r>=8;e[i+p]=255&a,p+=f,a/=256,r-=8);for(o=o<0;e[i+p]=255&o,p+=f,o/=256,h-=8);e[i+p-f]|=128*_}},{}]},{},[1])},568:(e,t,i)=>{"use strict";class s{constructor(e){this.jscad=e,this.hashesFromPreviousRun={},this.usedHashes={},this.argCache={}}cleanAllCache(){Object.keys(this.usedHashes).forEach((e=>{if(this.argCache[e])try{this.argCache[e].delete()}catch(e){}})),this.argCache={},this.usedHashes={},this.hashesFromPreviousRun={}}cleanUpCache(){}cacheOp(e,t){let i=null;const s=this.computeHash(e);this.usedHashes[s]=s,this.hashesFromPreviousRun[s]=s;const r=this.checkCache(s);return r?(i=r,i.hash=r.hash):(i=t(),i.hash=s,this.addToCache(s,i)),i}checkCache(e){return this.argCache[e]||null}addToCache(e,t){const i=t;return i.hash=e,this.argCache[e]=i,e}computeHash(e,t){let i=JSON.stringify(e);i=i.replace(/(\"ptr\"\:(-?[0-9]*?)\,)/g,""),i=i.replace(/(\"ptr\"\:(-?[0-9]*))/g,""),i.includes("ptr")&&console.error("YOU DONE MESSED UP YOUR REGEX.");const s=Math.random.toString()+i;return t?s:this.stringToHash(s)}stringToHash(e){let t=0;if(0===e.length)return t;for(let i=0;ie.hash!==t.hash||e.ptr!==t.ptr))}dupShape(e){return e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_WIRE?this.jscad.TopoDS.Wire_1(e):e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_SHELL?this.jscad.TopoDS.Shell_1(e):e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_EDGE?this.jscad.TopoDS.Edge_1(e):e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_SOLID?this.jscad.TopoDS.Solid_1(e):e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_FACE?this.jscad.TopoDS.Face_1(e):e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_COMPOUND?this.jscad.TopoDS.Compound_1(e):e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_COMPSOLID?this.jscad.TopoDS.CompSolid_1(e):e.ShapeType()===this.jscad.TopAbs_ShapeEnum.TopAbs_VERTEX?this.jscad.TopoDS.Vertex_1(e):void 0}}class r{constructor(){this.tolerance=1e-5}degToRad(e){return e*(Math.PI/180)}remap(e,t,i,s,r){return(e-t)/(i-t)*(r-s)+s}removeAllDuplicateVectors(e,t=1e-7){const i=[];return e.forEach((e=>{i.some((i=>this.vectorsTheSame(e,i,t)))||i.push(e)})),i}removeConsecutiveDuplicates(e,t=!0){const i=[];if(e.length>1){for(let t=1;te.map(((e,i)=>e+t[i]))),[0,0,0]).map((t=>t/e.length))}magnitude(e){return Math.sqrt(e.reduce(((e,t)=>e+t*t),0))}normalize(e){const t=this.magnitude(e);return e.map((e=>e/t))}translatePoint(e,t,i){return[e[0]+t[0]*i,e[1]+t[1]*i,e[2]+t[2]*i]}distanceBetweenPoints(e,t){const i=t[0]-e[0],s=t[1]-e[1],r=t[2]-e[2];return Math.sqrt(i*i+s*s+r*r)}}var n,o,a;!function(e){let t,i,s,r,n,o,a,l,h,c,u,d,p,f,_,m;!function(e){e.arc="arc",e.intersection="intersection",e.tangent="tangent"}(t=e.joinTypeEnum||(e.joinTypeEnum={})),function(e){e.skin="skin",e.pipe="pipe",e.rectoVerso="rectoVerso"}(i=e.bRepOffsetModeEnum||(e.bRepOffsetModeEnum={})),function(e){e.approxChordLength="approxChordLength",e.approxCentripetal="approxCentripetal",e.approxIsoParametric="approxIsoParametric"}(s=e.approxParametrizationTypeEnum||(e.approxParametrizationTypeEnum={})),function(e){e.outside="outside",e.inside="inside",e.middle="middle"}(r=e.directionEnum||(e.directionEnum={})),function(e){e.iges="iges",e.step="step"}(n=e.fileTypeEnum||(e.fileTypeEnum={})),function(e){e.forward="forward",e.reversed="reversed",e.internal="internal",e.external="external"}(o=e.topAbsOrientationEnum||(e.topAbsOrientationEnum={})),function(e){e.in="in",e.out="out",e.on="on",e.unknown="unknown"}(a=e.topAbsStateEnum||(e.topAbsStateEnum={})),function(e){e.unknown="unknown",e.vertex="vertex",e.edge="edge",e.wire="wire",e.face="face",e.shell="shell",e.solid="solid",e.compSolid="compSolid",e.compound="compound",e.shape="shape"}(l=e.shapeTypeEnum||(e.shapeTypeEnum={})),function(e){e.unqualified="unqualified",e.enclosing="enclosing",e.enclosed="enclosed",e.outside="outside",e.noqualifier="noqualifier"}(h=e.gccEntPositionEnum||(e.gccEntPositionEnum={})),function(e){e.keepSide1="keepSide1",e.keepSide2="keepSide2",e.all="all"}(c=e.positionResultEnum||(e.positionResultEnum={})),function(e){e.none="none",e.keepSide1="keepSide1",e.keepSide2="keepSide2"}(u=e.circleInclusionEnum||(e.circleInclusionEnum={})),function(e){e.none="none",e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(d=e.twoCircleInclusionEnum||(e.twoCircleInclusionEnum={})),function(e){e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(p=e.fourSidesStrictEnum||(e.fourSidesStrictEnum={})),function(e){e.outside="outside",e.inside="inside"}(f=e.twoSidesStrictEnum||(e.twoSidesStrictEnum={})),function(e){e.allWithAll="allWithAll",e.inOrder="inOrder",e.inOrderClosed="inOrderClosed"}(_=e.combinationCirclesForFaceEnum||(e.combinationCirclesForFaceEnum={})),function(e){e[e.curve=0]="curve",e[e.edge=1]="edge",e[e.wire=2]="wire",e[e.face=3]="face"}(m=e.typeSpecificityEnum||(e.typeSpecificityEnum={})),e.DecomposedMeshDto=class{constructor(e,t){void 0!==e&&(this.faceList=e),void 0!==t&&(this.edgeList=t)}},e.DecomposedFaceDto=class{},e.DecomposedEdgeDto=class{},e.ShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.PointDto=class{constructor(e){this.point=[0,0,0],void 0!==e&&(this.point=e)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.ConstraintTanLinesFromPtToCircleDto=class{constructor(e,t,i,s,r){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.positionResult=s),void 0!==r&&(this.circleRemainder=r)}},e.ConstraintTanLinesFromTwoPtsToCircleDto=class{constructor(e,t,i,s,r,n){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point1=t),void 0!==i&&(this.point1=i),void 0!==s&&(this.tolerance=s),void 0!==r&&(this.positionResult=r),void 0!==n&&(this.circleRemainder=n)}},e.ConstraintTanLinesOnTwoCirclesDto=class{constructor(e,t,i,s,r){this.tolerance=1e-7,this.positionResult=c.all,this.circleRemainders=d.none,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.positionResult=s),void 0!==r&&(this.circleRemainders=r)}},e.ConstraintTanCirclesOnTwoCirclesDto=class{constructor(e,t,i,s){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.radius=s)}},e.ConstraintTanCirclesOnCircleAndPntDto=class{constructor(e,t,i,s){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.radius=s)}},e.CurveAndSurfaceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t)}},e.FilletTwoEdgesInPlaneDto=class{constructor(e,t,i,s,r,n){this.planeOrigin=[0,0,0],this.planeDirection=[0,1,0],this.radius=.3,this.solution=-1,void 0!==e&&(this.edge1=e),void 0!==t&&(this.edge2=t),void 0!==i&&(this.planeOrigin=i),void 0!==s&&(this.planeDirection=s),void 0!==r&&(this.radius=r),void 0!==n&&(this.solution=n)}},e.ClosestPointsOnShapeFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.SplitWireOnPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.ClosestPointsOnShapesFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shapes=e),void 0!==t&&(this.points=t)}},e.ClosestPointsBetweenTwoShapesDto=class{constructor(e,t){void 0!==e&&(this.shape1=e),void 0!==t&&(this.shape2=t)}},e.FaceFromSurfaceAndWireDto=class{constructor(e,t,i){this.inside=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.wire=t),void 0!==i&&(this.inside=i)}},e.WireOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wire=e),void 0!==t&&(this.face=t)}},e.DrawShapeDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,p,f,_,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shape=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdgeIndexes=p),void 0!==f&&(this.edgeIndexHeight=f),void 0!==_&&(this.edgeIndexColour=_),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.DrawShapesDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,p,f,_,m,g,v){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shapes=e),void 0!==t&&(this.faceOpacity=t),void 0!==i&&(this.edgeOpacity=i),void 0!==s&&(this.edgeColour=s),void 0!==r&&(this.faceMaterial=r),void 0!==n&&(this.faceColour=n),void 0!==c&&(this.vertexColour=c),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==l&&(this.drawFaces=l),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdgeIndexes=p),void 0!==f&&(this.edgeIndexHeight=f),void 0!==_&&(this.edgeIndexColour=_),void 0!==m&&(this.drawFaceIndexes=m),void 0!==g&&(this.faceIndexHeight=g),void 0!==v&&(this.faceIndexColour=v)}},e.FaceSubdivisionDto=class{constructor(e,t,i,s,r,n,o,a,l){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepU=!1,this.removeStartEdgeU=!1,this.removeEndEdgeU=!1,this.shiftHalfStepV=!1,this.removeStartEdgeV=!1,this.removeEndEdgeV=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==s&&(this.shiftHalfStepU=s),void 0!==r&&(this.removeStartEdgeU=r),void 0!==n&&(this.removeEndEdgeU=n),void 0!==o&&(this.shiftHalfStepV=o),void 0!==a&&(this.removeStartEdgeV=a),void 0!==l&&(this.removeEndEdgeV=l)}},e.FaceSubdivisionControlledDto=class{constructor(e,t,i,s,r,n,o,a,l,h,c,u,d,p,f){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepNthU=0,this.shiftHalfStepUOffsetN=0,this.removeStartEdgeNthU=0,this.removeStartEdgeUOffsetN=0,this.removeEndEdgeNthU=0,this.removeEndEdgeUOffsetN=0,this.shiftHalfStepNthV=0,this.shiftHalfStepVOffsetN=0,this.removeStartEdgeNthV=0,this.removeStartEdgeVOffsetN=0,this.removeEndEdgeNthV=0,this.removeEndEdgeVOffsetN=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==i&&(this.nrDivisionsV=i),void 0!==s&&(this.shiftHalfStepNthU=s),void 0!==r&&(this.shiftHalfStepUOffsetN=r),void 0!==n&&(this.removeStartEdgeNthU=n),void 0!==o&&(this.removeStartEdgeUOffsetN=o),void 0!==a&&(this.removeEndEdgeNthU=a),void 0!==l&&(this.removeEndEdgeUOffsetN=l),void 0!==h&&(this.shiftHalfStepNthV=h),void 0!==c&&(this.shiftHalfStepVOffsetN=c),void 0!==u&&(this.removeStartEdgeNthV=u),void 0!==d&&(this.removeStartEdgeVOffsetN=d),void 0!==p&&(this.removeEndEdgeNthV=p),void 0!==f&&(this.removeEndEdgeVOffsetN=f)}},e.FaceLinearSubdivisionDto=class{constructor(e,t,i,s,r,n,o){this.isU=!0,this.param=.5,this.nrPoints=10,this.shiftHalfStep=!1,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==i&&(this.param=i),void 0!==s&&(this.nrPoints=s),void 0!==r&&(this.shiftHalfStep=r),void 0!==n&&(this.removeStartPoint=n),void 0!==o&&(this.removeEndPoint=o)}},e.DataOnUVDto=class{constructor(e,t,i){this.paramU=.5,this.paramV=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.paramU=t),void 0!==i&&(this.paramV=i)}},e.DataOnUVsDto=class{constructor(e,t){this.paramsUV=[[.5,.5]],void 0!==e&&(this.shape=e),void 0!==t&&(this.paramsUV=t)}},e.PolygonDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolygonsDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polygons=e),void 0!==t&&(this.returnCompound=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolylinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.returnCompound=t)}},e.SquareDto=class{constructor(e,t,i){this.size=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.RectangleDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.center=i),void 0!==s&&(this.direction=s)}},e.LPolygonDto=class{constructor(e,t,i,s,n,o,a,l){this.widthFirst=1,this.lengthFirst=2,this.widthSecond=.5,this.lengthSecond=2,this.align=r.outside,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.widthFirst=e),void 0!==t&&(this.lengthFirst=t),void 0!==i&&(this.widthSecond=i),void 0!==s&&(this.lengthSecond=s),void 0!==n&&(this.align=n),void 0!==o&&(this.rotation=o),void 0!==a&&(this.center=a),void 0!==l&&(this.direction=l)}},e.BoxDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.height=3,this.center=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==s&&(this.center=s)}},e.CubeDto=class{constructor(e,t){this.size=1,this.center=[0,0,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t)}},e.BoxFromCornerDto=class{constructor(e,t,i,s){this.width=1,this.length=2,this.height=3,this.corner=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==i&&(this.height=i),void 0!==s&&(this.corner=s)}},e.SphereDto=class{constructor(e,t){this.radius=1,this.center=[0,0,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.ConeDto=class{constructor(e,t,i,s,r,n){this.radius1=2,this.radius2=1,this.height=2,this.angle=360,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius1=e),void 0!==t&&(this.radius2=t),void 0!==i&&(this.height=i),void 0!==s&&(this.angle=s),void 0!==r&&(this.center=r),void 0!==n&&(this.direction=n)}},e.LineDto=class{constructor(e,t){this.start=[0,0,0],this.end=[0,1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.returnCompound=t)}},e.ArcEdgeTwoPointsTangentDto=class{constructor(e,t,i){this.start=[0,0,0],this.tangentVec=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.tangentVec=t),void 0!==i&&(this.end=i)}},e.ArcEdgeCircleTwoPointsDto=class{constructor(e,t,i,s){this.start=[0,0,0],this.end=[0,0,1],this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.start=t),void 0!==i&&(this.end=i),void 0!==s&&(this.sense=s)}},e.ArcEdgeCircleTwoAnglesDto=class{constructor(e,t,i,s){this.alphaAngle1=0,this.alphaAngle2=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle1=t),void 0!==i&&(this.alphaAngle2=i),void 0!==s&&(this.sense=s)}},e.ArcEdgeCirclePointAngleDto=class{constructor(e,t,i,s){this.alphaAngle=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle=t),void 0!==s&&(this.sense=s)}},e.ArcEdgeThreePointsDto=class{constructor(e,t,i){this.start=[0,0,0],this.middle=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.middle=t),void 0!==i&&(this.end=i)}},e.CylinderDto=class{constructor(e,t,i,s){this.radius=1,this.height=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.height=t),void 0!==i&&(this.center=i),void 0!==s&&(this.direction=s)}},e.CylindersOnLinesDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.lines=t)}},e.FilletDto=class{constructor(e,t,i,s){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.indexes=s)}},e.FilletEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i)}},e.FilletEdgesListOneRadiusDto=class{constructor(e,t,i){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radius=i)}},e.FilletEdgeVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.paramsU=s)}},e.FilletEdgesVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusLists=i),void 0!==s&&(this.paramsULists=s)}},e.FilletEdgesSameVariableRadiusDto=class{constructor(e,t,i,s){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.radiusList=i),void 0!==s&&(this.paramsU=s)}},e.Fillet3DWireDto=class{constructor(e,t,i,s,r){this.radius=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.direction=i),void 0!==s&&(this.radiusList=s),void 0!==r&&(this.indexes=r)}},e.ChamferDto=class{constructor(e,t,i,s){this.distance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.distance=t),void 0!==i&&(this.distanceList=i),void 0!==s&&(this.indexes=s)}},e.ChamferEdgesListDto=class{constructor(e,t,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.distanceList=i)}},e.ChamferEdgeDistAngleDto=class{constructor(e,t,i,s,r){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.angle=r)}},e.ChamferEdgeTwoDistancesDto=class{constructor(e,t,i,s,r){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.face=i),void 0!==s&&(this.distance1=s),void 0!==r&&(this.distance2=r)}},e.ChamferEdgesTwoDistancesListsDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distances1=s),void 0!==r&&(this.distances2=r)}},e.ChamferEdgesTwoDistancesDto=class{constructor(e,t,i,s,r){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distance1=s),void 0!==r&&(this.distance2=r)}},e.ChamferEdgesDistsAnglesDto=class{constructor(e,t,i,s,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distances=s),void 0!==r&&(this.angles=r)}},e.ChamferEdgesDistAngleDto=class{constructor(e,t,i,s,r){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==i&&(this.faces=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.angle=r)}},e.BSplineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BSplinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bSplines=e),void 0!==t&&(this.returnCompound=t)}},e.WireFromTwoCirclesTanDto=class{constructor(e,t,i,s,r){this.keepLines=f.outside,this.circleRemainders=p.outside,this.tolerance=1e-7,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==i&&(this.keepLines=i),void 0!==s&&(this.circleRemainders=s),void 0!==r&&(this.tolerance=r)}},e.FaceFromMultipleCircleTanWiresDto=class{constructor(e,t,i,s){this.combination=_.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.circles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==s&&(this.tolerance=s)}},e.FaceFromMultipleCircleTanWireCollectionsDto=class{constructor(e,t,i,s){this.combination=_.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.listsOfCircles=e),void 0!==t&&(this.combination=t),void 0!==i&&(this.unify=i),void 0!==s&&(this.tolerance=s)}},e.ZigZagBetweenTwoWiresDto=class{constructor(e,t,i,s,r,n){this.nrZigZags=20,this.divideByEqualDistance=!1,this.zigZagsPerEdge=!0,void 0!==e&&(this.wire1=e),void 0!==t&&(this.wire2=t),void 0!==i&&(this.nrZigZags=i),void 0!==s&&(this.inverse=s),void 0!==r&&(this.divideByEqualDistance=r),void 0!==n&&(this.zigZagsPerEdge=n)}},e.InterpolationDto=class{constructor(e,t,i){this.periodic=!1,this.tolerance=1e-7,void 0!==e&&(this.points=e),void 0!==t&&(this.periodic=t),void 0!==i&&(this.tolerance=i)}},e.InterpolateWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.interpolations=e),void 0!==t&&(this.returnCompound=t)}},e.BezierDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BezierWeightsDto=class{constructor(e,t,i){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.weights=t),void 0!==i&&(this.closed=i)}},e.BezierWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bezierWires=e),void 0!==t&&(this.returnCompound=t)}},e.DivideDto=class{constructor(e,t,i,s){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==s&&(this.removeEndPoint=s)}},e.ProjectWireDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wire=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.WiresToPointsDto=class{constructor(e,t,i,s,r,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==s&&(this.minimumOfPoints=s),void 0!==r&&(this.uTolerance=r),void 0!==n&&(this.minimumLength=n)}},e.EdgesToPointsDto=class{constructor(e,t,i,s,r,n){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==i&&(this.curvatureDeflection=i),void 0!==s&&(this.minimumOfPoints=s),void 0!==r&&(this.uTolerance=r),void 0!==n&&(this.minimumLength=n)}},e.ProjectWiresDto=class{constructor(e,t,i){this.direction=[0,1,0],void 0!==e&&(this.wires=e),void 0!==t&&(this.shape=t),void 0!==i&&(this.direction=i)}},e.DivideShapesDto=class{constructor(e,t,i,s){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==i&&(this.removeStartPoint=i),void 0!==s&&(this.removeEndPoint=s)}},e.DataOnGeometryAtParamDto=class{constructor(e,t){this.param=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t)}},e.PointInFaceDto=class{constructor(e,t,i,s){this.tEdgeParam=.5,this.distance2DParam=.5,void 0!==e&&(this.face=e),void 0!==t&&(this.edge=t),void 0!==i&&(this.tEdgeParam=i),void 0!==s&&(this.distance2DParam=s)}},e.DataOnGeometryAtLengthDto=class{constructor(e,t){this.length=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.length=t)}},e.CircleDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.LoftDto=class{constructor(e,t){this.makeSolid=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t)}},e.LoftAdvancedDto=class{constructor(e,t,i,r,n,o,a,l,h,c,u,d){this.makeSolid=!1,this.closed=!1,this.periodic=!1,this.straight=!1,this.nrPeriodicSections=10,this.useSmoothing=!1,this.maxUDegree=3,this.tolerance=1e-7,this.parType=s.approxCentripetal,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t),void 0!==i&&(this.closed=i),void 0!==r&&(this.periodic=r),void 0!==n&&(this.straight=n),void 0!==o&&(this.nrPeriodicSections=o),void 0!==a&&(this.useSmoothing=a),void 0!==l&&(this.maxUDegree=l),void 0!==h&&(this.tolerance=h),void 0!==c&&(this.parType=c),void 0!==u&&(this.startVertex=u),void 0!==d&&(this.endVertex=d)}},e.OffsetDto=class{constructor(e,t,i,s){this.distance=.2,this.tolerance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.face=t),void 0!==i&&(this.distance=i),void 0!==s&&(this.tolerance=s)}},e.OffsetAdvancedDto=class{constructor(e,i,s,r,n,o){this.distance=.2,this.tolerance=.1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.face=i),void 0!==s&&(this.distance=s),void 0!==r&&(this.tolerance=r),void 0!==n&&(this.joinType=n),void 0!==o&&(this.removeIntEdges=o)}},e.RevolveDto=class{constructor(e,t,i,s){this.angle=360,this.direction=[0,1,0],this.copy=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.direction=i),void 0!==s&&(this.copy=s)}},e.ShapeShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.WiresOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t)}},e.PipeWiresCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.radius=t)}},e.PipeWireCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t)}},e.PipePolygonWireNGonDto=class{constructor(e,t,i){this.radius=.1,this.nrCorners=6,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.nrCorners=i)}},e.ExtrudeDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t)}},e.ExtrudeShapesDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.direction=t)}},e.SplitDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.UnionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.DifferenceDto=class{constructor(e,t,i){this.keepEdges=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t),void 0!==i&&(this.keepEdges=i)}},e.IntersectionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.ShapeDto=class{constructor(e){void 0!==e&&(this.shape=e)}},e.CompareShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.otherShape=t)}},e.FixSmallEdgesInWireDto=class{constructor(e,t,i){this.lockvtx=!1,this.precsmall=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.lockvtx=t),void 0!==i&&(this.precsmall=i)}},e.BasicShapeRepairDto=class{constructor(e,t,i,s){this.precision=.001,this.maxTolerance=.01,this.minTolerance=1e-4,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.maxTolerance=i),void 0!==s&&(this.minTolerance=s)}},e.FixClosedDto=class{constructor(e,t){this.precision=-.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t)}},e.ShapesWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.ShapeWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.tolerance=t)}},e.ShapeIndexDto=class{constructor(e,t){this.index=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.EdgeIndexDto=class{constructor(e,t){this.index=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.RotationExtrudeDto=class{constructor(e,t,i){this.height=1,this.angle=360,void 0!==e&&(this.shape=e),void 0!==t&&(this.height=t),void 0!==i&&(this.angle=i)}},e.ThickSolidByJoinDto=class{constructor(e,i,s,r,n,o,a,l){this.offset=1,this.tolerance=.001,this.intersection=!1,this.selfIntersection=!1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==i&&(this.shapes=i),void 0!==s&&(this.offset=s),void 0!==r&&(this.tolerance=r),void 0!==n&&(this.intersection=n),void 0!==o&&(this.selfIntersection=o),void 0!==a&&(this.joinType=a),void 0!==l&&(this.removeIntEdges=l)}},e.TransformDto=class{constructor(e,t,i,s,r){this.translation=[0,0,0],this.rotationAxis=[0,1,0],this.rotationAngle=0,this.scaleFactor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t),void 0!==i&&(this.rotationAxis=i),void 0!==s&&(this.rotationAngle=s),void 0!==r&&(this.scaleFactor=r)}},e.TransformShapesDto=class{constructor(e,t,i,s,r){this.translations=[[0,0,0]],this.rotationAxes=[[0,1,0]],this.rotationAngles=[0],this.scaleFactors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t),void 0!==i&&(this.rotationAxes=i),void 0!==s&&(this.rotationAngles=s),void 0!==r&&(this.scaleFactors=r)}},e.TranslateDto=class{constructor(e,t){this.translation=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t)}},e.TranslateShapesDto=class{constructor(e,t){this.translations=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t)}},e.AlignDto=class{constructor(e,t,i,s,r){this.fromOrigin=[0,0,0],this.fromDirection=[0,0,1],this.toOrigin=[0,1,0],this.toDirection=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.fromOrigin=t),void 0!==i&&(this.fromDirection=i),void 0!==s&&(this.toOrigin=s),void 0!==r&&(this.toDirection=r)}},e.AlignShapesDto=class{constructor(e,t,i,s,r){this.fromOrigins=[[0,0,0]],this.fromDirections=[[0,0,1]],this.toOrigins=[[0,1,0]],this.toDirections=[[0,1,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.fromOrigins=t),void 0!==i&&(this.fromDirections=i),void 0!==s&&(this.toOrigins=s),void 0!==r&&(this.toDirections=r)}},e.MirrorDto=class{constructor(e,t,i){this.origin=[0,0,0],this.direction=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.direction=i)}},e.MirrorShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.directions=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.directions=i)}},e.MirrorAlongNormalDto=class{constructor(e,t,i){this.origin=[0,0,0],this.normal=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==i&&(this.normal=i)}},e.MirrorAlongNormalShapesDto=class{constructor(e,t,i){this.origins=[[0,0,0]],this.normals=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==i&&(this.normals=i)}},e.AlignAndTranslateDto=class{constructor(e,t,i){this.direction=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.center=i)}},e.UnifySameDomainDto=class{constructor(e,t,i,s){this.unifyEdges=!0,this.unifyFaces=!0,this.concatBSplines=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.unifyEdges=t),void 0!==i&&(this.unifyFaces=i),void 0!==s&&(this.concatBSplines=s)}},e.FilterFacePointsDto=class{constructor(e,t,i,s,r,n,o,a,l){this.tolerance=1e-4,this.useBndBox=!1,this.gapTolerance=.1,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.useBndBox=s),void 0!==r&&(this.gapTolerance=r),void 0!==n&&(this.keepIn=n),void 0!==o&&(this.keepOn=o),void 0!==a&&(this.keepOut=a),void 0!==l&&(this.keepUnknown=l)}},e.FilterSolidPointsDto=class{constructor(e,t,i,s,r,n,o){this.tolerance=1e-4,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==i&&(this.tolerance=i),void 0!==s&&(this.keepIn=s),void 0!==r&&(this.keepOn=r),void 0!==n&&(this.keepOut=n),void 0!==o&&(this.keepUnknown=o)}},e.AlignAndTranslateShapesDto=class{constructor(e,t,i){this.directions=[[0,1,0]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.directions=t),void 0!==i&&(this.centers=i)}},e.RotateDto=class{constructor(e,t,i){this.axis=[0,0,1],this.angle=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.axis=t),void 0!==i&&(this.angle=i)}},e.RotateAroundCenterDto=class{constructor(e,t,i,s){this.angle=0,this.center=[0,0,0],this.axis=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.center=i),void 0!==s&&(this.axis=s)}},e.RotateShapesDto=class{constructor(e,t,i){this.angles=[0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.axes=t),void 0!==i&&(this.angles=i)}},e.RotateAroundCenterShapesDto=class{constructor(e,t,i,s){this.angles=[0],this.centers=[[0,0,0]],this.axes=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.angles=t),void 0!==i&&(this.centers=i),void 0!==s&&(this.axes=s)}},e.ScaleDto=class{constructor(e,t){this.factor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.factor=t)}},e.ScaleShapesDto=class{constructor(e,t){this.factors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.factors=t)}},e.Scale3DDto=class{constructor(e,t,i){this.scale=[1,1,1],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.scale=t),void 0!==i&&(this.center=i)}},e.Scale3DShapesDto=class{constructor(e,t,i){this.scales=[[1,1,1]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.scales=t),void 0!==i&&(this.centers=i)}},e.ShapeToMeshDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.ShapesToMeshesDto=class{constructor(e,t,i){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.precision=t),void 0!==i&&(this.adjustYtoZ=i)}},e.SaveStepDto=class{constructor(e,t,i,s){this.fileName="shape.step",this.adjustYtoZ=!1,this.tryDownload=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustYtoZ=i),void 0!==s&&(this.tryDownload=s)}},e.SaveStlDto=class{constructor(e,t,i,s,r,n){this.fileName="shape.stl",this.precision=.01,this.adjustYtoZ=!1,this.tryDownload=!0,this.binary=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.precision=i),void 0!==s&&(this.adjustYtoZ=s),void 0!==r&&(this.tryDownload=r),void 0!==n&&(this.binary=n)}},e.ImportStepIgesFromTextDto=class{constructor(e,t,i){this.fileType=n.step,this.adjustZtoY=!0,void 0!==e&&(this.text=e),void 0!==t&&(this.fileType=t),void 0!==i&&(this.adjustZtoY=i)}},e.ImportStepIgesDto=class{constructor(e,t){this.adjustZtoY=!0,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.adjustZtoY=t)}},e.LoadStepOrIgesDto=class{constructor(e,t,i){this.fileName="shape.igs",this.adjustZtoY=!0,void 0!==e&&(this.filetext=e),void 0!==t&&(this.fileName=t),void 0!==i&&(this.adjustZtoY=i)}},e.CompoundShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.ThisckSolidSimpleDto=class{constructor(e,t){this.offset=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t)}},e.Offset3DWireDto=class{constructor(e,t,i){this.offset=1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t),void 0!==i&&(this.direction=i)}},e.FaceFromWireDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.planar=t)}},e.FaceFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.FacesFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.SewDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.FaceIsoCurveAtParamDto=class{constructor(e,t,i){this.dir="u",void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t),void 0!==i&&(this.dir=i)}},e.DivideFaceToUVPointsDto=class{constructor(e,t,i,s){this.nrOfPointsU=10,this.nrOfPointsV=10,this.flat=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfPointsU=t),void 0!==i&&(this.nrOfPointsV=i),void 0!==s&&(this.flat=s)}},e.Geom2dEllipseDto=class{constructor(e,t,i,s,r){this.center=[0,0],this.direction=[1,0],this.radiusMinor=1,this.radiusMajor=2,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==s&&(this.radiusMajor=s),void 0!==r&&(this.sense=r)}},e.Geom2dCircleDto=class{constructor(e,t,i,s){this.center=[0,0],this.direction=[1,0],this.radius=1,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.sense=s)}},e.ChristmasTreeDto=class{constructor(e,t,i,s,r,n,o,a,l,h){this.height=6,this.innerDist=1.5,this.outerDist=3,this.nrSkirts=5,this.trunkHeight=1,this.trunkWidth=1,this.half=!1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.innerDist=t),void 0!==i&&(this.outerDist=i),void 0!==s&&(this.nrSkirts=s),void 0!==r&&(this.trunkHeight=r),void 0!==n&&(this.trunkWidth=n),void 0!==o&&(this.half=o),void 0!==a&&(this.rotation=a),void 0!==l&&(this.origin=l),void 0!==h&&(this.direction=h)}},e.StarDto=class{constructor(e,t,i,s,r,n,o){this.center=[0,0,0],this.direction=[0,1,0],this.numRays=7,this.half=!1,void 0!==e&&(this.outerRadius=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.numRays=i),void 0!==s&&(this.center=s),void 0!==r&&(this.direction=r),void 0!==n&&(this.offsetOuterEdges=n),void 0!==o&&(this.half=o)}},e.ParallelogramDto=class{constructor(e,t,i,s,r,n){this.center=[0,0,0],this.direction=[0,1,0],this.aroundCenter=!0,this.width=2,this.height=1,this.angle=15,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.aroundCenter=i),void 0!==s&&(this.width=s),void 0!==r&&(this.height=r),void 0!==n&&(this.angle=n)}},e.Heart2DDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.rotation=0,this.sizeApprox=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.rotation=i),void 0!==s&&(this.sizeApprox=s)}},e.NGonWireDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.nrCorners=6,this.radius=1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.nrCorners=i),void 0!==s&&(this.radius=s)}},e.EllipseDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.direction=[0,1,0],this.radiusMinor=1,this.radiusMajor=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==i&&(this.radiusMinor=i),void 0!==s&&(this.radiusMajor=s)}},e.GeomCylindricalSurfaceDto=class{constructor(e,t,i){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==i&&(this.direction=i)}},e.Geom2dTrimmedCurveDto=class{constructor(e,t,i,s,r){this.u1=0,this.u2=1,this.sense=!0,this.adjustPeriodic=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.u1=t),void 0!==i&&(this.u2=i),void 0!==s&&(this.sense=s),void 0!==r&&(this.adjustPeriodic=r)}},e.Geom2dSegmentDto=class{constructor(e,t){this.start=[0,0],this.end=[1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.SliceDto=class{constructor(e,t,i){this.step=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.step=t),void 0!==i&&(this.direction=i)}},e.SliceInStepPatternDto=class{constructor(e,t,i){this.steps=[.1,.2],this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.steps=t),void 0!==i&&(this.direction=i)}}}(n||(n={})),function(e){let t;!function(e){e.default="default",e.clearSky="clearSky",e.city="city"}(t=e.skyboxEnum||(e.skyboxEnum={}))}(o||(o={})),"undefined"!=typeof document&&document.currentScript&&document.currentScript.src,function(e){let t,i;!function(e){e.edge="edge",e.round="round",e.chamfer="chamfer"}(t=e.solidCornerTypeEnum||(e.solidCornerTypeEnum={})),function(e){e.left="left",e.center="center",e.right="right"}(i=e.jscadTextAlignEnum||(e.jscadTextAlignEnum={})),e.DrawSolidMeshDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.mesh=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.jscadMesh=n)}},e.DrawSolidMeshesDto=class{constructor(e,t,i,s,r,n){this.opacity=1,this.colours="#444444",this.updatable=!1,this.hidden=!1,void 0!==e&&(this.meshes=e),void 0!==t&&(this.opacity=t),void 0!==i&&(this.colours=i),void 0!==s&&(this.updatable=s),void 0!==r&&(this.hidden=r),void 0!==n&&(this.jscadMesh=n)}},e.DrawPathDto=class{constructor(e,t,i,s,r,n){this.colour="#444444",this.opacity=1,this.width=10,this.updatable=!1,void 0!==e&&(this.path=e),void 0!==t&&(this.colour=t),void 0!==i&&(this.opacity=i),void 0!==s&&(this.width=s),void 0!==r&&(this.updatable=r),void 0!==n&&(this.pathMesh=n)}},e.TransformSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.transformation=t)}},e.TransformSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.transformation=t)}},e.DownloadSolidDto=class{constructor(e,t){void 0!==e&&(this.mesh=e),void 0!==t&&(this.fileName=t)}},e.DownloadGeometryDto=class{constructor(e,t){void 0!==e&&(this.geometry=e),void 0!==t&&(this.fileName=t)}},e.DownloadSolidsDto=class{constructor(e,t){void 0!==e&&(this.meshes=e),void 0!==t&&(this.fileName=t)}},e.ColorizeDto=class{constructor(e,t){this.color="#0000ff",void 0!==e&&(this.geometry=e),void 0!==t&&(this.color=t)}},e.BooleanObjectsDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.BooleanTwoObjectsDto=class{constructor(e,t){void 0!==e&&(this.first=e),void 0!==t&&(this.second=t)}},e.BooleanObjectsFromDto=class{constructor(e,t){void 0!==e&&(this.from=e),void 0!==t&&(this.meshes=t)}},e.ExpansionDto=class{constructor(e,i,s,r){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==s&&(this.corners=s),void 0!==r&&(this.segments=r)}},e.OffsetDto=class{constructor(e,i,s,r){this.delta=.1,this.corners=t.edge,this.segments=24,void 0!==e&&(this.geometry=e),void 0!==i&&(this.delta=i),void 0!==s&&(this.corners=s),void 0!==r&&(this.segments=r)}},e.ExtrudeLinearDto=class{constructor(e,t,i,s){this.height=1,this.twistAngle=90,this.twistSteps=15,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.twistAngle=i),void 0!==s&&(this.twistSteps=s)}},e.HullDto=class{constructor(e){void 0!==e&&(this.meshes=e)}},e.ExtrudeRectangularDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.geometry=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRectangularPointsDto=class{constructor(e,t,i){this.height=1,this.size=1,void 0!==e&&(this.points=e),void 0!==t&&(this.height=t),void 0!==i&&(this.size=i)}},e.ExtrudeRotateDto=class{constructor(e,t,i,s){this.angle=90,this.startAngle=0,this.segments=24,void 0!==e&&(this.polygon=e),void 0!==t&&(this.angle=t),void 0!==i&&(this.startAngle=i),void 0!==s&&(this.segments=s)}},e.PathDto=class{constructor(e){void 0!==e&&(this.path=e)}},e.PathFromPointsDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.PathsFromPointsDto=class{constructor(e){void 0!==e&&(this.pointsLists=e)}},e.PathFromPolylineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.polyline=e),void 0!==t&&(this.closed=t)}},e.PathAppendCurveDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.path=t)}},e.PathAppendPointsDto=class{constructor(e,t){void 0!==e&&(this.points=e),void 0!==t&&(this.path=t)}},e.PathAppendPolylineDto=class{constructor(e,t){void 0!==e&&(this.polyline=e),void 0!==t&&(this.path=t)}},e.PathAppendArcDto=class{constructor(e,t,i,s,r,n,o,a){this.endPoint=[1,1],this.xAxisRotation=90,this.clockwise=!0,this.large=!1,this.segments=24,this.radiusX=1,this.radiusY=1,void 0!==e&&(this.path=e),void 0!==t&&(this.endPoint=t),void 0!==i&&(this.xAxisRotation=i),void 0!==s&&(this.clockwise=s),void 0!==r&&(this.large=r),void 0!==n&&(this.segments=n),void 0!==o&&(this.radiusX=o),void 0!==a&&(this.radiusY=a)}},e.CircleDto=class{constructor(e,t,i){this.center=[0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipseDto=class{constructor(e,t,i){this.center=[0,0],this.radius=[1,2],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SquareDto=class{constructor(e,t){this.center=[0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.RectangleDto=class{constructor(e,t,i){this.center=[0,0],this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i)}},e.RoundedRectangleDto=class{constructor(e,t,i,s,r){this.center=[0,0],this.roundRadius=.2,this.segments=24,this.width=1,this.length=1,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.segments=i),void 0!==s&&(this.width=s),void 0!==r&&(this.length=r)}},e.StarDto=class{constructor(e,t,i,s,r,n){this.center=[0,0],this.vertices=10,this.density=1,this.outerRadius=2,this.innerRadius=1,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.vertices=t),void 0!==i&&(this.density=i),void 0!==s&&(this.outerRadius=s),void 0!==r&&(this.innerRadius=r),void 0!==n&&(this.startAngle=n)}},e.CubeDto=class{constructor(e,t){this.center=[0,0,0],this.size=1,void 0!==e&&(this.center=e),void 0!==t&&(this.size=t)}},e.CubeCentersDto=class{constructor(e,t){this.size=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.size=t)}},e.CuboidDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.width=1,this.length=1,this.height=1,void 0!==e&&(this.center=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.height=s)}},e.CuboidCentersDto=class{constructor(e,t,i,s){this.width=1,this.length=1,this.height=1,void 0!==e&&(this.centers=e),void 0!==t&&(this.width=t),void 0!==i&&(this.length=i),void 0!==s&&(this.height=s)}},e.RoundedCuboidDto=class{constructor(e,t,i,s,r,n){this.center=[0,0,0],this.roundRadius=1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==s&&(this.length=s),void 0!==r&&(this.height=r),void 0!==n&&(this.segments=n)}},e.RoundedCuboidCentersDto=class{constructor(e,t,i,s,r,n){this.roundRadius=.1,this.width=1,this.length=1,this.height=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.width=i),void 0!==s&&(this.length=s),void 0!==r&&(this.height=r),void 0!==n&&(this.segments=n)}},e.CylidnerEllipticDto=class{constructor(e,t,i,s,r){this.center=[0,0,0],this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==s&&(this.endRadius=s),void 0!==r&&(this.segments=r)}},e.CylidnerCentersEllipticDto=class{constructor(e,t,i,s,r){this.height=1,this.startRadius=[1,2],this.endRadius=[2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.startRadius=i),void 0!==s&&(this.endRadius=s),void 0!==r&&(this.segments=r)}},e.CylidnerDto=class{constructor(e,t,i,s){this.center=[0,0,0],this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.segments=s)}},e.RoundedCylidnerDto=class{constructor(e,t,i,s,r){this.center=[0,0,0],this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==s&&(this.radius=s),void 0!==r&&(this.segments=r)}},e.EllipsoidDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.EllipsoidCentersDto=class{constructor(e,t,i){this.radius=[1,2,3],this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.GeodesicSphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.frequency=12,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.GeodesicSphereCentersDto=class{constructor(e,t,i){this.radius=1,this.frequency=12,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.frequency=i)}},e.CylidnerCentersDto=class{constructor(e,t,i,s){this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.height=t),void 0!==i&&(this.radius=i),void 0!==s&&(this.segments=s)}},e.RoundedCylidnerCentersDto=class{constructor(e,t,i,s,r){this.roundRadius=.1,this.height=1,this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.roundRadius=t),void 0!==i&&(this.height=i),void 0!==s&&(this.radius=s),void 0!==r&&(this.segments=r)}},e.SphereDto=class{constructor(e,t,i){this.center=[0,0,0],this.radius=1,this.segments=24,void 0!==e&&(this.center=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.SphereCentersDto=class{constructor(e,t,i){this.radius=1,this.segments=24,void 0!==e&&(this.centers=e),void 0!==t&&(this.radius=t),void 0!==i&&(this.segments=i)}},e.TorusDto=class{constructor(e,t,i,s,r,n,o,a){this.center=[0,0,0],this.innerRadius=1,this.outerRadius=2,this.innerSegments=24,this.outerSegments=24,this.innerRotation=0,this.outerRotation=360,this.startAngle=0,void 0!==e&&(this.center=e),void 0!==t&&(this.innerRadius=t),void 0!==i&&(this.outerRadius=i),void 0!==s&&(this.innerSegments=s),void 0!==r&&(this.outerSegments=r),void 0!==n&&(this.innerRotation=n),void 0!==o&&(this.outerRotation=o),void 0!==a&&(this.startAngle=a)}},e.TextDto=class{constructor(e,t,s,r,n,o,a,l,h){this.text="Hello World",this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.segments=t),void 0!==s&&(this.xOffset=s),void 0!==r&&(this.yOffset=r),void 0!==n&&(this.height=n),void 0!==o&&(this.lineSpacing=o),void 0!==a&&(this.letterSpacing=a),void 0!==l&&(this.align=l),void 0!==h&&(this.extrudeOffset=h)}},e.CylinderTextDto=class{constructor(e,t,s,r,n,o,a,l,h,c,u){this.text="Hello World",this.extrusionHeight=.5,this.extrusionSize=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.extrusionHeight=t),void 0!==s&&(this.extrusionSize=s),void 0!==r&&(this.segments=r),void 0!==n&&(this.xOffset=n),void 0!==o&&(this.yOffset=o),void 0!==a&&(this.height=a),void 0!==l&&(this.lineSpacing=l),void 0!==h&&(this.letterSpacing=h),void 0!==c&&(this.align=c),void 0!==u&&(this.extrudeOffset=u)}},e.SphereTextDto=class{constructor(e,t,s,r,n,o,a,l,h,c){this.text="Hello World",this.radius=.1,this.segments=24,this.xOffset=0,this.yOffset=0,this.height=1,this.lineSpacing=1.4,this.letterSpacing=1,this.align=i.center,this.extrudeOffset=0,void 0!==e&&(this.text=e),void 0!==t&&(this.radius=t),void 0!==s&&(this.segments=s),void 0!==r&&(this.xOffset=r),void 0!==n&&(this.yOffset=n),void 0!==o&&(this.height=o),void 0!==a&&(this.lineSpacing=a),void 0!==l&&(this.letterSpacing=l),void 0!==h&&(this.align=h),void 0!==c&&(this.extrudeOffset=c)}},e.FromPolygonPoints=class{constructor(e){void 0!==e&&(this.polygonPoints=e)}}}(a||(a={}));class l{constructor(e){this.jscad=e}expand(e){const t=e.geometry.length&&e.geometry.length>0?e.geometry:[e.geometry];return e.corners||(e.corners=a.solidCornerTypeEnum.round),this.jscad.expansions.expand({delta:e.delta,corners:e.corners,segments:e.segments},...t)}offset(e){const t=e.geometry.length&&e.geometry.length>0?e.geometry:[e.geometry];return e.corners||(e.corners=a.solidCornerTypeEnum.edge),this.jscad.expansions.offset({delta:e.delta,corners:e.corners,segments:e.segments},...t)}}class h{constructor(e){this.jscad=e}intersect(e){return this.jscad.booleans.intersect(...e.meshes)}subtract(e){return this.jscad.booleans.subtract(...e.meshes)}union(e){return this.jscad.booleans.union(...e.meshes)}intersectTwo(e){const t=[e.first,e.second];return this.jscad.booleans.intersect(...t)}subtractTwo(e){const t=[e.first,e.second];return this.jscad.booleans.subtract(...t)}unionTwo(e){const t=[e.first,e.second];return this.jscad.booleans.union(...t)}subtractFrom(e){const t=[e.from,...e.meshes];return this.jscad.booleans.subtract(...t)}}const c={};function u(e,t){c[e]=t}function d(e){return c[e]}class p{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,i,s){for(const r in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,r)&&this._BabylonFileParsers[r](e,t,i,s)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach((t=>e=e.concat(t.bones))),e}}p._BabylonFileParsers={},p._IndividualBabylonFileParsers={},u("BABYLON.AbstractScene",p);class f{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(const e in f.Triggers)if(Object.prototype.hasOwnProperty.call(f.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in f.Triggers)if(Object.prototype.hasOwnProperty.call(f.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in f.Triggers)if(Object.prototype.hasOwnProperty.call(f.Triggers,t)&&parseInt(t)===e)return!0;return!1}}f.Triggers={};class _{constructor(e,t=!1,i,s){this.initialize(e,t,i,s)}initialize(e,t=!1,i,s){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=s,this}}class m{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class g{static FromPromise(e,t){const i=new g;return e.then((e=>{i.notifyObservers(e)})).catch((e=>{if(!t)throw e;t.notifyObservers(e)})),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new _(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,s=null,r=!1){if(!e)return null;const n=new m(e,t,s);return n.unregisterOnNextCall=r,i?this._observers.unshift(n):this._observers.push(n),this._onObserverAdded&&this._onObserverAdded(n),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(n,this._lastNotifiedValue),n._remove=()=>{this.remove(n)},n}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return!!e&&(e._remove=null,-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))}removeCallback(e,t){for(let i=0;i{this._remove(e)}),0))}_remove(e,t=!0){if(!e)return!1;const i=this._observers.indexOf(e);return-1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,s,r){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const n=this._eventState;n.mask=t,n.target=i,n.currentTarget=s,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=r;for(const i of this._observers)if(!i._willBeUnregistered&&(i.mask&t&&(i.unregisterOnNextCall&&this._deferUnregister(i),i.scope?n.lastReturnValue=i.callback.apply(i.scope,[e,n]):n.lastReturnValue=i.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const s=this._eventState;s.mask=i,s.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,s)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new g;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}const v=1/2.2,x=2.2,T=(Math.sqrt(5),.001);class S{static BuildArray(e,t){const i=[];for(let s=0;sfunction(e,t,i){const s=e[t];if("function"!=typeof s)return null;const r=function(){const s=e.length,n=r.previous.apply(e,arguments);return i(t,s),n};return s.next=r,r.previous=s,e[t]=r,()=>{const i=r.previous;if(!i)return;const s=r.next;s?(i.next=s,s.previous=i):(i.next=void 0,e[t]=i),r.next=void 0,r.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{e?.()}))}}class C{static SetMatrixPrecision(e){if(C.MatrixTrackPrecisionChange=!1,e&&!C.MatrixUse64Bits&&C.MatrixTrackedMatrices)for(let e=0;eparseInt(e.toString().replace(/\W/g,""));class N{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=O(this.x);return e=397*e^O(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return N.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new N(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new N(this.x+e.x,this.y+e.y)}subtract(e){return new N(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new N(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new N(this.x*e,this.y*t)}divide(e){return new N(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new N(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.x=this.x-e,i.y=this.y-t,i}negate(){return new N(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new N(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=T){return e&&A(this.x,e.x,t)&&A(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new N(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new N(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotateToRef(e,t){const i=Math.cos(e),s=Math.sin(e),r=i*this.x-s*this.y,n=s*this.x+i*this.y;return t.x=r,t.y=n,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new N;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new N(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new N(0,0)}static One(){return new N(1,1)}static Random(e=0,t=1){return new N(R(e,t),R(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(R(e,t),R(e,t))}static get ZeroReadOnly(){return N._ZeroReadOnly}static FromArray(e,t=0){return new N(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,a=.5*(2*t.x+(-e.x+i.x)*r+(2*e.x-5*t.x+4*i.x-s.x)*n+(-e.x+3*t.x-3*i.x+s.x)*o),l=.5*(2*t.y+(-e.y+i.y)*r+(2*e.y-5*t.y+4*i.y-s.y)*n+(-e.y+3*t.y-3*i.y+s.y)*o);return new N(a,l)}static ClampToRef(e,t,i,s){return s.x=P(e.x,t.x,i.x),s.y=P(e.y,t.y,i.y),s}static Clamp(e,t,i){const s=P(e.x,t.x,i.x),r=P(e.y,t.y,i.y);return new N(s,r)}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.x*a+i.x*l+t.x*h+s.x*c,d=e.y*a+i.y*l+t.y*h+s.y*c;return new N(u,d)}static Hermite1stDerivative(e,t,i,s,r){return this.Hermite1stDerivativeToRef(e,t,i,s,r,new N)}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n.x=6*(o-r)*e.x+(3*o-4*r+1)*t.x+6*(-o+r)*i.x+(3*o-2*r)*s.x,n.y=6*(o-r)*e.y+(3*o-4*r+1)*t.y+6*(-o+r)*i.y+(3*o-2*r)*s.y,n}static Lerp(e,t,i){const s=e.x+(t.x-e.x)*i,r=e.y+(t.y-e.y)*i;return new N(s,r)}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return N.NormalizeToRef(e,new N)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=e.xt.x?e.x:t.x,s=e.y>t.y?e.y:t.y;return new N(i,s)}static Transform(e,t){return N.TransformToRef(e,t,new N)}static TransformToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+s[12],n=e.x*s[1]+e.y*s[5]+s[13];return i.x=r,i.y=n,i}static PointInTriangle(e,t,i,s){const r=.5*(-i.y*s.x+t.y*(-i.x+s.x)+t.x*(i.y-s.y)+i.x*s.y),n=r<0?-1:1,o=(t.y*s.x-t.x*s.y+(s.y-t.y)*e.x+(t.x-s.x)*e.y)*n,a=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*n;return o>0&&a>0&&o+a<2*r*n}static Distance(e,t){return Math.sqrt(N.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y;return i*i+s*s}static Center(e,t){return N.CenterToRef(e,t,new N)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){const s=N.DistanceSquared(t,i);if(0===s)return N.Distance(e,t);const r=i.subtract(t),n=Math.max(0,Math.min(1,N.Dot(e.subtract(t),r)/s)),o=t.add(r.multiplyByFloats(n,n));return N.Distance(e,o)}}N._ZeroReadOnly=N.Zero(),Object.defineProperties(N.prototype,{dimension:{value:[2]},rank:{value:1}});class w{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=O(this._x);return e=397*e^O(this._y),e=397*e^O(this._z),e}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return w.FromArrayToRef(e,t,this),this}toQuaternion(){return L.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new w(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new w(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new w(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,s){return s.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new w(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new w(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){const t=this.length();let i=Math.acos(this.y/t);const s=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;const r=t*Math.sin(i)*Math.cos(s),n=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(s);return e.set(r,n,o),e}applyRotationQuaternionToRef(e,t){const i=this._x,s=this._y,r=this._z,n=e._x,o=e._y,a=e._z,l=e._w,h=2*(o*r-a*s),c=2*(a*i-n*r),u=2*(n*s-o*i);return t._x=i+l*h+o*u-a*c,t._y=s+l*c+a*h-n*u,t._z=r+l*u+n*c-o*h,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new w)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new w)}projectOnPlaneToRef(e,t,i){const s=e.normal,r=e.d,n=V.Vector3[0];this.subtractToRef(t,n),n.normalize();const o=w.Dot(n,s);if(Math.abs(o)<1e-10)i.setAll(1/0);else{const e=-(w.Dot(t,s)+r)/o,a=n.scaleInPlace(e);t.addToRef(a,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=T){return e&&A(this._x,e._x,t)&&A(this._y,e._y,t)&&A(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new w(this._x*e,this._y*t,this._z*i)}divide(e){return new w(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),i=Math.abs(this._y);if(!A(t,i,e))return!0;const s=Math.abs(this._z);return!A(t,s,e)||!A(i,s,e)}get isNonUniform(){const e=Math.abs(this._x);return e!==Math.abs(this._y)||e!==Math.abs(this._z)}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new w(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))}fractToRef(e){return e._x=this.x-Math.floor(this._x),e._y=this.y-Math.floor(this._y),e._z=this.z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new w(this.x-Math.floor(this._x),this.y-Math.floor(this._y),this.z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z==0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if("xyz"===(e=e.toLowerCase()))return this;const t=V.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(V.Matrix[0]),w.TransformCoordinatesToRef(this,V.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,V.Vector3[0]),V.Vector3[0].rotateByQuaternionToRef(e,V.Vector3[0]),t.addToRef(V.Vector3[0],i),i}cross(e){return w.CrossToRef(this,e,new w)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new w)}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFrom(this):this.scaleToRef(1/t,e)}clone(){return new w(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,s){const r=w.Dot(e,i);return(r-s)/(r-w.Dot(t,i))}static GetAngleBetweenVectors(e,t,i){const s=e.normalizeToRef(V.Vector3[1]),r=t.normalizeToRef(V.Vector3[2]);let n=w.Dot(s,r);n=P(n,-1,1);const o=Math.acos(n),a=V.Vector3[3];return w.CrossToRef(s,r,a),w.Dot(a,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){V.Vector3[0].copyFrom(e);const s=V.Vector3[0];V.Vector3[1].copyFrom(t);const r=V.Vector3[1];V.Vector3[2].copyFrom(i);const n=V.Vector3[2],o=V.Vector3[3],a=V.Vector3[4];return s.normalize(),r.normalize(),n.normalize(),w.CrossToRef(n,s,o),w.CrossToRef(o,n,a),M(Math.atan2(w.Dot(r,o),w.Dot(r,a)))}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){const s=U.Vector3[0];return t.subtractToRef(e,s),i._y=Math.atan2(s.x,s.z)||0,i._x=Math.atan2(Math.sqrt(s.x**2+s.z**2),s.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){const i=w.Zero();return w.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,s){i=P(i,0,1);const r=V.Vector3[0],n=V.Vector3[1];r.copyFrom(e);const o=r.length();r.normalizeFromLength(o),n.copyFrom(t);const a=n.length();n.normalizeFromLength(a);const l=w.Dot(r,n);let h,c;if(l<1-T){const e=Math.acos(l),t=1/Math.sin(e);h=Math.sin((1-i)*e)*t,c=Math.sin(i*e)*t}else h=1-i,c=i;return r.scaleInPlace(h),n.scaleInPlace(c),s.copyFrom(r).addInPlace(n),s.scaleInPlace(I(o,a,i)),s}static SmoothToRef(e,t,i,s,r){return w.SlerpToRef(e,t,0===s?1:i/s,r),r}static FromArray(e,t=0){return new w(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return w.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return w.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,s){return s.copyFromFloats(e,t,i),s}static Zero(){return new w(0,0,0)}static One(){return new w(1,1,1)}static Up(){return new w(0,1,0)}static get UpReadOnly(){return w._UpReadOnly}static get DownReadOnly(){return w._DownReadOnly}static get RightReadOnly(){return w._RightReadOnly}static get LeftReadOnly(){return w._LeftReadOnly}static get LeftHandedForwardReadOnly(){return w._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return w._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return w._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return w._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return w._ZeroReadOnly}static get OneReadOnly(){return w._OneReadOnly}static Down(){return new w(0,-1,0)}static Forward(e=!1){return new w(0,0,e?-1:1)}static Backward(e=!1){return new w(0,0,e?1:-1)}static Right(){return new w(1,0,0)}static Left(){return new w(-1,0,0)}static Random(e=0,t=1){return new w(R(e,t),R(e,t),R(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(R(e,t),R(e,t),R(e,t))}static TransformCoordinates(e,t){const i=w.Zero();return w.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return w.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=1/(e*n[3]+t*n[7]+i*n[11]+n[15]);return r._x=o*h,r._y=a*h,r._z=l*h,r._isDirty=!0,r}static TransformNormal(e,t){const i=w.Zero();return w.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,s,r){const n=s.m;return r._x=e*n[0]+t*n[4]+i*n[8],r._y=e*n[1]+t*n[5]+i*n[9],r._z=e*n[2]+t*n[6]+i*n[10],r._isDirty=!0,r}static CatmullRom(e,t,i,s,r){const n=r*r,o=r*n,a=.5*(2*t._x+(-e._x+i._x)*r+(2*e._x-5*t._x+4*i._x-s._x)*n+(-e._x+3*t._x-3*i._x+s._x)*o),l=.5*(2*t._y+(-e._y+i._y)*r+(2*e._y-5*t._y+4*i._y-s._y)*n+(-e._y+3*t._y-3*i._y+s._y)*o),h=.5*(2*t._z+(-e._z+i._z)*r+(2*e._z-5*t._z+4*i._z-s._z)*n+(-e._z+3*t._z-3*i._z+s._z)*o);return new w(a,l,h)}static Clamp(e,t,i){const s=new w;return w.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){let r=e._x;r=r>i._x?i._x:r,r=ri._y?i._y:n,n=ni._z?i._z:o,o=o0&&A<0?(I.copyFrom(n),M=t,D=i):A>0&&R<0?(I.copyFrom(a),M=i,D=s):(I.copyFrom(o).scaleInPlace(-1),M=s,D=t);const O=V.Vector3[9],N=V.Vector3[4];if(M.subtractToRef(g,E),D.subtractToRef(g,O),w.CrossToRef(E,O,N),!(w.Dot(N,l)<0))return r.copyFrom(g),Math.abs(f*_);const F=V.Vector3[5];w.CrossToRef(I,N,F),F.normalize();const L=V.Vector3[9];L.copyFrom(M).subtractInPlace(g);const B=L.length();if(Bthis.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,s){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(i,this.z),this.w=Math.min(s,this.w),this}maximizeInPlaceFromFloats(e,t,i,s){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(i,this.z),this.w=Math.max(s,this.w),this}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e}floor(){return new F(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e.z=this.z-Math.floor(this.z),e.w=this.w-Math.floor(this.w),e}fract(){return new F(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new F)}normalizeToRef(e){const t=this.length();return 0===t||1===t?(e.x=this.x,e.y=this.y,e.z=this.z,e.w=this.w,e):this.scaleToRef(1/t,e)}toVector3(){return new w(this.x,this.y,this.z)}clone(){return new F(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}static FromArray(e,t){return t||(t=0),new F(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return F.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,s,r){return r.x=e,r.y=t,r.z=i,r.w=s,r}static Zero(){return new F(0,0,0,0)}static One(){return new F(1,1,1,1)}static Random(e=0,t=1){return new F(R(e,t),R(e,t),R(e,t),R(e,t))}static RandomToRef(e=0,t=1,i){return i.x=R(e,t),i.y=R(e,t),i.z=R(e,t),i.w=R(e,t),i}static Clamp(e,t,i){return F.ClampToRef(e,t,i,new F)}static ClampToRef(e,t,i,s){return s.x=P(e.x,t.x,i.x),s.y=P(e.y,t.y,i.y),s.z=P(e.z,t.z,i.z),s.w=P(e.w,t.w,i.w),s}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return F._ZeroReadOnly}static Normalize(e){return F.NormalizeToRef(e,new F)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const i=new F;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){const i=new F;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(F.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return F.CenterToRef(e,t,new F)}static CenterToRef(e,t,i){return i.x=(e.x+t.x)/2,i.y=(e.y+t.y)/2,i.z=(e.z+t.z)/2,i.w=(e.w+t.w)/2,i}static TransformCoordinates(e,t){return F.TransformCoordinatesToRef(e,t,new F)}static TransformCoordinatesToRef(e,t,i){return F.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,s,r){const n=s.m,o=e*n[0]+t*n[4]+i*n[8]+n[12],a=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=e*n[3]+t*n[7]+i*n[11]+n[15];return r.x=o,r.y=a,r.z=l,r.w=h,r}static TransformNormal(e,t){return F.TransformNormalToRef(e,t,new F)}static TransformNormalToRef(e,t,i){const s=t.m,r=e.x*s[0]+e.y*s[4]+e.z*s[8],n=e.x*s[1]+e.y*s[5]+e.z*s[9],o=e.x*s[2]+e.y*s[6]+e.z*s[10];return i.x=r,i.y=n,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,s,r,n){const o=r.m;return n.x=e*o[0]+t*o[4]+i*o[8],n.y=e*o[1]+t*o[5]+i*o[9],n.z=e*o[2]+t*o[6]+i*o[10],n.w=s,n}static FromVector3(e,t=0){return new F(e._x,e._y,e._z,t)}static Dot(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w}}F._ZeroReadOnly=F.Zero(),Object.defineProperties(F.prototype,{dimension:{value:[4]},rank:{value:1}});class L{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,s=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=O(this._x);return e=397*e^O(this._y),e=397*e^O(this._z),e=397*e^O(this._w),e}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return L.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=T){return e&&A(this._x,e._x,t)&&A(this._y,e._y,t)&&A(this._z,e._z,t)&&A(this._w,e._w,t)}clone(){return new L(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._isDirty=!0,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new L(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,s){return this._x+=e,this._y+=t,this._z+=i,this._w+=s,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,s){return this.subtractFromFloatsToRef(e,t,i,s,new L)}subtractFromFloatsToRef(e,t,i,s,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._w=this._w-s,r._isDirty=!0,r}subtract(e){return new L(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new L(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){const t=new L(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,s=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,n=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,s,r,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,s){return this._x*=e,this._y*=t,this._z*=i,this._w*=s,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new L)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,s){return this._x===e&&this._y===t&&this._z===i&&this._w===s}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new L(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return 0==e||1==e||this.scaleInPlace(1/e),this}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new L(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=w.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,i=this._x,s=this._y,r=this._w,n=s*t-i*r,o=.4999999;if(n<-o)e._y=2*Math.atan2(s,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>o)e._y=2*Math.atan2(s,r),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const o=r*r,a=t*t,l=i*i,h=s*s;e._z=Math.atan2(2*(i*s+t*r),-a-l+h+o),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*i+s*r),a-l-h+o),e._isDirty=!0}return e}toRotationMatrix(e){return B.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return L.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}static FromRotationMatrix(e){const t=new L;return L.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[1],a=i[5],l=i[9],h=i[2],c=i[6],u=i[10],d=s+a+u;let p;return d>0?(p=.5/Math.sqrt(d+1),t._w=.25/p,t._x=(c-l)*p,t._y=(n-h)*p,t._z=(o-r)*p,t._isDirty=!0):s>a&&s>u?(p=2*Math.sqrt(1+s-a-u),t._w=(c-l)/p,t._x=.25*p,t._y=(r+o)/p,t._z=(n+h)/p,t._isDirty=!0):a>u?(p=2*Math.sqrt(1+a-s-u),t._w=(n-h)/p,t._x=(r+o)/p,t._y=.25*p,t._z=(l+c)/p,t._isDirty=!0):(p=2*Math.sqrt(1+u-s-a),t._w=(o-r)/p,t._x=(n+h)/p,t._y=(l+c)/p,t._z=.25*p,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){const s=L.Dot(e,t);return 1-s*s<=i}static SmoothToRef(e,t,i,s,r){let n=0===s?1:i/s;return n=P(n,0,1),L.SlerpToRef(e,t,n,r),r}static Zero(){return new L(0,0,0,0)}static Inverse(e){return new L(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new L(0,0,0,1)}static IsIdentity(e){return e&&0===e._x&&0===e._y&&0===e._z&&1===e._w}static RotationAxis(e,t){return L.RotationAxisToRef(e,t,new L)}static RotationAxisToRef(e,t,i){const s=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*s,i._y=e._y*s,i._z=e._z*s,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new L(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,s,r){return r.copyFromFloats(e,t,i,s),r}static FromEulerAngles(e,t,i){const s=new L;return L.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerAnglesToRef(e,t,i,s){return L.RotationYawPitchRollToRef(t,e,i,s),s}static FromEulerVector(e){const t=new L;return L.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return L.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,s=T){const r=w.Dot(e,t)+1;return rMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(w.CrossToRef(e,t,U.Vector3[0]),i.set(U.Vector3[0].x,U.Vector3[0].y,U.Vector3[0].z,r)),i.normalize()}static RotationYawPitchRoll(e,t,i){const s=new L;return L.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){const r=.5*i,n=.5*t,o=.5*e,a=Math.sin(r),l=Math.cos(r),h=Math.sin(n),c=Math.cos(n),u=Math.sin(o),d=Math.cos(o);return s._x=d*h*l+u*c*a,s._y=u*c*l-d*h*a,s._z=d*c*a-u*h*l,s._w=d*c*l+u*h*a,s._isDirty=!0,s}static RotationAlphaBetaGamma(e,t,i){const s=new L;return L.RotationAlphaBetaGammaToRef(e,t,i,s),s}static RotationAlphaBetaGammaToRef(e,t,i,s){const r=.5*(i+e),n=.5*(i-e),o=.5*t;return s._x=Math.cos(n)*Math.sin(o),s._y=Math.sin(n)*Math.sin(o),s._z=Math.sin(r)*Math.cos(o),s._w=Math.cos(r)*Math.cos(o),s._isDirty=!0,s}static RotationQuaternionFromAxis(e,t,i){const s=new L(0,0,0,0);return L.RotationQuaternionFromAxisToRef(e,t,i,s),s}static RotationQuaternionFromAxisToRef(e,t,i,s){const r=V.Matrix[0];return B.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),r),L.FromRotationMatrixToRef(r,s),s}static FromLookDirectionLH(e,t){const i=new L;return L.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){const s=V.Matrix[0];return B.LookDirectionLHToRef(e,t,s),L.FromRotationMatrixToRef(s,i),i}static FromLookDirectionRH(e,t){const i=new L;return L.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){const s=V.Matrix[0];return B.LookDirectionRHToRef(e,t,s),L.FromRotationMatrixToRef(s,i)}static Slerp(e,t,i){const s=L.Identity();return L.SlerpToRef(e,t,i,s),s}static SlerpToRef(e,t,i,s){let r,n,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,a=!1;if(o<0&&(a=!0,o=-o),o>.999999)n=1-i,r=a?-i:i;else{const e=Math.acos(o),t=1/Math.sin(e);n=Math.sin((1-i)*e)*t,r=a?-Math.sin(i*e)*t:Math.sin(i*e)*t}return s._x=n*e._x+r*t._x,s._y=n*e._y+r*t._y,s._z=n*e._z+r*t._z,s._w=n*e._w+r*t._w,s._isDirty=!0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e._x*a+i._x*l+t._x*h+s._x*c,d=e._y*a+i._y*l+t._y*h+s._y*c,p=e._z*a+i._z*l+t._z*h+s._z*c,f=e._w*a+i._w*l+t._w*h+s._w*c;return new L(u,d,p,f)}static Hermite1stDerivative(e,t,i,s,r){const n=new L;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;return n._x=6*(o-r)*e._x+(3*o-4*r+1)*t._x+6*(-o+r)*i._x+(3*o-2*r)*s._x,n._y=6*(o-r)*e._y+(3*o-4*r+1)*t._y+6*(-o+r)*i._y+(3*o-2*r)*s._y,n._z=6*(o-r)*e._z+(3*o-4*r+1)*t._z+6*(-o+r)*i._z+(3*o-2*r)*s._z,n._w=6*(o-r)*e._w+(3*o-4*r+1)*t._w+6*(-o+r)*i._w+(3*o-2*r)*s._w,n._isDirty=!0,n}static Normalize(e){const t=L.Zero();return L.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){const s=new L;return L.ClampToRef(e,t,i,s),s}static ClampToRef(e,t,i,s){return s.copyFromFloats(P(e.x,t.x,i.x),P(e.y,t.y,i.y),P(e.z,t.z,i.z),P(e.w,t.w,i.w))}static Random(e=0,t=1){return new L(R(e,t),R(e,t),R(e,t),R(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(R(e,t),R(e,t),R(e,t),R(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(L.DistanceSquared(e,t))}static DistanceSquared(e,t){const i=e.x-t.x,s=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return i*i+s*s+r*r+n*n}static Center(e,t){return L.CenterToRef(e,t,L.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}Object.defineProperties(L.prototype,{dimension:{value:[4]},rank:{value:1}});class B{static get Use64Bits(){return C.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=B._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,s=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&s}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,C.MatrixTrackPrecisionChange&&C.MatrixTrackedMatrices.push(this),this._m=new C.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]||0!==this._m[1]||0!==this._m[2]||0!==this._m[3]||0!==this._m[4]||0!==this._m[6]||0!==this._m[7]||0!==this._m[8]||0!==this._m[9]||0!==this._m[10]||0!==this._m[11]||0!==this._m[12]||0!==this._m[13]||0!==this._m[14]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;const e=this._m,t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],o=e[5],a=e[6],l=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],f=e[13],_=e[14],m=e[15],g=u*m-_*d,v=c*m-f*d,x=c*_-f*u,T=h*m-p*d,S=h*_-u*p,E=h*f-p*c;return t*+(o*g-a*v+l*x)+i*-(n*g-a*T+l*S)+s*+(n*v-o*T+l*E)+r*-(n*x-o*S+a*E)}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}\n${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}\n${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}\n${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const i=this._m;for(let s=0;s<16;s++)e[t+s]=i[s];return this}asArray(){return this._m}fromArray(e,t=0){return B.FromArrayToRef(e,t,this)}copyFromFloats(...e){return B.FromArrayToRef(e,0,this)}set(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){const t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return B.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){const t=new B;return this.addToRef(e,t),t}addToRef(e,t){const i=this._m,s=t._m,r=e.m;for(let e=0;e<16;e++)s[e]=i[e]+r[e];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}addInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]-s[e];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]-=i[e];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new B)}subtractFromFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let e=0;e<16;e++)s[e]=i[e]-r[e];return t.markAsUpdated(),t}invertToRef(e){if(!0===this._isIdentity)return B.IdentityToRef(e),e;const t=this._m,i=t[0],s=t[1],r=t[2],n=t[3],o=t[4],a=t[5],l=t[6],h=t[7],c=t[8],u=t[9],d=t[10],p=t[11],f=t[12],_=t[13],m=t[14],g=t[15],v=d*g-m*p,x=u*g-_*p,T=u*m-_*d,S=c*g-f*p,E=c*m-d*f,b=c*_-f*u,C=+(a*v-l*x+h*T),y=-(o*v-l*S+h*E),A=+(o*x-a*S+h*b),R=-(o*T-a*E+l*b),I=i*C+s*y+r*A+n*R;if(0===I)return e.copyFrom(this),e;const P=1/I,M=l*g-m*h,D=a*g-_*h,O=a*m-_*l,N=o*g-f*h,w=o*m-f*l,F=o*_-f*a,L=l*p-d*h,V=a*p-u*h,U=a*d-u*l,k=o*p-c*h,G=o*d-c*l,z=o*u-c*a,W=-(s*v-r*x+n*T),H=+(i*v-r*S+n*E),X=-(i*x-s*S+n*b),Y=+(i*T-s*E+r*b),j=+(s*M-r*D+n*O),$=-(i*M-r*N+n*w),K=+(i*D-s*N+n*F),q=-(i*O-s*w+r*F),Q=-(s*L-r*V+n*U),Z=+(i*L-r*k+n*G),J=-(i*V-s*k+n*z),ee=+(i*U-s*G+r*z);return B.FromValuesToRef(C*P,W*P,j*P,Q*P,y*P,H*P,$*P,Z*P,A*P,X*P,K*P,J*P,R*P,Y*P,q*P,ee*P,e),e}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new w(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){const e=this.m;return B.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]),this}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){const i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiply(e){const t=new B;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]*=i[e];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),i=this._m,s=t._m,r=e;for(let e=0;e<16;e++)s[e]=i[e]*r[e];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){const s=this._m,r=e.m,n=s[0],o=s[1],a=s[2],l=s[3],h=s[4],c=s[5],u=s[6],d=s[7],p=s[8],f=s[9],_=s[10],m=s[11],g=s[12],v=s[13],x=s[14],T=s[15],S=r[0],E=r[1],b=r[2],C=r[3],y=r[4],A=r[5],R=r[6],I=r[7],P=r[8],M=r[9],D=r[10],O=r[11],N=r[12],w=r[13],F=r[14],L=r[15];return t[i]=n*S+o*y+a*P+l*N,t[i+1]=n*E+o*A+a*M+l*w,t[i+2]=n*b+o*R+a*D+l*F,t[i+3]=n*C+o*I+a*O+l*L,t[i+4]=h*S+c*y+u*P+d*N,t[i+5]=h*E+c*A+u*M+d*w,t[i+6]=h*b+c*R+u*D+d*F,t[i+7]=h*C+c*I+u*O+d*L,t[i+8]=p*S+f*y+_*P+m*N,t[i+9]=p*E+f*A+_*M+m*w,t[i+10]=p*b+f*R+_*D+m*F,t[i+11]=p*C+f*I+_*O+m*L,t[i+12]=g*S+v*y+x*P+T*N,t[i+13]=g*E+v*A+x*M+T*w,t[i+14]=g*b+v*R+x*D+T*F,t[i+15]=g*C+v*I+x*O+T*L,this}divide(e){return this.divideToRef(e,new B)}divideToRef(e,t){const i=this._m,s=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=i[e]/s[e];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]/=i[e];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){const t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],i[e]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){const t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new B)}negateInPlace(){const e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=-t[e];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const i=this.m,s=t.m;return i[0]===s[0]&&i[1]===s[1]&&i[2]===s[2]&&i[3]===s[3]&&i[4]===s[4]&&i[5]===s[5]&&i[6]===s[6]&&i[7]===s[7]&&i[8]===s[8]&&i[9]===s[9]&&i[10]===s[10]&&i[11]===s[11]&&i[12]===s[12]&&i[13]===s[13]&&i[14]===s[14]&&i[15]===s[15]}equalsWithEpsilon(e,t=0){const i=this._m,s=e.m;for(let e=0;e<16;e++)if(!A(i[e],s[e],t))return!1;return!0}equalsToFloats(...e){const t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new B)}floorToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=Math.floor(t[e]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new B)}fractToRef(e){const t=this._m,i=e._m;for(let e=0;e<16;e++)i[e]=t[e]-Math.floor(t[e]);return e.markAsUpdated(),e}clone(){const e=new B;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=O(this._m[0]);for(let t=1;t<16;t++)e=397*e^O(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new L,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,s,r=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const n=this._m;if(i&&i.copyFromFloats(n[12],n[13],n[14]),(e=e||V.Vector3[0]).x=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),e.y=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),e.z=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]),s){const t=(r?s.absoluteScaling.x:s.scaling.x)<0?-1:1,i=(r?s.absoluteScaling.y:s.scaling.y)<0?-1:1,n=(r?s.absoluteScaling.z:s.scaling.z)<0?-1:1;e.x*=t,e.y*=i,e.z*=n}else this.determinant()<=0&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const i=1/e._x,s=1/e._y,r=1/e._z;B.FromValuesToRef(n[0]*i,n[1]*i,n[2]*i,0,n[4]*s,n[5]*s,n[6]*s,0,n[8]*r,n[9]*r,n[10]*r,0,0,0,0,1,V.Matrix[0]),L.FromRotationMatrixToRef(V.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new F(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){const i=4*e;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){const e=new B;return B.TransposeToRef(this,e),e}transposeToRef(e){return B.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,s,r){if(e<0||e>3)return this;const n=4*e;return this._m[n+0]=t,this._m[n+1]=i,this._m[n+2]=s,this._m[n+3]=r,this.markAsUpdated(),this}scale(e){const t=new B;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){const t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){const t=V.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const i=e._m;return B.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){const e=new B;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=V.Vector3[0];if(!this.decompose(t))return B.IdentityToRef(e),e;const i=this._m,s=1/t._x,r=1/t._y,n=1/t._z;return B.FromValuesToRef(i[0]*s,i[1]*s,i[2]*s,0,i[4]*r,i[5]*r,i[6]*r,0,i[8]*n,i[9]*n,i[10]*n,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){const i=new B;return B.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let s=0;s<16;s++)i._m[s]=e[s+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,s){for(let r=0;r<16;r++)s._m[r]=e[r+t]*i;return s.markAsUpdated(),s}static get IdentityReadOnly(){return B._IdentityReadOnly}static FromValuesToRef(e,t,i,s,r,n,o,a,l,h,c,u,d,p,f,_,m){const g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=s,g[4]=r,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=p,g[14]=f,g[15]=_,m.markAsUpdated()}static FromValues(e,t,i,s,r,n,o,a,l,h,c,u,d,p,f,_){const m=new B,g=m._m;return g[0]=e,g[1]=t,g[2]=i,g[3]=s,g[4]=r,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=p,g[14]=f,g[15]=_,m.markAsUpdated(),m}static Compose(e,t,i){const s=new B;return B.ComposeToRef(e,t,i,s),s}static ComposeToRef(e,t,i,s){const r=s._m,n=t._x,o=t._y,a=t._z,l=t._w,h=n+n,c=o+o,u=a+a,d=n*h,p=n*c,f=n*u,_=o*c,m=o*u,g=a*u,v=l*h,x=l*c,T=l*u,S=e._x,E=e._y,b=e._z;return r[0]=(1-(_+g))*S,r[1]=(p+T)*S,r[2]=(f-x)*S,r[3]=0,r[4]=(p-T)*E,r[5]=(1-(d+g))*E,r[6]=(m+v)*E,r[7]=0,r[8]=(f+x)*b,r[9]=(m-v)*b,r[10]=(1-(d+_))*b,r[11]=0,r[12]=i._x,r[13]=i._y,r[14]=i._z,r[15]=1,s.markAsUpdated(),s}static Identity(){const e=B.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return B.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){const e=B.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){const t=new B;return B.RotationXToRef(e,t),t}static Invert(e){const t=new B;return e.invertToRef(t),t}static RotationXToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return B.FromValuesToRef(1,0,0,0,0,s,i,0,0,-i,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationY(e){const t=new B;return B.RotationYToRef(e,t),t}static RotationYToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return B.FromValuesToRef(s,0,-i,0,0,1,0,0,i,0,s,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationZ(e){const t=new B;return B.RotationZToRef(e,t),t}static RotationZToRef(e,t){const i=Math.sin(e),s=Math.cos(e);return B.FromValuesToRef(s,i,0,0,-i,s,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===s&&0===i),t}static RotationAxis(e,t){const i=new B;return B.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){const s=Math.sin(-t),r=Math.cos(-t),n=1-r;e.normalize();const o=i._m;return o[0]=e._x*e._x*n+r,o[1]=e._x*e._y*n-e._z*s,o[2]=e._x*e._z*n+e._y*s,o[3]=0,o[4]=e._y*e._x*n+e._z*s,o[5]=e._y*e._y*n+r,o[6]=e._y*e._z*n-e._x*s,o[7]=0,o[8]=e._z*e._x*n-e._y*s,o[9]=e._z*e._y*n+e._x*s,o[10]=e._z*e._z*n+r,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,s=!1){const r=w.Dot(t,e),n=i._m;if(r<-1+T)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=s?1:-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=s?-1:1,n[11]=0;else{const i=w.Cross(t,e),s=1/(1+r);n[0]=i._x*i._x*s+r,n[1]=i._y*i._x*s-i._z,n[2]=i._z*i._x*s+i._y,n[3]=0,n[4]=i._x*i._y*s+i._z,n[5]=i._y*i._y*s+r,n[6]=i._z*i._y*s-i._x,n[7]=0,n[8]=i._x*i._z*s-i._y,n[9]=i._y*i._z*s+i._x,n[10]=i._z*i._z*s+r,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){const s=new B;return B.RotationYawPitchRollToRef(e,t,i,s),s}static RotationYawPitchRollToRef(e,t,i,s){return L.RotationYawPitchRollToRef(e,t,i,V.Quaternion[0]),V.Quaternion[0].toRotationMatrix(s),s}static Scaling(e,t,i){const s=new B;return B.ScalingToRef(e,t,i,s),s}static ScalingToRef(e,t,i,s){return B.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,s),s._updateIdentityStatus(1===e&&1===t&&1===i),s}static Translation(e,t,i){const s=new B;return B.TranslationToRef(e,t,i,s),s}static TranslationToRef(e,t,i,s){return B.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,s),s._updateIdentityStatus(0===e&&0===t&&0===i),s}static Lerp(e,t,i){const s=new B;return B.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){const r=s._m,n=e.m,o=t.m;for(let e=0;e<16;e++)r[e]=n[e]*(1-i)+o[e]*i;return s.markAsUpdated(),s}static DecomposeLerp(e,t,i){const s=new B;return B.DecomposeLerpToRef(e,t,i,s),s}static DecomposeLerpToRef(e,t,i,s){const r=V.Vector3[0],n=V.Quaternion[0],o=V.Vector3[1];e.decompose(r,n,o);const a=V.Vector3[2],l=V.Quaternion[1],h=V.Vector3[3];t.decompose(a,l,h);const c=V.Vector3[4];w.LerpToRef(r,a,i,c);const u=V.Quaternion[2];L.SlerpToRef(n,l,i,u);const d=V.Vector3[5];return w.LerpToRef(o,h,i,d),B.ComposeToRef(c,u,d,s),s}static LookAtLH(e,t,i){const s=new B;return B.LookAtLHToRef(e,t,i,s),s}static LookAtLHToRef(e,t,i,s){const r=V.Vector3[0],n=V.Vector3[1],o=V.Vector3[2];t.subtractToRef(e,o),o.normalize(),w.CrossToRef(i,o,r);const a=r.lengthSquared();0===a?r.x=1:r.normalizeFromLength(Math.sqrt(a)),w.CrossToRef(o,r,n),n.normalize();const l=-w.Dot(r,e),h=-w.Dot(n,e),c=-w.Dot(o,e);return B.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,l,h,c,1,s),s}static LookAtRH(e,t,i){const s=new B;return B.LookAtRHToRef(e,t,i,s),s}static LookAtRHToRef(e,t,i,s){const r=V.Vector3[0],n=V.Vector3[1],o=V.Vector3[2];e.subtractToRef(t,o),o.normalize(),w.CrossToRef(i,o,r);const a=r.lengthSquared();0===a?r.x=1:r.normalizeFromLength(Math.sqrt(a)),w.CrossToRef(o,r,n),n.normalize();const l=-w.Dot(r,e),h=-w.Dot(n,e),c=-w.Dot(o,e);return B.FromValuesToRef(r._x,n._x,o._x,0,r._y,n._y,o._y,0,r._z,n._z,o._z,0,l,h,c,1,s),s}static LookDirectionLH(e,t){const i=new B;return B.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){const s=V.Vector3[0];s.copyFrom(e),s.scaleInPlace(-1);const r=V.Vector3[1];return w.CrossToRef(t,s,r),B.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){const i=new B;return B.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){const s=V.Vector3[2];return w.CrossToRef(t,e,s),B.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,s,r){const n=new B;return B.OrthoLHToRef(e,t,i,s,n,r),n}static OrthoLHToRef(e,t,i,s,r,n){const o=2/e,a=2/t,l=2/(s-i),h=-(s+i)/(s-i);return B.FromValuesToRef(o,0,0,0,0,a,0,0,0,0,l,0,0,0,h,1,r),n&&r.multiplyToRef(k,r),r._updateIdentityStatus(1===o&&1===a&&1===l&&0===h),r}static OrthoOffCenterLH(e,t,i,s,r,n,o){const a=new B;return B.OrthoOffCenterLHToRef(e,t,i,s,r,n,a,o),a}static OrthoOffCenterLHToRef(e,t,i,s,r,n,o,a){const l=2/(t-e),h=2/(s-i),c=2/(n-r),u=-(n+r)/(n-r),d=(e+t)/(e-t),p=(s+i)/(i-s);return B.FromValuesToRef(l,0,0,0,0,h,0,0,0,0,c,0,d,p,u,1,o),a&&o.multiplyToRef(k,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,s,r,n,o,a,l,h,c){const u=-o*Math.cos(a),d=-o*Math.sin(a);return B.TranslationToRef(0,0,-l,V.Matrix[1]),B.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,V.Matrix[0]),V.Matrix[1].multiplyToRef(V.Matrix[0],V.Matrix[0]),B.TranslationToRef(0,0,l,V.Matrix[1]),V.Matrix[0].multiplyToRef(V.Matrix[1],V.Matrix[0]),B.OrthoOffCenterLHToRef(e,t,i,s,r,n,h,c),V.Matrix[0].multiplyToRef(h,h),h}static OrthoOffCenterRH(e,t,i,s,r,n,o){const a=new B;return B.OrthoOffCenterRHToRef(e,t,i,s,r,n,a,o),a}static OrthoOffCenterRHToRef(e,t,i,s,r,n,o,a){return B.OrthoOffCenterLHToRef(e,t,i,s,r,n,o,a),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,s,r,n,o,a,l,h,c){const u=o*Math.cos(a),d=o*Math.sin(a);return B.TranslationToRef(0,0,l,V.Matrix[1]),B.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,V.Matrix[0]),V.Matrix[1].multiplyToRef(V.Matrix[0],V.Matrix[0]),B.TranslationToRef(0,0,-l,V.Matrix[1]),V.Matrix[0].multiplyToRef(V.Matrix[1],V.Matrix[0]),B.OrthoOffCenterRHToRef(e,t,i,s,r,n,h,c),V.Matrix[0].multiplyToRef(h,h),h}static PerspectiveLH(e,t,i,s,r,n=0){const o=new B,a=2*i/e,l=2*i/t,h=(s+i)/(s-i),c=-2*s*i/(s-i),u=Math.tan(n);return B.FromValuesToRef(a,0,0,0,0,l,0,u,0,0,h,1,0,0,c,0,o),r&&o.multiplyToRef(k,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,s,r,n=0,o=!1){const a=new B;return B.PerspectiveFovLHToRef(e,t,i,s,a,!0,r,n,o),a}static PerspectiveFovLHToRef(e,t,i,s,r,n=!0,o,a=0,l=!1){const h=i,c=s,u=1/Math.tan(.5*e),d=n?u/t:u,p=n?u:u*t,f=l&&0===h?-1:0!==c?(c+h)/(c-h):1,_=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,m=Math.tan(a);return B.FromValuesToRef(d,0,0,0,0,p,0,m,0,0,f,1,0,0,_,0,r),o&&r.multiplyToRef(k,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,i,s,r,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return B.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,1,0,0,1,0,r),o&&r.multiplyToRef(k,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,i,s,r,n=0,o=!1){const a=new B;return B.PerspectiveFovRHToRef(e,t,i,s,a,!0,r,n,o),a}static PerspectiveFovRHToRef(e,t,i,s,r,n=!0,o,a=0,l=!1){const h=i,c=s,u=1/Math.tan(.5*e),d=n?u/t:u,p=n?u:u*t,f=l&&0===h?1:0!==c?-(c+h)/(c-h):-1,_=l&&0===h?2*c:0!==c?-2*c*h/(c-h):-2*h,m=Math.tan(a);return B.FromValuesToRef(d,0,0,0,0,p,0,m,0,0,f,-1,0,0,_,0,r),o&&r.multiplyToRef(k,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,i,s,r,n=!0,o,a=0){const l=1/Math.tan(.5*e),h=n?l/t:l,c=n?l:l*t,u=Math.tan(a);return B.FromValuesToRef(h,0,0,0,0,c,0,u,0,0,-i,-1,0,0,-1,0,r),o&&r.multiplyToRef(k,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,i,s,r,n){const o=e.width,a=e.height,l=e.x,h=e.y,c=B.FromValues(o/2,0,0,0,0,-a/2,0,0,0,0,n-r,0,l+o/2,a/2+h,r,1),u=new B;return t.multiplyToRef(i,u),u.multiplyToRef(s,u),u.multiplyToRef(c,u)}static GetAsMatrix2x2(e){const t=e.m,i=[t[0],t[1],t[4],t[5]];return C.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){const t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return C.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){const t=new B;return B.TransposeToRef(e,t),t}static TransposeToRef(e,t){const i=e.m,s=i[0],r=i[4],n=i[8],o=i[12],a=i[1],l=i[5],h=i[9],c=i[13],u=i[2],d=i[6],p=i[10],f=i[14],_=i[3],m=i[7],g=i[11],v=i[15],x=t._m;return x[0]=s,x[1]=r,x[2]=n,x[3]=o,x[4]=a,x[5]=l,x[6]=h,x[7]=c,x[8]=u,x[9]=d,x[10]=p,x[11]=f,x[12]=_,x[13]=m,x[14]=g,x[15]=v,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new B;return B.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const i=e.normal.x,s=e.normal.y,r=e.normal.z,n=-2*i,o=-2*s,a=-2*r;return B.FromValuesToRef(n*i+1,o*i,a*i,0,n*s,o*s+1,a*s,0,n*r,o*r,a*r+1,0,n*e.d,o*e.d,a*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,s){return B.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,s),s}static FromQuaternionToRef(e,t){const i=e._x*e._x,s=e._y*e._y,r=e._z*e._z,n=e._x*e._y,o=e._z*e._w,a=e._z*e._x,l=e._y*e._w,h=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(s+r),t._m[1]=2*(n+o),t._m[2]=2*(a-l),t._m[3]=0,t._m[4]=2*(n-o),t._m[5]=1-2*(r+i),t._m[6]=2*(h+c),t._m[7]=0,t._m[8]=2*(a+l),t._m[9]=2*(h-c),t._m[10]=1-2*(s+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}B._UpdateFlagSeed=0,B._IdentityReadOnly=B.Identity(),Object.defineProperties(B.prototype,{dimension:{value:[4,4]},rank:{value:2}});class V{}V.Vector3=S.BuildTuple(11,w.Zero),V.Matrix=S.BuildTuple(2,B.Identity),V.Quaternion=S.BuildTuple(3,L.Zero);class U{}U.Vector2=S.BuildTuple(3,N.Zero),U.Vector3=S.BuildTuple(13,w.Zero),U.Vector4=S.BuildTuple(3,F.Zero),U.Quaternion=S.BuildTuple(2,L.Zero),U.Matrix=S.BuildTuple(8,B.Identity),u("BABYLON.Vector2",N),u("BABYLON.Vector3",w),u("BABYLON.Vector4",F),u("BABYLON.Matrix",B);const k=B.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);class G{static Sign(e){return 0==(e=+e)||isNaN(e)?e:e>0?1:-1}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(0===e)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e*=2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=G.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=G.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=G.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return s=Math.abs(t-e)<=i?t:e+G.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=G.DeltaAngle(e,t);let r=0;return-i180&&(s-=360),e+s*P(i)}static InverseLerp(e,t,i){let s=0;return s=e!=t?P((i-e)/(t-e)):0,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n;return e*(2*o-3*n+1)+i*(-2*o+3*n)+t*(o-2*n+r)+s*(o-n)}static Hermite1stDerivative(e,t,i,s,r){const n=r*r;return 6*(n-r)*e+(3*n-4*r+1)*t+6*(-n+r)*i+(3*n-2*r)*s}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static HCF(e,t){const i=e%t;return 0===i?t:G.HCF(t,i)}}function z(e){return Math.pow(e,x)}function W(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function H(e){return Math.pow(e,v)}function X(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}G.TwoPi=2*Math.PI,G.WithinEpsilon=A,G.ToHex=D,G.Clamp=P,G.Lerp=I,G.RandomRange=R,G.NormalizeRadians=M;class Y{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return Y.FromArrayToRef(e,t,this),this}toColor4(e=1){return new j(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return.3*this.r+.59*this.g+.11*this.b}multiply(e){return new Y(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,i){return new Y(this.r*e,this.g*t,this.b*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=T){return G.WithinEpsilon(this.r,e.r,t)&&G.WithinEpsilon(this.g,e.g,t)&&G.WithinEpsilon(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new Y(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,i){return i.r=P(this.r,e,t),i.g=P(this.g,e,t),i.b=P(this.b,e,t),i}add(e){return new Y(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new Y(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,i){return new Y(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,s){return s.r=this.r-e,s.g=this.g-t,s.b=this.b-i,s}clone(){return new Y(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){const e=Math.round(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+D(e)+D(t)+D(i)}toHSV(){return this.toHSVToRef(new Y)}toHSVToRef(e){const t=this.r,i=this.g,s=this.b,r=Math.max(t,i,s),n=Math.min(t,i,s);let o=0,a=0;const l=r,h=r-n;return 0!==r&&(a=h/r),r!=n&&(r==t?(o=(i-s)/h,i=0&&n<=1?(a=r,l=o):n>=1&&n<=2?(a=o,l=r):n>=2&&n<=3?(l=r,h=o):n>=3&&n<=4?(l=o,h=r):n>=4&&n<=5?(a=o,h=r):n>=5&&n<=6&&(a=r,h=o);const c=i-r;return s.r=a+c,s.g=l+c,s.b=h+c,s}static FromHSV(e,t,i){const s=new Y(0,0,0);return Y.HSVtoRGBToRef(e,t,i,s),s}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new Y(0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16);return Y.FromInts(t,i,s)}static FromArray(e,t=0){return new Y(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new Y(e/255,t/255,i/255)}static Lerp(e,t,i){const s=new Y(0,0,0);return Y.LerpToRef(e,t,i,s),s}static LerpToRef(e,t,i,s){s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.r*a+i.r*l+t.r*h+s.r*c,d=e.g*a+i.g*l+t.g*h+s.g*c,p=e.b*a+i.b*l+t.b*h+s.b*c;return new Y(u,d,p)}static Hermite1stDerivative(e,t,i,s,r){const n=Y.Black();return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=6*(o-r)*e.r+(3*o-4*r+1)*t.r+6*(-o+r)*i.r+(3*o-2*r)*s.r,n.g=6*(o-r)*e.g+(3*o-4*r+1)*t.g+6*(-o+r)*i.g+(3*o-2*r)*s.g,n.b=6*(o-r)*e.b+(3*o-4*r+1)*t.b+6*(-o+r)*i.b+(3*o-2*r)*s.b}static Red(){return new Y(1,0,0)}static Green(){return new Y(0,1,0)}static Blue(){return new Y(0,0,1)}static Black(){return new Y(0,0,0)}static get BlackReadOnly(){return Y._BlackReadOnly}static White(){return new Y(1,1,1)}static Purple(){return new Y(.5,0,.5)}static Magenta(){return new Y(1,0,1)}static Yellow(){return new Y(1,1,0)}static Gray(){return new Y(.5,.5,.5)}static Teal(){return new Y(0,1,1)}static Random(){return new Y(Math.random(),Math.random(),Math.random())}}Y._BlackReadOnly=Y.Black(),Object.defineProperties(Y.prototype,{dimension:{value:[3]},rank:{value:1}});class j{constructor(e=0,t=0,i=0,s=1){this.r=e,this.g=t,this.b=i,this.a=s}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new j(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,s){return this.r+=e,this.g+=t,this.b+=i,this.a+=s,this}subtract(e){return new j(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,s){return new j(this.r-e,this.g-t,this.b-i,this.a-s)}subtractFromFloatsToRef(e,t,i,s,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r.a=this.a-s,r}scale(e){return new j(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,i){return i.r=P(this.r,e,t),i.g=P(this.g,e,t),i.b=P(this.b,e,t),i.a=P(this.a,e,t),i}multiply(e){return new j(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,s){return new j(this.r*e,this.g*t,this.b*i,this.a*s)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,s){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(s,this.a),this}maximizeInPlaceFromFloats(e,t,i,s){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(s,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=T){return G.WithinEpsilon(this.r,e.r,t)&&G.WithinEpsilon(this.g,e.g,t)&&G.WithinEpsilon(this.b,e.b,t)&&G.WithinEpsilon(this.a,e.a,t)}equalsToFloats(e,t,i,s){return this.r===e&&this.g===t&&this.b===i&&this.a===s}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e=397*e^255*this.a,e}clone(){return(new j).copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,s){return this.r=e,this.g=t,this.b=i,this.a=s,this}set(e,t,i,s){return this.copyFromFloats(e,t,i,s)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+D(t)+D(i)+D(s);const r=Math.round(255*this.a);return"#"+D(t)+D(i)+D(s)+D(r)}toLinearSpace(e=!1){const t=new j;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=W(this.r),e.g=W(this.g),e.b=W(this.b)):(e.r=z(this.r),e.g=z(this.g),e.b=z(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new j;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=X(this.r),e.g=X(this.g),e.b=X(this.b)):(e.r=H(this.r),e.g=H(this.g),e.b=H(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new j(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),s=parseInt(e.substring(5,7),16),r=9===e.length?parseInt(e.substring(7,9),16):255;return j.FromInts(t,i,s,r)}static Lerp(e,t,i){return j.LerpToRef(e,t,i,new j)}static LerpToRef(e,t,i,s){return s.r=e.r+(t.r-e.r)*i,s.g=e.g+(t.g-e.g)*i,s.b=e.b+(t.b-e.b)*i,s.a=e.a+(t.a-e.a)*i,s}static Hermite(e,t,i,s,r){const n=r*r,o=r*n,a=2*o-3*n+1,l=-2*o+3*n,h=o-2*n+r,c=o-n,u=e.r*a+i.r*l+t.r*h+s.r*c,d=e.g*a+i.g*l+t.g*h+s.g*c,p=e.b*a+i.b*l+t.b*h+s.b*c,f=e.a*a+i.a*l+t.a*h+s.a*c;return new j(u,d,p,f)}static Hermite1stDerivative(e,t,i,s,r){const n=new j;return this.Hermite1stDerivativeToRef(e,t,i,s,r,n),n}static Hermite1stDerivativeToRef(e,t,i,s,r,n){const o=r*r;n.r=6*(o-r)*e.r+(3*o-4*r+1)*t.r+6*(-o+r)*i.r+(3*o-2*r)*s.r,n.g=6*(o-r)*e.g+(3*o-4*r+1)*t.g+6*(-o+r)*i.g+(3*o-2*r)*s.g,n.b=6*(o-r)*e.b+(3*o-4*r+1)*t.b+6*(-o+r)*i.b+(3*o-2*r)*s.b,n.a=6*(o-r)*e.a+(3*o-4*r+1)*t.a+6*(-o+r)*i.a+(3*o-2*r)*s.a}static FromColor3(e,t=1){return new j(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new j(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,s){return new j(e/255,t/255,i/255,s/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;inew j(0,0,0,0))),u("BABYLON.Color3",Y),u("BABYLON.Color4",j);class K{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new g,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}_prepare(){}getTriggerParameter(){return this._triggerParameter}setTriggerParameter(e){this._triggerParameter=e}_evaluateConditionForCurrentFrame(){const e=this._condition;if(!e)return!0;const t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){this._evaluateConditionForCurrentFrame()&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())}execute(e){}skipToNextActiveAction(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this}then(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(e){return null}_serialize(e,t){const i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){const e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}}K._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof N?e.x+", "+e.y:e instanceof w?e.x+", "+e.y+", "+e.z:e instanceof Y?e.r+", "+e.g+", "+e.b:e instanceof j?e.r+", "+e.g+", "+e.b+", "+e.a:e,K._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),u("BABYLON.Action",K);class q{constructor(e,t,i,s,r,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=s,this.sourceEvent=r,this.additionalData=n}static CreateNew(e,t,i){const s=e.getScene();return new q(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new q(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new q(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new q(e,t.x,t.y,null,i,s)}}class Q{constructor(e){this._actionManager=e}isValid(){return!0}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(){}_serialize(e){return{type:2,children:[],name:e.name,properties:e.properties}}}class Z extends Q{static get IsEqual(){return Z._IsEqual}static get IsDifferent(){return Z._IsDifferent}static get IsGreater(){return Z._IsGreater}static get IsLesser(){return Z._IsLesser}constructor(e,t,i,s,r=Z.IsEqual){super(e),this.propertyPath=i,this.value=s,this.operator=r,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case Z.IsGreater:return this._effectiveTarget[this._property]>this.value;case Z.IsLesser:return this._effectiveTarget[this._property]e<10?"0"+e:""+e,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){const s=Array.isArray(t)?t[0]:t;if(void 0!==i&&!J._CheckLimit(s,i))return;const r=J._FormatMessage(s),n=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];n.logFunc&&n.logFunc("BJS - "+r,...o);const a=`
${r}

`;J._AddLogEntry(a),J._GenerateLimitMessage(s,e)}static get LogCache(){return J._LogCache}static ClearLogCache(){J._LogCache="",J._LogLimitOutputs={},J.errorsCount=0}static set LogLevels(e){J.Log=J._LogDisabled,J.Warn=J._LogDisabled,J.Error=J._LogDisabled,[J.MessageLogLevel,J.WarningLogLevel,J.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];J[e.name]=J._LogEnabled.bind(J,t)}}))}}J.NoneLogLevel=0,J.MessageLogLevel=1,J.WarningLogLevel=2,J.ErrorLogLevel=4,J.AllLogLevel=7,J.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",J._LogCache="",J._LogLimitOutputs={},J._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],J.errorsCount=0,J.Log=J._LogEnabled.bind(J,J.MessageLogLevel),J.Warn=J._LogEnabled.bind(J,J.WarningLogLevel),J.Error=J._LogEnabled.bind(J,J.ErrorLogLevel);class ee extends K{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class te extends K{constructor(e,t,i,s){super(e,s),this._target=t,this._parent=i}_prepare(){}execute(){if(this._target.parent===this._parent)return;const e=this._parent.getWorldMatrix().clone();e.invert(),this._target.position=w.TransformCoordinates(this._target.position,e),this._target.parent=this._parent}serialize(e){return super._serialize({name:"SetParentAction",properties:[K._GetTargetProperty(this._target),K._GetTargetProperty(this._parent)]},e)}}u("BABYLON.SetParentAction",te),u("BABYLON.ExecuteCodeAction",class extends K{constructor(e,t,i){super(e,i),this.func=t}execute(e){this.func(e)}}),u("BABYLON.DoNothingAction",ee),u("BABYLON.StopAnimationAction",class extends K{constructor(e,t,i){super(e,i),this._target=t}_prepare(){}execute(){this._actionManager.getScene().stopAnimation(this._target)}serialize(e){return super._serialize({name:"StopAnimationAction",properties:[K._GetTargetProperty(this._target)]},e)}}),u("BABYLON.PlayAnimationAction",class extends K{constructor(e,t,i,s,r,n){super(e,n),this.from=i,this.to=s,this.loop=r,this._target=t}_prepare(){}execute(){this._actionManager.getScene().beginAnimation(this._target,this.from,this.to,this.loop)}serialize(e){return super._serialize({name:"PlayAnimationAction",properties:[K._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:K._SerializeValueAsString(this.loop)||!1}]},e)}}),u("BABYLON.IncrementValueAction",class extends K{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&J.Warn("Warning: IncrementValueAction can only be used with number values")}execute(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"IncrementValueAction",properties:[K._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:K._SerializeValueAsString(this.value)}]},e)}}),u("BABYLON.SetValueAction",class extends K{constructor(e,t,i,s,r){super(e,r),this.propertyPath=i,this.value=s,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"SetValueAction",properties:[K._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:K._SerializeValueAsString(this.value)}]},e)}}),u("BABYLON.SetStateAction",class extends K{constructor(e,t,i,s){super(e,s),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[K._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}),u("BABYLON.SetParentAction",te),u("BABYLON.SwitchBooleanAction",class extends K{constructor(e,t,i,s){super(e,s),this.propertyPath=i,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]}serialize(e){return super._serialize({name:"SwitchBooleanAction",properties:[K._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}),u("BABYLON.CombineAction",class extends K{constructor(e,t,i,s=!0){super(e,i),this.children=t,this.enableChildrenConditions=s}_prepare(){for(let e=0;ee?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?{...e}:null:e.clone(t):null;class se{static DeepCopy(e,t,i,s,r=!1){const n=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const o of n){if("_"===o[0]&&(!s||-1===s.indexOf(o)))continue;if(o.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(o))continue;const n=e[o],a=typeof n;if("function"!==a)try{if("object"===a)if(n instanceof Uint8Array)t[o]=Uint8Array.from(n);else if(n instanceof Array){if(t[o]=[],n.length>0)if("object"==typeof n[0])for(let e=0;e-1&&this._scene.actionManagers.splice(e,1);const t=this._scene.meshes.filter((e=>e.actionManager===this));for(const e of t)e.actionManager=null}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=re.OnPickTrigger&&t.trigger<=re.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=re.OnPickTrigger&&t.trigger<=re.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===re.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(J.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,re.Triggers[e.trigger]?re.Triggers[e.trigger]++:re.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){const t=this.actions.indexOf(e);return-1!==t&&(this.actions.splice(t,1),re.Triggers[e.trigger]-=1,0===re.Triggers[e.trigger]&&delete re.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i{if(null===s){const e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}const r=s.split("."),n=t.split(",");for(let e=0;e{if(e.detached)return;const h=[];let c=null,u=null;const p=e.combine&&e.combine.length>0;if(2===e.type?h.push(s):h.push(t),p){const t=[];for(let i=0;i{const i=d("BABYLON."+e);return i&&new i(...t)})(e.name,h);if(f instanceof Q&&null!==o){const e=new ee(t,o);a?a.then(e):s.registerAction(e),a=e}null===l?f instanceof Q?(o=f,f=a):(o=null,a?a.then(f):s.registerAction(f)):l.push(f);for(let i=0;i0){const e=r.properties[0].value,t=null===r.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),s={trigger:re[r.name],parameter:t}}else s=re[r.name];for(let e=0;e=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o}Object.create,Object.create;const le={},he={};function ce(e){const t=e.getClassName();if(le[t])return le[t];le[t]={};const i=le[t];let s=e,r=t;for(;r;){const e=he[r];for(const t in e)i[t]=e[t];let t,n=!1;do{if(t=Object.getPrototypeOf(s),!t.getClassName){n=!0;break}if(t.getClassName()!==r)break;s=t}while(t);if(n)break;r=t.getClassName(),s=t}return i}function ue(e,t){return(i,s)=>{const r=function(e){const t=e.getClassName();return he[t]||(he[t]={}),he[t]}(i);r[s]||(r[s]={type:e,sourceName:t})}}function de(e,t=null){return function(e,t=null){return(i,s)=>{const r=t||"_"+s;Object.defineProperty(i,s,{get:function(){return this[r]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[r]!==t&&(this[r]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function pe(e){return ue(0,e)}function fe(e){return ue(1,e)}function _e(e){return ue(2,e)}function me(e){return ue(3,e)}function ge(e){return ue(4,e)}function ve(e){return ue(5,e)}function xe(e){return ue(6,e)}function Te(e){return ue(8,e)}function Se(e){return ue(9,e)}function Ee(e){return ue(12,e)}function be(e,t,i,s){const r=i.value;i.value=(...i)=>{let n=r;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];n=s?(...t)=>s(...t)?e(...t):r(...t):e}return e[t]=n,n(...i)}}be.filter=function(e){return(t,i,s)=>be(t,i,s,e)};const Ce={};function ye(e,t=!1){if(!t||!Ce[e])return Ce[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}class Ae{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),Ae._HandleParenthesisContent(e,t)))):Ae._HandleParenthesisContent(e,t))||"false"!==e&&Ae.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const s=e.split("||");for(const e in s)if(Object.prototype.hasOwnProperty.call(s,e)){let r=Ae._SimplifyNegation(s[e].trim());const n=r.split("&&");if(n.length>1)for(let e=0;e(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}class Re{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>Re.HasTags(e),e.addTags=t=>Re.AddTagsTo(e,t),e.removeTags=t=>Re.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>Re.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;const t=e._tags;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const t=[];for(const i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}return e._tags}static AddTagsTo(e,t){t&&"string"==typeof t&&t.split(" ").forEach((function(t){Re._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(Re.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!Re.HasTags(e))return;const i=t.split(" ");for(const t in i)Re._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?Re.HasTags(e):Ae.Eval(t,(t=>Re.HasTags(e)&&e._tags[t])))}}const Ie=function(e,t,i,s={}){const r=e();Re&&Re.HasTags(t)&&Re.AddTagsTo(r,Re.GetTags(t,!0));const n=ce(r),o={};for(const e in n){const a=n[e],l=t[e],h=a.type;if(null!=l&&("uniqueId"!==e||Pe.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:r[e]=l;break;case 1:s.cloneTexturesOnlyOnce&&o[l.uniqueId]?r[e]=o[l.uniqueId]:(r[e]=i||l.isRenderTarget?l:l.clone(),o[l.uniqueId]=r[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:r[e]=i?l:l.clone()}}return r};class Pe{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw ye("ImageProcessingConfiguration")},Pe._FresnelParametersParser=e=>{throw ye("FresnelParameters")},Pe._ColorCurvesParser=e=>{throw ye("ColorCurves")},Pe._TextureParser=(e,t,i)=>{throw ye("Texture")};class Me{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new g,this._onClonedObservable=new g}}class De{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,s){const r=this._NodeConstructors[e];return r?r(t,i,s):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;const t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){const t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){-1===this._nodeDataStorage._sceneRootNodesIndex&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(-1!==this._nodeDataStorage._sceneRootNodesIndex){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null,i=!0){this._isDirty=!1,this._nodeDataStorage=new Me,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new g,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=B.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new g,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||y.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),i&&this._addToSceneRootNodes()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return-1!==this._behaviors.indexOf(e)||(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce((()=>{e.attach(this)})):e.attach(this),this._behaviors.push(e)),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),this}get behaviors(){return this._behaviors}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={}}updateCache(e){!e&&this.isSynchronized()||this._updateCache()}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return!this._parentNode||!this._parentNode._isDirty&&this._parentUpdateId===this._parentNode._childUpdateId&&this._parentNode.isSynchronized()}isSynchronized(){return!(this._parentNode&&!this.isSynchronizedWithParent())&&this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return!1===e?this._nodeDataStorage._isEnabled:!!this._nodeDataStorage._isEnabled&&this._nodeDataStorage._isParentEnabled}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),this._children&&this._children.forEach((e=>{e._syncParentEnabledState()}))}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return!!this.parent&&(this.parent===e||this.parent.isDescendantOf(e))}_getDescendants(e,t=!1,i){if(this._children)for(let s=0;s(!t||t(e))&&void 0!==e.cullingStrategy)),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)}getAnimationByName(e){for(let t=0;tnew De(e,this.getScene())),this);if(t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i{throw ye("AnimationRange")},De._NodeConstructors={},ae([pe()],De.prototype,"name",void 0),ae([pe()],De.prototype,"id",void 0),ae([pe()],De.prototype,"uniqueId",void 0),ae([pe()],De.prototype,"state",void 0),ae([pe()],De.prototype,"metadata",void 0);class Oe{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=0|this.width;return e=397*e^this.height,e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new Oe(this.width*e,this.height*t)}clone(){return new Oe(this.width,this.height)}equals(e){return!!e&&this.width===e.width&&this.height===e.height}get surface(){return this.width*this.height}static Zero(){return new Oe(0,0)}add(e){return new Oe(this.width+e.width,this.height+e.height)}subtract(e){return new Oe(this.width-e.width,this.height-e.height)}scale(e){return new Oe(this.width*e,this.height*e)}static Lerp(e,t,i){const s=e.width+(t.width-e.width)*i,r=e.height+(t.height-e.height)*i;return new Oe(s,r)}}class Ne{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(Ne.CustomRequestHeaders).length>0||Ne.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in Ne.CustomRequestHeaders){const t=Ne.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return Ne.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){Ne.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const e of Ne.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}t=(t=t.replace("file:http:","http:")).replace("file:https:","https:"),this._requestURL=t,this._xhr.open(e,t,!0)}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}Ne.CustomRequestHeaders={},Ne.CustomRequestModifiers=new Array,Ne.SkipRequestModificationForBabylonCDN=!0;const we=Object.freeze(new L(0,0,0,0)),Fe=Object.freeze(w.Zero()),Le=Object.freeze(N.Zero()),Be=Object.freeze(Oe.Zero()),Ve=Object.freeze(Y.Black()),Ue=Object.freeze(new j(0,0,0,0)),ke={key:0,repeatCount:0,loopMode:2};class Ge{static _PrepareAnimation(e,t,i,s,r,n,o,a){let l;if(!isNaN(parseFloat(r))&&isFinite(r)?l=Ge.ANIMATIONTYPE_FLOAT:r instanceof L?l=Ge.ANIMATIONTYPE_QUATERNION:r instanceof w?l=Ge.ANIMATIONTYPE_VECTOR3:r instanceof N?l=Ge.ANIMATIONTYPE_VECTOR2:r instanceof Y?l=Ge.ANIMATIONTYPE_COLOR3:r instanceof j?l=Ge.ANIMATIONTYPE_COLOR4:r instanceof Oe&&(l=Ge.ANIMATIONTYPE_SIZE),null==l)return null;const h=new Ge(e,t,i,l,o),c=[{frame:0,value:r},{frame:s,value:n}];return h.setKeys(c),void 0!==a&&h.setEasingFunction(a),h}static CreateAnimation(e,t,i,s){const r=new Ge(e+"Animation",e,i,t,Ge.ANIMATIONLOOPMODE_CONSTANT);return r.setEasingFunction(s),r}static CreateAndStartAnimation(e,t,i,s,r,n,o,a,l,h,c){const u=Ge._PrepareAnimation(e,i,s,r,n,o,a,l);return u?(t.getScene&&(c=t.getScene()),c?c.beginDirectAnimation(t,[u],0,r,1===u.loopMode,1,h):null):null}static CreateAndStartHierarchyAnimation(e,t,i,s,r,n,o,a,l,h,c){const u=Ge._PrepareAnimation(e,s,r,n,o,a,l,h);return u?t.getScene().beginDirectHierarchyAnimation(t,i,[u],0,n,1===u.loopMode,1,c):null}static CreateMergeAndStartAnimation(e,t,i,s,r,n,o,a,l,h){const c=Ge._PrepareAnimation(e,i,s,r,n,o,a,l);return c?(t.animations.push(c),t.getScene().beginAnimation(t,0,r,1===c.loopMode,1,h)):null}static MakeAnimationAdditive(e,t,i,s=!1,r){let n;n="object"==typeof t?t:{referenceFrame:t??0,range:i,cloneOriginalAnimation:s,clonedAnimationName:r};let o=e;if(n.cloneOriginalAnimation&&(o=e.clone(),o.name=n.clonedAnimationName||o.name),!o._keys.length)return o;const a=n.referenceFrame&&n.referenceFrame>=0?n.referenceFrame:0;let l=0;const h=o._keys[0];let c=o._keys.length-1;const u=o._keys[c],d={referenceValue:h.value,referencePosition:U.Vector3[0],referenceQuaternion:U.Quaternion[0],referenceScaling:U.Vector3[1],keyPosition:U.Vector3[2],keyQuaternion:U.Quaternion[1],keyScaling:U.Vector3[3]};let p=h.frame,f=u.frame;if(n.range){const e=o.getRange(n.range);e&&(p=e.from,f=e.to)}else p=n.fromFrame??p,f=n.toFrame??f;if(p!==h.frame&&(l=o.createKeyForFrame(p)),f!==u.frame&&(c=o.createKeyForFrame(f)),1===o._keys.length){const e=o._getKeyValue(o._keys[0]);d.referenceValue=e.clone?e.clone():e}else if(a<=h.frame){const e=o._getKeyValue(h.value);d.referenceValue=e.clone?e.clone():e}else if(a>=u.frame){const e=o._getKeyValue(u.value);d.referenceValue=e.clone?e.clone():e}else{ke.key=0;const e=o._interpolate(a,ke);d.referenceValue=e.clone?e.clone():e}o.dataType===Ge.ANIMATIONTYPE_QUATERNION?d.referenceValue.normalize().conjugateInPlace():o.dataType===Ge.ANIMATIONTYPE_MATRIX&&(d.referenceValue.decompose(d.referenceScaling,d.referenceQuaternion,d.referencePosition),d.referenceQuaternion.normalize().conjugateInPlace());let _=Number.MAX_VALUE;const m=n.clipKeys?[]:null;for(let e=l;e<=c;e++){let t=o._keys[e];if((m||n.cloneOriginalAnimation)&&(t={frame:t.frame,value:t.value.clone?t.value.clone():t.value,inTangent:t.inTangent,outTangent:t.outTangent,interpolation:t.interpolation,lockedTangent:t.lockedTangent},m&&(_===Number.MAX_VALUE&&(_=t.frame),t.frame-=_,m.push(t))),!e||o.dataType===Ge.ANIMATIONTYPE_FLOAT||t.value!==h.value)switch(o.dataType){case Ge.ANIMATIONTYPE_MATRIX:t.value.decompose(d.keyScaling,d.keyQuaternion,d.keyPosition),d.keyPosition.subtractInPlace(d.referencePosition),d.keyScaling.divideInPlace(d.referenceScaling),d.referenceQuaternion.multiplyToRef(d.keyQuaternion,d.keyQuaternion),B.ComposeToRef(d.keyScaling,d.keyQuaternion,d.keyPosition,t.value);break;case Ge.ANIMATIONTYPE_QUATERNION:d.referenceValue.multiplyToRef(t.value,t.value);break;case Ge.ANIMATIONTYPE_VECTOR2:case Ge.ANIMATIONTYPE_VECTOR3:case Ge.ANIMATIONTYPE_COLOR3:case Ge.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(d.referenceValue,t.value);break;case Ge.ANIMATIONTYPE_SIZE:t.value.width-=d.referenceValue.width,t.value.height-=d.referenceValue.height;break;default:t.value-=d.referenceValue}}return m&&o.setKeys(m,!0),o}static TransitionTo(e,t,i,s,r,n,o,a=null){if(o<=0)return i[e]=t,a&&a(),null;const l=r*(o/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);const h=s.beginAnimation(i,0,l,!1);return h.onAnimationEnd=a,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,s,r,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=s,this.loopMode=r,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=s,this.loopMode=void 0===r?Ge.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=Ge._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort(((e,t)=>e.frame-t.frame))}removeEvents(e){for(let t=0;t=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const s=this._keys,r=s.length;let n=t.key;for(;n>=0&&e=s[n+1].frame;)++n;if(t.key=n,n<0)return i?void 0:this._getKeyValue(s[0].value);if(n+1>r-1)return i?void 0:this._getKeyValue(s[r-1].value);const o=s[n],a=s[n+1];if(i&&(e===o.frame||e===a.frame))return;const l=this._getKeyValue(o.value),h=this._getKeyValue(a.value);if(o.interpolation===ne.STEP)return a.frame>e?l:h;const c=void 0!==o.outTangent&&void 0!==a.inTangent,u=a.frame-o.frame;let d=(e-o.frame)/u;const p=o.easingFunction||this.getEasingFunction();switch(null!==p&&(d=p.ease(d)),this.dataType){case Ge.ANIMATIONTYPE_FLOAT:{const e=c?this.floatInterpolateFunctionWithTangents(l,o.outTangent*u,h,a.inTangent*u,d):this.floatInterpolateFunction(l,h,d);switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return e;case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+e}break}case Ge.ANIMATIONTYPE_QUATERNION:{const e=c?this.quaternionInterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.quaternionInterpolateFunction(l,h,d);switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return e;case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||we).scale(t.repeatCount))}return e}case Ge.ANIMATIONTYPE_VECTOR3:{const e=c?this.vector3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.vector3InterpolateFunction(l,h,d);switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return e;case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Fe).scale(t.repeatCount))}break}case Ge.ANIMATIONTYPE_VECTOR2:{const e=c?this.vector2InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.vector2InterpolateFunction(l,h,d);switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return e;case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Le).scale(t.repeatCount))}break}case Ge.ANIMATIONTYPE_SIZE:switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,h,d);case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(l,h,d).add((t.offsetValue||Be).scale(t.repeatCount))}break;case Ge.ANIMATIONTYPE_COLOR3:{const e=c?this.color3InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.color3InterpolateFunction(l,h,d);switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return e;case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Ve).scale(t.repeatCount))}break}case Ge.ANIMATIONTYPE_COLOR4:{const e=c?this.color4InterpolateFunctionWithTangents(l,o.outTangent.scale(u),h,a.inTangent.scale(u),d):this.color4InterpolateFunction(l,h,d);switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return e;case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Ue).scale(t.repeatCount))}break}case Ge.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case Ge.ANIMATIONLOOPMODE_CYCLE:case Ge.ANIMATIONLOOPMODE_CONSTANT:case Ge.ANIMATIONLOOPMODE_YOYO:return Ge.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,h,d,t.workValue):l;case Ge.ANIMATIONLOOPMODE_RELATIVE:case Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return l}}return 0}matrixInterpolateFunction(e,t,i,s){return Ge.AllowMatrixDecomposeForInterpolation?s?(B.DecomposeLerpToRef(e,t,i,s),s):B.DecomposeLerp(e,t,i):s?(B.LerpToRef(e,t,i,s),s):B.Lerp(e,t,i)}clone(){const e=new Ge(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(const t in this._ranges){const i=this._ranges[t];i&&(e._ranges[t]=i.clone())}}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){ke.key=0;const t=this._interpolate(e,ke,!0);if(!t)return this._keys[ke.key].frame===e?ke.key:ke.key+1;const i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(ke.key+1,0,i),ke.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let s=0;s=2&&(o=t.values[1]),t.values.length>=3&&(a=t.values[2]),t.values.length>=4&&(l=t.values[3]);break;case Ge.ANIMATIONTYPE_QUATERNION:if(r=L.FromArray(t.values),t.values.length>=8){const e=L.FromArray(t.values.slice(4,8));e.equals(L.Zero())||(o=e)}if(t.values.length>=12){const e=L.FromArray(t.values.slice(8,12));e.equals(L.Zero())||(a=e)}t.values.length>=13&&(l=t.values[12]);break;case Ge.ANIMATIONTYPE_MATRIX:r=B.FromArray(t.values),t.values.length>=17&&(l=t.values[16]);break;case Ge.ANIMATIONTYPE_COLOR3:r=Y.FromArray(t.values),t.values[3]&&(o=Y.FromArray(t.values[3])),t.values[4]&&(a=Y.FromArray(t.values[4])),t.values[5]&&(l=t.values[5]);break;case Ge.ANIMATIONTYPE_COLOR4:r=j.FromArray(t.values),t.values[4]&&(o=j.FromArray(t.values[4])),t.values[5]&&(a=j.FromArray(t.values[5])),t.values[6]&&(l=j.FromArray(t.values[6]));break;case Ge.ANIMATIONTYPE_VECTOR3:default:r=w.FromArray(t.values),t.values[3]&&(o=w.FromArray(t.values[3])),t.values[4]&&(a=w.FromArray(t.values[4])),t.values[5]&&(l=t.values[5])}const h={};h.frame=t.frame,h.value=r,null!=o&&(h.inTangent=o),null!=a&&(h.outTangent=a),null!=l&&(h.interpolation=l),s.push(h)}if(t.setKeys(s),e.ranges)for(n=0;n{const r=new Ne;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){let t=JSON.parse(r.responseText);if(t.animations&&(t=t.animations),t.length){const e=[];for(const i of t)e.push(this.Parse(i));i(e)}else{const s=this.Parse(t);e&&(s.name=e),i(s)}}else s("Unable to load the animation")})),r.open("GET",t),r.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const s=new Ne;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){const i=JSON.parse(JSON.parse(s.responseText).jsonPayload);if(i.animations){const s=JSON.parse(i.animations),r=[];for(const t of s.animations){const i=this.Parse(t);i.snippetId=e,r.push(i)}t(r)}else{const s=JSON.parse(i.animation),r=this.Parse(s);r.snippetId=e,t(r)}}else i("Unable to load the snippet "+e)})),s.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),s.send()}))}}Ge._UniqueIdGenerator=0,Ge.AllowMatricesInterpolation=!1,Ge.AllowMatrixDecomposeForInterpolation=!0,Ge.SnippetUrl="https://snippet.babylonjs.com",Ge.ANIMATIONTYPE_FLOAT=0,Ge.ANIMATIONTYPE_VECTOR3=1,Ge.ANIMATIONTYPE_QUATERNION=2,Ge.ANIMATIONTYPE_MATRIX=3,Ge.ANIMATIONTYPE_COLOR3=4,Ge.ANIMATIONTYPE_COLOR4=7,Ge.ANIMATIONTYPE_VECTOR2=5,Ge.ANIMATIONTYPE_SIZE=6,Ge.ANIMATIONLOOPMODE_RELATIVE=0,Ge.ANIMATIONLOOPMODE_CYCLE=1,Ge.ANIMATIONLOOPMODE_CONSTANT=2,Ge.ANIMATIONLOOPMODE_YOYO=4,Ge.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,Ge.CreateFromSnippetAsync=Ge.ParseFromSnippetAsync,u("BABYLON.Animation",Ge),De._AnimationRangeFactory=(e,t,i)=>new oe(e,t,i),u("BABYLON.InterpolateValueAction",class extends K{constructor(e,t,i,s,r=1e3,n,o,a){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new g,this.propertyPath=i,this.value=s,this.duration=r,this.stopOtherAnimations=o,this.onInterpolationDone=a,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){const e=this._actionManager.getScene(),t=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];let i;if("number"==typeof this.value)i=Ge.ANIMATIONTYPE_FLOAT;else if(this.value instanceof Y)i=Ge.ANIMATIONTYPE_COLOR3;else if(this.value instanceof w)i=Ge.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof B)i=Ge.ANIMATIONTYPE_MATRIX;else{if(!(this.value instanceof L))return void J.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");i=Ge.ANIMATIONTYPE_QUATERNION}const s=new Ge("InterpolateValueAction",this._property,1e3/this.duration*100,i,Ge.ANIMATIONLOOPMODE_CONSTANT);s.setKeys(t),this.stopOtherAnimations&&e.stopAnimation(this._effectiveTarget),e.beginDirectAnimation(this._effectiveTarget,[s],0,100,!1,1,(()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()}))}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[K._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:K._SerializeValueAsString(this.value)},{name:"duration",value:K._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:K._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}});class ze{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,i,s){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._yoyoDirection=1,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=s,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===Ge.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=B.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,0!==this._minFrame){const e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(const t of this._target)this._preparePath(t,e),this._getOriginalValues(e),e++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const r=t.getEvents();r&&r.length>0&&r.forEach((e=>{this._events.push(e._clone())})),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){const i=this._animation.targetPropertyPath;if(i.length>1){let s=e;for(let e=0;e-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray)for(let i=0;ii[i.length-1].frame&&(e=i[i.length-1].frame);const s=this._events;if(s.length)for(let t=0;tthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const h=i-t;let c,u=e*(o.framePerSecond*r)/1e3+this._absoluteFrameOffset,d=0,p=!1;const f=s&&this._animationState.loopMode===Ge.ANIMATIONLOOPMODE_YOYO;if(f){const e=(u-t)/h,i=Math.sin(e*Math.PI);u=Math.abs(i)*h+t;const s=i>=0?1:-1;this._yoyoDirection!==s&&(p=!0),this._yoyoDirection=s}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=u,!s&&i>=t&&(u>=h&&r>0||u<=0&&r<0))l=!1,d=o._getKeyValue(this._maxValue);else if(!s&&t>=i&&(u<=h&&r<0||u>=0&&r>0))l=!1,d=o._getKeyValue(this._minValue);else if(this._animationState.loopMode!==Ge.ANIMATIONLOOPMODE_CYCLE){const e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=Ge.ANIMATIONLOOPMODE_CYCLE;const s=o._interpolate(t,this._animationState),r=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case Ge.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=r-s;break;case Ge.ANIMATIONTYPE_QUATERNION:case Ge.ANIMATIONTYPE_VECTOR3:case Ge.ANIMATIONTYPE_VECTOR2:case Ge.ANIMATIONTYPE_SIZE:case Ge.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=r.subtract(s)}this._highLimitsCache[e]=r}d=this._highLimitsCache[e],c=this._offsetsCache[e]}if(void 0===c)switch(o.dataType){case Ge.ANIMATIONTYPE_FLOAT:c=0;break;case Ge.ANIMATIONTYPE_QUATERNION:c=we;break;case Ge.ANIMATIONTYPE_VECTOR3:c=Fe;break;case Ge.ANIMATIONTYPE_VECTOR2:c=Le;break;case Ge.ANIMATIONTYPE_SIZE:c=Be;break;case Ge.ANIMATIONTYPE_COLOR3:c=Ve;break;case Ge.ANIMATIONTYPE_COLOR4:c=Ue}let _;if(this._host&&this._host.syncRoot){const e=this._host.syncRoot;_=t+h*((e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame))}else _=u>0&&t>i||u<0&&t0&&this.currentFrame>_||r<0&&this.currentFrame<_)||f&&p){this._onLoop();for(let e=0;e0?0:o.getKeys().length-1}this._currentFrame=_,this._animationState.repeatCount=0===h?0:u/h|0,this._animationState.highLimitValue=d,this._animationState.offsetValue=c;const g=o._interpolate(_,this._animationState);if(this.setValue(g,n),m.length)for(let e=0;e=0&&_>=m[e].frame&&m[e].frame>=t||h<0&&_<=m[e].frame&&m[e].frame<=t){const t=m[e];t.isDone||(t.onlyOnce&&(m.splice(e,1),e--),t.isDone=!0,t.action(_))}return l||(this._stopped=!0),l}}function We(){return"undefined"!=typeof window}function He(){return"undefined"!=typeof navigator}function Xe(){return"undefined"!=typeof document}function Ye(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}class je{static get Now(){return We()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class $e{}$e.FilesToLoad={};class Ke extends Error{}Ke._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));const qe=3e3;class Qe extends Ke{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",Ke._setPrototypeOf(this,Qe.prototype)}}const Ze=e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,s,r,n,o,a,l,h="",c=0;const u=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c>2,o=(3&i)<<4|s>>4,a=(15&s)<<2|r>>6,l=63&r,isNaN(s)?a=l=64:isNaN(r)&&(l=64),h+=t.charAt(n)+t.charAt(o)+t.charAt(a)+t.charAt(l);return h},Je=e=>atob(e);class et{constructor(){this.children=[]}isValid(e){return!0}process(e,t){let i="";if(this.line){let s=this.line;const r=t.processor;if(r){r.lineProcessor&&(s=r.lineProcessor(s,t.isFragment,t.processingContext));const i=t.processor?.attributeKeywordName??"attribute",n=t.isFragment&&t.processor?.varyingFragmentKeywordName?t.processor?.varyingFragmentKeywordName:!t.isFragment&&t.processor?.varyingVertexKeywordName?t.processor?.varyingVertexKeywordName:"varying";!t.isFragment&&r.attributeProcessor&&this.line.startsWith(i)?s=r.attributeProcessor(this.line,e,t.processingContext):r.varyingProcessor&&(r.varyingCheck?.(this.line,t.isFragment)||!r.varyingCheck&&this.line.startsWith(n))?s=r.varyingProcessor(this.line,t.isFragment,e,t.processingContext):r.uniformProcessor&&r.uniformRegexp&&r.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(s=r.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):r.uniformBufferProcessor&&r.uniformBufferRegexp&&r.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(s=r.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):r.textureProcessor&&r.textureRegexp&&r.textureRegexp.test(this.line)?s=r.textureProcessor(this.line,t.isFragment,e,t.processingContext):(r.uniformProcessor||r.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?r.uniformProcessor&&(s=r.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):r.uniformBufferProcessor&&(s=r.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,r.endOfUniformBufferProcessor&&(s=r.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}i+=s+"\n"}return this.children.forEach((s=>{i+=s.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),i}}class tt{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(e);else{const e=t.split(";");for(let t=0;t{h=h.trim(),""!==h&&(i.push(h),h="")},n=e=>{srt._Stack[s],a=()=>-1===s?"!!INVALID EXPRESSION!!":rt._Stack[s--];let l=0,h="";for(;l1){for(r();-1!==s&&rt._OperatorPriority[o()]>=rt._OperatorPriority[c];)i.push(a());n(c),l++}else h+=t;l++}for(r();-1!==s;)"("===o()?a():i.push(a());return rt._InfixToPostfixCache.size>=rt.InfixToPostfixCacheLimitSize&&rt.ClearCache(),rt._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(rt._InfixToPostfixCache.entries()).sort(((e,t)=>e[1].accessTime-t[1].accessTime));for(let t=0;t":i=s>r;break;case"<":i=s=":i=s>=r;break;case"==":i=s===r;break;case"!=":i=s!==r}return i}}var ht,ct;(ct=ht||(ht={}))[ct.GLSL=0]="GLSL",ct[ct.WGSL=1]="WGSL";const ut={};function dt(e,t,i=""){return i+(t?t+"\n":"")+e}function pt(e,t,i,s,r,n,o){const a=o||ut.loadFile;if(a)return a(e,t,i,s,r,n);throw ye("FileTools")}function ft(e,t,i,s){if(e)return t?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,i?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(s?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return t&&(e+="#define IS_NDC_HALF_ZRANGE"),i&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),s&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}const _t=/defined\s*?\((.+?)\)/g,mt=/defined\s*?\[(.+?)\]/g,gt=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,vt=/__decl__/,xt=/light\{X\}.(\w*)/g,Tt=/\{X\}/g,St=[],Et=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function bt(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}function Ct(e,t,i,s){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),Ot(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const r=function(e,t,i){let s=function(e,t){if(t.processor?.noPrecision)return e;const i=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=i?"precision highp float;\n"+e:"precision mediump float;\n"+e:i||(e=e.replace("precision highp float","precision mediump float")),e}(e,t);if(!t.processor)return s;if(t.processor.shaderLanguage===ht.GLSL&&-1!==s.indexOf("#version 3")&&(s=s.replace("#version 300 es",""),!t.processor.parseGLES3))return s;const r=t.defines,n=Dt(t,i);return t.processor.preProcessor&&(s=t.processor.preProcessor(s,r,n,t.isFragment,t.processingContext)),s=Mt(s,n,t),t.processor.postProcessor&&(s=t.processor.postProcessor(s,r,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),i?._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}(e,t,s);i(r,e)}))}function yt(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}function At(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new nt(t[1].trim(),"!"===e[0]);const i=["==","!=",">=","<=","<",">"];let s="",r=0;for(s of i)if(r=e.indexOf(s),r>-1)break;if(-1===r)return new nt(e);const n=e.substring(0,r).trim(),o=e.substring(r+s.length).trim();return new lt(n,s,o)}function Rt(e,t){const i=new st,s=e.substring(0,t);let r=e.substring(t);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),i.testExpression="#ifdef"===s?new nt(r):"#ifndef"===s?new nt(r,!0):function(e){e=e.replace(_t,"defined[$1]");const t=rt.infixToPostfix(e),i=[];for(const e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],s=i[i.length-2];i.length-=2;const r="&&"==e?new at:new ot;"string"==typeof t&&(t=t.replace(mt,"defined($1)")),"string"==typeof s&&(s=s.replace(mt,"defined($1)")),r.leftOperand="string"==typeof s?At(s):s,r.rightOperand="string"==typeof t?At(t):t,i.push(r)}let s=i[i.length-1];return"string"==typeof s&&(s=s.replace(mt,"defined($1)")),"string"==typeof s?At(s):s}(r),i}function It(e,t,i){let s=e.currentLine;for(;Pt(e,i);){s=e.currentLine;const r=s.substring(0,5).toLowerCase();if("#else"===r){const i=new et;return t.children.push(i),void Pt(e,i)}if("#elif"===r){const e=Rt(s,5);t.children.push(e),i=e}}}function Pt(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const s=Et.exec(i);if(s&&s.length){switch(s[0]){case"#ifdef":{const s=new it;t.children.push(s);const r=Rt(i,6);s.children.push(r),It(e,s,r);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const s=new it;t.children.push(s);const r=Rt(i,7);s.children.push(r),It(e,s,r);break}case"#if":{const s=new it,r=Rt(i,3);t.children.push(s),s.children.push(r),It(e,s,r);break}}continue}}const s=new et;if(s.line=i,t.children.push(s),"#"===i[0]&&"d"===i[1]){const e=i.replace(";","").split(" ");s.additionalDefineKey=e[1],3===e.length&&(s.additionalDefineValue=e[2])}}return!1}function Mt(e,t,i){const s=new et,r=new tt;return r.lineIndex=-1,r.lines=e.split("\n"),Pt(r,s),s.process(t,i)}function Dt(e,t){const i=e.defines,s={};for(const e of i){const t=e.replace("#define","").replace(";","").trim().split(" ");s[t[0]]=t.length>1?t[1]:""}return e.processor?.shaderLanguage===ht.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",ft(s,t?.isNDCHalfZRange,t?.useReverseDepthBuffer,t?.useExactSrgbConversions),s}function Ot(e,t,i){let s;for(St.length=0;null!==(s=gt.exec(e));)St.push(s);let r=String(e),n=[e],o=!1;for(const e of St){let s=e[1];if(-1!==s.indexOf("__decl__")&&(s=s.replace(vt,""),t.supportsUniformBuffers&&(s=s.replace("Vertex","Ubo").replace("Fragment","Ubo")),s+="Declaration"),!t.includesShadersStore[s]){const e=t.shadersRepository+"ShadersInclude/"+s+".fx";return void Nt.loadFile(e,(e=>{t.includesShadersStore[s]=e,Ot(n.join(""),t,i)}))}{let i=t.includesShadersStore[s];if(e[2]){const t=e[3].split(",");for(let e=0;et+"{X}"))),i+=o.replace(Tt,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(xt,((e,t)=>t+"{X}"))),i=i.replace(Tt,s)}const r=[];for(const t of n){const s=t.split(e[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}}St.length=0,r=n.join(""),o?Ot(r.toString(),t,i):i(r)}const Nt={loadFile:(e,t,i,s,r,n)=>{throw ye("FileTools")}};class wt{static SetImmediate(e){We()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}class Ft{static GetShadersRepository(e=ht.GLSL){return e===ht.GLSL?Ft.ShadersRepository:Ft.ShadersRepositoryWGSL}static GetShadersStore(e=ht.GLSL){return e===ht.GLSL?Ft.ShadersStore:Ft.ShadersStoreWGSL}static GetIncludesShadersStore(e=ht.GLSL){return e===ht.GLSL?Ft.IncludesShadersStore:Ft.IncludesShadersStoreWGSL}}Ft.ShadersRepository="src/Shaders/",Ft.ShadersStore={},Ft.IncludesShadersStore={},Ft.ShadersRepositoryWGSL="src/ShadersWGSL/",Ft.ShadersStoreWGSL={},Ft.IncludesShadersStoreWGSL={};class Lt{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,i,s,r,n,o,a){const l=this.engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this.engine.getUniforms(this,i).forEach(((e,t)=>{s[i[t]]=e})),this._uniforms=s,h=0;h{n[e]=t}));for(const e of l.getAttributes(this,o))a.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s||2!==s.length)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r||3!==r.length)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this.engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this.engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}const Bt=new WeakMap,Vt={_webGLVersion:2,cachedPipelines:{}};function Ut(e){let t=Bt.get(e);if(!t){if(!e)return Vt;t={_webGLVersion:e.TEXTURE_BINDING_3D?2:1,_context:e,cachedPipelines:{}},Bt.set(e,t)}return t}function kt(e,t,i,s,r,n){const o=Ut(s);return n||(n=o._createShaderProgramInjection??zt),n(e,Xt(t,"vertex",s,o._contextWasLost),Xt(i,"fragment",s,o._contextWasLost),s,r,o.validateShaderPrograms)}function Gt(e,t,i,s,r,n=null,o){const a=Ut(r);o||(o=a._createShaderProgramInjection??zt);const l=a._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"";return o(e,Ht(t,"vertex",s,l,r,a._contextWasLost),Ht(i,"fragment",s,l,r,a._contextWasLost),r,n,a.validateShaderPrograms)}function zt(e,t,i,s,r=null,n){const o=s.createProgram();if(e.program=o,!o)throw new Error("Unable to create program");return s.attachShader(o,t),s.attachShader(o,i),s.linkProgram(o),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||Wt(e,s,n),o}function Wt(e,t,i){const s=e.context,r=e.vertexShader,n=e.fragmentShader,o=e.program;if(!s.getProgramParameter(o,s.LINK_STATUS)){if(!t.getShaderParameter(r,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(r);if(i)throw e.vertexCompilationError=i,new Error("VERTEX SHADER "+i)}if(!t.getShaderParameter(n,t.COMPILE_STATUS)){const i=t.getShaderInfoLog(n);if(i)throw e.fragmentCompilationError=i,new Error("FRAGMENT SHADER "+i)}const i=s.getProgramInfoLog(o);if(i)throw e.programLinkError=i,new Error(i)}if(i&&(s.validateProgram(o),!s.getProgramParameter(o,s.VALIDATE_STATUS))){const t=s.getProgramInfoLog(o);if(t)throw e.programValidationError=t,new Error(t)}s.deleteShader(r),s.deleteShader(n),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}function Ht(e,t,i,s,r,n){return Xt(dt(e,i,s),t,r,n)}function Xt(e,t,i,s){const r=i.createShader("vertex"===t?i.VERTEX_SHADER:i.FRAGMENT_SHADER);if(!r){let e=i.NO_ERROR,r=i.NO_ERROR;for(;(r=i.getError())!==i.NO_ERROR;)e=r;throw new Error(`Something went wrong while creating a gl ${t} shader object. gl error=${e}, gl isContextLost=${i.isContextLost()}, _contextWasLost=${s}`)}return i.shaderSource(r,e),i.compileShader(r),r}function Yt(e){const t=e._name,i=e.context;if(t&&i){const e=Ut(i),s=e.cachedPipelines[t];s?.dispose(),delete e.cachedPipelines[t]}}function jt(e,t,i,s,r,n){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void s(Ye(e));if("source:"===e.substr(0,7))return void s(e.substr(7));if("base64:"===e.substr(0,7))return void s(window.atob(e.substr(7)));const o=Ft.GetShadersStore(r);if(o[e+t+"Shader"])return void s(o[e+t+"Shader"]);if(i&&o[e+i+"Shader"])return void s(o[e+i+"Shader"]);let a;if(a="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:Ft.GetShadersRepository(r)+e,!(n=n||pt))throw new Error("loadFileInjection is not defined");n(a+"."+t.toLowerCase()+".fx",s)}class $t{static get ShadersRepository(){return Ft.ShadersRepository}static set ShadersRepository(e){Ft.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new g),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,s=null,r,n=null,o=null,a=null,l=null,h,c="",u=ht.GLSL){this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new g,this.onErrorObservable=new g,this._onBindObservable=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=c;const d=this._key.replace(/\r/g,"").replace(/\n/g,"|");let p;if(t.attributes){const e=t;if(this._engine=i,this._attributesNames=e.attributes,this._uniformsNames=e.uniformsNames.concat(e.samplers),this._samplerList=e.samplers.slice(),this.defines=e.defines,this.onError=e.onError,this.onCompiled=e.onCompiled,this._fallbacks=e.fallbacks,this._indexParameters=e.indexParameters,this._transformFeedbackVaryings=e.transformFeedbackVaryings||null,this._multiTarget=!!e.multiTarget,this._shaderLanguage=e.shaderLanguage??ht.GLSL,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t{if(c[0]&&c[1]){e.isFragment=!0;const[a,l]=c;Ct(l,e,((n,l)=>{o&&(o._fragmentSourceCodeBeforeMigration=l),i&&(n=i("fragment",n));const h=yt(a,n,e);e=null;const c=function(e,t,i,s){if(i){const r=i.vertexElement||i.vertex||i.spectorName||i,n=i.fragmentElement||i.fragment||i.spectorName||i;return{vertexSourceCode:(s===ht.WGSL?"//":"")+"#define SHADER_NAME vertex:"+r+"\n"+e,fragmentSourceCode:(s===ht.WGSL?"//":"")+"#define SHADER_NAME fragment:"+n+"\n"+t}}return{vertexSourceCode:e,fragmentSourceCode:t}}(h.vertexCode,h.fragmentCode,t,r);s?.(c.vertexSourceCode,c.fragmentSourceCode)}),n)}};jt(a,"Vertex","",(t=>{bt(e),Ct(t,e,((e,s)=>{o&&(o._rawVertexSourceCode=t,o._vertexSourceCodeBeforeMigration=s),i&&(e=i("vertex",e)),c[0]=e,u()}),n)}),r),jt(l,"Fragment","Pixel",(e=>{o&&(o._rawFragmentSourceCode=e),c[1]=e,u()}),r)}({defines:this.defines.split("\n"),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:e??this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Ft.GetShadersRepository(this._shaderLanguage),includesShadersStore:Ft.GetIncludesShadersStore(this._shaderLanguage),version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:this._processCodeAfterIncludes},this.name,this._processFinalCode,((e,i)=>{this._vertexSourceCode=e,this._fragmentSourceCode=i,this._prepareEffect(t)}),this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getAttributesNames(){return this._attributesNames}getAttributeLocation(e){return this._attributes[e]}getAttributeLocationByName(e){return this._attributeLocationByName[e]}getAttributesCount(){return this._attributes.length}getUniformIndex(e){return this._uniformsNames.indexOf(e)}getUniform(e){return this._uniforms[e]}getSamplers(){return this._samplerList}getUniformNames(){return this._uniformsNames}getUniformBuffersNames(){return this._uniformBuffersNamesList}getIndexParameters(){return this._indexParameters}getCompilationError(){return this._compilationError}allFallbacksProcessed(){return this._allFallbacksProcessed}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}this._isDisposed||setTimeout((()=>{this._checkIsReady(e)}),16)}get vertexSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:this._pipelineContext?._getVertexShaderCode()??this._vertexSourceCode}get fragmentSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:this._pipelineContext?._getFragmentShaderCode()??this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}getPipelineGenerationOptions(){return{platformName:this._engine.shaderPlatformName,shaderLanguage:this._shaderLanguage,shaderNameOrContent:this.name,key:this._key,defines:this.defines.split("\n"),addGlobalDefines:!1,extendedProcessingOptions:{indexParameters:this._indexParameters,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,supportsUniformBuffers:this._engine.supportsUniformBuffers},extendedCreatePipelineOptions:{transformFeedbackVaryings:this._transformFeedbackVaryings,createAsRaw:!(!this._vertexSourceCodeOverride||!this._fragmentSourceCodeOverride)}}}_rebuildProgram(e,t,i,s){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{s&&s(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;t{try{const r=e.existingPipelineContext||t(e.shaderProcessingContext);return r._name=e.name,e.name&&e.context&&(Ut(e.context).cachedPipelines[e.name]=r),i(r,e.vertex,e.fragment,!!e.createAsRaw,"","",e.rebuildRebind,e.defines,e.transformFeedbackVaryings,""),s(r,(()=>{e.onRenderingStateCompiled?.(r)})),r}catch(e){throw J.Error("Error compiling effect"),e}})({existingPipelineContext:e?t:null,vertex:r,fragment:n,context:"WEBGL2"===o.shaderPlatformName?o._gl:void 0,rebuildRebind:(e,t,i,s)=>this._rebuildProgram(e,t,i,s),defines:s,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:i,parallelShaderCompile:o._caps.parallelShaderCompile,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:i=>{t&&!e&&this._engine._deletePipelineContext(t),i&&this._onRenderingStateCompiled(i)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContext.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t,i){const s=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let r=null;if(t&&e){const n=t.match(s);if(n&&2===n.length){const t=parseInt(n[1]),s=e.split("\n",-1);s.length>=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${s[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){this._compilationError=e.message;const i=this._attributesNames,s=this._fallbacks;if(J.Error("Unable to compile effect:"),J.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),J.Error("Attributes: "+i.map((function(e){return" "+e}))),J.Error("Defines:\n"+this.defines),$t.LogShaderCodeOnCompilationError){let e=null,t=null,i=null;this._pipelineContext?._getVertexShaderCode()&&([i,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),i&&(J.Error("Vertex code:"),J.Error(i))),this._pipelineContext?._getFragmentShaderCode()&&([i,t]=this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(),this._compilationError,!0),i&&(J.Error("Fragment code:"),J.Error(i))),e&&J.Error(e),t&&J.Error(t)}J.Error("Error: "+this._compilationError);const r=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,r()),s?(this._pipelineContext=null,s.hasMoreFallbacks?(this._allFallbacksProcessed=!1,J.Error("Trying next fallback."),this.defines=s.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,r(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||r())}get isSupported(){return""===this._compilationError}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){const s=this._samplerList.indexOf(e);for(let e=1;e{t._swapAndDie(this,!1),this.isReady=e.isReady};return void(e.isAsync?e.proxy.then(t):t(e.proxy))}let e;switch(this.source){case ei.Temp:break;case ei.Url:return void(e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,(e=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer));case ei.Raw:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case ei.Raw3D:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case ei.Raw2DArray:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case ei.Dynamic:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case ei.Cube:return void(e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,(()=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer));case ei.CubeRaw:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case ei.CubeRawRGBD:return;case ei.CubePrefiltered:return e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,(e=>{e&&e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension),void(e._sphericalPolynomial=this._sphericalPolynomial);case ei.DepthStencil:case ei.Depth:}}_swapAndDie(e,t=!0){this._hardwareTexture?.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const i=this._engine.getLoadedTexturesCache();let s=i.indexOf(this);-1!==s&&i.splice(s,1),s=i.indexOf(e),-1===s&&i.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}function ii(e,t){if(We()){const{requestAnimationFrame:i}=t||window;if("function"==typeof i)return i(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}ti._Counter=0;class si{get frameId(){return this._frameId}get isWebGPU(){return this._isWebGPU}_getShaderProcessor(e){return this._shaderProcessor}get shaderPlatformName(){return this._shaderPlatformName}_clearEmptyResources(){this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,this._depthCullingState.depthFunc=e?518:515)}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}_getGlobalDefines(e){if(e)return this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return this.isNDCHalfZRange&&(e+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}_rebuildInternalTextures(){const e=this._internalTexturesCache.slice();for(const t of e)t._rebuild()}_rebuildRenderTargetWrappers(){const e=this._renderTargetWrapperCache.slice();for(const t of e)t._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}$t.ResetCache()}_rebuildGraphicsResources(){this.wipeCaches(!0),this._rebuildEffects(),this._rebuildComputeEffects?.(),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){J.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout((async()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=r,this._flagContextRestored()}),0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return 0}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){const e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get activeRenderLoops(){return this._activeRenderLoops}stopRenderLoop(e){if(!e)return this._activeRenderLoops.length=0,void this._cancelFrame();const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(0!==this._frameHandler){const e=this._frameHandler;if(this._frameHandler=0,We()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if("function"==typeof t)return t(e)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(e);return clearTimeout(e)}}beginFrame(){this.onBeginFrameObservable.notifyObservers(this)}endFrame(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e-1?e.substring(S).toLowerCase():""),b=null;E.indexOf("?")>-1&&(E=E.split("?")[0]);for(const e of si._TextureLoaders)if(e.canLoad(E,p)){b=e;break}s&&s.addPendingData(x),x.url=e,x.generateMipMaps=!t,x.samplingMode=r,x.invertY=i,x._useSRGBBuffer=this._getUseSRGBBuffer(!!_,t),this._doNotHandleContextLost||(x._buffer=h);let C=null;n&&!c&&(C=x.onLoadedObservable.add(n)),c||this._internalTexturesCache.push(x);const A=(i,c)=>{s&&s.removePendingData(x),e===T?(C&&x.onLoadedObservable.remove(C),y.UseFallbackTexture&&e!==y.FallbackTexture&&this._createTextureBase(y.FallbackTexture,t,x.invertY,s,r,null,o,a,l,h,x),i=(i||"Unknown error")+(y.UseFallbackTexture?" - Fallback texture was used":""),x.onErrorObservable.notifyObservers({message:i,exception:c}),o&&o(i,c)):(J.Warn(`Failed to load ${e}, falling back to ${T}`),this._createTextureBase(T,t,x.invertY,s,r,n,o,a,l,h,x,u,d,p,f,_))};if(b){const t=e=>{b.loadData(e,x,((e,t,i,n,o,l)=>{l?A("TextureLoader failed to load data"):a(x,E,s,{width:e,height:t},x.invertY,!i,n,(()=>(o(),!1)),r)}),f)};h?h instanceof ArrayBuffer?t(new Uint8Array(h)):ArrayBuffer.isView(h)?t(h):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,s?s.offlineProvider:void 0,!0,((e,t)=>{A("Unable to load "+(e&&e.responseURL,t))}))}else{const i=e=>{g&&!this._doNotHandleContextLost&&(x._buffer=e),a(x,E,s,e,x.invertY,t,!1,l,r)};!m||v?h&&("string"==typeof h.decoding||h.close)?i(h):si._FileToolsLoadImage(e||"",i,A,s?s.offlineProvider:null,p,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof h||h instanceof ArrayBuffer||ArrayBuffer.isView(h)||h instanceof Blob?si._FileToolsLoadImage(h,i,A,s?s.offlineProvider:null,p,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):h&&i(h)}return x}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuildAfterContextLost()}get _shouldUseHighPrecisionShader(){return!(!this._caps.highPrecisionShaderSupported||!this._highPrecisionShadersAllowed)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:Xe()?document:null}getLoadedTexturesCache(){return this._internalTexturesCache}clearInternalTexturesCache(){this._internalTexturesCache.length=0}getCaps(){return this._caps}resetTextureCache(){for(const e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}get name(){return this._name}set name(e){this._name=e}static get NpmPackage(){return"babylonjs@7.9.0"}static get Version(){return"7.9.0"}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get isStencilEnable(){return this._isStencilEnable}getCreationOptions(){return this._creationOptions}constructor(e,t,i){this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new Kt,this._stencilStateComposer=new qt,this._stencilState=new Qt,this._alphaState=new Zt,this._alphaMode=1,this._alphaEquation=0,this._activeRequests=[],this._badOS=!1,this._badDesktopOS=!1,this._compatibilityMode=!0,this._internalTexturesCache=new Array,this._currentRenderTarget=null,this._boundTexturesCache={},this._activeChannel=0,this._currentTextureChannel=-1,this._viewportCached={x:0,y:0,z:0,w:0},this._isWebGPU=!1,this.onCanvasBlurObservable=new g,this.onCanvasFocusObservable=new g,this.onNewSceneAddedObservable=new g,this.onResizeObservable=new g,this.onCanvasPointerOutObservable=new g,this.disablePerformanceMonitorInBackground=!1,this.disableVertexArrayObjects=!1,this._frameId=0,this.hostInformation={isMobile:!1},this.isFullscreen=!1,this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.currentRenderPassId=0,this.isPointerLock=!1,this.postProcesses=[],this.canvasTabIndex=1,this._contextWasLost=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this._renderTargetWrapperCache=new Array,this._compiledEffects={},this._isDisposed=!1,this.scenes=[],this._virtualScenes=new Array,this.onBeforeTextureInitObservable=new g,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new g,this.onAfterShaderCompilationObservable=new g,this.onBeginFrameObservable=new g,this.onEndFrameObservable=new g,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new g,this.onContextRestoredObservable=new g,this._name="",this.premultipliedAlpha=!0,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._doNotHandleContextLost=!1,this.cullBackFaces=null,this._renderPassNames=["main"],this._fps=60,this._deltaTime=0,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this.onDisposeObservable=new g,y.Instances.push(this),this.startTime=je.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,C.SetMatrixPrecision(!!t.useHighPrecisionMatrix),He()&&navigator.userAgent&&(this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),this.adaptToDeviceRatio=i??!1,t.antialias=e??t.antialias,t.deterministicLockstep=t.deterministicLockstep??!1,t.lockstepMaxSteps=t.lockstepMaxSteps??4,t.timeStep=t.timeStep??1/60,t.audioEngine=t.audioEngine??!0,t.stencil=t.stencil??!0,this._audioContext=t.audioEngineOptions?.audioContext??null,this._audioDestination=t.audioEngineOptions?.audioDestination??null,this.premultipliedAlpha=t.premultipliedAlpha??!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=t.useExactSrgbConversions??!1;const s=We()&&window.devicePixelRatio||1,r=t.limitDeviceRatio||s;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(r,s):1,this._lastDevicePixelRatio=s,this._creationOptions=t}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){const e=We()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if(We()&&Xe())if(this._renderingCanvas){const e=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||e.width||this._renderingCanvas.width||100,i=this._renderingCanvas.clientHeight||e.height||this._renderingCanvas.height||100}else t=window.innerWidth,i=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){if(!this._renderingCanvas)return!1;if(e|=0,t|=0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t)return!1;if(this._renderingCanvas.width=e,this._renderingCanvas.height=t,this.scenes){for(let e=0;e{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&Xe()&&"ontouchend"in document},this._checkForMobile(),We()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){this._drawCalls?.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}_createImageBitmapFromSource(e,t){throw new Error("createImageBitmapFromSource is not implemented")}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){throw new Error("resizeImageBitmap is not implemented")}getFontOffset(e){throw new Error("getFontOffset is not implemented")}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);const i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return si._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,s,r,n){throw ye("FileTools")}_loadFile(e,t,i,s,r,n){const o=pt(e,t,i,s,r,n);return this._activeRequests.push(o),o.onCompleteObservable.add((()=>{const e=this._activeRequests.indexOf(o);-1!==e&&this._activeRequests.splice(e,1)})),o}static _FileToolsLoadFile(e,t,i,s,r,n){if(ut.loadFile)return ut.loadFile(e,t,i,s,r,n);throw ye("FileTools")}dispose(){for(this.hideLoadingUI(),this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();this.releaseComputeEffects?.(),$t.ResetCache();for(const e of this._activeRequests)e.abort();this._boundRenderFunction=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onNewSceneAddedObservable.clear(),We()&&window.removeEventListener("resize",this._checkForMobile);const e=y.Instances.indexOf(this);e>=0&&y.Instances.splice(e,1),y.Instances.length||(y.OnEnginesDisposedObservable.notifyObservers(this),y.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw ye("LoadingScreen")}}si._TextureLoaders=[],si._RenderPassIdCounter=0,si._RescalePostProcessFactory=null;const ri=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class ni extends Qe{constructor(e,t){super(e,4e3),this.name="LoadFileError",Ke._setPrototypeOf(this,ni.prototype),t instanceof Ne?this.request=t:this.file=t}}class oi extends Qe{constructor(e,t){super(e,4001),this.request=t,this.name="RequestFileError",Ke._setPrototypeOf(this,oi.prototype)}}class ai extends Qe{constructor(e,t){super(e,4002),this.file=t,this.name="ReadFileError",Ke._setPrototypeOf(this,ai.prototype)}}const li={DefaultRetryStrategy:class{static ExponentialBackoff(e=3,t=500){return(i,s,r)=>0!==s.status||r>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,r)*t}}.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e,CleanUrl:e=>e.replace(/#/gm,"%23")},hi=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&li.CorsBehavior)if("string"==typeof li.CorsBehavior||li.CorsBehavior instanceof String)t.crossOrigin=li.CorsBehavior;else{const i=li.CorsBehavior(e);i&&(t.crossOrigin=i)}},ci=(e,t,i,s,r="",n)=>{const o=y.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!o?._features.forceBitmapOverHTMLImageElement)return i("LoadImage is only supported in web or BabylonNative environments."),null;let a,l=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(a=URL.createObjectURL(new Blob([e],{type:r})),l=!0):a=`data:${r};base64,`+Ze(e):e instanceof Blob?(a=URL.createObjectURL(e),l=!0):(a=li.CleanUrl(e),a=li.PreprocessUrl(e));const h=t=>{if(i){const s=a||e.toString();i(`Error while trying to load image: ${0===s.indexOf("http")||s.length<=128?s:s.slice(0,128)+"..."}`,t)}};if(o?._features.forceBitmapOverHTMLImageElement)return di(a,(s=>{o.createImageBitmap(new Blob([s],{type:r}),{premultiplyAlpha:"none",...n}).then((e=>{t(e),l&&URL.revokeObjectURL(a)})).catch((t=>{i&&i("Error while trying to load image: "+e,t)}))}),void 0,s||void 0,!0,((e,t)=>{h(t)})),null;const c=new Image;hi(a,c);const u=[],d=()=>{u.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),u.length=0};u.push({target:c,name:"load",handler:()=>{d(),t(c),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:c,name:"error",handler:e=>{d(),h(e),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==c.src)return;d();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);y.UseFallbackTexture=!1,h(t),l&&c.src&&URL.revokeObjectURL(c.src),c.src=""}}),u.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const p="blob:"===a.substring(0,5),f="data:"===a.substring(0,5),_=()=>{p||f||!Ne.IsCustomRequestAvailable?c.src=a:di(a,((e,t,i)=>{const s=new Blob([e],{type:!r&&i?i:r}),n=URL.createObjectURL(s);l=!0,c.src=n}),void 0,s||void 0,!0,((e,t)=>{h(t)}))};if(!p&&!f&&s&&s.enableTexturesOffline)s.open((()=>{s&&s.loadImage(a,c)}),_);else{if(-1!==a.indexOf("file:")){const e=decodeURIComponent(a.substring(5).toLowerCase());if($e.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL($e.FilesToLoad[e])}catch(i){t=URL.createObjectURL($e.FilesToLoad[e])}c.src=t,l=!0}catch(e){c.src=""}return c}}_()}return c},ui=(e,t,i,s,r)=>{const n=new FileReader,o={onCompleteObservable:new g,abort:()=>n.abort()};return n.onloadend=()=>o.onCompleteObservable.notifyObservers(o),r&&(n.onerror=()=>{r(new ai(`Unable to read ${e.name}`,e))}),n.onload=e=>{t(e.target.result)},i&&(n.onprogress=i),s?n.readAsArrayBuffer(e):n.readAsText(e),o},di=(e,t,i,s,r,n,o)=>{if(e.name)return ui(e,t,i,r,n?e=>{n(void 0,e)}:void 0);const a=e;if(-1!==a.indexOf("file:")){let e=decodeURIComponent(a.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const s=$e.FilesToLoad[e];if(s)return ui(s,t,i,r,n?e=>n(void 0,new ni(e.message,e.file)):void 0)}const{match:l,type:h}=mi(a);if(l){const e={onCompleteObservable:new g,abort:()=>()=>{}};try{const e=r?gi(a):vi(a);t(e,void 0,h)}catch(e){n?n(void 0,e):J.Error(e.message||"Failed to parse the Data URL")}return wt.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return pi(a,((e,i)=>{t(e,i?.responseURL,i?.getResponseHeader("content-type"))}),i,s,r,n?e=>{n(e.request,new ni(e.message,e.request))}:void 0,o)},pi=(e,t,i,s,r,n,o)=>{e=li.CleanUrl(e),e=li.PreprocessUrl(e);const a=li.BaseUrl+e;let l=!1;const h={onCompleteObservable:new g,abort:()=>l=!0},c=()=>{let e,s=new Ne,c=null;const u=()=>{s&&(i&&s.removeEventListener("progress",i),e&&s.removeEventListener("readystatechange",e),s.removeEventListener("loadend",d))};let d=()=>{u(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),i=void 0,e=null,d=null,n=void 0,o=void 0,t=void 0};h.abort=()=>{l=!0,d&&d(),s&&s.readyState!==(XMLHttpRequest.DONE||4)&&s.abort(),null!==c&&(clearTimeout(c),c=null),s=null};const p=e=>{const t=e.message||"Unknown error";n&&s?n(new oi(t,s)):J.Error(t)},f=h=>{if(s){if(s.open("GET",a),o)try{o(s)}catch(e){return void p(e)}r&&(s.responseType="arraybuffer"),i&&s.addEventListener("progress",i),d&&s.addEventListener("loadend",d),e=()=>{if(!l&&s&&s.readyState===(XMLHttpRequest.DONE||4)){if(e&&s.removeEventListener("readystatechange",e),s.status>=200&&s.status<300||0===s.status&&(!We()||fi())){try{t&&t(r?s.response:s.responseText,s)}catch(e){p(e)}return}const i=li.DefaultRetryStrategy;if(i){const e=i(a,s,h);if(-1!==e)return u(),s=new Ne,void(c=setTimeout((()=>f(h+1)),e))}const o=new oi("Error status: "+s.status+" "+s.statusText+" - Unable to load "+a,s);n&&n(o)}},s.addEventListener("readystatechange",e),s.send()}};f(0)};if(s&&s.enableSceneOffline){const o=e=>{e&&e.status>400?n&&n(e):c()},a=()=>{s&&s.loadFile(li.BaseUrl+e,(e=>{!l&&t&&t(e),h.onCompleteObservable.notifyObservers(h)}),i?e=>{!l&&i&&i(e)}:void 0,o,r)};s.open(a,o)}else c();return h},fi=()=>"undefined"!=typeof location&&"file:"===location.protocol,_i=e=>ri.test(e),mi=e=>{const t=ri.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function gi(e){return(e=>{const t=Je(e),i=t.length,s=new Uint8Array(new ArrayBuffer(i));for(let e=0;eJe(e.split(",")[1]);let xi;si._FileToolsLoadImage=ci,ut.loadFile=di,Nt.loadFile=di,((e,t,i,s,r,n,o,a,l,h)=>{xi={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:s,IsFileURL:r,LoadFile:n,LoadImage:o,ReadFile:a,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(xi,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(xi,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(xi,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(xi,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})})(gi,vi,li,_i,fi,di,ci,ui,pi,hi);class Ti{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=d(e);if(t)return t;J.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let s=window||this;for(let e=0,t=i.length;e{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}function Ei(e){let t=1;do{t*=2}while(te-i?i:t}function yi(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}function Ai(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}function Ri(e,t,i=2){let s;switch(i){case 1:s=Ai(e);break;case 2:s=Ci(e);break;default:s=yi(e)}return Math.min(s,t)}Ti.RegisteredExternalClasses={};class Ii{static get BaseUrl(){return li.BaseUrl}static set BaseUrl(e){li.BaseUrl=e}static get CleanUrl(){return li.CleanUrl}static set CleanUrl(e){li.CleanUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||-1!==e.indexOf("://")&&-1!==e.indexOf(".")&&-1!==e.indexOf("/")&&!(e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://"){di(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{s(t)}))}))}static GetBabylonScriptURL(e,t){if(!e)return"";if(Ii.ScriptBaseUrl&&e.startsWith(Ii._DefaultCdnUrl)){const t="/"===Ii.ScriptBaseUrl[Ii.ScriptBaseUrl.length-1]?Ii.ScriptBaseUrl.substring(0,Ii.ScriptBaseUrl.length-1):Ii.ScriptBaseUrl;e=e.replace(Ii._DefaultCdnUrl,t)}return e=Ii.ScriptPreprocessUrl(e),t&&(e=Ii.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,s){e=Ii.GetBabylonScriptURL(e),Ii.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=Ii.GetBabylonScriptURL(e),Ii.LoadScriptAsync(e)}static LoadScript(e,t,i,s){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){i?.(`Unable to load script '${e}' in worker`,t)}return}if(!We())return void i?.(`Cannot load script '${e}' outside of a window or a worker`);const r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("src",e),s&&(n.id=s),n.onload=()=>{t&&t()},n.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},r.appendChild(n)}static LoadScriptAsync(e,t){return new Promise(((i,s)=>{this.LoadScript(e,(()=>{i()}),((e,t)=>{s(t||new Error(e))}),t)}))}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new g,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,s,r){return ui(e,t,i,s,r)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,s){se.DeepCopy(e,t,i,s)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{const s=atob(this.toDataURL(t,i).split(",")[1]),r=s.length,n=new Uint8Array(r);for(let e=0;et(e))):e.toBlob((function(e){t(e)}),i,s)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const e=new Date;t="screenshot_"+(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2)+".png"}Ii.Download(e,t)}else if(e&&"undefined"!=typeof URL){const t=URL.createObjectURL(e),i=window.open("");if(!i)return;const s=i.document.createElement("img");s.onload=function(){URL.revokeObjectURL(t)},s.src=t,i.document.body.appendChild(s)}}static EncodeScreenshotCanvasData(e,t,i="image/png",s,r){if("string"!=typeof s&&t){if(t){if(Ii._IsOffScreenCanvas(e))return void e.convertToBlob({type:i,quality:r}).then((e=>{const i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{const e=i.result;t(e)}}));const s=e.toDataURL(i,r);t(s)}}else this.ToBlob(e,(function(e){e&&Ii.DownloadBlob(e,s),t&&t("")}),i,r)}static Download(e,t){if("undefined"==typeof URL)return;const i=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.style.display="none",s.href=i,s.download=t,s.addEventListener("click",(()=>{s.parentElement&&s.parentElement.removeChild(s)})),s.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,s,r="image/png",n=!1,o){throw ye("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,s="image/png",r){throw ye("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,s,r="image/png",n=1,o=!1,a,l=!1,h=!1,c=!0,u){throw ye("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,s="image/png",r=1,n=!1,o,a=!1,l=!1,h=!0,c){throw ye("ScreenshotTools")}static RandomId(){return Si()}static IsBase64(e){return _i(e)}static DecodeBase64(e){return gi(e)}static get errorsCount(){return J.errorsCount}static Log(e){J.Log(e)}static Warn(e){J.Warn(e)}static Error(e){J.Error(e)}static get LogCache(){return J.LogCache}static ClearLogCache(){J.ClearLogCache()}static set LogLevels(e){J.LogLevels=e}static set PerformanceLogLevel(e){return(e&Ii.PerformanceUserMarkLogLevel)===Ii.PerformanceUserMarkLogLevel?(Ii.StartPerformanceCounter=Ii._StartUserMark,void(Ii.EndPerformanceCounter=Ii._EndUserMark)):(e&Ii.PerformanceConsoleLogLevel)===Ii.PerformanceConsoleLogLevel?(Ii.StartPerformanceCounter=Ii._StartPerformanceConsole,void(Ii.EndPerformanceCounter=Ii._EndPerformanceConsole)):(Ii.StartPerformanceCounter=Ii._StartPerformanceCounterDisabled,void(Ii.EndPerformanceCounter=Ii._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Ii._Performance){if(!We())return;Ii._Performance=window.performance}t&&Ii._Performance.mark&&Ii._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&Ii._Performance.mark&&(Ii._Performance.mark(e+"-End"),Ii._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Ii._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Ii._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return je.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(const i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,s=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){const r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__,s=r.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=s?s+".":"")+i:null}static DelayAsync(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}static IsSafari(){return!!He()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}Ii.UseCustomRequestHeaders=!1,Ii.CustomRequestHeaders=Ne.CustomRequestHeaders,Ii.GetDOMTextContent=Ye,Ii._DefaultCdnUrl="https://cdn.babylonjs.com",Ii.GetAbsoluteUrl="object"==typeof document?e=>{const t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},Ii.NoneLogLevel=J.NoneLogLevel,Ii.MessageLogLevel=J.MessageLogLevel,Ii.WarningLogLevel=J.WarningLogLevel,Ii.ErrorLogLevel=J.ErrorLogLevel,Ii.AllLogLevel=J.AllLogLevel,Ii.IsWindowObjectExist=We,Ii.PerformanceNoneLogLevel=0,Ii.PerformanceUserMarkLogLevel=1,Ii.PerformanceConsoleLogLevel=2,Ii.StartPerformanceCounter=Ii._StartPerformanceCounterDisabled,Ii.EndPerformanceCounter=Ii._EndPerformanceCounterDisabled;class Pi{constructor(e,t,i,s=0){this.iterations=e,this.index=s-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{r&&r()?s.breakLoop():setTimeout((()=>{for(let n=0;n=e)break;if(i(o),r&&r()){s.breakLoop();break}}s.executeNext()}),n)}),s)}}Ii.Mix=bi,Ii.IsExponentOfTwo=Ei,y.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";class Mi{constructor(e){this.length=0,this.data=new Array(e),this._id=Mi._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}Mi._GlobalId=0;class Di extends Mi{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return!(e.__smartArrayFlags&&e.__smartArrayFlags[this._id]===this._duplicateId||(this.push(e),0))}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;tthis.add(e,t)))}get(e){const t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let i=this.get(e);return void 0!==i||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){const i=this.get(e);return void 0!==i?i:(this.add(e,t),t)}contains(e){return void 0!==this._data[e]}add(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)}set(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null}remove(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data)e(t,this._data[t])}first(e){for(const t in this._data){const i=e(t,this._data[t]);if(i)return i}return null}}function Ni(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}class wi{constructor(){this._dirty=!0,this._tempColor=new j(0,0,0,0),this._globalCurve=new j(0,0,0,0),this._highlightsCurve=new j(0,0,0,0),this._midtonesCurve=new j(0,0,0,0),this._shadowsCurve=new j(0,0,0,0),this._positiveCurve=new j(0,0,0,0),this._negativeCurve=new j(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",s="vCameraColorCurveNeutral",r="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(s,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(r,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,s,r){null!=e&&(e=wi._Clamp(e,0,360),t=wi._Clamp(t,-100,100),i=wi._Clamp(i,-100,100),s=wi._Clamp(s,-100,100),t=wi._ApplyColorGradingSliderNonlinear(t),t*=.5,s=wi._ApplyColorGradingSliderNonlinear(s),t<0&&(t*=-1,e=(e+180)%360),wi._FromHSBToRef(e,t,50+.25*s,r),r.scaleToRef(2,r),r.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,s){let r=wi._Clamp(e,0,360);const n=wi._Clamp(t/100,0,1),o=wi._Clamp(i/100,0,1);if(0===n)s.r=o,s.g=o,s.b=o;else{r/=60;const e=Math.floor(r),t=r-e,i=o*(1-n),a=o*(1-n*t),l=o*(1-n*(1-t));switch(e){case 0:s.r=o,s.g=l,s.b=i;break;case 1:s.r=a,s.g=o,s.b=i;break;case 2:s.r=i,s.g=o,s.b=l;break;case 3:s.r=i,s.g=a,s.b=o;break;case 4:s.r=l,s.g=i,s.b=o;break;default:s.r=o,s.g=i,s.b=a}}s.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return Pe.Clone((()=>new wi),this)}serialize(){return Pe.Serialize(this)}static Parse(e){return Pe.Parse((()=>new wi),e,null,null)}}function Fi(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&Ni(e),t.DITHER&&e.push("ditherIntensity")}function Li(e,t){t.COLORGRADING&&e.push("txColorTransform")}wi.PrepareUniforms=Ni,ae([pe()],wi.prototype,"_globalHue",void 0),ae([pe()],wi.prototype,"_globalDensity",void 0),ae([pe()],wi.prototype,"_globalSaturation",void 0),ae([pe()],wi.prototype,"_globalExposure",void 0),ae([pe()],wi.prototype,"_highlightsHue",void 0),ae([pe()],wi.prototype,"_highlightsDensity",void 0),ae([pe()],wi.prototype,"_highlightsSaturation",void 0),ae([pe()],wi.prototype,"_highlightsExposure",void 0),ae([pe()],wi.prototype,"_midtonesHue",void 0),ae([pe()],wi.prototype,"_midtonesDensity",void 0),ae([pe()],wi.prototype,"_midtonesSaturation",void 0),ae([pe()],wi.prototype,"_midtonesExposure",void 0),Pe._ColorCurvesParser=wi.Parse;class Bi{constructor(){this.colorCurves=new wi,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=Bi.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new j(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=Bi.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new g}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled)return e.VIGNETTE=!1,e.TONEMAPPING=0,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,void(e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===Bi._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,this._toneMappingEnabled)switch(this._toneMappingType){case Bi.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case Bi.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1}else e.TONEMAPPING=0;e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||!!e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&wi.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const i=1/e.getEngine().getRenderWidth(),s=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,s),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=null!=t?t:s/i;let n=Math.tan(.5*this.vignetteCameraFov),o=n*r;const a=Math.sqrt(o*n);o=bi(o,a,this.vignetteStretch),n=bi(n,a,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,n,-o*this.vignetteCenterX,-n*this.vignetteCenterY);const l=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,l)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return Pe.Clone((()=>new Bi),this)}serialize(){return Pe.Serialize(this)}static Parse(e){const t=Pe.Parse((()=>new Bi),e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}function Vi(e){return void 0===e.getPipelineContext}Bi.TONEMAPPING_STANDARD=0,Bi.TONEMAPPING_ACES=1,Bi.TONEMAPPING_KHR_PBR_NEUTRAL=2,Bi.PrepareUniforms=Fi,Bi.PrepareSamplers=Li,Bi._VIGNETTEMODE_MULTIPLY=0,Bi._VIGNETTEMODE_OPAQUE=1,ae([ue(7,undefined)],Bi.prototype,"colorCurves",void 0),ae([pe()],Bi.prototype,"_colorCurvesEnabled",void 0),ae([fe("colorGradingTexture")],Bi.prototype,"_colorGradingTexture",void 0),ae([pe()],Bi.prototype,"_colorGradingEnabled",void 0),ae([pe()],Bi.prototype,"_colorGradingWithGreenDepth",void 0),ae([pe()],Bi.prototype,"_colorGradingBGR",void 0),ae([pe()],Bi.prototype,"_exposure",void 0),ae([pe()],Bi.prototype,"_toneMappingEnabled",void 0),ae([pe()],Bi.prototype,"_toneMappingType",void 0),ae([pe()],Bi.prototype,"_contrast",void 0),ae([pe()],Bi.prototype,"vignetteStretch",void 0),ae([pe()],Bi.prototype,"vignetteCenterX",void 0),ae([pe()],Bi.prototype,"vignetteCenterY",void 0),ae([pe()],Bi.prototype,"vignetteWeight",void 0),ae([Te()],Bi.prototype,"vignetteColor",void 0),ae([pe()],Bi.prototype,"vignetteCameraFov",void 0),ae([pe()],Bi.prototype,"_vignetteBlendMode",void 0),ae([pe()],Bi.prototype,"_vignetteEnabled",void 0),ae([pe()],Bi.prototype,"_ditheringEnabled",void 0),ae([pe()],Bi.prototype,"_ditheringIntensity",void 0),ae([pe()],Bi.prototype,"_skipFinalColorClamp",void 0),ae([pe()],Bi.prototype,"_applyByPostProcess",void 0),ae([pe()],Bi.prototype,"_isEnabled",void 0),Pe._ImageProcessingConfigurationParser=Bi.Parse,u("BABYLON.ImageProcessingConfiguration",Bi);class Ui{constructor(){this.shaderLanguage=ht.GLSL}postProcessor(e,t,i,s,r){if(r.drawBuffersExtensionDisabled){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}const ki=/(flat\s)?\s*varying\s*.*/;class Gi{constructor(){this.shaderLanguage=ht.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return ki.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(s||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}class zi{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=zi._Counter++}}zi._Counter=0;class Wi extends zi{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class Hi{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){return this._MSAARenderBuffers?.[e]??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}class Xi{}class Yi extends si{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return $t.ShadersRepository}static set ShadersRepository(e){$t.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}snapshotRenderingReset(){this.snapshotRendering=!1}constructor(e,t,i,s){if(i=i||{},super(t??i.antialias,i,s),this._name="WebGL",this.forcePOTTextures=!1,this.validateShaderPrograms=!1,this.disableUniformBuffers=!1,this._webGLVersion=1,this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},!e)return;let r=null;if(e.getContext){if(r=e,this._renderingCanvas=r,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();const e=navigator.userAgent;for(const t of Yi.ExceptionList){const s=t.key,r=t.targets;if(new RegExp(s).test(e)){if(t.capture&&t.captureConstraint){const i=t.capture,s=t.captureConstraint,r=new RegExp(i).exec(e);if(r&&r.length>0&&parseInt(r[r.length-1])>=s)continue}for(const e of r)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,J.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost((()=>this._initGLContext()))},r.addEventListener("webglcontextlost",this._onContextLost,!1),r.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=r.getContext("webgl2",i)||r.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!r)throw new Error("The provided canvas is null or undefined.");try{this._gl=r.getContext("webgl",i)||r.getContext("experimental-webgl",i)}catch(e){throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";const t=this._gl.getContextAttributes();t&&(i.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==i.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e1?new Gi:new Ui;const n=`Babylon.js v${Yi.Version}`;J.Log(n+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",n);const o=Ut(this._gl);o.validateShaderPrograms=this.validateShaderPrograms,o.parallelShaderCompile=this._caps.parallelShaderCompile}_clearEmptyResources(){this._dummyFramebuffer=null,super._clearEmptyResources()}_getShaderProcessingContext(e){return null}areAllEffectsReady(){for(const e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_initGLContext(){this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||null!==this._gl.getExtension("OES_standard_derivatives"),maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:1!==this._webGLVersion,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=e&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)??0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!(!this._creationOptions||!this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);this._gl.uniformBlockBinding(s,r,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,s,r,n,o){const a=this._currentBufferPointers[t];if(!a)return;let l=!1;a.active?(a.buffer!==e&&(a.buffer=e,l=!0),a.size!==i&&(a.size=i,l=!0),a.type!==s&&(a.type=s,l=!0),a.normalized!==r&&(a.normalized=r,l=!0),a.stride!==n&&(a.stride=n,l=!0),a.offset!==o&&(a.offset=o,l=!0)):(l=!0,a.active=!0,a.index=t,a.size=i,a.type=s,a.normalized=r,a.stride=n,a.offset=o,a.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),s===this._gl.UNSIGNED_INT||s===this._gl.INT?this._gl.vertexAttribIPointer(t,i,s,n,o):this._gl.vertexAttribPointer(t,i,s,r,n,o))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){const s=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let r=0;r=0){const t=s[r];let o=null;if(i&&(o=i[t]),o||(o=e[t]),!o)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const a=o.getBuffer();a&&(this._vertexAttribPointer(a,n,o.getSize(),o.type,o.normalized,o.byteStride,o.byteOffset),o.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,o.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(a))))}}}recordVertexArrayObject(e,t,i,s){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,s),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,s,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const t=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let o=0;o=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[o],this._gl.FLOAT,!1,s,n)),n+=4*i[o]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,s){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===i||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,s)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t{s?.(),t(e)}}(e,t)}getUniforms(e,t){const i=new Array,s=e;for(let e=0;e1||this.isWebGPU)),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(a=1),1!==o||this._caps.textureFloat||(o=0,J.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=this._gl,d=new ti(this,s),p=e.width||e,f=e.height||e,_=e.depth||0,m=e.layers||0,g=this._getSamplingParameters(a,n),v=0!==m?u.TEXTURE_2D_ARRAY:0!==_?u.TEXTURE_3D:u.TEXTURE_2D,x=this._getRGBABufferInternalSizedFormat(o,l,h),T=this._getInternalFormat(l),S=this._getWebGLTextureType(o);return this._bindTextureDirectly(v,d),0!==m?(d.is2DArray=!0,u.texImage3D(v,0,x,p,f,m,0,T,S,null)):0!==_?(d.is3D=!0,u.texImage3D(v,0,x,p,f,_,0,T,S,null)):u.texImage2D(v,0,x,p,f,0,T,S,null),u.texParameteri(v,u.TEXTURE_MAG_FILTER,g.mag),u.texParameteri(v,u.TEXTURE_MIN_FILTER,g.min),u.texParameteri(v,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(v,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(v),this._bindTextureDirectly(v,null),d._useSRGBBuffer=h,d.baseWidth=p,d.baseHeight=f,d.width=p,d.height=f,d.depth=m,d.isReady=!0,d.samples=c,d.generateMipMaps=n,d.samplingMode=a,d.type=o,d.format=l,d.label=r,this._internalTexturesCache.push(d),d}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,p,f){return this._createTextureBase(e,t,i,s,r,n,o,((...e)=>this._prepareWebGLTexture(...e,h)),((e,t,i,r,n,o)=>{const a=this._gl,l=i.width===e&&i.height===t;n._creationFlags=p??0;const h=this._getTexImageParametersForCreateTexture(n.format,n._useSRGBBuffer);if(l)return a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,i),!1;const c=this._caps.maxTextureSize;if(i.width>c||i.height>c||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!(!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,this._workingCanvas),n.width=e,n.height=t,1));{const e=new ti(this,ei.Temp);this._bindTextureDirectly(a.TEXTURE_2D,e,!0),a.texImage2D(a.TEXTURE_2D,0,h.internalFormat,h.format,h.type,i),this._rescaleTexture(e,n,s,h.format,(()=>{this._releaseTexture(e),this._bindTextureDirectly(a.TEXTURE_2D,n,!0),o()}))}return!0}),a,l,h,c,u,d,f)}_getTexImageParametersForCreateTexture(e,t){let i,s;return 1===this.webGLVersion?(i=this._getInternalFormat(e,t),s=i):(i=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(0,e,t)),{internalFormat:s,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,s,r){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){const s=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(s,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(s,this._gl.TEXTURE_MIN_FILTER,r.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(s)),this._bindTextureDirectly(s,null),t.samplingMode=e}updateTextureDimensions(e,t,i,s=1){}updateTextureWrappingMode(e,t,i=null,s=null){const r=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==s&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(s),e),e._cachedWrapR=s),this._bindTextureDirectly(r,null)}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){const a=this._gl;let l=a.TEXTURE_2D;if(e.isCube&&(l=a.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=a.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(l,o,t,i,s,0,r)}_uploadDataToTextureDirectly(e,t,i=0,s=0,r,n=!1){const o=this._gl,a=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=void 0===r?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=o.TEXTURE_2D;e.isCube&&(c=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);const u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),p=n?e.width:Math.pow(2,Math.max(u-s,0)),f=n?e.height:Math.pow(2,Math.max(d-s,0));o.texImage2D(c,s,h,p,f,0,l,a,t)}updateTextureData(e,t,i,s,r,n,o=0,a=0,l=!1){const h=this._gl,c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,p=h.TEXTURE_2D;e.isCube&&(p=h.TEXTURE_CUBE_MAP_POSITIVE_X+o,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(p,a,i,s,r,n,u,c,t),l&&this._gl.generateMipmap(p),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){const r=this._gl,n=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,s),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,s,r){const n=this._gl;if(!n)return;const o=this._getSamplingParameters(r,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,o.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,o.min),i||s||n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,s,r,n,o,a,l,h){const c=this.getCaps().maxTextureSize,u=Math.min(c,this.needPOTTextures?Ri(s.width,c):s.width),d=Math.min(c,this.needPOTTextures?Ri(s.height,c):s.height),p=this._gl;p&&(e._hardwareTexture?(this._bindTextureDirectly(p.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),e.baseWidth=s.width,e.baseHeight=s.height,e.width=u,e.height=d,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:h??(".jpg"!==t||e._useSRGBBuffer?5:4),a(u,d,s,t,e,(()=>{this._prepareWebGLTextureContinuation(e,i,n,o,l)}))||this._prepareWebGLTextureContinuation(e,i,n,o,l)):i&&i.removePendingData(e))}_setupFramebufferDepthAttachments(e,t,i,s,r=1){const n=this._gl;if(e&&t)return this._createRenderBuffer(i,s,r,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let e=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=n.DEPTH_COMPONENT32F),this._createRenderBuffer(i,s,r,e,e,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,s,r,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,s,r,n,o=!0){const a=this._gl.createRenderbuffer();return this._updateRenderBuffer(a,e,t,i,s,r,n,o)}_updateRenderBuffer(e,t,i,s,r,n,o,a=!0){const l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),s>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,s,n,t,i):l.renderbufferStorage(l.RENDERBUFFER,r,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,o,l.RENDERBUFFER,e),a&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture?.underlyingResource),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);-1!==t&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(function(e,t){t.useProgram(e)}(e,this._gl),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t-1;if(i&&n&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||s){if(this._activateCurrentTexture(),t&&t.isMultiview)throw J.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,t?._hardwareTexture?.underlyingResource??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(r=!0,this._activateCurrentTexture());return n&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),r}_bindTexture(e,t,i){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;const s=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(s,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){const i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,s=!1,r=""){if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;const i=t.getInternalTexture();i&&(i._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;n=s?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&n&&(n._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),o=!1),this._activeChannel=e;const a=this._getTextureTarget(n);if(o&&this._bindTextureDirectly(a,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(a,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(a,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,s){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){var e;super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},We()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&this._gl.getExtension("WEBGL_lose_context")?.loseContext(),e=this._gl,Bt.delete(e)}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0;const s=t.createTexture();t.bindTexture(t.TEXTURE_2D,s),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,s,0);const n=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&n===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);const e=t.RGBA,s=t.UNSIGNED_BYTE,r=new Uint8Array(4);t.readPixels(0,0,1,1,e,s,r),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(s),t.deleteFramebuffer(r),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:i=this._gl.RED;break;case 7:i=this._gl.RG;break;case 4:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,s,r=!0,n=!0){const o=r?4:3,a=r?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(s*i*o);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,s,a,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{const e=si._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{const e=si._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}}Yi._TempClearColorUint32=new Uint32Array(4),Yi._TempClearColorInt32=new Int32Array(4),Yi.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],Yi.CollisionsEpsilon=.001,Yi._ConcatenateShader=dt,Yi._IsSupported=null,Yi._HasMajorPerformanceCaveat=null,Yi.CeilingPOT=yi,Yi.FloorPOT=Ai,Yi.NearestPOT=Ci,Yi.GetExponentOfTwo=Ri,Yi.QueueNewFrame=ii,Yi.prototype.createUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create uniform buffer");const s=new Wi(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},Yi.prototype.createDynamicUniformBuffer=function(e,t){const i=this._gl.createBuffer();if(!i)throw new Error("Unable to create dynamic uniform buffer");const s=new Wi(i);return this.bindUniformBuffer(s),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),s.references=1,s},Yi.prototype.updateUniformBuffer=function(e,t,i,s){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===s?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+s)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+s)),this.bindUniformBuffer(null)},Yi.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},Yi.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},Yi.prototype.bindUniformBlock=function(e,t,i){const s=e.program,r=this._gl.getUniformBlockIndex(s,t);4294967295!==r&&this._gl.uniformBlockBinding(s,r,i)};class ji{constructor(e,t,i,s,r=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,this._dynamic=i,this._name=s??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){const e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const i=this._uniformLocationPointer-e;for(let e=0;e0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:i},16==t?t*=i:t=t*i+(4-t)*i,s=[];for(let e=0;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(ji._UpdatedUbosInFrame[this._name]||(ji._UpdatedUbosInFrame[this._name]=0),ji._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.trackUbosInFrame;else this.create()}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let s=this._uniformLocations[e];if(void 0===s){if(this._buffer)return void J.Error("Cannot add an uniform after UBO has been created. uniformName="+e);this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e0)return void(this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label));J.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,s=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,s?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),this._data=0===t&&void 0===i?e:null)}_increaseReferences(){this._buffer&&(this._isAlreadyOwned?this._buffer.references++:this._isAlreadyOwned=!0)}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class Ki{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,s,r,n,o,a,l,h,c=!1,u=!1,d=1,p=!1){this._isDisposed=!1;let f=!1;if(this.engine=e,"object"==typeof s&&null!==s?(f=s.updatable??!1,r=s.postponeInternalCreation,n=s.stride,o=s.instanced,a=s.offset,l=s.size,h=s.type,c=s.normalized??!1,u=s.useBytes??!1,d=s.divisor??1,p=s.takeBufferOwnership??!1,this._label=s.label):f=!!s,t instanceof $i?(this._buffer=t,this._ownsBuffer=p):(this._buffer=new $i(e,t,f,n,r,o,u,d,this._label),this._ownsBuffer=!0),this.uniqueId=Ki._Counter++,this._kind=i,void 0===h){const e=this.getData();this.type=e?Ki.GetDataType(e):Ki.FLOAT}else this.type=h;const _=Ki.GetTypeByteLength(this.type);u?(this._size=l||(n?n/_:Ki.DeduceStride(i)),this.byteStride=n||this._buffer.byteStride||this._size*_,this.byteOffset=a||0):(this._size=l||n||Ki.DeduceStride(i),this.byteStride=n?n*_:this._buffer.byteStride||this._size*_,this.byteOffset=(a||0)*_),this.normalized=c,this._instanced=void 0!==o&&o,this._instanceDivisor=o?d:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120|0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){this._buffer?._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();return i?Ki.GetFloatData(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Ki.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/Ki.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*Ki.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){Ki.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case Ki.UVKind:case Ki.UV2Kind:case Ki.UV3Kind:case Ki.UV4Kind:case Ki.UV5Kind:case Ki.UV6Kind:return 2;case Ki.NormalKind:case Ki.PositionKind:return 3;case Ki.ColorKind:case Ki.ColorInstanceKind:case Ki.MatricesIndicesKind:case Ki.MatricesIndicesExtraKind:case Ki.MatricesWeightsKind:case Ki.MatricesWeightsExtraKind:case Ki.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?Ki.BYTE:e instanceof Uint8Array?Ki.UNSIGNED_BYTE:e instanceof Int16Array?Ki.SHORT:e instanceof Uint16Array?Ki.UNSIGNED_SHORT:e instanceof Int32Array?Ki.INT:e instanceof Uint32Array?Ki.UNSIGNED_INT:Ki.FLOAT}static GetTypeByteLength(e){switch(e){case Ki.BYTE:case Ki.UNSIGNED_BYTE:return 1;case Ki.SHORT:case Ki.UNSIGNED_SHORT:return 2;case Ki.INT:case Ki.UNSIGNED_INT:case Ki.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,s,r,n,o,a){if(e instanceof Array){let r=t/4;const o=i/4;for(let t=0;to[t]=e)),o}if(!(e instanceof Array||e instanceof Float32Array)||0!==s||e.length!==h){if(e instanceof Array){const t=s/4;return e.slice(t,t+h)}if(e instanceof ArrayBuffer)return new Float32Array(e,s,h);{let t=e.byteOffset+s;if(a){const i=new Float32Array(h),s=new Float32Array(e.buffer,t,h);return i.set(s),i}const i=t%4;return i&&(t=Math.max(0,t-i)),new Float32Array(e.buffer,t,h)}}return a?e.slice():e}}Ki._Counter=0,Ki.BYTE=5120,Ki.UNSIGNED_BYTE=5121,Ki.SHORT=5122,Ki.UNSIGNED_SHORT=5123,Ki.INT=5124,Ki.UNSIGNED_INT=5125,Ki.FLOAT=5126,Ki.PositionKind="position",Ki.NormalKind="normal",Ki.TangentKind="tangent",Ki.UVKind="uv",Ki.UV2Kind="uv2",Ki.UV3Kind="uv3",Ki.UV4Kind="uv4",Ki.UV5Kind="uv5",Ki.UV6Kind="uv6",Ki.ColorKind="color",Ki.ColorInstanceKind="instanceColor",Ki.MatricesIndicesKind="matricesIndices",Ki.MatricesWeightsKind="matricesWeights",Ki.MatricesIndicesExtraKind="matricesIndicesExtra",Ki.MatricesWeightsExtraKind="matricesWeightsExtra";class qi{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(Ki.NormalKind))return null;let i,s=this.pickedMesh.getIndices();0===s?.length&&(s=null);const r=U.Vector3[0],n=U.Vector3[1],o=U.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(Ki.NormalKind);let t=s?w.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),a=s?w.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=s?w.FromArrayToRef(e,3*s[3*this.faceId+2],o):o.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]);t=t.scale(this.bu),a=a.scale(this.bv),l=l.scale(1-this.bu-this.bv),i=new w(t.x+a.x+l.x,t.y+a.y+l.y,t.z+a.z+l.z)}else{const e=this.pickedMesh.getVerticesData(Ki.PositionKind),t=s?w.FromArrayToRef(e,3*s[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),a=s?w.FromArrayToRef(e,3*s[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),l=s?w.FromArrayToRef(e,3*s[3*this.faceId+2],o):o.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),h=t.subtract(a),c=l.subtract(a);i=w.Cross(h,c)}const a=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(U.Matrix[0].copyFrom(i),i=U.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(U.Matrix[1]),i=U.Matrix[1]),w.TransformNormalToRef(t,i,t)};if(e&&a(this.pickedMesh,i),this.ray){const t=U.Vector3[0].copyFrom(i);e||a(this.pickedMesh,t),w.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=Ki.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const i=this.pickedMesh.getVerticesData(e);if(!i)return null;let s=N.FromArray(i,2*t[3*this.faceId]),r=N.FromArray(i,2*t[3*this.faceId+1]),n=N.FromArray(i,2*t[3*this.faceId+2]);return s=s.scale(this.bu),r=r.scale(this.bv),n=n.scale(1-this.bu-this.bv),new N(s.x+r.x+n.x,s.y+r.y+n.y)}}class Qi{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[Ki.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[Ki.PositionKind]=new Ki(this._scene.getEngine(),e,Ki.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}_rebuild(){const e=this._vertexBuffers[Ki.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const i=this._scene.activeCamera;return!(!i||!(t=t||i._postProcesses.filter((e=>null!=e)))||0===t.length||!this._scene.postProcessesEnabled||(t[0].activate(i,e,null!=t),0))}directRender(e,t=null,i=!1,s=0,r=0,n=!1){const o=this._scene.getEngine();for(let a=0;anull!=e))).length||!this._scene.postProcessesEnabled)return;const o=this._scene.getEngine();for(let a=0,l=s.length;at._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),s=t.getMesh();return i.material&&s.material?i.material.uniqueId-s.material.uniqueId:i.uniqueId-s.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t.isEnabled()&&t.isVisible&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(0===this._particleSystems.length)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i=us.LeftClick&&i<=us.RightClick&&(a.type=1===s?"pointerdown":"pointerup",a.button=i-2),a}static _CreateWheelEvent(e,t,i,s,r,n){const o=this._CreateMouseEvent(e,t,i,s,r,n);switch(o.pointerId=1,o.type="wheel",o.deltaMode=vs.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case us.MouseWheelX:o.deltaX=s;break;case us.MouseWheelY:o.deltaY=s;break;case us.MouseWheelZ:o.deltaZ=s}return o}static _CreateMouseEvent(e,t,i,s,r,n){const o=this._CreateEvent(n),a=r.pollInput(e,t,us.Horizontal),l=r.pollInput(e,t,us.Vertical);return n?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-n.getBoundingClientRect().x,o.offsetY=o.movementY-n.getBoundingClientRect().y):(o.movementX=r.pollInput(e,t,ds.DeltaHorizontal),o.movementY=r.pollInput(e,t,ds.DeltaVertical),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,r),o.clientX=a,o.clientY=l,o.x=a,o.y=l,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=cs.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=1===t?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const i=t.isDeviceAvailable(cs.Keyboard),s=i&&1===t.pollInput(cs.Keyboard,0,18),r=i&&1===t.pollInput(cs.Keyboard,0,17),n=i&&(1===t.pollInput(cs.Keyboard,0,91)||1===t.pollInput(cs.Keyboard,0,92)||1===t.pollInput(cs.Keyboard,0,93)),o=i&&1===t.pollInput(cs.Keyboard,0,16);e.altKey=s,e.ctrlKey=r,e.metaKey=n,e.shiftKey=o}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class Ts{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,s,r)=>{const n=xs.CreateDeviceEvent(e,t,s,r,this);i(e,t,n)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===cs.Mouse||e===cs.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const Ss=Object.keys(us).length/2;class Es{constructor(e,t,i,s){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Ii.IsSafari(),this._usingMacOS=He()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=e=>{},this._keyboardUpEvent=e=>{},this._keyboardBlurEvent=e=>{},this._pointerMoveEvent=e=>{},this._pointerDownEvent=e=>{},this._pointerUpEvent=e=>{},this._pointerCancelEvent=e=>{},this._pointerWheelEvent=e=>{},this._pointerBlurEvent=e=>{},this._pointerMacOSChromeOutEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=He()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=He()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=Ii.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=s,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){const s=this._inputs[e][t];if(!s)throw`Unable to find device ${cs[e]}`;e>=cs.DualShock&&e<=cs.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(void 0===r)throw`Unable to find input ${i} for device ${cs[e]} in slot ${t}`;return i===us.Move&&Ii.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this?._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(const e of this._inputs)if(e)for(const t in e){const i=e[+t];if(i)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(cs.Keyboard,0,255));const t=this._inputs[cs.Keyboard][0];if(t){t[e.keyCode]=1;const i=e;i.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(cs.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(cs.Keyboard,0,255));const t=this._inputs[cs.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const i=xs.CreateDeviceEvent(cs.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(cs.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(cs.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[cs.Keyboard][0];for(let t=0;t{const t=this._getPointerType(e);let i=t===cs.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===cs.Touch&&-1===i){const s=this._activeTouchIds.indexOf(-1);if(!(s>=0))return void Ii.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=s,this._activeTouchIds[s]=e.pointerId,this._onDeviceConnected(t,i)}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=e;r.inputIndex=us.Move,s[us.Horizontal]=e.clientX,s[us.Vertical]=e.clientY,t===cs.Touch&&0===s[us.LeftClick]&&(s[us.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,r),this._usingSafari||-1===e.button||(r.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,r))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===cs.Mouse?0:e.pointerId;if(t===cs.Touch){let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t&&(t=this._activeTouchIds.indexOf(-1)),!(t>=0))return void Ii.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);i=t,this._activeTouchIds[t]=e.pointerId}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===cs.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=s[us.Horizontal],n=s[us.Vertical];if(t===cs.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}s[us.Horizontal]=e.clientX,s[us.Vertical]=e.clientY,s[e.button+2]=1;const o=e;o.inputIndex=e.button+2,this._onInputChanged(t,i,o),r===e.clientX&&n===e.clientY||(o.inputIndex=us.Move,this._onInputChanged(t,i,o))}},this._pointerUpEvent=e=>{const t=this._getPointerType(e),i=t===cs.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===cs.Touch){if(-1===i)return;this._activeTouchIds[i]=-1}const s=this._inputs[t]?.[i];if(s&&0!==s[e.button+2]){const r=s[us.Horizontal],n=s[us.Vertical];s[us.Horizontal]=e.clientX,s[us.Vertical]=e.clientY,s[e.button+2]=0;const o=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),r===e.clientX&&n===e.clientY||(o.inputIndex=us.Move,this._onInputChanged(t,i,o)),o.inputIndex=e.button+2,t===cs.Mouse&&this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(t,i,o),t===cs.Touch&&this._onDeviceDisconnected(t,i)}},this._pointerCancelEvent=e=>{if("mouse"===e.pointerType){const e=this._inputs[cs.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=us.LeftClick;t<=us.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=xs.CreateDeviceEvent(cs.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(cs.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[cs.Touch][t][us.LeftClick]=0;const i=xs.CreateDeviceEvent(cs.Touch,t,us.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(cs.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(cs.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1;const t=function(){};try{const i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch(e){}this._pointerBlurEvent=()=>{if(this.isDeviceAvailable(cs.Mouse)){const e=this._inputs[cs.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=us.LeftClick;t<=us.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=xs.CreateDeviceEvent(cs.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(cs.Mouse,0,i)}}if(this.isDeviceAvailable(cs.Touch)){const e=this._inputs[cs.Touch];for(let t=0;t{const t=cs.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,Ss));const i=this._inputs[t][0];if(i){i[us.MouseWheelX]=e.deltaX||0,i[us.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[us.MouseWheelZ]=e.deltaZ||0;const s=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[us.MouseWheelX]&&(s.inputIndex=us.MouseWheelX,this._onInputChanged(t,0,s)),0!==i[us.MouseWheelY]&&(s.inputIndex=us.MouseWheelY,this._onInputChanged(t,0,s)),0!==i[us.MouseWheelZ]&&(s.inputIndex=us.MouseWheelZ,this._onInputChanged(t,0,s))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=e=>{e.buttons>1&&this._pointerCancelEvent(e)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,!!e&&{passive:!1}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add((()=>{if(this.isDeviceAvailable(cs.Mouse)){const e=this._inputs[cs.Mouse][0];e[us.MouseWheelX]=0,e[us.MouseWheelY]=0,e[us.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const s=navigator.getGamepads()[t];if(s&&e===this._gamepads[t]){const r=this._inputs[e][t];i>=s.buttons.length?r[i]=s.axes[i-s.buttons.length].valueOf():r[i]=s.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?cs.DualSense:cs.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?cs.Xbox:-1!==e.indexOf("057e")?cs.Switch:cs.Generic}_getPointerType(e){let t=cs.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=cs.Touch),t}}class bs{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new g,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class Cs{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(cs).length/2;this._devices=new Array(t);const i=(e,t)=>{this._devices[e]||(this._devices[e]=new Array),this._devices[e][t]||(this._devices[e][t]=t);for(const i of this._registeredManagers){const s=new bs(this._deviceInputSystem,e,t);i._addDevice(s)}},s=(e,t)=>{this._devices[e]?.[t]&&delete this._devices[e][t];for(const i of this._registeredManagers)i._removeDevice(e,t)},r=(e,t,i)=>{if(i)for(const s of this._registeredManagers)s._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new Ts(i,s,r):this._deviceInputSystem=new Es(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class ys{getDeviceSource(e,t){if(void 0===t){if(void 0===this._firstDevice[e])return null;t=this._firstDevice[e]}return this._devices[e]&&void 0!==this._devices[e][t]?this._devices[e][t]:null}getDeviceSources(e){return this._devices[e]?this._devices[e].filter((e=>!!e)):[]}constructor(e){const t=Object.keys(cs).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new Cs(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new g((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new g,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){const i=this._devices[e]?.[t];this.onDeviceDisconnectedObservable.notifyObservers(i),this._devices[e]?.[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){this._devices[e]?.[t]?.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case cs.Keyboard:case cs.Mouse:this._firstDevice[e]=0;break;case cs.Touch:case cs.DualSense:case cs.DualShock:case cs.Xbox:case cs.Switch:case cs.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i=us.MouseWheelX&&t.inputIndex<=us.MouseWheelZ?ss.POINTERWHEEL:ss.POINTERMOVE;let o;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,n)),e?(o=new os(n,t,e),this._setRayOnPointerInfo(e,t)):(o=new os(n,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,n)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,B.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const s=this._scene,r=new ns(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,"xr-near"===t.pointerType&&e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const s=i.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(s.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const i=new PointerEvent("pointermove",t);i.inputIndex=us.Move,this._checkPrePointerObservable(e,i,ss.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,ss.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const s=e.pickedMesh._getActionManagerForTrigger();if(s){if(s.hasPickTriggers)switch(s.processTrigger(5,q.CreateNew(e.pickedMesh,t,e)),t.button){case 0:s.processTrigger(2,q.CreateNew(e.pickedMesh,t,e));break;case 1:s.processTrigger(4,q.CreateNew(e.pickedMesh,t,e));break;case 2:s.processTrigger(3,q.CreateNew(e.pickedMesh,t,e))}s.hasSpecificTrigger(8)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);e?.pickedMesh&&s&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>Rs.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,s.processTrigger(8,q.CreateNew(e.pickedMesh,t)))}),Rs.LongPressDelay)}}else for(const s of i._pointerDownStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=ss.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new os(r,t,e),this._setRayOnPointerInfo(e,t)):s=new os(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=us.Move;const r=new As;i?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,s,ss.POINTERUP)||this._processPointerUp(e,s,r)}_processPointerUp(e,t,i){const s=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){const i=ss.POINTERPICK,r=new os(i,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,i)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,q.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,q.CreateNew(e.pickedMesh,t,e));const s=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&s&&s.processTrigger(6,q.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,q.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new os(ss.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,ss.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,ss.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(i.singleClick?r=ss.POINTERTAP:i.doubleClick&&(r=ss.POINTERDOUBLETAP),r){const i=new os(r,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(r)&&s.onPointerObservable.notifyObservers(i,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,s=null){const r=this._scene,n=r.getEngine();s||(s=n.getInputElement()),this._alreadyAttached&&this.detachControl(),s&&(this._alreadyAttachedTo=s),this._deviceSourceManager=new ys(n),this._initActionManager=e=>{if(!this._meshPickProceed){const t=r.skipPointerUpPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers,r.pointerUpTrianglePredicate);this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>Rs.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){const t=this._delayedClicks[e].evt,i=ss.POINTERTAP,s=new os(i,t,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(i)&&r.onPointerObservable.notifyObservers(s,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,s)=>{const r=new As;this._currentPickResult=null;let n=null,o=e.hasSpecificMask(ss.POINTERPICK)||t.hasSpecificMask(ss.POINTERPICK)||e.hasSpecificMask(ss.POINTERTAP)||t.hasSpecificMask(ss.POINTERTAP)||e.hasSpecificMask(ss.POINTERDOUBLETAP)||t.hasSpecificMask(ss.POINTERDOUBLETAP);!o&&f&&(n=this._initActionManager(n,r),n&&(o=n.hasPickTriggers));let a=!1;if(o){const o=i.button;if(r.hasSwiped=this._isPointerSwiping(),!r.hasSwiped){let l=!Rs.ExclusiveDoubleClickMode;if(l||(l=!e.hasSpecificMask(ss.POINTERDOUBLETAP)&&!t.hasSpecificMask(ss.POINTERDOUBLETAP),l&&!f.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(l=!n.hasSpecificTrigger(6)))),l)(Date.now()-this._previousStartingPointerTime>Rs.DoubleClickDelay||o!==this._previousButtonPressed)&&(r.singleClick=!0,s(r,this._currentPickResult),a=!0);else{const e={evt:i,clickInfo:r,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,o,r,s),Rs.DoubleClickDelay)};this._delayedClicks[o]=e}let h=e.hasSpecificMask(ss.POINTERDOUBLETAP)||t.hasSpecificMask(ss.POINTERDOUBLETAP);!h&&f.HasSpecificTrigger(6)&&(n=this._initActionManager(n,r),n&&(h=n.hasSpecificTrigger(6))),h&&(o===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>Rs.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>Rs.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=us.MouseWheelX&&e.inputIndex<=us.MouseWheelZ?ss.POINTERWHEEL:ss.POINTERMOVE))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking)return void this._processPointerMove(new qi,e);r.pointerMovePredicate||(r.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask)));const t=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,Rs.ExclusiveDoubleClickMode)for(let t=0;te.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,t=r.skipPointerDownPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerDown?new qi:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers,r.pointerDownTrianglePredicate),this._processPointerDown(t,e)},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),r.preventDefaultOnPointerUp&&s&&(e.preventDefault(),s.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,e,((t,i)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,ss.POINTERUP))return this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),void(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1));t.hasSwiped||(t.singleClick&&r.onPrePointerObservable.hasSpecificMask(ss.POINTERTAP)&&this._checkPrePointerObservable(null,e,ss.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&r.onPrePointerObservable.hasSpecificMask(ss.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,ss.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(r.cameraToUseForPointers||r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(f&&f.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))):this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1)})))},this._onKeyDown=e=>{const t=as.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const i=new hs(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new ls(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(14,q.CreateNewFromScene(r,e))},this._onKeyUp=e=>{const t=as.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const i=new hs(t,e);if(r.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const i=new ls(t,e);r.onKeyboardObservable.notifyObservers(i,t)}r.actionManager&&r.actionManager.processTrigger(15,q.CreateNewFromScene(r,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((s=>{s.deviceType===cs.Mouse?s.onInputChangedObservable.add((r=>{this._originMouseEvent=r,r.inputIndex===us.LeftClick||r.inputIndex===us.MiddleClick||r.inputIndex===us.RightClick||r.inputIndex===us.BrowserBack||r.inputIndex===us.BrowserForward?t&&1===s.getInput(r.inputIndex)?this._onPointerDown(r):e&&0===s.getInput(r.inputIndex)&&this._onPointerUp(r):i&&(r.inputIndex===us.Move?this._onPointerMove(r):r.inputIndex!==us.MouseWheelX&&r.inputIndex!==us.MouseWheelY&&r.inputIndex!==us.MouseWheelZ||this._onPointerMove(r))})):s.deviceType===cs.Touch?s.onInputChangedObservable.add((r=>{r.inputIndex===us.LeftClick&&(t&&1===s.getInput(r.inputIndex)?(this._onPointerDown(r),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===s.getInput(r.inputIndex)&&(this._onPointerUp(r),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&r.inputIndex===us.Move&&this._onPointerMove(r)})):s.deviceType===cs.Keyboard&&s.onInputChangedObservable.add((e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)}))})),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,s){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const r=this._meshUnderPointerId[t];let n;r&&(n=r._getActionManagerForTrigger(10),n&&n.processTrigger(10,q.CreateNew(r,s,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(9),n&&n.processTrigger(9,q.CreateNew(e,s,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(const t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}Rs.DragMovementThreshold=10,Rs.LongPressDelay=500,Rs.DoubleClickDelay=300,Rs.ExclusiveDoubleClickMode=!1;class Is{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){Is.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){Is.Enabled&&(this._startMonitoringTime=je.Now)}endMonitoring(e=!0){if(!Is.Enabled)return;e&&this.fetchNewFrame();const t=je.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;const e=je.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}Is.Enabled=!0;class Ps{constructor(e,t,i,s){this.normal=new w(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new Ps(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^this.d,e}normalize(){const e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z);let t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=Ps._TmpMatrix;e.invertToRef(t);const i=t.m,s=this.normal.x,r=this.normal.y,n=this.normal.z,o=this.d,a=s*i[0]+r*i[1]+n*i[2]+o*i[3],l=s*i[4]+r*i[5]+n*i[6]+o*i[7],h=s*i[8]+r*i[9]+n*i[10]+o*i[11],c=s*i[12]+r*i[13]+n*i[14]+o*i[15];return new Ps(a,l,h,c)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const s=t.x-e.x,r=t.y-e.y,n=t.z-e.z,o=i.x-e.x,a=i.y-e.y,l=i.z-e.z,h=r*l-n*a,c=n*o-s*l,u=s*a-r*o,d=Math.sqrt(h*h+c*c+u*u);let p;return p=0!==d?1/d:0,this.normal.x=h*p,this.normal.y=c*p,this.normal.z=u*p,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return w.Dot(this.normal,e)<=t}signedDistanceTo(e){return w.Dot(e,this.normal)+this.d}static FromArray(e){return new Ps(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const s=new Ps(0,0,0,0);return s.copyFromPoints(e,t,i),s}static FromPositionAndNormal(e,t){const i=new Ps(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return w.Dot(i,t)+s}}Ps._TmpMatrix=B.Identity();class Ms{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new Ps(0,0,0,0));return Ms.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){Ms.GetNearPlaneToRef(e,t[0]),Ms.GetFarPlaneToRef(e,t[1]),Ms.GetLeftPlaneToRef(e,t[2]),Ms.GetRightPlaneToRef(e,t[3]),Ms.GetTopPlaneToRef(e,t[4]),Ms.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}class Ds{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}Ds._UniqueIdCounter=1;class Os{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}Os.FALLOFF_DEFAULT=0,Os.FALLOFF_PHYSICAL=1,Os.FALLOFF_GLTF=2,Os.FALLOFF_STANDARD=3,Os.LIGHTMAP_DEFAULT=0,Os.LIGHTMAP_SPECULAR=1,Os.LIGHTMAP_SHADOWSONLY=2,Os.INTENSITYMODE_AUTOMATIC=0,Os.INTENSITYMODE_LUMINOUSPOWER=1,Os.INTENSITYMODE_LUMINOUSINTENSITY=2,Os.INTENSITYMODE_ILLUMINANCE=3,Os.INTENSITYMODE_LUMINANCE=4,Os.LIGHTTYPEID_POINTLIGHT=0,Os.LIGHTTYPEID_DIRECTIONALLIGHT=1,Os.LIGHTTYPEID_SPOTLIGHT=2,Os.LIGHTTYPEID_HEMISPHERICLIGHT=3;class Ns{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var ws,Fs,Ls,Bs,Vs,Us;!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(ws||(ws={}));class ks extends p{static DefaultMaterialFactory(e){throw ye("StandardMaterial")}static CollisionCoordinatorFactory(){throw ye("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case ws.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case ws.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case ws.Aggressive:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return Rs.DragMovementThreshold}static set DragMovementThreshold(e){Rs.DragMovementThreshold=e}static get LongPressDelay(){return Rs.LongPressDelay}static set LongPressDelay(e){Rs.LongPressDelay=e}static get DoubleClickDelay(){return Rs.DoubleClickDelay}static set DoubleClickDelay(e){Rs.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return Rs.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){Rs.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){const s=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return U.Vector4[0].set(s.x,s.y,s.z,r?-1:1),e&&(i?e.setFloat3(t,U.Vector4[0].x,U.Vector4[0].y,U.Vector4[0].z):e.setVector4(t,U.Vector4[0])),U.Vector4[0]}finalizeSceneUbo(){const e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=b(e,(()=>{this.onActiveCamerasChanged.notifyObservers(this)}))),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=ks.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=ks.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new Rs(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new j(.2,.2,.3,1),this.ambientColor=new Y(0,0,0),this.environmentIntensity=1,this._performancePriority=ws.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new g,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new g,this._onDisposeObserver=null,this.onBeforeRenderObservable=new g,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new g,this.onAfterRenderCameraObservable=new g,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new g,this.onAfterAnimationsObservable=new g,this.onBeforeDrawPhaseObservable=new g,this.onAfterDrawPhaseObservable=new g,this.onReadyObservable=new g,this.onBeforeCameraRenderObservable=new g,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new g,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new g,this.onAfterActiveMeshesEvaluationObservable=new g,this.onBeforeParticlesRenderingObservable=new g,this.onAfterParticlesRenderingObservable=new g,this.onDataLoadedObservable=new g,this.onNewCameraAddedObservable=new g,this.onCameraRemovedObservable=new g,this.onNewLightAddedObservable=new g,this.onLightRemovedObservable=new g,this.onNewGeometryAddedObservable=new g,this.onGeometryRemovedObservable=new g,this.onNewTransformNodeAddedObservable=new g,this.onTransformNodeRemovedObservable=new g,this.onNewMeshAddedObservable=new g,this.onMeshRemovedObservable=new g,this.onNewSkeletonAddedObservable=new g,this.onSkeletonRemovedObservable=new g,this.onNewMaterialAddedObservable=new g,this.onNewMultiMaterialAddedObservable=new g,this.onMaterialRemovedObservable=new g,this.onMultiMaterialRemovedObservable=new g,this.onNewTextureAddedObservable=new g,this.onTextureRemovedObservable=new g,this.onBeforeRenderTargetsRenderObservable=new g,this.onAfterRenderTargetsRenderObservable=new g,this.onBeforeStepObservable=new g,this.onAfterStepObservable=new g,this.onActiveCameraChanged=new g,this.onActiveCamerasChanged=new g,this.onBeforeRenderingGroupObservable=new g,this.onAfterRenderingGroupObservable=new g,this.onMeshImportedObservable=new g,this.onAnimationFileImportedObservable=new g,this._registeredForLateAnimationBindings=new Di(256),this._pointerPickingConfiguration=new Ns,this.onPrePointerObservable=new g,this.onPointerObservable=new g,this.onPreKeyboardObservable=new g,this.onKeyboardObservable=new g,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=ks.FOGMODE_NONE,this.fogColor=new Y(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new w(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new Di(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new Is,this._activeIndices=new Is,this._activeParticles=new Is,this._activeBones=new Is,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=new Array(256),this._activeRequests=new Array,this._pendingData=new Array,this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new Mi(256),this._processedMaterials=new Mi(256),this._renderTargets=new Di(256),this._materialsRenderTargets=new Di(256),this._activeParticleSystems=new Mi(256),this._activeSkeletons=new Di(32),this._softwareSkinnedMeshes=new Di(32),this._activeAnimatables=new Array,this._transformMatrix=B.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=is.Create(),this._beforeClearStage=is.Create(),this._beforeRenderTargetClearStage=is.Create(),this._gatherRenderTargetsStage=is.Create(),this._gatherActiveCameraRenderTargetsStage=is.Create(),this._isReadyForMeshStage=is.Create(),this._beforeEvaluateActiveMeshStage=is.Create(),this._evaluateSubMeshStage=is.Create(),this._preActiveMeshStage=is.Create(),this._cameraDrawRenderTargetStage=is.Create(),this._beforeCameraDrawStage=is.Create(),this._beforeRenderTargetDrawStage=is.Create(),this._beforeRenderingGroupDrawStage=is.Create(),this._beforeRenderingMeshStage=is.Create(),this._afterRenderingMeshStage=is.Create(),this._afterRenderingGroupDrawStage=is.Create(),this._afterCameraDrawStage=is.Create(),this._afterCameraPostProcessStage=is.Create(),this._afterRenderTargetDrawStage=is.Create(),this._afterRenderTargetPostProcessStage=is.Create(),this._afterRenderStage=is.Create(),this._pointerMoveStage=is.Create(),this._pointerDownStage=is.Create(),this._pointerUpStage=is.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];const i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};e=this._engine=e||y.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(y._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new es(this),Qi&&(this.postProcessManager=new Qi(this)),We()&&this.attachControl(),this._createUbo(),Bi&&(this._imageProcessingConfiguration=new Bi),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,t&&t.virtual||e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return void 0!==this._animationRatio?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){if(this._isDisposed)return!1;let t;const i=this.getEngine(),s=i.currentRenderPassId;i.currentRenderPassId=this.activeCamera?.renderPassId??s;let r=!0;for(this._pendingData.length>0&&(r=!1),this.prePassRenderer?.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&r&&(r=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(const e of this._isReadyForMeshStage)e.action(s,n)||(r=!1);if(!e)continue;const o=s.material||this.defaultMaterial;if(o)if(o._storeEffectOnSubMeshes)for(const e of s.subMeshes){const t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else o.hasRenderTargetTextures&&null!=o.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(o)&&(this._processedMaterials.push(o),this._materialsRenderTargets.concatWithNoDuplicate(o.getRenderTargetTextures()))}if(e)for(t=0;t0)for(const e of this.activeCameras)e.isReady(!0)||(r=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(r=!1));for(const e of this.particleSystems)e.isReady()||(r=!1);if(this.layers)for(const e of this.layers)e.isReady()||(r=!1);return i.areAllEffectsReady()||(r=!1),i.currentRenderPassId=s,r}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout((()=>{this.unregisterBeforeRender(t)}))};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){void 0!==t?setTimeout((()=>{this._executeOnceBeforeRender(e)}),t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){const t=this.isLoading,i=this._pendingData.indexOf(e);-1!==i&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise((t=>{this.executeWhenReady((()=>{t()}),e)}))}_checkIsReady(e=!1){return this._registerTransientComponents(),this.isReady(e)?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):void(this._executeWhenReadyTimeoutId=setTimeout((()=>{this.incrementRenderId(),this._checkIsReady(e)}),100))}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=je.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,s){i||s||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?Ms.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Ms.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,s):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new ji(this._engine,void 0,!1,e??"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return Ds.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.addMesh(e)})))}removeMesh(e,t=!1){const i=this.meshes.indexOf(e);return-1!==i&&(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.removeMesh(e)})),i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){const e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){const t=this.skeletons.indexOf(e);return-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(-1!==t){for(const t of this.meshes)t._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t}removeCamera(e){const t=this.cameras.indexOf(e);if(-1!==t&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){const t=this.particleSystems.indexOf(e);return-1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(-1!==t&&tt.uniqueId===e))}getMaterialById(e,t=!1){return this._getMaterial(t,(t=>t.id===e))}getMaterialByName(e,t=!1){return this._getMaterial(t,(t=>t.name===e))}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t)for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t];return null}getTextureByUniqueId(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const i=this.getTransformNodeById(e);if(i)return i;const s=this.getLightById(e);if(s)return s;const r=this.getCameraById(e);if(r)return r;return this.getBoneById(e)||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const i=this.getTransformNodeByName(e);if(i)return i;const s=this.getLightByName(e);if(s)return s;const r=this.getCameraByName(e);if(r)return r;return this.getBoneByName(e)||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(this.activeCamera){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,s)for(let e=0;ee.dispose()))}_evaluateActiveMeshes(){if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode)return void(this._activeMeshes.length>0&&(this.activeCamera?._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset()));if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const e=this._activeMeshes.length;for(let t=0;t0&&t.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||t.alwaysSelectAsActiveMesh||t.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(t),this.activeCamera._activeMeshes.push(t),s!==t&&s._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(t);t._activate(this._renderId,!1)&&(t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(s=t):s._internalAbstractMeshDataInfo._onlyForInstances=!1,s._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(t,s)),t._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e0){const s=this.getActiveSubMeshCandidates(t),r=s.length;i=i||1===r;for(let n=0;n0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const e of this._gatherActiveCameraRenderTargetsStage)e.action(this._renderTargets);let r=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Ii.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e0),this._renderId++}for(const e of this._cameraDrawRenderTargetStage)r=e.action(this.activeCamera)||r;this._intermediateRendering=!1}this._engine.currentRenderPassId=e.outputRenderTarget?.renderPassId??e.renderPassId??0,r&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame();for(const e of this._beforeCameraDrawStage)e.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),s.snapshotRendering&&1===s.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const e of this._afterCameraDrawStage)e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(const e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview)return e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t-1&&(13===i.trigger&&i._executeCurrent(q.CreateNew(t,void 0,s)),t.actionManager.hasSpecificTrigger(13,(e=>{const t=e.mesh?e.mesh:e;return s===t}))&&13!==i.trigger||t._intersectionsInProgress.splice(n,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(ks.MinDeltaTime,Math.min(this._engine.getDeltaTime(),ks.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),i=1e3/t/1e3;let s=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&s0)for(let e=0;e0),this._intermediateRendering=!0;for(let e=0;e0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=s?.renderPassId??0,this.activeCamera=s,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const e of this._beforeClearStage)e.action();this._clearFrameBuffer(this.activeCamera);for(const e of this._gatherRenderTargetsStage)e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const e of this._afterRenderStage)e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e{e.onAnimationEndObservable.clear(),e.onAnimationEnd=null})),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;const e=this._activeRequests.slice();for(const t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){J.Error("An error occurred while calling onDisposeObservable!",e)}if(this.detachControl(),this._engine.getInputElement())for(let e=0;ee.dispose(!0))),this._disposeList(this.transformNodes,(e=>e.dispose(!0)));const t=this.cameras;this._disposeList(t),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),y._LastCreatedScene===this&&(this._engine.scenes.length>0?y._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:y._LastCreatedScene=null),i=this._engine._virtualScenes.indexOf(this),i>-1&&this._engine._virtualScenes.splice(i,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const i=e.slice(0);t=t??(e=>e.dispose());for(const e of i)t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach((e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;const s=e.getBoundingInfo(),r=s.boundingBox.minimumWorld,n=s.boundingBox.maximumWorld;w.CheckExtends(r,t,i),w.CheckExtends(n,t,i)})),{min:t,max:i}}createPickingRay(e,t,i,s,r=!1){throw ye("Ray")}createPickingRayToRef(e,t,i,s,r,n=!1,o=!1){throw ye("Ray")}createPickingRayInCameraSpace(e,t,i){throw ye("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,s){throw ye("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,s,r,n){const o=ye("Ray",!0);return o&&J.Warn(o),new qi}pickWithBoundingInfo(e,t,i,s,r){const n=ye("Ray",!0);return n&&J.Warn(n),new qi}pickWithRay(e,t,i,s){throw ye("Ray")}multiPick(e,t,i,s,r){throw ye("Ray")}multiPickWithRay(e,t,i){throw ye("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(void 0===t)return e;const s=[];for(const r in e){const n=e[r];Re&&Re.MatchesQuery(n,t)&&(!i||i(n))&&s.push(n)}return s}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t,i=!0,s=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,s)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,s,r,n,o){const a=di(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_loadFileAsync(e,t,i,s,r){return new Promise(((n,o)=>{this._loadFile(e,(e=>{n(e)}),t,i,s,((e,t)=>{o(t)}),r)}))}_requestFile(e,t,i,s,r,n,o){const a=pi(e,t,i,s?this.offlineProvider:void 0,r,n,o);return this._activeRequests.push(a),a.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),a}_requestFileAsync(e,t,i,s,r){return new Promise(((n,o)=>{this._requestFile(e,(e=>{n(e)}),t,i,s,(e=>{o(e)}),r)}))}_readFile(e,t,i,s,r){const n=ui(e,t,i,s,r);return this._activeRequests.push(n),n.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),n}_readFileAsync(e,t,i){return new Promise(((s,r)=>{this._readFile(e,(e=>{s(e)}),t,i,(e=>{r(e)}))}))}getPerfCollector(){throw ye("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}ks.FOGMODE_NONE=0,ks.FOGMODE_EXP=1,ks.FOGMODE_EXP2=2,ks.FOGMODE_LINEAR=3,ks.MinDeltaTime=1,ks.MaxDeltaTime=1e3,u("BABYLON.Scene",ks),(Us=Fs||(Fs={}))[Us.LOCAL=0]="LOCAL",Us[Us.WORLD=1]="WORLD",Us[Us.BONE=2]="BONE";class Gs{}Gs.X=new w(1,0,0),Gs.Y=new w(0,1,0),Gs.Z=new w(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Ls||(Ls={}));class zs extends De{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){(e.updateFlag!==this._localMatrix.updateFlag||this._needToCompose)&&(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,s=null,r=null,n=null,o=null){super(e,t.getScene(),!1),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=s?.clone()??B.Identity(),this._restMatrix=r??this._localMatrix.clone(),this._bindMatrix=n??this._localMatrix.clone(),this._index=o,this._absoluteMatrix=new B,this._absoluteBindMatrix=new B,this._absoluteInverseBindMatrix=new B,this._finalMatrix=new B,t.bones.push(this),this.setParent(i,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return null===this._index?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){const e=this.parent.children.indexOf(this);-1!==e&&this.parent.children.splice(e,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){if(this._linkedTransformNode){const e=U.Vector3[0],t=U.Quaternion[0],i=U.Vector3[1];this.getRestMatrix().decompose(e,t,i),this._linkedTransformNode.position.copyFrom(i),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??L.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(t),this._linkedTransformNode.scaling.copyFrom(e)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._absoluteMatrix}getAbsoluteTransform(){return this._absoluteMatrix}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=w.Zero(),this._localRotation=L.Zero(),this._localPosition=w.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,B.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let e=0;e-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(r)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const r=this._runtimeAnimations;for(let i=r.length-1;i>=0;i--){const s=r[i];e&&s.animation.name!=e||t&&!t(s.target)||(s.dispose(),r.splice(i,1))}0==r.length&&(i||this._scene._activeAnimatables.splice(s,1),this._raiseOnAnimationEnd())}}else{const e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);const t=this._runtimeAnimations;for(let e=0;e{this.onAnimationEndObservable.add((()=>{e(this)}),void 0,void 0,this,!0)}))}_animate(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),null!==this._manualJumpDelay&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,0===this._weight)return!0;let t=!1;const i=this._runtimeAnimations;let s;for(s=0;s0)return;this._animationTimeLast=t}this.deltaTime=void 0!==e?e:this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=t;const i=this._activeAnimatables;if(0===i.length)return;this._animationTime+=this.deltaTime;const s=this._animationTime;for(let e=0;ee.playOrder-t.playOrder))},ks.prototype.beginWeightedAnimation=function(e,t,i,s=1,r,n=1,o,a,l,h,c=!1){const u=this.beginAnimation(e,t,i,r,n,o,a,!1,l,h,c);return u.weight=s,u},ks.prototype.beginAnimation=function(e,t,i,s,r=1,n,o,a=!0,l,h,c=!1){t>i&&r>0&&(r*=-1),a&&this.stopAnimation(e,void 0,l),o||(o=new Ws(this,e,t,i,s,r,n,void 0,h,c));const u=!l||l(e);if(e.animations&&u&&o.appendAnimations(e,e.animations),e.getAnimatables){const c=e.getAnimatables();for(let e=0;es&&n>0)n*=-1;else if(s>i&&n<0){const e=s;s=i,i=e}return new Ws(this,e,i,s,r,n,o,t,a,l)},ks.prototype.beginDirectHierarchyAnimation=function(e,t,i,s,r,n,o,a,l,h=!1){const c=e.getDescendants(t),u=[];u.push(this.beginDirectAnimation(e,i,s,r,n,o,a,l,h));for(const e of c)u.push(this.beginDirectAnimation(e,i,s,r,n,o,a,l,h));return u},ks.prototype.getAnimatableByTarget=function(e){for(let t=0;t0?l:-l,r),a.scaleAndAddToRef(l,i)}r.normalize()}for(let t=0;t0)r.copyFrom(s);else if(1===e.animations.length){if(L.SlerpToRef(s,i.currentValue,Math.min(1,e.totalWeight),r),0===e.totalAdditiveWeight)return r}else if(e.animations.length>1){let i,n,o=1;if(e.totalWeight<1){const t=1-e.totalWeight;i=[],n=[],i.push(s),n.push(t)}else{if(2===e.animations.length&&(L.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],n=[],o=e.totalWeight}for(let t=0;t=o&&m.frame<=a&&(s?(v=m.value.clone(),d?(g=v.getTranslation(),v.setTranslation(g.scaleInPlace(p))):f&&r?(g=v.getTranslation(),v.setTranslation(g.multiplyInPlace(r))):v=m.value):v=m.value,_.push({frame:m.frame+i,value:v}));return this.animations[0].createRange(t,o+i,a+i),!0},function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(Bs||(Bs={}));class Hs{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return 180*this._radians/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),s=Math.atan2(i.y,i.x);return new Hs(s)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(0===i)return new Hs(Math.PI/2);i=Math.sqrt(i);let s=e.dot(t)/i;s=G.Clamp(s,-1,1);const r=Math.acos(s);return new Hs(r)}static FromRadians(e){return new Hs(e)}static FromDegrees(e){return new Hs(e*Math.PI/180)}}class Xs{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const s=Math.pow(t.x,2)+Math.pow(t.y,2),r=(Math.pow(e.x,2)+Math.pow(e.y,2)-s)/2,n=(s-Math.pow(i.x,2)-Math.pow(i.y,2))/2,o=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new N((r*(t.y-i.y)-n*(e.y-t.y))/o,((e.x-t.x)*n-(t.x-i.x)*r)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=Hs.BetweenTwoPoints(this.centerPoint,this.startPoint);const a=this.startAngle.degrees();let l=Hs.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=Hs.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-a>180&&(l-=360),l-a<-180&&(l+=360),h-l>180&&(h-=360),h-l<-180&&(h+=360),this.orientation=l-a<0?Bs.CW:Bs.CCW,this.angle=Hs.FromDegrees(this.orientation===Bs.CW?a-h:h-a)}}class Ys{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new N(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new N(e,t),s=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(s).length(),this}addArcTo(e,t,i,s,r=36){if(this.closed)return this;const n=this._points[this._points.length-1],o=new N(e,t),a=new N(i,s),l=new Xs(n,o,a);let h=l.angle.radians()/r;l.orientation===Bs.CW&&(h*=-1);let c=l.startAngle.radians()+h;for(let e=0;e(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*s,o=this._points[this._points.length-1];for(let a=0;a<=r;a++){const l=a/r,h=n(l,o.x,e,i),c=n(l,o.y,t,s);this.addLineTo(h,c)}return this}addBezierCurveTo(e,t,i,s,r,n,o=36){if(this.closed)return this;const a=(e,t,i,s,r)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*s+e*e*e*r,l=this._points[this._points.length-1];for(let h=0;h<=o;h++){const c=h/o,u=a(c,l.x,e,i,r),d=a(c,l.y,t,s,n);this.addLineTo(u,d)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let s=i-1,r=0;rNumber.EPSILON){if(a<0&&(i=this._points[r],o=-o,n=this._points[s],a=-a),e.yn.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{const s=a*(e.x-i.x)-o*(e.y-i.y);if(0===s)return!0;if(s<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(n.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=n.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1];e+=this._points[0].subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,s=0;s1)return N.Zero();const t=e*this.length();let i=0;for(let e=0;e=i&&t<=o){const e=n.normalize(),s=t-i;return new N(r.x+e.x*s,r.y+e.y*s)}i=o}return N.Zero()}static StartingAt(e,t){return new Ys(e,t)}}class js{constructor(e,t=null,i,s=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:w.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:B.Identity()};for(let t=0;tt){const i=e;e=t,t=i}const i=this.getCurve(),s=this.getPointAt(e);let r=this.getPreviousPointIndexAt(e);const n=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,a=[];return 0!==e&&(r++,a.push(s)),a.push(...i.slice(r,o)),1===t&&1!==e||a.push(n),new js(a,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;tt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,s=e.length();if(0===s&&(s=1),null==t){let t;t=G.WithinEpsilon(Math.abs(e.y)/s,1,T)?G.WithinEpsilon(Math.abs(e.x)/s,1,T)?G.WithinEpsilon(Math.abs(e.z)/s,1,T)?w.Zero():new w(0,0,1):new w(1,0,0):new w(0,-1,0),i=w.Cross(e,t)}else i=w.Cross(e,t),w.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;const i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let s,r=i[0],n=0;const o=e*this.length();for(let a=1;ao){const i=(n-o)/l,h=r.subtract(s),c=s.add(h.scaleInPlace(i));return this._setPointAtData(e,1-i,c,a-1,t)}r=s}return this._pointAtData}_setPointAtData(e,t,i,s,r){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=s,this._pointAtData.interpolateReady=r,r&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=B.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),s=this._normals[e].clone(),r=this._binormals[e].clone(),n=this._tangents[t].clone(),o=this._normals[t].clone(),a=this._binormals[t].clone(),l=L.RotationQuaternionFromAxis(s,r,i),h=L.RotationQuaternionFromAxis(o,a,n);L.Slerp(l,h,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class $s{static CreateQuadraticBezier(e,t,i,s){s=s>2?s:3;const r=[],n=(e,t,i,s)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*s;for(let o=0;o<=s;o++)r.push(new w(n(o/s,e.x,t.x,i.x),n(o/s,e.y,t.y,i.y),n(o/s,e.z,t.z,i.z)));return new $s(r)}static CreateCubicBezier(e,t,i,s,r){r=r>3?r:4;const n=[],o=(e,t,i,s,r)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*s+e*e*e*r;for(let a=0;a<=r;a++)n.push(new w(o(a/r,e.x,t.x,i.x,s.x),o(a/r,e.y,t.y,i.y,s.y),o(a/r,e.z,t.z,i.z,s.z)));return new $s(n)}static CreateHermiteSpline(e,t,i,s,r){const n=[],o=1/r;for(let a=0;a<=r;a++)n.push(w.Hermite(e,t,i,s,a*o));return new $s(n)}static CreateCatmullRomSpline(e,t,i){const s=[],r=1/t;let n=0;if(i){const i=e.length;for(let o=0;o=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}Ks.EASINGMODE_EASEIN=0,Ks.EASINGMODE_EASEOUT=1,Ks.EASINGMODE_EASEINOUT=2;class qs extends Ks{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class Qs extends Ks{easeInCore(e){return e*e}}class Zs extends Ks{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class Js{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class er{get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this.syncWithMask(!0))}syncWithMask(e=!1){if(this.mask||e){this._numActiveAnimatables=0;for(let e=0;e0)){for(let e=0;en&&(n=t.to);const o=new er(e[0].name+"_merged",e[0]._scene,s);for(const s of e){i&&s.normalize(r,n);for(const e of s.targetedAnimations)o.addTargetedAnimation(e.animation,e.target);t&&s.dispose()}return o}constructor(e,t=null,i=-1,s=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._parentContainer=null,this.onAnimationEndObservable=new g,this.onAnimationLoopObservable=new g,this.onAnimationGroupLoopObservable=new g,this.onAnimationGroupEndObservable=new g,this.onAnimationGroupPauseObservable=new g,this.onAnimationGroupPlayObservable=new g,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||y.LastCreatedScene,this._weight=i,this._playOrder=s,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const i=new Js;i.animation=e,i.target=t;const s=e.getKeys();return this._from>s[0].frame&&(this._from=s[0].frame),this._to-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;ie){const t={frame:e,value:r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation};s.splice(0,0,t)}if(n.frame{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,s,r){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(a)},this._processLoop(a,o,n),this._animatables.push(a)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e0&&(this._scene._activeAnimatables[t++]=i)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const e=this._parentContainer.animationGroups.indexOf(this);e>-1&&this._parentContainer.animationGroups.splice(e,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e){const t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const s=new er(e||this.name,this._scene,this._weight,this._playOrder);s._from=this.from,s._to=this.to,s._speedRatio=this.speedRatio,s._loopAnimation=this.loopAnimation,s._isAdditive=this.isAdditive,s._enableBlending=this.enableBlending,s._blendingSpeed=this.blendingSpeed,s.metadata=this.metadata,s.mask=this.mask;for(const e of this._targetedAnimations)s.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return s}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;tr[0].frame&&(e=r[0].frame),t=t&&e<=i||r&&s.frame>=t&&s.frame<=i){const e={frame:s.frame,value:s.value.clone?s.value.clone():s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation,lockedTangent:s.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,u.push(e)}}0!==u.length?(n>u[0].frame&&(n=u[0].frame),o{s.value=void 0,t(s)}),i):t(s)}catch(e){i(e)}}function ir(e,t,i,s,r){const n=()=>{let o;const a=e=>{e.done?i(e.value):void 0===o?o=!0:n()};do{o=void 0,r&&r.aborted?s(new Error("Aborted")):t(e,a,s),void 0===o&&(o=!1)}while(o)};n()}function sr(e,t){let i;return ir(e,tr,(e=>i=e),(e=>{throw e}),t),i}function rr(e,t,i){return new Promise(((s,r)=>{ir(e,t,s,r,i)}))}!function(e){e[e.Include=0]="Include",e[e.Exclude=1]="Exclude"}(Vs||(Vs={}));class nr{constructor(e,t,i,s){this.x=e,this.y=t,this.width=i,this.height=s}toGlobal(e,t){return new nr(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new nr(this.x,this.y,this.width,this.height)}}class or extends De{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){let e=0,t=0;if(this.mode===or.PERSPECTIVE_CAMERA)this.fovMode===or.FOVMODE_VERTICAL_FIXED?(t=2*this.minZ*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=2*this.minZ*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const i=this.getEngine().getRenderWidth()/2,s=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??i)-(this.orthoLeft??-i),t=(this.orthoTop??s)-(this.orthoBottom??-s)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,s=!0){super(e,i,!1),this._position=w.Zero(),this._upVector=w.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=or.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new nr(0,0,1,1),this.layerMask=268435455,this.fovMode=or.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=or.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new g,this.onProjectionMatrixChangedObservable=new g,this.onAfterCheckInputsObservable=new g,this.onRestoreStateObservable=new g,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new B,this._postProcesses=new Array,this._activeMeshes=new Mi(256),this._globalPosition=w.Zero(),this._computedViewMatrix=B.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=B.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=L.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),s&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i-1?(J.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))}detachPostProcess(e){const t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()||this.getViewMatrix(),this._worldMatrix}_getViewMatrix(){return B.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix)),this._computedViewMatrix}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const t=this.getEngine(),i=this.getScene(),s=t.useReverseDepthBuffer;if(this.mode===or.PERSPECTIVE_CAMERA){let e;this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=t.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),e=i.useRightHandedSystem?B.PerspectiveFovRHToRef:B.PerspectiveFovLHToRef,e(this.fov,t.getAspectRatio(this),s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===or.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{const e=t.getRenderWidth()/2,r=t.getRenderHeight()/2;i.useRightHandedSystem?this.oblique?B.ObliqueOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):B.OrthoOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?B.ObliqueOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):B.OrthoOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,s?this.maxZ:this.minZ,s?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=this.oblique?.angle,this._cache.obliqueLength=this.oblique?.length,this._cache.obliqueOffset=this.oblique?.offset,this._cache.renderWidth=t.getRenderWidth(),this._cache.renderHeight=t.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){return(this.radius||(this.target?w.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?Ms.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Ms.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;return this.rigCameras.forEach((i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)})),t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw ye("Ray")}getForwardRayToRef(e,t=100,i,s){throw ye("Ray")}dispose(e,t=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){const e=this._parentContainer.cameras.indexOf(this);e>-1&&this._parentContainer.cameras.splice(e,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==or.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){const t=this._postProcesses[e];t&&t.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),super.dispose(e,t)}get isLeftCamera(){return this._isLeftCamera}get isRightCamera(){return this._isRightCamera}get leftCamera(){return this._rigCameras.length<1?null:this._rigCameras[0]}get rightCamera(){return this._rigCameras.length<2?null:this._rigCameras[1]}getLeftTarget(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()}getRightTarget(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()}setCameraRigMode(e,t){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=Ii.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==or.RIG_MODE_NONE){const e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);const t=this.createRigCamera(this.name+"_R",1);t&&(t._isRightCamera=!0),e&&t&&(this._rigCameras.push(e),this._rigCameras.push(t))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return B.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=Ii.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eor._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,s=or.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=Pe.Parse(s,e,t);if(void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=w.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(w.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(w.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t{throw ye("UniversalCamera")},or.PERSPECTIVE_CAMERA=0,or.ORTHOGRAPHIC_CAMERA=1,or.FOVMODE_VERTICAL_FIXED=0,or.FOVMODE_HORIZONTAL_FIXED=1,or.RIG_MODE_NONE=0,or.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,or.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,or.RIG_MODE_STEREOSCOPIC_INTERLACED=14,or.RIG_MODE_VR=20,or.RIG_MODE_CUSTOM=22,or.ForceAttachControlToAlwaysPreventDefault=!1,ae([ve("position")],or.prototype,"_position",void 0),ae([ve("upVector")],or.prototype,"_upVector",void 0),ae([pe()],or.prototype,"orthoLeft",null),ae([pe()],or.prototype,"orthoRight",null),ae([pe()],or.prototype,"orthoBottom",null),ae([pe()],or.prototype,"orthoTop",null),ae([pe()],or.prototype,"fov",void 0),ae([pe()],or.prototype,"projectionPlaneTilt",void 0),ae([pe()],or.prototype,"minZ",void 0),ae([pe()],or.prototype,"maxZ",void 0),ae([pe()],or.prototype,"inertia",void 0),ae([pe()],or.prototype,"mode",null),ae([pe()],or.prototype,"layerMask",void 0),ae([pe()],or.prototype,"fovMode",void 0),ae([pe()],or.prototype,"cameraRigMode",void 0),ae([pe()],or.prototype,"interaxialDistance",void 0),ae([pe()],or.prototype,"isStereoscopicSideBySide",void 0);class ar{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class lr{constructor(e,t,i){this.vectors=S.BuildArray(8,w.Zero),this.center=w.Zero(),this.centerWorld=w.Zero(),this.extendSize=w.Zero(),this.extendSizeWorld=w.Zero(),this.directions=S.BuildArray(3,w.Zero),this.vectorsWorld=S.BuildArray(8,w.Zero),this.minimumWorld=w.Zero(),this.maximumWorld=w.Zero(),this.minimum=w.Zero(),this.maximum=w.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const s=e.x,r=e.y,n=e.z,o=t.x,a=t.y,l=t.z,h=this.vectors;this.minimum.copyFromFloats(s,r,n),this.maximum.copyFromFloats(o,a,l),h[0].copyFromFloats(s,r,n),h[1].copyFromFloats(o,a,l),h[2].copyFromFloats(o,r,n),h[3].copyFromFloats(s,a,n),h[4].copyFromFloats(s,r,l),h[5].copyFromFloats(o,a,n),h[6].copyFromFloats(s,a,l),h[7].copyFromFloats(o,r,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||B.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=lr._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),s=i.length();i.normalizeFromLength(s);const r=s*e,n=i.scaleInPlace(.5*r),o=this.center.subtractToRef(n,t[1]),a=this.center.addToRef(n,t[2]);return this.reConstruct(o,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,s=this.directions,r=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)r[e].copyFrom(n[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let s=0;s<8;++s){const o=r[s];w.TransformCoordinatesToRef(n[s],e,o),t.minimizeInPlace(o),i.maximizeInPlace(o)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}w.FromArrayToRef(e.m,0,s[0]),w.FromArrayToRef(e.m,4,s[1]),w.FromArrayToRef(e.m,8,s[2]),this._worldMatrix=e}isInFrustum(e){return lr.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return lr.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,s=t.x,r=t.y,n=t.z,o=i.x,a=i.y,l=i.z,h=e.x,c=e.y,u=e.z,d=-T;return!(o-hh-s||a-cc-r||l-uu-n)}intersectsSphere(e){return lr.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,s=this.maximumWorld,r=i.x,n=i.y,o=i.z,a=s.x,l=s.y,h=s.z,c=e.x,u=e.y,d=e.z,p=t.x,f=t.y,_=t.z;return!(ap||lf||h_)}dispose(){this._drawWrapperFront?.dispose(),this._drawWrapperBack?.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,s){const r=lr._TmpVector3[0];return w.ClampToRef(i,e,t,r),w.DistanceSquared(i,r)<=s*s}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){const s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let s=!0;const r=t[i];for(let t=0;t<8;++t)if(r.dotCoordinate(e[t])>=0){s=!1;break}if(s)return!1}return!0}}lr._TmpVector3=S.BuildArray(3,w.Zero);class hr{constructor(e,t,i){this.center=w.Zero(),this.centerWorld=w.Zero(),this.minimum=w.Zero(),this.maximum=w.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const s=w.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*s,this._update(i||B.IdentityReadOnly)}scale(e){const t=this.radius*e,i=hr._TmpVector3,s=i[0].setAll(t),r=this.center.subtractToRef(s,i[1]),n=this.center.addToRef(s,i[2]);return this.reConstruct(r,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{w.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=hr._TmpVector3[0];w.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,i=this.radiusWorld;for(let s=0;s<6;s++)if(e[s].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=w.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{const s=w.Dot(t.centerWorld,e),r=Math.abs(w.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(w.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(w.Dot(t.directions[2],e))*t.extendSize.z;i.min=s-r,i.max=s+r},pr=(e,t,i)=>(dr(e,t,cr),dr(e,i,ur),!(cr.min>ur.max||ur.min>cr.max));class fr{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new lr(e,t,i),this.boundingSphere=new hr(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}get minimum(){return this.boundingBox.minimum}get maximum(){return this.boundingBox.maximum}get isLocked(){return this._isLocked}set isLocked(e){this._isLocked=e}update(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))}centerOn(e,t){const i=fr._TmpVector3[0].copyFrom(e).subtractInPlace(t),s=fr._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,s,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=w.Minimize(this.minimum,e),i=w.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=U.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=U.Vector3[0];return w.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),w.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return!(2!==t&&3!==t||!this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(!(1!==t&&3!==t)||this.boundingBox.isInFrustum(e))}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,fr._TmpVector3[0]).length()}isCompletelyInFrustum(e){return this.boundingBox.isCompletelyInFrustum(e)}_checkCollision(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)}intersectsPoint(e){return!!this.boundingSphere.centerWorld&&!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e)}intersects(e,t){if(!hr.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!lr.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,s=e.boundingBox;return!!(pr(i.directions[0],i,s)&&pr(i.directions[1],i,s)&&pr(i.directions[2],i,s)&&pr(s.directions[0],i,s)&&pr(s.directions[1],i,s)&&pr(s.directions[2],i,s)&&pr(w.Cross(i.directions[0],s.directions[0]),i,s)&&pr(w.Cross(i.directions[0],s.directions[1]),i,s)&&pr(w.Cross(i.directions[0],s.directions[2]),i,s)&&pr(w.Cross(i.directions[1],s.directions[0]),i,s)&&pr(w.Cross(i.directions[1],s.directions[1]),i,s)&&pr(w.Cross(i.directions[1],s.directions[2]),i,s)&&pr(w.Cross(i.directions[2],s.directions[0]),i,s)&&pr(w.Cross(i.directions[2],s.directions[1]),i,s)&&pr(w.Cross(i.directions[2],s.directions[2]),i,s))}}fr._TmpVector3=S.BuildArray(2,w.Zero);class _r{static extractMinAndMaxIndexed(e,t,i,s,r,n){for(let o=i;o!Array.isArray(e)&&!Array.isArray(t)))],_r,"extractMinAndMaxIndexed",null),ae([be.filter(((...[e])=>!Array.isArray(e)))],_r,"extractMinAndMax",null);class gr{static GetEffect(e){return void 0===e.getPipelineContext?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){this.effect=e,void 0!==t&&(this.defines=t),i&&this.drawContext?.reset()}dispose(){this.drawContext?.dispose()}}class vr{get materialDefines(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:this._getDrawWrapper()?.defines}set materialDefines(e){(this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new gr(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){t&&this._drawWrappers[e]?.dispose(),this._drawWrappers[e]=void 0}get effect(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:this._getDrawWrapper()?.effect??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,s=!0){const r=this._drawWrapper;r.setEffect(e,t,s),void 0!==i&&(r.materialContext=i),e||(r.defines=null,r.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)e?.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,s,r,n,o,a=!0){return new vr(e,t,i,s,r,n,o,a)}constructor(e,t,i,s,r,n,o,a=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=s,this.indexCount=r,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=o||n,l&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,a&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){return(this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null)||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(!t)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(t)){const e=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return t}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(Ki.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();i={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else i=function(e,t,i,s,r=null){const n=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new w(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return _r.extractMinAndMaxIndexed(e,t,i,s,n,o),r&&(n.x-=n.x*r.x+r.y,n.y-=n.y*r.x+r.y,n.z-=n.z*r.x+r.y,o.x+=o.x*r.x+r.y,o.y+=o.y*r.x+r.y,o.z+=o.z*r.x+r.y),{minimum:n,maximum:o}}(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new fr(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const i=[];for(let t=this.indexStart;ta&&(a=t)}return new vr(e,o,a-o+1,t,i,s,r,n)}}class xr{}class Tr{constructor(){var e;this.uniqueId=0,this.metadata={},this._applyTo=(e=this._applyToCoroutine.bind(this),(...t)=>sr(e(...t),undefined)),this.uniqueId=Tr._UniqueIDGenerator,Tr._UniqueIDGenerator++}set(e,t){switch(e.length||J.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case Ki.PositionKind:this.positions=e;break;case Ki.NormalKind:this.normals=e;break;case Ki.TangentKind:this.tangents=e;break;case Ki.UVKind:this.uvs=e;break;case Ki.UV2Kind:this.uvs2=e;break;case Ki.UV3Kind:this.uvs3=e;break;case Ki.UV4Kind:this.uvs4=e;break;case Ki.UV5Kind:this.uvs5=e;break;case Ki.UV6Kind:this.uvs6=e;break;case Ki.ColorKind:this.colors=e;break;case Ki.MatricesIndicesKind:this.matricesIndices=e;break;case Ki.MatricesWeightsKind:this.matricesWeights=e;break;case Ki.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case Ki.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){if(this.positions&&(e.setVerticesData(Ki.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(Ki.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(Ki.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(Ki.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(Ki.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(Ki.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(Ki.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(Ki.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(Ki.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(Ki.ColorKind,this.colors,t),this.hasVertexAlpha&&void 0!==e.hasVertexAlpha&&(e.hasVertexAlpha=!0),i&&(yield)),this.matricesIndices&&(e.setVerticesData(Ki.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(Ki.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(Ki.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(Ki.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){const t=e;t.subMeshes=[];for(const e of this.materialInfos)new vr(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,t)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(Ki.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(Ki.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(Ki.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(Ki.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(Ki.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(Ki.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(Ki.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(Ki.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(Ki.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(Ki.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(Ki.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(Ki.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(Ki.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(Ki.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,s=e.length){const r=U.Vector3[0],n=U.Vector3[1];for(let o=i;o({vertexData:e}))):[{vertexData:e}];return sr(this._mergeCoroutine(void 0,n,t,!1,i,s,r))}*_mergeCoroutine(e,t,i=!1,s,r,n=!1,o=!1){this._validate();let a=t.map((e=>e.vertexData)),l=this;if(o)for(const e of a)e&&(e._validate(),!this.normals&&e.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&e.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&e.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&e.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&e.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&e.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&e.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&e.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&e.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&e.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&e.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&e.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&e.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const e of a)if(e)if(o)this.normals&&!e.normals&&(e.normals=new Float32Array(e.positions.length)),this.tangents&&!e.tangents&&(e.tangents=new Float32Array(e.positions.length/3*4)),this.uvs&&!e.uvs&&(e.uvs=new Float32Array(e.positions.length/3*2)),this.uvs2&&!e.uvs2&&(e.uvs2=new Float32Array(e.positions.length/3*2)),this.uvs3&&!e.uvs3&&(e.uvs3=new Float32Array(e.positions.length/3*2)),this.uvs4&&!e.uvs4&&(e.uvs4=new Float32Array(e.positions.length/3*2)),this.uvs5&&!e.uvs5&&(e.uvs5=new Float32Array(e.positions.length/3*2)),this.uvs6&&!e.uvs6&&(e.uvs6=new Float32Array(e.positions.length/3*2)),this.colors&&!e.colors&&(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)),this.matricesIndices&&!e.matricesIndices&&(e.matricesIndices=new Float32Array(e.positions.length/3*4)),this.matricesWeights&&!e.matricesWeights&&(e.matricesWeights=new Float32Array(e.positions.length/3*4)),this.matricesIndicesExtra&&!e.matricesIndicesExtra&&(e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4)),this.matricesWeightsExtra&&!e.matricesWeightsExtra&&(e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4));else if(e._validate(),!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");if(n){let i=0,s=0,r=0;const n=[];let o=null;const h=[];for(const t of this.splitBasedOnMaterialID())h.push({vertexData:t,transform:e});for(const e of t)if(e.vertexData)for(const t of e.vertexData.splitBasedOnMaterialID())h.push({vertexData:t,transform:e.transform});h.sort(((e,t)=>{const i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,s=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>s?1:i===s?0:-1}));for(const e of h){const t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,o&&o.materialIndex===i)o.indexCount+=t.indices.length,o.verticesCount+=t.positions.length/3;else{const e=new xr;e.materialIndex=i,e.indexStart=s,e.indexCount=t.indices.length,e.verticesStart=r,e.verticesCount=t.positions.length/3,n.push(e),o=e}s+=t.indices.length,r+=t.positions.length/3}const c=h.splice(0,1)[0];l=c.vertexData,e=c.transform,a=h.map((e=>e.vertexData)),t=h,this.materialInfos=n}const h=a.reduce(((e,t)=>e+(t.indices?.length??0)),l.indices?.length??0);let c=r||a.some((e=>e.indices===l.indices))?l.indices?.slice():l.indices;if(h>0){let r=c?.length??0;if(c||(c=new Array(h)),c.length!==h){if(Array.isArray(c))c.length=h;else{const e=i||c instanceof Uint32Array?new Uint32Array(h):new Uint16Array(h);e.set(c),c=e}e&&e.determinant()<0&&Tr._FlipFaces(c,0,r)}let n=l.positions?l.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t[e.vertexData.positions,e.transform]))),s&&(yield),l.normals&&(this.normals=Tr._MergeElement(Ki.NormalKind,l.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),s&&(yield)),l.tangents&&(this.tangents=Tr._MergeElement(Ki.TangentKind,l.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),s&&(yield)),l.uvs&&(this.uvs=Tr._MergeElement(Ki.UVKind,l.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),s&&(yield)),l.uvs2&&(this.uvs2=Tr._MergeElement(Ki.UV2Kind,l.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),s&&(yield)),l.uvs3&&(this.uvs3=Tr._MergeElement(Ki.UV3Kind,l.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),s&&(yield)),l.uvs4&&(this.uvs4=Tr._MergeElement(Ki.UV4Kind,l.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),s&&(yield)),l.uvs5&&(this.uvs5=Tr._MergeElement(Ki.UV5Kind,l.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),s&&(yield)),l.uvs6&&(this.uvs6=Tr._MergeElement(Ki.UV6Kind,l.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),s&&(yield)),l.colors&&(this.colors=Tr._MergeElement(Ki.ColorKind,l.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),(void 0!==l.hasVertexAlpha||t.some((e=>void 0!==e.vertexData.hasVertexAlpha)))&&(this.hasVertexAlpha=l.hasVertexAlpha||t.some((e=>e.vertexData.hasVertexAlpha))),s&&(yield)),l.matricesIndices&&(this.matricesIndices=Tr._MergeElement(Ki.MatricesIndicesKind,l.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),s&&(yield)),l.matricesWeights&&(this.matricesWeights=Tr._MergeElement(Ki.MatricesWeightsKind,l.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),s&&(yield)),l.matricesIndicesExtra&&(this.matricesIndicesExtra=Tr._MergeElement(Ki.MatricesIndicesExtraKind,l.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),s&&(yield)),l.matricesWeightsExtra&&(this.matricesWeightsExtra=Tr._MergeElement(Ki.MatricesWeightsExtraKind,l.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform])))),this}static _MergeElement(e,t,i,s){const r=s.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==r.length)return t;if(!t)return this._MergeElement(e,r[0][0],r[0][1],r.slice(1));const n=r.reduce(((e,t)=>e+t[0].length),t.length),o=e===Ki.PositionKind?Tr._TransformVector3Coordinates:e===Ki.NormalKind?Tr._TransformVector3Normals:e===Ki.TangentKind?Tr._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(n);e.set(t),i&&o(e,i,0,t.length);let s=t.length;for(const[t,i]of r)e.set(t,s),i&&o(e,i,s,t.length),s+=t.length;return e}{const e=new Array(n);for(let i=0;i{const i=Ki.DeduceStride(e);if(t.length%i!=0)throw new Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(Ki.PositionKind,this.positions),i=(i,s)=>{const r=e(i,s);if(r!==t)throw new Error("The "+i+"s element count ("+r+") does not match the positions count ("+t+")")};this.normals&&i(Ki.NormalKind,this.normals),this.tangents&&i(Ki.TangentKind,this.tangents),this.uvs&&i(Ki.UVKind,this.uvs),this.uvs2&&i(Ki.UV2Kind,this.uvs2),this.uvs3&&i(Ki.UV3Kind,this.uvs3),this.uvs4&&i(Ki.UV4Kind,this.uvs4),this.uvs5&&i(Ki.UV5Kind,this.uvs5),this.uvs6&&i(Ki.UV6Kind,this.uvs6),this.colors&&i(Ki.ColorKind,this.colors),this.matricesIndices&&i(Ki.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(Ki.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(Ki.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(Ki.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return Tr.Parse(e)}serialize(){const e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos){e.materialInfos=[];for(const t of this.materialInfos){const i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return Tr._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return Tr._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const s=new Tr;return e.isVerticesDataPresent(Ki.PositionKind)&&(s.positions=e.getVerticesData(Ki.PositionKind,t,i)),e.isVerticesDataPresent(Ki.NormalKind)&&(s.normals=e.getVerticesData(Ki.NormalKind,t,i)),e.isVerticesDataPresent(Ki.TangentKind)&&(s.tangents=e.getVerticesData(Ki.TangentKind,t,i)),e.isVerticesDataPresent(Ki.UVKind)&&(s.uvs=e.getVerticesData(Ki.UVKind,t,i)),e.isVerticesDataPresent(Ki.UV2Kind)&&(s.uvs2=e.getVerticesData(Ki.UV2Kind,t,i)),e.isVerticesDataPresent(Ki.UV3Kind)&&(s.uvs3=e.getVerticesData(Ki.UV3Kind,t,i)),e.isVerticesDataPresent(Ki.UV4Kind)&&(s.uvs4=e.getVerticesData(Ki.UV4Kind,t,i)),e.isVerticesDataPresent(Ki.UV5Kind)&&(s.uvs5=e.getVerticesData(Ki.UV5Kind,t,i)),e.isVerticesDataPresent(Ki.UV6Kind)&&(s.uvs6=e.getVerticesData(Ki.UV6Kind,t,i)),e.isVerticesDataPresent(Ki.ColorKind)&&(s.colors=e.getVerticesData(Ki.ColorKind,t,i)),e.isVerticesDataPresent(Ki.MatricesIndicesKind)&&(s.matricesIndices=e.getVerticesData(Ki.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(Ki.MatricesWeightsKind)&&(s.matricesWeights=e.getVerticesData(Ki.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(Ki.MatricesIndicesExtraKind)&&(s.matricesIndicesExtra=e.getVerticesData(Ki.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(Ki.MatricesWeightsExtraKind)&&(s.matricesWeightsExtra=e.getVerticesData(Ki.MatricesWeightsExtraKind,t,i)),s.indices=e.getIndices(t,i),s}static CreateRibbon(e){throw ye("ribbonBuilder")}static CreateBox(e){throw ye("boxBuilder")}static CreateTiledBox(e){throw ye("tiledBoxBuilder")}static CreateTiledPlane(e){throw ye("tiledPlaneBuilder")}static CreateSphere(e){throw ye("sphereBuilder")}static CreateCylinder(e){throw ye("cylinderBuilder")}static CreateTorus(e){throw ye("torusBuilder")}static CreateLineSystem(e){throw ye("linesBuilder")}static CreateDashedLines(e){throw ye("linesBuilder")}static CreateGround(e){throw ye("groundBuilder")}static CreateTiledGround(e){throw ye("groundBuilder")}static CreateGroundFromHeightMap(e){throw ye("groundBuilder")}static CreatePlane(e){throw ye("planeBuilder")}static CreateDisc(e){throw ye("discBuilder")}static CreatePolygon(e,t,i,s,r,n,o){throw ye("polygonBuilder")}static CreateIcoSphere(e){throw ye("icoSphereBuilder")}static CreatePolyhedron(e){throw ye("polyhedronBuilder")}static CreateCapsule(e={orientation:w.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw ye("capsuleBuilder")}static CreateTorusKnot(e){throw ye("torusKnotBuilder")}static ComputeNormals(e,t,i,s){let r=0,n=0,o=0,a=0,l=0,h=0,c=0,u=0,d=0,p=0,f=0,_=0,m=0,g=0,v=0,x=0,T=0,S=0,E=0,b=0,C=!1,y=!1,A=!1,R=!1,I=1,P=0,M=null;s&&(C=!!s.facetNormals,y=!!s.facetPositions,A=!!s.facetPartitioning,I=!0===s.useRightHandedSystem?-1:1,P=s.ratio||0,R=!!s.depthSort,M=s.distanceTo,R&&void 0===M&&(M=w.Zero()));let D=0,O=0,N=0,F=0;for(A&&s&&s.bbSize&&(D=s.subDiv.X*P/s.bbSize.x,O=s.subDiv.Y*P/s.bbSize.y,N=s.subDiv.Z*P/s.bbSize.z,F=s.subDiv.max*s.subDiv.max,s.facetPartitioning.length=0),r=0;r!Array.isArray(e)))],Tr,"_TransformVector3Coordinates",null),ae([be.filter(((...[e])=>!Array.isArray(e)))],Tr,"_TransformVector3Normals",null),ae([be.filter(((...[e])=>!Array.isArray(e)))],Tr,"_TransformVector4Normals",null),ae([be.filter(((...[e])=>!Array.isArray(e)))],Tr,"_FlipFaces",null);class Sr{static get ForceFullSceneLoadingForIncremental(){return Sr._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Sr._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Sr._ShowLoadingScreen}static set ShowLoadingScreen(e){Sr._ShowLoadingScreen=e}static get loggingLevel(){return Sr._LoggingLevel}static set loggingLevel(e){Sr._LoggingLevel=e}static get CleanBoneMatrixWeights(){return Sr._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Sr._CleanBoneMatrixWeights=e}}Sr._ForceFullSceneLoadingForIncremental=!1,Sr._ShowLoadingScreen=!0,Sr._CleanBoneMatrixWeights=!1,Sr._LoggingLevel=0;class Er{}Er.UseOpenGLOrientationForUV=!1;class br{get boundingBias(){return this._boundingBias}set boundingBias(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)}static CreateGeometryForMesh(e){const t=new br(br.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,s=!1,r=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||y.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=s,i?this.setAllVerticesData(i,s):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e{e._rebuild()}))}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,s){i&&Array.isArray(t)&&(t=new Float32Array(t));const r=new Ki(this._engine,t,e,{updatable:i,postponeInternalCreation:0===this._meshes.length,stride:s,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(r)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){const s=e.getKind();this._vertexBuffers[s]&&i&&this._vertexBuffers[s].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[s]=e;const r=this._meshes,n=r.length;if(s===Ki.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const i=this._extend&&this._extend.minimum||new w(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),s=this._extend&&this._extend.maximum||new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e65535);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),null!=t&&(this._totalVertices=t);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?void 0!==this._totalIndices?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){e&&this._vertexArrayObjects&&this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const i=this._meshes,s=i.indexOf(e);-1!==s&&(i.splice(s,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;const t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();const i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&!(e=this.getVerticesData(Ki.PositionKind)))return;this._extend=mr(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===Ki.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const e of this._meshes)e._markSubMeshesAsAttributesDirty()}load(e,t){2!==this.delayLoadState&&(this.isReady()?t&&t():(this.delayLoadState=2,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const s=this._meshes,r=s.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new Tr;t.indices=[];const i=this.getIndices();if(i)for(let e=0;e0){const s=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(Ki.PositionKind,s,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const s=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(Ki.NormalKind,s,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const s=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(Ki.TangentKind,s,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const s=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(Er.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(Er.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(Er.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(Er.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(Er.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(Er.UseOpenGLOrientationForUV)for(let e=1;e0){const s=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(Ki.ColorKind,s,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(Ki.MatricesIndicesKind,r,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const s=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),r=[];for(let e=0;e>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(Ki.MatricesIndicesExtraKind,r,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const s=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(Ki.MatricesWeightsKind,s,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){const s=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(s,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){const s=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(Ki.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(Ki.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t>8),i.push((16711680&s)>>16),i.push(s>>24&255)}t.setVerticesData(Ki.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(br._CleanMatricesWeights(e,t),t.setVerticesData(Ki.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(Ki.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;s=i.bones.length}const r=t.getVerticesData(Ki.MatricesIndicesKind),n=t.getVerticesData(Ki.MatricesIndicesExtraKind),o=e.matricesWeights,a=e.matricesWeightsExtra,l=e.numBoneInfluencer,h=o.length;for(let e=0;el-1)&&(h=l-1),t>i){const i=1/t;for(let t=0;t<4;t++)o[e+t]*=i;if(a)for(let t=0;t<4;t++)a[e+t]*=i}else h>=4?(a[e+h-4]=1-t,n[e+h-4]=s):(o[e+h]=1-t,r[e+h]=s)}t.setVerticesData(Ki.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(Ki.MatricesIndicesExtraKind,n)}static Parse(e,t,i){const s=new br(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,Re&&Re.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new fr(w.FromArray(e.boundingBoxMinimum),w.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(Ki.UVKind),e.hasUVs2&&s._delayInfo.push(Ki.UV2Kind),e.hasUVs3&&s._delayInfo.push(Ki.UV3Kind),e.hasUVs4&&s._delayInfo.push(Ki.UV4Kind),e.hasUVs5&&s._delayInfo.push(Ki.UV5Kind),e.hasUVs6&&s._delayInfo.push(Ki.UV6Kind),e.hasColors&&s._delayInfo.push(Ki.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(Ki.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(Ki.MatricesWeightsKind),s._delayLoadingFunction=Tr.ImportVertexData):Tr.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}class Cr{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new yr(e)}sampleFrame(e=je.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){const t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}}get averageFrameTime(){return this._rollingFrameTime.average}get averageFrameTimeVariance(){return this._rollingFrameTime.variance}get instantaneousFrameTime(){return this._rollingFrameTime.history(0)}get averageFPS(){return 1e3/this._rollingFrameTime.average}get instantaneousFPS(){const e=this._rollingFrameTime.history(0);return 0===e?0:1e3/e}get isSaturated(){return this._rollingFrameTime.isSaturated()}enable(){this._enabled=!0}disable(){this._enabled=!1,this._lastFrameTimeMs=null}get isEnabled(){return this._enabled}reset(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()}}class yr{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const e=this._samples[this._pos];t=e-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(e-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length}history(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;const t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]}isSaturated(){return this._sampleCount>=this._samples.length}reset(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0}_wrapPosition(e){const t=this._samples.length;return(e%t+t)%t}}function Ar(e,t,i=!1,s){switch(e){case 3:{const e=(ArrayBuffer,new Int8Array(t));return s&&e.set(new Int8Array(s)),e}case 0:{const e=(ArrayBuffer,new Uint8Array(t));return s&&e.set(new Uint8Array(s)),e}case 4:{const e=t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);return s&&e.set(new Int16Array(s)),e}case 5:case 8:case 9:case 10:case 2:{const e=t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);return s&&e.set(new Uint16Array(s)),e}case 6:{const e=t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);return s&&e.set(new Int32Array(s)),e}case 7:case 11:case 12:case 13:case 14:case 15:{const e=t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);return s&&e.set(new Uint32Array(s)),e}case 1:{const e=t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t);return s&&e.set(new Float32Array(s)),e}}const r=(ArrayBuffer,new Uint8Array(t));return s&&r.set(new Uint8Array(s)),r}function Rr(e,t,i){e._onCanvasFocus=()=>{e.onCanvasFocusObservable.notifyObservers(e)},e._onCanvasBlur=()=>{e.onCanvasBlurObservable.notifyObservers(e)},e._onCanvasContextMenu=t=>{e.disableContextMenu&&t.preventDefault()},t.addEventListener("focus",e._onCanvasFocus),t.addEventListener("blur",e._onCanvasBlur),t.addEventListener("contextmenu",e._onCanvasContextMenu),e._onBlur=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.disable(),e._windowIsBackground=!0},e._onFocus=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.enable(),e._windowIsBackground=!1},e._onCanvasPointerOut=i=>{document.elementFromPoint(i.clientX,i.clientY)!==t&&e.onCanvasPointerOutObservable.notifyObservers(i)};const s=e.getHostWindow();s&&"function"==typeof s.addEventListener&&(s.addEventListener("blur",e._onBlur),s.addEventListener("focus",e._onFocus)),t.addEventListener("pointerout",e._onCanvasPointerOut),i.doNotHandleTouchAction||function(e){e&&e.setAttribute&&(e.setAttribute("touch-action","none"),e.style.touchAction="none",e.style.webkitTapHighlightColor="transparent")}(t),!si.audioEngine&&i.audioEngine&&si.AudioEngineFactory&&(si.audioEngine=si.AudioEngineFactory(e.getRenderingCanvas(),e.getAudioContext(),e.getAudioDestination())),Xe()&&(e._onFullscreenChange=()=>{e.isFullscreen=!!document.fullscreenElement,e.isFullscreen&&e._pointerLockRequested&&t&&wr(t)},document.addEventListener("fullscreenchange",e._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",e._onFullscreenChange,!1),e._onPointerLockChange=()=>{e.isPointerLock=document.pointerLockElement===t},document.addEventListener("pointerlockchange",e._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",e._onPointerLockChange,!1)),e.enableOfflineSupport=void 0!==si.OfflineProviderFactory,e._deterministicLockstep=!!i.deterministicLockstep,e._lockstepMaxSteps=i.lockstepMaxSteps||0,e._timeStep=i.timeStep||1/60}function Ir(e,t){1===y.Instances.length&&si.audioEngine&&(si.audioEngine.dispose(),si.audioEngine=null);const i=e.getHostWindow();i&&"function"==typeof i.removeEventListener&&(i.removeEventListener("blur",e._onBlur),i.removeEventListener("focus",e._onFocus)),t&&(t.removeEventListener("focus",e._onCanvasFocus),t.removeEventListener("blur",e._onCanvasBlur),t.removeEventListener("pointerout",e._onCanvasPointerOut),t.removeEventListener("contextmenu",e._onCanvasContextMenu)),Xe()&&(document.removeEventListener("fullscreenchange",e._onFullscreenChange),document.removeEventListener("mozfullscreenchange",e._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",e._onFullscreenChange),document.removeEventListener("msfullscreenchange",e._onFullscreenChange),document.removeEventListener("pointerlockchange",e._onPointerLockChange),document.removeEventListener("mspointerlockchange",e._onPointerLockChange),document.removeEventListener("mozpointerlockchange",e._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",e._onPointerLockChange))}function Pr(e){const t=document.createElement("span");t.textContent="Hg",t.style.font=e;const i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";const s=document.createElement("div");s.style.whiteSpace="nowrap",s.appendChild(t),s.appendChild(i),document.body.appendChild(s);let r=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",r=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(s)}return{ascent:r,height:n,descent:n-r}}function Mr(e,t,i){return new Promise(((s,r)=>{const n=new Image;n.onload=()=>{n.decode().then((()=>{e.createImageBitmap(n,i).then((e=>{s(e)}))}))},n.onerror=()=>{r(`Error loading image ${n.src}`)},n.src=t}))}function Dr(e,t,i,s){const r=e.createCanvas(i,s).getContext("2d");if(!r)throw new Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(t,0,0),r.getImageData(0,0,i,s).data}function Or(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}function Nr(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}function wr(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}function Fr(){document.exitPointerLock&&document.exitPointerLock()}Yi.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode!==e){switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0}t||(this.depthCullingState.depthMask=0===e),this._alphaMode=e}else if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}},Yi.prototype._readTexturePixelsSync=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=c.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),s>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+s,e._hardwareTexture?.underlyingResource,r):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,e._hardwareTexture?.underlyingResource,r);let u=void 0!==e.type?this._getWebGLTextureType(e.type):c.UNSIGNED_BYTE;return a?n||(n=Ar(e.type,4*t*i)):u===c.UNSIGNED_BYTE?(n||(n=new Uint8Array(4*t*i)),u=c.UNSIGNED_BYTE):(n||(n=new Float32Array(4*t*i)),u=c.FLOAT),o&&this.flushFramebuffer(),c.readPixels(l,h,t,i,c.RGBA,u,n),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),n},Yi.prototype._readTexturePixels=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,s,r,n,o,a,l,h))},Yi.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let s;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),s=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,s,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},Yi.prototype.updateDynamicVertexBuffer=function(e,t,i,s){this.bindArrayBuffer(e),void 0===i&&(i=0);const r=t.byteLength||t.length;void 0===s||s>=r&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+s)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,s):new Uint8Array(t.buffer,t.byteOffset+i,s),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()},si.prototype.displayLoadingUI=function(){if(!We())return;const e=this.loadingScreen;e&&e.displayLoadingUI()},si.prototype.hideLoadingUI=function(){if(!We())return;const e=this._loadingScreen;e&&e.hideLoadingUI()},Object.defineProperty(si.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=si.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(si.prototype,"loadingUIText",{set:function(e){this.loadingScreen.loadingUIText=e},enumerable:!0,configurable:!0}),Object.defineProperty(si.prototype,"loadingUIBackgroundColor",{set:function(e){this.loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),si.prototype.getInputElement=function(){return this._renderingCanvas},si.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null},si.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null},si.prototype.getAspectRatio=function(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)},si.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)},si.prototype._verifyPointerLock=function(){this._onPointerLockChange?.()},si.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774)}this._alphaEquation=e}},si.prototype.getInputElement=function(){return this._renderingCanvas},si.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},si.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},si.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)},si.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)},si.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)},si.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)},si.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},si.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},si.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},si.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},si.prototype.getStencilMask=function(){return this._stencilState.stencilMask},si.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},si.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},si.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},si.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},si.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},si.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},si.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},si.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},si.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},si.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},si.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},si.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},si.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},si.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()},si.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)},si.prototype.setAlphaConstants=function(e,t,i,s){this._alphaState.setAlphaBlendConstants(e,t,i,s)},si.prototype.getAlphaMode=function(){return this._alphaMode},si.prototype.getAlphaEquation=function(){return this._alphaEquation},si.prototype.getRenderPassNames=function(){return this._renderPassNames},si.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]},si.prototype.createRenderPassId=function(e){const t=++si._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t},si.prototype.releaseRenderPassId=function(e){this._renderPassNames[e]=void 0;for(let t=0;tnew Lr(e,t,i);class Lr{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new g,this.onAudioLockedObservable=new g,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!We())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);const s=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{s&&s.canPlayType&&(s.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||s.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{s&&s.canPlayType&&s.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){if("running"===this._audioContext?.state)return this._hideMuteButton(),void(this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)));this._tryToRun?this._audioContext?.suspend().then((()=>{this._tryToRun=!1,this._triggerRunningState()})):this._triggerRunningState()}_resumeAudioContext(){return this._audioContext?.resume?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,J.Error("Web Audio: "+e.message)}}_triggerRunningState(){this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then((()=>{this._tryToRun=!1,this._muteButton&&this._hideMuteButton(),this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)})).catch((()=>{this._tryToRun=!1,this.unlocked=!1})))}_triggerSuspendedState(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()}_displayMuteButton(){if(this.useCustomUnlockedButton||this._muteButton)return;this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";const e=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",(()=>{this._triggerRunningState()}),!0),this._muteButton.addEventListener("click",(()=>{this.unlock()}),!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}}class Br extends Yi{static get NpmPackage(){return si.NpmPackage}static get Version(){return si.Version}static get Instances(){return y.Instances}static get LastCreatedEngine(){return y.LastCreatedEngine}static get LastCreatedScene(){return y.LastCreatedScene}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{this._loadFile(e,(e=>{s(e)}),void 0,t,i,((e,t)=>{r(t)}))}))}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return Pr(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(0!==this._frameHandler){this._frameHandler=0;const{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}enterPointerlock(){this._renderingCanvas&&wr(this._renderingCanvas)}exitPointerlock(){Fr()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){const t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,s,r,n=null){r=r||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const o=super.createShaderProgram(e,t,i,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),o}_createShaderProgram(e,t,i,s,r=null){const n=s.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");if(s.attachShader(n,t),s.attachShader(n,i),this.webGLVersion>1&&r){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=t}return s.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=s,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach((t=>{t.postProcesses.forEach((t=>{t._outputTexture===e&&(t._outputTexture=null)})),t.cameras.forEach((t=>{t._postProcesses.forEach((t=>{t&&t._outputTexture===e&&(t._outputTexture=null)}))}))}))}_rescaleTexture(e,t,i,s,r){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);const n=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});!this._rescalePostProcess&&Br._RescalePostProcessFactory&&(this._rescalePostProcess=Br._RescalePostProcessFactory(this)),this._rescalePostProcess&&(this._rescalePostProcess.externalTextureSamplerBinding=!0,this._rescalePostProcess.getEffect().executeWhenCompiled((()=>{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let o=i;o||(o=this.scenes[this.scenes.length-1]),o.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,s,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()})))}wrapWebGLTexture(e,t=!1,i=3,s=0,r=0){const n=new Hi(e,this._gl),o=new ti(this,ei.Unknown,!0);return o._hardwareTexture=n,o.baseWidth=s,o.baseHeight=r,o.width=s,o.height=r,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,s=0){const r=this._gl,n=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,o),l=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=r.TEXTURE_2D;e.isCube&&(h=r.TEXTURE_CUBE_MAP_POSITIVE_X+i),r.texImage2D(h,s,a,o,n,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void J.Error("WebGL 1 does not support texture comparison.");const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");const i=new Wi(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const s=this._gl;return new Promise(((r,n)=>{const o=()=>{const a=s.clientWaitSync(e,t,0);a!=s.WAIT_FAILED?a!=s.TIMEOUT_EXPIRED?r():setTimeout(o,i):n()};o()}))}_readPixelsAsync(e,t,i,s,r,n,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const a=this._gl,l=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.bufferData(a.PIXEL_PACK_BUFFER,o.byteLength,a.STREAM_READ),a.readPixels(e,t,i,s,r,n,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null);const h=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(a.flush(),this._clientWaitAsync(h,0,10).then((()=>(a.deleteSync(h),a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,o),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.deleteBuffer(l),o)))):null}dispose(){this._rescalePostProcess&&this._rescalePostProcess.dispose(),Ir(this,this._renderingCanvas),super.dispose()}}Br.ALPHA_DISABLE=0,Br.ALPHA_ADD=1,Br.ALPHA_COMBINE=2,Br.ALPHA_SUBTRACT=3,Br.ALPHA_MULTIPLY=4,Br.ALPHA_MAXIMIZED=5,Br.ALPHA_ONEONE=6,Br.ALPHA_PREMULTIPLIED=7,Br.ALPHA_PREMULTIPLIED_PORTERDUFF=8,Br.ALPHA_INTERPOLATE=9,Br.ALPHA_SCREENMODE=10,Br.DELAYLOADSTATE_NONE=0,Br.DELAYLOADSTATE_LOADED=1,Br.DELAYLOADSTATE_LOADING=2,Br.DELAYLOADSTATE_NOTLOADED=4,Br.NEVER=512,Br.ALWAYS=519,Br.LESS=513,Br.EQUAL=514,Br.LEQUAL=515,Br.GREATER=516,Br.GEQUAL=518,Br.NOTEQUAL=517,Br.KEEP=7680,Br.REPLACE=7681,Br.INCR=7682,Br.DECR=7683,Br.INVERT=5386,Br.INCR_WRAP=34055,Br.DECR_WRAP=34056,Br.TEXTURE_CLAMP_ADDRESSMODE=0,Br.TEXTURE_WRAP_ADDRESSMODE=1,Br.TEXTURE_MIRROR_ADDRESSMODE=2,Br.TEXTUREFORMAT_ALPHA=0,Br.TEXTUREFORMAT_LUMINANCE=1,Br.TEXTUREFORMAT_LUMINANCE_ALPHA=2,Br.TEXTUREFORMAT_RGB=4,Br.TEXTUREFORMAT_RGBA=5,Br.TEXTUREFORMAT_RED=6,Br.TEXTUREFORMAT_R=6,Br.TEXTUREFORMAT_RG=7,Br.TEXTUREFORMAT_RED_INTEGER=8,Br.TEXTUREFORMAT_R_INTEGER=8,Br.TEXTUREFORMAT_RG_INTEGER=9,Br.TEXTUREFORMAT_RGB_INTEGER=10,Br.TEXTUREFORMAT_RGBA_INTEGER=11,Br.TEXTURETYPE_UNSIGNED_BYTE=0,Br.TEXTURETYPE_UNSIGNED_INT=0,Br.TEXTURETYPE_FLOAT=1,Br.TEXTURETYPE_HALF_FLOAT=2,Br.TEXTURETYPE_BYTE=3,Br.TEXTURETYPE_SHORT=4,Br.TEXTURETYPE_UNSIGNED_SHORT=5,Br.TEXTURETYPE_INT=6,Br.TEXTURETYPE_UNSIGNED_INTEGER=7,Br.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,Br.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,Br.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,Br.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,Br.TEXTURETYPE_UNSIGNED_INT_24_8=12,Br.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,Br.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,Br.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,Br.TEXTURE_NEAREST_SAMPLINGMODE=1,Br.TEXTURE_BILINEAR_SAMPLINGMODE=2,Br.TEXTURE_TRILINEAR_SAMPLINGMODE=3,Br.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,Br.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,Br.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,Br.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,Br.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,Br.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,Br.TEXTURE_NEAREST_LINEAR=7,Br.TEXTURE_NEAREST_NEAREST=1,Br.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,Br.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,Br.TEXTURE_LINEAR_LINEAR=2,Br.TEXTURE_LINEAR_NEAREST=12,Br.TEXTURE_EXPLICIT_MODE=0,Br.TEXTURE_SPHERICAL_MODE=1,Br.TEXTURE_PLANAR_MODE=2,Br.TEXTURE_CUBIC_MODE=3,Br.TEXTURE_PROJECTION_MODE=4,Br.TEXTURE_SKYBOX_MODE=5,Br.TEXTURE_INVCUBIC_MODE=6,Br.TEXTURE_EQUIRECTANGULAR_MODE=7,Br.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,Br.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Br.SCALEMODE_FLOOR=1,Br.SCALEMODE_NEAREST=2,Br.SCALEMODE_CEILING=3;const Vr=B.Compose(w.One(),L.FromEulerAngles(0,Math.PI,0),w.Zero());class Ur extends De{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=!!(this._billboardMode&Ur.BILLBOARDMODE_USE_POSITION),this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==Ur.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t,!1),this._forward=new w(0,0,1),this._up=new w(0,1,0),this._right=new w(1,0,0),this._position=w.Zero(),this._rotation=w.Zero(),this._rotationQuaternion=null,this._scaling=w.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=Ur.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=B.Zero(),this._usePivotMatrix=!1,this._absolutePosition=w.Zero(),this._absoluteScaling=w.Zero(),this._absoluteRotationQuaternion=L.Identity(),this._pivotMatrix=B.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new g,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return w.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return w.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return w.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()}updatePoseMatrix(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=B.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==Ur.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this._infiniteDistance||this._position._isDirty||this._scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)}_initCache(){super._initCache();const e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1,e.useBillboardPath=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=B.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const s=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);s&&i&&i(this,s);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(s,t,i);return s}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||L.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,s;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],s=arguments[2]}else t=e.x,i=e.y,s=e.z;if(this.parent){const e=U.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),w.TransformCoordinatesFromFloatsToRef(t,i,s,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=s;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=w.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=U.Matrix[0];return this._localMatrix.invertToRef(e),w.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=w.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,s=0,r=Fs.LOCAL){const n=Ur._LookAtVectorCache,o=r===Fs.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,n),this.setDirection(n,t,i,s),r===Fs.WORLD&&this.parent)if(this.rotationQuaternion){const e=U.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=U.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=U.Quaternion[0];L.FromEulerVectorToRef(this.rotation,e);const t=U.Matrix[0];e.toRotationMatrix(t);const i=U.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=w.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return w.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,s=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,n);return this.rotationQuaternion?L.RotationYawPitchRollToRef(r+t,o+i,s,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=r+t,this.rotation.z=s),this}setPivotPoint(e,t=Fs.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==Fs.WORLD){const t=U.Matrix[0];i.invertToRef(t),e=w.TransformCoordinates(e,t)}return this.setPivotMatrix(B.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=w.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){const e=w.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),w.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;const s=U.Quaternion[0],r=U.Vector3[0],n=U.Vector3[1],o=U.Matrix[1];B.IdentityToRef(o);const a=U.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=Ur._TmpRotation,L.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),B.ComposeToRef(this.scaling,l,this.position,a),this.parent&&a.multiplyToRef(this.parent.computeWorldMatrix(!0),a),e&&(e.computeWorldMatrix(!0).invertToRef(o),a.multiplyToRef(o,a)),a.decompose(n,s,r,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(s):s.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(r),this.parent=e,i&&this.setPivotMatrix(B.Identity()),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=e?this._currentParentWhenAttachingToBone:null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){let s;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==Fs.LOCAL){if(this.parent){const i=this.parent.getWorldMatrix(),s=U.Matrix[0];i.invertToRef(s),e=w.TransformNormal(e,s),i.determinant()<0&&(t*=-1)}s=L.RotationAxisToRef(e,t,Ur._RotationAxisCache),s.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else s=L.RotationAxisToRef(e,t,Ur._RotationAxisCache),this.rotationQuaternion.multiplyToRef(s,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=L.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const s=U.Vector3[0],r=U.Vector3[1],n=U.Vector3[2],o=U.Quaternion[0],a=U.Matrix[0],l=U.Matrix[1],h=U.Matrix[2],c=U.Matrix[3];return e.subtractToRef(this.position,s),B.TranslationToRef(s.x,s.y,s.z,a),B.TranslationToRef(-s.x,-s.y,-s.z,l),B.RotationAxisToRef(t,i,h),l.multiplyToRef(h,c),c.multiplyToRef(a,c),c.decompose(r,o,n),this.position.addInPlace(n),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const s=e.scale(t);if(i&&i!==Fs.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(s));else{const e=this.getPositionExpressedInLocalSpace().add(s);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let s;this.rotationQuaternion?s=this.rotationQuaternion:(s=U.Quaternion[1],L.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,s));const r=U.Quaternion[0];return L.RotationYawPitchRollToRef(t,e,i,r),s.multiplyInPlace(r),this.rotationQuaternion||s.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==Ur.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const r=this._getEffectiveParent(),n=Ur._TmpScaling;let o,a=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new w(e.m[12],e.m[13],e.m[14]);a=Ur._TmpTranslation,a.copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,o=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(L.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(o=Ur._TmpRotation,L.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,o)),this._usePivotMatrix){const e=U.Matrix[1];B.ScalingToRef(n.x,n.y,n.z,e);const t=U.Matrix[0];o.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,U.Matrix[4]),U.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(a.x,a.y,a.z)}else B.ComposeToRef(n,o,a,this._localMatrix);if(r&&r.getWorldMatrix){if(e&&r.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),U.Matrix[7])}else U.Matrix[7].copyFrom(r.getWorldMatrix());const e=U.Vector3[5],t=U.Vector3[6],i=U.Quaternion[0];U.Matrix[7].decompose(t,i,e),B.ScalingToRef(t.x,t.y,t.z,U.Matrix[7]),U.Matrix[7].setTranslation(e),Ur.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(U.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),U.Matrix[6]),U.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(r.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){const e=U.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),U.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&U.Matrix[1].multiplyToRef(Vr,U.Matrix[1]),U.Matrix[1].setTranslationFromFloats(0,0,0),U.Matrix[1].invertToRef(U.Matrix[0]),(this.billboardMode&Ur.BILLBOARDMODE_ALL)!==Ur.BILLBOARDMODE_ALL){U.Matrix[0].decompose(void 0,U.Quaternion[0],void 0);const e=U.Vector3[1];U.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Ur.BILLBOARDMODE_X)!==Ur.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Ur.BILLBOARDMODE_Y)!==Ur.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Ur.BILLBOARDMODE_Z)!==Ur.BILLBOARDMODE_Z&&(e.z=0),B.RotationYawPitchRollToRef(e.y,e.x,e.z,U.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(U.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(U.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){const e=U.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(U.Matrix[1]);const s=U.Vector3[1];w.TransformCoordinatesToRef(i,U.Matrix[1],s),s.normalize();const r=-Math.atan2(s.z,s.x)+Math.PI/2,n=Math.sqrt(s.x*s.x+s.z*s.z),o=-Math.atan2(s.y,n);if(L.RotationYawPitchRollToRef(r,o,0,U.Quaternion[0]),(this.billboardMode&Ur.BILLBOARDMODE_ALL)!==Ur.BILLBOARDMODE_ALL){const e=U.Vector3[1];U.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Ur.BILLBOARDMODE_X)!==Ur.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Ur.BILLBOARDMODE_Y)!==Ur.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Ur.BILLBOARDMODE_Z)!==Ur.BILLBOARDMODE_Z&&(e.z=0),B.RotationYawPitchRollToRef(e.y,e.x,e.z,U.Matrix[0])}else B.FromQuaternionToRef(U.Quaternion[0],U.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(U.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(U.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):r&&r._nonUniformScaling?this._updateNonUniformScalingState(r._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=B.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;tnew Ur(e,this.getScene())),this);if(s.name=e,s.id=e,t&&(s.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;inew Ur(e.name,t)),e,t,i);if(e.localMatrix?s.setPreTransformMatrix(B.FromArray(e.localMatrix)):e.pivotMatrix&&s.setPivotMatrix(B.FromArray(e.pivotMatrix)),s.setEnabled(e.isEnabled),s._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let t=0;t(!t||t(e))&&e instanceof Ur)),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const e=this.getChildTransformNodes(!0);for(const t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let s=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(s=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,i),o=n.max.subtract(n.min),a=Math.max(o.x,o.y,o.z);if(0===a)return this;const l=1/a;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&s&&this.rotation.copyFrom(s)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}Ur.BILLBOARDMODE_NONE=0,Ur.BILLBOARDMODE_X=1,Ur.BILLBOARDMODE_Y=2,Ur.BILLBOARDMODE_Z=4,Ur.BILLBOARDMODE_ALL=7,Ur.BILLBOARDMODE_USE_POSITION=128,Ur.BillboardUseParentOrientation=!1,Ur._TmpRotation=L.Zero(),Ur._TmpScaling=w.Zero(),Ur._TmpTranslation=w.Zero(),Ur._LookAtVectorCache=new w(0,0,0),Ur._RotationAxisCache=new L,ae([ve("position")],Ur.prototype,"_position",void 0),ae([ve("rotation")],Ur.prototype,"_rotation",void 0),ae([ue(10,"rotationQuaternion")],Ur.prototype,"_rotationQuaternion",void 0),ae([ve("scaling")],Ur.prototype,"_scaling",void 0),ae([pe("billboardMode")],Ur.prototype,"_billboardMode",void 0),ae([pe()],Ur.prototype,"scalingDeterminant",void 0),ae([pe("infiniteDistance")],Ur.prototype,"_infiniteDistance",void 0),ae([pe()],Ur.prototype,"ignoreNonUniformScaling",void 0),ae([pe()],Ur.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class kr{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new w(0,0,0),this._diffPositionForCollisions=new w(0,0,0),this._collisionResponse=!0}}class Gr{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=w.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class zr{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Gr,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=null,this._currentLODIsUpToDate=!1,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new kr,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class Wr extends Ur{static get BILLBOARDMODE_NONE(){return Ur.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return Ur.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return Ur.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return Ur.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return Ur.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return Ur.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return!!super._updateNonUniformScalingState(e)&&(this._markSubMeshesAsMiscDirty(),!0)}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;const t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty((e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()}))}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){return this._internalAbstractMeshDataInfo._materialForRenderPass?.[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}get _positions(){return null}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new zr,this._waitingMaterialId=null,this.cullingStrategy=Wr.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new g,this.onCollisionPositionChangeObservable=new g,this.onMaterialChangedObservable=new g,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this.isVisible=!0,this.isPickable=!0,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=Y.Red(),this.outlineWidth=.02,this.overlayColor=Y.Red(),this.overlayAlpha=.5,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.alwaysSelectAsActiveMesh=!1,this.doNotSyncBoundingInfo=!1,this.actionManager=null,this.ellipsoid=new w(.5,1,.5),this.ellipsoidOffset=new w(0,0,0),this.edgesWidth=1,this.edgesColor=new j(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new g,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Br.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new ji(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case ws.Aggressive:this.doNotSyncBoundingInfo=!0;case ws.Intermediate:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){const t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()}getMeshUniformBuffer(){return this._uniformBuffer}getClassName(){return"AbstractMesh"}toString(e){let t="Name: "+this.name+", isInstance: "+("InstancedMesh"!==this.getClassName()?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);const i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==Ur.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),null!==this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes){for(const e of this.subMeshes)e._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e);let s=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;s=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(s)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let i=0;it.markAsLightDirty(e)))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty((e=>e.markAsAttributesDirty()))}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty((e=>e.markAsMiscDirty()))}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,s){return this}updateVerticesData(e,t,i,s){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new fr(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(Ki.MatricesIndicesKind)&&this.isVerticesDataPresent(Ki.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===Ur.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){const s=new B;(this.rotationQuaternion?this.rotationQuaternion:L.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(s);const r=w.Zero(),n=this.definedFacingForward?-1:1;return w.TransformCoordinatesFromFloatsToRef(e*n,t,i*n,s,r),r}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){const s=this.definedFacingForward?1:-1;return new w(e*s,t,i*s)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){const i=mr(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new fr(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t4,n=r?this.getVerticesData(Ki.MatricesIndicesExtraKind):null,o=r?this.getVerticesData(Ki.MatricesWeightsExtraKind):null,a=this.skeleton.getTransformMatrices(this),l=U.Vector3[0],h=U.Matrix[0],c=U.Matrix[1];let u=0;for(let d=0;d0&&(B.FromFloat32ArrayToRefScaled(a,Math.floor(16*e[u+p]),f,c),h.addToSelf(c));if(r)for(p=0;p<4;p++)f=o[u+p],f>0&&(B.FromFloat32ArrayToRefScaled(a,Math.floor(16*n[u+p]),f,c),h.addToSelf(c));s===Ki.NormalKind?w.TransformNormalFromFloatsToRef(i[d],i[d+1],i[d+2],h,l):w.TransformCoordinatesFromFloatsToRef(i[d],i[d+1],i[d+2],h,l),l.toArray(i,d),s===Ki.PositionKind&&this._positions&&this._positions[d/3].copyFrom(l)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,Ki.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,Ki.PositionKind)}_getPositionData(e,t){let i=this.getVerticesData(Ki.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),i&&(e&&this.skeleton||t&&this.morphTargetManager)){if(i=i.slice(),this._generatePointsArray(),this._positions){const e=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(e.length);for(let t=0;t1||!s.IsGlobal)&&s.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const s=this.getBoundingInfo(),r=e.getBoundingInfo();if(s.intersects(r,t))return!0;if(i)for(const i of this.getChildMeshes())if(i.intersectsMesh(e,t,!0))return!0;return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);const t=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=t.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,t.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const i=e.verticesStart,s=e.verticesStart+e.verticesCount;for(let r=i;r1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=U.Matrix[0],i=U.Matrix[1];return B.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,s=!1,r,n=!1){const o=new qi,a=this.getClassName(),l="InstancedLinesMesh"===a||"LinesMesh"===a||"GreasedLineMesh"===a?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes)return o;if(!(n||e.intersectsSphere(h.boundingSphere,l)&&e.intersectsBox(h.boundingBox,l)))return o;if(s)return o.hit=!n,o.pickedMesh=n?null:this,o.distance=n?0:w.Distance(e.origin,h.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let c=null;const u=this._scene.getIntersectingSubMeshCandidates(this,e),d=u.length;let p=!1;for(let e=0;e1&&!n&&!r.canIntersects(e))continue;const o=r.intersects(e,this._positions,this.getIndices(),t,i);if(o&&(t||!c||o.distancee!==this&&e.actionManager===this.actionManager))||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(this),-1!==t&&e.excludedMeshes.splice(t,1);const i=e.getShadowGenerators();if(i){const e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){const e=i.value.getShadowMap();e&&e.renderList&&(t=e.renderList.indexOf(this),-1!==t&&e.renderList.splice(t,1))}}})),"InstancedMesh"===this.getClassName()&&"InstancedLinesMesh"===this.getClassName()||this.releaseSubMeshes();const r=s.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,r.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),r.wipeCaches(),s.removeMesh(this),this._parentContainer){const e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:w.Zero()}e.depthSortedFacets=[];for(let t=0;tT?r.maximum.x-r.minimum.x:T,e.bbSize.y=r.maximum.y-r.minimum.y>T?r.maximum.y-r.minimum.y:T,e.bbSize.z=r.maximum.z-r.minimum.z>T?r.maximum.z-r.minimum.z:T;let n=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(n=n>e.bbSize.z?n:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/n),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/n),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/n),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=r,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),w.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,s&&Tr.ComputeNormals(t,i,s,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let s=0;sr.subDiv.max||o<0||o>r.subDiv.max||a<0||a>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*o+r.subDiv.max*r.subDiv.max*a]}getClosestFacetAtCoordinates(e,t,i,s,r=!1,n=!0){const o=this.getWorldMatrix(),a=U.Matrix[5];o.invertToRef(a);const l=U.Vector3[8];w.TransformCoordinatesFromFloatsToRef(e,t,i,a,l);const h=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,s,r,n);return s&&w.TransformCoordinatesFromFloatsToRef(s.x,s.y,s.z,o,s),h}getClosestFacetAtLocalCoordinates(e,t,i,s,r=!1,n=!0){let o=null,a=0,l=0,h=0,c=0,u=0,d=0,p=0,f=0;const _=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;let v,x,T,S=Number.MAX_VALUE,E=S;for(let b=0;b=0||r&&!n&&c<=0)&&(c=x.x*T.x+x.y*T.y+x.z*T.z,u=-(x.x*e+x.y*t+x.z*i-c)/(x.x*x.x+x.y*x.y+x.z*x.z),d=e+x.x*u,p=t+x.y*u,f=i+x.z*u,a=d-e,l=p-t,h=f-i,E=a*a+l*l+h*h,Ee.emitter===this))}}Wr.OCCLUSION_TYPE_NONE=0,Wr.OCCLUSION_TYPE_OPTIMISTIC=1,Wr.OCCLUSION_TYPE_STRICT=2,Wr.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,Wr.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,Wr.CULLINGSTRATEGY_STANDARD=0,Wr.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Wr.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Wr.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,u("BABYLON.AbstractMesh",Wr);class Hr{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681}get func(){return this._func}set func(e){this._func=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){Pe.Clone((()=>e),this)}serialize(){return Pe.Serialize(this)}parse(e,t,i){Pe.Parse((()=>this),e,t,i)}}var Xr,Yr;function jr(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}function $r(e,t,i){const s=!!(e.clipPlane??t.clipPlane),r=!!(e.clipPlane2??t.clipPlane2),n=!!(e.clipPlane3??t.clipPlane3),o=!!(e.clipPlane4??t.clipPlane4),a=!!(e.clipPlane5??t.clipPlane5),l=!!(e.clipPlane6??t.clipPlane6);s&&i.push("#define CLIPPLANE"),r&&i.push("#define CLIPPLANE2"),n&&i.push("#define CLIPPLANE3"),o&&i.push("#define CLIPPLANE4"),a&&i.push("#define CLIPPLANE5"),l&&i.push("#define CLIPPLANE6")}function Kr(e,t,i){let s=t.clipPlane??i.clipPlane;qr(e,"vClipPlane",s),s=t.clipPlane2??i.clipPlane2,qr(e,"vClipPlane2",s),s=t.clipPlane3??i.clipPlane3,qr(e,"vClipPlane3",s),s=t.clipPlane4??i.clipPlane4,qr(e,"vClipPlane4",s),s=t.clipPlane5??i.clipPlane5,qr(e,"vClipPlane5",s),s=t.clipPlane6??i.clipPlane6,qr(e,"vClipPlane6",s)}function qr(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}ae([pe()],Hr.prototype,"func",null),ae([pe()],Hr.prototype,"funcRef",null),ae([pe()],Hr.prototype,"funcMask",null),ae([pe()],Hr.prototype,"opStencilFail",null),ae([pe()],Hr.prototype,"opDepthFail",null),ae([pe()],Hr.prototype,"opStencilDepthPass",null),ae([pe()],Hr.prototype,"mask",null),ae([pe()],Hr.prototype,"enabled",null),(Yr=Xr||(Xr={}))[Yr.Created=1]="Created",Yr[Yr.Disposed=2]="Disposed",Yr[Yr.GetDefineNames=4]="GetDefineNames",Yr[Yr.PrepareUniformBuffer=8]="PrepareUniformBuffer",Yr[Yr.IsReadyForSubMesh=16]="IsReadyForSubMesh",Yr[Yr.PrepareDefines=32]="PrepareDefines",Yr[Yr.BindForSubMesh=64]="BindForSubMesh",Yr[Yr.PrepareEffect=128]="PrepareEffect",Yr[Yr.GetAnimatables=256]="GetAnimatables",Yr[Yr.GetActiveTextures=512]="GetActiveTextures",Yr[Yr.HasTexture=1024]="HasTexture",Yr[Yr.FillRenderTargetTextures=2048]="FillRenderTargetTextures",Yr[Yr.HasRenderTargetTextures=4096]="HasRenderTargetTextures",Yr[Yr.HardBindForSubMesh=8192]="HardBindForSubMesh";const Qr=Y.Black(),Zr={NUM_MORPH_INFLUENCERS:0};function Jr(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=i.activeCamera;1===e.mode&&J.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}function en(e,t,i,s=!1){i&&e.fogEnabled&&(!t||t.applyFog)&&0!==e.fogMode&&(i.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),s?(e.fogColor.toLinearSpaceToRef(Qr,e.getEngine().useExactSrgbConversions),i.setColor3("vFogColor",Qr)):i.setColor3("vFogColor",e.fogColor))}function tn(e,t,i){Zr.NUM_MORPH_INFLUENCERS=i,sn(e,t,Zr)}function sn(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&y.LastCreatedEngine){const r=y.LastCreatedEngine.getCaps().maxVertexAttribs,n=t.morphTargetManager;if(n?.isUsingTextureForTargets)return;const o=n&&n.supportsNormals&&i.NORMAL,a=n&&n.supportsTangents&&i.TANGENT,l=n&&n.supportsUVs&&i.UV1;for(let i=0;ir&&J.Error("Cannot add more vertex attributes for mesh "+t.name)}}function rn(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}function nn(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}function on(e,t){t.bindToEffect(e,"Scene")}function an(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}function ln(e,t,i){const s=e.getTextureMatrix();t.updateMatrix(i+"Matrix",s)}function hn(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}function cn(e,t,i){var s;if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const r=e.skeleton;if(r.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){const i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{const n=r.getTransformMatrices(e);n&&(t.setMatrices("mBones",n),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=n.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),s=n,i.previousBones[e.uniqueId].set(s)))}}}function un(e,t,i,s,r,n=!0){e._bindLight(t,i,s,r,n)}function dn(e,t,i,s,r=4){const n=Math.min(t.lightSources.length,r);for(let r=0;r0&&(s.addCPUSkinningFallback(0,t),e.push("matricesIndices"),e.push("matricesWeights"),i.NUM_BONE_INFLUENCERS>4&&(e.push("matricesIndicesExtra"),e.push("matricesWeightsExtra")))}function fn(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&rn(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push("instanceColor")}function _n(e,t,i=4,s=0){let r=0;for(let n=0;n0&&(r=s+n,t.addFallback(r,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(s,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(s,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(s,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(s,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(s,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(s,"SHADOWCLOSEESM"+n));return r++}function mn(e,t){return t.fogEnabled&&e.applyFog&&0!==t.fogMode}function gn(e,t,i,s,r,n,o,a=!1){o._areMiscDirty&&(o.LOGARITHMICDEPTH=i,o.POINTSIZE=s,o.FOG=r&&mn(e,t),o.NONUNIFORMSCALING=e.nonUniformScaling,o.ALPHATEST=n,o.DECAL_AFTER_DETAIL=a)}function vn(e,t,i,s,r=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let o=0;const a={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n)for(const n of t.lightSources)if(xn(e,t,n,o,i,s,a),o++,o===r)break;i.SPECULARTERM=a.specularEnabled,i.SHADOWS=a.shadowEnabled;for(let e=o;e0&&(o.shadowEnabled=!0,t.prepareDefines(r,s))}}i.lightmapMode!=Os.LIGHTMAP_DEFAULT?(o.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+s]=!0,r["LIGHTMAPNOSPECULAR"+s]=i.lightmapMode==Os.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+s]=!1,r["LIGHTMAPNOSPECULAR"+s]=!1)}function Tn(e,t,i,s,r,n=null,o=!1){let a=In(e,s);!1!==n&&(a=function(e,t,i){let s=!1;const r=!!(e.clipPlane??t.clipPlane),n=!!(e.clipPlane2??t.clipPlane2),o=!!(e.clipPlane3??t.clipPlane3),a=!!(e.clipPlane4??t.clipPlane4),l=!!(e.clipPlane5??t.clipPlane5),h=!!(e.clipPlane6??t.clipPlane6);return i.CLIPPLANE!==r&&(i.CLIPPLANE=r,s=!0),i.CLIPPLANE2!==n&&(i.CLIPPLANE2=n,s=!0),i.CLIPPLANE3!==o&&(i.CLIPPLANE3=o,s=!0),i.CLIPPLANE4!==a&&(i.CLIPPLANE4=a,s=!0),i.CLIPPLANE5!==l&&(i.CLIPPLANE5=l,s=!0),i.CLIPPLANE6!==h&&(i.CLIPPLANE6=h,s=!0),s}(i,e,s)),s.DEPTHPREPASS!==!t.getColorWrite()&&(s.DEPTHPREPASS=!s.DEPTHPREPASS,a=!0),s.INSTANCES!==r&&(s.INSTANCES=r,a=!0),s.THIN_INSTANCES!==o&&(s.THIN_INSTANCES=o,a=!0),a&&s.markAsUnprocessed()}function Sn(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;const s=e.getScene().prePassRenderer;if(s&&s.enabled){const i=-1===s.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}function En(e,t){const i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.NUM_MORPH_INFLUENCERS=i.numMaxInfluencers||i.numInfluencers,t.MORPHTARGETS=t.NUM_MORPH_INFLUENCERS>0,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}function bn(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}function Cn(e,t,i,s,r=!1,n=!0,o=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent("normal"),t._needNormals&&e.isVerticesDataPresent("tangent")&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){const i=e.useVertexColors&&e.isVerticesDataPresent("color");t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&n}return e.isVerticesDataPresent("instanceColor")&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),s&&Sn(e,t),r&&En(e,t),o&&bn(e,t),!0}function yn(e,t){if(e.activeCamera){const i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}function An(e,t,i){const s=t.ORDER_INDEPENDENT_TRANSPARENCY,r=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,s===t.ORDER_INDEPENDENT_TRANSPARENCY&&r===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}function Rn(e,t,i){const s=t.PREPASS;if(!t._arePrePassDirty)return;const r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let i=0;i{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const s=t||y.LastCreatedScene;s&&(this._scene=s,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||Ii.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new gr(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=Dn.ClockWiseSideOrientation:this.sideOrientation=Dn.CounterClockWiseSideOrientation,this._uniformBuffer=new ji(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),Dn.OnEventObservable.notifyObservers(this,Xr.Created))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const s=t.materialDefines;return!!s&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===Dn.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===Dn.MATERIAL_OPAQUE||this._transparencyMode===Dn.MATERIAL_ALPHATEST}needAlphaBlending(){return!this._disableAlphaBlending&&this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1||!this._disableAlphaBlending&&(e.hasVertexAlpha||this.needAlphaBlending())}needAlphaTesting(){return!!this._forceAlphaTest}_shouldTurnAlphaTestOn(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)if(t.getMaterial()===this)for(const i of t._drawWrappers)i&&this._materialContext===i.materialContext&&(i._wasPreviouslyReady=!1,i._wasPreviouslyUsingInstances=null,i._forceRebindOnNextCall=e);e&&this.markAsDirty(Dn.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),s=(null==t?this.sideOrientation:t)===Dn.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(Xr.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const s=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),s._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,on(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),this._scene._cachedVisibility=e?e.visibility:1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){const e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){const e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(Xr.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(Xr.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(Xr.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),Dn._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(const t of this.pluginManager._plugins){const i=e.pluginManager.getPlugin(t.name);i&&t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const i=this.meshMap[t];i&&e.push(i)}return e}return this._scene.meshes.filter((e=>e.material===this))}forceCompilation(e,t,i,s){const r={clipPlane:!1,useInstances:!1,...i},n=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const a=()=>{if(!this._scene||!this._scene.getEngine())return;const i=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new Ps(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,n=null;if(e.subMeshes){const t=new vr(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,r.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?n=t.effect.getCompilationError():(i=!1,setTimeout(a,16)))}i&&(this.allowShaderHotSwapping=o,n&&s&&s(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(a,16);r.clipPlane&&(n.clipPlane=i)};a()}forceCompilationAsync(e,t){return new Promise(((i,s)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{s(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(Dn._DirtyCallbackArray.length=0,e&Dn.TextureDirtyFlag&&Dn._DirtyCallbackArray.push(Dn._TextureDirtyCallBack),e&Dn.LightDirtyFlag&&Dn._DirtyCallbackArray.push(Dn._LightsDirtyCallBack),e&Dn.FresnelDirtyFlag&&Dn._DirtyCallbackArray.push(Dn._FresnelDirtyCallBack),e&Dn.AttributesDirtyFlag&&Dn._DirtyCallbackArray.push(Dn._AttributeDirtyCallBack),e&Dn.MiscDirtyFlag&&Dn._DirtyCallbackArray.push(Dn._MiscDirtyCallBack),e&Dn.PrePassDirtyFlag&&Dn._DirtyCallbackArray.push(Dn._PrePassDirtyCallBack),Dn._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(Dn._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const e of t.subMeshes)e.getMaterial()===this&&e.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const t=this.getScene().meshes;for(const i of t)if(i.subMeshes)for(const t of i.subMeshes)if(t.getMaterial(!1)===this)for(const i of t._drawWrappers)i&&i.defines&&i.defines.markAllAsDirty&&this._materialContext===i.materialContext&&e(i.defines)}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(Dn._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(Dn._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(Dn._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(Dn._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(Dn._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(Dn._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(Dn._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(Dn._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(Dn._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(Dn._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==ws.BackwardCompatible){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce((()=>{this.checkReadyOnlyOnce=!1}));this.onDisposeObservable.add((()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)}))}}setPrePassRenderer(e){return!1}dispose(e,t,i){const s=this.getScene();if(s.stopAnimation(this),s.freeProcessedMaterials(),s.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(Xr.Disposed,this._eventInfo),this._parentContainer){const e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i)if(this.meshMap)for(const t in this.meshMap){const i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{const t=s.meshes;for(const i of t)i.material!==this||i.sourceMesh||(i.material=null,this.releaseVertexArrayObject(i,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const i=e.geometry;if(i)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const s of e.subMeshes)i._releaseVertexArrayObject(s.effect),t&&s.effect&&s.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=Pe.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(const t of this.pluginManager._plugins)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,i){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return J.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else e.customType="BABYLON.StandardMaterial";const s=Ii.Instantiate(e.customType).Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _ParsePlugins(e,t,i,s){if(e.plugins)for(const r in e.plugins){const n=e.plugins[r];let o=t.pluginManager?.getPlugin(n.name);if(!o){const e=Ii.Instantiate("BABYLON."+r);e&&(o=new e(t))}o?.parse(n,i,s)}}}Dn.TriangleFillMode=0,Dn.WireFrameFillMode=1,Dn.PointFillMode=2,Dn.PointListDrawMode=3,Dn.LineListDrawMode=4,Dn.LineLoopDrawMode=5,Dn.LineStripDrawMode=6,Dn.TriangleStripDrawMode=7,Dn.TriangleFanDrawMode=8,Dn.ClockWiseSideOrientation=0,Dn.CounterClockWiseSideOrientation=1,Dn.TextureDirtyFlag=1,Dn.LightDirtyFlag=2,Dn.FresnelDirtyFlag=4,Dn.AttributesDirtyFlag=8,Dn.MiscDirtyFlag=16,Dn.PrePassDirtyFlag=32,Dn.AllDirtyFlag=63,Dn.MATERIAL_OPAQUE=0,Dn.MATERIAL_ALPHATEST=1,Dn.MATERIAL_ALPHABLEND=2,Dn.MATERIAL_ALPHATESTANDBLEND=3,Dn.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,Dn.MATERIAL_NORMALBLENDMETHOD_RNM=1,Dn.OnEventObservable=new g,Dn._AllDirtyCallBack=e=>e.markAllAsDirty(),Dn._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),Dn._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),Dn._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),Dn._MiscDirtyCallBack=e=>e.markAsMiscDirty(),Dn._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),Dn._LightsDirtyCallBack=e=>e.markAsLightDirty(),Dn._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),Dn._FresnelAndMiscDirtyCallBack=e=>{Dn._FresnelDirtyCallBack(e),Dn._MiscDirtyCallBack(e)},Dn._TextureAndMiscDirtyCallBack=e=>{Dn._TextureDirtyCallBack(e),Dn._MiscDirtyCallBack(e)},Dn._DirtyCallbackArray=[],Dn._RunDirtyCallBacks=e=>{for(const t of Dn._DirtyCallbackArray)t(e)},ae([pe()],Dn.prototype,"id",void 0),ae([pe()],Dn.prototype,"uniqueId",void 0),ae([pe()],Dn.prototype,"name",void 0),ae([pe()],Dn.prototype,"metadata",void 0),ae([pe()],Dn.prototype,"checkReadyOnEveryCall",void 0),ae([pe()],Dn.prototype,"checkReadyOnlyOnce",void 0),ae([pe()],Dn.prototype,"state",void 0),ae([pe("alpha")],Dn.prototype,"_alpha",void 0),ae([pe("backFaceCulling")],Dn.prototype,"_backFaceCulling",void 0),ae([pe("cullBackFaces")],Dn.prototype,"_cullBackFaces",void 0),ae([pe()],Dn.prototype,"sideOrientation",void 0),ae([pe("alphaMode")],Dn.prototype,"_alphaMode",void 0),ae([pe()],Dn.prototype,"_needDepthPrePass",void 0),ae([pe()],Dn.prototype,"disableDepthWrite",void 0),ae([pe()],Dn.prototype,"disableColorWrite",void 0),ae([pe()],Dn.prototype,"forceDepthWrite",void 0),ae([pe()],Dn.prototype,"depthFunction",void 0),ae([pe()],Dn.prototype,"separateCullingPass",void 0),ae([pe("fogEnabled")],Dn.prototype,"_fogEnabled",void 0),ae([pe()],Dn.prototype,"pointSize",void 0),ae([pe()],Dn.prototype,"zOffset",void 0),ae([pe()],Dn.prototype,"zOffsetUnits",void 0),ae([pe()],Dn.prototype,"pointsCloud",null),ae([pe()],Dn.prototype,"fillMode",null),ae([pe()],Dn.prototype,"useLogarithmicDepth",null),ae([pe()],Dn.prototype,"transparencyMode",null);class On extends Dn{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);return this._markAllSubMeshesAsTexturesDirty(),r}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map((e=>e?e.getActiveTextures():[])))}hasTexture(e){if(super.hasTexture(e))return!0;for(let t=0;t=0&&s.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new On(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,Re&&Re.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}u("BABYLON.MultiMaterial",On);class Nn{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class wn{}class Fn{constructor(){this.visibleInstances={},this.batchCache=new Ln,this.batchCacheReplacementModeInFrozenMode=new Ln,this.instancesBufferSize=2048}}class Ln{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class Bn{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class Vn{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}}class Un extends Wr{static _GetDefaultSideOrientation(e){return e||Un.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(Ki.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(Ki.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new g),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new g),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new g),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new g),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new g),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}constructor(e,t=null,i=null,s=null,r,n=!0){if(super(e,t),this._internalMeshDataInfo=new Vn,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new Fn,this._thinInstanceDataStorage=new Bn,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=Un.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,i)=>{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},s){if(s._geometry&&s._geometry.applyToMesh(this),se.DeepCopy(s,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=s,t.useClonedMeshMap&&(s._internalMeshDataInfo.meshMap||(s._internalMeshDataInfo.meshMap={}),s._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=s._originalBuilderSideOrientation,this._creationDataStorage=s._creationDataStorage,s._ranges){const e=s._ranges;for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(s.metadata&&s.metadata.clone?this.metadata=s.metadata.clone():this.metadata=s.metadata,this._internalMetadata=s._internalMetadata,Re&&Re.HasTags(s)&&Re.AddTagsTo(this,Re.GetTags(s,!0)),this.setEnabled(s.isEnabled(!1)),this.parent=s.parent,this.setPivotMatrix(s.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=e+"."+s.id,this.material=s.material,!r){const t=s.getDescendants(!0);for(let i=0;i{e.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add((()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))})))},this.onMeshReadyObservable=new g(this._internalMeshDataInfo._onMeshReadyObserverAdded),s&&s.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){const s=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));s.parent=e||this.parent,s.position=this.position.clone(),s.scaling=this.scaling.clone(),this.rotationQuaternion?s.rotationQuaternion=this.rotationQuaternion.clone():s.rotation=this.rotation.clone(),i&&i(this,s);for(const e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===s.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(s,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:s},i):e.instantiateHierarchy(s,t,i);return s}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort(((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0))}addLODLevel(e,t){if(t&&t._masterMesh)return J.Warn("You cannot use a mesh as LOD level twice"),this;const i=new Nn(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let i=0;io*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let e=0;e0||this.hasThinInstances);this.computeWorldMatrix();const n=this.material||s.defaultMaterial;if(n)if(n._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,r))return!1}else if(!t.isReady(this,r))return!1}else if(!n.isReady(this,r))return!1;const o=i.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const s=t.values();for(let e=s.next();!0!==e.done;e=s.next()){const t=e.value;if(t&&(!t.getShadowMap()?.renderList||t.getShadowMap()?.renderList&&-1!==t.getShadowMap()?.renderList?.indexOf(this))){const e=t.getShadowMap().renderPassIds??[i.currentRenderPassId];for(let s=0;s0){const i=this.getIndices();if(!i)return null;const s=i.length;let r=!1;if(e)r=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>s){r=!0;break}if(e.verticesStart+e.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new vr(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let i=t/e|0,s=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let r=0;r=t);r++)vr.CreateFromIndices(0,s,r===e-1?t-s:i,this,void 0,!1),s+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,s){if(this._geometry)this._geometry.setVerticesData(e,t,i,s);else{const s=new Tr;s.set(t,e);const r=this.getScene();new br(br.RandomId(),r,s,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=br.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,s){return this._geometry?(s?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){const i=this.getVerticesData(Ki.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(Ki.PositionKind,i,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(Ki.NormalKind);if(!t)return this;Tr.ComputeNormals(i,e,t),this.updateVerticesData(Ki.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(1===this._geometry.meshes.length)return this;const e=this._geometry,t=this._geometry.copy(br.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let s=this._geometry;s||(s=new br(br.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{const t=new Tr;t.indices=e;const s=this.getScene();new br(br.RandomId(),s,t,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,s=!0){if(!this._geometry)return this;const r=this.getScene().getEngine();let n;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)n=null;else switch(this._getRenderingFillMode(i)){case Dn.PointFillMode:n=null;break;case Dn.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case Dn.TriangleFillMode:n=this._geometry.getIndexBuffer()}return s&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,n,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,n),this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const s=this.getScene().getEngine();return this._unIndexed||t==Dn.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Dn.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):s.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const i=this.getScene(),s=i._isInIntermediateRendering(),r=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,r=i.getRenderId(),o=s?t.intermediateDefaultRenderId:t.defaultRenderId;n.visibleInstances[e]=t[r],!n.visibleInstances[e]&&o&&(n.visibleInstances[e]=t[o])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==n.visibleInstances[e]&&void 0!==n.visibleInstances[e],this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,i,s,r){const n=i.visibleInstances[e._id],o=n?n.length:0,a=this._instanceDataStorage,l=a.instancesBufferSize;let h=a.instancesBuffer,c=a.instancesPreviousBuffer;const u=16*(o+1)*4;for(;a.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera1&&s.activeCamera===s.activeCameras[0]||r<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const n=this._getInstancesRenderList(e._id,!!i);if(n.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const o=s.getEngine();let a=0,l=null;this.ignoreCameraMaxZ&&s.activeCamera&&!s._isInIntermediateRendering()&&(a=s.activeCamera.maxZ,l=s.activeCamera,s.activeCamera.maxZ=0,s.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const h=e.getRenderingMesh(),c=n.hardwareInstancedRendering[e._id]||h.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,u=this._instanceDataStorage,d=e.getMaterial();if(!d)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;if(u.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===d){if(d._storeEffectOnSubMeshes&&!e._drawWrapper?._wasPreviouslyReady||!d._storeEffectOnSubMeshes&&!d._getDrawWrapper()._wasPreviouslyReady)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this}else{if(d._storeEffectOnSubMeshes){if(!d.isReadyForSubMesh(this,e,c))return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this}else if(!d.isReady(this,c))return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=d}let p;t&&o.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),p=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const f=p?.effect??null;for(const t of s._beforeRenderingMeshStage)t.action(this,e,n,f);if(!p||!f)return l&&(l.maxZ=a,s.updateTransformMatrix(!0)),this;const _=i||this;let m;if(u.isFrozen||!this._internalMeshDataInfo._effectiveMaterial.backFaceCulling&&null===this.overrideMaterialSideOrientation&&!this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)m=u.sideOrientation;else{const e=_._getWorldMatrixDeterminant();m=this.overrideMaterialSideOrientation,null==m&&(m=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(m=m===Dn.ClockWiseSideOrientation?Dn.CounterClockWiseSideOrientation:Dn.ClockWiseSideOrientation),u.sideOrientation=m}const g=this._internalMeshDataInfo._effectiveMaterial._preBind(p,m);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&o.setDepthWrite(!0);const v=this._internalMeshDataInfo._effectiveMaterial,x=v.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),c||this._bind(e,f,x,!1);const T=_.getWorldMatrix();v._storeEffectOnSubMeshes?v.bindForSubMesh(T,this,e):v.bind(T,this),!v.backFaceCulling&&v.separateCullingPass&&(o.setState(!0,v.zOffset,!1,!g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._processRendering(this,e,f,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),o.setState(!0,v.zOffset,!1,g,v.cullBackFaces,v.stencil,v.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,f,x,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const t of s._afterRenderingMeshStage)t.action(this,e,n,f);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),l&&(l.maxZ=a,s.updateTransformMatrix(!0)),s.performancePriority!==ws.Aggressive||u.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(Ki.MatricesWeightsKind)&&(this.isVerticesDataPresent(Ki.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(Ki.MatricesWeightsKind),t=e.length;for(let i=0;ii&&s++,0!==n&&u++,c+=n,i=n}if(l[u]++,u>n&&(n=u),0===c)r++;else{const i=1/c;let s=0;for(let r=0;r.001&&o++}}const h=this.skeleton.bones.length,c=this.getVerticesData(Ki.MatricesIndicesKind),u=this.getVerticesData(Ki.MatricesIndicesExtraKind);let d=0;for(let e=0;e=h||i<0)&&d++}return{skinned:!0,valid:0===r&&0===o&&0===d,report:"Number of Weights = "+i/4+"\nMaximum influences = "+n+"\nMissing Weights = "+r+"\nNot Sorted = "+s+"\nNot Normalized = "+o+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+d}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return Ii.LoadFile(this.delayLoadingFile,(t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach((e=>{e.refreshBoundingInfo(),e._syncSubMeshes()})),this.delayLoadState=1,e.removePendingData(this)}),(()=>{}),e.offlineProvider,t),this}isInFrustum(e){return 2!==this.delayLoadState&&!!super.isInFrustum(e)&&(this._checkDelayState(),!0)}setMaterialById(e){const t=this.getScene().materials;let i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;const s=this.getScene().multiMaterials;for(i=s.length-1;i>-1;i--)if(s[i].id===e)return this.material=s[i],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(Ki.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(Ki.PositionKind);const s=w.Zero();let r;for(r=0;r{const a=e.width,l=e.height,h=this.getEngine().createCanvas(a,l).getContext("2d");h.drawImage(e,0,0);const c=h.getImageData(0,0,a,l).data;this.applyDisplacementMapFromBuffer(c,a,l,t,i,r,n,o),s&&s(this)}),a||(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,s,r,n,o,a=!1){if(!this.isVerticesDataPresent(Ki.PositionKind)||!this.isVerticesDataPresent(Ki.NormalKind)||!this.isVerticesDataPresent(Ki.UVKind))return J.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const l=this.getVerticesData(Ki.PositionKind,!0,!0),h=this.getVerticesData(Ki.NormalKind),c=this.getVerticesData(Ki.UVKind);let u=w.Zero();const d=w.Zero(),p=N.Zero();n=n||N.Zero(),o=o||new N(1,1);for(let a=0;a{const s=new Float32Array(i.length*t);let r=0;for(let n=0;n{const t=s.length-1-e,i=s[t];for(let e=0;e{for(let e=0;e-1&&(s.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(s.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(s.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t4,l=a?this.getVerticesData(Ki.MatricesIndicesExtraKind):null,h=a?this.getVerticesData(Ki.MatricesWeightsExtraKind):null,c=e.getTransformMatrices(this),u=w.Zero(),d=new B,p=new B;let f,_=0;for(let e=0;e0&&(B.FromFloat32ArrayToRefScaled(c,Math.floor(16*n[_+f]),m,p),d.addToSelf(p));if(a)for(f=0;f<4;f++)m=h[_+f],m>0&&(B.FromFloat32ArrayToRefScaled(c,Math.floor(16*l[_+f]),m,p),d.addToSelf(p));w.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],d,u),u.toArray(s,e),t&&(w.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],d,u),u.toArray(r,e)),d.reset()}return this.updateVerticesData(Ki.PositionKind,s),t&&this.updateVerticesData(Ki.NormalKind,r),this}static MinMax(e){let t=null,i=null;return e.forEach((function(e){const s=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(s.minimumWorld),i.maximizeInPlace(s.maximumWorld)):(t=s.minimumWorld,i=s.maximumWorld)})),t&&i?{min:t,max:i}:{min:w.Zero(),max:w.Zero()}}static Center(e){const t=e instanceof Array?Un.MinMax(e):e;return w.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,s,r,n){return sr(Un._MergeMeshesCoroutine(e,t,i,s,r,n,!1))}static MergeMeshesAsync(e,t=!0,i,s,r,n){return rr(Un._MergeMeshesCoroutine(e,t,i,s,r,n,!0),function(e=25){let t;return(i,s,r)=>{const n=performance.now();void 0===t||n-t>e?(t=n,setTimeout((()=>{tr(i,s,r)}),0)):tr(i,s,r)}}())}static*_MergeMeshesCoroutine(e,t=!0,i,s,r,n,o){if(0===(e=e.filter(Boolean)).length)return null;let a;if(!i){let t=0;for(a=0;a=65536)return J.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(r=!1);const l=new Array,h=new Array,c=new Array,u=e[0].overrideMaterialSideOrientation;for(a=0;a{const t=e.computeWorldMatrix(!0);return{vertexData:Tr.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:f,transform:_}=p(d);o&&(yield);const m=new Array(e.length-1);for(let t=1;t{throw ye("GroundMesh")},Un._GoldbergMeshParser=(e,t)=>{throw ye("GoldbergMesh")},Un._LinesMeshParser=(e,t)=>{throw ye("LinesMesh")},Un._GreasedLineMeshParser=(e,t)=>{throw ye("GreasedLineMesh")},Un._GreasedLineRibbonMeshParser=(e,t)=>{throw ye("GreasedLineRibbonMesh")},Un._TrailMeshParser=(e,t)=>{throw ye("TrailMesh")},u("BABYLON.Mesh",Un),Un._instancedMeshFactory=(e,t)=>{const i=new kn(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class kn extends Wr{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const e of t.getAnimationRanges())null!=e&&this.createAnimationRange(e.name,e.from,e.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){this._sourceMesh?.receiveShadows!==e&&Ii.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){this._sourceMesh?.material!==e&&Ii.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){this._sourceMesh?.visibility!==e&&Ii.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){this._sourceMesh?.skeleton!==e&&Ii.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){this._sourceMesh&&e!==this._sourceMesh.renderingGroupId&&J.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,s),this.sourceMesh}updateVerticesData(e,t,i,s){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,s),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||J.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),t){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1}_postActivate(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)}getWorldMatrix(){if(this._currentLOD&&this._currentLOD.billboardMode!==Ur.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new B);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,U.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(U.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;const t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){const t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e0&&-1===this.includedOnlyMeshes.indexOf(e)||this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)||!(0===this.includeOnlyWithLayerMask||this.includeOnlyWithLayerMask&e.layerMask)||0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(const e of this.getScene().meshes)e._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){const i=Gn.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const s=Pe.Clone(i,this);return e&&(s.name=e),t&&(s.parent=t),s.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(s),s}serialize(){const e=Pe.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0&&(e.excludedMeshesIds=[],this.excludedMeshes.forEach((t=>{e.excludedMeshesIds.push(t.id)}))),this.includedOnlyMeshes.length>0&&(e.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((t=>{e.includedOnlyMeshesIds.push(t.id)}))),Pe.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){return De.Construct("Light_Type_"+e,t,i)||null}static Parse(e,t){const i=Gn.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const s=Pe.Parse(i,e,t);if(e.excludedMeshesIds&&(s._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(s._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(s.falloffType=e.falloffType),void 0!==e.lightmapMode&&(s.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t{const s=t.apply(e,i);for(const e of i)e._resyncLightSource(this);return s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);for(const e of r)e._resyncLightSource(this);return r};for(const t of e)t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...i)=>{const s=t.apply(e,i);return this._resyncMeshes(),s};const i=e.splice;e.splice=(t,s)=>{const r=i.apply(e,[t,s]);return this._resyncMeshes(),r},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===Gn.INTENSITYMODE_AUTOMATIC&&(i=t===Gn.LIGHTTYPEID_DIRECTIONALLIGHT?Gn.INTENSITYMODE_ILLUMINANCE:Gn.INTENSITYMODE_LUMINOUSINTENSITY),t){case Gn.LIGHTTYPEID_POINTLIGHT:case Gn.LIGHTTYPEID_SPOTLIGHT:switch(i){case Gn.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Gn.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Gn.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case Gn.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case Gn.INTENSITYMODE_ILLUMINANCE:e=1;break;case Gn.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001),e=2*Math.PI*(1-Math.cos(t));break}}break;case Gn.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Gn.FALLOFF_DEFAULT=Os.FALLOFF_DEFAULT,Gn.FALLOFF_PHYSICAL=Os.FALLOFF_PHYSICAL,Gn.FALLOFF_GLTF=Os.FALLOFF_GLTF,Gn.FALLOFF_STANDARD=Os.FALLOFF_STANDARD,Gn.LIGHTMAP_DEFAULT=Os.LIGHTMAP_DEFAULT,Gn.LIGHTMAP_SPECULAR=Os.LIGHTMAP_SPECULAR,Gn.LIGHTMAP_SHADOWSONLY=Os.LIGHTMAP_SHADOWSONLY,Gn.INTENSITYMODE_AUTOMATIC=Os.INTENSITYMODE_AUTOMATIC,Gn.INTENSITYMODE_LUMINOUSPOWER=Os.INTENSITYMODE_LUMINOUSPOWER,Gn.INTENSITYMODE_LUMINOUSINTENSITY=Os.INTENSITYMODE_LUMINOUSINTENSITY,Gn.INTENSITYMODE_ILLUMINANCE=Os.INTENSITYMODE_ILLUMINANCE,Gn.INTENSITYMODE_LUMINANCE=Os.INTENSITYMODE_LUMINANCE,Gn.LIGHTTYPEID_POINTLIGHT=Os.LIGHTTYPEID_POINTLIGHT,Gn.LIGHTTYPEID_DIRECTIONALLIGHT=Os.LIGHTTYPEID_DIRECTIONALLIGHT,Gn.LIGHTTYPEID_SPOTLIGHT=Os.LIGHTTYPEID_SPOTLIGHT,Gn.LIGHTTYPEID_HEMISPHERICLIGHT=Os.LIGHTTYPEID_HEMISPHERICLIGHT,ae([_e()],Gn.prototype,"diffuse",void 0),ae([_e()],Gn.prototype,"specular",void 0),ae([pe()],Gn.prototype,"falloffType",void 0),ae([pe()],Gn.prototype,"intensity",void 0),ae([pe()],Gn.prototype,"range",null),ae([pe()],Gn.prototype,"intensityMode",null),ae([pe()],Gn.prototype,"radius",null),ae([pe()],Gn.prototype,"_renderPriority",void 0),ae([de("_reorderLightsInScene")],Gn.prototype,"renderPriority",void 0),ae([pe("shadowEnabled")],Gn.prototype,"_shadowEnabled",void 0),ae([pe("excludeWithLayerMask")],Gn.prototype,"_excludeWithLayerMask",void 0),ae([pe("includeOnlyWithLayerMask")],Gn.prototype,"_includeOnlyWithLayerMask",void 0),ae([pe("lightmapMode")],Gn.prototype,"_lightmapMode",void 0);class zn extends p{}class Wn{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){this.rootNodes.slice(0).forEach((e=>{e.dispose()})),this.rootNodes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0}}class Hn extends p{constructor(e){super(),this._wasAddedToScene=!1,(e=e||y.LastCreatedScene)&&(this.scene=e,this.sounds=[],this.effectLayers=[],this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.reflectionProbes=[],e.onDisposeObservable.add((()=>{this._wasAddedToScene||this.dispose()})),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();for(const e of this.particleSystems)e.rebuild();for(const e of this.textures)e._rebuild()})))}_topologicalSort(e){const t=new Map;for(const i of e)t.set(i.uniqueId,i);const i={dependsOn:new Map,dependedBy:new Map};for(const t of e){const e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(const s of e){const e=s.uniqueId,r=i.dependsOn.get(e);if(s instanceof kn){const n=s.sourceMesh;t.has(n.uniqueId)&&(r.add(n.uniqueId),i.dependedBy.get(n.uniqueId).add(e))}const n=i.dependedBy.get(e);for(const r of s.getDescendants()){const s=r.uniqueId;t.has(s)&&(n.add(s),i.dependsOn.get(s).add(e))}}const s=[],r=[];for(const s of e){const e=s.uniqueId;0===i.dependsOn.get(e).size&&(r.push(s),t.delete(e))}const n=r;for(;n.length>0;){const e=n.shift();s.push(e);const r=i.dependedBy.get(e.uniqueId);for(const s of Array.from(r.values())){const r=i.dependsOn.get(s);r.delete(e.uniqueId),0===r.size&&t.get(s)&&(n.push(t.get(s)),t.delete(s))}}return t.size>0&&(J.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>J.Error(e.name)))),s}_addNodeAndDescendantsToList(e,t,i,s){if(i&&(!s||s(i))&&!t.has(i.uniqueId)){e.push(i),t.add(i.uniqueId);for(const r of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,r,s)}}_isNodeInContainer(e){return e instanceof Wr&&-1!==this.meshes.indexOf(e)||e instanceof Ur&&-1!==this.transformNodes.indexOf(e)||e instanceof Gn&&-1!==this.lights.indexOf(e)||e instanceof or&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return J.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return J.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return J.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return J.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||Ii.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const s={},r={},n=new Wn,o=[],a=[],l={doNotInstantiate:!0,...i},h=[],c=new Set;for(const e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);for(const e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(h,c,e,l.predicate);const u=this._topologicalSort(h),d=(i,o)=>{if(((t,i)=>{if(s[t.uniqueId]=i.uniqueId,r[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof Un){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;te&&r[s[e.uniqueId]]))}}"InstancedMesh"!==n.getClassName()&&(n.material=r[s[t.uniqueId]])}else"MultiMaterial"===n.material.getClassName()?-1===this.scene.multiMaterials.indexOf(n.material)&&this.scene.addMultiMaterial(n.material):-1===this.scene.materials.indexOf(n.material)&&this.scene.addMaterial(n.material)}null===o.parent&&n.rootNodes.push(o)};return u.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,n=s[i.uniqueId],o=("number"==typeof n?r[n]:i).createInstance(t.name);d(t,o)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);const i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw new Error(`Could not clone or instantiate node on Asset Container ${e.name}`);d(e,i)}})),this.skeletons.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name);for(const e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){const t=r[s[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=i,-1!==o.indexOf(i))continue;o.push(i);for(const e of i.bones)e._linkedTransformNode&&(e._linkedTransformNode=r[s[e._linkedTransformNode.uniqueId]])}n.skeletons.push(i)})),this.animationGroups.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name,(e=>r[s[e.uniqueId]]||e));n.animationGroups.push(i)})),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Ii.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(const e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){const t=[];this.cameras.forEach((i=>{e&&!e(i)||(this.scene.addCamera(i),t.push(i))})),this.lights.forEach((i=>{e&&!e(i)||(this.scene.addLight(i),t.push(i))})),this.meshes.forEach((i=>{e&&!e(i)||(this.scene.addMesh(i),t.push(i))})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.addSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.addAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.addAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.addMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.addMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.addMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.addGeometry(t)})),this.transformNodes.forEach((i=>{e&&!e(i)||(this.scene.addTransformNode(i),t.push(i))})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.addActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.addTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.addReflectionProbe(t)}));for(const e of t)e.parent&&-1===this.scene.getNodes().indexOf(e.parent)&&(e.setParent?e.setParent(null):e.parent=null)}removeAllFromScene(){this._isValidHierarchy()||Ii.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach((t=>{e&&!e(t)||this.scene.removeCamera(t)})),this.lights.forEach((t=>{e&&!e(t)||this.scene.removeLight(t)})),this.meshes.forEach((t=>{e&&!e(t)||this.scene.removeMesh(t,!0)})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.removeSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.removeAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.removeMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.removeGeometry(t)})),this.transformNodes.forEach((t=>{e&&!e(t)||this.scene.removeTransformNode(t)})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.removeActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.removeTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)}))}dispose(){this.cameras.slice(0).forEach((e=>{e.dispose()})),this.cameras.length=0,this.lights.slice(0).forEach((e=>{e.dispose()})),this.lights.length=0,this.meshes.slice(0).forEach((e=>{e.dispose()})),this.meshes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach((e=>{e.dispose()})),this.multiMaterials.length=0,this.materials.slice(0).forEach((e=>{e.dispose()})),this.materials.length=0,this.geometries.slice(0).forEach((e=>{e.dispose()})),this.geometries.length=0,this.transformNodes.slice(0).forEach((e=>{e.dispose()})),this.transformNodes.length=0,this.actionManagers.slice(0).forEach((e=>{e.dispose()})),this.actionManagers.length=0,this.textures.slice(0).forEach((e=>{e.dispose()})),this.textures.length=0,this.reflectionProbes.slice(0).forEach((e=>{e.dispose()})),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach((e=>{e.dispose()})),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(e&&t)for(const s of e){let e=!0;if(i)for(const t of i)if(s===t){e=!1;break}e&&(t.push(s),s._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,void 0===e&&(e=new zn);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||("_environmentTexture"===t?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new Un("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=y.LastCreatedScene,t,i=null){if(!e)return J.Error("No scene available to merge animations to"),[];const s=i||(t=>{let i=null;const s=t.animations.length?t.animations[0].targetProperty:"",r=t.name.split(".").join("").split("_primitive")[0];switch(s){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(r);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(r);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(r)}return i});this.getNodes().forEach((e=>{const t=s(e);if(null!==t){for(const i of e.animations){const e=t.animations.filter((e=>e.targetProperty===i.targetProperty));for(const i of e){const e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}}));const r=[];return this.animationGroups.slice().forEach((e=>{r.push(e.clone(e.name,s)),e.animatables.forEach((e=>{e.stop()}))})),t.forEach((t=>{const i=s(t.target);i&&(e.beginAnimation(i,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))})),r}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.transformNodes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.lights.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.cameras.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}))}addAllAssetsToContainer(e){if(!e)return;const t=[],i=new Set;for(t.push(e);t.length>0;){const e=t.pop();if(e instanceof Un?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof Ur?this.transformNodes.push(e):e instanceof Gn?this.lights.push(e):e instanceof or&&this.cameras.push(e),e instanceof Wr){if(e.material&&-1===this.materials.indexOf(e.material)){this.materials.push(e.material);for(const t of e.material.getActiveTextures())-1===this.textures.indexOf(t)&&this.textures.push(t)}e.skeleton&&-1===this.skeletons.indexOf(e.skeleton)&&this.skeletons.push(e.skeleton),e.morphTargetManager&&-1===this.morphTargetManagers.indexOf(e.morphTargetManager)&&this.morphTargetManagers.push(e.morphTargetManager)}for(const s of e.getChildren())i.has(s)||t.push(s);i.add(e)}this.populateRootNodes()}}class Xn{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if(Br.audioEngine?.audioContext&&(this.isPlaying||this.isPaused)){const e=this.isPaused?0:Br.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;const t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,s=null,r){if(this.autoplay=!1,this._loop=!1,this.useCustomAttenuation=!1,this.isPlaying=!1,this.isPaused=!1,this.refDistance=1,this.rolloffFactor=1,this.maxDistance=100,this.distanceModel="linear",this.metadata=null,this.onEndedObservable=new g,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=w.Zero(),this._localDirection=new w(1,0,0),this._volume=1,this._isReadyToPlay=!1,this._isDirectional=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._coneOuterGain=0,this._isOutputConnected=!1,this._urlType="Unknown",this.name=e,i=i||y.LastCreatedScene)if(this._scene=i,Xn._SceneComponentInitialization(i),this._readyToPlayCallback=s,this._customAttenuationFunction=(e,t,i,s,r)=>t0&&(s=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()})),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(t,(e=>{this._soundLoaded(e)}),void 0,!0,!0,(e=>{e&&J.Error("XHR "+e.status+" error on: "+t+"."),J.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}));break}}break;default:e=!1}e?s||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)):J.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){J.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),Br.audioEngine&&!Br.audioEngine.WarnedWebAudioUnsupported&&(J.Error("Web Audio is not supported by your browser."),Br.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)}dispose(){Br.audioEngine?.canUseWebAudio&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,-1===this.soundTrackId?this._scene.mainSoundTrack.removeSound(this):this._scene.soundTracks&&this._scene.soundTracks[this.soundTrackId].removeSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._streamingSource&&this._streamingSource.disconnect(),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){Br.audioEngine?.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){Br.audioEngine?.audioContext&&Br.audioEngine.audioContext.decodeAudioData(e,(e=>{this._audioBufferLoaded(e)}),(e=>{J.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)}))}setAudioBuffer(e){Br.audioEngine?.canUseWebAudio&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){e&&(this.loop=e.loop??this.loop,this.maxDistance=e.maxDistance??this.maxDistance,this.useCustomAttenuation=e.useCustomAttenuation??this.useCustomAttenuation,this.rolloffFactor=e.rolloffFactor??this.rolloffFactor,this.refDistance=e.refDistance??this.refDistance,this.distanceModel=e.distanceModel??this.distanceModel,this._playbackRate=e.playbackRate??this._playbackRate,this._length=e.length??void 0,this.spatialSound=e.spatialSound??this._spatialSound,this._setOffset(e.offset??void 0),this.setVolume(e.volume??this._volume),this._updateSpatialParameters(),this.isPlaying&&(this._streaming&&this._htmlAudioElement?(this._htmlAudioElement.playbackRate=this._playbackRate,this._htmlAudioElement.loop!==this.loop&&(this._htmlAudioElement.loop=this.loop)):this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.loop!==this.loop&&(this._soundSource.loop=this.loop),void 0!==this._offset&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),void 0!==this._length&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(0|this._offset)+this._length))))}_createSpatialParameters(){Br.audioEngine?.canUseWebAudio&&Br.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??Br.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){this._spatialSound&&(this._inputAudioNode=this._soundGain,this._soundPanner?.disconnect(),this._soundPanner=null,this._spatialSound=!1)}_updateSpatialParameters(){this._spatialSound&&(this._soundPanner?this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel):this._createSpatialParameters())}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){Br.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){Br.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const e=()=>{if(Br.audioEngine?.unlocked){const t=this._htmlAudioElement.play();void 0!==t&&t.catch((()=>{Br.audioEngine?.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Br.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))}))}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Br.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))};e()}}else{const r=()=>{if(Br.audioEngine?.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){const e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=Br.audioEngine?.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,void 0!==t&&(this._soundSource.loopStart=t),void 0!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},s=e?Br.audioEngine?.audioContext.currentTime+e:Br.audioEngine.audioContext.currentTime;const r=((this.isPaused?this.currentTime:0)+(this._offset??0))%this._soundSource.buffer.duration;this._soundSource.start(s,r,this.loop?void 0:i)}}};"suspended"===Br.audioEngine?.audioContext.state?this._tryToPlayTimeout=setTimeout((()=>{"suspended"===Br.audioEngine?.audioContext.state?(Br.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=Br.audioEngine.onAudioUnlockedObservable.addOnce((()=>{r()})))):r()}),500):r()}this._startTime=s,this.isPlaying=!0,this.isPaused=!1}catch(e){J.Error("Error while trying to play audio: "+this.name+", "+e.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){if(this.isPlaying)if(this._clearTimeoutsAndObservers(),this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if(Br.audioEngine?.audioContext&&this._soundSource){const t=e?Br.audioEngine.audioContext.currentTime+e:void 0;this._soundSource.onended=()=>{this.isPlaying=!1,this.isPaused=!1,this._startTime=0,this._currentTime=0,this._soundSource&&(this._soundSource.onended=()=>{}),this._onended()},this._soundSource.stop(t)}else this.isPlaying=!1;else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):Br.audioEngine?.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=Br.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){Br.audioEngine?.canUseWebAudio&&this._soundGain&&(t&&Br.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(Br.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,Br.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,Br.audioEngine.audioContext.currentTime+t)):this._soundGain.gain.value=e),this._volume=e}setPlaybackRate(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))}getPlaybackRate(){return this._playbackRate}getVolume(){return this._volume}attachToMesh(e){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=e,this._spatialSound||(this._spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=e=>this._onRegisterAfterWorldMatrixUpdate(e),this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)}detachFromMesh(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)}_onRegisterAfterWorldMatrixUpdate(e){if(e.getBoundingInfo){const t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);Br.audioEngine?.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{const e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},i=new Xn(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){const e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,s){const r=e.name;let n;n=e.url?i+e.url:i+r;const o={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};let a;if(s){const e=()=>{s._isReadyToPlay?(a._audioBuffer=s.getAudioBuffer(),a._isReadyToPlay=!0,a.autoplay&&a.play(0,a._offset,a._length)):setTimeout(e,300)};a=new Xn(r,new ArrayBuffer(0),t,null,o),e()}else a=new Xn(r,n,t,(()=>{t.removePendingData(a)}),o),t.addPendingData(a);if(e.position){const t=w.FromArray(e.position);a.setPosition(t)}if(e.isDirectional&&(a.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const t=w.FromArray(e.localDirectionToMesh);a.setLocalDirectionToMesh(t)}if(e.connectedMeshId){const i=t.getMeshById(e.connectedMeshId);i&&a.attachToMesh(i)}return e.metadata&&(a.metadata=e.metadata),a}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(Br.audioEngine?.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}Xn._SceneComponentInitialization=e=>{throw ye("AudioSceneComponent")},u("BABYLON.Sound",Xn);class Yn{constructor(e,t={}){this.id=-1,this._isInitialized=!1,(e=e||y.LastCreatedScene)&&(this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1))}_initializeSoundTrackAudioGraph(){Br.audioEngine?.canUseWebAudio&&Br.audioEngine.audioContext&&(this._outputAudioNode=Br.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(Br.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(Br.audioEngine&&Br.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(e){this._isInitialized||this._initializeSoundTrackAudioGraph(),Br.audioEngine?.canUseWebAudio&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){const t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){Br.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){if(Br.audioEngine?.canUseWebAudio)for(let e=0;e{let r,n=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let o=0,a=e.sounds.length;o{e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)}))}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach((e=>{e.stop(),e.autoplay=!1,this.scene.mainSoundTrack.removeSound(e),t&&e.dispose()}))}dispose(){const e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(s=t.activeCameras[0]),this.audioListenerPositionProvider){const e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else s?this._cachedCameraPosition.equals(s.globalPosition)||(this._cachedCameraPosition.copyFrom(s.globalPosition),i.audioContext.listener.setPosition(s.globalPosition.x,s.globalPosition.y,s.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else s?(s.rigCameras&&s.rigCameras.length>0&&(s=s.rigCameras[0]),s.getViewMatrix().invertToRef(this._invertMatrixTemp),w.TransformNormalToRef(jn._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),isNaN(this._cameraDirectionTemp.x)||isNaN(this._cameraDirectionTemp.y)||isNaN(this._cameraDirectionTemp.z)||this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);for(e=0;e{let t=e._getComponent(ts.NAME_AUDIO);t||(t=new jn(e),e._addComponent(t))};class $n{constructor(e){this._texture=null,this._isEnabled=!0,this.isEnabled=!0,this.time=0,(e=e||y.LastCreatedScene)&&(this._scene=e,this.animationParameters=new F(0,0,0,30))}_markSubMeshesAsAttributesDirty(){for(const e of this._scene.meshes)e.bakedVertexAnimationManager===this&&e._markSubMeshesAsAttributesDirty()}bind(e,t=!1){if(!this._texture||!this._isEnabled)return;const i=this._texture.getSize();e.setFloat2("bakedVertexAnimationTextureSizeInverted",1/i.width,1/i.height),e.setFloat("bakedVertexAnimationTime",this.time),t||e.setVector4("bakedVertexAnimationSettings",this.animationParameters),e.setTexture("bakedVertexAnimationTexture",this._texture)}clone(){const e=new $n(this._scene);return this.copyTo(e),e}setAnimationParameters(e,t,i=0,s=30){this.animationParameters=new F(e,t,i,s)}dispose(e){e&&this._texture?.dispose()}getClassName(){return"BakedVertexAnimationManager"}copyTo(e){Pe.Clone((()=>e),this)}serialize(){return Pe.Serialize(this)}parse(e,t,i){Pe.Parse((()=>this),e,t,i)}}ae([fe(),de("_markSubMeshesAsAttributesDirty")],$n.prototype,"texture",void 0),ae([pe(),de("_markSubMeshesAsAttributesDirty")],$n.prototype,"isEnabled",void 0),ae([pe()],$n.prototype,"animationParameters",void 0),ae([pe()],$n.prototype,"time",void 0);class Kn{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return!!this._texture&&this._texture.isCube}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return void 0!==e?.shareDepth}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=Oe.Zero(),this._cachedBaseSize=Oe.Zero(),this._initialSamplingMode=2,this._texture=Kn._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return this.isReady()&&this._texture?this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}class qn extends Kn{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),this.getScene()?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return!!this._texture&&this._texture._linearSpecularLOD}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=Si()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=qn.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new g,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?qn._IsScene(e)?this._scene=e:this._engine=e:this._scene=y.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}getTextureMatrix(){return B.IdentityReadOnly}getReflectionTextureMatrix(){return B.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,s,r,n){const o=this._getEngine();if(!o)return null;const a=o._getUseSRGBBuffer(!!r,t),l=o.getLoadedTexturesCache();for(let o=0;o=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const e=this._parentContainer.textures.indexOf(this);e>-1&&this._parentContainer.textures.splice(e,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;const t=Pe.Serialize(this);return Pe.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let s=0;s{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}function Qn(e,t,i=!1){const s=t.width,r=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let s=e[t];s<0?s=0:s>1&&(s=1),i[t]=255*s}e=i}const n=document.createElement("canvas");n.width=s,n.height=r;const o=n.getContext("2d");if(!o)return null;const a=o.createImageData(s,r);if(a.data.set(e),o.putImageData(a,0,0),i){const e=document.createElement("canvas");e.width=s,e.height=r;const t=e.getContext("2d");return t?(t.translate(0,r),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}qn.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,ae([pe()],qn.prototype,"uniqueId",void 0),ae([pe()],qn.prototype,"name",void 0),ae([pe()],qn.prototype,"metadata",void 0),ae([pe("hasAlpha")],qn.prototype,"_hasAlpha",void 0),ae([pe("getAlphaFromRGB")],qn.prototype,"_getAlphaFromRGB",void 0),ae([pe()],qn.prototype,"level",void 0),ae([pe("coordinatesIndex")],qn.prototype,"_coordinatesIndex",void 0),ae([pe()],qn.prototype,"optimizeUVAllocation",void 0),ae([pe("coordinatesMode")],qn.prototype,"_coordinatesMode",void 0),ae([pe()],qn.prototype,"wrapU",null),ae([pe()],qn.prototype,"wrapV",null),ae([pe()],qn.prototype,"wrapR",void 0),ae([pe()],qn.prototype,"anisotropicFilteringLevel",void 0),ae([pe()],qn.prototype,"isCube",null),ae([pe()],qn.prototype,"is3D",null),ae([pe()],qn.prototype,"is2DArray",null),ae([pe()],qn.prototype,"gammaSpace",null),ae([pe()],qn.prototype,"invertZ",void 0),ae([pe()],qn.prototype,"lodLevelInAlpha",void 0),ae([pe()],qn.prototype,"lodGenerationOffset",null),ae([pe()],qn.prototype,"lodGenerationScale",null),ae([pe()],qn.prototype,"linearSpecularLOD",null),ae([fe()],qn.prototype,"irradianceTexture",null),ae([pe()],qn.prototype,"isRenderTarget",void 0);class Zn extends qn{static _CreateVideoTexture(e,t,i,s=!1,r=!1,n=Zn.TRILINEAR_SAMPLINGMODE,o={},a,l=5){throw ye("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,s,r=Zn.TRILINEAR_SAMPLINGMODE,n=null,o=null,a=null,l=!1,h,c,u,d,p){let f;super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=null,this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedIdentity3x2=!0,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new g,this._isBlocking=!0,this.name=e||"",this.url=e;let _=!1,m=null,v=!0;"object"==typeof i&&null!==i?(f=i.noMipmap??!1,s=i.invertY??!Er.UseOpenGLOrientationForUV,r=i.samplingMode??Zn.TRILINEAR_SAMPLINGMODE,n=i.onLoad??null,o=i.onError??null,a=i.buffer??null,l=i.deleteBuffer??!1,h=i.format,c=i.mimeType,u=i.loaderOptions,d=i.creationFlags,_=i.useSRGBBuffer??!1,m=i.internalTexture??null,v=i.gammaSpace??v):f=!!i,this._gammaSpace=v,this._noMipmap=f,this._invertY=void 0===s?!Er.UseOpenGLOrientationForUV:s,this._initialSamplingMode=r,this._buffer=a,this._deleteBuffer=l,this._mimeType=c,this._loaderOptions=u,this._creationFlags=d,this._useSRGBBuffer=_,this._forcedExtension=p,h&&(this._format=h);const x=this.getScene(),T=this._getEngine();if(!T)return;T.onBeforeTextureInitObservable.notifyObservers(this);const S=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),n&&n(),!this.isBlocking&&x&&x.resetCachedMaterial()},E=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},o&&o(e,t),Zn.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!m)return this._delayedOnLoad=S,void(this._delayedOnError=E);if(this._texture=m??this._getFromCache(this.url,f,r,this._invertY,_,this.isCube),this._texture)if(this._texture.isReady)wt.SetImmediate((()=>S()));else{const e=this._texture.onLoadedObservable.add(S);this._texture.onErrorObservable.add((t=>{E(t.message,t.exception),this._texture?.onLoadedObservable.remove(e)}))}else if(x&&x.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=S,this._delayedOnError=E;else{try{this._texture=T.createTexture(this.url,f,this._invertY,x,r,S,E,this._buffer,void 0,this._format,this._forcedExtension,c,u,d,_)}catch(e){throw E("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,i,s){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,(e=>e.hasTexture(this)))),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=s,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;const e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?wt.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,s){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,w.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,s),s.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,s.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,s.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,this._cachedTextureMatrix&&this._rowGenerationMatrix||(this._cachedTextureMatrix=B.Zero(),this._rowGenerationMatrix=new B,this._t0=w.Zero(),this._t1=w.Zero(),this._t2=w.Zero()),B.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(B.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,U.Matrix[0]),B.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,U.Matrix[1]),B.ScalingToRef(this._cachedUScale,this._cachedVScale,0,U.Matrix[2]),B.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,U.Matrix[3]),U.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(U.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(U.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(U.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),B.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));const t=this.getScene();if(!t)return this._cachedTextureMatrix;const i=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&i!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedTextureMatrix}getReflectionTextureMatrix(){const e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode){if(this.coordinatesMode!==Zn.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=B.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=B.Zero());const t=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case Zn.PLANAR_MODE:B.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break;case Zn.PROJECTION_MODE:{B.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:B.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedReflectionTextureMatrix}clone(){const e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return Pe.Clone((()=>new Zn(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){const e=this.name;Zn.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(Zn._SerializeInternalTextureUniqueId);return t?((Zn.SerializeBuffers||Zn.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(t.base64String=this._buffer,t.name=t.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?t.base64String="data:image/png;base64,"+Ze(this._buffer):(Zn.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?function(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=e._readPixelsSync(t,i);return r?Qn(r,e.getSize(),s.invertY):null}(this):async function(e,t=0,i=0){const s=e.getInternalTexture();if(!s)return null;const r=await e.readPixels(t,i);return r?Qn(r,e.getSize(),s.invertY):null}(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,Zn._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=this._texture?.uniqueId??void 0),t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){const s=Ti.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&s.updateSamplingMode&&s._samplingMode&&s._samplingMode!==e.samplingMode&&s.updateSamplingMode(e.samplingMode),s}if(e.isCube&&!e.isRenderTarget)return Zn._CubeTextureParser(e,t,i);const s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;let r;if(s){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}const n=t=>{if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){const i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i{let s=!0;if(e.noMipmap&&(s=!1),e.mirrorPlane){const i=Zn._CreateMirror(e.name,e.renderTargetSize,t,s);return i._waitingRenderList=e.renderList,i.mirrorPlane=Ps.FromArray(e.mirrorPlane),n(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{n(o)}),e._creationFlags??0,e._useSRGBBuffer??!1),o.name=e.name;else{let a;a=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||Zn.UseSerializedUrlIfAny)&&(a=e.url);const l={noMipmap:!s,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(o)},internalTexture:r};o=new Zn(a,t,l)}return o}}),e,t)}static CreateFromBase64String(e,t,i,s,r,n=Zn.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=5,h,c){return new Zn("data:"+t,i,s,r,n,o,a,e,!1,l,void 0,void 0,h,c)}static LoadFromDataString(e,t,i,s=!1,r,n=!0,o=Zn.TRILINEAR_SAMPLINGMODE,a=null,l=null,h=5,c,u){return"data:"!==e.substr(0,5)&&(e="data:"+e),new Zn(e,i,r,n,o,a,l,t,s,h,void 0,void 0,c,u)}}function Jn(e,t,i,s){let r,n=1;1===s?r=new Float32Array(t*i*4):2===s?(r=new Uint16Array(t*i*4),n=15360):r=7===s?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let s=0;s{throw ye("CubeTexture")},Zn._CreateMirror=(e,t,i,s)=>{throw ye("MirrorTexture")},Zn._CreateRenderTargetTexture=(e,t,i,s,r)=>{throw ye("RenderTargetTexture")},Zn.NEAREST_SAMPLINGMODE=1,Zn.NEAREST_NEAREST_MIPLINEAR=8,Zn.BILINEAR_SAMPLINGMODE=2,Zn.LINEAR_LINEAR_MIPNEAREST=11,Zn.TRILINEAR_SAMPLINGMODE=3,Zn.LINEAR_LINEAR_MIPLINEAR=3,Zn.NEAREST_NEAREST_MIPNEAREST=4,Zn.NEAREST_LINEAR_MIPNEAREST=5,Zn.NEAREST_LINEAR_MIPLINEAR=6,Zn.NEAREST_LINEAR=7,Zn.NEAREST_NEAREST=1,Zn.LINEAR_NEAREST_MIPNEAREST=9,Zn.LINEAR_NEAREST_MIPLINEAR=10,Zn.LINEAR_LINEAR=2,Zn.LINEAR_NEAREST=12,Zn.EXPLICIT_MODE=0,Zn.SPHERICAL_MODE=1,Zn.PLANAR_MODE=2,Zn.CUBIC_MODE=3,Zn.PROJECTION_MODE=4,Zn.SKYBOX_MODE=5,Zn.INVCUBIC_MODE=6,Zn.EQUIRECTANGULAR_MODE=7,Zn.FIXED_EQUIRECTANGULAR_MODE=8,Zn.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Zn.CLAMP_ADDRESSMODE=0,Zn.WRAP_ADDRESSMODE=1,Zn.MIRROR_ADDRESSMODE=2,Zn.UseSerializedUrlIfAny=!1,ae([pe()],Zn.prototype,"url",void 0),ae([pe()],Zn.prototype,"uOffset",void 0),ae([pe()],Zn.prototype,"vOffset",void 0),ae([pe()],Zn.prototype,"uScale",void 0),ae([pe()],Zn.prototype,"vScale",void 0),ae([pe()],Zn.prototype,"uAng",void 0),ae([pe()],Zn.prototype,"vAng",void 0),ae([pe()],Zn.prototype,"wAng",void 0),ae([pe()],Zn.prototype,"uRotationCenter",void 0),ae([pe()],Zn.prototype,"vRotationCenter",void 0),ae([pe()],Zn.prototype,"wRotationCenter",void 0),ae([pe()],Zn.prototype,"homogeneousRotationInUVTransform",void 0),ae([pe()],Zn.prototype,"isBlocking",null),u("BABYLON.Texture",Zn),Pe._TextureParser=Zn.Parse,Yi.prototype.updateRawTexture=function(e,t,i,s,r=null,n=0,o=!1){if(!e)return;const a=this._getRGBABufferInternalSizedFormat(n,i,o),l=this._getInternalFormat(i),h=this._getWebGLTextureType(n);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=n,e.invertY=s,e._compression=r),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[r],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,a,e.width,e.height,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0},Yi.prototype.createRawTexture=function(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new ti(this,ei.Raw);u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u._compression=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!r),this._doNotHandleContextLost||(u._bufferView=e),this.updateRawTexture(u,e,s,n,a,l,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);const d=this._getSamplingParameters(o,r);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),r&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u},Yi.prototype.createRawCubeTexture=function(e,t,i,s,r,n,o,a=null){const l=this._gl,h=new ti(this,ei.CubeRaw);h.isCube=!0,h.format=i,h.type=s,this._doNotHandleContextLost||(h._bufferViewArray=e);const c=this._getWebGLTextureType(s);let u=this._getInternalFormat(i);u===l.RGB&&(u=l.RGBA),c!==l.FLOAT||this._caps.textureFloatLinearFiltering?c!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?c!==l.FLOAT||this._caps.textureFloatRender?c!==l.HALF_FLOAT||this._caps.colorBufferFloat||(r=!1,J.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(r=!1,J.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(r=!1,o=1,J.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(r=!1,o=1,J.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."));const d=t,p=d;if(h.width=d,h.height=p,h.invertY=n,h._compression=a,!this.needPOTTextures||Ei(h.width)&&Ei(h.height)||(r=!1),e)this.updateRawCubeTexture(h,e,i,s,n,a);else{const e=this._getRGBABufferInternalSizedFormat(s),t=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let i=0;i<6;i++)a?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,this.getCaps().s3tc[a],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+i,t,e,h.width,h.height,0,u,c,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),e&&r&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const f=this._getSamplingParameters(o,r);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,f.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,f.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),h.generateMipMaps=r,h.samplingMode=o,h.isReady=!0,h},Yi.prototype.updateRawCubeTexture=function(e,t,i,s,r,n=null,o=0){e._bufferViewArray=t,e.format=i,e.type=s,e.invertY=r,e._compression=n;const a=this._gl,l=this._getWebGLTextureType(s);let h=this._getInternalFormat(i);const c=this._getRGBABufferInternalSizedFormat(s);let u=!1;h===a.RGB&&(h=a.RGBA,u=!0),this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===r||!!r),e.width%4!=0&&a.pixelStorei(a.UNPACK_ALIGNMENT,1);for(let i=0;i<6;i++){let r=t[i];n?a.compressedTexImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+i,o,this.getCaps().s3tc[n],e.width,e.height,0,r):(u&&(r=Jn(r,e.width,e.height,s)),a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+i,o,c,e.width,e.height,0,h,l,r))}(!this.needPOTTextures||Ei(e.width)&&Ei(e.height))&&e.generateMipMaps&&0===o&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},Yi.prototype.createRawCubeTextureFromUrl=function(e,t,i,s,r,n,o,a,l=null,h=null,c=3,u=!1){const d=this._gl,p=this.createRawCubeTexture(null,i,s,r,!n,u,c,null);t?.addPendingData(p),p.url=e,p.isReady=!1,this._internalTexturesCache.push(p);const f=e=>{const i=p.width,n=o(e);if(n){if(a){const e=this._getWebGLTextureType(r);let t=this._getInternalFormat(s);const o=this._getRGBABufferInternalSizedFormat(r);let l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,p,!0),this._unpackFlipY(!1);const h=a(n);for(let s=0;s>s;for(let i=0;i<6;i++){let a=h[s][i];l&&(a=Jn(a,n,n,r)),d.texImage2D(i,s,o,n,n,0,t,e,a)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(p,n,s,r,u);p.isReady=!0,t?.removePendingData(p),p.onLoadedObservable.notifyObservers(p),p.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,(e=>{f(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(p),h&&e&&h(e.status+" "+e.statusText,i)})),p},Yi.prototype.createRawTexture2DArray=eo(!1),Yi.prototype.createRawTexture3D=eo(!0),Yi.prototype.updateRawTexture2DArray=to(!1),Yi.prototype.updateRawTexture3D=to(!0);class io extends Zn{constructor(e,t,i,s,r,n=!0,o=!1,a=3,l=0,h,c){super(null,r,!n,o,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=s,this._engine&&(this._engine._caps.textureFloatLinearFiltering||1!==l||(a=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(a=1),this._texture=this._engine.createRawTexture(e,t,i,s,n,o,a,null,l,h??0,c??!1),this.wrapU=Zn.CLAMP_ADDRESSMODE,this.wrapV=Zn.CLAMP_ADDRESSMODE)}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}static CreateLuminanceTexture(e,t,i,s,r=!0,n=!1,o=3){return new io(e,t,i,1,s,r,n,o)}static CreateLuminanceAlphaTexture(e,t,i,s,r=!0,n=!1,o=3){return new io(e,t,i,2,s,r,n,o)}static CreateAlphaTexture(e,t,i,s,r=!0,n=!1,o=3){return new io(e,t,i,0,s,r,n,o)}static CreateRGBTexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=0,h=!1){return new io(e,t,i,4,s,r,n,o,a,l,h)}static CreateRGBATexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=0,h=!1){return new io(e,t,i,5,s,r,n,o,a,l,h)}static CreateRGBAStorageTexture(e,t,i,s,r=!0,n=!1,o=3,a=0,l=!1){return new io(e,t,i,5,s,r,n,o,a,1,l)}static CreateRTexture(e,t,i,s,r=!0,n=!1,o=Zn.TRILINEAR_SAMPLINGMODE,a=1){return new io(e,t,i,6,s,r,n,o,a)}static CreateRStorageTexture(e,t,i,s,r=!0,n=!1,o=Zn.TRILINEAR_SAMPLINGMODE,a=1){return new io(e,t,i,6,s,r,n,o,a,1)}}class so{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=B.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new g,this.bones=[],this._scene=i||y.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const s=this._scene.getEngine().getCaps();this._canUseTextureForBones=s.textureFloat&&s.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter((e=>!e.getParent()))}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return this._transformMatrices&&!this._isDirty||this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0)for(const e of this.bones)if(e._linkedTransformNode){const t=e._linkedTransformNode;e.position=t.position,t.rotationQuaternion?e.rotationQuaternion=t.rotationQuaternion:e.rotation=t.rotation,e.scaling=t.scaling}if(this.needInitialSkinMatrix)for(const e of this._meshesWithPoseMatrix){const t=e.getPoseMatrix();let i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){this._synchronizedWithMesh=e;for(const e of this.bones)e.getParent()||(e.getBindMatrix().multiplyToRef(t,U.Matrix[1]),e._updateAbsoluteBindMatrices(U.Matrix[1]));if(this.isUsingTextureForMatrices){const t=4*(this.bones.length+1);e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=io.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(e._bonesTransformMatrices,t),this.isUsingTextureForMatrices&&e._transformMatrixTexture&&e._transformMatrixTexture.update(e._bonesTransformMatrices)}}else{if(!this._isDirty)return;this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=io.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e{t.animations.forEach((t=>{t.enableBlending=!0,t.blendingSpeed=e}))}))}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){const e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){const e={};e.name=this.name,e.id=this.id,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let t=0;t0&&(r.animation=i.animations[0].serialize()),e.ranges=[];for(const t in this._ranges){const i=this._ranges[t];if(!i)continue;const s={};s.name=t,s.from=i.from,s.to=i.to,e.ranges.push(s)}}return e}static Parse(e,t){const i=new so(e.name,e.id,t);let s;for(e.dimensionsAtRest&&(i.dimensionsAtRest=w.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,s=0;s-1&&(n=i.bones[t.parentBoneIndex]);const o=t.rest?B.FromArray(t.rest):null,a=new zs(t.name,i,n,B.FromArray(t.matrix),o,null,r);void 0!==t.id&&null!==t.id&&(a.id=t.id),t.length&&(a.length=t.length),t.metadata&&(a.metadata=t.metadata),t.animation&&a.animations.push(Ge.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,a._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(s=0;s0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()}))}}class ro{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==ss.POINTERDOWN?e.type===ss.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=je.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const i=e-this._lastInteractionTime-this._idleRotationWaitTime,s=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*s,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=e??je.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(e&&(e.computeWorldMatrix(!0),e.getBoundingInfo)){const t=e.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=.05*t,this.upperRadiusTransitionRange=.05*t}})):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))}))}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return!!this._attachedCamera&&this._attachedCamera.radius===e&&!this._radiusIsAnimating}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(no.EasingFunction.setEasingMode(no.EasingMode),this._radiusBounceTransition=Ge.CreateAnimation("radius",Ge.ANIMATIONTYPE_FLOAT,60,no.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=Ge.TransitionTo("radius",this._attachedCamera.radius+e,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,(()=>this._clearAnimationLocks()));t&&this._animatables.push(t)}_clearAnimationLocks(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()}}no.EasingFunction=new class extends Ks{constructor(e=1){super(),this.amplitude=e}easeInCore(e){const t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}}(.3),no.EasingMode=Ks.EASINGMODE_EASEOUT;class oo{constructor(){this.onTargetFramingAnimationEndObservable=new g,this._mode=oo.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}get name(){return"Framing"}set mode(e){this._mode=e}get mode(){return this._mode}set radiusScale(e){this._radiusScale=e}get radiusScale(){return this._radiusScale}set positionScale(e){this._positionScale=e}get positionScale(){return this._positionScale}set defaultElevation(e){this._defaultElevation=e}get defaultElevation(){return this._defaultElevation}set elevationReturnTime(e){this._elevationReturnTime=e}get elevationReturnTime(){return this._elevationReturnTime}set elevationReturnWaitTime(e){this._elevationReturnWaitTime=e}get elevationReturnWaitTime(){return this._elevationReturnWaitTime}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set framingTime(e){this._framingTime=e}get framingTime(){return this._framingTime}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();oo.EasingFunction.setEasingMode(oo.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==ss.POINTERDOWN?e.type===ss.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add((e=>{e&&e.getBoundingInfo&&this.zoomOnMesh(e,void 0,(()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()}))})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(s.minimumWorld,s.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);const s=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(s.min,s.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){const s=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new w(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t{this.stopAllAnimations(),s&&s(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),l&&this._animatables.push(l),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=this._attachedCamera;if(!i)return 0;let s=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===oo.IgnoreBoundsSizeMode&&(s=si.upperRadiusLimit?i.upperRadiusLimit:s),s}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=je.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation,i=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=Ge.CreateAnimation("beta",Ge.ANIMATIONTYPE_FLOAT,60,oo.EasingFunction));const e=Ge.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(()=>{this._clearAnimationLocks(),this.stopAllAnimations()}));e&&this._animatables.push(e)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=je.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}oo.EasingFunction=new class extends Ks{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}},oo.EasingMode=Ks.EASINGMODE_EASEINOUT,oo.IgnoreBoundsSizeMode=0,oo.FitFrustumSidesMode=1;class ao{constructor(e,t,i=Number.MAX_VALUE,s=T){this.origin=e,this.direction=t,this.length=i,this.epsilon=s}clone(){return new ao(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const s=ao._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),r=ao._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let n,o,a,l,h=0,c=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xr.x)return!1}else if(n=1/this.direction.x,o=(s.x-this.origin.x)*n,a=(r.x-this.origin.x)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.yr.y)return!1}else if(n=1/this.direction.y,o=(s.y-this.origin.y)*n,a=(r.y-this.origin.y)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zr.z)return!1}else if(n=1/this.direction.z,o=(s.z-this.origin.z)*n,a=(r.z-this.origin.z)*n,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){const i=e.center.x-this.origin.x,s=e.center.y-this.origin.y,r=e.center.z-this.origin.z,n=i*i+s*s+r*r,o=e.radius+t,a=o*o;if(n<=a)return!0;const l=i*this.direction.x+s*this.direction.y+r*this.direction.z;return!(l<0)&&n-l*l<=a}intersectsTriangle(e,t,i){const s=ao._TmpVector3[0],r=ao._TmpVector3[1],n=ao._TmpVector3[2],o=ao._TmpVector3[3],a=ao._TmpVector3[4];t.subtractToRef(e,s),i.subtractToRef(e,r),w.CrossToRef(this.direction,r,n);const l=w.Dot(s,n);if(0===l)return null;const h=1/l;this.origin.subtractToRef(e,o);const c=w.Dot(o,n)*h;if(c<-this.epsilon||c>1+this.epsilon)return null;w.CrossToRef(o,s,a);const u=w.Dot(this.direction,a)*h;if(u<-this.epsilon||c+u>1+this.epsilon)return null;const d=w.Dot(r,a)*h;return d>this.length?null:new ar(1-c-u,c,d)}intersectsPlane(e){let t;const i=w.Dot(e.normal,this.direction);if(Math.abs(i)<9.99999997475243e-7)return null;{const s=w.Dot(e.normal,this.origin);return t=(-e.d-s)/i,t<0?t<-9.99999997475243e-7?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const e=(this.origin.y-t)/this.direction.y;return e>0?null:new w(this.origin.x+this.direction.x*-e,t,this.origin.z+this.direction.z*-e)}case"x":{const e=(this.origin.x-t)/this.direction.x;return e>0?null:new w(t,this.origin.y+this.direction.y*-e,this.origin.z+this.direction.z*-e)}case"z":{const e=(this.origin.z-t)/this.direction.z;return e>0?null:new w(this.origin.x+this.direction.x*-e,this.origin.y+this.direction.y*-e,t)}default:return null}}intersectsMesh(e,t,i,s=!1,r,n=!1){const o=U.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?ao.TransformToRef(this,o,this._tmpRay):this._tmpRay=ao.Transform(this,o),e.intersects(this._tmpRay,t,i,s,r,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let s=0;st.distance?1:0}intersectionSegment(e,t,i){const s=this.origin,r=U.Vector3[0],n=U.Vector3[1],o=U.Vector3[2],a=U.Vector3[3];t.subtractToRef(e,r),this.direction.scaleToRef(ao._Rayl,o),s.addToRef(o,n),e.subtractToRef(s,a);const l=w.Dot(r,r),h=w.Dot(r,o),c=w.Dot(o,o),u=w.Dot(r,a),d=w.Dot(o,a),p=l*c-h*h;let f,_,m=p,g=p;pm&&(f=m,_=d+h,g=c)),_<0?(_=0,-u<0?f=0:-u>l?f=m:(f=-u,m=l)):_>g&&(_=g,-u+h<0?f=0:-u+h>l?f=m:(f=-u+h,m=l));const v=Math.abs(f)0&&x<=this.length&&E.lengthSquared()=e.distance?null:h:null},ks.prototype._internalPick=function(e,t,i,s,r){let n=null;const o=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),a=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),n=this.cameraToUseForPointers||this.activeCamera;for(let o=0;o(this._tempPickingRay||(this._tempPickingRay=ao.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,r||null),this._tempPickingRay)),i,s,!0);return n&&(n.ray=this.createPickingRay(e,t,B.Identity(),r||null)),n},Object.defineProperty(ks.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),ks.prototype.pick=function(e,t,i,s,r,n,o=!1){const a=this._internalPick(((i,s)=>(this._tempPickingRay||(this._tempPickingRay=ao.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,r||null,!1,s),this._tempPickingRay)),i,s,!1,n);return a&&(a.ray=this.createPickingRay(e,t,B.Identity(),r||null)),a},ks.prototype.pickWithRay=function(e,t,i,s){const r=this._internalPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=B.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=ao.Zero()),ao.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i,!1,s);return r&&(r.ray=e),r},ks.prototype.multiPick=function(e,t,i,s,r){return this._internalMultiPick((i=>this.createPickingRay(e,t,i,s||null)),i,r)},ks.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=B.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=ao.Zero()),ao.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i)},or.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new ao(w.Zero(),w.Zero(),e),e,t,i)},or.prototype.getForwardRayToRef=function(e,t=100,i,s){i||(i=this.getWorldMatrix()),e.length=t,s?e.origin.copyFrom(s):e.origin.copyFrom(this.position);const r=U.Vector3[2];r.set(0,0,this._scene.useRightHandedSystem?-1:1);const n=U.Vector3[3];return w.TransformNormalToRef(r,i,n),w.NormalizeToRef(n,e.direction),e};class lo{static _RemoveAndStorePivotPoint(e){e&&0===lo._PivotCached&&(e.getPivotPointToRef(lo._OldPivotPoint),lo._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,lo._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(B.IdentityReadOnly),lo._OldPivotPoint.subtractToRef(e.getPivotPoint(),lo._PivotTranslation),lo._PivotTmpVector.copyFromFloats(1,1,1),lo._PivotTmpVector.subtractInPlace(e.scaling),lo._PivotTmpVector.multiplyInPlace(lo._PivotTranslation),e.position.addInPlace(lo._PivotTmpVector))),lo._PivotCached++}static _RestorePivotPoint(e){e&&!lo._OldPivotPoint.equalsToFloats(0,0,0)&&1===lo._PivotCached&&(e.setPivotPoint(lo._OldPivotPoint),e._postMultiplyPivotMatrix=lo._PivotPostMultiplyPivotMatrix,lo._PivotTmpVector.copyFromFloats(1,1,1),lo._PivotTmpVector.subtractInPlace(e.scaling),lo._PivotTmpVector.multiplyInPlace(lo._PivotTranslation),e.position.subtractInPlace(lo._PivotTmpVector)),this._PivotCached--}}function ho(e){const t=[],i=[],s=[],r=[],n=e.width||e.size||1,o=e.height||e.size||1,a=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE,l=n/2,h=o/2;i.push(-l,-h,0),s.push(0,0,-1),r.push(0,Er.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),s.push(0,0,-1),r.push(1,Er.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),s.push(0,0,-1),r.push(1,Er.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),s.push(0,0,-1),r.push(0,Er.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),Tr._ComputeSides(a,i,t,s,r,e.frontUVs,e.backUVs);const c=new Tr;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function co(e,t={},i=null){const s=new Un(e,i);return t.sideOrientation=Un._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,ho(t).applyToMesh(s,t.updatable),t.sourcePlane&&(s.translate(t.sourcePlane.normal,-t.sourcePlane.d),s.setDirection(t.sourcePlane.normal.scale(-1))),s}lo._PivotCached=0,lo._OldPivotPoint=new w,lo._PivotTranslation=new w,lo._PivotTmpVector=new w,lo._PivotPostMultiplyPivotMatrix=!1,Tr.CreatePlane=ho,Un.CreatePlane=(e,t,i,s,r)=>co(e,{size:t,width:t,height:t,sideOrientation:r,updatable:s},i);class uo{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new g,this.onDragStartObservable=new g,this.onDragEndObservable=new g,this.onEnabledObservable=new g,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new w(0,0,0),this._alternatePickedPoint=new w(0,0,0),this._worldDragAxis=new w(0,0,0),this._targetPosition=new w(0,0,0),this._attachedToElement=!1,this._startDragRay=new ao(new w,new w),this._lastPointerRay={},this._dragDelta=new w,this._pointA=new w(0,0,0),this._pointC=new w(0,0,0),this._localAxis=new w(0,0,0),this._lookAt=new w(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,uo._PlaneScene||(this._debugMode?uo._PlaneScene=this._scene:(uo._PlaneScene=new ks(this._scene.getEngine(),{virtual:!0}),uo._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce((()=>{uo._PlaneScene.dispose(),uo._PlaneScene=null})))),this._dragPlane=co("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:Un.DOUBLESIDE},uo._PlaneScene),this.lastDragPosition=new w(0,0,0);const i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add((e=>{if(this.enabled){if(e.type==ss.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&i(e.pickInfo.pickedMesh)&&-1===this._activeDragButton&&-1!==this.dragButtons.indexOf(e.event.button)&&(this._activeDragButton=e.event.button,this._activePointerInfo=e,this._startDrag(e.event.pointerId,e.pickInfo.ray,e.pickInfo.pickedPoint));else if(e.type==ss.POINTERUP)!this.startAndReleaseDragOnPointerEvents||this.currentDraggingPointerId!=e.event.pointerId||this._activeDragButton!==e.event.button&&-1!==this._activeDragButton||this.releaseDrag();else if(e.type==ss.POINTERMOVE){const t=e.event.pointerId;if(this.currentDraggingPointerId===uo._AnyMouseId&&t!==uo._AnyMouseId){const i=e.event;("mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[t]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=t)}this._lastPointerRay[t]||(this._lastPointerRay[t]=new ao(new w,new w)),e.pickInfo&&e.pickInfo.ray&&(this._lastPointerRay[t].origin.copyFrom(e.pickInfo.ray.origin),this._lastPointerRay[t].direction.copyFrom(e.pickInfo.ray.direction),this.currentDraggingPointerId==t&&this.dragging&&this._moveDrag(e.pickInfo.ray))}}else this._attachedToElement&&this.releaseDrag()})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{if(this._moving&&this.moveAttached){let e=!1;lo._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),e=!0),lo._RestorePivotPoint(this.attachedNode),e&&this.attachedNode.computeWorldMatrix()}}))}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){const e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}}startDrag(e=uo._AnyMouseId,t,i){this._startDrag(e,t,i);let s=this._lastPointerRay[e];e===uo._AnyMouseId&&(s=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),s&&this._moveDrag(s)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;lo._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);const s=this._pickWithRayOnDragPlane(this._startDragRay);s?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(s),this.onDragStartObservable.notifyObservers({dragPlanePoint:s,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),lo._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;const t=this._pickWithRayOnDragPlane(e);if(t){lo._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?w.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=w.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),lo._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(w.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*w.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);const t=w.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-t,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}return null}const i=this._dragPlane.forward,s=this._dragPlane.position,r=e.direction.dot(i);if(Math.abs(r).999?Math.abs(w.Dot(w.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(w.Right()):this._lookAt.copyFrom(w.UpReadOnly):(w.CrossToRef(this._localAxis,this._pointC,this._lookAt),w.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?w.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}}uo._AnyMouseId=-2;class po{}po.ANCHOR_SYSTEM="xr-anchor-system",po.BACKGROUND_REMOVER="xr-background-remover",po.HIT_TEST="xr-hit-test",po.MESH_DETECTION="xr-mesh-detection",po.PHYSICS_CONTROLLERS="xr-physics-controller",po.PLANE_DETECTION="xr-plane-detection",po.POINTER_SELECTION="xr-controller-pointer-selection",po.TELEPORTATION="xr-controller-teleportation",po.FEATURE_POINTS="xr-feature-points",po.HAND_TRACKING="xr-hand-tracking",po.IMAGE_TRACKING="xr-image-tracking",po.NEAR_INTERACTION="xr-near-interaction",po.DOM_OVERLAY="xr-dom-overlay",po.MOVEMENT="xr-controller-movement",po.LIGHT_ESTIMATION="xr-light-estimation",po.EYE_TRACKING="xr-eye-tracking",po.WALKING_LOCOMOTION="xr-walking-locomotion",po.LAYERS="xr-layers",po.DEPTH_SENSING="xr-depth-sensing",po.SPACE_WARP="xr-space-warp",po.RAW_CAMERA_ACCESS="xr-raw-camera-access";class fo{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)}))})),this._xrSessionManager.onXRSessionEnded.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)}))}))}static AddWebXRFeature(e,t,i=1,s=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),s&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,s){const r=this._AvailableFeatures[e][t];if(!r)throw new Error("feature not found");return r(i,s)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){const t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&(t.featureImplementation.attach()||Ii.Warn(`Feature ${e} failed to attach`))}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&(t.featureImplementation.detach()||Ii.Warn(`Feature ${e} failed to detach`))}disableFeature(e){const t="string"==typeof e?e:e.Name,i=this._features[t];return!(!i||!i.enabled||(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],0))}dispose(){this.getEnabledFeatures().forEach((e=>{this.disableFeature(e)}))}enableFeature(e,t="latest",i={},s=!0,r=!0){const n="string"==typeof e?e:e.Name;let o=0;if("string"==typeof t){if(!t)throw new Error(`Error in provided version - ${n} (${t})`);if(o="stable"===t?fo.GetStableVersionOfFeature(n):"latest"===t?fo.GetLatestVersionOfFeature(n):+t,-1===o||isNaN(o))throw new Error(`feature not found - ${n} (${t})`)}else o=t;const a=fo._ConflictingFeatures[n];if(void 0!==a&&-1!==this.getEnabledFeatures().indexOf(a))throw new Error(`Feature ${n} cannot be enabled while ${a} is enabled.`);const l=this._features[n],h=fo.ConstructFeature(n,o,this._xrSessionManager,i);if(!h)throw new Error(`feature not found - ${n}`);l&&this.disableFeature(n);const c=h();if(c.dependsOn){const e=c.dependsOn.every((e=>!!this._features[e]));if(!e)throw new Error(`Dependant features missing. Make sure the following features are enabled - ${c.dependsOn.join(", ")}`)}if(c.isCompatible())return this._features[n]={featureImplementation:c,enabled:!0,version:o,required:r},s?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(r)throw new Error("required feature not compatible");return Ii.Warn(`Feature ${n} not compatible with the current environment/browser and was not enabled.`),c}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){const t=this.getEnabledFeatures();for(const i of t){const t=this._features[i],s=t.featureImplementation.xrNativeFeatureName;if(s&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(s)&&e.requiredFeatures.push(s)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(s)&&e.optionalFeatures.push(s))),t.featureImplementation.getXRSessionInitExtension){const i=await t.featureImplementation.getXRSessionInitExtension();e={...e,...i}}}return e}}fo._AvailableFeatures={},fo._ConflictingFeatures={[po.TELEPORTATION]:po.MOVEMENT,[po.MOVEMENT]:po.TELEPORTATION};class _o{get xrNativeFeatureName(){return this._xrNativeFeatureName}set xrNativeFeatureName(e){!this._xrSessionManager.isNative&&e&&this._xrSessionManager.inXRSession&&-1===this._xrSessionManager.enabledFeatures?.indexOf(e)&&J.Warn(`The feature ${e} needs to be enabled before starting the XR session. Note - It is still possible it is not supported.`),this._xrNativeFeatureName=e}constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this._xrNativeFeatureName="",this.onFeatureAttachObservable=new g,this.onFeatureDetachObservable=new g}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;if(this._xrSessionManager.enabledFeatures){if(!this._xrSessionManager.isNative&&this.xrNativeFeatureName&&-1===this._xrSessionManager.enabledFeatures.indexOf(this.xrNativeFeatureName))return!1}else J.Warn("session.enabledFeatures is not available on this device. It is possible that this feature is not supported.");return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,(e=>this._onXRFrame(e))),this.onFeatureAttachObservable.notifyObservers(this),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach((e=>{e.observable.remove(e.observer)})),this.onFeatureDetachObservable.notifyObservers(this),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0,this.onFeatureAttachObservable.clear(),this.onFeatureDetachObservable.clear()}isCompatible(){return!0}_addNewAttachObserver(e,t,i){this._removeOnDetach.push({observable:e,observer:e.add(t,void 0,i)})}}class mo{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint,this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}mo.DistanceJoint=0,mo.HingeJoint=1,mo.BallAndSocketJoint=2,mo.WheelJoint=3,mo.SliderJoint=4,mo.PrismaticJoint=5,mo.UniversalJoint=6,mo.Hinge2Joint=mo.WheelJoint,mo.PointToPointJoint=8,mo.SpringJoint=9,mo.LockJoint=10,Un._PhysicsImpostorParser=function(e,t,i){return new go(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};class go{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},s){this.object=e,this.type=t,this._options=i,this._scene=s,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=w.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new L,this._tmpQuat2=new L,this.beforeStep=()=>{this._physicsEngine&&(this.object.translate(this._deltaPosition,-1),this._deltaRotationConjugated&&this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated,this.object.rotationQuaternion),this.object.computeWorldMatrix(!1),this.object.parent&&this.object.rotationQuaternion?(this.getParentsRotation(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this._tmpQuat)):this._tmpQuat.copyFrom(this.object.rotationQuaternion||new L),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach((e=>{e(this)})))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach((e=>{e(this)})),this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this),this.object.parent&&this.object.rotationQuaternion&&(this.getParentsRotation(),this._tmpQuat.conjugateInPlace(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this.object.rotationQuaternion)),this.object.setAbsolutePosition(this.object.position),this._deltaRotation?(this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotation,this.object.rotationQuaternion),this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation,go._TmpVecs[0]),this.object.translate(go._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=e=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent)return;if(!this._physicsEngine)return;const t=this._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(this.onCollideEvent&&this.onCollideEvent(this,t),this._onPhysicsCollideCallbacks.filter((e=>-1!==e.otherImpostors.indexOf(t))).forEach((i=>{i.callback(this,t,e.point,e.distance,e.impulse,e.normal)})))},this.object?(this.object.parent&&0!==i.mass&&J.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),this._scene&&(this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=L.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new L),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&J.Warn("You must affect impostors to children before affecting impostor to parent.")):J.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):J.Error("No object was provided. A physics object is obligatory")}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))}_getPhysicsParent(){return this.object.parent instanceof Wr?this.object.parent.physicsImpostor:null}isBodyInitRequired(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)}setScalingUpdated(){this.forceUpdate()}forceUpdate(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()}get physicsBody(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody}get parent(){return!this._options.ignoreParent&&this._parent?this._parent:null}set parent(e){this._parent=e}set physicsBody(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()}resetUpdateFlags(){this._bodyUpdateRequired=!1}getObjectExtents(){if(this.object.getBoundingInfo){const e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=go.IDENTITY_QUATERNION;const i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);const s=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return s.x=Math.abs(s.x),s.y=Math.abs(s.y),s.z=Math.abs(s.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),s}return go.DEFAULT_OBJECT_SIZE}getObjectCenter(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.centerWorld:this.object.position}getParam(e){return this._options[e]}setParam(e,t){this._options[e]=t,this._bodyUpdateRequired=!0}setMass(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)}getLinearVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):w.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):w.Zero()}setAngularVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)}executeNativeFunction(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)}registerBeforePhysicsStep(e){this._onBeforePhysicsStepCallbacks.push(e)}unregisterBeforePhysicsStep(e){const t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):J.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){const t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):J.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];let s=-1;this._onPhysicsCollideCallbacks.some(((e,r)=>{if(e.callback===t&&e.otherImpostors.length===i.length){const t=e.otherImpostors.every((e=>i.indexOf(e)>-1));return t&&(s=r),t}return!1}))?this._onPhysicsCollideCallbacks.splice(s,1):J.Warn("Function to remove was not found")}getParentsRotation(){let e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):L.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){const s=new mo(t,i);return this.addJoint(e,s),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,s,r){if(!this._physicsEngine)return this;const n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor?(this._physicsEngine&&n.appendAnchor(this,e,t,i,s,r),this):this}addHook(e,t,i,s){if(!this._physicsEngine)return this;const r=this._physicsEngine.getPhysicsPlugin();return r.appendAnchor?(this._physicsEngine&&r.appendHook(this,e,t,i,s),this):this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new go(e,this.type,this._options,this._scene):null}dispose(){this._physicsEngine&&(this._joints.forEach((e=>{this._physicsEngine&&this._physicsEngine.removeJoint(this,e.otherImpostor,e.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)}setDeltaPosition(e){this._deltaPosition.copyFrom(e)}setDeltaRotation(e){this._deltaRotation||(this._deltaRotation=new L),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,s,r){const n=go._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(r){const i=go._TmpQuat;o.rotationQuaternion.multiplyToRef(r,i),e.setRotationQuaternion(i,Fs.WORLD,t)}else e.setRotationQuaternion(o.rotationQuaternion,Fs.WORLD,t);n.x=0,n.y=0,n.z=0,i&&(n.x=i.x,n.y=i.y,n.z=i.z,e.getDirectionToRef(n,t,n),null==s&&(s=i.length()),n.x*=s,n.y*=s,n.z*=s),e.getParent()?(n.addInPlace(o.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(o.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,s,r,n){const o=this.object;if(o.rotationQuaternion)if(r){const i=go._TmpQuat;e.getRotationQuaternionToRef(Fs.WORLD,t,i),i.multiplyToRef(r,o.rotationQuaternion)}else e.getRotationQuaternionToRef(Fs.WORLD,t,o.rotationQuaternion);const a=go._TmpVecs[0],l=go._TmpVecs[1];n||((n=go._TmpVecs[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,a),null==s&&i&&(s=i.length()),null!=s&&(a.x+=l.x*s,a.y+=l.y*s,a.z+=l.z*s),o.setAbsolutePosition(a)}}var vo,xo,To,So,Eo,bo,Co,yo,Ao;go.DEFAULT_OBJECT_SIZE=new w(1,1,1),go.IDENTITY_QUATERNION=L.Identity(),go._TmpVecs=S.BuildArray(3,w.Zero),go._TmpQuat=L.Identity(),go.NoImpostor=0,go.SphereImpostor=1,go.BoxImpostor=2,go.PlaneImpostor=3,go.MeshImpostor=4,go.CapsuleImpostor=6,go.CylinderImpostor=7,go.ParticleImpostor=8,go.HeightmapImpostor=9,go.ConvexHullImpostor=10,go.CustomImpostor=100,go.RopeImpostor=101,go.ClothImpostor=102,go.SoftbodyImpostor=103,function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(vo||(vo={}));class Ro{static get ForceFullSceneLoadingForIncremental(){return Sr.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Sr.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Sr.ShowLoadingScreen}static set ShowLoadingScreen(e){Sr.ShowLoadingScreen=e}static get loggingLevel(){return Sr.loggingLevel}static set loggingLevel(e){Sr.loggingLevel=e}static get CleanBoneMatrixWeights(){return Sr.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Sr.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return Ro._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){return Ro._RegisteredPlugins[e]||(J.Warn("Unable to find a plugin to load "+e+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),Ro.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in Ro._RegisteredPlugins){const i=Ro._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return Ro._RegisteredPlugins[t]}return Ro.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const i=e.lastIndexOf("."),s=e.substring(i,e.length).toLowerCase();return Ro._GetPluginForExtension(s)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let s="Unable to load from "+(e.rawData?"binary data":e.url);return t?s+=`: ${t}`:i&&(s+=`: ${i}`),s}static _LoadData(e,t,i,s,r,n,o,a){const l=Ro._GetDirectLoad(e.url);if(e.rawData&&!o)throw"When using ArrayBufferView to load data the file extension must be provided.";const h=o?Ro._GetPluginForExtension(o):l?Ro._GetPluginForDirectLoad(e.url):Ro._GetPluginForFilename(e.url);if(e.rawData&&!h.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";let c;if(c=void 0!==h.plugin.createPlugin?h.plugin.createPlugin():h.plugin,!c)throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(Ro.OnPluginActivatedObservable.notifyObservers(c),l&&(c.canDirectLoad&&c.canDirectLoad(e.url)||!_i(e.url))){if(c.directLoad){const e=c.directLoad(t,l);e.then?e.then((e=>{i(c,e)})).catch((e=>{r("Error in directLoad of _loadData: "+e,e)})):i(c,e)}else i(c,l);return c}const u=h.isBinary,d=(e,s)=>{t.isDisposed?r("Scene has been disposed"):i(c,e,s)};let p=null,f=!1;const _=c.onDisposeObservable;_&&_.add((()=>{f=!0,p&&(p.abort(),p=null),n()}));const m=()=>{if(f)return;const i=(e,t)=>{r(e?.statusText,t)};if(!c.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";p=c.loadFile?c.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,d,s,u,i,a):t._loadFile(e.file||e.url,d,s,!0,u,i)},g=t.getEngine();let v=g.enableOfflineSupport;if(v){let i=!1;for(const s of t.disableOfflineSupportExceptionRules)if(s.test(e.url)){i=!0;break}v=!i}return v&&Br.OfflineProviderFactory?t.offlineProvider=Br.OfflineProviderFactory(e.url,m,g.disableManifestCheck):m(),c}static _GetFileInfo(e,t){let i,s,r=null,n=null;if(t)if(t.name){const e=t;i=`file:${e.name}`,s=e.name,r=e}else if(ArrayBuffer.isView(t))i="",s=Si(),n=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,s="";else{const r=t;if("/"===r.substr(0,1))return Ii.Error("Wrong sceneFilename parameter"),null;i=e+r,s=r}else i=e,s=Ii.GetFilename(e),e=Ii.GetFolderPath(e);return{url:i,rootUrl:e,name:s,file:r,rawData:n}}static GetPluginForExtension(e){return Ro._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!Ro._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){const t=e.extensions;Ro._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{Ro._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}}))}}static ImportMesh(e,t,i="",s=y.LastCreatedScene,r=null,n=null,o=null,a=null,l=""){if(!s)return J.Error("No scene available to import mesh to"),null;const h=Ro._GetFileInfo(t,i);if(!h)return null;const c={};s.addPendingData(c);const u=()=>{s.removePendingData(c)},d=(e,t)=>{const i=Ro._FormatErrorMessage(h,e,t);o?o(s,i,new Qe(i,qe,t)):J.Error(i),u()},p=n?e=>{try{n(e)}catch(e){d("Error in onProgress callback: "+e,e)}}:void 0,f=(e,t,i,n,o,a,l,u)=>{if(s.importedMeshesFiles.push(h.url),r)try{r(e,t,i,n,o,a,l,u)}catch(e){d("Error in onSuccess callback: "+e,e)}s.removePendingData(c)};return Ro._LoadData(h,s,((t,i,r)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,r)),t.importMesh){const r=[],n=[],o=[];if(!t.importMesh(e,s,i,h.rootUrl,r,n,o,d))return;s.loadingPluginName=t.name,f(r,n,o,[],[],[],[],[])}else t.importMeshAsync(e,s,i,h.rootUrl,p,h.name).then((e=>{s.loadingPluginName=t.name,f(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights,e.spriteManagers)})).catch((e=>{d(e.message,e)}))}),p,d,u,a,l)}static ImportMeshAsync(e,t,i="",s=y.LastCreatedScene,r=null,n=null,o=""){return new Promise(((a,l)=>{Ro.ImportMesh(e,t,i,s,((e,t,i,s,r,n,o,l)=>{a({meshes:e,particleSystems:t,skeletons:i,animationGroups:s,transformNodes:r,geometries:n,lights:o,spriteManagers:l})}),r,((e,t,i)=>{l(i||new Error(t))}),n,o)}))}static Load(e,t="",i=y.LastCreatedEngine,s=null,r=null,n=null,o=null,a=""){return i?Ro.Append(e,t,new ks(i),s,r,n,o,a):(Ii.Error("No engine available"),null)}static LoadAsync(e,t="",i=y.LastCreatedEngine,s=null,r=null,n=""){return new Promise(((o,a)=>{Ro.Load(e,t,i,(e=>{o(e)}),s,((e,t,i)=>{a(i||new Error(t))}),r,n)}))}static Append(e,t="",i=y.LastCreatedScene,s=null,r=null,n=null,o=null,a=""){if(!i)return J.Error("No scene available to append to"),null;const l=Ro._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)};Ro.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1})));const u=(e,t)=>{const s=Ro._FormatErrorMessage(l,e,t);n?n(i,s,new Qe(s,qe,t)):J.Error(s),c()},d=r?e=>{try{r(e)}catch(e){u("Error in onProgress callback",e)}}:void 0,p=()=>{if(s)try{s(i)}catch(e){u("Error in onSuccess callback",e)}i.removePendingData(h)};return Ro._LoadData(l,i,((e,t)=>{if(e.load){if(!e.load(i,t,l.rootUrl,u))return;i.loadingPluginName=e.name,p()}else e.loadAsync(i,t,l.rootUrl,d,l.name).then((()=>{i.loadingPluginName=e.name,p()})).catch((e=>{u(e.message,e)}))}),d,u,c,o,a)}static AppendAsync(e,t="",i=y.LastCreatedScene,s=null,r=null,n=""){return new Promise(((o,a)=>{Ro.Append(e,t,i,(e=>{o(e)}),s,((e,t,i)=>{a(i||new Error(t))}),r,n)}))}static LoadAssetContainer(e,t="",i=y.LastCreatedScene,s=null,r=null,n=null,o=null,a=""){if(!i)return J.Error("No scene available to load asset container to"),null;const l=Ro._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)},u=(e,t)=>{const s=Ro._FormatErrorMessage(l,e,t);n?n(i,s,new Qe(s,qe,t)):J.Error(s),c()},d=r?e=>{try{r(e)}catch(e){u("Error in onProgress callback",e)}}:void 0,p=e=>{if(s)try{s(e)}catch(e){u("Error in onSuccess callback",e)}i.removePendingData(h)};return Ro._LoadData(l,i,((e,t)=>{if(e.loadAssetContainer){const s=e.loadAssetContainer(i,t,l.rootUrl,u);if(!s)return;s.populateRootNodes(),i.loadingPluginName=e.name,p(s)}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,l.rootUrl,d,l.name).then((t=>{t.populateRootNodes(),i.loadingPluginName=e.name,p(t)})).catch((e=>{u(e.message,e)})):u("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),d,u,c,o,a)}static LoadAssetContainerAsync(e,t="",i=y.LastCreatedScene,s=null,r=null){return new Promise(((n,o)=>{Ro.LoadAssetContainer(e,t,i,(e=>{n(e)}),s,((e,t,i)=>{o(i||new Error(t))}),r)}))}static ImportAnimations(e,t="",i=y.LastCreatedScene,s=!0,r=vo.Clean,n=null,o=null,a=null,l=null,h=null){if(!i)return void J.Error("No scene available to load animations to");if(s){for(const e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach((e=>{e.dispose()})),i.getNodes().forEach((e=>{e.animations&&(e.animations=[])}))}else switch(r){case vo.Clean:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case vo.Stop:i.animationGroups.forEach((e=>{e.stop()}));break;case vo.Sync:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case vo.NoSync:break;default:return void J.Error("Unknown animation group loading mode value '"+r+"'")}const c=i.animatables.length;this.LoadAssetContainer(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(c),n),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)}),a,l,h)}static ImportAnimationsAsync(e,t="",i=y.LastCreatedScene,s=!0,r=vo.Clean,n=null,o=null,a=null,l=null,h=null){return new Promise(((o,l)=>{Ro.ImportAnimations(e,t,i,s,r,n,(e=>{o(e)}),a,((e,t,i)=>{l(i||new Error(t))}),h)}))}}Ro.NO_LOGGING=0,Ro.MINIMAL_LOGGING=1,Ro.SUMMARY_LOGGING=2,Ro.DETAILED_LOGGING=3,Ro.OnPluginActivatedObservable=new g,Ro._RegisteredPlugins={},Ro._ShowingLoadingScreen=!1;class Io extends Dn{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new B,this._storeEffectOnSubMeshes=i}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return!!e&&(!this._storeEffectOnSubMeshes||!e.subMeshes||0===e.subMeshes.length||this.isReadyForSubMesh(e,e.subMeshes[0],t))}_isReadyForSubMesh(e){const t=e.materialDefines;return!(this.checkReadyOnEveryCall||!e.effect||!t||t._renderId!==this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,i){super._afterBind(e,t,i),this.getScene()._cachedEffect=t,i?i._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,i,s=1){return i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,s)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}!function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.Object=256]="Object",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.All=4095]="All"}(xo||(xo={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(To||(To={}));class Po{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}get shaderLanguage(){return this.sharedData.nodeMaterial.shaderLanguage}get fSuffix(){return this.shaderLanguage===ht.WGSL?"f":""}finalize(e){const t=e.sharedData.emitComments,i=this.target===To.Fragment;this.shaderLanguage===ht.WGSL?this.compilationString=i?`\n${t?"//Entry point\n":""}@fragment\nfn main(input: FragmentInputs) -> FragmentOutputs {\n${this.compilationString}`:`\n${t?"//Entry point\n":""}@vertex\nfn main(input: VertexInputs) -> FragmentInputs{\n${this.compilationString}`:this.compilationString=`\n${t?"//Entry point\n":""}void main(void) {\n${this.compilationString}`,this._constantDeclaration&&(this.compilationString=`\n${t?"//Constants\n":""}${this._constantDeclaration}\n${this.compilationString}`);let s="";for(const e in this.functions)s+=this.functions[e]+"\n";if(this.compilationString=`\n${s}\n${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString}\n${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString}\n${this._injectAtEnd}`),this.compilationString=`${this.compilationString}\n}`,this.sharedData.varyingDeclaration&&(this.compilationString=`\n${t?"//Varyings\n":""}${this.sharedData.varyingDeclaration}\n${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=`\n${t?"//Samplers\n":""}${this._samplerDeclaration}\n${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=`\n${t?"//Uniforms\n":""}${this._uniformDeclaration}\n${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=`\n${t?"//Attributes\n":""}${this._attributeDeclaration}\n${this.compilationString}`),this.shaderLanguage!==ht.WGSL){this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defines(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,i&&(this.compilationString="#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n"+this.compilationString);for(const e in this.extensions){const t=this.extensions[e];this.compilationString=`\n${t}\n${this.compilationString}`}}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e]?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){this.samplers.indexOf(e)<0&&(this.shaderLanguage===ht.WGSL?(this._samplerDeclaration+=`var ${e+"Sampler"}: sampler;\n`,this._samplerDeclaration+=`var ${e}: texture_2d;\n`):this._samplerDeclaration+=`uniform sampler2D ${e};\n`,this.samplers.push(e))}_emit2DArraySampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2DArray ${e};\n`,this.samplers.push(e))}_getGLType(e){switch(e){case xo.Float:return"float";case xo.Int:return"int";case xo.Vector2:return"vec2";case xo.Color3:case xo.Vector3:return"vec3";case xo.Color4:case xo.Vector4:return"vec4";case xo.Matrix:return"mat4"}return""}_getShaderType(e){const t=this.shaderLanguage===ht.WGSL;switch(e){case xo.Float:return t?"f32":"float";case xo.Int:return t?"i32":"int";case xo.Vector2:return t?"vec2f":"vec2";case xo.Color3:case xo.Vector3:return t?"vec3f":"vec3";case xo.Color4:case xo.Vector4:return t?"vec4f":"vec4";case xo.Matrix:return t?"mat4x4f":"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i}\n${t}\n#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+"\n"+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`;let s=Ft.GetIncludesShadersStore(this.shaderLanguage)[e]+"\n";if(this.sharedData.emitComments&&(s=t+"\n"+s),!i)return s;if(i.replaceStrings)for(let e=0;e${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\n`:this.functions[r]=`#include<${e}>${i?.substitutionVars?"("+i?.substitutionVars+")":""}\n`,void(this.sharedData.emitComments&&(this.functions[r]=t+"\n"+this.functions[r]));const n=Ft.GetIncludesShadersStore(this.shaderLanguage);if(this.functions[r]=n[e],this.sharedData.emitComments&&(this.functions[r]=t+"\n"+this.functions[r]),i.removeIfDef&&(this.functions[r]=this.functions[r].replace(/^\s*?#ifdef.+$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#endif.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#else.*$/gm,""),this.functions[r]=this.functions[r].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[r]=this.functions[r].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[r]=this.functions[r].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[r]=this.functions[r].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(let e=0;e")}_convertTernaryOperandsToWGSL(e){return e.replace(new RegExp("\\[(.*?)\\?(.*?):(.*)\\]","g"),((e,t,i,s)=>`select(${s}, ${i}, ${t})`))}_convertModOperatorsToWGSL(e){return e.replace(new RegExp("mod\\((.+?),\\s*(.+?)\\)","g"),((e,t,i)=>`((${t})%(${i}))`))}_convertConstToWGSL(e){return e.replace(new RegExp("const var","g"),"const")}_convertInnerFunctionsToWGSL(e){return e.replace(new RegExp("inversesqrt","g"),"inverseSqrt")}_convertFunctionsToWGSL(e){const t=/var\s+(\w+)\s*:\s*(\w+)\((.*)\)/g;let i;for(;null!==(i=t.exec(e));){const t=i[1],s=i[2],r=i[3].replace(/var\s/g,"");e=e.replace(i[0],`fn ${t}(${r}) -> ${s}`)}return e}_babylonSLtoWGSL(e){return e=this._convertVariableDeclarationToWGSL("void","voidnull",e),e=this._convertVariableDeclarationToWGSL("bool","bool",e),e=this._convertVariableDeclarationToWGSL("int","i32",e),e=this._convertVariableDeclarationToWGSL("uint","u32",e),e=this._convertVariableDeclarationToWGSL("float","f32",e),e=this._convertVariableDeclarationToWGSL("vec2","vec2f",e),e=this._convertVariableDeclarationToWGSL("vec3","vec3f",e),e=this._convertVariableDeclarationToWGSL("vec4","vec4f",e),e=this._convertVariableDeclarationToWGSL("mat2","mat2x2f",e),e=this._convertVariableDeclarationToWGSL("mat3","mat3x3f",e),e=this._convertVariableDeclarationToWGSL("mat4","mat4x4f",e),e=this._convertVariableConstructorsToWGSL("float","f32",e),e=this._convertVariableConstructorsToWGSL("vec2","vec2f",e),e=this._convertVariableConstructorsToWGSL("vec3","vec3f",e),e=this._convertVariableConstructorsToWGSL("vec4","vec4f",e),e=this._convertVariableConstructorsToWGSL("mat2","mat2x2f",e),e=this._convertVariableConstructorsToWGSL("mat3","mat3x3f",e),e=this._convertVariableConstructorsToWGSL("mat4","mat4x4f",e),e=this._convertTernaryOperandsToWGSL(e),e=this._convertModOperatorsToWGSL(e),e=this._convertConstToWGSL(e),e=this._convertInnerFunctionsToWGSL(e),e=(e=this._convertOutParametersToWGSL(e)).replace(/\[\*\]/g,"*"),(e=(e=(e=this._convertFunctionsToWGSL(e)).replace(/\s->\svoidnull/g,"")).replace(/dFdx/g,"dpdx")).replace(/dFdy/g,"dpdy")}_convertTernaryOperandsToGLSL(e){return e.replace(new RegExp("\\[(.+?)\\?(.+?):(.+)\\]","g"),((e,t,i,s)=>`${t} ? ${i} : ${s}`))}_babylonSLtoGLSL(e){return e=e.replace(/\[\*\]/g,""),this._convertTernaryOperandsToGLSL(e)}}class Mo{constructor(){this.temps=[],this.varyings=[],this.varyingDeclaration="",this.inputBlocks=[],this.textureBlocks=[],this.bindableBlocks=[],this.forcedBindableBlocks=[],this.blocksWithFallbacks=[],this.blocksWithDefines=[],this.repeatableContentBlocks=[],this.dynamicUniformBlocks=[],this.blockingBlocks=[],this.animatedInputs=[],this.variableNames={},this.defineNames={},this.hints={needWorldViewMatrix:!1,needWorldViewProjectionMatrix:!1,needAlphaBlending:!1,needAlphaTesting:!1},this.checks={emitVertex:!1,emitFragment:!1,notConnectedNonOptionalInputs:new Array},this.allowEmptyVertexProgram=!1,this.variableNames.position=0,this.variableNames.normal=0,this.variableNames.tangent=0,this.variableNames.uv=0,this.variableNames.uv2=0,this.variableNames.uv3=0,this.variableNames.uv4=0,this.variableNames.uv5=0,this.variableNames.uv6=0,this.variableNames.color=0,this.variableNames.matricesIndices=0,this.variableNames.matricesWeights=0,this.variableNames.matricesIndicesExtra=0,this.variableNames.matricesWeightsExtra=0,this.variableNames.diffuseBase=0,this.variableNames.specularBase=0,this.variableNames.worldPos=0,this.variableNames.shadow=0,this.variableNames.view=0,this.variableNames.vTBN=0,this.defineNames.MAINUV0=0,this.defineNames.MAINUV1=0,this.defineNames.MAINUV2=0,this.defineNames.MAINUV3=0,this.defineNames.MAINUV4=0,this.defineNames.MAINUV5=0,this.defineNames.MAINUV6=0,this.defineNames.MAINUV7=0}emitErrors(){let e="";this.checks.emitVertex||this.allowEmptyVertexProgram||(e+="NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.\n"),this.checks.emitFragment||(e+="NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\n");for(const t of this.checks.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional.\n`;if(e)throw"Build of NodeMaterial failed:\n"+e}}class Do{constructor(e){if(this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!1,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)-1===this._keys.indexOf(e)&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;tthis._setDefaultValue(e)))}_setDefaultValue(e){const t=this._externalProperties?.[e]?.type??typeof this[e],i=this._externalProperties?.[e]?.default;switch(t){case"number":this[e]=i??0;break;case"string":this[e]=i??"";break;default:this[e]=i??!1}}toString(){let e="";for(let t=0;tthis._connectedPointBackingField=e)),this._connectedPointBackingField&&(this._connectedPointTypeChangedObserver=this._connectedPointBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get _typeConnectionSource(){return this._typeConnectionSourceBackingField}set _typeConnectionSource(e){this._typeConnectionSourceBackingField!==e&&(this._typeConnectionSourceTypeChangedObserver?.remove(),this._updateTypeDependentState((()=>this._typeConnectionSourceBackingField=e)),this._typeConnectionSourceBackingField&&(this._typeConnectionSourceTypeChangedObserver=this._typeConnectionSourceBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get _defaultConnectionPointType(){return this._defaultConnectionPointTypeBackingField}set _defaultConnectionPointType(e){this._updateTypeDependentState((()=>this._defaultConnectionPointTypeBackingField=e))}get _linkedConnectionSource(){return this._linkedConnectionSourceBackingField}set _linkedConnectionSource(e){this._linkedConnectionSourceBackingField!==e&&(this._linkedConnectionSourceTypeChangedObserver?.remove(),this._updateTypeDependentState((()=>this._linkedConnectionSourceBackingField=e)),this._linkedConnectionSourceBackingField&&(this._linkedConnectionSourceTypeChangedObserver=this._linkedConnectionSourceBackingField.onTypeChangedObservable.add((()=>{this._notifyTypeChanged()}))))}get direction(){return this._direction}get declarationVariableName(){return this._ownerBlock.isInput?this._ownerBlock.declarationVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.declarationVariableName}get associatedVariableName(){return this._ownerBlock.isInput?this._ownerBlock.associatedVariableName:this._enforceAssociatedVariableName&&this._associatedVariableName||!this._connectedPoint?this._associatedVariableName:this._connectedPoint.associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}get type(){if(this._type===xo.AutoDetect){if(this._ownerBlock.isInput)return this._ownerBlock.type;if(this._connectedPoint)return this._connectedPoint.type;if(this._linkedConnectionSource&&this._linkedConnectionSource.isConnected)return this._linkedConnectionSource.type}if(this._type===xo.BasedOnInput){if(this._typeConnectionSource)return!this._typeConnectionSource.isConnected&&this._defaultConnectionPointType?this._defaultConnectionPointType:this._typeConnectionSource.type;if(this._defaultConnectionPointType)return this._defaultConnectionPointType}return this._type}set type(e){this._updateTypeDependentState((()=>this._type=e))}get target(){return this._prioritizeVertex&&this._ownerBlock?this._target!==To.VertexAndFragment?this._target:this._ownerBlock.target===To.Fragment?To.Fragment:To.Vertex:this._target}set target(e){this._target=e}get isConnected(){return null!==this.connectedPoint||this.hasEndpoints}get isConnectedToInputBlock(){return null!==this.connectedPoint&&this.connectedPoint.ownerBlock.isInput}get connectInputBlock(){return this.isConnectedToInputBlock?this.connectedPoint.ownerBlock:null}get connectedPoint(){return this._connectedPoint}get ownerBlock(){return this._ownerBlock}get sourceBlock(){return this._connectedPoint?this._connectedPoint.ownerBlock:null}get connectedBlocks(){return 0===this._endpoints.length?[]:this._endpoints.map((e=>e.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===To.Vertex)return!0;if((e.ownerBlock.target===To.Neutral||e.ownerBlock.target===To.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isDirectlyConnectedToVertexOutput)))return!0}return!1}get isConnectedInVertexShader(){if(this.target===To.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===To.Vertex)return!0;if(e.target===To.Vertex)return!0;if((e.ownerBlock.target===To.Neutral||e.ownerBlock.target===To.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInVertexShader)))return!0}return!1}get isConnectedInFragmentShader(){if(this.target===To.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===To.Fragment)return!0;if((e.ownerBlock.target===To.Neutral||e.ownerBlock.target===To.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0}return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPointBackingField=null,this._endpoints=new Array,this._typeConnectionSourceBackingField=null,this._defaultConnectionPointTypeBackingField=null,this._linkedConnectionSourceBackingField=null,this._acceptedConnectionPointType=null,this._type=xo.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new g,this.onDisconnectionObservable=new g,this.onTypeChangedObservable=new g,this._isTypeChangeObservableNotifying=!1,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=To.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===So.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===To.Fragment){if(i.target===To.Vertex)return So.TargetIncompatible;for(const e of i.outputs)if(e.ownerBlock.target!=To.Neutral&&e.isConnectedInVertexShader)return So.TargetIncompatible}if(this.type!==e.type&&e.innerType!==xo.AutoDetect)return Oo.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&Oo.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?So.Compatible:So.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return So.TypeIncompatible;let s=i,r=t;return this.direction===Eo.Input&&(s=t,r=i),s.isAnAncestorOf(r)?So.HierarchyIssue:So.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear(),this.onTypeChangedObservable.clear(),this._connectedPoint=null,this._typeConnectionSource=null,this._linkedConnectionSource=null}_updateTypeDependentState(e){const t=this.type;e(),this.type!==t&&this._notifyTypeChanged()}_notifyTypeChanged(){this._isTypeChangeObservableNotifying||(this._isTypeChangeObservableNotifying=!0,this.onTypeChangedObservable.notifyObservers(this.type),this._isTypeChangeObservableNotifying=!1)}}class No{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){this._target&e||(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}constructor(e,t=To.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===To.Neutral,this._isFinalMerger=i,this._isInput="InputBlock"===this.getClassName(),this._isTeleportOut="NodeMaterialTeleportOutBlock"===this.getClassName(),this._isTeleportIn="NodeMaterialTeleportInBlock"===this.getClassName(),this._name=e,this.uniqueId=Ds.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===To.Neutral}initialize(e){}bind(e,t,i,s){}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return-1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some((e=>e.isConnectedInFragmentShader))}registerInput(e,t,i=!1,s,r){return(r=r??new Oo(e,this,Eo.Input)).type=t,r.isOptional=i,s&&(r.target=s),this._inputs.push(r),this}registerOutput(e,t,i,s){return(s=s??new Oo(e,this,Eo.Output)).type=t,i&&(s.target=i),this._outputs.push(s),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!(t.connectedPoint||e&&e.type!==t.type&&t.type!==xo.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===To.Neutral||e.target&t.target)return t;return null}getSiblingOutput(e){const t=this._outputs.indexOf(e);return-1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){if(i.ownerBlock===e)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),s=!0;for(;s;){const r=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&r&&i.canConnectTo(r))i.connectTo(r),s=!1;else{if(!i)throw"Unable to find a compatible match";i=this.getSiblingOutput(i)}}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,s){}provideFallbacks(e,t){}initializeDefines(e,t,i,s=!1){}prepareDefines(e,t,i,s=!1,r){}autoConfigure(e,t=(()=>!0)){}replaceRepeatableContent(e,t,i,s){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some((e=>e.isDirectlyConnectedToVertexOutput))||this.target===To.Vertex||this.target!==To.VertexAndFragment&&this.target!==To.Neutral||!this._outputs.some((e=>e.isConnectedInVertexShader)))}isReady(e,t,i,s=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,s){e.build(t,s);const r=null!=t._vertexState,n=e._buildTarget===To.Vertex&&e.target!==To.VertexAndFragment;if(r&&(!(e.target&e._buildTarget)||!(e.target&i.target)||this.target!==To.VertexAndFragment&&n)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){const e=i.connectedPoint;if(t._vertexState._emitVaryingFromString("v_"+e.declarationVariableName,e.type)){const i=t.shaderLanguage===ht.WGSL?"vertexOutputs.":"";t._vertexState.compilationString+=`${i}${"v_"+e.declarationVariableName} = ${e.associatedVariableName};\n`}const s=t.shaderLanguage===ht.WGSL?"fragmentInputs.":"";i.associatedVariableName=s+"v_"+e.declarationVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){const t=["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"];for(const i of t)if(e===i)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(const t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==To.Neutral){if(!(i.target&this.target))continue;if(!(i.target&e.target))continue}const s=i.connectedPoint.ownerBlock;s&&s!==this&&this._processBuild(s,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&J.Log(`${e.target===To.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case To.Vertex:e.sharedData.checks.emitVertex=!0;break;case To.Fragment:e.sharedData.checks.emitFragment=!0}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=`\n//${this.name}\n`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(const i of this._outputs)if(i.target&e.target)for(const s of i.endpoints){const i=s.ownerBlock;i&&i.target&e.target&&-1!==t.indexOf(i)&&this._processBuild(i,e,s,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector};\n${e}.visibleOnFrame = ${this.visibleOnFrame};\n${e}.target = ${this.target};\n`}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let s=`\n// ${this.getClassName()}\n`;this.comments&&(s+=`// ${this.comments}\n`),s+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\n`,s+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint.ownerBlock;-1===t.indexOf(r)&&(s+=r._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const r of i.endpoints){const i=r.ownerBlock;i&&-1===t.indexOf(i)&&(s+=i._dumpCode(e,t))}return s}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}return t}clone(e,t=""){const i=this.serialize(),s=d(i.customType);if(s){const r=new s;return r._deserialize(i,e,t),r}return null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i,s){this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=e.target??this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach(((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class wo extends No{constructor(e){super(e,To.Neutral),this.complementW=1,this.complementZ=0,this.target=To.Vertex,this.registerInput("vector",xo.AutoDetect),this.registerInput("transform",xo.Matrix),this.registerOutput("output",xo.Vector4),this.registerOutput("xyz",xo.Vector3),this._inputs[0].onConnectionObservable.add((e=>{if(e.ownerBlock.isInput){const t=e.ownerBlock;"normal"!==t.name&&"tangent"!==t.name||(this.complementW=0)}}))}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.transform,s=e._getShaderType(xo.Vector4),r=e._getShaderType(xo.Vector3);if(t.connectedPoint){if(0===this.complementW){const n=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",n),e.sharedData.blocksWithDefines.push(this);const o=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.shaderLanguage===ht.WGSL?e.compilationString+=`var ${o}: mat3x3f = mat3x3f(${i.associatedVariableName}[0].xyz, ${i.associatedVariableName}[1].xyz, ${i.associatedVariableName}[2].xyz);\n`:e.compilationString+=`mat3 ${o} = mat3(${i.associatedVariableName});\n`,e.compilationString+="#ifdef NONUNIFORMSCALING\n",e.compilationString+=`${o} = transposeMat3(inverseMat3(${o}));\n`,e.compilationString+="#endif\n",t.connectedPoint.type){case xo.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${s}(${o} * ${r}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\n`;break;case xo.Vector3:case xo.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${s}(${o} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${s}(${o} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\n`}}else{const r=i.associatedVariableName;switch(t.connectedPoint.type){case xo.Vector2:e.compilationString+=e._declareOutput(this.output)+` = ${r} * ${s}(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\n`;break;case xo.Vector3:case xo.Color3:e.compilationString+=e._declareOutput(this.output)+` = ${r} * ${s}(${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\n`;break;default:e.compilationString+=e._declareOutput(this.output)+` = ${r} * ${t.associatedVariableName};\n`}}this.xyz.hasEndpoints&&(e.compilationString+=e._declareOutput(this.xyz)+` = ${this.output.associatedVariableName}.xyz;\n`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){const e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ};\n`;return e+=`${this._codeVariableName}.complementW = ${this.complementW};\n`,e}}u("BABYLON.TransformBlock",wo);class Fo extends No{constructor(e){super(e,To.Vertex,!0),this.registerInput("vector",xo.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e,t){if(t)return!0;for(const t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);const t=this.vector;return e.shaderLanguage===ht.WGSL?e.compilationString+=`vertexOutputs.position = ${t.associatedVariableName};\n`:e.compilationString+=`gl_Position = ${t.associatedVariableName};\n`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes,e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant",xo.Float),e._emitVaryingFromString("vFragmentDepth",xo.Float),e.compilationString+="vFragmentDepth = 1.0 + gl_Position.w;\n",e.compilationString+="gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\n"),this}}function Lo(e,t=bo.Boolean,i="PROPERTIES",s){return(r,n)=>{let o=r._propStore;o||(o=[],r._propStore=o),o.push({propertyName:n,displayName:e,type:t,groupName:i,options:s??{}})}}u("BABYLON.VertexOutputBlock",Fo),function(e){e[e.Boolean=0]="Boolean",e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=3]="Vector2",e[e.List=4]="List"}(bo||(bo={}));class Bo extends No{constructor(e){super(e,To.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",xo.Color4,!0),this.registerInput("rgb",xo.AutoDetect,!0),this.registerInput("a",xo.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){(this.useLogarithmicDepth||t.useLogarithmicDepth)&&i&&Jr(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,s=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||s.isConnected,e.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant",xo.Float),e._emitVaryingFromString("vFragmentDepth",xo.Float),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r);let n="gl_FragColor";e.shaderLanguage===ht.WGSL&&(n="fragmentOutputs.color");const o=e._getShaderType(xo.Vector4);if(t.connectedPoint)s.isConnected?e.compilationString+=`${n} = ${o}(${t.associatedVariableName}.rgb, ${s.associatedVariableName});\n`:e.compilationString+=`${n} = ${t.associatedVariableName};\n`;else if(i.connectedPoint){let t="1.0";s.connectedPoint&&(t=s.associatedVariableName),i.connectedPoint.type===xo.Float?e.compilationString+=`${n} = ${o}(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t});\n`:e.compilationString+=`${n} = ${o}(${i.associatedVariableName}, ${t});\n`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${n} = toLinearSpace(${n});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${n} = toGammaSpace(${n});\n`,e.compilationString+="#endif\n",(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e.compilationString+="gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\n"),e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+="gl_FragData[0] = gl_FragColor;\r\n",e.compilationString+="#endif\r\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\n`,e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.useLogarithmicDepth=e.useLogarithmicDepth??!1}}ae([Lo("Convert to gamma space",bo.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Bo.prototype,"convertToGammaSpace",void 0),ae([Lo("Convert to linear space",bo.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Bo.prototype,"convertToLinearSpace",void 0),ae([Lo("Use logarithmic depth",bo.Boolean,"PROPERTIES")],Bo.prototype,"useLogarithmicDepth",void 0),u("BABYLON.FragmentOutputBlock",Bo),function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(Co||(Co={})),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime",e[e.CameraParameters=10]="CameraParameters",e[e.MaterialAlpha=11]="MaterialAlpha"}(yo||(yo={})),function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime",e[e.MouseInfo=3]="MouseInfo"}(Ao||(Ao={}));const Vo={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},Uo={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},ko={particle_texturemask:!0};class Go extends No{get type(){if(this._type===xo.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=xo.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=xo.Vector2,this._type;case"Vector3":return this._type=xo.Vector3,this._type;case"Vector4":return this._type=xo.Vector4,this._type;case"Color3":return this._type=xo.Color3,this._type;case"Color4":return this._type=xo.Color4,this._type;case"Matrix":return this._type=xo.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=xo.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=xo.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=xo.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=xo.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case yo.World:case yo.WorldView:case yo.WorldViewProjection:case yo.View:case yo.ViewProjection:case yo.Projection:return this._type=xo.Matrix,this._type;case yo.CameraPosition:return this._type=xo.Vector3,this._type;case yo.FogColor:return this._type=xo.Color3,this._type;case yo.DeltaTime:case yo.MaterialAlpha:return this._type=xo.Float,this._type;case yo.CameraParameters:return this._type=xo.Vector4,this._type}}return this._type}constructor(e,t=To.Vertex,i=xo.AutoDetect){super(e,t,!1),this._mode=Co.Undefined,this._animationType=Ao.None,this._prefix="",this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new g,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=Co.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===xo.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=Co.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=Co.Uniform}get declarationVariableName(){return this._associatedVariableName}get associatedVariableName(){return this._prefix+this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===Co.Undefined}get isUniform(){return this._mode===Co.Uniform}set isUniform(e){this._mode=e?Co.Uniform:Co.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===Co.Attribute}set isAttribute(e){this._mode=e?Co.Attribute:Co.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===Co.Varying}set isVarying(e){this._mode=e?Co.Varying:Co.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=Co.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case Ao.Time:this.type===xo.Float&&(this.value+=.01*e.getAnimationRatio());break;case Ao.RealTime:this.type===xo.Float&&(this.value=(je.Now-e.getEngine().startTime)/1e3);break;case Ao.MouseInfo:if(this.type===xo.Vector4){const t=e._inputManager._originMouseEvent;if(t){const e=t.offsetX,i=t.offsetY,s=1&t.buttons?1:0,r=2&t.buttons?1:0;this.value=new F(e,i,s,r)}else this.value=new F(0,0,0,0)}}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)}\n`:`#ifdef ${e}\n`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case xo.Float:this.value=0;break;case xo.Vector2:this.value=N.Zero();break;case xo.Vector3:this.value=w.Zero();break;case xo.Vector4:this.value=F.Zero();break;case xo.Color3:this.value=Y.White();break;case xo.Color4:this.value=new j(1,1,1,1);break;case xo.Matrix:this.value=B.Identity()}}_emitConstant(e){switch(this.type){case xo.Float:return`${e._emitFloat(this.value)}`;case xo.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case xo.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case xo.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case xo.Color3:return $.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&$.Color3[0].toGammaSpaceToRef($.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&$.Color3[0].toLinearSpaceToRef($.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${$.Color3[0].r}, ${$.Color3[0].g}, ${$.Color3[0].b})`;case xo.Color4:return $.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&$.Color4[0].toGammaSpaceToRef($.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&$.Color4[0].toLinearSpaceToRef($.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${$.Color4[0].r}, ${$.Color4[0].g}, ${$.Color4[0].b}, ${$.Color4[0].a})`}return""}get _noContextSwitch(){return Uo[this.name]}_emit(e,t){if(this.isUniform){if(this._associatedVariableName||(this._associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;return e.constants.push(this.associatedVariableName),void(e._constantDeclaration+=e._declareOutput(this.output,!0)+` = ${this._emitConstant(e)};\n`)}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t));const i=e._getShaderType(this.type);e.shaderLanguage===ht.WGSL?(e._uniformDeclaration+=`uniform ${this._associatedVariableName}: ${i};\n`,this._prefix="uniforms."):e._uniformDeclaration+=`uniform ${i} ${this.associatedVariableName};\n`,t&&(e._uniformDeclaration+="#endif\n");const s=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case yo.WorldView:s.needWorldViewMatrix=!0;break;case yo.WorldViewProjection:s.needWorldViewProjectionMatrix=!0}else this._animationType!==Ao.None&&e.sharedData.animatedInputs.push(this)}else if(this.isAttribute){if(this.associatedVariableName=Vo[this.name]??this.name,this.target===To.Vertex&&e._vertexState)return void(Uo[this.name]?ko[this.name]?(e._emitUniformFromString(this.associatedVariableName,this.type,t),e.shaderLanguage===ht.WGSL&&(this._prefix="vertexInputs.")):e._emitVaryingFromString(this.associatedVariableName,this.type,t):this._emit(e._vertexState,t));if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),Uo[this.name]?ko[this.name]?e._emitUniformFromString(this.associatedVariableName,this.type,t):e._emitVaryingFromString(this.associatedVariableName,this.type,t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e.shaderLanguage===ht.WGSL?(e._attributeDeclaration+=`attribute ${this.associatedVariableName}: ${e._getShaderType(this.type)};\n`,this._prefix="vertexInputs."):e._attributeDeclaration+=`attribute ${e._getShaderType(this.type)} ${this.associatedVariableName};\n`,t&&(e._attributeDeclaration+="#endif\n"))}}_transmitWorld(e,t,i,s){if(!this._systemValue)return;const r=this._associatedVariableName;switch(this._systemValue){case yo.World:e.setMatrix(r,t);break;case yo.WorldView:e.setMatrix(r,i);break;case yo.WorldViewProjection:e.setMatrix(r,s)}}_transmit(e,t,i){if(this.isAttribute)return;const s=this._associatedVariableName;if(this._systemValue){switch(this._systemValue){case yo.World:case yo.WorldView:case yo.WorldViewProjection:return;case yo.View:e.setMatrix(s,t.getViewMatrix());break;case yo.Projection:e.setMatrix(s,t.getProjectionMatrix());break;case yo.ViewProjection:e.setMatrix(s,t.getTransformMatrix());break;case yo.CameraPosition:t.bindEyePosition(e,s,!0);break;case yo.FogColor:e.setColor3(s,t.fogColor);break;case yo.DeltaTime:e.setFloat(s,t.deltaTime/1e3);break;case yo.CameraParameters:t.activeCamera&&e.setFloat4(s,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case yo.MaterialAlpha:e.setFloat(s,i.alpha)}return}const r=this._valueCallback?this._valueCallback():this._storedValue;if(null!==r)switch(this.type){case xo.Float:e.setFloat(s,r);break;case xo.Int:e.setInt(s,r);break;case xo.Color3:$.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&$.Color3[0].toGammaSpaceToRef($.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&$.Color3[0].toLinearSpaceToRef($.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(s,$.Color3[0]);break;case xo.Color4:$.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&$.Color4[0].toGammaSpaceToRef($.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&$.Color4[0].toLinearSpaceToRef($.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(s,$.Color4[0]);break;case xo.Vector2:e.setVector2(s,r);break;case xo.Vector3:e.setVector3(s,r);break;case xo.Vector4:e.setVector4(s,r);break;case xo.Matrix:e.setMatrix(s,r)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}");\n`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${yo[this._systemValue]});\n`;if(this.isUniform){const t=[];let i="";switch(this.type){case xo.Float:i=`${this.value}`;break;case xo.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case xo.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case xo.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case xo.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case xo.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case xo.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===xo.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${Ao[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){const e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,null!=this._storedValue&&this._mode===Co.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,"tangent"===e.name&&e.mode===Co.Attribute&&e.type===xo.Vector3&&(this._type=xo.Vector4),e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=d(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}u("BABYLON.InputBlock",Go);class zo extends No{constructor(e){super(e,To.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",xo.AutoDetect,!1,To.VertexAndFragment),this.registerOutput("rgba",xo.Color4,To.Neutral),this.registerOutput("rgb",xo.Color3,To.Neutral),this.registerOutput("r",xo.Float,To.Neutral),this.registerOutput("g",xo.Float,To.Neutral),this.registerOutput("b",xo.Float,To.Neutral),this.registerOutput("a",xo.Float,To.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Vector2|xo.Vector3|xo.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?To.VertexAndFragment:To.Fragment:To.VertexAndFragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,xo.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,xo.Vector2),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===To.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\n`}else this.uv.ownerBlock.target!==To.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\n`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===To.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target!==To.Fragment?(e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"):e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.blockingBlocks.indexOf(this)<0&&e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.indexOf(this)<0&&e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.indexOf(this)<0&&e.sharedData.blocksWithDefines.push(this),e.target!==To.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Zn.Parse(e.texture,t,i))}}u("BABYLON.CurrentScreenBlock",zo);class Wo extends No{constructor(e){super(e,To.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",xo.AutoDetect,!1,To.VertexAndFragment),this.registerOutput("rgba",xo.Color4,To.Neutral),this.registerOutput("rgb",xo.Color3,To.Neutral),this.registerOutput("r",xo.Float,To.Neutral),this.registerOutput("g",xo.Float,To.Neutral),this.registerOutput("b",xo.Float,To.Neutral),this.registerOutput("a",xo.Float,To.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Vector2|xo.Vector3|xo.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"particle_uv"===e.name&&t(e)));i||(i=new Go("uv"),i.setAsAttribute("particle_uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_writeOutput(e,t,i){e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n`,e.compilationString+="#endif\n"}_buildBlock(e){if(super._buildBlock(e),e.target===To.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName});\n`;for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Zn.Parse(e.texture,t,i))}}u("BABYLON.ParticleTextureBlock",Wo);class Ho extends No{constructor(e){super(e,To.Fragment),this._isUnique=!0,this.registerInput("color",xo.Color4,!1,To.Fragment),this.registerOutput("rampColor",xo.Color4,To.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==To.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges",xo.Vector4,"RAMPGRADIENT"),e.compilationString+=`\n #ifdef RAMPGRADIENT\n vec4 baseColor = ${this.color.associatedVariableName};\n float alpha = ${this.color.associatedVariableName}.a;\n\n float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\n\n vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));\n baseColor.rgb *= rampColor.rgb;\n\n // Remapped alpha\n float finalAlpha = baseColor.a;\n baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);\n\n ${e._declareOutput(this.rampColor)} = baseColor;\n #else\n ${e._declareOutput(this.rampColor)} = ${this.color.associatedVariableName};\n #endif\n `,this}}u("BABYLON.ParticleRampGradientBlock",Ho);class Xo extends No{constructor(e){super(e,To.Fragment),this._isUnique=!0,this.registerInput("color",xo.Color4,!1,To.Fragment),this.registerInput("alphaTexture",xo.Float,!1,To.Fragment),this.registerInput("alphaColor",xo.Float,!1,To.Fragment),this.registerOutput("blendColor",xo.Color4,To.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==To.Vertex)return e.compilationString+=`\n #ifdef BLENDMULTIPLYMODE\n ${e._declareOutput(this.blendColor)};\n float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};\n ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);\n ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a;\n #else\n ${e._declareOutput(this.blendColor)} = ${this.color.associatedVariableName};\n #endif\n `,this}}u("BABYLON.ParticleBlendMultiplyBlock",Xo);class Yo{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let e=0;e0&&(s.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;i0}get is3D(){return this.depth>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){return this._textures?.[0]??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;const s=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,s}constructor(e,t,i,s,r){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=s,this._depthStencilTexture=null,this.label=r}setTextures(e){Array.isArray(e)?this._textures=e:this._textures=e?[e]:null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){return this._depthStencilTexture?.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:s,depthTextureFormat:r,label:n},this),this._depthStencilTexture}_shareDepth(e){this.shareDepth(e)}shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){let e=null;if(this._isMulti){const t=this.textures;if(t&&t.length>0){let i=!1,s=t.length,r=-1;const n=t[t.length-1]._source;n!==ei.Depth&&n!==ei.DepthStencil||(i=!0,r=t[t.length-1].format,s--);const o=[],a=[],l=[],h=[],c=[],u=[],d=[],p={};for(let e=0;e1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e1){const r=this._context,n=r["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=i??this.layerIndices?.[t]??0,r.framebufferTextureLayer(r.FRAMEBUFFER,n,e._hardwareTexture.underlyingResource,s,i)):e.isCube?(i=i??this.faceIndices?.[t]??0,r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,s)):r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_2D,e._hardwareTexture.underlyingResource,s)}else{const r=this._context,n=r["COLOR_ATTACHMENT"+t+"_WEBGL"],o=void 0!==i?r.TEXTURE_CUBE_MAP_POSITIVE_X+i:r.TEXTURE_2D;r.framebufferTexture2D(r.FRAMEBUFFER,n,o,e._hardwareTexture.underlyingResource,s)}n._bindUnboundFramebuffer(o)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=this._attachments?.length??this.textures.length;for(let e=0;e1&&(15===o.format?u=i.DEPTH_COMPONENT16:16===o.format?u=i.DEPTH_COMPONENT24:17===o.format||13===o.format?u=i.DEPTH24_STENCIL8:14===o.format?u=i.DEPTH_COMPONENT32F:18===o.format&&(u=i.DEPTH32F_STENCIL8)),o.is2DArray?i.texImage3D(n,0,u,o.width,o.height,s,0,c,h,null):o.is3D?i.texImage3D(n,0,u,o.width,o.height,r,0,c,h,null):i.texImage2D(n,0,u,o.width,o.height,0,c,h,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(o),o},Yi.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);const s=e.texture._hardwareTexture;if(s.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){const r=i.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBABufferInternalSizedFormat(e.texture.type,e.texture.format,e.texture._useSRGBBuffer),i.COLOR_ATTACHMENT0,!1);if(!n)throw new Error("Unable to create multi sampled framebuffer");s.addMSAARenderBuffer(n)}else this._bindUnboundFramebuffer(e._framebuffer);return e.texture.samples=t,e._samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t),this._bindUnboundFramebuffer(null),t},Yi.prototype._setupDepthStencilTexture=function(e,t,i,s,r,n=1){const o=t.width||t,a=t.height||t,l=t.layers||0,h=t.depth||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.depth=l||h,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=0,e._comparisonFunction=r;const c=this._gl,u=this._getTextureTarget(e),d=this._getSamplingParameters(e.samplingMode,!1);c.texParameteri(u,c.TEXTURE_MAG_FILTER,d.mag),c.texParameteri(u,c.TEXTURE_MIN_FILTER,d.min),c.texParameteri(u,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(u,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===r?(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,515),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,r),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))},si.prototype.setTextureFromPostProcess=function(e,t,i){let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,s?.texture??null,i)},si.prototype.setTextureFromPostProcessOutput=function(e,t,i){this._bindTexture(e,t?._outputTexture?.texture??null,i)},$t.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)},$t.prototype.setTextureFromPostProcessOutput=function(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)};class Ko{static RegisterShaderCodeProcessing(e,t){t?Ko._CustomShaderCodeProcessing[e??""]=t:delete Ko._CustomShaderCodeProcessing[e??""]}static _GetShaderCodeProcessing(e){return Ko._CustomShaderCodeProcessing[e]??Ko._CustomShaderCodeProcessing[""]}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach((e=>{e.setSamples(this._samples)}))}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,s,r,n,o=1,a,l,h=null,c=0,u="postprocess",d,p=!1,f=5,_=ht.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new Mi(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new N(1,1),this._texelSize=N.Zero(),this.onActivateObservable=new g,this.onSizeChangedObservable=new g,this.onApplyObservable=new g,this.onBeforeRenderObservable=new g,this.onAfterRenderObservable=new g,this.name=e;let m=1,v=null;if(i&&!Array.isArray(i)){const e=i;i=e.uniforms??null,s=e.samplers??null,m=e.size??1,n=e.camera??null,o=e.samplingMode??1,a=e.engine,l=e.reusable,h=e.defines??null,c=e.textureType??0,u=e.vertexUrl??"postprocess",d=e.indexParameters,p=e.blockCompilation??!1,f=e.textureFormat??5,_=e.shaderLanguage??ht.GLSL,v=e.uniformBuffers??null}else r&&(m="number"==typeof r?r:{width:r.width,height:r.height});null!=n?(this._camera=n,this._scene=n.getScene(),n.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):a&&(this._engine=a,this._engine.postProcesses.push(this)),this._options=m,this.renderTargetSamplingMode=o||1,this._reusable=l||!1,this._textureType=c,this._textureFormat=f,this._shaderLanguage=_,this._samplers=s||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=u,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=v||[],this._indexParameters=d,this._drawWrapper=new gr(this._engine),p||this.updateEffect(h)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){0==this._textures.length&&(this._textures=new Mi(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,s,r,n,o,a){const l=Ko._GetShaderCodeProcessing(this.name);if(l?.defineCustomBindings){const s=t?.slice()??[];s.push(...this._parameters);const r=i?.slice()??[];r.push(...this._samplers),e=l.defineCustomBindings(this.name,e,s,r),t=s,i=r}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:o??this._vertexUrl,fragment:a??this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:r??null,onError:n??null,indexParameters:s||this._indexParameters,processCodeAfterIncludes:l?.processCodeAfterIncludes?(e,t)=>l.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:l?.processFinalCode?(e,t)=>l.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let s=0;s=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i)for(let e=0;e{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}return u||(u=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(o/l,a/h),this._engine.bindFramebuffer(u,0,o,a,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(u,0,void 0,void 0,this.forceFullscreenViewport)),this._engine._debugInsertMarker?.(`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:s.clearColor,s._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),u}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._drawWrapper.effect?.isReady()??!1}apply(){if(!this._drawWrapper.effect?.isReady())return null;let e;return this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),e=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e?.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),Ko._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name,this._drawWrapper.effect),this._drawWrapper.effect}_disposeTextures(){this._shareOutputWithPostProcess||this._forcedOutputTexture?this._disposeTextureCache():(this._disposeTextureCache(),this._textures.dispose())}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return!!this._prePassEffectConfiguration&&(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0)}dispose(e){let t;if(e=e||this._camera,this._disposeTextures(),this._scene&&(t=this._scene.postProcesses.indexOf(this),-1!==t&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),-1!==t&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),0===t&&e._postProcesses.length>0){const e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){const e=Pe.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const e=this.serialize();e._engine=this._engine,e.cameraId=null;const t=Ko.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){const s=d(e.customType);if(!s||!s._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return s._Parse(e,r,t,i)}static _Parse(e,t,i,s){return Pe.Parse((()=>new Ko(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat)),e,i,s)}}Ko._CustomShaderCodeProcessing={},ae([pe()],Ko.prototype,"uniqueId",void 0),ae([pe()],Ko.prototype,"name",void 0),ae([pe()],Ko.prototype,"width",void 0),ae([pe()],Ko.prototype,"height",void 0),ae([pe()],Ko.prototype,"renderTargetSamplingMode",void 0),ae([Te()],Ko.prototype,"clearColor",void 0),ae([pe()],Ko.prototype,"autoClear",void 0),ae([pe()],Ko.prototype,"forceAutoClearInAlphaMode",void 0),ae([pe()],Ko.prototype,"alphaMode",void 0),ae([pe()],Ko.prototype,"alphaConstants",void 0),ae([pe()],Ko.prototype,"enablePixelPerfectMode",void 0),ae([pe()],Ko.prototype,"forceFullscreenViewport",void 0),ae([pe()],Ko.prototype,"scaleMode",void 0),ae([pe()],Ko.prototype,"alwaysForcePOT",void 0),ae([pe("samples")],Ko.prototype,"_samples",void 0),ae([pe()],Ko.prototype,"adaptScaleToCurrentViewport",void 0),u("BABYLON.PostProcess",Ko);class qo extends No{constructor(e){super(e,To.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",xo.Vector4,!0),this.registerInput("xyz ",xo.Vector3,!0),this.registerInput("xy ",xo.Vector2,!0),this.registerInput("zw ",xo.Vector2,!0),this.registerInput("x",xo.Float,!0),this.registerInput("y",xo.Float,!0),this.registerInput("z",xo.Float,!0),this.registerInput("w",xo.Float,!0),this.registerOutput("xyzw",xo.Vector4),this.registerOutput("xyz",xo.Vector3),this.registerOutput("xy",xo.Vector2),this.registerOutput("zw",xo.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.x,i=this.y,s=this.z,r=this.w,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],c=this._outputs[1],u=this._outputs[2],d=this._outputs[3],p=e._getShaderType(xo.Vector4),f=e._getShaderType(xo.Vector3),_=e._getShaderType(xo.Vector2);return l.isConnected?(h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${l.associatedVariableName}${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${l.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${l.associatedVariableName}${this._buildSwizzle(2)};\n`)):a.isConnected?(h.hasEndpoints&&(e.compilationString+=e._declareOutput(h)+` = ${p}(${a.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${a.associatedVariableName}${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${a.associatedVariableName}${this._buildSwizzle(2)};\n`)):n.isConnected?(h.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(h)+` = ${p}(${n.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=e._declareOutput(h)+` = ${p}(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${f}(${n.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${n.associatedVariableName}${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(d)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=e._declareOutput(d)+` = ${_}(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};\n`)):(h.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(h)+` = ${p}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${o.associatedVariableName})${this._buildSwizzle(4)};\n`:e.compilationString+=e._declareOutput(h)+` = ${p}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(4)};\n`),c.hasEndpoints&&(e.compilationString+=e._declareOutput(c)+` = ${f}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(3)};\n`),u.hasEndpoints&&(e.compilationString+=e._declareOutput(u)+` = ${_}(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)};\n`),d.hasEndpoints&&(o.isConnected?e.compilationString+=e._declareOutput(d)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\n`:e.compilationString+=e._declareOutput(d)+` = ${_}(${s.isConnected?this._writeVariable(s):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(2)};\n`)),this}serialize(){const e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.xSwizzle=e.xSwizzle??"x",this.ySwizzle=e.ySwizzle??"y",this.zSwizzle=e.zSwizzle??"z",this.wSwizzle=e.wSwizzle??"w"}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}";\n`,e+=`${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";\n`,e+=`${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";\n`,e+=`${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";\n`,e}}u("BABYLON.VectorMergerBlock",qo);class Qo extends No{constructor(e){super(e,To.Neutral),this.sourceRange=new N(-1,1),this.targetRange=new N(0,1),this.registerInput("input",xo.AutoDetect),this.registerInput("sourceMin",xo.Float,!0),this.registerInput("sourceMax",xo.Float,!0),this.registerInput("targetMin",xo.Float,!0),this.registerInput("targetMax",xo.Float,!0),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),s=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),r=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),n=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=e._declareOutput(t)+` = ${r} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${r}) / (${s} - ${i});\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\n`;return e+=`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\n`,e}serialize(){const e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=N.FromArray(e.sourceRange),this.targetRange=N.FromArray(e.targetRange)}}ae([Lo("From",bo.Vector2)],Qo.prototype,"sourceRange",void 0),ae([Lo("To",bo.Vector2)],Qo.prototype,"targetRange",void 0),u("BABYLON.RemapBlock",Qo);class Zo extends No{constructor(e){super(e,To.Neutral),this.registerInput("left",xo.AutoDetect),this.registerInput("right",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this.output._typeConnectionSource=this.left,this._linkConnectionTypes(0,1,!0),this.left.acceptedConnectionPointTypes.push(xo.Float),this.right.acceptedConnectionPointTypes.push(xo.Float),this._connectionObservers=[this.left.onTypeChangedObservable.add((()=>this._updateInputOutputTypes())),this.right.onTypeChangedObservable.add((()=>this._updateInputOutputTypes()))]}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===xo.Int||this.left.type===xo.Float&&this.right.type!==xo.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(const[e,t]of[[this.left,this.right],[this.right,this.left]])e.acceptedConnectionPointTypes=[xo.Int,xo.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==xo.Int&&t.type!==xo.Float||e.acceptedConnectionPointTypes.push(xo.Vector2,xo.Vector3,xo.Vector4,xo.Color3,xo.Color4,xo.Matrix))}dispose(){super.dispose(),this._connectionObservers.forEach((e=>e.remove())),this._connectionObservers.length=0}}class Jo extends Zo{constructor(e){super(e)}getClassName(){return"MultiplyBlock"}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};\n`,this}}var ea;u("BABYLON.MultiplyBlock",Jo),function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture"}(ea||(ea={}));class ta extends Do{constructor(){super(),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class ia{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:w.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:w.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:w.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:w.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let s=0;for(const i of t){if(i.gradient===e){t.splice(s,1);break}s++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=w.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this.applyFog=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new w(10,10,10),this.onAnimationEnd=null,this.blendMode=ia.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new N(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new w(0,0,0),this._useLogarithmicDepth=!1,this.gravity=w.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new j(1,1,1,1),this.color2=new j(1,1,1,1),this.colorDead=new j(0,0,0,1),this.textureMask=new j(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new ta,this.id=e,this.name=e}createPointEmitter(e,t){throw new Error("Method not implemented.")}createHemisphericEmitter(e=1,t=1){throw new Error("Method not implemented.")}createSphereEmitter(e=1,t=1){throw new Error("Method not implemented.")}createDirectedSphereEmitter(e=1,t=new w(0,1,0),i=new w(0,1,0)){throw new Error("Method not implemented.")}createCylinderEmitter(e=1,t=1,i=1,s=0){throw new Error("Method not implemented.")}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new w(0,1,0),r=new w(0,1,0)){throw new Error("Method not implemented.")}createConeEmitter(e=1,t=Math.PI/4){throw new Error("Method not implemented.")}createBoxEmitter(e,t,i,s){throw new Error("Method not implemented.")}}ia.BLENDMODE_ONEONE=0,ia.BLENDMODE_STANDARD=1,ia.BLENDMODE_ADD=2,ia.BLENDMODE_MULTIPLY=3,ia.BLENDMODE_MULTIPLYADD=4,u("BABYLON.BaseParticleSystem",ia);class sa extends No{constructor(e){super(e,To.Neutral),this.registerInput("rgba",xo.Color4,!0),this.registerInput("rgb ",xo.Color3,!0),this.registerOutput("rgb",xo.Color3),this.registerOutput("r",xo.Float),this.registerOutput("g",xo.Float),this.registerOutput("b",xo.Float),this.registerOutput("a",xo.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);const t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;const i=this._outputs[0],s=this._outputs[1],r=this._outputs[2],n=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${t.associatedVariableName}.rgb;\n`),s.hasEndpoints&&(e.compilationString+=e._declareOutput(s)+` = ${t.associatedVariableName}.r;\n`),r.hasEndpoints&&(e.compilationString+=e._declareOutput(r)+` = ${t.associatedVariableName}.g;\n`),n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = ${t.associatedVariableName}.b;\n`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = ${t.associatedVariableName}.a;\n`),this}}u("BABYLON.ColorSplitterBlock",sa),Yi.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,(1!==s.type||this._caps.textureFloatLinearFiltering)&&(2!==s.type||this._caps.textureHalfFloatLinearFiltering)||(s.samplingMode=1);const r=this._gl,n=new ti(this,ei.RenderTarget);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,n,!0);const o=this._getSamplingParameters(s.samplingMode,s.generateMipMaps);1!==s.type||this._caps.textureFloat||(s.type=0,J.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,o.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,o.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let t=0;t<6;t++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(s.type,s.format),e,e,0,this._getInternalFormat(s.format),this._getWebGLTextureType(s.type),null);const a=r.createFramebuffer();return this._bindUnboundFramebuffer(a),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(s.generateStencilBuffer,s.generateDepthBuffer,e,e),s.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=a,i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=s.generateMipMaps,n.samplingMode=s.samplingMode,n.type=s.type,n.format=s.format,this._internalTexturesCache.push(n),i.setTextures(n),i},Yi.prototype.setDepthStencilTexture=function(e,t,i,s){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,s):this._setTexture(e,null,void 0,void 0,s))};const ra={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class na{constructor(e,t=ra){this._fullscreenViewport=new nr(0,0,1,1);const i=t.positions??ra.positions,s=t.indices??ra.indices;this.engine=e,this._vertexBuffers={[Ki.PositionKind]:new Ki(e,i,Ki.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(s),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(s);for(const e in this._vertexBuffers)this._vertexBuffers[e]._rebuild()}))}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const i=null===t?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){const e=this._vertexBuffers[Ki.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[Ki.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class oa{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new g;const i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add((()=>{this.effect.setFloat2("scale",1,1)})));const s=e.defines?e.defines.join("\n"):"";this._drawWrapper=new gr(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],i,e.samplerNames,s,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new $t(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,s,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add((()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const aa="passPixelShader",la="varying vec2 vUV;uniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);}";Ft.ShadersStore[aa]=la;const ha=aa,ca=la;class ua{static _CreateDumpRenderer(){if(!ua._DumpToolsEngine){let e,t=null;const i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new Yi(e,!1,i)}catch(s){e=document.createElement("canvas"),t=new Yi(e,!1,i)}y.Instances.pop(),y.OnEnginesDisposedObservable.add((e=>{t&&e!==t&&!t.isDisposed&&0===y.Instances.length&&ua.Dispose()})),t.getCaps().parallelShaderCompile=void 0;const s=new na(t),r=new oa({engine:t,name:ha,fragmentShader:ca,samplerNames:["textureSampler"]});ua._DumpToolsEngine={canvas:e,engine:t,renderer:s,wrapper:r}}return ua._DumpToolsEngine}static async DumpFramebuffer(e,t,i,s,r="image/png",n,o){const a=await i.readPixels(0,0,e,t),l=new Uint8Array(a.buffer);ua.DumpData(e,t,l,s,r,n,!0,void 0,o)}static DumpDataAsync(e,t,i,s="image/png",r,n=!1,o=!1,a){return new Promise((l=>{ua.DumpData(e,t,i,(e=>l(e)),s,r,n,o,a)}))}static DumpData(e,t,i,s,r="image/png",n,o=!1,a=!1,l){const h=ua._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){const e=new Uint8Array(i.length);let t=i.length;for(;t--;){const s=i[t];e[t]=Math.round(255*G.Clamp(s))}i=e}const c=h.engine.createRawTexture(i,e,t,5,!1,!o,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",c),h.renderer.draw(),a?Ii.ToBlob(h.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;s&&s(t)},t.readAsArrayBuffer(e)}),r,l):Ii.EncodeScreenshotCanvasData(h.canvas,s,r,n,l),c.dispose()}static Dispose(){ua._DumpToolsEngine&&(ua._DumpToolsEngine.wrapper.dispose(),ua._DumpToolsEngine.renderer.dispose(),ua._DumpToolsEngine.engine.dispose()),ua._DumpToolsEngine=null}}Ii.DumpData=ua.DumpData,Ii.DumpDataAsync=ua.DumpDataAsync,Ii.DumpFramebuffer=ua.DumpFramebuffer,$t.prototype.setDepthStencilTexture=function(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)};class da extends Zn{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=b(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let i;i=Array.isArray(e)?e:[e];for(let e=0;e{const i=this._renderList?this._renderList.length:0;(0===t&&i>0||0===i)&&this.getScene()?.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new g,this.onAfterUnbindObservable=new g,this.onBeforeRenderObservable=new g,this.onAfterRenderObservable=new g,this.onClearObservable=new g,this.onResizeObservable=new g,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=w.Zero(),!(i=this.getScene()))return;const T=this.getScene().getEngine();this._gammaSpace=x,this._coordinatesMode=Zn.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=o,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=T.onResizeObservable.add((()=>{})),this._generateMipMaps=!!s,this._doNotChangeAspectRatio=r,this._renderingManager=new es(i),this._renderingManager._useSceneAutoClearSetup=!0,c||(this._renderTargetOptions={generateMipMaps:s,type:n,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:h,samples:p,creationFlags:f,noColorAttachment:_,useSRGBBuffer:m,colorAttachment:v,label:this.name},this.samplingMode===Zn.NEAREST_SAMPLINGMODE&&(this.wrapU=Zn.CLAMP_ADDRESSMODE,this.wrapV=Zn.CLAMP_ADDRESSMODE),d||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=Zn.INVCUBIC_MODE,this._textureMatrix=B.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==p&&(this.samples=p)))}createDepthStencilTexture(e=0,t=!0,i=!1,s=1,r=14,n){this._renderTarget?.createDepthStencilTexture(e,t,i,s,r,n)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;if(e)return e;return this._size.depth||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){const t=this.isCube;this._renderTarget?.dispose(),this._renderTarget=null;const i=this.getScene();i&&(this._processSizeParameter(e,!1),this._renderTarget=t?i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==this._renderTargetOptions.samples&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,i=!1){const s=this.getScene();if(!s)return i;const r=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let e=0;e{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,s){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):s&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,s=0,r=null){const n=this.getScene();if(!n)return;const o=n.getEngine();if(o._debugPushGroup?.(`render to face #${e} layer #${s}`,1),this._prepareFrame(n,e,s,t),this.is2DArray||this.is3D?(o.currentRenderPassId=this._renderPassIds[s],this.onBeforeRenderObservable.notifyObservers(s)):(o.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),o.snapshotRendering&&1===o.snapshotRenderingMode)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||n.clearColor,!0,!0,!0);else{let a=null;const l=this.renderList?this.renderList:n.getActiveMeshes().data,h=this.renderList?this.renderList.length:n.getActiveMeshes().length;this.getCustomRenderList&&(a=this.getCustomRenderList(this.is2DArray||this.is3D?s:e,l,h)),a?this._prepareRenderingManager(a,a.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(l,h,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),a=l);for(const t of n._beforeRenderTargetClearStage)t.action(this,e,s);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(o):this.skipInitialClear||o.clear(this.clearColor||n.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0);for(const t of n._beforeRenderTargetDrawStage)t.action(this,e,s);this._renderingManager.render(this.customRenderFunction,a,this.renderParticles,this.renderSprites);for(const t of n._afterRenderTargetDrawStage)t.action(this,e,s);const c=this._texture?.generateMipMaps??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&n.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e);for(const t of n._afterRenderTargetPostProcessStage)t.action(this,e,s);this._texture&&(this._texture.generateMipMaps=c),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0),i&&ua.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),o)}this._unbindFrameBuffer(o,e),this._texture&&this.isCube&&5===e&&o.generateMipMapsForCubemap(this._texture,!0),o._debugPopGroup?.(1)}setRenderingOrder(e,t=null,i=null,s=null){this._renderingManager.setRenderingOrder(e,t,i,s)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new da(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&e.customRenderTargets.splice(t,1);for(const i of e.cameras)t=i.customRenderTargets.indexOf(this),t>=0&&i.customRenderTargets.splice(t,1);this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===da.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=da.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}da.REFRESHRATE_RENDER_ONCE=0,da.REFRESHRATE_RENDER_ONEVERYFRAME=1,da.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,Zn._CreateRenderTargetTexture=(e,t,i,s,r)=>new da(e,t,i,s);class pa{constructor(e){this.name=ts.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(ts.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){Ii.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}Ft.ShadersStore.proceduralVertexShader="attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class fa extends Zn{constructor(e,t,i,s,r=null,n=!0,o=!1,a=0){super(null,s,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new g,this.onBeforeGenerationObservable=new g,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._vectors4={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null,null===r||r instanceof Zn?(this._options={},this._fallbackTexture=r):(this._options=r,this._fallbackTexture=r.fallbackTexture??null);let l=(s=this.getScene()||y.LastCreatedScene)._getComponent(ts.NAME_PROCEDURALTEXTURE);l||(l=new pa(s),s._addComponent(l)),s.proceduralTextures.push(this),this._fullEngine=s.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=a,this._generateMipMaps=n,this._drawWrapper=new gr(this._fullEngine),this.setFragment(i);const h=this._createRtWrapper(o,t,n,a);this._texture=h.texture;const c=[];c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1),this._vertexBuffers[Ki.PositionKind]=new Ki(this._fullEngine,c,Ki.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,s){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:s,...this._options}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.then((e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId})):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId)),this._contentData}_createIndexBuffer(){const e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[Ki.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===da.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=da.REFRESHRATE_RENDER_ONCE)}reset(){this._drawWrapper.effect?.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}executeWhenReady(e){if(this.isReady())return void e(this);const t=this.getEffect();t&&t.executeWhenCompiled((()=>{e(this)}))}isReady(){const e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;const t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;const i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:"string"==typeof this._fragment?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[Ki.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,(()=>{this._rtWrapper?.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0}))),this._drawWrapper.effect.isReady()}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;const i=this._texture.isCube;this._rtWrapper.dispose();const s=this._createRtWrapper(i,e,t,this._textureType);this._texture=s.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){const t=this.getScene();if(!t)return;const i=this._fullEngine;if(i.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),i.setState(!1),!this.nodeMaterialSource){for(const e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(const e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(const e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(const e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(const e in this._colors4){const t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(const e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)this._drawWrapper.effect.setVector4(e,this._vectors4[e]);for(const e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;i._debugPushGroup?.(`procedural texture generation for ${this.name}`,1);const s=i.currentViewport;if(this.isCube)for(let e=0;e<6;e++)i.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),i.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&i.clear(t.clearColor,!0,!1,!1),i.drawElementsType(Dn.TriangleFillMode,0,6);else{let e=1;this._rtWrapper.is3D?e=this._rtWrapper.depth:this._rtWrapper.is2DArray&&(e=this._rtWrapper.layers);for(let s=0;s=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[Ki.PositionKind];i&&(i.dispose(),this._vertexBuffers[Ki.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}var _a;ae([pe()],fa.prototype,"isEnabled",void 0),ae([pe()],fa.prototype,"autoClear",void 0),ae([pe()],fa.prototype,"_generateMipMaps",void 0),ae([pe()],fa.prototype,"_size",void 0),ae([pe()],fa.prototype,"refreshRate",null),u("BABYLON.ProceduralTexture",fa),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees",e[e.Set=18]="Set"}(_a||(_a={}));class ma extends No{constructor(e){super(e,To.Neutral),this.operation=_a.Cos,this.registerInput("input",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="";switch(this.operation){case _a.Cos:i="cos";break;case _a.Sin:i="sin";break;case _a.Abs:i="abs";break;case _a.Exp:i="exp";break;case _a.Exp2:i="exp2";break;case _a.Round:i="round";break;case _a.Floor:i="floor";break;case _a.Ceiling:i="ceil";break;case _a.Sqrt:i="sqrt";break;case _a.Log:i="log";break;case _a.Tan:i="tan";break;case _a.ArcTan:i="atan";break;case _a.ArcCos:i="acos";break;case _a.ArcSin:i="asin";break;case _a.Fract:i="fract";break;case _a.Sign:i="sign";break;case _a.Radians:i="radians";break;case _a.Degrees:i="degrees";break;case _a.Set:i=""}return e.compilationString+=e._declareOutput(t)+` = ${i}(${this.input.associatedVariableName});\n`,this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${_a[this.operation]};\n`}}u("BABYLON.TrigonometryBlock",ma);const ga={effect:null,subMesh:null};class va extends Do{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class xa extends Io{static _BlockIsTextureBlock(e){return"TextureBlock"===e.getClassName()||"ReflectionTextureBaseBlock"===e.getClassName()||"ReflectionTextureBlock"===e.getClassName()||"ReflectionBlock"===e.getClassName()||"RefractionBlock"===e.getClassName()||"CurrentScreenBlock"===e.getClassName()||"ParticleTextureBlock"===e.getClassName()||"ImageSourceBlock"===e.getClassName()||"TriPlanarBlock"===e.getClassName()||"BiPlanarBlock"===e.getClassName()||"PrePassTextureBlock"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get shaderLanguage(){return this._options.shaderLanguage}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){if(super(e,t||y.LastCreatedScene),this._buildId=xa._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new B,this._cachedWorldViewProjectionMatrix=new B,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new g,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=[],this._mode=ea.Material,this.forceAlphaBlending=!1,i&&i.shaderLanguage===ht.WGSL&&!this.getScene().getEngine().isWebGPU)throw new Error("WebGPU shader language is only supported with WebGPU engine");this._options={emitComments:!1,shaderLanguage:xa.DefaultShaderLanguage,...i},this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return Ii.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(const t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){const t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return e.target&To.Vertex&&this._addVertexOutputNode(e),e.target&To.Fragment&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||(e.target&To.Vertex&&this._removeVertexOutputNode(e),e.target&To.Fragment&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=To.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){const t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=To.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){const t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,s=!0){(e.target===To.VertexAndFragment||t.target===To.Fragment&&e.target===To.Vertex&&e._preparationId!==this._buildId)&&i.push(e),this._initializeBlock(e,t,i,s)}_initializeBlock(e,t,i,s=!0){if(e.initialize(t),s&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){const t=e.getClassName();for(const e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const r of e.inputs){r.associatedVariableName="";const n=r.connectedPoint;if(n){const r=n.ownerBlock;r!==e&&this._processInitializeOnLink(r,t,i,s)}}if(e.isTeleportOut){const r=e;r.entryPoint&&this._processInitializeOnLink(r.entryPoint,t,i,s)}for(const t of e.outputs)t.associatedVariableName=""}_resetDualBlocks(e,t){e.target===To.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._resetDualBlocks(i.entryPoint,t)}}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){this._vertexCompilationState||i||(i=!0),this._buildWasSuccessful=!1;const s=this.getScene().getEngine(),r=this._mode===ea.Particle;if(0===this._vertexOutputNodes.length&&!r)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new Po,this._vertexCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._vertexCompilationState.target=To.Vertex,this._fragmentCompilationState=new Po,this._fragmentCompilationState.supportUniformBuffers=s.supportsUniformBuffers,this._fragmentCompilationState.target=To.Fragment,this._sharedData=new Mo,this._sharedData.nodeMaterial=this,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=r;const n=[],o=[];for(const e of this._vertexOutputNodes)n.push(e),this._initializeBlock(e,this._vertexCompilationState,o,i);for(const e of this._fragmentOutputNodes)o.push(e),this._initializeBlock(e,this._fragmentCompilationState,n,i);this.optimize();for(const e of n)e.build(this._vertexCompilationState,n);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(const e of o)this._resetDualBlocks(e,this._buildId-1);for(const e of o)e.build(this._fragmentCompilationState,o);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=xa._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(J.Log("Vertex shader:"),J.Log(this._vertexCompilationState.compilationString),J.Log("Fragment shader:"),J.Log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const a=this.getScene().meshes;for(const e of a)if(e.subMeshes)for(const t of e.subMeshes){if(t.getMaterial()!==this)continue;if(!t.materialDefines)continue;const e=t.materialDefines;e.markAllAsDirty(),e.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();const l=this.getScene().prePassRenderer;l&&l.markAsDirty()}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,s=t.TANGENT,r=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(Ki.NormalKind),t.TANGENT=e.isVerticesDataPresent(Ki.TangentKind);const n=e.useVertexColors&&e.isVerticesDataPresent(Ki.ColorKind);t.VERTEXCOLOR_NME=n;let o=!1;for(let i=1;i<=6;++i){const s=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),o=o||t["UV"+i]!==s}const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;Rn(this.getScene(),t,!a),(i!==t.NORMAL||s!==t.TANGENT||r!==t.VERTEXCOLOR_NME||o)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){const e=this.getBlockByPredicate((e=>"PrePassOutputBlock"===e.getClassName())),t=[4];return e?(this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t):t}get prePassTextureInputs(){const e=this.getAllTextureBlocks().filter((e=>"PrePassTextureBlock"===e.getClassName())),t=[];for(const i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){const t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]}));for(const e of t)i.texturesRequired.includes(e)||i.texturesRequired.push(e);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,s,r,n=0,o=5){return this.mode!==ea.PostProcess?(J.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,s,r,n,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,s=1,r,n,o=0,a=5){let l=this.name+this._buildId;const h=new va,c=new Wr(l+"PostProcess",this.getScene());let u=this._buildId;return this._processDefines(c,h),$t.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new Ko(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,s,r,n,h.toString(),o,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,a),e.nodeMaterialSource=this,e.onApplyObservable.add((t=>{u!==this._buildId&&(delete $t.ShadersStore[l+"VertexShader"],delete $t.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),u=this._buildId),this._processDefines(c,h)&&($t.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),wt.SetImmediate((()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l)))),this._checkInternals(t)})),e}createProceduralTexture(e,t){if(this.mode!==ea.ProceduralTexture)return J.Log("Incompatible material mode"),null;let i=this.name+this._buildId;const s=new fa(i,e,null,t),r=new Wr(i+"Procedural",this.getScene());r.reservedDataStore={hidden:!0};const n=new va,o=this._processDefines(r,n);$t.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[Ki.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),o?.fallbacks,void 0);s.nodeMaterialSource=this,s._setEffect(a);let l=this._buildId;return s.onBeforeGenerationObservable.add((()=>{l!==this._buildId&&(delete $t.ShadersStore[i+"VertexShader"],delete $t.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),l=this._buildId);const e=this._processDefines(r,n);e&&($t.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),wt.SetImmediate((()=>{a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[Ki.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),e?.fallbacks,void 0),s._setEffect(a)}))),this._checkInternals(a)})),s}_createEffectForParticles(e,t,i,s,r,n,o,a=""){let l=this.name+this._buildId+"_"+t;n||(n=new va),o||(o=this.getScene().getMeshByName(this.name+"Particle"))||((o=new Wr(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId;const c=[];let u=a;if(!r){const a=this._processDefines(o,n);$t.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(c,t,!1),u=c.join("\n"),r=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,a?.fallbacks,i,s,e),e.setCustomEffect(r,t)}r.onBindObservable.add((r=>{h!==this._buildId&&(delete $t.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,n.markAllAsDirty(),h=this._buildId),c.length=0,e.fillDefines(c,t,!1);const d=c.join("\n");d!==u&&(n.markAllAsDirty(),u=d);const p=this._processDefines(o,n);if(p)return $t.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),r=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+u,p?.fallbacks,i,s,e),e.setCustomEffect(r,t),void this._createEffectForParticles(e,t,i,s,r,n,o,a);this._checkInternals(r)}))}_checkInternals(e){if(this._sharedData.animatedInputs){const e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(const t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(const t of this._sharedData.bindableBlocks)t.bind(e,this);for(const t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){this.mode===ea.Particle?(this._createEffectForParticles(e,ia.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,ia.BLENDMODE_MULTIPLY,t,i)):J.Log("Incompatible material mode")}createAsShadowDepthWrapper(e){this.mode===ea.Material?e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene()):J.Log("Incompatible material mode")}_processDefines(e,t,i=!1,s){let r=null;if(In(this.getScene(),t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach((s=>{s.initializeDefines(e,this,t,i)})),this._sharedData.blocksWithDefines.forEach((r=>{r.prepareDefines(e,this,t,i,s)})),t.isDirty){const i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach((i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)}));const s=[];this._sharedData.dynamicUniformBlocks.forEach((e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,s)}));const n=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach((e=>{-1===n.indexOf(e)&&n.push(e)}));const o=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach((e=>{-1===o.indexOf(e)&&o.push(e)}));const a=new Yo;this._sharedData.blocksWithFallbacks.forEach((t=>{t.provideFallbacks(e,a)})),r={lightDisposed:i,uniformBuffers:s,mergedUniforms:n,mergedSamplers:o,fallbacks:a}}return r}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const s=this.getScene();if(this._sharedData.animatedInputs){const e=s.getFrameId();if(this._animationFrame!==e){for(const e of this._sharedData.animatedInputs)e.animate(s);this._animationFrame=e}}const r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new va);const n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=s.getEngine();if(this._prepareDefinesForAttributes(e,n),this._sharedData.blockingBlocks.some((t=>!t.isReady(e,this,n,i))))return!1;const a=this._processDefines(e,n,i,t);if(a){const e=t.effect,i=n.toString();let r=o.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:i,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:n.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS},shaderLanguage:this.shaderLanguage},o);if(r)if(this._onEffectCreatedObservable&&(ga.effect=r,ga.subMesh=t,this._onEffectCreatedObservable.notifyObservers(ga)),this.allowShaderHotSwapping&&e&&!r.isReady()){if(r=e,n.markAsUnprocessed(),a.lightDisposed)return n._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(r,n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=s.getRenderId(),r._wasPreviouslyReady=!0,r._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}get compiledShaders(){return`// Vertex shader\n${this._vertexCompilationState.compilationString}\n\n// Fragment shader\n${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){const t=this.getScene();if(!this._activeEffect)return;const i=this._sharedData.hints;i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(const t of this._sharedData.inputBlocks)t._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.effect;if(!r)return;this._activeEffect=r,this.bindOnlyWorldMatrix(e);const n=this._mustRebind(s,r,i,t.visibility),o=this._sharedData;if(n){for(const e of o.bindableBlocks)e.bind(r,this,t,i);for(const e of o.forcedBindableBlocks)e.bind(r,this,t,i);for(const e of o.inputBlocks)e._transmit(r,s,this)}else if(!this.isFrozen)for(const e of o.forcedBindableBlocks)e.bind(r,this,t,i);this._afterBind(t,this._activeEffect,i)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter((e=>e.texture)).map((e=>e.texture))),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)xa._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(const t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(const e of this.getTextureBlocks().filter((e=>e.texture)).map((e=>e.texture)))e.dispose();for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){const t={nodeMaterial:this,...e};this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise((t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),void 0===this.BJSNODEMATERIALEDITOR){const i=e&&e.editorURL?e.editorURL:xa.EditorURL;Ii.LoadBabylonScript(i,(()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(e?.nodeEditorConfig),t()}))}else this._createNodeEditor(e?.nodeEditorConfig),t()}))}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;const e=new Go("Position");e.setAsAttribute("position");const t=new Go("World");t.setAsSystemValue(yo.World);const i=new wo("WorldPos");e.connectTo(i),t.connectTo(i);const s=new Go("ViewProjection");s.setAsSystemValue(yo.ViewProjection);const r=new wo("WorldPos * ViewProjectionTransform");i.connectTo(r),s.connectTo(r);const n=new Fo("VertexOutput");r.connectTo(n);const o=new Go("color");o.value=new j(.8,.8,.8,1);const a=new Bo("FragmentOutput");o.connectTo(a),this.addOutputNode(n),this.addOutputNode(a),this._mode=ea.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Go("Position");e.setAsAttribute("position2d");const t=new Go("Constant1");t.isConstant=!0,t.value=1;const i=new qo("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new Fo("VertexOutput");i.connectTo(s);const r=new Go("Scale");r.visibleInInspector=!0,r.value=new N(1,1);const n=new Qo("uv0");e.connectTo(n);const o=new Jo("UV scale");n.connectTo(o),r.connectTo(o);const a=new zo("CurrentScreen");o.connectTo(a),a.texture=new Zn("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const l=new Bo("FragmentOutput");a.connectTo(l,{output:"rgba"}),this.addOutputNode(s),this.addOutputNode(l),this._mode=ea.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Go("Position");e.setAsAttribute("position2d");const t=new Go("Constant1");t.isConstant=!0,t.value=1;const i=new qo("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const s=new Fo("VertexOutput");i.connectTo(s);const r=new Go("Time");r.value=0,r.min=0,r.max=0,r.isBoolean=!1,r.matrixMode=0,r.animationType=Ao.Time,r.isConstant=!1;const n=new Go("Color3");n.value=new Y(1,1,1),n.isConstant=!1;const o=new Bo("FragmentOutput"),a=new qo("VectorMerger");a.visibleInInspector=!1;const l=new ma("Cos");l.operation=_a.Cos,e.connectTo(a),r.output.connectTo(l.input),l.output.connectTo(a.z),a.xyzOut.connectTo(o.rgb),this.addOutputNode(s),this.addOutputNode(o),this._mode=ea.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Go("uv");e.setAsAttribute("particle_uv");const t=new Wo("ParticleTexture");e.connectTo(t);const i=new Go("Color");i.setAsAttribute("particle_color");const s=new Jo("Texture * Color");t.connectTo(s),i.connectTo(s);const r=new Ho("ParticleRampGradient");s.connectTo(r);const n=new sa("ColorSplitter");i.connectTo(n);const o=new Xo("ParticleBlendMultiply");r.connectTo(o),t.connectTo(o,{output:"a"}),n.connectTo(o,{output:"a"});const a=new Bo("FragmentOutput");o.connectTo(a),this.addOutputNode(a),this._mode=ea.Particle}async loadAsync(e,t=""){return xa.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,t);const s=[];for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,s);let r=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}");\n`;r+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${ea[this.mode]};\n`;for(const s of t)s.isInput&&-1===e.indexOf(s)&&(r+=s._dumpCode(i,e));for(const t of s)t.isInput&&-1===e.indexOf(t)&&(r+=t._dumpCode(i,e));e=[],r+="\n// Connections\n";for(const t of this._vertexOutputNodes)r+=t._dumpCodeForOutputConnections(e);for(const t of this._fragmentOutputNodes)r+=t._dumpCodeForOutputConnections(e);r+="\n// Output nodes\n";for(const e of this._vertexOutputNodes)r+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;for(const e of this._fragmentOutputNodes)r+=`nodeMaterial.addOutputNode(${e._codeVariableName});\n`;return r+="nodeMaterial.build();\n",r}serialize(e){const t=e?{}:Pe.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{t.customType="BABYLON.NodeMaterial",t.outputNodes=[];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n)for(const o of r.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==s.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;s.connectTo(e,!0),this._restoreConnections(n,t,i)}}}parseSerializedObject(e,t="",i=!1,s){i||this.clear();const r={};for(const i of e.blocks){const e=d(i.customType);if(e){const n=new e;n._deserialize(i,this.getScene(),t,s),r[i.id]=n,this.attachedBlocks.push(n)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,i=t._tempEntryPointUniqueId;i&&r[i].attachToEndpoint(t)}for(let t=0;tnew xa(e,this.getScene(),this.options)),this);return s.id=e,s.name=e,s.parseSerializedObject(i),s._buildId=this._buildId,s.build(!1,!t),s}whenTexturesReadyAsync(){const e=[];return this.getActiveTextures().forEach((t=>{const i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise(((e,t)=>{i.onLoadedObservable.addOnce((()=>{e()})),i.onErrorObservable.addOnce((e=>{t(e)}))})))})),Promise.all(e)}static Parse(e,t,i="",s=ht.GLSL){const r=Pe.Parse((()=>new xa(e.name,t,{shaderLanguage:s})),e,t,i);return r.parseSerializedObject(e,i),r.build(),r}static async ParseFromFileAsync(e,t,i,s="",r=!1,n,o){const a=n??new xa(e,i),l=await i._loadFileAsync(t),h=JSON.parse(l);return a.parseSerializedObject(h,s,void 0,o),r||a.build(),a}static ParseFromSnippetAsync(e,t=y.LastCreatedScene,i="",s,r=!1,n=!1,o){return"_BLANK"===e?Promise.resolve(xa.CreateDefault("blank",t)):new Promise(((a,l)=>{const h=new Ne;h.addEventListener("readystatechange",(()=>{if(4==h.readyState)if(200==h.status){const c=JSON.parse(JSON.parse(h.responseText).jsonPayload),u=JSON.parse(c.nodeMaterial);s||((s=Pe.Parse((()=>new xa(e,t)),u,t,i)).uniqueId=t.getUniqueId()),s.parseSerializedObject(u,void 0,void 0,o),s.snippetId=e;try{r||s.build()}catch(e){l(e)}n?s.whenTexturesReadyAsync().then((()=>{a(s)})).catch((e=>{l(e)})):a(s)}else l("Unable to load the snippet "+e)})),h.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),h.send()}))}static CreateDefault(e,t){const i=new xa(e,t);return i.setToDefault(),i.build(),i}}function Ta(e){const t=e.sideOrientation||Tr.DEFAULTSIDE,i=e.radius||1,s=void 0===e.flat||e.flat,r=0|(e.subdivisions||4),n=e.radiusX||i,o=e.radiusY||i,a=e.radiusZ||i,l=(1+Math.sqrt(5))/2,h=[-1,l,-0,1,l,0,-1,-l,0,1,-l,0,0,-1,-l,0,1,-l,0,-1,l,0,1,l,l,0,1,l,0,-1,-l,0,1,-l,0,-1],c=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],u=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],d=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],p=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],f=[],_=[],m=[],g=[];let v=0;const x=new Array(3),T=new Array(3);let S;for(S=0;S<3;S++)x[S]=w.Zero(),T[S]=N.Zero();for(let e=0;e<20;e++){for(S=0;S<3;S++){const t=c[3*e+S];x[S].copyFromFloats(h[3*u[t]],h[3*u[t]+1],h[3*u[t]+2]),x[S].normalize(),T[S].copyFromFloats(.134765625*d[2*t]+.05859375+-.0390625*p[e],.2333984375*d[2*t+1]+.025390625+.01953125*p[e])}const t=(e,t,i,l)=>{const h=w.Lerp(x[0],x[2],t/r),c=w.Lerp(x[1],x[2],t/r),u=r===t?x[2]:w.Lerp(h,c,e/(r-t));let d;if(u.normalize(),s){const e=w.Lerp(x[0],x[2],l/r),t=w.Lerp(x[1],x[2],l/r);d=w.Lerp(e,t,i/(r-l))}else d=new w(u.x,u.y,u.z);d.x/=n,d.y/=o,d.z/=a,d.normalize();const p=N.Lerp(T[0],T[2],t/r),S=N.Lerp(T[1],T[2],t/r),E=r===t?T[2]:N.Lerp(p,S,e/(r-t));_.push(u.x*n,u.y*o,u.z*a),m.push(d.x,d.y,d.z),g.push(E.x,Er.UseOpenGLOrientationForUV?1-E.y:E.y),f.push(v),v++};for(let e=0;eSa(e,t,i),function(e){e.WRIST="wrist",e.THUMB="thumb",e.INDEX="index",e.MIDDLE="middle",e.RING="ring",e.LITTLE="little"}(Ea||(Ea={})),(Ca=ba||(ba={})).WRIST="wrist",Ca.THUMB_METACARPAL="thumb-metacarpal",Ca.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",Ca.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",Ca.THUMB_TIP="thumb-tip",Ca.INDEX_FINGER_METACARPAL="index-finger-metacarpal",Ca.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",Ca.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",Ca.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",Ca.INDEX_FINGER_TIP="index-finger-tip",Ca.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",Ca.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",Ca.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",Ca.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",Ca.MIDDLE_FINGER_TIP="middle-finger-tip",Ca.RING_FINGER_METACARPAL="ring-finger-metacarpal",Ca.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",Ca.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",Ca.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",Ca.RING_FINGER_TIP="ring-finger-tip",Ca.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",Ca.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",Ca.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",Ca.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",Ca.PINKY_FINGER_TIP="pinky-finger-tip";const ya=[ba.WRIST,ba.THUMB_METACARPAL,ba.THUMB_PHALANX_PROXIMAL,ba.THUMB_PHALANX_DISTAL,ba.THUMB_TIP,ba.INDEX_FINGER_METACARPAL,ba.INDEX_FINGER_PHALANX_PROXIMAL,ba.INDEX_FINGER_PHALANX_INTERMEDIATE,ba.INDEX_FINGER_PHALANX_DISTAL,ba.INDEX_FINGER_TIP,ba.MIDDLE_FINGER_METACARPAL,ba.MIDDLE_FINGER_PHALANX_PROXIMAL,ba.MIDDLE_FINGER_PHALANX_INTERMEDIATE,ba.MIDDLE_FINGER_PHALANX_DISTAL,ba.MIDDLE_FINGER_TIP,ba.RING_FINGER_METACARPAL,ba.RING_FINGER_PHALANX_PROXIMAL,ba.RING_FINGER_PHALANX_INTERMEDIATE,ba.RING_FINGER_PHALANX_DISTAL,ba.RING_FINGER_TIP,ba.PINKY_FINGER_METACARPAL,ba.PINKY_FINGER_PHALANX_PROXIMAL,ba.PINKY_FINGER_PHALANX_INTERMEDIATE,ba.PINKY_FINGER_PHALANX_DISTAL,ba.PINKY_FINGER_TIP],Aa={[Ea.WRIST]:[ba.WRIST],[Ea.THUMB]:[ba.THUMB_METACARPAL,ba.THUMB_PHALANX_PROXIMAL,ba.THUMB_PHALANX_DISTAL,ba.THUMB_TIP],[Ea.INDEX]:[ba.INDEX_FINGER_METACARPAL,ba.INDEX_FINGER_PHALANX_PROXIMAL,ba.INDEX_FINGER_PHALANX_INTERMEDIATE,ba.INDEX_FINGER_PHALANX_DISTAL,ba.INDEX_FINGER_TIP],[Ea.MIDDLE]:[ba.MIDDLE_FINGER_METACARPAL,ba.MIDDLE_FINGER_PHALANX_PROXIMAL,ba.MIDDLE_FINGER_PHALANX_INTERMEDIATE,ba.MIDDLE_FINGER_PHALANX_DISTAL,ba.MIDDLE_FINGER_TIP],[Ea.RING]:[ba.RING_FINGER_METACARPAL,ba.RING_FINGER_PHALANX_PROXIMAL,ba.RING_FINGER_PHALANX_INTERMEDIATE,ba.RING_FINGER_PHALANX_DISTAL,ba.RING_FINGER_TIP],[Ea.LITTLE]:[ba.PINKY_FINGER_METACARPAL,ba.PINKY_FINGER_PHALANX_PROXIMAL,ba.PINKY_FINGER_PHALANX_INTERMEDIATE,ba.PINKY_FINGER_PHALANX_DISTAL,ba.PINKY_FINGER_TIP]};class Ra{get handMesh(){return this._handMesh}getHandPartMeshes(e){return Aa[e].map((e=>this._jointMeshes[ya.indexOf(e)]))}getJointMesh(e){return this._jointMeshes[ya.indexOf(e)]}constructor(e,t,i,s,r=!1,n=!1,o=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=s,this._leftHandedMeshes=r,this._jointsInvisible=n,this._jointScaleFactor=o,this.onHandMeshSetObservable=new g,this._jointTransforms=new Array(ya.length),this._jointTransformMatrices=new Float32Array(16*ya.length),this._tempJointMatrix=new B,this._jointRadii=new Float32Array(ya.length),this._scene=t[0].getScene();for(let e=0;e{e._doNotLoadControllerMesh=!0}))}setHandMesh(e,t,i){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach((e=>{e.alwaysSelectAsActiveMesh=!0})),this._handMesh.skeleton){const e=this._handMesh.skeleton;ya.forEach(((i,s)=>{const r=e.getBoneIndexByName(t?t[i]:i);-1!==r&&e.bones[r].linkTransformNode(this._jointTransforms[s])}))}this.onHandMeshSetObservable.notifyObservers(this)}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const s=i,r=ya.map((e=>s[e]||i.get(e)));let n=!1;if(e.fillPoses&&e.fillJointRadii)n=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){n=!0;for(let i=0;i{const i=this._jointTransforms[t];B.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);const s=this._jointRadii[t]*this._jointScaleFactor,r=this._jointMeshes[t];r.isVisible=!this._handMesh&&!this._jointsInvisible,r.position.copyFrom(i.position),r.rotationQuaternion.copyFrom(i.rotationQuaternion),r.scaling.setAll(s),this._scene.useRightHandedSystem||(r.position.z*=-1,r.rotationQuaternion.z*=-1,r.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))})),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(e=!1){this._handMesh&&(e?(this._handMesh.skeleton?.dispose(),this._handMesh.dispose(!1,!0)):this._handMesh.isVisible=!1)}}class Ia extends _o{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map((i=>{const s=[],r=e.jointMeshes?.sourceMesh||Sa("jointParent",Ia._ICOSPHERE_PARAMS);r.isVisible=!!e.jointMeshes?.keepOriginalVisible;for(let t=0;t{const r={};Ia._RightHandGLB?.meshes[1]?.isDisposed()&&(Ia._RightHandGLB=null),Ia._LeftHandGLB?.meshes[1]?.isDisposed()&&(Ia._LeftHandGLB=null);const n=!(!Ia._RightHandGLB||!Ia._LeftHandGLB),o=await Promise.all([Ia._RightHandGLB||Ro.ImportMeshAsync("",Ia.DEFAULT_HAND_MODEL_BASE_URL,Ia.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),Ia._LeftHandGLB||Ro.ImportMeshAsync("",Ia.DEFAULT_HAND_MODEL_BASE_URL,Ia.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);Ia._RightHandGLB=o[0],Ia._LeftHandGLB=o[1];const a=await xa.ParseFromFileAsync("handShader",Ia.DEFAULT_HAND_MODEL_SHADER_URL,e);a.needDepthPrePass=!0,a.transparencyMode=Dn.MATERIAL_ALPHABLEND,a.alphaMode=2,a.build(!1);const l={base:Y.FromInts(116,63,203),fresnel:Y.FromInts(149,102,229),fingerColor:Y.FromInts(177,130,255),tipFresnel:Y.FromInts(220,200,255),...i?.handMeshes?.customColors},h={base:a.getBlockByName("baseColor"),fresnel:a.getBlockByName("fresnelColor"),fingerColor:a.getBlockByName("fingerColor"),tipFresnel:a.getBlockByName("tipFresnelColor")};h.base.value=l.base,h.fresnel.value=l.fresnel,h.fingerColor.value=l.fingerColor,h.tipFresnel.value=l.tipFresnel;const c=t._getBaseLayerWrapper()?.isMultiview;["left","right"].forEach((t=>{const i="left"==t?Ia._LeftHandGLB:Ia._RightHandGLB;if(!i)throw new Error("Could not load hand model");const s=i.meshes[1];s._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,c||(s.material=a.clone(`${t}HandShaderClone`,!0)),s.isVisible=!1,r[t]=s,n||e.useRightHandedSystem||i.meshes[1].rotate(Gs.Y,Math.PI)})),a.dispose(),s({left:r.left,right:r.right})}))}static _GenerateDefaultHandMeshRigMapping(e){const t="right"==e?"R":"L";return{[ba.WRIST]:`wrist_${t}`,[ba.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[ba.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[ba.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[ba.THUMB_TIP]:`thumb_tip_${t}`,[ba.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[ba.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[ba.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[ba.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[ba.INDEX_FINGER_TIP]:`index_tip_${t}`,[ba.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[ba.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[ba.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[ba.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[ba.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[ba.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[ba.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[ba.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[ba.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[ba.RING_FINGER_TIP]:`ring_tip_${t}`,[ba.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[ba.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[ba.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[ba.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[ba.PINKY_FINGER_TIP]:`little_tip_${t}`}}isCompatible(){return"undefined"!=typeof XRHand}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return"none"==e?null:this._trackingHands[e]}constructor(e,t){super(e),this.options=t,this._attachedHands={},this._trackingHands={left:null,right:null},this._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},this._worldScaleObserver=null,this.onHandAddedObservable=new g,this.onHandRemovedObservable=new g,this._attachHand=e=>{if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;const t=e.inputSource.handedness,i=new Ra(e,this._handResources.jointMeshes[t],this._handResources.handMeshes&&this._handResources.handMeshes[t],this._handResources.rigMappings&&this._handResources.rigMappings[t],this.options.handMeshes?.meshesUseLeftHandedCoordinates,this.options.jointMeshes?.invisible,this.options.jointMeshes?.scaleFactor);this._attachedHands[e.uniqueId]=i,this._trackingHands[t]=i,this.onHandAddedObservable.notifyObservers(i)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";const i=t.jointMeshes;if(i&&(void 0!==i.disableDefaultHandMesh&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=i.disableDefaultHandMesh),void 0!==i.handMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=i.handMeshes),void 0!==i.leftHandedSystemMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=i.leftHandedSystemMeshes),void 0!==i.rigMapping)){t.handMeshes=t.handMeshes||{};const e={},s={};[[i.rigMapping.left,e],[i.rigMapping.right,s]].forEach((e=>{const t=e[0],i=e[1];t.forEach(((e,t)=>{i[ya[t]]=e}))})),t.handMeshes.customRigMappings={left:e,right:s}}}attach(){return!!super.attach()&&(this._handResources={jointMeshes:Ia._GenerateTrackedJointMeshes(this.options),handMeshes:this.options.handMeshes?.customMeshes||null,rigMappings:this.options.handMeshes?.customRigMappings||null},this.options.handMeshes?.customMeshes||this.options.handMeshes?.disableDefaultMeshes||(Ia._GenerateDefaultHandMeshesAsync(y.LastCreatedScene,this._xrSessionManager,this.options).then((e=>{this._handResources.handMeshes=e,this._handResources.rigMappings={left:Ia._GenerateDefaultHandMeshRigMapping("left"),right:Ia._GenerateDefaultHandMeshRigMapping("right")},this._trackingHands.left?.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left,this._xrSessionManager),this._trackingHands.right?.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right,this._xrSessionManager),this._handResources.handMeshes.left.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._handResources.handMeshes.right.scaling.setAll(this._xrSessionManager.worldScalingFactor)})),this._worldScaleObserver=this._xrSessionManager.onWorldScaleFactorChangedObservable.add((e=>{this._handResources.handMeshes&&(this._handResources.handMeshes.left.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor),this._handResources.handMeshes.right.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor))}))),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0)}_onXRFrame(e){this._trackingHands.left?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),this._trackingHands.right?.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e,t){const i=this.getHandByControllerId(e);if(i){const s="left"==i.xrController.inputSource.handedness?"left":"right";this._trackingHands[s]?.xrController.uniqueId===e&&(this._trackingHands[s]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(t),delete this._attachedHands[e]}}detach(){return!!super.detach()&&(Object.keys(this._attachedHands).forEach((e=>this._detachHandById(e,this.options.handMeshes?.disposeOnSessionEnd))),this.options.handMeshes?.disposeOnSessionEnd&&this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose()))),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver),!0)}dispose(){super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!this.options.handMeshes?.customMeshes&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),Ia._RightHandGLB=null,Ia._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose())))}}var Pa,Ma,Da;Ia.Name=po.HAND_TRACKING,Ia.Version=1,Ia.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",Ia.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",Ia.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",Ia.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",Ia._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},Ia._RightHandGLB=null,Ia._LeftHandGLB=null,fo.AddWebXRFeature(Ia.Name,((e,t)=>()=>new Ia(e,t)),Ia.Version,!1),function(e){e[e.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",e[e.RADIAL_SIDE=1]="RADIAL_SIDE",e[e.ULNAR_SIDE=2]="ULNAR_SIDE",e[e.BELOW_WRIST=3]="BELOW_WRIST"}(Pa||(Pa={})),function(e){e[e.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",e[e.HAND_ROTATION=1]="HAND_ROTATION"}(Ma||(Ma={})),function(e){e[e.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",e[e.PALM_UP=1]="PALM_UP",e[e.GAZE_FOCUS=2]="GAZE_FOCUS",e[e.PALM_AND_GAZE=3]="PALM_AND_GAZE"}(Da||(Da={}));class Oa{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=w.Zero(),this.poleTargetPosition=w.Zero(),this.poleTargetLocalOffset=w.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=L.Identity(),this._bone1Mat=B.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=w.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;const s=t.getParent();if(!s)return this._notEnoughInformation=!0,void J.Error("BoneIKController: bone must have a parent for IK to work.");if(this._bone1=s,0===this._bone2.children.length&&!this._bone2.length)return this._notEnoughInformation=!0,void J.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();const r=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,r.x>r.y&&r.x>r.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){const e=this._bone1.getScale(),t=this._bone2.getScale();this._bone1Length=this._bone1.length*e.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);const t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),s=this._bone1.getAbsolutePosition(e);this._bone2Length=w.Distance(t,i),this._bone1Length=w.Distance(i,s)}else{e.computeWorldMatrix(!0);const t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;const i=this._bone2.getAbsolutePosition(e),s=this._bone1.getAbsolutePosition(e);this._bone1Length=w.Distance(i,s)}this._bone1.getRotationMatrixToRef(Fs.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||null==e)&&(e=Math.PI),this._maxAngle=e;const t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;const e=this.targetPosition,t=this.poleTargetPosition,i=Oa._TmpMats[0],s=Oa._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&w.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);const r=Oa._TmpVecs[0],n=Oa._TmpVecs[1],o=Oa._TmpVecs[2],a=Oa._TmpVecs[3],l=Oa._TmpVecs[4],h=Oa._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,r),t.subtractToRef(r,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),e.subtractToRef(r,a),a.normalize(),w.CrossToRef(a,l,n),n.normalize(),w.CrossToRef(a,n,o),o.normalize(),B.FromXYZAxesToRef(o,a,n,i);const c=this._bone1Length,u=this._bone2Length;let d=w.Distance(r,e);this._maxReach>0&&(d=Math.min(this._maxReach,d));let p=(u*u+d*d-c*c)/(2*u*d),f=(d*d+c*c-u*u)/(2*d*c);p>1&&(p=1),f>1&&(f=1),p<-1&&(p=-1),f<-1&&(f=-1);const _=Math.acos(p),m=Math.acos(f);let g=-_-m;if(this._rightHandedSystem)B.RotationYawPitchRollToRef(0,0,this._adjustRoll,s),s.multiplyToRef(i,i),B.RotationAxisToRef(this._bendAxis,m,s),s.multiplyToRef(i,i);else{const e=Oa._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,B.RotationAxisToRef(e,-m,s),s.multiplyToRef(i,i)}this.poleAngle&&(B.RotationAxisToRef(a,this.poleAngle,s),i.multiplyToRef(s,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||L.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),L.FromRotationMatrixToRef(i,h),L.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),g=this._bone2Ang*(1-this.slerpAmount)+g*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,Fs.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,Fs.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,g,Fs.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=g}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new L),e.getRotationQuaternionToRef(Fs.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}Oa._TmpVecs=[w.Zero(),w.Zero(),w.Zero(),w.Zero(),w.Zero(),w.Zero()],Oa._TmpQuat=L.Identity(),Oa._TmpMats=[B.Identity(),B.Identity()];class Na{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,s){if(this.upAxis=w.Up(),this.upAxisSpace=Fs.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=L.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=w.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,s){if(s.adjustYaw&&(this.adjustYaw=s.adjustYaw),s.adjustPitch&&(this.adjustPitch=s.adjustPitch),s.adjustRoll&&(this.adjustRoll=s.adjustRoll),null!=s.maxYaw?this.maxYaw=s.maxYaw:this.maxYaw=Math.PI,null!=s.minYaw?this.minYaw=s.minYaw:this.minYaw=-Math.PI,null!=s.maxPitch?this.maxPitch=s.maxPitch:this.maxPitch=Math.PI,null!=s.minPitch?this.minPitch=s.minPitch:this.minPitch=-Math.PI,null!=s.slerpAmount&&(this.slerpAmount=s.slerpAmount),null!=s.upAxis&&(this.upAxis=s.upAxis),null!=s.upAxisSpace&&(this.upAxisSpace=s.upAxisSpace),null!=s.yawAxis||null!=s.pitchAxis){let e=Gs.Y,t=Gs.X;null!=s.yawAxis&&(e=s.yawAxis.clone(),e.normalize()),null!=s.pitchAxis&&(t=s.pitchAxis.clone(),t.normalize());const i=w.Cross(t,e);this._transformYawPitch=B.Identity(),B.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==s.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=s.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=Fs.BONE||(this.upAxisSpace=Fs.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped)return void(this._firstFrameSkipped=!0);const e=this.bone,t=Na._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target;const s=Na._TmpMats[0],r=Na._TmpMats[1],n=this.mesh,o=e.getParent(),a=Na._TmpVecs[1];a.copyFrom(this.upAxis),this.upAxisSpace==Fs.BONE&&o?(this._transformYawPitch&&w.TransformCoordinatesToRef(a,this._transformYawPitchInv,a),o.getDirectionToRef(a,this.mesh,a)):this.upAxisSpace==Fs.LOCAL&&(n.getDirectionToRef(a,a),1==n.scaling.x&&1==n.scaling.y&&1==n.scaling.z||a.normalize());let l=!1,h=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(l=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(h=!0),l||h){const e=Na._TmpMats[2],s=Na._TmpMats[3];if(this.upAxisSpace==Fs.BONE&&1==a.y&&o)o.getRotationMatrixToRef(Fs.WORLD,this.mesh,e);else if(this.upAxisSpace!=Fs.LOCAL||1!=a.y||o){let t=Na._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&w.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),o?o.getDirectionToRef(t,this.mesh,t):n.getDirectionToRef(t,t);const i=w.Cross(a,t);i.normalize(),t=w.Cross(i,a),B.FromXYZAxesToRef(i,a,t,e)}else e.copyFrom(n.getWorldMatrix());e.invertToRef(s);let r=null;if(h){const n=Na._TmpVecs[3];i.subtractToRef(t,n),w.TransformCoordinatesToRef(n,s,n),r=Math.sqrt(n.x*n.x+n.z*n.z);const o=Math.atan2(n.y,r);let a=o;o>this._maxPitch?(n.y=this._maxPitchTan*r,a=this._maxPitch):othis._maxYaw||aMath.PI?this._isAngleBetween(o,this._maxYaw,this._midYawConstraint)?(n.z=this._maxYawCos*r,n.x=this._maxYawSin*r,l=this._maxYaw):this._isAngleBetween(o,this._midYawConstraint,this._minYaw)&&(n.z=this._minYawCos*r,n.x=this._minYawSin*r,l=this._minYaw):a>this._maxYaw?(n.z=this._maxYawCos*r,n.x=this._maxYawSin*r,o<0&&this.useAbsoluteValueForYaw&&(n.x*=-1),l=this._maxYaw):aMath.PI){const e=Na._TmpVecs[8];e.copyFrom(Gs.Z),this._transformYawPitch&&w.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);const t=Na._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),w.TransformCoordinatesToRef(e,t,e),w.TransformCoordinatesToRef(e,s,e);const i=Math.atan2(e.x,e.z);if(this._getAngleBetween(i,o)>this._getAngleBetween(i,this._midYawConstraint)){null==r&&(r=Math.sqrt(n.x*n.x+n.z*n.z));const e=this._getAngleBetween(i,this._maxYaw);this._getAngleBetween(i,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){let i=0;return i=(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)<(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)?t-e:e-t,i>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e=(e%=2*Math.PI)<0?e+2*Math.PI:e,(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)<(i=(i%=2*Math.PI)<0?i+2*Math.PI:i)){if(e>t&&ei&&e{const e=new Uint8Array(4);return!!((new Uint32Array(e.buffer)[0]=1)&e[0])})();Object.defineProperty(Ki.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0}),Object.defineProperty(Ki.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0}),Object.defineProperty(Ki.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0}),Ki.prototype._rebuild=function(){this._buffer?._rebuild(),this._alignedBuffer?._rebuild()},Ki.prototype.dispose=function(){this._ownsBuffer&&this._buffer.dispose(),this._alignedBuffer?.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0},Ki.prototype.getWrapperBuffer=function(){return this._alignedBuffer||this._buffer},Ki.prototype._alignBuffer=function(){const e=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideAndOffsetMultiple4Bytes||this.byteStride%4==0&&this.byteOffset%4==0||!e)return;const t=Ki.GetTypeByteLength(this.type),i=this.byteStride+3&-4,s=i/t,r=this._maxVerticesCount,n=r*i/t;let o,a;if(Array.isArray(e)){const t=new Float32Array(e);o=new DataView(t.buffer,t.byteOffset,t.byteLength)}else o=e instanceof ArrayBuffer?new DataView(e,0,e.byteLength):new DataView(e.buffer,e.byteOffset,e.byteLength);a=this.type===Ki.BYTE?new Int8Array(n):this.type===Ki.UNSIGNED_BYTE?new Uint8Array(n):this.type===Ki.SHORT?new Int16Array(n):this.type===Ki.UNSIGNED_SHORT?new Uint16Array(n):this.type===Ki.INT?new Int32Array(n):this.type===Ki.UNSIGNED_INT?new Uint32Array(n):new Float32Array(n);const l=this.getSize();let h=this.byteOffset;for(let e=0;e{if(t.type!==ss.POINTERWHEEL)return;const i=t.event,s=i.deltaMode===vs.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*s*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*s*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*s*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,ss.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}ae([pe()],La.prototype,"wheelPrecisionX",void 0),ae([pe()],La.prototype,"wheelPrecisionY",void 0),ae([pe()],La.prototype,"wheelPrecisionZ",void 0);class Ba{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let s=0,r=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=n=>{const o=n.event,a="touch"===o.pointerType;if(n.type!==ss.POINTERMOVE&&-1===this.buttons.indexOf(o.button))return;const l=o.target;if(this._altKey=o.altKey,this._ctrlKey=o.ctrlKey,this._metaKey=o.metaKey,this._shiftKey=o.shiftKey,this._buttonsPressed=o.buttons,t.isPointerLock){const e=o.movementX,t=o.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(n.type!==ss.POINTERDOWN&&n.type!==ss.POINTERDOUBLETAP&&a&&this._pointA?.pointerId!==o.pointerId&&this._pointB?.pointerId!==o.pointerId)return;if(n.type!==ss.POINTERDOWN||-1!==this._currentActiveButton&&!a)if(n.type===ss.POINTERDOUBLETAP)this.onDoubleTap(o.pointerType);else if(n.type!==ss.POINTERUP||this._currentActiveButton!==o.button&&!a){if(n.type===ss.POINTERMOVE)if(e||o.preventDefault(),this._pointA&&null===this._pointB){const e=o.clientX-this._pointA.x,t=o.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=o.clientX,this._pointA.y=o.clientY}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===o.pointerId?this._pointA:this._pointB;e.x=o.clientX,e.y=o.clientY;const t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,a=t*t+i*i,l={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:o.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,s,a,r,l),r=l,s=a}}else{try{l?.releasePointerCapture(o.pointerId)}catch(e){}a||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==o.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==o.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==s||r)&&(this.onMultiTouch(this._pointA,this._pointB,s,0,r,null),s=0,r=null),this._currentActiveButton=-1,this.onButtonUp(o),e||o.preventDefault()}else{try{l?.setPointerCapture(o.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType};else{if(null!==this._pointB)return;this._pointB={x:o.clientX,y:o.clientY,pointerId:o.pointerId,type:o.pointerType}}-1!==this._currentActiveButton||a||(this._currentActiveButton=o.button),this.onButtonDown(o),e||(o.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,ss.POINTERDOWN|ss.POINTERUP|ss.POINTERMOVE|ss.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,s=0,r=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&Ii.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Ii.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,s,r,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}ae([pe()],Ba.prototype,"buttons",void 0);var Va,Ua,ka,Ga,za,Wa,Ha={};class Xa{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();this.attached[t]?J.Warn("camera input of type "+t+" already exists on camera"):(this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault))}remove(e){for(const t in this.attached){const i=this.attached[t];if(i===e)return i.detachControl(),i.camera=null,delete this.attached[t],void this.rebuildInputCheck()}}removeByType(e){for(const t in this.attached){const i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){const t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=!or.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e;for(const t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(const t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(const e in this.attached){const t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){const t={};for(const e in this.attached){const i=this.attached[e],s=Pe.Serialize(i);t[i.getClassName()]=s}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=Ha[e];if(i){const s=t[e],r=Pe.Parse((()=>new i),s,null);this.add(r)}}}else for(const t in this.attached){const i=Ha[this.attached[t].getClassName()];if(i){const s=Pe.Parse((()=>new i),e,null);this.remove(this.attached[t]),this.add(s)}}}}class Ya{get isConnected(){return this._isConnected}constructor(e,t,i,s=0,r=1,n=2,o=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=Ya.GAMEPAD,this._leftStickAxisX=s,this._leftStickAxisY=r,this._rightStickAxisX=n,this._rightStickAxisY=o,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}}Ya.GAMEPAD=0,Ya.GENERIC=1,Ya.XBOX=2,Ya.POSE_ENABLED=3,Ya.DUALSHOCK=4;class ja extends Ya{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new g,this.onButtonUpObservable=new g,this.type=Ya.GENERIC,this._buttons=new Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{e.type!==Ya.POSE_ENABLED&&(this.gamepad&&e.type!==Ya.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(Ya.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){const e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){const i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){const i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}const i=this.gamepad.leftStick;if(i&&0!=i.y){const e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}ae([pe()],$a.prototype,"gamepadRotationSensibility",void 0),ae([pe()],$a.prototype,"gamepadMoveSensibility",void 0),Ha.ArcRotateCameraGamepadInput=$a;class Ka{constructor(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===as.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t0?s/(1+this.wheelDeltaPercentage):s*(1+this.wheelDeltaPercentage),i}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==ss.POINTERWHEEL)return;const i=t.event;let s=0;const r=i.deltaMode===vs.DOM_DELTA_LINE?40:1,n=-i.deltaY*r;if(this.customComputeDeltaFromMouseWheel)s=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if(s=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius),s>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+s;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=G.Clamp(e,0,Number.MAX_VALUE),s=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else s=n/(40*this.wheelPrecision);s&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(s)):this.camera.inertialRadiusOffset+=s),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,ss.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}checkInputs(){if(!this.zoomToMouseLocation)return;const e=this.camera;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){const e=this.camera,t=e.target.subtract(e.position);this._hitPlane=Ps.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,B.Identity(),e,!1);0===e.targetScreenOffset.x&&0===e.targetScreenOffset.y||(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=w.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=i.intersectsPlane(this._hitPlane)??0),i.origin.addInPlace(i.direction.scaleInPlace(s))}_zoomToMouse(e){const t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){const s=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/is&&(e=(t.radius-s)*i-t.inertialRadiusOffset)}const s=e/i/t.radius,r=this._getPosition(),n=U.Vector3[6];r.subtractToRef(t.target,n),n.scaleInPlace(s),n.scaleInPlace(i),this._inertialPanning.addInPlace(n),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,s),this._isPinching=!0):this._computeMultiTouchPanning(r,n)):this.multiTouchPanning?this._computeMultiTouchPanning(r,n):this.pinchZoom&&this._computePinchZoom(i,s))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}Qa.MinimumRadiusForPinch=.001,ae([pe()],Qa.prototype,"buttons",void 0),ae([pe()],Qa.prototype,"angularSensibilityX",void 0),ae([pe()],Qa.prototype,"angularSensibilityY",void 0),ae([pe()],Qa.prototype,"pinchPrecision",void 0),ae([pe()],Qa.prototype,"pinchDeltaPercentage",void 0),ae([pe()],Qa.prototype,"useNaturalPinchZoom",void 0),ae([pe()],Qa.prototype,"pinchZoom",void 0),ae([pe()],Qa.prototype,"panningSensibility",void 0),ae([pe()],Qa.prototype,"multiTouchPanning",void 0),ae([pe()],Qa.prototype,"multiTouchPanAndZoom",void 0),Ha.ArcRotateCameraPointersInput=Qa;class Za extends Xa{constructor(e){super(e)}addMouseWheel(){return this.add(new qa),this}addPointers(){return this.add(new Qa),this}addKeyboard(){return this.add(new Ka),this}}Za.prototype.addVRDeviceOrientation=function(){return this.add(new Ja),this};class Ja{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=e=>this._onOrientationEvent(e)}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);const t=this.camera.getScene().getEngine().getHostWindow();t&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t.addEventListener("deviceorientation",this._deviceOrientationHandler):Ii.Warn("Permission not granted.")})).catch((e=>{Ii.Error(e)})):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*this.gammaCorrection),this._dirty=!0}checkInputs(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)}detachControl(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)}getClassName(){return"ArcRotateCameraVRDeviceOrientationInput"}getSimpleName(){return"VRDeviceOrientation"}}Ha.ArcRotateCameraVRDeviceOrientationInput=Ja;class el{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=new Array}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(t.type===as.KEYDOWN)-1===this.keysForward.indexOf(i.keyCode)&&-1===this.keysBackward.indexOf(i.keyCode)&&-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{this._pointerInput(e)}),ss.POINTERDOWN|ss.POINTERUP|ss.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add((()=>{this.camera.rollCorrect&&this.camera.restoreRoll(this.camera.rollCorrect)}))}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)}getClassName(){return"FlyCameraMouseInput"}getSimpleName(){return"mouse"}_pointerInput(e){const t=e.event,i=this.camera.getEngine();if(!this.touchEnabled&&"touch"===t.pointerType)return;if(e.type!==ss.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;const s=t.target;if(e.type===ss.POINTERDOWN){try{s?.setPointerCapture(t.pointerId)}catch(t){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),i.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===ss.POINTERUP){try{s?.releasePointerCapture(t.pointerId)}catch(t){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===ss.POINTERMOVE){if(!this._previousPosition)return void(i.isPointerLock&&this._onMouseMove(e.event));const s=t.clientX-this._previousPosition.x,r=t.clientY-this._previousPosition.y;this._rotateCamera(s,r),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){if(!this.camera.getEngine().isPointerLock)return;const t=e.movementX,i=e.movementY;this._rotateCamera(t,i),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera,s=(e*=i._calculateHandednessMultiplier())/this.angularSensibility,r=t/this.angularSensibility,n=L.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let o;if(this.buttonsPitch.some((e=>e===this.activeButton))&&(o=L.RotationAxis(Gs.X,r),n.multiplyInPlace(o)),this.buttonsYaw.some((e=>e===this.activeButton))){o=L.RotationAxis(Gs.Y,s),n.multiplyInPlace(o);const e=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-ee===this.activeButton))&&(o=L.RotationAxis(Gs.Z,-s),i._trackRoll-=s,n.multiplyInPlace(o)),n.toEulerAnglesToRef(i.rotation)}}ae([pe()],tl.prototype,"buttons",void 0),ae([pe()],tl.prototype,"angularSensibility",void 0),Ha.FlyCameraMouseInput=tl;class il{constructor(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=new Array}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===as.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){this._onKeyboardObserver&&this._keys.forEach((e=>{-1!==this.keysHeightOffsetIncr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:-1!==this.keysHeightOffsetDecr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:-1!==this.keysRotationOffsetIncr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRotationOffsetDecr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRadiusIncr.indexOf(e)&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:-1!==this.keysRadiusDecr.indexOf(e)&&this._modifierRadius()&&(this.camera.radius-=this.radiusSensibility)}))}getClassName(){return"FollowCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}_modifierHeightOffset(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed}_modifierRotationOffset(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed}_modifierRadius(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed}}ae([pe()],il.prototype,"keysHeightOffsetIncr",void 0),ae([pe()],il.prototype,"keysHeightOffsetDecr",void 0),ae([pe()],il.prototype,"keysHeightOffsetModifierAlt",void 0),ae([pe()],il.prototype,"keysHeightOffsetModifierCtrl",void 0),ae([pe()],il.prototype,"keysHeightOffsetModifierShift",void 0),ae([pe()],il.prototype,"keysRotationOffsetIncr",void 0),ae([pe()],il.prototype,"keysRotationOffsetDecr",void 0),ae([pe()],il.prototype,"keysRotationOffsetModifierAlt",void 0),ae([pe()],il.prototype,"keysRotationOffsetModifierCtrl",void 0),ae([pe()],il.prototype,"keysRotationOffsetModifierShift",void 0),ae([pe()],il.prototype,"keysRadiusIncr",void 0),ae([pe()],il.prototype,"keysRadiusDecr",void 0),ae([pe()],il.prototype,"keysRadiusModifierAlt",void 0),ae([pe()],il.prototype,"keysRadiusModifierCtrl",void 0),ae([pe()],il.prototype,"keysRadiusModifierShift",void 0),ae([pe()],il.prototype,"heightSensibility",void 0),ae([pe()],il.prototype,"rotationSensibility",void 0),ae([pe()],il.prototype,"radiusSensibility",void 0),Ha.FollowCameraKeyboardMoveInput=il;class sl{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==ss.POINTERWHEEL)return;const i=t.event;let s=0;const r=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(+this.axisControlRadius+ +this.axisControlHeight+ +this.axisControlRotation&&J.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?s=.01*r*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?s=.01*r*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(s=.01*r*this.wheelDeltaPercentage*this.camera.rotationOffset)):s=r*this.wheelPrecision,s&&(this.axisControlRadius?this.camera.radius+=s:this.axisControlHeight?this.camera.heightOffset-=s:this.axisControlRotation&&(this.camera.rotationOffset-=s)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,ss.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}ae([pe()],sl.prototype,"axisControlRadius",void 0),ae([pe()],sl.prototype,"axisControlHeight",void 0),ae([pe()],sl.prototype,"axisControlRotation",void 0),ae([pe()],sl.prototype,"wheelPrecision",void 0),ae([pe()],sl.prototype,"wheelDeltaPercentage",void 0),Ha.FollowCameraMouseWheelInput=sl;class rl extends Ba{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,s,r,n){if(0===i&&null===r)return;if(0===s&&null===n)return;let o=(s-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(o*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=o*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=o*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=o*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=o),this.axisPinchControlHeight&&(this.camera.heightOffset+=o),this.axisPinchControlRadius&&(this.camera.radius-=o))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;const e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";+this.axisXControlRotation+ +this.axisXControlHeight+ +this.axisXControlRadius<=1&&J.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&J.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&J.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}ae([pe()],rl.prototype,"angularSensibilityX",void 0),ae([pe()],rl.prototype,"angularSensibilityY",void 0),ae([pe()],rl.prototype,"pinchPrecision",void 0),ae([pe()],rl.prototype,"pinchDeltaPercentage",void 0),ae([pe()],rl.prototype,"axisXControlRadius",void 0),ae([pe()],rl.prototype,"axisXControlHeight",void 0),ae([pe()],rl.prototype,"axisXControlRotation",void 0),ae([pe()],rl.prototype,"axisYControlRadius",void 0),ae([pe()],rl.prototype,"axisYControlHeight",void 0),ae([pe()],rl.prototype,"axisYControlRotation",void 0),ae([pe()],rl.prototype,"axisPinchControlRadius",void 0),ae([pe()],rl.prototype,"axisPinchControlHeight",void 0),ae([pe()],rl.prototype,"axisPinchControlRotation",void 0),Ha.FollowCameraPointersInput=rl;class nl{constructor(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(!i.metaKey)if(t.type===as.KEYDOWN)-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)&&-1===this.keysUpward.indexOf(i.keyCode)&&-1===this.keysDownward.indexOf(i.keyCode)&&-1===this.keysRotateLeft.indexOf(i.keyCode)&&-1===this.keysRotateRight.indexOf(i.keyCode)&&-1===this.keysRotateUp.indexOf(i.keyCode)&&-1===this.keysRotateDown.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysUpward.indexOf(i.keyCode)||-1!==this.keysDownward.indexOf(i.keyCode)||-1!==this.keysRotateLeft.indexOf(i.keyCode)||-1!==this.keysRotateRight.indexOf(i.keyCode)||-1!==this.keysRotateUp.indexOf(i.keyCode)||-1!==this.keysRotateDown.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{const r=s.event,n="touch"===r.pointerType;if(!this.touchEnabled&&n)return;if(s.type!==ss.POINTERMOVE&&-1===this.buttons.indexOf(r.button))return;const o=r.target;if(s.type===ss.POINTERDOWN){if(n&&-1!==this._activePointerId||!n&&-1!==this._currentActiveButton)return;this._activePointerId=r.pointerId;try{o?.setPointerCapture(r.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=r.button),this._previousPosition={x:r.clientX,y:r.clientY},e||(r.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(s.event)}else if(s.type===ss.POINTERUP){if(n&&this._activePointerId!==r.pointerId||!n&&this._currentActiveButton!==r.button)return;try{o?.releasePointerCapture(r.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||r.preventDefault(),this._activePointerId=-1}else if(s.type===ss.POINTERMOVE&&(this._activePointerId===r.pointerId||!n))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(s.event);else if(this._previousPosition){const t=this.camera._calculateHandednessMultiplier(),i=(r.clientX-this._previousPosition.x)*t,s=r.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=s/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:s}),this._previousPosition={x:r.clientX,y:r.clientY},e||r.preventDefault()}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;const s=this.camera._calculateHandednessMultiplier(),r=i.movementX*s;this.camera.cameraRotation.y+=r/this.angularSensibility;const n=i.movementY;this.camera.cameraRotation.x+=n/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,ss.POINTERDOWN|ss.POINTERUP|ss.POINTERMOVE),i&&(this._contextMenuBind=e=>this.onContextMenu(e),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}ae([pe()],ol.prototype,"buttons",void 0),ae([pe()],ol.prototype,"angularSensibility",void 0),Ha.FreeCameraMouseInput=ol,function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(Va||(Va={}));class al extends La{constructor(){super(...arguments),this._moveRelative=w.Zero(),this._rotateRelative=w.Zero(),this._moveScene=w.Zero(),this._wheelXAction=Va.MoveRelative,this._wheelXActionCoordinate=Ls.X,this._wheelYAction=Va.MoveRelative,this._wheelYActionCoordinate=Ls.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){null===e&&this._wheelXAction!==Va.MoveRelative||(this._wheelXAction=Va.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Va.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){null===e&&this._wheelYAction!==Va.MoveRelative||(this._wheelYAction=Va.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Va.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){null===e&&this._wheelZAction!==Va.MoveRelative||(this._wheelZAction=Va.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Va.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){null===e&&this._wheelXAction!==Va.RotateRelative||(this._wheelXAction=Va.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Va.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){null===e&&this._wheelYAction!==Va.RotateRelative||(this._wheelYAction=Va.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Va.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){null===e&&this._wheelZAction!==Va.RotateRelative||(this._wheelZAction=Va.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Va.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){null===e&&this._wheelXAction!==Va.MoveScene||(this._wheelXAction=Va.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Va.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){null===e&&this._wheelYAction!==Va.MoveScene||(this._wheelYAction=Va.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Va.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){null===e&&this._wheelZAction!==Va.MoveScene||(this._wheelZAction=Va.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Va.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(0===this._wheelDeltaX&&0===this._wheelDeltaY&&0==this._wheelDeltaZ)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);const e=B.Zero();this.camera.getViewMatrix().invertToRef(e);const t=w.Zero();w.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,i){if(0===e)return;if(null===t||null===i)return;let s=null;switch(t){case Va.MoveRelative:s=this._moveRelative;break;case Va.RotateRelative:s=this._rotateRelative;break;case Va.MoveScene:s=this._moveScene}switch(i){case Ls.X:s.set(e,0,0);break;case Ls.Y:s.set(0,e,0);break;case Ls.Z:s.set(0,0,e)}}}ae([pe()],al.prototype,"wheelXMoveRelative",null),ae([pe()],al.prototype,"wheelYMoveRelative",null),ae([pe()],al.prototype,"wheelZMoveRelative",null),ae([pe()],al.prototype,"wheelXRotateRelative",null),ae([pe()],al.prototype,"wheelYRotateRelative",null),ae([pe()],al.prototype,"wheelZRotateRelative",null),ae([pe()],al.prototype,"wheelXMoveScene",null),ae([pe()],al.prototype,"wheelYMoveScene",null),ae([pe()],al.prototype,"wheelZMoveScene",null),Ha.FreeCameraMouseWheelInput=al;class ll{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=Ii.IsSafari()}attachControl(e){e=Ii.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{const s=i.event,r="mouse"===s.pointerType||this._isSafari&&void 0===s.pointerType;if(this.allowMouse||!r)if(i.type===ss.POINTERDOWN){if(e||s.preventDefault(),this._pointerPressed.push(s.pointerId),1!==this._pointerPressed.length)return;t={x:s.clientX,y:s.clientY}}else if(i.type===ss.POINTERUP){e||s.preventDefault();const i=this._pointerPressed.indexOf(s.pointerId);if(-1===i)return;if(this._pointerPressed.splice(i,1),0!=i)return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===ss.POINTERMOVE){if(e||s.preventDefault(),!t)return;if(0!=this._pointerPressed.indexOf(s.pointerId))return;this._offsetX=s.clientX-t.x,this._offsetY=-(s.clientY-t.y)}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,ss.POINTERDOWN|ss.POINTERUP|ss.POINTERMOVE),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(null===this._offsetX||null===this._offsetY)return;if(0===this._offsetX&&0===this._offsetY)return;const e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility,this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{const t=e._computeLocalCameraSpeed(),i=new w(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);B.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(w.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}ae([pe()],ll.prototype,"touchAngularSensibility",void 0),ae([pe()],ll.prototype,"touchMoveSensibility",void 0),Ha.FreeCameraTouchInput=ll;class hl extends Xa{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new nl),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new ol(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new al,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new ll),this}clear(){super.clear(),this._mouseInput=null}}hl.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new cl,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};class cl{static WaitForOrientationChangeAsync(e){return new Promise(((t,i)=>{let s=!1;const r=()=>{window.removeEventListener("deviceorientation",r),s=!0,t()};e&&setTimeout((()=>{s||(window.removeEventListener("deviceorientation",r),i("WaitForOrientationChangeAsync timed out"))}),e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"==e?window.addEventListener("deviceorientation",r):Ii.Warn("Permission not granted.")})).catch((e=>{Ii.Error(e)})):window.addEventListener("deviceorientation",r)}))}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new L,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new g,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-Ii.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?Ii.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?Ii.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?Ii.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new L(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new L),this._camera&&this._camera.onDisposeObservable.add((()=>{this._onDeviceOrientationChangedObservable.clear()}))}attachControl(){const e=this.camera.getScene().getEngine().getHostWindow();if(e){const t=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t():Ii.Warn("Permission not granted.")})).catch((e=>{Ii.Error(e)})):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(L.RotationYawPitchRollToRef(Ii.ToRadians(this._alpha),Ii.ToRadians(this._beta),-Ii.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}Ha.FreeCameraDeviceOrientationInput=cl;class ul{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=B.Identity(),this._deltaTransform=w.Zero(),this._vector3=w.Zero(),this._vector2=N.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{e.type!==Ya.POSE_ENABLED&&(this.gamepad&&e.type!==Ya.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(Ya.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){const e=this.camera,t=this.gamepad.leftStick;0!==this.gamepadMoveSensibility&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&0!==this.gamepadAngularSensibility?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):B.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const s=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*s,0,-t.y*s),w.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}}ae([pe()],ul.prototype,"gamepadAngularSensibility",void 0),ae([pe()],ul.prototype,"gamepadMoveSensibility",void 0),Ha.FreeCameraGamepadInput=ul,function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Ua||(Ua={}));class dl{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;const i={...dl._GetDefaultOptions(),...t};if(this._leftJoystick=!!e,dl._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=Ua.X,this._axisTargetedByUpAndDown=Ua.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new Oi,this.deltaPosition=w.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{dl._VJCanvasWidth=window.innerWidth,dl._VJCanvasHeight=window.innerHeight,dl.Canvas&&(dl.Canvas.width=dl._VJCanvasWidth,dl.Canvas.height=dl._VJCanvasHeight),dl._HalfWidth=dl._VJCanvasWidth/2},!dl.Canvas){window.addEventListener("resize",this._onResize,!1),dl.Canvas=document.createElement("canvas"),dl._VJCanvasWidth=window.innerWidth,dl._VJCanvasHeight=window.innerHeight,dl.Canvas.width=window.innerWidth,dl.Canvas.height=window.innerHeight,dl.Canvas.style.width="100%",dl.Canvas.style.height="100%",dl.Canvas.style.position="absolute",dl.Canvas.style.backgroundColor="transparent",dl.Canvas.style.top="0px",dl.Canvas.style.left="0px",dl.Canvas.style.zIndex="5",dl.Canvas.style.touchAction="none",dl.Canvas.setAttribute("touch-action","none");const e=dl.Canvas.getContext("2d");if(!e)throw new Error("Unable to create canvas for virtual joystick");dl._VJCanvasContext=e,dl._VJCanvasContext.strokeStyle="#ffffff",dl._VJCanvasContext.lineWidth=2,document.body.appendChild(dl.Canvas)}dl._HalfWidth=dl.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&dl._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new N(0,0),this._joystickPreviousPointerPos=new N(0,0),this._joystickPointerStartPos=new N(0,0),this._deltaJoystickVector=new N(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},dl.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),dl.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),dl.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),dl.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),dl.Canvas.addEventListener("contextmenu",(e=>{e.preventDefault()}),!1),requestAnimationFrame((()=>{this._drawVirtualJoystick()}))}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){let t;e.preventDefault(),t=!0===this._leftJoystick?e.clientXdl._HalfWidth,t&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):dl._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){const t=new N(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0this._containerImage=t}setPuckImage(e){const t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){const e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?dl._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(dl._VJCanvasContext.beginPath(),dl._VJCanvasContext.strokeStyle=this._joystickColor,dl._VJCanvasContext.lineWidth=2,dl._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),dl._VJCanvasContext.stroke(),dl._VJCanvasContext.closePath(),dl._VJCanvasContext.beginPath(),dl._VJCanvasContext.lineWidth=6,dl._VJCanvasContext.strokeStyle=this._joystickColor,dl._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),dl._VJCanvasContext.stroke(),dl._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?dl._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(dl._VJCanvasContext.beginPath(),dl._VJCanvasContext.strokeStyle=this._joystickColor,dl._VJCanvasContext.lineWidth=2,dl._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),dl._VJCanvasContext.stroke(),dl._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach(((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(dl._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),dl._VJCanvasContext.beginPath(),dl._VJCanvasContext.fillStyle="white",dl._VJCanvasContext.beginPath(),dl._VJCanvasContext.strokeStyle="red",dl._VJCanvasContext.lineWidth=6,dl._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),dl._VJCanvasContext.stroke(),dl._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)})),requestAnimationFrame((()=>{this._drawVirtualJoystick()})))}releaseCanvas(){dl.Canvas&&(dl.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),dl.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),dl.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),dl.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(dl.Canvas),dl.Canvas=null),this._released=!0}}dl._GlobalJoystickIndex=0,dl._AlwaysVisibleSticks=0,hl.prototype.addVirtualJoystick=function(){return this.add(new pl),this};class pl{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=50*e._computeLocalCameraSpeed(),i=B.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),s=w.TransformCoordinates(new w(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(s),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new dl(!0),this._leftjoystick.setAxisForUpDown(Ua.Z),this._leftjoystick.setAxisForLeftRight(Ua.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new dl(!1),this._rightjoystick.setAxisForUpDown(Ua.X),this._rightjoystick.setAxisForLeftRight(Ua.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}}Ha.FreeCameraVirtualJoystickInput=pl,De.AddNodeConstructor("TargetCamera",((e,t)=>()=>new fl(e,w.Zero(),t)));class fl extends or{constructor(e,t,i,s=!0){super(e,t,i,s),this._tmpUpVector=w.Zero(),this._tmpTargetVector=w.Zero(),this.cameraDirection=new w(0,0,0),this.cameraRotation=new N(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new L,this.rotation=new w(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=w.Zero(),this._initialFocalDistance=1,this._viewMatrix=B.Zero(),this._camMatrix=B.Zero(),this._cameraTransformMatrix=B.Zero(),this._cameraRotationMatrix=B.Zero(),this._referencePoint=new w(0,0,1),this._transformedReferencePoint=w.Zero(),this._deferredPositionUpdate=new w,this._deferredRotationQuaternionUpdate=new L,this._deferredRotationUpdate=new w,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=w.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();const t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){const e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)}_initCache(){super._initCache(),this._cache.lockedTarget=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new L(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();const t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;const e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){const e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=T),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),B.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);const t=e.subtract(this.position);t.x>=0?this.rotation.y=-Math.atan(t.z/t.x)+Math.PI/2:this.rotation.y=-Math.atan(t.z/t.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&L.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(U.Matrix[0]),w.TransformNormalToRef(this.cameraDirection,U.Matrix[0],U.Vector3[0]),this._deferredPositionUpdate.addInPlace(U.Vector3[0]),void(this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate));this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint){const e=1.570796;this._deferredRotationUpdate.x>e&&(this._deferredRotationUpdate.x=e),this._deferredRotationUpdate.x<-e&&(this._deferredRotationUpdate.x=-e)}this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(L.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))}t&&(Math.abs(this.cameraDirection.x){this._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>Br.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new hl(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ii.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new w(0,0,0),this.cameraRotation=new N(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?w.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=w.Zero(),this._transformedDirection=w.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}}ae([ve()],_l.prototype,"ellipsoid",void 0),ae([ve()],_l.prototype,"ellipsoidOffset",void 0),ae([pe()],_l.prototype,"checkCollisions",void 0),ae([pe()],_l.prototype,"applyGravity",void 0),u("BABYLON.FreeCamera",_l),De.AddNodeConstructor("TouchCamera",((e,t)=>()=>new ml(e,w.Zero(),t)));class ml extends _l{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!e:e.allowMouse=!t}}De.AddNodeConstructor("ArcRotateCamera",((e,t)=>()=>new gl(e,0,0,1,w.Zero(),t)));class gl extends fl{get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new B,this._upToYMatrix=new B,this._upVector=w.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){B.RotationAlignToRef(w.UpReadOnly,this._upVector,this._yToUpMatrix),B.RotationAlignToRef(this._upVector,w.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){const e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){const t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){const e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){const t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){const e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){const t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){const e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){const t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){const e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){const e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){const t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){const e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return null!=this._bouncingBehavior}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new no,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return null!=this._framingBehavior}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new oo,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return null!=this._autoRotationBehavior}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new ro,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,s,r,n,o=!0){super(e,w.Zero(),n,o),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=w.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=N.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new B,this.panningAxis=new w(1,1,0),this._transformedDirection=new w,this.mapPanning=!1,this.onMeshTargetChangedObservable=new g,this.checkCollisions=!1,this.collisionRadius=new w(.5,.5,.5),this._previousPosition=w.Zero(),this._collisionVelocity=w.Zero(),this._newPosition=w.Zero(),this._computationVector=w.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);const s=Math.cos(this.alpha),r=Math.sin(this.alpha),n=Math.cos(this.beta);let o=Math.sin(this.beta);0===o&&(o=1e-4);const a=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*s*o,this.radius*n,this.radius*r*o),a.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=l.clone(),l=l.negate()),this._computeViewMatrix(this._position,a,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=w.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=i,this.radius=s,this.getViewMatrix(),this.inputs=new Za(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=N.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){const e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}return this._getLockedTargetPosition()||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)}_isSynchronizedViewMatrix(){return!!super._isSynchronizedViewMatrix()&&this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset)}attachControl(e,t,i=!0,s=2){const r=arguments;t=Ii.BackCompatCameraNoPreventDefault(r),this._useCtrlForPanning=i,this._panningMouseButton=s,"boolean"==typeof r[0]&&(r.length>1&&(this._useCtrlForPanning=r[1]),r.length>2&&(this._panningMouseButton=r[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){const e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier();let i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||w.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);const e=this.alpha;0===this._computationVector.x&&0===this._computationVector.z?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,s=!1){if(s=this.overrideCloneAlphaBetaRadius??s,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const t=e,s=this._getTargetPosition();if(s&&!i&&s.equals(t))return;this._targetHost=null,this._target=t,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}s||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta);let s=Math.sin(this.beta);0===s&&(s=1e-4),0===this.radius&&(this.radius=1e-4);const r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*s,this.radius*i,this.radius*t*s),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||w.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),r.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&s<0&&(e=e.negate()),this._computeViewMatrix(this._position,r,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=Un.MinMax(e);let s=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);s=Math.max(Math.min(s,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=s*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:s},t)}focusOn(e,t=!1){let i,s;if(void 0===e.min){const t=e||this.getScene().meshes;i=Un.MinMax(t),s=w.Distance(i.min,i.max)}else i=e,s=e.distance;this._target=Un.Center(i),t||(this.maxZ=2*s)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case or.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case or.RIG_MODE_STEREOSCOPIC_OVERUNDER:case or.RIG_MODE_STEREOSCOPIC_INTERLACED:case or.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const s=new gl(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return s._cameraRigParams={},s.isRigCamera=!0,s.rigParent=this,s.upVector=this.upVector,s.mode=this.mode,s.orthoLeft=this.orthoLeft,s.orthoRight=this.orthoRight,s.orthoBottom=this.orthoBottom,s.orthoTop=this.orthoTop,s}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case or.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case or.RIG_MODE_STEREOSCOPIC_OVERUNDER:case or.RIG_MODE_STEREOSCOPIC_INTERLACED:case or.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){const s=w.Distance(e,t),r=this.getScene().getEngine().getAspectRatio(this),n=Math.tan(this.fov/2),o=n*r,a=.5*s*i,l=a*Math.sqrt(1+1/(o*o)),h=a*Math.sqrt(1+1/(n*n));return Math.max(l,h)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}ae([pe()],gl.prototype,"alpha",void 0),ae([pe()],gl.prototype,"beta",void 0),ae([pe()],gl.prototype,"radius",void 0),ae([pe()],gl.prototype,"overrideCloneAlphaBetaRadius",void 0),ae([ve("target")],gl.prototype,"_target",void 0),ae([xe("targetHost")],gl.prototype,"_targetHost",void 0),ae([pe()],gl.prototype,"inertialAlphaOffset",void 0),ae([pe()],gl.prototype,"inertialBetaOffset",void 0),ae([pe()],gl.prototype,"inertialRadiusOffset",void 0),ae([pe()],gl.prototype,"lowerAlphaLimit",void 0),ae([pe()],gl.prototype,"upperAlphaLimit",void 0),ae([pe()],gl.prototype,"lowerBetaLimit",void 0),ae([pe()],gl.prototype,"upperBetaLimit",void 0),ae([pe()],gl.prototype,"lowerRadiusLimit",void 0),ae([pe()],gl.prototype,"upperRadiusLimit",void 0),ae([pe()],gl.prototype,"inertialPanningX",void 0),ae([pe()],gl.prototype,"inertialPanningY",void 0),ae([pe()],gl.prototype,"pinchToPanMaxDistance",void 0),ae([pe()],gl.prototype,"panningDistanceLimit",void 0),ae([ve()],gl.prototype,"panningOriginTarget",void 0),ae([pe()],gl.prototype,"panningInertia",void 0),ae([pe()],gl.prototype,"zoomToMouseLocation",null),ae([pe()],gl.prototype,"zoomOnFactor",void 0),ae([ge()],gl.prototype,"targetScreenOffset",void 0),ae([pe()],gl.prototype,"allowUpsideDown",void 0),ae([pe()],gl.prototype,"useInputToRestoreState",void 0),u("BABYLON.ArcRotateCamera",gl),De.AddNodeConstructor("DeviceOrientationCamera",((e,t)=>()=>new vl(e,w.Zero(),t)));class vl extends _l{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new L,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new L,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce((()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add((e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new L),L.FromEulerAnglesToRef(0,e.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))})))}))}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=Gs.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new L),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}}class xl extends Xa{constructor(e){super(e)}addKeyboard(){return this.add(new el),this}addMouse(){return this.add(new tl),this}}class Tl extends fl{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){const e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){const t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){const e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){const t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,s=!0){super(e,t,i,s),this.ellipsoid=new w(1,1,1),this.ellipsoidOffset=new w(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=w.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=w.Zero(),this._diffPosition=w.Zero(),this._newPosition=w.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>Br.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new xl(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Ii.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new w(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?w.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let s=e;this.applyGravity&&(s=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,s,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=w.Zero(),this._transformedDirection=w.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}restoreRoll(e){const t=this._trackRoll,i=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,Math.abs(t-this.rotation.z)<=.001&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}ae([ve()],Tl.prototype,"ellipsoid",void 0),ae([ve()],Tl.prototype,"ellipsoidOffset",void 0),ae([pe()],Tl.prototype,"checkCollisions",void 0),ae([pe()],Tl.prototype,"applyGravity",void 0),u("BABYLON.FlyCamera",Tl);class Sl extends Xa{constructor(e){super(e)}addKeyboard(){return this.add(new il),this}addMouseWheel(){return this.add(new sl),this}addPointers(){return this.add(new rl),this}addVRDeviceOrientation(){return J.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}De.AddNodeConstructor("FollowCamera",((e,t)=>()=>new El(e,w.Zero(),t))),De.AddNodeConstructor("ArcFollowCamera",((e,t)=>()=>new bl(e,0,0,1,null,t)));class El extends fl{constructor(e,t,i,s=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=s,this.inputs=new Sl(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=U.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),s=Ii.ToRadians(this.rotationOffset)+i,r=e.getAbsolutePosition(),n=r.x+Math.sin(s)*this.radius,o=r.z+Math.cos(s)*this.radius,a=n-this.position.x,l=r.y+this.heightOffset-this.position.y,h=o-this.position.z;let c=a*this.cameraAcceleration*2,u=l*this.cameraAcceleration,d=h*this.cameraAcceleration*2;(c>this.maxCameraSpeed||c<-this.maxCameraSpeed)&&(c=c<1?-this.maxCameraSpeed:this.maxCameraSpeed),(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new w(this.position.x+c,this.position.y+u,this.position.z+d),this.setTarget(r)}attachControl(e,t){t=Ii.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=()=>{}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){this.inputs.checkInputs(),this._checkLimits(),super._checkInputs(),this.lockedTarget&&this._follow(this.lockedTarget)}_checkLimits(){null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}ae([pe()],El.prototype,"radius",void 0),ae([pe()],El.prototype,"lowerRadiusLimit",void 0),ae([pe()],El.prototype,"upperRadiusLimit",void 0),ae([pe()],El.prototype,"rotationOffset",void 0),ae([pe()],El.prototype,"lowerRotationOffsetLimit",void 0),ae([pe()],El.prototype,"upperRotationOffsetLimit",void 0),ae([pe()],El.prototype,"heightOffset",void 0),ae([pe()],El.prototype,"lowerHeightOffsetLimit",void 0),ae([pe()],El.prototype,"upperHeightOffsetLimit",void 0),ae([pe()],El.prototype,"cameraAcceleration",void 0),ae([pe()],El.prototype,"maxCameraSpeed",void 0),ae([xe("lockedTargetId")],El.prototype,"lockedTarget",void 0);class bl extends fl{constructor(e,t,i,s,r,n){super(e,w.Zero(),n),this.alpha=t,this.beta=i,this.radius=s,this._cartesianCoordinates=w.Zero(),this.setMeshTarget(r)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);const e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}u("BABYLON.FollowCamera",El),u("BABYLON.ArcFollowCamera",bl),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(ka||(ka={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Ga||(Ga={}));class Cl extends Ya{constructor(e,t,i,s=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new g,this.onButtonUpObservable=new g,this.onPadDownObservable=new g,this.onPadUpObservable=new g,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this.type=Ya.XBOX,this._isXboxOnePad=s}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,ka.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,ka.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,ka.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,ka.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,ka.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,ka.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,ka.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,ka.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,ka.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,ka.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Ga.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Ga.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Ga.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Ga.Right)}update(){super.update(),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}!function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(za||(za={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Wa||(Wa={}));class yl extends Ya{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new g,this.onButtonUpObservable=new g,this.onPadDownObservable=new g,this.onPadUpObservable=new g,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=Ya.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,za.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,za.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,za.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,za.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,za.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,za.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,za.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,za.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,za.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,za.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Wa.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Wa.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Wa.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Wa.Right)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class Al{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new g,We()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new g((e=>{for(const t in this._babylonGamepads){const i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}})),this._onGamepadConnectedEvent=e=>{const t=e.gamepad;if(t.index in this._babylonGamepads&&this._babylonGamepads[t.index].isConnected)return;let i;this._babylonGamepads[t.index]?(i=this._babylonGamepads[t.index],i.browserGamepad=t,i._isConnected=!0):i=this._addNewGamepad(t),this.onGamepadConnectedObservable.notifyObservers(i),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=e=>{const t=e.gamepad;for(const e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){const t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){const e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}get gamepads(){return this._babylonGamepads}getGamepadByType(e=Ya.XBOX){for(const t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach((e=>{e.dispose()})),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);const i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),s=-1!==e.id.search("Xbox One");return t=s||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new Cl(e.id,e.index,e,s):i?new yl(e.id,e.index,e):new ja(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){this._updateGamepadObjects();for(const e in this._babylonGamepads){const t=this._babylonGamepads[e];if(t&&t.isConnected)try{t.update()}catch{-1===this._loggedErrors.indexOf(t.index)&&(Ii.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&Br.QueueNewFrame((()=>{this._checkGamepadsStatus()}))}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new Il(e,w.Zero(),t)));class Il extends ml{get gamepadAngularSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}}or._CreateDefaultParsedCamera=(e,t)=>new Il(e,w.Zero(),t),De.AddNodeConstructor("GamepadCamera",((e,t)=>()=>new Pl(e,w.Zero(),t)));class Pl extends Il{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}Ft.ShadersStore.passCubePixelShader="varying vec2 vUV;uniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";class Ml extends Ko{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,s,r,n,o=0,a=!1){super(e,"pass",null,null,t,i,s,r,n,void 0,o,void 0,null,a)}static _Parse(e,t,i,s){return Pe.Parse((()=>new Ml(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,s)}}u("BABYLON.PassPostProcess",Ml),si._RescalePostProcessFactory=e=>new Ml("rescale",1,null,2,e,!1,0);Ft.ShadersStore.anaglyphPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}";class Dl extends Ko{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,s,r,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],s,r,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)}))}}function Ol(e){e._rigCameras[0]._rigPostProcess=new Ml(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new Dl(e.name+"_anaglyph",1,e._rigCameras)}u("BABYLON.AnaglyphPostProcess",Dl),De.AddNodeConstructor("AnaglyphArcRotateCamera",((e,t,i)=>()=>new Nl(e,0,0,1,w.Zero(),i.interaxial_distance,t)));class Nl extends gl{constructor(e,t,i,s,r,n,o){super(e,t,i,s,r,o),this._setRigMode=()=>Ol(this),this.interaxialDistance=n,this.setCameraRigMode(or.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}De.AddNodeConstructor("AnaglyphFreeCamera",((e,t,i)=>()=>new wl(e,w.Zero(),i.interaxial_distance,t)));class wl extends _l{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Ol(this),this.interaxialDistance=i,this.setCameraRigMode(or.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}De.AddNodeConstructor("AnaglyphGamepadCamera",((e,t,i)=>()=>new Fl(e,w.Zero(),i.interaxial_distance,t)));class Fl extends Pl{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Ol(this),this.interaxialDistance=i,this.setCameraRigMode(or.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}De.AddNodeConstructor("AnaglyphUniversalCamera",((e,t,i)=>()=>new Ll(e,w.Zero(),i.interaxial_distance,t)));class Ll extends Il{constructor(e,t,i,s){super(e,t,s),this._setRigMode=()=>Ol(this),this.interaxialDistance=i,this.setCameraRigMode(or.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}Ft.ShadersStore.stereoscopicInterlacePixelShader="const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\n#ifdef IS_STEREOSCOPIC_INTERLACED\nfloat rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n#endif\nif (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);}\n";class Bl extends Ko{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,s,r,n,o){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],r,n,o,s?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new N(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new N(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}function Vl(e){const t=e.cameraRigMode===or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;e.cameraRigMode===or.RIG_MODE_STEREOSCOPIC_INTERLACED?(e._rigCameras[0]._rigPostProcess=new Ml(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new Bl(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new nr(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new nr(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}De.AddNodeConstructor("StereoscopicArcRotateCamera",((e,t,i)=>()=>new Ul(e,0,0,1,w.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Ul extends gl{constructor(e,t,i,s,r,n,o,a){super(e,t,i,s,r,a),this._setRigMode=()=>Vl(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:or.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}De.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new kl(e,w.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class kl extends _l{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Vl(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:or.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}De.AddNodeConstructor("StereoscopicGamepadCamera",((e,t,i)=>()=>new Gl(e,w.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class Gl extends Pl{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Vl(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:or.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}De.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new zl(e,w.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class zl extends Il{constructor(e,t,i,s,r){super(e,t,r),this._setRigMode=()=>Vl(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=s,this.setCameraRigMode(s?or.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:or.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}De.AddNodeConstructor("VirtualJoysticksCamera",((e,t)=>()=>new Wl(e,w.Zero(),t)));class Wl extends _l{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class Hl{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return B.Translation(e,0,0)}get rightHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return B.Translation(-e,0,0)}get leftPreViewMatrix(){return B.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return B.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new Hl;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}Ft.ShadersStore.vrDistortionCorrectionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}";class Xl extends Ko{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,s){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,s.postProcessScaleFactor,t,Zn.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=s.distortionK,this._postProcessScaleFactor=s.postProcessScaleFactor,this._lensCenterOffset=s.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add((()=>{this._scaleIn=new N(2,2/this.aspectRatio),this._scaleFactor=new N(1/this._postProcessScaleFactor*.5,1/this._postProcessScaleFactor*.5*this.aspectRatio),this._lensCenter=new N(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)})),this.onApplyObservable.add((e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])}))}}Ft.ShadersStore.vrMultiviewToSingleviewPixelShader="precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}";class Yl extends da{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}}function jl(e,t){const i=new ji(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}Br.prototype.createMultiviewRenderTargetTexture=function(e,t,i,s){const r=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const n=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});n._framebuffer=r.createFramebuffer();const o=new ti(this,ei.Unknown,!0);return o.width=e,o.height=t,o.isMultiview=!0,i||(i=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,i),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.RGBA8,e,t,2)),n._colorTextureArray=i,s||(s=r.createTexture(),r.bindTexture(r.TEXTURE_2D_ARRAY,s),r.texStorage3D(r.TEXTURE_2D_ARRAY,1,r.DEPTH24_STENCIL8,e,t,2)),n._depthStencilTextureArray=s,o.isReady=!0,n.setTextures(o),n._depthStencilTexture=o,n},Br.prototype.bindMultiviewFramebuffer=function(e){const t=e,i=this._gl,s=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw"Invalid multiview frame buffer";this.getCaps().oculusMultiview?(s.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,t.samples,0,2),s.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,t.samples,0,2)):(s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,0,2))},Br.prototype.bindSpaceWarpFramebuffer=function(e){const t=e,i=this._gl,s=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw new Error("Invalid Space Warp framebuffer");s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),s.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_ATTACHMENT,t._depthStencilTextureArray,0,0,2)},or.prototype._useMultiviewToSingleView=!1,or.prototype._multiviewTexture=null,or.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==e&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new Yl(this.getScene(),{width:e,height:t})):this._multiviewTexture=new Yl(this.getScene(),{width:e,height:t})};const $l=ks.prototype.createSceneUniformBuffer;ks.prototype._transformMatrixR=B.Zero(),ks.prototype._multiviewSceneUbo=null,ks.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=jl(this.getEngine(),"scene_multiview")},ks.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?jl(this.getEngine(),e):$l.bind(this)(e)},ks.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,U.Matrix[0]),Ms.GetRightPlaneToRef(U.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))},ks.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t{})),this.onApplyObservable.add((e=>{s._scene.activeCamera&&s._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",s._multiviewTexture)}))}}function ql(e,t){const i=t.vrCameraMetrics||Hl.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new nr(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new B,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new nr(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new B,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new Kl("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(J.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new Xl("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new Xl("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}De.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",((e,t)=>()=>new Ql(e,0,0,1,w.Zero(),t)));class Ql extends gl{constructor(e,t,i,s,r,n,o=!0,a=Hl.GetDefault()){super(e,t,i,s,r,n),this._setRigMode=e=>ql(this,e),a.compensateDistortion=o,this.setCameraRigMode(or.RIG_MODE_VR,{vrCameraMetrics:a}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}De.AddNodeConstructor("VRDeviceOrientationFreeCamera",((e,t)=>()=>new Zl(e,w.Zero(),t)));class Zl extends vl{constructor(e,t,i,s=!0,r=Hl.GetDefault()){super(e,t,i),this._setRigMode=e=>ql(this,e),r.compensateDistortion=s,this.setCameraRigMode(or.RIG_MODE_VR,{vrCameraMetrics:r})}getClassName(){return"VRDeviceOrientationFreeCamera"}}De.AddNodeConstructor("VRDeviceOrientationGamepadCamera",((e,t)=>()=>new Jl(e,w.Zero(),t)));class Jl extends Zl{constructor(e,t,i,s=!0,r=Hl.GetDefault()){super(e,t,i,s,r),this._setRigMode=e=>ql(this,e),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}class eh{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,s,r){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(2)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=s.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const r=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==r.frameId&&(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=s.clone()}}}class th{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,Br.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._TranslucencyIntensityTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get TranslucencyColorTextureEnabled(){return this._TranslucencyColorTextureEnabled}static set TranslucencyColorTextureEnabled(e){this._TranslucencyColorTextureEnabled!==e&&(this._TranslucencyColorTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,Br.MarkAllMaterialsAsDirty(1))}}th._DiffuseTextureEnabled=!0,th._DetailTextureEnabled=!0,th._DecalMapEnabled=!0,th._AmbientTextureEnabled=!0,th._OpacityTextureEnabled=!0,th._ReflectionTextureEnabled=!0,th._EmissiveTextureEnabled=!0,th._SpecularTextureEnabled=!0,th._BumpTextureEnabled=!0,th._LightmapTextureEnabled=!0,th._RefractionTextureEnabled=!0,th._ColorGradingTextureEnabled=!0,th._FresnelEnabled=!0,th._ClearCoatTextureEnabled=!0,th._ClearCoatBumpTextureEnabled=!0,th._ClearCoatTintTextureEnabled=!0,th._SheenTextureEnabled=!0,th._AnisotropicTextureEnabled=!0,th._ThicknessTextureEnabled=!0,th._RefractionIntensityTextureEnabled=!0,th._TranslucencyIntensityTextureEnabled=!0,th._TranslucencyColorTextureEnabled=!0,th._IridescenceTextureEnabled=!0;Ft.IncludesShadersStore.decalFragmentDeclaration="#ifdef DECAL\nuniform vec4 vDecalInfos;\n#endif\n";Ft.IncludesShadersStore.defaultFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;uniform vec4 refractionRightColor;\n#endif\n#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)\nuniform mat4 reflectionMatrix;\n#endif\n#ifndef REFLECTIONMAP_SKYBOX\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";Ft.IncludesShadersStore.sceneUboDeclaration="layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection;\n#ifdef MULTIVIEW\nmat4 viewProjectionR;\n#endif \nmat4 view;mat4 projection;vec4 vEyePosition;};\n";Ft.IncludesShadersStore.meshUboDeclaration="#ifdef WEBGL2\nuniform mat4 world;uniform float visibility;\n#else\nlayout(std140,column_major) uniform;uniform Mesh\n{mat4 world;float visibility;};\n#endif\n#define WORLD_UBO\n";Ft.IncludesShadersStore.defaultUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";Ft.IncludesShadersStore.prePassDeclaration="#ifdef PREPASS\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor;\n#ifdef PREPASS_DEPTH\nvarying highp vec3 vViewPos;\n#endif\n#ifdef PREPASS_VELOCITY\nvarying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition;\n#endif\n#endif\n";Ft.IncludesShadersStore.oitDeclaration="#ifdef ORDER_INDEPENDENT_TRANSPARENCY\n#extension GL_EXT_draw_buffers : require\nlayout(location=0) out vec2 depth; \nlayout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor;\n#define MAX_DEPTH 99999.0\nhighp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler;\n#endif\n";Ft.IncludesShadersStore.mainUVVaryingDeclaration="#ifdef MAINUV{X}\nvarying vec2 vMainUV{X};\n#endif\n";Ft.IncludesShadersStore.helperFunctions="const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; \nconst float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\n#define absEps(x) abs(x)+Epsilon\n#define maxEps(x) max(x,Epsilon)\n#define saturateEps(x) clamp(x,Epsilon,1.0)\nmat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nmat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;}\n#if USE_EXACT_SRGB_CONVERSIONS\nvec3 toLinearSpaceExact(vec3 color)\n{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));\n#else\nreturn\nvec3(\ncolor.r<=0.04045 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.04045 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.04045 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\nvec3 toGammaSpaceExact(vec3 color)\n{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055);\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nreturn mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));\n#else\nreturn\nvec3(\ncolor.r<=0.0031308 ? nearZeroSection.r : remainingSection.r,\ncolor.g<=0.0031308 ? nearZeroSection.g : remainingSection.g,\ncolor.b<=0.0031308 ? nearZeroSection.b : remainingSection.b);\n#endif\n}\n#endif\nfloat toLinearSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,LinearEncodePowerApprox);\n#endif\n}\nvec3 toLinearSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nvec4 toLinearSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfloat toGammaSpace(float color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nfloat nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection;\n#else\nreturn pow(color,GammaEncodePowerApprox);\n#endif\n}\nvec3 toGammaSpace(vec3 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nvec4 toGammaSpace(vec4 color)\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfloat square(float value)\n{return value*value;}\nvec3 square(vec3 value)\n{return value*value;}\nfloat pow5(float value) {float sq=value*value;return sq*sq*value;}\nfloat getLuminance(vec3 color)\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfloat getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfloat dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;}\nconst float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); }\nvec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;}\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";Ft.IncludesShadersStore.lightFragmentDeclaration="#ifdef LIGHT{X}\nuniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\n#else\nvec4 vLightSpecular{X}=vec4(0.);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};\n#else\nuniform highp sampler2DArray shadowTexture{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowTexture{X};\n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowTexture{X};\n#else\nuniform sampler2D shadowTexture{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};uniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};\n#endif\n#endif\n";Ft.IncludesShadersStore.lightUboDeclaration="#ifdef LIGHT{X}\nuniform Light{X}\n{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;vec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;vec2 depthValues;} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X};\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowTexture{X};\n#else\nuniform highp sampler2DArray shadowTexture{X};\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\n(\nvec3 ( 1.5,0.0,0.0 ),\nvec3 ( 0.0,1.5,0.0 ),\nvec3 ( 0.0,0.0,5.5 ),\nvec3 ( 1.5,0.0,5.5 ),\nvec3 ( 1.5,1.5,0.0 ),\nvec3 ( 1.0,1.0,1.0 ),\nvec3 ( 0.0,1.0,5.5 ),\nvec3 ( 0.5,3.5,0.75 )\n);vec3 shadowDebug{X};\n#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\n#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nfloat diff{X}=0.;\n#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowTexture{X}; \n#else\nvarying vec4 vPositionFromLight{X};varying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowTexture{X};\n#else\nuniform sampler2D shadowTexture{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif\n";Ft.IncludesShadersStore.lightsFragmentFunctions="struct lightingInfo\n{vec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.)\n{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\n#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}";Ft.IncludesShadersStore.shadowsFragmentFunctions="#ifdef SHADOWS\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}\n#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\n#define inline\nfloat computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nreturn depth>shadow ? darkness : 1.0;}\n#define inline\nfloat computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}\n#endif\n#define inline\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}}\n#define inline\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{float shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\n#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\n#ifdef IS_NDC_HALF_ZRANGE\n#define ZINCLIP clipSpace.z\n#else\n#define ZINCLIP uvDepth.z\n#endif\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define GREATEST_LESS_THAN_ONE 0.99999994\n#define DISABLE_UNIFORMITY_ANALYSIS\n#define inline\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\n#define inline\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\n#define inline\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.),\nvec3(0.)\n);const vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n#define inline\nfloat computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness)\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; ithis._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort(((e,t)=>e.priority-t.priority)),this._codeInjectionPoints={};const i={};i[sh._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const e of this._plugins)e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t0&&e.uniforms.push(...this._uniformList),this._samplerList.length>0&&e.samplers.push(...this._samplerList),this._uboList.length>0&&e.uniformBuffersNames.push(...this._uboList),e.customCode=this._injectCustomCode(e,e.customCode);break}case Xr.PrepareUniformBuffer:{const e=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const t of this._plugins){const i=t.getUniforms();if(i){if(i.ubo)for(const t of i.ubo){if(t.size&&t.type){const i=t.arraySize??0;e.ubo.addUniform(t.name,t.size,i),this._uboDeclaration+=`${t.type} ${t.name}${i>0?`[${i}]`:""};\n`}this._uniformList.push(t.name)}i.vertex&&(this._vertexDeclaration+=i.vertex+"\n"),i.fragment&&(this._fragmentDeclaration+=i.fragment+"\n")}t.getSamplers(this._samplerList),t.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,s)=>{t&&(s=t(i,s)),this._uboDeclaration&&(s=s.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(s=s.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(s=s.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const r=this._codeInjectionPoints?.[i];if(!r)return s;let n=null;for(let t in r){let r="";for(const s of this._activePlugins){let o=s.getCustomCode(i)?.[t];if(o){if(s.resolveIncludes){if(null===n){const t=ht.GLSL;n={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:Ft.GetShadersRepository(t),includesShadersStore:Ft.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}n.isFragment="fragment"===i,Ot(o,n,(e=>o=e))}r+=o+"\n"}}if(r.length>0)if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{const i=ih.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}e.indexOf("g")<0&&(e+="g");const i=s,n=new RegExp(t,e);let o=n.exec(i);for(;null!==o;){let e=r;for(let t=0;t{rh.length=0,nh=!1,Dn.OnEventObservable.remove(oh),oh=null}));const rh=[];let nh=!1,oh=null;class ah{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,s,r=!0,n=!1,o=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=o,e.pluginManager||(e.pluginManager=new sh(e),e.onDisposeObservable.add((()=>{e.pluginManager=void 0}))),this._pluginDefineNames=s,this._pluginManager=e.pluginManager,r&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,s){return!0}hardBindForSubMesh(e,t,i,s){}bindForSubMesh(e,t,i,s){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;const i=typeof this._pluginDefineNames[t];e[t]={type:"number"===i?"number":"string"===i?"string":"boolean"===i?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(){return{}}copyTo(e){Pe.Clone((()=>e),this)}serialize(){return Pe.Serialize(this)}parse(e,t,i){Pe.Parse((()=>this),e,t,i)}}ae([pe()],ah.prototype,"name",void 0),ae([pe()],ah.prototype,"priority",void 0),ae([pe()],ah.prototype,"resolveIncludes",void 0),ae([pe()],ah.prototype,"registerForExtraEvents",void 0),u("BABYLON.MaterialPluginBase",ah);class lh extends Do{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class hh extends ah{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new lh,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Dn.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&th.DetailTextureEnabled&&!this._texture.isReady())}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&th.DetailTextureEnabled&&this._isEnabled?(an(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||this._texture&&th.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),ln(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&th.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture?.dispose()}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}ae([fe("detailTexture"),de("_markAllSubMeshesAsTexturesDirty")],hh.prototype,"texture",void 0),ae([pe()],hh.prototype,"diffuseBlendLevel",void 0),ae([pe()],hh.prototype,"roughnessBlendLevel",void 0),ae([pe()],hh.prototype,"bumpLevel",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],hh.prototype,"normalBlendMethod",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],hh.prototype,"isEnabled",void 0);const ch={effect:null,subMesh:null};class uh extends Do{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){const t=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];for(const i of t)this[i]=i===e}}class dh extends Io{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new Y(0,0,0),this.diffuseColor=new Y(1,1,1),this.specularColor=new Y(1,1,1),this.emissiveColor=new Y(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._renderTargets=new Mi(16),this._worldViewProjectionMatrix=B.Zero(),this._globalAmbientColor=new Y(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new hh(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new eh,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),dh.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),dh.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return!!(dh.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||!!(dh.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Dn.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Dn.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Xr.GetDefineNames,this._eventInfo),t.materialDefines=new uh(this._eventInfo.defineNames));const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();n._needNormals=vn(r,e,n,!0,this._maxSimultaneousLights,this._disableLighting),yn(r,n);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Rn(r,n,this.canRenderToMRT&&!a),An(r,n,a),n._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n._needUVs=!1;for(let e=1;e<=6;++e)n["MAINUV"+e]=!1;if(r.texturesEnabled){if(n.DIFFUSEDIRECTUV=0,n.BUMPDIRECTUV=0,n.AMBIENTDIRECTUV=0,n.OPACITYDIRECTUV=0,n.EMISSIVEDIRECTUV=0,n.SPECULARDIRECTUV=0,n.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&dh.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;an(this._diffuseTexture,n,"DIFFUSE")}else n.DIFFUSE=!1;if(this._ambientTexture&&dh.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;an(this._ambientTexture,n,"AMBIENT")}else n.AMBIENT=!1;if(this._opacityTexture&&dh.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;an(this._opacityTexture,n,"OPACITY"),n.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else n.OPACITY=!1;if(this._reflectionTexture&&dh.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(n._needNormals=!0,n.REFLECTION=!0,n.ROUGHNESS=this._roughness>0,n.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,n.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===Zn.INVCUBIC_MODE,n.REFLECTIONMAP_3D=this._reflectionTexture.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,n.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case Zn.EXPLICIT_MODE:n.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case Zn.PLANAR_MODE:n.setReflectionMode("REFLECTIONMAP_PLANAR");break;case Zn.PROJECTION_MODE:n.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case Zn.SKYBOX_MODE:n.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case Zn.SPHERICAL_MODE:n.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case Zn.EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case Zn.FIXED_EQUIRECTANGULAR_MODE:n.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case Zn.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case Zn.CUBIC_MODE:case Zn.INVCUBIC_MODE:default:n.setReflectionMode("REFLECTIONMAP_CUBIC")}n.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else n.REFLECTION=!1,n.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&dh.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;an(this._emissiveTexture,n,"EMISSIVE")}else n.EMISSIVE=!1;if(this._lightmapTexture&&dh.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;an(this._lightmapTexture,n,"LIGHTMAP"),n.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,n.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else n.LIGHTMAP=!1;if(this._specularTexture&&dh.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;an(this._specularTexture,n,"SPECULAR"),n.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else n.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&dh.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;an(this._bumpTexture,n,"BUMP"),n.PARALLAX=this._useParallax,n.PARALLAX_RHS=r.useRightHandedSystem,n.PARALLAXOCCLUSION=this._useParallaxOcclusion,n.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else n.BUMP=!1,n.PARALLAX=!1,n.PARALLAX_RHS=!1,n.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&dh.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;n._needUVs=!0,n.REFRACTION=!0,n.REFRACTIONMAP_3D=this._refractionTexture.isCube,n.RGBDREFRACTION=this._refractionTexture.isRGBD,n.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else n.REFRACTION=!1;n.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else n.DIFFUSE=!1,n.AMBIENT=!1,n.OPACITY=!1,n.REFLECTION=!1,n.EMISSIVE=!1,n.LIGHTMAP=!1,n.BUMP=!1,n.REFRACTION=!1;n.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),n.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,n.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,n.SPECULAROVERALPHA=this._useSpecularOverAlpha,n.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,n.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,n.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=n,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n),n.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,n.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}n._areFresnelDirty&&(dh.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(n.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,n.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,n.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,n.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,n.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,n.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,n._needNormals=!0,n.FRESNEL=!0):n.FRESNEL=!1),gn(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,n,this._applyDecalMapAfterDetailMap),Tn(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=n,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),Cn(e,n,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let l=!1;if(n.isDirty){const i=n._areLightsDisposed;n.markAsProcessed();const s=new Yo;n.REFLECTION&&s.addFallback(0,"REFLECTION"),n.SPECULAR&&s.addFallback(0,"SPECULAR"),n.BUMP&&s.addFallback(0,"BUMP"),n.PARALLAX&&s.addFallback(1,"PARALLAX"),n.PARALLAX_RHS&&s.addFallback(1,"PARALLAX_RHS"),n.PARALLAXOCCLUSION&&s.addFallback(0,"PARALLAXOCCLUSION"),n.SPECULAROVERALPHA&&s.addFallback(0,"SPECULAROVERALPHA"),n.FOG&&s.addFallback(1,"FOG"),n.POINTSIZE&&s.addFallback(0,"POINTSIZE"),n.LOGARITHMICDEPTH&&s.addFallback(0,"LOGARITHMICDEPTH"),_n(n,s,this._maxSimultaneousLights),n.SPECULARTERM&&s.addFallback(0,"SPECULARTERM"),n.DIFFUSEFRESNEL&&s.addFallback(1,"DIFFUSEFRESNEL"),n.OPACITYFRESNEL&&s.addFallback(2,"OPACITYFRESNEL"),n.REFLECTIONFRESNEL&&s.addFallback(3,"REFLECTIONFRESNEL"),n.EMISSIVEFRESNEL&&s.addFallback(4,"EMISSIVEFRESNEL"),n.FRESNEL&&s.addFallback(4,"FRESNEL"),n.MULTIVIEW&&s.addFallback(0,"MULTIVIEW");const a=[Ki.PositionKind];n.NORMAL&&a.push(Ki.NormalKind),n.TANGENT&&a.push(Ki.TangentKind);for(let e=1;e<=6;++e)n["UV"+e]&&a.push(`uv${1===e?"":e}`);n.VERTEXCOLOR&&a.push(Ki.ColorKind),pn(a,e,n,s),fn(a,n),sn(a,e,n),hn(a,0,n);let h="default";const c=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],u=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],d=["Material","Scene","Mesh"],p={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:n.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=s,this._eventInfo.fallbackRank=0,this._eventInfo.defines=n,this._eventInfo.uniforms=c,this._eventInfo.attributes=a,this._eventInfo.samplers=u,this._eventInfo.uniformBuffersNames=d,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=p,this._callbackPluginEventGeneric(Xr.PrepareEffect,this._eventInfo),eh.AddUniforms(c),eh.AddSamplers(u),Bi&&(Bi.PrepareUniforms(c,n),Bi.PrepareSamplers(u,n)),Mn({uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:n,maxSimultaneousLights:this._maxSimultaneousLights}),jr(c);const f={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,c,d,u,n,a,f));const _=n.toString(),m=t.effect;let g=r.getEngine().createEffect(h,{attributes:a,uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:_,fallbacks:s,onCompiled:this.onCompiled,onError:this.onError,indexParameters:p,processFinalCode:f.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:n.PREPASS},o);if(this._eventInfo.customCode=void 0,g)if(this._onEffectCreatedObservable&&(ch.effect=g,ch.subMesh=t,this._onEffectCreatedObservable.notifyObservers(ch)),this.allowShaderHotSwapping&&m&&!g.isReady()){if(g=m,n.markAsUnprocessed(),l=this.isFrozen,i)return n._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(g,n,this._materialContext)}return!(!t.effect||!t.effect.isReady()||(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!l,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(s,n,i,t.visibility);cn(t,n);const a=this._uniformBuffer;if(o){if(this.bindViewProjection(n),!a.useUbo||!this.isFrozen||!a.isSync||i._drawWrapper._forceRebindOnNextCall){if(dh.FresnelEnabled&&r.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(a.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),a.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&a.updateColor4("opacityParts",new Y(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(a.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),a.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(a.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),a.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(a.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),a.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&dh.DiffuseTextureEnabled&&(a.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),ln(this._diffuseTexture,a,"diffuse")),this._ambientTexture&&dh.AmbientTextureEnabled&&(a.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),ln(this._ambientTexture,a,"ambient")),this._opacityTexture&&dh.OpacityTextureEnabled&&(a.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),ln(this._opacityTexture,a,"opacity")),this._hasAlphaChannel()&&a.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&dh.ReflectionTextureEnabled&&(a.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),a.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const e=this._reflectionTexture;a.updateVector3("vReflectionPosition",e.boundingBoxPosition),a.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&dh.EmissiveTextureEnabled&&(a.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),ln(this._emissiveTexture,a,"emissive")),this._lightmapTexture&&dh.LightmapTextureEnabled&&(a.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),ln(this._lightmapTexture,a,"lightmap")),this._specularTexture&&dh.SpecularTextureEnabled&&(a.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),ln(this._specularTexture,a,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&dh.BumpTextureEnabled&&(a.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),ln(this._bumpTexture,a,"bump"),s._mirroredCameraPosition?a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):a.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&dh.RefractionTextureEnabled){let e=1;if(this._refractionTexture.isCube||(a.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),a.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const e=this._refractionTexture;a.updateVector3("vRefractionPosition",e.boundingBoxPosition),a.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&a.updateFloat("pointSize",this.pointSize),r.SPECULARTERM&&a.updateColor4("vSpecularColor",this.specularColor,this.specularPower),a.updateColor3("vEmissiveColor",dh.EmissiveTextureEnabled?this.emissiveColor:Y.BlackReadOnly),a.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),a.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&dh.DiffuseTextureEnabled&&n.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&dh.AmbientTextureEnabled&&n.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&dh.OpacityTextureEnabled&&n.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&dh.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?n.setTexture("reflectionCubeSampler",this._reflectionTexture):n.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&dh.EmissiveTextureEnabled&&n.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&dh.LightmapTextureEnabled&&n.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&dh.SpecularTextureEnabled&&n.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&dh.BumpTextureEnabled&&n.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&dh.RefractionTextureEnabled&&(this._refractionTexture.isCube?n.setTexture("refractionCubeSampler",this._refractionTexture):n.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Kr(n,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!o&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&dn(s,t,n,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==ks.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),en(s,t,n),r.NUM_MORPH_INFLUENCERS&&nn(t,n),r.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,r.INSTANCES),this.useLogarithmicDepth&&Jr(r,n,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),a.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e}dispose(e,t){t&&(this._diffuseTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._specularTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._refractionTexture?.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const s=Pe.Clone((()=>new dh(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return s.name=e,s.id=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}static Parse(e,t,i){const s=Pe.Parse((()=>new dh(e.name,t)),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),Dn._ParsePlugins(e,s,t,i),s}static get DiffuseTextureEnabled(){return th.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){th.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return th.DetailTextureEnabled}static set DetailTextureEnabled(e){th.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return th.AmbientTextureEnabled}static set AmbientTextureEnabled(e){th.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return th.OpacityTextureEnabled}static set OpacityTextureEnabled(e){th.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return th.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){th.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return th.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){th.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return th.SpecularTextureEnabled}static set SpecularTextureEnabled(e){th.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return th.BumpTextureEnabled}static set BumpTextureEnabled(e){th.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return th.LightmapTextureEnabled}static set LightmapTextureEnabled(e){th.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return th.RefractionTextureEnabled}static set RefractionTextureEnabled(e){th.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return th.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){th.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return th.FresnelEnabled}static set FresnelEnabled(e){th.FresnelEnabled=e}}ae([fe("diffuseTexture")],dh.prototype,"_diffuseTexture",void 0),ae([de("_markAllSubMeshesAsTexturesAndMiscDirty")],dh.prototype,"diffuseTexture",void 0),ae([fe("ambientTexture")],dh.prototype,"_ambientTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"ambientTexture",void 0),ae([fe("opacityTexture")],dh.prototype,"_opacityTexture",void 0),ae([de("_markAllSubMeshesAsTexturesAndMiscDirty")],dh.prototype,"opacityTexture",void 0),ae([fe("reflectionTexture")],dh.prototype,"_reflectionTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"reflectionTexture",void 0),ae([fe("emissiveTexture")],dh.prototype,"_emissiveTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"emissiveTexture",void 0),ae([fe("specularTexture")],dh.prototype,"_specularTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"specularTexture",void 0),ae([fe("bumpTexture")],dh.prototype,"_bumpTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"bumpTexture",void 0),ae([fe("lightmapTexture")],dh.prototype,"_lightmapTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"lightmapTexture",void 0),ae([fe("refractionTexture")],dh.prototype,"_refractionTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"refractionTexture",void 0),ae([_e("ambient")],dh.prototype,"ambientColor",void 0),ae([_e("diffuse")],dh.prototype,"diffuseColor",void 0),ae([_e("specular")],dh.prototype,"specularColor",void 0),ae([_e("emissive")],dh.prototype,"emissiveColor",void 0),ae([pe()],dh.prototype,"specularPower",void 0),ae([pe("useAlphaFromDiffuseTexture")],dh.prototype,"_useAlphaFromDiffuseTexture",void 0),ae([de("_markAllSubMeshesAsTexturesAndMiscDirty")],dh.prototype,"useAlphaFromDiffuseTexture",void 0),ae([pe("useEmissiveAsIllumination")],dh.prototype,"_useEmissiveAsIllumination",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useEmissiveAsIllumination",void 0),ae([pe("linkEmissiveWithDiffuse")],dh.prototype,"_linkEmissiveWithDiffuse",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"linkEmissiveWithDiffuse",void 0),ae([pe("useSpecularOverAlpha")],dh.prototype,"_useSpecularOverAlpha",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useSpecularOverAlpha",void 0),ae([pe("useReflectionOverAlpha")],dh.prototype,"_useReflectionOverAlpha",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useReflectionOverAlpha",void 0),ae([pe("disableLighting")],dh.prototype,"_disableLighting",void 0),ae([de("_markAllSubMeshesAsLightsDirty")],dh.prototype,"disableLighting",void 0),ae([pe("useObjectSpaceNormalMap")],dh.prototype,"_useObjectSpaceNormalMap",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useObjectSpaceNormalMap",void 0),ae([pe("useParallax")],dh.prototype,"_useParallax",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useParallax",void 0),ae([pe("useParallaxOcclusion")],dh.prototype,"_useParallaxOcclusion",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useParallaxOcclusion",void 0),ae([pe()],dh.prototype,"parallaxScaleBias",void 0),ae([pe("roughness")],dh.prototype,"_roughness",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"roughness",void 0),ae([pe()],dh.prototype,"indexOfRefraction",void 0),ae([pe()],dh.prototype,"invertRefractionY",void 0),ae([pe()],dh.prototype,"alphaCutOff",void 0),ae([pe("useLightmapAsShadowmap")],dh.prototype,"_useLightmapAsShadowmap",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useLightmapAsShadowmap",void 0),ae([me("diffuseFresnelParameters")],dh.prototype,"_diffuseFresnelParameters",void 0),ae([de("_markAllSubMeshesAsFresnelDirty")],dh.prototype,"diffuseFresnelParameters",void 0),ae([me("opacityFresnelParameters")],dh.prototype,"_opacityFresnelParameters",void 0),ae([de("_markAllSubMeshesAsFresnelAndMiscDirty")],dh.prototype,"opacityFresnelParameters",void 0),ae([me("reflectionFresnelParameters")],dh.prototype,"_reflectionFresnelParameters",void 0),ae([de("_markAllSubMeshesAsFresnelDirty")],dh.prototype,"reflectionFresnelParameters",void 0),ae([me("refractionFresnelParameters")],dh.prototype,"_refractionFresnelParameters",void 0),ae([de("_markAllSubMeshesAsFresnelDirty")],dh.prototype,"refractionFresnelParameters",void 0),ae([me("emissiveFresnelParameters")],dh.prototype,"_emissiveFresnelParameters",void 0),ae([de("_markAllSubMeshesAsFresnelDirty")],dh.prototype,"emissiveFresnelParameters",void 0),ae([pe("useReflectionFresnelFromSpecular")],dh.prototype,"_useReflectionFresnelFromSpecular",void 0),ae([de("_markAllSubMeshesAsFresnelDirty")],dh.prototype,"useReflectionFresnelFromSpecular",void 0),ae([pe("useGlossinessFromSpecularMapAlpha")],dh.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"useGlossinessFromSpecularMapAlpha",void 0),ae([pe("maxSimultaneousLights")],dh.prototype,"_maxSimultaneousLights",void 0),ae([de("_markAllSubMeshesAsLightsDirty")],dh.prototype,"maxSimultaneousLights",void 0),ae([pe("invertNormalMapX")],dh.prototype,"_invertNormalMapX",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"invertNormalMapX",void 0),ae([pe("invertNormalMapY")],dh.prototype,"_invertNormalMapY",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"invertNormalMapY",void 0),ae([pe("twoSidedLighting")],dh.prototype,"_twoSidedLighting",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],dh.prototype,"twoSidedLighting",void 0),ae([pe("applyDecalMapAfterDetailMap")],dh.prototype,"_applyDecalMapAfterDetailMap",void 0),ae([de("_markAllSubMeshesAsMiscDirty")],dh.prototype,"applyDecalMapAfterDetailMap",void 0),u("BABYLON.StandardMaterial",dh),ks.DefaultMaterialFactory=e=>new dh("default material",e),Yi.prototype.createDynamicTexture=function(e,t,i,s){const r=new ti(this,ei.Dynamic);return r.baseWidth=e,r.baseHeight=t,i&&(e=this.needPOTTextures?Ri(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?Ri(t,this._caps.maxTextureSize):t),r.width=e,r.height=t,r.isReady=!1,r.generateMipMaps=i,r.samplingMode=s,this.updateTextureSamplingMode(s,r),this._internalTexturesCache.push(r),r},Yi.prototype.updateDynamicTexture=function(e,t,i,s=!1,r,n=!1,o=!1){if(!e)return;const a=this._gl,l=a.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,n);this._unpackFlipY(void 0===i?e.invertY:i),s&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(r||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,u);a.texImage2D(l,0,d,u,c,t),e.generateMipMaps&&a.generateMipmap(l),h||this._bindTextureDirectly(l,null),s&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),r&&(e.format=r),e._dynamicTextureSource=t,e._premulAlpha=s,e.invertY=i||!1,e.isReady=!0};class ph extends Zn{constructor(e,t,i=null,s=!1,r=3,n=5,o){super(null,i,!s,o,r,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=Zn.CLAMP_ADDRESSMODE,this.wrapV=Zn.CLAMP_ADDRESSMODE,this._generateMipMaps=s;const a=this._getEngine();if(!a)return;t.getContext?(this._canvas=t,this._ownCanvas=!1,this._texture=a.createDynamicTexture(t.width,t.height,s,r)):(this._canvas=a.createCanvas(1,1),this._ownCanvas=!0,t.width||0===t.width?this._texture=a.createDynamicTexture(t.width,t.height,s,r):this._texture=a.createDynamicTexture(t,t,s,r));const l=this.getSize();this._canvas.width!==l.width&&(this._canvas.width=l.width),this._canvas.height!==l.height&&(this._canvas.height=l.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){const t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){const i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){const t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0,void 0,i)}drawText(e,t,i,s,r,n,o,a=!0){const l=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,l.width,l.height)),this._context.font=s,null==t){const i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){const e=parseInt(s.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=r||"",this._context.fillText(e,t,i),a&&this.update(o)}dispose(){super.dispose(),this._ownCanvas&&this._canvas?.remove?.(),this._canvas=null,this._context=null}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new ph(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){const e=this.getScene();e&&!e.isReady()&&J.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return ph._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return void 0!==e.toDataURL}_rebuild(){this.update()}}class fh{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){if(this.isFixedFoveationSupported){const t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}}createRenderTargetTextureProvider(e){return this._rttWrapper=this._createRenderTargetTextureProvider(e),this._rttWrapper}dispose(){this._rttWrapper&&(this._rttWrapper.dispose(),this._rttWrapper=null)}constructor(e,t,i,s,r){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this._createRenderTargetTextureProvider=r,this._rttWrapper=null}}class _h{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new ti(this._engine,ei.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new Hi(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,s,r,n){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},a=n?new Yl(this._scene,o):new da("XR renderTargetTexture",o,this._scene),l=a.renderTarget;if(l._samples=a.samples,!i&&s||(l._framebuffer=i),s)if(n)l._colorTextureArray=s;else{const e=this._createInternalTexture(o,s);l.setTexture(e,0),a._texture=e}return r&&(n?l._depthStencilTextureArray=r:l._depthStencilTexture=this._createInternalTexture(o,r)),a.disableRescaling(),this._renderTargetTextures.push(a),a}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.length=0}}class mh extends fh{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new gh(e.scene,this))),this.layer=e}}class gh extends _h{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){const i=this._layer.getViewport(t);if(!i)return!1;const s=this._framebufferDimensions.framebufferWidth,r=this._framebufferDimensions.framebufferHeight;return e.x=i.x/s,e.y=i.y/r,e.width=i.width/s,e.height=i.height/r,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,s=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&s===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,s),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=s),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class vh{static GetDefaults(e){const t=new vh;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class xh{constructor(e,t=vh.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new g,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{const e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add((()=>{this._addCanvas()})),e.onXRSessionEnded.add((()=>{this._removeCanvas()})),this._makeCanvasCompatibleAsync()}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}_makeCanvasCompatibleAsync(){this._canvasCompatiblePromise=new Promise((e=>{this.canvasContext&&this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then((()=>{e()})):e()}))}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new mh(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this._canvasCompatiblePromise.then((()=>{}),(()=>{Ii.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")})).then((()=>t()))}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce((()=>{this._setCanvasSize(!0)}))}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class Th extends fh{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new Sh(e,this))),this.layer=e}}class Sh extends _h{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}}class Eh{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}}class bh{get worldScalingFactor(){return this._worldScalingFactor}set worldScalingFactor(e){const t=this._worldScalingFactor;this._worldScalingFactor=e,this.onWorldScaleFactorChangedObservable.notifyObservers({previousScaleFactor:t,newScaleFactor:e})}constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new g,this.onXRReferenceSpaceChanged=new g,this.onXRSessionEnded=new g,this.onXRSessionInit=new g,this.onXRReferenceSpaceInitialized=new g,this.onXRReady=new g,this.inXRFrameLoop=!1,this.inXRSession=!1,this._worldScalingFactor=1,this.onWorldScaleFactorChangedObservable=new g(void 0,!0),this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),this.onWorldScaleFactorChangedObservable.clear(),this._engine?.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}async exitXRAsync(){if(this.session&&this.inXRSession){this.inXRSession=!1;try{return await this.session.end()}catch{J.Warn("Could not end XR session.")}}return Promise.resolve()}trySetViewportForView(e,t){return this._baseLayerRTTProvider?.trySetViewportForView(e,t)||!1}getRenderTargetTextureForEye(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForEye(e)||null}getRenderTargetTextureForView(e){return this._baseLayerRTTProvider?.getRenderTargetTextureForView(e)||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new Eh(this):((e=e||vh.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new xh(this,e))}initializeAsync(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then((t=>(this.session=t,this._sessionMode=e,this.inXRSession=!0,this.onXRSessionInit.notifyObservers(t),this.session.addEventListener("end",(()=>{this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&this._baseLayerRTTProvider?.dispose(),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null}),{once:!0}),this.session)))}isSessionSupportedAsync(e){return bh.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:e=>this.session.requestAnimationFrame(e),renderFunction:(e,t)=>{if(this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t)){this.inXRFrameLoop=!0;const e=this._baseLayerRTTProvider?.getFramebufferDimensions()||null;this._engine.framebufferDimensionsObject!==e&&(this._engine.framebufferDimensionsObject=e),this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1}}},this._engine.framebufferDimensionsObject=this._baseLayerRTTProvider?.getFramebufferDimensions()||null,this.onXRFrameObservable.addOnce((()=>{this.onXRReady.notifyObservers(this)})),"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then((e=>e),(e=>(J.Error("XR.requestReferenceSpace failed for the following reason: "),J.Error(e),J.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then((e=>{const t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)}),(e=>{throw J.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))))).then((e=>this.session.requestReferenceSpace("viewer").then((t=>(this.viewerReferenceSpace=t,e))))).then((e=>(this.referenceSpace=this.baseReferenceSpace=e,this.onXRReferenceSpaceInitialized.notifyObservers(e),this.referenceSpace)))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){this.isNative&&this._baseLayerRTTProvider?.dispose(),this._baseLayerWrapper=e,this._baseLayerRTTProvider=this._baseLayerWrapper?.createRenderTargetTextureProvider(this)||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new Th(e.baseLayer):new mh(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);const t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then((e=>{const t=void 0===e||e;return Promise.resolve(t)})).catch((e=>(J.Warn(e),Promise.resolve(!1)))):Promise.resolve(!1)}get isNative(){return this._xrNavigator.xr.native??!1}get currentFrameRate(){return this.session?.frameRate}get supportedFrameRates(){return this.session?.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():!this.inXRSession&&t||this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){return this._baseLayerWrapper?.isFixedFoveationSupported||!1}get fixedFoveation(){return this._baseLayerWrapper?.fixedFoveation||null}set fixedFoveation(e){const t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)}get enabledFeatures(){return this.session?.enabledFeatures??null}}var Ch,yh;!function(e){e[e.ENTERING_XR=0]="ENTERING_XR",e[e.EXITING_XR=1]="EXITING_XR",e[e.IN_XR=2]="IN_XR",e[e.NOT_IN_XR=3]="NOT_IN_XR"}(Ch||(Ch={})),function(e){e[e.NOT_TRACKING=0]="NOT_TRACKING",e[e.TRACKING_LOST=1]="TRACKING_LOST",e[e.TRACKING=2]="TRACKING"}(yh||(yh={})),Un._GroundMeshParser=(e,t)=>Ah.Parse(e,t);class Ah extends Un{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const i=this.getWorldMatrix(),s=U.Matrix[5];i.invertToRef(s);const r=U.Vector3[8];if(w.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const n=this._getFacetAt(e,t),o=-(n.x*e+n.z*t+n.w)/n.y;return w.TransformCoordinatesFromFloatsToRef(0,o,0,i,r),r.y}getNormalAtCoordinates(e,t){const i=new w(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const s=this.getWorldMatrix(),r=U.Matrix[5];s.invertToRef(r);const n=U.Vector3[8];if(w.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const o=this._getFacetAt(e,t);return w.TransformNormalFromFloatsToRef(o.x,o.y,o.z,s,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),s=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[s*this._subdivisionsX+i];let n;return n=te.maxHeight){h=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(n=0;n<=e.subdivisions;n++)for(o=0;o<=e.subdivisions;o++){const t=new w(o*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-n)*e.height/e.subdivisions-e.height/2),c=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let u=e.buffer[c]/255,d=e.buffer[c+1]/255,p=e.buffer[c+2]/255;const f=e.buffer[c+3]/255;h&&(u=1-u,d=1-d,p=1-p);const _=u*a.r+d*a.g+p*a.b;t.y=f>=l?e.minHeight+(e.maxHeight-e.minHeight)*_:e.minHeight-T,e.heightBuffer&&(e.heightBuffer[n*(e.subdivisions+1)+o]=t.y),i.push(t.x,t.y,t.z),s.push(0,0,0),r.push(o/e.subdivisions,1-n/e.subdivisions)}for(n=0;n=e.minHeight,c=i[3*r+1]>=e.minHeight,u=i[3*a+1]>=e.minHeight;h&&c&&u&&(t.push(s),t.push(r),t.push(a)),i[3*l+1]>=e.minHeight&&h&&u&&(t.push(l),t.push(s),t.push(a))}Tr.ComputeNormals(i,t,s);const c=new Tr;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function Mh(e,t={},i){const s=new Ah(e,i);return s._setReady(!1),s._subdivisionsX=t.subdivisionsX||t.subdivisions||1,s._subdivisionsY=t.subdivisionsY||t.subdivisions||1,s._width=t.width||1,s._height=t.height||1,s._maxX=s._width/2,s._maxZ=s._height/2,s._minX=-s._maxX,s._minZ=-s._maxZ,Rh(t).applyToMesh(s,t.updatable),s._setReady(!0),s}function Dh(e){const t=[],i=[],s=[],r=[],n=e.diameter||1,o=e.thickness||.5,a=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE,h=a+1;for(let e=0;e<=a;e++){const l=e/a,c=e*Math.PI*2/a-Math.PI/2,u=B.Translation(n/2,0,0).multiply(B.RotationY(c));for(let n=0;n<=a;n++){const c=1-n/a,d=n*Math.PI*2/a+Math.PI,p=Math.cos(d),f=Math.sin(d);let _=new w(p,f,0),m=_.scale(o/2);const g=new N(l,c);m=w.TransformCoordinates(m,u),_=w.TransformNormal(_,u),i.push(m.x,m.y,m.z),s.push(_.x,_.y,_.z),r.push(g.x,Er.UseOpenGLOrientationForUV?1-g.y:g.y);const v=(e+1)%h,x=(n+1)%h;t.push(e*h+n),t.push(e*h+x),t.push(v*h+n),t.push(e*h+x),t.push(v*h+x),t.push(v*h+n)}}Tr._ComputeSides(l,i,t,s,r,e.frontUVs,e.backUVs);const c=new Tr;return c.indices=t,c.positions=i,c.normals=s,c.uvs=r,c}function Oh(e,t={},i){const s=new Un(e,i);return t.sideOrientation=Un._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,Dh(t).applyToMesh(s,t.updatable),s}Tr.CreateGround=Rh,Tr.CreateTiledGround=Ih,Tr.CreateGroundFromHeightMap=Ph,Un.CreateGround=(e,t,i,s,r,n)=>Mh(e,{width:t,height:i,subdivisions:s,updatable:n},r),Un.CreateTiledGround=(e,t,i,s,r,n,o,a,l)=>function(e,t,i=null){const s=new Un(e,i);return Ih(t).applyToMesh(s,t.updatable),s}(e,{xmin:t,zmin:i,xmax:s,zmax:r,subdivisions:n,precision:o,updatable:l},a),Un.CreateGroundFromHeightMap=(e,t,i,s,r,n,o,a,l,h,c)=>function(e,t,i={},s=null){const r=i.width||10,n=i.height||10,o=i.subdivisions||1,a=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new Y(.3,.59,.11),c=i.alphaFilter||0,u=i.updatable,d=i.onReady;s=s||y.LastCreatedScene;const p=new Ah(e,s);let f;p._subdivisionsX=o,p._subdivisionsY=o,p._width=r,p._height=n,p._maxX=p._width/2,p._maxZ=p._height/2,p._minX=-p._maxX,p._minZ=-p._maxZ,p._setReady(!1),i.passHeightBufferInCallback&&(f=new Float32Array((o+1)*(o+1)));const _=(e,t,i)=>{Ph({width:r,height:n,subdivisions:o,minHeight:a,maxHeight:l,colorFilter:h,buffer:e,bufferWidth:t,bufferHeight:i,alphaFilter:c,heightBuffer:f}).applyToMesh(p,u),d&&d(p,f),p._setReady(!0)};if("string"==typeof t){const e=e=>{const t=e.width,i=e.height;if(s.isDisposed)return;const r=s?.getEngine().resizeImageBitmap(e,t,i);_(r,t,i)};Ii.LoadImage(t,e,i.onError?i.onError:()=>{},s.offlineProvider)}else _(t.data,t.width,t.height);return p}(e,t,{width:i,height:s,subdivisions:r,minHeight:n,maxHeight:o,updatable:l,onReady:h,alphaFilter:c},a),Tr.CreateTorus=Dh,Un.CreateTorus=(e,t,i,s,r,n,o)=>Oh(e,{diameter:t,thickness:i,tessellation:s,sideOrientation:o,updatable:n},r);class Nh{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=Nh._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=Oh("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const t=new dh("targetMat",e);t.specularColor=Y.Black(),t.emissiveColor=new Y(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new ao(w.Zero(),new w(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}}Nh._IdCounter=0;class wh extends Nh{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new ao(w.Zero(),w.Forward())}}class Fh{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._scene.activeCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated}constructor(e,t={}){if(this.webVROptions=t,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new g,this.onAfterEnteringVRObservable=new g,this.onExitingVRObservable=new g,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=Fh.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new w(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new w(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new Y(.2,.2,1),this._pickedGazeColor=new Y(0,0,1),this.onNewMeshSelected=new g,this.onNewMeshPicked=new g,this.onBeforeCameraTeleport=new g,this.onAfterCameraTeleport=new g,this.onSelectedMeshUnselected=new g,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock||(this._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=e=>{e.type!==Ya.POSE_ENABLED&&(e.leftStick&&e.onleftstickchanged((e=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))})),e.rightStick&&e.onrightstickchanged((e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)})),e.type===Ya.XBOX&&(e.onbuttondown((e=>{this._interactionsEnabled&&e===ka.A&&this._cameraGazer._selectionPointerDown()})),e.onbuttonup((e=>{this._interactionsEnabled&&e===ka.A&&this._cameraGazer._selectionPointerUp()}))))},this._workingVector=w.Zero(),this._workingQuaternion=L.Identity(),this._workingMatrix=B.Identity(),J.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement(),"getVRDisplays"in navigator||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new w(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new vl("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof fl&&this._scene.activeCamera.rotation)){const e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(L.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?bh.IsSessionSupportedAsync("immersive-vr").then((i=>{i?(J.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then((t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new wh((()=>this.xr.baseExperience.camera),e),this.xr.baseExperience.onStateChangedObservable.add((e=>{switch(e){case Ch.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case Ch.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case Ch.IN_XR:this._hasEnteredVR=!0;break;case Ch.NOT_IN_XR:this._hasEnteredVR=!1}}))}))):this._completeVRInit(e,t)})):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new Zl("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new wh((()=>this.currentVRCamera),e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let e=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";e+=".babylonVRicon.vrdisplaypresenting { display: none; }";const t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",(()=>{this.isInVRMode||this.enterVR()}));const i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add((()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())}),ss.POINTERDOUBLETAP,!1),e.onDisposeObservable.add((()=>{this.dispose()})),this._updateButtonVisibility(),this._circleEase=new qs,this._circleEase.setEasingMode(Ks.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add((t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===ss.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===ss.POINTERUP&&this._cameraGazer._selectionPointerUp())})),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===Ch.IN_XR||this._fullscreenVRpresenting}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){const e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))}enterVR(){if(this.xr)this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);else{if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){J.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=L.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce((()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})}))),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}}exitVR(){if(this.xr)this.xr.baseExperience.exitXRAsync();else if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){J.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this.xr)return void(this.xr.baseExperience.state===Ch.IN_XR&&this.xr.pointerSelection.attach());this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>!!(this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}_isTeleportationFloor(e){for(let t=0;t-1||this._floorMeshesCollection.push(e))}removeFloorMesh(e){if(!this._floorMeshesCollection)return;const t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const t=e.floorMeshes||[];if(!t.length){const i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr)return t.forEach((e=>{this.xr.teleportation.addFloorMesh(e)})),void(this.xr.teleportation.attached||this.xr.teleportation.attach());if(!this.xrTestDone){const t=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(t),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};return void this._scene.registerBeforeRender(t)}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction);const t=new Bi;t.vignetteColor=new j(0,0,0,0),t.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}}_checkTeleportWithRay(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;const e=L.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,L.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),w.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const s=new ao(i,this._workingVector),r=this._scene.pickWithRay(s,this._raySelectionPredicate);r&&r.pickedPoint&&r.pickedMesh&&this._isTeleportationFloor(r.pickedMesh)&&r.distance<5&&this.teleportCamera(r.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_createTeleportationCircles(){this._teleportationTarget=Mh("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=new ph("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;const t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();const i=new dh("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;const s=Oh("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);s.isPickable=!1,s.parent=this._teleportationTarget;const r=new Ge("animationInnerCircle","position.y",30,Ge.ANIMATIONTYPE_FLOAT,Ge.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),r.setKeys(n);const o=new Zs;o.setEasingMode(Ks.EASINGMODE_EASEINOUT),r.setEasingFunction(o),s.animations=[],s.animations.push(r),this._scene.beginAnimation(s,0,60,!0),this._hideTeleportationTarget()}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof _l))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=L.FromRotationMatrix(B.RotationY(Math.PI/4*this._rotationAngle)),i=new Ge("animationRotation","rotationQuaternion",90,Ge.ANIMATIONTYPE_QUATERNION,Ge.ANIMATIONLOOPMODE_CONSTANT),s=[];s.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),s.push({frame:6,value:t}),i.setKeys(s),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const r=new Ge("animationPP","vignetteWeight",90,Ge.ANIMATIONTYPE_FLOAT,Ge.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),r.setKeys(n),r.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(r);const o=new Ge("animationPP2","vignetteStretch",90,Ge.ANIMATIONTYPE_FLOAT,Ge.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:10}),a.push({frame:6,value:0}),o.setKeys(a),o.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(o),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}teleportCamera(e){if(!(this.currentVRCamera instanceof _l))return;let t,i;if(this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==Fh.TELEPORTATIONMODE_CONSTANTSPEED){i=90;const e=w.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];const s=new Ge("animationCameraTeleportation","position",90,Ge.ANIMATIONTYPE_VECTOR3,Ge.ANIMATIONLOOPMODE_CONSTANT),r=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];s.setKeys(r),s.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(s),this._postProcessMove.animations=[];const n=Math.round(i/2),o=new Ge("animationPP","vignetteWeight",90,Ge.ANIMATIONTYPE_FLOAT,Ge.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:n,value:8}),a.push({frame:i,value:0}),o.setKeys(a),this._postProcessMove.animations.push(o);const l=new Ge("animationPP2","vignetteStretch",90,Ge.ANIMATIONTYPE_FLOAT,Ge.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:n,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,(()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)})),this._hideTeleportationTarget()}setLaserColor(e,t=this._pickedLaserColor){this._pickedLaserColor=t}setLaserLightingState(e=!0){}setGazeColor(e,t=this._pickedGazeColor){this._pickedGazeColor=t}changeLaserColor(e){this.updateControllerLaserColor}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}}Fh.TELEPORTATIONMODE_CONSTANTTIME=0,Fh.TELEPORTATIONMODE_CONSTANTSPEED=1;const Lh=function(){const e={root:0,found:!1};return function(t,i,s,r){e.root=0,e.found=!1;const n=i*i-4*t*s;if(n<0)return e;const o=Math.sqrt(n);let a=(-i-o)/(2*t),l=(-i+o)/(2*t);if(a>l){const e=l;l=a,a=e}return a>0&&a0&&l=0))}_canDoCollision(e,t,i,s){const r=w.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(r>this._velocityWorldLength+n+t||!((e,t,i,s)=>!(e.x>i.x+s||i.x-s>t.x||e.y>i.y+s||i.y-s>t.y||e.z>i.z+s||i.z-s>t.z))(i,s,this._basePointWorld,this._velocityWorldLength+n))}_testTriangle(e,t,i,s,r,n,o){let a,l=!1;t||(t=[]),t[e]||(t[e]=new Ps(0,0,0,0),t[e].copyFromPoints(i,s,r));const h=t[e];if(!n&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;const c=h.signedDistanceTo(this._basePoint),u=w.Dot(h.normal,this._velocity);if(Bh.DoubleSidedCheck&&u>1e-4)return;if(0==u){if(Math.abs(c)>=1)return;l=!0,a=0}else{a=(-1-c)/u;let e=(1-c)/u;if(a>e){const t=e;e=a,a=t}if(a>1||e<0)return;a<0&&(a=0),a>1&&(a=1)}this._collisionPoint.copyFromFloats(0,0,0);let d=!1,p=1;if(l||(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(a,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,s,r,h.normal)&&(d=!0,p=a,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!d){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*w.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=Lh(e,t,n,p);o.found&&(p=o.root,d=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(s,this._tempVector),t=2*w.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=Lh(e,t,n,p),o.found&&(p=o.root,d=!0,this._collisionPoint.copyFrom(s)),this._basePoint.subtractToRef(r,this._tempVector),t=2*w.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,o=Lh(e,t,n,p),o.found&&(p=o.root,d=!0,this._collisionPoint.copyFrom(r)),s.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let a=this._edge.lengthSquared(),l=w.Dot(this._edge,this._velocity),h=w.Dot(this._edge,this._baseToVertex);if(e=a*-this._velocitySquaredLength+l*l,t=2*(a*w.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=Lh(e,t,n,p),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(p=o.root,d=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(r.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=w.Dot(this._edge,this._velocity),h=w.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*w.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=Lh(e,t,n,p),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(p=o.root,d=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),a=this._edge.lengthSquared(),l=w.Dot(this._edge,this._velocity),h=w.Dot(this._edge,this._baseToVertex),e=a*-this._velocitySquaredLength+l*l,t=2*(a*w.Dot(this._velocity,this._baseToVertex)-l*h),n=a*(1-this._baseToVertex.lengthSquared())+h*h,o=Lh(e,t,n,p),o.found){const e=(l*o.root-h)/a;e>=0&&e<=1&&(p=o.root,d=!0,this._edge.scaleInPlace(e),r.addToRef(this._edge,this._collisionPoint))}}if(d){const e=p*p*this._velocitySquaredLength;(!this.collisionFound||e=s)return void r.copyFrom(e);const a=n?n.collisionMask:i.collisionMask;i._initialize(e,t,o);const l=n&&n.surroundingMeshes||this._scene.meshes;for(let e=0;enew Vh;class Uh{constructor(e,t,i,s=""){let r;this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new g,this.onErrorObservable=new g,this.onBindObservable=new g,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=ht.WGSL,this.name=e,this._key=s,this._engine=i,this.uniqueId=Uh._UniqueIdSeed++,this.defines=t.defines??"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=t.entryPoint??"main",this._shaderStore=Ft.GetShadersStore(this._shaderLanguage),this._shaderRepository=Ft.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=Ft.GetIncludesShadersStore(this._shaderLanguage);const n=We()?this._engine.getHostDocument():null;r="string"==typeof e?e:e.computeSource?"source:"+e.computeSource:e.computeElement?n?.getElementById(e.computeElement)||e.computeElement:e.compute||e;const o={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(r,"Compute","",(i=>{bt(o),function(e,t,i,s){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),Ot(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const r=function(e,t,i){let s=e;const r=t.defines,n=Dt(t,i);return t.processor?.preProcessor&&(s=t.processor.preProcessor(s,r,n,t.isFragment,t.processingContext)),s=Mt(s,n,t),t.processor?.postProcessor&&(s=t.processor.postProcessor(s,r,t.isFragment,t.processingContext,i?{drawBuffersExtensionDisabled:!i.getCaps().drawBuffersExtension}:{})),i._features.needShaderCodeInlining&&(s=i.inlineShaderCode(s)),s}(e,t,s);i(r,e)}))}(i,o,(s=>{this._rawComputeSourceCode=i,t.processFinalCode&&(s=t.processFinalCode(s));const r=yt(s,"",o);this._useFinalCode(r.vertexCode,e)}),this._engine)}))}_useFinalCode(e,t){if(t){const i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}setTimeout((()=>{this._checkIsReady(e)}),16)}_loadShader(e,t,i,s){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement)return void s(Ye(e));if("source:"===e.substr(0,7))return void s(e.substr(7));if("base64:"===e.substr(0,7))return void s(window.atob(e.substr(7)));if(this._shaderStore[e+t+"Shader"])return void s(this._shaderStore[e+t+"Shader"]);if(i&&this._shaderStore[e+i+"Shader"])return void s(this._shaderStore[e+i+"Shader"]);let r;r="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(r+"."+t.toLowerCase()+".fx",s)}get computeSourceCode(){return this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._pipelineContext?._getComputeShaderCode()??this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){const e=this.defines,t=this._pipelineContext;this._isReady=!1;try{const i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,(e=>{e&&e.numErrors>0?this._processCompilationErrors(e,t):(this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t))})),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_processCompilationErrors(e,t=null){if(this._compilationError="",J.Error("Unable to compile compute effect:"),this.defines&&J.Error("Defines:\n"+this.defines),Uh.LogShaderCodeOnCompilationError){const e=this._pipelineContext?._getComputeShaderCode();e&&(J.Error("Compute code:"),J.Error(e))}if("string"==typeof e)this._compilationError=e,J.Error("Error: "+this._compilationError);else for(const t of e.messages){let e="";void 0!==t.line&&(e+="Line "+t.line+", "),void 0!==t.offset&&(e+="Offset "+t.offset+", "),void 0!==t.length&&(e+="Length "+t.length+", "),e+=t.type+": "+t.text,this._compilationError&&(this._compilationError+="\n"),this._compilationError+=e,J.Error(e)}t&&(this._pipelineContext=t,this._isReady=!0),this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){Ft.GetShadersStore(ht.WGSL)[`${e}ComputeShader`]=t}}var kh,Gh,zh,Wh,Hh;Uh._UniqueIdSeed=0,Uh.LogShaderCodeOnCompilationError=!0,function(e){e[e.Texture=0]="Texture",e[e.StorageTexture=1]="StorageTexture",e[e.UniformBuffer=2]="UniformBuffer",e[e.StorageBuffer=3]="StorageBuffer",e[e.TextureWithoutSampler=4]="TextureWithoutSampler",e[e.Sampler=5]="Sampler",e[e.ExternalTexture=6]="ExternalTexture",e[e.DataBuffer=7]="DataBuffer"}(kh||(kh={})),Yi.prototype.createComputeEffect=function(e,t){throw new Error("createComputeEffect: This engine does not support compute shaders!")},Yi.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")},Yi.prototype.createComputeContext=function(){},Yi.prototype.computeDispatch=function(e,t,i,s,r,n,o){throw new Error("computeDispatch: This engine does not support compute shaders!")},Yi.prototype.computeDispatchIndirect=function(e,t,i,s,r,n){throw new Error("computeDispatchIndirect: This engine does not support compute shaders!")},Yi.prototype.areAllComputeEffectsReady=function(){return!0},Yi.prototype.releaseComputeEffects=function(){},Yi.prototype._prepareComputePipelineContext=function(e,t,i,s,r){},Yi.prototype._rebuildComputeEffects=function(){},si.prototype._executeWhenComputeStateIsCompiled=function(e,t){t(null)},Yi.prototype._releaseComputeEffect=function(e){},Yi.prototype._deleteComputePipelineContext=function(e){};class Xh{constructor(){this._gpuTimeInFrameId=-1,this.counter=new Is}_addDuration(e,t){e{const n=()=>{this.dispatch(e,t,i)?r():setTimeout(n,s)};n()}))}serialize(){const e=Pe.Serialize(this);e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={};for(const t in this._bindings){const i=this._bindings[t],s=i.object;switch(i.type){case kh.Texture:case kh.TextureWithoutSampler:case kh.StorageTexture:{const r=s.serialize();r&&(e.textures[t]=r,e.bindings[t]={type:i.type});break}case kh.UniformBuffer:}}return e}static Parse(e,t,i){const s=Pe.Parse((()=>new Yh(e.name,t.getEngine(),e.shaderPath,e.options)),e,t,i);for(const r in e.textures){const n=e.bindings[r],o=Zn.Parse(e.textures[r],t,i);n.type===kh.Texture?s.setTexture(r,o):n.type===kh.TextureWithoutSampler?s.setTexture(r,o,!1):s.setStorageTexture(r,o)}return s}static _BufferIsDataBuffer(e){return void 0!==e.underlyingResource}}ae([pe()],Yh.prototype,"name",void 0),ae([pe()],Yh.prototype,"fastMode",void 0),u("BABYLON.ComputeShader",Yh);class jh{constructor(e,t,i,s,r,n){this.entries=[],this._boundingVectors=new Array,this._capacity=i,this._depth=s,this._maxDepth=r,this._creationFunc=n,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks)for(let t=0;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{const i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},$h.CreationFuncForSubMeshes=(e,t)=>{e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},ks.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(ts.NAME_OCTREE);i||(i=new Kh(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new $h($h.CreationFuncForMeshes,e,t));const s=this.getWorldExtends();return this._selectionOctree.update(s.min,s.max,this.meshes),this._selectionOctree},Object.defineProperty(ks.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),Wr.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){const i=this.getScene();let s=i._getComponent(ts.NAME_OCTREE);s||(s=new Kh(i),i._addComponent(s)),this._submeshesOctree||(this._submeshesOctree=new $h($h.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);const r=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(r.minimumWorld,r.maximumWorld,this.subMeshes),this._submeshesOctree};class Kh{constructor(e){this.name=ts.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new ao(w.Zero(),new w(1,1,1)),(e=e||y.LastCreatedScene)&&(this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=e=>this.getActiveSubMeshCandidates(e),this.scene.getCollidingSubMeshCandidates=(e,t)=>this.getCollidingSubMeshCandidates(e,t),this.scene.getIntersectingSubMeshCandidates=(e,t)=>this.getIntersectingSubMeshCandidates(e,t))}register(){this.scene.onMeshRemovedObservable.add((e=>{const t=this.scene.selectionOctree;if(null!=t){const i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}})),this.scene.onMeshImportedObservable.add((e=>{const t=this.scene.selectionOctree;null!=t&&t.addMesh(e)}))}getActiveMeshCandidates(){return this.scene._selectionOctree?.select(this.scene.frustumPlanes)||this.scene._getDefaultMeshCandidates()}getActiveSubMeshCandidates(e){return e._submeshesOctree&&e.useOctreeForRenderingSelection?e._submeshesOctree.select(this.scene.frustumPlanes):this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){return e._submeshesOctree&&e.useOctreeForPicking?(ao.TransformToRef(t,e.getWorldMatrix(),this._tempRay),e._submeshesOctree.intersectsRay(this._tempRay)):this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){const i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z);return e._submeshesOctree.intersects(t._basePointWorld,i)}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}}function qh(e){const t=e.height||2;let i=0===e.diameterTop?0:e.diameterTop||e.diameter||1,s=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;i=i||1e-5,s=s||1e-5;const r=0|(e.tessellation||24),n=0|(e.subdivisions||1),o=!!e.hasRings,a=!!e.enclose,l=0===e.cap?0:e.cap||Un.CAP_ALL,h=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,c=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE,u=e.faceUV||new Array(3),d=e.faceColors,p=2+(1+(1!==h&&a?2:0))*(o?n:1);let f;for(f=0;f{const n=e?i/2:s/2;if(0===n)return;let o,a,l;const c=e?u[p-1]:u[0];let f=null;d&&(f=e?d[p-1]:d[0]);const T=m.length/3,S=e?t/2:-t/2,E=new w(0,S,0);m.push(E.x,E.y,E.z),g.push(0,e?1:-1,0);const b=c.y+.5*(c.w-c.y);v.push(c.x+.5*(c.z-c.x),Er.UseOpenGLOrientationForUV?1-b:b),f&&x.push(f.r,f.g,f.b,f.a);const C=new N(.5,.5);for(l=0;l<=r;l++){o=2*Math.PI*l*h/r;const t=Math.cos(-o),i=Math.sin(-o);a=new w(t*n,S,i*n);const s=new N(t*C.x+.5,i*C.y+.5);m.push(a.x,a.y,a.z),g.push(0,e?1:-1,0);const u=c.y+(c.w-c.y)*s.y;v.push(c.x+(c.z-c.x)*s.x,Er.UseOpenGLOrientationForUV?1-u:u),f&&x.push(f.r,f.g,f.b,f.a)}for(l=0;l(void 0!==o&&o instanceof ks||(void 0!==o&&(l=a||Un.DEFAULTSIDE,a=o),o=n,n=1),Qh(e,{height:t,diameterTop:i,diameterBottom:s,tessellation:r,subdivisions:n,sideOrientation:l,updatable:a},o)),De.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new Zh(e,w.Zero(),t)));class Zh extends Gn{constructor(e,t,i){super(e,i),this.groundColor=new Y(0,0,0),this.direction=t||w.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=w.Normalize(e.subtract(w.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=w.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){const i=w.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=B.Identity()),this._worldMatrix}getTypeID(){return Gn.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}ae([_e()],Zh.prototype,"groundColor",void 0),ae([ve()],Zh.prototype,"direction",void 0),u("BABYLON.HemisphericLight",Zh);class Jh{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new Zh("shared gizmo light",new w(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=Y.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==Jh._DefaultUtilityLayer?Jh._CreateDefaultUtilityLayerFromScene(y.LastCreatedScene):Jh._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return Jh._DefaultUtilityLayer=new Jh(e),Jh._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{Jh._DefaultUtilityLayer=null})),Jh._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==Jh._DefaultKeepDepthUtilityLayer&&(Jh._DefaultKeepDepthUtilityLayer=new Jh(y.LastCreatedScene),Jh._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,Jh._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{Jh._DefaultKeepDepthUtilityLayer=null}))),Jh._DefaultKeepDepthUtilityLayer}constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new g,this.utilityLayerScene=new ks(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add((t=>{if(!this.utilityLayerScene.activeCamera)return;if(!this.pickingEnabled)return;if(!this.processAllEvents&&t.type!==ss.POINTERMOVE&&t.type!==ss.POINTERUP&&t.type!==ss.POINTERDOWN&&t.type!==ss.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const i=t.event;if(e.isPointerCaptured(i.pointerId))return void(this._pointerCaptures[i.pointerId]=!1);const s=i=>{let s=null;if(t.nearInteractionPickingInfo)s=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new qi;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)s=t.originalPickingInfo;else{let r=null;this._renderCamera&&(r=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),s=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),r&&(i._activeCamera=r)}return s},r=s(this.utilityLayerScene);if(!t.ray&&r&&(t.ray=r.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=ss.POINTERDOWN)return t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new os(t.type,t.event,r),t.type),void(t.type===ss.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1));if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)r&&r.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new os(t.type,t.event,r),t.type),t.skipOnPointerObservable=!0);else{const i=s(e),n=t.event;i&&r&&(0===r.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):t.type===ss.POINTERDOWN?this._pointerCaptures[n.pointerId]=!0:t.type!==ss.POINTERMOVE&&t.type!==ss.POINTERUP||(this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,i,n)):!this._pointerCaptures[n.pointerId]&&(r.distance0)):!this._pointerCaptures[n.pointerId]&&r.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):(t.type!==ss.POINTERMOVE&&t.type!==ss.POINTERUP||this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,r,n))),t.type===ss.POINTERUP&&this._pointerCaptures[n.pointerId]&&(this._pointerCaptures[n.pointerId]=!1))}})),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add((e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add((()=>{this.dispose()})),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new os(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){const e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}}Jh._DefaultUtilityLayer=null,Jh._DefaultKeepDepthUtilityLayer=null,function(e){e[e.Origin=0]="Origin",e[e.Pivot=1]="Pivot"}(Gh||(Gh={})),(Hh=zh||(zh={}))[Hh.World=0]="World",Hh[Hh.Local=1]="Local";class ec{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach((e=>{e.dispose()})),e.parent=this._rootMesh,this._customMeshSet=!0}get additionalTransformNode(){return this._additionalTransformNode}set additionalTransformNode(e){this._additionalTransformNode=e}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;const t=e==zh.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=Jh.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=Gh.Origin,this._updateScale=!0,this._coordinatesMode=zh.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=B.RotationY(Math.PI),this._rootMesh=new Un("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=L.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add((()=>{this._update()}))}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh)if(this.anchorPoint==Gh.Pivot&&e.getAbsolutePivotPoint){const t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{const t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new w(0,0,0);this._rootMesh.position.copyFrom(i)}if(this.updateGizmoRotationToMatchAttachedMesh){const t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName()?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,ec.PreserveScaling?t:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){const t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,U.Vector3[0]);let s=this.scaleRatio;if(t.mode==or.ORTHOGRAPHIC_CAMERA)t.orthoTop&&t.orthoBottom&&(s*=t.orthoTop-t.orthoBottom);else{const e=t.getScene().useRightHandedSystem?w.RightHandedForwardReadOnly:w.LeftHandedForwardReadOnly,i=t.getDirection(e);s*=w.Dot(U.Vector3[0],i)}this._rootMesh.scaling.setAll(s),e._getWorldMatrixDeterminant()<0&&!ec.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}this.additionalTransformNode&&(this._rootMesh.computeWorldMatrix(!0),this._rootMesh.getWorldMatrix().multiplyToRef(this.additionalTransformNode.getWorldMatrix(),U.Matrix[0]),U.Matrix[0].decompose(this._rootMesh.scaling,this._rootMesh.rotationQuaternion,this._rootMesh.position))}_handlePivotMatrixInverse(e,t,i){if(e.isUsingPivotMatrix()&&!e.isUsingPostMultiplyPivotMatrix())return e.getPivotMatrix().invertToRef(U.Matrix[5]),void U.Matrix[5].multiplyToRef(t,i);i.copyFrom(t)}_matrixChanged(){if(this._attachedNode)if(this._attachedNode._isCamera){const e=this._attachedNode;let t,i;if(e.parent){const i=U.Matrix[1];e.parent._worldMatrix.invertToRef(i),this._attachedNode._worldMatrix.multiplyToRef(i,U.Matrix[0]),t=U.Matrix[0]}else t=this._attachedNode._worldMatrix;if(e.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(t,U.Matrix[1]),i=U.Matrix[1]):i=t,i.decompose(U.Vector3[1],U.Quaternion[0],U.Vector3[0]),"FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName()){const e=this._attachedNode;e.rotation=U.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(U.Quaternion[0]),e.rotationQuaternion.normalize())}e.position.copyFrom(U.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){const e=this._attachedNode;if(e.parent){const t=U.Matrix[0],i=U.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i);const s=U.Matrix[4];if(this._handlePivotMatrixInverse(e,i,s),s.decompose(U.Vector3[0],U.Quaternion[0],e.position,ec.PreserveScaling?e:void 0,ec.UseAbsoluteScaling),U.Quaternion[0].normalize(),e.isUsingPivotMatrix()){const t=U.Quaternion[1];L.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,t);const i=U.Matrix[2];B.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,i);const s=U.Matrix[2];t.toRotationMatrix(s);const r=e.getPivotMatrix(),n=U.Matrix[3];r.invertToRef(n),r.multiplyToRef(i,U.Matrix[4]),U.Matrix[4].multiplyToRef(s,U.Matrix[5]),U.Matrix[5].multiplyToRef(n,U.Matrix[6]),U.Matrix[6].getTranslationToRef(U.Vector3[1]),e.position.subtractInPlace(U.Vector3[1])}}else{const t=U.Matrix[4];this._handlePivotMatrixInverse(e,this._attachedNode._worldMatrix,t),t.decompose(U.Vector3[0],U.Quaternion[0],e.position,ec.PreserveScaling?e:void 0,ec.UseAbsoluteScaling)}U.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(U.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(U.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=U.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){const e=this._attachedNode,t=e.getParent();if(t){const i=U.Matrix[0],s=U.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,s),e.getLocalMatrix().copyFrom(s)}else e.getLocalMatrix().copyFrom(e.getFinalMatrix());e.markAsDirty()}else{const e=this._attachedNode;if(e.getTypeID){const t=e.getTypeID();if(t===Gn.LIGHTTYPEID_DIRECTIONALLIGHT||t===Gn.LIGHTTYPEID_SPOTLIGHT||t===Gn.LIGHTTYPEID_POINTLIGHT){const t=e.parent;if(t){const i=U.Matrix[0],s=U.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,s),s.decompose(void 0,U.Quaternion[0],U.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,U.Quaternion[0],U.Vector3[0]);e.position=new w(U.Vector3[0].x,U.Vector3[0].y,U.Vector3[0].z),e.direction&&(e.direction=new w(e.direction.x,e.direction.y,e.direction.z))}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach((e=>{e.material=t,e.color&&(e.color=t.diffuseColor)}))}static GizmoAxisPointerObserver(e,t){let i=!1;return e.utilityLayerScene.onPointerObservable.add((e=>{if(e.pickInfo){if(e.type===ss.POINTERMOVE){if(i)return;t.forEach((t=>{if(t.colliderMeshes&&t.gizmoMeshes){const i=-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh),s=t.dragBehavior.enabled?i||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=s,e.color&&(e.color=s.diffuseColor)}))}}))}e.type===ss.POINTERDOWN&&t.has(e.pickInfo.pickedMesh?.parent)&&(i=!0,t.get(e.pickInfo.pickedMesh?.parent).active=!0,t.forEach((t=>{const i=(-1!=t.colliderMeshes?.indexOf(e?.pickInfo?.pickedMesh)||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=i,e.color&&(e.color=i.diffuseColor)}))}))),e.type===ss.POINTERUP&&t.forEach((e=>{e.active=!1,i=!1,e.gizmoMeshes.forEach((t=>{t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)}))}))}}))}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}ec.PreserveScaling=!1,ec.UseAbsoluteScaling=!0,Object.defineProperty(ks.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new tc(this)),this._debugLayer},enumerable:!0,configurable:!0}),function(e){e[e.Properties=0]="Properties",e[e.Debug=1]="Debug",e[e.Statistics=2]="Statistics",e[e.Tools=3]="Tools",e[e.Settings=4]="Settings"}(Wh||(Wh={}));class tc{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new g),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new g),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||y.LastCreatedScene,this._scene&&this._scene.onDisposeObservable.add((()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()}))}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(const e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(const e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}const t={...tc.Config,...e};this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise((t=>{if(void 0===this.BJSINSPECTOR){const i=e&&e.inspectorURL?e.inspectorURL:tc.InspectorURL;Ii.LoadBabylonScript(i,(()=>{this._createInspector(e),t(this)}))}else this._createInspector(e),t(this)}))}}function ic(e){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],s=[];let r=[];const n=e.width||e.size||1,o=e.height||e.size||1,a=e.depth||e.size||1,l=e.wrap||!1;let h=void 0===e.topBaseAt?1:e.topBaseAt,c=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,c=(c+4)%4;let u=[2,0,3,1][h],d=[2,0,1,3][c],p=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(l){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],p=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let e=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],i=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const s=[17,18,19,16],r=[22,23,20,21];for(;u>0;)e.unshift(e.pop()),s.unshift(s.pop()),u--;for(;d>0;)i.unshift(i.pop()),r.unshift(r.pop()),d--;e=e.flat(),i=i.flat(),p=p.concat(e).concat(i),t.push(s[0],s[2],s[3],s[0],s[1],s[2]),t.push(r[0],r[2],r[3],r[0],r[1],r[2])}const f=[n/2,o/2,a/2];r=p.reduce(((e,t,i)=>e.concat(t*f[i%3])),[]);const _=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE,m=e.faceUV||new Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new F(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new j(1,1,1,1));for(let e=0;e<6;e++)if(s.push(m[e].z,Er.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),s.push(m[e].x,Er.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),s.push(m[e].x,Er.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),s.push(m[e].z,Er.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);Tr._ComputeSides(_,r,t,i,s,e.frontUVs,e.backUVs);const x=new Tr;if(x.indices=t,x.positions=r,x.normals=i,x.uvs=s,g){const e=_===Tr.DOUBLESIDE?v.concat(v):v;x.colors=e}return x}function sc(e,t={},i=null){const s=new Un(e,i);return t.sideOrientation=Un._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,ic(t).applyToMesh(s,t.updatable),s}function rc(e){const t=0|(e.segments||32),i=e.diameterX||e.diameter||1,s=e.diameterY||e.diameter||1,r=e.diameterZ||e.diameter||1,n=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,o=e.slice&&e.slice<=0?1:e.slice||1,a=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new w(i/2,s/2,r/2),c=2+t,u=2*c,d=[],p=[],f=[],_=[];for(let e=0;e<=c;e++){const t=e/c,i=t*Math.PI*o;for(let e=0;e<=u;e++){const s=e/u,r=s*Math.PI*2*n,o=B.RotationZ(-i),a=B.RotationY(r),l=w.TransformCoordinates(w.Up(),o),c=w.TransformCoordinates(l,a),d=c.multiply(h),m=c.divide(h).normalize();p.push(d.x,d.y,d.z),f.push(m.x,m.y,m.z),_.push(s,Er.UseOpenGLOrientationForUV?1-t:t)}if(e>0){const t=p.length/3;for(let i=t-2*(u+1);i+u+21&&(d.push(i),d.push(i+1),d.push(i+u+1)),(en?n:Math.floor(o);const a=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE,l=e.uvs,h=e.colors,c=[],u=[],d=[],p=[],f=[],_=[],m=[],g=[];let v;const x=[],T=[];let S,E,b;if(t.length<2){const e=[],i=[];for(E=0;E0&&(P=R[b].subtract(R[b-1]).length(),M=P+m[S],f[S].push(M),m[S]=M),b++;s&&(b--,c.push(R[0].x,R[0].y,R[0].z),P=R[b].subtract(R[0]).length(),M=P+m[S],f[S].push(M),m[S]=M),x[S]=I+y,T[S]=C,C+=I+y}let N,w,F=null,L=null;for(E=0;E{let r=s[0].length;const n=a;let o=0;const l=n._originalBuilderSideOrientation===Un.DOUBLESIDE?2:1;for(let a=1;a<=l;++a)for(let a=0;a1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE;t.push(0,0,0),r.push(.5,.5);const h=2*Math.PI*a,c=1===a?h/o:h/(o-1);let u=0;for(let e=0;e0||u>0){switch(m=-d,g=-p,v=d,x=p,r){case Un.CENTER:l/=2,m-=l,v+=l;break;case Un.LEFT:v+=l,f=-l/2;break;case Un.RIGHT:m-=l,f=l/2}switch(n){case Un.CENTER:u/=2,g-=u,x+=u;break;case Un.BOTTOM:x+=u,_=-u/2;break;case Un.TOP:g-=u,_=u/2}}const T=[],S=[],E=[];E[0]=[0,0,1,0,1,1,0,1],E[1]=[0,0,1,0,1,1,0,1],t!==Un.ROTATE_TILE&&t!==Un.ROTATE_ROW||(E[1]=[1,1,0,1,0,0,1,0]),t!==Un.FLIP_TILE&&t!==Un.FLIP_ROW||(E[1]=[1,0,0,0,0,1,1,1]),t!==Un.FLIP_N_ROTATE_TILE&&t!==Un.FLIP_N_ROTATE_ROW||(E[1]=[0,1,1,1,1,0,0,0]);let b=[];const C=[],y=[];let A=0;for(let e=0;e0||u>0){const e=u>0&&(n===Un.CENTER||n===Un.TOP),o=u>0&&(n===Un.CENTER||n===Un.BOTTOM),h=l>0&&(r===Un.CENTER||r===Un.RIGHT),E=l>0&&(r===Un.CENTER||r===Un.LEFT);let R,I,P,M,D=[];if(e&&h&&(T.push(m+f,g+_,0),T.push(-d+f,g+_,0),T.push(-d+f,g+u+_,0),T.push(m+f,g+u+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=1-l/i,I=1-u/s,P=1,M=1,D=[R,I,P,I,P,M,R,M],t===Un.ROTATE_ROW&&(D=[1-R,1-I,1-P,1-I,1-P,1-M,1-R,1-M]),t===Un.FLIP_ROW&&(D=[1-R,I,1-P,I,1-P,M,1-R,M]),t===Un.FLIP_N_ROTATE_ROW&&(D=[R,1-I,P,1-I,P,1-M,R,1-M]),b=b.concat(D),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e&&E&&(T.push(d+f,g+_,0),T.push(v+f,g+_,0),T.push(v+f,g+u+_,0),T.push(d+f,g+u+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=0,I=1-u/s,P=l/i,M=1,D=[R,I,P,I,P,M,R,M],(t===Un.ROTATE_ROW||t===Un.ROTATE_TILE&&a%2==0)&&(D=[1-R,1-I,1-P,1-I,1-P,1-M,1-R,1-M]),(t===Un.FLIP_ROW||t===Un.FLIP_TILE&&a%2==0)&&(D=[1-R,I,1-P,I,1-P,M,1-R,M]),(t===Un.FLIP_N_ROTATE_ROW||t===Un.FLIP_N_ROTATE_TILE&&a%2==0)&&(D=[R,1-I,P,1-I,P,1-M,R,1-M]),b=b.concat(D),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&h&&(T.push(m+f,p+_,0),T.push(-d+f,p+_,0),T.push(-d+f,x+_,0),T.push(m+f,x+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=1-l/i,I=0,P=1,M=u/s,D=[R,I,P,I,P,M,R,M],(t===Un.ROTATE_ROW&&c%2==1||t===Un.ROTATE_TILE&&c%1==0)&&(D=[1-R,1-I,1-P,1-I,1-P,1-M,1-R,1-M]),(t===Un.FLIP_ROW&&c%2==1||t===Un.FLIP_TILE&&c%2==0)&&(D=[1-R,I,1-P,I,1-P,M,1-R,M]),(t===Un.FLIP_N_ROTATE_ROW&&c%2==1||t===Un.FLIP_N_ROTATE_TILE&&c%2==0)&&(D=[R,1-I,P,1-I,P,1-M,R,1-M]),b=b.concat(D),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&E&&(T.push(d+f,p+_,0),T.push(v+f,p+_,0),T.push(v+f,x+_,0),T.push(d+f,x+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=0,I=0,P=l/i,M=u/s,D=[R,I,P,I,P,M,R,M],(t===Un.ROTATE_ROW&&c%2==1||t===Un.ROTATE_TILE&&(c+a)%2==1)&&(D=[1-R,1-I,1-P,1-I,1-P,1-M,1-R,1-M]),(t===Un.FLIP_ROW&&c%2==1||t===Un.FLIP_TILE&&(c+a)%2==1)&&(D=[1-R,I,1-P,I,1-P,M,1-R,M]),(t===Un.FLIP_N_ROTATE_ROW&&c%2==1||t===Un.FLIP_N_ROTATE_TILE&&(c+a)%2==1)&&(D=[R,1-I,P,1-I,P,1-M,R,1-M]),b=b.concat(D),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e){const e=[];R=0,I=1-u/s,P=1,M=1,e[0]=[R,I,P,I,P,M,R,M],e[1]=[R,I,P,I,P,M,R,M],t!==Un.ROTATE_TILE&&t!==Un.ROTATE_ROW||(e[1]=[1-R,1-I,1-P,1-I,1-P,1-M,1-R,1-M]),t!==Un.FLIP_TILE&&t!==Un.FLIP_ROW||(e[1]=[1-R,I,1-P,I,1-P,M,1-R,M]),t!==Un.FLIP_N_ROTATE_TILE&&t!==Un.FLIP_N_ROTATE_ROW||(e[1]=[R,1-I,P,1-I,P,1-M,R,1-M]);for(let s=0;s{const t=Math.cos(e),i=Math.sin(e),s=c/h*e,r=Math.cos(s),o=n*(2+r)*.5*t,a=n*(2+r)*i*.5,l=n*Math.sin(s)*.5;return new w(o,a,l)};let p,f;for(p=0;p<=a;p++){const e=p%a/a*2*h*Math.PI,t=d(e),s=d(e+.01),n=s.subtract(t);let c=s.add(t);const u=w.Cross(n,c);for(c=w.Cross(u,n),u.normalize(),c.normalize(),f=0;fsc(e,{size:t,sideOrientation:r,updatable:s},i),Tr.CreateSphere=rc,Un.CreateSphere=(e,t,i,s,r,n)=>nc(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:n,updatable:r},s),Un.CreateCapsule=(e,t,i)=>function(e,t={orientation:w.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6,updatable:!1},i=null){const s=new Un(e,i);return oc(t).applyToMesh(s,t.updatable),s}(e,t,i),Tr.CreateCapsule=oc,Tr.CreateRibbon=ac,Un.CreateRibbon=(e,t,i=!1,s,r,n,o=!1,a,l)=>lc(e,{pathArray:t,closeArray:i,closePath:s,offset:r,updatable:o,sideOrientation:a,instance:l},n),Tr.CreateDisc=hc,Un.CreateDisc=(e,t,i,s=null,r,n)=>cc(e,{radius:t,tessellation:i,sideOrientation:n,updatable:r},s),Tr.CreateTiledPlane=uc,Tr.CreateTiledBox=function(e){const t=e.faceUV||new Array(6),i=e.faceColors,s=e.pattern||Un.NO_FLIP,r=e.width||e.size||1,n=e.height||e.size||1,o=e.depth||e.size||1,a=e.tileWidth||e.tileSize||1,l=e.tileHeight||e.tileSize||1,h=e.alignHorizontal||0,c=e.alignVertical||0,u=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE;for(let e=0;e<6;e++)void 0===t[e]&&(t[e]=new F(0,0,1,1)),i&&void 0===i[e]&&(i[e]=new j(1,1,1,1));const d=r/2,p=n/2,f=o/2,_=[];for(let e=0;e<2;e++)_[e]=uc({pattern:s,tileWidth:a,tileHeight:l,width:r,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});for(let e=2;e<4;e++)_[e]=uc({pattern:s,tileWidth:a,tileHeight:l,width:o,height:n,alignVertical:c,alignHorizontal:h,sideOrientation:u});let m=c;c===Un.BOTTOM?m=Un.TOP:c===Un.TOP&&(m=Un.BOTTOM);for(let e=4;e<6;e++)_[e]=uc({pattern:s,tileWidth:a,tileHeight:l,width:r,height:o,alignVertical:m,alignHorizontal:h,sideOrientation:u});let g=[],v=[],x=[],T=[];const S=[],E=[],b=[],C=[];let y=0,A=0;for(let e=0;e<6;e++){const s=_[e].positions.length;E[e]=[],b[e]=[];for(let t=0;te+A))),A+=E[e].length,i)for(let t=0;t<4;t++)S.push(i[e].r,i[e].g,i[e].b,i[e].a)}const R=new w(0,0,f),I=B.RotationY(Math.PI);g=E[0].map((e=>w.TransformNormal(e,I).add(R))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),v=b[0].map((e=>w.TransformNormal(e,I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),g=g.concat(E[1].map((e=>e.subtract(R))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(b[1].map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const P=new w(d,0,0),M=B.RotationY(-Math.PI/2);g=g.concat(E[2].map((e=>w.TransformNormal(e,M).add(P))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(b[2].map((e=>w.TransformNormal(e,M))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const D=B.RotationY(Math.PI/2);g=g.concat(E[3].map((e=>w.TransformNormal(e,D).subtract(P))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(b[3].map((e=>w.TransformNormal(e,D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const O=new w(0,p,0),N=B.RotationX(Math.PI/2);g=g.concat(E[4].map((e=>w.TransformNormal(e,N).add(O))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(b[4].map((e=>w.TransformNormal(e,N))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const L=B.RotationX(-Math.PI/2);g=g.concat(E[5].map((e=>w.TransformNormal(e,L).subtract(O))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),v=v.concat(b[5].map((e=>w.TransformNormal(e,L))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),Tr._ComputeSides(u,g,T,v,x);const V=new Tr;if(V.indices=T,V.positions=g,V.normals=v,V.uvs=x,i){const e=u===Tr.DOUBLESIDE?S.concat(S):S;V.colors=e}return V},Tr.CreateTorusKnot=dc,Un.CreateTorusKnot=(e,t,i,s,r,n,o,a,l,h)=>function(e,t={},i){const s=new Un(e,i);return t.sideOrientation=Un._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,dc(t).applyToMesh(s,t.updatable),s}(e,{radius:t,tube:i,radialSegments:s,tubularSegments:r,p:n,q:o,sideOrientation:h,updatable:l},a);const pc={effect:null,subMesh:null};class fc extends Io{constructor(e,t,i,s={},r=!0){super(e,t,r),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new B,this._cachedWorldViewProjectionMatrix=new B,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...s}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return-1===this._options.externalTextures.indexOf(e)&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(16*t.length);for(let e=0;et===e||t.startsWith(i)));return s>=0&&this.options.defines.splice(s,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){const s=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){const e=s?i._drawWrapper:this._drawWrapper;if(e.effect&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}const r=this.getScene(),n=r.getEngine(),o=[],a=[],l=new Yo;let h=this._shaderPath,c=this._options.uniforms,u=this._options.uniformBuffers,d=this._options.samplers;n.getCaps().multiview&&r.activeCamera&&r.activeCamera.outputRenderTarget&&r.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),-1!==c.indexOf("viewProjection")&&-1===c.indexOf("viewProjectionR")&&c.push("viewProjectionR"));for(let e=0;e4&&(a.push(Ki.MatricesIndicesExtraKind),a.push(Ki.MatricesWeightsExtraKind));const t=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),l.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),-1===c.indexOf("boneTextureWidth")&&c.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(t.bones.length+1)),-1===c.indexOf("mBones")&&c.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let p=0;const f=e?e.morphTargetManager:null;if(f){const e=f.supportsUVs&&-1!==o.indexOf("#define UV1"),t=f.supportsTangents&&-1!==o.indexOf("#define TANGENT"),i=f.supportsNormals&&-1!==o.indexOf("#define NORMAL");p=f.numMaxInfluencers||f.numInfluencers,e&&o.push("#define MORPHTARGETS_UV"),t&&o.push("#define MORPHTARGETS_TANGENT"),i&&o.push("#define MORPHTARGETS_NORMAL"),p>0&&o.push("#define MORPHTARGETS"),f.isUsingTextureForTargets&&(o.push("#define MORPHTARGETS_TEXTURE"),-1===c.indexOf("morphTargetTextureIndices")&&c.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),o.push("#define NUM_MORPH_INFLUENCERS "+p);for(let s=0;s0&&(c=c.slice(),c.push("morphTargetInfluences"),c.push("morphTargetCount"),c.push("morphTargetTextureInfo"),c.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===c.indexOf("bakedVertexAnimationSettings")&&c.push("bakedVertexAnimationSettings"),-1===c.indexOf("bakedVertexAnimationTextureSizeInverted")&&c.push("bakedVertexAnimationTextureSizeInverted"),-1===c.indexOf("bakedVertexAnimationTime")&&c.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),hn(a,0,o)}for(const e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&o.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&(jr(c),$r(this,r,o)),r.fogEnabled&&e?.applyFog&&r.fogMode!==ks.FOGMODE_NONE&&(o.push("#define FOG"),-1===c.indexOf("view")&&c.push("view"),-1===c.indexOf("vFogInfos")&&c.push("vFogInfos"),-1===c.indexOf("vFogColor")&&c.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),-1===c.indexOf("logarithmicDepthConstant")&&c.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(c=c.slice(),u=u.slice(),d=d.slice(),h=this.customShaderNameResolve(this.name,c,u,d,o,a));const _=s?i._getDrawWrapper(void 0,!0):this._drawWrapper,m=_?.effect??null,g=_?.defines??null,v=o.join("\n");let x=m;return g!==v&&(x=n.createEffect(h,{attributes:a,uniformsNames:c,uniformBuffersNames:u,samplers:d,defines:v,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:p},shaderLanguage:this._options.shaderLanguage},n),s?i.setEffect(x,v,this._materialContext):_&&_.setEffect(x,v),this._onEffectCreatedObservable&&(pc.effect=x,pc.subMesh=i??e?.subMeshes[0]??null,this._onEffectCreatedObservable.notifyObservers(pc))),_._wasPreviouslyUsingInstances=!!t,!(!x?.isReady()??1)&&(m!==x&&r.resetCachedMaterial(),_._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),s=t??this.getEffect();s&&(-1!==this._options.uniforms.indexOf("world")&&s.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),s.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),s.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),-1!==this._options.uniforms.indexOf("view")&&s.setMatrix("view",i.getViewMatrix()))}bindForSubMesh(e,t,i){this.bind(e,t,i._drawWrapperOverride?.effect,i)}bind(e,t,i,s){const r=s&&this._storeEffectOnSubMeshes,n=i??(r?s.effect:this.getEffect());if(!n)return;const o=this.getScene();this._activeEffect=n,this.bindOnlyWorldMatrix(e,i);const a=this._options.uniformBuffers;let l=!1;if(n&&a&&a.length>0&&o.getEngine().supportsUniformBuffers)for(let i=0;i0&&nn(t,n);const i=t.bakedVertexAnimationManager;if(i&&i.isEnabled){const e=r?s._drawWrapper:this._drawWrapper;t.bakedVertexAnimationManager?.bind(n,!!e._wasPreviouslyUsingInstances)}}this._afterBind(t,n,s)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let t=0;tnew fc(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes)),this);t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath={...t._shaderPath}),this._options={...this._options},Object.keys(this._options).forEach((e=>{const t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))})),this.stencil.copyTo(t.stencil);for(const e in this._textures)t.setTexture(e,this._textures[e]);for(const e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(const e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(const e in this._ints)t.setInt(e,this._ints[e]);for(const e in this._uints)t.setUInt(e,this._uints[e]);for(const e in this._floats)t.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(const e in this._colors3)t.setColor3(e,this._colors3[e]);for(const e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(const e in this._colors4)t.setColor4(e,this._colors4[e]);for(const e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(const e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(const e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(const e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(const e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(const e in this._matrices)t.setMatrix(e,this._matrices[e]);for(const e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(const e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(const e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(const e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(const e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(const e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(const e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(const e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(const e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){const t=this._textureArrays[e];for(let e=0;enew fc(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes)),e,t,i);let r;for(r in e.stencil&&s.stencil.parse(e.stencil,t,i),e.textures)s.setTexture(r,Zn.Parse(e.textures[r],t,i));for(r in e.textureArrays){const n=e.textureArrays[r],o=[];for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>Y.FromArray(e)));s.setColor3Array(r,t)}for(r in e.colors4)s.setColor4(r,j.FromArray(e.colors4[r]));for(r in e.colors4Arrays){const t=e.colors4Arrays[r].reduce(((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>j.FromArray(e)));s.setColor4Array(r,t)}for(r in e.vectors2)s.setVector2(r,N.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,w.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,F.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,L.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,B.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,s=""){return new Promise(((r,n)=>{const o=new Ne;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=this.Parse(t,i||y.LastCreatedScene,s);e&&(n.name=e),r(n)}else n("Unable to load the ShaderMaterial")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return new Promise(((s,r)=>{const n=new Ne;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const r=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(r.shaderMaterial),a=this.Parse(o,t||y.LastCreatedScene,i);a.snippetId=e,s(a)}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}fc.SnippetUrl="https://snippet.babylonjs.com",fc.CreateFromSnippetAsync=fc.ParseFromSnippetAsync,u("BABYLON.ShaderMaterial",fc);Ft.ShadersStore.colorPixelShader="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n#include(color,gl_FragColor)\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.colorVertexShader="attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\n#ifdef FOG\nuniform mat4 view;\n#endif\n#include\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}",Un._LinesMeshParser=(e,t)=>_c.Parse(e,t);class _c extends Un{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,s=null,r,n,o,a){super(e,t,i,s,r),this.useVertexColor=n,this.useVertexAlpha=o,this.color=new Y(1,1,1),this.alpha=1,s&&(this.color=s.color.clone(),this.alpha=s.alpha,this.useVertexColor=s.useVertexColor,this.useVertexAlpha=s.useVertexAlpha),this.intersectionThreshold=.1;const l={attributes:[Ki.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===o?l.needAlphaBlending=!1:l.defines.push("#define VERTEXALPHA"),n?(l.defines.push("#define VERTEXCOLOR"),l.attributes.push(Ki.ColorKind)):(l.uniforms.push("color"),this._color4=new j),a?this.material=a:(this.material=new fc("colorShader",this.getScene(),"color",l,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=Dn.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;const i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const s=this.getScene().getEngine();return this._unIndexed?s.drawArraysType(Dn.LineListDrawMode,e.verticesStart,e.verticesCount,i):s.drawElementsType(Dn.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new _c(e,this.getScene(),t,this,i)}createInstance(e){const t=new mc(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const e in this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new _c(e.name,t);return i.color=Y.FromArray(e.color),i.alpha=e.alpha,i}}class mc extends kn{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function gc(e){const t=[],i=[],s=e.lines,r=e.colors,n=[];let o=0;for(let e=0;e0&&(t.push(o-1),t.push(o)),o++}}const a=new Tr;return a.indices=t,a.positions=i,r&&(a.colors=n),a}function vc(e){const t=e.dashSize||3,i=e.gapSize||1,s=e.dashNb||200,r=e.points,n=[],o=[],a=w.Zero();let l=0,h=0,c=0,u=0,d=0,p=0,f=0;for(f=0;fTc(e,{points:t,updatable:s,instance:r},i),Un.CreateDashedLines=(e,t,i,s,r,n=null,o,a)=>function(e,t,i=null){const s=t.points,r=t.instance,n=t.gapSize||1,o=t.dashSize||3;if(r){const e=e=>{const t=w.Zero(),i=e.length/6;let n=0,o=0,a=0,l=0,h=0,c=0,u=0,d=0;for(u=0;u{const i=new Sc(e,this.elements.length);t.push(i),this.elements.push(i)})),t}computeBounds(){const e=new N(this.elements[0].x,this.elements[0].y),t=new N(this.elements[0].x,this.elements[0].y);return this.elements.forEach((i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)})),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class bc{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,s=earcut){let r;this._points=new Ec,this._outlinepoints=new Ec,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=s,this._name=e,this._scene=i||y.LastCreatedScene,r=t instanceof Ys?t.getPoints():t,this._addToepoint(r),this._points.add(r),this._outlinepoints.add(r),void 0===this.bjsEarcut&&J.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new Ec;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){const s=new Un(this._name,this._scene),r=this.buildVertexData(t,i);return s.setVerticesData(Ki.PositionKind,r.positions,e),s.setVerticesData(Ki.NormalKind,r.normals,e),s.setVerticesData(Ki.UVKind,r.uvs,e),s.setIndices(r.indices),s}buildVertexData(e=0,t=2){const i=new Tr,s=[],r=[],n=[],o=this._points.computeBounds();this._points.elements.forEach((e=>{s.push(0,1,0),r.push(e.x,0,e.y),n.push((e.x-o.min.x)/o.width,(e.y-o.min.y)/o.height)}));const a=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e0){const i=r.length/3;this._points.elements.forEach((t=>{s.push(0,-1,0),r.push(t.x,-e,t.y),n.push(1-(t.x-o.min.x)/o.width,1-(t.y-o.min.y)/o.height)}));const l=a.length;for(let e=0;e{this._addSide(r,s,n,a,o,i,e,!0,t)}))}return i.indices=a,i.positions=r,i.normals=s,i.uvs=n,i}_addSide(e,t,i,s,r,n,o,a,l){let h=e.length/3,c=0;for(let u=0;ul?bl?C1),o=t.rotationFunction||(()=>0),a=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||Un.NO_CAP,c=t.updatable,u=t.firstNormal||null,d=t.adjustFrame||!1;return Ic(e,r,s,null,null,n,o,a,l,h,!0,i,!!c,Un._GetDefaultSideOrientation(t.sideOrientation),t.instance||null,t.invertUV||!1,t.frontUVs||null,t.backUVs||null,u,d)}function Ic(e,t,i,s,r,n,o,a,l,h,c,u,d,p,f,_,m,g,v,x){const T=(e,t,i,s,r,n,o,a,l,h,c)=>{const u=i.getTangents(),d=i.getNormals(),p=i.getBinormals(),f=i.getDistances();if(c)for(let e=0;e0){let t=u[e-1];w.Dot(t,u[e])<0&&u[e].scaleInPlace(-1),t=d[e-1],w.Dot(t,d[e])<0&&d[e].scaleInPlace(-1),t=p[e-1],w.Dot(t,p[e])<0&&p[e].scaleInPlace(-1)}let _=0;const m=h&&a?a:()=>null!==n?n:0,g=h&&o?o:()=>null!==r?r:1;let v=l===Un.NO_CAP||l===Un.CAP_END?0:2;const x=U.Matrix[0];for(let i=0;i{const t=Array(),i=w.Zero();let s;for(s=0;s3?0:h,c,x);const b=lc(e,{pathArray:E,closeArray:a,closePath:l,updatable:d,sideOrientation:p,invertUV:_,frontUVs:m||void 0,backUVs:g||void 0},u);return b._creationDataStorage.pathArray=E,b._creationDataStorage.path3D=S,b._creationDataStorage.cap=h,b}function Pc(e){const t=[];t[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},t[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},t[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},t[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},t[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},t[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},t[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},t[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},t[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},t[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},t[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},t[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},t[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},t[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},t[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};const i=e.type&&(e.type<0||e.type>=t.length)?0:e.type||0,s=e.size,r=e.sizeX||s||1,n=e.sizeY||s||1,o=e.sizeZ||s||1,a=e.custom||t[i],l=a.face.length,h=e.faceUV||new Array(l),c=e.faceColors,u=void 0===e.flat||e.flat,d=0===e.sideOrientation?0:e.sideOrientation||Tr.DEFAULTSIDE,p=[],f=[],_=[],m=[],g=[];let v=0,x=0;const T=[];let S,E,b,C,y,A,R=0,I=0;if(u)for(I=0;Iyc(e,{shape:t,holes:s,updatable:r,sideOrientation:n},i,o),Un.ExtrudePolygon=(e,t,i,s,r,n,o,a=earcut)=>function(e,t,i=null,s=earcut){return yc(e,t,i,s)}(e,{shape:t,holes:r,depth:i,updatable:n,sideOrientation:o},s,a),Un.ExtrudeShape=(e,t,i,s,r,n,o=null,a,l,h)=>Ac(e,{shape:t,path:i,scale:s,rotation:r,cap:0===n?0:n||Un.NO_CAP,sideOrientation:l,instance:h,updatable:a},o),Un.ExtrudeShapeCustom=(e,t,i,s,r,n,o,a,l,h,c,u)=>Rc(e,{shape:t,path:i,scaleFunction:s,rotationFunction:r,ribbonCloseArray:n,ribbonClosePath:o,cap:0===a?0:a||Un.NO_CAP,sideOrientation:c,instance:u,updatable:h},l),Un.CreateLathe=(e,t,i,s,r,n,o)=>function(e,t,i=null){const s=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,r=void 0===t.closed||t.closed,n=t.shape,o=t.radius||1,a=t.tessellation||64,l=t.clip||0,h=t.updatable,c=Un._GetDefaultSideOrientation(t.sideOrientation),u=t.cap||Un.NO_CAP,d=2*Math.PI,p=[],f=t.invertUV||!1;let _=0,m=0;const g=d/a*s;let v,x;for(_=0;_<=a-l;_++){for(x=[],u!=Un.CAP_START&&u!=Un.CAP_ALL||(x.push(new w(0,n[0].y,0)),x.push(new w(Math.cos(_*g)*n[0].x*o,n[0].y,Math.sin(_*g)*n[0].x*o))),m=0;mfunction(e,t,i=null){const s=t.path;let r=t.instance,n=1;void 0!==t.radius?n=t.radius:r&&(n=r._creationDataStorage.radius);const o=t.tessellation||64,a=t.radiusFunction||null;let l=t.cap||Un.NO_CAP;const h=t.invertUV||!1,c=t.updatable,u=Un._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;const d=(e,t,i,s,r,n,o,a)=>{const l=t.getTangents(),h=t.getNormals(),c=t.getDistances(),u=2*Math.PI/r*a,d=n||(()=>s);let p,f,_,m;const g=U.Matrix[0];let v=o===Un.NO_CAP||o===Un.CAP_END?0:2;for(let t=0;t{const s=Array();for(let r=0;r3?0:l,f=d(s,p,new Array,n,o,a,l,t.arc);const _=lc(e,{pathArray:f,closePath:!0,closeArray:!1,updatable:c,sideOrientation:u,invertUV:h,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return _._creationDataStorage.pathArray=f,_._creationDataStorage.path3D=p,_._creationDataStorage.tessellation=o,_._creationDataStorage.cap=l,_._creationDataStorage.arc=t.arc,_._creationDataStorage.radius=n,_}(e,{path:t,radius:i,tessellation:s,radiusFunction:r,arc:1,cap:n,updatable:a,sideOrientation:l,instance:h},o),Tr.CreatePolyhedron=Pc,Un.CreatePolyhedron=(e,t,i)=>function(e,t={},i=null){const s=new Un(e,i);return t.sideOrientation=Un._GetDefaultSideOrientation(t.sideOrientation),s._originalBuilderSideOrientation=t.sideOrientation,Pc(t).applyToMesh(s,t.updatable),s}(e,t,i);const Mc=new w(1,0,0),Dc=new w(-1,0,0),Oc=new w(0,1,0),Nc=new w(0,-1,0),wc=new w(0,0,1),Fc=new w(0,0,-1);class Lc{constructor(e=w.Zero(),t=w.Up(),i=N.Zero(),s=0,r=0,n=null,o=null,a=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=s,this.vertexIdxForBones=r,this.localPositionOverride=n,this.localNormalOverride=o,this.matrixIndicesOverride=a,this.matrixWeightsOverride=l}clone(){return new Lc(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,this.localPositionOverride?.slice(),this.localNormalOverride?.slice(),this.matrixIndicesOverride?.slice(),this.matrixWeightsOverride?.slice())}}Un.CreateDecal=(e,t,i,s,r,n)=>function(e,t,i){const s=!!t.skeleton,r=i.localMode||s,n=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,o=t.getIndices(),a=s?t.getPositionData(!0,!0):t.getVerticesData(Ki.PositionKind),l=s?t.getNormalsData(!0,!0):t.getVerticesData(Ki.NormalKind),h=r?s?t.getVerticesData(Ki.PositionKind):a:null,c=r?s?t.getVerticesData(Ki.NormalKind):l:null,u=t.getVerticesData(Ki.UVKind),d=s?t.getVerticesData(Ki.MatricesIndicesKind):null,p=s?t.getVerticesData(Ki.MatricesWeightsKind):null,f=s?t.getVerticesData(Ki.MatricesIndicesExtraKind):null,_=s?t.getVerticesData(Ki.MatricesWeightsExtraKind):null,m=i.position||w.Zero();let g=i.normal||w.Up();const v=i.size||w.One(),x=i.angle||0;if(!g){const e=new w(0,0,1),i=t.getScene().activeCamera,s=w.TransformCoordinates(e,i.getWorldMatrix());g=i.globalPosition.subtract(s)}const T=-Math.atan2(g.z,g.x)-Math.PI/2,S=Math.sqrt(g.x*g.x+g.z*g.z),E=Math.atan2(g.y,S),b=new Tr;b.indices=[],b.positions=[],b.normals=[],b.uvs=[],b.matricesIndices=s?[]:null,b.matricesWeights=s?[]:null,b.matricesIndicesExtra=f?[]:null,b.matricesWeightsExtra=_?[]:null;let C=0;const y=(e,t)=>{const s=new Lc;if(!o||!a||!l)return s;const r=o[e];if(s.vertexIdx=3*r,s.vertexIdxForBones=4*r,s.position=new w(a[3*r],a[3*r+1],a[3*r+2]),w.TransformCoordinatesToRef(s.position,t,s.position),s.normal=new w(l[3*r],l[3*r+1],l[3*r+2]),w.TransformNormalToRef(s.normal,t,s.normal),i.captureUVS&&u){const e=u[2*r+1];s.uv=new N(u[2*r],Er.UseOpenGLOrientationForUV?1-e:e)}return s},A=[0,0,0,0],R=(e,t)=>{if(0===e.length)return e;const i=.5*Math.abs(w.Dot(v,t)),s=(e,t,i,s)=>{for(let r=0;r{const n=w.GetClipFactor(e.position,r.position,t,i);let o=A,a=A;if(d&&p){const t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=e.matrixIndicesOverride??d,l=e.matrixWeightsOverride??p,h=r.matrixIndicesOverride?0:r.vertexIdxForBones,c=r.matrixIndicesOverride??d,u=r.matrixWeightsOverride??p;o=[0,0,0,0],a=[0,0,0,0];let f=0;for(let e=0;e<4;++e)if(l[t+e]>0){const r=s(c,i[t+e],h,4);o[f]=i[t+e],a[f]=G.Lerp(l[t+e],r>=0?u[r]:0,n),f++}for(let e=0;e<4&&f<4;++e){const r=c[h+e];-1===s(i,r,t,4)&&(o[f]=r,a[f]=G.Lerp(0,u[h+e],n),f++)}const _=a[0]+a[1]+a[2]+a[3];a[0]/=_,a[1]/=_,a[2]/=_,a[3]/=_}const l=e.localPositionOverride?e.localPositionOverride[0]:h?.[e.vertexIdx]??0,u=e.localPositionOverride?e.localPositionOverride[1]:h?.[e.vertexIdx+1]??0,f=e.localPositionOverride?e.localPositionOverride[2]:h?.[e.vertexIdx+2]??0,_=r.localPositionOverride?r.localPositionOverride[0]:h?.[r.vertexIdx]??0,m=r.localPositionOverride?r.localPositionOverride[1]:h?.[r.vertexIdx+1]??0,g=r.localPositionOverride?r.localPositionOverride[2]:h?.[r.vertexIdx+2]??0,v=e.localNormalOverride?e.localNormalOverride[0]:c?.[e.vertexIdx]??0,x=e.localNormalOverride?e.localNormalOverride[1]:c?.[e.vertexIdx+1]??0,T=e.localNormalOverride?e.localNormalOverride[2]:c?.[e.vertexIdx+2]??0,S=v+((r.localNormalOverride?r.localNormalOverride[0]:c?.[r.vertexIdx]??0)-v)*n,E=x+((r.localNormalOverride?r.localNormalOverride[1]:c?.[r.vertexIdx+1]??0)-x)*n,b=T+((r.localNormalOverride?r.localNormalOverride[2]:c?.[r.vertexIdx+2]??0)-T)*n,C=Math.sqrt(S*S+E*E+b*b);return new Lc(w.Lerp(e.position,r.position,n),w.Lerp(e.normal,r.normal,n).normalize(),N.Lerp(e.uv,r.uv,n),-1,-1,h?[l+(_-l)*n,u+(m-u)*n,f+(g-f)*n]:null,c?[S/C,E/C,b/C]:null,o,a)};let n=null;e.length>3&&(n=[]);for(let s=0;s0,d=w.Dot(e[s+1].position,t)-i>0,p=w.Dot(e[s+2].position,t)-i>0;switch(o=(u?1:0)+(d?1:0)+(p?1:0),o){case 0:e.length>3?(n.push(e[s]),n.push(e[s+1]),n.push(e[s+2])):n=e;break;case 1:if(n=n??new Array,u&&(a=e[s+1],l=e[s+2],h=r(e[s],a),c=r(e[s],l)),d){a=e[s],l=e[s+2],h=r(e[s+1],a),c=r(e[s+1],l),n.push(h),n.push(l.clone()),n.push(a.clone()),n.push(l.clone()),n.push(h.clone()),n.push(c);break}p&&(a=e[s],l=e[s+1],h=r(e[s+2],a),c=r(e[s+2],l)),a&&l&&h&&c&&(n.push(a.clone()),n.push(l.clone()),n.push(h),n.push(c),n.push(h.clone()),n.push(l.clone()));break;case 2:n=n??new Array,u||(a=e[s].clone(),l=r(a,e[s+1]),h=r(a,e[s+2]),n.push(a),n.push(l),n.push(h)),d||(a=e[s+1].clone(),l=r(a,e[s+2]),h=r(a,e[s]),n.push(a),n.push(l),n.push(h)),p||(a=e[s+2].clone(),l=r(a,e[s]),h=r(a,e[s+1]),n.push(a),n.push(l),n.push(h))}}return n},I=t instanceof Un?t:null,P=I?._thinInstanceDataStorage.matrixData,M=I?.thinInstanceCount||1,D=U.Matrix[0];D.copyFrom(B.IdentityReadOnly);for(let e=0;eBc.Parse(e,t);class Bc extends Un{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(J.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(J.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(J.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let t=0;t1&&(c=1),l.push(c,u);for(let e=0;e<6;e++)c=n.x+o*Math.cos(a+e*Math.PI/3),u=n.y+o*Math.sin(a+e*Math.PI/3),c<0&&(c=0),c>1&&(c=1),h.push(c,u);for(let e=s;ej.FromArray(e))),i.faceCenters=i.faceCenters.map((e=>w.FromArray(e))),i.faceZaxis=i.faceZaxis.map((e=>w.FromArray(e))),i.faceXaxis=i.faceXaxis.map((e=>w.FromArray(e))),i.faceYaxis=i.faceYaxis.map((e=>w.FromArray(e)));const s=new Bc(e.name,t);return s.goldbergData=i,s}}class Vc{constructor(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}moveTo(e,t){this._currentPath=new Ys(e,t),this._tempPaths.push(this._currentPath)}lineTo(e,t){this._currentPath.addLineTo(e,t)}quadraticCurveTo(e,t,i,s){this._currentPath.addQuadraticCurveTo(e,t,i,s,this._resolution)}bezierCurveTo(e,t,i,s,r,n){this._currentPath.addBezierCurveTo(e,t,i,s,r,n,this._resolution)}extractHoles(){for(const e of this._tempPaths)e.area()>0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function Uc(e,t,i,s,r,n){const o=n.glyphs[e]||n.glyphs["?"];if(!o)return null;const a=new Vc(r);if(o.o){const e=o.o.split(" ");for(let r=0,n=e.length;r\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n\n #include\n\n varying vec3 vColor;\n\n uniform vec3 colorBase;\n uniform vec3 colorZero;\n uniform vec3 colorQuarter;\n uniform vec3 colorHalf;\n uniform vec3 colorFull;\n\n uniform float targetBoneIndex;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n vec3 color = colorBase;\n float totalWeight = 0.;\n if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){\n totalWeight += matricesWeights[0];\n }\n if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){\n totalWeight += matricesWeights[1];\n }\n if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){\n totalWeight += matricesWeights[2];\n }\n if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){\n totalWeight += matricesWeights[3];\n }\n\n color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));\n color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));\n color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));\n color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));\n vColor = color;\n\n gl_Position = projection * view * worldPos;\n }",$t.ShadersStore["boneWeights:"+i.name+"FragmentShader"]="\n precision highp float;\n varying vec3 vPosition;\n\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4(vColor, 1.0);\n gl_FragColor = color;\n }\n ";const h=new fc("boneWeight:"+i.name,t,{vertex:"boneWeights:"+i.name,fragment:"boneWeights:"+i.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return h.setColor3("colorBase",s),h.setColor3("colorZero",r),h.setColor3("colorQuarter",n),h.setColor3("colorHalf",o),h.setColor3("colorFull",a),h.setFloat("targetBoneIndex",l),h.getClassName=()=>"BoneWeightShader",h.transparencyMode=Dn.MATERIAL_OPAQUE,h}static CreateSkeletonMapShader(e,t){const i=e.skeleton,s=e.colorMap??[{color:new Y(1,.38,.18),location:0},{color:new Y(.59,.18,1),location:.2},{color:new Y(.59,1,.18),location:.4},{color:new Y(1,.87,.17),location:.6},{color:new Y(1,.17,.42),location:.8},{color:new Y(.17,.68,1),location:1}],r=i.bones.length+1,n=kc._CreateBoneMapColorBuffer(r,s,t),o=new fc("boneWeights:"+i.name,t,{vertexSource:"precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n uniform float colorMap["+4*i.bones.length+"];\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n #include\n\n varying vec3 vColor;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec3 color = vec3(0.);\n bool first = true;\n\n for (int i = 0; i < 4; i++) {\n int boneIdx = int(matricesIndices[i]);\n float boneWgt = matricesWeights[i];\n\n vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);\n\n if (boneWgt > 0.) {\n if (first) {\n first = false;\n color = c;\n } else {\n color = mix(color, c, boneWgt);\n }\n }\n }\n\n vColor = color;\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n gl_Position = projection * view * worldPos;\n }",fragmentSource:"\n precision highp float;\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4( vColor, 1.0 );\n gl_FragColor = color;\n }\n "},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",n),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=Dn.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){const s=new ph("temp",{width:e,height:1},i,!1),r=s.getContext(),n=r.createLinearGradient(0,0,e,0);t.forEach((e=>{n.addColorStop(e.location,e.color.toHexString())})),r.fillStyle=n,r.fillRect(0,0,e,1),s.update();const o=[],a=r.getImageData(0,0,e,1).data,l=1/255;for(let e=0;ekc.DISPLAY_SPHERE_AND_SPURS&&(e=kc.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,s=!0,r=3,n={}){if(this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=s,this.renderingGroupId=r,this.options=n,this.color=Y.White(),this._debugLines=new Array,this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,n.pauseAnimations=n.pauseAnimations??!0,n.returnToRest=n.returnToRest??!1,n.displayMode=n.displayMode??kc.DISPLAY_LINES,n.displayOptions=n.displayOptions??{},n.displayOptions.midStep=n.displayOptions.midStep??.235,n.displayOptions.midStepFactor=n.displayOptions.midStepFactor??.155,n.displayOptions.sphereBaseSize=n.displayOptions.sphereBaseSize??.15,n.displayOptions.sphereScaleUnit=n.displayOptions.sphereScaleUnit??2,n.displayOptions.sphereFactor=n.displayOptions.sphereFactor??.865,n.displayOptions.spurFollowsChild=n.displayOptions.spurFollowsChild??!1,n.displayOptions.showLocalAxes=n.displayOptions.showLocalAxes??!1,n.displayOptions.localAxesSize=n.displayOptions.localAxesSize??.075,n.computeBonesUsingShaders=n.computeBonesUsingShaders??!0,n.useAllBones=n.useAllBones??!0,this._boneIndices=new Set,!n.useAllBones){const e=t?.getVerticesData(Ki.MatricesIndicesKind),i=t?.getVerticesData(Ki.MatricesWeightsKind);if(e&&i)for(let t=0;tkc.DISPLAY_SPHERE_AND_SPURS&&(o=kc.DISPLAY_LINES),this.displayMode=o,this.update(),this._bindObs()}_bindObs(){this.displayMode===kc.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add((()=>{this._displayLinesUpdate()})))}update(){switch(this.displayMode){case kc.DISPLAY_LINES:this._displayLinesUpdate();break;case kc.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case kc.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,s=0,r=0,n=0){const o=U.Matrix[0],a=t.getParent();if(o.copyFrom(t.getLocalMatrix()),0!==s||0!==r||0!==n){const e=U.Matrix[1];B.IdentityToRef(e),e.setTranslationFromFloats(s,r,n),e.multiplyToRef(o,o)}a&&o.multiplyToRef(a.getAbsoluteMatrix(),o),o.multiplyToRef(i,o),e.x=o.m[12],e.y=o.m[13],e.z=o.m[14]}_getLinesForBonesWithLength(e,t){const i=e.length;let s,r;t?(s=t.getWorldMatrix(),r=t.position):(s=new B,r=e[0].position);let n=0;for(let t=0;t=0;s--){const t=e[s],o=t.getParent();if(!o||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let a=this._debugLines[i];a||(a=[w.Zero(),w.Zero()],this._debugLines[i]=a),t.getAbsolutePositionToRef(r,a[0]),o.getAbsolutePositionToRef(r,a[1]),a[0].subtractInPlace(n),a[1].subtractInPlace(n),i++}s||r.dispose()}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){null!==e&&-1!==e._index?(this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)):t.copyFrom(B.Identity())}_createSpur(e,t,i,s,r,n){const o=i.subtract(e),a=o.length(),l=o.normalize().scale(a),h=r.midStep||.165,c=r.midStepFactor||.215,u=l.scale(h),d=Rc("skeletonViewer",{shape:[new w(1,-1,0),new w(1,1,0),new w(-1,1,0),new w(-1,-1,0),new w(1,-1,0)],path:[w.Zero(),u,l],scaleFunction:e=>{switch(e){case 0:case 2:return 0;case 1:return a*c}return 0},sideOrientation:Un.DEFAULTSIDE,updatable:!1},n),p=d.getTotalVertices(),f=[],_=[];for(let e=0;e9?_.push(s.getIndex(),0,0,0):_.push(t.getIndex(),0,0,0);return d.position=e.clone(),d.setVerticesData(Ki.MatricesWeightsKind,f,!1),d.setVerticesData(Ki.MatricesIndicesKind,_,!1),d.convertToFlatShadedMesh(),d}_getBoundingSphereForBone(e){if(!this.mesh)return null;const t=this.mesh.getVerticesData(Ki.PositionKind),i=this.mesh.getIndices(),s=this.mesh.getVerticesData(Ki.MatricesWeightsKind),r=this.mesh.getVerticesData(Ki.MatricesIndicesKind);if(!(t&&i&&s&&r))return null;const n=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o=new w(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);let a=0;for(let l=0;l1e-5){w.FromArrayToRef(t,3*h,U.Vector3[0]),n.minimizeInPlace(U.Vector3[0]),o.maximizeInPlace(U.Vector3[0]),a++;break}}}return a>1?{center:w.Center(n,o),radius:w.Distance(n,o)/2}:null}_buildSpheresAndSpurs(e=!0){this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;const t=this.utilityLayer?.utilityLayerScene,i=this.skeleton.bones,s=[],r=[],n=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,t.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let o=Number.NEGATIVE_INFINITY;const a=this.options.displayOptions||{};for(let n=0;n0)l.children.forEach((i=>{const s=new B;i.getLocalMatrix().multiplyToRef(h,s);const n=new w;s.decompose(void 0,void 0,n);const u=w.Distance(c,n);u>o&&(o=u),e||r.push(this._createSpur(c,l,n,i,a,t))}));else{const i=this._getBoundingSphereForBone(l.getIndex());if(i&&(i.radius>o&&(o=i.radius),!e)){let e;const s=l.getParent();s?(this._getAbsoluteBindPoseToRef(s,h),h.decompose(void 0,void 0,U.Vector3[0]),e=c.subtract(U.Vector3[0]).normalize().scale(i.radius).add(c)):e=i.center.subtract(c).normalize().scale(i.radius).add(c),r.push(this._createSpur(c,l,e,null,a,t))}}const u=nc("skeletonViewer",{segments:6,diameter:a.sphereBaseSize||.2,updatable:!0},t),d=u.getTotalVertices(),p=[],f=[];for(let e=0;e{i[t]=e,i._internalCount++,6===i._internalCount&&s(i)}),void 0,void 0,!0,((e,t)=>{r&&e&&r(e.status+" "+e.statusText,t)}))},si.prototype._cascadeLoadFiles=function(e,t,i,s=null){const r=[];r._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,r,t,s)},si.prototype._cascadeLoadImgs=function(e,t,i,s,r=null,n){const o=[];o._internalCount=0;for(let a=0;a<6;a++)this._partialLoadImg(s[a],a,o,e,t,i,r,n)},si.prototype._partialLoadImg=function(e,t,i,s,r,n,o=null,a){const l=Si();ci(e,(e=>{i[t]=e,i._internalCount++,s&&s.removePendingData(l),6===i._internalCount&&n&&n(r,i)}),((e,t)=>{s&&s.removePendingData(l),o&&o(e,t)}),s?s.offlineProvider:null,a),s&&s.addPendingData(l)},si.prototype.createCubeTextureBase=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d=null,p=null,f=!1){const _=u||new ti(this,ei.Cube);_.isCube=!0,_.url=e,_.generateMipMaps=!s,_._lodGenerationScale=h,_._lodGenerationOffset=c,_._useSRGBBuffer=!!f&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!s),_!==u&&(_.label=e.substring(0,60)),this._doNotHandleContextLost||(_._extension=a,_._files=i);const m=e;this._transformTextureUrl&&!u&&(e=this._transformTextureUrl(e));const g=e.split("?")[0],v=g.lastIndexOf("."),x=a||(v>-1?g.substring(v).toLowerCase():"");let T=null;for(const e of si._TextureLoaders)if(e.canLoad(x)){T=e;break}const S=(u,g)=>{e===m?n&&u&&n(u.status+" "+u.statusText,g):(J.Warn(`Failed to load ${e}, falling back to the ${m}`),this.createCubeTextureBase(m,t,i,!!s,r,n,o,a,l,h,c,_,d,p,f))};if(T){const s=e=>{d&&d(_,e),T.loadCubeData(e,_,l,r,n)};i&&6===i.length?T.supportCascades?this._cascadeLoadFiles(t,(e=>s(e.map((e=>new Uint8Array(e))))),i,n):n?n("Textures type does not support cascades."):J.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>s(new Uint8Array(e))),void 0,void 0,!0,S)}else{if(!i||0===i.length)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(t,_,((e,t)=>{p&&p(e,t)}),i,n)}return this._internalTexturesCache.push(_),_};class zc{constructor(){this.occlusionInternalRetryCounter=0,this.isOcclusionQueryInProgress=!1,this.isOccluded=!1,this.occlusionRetryCount=-1,this.occlusionType=Wr.OCCLUSION_TYPE_NONE,this.occlusionQueryAlgorithmType=Wr.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE,this.forceRenderingWhenOccluded=!1}}si.prototype.getGPUFrameTimeCounter=function(){return null},si.prototype.captureGPUFrameTime=function(e){},si.prototype.createQuery=function(){return null},si.prototype.deleteQuery=function(e){return this},si.prototype.isQueryResultAvailable=function(e){return!1},si.prototype.getQueryResult=function(e){return 0},si.prototype.beginOcclusionQuery=function(e,t){return!1},si.prototype.endOcclusionQuery=function(e){return this},Object.defineProperty(Wr.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(Wr.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new zc),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(Wr.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(Wr.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Wr.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(Wr.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(Wr.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),Wr.prototype._checkOcclusionQuery=function(){const e=this._occlusionDataStorage;if(e.occlusionType===Wr.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;const t=this.getEngine();if(!t.getCaps().supportOcclusionQuery)return e.isOccluded=!1,!1;if(!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&null!==this._occlusionQuery&&void 0!==this._occlusionQuery)if(t.isQueryResultAvailable(this._occlusionQuery)){const i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,!(-1!==e.occlusionRetryCount&&e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==Wr.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==Wr.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}const i=this.getScene();if(i.getBoundingBoxRenderer){const s=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),this._occlusionQuery&&t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(s.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded};const Wc=new g,Hc=new g;Object.defineProperty(si.prototype,"onBeforeViewRenderObservable",{get:function(){return Wc}}),Object.defineProperty(si.prototype,"onAfterViewRenderObservable",{get:function(){return Hc}}),Object.defineProperty(si.prototype,"inputElement",{get:function(){return this._inputElement},set:function(e){this._inputElement!==e&&(this._inputElement=e,this._onEngineViewChanged?.())}}),si.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},si.prototype.registerView=function(e,t,i){this.views||(this.views=[]);for(const t of this.views)if(t.target===e)return t;const s=this.getRenderingCanvas();s&&(e.width=s.width,e.height=s.height);const r={target:e,camera:t,clearBeforeCopy:i,enabled:!0,id:(1e5*Math.random()).toFixed()};return this.views.push(r),t&&!Array.isArray(t)&&t.onDisposeObservable.add((()=>{this.unRegisterView(e)})),r},si.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(const t of this.views)if(t.target===e){const e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},si.prototype._renderViewStep=function(e){const t=e.target,i=t.getContext("2d");if(!i)return!0;const s=this.getRenderingCanvas();Wc.notifyObservers(e);const r=e.camera;let n=null,o=null,a=null;if(r&&(a=Array.isArray(r)?r[0].getScene():r.getScene(),n=a.activeCamera,o=a.activeCameras,this.activeView=e,Array.isArray(r)?a.activeCameras=r:(a.activeCamera=r,a.activeCameras=null)),e.customResize)e.customResize(t);else{const e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),r=e!==t.width||s.width!==t.width||i!==t.height||s.height!==t.height;t.clientWidth&&t.clientHeight&&r&&(t.width=e,t.height=i,this.setSize(e,i))}return!(!s.width||!s.height||(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,s.width,s.height),i.drawImage(s,0,0),a&&(a.activeCameras=o,a.activeCamera=n),Hc.notifyObservers(e),0))},si.prototype._renderViews=function(){if(!this.views||0===this.views.length)return!1;if(!this.getRenderingCanvas())return!1;let e;for(const t of this.views)if(t.enabled)if(t.target!==this.inputElement){if(!this._renderViewStep(t))return!1}else e=t;return!(e&&!this._renderViewStep(e)||(this.activeView=null,0))},si.prototype._debugPushGroup=function(e,t){},si.prototype._debugPopGroup=function(e){},si.prototype._debugInsertMarker=function(e,t){},si.prototype._debugFlushPendingCommands=function(){};class Xc{constructor(){this._timeElapsedQueryEnded=!1}}Br.prototype.createQuery=function(){const e=this._gl.createQuery();if(!e)throw new Error("Unable to create Occlusion Query");return e},Br.prototype.deleteQuery=function(e){return this._gl.deleteQuery(e),this},Br.prototype.isQueryResultAvailable=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT_AVAILABLE)},Br.prototype.getQueryResult=function(e){return this._gl.getQueryParameter(e,this._gl.QUERY_RESULT)},Br.prototype.beginOcclusionQuery=function(e,t){const i=this._getGlAlgorithmType(e);return this._gl.beginQuery(i,t),!0},Br.prototype.endOcclusionQuery=function(e){const t=this._getGlAlgorithmType(e);return this._gl.endQuery(t),this},Br.prototype._createTimeQuery=function(){const e=this.getCaps().timerQuery;return e.createQueryEXT?e.createQueryEXT():this.createQuery()},Br.prototype._deleteTimeQuery=function(e){const t=this.getCaps().timerQuery;t.deleteQueryEXT?t.deleteQueryEXT(e):this.deleteQuery(e)},Br.prototype._getTimeQueryResult=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT):this.getQueryResult(e)},Br.prototype._getTimeQueryAvailability=function(e){const t=this.getCaps().timerQuery;return t.getQueryObjectEXT?t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT):this.isQueryResultAvailable(e)},Br.prototype.startTimeQuery=function(){const e=this.getCaps(),t=e.timerQuery;if(!t)return null;const i=new Xc;if(this._gl.getParameter(t.GPU_DISJOINT_EXT),e.canUseTimestampForTimerQuery)i._startTimeQuery=this._createTimeQuery(),i._startTimeQuery&&t.queryCounterEXT(i._startTimeQuery,t.TIMESTAMP_EXT);else{if(this._currentNonTimestampToken)return this._currentNonTimestampToken;i._timeElapsedQuery=this._createTimeQuery(),i._timeElapsedQuery&&(t.beginQueryEXT?t.beginQueryEXT(t.TIME_ELAPSED_EXT,i._timeElapsedQuery):this._gl.beginQuery(t.TIME_ELAPSED_EXT,i._timeElapsedQuery)),this._currentNonTimestampToken=i}return i},Br.prototype.endTimeQuery=function(e){const t=this.getCaps(),i=t.timerQuery;if(!i||!e)return-1;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery)return-1;e._endTimeQuery||(e._endTimeQuery=this._createTimeQuery(),e._endTimeQuery&&i.queryCounterEXT(e._endTimeQuery,i.TIMESTAMP_EXT))}else if(!e._timeElapsedQueryEnded){if(!e._timeElapsedQuery)return-1;i.endQueryEXT?i.endQueryEXT(i.TIME_ELAPSED_EXT):(this._gl.endQuery(i.TIME_ELAPSED_EXT),this._currentNonTimestampToken=null),e._timeElapsedQueryEnded=!0}const s=this._gl.getParameter(i.GPU_DISJOINT_EXT);let r=!1;if(e._endTimeQuery?r=this._getTimeQueryAvailability(e._endTimeQuery):e._timeElapsedQuery&&(r=this._getTimeQueryAvailability(e._timeElapsedQuery)),r&&!s){let i=0;if(t.canUseTimestampForTimerQuery){if(!e._startTimeQuery||!e._endTimeQuery)return-1;const t=this._getTimeQueryResult(e._startTimeQuery);i=this._getTimeQueryResult(e._endTimeQuery)-t,this._deleteTimeQuery(e._startTimeQuery),this._deleteTimeQuery(e._endTimeQuery),e._startTimeQuery=null,e._endTimeQuery=null}else{if(!e._timeElapsedQuery)return-1;i=this._getTimeQueryResult(e._timeElapsedQuery),this._deleteTimeQuery(e._timeElapsedQuery),e._timeElapsedQuery=null,e._timeElapsedQueryEnded=!1}return i}return-1},Br.prototype._captureGPUFrameTime=!1,Br.prototype._gpuFrameTime=new Is,Br.prototype.getGPUFrameTimeCounter=function(){return this._gpuFrameTime},Br.prototype.captureGPUFrameTime=function(e){e!==this._captureGPUFrameTime&&(this._captureGPUFrameTime=e,e?(this._onBeginFrameObserver=this.onBeginFrameObservable.add((()=>{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())})),this._onEndFrameObserver=this.onEndFrameObservable.add((()=>{if(!this._gpuFrameTimeToken)return;const e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))}))):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},Br.prototype._getGlAlgorithmType=function(e){return e===Wr.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED},Br.prototype.createTransformFeedback=function(){const e=this._gl.createTransformFeedback();if(!e)throw new Error("Unable to create Transform Feedback");return e},Br.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},Br.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},Br.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},Br.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},Br.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},Br.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},Yi.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;const s=this._getInternalFormat(e.format),r=this._getRGBABufferInternalSizedFormat(0,e.format),n=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);const t=e._workingCanvas.getContext("2d");if(!t)throw new Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,r,s,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},Yi.prototype.restoreSingleAttachment=function(){const e=this._gl;this.bindAttachments([e.BACK])},Yi.prototype.restoreSingleAttachmentForRenderTarget=function(){const e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},Yi.prototype.buildTextureLayout=function(e){const t=this._gl,i=[];for(let s=0;s1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],s.readBuffer(r[t]),s.drawBuffers(r),s.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,s.COLOR_BUFFER_BIT,s.NEAREST)}for(let e=0;e1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];s.drawBuffers(r)}for(let i=0;i1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(a=t.depthTextureFormat)),g.label=t?.label??"MultiRenderTargetWrapper";const v=this._gl,x=v.createFramebuffer();this._bindUnboundFramebuffer(x);const T=e.width||e,S=e.height||e,E=[],b=[],C=this.webGLVersion>1&&o&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),y=this._setupFramebufferDepthAttachments(!C&&n,!o&&r,T,S);g._framebuffer=x,g._depthStencilBuffer=y,g._generateDepthBuffer=!o&&r,g._generateStencilBuffer=!C&&n,g._attachments=b;for(let e=0;e1||this.isWebGPU);const f=this.webGLVersion>1,_=v[f?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(b.push(_),-1===o)continue;const g=new ti(this,ei.MultiRenderTarget);E[e]=g,v.activeTexture(v["TEXTURE"+e]),v.bindTexture(o,g._hardwareTexture.underlyingResource),v.texParameteri(o,v.TEXTURE_MAG_FILTER,l.mag),v.texParameteri(o,v.TEXTURE_MIN_FILTER,l.min),v.texParameteri(o,v.TEXTURE_WRAP_S,v.CLAMP_TO_EDGE),v.texParameteri(o,v.TEXTURE_WRAP_T,v.CLAMP_TO_EDGE);const x=this._getRGBABufferInternalSizedFormat(i,n,r),C=this._getInternalFormat(n),y=this._getWebGLTextureType(i);if(!f||35866!==o&&32879!==o)if(34067===o){for(let e=0;e<6;e++)v.texImage2D(v.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,x,T,S,0,C,y,null);g.isCube=!0}else v.texImage2D(v.TEXTURE_2D,0,x,T,S,0,C,y,null);else 35866===o?g.is2DArray=!0:g.is3D=!0,g.baseDepth=g.depth=a,v.texImage3D(o,0,x,T,S,a,0,C,y,null);s&&v.generateMipmap(o),this._bindTextureDirectly(o,null),g.baseWidth=T,g.baseHeight=S,g.width=T,g.height=S,g.isReady=!0,g.samples=1,g.generateMipMaps=s,g.samplingMode=t,g.type=i,g._useSRGBBuffer=r,g.format=n,this._internalTexturesCache.push(g)}if(o&&this._caps.depthTextureExtension){const e=new ti(this,ei.Depth);let t=5,i=v.DEPTH_COMPONENT16,r=v.DEPTH_COMPONENT,n=v.UNSIGNED_SHORT,o=v.DEPTH_ATTACHMENT;this.webGLVersion<2?i=v.DEPTH_COMPONENT:14===a?(t=1,n=v.FLOAT,i=v.DEPTH_COMPONENT32F):18===a?(t=0,n=v.FLOAT_32_UNSIGNED_INT_24_8_REV,i=v.DEPTH32F_STENCIL8,r=v.DEPTH_STENCIL,o=v.DEPTH_STENCIL_ATTACHMENT):16===a?(t=0,n=v.UNSIGNED_INT,i=v.DEPTH_COMPONENT24,o=v.DEPTH_ATTACHMENT):13!==a&&17!==a||(t=12,n=v.UNSIGNED_INT_24_8,i=v.DEPTH24_STENCIL8,r=v.DEPTH_STENCIL,o=v.DEPTH_STENCIL_ATTACHMENT),v.activeTexture(v.TEXTURE0),v.bindTexture(v.TEXTURE_2D,e._hardwareTexture.underlyingResource),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_MAG_FILTER,v.NEAREST),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_MIN_FILTER,v.NEAREST),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_WRAP_S,v.CLAMP_TO_EDGE),v.texParameteri(v.TEXTURE_2D,v.TEXTURE_WRAP_T,v.CLAMP_TO_EDGE),v.texImage2D(v.TEXTURE_2D,0,i,T,S,0,r,n,null),v.framebufferTexture2D(v.FRAMEBUFFER,o,v.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=T,e.baseHeight=S,e.width=T,e.height=S,e.isReady=!0,e.samples=1,e.generateMipMaps=s,e.samplingMode=1,e.format=a,e.type=t,E[l]=e,this._internalTexturesCache.push(e)}return g.setTextures(E),i&&v.drawBuffers(b),this._bindUnboundFramebuffer(null),g.setLayerAndFaceIndices(_,f),this.resetTextureCache(),g},Yi.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const s=e._attachments.length;if(0===s)return 1;const r=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);const n=!!e._depthStencilBuffer;if(n&&(r.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(r.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof r.renderbufferStorageMultisample){const n=r.createFramebuffer();if(!n)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);const o=[];for(let t=0;t1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(s.width,s.height,t,-1,this._getRGBABufferInternalSizedFormat(s.type,s.format,s._useSRGBBuffer),a);if(!l)throw new Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(l),s.samples=t,o.push(a)}i&&r.drawBuffers(o)}else this._bindUnboundFramebuffer(e._framebuffer);return n&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},Yi.prototype._createDepthStencilCubeTexture=function(e,t){const i=new ti(this,ei.DepthStencil);if(i.isCube=!0,1===this.webGLVersion)return J.Error("Depth cube texture is not supported by WebGL 1."),i;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t},r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,i,!0),this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction);for(let t=0;t<6;t++)s.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH24_STENCIL8,e,e,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH_COMPONENT24,e,e,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(i),i},Yi.prototype._setCubeMapTextureParams=function(e,t,i){const s=this._gl;s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,t?s.LINEAR_MIPMAP_LINEAR:s.LINEAR),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null)},Yi.prototype.createCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,p=!1){const f=this._gl;return this.createCubeTextureBase(e,t,i,!!s,r,n,o,a,l,h,c,u,(e=>this._bindTextureDirectly(f.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const i=this.needPOTTextures?Ri(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,n=i,a=[f.TEXTURE_CUBE_MAP_POSITIVE_X,f.TEXTURE_CUBE_MAP_POSITIVE_Y,f.TEXTURE_CUBE_MAP_POSITIVE_Z,f.TEXTURE_CUBE_MAP_NEGATIVE_X,f.TEXTURE_CUBE_MAP_NEGATIVE_Y,f.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(f.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const l=o?this._getInternalFormat(o,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:f.RGBA;let h=o?this._getInternalFormat(o):f.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(h=l);for(let e=0;e1,e=>e.y,e=>e.z,e=>e.x,e=>e.x*e.y,e=>e.y*e.z,e=>3*e.z*e.z-1,e=>e.x*e.z,e=>e.x*e.x-e.y*e.y],$c=(e,t)=>Yc[e]*jc[e](t),Kc=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4];class qc{constructor(){this.preScaled=!1,this.l00=w.Zero(),this.l1_1=w.Zero(),this.l10=w.Zero(),this.l11=w.Zero(),this.l2_2=w.Zero(),this.l2_1=w.Zero(),this.l20=w.Zero(),this.l21=w.Zero(),this.l22=w.Zero()}addLight(e,t,i){U.Vector3[0].set(t.r,t.g,t.b);const s=U.Vector3[0],r=U.Vector3[1];s.scaleToRef(i,r),r.scaleToRef($c(0,e),U.Vector3[2]),this.l00.addInPlace(U.Vector3[2]),r.scaleToRef($c(1,e),U.Vector3[2]),this.l1_1.addInPlace(U.Vector3[2]),r.scaleToRef($c(2,e),U.Vector3[2]),this.l10.addInPlace(U.Vector3[2]),r.scaleToRef($c(3,e),U.Vector3[2]),this.l11.addInPlace(U.Vector3[2]),r.scaleToRef($c(4,e),U.Vector3[2]),this.l2_2.addInPlace(U.Vector3[2]),r.scaleToRef($c(5,e),U.Vector3[2]),this.l2_1.addInPlace(U.Vector3[2]),r.scaleToRef($c(6,e),U.Vector3[2]),this.l20.addInPlace(U.Vector3[2]),r.scaleToRef($c(7,e),U.Vector3[2]),this.l21.addInPlace(U.Vector3[2]),r.scaleToRef($c(8,e),U.Vector3[2]),this.l22.addInPlace(U.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(Kc[0]),this.l1_1.scaleInPlace(Kc[1]),this.l10.scaleInPlace(Kc[2]),this.l11.scaleInPlace(Kc[3]),this.l2_2.scaleInPlace(Kc[4]),this.l2_1.scaleInPlace(Kc[5]),this.l20.scaleInPlace(Kc[6]),this.l21.scaleInPlace(Kc[7]),this.l22.scaleInPlace(Kc[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(Yc[0]),this.l1_1.scaleInPlace(Yc[1]),this.l10.scaleInPlace(Yc[2]),this.l11.scaleInPlace(Yc[3]),this.l2_2.scaleInPlace(Yc[4]),this.l2_1.scaleInPlace(Yc[5]),this.l20.scaleInPlace(Yc[6]),this.l21.scaleInPlace(Yc[7]),this.l22.scaleInPlace(Yc[8])}updateFromArray(e){return w.FromArrayToRef(e[0],0,this.l00),w.FromArrayToRef(e[1],0,this.l1_1),w.FromArrayToRef(e[2],0,this.l10),w.FromArrayToRef(e[3],0,this.l11),w.FromArrayToRef(e[4],0,this.l2_2),w.FromArrayToRef(e[5],0,this.l2_1),w.FromArrayToRef(e[6],0,this.l20),w.FromArrayToRef(e[7],0,this.l21),w.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return w.FromFloatsToRef(e[0],e[1],e[2],this.l00),w.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),w.FromFloatsToRef(e[6],e[7],e[8],this.l10),w.FromFloatsToRef(e[9],e[10],e[11],this.l11),w.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),w.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),w.FromFloatsToRef(e[18],e[19],e[20],this.l20),w.FromFloatsToRef(e[21],e[22],e[23],this.l21),w.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new qc).updateFromArray(e)}static FromPolynomial(e){const t=new qc;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}}class Qc{constructor(){this.x=w.Zero(),this.y=w.Zero(),this.z=w.Zero(),this.xx=w.Zero(),this.yy=w.Zero(),this.zz=w.Zero(),this.xy=w.Zero(),this.yz=w.Zero(),this.zx=w.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=qc.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){U.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=U.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),U.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),U.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(U.Vector3[0]).addInPlace(U.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(U.Vector3[0]).subtractInPlace(U.Vector3[1]),this.zz.copyFrom(e.l00),U.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(U.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return(new Qc).updateFromHarmonics(e)}static FromArray(e){const t=new Qc;return w.FromArrayToRef(e[0],0,t.x),w.FromArrayToRef(e[1],0,t.y),w.FromArrayToRef(e[2],0,t.z),w.FromArrayToRef(e[3],0,t.xx),w.FromArrayToRef(e[4],0,t.yy),w.FromArrayToRef(e[5],0,t.zz),w.FromArrayToRef(e[6],0,t.yz),w.FromArrayToRef(e[7],0,t.zx),w.FromArrayToRef(e[8],0,t.xy),t}}class Zc{constructor(e,t,i,s){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=s}}class Jc{static ConvertCubeMapTextureToSphericalPolynomial(e){if(!e.isCube)return null;e.getScene()?.getEngine().flushFramebuffer();const t=e.getSize().width,i=e.readPixels(0,void 0,void 0,!1),s=e.readPixels(1,void 0,void 0,!1);let r,n;e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),n=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),n=e.readPixels(3,void 0,void 0,!1));const o=e.readPixels(4,void 0,void 0,!1),a=e.readPixels(5,void 0,void 0,!1),l=e.gammaSpace;let h=0;return 1!=e.textureType&&2!=e.textureType||(h=1),new Promise((e=>{Promise.all([s,i,r,n,o,a]).then((([i,s,r,n,o,a])=>{const c={size:t,right:s,left:i,up:r,down:n,front:o,back:a,format:5,type:h,gammaSpace:l};e(this.ConvertCubeMapToSphericalPolynomial(c))}))}))}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new qc;let i=0;const s=2/e.size,r=s,n=.5*s,o=n-1;for(let a=0;a<6;a++){const l=this._FileFaces[a],h=e[l.name];let c=o;const u=5===e.format?4:3;for(let a=0;ag){const t=g/e;f*=t,_*=t,m*=t}}else f=G.Clamp(f,0,g),_=G.Clamp(_,0,g),m=G.Clamp(m,0,g);const v=new Y(f,_,m);t.addLight(o,v,p),i+=p,d+=s}c+=r}}const a=4*Math.PI*6/6/i;return t.scaleInPlace(a),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),Qc.FromHarmonics(t)}}Jc._FileFaces=[new Zc("right",new w(1,0,0),new w(0,0,-1),new w(0,-1,0)),new Zc("left",new w(-1,0,0),new w(0,0,1),new w(0,-1,0)),new Zc("up",new w(0,1,0),new w(1,0,0),new w(0,0,1)),new Zc("down",new w(0,-1,0),new w(1,0,0),new w(0,0,-1)),new Zc("front",new w(0,0,1),new w(1,0,0),new w(0,-1,0)),new Zc("back",new w(0,0,-1),new w(-1,0,0),new w(0,-1,0))],Jc.MAX_HDRI_VALUE=4096,Jc.PRESERVE_CLAMPED_COLORS=!1;Ft.ShadersStore.lodPixelShader="#extension GL_EXT_shader_texture_lod : enable\nprecision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform sampler2D textureSampler;uniform float lod;uniform vec2 texSize;uniform bool gamma;void main(void)\n{gl_FragColor=textureLod(textureSampler,vUV,lod);if (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";function eu(e,t,i,s,r,n,o,a){const l=t.getEngine();return t.isReady=!1,r=r??t.samplingMode,s=s??t.type,n=n??t.format,o=o??t.width,a=a??t.height,-1===s&&(s=0),new Promise((h=>{const c=new Ko("postprocess",e,null,null,1,null,r,l,!1,void 0,s,void 0,null,!1,n);c.externalTextureSamplerBinding=!0;const u=l.createRenderTargetTexture({width:o,height:a},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:r,type:s,format:n});c.getEffect().executeWhenCompiled((()=>{c.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([c],u,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),c&&c.dispose(),u._swapAndDie(t),t.type=s,t.format=5,t.isReady=!0,h(t)}))}))}let tu,iu;function su(e){tu||(tu=new Float32Array(1),iu=new Int32Array(tu.buffer)),tu[0]=e;const t=iu[0];let i=t>>16&32768,s=t>>12&2047;const r=t>>23&255;return r<103?i:r>142?(i|=31744,i|=(255==r?0:1)&&8388607&t,i):r<113?(s|=2048,i|=(s>>114-r)+(s>>113-r&1),i):(i|=r-112<<10|s>>1,i+=1&s,i)}function ru(e){const t=(32768&e)>>15,i=(31744&e)>>10,s=1023&e;return 0===i?(t?-1:1)*Math.pow(2,-14)*(s/Math.pow(2,10)):31==i?s?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+s/Math.pow(2,10))}Ft.ShadersStore.lodCubePixelShader="precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform samplerCube textureSampler;uniform float lod;uniform bool gamma;void main(void)\n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x),lod);\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x),lod);\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x),lod);\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x),lod);\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001),lod);\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001),lod);\n#endif\nif (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";const nu=async function(e,t,i,s=0,r=0){return!e.isReady()&&e._texture&&await new Promise(((t,i)=>{null!==e._texture?e._texture.onLoadedObservable.addOnce((()=>{t(0)})):i(0)})),await(async(e,t,i,s,r)=>{const n=e.getScene(),o=n.getEngine();let a;if(e.isCube){const e=["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"];a=new Ko("lodCube","lodCube",["lod","gamma"],null,1,null,Zn.NEAREST_NEAREST_MIPNEAREST,o,!1,e[s])}else a=new Ko("lod","lod",["lod","gamma"],null,1,null,Zn.NEAREST_NEAREST_MIPNEAREST,o);await new Promise((e=>{a.getEffect().executeWhenCompiled((()=>{e(0)}))}));const l=new da("temp",{width:t,height:i},n,!1);a.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",r),t.setBool("gamma",e.gammaSpace)};const h=e.getInternalTexture();try{if(l.renderTarget&&h){const s=h.samplingMode;0!==r?e.updateSamplingMode(Zn.NEAREST_NEAREST_MIPNEAREST):e.updateSamplingMode(Zn.NEAREST_NEAREST),n.postProcessManager.directRender([a],l.renderTarget,!0),e.updateSamplingMode(s);const c=await o.readPixels(0,0,t,i),u=new Uint8Array(c.buffer,0,c.byteLength);return o.unBindFramebuffer(l.renderTarget),u}throw Error("Render to texture failed.")}finally{l.dispose(),a.dispose()}})(e,t,i,s,r)},ou=131072,au=131072;function lu(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}const hu=lu("DXT1"),cu=lu("DXT3"),uu=lu("DXT5"),du=lu("DX10");class pu{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35);let s=1;t[2]&ou&&(s=Math.max(1,t[7]));const r=t[21],n=r===du?i[32]:0;let o=0;switch(r){case 113:o=2;break;case 116:o=1;break;case du:if(10===n){o=2;break}if(2===n){o=1;break}}return{width:t[4],height:t[3],mipmapCount:s,isFourCC:!(4&~t[20]),isRGB:!(64&~t[20]),isLuminance:(t[20]&au)===au,isCube:!(512&~t[28]),isCompressed:r===hu||r===cu||r===uu,dxgiFormat:n,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,s,r,n){const o=new Float32Array(s),a=new Uint16Array(r,i);let l=0;for(let i=0;i>8)}static _GetRGBArrayBuffer(e,t,i,s,r,n,o,a){const l=new Uint8Array(s),h=new Uint8Array(r,i);let c=0;for(let i=0;i>8&255,C>>16&255,C>>24&255))])}var C;const y=pu._ExtractLongWordOrder(u[23]),A=pu._ExtractLongWordOrder(u[24]),R=pu._ExtractLongWordOrder(u[25]),I=pu._ExtractLongWordOrder(u[26]);b&&(T=e._getRGBABufferInternalSizedFormat(s.textureType)),g=1,u[2]&ou&&!1!==r&&(g=Math.max(1,u[7]));const P=a||0,M=e.getCaps();for(let r=P;r0?s.sphericalPolynomial=Jc.ConvertCubeMapToSphericalPolynomial({size:u[4],right:h[0],left:h[1],up:h[2],down:h[3],front:h[4],back:h[5],format:5,type:1,gammaSpace:!1}):s.sphericalPolynomial=void 0}}function fu(e){if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some((t=>{const i="\\b"+t+"\\b";return e&&(e===t||e.match(new RegExp(i,"g")))})))return e;const t=e.lastIndexOf("."),i=e.lastIndexOf("?"),s=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+s}pu.StoreLODInAlphaChannel=!1,Yi.prototype.createPrefilteredCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(r&&r(null));const n=e.texture;if(l?e.info.sphericalPolynomial&&(n._sphericalPolynomial=e.info.sphericalPolynomial):n._sphericalPolynomial=new Qc,n._source=ei.CubePrefiltered,this.getCaps().textureLOD)return void(r&&r(n));const o=this._gl,a=e.width;if(!a)return;const h=[];for(let r=0;r<3;r++){const l=1-r/2,c=s,u=G.Log2(a)*i+s,d=c+(u-c)*l,p=Math.round(Math.min(Math.max(d,0),u)),f=new ti(this,ei.Temp);if(f.type=n.type,f.format=n.format,f.width=Math.pow(2,Math.max(G.Log2(a)-p,0)),f.height=f.width,f.isCube=!0,f._cachedWrapU=0,f._cachedWrapV=0,this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,f,!0),f.samplingMode=2,o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),e.isDDS){const t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),pu.UploadDDSLevels(this,f,i,t,!0,6,p)}else J.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null);const _=new qn(t);_._isCube=!0,_._texture=f,f.isReady=!0,h.push(_)}n._lodTextureHigh=h[2],n._lodTextureMid=h[1],n._lodTextureLow=h[0],r&&r(n)}),n,o,a,l,i,s)},Object.defineProperty(Br.prototype,"texturesSupported",{get:function(){const e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(Br.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),Br.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},Br.prototype.setTextureFormatToUse=function(e){const t=this.texturesSupported;for(let i=0,s=t.length;i{this._flush()}))}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}}_u.DEFAULT_BUFFER_SIZE=65536;Ft.ShadersStore.rgbdDecodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}";class mu{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),s=i.getCaps(),r=t.isReady;let n=!1;s.textureHalfFloatRender&&s.textureHalfFloatLinearFiltering?(n=!0,t.type=2):s.textureFloatRender&&s.textureFloatLinearFiltering&&(n=!0,t.type=1),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const o=()=>{const s=new Ko("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);s.externalTextureSamplerBinding=!0;const r=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});s.getEffect().executeWhenCompiled((()=>{s.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([s],r,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),s&&s.dispose(),r._swapAndDie(t),t.isReady=!0}))};n&&(r?o():e.onLoadObservable.addOnce(o))}static EncodeTextureToRGBD(e,t,i=0){return eu("rgbdEncode",e,t,i,1,5)}}qn.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(qn.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=Jc.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then((e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))),null}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});Ft.ShadersStore.rgbdEncodePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}";const gu="image/png",vu=2,xu=[134,22,135,150,246,214,150,54];function Tu(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;for(let e=0;evu)throw new Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "${vu}".`);return 2===e.version?e:e={...e,version:2,imageType:gu}}function Eu(e,t){const i=(t=Su(t)).specular;let s=G.Log2(t.width);if(s=Math.round(s)+1,i.mipmaps.length!==6*s)throw new Error(`Unsupported specular mipmaps number "${i.mipmaps.length}"`);const r=new Array(s);for(let t=0;tCu(t,r,n,a,f,c,s,o,h,l,e)));else{const t=new Image;t.src=f,_=new Promise(((i,u)=>{t.onload=()=>{Cu(t,r,n,a,f,c,s,o,h,l,e).then((()=>i())).catch((e=>{u(e)}))},t.onerror=e=>{u(e)}}))}u.push(_)}if(t.length{l&&(r._releaseTexture(e),l._swapAndDie(e)),a&&a.dispose(),o&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))}))}(e,Eu(t,i),i.imageType)):Promise.resolve()}function Cu(e,t,i,s,r,n,o,a,l,h,c){return new Promise(((u,d)=>{if(i){const i=t.createTexture(null,!0,!0,null,1,null,(e=>{d(e)}),e);s.getEffect().executeWhenCompiled((()=>{s.externalTextureSamplerBinding=!0,s.onApply=s=>{s._bindTexture("textureSampler",i),s.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([s],h,!0,n,o),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(r),u())}))}else{if(t._uploadImageToTexture(c,e,n,o),a){const i=l[o];i&&t._uploadImageToTexture(i._texture,e,n,0)}u()}}))}function yu(e,t){const i=(t=Su(t)).irradiance;if(!i)return;const s=new Qc;w.FromArrayToRef(i.x,0,s.x),w.FromArrayToRef(i.y,0,s.y),w.FromArrayToRef(i.z,0,s.z),w.FromArrayToRef(i.xx,0,s.xx),w.FromArrayToRef(i.yy,0,s.yy),w.FromArrayToRef(i.zz,0,s.zz),w.FromArrayToRef(i.yz,0,s.yz),w.FromArrayToRef(i.zx,0,s.zx),w.FromArrayToRef(i.xy,0,s.xy),e._sphericalPolynomial=s}function Au(e,t,i,s){let r=s,n=0,o="";for(;r=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function Pu(e){let t=0,i="",s=!1;const r=[];for(;t=0&&e.charAt(t)!==i&&(!s||e.charAt(t)!==s);)t--;return t}function Du(e,t,i,s){let r=e.indexOf(t);if(r<0)return e;if(i){for(;r++=0&&d.push(t.substring(i+1))}"void"!==r&&d.push("return"),this._functionDescr.push({name:n,type:r,parameters:d,body:c,callIndex:0}),e=h+1;const p=t>0?this._sourceCode.substring(0,t):"",f=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&J.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:s,parameters:r,body:n}=t;let o=0;for(;o{const t=[];let i=0,s=0;for(;i0?this._sourceCode.substring(0,a):"";const g=h+1{const a=r[0];return Iu(e.charAt(a-1))||Iu(e.charAt(a+n))?t[s]:o}))}return e}}Ou._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;const Nu=/(flat\s)?\s*varying\s*.*/;class wu{constructor(){this.shaderLanguage=ht.GLSL}initializeShaders(e){this._nativeProcessingContext=e,this._nativeProcessingContext&&(this._nativeProcessingContext.remappedAttributeNames={},this._nativeProcessingContext.injectInVertexMain="")}attributeProcessor(e){if(!this._nativeProcessingContext)return e.replace("attribute","in");const t=/\s*(?:attribute|in)\s+(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==t){const i=t[1],s=t[2],r=this._nativeProcessingContext.vertexBufferKindToNumberOfComponents[s];if(void 0!==r){const n=r<0?-1===r?"int":"ivec"+-r:1===r?"uint":"uvec"+r,o=`_int_${s}_`;e=e.replace(t[0],`in ${n} ${o}; ${i} ${s};`),this._nativeProcessingContext.injectInVertexMain+=`${s} = ${i}(${o});\n`,this._nativeProcessingContext.remappedAttributeNames[s]=o}else e=e.replace(t[0],`in ${i} ${s};`)}return e}varyingCheck(e,t){return Nu.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){const s=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),i){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(s||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else if(this._nativeProcessingContext?.injectInVertexMain&&(e=Du(e,"void main",this._nativeProcessingContext.injectInVertexMain)),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;return e}}class Fu{get isReady(){if(this.compilationError){const e=this.compilationError.message;throw new Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}constructor(e,t,i){this.isCompiled=!1,this.vertexBufferKindToType={},this._valueCache={},this._engine=e,this.isAsync=t,this.shaderProcessingContext=i}_fillEffectInformation(e,t,i,s,r,n,o,a){const l=this._engine;if(l.supportsUniformBuffers)for(const i in t)e.bindUniformBlock(i,t[i]);let h;for(this._engine.getUniforms(this,i).forEach(((e,t)=>{s[i[t]]=e})),this._uniforms=s,h=0;h{n[e]=t})),a.push(...l.getAttributes(this,o))}setEngine(e){this._engine=e}dispose(){this._uniforms={}}_cacheMatrix(e,t){const i=this._valueCache[e],s=t.updateFlag;return(void 0===i||i!==s)&&(this._valueCache[e]=s,!0)}_cacheFloat2(e,t,i){let s=this._valueCache[e];if(!s)return s=[t,i],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),r}_cacheFloat3(e,t,i,s){let r=this._valueCache[e];if(!r)return r=[t,i,s],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==i&&(r[1]=i,n=!0),r[2]!==s&&(r[2]=s,n=!0),n}_cacheFloat4(e,t,i,s,r){let n=this._valueCache[e];if(!n)return n=[t,i,s,r],this._valueCache[e]=n,!0;let o=!1;return n[0]!==t&&(n[0]=t,o=!0),n[1]!==i&&(n[1]=i,o=!0),n[2]!==s&&(n[2]=s,o=!0),n[3]!==r&&(n[3]=r,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setUInt3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setUInt4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setUInt4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this._engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this._engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this._engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this._engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,s){this._cacheFloat3(e,t,i,s)&&(this._engine.setFloat3(this._uniforms[e],t,i,s)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,s,r){this._cacheFloat4(e,t,i,s,r)&&(this._engine.setFloat4(this._uniforms[e],t,i,s,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}}class Lu extends jo{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,s){super(e,t,i,s),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=s}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class Bu{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}}function Vu(e,t){switch(e){case 15:return _native.Engine.TEXTURE_FORMAT_D16;case 16:return _native.Engine.TEXTURE_FORMAT_D24;case 13:return _native.Engine.TEXTURE_FORMAT_D24S8;case 14:return _native.Engine.TEXTURE_FORMAT_D32F;case 36492:return _native.Engine.TEXTURE_FORMAT_BC7;case 36494:return _native.Engine.TEXTURE_FORMAT_BC6H;case 33779:return _native.Engine.TEXTURE_FORMAT_BC3;case 33778:return _native.Engine.TEXTURE_FORMAT_BC2;case 33777:case 33776:return _native.Engine.TEXTURE_FORMAT_BC1;case 37808:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case 36196:return _native.Engine.TEXTURE_FORMAT_ETC1;case 37492:return _native.Engine.TEXTURE_FORMAT_ETC2;case 37496:return _native.Engine.TEXTURE_FORMAT_ETC2A;case 4:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGB8;case 3:return _native.Engine.TEXTURE_FORMAT_RGB8S;case 6:return _native.Engine.TEXTURE_FORMAT_RGB8I;case 7:return _native.Engine.TEXTURE_FORMAT_RGB8U}break;case 5:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGBA8;case 1:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case 2:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case 3:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case 4:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case 5:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case 6:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case 7:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break;case 6:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_R8;case 1:return _native.Engine.TEXTURE_FORMAT_R32F;case 2:return _native.Engine.TEXTURE_FORMAT_R16F;case 3:return _native.Engine.TEXTURE_FORMAT_R8S;case 4:return _native.Engine.TEXTURE_FORMAT_R16S;case 5:return _native.Engine.TEXTURE_FORMAT_R16U;case 6:return _native.Engine.TEXTURE_FORMAT_R32I;case 7:return _native.Engine.TEXTURE_FORMAT_R32U}break;case 7:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RG8;case 1:return _native.Engine.TEXTURE_FORMAT_RG32F;case 2:return _native.Engine.TEXTURE_FORMAT_RG16F;case 3:return _native.Engine.TEXTURE_FORMAT_RG8S;case 4:return _native.Engine.TEXTURE_FORMAT_RG16S;case 5:return _native.Engine.TEXTURE_FORMAT_RG16U;case 6:return _native.Engine.TEXTURE_FORMAT_RG32I;case 7:return _native.Engine.TEXTURE_FORMAT_RG32U}break;case 12:if(0===t)return _native.Engine.TEXTURE_FORMAT_BGRA8}throw new Qe(`Unsupported texture format or type: format ${e}, type ${t}.`,1e3)}function Uu(e){switch(e){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw new Error(`Unsupported sampling mode: ${e}.`)}}function ku(e){switch(e){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw new Error("Unexpected wrap mode: "+e+".")}}function Gu(e){switch(e){case Ki.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case Ki.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case Ki.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case Ki.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case Ki.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${e}.`)}}const zu={[Ki.PositionKind]:!0,[Ki.NormalKind]:!0,[Ki.TangentKind]:!0,[Ki.UVKind]:!0,[Ki.UV2Kind]:!0,[Ki.UV3Kind]:!0,[Ki.UV4Kind]:!0,[Ki.UV5Kind]:!0,[Ki.UV6Kind]:!0,[Ki.ColorKind]:!0,[Ki.ColorInstanceKind]:!0,[Ki.MatricesIndicesKind]:!0,[Ki.MatricesWeightsKind]:!0,[Ki.MatricesIndicesExtraKind]:!0,[Ki.MatricesWeightsExtraKind]:!0};function Wu(e){switch(e){case Ki.BYTE:case Ki.SHORT:case Ki.INT:case Ki.FLOAT:return!0;case Ki.UNSIGNED_BYTE:case Ki.UNSIGNED_SHORT:case Ki.UNSIGNED_INT:return!1;default:throw new Error(`Invalid type '${e}'`)}}function Hu(e,t){const i=t.getEngine(),s=t._pipelineContext;if(!s?.vertexBufferKindToType)return;let r=null;for(const n in e){const o=e[n];if(!o||!zu[n])continue;const a=o.normalized?Ki.FLOAT:o.type,l=s.vertexBufferKindToType[n];(a!==Ki.FLOAT&&void 0===l||void 0!==l&&l!==a)&&(r||(r=i._getShaderProcessingContext(t.shaderLanguage)),s.vertexBufferKindToType[n]=a,a!==Ki.FLOAT&&(r.vertexBufferKindToNumberOfComponents[n]=Ki.DeduceStride(n),Wu(a)&&(r.vertexBufferKindToNumberOfComponents[n]*=-1)))}if(r){const e=i._caps.parallelShaderCompile;i._caps.parallelShaderCompile=void 0,t._processShaderCode(null,i._features._checkNonFloatVertexBuffersDontRecreatePipelineContext,r),i._caps.parallelShaderCompile=e}}class Xu{constructor(){this.vertexBufferKindToNumberOfComponents={},this.remappedAttributeNames={},this.injectInVertexMain=""}}const Yu=new g;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{e=t,e&&Yu.notifyObservers(e)}})}class ju extends zi{}class $u{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=qu._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw new Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw new Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}}const Ku=[];class qu extends Br{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine({version:Br.Version,nonFloatVertexBuffers:!0}),this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new $u(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==qu.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${qu.PROTOCOL_VERSION} (JS)`);this._engine.setDeviceLostCallback&&this._engine.setDeviceLostCallback((()=>{this.onContextLostObservable.notifyObservers(this),this._contextWasLost=!0,this._restoreEngineAfterContextLost()})),this._webGLVersion=2,this.disableUniformBuffers=!0,this._shaderPlatformName="NATIVE",this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!0,textureFloatLinearFiltering:!0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1,parallelShaderCompile:{COMPLETION_STATUS_KHR:0}},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1},Ii.Log("Babylon Native (v"+Br.Version+") launched"),Ii.LoadScript=function(e,t,i,s){Ii.LoadFile(e,(e=>{Function(e).apply(null),t&&t()}),void 0,void 0,!1,((e,t)=>{i&&i("LoadScript Error",t)}))},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(){const t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,(function(i,s){return Array.isArray(s)?i.push.apply(i,e.call(s,t-1)):i.push(s),i}),[]):Array.prototype.slice.call(this)},writable:!0});const t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();const i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new wu,this.onNewSceneAddedObservable.add((e=>{const t=e.render;e.render=(...i)=>{this._commandBufferEncoder.beginCommandScope(),t.apply(e,i),this._commandBufferEncoder.endCommandScope()}}))}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new _u}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_restoreEngineAfterContextLost(){this._clearEmptyResources();const e=this._depthCullingState.depthTest,t=this._depthCullingState.depthFunc,i=this._depthCullingState.depthMask,s=this._stencilState.stencilTest;this._rebuildGraphicsResources(),this._depthCullingState.depthTest=e,this._depthCullingState.depthFunc=t,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=s,this._flagContextRestored()}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,s=!1){if(this.useReverseDepthBuffer)throw new Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(s?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){const s=this._normalizeIndexData(e),r=new ju;return r.references=1,r.is32Bits=4===s.BYTES_PER_ELEMENT,s.byteLength&&(r.nativeIndexBuffer=this._engine.createIndexBuffer(s.buffer,s.byteOffset,s.byteLength,r.is32Bits,t??!1)),r}createVertexBuffer(e,t,i){const s=ArrayBuffer.isView(e)?e:new Float32Array(e),r=new ju;return r.references=1,s.byteLength&&(r.nativeVertexBuffer=this._engine.createVertexBuffer(s.buffer,s.byteOffset,s.byteLength,t??!1)),r}_recordVertexArrayObject(e,t,i,s,r){Hu(t,s),i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const n=s.getAttributesNames();for(let i=0;i=0){const s=n[i];let a=null;if(r&&(a=r[s]),a||(a=t[s]),a){const t=a.effectiveBuffer;t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,o,a.effectiveByteOffset,a.effectiveByteStride,a.getSize(),Gu(a.type),a.normalized,a.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,s){const r=this._engine.createVertexArray();return this._recordVertexArrayObject(r,e,t,i,s),r}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){const i=e,s=i.shaderProcessingContext;Ku.length=0;for(let e=0;e{e(),t()}}else i.onCompiled=t;else t()}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,s){const r=e;this.onBeforeShaderCompilationObservable.notifyObservers(this);const n=new Ou(t);n.processCode(),t=n.code;const o=new Ou(i);o.processCode(),i=o.code,t=Yi._ConcatenateShader(t,s),i=Yi._ConcatenateShader(i,s);const a=()=>{r.isCompiled=!0,r.onCompiled?.(),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(e.isAsync)r.program=this._engine.createProgramAsync(t,i,a,(e=>{r.compilationError=e}));else try{r.program=this._engine.createProgram(t,i),a()}catch(e){const t=e?.message;throw new Error("SHADER ERROR"+("string"==typeof t?"\n"+t:""))}return r.program}inlineShaderCode(e){const t=new Ou(e);return t.debug=!1,t.processCode(),t.code}_setProgram(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)}_deletePipelineContext(e){const t=e;t&&t.program&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(t.program),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){const i=e;return this._engine.getUniforms(i.program,t)}bindUniformBlock(e,t,i){throw new Error("Not Implemented")}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const i=e.getSamplers();for(let t=0;t{}}}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()}setDepthWrite(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}setColorWrite(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}getColorWrite(){return this._colorWrite}applyStencil(){this._setStencil(this._stencilMask,function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw new Error(`Unsupported stencil OpFail mode: ${e}.`)}}(this._stencilOpStencilFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw new Error(`Unsupported stencil depthFail mode: ${e}.`)}}(this._stencilOpDepthFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw new Error(`Unsupported stencil opPass mode: ${e}.`)}}(this._stencilOpStencilDepthPass),function(e){switch(e){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw new Error(`Unsupported stencil func mode: ${e}.`)}}(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,s,r,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,s){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=function(e){switch(e){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw new Error(`Unsupported alpha mode: ${e}.`)}}(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(0===e),this._alphaMode=e}setInt(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setArray(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))}setArray2(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))}setArray3(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))}setArray4(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))}setMatrices(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix3x3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix2x2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat2(e,t,i){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat3(e,t,i,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,s,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,s=!1,r){if(void 0===s&&(s=!1),e&&e._hardwareTexture){const i=t.getCanvasTexture(),s=e._hardwareTexture.underlyingResource;this._engine.copyTexture(s,i),e.isReady=!0}}createDynamicTexture(e,t,i,s){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,s)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const s=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(s,t,i)}}createRawTexture(e,t,i,s,r,n,o,a=null,l=0,h=0,c=!1){const u=new ti(this,ei.Raw);if(u.format=s,u.generateMipMaps=r,u.samplingMode=o,u.invertY=n,u.baseWidth=t,u.baseHeight=i,u.width=u.baseWidth,u.height=u.baseHeight,u._compression=a,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!r),this.updateRawTexture(u,e,s,n,a,l,u._useSRGBBuffer),u._hardwareTexture){const e=u._hardwareTexture.underlyingResource,t=Uu(o);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(u),u}createRawTexture2DArray(e,t,i,s,r,n,o,a,l=null,h=0){const c=new ti(this,ei.Raw2DArray);if(c.baseWidth=t,c.baseHeight=i,c.baseDepth=s,c.width=t,c.height=i,c.depth=s,c.format=r,c.type=h,c.generateMipMaps=n,c.samplingMode=a,c.is2DArray=!0,c._hardwareTexture){const l=c._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,s,Vu(r,h),n,o);const u=Uu(a);this._setTextureSampling(l,u)}return c.isReady=!0,this._internalTexturesCache.push(c),c}updateRawTexture(e,t,i,s,r=null,n=0,o=!1){if(e){if(t&&e._hardwareTexture){const s=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(s,t,e.width,e.height,Vu(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,p,f=!1){const _="data:"===(e=e||"").substr(0,5),m=_&&-1!==e.indexOf(";base64,"),g=l||new ti(this,ei.Url),v=e;!this._transformTextureUrl||m||l||a||(e=this._transformTextureUrl(e));const x=e.lastIndexOf("."),T=c||(x>-1?e.substring(x).toLowerCase():"");let S=null;for(const e of si._TextureLoaders)if(e.canLoad(T)){S=e;break}s&&s.addPendingData(g),g.url=e,g.generateMipMaps=!t,g.samplingMode=r,g.invertY=i,g._useSRGBBuffer=this._getUseSRGBBuffer(f,t),this.doNotHandleContextLost||(g._buffer=a);let E=null;n&&!l&&(E=g.onLoadedObservable.add(n)),l||this._internalTexturesCache.push(g);const b=(i,l)=>{s&&s.removePendingData(g),e===v?(E&&g.onLoadedObservable.remove(E),y.UseFallbackTexture&&this.createTexture(y.FallbackTexture,t,g.invertY,s,r,null,o,a,g),o&&o((i||"Unknown error")+(y.UseFallbackTexture?" - Fallback texture was used":""),l)):(J.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,g.invertY,s,r,n,o,a,g,h,c,u,d))};if(S)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const n=e=>{if(!g._hardwareTexture)return void(s&&s.removePendingData(g));const n=g._hardwareTexture.underlyingResource;this._engine.loadTexture(n,e,!t,i,g._useSRGBBuffer,(()=>{g.baseWidth=this._engine.getTextureWidth(n),g.baseHeight=this._engine.getTextureHeight(n),g.width=g.baseWidth,g.height=g.baseHeight,g.isReady=!0;const e=Uu(r);this._setTextureSampling(n,e),s&&s.removePendingData(g),g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()}),(()=>{throw new Error("Could not load a native texture.")}))};if(_&&a)if(a instanceof ArrayBuffer)n(new Uint8Array(a));else if(ArrayBuffer.isView(a))n(a);else{if("string"!=typeof a)throw new Error("Unsupported buffer type");n(new Uint8Array(Ii.DecodeBase64(a)))}else m?n(new Uint8Array(Ii.DecodeBase64(e))):this._loadFile(e,(e=>n(new Uint8Array(e))),void 0,void 0,!0,((e,t)=>{b("Unable to load "+(e&&e.responseURL,t))}))}return g}wrapNativeTexture(e,t=!1,i=3){const s=new Bu(e,this._engine),r=new ti(this,ei.Unknown,!0);return r._hardwareTexture=s,r.baseWidth=this._engine.getTextureWidth(e),r.baseHeight=this._engine.getTextureHeight(e),r.width=r.baseWidth,r.height=r.baseHeight,r.isReady=!0,r.useMipMaps=t,this.updateTextureSamplingMode(i,r),r}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const s=t.generateStencil||!1,r=t.samples||1,n=i,o=new ti(this,ei.DepthStencil),a=e.width??e,l=e.height??e,h=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,a,l,s,!0,r);return n._framebufferDepthStencil=h,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){return new Promise(((t,i)=>{const s=this.createCanvasImage();s.onload=()=>{try{const e=this._engine.createImageBitmap(s);t(e)}catch(e){i(`Error loading image ${s.src} with exception: ${e}`)}},s.onerror=e=>{i(`Error loading image ${s.src} with exception: ${e}`)},s.src=e}))}createImageBitmap(e,t){return new Promise(((t,i)=>{if(Array.isArray(e)){const i=e;if(i.length){const e=this._engine.createImageBitmap(i[0]);if(e)return void t(e)}}i("Unsupported data for createImageBitmap.")}))}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d,p=!1){const f=u||new ti(this,ei.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!s,f._lodGenerationScale=h,f._lodGenerationOffset=c,f._useSRGBBuffer=this._getUseSRGBBuffer(p,!!s),this._doNotHandleContextLost||(f._extension=a,f._files=i);const _=e.lastIndexOf(".");if(".env"===(a||(_>-1?e.substring(_).toLowerCase():""))){const t=e=>{const t=Tu(e);f.width=t.width,f.height=t.width,yu(f,t);const i=t.specular;if(!i)throw new Error("Nothing else parsed so far");f._lodGenerationScale=i.lodGenerationScale;const s=Eu(e,t);f.format=5,f.type=0,f.generateMipMaps=!0,f.getEngine().updateTextureSamplingMode(Zn.TRILINEAR_SAMPLINGMODE,f),f._isRGBD=!0,f.invertY=!0,this._engine.loadCubeTextureWithMips(f._hardwareTexture.underlyingResource,s,!1,f._useSRGBBuffer,(()=>{f.isReady=!0,r&&r()}),(()=>{throw new Error("Could not load a native cube texture.")}))};if(i&&6===i.length)throw new Error("Multi-file loading not allowed on env files.");{const i=(e,t)=>{n&&e&&n(e.status+" "+e.statusText,t)};this._loadFile(e,(e=>{t(new Uint8Array(e,0,e.byteLength))}),void 0,void 0,!0,i)}}else{if(!i||6!==i.length)throw new Error("Cannot load cubemap because 6 files were not defined");const e=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(e.map((e=>this._loadFileAsync(e,void 0,!0).then((e=>new Uint8Array(e,0,e.byteLength)))))).then((e=>new Promise(((t,i)=>{this._engine.loadCubeTexture(f._hardwareTexture.underlyingResource,e,!s,!0,f._useSRGBBuffer,t,i)})))).then((()=>{f.isReady=!0,r&&r()}),(e=>{n&&n(`Failed to load cubemap: ${e.message}`,e)}))}return this._internalTexturesCache.push(f),f}_createHardwareTexture(){return new Bu(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const s=new Lu(e,t,i,this);return this._renderTargetWrapperCache.push(s),s}_createInternalTexture(e,t,i=!0,s=ei.Unknown){let r,n=!1,o=0,a=3,l=5,h=!1,c=1;void 0!==t&&"object"==typeof t?(n=!!t.generateMipMaps,o=void 0===t.type?0:t.type,a=void 0===t.samplingMode?3:t.samplingMode,l=void 0===t.format?5:t.format,h=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,c=t.samples??1,r=t.label):n=!!t,h=this._getUseSRGBBuffer(h,!n),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(a=1),1!==o||this._caps.textureFloat||(o=0,J.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=new ti(this,s),d=e.width??e,p=e.height??e,f=e.layers||0;if(0!==f)throw new Error("Texture layers are not supported in Babylon Native");const _=u._hardwareTexture.underlyingResource,m=Vu(l,o);return this._engine.initializeTexture(_,d,p,n,m,!0,h,c),this._setTextureSampling(_,Uu(a)),u._useSRGBBuffer=h,u.baseWidth=d,u.baseHeight=p,u.width=d,u.height=p,u.depth=f,u.isReady=!0,u.samples=c,u.generateMipMaps=n,u.samplingMode=a,u.type=o,u.format=l,u.label=r,this._internalTexturesCache.push(u),u}createRenderTargetTexture(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e);let s,r=!0,n=!1,o=!1,a=1;void 0!==t&&"object"==typeof t&&(r=t.generateDepthBuffer??!0,n=!!t.generateStencilBuffer,o=!!t.noColorAttachment,s=t.colorAttachment,a=t.samples??1);const l=s||(o?null:this._createInternalTexture(e,t,!0,ei.RenderTarget)),h=e.width??e,c=e.height??e,u=this._engine.createFrameBuffer(l?l._hardwareTexture.underlyingResource:null,h,c,n,r,a);return i._framebuffer=u,i._generateDepthBuffer=r,i._generateStencilBuffer=n,i._samples=a,i.setTextures(l),i}updateRenderTargetTextureSampleCount(e,t){return J.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=Uu(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,s,r){const n=e;if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||s)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");n._framebufferDepthStencil?this._bindUnboundFramebuffer(n._framebufferDepthStencil):this._bindUnboundFramebuffer(n._framebuffer)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e,!0)}updateDynamicIndexBuffer(e,t,i=0){const s=e,r=this._normalizeIndexData(t);s.is32Bits=4===r.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(s.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i=0,s){const r=e,n=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,o=new Uint8Array(n.buffer,n.byteOffset,s??n.byteLength);this._engine.updateDynamicVertexBuffer(r.nativeVertexBuffer,o.buffer,o.byteOffset,o.byteLength,i)}_setTexture(e,t,i=!1,s=!1){const r=this._boundUniforms[e];if(!r)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null,this._unsetNativeTexture(r)),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let n;return n=s?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!(!n||!n._hardwareTexture||(this._setTextureWrapMode(n._hardwareTexture.underlyingResource,ku(t.wrapU),ku(t.wrapV),ku(t.wrapR)),this._updateAnisotropicLevel(t),this._setNativeTexture(r,n._hardwareTexture.underlyingResource),0))}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,s){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.finishEncodingCommand()}_setNativeTexture(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_unsetNativeTexture(e){_native.Engine.COMMAND_UNSETTEXTURE&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNSETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_updateAnisotropicLevel(e){const t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){const i=this._boundUniforms[e];if(i)if(t&&t._hardwareTexture){const e=t._hardwareTexture.underlyingResource;this._setNativeTexture(i,e)}else this._unsetNativeTexture(i)}unbindAllTextures(){_native.Engine.COMMAND_DISCARDALLTEXTURES&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DISCARDALLTEXTURES),this._commandBufferEncoder.finishEncodingCommand())}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");const i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");return new _native.Image}updateTextureData(e,t,i,s,r,n,o=0,a=0,l=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,s,r,n=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,s=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,s=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}flushFramebuffer(){}_readTexturePixels(e,t,i,s,r,n,o,a,l,h){if(void 0!==s&&-1!==s)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${s}.`);return this._engine.readTexture(e._hardwareTexture?.underlyingResource,r??0,l??0,h??0,t,i,n?.buffer??null,n?.byteOffset??0,n?.byteLength??0).then((e=>(n||(n=new Uint8Array(e)),n)))}}qu.PROTOCOL_VERSION=8,qu._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new Qu:new _u};class Qu extends _u{constructor(){super()}writeUint32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32),super.writeUint32(e)}writeInt32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32),super.writeInt32(e)}writeFloat32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32),super.writeFloat32(e)}writeUint32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),super.writeUint32Array(e)}writeInt32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY),super.writeInt32Array(e)}writeFloat32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),super.writeFloat32Array(e)}writeNativeData(e){super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA),super.writeNativeData(e)}writeBoolean(e){super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN),super.writeBoolean(e)}}var Zu,Ju,ed,td,id,sd,rd,nd,od,ad,ld,hd,cd,ud,dd,pd,fd,_d,md,gd,vd,xd,Td,Sd,Ed,bd,Cd,yd,Ad,Rd,Id,Pd,Md,Dd,Od,Nd,wd,Fd,Ld,Bd;!function(e){e.LowPower="low-power",e.HighPerformance="high-performance"}(Zu||(Zu={})),function(e){e.DepthClipControl="depth-clip-control",e.Depth32FloatStencil8="depth32float-stencil8",e.TextureCompressionBC="texture-compression-bc",e.TextureCompressionETC2="texture-compression-etc2",e.TextureCompressionASTC="texture-compression-astc",e.TimestampQuery="timestamp-query",e.IndirectFirstInstance="indirect-first-instance",e.ShaderF16="shader-f16",e.RG11B10UFloatRenderable="rg11b10ufloat-renderable",e.BGRA8UnormStorage="bgra8unorm-storage",e.Float32Filterable="float32-filterable"}(Ju||(Ju={})),function(e){e.Unmapped="unmapped",e.Pending="pending",e.Mapped="mapped"}(ed||(ed={})),function(e){e[e.MapRead=1]="MapRead",e[e.MapWrite=2]="MapWrite",e[e.CopySrc=4]="CopySrc",e[e.CopyDst=8]="CopyDst",e[e.Index=16]="Index",e[e.Vertex=32]="Vertex",e[e.Uniform=64]="Uniform",e[e.Storage=128]="Storage",e[e.Indirect=256]="Indirect",e[e.QueryResolve=512]="QueryResolve"}(td||(td={})),function(e){e[e.Read=1]="Read",e[e.Write=2]="Write"}(id||(id={})),function(e){e.E1d="1d",e.E2d="2d",e.E3d="3d"}(sd||(sd={})),function(e){e[e.CopySrc=1]="CopySrc",e[e.CopyDst=2]="CopyDst",e[e.TextureBinding=4]="TextureBinding",e[e.StorageBinding=8]="StorageBinding",e[e.RenderAttachment=16]="RenderAttachment"}(rd||(rd={})),function(e){e.E1d="1d",e.E2d="2d",e.E2dArray="2d-array",e.Cube="cube",e.CubeArray="cube-array",e.E3d="3d"}(nd||(nd={})),function(e){e.All="all",e.StencilOnly="stencil-only",e.DepthOnly="depth-only"}(od||(od={})),function(e){e.R8Unorm="r8unorm",e.R8Snorm="r8snorm",e.R8Uint="r8uint",e.R8Sint="r8sint",e.R16Uint="r16uint",e.R16Sint="r16sint",e.R16Float="r16float",e.RG8Unorm="rg8unorm",e.RG8Snorm="rg8snorm",e.RG8Uint="rg8uint",e.RG8Sint="rg8sint",e.R32Uint="r32uint",e.R32Sint="r32sint",e.R32Float="r32float",e.RG16Uint="rg16uint",e.RG16Sint="rg16sint",e.RG16Float="rg16float",e.RGBA8Unorm="rgba8unorm",e.RGBA8UnormSRGB="rgba8unorm-srgb",e.RGBA8Snorm="rgba8snorm",e.RGBA8Uint="rgba8uint",e.RGBA8Sint="rgba8sint",e.BGRA8Unorm="bgra8unorm",e.BGRA8UnormSRGB="bgra8unorm-srgb",e.RGB9E5UFloat="rgb9e5ufloat",e.RGB10A2UINT="rgb10a2uint",e.RGB10A2Unorm="rgb10a2unorm",e.RG11B10UFloat="rg11b10ufloat",e.RG32Uint="rg32uint",e.RG32Sint="rg32sint",e.RG32Float="rg32float",e.RGBA16Uint="rgba16uint",e.RGBA16Sint="rgba16sint",e.RGBA16Float="rgba16float",e.RGBA32Uint="rgba32uint",e.RGBA32Sint="rgba32sint",e.RGBA32Float="rgba32float",e.Stencil8="stencil8",e.Depth16Unorm="depth16unorm",e.Depth24Plus="depth24plus",e.Depth24PlusStencil8="depth24plus-stencil8",e.Depth32Float="depth32float",e.BC1RGBAUnorm="bc1-rgba-unorm",e.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",e.BC2RGBAUnorm="bc2-rgba-unorm",e.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",e.BC3RGBAUnorm="bc3-rgba-unorm",e.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",e.BC4RUnorm="bc4-r-unorm",e.BC4RSnorm="bc4-r-snorm",e.BC5RGUnorm="bc5-rg-unorm",e.BC5RGSnorm="bc5-rg-snorm",e.BC6HRGBUFloat="bc6h-rgb-ufloat",e.BC6HRGBFloat="bc6h-rgb-float",e.BC7RGBAUnorm="bc7-rgba-unorm",e.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",e.ETC2RGB8Unorm="etc2-rgb8unorm",e.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",e.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",e.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",e.ETC2RGBA8Unorm="etc2-rgba8unorm",e.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",e.EACR11Unorm="eac-r11unorm",e.EACR11Snorm="eac-r11snorm",e.EACRG11Unorm="eac-rg11unorm",e.EACRG11Snorm="eac-rg11snorm",e.ASTC4x4Unorm="astc-4x4-unorm",e.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",e.ASTC5x4Unorm="astc-5x4-unorm",e.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",e.ASTC5x5Unorm="astc-5x5-unorm",e.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",e.ASTC6x5Unorm="astc-6x5-unorm",e.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",e.ASTC6x6Unorm="astc-6x6-unorm",e.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",e.ASTC8x5Unorm="astc-8x5-unorm",e.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",e.ASTC8x6Unorm="astc-8x6-unorm",e.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",e.ASTC8x8Unorm="astc-8x8-unorm",e.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",e.ASTC10x5Unorm="astc-10x5-unorm",e.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",e.ASTC10x6Unorm="astc-10x6-unorm",e.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",e.ASTC10x8Unorm="astc-10x8-unorm",e.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",e.ASTC10x10Unorm="astc-10x10-unorm",e.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",e.ASTC12x10Unorm="astc-12x10-unorm",e.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",e.ASTC12x12Unorm="astc-12x12-unorm",e.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",e.Depth32FloatStencil8="depth32float-stencil8"}(ad||(ad={})),function(e){e.ClampToEdge="clamp-to-edge",e.Repeat="repeat",e.MirrorRepeat="mirror-repeat"}(ld||(ld={})),function(e){e.Nearest="nearest",e.Linear="linear"}(hd||(hd={})),function(e){e.Nearest="nearest",e.Linear="linear"}(cd||(cd={})),function(e){e.Never="never",e.Less="less",e.Equal="equal",e.LessEqual="less-equal",e.Greater="greater",e.NotEqual="not-equal",e.GreaterEqual="greater-equal",e.Always="always"}(ud||(ud={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Compute=4]="Compute"}(dd||(dd={})),function(e){e.Uniform="uniform",e.Storage="storage",e.ReadOnlyStorage="read-only-storage"}(pd||(pd={})),function(e){e.Filtering="filtering",e.NonFiltering="non-filtering",e.Comparison="comparison"}(fd||(fd={})),function(e){e.Float="float",e.UnfilterableFloat="unfilterable-float",e.Depth="depth",e.Sint="sint",e.Uint="uint"}(_d||(_d={})),function(e){e.WriteOnly="write-only",e.ReadOnly="read-only",e.ReadWrite="read-write"}(md||(md={})),function(e){e.Error="error",e.Warning="warning",e.Info="info"}(gd||(gd={})),function(e){e.Validation="validation",e.Internal="internal"}(vd||(vd={})),function(e){e.Auto="auto"}(xd||(xd={})),function(e){e.PointList="point-list",e.LineList="line-list",e.LineStrip="line-strip",e.TriangleList="triangle-list",e.TriangleStrip="triangle-strip"}(Td||(Td={})),function(e){e.CCW="ccw",e.CW="cw"}(Sd||(Sd={})),function(e){e.None="none",e.Front="front",e.Back="back"}(Ed||(Ed={})),function(e){e[e.Red=1]="Red",e[e.Green=2]="Green",e[e.Blue=4]="Blue",e[e.Alpha=8]="Alpha",e[e.All=15]="All"}(bd||(bd={})),function(e){e.Zero="zero",e.One="one",e.Src="src",e.OneMinusSrc="one-minus-src",e.SrcAlpha="src-alpha",e.OneMinusSrcAlpha="one-minus-src-alpha",e.Dst="dst",e.OneMinusDst="one-minus-dst",e.DstAlpha="dst-alpha",e.OneMinusDstAlpha="one-minus-dst-alpha",e.SrcAlphaSaturated="src-alpha-saturated",e.Constant="constant",e.OneMinusConstant="one-minus-constant"}(Cd||(Cd={})),function(e){e.Add="add",e.Subtract="subtract",e.ReverseSubtract="reverse-subtract",e.Min="min",e.Max="max"}(yd||(yd={})),function(e){e.Keep="keep",e.Zero="zero",e.Replace="replace",e.Invert="invert",e.IncrementClamp="increment-clamp",e.DecrementClamp="decrement-clamp",e.IncrementWrap="increment-wrap",e.DecrementWrap="decrement-wrap"}(Ad||(Ad={})),function(e){e.Uint16="uint16",e.Uint32="uint32"}(Rd||(Rd={})),function(e){e.Uint8x2="uint8x2",e.Uint8x4="uint8x4",e.Sint8x2="sint8x2",e.Sint8x4="sint8x4",e.Unorm8x2="unorm8x2",e.Unorm8x4="unorm8x4",e.Snorm8x2="snorm8x2",e.Snorm8x4="snorm8x4",e.Uint16x2="uint16x2",e.Uint16x4="uint16x4",e.Sint16x2="sint16x2",e.Sint16x4="sint16x4",e.Unorm16x2="unorm16x2",e.Unorm16x4="unorm16x4",e.Snorm16x2="snorm16x2",e.Snorm16x4="snorm16x4",e.Float16x2="float16x2",e.Float16x4="float16x4",e.Float32="float32",e.Float32x2="float32x2",e.Float32x3="float32x3",e.Float32x4="float32x4",e.Uint32="uint32",e.Uint32x2="uint32x2",e.Uint32x3="uint32x3",e.Uint32x4="uint32x4",e.Sint32="sint32",e.Sint32x2="sint32x2",e.Sint32x3="sint32x3",e.Sint32x4="sint32x4",e.UNORM10x10x10x2="unorm10-10-10-2"}(Id||(Id={})),function(e){e.Vertex="vertex",e.Instance="instance"}(Pd||(Pd={})),function(e){e.Beginning="beginning",e.End="end"}(Md||(Md={})),function(e){e.Beginning="beginning",e.End="end"}(Dd||(Dd={})),function(e){e.Load="load",e.Clear="clear"}(Od||(Od={})),function(e){e.Store="store",e.Discard="discard"}(Nd||(Nd={})),function(e){e.Occlusion="occlusion",e.Timestamp="timestamp"}(wd||(wd={})),function(e){e.Opaque="opaque",e.Premultiplied="premultiplied"}(Fd||(Fd={})),function(e){e.Unknown="unknown",e.Destroyed="destroyed"}(Ld||(Ld={})),function(e){e.Validation="validation",e.OutOfMemory="out-of-memory",e.Internal="internal"}(Bd||(Bd={}));class Vd{constructor(){this.shaderLanguage=ht.GLSL}_addUniformToLeftOverUBO(e,t,i){let s=0;[e,t,s]=this._getArraySize(e,t,i);for(let t=0;t=0&&(u.push(o[c]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=u,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new ji(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=Vd.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}setEngine(e){this.engine=e}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,s)}setInt4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,s,r)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,s)}setUInt4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,s,r)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,s)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,s,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,s,r)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){return this.sources?.vertex}_getFragmentShaderCode(){return this.sources?.fragment}}const kd={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class Gd{static get KnownUBOs(){return Gd._SimplifiedKnownBindings?Gd._SimplifiedKnownUBOs:Gd._KnownUBOs}constructor(e){this.vertexBufferKindToNumberOfComponents={},this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=Gd.KnownUBOs,t=[];for(const i in e){const s=e[i].binding;-1!==s.groupIndex&&(void 0===t[s.groupIndex]?t[s.groupIndex]=s.bindingIndex:t[s.groupIndex]=Math.max(t[s.groupIndex],s.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){const i=this._attributeNextLocation;return this._attributeNextLocation+=(kd[e]??1)*(t||1),i}getVaryingNextLocation(e,t=0){const i=this._varyingNextLocation;return this._varyingNextLocation+=(kd[e]??1)*(t||1),i}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";const t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}Gd._SimplifiedKnownBindings=!0,Gd._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}},Gd._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};class zd extends Vd{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=ht.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let s=0;const r=e.indexOf("["),n=e.indexOf("]");if(r>0&&n>0){const t=e.substring(r+1,n);s=+t,isNaN(s)&&(s=+i[t.trim()]),e=e.substr(0,r)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){const i=`// Internals UBO\nuniform ${Vd.InternalsUBOName} {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n`,s=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),s?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),s?e:i+e)}varyingCheck(e,t){return(t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/).test(e)}varyingProcessor(e,t,i){this._preProcessors=i;const s=(t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==s){const r=s[1]??"",n=s[2],o=s[3];let a;t?(a=this._webgpuProcessingContext.availableVaryings[o],this._missingVaryings[a]="",void 0===a&&J.Warn(`Invalid fragment shader: The varying named "${o}" is not declared in the vertex shader! This declaration will be ignored.`)):(a=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(o,n,i)[2]),this._webgpuProcessingContext.availableVaryings[o]=a,this._missingVaryings[a]=`layout(location = ${a}) ${r} in ${n} ${o};`),e=e.replace(s[0],void 0===a?"":`layout(location = ${a}) ${r} ${t?"in":"out"} ${n} ${o};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=(this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==i){const s=i[1],r=i[2],n=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(r,s,t)[2]);this._webgpuProcessingContext.availableAttributes[r]=n,this._webgpuProcessingContext.orderedAttributes[n]=r;const o=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[r];if(void 0!==o){const t=o<0?-1===o?"int":"ivec"+-o:1===o?"uint":"uvec"+o,a=`_int_${r}_`;e=e.replace(i[0],`layout(location = ${n}) in ${t} ${a}; ${s} ${r} = ${s}(${a});`)}else e=e.replace(i[0],`layout(location = ${n}) in ${s} ${r};`)}return e}uniformProcessor(e,t,i){this._preProcessors=i;const s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let r=s[1],n=s[2];if(0===r.indexOf("sampler")||1===r.indexOf("sampler")){let s=0;[n,r,s]=this._getArraySize(n,r,i);let o=this._webgpuProcessingContext.availableTextures[n];if(!o){o={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:_d.Float};for(let e=0;e<(s||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const a=Vd._SamplerTypeByWebGLSamplerType[r]??"sampler",l=!!Vd._IsComparisonSamplerByWebGPUSamplerType[a],h=l?fd.Comparison:fd.Filtering,c=n+"Sampler";let u=this._webgpuProcessingContext.availableSamplers[c];u||(u={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:h});const d="u"===r.charAt(0)?"u":"i"===r.charAt(0)?"i":"";d&&(r=r.substr(1));const p=l?_d.Depth:"u"===d?_d.Uint:"i"===d?_d.Sint:_d.Float;o.sampleType=p;const f=s>0,_=u.binding.groupIndex,m=u.binding.bindingIndex,g=Vd._SamplerFunctionByWebGLSamplerType[r],v=Vd._TextureTypeByWebGLSamplerType[r],x=Vd._GpuTextureViewDimensionByWebGPUTextureType[v];if(f){const t=[];t.push(`layout(set = ${_}, binding = ${m}) uniform ${d}${a} ${c};`),e="\n";for(let i=0;i0?"\n":""}#define ${n}${i} ${d}${g}(${n}Texture${i}, ${c})`}e=t.join("\n")+e,this._textureArrayProcessing.push(n)}else s=1,e=`layout(set = ${_}, binding = ${m}) uniform ${a} ${c};\n layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${d}${v} ${n}Texture;\n #define ${n} ${d}${g}(${n}Texture, ${c})`;this._webgpuProcessingContext.availableTextures[n]=o,this._webgpuProcessingContext.availableSamplers[c]=u,this._addSamplerBindingDescription(c,u,!t);for(let e=0;e=0,i="\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n ",s=t?"vec4 glFragCoord_;\n":"",r=-1!==e.search(/layout *\(location *= *0\) *out/g);if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){const t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(n||r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",s),t&&(e=Du(e,"void main",i))}else if(e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex"),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;if(!i){const t=e.lastIndexOf("}");e=e.substring(0,t),e+="gl_Position.y *= yFactor_;\n",e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let s=i.exec(e);for(;null!==s;){const r=s[1];let n=+r;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[r.trim()]),e=e.replace(s[0],t+n),s=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} {\n `;for(const e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}];\n`:i+=` ${e.type} ${e.name};\n`;return i+="};\n\n",i}finalizeShaders(e,t){for(let i=0;i0&&(t=i+"\n"+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}Ft.IncludesShadersStoreWGSL.bonesDeclaration="#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4;attribute matricesWeights : vec4;\n#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d;uniform boneTextureWidth : f32;\n#else\nuniform mBones : array;\n#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array;\n#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\n{let offset=i32(index) *4; \nlet m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);}\n#endif\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.bonesVertex="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\n#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\n#endif \n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4\n{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);}\n#endif\n";Ft.IncludesShadersStoreWGSL.bakedVertexAnimation="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\n#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\n#endif\nlet totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];\n#endif\nfinalWorld=finalWorld*VATInfluence;}\n#endif\n";Ft.IncludesShadersStoreWGSL.clipPlaneFragment="#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\n#endif\n#ifdef CLIPPLANE\nelse if (fragmentInputs.fClipDistance>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\n{discard;}\n#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\n{discard;}\n#endif\n";Ft.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration="#ifdef CLIPPLANE\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nvarying fClipDistance6: f32;\n#endif\n";Ft.IncludesShadersStoreWGSL.clipPlaneVertex="#ifdef CLIPPLANE\nvertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nvertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nvertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nvertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);\n#endif\n#ifdef CLIPPLANE5\nvertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);\n#endif\n#ifdef CLIPPLANE6\nvertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);\n#endif\n";Ft.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration="#ifdef CLIPPLANE\nuniform vClipPlane: vec4;varying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4;varying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4;varying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4;varying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4;varying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4;varying fClipDistance6: f32;\n#endif\n";Ft.IncludesShadersStoreWGSL.instancesDeclaration="#ifdef INSTANCES\nattribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4;\n#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4;\n#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform previousWorld : mat4x4;\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.instancesVertex="#ifdef INSTANCES\nvar finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\n#endif\n#ifdef THIN_INSTANCES\n#if !defined(WORLD_UBO)\nfinalWorld=uniforms.world*finalWorld;\n#else\nfinalWorld=mesh.world*finalWorld;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nvar finalWorld=uniforms.world;\n#else\nvar finalWorld=mesh.world;\n#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=previousWorld;\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.helperFunctions="const PI: f32=3.1415926535897932384626433832795;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const HALF_MIN: f32=5.96046448e-08; \nconst LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3=vec3 (0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;\n#define saturate(x) clamp(x,0.0,1.0)\nfn transposeMat3(inMatrix: mat3x3f)->mat3x3f {let i0: vec3=inMatrix[0];let i1: vec3=inMatrix[1];let i2: vec3=inMatrix[2];let outMatrix:mat3x3f=mat3x3f(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);return outMatrix;}\nfn inverseMat3(inMatrix: mat3x3f)->mat3x3f {let a00: f32=inMatrix[0][0];let a01: f32=inMatrix[0][1];let a02: f32=inMatrix[0][2];let a10: f32=inMatrix[1][0];let a11: f32=inMatrix[1][1];let a12: f32=inMatrix[1][2];let a20: f32=inMatrix[2][0];let a21: f32=inMatrix[2][1];let a22: f32=inMatrix[2][2];let b01: f32=a22*a11-a12*a21;let b11: f32=-a22*a10+a12*a20;let b21: f32=a21*a10-a11*a20;let det: f32=a00*b01+a01*b11+a02*b21;return mat3x3f(b01/det,(-a22*a01+a02*a21)/det,(a12*a01-a02*a11)/det,\nb11/det,(a22*a00-a02*a20)/det,(-a12*a00+a02*a10)/det,\nb21/det,(-a21*a00+a01*a20)/det,(a11*a00-a01*a10)/det);}\n#if USE_EXACT_SRGB_CONVERSIONS\nfn toLinearSpaceExact(color: vec3)->vec3\n{let nearZeroSection: vec3=0.0773993808*color;let remainingSection: vec3=pow(0.947867299*(color+vec3(0.055)),vec3(2.4));return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045)));}\nfn toGammaSpaceExact(color: vec3)->vec3\n{let nearZeroSection: vec3=12.92*color;let remainingSection: vec3=1.055*pow(color,vec3(0.41666))-vec3(0.055);return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308)));}\n#endif\nfn toLinearSpace(color: vec4)->vec4\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toLinearSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a);\n#endif\n}\nfn toLinearSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toLinearSpaceExact(color);\n#else\nreturn pow(color,vec3(LinearEncodePowerApprox));\n#endif\n}\nfn toGammaSpace(color: vec4)->vec4\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn vec4(toGammaSpaceExact(color.rgb),color.a);\n#else\nreturn vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a);\n#endif\n}\nfn toGammaSpaceVec3(color: vec3)->vec3\n{\n#if USE_EXACT_SRGB_CONVERSIONS\nreturn toGammaSpaceExact(color);\n#else\nreturn pow(color,vec3(GammaEncodePowerApprox));\n#endif\n}\nfn square(value: vec3)->vec3\n{return value*value;}\nfn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;}\nfn getLuminance(color: vec3)->f32\n{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);}\nfn getRand(seed: vec2)->f32 {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);}\nfn dither(seed: vec2,varianceAmount: f32)->f32 {let rand: f32=getRand(seed);let normVariance: f32=varianceAmount/255.0;let dither: f32=mix(-normVariance,normVariance,rand);return dither;}\nconst rgbdMaxRange: f32=255.0;fn toRGBD(color: vec3)->vec4 {let maxRGB: f32=max(max(color.r,max(color.g,color.b)),Epsilon);var D: f32 =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);var rgb: vec3 =color.rgb*D;rgb=toGammaSpaceVec3(rgb);return vec4(clamp(rgb,vec3(0.,0.,0.),vec3(1.,1.,1.)),D); }\nfn fromRGBD(rgbd: vec4)->vec3 {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;}\nfn parallaxCorrectNormal(vertexPos: vec3,origVec: vec3,cubeSize: vec3,cubePos: vec3)->vec3 {let invOrigVec: vec3=vec3(1.0,1.0,1.0)/origVec;let halfSize: vec3=cubeSize*0.5;let intersecAtMaxPlane: vec3=(cubePos+halfSize-vertexPos)*invOrigVec;let intersecAtMinPlane: vec3=(cubePos-halfSize-vertexPos)*invOrigVec;let largestIntersec: vec3=max(intersecAtMaxPlane,intersecAtMinPlane);let distance: f32=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);let intersectPositionWS: vec3=vertexPos+origVec*distance;return intersectPositionWS-cubePos;}\n";Ft.IncludesShadersStoreWGSL.fresnelFunction="#ifdef FRESNEL\nfn computeFresnelTerm(viewDirection: vec3f,worldNormal: vec3f,bias: f32,power: f32)->f32\n{let fresnelTerm: f32=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);}\n#endif\n";Ft.IncludesShadersStoreWGSL.meshUboDeclaration="struct Mesh {world : mat4x4,\nvisibility : f32,};var mesh : Mesh;\n#define WORLD_UBO\n";Ft.IncludesShadersStoreWGSL.morphTargetsVertex="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\n#if {X}==0\nfor (var i=0; i=uniforms.morphTargetCount) {break;}\nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n}\n#endif\n#else\npositionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3;\n#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2;\n#endif\n#elif {X}==0\nuniform morphTargetCount: i32;\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.morphTargetsVertexGlobal="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration="#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array;\n#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3\n{ \nlet y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;}\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.sceneUboDeclaration="struct Scene {viewProjection : mat4x4,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4,\n#endif \nview : mat4x4,\nprojection : mat4x4,\nvEyePosition : vec4,};var scene : Scene;\n";Ft.IncludesShadersStoreWGSL.lightsFragmentFunctions="struct lightingInfo\n{diffuse: vec3f,\n#ifdef SPECULARTERM\nspecular: vec3f,\n#endif\n#ifdef NDOTL\nndl: f32,\n#endif\n};fn computeLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var lightVectorW: vec3f;var attenuation: f32=1.0;if (lightData.w==0.)\n{var direction: vec3f=lightData.xyz-vPositionW;var attenuation: f32=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);}\nelse\n{lightVectorW=normalize(-lightData.xyz);}\nvar ndl: f32=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nfn computeSpotLighting(viewDirectionW: vec3f,vNormal: vec3f ,lightData: vec4f,lightDirection: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var direction: vec3f=lightData.xyz-vPositionW;var lightVectorW: vec3f=normalize(direction);var attenuation: f32=max(0.,1.0-length(direction)/range);var cosAngle: f32=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w)\n{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;var ndl: f32=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;}\nresult.diffuse=vec3f(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3f(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;}\nfn computeHemisphericLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,groundColor: vec3f,glossiness: f32)->lightingInfo {var result: lightingInfo;var ndl: f32=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\nvar angleW: vec3f=normalize(viewDirectionW+lightData.xyz);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor;\n#endif\nreturn result;}\nfn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f)->vec3f {var strq: vec4f=textureProjectionMatrix*vec4f(vPositionW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return textureColor;}";Ft.IncludesShadersStoreWGSL.lightFragment="#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(POINTLIGHT{X})\npreInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(HEMILIGHT{X})\npreInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#elif defined(DIRLIGHT{X})\npreInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW);\n#endif\npreInfo.NdotV=NdotV;\n#ifdef SPOTLIGHT{X}\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\n#elif defined(POINTLIGHT{X})\n#ifdef LIGHT_FALLOFF_GLTF{X}\npreInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npreInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npreInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npreInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\n#else\npreInfo.attenuation=1.0;\n#endif\n#ifdef HEMILIGHT{X}\npreInfo.roughness=roughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#ifdef IRIDESCENCE\npreInfo.iridescenceIntensity=iridescenceIntensity;\n#endif\n#ifdef HEMILIGHT{X}\ninfo.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround);\n#elif defined(SS_TRANSLUCENCY)\ninfo.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance);\n#else\ninfo.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef SPECULARTERM\n#ifdef ANISOTROPIC\ninfo.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#else\ninfo.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#endif\n#ifdef SHEEN\n#ifdef SHEEN_LINKWITHALBEDO\npreInfo.roughness=sheenOut.sheenIntensity;\n#else\n#ifdef HEMILIGHT{X}\npreInfo.roughness=sheenOut.sheenRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\n#endif\ninfo.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb);\n#endif\n#ifdef CLEARCOAT\n#ifdef HEMILIGHT{X}\npreInfo.roughness=clearcoatOut.clearCoatRoughness;\n#else\npreInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance);\n#endif\ninfo.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb);\n#ifdef CLEARCOAT_TINT\nabsorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption;\n#ifdef SPECULARTERM\ninfo.specular*=absorption;\n#endif\n#endif\ninfo.diffuse*=info.clearCoat.w;\n#ifdef SPECULARTERM\ninfo.specular*=info.clearCoat.w;\n#endif\n#ifdef SHEEN\ninfo.sheen*=info.clearCoat.w;\n#endif\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},projectionLightTexture{X}Sampler,textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSMDEBUG{X} \nvar shadowDebug{X}: vec3f;\n#endif\n#ifdef SHADOWCSM{X}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nvar index{X}: i32=-1;\n#else\nvar index{X}: i32=SHADOWCSMNUM_CASCADES{X}-1;\n#endif\nvar diff{X}: f32=0.;vPositionFromLight{X}[0]=fragmentInputs.vPositionFromLight{X}_0;vPositionFromLight{X}[1]=fragmentInputs.vPositionFromLight{X}_1;vPositionFromLight{X}[2]=fragmentInputs.vPositionFromLight{X}_2;vPositionFromLight{X}[3]=fragmentInputs.vPositionFromLight{X}_3;vDepthMetric{X}[0]=fragmentInputs.vDepthMetric{X}_0;vDepthMetric{X}[1]=fragmentInputs.vDepthMetric{X}_1;vDepthMetric{X}[2]=fragmentInputs.vDepthMetric{X}_2;vDepthMetric{X}[3]=fragmentInputs.vDepthMetric{X}_3;for (var i:i32=0; i=0.) {index{X}=i;break;}}\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nif (index{X}>=0)\n#endif\n{\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#else\nshadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#endif\n#else\nshadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=vec3f(shadow)*vCascadeColorsMultiplier{X}[index{X}];\n#endif\n#ifndef SHADOWCSMNOBLEND{X}\nvar frustumLength:f32=uniforms.frustumLengths{X}[index{X}];var diffRatio:f32=clamp(diff{X}/frustumLength,0.,1.)*uniforms.cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)\n{index{X}+=1;var nextShadow: f32=0.;\n#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nnextShadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#else\nnextShadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X});\n#endif\n#else\nnextShadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\nshadow=mix(nextShadow,shadow,diffRatio);\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);\n#endif\n}\n#endif\n}\n#elif defined(SHADOWCLOSEESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;shadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\naggShadow+=shadow;numLights+=1.0;\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor.rgb*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef CLEARCOAT\n#ifndef LIGHTMAPNOSPECULAR{X}\nclearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;\n#endif\n#endif\n#ifdef SHEEN\n#ifndef LIGHTMAPNOSPECULAR{X}\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#else\n#ifdef SHADOWCSMDEBUG{X}\ndiffuseBase+=info.diffuse*shadowDebug{X};\n#else \ndiffuseBase+=info.diffuse*shadow;\n#endif\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#ifdef CLEARCOAT\nclearCoatBase+=info.clearCoat.rgb*shadow;\n#endif\n#ifdef SHEEN\nsheenBase+=info.sheen.rgb*shadow;\n#endif\n#endif\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.lightUboDeclaration="#ifdef LIGHT{X}\nstruct Light{X}\n{vLightData: vec4f,\nvLightDiffuse: vec4f,\nvLightSpecular: vec4f,\n#ifdef SPOTLIGHT{X}\nvLightDirection: vec4f,\nvLightFalloff: vec4f,\n#elif defined(POINTLIGHT{X})\nvLightFalloff: vec4f,\n#elif defined(HEMILIGHT{X})\nvLightGround: vec3f,\n#endif\nshadowsInfo: vec4f,\ndepthValues: vec2f} ;var light{X} : Light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform textureProjectionMatrix{X}: mat4x4f;var projectionLightTexture{X}sampler: sampler;var projectionLightTexture{X}: texture_2d;\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array;uniform viewFrustumZ{X}: array;uniform frustumLengths{X}: array;uniform cascadeBlendFactor{X}: f32;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;var vPositionFromLight{X}: array;var vDepthMetric{X} : array;\n#if defined(SHADOWPCSS{X})\nvar shadowTexture{X}Sampler: sampler_comparison; \nvar shadowTexture{X}: texture_depth_2d_array;var depthTexture{X}Sampler: sampler;var depthTexture{X}: texture_2d_array;uniform lightSizeUVCorrection{X}: array;uniform depthCorrection{X}: array;uniform penumbraDarkness{X}: f32;\n#elif defined(SHADOWPCF{X})\nvar shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d_array;\n#else \nvar shadowTexture{X}Sampler: sampler; \nvar shadowTexture{X}: texture_2d_array;\n#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vCascadeColorsMultiplier{X}: array=array\n(\nvec3f ( 1.5,0.0,0.0 ),\nvec3f ( 0.0,1.5,0.0 ),\nvec3f ( 0.0,0.0,5.5 ),\nvec3f ( 1.5,0.0,5.5 ),\nvec3f ( 1.5,1.5,0.0 ),\nvec3f ( 1.0,1.0,1.0 ),\nvec3f ( 0.0,1.0,5.5 ),\nvec3f ( 0.5,3.5,0.75 )\n);\n#endif\n#elif defined(SHADOWCUBE{X})\nvar shadowTexture{X}Sampler: sampler;var shadowTexture{X}: texture_cube;\n#else\nvarying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;\n#if defined(SHADOWPCSS{X})\nvar shadowTexture{X}Sampler: sampler_comparison; \nvar shadowTexture{X}: texture_depth_2d;var depthTexture{X}Sampler: sampler; \nvar depthTexture{X}: texture_2d;\n#elif defined(SHADOWPCF{X})\nvar shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d;\n#else\nvar shadowTexture{X}Sampler: sampler; \nvar shadowTexture{X}: texture_2d;\n#endif\nuniform lightMatrix{X}: mat4x4f;\n#endif\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.lightVxUboDeclaration="#ifdef LIGHT{X}\nstruct Light{X}\n{vLightData: vec4f,\nvLightDiffuse: vec4f,\nvLightSpecular: vec4f,\n#ifdef SPOTLIGHT{X}\nvLightDirection: vec4f,\nvLightFalloff: vec4f,\n#elif defined(POINTLIGHT{X})\nvLightFalloff: vec4f,\n#elif defined(HEMILIGHT{X})\nvLightGround: vec3f,\n#endif\nshadowsInfo: vec4f,\ndepthValues: vec2f} ;var light{X} : Light{X};\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform lightMatrix{X}: array;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;\n#elif defined(SHADOWCUBE{X})\n#else\nvarying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f;\n#endif\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.shadowsFragmentFunctions="#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfn unpack(color: vec4f)->f32\n{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}\n#endif\nfn computeFallOff(value: f32,clipSpace: vec2f,frustumEdgeFalloff: f32)->f32\n{var mask: f32=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);}\nfn computeShadowCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadow: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nreturn select(darkness,1.0,depth>shadow);}\nfn computeShadowWithPoissonSamplingCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,mapSize: f32,darkness: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec3f(-1.0,1.0,-1.0);poissonDisk[1]= vec3f(1.0,-1.0,-1.0);poissonDisk[2]= vec3f(-1.0,-1.0,-1.0);poissonDisk[3]= vec3f(1.0,-1.0,1.0);\n#ifndef SHADOWFLOAT\nif (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[0]*mapSize)),shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nvar esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;}\nfn computeShadowWithCloseESMCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32\n{var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight));\n#else\nvar shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x;\n#endif\nvar esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;}\nfn computeShadowCSM(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d_array,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,uv,layer));\n#else\nvar shadow: f32=textureSample(shadowTexture,shadowSampler,uv,layer).x;\n#endif\nreturn select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}\nfn computeShadow(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadow: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadow: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nreturn select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}}\nfn computeShadowWithPoissonSampling(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,mapSize: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec2f(-0.94201624,-0.39906216);poissonDisk[1]= vec2f(0.94558609,-0.76890725);poissonDisk[2]= vec2f(-0.094184101,-0.92938870);poissonDisk[3]= vec2f(0.34495938,0.29387760);\n#ifndef SHADOWFLOAT\nif (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[0]*mapSize,0.)),shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nvar esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithCloseESM(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{return 1.0;}\nelse\n{var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nvar shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.));\n#else\nvar shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x;\n#endif\nvar esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}}\nfn getZInClip(clipSpace: vec3f,uvDepth: vec3f)->f32\n{\n#ifdef IS_NDC_HALF_ZRANGE\nreturn clipSpace.z;\n#else\nreturn uvDepth.z;\n#endif\n}\nconst GREATEST_LESS_THAN_ONE: f32=0.99999994;\n#define DIAGNOSTIC_OFF\nfn computeShadowWithCSMPCF1(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var shadow: f32=textureSampleCompare(shadowTexture,shadowSampler,uvDepth.xy,layer,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithCSMPCF3(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithCSMPCF5(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),layer,uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),layer,uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),layer,uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),layer,uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}\nfn computeShadowWithPCF1(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var shadow: f32=textureSampleCompareLevel(shadowTexture,shadowSampler,uvDepth.xy,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithPCF3(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nfn computeShadowWithPCF5(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32\n{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;}\nelse\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvar st: vec2f=fract(uv); \nvar base_uv: vec2f=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \nvar uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}}\nconst PoissonSamplers32: array=array (\nvec3f(0.06407013,0.05409927,0.),\nvec3f(0.7366577,0.5789394,0.),\nvec3f(-0.6270542,-0.5320278,0.),\nvec3f(-0.4096107,0.8411095,0.),\nvec3f(0.6849564,-0.4990818,0.),\nvec3f(-0.874181,-0.04579735,0.),\nvec3f(0.9989998,0.0009880066,0.),\nvec3f(-0.004920578,-0.9151649,0.),\nvec3f(0.1805763,0.9747483,0.),\nvec3f(-0.2138451,0.2635818,0.),\nvec3f(0.109845,0.3884785,0.),\nvec3f(0.06876755,-0.3581074,0.),\nvec3f(0.374073,-0.7661266,0.),\nvec3f(0.3079132,-0.1216763,0.),\nvec3f(-0.3794335,-0.8271583,0.),\nvec3f(-0.203878,-0.07715034,0.),\nvec3f(0.5912697,0.1469799,0.),\nvec3f(-0.88069,0.3031784,0.),\nvec3f(0.5040108,0.8283722,0.),\nvec3f(-0.5844124,0.5494877,0.),\nvec3f(0.6017799,-0.1726654,0.),\nvec3f(-0.5554981,0.1559997,0.),\nvec3f(-0.3016369,-0.3900928,0.),\nvec3f(-0.5550632,-0.1723762,0.),\nvec3f(0.925029,0.2995041,0.),\nvec3f(-0.2473137,0.5538505,0.),\nvec3f(0.9183037,-0.2862392,0.),\nvec3f(0.2469421,0.6718712,0.),\nvec3f(0.3916397,-0.4328209,0.),\nvec3f(-0.03576927,-0.6220032,0.),\nvec3f(-0.04661255,0.7995201,0.),\nvec3f(0.4402924,0.3640312,0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.),\nvec3f(0.)\n);const PoissonSamplers64: array=array (\nvec3f(-0.613392,0.617481,0.),\nvec3f(0.170019,-0.040254,0.),\nvec3f(-0.299417,0.791925,0.),\nvec3f(0.645680,0.493210,0.),\nvec3f(-0.651784,0.717887,0.),\nvec3f(0.421003,0.027070,0.),\nvec3f(-0.817194,-0.271096,0.),\nvec3f(-0.705374,-0.668203,0.),\nvec3f(0.977050,-0.108615,0.),\nvec3f(0.063326,0.142369,0.),\nvec3f(0.203528,0.214331,0.),\nvec3f(-0.667531,0.326090,0.),\nvec3f(-0.098422,-0.295755,0.),\nvec3f(-0.885922,0.215369,0.),\nvec3f(0.566637,0.605213,0.),\nvec3f(0.039766,-0.396100,0.),\nvec3f(0.751946,0.453352,0.),\nvec3f(0.078707,-0.715323,0.),\nvec3f(-0.075838,-0.529344,0.),\nvec3f(0.724479,-0.580798,0.),\nvec3f(0.222999,-0.215125,0.),\nvec3f(-0.467574,-0.405438,0.),\nvec3f(-0.248268,-0.814753,0.),\nvec3f(0.354411,-0.887570,0.),\nvec3f(0.175817,0.382366,0.),\nvec3f(0.487472,-0.063082,0.),\nvec3f(-0.084078,0.898312,0.),\nvec3f(0.488876,-0.783441,0.),\nvec3f(0.470016,0.217933,0.),\nvec3f(-0.696890,-0.549791,0.),\nvec3f(-0.149693,0.605762,0.),\nvec3f(0.034211,0.979980,0.),\nvec3f(0.503098,-0.308878,0.),\nvec3f(-0.016205,-0.872921,0.),\nvec3f(0.385784,-0.393902,0.),\nvec3f(-0.146886,-0.859249,0.),\nvec3f(0.643361,0.164098,0.),\nvec3f(0.634388,-0.049471,0.),\nvec3f(-0.688894,0.007843,0.),\nvec3f(0.464034,-0.188818,0.),\nvec3f(-0.440840,0.137486,0.),\nvec3f(0.364483,0.511704,0.),\nvec3f(0.034028,0.325968,0.),\nvec3f(0.099094,-0.308023,0.),\nvec3f(0.693960,-0.366253,0.),\nvec3f(0.678884,-0.204688,0.),\nvec3f(0.001801,0.780328,0.),\nvec3f(0.145177,-0.898984,0.),\nvec3f(0.062655,-0.611866,0.),\nvec3f(0.315226,-0.604297,0.),\nvec3f(-0.780145,0.486251,0.),\nvec3f(-0.371868,0.882138,0.),\nvec3f(0.200476,0.494430,0.),\nvec3f(-0.494552,-0.711051,0.),\nvec3f(0.612476,0.705252,0.),\nvec3f(-0.578845,-0.768792,0.),\nvec3f(-0.772454,-0.090976,0.),\nvec3f(0.504440,0.372295,0.),\nvec3f(0.155736,0.065157,0.),\nvec3f(0.391522,0.849605,0.),\nvec3f(-0.620106,-0.328104,0.),\nvec3f(0.789239,-0.419965,0.),\nvec3f(-0.545396,0.538133,0.),\nvec3f(-0.178564,-0.596057,0.)\n);fn computeShadowWithCSMPCSS(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uvDepthLayer: vec4f= vec4f(uvDepth.x,uvDepth.y,f32(layer),uvDepth.z);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array)->f32\n{var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;var exitCondition: bool=depthMetric>1.0 || depthMetric<0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);}\nfn computeShadowWithPCSS32(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);}\nfn computeShadowWithPCSS64(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32\n{return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);}\nfn computeShadowWithCSMPCSS16(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\nfn computeShadowWithCSMPCSS32(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\nfn computeShadowWithCSMPCSS64(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32\n{return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);}\n#endif\n";Ft.IncludesShadersStoreWGSL.shadowsVertex="#ifdef SHADOWS\n#if defined(SHADOWCSM{X})\nvertexOutputs.vPositionFromCamera{X}=view*worldPos;\n#if SHADOWCSMNUM_CASCADES{X}>0\nvertexOutputs.vPositionFromLight{X}_0=uniforms.lightMatrix{X}[0]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_0=(-vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_0= (vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#if SHADOWCSMNUM_CASCADES{X}>1\nvertexOutputs.vPositionFromLight{X}_1=uniforms.lightMatrix{X}[1]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_1=(-vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_1= (vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#if SHADOWCSMNUM_CASCADES{X}>2\nvertexOutputs.vPositionFromLight{X}_2=uniforms.lightMatrix{X}[2]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_2=(-vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_2= (vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#if SHADOWCSMNUM_CASCADES{X}>3\nvertexOutputs.vPositionFromLight{X}_3=uniforms.lightMatrix{X}[3]*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}_3=(-vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}_3= (vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif \n#elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvertexOutputs.vPositionFromLight{X}=uniforms.lightMatrix{X}*worldPos;\n#ifdef USE_REVERSE_DEPTHBUFFER\nvertexOutputs.vDepthMetric{X}=(-vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#else\nvertexOutputs.vDepthMetric{X}=(vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y;\n#endif\n#endif\n#endif\n";Ft.IncludesShadersStoreWGSL.fogFragmentDeclaration="#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vFogInfos: vec4f;uniform vFogColor: vec3f;varying vFogDistance: vec3f;fn CalcFogFactor()->f32\n{var fogCoeff: f32=1.0;var fogStart: f32=uniforms.vFogInfos.y;var fogEnd: f32=uniforms.vFogInfos.z;var fogDensity: f32=uniforms.vFogInfos.w;var fogDistance: f32=length(fragmentInputs.vFogDistance);if (FOGMODE_LINEAR==uniforms.vFogInfos.x)\n{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);}\nelse if (FOGMODE_EXP==uniforms.vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDensity);}\nelse if (FOGMODE_EXP2==uniforms.vFogInfos.x)\n{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);}\nreturn clamp(fogCoeff,0.0,1.0);}\n#endif\n";Ft.IncludesShadersStoreWGSL.bumpFragment="var uvOffset: vec2f= vec2f(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL)\n#ifdef NORMALXYSCALE\nvar normalScale: f32=1.0;\n#elif defined(BUMP)\nvar normalScale: f32=vBumpInfos.y;\n#else\nvar normalScale: f32=1.0;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nvar TBN: mat3x3f=vTBN;\n#elif defined(BUMP)\nvar TBNUV: vec2f=select(-vBumpUV,vBumpUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams);\n#else\nvar TBNUV: vec2f=select(-vDetailUV,vDetailUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,vPositionW,TBNUV, vec2f(1.,1.));\n#endif\n#elif defined(ANISOTROPIC)\n#if defined(TANGENT) && defined(NORMAL)\nvar TBN: mat3x3f=vTBN;\n#else\nvar TBNUV: vec2f=select( -vMainUV1,vMainUV1,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW,vPositionW,TBNUV, vec2f(1.,1.));\n#endif\n#endif\n#ifdef PARALLAX\nvar invTBN: mat3x3f=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef DETAIL\nvar detailColor: vec4f=textureSample(detail,detailSampler,vDetailUV+uvOffset);var detailNormalRG: vec2f=detailColor.wy*2.0-1.0;var detailNormalB: f32=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));var detailNormal: vec3f= vec3f(detailNormalRG,detailNormalB);\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\n#define CUSTOM_FRAGMENT_BUMP_FRAGMENT\nnormalW=normalize(textureSample(bump,bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize( mat3x3f(normalMatrix)*normalW);\n#elif !defined(DETAIL)\nnormalW=perturbNormal(TBN,textureSample(bump,bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y);\n#else\nvar bumpNormal: vec3f=textureSample(bump,bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0;\n#if DETAIL_NORMALBLENDMETHOD==0 \ndetailNormal.xy*=vDetailInfos.z;var blendedNormal: vec3f=normalize( vec3f(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z));\n#elif DETAIL_NORMALBLENDMETHOD==1 \ndetailNormal.xy*=vDetailInfos.z;bumpNormal+= vec3f(0.0,0.0,1.0);detailNormal*= vec3f(-1.0,-1.0,1.0);var blendedNormal: vec3f=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal;\n#endif\nnormalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y);\n#endif\n#elif defined(DETAIL)\ndetailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z);\n#endif\n";Ft.IncludesShadersStoreWGSL.bumpFragmentMainFunctions="#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL)\n#if defined(TANGENT) && defined(NORMAL) \nvarying vTBN: mat3x3f;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform normalMatrix: mat4x4f;\n#if defined(WEBGL2) || defined(WEBGPU)\nfn toNormalMatrix(wMatrix: mat4x4f)->mat4x4f\n{var ret: mat4x4f=inverse(wMatrix);ret=transpose(ret);ret[0][3]=0.;ret[1][3]=0.;ret[2][3]=0.;ret[3]= vec4f(0.,0.,0.,1.);return ret;}\n#else\nfn toNormalMatrix(m: mat4x4f)->mat4x4f\n{var a00: f32=m[0][0],a01=m[0][1],a02=m[0][2],a03=m[0][3],\na10=m[1][0],a11=m[1][1],a12=m[1][2],a13=m[1][3],\na20=m[2][0],a21=m[2][1],a22=m[2][2],a23=m[2][3],\na30=m[3][0],a31=m[3][1],a32=m[3][2],a33=m[3][3],\nb00=a00*a11-a01*a10,\nb01=a00*a12-a02*a10,\nb02=a00*a13-a03*a10,\nb03=a01*a12-a02*a11,\nb04=a01*a13-a03*a11,\nb05=a02*a13-a03*a12,\nb06=a20*a31-a21*a30,\nb07=a20*a32-a22*a30,\nb08=a20*a33-a23*a30,\nb09=a21*a32-a22*a31,\nb10=a21*a33-a23*a31,\nb11=a22*a33-a23*a32,\ndet=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;var mi: mat4x4f= mat4x4f(\na11*b11-a12*b10+a13*b09,\na02*b10-a01*b11-a03*b09,\na31*b05-a32*b04+a33*b03,\na22*b04-a21*b05-a23*b03,\na12*b08-a10*b11-a13*b07,\na00*b11-a02*b08+a03*b07,\na32*b02-a30*b05-a33*b01,\na20*b05-a22*b02+a23*b01,\na10*b10-a11*b08+a13*b06,\na01*b08-a00*b10-a03*b06,\na30*b04-a31*b02+a33*b00,\na21*b02-a20*b04-a23*b00,\na11*b07-a10*b09-a12*b06,\na00*b09-a01*b07+a02*b06,\na31*b01-a30*b03-a32*b00,\na20*b03-a21*b01+a22*b00)/det;return mat4x4f(mi[0][0],mi[1][0],mi[2][0],mi[3][0],\nmi[0][1],mi[1][1],mi[2][1],mi[3][1],\nmi[0][2],mi[1][2],mi[2][2],mi[3][2],\nmi[0][3],mi[1][3],mi[2][3],mi[3][3]);}\n#endif\n#endif\nfn perturbNormalBase(cotangentFrame: mat3x3f,normal: vec3f,scale: f32)->vec3f\n{\n#ifdef NORMALXYSCALE\nnormal=normalize(normal* vec3f(scale,scale,1.0));\n#endif\nreturn normalize(cotangentFrame*normal);}\nfn perturbNormal(cotangentFrame: mat3x3f,textureSample: vec3f,scale: f32)->vec3f\n{return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);}\nfn cotangent_frame(normal: vec3f,p: vec3f,uv: vec2f,tangentSpaceParams: vec2f)->mat3x3f\n{var dp1: vec3f=dpdx(p);var dp2: vec3f=dpdy(p);var duv1: vec2f=dpdx(uv);var duv2: vec2f=dpdy(uv);var dp2perp: vec3f=cross(dp2,normal);var dp1perp: vec3f=cross(normal,dp1);var tangent: vec3f=dp2perp*duv1.x+dp1perp*duv2.x;var bitangent: vec3f=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;var det: f32=max(dot(tangent,tangent),dot(bitangent,bitangent));var invmax: f32=select(inverseSqrt(det),0.0,det==0.0);return mat3x3f(tangent*invmax,bitangent*invmax,normal);}\n#endif\n";Ft.IncludesShadersStoreWGSL.samplerFragmentDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying v_VARYINGNAME_UV: vec2f;\n#endif\nuniform _SAMPLERNAME_Sampler: sampler;uniform _SAMPLERNAME_: texture_2d;\n#endif\n";Ft.IncludesShadersStoreWGSL.bumpFragmentFunctions="#if defined(BUMP)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump)\n#endif\n#if defined(DETAIL)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail)\n#endif\n#if defined(BUMP) && defined(PARALLAX)\nconst minSamples: f32=4.;const maxSamples: f32=15.;const iMaxSamples: i32=15;fn parallaxOcclusion(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32)->vec2f {var parallaxLimit: f32=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;var vOffsetDir: vec2f=normalize(vViewDirCoT.xy);var vMaxOffset: vec2f=vOffsetDir*parallaxLimit;var numSamples: f32=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));var stepSize: f32=1.0/numSamples;var currRayHeight: f32=1.0;var vCurrOffset: vec2f= vec2f(0,0);var vLastOffset: vec2f= vec2f(0,0);var lastSampledHeight: f32=1.0;var currSampledHeight: f32=1.0;var keepWorking: bool=true;for (var i: i32=0; icurrRayHeight)\n{var delta1: f32=currSampledHeight-currRayHeight;var delta2: f32=(currRayHeight+stepSize)-lastSampledHeight;var ratio: f32=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;}\nelse\n{currRayHeight-=stepSize;vLastOffset=vCurrOffset;\n#ifdef PARALLAX_RHS\nvCurrOffset-=stepSize*vMaxOffset;\n#else\nvCurrOffset+=stepSize*vMaxOffset;\n#endif\nlastSampledHeight=currSampledHeight;}}\nreturn vCurrOffset;}\nfn parallaxOffset(viewDir: vec3f,heightScale: f32)->vec2f\n{var height: f32=textureSample(bump,bumpSampler,vBumpUV).w;var texCoordOffset: vec2f=heightScale*viewDir.xy*height;\n#ifdef PARALLAX_RHS\nreturn texCoordOffset;\n#else\nreturn -texCoordOffset;\n#endif\n}\n#endif\n";const Wd={texture_1d:nd.E1d,texture_2d:nd.E2d,texture_2d_array:nd.E2dArray,texture_3d:nd.E3d,texture_cube:nd.Cube,texture_cube_array:nd.CubeArray,texture_multisampled_2d:nd.E2d,texture_depth_2d:nd.E2d,texture_depth_2d_array:nd.E2dArray,texture_depth_cube:nd.Cube,texture_depth_cube_array:nd.CubeArray,texture_depth_multisampled_2d:nd.E2d,texture_storage_1d:nd.E1d,texture_storage_2d:nd.E2d,texture_storage_2d_array:nd.E2dArray,texture_storage_3d:nd.E3d,texture_external:null};class Hd extends Vd{constructor(){super(...arguments),this.shaderLanguage=ht.WGSL,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0}preProcessor(e,t,i,s,r){for(const t in i){if("__VERSION__"===t)continue;const s=i[t];isNaN(parseInt(s))&&isNaN(parseFloat(s))||(e=`const ${t} = ${s};\n`+e)}return e}_getArraySize(e,t,i){let s=0;const r=t.lastIndexOf(">");if(t.indexOf("array")>=0&&r>0){let e=r;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;const n=t.substring(e+1,r);for(s=+n,isNaN(s)&&(s=+i[n.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,s]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){const t=`struct ${Vd.InternalsUBOName} {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar internals : ${Vd.InternalsUBOName};\n`;return-1!==e.indexOf(t)?e:t+Pu(e)}varyingCheck(e,t){return/(flat|linear|perspective)?\s*(center|centroid|sample)?\s*\bvarying\b/.test(e)}varyingProcessor(e,t,i){const s=/\s*(flat|linear|perspective)?\s*(center|centroid|sample)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==s){const r=s[1]??"perspective",n=s[2]??"center",o=s[4],a=s[3],l="flat"===r?`@interpolate(${r})`:`@interpolate(${r}, ${n})`;let h;t?(h=this._webgpuProcessingContext.availableVaryings[a],void 0===h&&J.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`)):(h=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(a,o,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=h,this._varyingsWGSL.push(` @location(${h}) ${l} ${a} : ${o},`),this._varyingNamesWGSL.push(a)),e=""}return e}attributeProcessor(e,t){const i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){const s=i[2],r=i[1],n=this._webgpuProcessingContext.getAttributeNextLocation(s,this._getArraySize(r,s,t)[2]);this._webgpuProcessingContext.availableAttributes[r]=n,this._webgpuProcessingContext.orderedAttributes[n]=r;const o=this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents[r];if(void 0!==o){const e=o<0?-1===o?"i32":"vec"+-o+"":1===o?"u32":"vec"+o+"",t=`_int_${r}_`;this._attributesInputWGSL.push(`@location(${n}) ${t} : ${e},`),this._attributesWGSL.push(`${r} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${r} = ${s}(vertexInputs_.${t});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${n}) ${r} : ${s},`),this._attributesWGSL.push(`${r} : ${s},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${r} = vertexInputs_.${r};`);e=""}return e}uniformProcessor(e,t,i){const s=this.uniformRegexp.exec(e);if(null!==s){const t=s[2],r=s[1];this._addUniformToLeftOverUBO(r,t,i),e=""}return e}textureProcessor(e,t,i){const s=this.textureRegexp.exec(e);if(null!==s){const r=s[1],n=s[2],o=!!s[3],a=s[4],l=a.indexOf("storage")>0,h=s[6],c=l?h.substring(0,h.indexOf(",")).trim():null;let u=o?this._getArraySize(r,n,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[r];if(d)u=d.textures.length;else{d={isTextureArray:u>0,isStorageTexture:l,textures:[],sampleType:_d.Float},u=u||1;for(let e=0;e0,f=Wd[a],_=p?_d.Depth:"u32"===h?_d.Uint:"i32"===h?_d.Sint:_d.Float;if(d.sampleType=_,void 0===f)throw`Can't get the texture dimension corresponding to the texture function "${a}"!`;for(let i=0;i=0?"\n if (internals.yFactor_ == 1.) {\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\n }\n ":"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);const s=this._buildLeftOverUBO();t=s+t,e=(e=(e=s+e).replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;")).replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let r="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesInputWGSL.length>0&&(r+=this._attributesInputWGSL.join("\n")),r+="\n};\nvar vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(r+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n",r+=this._attributesWGSL.join("\n"),r+="\n};\nvar vertexInputs : VertexInputs_;\n");let n="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join("\n")),n+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=r+n+e;let o=`\n vertexInputs${this._hasNonFloatAttribute?"_":""} = input;\n`;this._hasNonFloatAttribute&&(o+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n",o+=this._attributesConversionCodeWGSL.join("\n"),o+="\n");let a=-1!==e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS");e=(a?"diagnostic(off, derivative_uniformity);\n":"")+Du(e,"fn main",o," vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;"),t=(t=t.replace(/#define (\w+)\s+(\d+\.?\d*)/g,"const $1 = $2;")).replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let l="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(l+=this._varyingsWGSL.join("\n")),l+="\n};\nvar fragmentInputs : FragmentInputs;\n";let h="struct FragmentOutputs {\n @location(0) color : vec4,\n",c=!1,u=0;for(;!(c||(u=t.indexOf("fragmentOutputs.fragDepth",u),u<0));){const e=u;for(c=!0;u>1&&"\n"!==t.charAt(u);){if("/"===t.charAt(u)&&"/"===t.charAt(u-1)){c=!1;break}u--}u=e+25}c&&(h+=" @builtin(frag_depth) fragDepth: f32,\n"),h+="};\nvar fragmentOutputs : FragmentOutputs;\n";const d=" fragmentInputs = input;\n "+i;return a=-1!==(t=l+h+t).indexOf("#define DISABLE_UNIFORMITY_ANALYSIS"),t=(a?"diagnostic(off, derivative_uniformity);\n":"")+Du(t,"fn main",d," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this._webgpuProcessingContext.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",s=`struct ${e} {\n`;for(const t of this._webgpuProcessingContext.leftOverUniforms){const r=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),n=Vd.UniformSizes[r];if(t.length>0)if(n<=2){const n=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${n} {\n @size(16)\n el: ${r},\n }`,this._stridedUniformArrays.push(t.name),s+=` @align(16) ${t.name} : array<${n}, ${t.length}>,\n`}else s+=` ${t.name} : array<${t.type}, ${t.length}>,\n`;else s+=` ${t.name} : ${t.type},\n`}return s+="};\n",s=`${i}\n${s}`,s+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var uniforms : ${e};\n`,s}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const s=i.exec(e);if(null===s)break;const r=s[1],n=s[2],o=r.indexOf("Sampler")===r.length-7?r.substring(0,r.indexOf("Sampler")):null,a="sampler_comparison"===n?fd.Comparison:fd.Filtering;if(o){const e=this._webgpuProcessingContext.availableTextures[o];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[r];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:a},this._webgpuProcessingContext.availableSamplers[r]=l),this._addSamplerBindingDescription(r,l,t);const h=e.substring(0,s.index),c=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `,u=e.substring(s.index);e=h+c+u,i.lastIndex+=c.length}return e}_processCustomBuffers(e,t){const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const s=i.exec(e);if(null===s)break;const r=s[1],n=s[3];let o=s[4];const a=s[5];let l=this._webgpuProcessingContext.availableBuffers[o];if(!l){const e="uniform"===r?Gd.KnownUBOs[a]:null;let t;e?(o=a,t=e.binding,-1===t.groupIndex&&(t=this._webgpuProcessingContext.availableBuffers[o]?.binding,t||(t=this._webgpuProcessingContext.getNextFreeUBOBinding()))):t=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:t},this._webgpuProcessingContext.availableBuffers[o]=l}this._addBufferBindingDescription(o,this._webgpuProcessingContext.availableBuffers[o],"read_write"===n?pd.Storage:"storage"===r?pd.ReadOnlyStorage:pd.Uniform,t);const h=l.binding.groupIndex,c=l.binding.bindingIndex,u=e.substring(0,s.index),d=`@group(${h}) @binding(${c}) `,p=e.substring(s.index);e=u+d+p,i.lastIndex+=d.length}return e}_processStridedUniformArrays(e){for(const t of this._stridedUniformArrays)e=e.replace(new RegExp(`${t}\\s*\\[(.*?)\\]`,"g"),`${t}[$1].el`);return e}}class Xd{static ComputeNumMipmapLevels(e,t){return G.ILog2(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case ad.R8Unorm:case ad.R8Snorm:case ad.R8Uint:case ad.R8Sint:case ad.RG8Unorm:case ad.RG8Snorm:case ad.RG8Uint:case ad.RG8Sint:case ad.RGBA8Unorm:case ad.RGBA8UnormSRGB:case ad.RGBA8Snorm:case ad.RGBA8Uint:case ad.RGBA8Sint:case ad.BGRA8Unorm:case ad.BGRA8UnormSRGB:case ad.RGB10A2UINT:case ad.RGB10A2Unorm:case ad.RGB9E5UFloat:case ad.RG11B10UFloat:case ad.BC7RGBAUnorm:case ad.BC7RGBAUnormSRGB:case ad.BC6HRGBUFloat:case ad.BC6HRGBFloat:case ad.BC5RGUnorm:case ad.BC5RGSnorm:case ad.BC3RGBAUnorm:case ad.BC3RGBAUnormSRGB:case ad.BC2RGBAUnorm:case ad.BC2RGBAUnormSRGB:case ad.BC4RUnorm:case ad.BC4RSnorm:case ad.BC1RGBAUnorm:case ad.BC1RGBAUnormSRGB:case ad.ETC2RGB8Unorm:case ad.ETC2RGB8UnormSRGB:case ad.ETC2RGB8A1Unorm:case ad.ETC2RGB8A1UnormSRGB:case ad.ETC2RGBA8Unorm:case ad.ETC2RGBA8UnormSRGB:case ad.EACR11Unorm:case ad.EACR11Snorm:case ad.EACRG11Unorm:case ad.EACRG11Snorm:case ad.ASTC4x4Unorm:case ad.ASTC4x4UnormSRGB:case ad.ASTC5x4Unorm:case ad.ASTC5x4UnormSRGB:case ad.ASTC5x5Unorm:case ad.ASTC5x5UnormSRGB:case ad.ASTC6x5Unorm:case ad.ASTC6x5UnormSRGB:case ad.ASTC6x6Unorm:case ad.ASTC6x6UnormSRGB:case ad.ASTC8x5Unorm:case ad.ASTC8x5UnormSRGB:case ad.ASTC8x6Unorm:case ad.ASTC8x6UnormSRGB:case ad.ASTC8x8Unorm:case ad.ASTC8x8UnormSRGB:case ad.ASTC10x5Unorm:case ad.ASTC10x5UnormSRGB:case ad.ASTC10x6Unorm:case ad.ASTC10x6UnormSRGB:case ad.ASTC10x8Unorm:case ad.ASTC10x8UnormSRGB:case ad.ASTC10x10Unorm:case ad.ASTC10x10UnormSRGB:case ad.ASTC12x10Unorm:case ad.ASTC12x10UnormSRGB:case ad.ASTC12x12Unorm:case ad.ASTC12x12UnormSRGB:case ad.Stencil8:return 0;case ad.R16Uint:case ad.R16Sint:case ad.RG16Uint:case ad.RG16Sint:case ad.RGBA16Uint:case ad.RGBA16Sint:case ad.Depth16Unorm:return 5;case ad.R16Float:case ad.RG16Float:case ad.RGBA16Float:return 2;case ad.R32Uint:case ad.R32Sint:case ad.RG32Uint:case ad.RG32Sint:case ad.RGBA32Uint:case ad.RGBA32Sint:return 7;case ad.R32Float:case ad.RG32Float:case ad.RGBA32Float:case ad.Depth32Float:case ad.Depth32FloatStencil8:case ad.Depth24Plus:case ad.Depth24PlusStencil8:return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case ad.R8Unorm:case ad.R8Snorm:case ad.R8Uint:case ad.R8Sint:return{width:1,height:1,length:1};case ad.R16Uint:case ad.R16Sint:case ad.R16Float:case ad.RG8Unorm:case ad.RG8Snorm:case ad.RG8Uint:case ad.RG8Sint:return{width:1,height:1,length:2};case ad.R32Uint:case ad.R32Sint:case ad.R32Float:case ad.RG16Uint:case ad.RG16Sint:case ad.RG16Float:case ad.RGBA8Unorm:case ad.RGBA8UnormSRGB:case ad.RGBA8Snorm:case ad.RGBA8Uint:case ad.RGBA8Sint:case ad.BGRA8Unorm:case ad.BGRA8UnormSRGB:case ad.RGB9E5UFloat:case ad.RGB10A2UINT:case ad.RGB10A2Unorm:case ad.RG11B10UFloat:return{width:1,height:1,length:4};case ad.RG32Uint:case ad.RG32Sint:case ad.RG32Float:case ad.RGBA16Uint:case ad.RGBA16Sint:case ad.RGBA16Float:return{width:1,height:1,length:8};case ad.RGBA32Uint:case ad.RGBA32Sint:case ad.RGBA32Float:return{width:1,height:1,length:16};case ad.Stencil8:throw"No fixed size for Stencil8 format!";case ad.Depth16Unorm:return{width:1,height:1,length:2};case ad.Depth24Plus:throw"No fixed size for Depth24Plus format!";case ad.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case ad.Depth32Float:return{width:1,height:1,length:4};case ad.Depth32FloatStencil8:return{width:1,height:1,length:5};case ad.BC7RGBAUnorm:case ad.BC7RGBAUnormSRGB:case ad.BC6HRGBUFloat:case ad.BC6HRGBFloat:case ad.BC5RGUnorm:case ad.BC5RGSnorm:case ad.BC3RGBAUnorm:case ad.BC3RGBAUnormSRGB:case ad.BC2RGBAUnorm:case ad.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case ad.BC4RUnorm:case ad.BC4RSnorm:case ad.BC1RGBAUnorm:case ad.BC1RGBAUnormSRGB:case ad.ETC2RGB8Unorm:case ad.ETC2RGB8UnormSRGB:case ad.ETC2RGB8A1Unorm:case ad.ETC2RGB8A1UnormSRGB:case ad.EACR11Unorm:case ad.EACR11Snorm:return{width:4,height:4,length:8};case ad.ETC2RGBA8Unorm:case ad.ETC2RGBA8UnormSRGB:case ad.EACRG11Unorm:case ad.EACRG11Snorm:case ad.ASTC4x4Unorm:case ad.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case ad.ASTC5x4Unorm:case ad.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case ad.ASTC5x5Unorm:case ad.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case ad.ASTC6x5Unorm:case ad.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case ad.ASTC6x6Unorm:case ad.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case ad.ASTC8x5Unorm:case ad.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case ad.ASTC8x6Unorm:case ad.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case ad.ASTC8x8Unorm:case ad.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case ad.ASTC10x5Unorm:case ad.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case ad.ASTC10x6Unorm:case ad.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case ad.ASTC10x8Unorm:case ad.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case ad.ASTC10x10Unorm:case ad.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case ad.ASTC12x10Unorm:case ad.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case ad.ASTC12x12Unorm:case ad.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}static IsCompressedFormat(e){switch(e){case ad.BC7RGBAUnormSRGB:case ad.BC7RGBAUnorm:case ad.BC6HRGBFloat:case ad.BC6HRGBUFloat:case ad.BC5RGSnorm:case ad.BC5RGUnorm:case ad.BC4RSnorm:case ad.BC4RUnorm:case ad.BC3RGBAUnormSRGB:case ad.BC3RGBAUnorm:case ad.BC2RGBAUnormSRGB:case ad.BC2RGBAUnorm:case ad.BC1RGBAUnormSRGB:case ad.BC1RGBAUnorm:case ad.ETC2RGB8Unorm:case ad.ETC2RGB8UnormSRGB:case ad.ETC2RGB8A1Unorm:case ad.ETC2RGB8A1UnormSRGB:case ad.ETC2RGBA8Unorm:case ad.ETC2RGBA8UnormSRGB:case ad.EACR11Unorm:case ad.EACR11Snorm:case ad.EACRG11Unorm:case ad.EACRG11Snorm:case ad.ASTC4x4Unorm:case ad.ASTC4x4UnormSRGB:case ad.ASTC5x4Unorm:case ad.ASTC5x4UnormSRGB:case ad.ASTC5x5Unorm:case ad.ASTC5x5UnormSRGB:case ad.ASTC6x5Unorm:case ad.ASTC6x5UnormSRGB:case ad.ASTC6x6Unorm:case ad.ASTC6x6UnormSRGB:case ad.ASTC8x5Unorm:case ad.ASTC8x5UnormSRGB:case ad.ASTC8x6Unorm:case ad.ASTC8x6UnormSRGB:case ad.ASTC8x8Unorm:case ad.ASTC8x8UnormSRGB:case ad.ASTC10x5Unorm:case ad.ASTC10x5UnormSRGB:case ad.ASTC10x6Unorm:case ad.ASTC10x6UnormSRGB:case ad.ASTC10x8Unorm:case ad.ASTC10x8UnormSRGB:case ad.ASTC10x10Unorm:case ad.ASTC10x10UnormSRGB:case ad.ASTC12x10Unorm:case ad.ASTC12x10UnormSRGB:case ad.ASTC12x12Unorm:case ad.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return ad.Depth16Unorm;case 16:return ad.Depth24Plus;case 13:return ad.Depth24PlusStencil8;case 14:return ad.Depth32Float;case 18:return ad.Depth32FloatStencil8;case 19:return ad.Stencil8;case 36492:return i?ad.BC7RGBAUnormSRGB:ad.BC7RGBAUnorm;case 36495:return ad.BC6HRGBUFloat;case 36494:return ad.BC6HRGBFloat;case 33779:return i?ad.BC3RGBAUnormSRGB:ad.BC3RGBAUnorm;case 33778:return i?ad.BC2RGBAUnormSRGB:ad.BC2RGBAUnorm;case 33777:case 33776:return i?ad.BC1RGBAUnormSRGB:ad.BC1RGBAUnorm;case 37808:return i?ad.ASTC4x4UnormSRGB:ad.ASTC4x4Unorm;case 36196:case 37492:return i?ad.ETC2RGB8UnormSRGB:ad.ETC2RGB8Unorm;case 37496:return i?ad.ETC2RGBA8UnormSRGB:ad.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return ad.R8Snorm;case 7:return ad.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return ad.R8Sint;case 9:return ad.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return ad.RGBA8Sint;default:return ad.RGBA8Snorm}case 0:switch(t){case 6:return ad.R8Unorm;case 7:return ad.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?ad.RGBA8UnormSRGB:ad.RGBA8Unorm;case 12:return i?ad.BGRA8UnormSRGB:ad.BGRA8Unorm;case 8:return ad.R8Uint;case 9:return ad.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return ad.RGBA8Uint;case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return ad.RGBA8Unorm}case 4:switch(t){case 8:return ad.R16Sint;case 9:return ad.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ad.RGBA16Sint}case 5:switch(t){case 8:return ad.R16Uint;case 9:return ad.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ad.RGBA16Uint}case 6:switch(t){case 8:return ad.R32Sint;case 9:return ad.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ad.RGBA32Sint}case 7:switch(t){case 8:return ad.R32Uint;case 9:return ad.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return ad.RGBA32Uint}case 1:switch(t){case 6:return ad.R32Float;case 7:return ad.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return ad.RGBA32Float}case 2:switch(t){case 6:return ad.R16Float;case 7:return ad.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return ad.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return ad.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"}case 14:switch(t){case 5:default:return ad.RGB9E5UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:default:return ad.RGB10A2Unorm;case 11:return ad.RGB10A2UINT}}return i?ad.RGBA8UnormSRGB:ad.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case ad.R8Unorm:case ad.R8Snorm:case ad.R8Uint:case ad.R8Sint:case ad.BC4RUnorm:case ad.BC4RSnorm:case ad.R16Uint:case ad.R16Sint:case ad.Depth16Unorm:case ad.R16Float:case ad.R32Uint:case ad.R32Sint:case ad.R32Float:case ad.Depth32Float:case ad.Stencil8:case ad.Depth24Plus:case ad.EACR11Unorm:case ad.EACR11Snorm:return 1;case ad.RG8Unorm:case ad.RG8Snorm:case ad.RG8Uint:case ad.RG8Sint:case ad.Depth32FloatStencil8:case ad.BC5RGUnorm:case ad.BC5RGSnorm:case ad.RG16Uint:case ad.RG16Sint:case ad.RG16Float:case ad.RG32Uint:case ad.RG32Sint:case ad.RG32Float:case ad.Depth24PlusStencil8:case ad.EACRG11Unorm:case ad.EACRG11Snorm:return 2;case ad.RGB9E5UFloat:case ad.RG11B10UFloat:case ad.BC6HRGBUFloat:case ad.BC6HRGBFloat:case ad.ETC2RGB8Unorm:case ad.ETC2RGB8UnormSRGB:return 3;case ad.RGBA8Unorm:case ad.RGBA8UnormSRGB:case ad.RGBA8Snorm:case ad.RGBA8Uint:case ad.RGBA8Sint:case ad.BGRA8Unorm:case ad.BGRA8UnormSRGB:case ad.RGB10A2UINT:case ad.RGB10A2Unorm:case ad.BC7RGBAUnorm:case ad.BC7RGBAUnormSRGB:case ad.BC3RGBAUnorm:case ad.BC3RGBAUnormSRGB:case ad.BC2RGBAUnorm:case ad.BC2RGBAUnormSRGB:case ad.BC1RGBAUnorm:case ad.BC1RGBAUnormSRGB:case ad.RGBA16Uint:case ad.RGBA16Sint:case ad.RGBA16Float:case ad.RGBA32Uint:case ad.RGBA32Sint:case ad.RGBA32Float:case ad.ETC2RGB8A1Unorm:case ad.ETC2RGB8A1UnormSRGB:case ad.ETC2RGBA8Unorm:case ad.ETC2RGBA8UnormSRGB:case ad.ASTC4x4Unorm:case ad.ASTC4x4UnormSRGB:case ad.ASTC5x4Unorm:case ad.ASTC5x4UnormSRGB:case ad.ASTC5x5Unorm:case ad.ASTC5x5UnormSRGB:case ad.ASTC6x5Unorm:case ad.ASTC6x5UnormSRGB:case ad.ASTC6x6Unorm:case ad.ASTC6x6UnormSRGB:case ad.ASTC8x5Unorm:case ad.ASTC8x5UnormSRGB:case ad.ASTC8x6Unorm:case ad.ASTC8x6UnormSRGB:case ad.ASTC8x8Unorm:case ad.ASTC8x8UnormSRGB:case ad.ASTC10x5Unorm:case ad.ASTC10x5UnormSRGB:case ad.ASTC10x6Unorm:case ad.ASTC10x6UnormSRGB:case ad.ASTC10x8Unorm:case ad.ASTC10x8UnormSRGB:case ad.ASTC10x10Unorm:case ad.ASTC10x10UnormSRGB:case ad.ASTC12x10Unorm:case ad.ASTC12x10UnormSRGB:case ad.ASTC12x12Unorm:case ad.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case ad.Stencil8:case ad.Depth32FloatStencil8:case ad.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case ad.Depth32FloatStencil8:case ad.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case ad.Depth16Unorm:return ad.Depth16Unorm;case ad.Depth24Plus:case ad.Depth24PlusStencil8:return ad.Depth24Plus;case ad.Depth32Float:case ad.Depth32FloatStencil8:return ad.Depth32Float}return e}static GetSample(e){return e>1?4:1}}class Yd{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){return this._webgpuMSAATexture?.[e]??null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),-1===t&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(const e of this._webgpuMSAATexture)e?.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this._originalFormatIsRGB=!1,this.format=ad.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,s,r,n,o,a){let l=nd.E2d,h=1;s?(l=i?nd.CubeArray:nd.Cube,h=6*(a||1)):r?(l=nd.E3d,h=1):i&&(l=nd.E2dArray,h=a);const c=Xd.GetDepthFormatOnly(this.format),u=Xd.HasDepthAndStencilAspects(this.format)?od.DepthOnly:od.All;this.createView({label:`TextureView${r?"3D":s?"Cube":"2D"}${i?"_Array"+h:""}_${n}x${o}_${t?"wmips":"womips"}_${this.format}_${l}`,format:c,dimension:l,mipLevelCount:t?G.ILog2(Math.max(n,o))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:h,aspect:u})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){this._webgpuTexture?.destroy(),this.releaseMSAATexture(),this._copyInvertYTempTexture?.destroy(),this.reset()}}const jd="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) out flat ivec2 vTextureSize;\n #endif\n\n void main() {\n #ifdef INVERTY\n vTextureSize = textureSize(img, 0);\n #endif\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",$d=jd;var Kd,qd;!function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"}(Kd||(Kd={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(qd||(qd={}));const Qd=[{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(location = 0) out vec2 vTex;\n\n void main() {\n vTex = tex[gl_VertexIndex];\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform sampler imgSampler;\n layout(set = 0, binding = 1) uniform texture2D img;\n\n layout(location = 0) in vec2 vTex;\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = texture(sampler2D(img, imgSampler), vTex);\n }\n "},{vertex:jd,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "},{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n\n void main() {\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform Uniforms {\n uniform vec4 color;\n };\n\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = color;\n }\n "},{vertex:$d,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n layout(set = 0, binding = 1) uniform Params {\n float ofstX;\n float ofstY;\n float width;\n float height;\n };\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) {\n discard;\n }\n if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) {\n discard;\n }\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "}],Zd={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};class Jd{constructor(e,t,i,s,r,n){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._glslang=i,this._tintWASM=s,this._bufferManager=r,-1!==n.indexOf(Ju.RG11B10UFloatRenderable)){const e=Object.keys(Zd);Zd[ad.RG11B10UFloat]=Zd[e[e.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:hd.Linear}),this._videoSampler=t.createSampler({minFilter:hd.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,td.Uniform|td.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(ad.RGBA8Unorm),this._getVideoPipeline(ad.RGBA8Unorm)}_getPipeline(e,t=Kd.MipMap,i){const s=t===Kd.MipMap?1:t===Kd.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===Kd.Clear?8:t===Kd.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let r=this._pipelines[e][s];if(!r){let n="#version 450\n";t!==Kd.InvertYPremultiplyAlpha&&t!==Kd.InvertYPremultiplyAlphaWithOfst||(i.invertY&&(n+="#define INVERTY\n"),i.premultiplyAlpha&&(n+="#define PREMULTIPLYALPHA\n"));let o=this._compiledShaders[s];if(!o){let e=this._glslang.compileGLSL(n+Qd[t].vertex,"vertex"),i=this._glslang.compileGLSL(n+Qd[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));const r=this._device.createShaderModule({code:e}),a=this._device.createShaderModule({code:i});o=this._compiledShaders[s]=[r,a]}const a=this._device.createRenderPipeline({layout:xd.Auto,vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Td.TriangleStrip,stripIndexFormat:Rd.Uint16}});r=this._pipelines[e][s]=[a,a.getBindGroupLayout(0)]}return r}_getVideoPipeline(e,t=qd.DontInvertY){const i=t===qd.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let s=this._videoPipelines[e][i];if(!s){let t=this._videoCompiledShaders[i];if(!t){const e=this._device.createShaderModule({code:"\n struct VertexOutput {\n @builtin(position) Position : vec4,\n @location(0) fragUV : vec2\n }\n\n @vertex\n fn main(\n @builtin(vertex_index) VertexIndex : u32\n ) -> VertexOutput {\n var pos = array, 4>(\n vec2(-1.0, 1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, -1.0)\n );\n var tex = array, 4>(\n vec2(0.0, 0.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(1.0, 1.0)\n );\n\n var output: VertexOutput;\n\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = tex[VertexIndex];\n\n return output;\n }\n "}),s=this._device.createShaderModule({code:0===i?"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\n }\n ":"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y));\n }\n "});t=this._videoCompiledShaders[i]=[e,s]}const r=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:xd.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Td.TriangleStrip,stripIndexFormat:Rd.Uint16}});s=this._videoPipelines[e][i]=[r,r.getBindGroupLayout(0)]}return s}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,s=!1,r){const n=void 0===r,[o,a]=this._getVideoPipeline(i,s?qd.InvertY:qd.DontInvertY);n&&(r=this._device.createCommandEncoder({})),r.pushDebugGroup?.(`copy video to texture - invertY=${s}`);const l=t._hardwareTexture,h={label:`BabylonWebGPUDevice${this._engine.uniqueId}_copyVideoToTexture_${i}_${s?"InvertY":"DontInvertY"}${t.label?"_"+t.label:""}`,colorAttachments:[{view:l.underlyingResource.createView({format:i,dimension:nd.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:od.All}),loadOp:Od.Load,storeOp:Nd.Store}]},c=r.beginRenderPass(h),u={layout:a,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},d=this._device.createBindGroup(u);c.setPipeline(o),c.setBindGroup(0,d),c.draw(4,1,0,0),c.end(),r.popDebugGroup?.(),n&&(this._device.queue.submit([r.finish()]),r=null)}invertYPreMultiplyAlpha(e,t,i,s,r=!1,n=!1,o=0,a=0,l=1,h=0,c=0,u=0,d=0,p,f){const _=0!==u,m=void 0===p,[g,v]=this._getPipeline(s,_?Kd.InvertYPremultiplyAlphaWithOfst:Kd.InvertYPremultiplyAlpha,{invertY:r,premultiplyAlpha:n});let x;if(o=Math.max(o,0),m&&(p=this._device.createCommandEncoder({})),p.pushDebugGroup?.(`internal process texture - invertY=${r} premultiplyAlpha=${n}`),Xd.IsHardwareTexture(e)?(x=e.underlyingResource,r&&!n&&1===l&&0===o||(e=void 0)):(x=e,e=void 0),!x)return;_&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,c,u,d]),0,16);const T=e,S=T?._copyInvertYTempTexture??this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,s,1,p,rd.CopySrc|rd.RenderAttachment|rd.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),E=T?._copyInvertYRenderPassDescr??{label:`BabylonWebGPUDevice${this._engine.uniqueId}_invertYPreMultiplyAlpha_${s}_${r?"InvertY":"DontInvertY"}_${n?"PremultiplyAlpha":"DontPremultiplyAlpha"}`,colorAttachments:[{view:S.createView({format:s,dimension:nd.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:Od.Load,storeOp:Nd.Store}]},b=p.beginRenderPass(E);let C=_?T?._copyInvertYBindGroupWithOfst:T?._copyInvertYBindGroup;if(!C){const e={layout:v,entries:[{binding:0,resource:x.createView({format:s,dimension:nd.E2d,baseMipLevel:a,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:o})}]};_&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),C=this._device.createBindGroup(e)}b.setPipeline(g),b.setBindGroup(0,C),b.draw(4,1,0,0),b.end(),p.copyTextureToTexture({texture:S},{texture:x,mipLevel:a,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),T?(T._copyInvertYTempTexture=S,T._copyInvertYRenderPassDescr=E,_?T._copyInvertYBindGroupWithOfst=C:T._copyInvertYBindGroup=C):this._deferredReleaseTextures.push([S,null]),p.popDebugGroup?.(),m&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,s){const r=void 0===s,[n,o]=this._getPipeline(t,Kd.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});r&&(s=this._device.createCommandEncoder({})),s.pushDebugGroup?.("internal copy texture with invertY");const a=s.beginRenderPass(i),l=this._device.createBindGroup({layout:o,entries:[{binding:0,resource:e}]});a.setPipeline(n),a.setBindGroup(0,l),a.draw(4,1,0,0),a.end(),s.popDebugGroup?.(),r&&(this._device.queue.submit([s.finish()]),s=null)}createTexture(e,t=!1,i=!1,s=!1,r=!1,n=!1,o=ad.RGBA8Unorm,a=1,l,h=-1,c=0,u){a=Xd.GetSample(a);const d=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:d},f=Zd[o]?rd.RenderAttachment:0,_=Xd.IsCompressedFormat(o),m=t?Xd.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:rd.CopySrc|rd.CopyDst|rd.TextureBinding;c|=t&&!_?rd.CopySrc|f:0,_||n||(c|=f|rd.CopyDst);const v=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_Texture${n?"3D":"2D"}_${u?u+"_":""}${p.width}x${p.height}x${p.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${a}`,size:p,dimension:n?sd.E3d:sd.E2d,format:o,usage:g|c,sampleCount:a,mipLevelCount:m});return Xd.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,o,0,0,s,r,0,0),t&&i&&this.generateMipmaps(v,o,m,0,n,l)),v}createCubeTexture(e,t=!1,i=!1,s=!1,r=!1,n=ad.RGBA8Unorm,o=1,a,l=-1,h=0,c){o=Xd.GetSample(o);const u=Xd.IsImageBitmapArray(e)?e[0].width:e.width,d=Xd.IsImageBitmapArray(e)?e[0].height:e.height,p=Zd[n]?rd.RenderAttachment:0,f=Xd.IsCompressedFormat(n),_=t?Xd.ComputeNumMipmapLevels(u,d):1,m=l>=0?l:rd.CopySrc|rd.CopyDst|rd.TextureBinding;h|=t&&!f?rd.CopySrc|p:0,f||(h|=p|rd.CopyDst);const g=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${c?c+"_":""}${u}x${d}x6_${t?"wmips":"womips"}_${n}_samples${o}`,size:{width:u,height:d,depthOrArrayLayers:6},dimension:sd.E2d,format:n,usage:m|h,sampleCount:o,mipLevelCount:_});return Xd.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,u,d,n,s,r,0,0),t&&i&&this.generateCubeMipmaps(g,n,_,a)),g}generateCubeMipmaps(e,t,i,s){const r=void 0===s;r&&(s=this._device.createCommandEncoder({})),s.pushDebugGroup?.(`create cube mipmaps - ${i} levels`);for(let r=0;r<6;++r)this.generateMipmaps(e,t,i,r,!1,s);s.popDebugGroup?.(),r&&(this._device.queue.submit([s.finish()]),s=null)}generateMipmaps(e,t,i,s=0,r=!1,n){const o=void 0===n,[a,l]=this._getPipeline(t);let h;if(s=Math.max(s,0),o&&(n=this._device.createCommandEncoder({})),n.pushDebugGroup?.(`create mipmaps for face #${s} - ${i} levels`),Xd.IsHardwareTexture(e)?(h=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(h=e,e=void 0),!h)return;const c=e;for(let e=1;eh;)this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,h),c+=h;this._device.queue.writeBuffer(n,t+c,i.buffer,o+c,r-c)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const s=new Uint16Array(t);for(;e--;)i[e]=ru(s[e]);return i}readDataFromBuffer(e,t,i,s,r,n,o=0,a=0,l=null,h=!0,c=!1){const u=1===o?2:2===o?1:0,d=this._engine.uniqueId;return new Promise(((i,p)=>{e.mapAsync(id.Read,a,t).then((()=>{const d=e.getMappedRange(a,t);let p=l;if(c)p=null===p?Ar(o,t,!0,d):Ar(o,p.buffer,void 0,d);else if(null===p)switch(u){case 0:p=new Uint8Array(t),p.set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:p=new Float32Array(t/4),p.set(new Float32Array(d))}else switch(u){case 0:p=new Uint8Array(p.buffer),p.set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:p=new Float32Array(p.buffer),p.set(new Float32Array(d))}if(r!==n){1!==u||c||(r*=2,n*=2);const e=new Uint8Array(p.buffer);let t=r,i=0;for(let o=1;o{this._engine.isDisposed||this._engine.uniqueId!==d?i(new Uint8Array):p(e)}))}))}releaseBuffer(e){return tp._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e1?4:1;return ip[e.samplingMode]+sp[(e._comparisonFunction||514)-512+1]+rp[e.samplingMode]+((e._cachedWrapU??1)<<8)+((e._cachedWrapV??1)<<10)+((e._cachedWrapR??1)<<12)+((e.useMipMaps?1:0)<<14)+(t<<15)}static _GetSamplerFilterDescriptor(e,t){let i,s,r,n,o;const a=e.useMipMaps;switch(e.samplingMode){case 11:i=hd.Linear,s=hd.Linear,r=hd.Nearest,a||(n=o=0);break;case 3:case 3:i=hd.Linear,s=hd.Linear,a?r=hd.Linear:(r=hd.Nearest,n=o=0);break;case 8:i=hd.Nearest,s=hd.Nearest,a?r=hd.Linear:(r=hd.Nearest,n=o=0);break;case 4:i=hd.Nearest,s=hd.Nearest,r=hd.Nearest,a||(n=o=0);break;case 5:i=hd.Nearest,s=hd.Linear,r=hd.Nearest,a||(n=o=0);break;case 6:i=hd.Nearest,s=hd.Linear,a?r=hd.Linear:(r=hd.Nearest,n=o=0);break;case 7:i=hd.Nearest,s=hd.Linear,r=hd.Nearest,n=o=0;break;case 1:case 1:default:i=hd.Nearest,s=hd.Nearest,r=hd.Nearest,n=o=0;break;case 9:i=hd.Linear,s=hd.Nearest,r=hd.Nearest,a||(n=o=0);break;case 10:i=hd.Linear,s=hd.Nearest,a?r=hd.Linear:(r=hd.Nearest,n=o=0);break;case 2:case 2:i=hd.Linear,s=hd.Linear,r=hd.Nearest,n=o=0;break;case 12:i=hd.Linear,s=hd.Nearest,r=hd.Nearest,n=o=0}return t>1&&(0!==n||0!==o)&&r!==hd.Nearest?{magFilter:hd.Linear,minFilter:hd.Linear,mipmapFilter:hd.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:s,mipmapFilter:r,lodMinClamp:n,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return ld.Repeat;case 0:return ld.ClampToEdge;case 2:return ld.MirrorRepeat}return ld.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,t){const i=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,s=this._GetSamplerFilterDescriptor(e,i);return{label:t,...s,...this._GetSamplerWrappingDescriptor(e),compare:e._comparisonFunction?np.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:s.anisotropyEnabled?i:1}}static GetCompareFunction(e){switch(e){case 519:return ud.Always;case 514:return ud.Equal;case 516:return ud.Greater;case 518:return ud.GreaterEqual;case 513:default:return ud.Less;case 515:return ud.LessEqual;case 512:return ud.Never;case 517:return ud.NotEqual}}getSampler(e,t=!1,i=0,s){if(this.disabled)return this._device.createSampler(np._GetSamplerDescriptor(e,s));t?i=0:0===i&&(i=np.GetSamplerHashCode(e));let r=t?void 0:this._samplers[i];return r||(r=this._device.createSampler(np._GetSamplerDescriptor(e,s)),t||(this._samplers[i]=r)),r}}var op;!function(e){e[e.StencilReadMask=0]="StencilReadMask",e[e.StencilWriteMask=1]="StencilWriteMask",e[e.DepthBias=2]="DepthBias",e[e.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",e[e.DepthStencilState=4]="DepthStencilState",e[e.MRTAttachments1=5]="MRTAttachments1",e[e.MRTAttachments2=6]="MRTAttachments2",e[e.RasterizationState=7]="RasterizationState",e[e.ColorStates=8]="ColorStates",e[e.ShaderStage=9]="ShaderStage",e[e.TextureStage=10]="TextureStage",e[e.VertexState=11]="VertexState",e[e.NumStates=12]="NumStates"}(op||(op={}));const ap={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},lp={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class hp{constructor(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[ad.BGRA8Unorm],this.setColorFormat(ad.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(ad.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,s=0){if(i=Xd.GetSample(i),this.disabled){const r=hp._GetTopology(e);return this._setVertexState(t),this._setTextureState(s),this._parameter.pipeline=this._createRenderPipeline(t,r,i),hp.NumCacheMiss++,hp._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(s),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,hp.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return hp.NumCacheHitWithHash++,this._parameter.pipeline;const r=hp._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,r,i),this._setRenderPipeline(this._parameter),hp.NumCacheMiss++,hp._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){hp.NumPipelineCreationLastFrame=hp._NumPipelineCreationCurrentFrame,hp._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,s,r,n,o,a){this._depthWriteEnabled=o,this._depthTestEnabled=n,this._depthCompare=(a??519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(s),this.setDepthBias(r)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[op.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[op.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=Zd[e??""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const i=[0,0];let s=0,r=0,n=0;for(let o=0;o=32&&(r=0,s++)}this._mrtFormats.length=n,this._mrtAttachments1===i[0]&&this._mrtAttachments2===i[1]||(this._mrtAttachments1=i[0],this._mrtAttachments2=i[1],this._states[op.MRTAttachments1]=i[0],this._states[op.MRTAttachments2]=i[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=void 0===e?0:Zd[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(e??519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(e??519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=null===e?1:lp[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:lp[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:lp[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[op.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[op.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,s,r,n,o){this._stencilEnabled=e,this._stencilFrontCompare=(t??519)-512,this._stencilFrontDepthFailOp=null===i?1:lp[i],this._stencilFrontPassOp=null===s?2:lp[s],this._stencilFrontFailOp=null===r?1:lp[r],this.setStencilReadMask(n),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return Td.TriangleList;case 2:case 3:return Td.PointList;case 1:case 4:return Td.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return Td.LineStrip;case 7:return Td.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return yd.Add;case 32778:return yd.Subtract;case 32779:return yd.ReverseSubtract;case 32775:return yd.Min;case 32776:return yd.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return Cd.Zero;case 1:default:return Cd.One;case 768:return Cd.Src;case 769:return Cd.OneMinusSrc;case 770:return Cd.SrcAlpha;case 771:return Cd.OneMinusSrcAlpha;case 772:return Cd.DstAlpha;case 773:return Cd.OneMinusDstAlpha;case 774:return Cd.Dst;case 775:return Cd.OneMinusDst;case 776:return Cd.SrcAlphaSaturated;case 32769:case 32771:return Cd.Constant;case 32770:case 32772:return Cd.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:return ud.Never;case 1:return ud.Less;case 2:return ud.Equal;case 3:return ud.LessEqual;case 4:return ud.Greater;case 5:return ud.NotEqual;case 6:return ud.GreaterEqual;case 7:return ud.Always}return ud.Never}static _GetStencilOpFunction(e){switch(e){case 0:return Ad.Zero;case 1:return Ad.Keep;case 2:return Ad.Replace;case 3:return Ad.IncrementClamp;case 4:return Ad.DecrementClamp;case 5:return Ad.Invert;case 6:return Ad.IncrementWrap;case 7:return Ad.DecrementWrap}return Ad.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,s=e.getSize();switch(t){case Ki.BYTE:switch(s){case 1:case 2:return i?Id.Snorm8x2:Id.Sint8x2;case 3:case 4:return i?Id.Snorm8x4:Id.Sint8x4}break;case Ki.UNSIGNED_BYTE:switch(s){case 1:case 2:return i?Id.Unorm8x2:Id.Uint8x2;case 3:case 4:return i?Id.Unorm8x4:Id.Uint8x4}break;case Ki.SHORT:switch(s){case 1:case 2:return i?Id.Snorm16x2:Id.Sint16x2;case 3:case 4:return i?Id.Snorm16x4:Id.Sint16x4}break;case Ki.UNSIGNED_SHORT:switch(s){case 1:case 2:return i?Id.Unorm16x2:Id.Uint16x2;case 3:case 4:return i?Id.Unorm16x4:Id.Uint16x4}break;case Ki.INT:switch(s){case 1:return Id.Sint32;case 2:return Id.Sint32x2;case 3:return Id.Sint32x3;case 4:return Id.Sint32x4}break;case Ki.UNSIGNED_INT:switch(s){case 1:return Id.Uint32;case 2:return Id.Uint32x2;case 3:return Id.Uint32x3;case 4:return Id.Uint32x4}break;case Ki.FLOAT:switch(s){case 1:return Id.Float32;case 2:return Id.Float32x2;case 3:return Id.Float32x3;case 4:return Id.Float32x4}}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${s}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:hp._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:hp._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:hp._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:hp._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:hp._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:hp._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[op.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace-1+((this._cullEnabled?this._cullFace:0)<<1)+((this._clampDepth?1:0)<<3)+((this._alphaToCoverageEnabled?1:0)<<4)+(e<<5)+(t<<8);this._rasterizationState!==i&&(this._rasterizationState=i,this._states[op.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=(0|(null===this._alphaBlendFuncParams[0]?2:ap[this._alphaBlendFuncParams[0]]))+((null===this._alphaBlendFuncParams[1]?2:ap[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:ap[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:ap[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[op.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.ColorStates))}_setDepthStencilState(){const e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[op.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,op.DepthStencilState))}_setVertexState(e){const t=this._statesLength;let i=op.VertexState;const s=e._pipelineContext,r=s.shaderProcessingContext.attributeNamesFromEffect,n=s.shaderProcessingContext.attributeLocationsFromEffect;let o,a=0;for(let e=0;e0)for(let e=0;e=this._video.HAVE_CURRENT_DATA}dispose(){}}class _p{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=_p._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],s=-1;i?s=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?np.GetSamplerHashCode(t):0;const r=s!==i.hashCode;r&&this.updateId++,this.isDirty||(this.isDirty=r)}setTexture(e,t){let i=this.textures[e],s=-1;i?s=i.texture?.uniqueId??-1:this.textures[e]=i={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},i.isExternalTexture&&this._numExternalTextures--,i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(i.isFloatOrDepthTexture=1===t.type||t.format>=13&&t.format<=18,i.isExternalTexture=fp.IsExternalTexture(t),i.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,i.isExternalTexture&&this._numExternalTextures++):(i.isFloatOrDepthTexture=!1,i.isExternalTexture=!1),i.texture=t;const r=s!==(t?.uniqueId??-1);r&&this.updateId++,this.isDirty||(this.isDirty=r)}}_p._Counter=0;class mp{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,td.CopyDst|td.Indirect|td.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=mp._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){this._isDirty||(this._isDirty=t?.uniqueId!==this.buffers[e]?.uniqueId),this.buffers[e]=t}setIndirectData(e,t,i){t!==this._currentInstanceCount&&this.indirectDrawBuffer&&this._indirectDrawData&&(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}}mp._Counter=0;class gp{constructor(){this.values={}}}class vp{static get Statistics(){return{totalCreated:vp.NumBindGroupsCreatedTotal,lastFrameCreated:vp.NumBindGroupsCreatedLastFrame,lookupLastFrame:vp.NumBindGroupsLookupLastFrame,noLookupLastFrame:vp.NumBindGroupsNoLookupLastFrame}}static ResetCache(){vp._Cache=new gp,vp.NumBindGroupsCreatedTotal=0,vp.NumBindGroupsCreatedLastFrame=0,vp.NumBindGroupsLookupLastFrame=0,vp.NumBindGroupsNoLookupLastFrame=0,vp._NumBindGroupsCreatedCurrentFrame=0,vp._NumBindGroupsLookupCurrentFrame=0,vp._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){vp.NumBindGroupsCreatedLastFrame=vp._NumBindGroupsCreatedCurrentFrame,vp.NumBindGroupsLookupLastFrame=vp._NumBindGroupsLookupCurrentFrame,vp.NumBindGroupsNoLookupLastFrame=vp._NumBindGroupsNoLookupCurrentFrame,vp._NumBindGroupsCreatedCurrentFrame=0,vp._NumBindGroupsLookupCurrentFrame=0,vp._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){let s,r=vp._Cache;const n=this.disabled||i.forceBindGroupCreation;if(!n){if(!t.isDirty(i.updateId)&&!i.isDirty)return vp._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const i of e.shaderProcessingContext.bufferNames){const e=t.buffers[i]?.uniqueId??0;let s=r.values[e];s||(s=new gp,r.values[e]=s),r=s}for(const t of e.shaderProcessingContext.samplerNames){const e=i.samplers[t]?.hashCode??0;let s=r.values[e];s||(s=new gp,r.values[e]=s),r=s}for(const t of e.shaderProcessingContext.textureNames){const e=i.textures[t]?.texture?.uniqueId??0;let s=r.values[e];s||(s=new gp,r.values[e]=s),r=s}s=r.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,s)return t.bindGroups=s,vp._NumBindGroupsLookupCurrentFrame++,s;s=[],t.bindGroups=s,n||(r.bindGroups=s),vp.NumBindGroupsCreatedTotal++,vp._NumBindGroupsCreatedCurrentFrame++;const o=e.bindGroupLayouts[i.textureState];for(let r=0;r"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=this._cacheSampler.getSampler(t,!1,e.hashCode,t.label)}else J.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.texture||n.storageTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){J.Error(`Trying to bind a null texture! entry=${JSON.stringify(n)}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||n.texture&&!t.view||n.storageTexture&&!t.viewForWriting)){J.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=n.storageTexture?t.viewForWriting:t.view}else J.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.externalTexture){const e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){J.Error(`Trying to bind a null external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){J.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(n)}, name=${l}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${e.texture?.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[s].resource=this._device.importExternalTexture({source:t})}else J.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.buffer){const e=t.buffers[l];if(e){const t=e.underlyingResource;a[s].resource.buffer=t,a[s].resource.size=e.capacity}else J.Error(`Can't find buffer "${l}". entry=${JSON.stringify(n)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const l=o[r];s[r]=this._device.createBindGroup({layout:l,entries:a})}return s}}vp.NumBindGroupsCreatedTotal=0,vp.NumBindGroupsCreatedLastFrame=0,vp.NumBindGroupsLookupLastFrame=0,vp.NumBindGroupsNoLookupLastFrame=0,vp._Cache=new gp,vp._NumBindGroupsCreatedCurrentFrame=0,vp._NumBindGroupsLookupCurrentFrame=0,vp._NumBindGroupsNoLookupCurrentFrame=0;Ft.ShadersStoreWGSL.clearQuadVertexShader="uniform depthValue: f32;const pos=array(\nvec2f(-1.0,1.0),\nvec2f(1.0,1.0),\nvec2f(-1.0,-1.0),\nvec2f(1.0,-1.0)\n);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.position=vec4f(pos[input.vertexIndex],uniforms.depthValue,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";Ft.ShadersStoreWGSL.clearQuadPixelShader="uniform color: vec4f;@fragment\nfn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=uniforms.color;}\n";class xp{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new up(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"],void 0,void 0,void 0,void 0,void 0,void 0,ht.WGSL)}clear(e,t,i,s,r=1){let n,o,a=null;const l=!!this._engine._currentRenderTarget;if(e)n=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t1?2**36:0)+h*2**37,o=this._keyTemp.join("_"),a=this._bundleCache[o],a)return a;n=this._device.createRenderBundleEncoder({label:"clearQuadRenderBundle",colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:Xd.GetSample(r)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!s&&!!this._depthTextureFormat&&Xd.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(s?255:0),this._cacheRenderPipeline.setStencilCompare(s?519:512),this._cacheRenderPipeline.setStencilPassOp(s?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const h=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,r),c=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),c.uniformBuffer.update();const u=l?this._engine._ubInvertY:this._engine._ubDontInvertY,d=c.uniformBuffer.getBuffer(),p=d.uniqueId+"-"+u.uniqueId;let f=this._bindGroups[p];if(!f){const e=c.bindGroupLayouts[0];f=this._bindGroups[p]=[],f.push(this._device.createBindGroup({label:`clearQuadBindGroup0-${p}`,layout:e[0],entries:[]})),Gd._SimplifiedKnownBindings||f.push(this._device.createBindGroup({label:`clearQuadBindGroup1-${p}`,layout:e[1],entries:[]})),f.push(this._device.createBindGroup({label:`clearQuadBindGroup${Gd._SimplifiedKnownBindings?1:2}-${p}`,layout:e[Gd._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:u.underlyingResource,size:u.capacity}},{binding:1,resource:{buffer:d.underlyingResource,size:d.capacity}}]}))}n.setPipeline(h);for(let e=0;e{const e=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,e}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==s)return null;throw e}))}async readValue(e=0){const t=this._getBuffer(e,1);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(id.Read).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}async readTwoValuesAndSubtract(e=0){const t=this._getBuffer(e,2);if(null===t)return null;const i=this._engine.uniqueId;return t.mapAsync(id.Read).then((()=>{const e=new BigUint64Array(t.getMappedRange()),i=Number(e[1]-e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i}),(e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e}))}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0})))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;const i=this._engine.frameId;this._measureDuration.stopPass(e).then((e=>{t._addDuration(i,null!==e&&e>0?e:0)}))}dispose(){this._measureDuration?.dispose()}}class Mp{constructor(e,t,i,s=2,r){this._count=s,this._querySet=new Ip(e,s,wd.Timestamp,t,i,!0,r)}start(e){e.writeTimestamp?.(this._querySet.querySet,0)}async stop(e){return e.writeTimestamp?.(this._querySet.querySet,1),e.writeTimestamp?this._querySet.readTwoValuesAndSubtract(0):0}startPass(e,t){if(t+3>this._count)throw new Error("WebGPUDurationMeasure: index out of range ("+t+")");e.timestampWrites={querySet:this._querySet.querySet,beginningOfPassWriteIndex:t+2,endOfPassWriteIndex:t+3}}async stopPass(e){return this._querySet.readTwoValuesAndSubtract(e+2)}dispose(){this._querySet.dispose()}}class Dp{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;const t=void 0!==this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,s=50,r=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=r,this._allocateNewIndices(s)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();const e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e})))}_allocateNewIndices(e){e=e??this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose),1e3)}dispose(){this._querySet?.dispose(),this._availableIndices.length=0}}class Op{async initTwgsl(e){if(!Op._Twgsl)return e=e||{},(e={...Op._TWgslDefaultOptions,...e}).twgsl?(Op._Twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await Ii.LoadBabylonScriptAsync(e.jsPath),self.twgsl?(Op._Twgsl=await self.twgsl(Ii.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=Op._Twgsl.convertSpirV2WGSL(e,Op.DisableUniformityAnalysis||t);return Op.ShowWGSLShaderCode&&(J.Log(i),J.Log("***********************************************")),Op.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}Op._TWgslDefaultOptions={jsPath:`${Ii._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${Ii._DefaultCdnUrl}/twgsl/twgsl.wasm`},Op.ShowWGSLShaderCode=!1,Op.DisableUniformityAnalysis=!1,Op._Twgsl=null;class Np{constructor(e,t,i){this._record=!1,this._play=!1,this._playBundleListIndex=0,this._allBundleLists=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._allBundleLists.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endRenderPass(e){if(!this._record&&!this._play)return!1;let t;if(this._record)t=this._bundleList.clone(),this._allBundleLists.push(t),this._bundleList.reset();else{if(this._playBundleListIndex>=this._allBundleLists.length)throw new Error(`Invalid playBundleListIndex! Your snapshot is no longer valid for the current frame, you should recreate a new one. playBundleListIndex=${this._playBundleListIndex}, allBundleLists.length=${this._allBundleLists.length}}`);t=this._allBundleLists[this._playBundleListIndex++]}return t.run(e),1===this._mode&&this._engine._reportDrawCall(t.numDrawCalls),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0}reset(){this.enabled=!1,this.enabled=!0}}Ft.ShadersStoreWGSL.postprocessVertexShader="attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\nfn main(input : VertexInputs)->FragmentInputs {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class wp extends fp{constructor(e){super(e)}}const Fp={label:"TextureView_SwapChain_ResolveTarget",dimension:sd.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Lp={label:"TextureView_SwapChain",dimension:sd.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},Bp=new j;class Vp extends si{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return!!this._cacheSampler&&this._cacheSampler.disabled}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}areAllEffectsReady(){return!0}getFontOffset(e){return Pr(e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then((e=>!!e),(()=>!1)).catch((()=>!1)):Promise.resolve(!1)}static get IsSupported(){return J.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){return this.name+this.version}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get enableGPUTimingMeasurements(){return this._timestampQuery.enable}set enableGPUTimingMeasurements(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new Xh:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new Vp(e,t);return new Promise((e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then((()=>e(i)))}))}constructor(e,t={}){super(t.antialias??!0,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._timestampIndex=0,this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this.scenes=[],this._virtualScenes=new Array,this._commandBuffers=[null,null],this._currentRenderPass=null,this._mainRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._rttRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._pendingDebugCommands=[],this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this._snapshotRenderingMode=0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._performanceMonitor=new Cr,this._name="WebGPU",this._drawCalls=new Is,t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=t.enableGPUDebugMarkers??!1,J.Log(`Babylon.js v${Br.Version} - ${this.description} engine`),navigator.gpu?(t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,navigator&&navigator.userAgent&&this._setupMobileChecks(),this._sharedInit(this._renderingCanvas),this._shaderProcessor=new zd,this._shaderProcessorWGSL=new Hd):J.Error("WebGPU is not supported by your browser.")}initAsync(e,t){return this.uniqueId=Vp._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,this._initGlslang(e??this._options?.glslangOptions).then((e=>(this._glslang=e,this._tintWASM=Vp.UseTWGSL?new Op:null,this._tintWASM?this._tintWASM.initTwgsl(t??this._options?.twgslOptions).then((()=>navigator.gpu.requestAdapter(this._options))):navigator.gpu.requestAdapter(this._options)))).then((e=>{if(e){this._adapter=e,this._adapterSupportedExtensions=[],this._adapter.features?.forEach((e=>this._adapterSupportedExtensions.push(e))),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then((e=>{this._adapterInfo=e}));const t=this._options.deviceDescriptor??{},i=t?.requiredFeatures??(this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0);if(i){const e=i,s=[];for(const t of e)-1!==this._adapterSupportedExtensions.indexOf(t)&&s.push(t);t.requiredFeatures=s}if(this._options.setMaximumLimits&&!t.requiredLimits){t.requiredLimits={};for(const e in this._adapterSupportedLimits)"minSubgroupSize"!==e&&"maxSubgroupSize"!==e&&(t.requiredLimits[e]=this._adapterSupportedLimits[e])}return t.label=`BabylonWebGPUDevice${this.uniqueId}`,this._adapter.requestDevice(t)}throw"Could not retrieve a WebGPU adapter (adapter is null)."})).then((e=>{this._device=e,this._deviceEnabledExtensions=[],this._device.features?.forEach((e=>this._deviceEnabledExtensions.push(e))),this._deviceLimits=e.limits;let t=-1;this._device.addEventListener("uncapturederror",(e=>{++t{this._isDisposed||(this._contextWasLost=!0,J.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost((async()=>{const e=this.snapshotRenderingMode,t=this.snapshotRendering,i=this.disableCacheSamplers,s=this.disableCacheRenderPipelines,r=this.disableCacheBindGroups,n=this.enableGPUTimingMeasurements;await this.initAsync(this._glslangOptions??this._options?.glslangOptions,this._twgslOptions??this._options?.twgslOptions),this.snapshotRenderingMode=e,this.snapshotRendering=t,this.disableCacheSamplers=i,this.disableCacheRenderPipelines=s,this.disableCacheBindGroups=r,this.enableGPUTimingMeasurements=n,this._currentRenderPass=null})))}))})).then((()=>{this._bufferManager=new tp(this,this._device),this._textureHelper=new Jd(this,this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new np(this._device),this._cacheBindGroups=new vp(this._device,this._cacheSampler,this),this._timestampQuery=new Pp(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new Dp(this,this._device,this._bufferManager):void 0,this._bundleList=new Rp(this._device),this._snapshotRendering=new Np(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),td.Uniform|td.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),td.Uniform|td.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&void 0===this._count&&(this._count=0,J.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._initializeLimits(),this._emptyVertexBuffer=new Ki(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new up(this._device,this._emptyVertexBuffer),this._depthCullingState=new pp(this._cacheRenderPipeline),this._stencilStateComposer=new dp(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new xp(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()})).catch((e=>{throw J.Error("A fatal error occurred during WebGPU creation/initialization."),e}))}_initGlslang(e){return e=e||{},(e={...Vp._GLSLslangDefaultOptions,...e}).glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?Ii.LoadBabylonScriptAsync(e.jsPath).then((()=>self.glslang(Ii.GetBabylonScriptURL(e.wasmPath)))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(Ju.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(Ju.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(Ju.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(Ju.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf(Ju.RG11B10UFloatRenderable)>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(Ju.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf(Ju.TimestampQuery)||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!0,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new Yd],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._setColorFormat(this._mainRenderPassWrapper)}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};const e=new Float32Array([this.getRenderHeight(!0)]);let t;if(this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e),this._options.antialias){const e={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:sd.E2d,format:this._options.swapChainFormat,usage:rd.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(e),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:sd.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new j(0,0,0,1),loadOp:Od.Clear,storeOp:Nd.Store}]}else t=[{view:void 0,clearValue:new j(0,0,0,1),loadOp:Od.Clear,storeOp:Nd.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?ad.Depth24PlusStencil8:ad.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);const i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:sd.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:rd.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const s={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:sd.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:Od.Clear,depthStoreOp:Nd.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?Od.Clear:void 0,stencilStoreOp:this.isStencilEnable?Nd.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:t,depthStencilAttachment:s}}_sharedInit(e){super._sharedInit(e),Rr(this,e,this._creationOptions)}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:rd.RenderAttachment|rd.CopySrc,alphaMode:this.premultipliedAlpha?Fd.Premultiplied:Fd.Opaque})}resizeImageBitmap(e,t,i){return Dr(this,e,t,i)}_createImageBitmapFromSource(e,t){return Mr(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&Or(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&Nr()}enterPointerlock(){this._renderingCanvas&&wr(this._renderingCanvas)}exitPointerlock(){Fr()}_rebuildBuffers(){super._rebuildBuffers();for(const e of this._storageBuffers)e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){up.ResetCache(),vp.ResetCache();const t=e=>{for(const t of e){for(const e of t.meshes){const t=e.subMeshes;if(t)for(const e of t)e._drawWrappers=[]}for(const e of t.materials)e._materialContext?.reset()}};t(this.scenes),t(this._virtualScenes);const i=[];for(const e of this._uniformBuffers)e.name.indexOf("leftOver")<0&&i.push(e);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setSize(e,t,i=!1){return!!super.setSize(e,t,i)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0,r=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,n=i===ht.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===ht.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,o,i,s,r)}_compilePipelineStageDescriptor(e,t,i,s){this.onBeforeShaderCompilationObservable.notifyObservers(this);const r=e.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,n=t.indexOf("#define DISABLE_UNIFORMITY_ANALYSIS")>=0,o="#version 450\n",a=s===ht.GLSL?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),l=s===ht.GLSL?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(a,l,s,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new Ou(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new Ud(e,this)}createMaterialContext(){return new _p}createDrawContext(){return new mp(this._bufferManager)}_preparePipelineContext(e,t,i,s,r,n,o,a){const l=e,h=l.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(J.Log(["defines",a]),J.Log(t),J.Log(i),J.Log("***********************************************")),l.sources={fragment:i,vertex:t,rawVertex:r,rawFragment:n},l.stages=s?this._compileRawPipelineStageDescriptor(t,i,h):this._compilePipelineStageDescriptor(t,i,a,h)}getAttributes(e,t){const i=new Array(t.length),s=e;for(let e=0;e0,n.is3D=l>0,n._cachedWrapU=0,n._cachedWrapV=0,n._useSRGBBuffer=r.useSRGBBuffer,n.label=r.label,this._internalTexturesCache.push(n),i||this._textureHelper.createGPUTextureForInternalTexture(n,o,a,h||1,r.creationFlags),n}createTexture(e,t,i,s,r=3,n=null,o=null,a=null,l=null,h=null,c=null,u,d,p,f){return this._createTextureBase(e,t,i,s,r,n,o,((e,t,i,s,r,n,o,a)=>{const l=s;if(e.baseWidth=l.width,e.baseHeight=l.height,e.width=l.width,e.height=l.height,e.format=-1!==e.format?e.format:h??5,e.type=-1!==e.type?e.type:0,e._creationFlags=p??0,a(e.width,e.height,l,t,e,(()=>{})),e._hardwareTexture?.underlyingResource)n||o||this._generateMipmaps(e,this._uploadEncoder);else{const t=this._textureHelper.createGPUTextureForInternalTexture(e,l.width,l.height,void 0,p);Xd.IsImageBitmap(l)&&(this._textureHelper.updateTexture(l,e,l.width,l.height,e.depth,t.format,0,0,r,!1,0,0),n||o||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}),(()=>!1),a,l,h,c,u,d,f)}wrapWebGPUTexture(e){const t=new Yd(e),i=new ti(this,ei.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers}_unpackFlipY(e){}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,s=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==s&&(e._cachedWrapR=s)}updateTextureDimensions(e,t,i,s=1){if(!e._hardwareTexture)return;if(e.width===t&&e.height===i&&e.depth===s)return;const r=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,s,r)}_setInternalTexture(e,t,i){if(i=i??e,this._currentEffect){const s=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),s&&s.autoBindSampler){const e=i+"Sampler";this._currentMaterialContext.setSampler(e,t)}}}createPrefilteredCubeTexture(e,t,i,s,r=null,n=null,o,a=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(r&&r(null));const t=e.texture;l?e.info.sphericalPolynomial&&(t._sphericalPolynomial=e.info.sphericalPolynomial):t._sphericalPolynomial=new Qc,t._source=ei.CubePrefiltered,r&&r(t)}),n,o,a,l,i,s)}setTexture(e,t,i,s){this._setTexture(e,i,!1,!1,s,s)}setTextureArray(e,t,i,s){for(let e=0;e{const o=()=>{n.mapAsync(id.Read,0,i).then((()=>{const t=n.getMappedRange(0,i);let r=s;if(void 0===r)r=new Uint8Array(i),r.set(new Uint8Array(t));else{const e=r.constructor;r=new e(r.buffer),r.set(new e(t))}n.unmap(),this._bufferManager.releaseBuffer(n),e(r)}),(i=>{this.isDisposed?e(new Uint8Array):t(i)}))};r?(this.flushFramebuffer(),o()):this.onEndFrameObservable.addOnce((()=>{o()}))}))}setStorageBuffer(e,t){this._currentDrawContext?.setBuffer(e,t?.getBuffer()??null)}}Vp._GLSLslangDefaultOptions={jsPath:`${Ii._DefaultCdnUrl}/glslang/glslang.js`,wasmPath:`${Ii._DefaultCdnUrl}/glslang/glslang.wasm`},Vp._InstanceId=0,Vp.UseTWGSL=!0,Vp.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode===e&&(0===e&&!this._alphaState.alphaBlend||0!==e&&this._alphaState.alphaBlend)){if(!t){const t=0===e;this.depthCullingState.depthMask!==t&&(this.setDepthWrite(t),this._cacheRenderPipeline.setDepthWriteEnabled(t))}}else{switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,1),this._alphaState.alphaBlend=!0;break;case 8:case 14:this._alphaState.setAlphaBlendFunctionParameters(1,771,1,771),this._alphaState.alphaBlend=!0;break;case 2:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,1),this._alphaState.alphaBlend=!0;break;case 6:this._alphaState.setAlphaBlendFunctionParameters(1,1,0,1),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(770,1,0,1),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(0,769,1,1),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(774,0,1,1),this._alphaState.alphaBlend=!0;break;case 5:this._alphaState.setAlphaBlendFunctionParameters(770,769,1,1),this._alphaState.alphaBlend=!0;break;case 9:this._alphaState.setAlphaBlendFunctionParameters(32769,32770,32771,32772),this._alphaState.alphaBlend=!0;break;case 10:this._alphaState.setAlphaBlendFunctionParameters(1,769,1,771),this._alphaState.alphaBlend=!0;break;case 11:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,1),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(772,1,0,0),this._alphaState.alphaBlend=!0;break;case 13:this._alphaState.setAlphaBlendFunctionParameters(775,769,773,771),this._alphaState.alphaBlend=!0;break;case 15:this._alphaState.setAlphaBlendFunctionParameters(1,1,1,0),this._alphaState.alphaBlend=!0;break;case 16:this._alphaState.setAlphaBlendFunctionParameters(775,769,0,1),this._alphaState.alphaBlend=!0;break;case 17:this._alphaState.setAlphaBlendFunctionParameters(770,771,1,771),this._alphaState.alphaBlend=!0}t||(this.setDepthWrite(0===e),this._cacheRenderPipeline.setDepthWriteEnabled(0===e)),this._alphaMode=e,this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)}},Vp.prototype.setAlphaEquation=function(e){si.prototype.setAlphaEquation.call(this,e),this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters,this._alphaState._blendEquationParameters)};class Up{getBindGroups(e,t,i){if(!i)throw new Error("WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!");if(0===this._bindGroups.length){const s=this._bindGroupEntries.length>0;for(const t in e){const r=e[t],n=i[t],o=n.group,a=n.binding,l=r.type,h=r.object;let c=r.indexInGroupEntries,u=this._bindGroupEntries[o];switch(u||(u=this._bindGroupEntries[o]=[]),l){case kh.Sampler:{const e=h;void 0!==c&&s?u[c].resource=this._cacheSampler.getSampler(e):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:this._cacheSampler.getSampler(e)}));break}case kh.Texture:case kh.TextureWithoutSampler:{const e=h,t=e._texture._hardwareTexture;void 0!==c&&s?(l===kh.Texture&&(u[c++].resource=this._cacheSampler.getSampler(e._texture)),u[c].resource=t.view):(r.indexInGroupEntries=u.length,l===kh.Texture&&u.push({binding:a-1,resource:this._cacheSampler.getSampler(e._texture)}),u.push({binding:a,resource:t.view}));break}case kh.StorageTexture:{const e=h,t=e._texture._hardwareTexture;t.textureAdditionalUsages&rd.StorageBinding||J.Error(`computeDispatch: The texture (name=${e.name}, uniqueId=${e.uniqueId}) is not a storage texture!`,50),void 0!==c&&s?u[c].resource=t.viewForWriting:(r.indexInGroupEntries=u.length,u.push({binding:a,resource:t.viewForWriting}));break}case kh.ExternalTexture:{const e=h.underlyingResource;void 0!==c&&s?u[c].resource=this._device.importExternalTexture({source:e}):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:this._device.importExternalTexture({source:e})}));break}case kh.UniformBuffer:case kh.StorageBuffer:case kh.DataBuffer:{const e=l===kh.DataBuffer?h:(kh.UniformBuffer,h.getBuffer()),t=e.underlyingResource;void 0!==c&&s?(u[c].resource.buffer=t,u[c].resource.size=e.capacity):(r.indexInGroupEntries=u.length,u.push({binding:a,resource:{buffer:t,offset:0,size:e.capacity}}));break}}}for(let e=0;e0&&d.dispatchWorkgroups(s,r,n),d.end(),h&&(this._timestampQuery.endPass(this._timestampIndex,h),this._timestampIndex+=2)},Vp.prototype.releaseComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e].getPipelineContext();this._deleteComputePipelineContext(t)}this._compiledComputeEffects={}},Vp.prototype._prepareComputePipelineContext=function(e,t,i,s,r){const n=e;this.dbgShowShaderCode&&(J.Log(s),J.Log(t)),n.sources={compute:t,rawCompute:i},n.stage=this._createComputePipelineStageDescriptor(t,s,r)},Vp.prototype._releaseComputeEffect=function(e){this._compiledComputeEffects[e._key]&&(delete this._compiledComputeEffects[e._key],this._deleteComputePipelineContext(e.getPipelineContext()))},Vp.prototype._rebuildComputeEffects=function(){for(const e in this._compiledComputeEffects){const t=this._compiledComputeEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}},Vp.prototype._executeWhenComputeStateIsCompiled=function(e,t){e.stage.module.getCompilationInfo().then((e=>{const i={numErrors:0,messages:[]};for(const t of e.messages)"error"===t.type&&i.numErrors++,i.messages.push({type:t.type,text:t.message,line:t.lineNum,column:t.linePos,length:t.length,offset:t.offset});t(i)}))},Vp.prototype._deleteComputePipelineContext=function(e){e&&e.dispose()},Vp.prototype._createComputePipelineStageDescriptor=function(e,t,i){return t=t?"//"+t.split("\n").join("\n//")+"\n":"",{module:this._device.createShaderModule({code:t+e}),entryPoint:i}},Vp.prototype._createDepthStencilCubeTexture=function(e,t){const i=new ti(this,t.generateStencil?ei.DepthStencil:ei.Depth);i.isCube=!0,i.label=t.label;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t};i.format=s.depthTextureFormat,this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction,s.samples),this._textureHelper.createGPUTextureForInternalTexture(i);const r=i._hardwareTexture;return i.type=Xd.GetTextureTypeFromFormat(r.format),this._internalTexturesCache.push(i),i},Vp.prototype.createCubeTexture=function(e,t,i,s,r=null,n=null,o,a=null,l=!1,h=0,c=0,u=null,d=!1){return this.createCubeTextureBase(e,t,i,!!s,r,n,o,a,l,h,c,u,null,((e,t)=>{const i=t,n=i[0].width,a=n;this._setCubeMapTextureParams(e,!s),e.format=o??-1;const l=this._textureHelper.createGPUTextureForInternalTexture(e,n,a);this._textureHelper.updateCubeTextures(i,l.underlyingResource,n,a,l.format,!1,!1,0,0),s||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),r&&r()}),!!d)},Vp.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},Vp.prototype.generateMipMapsForCubemap=function(e){if(e.generateMipMaps){const t=e._hardwareTexture?.underlyingResource;t||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e)}},Vp.prototype._debugPushGroup=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.pushDebugGroup(e):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e]))},Vp.prototype._debugPopGroup=function(e){this._options.enableGPUDebugMarkers&&(0===e||1===e?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))},Vp.prototype._debugInsertMarker=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.insertDebugMarker(e):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e]))},Vp.prototype._debugFlushPendingCommands=function(){for(let e=0;e{const i=d.width,n=o(e);if(n){if(a){const e=4===s,t=a(n),o=d._hardwareTexture,l=[0,1,2,3,4,5];for(let s=0;s>s,a=[];for(let i=0;i<6;i++){let o=t[s][l[i]];e&&(o=zp(o,n,n,r)),a.push(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}this._textureHelper.updateCubeTextures(a,o.underlyingResource,n,n,o.format,u,!1,0,0)}}else this.updateRawCubeTexture(d,n,s,r,u);d.isReady=!0,t?.removePendingData(d),l&&l()}};return this._loadFile(e,(e=>{p(e)}),void 0,t?.offlineProvider,!0,((e,i)=>{t?.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)})),d},Vp.prototype.createRawTexture3D=function(e,t,i,s,r,n,o,a,l=null,h=0,c=0){const u=ei.Raw3D,d=new ti(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=s,d.width=t,d.height=i,d.depth=s,d.format=r,d.type=h,d.generateMipMaps=n,d.samplingMode=a,d.is3D=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,void 0,c),this.updateRawTexture3D(d,e,r,o,l,h),this._internalTexturesCache.push(d),d},Vp.prototype.updateRawTexture3D=function(e,t,i,s,r=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r),t){const r=e._hardwareTexture;4===i&&(t=zp(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,r.format,0,0,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Vp.prototype.createRawTexture2DArray=function(e,t,i,s,r,n,o,a,l=null,h=0,c=0){const u=ei.Raw2DArray,d=new ti(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=s,d.width=t,d.height=i,d.depth=s,d.format=r,d.type=h,d.generateMipMaps=n,d.samplingMode=a,d.is2DArray=!0,d._creationFlags=c,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,s,c),this.updateRawTexture2DArray(d,e,r,o,l,h),this._internalTexturesCache.push(d),d},Vp.prototype.updateRawTexture2DArray=function(e,t,i,s,r=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=s,e._compression=r),t){const r=e._hardwareTexture;4===i&&(t=zp(t,e.width,e.height,n));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,r.format,0,0,s,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},Vp.prototype._readTexturePixels=function(e,t,i,s=-1,r=0,n=null,o=!0,a=!1,l=0,h=0){const c=e._hardwareTexture;return o&&this.flushFramebuffer(),this._textureHelper.readPixels(c.underlyingResource,l,h,t,i,c.format,s,r,n,a)},Vp.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};class Wp extends jo{constructor(e,t,i,s,r){super(e,t,i,s,r),s.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new Xh)}}Vp.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const s=new Wp(e,t,i,this);return this._renderTargetWrapperCache.push(s),s},Vp.prototype.createRenderTargetTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!1,e),s={};void 0!==t&&"object"==typeof t?(s.generateMipMaps=t.generateMipMaps,s.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,s.generateStencilBuffer=s.generateDepthBuffer&&t.generateStencilBuffer,s.samplingMode=void 0===t.samplingMode?3:t.samplingMode,s.creationFlags=t.creationFlags??0,s.noColorAttachment=!!t.noColorAttachment,s.samples=t.samples,s.label=t.label):(s.generateMipMaps=t,s.generateDepthBuffer=!0,s.generateStencilBuffer=!1,s.samplingMode=3,s.creationFlags=0,s.noColorAttachment=!1);const r=s.noColorAttachment?null:this._createInternalTexture(e,t,!0,ei.RenderTarget);return i.label=s.label??"RenderTargetWrapper",i._samples=s.samples??1,i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=!!s.generateStencilBuffer,i.setTextures(r),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,!1,i._generateStencilBuffer,i.samples,s.generateStencilBuffer?13:14,s.label?s.label+"-DepthStencil":void 0),r&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r,void 0,void 0,void 0,s.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!1)),i},Vp.prototype._createDepthStencilTexture=function(e,t){const i=new ti(this,t.generateStencil?ei.DepthStencil:ei.Depth);i.label=t.label;const s={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14,...t};i.format=s.depthTextureFormat,this._setupDepthStencilTexture(i,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction,s.samples),this._textureHelper.createGPUTextureForInternalTexture(i);const r=i._hardwareTexture;return i.type=Xd.GetTextureTypeFromFormat(r.format),this._internalTexturesCache.push(i),i},Vp.prototype._setupDepthStencilTexture=function(e,t,i,s,r,n=1){const o=t.width||t,a=t.height||t,l=t.layers||0,h=t.depth||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.is3D=h>0,e.depth=l||h,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=s?2:1,e.type=1,e._comparisonFunction=r,e._cachedWrapU=0,e._cachedWrapV=0},Vp.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t?(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t,t):t},Vp.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),s={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1,...t};s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,i.label=s.label??"RenderTargetWrapper",i._generateDepthBuffer=s.generateDepthBuffer,i._generateStencilBuffer=s.generateStencilBuffer;const r=new ti(this,ei.RenderTarget);return r.width=e,r.height=e,r.depth=0,r.isReady=!0,r.isCube=!0,r.samples=s.samples,r.generateMipMaps=s.generateMipMaps,r.samplingMode=s.samplingMode,r.type=s.type,r.format=s.format,this._internalTexturesCache.push(r),i.setTextures(r),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,void 0===s.samplingMode||2===s.samplingMode||2===s.samplingMode||3===s.samplingMode||3===s.samplingMode||5===s.samplingMode||6===s.samplingMode||7===s.samplingMode||11===s.samplingMode,i._generateStencilBuffer,i.samples),t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(r),t&&t.createMipMaps&&!s.generateMipMaps&&(r.generateMipMaps=!1),i},Vp.prototype.setDepthStencilTexture=function(e,t,i,s){i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,s):this._setTexture(e,null,void 0,void 0,s)},Vp.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;e._hardwareTexture?.underlyingResource||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),function(e){return!(!e||void 0===e.underlyingResource)}(t)?(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0):t&&this.createImageBitmap(t).then((t=>{this._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,s.format,0,0,!i,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0})).catch((()=>{e.isReady=!0}))};class Hp{}Hp.COPY=1,Hp.CUT=2,Hp.PASTE=3;class Xp extends ec{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=Y.Gray(),i=Jh.DefaultUtilityLayer,s=null,r=1,n=Y.Yellow(),o=Y.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new g,this.uniformScaling=!1,this.sensitivity=1,this.dragScale=1,this.incrementalSnap=!1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._tmpVector=new w(0,0,0),this._incrementalStartupValue=w.Zero(),this._parent=s,this._coloredMaterial=new dh("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Y(.1,.1,.1)),this._hoverMaterial=new dh("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new dh("",i.utilityLayerScene),this._disableMaterial.diffuseColor=o,this._disableMaterial.alpha=.4,this._gizmoMesh=new Un("axis",i.utilityLayerScene);const{arrowMesh:a,arrowTail:l}=this._createGizmoMesh(this._gizmoMesh,r),h=this._createGizmoMesh(this._gizmoMesh,r+4,!0);this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,ec.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3);const c=a.position.clone(),u=l.position.clone(),d=l.scaling.clone(),p=e=>{const t=e*(3/this._rootMesh.scaling.length())*6;a.position.z+=t/3.5,l.scaling.y+=t,this.dragScale=l.scaling.y,l.position.z=a.position.z/2},f=()=>{a.position.set(c.x,c.y,c.z),l.position.set(u.x,u.y,u.z),l.scaling.set(d.x,d.y,d.z),this.dragScale=l.scaling.y,this._dragging=!1};this.dragBehavior=new uo({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior);let _=0,m=0;const v={snapDistance:0};this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const i=this.sensitivity*t.dragDistance*(3*this.scaleRatio/this._rootMesh.scaling.length()),s=this._tmpVector;let r=!1,n=0;if(this.uniformScaling?s.setAll(.57735):s.copyFrom(e),0==this.snapDistance)s.scaleToRef(i,s);else{_+=i,m+=i;const e=this.incrementalSnap?m:_;Math.abs(e)>this.snapDistance?(n=Math.floor(Math.abs(e)/this.snapDistance),e<0&&(n*=-1),_%=this.snapDistance,s.scaleToRef(this.snapDistance*n,s),r=!0):s.scaleInPlace(0)}s.addInPlaceFromFloats(1,1,1),s.x=Math.abs(s.x)0&&this.incrementalSnap?(this.attachedNode.getWorldMatrix().decompose(void 0,U.Quaternion[0],U.Vector3[2],ec.PreserveScaling?o:void 0),s.addInPlace(this._incrementalStartupValue),s.addInPlaceFromFloats(-1,-1,-1),s.x=Math.abs(s.x)*(this._incrementalStartupValue.x>0?1:-1),s.y=Math.abs(s.y)*(this._incrementalStartupValue.y>0?1:-1),s.z=Math.abs(s.z)*(this._incrementalStartupValue.z>0?1:-1),B.ComposeToRef(s,U.Quaternion[0],U.Vector3[2],U.Matrix[1])):(B.ScalingToRef(s.x,s.y,s.z,U.Matrix[2]),U.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(),U.Matrix[1])),U.Matrix[1].decompose(U.Vector3[1],void 0,void 0,ec.PreserveScaling?o:void 0);const a=1e5;Math.abs(U.Vector3[1].x){this._dragging=!0;const e=this.attachedNode._isMesh?this.attachedNode:void 0;this.attachedNode?.getWorldMatrix().decompose(this._incrementalStartupValue,void 0,void 0,ec.PreserveScaling?e:void 0),_=0,m=0})),this.dragBehavior.onDragObservable.add((e=>p(e.dragDistance))),this.dragBehavior.onDragEndObservable.add(f),s?.uniformScaleGizmo?.dragBehavior?.onDragObservable?.add((e=>p(e.delta.y))),s?.uniformScaleGizmo?.dragBehavior?.onDragEndObservable?.add(f);const x={gizmoMeshes:[a,l],colliderMeshes:[h.arrowMesh,h.arrowTail],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,x),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(this._customMeshSet)return;let t=this._parent?.getAxisCache(this._gizmoMesh);if(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),t=this._parent?.getAxisCache(this._rootMesh),this._isHovered||(this._isHovered=!(!t||-1==t.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh))),!this._parent){const e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(x.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(x.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}));const T=i._getSharedGizmoLight();T.includedOnlyMeshes=T.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes())}_createGizmoMesh(e,t,i=!1){const s=sc("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),r=Qh("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return s.scaling.scaleInPlace(.1),s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,s.position.z+=.3,r.material=this._coloredMaterial,r.position.z+=.1375,r.rotation.x=Math.PI/2,i&&(s.visibility=0,r.visibility=0),e.addChild(s),e.addChild(r),{arrowMesh:s,arrowTail:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}setCustomMesh(e,t=!1){super.setCustomMesh(e),t&&(this._rootMesh.getChildMeshes().forEach((e=>{e.material=this._coloredMaterial,e.color&&(e.color=this._coloredMaterial.diffuseColor)})),this._customMeshSet=!1)}}Xp.MinimumAbsoluteScale=T;class Yp extends ec{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}set rotationColor(e){this._rotationShaderMaterial.setColor3("rotationColor",e)}get disableMaterial(){return this._disableMaterial}constructor(e,t=Y.Gray(),i=Jh.DefaultUtilityLayer,s=32,r=null,n=!1,o=1,a=Y.Yellow(),l=Y.Gray()){super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new g,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new w,this._parent=r,this._coloredMaterial=new dh("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new Y(.1,.1,.1)),this._hoverMaterial=new dh("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a,this._hoverMaterial.specularColor=a,this._disableMaterial=new dh("",i.utilityLayerScene),this._disableMaterial.diffuseColor=l,this._disableMaterial.alpha=.4,this._gizmoMesh=new Un("",i.utilityLayerScene);const{rotationMesh:h,collider:c}=this._createGizmoMesh(this._gizmoMesh,o,s);this._rotationDisplayPlane=co("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),$t.ShadersStore.rotationGizmoVertexShader=Yp._RotationGizmoVertexShader,$t.ShadersStore.rotationGizmoFragmentShader=Yp._RotationGizmoFragmentShader,this._rotationShaderMaterial=new fc("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles","rotationColor"]}),this._rotationShaderMaterial.backFaceCulling=!1,this.rotationColor=a,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,ec.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new uo({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=Yp.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);const u=new w,d=new B,p=new w;let f=new w;this.dragBehavior.onDragStartObservable.add((e=>{this.attachedNode&&(u.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(d),w.TransformCoordinatesToRef(e.dragPlanePoint,d,u),this._angles.x=Math.atan2(u.y,u.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,u.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)}));const _={snapDistance:0};let m=0;const v=new B,x=new L;this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const s=new w(1,1,1),r=new L(0,0,0,1),n=new w(0,0,0);if(this.attachedNode.getWorldMatrix().decompose(s,r,n),!(Math.abs(Math.abs(s.x)-Math.abs(s.y))<=T&&Math.abs(Math.abs(s.x)-Math.abs(s.z))<=T)&&this.updateGizmoRotationToMatchAttachedMesh)return void J.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");r.normalize();const o=this.updateGizmoPositionToMatchAttachedMesh?n:this._rootMesh.absolutePosition,a=t.dragPlanePoint.subtract(o).normalize(),l=u.subtract(o).normalize(),h=w.Cross(a,l),c=w.Dot(a,l);let g=Math.atan2(h.length(),c)*this.sensitivity;p.copyFrom(e),f.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(r.toRotationMatrix(d),f=w.TransformCoordinates(p,d));let S=!1;if(i.utilityLayerScene.activeCamera){const e=i.utilityLayerScene.activeCamera.position.subtract(o).normalize();w.Dot(e,f)>0&&(p.scaleInPlace(-1),f.scaleInPlace(-1),S=!0)}w.Dot(f,h)>0&&(g=-g),U.Vector3[0].set(g,0,0),this.dragBehavior.validateDrag(U.Vector3[0])||(g=0);let E=!1;if(0!=this.snapDistance)if(m+=g,Math.abs(m)>this.snapDistance){let e=Math.floor(Math.abs(m)/this.snapDistance);m<0&&(e*=-1),m%=this.snapDistance,g=this.snapDistance*e,E=!0}else g=0;const b=Math.sin(g/2);if(x.set(p.x*b,p.y*b,p.z*b,Math.cos(g/2)),v.determinant()>0){const e=new w;x.toEulerAnglesToRef(e),L.RotationYawPitchRollToRef(e.y,-e.x,-e.z,x)}if(this.updateGizmoRotationToMatchAttachedMesh)r.multiplyToRef(x,r),r.normalize(),B.ComposeToRef(s,r,n,this.attachedNode.getWorldMatrix());else{x.toRotationMatrix(U.Matrix[0]);const e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(U.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}u.copyFrom(t.dragPlanePoint),E&&(_.snapDistance=g,this.onSnapObservable.notifyObservers(_)),this._angles.y+=g,this.angle+=S?-g:g,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}}));const S=i._getSharedGizmoLight();S.includedOnlyMeshes=S.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const E={colliderMeshes:[c],gizmoMeshes:[h],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};this._parent?.addToAxisCache(this._gizmoMesh,E),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=Yp.MaxDragAngle,this._isHovered=!(-1==E.colliderMeshes.indexOf(e?.pickInfo?.pickedMesh)),!this._parent)){const e=E.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(E.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(E.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_createGizmoMesh(e,t,i){const s=Oh("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);s.visibility=0;const r=Oh("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return r.material=this._coloredMaterial,r.rotation.x=Math.PI/2,s.rotation.x=Math.PI/2,e.addChild(r,ec.PreserveScaling),e.addChild(s,ec.PreserveScaling),{rotationMesh:r,collider:s}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}Yp.MaxDragAngle=9*Math.PI/20,Yp._RotationGizmoVertexShader="\n precision highp float;\n attribute vec3 position;\n attribute vec2 uv;\n uniform mat4 worldViewProjection;\n varying vec3 vPosition;\n varying vec2 vUV;\n\n void main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n vUV = uv;\n }",Yp._RotationGizmoFragmentShader="\n precision highp float;\n varying vec2 vUV;\n varying vec3 vPosition;\n uniform vec3 angles;\n uniform vec3 rotationColor;\n\n #define twopi 6.283185307\n\n void main(void) {\n vec2 uv = vUV - vec2(0.5);\n float angle = atan(uv.y, uv.x) + 3.141592;\n float delta = gl_FrontFacing ? angles.y : -angles.y;\n float begin = angles.x - delta * angles.z;\n float start = (begin < (begin + delta)) ? begin : (begin + delta);\n float end = (begin > (begin + delta)) ? begin : (begin + delta);\n float len = sqrt(dot(uv,uv));\n float opacity = 1. - step(0.5, len);\n\n float base = abs(floor(start / twopi)) * twopi;\n start += base;\n end += base;\n\n float intensity = 0.;\n for (int i = 0; i < 5; i++)\n {\n intensity += max(step(start, angle) - step(end, angle), 0.);\n angle += twopi;\n }\n gl_FragColor = vec4(rotationColor, min(intensity * 0.25, 0.8)) * opacity;\n }\n ";class jp extends Gn{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=B.Identity(),this._projectionMatrix=B.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return!(!this.parent||!this.parent.getWorldMatrix||(this.transformedPosition||(this.transformedPosition=w.Zero()),w.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=w.Zero()),w.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),0))}getDepthScale(){return 50}getShadowDirection(e){return this.transformedDirection?this.transformedDirection:this.direction}getAbsolutePosition(){return this.transformedPosition?this.transformedPosition:this.position}setDirectionToTarget(e){return this.direction=w.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=w.Cross(this.direction,Gs.Y),t=w.Cross(e,this.direction);return w.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=w.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=B.Identity()),B.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),this.parent&&this.parent.getWorldMatrix||(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){const t=U.Vector3[0];let i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),w.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(w.Dot(t,w.Up()))&&(t.z=1e-13);const s=U.Vector3[1];return i.addToRef(t,s),B.LookAtLHToRef(i,s,w.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}ae([ve()],jp.prototype,"position",null),ae([ve()],jp.prototype,"direction",null),ae([pe()],jp.prototype,"shadowMinZ",null),ae([pe()],jp.prototype,"shadowMaxZ",null),De.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new $p(e,w.Zero(),t)));class $p extends jp{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,i){super(e,i),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return Gn.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){const t=this.getScene().activeCamera;t&&B.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=w.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let s=Number.MAX_VALUE,r=-Number.MAX_VALUE;for(let n=0;nthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zr&&(r=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=s,this._shadowMaxZ=r)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,o=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;B.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,l?a:o,l?o:a,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}function Kp(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);const s=nc("",{slice:.5,diameter:t.diameter,segments:t.segments},i),r=cc("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);r.rotation.x=-Math.PI/2,r.parent=s;const n=Un.MergeMeshes([r,s],!0);return n.name=e,n}ae([pe()],$p.prototype,"shadowFrustumSize",null),ae([pe()],$p.prototype,"shadowOrthoScale",null),ae([pe()],$p.prototype,"autoUpdateExtends",void 0),ae([pe()],$p.prototype,"autoCalcShadowZBounds",void 0),ae([pe("orthoLeft")],$p.prototype,"_orthoLeft",void 0),ae([pe("orthoRight")],$p.prototype,"_orthoRight",void 0),ae([pe("orthoTop")],$p.prototype,"_orthoTop",void 0),ae([pe("orthoBottom")],$p.prototype,"_orthoBottom",void 0),u("BABYLON.DirectionalLight",$p),Un.CreateHemisphere=(e,t,i,s)=>Kp(e,{segments:t,diameter:i},s),De.AddNodeConstructor("Light_Type_2",((e,t)=>()=>new qp(e,w.Zero(),w.Zero(),0,0,t)));class qp extends jp{get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(.5*e),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()}get innerAngle(){return this._innerAngle}set innerAngle(e){this._innerAngle=e,this._computeAngleValues()}get shadowAngleScale(){return this._shadowAngleScale}set shadowAngleScale(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()}get projectionTextureMatrix(){return this._projectionTextureMatrix}get projectionTextureLightNear(){return this._projectionTextureLightNear}set projectionTextureLightNear(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureLightFar(){return this._projectionTextureLightFar}set projectionTextureLightFar(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureUpDirection(){return this._projectionTextureUpDirection}set projectionTextureUpDirection(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0}get projectionTexture(){return this._projectionTexture}set projectionTexture(e){this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(qp._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((()=>{this._markMeshesAsLightDirty()})):qp._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce((()=>{this._markMeshesAsLightDirty()}))))}static _IsProceduralTexture(e){return void 0!==e.onGeneratedObservable}static _IsTexture(e){return void 0!==e.onLoadObservable}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,s,r,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=B.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=w.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=w.Zero(),this._projectionTextureViewLightMatrix=B.Zero(),this._projectionTextureProjectionLightMatrix=B.Zero(),this._projectionTextureScalingMatrix=B.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=s,this.exponent=r}getClassName(){return"SpotLight"}getTypeID(){return Gn.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;this._shadowAngleScale=this._shadowAngleScale||1;const r=this._shadowAngleScale*this._angle,n=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;B.PerspectiveFovLHToRef(r,1,a?o:n,a?n:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,a)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),B.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),s=-i*t,r=1/Math.tan(this._angle/2);B.FromValuesToRef(r/1,0,0,0,0,r,0,0,0,0,i,1,0,0,s,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof Zn){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;B.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}_computeAngleValues(){this._lightAngleScale=1/Math.max(.001,Math.cos(.5*this._innerAngle)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightTexture"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=w.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=w.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return i=this.computeTransformedInformation()?w.Normalize(this.transformedDirection):w.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!(!this.projectionTexture||!this.projectionTexture.isReady())}}ae([pe()],qp.prototype,"angle",null),ae([pe()],qp.prototype,"innerAngle",null),ae([pe()],qp.prototype,"shadowAngleScale",null),ae([pe()],qp.prototype,"exponent",void 0),ae([pe()],qp.prototype,"projectionTextureLightNear",null),ae([pe()],qp.prototype,"projectionTextureLightFar",null),ae([pe()],qp.prototype,"projectionTextureUpDirection",null),ae([fe("projectedLightTexture")],qp.prototype,"_projectionTexture",void 0),u("BABYLON.SpotLight",qp);class Qp extends ec{constructor(e=Jh.DefaultUtilityLayer){super(e),this._cachedPosition=new w,this._cachedForward=new w(0,0,1),this._pointerObserver=null,this.onClickedObservable=new g,this._light=null,this.attachedMesh=new Wr("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new Ur("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new dh("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new Y(.5,.5,.5),this._material.specularColor=new Y(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._light&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._light))}),ss.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){J.Warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),this._lightMesh=e instanceof Zh?Qp._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof $p?Qp._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof qp?Qp._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):Qp._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._lightMesh.parent=this._rootMesh;const t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new L,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction){this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0);const t=this._getMeshForward();this._cachedForward.copyFrom(t)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(U.Vector3[0]),e=U.Vector3[0]),e}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position)if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{const e=this.attachedMesh.position;this._light.position=new w(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction){const e=this._getMeshForward();if(w.DistanceSquared(e,this._cachedForward)>1e-4){const t=e;this._light.direction=new w(t.x,t.y,t.z),this._cachedForward.copyFrom(e)}else w.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){const t=new Un("hemisphereLight",e),i=Kp(t.name,{segments:10,diameter:1},e);return i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(3,e).parent=t,t.scaling.scaleInPlace(Qp._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){const t=new Un("pointLight",e),i=nc(t.name,{segments:10,diameter:1},e);return i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(5,e).parent=t,t.scaling.scaleInPlace(Qp._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){const t=new Un("spotLight",e);nc(t.name,{segments:10,diameter:1},e).parent=t;const i=Kp(t.name,{segments:10,diameter:2},e);return i.parent=t,i.rotation.x=-Math.PI/2,this._CreateLightLines(2,e).parent=t,t.scaling.scaleInPlace(Qp._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){const t=new Un("directionalLight",e),i=new Un(t.name,e);i.parent=t,nc(t.name,{diameter:1.2,segments:10},e).parent=i;const s=Qh(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);s.parent=i;let r=s.clone(t.name);r.scaling.y=.5,r.position.x+=1.25;let n=s.clone(t.name);n.scaling.y=.5,n.position.x+=-1.25;const o=Qh(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,r=o.clone(t.name),r.position.y=1.5,r.position.x+=1.25,n=o.clone(t.name),n.position.y=1.5,n.position.x+=-1.25,i.scaling.scaleInPlace(Qp._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}Qp._Scale=.007,Qp._CreateLightLines=(e,t)=>{const i=new Un("root",t);i.rotation.x=Math.PI/2;const s=new Un("linePivot",t);s.parent=i;const r=Qh("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(r.position.y=r.scaling.y/2+1.2,r.parent=s,e<2)return s;for(let e=0;e<4;e++){const t=s.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){const t=s.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){const t=s.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}return e<5||(s.clone("linePivotClone").rotation.z=Math.PI),i};class Zp extends ec{constructor(e=Jh.DefaultUtilityLayer,t,i){super(e),this._pointerObserver=null,this.onClickedObservable=new g,this._camera=null,this._invProjection=new B,this._material=new dh("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._frustumLinesColor=i,this._material.diffuseColor=t??new Y(.5,.5,.5),this._material.specularColor=new Y(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._camera&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._camera))}),ss.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){if(this._camera=e,this.attachedNode=e,e){this._customMeshSet||(this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=Zp._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._cameraMesh.parent=this._rootMesh),this._cameraLinesMesh&&this._cameraLinesMesh.dispose();const t=this._frustumLinesColor?.toColor4(1)??new j(1,1,1,1);this._cameraLinesMesh=Zp._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene,t),this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;const i=this.gizmoLayer._getSharedGizmoLight();i.includedOnlyMeshes=i.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}}get camera(){return this._camera}get material(){return this._material}_update(){super._update(),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._cameraMesh&&this._cameraMesh.dispose(),this._cameraMesh=e,this._cameraMesh.parent=this._rootMesh,this._customMeshSet=!0}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),super.dispose()}static _CreateCameraMesh(e){const t=new Un("rootCameraGizmo",e),i=new Un(t.name,e);i.parent=t,sc(t.name,{width:1,height:.8,depth:.5},e).parent=i;const s=Qh(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);s.parent=i,s.position.y=.3,s.position.x=-.6,s.rotation.x=.5*Math.PI;const r=Qh(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);r.parent=i,r.position.y=.5,r.position.x=.4,r.rotation.x=.5*Math.PI;const n=Qh(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return n.parent=i,n.position.y=0,n.position.x=.6,n.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(Zp._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e,t){const i=new Un("rootCameraGizmo",e),s=new Un(i.name,e);s.parent=i;for(let i=0;i<4;i+=2)for(let r=0;r<4;r+=2){let n=Tc("lines",{points:[new w(-1+r,-1+i,-1),new w(-1+r,-1+i,1)],colors:[t,t]},e);n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Tc("lines",{points:[new w(-1,-1+r,-1+i),new w(1,-1+r,-1+i)],colors:[t,t]},e),n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,n=Tc("lines",{points:[new w(-1+r,-1,-1+i),new w(-1+r,1,-1+i)],colors:[t,t]},e),n.parent=s,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1}return i}}Zp._Scale=.05;Ft.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";Ft.IncludesShadersStore.packingFunctions="vec4 pack(float depth)\n{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;}\nfloat unpack(vec4 color)\n{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}";Ft.IncludesShadersStore.kernelBlurFragment="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif\n";Ft.IncludesShadersStore.kernelBlurFragment2="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";Ft.ShadersStore.kernelBlurPixelShader="uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; }\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";Ft.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";Ft.ShadersStore.kernelBlurVertexShader="attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class Jp extends Ko{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,s,r,n=Zn.BILINEAR_SAMPLINGMODE,o,a,l=0,h="",c=!1,u=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],s,r,n,o,a,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,u),this._blockCompilation=c,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add((e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)})),this.kernel=i}updateEffect(e=null,t=null,i=null,s,r,n){this._updateParameters(r,n)}_updateParameters(e,t){const i=this._kernel,s=(i-1)/2;let r=[],n=[],o=0;for(let e=0;e0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){const t=1/3,i=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(i)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,s){return Pe.Parse((()=>new Jp(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)),e,i,s)}}ae([pe("kernel")],Jp.prototype,"_kernel",void 0),ae([pe("packedFloat")],Jp.prototype,"_packedFloat",void 0),ae([ge()],Jp.prototype,"direction",void 0),u("BABYLON.BlurPostProcess",Jp);class ef extends da{set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){const e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){const e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,s,r=0,n=Zn.BILINEAR_SAMPLINGMODE,o=!0){if(super(e,t,i,s,!0,r,!1,n,o),this.mirrorPlane=new Ps(0,1,0,1),this._transformMatrix=B.Zero(),this._mirrorMatrix=B.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateGammaSpace()}));const a=i.getEngine();let l;a.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add((()=>{a._debugPushGroup?.(`mirror generation for ${e}`,1)})),this.onAfterUnbindObservable.add((()=>{a._debugPopGroup?.(1)})),this.onBeforeRenderObservable.add((()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),B.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),l=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=w.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)})),this.onAfterRenderObservable.add((()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=l}))}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){const e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new Jp("horizontal blur",new N(1,0),this._blurKernelX,this._blurRatio,null,Zn.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new Jp("vertical blur",new N(0,1),this._blurKernelY,this._blurRatio,null,Zn.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new ef(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){super.dispose();const e=this.getScene();e&&e.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),this._sceneUBO?.dispose()}}Zn._CreateMirror=(e,t,i,s)=>new ef(e,t,i,s);class tf extends qn{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(B.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let s="";return e.forEach((e=>s+=e)),new tf(s,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,s=!0){const r=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const n=new tf(e,t,null,!1,null,null,null,void 0,!0,i,s);return t.useDelayedTextureLoading=r,n}constructor(e,t,i=null,s=!1,r=null,n=null,o=null,a=5,l=!1,h=null,c=!1,u=.8,d=0,p,f){super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new g,this.boundingBoxPosition=w.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new B,this.name=e,this.url=e,this._noMipmap=s,this.hasAlpha=!1,this._format=a,this.isCube=!0,this._textureMatrix=B.Identity(),this._createPolynomials=c,this.coordinatesMode=Zn.CUBIC_MODE,this._extensions=i,this._files=r,this._forcedExtension=h,this._loaderOptions=p,this._useSRGBBuffer=f,this._lodScale=u,this._lodOffset=d,(e||r)&&this.updateURL(e,h,n,l,o,i,this.getScene()?.useDelayedTextureLoading,r)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,s=!1,r=null,n=null,o=!1,a=null){this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,t&&(this._forcedExtension=t);const l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),c=0===h.indexOf(".dds"),u=0===h.indexOf(".env"),d=0===h.indexOf(".basis");if(u?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=s,s&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),a)this._files=a;else if(d||u||c||n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,n){for(let t=0;t-1!==e.getActiveTextures().indexOf(this))),this._textureMatrix=e,!this.getScene()?.useRightHandedSystem)return;const t=U.Vector3[0],i=U.Quaternion[0],s=U.Vector3[1];this._textureMatrix.decompose(t,i,s),i.z*=-1,i.w*=-1,B.ComposeToRef(t,i,s,this._textureMatrixRefraction)}getRefractionTextureMatrix(){return this.getScene()?.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){const i=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const r=()=>{this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),this.getScene()?.markAllMaterialsAsDirty(1)),e&&e()},n=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),Zn.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Ii.SetImmediate((()=>r())):this._texture.onLoadedObservable.add((()=>r())):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,i,this._lodScale,this._lodOffset,e,n,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,i,this._files,this._noMipmap,e,n,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),this._texture?.onLoadedObservable.add((()=>this.onLoadObservable.notifyObservers(this))))}static Parse(e,t,i){const s=Pe.Parse((()=>{let s=!1;return e.prefiltered&&(s=e.prefiltered),new tf(i+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(s.boundingBoxPosition=w.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=w.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t{const t=new tf(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}ae([pe()],tf.prototype,"url",void 0),ae([ve()],tf.prototype,"boundingBoxPosition",void 0),ae([ve()],tf.prototype,"boundingBoxSize",null),ae([pe("rotationY")],tf.prototype,"rotationY",null),ae([pe("files")],tf.prototype,"_files",void 0),ae([pe("forcedExtension")],tf.prototype,"_forcedExtension",void 0),ae([pe("extensions")],tf.prototype,"_extensions",void 0),ae([Ee("textureMatrix")],tf.prototype,"_textureMatrix",void 0),ae([Ee("textureMatrixRefraction")],tf.prototype,"_textureMatrixRefraction",void 0),Zn._CubeTextureParser=tf.Parse,u("BABYLON.CubeTexture",tf);Ft.IncludesShadersStore.backgroundFragmentDeclaration="uniform vec4 vEyePosition;uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;uniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef PROJECTED_GROUND\nuniform vec2 projectedGroundInfos;\n#endif\n";Ft.IncludesShadersStore.backgroundUboDeclaration="layout(std140,column_major) uniform;uniform Material\n{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;};\n#include\n";Ft.ShadersStore.backgroundPixelShader="#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#include\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#include\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#ifdef PROJECTED_GROUND\nfloat diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; }\nvec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q)\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\nfloat shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.;\n#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n#ifndef BACKMAT_SHADOWONLY\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\n#ifdef PROJECTED_GROUND\nvec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.));\n#else\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);} else {reflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\nvec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor;\n#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\nvec4 color=vec4(finalColor,finalAlpha);\n#else\nvec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);\n#endif\n#include\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#endif\n#else\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Ft.IncludesShadersStore.backgroundVertexDeclaration="uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";Ft.ShadersStore.backgroundVertexShader="precision highp float;\n#include<__decl__backgroundVertex>\n#include\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vec2 vDiffuseUV;\n#endif\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif\n#include\n#include\n#include\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);}\n#else\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#endif\nvec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (vDiffuseInfos.x==0.)\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));}\nelse\n{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n";class sf extends Do{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.PROJECTED_GROUND=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}}class rf extends Io{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t*=2,this.reflectionReflectance0=rf.StandardReflectance0*t,this.reflectionReflectance90=rf.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=rf.StandardReflectance0+(1-rf.StandardReflectance0)*t,this.reflectionReflectance90=rf.StandardReflectance90+(1-rf.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()}))))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.primaryColor=Y.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=w.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._enableGroundProjection=!1,this.enableGroundProjection=!1,this.projectedGroundRadius=1e3,this.projectedGroundHeight=10,this._renderTargets=new Mi(16),this._reflectionControls=F.Zero(),this._white=Y.White(),this._primaryShadowColor=Y.Black(),this._primaryHighlightColor=Y.Black(),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!(!this._diffuseTexture||!this._diffuseTexture.isRenderTarget)||!(!this._reflectionTexture||!this._reflectionTexture.isRenderTarget)}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new sf);const r=this.getScene(),n=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const o=r.getEngine();if(vn(r,e,n,!1,this._maxSimultaneousLights),n._needNormals=!0,yn(r,n),n._areTexturesDirty){if(n._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(n.TEXTURELODSUPPORT=!0),this._diffuseTexture&&th.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;an(this._diffuseTexture,n,"DIFFUSE"),n.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,n.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,n.OPACITYFRESNEL=this._opacityFresnel}else n.DIFFUSE=!1,n.DIFFUSEDIRECTUV=0,n.DIFFUSEHASALPHA=!1,n.GAMMADIFFUSE=!1,n.OPACITYFRESNEL=!1;const e=this._reflectionTexture;if(e&&th.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(n.REFLECTION=!0,n.GAMMAREFLECTION=e.gammaSpace,n.RGBDREFLECTION=e.isRGBD,n.REFLECTIONBLUR=this._reflectionBlur>0,n.LODINREFLECTIONALPHA=e.lodLevelInAlpha,n.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,n.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===Zn.INVCUBIC_MODE&&(n.INVERTCUBICMAP=!0),n.REFLECTIONMAP_3D=e.isCube,n.REFLECTIONMAP_OPPOSITEZ=n.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case Zn.EXPLICIT_MODE:n.REFLECTIONMAP_EXPLICIT=!0;break;case Zn.PLANAR_MODE:n.REFLECTIONMAP_PLANAR=!0;break;case Zn.PROJECTION_MODE:n.REFLECTIONMAP_PROJECTION=!0;break;case Zn.SKYBOX_MODE:n.REFLECTIONMAP_SKYBOX=!0;break;case Zn.SPHERICAL_MODE:n.REFLECTIONMAP_SPHERICAL=!0;break;case Zn.EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Zn.FIXED_EQUIRECTANGULAR_MODE:n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Zn.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Zn.CUBIC_MODE:case Zn.INVCUBIC_MODE:default:n.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(n.REFLECTIONFRESNEL=!0,n.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1)}else n.REFLECTION=!1,n.REFLECTIONFRESNEL=!1,n.REFLECTIONFALLOFF=!1,n.REFLECTIONBLUR=!1,n.REFLECTIONMAP_3D=!1,n.REFLECTIONMAP_SPHERICAL=!1,n.REFLECTIONMAP_PLANAR=!1,n.REFLECTIONMAP_CUBIC=!1,n.REFLECTIONMAP_PROJECTION=!1,n.REFLECTIONMAP_SKYBOX=!1,n.REFLECTIONMAP_EXPLICIT=!1,n.REFLECTIONMAP_EQUIRECTANGULAR=!1,n.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,n.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,n.INVERTCUBICMAP=!1,n.REFLECTIONMAP_OPPOSITEZ=!1,n.LODINREFLECTIONALPHA=!1,n.GAMMAREFLECTION=!1,n.RGBDREFLECTION=!1}n.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,n.USERGBCOLOR=this._useRGBColor,n.NOISE=this._enableNoise}if(n._areLightsDirty&&(n.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),n.BACKMAT_SHADOWONLY=this._shadowOnly),n._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(n)}if(n._areMiscDirty&&(n.REFLECTIONMAP_3D&&this._enableGroundProjection?(n.PROJECTED_GROUND=!0,n.REFLECTIONMAP_SKYBOX=!0):n.PROJECTED_GROUND=!1),gn(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),n),Tn(r,o,this,n,i,null,t.getRenderingMesh().hasThinInstances),Cn(e,n,!1,!0,!1)&&e&&(r.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(Ki.NormalKind)||(e.createNormals(!0),J.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),n.isDirty){n.markAsProcessed(),r.resetCachedMaterial();const i=new Yo;n.FOG&&i.addFallback(0,"FOG"),n.POINTSIZE&&i.addFallback(1,"POINTSIZE"),n.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),_n(n,i,this._maxSimultaneousLights);const s=[Ki.PositionKind];n.NORMAL&&s.push(Ki.NormalKind),n.UV1&&s.push(Ki.UVKind),n.UV2&&s.push(Ki.UV2Kind),pn(s,e,n,i),fn(s,n);const a=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];jr(a);const l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];Bi&&(Bi.PrepareUniforms(a,n),Bi.PrepareSamplers(l,n)),Mn({uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:n,maxSimultaneousLights:this._maxSimultaneousLights});const c=n.toString(),u=r.getEngine().createEffect("background",{attributes:s,uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:c,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o);t.setEffect(u,n,this._materialContext),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady()||(n._renderId=r.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),0))}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),cn(t,this._activeEffect);const o=this._mustRebind(s,n,i,t.visibility);if(o){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);const e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync&&!i._drawWrapper._forceRebindOnNextCall||(s.texturesEnabled&&(this._diffuseTexture&&th.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),ln(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&th.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),r.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),s.texturesEnabled&&(this._diffuseTexture&&th.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&th.ReflectionTextureEnabled&&(r.REFLECTIONBLUR&&r.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):r.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),r.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),r.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),Kr(this._activeEffect,this,s),s.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);!o&&this.isFrozen||(s.lightsEnabled&&dn(s,t,this._activeEffect,r,this._maxSimultaneousLights),this.bindView(n),en(s,t,this._activeEffect,!0),this._useLogarithmicDepth&&Jr(r,n,s),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return Pe.Clone((()=>new rf(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return Pe.Parse((()=>new rf(e.name,t)),e,t,i)}}rf.StandardReflectance0=.05,rf.StandardReflectance90=.5,ae([_e()],rf.prototype,"_primaryColor",void 0),ae([de("_markAllSubMeshesAsLightsDirty")],rf.prototype,"primaryColor",void 0),ae([_e()],rf.prototype,"__perceptualColor",void 0),ae([pe()],rf.prototype,"_primaryColorShadowLevel",void 0),ae([pe()],rf.prototype,"_primaryColorHighlightLevel",void 0),ae([de("_markAllSubMeshesAsLightsDirty")],rf.prototype,"primaryColorHighlightLevel",null),ae([fe()],rf.prototype,"_reflectionTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"reflectionTexture",void 0),ae([pe()],rf.prototype,"_reflectionBlur",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"reflectionBlur",void 0),ae([fe()],rf.prototype,"_diffuseTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"diffuseTexture",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"shadowLights",void 0),ae([pe()],rf.prototype,"_shadowLevel",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"shadowLevel",void 0),ae([ve()],rf.prototype,"_sceneCenter",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"sceneCenter",void 0),ae([pe()],rf.prototype,"_opacityFresnel",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"opacityFresnel",void 0),ae([pe()],rf.prototype,"_reflectionFresnel",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"reflectionFresnel",void 0),ae([pe()],rf.prototype,"_reflectionFalloffDistance",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"reflectionFalloffDistance",void 0),ae([pe()],rf.prototype,"_reflectionAmount",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"reflectionAmount",void 0),ae([pe()],rf.prototype,"_reflectionReflectance0",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"reflectionReflectance0",void 0),ae([pe()],rf.prototype,"_reflectionReflectance90",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"reflectionReflectance90",void 0),ae([pe()],rf.prototype,"_useRGBColor",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"useRGBColor",void 0),ae([pe()],rf.prototype,"_enableNoise",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"enableNoise",void 0),ae([pe()],rf.prototype,"_maxSimultaneousLights",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],rf.prototype,"maxSimultaneousLights",void 0),ae([pe()],rf.prototype,"_shadowOnly",void 0),ae([de("_markAllSubMeshesAsLightsDirty")],rf.prototype,"shadowOnly",void 0),ae([Se()],rf.prototype,"_imageProcessingConfiguration",void 0),ae([pe(),de("_markAllSubMeshesAsMiscDirty")],rf.prototype,"enableGroundProjection",void 0),ae([pe()],rf.prototype,"projectedGroundRadius",void 0),ae([pe()],rf.prototype,"projectedGroundHeight",void 0),u("BABYLON.BackgroundMaterial",rf);class nf{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new Y(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new Y(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:w.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}constructor(e,t){this._errorHandler=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options={...nf._GetDefaultOptions(t),...e},this._scene=t,this.onErrorObservable=new g,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){const t={...this._options,...e};this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new j(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof qn)return void(this._scene.environmentTexture=this._options.environmentTexture);const e=tf.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new Un("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;const e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};const s=this._scene.getWorldExtends((e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox)),r=s.max.subtract(s.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof gl&&this._scene.activeCamera.upperRadiusLimit&&(e=2*this._scene.activeCamera.upperRadiusLimit,t=e);const n=r.length();n>e&&(e=2*n,t=e),e*=1.1,t*=1.5,i=s.min.add(r.scale(.5)),i.y=s.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){this._ground&&!this._ground.isDisposed()||(this._ground=co("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((()=>{this._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new rf("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){this._groundMaterial&&(this._groundTexture||(this._options.groundTexture instanceof qn?this._groundMaterial.diffuseTexture=this._options.groundTexture:(this._groundTexture=new Zn(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture)))}_setupGroundMirrorTexture(e){const t=Zn.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new ef("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,Zn.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new Ps(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e{this._skybox=null}))),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new rf("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){this._skyboxMaterial&&(this._skyboxTexture||(this._options.skyboxTexture instanceof qn?this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture:(this._skyboxTexture=new tf(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=Zn.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture)))}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}}nf._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",nf._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",nf._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class of extends Ur{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=Zn.CLAMP_ADDRESSMODE,this._texture.wrapV=Zn.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=Zn.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=Zn.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,s,r=null){super(e,s),this.onError=r,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=of.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new g,this.onLoadObservable=new g,s=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=Boolean(i.clickToPlay),i.autoPlay=void 0===i.autoPlay||Boolean(i.autoPlay),i.loop=void 0===i.loop||Boolean(i.loop),i.size=Math.abs(i.size)||(s.activeCamera?.48*s.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=nc(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:Un.BACKSIDE},s);const n=this._material=new rf(e+"_material",s);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;const o=this._initTexture(t,s,i);if(this.texture=o,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=nc("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:Un.BACKSIDE},s),this._halfDomeMask.rotate(Gs.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce((()=>{this._setReady(!0)})),i.faceForward&&s.activeCamera){const e=s.activeCamera,t=w.Forward(),i=w.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(w.Dot(t,i))}this._changeTextureMode(this._textureMode)}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case of.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case of.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;const e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((i=>{let s=i.isRightCamera;this._crossEye&&(s=!s),this._texture.uOffset=s?e:t}));break}case of.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0}))}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}}of.MODE_MONOSCOPIC=0,of.MODE_TOPBOTTOM=1,of.MODE_SIDEBYSIDE=2;class af extends of{get photoTexture(){return this.texture}set photoTexture(e){this.texture=e}get imageMode(){return this.textureMode}set imageMode(e){this.textureMode=e}_initTexture(e,t,i){return new Zn(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,(()=>{this.onLoadObservable.notifyObservers()}),((e,t)=>{this.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),this.onError&&this.onError(e,t)}))}}af.MODE_MONOSCOPIC=of.MODE_MONOSCOPIC,af.MODE_TOPBOTTOM=of.MODE_TOPBOTTOM,af.MODE_SIDEBYSIDE=of.MODE_SIDEBYSIDE;let lf=0;const hf=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const i=e._blockEntityCollection;e._blockEntityCollection=!1;const s=Zn.CreateFromBase64String("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==","EnvironmentBRDFTexture"+lf++,e,!0,!1,Zn.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;const r=e.getEngine().getLoadedTexturesCache(),n=r.indexOf(s.getInternalTexture());-1!==n&&r.splice(n,1),s.isRGBD=!0,s.wrapU=Zn.CLAMP_ADDRESSMODE,s.wrapV=Zn.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=s,e.useDelayedTextureLoading=t,mu.ExpandRGBDTexture(s);const o=e.getEngine().onContextRestoredObservable.add((()=>{s.isRGBD=!0;const t=e.onBeforeRenderObservable.add((()=>{s.isReady()&&(e.onBeforeRenderObservable.remove(t),mu.ExpandRGBDTexture(s))}))}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(o)}))}return e.environmentBRDFTexture};class cf extends Do{constructor(){super(...arguments),this.BRDF_V_HEIGHT_CORRELATED=!1,this.MS_BRDF_ENERGY_CONSERVATION=!1,this.SPHERICAL_HARMONICS=!1,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1}}class uf extends ah{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new cf,t),this._useEnergyConservation=uf.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=uf.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=uf.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=uf.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=uf.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=uf.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=uf.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=uf.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation}getClassName(){return"PBRBRDFConfiguration"}}uf.DEFAULT_USE_ENERGY_CONSERVATION=!0,uf.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,uf.DEFAULT_USE_SPHERICAL_HARMONICS=!0,uf.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,ae([pe(),de("_markAllSubMeshesAsMiscDirty")],uf.prototype,"useEnergyConservation",void 0),ae([pe(),de("_markAllSubMeshesAsMiscDirty")],uf.prototype,"useSmithVisibilityHeightCorrelated",void 0),ae([pe(),de("_markAllSubMeshesAsMiscDirty")],uf.prototype,"useSphericalHarmonics",void 0),ae([pe(),de("_markAllSubMeshesAsMiscDirty")],uf.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);Ft.IncludesShadersStore.pbrFragmentDeclaration="uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor;\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)\nuniform mat4 view;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REALTIME_FILTERING\nuniform vec2 vReflectionFilteringInfo;\n#endif\nuniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; \n#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; \n#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams;\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\n#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\n#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\n#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix;\n#endif\n#endif\n#endif\n#ifdef IRIDESCENCE\nuniform vec4 vIridescenceParams;\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\n#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\n#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\n#endif\n#endif\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix;\n#endif\n#endif\n#ifdef SHEEN\nuniform vec4 vSheenColor;\n#ifdef SHEEN_ROUGHNESS\nuniform float vSheenRoughness;\n#endif\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\n#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\n#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\n#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix;\n#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\n#endif\n#ifdef SS_DISPERSION\nuniform float dispersion;\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix;\n#endif\nuniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity;uniform vec4 vTranslucencyColor;\n#ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\nuniform vec2 vTranslucencyColorInfos;uniform mat4 translucencyColorMatrix;\n#endif\n#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\n#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22;\n#else\nuniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX;\n#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";Ft.IncludesShadersStore.pbrUboDeclaration="layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";Ft.IncludesShadersStore.pbrFragmentExtraDeclaration="varying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#include[1..7]\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n";Ft.IncludesShadersStore.samplerFragmentAlternateDeclaration="#ifdef _DEFINENAME_\n#if _DEFINENAME_DIRECTUV==1\n#define v_VARYINGNAME_UV vMainUV1\n#elif _DEFINENAME_DIRECTUV==2\n#define v_VARYINGNAME_UV vMainUV2\n#elif _DEFINENAME_DIRECTUV==3\n#define v_VARYINGNAME_UV vMainUV3\n#elif _DEFINENAME_DIRECTUV==4\n#define v_VARYINGNAME_UV vMainUV4\n#elif _DEFINENAME_DIRECTUV==5\n#define v_VARYINGNAME_UV vMainUV5\n#elif _DEFINENAME_DIRECTUV==6\n#define v_VARYINGNAME_UV vMainUV6\n#else\nvarying vec2 v_VARYINGNAME_UV;\n#endif\n#endif\n";Ft.IncludesShadersStore.pbrFragmentSamplersDeclaration="#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform sampler2D clearCoatRoughnessSampler;\n#endif\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform sampler2D sheenRoughnessSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh;\n#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh;\n#endif\n#endif\n#endif\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYCOLOR_TEXTURE,_VARYINGNAME_,TranslucencyColor,_SAMPLERNAME_,translucencyColor)\n#endif\n";Ft.IncludesShadersStore.subSurfaceScatteringFunctions="bool testLightingForSSS(float diffusionProfile)\n{return diffusionProfile<1.;}";Ft.IncludesShadersStore.importanceSampling="vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}\nvec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { \nfloat phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}";Ft.IncludesShadersStore.pbrHelperFunctions="#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{return square(roughness)+MINIMUMVARIANCE;}\nfloat fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;}\n#else\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;}\n#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);}\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));}\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);return clearCoatAbsorption;}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;}\n#endif\n";Ft.IncludesShadersStore.harmonicsFunctions="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nvec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00\n+ vSphericalL1_1*(normal.y)\n+ vSphericalL10*(normal.z)\n+ vSphericalL11*(normal.x)\n+ vSphericalL2_2*(normal.y*normal.x)\n+ vSphericalL2_1*(normal.y*normal.z)\n+ vSphericalL20*((3.0*normal.z*normal.z)-1.0)\n+ vSphericalL21*(normal.z*normal.x)\n+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));}\n#else\nvec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;}\n#endif\n#endif\n";Ft.IncludesShadersStore.pbrDirectLightingSetupFunctions="struct preLightingInfo\n{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness;\n#ifdef IRIDESCENCE\nfloat iridescenceIntensity;\n#endif\n};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;}\npreLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;}";Ft.IncludesShadersStore.pbrDirectLightingFalloffFunctions="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{return max(0.,1.0-length(lightOffset)/range);}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{return 1.0/maxEps(lightDistanceSquared);}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle)\n{falloff=max(0.,pow(cosAngle,exponent));}\nreturn falloff;}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}";Ft.IncludesShadersStore.pbrBRDFFunctions="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y;\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y;\n#endif\nreturn reflectance;}\nvec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\n#ifdef BRDF_V_HEIGHT_CORRELATED\nvec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0);\n#else\nvec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#endif\nreturn reflectance;}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfloat getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)\n{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));}\n#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\n/**\n* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture.\n* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table\n*/\nvec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;}\n#endif\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);}\n#ifdef CLEARCOAT\nvec3 getR0RemappedForClearCoat(vec3 f0) {\n#ifdef CLEARCOAT_DEFAULTIOR\n#ifdef MOBILE\nreturn saturate(f0*(f0*0.526868+0.529324)-0.0482256);\n#else\nreturn saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998);\n#endif\n#else\nvec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t);\n#endif\n}\n#endif\n#ifdef IRIDESCENCE\nconst mat3 XYZ_TO_REC709=mat3(\n3.2404542,-0.9692660, 0.0556434,\n-1.5371385, 1.8760108,-0.2040259,\n-0.4985314, 0.0415560, 1.0572252\n);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);}\nvec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));}\nfloat getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));}\nvec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;}\nvec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;}\nfloat cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose(),this._bumpTexture?.dispose(),this._tintTexture?.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}}pf._DefaultIndexOfRefraction=1.5,ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"isEnabled",void 0),ae([pe()],pf.prototype,"intensity",void 0),ae([pe()],pf.prototype,"roughness",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"indexOfRefraction",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"texture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"useRoughnessFromMainTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"textureRoughness",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"remapF0OnInterfaceChange",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"bumpTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"isTintEnabled",void 0),ae([_e()],pf.prototype,"tintColor",void 0),ae([pe()],pf.prototype,"tintColorAtDistance",void 0),ae([pe()],pf.prototype,"tintThickness",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],pf.prototype,"tintTexture",void 0);class ff extends Do{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0}}class _f extends ah{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new ff,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=_f._DefaultMinimumThickness,this.maximumThickness=_f._DefaultMaximumThickness,this.indexOfRefraction=_f._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&th.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&th.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&th.IridescenceTextureEnabled?an(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&th.IridescenceTextureEnabled?an(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||((this._texture||this._thicknessTexture)&&th.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._thicknessTexture?.coordinatesIndex??0,this._thicknessTexture?.level??0),this._texture&&ln(this._texture,e,"iridescence"),this._thicknessTexture&&ln(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&th.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&th.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){e&&(this._texture?.dispose(),this._thicknessTexture?.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}}_f._DefaultMinimumThickness=100,_f._DefaultMaximumThickness=400,_f._DefaultIndexOfRefraction=1.3,ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],_f.prototype,"isEnabled",void 0),ae([pe()],_f.prototype,"intensity",void 0),ae([pe()],_f.prototype,"minimumThickness",void 0),ae([pe()],_f.prototype,"maximumThickness",void 0),ae([pe()],_f.prototype,"indexOfRefraction",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],_f.prototype,"texture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],_f.prototype,"thicknessTexture",void 0);class mf extends Do{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class gf extends ah{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new mf,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new N(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&th.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(Ki.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&th.AnisotropicTextureEnabled?an(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1),e._areMiscDirty&&(e.ANISOTROPIC_LEGACY=this._legacy)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.ANISOTROPIC_LEGACY=!1)}bindForSubMesh(e,t){if(!this._isEnabled)return;const i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&th.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),ln(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&th.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,i){super.parse(e,t,i),void 0===e.legacy&&(this.legacy=!0)}}ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],gf.prototype,"isEnabled",void 0),ae([pe()],gf.prototype,"intensity",void 0),ae([ge()],gf.prototype,"direction",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],gf.prototype,"texture",void 0),ae([pe(),de("_markAllSubMeshesAsMiscDirty")],gf.prototype,"legacy",void 0);class vf extends Do{constructor(){super(...arguments),this.SHEEN=!1,this.SHEEN_TEXTURE=!1,this.SHEEN_GAMMATEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS=!1,this.SHEEN_TEXTUREDIRECTUV=0,this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,this.SHEEN_LINKWITHALBEDO=!1,this.SHEEN_ROUGHNESS=!1,this.SHEEN_ALBEDOSCALING=!1,this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1}}class xf extends ah{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new vf,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=Y.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&th.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&th.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=null!==this._roughness,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&th.SheenTextureEnabled?(an(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&th.SheenTextureEnabled?an(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,s){if(!this._isEnabled)return;const r=s.materialDefines,n=this._material.isFrozen;e.useUbo&&n&&e.isSync||((this._texture||this._textureRoughness)&&th.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&ln(this._texture,e,"sheen"),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&ln(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),null!==this._roughness&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&th.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&th.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}}ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],xf.prototype,"isEnabled",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],xf.prototype,"linkSheenWithAlbedo",void 0),ae([pe()],xf.prototype,"intensity",void 0),ae([_e()],xf.prototype,"color",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],xf.prototype,"texture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],xf.prototype,"useRoughnessFromMainTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],xf.prototype,"roughness",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],xf.prototype,"textureRoughness",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],xf.prototype,"albedoScaling",void 0);class Tf extends Do{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_SCATTERING=!1,this.SS_DISPERSION=!1,this.SS_THICKNESSANDMASK_TEXTURE=!1,this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,this.SS_HAS_THICKNESS=!1,this.SS_REFRACTIONINTENSITY_TEXTURE=!1,this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,this.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0,this.SS_REFRACTIONMAP_3D=!1,this.SS_REFRACTIONMAP_OPPOSITEZ=!1,this.SS_LODINREFRACTIONALPHA=!1,this.SS_GAMMAREFRACTION=!1,this.SS_RGBDREFRACTION=!1,this.SS_LINEARSPECULARREFRACTION=!1,this.SS_LINKREFRACTIONTOTRANSPARENCY=!1,this.SS_ALBEDOFORREFRACTIONTINT=!1,this.SS_ALBEDOFORTRANSLUCENCYTINT=!1,this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.SS_USE_THICKNESS_AS_DEPTH=!1,this.SS_USE_GLTF_TEXTURES=!1}}class Sf extends ah{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){this._volumeIndexOfRefraction=e>=1?e:-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new Tf,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isDispersionEnabled=!1,this.isDispersionEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this.useAlbedoToTintRefraction=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=Y.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=Y.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this.translucencyColor=null,this._translucencyColorTexture=null,this.translucencyColorTexture=null,this._useGltfStyleTextures=!0,this.useGltfStyleTextures=!0,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&th.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;if(this._translucencyColorTexture&&th.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&th.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return e.SUBSURFACE=!1,e.SS_DISPERSION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,void(e.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0);if(e._areTexturesDirty){if(e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&th.ThicknessTextureEnabled&&an(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&th.RefractionIntensityTextureEnabled&&an(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&th.TranslucencyIntensityTextureEnabled&&an(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&&th.TranslucencyColorTextureEnabled&&an(this._translucencyColorTexture,e,"SS_TRANSLUCENCYCOLOR_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._refractionIntensityTexture,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._translucencyIntensityTexture,this._isRefractionEnabled&&t.texturesEnabled){const i=this._getRefractionTexture(t);i&&th.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;s.getRenderingMesh().getWorldMatrix().decompose(U.Vector3[0]);const r=Math.max(Math.abs(U.Vector3[0].x),Math.abs(U.Vector3[0].y),Math.abs(U.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*r,(this.maximumThickness-this.minimumThickness)*r)}bindForSubMesh(e,t,i,s){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const r=s.materialDefines,n=this._material.isFrozen,o=this._material.realTimeFiltering,a=r.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&th.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),ln(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&th.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),ln(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&&th.TranslucencyColorTextureEnabled&&r.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),ln(this._translucencyColorTexture,e,"translucencyColor")),l&&th.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;l.isCube||l.depth&&(t=l.depth);const i=l.getSize().width,s=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",l.level,1/s,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",i,G.Log2(i)),l.boundingBoxSize){const t=l;e.updateVector3("vRefractionPosition",t.boundingBoxPosition),e.updateVector3("vRefractionSize",t.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateColor4("vTranslucencyColor",this.translucencyColor??this.tintColor,0),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&th.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&th.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&th.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&&th.TranslucencyColorTextureEnabled&&r.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),l&&th.RefractionTextureEnabled&&(a?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){th.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e||this._refractionIntensityTexture===e||this._translucencyIntensityTexture===e||this._translucencyColorTexture===e}hasRenderTargetTextures(){return!!(th.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture),this._translucencyColorTexture&&e.push(this._translucencyColorTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),this._translucencyColorTexture&&this._translucencyColorTexture.animations&&this._translucencyColorTexture.animations.length>0&&e.push(this._translucencyColorTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose(),this._translucencyColorTexture&&this._translucencyColorTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","translucencyColorSampler")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"},{name:"vTranslucencyColor",size:4,type:"vec4"},{name:"vTranslucencyColorInfos",size:2,type:"vec2"},{name:"translucencyColorMatrix",size:16,type:"mat4"}]}}}ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"isRefractionEnabled",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"isTranslucencyEnabled",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"isDispersionEnabled",void 0),ae([pe(),de("_markScenePrePassDirty")],Sf.prototype,"isScatteringEnabled",void 0),ae([pe()],Sf.prototype,"_scatteringDiffusionProfileIndex",void 0),ae([pe()],Sf.prototype,"refractionIntensity",void 0),ae([pe()],Sf.prototype,"translucencyIntensity",void 0),ae([pe()],Sf.prototype,"useAlbedoToTintRefraction",void 0),ae([pe()],Sf.prototype,"useAlbedoToTintTranslucency",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"thicknessTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"refractionTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"indexOfRefraction",void 0),ae([pe()],Sf.prototype,"_volumeIndexOfRefraction",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"volumeIndexOfRefraction",null),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"invertRefractionY",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"linkRefractionWithTransparency",void 0),ae([pe()],Sf.prototype,"minimumThickness",void 0),ae([pe()],Sf.prototype,"maximumThickness",void 0),ae([pe()],Sf.prototype,"useThicknessAsDepth",void 0),ae([_e()],Sf.prototype,"tintColor",void 0),ae([pe()],Sf.prototype,"tintColorAtDistance",void 0),ae([pe()],Sf.prototype,"dispersion",void 0),ae([_e()],Sf.prototype,"diffusionDistance",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"useMaskFromThicknessTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"refractionIntensityTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"translucencyIntensityTexture",void 0),ae([_e()],Sf.prototype,"translucencyColor",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"translucencyColorTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],Sf.prototype,"useGltfStyleTextures",void 0);const Ef={effect:null,subMesh:null};class bf extends Do{constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class Cf extends Io{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new F(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=Cf.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._reflectivityTexture=null,this._metallicTexture=null,this._metallic=null,this._roughness=null,this._metallicF0Factor=1,this._metallicReflectanceColor=Y.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new Y(0,0,0),this._albedoColor=new Y(1,1,1),this._reflectivityColor=new Y(1,1,1),this._reflectionColor=new Y(1,1,1),this._emissiveColor=new Y(0,0,0),this._microSurface=.9,this._useLightmapAsShadowmap=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromAlbedoTexture=!1,this._useSpecularOverAlpha=!0,this._useMicroSurfaceFromReflectivityMapAlpha=!1,this._useRoughnessFromMetallicTextureAlpha=!0,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallnessFromMetallicTextureBlue=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useAmbientInGrayScale=!1,this._useAutoMicroSurfaceFromReflectivityMap=!1,this._lightFalloff=Cf.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._forceAlphaTest=!1,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new Mi(16),this._globalAmbientColor=new Y(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new uf(this),this.clearCoat=new pf(this),this.iridescence=new _f(this),this.anisotropy=new gf(this),this.sheen=new xf(this),this.subSurface=new Sf(this),this.detailMap=new hh(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),th.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=hf(this.getScene()),this.prePassConfiguration=new eh}get hasRenderTargetTextures(){return!!(th.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){return this._transparencyMode===Cf.PBRMATERIAL_OPAQUE||this._transparencyMode===Cf.PBRMATERIAL_ALPHATEST||this.subSurface?.disableAlphaBlending}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){return!!this._forceAlphaTest||!this.subSurface?.disableAlphaBlending&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Cf.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==Cf.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const s=t._drawWrapper;if(s.effect&&this.isFrozen&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Xr.GetDefineNames,this._eventInfo),t.materialDefines=new bf(this._eventInfo.defineNames));const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=this.getScene(),o=n.getEngine();if(r._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&th.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&th.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&th.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&th.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&e.getInternalTexture()?._sphericalPolynomialPromise)return!1}if(this._lightmapTexture&&th.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&th.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(th.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking())return!1;if(this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&th.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&th.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(r._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;o.getCaps().standardDerivatives||e.isVerticesDataPresent(Ki.NormalKind)||(e.createNormals(!0),J.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const a=t.effect,l=r._areLightsDisposed;let h=this._prepareEffect(e,r,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),c=!1;if(h)if(this._onEffectCreatedObservable&&(Ef.effect=h,Ef.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Ef)),this.allowShaderHotSwapping&&a&&!h.isReady()){if(h=a,r.markAsUnprocessed(),c=this.isFrozen,l)return r._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(h,r,this._materialContext);return!(!t.effect||!t.effect.isReady()||(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!c,s._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),0))}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,i=null,s=null,r=null,n=null,o){if(this._prepareDefines(e,t,r,n,o),!t.isDirty)return null;t.markAsProcessed();const a=this.getScene().getEngine(),l=new Yo;let h=0;t.USESPHERICALINVERTEX&&l.addFallback(h++,"USESPHERICALINVERTEX"),t.FOG&&l.addFallback(h,"FOG"),t.SPECULARAA&&l.addFallback(h,"SPECULARAA"),t.POINTSIZE&&l.addFallback(h,"POINTSIZE"),t.LOGARITHMICDEPTH&&l.addFallback(h,"LOGARITHMICDEPTH"),t.PARALLAX&&l.addFallback(h,"PARALLAX"),t.PARALLAX_RHS&&l.addFallback(h,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&l.addFallback(h++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&l.addFallback(h++,"ENVIRONMENTBRDF"),t.TANGENT&&l.addFallback(h++,"TANGENT"),t.BUMP&&l.addFallback(h++,"BUMP"),h=_n(t,l,this._maxSimultaneousLights,h++),t.SPECULARTERM&&l.addFallback(h++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&l.addFallback(h++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&l.addFallback(h++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&l.addFallback(h++,"LIGHTMAP"),t.NORMAL&&l.addFallback(h++,"NORMAL"),t.AMBIENT&&l.addFallback(h++,"AMBIENT"),t.EMISSIVE&&l.addFallback(h++,"EMISSIVE"),t.VERTEXCOLOR&&l.addFallback(h++,"VERTEXCOLOR"),t.MORPHTARGETS&&l.addFallback(h++,"MORPHTARGETS"),t.MULTIVIEW&&l.addFallback(0,"MULTIVIEW");const c=[Ki.PositionKind];t.NORMAL&&c.push(Ki.NormalKind),t.TANGENT&&c.push(Ki.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&c.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&c.push(Ki.ColorKind),pn(c,e,t,l),fn(c,t),sn(c,e,t),hn(c,0,t);let u="pbr";const d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],p=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],f=["Material","Scene","Mesh"],_={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=l,this._eventInfo.fallbackRank=h,this._eventInfo.defines=t,this._eventInfo.uniforms=d,this._eventInfo.attributes=c,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=f,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=_,this._callbackPluginEventGeneric(Xr.PrepareEffect,this._eventInfo),eh.AddUniforms(d),eh.AddSamplers(p),jr(d),Bi&&(Bi.PrepareUniforms(d,t),Bi.PrepareSamplers(p,t)),Mn({uniformsNames:d,uniformBuffersNames:f,samplers:p,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const m={};this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,d,f,p,t,c,m));const g=t.toString(),v=a.createEffect(u,{attributes:c,uniformsNames:d,uniformBuffersNames:f,samplers:p,defines:g,fallbacks:l,onCompiled:i,onError:s,indexParameters:_,processFinalCode:m.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},a);return this._eventInfo.customCode=void 0,v}_prepareDefines(e,t,i=null,s=null,r=!1){const n=this.getScene(),o=n.getEngine();vn(n,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,yn(n,t);const a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Rn(n,t,this.canRenderToMRT&&!a),An(n,t,a),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!1;if(n.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&th.DiffuseTextureEnabled?(an(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&th.AmbientTextureEnabled?(an(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&th.OpacityTextureEnabled?(an(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&th.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(t.NUM_SAMPLES=""+this.realTimeFilteringQuality,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===Zn.INVCUBIC_MODE,t.REFLECTIONMAP_3D=e.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.coordinatesMode){case Zn.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case Zn.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case Zn.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case Zn.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case Zn.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case Zn.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Zn.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Zn.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Zn.CUBIC_MODE:case Zn.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==Zn.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||o.getCaps().maxVaryingVectors<=8?t.USESPHERICALINVERTEX=!1:t.USESPHERICALINVERTEX=!0))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;this._lightmapTexture&&th.LightmapTextureEnabled?(an(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&th.EmissiveTextureEnabled?(an(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,th.SpecularTextureEnabled?(this._metallicTexture?(an(this._metallicTexture,t,"REFLECTIVITY"),t.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,t.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,t.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,t.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,t.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(an(this._reflectivityTexture,t,"REFLECTIVITY"),t.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,t.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,t.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):t.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture?(t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture,this._metallicReflectanceTexture?(an(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(an(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1):(t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1),this._microSurfaceTexture?an(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1):(t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1),o.getCaps().standardDerivatives&&this._bumpTexture&&th.BumpTextureEnabled&&!this._disableBumpMap?(an(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&th.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=n.useRightHandedSystem,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAX_RHS=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&th.ReflectionTextureEnabled?(t.ENVIRONMENTBRDF=!0,t.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(t.ENVIRONMENTBRDF=!1,t.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?t.ALPHAFROMALBEDO=!0:t.ALPHAFROMALBEDO=!1}t.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===Cf.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Cf.LIGHTFALLOFF_GLTF?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!0):(t.USEPHYSICALLIGHTFALLOFF=!0,t.USEGLTFLIGHTFALLOFF=!1),t.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?t.TWOSIDEDLIGHTING=!0:t.TWOSIDEDLIGHTING=!1,t.SPECULARAA=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(gn(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(Ki.NormalKind),t.DEBUGMODE=this._debugMode),Tn(n,o,this,t,!!i,s,r),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),Cn(e,t,!0,!0,!0,this._transparencyMode!==Cf.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const s={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(Xr.GetDefineNames,this._eventInfo);const r=new bf(this._eventInfo.defineNames),n=this._prepareEffect(e,r,void 0,void 0,s.useInstances,s.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(Ef.effect=n,Ef.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Ef)),n.isReady()?t&&t(this):n.onCompileObservable.add((()=>{t&&t(this)}))}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionFilteringInfo",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("reflectionMatrix",16),e.addUniform("vReflectionColor",3),e.addUniform("vAlbedoColor",4),e.addUniform("vLightingIntensity",4),e.addUniform("vReflectionMicrosurfaceInfos",3),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),e.addUniform("vSphericalL00",3),e.addUniform("vSphericalL1_1",3),e.addUniform("vSphericalL10",3),e.addUniform("vSphericalL11",3),e.addUniform("vSphericalL2_2",3),e.addUniform("vSphericalL2_1",3),e.addUniform("vSphericalL20",3),e.addUniform("vSphericalL21",3),e.addUniform("vSphericalL22",3),e.addUniform("vSphericalX",3),e.addUniform("vSphericalY",3),e.addUniform("vSphericalZ",3),e.addUniform("vSphericalXX_ZZ",3),e.addUniform("vSphericalYY_ZZ",3),e.addUniform("vSphericalZZ",3),e.addUniform("vSphericalXY",3),e.addUniform("vSphericalYZ",3),e.addUniform("vSphericalZX",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e);const o=s.getEngine();this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const a=this._mustRebind(s,n,i,t.visibility);cn(t,this._activeEffect,this.prePassConfiguration);let l=null;const h=this._uniformBuffer;if(a){if(this.bindViewProjection(n),l=this._getReflectionTexture(),!h.useUbo||!this.isFrozen||!h.isSync||i._drawWrapper._forceRebindOnNextCall){if(s.texturesEnabled){if(this._albedoTexture&&th.DiffuseTextureEnabled&&(h.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),ln(this._albedoTexture,h,"albedo")),this._ambientTexture&&th.AmbientTextureEnabled&&(h.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),ln(this._ambientTexture,h,"ambient")),this._opacityTexture&&th.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),ln(this._opacityTexture,h,"opacity")),l&&th.ReflectionTextureEnabled){if(h.updateMatrix("reflectionMatrix",l.getReflectionTextureMatrix()),h.updateFloat2("vReflectionInfos",l.level,0),l.boundingBoxSize){const e=l;h.updateVector3("vReflectionPosition",e.boundingBoxPosition),h.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=l.getSize().width;h.updateFloat2("vReflectionFilteringInfo",e,G.Log2(e))}if(!r.USEIRRADIANCEMAP){const e=l.sphericalPolynomial;if(r.USESPHERICALFROMREFLECTIONMAP&&e)if(r.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;h.updateVector3("vSphericalL00",t.l00),h.updateVector3("vSphericalL1_1",t.l1_1),h.updateVector3("vSphericalL10",t.l10),h.updateVector3("vSphericalL11",t.l11),h.updateVector3("vSphericalL2_2",t.l2_2),h.updateVector3("vSphericalL2_1",t.l2_1),h.updateVector3("vSphericalL20",t.l20),h.updateVector3("vSphericalL21",t.l21),h.updateVector3("vSphericalL22",t.l22)}else h.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),h.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),h.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),h.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),h.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),h.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),h.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),h.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),h.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}h.updateFloat3("vReflectionMicrosurfaceInfos",l.getSize().width,l.lodGenerationScale,l.lodGenerationOffset)}this._emissiveTexture&&th.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),ln(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&th.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),ln(this._lightmapTexture,h,"lightmap")),th.SpecularTextureEnabled&&(this._metallicTexture?(h.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),ln(this._metallicTexture,h,"reflectivity")):this._reflectivityTexture&&(h.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),ln(this._reflectivityTexture,h,"reflectivity")),this._metallicReflectanceTexture&&(h.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),ln(this._metallicReflectanceTexture,h,"metallicReflectance")),this._reflectanceTexture&&r.REFLECTANCE&&(h.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),ln(this._reflectanceTexture,h,"reflectance")),this._microSurfaceTexture&&(h.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),ln(this._microSurfaceTexture,h,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&&th.BumpTextureEnabled&&!this._disableBumpMap&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),ln(this._bumpTexture,h,"bump"),s._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),r.METALLICWORKFLOW){$.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,$.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,h.updateColor4("vReflectivityColor",$.Color3[0],1);const e=this.subSurface?._indexOfRefraction??1.5,t=1,i=Math.pow((e-t)/(e+t),2);this._metallicReflectanceColor.scaleToRef(i*this._metallicF0Factor,$.Color3[0]);const s=this._metallicF0Factor;h.updateColor4("vMetallicReflectanceFactors",$.Color3[0],s)}else h.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);h.updateColor3("vEmissiveColor",th.EmissiveTextureEnabled?this._emissiveColor:Y.BlackReadOnly),h.updateColor3("vReflectionColor",this._reflectionColor),!r.SS_REFRACTION&&this.subSurface?._linkRefractionWithTransparency?h.updateColor4("vAlbedoColor",this._albedoColor,1):h.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*s.environmentIntensity,this._lightingInfos.w=this._specularIntensity,h.updateVector4("vLightingIntensity",this._lightingInfos),s.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor),h.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}s.texturesEnabled&&(this._albedoTexture&&th.DiffuseTextureEnabled&&h.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&th.AmbientTextureEnabled&&h.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&th.OpacityTextureEnabled&&h.setTexture("opacitySampler",this._opacityTexture),l&&th.ReflectionTextureEnabled&&(r.LODBASEDMICROSFURACE?h.setTexture("reflectionSampler",l):(h.setTexture("reflectionSampler",l._lodTextureMid||l),h.setTexture("reflectionSamplerLow",l._lodTextureLow||l),h.setTexture("reflectionSamplerHigh",l._lodTextureHigh||l)),r.USEIRRADIANCEMAP&&h.setTexture("irradianceSampler",l.irradianceTexture)),r.ENVIRONMENTBRDF&&h.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&th.EmissiveTextureEnabled&&h.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&th.LightmapTextureEnabled&&h.setTexture("lightmapSampler",this._lightmapTexture),th.SpecularTextureEnabled&&(this._metallicTexture?h.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&h.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&h.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&r.REFLECTANCE&&h.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&h.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&&th.BumpTextureEnabled&&!this._disableBumpMap&&h.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Kr(this._activeEffect,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!a&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&dn(s,t,this._activeEffect,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==ks.FOGMODE_NONE||l||this.subSurface.refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),en(s,t,this._activeEffect,!0),r.NUM_MORPH_INFLUENCERS&&nn(t,this._activeEffect),r.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,r.INSTANCES),this._imageProcessingConfiguration.bind(this._activeEffect),Jr(r,this._activeEffect,s)),this._afterBind(t,this._activeEffect,i),h.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._albedoTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e}setPrePassRenderer(){if(!this.subSurface?.isScatteringEnabled)return!1;const e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._albedoTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._metallicTexture?.dispose(),this._reflectivityTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._metallicReflectanceTexture?.dispose(),this._reflectanceTexture?.dispose(),this._microSurfaceTexture?.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}Cf.PBRMATERIAL_OPAQUE=Dn.MATERIAL_OPAQUE,Cf.PBRMATERIAL_ALPHATEST=Dn.MATERIAL_ALPHATEST,Cf.PBRMATERIAL_ALPHABLEND=Dn.MATERIAL_ALPHABLEND,Cf.PBRMATERIAL_ALPHATESTANDBLEND=Dn.MATERIAL_ALPHATESTANDBLEND,Cf.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,Cf.LIGHTFALLOFF_PHYSICAL=0,Cf.LIGHTFALLOFF_GLTF=1,Cf.LIGHTFALLOFF_STANDARD=2,ae([Se()],Cf.prototype,"_imageProcessingConfiguration",void 0),ae([de("_markAllSubMeshesAsMiscDirty")],Cf.prototype,"debugMode",void 0);class yf extends Cf{get refractionTexture(){return this.subSurface.refractionTexture}set refractionTexture(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)}get indexOfRefraction(){return this.subSurface.indexOfRefraction}set indexOfRefraction(e){this.subSurface.indexOfRefraction=e}get invertRefractionY(){return this.subSurface.invertRefractionY}set invertRefractionY(e){this.subSurface.invertRefractionY=e}get linkRefractionWithTransparency(){return this.subSurface.linkRefractionWithTransparency}set linkRefractionWithTransparency(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)}get usePhysicalLightFalloff(){return this._lightFalloff===Cf.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Cf.LIGHTFALLOFF_PHYSICAL:Cf.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Cf.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Cf.LIGHTFALLOFF_GLTF:Cf.LIGHTFALLOFF_STANDARD)}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=yf.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=Y.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new Y(0,0,0),this.albedoColor=new Y(1,1,1),this.reflectivityColor=new Y(1,1,1),this.reflectionColor=new Y(1,1,1),this.emissiveColor=new Y(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=hf(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const s=Pe.Clone((()=>new yf(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return s.id=e,s.name=e,this.stencil.copyTo(s.stencil),this._clonePlugins(s,i),s}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){const s=Pe.Parse((()=>new yf(e.name,t)),e,t,i);return e.stencil&&s.stencil.parse(e.stencil,t,i),Dn._ParsePlugins(e,s,t,i),e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}yf.PBRMATERIAL_OPAQUE=Cf.PBRMATERIAL_OPAQUE,yf.PBRMATERIAL_ALPHATEST=Cf.PBRMATERIAL_ALPHATEST,yf.PBRMATERIAL_ALPHABLEND=Cf.PBRMATERIAL_ALPHABLEND,yf.PBRMATERIAL_ALPHATESTANDBLEND=Cf.PBRMATERIAL_ALPHATESTANDBLEND,yf.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Cf.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"directIntensity",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"emissiveIntensity",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"environmentIntensity",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"specularIntensity",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"disableBumpMap",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"albedoTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"ambientTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"ambientTextureStrength",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesAndMiscDirty")],yf.prototype,"opacityTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"reflectionTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"emissiveTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"reflectivityTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"metallicTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"metallic",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"roughness",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"metallicF0Factor",void 0),ae([_e(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"metallicReflectanceColor",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"metallicReflectanceTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"reflectanceTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"microSurfaceTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"bumpTexture",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty",null)],yf.prototype,"lightmapTexture",void 0),ae([_e("ambient"),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"ambientColor",void 0),ae([_e("albedo"),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"albedoColor",void 0),ae([_e("reflectivity"),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"reflectivityColor",void 0),ae([_e("reflection"),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"reflectionColor",void 0),ae([_e("emissive"),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"emissiveColor",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"microSurface",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useLightmapAsShadowmap",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesAndMiscDirty")],yf.prototype,"useAlphaFromAlbedoTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesAndMiscDirty")],yf.prototype,"forceAlphaTest",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesAndMiscDirty")],yf.prototype,"alphaCutOff",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useSpecularOverAlpha",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useRoughnessFromMetallicTextureGreen",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useMetallnessFromMetallicTextureBlue",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useAmbientInGrayScale",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),ae([pe()],yf.prototype,"usePhysicalLightFalloff",null),ae([pe()],yf.prototype,"useGLTFLightFalloff",null),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useRadianceOverAlpha",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useObjectSpaceNormalMap",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useParallax",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useParallaxOcclusion",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"parallaxScaleBias",void 0),ae([pe(),de("_markAllSubMeshesAsLightsDirty")],yf.prototype,"disableLighting",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"forceIrradianceInFragment",void 0),ae([pe(),de("_markAllSubMeshesAsLightsDirty")],yf.prototype,"maxSimultaneousLights",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"invertNormalMapX",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"invertNormalMapY",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"twoSidedLighting",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useAlphaFresnel",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useLinearAlphaFresnel",void 0),ae([de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"environmentBRDFTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"forceNormalForward",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"enableSpecularAntiAliasing",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useHorizonOcclusion",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yf.prototype,"useRadianceOcclusion",void 0),ae([pe(),de("_markAllSubMeshesAsMiscDirty")],yf.prototype,"unlit",void 0),ae([pe(),de("_markAllSubMeshesAsMiscDirty")],yf.prototype,"applyDecalMapAfterDetailMap",void 0),u("BABYLON.PBRMaterial",yf),Br._TextureLoaders.push(new class{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,s){const r=t.getEngine();let n,o=!1,a=1e3;if(Array.isArray(e))for(let i=0;i1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),pu.UploadDDSLevels(r,t,s,n,o,6,-1,i),n.isFourCC||1!==n.mipmapCount?a=n.mipmapCount-1:r.generateMipMapsForCubemap(t)}else{const s=e;n=pu.GetDDSInfo(s),t.width=n.width,t.height=n.height,i&&(n.sphericalPolynomial=new Qc),o=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps,r._unpackFlipY(n.isCompressed),pu.UploadDDSLevels(r,t,s,n,o,6),n.isFourCC||1!==n.mipmapCount?a=n.mipmapCount-1:r.generateMipMapsForCubemap(t,!1)}r._setCubeMapTextureParams(t,o,a),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s({isDDS:!0,width:t.width,info:n,data:e,texture:t})}loadData(e,t,i){const s=pu.GetDDSInfo(e),r=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps&&s.width>>s.mipmapCount-1==1;i(s.width,s.height,r,s.isFourCC,(()=>{pu.UploadDDSLevels(t.getEngine(),t,e,s,r,1)}))}}),Br._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=Tu(e);if(n){t.width=n.width,t.height=n.width;try{yu(t,n),bu(t,e,n).then((()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}),(e=>{r?.("Can not upload environment levels",e)}))}catch(e){r?.("Can not upload environment file",e)}}else r&&r("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}});class Af{constructor(e,t){if(this.data=e,this.isInvalid=!1,!Af.IsValid(e))return this.isInvalid=!0,void J.Error("texture missing KTX identifier");const i=Uint32Array.BYTES_PER_ELEMENT,s=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),r=67305985===s.getUint32(0,!0);return this.glType=s.getUint32(1*i,r),this.glTypeSize=s.getUint32(2*i,r),this.glFormat=s.getUint32(3*i,r),this.glInternalFormat=s.getUint32(4*i,r),this.glBaseInternalFormat=s.getUint32(5*i,r),this.pixelWidth=s.getUint32(6*i,r),this.pixelHeight=s.getUint32(7*i,r),this.pixelDepth=s.getUint32(8*i,r),this.numberOfArrayElements=s.getUint32(9*i,r),this.numberOfFaces=s.getUint32(10*i,r),this.numberOfMipmapLevels=s.getUint32(11*i,r),this.bytesOfKeyValueData=s.getUint32(12*i,r),0!==this.glType?(J.Error("only compressed formats currently supported"),void(this.isInvalid=!0)):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?(J.Error("only 2D textures currently supported"),void(this.isInvalid=!0)):0!==this.numberOfArrayElements?(J.Error("texture arrays not currently supported"),void(this.isInvalid=!0)):this.numberOfFaces!==t?(J.Error("number of faces expected"+t+", but found "+this.numberOfFaces),void(this.isInvalid=!0)):void(this.loadType=Af.COMPRESSED_2D))}uploadLevels(e,t){switch(this.loadType){case Af.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case Af.TEX_2D:case Af.COMPRESSED_3D:case Af.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=Af.HEADER_LEN+this.bytesOfKeyValueData,s=this.pixelWidth,r=this.pixelHeight;const n=t?this.numberOfMipmapLevels:1;for(let t=0;t=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}Af.HEADER_LEN=64,Af.COMPRESSED_2D=0,Af.COMPRESSED_3D=1,Af.TEX_2D=2,Af.TEX_3D=3;class Rf{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map((e=>({workerPromise:Promise.resolve(e),idle:!0})))}dispose(){for(const e of this._workerInfos)e.workerPromise.then((e=>{e.terminate()}));this._workerInfos.length=0,this._pendingActions.length=0}push(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)}_executeOnIdleWorker(e){for(const t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then((i=>{t(i,(()=>{const t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0}))}))}}class If extends Rf{constructor(e,t,i=If.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,(()=>{s(),e.idle&&(e.timeoutId=setTimeout((()=>{e.workerPromise.then((e=>{e.terminate()}));const t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)}),this._options.idleTimeElapsedBeforeRelease))}))}))}}var Pf,Mf,Df;function Of(e,t){const i=t?.jsDecoderModule||KTX2DECODER;e&&(e.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(i.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(i.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)),t&&(t.wasmUASTCToASTC&&(i.LiteTranscoder_UASTC_ASTC.WasmBinary=t.wasmUASTCToASTC),t.wasmUASTCToBC7&&(i.LiteTranscoder_UASTC_BC7.WasmBinary=t.wasmUASTCToBC7),t.wasmUASTCToRGBA_UNORM&&(i.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary=t.wasmUASTCToRGBA_UNORM),t.wasmUASTCToRGBA_SRGB&&(i.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary=t.wasmUASTCToRGBA_SRGB),t.wasmUASTCToR8_UNORM&&(i.LiteTranscoder_UASTC_R8_UNORM.WasmBinary=t.wasmUASTCToR8_UNORM),t.wasmUASTCToRG8_UNORM&&(i.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary=t.wasmUASTCToRG8_UNORM),t.jsMSCTranscoder&&(i.MSCTranscoder.JSModule=t.jsMSCTranscoder),t.wasmMSCTranscoder&&(i.MSCTranscoder.WasmBinary=t.wasmMSCTranscoder),t.wasmZSTDDecoder&&(i.ZSTDDecoder.WasmBinary=t.wasmZSTDDecoder))}function Nf(e){let t;void 0===e&&"undefined"!=typeof KTX2DECODER&&(e=KTX2DECODER),onmessage=i=>{if(i.data)switch(i.data.action){case"init":{const s=i.data.urls;s&&(s.jsDecoderModule&&void 0===e&&(importScripts(s.jsDecoderModule),e=KTX2DECODER),Of(s)),i.data.wasmBinaries&&Of(void 0,{...i.data.wasmBinaries,jsDecoderModule:e}),t=new e.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":e.KTX2Decoder.DefaultDecoderOptions=i.data.options;break;case"decode":t.decode(i.data.data,i.data.caps,i.data.options).then((e=>{const t=[];for(let i=0;i{postMessage({action:"decoded",success:!1,msg:e})}))}}}If.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(Pf||(Pf={})),function(e){e[e.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",e[e.BC7_RGBA=1]="BC7_RGBA",e[e.BC3_RGBA=2]="BC3_RGBA",e[e.BC1_RGB=3]="BC1_RGB",e[e.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",e[e.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",e[e.ETC2_RGBA=6]="ETC2_RGBA",e[e.ETC1_RGB=7]="ETC1_RGB",e[e.RGBA32=8]="RGBA32",e[e.R8=9]="R8",e[e.RG8=10]="RG8"}(Mf||(Mf={})),function(e){e[e.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",e[e.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",e[e.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",e[e.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",e[e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",e[e.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",e[e.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",e[e.RGBA8Format=32856]="RGBA8Format",e[e.R8Format=33321]="R8Format",e[e.RG8Format=33323]="RG8Format"}(Df||(Df={}));class wf{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(wf._WorkerPoolPromise||wf._DecoderModulePromise)return;const t={jsDecoderModule:Ii.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:Ii.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:Ii.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:Ii.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:Ii.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:Ii.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:Ii.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:Ii.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:Ii.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:Ii.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?wf._WorkerPoolPromise=new Promise((i=>{const s=`${Of}(${Nf})()`,r=URL.createObjectURL(new Blob([s],{type:"application/javascript"}));i(new If(e,(()=>function(e,t,i){return new Promise(((t,s)=>{const r=t=>{e.removeEventListener("error",r),e.removeEventListener("message",n),s(t)},n=i=>{"init"===i.data.action&&(e.removeEventListener("error",r),e.removeEventListener("message",n),t(e))};e.addEventListener("error",r),e.addEventListener("message",n),e.postMessage({action:"init",urls:i,wasmBinaries:undefined})}))}(new Worker(r),0,t))))})):void 0===wf._KTX2DecoderModule?wf._DecoderModulePromise=Ii.LoadBabylonScriptAsync(t.jsDecoderModule).then((()=>(wf._KTX2DecoderModule=KTX2DECODER,wf._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,wf._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,Of(t,wf._KTX2DecoderModule),new wf._KTX2DecoderModule.KTX2Decoder))):(wf._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,wf._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,wf._DecoderModulePromise=Promise.resolve(new wf._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=wf.DefaultNumWorkers){this._engine=e;const i="object"==typeof t&&t.workerPool||wf.WorkerPool;if(i)wf._WorkerPoolPromise=Promise.resolve(i);else{"object"==typeof t?wf._KTX2DecoderModule=t?.binariesAndModulesContainer?.jsDecoderModule:"undefined"!=typeof KTX2DECODER&&(wf._KTX2DecoderModule=KTX2DECODER);const e="number"==typeof t?t:t.numWorkers??wf.DefaultNumWorkers;wf._Initialize(e)}}_uploadAsync(e,t,i){const s=this._engine.getCaps(),r={astc:!!s.astc,bptc:!!s.bptc,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,etc1:!!s.etc1};if(wf._WorkerPoolPromise)return wf._WorkerPoolPromise.then((s=>new Promise(((n,o)=>{s.push(((s,a)=>{const l=e=>{s.removeEventListener("error",l),s.removeEventListener("message",h),o(e),a()},h=e=>{if("decoded"===e.data.action){if(s.removeEventListener("error",l),s.removeEventListener("message",h),e.data.success)try{this._createTexture(e.data.decodedData,t,i),n()}catch(e){o({message:e})}else o({message:e.data.msg});a()}};s.addEventListener("error",l),s.addEventListener("message",h),s.postMessage({action:"setDefaultDecoderOptions",options:wf.DefaultDecoderOptions._getKTX2DecoderOptions()});const c=new Uint8Array(e.byteLength);c.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),s.postMessage({action:"decode",data:c,caps:r,options:i},[c.buffer])}))}))));if(wf._DecoderModulePromise)return wf._DecoderModulePromise.then((i=>(wf.DefaultDecoderOptions.isDirty&&(wf._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=wf.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise(((r,n)=>{i.decode(e,s).then((e=>{this._createTexture(e,t),r()})).catch((e=>{n({message:e})}))})))));throw new Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let s=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,s=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw new Error("KTX2 container - could not transcode the data. "+e.errors);for(let i=0;i=12){const t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}wf.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null},wf.DefaultNumWorkers=wf.GetDefaultNumWorkers(),wf.DefaultDecoderOptions=new class{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;const e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[Mf.BC1_RGB,Mf.BC3_RGBA],yes:{transcodeFormat:Mf.RGBA32,engineFormat:Df.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}},Br._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,s){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const r=t.getEngine(),n=new Af(e,6),o=n.numberOfMipmapLevels>1&&t.generateMipMaps;r._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,r._setCubeMapTextureParams(t,o,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()}loadData(e,t,i,s){if(Af.IsValid(e)){t._invertVScale=!t.invertY;const s=new Af(e,1),r=function(e){switch(e){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}(s.glInternalFormat);r?(t.format=r,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=s.glInternalFormat,i(s.pixelWidth,s.pixelHeight,t.generateMipMaps,!0,(()=>{s.uploadLevels(t,t.generateMipMaps)}),s.isInvalid)}else wf.IsValid(e)?new wf(t.getEngine())._uploadAsync(e,t,s).then((()=>{i(t.width,t.height,t.generateMipMaps,!0,(()=>{}),!1)}),(e=>{J.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,(()=>{}),!0)})):(J.Error("texture missing KTX identifier"),i(0,0,!1,!1,(()=>{}),!0))}});class Ff extends _l{constructor(e,t,i){super(e,w.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=L.Identity(),this._referencedPosition=new w,this._trackingState=yh.NOT_TRACKING,this.onXRCameraInitializedObservable=new g,this.onBeforeCameraTeleport=new g,this.onAfterCameraTeleport=new g,this.onTrackingStateChanged=new g,this.compensateOnFirstFrame=!0,this._rotate180=new L(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new L,this.cameraRigMode=or.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add((()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame,this._xrSessionManager.onWorldScaleFactorChangedObservable.add((()=>{this._xrSessionManager.currentFrame&&this._updateDepthNearFar()}))})),this._xrSessionManager.onXRFrameObservable.add((()=>{this._firstFrame&&this._updateFromXRSession(),this.onXRCameraInitializedObservable.hasObservers()&&(this.onXRCameraInitializedObservable.notifyObservers(this),this.onXRCameraInitializedObservable.clear()),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()}),void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y*this._xrSessionManager.worldScalingFactor:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new nr(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new nr(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){e&&e!==this&&(e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,L.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace())}getClassName(){return"WebXRCamera"}setTarget(e){const t=U.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),L.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateDepthNearFar(){const e=(this.maxZ||1e4)*this._xrSessionManager.worldScalingFactor,t={depthFar:e,depthNear:this.minZ};this._xrSessionManager.updateRenderState(t),this._cache.minZ=this.minZ,this._cache.maxZ=e}_updateFromXRSession(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e)return void this._setTrackingState(yh.NOT_TRACKING);const t=e.emulatedPosition?yh.TRACKING_LOST:yh.TRACKING;if(this._setTrackingState(t),this.minZ===this._cache.minZ&&this.maxZ===this._cache.maxZ||this._updateDepthNearFar(),e.transform){const t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;const i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._referenceQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach(((e,t)=>{const i=this.rigCameras[t];i.isLeftCamera||i.isRightCamera||("right"===e.eye?i._isRightCamera=!0:"left"===e.eye&&(i._isLeftCamera=!0));const s=this.getScene().customRenderTargets;for(let e=0;ee;){const e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=U.Matrix[0],t=U.Matrix[1],i=U.Matrix[2];B.ComposeToRef(Ff._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),B.ComposeToRef(Ff._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);const s=new XRRigidTransform({x:this._referencedPosition.x/this._xrSessionManager.worldScalingFactor,y:this._referencedPosition.y/this._xrSessionManager.worldScalingFactor,z:this._referencedPosition.z/this._xrSessionManager.worldScalingFactor},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(s)}}}Ff._ScaleReadOnly=w.One();class Lf{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new g,this.onStateChangedObservable=new g,this.state=Ch.NOT_IN_XR,this.sessionManager=new bh(e),this.camera=new Ff("webxr",e,this.sessionManager),this.featuresManager=new fo(this.sessionManager),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}static CreateAsync(e){const t=new Lf(e);return t.sessionManager.initializeAsync().then((()=>(t._supported=!0,t))).catch((e=>{throw t._setState(Ch.NOT_IN_XR),t.dispose(),e}))}dispose(){this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),this._spectatorCamera?.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),s={}){if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(Ch.ENTERING_XR),"viewer"!==t&&"local"!==t&&(s.optionalFeatures=s.optionalFeatures||[],s.optionalFeatures.push(t)),s=await this.featuresManager._extendXRSessionInitObject(s),"immersive-ar"===e&&"unbounded"!==t&&J.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,s),await this.sessionManager.setReferenceSpaceTypeAsync(t);const r={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};if(!this.featuresManager.getEnabledFeature(po.LAYERS)){const e=await i.initializeXRLayerAsync(this.sessionManager.session);r.baseLayer=e}return this.sessionManager.updateRenderState(r),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!this._nonVRCamera?.inputs?.attachedToElement,this._nonVRCamera?.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),this.sessionManager.onXRSessionEnded.addOnce((()=>{this.state!==Ch.EXITING_XR&&this._setState(Ch.EXITING_XR),this.camera.rigCameras.forEach((e=>{e.outputRenderTarget=null})),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(Ch.NOT_IN_XR)})),this.sessionManager.onXRFrameObservable.addOnce((()=>{this._setState(Ch.IN_XR)})),this.sessionManager}catch(e){throw J.Log(e),J.Log(e.message),this._setState(Ch.NOT_IN_XR),e}}exitXRAsync(){return this.state!==Ch.IN_XR?Promise.resolve():(this._setState(Ch.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){const t=1/(e?.fps?e.fps:1e3)*1e3,i=e?.preferredCameraIndex?e?.preferredCameraIndex:0,s=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=t&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[i].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[i].absoluteRotation))};if(this._spectatorMode){if(i>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const e=()=>{this.state===Ch.IN_XR?(this._spectatorCamera=new Il("webxr-spectator",w.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new L,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(s),this._scene.onAfterRenderCameraObservable.add((e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)}))):this.state===Ch.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=null)};this.onStateChangedObservable.add(e),e()}else this.sessionManager.onXRFrameObservable.removeCallback(s),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class Bf{constructor(e,t,i=-1,s=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=s,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new g,this.onButtonStateChangedObservable=new g}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return 0!==this._axesIndices.length}isButton(){return-1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){const i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}}Bf.BUTTON_TYPE="button",Bf.SQUEEZE_TYPE="squeeze",Bf.THUMBSTICK_TYPE="thumbstick",Bf.TOUCHPAD_TYPE="touchpad",Bf.TRIGGER_TYPE="trigger";class Vf{constructor(e,t,i,s,r=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=s,this._doNotLoadControllerMesh=r,this._controllerCache=n,this._initComponent=e=>{if(!e)return;const t=this.layout.components[e],i=t.type,s=t.gamepadIndices.button,r=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&r.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new Bf(e,i,s,r)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new g,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach((e=>this.getComponent(e).dispose())),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach((e=>{e.setEnabled(!1)})),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map((e=>this.components[e])).filter((t=>t.type===e))}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){const e=!this._getModelLoadingConstraints();let t=this._getGenericFilenameAndPath();return e?J.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise(((i,s)=>{const r=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const e=this._controllerCache.filter((e=>e.filename===t.filename&&e.path===t.path));if(e[0])return e[0].meshes.forEach((e=>e.setEnabled(!0))),void r(e[0].meshes)}Ro.ImportMesh("",t.path,t.filename,this.scene,(e=>{this._controllerCache&&this._controllerCache.push({...t,meshes:e}),r(e)}),null,((e,i)=>{J.Log(i),J.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),s(i)}))}))}updateFromXRFrame(e){this.getComponentIds().forEach((e=>this.getComponent(e).update(this.gamepadObject))),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren((e=>e.name===t),!1)[0]}_getImmediateChildByName(e,t){return e.getChildren((e=>e.name==t),!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh)return;if(!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;const s=i?.5*t+.5:t;L.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,s,e.valueMesh.rotationQuaternion),w.LerpToRef(e.minMesh.position,e.maxMesh.position,s,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new Un(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))})),this.rootMesh.rotationQuaternion=L.FromEulerAngles(0,Math.PI,0)}}class Uf extends Vf{constructor(e,t,i){super(e,kf[i],t,i),this.profileId=Uf.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new Un(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)})),this.rootMesh.rotationQuaternion=L.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}Uf.ProfileId="generic-trigger";const kf={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};class Gf extends Vf{constructor(e,t,i,s,r){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,r),this._repositoryUrl=s,this.controllerCache=r,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach((e=>{this._touchDots[e].dispose()}))}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){const e=Ro.IsPluginForExtensionAvailable(".glb");return e||J.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach((i=>{const s=t.visualResponses[i];if("transform"===s.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s.valueNodeName),minMesh:this._getChildByName(this.rootMesh,s.minNodeName),maxMesh:this._getChildByName(this.rootMesh,s.maxNodeName)};else{const r=t.type===Bf.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:s.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r)},t.type===Bf.TOUCHPAD_TYPE&&!this._touchDots[i]){const t=nc(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new dh(i+"mat",this.scene),t.material.diffuseColor=Y.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}}))}))}_setRootMesh(e){let t;this.rootMesh=new Un(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i{const t=this.getComponent(e);if(!t.hasChanges)return;const i=this._buttonMeshMapping[e],s=this.layout.components[e];Object.keys(s.visualResponses).forEach((e=>{const r=s.visualResponses[e];let n=t.value;if("xAxis"===r.componentProperty?n=t.axes.x:"yAxis"===r.componentProperty&&(n=t.axes.y),"transform"===r.valueNodeProperty)this._lerpTransform(i.states[e],n,"button"!==r.componentProperty);else{const s=i.states[e].valueMesh;s&&(s.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}}))}))}}const zf=[];class Wf{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){const t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){const s=[];i&&s.push(i),s.push(...e.profiles||[]),s.length&&!s[0]&&s.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&s.push("oculus-touch-v2");const r=s.indexOf("windows-mixed-reality");if(-1!==r&&s.splice(r,0,"microsoft-mixed-reality"),s.length||s.push("generic-trigger"),this.UseOnlineRepository){const i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,r=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,s,e,t).catch((()=>r.call(this,s,e,t)))}return this._LoadProfilesFromAvailableControllers(s,e,t)}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=Ii.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then((e=>JSON.parse(e))),this._ProfilesList}static ClearControllerCache(){zf.forEach((e=>{e.meshes.forEach((e=>{e.dispose(!1,!0)}))})),zf.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then((()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList())).then((t=>{for(let i=0;i(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=Ii.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then((e=>JSON.parse(e)))),this._ProfileLoadingPromises[e]))).then((e=>new Gf(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:zf)))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let s=0;snew Uf(t,e.gamepad,e.handedness))),Wf.DefaultFallbacks();let Hf=0;class Xf{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new w,this._disposed=!1,this.onDisposeObservable=new g,this.onMeshLoadedObservable=new g,this.onMotionControllerInitObservable=new g,this._uniqueId=`controller-${Hf++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new Wr(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new L,this.inputSource.gripSpace&&(this.grip=new Wr(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new L),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&Wf.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then((e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then((e=>{e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach((e=>e.renderingGroupId=this._options.renderingGroupId))),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&this.motionController?.dispose()}))}),(()=>{Ii.Warn("Could not find a matching motion controller for the registered input source")}))}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){const i=t&&this.grip?this.grip:this.pointer;w.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i,s){const r=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=r,r){const e=r.transform.position;this.pointer.position.set(e.x,e.y,e.z).scaleInPlace(s.worldScalingFactor);const t=r.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent,this.pointer.scaling.setAll(s.worldScalingFactor)}if(this.inputSource.gripSpace&&this.grip){const r=e.getPose(this.inputSource.gripSpace,t);if(r){const e=r.transform.position,t=r.transform.orientation;this.grip.position.set(e.x,e.y,e.z).scaleInPlace(s.worldScalingFactor),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent,this.grip.scaling.setAll(s.worldScalingFactor)}this.motionController&&this.motionController.updateFromXRFrame(e)}}class Yf{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new g,this.onControllerRemovedObservable=new g,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add((()=>{this._addAndRemoveControllers([],this.controllers.map((e=>e.inputSource)))})),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add((e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)})),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add((e=>{this.controllers.forEach((t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera,this.xrSessionManager)}))})),this._options.customControllersRepositoryURL&&(Wf.BaseRepositoryUrl=this._options.customControllersRepositoryURL),Wf.UseOnlineRepository=!this._options.disableOnlineControllerRepository,Wf.UseOnlineRepository)try{Wf.UpdateProfilesList().catch((()=>{Wf.UseOnlineRepository=!1}))}catch(e){Wf.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map((e=>e.inputSource));for(const t of e)if(-1===i.indexOf(t)){const e=new Xf(this.xrSessionManager.scene,t,{...this._options.controllerOptions||{},forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation});this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}const s=[],r=[];this.controllers.forEach((e=>{-1===t.indexOf(e.inputSource)?s.push(e):r.push(e)})),this.controllers=s,r.forEach((e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()}))}dispose(){this.controllers.forEach((e=>{e.dispose()})),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),Wf.ClearControllerCache()}}class jf extends _o{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;const{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(this._options.forceGripIfAvailable&&e.grip?e.grip:e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new ao(new w,new w),disabledByNearInteraction:!1,id:jf._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":case"transient-pointer":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new w,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new Y(.9,.9,.9),this.laserPointerDefaultColor=new Y(.7,.7,.7),this.selectionMeshDefaultColor=new Y(.8,.8,.8),this.selectionMeshPickedColor=new Y(.3,.3,1),this._identityMatrix=B.Identity(),this._screenCoordinatesRef=w.Zero(),this._viewportRef=new nr(0,0,0,0),this._scene=this._xrSessionManager.scene,void 0===this._options.lookAndPickMode&&(this._scene.getEngine()._badDesktopOS||this._scene.getEngine()._badOS)&&(this._options.lookAndPickMode=!0),this._options.lookAndPickMode&&(this._options.enablePointerSelectionOnAllControllers=!0,this.displayLaserPointer=!1)}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController,!0),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)}),!0),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){const e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new ao(new w,new w),disabledByNearInteraction:!1,id:jf._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i{const t=this._controllers[e];if(this._options.lookAndPickMode&&"transient-pointer"!==t.xrController?.inputSource.targetRayMode)return;if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||t.disabledByNearInteraction)return t.selectionMesh.isVisible=!1,t.laserPointer.isVisible=!1,void(t.pick=null);let i;if(t.laserPointer.isVisible=this.displayLaserPointer,t.xrController)i=this._options.forceGripIfAvailable&&t.xrController.grip?t.xrController.grip.position:t.xrController.pointer.position,t.xrController.getWorldPointerRayToRef(t.tmpRay,this._options.forceGripIfAvailable);else{if(!t.webXRCamera)return;i=t.webXRCamera.position,t.webXRCamera.getForwardRayToRef(t.tmpRay)}if(this._options.maxPointerDistance&&(t.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&i){const e=this._xrSessionManager.scene,s=this._options.xrInput.xrCamera;s&&(s.viewport.toGlobalToRef(e.getEngine().getRenderWidth()/s.rigCameras.length,e.getEngine().getRenderHeight(),this._viewportRef),w.ProjectToRef(i,this._identityMatrix,s.getTransformationMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||this._screenCoordinatesRef.x===1/0||this._screenCoordinatesRef.y===1/0||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,t.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let s=null;this._utilityLayerScene&&(s=this._utilityLayerScene.pickWithRay(t.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const r=this._scene.pickWithRay(t.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);s&&s.hit?r&&r.hit?s.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit)if(this._pickingMoved(r,t.pick))a&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,l)),a=!1,o=0;else if(o>i/10&&(n.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,l),a=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),n.isVisible=!1;else{const e=1-o/i;n.scaling.set(e,e,e)}else a=!1,o=0;this._scene.simulatePointerMove(t.pick,l),r=t.pick}})),void 0!==this._options.renderingGroupId&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce((()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&a&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),n.dispose()}))}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const s={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),!t.pick||this._options.disablePointerUpOnTouchOut&&i||(i?this._scene.simulatePointerMove(t.pick,s):(this._scene.simulatePointerDown(t.pick,s),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,s)))})),e.onDisposeObservable.addOnce((()=>{this._augmentPointerInit(s,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame((()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,s),t.finalPointerUpTriggered=!0)}))}))}_attachTrackedPointerRayMode(e){const t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);const i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))})),e.inputSource.gamepad){const s=s=>{this._options.overrideButtonId&&(t.selectionComponent=s.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=s.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((s=>{if(s.changes.pressed){const r=s.changes.pressed.current;if(t.pick)(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),r?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor));else if(r&&!this._options.enablePointerSelectionOnAllControllers&&!this._options.disableSwitchOnClick){const t=this._controllers[this._attachedController];t&&t.pointerDownTriggered&&!t.finalPointerUpTriggered&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerUp(new qi,{pointerId:t.id,pointerType:"xr"}),t.finalPointerUpTriggered=!0),this._attachedController=e.uniqueId}}}))};e.motionController?s(e.motionController):e.onMotionControllerInitObservable.add(s)}else{const e=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)}))},s=e=>{this._xrSessionManager.onXRFrameObservable.addOnce((()=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)}))};t.eventListeners={selectend:s,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",s)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(w.Dot(e,t.direction)){const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),!t.finalPointerUpTriggered&&t.pointerDownTriggered){const e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame((()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new qi,e),t.finalPointerUpTriggered=!0}))}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce((()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){Ii.Warn("controller already detached.")}}))}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Jh.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():Qh("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const s=new dh("laserPointerMat",t);s.emissiveColor=this.laserPointerDefaultColor,s.alpha=.7,i.material=s,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const r=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():Oh("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);r.bakeCurrentTransformIntoVertices(),r.isPickable=!1,r.isVisible=!1;const n=new dh("targetMat",t);return n.specularColor=Y.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,r.material=n,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:r}}_pickingMoved(e,t){if(!e.hit||!t.hit)return!0;if(!(e.pickedMesh&&e.pickedPoint&&t.pickedMesh&&t.pickedPoint))return!0;if(e.pickedMesh!==t.pickedMesh)return!0;e.pickedPoint?.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const i=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance;return this._tmpVectorForPickCompare.length()>i}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}}var $f,Kf,qf;jf._IdCounter=200,jf.Name=po.POINTER_SELECTION,jf.Version=1,fo.AddWebXRFeature(jf.Name,((e,t)=>()=>new jf(e,t)),jf.Version,!0),vr.prototype._projectOnTrianglesToRef=function(e,t,i,s,r,n){const o=U.Vector3[0],a=U.Vector3[1];let l=1/0;for(let n=this.indexStart;n{if(this._controllers[e.uniqueId])return;const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s}=this._generateNewTouchPointMesh(),r=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s,currentAnimationState:$f.DEHYDRATED,grabRay:new ao(new w,new w),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,downTriggered:!1,id:Qf._IdCounter++,pickedPointVisualCue:r},this._controllers[e.uniqueId]._worldScaleObserver=this._controllers[e.uniqueId]._worldScaleObserver||this._xrSessionManager.onWorldScaleFactorChangedObservable.add((t=>{if(t.newScaleFactor!==t.previousScaleFactor){this._controllers[e.uniqueId].touchCollisionMesh.dispose(),this._controllers[e.uniqueId].pickedPointVisualCue.dispose();const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:s}=this._generateNewTouchPointMesh();this._controllers[e.uniqueId].touchCollisionMesh=t,this._controllers[e.uniqueId].touchCollisionMeshFunction=i,this._controllers[e.uniqueId].hydrateCollisionMeshFunction=s,this._controllers[e.uniqueId].pickedPointVisualCue=this._generateVisualCue()}})),this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new Y(.8,.8,.8),this.selectionMeshPickedColor=new Y(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=Kf.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;ie.currentAnimationState)switch(e.currentAnimationState){case $f.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===$f.HOVER)break;case $f.HOVER:if(e.touchCollisionMeshFunction(!0),t===$f.TOUCH)break}else switch(e.currentAnimationState){case $f.TOUCH:if(e.touchCollisionMeshFunction(!1),t===$f.HOVER)break;case $f.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===$f.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){const s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(U.Vector3[0]),s.grabRay.direction.copyFrom(U.Vector3[0]),this._options.nearInteractionControllerMode!==Kf.CENTERED_IN_FRONT||s.xrController?.inputSource.hand||(s.xrController.getWorldPointerRayToRef(this._tmpRay),s.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),s.grabRay.length=this._nearGrabLengthScale*this._hoverRadius*this._xrSessionManager.worldScalingFactor,s.touchCollisionMesh.position.copyFrom(s.grabRay.origin).scaleInPlace(this._xrSessionManager.worldScalingFactor)}_onXRFrame(e){Object.keys(this._controllers).forEach((t=>{const i=this._controllers[t],s=i.xrController?.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!i.xrController||!s&&(!this._options.nearInteractionControllerMode||!i.xrController.inputSource.gamepad))return void(i.pick=null);if(i.hoverInteraction=!1,i.nearInteraction=!1,!i.xrController)return;if(s){const i=s.get("index-finger-tip");if(i){const s=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(s&&s.transform){const e=this._scene.useRightHandedSystem?1:-1;U.Vector3[0].set(s.transform.position.x,s.transform.position.y,s.transform.position.z*e),U.Quaternion[0].set(s.transform.orientation.x,s.transform.orientation.y,s.transform.orientation.z*e,s.transform.orientation.w*e),this._processTouchPoint(t,U.Vector3[0],U.Quaternion[0])}}}else if(i.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==Kf.DISABLED){let e=i.xrController.pointer;i.xrController.grip&&this._options.nearInteractionControllerMode===Kf.CENTERED_ON_CONTROLLER&&(e=i.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}const r=(e,t)=>{let i=null;return i=t&&t.hit?e&&e.hit?t.distance{let t=new qi,i=!1;const s=e&&e.pickedPoint&&e.hit;return e?.pickedPoint&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),s&&!i&&(t=e),t};if(!i.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._utilityLayerScene,(e=>this._nearInteractionPredicate(e))));const o=r(this._pickWithSphere(i,this._hoverRadius*this._xrSessionManager.worldScalingFactor,this._scene,(e=>this._nearInteractionPredicate(e))),t);if(o&&o.hit&&(e=n(o),e.hit&&(i.hoverInteraction=!0)),i.hoverInteraction){let t=null;const o=(s?this._pickRadius:this._controllerPickRadius)*this._xrSessionManager.worldScalingFactor;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(i,o,this._utilityLayerScene,(e=>this._nearPickPredicate(e))));const a=n(r(this._pickWithSphere(i,o,this._scene,(e=>this._nearPickPredicate(e))),t));a.hit&&(e=a,i.nearInteraction=!0)}i.stalePick=i.pick,i.pick=e,i.pick&&i.pick.pickedPoint&&i.pick.hit?(i.meshUnderPointer=i.pick.pickedMesh,i.pickedPointVisualCue.position.copyFrom(i.pick.pickedPoint),i.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!0)):(i.meshUnderPointer=null,i.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(i.id,!1))}let o=$f.DEHYDRATED;i.grabInteraction||i.nearInteraction?o=$f.TOUCH:i.hoverInteraction&&(o=$f.HOVER),this._handleTransitionAnimation(i,o)}))}get _utilityLayerScene(){return this._options.customUtilityLayerScene||Jh.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Jh.DefaultUtilityLayer.utilityLayerScene:this._scene,t=nc("nearInteraction",{diameter:.0105*this._xrSessionManager.worldScalingFactor},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=L.Identity();const i=new dh("targetMat",e);return i.specularColor=Y.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer,t.downTriggered=!0):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.downTriggered=!1,t.nearInteractionTargetMesh=null))}));const s=s=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),s&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0):!s&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.downTriggered=!1,t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!s||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const i=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;s(t)}})):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;s(t)}})))};e.motionController?i(e.motionController):e.onMotionControllerInitObservable.add(i)}else{const e=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i),t.downTriggered=!0)},s=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0,t.downTriggered=!1)};t.eventListeners={selectend:s,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",s)}}_detachController(e){const t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach((e=>{const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame((()=>{if(!t.downTriggered)return;const e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new qi,e)})),t._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(t._worldScaleObserver),delete this._controllers[e],this._attachedController===e)){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){const e=this._xrSessionManager.worldScalingFactor,t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Jh.DefaultUtilityLayer.utilityLayerScene:this._scene,i=nc("PickSphere",{diameter:1*e},t);if(i.isVisible=!1,this._options.motionControllerOrbMaterial)i.material=this._options.motionControllerOrbMaterial;else{let e;e=this._options.motionControllerTouchMaterialSnippetUrl?xa.ParseFromFileAsync("motionControllerTouchMaterial",this._options.motionControllerTouchMaterialSnippetUrl,t):xa.ParseFromSnippetAsync("8RUNKL#3",t),e.then((e=>{i.material=e})).catch((e=>{J.Warn(`Error creating touch material in WebXRNearInteraction: ${e}`)}))}const s=new Qs;s.setEasingMode(Ks.EASINGMODE_EASEINOUT);const r=new w(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius).scaleInPlace(e),n=this._controllerPickRadius*(4/3),o=new w(n,n,n).scaleInPlace(e),a=this._controllerPickRadius*(7/6),l=new w(a,a,a).scaleInPlace(e),h=.8*this._controllerPickRadius,c=new w(h,h,h).scaleInPlace(e),u=1.5*this._controllerPickRadius,d=[{frame:0,value:r},{frame:10,value:new w(u,u,u).scaleInPlace(e)},{frame:18,value:o}],p=[{frame:0,value:o},{frame:10,value:c},{frame:18,value:r}],f=[{frame:0,value:w.ZeroReadOnly},{frame:12,value:l},{frame:15,value:r}],_=[{frame:0,value:r},{frame:10,value:w.ZeroReadOnly},{frame:15,value:w.ZeroReadOnly}],m=new Ge("touch","scaling",60,Ge.ANIMATIONTYPE_VECTOR3,Ge.ANIMATIONLOOPMODE_CONSTANT),g=new Ge("release","scaling",60,Ge.ANIMATIONTYPE_VECTOR3,Ge.ANIMATIONLOOPMODE_CONSTANT),v=new Ge("hydrate","scaling",60,Ge.ANIMATIONTYPE_VECTOR3,Ge.ANIMATIONLOOPMODE_CONSTANT),x=new Ge("dehydrate","scaling",60,Ge.ANIMATIONTYPE_VECTOR3,Ge.ANIMATIONLOOPMODE_CONSTANT);return m.setEasingFunction(s),g.setEasingFunction(s),v.setEasingFunction(s),x.setEasingFunction(s),m.setKeys(d),g.setKeys(p),v.setKeys(f),x.setKeys(_),{touchCollisionMesh:i,touchCollisionMeshFunction:e=>{const s=e?m:g;t.beginDirectAnimation(i,[s],0,18,!1,1)},hydrateCollisionMeshFunction:e=>{const s=e?v:x;e&&(i.isVisible=!0),t.beginDirectAnimation(i,[s],0,15,!1,1,(()=>{e||(i.isVisible=!1)}))}}}_pickWithSphere(e,t,i,s){const r=new qi;if(r.distance=1/0,e.touchCollisionMesh&&e.xrController){const n=e.touchCollisionMesh.position,o=hr.CreateFromCenterAndRadius(n,t);for(let t=0;tc&&(h=0,a.copyFrom(t.center)),-1!==h&&h()=>new Qf(e,t)),Qf.Version,!0);class Zf{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class Jf{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new g,this._onSessionGranted=e=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw Ii.Warn("WebXR can only be served over HTTPS"),new Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";const e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor";let s=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+("undefined"==typeof SVGSVGElement?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";s+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const r=document.createElement("style");r.appendChild(document.createTextNode(s)),document.getElementsByTagName("head")[0].appendChild(r);const n=document.createElement("button");n.className="babylonVRicon",n.title=`${e} - ${i}`,this._buttons.push(new Zf(n,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",n.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}const i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce((()=>{this.dispose()})))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;const i=this._buttons.map((t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode)));e.onStateChangedObservable.add((e=>{e==Ch.NOT_IN_XR&&this._updateButtons(null)})),(await Promise.all(i)).forEach(((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):Ii.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)}))}static async CreateAsync(e,t,i){const s=new Jf(e,i);return await s.setHelperAsync(t,i.renderTarget||void 0),s}async _enterXRWithButtonIndex(e=0){if(this._helper.state==Ch.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==Ch.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(t){this._updateButtons(null);const i=this._buttons[e].element,s=i.title;i.title="Error entering XR session : "+s,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t)}}dispose(){const e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach((e=>{e.update(this._activeButton)})),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}function e_(e){let t=0;const i=Date.now();e.observableParameters=e.observableParameters??{};const s=e.contextObservable.add((r=>{const n=Date.now();t=n-i;const o={startTime:i,currentTime:n,deltaTime:t,completeRate:t/e.timeout,payload:r};e.onTick&&e.onTick(o),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(o)),t>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(o))}),e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return s}!function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(qf||(qf={}));class t_{constructor(e){this.onEachCountObservable=new g,this.onTimerAbortedObservable=new g,this.onTimerEndedObservable=new g,this.onStateChangedObservable=new g,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{const t=Date.now();this._timer=t-this._startTime;const i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},s=this._breakOnNextTick||this._breakCondition(i);s||this._timer>=this._timeToEnd?this._stop(i,s):this.onEachCountObservable.notifyObservers(i)},this._setState(qf.INIT),this._contextObservable=e.contextObservable,this._observableParameters=e.observableParameters??{},this._breakCondition=e.breakCondition??(()=>!1),this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}set breakCondition(e){this._breakCondition=e}clearObservables(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()}start(e=this._timeToEnd){if(this._state===qf.STARTED)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(qf.STARTED)}stop(){this._state===qf.STARTED&&(this._breakOnNextTick=!0)}dispose(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()}_setState(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)}_stop(e,t=!1){this._contextObservable.remove(this._observer),this._setState(qf.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class i_ extends _o{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){const t=this._options.teleportationTargetMesh.getChildMeshes(!1,(e=>"rotationCone"===e.name));t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new j(1,1,1,1),this._tmpRay=new ao(new w,new w),this._tmpVector=new w,this._tmpQuaternion=new L,this._worldScaleObserver=null,this.skipNextTeleportation=!1,this.backwardsMovementEnabled=!0,this.backwardsTeleportationDistance=.7,this.parabolicCheckRadius=5,this.parabolicRayEnabled=!0,this.straightRayEnabled=!0,this.rotationAngle=Math.PI/8,this.onTargetMeshPositionUpdatedObservable=new g,this.teleportationEnabled=!0,this._rotationEnabled=!0,this.onBeforeCameraTeleportRotation=new g,this.onAfterCameraTeleportRotation=new g,this._attachController=e=>{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1,initialHit:!1,mainComponentUsed:!1}};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController){const i=e.motionController.getComponentOfType(Bf.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(Bf.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){const i=e.motionController.getMainComponent();if(!i)return;t.teleportationState.mainComponentUsed=!0,t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add((()=>{if(!this.teleportationEnabled)return;const s=()=>{t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,e_({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};i.changes.pressed&&(i.changes.pressed.current?this._options.timeToTeleportStart?e_({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{i.pressed&&s()}}):s():(t.teleportationState.forward=!1,this._currentTeleportationControllerId=""))}))}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add((i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,L.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);const e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,(e=>-1!==this._floorMeshes.indexOf(e)));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout((()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))})):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;const e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this.onBeforeCameraTeleportRotation.notifyObservers(e),L.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),t.teleportationState.forward&&this._teleportForward(e.uniqueId))}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}else{t.teleportationState.mainComponentUsed=!0;let i=!1;const s=()=>{this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.forward=!0,t.teleportationState.initialHit=!1,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,e_({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})};this._xrSessionManager.scene.onPointerObservable.add((e=>{e.type===ss.POINTERDOWN?(i=!1,this._options.timeToTeleportStart?e_({timeout:this._options.timeToTeleportStart,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&s()},breakCondition:()=>!!i&&(i=!1,!0)}):s()):e.type===ss.POINTERUP&&(i=!0,t.teleportationState.forward=!1,this._currentTeleportationControllerId="")}))}},this._colorArray=Array(24).fill(this._cachedColor4White),this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new j(1,0,0,.75),this._setTargetMeshVisibility(!1),this.onBeforeCameraTeleport=t.xrInput.xrCamera.onBeforeCameraTeleport,this.onAfterCameraTeleport=t.xrInput.xrCamera.onAfterCameraTeleport,this.parabolicCheckRadius*=this._xrSessionManager.worldScalingFactor,this._worldScaleObserver=e.onWorldScaleFactorChangedObservable.add((e=>{this.parabolicCheckRadius=this.parabolicCheckRadius/e.previousScaleFactor*e.newScaleFactor,this._options.teleportationTargetMesh?.scaling.scaleInPlace(e.newScaleFactor/e.previousScaleFactor)}))}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return!!super.attach()&&(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0),this._worldScaleObserver&&this._xrSessionManager.onWorldScaleFactorChangedObservable.remove(this._worldScaleObserver)}removeFloorMesh(e){const t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];const t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){const t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(-1===t)for(let i=0;i{if(this._options.blockerMeshesPredicate&&this._options.blockerMeshesPredicate(e))return!0;if(this._options.blockAllPickableMeshes&&e.isPickable)return!0;if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;const t=this._floorMeshes.indexOf(e);return-1!==t&&this._floorMeshes[t].absolutePosition.y!(!this._options.blockerMeshesPredicate||!this._options.blockerMeshesPredicate(e))||!(!this._options.blockAllPickableMeshes||!e.isPickable)||!(!this._options.pickBlockerMeshes||-1===this._options.pickBlockerMeshes.indexOf(e))||-1!==this._floorMeshes.indexOf(e))),l=a&&a.pickedMesh&&-1!==this._floorMeshes.indexOf(a.pickedMesh);if(a&&a.pickedMesh&&!l)return e.teleportationState.mainComponentUsed&&!e.teleportationState.initialHit?void(e.teleportationState.forward=!1):(e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1,!1,r),void this._showParabolicPath(a));a&&a.pickedPoint&&(e.teleportationState.initialHit=!0,e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(a),this._setTargetMeshVisibility(!0,!1,r),this._showParabolicPath(a))}this._setTargetMeshVisibility(t,!1,r)}else this._setTargetMeshVisibility(!1,!1,!0)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1,!1,!0)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Jh.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=Mh("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const i=512,s=new ph("teleportationPlaneDynamicTexture",i,e,!0);s.hasAlpha=!0;const r=s.getContext(),n=i/2,o=i/2,a=200;r.beginPath(),r.arc(n,o,a,0,2*Math.PI,!1),r.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",r.fill(),r.lineWidth=10,r.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",r.stroke(),r.closePath(),s.update();const l=new dh("teleportationPlaneMaterial",e);l.diffuseTexture=s,t.material=l}const i=Oh("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const t=new Ge("animationInnerCircle","position.y",30,Ge.ANIMATIONTYPE_FLOAT,Ge.ANIMATIONLOOPMODE_CYCLE),s=[];s.push({frame:0,value:0}),s.push({frame:30,value:.4}),s.push({frame:60,value:0}),t.setKeys(s);const r=new Zs;r.setEasingMode(Ks.EASINGMODE_EASEINOUT),t.setEasingFunction(r),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}const s=Qh("rotationCone",{diameterTop:0,tessellation:4},e);if(s.isPickable=!1,s.scaling.set(.5,.12,.2),s.rotate(Gs.X,Math.PI/2),s.position.z=.6,s.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,s.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const t=new dh("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new Y(.3,.3,1):t.diffuseColor=new Y(.3,.3,1),t.alpha=.9,i.material=t,s.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._options.teleportationTargetMesh.scaling.setAll(this._xrSessionManager.worldScalingFactor),this._setTargetMeshVisibility(!1)}_detachController(e){const t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,s=Number.MAX_VALUE;if(this._snapToPositions.length){const r=t*t;this._snapToPositions.forEach((t=>{const n=w.DistanceSquared(t,e);n<=r&&n{t.isVisible=e})),e?this._selectionFeature&&i&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&i&&this._selectionFeature.attach()))}_disposeBezierCurve(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||Jh.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],s=$s.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),r=i.teleportationState.blocked?this._blockedRayColor:void 0,n=this._colorArray.fill(r||this._cachedColor4White),o=s.getPoints();o.shift(),o.shift(),this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(s.getPoints(),e):this._quadraticBezierCurve=Tc("teleportation path line",{points:o,instance:this._quadraticBezierCurve,updatable:!0,colors:n},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){const t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint))if(this.skipNextTeleportation)this.skipNextTeleportation=!1;else if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){const e=this._options.xrInput.xrCamera.realWorldHeight;this.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=e,L.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}i_.Name=po.TELEPORTATION,i_.Version=1,fo.AddWebXRFeature(i_.Name,((e,t)=>()=>new i_(e,t)),i_.Version,!0);class s_{constructor(){}static CreateAsync(e,t={}){const i=new s_;if(e.onDisposeObservable.addOnce((()=>{i.dispose()})),!t.disableDefaultUI){const s={renderTarget:i.renderTarget,...t.uiOptions||{}};t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?s.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:s.optionalFeatures=t.optionalFeatures),i.enterExitUI=new Jf(e,s)}return Lf.CreateAsync(e).then((e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new Yf(e.sessionManager,e.camera,{controllerOptions:{renderingGroupId:t.renderingGroupId},...t.inputOptions||{}}),!t.disablePointerSelection){const e={...t.pointerSelectionOptions,xrInput:i.input,renderingGroupId:t.renderingGroupId};i.pointerSelection=i.baseExperience.featuresManager.enableFeature(jf.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(i_.Name,t.useStablePlugins?"stable":"latest",{floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId,...t.teleportationOptions}),i.teleportation.setSelectionFeature(i.pointerSelection))}return t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(Qf.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0,...t.nearInteractionOptions})),t.disableHandTracking||i.baseExperience.featuresManager.enableFeature(Ia.Name,t.useStablePlugins?"stable":"latest",{xrInput:i.input,...t.handSupportOptions},void 0,!1),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)})).then((()=>i)).catch((e=>(J.Error("Error initializing XR"),J.Error(e),i)))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}function r_(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}ks.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;ee.isVisible&&e.isEnabled())),s=t.max.subtract(t.min),r=t.min.add(s.scale(.5));let n,o=1.5*s.length();if(isFinite(o)||(o=1,r.copyFromFloats(0,0,0)),e){const e=new gl("default camera",-Math.PI/2,Math.PI/2,o,r,this);e.lowerRadiusLimit=.01*o,e.wheelPrecision=100/o,n=e}else{const e=new _l("default camera",new w(r.x,r.y,-o),this);e.setTarget(r),n=e}n.minZ=.01*o,n.maxZ=1e3*o,n.speed=.2*o,this.activeCamera=n,i&&n.attachControl()}},ks.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},ks.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,s=0,r=!0){if(!e)return J.Warn("Can not create default skybox without environment texture."),null;r&&e&&(this.environmentTexture=e);const n=sc("hdrSkyBox",{size:i},this);if(t){const t=new yf("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Zn.SKYBOX_MODE),t.microSurface=1-s,t.disableLighting=!0,t.twoSidedLighting=!0,n.material=t}else{const t=new dh("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Zn.SKYBOX_MODE),t.disableLighting=!0,n.material=t}return n.isPickable=!1,n.infiniteDistance=!0,n.ignoreCameraMaxZ=!0,n},ks.prototype.createDefaultEnvironment=function(e){return nf?new nf(e,this):null},ks.prototype.createDefaultVRExperience=function(e={}){return new Fh(this,e)},ks.prototype.createDefaultXRExperienceAsync=function(e={}){return s_.CreateAsync(this,e).then((e=>e))};class n_ extends Zn{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new g),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(e?.message):J.Error(e?.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch((e=>{if("NotAllowedError"===e?.name){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers())return void this._onUserActionRequestedObservable.notifyObservers(this);if(!this.video.muted)return J.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,void this.video.play().catch((e=>{this._processError(e)}))}this._processError(e)}))}constructor(e,t,i,s=!1,r=!1,n=Zn.TRILINEAR_SAMPLINGMODE,o={},a,l=5){super(null,i,!s,r),this._externalTexture=null,this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||Ii.IsExponentOfTwo(this.video.videoWidth)&&Ii.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=Zn.WRAP_ADDRESSMODE,this.wrapV=Zn.WRAP_ADDRESSMODE):(this.wrapU=Zn.CLAMP_ADDRESSMODE,this.wrapV=Zn.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=this._format??5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(null!=this._texture){if(!this._displayingPosterTexture)return;this._displayingPosterTexture=!1}if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{const e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture)return;if(this.video.readyState=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&u?u&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return Ii.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return"string"==typeof e?(Ii.SetCorsBehavior(e,t),t.src=e):(Ii.SetCorsBehavior(e[0],t),e.forEach((e=>{const i=document.createElement("source");i.src=e,t.appendChild(i)}))),this.onDisposeObservable.addOnce((()=>{r_(t)})),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))}get externalTexture(){return this._externalTexture}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new n_(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("loadeddata",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),this._externalTexture?.dispose()}static CreateFromStreamAsync(e,t,i,s=!0){const r=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(r),r.style.transform="scale(0.0001, 0.0001)",r.style.opacity="0",r.style.position="fixed",r.style.bottom="0px",r.style.right="0px"),r.setAttribute("autoplay",""),r.setAttribute("muted","true"),r.setAttribute("playsinline",""),r.muted=!0,r.isNative||(void 0!==r.mozSrcObject?r.mozSrcObject=t:"object"==typeof r.srcObject?r.srcObject=t:r.src=window.URL&&window.URL.createObjectURL(t)),new Promise((t=>{const i=()=>{const n=new n_("video",r,e,!0,s,void 0,void 0,void 0,4);e.getEngine()._badOS&&n.onDisposeObservable.addOnce((()=>{r.remove()})),n.onDisposeObservable.addOnce((()=>{r_(r)})),t(n),r.removeEventListener("playing",i)};r.addEventListener("playing",i),r.play()}))}static async CreateFromWebCamAsync(e,t,i=!1,s=!0){if(navigator.mediaDevices){const r=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,r,t,s);return n.onDisposeObservable.addOnce((()=>{r.getTracks().forEach((e=>{e.stop()}))})),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,s=!1,r=!0){this.CreateFromWebCamAsync(e,i,s,r).then((function(e){t&&t(e)})).catch((function(e){J.Error(e.name)}))}}ae([pe("settings")],n_.prototype,"_settings",void 0),ae([pe("src")],n_.prototype,"_currentSrc",void 0),ae([pe()],n_.prototype,"isVideo",void 0),Zn._CreateVideoTexture=(e,t,i,s=!1,r=!1,n=Zn.TRILINEAR_SAMPLINGMODE,o={},a,l=5)=>new n_(e,t,i,s,r,n,o,a,l),u("BABYLON.VideoTexture",n_);class o_ extends of{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const s={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},r=new n_((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,Zn.TRILINEAR_SAMPLINGMODE,s);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add((e=>{e.pickInfo?.pickedMesh===this.mesh&&this._texture.video.play()}),ss.POINTERDOWN)),this._textureObserver=r.onLoadObservable.add((()=>{this.onLoadObservable.notifyObservers()})),r}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}o_.MODE_MONOSCOPIC=of.MODE_MONOSCOPIC,o_.MODE_TOPBOTTOM=of.MODE_TOPBOTTOM,o_.MODE_SIDEBYSIDE=of.MODE_SIDEBYSIDE;Ft.ShadersStore.glowMapGenerationPixelShader="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;uniform float glowIntensity;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;varying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;uniform mat4 diffuseMatrix;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;uniform mat4 opacityMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;uniform mat4 emissiveMatrix;\n#endif\n#ifdef VERTEXALPHA\nattribute vec4 color;varying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef CUBEMAP\nvPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*worldPos;gl_Position=vPosition;\n#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef OPACITYUV2\nvUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef VERTEXALPHA\nvColor=color;\n#endif\n#include\n}";class a_{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||0===t)&&e.subMeshes)for(let t=0;t{let r;this.onBeforeRenderMainTextureObservable.notifyObservers(this);const n=this._scene.getEngine();if(s.length){for(n.setColorWrite(!1),r=0;r{e.clear(this.neutralColor,!0,!0,!0)})),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e})),this._mainTexture.onAfterUnbindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=e}))}}_addCustomEffectDefines(e){}_isReady(e,t,i){const s=this._scene.getEngine(),r=e.getMesh(),n=r._internalAbstractMeshDataInfo._materialForRenderPass?.[s.currentRenderPassId];if(n)return n.isReadyForSubMesh(r,e,t);const o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);const a=[],l=[Ki.PositionKind];let h=!1,c=!1;if(o){const e=o.needAlphaTesting(),t=o.getAlphaTestTexture(),i=t&&t.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);t&&(e||i)&&(a.push("#define DIFFUSE"),r.isVerticesDataPresent(Ki.UV2Kind)&&1===t.coordinatesIndex?(a.push("#define DIFFUSEUV2"),c=!0):r.isVerticesDataPresent(Ki.UVKind)&&(a.push("#define DIFFUSEUV1"),h=!0),e&&(a.push("#define ALPHATEST"),a.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||a.push("#define DIFFUSE_ISLINEAR"));const s=o.opacityTexture;s&&(a.push("#define OPACITY"),r.isVerticesDataPresent(Ki.UV2Kind)&&1===s.coordinatesIndex?(a.push("#define OPACITYUV2"),c=!0):r.isVerticesDataPresent(Ki.UVKind)&&(a.push("#define OPACITYUV1"),h=!0))}i&&(a.push("#define EMISSIVE"),r.isVerticesDataPresent(Ki.UV2Kind)&&1===i.coordinatesIndex?(a.push("#define EMISSIVEUV2"),c=!0):r.isVerticesDataPresent(Ki.UVKind)&&(a.push("#define EMISSIVEUV1"),h=!0),i.gammaSpace||a.push("#define EMISSIVE_ISLINEAR")),r.useVertexColors&&r.isVerticesDataPresent(Ki.ColorKind)&&r.hasVertexAlpha&&o.transparencyMode!==Dn.MATERIAL_OPAQUE&&(l.push(Ki.ColorKind),a.push("#define VERTEXALPHA")),h&&(l.push(Ki.UVKind),a.push("#define UV1")),c&&(l.push(Ki.UV2Kind),a.push("#define UV2"));const u=new Yo;if(r.useBones&&r.computeBonesUsingShaders){l.push(Ki.MatricesIndicesKind),l.push(Ki.MatricesWeightsKind),r.numBoneInfluencers>4&&(l.push(Ki.MatricesIndicesExtraKind),l.push(Ki.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers);const e=r.skeleton;e&&e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),r.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,r)}else a.push("#define NUM_BONE_INFLUENCERS 0");const d=r.morphTargetManager;let p=0;d&&(p=d.numMaxInfluencers||d.numInfluencers,p>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+p),d.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),tn(l,r,p))),t&&(a.push("#define INSTANCES"),rn(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),$r(o,this._scene,a),this._addCustomEffectDefines(a);const f=e._getDrawWrapper(void 0,!0),_=f.defines,m=a.join("\n");if(_!==m){const e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];jr(e),f.setEffect(this._engine.createEffect("glowMapGeneration",l,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],m,u,void 0,void 0,{maxSimultaneousMorphTargets:p}),m)}return f.effect.isReady()}render(){for(let e=0;eh.setMatrix("world",t)))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(s)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[Ki.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return Ii.Instantiate(e.customType).Parse(e,t,i)}}a_._SceneComponentInitialization=e=>{throw ye("EffectLayerSceneComponent")},ae([pe()],a_.prototype,"name",void 0),ae([Te()],a_.prototype,"neutralColor",void 0),ae([pe()],a_.prototype,"isEnabled",void 0),ae([ue(11,void 0)],a_.prototype,"camera",null),ae([pe()],a_.prototype,"renderingGroupId",null),ae([pe()],a_.prototype,"disableBoundingBoxesFromEffectLayer",void 0),p.AddParser(ts.NAME_EFFECTLAYER,((e,t,i,s)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let r=0;r{this.scene.addEffectLayer(e)}))}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach((e=>{this.scene.removeEffectLayer(e),t&&e.dispose()}))}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,s=this.scene.effectLayers;for(const r of s){if(!r.hasMesh(e))continue;const s=r._mainTexture;this._engine.currentRenderPassId=s.renderPassId;for(const s of e.subMeshes)if(!r.isReady(s,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const s of i)if(s.shouldRender()&&(!s.camera||s.camera.cameraRigMode===or.RIG_MODE_NONE&&e===s.camera||s.camera.cameraRigMode!==or.RIG_MODE_NONE&&s.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||s.needStencil();const e=s._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i{let t=e._getComponent(ts.NAME_EFFECTLAYER);t||(t=new l_(e),e._addComponent(t))};Ft.ShadersStore.glowMapMergePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);baseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.glowMapMergeVertexShader="attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}",p.prototype.getGlowLayerByName=function(e){for(let t=0;t{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess1=new Jp("GlowLayerVBP1",new N(0,1),n,{width:e,height:t},null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new Jp("GlowLayerHBP2",new N(1,0),n,{width:s,height:r},null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=s,this._horizontalBlurPostprocess2.height=r,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._blurTexture1)})),this._verticalBlurPostprocess2=new Jp("GlowLayerVBP2",new N(0,1),n,{width:s,height:r},null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add((()=>{const e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);const t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(t??e,!0)}})),this._postProcesses.map((e=>{e.autoClear=!1}))}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s)return!1;const r=i.emissiveTexture;return super._isReady(e,t,r)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(Dn.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){let s=1;this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector?this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color):i.emissiveColor?(s*=i.emissiveIntensity??1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){const e=Pe.Serialize(this);let t;if(e.customType="BABYLON.GlowLayer",e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew h_(e.name,t,e.options)),e,t,i);let r;for(r=0;r{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)}))}}class u_ extends a_{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new g,this.onAfterBlurObservable=new g,this._instanceGlowingMeshStencilReference=u_.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=u_.NeutralColor,this._engine.isStencilEnable||J.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,...i},this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return u_.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[Ki.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?Ri(e,this._maxSize):e,t=this._engine.needPOTTextures?Ri(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new da("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=Zn.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=Zn.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(Zn.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new Ml("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._horizontalBlurPostprocess=new c_("HighlightLayerHBP",new N(1,0),this._options.blurHorizontalSize,1,null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._verticalBlurPostprocess=new c_("HighlightLayerVBP",new N(0,1),this._options.blurVerticalSize,1,null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new Jp("HighlightLayerHBP",new N(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess=new Jp("HighlightLayerVBP",new N(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add((()=>{this.onBeforeBlurObservable.notifyObservers(this);const e=this._blurTexture.renderTarget;e&&(this._scene.postProcessManager.directRender(this._postProcesses,e,!0),this._engine.unBindFramebuffer(e,!0)),this.onAfterBlurObservable.notifyObservers(this)})),this._postProcesses.map((e=>{e.autoClear=!1}))}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),s=e.getRenderingMesh();if(!i||!s||!this._meshes)return!1;let r=null;const n=this._meshes[s.uniqueId];return n&&n.glowEmissiveOnly&&i&&(r=i.emissiveTexture),super._isReady(e,t,r)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);const i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(Dn.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(Dn.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return!!super.shouldRender()&&!!this._meshes}_shouldRenderMesh(e){return!(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]||!super.hasMesh(e))}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){const s=this._meshes[e.uniqueId];s?this._emissiveTextureAndColor.color.set(s.color.r,s.color.g,s.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),s&&s.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(this._excludedMeshes&&!this._excludedMeshes[e.uniqueId]){const t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add((e=>{t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)})),t.afterRender=e.onAfterRenderObservable.add((e=>{e.getEngine().setStencilBuffer(t.stencilState)})),this._excludedMeshes[e.uniqueId]=t}}removeExcludedMesh(e){if(!this._excludedMeshes)return;const t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!!this._meshes&&!!super.hasMesh(e)&&void 0!==this._meshes[e.uniqueId]&&null!==this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;const s=this._meshes[e.uniqueId];s?s.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add((e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))})),observerDefault:e.onAfterRenderObservable.add((e=>{this.isEnabled&&this._defaultStencilReference(e)})),glowEmissiveOnly:i},e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;const t=this._meshes[e.uniqueId];t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(const e in this._meshes)if(this._meshes[e]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes)for(const e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){const t=this._meshes[e];t&&this.removeMesh(t.mesh)}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(u_.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(const e in this._meshes){const t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(const e in this._excludedMeshes){const t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){const e=Pe.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(const t in this._meshes){const i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(const t in this._excludedMeshes){const i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){const s=Pe.Parse((()=>new u_(e.name,t,e.options)),e,t,i);let r;for(r=0;rthis._drawCameraPredicate(t,!0,!0,e.layerMask)))}_drawCameraForegroundWithPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!0,e.layerMask)))}_drawCameraForegroundWithoutPostProcessing(e){this._draw((t=>this._drawCameraPredicate(t,!1,!1,e.layerMask)))}_drawRenderTargetPredicate(e,t,i,s,r){return e.renderTargetTextures.length>0&&e.isBackground===t&&e.applyPostProcess===i&&e.renderTargetTextures.indexOf(r)>-1&&!!(e.layerMask&s)}_drawRenderTargetBackground(e){this._draw((t=>this._drawRenderTargetPredicate(t,!0,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!0,this.scene.activeCamera.layerMask,e)))}_drawRenderTargetForegroundWithoutPostProcessing(e){this._draw((t=>this._drawRenderTargetPredicate(t,!1,!1,this.scene.activeCamera.layerMask,e)))}addFromContainer(e){e.layers&&e.layers.forEach((e=>{this.scene.layers.push(e)}))}removeFromContainer(e,t=!1){e.layers&&e.layers.forEach((e=>{const i=this.scene.layers.indexOf(e);-1!==i&&this.scene.layers.splice(i,1),t&&e.dispose()}))}}Ft.ShadersStore.layerPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef LINEAR\nbaseColor.rgb=toGammaSpace(baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.layerVertexShader="attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class p_{set applyPostProcess(e){this._applyPostProcess=e}get applyPostProcess(){return this.isBackground||this._applyPostProcess}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}constructor(e,t,i,s,r){this.name=e,this._applyPostProcess=!0,this.scale=new N(1,1),this.offset=new N(0,0),this.alphaBlendingMode=2,this.layerMask=268435455,this.renderTargetTextures=[],this.renderOnlyInRenderTargetTextures=!1,this.isEnabled=!0,this._vertexBuffers={},this.onDisposeObservable=new g,this.onBeforeRenderObservable=new g,this.onAfterRenderObservable=new g,this.texture=t?new Zn(t,i,!0):null,this.isBackground=void 0===s||s,this.color=void 0===r?new j(1,1,1,1):r,this._scene=i||y.LastCreatedScene;let n=this._scene._getComponent(ts.NAME_LAYER);n||(n=new d_(this._scene),this._scene._addComponent(n)),this._scene.layers.push(this);const o=this._scene.getEngine();this._drawWrapper=new gr(o);const a=[];a.push(1,1),a.push(-1,1),a.push(-1,-1),a.push(1,-1);const l=new Ki(o,a,Ki.PositionKind,!1,!1,2);this._vertexBuffers[Ki.PositionKind]=l,this._createIndexBuffer()}_createIndexBuffer(){const e=this._scene.getEngine(),t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[Ki.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}isReady(){const e=this._scene.getEngine();let t="";this.alphaTest&&(t="#define ALPHATEST"),this.texture&&!this.texture.gammaSpace&&(t+="\n#define LINEAR"),this._previousDefines!==t&&(this._previousDefines=t,this._drawWrapper.effect=e.createEffect("layer",[Ki.PositionKind],["textureMatrix","color","scale","offset"],["textureSampler"],t));const i=this._drawWrapper.effect;return i?.isReady()&&this.texture?.isReady()}render(){if(!this.isEnabled)return;const e=this._scene.getEngine();if(!this.isReady())return;const t=this._drawWrapper.effect;this.onBeforeRenderObservable.notifyObservers(this),e.enableEffect(this._drawWrapper),e.setState(!1),t.setTexture("textureSampler",this.texture),t.setMatrix("textureMatrix",this.texture.getTextureMatrix()),t.setFloat4("color",this.color.r,this.color.g,this.color.b,this.color.a),t.setVector2("offset",this.offset),t.setVector2("scale",this.scale),e.bindBuffers(this._vertexBuffers,this._indexBuffer,t),this.alphaTest?e.drawElementsType(Dn.TriangleFillMode,0,6):(e.setAlphaMode(this.alphaBlendingMode),e.drawElementsType(Dn.TriangleFillMode,0,6),e.setAlphaMode(0)),this.onAfterRenderObservable.notifyObservers(this)}dispose(){const e=this._vertexBuffers[Ki.PositionKind];e&&(e.dispose(),this._vertexBuffers[Ki.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this.texture&&(this.texture.dispose(),this.texture=null),this.renderTargetTextures=[];const t=this._scene.layers.indexOf(this);this._scene.layers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderObservable.clear()}}class f_{static AddFlare(e,t,i,s,r){return new f_(e,t,i,s,r)}constructor(e,t,i,s,r){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new Y(1,1,1),this.texture=s?new Zn(s,r.getScene(),!0):null,this._system=r;const n=r.scene.getEngine();this._drawWrapper=new gr(n),this._drawWrapper.effect=n.createEffect("lensFlare",[Ki.PositionKind],["color","viewportMatrix"],["textureSampler"],""),r.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();const e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}Ft.ShadersStore.lensFlarePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.lensFlareVertexShader="attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";class __{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||y.LastCreatedScene,__._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&!!(e.layerMask&i.activeCamera.layerMask);const s=i.getEngine(),r=[];r.push(1,1),r.push(-1,1),r.push(-1,-1),r.push(1,-1),this._vertexBuffers[Ki.PositionKind]=new Ki(s,r,Ki.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=w.Project(t,B.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=w.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);const i=this._scene.useRightHandedSystem;return!!(t.z>0&&!i||t.z<0&&i)&&(this._positionX>e.x&&this._positionXe.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;const e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();const i=new ao(this._scene.activeCamera.globalPosition,e),s=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!s||!s.hit||s.distance>t}render(){if(!this._scene.activeCamera)return!1;const e=this._scene.getEngine(),t=this._scene.activeCamera.viewport.toGlobal(e.getRenderWidth(!0),e.getRenderHeight(!0));if(!this.computeEffectivePosition(t))return!1;if(!this._isVisible())return!1;let i,s;i=this._positionXt.x+t.width-this.borderLimit?this._positionX-t.x-t.width+this.borderLimit:0,s=this._positionYt.y+t.height-this.borderLimit?this._positionY-t.y-t.height+this.borderLimit:0;let r=i>s?i:s;r-=this.viewportBorder,r>this.borderLimit&&(r=this.borderLimit);let n=1-G.Clamp(r/this.borderLimit,0,1);if(n<0)return!1;n>1&&(n=1),this.viewportBorder>0&&(t.x+=this.viewportBorder,t.y+=this.viewportBorder,t.width-=2*this.viewportBorder,t.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);const o=t.x+t.width/2,a=t.y+t.height/2,l=o-this._positionX,h=a-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let i=0;i{throw ye("LensFlareSystemSceneComponent")},p.AddParser(ts.NAME_LENSFLARESYSTEM,((e,t,i,s)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(let r=0,n=e.lensFlareSystems.length;r{this.scene.addLensFlareSystem(e)}))}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach((e=>{this.scene.removeLensFlareSystem(e),t&&e.dispose()}))}serialize(e){e.lensFlareSystems=[];const t=this.scene.lensFlareSystems;for(const i of t)e.lensFlareSystems.push(i.serialize())}dispose(){const e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){const t=this.scene.lensFlareSystems;Ii.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)e.layerMask&i.layerMask&&i.render();Ii.EndPerformanceCounter("Lens flares",t.length>0)}}}__._SceneComponentInitialization=e=>{let t=e._getComponent(ts.NAME_LENSFLARESYSTEM);t||(t=new m_(e),e._addComponent(t))};Ft.IncludesShadersStore.bayerDitherFunctions="float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);}\nfloat bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5*mod(_P,4.0)); \nreturn 4.0*bayerDither2(P1)+bayerDither2(P2);}\nfloat bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5 *mod(_P,4.0)); \nvec2 P4=floor(0.25*mod(_P,8.0)); \nreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);}\n";Ft.IncludesShadersStore.shadowMapFragmentExtraDeclaration="#if SM_FLOAT==0\n#include\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include\nuniform float softTransparentShadowSM;\n#endif\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nuniform vec3 lightDataSM;varying vec3 vPositionWSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";Ft.IncludesShadersStore.shadowMapFragment="float depthSM=vDepthMetricSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\ndepthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_FragDepth=clamp(1.0-depthSM,0.0,1.0);\n#else\ngl_FragDepth=clamp(depthSM,0.0,1.0); \n#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);\n#endif\n#if SM_FLOAT==1\ngl_FragColor=vec4(depthSM,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depthSM);\n#endif\nreturn;";Ft.ShadersStore.shadowMapPixelShader="#include\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEXTURE\nfloat alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;\n#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard;\n#else\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;\n#endif\n#endif\n#include\n}";Ft.IncludesShadersStore.sceneVertexDeclaration="uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\nuniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition;\n";Ft.IncludesShadersStore.meshVertexDeclaration="uniform mat4 world;uniform float visibility;\n";Ft.IncludesShadersStore.shadowMapVertexDeclaration="#include\n#include\n";Ft.IncludesShadersStore.shadowMapUboDeclaration="layout(std140,column_major) uniform;\n#include\n#include\n";Ft.IncludesShadersStore.shadowMapVertexExtraDeclaration="#if SM_NORMALBIAS==1\nuniform vec3 lightDataSM;\n#endif\nuniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nvarying vec3 vPositionWSM;\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";Ft.IncludesShadersStore.shadowMapVertexNormalBias="#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvec3 worldLightDirSM=normalize(-lightDataSM.xyz);\n#else\nvec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM);\n#endif\nfloat ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM;\n#endif\n";Ft.IncludesShadersStore.shadowMapVertexMetric="#if SM_USEDISTANCE==1\nvPositionWSM=worldPos.xyz;\n#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#else\ngl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nzSM=gl_Position.z;gl_Position.z=0.0;\n#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\nvDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n";Ft.ShadersStore.shadowMapVertexShader="attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3;\n#endif\n#include\n#include<__decl__shadowMapVertex>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normWorldSM=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvec3 vNormalW=normalize(normWorldSM*normalUpdated);\n#endif\n#endif\n#include\ngl_Position=viewProjection*worldPos;\n#include\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}";Ft.ShadersStore.depthBoxBlurPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}";Ft.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow="#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;\n#endif\n";class g_{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===g_.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(e===g_.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(e===g_.FILTER_PCF||e===g_.FILTER_PCSS)return void(this.usePoissonSampling=!0)}e!==g_.FILTER_PCF&&e!==g_.FILTER_PCSS||this._scene.getEngine()._features.supportShadowSamplers?this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0}get usePoissonSampling(){return this.filter===g_.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(g_.FILTER_POISSONSAMPLING);(e||this.filter===g_.FILTER_POISSONSAMPLING)&&(this.filter=e?t:g_.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===g_.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(g_.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===g_.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:g_.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===g_.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(g_.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===g_.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:g_.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===g_.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(g_.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===g_.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:g_.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===g_.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(g_.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===g_.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:g_.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===g_.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(g_.FILTER_PCF);(e||this.filter===g_.FILTER_PCF)&&(this.filter=e?t:g_.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===g_.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(g_.FILTER_PCSS);(e||this.filter===g_.FILTER_PCSS)&&(this.filter=e?t:g_.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return this._darkness=e>=1?1:e<=0?0:e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return g_.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(const t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(const t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}_getCamera(){return this._camera??this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,s,r){this.onBeforeShadowMapRenderObservable=new g,this.onAfterShadowMapRenderObservable=new g,this.onBeforeShadowMapRenderMeshObservable=new g,this.onAfterShadowMapRenderMeshObservable=new g,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=g_.FILTER_NONE,this._filteringQuality=g_.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=w.Zero(),this._viewMatrix=B.Zero(),this._projectionMatrix=B.Zero(),this._transformMatrix=B.Zero(),this._cachedPosition=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=B.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=s??null,this._useRedTextureType=!!r;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),g_._SceneComponentInitialization(this._scene);const o=this._scene.getEngine().getCaps();i?o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:o.textureHalfFloatRender&&o.textureHalfFloatLinearFiltering?this._textureType=2:o.textureFloatRender&&o.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new da(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForShadowGenerator-${this._light.name}`)):this._shadowMap=new da(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=Zn.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=Zn.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(Zn.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,s)=>this._renderForShadowMap(e,t,i,s),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`shadow map generation for pass id ${e.currentRenderPassId}`,1)})),this._shadowMap.onBeforeRenderObservable.add((t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===g_.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onAfterUnbindObservable.add((()=>{if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===g_.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap)return void e._debugPopGroup?.(1);const t=this.getShadowMapForRendering();t&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,t.renderTarget,!0),e.unBindFramebuffer(t.renderTarget,!0),e._debugPopGroup?.(1))}));const t=new j(0,0,0,0),i=new j(1,1,1,1);this._shadowMap.onClearObservable.add((e=>{this._filter===g_.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)})),this._shadowMap.onResizeObservable.add((e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}));for(let e=es.MIN_RENDERINGGROUPS;e{e.setTexture("textureSampler",this._shadowMap)})),this._kernelBlurYPostprocess=new Jp(this._light.name+"KernelBlurY",new N(0,1),this.blurKernel,1,null,Zn.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new Ko(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,Zn.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add((e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,s){let r;if(s.length)for(r=0;r{s===i||e?(s.getMeshUniformBuffer().bindToEffect(h,"Mesh"),s.transferToEffect(e?t:p)):(i.getMeshUniformBuffer().bindToEffect(h,"Mesh"),i.transferToEffect(t))})),this.forceBackFacesOnly&&n.setState(!0,0,!1,!1,o.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(h),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===g_.FILTER_NONE||this.filter===g_.FILTER_PCSS?this._shadowMap.updateSamplingMode(Zn.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(Zn.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i={useInstances:!1,...t},s=this.getShadowMap();if(!s)return void(e&&e(this));const r=s.renderList;if(!r)return void(e&&e(this));const n=[];for(const e of r)n.push(...e.subMeshes);if(0===n.length)return void(e&&e(this));let o=0;const a=()=>{if(this._scene&&this._scene.getEngine()){for(;this.isReady(n[o],i.useInstances,n[o].getMaterial()?.needAlphaBlendingForMesh(n[o].getMesh())??!1);)if(o++,o>=n.length)return void(e&&e(this));setTimeout(a,16)}};a()}forceCompilationAsync(e){return new Promise((t=>{this.forceCompilation((()=>{t()}),e)}))}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,s){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const r=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&r.isVerticesDataPresent(Ki.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Gn.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&s?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){const s=e.getMaterial(),r=s?.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;const n=[];if(this._prepareShadowDefines(e,t,n,i),r){if(!r.isReadyForSubMesh(e,n,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const i=e._getDrawWrapper(void 0,!0);let r=i.effect,o=i.defines;const a=[Ki.PositionKind],l=e.getMesh();this.normalBias&&l.isVerticesDataPresent(Ki.NormalKind)&&(a.push(Ki.NormalKind),n.push("#define NORMAL"),l.nonUniformScaling&&n.push("#define NONUNIFORMSCALING"));const h=s.needAlphaTesting();if((h||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const e=s.alphaCutOff??g_.DEFAULT_ALPHA_CUTOFF;n.push("#define ALPHATEXTURE"),h&&n.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),l.isVerticesDataPresent(Ki.UVKind)&&(a.push(Ki.UVKind),n.push("#define UV1")),l.isVerticesDataPresent(Ki.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(a.push(Ki.UV2Kind),n.push("#define UV2"))}const c=new Yo;if(l.useBones&&l.computeBonesUsingShaders&&l.skeleton){a.push(Ki.MatricesIndicesKind),a.push(Ki.MatricesWeightsKind),l.numBoneInfluencers>4&&(a.push(Ki.MatricesIndicesExtraKind),a.push(Ki.MatricesWeightsExtraKind));const e=l.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+l.numBoneInfluencers),l.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,l),e.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(e.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");const u=l.morphTargetManager;let d=0;if(u&&(d=u.numMaxInfluencers||u.numInfluencers,d>0&&(n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+d),u.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),tn(a,l,d))),$r(s,this._scene,n),t&&(n.push("#define INSTANCES"),rn(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const e of this.customShaderOptions.defines)-1===n.indexOf(e)&&n.push(e);const p=l.bakedVertexAnimationManager;t&&p&&p.isEnabled&&(n.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),a.push("bakedVertexAnimationSettingsInstanced"));const f=n.join("\n");if(o!==f){o=f;let e="shadowMap";const t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],s=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],n=["Scene","Mesh"];if(jr(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const e of this.customShaderOptions.attributes)-1===a.indexOf(e)&&a.push(e);if(this.customShaderOptions.uniforms)for(const e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(const e of this.customShaderOptions.samplers)-1===s.indexOf(e)&&s.push(e)}const l=this._scene.getEngine();r=l.createEffect(e,{attributes:a,uniformsNames:t,uniformBuffersNames:n,samplers:s,defines:f,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:d}},l),i.setEffect(r,o)}if(!r.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){const i=this._scene,s=this._light;i.shadowsEnabled&&s.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===g_.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===g_.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===g_.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===g_.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),s.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();if(!r)return;i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix());const n=this.getShadowMapForRendering();this._filter===g_.FILTER_PCF?(t.setDepthStencilTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),r.getSize().width,1/r.getSize().width,this.frustumEdgeFalloff,e)):this._filter===g_.FILTER_PCSS?(t.setDepthStencilTexture("shadowTexture"+e,n),t.setTexture("depthTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/r.getSize().width,this._contactHardeningLightSizeUVRatio*r.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowTexture"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/r.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e)}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){const e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),w.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(w.Dot(this._lightDirection,w.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),B.LookAtLHToRef(t,t.add(this._lightDirection),w.Up(),this._viewMatrix);const e=this.getShadowMap();if(e){const t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){const e=this._shadowMap;if(!e)return;const t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(const e of t)this._shadowMap.renderList.push(e)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){const e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){const e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=this._camera?.id,e.id=this.id,e.mapSize=t.getRenderSize(),e.forceBackFacesOnly=this.forceBackFacesOnly,e.darkness=this.getDarkness(),e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.filteringQuality=this.filteringQuality,e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.depthScale=this.depthScale,e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.renderList=[],t.renderList)for(let i=0;i{throw ye("ShadowGeneratorSceneComponent")};Ft.ShadersStore.depthPixelShader="#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\nvarying float vDepthMetric;\n#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\n#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\n#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\n#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";Ft.IncludesShadersStore.pointCloudVertexDeclaration="#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";Ft.ShadersStore.depthVertexShader="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;uniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;varying vec4 vViewPos;\n#endif\n#include\nvarying float vDepthMetric;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#include\ngl_Position=viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\n#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}\n";class v_{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,s=!1,r=Zn.TRILINEAR_SAMPLINGMODE,n=!1,o){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=s,this._storeCameraSpaceZ=n,this.isPacked=0===t,this.isPacked?this.clearColor=new j(1,1,1,1):this.clearColor=new j(n?1e8:1,0,0,1),v_._SceneComponentInitialization(this._scene);const a=e.getEngine();this._camera=i,r!==Zn.NEAREST_SAMPLINGMODE&&(1!==t||a._caps.textureFloatLinearFiltering||(r=Zn.NEAREST_SAMPLINGMODE),2!==t||a._caps.textureHalfFloatLinearFiltering||(r=Zn.NEAREST_SAMPLINGMODE));const l=this.isPacked||!a._features.supportExtendedTextureFormats?5:6;this._depthMap=new da(o??"DepthRenderer",{width:a.getRenderWidth(),height:a.getRenderHeight()},this._scene,!1,!0,t,!1,r,void 0,void 0,void 0,l),this._depthMap.wrapU=Zn.CLAMP_ADDRESSMODE,this._depthMap.wrapV=Zn.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((e=>{e.clear(this.clearColor,!0,!0,!0)})),this._depthMap.onBeforeBindObservable.add((()=>{a._debugPushGroup?.("depth renderer",1)})),this._depthMap.onAfterUnbindObservable.add((()=>{a._debugPopGroup?.(1)})),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),s=this._scene,r=s.getEngine(),n=e.getMaterial();if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!n||i.infiniteDistance||n.disableDepthWrite||0===e.verticesCount||e._renderId===s.getRenderId())return;const o=i._getWorldMatrixDeterminant()<0;let a=t.overrideMaterialSideOrientation??n.sideOrientation;o&&(a=0===a?1:0);const l=0===a;r.setState(n.backFaceCulling,0,!1,l,this.reverseCulling?!n.cullBackFaces:n.cullBackFaces);const h=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(h.mustReturn)return;const c=r.getCaps().instancedArrays&&(null!==h.visibleInstances[e._id]&&void 0!==h.visibleInstances[e._id]||t.hasThinInstances),u=this._camera||s.activeCamera;if(this.isReady(e,c)&&u){e._renderId=s.getRenderId();const o=i._internalAbstractMeshDataInfo._materialForRenderPass?.[r.currentRenderPassId];let a=e._getDrawWrapper();!a&&o&&(a=o._getDrawWrapper());const l=u.mode===or.ORTHOGRAPHIC_CAMERA;if(!a)return;const d=a.effect;let p,f;if(r.enableEffect(a),c||t._bind(e,d,n.fillMode),o?o.bindForSubMesh(i.getWorldMatrix(),i,e):(d.setMatrix("viewProjection",s.getTransformMatrix()),d.setMatrix("world",i.getWorldMatrix()),this._storeCameraSpaceZ&&d.setMatrix("view",s.getViewMatrix())),l?(p=!r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1,f=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:1):(p=r.useReverseDepthBuffer&&r.isNDCHalfZRange?u.minZ:r.isNDCHalfZRange?0:u.minZ,f=r.useReverseDepthBuffer&&r.isNDCHalfZRange?0:u.maxZ),d.setFloat2("depthValues",p,p+f),!o){if(n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(d.setTexture("diffuseSampler",e),d.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices){const i=e.getTransformMatrixTexture(t);if(!i)return;d.setTexture("boneSampler",i),d.setFloat("boneTextureWidth",4*(e.bones.length+1))}else d.setMatrices("mBones",e.getTransformMatrices(t))}Kr(d,n,s),nn(t,d),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(d),n.pointsCloud&&d.setFloat("pointSize",n.pointSize)}t._processRendering(i,e,d,n.fillMode,h,c,((e,t)=>d.setMatrix("world",t)))}};this._depthMap.customRenderFunction=(e,t,i,s)=>{let r;if(s.length)for(r=0;r4&&(l.push(Ki.MatricesIndicesExtraKind),l.push(Ki.MatricesWeightsExtraKind)),a.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),a.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));const t=e.getRenderingMesh().skeleton;t?.isUsingTextureForMatrices&&a.push("#define BONETEXTURE")}else a.push("#define NUM_BONE_INFLUENCERS 0");const h=s.morphTargetManager;let c=0;h&&(c=h.numMaxInfluencers||h.numInfluencers,c>0&&(a.push("#define MORPHTARGETS"),a.push("#define NUM_MORPH_INFLUENCERS "+c),h.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),tn(l,s,c))),o.pointsCloud&&a.push("#define POINTSIZE"),t&&(a.push("#define INSTANCES"),rn(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&a.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&a.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&a.push("#define PACKED"),$r(o,r,a);const u=e._getDrawWrapper(void 0,!0),d=u.defines,p=a.join("\n");if(d!==p){const e=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];jr(e),u.setEffect(i.createEffect("depth",l,e,["diffuseSampler","morphTargets","boneSampler"],p,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),p)}return u.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}v_._SceneComponentInitialization=e=>{throw ye("DepthRendererSceneComponent")};Ft.ShadersStore.minmaxReduxPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#if defined(INITIAL)\nuniform sampler2D sourceTexture;uniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4);\n#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\n#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\n#endif\nglFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(MAIN)\nuniform vec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;void main(void)\n{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);}\n#elif defined(LAST)\nvoid main(void)\n{glFragColor=vec4(0.);if (true) { \ndiscard;}}\n#endif\n";class x_{constructor(e){this.onAfterReductionPerformed=new g,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new Qi(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{this._postProcessManager._rebuild()}))}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,s=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=s;const r=this._camera.getScene(),n=new Ko("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,r.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);n.autoClear=!1,n.forceFullscreenViewport=s;let o=this._sourceTexture.getRenderWidth(),a=this._sourceTexture.getRenderHeight();n.onApply=((e,t)=>i=>{i.setTexture("sourceTexture",this._sourceTexture),i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(n);let l=1;for(;o>1||a>1;){o=Math.max(Math.round(o/2),1),a=Math.max(Math.round(a/2),1);const e=new Ko("Reduction phase "+l,"minmaxRedux",["texSize"],null,{width:o,height:a},null,1,r.getEngine(),!1,"#define "+(1==o&&1==a?"LAST":1==o||1==a?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=s,e.onApply=((e,t)=>i=>{1==e||1==t?i.setInt2("texSize",e,t):i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(e),l++,1==o&&1==a){const t=(e,t,i)=>{const s=new Float32Array(4*e*t),n={min:0,max:0};return()=>{r.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,s,!1),n.min=s[0],n.max=s[1],this.onAfterReductionPerformed.notifyObservers(n)}};e.onAfterRenderObservable.add(t(o,a,e))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add((()=>{const e=this._camera.getScene().getEngine();e._debugPushGroup?.("min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),e.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),e._debugPopGroup?.(1)})),this._activated=!0)}deactivate(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let e=0;ethis._computeShadowCastersBoundingInfo()))),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){const e=this._shadowMap.renderList;for(let t=0;tt&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return A_.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let t=e.min,i=e.max;t>=i&&(t=0,i=1),t==this._minDistance&&i==this._maxDistance||this.setMinMaxDistance(t,i)})),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate??-1}set autoCalcDepthBoundsRefreshRate(e){this._depthReducer?.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,s=i-t,r=this._minDistance,n=t+r*s,o=t+(this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance)*s,a=o-n,l=o/n;for(let e=0;e{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===g_.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onBeforeBindObservable.add((()=>{this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._debugPushGroup?.(`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()})),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==g_.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,s=this._light;if(!i.shadowsEnabled||!s.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const r=this._getCamera();r&&this._shadowMaxZ<=(r.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const s=this._getCamera();if(!s)return;const r=this.getShadowMap();if(!r)return;const n=r.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===g_.FILTER_PCF)t.setDepthStencilTexture("shadowTexture"+e,r),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n,1/n,this.frustumEdgeFalloff,e);else if(this._filter===g_.FILTER_PCSS){for(let e=0;enew A_(e,t,void 0,i)));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}A_._FrustumCornersNDCSpace=[new w(-1,1,-1),new w(1,1,-1),new w(1,-1,-1),new w(-1,-1,-1),new w(-1,1,1),new w(1,1,1),new w(1,-1,1),new w(-1,-1,1)],A_.CLASSNAME="CascadedShadowGenerator",A_.DEFAULT_CASCADES_COUNT=4,A_.MIN_CASCADES_COUNT=2,A_.MAX_CASCADES_COUNT=4,A_._SceneComponentInitialization=e=>{throw ye("ShadowGeneratorSceneComponent")},p.AddParser(ts.NAME_SHADOWGENERATOR,((e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,s=e.shadowGenerators.length;i{let t=e._getComponent(ts.NAME_SHADOWGENERATOR);t||(t=new R_(e),e._addComponent(t))},De.AddNodeConstructor("Light_Type_0",((e,t)=>()=>new I_(e,w.Zero(),t)));class I_ extends jp{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){const t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return Gn.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new w(1,0,0);case 1:return new w(-1,0,0);case 2:return new w(0,-1,0);case 3:return new w(0,1,0);case 4:return new w(0,0,1);case 5:return new w(0,0,-1)}return w.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const s=this.getScene().activeCamera;if(!s)return;const r=void 0!==this.shadowMinZ?this.shadowMinZ:s.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:s.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;B.PerspectiveFovLHToRef(this.shadowAngle,1,o?n:r,o?r:n,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}}ae([pe()],I_.prototype,"shadowAngle",null),u("BABYLON.PointLight",I_);class P_{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css",this._style.innerHTML="@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }",document.getElementsByTagName("head")[0].appendChild(this._style);const e=!!window.SVGSVGElement,t=new Image;P_.DefaultLogoUrl?t.src=P_.DefaultLogoUrl:t.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",t.style.width="150px",t.style.gridColumn="1",t.style.gridRow="1",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.position="absolute";const i=document.createElement("div");i.style.width="300px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const s=new Image;if(P_.DefaultSpinnerUrl?s.src=P_.DefaultSpinnerUrl:s.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!e){const e={w:16,h:18.5},i={w:30,h:30};t.style.width=`${e.w}vh`,t.style.height=`${e.h}vh`,t.style.left=`calc(50% - ${e.w/2}vh)`,t.style.top=`calc(50% - ${e.h/2}vh)`,s.style.width=`${i.w}vh`,s.style.height=`${i.h}vh`,s.style.left=`calc(50% - ${i.w/2}vh)`,s.style.top=`calc(50% - ${i.h/2}vh)`}i.appendChild(s),this._loadingDiv.appendChild(t),this._loadingDiv.appendChild(i),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",(()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)})))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}P_.DefaultLogoUrl="",P_.DefaultSpinnerUrl="",si.DefaultLoadingScreenFactory=e=>new P_(e);class M_{static ConvertPanoramaToCubemap(e,t,i,s,r=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(s,this.FACE_FRONT,e,t,i,r),back:this.CreateCubemapTexture(s,this.FACE_BACK,e,t,i,r),left:this.CreateCubemapTexture(s,this.FACE_LEFT,e,t,i,r),right:this.CreateCubemapTexture(s,this.FACE_RIGHT,e,t,i,r),up:this.CreateCubemapTexture(s,this.FACE_UP,e,t,i,r),down:this.CreateCubemapTexture(s,this.FACE_DOWN,e,t,i,r),size:s,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,s,r,n=!1){const o=new ArrayBuffer(e*e*4*3),a=new Float32Array(o),l=n?Math.max(1,Math.round(s/4/e)):1,h=1/l,c=h*h,u=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),p=1/e;let f=0;for(let n=0;nMath.PI;)r-=2*Math.PI;let o=r/Math.PI;const a=n/Math.PI;o=.5*o+.5;let l=Math.round(o*i);l<0?l=0:l>=i&&(l=i-1);let h=Math.round(a*s);h<0?h=0:h>=s&&(h=s-1);const c=s-h-1;return{r:t[c*i*3+3*l+0],g:t[c*i*3+3*l+1],b:t[c*i*3+3*l+2]}}}M_.FACE_LEFT=[new w(-1,-1,-1),new w(1,-1,-1),new w(-1,1,-1),new w(1,1,-1)],M_.FACE_RIGHT=[new w(1,-1,1),new w(-1,-1,1),new w(1,1,1),new w(-1,1,1)],M_.FACE_FRONT=[new w(1,-1,-1),new w(1,-1,1),new w(1,1,-1),new w(1,1,1)],M_.FACE_BACK=[new w(-1,-1,1),new w(-1,-1,-1),new w(-1,1,1),new w(-1,1,-1)],M_.FACE_DOWN=[new w(1,1,-1),new w(1,1,1),new w(-1,1,-1),new w(-1,1,1)],M_.FACE_UP=[new w(-1,-1,-1),new w(-1,-1,1),new w(1,-1,-1),new w(1,-1,1)];class D_{static _Ldexp(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,s,r,n){r>0?(r=this._Ldexp(1,r-136),e[n+0]=t*r,e[n+1]=i*r,e[n+2]=s*r):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}static _ReadStringLine(e,t){let i="",s="";for(let r=t;r32767)throw"HDR Bad header format, unsupported size";return o+=s.length+1,{height:t,width:i,dataPosition:o}}static GetCubeMapTextureData(e,t,i=!1){const s=new Uint8Array(e),r=this.RGBE_ReadHeader(s),n=this.RGBE_ReadPixels(s,r);return M_.ConvertPanoramaToCubemap(n,r.width,r.height,t,i)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i=t.height;const s=t.width;let r,n,o,a,l,h=t.dataPosition,c=0,u=0,d=0;const p=new ArrayBuffer(4*s),f=new Uint8Array(p),_=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(_);for(;i>0;){if(r=e[h++],n=e[h++],o=e[h++],a=e[h++],2!=r||2!=n||128&o||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((o<<8|a)!=s)throw"HDR Bad header format, wrong scan line width";for(c=0,d=0;d<4;d++)for(u=(d+1)*s;c128){if(l=r-128,0==l||l>u-c)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)f[c++]=n}else{if(l=r,0==l||l>u-c)throw"HDR Bad Format, bad scanline data (non-run)";if(f[c++]=n,--l>0)for(let t=0;t0;){for(l=0;l{this._effectRenderer=new na(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled((()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()}))})):(J.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}}class N_ extends qn{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(B.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,s=!1,r=!0,n=!1,o=!1,a=null,l=null,h=!1){super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=w.Zero(),this.onLoadObservable=new g,e&&(this._coordinatesMode=Zn.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=B.Identity(),this._prefilterOnLoad=o,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),a&&a()},this._onError=l,this.gammaSpace=n,this._noMipmap=s,this._size=i,this._supersample=h,this._generateHarmonics=r,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?Ii.SetImmediate((()=>this._onLoad())):this._texture.onLoadedObservable.add(this._onLoad):this.getScene()?.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture())}getClassName(){return"HDRCubeTexture"}_loadTexture(){const e=this._getEngine(),t=e.getCaps();let i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const t=this._onLoad,i=new O_(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,(e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const t=D_.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){const e=Jc.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}const s=[];let r=null,n=null;for(let e=0;e<6;e++){2===i?n=new Uint16Array(this._size*this._size*3):0===i&&(r=new Uint8Array(this._size*this._size*3));const o=t[N_._FacesMapping[e]];if(this.gammaSpace||n||r)for(let e=0;e255){const e=255/n;t*=e,i*=e,s*=e}r[3*e+0]=t,r[3*e+1]=i,r[3*e+2]=s}n?s.push(n):r?s.push(r):s.push(o)}return s}),null,this._onLoad,this._onError)}clone(){const e=new N_(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&this.getScene()?.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(this)))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let s=null;return e.name&&!e.isRenderTarget&&(s=new N_(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),s.name=e.name,s.hasAlpha=e.hasAlpha,s.level=e.level,s.coordinatesMode=e.coordinatesMode,s.isBlocking=e.isBlocking),s&&(e.boundingBoxPosition&&(s.boundingBoxPosition=w.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(s.boundingBoxSize=w.FromArray(e.boundingBoxSize)),e.rotationY&&(s.rotationY=e.rotationY)),s}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}N_._FacesMapping=["right","left","up","down","front","back"],u("BABYLON.HDRCubeTexture",N_);class w_{get influence(){return this._influence}set influence(e){if(this._influence===e)return;const t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new g,this._onDataLayoutChanged=new g,this._animationPropertiesOverride=null,this._scene=i||y.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}setPositions(e){const t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){const t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){const t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){const t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){const e=Pe.Clone((()=>new w_(this.name,this.influence,this._scene)),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e}serialize(){const e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),null!=this.id&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),Pe.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new w_(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Mi(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=y.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._syncActiveTargets(!0))}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get numTargets(){return this._targets.length}get numInfluencers(){return this._activeTargets.length}get influences(){return this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets=e}get isUsingTextureForTargets(){return L_.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!this._scene?.getEngine().getCaps().disableMorphTargetTexture}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}getTargetByName(e){for(const t of this._targets)if(t.name===e)return t;return null}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add((e=>{this._syncActiveTargets(e)}))),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add((()=>{this._syncActiveTargets(!0)}))),this._syncActiveTargets(!0)}removeTarget(e){const t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0)),this._scene&&this._scene.stopAnimation(e)}_bind(e){e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setInt("morphTargetCount",this.numInfluencers)}clone(){const e=new L_(this._scene);for(const t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){const e={};e.id=this.uniqueId,e.targets=[];for(const t of this._targets)e.targets.push(t.serialize());return e}_syncActiveTargets(e){if(this.areUpdatesFrozen)return;let t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),this._morphTargetTextureIndices&&this._morphTargetTextureIndices.length===this._targets.length||(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let i=-1;for(const e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=L_.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;const s=e.getPositions();if(s){const e=s.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e)return void J.Error("Incompatible target. Targets must all have the same vertices count.")}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e0)){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;const e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){const e=this._targetStoreTexture.getSize();e.width===this._textureWidth&&e.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4);let i=0;for(let s=0;s-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(const e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){const i=new L_(t);i._uniqueId=e.id;for(const s of e.targets)i.addTarget(w_.Parse(s,t));return i}}L_.EnableTextureStorage=!0,L_.MaxActiveMorphTargetsInVertexAttributeMode=8;class B_{constructor(){this._hasHit=!1,this._hitNormal=w.Zero(),this._hitPoint=w.Zero(),this._triangleIndex=-1}get hitPoint(){return this._hitPoint}get hitNormal(){return this._hitNormal}get hasHit(){return this._hasHit}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormal.set(e.x,e.y,e.z),this._hitPoint.set(t.x,t.y,t.z),this._triangleIndex=i??-1}reset(){this._hasHit=!1,this._hitNormal.setAll(0),this._hitPoint.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0,this.shape=void 0}}class V_ extends B_{constructor(){super(...arguments),this._hitDistance=0,this._rayFromWorld=w.Zero(),this._rayToWorld=w.Zero()}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormal}get hitPointWorld(){return this._hitPoint}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=w.Distance(this._rayFromWorld,this._hitPoint)}reset(e=w.Zero(),t=w.Zero()){super.reset(),this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hitDistance=0}}class U_{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw ye("CannonJSPlugin")}constructor(e,t=U_.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new w(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){const t=this._impostors.indexOf(e);t>-1&&this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)}addJoint(e,t,i){const s={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(s),this._physicsPlugin.generateJoint(s)}removeJoint(e,t,i){const s=this._joints.filter((function(s){return s.connectedImpostor===t&&s.joint===i&&s.mainImpostor===e}));s.length&&this._physicsPlugin.removeJoint(s[0])}_step(e){this._impostors.forEach((e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t0&&(this._physicsBodiesToRemoveAfterStep.forEach((e=>{"function"==typeof this.world.removeBody?this.world.removeBody(e):this.world.remove(e)})),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(r,s)}applyForce(e,t,i){const s=new this.BJSCANNON.Vec3(i.x,i.y,i.z),r=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(r,s)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const t=this._createShape(e);if(!t)return void J.Warn("It was not possible to create a physics body for this object.");const i=e.physicsBody;i&&this.removePhysicsBody(e);const s=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),r={mass:e.getParam("mass"),material:s},n=e.getParam("nativeOptions");for(const e in n)Object.prototype.hasOwnProperty.call(n,e)&&(r[e]=n[e]);e.physicsBody=new this.BJSCANNON.Body(r),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){const s=i[t];e.physicsBody[t].set(s.x,s.y,s.z)})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}}_processChildMeshes(e){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],i=e.object.rotationQuaternion;if(i?i.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),t.length){const i=t=>{if(!t.rotationQuaternion)return;const s=t.getPhysicsImpostor();if(s&&s.parent!==e&&t.parent){const i=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),r=t.rotationQuaternion.multiply(this._tmpQuaternion);s.physicsBody&&(this.removePhysicsBody(s),s.physicsBody=null),s.parent=e,s.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(s),new this.BJSCANNON.Vec3(i.x,i.y,i.z),new this.BJSCANNON.Quaternion(r.x,r.y,r.z,r.w)),e.physicsBody.mass+=s.getParam("mass")}t.getChildMeshes(!0).filter((e=>!!e.physicsImpostor)).forEach(i)};t.filter((e=>!!e.physicsImpostor)).forEach(i)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;let s;const r=e.joint.jointData,n={pivotA:r.mainPivot?(new this.BJSCANNON.Vec3).set(r.mainPivot.x,r.mainPivot.y,r.mainPivot.z):null,pivotB:r.connectedPivot?(new this.BJSCANNON.Vec3).set(r.connectedPivot.x,r.connectedPivot.y,r.connectedPivot.z):null,axisA:r.mainAxis?(new this.BJSCANNON.Vec3).set(r.mainAxis.x,r.mainAxis.y,r.mainAxis.z):null,axisB:r.connectedAxis?(new this.BJSCANNON.Vec3).set(r.connectedAxis.x,r.connectedAxis.y,r.connectedAxis.z):null,maxForce:r.nativeParams.maxForce,collideConnected:!!r.collision};switch(e.joint.type){case mo.HingeJoint:case mo.Hinge2Joint:s=new this.BJSCANNON.HingeConstraint(t,i,n);break;case mo.DistanceJoint:s=new this.BJSCANNON.DistanceConstraint(t,i,r.maxDistance||2);break;case mo.SpringJoint:{const e=r;s=new this.BJSCANNON.Spring(t,i,{restLength:e.length,stiffness:e.stiffness,damping:e.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break}case mo.LockJoint:s=new this.BJSCANNON.LockConstraint(t,i,n);break;case mo.PointToPointJoint:case mo.BallAndSocketJoint:default:s=new this.BJSCANNON.PointToPointConstraint(t,n.pivotA,i,n.pivotB,n.maxForce)}s.collideConnected=!!r.collision,e.joint.physicsJoint=s,e.joint.type!==mo.SpringJoint?this.world.addConstraint(s):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){s.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==mo.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let s,r;for(s=0;s1e3*i));e++);this.time+=s;const a=this.time%i/i,l=e,h=this.bodies;for(let e=0;e!==h.length;e++){const i=h[e];i.type!==t.Body.STATIC&&i.sleepState!==t.Body.SLEEPING?(i.position.vsub(i.previousPosition,l),l.scale(a,l),i.position.vadd(l,i.interpolatedPosition)):(i.interpolatedPosition.set(i.position.x,i.position.y,i.position.z),i.interpolatedQuaternion.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w))}}}}raycast(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))}}U_.DefaultPluginFactory=()=>new k_;class G_{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=w.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new V_}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this.world.timeStep=e}getTimeStep(){return this.world.timeStep}executeStep(e,t){t.forEach((function(e){e.beforeStep()})),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach((e=>{e.afterStep(),this._tmpImpostorsArray[e.uniqueId]=e}));let i=this.world.contacts;for(;null!==i;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];e&&t?(e.onCollide({body:t.physicsBody,point:null,distance:0,impulse:0,normal:null}),t.onCollide({body:e.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next):i=i.next}}applyImpulse(e,t,i){const s=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*s))}applyForce(e,t,i){J.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},s=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach((function(e){e.physicsImpostor&&s.push(e.physicsImpostor)}));const r=e=>Math.max(e,T),n=new L;s.forEach((t=>{if(!t.object.rotationQuaternion)return;const s=t.object.rotationQuaternion;n.copyFrom(s),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);const o=n.toEulerAngles(),a=t.getObjectExtents(),l=57.29577951308232;if(t===e){const t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{const e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(o.x*l,o.y*l,o.z*l)}switch(t.object.rotationQuaternion.copyFrom(n),t.type){case go.ParticleImpostor:J.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case go.SphereImpostor:{const e=a.x,t=a.y,s=a.z,n=Math.max(r(e),r(t),r(s))/2;i.type.push("sphere"),i.size.push(n),i.size.push(n),i.size.push(n);break}case go.CylinderImpostor:{const e=r(a.x)/2,t=r(a.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case go.PlaneImpostor:case go.BoxImpostor:default:{const e=r(a.x),t=r(a.y),s=r(a.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(s);break}}t.object.rotationQuaternion=s})),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(n),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}var t}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const s=e.joint.jointData,r=s.nativeParams||{};let n;const o={body1:t,body2:i,axe1:r.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:r.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:r.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:r.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:r.min,max:r.max,collision:r.collision||s.collision,spring:r.spring,world:this.world};switch(e.joint.type){case mo.BallAndSocketJoint:n="jointBall";break;case mo.SpringJoint:{J.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const e=s;o.min=e.length||o.min,o.max=Math.max(o.min,o.max)}case mo.DistanceJoint:n="jointDistance",o.max=s.maxDistance;break;case mo.PrismaticJoint:n="jointPrisme";break;case mo.SliderJoint:n="jointSlide";break;case mo.WheelJoint:n="jointWheel";break;case mo.HingeJoint:default:n="jointHinge"}o.type=n,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){J.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{const t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){const t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){const s=e.physicsBody;e.physicsBody.shapes.next||(s.position.set(t.x,t.y,t.z),s.orientation.set(i.x,i.y,i.z,i.w),s.syncShapes(),s.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){const t=e.physicsBody.linearVelocity;return t?new w(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new w(t.x,t.y,t.z):null}setBodyMass(e,t){const i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,s){void 0!==i?J.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setMotor(t,i)}setLimit(e,t,i,s){const r=s?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;r&&r.setLimit(t,void 0===i?-t:i)}syncMeshWithImpostor(e,t){const i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)}getRadius(e){return e.physicsBody.shapes.radius}getBoxSizeToRef(e,t){const i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth}dispose(){this.world.clear()}raycast(e,t){return J.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){J.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class z_{constructor(e=!0,t=Ammo,i=null){this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new L,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new w,this._tmpContactNormal=new w,this._tmpVec3=new w,this._tmpMatrix=new B,"function"!=typeof t?(this.bjsAMMO=t,this.isSupported()?(this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=e=>{const t=(e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint)).getPositionWorldOnA(),i=e.m_normalWorldOnB;this._tmpContactPoint.x=t.x(),this._tmpContactPoint.y=t.y(),this._tmpContactPoint.z=t.z(),this._tmpContactNormal.x=i.x(),this._tmpContactNormal.y=i.y(),this._tmpContactNormal.z=i.z(),this._tmpContactImpulse=e.getAppliedImpulse(),this._tmpContactDistance=e.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new V_,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)):J.Error("AmmoJS is not available. Please make sure you included the js file.")):J.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.")}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(e))for(const t of e._onPhysicsCollideCallbacks)for(const i of t.otherImpostors)(e.physicsBody.isActive()||i.physicsBody.isActive())&&this._isImpostorPairInContact(e,i)&&(e.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),i.onCollide({body:e.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===go.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let s,r,n,o,a;const l=new Array;for(let e=0;e{this.bjsAMMO.destroy(e)})),e._pluginData.toDispose=[]))}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;if(e.joint.physicsJoint)return;const s=e.joint.jointData;let r;switch(s.mainPivot||(s.mainPivot=new w(0,0,0)),s.connectedPivot||(s.connectedPivot=new w(0,0,0)),e.joint.type){case mo.DistanceJoint:{const e=s.maxDistance;e&&(s.mainPivot=new w(0,-e/2,0),s.connectedPivot=new w(0,e/2,0));const n=this._tmpAmmoVectorA;n.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const o=this._tmpAmmoVectorB;o.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,n,o);break}case mo.HingeJoint:{s.mainAxis||(s.mainAxis=new w(0,0,0)),s.connectedAxis||(s.connectedAxis=new w(0,0,0));const e=this._tmpAmmoVectorA;e.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z);const o=this._tmpAmmoVectorC;o.setValue(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z);const a=this._tmpAmmoVectorD;a.setValue(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z),r=new this.bjsAMMO.btHingeConstraint(t,i,e,n,o,a);break}case mo.BallAndSocketJoint:{const e=this._tmpAmmoVectorA;e.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,e,n);break}default:{J.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint");const e=this._tmpAmmoVectorA;e.setValue(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z);const n=this._tmpAmmoVectorB;n.setValue(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),r=new this.bjsAMMO.btPoint2PointConstraint(t,i,e,n);break}}this.world.addConstraint(r,!e.joint.jointData.collision),e.joint.physicsJoint=r}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint),this.bjsAMMO.destroy(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n,o=i.getVerticesData(Ki.PositionKind);if(o||(o=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?L.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):L.Identity(),B.Compose(w.One(),e,t.position).invertToRef(this._tmpMatrix),n=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else B.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),n=this._tmpMatrix;const a=r.length/3;for(let t=0;t{s+=this._addMeshVerts(e,t,i)}))}return s}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(Ki.PositionKind);i||(i=[]);let s=t.getVerticesData(Ki.NormalKind);s||(s=[]),t.computeWorldMatrix(!1);const r=[],n=[];for(let e=0;ee*e)).reduce(((e,t)=>e+t)))t=r.length,i=t/3-1,this._tmpAmmoVectorA.setValue(r[0],r[1],r[2]),this._tmpAmmoVectorB.setValue(r[t-3],r[t-2],r[t-1]);else{e._isFromLine=!1;const s=e.getParam("path");if(null===e.getParam("shape"))return J.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;t=s.length,i=t-1,this._tmpAmmoVectorA.setValue(s[0].x,s[0].y,s[0].z),this._tmpAmmoVectorB.setValue(s[t-1].x,s[t-1].y,s[t-1].z)}e.segments=i;let o=e.getParam("fixedPoints");o=o>3?3:o;const a=(new this.bjsAMMO.btSoftBodyHelpers).CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,o);return a.get_m_cfg().set_collisions(17),a}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let s=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let r=i.getIndices();r||(r=[]);let n=i.getVerticesData(Ki.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);const o=r.length/3;for(let t=0;t{s+=this._addHullVerts(e,t,i)}))}return s}_createShape(e,t=!1){const i=e.object;let s;const r=e.getObjectExtents();if(!t){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];s=new this.bjsAMMO.btCompoundShape;let i=0;if(t.forEach((e=>{const t=e.getPhysicsImpostor();if(t){if(t.type==go.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const r=this._createShape(t),n=e.parent.getWorldMatrix().clone(),o=new w;n.decompose(o),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*o.x,e.position.y*o.y,e.position.z*o.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,r),t.dispose(),i++}})),i>0){if(e.type!=go.NoImpostor){const t=this._createShape(e,!0);t&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),s.addChildShape(this._tmpAmmoTransform,t))}return s}this.bjsAMMO.destroy(s),s=null}switch(e.type){case go.SphereImpostor:if(G.WithinEpsilon(r.x,r.y,1e-4)&&G.WithinEpsilon(r.x,r.z,1e-4))s=new this.bjsAMMO.btSphereShape(r.x/2);else{this._tmpAmmoVectorA.setValue(0,0,0);const e=[this._tmpAmmoVectorA],t=[1];s=new this.bjsAMMO.btMultiSphereShape(e,t,1),this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s.setLocalScaling(this._tmpAmmoVectorA)}break;case go.CapsuleImpostor:{const e=r.x/2;s=new this.bjsAMMO.btCapsuleShape(e,r.y-2*e)}break;case go.CylinderImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case go.PlaneImpostor:case go.BoxImpostor:this._tmpAmmoVectorA.setValue(r.x/2,r.y/2,r.z/2),s=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case go.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)s=this.onCreateCustomMeshImpostor(e);else{const t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);const r=this._addMeshVerts(t,i,i);s=0==r?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case go.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)s=this.onCreateCustomConvexHullImpostor(e);else{const t=new this.bjsAMMO.btConvexHullShape;0==this._addHullVerts(t,i,i)?(e._pluginData.toDispose.push(t),s=new this.bjsAMMO.btCompoundShape):s=t}break;case go.NoImpostor:s=new this.bjsAMMO.btSphereShape(r.x/2);break;case go.CustomImpostor:s=this._createCustom(e);break;case go.SoftbodyImpostor:s=this._createSoftbody(e);break;case go.ClothImpostor:s=this._createCloth(e);break;case go.RopeImpostor:s=this._createRope(e);break;default:J.Warn("The impostor type is not currently supported by the ammo plugin.")}return s}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){const s=e.physicsBody.getWorldTransform();if(Math.abs(s.getOrigin().x()-t.x)>T||Math.abs(s.getOrigin().y()-t.y)>T||Math.abs(s.getOrigin().z()-t.z)>T||Math.abs(s.getRotation().x()-i.x)>T||Math.abs(s.getRotation().y()-i.y)>T||Math.abs(s.getRotation().z()-i.z)>T||Math.abs(s.getRotation().w()-i.w)>T)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),s.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),s.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(s),0==e.mass){const t=e.physicsBody.getMotionState();t&&t.setWorldTransform(s)}else e.physicsBody.activate()}isSupported(){return void 0!==this.bjsAMMO}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity(),!t)return null;const i=new w(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity(),!t)return null;const i=new w(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}setBodyMass(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t}getBodyMass(e){return e._pluginData.mass||0}getBodyFriction(e){return e._pluginData.friction||0}setBodyFriction(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t}getBodyRestitution(e){return e._pluginData.restitution||0}setBodyRestitution(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t}getBodyPressure(e){return e.soft?e._pluginData.pressure||0:(J.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===go.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):J.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(J.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):J.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(J.Warn("Velocity iterations is not a property of a rigid body"),0)}setBodyVelocityIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):J.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(J.Warn("Position iterations is not a property of a rigid body"),0)}setBodyPositionIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):J.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,s,r=1,n=!1){const o=e.segments,a=Math.round((o-1)*i)+o*(o-1-Math.round((o-1)*s));e.physicsBody.appendAnchor(a,t.physicsBody,n,r)}appendHook(e,t,i,s=1,r=!1){const n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,r,s)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){J.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){J.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){return e.getObjectExtents().x/2}getBoxSizeToRef(e,t){const i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._softBodySolver),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoVectorD),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);const s=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,s),i.reset(e,t),s.hasHit()&&(i.setHitData({x:s.get_m_hitNormalWorld().x(),y:s.get_m_hitNormalWorld().y(),z:s.get_m_hitNormalWorld().z()},{x:s.get_m_hitPointWorld().x(),y:s.get_m_hitPointWorld().y(),z:s.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(s),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}z_._DISABLE_COLLISION_FLAG=4,z_._KINEMATIC_FLAG=2,z_._DISABLE_DEACTIVATION_FLAG=4,p.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return-1;const t=this.reflectionProbes.indexOf(e);return-1!==t&&this.reflectionProbes.splice(t,1),t},p.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};class W_{constructor(e,t,i,s=!0,r=!1,n=!1){if(this.name=e,this._viewMatrix=B.Identity(),this._target=w.Zero(),this._add=w.Zero(),this._invertYAxis=!1,this.position=w.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(r){const e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?o=2:e.textureFloatRender&&(o=1)}this._renderTargetTexture=new da(e,t,i,s,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const a=i.getEngine().useReverseDepthBuffer;let l;this._renderTargetTexture.onBeforeRenderObservable.add((e=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){case 0:this._add.copyFromFloats(1,0,0);break;case 1:this._add.copyFromFloats(-1,0,0);break;case 2:this._add.copyFromFloats(0,this._invertYAxis?1:-1,0);break;case 3:this._add.copyFromFloats(0,this._invertYAxis?-1:1,0);break;case 4:this._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:this._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1)}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);const t=i.useRightHandedSystem?B.LookAtRHToRef:B.LookAtLHToRef,s=i.useRightHandedSystem?B.PerspectiveFovRH:B.PerspectiveFovLH;t(this.position,this._target,w.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=s(Math.PI/2,1,a?i.activeCamera.maxZ:i.activeCamera.minZ,a?i.activeCamera.minZ:i.activeCamera.maxZ,this._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(this._viewMatrix,this._projectionMatrix),i.activeCamera.isRigCamera&&!this._renderTargetTexture.activeCamera&&(this._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=this.position})),this._renderTargetTexture.onBeforeBindObservable.add((()=>{this._currentSceneUBO=i.getSceneUniformBuffer(),i.getEngine()._debugPushGroup?.(`reflection probe generation for ${e}`,1),l=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)})),this._renderTargetTexture.onAfterUnbindObservable.add((()=>{i.imageProcessingConfiguration.applyByPostProcess=l,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),i.getEngine()._debugPopGroup?.(1)}))}get samples(){return this._renderTargetTexture.samples}set samples(e){this._renderTargetTexture.samples=e}get refreshRate(){return this._renderTargetTexture.refreshRate}set refreshRate(e){this._renderTargetTexture.refreshRate=e}getScene(){return this._scene}get cubeTexture(){return this._renderTargetTexture}get renderList(){return this._renderTargetTexture.renderList}set renderList(e){this._renderTargetTexture.renderList=e}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){const e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){const e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}toString(e){let t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t}getClassName(){return"ReflectionProbe"}serialize(){const e=Pe.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let s=null;if(t.reflectionProbes)for(let i=0;is||new W_(e.name,e.renderTargetSize,t,e._generateMipMaps)),e,t,i),s.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&s.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(s.metadata=e.metadata),s}}ae([xe()],W_.prototype,"_attachedMesh",void 0),ae([ve()],W_.prototype,"position",void 0);class H_{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,s,r){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=s||1,this._animationStarted=!0,this._onBaseAnimationEnd=r,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class X_ extends H_{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=new Array,this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new g,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new j(1,1,1,1),this.position=w.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,s,r=null){this._onAnimationEnd=r,super.playAnimation(e,t,i,s,this._endAnimation)}dispose(){for(let e=0;e0)for(let n=0;n=r.distance))&&(r=a,i))break}return r||new qi},ks.prototype._internalMultiPickSprites=function(e,t,i){if(!qi)return null;let s=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let r=0;r!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(ts.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(ts.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(ts.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();const e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,s,r){const n=this.scene.pickSprite(t,i,this._spritePredicate,s,r);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,s,r){const n=this.scene;return s?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&r&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?r.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:r.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null),i}_pointerDown(e,t,i,s){const r=this.scene;if(r._pickedDownSprite=null,r.spriteManagers&&r.spriteManagers.length>0&&(i=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(r._pickedDownSprite=i.pickedSprite,s.button){case 0:i.pickedSprite.actionManager.processTrigger(2,q.CreateNewFromSprite(i.pickedSprite,r,s));break;case 1:i.pickedSprite.actionManager.processTrigger(4,q.CreateNewFromSprite(i.pickedSprite,r,s));break;case 2:i.pickedSprite.actionManager.processTrigger(3,q.CreateNewFromSprite(i.pickedSprite,r,s))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,q.CreateNewFromSprite(i.pickedSprite,r,s))}return i}_pointerUp(e,t,i,s,r){const n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){const i=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,q.CreateNewFromSprite(i.pickedSprite,n,s)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,q.CreateNewFromSprite(i.pickedSprite,n,s)),r&&i.pickedSprite.actionManager.processTrigger(6,q.CreateNewFromSprite(i.pickedSprite,n,s)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==i.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,q.CreateNewFromSprite(n._pickedDownSprite,n,s)))}return i}}Ft.IncludesShadersStore.imageProcessingCompatibility="#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));\n#endif\n";Ft.ShadersStore.spritesPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler;\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nvec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;}\n#endif\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvec2 uv=uvPixelPerfect(vUV);\n#else\nvec2 uv=vUV;\n#endif\nvec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.)\n{if (color.a<0.95)\ndiscard;}\ncolor*=vColor;\n#include\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.spritesVertexShader="attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor;\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); \nvColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y;\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";class j_{get fogEnabled(){return this._fogEnabled}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this._createEffects())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=!!this._scene?.getEngine().getCaps().fragmentDepthSupported;e&&!t&&J.Warn("Logarithmic depth has been requested for a sprite renderer on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._createEffects()}get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,s=null){this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this._fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=s,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new $i(e,this._vertexData,!0,this._vertexBufferSize);const r=this._buffer.createVertexBuffer(Ki.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),n=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing);let o,a=6;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new $i(e,t,!1,2),o=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else o=this._buffer.createVertexBuffer("offsets",a,2,this._vertexBufferSize,this._useInstancing),a+=2;const l=this._buffer.createVertexBuffer("inverts",a,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",a+2,4,this._vertexBufferSize,this._useInstancing),c=this._buffer.createVertexBuffer(Ki.ColorKind,a+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[Ki.PositionKind]=r,this._vertexBuffers.options=n,this._vertexBuffers.offsets=o,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[Ki.ColorKind]=c,this._createEffects()}_createEffects(){this._drawWrapperBase?.dispose(),this._drawWrapperDepth?.dispose(),this._drawWrapperBase=new gr(this._engine),this._drawWrapperDepth=new gr(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing);let e="";this._pixelPerfect&&(e+="#define PIXEL_PERFECT\n"),this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&this._fogEnabled&&(e+="#define FOG\n"),this._useLogarithmicDepth&&(e+="#define LOGARITHMICDEPTH\n"),this._drawWrapperBase.effect=this._engine.createEffect("sprites",[Ki.PositionKind,"options","offsets","inverts","cellInfo",Ki.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor","logarithmicDepthConstant"],["diffuseSampler"],e),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext}render(e,t,i,s,r=null){if(!this.texture||!this.texture.isReady()||!e.length)return;const n=this._drawWrapperBase,o=this._drawWrapperDepth,a=this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode,l=n.effect;if(!l.isReady())return;const h=this._engine,c=!(!this._scene||!this._scene.useRightHandedSystem),u=this.texture.getBaseSize(),d=Math.min(this._capacity,e.length);let p=0,f=!0;for(let i=0;i{e.cellRef||(e.cellIndex=0);const i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=this._spriteMap[e.cellIndex]),e._xOffset=this._cellData[e.cellRef].frame.x/t.width,e._yOffset=this._cellData[e.cellRef].frame.y/t.height,e._xSize=this._cellData[e.cellRef].frame.w,e._ySize=this._cellData[e.cellRef].frame.h},r||(r=y.LastCreatedScene),r._getComponent(ts.NAME_SPRITE)||r._addComponent(new Y_(r)),this._fromPacked=a,this._scene=r;const h=this._scene.getEngine();if(this._spriteRenderer=new j_(h,i,n,r),s.width&&s.height)this.cellWidth=s.width,this.cellHeight=s.height;else{if(void 0===s)return void(this._spriteRenderer=null);this.cellWidth=s,this.cellHeight=s}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new Zn(t,r,!0,!1,o)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if(e="string"==typeof t?JSON.parse(t):t,e.frames.length){const t={};for(let i=0;i0);const s=e.substring(0,i-1)+".json",r=()=>{J.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},n=e=>{try{const t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};Ii.LoadFile(s,n,void 0,void 0,!1,r)}}_checkTextureAlpha(e,t,i,s,r){if(!e.useAlphaForPicking||!this.texture)return!0;const n=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(n.width*n.height*4),this.texture.readPixels(0,0,this._textureContent));const o=U.Vector3[0];o.copyFrom(t.direction),o.normalize(),o.scaleInPlace(i),o.addInPlace(t.origin);const a=(o.x-s.x)/(r.x-s.x),l=1-(o.y-s.y)/(r.y-s.y),h=e._xOffset*n.width+a*e._xSize|0,c=e._yOffset*n.height+l*e._ySize|0;return this._textureContent[4*(h+c*n.width)+3]>.5}intersects(e,t,i,s){const r=Math.min(this.capacity,this.sprites.length),n=w.Zero(),o=w.Zero();let a=Number.MAX_VALUE,l=null;const h=U.Vector3[0],c=U.Vector3[1],u=t.getViewMatrix();let d=e,p=e;for(let t=0;te){if(!this._checkTextureAlpha(r,d,e,n,o))continue;if(p=d,a=e,l=r,s)break}}}}if(l){const e=new qi;u.invertToRef(U.Matrix[0]),e.hit=!0,e.pickedSprite=l,e.distance=a;const t=U.Vector3[2];return t.copyFrom(p.direction),t.normalize(),t.scaleInPlace(a),p.origin.addToRef(t,h),e.pickedPoint=w.TransformCoordinates(h,U.Matrix[0]),e}return null}multiIntersects(e,t,i){const s=Math.min(this.capacity,this.sprites.length),r=w.Zero(),n=w.Zero();let o;const a=[],l=U.Vector3[0].copyFromFloats(0,0,0),h=U.Vector3[1].copyFromFloats(0,0,0),c=t.getViewMatrix();for(let t=0;t{const o=new Ne;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),n=$_.Parse(t,i||y.LastCreatedScene,s);e&&(n.name=e),r(n)}else n("Unable to load the sprite manager")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new $_("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise(((s,r)=>{const n=new Ne;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const r=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(r.spriteManager),a=$_.Parse(o,t||y.LastCreatedScene,i);a.snippetId=e,s(a)}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}$_.SnippetUrl="https://snippet.babylonjs.com",$_.CreateFromSnippetAsync=$_.ParseFromSnippetAsync;class K_{}K_.LoaderInjectedPhysicsEngine=void 0;let q_={},Q_={};const Z_=(e,t,i,s)=>{if(!t.materials)return null;for(let r=0,n=t.materials.length;r{for(const s in t)if(e.name===t[s])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},em=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),tm=(e,t)=>{const i=t;if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){const s=t._waitingData.lods.ids,r=i.isEnabled(!1);if(t._waitingData.lods.distances){const n=t._waitingData.lods.distances;if(n.length>=s.length){const t=n.length>s.length?n[n.length-1]:0;i.setEnabled(!1);for(let t=0;t0&&i.addLODLevel(t,null),!0===r&&i.setEnabled(!0)}else Ii.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},im=(e,t,i)=>{if("number"!=typeof e){const s=i.getLastEntryById(e);return s&&null!=t?s.instances[parseInt(t)]:s}const s=q_[e];return s&&null!=t?s.instances[parseInt(t)]:s},sm=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):Q_[e],rm=(e,t,i,s,r=!1)=>{const n=new Hn(e);let o="importScene has failed JSON parse";try{var a=JSON.parse(t);o="";const s=Ro.loggingLevel===Ro.DETAILED_LOGGING;let r,l;if(void 0!==a.environmentTexture&&null!==a.environmentTexture){const t=void 0===a.isPBR||a.isPBR;if(a.environmentTextureType&&"BABYLON.HDRCubeTexture"===a.environmentTextureType){const s=a.environmentTextureSize?a.environmentTextureSize:128,r=new N_((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,s,!0,!t,void 0,a.environmentTexturePrefilterOnLoad);a.environmentTextureRotationY&&(r.rotationY=a.environmentTextureRotationY),e.environmentTexture=r}else if("object"==typeof a.environmentTexture){const t=tf.Parse(a.environmentTexture,e,i);e.environmentTexture=t}else if(a.environmentTexture.endsWith(".env")){const t=new tf((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}else{const t=tf.CreateFromPrefilteredData((a.environmentTexture.match(/https?:\/\//g)?"":i)+a.environmentTexture,e,a.environmentTextureForcedExtension);a.environmentTextureRotationY&&(t.rotationY=a.environmentTextureRotationY),e.environmentTexture=t}if(!0===a.createDefaultSkybox){const i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,s=a.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,s)}n.environmentTexture=e.environmentTexture}if(void 0!==a.environmentIntensity&&null!==a.environmentIntensity&&(e.environmentIntensity=a.environmentIntensity),void 0!==a.lights&&null!==a.lights)for(r=0,l=a.lights.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})))}if(void 0!==a.multiMaterials&&null!==a.multiMaterials)for(r=0,l=a.multiMaterials.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)}))}if(void 0!==a.morphTargetManagers&&null!==a.morphTargetManagers)for(const t of a.morphTargetManagers){const i=L_.Parse(t,e);n.morphTargetManagers.push(i),i._parentContainer=n}if(void 0!==a.skeletons&&null!==a.skeletons)for(r=0,l=a.skeletons.length;r{e&&(n.geometries.push(e),e._parentContainer=n)}))}if(void 0!==a.transformNodes&&null!==a.transformNodes)for(r=0,l=a.transformNodes.length;r{t._waitingSubMaterialsUniqueIds.forEach((i=>{t.subMaterials.push(sm(i,e))})),t._waitingSubMaterialsUniqueIds=[]})),e.meshes.forEach((t=>{null!==t._waitingMaterialId&&(t.material=sm(t._waitingMaterialId,e),t._waitingMaterialId=null)})),r=0,l=e.skeletons.length;r{if(t._waitingTransformNodeId){const i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}})),t._hasWaitingData=null)}for(r=0,l=e.meshes.length;r0){for(let i=0;i0){for(let i=0;i{e._loadedUniqueId=""})),p.Parse(a,e,n,i),r=0,l=e.meshes.length;r-1!==e.indexOf("babylon"),importMesh:(e,t,i,s,r,n,o,a)=>{let l="importMesh has failed JSON parse";try{var h=JSON.parse(i);l="";const a=Ro.loggingLevel===Ro.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;const c=[],u=new Map,d=[];if(void 0!==h.transformNodes&&null!==h.transformNodes)for(let e=0,i=h.transformNodes.length;e{!0!==e&&h.geometries[i]&&Array.isArray(h.geometries[i])&&h.geometries[i].forEach((r=>{r.id===_.geometryId&&("vertexData"===i&&br.Parse(r,t,s),e=!0)}))})),!1===e&&J.Warn("Geometry not found for mesh "+_.id)}if(_.materialUniqueId||_.materialId){const e=_.materialUniqueId?p:n;let i=-1!==e.indexOf(_.materialUniqueId||_.materialId);if(!1===i&&void 0!==h.multiMaterials&&null!==h.multiMaterials){const r=(i,r)=>{e.push(i);const n=Z_(r,h,t,s);n&&n.material&&(Q_[n.parsedMaterial.uniqueId||n.parsedMaterial.id]=n.material,l+="\n\tMaterial "+n.material.toString(a))};for(let s=0,n=h.multiMaterials.length;sr(e,(t=>t.uniqueId===e)))):n.materials.forEach((e=>r(e,(t=>t.id===e)))),e.push(n.uniqueId||n.id);const s=On.ParseMultiMaterial(n,t);Q_[n.uniqueId||n.id]=s,s&&(i=!0,l+="\n\tMulti-Material "+s.toString(a));break}}}if(!1===i){e.push(_.materialUniqueId||_.materialId);const i=Z_((e=>_.materialUniqueId&&e.uniqueId===_.materialUniqueId||e.id===_.materialId),h,t,s);i&&i.material?(Q_[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,l+="\n\tMaterial "+i.material.toString(a)):J.Warn("Material not found for mesh "+_.id)}}if(null!==_.skeletonId&&void 0!==_.skeletonId&&-1!==h.skeletonId&&void 0!==h.skeletons&&null!==h.skeletons&&!(i.indexOf(_.skeletonId)>-1))for(let e=0,s=h.skeletons.length;e-1&&void 0!==h.morphTargetManagers&&null!==h.morphTargetManagers&&!(f.indexOf(_.morphTargetManagerId)>-1))for(let e=0,i=h.morphTargetManagers.length;e{e._waitingSubMaterialsUniqueIds.forEach((i=>{e.subMaterials.push(sm(i,t))})),e._waitingSubMaterialsUniqueIds=[]})),t.meshes.forEach((e=>{null!==e._waitingMaterialId&&(e.material=sm(e._waitingMaterialId,t),e._waitingMaterialId=null)}));for(let e=0,i=t.transformNodes.length;e-1&&d.splice(e,1)}_._waitingParentId=null}_._waitingData.lods&&tm(t,_)}for(const e of d)e.dispose();for(let e=0,i=t.skeletons.length;e{if(e._waitingTransformNodeId){const i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}})),i._hasWaitingData=null)}for(let e=0,i=t.meshes.length;e{e._loadedUniqueId=""})),!0}catch(e){const t=em("importMesh",h?h.producer:"Unknown")+l;if(!a)throw J.Log(t),e;a(t,e)}finally{null!==l&&Ro.loggingLevel!==Ro.NO_LOGGING&&J.Log(em("importMesh",h?h.producer:"Unknown")+(Ro.loggingLevel!==Ro.MINIMAL_LOGGING?l:"")),Q_={}}return!1},load:(e,t,i,s)=>{let r="importScene has failed JSON parse";try{var n=JSON.parse(t);switch(r="",void 0!==n.useDelayedTextureLoading&&null!==n.useDelayedTextureLoading&&(e.useDelayedTextureLoading=n.useDelayedTextureLoading&&!Ro.ForceFullSceneLoadingForIncremental),void 0!==n.autoClear&&null!==n.autoClear&&(e.autoClear=n.autoClear),void 0!==n.clearColor&&null!==n.clearColor&&(e.clearColor=j.FromArray(n.clearColor)),void 0!==n.ambientColor&&null!==n.ambientColor&&(e.ambientColor=Y.FromArray(n.ambientColor)),void 0!==n.gravity&&null!==n.gravity&&(e.gravity=w.FromArray(n.gravity)),void 0!==n.useRightHandedSystem&&(e.useRightHandedSystem=!!n.useRightHandedSystem),void 0!==n.fogMode&&null!==n.fogMode&&(e.fogMode=n.fogMode),void 0!==n.fogColor&&null!==n.fogColor&&(e.fogColor=Y.FromArray(n.fogColor)),void 0!==n.fogStart&&null!==n.fogStart&&(e.fogStart=n.fogStart),void 0!==n.fogEnd&&null!==n.fogEnd&&(e.fogEnd=n.fogEnd),void 0!==n.fogDensity&&null!==n.fogDensity&&(e.fogDensity=n.fogDensity),r+="\tFog mode for scene: ",e.fogMode){case 0:r+="none\n";break;case 1:r+="exp\n";break;case 2:r+="exp2\n";break;case 3:r+="linear\n"}if(n.physicsEnabled){let t;"cannon"===n.physicsEngine||n.physicsEngine===k_.name?t=new k_(void 0,void 0,K_.LoaderInjectedPhysicsEngine):"oimo"===n.physicsEngine||n.physicsEngine===G_.name?t=new G_(void 0,K_.LoaderInjectedPhysicsEngine):"ammo"!==n.physicsEngine&&n.physicsEngine!==z_.name||(t=new z_(void 0,K_.LoaderInjectedPhysicsEngine,void 0)),r="\tPhysics engine "+(n.physicsEngine?n.physicsEngine:"oimo")+" enabled\n";const i=n.physicsGravity?w.FromArray(n.physicsGravity):null;e.enablePhysics(i,t)}return void 0!==n.metadata&&null!==n.metadata&&(e.metadata=n.metadata),void 0!==n.collisionsEnabled&&null!==n.collisionsEnabled&&(e.collisionsEnabled=n.collisionsEnabled),!!rm(e,t,i,s,!0)&&(n.autoAnimate&&e.beginAnimation(e,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1),void 0!==n.activeCameraID&&null!==n.activeCameraID&&e.setActiveCameraById(n.activeCameraID),!0)}catch(e){const t=em("importScene",n?n.producer:"Unknown")+r;if(!s)throw J.Log(t),e;s(t,e)}finally{null!==r&&Ro.loggingLevel!==Ro.NO_LOGGING&&J.Log(em("importScene",n?n.producer:"Unknown")+(Ro.loggingLevel!==Ro.MINIMAL_LOGGING?r:""))}return!1},loadAssetContainer:(e,t,i,s)=>rm(e,t,i,s)});class nm{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,Br.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||Y.White(),this.rightColor=e.rightColor||Y.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){const e=new nm;return se.DeepCopy(this,e),e}equals(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled}serialize(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}}static Parse(e){return new nm({isEnabled:e.isEnabled,leftColor:Y.FromArray(e.leftColor),rightColor:Y.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}Pe._FresnelParametersParser=nm.Parse;class om{}om.BindSceneUniformBuffer=on,om.PrepareDefinesForMergedUV=an,om.BindTextureMatrix=ln,om.GetFogState=mn,om.PrepareDefinesForMisc=gn,om.PrepareDefinesForCamera=In,om.PrepareDefinesForFrameBoundValues=Tn,om.PrepareDefinesForBones=Sn,om.PrepareDefinesForMorphTargets=En,om.PrepareDefinesForBakedVertexAnimation=bn,om.PrepareDefinesForAttributes=Cn,om.PrepareDefinesForMultiview=yn,om.PrepareDefinesForOIT=An,om.PrepareDefinesForPrePass=Rn,om.PrepareDefinesForLight=xn,om.PrepareDefinesForLights=vn,om.PrepareUniformsAndSamplersForLight=Pn,om.PrepareUniformsAndSamplersList=Mn,om.HandleFallbacksForShadows=_n,om.PrepareAttributesForMorphTargetsInfluencers=tn,om.PrepareAttributesForMorphTargets=sn,om.PrepareAttributesForBakedVertexAnimation=hn,om.PrepareAttributesForBones=pn,om.PrepareAttributesForInstances=fn,om.PushAttributesForInstances=rn,om.BindLightProperties=function(e,t,i){e.transferToEffect(t,i+"")},om.BindLight=un,om.BindLights=dn,om.BindFogParameters=en,om.BindBonesParameters=cn,om.BindMorphTargetParameters=nn,om.BindLogDepth=Jr;class am extends Cf{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new Y(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}ae([pe(),de("_markAllSubMeshesAsLightsDirty")],am.prototype,"maxSimultaneousLights",void 0),ae([pe(),de("_markAllSubMeshesAsLightsDirty")],am.prototype,"disableLighting",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],am.prototype,"environmentTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],am.prototype,"invertNormalMapX",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],am.prototype,"invertNormalMapY",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],am.prototype,"normalTexture",void 0),ae([_e("emissive"),de("_markAllSubMeshesAsTexturesDirty")],am.prototype,"emissiveColor",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty")],am.prototype,"emissiveTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],am.prototype,"occlusionStrength",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],am.prototype,"occlusionTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],am.prototype,"alphaCutOff",void 0),ae([pe()],am.prototype,"doubleSided",null),ae([fe(),de("_markAllSubMeshesAsTexturesDirty",null)],am.prototype,"lightmapTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],am.prototype,"useLightmapAsShadowmap",void 0);class lm extends am{constructor(e,t){super(e,t),this._useRoughnessFromMetallicTextureAlpha=!1,this._useRoughnessFromMetallicTextureGreen=!0,this._useMetallnessFromMetallicTextureBlue=!0,this.metallic=1,this.roughness=1}getClassName(){return"PBRMetallicRoughnessMaterial"}clone(e){const t=Pe.Clone((()=>new lm(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=Pe.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const s=Pe.Parse((()=>new lm(e.name,t)),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}ae([_e(),de("_markAllSubMeshesAsTexturesDirty","_albedoColor")],lm.prototype,"baseColor",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],lm.prototype,"baseTexture",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],lm.prototype,"metallic",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],lm.prototype,"roughness",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],lm.prototype,"metallicRoughnessTexture",void 0),u("BABYLON.PBRMetallicRoughnessMaterial",lm);class hm extends am{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=Pe.Clone((()=>new hm(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=Pe.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const s=Pe.Parse((()=>new hm(e.name,t)),e,t,i);return e.clearCoat&&s.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&s.anisotropy.parse(e.anisotropy,t,i),e.brdf&&s.brdf.parse(e.brdf,t,i),e.sheen&&s.sheen.parse(e.sheen,t,i),e.subSurface&&s.subSurface.parse(e.subSurface,t,i),e.iridescence&&s.iridescence.parse(e.iridescence,t,i),s}}ae([_e("diffuse"),de("_markAllSubMeshesAsTexturesDirty","_albedoColor")],hm.prototype,"diffuseColor",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],hm.prototype,"diffuseTexture",void 0),ae([_e("specular"),de("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],hm.prototype,"specularColor",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty","_microSurface")],hm.prototype,"glossiness",void 0),ae([fe(),de("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],hm.prototype,"specularGlossinessTexture",void 0),u("BABYLON.PBRSpecularGlossinessMaterial",hm);class cm extends qn{constructor(e,t,i=null){if(super(t),e)if(this._textureMatrix=B.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){const e=this._getEngine();let t;t=e._features.support3DTextures?e.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):e.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=t,this._texture.isReady=!1,this.isCube=!1,this.is3D=e._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;const i=i=>{if("string"!=typeof i)return;let s,r=null,n=null;const o=i.split("\n");let a=0,l=0,h=0,c=0,u=0;for(let e=0;e0&&(e+1)%4==0)r[e]=255;else{const t=n[e];r[e]=t/u*255}t.is3D?(t.updateSize(a,a,a),e.updateRawTexture3D(t,r,5,!1)):(t.updateSize(a*a,a),e.updateRawTexture(t,r,5,!1)),t.isReady=!0,this._triggerOnLoad()},s=this.getScene();return s?s._loadFile(this.url,i):e._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){const e=new cm(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())}static Parse(e,t){let i=null;return e.name&&!e.isRenderTarget&&(i=new cm(e.name,t),i.name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}}cm._NoneEmptyLineRegex=/\S+/,u("BABYLON.ColorGradingTexture",cm);class um extends qn{constructor(e,t,i,s=!1,r=!0,n=null,o=null,a=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=Zn.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=a,this._noMipmap=s,this.gammaSpace=r,this._onLoad=n,this._onError=o,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?n&&(this._texture.isReady?Ii.SetImmediate((()=>n())):this._texture.onLoadedObservable.add(n)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage((()=>this._loadTexture()),this._onError)}_loadImage(e,t){const i=this.getScene();if(!i)return;const s=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,!this._noMipmap,!1,3);s.generateMipMaps=!this._noMipmap,i.addPendingData(s),s.url=this.url,s.isReady=!1,i.getEngine()._internalTexturesCache.push(s),this._texture=s;const r=document.createElement("canvas");ci(this.url,(t=>{this._width=t.width,this._height=t.height,r.width=this._width,r.height=this._height;const i=r.getContext("2d");i.drawImage(t,0,0);const s=i.getImageData(0,0,t.width,t.height);this._buffer=s.data.buffer,r.remove(),e()}),((e,r)=>{i.removePendingData(s),t&&t(`${this.getClassName()} could not be loaded`,r)}),i?i.offlineProvider:null)}_loadTexture(){const e=this.getScene();if(!e)return;const t=(()=>{const e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=M_.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){const s=t[um._FacesMapping[e]];i.push(s)}return i})(),i=this._texture;e.getEngine().updateRawCubeTexture(i,t,i.format,i.type,i.invertY),i.isReady=!0,e.removePendingData(i),i.onLoadedObservable.notifyObservers(i),i.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(3*e.byteLength/4);let s=0;for(let r=0;rt.length)return void J.Error("Unable to load TGA file - Not enough data");i+=s.id_length;let r,n=!1,o=!1,a=!1;switch(s.image_type){case 9:n=!0;case 1:o=!0;break;case 10:n=!0;case 2:break;case 11:n=!0;case 3:a=!0}const l=s.pixel_size>>3,h=s.width*s.height*l;let c,u,d,p,f,_,m;if(o&&(c=t.subarray(i,i+=s.colormap_length*(s.colormap_size>>3))),n){let e,s,n;r=new Uint8Array(h);let o=0;const a=new Uint8Array(l);for(;i>4){default:case 2:u=0,p=1,m=s.width,d=0,f=1,_=s.height;break;case 0:u=0,p=1,m=s.width,d=s.height-1,f=-1,_=-1;break;case 3:u=s.width-1,p=-1,m=-1,d=0,f=1,_=s.height;break;case 1:u=s.width-1,p=-1,m=-1,d=s.height-1,f=-1,_=-1}const g="_getImageData"+(a?"Grey":"")+s.pixel_size+"bits",v=_m[g](s,c,r,d,f,_,u,p,m);e.getEngine()._uploadDataToTextureDirectly(e,v)}dm._DefaultOptions={generateMipMaps:!1,samplingMode:2,format:5,engine:null,scene:null};const _m={GetTGAHeader:pm,UploadContent:fm,_getImageData8bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=t,u=e.width,d=e.height;let p,f,_,m=0;const g=new Uint8Array(u*d*4);for(_=s;_!==n;_+=r)for(f=o;f!==l;f+=a,m++)p=h[m],g[4*(f+u*_)+3]=255,g[4*(f+u*_)+2]=c[3*p+0],g[4*(f+u*_)+1]=c[3*p+1],g[4*(f+u*_)+0]=c[3*p+2];return g},_getImageData16bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,p,f,_=0;const m=new Uint8Array(c*u*4);for(f=s;f!==n;f+=r)for(p=o;p!==l;p+=a,_+=2){d=h[_+0]+(h[_+1]<<8);const e=255*((31744&d)>>10)/31|0,t=255*((992&d)>>5)/31|0,i=255*(31&d)/31|0;m[4*(p+c*f)+0]=e,m[4*(p+c*f)+1]=t,m[4*(p+c*f)+2]=i,m[4*(p+c*f)+3]=32768&d?0:255}return m},_getImageData24bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,p,f=0;const _=new Uint8Array(c*u*4);for(p=s;p!==n;p+=r)for(d=o;d!==l;d+=a,f+=3)_[4*(d+c*p)+3]=255,_[4*(d+c*p)+2]=h[f+0],_[4*(d+c*p)+1]=h[f+1],_[4*(d+c*p)+0]=h[f+2];return _},_getImageData32bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,p,f=0;const _=new Uint8Array(c*u*4);for(p=s;p!==n;p+=r)for(d=o;d!==l;d+=a,f+=4)_[4*(d+c*p)+2]=h[f+0],_[4*(d+c*p)+1]=h[f+1],_[4*(d+c*p)+0]=h[f+2],_[4*(d+c*p)+3]=h[f+3];return _},_getImageDataGrey8bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,p,f,_=0;const m=new Uint8Array(c*u*4);for(f=s;f!==n;f+=r)for(p=o;p!==l;p+=a,_++)d=h[_],m[4*(p+c*f)+0]=d,m[4*(p+c*f)+1]=d,m[4*(p+c*f)+2]=d,m[4*(p+c*f)+3]=255;return m},_getImageDataGrey16bits:function(e,t,i,s,r,n,o,a,l){const h=i,c=e.width,u=e.height;let d,p,f=0;const _=new Uint8Array(c*u*4);for(p=s;p!==n;p+=r)for(d=o;d!==l;d+=a,f+=2)_[4*(d+c*p)+0]=h[f+0],_[4*(d+c*p)+1]=h[f+0],_[4*(d+c*p)+2]=h[f+0],_[4*(d+c*p)+3]=h[f+1];return _}};function mm(){let e=null;function t(e,t,i,s,r){const n=e.getImageTranscodedSizeInBytes(t,i,s);let o=new Uint8Array(n);return e.transcodeImage(o,t,i,s,1,0)?(r&&(o=function(e,t,i,s){const r=new Uint16Array(4),n=new Uint16Array(i*s),o=i/4,a=s/4;for(let t=0;t>2&3],n[h++]=r[l>>4&3],n[h++]=r[l>>6&3]}}return n}(o,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)),o):null}onmessage=i=>{if("init"===i.data.action){if(i.data.url)try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}e||(e=BASIS({wasmBinary:i.data.wasmBinary})),null!==e&&e.then((e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})}))}else if("transcode"===i.data.action){const e=i.data.config,s=i.data.imageData,r=new BASIS.BasisFile(s),n=function(e){const t=e.getHasAlpha(),i=e.getNumImages(),s=[];for(let t=0;t{fm(t,s)}))}}),Br._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=D_.RGBE_ReadHeader(s),n=D_.RGBE_ReadPixels(s,r),o=r.width*r.height,a=new Float32Array(4*o);for(let e=0;e{const e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,a)}))}}),function(e){e[e.cTFETC1=0]="cTFETC1",e[e.cTFETC2=1]="cTFETC2",e[e.cTFBC1=2]="cTFBC1",e[e.cTFBC3=3]="cTFBC3",e[e.cTFBC4=4]="cTFBC4",e[e.cTFBC5=5]="cTFBC5",e[e.cTFBC7=6]="cTFBC7",e[e.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",e[e.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",e[e.cTFASTC_4x4=10]="cTFASTC_4x4",e[e.cTFATC_RGB=11]="cTFATC_RGB",e[e.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",e[e.cTFRGBA32=13]="cTFRGBA32",e[e.cTFRGB565=14]="cTFRGB565",e[e.cTFBGR565=15]="cTFBGR565",e[e.cTFRGBA4444=16]="cTFRGBA4444",e[e.cTFFXT1_RGB=17]="cTFFXT1_RGB",e[e.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",e[e.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",e[e.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",e[e.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"}(gm||(gm={}));const vm={JSModuleURL:`${Ii._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${Ii._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`};let xm=null,Tm=null,Sm=0;const Em=(e,t)=>{const i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise(((e,s)=>{(xm||(xm=new Promise(((e,t)=>{Tm?e(Tm):Ii.LoadFileAsync(Ii.GetBabylonScriptURL(vm.WasmModuleURL)).then((i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");const s=URL.createObjectURL(new Blob([`(${mm})()`],{type:"application/javascript"}));Tm=new Worker(s),function(e,t,i){return new Promise(((s,r)=>{const n=t=>{"init"===t.data.action?(e.removeEventListener("message",n),s(e)):"error"===t.data.action&&r(t.data.error||"error initializing worker")};e.addEventListener("message",n),e.postMessage({action:"init",url:i?Ii.GetBabylonScriptURL(i):void 0,wasmBinary:t},[t])}))}(Tm,i,vm.JSModuleURL).then(e,t)})).catch(t)}))),xm).then((()=>{const r=Sm++,n=t=>{"transcode"===t.data.action&&t.data.id===r&&(Tm.removeEventListener("message",n),t.data.success?e(t.data):s("Transcode is not supported on this device"))};Tm.addEventListener("message",n);const o=new Uint8Array(i.byteLength);o.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),Tm.postMessage({action:"transcode",id:r,imageData:o,config:t,ignoreSupportedFormats:!1},[o.buffer])}),(e=>{s(e)}))}))},bm=(e,t)=>{let i=t._gl?.TEXTURE_2D;e.isCube&&(i=t._gl?.TEXTURE_CUBE_MAP),t._bindTextureDirectly(i,e,!0)},Cm=(e,t)=>{const i=e.getEngine();for(let s=0;s{i._releaseTexture(t),bm(e,i)}))}else{e.width=r.width,e.height=r.height,e.generateMipMaps=t.fileInfo.images[s].levels.length>1;const n=ym.GetInternalFormatFromBasisFormat(t.format,i);e.format=n,bm(e,i),t.fileInfo.images[s].levels.forEach(((t,r)=>{i._uploadCompressedDataToTextureDirectly(e,n,t.width,t.height,t.transcodedPixels,s,r)})),!i._features.basisNeedsPOT||G.Log2(e.width)%1==0&&G.Log2(e.height)%1==0||(Ii.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),e._cachedWrapU=Zn.CLAMP_ADDRESSMODE,e._cachedWrapV=Zn.CLAMP_ADDRESSMODE)}}},ym={JSModuleURL:vm.JSModuleURL,WasmModuleURL:vm.WasmModuleURL,GetInternalFormatFromBasisFormat:(e,t)=>{let i;switch(e){case gm.cTFETC1:i=36196;break;case gm.cTFBC1:i=33776;break;case gm.cTFBC4:i=33779;break;case gm.cTFASTC_4x4:i=37808;break;case gm.cTFETC2:i=37496;break;case gm.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i},TranscodeAsync:Em,LoadTextureFromTranscodeResult:Cm};Object.defineProperty(ym,"JSModuleURL",{get:function(){return vm.JSModuleURL},set:function(e){vm.JSModuleURL=e}}),Object.defineProperty(ym,"WasmModuleURL",{get:function(){return vm.WasmModuleURL},set:function(e){vm.WasmModuleURL=e}}),si._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,s,r){if(Array.isArray(e))return;const n=t.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};Em(e,o).then((e=>{const i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;Cm(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),s&&s()})).catch((e=>{Ii.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,r&&r(e)}))}loadData(e,t,i){const s=t.getEngine().getCaps(),r={supportedCompressionFormats:{etc1:!!s.etc1,s3tc:!!s.s3tc,pvrtc:!!s.pvrtc,etc2:!!s.etc2,astc:!!s.astc,bc7:!!s.bptc}};Em(e,r).then((e=>{const s=e.fileInfo.images[0].levels[0],r=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(s.width,s.height,r,-1!==e.format,(()=>{Cm(t,e)}))})).catch((e=>{Ii.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),Ii.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,(()=>{}),!0)}))}});class Am extends da{get isSupported(){return this._engine?.getCaps().drawBuffersExtension??!1}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,s,r,n,o,a,l,h){for(let c=0;c{this.onAfterRenderObservable.notifyObservers(t)}))}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){const e=this._renderTarget?.textures;if(e){for(let t=e.length-1;t>=0;t--)this._textures[t]._texture=null;this._renderTarget?.dispose(),this._renderTarget=null}}}class Rm{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class Im{constructor(e,t,i,s){return this.name=e,this.meshes=t,this.scene=s,this.options=i,this.options.map=this.options.map??["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=this.options.uvsIn??Ki.UVKind,this.options.uvsOut=this.options.uvsOut??Ki.UVKind,this.options.layout=this.options.layout??Im.LAYOUT_STRIP,this.options.layout===Im.LAYOUT_COLNUM&&(this.options.colnum=this.options.colnum??8),this.options.updateInputMeshes=this.options.updateInputMeshes??!0,this.options.disposeSources=this.options.disposeSources??!0,this._expecting=0,this.options.fillBlanks=this.options.fillBlanks??!0,!0===this.options.fillBlanks&&(this.options.customFillColor=this.options.customFillColor??"black"),this.options.frameSize=this.options.frameSize??256,this.options.paddingRatio=this.options.paddingRatio??.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=this.options.paddingMode??Im.SUBUV_WRAP,this.options.paddingMode===Im.SUBUV_COLOR&&(this.options.paddingColor=this.options.paddingColor??new j(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){const t=this._calculateSize(),i=new N(1,1).divide(t);let s=0;const r=this._expecting,n=this.meshes.length,o=Object.keys(this.sets);for(let e=0;e{this._calculateMeshUVFrames(a,l,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i{s++,d.update(!1);const i=p.getImageData(0,0,h,h),n=this.sets[m];if(n.getContext().putImageData(i,t.x*f.x,t.y*f.y),d.dispose(),n.update(!1),s==r)return c(),void e()},m=o[u]||"_blank";if(n&&null!==n[m]){const e=n[m],t=new Image;t.src=e instanceof ph?e.getContext().canvas.toDataURL("image/png"):e.url,Ii.SetCorsBehavior(t.src,t),t.onload=()=>{p.fillStyle="rgba(0,0,0,0)",p.fillRect(0,0,h,h),d.update(!1),p.setTransform(1,0,0,-1,0,0);const e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let i=0;i<9;i++)p.drawImage(t,0,0,t.width,t.height,l+a*e[i],l+a*e[i+1]-h,a,a);break;case 1:for(let i=0;i{e.dispose&&e.dispose()};for(let e=0;e{try{if(0===this.meshes.length)return void e();let t=0;const i=i=>{if(t++,this.options.map){for(let e=0;e{i(n)}));else if(t++,t===this.meshes.length)return this._createFrames(e)}}catch(e){return t(e)}}))}dispose(){const e=Object.keys(this.sets);for(let t=0;t{const i={name:this.name,sets:{},options:{},frames:[]},s=Object.keys(this.sets),r=Object.keys(this.options);try{for(let r=0;r!0)){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesIndices"===e.name&&t(e)));i||(i=new Go("matricesIndices"),i.setAsAttribute("matricesIndices")),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesWeights"===e.name&&t(e)));i||(i=new Go("matricesWeights"),i.setAsAttribute("matricesWeights")),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.World&&t(e)));i||(i=new Go("world"),i.setAsSystemValue(yo.World)),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){cn(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&Sn(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");const t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});const i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});const s=this._outputs[0],r=this.world;return e.compilationString+="#if NUM_BONE_INFLUENCERS>0\n",e.compilationString+=e._declareOutput(s)+` = ${r.associatedVariableName} * ${i};\n`,e.compilationString+="#else\n",e.compilationString+=e._declareOutput(s)+` = ${r.associatedVariableName};\n`,e.compilationString+="#endif\n",this}}),u("BABYLON.InstancesBlock",class extends No{constructor(e){super(e,To.Vertex),this.registerInput("world0",xo.Vector4),this.registerInput("world1",xo.Vector4),this.registerInput("world2",xo.Vector4),this.registerInput("world3",xo.Vector4),this.registerInput("world",xo.Matrix,!0),this.registerOutput("output",xo.Matrix),this.registerOutput("instanceID",xo.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e,t=(()=>!0)){if(!this.world0.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world0"===e.name&&t(e)));i||(i=new Go("world0"),i.setAsAttribute("world0")),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world1"===e.name&&t(e)));i||(i=new Go("world1"),i.setAsAttribute("world1")),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world2"===e.name&&t(e)));i||(i=new Go("world2"),i.setAsAttribute("world2")),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world3"===e.name&&t(e)));i||(i=new Go("world3"),i.setAsAttribute("world3")),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"world"===e.name&&t(e)));i||(i=new Go("world"),i.setAsSystemValue(yo.World)),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,s=!1,r){let n=!1;i.INSTANCES!==s&&(i.setValue("INSTANCES",s),n=!0),r&&i.THIN_INSTANCES!==!!r?.getRenderingMesh().hasThinInstances&&(i.setValue("THIN_INSTANCES",!!r?.getRenderingMesh().hasThinInstances),n=!0),n&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);const t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);const i=this._outputs[0],s=this._outputs[1],r=this.world0,n=this.world1,o=this.world2,a=this.world3;let l="mat4",h="gl_InstanceID",c="float";return e.shaderLanguage===ht.WGSL&&(l="mat4x4f",h="vertexInputs.instanceIndex",c="f32"),e.compilationString+="#ifdef INSTANCES\n",e.compilationString+=e._declareOutput(i)+` = ${l}(${r.associatedVariableName}, ${n.associatedVariableName}, ${o.associatedVariableName}, ${a.associatedVariableName});\n`,e.compilationString+="#ifdef THIN_INSTANCES\n",e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName};\n`,e.compilationString+="#endif\n",t._caps.canUseGLInstanceID?e.compilationString+=e._declareOutput(s)+` = ${c}(${h});\n`:e.compilationString+=e._declareOutput(s)+" = 0.0;\n",e.compilationString+="#else\n",e.compilationString+=e._declareOutput(i)+` = ${this.world.associatedVariableName};\n`,e.compilationString+=e._declareOutput(s)+" = 0.0;\n",e.compilationString+="#endif\n",this}});class Dm extends No{constructor(e){super(e,To.Vertex),this.registerInput("position",xo.Vector3),this.registerInput("normal",xo.Vector3),this.registerInput("tangent",xo.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(xo.Color4|xo.Vector4|xo.Vector3),this.registerInput("uv",xo.Vector2),this.registerOutput("positionOutput",xo.Vector3),this.registerOutput("normalOutput",xo.Vector3),this.registerOutput("tangentOutput",xo.Vector4),this.registerOutput("uvOutput",xo.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Go("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Go("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&t(e)));i||(i=new Go("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Go("uv"),i.setAsAttribute("uv")),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const t=e.morphTargetManager;t?.isUsingTextureForTargets&&(t.numMaxInfluencers||t.numInfluencers)!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&En(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(nn(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,s){const r=this.position,n=this.normal,o=this.tangent,a=this.uv,l=this.positionOutput,h=this.normalOutput,c=this.tangentOutput,u=this.uvOutput,d=e,p=s.NUM_MORPH_INFLUENCERS,f=i.morphTargetManager,_=f&&f.supportsNormals&&s.NORMAL,m=f&&f.supportsTangents&&s.TANGENT,g=f&&f.supportsUVs&&s.UV1;let v="";f?.isUsingTextureForTargets&&p>0&&(v+=`${d._declareLocalVar("vertexID",xo.Float)};\n`),v+="#ifdef MORPHTARGETS\n";const x=d.shaderLanguage===ht.WGSL,T=x?"uniforms.":"";if(f?.isUsingTextureForTargets)v+=`for (${x?"var":"int"} i = 0; i < NUM_MORPH_INFLUENCERS; i++) {\n`,v+=`if (i >= ${T}morphTargetCount) { break; }\n`,v+=`vertexID = ${x?"f32(vertexInputs.vertexIndex":"float(gl_VertexID"}) * ${T}morphTargetTextureInfo.x;\n`,v+=`${l.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${r.associatedVariableName}) * ${T}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",_&&(v+="#ifdef MORPHTARGETS_NORMAL\n",v+=`${h.associatedVariableName} += (readVector3FromRawSampler(i, vertexID) - ${n.associatedVariableName}) * ${T}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),g&&(v+="#ifdef MORPHTARGETS_UV\n",v+=`${u.associatedVariableName} += (readVector3FromRawSampler(i, vertexID).xy - ${a.associatedVariableName}) * ${T}morphTargetInfluences[i];\n`,v+="vertexID += 1.0;\n",v+="#endif\n"),m&&(v+="#ifdef MORPHTARGETS_TANGENT\n",v+=`${c.associatedVariableName}.xyz += (readVector3FromRawSampler(i, vertexID) - ${o.associatedVariableName}.xyz) * ${T}morphTargetInfluences[i];\n`,o.type===xo.Vector4?v+=`${c.associatedVariableName}.w = ${o.associatedVariableName}.w;\n`:v+=`${c.associatedVariableName}.w = 1.;\n`,v+="#endif\n"),v+="}\n";else for(let e=0;e0)for(let e=0;e!0)){if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.isSystemValue&&e.systemValue===yo.World&&t(e)));i||(i=new Go("world"),i.setAsSystemValue(yo.World)),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name&&t(e)));i||(i=new Go("normal"),i.setAsAttribute("normal")),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&e.type===xo.Vector4&&t(e)));i||(i=new Go("tangent"),i.setAsAttribute("tangent")),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){const s=this.normal,r=this.tangent;let n=s.isConnected;s.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(s.connectInputBlock?.name)&&(n=!1);let o=r.isConnected;r.connectInputBlock?.isAttribute&&!e.isVerticesDataPresent(r.connectInputBlock?.name)&&(o=!1);const a=n&&o;i.setValue("TBNBLOCK",a,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,s=this.world,r=this.TBN,n=this.row0,o=this.row1,a=this.row2,l=e.shaderLanguage===ht.WGSL,h=l?"mat3x3f":"mat3",c=l?"f":"";return e.target===To.Fragment&&(e.compilationString+=`\n // ${this.name}\n ${e._declareLocalVar("tbnNormal",xo.Vector3)} = normalize(${t.associatedVariableName}).xyz;\n ${e._declareLocalVar("tbnTangent",xo.Vector3)} = normalize(${i.associatedVariableName}.xyz);\n ${e._declareLocalVar("tbnBitangent",xo.Vector3)} = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w;\n ${l?"var":"mat3"} ${r.associatedVariableName} = ${h}(${s.associatedVariableName}[0].xyz, ${s.associatedVariableName}[1].xyz, ${s.associatedVariableName}[2].xyz) * ${h}(tbnTangent, tbnBitangent, tbnNormal);\n `,n.hasEndpoints&&(e.compilationString+=e._declareOutput(n)+` = vec3${c}(${r.associatedVariableName}[0][0], ${r.associatedVariableName}[0][1], ${r.associatedVariableName}[0][2]);\n`),o.hasEndpoints&&(e.compilationString+=e._declareOutput(o)+` = vec3${c}(${r.associatedVariableName}[1[0], ${r.associatedVariableName}[1][1], ${r.associatedVariableName}[1][2]);\n`),a.hasEndpoints&&(e.compilationString+=e._declareOutput(a)+` = vec3${c}(${r.associatedVariableName}[2][0], ${r.associatedVariableName}[2][1], ${r.associatedVariableName}[2][2]);\n`),e.sharedData.blocksWithDefines.push(this)),this}}u("BABYLON.TBNBlock",Nm);class wm extends No{constructor(e){super(e,To.Fragment),this._tangentSpaceParameterName="",this._tangentCorrectionFactorName="",this._worldMatrixName="",this.invertX=!1,this.invertY=!1,this.useParallaxOcclusion=!1,this.useObjectSpaceNormalMap=!1,this._isUnique=!0,this.registerInput("worldPosition",xo.Vector4,!1),this.registerInput("worldNormal",xo.Vector4,!1),this.registerInput("worldTangent",xo.Vector4,!0),this.registerInput("uv",xo.Vector2,!1),this.registerInput("normalMapColor",xo.Color3,!1),this.registerInput("strength",xo.Float,!1),this.registerInput("viewDirection",xo.Vector3,!0),this.registerInput("parallaxScale",xo.Float,!0),this.registerInput("parallaxHeight",xo.Float,!0),this.registerInput("TBN",xo.Object,!0,To.VertexAndFragment,new Mm("TBN",this,Eo.Input,Nm,"TBNBlock")),this.registerInput("world",xo.Matrix,!0),this.registerOutput("output",xo.Vector4),this.registerOutput("uvOffset",xo.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}prepareDefines(e,t,i){const s=this.normalMapColor.connectedPoint._ownerBlock.samplerName,r=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&s||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",r,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name&&t(e)));i||(i=new Go("uv"),i.setAsAttribute()),i.output.connectTo(this.uv)}if(!this.strength.isConnected){const e=new Go("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,s=this.worldPosition,r=this.worldNormal,n=this.worldTangent,o=e.shaderLanguage===ht.WGSL,a=o?"mat3x3f":"mat3",l=o?"f":"",h=o?"uniforms.":"";e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,xo.Vector2),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,xo.Float),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,xo.Matrix);let c=null;this.normalMapColor.connectedPoint&&(c=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const u=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&c||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),d=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",p=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${e._emitFloat(this.strength.connectInputBlock.value)}`:`\n#if !defined(NORMALXYSCALE)\n1.0/\n#endif\n${this.strength.associatedVariableName}`;o||e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const f={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},_=this.TBN;_.isConnected?e.compilationString+=`\n #ifdef TBNBLOCK\n ${o?"var":"mat3"} vTBN = ${_.associatedVariableName};\n #endif\n `:n.isConnected&&(e.compilationString+=`${e._declareLocalVar("tbnNormal",xo.Vector3)} = normalize(${r.associatedVariableName}.xyz);\n`,e.compilationString+=`${e._declareLocalVar("tbnTangent",xo.Vector3)} = normalize(${n.associatedVariableName}.xyz);\n`,e.compilationString+=`${e._declareLocalVar("tbnBitangent",xo.Vector3)} = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\n`,e.compilationString+=`${o?"var":"mat3"} vTBN = ${a}(tbnTangent, tbnBitangent, tbnNormal);\n`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[f,{search:/varying mat3 vTBN;/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]});const m=o?"fn parallaxOcclusion(vViewDirCoT: vec3f, vNormalCoT: vec3f, texCoord: vec2f, parallaxScale:f32, bump: texture_2d, bumpSampler: sampler)":"#define inline\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)",g=o?/fn parallaxOcclusion\(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32\)/g:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,v=o?"fn parallaxOffset(viewDir: vec3f, heightScale: f32, height_: f32)":"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)",x=o?/fn parallaxOffset\(viewDir: vec3f,heightScale: f32\)/g:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g;e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:g,replace:m},{search:x,replace:v},{search:/texture.+?bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const T=u&&c?`${o?`textureSample(${c}, ${c+"Sampler"}`:`texture2D(${c}`}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName,S=e._getFreeVariableName("tempOutput");return e.compilationString+=e._declareLocalVar(S,xo.Vector3)+` = vec3${l}(0.);\n`,e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture.+?bumpSampler,vBumpUV\)/g,replace:`${T}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`${e._declareLocalVar("normalMatrix",xo.Matrix)} = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture.+?bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${T}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${o?u&&this.useParallaxOcclusion?`${c}, ${c+"Sampler"}`:"bump, bumpSampler":u&&this.useParallaxOcclusion?c:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${u?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:h+this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:p},{search:/vBumpInfos.z/g,replace:d},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:s.associatedVariableName+".xyz"},{search:/normalW=/g,replace:S+" = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:`${a}(normalMatrix) * `+S},{search:/normalW/g,replace:r.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:u?this.viewDirection.associatedVariableName:`vec3${l}(0.)`},f]}),e.compilationString+=e._declareOutput(this.output)+` = vec4${l}(${S}, 0.);\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX};\n`;return e+=`${this._codeVariableName}.invertY = ${this.invertY};\n`,e+=`${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};\n`,e+=`${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};\n`,e}serialize(){const e=super.serialize();return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!e.useObjectSpaceNormalMap}}ae([Lo("Invert X axis",bo.Boolean,"PROPERTIES",{notifiers:{update:!1}})],wm.prototype,"invertX",void 0),ae([Lo("Invert Y axis",bo.Boolean,"PROPERTIES",{notifiers:{update:!1}})],wm.prototype,"invertY",void 0),ae([Lo("Use parallax occlusion",bo.Boolean)],wm.prototype,"useParallaxOcclusion",void 0),ae([Lo("Object Space Mode",bo.Boolean,"PROPERTIES",{notifiers:{update:!1}})],wm.prototype,"useObjectSpaceNormalMap",void 0),u("BABYLON.PerturbNormalBlock",wm),u("BABYLON.DiscardBlock",class extends No{constructor(e){super(e,To.Fragment,!0),this.registerInput("value",xo.Float,!0),this.registerInput("cutoff",xo.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) { discard; }\n`,this}}),u("BABYLON.FrontFacingBlock",class extends No{constructor(e){super(e,To.Fragment),this.registerOutput("output",xo.Float,To.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===To.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary("1.0","0.0",e.shaderLanguage===ht.GLSL?"gl_FrontFacing":"fragmentInputs.frontFacing")};\n`,this}}),u("BABYLON.DerivativeBlock",class extends No{constructor(e){super(e,To.Fragment),this.registerInput("input",xo.AutoDetect,!1),this.registerOutput("dx",xo.BasedOnInput),this.registerOutput("dy",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._outputs[1];e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let s="dFdx",r="dFdy";return e.shaderLanguage===ht.WGSL&&(s="dpdx",r="dpdy"),t.hasEndpoints&&(e.compilationString+=e._declareOutput(t)+` = ${s}(${this.input.associatedVariableName});\n`),i.hasEndpoints&&(e.compilationString+=e._declareOutput(i)+` = ${r}(${this.input.associatedVariableName});\n`),this}}),u("BABYLON.FragCoordBlock",class extends No{constructor(e){super(e,To.Fragment),this.registerOutput("xy",xo.Vector2,To.Fragment),this.registerOutput("xyz",xo.Vector3,To.Fragment),this.registerOutput("xyzw",xo.Vector4,To.Fragment),this.registerOutput("x",xo.Float,To.Fragment),this.registerOutput("y",xo.Float,To.Fragment),this.registerOutput("z",xo.Float,To.Fragment),this.registerOutput("w",xo.Float,To.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";const i=e.shaderLanguage===ht.WGSL?"fragmentInputs.position":"gl_FragCoord";for(const s of this._outputs)s.hasEndpoints&&(t+=`${e._declareOutput(s)} = ${i}.${s.name};\n`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===To.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}),u("BABYLON.ScreenSizeBlock",class extends No{constructor(e){super(e,To.Fragment),this.registerOutput("xy",xo.Vector2,To.Fragment),this.registerOutput("x",xo.Float,To.Fragment),this.registerOutput("y",xo.Float,To.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){const t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(const s of this._outputs)s.hasEndpoints&&(i+=`${e._declareOutput(s)} = ${t}.${s.name};\n`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===To.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,xo.Vector2);const t=e.shaderLanguage===ht.WGSL?"uniforms.":"";return e.compilationString+=this.writeOutputs(e,t+this._varName),this}}),u("BABYLON.ScreenSpaceBlock",class extends No{constructor(e){super(e,To.Fragment),this.registerInput("vector",xo.AutoDetect),this.registerInput("worldViewProjection",xo.Matrix),this.registerOutput("output",xo.Vector2),this.registerOutput("x",xo.Float),this.registerOutput("y",xo.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e,t=(()=>!0)){if(!this.worldViewProjection.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.WorldViewProjection&&t(e)));i||(i=new Go("worldViewProjection"),i.setAsSystemValue(yo.WorldViewProjection)),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const s=i.associatedVariableName,r=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case xo.Vector3:e.compilationString+=`${e._declareLocalVar(r,xo.Vector4)} = ${s} * vec4${e.fSuffix}(${t.associatedVariableName}, 1.0);\n`;break;case xo.Vector4:e.compilationString+=`${e._declareLocalVar(r,xo.Vector4)} = ${s} * ${t.associatedVariableName};\n`}return e.compilationString+=`${r} = vec4${e.fSuffix}(${r}.xy / ${r}.w, ${r}.zw);`,e.compilationString+=`${r} = vec4${e.fSuffix}(${r}.xy * 0.5 + vec2${e.fSuffix}(0.5, 0.5), ${r}.zw);`,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${r}.xy;\n`),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${r}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${r}.y;\n`),this}}),u("BABYLON.TwirlBlock",class extends No{constructor(e){super(e,To.Fragment),this.registerInput("input",xo.Vector2),this.registerInput("strength",xo.Float),this.registerInput("center",xo.Vector2),this.registerInput("offset",xo.Vector2),this.registerOutput("output",xo.Vector2),this.registerOutput("x",xo.Float),this.registerOutput("y",xo.Float)}getClassName(){return"TwirlBlock"}get input(){return this._inputs[0]}get strength(){return this._inputs[1]}get center(){return this._inputs[2]}get offset(){return this._inputs[3]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(){if(!this.center.isConnected){const e=new Go("center");e.value=new N(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new Go("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new Go("offset");e.value=new N(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),s=e._getFreeVariableName("x"),r=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=` \n ${e._declareLocalVar(t,xo.Vector2)} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName};\n ${e._declareLocalVar(i,xo.Float)} = ${this.strength.associatedVariableName} * length(${t});\n ${e._declareLocalVar(s,xo.Float)} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y;\n ${e._declareLocalVar(r,xo.Float)} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y;\n ${e._declareLocalVar(n,xo.Vector2)} = vec2(${s} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${r} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y);\n `,this.output.hasEndpoints&&(e.compilationString+=e._declareOutput(this.output)+` = ${n};\n`),this.x.hasEndpoints&&(e.compilationString+=e._declareOutput(this.x)+` = ${n}.x;\n`),this.y.hasEndpoints&&(e.compilationString+=e._declareOutput(this.y)+` = ${n}.y;\n`),this}});class Fm extends No{constructor(e){super(e,To.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",xo.Float),this.registerInput("worldPosition",xo.Vector3),this.registerInput("worldNormal",xo.Vector3),this.registerInput("worldTangent",xo.AutoDetect,!0),this.registerOutput("output",xo.Vector4),this.registerOutput("xyz",xo.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e.shaderLanguage===ht.WGSL,s=e.fSuffix;this.generateInWorldSpace||this.worldTangent.isConnected||J.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const r=this.generateInWorldSpace?"":"\n vec3 biTangent = cross(norm, tgt);\n mat3 TBN = mat3(tgt, biTangent, norm);\n ",n=this.generateInWorldSpace?"":"\n result = TBN * result;\n result = result * vec3(0.5) + vec3(0.5);\n ";let o=`\n vec4 heightToNormal(float height, vec3 position, vec3 tangent, vec3 normal) {\n vec3 tgt = ${this.automaticNormalizationTangent?"normalize(tangent);":"tangent;"}\n vec3 norm = ${this.automaticNormalizationNormal?"normalize(normal);":"normal;"}\n ${r}\n vec3 worlddX = dFdx(position);\n vec3 worlddY = dFdy(position);\n vec3 crossX = cross(norm, worlddX);\n vec3 crossY = cross(norm, worlddY);\n float d = abs(dot(crossY, worlddX));\n vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));\n inToNormal.y *= -1.0;\n vec3 result = normalize((d * norm) - inToNormal);\n ${n}\n return vec4(result, 0.);\n }`;return i?o=e._babylonSLtoWGSL(o):e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",o,"// heightToNormal"),e.compilationString+=e._declareOutput(t)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:`vec3${s}(0.)`}.xyz, ${this.worldNormal.associatedVariableName});\n`,this.xyz.hasEndpoints&&(e.compilationString+=e._declareOutput(this.xyz)+` = ${this.output.associatedVariableName}.xyz;\n`),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};\n`,e+=`${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};\n`,e+=`${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};\n`,e}serialize(){const e=super.serialize();return e.generateInWorldSpace=this.generateInWorldSpace,e.automaticNormalizationNormal=this.automaticNormalizationNormal,e.automaticNormalizationTangent=this.automaticNormalizationTangent,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.generateInWorldSpace=e.generateInWorldSpace,this.automaticNormalizationNormal=e.automaticNormalizationNormal,this.automaticNormalizationTangent=e.automaticNormalizationTangent}}ae([Lo("Generate in world space instead of tangent space",bo.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Fm.prototype,"generateInWorldSpace",void 0),ae([Lo("Force normalization for the worldNormal input",bo.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Fm.prototype,"automaticNormalizationNormal",void 0),ae([Lo("Force normalization for the worldTangent input",bo.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Fm.prototype,"automaticNormalizationTangent",void 0),u("BABYLON.HeightToNormalBlock",Fm),u("BABYLON.FragDepthBlock",class extends No{constructor(e){super(e,To.Fragment,!0),this.registerInput("depth",xo.Float,!0),this.registerInput("worldPos",xo.Vector4,!0),this.registerInput("viewProjection",xo.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){super._buildBlock(e);const t=e.shaderLanguage===ht.GLSL?"gl_FragDepth":"fragmentOutputs.fragDepth";return this.depth.isConnected?e.compilationString+=`${t} = ${this.depth.associatedVariableName};\n`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=`\n ${e._declareLocalVar("p",xo.Vector4)} = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName};\n ${e._declareLocalVar("v",xo.Vector4)} = p.z / p.w;\n #ifndef IS_NDC_HALF_ZRANGE\n v = v * 0.5 + 0.5;\n #endif\n ${t} = v;\n \n `:J.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}),u("BABYLON.ShadowMapBlock",class extends No{constructor(e){super(e,To.Fragment),this.registerInput("worldPosition",xo.Vector4,!1),this.registerInput("viewProjection",xo.Matrix,!1),this.registerInput("worldNormal",xo.AutoDetect,!0),this.registerOutput("depth",xo.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM")}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitUniformFromString("biasAndScaleSM",xo.Vector3),e._emitUniformFromString("lightDataSM",xo.Vector3),e._emitUniformFromString("depthValuesSM",xo.Vector3),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`vec4 worldPos = ${this.worldPosition.associatedVariableName};\n`,e.compilationString+="vec3 vPositionWSM;\n",e.compilationString+="float vDepthMetricSM = 0.0;\n",e.compilationString+="float zSM;\n",this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos;\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+="\n #if SM_DEPTHTEXTURE == 1\n #ifdef IS_NDC_HALF_ZRANGE\n gl_FragDepth = (clipPos.z / clipPos.w);\n #else\n gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5;\n #endif\n #endif\n ",e.compilationString+=`${e._declareOutput(this.depth)} = vec3(depthSM, 1., 1.);\n`,this}}),u("BABYLON.PrePassOutputBlock",class extends No{constructor(e){super(e,To.Fragment,!0),this.registerInput("viewDepth",xo.Float,!0),this.registerInput("worldPosition",xo.AutoDetect,!0),this.registerInput("viewNormal",xo.AutoDetect,!0),this.registerInput("reflectivity",xo.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(xo.Vector3|xo.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(xo.Vector3|xo.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(xo.Vector3|xo.Vector4|xo.Color3|xo.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}get reflectivity(){return this._inputs[3]}_buildBlock(e){super._buildBlock(e);const t=this.worldPosition,i=this.viewNormal,s=this.viewDepth,r=this.reflectivity;e.sharedData.blocksWithDefines.push(this);const n=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",n),e.compilationString+="#if defined(PREPASS)\r\n",e.compilationString+="#ifdef PREPASS_DEPTH\r\n",s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${s.associatedVariableName}, 0.0, 0.0, 1.0);\r\n`:e.compilationString+=" gl_FragData[PREPASS_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_POSITION\r\n",t.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===xo.Vector4?t.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_NORMAL\r\n",i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===xo.Vector4?i.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#ifdef PREPASS_REFLECTIVITY\r\n",r.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(${r.associatedVariableName}.rgb, ${r.connectedPoint.type===xo.Vector4?r.associatedVariableName+".a":"1.0"});\r\n`:e.compilationString+=" gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r\n",e.compilationString+="#endif\r\n",e.compilationString+="#endif\r\n",this}}),u("BABYLON.FogBlock",class extends No{constructor(e){super(e,To.VertexAndFragment,!1),this.registerInput("worldPosition",xo.Vector4,!1,To.Vertex),this.registerInput("view",xo.Matrix,!1,To.Vertex),this.registerInput("input",xo.AutoDetect,!1,To.Fragment),this.registerInput("fogColor",xo.AutoDetect,!1,To.Fragment),this.registerOutput("output",xo.Color3,To.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e,t=(()=>!0)){if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.View&&t(e)));i||(i=new Go("view"),i.setAsSystemValue(yo.View)),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.FogColor&&t(e)));i||(i=new Go("fogColor",void 0,xo.Color3),i.setAsSystemValue(yo.FogColor)),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const s=e.getScene();i.setValue("FOG",t.fogEnabled&&mn(e,s))}bind(e,t,i){if(!i)return;const s=i.getScene();e.setFloat4(this._fogParameters,s.fogMode,s.fogStart,s.fogEnd,s.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===To.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=[],i="",s="";e.shaderLanguage===ht.WGSL?(t=[{search:/fn CalcFogFactor\(\)/,replace:"fn CalcFogFactor(vFogDistance: vec3f, vFogInfos: vec4f)"},{search:/uniforms.vFogInfos/g,replace:"vFogInfos"},{search:/fragmentInputs.vFogDistance/g,replace:"vFogDistance"}],i="fragmentInputs.",s="uniforms."):t=[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}],e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:t});const r=e._getFreeVariableName("fog"),n=this.input,o=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const a=this._outputs[0];e._emitUniformFromString(this._fogParameters,xo.Vector4),e.compilationString+="#ifdef FOG\n",e.compilationString+=`${e._declareLocalVar(r,xo.Float)} = CalcFogFactor(${i}${this._fogDistanceName}, ${s}${this._fogParameters});\n`,e.compilationString+=e._declareOutput(a)+` = ${r} * ${n.associatedVariableName}.rgb + (1.0 - ${r}) * ${o.associatedVariableName}.rgb;\n`,e.compilationString+=`#else\n${e._declareOutput(a)} = ${n.associatedVariableName}.rgb;\n`,e.compilationString+="#endif\n"}else{const t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,xo.Vector3);const s=e.shaderLanguage===ht.WGSL?"vertexOutputs.":"";e.compilationString+=`${s}${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz;\n`}return this}});class Lm extends No{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,J.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?To.Fragment:To.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?To.Fragment:To.Vertex}constructor(e){super(e,To.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",xo.Vector4,!1,To.Vertex),this.registerInput("worldNormal",xo.Vector4,!1,To.Fragment),this.registerInput("cameraPosition",xo.Vector3,!1,To.Fragment),this.registerInput("glossiness",xo.Float,!0,To.Fragment),this.registerInput("glossPower",xo.Float,!0,To.Fragment),this.registerInput("diffuseColor",xo.Color3,!0,To.Fragment),this.registerInput("specularColor",xo.Color3,!0,To.Fragment),this.registerInput("view",xo.Matrix,!0),this.registerOutput("diffuseOutput",xo.Color3,To.Fragment),this.registerOutput("specularOutput",xo.Color3,To.Fragment),this.registerOutput("shadow",xo.Float,To.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.CameraPosition&&t(e)));i||(i=new Go("cameraPosition"),i.setAsSystemValue(yo.CameraPosition)),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const s=e.getScene();if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};xn(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else vn(s,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;Pn(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,t)}}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?un(this.light,this._lightId,s,e,!0):dn(s,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,xo.Vector4)&&(e.compilationString+=(e.shaderLanguage===ht.WGSL?"vertexOutputs.":"")+`${s} = ${t.associatedVariableName};\n`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`${e._declareLocalVar("worldPos",xo.Vector4)} = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`${e._declareLocalVar("view",xo.Matrix)} = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_injectUBODeclaration(e){const t=`//${this.name}`;this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0})}_buildBlock(e){super._buildBlock(e);const t=e.shaderLanguage===ht.WGSL,i=t?"f":"",s=`//${this.name}`;if(e.target!==To.Fragment)return void this._injectVertexCode(e);this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const r=e.shaderLanguage===ht.WGSL?"fragmentInputs.":"";e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const n=this.worldPosition;let o=n.associatedVariableName;this.generateOnlyFragmentCode?(o=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`${e._declareLocalVar(o,xo.Vector3)};\n`,s),e.compilationString+=`${o} = ${n.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${n.associatedVariableName}`:void 0})):o=r+"v_"+o+".xyz",e._emitFunctionFromInclude("helperFunctions",s),e._emitFunctionFromInclude("lightsFragmentFunctions",s,{replaceStrings:[{search:/vPositionW/g,replace:o}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",s,{replaceStrings:[{search:/vPositionW/g,replace:o}]}),this._injectUBODeclaration(e),0===this._lightId&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`${e._declareLocalVar("viewDirectionW",xo.Vector3)} = normalize(${this.cameraPosition.associatedVariableName} - ${o});\n`),e.compilationString+=t?"var info: lightingInfo;\n":"lightingInfo info;\n",e.compilationString+=`${e._declareLocalVar("shadow",xo.Float)} = 1.;\n`,e.compilationString+=`${e._declareLocalVar("aggShadow",xo.Float)} = 0.;\n`,e.compilationString+=`${e._declareLocalVar("numLights",xo.Float)} = 0.;\n`,e.compilationString+=`${e._declareLocalVar("glossiness",xo.Float)} = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"};\n`,e.compilationString+=`${e._declareLocalVar("diffuseBase",xo.Vector3)} = vec3${i}(0., 0., 0.);\n`,e.compilationString+=`${e._declareLocalVar("specularBase",xo.Vector3)} = vec3${i}(0., 0., 0.);\n`,e.compilationString+=`${e._declareLocalVar("normalW",xo.Vector3)} = ${this.worldNormal.associatedVariableName}.xyz;\n`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:o+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",s,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${o}.xyz`}),0===this._lightId&&(e.compilationString+="aggShadow = aggShadow / numLights;\n");const a=this.diffuseOutput,l=this.specularOutput;return e.compilationString+=e._declareOutput(a)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""};\n`,l.hasEndpoints&&(e.compilationString+=e._declareOutput(l)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""};\n`),this.shadow.hasEndpoints&&(e.compilationString+=e._declareOutput(this.shadow)+" = aggShadow;\n"),this}serialize(){const e=super.serialize();return e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}ae([Lo("Generate only fragment code",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Lm._OnGenerateOnlyFragmentCodeChanged}})],Lm.prototype,"generateOnlyFragmentCode",void 0),u("BABYLON.LightBlock",Lm);class Bm extends No{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??y.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get samplerName(){return this._samplerName}constructor(e){super(e,To.VertexAndFragment),this.registerOutput("source",xo.Object,To.VertexAndFragment,new Mm("source",this,Eo.Output,Bm,"ImageSourceBlock"))}bind(e){this.texture&&e.setTexture(this._samplerName,this.texture)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}getClassName(){return"ImageSourceBlock"}get source(){return this._outputs[0]}_buildBlock(e){return super._buildBlock(e),e.target===To.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Texture"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i,s){super._deserialize(e,t,i,s),e.texture&&!xa.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(0===e.texture.url.indexOf("data:")?i="":s&&(e.texture.url=s(e.texture.url),e.texture.name=e.texture.url),this.texture=Zn.Parse(e.texture,t,i))}}u("BABYLON.ImageSourceBlock",Bm);class Vm extends No{get texture(){return this.source.isConnected?(this.source.connectedPoint?.ownerBlock).texture:this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??y.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _IsPrePassTextureBlock(e){return"PrePassTextureBlock"===e?.getClassName()}get _isSourcePrePass(){return Vm._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!Vm._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=this.texture.getScene()??y.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??y.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?To.Fragment:To.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",xo.AutoDetect,!1,To.VertexAndFragment),this.registerInput("source",xo.Object,!0,To.VertexAndFragment,new Mm("source",this,Eo.Input,Bm,"ImageSourceBlock")),this.registerInput("layer",xo.Float,!0),this.registerInput("lod",xo.Float,!0),this.registerOutput("rgba",xo.Color4,To.Neutral),this.registerOutput("rgb",xo.Color3,To.Neutral),this.registerOutput("r",xo.Float,To.Neutral),this.registerOutput("g",xo.Float,To.Neutral),this.registerOutput("b",xo.Float,To.Neutral),this.registerOutput("a",xo.Float,To.Neutral),this.registerOutput("level",xo.Float,To.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Vector2|xo.Vector3|xo.Vector4),this._inputs[0]._prioritizeVertex=!t}getClassName(){return"TextureBlock"}get uv(){return this._inputs[0]}get source(){return this._inputs[1]}get layer(){return this._inputs[2]}get lod(){return this._inputs[3]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}get target(){if(this._fragmentOnly)return To.Fragment;if(!this.uv.isConnected)return To.VertexAndFragment;if(this.uv.sourceBlock.isInput)return To.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===To.Fragment)return To.Fragment;if(e.target===To.Vertex)return To.VertexAndFragment;if(e.target===To.Neutral||e.target===To.VertexAndFragment){const t=e.ownerBlock;if(t.target===To.Fragment)return To.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return To.VertexAndFragment}set target(e){}autoConfigure(e,t=(()=>!0)){if(!this.uv.isConnected)if(e.mode===ea.PostProcess){const i=e.getBlockByPredicate((e=>"uv"===e.name&&t(e)));i&&i.connectTo(this)}else{const i=e.mode===ea.Particle?"particle_uv":"uv";let s=e.getInputBlockByPredicate((e=>e.isAttribute&&e.name===i&&t(e)));s||(s=new Go("uv"),s.setAsAttribute(i)),s.output.connectTo(this.uv)}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix)return void(this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)));const s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),null==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!!this._isSourcePrePass||!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==To.Fragment}_injectVertexCode(e){const t=this.uv;this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.declarationVariableName.toUpperCase(),this._mainUVName="vMain"+t.declarationVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,xo.Vector2,this._defineName),e._emitVaryingFromString(this._mainUVName,xo.Vector2,this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,xo.Matrix,this._defineName);const i=e._getShaderType(xo.Vector4),s=e._getShaderType(xo.Vector2);if(e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`${e._getVaryingName(this._transformedUVName)} = ${s}(${this._textureTransformName} * ${i}(${t.associatedVariableName}.xy, 1.0, 0.0));\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`,e.compilationString+=`${e._getVaryingName(this._mainUVName)} = ${t.associatedVariableName}.xy;\n`,e.compilationString+="#endif\n",this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}}_getUVW(e){let t=e;const i=this._texture?._texture?.is2DArray??!1,s=this._texture?._texture?.is3D??!1;return(i||s)&&(t=`vec3(${e}, ${this.layer.isConnected?this.layer.associatedVariableName:"0"})`),t}_samplerFunc(e){return e.shaderLanguage===ht.WGSL?e.target===To.Vertex?"textureSampleLevel":"textureSample":this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureSample(e,t){if(t.shaderLanguage===ht.WGSL){const i=t.target===To.Vertex;return`${this._samplerFunc(t)}(${this.samplerName},${this.samplerName+"Sampler"}, ${this._getUVW(e)}${this._samplerLodSuffix}${i?", 0":""})`}return`${this._samplerFunc(t)}(${this.samplerName}, ${this._getUVW(e)}${this._samplerLodSuffix})`}_generateTextureLookup(e){e.compilationString+=`#ifdef ${this._defineName}\n`,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,xo.Vector4)} = ${this._generateTextureSample(e._getVaryingName(this._transformedUVName),e)};\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\n`,e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,xo.Vector4)} = ${this._generateTextureSample(this._mainUVName?e._getVaryingName(this._mainUVName):this.uv.associatedVariableName,e)}${this._samplerLodSuffix};\n`,e.compilationString+="#endif\n"}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===To.Fragment)return;this._generateTextureLookup(e)}else this.uv.ownerBlock.target!==To.Fragment?this._generateTextureLookup(e):e.compilationString+=`${e._declareLocalVar(this._tempTextureRead,xo.Vector4)} = ${this._generateTextureSample(i.associatedVariableName,e)}${this._samplerLodSuffix};\n`}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i,s=!1){if(s){if(e.target===To.Fragment)return;return e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i)}if(this.uv.ownerBlock.target===To.Fragment)return e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`,void this._generateConversionCode(e,t,i);let r="";this.disableLevelMultiplication||(r=" * "+(e.shaderLanguage===ht.WGSL?"uniforms.":"")+this._textureInfoName),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${r};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===To.Vertex||this._fragmentOnly||e.target===To.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),!this._isMixed&&e.target===To.Fragment||this._isMixed&&e.target===To.Vertex){if(!this._imageSource){const t=e._getFreeVariableName(this.name);this._samplerName=t+"Texture",this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)}e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)}if(e.target!==To.Fragment)return void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;this._isMixed&&!this._imageSource&&(this._texture?._texture?.is2DArray?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._isMixed&&e._emitUniformFromString(this._textureInfoName,xo.Float),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i,s){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!xa.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(0===e.texture.url.indexOf("data:")?i="":s&&(e.texture.url=s(e.texture.url),e.texture.name=e.texture.url),this.texture=Zn.Parse(e.texture,t,i))}}u("BABYLON.TextureBlock",Vm);class Um extends No{get texture(){return this._texture}set texture(e){if(this._texture===e)return;const t=e?.getScene()??y.LastCreatedScene;!e&&t&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?To.Fragment:To.VertexAndFragment)}constructor(e){super(e,To.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=(()=>!0)){if(!this.position.isConnected){let i=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name&&t(e)));i||(i=new Go("position"),i.setAsAttribute()),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.World&&t(e)));i||(i=new Go("world"),i.setAsSystemValue(yo.World)),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.View&&t(e)));i||(i=new Go("view"),i.setAsSystemValue(yo.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this._getTexture();s&&s.getTextureMatrix&&(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLocalCubicName,!!s.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===s.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===s.coordinatesMode,!0),i.setValue(this._defineCubicName,3===s.coordinatesMode||6===s.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===s.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===s.coordinatesMode,!0),i.setValue(this._definePlanarName,2===s.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===s.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===s.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===s.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===s.coordinatesMode,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i,s){const r=this._getTexture();if(i&&r&&(e.setMatrix(this._reflectionMatrixName,r.getReflectionTextureMatrix()),r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),r.boundingBoxSize)){const t=r;e.setVector3(this._reflectionPositionName,t.boundingBoxPosition),e.setVector3(this._reflectionSizeName,t.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===To.Vertex)return"";this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,xo.Matrix);let t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");const i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,xo.Vector4))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName};\n`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,xo.Vector3,this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName}\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\n`,t+="#endif\n"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,xo.Vector3,`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0)));\n`,t+="#endif\n"),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\n`,e._samplerDeclaration+="#else\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\n`,e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,xo.Vector3),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,xo.Vector3)}handleFragmentSideCodeReflectionCoords(e,t,i=!1,s=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const r=this._reflectionMatrixName,n=`normalize(${this._directionWName})`,o=`${this._positionUVWName}`,a=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=`\n #ifdef ${this._defineMirroredEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${n});\n #endif\n\n #ifdef ${this._defineEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${n});\n #endif\n\n #ifdef ${this._defineEquirectangularName}\n vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n\n #ifdef ${this._defineSphericalName}\n vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${r});\n #endif\n\n #ifdef ${this._definePlanarName}\n vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n\n #ifdef ${this._defineCubicName}\n #ifdef ${this._defineLocalCubicName}\n vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${a}.xyz, ${r}, ${this._reflectionSizeName}, ${this._reflectionPositionName});\n #else\n vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${a}.xyz, ${r});\n #endif\n #endif\n\n #ifdef ${this._defineProjectionName}\n vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${r});\n #endif\n\n #ifdef ${this._defineSkyboxName}\n vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${o}, ${r});\n #endif\n\n #ifdef ${this._defineExplicitName}\n vec3 ${this._reflectionVectorName} = vec3(0, 0, 0);\n #endif\n`;return s||(h+=`#ifdef ${this._defineOppositeZ}\n ${this._reflectionVectorName}.z *= -1.0;\n #endif\n`),i||(h+=`\n #ifdef ${this._define3DName}\n vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName};\n #else\n vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy;\n #ifdef ${this._defineProjectionName}\n ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;\n #endif\n ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;\n #endif\n`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i=`${"vec"+(0===t.length?"4":t.length-1)} ${this._reflectionColorName};\n #ifdef ${this._define3DName}\n`;return i+=e?`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t};\n`:`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t};\n`,i+="\n #else\n",i+=e?`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t};\n`:`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t};\n`,i+="#endif\n",i}writeOutputs(e,t){let i="";if(e.target===To.Fragment)for(const s of this._outputs)s.hasEndpoints&&(i+=`${e._declareOutput(s)} = ${t}.${s.name};\n`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){const t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"});\n`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);\n`;return e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!xa.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=tf.Parse(e.texture,t,i):this.texture=Zn.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}ae([Lo("Generate only fragment code",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Um._OnGenerateOnlyFragmentCodeChanged}})],Um.prototype,"generateOnlyFragmentCode",void 0),u("BABYLON.ReflectionTextureBaseBlock",Um),u("BABYLON.ReflectionTextureBlock",class extends Um{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,J.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,J.Error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?To.Fragment:To.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?To.Fragment:To.Vertex}constructor(e){super(e),this.registerInput("position",xo.AutoDetect,!1,To.Vertex),this.registerInput("worldPosition",xo.Vector4,!1,To.Vertex),this.registerInput("worldNormal",xo.Vector4,!1,To.Fragment),this.registerInput("world",xo.Matrix,!1,To.Vertex),this.registerInput("cameraPosition",xo.Vector3,!1,To.Fragment),this.registerInput("view",xo.Matrix,!1,To.Fragment),this.registerOutput("rgb",xo.Color3,To.Fragment),this.registerOutput("rgba",xo.Color4,To.Fragment),this.registerOutput("r",xo.Float,To.Fragment),this.registerOutput("g",xo.Float,To.Fragment),this.registerOutput("b",xo.Float,To.Fragment),this.registerOutput("a",xo.Float,To.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e,t=(()=>!0)){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.CameraPosition&&t(e)));i||(i=new Go("cameraPosition"),i.setAsSystemValue(yo.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==To.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);const t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName});\n`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}});class km extends No{constructor(e){super(e,To.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",xo.AutoDetect,!1,To.VertexAndFragment),this.registerOutput("depth",xo.Float,To.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Vector2|xo.Vector3|xo.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"SceneDepthBlock"}get uv(){return this._inputs[0]}get depth(){return this._outputs[0]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?To.VertexAndFragment:To.Fragment:To.VertexAndFragment}_getTexture(e){return e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ).getDepthMap()}bind(e,t){const i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&(t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,t.type===xo.Vector3?xo.Vector3:t.type===xo.Vector4?xo.Vector4:xo.Vector2)),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,xo.Vector2),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===To.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\n`}else this.uv.ownerBlock.target!==To.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\n`}_writeOutput(e,t,i,s=!1){if(s){if(e.target===To.Fragment)return;e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}else this.uv.ownerBlock.target,To.Fragment,e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i};\n`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.bindableBlocks.indexOf(this)<0&&e.sharedData.bindableBlocks.push(this),e.target!==To.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(this._outputs.some((e=>e.isConnectedInFragmentShader))){e._emit2DSampler(this._samplerName),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){const e=super.serialize();return e.useNonLinearDepth=this.useNonLinearDepth,e.storeCameraSpaceZ=this.storeCameraSpaceZ,e.force32itsFloat=this.force32itsFloat,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useNonLinearDepth=e.useNonLinearDepth,this.storeCameraSpaceZ=!!e.storeCameraSpaceZ,this.force32itsFloat=e.force32itsFloat}}ae([Lo("Use non linear depth",bo.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let s=!1;return i.useNonLinearDepth&&(i.storeCameraSpaceZ=!1,s=!0),e&&e.disableDepthRenderer(),s}}})],km.prototype,"useNonLinearDepth",void 0),ae([Lo("Store Camera space Z",bo.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let s=!1;return i.storeCameraSpaceZ&&(i.useNonLinearDepth=!1,s=!0),e&&e.disableDepthRenderer(),s}}})],km.prototype,"storeCameraSpaceZ",void 0),ae([Lo("Force 32 bits float",bo.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>e?.disableDepthRenderer()}})],km.prototype,"force32itsFloat",void 0),u("BABYLON.SceneDepthBlock",km),u("BABYLON.ClipPlanesBlock",class extends No{constructor(e){super(e,To.VertexAndFragment,!0),this.registerInput("worldPosition",xo.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6")}get worldPosition(){return this._inputs[0]}get target(){return To.VertexAndFragment}set target(e){}prepareDefines(e,t,i){const s=e.getScene(),r=!!(t.clipPlane??s.clipPlane),n=!!(t.clipPlane2??s.clipPlane2),o=!!(t.clipPlane3??s.clipPlane3),a=!!(t.clipPlane4??s.clipPlane4),l=!!(t.clipPlane5??s.clipPlane5),h=!!(t.clipPlane6??s.clipPlane6);i.setValue("CLIPPLANE",r,!0),i.setValue("CLIPPLANE2",n,!0),i.setValue("CLIPPLANE3",o,!0),i.setValue("CLIPPLANE4",a,!0),i.setValue("CLIPPLANE5",l,!0),i.setValue("CLIPPLANE6",h,!0)}bind(e,t,i){i&&Kr(e,t,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==To.Fragment){const i=this.worldPosition;return e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane",xo.Vector4),e._emitUniformFromString("vClipPlane2",xo.Vector4),e._emitUniformFromString("vClipPlane3",xo.Vector4),e._emitUniformFromString("vClipPlane4",xo.Vector4),e._emitUniformFromString("vClipPlane5",xo.Vector4),void e._emitUniformFromString("vClipPlane6",xo.Vector4)}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}),u("BABYLON.PrePassTextureBlock",class extends No{get texture(){return null}set texture(e){}constructor(e,t=To.VertexAndFragment){super(e,t,!1),this.registerOutput("position",xo.Object,To.VertexAndFragment,new Mm("position",this,Eo.Output,Bm,"ImageSourceBlock")),this.registerOutput("depth",xo.Object,To.VertexAndFragment,new Mm("depth",this,Eo.Output,Bm,"ImageSourceBlock")),this.registerOutput("normal",xo.Object,To.VertexAndFragment,new Mm("normal",this,Eo.Output,Bm,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==To.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){const i=t.getScene().enablePrePassRenderer();if(!i)return;const s=i.defaultRT;s.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,s.textures[i.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,s.textures[i.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,s.textures[i.getIndex(6)]))}}),u("BABYLON.NodeMaterialTeleportInBlock",class extends No{get endpoints(){return this._endpoints}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==To.VertexAndFragment)return t.target;if(e.connectedPoint.target!==To.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){this._target&e||(this._target=e)}constructor(e){super(e,To.Neutral),this._endpoints=[],this.registerInput("input",xo.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some((e=>e.output.isConnectedInFragmentShader))}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)-1===t.indexOf(s)&&(i+=s._dumpCode(e,t));return i}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(t.isAnAncestorOf(e))return!0}return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){super.dispose();for(const e of this._endpoints)this.detachFromEndpoint(e);this._endpoints=[]}}),u("BABYLON.NodeMaterialTeleportOutBlock",class extends No{constructor(e){super(e,To.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",xo.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){this._target&e||(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=e._declareOutput(this.output)+` = ${this.entryPoint.input.associatedVariableName};\n`)}clone(e,t=""){const i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}),u("BABYLON.AddBlock",class extends Zo{constructor(e){super(e)}getClassName(){return"AddBlock"}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName};\n`,this}}),u("BABYLON.ScaleBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("input",xo.AutoDetect),this.registerInput("factor",xo.Float),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ScaleBlock"}get input(){return this._inputs[0]}get factor(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName};\n`,this}});class Gm extends No{constructor(e){super(e,To.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e.shaderLanguage===ht.WGSL?e._getShaderType(this.value.type):"";return e.compilationString+=e._declareOutput(t)+` = clamp(${this.value.associatedVariableName}, ${i}(${this._writeFloat(this.minimum)}), ${i}(${this._writeFloat(this.maximum)}));\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.minimum=e.minimum,this.maximum=e.maximum}}ae([Lo("Minimum",bo.Float)],Gm.prototype,"minimum",void 0),ae([Lo("Maximum",bo.Float)],Gm.prototype,"maximum",void 0),u("BABYLON.ClampBlock",Gm),u("BABYLON.CrossBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("left",xo.AutoDetect),this.registerInput("right",xo.AutoDetect),this.registerOutput("output",xo.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(xo.Float),this._inputs[0].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[0].excludedConnectionPointTypes.push(xo.Vector2),this._inputs[1].excludedConnectionPointTypes.push(xo.Float),this._inputs[1].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xo.Vector2)}getClassName(){return"CrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz);\n`,this}}),u("BABYLON.CustomBlock",class extends No{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach((s=>{const r=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),n=e._getGLType(s.type);t=t.replace(r,n),i=i.replace(r,n)})),this._outputs.forEach((s=>{const r=new RegExp("\\{TYPE_"+s.name+"\\}","gm"),n=e._getGLType(s.type);t=t.replace(r,n),i=i.replace(r,n)})),e._emitFunction(i,t,""),this._outputs.forEach((t=>{e.compilationString+=e._declareOutput(t)+";\n"})),e.compilationString+=i+"(";let s=!1;return this._inputs.forEach(((t,i)=>{i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=t.connectedPoint?.ownerBlock?.samplerName??t.associatedVariableName:e.compilationString+=t.associatedVariableName,s=!0})),this._outputs.forEach(((t,i)=>{(i>0||s)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName})),e.compilationString+=");\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.options = ${JSON.stringify(this._options)};\n`,e}serialize(){const e=super.serialize();return e.options=this._options,e}_deserialize(e,t,i){this._deserializeOptions(e.options),super._deserialize(e,t,i)}_deserializeOptions(e){this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=To[e.target],e.inParameters?.forEach(((e,t)=>{const i=xo[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,xo.Object,!0,To.VertexAndFragment,new Mm(e.name,this,Eo.Input,Bm,"ImageSourceBlock"))):this.registerInput(e.name,i),Object.defineProperty(this,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})})),e.outParameters?.forEach(((e,t)=>{this.registerOutput(e.name,xo[e.type]),Object.defineProperty(this,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(this._outputs[t]._typeConnectionSource=this._findInputByName(e.typeFromInput)[0])})),e.inLinkedConnectionTypes?.forEach((e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])}))}_findInputByName(e){if(!e)return null;for(let t=0;t!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.CameraPosition&&t(e)));i||(i=new Go("cameraPosition"),i.setAsSystemValue(yo.CameraPosition)),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz);\n`,this}}var Hm;u("BABYLON.ViewDirectionBlock",Wm),u("BABYLON.FresnelBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("worldNormal",xo.Vector4),this.registerInput("viewDirection",xo.Vector3),this.registerInput("bias",xo.Float),this.registerInput("power",xo.Float),this.registerOutput("fresnel",xo.Float)}getClassName(){return"FresnelBlock"}get worldNormal(){return this._inputs[0]}get viewDirection(){return this._inputs[1]}get bias(){return this._inputs[2]}get power(){return this._inputs[3]}get fresnel(){return this._outputs[0]}autoConfigure(e){if(!this.viewDirection.isConnected){const t=new Wm("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const e=new Go("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){const e=new Go("power");e.value=1,e.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitFunctionFromInclude("fresnelFunction",t,{removeIfDef:!0}),e.compilationString+=e._declareOutput(this.fresnel)+` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName});\n`,this}}),u("BABYLON.MaxBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("left",xo.AutoDetect),this.registerInput("right",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MaxBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`,this}}),u("BABYLON.MinBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("left",xo.AutoDetect),this.registerInput("right",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MinBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`,this}}),u("BABYLON.DistanceBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("left",xo.AutoDetect),this.registerInput("right",xo.AutoDetect),this.registerOutput("output",xo.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(xo.Float),this._inputs[0].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xo.Float),this._inputs[1].excludedConnectionPointTypes.push(xo.Matrix)}getClassName(){return"DistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName});\n`,this}}),u("BABYLON.LengthBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("value",xo.AutoDetect),this.registerOutput("output",xo.Float),this._inputs[0].excludedConnectionPointTypes.push(xo.Float),this._inputs[0].excludedConnectionPointTypes.push(xo.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = length(${this.value.associatedVariableName});\n`,this}}),u("BABYLON.NegateBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("value",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NegateBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = -1.0 * ${this.value.associatedVariableName};\n`,this}}),u("BABYLON.PowBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("value",xo.AutoDetect),this.registerInput("power",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"PowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName});\n`,this}}),u("BABYLON.RandomNumberBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("seed",xo.AutoDetect),this.registerOutput("output",xo.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Vector2|xo.Vector3|xo.Vector4|xo.Color3|xo.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=e._declareOutput(t)+` = getRand(${this.seed.associatedVariableName}.xy);\n`,this}}),u("BABYLON.ArcTan2Block",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("x",xo.Float),this.registerInput("y",xo.Float),this.registerOutput("output",xo.Float)}getClassName(){return"ArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e.shaderLanguage===ht.WGSL?"atan2":"atan";return e.compilationString+=e._declareOutput(t)+` = ${i}(${this.x.associatedVariableName}, ${this.y.associatedVariableName});\n`,this}}),u("BABYLON.SmoothStepBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("value",xo.AutoDetect),this.registerInput("edge0",xo.Float),this.registerInput("edge1",xo.Float),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"SmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e._getShaderType(this.value.type);return e.compilationString+=e._declareOutput(t)+` = smoothstep(${i}(${this.edge0.associatedVariableName}), ${i}(${this.edge1.associatedVariableName}), ${this.value.associatedVariableName});\n`,this}}),u("BABYLON.ReciprocalBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("input",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ReciprocalBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return this.input.type===xo.Matrix?e.compilationString+=e._declareOutput(t)+` = inverse(${this.input.associatedVariableName});\n`:e.compilationString+=e._declareOutput(t)+` = 1. / ${this.input.associatedVariableName};\n`,this}}),u("BABYLON.ReplaceColorBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("value",xo.AutoDetect),this.registerInput("reference",xo.AutoDetect),this.registerInput("distance",xo.Float),this.registerInput("replacement",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(xo.Float),this._inputs[0].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xo.Float),this._inputs[1].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[3].excludedConnectionPointTypes.push(xo.Float),this._inputs[3].excludedConnectionPointTypes.push(xo.Matrix)}getClassName(){return"ReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+";\n",e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {\n`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName};\n`,e.compilationString+="} else {\n",e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName};\n`,e.compilationString+="}\n",this}}),u("BABYLON.PosterizeBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("value",xo.AutoDetect),this.registerInput("steps",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[1].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(xo.Float)}getClassName(){return"PosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=e._declareOutput(t)+` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName});\n`,this}}),function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(Hm||(Hm={})),u("BABYLON.WaveBlock",class extends No{constructor(e){super(e,To.Neutral),this.kind=Hm.SawTooth,this.registerInput("input",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(xo.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];switch(this.kind){case Hm.SawTooth:e.compilationString+=e._declareOutput(t)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\n`;break;case Hm.Square:e.compilationString+=e._declareOutput(t)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\n`;break;case Hm.Triangle:e.compilationString+=e._declareOutput(t)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\n`}return this}serialize(){const e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}});class Xm{get step(){return this._step}set step(e){this._step=e}get color(){return this._color}set color(e){this._color=e}constructor(e,t){this.step=e,this.color=t}}u("BABYLON.GradientBlock",class extends No{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,To.Neutral),this.colorSteps=[new Xm(0,Y.Black()),new Xm(1,Y.White())],this.onValueChangedObservable=new g,this.registerInput("gradient",xo.AutoDetect),this.registerOutput("output",xo.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Float|xo.Vector2|xo.Vector3|xo.Vector4|xo.Color3|xo.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e,t){const i=this.colorSteps[e];return`${t}(${i.color.r}, ${i.color.g}, ${i.color.b})`}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=e._getShaderType(xo.Vector3);if(!this.colorSteps.length||!this.gradient.connectedPoint)return void(e.compilationString+=e._declareOutput(t)+` = ${i}(0., 0., 0.);\n`);const s=e._getFreeVariableName("gradientTempColor"),r=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`${e._declareLocalVar(s,xo.Vector3)} = ${this._writeColorConstant(0,i)};\n`,e.compilationString+=`${e._declareLocalVar(r,xo.Float)};\n`;let n=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==xo.Float&&(n+=".x");for(let t=1;t!0)){if(!this.intensity.isConnected){const e=new Go("Refraction intensity",To.Fragment,xo.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.View&&t(e)));i||(i=new Go("view"),i.setAsSystemValue(yo.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this._getTexture(),r=s&&s.getTextureMatrix;i.setValue("SS_REFRACTION",r,!0),r&&(i.setValue(this._define3DName,s.isCube,!0),i.setValue(this._defineLODRefractionAlpha,s.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,s.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&s.isCube?!s.invertZ:s.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",s.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",s.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!s.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){super.bind(e,t,i);const s=this._getTexture();if(!s)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s),e.setMatrix(this._refractionMatrixName,s.getRefractionTextureMatrix());let r=1;s.isCube||s.depth&&(r=s.depth);const n=this.volumeIndexOfRefraction.connectInputBlock?.value??this.indexOfRefractionConnectionPoint.connectInputBlock?.value??1.5;e.setFloat4(this._vRefractionInfosName,s.level,1/n,r,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,s.getSize().width,s.lodGenerationScale,s.lodGenerationOffset,1/n);const o=s.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,o,G.Log2(o)),s.boundingBoxSize){const t=s;e.setVector3("vRefractionPosition",t.boundingBoxPosition),e.setVector3("vRefractionSize",t.boundingBoxSize)}}getCode(e){return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+=`#ifdef ${this._define3DName}\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\n`,e._samplerDeclaration+="#else\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\n`,e._samplerDeclaration+="#endif\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,xo.Matrix),e._emitFunction("sampleRefraction",`\n #ifdef ${this._define3DName}\n #define sampleRefraction(s, c) textureCube(s, c)\n #else\n #define sampleRefraction(s, c) texture2D(s, c)\n #endif\n`,`//${this.name}`),e._emitFunction("sampleRefractionLod",`\n #ifdef ${this._define3DName}\n #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\n`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,xo.Vector4),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,xo.Vector4),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,xo.Vector2),e._emitUniformFromString("vRefractionPosition",xo.Vector3),e._emitUniformFromString("vRefractionSize",xo.Vector3),""}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e=this.texture.isCube?`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\n`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\n`,e+=`${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\n`,e+=`${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=tf.Parse(e.texture,t,i):this.texture=Zn.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}ae([Lo("Link refraction to transparency",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],Zm.prototype,"linkRefractionWithTransparency",void 0),ae([Lo("Invert refraction Y",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],Zm.prototype,"invertRefractionY",void 0),ae([Lo("Use thickness as depth",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],Zm.prototype,"useThicknessAsDepth",void 0),u("BABYLON.RefractionBlock",Zm);class Jm extends No{constructor(e){super(e,To.Fragment),this._isUnique=!0,this.registerInput("thickness",xo.Float,!1,To.Fragment),this.registerInput("tintColor",xo.Color3,!0,To.Fragment),this.registerInput("translucencyIntensity",xo.Float,!0,To.Fragment),this.registerInput("translucencyDiffusionDist",xo.Color3,!0,To.Fragment),this.registerInput("refraction",xo.Object,!0,To.Fragment,new Mm("refraction",this,Eo.Input,Zm,"RefractionBlock")),this.registerInput("dispersion",xo.Float,!0,To.Fragment),this.registerOutput("subsurface",xo.Object,To.Fragment,new Mm("subsurface",this,Eo.Output,Jm,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vTranslucencyColor"),e._excludeVariableName("vSubSurfaceIntensity"),e._excludeVariableName("dispersion")}getClassName(){return"SubSurfaceBlock"}get thickness(){return this._inputs[0]}get tintColor(){return this._inputs[1]}get translucencyIntensity(){return this._inputs[2]}get translucencyDiffusionDist(){return this._inputs[3]}get refraction(){return this._inputs[4]}get dispersion(){return this._inputs[5]}get subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){const e=new Go("SubSurface thickness",To.Fragment,xo.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const s=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",s||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",s,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0),i.setValue("SS_DISPERSION",this.dispersion.isConnected,!0)}static GetCode(e,t,i,s){let r="";const n=t?.thickness.isConnected?t.thickness.associatedVariableName:"0.",o=t?.tintColor.isConnected?t.tintColor.associatedVariableName:"vec3(1.)",a=t?.translucencyIntensity.isConnected?t?.translucencyIntensity.associatedVariableName:"1.",l=t?.translucencyDiffusionDist.isConnected?t?.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",h=t?.refraction.isConnected?t?.refraction.connectedPoint?.ownerBlock:null,c=h?.tintAtDistance.isConnected?h.tintAtDistance.associatedVariableName:"1.",u=h?.intensity.isConnected?h.intensity.associatedVariableName:"1.",d=h?.view.isConnected?h.view.associatedVariableName:"",p=t?.dispersion.isConnected?t?.dispersion.associatedVariableName:"0.0";return r+=h?.getCode(e)??"",r+=`subSurfaceOutParams subSurfaceOut;\n\n #ifdef SUBSURFACE\n vec2 vThicknessParam = vec2(0., ${n});\n vec4 vTintColor = vec4(${o}, ${c});\n vec3 vSubSurfaceIntensity = vec3(${u}, ${a}, 0.);\n float dispersion = ${p};\n subSurfaceBlock(\n vSubSurfaceIntensity,\n vThicknessParam,\n vTintColor,\n normalW,\n specularEnvironmentReflectance,\n #ifdef SS_THICKNESSANDMASK_TEXTURE\n vec4(0.),\n #endif\n #ifdef REFLECTION\n #ifdef SS_TRANSLUCENCY\n ${i?._reflectionMatrixName},\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n reflectionOut.irradianceVector,\n #endif\n #if defined(REALTIME_FILTERING)\n ${i?._cubeSamplerName},\n ${i?._vReflectionFilteringInfoName},\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n irradianceSampler,\n #endif\n #endif\n #endif\n #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\n surfaceAlbedo,\n #endif\n #ifdef SS_REFRACTION\n ${s}.xyz,\n viewDirectionW,\n ${d},\n ${h?._vRefractionInfosName??""},\n ${h?._refractionMatrixName??""},\n ${h?._vRefractionMicrosurfaceInfosName??""},\n vLightingIntensity,\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha,\n #endif\n #ifdef ${h?._defineLODRefractionAlpha??"IGNORE"}\n NdotVUnclamped,\n #endif\n #ifdef ${h?._defineLinearSpecularRefraction??"IGNORE"}\n roughness,\n #endif\n alphaG,\n #ifdef ${h?._define3DName??"IGNORE"}\n ${h?._cubeSamplerName??""},\n #else\n ${h?._2DSamplerName??""},\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${h?._define3DName??"IGNORE"}\n ${h?._cubeSamplerName??""},\n ${h?._cubeSamplerName??""},\n #else\n ${h?._2DSamplerName??""},\n ${h?._2DSamplerName??""},\n #endif\n #endif\n #ifdef ANISOTROPIC\n anisotropicOut,\n #endif\n #ifdef REALTIME_FILTERING\n ${h?._vRefractionFilteringInfoName??""},\n #endif\n #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n vRefractionPosition,\n vRefractionSize,\n #endif\n #ifdef SS_DISPERSION\n dispersion,\n #endif\n #endif\n #ifdef SS_TRANSLUCENCY\n ${l},\n vTintColor,\n #ifdef SS_TRANSLUCENCYCOLOR_TEXTURE\n vec4(0.),\n #endif\n #endif\n subSurfaceOut\n );\n\n #ifdef SS_REFRACTION\n surfaceAlbedo = subSurfaceOut.surfaceAlbedo;\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha = subSurfaceOut.alpha;\n #endif\n #endif\n #else\n subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;\n #endif\n`,r}_buildBlock(e){return e.target===To.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}u("BABYLON.SubSurfaceBlock",Jm);const eg={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]};class tg extends No{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,J.Error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?To.Fragment:To.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?To.Fragment:To.Vertex}constructor(e){super(e,To.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=Y.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",xo.Vector4,!1,To.Vertex),this.registerInput("worldNormal",xo.Vector4,!1,To.Fragment),this.registerInput("view",xo.Matrix,!1),this.registerInput("cameraPosition",xo.Vector3,!1,To.Fragment),this.registerInput("perturbedNormal",xo.Vector4,!0,To.Fragment),this.registerInput("baseColor",xo.Color3,!0,To.Fragment),this.registerInput("metallic",xo.Float,!1,To.Fragment),this.registerInput("roughness",xo.Float,!1,To.Fragment),this.registerInput("ambientOcc",xo.Float,!0,To.Fragment),this.registerInput("opacity",xo.Float,!0,To.Fragment),this.registerInput("indexOfRefraction",xo.Float,!0,To.Fragment),this.registerInput("ambientColor",xo.Color3,!0,To.Fragment),this.registerInput("reflection",xo.Object,!0,To.Fragment,new Mm("reflection",this,Eo.Input,Km,"ReflectionBlock")),this.registerInput("clearcoat",xo.Object,!0,To.Fragment,new Mm("clearcoat",this,Eo.Input,qm,"ClearCoatBlock")),this.registerInput("sheen",xo.Object,!0,To.Fragment,new Mm("sheen",this,Eo.Input,jm,"SheenBlock")),this.registerInput("subsurface",xo.Object,!0,To.Fragment,new Mm("subsurface",this,Eo.Input,Jm,"SubSurfaceBlock")),this.registerInput("anisotropy",xo.Object,!0,To.Fragment,new Mm("anisotropy",this,Eo.Input,$m,"AnisotropyBlock")),this.registerInput("iridescence",xo.Object,!0,To.Fragment,new Mm("iridescence",this,Eo.Input,Qm,"IridescenceBlock")),this.registerOutput("ambientClr",xo.Color3,To.Fragment),this.registerOutput("diffuseDir",xo.Color3,To.Fragment),this.registerOutput("specularDir",xo.Color3,To.Fragment),this.registerOutput("clearcoatDir",xo.Color3,To.Fragment),this.registerOutput("sheenDir",xo.Color3,To.Fragment),this.registerOutput("diffuseInd",xo.Color3,To.Fragment),this.registerOutput("specularInd",xo.Color3,To.Fragment),this.registerOutput("clearcoatInd",xo.Color3,To.Fragment),this.registerOutput("sheenInd",xo.Color3,To.Fragment),this.registerOutput("refraction",xo.Color3,To.Fragment),this.registerOutput("lighting",xo.Color3,To.Fragment),this.registerOutput("shadow",xo.Float,To.Fragment),this.registerOutput("alpha",xo.Float,To.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=(()=>!0)){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.CameraPosition&&t(e)));i||(i=new Go("cameraPosition"),i.setAsSystemValue(yo.CameraPosition)),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate((e=>e.systemValue===yo.View&&t(e)));i||(i=new Go("view"),i.setAsSystemValue(yo.View)),i.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===Cf.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===Cf.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const s=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",s.indexOf(".")<0?s+".":s,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);const r=e.getScene();if(r.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&th.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),i._areLightsDirty)if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};xn(r,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else vn(r,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,yn(r,i)}updateUniformsAndSamples(e,t,i,s){for(let r=0;r=0;Pn(r,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+r],s,t)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady()||i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){if(!i)return;const s=i.getScene();this.light?un(this.light,this._lightId,s,e,!0):dn(s,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const r=this._scene.ambientColor;r&&e.setColor3("ambientFromScene",r);const n=s.useRightHandedSystem===(null!=s._mirroredCameraPosition);e.setFloat(this._invertNormalName,n?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const o=this.indexOfRefraction.connectInputBlock?.value??1.5,a=Math.pow((o-1)/(o+1),2);this._metallicReflectanceColor.scaleToRef(a*this._metallicF0Factor,$.Color3[0]);const l=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,$.Color3[0],l),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const s="v_"+t.associatedVariableName;e._emitVaryingFromString(s,xo.Vector4)&&(e.compilationString+=`${s} = ${t.associatedVariableName};\n`);const r=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;r&&(r.viewConnectionPoint=this.view),e.compilationString+=r?.handleVertexSide(e)??"",e._emitVaryingFromString("vClipSpacePosition",xo.Vector4,"defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+="#if DEBUGMODE > 0\n",e._injectAtEnd+="vClipSpacePosition = gl_Position;\n",e._injectAtEnd+="#endif\n"),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName};\n`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e="albedoOpacityOutParams albedoOpacityOut;\n";return e+=`albedoOpacityBlock(\n vec4(${this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)"}, 1.),\n #ifdef ALBEDO\n vec4(1.),\n vec2(1., 1.),\n #endif\n #ifdef OPACITY\n vec4(${this.opacity.isConnected?this.opacity.associatedVariableName:"1."}),\n vec2(1., 1.),\n #endif\n albedoOpacityOut\n );\n\n vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;\n float alpha = albedoOpacityOut.alpha;\n`,e}_getAmbientOcclusionCode(){let e="ambientOcclusionOutParams aoOut;\n";return e+=`ambientOcclusionBlock(\n #ifdef AMBIENT\n vec3(${this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1."}),\n vec4(0., 1.0, 1.0, 0.),\n #endif\n aoOut\n );\n`,e}_getReflectivityCode(e){let t="reflectivityOutParams reflectivityOut;\n";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,xo.Vector4),t+=`vec3 baseColor = surfaceAlbedo;\n\n reflectivityBlock(\n vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.),\n #ifdef METALLICWORKFLOW\n surfaceAlbedo,\n ${this._vMetallicReflectanceFactorsName},\n #endif\n #ifdef REFLECTIVITY\n vec3(0., 0., 1.),\n vec4(1.),\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor,\n #endif\n #ifdef MICROSURFACEMAP\n microSurfaceTexel, <== not handled!\n #endif\n reflectivityOut\n );\n\n float microSurface = reflectivityOut.microSurface;\n float roughness = reflectivityOut.roughness;\n\n #ifdef METALLICWORKFLOW\n surfaceAlbedo = reflectivityOut.surfaceAlbedo;\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;\n #endif\n`,t}_buildBlock(e){super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=hf(this._scene));const t=this.reflection.isConnected?this.reflection.connectedPoint?.ownerBlock:null;if(t&&(t.worldPositionConnectionPoint=this.worldPosition,t.cameraPositionConnectionPoint=this.cameraPosition,t.worldNormalConnectionPoint=this.worldNormal,t.viewConnectionPoint=this.view),e.target!==To.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const i=`//${this.name}`,s=this.perturbedNormal;let r=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${r};\n`,i),e.compilationString+=`${r} = ${this.worldPosition.associatedVariableName}.xyz;\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+="#if DEBUGMODE > 0\n",e.compilationString+="vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0);\n",e.compilationString+="#endif\n"):r="v_"+r,this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode",xo.Vector2,"defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene",xo.Vector3),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",i),e._emitFunctionFromInclude("importanceSampling",i),e._emitFunctionFromInclude("pbrHelperFunctions",i),e._emitFunctionFromInclude("imageProcessingDeclaration",i),e._emitFunctionFromInclude("imageProcessingFunctions",i),e._emitFunctionFromInclude("shadowsFragmentFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",i),e._emitFunctionFromInclude("pbrBRDFFunctions",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",i),e._emitFunctionFromInclude("pbrDirectLightingFunctions",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",i),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",i),e._emitFunctionFromInclude("pbrBlockReflectivity",i),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",i),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",i),e._emitFunctionFromInclude("pbrBlockAnisotropic",i),e._emitUniformFromString("vLightingIntensity",xo.Vector4),t?.generateOnlyFragmentCode&&(e.compilationString+=t.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName});\n`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${r}.xyz);\n`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz;\n`,e.compilationString+=`vec3 normalW = ${s.isConnected?"normalize("+s.associatedVariableName+".xyz)":"geometricNormalW"};\n`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,xo.Float),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",i,{replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",i),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",i),e.compilationString+="#ifdef UNLIT\n vec3 diffuseBase = vec3(1., 1., 1.);\n #else\n",e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"}]});const n=this.anisotropy.isConnected?this.anisotropy.connectedPoint?.ownerBlock:null;n&&(n.worldPositionConnectionPoint=this.worldPosition,n.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=n.getCode(e,!this.perturbedNormal.isConnected)),t&&t.hasTexture&&(e.compilationString+=t.getCode(e,n?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:t?._vReflectionFilteringInfoName??"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",i,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});const o=this.sheen.isConnected?this.sheen.connectedPoint?.ownerBlock:null;o&&(e.compilationString+=o.getCode(t)),e._emitFunctionFromInclude("pbrBlockSheen",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"}]});const a=this.iridescence.isConnected?this.iridescence.connectedPoint?.ownerBlock:null;e.compilationString+=Qm.GetCode(a),e._emitFunctionFromInclude("pbrBlockIridescence",i,{replaceStrings:[]});const l=this.clearcoat.isConnected?this.clearcoat.connectedPoint?.ownerBlock:null,h=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,c=this.perturbedNormal.isConnected&&(this.perturbedNormal.connectedPoint?.ownerBlock).worldTangent?.isConnected,u=this.anisotropy.isConnected&&(this.anisotropy.connectedPoint?.ownerBlock).worldTangent.isConnected;let d=c||!this.perturbedNormal.isConnected&&u;e.compilationString+=qm.GetCode(e,l,t,r,h,d,this.worldNormal.associatedVariableName),h&&(d=l?.worldTangent.isConnected??!1),e._emitFunctionFromInclude("pbrBlockClearcoat",i,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:t?._defineLODReflectionAlpha??"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:t?._defineLinearSpecularReflection??"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:d?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",i,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:t?._defineSkyboxName??"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"}]});const p=this.subsurface.isConnected?this.subsurface.connectedPoint?.ownerBlock:null,f=this.subsurface.isConnected?(this.subsurface.connectedPoint?.ownerBlock).refraction.connectedPoint?.ownerBlock:null;f&&(f.viewConnectionPoint=this.view,f.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=Jm.GetCode(e,p,t,r),e._emitFunctionFromInclude("pbrBlockSubSurface",i,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:t?._define3DName??"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:t?._defineOppositeZ??"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:t?._defineProjectionName??"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:f?._define3DName??"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:f?._defineLODRefractionAlpha??"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:f?._defineLinearSpecularRefraction??"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:f?._defineOppositeZ??"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",i),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:r+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",i,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${r}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",i),e.compilationString+="#endif\n";const _=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)";let m=Cf.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();-1===m.indexOf(".")&&(m+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",i,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:_+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:m}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",i,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",i,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",i,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:r},{search:/albedoTexture\.rgb;/g,replace:"vec3(1.);\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\n"}]});for(const t of this._outputs)if(t.hasEndpoints){const i=eg[t.name];if(i){const[s,r]=i;r&&(e.compilationString+=`#if ${r}\n`),e.compilationString+=`${e._declareOutput(t)} = ${s};\n`,r&&(e.compilationString+="#else\n",e.compilationString+=`${e._declareOutput(t)} = vec3(0.);\n`,e.compilationString+="#endif\n")}else J.Error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.lightFalloff = ${this.lightFalloff};\n`,e+=`${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};\n`,e+=`${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};\n`,e+=`${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};\n`,e+=`${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};\n`,e+=`${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};\n`,e+=`${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};\n`,e+=`${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};\n`,e+=`${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};\n`,e+=`${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};\n`,e+=`${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};\n`,e+=`${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};\n`,e+=`${this._codeVariableName}.unlit = ${this.unlit};\n`,e+=`${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};\n`,e+=`${this._codeVariableName}.debugMode = ${this.debugMode};\n`,e+=`${this._codeVariableName}.debugLimit = ${this.debugLimit};\n`,e+=`${this._codeVariableName}.debugFactor = ${this.debugFactor};\n`,e}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=e.lightFalloff??0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=e.realTimeFilteringQuality??8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor,this.generateOnlyFragmentCode=!!e.generateOnlyFragmentCode,this._setTarget()}}var ig,sg,rg,ng,og,ag,lg;ae([Lo("Direct lights",bo.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],tg.prototype,"directIntensity",void 0),ae([Lo("Environment lights",bo.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],tg.prototype,"environmentIntensity",void 0),ae([Lo("Specular highlights",bo.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],tg.prototype,"specularIntensity",void 0),ae([Lo("Light falloff",bo.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:Cf.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:Cf.LIGHTFALLOFF_GLTF},{label:"Standard",value:Cf.LIGHTFALLOFF_STANDARD}]})],tg.prototype,"lightFalloff",void 0),ae([Lo("Alpha Testing",bo.Boolean,"OPACITY")],tg.prototype,"useAlphaTest",void 0),ae([Lo("Alpha CutOff",bo.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],tg.prototype,"alphaTestCutoff",void 0),ae([Lo("Alpha blending",bo.Boolean,"OPACITY")],tg.prototype,"useAlphaBlending",void 0),ae([Lo("Radiance over alpha",bo.Boolean,"RENDERING",{notifiers:{update:!0}})],tg.prototype,"useRadianceOverAlpha",void 0),ae([Lo("Specular over alpha",bo.Boolean,"RENDERING",{notifiers:{update:!0}})],tg.prototype,"useSpecularOverAlpha",void 0),ae([Lo("Specular anti-aliasing",bo.Boolean,"RENDERING",{notifiers:{update:!0}})],tg.prototype,"enableSpecularAntiAliasing",void 0),ae([Lo("Realtime filtering",bo.Boolean,"RENDERING",{notifiers:{update:!0}})],tg.prototype,"realTimeFiltering",void 0),ae([Lo("Realtime filtering quality",bo.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],tg.prototype,"realTimeFilteringQuality",void 0),ae([Lo("Energy Conservation",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],tg.prototype,"useEnergyConservation",void 0),ae([Lo("Radiance occlusion",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],tg.prototype,"useRadianceOcclusion",void 0),ae([Lo("Horizon occlusion",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],tg.prototype,"useHorizonOcclusion",void 0),ae([Lo("Unlit",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],tg.prototype,"unlit",void 0),ae([Lo("Force normal forward",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],tg.prototype,"forceNormalForward",void 0),ae([Lo("Generate only fragment code",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:tg._OnGenerateOnlyFragmentCodeChanged}})],tg.prototype,"generateOnlyFragmentCode",void 0),ae([Lo("Debug mode",bo.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87},{label:"Albedo color",value:88},{label:"Ambient occlusion color",value:89}]})],tg.prototype,"debugMode",void 0),ae([Lo("Split position",bo.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],tg.prototype,"debugLimit",void 0),ae([Lo("Output factor",bo.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],tg.prototype,"debugFactor",void 0),u("BABYLON.PBRMetallicRoughnessBlock",tg),u("BABYLON.ModBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("left",xo.AutoDetect),this.registerInput("right",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[1].acceptedConnectionPointTypes.push(xo.Float)}getClassName(){return"ModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.shaderLanguage===ht.GLSL?e.compilationString+=e._declareOutput(t)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\n`:e.compilationString+=e._declareOutput(t)+` = (${this.left.associatedVariableName} % ${this.right.associatedVariableName});\n`,this}}),u("BABYLON.MatrixBuilder",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("row0",xo.Vector4),this.registerInput("row1",xo.Vector4),this.registerInput("row2",xo.Vector4),this.registerInput("row3",xo.Vector4),this.registerOutput("output",xo.Matrix)}getClassName(){return"MatrixBuilder"}get row0(){return this._inputs[0]}get row1(){return this._inputs[1]}get row2(){return this._inputs[2]}get row3(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(){if(!this.row0.isConnected){const e=new Go("row0");e.value=new F(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new Go("row1");e.value=new F(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new Go("row2");e.value=new F(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new Go("row3");e.value=new F(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,s=this.row1,r=this.row2,n=this.row3,o=e.shaderLanguage===ht.WGSL?"mat4x4f":"mat4";return e.compilationString+=e._declareOutput(t)+` = ${o}(${i.associatedVariableName}, ${s.associatedVariableName}, ${r.associatedVariableName}, ${n.associatedVariableName});\n`,this}}),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(ig||(ig={})),u("BABYLON.ConditionalBlock",class extends No{constructor(e){super(e,To.Neutral),this.condition=ig.LessThan,this.registerInput("a",xo.Float),this.registerInput("b",xo.Float),this.registerInput("true",xo.AutoDetect,!0),this.registerInput("false",xo.AutoDetect,!0),this.registerOutput("output",xo.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=xo.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",s=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case ig.Equal:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} == ${this.b.associatedVariableName}`)};\n`;break;case ig.NotEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} != ${this.b.associatedVariableName}`)};\n`;break;case ig.LessThan:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} < ${this.b.associatedVariableName}`)};\n`;break;case ig.LessOrEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} <= ${this.b.associatedVariableName}`)};\n`;break;case ig.GreaterThan:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} > ${this.b.associatedVariableName}`)};\n`;break;case ig.GreaterOrEqual:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`${this.a.associatedVariableName} >= ${this.b.associatedVariableName}`)};\n`;break;case ig.Xor:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`(((${this.a.associatedVariableName} + ${this.b.associatedVariableName}) % 2.0) > 0.0)`)};\n`;break;case ig.Or:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`(min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0)`)};\n`;break;case ig.And:e.compilationString+=e._declareOutput(t)+` = ${e._generateTernary(i,s,`(${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0)`)};\n`}return this}serialize(){const e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${ig[this.condition]};\n`}});class hg extends No{constructor(e){super(e,To.Neutral),this.octaves=6,this.registerInput("seed",xo.AutoDetect),this.registerInput("chaos",xo.AutoDetect,!0),this.registerInput("offsetX",xo.Float,!0),this.registerInput("offsetY",xo.Float,!0),this.registerInput("offsetZ",xo.Float,!0),this.registerOutput("output",xo.Float),this._inputs[0].acceptedConnectionPointTypes.push(xo.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(xo.Vector3),this._linkConnectionTypes(0,1)}getClassName(){return"CloudBlock"}get seed(){return this._inputs[0]}get chaos(){return this._inputs[1]}get offsetX(){return this._inputs[2]}get offsetY(){return this._inputs[3]}get offsetZ(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;if(!this._outputs[0].hasEndpoints)return;let t="\n\n float cloudRandom(float p) { \n float temp = fract(p * 0.011); \n temp *= temp + 7.5; \n temp *= temp + temp; \n return fract(temp); \n }\n\n // Based on Morgan McGuire @morgan3d\n // https://www.shadertoy.com/view/4dS3Wd\n float cloudNoise2(vec2 x, vec2 chaos) {\n vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);\n\n vec2 i = floor(x);\n vec2 f = fract(x);\n\n float n = dot(i, step);\n\n vec2 u = f * f * (3.0 - 2.0 * f);\n return mix(\n mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),\n mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),\n u.y\n );\n }\n\n float cloudNoise3(vec3 x, vec3 chaos) {\n vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);\n\n vec3 i = floor(x);\n vec3 f = fract(x);\n\n float n = dot(i, step);\n\n vec3 u = f * f * (3.0 - 2.0 * f);\n return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),\n mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);\n }",i="\n float fbm2(vec2 st, vec2 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = .5;\n float frequency = 0.;\n\n // Loop of octaves\n vec2 tempST = st;\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise2(tempST, chaos);\n tempST *= 2.0;\n amplitude *= 0.5;\n }\n return value;\n }\n\n float fbm3(vec3 x, vec3 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = 0.5;\n vec3 tempX = x;\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise3(tempX, chaos);\n tempX = tempX * 2.0;\n amplitude *= 0.5;\n }\n return value;\n }";e.shaderLanguage===ht.WGSL&&(t=e._babylonSLtoWGSL(t),i=e._babylonSLtoWGSL(i));const s=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",t,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,i.replace(/fbm/gi,s).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");const r=e._getFreeVariableName("st"),n=this.seed.connectedPoint?.type||xo.Vector3;e.compilationString+=`${e._declareLocalVar(r,n)} = ${this.seed.associatedVariableName};\n`,this.offsetX.isConnected&&(e.compilationString+=`${r}.x += 0.1 * ${this.offsetX.associatedVariableName};\n`),this.offsetY.isConnected&&(e.compilationString+=`${r}.y += 0.1 * ${this.offsetY.associatedVariableName};\n`),this.offsetZ.isConnected&&n===xo.Vector3&&(e.compilationString+=`${r}.z += 0.1 * ${this.offsetZ.associatedVariableName};\n`);let o="";if(this.chaos.isConnected)o=this.chaos.associatedVariableName;else{const t=e.fSuffix;o=this.seed.connectedPoint?.type===xo.Vector2?`vec2${t}(0., 0.)`:`vec3${t}(0., 0., 0.)`}return e.compilationString+=e._declareOutput(this._outputs[0])+` = ${s}${this.seed.connectedPoint?.type===xo.Vector2?"2":"3"}(${r}, ${o});\n`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves};\n`}serialize(){const e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}ae([Lo("Octaves",bo.Int)],hg.prototype,"octaves",void 0),u("BABYLON.CloudBlock",hg),u("BABYLON.VoronoiNoiseBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("seed",xo.Vector2),this.registerInput("offset",xo.Float),this.registerInput("density",xo.Float),this.registerOutput("output",xo.Float),this.registerOutput("cells",xo.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t="vec2 voronoiRandom(vec2 p){\n p = vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3)));\n return fract(sin(p)*18.5453);\n }\n ";e.shaderLanguage===ht.WGSL&&(t=e._babylonSLtoWGSL(t)),e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t="void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){\n vec2 n = floor(seed * density);\n vec2 f = fract(seed * density);\n vec3 m = vec3( 8.0 );\n for( int j=-1; j<=1; j++ ){\n for( int i=-1; i<=1; i++ ){\n vec2 g = vec2( float(i), float(j) );\n vec2 o = voronoiRandom( n + g);\n vec2 r = g - f + (0.5+0.5*sin(offset+6.2831*o));\n float d = dot( r, r );\n if( de.hasTexture(this._texture))),this._texture=e,e&&t&&t.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get textureY(){return this.sourceY.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}get textureZ(){return this.sourceZ?.isConnected?(this.sourceY.connectedPoint?.ownerBlock).texture:null}_getImageSourceBlock(e){return e?.isConnected?e.connectedPoint.ownerBlock:null}get samplerName(){const e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){return this._getImageSourceBlock(this.sourceY)?.samplerName??null}get samplerZName(){return this._getImageSourceBlock(this.sourceZ)?.samplerName??null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=this.texture.getScene()??y.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=this.texture.getScene()??y.LastCreatedScene;e?.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,To.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",xo.AutoDetect,!1),this.registerInput("normal",xo.AutoDetect,!1),this.registerInput("sharpness",xo.Float,!0),this.registerInput("source",xo.Object,!0,To.VertexAndFragment,new Mm("source",this,Eo.Input,Bm,"ImageSourceBlock")),this.registerInput("sourceY",xo.Object,!0,To.VertexAndFragment,new Mm("sourceY",this,Eo.Input,Bm,"ImageSourceBlock")),t||this.registerInput("sourceZ",xo.Object,!0,To.VertexAndFragment,new Mm("sourceZ",this,Eo.Input,Bm,"ImageSourceBlock")),this.registerOutput("rgba",xo.Color4,To.Neutral),this.registerOutput("rgb",xo.Color3,To.Neutral),this.registerOutput("r",xo.Float,To.Neutral),this.registerOutput("g",xo.Float,To.Neutral),this.registerOutput("b",xo.Float,To.Neutral),this.registerOutput("a",xo.Float,To.Neutral),this.registerOutput("level",xo.Float,To.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(xo.Color3|xo.Vector3|xo.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const s=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,r=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,s,!0),i.setValue(this._gammaDefineName,r,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_samplerFunc(e){return e.shaderLanguage===ht.WGSL?"textureSample":"texture2D"}_generateTextureSample(e,t,i){return i.shaderLanguage===ht.WGSL?`${this._samplerFunc(i)}(${e},${e+"Sampler"}, ${t})`:`${this._samplerFunc(i)}(${e}, ${t})`}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??t,s=this.samplerZName??t,r=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("x"),o=e._getFreeVariableName("y"),a=e._getFreeVariableName("z"),l=e._getFreeVariableName("w"),h=e._getFreeVariableName("n"),c=e._getFreeVariableName("uvx"),u=e._getFreeVariableName("uvy"),d=e._getFreeVariableName("uvz");e.compilationString+=`\n ${e._declareLocalVar(h,xo.Vector3)} = ${this.normal.associatedVariableName}.xyz;\n\n ${e._declareLocalVar(c,xo.Vector2)} = ${this.position.associatedVariableName}.yz;\n ${e._declareLocalVar(u,xo.Vector2)} = ${this.position.associatedVariableName}.zx;\n ${e._declareLocalVar(d,xo.Vector2)} = ${this.position.associatedVariableName}.xy;\n `,this.projectAsCube&&(e.compilationString+=`\n ${c}.xy = ${c}.yx;\n\n if (${h}.x >= 0.0) {\n ${c}.x = -${c}.x;\n }\n if (${h}.y < 0.0) {\n ${u}.y = -${u}.y;\n }\n if (${h}.z < 0.0) {\n ${d}.x = -${d}.x;\n }\n `);const p=e.fSuffix;e.compilationString+=`\n ${e._declareLocalVar(n,xo.Vector4)} = ${this._generateTextureSample(t,c,e)};\n ${e._declareLocalVar(o,xo.Vector4)} = ${this._generateTextureSample(i,u,e)};\n ${e._declareLocalVar(a,xo.Vector4)} = ${this._generateTextureSample(s,d,e)};\n \n // blend weights\n ${e._declareLocalVar(l,xo.Vector3)} = pow(abs(${h}), vec3${p}(${r}));\n\n // blend and return\n ${e._declareLocalVar(this._tempTextureRead,xo.Vector4)} = (${n}*${l}.x + ${o}*${l}.y + ${a}*${l}.z) / (${l}.x + ${l}.y + ${l}.z); \n `}_generateConversionCode(e,t,i){let s="";e.shaderLanguage!==ht.WGSL||t.type!==xo.Vector3&&t.type!==xo.Color3||(s="Vec3"),"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace${s}(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace${s}(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i){let s="";this.disableLevelMultiplication||(s=` * ${e.shaderLanguage===ht.WGSL?"uniforms.":""}${this._textureInfoName}`),e.compilationString+=`${e._declareOutput(t)} = ${this._tempTextureRead}.${i}${s};\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=(e.shaderLanguage===ht.WGSL?"uniforms.":"")+this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Texture"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,xo.Float),this._generateTextureLookup(e);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\n`,e+=`${this._codeVariableName}.projectAsCube = ${this.projectAsCube};\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!xa.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Zn.Parse(e.texture,t,i))}}ae([Lo("Project as cube",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],cg.prototype,"projectAsCube",void 0),u("BABYLON.TriPlanarBlock",cg),u("BABYLON.BiPlanarBlock",class extends cg{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_declareLocalVarAsVec3I(e,t){return t.shaderLanguage===ht.WGSL?`var ${e}: vec3`:`ivec3 ${e}`}_getTextureGrad(e,t){return e.shaderLanguage===ht.WGSL?`textureSampleGrad(${t},${t+"Sampler"}`:`textureGrad(${t}`}_generateTextureLookup(e){const t=this.samplerName,i=this.samplerYName??this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",r=e._getFreeVariableName("dxValue"),n=e._getFreeVariableName("dyValue"),o=e._getFreeVariableName("n"),a=e._getFreeVariableName("ma"),l=e._getFreeVariableName("mi"),h=e._getFreeVariableName("me"),c=e._getFreeVariableName("x"),u=e._getFreeVariableName("y"),d=e._getFreeVariableName("w");let p="ivec3",f="dFdx",_="dFdy";const m=e.fSuffix;e.shaderLanguage===ht.WGSL&&(p="vec3",f="dpdx",_="dpdy"),e.compilationString+=`\n // grab coord derivatives for texturing\n ${e._declareLocalVar(r,xo.Vector3)} = ${f}(${this.position.associatedVariableName}.xyz);\n ${e._declareLocalVar(n,xo.Vector3)} = ${_}(${this.position.associatedVariableName}.xyz);\n ${e._declareLocalVar(o,xo.Vector3)} = abs(${this.normal.associatedVariableName}.xyz);\n \n // determine major axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(a,e)} = ${e._generateTernary(`${p}(0,1,2)`,`${e._generateTernary(`${p}(1,2,0)`,`${p}(2,0,1)`,`(${o}.y>${o}.z)`)}`,`(${o}.x>${o}.y && ${o}.x>${o}.z)`)}; \n\n // determine minor axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(l,e)} = ${e._generateTernary(`${p}(0,1,2)`,`${e._generateTernary(`${p}(1,2,0)`,`${p}(2,0,1)`,`(${o}.y<${o}.z)`)}`,`(${o}.x<${o}.y && ${o}.x<${o}.z)`)}; \n \n // determine median axis (in x; yz are following axis)\n ${this._declareLocalVarAsVec3I(h,e)} = ${p}(3) - ${l} - ${a};\n \n // project+fetch\n ${e._declareLocalVar(c,xo.Vector4)} = ${this._getTextureGrad(e,t)}, vec2${m}(${this.position.associatedVariableName}[${a}.y], ${this.position.associatedVariableName}[${a}.z]), \n vec2${m}(${r}[${a}.y],${r}[${a}.z]), \n vec2${m}(${n}[${a}.y],${n}[${a}.z]));\n ${e._declareLocalVar(u,xo.Vector4)} = ${this._getTextureGrad(e,i)}, vec2${m}(${this.position.associatedVariableName}[${h}.y], ${this.position.associatedVariableName}[${h}.z]), \n vec2${m}(${r}[${h}.y],${r}[${h}.z]),\n vec2${m}(${n}[${h}.y],${n}[${h}.z]));\n \n // blend factors\n ${e._declareLocalVar(d,xo.Vector2)} = vec2${m}(${o}[${a}.x],${o}[${h}.x]);\n // make local support\n ${d} = clamp( (${d}-0.5773)/(1.0-0.5773), vec2${m}(0.0), vec2${m}(1.0) );\n // shape transition\n ${d} = pow( ${d}, vec2${m}(${s}/8.0) );\n // blend and return\n ${e._declareLocalVar(this._tempTextureRead,xo.Vector4)} = (${c}*${d}.x + ${u}*${d}.y) / (${d}.x + ${d}.y);\n `}}),u("BABYLON.MatrixDeterminantBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("input",xo.Matrix),this.registerOutput("output",xo.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=e._declareOutput(t)+` = determinant(${i.associatedVariableName});\n`,this}}),u("BABYLON.MatrixTransposeBlock",class extends No{constructor(e){super(e,To.Neutral),this.registerInput("input",xo.Matrix),this.registerOutput("output",xo.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=e._declareOutput(t)+` = transpose(${i.associatedVariableName});\n`,this}}),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Tangent=2]="Tangent",e[e.VertexColor=3]="VertexColor",e[e.UV1=4]="UV1",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6"}(sg||(sg={}));class ug extends No{constructor(e){super(e,To.Neutral),this.attributeType=sg.None,this.registerInput("input",xo.AutoDetect),this.registerInput("fallback",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add((e=>{if(this.attributeType)return;const t=e.ownerBlock;if(t instanceof Go&&t.isAttribute)switch(t.name){case"color":this.attributeType=sg.VertexColor;break;case"normal":this.attributeType=sg.Normal;break;case"tangent":this.attributeType=sg.Tangent;break;case"uv":this.attributeType=sg.UV1;break;case"uv2":this.attributeType=sg.UV2;break;case"uv3":this.attributeType=sg.UV3;break;case"uv4":this.attributeType=sg.UV4;break;case"uv5":this.attributeType=sg.UV5;break;case"uv6":this.attributeType=sg.UV6}else if(t instanceof Dm)switch(this.input.connectedPoint?.name){case"normalOutput":this.attributeType=sg.Normal;break;case"tangentOutput":this.attributeType=sg.Tangent;break;case"uvOutput":this.attributeType=sg.UV1}}))}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case sg.VertexColor:t="VERTEXCOLOR_NME";break;case sg.Normal:t="NORMAL";break;case sg.Tangent:t="TANGENT";break;case sg.UV1:t="UV1";break;case sg.UV2:t="UV2";break;case sg.UV3:t="UV3";break;case sg.UV4:t="UV4";break;case sg.UV5:t="UV5";break;case sg.UV6:t="UV6"}const i=e._declareOutput(this.output);return t&&(e.compilationString+=`#ifdef ${t}\n`),e.compilationString+=`${i} = ${this.input.associatedVariableName};\n`,t&&(e.compilationString+="#else\n",e.compilationString+=`${i} = ${this.fallback.associatedVariableName};\n`,e.compilationString+="#endif\n"),this}serialize(){const e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.attributeType=e.attributeType??sg.None}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType};\n`,e}}ae([Lo("Attribute lookup",bo.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:sg.None},{label:"Normal",value:sg.Normal},{label:"Tangent",value:sg.Tangent},{label:"Vertex Color",value:sg.VertexColor},{label:"UV1",value:sg.UV1},{label:"UV2",value:sg.UV2},{label:"UV3",value:sg.UV3},{label:"UV4",value:sg.UV4},{label:"UV5",value:sg.UV5},{label:"UV6",value:sg.UV6}]})],ug.prototype,"attributeType",void 0),u("BABYLON.MeshAttributeExistsBlock",ug),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(rg||(rg={})),u("BABYLON.CurveBlock",class extends No{constructor(e){super(e,To.Neutral),this.type=rg.EaseInOutSine,this.registerInput("input",xo.AutoDetect),this.registerOutput("output",xo.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(xo.Matrix),this._inputs[0].excludedConnectionPointTypes.push(xo.Object),this._inputs[0].excludedConnectionPointTypes.push(xo.Int)}getClassName(){return"CurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_duplicateEntry(e,t){return`ret.${t} = ${e.replace(/VAL/g,"v."+t)}`}_duplicateEntryDirect(e){return`return ${e.replace(/VAL/g,"v")}`}_duplicateVector(e,t,i){if("float"===t||"f32"===t)return this._duplicateEntryDirect(e);const s=parseInt(t.replace("vec",""));let r=i?`\n var ret: vec${s}f = vec${s}f(0.0);\n `:`\n vec${s} ret = vec${s}(0.0);\n `;for(let t=1;t<=s;t++)r+=this._duplicateEntry(e,1===t?"x":2===t?"y":3===t?"z":"w")+";\n";return r+="return ret;\n",r}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",s="";const r=e._getShaderType(this.input.type),n=e.shaderLanguage===ht.WGSL;switch(s=rg[this.type]+"_"+r.replace("<","").replace(">",""),this.type){case rg.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case rg.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case rg.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case rg.EaseInQuad:i="return v * v";break;case rg.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case rg.EaseInOutQuad:{const t=e._generateTernary("2.0 * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case rg.EaseInCubic:i="return v * v * v";break;case rg.EaseOutCubic:{const e="1.0 - pow(1.0 - VAL, 3.0)";i=this._duplicateVector(e,r,n);break}case rg.EaseInOutCubic:{const t=e._generateTernary("4.0 * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case rg.EaseInQuart:i="return v * v * v * v";break;case rg.EaseOutQuart:{const e="1.0 - pow(1.0 - VAL, 4.0)";i=this._duplicateVector(e,r,n);break}case rg.EaseInOutQuart:{const t=e._generateTernary("8.0 * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case rg.EaseInQuint:i="return v * v * v * v * v";break;case rg.EaseOutQuint:{const e="1.0 - pow(1.0 - VAL, 5.0)";i=this._duplicateVector(e,r,n);break}case rg.EaseInOutQuint:{const t=e._generateTernary("16.0 * VAL * VAL * VAL * VAL * VAL","1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case rg.EaseInExpo:{const t=e._generateTernary("0.0","pow(2.0, 10.0 * VAL - 10.0)","VAL == 0.0");i=this._duplicateVector(t,r,n);break}case rg.EaseOutExpo:{const t=e._generateTernary("1.0","1.0 - pow(2.0, -10.0 * VAL)","VAL == 1.0");i=this._duplicateVector(t,r,n);break}case rg.EaseInOutExpo:{const t=e._generateTernary("0.0",e._generateTernary("1.0",e._generateTernary("pow(2.0, 20.0 * VAL - 10.0) / 2.0","(2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}case rg.EaseInCirc:{const e="1.0 - sqrt(1.0 - pow(VAL, 2.0))";i=this._duplicateVector(e,r,n);break}case rg.EaseOutCirc:{const e="sqrt(1.0 - pow(VAL - 1.0, 2.0))";i=this._duplicateVector(e,r,n);break}case rg.EaseInOutCirc:{const t=e._generateTernary("(1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0","(sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case rg.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case rg.EaseOutBack:{const e="2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)";i=this._duplicateVector(e,r,n);break}case rg.EaseInOutBack:{const t=e._generateTernary("(pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0","(pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0","VAL < 0.5");i=this._duplicateVector(t,r,n);break}case rg.EaseInElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0","-pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))","VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}case rg.EaseOutElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0","pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0","VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}case rg.EaseInOutElastic:{const t=e._generateTernary("0.0",e._generateTernary("1.0",e._generateTernary("-(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0","(pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0","VAL < 0.5"),"VAL == 1.0"),"VAL == 0.0");i=this._duplicateVector(t,r,n);break}}return n?e._emitFunction(s,`fn ${s}(v: ${r}) -> ${r} {${i};}\n`,""):e._emitFunction(s,`${r} ${s}(${r} v) {${i};}\n`,""),e.compilationString+=e._declareOutput(t)+` = ${s}(${this.input.associatedVariableName});\n`,this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${rg[this.type]};\n`}});class dg extends Do{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}}class pg extends ah{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new dg,t),this._isEnabled=!1,this.isEnabled=!1,this._smoothAlpha=!1,this.smoothAlpha=!1,this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i,s){const r=s.getMesh().decalMap;return!(this._isEnabled&&r?.texture&&th.DecalMapEnabled&&t.texturesEnabled)||r.isReady()}prepareDefines(e,t,i){const s=i.decalMap;this._isEnabled&&s?.texture&&th.DecalMapEnabled&&t.texturesEnabled?((!e.DECAL||e.GAMMADECAL!==s.texture.gammaSpace)&&e.markAsTexturesDirty(),e.DECAL=!0,e.GAMMADECAL=s.texture.gammaSpace,e.DECAL_SMOOTHALPHA=this._smoothAlpha,an(s.texture,e,"DECAL")):(e.DECAL&&e.markAsTexturesDirty(),e.DECAL=!1)}hardBindForSubMesh(e,t,i,s){const r=s.getMesh().decalMap;if(!(this._isEnabled&&r?.texture&&th.DecalMapEnabled&&t.texturesEnabled))return;const n=this._material.isFrozen,o=r.texture;e.useUbo&&n&&e.isSync||(e.updateFloat4("vDecalInfos",o.coordinatesIndex,0,0,0),ln(o,e,"decal")),e.setTexture("decalSampler",o)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}}ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],pg.prototype,"isEnabled",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],pg.prototype,"smoothAlpha",void 0),u("BABYLON.DecalMapConfiguration",pg),(lg=ng||(ng={}))[lg.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",lg[lg.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",lg[lg.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE",function(e){e[e.COLOR_MODE_SET=0]="COLOR_MODE_SET",e[e.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",e[e.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY"}(og||(og={})),function(e){e[e.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",e[e.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"}(ag||(ag={}));class fg{}fg.DEFAULT_COLOR=Y.White(),fg.DEFAULT_WIDTH_ATTENUATED=1,fg.DEFAULT_WIDTH=.1;class _g{static ConvertPoints(e){if(e.length&&Array.isArray(e)&&"number"==typeof e[0])return[e];if(e.length&&Array.isArray(e[0])&&"number"==typeof e[0][0])return e;if(e.length&&!Array.isArray(e[0])&&e[0]instanceof w){const t=[];for(let i=0;i0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof w){const t=[];return e.forEach((e=>{t.push(e.flatMap((e=>[e.x,e.y,e.z])))})),t}if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){const t=[];return e.forEach((e=>{t.push(Array.from(e))})),t}return[]}static OmitZeroLengthPredicate(e,t,i){const s=[];return t.subtract(e).lengthSquared()>0&&s.push([e,t]),i.subtract(t).lengthSquared()>0&&s.push([t,i]),e.subtract(i).lengthSquared()>0&&s.push([i,e]),0===s.length?null:s}static OmitDuplicatesPredicate(e,t,i,s){const r=[];return _g._SearchInPoints(e,t,s)||r.push([e,t]),_g._SearchInPoints(t,i,s)||r.push([t,i]),_g._SearchInPoints(i,e,s)||r.push([i,e]),0===r.length?null:r}static _SearchInPoints(e,t,i){for(const s of i)for(let i=0;i{const r=e.getVerticesData(Ki.PositionKind),n=e.getIndices();if(r&&n)for(let o=0,a=0;o[e.x,e.y,e.z]))}static GetPointsCountInfo(e){const t=new Array(e.length);let i=0;for(let s=e.length;s--;)t[s]=e[s].length/3,i+=t[s];return{total:i,counts:t}}static GetLineLength(e){if(0===e.length)return 0;let t;t="number"==typeof e[0]?_g.ToVector3Array(e):e;const i=U.Vector3[0];let s=0;for(let e=0;e{e.length>t?_g.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t)).forEach((e=>{s.push(e)})):(s.push(e.point1),s.push(e.point2))})),s}static SegmentizeLineBySegmentCount(e,t){const i="number"==typeof e[0]?_g.ToVector3Array(e):e,s=_g.GetLineLength(i)/t;return _g.SegmentizeLineBySegmentLength(i,s)}static GetLineSegments(e){const t=[];for(let i=0;ie.length));return{min:t[0].length,max:t[t.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,s=!1){const r=t*i;let n=0,o=0;const a=e.length;for(let t=0;t[e.x,e.y,e.z]))}static GetArrowCap(e,t,i,s,r,n=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[s,r,n,o]}}static GetPointsFromText(e,t,i,s,r=0,n=!0){const o=[],a=function(e,t,i,s){const r=Array.from(e),n=t/s.resolution,o=(s.boundingBox.yMax-s.boundingBox.yMin+s.underlineThickness)*n,a=[];let l=0,h=0;for(let e=0;er?r:t.length,o=Math.ceil(t.length/r);o>1&&(t=[...t,...Array(n*o-t.length).fill(t[0])]);const a=_g.Color3toRGBAUint8(t),l=new io(a,n,o,Br.TEXTUREFORMAT_RGBA,s,!1,!0,i);return l.name=e,l}static PrepareEmptyColorsTexture(e){if(!fg.EmptyColorsTexture){const t=new Uint8Array(4);fg.EmptyColorsTexture=new io(t,1,1,Br.TEXTUREFORMAT_RGBA,e,!1,!1,io.NEAREST_NEAREST),fg.EmptyColorsTexture.name="grlEmptyColorsTexture"}return fg.EmptyColorsTexture}static DisposeEmptyColorsTexture(){fg.EmptyColorsTexture?.dispose(),fg.EmptyColorsTexture=null}static BooleanToNumber(e){return e?1:0}}class mg extends Do{constructor(){super(...arguments),this.GREASED_LINE_HAS_COLOR=!1,this.GREASED_LINE_SIZE_ATTENUATION=!1,this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=!1,this.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=!1,this.GREASED_LINE_CAMERA_FACING=!0}}class gg extends ah{constructor(e,t,i){i=i||{color:fg.DEFAULT_COLOR};const s=new mg;s.GREASED_LINE_HAS_COLOR=!!i.color&&!i.useColors,s.GREASED_LINE_SIZE_ATTENUATION=i.sizeAttenuation??!1,s.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=i.colorDistributionType===ag.COLOR_DISTRIBUTION_TYPE_LINE,s.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=(t??e.getScene()).useRightHandedSystem,s.GREASED_LINE_CAMERA_FACING=i.cameraFacing??!0,super(e,gg.GREASED_LINE_MATERIAL_NAME,200,s),this.colorsTexture=null,this._scene=t??e.getScene(),this._engine=this._scene.getEngine(),this._cameraFacing=i.cameraFacing??!0,this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.width=i.width?i.width:i.sizeAttenuation?fg.DEFAULT_WIDTH_ATTENUATED:fg.DEFAULT_WIDTH,this._sizeAttenuation=i.sizeAttenuation??!1,this.colorMode=i.colorMode??og.COLOR_MODE_SET,this._color=i.color??null,this.useColors=i.useColors??!1,this._colorsDistributionType=i.colorDistributionType??ag.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=i.colorsSampling??io.NEAREST_NEAREST,this._colors=i.colors??null,this.dashCount=i.dashCount??1,this.resolution=i.resolution??new N(this._engine.getRenderWidth(),this._engine.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this._colors?this.colorsTexture=_g.CreateColorsTexture(`${e.name}-colors-texture`,this._colors,this.colorsSampling,this._scene):(this._color=this._color??fg.DEFAULT_COLOR,_g.PrepareEmptyColorsTexture(this._scene)),this._engine.onDisposeObservable.add((()=>{_g.DisposeEmptyColorsTexture()})),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this.colorsTexture&&e.push(this.colorsTexture)}getUniforms(){const e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_textureSize",size:2,type:"vec2"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?"\n uniform vec4 grl_aspect_resolution_lineWidth;\n uniform mat4 grl_projection;\n ":"",fragment:"\n uniform vec4 grl_dashOptions;\n uniform vec2 grl_textureSize;\n uniform vec4 grl_colorMode_visibility_colorsWidth_useColors;\n uniform vec3 grl_singleColor;\n "}}get isEnabled(){return!0}bindForSubMesh(e){if(this._cameraFacing){const t=this._scene.activeCamera;if(!t)throw Error("GreasedLinePluginMaterial requires an active camera.");{const i=t.getProjectionMatrix();e.updateMatrix("grl_projection",i)}const i=U.Vector4[0];i.x=this._aspect,i.y=this._resolution.x,i.z=this._resolution.y,i.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",i)}const t=U.Vector4[0];t.x=_g.BooleanToNumber(this.useDash),t.y=this._dashArray,t.z=this.dashOffset,t.w=this.dashRatio,e.updateVector4("grl_dashOptions",t);const i=U.Vector4[1];i.x=this.colorMode,i.y=this.visibility,i.z=this.colorsTexture?this.colorsTexture.getSize().width:0,i.w=_g.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",i),this._color&&e.updateColor3("grl_singleColor",this._color);const s=this.colorsTexture??fg.EmptyColorsTexture;e.setTexture("grl_colors",s),e.updateFloat2("grl_textureSize",s?.getSize().width??1,s?.getSize().height??1)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===ag.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return gg.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if("vertex"===e){const e={CUSTOM_VERTEX_DEFINITIONS:"\n attribute float grl_widths;\n attribute vec3 grl_offsets;\n attribute float grl_colorPointers;\n varying float grlCounters;\n varying float grlColorPointer;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n attribute vec4 grl_previousAndSide;\n attribute vec4 grl_nextAndCounters;\n\n vec2 grlFix( vec4 i, float aspect ) {\n vec2 res = i.xy / i.w;\n res.x *= aspect;\n return res;\n }\n #else\n attribute vec3 grl_slopes;\n attribute float grl_counters;\n #endif\n ",CUSTOM_VERTEX_UPDATE_POSITION:"\n #ifdef GREASED_LINE_CAMERA_FACING\n vec3 grlPositionOffset = grl_offsets;\n positionUpdated += grlPositionOffset;\n #else\n positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths);\n #endif\n ",CUSTOM_VERTEX_MAIN_END:"\n grlColorPointer = grl_colorPointers;\n\n #ifdef GREASED_LINE_CAMERA_FACING\n\n float grlAspect = grl_aspect_resolution_lineWidth.x;\n float grlBaseWidth = grl_aspect_resolution_lineWidth.w;\n\n\n vec3 grlPrevious = grl_previousAndSide.xyz;\n float grlSide = grl_previousAndSide.w;\n\n vec3 grlNext = grl_nextAndCounters.xyz;\n grlCounters = grl_nextAndCounters.w;\n\n mat4 grlMatrix = viewProjection * finalWorld;\n vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 );\n vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 );\n vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 );\n\n vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect );\n vec2 grlPrevP = grlFix( grlPrevPos, grlAspect );\n vec2 grlNextP = grlFix( grlNextPos, grlAspect );\n\n float grlWidth = grlBaseWidth * grl_widths;\n\n vec2 grlDir;\n if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP );\n else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP );\n else {\n vec2 grlDir1 = normalize( grlCurrentP - grlPrevP );\n vec2 grlDir2 = normalize( grlNextP - grlCurrentP );\n grlDir = normalize( grlDir1 + grlDir2 );\n }\n vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. );\n #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\n grlNormal.xy *= -.5 * grlWidth;\n #else\n grlNormal.xy *= .5 * grlWidth;\n #endif\n\n grlNormal *= grl_projection;\n\n #ifdef GREASED_LINE_SIZE_ATTENUATION\n grlNormal.xy *= grlFinalPosition.w;\n grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy;\n #endif\n\n grlFinalPosition.xy += grlNormal.xy * grlSide;\n gl_Position = grlFinalPosition;\n\n vPositionW = vec3(grlFinalPosition);\n #else\n grlCounters = grl_counters;\n #endif\n "};return this._cameraFacing&&(e["!gl_Position\\=viewProjection\\*worldPos;"]="//"),e}return"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:"\n varying float grlCounters;\n varying float grlColorPointer;\n uniform sampler2D grl_colors;\n ",CUSTOM_FRAGMENT_MAIN_END:`\n float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x;\n float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y;\n float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z;\n float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w;\n\n float grlUseDash = grl_dashOptions.x;\n float grlDashArray = grl_dashOptions.y;\n float grlDashOffset = grl_dashOptions.z;\n float grlDashRatio = grl_dashOptions.w;\n\n gl_FragColor.a *= step(grlCounters, grlVisibility);\n if( gl_FragColor.a == 0. ) discard;\n\n if(grlUseDash == 1.){\n gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio));\n if (gl_FragColor.a == 0.) discard;\n }\n\n #ifdef GREASED_LINE_HAS_COLOR\n if (grlColorMode == ${og.COLOR_MODE_SET}.) {\n gl_FragColor.rgb = grl_singleColor;\n } else if (grlColorMode == ${og.COLOR_MODE_ADD}.) {\n gl_FragColor.rgb += grl_singleColor;\n } else if (grlColorMode == ${og.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor.rgb *= grl_singleColor;\n }\n #else\n if (grlUseColors == 1.) {\n #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE\n vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.);\n #else\n vec2 lookup = vec2(fract(grlColorPointer / grl_textureSize.x), 1.0 - floor(grlColorPointer / grl_textureSize.x) / max(grl_textureSize.y - 1.0, 1.0));\n vec4 grlColor = texture2D(grl_colors, lookup, 0.0);\n #endif\n if (grlColorMode == ${og.COLOR_MODE_SET}.) {\n gl_FragColor = grlColor;\n } else if (grlColorMode == ${og.COLOR_MODE_ADD}.) {\n gl_FragColor += grlColor;\n } else if (grlColorMode == ${og.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor *= grlColor;\n }\n }\n #endif\n\n `}:null}dispose(){this.colorsTexture?.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){const s=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this.colorsTexture&&s===e.length&&!i){const t=_g.Color3toRGBAUint8(e);this.colorsTexture.update(t)}else this.colorsTexture?.dispose(),this.colorsTexture=_g.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}else this.colorsTexture?.dispose()}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){null===this._color&&null!==e||null!==this._color&&null===e?(this._color=e,!t&&this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){super.parse(e,t,i);const s=e.greasedLineMaterialOptions;this.colorsTexture?.dispose(),s.color&&this.setColor(s.color,!0),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colors&&(this.colors=s.colors),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),this.colors?this.colorsTexture=_g.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):_g.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){const t=e;t.colorsTexture?.dispose(),this._colors&&(t.colorsTexture=_g.CreateColorsTexture(`${t._material.name}-colors-texture`,this._colors,t.colorsSampling,this._scene)),t.setColor(this.color,!0),t.colorsDistributionType=this.colorsDistributionType,t.colorsSampling=this.colorsSampling,t.colorMode=this.colorMode,t.useColors=this.useColors,t.visibility=this.visibility,t.useDash=this.useDash,t.dashCount=this.dashCount,t.dashRatio=this.dashRatio,t.dashOffset=this.dashOffset,t.width=this.width,t.sizeAttenuation=this.sizeAttenuation,t.resolution=this.resolution,t.markAllDefinesAsDirty()}}gg.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",u(`BABYLON.${gg.GREASED_LINE_MATERIAL_NAME}`,gg);Ft.ShadersStore.greasedLinePixelShader="precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;}\nif (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { \ntextureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);}\nif (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}}\n";Ft.ShadersStore.greasedLineVertexShader="precision highp float;\n#include\nattribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer;\n#ifdef GREASED_LINE_CAMERA_FACING\nattribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;}\n#else\nattribute vec3 grl_slopes;attribute float grl_counters;\n#endif\nvoid main() {\n#include\ngrlColorPointer=grl_colorPointers;mat4 grlMatrix=viewProjection*finalWorld ;\n#ifdef GREASED_LINE_CAMERA_FACING\nfloat grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );}\nvec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. );\n#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM\ngrlNormal.xy*=-.5*grlWidth;\n#else\ngrlNormal.xy*=.5*grlWidth;\n#endif\ngrlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;}\ngrlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition;\n#else\ngrlCounters=grl_counters;vec4 grlFinalPosition=grlMatrix*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition;\n#endif\n}\n";class vg extends fc{constructor(e,t,i){const s=[`COLOR_DISTRIBUTION_TYPE_LINE ${ag.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${ag.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${og.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${og.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${og.COLOR_MODE_MULTIPLY}.`],r=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&s.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(s.push("GREASED_LINE_CAMERA_FACING"),r.push("grl_previousAndSide","grl_nextAndCounters")):(r.push("grl_slopes"),r.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:r,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:s}),this._color=Y.White(),this._colorsDistributionType=ag.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:fg.DEFAULT_COLOR};const n=t.getEngine();this.visibility=i.visibility??1,this.useDash=i.useDash??!1,this.dashRatio=i.dashRatio??.5,this.dashOffset=i.dashOffset??0,this.dashCount=i.dashCount??1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?fg.DEFAULT_WIDTH_ATTENUATED:fg.DEFAULT_WIDTH,this.sizeAttenuation=i.sizeAttenuation??!1,this.color=i.color??Y.White(),this.useColors=i.useColors??!1,this.colorsDistributionType=i.colorDistributionType??ag.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=i.colorsSampling??io.NEAREST_NEAREST,this.colorMode=i.colorMode??og.COLOR_MODE_SET,this._colors=i.colors??null,this._cameraFacing=i.cameraFacing??!0,this.resolution=i.resolution??new N(n.getRenderWidth(),n.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=_g.PrepareEmptyColorsTexture(t),this._colors&&this.setColors(this._colors),n.onDisposeObservable.add((()=>{_g.DisposeEmptyColorsTexture()}))}dispose(){this._colorsTexture?.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new N(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){const s=this._colors?.length??0;if(this._colors=e,null!==e&&0!==e.length){if(!t||i)if(this._colorsTexture&&s===e.length&&!i){const t=_g.Color3toRGBAUint8(e);this._colorsTexture.update(t)}else this._colorsTexture?.dispose(),this.colorsTexture=_g.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}else this._colorsTexture?.dispose()}get colorsTexture(){return this._colorsTexture??null}set colorsTexture(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",_g.BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",_g.BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",_g.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=e??fg.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){const e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){const s=e.greasedLineMaterialOptions;this._colorsTexture?.dispose(),s.color&&(this.color=s.color),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),s.colors?this.colorsTexture=_g.CreateColorsTexture(`${this.name}-colors-texture`,s.colors,this.colorsSampling,this.getScene()):this.colorsTexture=_g.PrepareEmptyColorsTexture(t),this._cameraFacing=s.cameraFacing??!0,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}const xg=[new Y(.98,.26,.38),new Y(.47,.75,.3),new Y(0,.26,.77),new Y(.97,.6,.76),new Y(.19,.63,.78),new Y(.98,.8,.6),new Y(.65,.43,.15),new Y(.15,.47,.22),new Y(.67,.71,.86),new Y(.09,.46,.56),new Y(.8,.98,.02),new Y(.39,.29,.13),new Y(.53,.63,.06),new Y(.95,.96,.41),new Y(1,.72,.94),new Y(.63,.08,.31),new Y(.66,.96,.95),new Y(.22,.14,.19),new Y(.14,.65,.59),new Y(.93,1,.68),new Y(.93,.14,.44),new Y(.47,.86,.67),new Y(.85,.07,.78),new Y(.53,.64,.98),new Y(.43,.37,.56),new Y(.71,.65,.25),new Y(.66,.19,.01),new Y(.94,.53,.12),new Y(.41,.44,.44),new Y(.24,.71,.96),new Y(.57,.28,.56),new Y(.44,.98,.42)];var Tg;!function(e){e[e.NONE=0]="NONE",e[e.TRIANGLES=1]="TRIANGLES",e[e.VERTICES=2]="VERTICES",e[e.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",e[e.UV0=4]="UV0",e[e.UV1=5]="UV1",e[e.VERTEXCOLORS=6]="VERTEXCOLORS",e[e.MATERIALIDS=7]="MATERIALIDS"}(Tg||(Tg={}));class Sg extends Do{constructor(){super(...arguments),this.DBG_MODE=Tg.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class Eg extends ah{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){const i=new Sg;i.DBG_MODE=t.mode??i.DBG_MODE,i.DBG_MULTIPLY=t.multiply??i.DBG_MULTIPLY,super(e,"MeshDebug",200,i,!0,!0),this._mode=i.DBG_MODE,this._multiply=i.DBG_MULTIPLY,this.shadedDiffuseColor=t.shadedDiffuseColor??new Y(1,1,1),this.shadedSpecularColor=t.shadedSpecularColor??new Y(.8,.8,.8),this.shadedSpecularPower=t.shadedSpecularPower??10,this.wireframeThickness=t.wireframeThickness??.7,this.wireframeTrianglesColor=t.wireframeTrianglesColor??new Y(0,0,0),this.wireframeVerticesColor=t.wireframeVerticesColor??new Y(.8,.8,.8),this.vertexColor=t.vertexColor??new Y(0,0,0),this.vertexRadius=t.vertexRadius??1.2,this.uvScale=t.uvScale??20,this.uvPrimaryColor=t.uvPrimaryColor??new Y(1,1,1),this.uvSecondaryColor=t.uvSecondaryColor??new Y(.5,.5,.5),this._materialColor=Eg.MaterialColors[Eg._PluginCount++%Eg.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&1==this._material.getScene().getEngine().version)return J.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),void(this._isEnabled=!1);this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){this._mode!=Tg.VERTICES&&this._mode!=Tg.TRIANGLES&&this._mode!=Tg.TRIANGLES_VERTICES||i.isVerticesDataPresent("dbg_initialPass")||J.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:"#if defined(DBG_ENABLED)\nuniform vec3 dbg_shadedDiffuseColor;\nuniform vec4 dbg_shadedSpecularColorPower;\nuniform vec3 dbg_thicknessRadiusScale;\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n uniform vec3 dbg_vertexColor;\n#endif\n\n#if DBG_MODE == 1\n uniform vec3 dbg_wireframeTrianglesColor;\n#elif DBG_MODE == 3\n uniform vec3 dbg_wireframeVerticesColor;\n#elif DBG_MODE == 4 || DBG_MODE == 5\n uniform vec3 dbg_uvPrimaryColor;\n uniform vec3 dbg_uvSecondaryColor;\n#elif DBG_MODE == 7\n uniform vec3 dbg_materialColor;\n#endif\n#endif"}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:"#if defined(DBG_ENABLED)\nattribute float dbg_initialPass;\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n#endif",CUSTOM_VERTEX_MAIN_END:"#if defined(DBG_ENABLED)\nfloat dbg_vertexIndex = mod(float(gl_VertexID), 3.);\nif (dbg_vertexIndex == 0.0) { \n dbg_vBarycentric = vec3(1.,0.,0.); \n}\nelse if (dbg_vertexIndex == 1.0) { \n dbg_vBarycentric = vec3(0.,1.,0.); \n}\nelse { \n dbg_vBarycentric = vec3(0.,0.,1.); \n}\n\ndbg_vVertexWorldPos = vPositionW;\ndbg_vPass = dbg_initialPass;\n#endif"}:{CUSTOM_FRAGMENT_DEFINITIONS:"#if defined(DBG_ENABLED)\nvarying vec3 dbg_vBarycentric;\nflat varying vec3 dbg_vVertexWorldPos;\nflat varying float dbg_vPass;\n\n#if !defined(DBG_MULTIPLY)\n vec3 dbg_applyShading(vec3 color) {\n vec3 N = vNormalW.xyz;\n vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz);\n vec3 H = normalize(L + L);\n float LdotN = clamp(dot(L,N), 0., 1.);\n float HdotN = clamp(dot(H,N), 0., 1.);\n float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w);\n color *= (LdotN / PI);\n color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI);\n return color;\n }\n#endif\n\n#if DBG_MODE == 1 || DBG_MODE == 3\n float dbg_edgeFactor() {\n vec3 d = fwidth(dbg_vBarycentric);\n vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric);\n return min(min(a3.x, a3.y), a3.z);\n }\n#endif\n\n#if DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor() {\n vec3 worldPos = vPositionW;\n float dist = length(worldPos - dbg_vVertexWorldPos);\n float camDist = length(worldPos - vEyePosition.xyz);\n float d = sqrt(camDist) * .001;\n return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist);\n }\n#endif\n\n#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2))\n float dbg_checkerboardFactor(vec2 uv) {\n vec2 f = fract(uv * dbg_thicknessRadiusScale.z);\n f -= .5;\n return (f.x * f.y) > 0. ? 1. : 0.;\n }\n#endif\n#endif",CUSTOM_FRAGMENT_MAIN_END:"#if defined(DBG_ENABLED)\nvec3 dbg_color = vec3(1.);\n#if DBG_MODE == 1\n dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor());\n#elif DBG_MODE == 2 || DBG_MODE == 3\n float dbg_cornerFactor = dbg_cornerFactor();\n if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard;\n dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor);\n #if DBG_MODE == 3\n dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor());\n #endif\n#elif DBG_MODE == 4 && defined(MAINUV1)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1));\n#elif DBG_MODE == 5 && defined(MAINUV2)\n dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2));\n#elif DBG_MODE == 6 && defined(VERTEXCOLOR)\n dbg_color = vColor.rgb;\n#elif DBG_MODE == 7\n dbg_color = dbg_materialColor;\n#endif\n\n#if defined(DBG_MULTIPLY)\n gl_FragColor *= vec4(dbg_color, 1.);\n#else\n #if DBG_MODE != 6\n gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.);\n #else\n gl_FragColor = vec4(dbg_color, 1.);\n #endif\n#endif\n#endif"}}static Reset(){this._PluginCount=0,this.MaterialColors=xg}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(0==e.getTotalIndices())return i;if(t){const t=e.getVerticesDataKinds(),s=e.getIndices(),r={};for(const i of t)r[i]=e.getVerticesData(i);i=function(){e.setIndices(s);for(const i of t){const t=e.getVertexBuffer(i).getStrideSize();e.setVerticesData(i,r[i],void 0,t)}e.removeVerticesData("dbg_initialPass")}}let s=Array.from(e.getIndices());const r=[];for(let e=0;enew Cg(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.GaussianSplattingMaterial",e}getClassName(){return"GaussianSplattingMaterial"}static Parse(e,t,i){return Pe.Parse((()=>new Cg(e.name,t)),e,t,i)}}u("BABYLON.GaussianSplattingMaterial",Cg),Object.defineProperty(dh.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new pg(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(Cf.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new pg(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(Wr.prototype,"decalMap",{get:function(){return this._decalMap},set:function(e){this._decalMap=e},enumerable:!0,configurable:!0});class yg{constructor(e,t=2,i=3,s=1,r=1){this._curIndex=0,this._sequence=[],this._numSamples=0,this.x=0,this.y=0,this._width=s,this._height=r,this._baseX=t,this._baseY=i,this._generateSequence(e),this.next()}regenerate(e){this._generateSequence(e),this.next()}setDimensions(e,t){this._width=e,this._height=t}next(){this.x=this._sequence[this._curIndex]/this._width,this.y=this._sequence[this._curIndex+1]/this._height,this._curIndex+=2,this._curIndex>=2*this._numSamples&&(this._curIndex=0)}_generateSequence(e){this._sequence=[],this._curIndex=0,this._numSamples=e;for(let t=1;t<=e;++t)this._sequence.push(this._halton(t,this._baseX)-.5,this._halton(t,this._baseY)-.5)}_halton(e,t){let i=1,s=0;for(;e>0;)i/=t,s+=i*(e%t),e=~~(e/t);return s}}function Ag(e,t){return`{X: ${e._x.toFixed(t)} Y: ${e._y.toFixed(t)} Z: ${e._z.toFixed(t)}}`}function Rg(e,t){return`{X: ${e.x.toFixed(t)} Y: ${e.y.toFixed(t)} Z: ${e.z.toFixed(t)} W: ${e.w.toFixed(t)}}`}function Ig(e,t,i,s,r){let n=null,o=null,a=null;try{let l;n=new e.Decoder,o=new e.DecoderBuffer,o.Init(t,t.byteLength);const h=n.GetEncodedGeometryType(o);switch(h){case e.TRIANGULAR_MESH:{const t=new e.Mesh;if(l=n.DecodeBufferToMesh(o,t),!l.ok()||0===t.ptr)throw new Error(l.error_msg());const i=3*t.num_faces(),r=4*i,h=e._malloc(r);try{n.GetTrianglesUInt32Array(t,r,h);const o=new Uint32Array(i);o.set(new Uint32Array(e.HEAPF32.buffer,h,i)),s(o)}finally{e._free(h)}a=t;break}case e.POINT_CLOUD:{const t=new e.PointCloud;if(l=n.DecodeBufferToPointCloud(o,t),!l.ok()||!t.ptr)throw new Error(l.error_msg());a=t;break}default:throw new Error(`Invalid geometry type ${h}`)}const c=a.num_points(),u=(t,i,s,n)=>{const o=n.data_type(),a=n.num_components(),l=n.normalized(),h=n.byte_stride(),u=n.byte_offset(),d={[e.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:e.HEAPF32},[e.DT_INT8]:{typedArrayConstructor:Int8Array,heap:e.HEAP8},[e.DT_INT16]:{typedArrayConstructor:Int16Array,heap:e.HEAP16},[e.DT_INT32]:{typedArrayConstructor:Int32Array,heap:e.HEAP32},[e.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:e.HEAPU8},[e.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:e.HEAPU16},[e.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:e.HEAPU32}}[o];if(!d)throw new Error(`Invalid data type ${o}`);const p=c*a,f=p*d.typedArrayConstructor.BYTES_PER_ELEMENT,_=e._malloc(f);try{t.GetAttributeDataArrayForAllPoints(i,n,o,f,_);const e=new d.typedArrayConstructor(d.heap.buffer,_,p);r(s,e.slice(),a,u,h,l)}finally{e._free(_)}};if(i)for(const e in i){const t=i[e],s=n.GetAttributeByUniqueId(a,t);u(n,a,e,s)}else{const t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(const e in t){const i=n.GetAttributeId(a,t[e]);if(-1!==i){const t=n.GetAttribute(a,i);u(n,a,e,t)}}}return c}finally{a&&e.destroy(a),o&&e.destroy(o),n&&e.destroy(n)}}function Pg(){let e;onmessage=t=>{const i=t.data;switch(i.id){case"init":{const t=i.decoder;t.url&&importScripts(t.url);const s=t.wasmBinary?{wasmBinary:t.wasmBinary}:{};e=DracoDecoderModule(s),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((e=>{const t=Ig(e,i.dataView,i.attributes,(e=>{postMessage({id:"indices",data:e},[e.buffer])}),((e,t,i,s,r,n)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:s,byteStride:r,normalized:n},[t.buffer])}));postMessage({id:"decodeMeshDone",totalVertices:t})}))}}}class Mg{static get DecoderAvailable(){const e=Mg.Configuration.decoder;return!!(e.wasmUrl&&e.wasmBinaryUrl&&"object"==typeof WebAssembly||e.fallbackUrl)}static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static get Default(){return Mg._Default||(Mg._Default=new Mg),Mg._Default}static ResetDefault(e){Mg._Default&&(e||Mg._Default.dispose(),Mg._Default=null)}constructor(e=Mg.DefaultNumWorkers){const t=Mg.Configuration.decoder;if(t.workerPool||"object"==typeof e&&e.workerPool)this._workerPoolPromise=Promise.resolve(t.workerPool||e.workerPool);else{const i=t.wasmBinary||"object"==typeof e&&e.wasmBinary,s="number"==typeof e?e:e.numWorkers,r=s&&"function"==typeof Worker&&"function"==typeof URL,n=r||!r&&!t.jsModule,o=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:n?Ii.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:i?Promise.resolve(i):Ii.LoadFileAsync(Ii.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:n?Ii.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};r?this._workerPoolPromise=o.wasmBinaryPromise.then((e=>{const t=`${Ig}(${Pg})()`,i=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));return new If(s,(()=>function(e,t,i){return new Promise(((s,r)=>{const n=t=>{e.removeEventListener("error",n),e.removeEventListener("message",o),r(t)},o=t=>{"initDone"===t.data.id&&(e.removeEventListener("error",n),e.removeEventListener("message",o),s(e))};if(e.addEventListener("error",n),e.addEventListener("message",o),t){const s=t.slice(0);e.postMessage({id:"init",decoder:{url:i,wasmBinary:s}},[s])}else e.postMessage({id:"init",decoder:{url:i}})}))}(new Worker(i),e,o.url)))})):this._decoderModulePromise=o.wasmBinaryPromise.then((async e=>{if("undefined"==typeof DracoDecoderModule&&!t.jsModule){if(!o.url)throw new Error("Draco decoder module is not available");await Ii.LoadBabylonScriptAsync(o.url)}return await(i=e,s=t.jsModule,new Promise((e=>{(s||DracoDecoderModule)({wasmBinary:i}).then((t=>{e({module:t})}))})));var i,s}))}}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then((e=>{e.dispose()})),delete this._workerPoolPromise,delete this._decoderModulePromise}async whenReadyAsync(){this._workerPoolPromise?await this._workerPoolPromise:this._decoderModulePromise&&await this._decoderModulePromise}decodeMeshToMeshDataAsync(e,t,i){const s=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength);if(this._workerPoolPromise)return this._workerPoolPromise.then((e=>new Promise(((r,n)=>{e.push(((e,o)=>{let a=null;const l=[],h=t=>{e.removeEventListener("error",h),e.removeEventListener("message",c),n(t),o()},c=t=>{const s=t.data;switch(s.id){case"decodeMeshDone":e.removeEventListener("error",h),e.removeEventListener("message",c),r({indices:a,attributes:l,totalVertices:s.totalVertices}),o();break;case"indices":a=s.data;break;case"attribute":l.push({kind:s.kind,data:s.data,size:s.size,byteOffset:s.byteOffset,byteStride:s.byteStride,normalized:(n=s.kind,u=s.normalized,i&&void 0!==i[n]?(u!==i[n]&&J.Warn(`Normalized flag from Draco data (${u}) does not match normalized flag from glTF accessor (${i[n]}). Using flag from glTF accessor.`),i[n]):u)})}var n,u};e.addEventListener("error",h),e.addEventListener("message",c);const u=s.slice();e.postMessage({id:"decodeMesh",dataView:u,attributes:t},[u.buffer])}))}))));if(this._decoderModulePromise)return this._decoderModulePromise.then((e=>{let i=null;const r=[],n=Ig(e.module,s,t,(e=>{i=e}),((e,t,i,s,n,o)=>{r.push({kind:e,data:t,size:i,byteOffset:s,byteStride:n,normalized:o})}));return{indices:i,attributes:r,totalVertices:n}}));throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,i,s){const r=await this.decodeMeshToMeshDataAsync(i,s),n=new br(e,t);r.indices&&n.setIndices(r.indices);for(const e of r.attributes)n.setVerticesBuffer(new Ki(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),r.totalVertices);return n}async _decodeMeshToGeometryForGltfAsync(e,t,i,s,r){const n=await this.decodeMeshToMeshDataAsync(i,s,r),o=new br(e,t);n.indices&&o.setIndices(n.indices);for(const e of n.attributes)o.setVerticesBuffer(new Ki(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),n.totalVertices);return o}async decodeMeshAsync(e,t){const i=await this.decodeMeshToMeshDataAsync(e,t),s=new Tr;i.indices&&(s.indices=i.indices);for(const e of i.attributes){const t=Ki.GetFloatData(e.data,e.size,Ki.GetDataType(e.data),e.byteOffset,e.byteStride,e.normalized,i.totalVertices);s.set(t,e.kind)}return s}}Mg.Configuration={decoder:{wasmUrl:`${Ii._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${Ii._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${Ii._DefaultCdnUrl}/draco_decoder_gltf.js`}},Mg.DefaultNumWorkers=Mg.GetDefaultNumWorkers(),Mg._Default=null;class Dg{static get Default(){return Dg._Default||(Dg._Default=new Dg),Dg._Default}constructor(){const e=Dg.Configuration.decoder;this._decoderModulePromise=Ii.LoadBabylonScriptAsync(e.url).then((()=>MeshoptDecoder.ready))}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,s,r){return this._decoderModulePromise.then((async()=>{MeshoptDecoder.useWorkers(1);const n=await MeshoptDecoder.decodeGltfBufferAsync(t,i,e,s,r);return MeshoptDecoder.useWorkers(0),n}))}}Dg.Configuration={decoder:{url:`${Ii._DefaultCdnUrl}/meshopt_decoder.js`}},Dg._Default=null;let Og=0;class Ng{constructor(e,t,i,s){this.pos=e,this.normal=t,this.uv=i,this.vertColor=s}clone(){return new Ng(this.pos.clone(),this.normal.clone(),this.uv?.clone(),this.vertColor?.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new Ng(w.Lerp(this.pos,e.pos,t),w.Lerp(this.normal,e.normal,t),this.uv&&e.uv?N.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?j.Lerp(this.vertColor,e.vertColor,t):void 0)}}class wg{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const s=i.subtract(e),r=t.subtract(e);if(0===s.lengthSquared()||0===r.lengthSquared())return null;const n=w.Normalize(w.Cross(s,r));return new wg(n,w.Dot(n,e))}clone(){return new wg(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,s,r){let n=0;const o=[];let a,l;for(a=0;awg.EPSILON?1:0;n|=t,o.push(t)}switch(n){case 0:(w.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:s.push(e);break;case 2:r.push(e);break;case 3:{const t=[],i=[];for(a=0;a=3&&(n=new Fg(t,e.shared),n.plane&&s.push(n)),i.length>=3&&(n=new Fg(i,e.shared),n.plane&&r.push(n));break}}}}wg.EPSILON=1e-5;class Fg{constructor(e,t){this.vertices=e,this.shared=t,this.plane=wg.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map((e=>e.clone()));return new Fg(e,this.shared)}flip(){this.vertices.reverse().map((e=>{e.flip()})),this.plane.flip()}}class Lg{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=new Array,e&&this.build(e)}clone(){const e=new Lg;return e._plane=this._plane&&this._plane.clone(),e._front=this._front&&this._front.clone(),e._back=this._back&&this._back.clone(),e._polygons=this._polygons.map((e=>e.clone())),e}invert(){for(let e=0;ee.clone())),e.copyTransformAttributes(this),e}union(e){const t=new Lg(this.clone()._polygons),i=new Lg(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),Bg._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){const t=new Lg(this._polygons),i=new Lg(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()}subtract(e){const t=new Lg(this.clone()._polygons),i=new Lg(e.clone()._polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),Bg._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){const t=new Lg(this._polygons),i=new Lg(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}intersect(e){const t=new Lg(this.clone()._polygons),i=new Lg(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),Bg._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){const t=new Lg(this._polygons),i=new Lg(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){const e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map((e=>{e.flip()}))}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){const i=this.matrix.clone();i.invert();const s=this._polygons,r=[],n=[],o=[];let a=null,l=null;const h=w.Zero(),c=w.Zero(),u=N.Zero(),d=new j(0,0,0,0),p=[0,0,0],f={};let _;for(let m=0,g=s.length;me.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId)),this.toVertexData((e=>{o[e.shared.meshId]||(o[e.shared.meshId]={}),o[e.shared.meshId][e.shared.subMeshId]||(o[e.shared.meshId][e.shared.subMeshId]={indexStart:1/0,indexEnd:-1/0,materialIndex:e.shared.materialIndex}),a=o[e.shared.meshId][e.shared.subMeshId]}),(()=>{a.indexStart=Math.min(n,a.indexStart),a.indexEnd=Math.max(n,a.indexEnd),n++})).applyToMesh(s),i){let e,t=0;s.subMeshes=[];for(const i in o){e=-1;for(const r in o[i])a=o[i][r],vr.CreateFromIndices(a.materialIndex+t,a.indexStart,a.indexEnd-a.indexStart+1,s),e=Math.max(a.materialIndex,e);t+=++e}}return s}toMesh(e,t=null,i,s){const r=this.buildMeshGeometry(e,i,s);return r.material=t,r.position.copyFrom(this.position),r.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(r.rotationQuaternion=this.rotationQuaternion.clone()),r.scaling.copyFrom(this.scaling),r.computeWorldMatrix(!0),r}}Ft.ShadersStore.meshUVSpaceRendererVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nvoid main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW;\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\n#endif\nvec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);}";Ft.ShadersStore.meshUVSpaceRendererPixelShader="precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;}\ngl_FragColor=texture2D(textureSampler,vDecalTC);}\n";Ft.ShadersStore.meshUVSpaceRendererMaskerVertexShader="attribute vec2 uv;varying vec2 vUV;void main(void) {gl_Position=vec4(vec2(uv.x,uv.y)*2.0-1.0,0.,1.0);vUV=uv;}";Ft.ShadersStore.meshUVSpaceRendererMaskerPixelShader="varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);}\n";Ft.ShadersStore.meshUVSpaceRendererFinaliserPixelShader="precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D maskTextureSampler;uniform vec2 textureSize;void main() {vec4 mask=texture2D(maskTextureSampler,vUV).rgba;if (mask.r>0.5) {gl_FragColor=texture2D(textureSampler,vUV);} else {vec2 texelSize=4.0/textureSize;vec2 uv_p01=vUV+vec2(-1.0,0.0)*texelSize;vec2 uv_p21=vUV+vec2(1.0,0.0)*texelSize;vec2 uv_p10=vUV+vec2(0.0,-1.0)*texelSize;vec2 uv_p12=vUV+vec2(0.0,1.0)*texelSize;float mask_p01=texture2D(maskTextureSampler,uv_p01).r;float mask_p21=texture2D(maskTextureSampler,uv_p21).r;float mask_p10=texture2D(maskTextureSampler,uv_p10).r;float mask_p12=texture2D(maskTextureSampler,uv_p12).r;vec4 col=vec4(0.0,0.0,0.0,0.0);float total_weight=0.0;if (mask_p01>0.5) {col+=texture2D(textureSampler,uv_p01);total_weight+=1.0;}\nif (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;}\nif (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;}\nif (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;}\nif (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}}\n";Ft.ShadersStore.meshUVSpaceRendererFinaliserVertexShader="precision highp float;attribute vec3 position;attribute vec2 uv;uniform mat4 worldViewProjection;varying vec2 vUV;void main() {gl_Position=worldViewProjection*vec4(position,1.0);vUV=uv;}\n",Un._TrailMeshParser=(e,t)=>Vg.Parse(e,t);class Vg extends Un{constructor(e,t,i,s,r=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._generator=t,"object"==typeof s&&null!==s?(this.diameter=s.diameter||1,this._length=s.length||60,this._segments=s.segments?s.segments>this._length?this._length:s.segments:this._length,this._sectionPolygonPointsCount=s.sections||4,this._doNotTaper=s.doNotTaper||!1,this._autoStart=s.autoStart||!0):(this.diameter=s||1,this._length=r,this._segments=this._length,this._doNotTaper=!1,this._autoStart=n),this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e<=this._sectionPolygonPointsCount;e++)this._sectionVectors[e]=w.Zero(),this._sectionNormalVectors[e]=w.Zero();this._createMesh()}getClassName(){return"TrailMesh"}_createMesh(){const e=new Tr,t=[],i=[],s=[],r=[];let n=w.Zero();n=this._generator instanceof Wr&&this._generator.hasBoundingInfo?this._generator.getBoundingInfo().boundingBox.centerWorld:this._generator.absolutePosition;const o=2*Math.PI/this._sectionPolygonPointsCount;for(let e=0;e<=this._sectionPolygonPointsCount;e++){const i=e!==this._sectionPolygonPointsCount?e*o:0;t.push(n.x+Math.cos(i)*this.diameter,n.y+Math.sin(i)*this.diameter,n.z),r.push(e/this._sectionPolygonPointsCount,0)}for(let e=1;e<=this._segments;e++){for(let i=0;i<=this._sectionPolygonPointsCount;i++){const s=i!==this._sectionPolygonPointsCount?i*o:0;t.push(n.x+Math.cos(s)*this.diameter,n.y+Math.sin(s)*this.diameter,n.z),r.push(i/this._sectionPolygonPointsCount,e/this._segments)}const i=t.length/3-2*(this._sectionPolygonPointsCount+1);for(let e=0;e<=this._sectionPolygonPointsCount;e++)s.push(i+e,i+e+this._sectionPolygonPointsCount,i+e+this._sectionPolygonPointsCount+1),s.push(i+e,i+e+this._sectionPolygonPointsCount+1,i+e+1)}Tr.ComputeNormals(t,s,i),e.positions=t,e.normals=i,e.indices=s,e.uvs=r,e.applyToMesh(this,!0),this._autoStart&&this.start()}start(){this._running||(this._running=!0,this._beforeRenderObserver=this.getScene().onBeforeRenderObservable.add((()=>{this.update()})))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){const e=this.getVerticesData(Ki.PositionKind),t=this.getVerticesData(Ki.NormalKind),i=this._generator.getWorldMatrix(),s=3*(this._sectionPolygonPointsCount+1);if(e&&t){if(this._doNotTaper)for(let t=s;t{this._getSimplifier(e).simplify(t,(i=>{void 0!==t.distance&&e.mesh.addLODLevel(t.distance,i),i.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()}))}));else{const t=this._getSimplifier(e),i=(i,s)=>{t.simplify(i,(t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,s()}))};Pi.Run(e.settings.length,(t=>{i(e.settings[t.index],(()=>{t.executeNext()}))}),(()=>{e.successCallback&&e.successCallback(),this.executeNext()}))}}_getSimplifier(e){return e.simplificationType,kg.QUADRATIC,new cv(e.mesh)}}var kg,Gg,zg,Wg,Hg,Xg,Yg,jg,$g,Kg,qg,Qg,Zg,Jg,ev,tv,iv,sv,rv,nv;!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(kg||(kg={}));class ov{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class av{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new lv,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class lv{constructor(e){this.data=new Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,s,r,n,o,a,l){return this.data[e]*this.data[r]*this.data[l]+this.data[i]*this.data[s]*this.data[a]+this.data[t]*this.data[n]*this.data[o]-this.data[i]*this.data[r]*this.data[o]-this.data[e]*this.data[n]*this.data[a]-this.data[t]*this.data[s]*this.data[l]}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){const t=new lv;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,s){return new lv(lv.DataFromNumbers(e,t,i,s))}static DataFromNumbers(e,t,i,s){return[e*e,e*t,e*i,e*s,t*t,t*i,t*s,i*i,i*s,s*s]}}class hv{constructor(e,t){this.vertexId=e,this.triangleId=t}}class cv{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=T}simplify(e,t){this._initDecimatedMesh(),Pi.Run(this._mesh.subMeshes.length,(t=>{this._initWithMesh(t.index,(()=>{this._runDecimation(e,t.index,(()=>{t.executeNext()}))}),e.optimizeMesh)}),(()=>{setTimeout((()=>{t(this._reconstructedMesh)}),0)}))}_runDecimation(e,t,i){const s=~~(this._triangles.length*e.quality);let r=0;const n=this._triangles.length,o=(e,t)=>{setTimeout((()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e{const t=~~((this._triangles.length/2+e)%this._triangles.length),s=this._triangles[t];if(s&&!(s.error[3]>i||s.deleted||s.isDirty))for(let e=0;e<3;++e)if(s.error[e]{-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))})),h.length%2!=0)continue;n.q=o.q.add(n.q),n.updatePosition(a);const c=this._references.length;r=this._updateTriangles(n,n,t,r),r=this._updateTriangles(n,o,i,r);const u=this._references.length-c;if(u<=n.triangleCount){if(u)for(let e=0;en-r<=s))}),0)};Pi.Run(this.decimationIterations,(e=>{n-r<=s?e.breakLoop():o(e.index,(()=>{e.executeNext()}))}),(()=>{setTimeout((()=>{this._reconstructMesh(t),i()}),0)}))}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const s=this._mesh.getVerticesData(Ki.PositionKind),r=this._mesh.getIndices(),n=this._mesh.subMeshes[e],o=e=>{if(i)for(let t=0;t{if(!s)return;const t=e+n.verticesStart,i=w.FromArray(s,3*t),r=o(i)||new av(i,this._vertices.length);r.originalOffsets.push(t),r.id===this._vertices.length&&this._vertices.push(r),a.push(r.id)}),(()=>{Pi.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,(e=>{if(!r)return;const t=3*(n.indexStart/3+e),i=r[t+0],s=r[t+1],o=r[t+2],l=this._vertices[a[i-n.verticesStart]],h=this._vertices[a[s-n.verticesStart]],c=this._vertices[a[o-n.verticesStart]],u=new ov([l,h,c]);u.originalOffset=t,this._triangles.push(u)}),(()=>{this._init(t)}))}))}_init(e){Pi.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];t.normal=w.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(lv.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-w.Dot(t.normal,t._vertices[0].position)))}),(()=>{Pi.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])}),(()=>{e()}))}))}_reconstructMesh(e){const t=[];let i,s,r;for(i=0;i{n.push(e.position.x),n.push(e.position.y),n.push(e.position.z),h&&h.length&&(o.push(h[3*t]),o.push(h[3*t+1]),o.push(h[3*t+2])),c&&c.length&&(a.push(c[2*t]),a.push(c[2*t+1])),u&&u.length&&(l.push(u[4*t]),l.push(u[4*t+1]),l.push(u[4*t+2]),l.push(u[4*t+3])),++d}))}const p=this._reconstructedMesh.getTotalIndices(),f=this._reconstructedMesh.getTotalVertices(),_=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(i=0;i{const t=g[s.originalOffset+e];let i=s._vertices[e].originalOffsets.indexOf(t);i<0&&(i=0),m.push(s._vertices[e].id+i+f)}));this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(Ki.PositionKind,n),o.length>0&&this._reconstructedMesh.setVerticesData(Ki.NormalKind,o),a.length>0&&this._reconstructedMesh.setVerticesData(Ki.UVKind,a),l.length>0&&this._reconstructedMesh.setVerticesData(Ki.ColorKind,l);const v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],_.forEach((e=>{vr.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())})),vr.AddToMesh(v.materialIndex,f,d,p,3*t.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new Un(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,s,r){for(let n=0;n.999)return!0;const d=w.Cross(c,u).normalize();if(s[n]=!1,w.Dot(d,o.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,s){let r=s;for(let s=0;spv.Parse(e,t);class pv extends dv{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(_g.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[],this._points.forEach((t=>{for(let i=0;i{i+=2*e.length,s+=2*(e.length-3),r+=4*e.length/3,n+=8*e.length/3}));const o=new Float32Array(i),a=i>65535?new Uint32Array(s):new Uint16Array(s),l=new Float32Array(r),h=new Float32Array(n),c=new Float32Array(n);let u=0,d=0,p=0,f=0,_=0;e.forEach((e=>{const i=_g.GetLineLengthArray(e),s=i[i.length-1];for(let i=0,s=0;s>1]/s;if(this._options.uvs)for(let e=0;efv.Parse(e,t);class fv extends dv{constructor(e,t,i,s){if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=i.widths??[],this._ribbonWidths=[],this._pathsOptions=s??[],i.points&&this.addPoints(_g.ConvertPoints(i.points),i,!!s)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t{const r=fv._ConvertToRibbonPath(e,n.ribbonOptions,this._scene.useRightHandedSystem,i?i[t]:i);s=this._preprocess(r,s,n)}))}}this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:new Array(e).fill(t)}static _CreateRibbonVertexData(e,t){const i=e.length;if(i<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";const s=[],r=[],n=e[0];for(let t=0;t2)for(let e=0;e0&&(o[0]+=1,o[1]+=1),r.push(o[1]+(e%2!=0?i:0),o[0],o[2]),a&&r.push(o[0],o[1]+(e%2!=0?i:0),o[2])}else for(let e=0;ee.y&&e.x>e.z?i?fv._RightHandedForwardReadOnlyQuaternion:fv._LeftHandedForwardReadOnlyQuaternion:fv._LeftReadOnlyQuaternion),l=e.normalize()}h=l.multiplyByFloats(o,o,o),r.push(c.add(h)),n.push(c.subtract(h))}s||(r.push(a[a.length-1].add(h)),n.push(a[a.length-1].subtract(h)))}return[r,n]}static _GetDirectionFromPoints(e,t,i){return e.x!==t.x||i&&1!==i?.x?e.y===t.y?fv.DIRECTION_XZ:e.z===t.z?fv.DIRECTION_XY:fv.DIRECTION_XZ:fv.DIRECTION_YZ}clone(e=`${this.name}-cloned`,t){const i=this._createLineOptions(),s={},r=[];se.DeepCopy(this._pathsOptions,r,void 0,void 0,!0),se.DeepCopy(i,s,["instance"],void 0,!0);const n=new fv(e,this._scene,s,r);return t&&(n.parent=t),n.material=this.material,n}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions(),e.pathsOptions=this._pathsOptions}static Parse(e,t){const i=e.lineOptions,s=e.name,r=e.pathOptions;return new fv(s,t,i,r)}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){const t=e.length;this._vSegmentLengths=new Array(t),this._vTotalLengths=new Array(t);let i=0;for(let s=0;s=this._thinInstanceDataStorage.instancesCount)return!1;const s=this._thinInstanceDataStorage.matrixData;return t.copyToArray(s,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},Un.prototype.thinInstanceSetAttributeAt=function(e,t,i,s=!0){return e===Ki.ColorKind&&(e=Ki.ColorInstanceKind),!(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[e]||t>=this._thinInstanceDataStorage.instancesCount||(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),s&&this.thinInstanceBufferUpdated(e),0))},Object.defineProperty(Un.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){const t=this._thinInstanceDataStorage.matrixData??this.source?._thinInstanceDataStorage.matrixData;e<=(t?t.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),Un.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!0){const s=new $i(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(s.createVertexBuffer(e+t,4*t,4));return s},Un.prototype.thinInstanceSetBuffer=function(e,t,i=0,s=!0){i=i||16,"matrix"===e?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*i,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/i,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,s),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,s))):(e===Ki.ColorKind&&(e=Ki.ColorInstanceKind),null===t?this._userThinInstanceBuffersStorage?.data[e]&&(this.removeVerticesData(e),delete this._userThinInstanceBuffersStorage.data[e],delete this._userThinInstanceBuffersStorage.strides[e],delete this._userThinInstanceBuffersStorage.sizes[e],delete this._userThinInstanceBuffersStorage.vertexBuffers[e]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[e]=t,this._userThinInstanceBuffersStorage.strides[e]=i,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new Ki(this.getEngine(),t,e,!s,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},Un.prototype.thinInstanceBufferUpdated=function(e){"matrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.matrixBuffer?.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):"previousMatrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.previousMatrixBuffer?.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(e===Ki.ColorKind&&(e=Ki.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[e].isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0)))},Un.prototype.thinInstancePartialBufferUpdate=function(e,t,i){"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===Ki.ColorKind&&(e=Ki.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},Un.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;te.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}_resetCounters(){this._callCount=0,this._executionCount=0}get callCount(){return this._callCount}get executionCount(){return this._executionCount}getConnectedValue(e){return this.isConnected?this._connectedPoint?._storedFunction?(this._connectedPoint._callCount++,this._connectedPoint._executionCount++,this._connectedPoint._storedFunction(e)):(this._connectedPoint._callCount++,this._connectedPoint._executionCount=1,this._connectedPoint._storedValue):(this._callCount++,this._executionCount=1,this.value)}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=new Array,this._type=Yg.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new g,this.onDisconnectionObservable=new g,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._callCount=0,this._executionCount=0,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===jg.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==Yg.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?jg.Compatible:jg.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return jg.TypeIncompatible;let s=i,r=t;return this.direction===$g.Input&&(s=t,r=i),s.isAnAncestorOf(r)?jg.HierarchyIssue:jg.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this.onDisconnectionObservable.notifyObservers(e),e.onDisconnectionObservable.notifyObservers(this)),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear(),this.onDisconnectionObservable.clear()}}class mv{get buildExecutionTime(){return this._buildExecutionTime}get inputs(){return this._inputs}get outputs(){return this._outputs}get name(){return this._name}set name(e){this._name=e}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get isDebug(){return this._isDebug}get isUnique(){return this._isUnique}getClassName(){return"NodeGeometryBlock"}_inputRename(e){return e}_outputRename(e){return e}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){if(i.ownerBlock===e)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints)if(i.ownerBlock.isAnAncestorOfType(e))return!0;return!1}getDescendantOfPredicate(e){if(e(this))return this;for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){const t=i.ownerBlock.getDescendantOfPredicate(e);if(t)return t}return null}constructor(e){this._name="",this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._isDebug=!1,this._isUnique=!1,this._buildExecutionTime=0,this.onBuildObservable=new g,this._inputs=new Array,this._outputs=new Array,this._codeVariableName="",this.visibleOnFrame=!1,this._name=e,this.uniqueId=Ds.UniqueId}registerInput(e,t,i=!1,s,r,n){const o=new _v(e,this,$g.Input);return o.type=t,o.isOptional=i,o.defaultValue=s,o.value=s,o.valueMin=r,o.valueMax=n,this._inputs.push(o),this}registerOutput(e,t,i){return(i=i??new _v(e,this,$g.Output)).type=t,this._outputs.push(i),this}_buildBlock(e){}_customBuildStep(e){}build(e){if(this._buildId===e.buildId)return!0;if(this._outputs.length>0){if(!this._outputs.some((e=>e.hasEndpoints))&&!this.isDebug)return!1;this.outputs.forEach((e=>e._resetCounters()))}this._buildId=e.buildId;for(const t of this._inputs){if(!t.connectedPoint){t.isOptional||e.notConnectedNonOptionalInputs.push(t);continue}const i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}this._customBuildStep(e),e.verbose&&J.Log(`Building ${this.name} [${this.getClassName()}]`);const t=je.Now;this._buildBlock(e),this._buildExecutionTime=je.Now-t;for(const t of this._outputs)for(const i of t.endpoints){const t=i.ownerBlock;t&&t.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.visibleOnFrame=this.visibleOnFrame,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach((e=>{const t=this.inputs.find((t=>t.name===e.name));if(t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value))if("number"===e.valueType)t.value=e.value;else{const i=d(e.valueType);i&&(t.value=i.FromArray(e.value))}})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}_dumpPropertiesCode(){return`${this._codeVariableName}.visibleOnFrame = ${this.visibleOnFrame};\n`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const s=i.connectedPoint,r=s.ownerBlock;t+=r._dumpCodeForOutputConnections(e),t+=`${r._codeVariableName}.${r._outputRename(s.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\n`}return t}_dumpCode(e,t){t.push(this);const i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=i+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let s=`\n// ${this.getClassName()}\n`;this.comments&&(s+=`// ${this.comments}\n`);const r=this.getClassName();if("GeometryInputBlock"===r){const e=this.type;s+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${e});\n`}else s+=`var ${this._codeVariableName} = new BABYLON.${r}("${this.name}");\n`;s+=this._dumpPropertiesCode();for(const i of this.inputs){if(!i.isConnected)continue;const r=i.connectedPoint.ownerBlock;-1===t.indexOf(r)&&(s+=r._dumpCode(e,t))}for(const i of this.outputs)if(i.hasEndpoints)for(const r of i.endpoints){const i=r.ownerBlock;i&&-1===t.indexOf(i)&&(s+=i._dumpCode(e,t))}return s}clone(){const e=this.serialize(),t=d(e.customType);if(t){const i=new t;return i._deserialize(e),i}return null}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose();this.onBuildObservable.clear()}}ae([pe("comment")],mv.prototype,"comments",void 0);class gv extends mv{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",Yg.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}u("BABYLON.GeometryOutputBlock",gv),function(e){e[e.None=0]="None",e[e.Positions=1]="Positions",e[e.Normals=2]="Normals",e[e.Tangents=3]="Tangents",e[e.UV=4]="UV",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6",e[e.Colors=10]="Colors",e[e.VertexID=11]="VertexID",e[e.FaceID=12]="FaceID",e[e.GeometryID=13]="GeometryID",e[e.CollectionID=14]="CollectionID",e[e.LoopID=15]="LoopID",e[e.InstanceID=16]="InstanceID"}(Kg||(Kg={}));class vv{constructor(){this._rotationMatrix=new B,this._scalingMatrix=new B,this._positionMatrix=new B,this._scalingRotationMatrix=new B,this._transformMatrix=new B,this._tempVector3=new w,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}get geometryContext(){return this._geometryContext}get executionContext(){return this._executionContext}get instancingContext(){return this._instancingContext}pushGeometryContext(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)}pushExecutionContext(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)}pushInstancingContext(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)}restoreGeometryContext(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null}restoreExecutionContext(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null}restoreInstancingContext(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null}getContextualValue(e,t=!1){if(!this.executionContext)return t||this.noContextualData.push(e),null;const i=this.executionContext.getExecutionIndex();switch(e){case Kg.Positions:return this.executionContext.getOverridePositionsContextualValue?this.executionContext.getOverridePositionsContextualValue():this.geometryContext&&this.geometryContext.positions?w.FromArray(this.geometryContext.positions,3*i):w.Zero();case Kg.Normals:return this.executionContext.getOverrideNormalsContextualValue?this.executionContext.getOverrideNormalsContextualValue():this.geometryContext&&this.geometryContext.normals?w.FromArray(this.geometryContext.normals,3*i):w.Zero();case Kg.Colors:return this.geometryContext&&this.geometryContext.colors?F.FromArray(this.geometryContext.colors,4*i):F.Zero();case Kg.Tangents:return this.geometryContext&&this.geometryContext.tangents?F.FromArray(this.geometryContext.tangents,4*i):F.Zero();case Kg.UV:return this.executionContext.getOverrideUVs1ContextualValue?this.executionContext.getOverrideUVs1ContextualValue():this.geometryContext&&this.geometryContext.uvs?N.FromArray(this.geometryContext.uvs,2*i):N.Zero();case Kg.UV2:return this.geometryContext&&this.geometryContext.uvs2?N.FromArray(this.geometryContext.uvs2,2*i):N.Zero();case Kg.UV3:return this.geometryContext&&this.geometryContext.uvs3?N.FromArray(this.geometryContext.uvs3,2*i):N.Zero();case Kg.UV4:return this.geometryContext&&this.geometryContext.uvs4?N.FromArray(this.geometryContext.uvs4,2*i):N.Zero();case Kg.UV5:return this.geometryContext&&this.geometryContext.uvs5?N.FromArray(this.geometryContext.uvs5,2*i):N.Zero();case Kg.UV6:return this.geometryContext&&this.geometryContext.uvs6?N.FromArray(this.geometryContext.uvs6,2*i):N.Zero();case Kg.VertexID:return i;case Kg.FaceID:return this.executionContext.getExecutionFaceIndex();case Kg.LoopID:return this.executionContext.getExecutionLoopIndex();case Kg.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case Kg.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case Kg.CollectionID:return this.geometryContext&&this.geometryContext.metadata&&this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){const i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case Yg.Vector2:return new N(i,i);case Yg.Vector3:return new w(i,i,i);case Yg.Vector4:return new F(i,i,i,i)}return null}adaptInput(e,t,i){if(!e.isConnected)return e.value||i;const s=e.getConnectedValue(this);if(e._connectedPoint?.type===t)return s;switch(t){case Yg.Vector2:return new N(s,s);case Yg.Vector3:return new w(s,s,s);case Yg.Vector4:return new F(s,s,s,s)}return null}emitErrors(){let e="";for(const t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional.\n`;for(const t of this.noContextualData)e+=`Contextual input ${Kg[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block).\n`;if(e)throw"Build of NodeGeometry failed:\n"+e}_instantiate(e,t,i,s,r){B.ScalingToRef(s.x,s.y,s.z,this._scalingMatrix),B.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),B.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let t=0;te.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${Kg[this._contextualSource]};\n`;const t=[];let i="";switch(this.type){case Yg.Float:case Yg.Int:i=`${this.value}`;break;case Yg.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case Yg.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case Yg.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`}return t.push(`${e}.value = ${i}`),this.type!==Yg.Float&&this.type!==Yg.Int||t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}serialize(){const e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,null===this._storedValue||this.isContextual||(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=d(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}u("BABYLON.GeometryInputBlock",xv);class Tv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",Yg.Float,!0,1),this.registerInput("width",Yg.Float,!0,0),this.registerInput("height",Yg.Float,!0,0),this.registerInput("depth",Yg.Float,!0,0),this.registerInput("subdivisions",Yg.Int,!0,1),this.registerInput("subdivisionsX",Yg.Int,!0,0),this.registerInput("subdivisionsY",Yg.Int,!0,0),this.registerInput("subdivisionsZ",Yg.Int,!0,0),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){const e=new xv("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){const e=new xv("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new xv("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){const e=new xv("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){const t={},i=e=>{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.depth=this.depth.getConnectedValue(e);const i=this.subdivisions.getConnectedValue(e),s=this.subdivisionsX.getConnectedValue(e),r=this.subdivisionsY.getConnectedValue(e),n=this.subdivisionsZ.getConnectedValue(e);return i&&(t.segments=i),s&&(t.widthSegments=s),r&&(t.heightSegments=r),n&&(t.depthSegments=n),function(e){const t=e.width||e.size||1,i=e.height||e.size||1,s=e.depth||e.size||1,r=0|(e.widthSegments||e.segments||1),n=0|(e.heightSegments||e.segments||1),o=0|(e.depthSegments||e.segments||1),a=new B,l=new B,h=new B,c=Rh({width:t,height:s,subdivisionsX:r,subdivisionsY:o});B.TranslationToRef(0,-i/2,0,l),B.RotationZToRef(Math.PI,a),a.multiplyToRef(l,h),c.transform(h);const u=Rh({width:t,height:s,subdivisionsX:r,subdivisionsY:o});B.TranslationToRef(0,i/2,0,h),u.transform(h);const d=Rh({width:i,height:s,subdivisionsX:n,subdivisionsY:o});B.TranslationToRef(-t/2,0,0,l),B.RotationZToRef(Math.PI/2,a),a.multiplyToRef(l,h),d.transform(h);const p=Rh({width:i,height:s,subdivisionsX:n,subdivisionsY:o});B.TranslationToRef(t/2,0,0,l),B.RotationZToRef(-Math.PI/2,a),a.multiplyToRef(l,h),p.transform(h);const f=Rh({width:t,height:i,subdivisionsX:r,subdivisionsY:n});B.TranslationToRef(0,0,-s/2,l),B.RotationXToRef(-Math.PI/2,a),a.multiplyToRef(l,h),f.transform(h);const _=Rh({width:t,height:i,subdivisionsX:r,subdivisionsY:n});return B.TranslationToRef(0,0,s/2,l),B.RotationXToRef(Math.PI/2,a),a.multiplyToRef(l,h),_.transform(h),c.merge([u,p,d,f,_],!0),c}(t)};if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Tv.prototype,"evaluateContext",void 0),u("BABYLON.BoxBlock",Tv);class Sv{_getGlobalNodeGeometryEditor(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=Sv._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new g,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return Ii.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise((t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),void 0===this.BJSNODEGEOMETRYEDITOR){const i=e&&e.editorURL?e.editorURL:Sv.EditorURL;Ii.LoadBabylonScript(i,(()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}else this._createNodeEditor(e?.nodeGeometryEditorConfig),t()}))}_createNodeEditor(e){const t={nodeGeometry:this,...e};this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";const s=je.Now;this._initializeBlock(this.outputBlock,i);const r=new vv;r.buildId=this._buildId,r.verbose=e,this.outputBlock.build(r),t&&(this._buildId=Sv._BuildIdGenerator++),this._buildExecutionTime=je.Now-s,r.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=r.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;const i=new Un(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),!!this._vertexData&&(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e)}_initializeBlock(e,t=!0){e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._initializeBlock(i,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();const i={};for(const t of e.blocks){const e=d(t.customType);if(e){const s=new e;s._deserialize(t),i[t.id]=s,this.attachedBlocks.push(s)}}for(const e of this.attachedBlocks)if(e.isTeleportOut){const t=e,s=t._tempEntryPointUniqueId;if(s){const e=i[s];e&&e.attachToEndpoint(t)}}for(let s=0;se.targetConnectionName))&&!t||this._restoreConnections(n,e,i))}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){const s=e.locations||e.editorData.locations;for(const e of s)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&s.concat(this.editorData.locations),e.locations?this.editorData={locations:s}:(this.editorData=e.editorData,this.editorData.locations=s);const r=[];for(const e in i)r[e]=i[e].uniqueId;this.editorData.map=r}this.comment=e.comment}_restoreConnections(e,t,i){for(const s of e.outputs)for(const r of t.blocks){const n=i[r.id];if(n)for(const o of r.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==s.name);else{const e=n.getInputByName(o.inputName);if(!e||e.isConnected)continue;s.connectTo(e,!0),this._restoreConnections(n,t,i)}}}generateCode(){let e=[];const t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let s=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}");\n`;for(const r of t)r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));return this.outputBlock&&(e=[],s+="// Connections\n",s+=this.outputBlock._dumpCodeForOutputConnections(e),s+="// Output nodes\n",s+=`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName};\n`,s+="nodeGeometry.build();\n"),s}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const s=i.connectedPoint;if(s){const i=s.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}if(e.isTeleportOut){const i=e;i.entryPoint&&this._gatherBlocks(i.entryPoint,t)}}}setToDefault(){this.clear(),this.editorData=null;const e=new Tv("Box");e.autoConfigure();const t=new gv("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){const t=this.serialize(),i=Pe.Clone((()=>new Sv(e)),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){const t=e?{}:Pe.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[];for(const e of i)t.blocks.push(e.serialize());if(!e)for(const e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}dispose(){for(const e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){const t=new Sv(e);return t.setToDefault(),t.build(),t}static Parse(e){const t=Pe.Parse((()=>new Sv(e.name)),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return"_BLANK"===e?Promise.resolve(Sv.CreateDefault("blank")):new Promise(((s,r)=>{const n=new Ne;n.addEventListener("readystatechange",(()=>{if(4==n.readyState)if(200==n.status){const o=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(o.nodeGeometry);t||(t=Pe.Parse((()=>new Sv(e)),a,null)),t.parseSerializedObject(a),t.snippetId=e;try{i||t.build(),s(t)}catch(e){r(e)}}else r("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}Sv._BuildIdGenerator=0,Sv.EditorURL=`${Ii._DefaultCdnUrl}/v${Br.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`,Sv.SnippetUrl="https://snippet.babylonjs.com",ae([pe()],Sv.prototype,"name",void 0),ae([pe("comment")],Sv.prototype,"comment",void 0);class Ev extends mv{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=T,this.registerInput("geometry",Yg.Geometry),this.registerOutput("output",Yg.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e),i=[],s={};for(let e=0;es[e])),r};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`;return e+=`${this._codeVariableName}.epsilon = ${this.epsilon};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Ev.prototype,"evaluateContext",void 0),ae([Lo("Epsilon",bo.Float,"ADVANCED",{notifiers:{rebuild:!0}})],Ev.prototype,"epsilon",void 0),u("BABYLON.GeometryOptimizeBlock",Ev);class bv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",Yg.Float,!0,1),this.registerInput("width",Yg.Float,!0,0),this.registerInput("height",Yg.Float,!0,0),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){const e=new xv("Size");return e.value=1,void e.output.connectTo(this.size)}if(!this.width.isConnected){const e=new xv("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new xv("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){const t={},i=e=>(t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),ho(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],bv.prototype,"evaluateContext",void 0),u("BABYLON.PlaneBlock",bv);class Cv extends mv{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.reverseWindingOrder=!1,this.serializedCachedData=!1,this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}cleanData(){this._mesh=null,this._cachedVertexData=null}_buildBlock(){if(!this._mesh)return void(this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null);const e=Tr.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;te.clone()}serialize(){const e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=Tr.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(e.cachedVertexData=this._cachedVertexData.serialize())),e.reverseWindingOrder=this.reverseWindingOrder,e}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=Tr.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}ae([Lo("Serialize cached data",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Cv.prototype,"serializedCachedData",void 0),u("BABYLON.MeshBlock",Cv);class yv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",Yg.Float,!0,1),this.registerInput("radiusX",Yg.Float,!0,0),this.registerInput("radiusY",Yg.Float,!0,0),this.registerInput("radiusZ",Yg.Float,!0,0),this.registerInput("subdivisions",Yg.Int,!0,4),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new xv("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.radiusX=this.radiusX.getConnectedValue(e),t.radiusY=this.radiusY.getConnectedValue(e),t.radiusZ=this.radiusZ.getConnectedValue(e),Ta(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],yv.prototype,"evaluateContext",void 0),u("BABYLON.IcoSphereBlock",yv);class Av extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",Yg.Int,!0,32),this.registerInput("diameter",Yg.Float,!0,1),this.registerInput("diameterX",Yg.Float,!0,0),this.registerInput("diameterY",Yg.Float,!0,0),this.registerInput("diameterZ",Yg.Float,!0,0),this.registerInput("arc",Yg.Float,!0,1),this.registerInput("slice",Yg.Float,!0,1),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new xv("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.segments=this.segments.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterX=this.diameterX.getConnectedValue(e),t.diameterY=this.diameterY.getConnectedValue(e),t.diameterZ=this.diameterZ.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),t.slice=this.slice.getConnectedValue(e),rc(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Av.prototype,"evaluateContext",void 0),u("BABYLON.SphereBlock",Av);class Rv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",Yg.Float,!0,1),this.registerInput("height",Yg.Float,!0,1),this.registerInput("subdivisions",Yg.Int,!0,1),this.registerInput("subdivisionsX",Yg.Int,!0,0),this.registerInput("subdivisionsY",Yg.Int,!0,0),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){const e=new xv("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){const e=new xv("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.subdivisionsX=this.subdivisionsX.getConnectedValue(e),t.subdivisionsY=this.subdivisionsY.getConnectedValue(e),Rh(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Rv.prototype,"evaluateContext",void 0),u("BABYLON.GridBlock",Rv);class Iv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",Yg.Float,!0,1),this.registerInput("thickness",Yg.Float,!0,.5),this.registerInput("tessellation",Yg.Int,!0,16),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new xv("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){const t={},i=e=>(t.thickness=this.thickness.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),Dh(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Iv.prototype,"evaluateContext",void 0),u("BABYLON.TorusBlock",Iv);class Pv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",Yg.Float,!0,25),this.registerInput("diameter",Yg.Float,!0,1),this.registerInput("diameterTop",Yg.Float,!0,-1),this.registerInput("diameterBottom",Yg.Float,!0,-1),this.registerInput("subdivisions",Yg.Int,!0,1),this.registerInput("tessellation",Yg.Int,!0,24),this.registerInput("arc",Yg.Float,!0,1),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){const e=new xv("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){const e=new xv("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterTop=this.diameterTop.getConnectedValue(e),t.diameterBottom=this.diameterBottom.getConnectedValue(e),-1===t.diameterTop&&(t.diameterTop=t.diameter),-1===t.diameterBottom&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),qh(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Pv.prototype,"evaluateContext",void 0),u("BABYLON.CylinderBlock",Pv);class Mv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",Yg.Float,!0,1),this.registerInput("radius",Yg.Float,!0,.25),this.registerInput("tessellation",Yg.Int,!0,16),this.registerInput("subdivisions",Yg.Int,!0,2),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){const e=new xv("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){const e=new xv("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.height=this.height.getConnectedValue(e),t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),oc(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Mv.prototype,"evaluateContext",void 0),u("BABYLON.CapsuleBlock",Mv);class Dv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",Yg.Float,!0,.5),this.registerInput("tessellation",Yg.Int,!0,64),this.registerInput("arc",Yg.Float,!0,1),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){const e=new xv("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){const t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),hc(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{const t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Dv.prototype,"evaluateContext",void 0),u("BABYLON.DiscBlock",Dv),u("BABYLON.NullBlock",class extends mv{constructor(e){super(e),this.registerOutput("geometry",Yg.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}});class Ov extends mv{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",Yg.Geometry),this.registerInput("positions",Yg.Vector3),this.registerOutput("output",Yg.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.normals.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.normals||(this._vertexData.normals=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.uvs.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);const t=[],i=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.colors.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.colors||(this._vertexData.colors=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=null);if(!this.tangents.isConnected)return e.restoreGeometryContext(),e.restoreExecutionContext(),void(this.output._storedValue=this._vertexData);this._vertexData.tangents||(this._vertexData.tangents=[]);const t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndexthis._updateInputOutputTypes())),this.left.onDisconnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onConnectionObservable.add((()=>this._updateInputOutputTypes())),this.right.onDisconnectionObservable.add((()=>this._updateInputOutputTypes()))]}getClassName(){return"MathBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){let e;const t=this.left,i=this.right;if(!t.isConnected||!i.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const s=t.type===Yg.Float||t.type===Yg.Int,r=i.type===Yg.Float||i.type===Yg.Int,n=s&&r;switch(this.operation){case qg.Add:e=n?e=>t.getConnectedValue(e)+i.getConnectedValue(e):s?e=>e.adapt(t,i.type).add(i.getConnectedValue(e)):e=>t.getConnectedValue(e).add(e.adapt(i,t.type));break;case qg.Subtract:e=n?e=>t.getConnectedValue(e)-i.getConnectedValue(e):s?e=>e.adapt(t,i.type).subtract(i.getConnectedValue(e)):e=>t.getConnectedValue(e).subtract(e.adapt(i,t.type));break;case qg.Multiply:e=n?e=>t.getConnectedValue(e)*i.getConnectedValue(e):s?e=>e.adapt(t,i.type).multiply(i.getConnectedValue(e)):e=>t.getConnectedValue(e).multiply(e.adapt(i,t.type));break;case qg.Divide:e=n?e=>t.getConnectedValue(e)/i.getConnectedValue(e):s?e=>e.adapt(t,i.type).divide(i.getConnectedValue(e)):e=>t.getConnectedValue(e).divide(e.adapt(i,t.type));break;case qg.Min:if(n)e=e=>Math.min(t.getConnectedValue(e),i.getConnectedValue(e));else{const[r,n]=s?[i,t]:[t,i];switch(r.type){case Yg.Vector2:e=e=>N.Minimize(r.getConnectedValue(e),e.adapt(n,r.type));break;case Yg.Vector3:e=e=>w.Minimize(r.getConnectedValue(e),e.adapt(n,r.type));break;case Yg.Vector4:e=e=>F.Minimize(r.getConnectedValue(e),e.adapt(n,r.type))}}break;case qg.Max:if(!n){const[r,n]=s?[i,t]:[t,i];switch(r.type){case Yg.Vector2:e=e=>N.Maximize(r.getConnectedValue(e),e.adapt(n,r.type));break;case Yg.Vector3:e=e=>w.Maximize(r.getConnectedValue(e),e.adapt(n,r.type));break;case Yg.Vector4:e=e=>F.Maximize(r.getConnectedValue(e),e.adapt(n,r.type))}break}e=e=>Math.max(t.getConnectedValue(e),i.getConnectedValue(e))}this.output._storedFunction=i=>t.type===Yg.Int?0|e(i):e(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${qg[this.operation]};\n`}_updateInputOutputTypes(){if(this.output._typeConnectionSource=this.left,this.left.isConnected&&this.right.isConnected?(this.left.type===Yg.Int||this.left.type===Yg.Float&&this.right.type!==Yg.Int)&&(this.output._typeConnectionSource=this.right):this.left.isConnected!==this.right.isConnected&&(this.output._typeConnectionSource=this.left.isConnected?this.left:this.right),this.left.isConnected||this.right.isConnected)for(const[e,t]of[[this.left,this.right],[this.right,this.left]])e.acceptedConnectionPointTypes=[Yg.Int,Yg.Float],t.isConnected&&(e.acceptedConnectionPointTypes.push(t.type),t.type!==Yg.Int&&t.type!==Yg.Float||e.acceptedConnectionPointTypes.push(Yg.Vector2,Yg.Vector3,Yg.Vector4))}dispose(){super.dispose(),this._connectionObservers.forEach((e=>e.remove())),this._connectionObservers.length=0}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}}ae([Lo("Operation",bo.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:qg.Add},{label:"Subtract",value:qg.Subtract},{label:"Multiply",value:qg.Multiply},{label:"Divide",value:qg.Divide},{label:"Max",value:qg.Max},{label:"Min",value:qg.Min}]})],Bv.prototype,"operation",void 0),u("BABYLON.MathBlock",Bv),u("BABYLON.MapRangeBlock",class extends mv{constructor(e){super(e),this.registerInput("value",Yg.AutoDetect),this.registerInput("fromMin",Yg.Float,!0,0),this.registerInput("fromMax",Yg.Float,!0,1),this.registerInput("toMin",Yg.Float,!0,0),this.registerInput("toMax",Yg.Float,!0,1),this.registerOutput("output",Yg.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(Yg.Vector2),this._inputs[0].excludedConnectionPointTypes.push(Yg.Vector3),this._inputs[0].excludedConnectionPointTypes.push(Yg.Vector4),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),s=this.fromMax.getConnectedValue(e),r=this.toMin.getConnectedValue(e),n=(t-i)/(s-i)*(this.toMax.getConnectedValue(e)-r)+r;return this.output.type===Yg.Int?Math.floor(n):n}}}),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(Qg||(Qg={}));class Vv extends mv{constructor(e){super(e),this.test=Qg.Equal,this.registerInput("left",Yg.Float),this.registerInput("right",Yg.Float,!0,0),this.registerInput("ifTrue",Yg.AutoDetect,!0,1),this.registerInput("ifFalse",Yg.AutoDetect,!0,0),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=Yg.Float,this._inputs[0].acceptedConnectionPointTypes.push(Yg.Int),this._inputs[1].acceptedConnectionPointTypes.push(Yg.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);let s=!1;switch(this.test){case Qg.Equal:s=G.WithinEpsilon(t,i,T);break;case Qg.NotEqual:s=t!==i;break;case Qg.LessThan:s=ti;break;case Qg.LessOrEqual:s=t<=i;break;case Qg.GreaterOrEqual:s=t>=i;break;case Qg.Xor:s=!!t&&!i||!t&&!!i;break;case Qg.Or:s=!!t||!!i;break;case Qg.And:s=!!t&&!!i}return s};this.output._storedFunction=t=>e(t)?this.ifTrue.getConnectedValue(t):this.ifFalse.getConnectedValue(t)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${Qg[this.test]};\n`}serialize(){const e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}ae([Lo("Test",bo.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:Qg.Equal},{label:"NotEqual",value:Qg.NotEqual},{label:"LessThan",value:Qg.LessThan},{label:"GreaterThan",value:Qg.GreaterThan},{label:"LessOrEqual",value:Qg.LessOrEqual},{label:"GreaterOrEqual",value:Qg.GreaterOrEqual},{label:"Xor",value:Qg.Xor},{label:"Or",value:Qg.Or},{label:"And",value:Qg.And}]})],Vv.prototype,"test",void 0),u("BABYLON.ConditionBlock",Vv),function(e){e[e.None=0]="None",e[e.LoopID=1]="LoopID",e[e.InstanceID=2]="InstanceID"}(Zg||(Zg={}));class Uv extends mv{constructor(e){super(e),this._currentLockId=-1,this.lockMode=Zg.None,this.registerInput("min",Yg.AutoDetect),this.registerInput("max",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture),this._inputs[1].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[1].excludedConnectionPointTypes.push(Yg.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){const e=new xv("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){const e=new xv("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case Yg.Int:case Yg.Float:e=e=>{const t=this.min.getConnectedValue(e)||0,i=this.max.getConnectedValue(e)||0;return t+Math.random()*(i-t)};break;case Yg.Vector2:e=e=>{const t=this.min.getConnectedValue(e)||N.Zero(),i=this.max.getConnectedValue(e)||N.Zero();return new N(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y))};break;case Yg.Vector3:e=e=>{const t=this.min.getConnectedValue(e)||w.Zero(),i=this.max.getConnectedValue(e)||w.Zero();return new w(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z))};break;case Yg.Vector4:e=e=>{const t=this.min.getConnectedValue(e)||F.Zero(),i=this.max.getConnectedValue(e)||F.Zero();return new F(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z),t.w+Math.random()*(i.w-t.w))}}this.lockMode!==Zg.None&&e?this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case Zg.InstanceID:i=t.getContextualValue(Kg.InstanceID,!0)||0;break;case Zg.LoopID:i=t.getContextualValue(Kg.LoopID,!0)||0}return this._currentLockId===i&&this.lockMode!==Zg.None||(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}:this.output._storedFunction=e}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${Zg[this.lockMode]};\n`}serialize(){const e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}ae([Lo("LockMode",bo.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:Zg.None},{label:"LoopID",value:Zg.LoopID},{label:"InstanceID",value:Zg.InstanceID}]})],Uv.prototype,"lockMode",void 0),u("BABYLON.RandomBlock",Uv),u("BABYLON.NoiseBlock",class extends mv{constructor(e){super(e),this.registerInput("offset",Yg.Vector3,!0,w.Zero()),this.registerInput("scale",Yg.Float,!0,1),this.registerInput("octaves",Yg.Float,!0,2,0,16),this.registerInput("roughness",Yg.Float,!0,.5,0,1),this.registerOutput("output",Yg.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return 0!==t?-e:e}_noiseGrad(e,t,i,s){const r=15&e,n=r<8?t:i,o=r<4?i:12===r||14==r?t:s;return this._negateIf(n,r&n)+this._negateIf(o,2&r)}_fade(e){return e*e*e*(e*(6*e-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let s,r,n;return s=r=n=3735928584,n+=i,r+=t,s+=e,n^=r,n-=this._hashBitRotate(r,14),s^=n,s-=this._hashBitRotate(n,11),r^=s,r-=this._hashBitRotate(s,25),n^=r,n-=this._hashBitRotate(r,16),s^=n,s-=this._hashBitRotate(n,4),r^=s,r-=this._hashBitRotate(s,14),n^=r,n-=this._hashBitRotate(r,24),n}_mix(e,t,i,s,r,n,o,a,l,h,c){const u=1-l,d=1-h;return(1-c)*(d*(e*u+t*l)+h*(i*u+s*l))+c*(d*(r*u+n*l)+h*(o*u+a*l))}_perlinNoise(e){const t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),s=(0|e.z)-(e.z<0?1:0),r=e.x-t,n=e.y-i,o=e.z-s,a=this._fade(r),l=this._fade(n),h=this._fade(o);return this._mix(this._noiseGrad(this._hash(t,i,s),r,n,o),this._noiseGrad(this._hash(t+1,i,s),r-1,n,o),this._noiseGrad(this._hash(t,i+1,s),r,n-1,o),this._noiseGrad(this._hash(t+1,i+1,s),r-1,n-1,o),this._noiseGrad(this._hash(t,i,s+1),r,n,o-1),this._noiseGrad(this._hash(t+1,i,s+1),r-1,n,o-1),this._noiseGrad(this._hash(t,i+1,s+1),r,n-1,o-1),this._noiseGrad(this._hash(t+1,i+1,s+1),r-1,n-1,o-1),a,l,h)}_perlinSigned(e){return.982*this._perlinNoise(e)}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,s,r){const n=new w(i.x*r+s.x,i.y*r+s.y,i.z*r+s.z);let o=1,a=1,l=0,h=0;const c=0|(e=G.Clamp(e,0,15));for(let e=0;e<=c;e++)h+=this._perlin(n.scale(o))*a,l+=a,a*=G.Clamp(t,0,1),o*=2;const u=e-Math.floor(e);if(0==u)return h/l;let d=h+this._perlin(n.scale(o))*a;return h/=l,d/=l+a,(1-u)*h+u*d}_buildBlock(){this.output._storedFunction=e=>{const t=e.getContextualValue(Kg.Positions),i=this.octaves.getConnectedValue(e),s=this.roughness.getConnectedValue(e),r=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,s,t,r,n)}}});class kv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",Yg.Geometry),this.registerInput("geometry1",Yg.Geometry,!0),this.registerInput("geometry2",Yg.Geometry,!0),this.registerInput("geometry3",Yg.Geometry,!0),this.registerInput("geometry4",Yg.Geometry,!0),this.registerOutput("output",Yg.Geometry)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{let t=this.geometry0.getConnectedValue(e);const i=[];if(!t)return null;if(t=t.clone(),this.geometry1.isConnected){const t=this.geometry1.getConnectedValue(e);t&&i.push(t)}if(this.geometry2.isConnected){const t=this.geometry2.getConnectedValue(e);t&&i.push(t)}if(this.geometry3.isConnected){const t=this.geometry3.getConnectedValue(e);t&&i.push(t)}if(this.geometry4.isConnected){const t=this.geometry4.getConnectedValue(e);t&&i.push(t)}return i.length&&t&&(t=t.merge(i,!0,!1,!0,!0)),t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],kv.prototype,"evaluateContext",void 0),u("BABYLON.MergeGeometryBlock",kv);class Gv extends mv{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",Yg.Geometry,!0),this.registerInput("geometry1",Yg.Geometry,!0),this.registerInput("geometry2",Yg.Geometry,!0),this.registerInput("geometry3",Yg.Geometry,!0),this.registerInput("geometry4",Yg.Geometry,!0),this.registerInput("geometry5",Yg.Geometry,!0),this.registerInput("geometry6",Yg.Geometry,!0),this.registerInput("geometry7",Yg.Geometry,!0),this.registerInput("geometry8",Yg.Geometry,!0),this.registerInput("geometry9",Yg.Geometry,!0),this.registerOutput("output",Yg.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,s){if(e.isConnected){const r=e.getConnectedValue(t);if(!r)return;r.metadata=r.metadata||{},r.metadata.collectionId=i,s.push(r)}}_buildBlock(e){const t=e=>{const t=[];return this._storeGeometry(this.geometry0,e,0,t),this._storeGeometry(this.geometry1,e,1,t),this._storeGeometry(this.geometry2,e,2,t),this._storeGeometry(this.geometry3,e,3,t),this._storeGeometry(this.geometry4,e,4,t),this._storeGeometry(this.geometry5,e,5,t),this._storeGeometry(this.geometry6,e,6,t),this._storeGeometry(this.geometry7,e,7,t),this._storeGeometry(this.geometry8,e,8,t),this._storeGeometry(this.geometry9,e,9,t),t.length?t[Math.round(Math.random()*(t.length-1))]:null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Gv.prototype,"evaluateContext",void 0),u("BABYLON.GeometryCollectionBlock",Gv),u("BABYLON.GeometryElbowBlock",class extends mv{constructor(e){super(e),this.registerInput("input",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];t._storedFunction=e=>i.getConnectedValue(e)}}),u("BABYLON.ComputeNormalsBlock",class extends mv{constructor(e){super(e),this.registerInput("geometry",Yg.Geometry),this.registerOutput("output",Yg.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;const t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),Tr.ComputeNormals(t.positions,t.indices,t.normals),t}}}),u("BABYLON.VectorConverterBlock",class extends mv{constructor(e){super(e),this.registerInput("xyzw ",Yg.Vector4,!0),this.registerInput("xyz ",Yg.Vector3,!0),this.registerInput("xy ",Yg.Vector2,!0),this.registerInput("zw ",Yg.Vector2,!0),this.registerInput("x ",Yg.Float,!0),this.registerInput("y ",Yg.Float,!0),this.registerInput("z ",Yg.Float,!0),this.registerInput("w ",Yg.Float,!0),this.registerOutput("xyzw",Yg.Vector4),this.registerOutput("xyz",Yg.Vector3),this.registerOutput("xy",Yg.Vector2),this.registerOutput("zw",Yg.Vector2),this.registerOutput("x",Yg.Float),this.registerOutput("y",Yg.Float),this.registerOutput("z",Yg.Float),this.registerOutput("w",Yg.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);const t=this.xIn,i=this.yIn,s=this.zIn,r=this.wIn,n=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,c=this.xyzOut,u=this.xyOut,d=this.zwOut,p=this.xOut,f=this.yOut,_=this.zOut,m=this.wOut,g=e=>{if(l.isConnected)return l.getConnectedValue(e);let h=0,c=0,u=0,d=0;if(t.isConnected&&(h=t.getConnectedValue(e)),i.isConnected&&(c=i.getConnectedValue(e)),s.isConnected&&(u=s.getConnectedValue(e)),r.isConnected&&(d=r.getConnectedValue(e)),n.isConnected){const t=n.getConnectedValue(e);t&&(h=t.x,c=t.y)}if(o.isConnected){const t=o.getConnectedValue(e);t&&(u=t.x,d=t.y)}if(a.isConnected){const t=a.getConnectedValue(e);t&&(h=t.x,c=t.y,u=t.z)}return new F(h,c,u,d)};h._storedFunction=e=>g(e),c._storedFunction=e=>{const t=g(e);return new w(t.x,t.y,t.z)},u._storedFunction=e=>{const t=g(e);return new N(t.x,t.y)},d._storedFunction=e=>{const t=g(e);return new N(t.z,t.w)},p._storedFunction=e=>g(e).x,f._storedFunction=e=>g(e).y,_._storedFunction=e=>g(e).z,m._storedFunction=e=>g(e).w}}),u("BABYLON.NormalizeVectorBlock",class extends mv{constructor(e){super(e),this.registerInput("input",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(Yg.Float),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.output._storedFunction=null,this.input.isConnected?this.output._storedFunction=e=>this.input.getConnectedValue(e).normalize():this.output._storedValue=null}});class zv extends mv{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",Yg.Geometry),this.registerInput("id",Yg.Int,!0,0),this.registerOutput("output",Yg.Geometry),this.id.acceptedConnectionPointTypes.push(Yg.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.geometry.getConnectedValue(e);if(!t||!t.indices||!t.positions)return t;const i=new xr;return i.materialIndex=0|this.id.getConnectedValue(e),i.indexStart=0,i.indexCount=t.indices.length,i.verticesStart=0,i.verticesCount=t.positions.length/3,t.materialInfos=[i],t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],zv.prototype,"evaluateContext",void 0),u("BABYLON.SetMaterialIDBlock",zv),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Round=4]="Round",e[e.Floor=5]="Floor",e[e.Ceiling=6]="Ceiling",e[e.Sqrt=7]="Sqrt",e[e.Log=8]="Log",e[e.Tan=9]="Tan",e[e.ArcTan=10]="ArcTan",e[e.ArcCos=11]="ArcCos",e[e.ArcSin=12]="ArcSin",e[e.Sign=13]="Sign",e[e.Negate=14]="Negate",e[e.OneMinus=15]="OneMinus",e[e.Reciprocal=16]="Reciprocal",e[e.ToDegrees=17]="ToDegrees",e[e.ToRadians=18]="ToRadians",e[e.Fract=19]="Fract",e[e.Exp2=20]="Exp2"}(Jg||(Jg={}));class Wv extends mv{constructor(e){super(e),this.operation=Jg.Cos,this.registerInput("input",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case Jg.Cos:t=e=>Math.cos(e);break;case Jg.Sin:t=e=>Math.sin(e);break;case Jg.Abs:t=e=>Math.abs(e);break;case Jg.Exp:t=e=>Math.exp(e);break;case Jg.Exp2:t=e=>Math.pow(2,e);break;case Jg.Round:t=e=>Math.round(e);break;case Jg.Floor:t=e=>Math.floor(e);break;case Jg.Ceiling:t=e=>Math.ceil(e);break;case Jg.Sqrt:t=e=>Math.sqrt(e);break;case Jg.Log:t=e=>Math.log(e);break;case Jg.Tan:t=e=>Math.tan(e);break;case Jg.ArcTan:t=e=>Math.atan(e);break;case Jg.ArcCos:t=e=>Math.acos(e);break;case Jg.ArcSin:t=e=>Math.asin(e);break;case Jg.Sign:t=e=>Math.sign(e);break;case Jg.Negate:t=e=>-e;break;case Jg.OneMinus:t=e=>1-e;break;case Jg.Reciprocal:t=e=>1/e;break;case Jg.ToRadians:t=e=>e*Math.PI/180;break;case Jg.ToDegrees:t=e=>180*e/Math.PI;break;case Jg.Fract:t=e=>e>=0?e-Math.floor(e):e-Math.ceil(e)}if(!t)return this.output._storedFunction=null,void(this.output._storedValue=null);switch(this.input.type){case Yg.Int:case Yg.Float:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return t(i)};break;case Yg.Vector2:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new N(t(i.x),t(i.y))};break;case Yg.Vector3:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new w(t(i.x),t(i.y),t(i.z))};break;case Yg.Vector4:this.output._storedFunction=e=>{const i=this.input.getConnectedValue(e);return new F(t(i.x),t(i.y),t(i.z),t(i.w))}}return this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${Jg[this.operation]};\n`}}ae([Lo("Operation",bo.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:Jg.Cos},{label:"Sin",value:Jg.Sin},{label:"Abs",value:Jg.Abs},{label:"Exp",value:Jg.Exp},{label:"Exp2",value:Jg.Exp2},{label:"Round",value:Jg.Round},{label:"Floor",value:Jg.Floor},{label:"Ceiling",value:Jg.Ceiling},{label:"Sqrt",value:Jg.Sqrt},{label:"Log",value:Jg.Log},{label:"Tan",value:Jg.Tan},{label:"ArcTan",value:Jg.ArcTan},{label:"ArcCos",value:Jg.ArcCos},{label:"ArcSin",value:Jg.ArcSin},{label:"Sign",value:Jg.Sign},{label:"Negate",value:Jg.Negate},{label:"OneMinus",value:Jg.OneMinus},{label:"Reciprocal",value:Jg.Reciprocal},{label:"ToDegrees",value:Jg.ToDegrees},{label:"ToRadians",value:Jg.ToRadians},{label:"Fract",value:Jg.Fract}]})],Wv.prototype,"operation",void 0),u("BABYLON.GeometryTrigonometryBlock",Wv);class Hv extends mv{constructor(e){super(e),this._rotationMatrix=new B,this._scalingMatrix=new B,this._translationMatrix=new B,this._scalingRotationMatrix=new B,this._transformMatrix=new B,this.evaluateContext=!0,this.registerInput("value",Yg.AutoDetect),this.registerInput("matrix",Yg.Matrix,!0),this.registerInput("translation",Yg.Vector3,!0,w.Zero()),this.registerInput("rotation",Yg.Vector3,!0,w.Zero()),this.registerInput("scaling",Yg.Vector3,!0,w.One()),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Yg.Float),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const t=e=>{const t=this.value.getConnectedValue(e);if(!t)return null;let i;if(this.matrix.isConnected)i=this.matrix.getConnectedValue(e);else{const t=this.scaling.getConnectedValue(e),s=this.rotation.getConnectedValue(e),r=this.translation.getConnectedValue(e);B.ScalingToRef(t.x,t.y,t.z,this._scalingMatrix),B.RotationYawPitchRollToRef(s.y,s.x,s.z,this._rotationMatrix),B.TranslationToRef(r.x,r.y,r.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),i=this._transformMatrix}switch(this.value.type){case Yg.Geometry:{const e=t.clone();return e.transform(i),e}case Yg.Vector2:return N.Transform(t,i);case Yg.Vector3:return w.TransformCoordinates(t,i);case Yg.Vector4:return F.TransformCoordinates(t,i)}return null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Hv.prototype,"evaluateContext",void 0),u("BABYLON.GeometryTransformBlock",Hv),u("BABYLON.RotationXBlock",class extends mv{constructor(e){super(e),this.registerInput("angle",Yg.Float,!1,0),this.registerOutput("matrix",Yg.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new xv("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>B.RotationX(this.angle.getConnectedValue(e))}}),u("BABYLON.RotationYBlock",class extends mv{constructor(e){super(e),this.registerInput("angle",Yg.Float,!1,0),this.registerOutput("matrix",Yg.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new xv("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>B.RotationY(this.angle.getConnectedValue(e))}}),u("BABYLON.RotationZBlock",class extends mv{constructor(e){super(e),this.registerInput("angle",Yg.Float,!1,0),this.registerOutput("matrix",Yg.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){const e=new xv("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>B.RotationZ(this.angle.getConnectedValue(e))}}),u("BABYLON.ScalingBlock",class extends mv{constructor(e){super(e),this.registerInput("scale",Yg.Vector3,!1,w.One()),this.registerOutput("matrix",Yg.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){const e=new xv("Scale");e.value=new w(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.scale.getConnectedValue(e);return B.Scaling(t.x,t.y,t.z)}}}),u("BABYLON.AlignBlock",class extends mv{constructor(e){super(e),this.registerInput("source",Yg.Vector3,!0,w.Up()),this.registerInput("target",Yg.Vector3,!0,w.Left()),this.registerOutput("matrix",Yg.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.source.getConnectedValue(e).clone(),i=this.target.getConnectedValue(e).clone(),s=new B;return t.normalize(),i.normalize(),B.RotationAlignToRef(t,i,s,!0),s}}}),u("BABYLON.TranslationBlock",class extends mv{constructor(e){super(e),this.registerInput("translation",Yg.Vector3,!1,w.Zero()),this.registerOutput("matrix",Yg.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){const e=new xv("Translation");e.value=new w(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{const t=this.translation.getConnectedValue(e);return B.Translation(t.x,t.y,t.z)}}});class Xv extends mv{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",Yg.Geometry),this.registerInput("instance",Yg.Geometry,!0),this.registerInput("density",Yg.Float,!0,1,0,1),this.registerInput("matrix",Yg.Matrix,!0),this.registerInput("rotation",Yg.Vector3,!0,w.Zero()),this.registerInput("scaling",Yg.Vector3,!0,w.One()),this.scaling.acceptedConnectionPointTypes.push(Yg.Float),this.registerOutput("output",Yg.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get density(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected)return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=this._vertexData.positions.length/3;const i=[],s=new w,r=[];let n=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexr)continue;s.fromArray(n,3*this._currentIndex);const o=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(o,s,t,i)}else{const t=e.adaptInput(this.scaling,Yg.Vector3,w.OneReadOnly),r=this.rotation.getConnectedValue(e)||w.ZeroReadOnly;e._instantiate(o,s,r,t,i)}this._currentLoopIndex++}if(e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),!i.length)return null;if(1===i.length)this._vertexData=i[0];else{const e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}return this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"};\n`;return e+=`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`,e}serialize(){const e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Xv.prototype,"evaluateContext",void 0),ae([Lo("Remove duplicated positions",bo.Boolean,"ADVANCED",{notifiers:{update:!0}})],Xv.prototype,"removeDuplicatedPositions",void 0),u("BABYLON.InstantiateOnVerticesBlock",Xv);class Yv extends mv{constructor(e){super(e),this._currentPosition=new w,this._currentUV=new N,this._vertex0=new w,this._vertex1=new w,this._vertex2=new w,this._tempVector0=new w,this._tempVector1=new w,this._uv0=new N,this._uv1=new N,this._uv2=new N,this.evaluateContext=!0,this.registerInput("geometry",Yg.Geometry),this.registerInput("instance",Yg.Geometry,!0),this.registerInput("count",Yg.Int,!0,256),this.registerInput("matrix",Yg.Matrix,!0),this.registerInput("rotation",Yg.Vector3,!0,w.Zero()),this.registerInput("scaling",Yg.Vector3,!0,w.One()),this.scaling.acceptedConnectionPointTypes.push(Yg.Float),this.registerOutput("output",Yg.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),w.Cross(this._tempVector1,this._tempVector0)}getOverrideUVs1ContextualValue(){return this._currentUV}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),s=this._vertexData.indices.length/3,r=i/s;let n=0;const o=[];let a=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=i);l++){let i=Math.random(),s=Math.random();if(i>s){const e=i;i=s,s=e}const l=i,h=s-i,c=1-l-h;if(this._currentPosition.set(l*this._vertex0.x+h*this._vertex1.x+c*this._vertex2.x,l*this._vertex0.y+h*this._vertex1.y+c*this._vertex2.y,l*this._vertex0.z+h*this._vertex1.z+c*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(l*this._uv0.x+h*this._uv1.x+c*this._uv2.x,l*this._uv0.y+h*this._uv1.y+c*this._uv2.y),t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length){n-=r;continue}const u=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(u,this._currentPosition,t,o)}else{const t=e.adaptInput(this.scaling,Yg.Vector3,w.OneReadOnly),i=this.rotation.getConnectedValue(e)||w.ZeroReadOnly;e._instantiate(u,this._currentPosition,i,t,o)}a++,this._currentLoopIndex++}}if(o.length)if(1===o.length)this._vertexData=o[0];else{const e=o.splice(0,1)[0];this._vertexData=e.merge(o,!0,!1,!0,!0)}return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Yv.prototype,"evaluateContext",void 0),u("BABYLON.InstantiateOnFacesBlock",Yv);class jv extends mv{constructor(e){super(e),this._currentPosition=new w,this._vertex0=new w,this._vertex1=new w,this._vertex2=new w,this.evaluateContext=!0,this.registerInput("geometry",Yg.Geometry),this.registerInput("instance",Yg.Geometry,!0),this.registerInput("count",Yg.Int,!0,256),this.registerInput("matrix",Yg.Matrix,!0),this.registerInput("rotation",Yg.Vector3,!0,w.Zero()),this.registerInput("scaling",Yg.Vector3,!0,w.One()),this.scaling.acceptedConnectionPointTypes.push(Yg.Float),this.registerOutput("output",Yg.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!(this._vertexData&&this._vertexData.positions&&this._vertexData.indices&&this.instance.isConnected))return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),void(this.output._storedValue=null);let t=null;const i=this.count.getConnectedValue(e),s=[],r=mr(this._vertexData.positions,0,this._vertexData.positions.length/3),n=r.minimum,o=r.maximum,a=new w(1,0,0),l=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let r=0;r0&&h++}if(h%2==0){r--;continue}if(t=this.instance.getConnectedValue(e),!t||!t.positions||0===t.positions.length)continue;const c=t.clone();if(this.matrix.isConnected){const t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(c,this._currentPosition,t,s)}else{const t=e.adaptInput(this.scaling,Yg.Vector3,w.OneReadOnly),i=this.rotation.getConnectedValue(e)||w.ZeroReadOnly;e._instantiate(c,this._currentPosition,i,t,s)}this._currentLoopIndex++}if(s.length)if(1===s.length)this._vertexData=s[0];else{const e=s.splice(0,1)[0];this._vertexData=e.merge(s,!0,!1,!0,!0)}return e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],jv.prototype,"evaluateContext",void 0),u("BABYLON.InstantiateOnVolumeBlock",jv);class $v extends mv{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",Yg.Geometry,!0),this.registerInput("count",Yg.Int,!0,1),this.registerOutput("output",Yg.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBaseBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get output(){return this._outputs[0]}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],$v.prototype,"evaluateContext",void 0),u("BABYLON.InstantiateBlock",class extends $v{constructor(e){super(e),this.registerInput("matrix",Yg.Matrix,!0),this.registerInput("position",Yg.Vector3,!0,w.Zero()),this.registerInput("rotation",Yg.Vector3,!0,w.Zero()),this.registerInput("scaling",Yg.Vector3,!0,w.One()),this.scaling.acceptedConnectionPointTypes.push(Yg.Float)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get matrix(){return this._inputs[2]}get position(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}_buildBlock(e){const t=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[];for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],s=B.Identity(),r=w.Zero(),n=w.Zero(),o=w.Zero();for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);const t=this.count.getConnectedValue(e),i=[],s=B.Identity(),r=B.Identity(),n=B.Identity(),o=w.Zero(),a=w.Zero(),l=w.Zero();for(this._currentIndex=0;this._currentIndexthis.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?Math.floor(this.floatIn.getConnectedValue(e)):this.intIn.isConnected?Math.floor(this.intIn.getConnectedValue(e)):0}}),u("BABYLON.DebugBlock",class extends mv{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);this.log=[];const t=e=>{const t=this.input.getConnectedValue(e);if(null==t)return this.log.push(["null",""]),t;switch(this.input.type){case Yg.Vector2:this.log.push([(i=t,4,`{X: ${i.x.toFixed(4)} Y: ${i.y.toFixed(4)}}`),t.toString()]);break;case Yg.Vector3:this.log.push([Ag(t,4),t.toString()]);break;case Yg.Vector4:this.log.push([Rg(t,4),t.toString()]);break;default:this.log.push([t.toString(),t.toString()])}var i;return t};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}),u("BABYLON.GeometryInfoBlock",class extends mv{constructor(e){super(e),this.registerInput("geometry",Yg.Geometry),this.registerOutput("output",Yg.Geometry),this.registerOutput("id",Yg.Int),this.registerOutput("collectionId",Yg.Int),this.registerOutput("verticesCount",Yg.Int),this.registerOutput("facesCount",Yg.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected)return this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,void(this.output._storedFunction=null);this.output._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData),this.id._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}}),function(e){e[e.Spherical=0]="Spherical",e[e.Cylindrical=1]="Cylindrical",e[e.Cubic=2]="Cubic"}(ev||(ev={}));class Kv extends mv{constructor(e){super(e),this.mapping=ev.Spherical,this.registerInput("position",Yg.Vector3),this.registerInput("normal",Yg.Vector3),this.registerInput("center",Yg.Vector3,!0,w.Zero()),this.registerOutput("uv",Yg.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get center(){return this._inputs[2]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected)return this.uv._storedFunction=null,void(this.uv._storedValue=null);const e=w.Zero(),t=t=>{const i=this.position.getConnectedValue(t)||w.Zero(),s=this.normal.getConnectedValue(t)||w.Zero(),r=this.center.getConnectedValue(t),n=N.Zero();switch(this.mapping){case ev.Spherical:{i.subtractToRef(r,e);const t=e.length();t>0&&(n.x=Math.acos(e.y/t)/Math.PI,0===e.x&&0===e.z||(n.y=Math.atan2(e.x,e.z)/(2*Math.PI)));break}case ev.Cylindrical:{i.subtractToRef(r,e);const t=e.length();t>0&&(n.x=Math.atan2(e.x/t,e.z/t)/(2*Math.PI),n.y=(e.y+1)/2);break}case ev.Cubic:{const e=Math.abs(s.x),t=Math.abs(s.y),o=Math.abs(s.z),a=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z));let l=0,h=0;e>=t&&e>=o?(l=i.y/a-r.y,h=i.z/a-r.z):t>=e&&t>=o?(l=i.x/a-r.x,h=i.z/a-r.z):(l=i.x/a-r.x,h=i.y/a-r.y),n.x=(l+1)/2,n.y=(h+1)/2}}return n};this.uv._storedFunction=e=>t(e)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${ev[this.mapping]};\n`}serialize(){const e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}ae([Lo("Mapping",bo.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:ev.Spherical},{label:"Cylindrical",value:ev.Cylindrical},{label:"Cubic",value:ev.Cubic}]})],Kv.prototype,"mapping",void 0),u("BABYLON.MappingBlock",Kv),u("BABYLON.MatrixComposeBlock",class extends mv{constructor(e){super(e),this.registerInput("matrix0",Yg.Matrix),this.registerInput("matrix1",Yg.Matrix),this.registerOutput("output",Yg.Matrix)}getClassName(){return"MatrixComposeBlock"}get matrix0(){return this._inputs[0]}get matrix1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.matrix0.isConnected||!this.matrix1.isConnected)return null;const t=this.matrix0.getConnectedValue(e),i=this.matrix1.getConnectedValue(e);return t&&i?t.multiply(i):null}}}),u("BABYLON.TeleportInBlock",class extends mv{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",Yg.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(const s of this.endpoints)-1===t.indexOf(s)&&(i+=s._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(const t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(const t of this.endpoints){if(t===e)return!0;if(t.isAnAncestorOf(e))return!0}return!1}getDescendantOfPredicate(e){if(e(this))return this;for(const t of this.endpoints){const i=t.getDescendantOfPredicate(e);if(i)return i}return null}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){const t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(const e of this._endpoints)e.output._storedFunction=e=>this.input.getConnectedValue(e)}}),u("BABYLON.TeleportOutBlock",class extends mv{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",Yg.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){const e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName});\n`),e}serialize(){const e=super.serialize();return e.entryPoint=this.entryPoint?.uniqueId??"",e}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}});class qv extends mv{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.serializedCachedData=!1,this.registerOutput("texture",Yg.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise(((t,i)=>{const s=new Image,r=document.createElement("canvas"),n=r.getContext("2d");s.onload=()=>{r.width=s.width,r.height=s.height,n.drawImage(s,0,0);const e=n.getImageData(0,0,s.width,s.height).data,i=new Float32Array(e.length);for(let t=0;t{this._data=null,i()},s.src=e}))}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise(((t,i)=>{if(!e.isReady())return void e.onLoadObservable.addOnce((()=>this.extractFromTextureAsync(e).then(t).catch(i)));const s=e.getSize();nu(e,s.width,s.height).then((async e=>{const i=new Float32Array(e.length);for(let t=0;t=0?e%1:1-Math.abs(e)%1}_buildBlock(){const e=e=>{const t=this.texture.getConnectedValue(e);if(!t||!t.data)return null;const i=this.coordinates.getConnectedValue(e);if(!i)return null;const s=this.clampCoordinates?Math.max(0,Math.min(i.x,1)):this._repeatClamp(i.x),r=this.clampCoordinates?Math.max(0,Math.min(i.y,1)):this._repeatClamp(i.y),n=Math.floor(s*(t.width-1)),o=Math.floor(r*(t.height-1)),a=n+t.width*o;return F.FromArray(t.data,4*a)};this.rgba._storedFunction=t=>e(t),this.rgb._storedFunction=t=>{const i=e(t);return i?i.toVector3():null},this.r._storedFunction=t=>{const i=e(t);return i?i.x:null},this.g._storedFunction=t=>{const i=e(t);return i?i.y:null},this.b._storedFunction=t=>{const i=e(t);return i?i.z:null},this.a._storedFunction=t=>{const i=e(t);return i?i.w:null}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates};\n`}serialize(){const e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}}ae([Lo("Clamp Coordinates",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Qv.prototype,"clampCoordinates",void 0),u("BABYLON.GeometryTextureFetchBlock",Qv),u("BABYLON.BoundingBlock",class extends mv{constructor(e){super(e),this.registerInput("geometry",Yg.Geometry),this.registerOutput("min",Yg.Vector3),this.registerOutput("max",Yg.Vector3)}getClassName(){return"BoundingBlock"}get geometry(){return this._inputs[0]}get min(){return this._outputs[0]}get max(){return this._outputs[1]}_buildBlock(){this.min._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?mr(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{const t=this.geometry.getConnectedValue(e);return t?mr(t.positions,0,t.positions.length/3).maximum:null}}}),function(e){e[e.Intersect=0]="Intersect",e[e.Subtract=1]="Subtract",e[e.Union=2]="Union"}(tv||(tv={}));class Zv extends mv{constructor(e){super(e),this.evaluateContext=!1,this.operation=tv.Intersect,this.registerInput("geometry0",Yg.Geometry),this.registerInput("geometry1",Yg.Geometry),this.registerOutput("output",Yg.Geometry)}getClassName(){return"BooleanGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){const t=e=>{const t=this.geometry0.getConnectedValue(e),i=this.geometry1.getConnectedValue(e);if(!t||!i)return null;const s=t.positions.length/3;!t.normals&&i.normals&&(t.normals=new Array(t.positions.length)),!i.normals&&t.normals&&(i.normals=new Array(i.positions.length)),!t.uvs&&i.uvs&&(t.uvs=new Array(2*s)),!i.uvs&&t.uvs&&(i.uvs=new Array(2*s)),!t.colors&&i.colors&&(t.colors=new Array(4*s)),!i.colors&&t.colors&&(i.colors=new Array(4*s));const r=Bg.FromVertexData(t),n=Bg.FromVertexData(i);let o;switch(this.operation){case tv.Intersect:o=r.intersect(n);break;case tv.Subtract:o=r.subtract(n);break;case tv.Union:o=r.union(n)}return o.toVertexData()};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"};\n`;return e+=`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${tv[this.operation]};\n`,e}serialize(){const e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation)}}ae([Lo("Evaluate context",bo.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],Zv.prototype,"evaluateContext",void 0),ae([Lo("Operation",bo.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:tv.Intersect},{label:"Subtract",value:tv.Subtract},{label:"Union",value:tv.Union}]})],Zv.prototype,"operation",void 0),u("BABYLON.BooleanGeometryBlock",Zv),u("BABYLON.GeometryArcTan2Block",class extends mv{constructor(e){super(e),this.registerInput("x",Yg.AutoDetect),this.registerInput("y",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.x.isConnected||!this.y.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.atan2(e,t);this.output._storedFunction=t=>{const i=this.x.getConnectedValue(t),s=this.y.getConnectedValue(t);switch(this.x.type){case Yg.Int:case Yg.Float:return e(i,s);case Yg.Vector2:return new N(e(i.x,s.x),e(i.y,s.y));case Yg.Vector3:return new w(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case Yg.Vector4:return new F(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0}}}),u("BABYLON.GeometryLerpBlock",class extends mv{constructor(e){super(e),this.registerInput("left",Yg.AutoDetect),this.registerInput("right",Yg.AutoDetect),this.registerInput("gradient",Yg.Float),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case Yg.Int:case Yg.Float:return e(r,i,s);case Yg.Vector2:return new N(e(r,i.x,s.x),e(r,i.y,s.y));case Yg.Vector3:return new w(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));case Yg.Vector4:return new F(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w))}return 0},this}}),u("BABYLON.GeometryNLerpBlock",class extends mv{constructor(e){super(e),this.registerInput("left",Yg.AutoDetect),this.registerInput("right",Yg.AutoDetect),this.registerInput("gradient",Yg.Float),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryNLerpBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get gradient(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected||!this.gradient.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>(1-e)*t+e*i;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t),r=this.gradient.getConnectedValue(t);switch(this.left.type){case Yg.Int:case Yg.Float:return e(r,i,s);case Yg.Vector2:{const t=new N(e(r,i.x,s.x),e(r,i.y,s.y));return t.normalize(),t}case Yg.Vector3:{const t=new w(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z));return t.normalize(),t}case Yg.Vector4:{const t=new F(e(r,i.x,s.x),e(r,i.y,s.y),e(r,i.z,s.z),e(r,i.w,s.w));return t.normalize(),t}}return 0},this}}),u("BABYLON.GeometryStepBlock",class extends mv{constructor(e){super(e),this.registerInput("value",Yg.AutoDetect),this.registerInput("edge",Yg.Float),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryStepBlock"}get value(){return this._inputs[0]}get edge(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e{const i=this.value.getConnectedValue(t),s=this.edge.getConnectedValue(t);switch(this.value.type){case Yg.Int:case Yg.Float:return e(i,s);case Yg.Vector2:return new N(e(i.x,s),e(i.y,s));case Yg.Vector3:return new w(e(i.x,s),e(i.y,s),e(i.z,s));case Yg.Vector4:return new F(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}}),u("BABYLON.GeometrySmoothStepBlock",class extends mv{constructor(e){super(e),this.registerInput("value",Yg.AutoDetect),this.registerInput("edge0",Yg.Float),this.registerInput("edge1",Yg.Float),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometrySmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.edge0.isConnected||!this.edge1.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t,i)=>{const s=Math.max(0,Math.min((e-t)/(i-t),1));return s*s*(3-2*s)};return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.edge0.getConnectedValue(t),r=this.edge1.getConnectedValue(t);switch(this.value.type){case Yg.Int:case Yg.Float:return e(i,s,r);case Yg.Vector2:return new N(e(i.x,s,r),e(i.y,s,r));case Yg.Vector3:return new w(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r));case Yg.Vector4:return new F(e(i.x,s,r),e(i.y,s,r),e(i.z,s,r),e(i.w,s,r))}return 0},this}}),u("BABYLON.GeometryModBlock",class extends mv{constructor(e){super(e),this.registerInput("left",Yg.AutoDetect),this.registerInput("right",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected||!this.right.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>e-Math.floor(e/t)*t;return this.output._storedFunction=t=>{const i=this.left.getConnectedValue(t),s=this.right.getConnectedValue(t);switch(this.left.type){case Yg.Int:case Yg.Float:return e(i,s);case Yg.Vector2:return new N(e(i.x,s.x),e(i.y,s.y));case Yg.Vector3:return new w(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z));case Yg.Vector4:return new F(e(i.x,s.x),e(i.y,s.y),e(i.z,s.z),e(i.w,s.w))}return 0},this}}),u("BABYLON.GeometryPowBlock",class extends mv{constructor(e){super(e),this.registerInput("value",Yg.AutoDetect),this.registerInput("power",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryPowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected||!this.power.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=(e,t)=>Math.pow(e,t);return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t),s=this.power.getConnectedValue(t);switch(this.value.type){case Yg.Int:case Yg.Float:return e(i,s);case Yg.Vector2:return new N(e(i.x,s),e(i.y,s));case Yg.Vector3:return new w(e(i.x,s),e(i.y,s),e(i.z,s));case Yg.Vector4:return new F(e(i.x,s),e(i.y,s),e(i.z,s),e(i.w,s))}return 0},this}});class Jv extends mv{constructor(e){super(e),this.minimum=0,this.maximum=1,this.registerInput("value",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Geometry),this._inputs[0].excludedConnectionPointTypes.push(Yg.Texture)}getClassName(){return"GeometryClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);const e=e=>Math.max(this.minimum,Math.min(e,this.maximum));return this.output._storedFunction=t=>{const i=this.value.getConnectedValue(t);switch(this.value.type){case Yg.Int:case Yg.Float:return e(i);case Yg.Vector2:return new N(e(i.x),e(i.y));case Yg.Vector3:return new w(e(i.x),e(i.y),e(i.z));case Yg.Vector4:return new F(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\n`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e){super._deserialize(e),this.minimum=e.minimum,this.maximum=e.maximum}}ae([Lo("Minimum",bo.Float)],Jv.prototype,"minimum",void 0),ae([Lo("Maximum",bo.Float)],Jv.prototype,"maximum",void 0),u("BABYLON.GeometryClampBlock",Jv),u("BABYLON.GeometryCrossBlock",class extends mv{constructor(e){super(e),this.registerInput("left",Yg.AutoDetect),this.registerInput("right",Yg.AutoDetect),this.registerOutput("output",Yg.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Int),this._inputs[0].excludedConnectionPointTypes.push(Yg.Float),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Vector2),this._inputs[1].excludedConnectionPointTypes.push(Yg.Int),this._inputs[1].excludedConnectionPointTypes.push(Yg.Float),this._inputs[1].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Yg.Vector2)}getClassName(){return"GeometryCrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);switch(this.left.type){case Yg.Vector3:return w.Cross(t,i);case Yg.Vector4:return w.Cross(t.toVector3(),i.toVector3())}return 0},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(iv||(iv={}));class ex extends mv{constructor(e){super(e),this.type=iv.EaseInOutSine,this.registerInput("input",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[0].excludedConnectionPointTypes.push(Yg.Int)}getClassName(){return"GeometryCurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){if(!this.input.isConnected)return this.output._storedFunction=null,void(this.output._storedValue=null);let e;switch(this.type){case iv.EaseInSine:e=e=>1-Math.cos(3.1415*e/2);break;case iv.EaseOutSine:e=e=>Math.sin(3.1415*e/2);break;case iv.EaseInOutSine:e=e=>-(Math.cos(3.1415*e)-1)/2;break;case iv.EaseInQuad:e=e=>e*e;break;case iv.EaseOutQuad:e=e=>(1-e)*(1-e);break;case iv.EaseInOutQuad:e=e=>e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;break;case iv.EaseInCubic:e=e=>e*e*e;break;case iv.EaseOutCubic:e=e=>1-Math.pow(1-e,3);break;case iv.EaseInOutCubic:e=e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;break;case iv.EaseInQuart:e=e=>e*e*e*e;break;case iv.EaseOutQuart:e=e=>1-Math.pow(1-e,4);break;case iv.EaseInOutQuart:e=e=>e<.5?8*e*e*e*e:1-Math.pow(-2*e+2,4)/2;break;case iv.EaseInQuint:e=e=>e*e*e*e*e;break;case iv.EaseOutQuint:e=e=>1-Math.pow(1-e,5);break;case iv.EaseInOutQuint:e=e=>e<.5?16*e*e*e*e*e:1-Math.pow(-2*e+2,5)/2;break;case iv.EaseInExpo:e=e=>0===e?0:Math.pow(2,10*e-10);break;case iv.EaseOutExpo:e=e=>1===e?1:1-Math.pow(2,-10*e);break;case iv.EaseInOutExpo:e=e=>0===e?0:1===e?1:e<.5?Math.pow(2,20*e-10)/2:(2-Math.pow(2,-20*e+10))/2;break;case iv.EaseInCirc:e=e=>1-Math.sqrt(1-Math.pow(e,2));break;case iv.EaseOutCirc:e=e=>Math.sqrt(1-Math.pow(e-1,2));break;case iv.EaseInOutCirc:e=e=>e<.5?(1-Math.sqrt(1-Math.pow(2*e,2)))/2:(Math.sqrt(1-Math.pow(-2*e+2,2))+1)/2;break;case iv.EaseInBack:e=e=>2.70158*e*e*e-1.70158*e*e;break;case iv.EaseOutBack:e=e=>2.70158*Math.pow(e-1,3)+1.70158*Math.pow(e-1,2);break;case iv.EaseInOutBack:e=e=>e<.5?Math.pow(2*e,2)*(7.189819*e-2.5949095)/2:(Math.pow(2*e-2,2)*(3.5949095*(2*e-2)+3.5949095)+2)/2;break;case iv.EaseInElastic:e=e=>0===e?0:1===e?1:-Math.pow(2,10*e-10)*Math.sin(6.283/3*(10*e-10.75));break;case iv.EaseOutElastic:e=e=>0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(6.283/3*(10*e-.75))+1;break;case iv.EaseInOutElastic:e=e=>0===e?0:1==e?1:e<.5?-Math.pow(2,20*e-10)*Math.sin(6.283/4.5*(20*e-11.125))/2:Math.pow(2,-20*e+10)*Math.sin(6.283/4.5*(20*e-11.125))/2+1}return this.output._storedFunction=t=>{const i=this.input.getConnectedValue(t);switch(this.input.type){case Yg.Float:return e(i);case Yg.Vector2:return new N(e(i.x),e(i.y));case Yg.Vector3:return new w(e(i.x),e(i.y),e(i.z));case Yg.Vector4:return new F(e(i.x),e(i.y),e(i.z),e(i.w))}return 0},this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e){super._deserialize(e),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.GeometryCurveBlockTypes.${iv[this.type]};\n`}}ae([Lo("Type",bo.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"EaseInSine",value:iv.EaseInSine},{label:"EaseOutSine",value:iv.EaseOutSine},{label:"EaseInOutSine",value:iv.EaseInOutSine},{label:"EaseInQuad",value:iv.EaseInQuad},{label:"EaseOutQuad",value:iv.EaseOutQuad},{label:"EaseInOutQuad",value:iv.EaseInOutQuad},{label:"EaseInCubic",value:iv.EaseInCubic},{label:"EaseOutCubic",value:iv.EaseOutCubic},{label:"EaseInOutCubic",value:iv.EaseInOutCubic},{label:"EaseInQuart",value:iv.EaseInQuart},{label:"EaseOutQuart",value:iv.EaseOutQuart},{label:"EaseInOutQuart",value:iv.EaseInOutQuart},{label:"EaseInQuint",value:iv.EaseInQuint},{label:"EaseOutQuint",value:iv.EaseOutQuint},{label:"EaseInOutQuint",value:iv.EaseInOutQuint},{label:"EaseInExpo",value:iv.EaseInExpo},{label:"EaseOutExpo",value:iv.EaseOutExpo},{label:"EaseInOutExpo",value:iv.EaseInOutExpo},{label:"EaseInCirc",value:iv.EaseInCirc},{label:"EaseOutCirc",value:iv.EaseOutCirc},{label:"EaseInOutCirc",value:iv.EaseInOutCirc},{label:"EaseInBack",value:iv.EaseInBack},{label:"EaseOutBack",value:iv.EaseOutBack},{label:"EaseInOutBack",value:iv.EaseInOutBack},{label:"EaseInElastic",value:iv.EaseInElastic},{label:"EaseOutElastic",value:iv.EaseOutElastic},{label:"EaseInOutElastic",value:iv.EaseInOutElastic}]})],ex.prototype,"type",void 0),u("BABYLON.GeometryCurveBlock",ex),u("BABYLON.GeometryDesaturateBlock",class extends mv{constructor(e){super(e),this.registerInput("color",Yg.Vector3),this.registerInput("level",Yg.Float,!0,0),this.registerOutput("output",Yg.Vector3)}getClassName(){return"GeometryDesaturateBlock"}get color(){return this._inputs[0]}get level(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.color.isConnected?(this.output._storedFunction=e=>{const t=this.color.getConnectedValue(e),i=this.level.getConnectedValue(e),s=.5*(Math.min(t.x,t.y,t.z)+Math.max(t.x,t.y,t.z));return new w(t.x*(1-i)+s*i,t.y*(1-i)+s*i,t.z*(1-i)+s*i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}),u("BABYLON.GeometryPosterizeBlock",class extends mv{constructor(e){super(e),this.registerInput("value",Yg.AutoDetect),this.registerInput("steps",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[1].acceptedConnectionPointTypes.push(Yg.Float)}getClassName(){return"GeometryPosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected&&this.steps.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.steps.getConnectedValue(e);let s=i;if(this.steps.type===Yg.Float)switch(this.value.type){case Yg.Vector2:s=new N(i,i);break;case Yg.Vector3:s=new w(i,i,i);break;case Yg.Vector4:s=new F(i,i,i,i)}switch(this.value.type){case Yg.Vector2:return new N(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y));case Yg.Vector3:return new w(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z));case Yg.Vector4:return new F(t.x/(1/s.x)*(1/s.x),t.y/(1/s.y)*(1/s.y),t.z/(1/s.z)*(1/s.z),t.w/(1/s.w)*(1/s.w));default:return Math.floor(t/(1/i)*(1/i))}},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}),u("BABYLON.GeometryReplaceColorBlock",class extends mv{constructor(e){super(e),this.registerInput("value",Yg.AutoDetect),this.registerInput("reference",Yg.AutoDetect),this.registerInput("distance",Yg.Float),this.registerInput("replacement",Yg.AutoDetect),this.registerOutput("output",Yg.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(Yg.Float),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Yg.Float),this._inputs[1].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[3].excludedConnectionPointTypes.push(Yg.Float),this._inputs[3].excludedConnectionPointTypes.push(Yg.Matrix)}getClassName(){return"GeometryReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected&&this.reference.isConnected&&this.distance.isConnected&&this.replacement.isConnected?(this.output._storedFunction=e=>{const t=this.value.getConnectedValue(e),i=this.reference.getConnectedValue(e),s=this.distance.getConnectedValue(e),r=this.replacement.getConnectedValue(e);return t.subtract(i).length(){const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.subtract(i).length()},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}),u("BABYLON.GeometryDotBlock",class extends mv{constructor(e){super(e),this.registerInput("left",Yg.AutoDetect),this.registerInput("right",Yg.AutoDetect),this.registerOutput("output",Yg.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(Yg.Int),this._inputs[0].excludedConnectionPointTypes.push(Yg.Float),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix),this._inputs[1].excludedConnectionPointTypes.push(Yg.Float),this._inputs[1].excludedConnectionPointTypes.push(Yg.Matrix)}getClassName(){return"GeometryDotBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.left.isConnected&&this.right.isConnected?(this.output._storedFunction=e=>{const t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e);return t.dot(i)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}),u("BABYLON.GeometryLengthBlock",class extends mv{constructor(e){super(e),this.registerInput("value",Yg.AutoDetect),this.registerOutput("output",Yg.Float),this._inputs[0].excludedConnectionPointTypes.push(Yg.Int),this._inputs[0].excludedConnectionPointTypes.push(Yg.Float),this._inputs[0].excludedConnectionPointTypes.push(Yg.Matrix)}getClassName(){return"GeometryLengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){return this.value.isConnected?(this.output._storedFunction=e=>this.value.getConnectedValue(e).length(),this):(this.output._storedFunction=null,void(this.output._storedValue=null))}}),u("BABYLON.GeometryRotate2dBlock",class extends mv{constructor(e){super(e),this.registerInput("input",Yg.Vector2),this.registerInput("angle",Yg.Float),this.registerOutput("output",Yg.Vector2)}getClassName(){return"GeometryRotate2dBlock"}get input(){return this._inputs[0]}get angle(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){return this.angle.isConnected&&this.input.isConnected?(this.output._storedFunction=e=>{const t=this.input.getConnectedValue(e),i=this.angle.getConnectedValue(e);return new N(Math.cos(i)*t.x-Math.sin(i)*t.y,Math.sin(i)*t.x+Math.cos(i)*t.y)},this):(this.output._storedFunction=null,void(this.output._storedValue=null))}});class tx extends Un{get covariancesATexture(){return this._covariancesATexture}get covariancesBTexture(){return this._covariancesBTexture}get centersTexture(){return this._centersTexture}get colorsTexture(){return this._colorsTexture}constructor(e,t=null,i=null){super(e,i),this._vertexCount=0,this._worker=null,this._frameIdLastUpdate=-1,this._modelViewMatrix=B.Identity(),this._material=null,this._canPostToWorker=!0,this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null;const s=new Tr;s.positions=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],s.indices=[0,1,2,0,2,3],s.applyToMesh(this),this.subMeshes=[],new vr(0,0,4,0,6,this),this.doNotSyncBoundingInfo=!0,this.setEnabled(!1),this._lastProj=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t&&this.loadFileAsync(t)}getClassName(){return"GaussianSplattingMesh"}getTotalVertices(){return this._vertexCount}render(e,t,i){this.material||(this._material=new Cg(this.name+"_material",this._scene),this.material=this._material);const s=this.getScene().getFrameId();if(s!==this._frameIdLastUpdate&&this._worker&&this._scene.activeCamera&&this._canPostToWorker){this.getWorldMatrix().multiplyToRef(this._scene.activeCamera.getViewMatrix(),this._modelViewMatrix);const e=this._lastProj[2]*this._modelViewMatrix.m[2]+this._lastProj[6]*this._modelViewMatrix.m[6]+this._lastProj[10]*this._modelViewMatrix.m[10];Math.abs(e-1)>=.01&&(this._frameIdLastUpdate=s,this._canPostToWorker=!1,this._lastProj=this._modelViewMatrix.m.slice(0),this._worker.postMessage({view:this._modelViewMatrix.m,depthMix:this._depthMix,useRightHandedSystem:this._scene.useRightHandedSystem},[this._depthMix.buffer]))}return super.render(e,t,i)}static ConvertPLYToSplat(e){const t=new Uint8Array(e),i=(new TextDecoder).decode(t.slice(0,10240)),s=i.indexOf("end_header\n");if(s<0||!i)return e;const r=parseInt(/element vertex (\d+)\n/.exec(i)[1]);let n=0;const o={double:8,int:4,uint:4,float:4,short:2,ushort:2,uchar:1},a=[],l=i.slice(0,s).split("\n").filter((e=>e.startsWith("property ")));for(const e of l){const[,t,i]=e.split(" ");if(a.push({name:i,type:t,offset:n}),!o[t])return J.Error(`Unsupported property type: ${t}. Are you sure it's a valid Gaussian Splatting file?`),new ArrayBuffer(0);n+=o[t]}const h=.28209479177387814,c=new DataView(e,s+11),u=new ArrayBuffer(32*r),d=new L;for(let e=0;e{this._loadData(tx.ConvertPLYToSplat(e))}))}dispose(e){this._covariancesATexture?.dispose(),this._covariancesBTexture?.dispose(),this._centersTexture?.dispose(),this._colorsTexture?.dispose(),this._covariancesATexture=null,this._covariancesBTexture=null,this._centersTexture=null,this._colorsTexture=null,this._material?.dispose(!1,!0),this._material=null,this._worker?.terminate(),this._worker=null,super.dispose(e)}_loadData(e){if(!e.byteLength)return;const t=new Uint8Array(e),i=new Float32Array(t.buffer),s=t.length/32;this._vertexCount=s;const r=this._getTextureSize(s),n=r.x*r.y,o=new Float32Array(3*n),a=new Float32Array(3*n),l=new Float32Array(3*n),h=U.Matrix[0],c=U.Matrix[1],u=U.Quaternion[0],d=new w(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),p=new w(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let e=0;enew io(e,t,i,s,this._scene,!1,!1,2,1),g=e=>{const t=e.length/3,i=new Float32Array(4*t);for(let s=0;s{this._depthMix=e.data.depthMix;const t=new Uint32Array(e.data.depthMix.buffer);for(let e=0;ei&&(J.Error("GaussianSplatting texture size: ("+i+", "+s+"), maxTextureSize: "+i),s=i),new N(i,s)}}tx._CreateWorker=function(e){let t,i,s,r,n=0;e.onmessage=o=>{if(o.data.positions)t=o.data.positions,n=o.data.vertexCount;else{const a=o.data.view;if(!t||!a)throw new Error("positions or view is not defined!");i=o.data.depthMix,s=new Uint32Array(i.buffer),r=new Float32Array(i.buffer);for(let e=0;enew ix(e,t,i);class ix{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=ix._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,ix.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,Ii.SetImmediate((()=>{t(!0)}))):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){const t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){const e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`};let s=!1,r=i();const n=new Ne;navigator.onLine&&(s=!0,r=r+(null==r.match(/\?/)?"?":"&")+Date.now()),n.open("GET",r),n.addEventListener("load",(()=>{if(200===n.status||ix._ValidateXHRData(n,1))try{const t=JSON.parse(n.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&ix._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){t()}else t()}),!1),n.addEventListener("error",(()=>{if(s){s=!1;const e=i();n.open("GET",e),n.send()}else t()}),!1);try{n.send()}catch(t){J.Error("Error on XHR send request."),e(!1)}}open(e,t){const i=()=>{this._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline))if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;const t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{i()},t.onblocked=()=>{J.Error("IDB request blocked. Please reload the page."),i()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){J.Error("Error while creating object stores. Exception: "+e.message),i()}}}else this._isSupported=!1,t&&t()}loadImage(e,t){const i=ix._ReturnFullUrlLocation(e),s=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?s():this._loadImageFromDBAsync(i,t,s)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let s;const r=this._db.transaction(["textures"]);r.onabort=()=>{t.src=e},r.oncomplete=()=>{let r;s&&"function"==typeof URL?(r=URL.createObjectURL(s.data),t.onerror=()=>{J.Error("Error loading image from blob URL: "+r+" switching back to web url: "+e),t.src=e},t.src=r):i()};const n=r.objectStore("textures").get(e);n.onsuccess=e=>{s=e.target.result},n.onerror=()=>{J.Error("Error loading texture "+e+" from DB."),t.src=e}}else J.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){const s=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(ix._IsUASupportingBlobStorage){const r=new Ne;r.open("GET",e),r.responseType="blob",r.addEventListener("load",(()=>{if(200===r.status&&this._db){i=r.response;const n=this._db.transaction(["textures"],"readwrite");n.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}s()},n.oncomplete=()=>{s()};const o={textureUrl:e,data:i};try{const e=n.objectStore("textures").put(o);e.onsuccess=()=>{},e.onerror=()=>{s()}}catch(i){25===i.code&&(ix._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e}),!1),r.addEventListener("error",(()=>{J.Error("Error in XHR request in BABYLON.Database."),t.src=e}),!1),r.send()}else t.src=e}else J.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,(()=>{this._saveVersionIntoDBAsync(e,t)}))}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let s;try{const r=this._db.transaction(["versions"]);r.oncomplete=()=>{s?this._manifestVersionFound!==s.data?(this._mustUpdateRessources=!0,i()):t(s.data):(this._mustUpdateRessources=!0,i())},r.onabort=()=>{t(-1)};const n=r.objectStore("versions").get(e);n.onsuccess=e=>{s=e.target.result},n.onerror=()=>{J.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){J.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else J.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)}_saveVersionIntoDBAsync(e,t){if(this._isSupported&&!this._hasReachedQuota&&this._db)try{const i=this._db.transaction(["versions"],"readwrite");i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const s={sceneUrl:e,data:this._manifestVersionFound},r=i.objectStore("versions").put(s);r.onsuccess=()=>{},r.onerror=()=>{J.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){J.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,s,r){const n=ix._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(n,t,i,r,s)};this._checkVersionFromDB(n,(e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(n,t,i,r,s):this._loadFileAsync(n,t,o):s&&s()}))}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let s,r;s=-1!==e.indexOf(".babylon")?"scenes":"textures";const n=this._db.transaction([s]);n.oncomplete=()=>{r?t(r.data):i()},n.onabort=()=>{i()};const o=n.objectStore(s).get(e);o.onsuccess=e=>{r=e.target.result},o.onerror=()=>{J.Error("Error loading file "+e+" from DB."),i()}}else J.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,s,r){if(this._isSupported){let n;n=-1!==e.indexOf(".babylon")?"scenes":"textures";const o=new Ne;let a;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),s&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",(()=>{if(200===o.status||o.status<400&&ix._ValidateXHRData(o,s?6:1))if(a=s?o.response:o.responseText,!this._hasReachedQuota&&this._db){const i=this._db.transaction([n],"readwrite");let s;i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(a)},i.oncomplete=()=>{t(a)},s="scenes"===n?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{const e=i.objectStore(n).put(s);e.onsuccess=()=>{},e.onerror=()=>{J.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(a)}}else t(a);else o.status>=400&&r?r(o):t()}),!1),o.addEventListener("error",(()=>{J.Error("error on XHR request."),r&&r()}),!1),o.send()}else J.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),r&&r()}static _ValidateXHRData(e,t=7){try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){const i=pm(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){const t=new Uint8Array(e.response,0,3);return 68===t[0]&&68===t[1]&&83===t[2]}}catch(e){}return!1}}ix._IsUASupportingBlobStorage=!0,ix.IDBStorageEnabled=!1,ix._ParseURL=e=>{document.createElement("a").href=e;const t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},ix._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?ix._ParseURL(window.location.href)+e:e;class sx{constructor(){this.direction1=new w(0,1,0),this.direction2=new w(0,1,0),this.minEmitBox=new w(-.5,-.5,-.5),this.maxEmitBox=new w(.5,.5,.5)}startDirectionFunction(e,t,i,s){const r=R(this.direction1.x,this.direction2.x),n=R(this.direction1.y,this.direction2.y),o=R(this.direction1.z,this.direction2.z);if(s)return t.x=r,t.y=n,void(t.z=o);w.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){const r=R(this.minEmitBox.x,this.maxEmitBox.x),n=R(this.minEmitBox.y,this.maxEmitBox.y),o=R(this.minEmitBox.z,this.maxEmitBox.z);if(s)return t.x=r,t.y=n,void(t.z=o);w.TransformCoordinatesFromFloatsToRef(r,n,o,e,t)}clone(){const e=new sx;return se.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){w.FromArrayToRef(e.direction1,0,this.direction1),w.FromArrayToRef(e.direction2,0,this.direction2),w.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),w.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class rx{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,s){s?U.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),U.Vector3[0]).normalize();const r=G.RandomRange(0,this.directionRandomizer),n=G.RandomRange(0,this.directionRandomizer),o=G.RandomRange(0,this.directionRandomizer);t.x=U.Vector3[0].x+r,t.y=U.Vector3[0].y+n,t.z=U.Vector3[0].z+o,t.normalize()}startPositionFunction(e,t,i,s){const r=G.RandomRange(0,2*Math.PI);let n;this.emitFromSpawnPointOnly?n=1e-4:(n=G.RandomRange(0,this.heightRange),n=1-n*n);let o=this._radius-G.RandomRange(0,this._radius*this.radiusRange);o*=n;const a=o*Math.sin(r),l=o*Math.cos(r),h=n*this._height;if(s)return t.x=a,t.y=h,void(t.z=l);w.TransformCoordinatesFromFloatsToRef(a,h,l,e,t)}clone(){const e=new rx(this._radius,this._angle,this.directionRandomizer);return se.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e}getClassName(){return"ConeParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}}class nx{constructor(e=1,t=1,i=1,s=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=s,this._tempVector=w.Zero()}startDirectionFunction(e,t,i,s,r){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),w.TransformNormalToRef(this._tempVector,r,this._tempVector);const n=G.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let o=Math.atan2(this._tempVector.x,this._tempVector.z);o+=G.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=n,this._tempVector.x=Math.sin(o),this._tempVector.z=Math.cos(o),this._tempVector.normalize(),s?t.copyFrom(this._tempVector):w.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,s){const r=G.RandomRange(-this.height/2,this.height/2),n=G.RandomRange(0,2*Math.PI),o=G.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),a=Math.sqrt(o)*this.radius,l=a*Math.cos(n),h=a*Math.sin(n);s?t.copyFromFloats(l,r,h):w.TransformCoordinatesFromFloatsToRef(l,r,h,e,t)}clone(){const e=new nx(this.radius,this.directionRandomizer);return se.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class ox extends nx{constructor(e=1,t=1,i=1,s=new w(0,1,0),r=new w(0,1,0)){super(e,t,i),this.direction1=s,this.direction2=r}startDirectionFunction(e,t,i,s){const r=G.RandomRange(this.direction1.x,this.direction2.x),n=G.RandomRange(this.direction1.y,this.direction2.y),o=G.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):w.TransformNormalFromFloatsToRef(r,n,o,e,t)}clone(){const e=new ox(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return se.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),w.FromArrayToRef(e.direction1,0,this.direction1),w.FromArrayToRef(e.direction2,0,this.direction2)}}class ax{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=G.RandomRange(0,this.directionRandomizer),o=G.RandomRange(0,this.directionRandomizer),a=G.RandomRange(0,this.directionRandomizer);r.x+=n,r.y+=o,r.z+=a,r.normalize(),s?t.copyFrom(r):w.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-G.RandomRange(0,this.radius*this.radiusRange),n=G.RandomRange(0,1),o=G.RandomRange(0,2*Math.PI),a=Math.acos(2*n-1),l=r*Math.cos(o)*Math.sin(a),h=r*Math.cos(a),c=r*Math.sin(o)*Math.sin(a);s?t.copyFromFloats(l,Math.abs(h),c):w.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),c,e,t)}clone(){const e=new ax(this.radius,this.directionRandomizer);return se.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class lx{constructor(){this.direction1=new w(0,1,0),this.direction2=new w(0,1,0)}startDirectionFunction(e,t,i,s){const r=G.RandomRange(this.direction1.x,this.direction2.x),n=G.RandomRange(this.direction1.y,this.direction2.y),o=G.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):w.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){s?t.copyFromFloats(0,0,0):w.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new lx;return se.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){w.FromArrayToRef(e.direction1,0,this.direction1),w.FromArrayToRef(e.direction2,0,this.direction2)}}class hx{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,s){const r=i.position.subtract(e.getTranslation()).normalize(),n=G.RandomRange(0,this.directionRandomizer),o=G.RandomRange(0,this.directionRandomizer),a=G.RandomRange(0,this.directionRandomizer);r.x+=n,r.y+=o,r.z+=a,r.normalize(),s?t.copyFrom(r):w.TransformNormalFromFloatsToRef(r.x,r.y,r.z,e,t)}startPositionFunction(e,t,i,s){const r=this.radius-G.RandomRange(0,this.radius*this.radiusRange),n=G.RandomRange(0,1),o=G.RandomRange(0,2*Math.PI),a=Math.acos(2*n-1),l=r*Math.cos(o)*Math.sin(a),h=r*Math.cos(a),c=r*Math.sin(o)*Math.sin(a);s?t.copyFromFloats(l,h,c):w.TransformCoordinatesFromFloatsToRef(l,h,c,e,t)}clone(){const e=new hx(this.radius,this.directionRandomizer);return se.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class cx extends hx{constructor(e=1,t=new w(0,1,0),i=new w(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=G.RandomRange(this.direction1.x,this.direction2.x),s=G.RandomRange(this.direction1.y,this.direction2.y),r=G.RandomRange(this.direction1.z,this.direction2.z);w.TransformNormalFromFloatsToRef(i,s,r,e,t)}clone(){const e=new cx(this.radius,this.direction1,this.direction2);return se.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class ux{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,s){const r=U.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,r);const e=U.Vector3[1];r.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,r)}else r.set(0,0,0);s?t.copyFrom(r):w.TransformNormalToRef(r,e,t)}startPositionFunction(e,t,i,s){const r=U.Vector3[0];this.particlePositionGenerator?this.particlePositionGenerator(-1,i,r):r.set(0,0,0),s?t.copyFrom(r):w.TransformCoordinatesToRef(r,e,t)}clone(){const e=new ux;return se.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.particlePositionGenerator=this.particlePositionGenerator,e.particleDestinationGenerator=this.particleDestinationGenerator,e}parse(e){e.particlePositionGenerator&&(this.particlePositionGenerator=e.particlePositionGenerator),e.particleDestinationGenerator&&(this.particleDestinationGenerator=e.particleDestinationGenerator)}}class dx{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(Ki.PositionKind),this._normals=e.getVerticesData(Ki.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=w.Zero(),this._mesh=null,this.direction1=new w(0,1,0),this.direction2=new w(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,s){if(this.useMeshNormalsForDirection&&this._normals)return void w.TransformNormalToRef(this._storedNormal,e,t);const r=G.RandomRange(this.direction1.x,this.direction2.x),n=G.RandomRange(this.direction1.y,this.direction2.y),o=G.RandomRange(this.direction1.z,this.direction2.z);s?t.copyFromFloats(r,n,o):w.TransformNormalFromFloatsToRef(r,n,o,e,t)}startPositionFunction(e,t,i,s){if(!this._indices||!this._positions)return;const r=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),o=Math.random()*(1-n),a=1-n-o,l=this._indices[r],h=this._indices[r+1],c=this._indices[r+2],u=U.Vector3[0],d=U.Vector3[1],p=U.Vector3[2],f=U.Vector3[3];w.FromArrayToRef(this._positions,3*l,u),w.FromArrayToRef(this._positions,3*h,d),w.FromArrayToRef(this._positions,3*c,p),f.x=n*u.x+o*d.x+a*p.x,f.y=n*u.y+o*d.y+a*p.y,f.z=n*u.z+o*d.z+a*p.z,s?t.copyFromFloats(f.x,f.y,f.z):w.TransformCoordinatesFromFloatsToRef(f.x,f.y,f.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(w.FromArrayToRef(this._normals,3*l,u),w.FromArrayToRef(this._normals,3*h,d),w.FromArrayToRef(this._normals,3*c,p),this._storedNormal.x=n*u.x+o*d.x+a*p.x,this._storedNormal.y=n*u.y+o*d.y+a*p.y,this._storedNormal.z=n*u.z+o*d.z+a*p.z)}clone(){const e=new dx(this.mesh);return se.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.meshId=this.mesh?.id,e.useMeshNormalsForDirection=this.useMeshNormalsForDirection,e}parse(e,t){w.FromArrayToRef(e.direction1,0,this.direction1),w.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class px{_isUbo(e){return void 0!==e.addUniform}constructor(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}}Ft.ShadersStore.gpuUpdateParticlesPixelShader="#version 300 es\nvoid main() {discard;}\n";Ft.ShadersStore.gpuUpdateParticlesVertexShader="#version 300 es\n#define PI 3.14159\nuniform float currentCount;uniform float timeDelta;uniform float stopFactor;\n#ifndef LOCAL\nuniform mat4 emitterWM;\n#endif\nuniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;uniform vec4 color2;\n#endif\nuniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;uniform float radiusRange;uniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;uniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;uniform float height;uniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;uniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer;\n#endif\nin vec3 position;\n#ifdef CUSTOMEMITTER\nin vec3 initialPosition;\n#endif\nin float age;in float life;in vec4 seed;in vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;in vec3 noiseCoordinates2;\n#endif\nout vec3 outPosition;\n#ifdef CUSTOMEMITTER\nout vec3 outInitialPosition;\n#endif\nout float outAge;out float outLife;out vec4 outSeed;out vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;uniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec4 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;}\nvec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));}\nvoid main() {float newAge=age+timeDelta; \nif (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed;\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(direction1+(direction2-direction1)*randoms3);\n#else\nnewDirection=normalize(newPosition+directionRandomizer*randoms3);\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\nangle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.0001;\n#else\nfloat h=randoms2.y*height.y;h=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); \nif (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); }\n#elif defined(CUSTOMEMITTER)\nnewPosition=initialPosition;outInitialPosition=initialPosition;\n#else \nnewPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\n#ifdef LOCAL\noutPosition=newPosition;\n#else\noutPosition=(emitterWM*vec4(newPosition,1.)).xyz;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#ifndef BILLBOARD \noutInitialDirection=direction;\n#endif\n#else\n#ifdef LOCAL\nvec3 initial=newDirection;\n#else \nvec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;\n#endif\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#if defined(CUSTOMEMITTER)\noutPosition=position+(direction-position)*ageGradient; \noutInitialPosition=initialPosition;\n#else\noutPosition=position+direction*directionScale;\n#endif\noutLife=life;outSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#else\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2;\n#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;float dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset;\n#else\nfloat cellStartOffset=0.;\n#endif \nfloat ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);}\nelse {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);}\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}}",u("BABYLON.WebGL2ParticleSystem",class{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){return this._updateEffect?.isReady()??!1}createUpdateBuffer(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof ux&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new $t("gpuUpdateParticles",this._updateEffectOptions,this._engine),new px(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){const e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);const s=this._engine;s.bindTransformFeedbackBuffer(t.getBuffer()),s.setRasterizerState(!1),s.beginTransformFeedback(!0),s.drawArraysType(3,0,i),s.endTransformFeedback(),s.setRasterizerState(!0),s.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;ee)return void i(t[0],t[0],1);for(let s=0;s=r.gradient&&e<=n.gradient)return void i(r,n,(e-r.gradient)/(n.gradient-r.gradient))}const s=t.length-1;i(t[s],t[s],1)}}class vx{constructor(e){this.particleSystem=e,this.position=w.Zero(),this.direction=w.Zero(),this.color=new j(0,0,0,0),this.colorStep=new j(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new N(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new j(0,0,0,0),this._currentColor2=new j(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=vx._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===t?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);const i=this._initialEndSpriteCellID-this._initialStartSpriteCellID+1;let s;s=this._initialSpriteCellLoop?P(e*t%this.lifeTime/this.lifeTime):P(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+s*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const e=U.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,U.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(U.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach((e=>{this._inheritParticleInfoToSubEmitter(e)}))}_reset(){this.age=0,this.id=vx._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new F(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}}vx._Count=0;Ft.ShadersStore.particlesPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler;\n#include\n#include\n#include\n#include\n#include\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;uniform sampler2D rampSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n#include\n#include(color,baseColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.particlesVertexShader="attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos; \n#endif\nvarying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#include\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvec3 row1=direction;\n#else\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nmat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size;\n#ifdef BILLBOARD\nvec3 rotatedCorner;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\ngl_Position=projection*vec4(viewPos,1.0);\n#else\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0);\n#endif\nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";class xx extends ia{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new gr(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new g),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,s=null,r=!1,n=.01){super(e),this._emitterInverseWorldMatrix=B.Identity(),this._inheritedVelocityOffset=new w,this.onDisposeObservable=new g,this.onStoppedObservable=new g,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new j(0,0,0,0),this._colorDiff=new j(0,0,0,0),this._scaledDirection=w.Zero(),this._scaledGravity=w.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this._emitFromParticle=e=>{},this.recycleParticle=e=>{const t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;return 0!==this._stockParticles.length?(e=this._stockParticles.pop(),e._reset()):e=new vx(this),this._prepareParticle(e),e},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=r,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=B.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||y.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new gr(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new sx;let o=null;this.updateFunction=e=>{let t=null;this.noiseTexture&&(t=this.noiseTexture.getSize(),this.noiseTexture.getContent()?.then((e=>{o=e})));const i=e===this._particles;for(let s=0;sr.lifeTime){const e=r.age-a;n=(r.lifeTime-a)*n/e,r.age=r.lifeTime}const l=r.age/r.lifeTime;this._colorGradients&&this._colorGradients.length>0?gx.GetCurrentGradient(l,this._colorGradients,((e,t,i)=>{e!==r._currentColorGradient&&(r._currentColor1.copyFrom(r._currentColor2),t.getColorToRef(r._currentColor2),r._currentColorGradient=e),j.LerpToRef(r._currentColor1,r._currentColor2,i,r.color)})):(r.colorStep.scaleToRef(n,this._scaledColorStep),r.color.addInPlace(this._scaledColorStep),r.color.a<0&&(r.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&gx.GetCurrentGradient(l,this._angularSpeedGradients,((e,t,i)=>{e!==r._currentAngularSpeedGradient&&(r._currentAngularSpeed1=r._currentAngularSpeed2,r._currentAngularSpeed2=t.getFactor(),r._currentAngularSpeedGradient=e),r.angularSpeed=I(r._currentAngularSpeed1,r._currentAngularSpeed2,i)})),r.angle+=r.angularSpeed*n;let h=n;if(this._velocityGradients&&this._velocityGradients.length>0&&gx.GetCurrentGradient(l,this._velocityGradients,((e,t,i)=>{e!==r._currentVelocityGradient&&(r._currentVelocity1=r._currentVelocity2,r._currentVelocity2=t.getFactor(),r._currentVelocityGradient=e),h*=I(r._currentVelocity1,r._currentVelocity2,i)})),r.direction.scaleToRef(h,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&gx.GetCurrentGradient(l,this._limitVelocityGradients,((e,t,i)=>{e!==r._currentLimitVelocityGradient&&(r._currentLimitVelocity1=r._currentLimitVelocity2,r._currentLimitVelocity2=t.getFactor(),r._currentLimitVelocityGradient=e);const s=I(r._currentLimitVelocity1,r._currentLimitVelocity2,i);r.direction.length()>s&&r.direction.scaleInPlace(this.limitVelocityDamping)})),this._dragGradients&&this._dragGradients.length>0&&gx.GetCurrentGradient(l,this._dragGradients,((e,t,i)=>{e!==r._currentDragGradient&&(r._currentDrag1=r._currentDrag2,r._currentDrag2=t.getFactor(),r._currentDragGradient=e);const s=I(r._currentDrag1,r._currentDrag2,i);this._scaledDirection.scaleInPlace(1-s)})),this.isLocal&&r._localPosition?(r._localPosition.addInPlace(this._scaledDirection),w.TransformCoordinatesToRef(r._localPosition,this._emitterWorldMatrix,r.position)):r.position.addInPlace(this._scaledDirection),o&&t&&r._randomNoiseCoordinates1){const e=this._fetchR(r._randomNoiseCoordinates1.x,r._randomNoiseCoordinates1.y,t.width,t.height,o),i=this._fetchR(r._randomNoiseCoordinates1.z,r._randomNoiseCoordinates2.x,t.width,t.height,o),s=this._fetchR(r._randomNoiseCoordinates2.y,r._randomNoiseCoordinates2.z,t.width,t.height,o),a=U.Vector3[0],l=U.Vector3[1];a.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*i-1)*this.noiseStrength.y,(2*s-1)*this.noiseStrength.z),a.scaleToRef(n,l),r.direction.addInPlace(l)}this.gravity.scaleToRef(n,this._scaledGravity),r.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&gx.GetCurrentGradient(l,this._sizeGradients,((e,t,i)=>{e!==r._currentSizeGradient&&(r._currentSize1=r._currentSize2,r._currentSize2=t.getFactor(),r._currentSizeGradient=e),r.size=I(r._currentSize1,r._currentSize2,i)})),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&gx.GetCurrentGradient(l,this._colorRemapGradients,((e,t,i)=>{const s=I(e.factor1,t.factor1,i),n=I(e.factor2,t.factor2,i);r.remapData.x=s,r.remapData.y=n-s})),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&gx.GetCurrentGradient(l,this._alphaRemapGradients,((e,t,i)=>{const s=I(e.factor1,t.factor1,i),n=I(e.factor2,t.factor2,i);r.remapData.z=s,r.remapData.w=n-s}))),this._isAnimationSheetEnabled&&r.updateCellIndex(),r._inheritParticleInfoToSubEmitters(),r.age>=r.lifeTime&&(this._emitFromParticle(r),r._attachedSubEmitters&&(r._attachedSubEmitters.forEach((e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()})),r._attachedSubEmitters=null),this.recycleParticle(r),i&&s--)}}}serialize(e){throw new Error("Method not implemented.")}clone(e,t,i=!1){throw new Error("Method not implemented.")}_addFactorGradient(e,t,i,s){const r=new mx(t,i,s);e.push(r),e.sort(((e,t)=>e.gradientt.gradient?1:0))}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const s of e){if(s.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;const e=new Uint8Array(4*this._rawTextureWidth),t=$.Color3[0];for(let i=0;i{Y.LerpToRef(s.color,r.color,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255}))}this._rampGradientsTexture=io.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);const i=new _x(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);const s=new fx(e,t,i);return this._colorGradients.push(s),this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(const i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(const e of this._drawWrappers)if(e)for(const t of e)t?.dispose();this._drawWrappers=[]}_fetchR(e,t,i,s,r){return r[4*(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*s%s|0)*i)]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&8!==this.billboardMode&&9!==this.billboardMode||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);const e=this._engine,t=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*t),this._vertexBuffer=new $i(e,this._vertexData,!0,t);let i=0;const s=this._vertexBuffer.createVertexBuffer(Ki.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[Ki.PositionKind]=s,i+=3;const r=this._vertexBuffer.createVertexBuffer(Ki.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[Ki.ColorKind]=r,i+=4;const n=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=n,i+=1;const o=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,i+=2,this._isAnimationSheetEnabled){const e=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,i+=1}if(!this._isBillboardBased||8===this.billboardMode||9===this.billboardMode){const e=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,i+=3}if(this._useRampGradients){const e=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,i+=4}let a;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new $i(e,t,!1,2),a=this._spriteBuffer.createVertexBuffer("offset",0,2)}else a=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=a,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing)return void(this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3])));const e=[],t=[];let i=0;for(let s=0;s{this.start(0)}),e);else{if(this._started=!0,this._stopped=!1,this._actualFrame=0,this._preStart(),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){-1!==this.emitter?.getClassName().indexOf("Mesh")&&this.emitter.computeWorldMatrix(!0);const e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce((()=>{setTimeout((()=>{for(let t=0;t0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,this._postStop(e))}_postStop(e){}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,s){let r=e*this._vertexBufferSize;if(this._vertexData[r++]=t.position.x+this.worldOffset.x,this._vertexData[r++]=t.position.y+this.worldOffset.y,this._vertexData[r++]=t.position.z+this.worldOffset.z,this._vertexData[r++]=t.color.r,this._vertexData[r++]=t.color.g,this._vertexData[r++]=t.color.b,this._vertexData[r++]=t.color.a,this._vertexData[r++]=t.angle,this._vertexData[r++]=t.scale.x*t.size,this._vertexData[r++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[r++]=t.cellIndex),this._isBillboardBased)8!==this.billboardMode&&9!==this.billboardMode||(this._vertexData[r++]=t.direction.x,this._vertexData[r++]=t.direction.y,this._vertexData[r++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(w.TransformNormalToRef(e,this._emitterWorldMatrix,U.Vector3[0]),e=U.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[r++]=e.x,this._vertexData[r++]=e.y,this._vertexData[r++]=e.z}else{let e=t.direction;this.isLocal&&(w.TransformNormalToRef(e,this._emitterWorldMatrix,U.Vector3[0]),e=U.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[r++]=e.x,this._vertexData[r++]=e.y,this._vertexData[r++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[r++]=t.remapData.x,this._vertexData[r++]=t.remapData.y,this._vertexData[r++]=t.remapData.z,this._vertexData[r++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===s?s=this._epsilon:1===s&&(s=1-this._epsilon)),this._vertexData[r++]=i,this._vertexData[r++]=s)}_prepareParticle(e){}_update(e){if(this._alive=this._particles.length>0,this.emitter.position){const e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{const e=this.emitter;this._emitterWorldMatrix=B.Translation(e.x,e.y,e.z)}let t;this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i0){const e=P(this._actualFrame/this.targetStopDuration);gx.GetCurrentGradient(e,this._lifeTimeGradients,((i,s)=>{const r=i,n=s,o=r.getFactor(),a=n.getFactor(),l=(e-r.gradient)/(n.gradient-r.gradient);t.lifeTime=I(o,a,l)}))}else t.lifeTime=R(this.minLifeTime,this.maxLifeTime);const e=R(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),w.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=R(this.minSize,this.maxSize),t.scale.copyFromFloats(R(this.minScaleX,this.maxScaleX),R(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const e=this._actualFrame/this.targetStopDuration;gx.GetCurrentGradient(e,this._startSizeGradients,((e,i,s)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);const r=I(this._currentStartSize1,this._currentStartSize2,s);t.scale.scaleInPlace(r)}))}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=R(this.minAngularSpeed,this.maxAngularSpeed),t.angle=R(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),this._colorGradients&&0!==this._colorGradients.length)t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);else{const e=R(0,1);j.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new F(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new w(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new w(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const s=[Ki.PositionKind,Ki.ColorKind,"angle","offset","size"];return e&&s.push("cellIndex"),t||s.push("direction"),i&&s.push("remapData"),s}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["invView","view","projection","textureMask","translationPivot","eyePosition"];return jr(s),e&&s.push("particlesInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t,i=!0){if(this._scene&&($r(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&0!==this._scene.fogMode&&e.push("#define FOG")),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===ia.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case 2:e.push("#define BILLBOARDY");break;case 8:case 9:e.push("#define BILLBOARDSTRETCHED"),9===this.billboardMode&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case 7:e.push("#define BILLBOARDMODE_ALL")}i&&this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...xx._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&8!==this.billboardMode&&9!==this.billboardMode,this._useRampGradients)),e.push(...xx._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(Fi(e,this._imageProcessingConfigurationDefines),Li(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);const s=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let r=this._drawWrappers[s];r||(r=this._drawWrappers[s]=[]);let n=r[e];n||(n=new gr(this._engine),n.drawContext&&(n.drawContext.useInstancing=this._useInstancing),r[e]=n);const o=i.join("\n");if(n.defines!==o){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("particles",e,t,i,o),o)}return n}animate(e=!1){if(!this._started)return;if(!e&&this._scene){if(!this.isReady())return;if(this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}let t;if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this.manualEmitCount>-1)t=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const t=this._actualFrame/this.targetStopDuration;gx.GetCurrentGradient(t,this._emitRateGradients,((t,i,s)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=I(this._currentEmitRate1,this._currentEmitRate2,s)}))}t=e*this._scaledUpdateSpeed|0,this._newPartsExcess+=e*this._scaledUpdateSpeed-t}if(this._newPartsExcess>1&&(t+=0|this._newPartsExcess,this._newPartsExcess-=0|this._newPartsExcess),this._alive=!1,this._stopped?t=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(t),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){let e=0;for(let t=0;t=0&&(r.invertToRef(U.Matrix[0]),i.setMatrix("invView",U.Matrix[0])),void 0!==this._vertexArrayObject?this._scene?.forceWireframe?s.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,i):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,i)),this._engine.bindVertexArrayObject(this._vertexArrayObject,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?s.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBuffer:this._indexBuffer,i):s.bindBuffers(this._vertexBuffers,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null,i),this.useLogarithmicDepth&&this._scene&&Jr(n,i,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(i),e){case ia.BLENDMODE_ADD:s.setAlphaMode(1);break;case ia.BLENDMODE_ONEONE:s.setAlphaMode(6);break;case ia.BLENDMODE_STANDARD:s.setAlphaMode(2);break;case ia.BLENDMODE_MULTIPLY:s.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(i),this._useInstancing?this._scene?.forceWireframe?s.drawElementsType(6,0,10,this._particles.length):s.drawArraysType(7,0,4,this._particles.length):this._scene?.forceWireframe?s.drawElementsType(1,0,10*this._particles.length):s.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;const e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===ia.BLENDMODE_MULTIPLYADD?this._render(ia.BLENDMODE_MULTIPLY)+this._render(ia.BLENDMODE_ADD):this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}_onDispose(e=!1,t=!1){}dispose(e=!0,t=!1,i=!1){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._onDispose(t,i),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.clear(),this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}}var Tx;!function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(Tx||(Tx={}));class Sx{constructor(e){if(this.particleSystem=e,this.type=Tx.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=d("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;e?e instanceof w?e=e.clone():-1!==e.getClassName().indexOf("Mesh")&&(e=new(d("BABYLON.Mesh"))("",e.getScene()),e.isVisible=!1):e=new w;const t=new Sx(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){const t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,s=!1){throw ye("ParseParticle")}static Parse(e,t,i){const s=e.particleSystem,r=new Sx(Sx._ParseParticleSystem(s,t,i,!0));return r.type=e.type,r.inheritDirection=e.inheritDirection,r.inheritedVelocityAmount=e.inheritedVelocityAmount,r.particleSystem._isSubEmitter=!0,r}dispose(){this.particleSystem.dispose()}}function Ex(e,t){const i=new lx;return i.direction1=e,i.direction2=t,i}function bx(e=1,t=1){return new ax(e,t)}function Cx(e=1,t=1){return new hx(e,t)}function yx(e=1,t=new w(0,1,0),i=new w(0,1,0)){return new cx(e,t,i)}function Ax(e=1,t=1,i=1,s=0){return new nx(e,t,i,s)}function Rx(e=1,t=1,i=1,s=new w(0,1,0),r=new w(0,1,0)){return new ox(e,t,i,s,r)}function Ix(e=1,t=Math.PI/4){return new rx(e,t)}class Px extends xx{constructor(){super(...arguments),this._disposeEmitterOnDispose=!1,this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;const t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach((t=>{if(t.type===Tx.END){const i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}}))}}createPointEmitter(e,t){const i=Ex(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=bx(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=Cx(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new w(0,1,0),i=new w(0,1,0)){const s=yx(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=Ax(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new w(0,1,0),r=new w(0,1,0)){const n=Rx(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=Ix(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new sx;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}_prepareSubEmitterInternalArray(){this._subEmitters=new Array,this.subEmitters&&this.subEmitters.forEach((e=>{e instanceof Px?this._subEmitters.push([new Sx(e)]):e instanceof Sx?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)}))}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach((e=>{e.stop(!0)})),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;const e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_preStart(){this._prepareSubEmitterInternalArray(),this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=[])}_postStop(e){e&&this._stopSubEmitters()}_prepareParticle(e){if(this._subEmitters&&this._subEmitters.length>0){const t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach((t=>{if(t.type===Tx.ATTACHED){const i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}}))}}_onDispose(e=!1,t=!1){if(this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),e&&this.particles?.forEach((e=>{if(e._attachedSubEmitters)for(let t=e._attachedSubEmitters.length-1;t>=0;t-=1)e._attachedSubEmitters[t].dispose()})),t&&this.activeSubSystems)for(let e=this.activeSubSystems.length-1;e>=0;e-=1)this.activeSubSystems[e].dispose();if(this._subEmitters&&this._subEmitters.length){for(let e=0;e0?h.shaderOptions.defines.join("\n"):"";l=o.createEffectForParticles(h.shaderPath.fragmentElement,h.shaderOptions.uniforms,h.shaderOptions.samplers,t)}const c=new Px(n,r||e.capacity,t,l,e.isAnimationSheetEnabled);if(c.customShader=h,c._rootUrl=i,e.id&&(c.id=e.id),e.subEmitters){c.subEmitters=[];for(const s of e.subEmitters){const e=[];for(const r of s)e.push(Sx.Parse(r,t,i));c.subEmitters.push(e)}}return Px._Parse(e,c,t,i),e.textureMask&&(c.textureMask=j.FromArray(e.textureMask)),e.worldOffset&&(c.worldOffset=w.FromArray(e.worldOffset)),e.preventAutoStart&&(c.preventAutoStart=e.preventAutoStart),s||c.preventAutoStart||c.start(),c}serialize(e=!1){const t={};if(Px._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,t.worldOffset=this.worldOffset.asArray(),this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const s=[];for(const t of i)s.push(t.serialize(e));t.subEmitters.push(s)}}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){const i=t.emitter;e.emitterId=i.id}else{const i=t.emitter;e.emitter=i.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,Pe.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;const s=t.getColorGradients();if(s){e.colorGradients=[];for(const t of s){const i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}}const r=t.getRampGradients();if(r){e.rampGradients=[];for(const t of r){const i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}const n=t.getColorRemapGradients();if(n){e.colorRemapGradients=[];for(const t of n){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const t of o){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}}const a=t.getSizeGradients();if(a){e.sizeGradients=[];for(const t of a){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}}const l=t.getAngularSpeedGradients();if(l){e.angularSpeedGradients=[];for(const t of l){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}}const h=t.getVelocityGradients();if(h){e.velocityGradients=[];for(const t of h){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}}const c=t.getDragGradients();if(c){e.dragGradients=[];for(const t of c){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}}const u=t.getEmitRateGradients();if(u){e.emitRateGradients=[];for(const t of u){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}}const d=t.getStartSizeGradients();if(d){e.startSizeGradients=[];for(const t of d){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}}const p=t.getLifeTimeGradients();if(p){e.lifeTimeGradients=[];for(const t of p){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}}const f=t.getLimitVelocityGradients();if(f){e.limitVelocityGradients=[];for(const t of f){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}clone(e,t,i=!1){const s={...this._customWrappers};let r=null;const n=this._engine;if(n.createEffectForParticles&&null!=this.customShader){r=this.customShader;const e=r.shaderOptions.defines.length>0?r.shaderOptions.defines.join("\n"):"",t=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,e);s[0]?s[0].effect=t:this.setCustomEffect(t,0)}const o=this.serialize(i),a=Px.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=r,a._customWrappers=s,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,this.preventAutoStart||a.start(),a}}Px.BILLBOARDMODE_Y=2,Px.BILLBOARDMODE_ALL=7,Px.BILLBOARDMODE_STRETCHED=8,Px.BILLBOARDMODE_STRETCHED_LOCAL=9,Sx._ParseParticleSystem=Px.Parse;Ft.IncludesShadersStore.clipPlaneFragmentDeclaration2="#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nin float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nin float fClipDistance6;\n#endif\n";Ft.ShadersStore.gpuRenderParticlesPixelShader="precision highp float;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor;\n#include \n#include\n#include\n#include\n#include\n#include\nvoid main() {\n#include \nvec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha);\n#endif \n#include\n#include(color,gl_FragColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor);\n#endif\n#endif\n}\n";Ft.IncludesShadersStore.clipPlaneVertexDeclaration2="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;out float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;out float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;out float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;out float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;out float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;out float fClipDistance6;\n#endif\n";Ft.ShadersStore.gpuRenderParticlesVertexShader="precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset;\n#ifdef LOCAL\nuniform mat4 emitterWM;\n#endif\nattribute vec3 position;attribute float age;attribute float life;attribute vec3 size;\n#ifndef BILLBOARD\nattribute vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\nattribute float angle;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\nattribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW;\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#include\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;attribute vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture2D(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x;\n#ifdef BILLBOARD\nvec4 rotatedCorner;rotatedCorner.w=0.;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0));\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;\n#ifdef LOCAL\nvec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner;\n#else\nvec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner;\n#endif\nvPositionW=(invView*viewPosition).xyz;\n#endif\n#else\nvec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0);\n#endif\ngl_Position=projection*viewPosition;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#include\n}";class Mx extends ia{static get IsSupported(){if(!y.LastCreatedEngine)return!1;const e=y.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]),void 0,"GPUParticleSystemLinesIndexBuffer")}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}createPointEmitter(e,t){const i=Ex(e,t);return this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=bx(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=Cx(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new w(0,1,0),i=new w(0,1,0)){const s=yx(e,t,i);return this.particleEmitterType=s,s}createCylinderEmitter(e=1,t=1,i=1,s=0){const r=Ax(e,t,i,s);return this.particleEmitterType=r,r}createDirectedCylinderEmitter(e=1,t=1,i=1,s=new w(0,1,0),r=new w(0,1,0)){const n=Rx(e,t,i,s,r);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){const i=Ix(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,s){const r=new sx;return this.particleEmitterType=r,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=s,r}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady()||this._rebuildingAfterContextLost)return!1;if(this.blendMode!==Px.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else{if(!this._getWrapper(Px.BLENDMODE_MULTIPLY).effect.isReady())return!1;if(!this._getWrapper(Px.BLENDMODE_ADD).effect.isReady())return!1}return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";e?setTimeout((()=>{this.start(0)}),e):(this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop))}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){return this._customWrappers[e]?.effect??this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){return this._customWrappers[e]??this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new gr(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new g),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[1^this._targetIndex]}get indexBuffer(){return null}_removeGradientAndTexture(e,t,i){return super._removeGradientAndTexture(e,t,i),this._releaseBuffers(),this}addColorGradient(e,t){this._colorGradients||(this._colorGradients=[]);const i=new fx(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))}forceRefreshGradients(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()}removeColorGradient(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this}resetDrawCache(){for(const e in this._drawWrappers){const t=this._drawWrappers[e];t.drawContext?.reset()}}_addFactorGradient(e,t,i){const s=new mx(t,i);e.push(s),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){if(!e)return;i&&e.sort(((e,t)=>e.gradientt.gradient?1:0));const s=this;s[t]&&(s[t].dispose(),s[t]=null)}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,s=null,r=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this._rebuildingAfterContextLost=!1,this.onDisposeObservable=new g,this.onStoppedObservable=new g,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=B.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||y.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!d("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new(d("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!d("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new(d("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new gr(this._engine)},this._customWrappers[0].effect=s,this._drawWrappers={0:new gr(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),(t=t??{}).randomTextureSize||delete t.randomTextureSize;const n={capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize,...t},o=t;isFinite(o)&&(n.capacity=o),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=r,this.particleEmitterType=new sx;const a=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize);let l=[];for(let e=0;e0;)i.push(0)}const o=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),a=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new $i(t,a,!1,this._attributesStrideSize),this._buffer1=new $i(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new $i(t,o,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}_recreateUpdateEffect(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();let e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e)),this._platform.isUpdateBufferReady()}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(t?.effect)return t;const i=[];this.fillDefines(i,e);let s=this._drawWrappers[e];s||(s=new gr(this._engine),s.drawContext&&(s.drawContext.useInstancing=!0),this._drawWrappers[e]=s);const r=i.join("\n");if(s.defines!==r){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),s.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,r),r)}return s}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,s=!1){const r=[Ki.PositionKind,"age","life","size","angle"];return e||r.push(Ki.ColorKind),t&&r.push("cellIndex"),i||r.push("initialDirection"),s&&r.push("direction"),r.push("offset",Ki.UVKind),r}static _GetEffectCreationOptions(e=!1,t=!1,i=!1){const s=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return jr(s),e&&s.push("sheetInfos"),t&&s.push("logarithmicDepthConstant"),i&&(s.push("vFogInfos"),s.push("vFogColor")),s}fillDefines(e,t=0,i=!0){if(this._scene&&($r(this,this._scene,e),this.applyFog&&this._scene.fogEnabled&&this._scene.fogMode!==ks.FOGMODE_NONE&&e.push("#define FOG")),t===Px.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case Px.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case Px.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case Px.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),i&&this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...Mx._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===Px.BILLBOARDMODE_STRETCHED)),e.push(...Mx._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth,this.applyFog)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(Bi.PrepareUniforms(e,this._imageProcessingConfigurationDefines),Bi.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:this._scene?.getAnimationRatio()||1),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){const i=this[t];if(!e||!e.length||i)return;const s=new Float32Array(this._rawTextureWidth);for(let t=0;t{s[t]=G.Lerp(e.factor1,i.factor1,r)}))}this[t]=io.CreateRTexture(s,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;const e=new Uint8Array(4*this._rawTextureWidth),t=$.Color4[0];for(let i=0;i{j.LerpToRef(s.color1,r.color1,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a}))}this._colorGradientsTexture=io.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){const i=this._getWrapper(e),s=i.effect;this._engine.enableEffect(i);const r=this._scene?.getViewMatrix()||B.IdentityReadOnly;if(s.setMatrix("view",r),s.setMatrix("projection",this.defaultProjectionMatrix??this._scene.getProjectionMatrix()),s.setTexture("diffuseSampler",this.particleTexture),s.setVector2("translationPivot",this.translationPivot),s.setVector3("worldOffset",this.worldOffset),this.isLocal&&s.setMatrix("emitterWM",t),this._colorGradientsTexture?s.setTexture("colorGradientSampler",this._colorGradientsTexture):s.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const e=this.particleTexture.getBaseSize();s.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const e=this._scene.activeCamera;s.setVector3("eyePosition",e.globalPosition)}const n=s.defines;if(this._scene&&(Kr(s,this,this._scene),this.applyFog&&en(this._scene,void 0,s)),n.indexOf("#define BILLBOARDMODE_ALL")>=0){const e=r.clone();e.invert(),s.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&Jr(n,s,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(s),e){case Px.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case Px.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case Px.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case Px.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,s,this._scene?.forceWireframe?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(s),this._scene?.forceWireframe?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),this._scene?.forceWireframe&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer)return;if(!this._recreateUpdateEffect()||this._rebuildingAfterContextLost)return;if(!e)if(this.emitter.position)e=this.emitter.getWorldMatrix();else{const t=this.emitter;e=U.Matrix[0],B.TranslationToRef(t.x,t.y,t.z,e)}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,2===this._targetIndex&&(this._targetIndex=0);const t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){if(!this._started)return 0;if(!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e1){const e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount+=e}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;let i;if(this.emitter.position)i=this.emitter.getWorldMatrix();else{const e=this.emitter;i=U.Matrix[0],B.TranslationToRef(e.x,e.y,e.z,i)}const s=this._engine;this.updateInAnimate||this._update(i);let r=0;return e||t||(s.setState(!1),this.forceDepthWrite&&s.setDepthWrite(!0),r=this.blendMode===Px.BLENDMODE_MULTIPLYADD?this._render(Px.BLENDMODE_MULTIPLY,i)+this._render(Px.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),r}rebuild(){const e=()=>{this._recreateUpdateEffect()&&this._platform.isUpdateBufferReady()?(this._initialize(!0),this._rebuildingAfterContextLost=!1):setTimeout(e,10)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),this._rebuildingAfterContextLost=!0,e()}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(const e in this._drawWrappers)this._drawWrappers[e].dispose();if(this._drawWrappers={},this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e0?r.shaderOptions.defines.join("\n"):"";s[0]=n.createEffectForParticles(r.shaderPath.fragmentElement,r.shaderOptions.uniforms,r.shaderOptions.samplers,e,void 0,void 0,void 0,this)}const o=this.serialize(i),a=Mx.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=r,a._customWrappers=s,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,a}serialize(e=!1){const t={};return Px._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,s=!1,r){const n=e.name;let o,a;t instanceof si?o=t:(a=t,o=a.getEngine());const l=new Mx(n,{capacity:r||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(l._rootUrl=i,e.customShader&&o.createEffectForParticles){const t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",s=o.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,l);l.setCustomEffect(s,0),l.customShader=t}return e.id&&(l.id=e.id),e.activeParticleCount&&(l.activeParticleCount=e.activeParticleCount),Px._Parse(e,l,t,i),e.preventAutoStart&&(l.preventAutoStart=e.preventAutoStart),s||l.preventAutoStart||l.start(),l}}class Dx{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1);for(const t of this.systems)t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};const s=nc("emitterSphere",{diameter:e.diameter,segments:e.segments},i);s.renderingGroupId=t;const r=new dh("emitterSphereMaterial",i);r.emissiveColor=e.color,s.material=r;for(const e of this.systems)e.emitter=s;this._emitterNode=s}start(e){for(const t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(const e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){const t={systems:[]};for(const i of this.systems)t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,s){const r=new Dx,n=this.BaseAssetsUrl+"/textures/";t=t||y.LastCreatedScene;for(const o of e.systems)r.systems.push(i?Mx.Parse(o,t,n,!0,s):Px.Parse(o,t,n,!0,s));if(e.emitter){const i=e.emitter.options;"Sphere"===e.emitter.kind&&r.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:Y.FromArray(i.color)},e.emitter.renderingGroupId,t)}return r}}Dx.BaseAssetsUrl="https://assets.babylonjs.com/particles";class Ox{static CreateDefault(e,t=500,i,s=!1){let r;return r=s?new Mx("default system",{capacity:t},i):new Px("default system",t,i),r.emitter=e,r.particleTexture=new Zn("https://assets.babylonjs.com/textures/flare.png",r.getScene()),r.createConeEmitter(.1,Math.PI/4),r.color1=new j(1,1,1,1),r.color2=new j(1,1,1,1),r.colorDead=new j(1,1,1,0),r.minSize=.1,r.maxSize=.1,r.minEmitPower=2,r.maxEmitPower=2,r.updateSpeed=1/60,r.emitRate=30,r}static CreateAsync(e,t,i=!1,s){t||(t=y.LastCreatedScene);const r={};return t.addPendingData(r),new Promise(((n,o)=>{if(i&&!Mx.IsSupported)return t.removePendingData(r),o("Particle system with GPU is not supported.");Ii.LoadFile(`${Ox.BaseAssetsUrl}/systems/${e}.json`,(e=>{t.removePendingData(r);const o=JSON.parse(e.toString());return n(Dx.Parse(o,t,i,s))}),void 0,void 0,void 0,(()=>(t.removePendingData(r),o(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`))))}))}static ExportSet(e){const t=new Dx;for(const i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,s=!1,r="",n){return new Promise(((o,a)=>{const l=new Ne;l.addEventListener("readystatechange",(()=>{if(4==l.readyState)if(200==l.status){const t=JSON.parse(l.responseText);let a;a=s?Mx.Parse(t,i,r,!1,n):Px.Parse(t,i,r,!1,n),e&&(a.name=e),o(a)}else a("Unable to load the particle system")})),l.open("GET",t),l.send()}))}static ParseFromSnippetAsync(e,t,i=!1,s="",r){if("_BLANK"===e){const e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise(((n,o)=>{const a=new Ne;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.particleSystem);let h;h=i?Mx.Parse(l,t,s,!1,r):Px.Parse(l,t,s,!1,r),h.snippetId=e,n(h)}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}}var Nx,wx,Fx,Lx,Bx,Vx,Ux,kx,Gx,zx,Wx,Hx,Xx,Yx,jx,$x,Kx,qx,Qx,Zx,Jx;Ox.BaseAssetsUrl=Dx.BaseAssetsUrl,Ox.SnippetUrl="https://snippet.babylonjs.com",Ox.CreateFromSnippetAsync=Ox.ParseFromSnippetAsync,p.AddParser(ts.NAME_PARTICLESYSTEM,((e,t,i,s)=>{const r=p.GetIndividualParser(ts.NAME_PARTICLESYSTEM);if(r&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,o=e.particleSystems.length;ne.activeParticleCount?Mx.Parse(e,t,i):Px.Parse(e,t,i))),si.prototype.createEffectForParticles=function(e,t=[],i=[],s="",r,n,o,a){let l=[],h=[];const c=[];return a?a.fillUniformsAttributesAndSamplerNames(h,l,c):(l=Px._GetAttributeNamesOrOptions(),h=Px._GetEffectCreationOptions()),-1===s.indexOf(" BILLBOARD")&&(s+="\n#define BILLBOARD\n"),a?.isAnimationSheetEnabled&&-1===s.indexOf(" ANIMATESHEET")&&(s+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:a?.vertexShaderName??"particles",fragmentElement:e},l,h.concat(t),c.concat(i),s,r,n,o)},Un.prototype.getEmittedParticleSystems=function(){const e=[];for(let t=0;t{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)}))))},enumerable:!0,configurable:!0}),Wr.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},Wr.prototype.applyImpulse=function(e,t){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(e,t),this):this},Wr.prototype.setPhysicsLinkWith=function(e,t,i,s){return this.physicsImpostor&&e.physicsImpostor?(this.physicsImpostor.createJoint(e.physicsImpostor,mo.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:s}),this):this};class eT{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw ye("")}constructor(e,t=eT.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new w(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){const t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,s){this._physicsPlugin.raycast(e,t,i,s)}raycast(e,t,i){const s=new V_;return this._physicsPlugin.raycast(e,t,s,i),s}}(Zx=wx||(wx={}))[Zx.FREE=0]="FREE",Zx[Zx.LIMITED=1]="LIMITED",Zx[Zx.LOCKED=2]="LOCKED",(Qx=Fx||(Fx={}))[Qx.LINEAR_X=0]="LINEAR_X",Qx[Qx.LINEAR_Y=1]="LINEAR_Y",Qx[Qx.LINEAR_Z=2]="LINEAR_Z",Qx[Qx.ANGULAR_X=3]="ANGULAR_X",Qx[Qx.ANGULAR_Y=4]="ANGULAR_Y",Qx[Qx.ANGULAR_Z=5]="ANGULAR_Z",Qx[Qx.LINEAR_DISTANCE=6]="LINEAR_DISTANCE",(qx=Lx||(Lx={}))[qx.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",qx[qx.DISTANCE=2]="DISTANCE",qx[qx.HINGE=3]="HINGE",qx[qx.SLIDER=4]="SLIDER",qx[qx.LOCK=5]="LOCK",qx[qx.PRISMATIC=6]="PRISMATIC",qx[qx.SIX_DOF=7]="SIX_DOF",(Kx=Bx||(Bx={}))[Kx.SPHERE=0]="SPHERE",Kx[Kx.CAPSULE=1]="CAPSULE",Kx[Kx.CYLINDER=2]="CYLINDER",Kx[Kx.BOX=3]="BOX",Kx[Kx.CONVEX_HULL=4]="CONVEX_HULL",Kx[Kx.CONTAINER=5]="CONTAINER",Kx[Kx.MESH=6]="MESH",Kx[Kx.HEIGHTFIELD=7]="HEIGHTFIELD",($x=Vx||(Vx={}))[$x.NONE=0]="NONE",$x[$x.VELOCITY=1]="VELOCITY",$x[$x.POSITION=2]="POSITION",(jx=Ux||(Ux={})).COLLISION_STARTED="COLLISION_STARTED",jx.COLLISION_CONTINUED="COLLISION_CONTINUED",jx.COLLISION_FINISHED="COLLISION_FINISHED",jx.TRIGGER_ENTERED="TRIGGER_ENTERED",jx.TRIGGER_EXITED="TRIGGER_EXITED",(Yx=kx||(kx={}))[Yx.STATIC=0]="STATIC",Yx[Yx.ANIMATED=1]="ANIMATED",Yx[Yx.DYNAMIC=2]="DYNAMIC",(Xx=Gx||(Gx={}))[Xx.SIMULATION_CONTROLLED=0]="SIMULATION_CONTROLLED",Xx[Xx.ALWAYS_ACTIVE=1]="ALWAYS_ACTIVE",Xx[Xx.ALWAYS_INACTIVE=2]="ALWAYS_INACTIVE",(Jx=zx||(zx={}))[Jx.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",Jx[Jx.MINIMUM=1]="MINIMUM",Jx[Jx.MAXIMUM=2]="MAXIMUM",Jx[Jx.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",Jx[Jx.MULTIPLY=4]="MULTIPLY",ks.prototype.getPhysicsEngine=function(){return this._physicsEngine},ks.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(ts.NAME_PHYSICSENGINE);i||(i=new tT(this),this._addComponent(i));try{if(t&&1!==t?.getPluginVersion()){if(2!==t?.getPluginVersion())throw new Error("Unsupported Physics plugin version.");this._physicsEngine=new eT(e,t)}else this._physicsEngine=new U_(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return J.Error(e.message),!1}},ks.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},ks.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},ks.prototype.deleteCompoundImpostor=function(e){const t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},ks.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){const t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class tT{constructor(e){this.name=ts.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new g,this.scene.onAfterPhysicsObservable=new g,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?1e3*this.scene._physicsEngine.getTimeStep():1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(Ur.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)}))))},enumerable:!0,configurable:!0}),Ur.prototype.getPhysicsBody=function(){return this.physicsBody},Ur.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this},Ur.prototype.applyAngularImpulse=function(e){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyAngularImpulse(e),this};class iT{static GetContactPointToRef(e,t,i,s,r){const n=e.getScene().getPhysicsEngine(),o=n?.getPluginVersion();if(1===o){const r=new ao(t,i).intersectsMesh(e);if(r.hit&&r.pickedPoint)return s.copyFrom(r.pickedPoint),!0}else if(2===o)return e.physicsBody.getObjectCenterWorldToRef(s,r),!0;return!1}static HasAppliedForces(e,t){return e.getMotionType(t)===kx.STATIC||0===(e.getMassProperties(t)?.mass??0)||0===e.transformNode?.getTotalVertices()}static IsInsideCylinder(e,t,i,s){const r=U.Vector3[0];return e.subtractToRef(t,r),Math.abs(r.x)<=i&&Math.abs(r.z)<=i&&r.y>=0&&r.y<=s}}class sT{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=w.Zero(),this._originDirection=w.Zero(),this._cylinderPosition=w.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new nT,...this._options},this._origin.addToRef(new w(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new w(0,this._options.height,0),this._originTop),this._options.updraftMode===Hx.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout((()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)}),0))}_getHitData(e,t){let i;i=this._options.updraftMode===Hx.Perpendicular?this._originDirection:e.subtract(this._originTop);const s=w.Distance(this._origin,e),r=-1*this._options.strength,n=i.multiplyByFloats(r,r,r);t.force.copyFrom(n),t.contactPoint.copyFrom(e),t.distanceFromOrigin=s}_getBodyHitData(e,t,i){if(iT.HasAppliedForces(e))return!1;const s=e.getObjectCenterWorld(i);return!!iT.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(s,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const s=e.getObjectCenter();return this._getHitData(s,t),!0}_tick(){const e=sT._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=Qh("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))}}sT._HitData={force:new w,contactPoint:new w,distanceFromOrigin:0};class rT{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=w.Zero(),this._cylinderPosition=w.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options={...new oT,...this._options},this._origin.addToRef(new w(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new w(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout((()=>{this._dataFetched||this._cylinder.dispose()}),0))}_getHitData(e,t,i){const s=rT._OriginOnPlane;s.set(this._origin.x,t.y,this._origin.z);const r=U.Vector3[0];t.subtractToRef(s,r);const n=U.Vector3[1];if(!iT.GetContactPointToRef(e,s,r,n,i.instanceIndex))return!1;const o=w.Distance(n,s)/this._options.radius,a=U.Vector3[2];let l,h,c;if(n.normalizeToRef(a),o>this._options.centripetalForceThreshold&&a.negateInPlace(),o>this._options.centripetalForceThreshold)l=a.x*this._options.centripetalForceMultiplier,h=a.y*this._options.updraftForceMultiplier,c=a.z*this._options.centripetalForceMultiplier;else{const e=w.Cross(s,t).normalize();l=(e.x+a.x)*this._options.centrifugalForceMultiplier,h=this._originTop.y*this._options.updraftForceMultiplier,c=(e.z+a.z)*this._options.centrifugalForceMultiplier}const u=U.Vector3[3];return u.set(l,h,c),u.scaleInPlace(this._options.strength),i.force.copyFrom(u),i.contactPoint.copyFrom(t),i.distanceFromOrigin=o,!0}_getBodyHitData(e,t,i){if(iT.HasAppliedForces(e,i))return!1;const s=e.transformNode,r=e.getObjectCenterWorld(i);return!!iT.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(s,r,t))}_getImpostorHitData(e,t){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const s=e.getObjectCenter();return this._getHitData(i,s,t),!0}_tick(){const e=rT._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=Qh("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}}rT._OriginOnPlane=w.Zero(),rT._HitData={force:new w,contactPoint:new w,distanceFromOrigin:0};class nT{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=Hx.Center}}class oT{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}!function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"}(Wx||(Wx={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(Hx||(Hx={}));Ft.ShadersStore.blackAndWhitePixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}";class aT extends Ko{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,s,r,n){super(e,"blackAndWhite",["degree"],null,t,i,s,r,n),this.degree=1,this.onApplyObservable.add((e=>{e.setFloat("degree",this.degree)}))}static _Parse(e,t,i,s){return Pe.Parse((()=>new aT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}ae([pe()],aT.prototype,"degree",void 0),u("BABYLON.BlackAndWhitePostProcess",aT);class lT{constructor(e,t,i,s){this._name=t,this._singleInstance=s||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let e=0;e{const t=s.attachPostProcess(e);this._indicesForCamera[r].push(t)})),this._cameras[r]||(this._cameras[r]=s)}}_detachCameras(e){const t=Ii.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)})),this._cameras[s]&&(this._cameras[s]=null),delete this._indicesForCamera[s]}}_enable(e){const t=Ii.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)}))}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}Ft.ShadersStore.extractHighlightsPixelShader="#include\nvarying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}";class hT extends Ko{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,s,r,n,null,o,void 0,null,a),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add((e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess),e.setFloat("threshold",Math.pow(this.threshold,v)),e.setFloat("exposure",this._exposure)}))}}ae([pe()],hT.prototype,"threshold",void 0),u("BABYLON.ExtractHighlightsPostProcess",hT);Ft.ShadersStore.bloomMergePixelShader="uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); }\n";class cT extends Ko{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,s,r,n,o,a,l,h=0,c=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],r,n,o,a,l,null,h,void 0,null,!0),this.weight=1,this.weight=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)})),c||this.updateEffect()}}ae([pe()],cT.prototype,"weight",void 0),u("BABYLON.BloomMergePostProcess",cT);class uT extends lT{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,s,r=0,n=!1){super(e.getEngine(),"bloom",(()=>this._effects),!0),this._bloomScale=t,this._effects=[],this._downscale=new hT("highlights",1,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._blurX=new Jp("horizontal blur",new N(1,0),10,t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new Jp("vertical blur",new N(0,1),10,t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=s,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new cT("bloomMerge",this._downscale,this._blurY,i,t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)}))}static _Parse(e,t,i,s){return Pe.Parse((()=>new dT(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,s)}}ae([pe()],dT.prototype,"aberrationAmount",void 0),ae([pe()],dT.prototype,"radialIntensity",void 0),ae([pe()],dT.prototype,"direction",void 0),ae([pe()],dT.prototype,"centerPosition",void 0),ae([pe()],dT.prototype,"screenWidth",void 0),ae([pe()],dT.prototype,"screenHeight",void 0),u("BABYLON.ChromaticAberrationPostProcess",dT);Ft.ShadersStore.circleOfConfusionPixelShader="uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float depth=texture2D(depthSampler,vUV).r;\n#define CUSTOM_COC_DEPTH\nfloat pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; \n#define CUSTOM_COC_PIXELDISTANCE\nfloat coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);}\n";class pT extends Ko{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,s,r,n,o,a=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,s,r,n,o,null,a,void 0,null,l),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add((e=>{if(!this._depthTexture)return void J.Warn("No depth texture set on CircleOfConfusionPostProcess");e.setTexture("depthSampler",this._depthTexture);const t=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",t);const i=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",i.minZ,i.maxZ-i.minZ)}))}set depthTexture(e){this._depthTexture=e}}ae([pe()],pT.prototype,"lensSize",void 0),ae([pe()],pT.prototype,"fStop",void 0),ae([pe()],pT.prototype,"focusDistance",void 0),ae([pe()],pT.prototype,"focalLength",void 0),u("BABYLON.CircleOfConfusionPostProcess",pT);Ft.ShadersStore.colorCorrectionPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D colorTable; \nvarying vec2 vUV;const float SLICE_COUNT=16.0; \nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}";class fT extends Ko{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"colorCorrection",null,["colorTable"],i,s,r,n,o);const a=s?.getScene()||null;this._colorTableTexture=new Zn(t,a,!0,!1,Zn.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=Zn.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=Zn.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,s){return Pe.Parse((()=>new fT(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}ae([pe()],fT.prototype,"colorTableUrl",void 0),u("BABYLON.ColorCorrectionPostProcess",fT);Ft.ShadersStore.convolutionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9];\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}";class _T extends Ko{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,s,r,n,o,a=0){super(e,"convolution",["kernel","screenSize"],null,i,s,r,n,o,null,a),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,s){return Pe.Parse((()=>new _T(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType)),e,i,s)}}_T.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],_T.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],_T.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],_T.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],_T.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],_T.GaussianKernel=[0,1,0,1,1,1,0,1,0],ae([pe()],_T.prototype,"kernel",void 0),u("BABYLON.ConvolutionPostProcess",_T);class mT extends Jp{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,s,r,n,o,a=null,l=Zn.BILINEAR_SAMPLINGMODE,h,c,u=0,d=!1,p=5){super(e,i,s,r,n,2,h,c,u,"#define DOF 1\n",d,p),this.direction=i,this.externalTextureSamplerBinding=!!a,this.onApplyObservable.add((e=>{null!=a&&e.setTextureFromPostProcess("textureSampler",a),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)}))}}ae([pe()],mT.prototype,"direction",void 0),u("BABYLON.DepthOfFieldBlurPostProcess",mT);Ft.ShadersStore.depthOfFieldMergePixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;\n#if BLUR_LEVEL==0\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);}\n#endif\n#if BLUR_LEVEL==2\nif(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);}\n#endif\n}\n";class gT extends Ko{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,s,r,n,o,a,l,h=0,c=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],r,n,o,a,l,null,h,void 0,null,!0),this._blurSteps=s,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),s.forEach(((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(s.length-i-1),t)}))})),c||this.updateEffect()}updateEffect(e=null,t=null,i=null,s,r,n){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,s,r,n)}}var vT;!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(vT||(vT={}));class xT extends lT{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=vT.Low,s=0,r=!1){super(e.getEngine(),"depth of field",(()=>this._effects),!0),this._effects=[];const n=e.getEngine(),o=n.isWebGPU||n.version>1?6:5;this._circleOfConfusion=new pT("circleOfConfusion",t,1,null,Zn.BILINEAR_SAMPLINGMODE,n,!1,s,r),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let a=1,l=15;switch(i){case vT.High:a=3,l=51;break;case vT.Medium:a=2,l=31;break;default:l=15,a=1}const h=l/Math.pow(2,a-1);let c=1;for(let t=0;tnew TT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}u("BABYLON.DisplayPassPostProcess",TT);Ft.ShadersStore.filterPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}";class ST extends Ko{getClassName(){return"FilterPostProcess"}constructor(e,t,i,s,r,n,o){super(e,"filter",["kernelMatrix"],null,i,s,r,n,o),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,s){return Pe.Parse((()=>new ST(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}ae([Ee()],ST.prototype,"kernelMatrix",void 0),u("BABYLON.FilterPostProcess",ST);Ft.ShadersStore.fxaaPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan)\n{lumaN=lumaW;}\nif (!horzSpan) \n{lumaS=lumaE;}\nif (horzSpan) \n{lengthSign=texelSize.y;}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN)\n{lengthSign=-lengthSign;}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) \n{posB.x+=lengthSign*0.5;}\nif (horzSpan)\n{posB.y+=lengthSign*0.5;}\nvec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) \n{lumaNN=lumaSS;}\nfloat gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) \n{posN.x-=offNP.x*3.0;}\nif (!doneN) \n{posN.y-=offNP.y*3.0;}\nbool doneNP=(!doneN) || (!doneP);if (!doneP) \n{posP.x+=offNP.x*3.0;}\nif (!doneP)\n{posP.y+=offNP.y*3.0;}\nif (doneNP)\n{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;}\nfloat dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan)\n{dstN=posM.y-posN.y;}\nif (!horzSpan) \n{dstP=posP.y-posM.y;}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{const t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)}))}_getDefines(){const e=this.getEngine();return e&&e.extractDriverInfo().toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,s){return Pe.Parse((()=>new ET(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}u("BABYLON.FxaaPostProcess",ET);Ft.ShadersStore.grainPixelShader="#include\nuniform sampler2D textureSampler; \nuniform float intensity;uniform float animatedSeed;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}";class bT extends Ko{getClassName(){return"GrainPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,s,r,n,null,o,void 0,null,a),this.intensity=30,this.animated=!1,this.onApplyObservable.add((e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)}))}static _Parse(e,t,i,s){return Pe.Parse((()=>new bT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}ae([pe()],bT.prototype,"intensity",void 0),ae([pe()],bT.prototype,"animated",void 0),u("BABYLON.GrainPostProcess",bT);Ft.ShadersStore.highlightsPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }";Ft.ShadersStore.imageProcessingPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;}";class CT extends Ko{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null;const t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){const i=t.scenes;e=i[i.length-1]}else e=y.LastCreatedScene;this._imageProcessingConfiguration=e?e.imageProcessingConfiguration:new Bi}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateParameters()}))),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,s,r,n,o=0,a){super(e,"imageProcessing",[],[],t,i,s,r,n,null,o,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:0,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},a?(a.applyByPostProcess=!0,this._attachImageProcessingConfiguration(a,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const t in this._defines){const i=this._defines[t];switch(typeof i){case"number":case"string":e+=`#define ${t} ${i};\n`;break;default:i&&(e+=`#define ${t};\n`)}}const t=["textureSampler"],i=["scale"];Bi&&(Bi.PrepareSamplers(t,this._defines),Bi.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}ae([pe()],CT.prototype,"_fromLinearSpace",void 0);Ft.IncludesShadersStore.mrtFragmentDeclaration="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n";Ft.ShadersStore.geometryPixelShader="#extension GL_EXT_draw_buffers : require\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\nprecision highp float;\n#ifdef BUMP\nvarying mat4 vWorldView;varying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nvarying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#ifdef NEED_UV\nvarying vec2 vUV;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIVITY)\n#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nuniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV;\n#endif\n#ifdef ALBEDOTEXTURE\nvarying vec2 vAlbedoUV;uniform sampler2D albedoSampler;\n#endif\n#ifdef REFLECTIVITYCOLOR\nuniform vec3 reflectivityColor;\n#endif\n#ifdef ALBEDOCOLOR\nuniform vec3 albedoColor;\n#endif\n#ifdef METALLIC\nuniform float metallic;\n#endif\n#if defined(ROUGHNESS) || defined(GLOSSINESS)\nuniform float glossiness;\n#endif\n#endif\n#if defined(ALPHATEST) && defined(NEED_UV)\nuniform sampler2D diffuseSampler;\n#endif\n#include\n#include[RENDER_TARGET_COUNT]\n#include\n#include\n#include\nvoid main() {\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nvec3 normalOutput;\n#ifdef BUMP\nvec3 normalW=normalize(vNormalW);\n#include\n#ifdef NORMAL_WORLDSPACE\nnormalOutput=normalW;\n#else\nnormalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0)));\n#endif\n#else\nnormalOutput=normalize(vNormalV);\n#endif\n#ifdef ENCODE_NORMAL\nnormalOutput=normalOutput*0.5+0.5;\n#endif\n#ifdef PREPASS\n#ifdef PREPASS_DEPTH\ngl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n#endif\n#ifdef PREPASS_NORMAL\ngl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0);\n#endif\n#else\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0);\n#endif\n#ifdef POSITION\ngl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);\n#endif\n#ifdef REFLECTIVITY\nvec4 reflectivity=vec4(0.0,0.0,0.0,1.0);\n#ifdef METALLICWORKFLOW\nfloat metal=1.0;float roughness=1.0;\n#ifdef ORMTEXTURE\nmetal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g;\n#endif\n#ifdef METALLIC\nmetal*=metallic;\n#endif\n#ifdef ROUGHNESS\nroughness*=(1.0-glossiness); \n#endif\nreflectivity.a-=roughness;vec3 color=vec3(1.0);\n#ifdef ALBEDOTEXTURE\ncolor=texture2D(albedoSampler,vAlbedoUV).rgb;\n#ifdef GAMMAALBEDO\ncolor=toLinearSpace(color);\n#endif\n#endif\n#ifdef ALBEDOCOLOR\ncolor*=albedoColor.xyz;\n#endif\nreflectivity.rgb=mix(vec3(0.04),color,metal);\n#else\n#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nreflectivity=texture2D(reflectivitySampler,vReflectivityUV);\n#ifdef GAMMAREFLECTIVITYTEXTURE\nreflectivity.rgb=toLinearSpace(reflectivity.rgb);\n#endif\n#else \n#ifdef REFLECTIVITYCOLOR\nreflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0;\n#endif\n#endif\n#ifdef GLOSSINESSS\nreflectivity.a*=glossiness; \n#endif\n#endif\ngl_FragData[REFLECTIVITY_INDEX]=reflectivity;\n#endif\n}\n";Ft.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;";Ft.IncludesShadersStore.geometryUboDeclaration="#include\n";Ft.ShadersStore.geometryVertexShader="precision highp float;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include<__decl__geometryVertex>\n#include\nattribute vec3 position;attribute vec3 normal;\n#ifdef NEED_UV\nvarying vec2 vUV;\n#ifdef ALPHATEST\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef BUMP\nuniform mat4 bumpMatrix;varying vec2 vBumpUV;\n#endif\n#ifdef REFLECTIVITY\nuniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef BUMP\nvarying mat4 vWorldView;\n#endif\n#ifdef BUMP\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nuniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include\n#include\nvec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0));\n#ifdef BUMP\nvWorldView=view*finalWorld;vNormalW=normalUpdated;\n#else\n#ifdef NORMAL_WORLDSPACE\nvNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#else\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));\n#endif\n#endif\nvViewPos=view*worldPos;\n#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n#if defined(POSITION) || defined(BUMP)\nvPositionW=worldPos.xyz/worldPos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#include\n#ifdef NEED_UV\n#ifdef UV1\n#if defined(ALPHATEST) && defined(ALPHATEST_UV1)\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#else\nvUV=uv;\n#endif\n#ifdef BUMP_UV1\nvBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV1\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV1\nvAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#endif\n#ifdef UV2\n#if defined(ALPHATEST) && defined(ALPHATEST_UV2)\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#else\nvUV=uv2;\n#endif\n#ifdef BUMP_UV2\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV2\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV2\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#endif\n#include\n}\n";const yT=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];jr(yT);class AT{get normalsAreUnsigned(){return this._normalsAreUnsigned}_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add((()=>{})))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===AT.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===AT.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===AT.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===AT.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===AT.NORMAL_TEXTURE_TYPE&&(this._normalIndex=t)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case AT.POSITION_TEXTURE_TYPE:return this._positionIndex;case AT.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case AT.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case AT.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case AT.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return-1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return"object"==typeof this._ratioOrDimensions?1:this._ratioOrDimensions}constructor(e,t=1,i=15,s){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new j(0,0,0,0),this._clearDepthColor=new j(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=s||{},AT._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const s=[],r=[Ki.PositionKind,Ki.NormalKind],n=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(s.push("#define ALPHATEST"),s.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&th.BumpTextureEnabled&&(s.push("#define BUMP"),s.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(i.metallicRoughnessTexture&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!=i.metallic&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),t=!0),null!=i.roughness&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),t=!0),t&&(i.baseTexture&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),e=!0),i.baseColor&&s.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(i.specularGlossinessTexture?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor&&s.push("#define REFLECTIVITYCOLOR"),null!=i.glossiness&&s.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(i.metallicTexture&&(s.push("#define ORMTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),s.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!=i.metallic&&(s.push("#define METALLIC"),s.push("#define METALLICWORKFLOW"),t=!0),null!=i.roughness&&(s.push("#define ROUGHNESS"),s.push("#define METALLICWORKFLOW"),t=!0),t?(i.albedoTexture&&(s.push("#define ALBEDOTEXTURE"),s.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&s.push("#define GAMMAALBEDO"),e=!0),i.albedoColor&&s.push("#define ALBEDOCOLOR")):(i.reflectivityTexture?(s.push("#define SPECULARGLOSSINESSTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):i.reflectivityColor&&s.push("#define REFLECTIVITYCOLOR"),null!=i.microSurface&&s.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(i.specularTexture&&(s.push("#define REFLECTIVITYTEXTURE"),s.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&s.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),i.specularColor&&s.push("#define REFLECTIVITYCOLOR"))}e&&(s.push("#define NEED_UV"),n.isVerticesDataPresent(Ki.UVKind)&&(r.push(Ki.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(Ki.UV2Kind)&&(r.push(Ki.UV2Kind),s.push("#define UV2")))}this._linkedWithPrePass&&(s.push("#define PREPASS"),-1!==this._depthIndex&&(s.push("#define DEPTH_INDEX "+this._depthIndex),s.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(s.push("#define NORMAL_INDEX "+this._normalIndex),s.push("#define PREPASS_NORMAL"))),this._enablePosition&&(s.push("#define POSITION"),s.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(s.push("#define VELOCITY"),s.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(n)&&s.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(s.push("#define REFLECTIVITY"),s.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&s.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&s.push("#define ENCODE_NORMAL"),n.useBones&&n.computeBonesUsingShaders&&n.skeleton?(r.push(Ki.MatricesIndicesKind),r.push(Ki.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(Ki.MatricesIndicesExtraKind),r.push(Ki.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BONETEXTURE "+n.skeleton.isUsingTextureForMatrices),s.push("#define BonesPerMesh "+(n.skeleton.bones.length+1))):(s.push("#define NUM_BONE_INFLUENCERS 0"),s.push("#define BONETEXTURE false"),s.push("#define BonesPerMesh 0"));const o=n.morphTargetManager;let a=0;o&&(a=o.numMaxInfluencers||o.numInfluencers,a>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+a),o.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),tn(r,n,a))),t&&(s.push("#define INSTANCES"),rn(r,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES")),this._linkedWithPrePass?s.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):s.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),$r(i,this._scene,s);const l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),c=h.defines,u=s.join("\n");return c!==u&&h.setEffect(l.createEffect("geometry",{attributes:r,uniformsNames:yT,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler"],defines:u,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:a}},l),u),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.getGBuffer().dispose()}_assignRenderTargetIndices(){const e=[],t=[];let i=2;return e.push("gBuffer_Depth","gBuffer_Normal"),t.push(this._textureTypesAndFormats[AT.DEPTH_TEXTURE_TYPE]),t.push(this._textureTypesAndFormats[AT.NORMAL_TEXTURE_TYPE]),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[AT.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[AT.VELOCITY_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[AT.REFLECTIVITY_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i,s]=this._assignRenderTargetIndices();let r=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?r=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(r=2);const n=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],a=[];for(const e of s)e?(o.push(e.textureType),a.push(e.textureFormat)):(o.push(r),a.push(5));if(this._normalsAreUnsigned=11===o[AT.NORMAL_TEXTURE_TYPE]||13===o[AT.NORMAL_TEXTURE_TYPE],this._multiRenderTarget=new Am("gBuffer",n,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:o,formats:a,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=Zn.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=Zn.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const l=[!0],h=[!1],c=[!0];for(let e=1;e{e.bindAttachments(this.useSpecificClearForDepthTexture?d:u),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(p),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(u)})),this._resizeObserver=e.onResizeObservable.add((()=>{if(this._multiRenderTarget){const t=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(t)}}));const f=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),s=this._scene,r=s.getEngine(),n=e.getMaterial();if(!n)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:B.Identity(),viewProjection:s.getTransformMatrix()},t.skeleton)){const e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=r.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances),l=i.getWorldMatrix();if(this.isReady(e,a)){const h=e._getDrawWrapper();if(!h)return;const c=h.effect;let u;r.enableEffect(h),a||t._bind(e,c,n.fillMode),this._useUbo?(on(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",s.getTransformMatrix()),c.setMatrix("view",s.getViewMatrix()));const d=t._instanceDataStorage;if(d.isFrozen||!n.backFaceCulling&&null===t.overrideMaterialSideOrientation)u=d.sideOrientation;else{const e=i._getWorldMatrixDeterminant();u=t.overrideMaterialSideOrientation,null===u&&(u=n.sideOrientation),e<0&&(u=u===Dn.ClockWiseSideOrientation?Dn.CounterClockWiseSideOrientation:Dn.ClockWiseSideOrientation)}if(n._preBind(h,u),n.needAlphaTesting()){const e=n.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(n.bumpTexture&&s.getEngine().getCaps().standardDerivatives&&th.BumpTextureEnabled&&(c.setFloat3("vBumpInfos",n.bumpTexture.coordinatesIndex,1/n.bumpTexture.level,n.parallaxScaleBias),c.setMatrix("bumpMatrix",n.bumpTexture.getTextureMatrix()),c.setTexture("bumpSampler",n.bumpTexture),c.setFloat2("vTangentSpaceParams",n.invertNormalMapX?-1:1,n.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===n.getClassName()?(null!==n.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",n.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",n.metallicRoughnessTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.baseTexture&&(c.setTexture("albedoSampler",n.baseTexture),c.setMatrix("albedoMatrix",n.baseTexture.getTextureMatrix())),null!==n.baseColor&&c.setColor3("albedoColor",n.baseColor)):"PBRSpecularGlossinessMaterial"===n.getClassName()?(null!==n.specularGlossinessTexture?(c.setTexture("reflectivitySampler",n.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",n.specularGlossinessTexture.getTextureMatrix())):null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor),null!==n.glossiness&&c.setFloat("glossiness",n.glossiness)):"PBRMaterial"===n.getClassName()?(null!==n.metallicTexture&&(c.setTexture("reflectivitySampler",n.metallicTexture),c.setMatrix("reflectivityMatrix",n.metallicTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.roughness||null!==n.metallic||null!==n.metallicTexture?(null!==n.albedoTexture&&(c.setTexture("albedoSampler",n.albedoTexture),c.setMatrix("albedoMatrix",n.albedoTexture.getTextureMatrix())),null!==n.albedoColor&&c.setColor3("albedoColor",n.albedoColor)):(null!==n.reflectivityTexture?(c.setTexture("reflectivitySampler",n.reflectivityTexture),c.setMatrix("reflectivityMatrix",n.reflectivityTexture.getTextureMatrix())):null!==n.reflectivityColor&&c.setColor3("reflectivityColor",n.reflectivityColor),null!==n.microSurface&&c.setFloat("glossiness",n.microSurface))):"StandardMaterial"===n.getClassName()&&(null!==n.specularTexture&&(c.setTexture("reflectivitySampler",n.specularTexture),c.setMatrix("reflectivityMatrix",n.specularTexture.getTextureMatrix())),null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor))),Kr(c,n,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton){const e=t.skeleton;if(e.isUsingTextureForMatrices&&c.getUniformIndex("boneTextureWidth")>-1){const i=e.getTransformMatrixTexture(t);c.setTexture("boneSampler",i),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",t.skeleton.getTransformMatrices(t));this._enableVelocity&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])}nn(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c),this._enableVelocity&&(c.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),c.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),a&&t.hasThinInstances&&c.setMatrix("world",l),t._processRendering(i,e,c,n.fillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=l.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,s)=>{if((s||0===i)&&t.subMeshes)for(let i=0;i{let n;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(r.length){for(e.setColorWrite(!1),n=0;n{throw ye("GeometryBufferRendererSceneComponent")};class RT{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(ks.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),ks.prototype.enableGeometryBufferRenderer=function(e=1,t=15,i){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new AT(this,e,t,i),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},ks.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class IT{constructor(e){this.name=ts.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ts.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}AT._SceneComponentInitialization=e=>{let t=e._getComponent(ts.NAME_GEOMETRYBUFFERRENDERER);t||(t=new IT(e),e._addComponent(t))};Ft.ShadersStore.motionBlurPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize;\n#ifdef OBJECT_BASED\nuniform sampler2D velocitySampler;\n#else\nuniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\n#ifdef OBJECT_BASED\nvec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=samplesCount)\nbreak;vec2 offset=vUV+velocity*(hlim+float(i));\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset,0.0);\n#else\nresult+=texture2D(textureSampler,offset);\n#endif\n}\ngl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0;\n#else\nvec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; \nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=nSamples)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset1,0.0);\n#else\nresult+=texture2D(textureSampler,offset1);\n#endif\n}\ngl_FragColor=result/float(nSamples);\n#endif\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";class PT extends Ko{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,s,r,n,o,a=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,s,r,n,o,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",a,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new RT)),this._applyMode()}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}const i=t.indexOf(e);-1!==i&&t.splice(i,1)}}dispose(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),super.dispose(e)}_applyMode(){if(!this._geometryBufferRenderer&&!this._prePassRenderer)return J.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=B.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=5),this.onApply=e=>this._onApplyScreenBased(e))}_onApplyObjectBased(e){if(e.setVector2("screenSize",new N(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(AT.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){const t=U.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new N(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(AT.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){const e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}}static _Parse(e,t,i,s){return Pe.Parse((()=>new PT(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,s)}}ae([pe()],PT.prototype,"motionStrength",void 0),ae([pe()],PT.prototype,"motionBlurSamples",null),ae([pe()],PT.prototype,"isObjectBased",null),u("BABYLON.MotionBlurPostProcess",PT);Ft.ShadersStore.refractionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";class MT extends Ko{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,s,r,n,o,a,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,o,a,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=s,this.colorLevel=r,this.refractionTextureUrl=t,this.onActivateObservable.add((e=>{this._refTexture=this._refTexture||new Zn(t,e.getScene())})),this.onApplyObservable.add((e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)}))}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,s){return Pe.Parse((()=>new MT(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,s)}}ae([pe()],MT.prototype,"color",void 0),ae([pe()],MT.prototype,"depth",void 0),ae([pe()],MT.prototype,"colorLevel",void 0),ae([pe()],MT.prototype,"refractionTextureUrl",void 0),u("BABYLON.RefractionPostProcess",MT);Ft.ShadersStore.sharpenPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}";class DT extends Ko{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,s,r,n,o=0,a=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,s,r,n,null,o,void 0,null,a),this.colorAmount=1,this.edgeAmount=.3,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,s){return Pe.Parse((()=>new DT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}ae([pe()],DT.prototype,"colorAmount",void 0),ae([pe()],DT.prototype,"edgeAmount",void 0),u("BABYLON.SharpenPostProcess",DT);class OT{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(const e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){const i=this._renderEffects[e];i&&i._enable(Ii.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(Ii.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=Ii.MakeArray(e||this._cameras);if(!i)return;const s=[];let r;for(r=0;r0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){const e=Object.keys(this._renderEffects);for(const t of e){const e=this._renderEffects[t].getPostProcesses();if(e)for(const t of e)t.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}ae([pe()],OT.prototype,"_name",void 0);class NT{constructor(){this._renderPipelines={}}get supportedPipelines(){const e=[];for(const t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){const i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){const s=this._renderPipelines[e];s&&s._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const s=this._renderPipelines[e];s&&s._disableEffect(t,i)}update(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){const t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e]._rebuild()}dispose(){for(const e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e].dispose()}}Object.defineProperty(ks.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(ts.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new wT(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new NT}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class wT{constructor(e){this.name=ts.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(ts.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}}class FT extends OT{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){const e=this.bloom;this.bloom=new uT(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen),!0),this.depthOfField=new xT(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=o.getHardwareScalingLevel(),this._resizeObserver=o.onResizeObservable.add((()=>{this._hardwareScaleLevel=o.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel})),this.bloom=new uT(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new dT("ChromaticAberration",o.getRenderWidth(),o.getRenderHeight(),1,null,Zn.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new lT(o,this.ChromaticAberrationPostProcessId,(()=>this.chromaticAberration),!0),this.grain=new bT("Grain",1,null,Zn.BILINEAR_SAMPLINGMODE,o,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new lT(o,this.GrainPostProcessId,(()=>this.grain),!0);let a=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add((()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,a?Ii.SetImmediate((()=>{this._buildPipeline()})):this._buildPipeline())})),this._buildPipeline(),a=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){const e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;const e=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(const e of this._cameras)this._scene.enableDepthRenderer(e).useOnlyInActiveCamera=!0;this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add((e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())}))}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new CT("imageProcessing",1,null,Zn.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new lT(e,this.ImageProcessingPostProcessId,(()=>this.imageProcessing),!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new ET("fxaa",1,null,Zn.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new lT(e,this.FxaaPostProcessId,(()=>this.fxaa),!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add((()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)}))),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add((()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)}))),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&J.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew FT(e._name,e._name._hdr,t)),e,t,i)}}ae([pe()],FT.prototype,"sharpenEnabled",null),ae([pe()],FT.prototype,"bloomKernel",null),ae([pe()],FT.prototype,"_bloomWeight",void 0),ae([pe()],FT.prototype,"_bloomThreshold",void 0),ae([pe()],FT.prototype,"_hdr",void 0),ae([pe()],FT.prototype,"bloomWeight",null),ae([pe()],FT.prototype,"bloomThreshold",null),ae([pe()],FT.prototype,"bloomScale",null),ae([pe()],FT.prototype,"bloomEnabled",null),ae([pe()],FT.prototype,"depthOfFieldEnabled",null),ae([pe()],FT.prototype,"depthOfFieldBlurLevel",null),ae([pe()],FT.prototype,"fxaaEnabled",null),ae([pe()],FT.prototype,"samples",null),ae([pe()],FT.prototype,"imageProcessingEnabled",null),ae([pe()],FT.prototype,"glowLayerEnabled",null),ae([pe()],FT.prototype,"chromaticAberrationEnabled",null),ae([pe()],FT.prototype,"grainEnabled",null),u("BABYLON.DefaultRenderingPipeline",FT);Ft.ShadersStore.lensHighlightsPixelShader="uniform sampler2D textureSampler; \nuniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;}\nfloat w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;gl_FragColor=blurred;}";Ft.ShadersStore.depthOfFieldPixelShader="uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; \nuniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV;\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \nvec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co)\n{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);}\nvec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;}\nfloat sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;}\nfloat getBlurLevel(float size) {return min(3.0,ceil(size/1.0));}\nvec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);}\nif (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);}\ncol/=total_weight; \nif (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);}\nreturn col;}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; }\nfloat edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;}\nfloat blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);}\nelse {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;}\nif (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}}\nif (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}}\n";class LT{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}}Ft.ShadersStore.ssao2PixelShader="precision highp float;uniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSAO\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base;uniform float xViewport;uniform float yViewport;uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main()\n{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=sign(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;}\nfloat sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);}\n#endif\n#ifdef BLUR\nuniform float outSize;uniform float soften;uniform float tolerance;uniform int samples;\n#ifndef BLUR_BYPASS\nuniform sampler2D depthSampler;\n#ifdef BLUR_LEGACY\n#define inline\nfloat blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;}\n#endif\n#endif\nvoid main()\n{float result=0.0;\n#ifdef BLUR_BYPASS\nresult=textureLod(textureSampler,vUV,0.0).r;\n#else\n#ifdef BLUR_H\nvec2 step=vec2(1.0/outSize,0.0);\n#else\nvec2 step=vec2(0.0,1.0/outSize);\n#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,vUV,step);\n#else\nfloat compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; ithis._originalColorPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e{if(!this._scene.activeCamera)return;const t=n?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=n?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},o.samples=this.textureSamples,o.autoClear=!1,o}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,2.3283064365386963e-10*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){const i=2*t*Math.PI,s=1-.85*e,r=Math.sqrt(1-s*s);return new w(Math.cos(i)*r,Math.sin(i)*r,s)}_generateHemisphere(){const e=this.samples,t=[];let i,s=0;for(;s{if(this._scene.activeCamera){if(e.setArray3("sampleSphere",this._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/this.samples),e.setFloat("totalStrength",this.totalStrength),e.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),e.setFloat("radius",this.radius),e.setFloat("maxZ",this.maxZ),e.setFloat("minZAspect",this.minZAspect),e.setFloat("base",this.base),e.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===or.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",BT.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const t=this._scene.getEngine().getRenderWidth()/2,i=this._scene.getEngine().getRenderHeight()/2,s=this._scene.activeCamera.orthoLeft??-t,r=this._scene.activeCamera.orthoRight??t,n=this._scene.activeCamera.orthoBottom??-i,o=this._scene.activeCamera.orthoTop??i;e.setMatrix3x3("depthProjection",BT.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",.5*(r-s)),e.setFloat("yViewport",.5*(o-n))}e.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),e.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),e.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new LT)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new Ko("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{const t=this._scene.activeCamera.viewport;e.setVector4("viewport",U.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.autoClear=!1,this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){const e=new Uint8Array(65536),t=N.Zero();for(let i=0;inew BT(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType)),e,t,i)}}BT.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],BT.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],ae([pe()],BT.prototype,"totalStrength",void 0),ae([pe()],BT.prototype,"maxZ",void 0),ae([pe()],BT.prototype,"minZAspect",void 0),ae([pe("epsilon")],BT.prototype,"_epsilon",void 0),ae([pe("samples")],BT.prototype,"_samples",void 0),ae([pe("textureSamples")],BT.prototype,"_textureSamples",void 0),ae([pe()],BT.prototype,"_forceGeometryBuffer",void 0),ae([pe()],BT.prototype,"_ratio",void 0),ae([pe()],BT.prototype,"_textureType",void 0),ae([pe()],BT.prototype,"radius",void 0),ae([pe()],BT.prototype,"base",void 0),ae([pe("bypassBlur")],BT.prototype,"_bypassBlur",void 0),ae([pe("expensiveBlur")],BT.prototype,"_expensiveBlur",void 0),ae([pe()],BT.prototype,"bilateralSamples",void 0),ae([pe()],BT.prototype,"bilateralSoften",void 0),ae([pe()],BT.prototype,"bilateralTolerance",void 0),u("BABYLON.SSAO2RenderingPipeline",BT);Ft.ShadersStore.ssaoPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords)\n{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);}\nvoid main()\n{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; ithis._originalColorPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new lT(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),s&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,s)}_attachCameras(e,t){super._attachCameras(e,t);for(const e of this._cameras)this._scene.enableDepthRenderer(e).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e{const e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e})),this._blurVPostProcess.onActivateObservable.add((()=>{const e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e}))}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){const t=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271];this._ssaoPostProcess=new Ko("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=e=>{this._firstUpdate&&(e.setArray3("sampleSphere",t),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",this.totalStrength),e.setFloat("radius",this.radius),e.setFloat("area",this.area),e.setFloat("fallOff",this.fallOff),e.setFloat("base",this.base),e.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new Ko("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Zn.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",U.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){const e=new Uint8Array(1048576);for(let t=0;t0.0)\nhitCoord-=dir;else\nhitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;}\nprojectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;}\n/**\n* Tests the given world position (hitCoord) according to the given reflection vector (dir)\n* until it finds a collision (means that depth is enough close to say \"it's the pixel to sample!\").\n*/\nReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)\n{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i{const i=this._geometryBufferRenderer,s=this._prePassRenderer;if(!s&&!i)return;if(i){const t=i.getTextureIndex(AT.POSITION_TEXTURE_TYPE),s=i.getTextureIndex(AT.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[s])}else if(s){const t=s.getIndex(1),i=s.getIndex(3),r=s.getIndex(6);e.setTexture("normalSampler",s.getRenderTarget().textures[r]),e.setTexture("positionSampler",s.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",s.getRenderTarget().textures[i])}const r=t.activeCamera;if(!r)return;const n=r.getViewMatrix(!0),o=r.getProjectionMatrix(!0);e.setMatrix("projection",o),e.setMatrix("view",n),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(0|this._reflectionSamples)),e.push("#define SMOOTH_STEPS "+(0|this._smoothSteps)),this.updateEffect(e.join("\n"))}static _Parse(e,t,i,s){return Pe.Parse((()=>new kT(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}ae([pe()],kT.prototype,"threshold",void 0),ae([pe()],kT.prototype,"strength",void 0),ae([pe()],kT.prototype,"reflectionSpecularFalloffExponent",void 0),ae([pe()],kT.prototype,"step",void 0),ae([pe()],kT.prototype,"roughnessFactor",void 0),ae([pe()],kT.prototype,"enableSmoothReflections",null),ae([pe()],kT.prototype,"reflectionSamples",null),ae([pe()],kT.prototype,"smoothSteps",null),u("BABYLON.ScreenSpaceReflectionPostProcess",kT);Ft.ShadersStore.standardPixelShader="uniform sampler2D textureSampler;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];void main(void)\n{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void)\n{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminanceshadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;}\naccumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;void main(void)\n{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];void main()\n{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++)\n{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));}\naverage=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];uniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\n#include\n#endif\nvoid main()\n{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++)\n{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;uniform float averageLuminance;void main()\n{vec4 color=texture2D(textureAdderSampler,vUV);\n#ifndef AUTO_EXPOSURE\nvec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0;\n#endif\ngl_FragColor=color;}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p)\n{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);}\nfloat noise(in vec2 p)\n{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);}\nfloat fbm(vec2 p)\n{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;}\nvec3 pattern(vec2 uv)\n{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);}\nfloat luminance(vec3 color)\n{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{return vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);}\nvoid main(void)\n{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i=nSamples)\nbreak;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);}\ngl_FragColor=result/float(nSamples);}\n#endif\n";class GT extends OT{get exposure(){return this._fixedExposure}set exposure(e){this._fixedExposure=e,this._currentExposure=e}get hdrAutoExposure(){return this._hdrAutoExposure}set hdrAutoExposure(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){const t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join("\n"))}}get motionStrength(){return this._motionStrength}set motionStrength(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)}get objectBasedMotionBlur(){return this._isObjectBasedMotionBlur}set objectBasedMotionBlur(e){const t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()}get BloomEnabled(){return this._bloomEnabled}set BloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get DepthOfFieldEnabled(){return this._depthOfFieldEnabled}set DepthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get LensFlareEnabled(){return this._lensFlareEnabled}set LensFlareEnabled(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())}get HDREnabled(){return this._hdrEnabled}set HDREnabled(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())}get VLSEnabled(){return this._vlsEnabled}set VLSEnabled(e){if(this._vlsEnabled!==e){if(e&&!this._scene.enableGeometryBufferRenderer())return void J.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,s=null,r){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=r||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=s,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){const e=this._ratio,t=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new kT("HDRPass",t,e,null,Zn.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess})),this.addEffect(new lT(t.getEngine(),"HDRScreenSpaceReflections",(()=>this.screenSpaceReflectionPostProcess),!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new Ko("HDRPass","standard",[],[],e,null,Zn.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.originalPostProcess})),this.addEffect(new lT(t.getEngine(),"HDRPassPostProcess",(()=>this.originalPostProcess),!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(t,e/4),this._createBrightPassPostProcess(t,e/4),this._createBlurPostProcesses(t,e/4,1),this._createTextureAdderPostProcess(t,e),this.textureAdderFinalPostProcess=new Ko("HDRDepthOfFieldSource","standard",[],[],e,null,Zn.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new lT(t.getEngine(),"HDRBaseDepthOfFieldSource",(()=>this.textureAdderFinalPostProcess),!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new Ko("HDRVLSFinal","standard",[],[],e,null,Zn.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new lT(t.getEngine(),"HDRVLSFinal",(()=>this.volumetricLightFinalPostProcess),!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new Ko("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,Zn.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new lT(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",(()=>this.lensFlareFinalPostProcess),!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new Ko("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,Zn.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new lT(t.getEngine(),"HDRPostHDReDepthOfFieldSource",(()=>this.hdrFinalPostProcess),!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(t,e/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(t,e)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(t,e),this._fxaaEnabled&&(this.fxaaPostProcess=new ET("fxaa",1,null,Zn.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new lT(t.getEngine(),"HDRFxaa",(()=>this.fxaaPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&J.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){const i=new Array(32);this.downSampleX4PostProcess=new Ko("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0;const s=this.downSampleX4PostProcess.width,r=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let n=-2;n<2;n++)i[t]=(e+.5)*(1/s),i[t+1]=(n+.5)*(1/r),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new lT(e.getEngine(),"HDRDownSampleX4",(()=>this.downSampleX4PostProcess),!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new Ko("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{const t=1/this.brightPassPostProcess.width,s=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*s,i[2]=.5*t,i[3]=.5*s,i[4]=-.5*t,i[5]=-.5*s,i[6]=.5*t,i[7]=-.5*s,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new lT(e.getEngine(),"HDRBrightPass",(()=>this.brightPassPostProcess),!0))}_createBlurPostProcesses(e,t,i,s="blurWidth"){const r=e.getEngine(),n=new Jp("HDRBlurH_"+i,new N(1,0),this[s],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),o=new Jp("HDRBlurV_"+i,new N(0,1),this[s],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add((()=>{const e=n.width/r.getRenderWidth();n.kernel=this[s]*e})),o.onActivateObservable.add((()=>{const e=o.height/r.getRenderHeight();o.kernel=this.horizontalBlur?64*e:this[s]*e})),this.addEffect(new lT(e.getEngine(),"HDRBlurH"+i,(()=>n),!0)),this.addEffect(new lT(e.getEngine(),"HDRBlurV"+i,(()=>o),!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(o)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new Ko("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),e.setTexture("lensSampler",this.lensTexture),e.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new lT(e.getEngine(),"HDRTextureAdder",(()=>this.textureAdderPostProcess),!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const s=i.getGBuffer();this.volumetricLightPostProcess=new Ko("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));const r=N.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",s.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),r.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),r.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",r)}},this.addEffect(new lT(e.getEngine(),"HDRVLS",(()=>this.volumetricLightPostProcess),!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new Ko("HDRVLSMerge","standard",[],["originalSampler"],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=e=>{e.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new lT(e.getEngine(),"HDRVLSMerge",(()=>this.volumetricLightMergePostProces),!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,GT.LuminanceSteps);this.luminancePostProcess=new Ko("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const s=[];this.luminancePostProcess.onApply=e=>{const t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;s[0]=-.5*t,s[1]=.5*i,s[2]=.5*t,s[3]=.5*i,s[4]=-.5*t,s[5]=-.5*i,s[6]=.5*t,s[7]=-.5*i,e.setArray2("lumOffsets",s)},this.addEffect(new lT(e.getEngine(),"HDRLuminance",(()=>this.luminancePostProcess),!0));for(let s=GT.LuminanceSteps-1;s>=0;s--){i=Math.pow(3,s);let r="#define LUMINANCE_DOWN_SAMPLE\n";0===s&&(r+="#define FINAL_DOWN_SAMPLER");const n=new Ko("HDRLuminanceDownSample"+s,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,r,t);this.luminanceDownSamplePostProcesses.push(n)}let r=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach(((t,i)=>{const s=new Array(18);t.onApply=e=>{if(!r)return;let n=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)s[n]=e/r.width,s[n+1]=t/r.height,n+=2;e.setArray2("dsOffsets",s),e.setFloat("halfDestPixelSize",.5/r.width),r=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{const t=e.getEngine().readPixels(0,0,1,1),i=new F(1/16581375,1/65025,1/255,1);t.then((e=>{const t=new Uint8Array(e.buffer);this._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100}))}),this.addEffect(new lT(e.getEngine(),"HDRLuminanceDownSample"+i,(()=>t),!0))}))}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new Ko("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let s=1,r=0,n=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),r+=e.getEngine().getDeltaTime(),s<0)s=this._hdrCurrentLuminance;else{const e=(n-r)/1e3;this._hdrCurrentLuminances-this.hdrIncreaseRate*e?s-=this.hdrIncreaseRate*e:s=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/s:(s=G.Clamp(s,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",s)),n=r,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new lT(e.getEngine(),"HDR",(()=>this.hdrPostProcess),!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new Ko("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new lT(e.getEngine(),"HDRLensFlare",(()=>this.lensFlarePostProcess),!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new Ko("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new lT(e.getEngine(),"HDRLensFlareCompose",(()=>this.lensFlareComposePostProcess),!0));const i=new N(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=e=>{e.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),e.setTexture("lensColorSampler",this.lensColorTexture),e.setFloat("strength",this.lensFlareStrength),e.setFloat("ghostDispersal",this.lensFlareGhostDispersal),e.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,e.setVector2("resolution",i),e.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const s=B.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),r=B.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=e=>{if(!this._scene.activeCamera)return;e.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),e.setTexture("lensDirtSampler",this.lensFlareDirtTexture),e.setTexture("lensStarSampler",this.lensStarTexture);const t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2);let n=w.Dot(t.toVector3(),new w(1,0,0))+w.Dot(i.toVector3(),new w(0,0,1));n*=4;const o=B.FromValues(.5*Math.cos(n),-Math.sin(n),0,0,Math.sin(n),.5*Math.cos(n),0,0,0,0,1,0,0,0,0,1),a=r.multiply(o).multiply(s);e.setMatrix("lensStarMatrix",a),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new Ko("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),e.setTexture("depthSampler",this._getDepthTexture()),e.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new lT(e.getEngine(),"HDRDepthOfField",(()=>this.depthOfFieldPostProcess),!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new PT("HDRMotionBlur",e,t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new Ko("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,Zn.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,s=B.Identity();const r=B.Identity();let n=B.Identity();const o=N.Zero();this.motionBlurPostProcess.onApply=t=>{n=e.getProjectionMatrix().multiply(e.getViewMatrix()),n.invertToRef(r),t.setMatrix("inverseViewProjection",r),t.setMatrix("prevViewProjection",s),s=n,o.x=this.motionBlurPostProcess.width,o.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",o),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new lT(e.getEngine(),"HDRMotionBlur",(()=>this.motionBlurPostProcess),!0))}_getDepthTexture(){return this._scene.getEngine().getCaps().drawBuffersExtension?this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]:this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;enew GT(e._name,t,e._ratio)),e,t,i);return e.sourceLightId&&(s.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&Pe.Parse((()=>s.screenSpaceReflectionPostProcess),e.screenSpaceReflectionPostProcess,t,i),s}}GT.LuminanceSteps=6,ae([pe()],GT.prototype,"brightThreshold",void 0),ae([pe()],GT.prototype,"blurWidth",void 0),ae([pe()],GT.prototype,"horizontalBlur",void 0),ae([pe()],GT.prototype,"exposure",null),ae([fe("lensTexture")],GT.prototype,"lensTexture",void 0),ae([pe()],GT.prototype,"volumetricLightCoefficient",void 0),ae([pe()],GT.prototype,"volumetricLightPower",void 0),ae([pe()],GT.prototype,"volumetricLightBlurScale",void 0),ae([pe()],GT.prototype,"hdrMinimumLuminance",void 0),ae([pe()],GT.prototype,"hdrDecreaseRate",void 0),ae([pe()],GT.prototype,"hdrIncreaseRate",void 0),ae([pe()],GT.prototype,"hdrAutoExposure",null),ae([fe("lensColorTexture")],GT.prototype,"lensColorTexture",void 0),ae([pe()],GT.prototype,"lensFlareStrength",void 0),ae([pe()],GT.prototype,"lensFlareGhostDispersal",void 0),ae([pe()],GT.prototype,"lensFlareHaloWidth",void 0),ae([pe()],GT.prototype,"lensFlareDistortionStrength",void 0),ae([pe()],GT.prototype,"lensFlareBlurWidth",void 0),ae([fe("lensStarTexture")],GT.prototype,"lensStarTexture",void 0),ae([fe("lensFlareDirtTexture")],GT.prototype,"lensFlareDirtTexture",void 0),ae([pe()],GT.prototype,"depthOfFieldDistance",void 0),ae([pe()],GT.prototype,"depthOfFieldBlurWidth",void 0),ae([pe()],GT.prototype,"motionStrength",null),ae([pe()],GT.prototype,"objectBasedMotionBlur",null),ae([pe()],GT.prototype,"_ratio",void 0),ae([pe()],GT.prototype,"BloomEnabled",null),ae([pe()],GT.prototype,"DepthOfFieldEnabled",null),ae([pe()],GT.prototype,"LensFlareEnabled",null),ae([pe()],GT.prototype,"HDREnabled",null),ae([pe()],GT.prototype,"VLSEnabled",null),ae([pe()],GT.prototype,"MotionBlurEnabled",null),ae([pe()],GT.prototype,"fxaaEnabled",null),ae([pe()],GT.prototype,"screenSpaceReflectionsEnabled",null),ae([pe()],GT.prototype,"volumetricLightStepsCount",null),ae([pe()],GT.prototype,"motionBlurSamples",null),ae([pe()],GT.prototype,"samples",null),u("BABYLON.StandardRenderingPipeline",GT);class zT{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}Ft.IncludesShadersStore.screenSpaceRayTrace="float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }\n/**\nparam csOrigin Camera-space ray origin,which must be \nwithin the view volume and must have z>0.01 and project within the valid screen rectangle\nparam csDirection Unit length camera-space ray direction\nparam projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \n(**not** [-1,+1] normalized device coordinates).\nparam csZBuffer The camera-space Z buffer\nparam csZBufferSize Dimensions of csZBuffer\nparam csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\nparam nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\nfor clipping rays headed towards the camera\nparam stride Step in horizontal or vertical pixels between samples. This is a float\nbecause integer math is slow on GPUs,but should be set to an integer>=1\nparam jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\nto conceal banding artifacts,plus the stride ray offset.\nparam maxSteps Maximum number of iterations. Higher gives better images but may be slow\nparam maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\nparam selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.\n1 is a reasonable value,depending on the scene you may need to set this value to 2\nparam hitPixel Pixel coordinates of the first intersection with the scene\nparam numIterations number of iterations performed\nparam csHitPoint Camera space location of the ray hit\n*/\n#define inline\nbool traceScreenSpaceRay1(\nvec3 csOrigin,\nvec3 csDirection,\nmat4 projectToPixelMatrix,\nsampler2D csZBuffer,\nvec2 csZBufferSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nsampler2D csZBackBuffer,\nfloat csZBackSizeFactor,\n#endif\nfloat csZThickness,\nfloat nearPlaneZ,\nfloat stride,\nfloat jitterFraction,\nfloat maxSteps,\nfloat maxRayTraceDistance,\nfloat selfCollisionNumSkip,\nout vec2 startPixel,\nout vec2 hitPixel,\nout vec3 csHitPoint,\nout float numIterations\n#ifdef SSRAYTRACE_DEBUG\n,out vec3 debugColor\n#endif\n)\n{\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\n#else\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);}\nif ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));}\nP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\n#endif\nP1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { \nfloat t=rayZMin; rayZMin=rayZMax; rayZMax=t;}\nsceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\n#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\n#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\n#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\n#endif\n#endif\n}\npqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;}\n#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 ||\n(refinementStepCount<=stride*1.4) &&\n(rayZMaxend) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);}\n#endif\nreturn hit;}\n/**\ntexCoord: in the [0,1] range\ndepth: depth in view space (range [znear,zfar]])\n*/\nvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef ORTHOGRAPHIC_CAMERA\nndc.z=-projection[2].z*depth+projection[3].z;\n#else\nndc.z=-projection[2].z-projection[3].z/depth;\n#endif\n#else\n#ifdef ORTHOGRAPHIC_CAMERA\nndc.z=projection[2].z*depth+projection[3].z;\n#else\nndc.z=projection[2].z+projection[3].z/depth;\n#endif\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\n";Ft.ShadersStore.screenSpaceReflection2PixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nuniform sampler2D backDepthSampler;uniform float backSizeFactor;\n#endif\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nuniform samplerCube envCubeSampler;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nuniform vec3 vReflectionPosition;uniform vec3 vReflectionSize;\n#endif\n#endif\nuniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold;\n#include\n#include\n#include\nvec3 hash(vec3 a)\n{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);}\nfloat computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0;\n#ifdef SSR_ATTENUATE_SCREEN_BORDERS\nvec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE\nattenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\nattenuation*=1.0-(numIterations/maxSteps);\n#endif\n#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION\nvec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation;\n#endif\nreturn attenuation;}\n#endif\nvoid main()\n{\n#ifdef SSR_SUPPORTED\nvec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {\n#ifdef SSR_USE_BLUR\ngl_FragColor=vec4(0.);\n#else\ngl_FragColor=colorFull;\n#endif\nreturn;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; \n#ifdef SSR_DECODE_NORMAL\ncsNormal=csNormal*2.0-1.0;\n#endif\n#ifdef SSR_NORMAL_IS_IN_WORLDSPACE\ncsNormal=(view*vec4(csNormal,0.0)).xyz;\n#endif\nfloat depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);\n#ifdef ORTHOGRAPHIC_CAMERA\nvec3 csViewDirection=vec3(0.,0.,1.);\n#else\nvec3 csViewDirection=normalize(csPosition);\n#endif\nvec3 csReflectedVector=reflect(csViewDirection,csNormal);\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0));\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nvec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition);\n#endif\n#ifdef SSR_INVERTCUBICMAP\nwReflectedVector.y*=-1.0;\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nwReflectedVector.z*=-1.0;\n#endif\nvec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz;\n#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\nenvColor=toLinearSpace(envColor);\n#endif\n#else\nvec3 envColor=color;\n#endif\nfloat reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations;\n#ifdef SSRAYTRACE_DEBUG\nvec3 debugColor;\n#endif\n#ifdef SSR_ATTENUATE_FACING_CAMERA\nreflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));\n#endif\nif (reflectionAttenuation>0.0) {\n#ifdef SSR_USE_BLUR\nvec3 jitt=vec3(0.);\n#else\nfloat roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; \n#endif\nvec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); \nrayHasHit=traceScreenSpaceRay1(\ncsPosition,\nnormalize(csReflectedVector+jitt),\nprojectionPixel,\ndepthSampler,\ntexSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nbackDepthSampler,\nbackSizeFactor,\n#endif\nthickness,\nnearPlaneZ,\nstepSize,\njitter,\nmaxSteps,\nmaxDistance,\nselfCollisionNumSkip,\nstartPixel,\nhitPixel,\nhitPoint,\nnumIterations\n#ifdef SSRAYTRACE_DEBUG\n,debugColor\n#endif\n);}\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=vec4(debugColor,1.);return;\n#endif\nvec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb;\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\nreflectedColor=toLinearSpace(reflectedColor);\n#endif\nreflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;}\n#ifndef SSR_BLEND_WITH_FRESNEL\nSSR*=fresnel;\n#endif\n#ifdef SSR_USE_BLUR\nfloat blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; \nfloat a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);}\ngl_FragColor=vec4(SSR,blur_radius/255.0); \n#else\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,colorFull.a);\n#endif\n#else\ngl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0);\n#endif\n}\n";Ft.ShadersStore.screenSpaceReflection2BlurPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator)\n{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;}\nvoid main()\n{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;}\nfloat blurRadius=colorFull.a*255.0; \nvec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);}\n";Ft.ShadersStore.screenSpaceReflection2BlurCombinerPixelShader="uniform sampler2D textureSampler; \nuniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV;\n#include\n#ifdef SSR_BLEND_WITH_FRESNEL\n#include\n#include\nuniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler;\n#endif\nvoid main()\n{\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=texture2D(textureSampler,vUV);\n#else\nvec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,color.a);\n#endif\n}\n";const WT=B.Compose(new w(.5,.5,.5),L.Identity(),new w(.5,.5,.5)),HT=B.Compose(new w(.5,.5,1),L.Identity(),new w(.5,.5,0));class XT extends OT{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}get reflectivityThreshold(){return this._reflectivityThreshold}set reflectivityThreshold(e){e!==this._reflectivityThreshold&&(0===e&&0!==this._reflectivityThreshold||0!==e&&0===this._reflectivityThreshold?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)}get ssrDownsample(){return this._ssrDownsample}set ssrDownsample(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())}get blurDispersionStrength(){return this._blurDispersionStrength}set blurDispersionStrength(e){if(e===this._blurDispersionStrength)return;const t=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;this._blurDispersionStrength=e,t&&this._buildPipeline()}_useBlur(){return this._blurDispersionStrength>0}get blurDownsample(){return this._blurDownsample}set blurDownsample(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e,this._updateEffectDefines()}get environmentTextureIsProbe(){return this._environmentTextureIsProbe}set environmentTextureIsProbe(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()}get attenuateScreenBorders(){return this._attenuateScreenBorders}set attenuateScreenBorders(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())}get attenuateIntersectionDistance(){return this._attenuateIntersectionDistance}set attenuateIntersectionDistance(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())}get attenuateIntersectionIterations(){return this._attenuateIntersectionIterations}set attenuateIntersectionIterations(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())}get attenuateFacingCamera(){return this._attenuateFacingCamera}set attenuateFacingCamera(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())}get attenuateBackfaceReflection(){return this._attenuateBackfaceReflection}set attenuateBackfaceReflection(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())}get clipToFrustum(){return this._clipToFrustum}set clipToFrustum(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())}get useFresnel(){return this._useFresnel}set useFresnel(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())}get enableAutomaticThicknessComputation(){return this._enableAutomaticThicknessComputation}set enableAutomaticThicknessComputation(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())}get backfaceDepthRenderer(){return this._depthRenderer}get backfaceDepthTextureDownsample(){return this._backfaceDepthTextureDownsample}set backfaceDepthTextureDownsample(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())}get backfaceForceDepthWriteTransparentMeshes(){return this._backfaceForceDepthWriteTransparentMeshes}set backfaceForceDepthWriteTransparentMeshes(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){const e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,s=!1,r=0){if(super(t.getEngine(),e),this.SSRRenderEffect="SSRRenderEffect",this.SSRBlurRenderEffect="SSRBlurRenderEffect",this.SSRCombineRenderEffect="SSRCombineRenderEffect",this._samples=1,this.maxDistance=1e3,this.step=1,this.thickness=.5,this.strength=1,this.reflectionSpecularFalloffExponent=1,this.maxSteps=1e3,this.roughnessFactor=.2,this.selfCollisionNumSkip=1,this._reflectivityThreshold=.04,this._ssrDownsample=0,this._blurDispersionStrength=.03,this._blurDownsample=0,this._enableSmoothReflections=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=r,this._forceGeometryBuffer=s,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0)}else{const e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty())}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){const e=this._scene.getEngine(),t=this._prePassRenderer;let i={width:e.getRenderWidth(),height:e.getRenderHeight()};if(t&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const e=t.getRenderTarget();e&&e.textures&&(i=e.textures[t.getIndex(4)].getSize())}else this._ssrPostProcess?.inputTexture&&(i.width=this._ssrPostProcess.inputTexture.width,i.height=this._ssrPostProcess.inputTexture.height);return i}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&e.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(e.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&e.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&e.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&e.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&e.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&e.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&e.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&e.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&e.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&e.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&e.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&e.push("#define SSR_USE_BLUR"),this._debug&&e.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&e.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&e.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&e.push("#define SSR_BLEND_WITH_FRESNEL"),0===this._reflectivityThreshold&&e.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(this._geometryBufferRenderer?.generateNormalsInWorldSpace??this._prePassRenderer?.generateNormalsInWorldSpace)&&e.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),this._geometryBufferRenderer?.normalsAreUnsigned&&e.push("#define SSR_DECODE_NORMAL");const t=this._cameras?.[0];t&&1===t.mode&&e.push("#define ORTHOGRAPHIC_CAMERA"),this._ssrPostProcess?.updateEffect(e.join("\n"))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){const e=this._cameras?.[0];e&&(this._depthRendererCamera=e,this._depthRenderer=new v_(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),e.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new lT(e,this.SSRRenderEffect,(()=>this._ssrPostProcess),!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new lT(e,this.SSRBlurRenderEffect,(()=>[this._blurPostProcessX,this._blurPostProcessY]),!0)),this.addEffect(new lT(e,this.SSRCombineRenderEffect,(()=>this._blurCombinerPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;const e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),s=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));t.width===i&&t.height===s||this._depthRenderer.getDepthMap().resize({width:i,height:s})}_disposeDepthRenderer(){if(this._depthRenderer){if(this._depthRendererCamera){const e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap())??-1;-1!==e&&this._depthRendererCamera.customRenderTargets.splice(e,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){for(let e=0;e{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const i=t.getTextureIndex(AT.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){const t=i.getIndex(5),s=i.getIndex(3),r=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[r]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[s])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const s=this._scene.activeCamera;if(!s)return;const r=s.getViewMatrix(),n=s.getProjectionMatrix();n.invertToRef(U.Matrix[0]),r.invertToRef(U.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",r),e.setMatrix("invView",U.Matrix[1]),e.setMatrix("invProjectionMatrix",U.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",s.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const o=this._getTextureSize();B.ScalingToRef(o.width,o.height,1,U.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?HT:WT,U.Matrix[3]),U.Matrix[3].multiplyToRef(U.Matrix[2],U.Matrix[4]),e.setMatrix("projectionPixel",U.Matrix[4]),this._environmentTexture&&(e.setTexture("envCubeSampler",this._environmentTexture),this._environmentTexture.boundingBoxSize&&(e.setVector3("vReflectionPosition",this._environmentTexture.boundingBoxPosition),e.setVector3("vReflectionSize",this._environmentTexture.boundingBoxSize)))},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new zT)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new Ko("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add((e=>{const t=this._blurPostProcessX?.inputTexture.width??this._scene.getEngine().getRenderWidth();e.setFloat2("texelOffsetScale",this._blurDispersionStrength/t,0)})),this._blurPostProcessY=new Ko("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add((e=>{const t=this._blurPostProcessY?.inputTexture.height??this._scene.getEngine().getRenderHeight();e.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/t)}));const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"];let s="";this._debug&&(s+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(s+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(s+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(s+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(s+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new Ko("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,s,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add((e=>{const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(i||t){if(i&&this._scene.activeCamera?._getFirstPostProcess()===this._ssrPostProcess){const t=i.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[i.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(t){const i=t.getTextureIndex(AT.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),this.useFresnel&&(e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("depthSampler",t.getGBuffer().textures[0]))}else if(i){const t=i.getIndex(3);if(e.setTexture("reflectivitySampler",i.getRenderTarget().textures[t]),this.useFresnel){const t=i.getIndex(5),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const t=this._scene.activeCamera;if(t){const i=t.getProjectionMatrix();i.invertToRef(U.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",U.Matrix[0])}}}}))}serialize(){const e=Pe.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return Pe.Parse((()=>new XT(e._name,t,e._ratio)),e,t,i)}}ae([pe()],XT.prototype,"samples",null),ae([pe()],XT.prototype,"maxDistance",void 0),ae([pe()],XT.prototype,"step",void 0),ae([pe()],XT.prototype,"thickness",void 0),ae([pe()],XT.prototype,"strength",void 0),ae([pe()],XT.prototype,"reflectionSpecularFalloffExponent",void 0),ae([pe()],XT.prototype,"maxSteps",void 0),ae([pe()],XT.prototype,"roughnessFactor",void 0),ae([pe()],XT.prototype,"selfCollisionNumSkip",void 0),ae([pe()],XT.prototype,"_reflectivityThreshold",void 0),ae([pe("_ssrDownsample")],XT.prototype,"_ssrDownsample",void 0),ae([pe()],XT.prototype,"ssrDownsample",null),ae([pe("blurDispersionStrength")],XT.prototype,"_blurDispersionStrength",void 0),ae([pe("blurDownsample")],XT.prototype,"_blurDownsample",void 0),ae([pe("enableSmoothReflections")],XT.prototype,"_enableSmoothReflections",void 0),ae([pe("environmentTexture")],XT.prototype,"_environmentTexture",void 0),ae([pe("environmentTextureIsProbe")],XT.prototype,"_environmentTextureIsProbe",void 0),ae([pe("attenuateScreenBorders")],XT.prototype,"_attenuateScreenBorders",void 0),ae([pe("attenuateIntersectionDistance")],XT.prototype,"_attenuateIntersectionDistance",void 0),ae([pe("attenuateIntersectionIterations")],XT.prototype,"_attenuateIntersectionIterations",void 0),ae([pe("attenuateFacingCamera")],XT.prototype,"_attenuateFacingCamera",void 0),ae([pe("attenuateBackfaceReflection")],XT.prototype,"_attenuateBackfaceReflection",void 0),ae([pe("clipToFrustum")],XT.prototype,"_clipToFrustum",void 0),ae([pe("useFresnel")],XT.prototype,"_useFresnel",void 0),ae([pe("enableAutomaticThicknessComputation")],XT.prototype,"_enableAutomaticThicknessComputation",void 0),ae([pe("backfaceDepthTextureDownsample")],XT.prototype,"_backfaceDepthTextureDownsample",void 0),ae([pe("backfaceForceDepthWriteTransparentMeshes")],XT.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),ae([pe("isEnabled")],XT.prototype,"_isEnabled",void 0),ae([pe("inputTextureColorIsInGammaSpace")],XT.prototype,"_inputTextureColorIsInGammaSpace",void 0),ae([pe("generateOutputInGammaSpace")],XT.prototype,"_generateOutputInGammaSpace",void 0),ae([pe("debug")],XT.prototype,"_debug",void 0),u("BABYLON.SSRRenderingPipeline",XT);Ft.ShadersStore.taaPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D historySampler;uniform float factor;void main() {vec4 c=texelFetch(textureSampler,ivec2(gl_FragCoord.xy),0);vec4 h=texelFetch(historySampler,ivec2(gl_FragCoord.xy),0);gl_FragColor=mix(h,c,factor);}\n";class YT extends OT{set samples(e){this._samples!==e&&(this._samples=e,this._hs.regenerate(e))}get samples(){return this._samples}set msaaSamples(e){this._msaaSamples!==e&&(this._msaaSamples=e,this._taaPostProcess&&(this._taaPostProcess.samples=e))}get msaaSamples(){return this._msaaSamples}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&(this._firstUpdate=!0,this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras))):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get scene(){return this._scene}get isSupported(){return this._scene.getEngine().getCaps().texelFetch}constructor(e,t,i,s=0){const r=t.getEngine();super(r,e),this.TAARenderEffect="TAARenderEffect",this.TAAPassEffect="TAAPassEffect",this._samples=8,this._msaaSamples=1,this.factor=.05,this.disableOnCameraMove=!0,this._isEnabled=!0,this._isDirty=!1,this._camerasToBeAttached=[],this._pingpong=0,this._firstUpdate=!0,this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._hs=new yg(this.samples),this.isSupported&&(this._createPingPongTextures(r.getRenderWidth(),r.getRenderHeight()),t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline())}getClassName(){return"TAARenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(){this._disposePostProcesses(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._ping.dispose(),this._pong.dispose(),super.dispose()}_createPingPongTextures(e,t){const i=this._scene.getEngine();this._ping?.dispose(),this._pong?.dispose(),this._ping=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._pong=i.createRenderTargetTexture({width:e,height:t},{generateMipMaps:!1,generateDepthBuffer:!1,type:2,samplingMode:1}),this._hs.setDimensions(e/2,t/2),this._firstUpdate=!0}_updateEffectDefines(){this._taaPostProcess?.updateEffect([].join("\n"))}_buildPipeline(){if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const e=this._scene.getEngine();this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._createTAAPostProcess(),this.addEffect(new lT(e,this.TAARenderEffect,(()=>this._taaPostProcess),!0)),this._createPassPostProcess(),this.addEffect(new lT(e,this.TAAPassEffect,(()=>this._passPostProcess),!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_disposePostProcesses(){for(let e=0;e{const e=this._scene.activeCamera;if(this._taaPostProcess?.width!==this._ping.width||this._taaPostProcess?.height!==this._ping.height){const e=this._scene.getEngine();this._createPingPongTextures(e.getRenderWidth(),e.getRenderHeight())}if(e&&!e.hasMoved)if(e.mode===or.PERSPECTIVE_CAMERA){const t=e.getProjectionMatrix();t.setRowFromFloats(2,this._hs.x,this._hs.y,t.m[10],t.m[11])}else{const t=e.getProjectionMatrix(!0);t.setRowFromFloats(3,this._hs.x+t.m[12],this._hs.y+t.m[13],t.m[14],t.m[15])}this._passPostProcess&&(this._passPostProcess.inputTexture=this._pingpong?this._ping:this._pong),this._pingpong=1^this._pingpong,this._hs.next()})),this._taaPostProcess.onApplyObservable.add((e=>{const t=this._scene.activeCamera;e._bindTexture("historySampler",this._pingpong?this._ping.texture:this._pong.texture),e.setFloat("factor",t?.hasMoved&&this.disableOnCameraMove||this._firstUpdate?1:this.factor),this._firstUpdate=!1}))}_createPassPostProcess(){const e=this._scene.getEngine();this._passPostProcess=new Ml("TAAPass",1,null,1,e),this._passPostProcess.inputTexture=this._ping,this._passPostProcess.autoClear=!1}serialize(){const e=Pe.Serialize(this);return e.customType="TAARenderingPipeline",e}static Parse(e,t,i){return Pe.Parse((()=>new YT(e._name,t,e._ratio)),e,t,i)}}ae([pe("samples")],YT.prototype,"_samples",void 0),ae([pe("msaaSamples")],YT.prototype,"_msaaSamples",void 0),ae([pe()],YT.prototype,"factor",void 0),ae([pe()],YT.prototype,"disableOnCameraMove",void 0),ae([pe("isEnabled")],YT.prototype,"_isEnabled",void 0),u("BABYLON.TAARenderingPipeline",YT);var jT;Ft.ShadersStore.tonemapPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{return dot(c,vec3(0.22,0.707,0.071));}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);}",function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(jT||(jT={}));Ft.ShadersStore.volumetricLightScatteringPixelShader="uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add((e=>{this._updateMeshScreenCoordinates(l),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)}))}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){const i=e.getMesh();if(i===this.mesh&&i.material)return i.material.isReady(i);const s=i._internalAbstractMeshDataInfo._materialForRenderPass?.[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(i,e,t);const r=[],n=[Ki.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&r.push("#define ALPHATEST"),i.isVerticesDataPresent(Ki.UVKind)&&(n.push(Ki.UVKind),r.push("#define UV1")),i.isVerticesDataPresent(Ki.UV2Kind)&&(n.push(Ki.UV2Kind),r.push("#define UV2"))),i.useBones&&i.computeBonesUsingShaders?(n.push(Ki.MatricesIndicesKind),n.push(Ki.MatricesWeightsKind),r.push("#define NUM_BONE_INFLUENCERS "+i.numBoneInfluencers),r.push("#define BonesPerMesh "+(i.skeleton?i.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0"),t&&(r.push("#define INSTANCES"),rn(n),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));const a=e._getDrawWrapper(void 0,!0),l=a.defines,h=r.join("\n");return l!==h&&a.setEffect(i.getScene().getEngine().createEffect("volumetricLightScatteringPass",n,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],h,void 0,void 0,void 0,{maxSimultaneousMorphTargets:i.numBoneInfluencers}),h),a.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){const t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==t&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)}_createPass(e,t){const i=e.getEngine();this._volumetricLightScatteringRTT=new da("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=Zn.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=Zn.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const r=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh();if(this._meshExcluded(t))return;i._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const s=e.getMaterial();if(!s)return;const r=t.getScene(),n=r.getEngine();n.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);const o=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;const a=n.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||t.hasThinInstances);if(this._isReady(e,a)){const l=i._internalAbstractMeshDataInfo._materialForRenderPass?.[n.currentRenderPassId];let h=e._getDrawWrapper();if(t!==this.mesh||h||(h=s._getDrawWrapper()),!h)return;const c=h.effect;if(n.enableEffect(h),a||t._bind(e,c,s.fillMode),t===this.mesh)s.bind(i.getWorldMatrix(),t);else if(l)l.bindForSubMesh(i.getWorldMatrix(),i,e);else{if(c.setMatrix("viewProjection",r.getTransformMatrix()),s&&s.needAlphaTesting()){const e=s.getAlphaTestTexture();c.setTexture("diffuseSampler",e),e&&c.setMatrix("diffuseMatrix",e.getTextureMatrix())}t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&c.setMatrices("mBones",t.skeleton.getTransformMatrices(t))}a&&t.hasThinInstances&&c.setMatrix("world",i.getWorldMatrix()),t._processRendering(i,e,c,Dn.TriangleFillMode,o,a,((e,t)=>{e||c.setMatrix("world",t)}))}};let n;const o=new j(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((()=>{n=e.clearColor,e.clearColor=o})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((()=>{e.clearColor=n})),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,s)=>{if((s||0===t)&&e.subMeshes)for(let t=0;t{const o=e.getEngine();let a;if(n.length){for(o.setColorWrite(!1),a=0;ae._alphaIndex>t._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0)),o.setAlphaMode(2),a=0;a{e.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));const t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}):J.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=y.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,s){return Pe.Parse((()=>new KT(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,s)}}ae([pe()],KT.prototype,"ridge",void 0),ae([pe()],KT.prototype,"valley",void 0),u("BABYLON.ScreenSpaceCurvaturePostProcess",KT);Ft.IncludesShadersStore.boundingBoxRendererFragmentDeclaration="uniform vec4 color;\n";Ft.IncludesShadersStore.boundingBoxRendererUboDeclaration="#ifdef WEBGL2\nuniform vec4 color;uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#else\nlayout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;};\n#endif\n";Ft.ShadersStore.boundingBoxRendererPixelShader="#include<__decl__boundingBoxRendererFragment>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.IncludesShadersStore.boundingBoxRendererVertexDeclaration="uniform mat4 world;uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n";Ft.ShadersStore.boundingBoxRendererVertexShader="attribute vec3 position;\n#include<__decl__boundingBoxRendererVertex>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec4 worldPos=world*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n",Object.defineProperty(ks.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),ks.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new qT(this)),this._boundingBoxRenderer},Object.defineProperty(Wr.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class qT{constructor(e){this.name=ts.NAME_BOUNDINGBOXRENDERER,this.frontColor=new Y(1,1,1),this.backColor=new Y(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new g,this.onAfterBoxRenderingObservable=new g,this.onResourcesReadyObservable=new g,this.enabled=!0,this.renderList=new Mi(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new ji(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new ji(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(ts.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(ts.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(ts.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(ts.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){const i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){const t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new fc("colorShader",this.scene,"boundingBoxRenderer",{attributes:[Ki.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new fc("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[Ki.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=ic({size:1});this._vertexBuffers[Ki.PositionKind]=new Ki(e,t.positions,Ki.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){const e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){const e=this._vertexBuffers[Ki.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){if(0===this.renderList.length||!this.enabled)return;if(this._prepareResources(),!this._colorShader.isReady())return;const t=this.scene.getEngine();t.setDepthWrite(!1);const i=this.scene.getTransformMatrix();for(let s=0;s{let t=e._getComponent(ts.NAME_DEPTHRENDERER);t||(t=new QT(e),e._addComponent(t))};Ft.ShadersStore.oitFinalPixelShader="precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4(\nfrontColor.rgb+alphaMultiplier*backColor.rgb,\nfrontColor.a+backColor.a\n);}";Ft.ShadersStore.oitBackBlendPixelShader="precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { \ndiscard;}}";class ZT{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class JT{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new Mi(10),this._excludedSubMeshes=new Mi(10),this._excludedMeshes=[],this._colorCache=[new j(JT._DEPTH_CLEAR_VALUE,JT._DEPTH_CLEAR_VALUE,0,0),new j(-JT._MIN_DEPTH,JT._MAX_DEPTH,0,0),new j(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,e.enablePrePassRenderer()){for(let e=0;e\nuniform vec4 color;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.lineVertexShader="#include\n#include\nattribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio;\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nmat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#include\n#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}",Wr.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},Wr.prototype.enableEdgesRendering=function(e=.95,t=!1,i){return this.disableEdgesRendering(),this._edgesRenderer=new iS(this,e,t,!0,i),this},Object.defineProperty(Wr.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),_c.prototype.enableEdgesRendering=function(e=.95,t=!1){return this.disableEdgesRendering(),this._edgesRenderer=new sS(this,e,t),this},mc.prototype.enableEdgesRendering=function(e=.95,t=!1){return _c.prototype.enableEdgesRendering.apply(this,arguments),this};class tS{constructor(){this.edges=[],this.edgesConnectedCount=0}}class iS{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){const t=new fc("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,s=!0,r){this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=new Array,this._linesNormals=new Array,this._linesIndices=new Array,this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new Mi(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=r??null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new gr(e.getEngine())),this._prepareRessources(),s&&(r?.useAlternateEdgeFinder??1?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add((()=>{this._rebuild()})),this._meshDisposeObserver=this._source.onDisposeObservable.add((()=>{this.dispose()}))}_prepareRessources(){this._lineShader||(this._lineShader=iS._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[Ki.PositionKind];e&&e._rebuild(),e=this._buffers[Ki.NormalKind],e&&e._rebuild();const t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)}dispose(){this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let e=this._buffers[Ki.PositionKind];e&&(e.dispose(),this._buffers[Ki.PositionKind]=null),e=this._buffers[Ki.NormalKind],e&&(e.dispose(),this._buffers[Ki.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),this._drawWrapper?.dispose()}_processEdgeForAdjacencies(e,t,i,s,r){return e===i&&t===s||e===s&&t===i?0:e===s&&t===r||e===r&&t===s?1:e===r&&t===i||e===i&&t===r?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,s,r){const n=1e-10;return e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(s,n)||e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(i,n)?0:e.equalsWithEpsilon(s,n)&&t.equalsWithEpsilon(r,n)||e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(s,n)?1:e.equalsWithEpsilon(r,n)&&t.equalsWithEpsilon(i,n)||e.equalsWithEpsilon(i,n)&&t.equalsWithEpsilon(r,n)?2:-1}_checkEdge(e,t,i,s,r){let n;n=void 0===t||w.Dot(i[e],i[t]){i>=0&&t.push(i);for(let i=0;i=e[0].length&&e[1].length>=e[2].length?n=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(n=2);for(let t=0;t<3;++t)t===n?e[t].sort(((e,t)=>e[1]t[1]?1:0)):e[t].sort(((e,t)=>e[1]>t[1]?-1:e[1]=n+1;--o)r(e[o%3],a,o!==n+2?s[i[t+(o+1)%3]]:-1);const h=a.length;i.push(s[i[t+n]],o[0],a[0]),i.push(s[i[t+(n+1)%3]],a[h-1],o[l-1]);const c=l<=h,u=c?l:h,d=c?h:l,p=c?l-1:h-1,f=c?0:1;let _=l+h-2,m=0,g=0;const v=c?o:a,x=c?a:o;let T=0;for(;_-- >0;){let e;f?i.push(v[m],x[g]):i.push(x[g],v[m]),T+=u,T>=d&&ml){const e=a;a=l,l=e}const c=a+"_"+l,u=o[c];u?u.done||(w.Dot(s,u.normal)0||this._source.hasThinInstances)}render(){const e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera)return void this._lineShader._setDrawWrapper(t);const i=this._source.hasInstances&&this.customInstances.length>0,s=i||this._source.hasThinInstances;let r=0;if(s)if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){const e=this._source._instanceDataStorage;if(r=this.customInstances.length,!e.instancesData)return void(this._source.getScene()._activeMeshesFrozen||this.customInstances.reset());if(!e.isFrozen){let t=0;for(let i=0;i0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[r]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),s.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(s)}_resetLayout(){for(let e=0;enull!=e)),this._scene.autoClear=!0;const s=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!s&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const r=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||s,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?o=n:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:r&&(o=r),this._bindFrameBuffer(),this._linkInternalTexture(e,o)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;enull!=e)),e)){for(let s=0;s=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw ye("PrePassRendererSceneComponent")},nS.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}],Object.defineProperty(ks.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),ks.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new nS(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,J.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},ks.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class oS{constructor(e){this.name=ts.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(ts.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(ts.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(ts.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(ts.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(ts.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(ts.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(ts.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(ts.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,s){if(!s)return;const r=e.getScene();r.prePassRenderer&&r.prePassRenderer.bindAttachmentsForEffect(s,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){}dispose(){this.scene.disablePrePassRenderer()}}nS._SceneComponentInitialization=e=>{let t=e._getComponent(ts.NAME_PREPASSRENDERER);t||(t=new oS(e),e._addComponent(t))};Ft.IncludesShadersStore.fibonacci="#define rcp(x) 1./x\n#define GOLDEN_RATIO 1.618033988749895\n#define TWO_PI 6.2831855\nvec2 Golden2dSeq(int i,float n)\n{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));}\nvec2 SampleDiskGolden(int i,int sampleCount)\n{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}";Ft.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";Ft.ShadersStore.subSurfaceScatteringPixelShader="#include\n#include\n#include\n#include\nvarying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40;\n#define rcp(x) 1./x\n#define Sq(x) x*x\n#define SSS_BILATERAL_FILTER true\nvec3 EvalBurleyDiffusionProfile(float r,vec3 S)\n{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); \nvec3 expSum=exp_13*(1.+exp_13*exp_13); \nreturn (S*rcp(8.*PI))*expSum; }\nvec2 SampleBurleyDiffusionProfile(float u,float rcpS)\n{u=1.-u; \nfloat g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); \nfloat p=(g*n)*n; \nfloat c=1.+p+n; \nfloat d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); \nfloat x=(3./LOG2_E)*log2(c)-d; \nfloat rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; \nreturn vec2(r,rcpPdf);}\nvec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)\n{\n#ifndef SSS_BILATERAL_FILTER\nz=0.;\n#endif\nfloat r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf;\n#if SSS_CLAMP_ARTIFACT\nreturn clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);\n#else\nreturn EvalBurleyDiffusionProfile(r,S)*area;\n#endif\n}\nvoid EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,\nfloat phase,inout vec3 totalIrradiance,inout vec3 totalWeight)\n{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; \nfloat cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; \nvec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; \nfloat xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a))\n{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;}\nelse\n{}}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest)\n{centerDepth=texture2D(depthSampler,vUV).r;}\nif (!passedStencilTest) { \ngl_FragColor=inputColor;return;}\nfloat distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; \nvec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; \nfloat mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1)\n{\n#ifdef DEBUG_SSS_SAMPLES\nvec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return;\n#endif\ngl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;}\n#ifdef DEBUG_SSS_SAMPLES\nvec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return;\n#endif\nfloat phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); \nvec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration)return void J.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");const i=this.texelSize;e.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",i.x,i.y),e.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),e.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),e.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),e.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),e.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)}))}}class lS{get ssDiffusionS(){return this._ssDiffusionS}get ssDiffusionD(){return this._ssDiffusionD}get ssFilterRadii(){return this._ssFilterRadii}constructor(e){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=ts.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new Y(1,1,1)),this._scene=e,lS._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return J.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw ye("SubSurfaceSceneComponent")},p.AddParser(ts.NAME_SUBSURFACE,((e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,s=e.ssDiffusionProfileColors.length;i{let t=e._getComponent(ts.NAME_SUBSURFACE);t||(t=new hS(e),e._addComponent(t))};Ft.ShadersStore.outlinePixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform sampler2D diffuseSampler;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.outlineVertexShader="attribute vec3 position;attribute vec3 normal;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;uniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{vec3 positionUpdated=position;vec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n#include\n}\n",ks.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new cS(this)),this._outlineRenderer},Object.defineProperty(Un.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(Un.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});class cS{constructor(e){this.name=ts.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(ts.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(ts.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{p.setMatrix("world",t)})),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=i??this._passIdForDrawWrapper[0];const s=[],r=[Ki.PositionKind,Ki.NormalKind],n=e.getMesh(),o=e.getMaterial();if(!o)return!1;const a=n.getScene();o.needAlphaTesting()&&(s.push("#define ALPHATEST"),n.isVerticesDataPresent(Ki.UVKind)&&(r.push(Ki.UVKind),s.push("#define UV1")),n.isVerticesDataPresent(Ki.UV2Kind)&&(r.push(Ki.UV2Kind),s.push("#define UV2"))),o.useLogarithmicDepth&&s.push("#define LOGARITHMICDEPTH"),$r(o,a,s),n.useBones&&n.computeBonesUsingShaders?(r.push(Ki.MatricesIndicesKind),r.push(Ki.MatricesWeightsKind),n.numBoneInfluencers>4&&(r.push(Ki.MatricesIndicesExtraKind),r.push(Ki.MatricesWeightsExtraKind)),s.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),s.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):s.push("#define NUM_BONE_INFLUENCERS 0");const l=n.morphTargetManager;let h=0;l&&(h=l.numMaxInfluencers||l.numInfluencers,h>0&&(s.push("#define MORPHTARGETS"),s.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&s.push("#define MORPHTARGETS_TEXTURE"),tn(r,n,h))),t&&(s.push("#define INSTANCES"),rn(r),e.getRenderingMesh().hasThinInstances&&s.push("#define THIN_INSTANCES"));const c=e._getDrawWrapper(i,!0),u=c.defines,d=s.join("\n");if(u!==d){const e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices"];jr(e),c.setEffect(this.scene.getEngine().createEffect("outline",r,e,["diffuseSampler","morphTargets"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),d)}return c.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const s=t.getMaterial();s&&s.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(cS._StencilReference),this._engine.setStencilFunctionReference(cS._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),s&&s.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const e=this._engine.getAlphaMode(),s=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=s}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}cS._StencilReference=4;class uS{get particleSize(){return this._particleSize}set particleSize(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))}get useInstancing(){return!this.indexBuffer}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&this._hasVelocity()&&(this._useVelocity=e,this._effectsAreDirty=!0)}_hasVelocity(){return!!this.vertexBuffers?.velocity}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new g,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){const e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new oa({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new oa({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})}isReady(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;const e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){const e=this.numParticles;if(!this._depthEffectWrapper||0===e)return;const t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}renderThicknessTexture(){const e=this.numParticles;if(!this._thicknessEffectWrapper||0===e)return;const t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(6),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0)}renderDiffuseTexture(){}dispose(){this._depthEffectWrapper?.dispose(),this._thicknessEffectWrapper?.dispose()}}class dS extends uS{get particleSystem(){return this._particleSystem}getClassName(){return"FluidRenderingObjectParticleSystem"}get useTrueRenderingForDiffuseTexture(){return this._useTrueRenderingForDiffuseTexture}set useTrueRenderingForDiffuseTexture(e){this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add((()=>{this._engine.setAlphaMode(2)}))))}get vertexBuffers(){return this._particleSystem.vertexBuffers}get indexBuffer(){return this._particleSystem.indexBuffer}constructor(e,t){super(e),this._useTrueRenderingForDiffuseTexture=!0,this._particleSystem=t,this._originalRender=t.render.bind(t),this._blendMode=t.blendMode,this._onBeforeDrawParticleObserver=null,this._updateInAnimate=this._particleSystem.updateInAnimate,this._particleSystem.updateInAnimate=!0,this._particleSystem.render=()=>0,this.particleSize=(t.minSize+t.maxSize)/2,this.useTrueRenderingForDiffuseTexture=!1}isReady(){return super.isReady()&&this._particleSystem.isReady()}get numParticles(){return this._particleSystem.getActiveCount()}renderDiffuseTexture(){this._originalRender()}dispose(){super.dispose(),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate}}class pS{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){const e=this._blurPostProcesses[0],t=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let i=0;i<2*this._blurNumIterations;++i)this._blurPostProcesses[i]=1&i?t:e}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}constructor(e,t,i,s,r,n,o=1,a=6,l=1,h=6,c=!1,u=null,d=!0,p=1){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new g,this._name=e,this._scene=t,this._camera=u,this._engine=t.getEngine(),this._width=i,this._height=s,this._blurTextureSizeX=r,this._blurTextureSizeY=n,this._textureType=o,this._textureFormat=a,this._blurTextureType=l,this._blurTextureFormat=h,this._useStandardBlur=c,this._generateDepthBuffer=d,this._samples=p,this._postProcessRunningIndex=0,this.enableBlur=0!==r&&0!==n,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){const[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});const e=this._rt.texture;e.incrementReferences(),this._texture=new Zn(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=Zn.CLAMP_ADDRESSMODE,this._texture.wrapV=Zn.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,s,r,n=!1){const o=this._scene.getEngine(),a=new N(Math.floor(this._blurTextureSizeX/s),Math.floor(this._blurTextureSizeY/s)),l=1===t&&o.getCaps().textureFloatLinearFiltering||2===t&&o.getCaps().textureHalfFloatLinearFiltering,h=this._engine.createRenderTargetTexture({width:a.x,height:a.y},{generateMipMaps:!1,type:t,format:i,samplingMode:l?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${r}`}),c=h.texture;c.incrementReferences();const u=new Zn(null,this._scene);if(u.name="rttBlurred"+r,u._texture=c,u.wrapU=Zn.CLAMP_ADDRESSMODE,u.wrapV=Zn.CLAMP_ADDRESSMODE,u.anisotropicFilteringLevel=1,n){const s=new Ko("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",s.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++})),s.onSizeChangedObservable.add((()=>{s._textures.forEach((e=>{e.texture.wrapU=Zn.CLAMP_ADDRESSMODE,e.texture.wrapV=Zn.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(s);const r=new Ko("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.onApplyObservable.add((e=>{e.setInt("filterSize",this.blurFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++})),r.onSizeChangedObservable.add((()=>{r._textures.forEach((e=>{e.texture.wrapU=Zn.CLAMP_ADDRESSMODE,e.texture.wrapV=Zn.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(r),s.autoClear=!1,r.autoClear=!1;const n=[];for(let e=0;e<2*this._blurNumIterations;++e)n[e]=1&e?r:s;return[h,u,n]}{const s=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],r=new Ko("BilateralBlurX","fluidRenderingBilateralBlur",s,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",r.inputTexture.texture),t.setInt("maxFilterSize",this.blurMaxFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),t.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),r.onSizeChangedObservable.add((()=>{r._textures.forEach((e=>{e.texture.wrapU=Zn.CLAMP_ADDRESSMODE,e.texture.wrapV=Zn.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(r);const n=new Ko("BilateralBlurY","fluidRenderingBilateralBlur",s,null,1,null,1,o,!0,null,t,void 0,void 0,void 0,i);n.samples=this._samples,n.onApplyObservable.add((e=>{e.setInt("maxFilterSize",this.blurMaxFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),e.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),e.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),n.onSizeChangedObservable.add((()=>{n._textures.forEach((e=>{e.texture.wrapU=Zn.CLAMP_ADDRESSMODE,e.texture.wrapV=Zn.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(n),r.autoClear=!1,n.autoClear=!1;const a=[];for(let e=0;e<2*this._blurNumIterations;++e)a[e]=1&e?n:r;return[h,u,a]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})),e.onApplyObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})))}_getProjectedParticleConstant(){return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((this._camera?.fov??45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),this._rt?.dispose(),this._rt=null,this._texture?.dispose(),this._texture=null,this._rtBlur?.dispose(),this._rtBlur=null,this._textureBlurred?.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}var fS;!function(e){e[e.DepthTexture=0]="DepthTexture",e[e.DepthBlurredTexture=1]="DepthBlurredTexture",e[e.ThicknessTexture=2]="ThicknessTexture",e[e.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",e[e.DiffuseTexture=4]="DiffuseTexture",e[e.Normals=5]="Normals",e[e.DiffuseRendering=6]="DiffuseRendering"}(fS||(fS={}));class _S{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get compositeMode(){return this._compositeMode}set compositeMode(e){this._compositeMode!==e&&(this._compositeMode=e,this._needInitialization=!0)}get camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new Y(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new w(-2,-1,1).normalize(),this._debugFeature=fS.DepthBlurredTexture,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new g,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._compositeMode=!1,this._scene=e,this._engine=e.getEngine(),this._camera=t??e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new B,this._depthClearColor=new j(1e6,1e6,1e6,1),this._thicknessClearColor=new j(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){this.dispose(),this._needInitialization=!1;const e=this._depthMapSize??this._engine.getRenderWidth(),t=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new pS("Depth",this._scene,e,t,e,t,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const e=this._diffuseMapSize??this._engine.getRenderWidth(),t=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new pS("Diffuse",this._scene,e,t,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const i=this._thicknessMapSize??this._engine.getRenderWidth(),s=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new pS("Thickness",this._scene,i,s,i,s,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){null!==e&&e!==this._depthRenderTarget||this._setBlurDepthParameters(),null!==e&&e!==this._thicknessRenderTarget||this._setBlurThicknessParameters()}_setBlurDepthParameters(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)}_setBlurThicknessParameters(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)}_initializeRenderTarget(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()}_createLiquidRenderingPostProcess(){const e=this._scene.getEngine(),t=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],i=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;const r=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,n=new N(1/r.getSize().width,1/r.getSize().height);this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap&&(this._environmentMap??this._scene.environmentTexture)&&(i.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(i.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):t.push("diffuseColor"),this._useVelocity&&(i.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(t.push("thickness"),i.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(t.push("minimumThickness"),i.push("thicknessSampler")),this._compositeMode&&s.push("#define FLUIDRENDERING_COMPOSITE_MODE"),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===fS.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===fS.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),i.push("debugSampler"),this._debugFeature!==fS.DepthTexture&&this._debugFeature!==fS.DepthBlurredTexture||s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new Ko("FluidRendering","fluidRenderingRender",t,i,1,null,2,e,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(s.join("\n")),this._renderPostProcess.samples=this._samples;const o=e,a=o.setTextureSampler;this._renderPostProcess.onApplyObservable.add((e=>{if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),a&&a.call(o,"textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(e.setTexture("depthSampler",this._depthRenderTarget.textureBlur),a&&a.call(o,"depthSamplerSampler",this._depthRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),a&&a.call(o,"depthSamplerSampler",this._depthRenderTarget.texture?.getInternalTexture()??null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),a&&a.call(o,"diffuseSamplerSampler",this._diffuseRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),a&&a.call(o,"diffuseSamplerSampler",this._diffuseRenderTarget.texture?.getInternalTexture()??null)):e.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(e.setFloat("thickness",this.minimumThickness),e._bindTexture("bgDepthSampler",this._bgDepthTexture),a&&a.call(o,"bgDepthSamplerSampler",this._bgDepthTexture??null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),a&&a.call(o,"thicknessSamplerSampler",this._thicknessRenderTarget.textureBlur?.getInternalTexture()??null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),a&&a.call(o,"thicknessSamplerSampler",this._thicknessRenderTarget.texture?.getInternalTexture()??null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){const t=this._environmentMap??this._scene.environmentTexture;t&&(e.setTexture("reflectionSampler",t),a&&a.call(o,"reflectionSamplerSampler",t?.getInternalTexture()??null))}if(e.setMatrix("viewMatrix",this._scene.getViewMatrix()),e.setMatrix("invProjectionMatrix",this._invProjectionMatrix),e.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),e.setVector2("texelSize",n),e.setFloat("density",this.density),e.setFloat("refractionStrength",this.refractionStrength),e.setFloat("fresnelClamp",this.fresnelClamp),e.setFloat("specularPower",this.specularPower),e.setVector3("dirLight",this.dirLight),e.setFloat("cameraFar",this._camera.maxZ),this._debug){let t=null;switch(this._debugFeature){case fS.DepthTexture:t=this._depthRenderTarget.texture;break;case fS.DepthBlurredTexture:t=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case fS.ThicknessTexture:t=this._thicknessRenderTarget?.texture??null;break;case fS.ThicknessBlurredTexture:t=this._thicknessRenderTarget?.enableBlur?this._thicknessRenderTarget?.textureBlur??null:this._thicknessRenderTarget?.texture??null;break;case fS.DiffuseTexture:this._diffuseRenderTarget&&(t=this._diffuseRenderTarget.texture)}this._debugFeature!==fS.Normals&&(e.setTexture("debugSampler",t),a&&a.call(o,"debugSamplerSampler",t?.getInternalTexture()??null))}}))}_clearTargets(){this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){if(this._needInitialization||!e.isReady())return;const t=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0),this._depthRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),this._diffuseRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),this._thicknessRenderTarget?.renderTarget&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),this._depthRenderTarget?.applyBlurPostProcesses(),this._diffuseRenderTarget?.applyBlurPostProcesses(),this._thicknessRenderTarget?.applyBlurPostProcesses(),t&&this._engine.bindFramebuffer(t)}dispose(e=!1){e||(this._depthRenderTarget?.dispose(),this._depthRenderTarget=null,this._diffuseRenderTarget?.dispose(),this._diffuseRenderTarget=null,this._thicknessRenderTarget?.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),this._renderPostProcess?.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class mS extends uS{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i){super(e),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(const t in e){let i,s=!0;switch(t){case"velocity":i=3;break;case"offset":s=!1}this._vertexBuffers[t]=new Ki(this._engine,e[t],t,!0,!1,i,s)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new oa({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[]})}isReady(){return this._vertexBuffers.offset||(this._vertexBuffers.offset=new Ki(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&(this._diffuseEffectWrapper?.effect.isReady()??!1)}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){const e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)return;const t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),null!==this._particleSize&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){super.dispose(),this._diffuseEffectWrapper?.dispose();for(const e in this._vertexBuffers)this._vertexBuffers[e].dispose();this._vertexBuffers={}}}var gS;Ft.ShadersStore.copyTextureToTexturePixelShader="uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV;\n#include\nvoid main(void) \n{vec4 color=texture2D(textureSampler,vUV);\n#ifdef DEPTH_TEXTURE\ngl_FragDepth=color.r;\n#else\nif (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);}\ngl_FragColor=color;\n#endif\n}\n",function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(gS||(gS={}));class vS{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new na(e),this._effectWrapper=new oa({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add((()=>{t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.depthCullingState.depthFunc=519),this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)}))}isReady(){return this._effectWrapper.effect.isReady()}copy(e,t,i=gS.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;const s=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&s&&(this._engine.depthCullingState.depthFunc=s),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class xS{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,s=1){this._engine=e,this._copyTextureToTexture=new vS(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:s,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil").label=`FluidDepthTextureCopy${t}x${i}x${s}`}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}Ft.ShadersStore.fluidRenderingParticleDepthVertexShader="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nattribute vec3 velocity;varying float velocityNorm;\n#endif\nvoid main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0;\n#ifdef FLUIDRENDERING_VELOCITY\nvelocityNorm=length(velocity);\n#endif\n}\n";Ft.ShadersStore.fluidRenderingParticleDepthPixelShader="uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nvarying float velocityNorm;\n#endif\nvoid main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2);\n#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\n#endif\nvec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos;\n#ifdef WEBGPU\ngl_FragDepth=clipSpacePos.z/clipSpacePos.w;\n#else\ngl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;\n#endif\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nglFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);\n#else\nglFragColor=vec4(realViewPos.z,0.,0.,1.);\n#endif\n}\n";Ft.ShadersStore.fluidRenderingParticleThicknessVertexShader="attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;}\n";Ft.ShadersStore.fluidRenderingParticleThicknessPixelShader="uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);}\n";Ft.ShadersStore.fluidRenderingParticleDiffuseVertexShader="attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;}\n";Ft.ShadersStore.fluidRenderingParticleDiffusePixelShader="uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);}\n";Ft.ShadersStore.fluidRenderingBilateralBlurPixelShader="uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;}\nint filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;}\nglFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);}\n";Ft.ShadersStore.fluidRenderingStandardBlurPixelShader="uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;}\nfloat sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;}\nsum/=wsum;glFragColor=vec4(sum.rgb,1.);}\n";function TS(e){return!!e.particleSystem}function SS(e){return!!e.addBuffers}Ft.ShadersStore.fluidRenderingRenderPixelShader="#define DISABLE_UNIFORMITY_ANALYSIS\n#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nuniform sampler2D textureSampler;uniform sampler2D depthSampler;\n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nuniform sampler2D diffuseSampler;\n#else\nuniform vec3 diffuseColor;\n#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform float thickness;uniform sampler2D bgDepthSampler;\n#else\nuniform float minimumThickness;uniform sampler2D thicknessSampler;\n#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nuniform samplerCube reflectionSampler;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nuniform sampler2D debugSampler;\n#endif\nuniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0;\n#ifdef FLUIDRENDERING_RHS\nndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#else\nndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#endif\nndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;}\nvec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);}\nvoid main(void) {vec2 texCoord=vUV;\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvec4 color=texture2D(debugSampler,texCoord);\n#ifdef FLUIDRENDERING_DEBUG_DEPTH\nglFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);}\n#else\nglFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);}\n#endif\nreturn;\n#endif\nvec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r;\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nfloat thickness=texture2D(thicknessSampler,texCoord).x;\n#else\nfloat bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5;\n#endif\nvec4 backColor=texture2D(textureSampler,texCoord);\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {\n#else\nif (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\n#endif\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nglFragColor.rgb=backColor.rgb*backColor.a;glFragColor.a=backColor.a;\n#else\nglFragColor=backColor;\n#endif\nreturn;}\nvec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;}\nvec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;}\nvec3 normal=normalize(cross(ddy,ddx));\n#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\n#endif\n#ifndef WEBGPU\nif(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);}\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nglFragColor=vec4(normal*0.5+0.5,1.0);return;\n#endif\nvec3 rayDir=normalize(viewPos); \n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;\n#endif\nvec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower);\n#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nfloat diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return;\n#endif\nvec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);\n#ifdef FLUIDRENDERING_COMPOSITE_MODE\nif (transmitted.a==0.) transmitted.a=thickness;\n#endif\nvec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); \nvec3 refractionColor=transmitted.rgb*transmittance;\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular;\n#else\nvec3 finalColor=refractionColor+specular;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfloat velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));\n#endif\nglFragColor=vec4(finalColor,transmitted.a);}\n",Object.defineProperty(ks.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),ks.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new bS(this)),this._fluidRenderer},ks.prototype.disableFluidRenderer=function(){this._fluidRenderer?.dispose(),this._fluidRenderer=null};class ES{constructor(e){this.name=ts.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(ts.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(ts.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){this.scene.fluidRenderer?._prepareRendering()}_afterCameraDraw(e){this.scene.fluidRenderer?._render(e)}rebuild(){const e=this.scene.fluidRenderer;if(!e)return;const t=new Set;for(let i=0;i{e._rebuild()}))}dispose(){this.scene.disableFluidRenderer()}}class bS{static _SceneComponentInitialization(e){let t=e._getComponent(ts.NAME_FLUIDRENDERER);t||(t=new ES(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,bS._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add((()=>{this._initialize()}))}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){const t=this._getParticleSystemIndex(e);return-1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,s){const r=new dS(this._scene,e);r.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),i||(i=new _S(this._scene,s),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==t&&(i.generateDiffuseTexture=t);const n={object:r,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,s,r){const n=new mS(this._scene,e,t);n.onParticleSizeChanged.add((()=>this._setParticleSizeForRenderTargets())),s||(s=new _S(this._scene,r),this.targetRenderers.push(s)),s._onUseVelocityChanged.hasObservers()||s._onUseVelocityChanged.add((()=>this._setUseVelocityForRenderObject())),void 0!==i&&(s.generateDiffuseTexture=i);const o={object:n,targetRenderer:s};return this.renderObjects.push(o),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),o}removeRenderObject(e,t=!0){const i=this.renderObjects.indexOf(e);return-1!==i&&(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort(((e,t)=>e.object.priorityt.object.priority?1:0))}_removeUnusedTargetRenderers(){const e={};for(let t=0;t{r.inputTexture.depthStencilTexture||r.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,n[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${r.name}`);for(const e of n){const t=e._thicknessRenderTarget?.renderTarget,i=t?.texture;if(t&&i){const e=i.width+"_"+i.height;let s=o[e];s||(s=o[e]=new xS(this._engine,i.width,i.height)),s.depthRTWrapper.shareDepth(t)}}}))}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value,s=this._cameras.get(t)[1],r=e.get(t);if(r)for(const e in s)r[1][e]||s[e].dispose();else for(const e in s)s[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){const e=new Map;for(let t=0;t{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)}))}_setUseVelocityForRenderObject(){for(const e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(const e of this.targetRenderers)if(e.needInitialization)return void this._initialize()}_render(e){for(let t=0;t{const t=e[1];for(const e in t)t[e].dispose()})),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class CS extends Do{constructor(){super(...arguments),this.RSMCREATE=!1,this.RSMCREATE_PROJTEXTURE=!1,this.RSMCREATE_LIGHT_IS_SPOT=!1}}class yS extends ah{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,yS.Name,300,new CS),this._lightColor=new Y,this._hasProjectionTexture=!1,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._varAlbedoName=e instanceof Cf?"surfaceAlbedo":"baseColor.rgb"}prepareDefines(e){e.RSMCREATE=this._isEnabled,this._hasProjectionTexture=!1;const t=this.light.getTypeID()===Gn.LIGHTTYPEID_SPOTLIGHT;if(t){const e=this.light;this._hasProjectionTexture=!!e.projectionTexture&&e.projectionTexture.isReady()}e.RSMCREATE_PROJTEXTURE=this._hasProjectionTexture,e.RSMCREATE_LIGHT_IS_SPOT=t}getClassName(){return"RSMCreatePluginMaterial"}getUniforms(){return{ubo:[{name:"rsmTextureProjectionMatrix",size:16,type:"mat4"},{name:"rsmSpotInfo",size:4,type:"vec4"},{name:"rsmLightColor",size:3,type:"vec3"},{name:"rsmLightPosition",size:3,type:"vec3"}],fragment:"#ifdef RSMCREATE\n uniform mat4 rsmTextureProjectionMatrix;\n uniform vec4 rsmSpotInfo;\n uniform vec3 rsmLightColor;\n uniform vec3 rsmLightPosition;\n #endif"}}getSamplers(e){e.push("rsmTextureProjectionSampler")}bindForSubMesh(e){if(this._isEnabled&&(this.light.diffuse.scaleToRef(this.light.getScaledIntensity(),this._lightColor),e.updateColor3("rsmLightColor",this._lightColor),this.light.getTypeID()===Gn.LIGHTTYPEID_SPOTLIGHT)){const t=this.light;this._hasProjectionTexture&&(e.updateMatrix("rsmTextureProjectionMatrix",t.projectionTextureMatrix),e.setTexture("rsmTextureProjectionSampler",t.projectionTexture));const i=U.Vector3[0];t.computeTransformedInformation()?(e.updateFloat3("rsmLightPosition",this.light.transformedPosition.x,this.light.transformedPosition.y,this.light.transformedPosition.z),t.transformedDirection.normalizeToRef(i)):(e.updateFloat3("rsmLightPosition",this.light.position.x,this.light.position.y,this.light.position.z),t.direction.normalizeToRef(i)),e.updateFloat4("rsmSpotInfo",i.x,i.y,i.z,Math.cos(.5*t.angle))}}getCustomCode(e){return"vertex"===e?null:{CUSTOM_FRAGMENT_BEGIN:"\n #ifdef RSMCREATE\n #extension GL_EXT_draw_buffers : require\n #endif\n ",CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RSMCREATE\n #ifdef RSMCREATE_PROJTEXTURE\n uniform highp sampler2D rsmTextureProjectionSampler; \n #endif\n layout(location = 0) out highp vec4 glFragData[3];\n vec4 glFragColor;\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR:`\n #ifdef RSMCREATE\n vec3 rsmColor = ${this._varAlbedoName} * rsmLightColor;\n #ifdef RSMCREATE_PROJTEXTURE\n {\n vec4 strq = rsmTextureProjectionMatrix * vec4(vPositionW, 1.0);\n strq /= strq.w;\n rsmColor *= texture2D(rsmTextureProjectionSampler, strq.xy).rgb;\n }\n #endif\n #ifdef RSMCREATE_LIGHT_IS_SPOT\n {\n float cosAngle = max(0., dot(rsmSpotInfo.xyz, normalize(vPositionW - rsmLightPosition)));\n rsmColor = sign(cosAngle - rsmSpotInfo.w) * rsmColor;\n }\n #endif\n glFragData[0] = vec4(vPositionW, 1.);\n glFragData[1] = vec4(normalize(normalW) * 0.5 + 0.5, 1.);\n glFragData[2] = vec4(rsmColor, 1.);\n #endif\n `}}}yS.Name="RSMCreate",ae([pe()],yS.prototype,"light",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],yS.prototype,"isEnabled",void 0),u("BABYLON.RSMCreatePluginMaterial",yS);Ft.ShadersStore.bilateralBlurPixelShader="uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec3 sampleColor=textureLod(textureSampler,vUV+coords*blurDir,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords*blurDir,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords*blurDir,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat r=dot(coords,coords);float w=exp(-r/two_sigma2);float depthDelta=abs(sampleDepth-depth);float wd=step(depthDelta,depthThreshold);vec3 normalDelta=abs(sampleNormal-normal);float wn=step(normalDelta.x+normalDelta.y+normalDelta.z,normalThreshold);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}\nglFragColor=vec4(sum/wsum,1.);}\n";Ft.ShadersStore.bilateralBlurQualityPixelShader="uniform sampler2D textureSampler;uniform sampler2D depthSampler;uniform sampler2D normalSampler;uniform int filterSize;uniform vec2 blurDir;uniform float depthThreshold;uniform float normalThreshold;varying vec2 vUV;void main(void) {vec3 color=textureLod(textureSampler,vUV,0.).rgb;float depth=textureLod(depthSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(color,1.);return;}\nvec3 normal=textureLod(normalSampler,vUV,0.).rgb;\n#ifdef DECODE_NORMAL\nnormal=normal*2.0-1.0;\n#endif\nfloat sigma=float(filterSize);float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sigmaNormal=normalThreshold;float two_sigmaNormal2=2.0*sigmaNormal*sigmaNormal;vec3 sum=vec3(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {for (int y=-filterSize; y<=filterSize; ++y) {vec2 coords=vec2(x,y)*blurDir;vec3 sampleColor=textureLod(textureSampler,vUV+coords,0.).rgb;float sampleDepth=textureLod(depthSampler,vUV+coords,0.).r;vec3 sampleNormal=textureLod(normalSampler,vUV+coords,0.).rgb;\n#ifdef DECODE_NORMAL\nsampleNormal=sampleNormal*2.0-1.0;\n#endif\nfloat r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepth-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);float rNormal=abs(sampleNormal.x-normal.x)+abs(sampleNormal.y-normal.y)+abs(sampleNormal.z-normal.z);float wn=exp(-rNormal*rNormal/two_sigmaNormal2);sum+=sampleColor*w*wd*wn;wsum+=w*wd*wn;}}\nglFragColor=vec4(sum/wsum,1.);}\n";Ft.ShadersStore.rsmGlobalIlluminationPixelShader="/**\n* The implementation is an application of the formula found in http:\n* For better results,it also adds a random (noise) rotation to the RSM samples (the noise artifacts are easier to remove than the banding artifacts).\n*/\nprecision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform vec4 rsmInfo2;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;uniform sampler2D rsmSamples;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nfloat mod289(float x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 mod289(vec4 x){return x-floor(x*(1.0/289.0))*289.0;}\nvec4 perm(vec4 x){return mod289(((x*34.0)+1.0)*x);}\nfloat noise(vec3 p){vec3 a=floor(p);vec3 d=p-a;d=d*d*(3.0-2.0*d);vec4 b=a.xxyy+vec4(0.0,1.0,0.0,1.0);vec4 k1=perm(b.xyxy);vec4 k2=perm(k1.xyxy+b.zzww);vec4 c=k2+a.zzzz;vec4 k3=perm(c);vec4 k4=perm(c+1.0);vec4 o1=fract(k3*(1.0/41.0));vec4 o2=fract(k4*(1.0/41.0));vec4 o3=o2*d.z+o1*(1.0-d.z);vec2 o4=o3.yw*d.x+o3.xz*(1.0-d.x);return o4.y*d.y+o4.x*(1.0-d.y);}\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);int numSamples=int(rsmInfo.x);float radius=rsmInfo.y;float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;float angle=noise(p*rsmInfo2.x);float c=cos(angle);float s=sin(angle);for (int i=0; i1. || uv.y<0. || uv.y>1.) continue;vec3 vplPositionW=textureLod(rsmPositionW,uv,0.).xyz;vec3 vplNormalW=textureLod(rsmNormalW,uv,0.).xyz*2.0-1.0;vec3 vplFlux=textureLod(rsmFlux,uv,0.).rgb;vplPositionW-=vplNormalW*edgeArtifactCorrection; \nfloat dist2=dot(vplPositionW-p,vplPositionW-p);indirectDiffuse+=vplFlux*weightSquare*max(0.,dot(n,vplPositionW-p))*max(0.,dot(vplNormalW,p-vplPositionW))/(dist2*dist2);}\nreturn clamp(indirectDiffuse*intensity,0.0,1.0);}\nvoid main(void) \n{vec3 positionW=texture2D(textureSampler,vUV).xyz;vec3 normalW=texture2D(normalSampler,vUV).xyz;\n#ifdef DECODE_NORMAL\nnormalW=normalW*2.0-1.0;\n#endif\n#ifdef TRANSFORM_NORMAL\nnormalW=(invView*vec4(normalW,0.)).xyz;\n#endif\ngl_FragColor.rgb=computeIndirect(positionW,normalW);gl_FragColor.a=1.0;}\n";Ft.ShadersStore.rsmFullGlobalIlluminationPixelShader="/**\n* The implementation is a direct application of the formula found in http:\n*/\nprecision highp float;varying vec2 vUV;uniform mat4 rsmLightMatrix;uniform vec4 rsmInfo;uniform sampler2D textureSampler;uniform sampler2D normalSampler;uniform sampler2D rsmPositionW;uniform sampler2D rsmNormalW;uniform sampler2D rsmFlux;\n#ifdef TRANSFORM_NORMAL\nuniform mat4 invView;\n#endif\nvec3 computeIndirect(vec3 p,vec3 n) {vec3 indirectDiffuse=vec3(0.);float intensity=rsmInfo.z;float edgeArtifactCorrection=rsmInfo.w;vec4 texRSM=rsmLightMatrix*vec4(p,1.);texRSM.xy/=texRSM.w;texRSM.xy=texRSM.xy*0.5+0.5;int width=int(rsmInfo.x);int height=int(rsmInfo.y);for (int j=0; j{t.pluginManager&&(t.pluginManager.getPlugin(IS.Name).isEnabled=e)})),this.recreateResources(!e))}get enableBlur(){return this._enableBlur}set enableBlur(e){e!==this._enableBlur&&(this._enableBlur=e,this.recreateResources())}get useQualityBlur(){return this._useQualityBlur}set useQualityBlur(e){e!==this._useQualityBlur&&(this._useQualityBlur=e,this.recreateResources())}get fullSizeBlur(){return this._forceFullSizeBlur}set fullSizeBlur(e){this._forceFullSizeBlur!==e&&(this._forceFullSizeBlur=e,this.recreateResources())}get useQualityUpsampling(){return this._useQualityUpsampling}set useQualityUpsampling(e){e!==this._useQualityUpsampling&&(this._useQualityUpsampling=e,this.recreateResources())}get showOnlyGI(){return this._showOnlyGI}set showOnlyGI(e){this._showOnlyGI!==e&&(this._showOnlyGI=e,this._debugLayer.isEnabled=e)}get use32BitsDepthBuffer(){return this._use32BitsDepthBuffer}set use32BitsDepthBuffer(e){this._use32BitsDepthBuffer!==e&&(this._use32BitsDepthBuffer=e,this.recreateResources())}setOutputDimensions(e){this._outputDimensions=e,this.recreateResources()}setGITextureDimensions(e){this._giTextureDimensions=e,this.recreateResources()}get giTextureType(){return this._giTextureType}set giTextureType(e){this._giTextureType!==e&&(this._giTextureType=e,this.recreateResources())}get giRSM(){return this._giRSM}addGIRSM(e){Array.isArray(e)?this._giRSM.push(...e):this._giRSM.push(e),this.recreateResources()}removeGIRSM(e){if(Array.isArray(e))for(let t=0;t{e.getTotalVertices()>0&&e.isEnabled()&&e.material&&this._addGISupportToMaterial(e.material)}))}get countersGPU(){return this._counters}recreateResources(e=!1){this._disposePostProcesses(e),this._createPostProcesses(),this._setPluginParameters()}generateSampleTexture(e){this._sampleTexture?.dispose(),this._maxSamples=e;const t=new Float32Array(4*this._maxSamples);for(let e=0;e{const e=this._engine._currentRenderTarget;let t=!1;if(this._enable){this.pause||(this._scene.postProcessManager.directRender(this._ppGlobalIllumination,this._ppGlobalIllumination[0].inputTexture),this._engine.unBindFramebuffer(this._ppGlobalIllumination[0].inputTexture,!0),this._engine.setAlphaMode(0),t=!0,this.enableBlur&&this._blurPostProcesses&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,this._blurRTT.renderTarget,!0),this._engine.unBindFramebuffer(this._blurRTT.renderTarget,!0)));for(let e=0;e{if(e.pluginManager){const t=e.pluginManager.getPlugin(IS.Name);t.textureGIContrib=this.enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height}}))}_createPostProcesses(){if(!this._enable)return;const e=13===this._giTextureType?4:5;this._firstActivation&&(this._firstActivation=!1,this._geomBufferEnabled=!!this._scene.geometryBufferRenderer,this._geomBufferEnablePosition=this._scene.geometryBufferRenderer?.enablePosition??!1),this._geomBufferEnabled||this._scene.disableGeometryBufferRenderer();const t=this._scene.enableGeometryBufferRenderer(this._enableBlur?this._outputDimensions:this._giTextureDimensions,this._use32BitsDepthBuffer?14:15,AS.GeometryBufferTextureTypesAndFormats);if(!t)throw new Error("Geometry buffer renderer is not supported but is required for GIRSMManager.");t.enablePosition=!0,this._geomBufferEnabled||(t.generateNormalsInWorldSpace=!0);const i=t.normalsAreUnsigned,s=t.generateNormalsInWorldSpace;this._counters.push({name:"Geometry buffer renderer",value:0}),this._countersRTW.push([this._scene.geometryBufferRenderer.getGBuffer().renderTarget]);let r="";i&&(r+="#define DECODE_NORMAL\n"),s||(r+="#define TRANSFORM_NORMAL\n");for(let i=0;i{e.setTexture("textureSampler",t.getGBuffer().textures[t.getTextureIndex(AT.POSITION_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(AT.NORMAL_TEXTURE_TYPE)]),e.setTexture("rsmPositionW",o.positionWorldTexture),e.setTexture("rsmNormalW",o.normalWorldTexture),e.setTexture("rsmFlux",o.fluxTexture),e.setMatrix("rsmLightMatrix",o.lightTransformationMatrix),n.useFullTexture?e.setFloat4("rsmInfo",o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height,n.intensity,n.edgeArtifactCorrection):(e.setTexture("rsmSamples",this._sampleTexture),e.setFloat4("rsmInfo",n.numSamples,n.radius,n.intensity,n.edgeArtifactCorrection),e.setFloat4("rsmInfo2",n.noiseFactor,n.rotateSample?1:0,o.fluxTexture.getInternalTexture().width,o.fluxTexture.getInternalTexture().height)),s||(this._tempMatrix.copyFrom(this._scene.activeCamera.getViewMatrix()),this._tempMatrix.invert(),e.setMatrix("invView",this._tempMatrix))}))}for(const e of this._ppGlobalIllumination)e.inputTexture||e.resize(this._giTextureDimensions.width,this._giTextureDimensions.height);if(this._counters.push({name:"GI generation",value:0}),this._countersRTW.push([this._ppGlobalIllumination[0].inputTexture]),this._enableBlur){const s=this._forceFullSizeBlur?this._outputDimensions:this._giTextureDimensions;this._blurRTT=new da("GIRSMContribution",this._outputDimensions,this._scene,{type:this._giTextureType,format:e,generateDepthBuffer:!1}),this._blurRTT.wrapU=0,this._blurRTT.wrapV=0,this._blurRTT.updateSamplingMode(1),this._blurRTT.skipInitialClear=!0;const r=[];if(this._counters.push({name:"GI blur",value:0}),this._countersRTW.push(r),this._blurXPostprocess=new Ko(this._useQualityBlur?"BilateralBlur":"BilateralBlurX",this._useQualityBlur?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._blurXPostprocess.onApplyObservable.add((e=>{e._bindTexture("textureSampler",this._ppGlobalIllumination[0].inputTexture.texture),e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(AT.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(AT.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",1/this._giTextureDimensions.width,this._useQualityBlur?1/this._giTextureDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurXPostprocess.externalTextureSamplerBinding=!0,this._blurXPostprocess.autoClear=!1,this._useQualityBlur||(this._blurYPostprocess=new Ko("BilateralBlurY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._blurYPostprocess.autoClear=!1,this._blurYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(AT.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(AT.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.blurKernel),e.setFloat2("blurDir",0,1/this._giTextureDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._blurYPostprocess.resize(s.width,s.height),r.push(this._blurYPostprocess.inputTexture)),this._blurPostProcesses=[this._blurXPostprocess],this._blurYPostprocess&&this._blurPostProcesses.push(this._blurYPostprocess),this._giTextureDimensions.width>=this._outputDimensions.width&&this._giTextureDimensions.height>=this._outputDimensions.height||this._forceFullSizeBlur)r.push(this._blurRTT.renderTarget);else{const n=[];this._counters.push({name:"GI upsampling",value:0}),this._countersRTW.push(n),this._upsamplingXPostprocess=new Ko(this._useQualityUpsampling?"BilateralUpsampling":"BilateralUpsamplingX",this._useQualityUpsampling?"bilateralBlurQuality":"bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:s,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._upsamplingXPostprocess.autoClear=!1,this._upsamplingXPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(AT.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(AT.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",1/this._outputDimensions.width,this._useQualityUpsampling?1/this._outputDimensions.height:0),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingXPostprocess.resize(s.width,s.height),r.push(this._upsamplingXPostprocess.inputTexture),this.useQualityUpsampling||(this._upsamplingYPostprocess=new Ko("BilateralUpsamplingY","bilateralBlur",{uniforms:["filterSize","blurDir","depthThreshold","normalThreshold"],samplers:["depthSampler","normalSampler"],defines:i?"#define DECODE_NORMAL":void 0,size:this._outputDimensions,samplingMode:2,engine:this._engine,textureType:this._giTextureType,textureFormat:e}),this._upsamplingYPostprocess.autoClear=!1,this._upsamplingYPostprocess.onApplyObservable.add((e=>{e.setTexture("depthSampler",t.getGBuffer().textures[t.getTextureIndex(AT.DEPTH_TEXTURE_TYPE)]),e.setTexture("normalSampler",t.getGBuffer().textures[t.getTextureIndex(AT.NORMAL_TEXTURE_TYPE)]),e.setInt("filterSize",this.upsamplerKernel),e.setFloat2("blurDir",0,1/this._outputDimensions.height),e.setFloat("depthThreshold",this.blurDepthThreshold),e.setFloat("normalThreshold",this.blurNormalThreshold)})),this._upsamplingYPostprocess.resize(this._outputDimensions.width,this._outputDimensions.height),n.push(this._upsamplingYPostprocess.inputTexture)),n.push(this._blurRTT.renderTarget),this._blurPostProcesses.push(this._upsamplingXPostprocess),this._upsamplingYPostprocess&&this._blurPostProcesses.push(this._upsamplingYPostprocess)}}this._debugLayer.texture?.dispose(),this._debugLayer.texture=new qn(this._scene,this._enableBlur?this._blurRTT.renderTarget.texture:this._ppGlobalIllumination[0].inputTexture.texture)}_addGISupportToMaterial(e){if(e.pluginManager?.getPlugin(IS.Name))return;const t=new IS(e);this._enable&&this._ppGlobalIllumination.length>0&&(t.textureGIContrib=this._ppGlobalIllumination[0].inputTexture.texture,t.outputTextureWidth=this._outputDimensions.width,t.outputTextureHeight=this._outputDimensions.height),t.isEnabled=this._enable,this._materialsWithRenderPlugin.push(e)}}AS.GeometryBufferTextureTypesAndFormats={0:{textureType:2,textureFormat:6},1:{textureType:11,textureFormat:5},2:{textureType:2,textureFormat:5}};class RS extends Do{constructor(){super(...arguments),this.RENDER_WITH_GIRSM=!1,this.RSMCREATE_PROJTEXTURE=!1}}class IS extends ah{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e){super(e,IS.Name,310,new RS),this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._isPBR=e instanceof Cf}prepareDefines(e){e.RENDER_WITH_GIRSM=this._isEnabled}getClassName(){return"GIRSMRenderPluginMaterial"}getUniforms(){return{ubo:[{name:"girsmTextureOutputSize",size:2,type:"vec2"}],fragment:"#ifdef RENDER_WITH_GIRSM\n uniform vec2 girsmTextureOutputSize;\n #endif"}}getSamplers(e){e.push("girsmTextureGIContrib")}bindForSubMesh(e){this._isEnabled&&(e.bindTexture("girsmTextureGIContrib",this.textureGIContrib),e.updateFloat2("girsmTextureOutputSize",this.outputTextureWidth,this.outputTextureHeight))}getCustomCode(e){const t={CUSTOM_FRAGMENT_DEFINITIONS:"\n #ifdef RENDER_WITH_GIRSM\n uniform sampler2D girsmTextureGIContrib;\n\n vec3 computeIndirect() {\n vec2 uv = gl_FragCoord.xy / girsmTextureOutputSize;\n return texture2D(girsmTextureGIContrib, uv).rgb;\n }\n #endif\n ",CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:"\n #ifdef RENDER_WITH_GIRSM\n finalDiffuse += computeIndirect() * surfaceAlbedo.rgb;\n #endif\n "};return this._isPBR||(t.CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR="\n #ifdef RENDER_WITH_GIRSM\n color.rgb += computeIndirect() * baseColor.rgb;\n #endif\n "),"vertex"===e?null:t}}IS.Name="GIRSMRender",ae([pe()],IS.prototype,"textureGIContrib",void 0),ae([pe()],IS.prototype,"outputTextureWidth",void 0),ae([pe()],IS.prototype,"outputTextureHeight",void 0),ae([pe(),de("_markAllSubMeshesAsTexturesDirty")],IS.prototype,"isEnabled",void 0),u("BABYLON.GIRSMRenderPluginMaterial",IS);Ft.ShadersStore.spriteMapPixelShader="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nprecision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4(\ntexture2D(frameMap,vec2(fX,0.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*1.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*2.),0.),\nvec4(0.)\n);}\nvoid main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV);\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\nvec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; fmt){frameID=animationData.x;break;}\nanimationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}}\nmat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;}\nvec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}}\ncolor.xyz*=colorMul;gl_FragColor=color;}";var PS;Ft.ShadersStore.spriteMapVertexShader="precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; \ngl_Position=worldViewProjection*p;}",function(e){e[e.INIT=0]="INIT",e[e.RUNNING=1]="RUNNING",e[e.DONE=2]="DONE",e[e.ERROR=3]="ERROR"}(PS||(PS={})),g.prototype.notifyObserversWithPromise=async function(e,t=-1,i,s,r){let n=Promise.resolve(e);if(!this.observers.length)return n;const o=this._eventState;return o.mask=t,o.target=i,o.currentTarget=s,o.skipNextObservers=!1,o.userInfo=r,this.observers.forEach((i=>{o.skipNextObservers||i._willBeUnregistered||i.mask&t&&(n=i.scope?n.then((t=>(o.lastReturnValue=t,i.callback.apply(i.scope,[e,o])))):n.then((t=>(o.lastReturnValue=t,i.callback(e,o)))),i.unregisterOnNextCall&&this._deferUnregister(i))})),await n,e};class MS{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class DS extends MS{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof Un))return!1;const t=e;return!(t.isDisposed()||!t.isVisible||!t.isEnabled()||t.instances.length>0||t.skeleton||t.hasLODLevels||0===t.getTotalVertices())}}static get UpdateSelectionTree(){return DS._UpdateSelectionTree}static set UpdateSelectionTree(e){DS._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const s=e.meshes.slice(0);let r=s.length;for(let e=0;e{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),OS[e.id]=!0)},wS=(e,t)=>{const i={},s=e._geometry;return s&&(e.getScene().getGeometryById(s.id)||NS(s,t.geometries)),e.serialize&&e.serialize(i),i};class FS{static ClearCache(){OS=[]}static Serialize(e){return FS._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&Zn.ForceSerializeBuffers&&J.Warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),FS.ClearCache(),i.useDelayedTextureLoading=e.useDelayedTextureLoading,i.autoClear=e.autoClear,i.clearColor=e.clearColor.asArray(),i.ambientColor=e.ambientColor.asArray(),i.gravity=e.gravity.asArray(),i.collisionsEnabled=e.collisionsEnabled,i.useRightHandedSystem=e.useRightHandedSystem,void 0!==e.fogMode&&null!==e.fogMode&&(i.fogMode=e.fogMode),void 0!==e.fogColor&&null!==e.fogColor&&(i.fogColor=e.fogColor.asArray()),void 0!==e.fogStart&&null!==e.fogStart&&(i.fogStart=e.fogStart),void 0!==e.fogEnd&&null!==e.fogEnd&&(i.fogEnd=e.fogEnd),void 0!==e.fogDensity&&null!==e.fogDensity&&(i.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){const t=e.getPhysicsEngine();t&&(i.physicsEnabled=!0,i.physicsGravity=t.gravity.asArray(),i.physicsEngine=t.getPhysicsPluginName())}e.metadata&&(i.metadata=e.metadata),i.morphTargetManagers=[];for(const t of e.meshes){const e=t.morphTargetManager;e&&i.morphTargetManagers.push(e.serialize())}let s,r,n;for(i.lights=[],s=0;s0){i.animationGroups=[];for(let t=0;t0)for(i.reflectionProbes=[],s=0;st))}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=t))):(s instanceof Object||Array.isArray(s))&&this._CollectPromises(s,t)}else if(e instanceof Object)for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const s=e[i];s instanceof Promise?t.push(s.then((t=>e[i]=t))):(s instanceof Object||Array.isArray(s))&&this._CollectPromises(s,t)}}static SerializeMesh(e,t=!1,i=!1){const s={meshes:[],transformNodes:[],cameras:[],lights:[]};if(FS.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let s=0;s{e.indexOf(t)<0&&!t.doNotSerialize&&e.push(t)})),t&&e[s].parent&&e.indexOf(e[s].parent)<0&&!e[s].parent.doNotSerialize&&e.push(e[s].parent);return e.forEach((e=>{((e,t)=>{if(e._isMesh){const i=e;if(1===i.delayLoadState||0===i.delayLoadState){const e=e=>{t.materials=t.materials||[],i.material&&!t.materials.some((e=>e.id===i.material.id))&&t.materials.push(e.serialize())};if(i.material&&!i.material.doNotSerialize)if(i.material instanceof On){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some((e=>e.id===i.material.id))){t.multiMaterials.push(i.material.serialize());for(const t of i.material.subMaterials)t&&e(t)}}else e(i.material);else i.material||e(i.getScene().defaultMaterial);const s=i._geometry;s&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),NS(s,t.geometries)),i.skeleton&&!i.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(i.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(wS(i,t))}}else if("TransformNode"===e.getClassName()){const i=e;t.transformNodes.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Camera")){const i=e;t.cameras.push(i.serialize())}else if(-1!==e.getClassName().indexOf("Light")){const i=e;t.lights.push(i.serialize())}})(e,s)})),s}}class LS{static IsSupported(e,t){const i=t??e.getRenderingCanvas();return!!i&&"function"==typeof i.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!LS.IsSupported(e,t.canvas))throw"Your browser does not support recording so far.";const i=t.canvas??e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options={...LS._DefaultOptions,...t};const s=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const e of this._options.audioTracks)s.addTrack(e);this._mediaRecorder=new MediaRecorder(s,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=e=>this._handleDataAvailable(e),this._mediaRecorder.onerror=e=>this._handleError(e),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout((()=>{this.stopRecording()}),1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),!this._reject)throw new e.error;this._reject(e.error)}_handleStop(){this.stopRecording();const e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&Ii.Download(e,this._fileName)}}LS._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let BS=null;function VS(e,t,i,s,r="image/png",n=!1,o){const{height:a,width:l}=kS(e,t,i);if(!a||!l)return void J.Error("Invalid 'size' parameter !");BS||(BS=document.createElement("canvas")),BS.width=l,BS.height=a;const h=BS.getContext("2d"),c=e.getRenderWidth()/e.getRenderHeight();let u=l,d=u/c;d>a&&(d=a,u=d*c);const p=Math.max(0,l-u)/2,f=Math.max(0,a-d)/2;t.getScene().activeCamera!==t?US(e,t,i,(e=>{if(n){const t=new Blob([e]);Ii.DownloadBlob(t),s&&s("")}else s&&s(e)}),r,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,o):e.onEndFrameObservable.addOnce((()=>{const t=e.getRenderingCanvas();h&&t&&h.drawImage(t,p,f,u,d),BS&&(n?(Ii.EncodeScreenshotCanvasData(BS,void 0,r,void 0,o),s&&s("")):Ii.EncodeScreenshotCanvasData(BS,s,r,void 0,o))}))}function US(e,t,i,s,r="image/png",n=1,o=!1,a,l=!1,h=!1,c=!0,u,d){const{height:p,width:f,finalWidth:_,finalHeight:m}=kS(e,t,i),g={width:f,height:p};if(!p||!f)return void J.Error("Invalid 'size' parameter !");const v={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(f,p);const x=t.getScene(),T=new da("screenShot",g,x,!1,!1,0,!1,Zn.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,n);T.renderList=x.meshes.slice(),T.samples=n,T.renderSprites=l,T.activeCamera=t,T.forceLayerMaskCheck=c,d?.(T);const S=()=>{T.isReadyForRendering()&&t.isReady(!0)?(e.onEndFrameObservable.addOnce((()=>{_===f&&m===p?T.readPixels(void 0,void 0,void 0,!1).then((e=>{ua.DumpData(f,p,e,s,r,a,!0,void 0,u),T.dispose()})):eu("pass",T.getInternalTexture(),x,void 0,void 0,void 0,_,m).then((t=>{e._readTexturePixels(t,_,m,-1,0,null,!0,!1,0,0).then((e=>{ua.DumpData(_,m,e,s,r,a,!0,void 0,u),t.dispose()}))}))})),T.render(!0),x.incrementRenderId(),x.resetCachedMaterial(),e.setSize(v.width,v.height),t.getProjectionMatrix(!0),x.render()):setTimeout(S,16)},E=()=>{x.incrementRenderId(),x.resetCachedMaterial(),S()};if(o){const e=new ET("antialiasing",1,x.activeCamera);T.addPostProcess(e),e.getEffect().isReady()?E():e.getEffect().onCompiled=()=>{E()}}else E()}function kS(e,t,i){let s=0,r=0,n=0,o=0;if("object"==typeof i){const a=i.precision?Math.abs(i.precision):1;i.width&&i.height?(s=i.height*a,r=i.width*a):i.width&&!i.height?(r=i.width*a,s=Math.round(r/e.getAspectRatio(t))):i.height&&!i.width?(s=i.height*a,r=Math.round(s*e.getAspectRatio(t))):(r=Math.round(e.getRenderWidth()*a),s=Math.round(r/e.getAspectRatio(t))),i.finalWidth&&i.finalHeight?(o=i.finalHeight,n=i.finalWidth):i.finalWidth&&!i.finalHeight?(n=i.finalWidth,o=Math.round(n/e.getAspectRatio(t))):i.finalHeight&&!i.finalWidth?(o=i.finalHeight,n=Math.round(o*e.getAspectRatio(t))):(n=r,o=s)}else isNaN(i)||(s=i,r=i,n=i,o=i);return r&&(r=Math.floor(r)),s&&(s=Math.floor(s)),n&&(n=Math.floor(n)),o&&(o=Math.floor(o)),{height:0|s,width:0|r,finalWidth:0|n,finalHeight:0|o}}var GS,zS;Ii.CreateScreenshot=VS,Ii.CreateScreenshotAsync=function(e,t,i,s="image/png",r){return new Promise(((n,o)=>{VS(e,t,i,(e=>{void 0!==e?n(e):o(new Error("Data is undefined"))}),s,void 0,r)}))},Ii.CreateScreenshotUsingRenderTarget=US,Ii.CreateScreenshotUsingRenderTargetAsync=function(e,t,i,s="image/png",r=1,n=!1,o,a=!1,l=!1,h=!0,c){return new Promise(((u,d)=>{US(e,t,i,(e=>{void 0!==e?u(e):d(new Error("Data is undefined"))}),s,r,n,o,a,l,h,c)}))},function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String",e[e.Button=6]="Button",e[e.Options=7]="Options",e[e.Tab=8]="Tab",e[e.FileButton=9]="FileButton",e[e.Vector2=10]="Vector2"}(GS||(GS={}));class WS{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch{const e={};return{getItem:t=>{const i=e[t];return void 0===i?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){const i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){const i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){const i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}WS._Storage=WS._GetStorage(),function(e){class t{serialize(){const e={},t=new Array(this._characterToIdx.size);return this._characterToIdx.forEach(((e,i)=>{t[e]=i})),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){const i=JSON.parse(e),s=new t(i.characters);return s._insertionCosts=i.insertionCosts,s._deletionCosts=i.deletionCosts,s._substitutionCosts=i.substitutionCosts,s}constructor(e,t=null,i=null,s=null){let r;t=t??(()=>1),i=i??(()=>1),s=s??((e,t)=>e===t?0:1),this._characterToIdx=new Map,this._insertionCosts=new Array(e.length),this._deletionCosts=new Array(e.length),this._substitutionCosts=new Array(e.length);for(let n=0;ni._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+i._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map((e=>this._alphabet.getCharacterIdx(e)))}distance(e){return i._Distance(this,e)}static _Distance(e,t){const s=e._alphabet;if(s!==t._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const r=e._characters,n=t._characters,o=r.length,a=n.length,l=i._CostMatrix;l[0][0]=0;for(let e=0;enew Array(i._MAX_SEQUENCE_LENGTH+1))),e.Sequence=i}(zS||(zS={}));class HS{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new HS(t._segmentLength);return i._points=t._points.map((e=>new w(e._x,e._y,e._z))),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{const i=()=>this._segmentLength/w.Distance(this._points[t-1],e);for(let s=i();s<=1;s=i()){const i=this._points[t-1].scale(1-s);e.scaleAndAddToRef(s,i),this._points.push(i),++t}}}resampleAtTargetResolution(e){const t=new HS(this.getLength()/e);return this._points.forEach((e=>{t.add(e)})),t}tokenize(e){const t=[],i=new w;for(let s=2;s.98||(w.CrossToRef(HS._ForwardDir,HS._InverseFromVec,HS._UpDir),HS._UpDir.normalize(),B.LookAtLHToRef(e,t,HS._UpDir,HS._LookMatrix),i.subtractToRef(t,HS._FromToVec),HS._FromToVec.normalize(),w.TransformNormalToRef(HS._FromToVec,HS._LookMatrix,s),0))}static _TokenizeSegment(e,t){HS._BestMatch=0,HS._Score=w.Dot(e,t[0]),HS._BestScore=HS._Score;for(let i=1;iHS._BestScore&&(HS._BestMatch=i,HS._BestScore=HS._Score);return HS._BestMatch}}HS._ForwardDir=new w,HS._InverseFromVec=new w,HS._UpDir=new w,HS._FromToVec=new w,HS._LookMatrix=new B;class XS{serialize(){return JSON.stringify(this._sequences.map((e=>e.serialize())))}static Deserialize(e,t){const i=new XS;return i._sequences=JSON.parse(e).map((e=>zS.Sequence.Deserialize(e,t))),i}static CreateFromTrajectory(e,t,i){return XS.CreateFromTokenizationPyramid(XS._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new XS;return i._sequences=e.map((e=>new zS.Sequence(e,t))),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=XS._FINEST_DESCRIPTOR_RESOLUTION){const s=[];for(let r=i;r>4;r=Math.floor(r/2))s.push(e.resampleAtTargetResolution(r).tokenize(t.chars));return s}distance(e){let t,i=0;for(let s=0;se.serialize())),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),s=new YS;return s._descriptors=i.descriptors.map((e=>XS.Deserialize(e,t))),s._centroidIdx=i.centroidIdx,s._averageDistance=i.averageDistance,s}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map((t=>t.distance(e))))}_refreshDescription(){let e;this._centroidIdx=-1;const t=this._descriptors.map((t=>(e=0,this._descriptors.forEach((i=>{e+=t.distance(i)})),e)));for(let e=0;e{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])})),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,YS._MIN_AVERAGE_DISTANCE))}}YS._MIN_AVERAGE_DISTANCE=1;class jS{constructor(e,t,i){this._scene=e,J.Log(`[Reflector] Connecting to ws://${t}:${i}`),this._webSocket=new WebSocket(`ws://${t}:${i}`),this._webSocket.onmessage=e=>{const t=e.data;if(t.startsWith(jS._SERVER_PREFIX)){const e=t.substr(jS._SERVER_PREFIX.length);return J.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),void this._handleServerMessage(e)}J.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{J.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&FS.SerializeAsync(this._scene).then((e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)}))}_handleClientMessage(){}}jS._SERVER_PREFIX="$$";class $S{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){const e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}}const KS=1800,qS="timestamp",QS="numPoints",ZS=/\r/g;class JS{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const e=je.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength;let s=0;if(i>0){const e=this.datasets.startingIndices.at(i-1);s=e+this.datasets.data.at(e+JS.NumberOfPointsOffset)+JS.SliceDataOffset}if(this.datasets.startingIndices.push(s),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach((e=>{const t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())})),this.datasetObservable.hasObservers()){const i=[e,t];for(let e=0;ee.callback(this._datasetMeta,new _(0)))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&(this._strategies.get(e)?.dispose(),this._strategies.delete(e));const s={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,s=0;const r=t.onAfterRenderObservable.add((()=>{s=i,i=0})),n=this._customEventObservable.add((t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)}));return{id:e,getData:()=>s,dispose:()=>{t.onAfterRenderObservable.remove(r),this._customEventObservable.remove(n)}}},category:i}),s}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach((e=>{this.registerEvent(e,!0)}))}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:s}of e){const e=t(this._scene);this._strategies.has(e.id)?e.dispose():(this.datasets.ids.push(e.id),i&&(i=i.replace(new RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:s}),this._strategies.set(e.id,e))}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i>e&255).toString(16)).substr(-2);return i}getCurrentSlice(){const e=[je.Now-this._startingTimestamp,this.datasets.ids.length];this.datasets.ids.forEach((t=>{const i=this._strategies.get(t);i&&this.datasetObservable.hasObservers()&&e.push(i.getData())})),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(e)}updateMetadata(e,t,i){const s=this._datasetMeta.get(e);s&&(s[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new $S(KS),this.datasets.ids.length=0,this.datasets.startingIndices=new $S(KS),this._datasetMeta.clear(),this._strategies.forEach((e=>e.dispose())),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){const i=e.replace(ZS,"").split("\n").map((e=>e.split(",").filter((e=>e.length>0)))).filter((e=>e.length>0)),s=JS.NumberOfPointsOffset;if(i.length<2)return!1;const r={ids:[],data:new $S(KS),startingIndices:new $S(KS)},[n,...o]=i;if(n.length<2||n[0]!==qS||n[s]!==QS)return!1;const a=new Map;for(let e=JS.SliceDataOffset;ee.dispose())),this._strategies.clear(),!t)for(const e of this.datasets.ids){const t=a.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${qS},${QS}`;for(let t=0;t{e.dispose()})),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}ks.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new JS(this)),this._perfCollector},g.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){const e=function(e){const t=new Array,i=new Array,s=new Array,r=e.add((()=>{const e=t.length;for(let r=0;r{t.push(e),i.push(r),s.push(n)},dispose:()=>{e.remove(r)}}}(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return rr(e,this._coroutineScheduler)},g.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};Ft.ShadersStore.equirectangularPanoramaPixelShader="#ifdef GL_ES\nprecision highp float;\n#endif\n#define M_PI 3.1415926535897932384626433832795\nvarying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3(\n- sin( longitude )*sin( latitude ),\ncos( latitude ),\n- cos( longitude )*sin( latitude )\n);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}";class eE extends _o{constructor(e,t={}){super(e),this.options=t,this._direction=new w(0,0,-1),this._mat=new B,this._onSelectEnabled=!1,this._origin=new w(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new g,this._onHitTestResults=e=>{const t=e.map((e=>{const t=B.FromArray(e.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&t.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}}));this.lastNativeXRHitResults=e,this.onHitTestResultObservable.notifyObservers(t)},this._onSelect=e=>{this._onSelectEnabled&&eE.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",Ii.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,s){return e.requestHitTest(t,i).then((e=>{const t=s||(e=>!!e.hitMatrix);return e.filter(t)}))}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const s=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,s,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;B.FromArrayToRef(t.transform.matrix,0,this._mat),w.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),w.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();const i=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});eE.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}eE.Name=po.HIT_TEST,eE.Version=1,fo.AddWebXRFeature(eE.Name,((e,t)=>()=>new eE(e,t)),eE.Version,!1);let tE=0;class iE extends _o{set referenceSpaceForFrameAnchors(e){this._referenceSpaceForFrameAnchors=e}constructor(e,t={}){super(e),this._options=t,this._lastFrameDetected=new Set,this._trackedAnchors=[],this._futureAnchors=[],this.onAnchorAddedObservable=new g,this.onAnchorRemovedObservable=new g,this.onAnchorUpdatedObservable=new g,this._tmpVector=new w,this._tmpQuaternion=new L,this.xrNativeFeatureName="anchors"}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new w,i=new L){this._populateTmpTransformation(t,i);const s=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(!e.xrHitResult.createAnchor)throw this.detach(),new Error("Anchors not enabled in this environment/browser");try{const t=await e.xrHitResult.createAnchor(s);return new Promise(((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:s,resolve:e,reject:i})}))}catch(e){throw new Error(e)}}async addAnchorAtPositionAndRotationAsync(e,t=new L,i=!1){this._populateTmpTransformation(e,t);const s=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),r=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(s,this._xrSessionManager.currentFrame):void 0;return new Promise(((e,t)=>{this._futureAnchors.push({nativeAnchor:r,resolved:!1,submitted:!1,xrTransformation:s,resolve:e,reject:t})}))}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){const e=this._trackedAnchors.pop();if(e){try{e.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(e)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;const t=e.trackedAnchors;if(t){const i=this._trackedAnchors.filter((e=>!t.has(e.xrAnchor))).map((e=>this._trackedAnchors.indexOf(e)));let s=0;i.forEach((e=>{const t=this._trackedAnchors.splice(e-s,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),s++})),t.forEach((t=>{if(this._lastFrameDetected.has(t)){const i=this._findIndexInAnchorArray(t),s=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,s,e),s.attachedNode&&(s.attachedNode.rotationQuaternion=s.attachedNode.rotationQuaternion||new L,s.transformationMatrix.decompose(s.attachedNode.scaling,s.attachedNode.rotationQuaternion,s.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(s)}catch(e){Ii.Warn("Anchor could not be updated")}}else{const i={id:tE++,xrAnchor:t,remove:()=>t.delete()},s=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(s),this.onAnchorAddedObservable.notifyObservers(s);const r=this._futureAnchors.filter((e=>e.nativeAnchor===t))[0];r&&(r.resolve(s),r.resolved=!0)}})),this._lastFrameDetected=t}this._futureAnchors.forEach((t=>{t.resolved||t.submitted||(this._createAnchorAtTransformation(t.xrTransformation,e).then((e=>{t.nativeAnchor=e}),(e=>{t.resolved=!0,t.reject(e)})),t.submitted=!0)}))}_findIndexInAnchorArray(e){for(let t=0;t()=>new iE(e,t)),iE.Version);let sE=0;class rE extends _o{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new g,this.onPlaneRemovedObservable=new g,this.onPlaneUpdatedObservable=new g,this.xrNativeFeatureName="plane-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){if(!super.detach())return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){const e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return"undefined"!=typeof XRPlane}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.detectedPlanes||e.worldInformation?.detectedPlanes;if(t){for(let e=0;e{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._findIndexInPlaneArray(t),s=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,s,e),this.onPlaneUpdatedObservable.notifyObservers(s)}}else{const i={id:sE++,xrPlane:t,polygonDefinition:[]},s=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(s),this.onPlaneAddedObservable.notifyObservers(s)}})),this._lastFrameDetected=t}}_init(){const e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),this._xrSessionManager.session.updateWorldTrackingState?(this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()):e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map((e=>{const t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new w(e.x,e.y,e.z*t)}));const s=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(s){const e=t.transformationMatrix||new B;B.FromArrayToRef(s.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new rE(e,t)),rE.Version);class nE extends _o{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new g}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){const t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper)if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){const i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){const i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{const i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach((t=>t.setEnabled(e))),this.onBackgroundStateChangedObservable.notifyObservers(e)}}nE.Name=po.BACKGROUND_REMOVER,nE.Version=1,fo.AddWebXRFeature(nE.Name,((e,t)=>()=>new nE(e,t)),nE.Version,!0);class oE extends _o{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||go.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,s=nc("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});s.isVisible=this._debugMode,s.isPickable=!1,s.rotationQuaternion=new L;const r=e.grip||e.pointer;s.position.copyFrom(r.position),s.rotationQuaternion.copyFrom(r.rotationQuaternion);const n=new go(s,t,{mass:0,...this._options.physicsProperties});this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:s}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||J.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce((t=>{t._doNotLoadControllerMesh?this._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce((()=>{const i=new go(t.rootMesh,go.MeshImpostor,{mass:0,...this._options.physicsProperties}),s=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:s.position.clone(),oldRotation:s.rotationQuaternion.clone()}}))})):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new L,this._tmpVector=new w,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e];t.impostorMesh&&(t.impostorMesh.isVisible=!0)}))}addController(e){this._attachController(e)}attach(){if(!super.attach())return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._options.enableHeadsetImpostor){const e=this._options.headsetImpostorParams||{impostorType:go.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=nc("headset-mesh",{diameterX:"number"==typeof t?t:t.width,diameterY:"number"==typeof t?t:t.height,diameterZ:"number"==typeof t?t:t.depth}),this._headsetMesh.rotationQuaternion=new L,this._headsetMesh.isVisible=!1,this._headsetImpostor=new go(this._headsetMesh,e.impostorType,{mass:0,...e})}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._headsetMesh&&this._headsetMesh.dispose(),!0)}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){const t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties={...this._options.physicsProperties,...e}}_onXRFrame(e){if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),this._options.xrInput.xrCamera._lastXRViewerPose?.linearVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(this._options.xrInput.xrCamera._lastXRViewerPose?.angularVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e],i=t.xrController.grip||t.xrController.pointer,s=t.oldPos||t.impostorMesh.position;if(t.xrController._lastXRPose?.linearVelocity){const e=t.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setLinearVelocity(this._tmpVector)}else i.position.subtractToRef(s,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),t.impostor.setLinearVelocity(this._tmpVector);s.copyFrom(i.position),this._debugMode&&J.Log([this._tmpVector,"linear"]);const r=t.oldRotation||t.impostorMesh.rotationQuaternion;if(t.xrController._lastXRPose?.angularVelocity){const e=t.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),t.impostor.setAngularVelocity(this._tmpVector)}else if(!r.equalsWithEpsilon(i.rotationQuaternion)){r.conjugateInPlace().multiplyToRef(i.rotationQuaternion,this._tmpQuaternion);const e=Math.sqrt(this._tmpQuaternion.x*this._tmpQuaternion.x+this._tmpQuaternion.y*this._tmpQuaternion.y+this._tmpQuaternion.z*this._tmpQuaternion.z);if(this._tmpVector.set(this._tmpQuaternion.x,this._tmpQuaternion.y,this._tmpQuaternion.z),e<.001)this._tmpVector.scaleInPlace(2);else{const t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}t.impostor.setAngularVelocity(this._tmpVector)}r.copyFrom(i.rotationQuaternion),this._debugMode&&J.Log([this._tmpVector,this._tmpQuaternion,"angular"])}))}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}oE.Name=po.PHYSICS_CONTROLLERS,oE.Version=1,fo.AddWebXRFeature(oE.Name,((e,t)=>()=>new oE(e,t)),oE.Version,!0);class aE extends _o{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new B,this._tmpPos=new w,this._tmpQuat=new L,this._initHitTestSource=e=>{if(!e)return;const t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),i.space?this._xrSessionManager.session.requestHitTestSource(i).then((e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})):Ii.Warn("waiting for viewer reference space to initialize")},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new g,this.paused=!1,this.xrNativeFeatureName="hit-test",Ii.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach())return!1;if(!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){const e=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:e,entityTypes:this.options.entityTypes}).then((e=>{this._transientXrHitTestSource=e}))}return!0}detach(){return!!super.detach()&&(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(this.attached&&!this.paused){if(this._xrHitTestSource){const t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}this._transientXrHitTestSource&&e.getHitTestResultsForTransientInput(this._transientXrHitTestSource).forEach((e=>{this._processWebXRHitTestResult(e.results,e.inputSource)}))}}_processWebXRHitTestResult(e,t){const i=[];e.forEach((e=>{const s=e.getPose(this._xrSessionManager.referenceSpace);if(!s)return;const r=s.transform.position,n=s.transform.orientation;this._tmpPos.set(r.x,r.y,r.z).scaleInPlace(this._xrSessionManager.worldScalingFactor),this._tmpQuat.set(n.x,n.y,n.z,n.w),B.FromFloat32ArrayToRefScaled(s.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());const o={position:this.autoCloneTransformation?this._tmpPos.clone():this._tmpPos,rotationQuaternion:this.autoCloneTransformation?this._tmpQuat.clone():this._tmpQuat,transformationMatrix:this.autoCloneTransformation?this._tmpMat.clone():this._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:e};i.push(o)})),this.onHitTestResultObservable.notifyObservers(i)}}aE.Name=po.HIT_TEST,aE.Version=2,fo.AddWebXRFeature(aE.Name,((e,t)=>()=>new aE(e,t)),aE.Version,!1);class lE extends _o{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new g,this.onFeaturePointsUpdatedObservable=new g,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this.featurePointCloud.length=0,!0)}dispose(){super.dispose(),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw new Error("Received malformed feature point cloud of length: "+t.length);const e=t.length/5,i=[],s=[];for(let r=0;r0&&this.onFeaturePointsAddedObservable.notifyObservers(s),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}}lE.Name=po.FEATURE_POINTS,lE.Version=1,fo.AddWebXRFeature(lE.Name,(e=>()=>new lE(e)),lE.Version);let hE=0;class cE extends _o{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new g,this.onMeshRemovedObservable=new g,this.onMeshUpdatedObservable=new g,this.xrNativeFeatureName="mesh-detection",this._options.generateMeshes&&(this._options.convertCoordinateSystems=!0),this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach((e=>{this.onMeshRemovedObservable.notifyObservers(e)})),this._detectedMeshes.clear()),!0)}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){try{if(!this.attached||!e)return;const t=e.detectedMeshes||e.worldInformation?.detectedMeshes;if(t){const i=new Set;this._detectedMeshes.forEach(((e,s)=>{t.has(s)||i.add(s)})),i.forEach((e=>{const t=this._detectedMeshes.get(e);t&&(this.onMeshRemovedObservable.notifyObservers(t),this._detectedMeshes.delete(e))})),t.forEach((t=>{if(this._detectedMeshes.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{const i={id:hE++,xrMesh:t},s=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,s),this.onMeshAddedObservable.notifyObservers(s)}}))}}catch(e){J.Log(e.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;const s=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=s,t.normals=e.normals;else{t.positions=new Float32Array(s.length);for(let e=0;e()=>new cE(e,t)),cE.Version,!1),function(e){e[e.NotReceived=0]="NotReceived",e[e.Waiting=1]="Waiting",e[e.Received=2]="Received"}(uE||(uE={}));class dE extends _o{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new g,this.onTrackableImageFoundObservable=new g,this.onTrackedImageUpdatedObservable=new g,this._trackableScoreStatus=uE.NotReceived,this._trackedImages=[],this.xrNativeFeatureName="image-tracking"}attach(){return super.attach()}detach(){return super.detach()}getTrackedImageById(e){return this._trackedImages[e]||null}dispose(){super.dispose(),this._trackedImages.forEach((e=>{e.originalBitmap.close()})),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()}async getXRSessionInitExtension(){if(!this.options.images||!this.options.images.length)return{};const e=this.options.images.map((e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src)));try{const t=await Promise.all(e);return this._originalTrackingRequest=t.map(((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth}))),{trackedImages:this._originalTrackingRequest}}catch(e){return Ii.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===uE.Waiting)return;if(this._trackableScoreStatus===uE.NotReceived)return void this._checkScoresAsync();const t=e.getImageTrackingResults();for(const i of t){let t=!1;const s=i.index,r=this._trackedImages[s];if(!r)continue;r.xrTrackingResult=i,r.realWorldWidth!==i.measuredWidthInMeters&&(r.realWorldWidth=i.measuredWidthInMeters,t=!0);const n=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(n){const e=r.transformationMatrix;B.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}const o="emulated"===i.trackingState;r.emulated!==o&&(r.emulated=o,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(r)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==uE.NotReceived)return;this._trackableScoreStatus=uE.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(e&&0!==e.length){for(let t=0;t0?uE.Received:uE.NotReceived}else this._trackableScoreStatus=uE.NotReceived}}dE.Name=po.IMAGE_TRACKING,dE.Version=1,fo.AddWebXRFeature(dE.Name,((e,t)=>()=>new dE(e,t)),dE.Version,!1);class pE extends _o{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",Ii.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!(!super.attach()||!this._xrSessionManager.session.domOverlayState||null===this._xrSessionManager.session.domOverlayState.type||(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),0))}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(void 0===this.options.element)return Ii.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){const e=document.querySelector(this.options.element);if(null===e)return Ii.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`),{};this._element=e}else this._element=this.options.element;return{domOverlay:{root:this._element}}}}pE.Name=po.DOM_OVERLAY,pE.Version=1,fo.AddWebXRFeature(pE.Name,((e,t)=>()=>new pE(e,t)),pE.Version,!1);class fE extends _o{get movementDirection(){return this._movementDirection}get movementEnabled(){return this._featureContext.movementEnabled}set movementEnabled(e){this._featureContext.movementEnabled=e}get movementOrientationFollowsViewerPose(){return this._featureContext.movementOrientationFollowsViewerPose}set movementOrientationFollowsViewerPose(e){this._featureContext.movementOrientationFollowsViewerPose=e}get movementSpeed(){return this._featureContext.movementSpeed}set movementSpeed(e){this._featureContext.movementSpeed=e}get movementThreshold(){return this._featureContext.movementThreshold}set movementThreshold(e){this._featureContext.movementThreshold=e}get rotationEnabled(){return this._featureContext.rotationEnabled}set rotationEnabled(e){this._featureContext.rotationEnabled=e}get rotationSpeed(){return this._featureContext.rotationSpeed}set rotationSpeed(e){this._featureContext.rotationSpeed=e}get rotationThreshold(){return this._featureContext.rotationThreshold}set rotationThreshold(e){this._featureContext.rotationThreshold=e}constructor(e,t){super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new L,this._tmpRotationMatrix=B.Identity(),this._tmpTranslationDirection=new w,this._tmpMovementTranslation=new w,this._tempCacheQuaternion=new L,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController)for(const i of this._currentRegistrationConfigurations){let s=null;if(i.allowedComponentTypes)for(const t of i.allowedComponentTypes){const i=e.motionController.getComponentOfType(t);if(null!==i){s=i;break}}if(i.mainComponentOnly){const t=e.motionController.getMainComponent();if(null===t)continue;s=t}if("function"==typeof i.componentSelectionPredicate&&(s=i.componentSelectionPredicate(e)),s&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness)continue;if(null===s)continue;const r={registrationConfiguration:i,component:s};t.registeredComponents.push(r),"axisChangedHandler"in i&&(r.onAxisChangedObserver=s.onAxisValueChangedObservable.add((e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)}))),"buttonChangedhandler"in i&&(r.onButtonChangedObserver=s.onButtonStateChangedObservable.add((()=>{s.changes.pressed&&i.buttonChangedhandler(s.changes.pressed,this._movementState,this._featureContext,this._xrInput)})))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}},t&&void 0!==t.xrInput?(Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=fE.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:t.movementOrientationFollowsViewerPose??!0,movementSpeed:t.movementSpeed??1,movementThreshold:t.movementThreshold??.25,rotationEnabled:t.rotationEnabled??!0,rotationSpeed:t.rotationSpeed??1,rotationThreshold:t.rotationThreshold??.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput):Ii.Error('WebXRControllerMovement feature requires "xrInput" option.')}attach(){return!!super.attach()&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._controllers={},!0)}_onXRFrame(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){const e=.001*this._xrSessionManager.scene.getEngine().getDeltaTime()*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=e,L.RotationYawPitchRollToRef(e,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(L.RotationYawPitchRollToRef(3*e,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(B.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),w.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}}_detachController(e){const t=this._controllers[e];if(t){for(const e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}}fE.Name=po.MOVEMENT,fE.REGISTRATIONS={default:[{allowedComponentTypes:[Bf.THUMBSTICK_TYPE,Bf.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(e,t,i)=>{t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[Bf.THUMBSTICK_TYPE,Bf.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(e,t,i)=>{t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},fE.Version=1,fo.AddWebXRFeature(fE.Name,((e,t)=>()=>new fE(e,t)),fE.Version,!0);class _E extends _o{constructor(e,t){super(e),this.options=t,this._canvasContext=null,this._reflectionCubeMap=null,this._xrLightEstimate=null,this._xrLightProbe=null,this._xrWebGLBinding=null,this._lightDirection=w.Up().negateInPlace(),this._lightColor=Y.White(),this._intensity=1,this._sphericalHarmonics=new qc,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new g,this._updateReflectionCubeMap=()=>{if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const e=Date.now();if(e-this._cubeMapPollTime{this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap)})))}},this.xrNativeFeatureName="light-estimation",this.options.createDirectionalLightSource&&(this.directionalLight=new $p("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new w(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=Os.FALLOFF_GLTF),this._hdrFilter=new O_(this._xrSessionManager.scene.getEngine()),Ii.Warn("light-estimation is an experimental and unstable feature.")}get reflectionCubeMapTexture(){return this._reflectionCubeMap}get xrLightingEstimate(){return this._xrLightEstimate?{lightColor:this._lightColor,lightDirection:this._lightDirection,lightIntensity:this._intensity,sphericalHarmonics:this._sphericalHarmonics}:this._xrLightEstimate}_getCanvasContext(){return null===this._canvasContext&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(null===this._xrWebGLBinding){const e=this._getCanvasContext();this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,e)}return this._xrWebGLBinding}attach(){if(!super.attach())return!1;const e=this.options.reflectionFormat??(this._xrSessionManager.session.preferredReflectionFormat||"srgba8");return this.options.reflectionFormat=e,this._xrSessionManager.session.requestLightProbe({reflectionFormat:e}).then((e=>{this._xrLightProbe=e,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new qn(this._xrSessionManager.scene),this._reflectionCubeMap._isCube=!0,this._reflectionCubeMap.coordinatesMode=3,this.options.setSceneEnvironmentTexture&&(this._xrSessionManager.scene.environmentTexture=this._reflectionCubeMap)),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap))})),!0}detach(){const e=super.detach();return null===this._xrLightProbe||this.options.disableCubeMapReflection||(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,e}dispose(){super.dispose(),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){const e=Date.now();if(e-this._lightEstimationPollTime()=>new _E(e,t)),_E.Version,!1);class mE extends _o{constructor(e){super(e),this.onEyeTrackingStartedObservable=new g,this.onEyeTrackingEndedObservable=new g,this.onEyeTrackingFrameUpdateObservable=new g,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new ao(w.Zero(),w.Forward()),this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay)},this._eyeTrackingEndListener=()=>{this._latestEyeSpace=null,this._gazeRay=null,this.onEyeTrackingEndedObservable.notifyObservers()},this.xrNativeFeatureName="eye-tracking",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}dispose(){super.dispose(),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()}get isEyeGazeValid(){return!!this._gazeRay}getEyeGaze(){return this._gazeRay}_onXRFrame(e){if(this.attached&&e&&this._latestEyeSpace&&this._gazeRay){const t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z).scaleInPlace(this._xrSessionManager.worldScalingFactor);const e=t.transform.orientation;U.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?w.RightHandedForwardReadOnly.rotateByQuaternionToRef(U.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,U.Quaternion[0].z*=-1,U.Quaternion[0].w*=-1,w.LeftHandedForwardReadOnly.rotateByQuaternionToRef(U.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))}}mE.Name=po.EYE_TRACKING,mE.Version=1,fo.AddWebXRFeature(mE.Name,(e=>()=>new mE(e)),mE.Version,!1);class gE{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw new Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class vE{constructor(){this._samples=new gE(20),this._entropy=0,this.onFirstStepDetected=new g}update(e,t,i,s){this._samples.push(e,t);const r=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=N.Distance(r,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let n;for(n=this._samePointCheckStartIdx;no&&(a=t,o=e);if(on*this._squaredProjectionDistanceThreshold)return;const f=U.Vector3[0];f.set(i,s,0);const _=U.Vector3[1];_.set(h.x,h.y,0);const m=w.Cross(f,_).z>0,g=r.clone(),v=r.clone();l.subtractToRef(r,h),m?(h.scaleAndAddToRef(this._axisToApexShrinkFactor,g),h.scaleAndAddToRef(this._axisToApexExtendFactor,v)):(h.scaleAndAddToRef(this._axisToApexExtendFactor,g),h.scaleAndAddToRef(this._axisToApexShrinkFactor,v)),this.onFirstStepDetected.notifyObservers({leftApex:g,rightApex:v,currentPosition:r,currentStepDirection:m?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),this._axisLength<.03))}get _vitalityThreshold(){return.1}get forward(){return this._forward}}class TE{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new vE,this._walker=null,this._movement=new N,this._millisecondsSinceLastUpdate=TE._MillisecondsPerUpdate,this.movementThisFrame=w.Zero(),this._engine=e,this._detector.onFirstStepDetected.add((e=>{this._walker||(this._walker=new xE(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),this._walker.onFootfall.add((()=>{J.Log("Footfall!")})),this._walker.onMovement.add((e=>{this._walker.forward.scaleAndAddToRef(.024*e.deltaT,this._movement)})))}))}update(e,t){t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=TE._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=TE._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker&&(this._walker.update(e.x,e.z)||(this._walker=null)),this._movement.scaleInPlace(.85)),this.movementThisFrame.set(this._movement.x,0,this._movement.y)}}class SE extends _o{static get Name(){return po.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()}constructor(e,t){super(e),this._up=new w,this._forward=new w,this._position=new w,this._movement=new w,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&J.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended")}isCompatible(){return void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!(!this.isCompatible||!super.attach()||(this._walker=new TE(this._sessionManager.scene.getEngine()),0))}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){const t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;const i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,s=t.transform.matrix;this._up.copyFromFloats(s[4],s[5],i*s[6]),this._forward.copyFromFloats(s[8],s[9],i*s[10]),this._position.copyFromFloats(s[12],s[13],i*s[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||w.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}fo.AddWebXRFeature(SE.Name,((e,t)=>()=>new SE(e,t)),SE.Version,!1);class EE extends fh{constructor(e,t,i,s,r,n,o=null){super(e,t,i,s,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=s,this.isMultiview=r,this.createRTTProvider=n,this._originalInternalTexture=o}}class bE extends _h{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this.onRenderTargetTextureCreatedObservable=new g,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t="none"){const i=this._lastSubImages.get(t),s="right"==t?1:0,r=e.colorTextureWidth??e.textureWidth,n=e.colorTextureHeight??e.textureHeight;if(!this._renderTargetTextures[s]||i?.textureWidth!==r||i?.textureHeight!==n){let i;const o=e.depthStencilTextureWidth??r,a=e.depthStencilTextureHeight??n;r!==o&&n!==a||(i=e.depthStencilTexture),this._renderTargetTextures[s]=this._createRenderTargetTexture(r,n,null,e.colorTexture,i,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n},this.onRenderTargetTextureCreatedObservable.notifyObservers({texture:this._renderTargetTextures[s],eye:t})}return this._lastSubImages.set(t,e),this._renderTargetTextures[s]}_getSubImageForEye(e){const t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){const t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e?.eye)}_setViewportForSubImage(e,t){const i=t.colorTextureWidth??t.textureWidth,s=t.colorTextureHeight??t.textureHeight,r=t.viewport;e.x=r.x/i,e.y=r.y/s,e.width=r.width/i,e.height=r.height/s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}}class CE extends EE{constructor(e,t,i){super((()=>e.textureWidth),(()=>e.textureHeight),e,"XRProjectionLayer",t,(e=>new yE(e,i,this))),this.layer=e}}class yE extends bE{constructor(e,t,i){super(e,t,i),this.layerWrapper=i,this._projectionLayer=i.layer}_getSubImageForView(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)}getRenderTargetTextureForView(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)}getRenderTargetTextureForEye(e){const t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}}const AE={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1,clearOnAccess:!1},RE={};class IE extends _o{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this._isMultiviewEnabled=!1,this._projectionLayerInitialized=!1,this._compositionLayerTextureMapping=new WeakMap,this._layerToRTTProviderMapping=new WeakMap,this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;const t={...AE,...this._options.projectionLayerInit};return this._isMultiviewEnabled=this._options.preferMultiviewOnInit&&e.getCaps().multiview,this.createProjectionLayer(t),this._projectionLayerInitialized=!0,!0}detach(){return!!super.detach()&&(this._existingLayers.forEach((e=>{e.dispose()})),this._existingLayers.length=0,this._projectionLayerInitialized=!1,!0)}createXRWebGLLayer(e=RE){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new mh(t)}_validateLayerInit(e,t=this._isMultiviewEnabled){if(!this._xrSessionManager.inXRSession)throw new Error("Cannot create a layer outside of a WebXR session. Make sure the session has started before creating layers.");if(t&&"texture-array"!==e.textureType)throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)throw new Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.")}_extendXRLayerInit(e,t=this._isMultiviewEnabled){return t&&(e.textureType="texture-array"),e}createProjectionLayer(e=AE,t=this._isMultiviewEnabled){this._extendXRLayerInit(e,t),this._validateLayerInit(e,t);const i=this._xrWebGLBinding.createProjectionLayer(e),s=new CE(i,t,this._xrWebGLBinding);return this.addXRSessionLayer(s),s}_createQuadLayer(e={params:{}},t){this._extendXRLayerInit(e.params,!1);const i=this._existingLayers[0].layer.textureWidth,s=this._existingLayers[0].layer.textureHeight,r={space:this._xrSessionManager.referenceSpace,viewPixelWidth:i,viewPixelHeight:s,clearOnAccess:!0,...e.params};this._validateLayerInit(r,!1);const n=this._xrWebGLBinding.createQuadLayer(r);n.width=this._isMultiviewEnabled?1:2,n.height=1;const o=new EE((()=>n.width),(()=>n.height),n,"XRQuadLayer",!1,(e=>new bE(e,this._xrWebGLBinding,o)));t&&this._compositionLayerTextureMapping.set(n,t);const a=o.createRenderTargetTextureProvider(this._xrSessionManager);return this._layerToRTTProviderMapping.set(n,a),this.addXRSessionLayer(o),o}addFullscreenAdvancedDynamicTexture(e,t={distanceFromHeadset:1.5}){const i=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}},e),s=i.layer,r={x:0,y:0,z:-Math.max(.1,t.distanceFromHeadset)};s.transform=new XRRigidTransform(r,{x:0,y:0,z:0,w:1});const n=this._layerToRTTProviderMapping.get(s);if(!n)throw new Error("Could not find the RTT provider for the layer");const o=this._xrSessionManager.scene.layers.find((t=>t.texture===e));if(!o)throw new Error("Could not find the babylon layer for the texture");return n.onRenderTargetTextureCreatedObservable.add((e=>{e.eye&&"right"===e.eye||(e.texture.clearColor=new j(0,0,0,0),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.scene.onBeforeRenderObservable.add((()=>{e.texture.render()})),o.renderTargetTextures.push(e.texture),o.renderOnlyInRenderTargetTextures=!0,this._xrSessionManager.onXRSessionEnded.addOnce((()=>{o.renderTargetTextures.splice(o.renderTargetTextures.indexOf(e.texture),1),o.renderOnlyInRenderTargetTextures=!1})))})),i}_addLensFlareSystem(e){const t=this._createQuadLayer({params:{space:this._xrSessionManager.viewerReferenceSpace,textureType:"texture",layout:"mono"}}),i=t.layer;i.width=2,i.height=1;i.transform=new XRRigidTransform({x:0,y:0,z:-10},{x:0,y:0,z:0,w:1});const s=this._layerToRTTProviderMapping.get(i);if(!s)throw new Error("Could not find the RTT provider for the layer");return s.onRenderTargetTextureCreatedObservable.add((t=>{t.texture.clearColor=new j(0,0,0,0),t.texture.customRenderFunction=()=>{e.render()}})),this._xrSessionManager.onXRSessionInit.add((()=>{this._xrSessionManager.scene.lensFlareSystems.splice(this._xrSessionManager.scene.lensFlareSystems.indexOf(e),1)})),this._xrSessionManager.onXRSessionEnded.add((()=>{this._xrSessionManager.scene.lensFlareSystems.push(e)})),t}addXRSessionLayer(e){this._existingLayers.push(e),this.setXRSessionLayers(this._existingLayers)}setXRSessionLayers(e=this._existingLayers){const t={...this._xrSessionManager.session.renderState};t.baseLayer=void 0,t.layers=e.map((e=>e.layer)),this._xrSessionManager.updateRenderState(t),this._projectionLayerInitialized||this._xrSessionManager._setBaseLayerWrapper(e.length>0?e.at(0):null)}isCompatible(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){const t=this._existingLayers;for(let i=0;i()=>new IE(e,t)),IE.Version,!1);class PE extends _o{get width(){return this._width}get height(){return this._height}get rawValueToMeters(){return this._rawValueToMeters}get normDepthBufferFromNormView(){return this._normDepthBufferFromNormView}get depthUsage(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}}get depthDataFormat(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}}get latestInternalTexture(){if(!this._cachedWebGLTexture)return null;const e=this._xrSessionManager.scene.getEngine(),t=new ti(e,ei.Unknown);return t.isCube=!1,t.invertY=!1,t._useSRGBBuffer=!1,t.format="ushort"===this.depthDataFormat?2:5,t.generateMipMaps=!1,t.type="ushort"===this.depthDataFormat?5:1,t.samplingMode=7,t.width=this.width??0,t.height=this.height??0,t._cachedWrapU=1,t._cachedWrapV=1,t._hardwareTexture=new Hi(this._cachedWebGLTexture,e._gl),t}get latestDepthBuffer(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null}get latestDepthImageTexture(){return this._cachedDepthImageTexture}constructor(e,t){super(e),this.options=t,this._width=null,this._height=null,this._rawValueToMeters=null,this._normDepthBufferFromNormView=null,this._cachedDepthBuffer=null,this._cachedWebGLTexture=null,this._cachedDepthImageTexture=null,this.onGetDepthInMetersAvailable=new g,this.xrNativeFeatureName="depth-sensing",Ii.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){return!!super.attach(e)&&(null!=this._xrSessionManager.session.depthDataFormat&&null!=this._xrSessionManager.session.depthUsage&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0))}dispose(){this._cachedDepthImageTexture?.dispose()}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(const t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:Ii.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(null===s)return;const{data:r,width:n,height:o,rawValueToMeters:a,getDepthInMeters:l}=s;switch(this._width=n,this._height=o,this._rawValueToMeters=a,this._cachedDepthBuffer=r,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(s)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=io.CreateRTexture(null,n,o,this._xrSessionManager.scene,!1,!0,Zn.NEAREST_SAMPLINGMODE,Br.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(r)).map((e=>e*a)));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(r).map((e=>e*a)))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const s=e.getDepthInformation(t);if(null===s)return;const{texture:r,width:n,height:o}=s;this._width=n,this._height=o,this._cachedWebGLTexture=r;const a=this._xrSessionManager.scene,l=a.getEngine().wrapWebGLTexture(r);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=io.CreateRTexture(null,n,o,a,!1,!0,Zn.NEAREST_SAMPLINGMODE,"ushort"===i?Br.TEXTURETYPE_UNSIGNED_BYTE:Br.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=l}getXRSessionInitExtension(){const e=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,t=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise((i=>{i(e&&t?{depthSensing:{usagePreference:this.options.usagePreference.map((e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}})),dataFormatPreference:this.options.dataFormatPreference.map((e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}}))}}:{})}))}}PE.Name=po.DEPTH_SENSING,PE.Version=1,fo.AddWebXRFeature(PE.Name,((e,t)=>()=>new PE(e,t)),PE.Version,!1);Ft.ShadersStore.velocityPixelShader="precision highp float;\n#define CUSTOM_FRAGMENT_BEGIN\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nhighp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ft.ShadersStore.velocityVertexShader="#define CUSTOM_VERTEX_BEGIN\n#define VELOCITY\nattribute vec3 position;\n#include\nuniform mat4 viewProjection;uniform mat4 previousViewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR;\n#endif\nvarying vec4 clipPos;varying vec4 previousClipPos;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;}\n#elif\nclipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";class ME extends da{constructor(e,t,i,s=512){super("spacewarp rtt",s,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[B.Identity(),B.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new fc("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add((e=>{this._previousWorldMatrices[e.uniqueId]=this._previousWorldMatrices[e.uniqueId]||e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[e.uniqueId]),this._previousWorldMatrices[e.uniqueId]=e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)})),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;const i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach((e=>{this._originalPairing.push([e,e.material]),e.material=this._velocityMaterial})),super.render(e,t),this._originalPairing.forEach((e=>{e[0].material=e[1]}))}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}}class DE{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){const t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');const i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,s,r){if(!this._engine)throw new Error("Engine is disposed");const n={width:e,height:t},o=new ME(s,r,this._scene,n),a=o.renderTarget;return i&&(a._framebuffer=i),a._colorTextureArray=s,a._depthStencilTextureArray=r,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let s=this._renderTargetTextures.get(t.eye);const r=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return s&&i?.textureWidth===r&&i?.textureHeight==n||(s=this._createRenderTargetTexture(r,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,s),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n}),this._lastSubImages.set(t,e),s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}accessMotionVector(e){const t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){const t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.clear()}}class OE extends _o{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[po.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new DE(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add((()=>this._onAfterRender())),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;const i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}}OE.Name=po.SPACE_WARP,OE.Version=1,fo.AddWebXRFeature(OE.Name,(e=>()=>new OE(e)),OE.Version,!1);class NE extends _o{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new g,this.xrNativeFeatureName="camera-access"}attach(e){return!!super.attach(e)&&(this._glContext=this._xrSessionManager.scene.getEngine()._gl,this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),!0)}detach(){return!!super.detach()&&(this._glBinding=void 0,this.options.doNotDisposeOnDetach||(this._cachedInternalTextures.forEach((e=>e.dispose())),this.texturesData.forEach((e=>e.dispose())),this._cachedInternalTextures.length=0,this.texturesData.length=0,this.cameraIntrinsics.length=0),!0)}dispose(){super.dispose(),this.onTexturesUpdatedObservable.clear()}_updateCameraIntrinsics(e,t){const i={width:e.camera.width,height:e.camera.height,x:0,y:0},s=e.projectionMatrix,r=(1-s[8])*i.width/2+i.x,n=(1-s[9])*i.height/2+i.y,o=i.width/2*s[0],a=i.height/2*s[5],l=i.width/2*s[4];this.cameraIntrinsics[t]={u0:r,v0:n,ax:o,ay:a,gamma:l,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){if(!e.camera)return!1;this.viewIndex[t]=e.eye;const i=this._glBinding?.getCameraImage(e.camera);if(this._cachedInternalTextures[t])this._cachedInternalTextures[t]._hardwareTexture?.set(i);else{const s=new ti(this._xrSessionManager.scene.getEngine(),ei.Unknown,!0);s.isCube=!0,s.invertY=!1,s.format=5,s.generateMipMaps=!0,s.type=1,s.samplingMode=3,s.width=e.camera.width,s.height=e.camera.height,s._cachedWrapU=1,s._cachedWrapV=1,s._hardwareTexture=new Hi(i,this._glContext),this._cachedInternalTextures[t]=s;const r=new qn(this._xrSessionManager.scene);r.name=`WebXR Raw Camera Access (${t})`,r._texture=this._cachedInternalTextures[t],this.texturesData[t]=r,this._updateCameraIntrinsics(e,t)}return this._cachedInternalTextures[t].isReady=!0,!0}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(!i||!i.views)return;let s=!0;i.views.forEach(((e,t)=>{s=s&&this._updateInternalTextures(e,t)})),s&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}NE.Name=po.RAW_CAMERA_ACCESS,NE.Version=1,fo.AddWebXRFeature(NE.Name,((e,t)=>()=>new NE(e,t)),NE.Version,!1);class wE extends Vf{constructor(e,t,i){super(e,FE[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}}Wf.RegisterController("generic-hand-select-grasp",((e,t)=>new wE(t,e.gamepad,e.handedness)));const FE={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};class LE extends Vf{constructor(e,t,i){super(e,BE["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";return e="left"===this.handedness?LE.MODEL_LEFT_FILENAME:LE.MODEL_RIGHT_FILENAME,{filename:e,path:LE.MODEL_BASE_URL+"default/"}}_getModelLoadingConstraints(){const e=Ro.IsPluginForExtensionAvailable(".glb");return e||J.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach(((e,t)=>{if(!this.disableAnimation&&e&&this.rootMesh){const i=this._mapping.buttons[e],s=i.rootNodeName;if(!s)return void J.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);const r=this._getChildByName(this.rootMesh,s);if(!r)return void J.Warn("Missing button mesh with name: "+s);if(i.valueMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.valueNodeName),i.pressedMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.pressedNodeName),i.unpressedMesh=this._getImmediateChildByName(r,this._mapping.defaultButton.unpressedNodeName),i.valueMesh&&i.pressedMesh&&i.unpressedMesh){const t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add((e=>{this._lerpTransform(i,e.value)}),void 0,!0)}else J.Warn("Missing button submesh under mesh with name: "+s)}})),this.getComponentIds().forEach((e=>{const t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach((i=>{if(!this.rootMesh)return;const s=this._mapping.axes[e][i],r=this._getChildByName(this.rootMesh,s.rootNodeName);r?(s.valueMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.valueNodeName),s.minMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.minNodeName),s.maxMesh=this._getImmediateChildByName(r,this._mapping.defaultAxis.maxNodeName),s.valueMesh&&s.minMesh&&s.maxMesh?t&&t.onAxisValueChangedObservable.add((e=>{const t="x-axis"===i?e.x:e.y;this._lerpTransform(s,t,!0)}),void 0,!0):J.Warn("Missing axis submesh under mesh with name: "+s.rootNodeName)):J.Warn("Missing axis mesh with name: "+s.rootNodeName)}))})))}_setRootMesh(e){let t;this.rootMesh=new Un(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;inew LE(t,e.gamepad,e.handedness)));const BE={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};class VE extends Vf{constructor(e,t,i,s=!1,r=!1){super(e,UE[i],t,i),this._forceLegacyControllers=r,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";return e="left"===this.handedness?VE.MODEL_LEFT_FILENAME:VE.MODEL_RIGHT_FILENAME,{filename:e,path:this._isQuest()?VE.QUEST_MODEL_BASE_URL:VE.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){const t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach((e=>{const s=e&&this.getComponent(e);s&&s.onButtonStateChangedObservable.add((s=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(t||(this._modelRootNode.getChildren()[3].rotation.x=.2*-s.value,this._modelRootNode.getChildren()[3].position.y=.005*-s.value,this._modelRootNode.getChildren()[3].position.z=.005*-s.value));case"xr-standard-squeeze":return void(t||(this._modelRootNode.getChildren()[4].position.x=i*s.value*.0035));case"xr-standard-thumbstick":return;case"a-button":case"x-button":return void(t||(s.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0));case"b-button":case"y-button":return void(t||(s.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0))}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new Un(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=L.FromEulerAngles(0,Math.PI,0)),e.forEach((e=>{e.isPickable=!1})),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}}VE.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",VE.MODEL_LEFT_FILENAME="left.babylon",VE.MODEL_RIGHT_FILENAME="right.babylon",VE.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",Wf.RegisterController("oculus-touch",((e,t)=>new VE(t,e.gamepad,e.handedness))),Wf.RegisterController("oculus-touch-legacy",((e,t)=>new VE(t,e.gamepad,e.handedness,!0)));const UE={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};class kE extends Vf{constructor(e,t,i){super(e,GE[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){return{filename:kE.MODEL_FILENAME,path:kE.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add((t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(this._modelRootNode.getChildren()[6].rotation.x=.15*-t.value);case"xr-standard-touchpad":case"xr-standard-squeeze":return}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new Un(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1})),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=L.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}kE.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",kE.MODEL_FILENAME="wand.babylon",Wf.RegisterController("htc-vive",((e,t)=>new kE(t,e.gamepad,e.handedness)));const GE={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};var zE;!async function(e,t){(await new Promise((e=>{"undefined"==typeof _native?Yu.addOnce((t=>e(t))):e(_native)}))).NativeXRFrame=class{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw new Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>this._nativeImpl._imageTrackingResults??[]}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;const i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];const s=this._xrTransform.orientation;return s.x=this._xrPoseVectorData[4],s.y=this._xrPoseVectorData[5],s.z=this._xrPoseVectorData[6],s.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw new Error("This function is not available in Babylon Native")}}}(),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(zE||(zE={}));class WE{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=Si(),this.connectedPointIds=[],this.name=e,this._connectionType=t}get connectionType(){return this._connectionType}_isSingularConnection(){return!0}isConnected(){return this._connectedPoint.length>0}connectTo(e){if(this._connectionType===e._connectionType)throw new Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw new Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName();for(const t of this._connectedPoint)e.connectedPointIds.push(t.uniqueId)}getClassName(){return"FGConnection"}deserialize(e){this.uniqueId=e.uniqueId,this.name=e.name,this._connectionType=e._connectionType,this.connectedPointIds=e.connectedPointIds}static Parse(e={},t){const i=new(Ii.Instantiate(e.className))(e.name,e._connectionType,t);return i.deserialize(e),i}}class HE{constructor(e){this.value=this._toInt(e)}_toInt(e){return 0|e}add(e){return new HE(this.value+e.value)}subtract(e){return new HE(this.value-e.value)}multiply(e){return new HE(Math.imul(this.value,e.value))}divide(e){return new HE(this.value/e.value)}getClassName(){return HE.ClassName}equals(e){return this.value===e.value}static Parse(e){return new HE(e.value)}}HE.ClassName="FlowGraphInteger",u("FlowGraphInteger",HE);class XE{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new XE(e.typeName,e.defaultValue)}}const YE=new XE("any",void 0),jE=new XE("string",""),$E=new XE("number",0),KE=new XE("boolean",!1),qE=new XE("Vector2",N.Zero()),QE=new XE("Vector3",w.Zero()),ZE=new XE("Vector4",F.Zero()),JE=new XE("Matrix",B.Identity()),eb=new XE("Color3",Y.Black()),tb=new XE("Color4",new j(0,0,0,0)),ib=new XE("Quaternion",L.Identity()),sb=new XE("FlowGraphInteger",new HE(0));class rb extends WE{constructor(e,t,i,s){super(e,t,i),this.richType=s}_isSingularConnection(){return this.connectionType===zE.Input}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===zE.Output?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){const i=WE.Parse(e,t);return i.richType=XE.Parse(e.richType),i}}function nb(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function ob(e){return"Vector2"===e||"Vector3"===e||"Vector4"===e||"Quaternion"===e||"Color3"===e||"Color4"===e}function ab(e,t,i){const s=t?.getClassName?.()??"";nb(s)?i[e]={name:t.name,className:s}:ob(s)?i[e]={value:t.asArray(),className:s}:i[e]=t}function lb(e,t,i){const s=t[e];let r;const n=s?.className;return r=nb(n)?i.getMeshByName(s.name):ob(n)?function(e,t){if("Vector2"===e)return N.FromArray(t);if("Vector3"===e)return w.FromArray(t);if("Vector4"===e)return F.FromArray(t);if("Quaternion"===e)return L.FromArray(t);if("Color3"===e)return new Y(t[0],t[1],t[2]);if("Color4"===e)return new j(t[0],t[1],t[2],t[3]);throw new Error(`Unknown vector class name ${e}`)}(n,s.value):"Matrix"===n?B.FromArray(s.value):n===HE.ClassName?HE.Parse(s):s&&void 0!==s.value?s.value:s,r}u("FGDataConnection",rb);class hb{constructor(e){this.config=e,this.uniqueId=Si(),this.name=this.config?.name??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new rb(e,zE.Input,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new rb(e,zE.Output,this,t);return this.dataOutputs.push(i),i}getDataInput(e){return this.dataInputs.find((t=>t.name===e))}getDataOutput(e){return this.dataOutputs.find((t=>t.name===e))}serialize(e={},t=ab){e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName();for(const t of this.dataInputs){const i={};t.serialize(i),e.dataInputs.push(i)}for(const t of this.dataOutputs){const i={};t.serialize(i),e.dataOutputs.push(i)}}getClassName(){return"FGBlock"}static Parse(e,t){const i=Ii.Instantiate(e.className),s={},r=t.valueParseFunction??lb;if(e.config)for(const i in e.config)s[i]=r(i,e.config,t.scene);var n;("FGSetPropertyBlock"===(n=e.className)||"FGGetPropertyBlock"===n||"FGPlayAnimationBlock"===n||"FGMeshPickEventBlock"===n)&&(s.pathConverter=t.pathConverter);const o=new i(s);o.uniqueId=e.uniqueId;for(let t=0;tt.name===e))}getSignalOutput(e){return this.signalOutputs.find((t=>t.name===e))}serialize(e={}){super.serialize(e),e.signalInputs=[],e.signalOutputs=[];for(const t of this.signalInputs){const i={};t.serialize(i),e.signalInputs.push(i)}for(const t of this.signalOutputs){const i={};t.serialize(i),e.signalOutputs.push(i)}}deserialize(e){for(let t=0;t{t.type===ss.POINTERPICK&&t.pickInfo?.pickedMesh&&(t.pickInfo?.pickedMesh===i||_b(t.pickInfo?.pickedMesh,i))&&this._execute(e)}));const s=i.onDisposeObservable.add((()=>this._onDispose));e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",s)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),s=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(s),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return mb.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}var gb;mb.ClassName="FGMeshPickEventBlock",u(mb.ClassName,mb),function(e){e[e.Stopped=0]="Stopped",e[e.Started=1]="Started"}(gb||(gb={}));class vb{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=gb.Stopped,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>this.dispose()))}createContext(){const e=new fb({scene:this._scene,coordinator:this._coordinator});return this._executionContexts.push(e),e}getContext(e){return this._executionContexts[e]}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==gb.Started){this.state=gb.Started,0===this._executionContexts.length&&this.createContext();for(const e of this._executionContexts){const t=this._getContextualOrder();for(const i of t)i._startPendingTasks(e)}}}_getContextualOrder(){const e=[];for(const t of this._eventBlocks)if(t.getClassName()===mb.ClassName){const i=t._getReferencedMesh();let s=0;for(;s0;){const s=t.pop();e(s);for(const e of s.dataInputs)for(const s of e._connectedPoint)i.has(s._ownerBlock.uniqueId)||(t.push(s._ownerBlock),i.add(s._ownerBlock.uniqueId));if(s instanceof ub)for(const e of s.signalOutputs)for(const s of e._connectedPoint)i.has(s._ownerBlock.uniqueId)||(t.push(s._ownerBlock),i.add(s._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks((t=>{const i={};t.serialize(i),e.allBlocks.push(i)})),e.executionContexts=[];for(const i of this._executionContexts){const s={};i.serialize(s,t),e.executionContexts.push(s)}}static GetDataOutConnectionByUniqueId(e,t){for(const i of e)for(const e of i.dataOutputs)if(e.uniqueId===t)return e;throw new Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(const i of e)if(i instanceof ub)for(const e of i.signalInputs)if(e.uniqueId===t)return e;throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const i=t.coordinator.createGraph(),s=[],r=t.valueParseFunction??lb;for(const n of e.allBlocks){const e=hb.Parse(n,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:r});s.push(e),e instanceof pb&&i.addEventBlock(e)}for(const e of s){for(const t of e.dataInputs)for(const e of t.connectedPointIds){const i=vb.GetDataOutConnectionByUniqueId(s,e);t.connectTo(i)}if(e instanceof ub)for(const t of e.signalOutputs)for(const e of t.connectedPointIds){const i=vb.GetSignalInConnectionByUniqueId(s,e);t.connectTo(i)}}for(const t of e.executionContexts)fb.Parse(t,{graph:i,valueParseFunction:r});return i}}class xb{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add((()=>{this.dispose()})),(xb.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new vb({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){const t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach((e=>e.start()))}dispose(){this._flowGraphs.forEach((e=>e.dispose())),this._flowGraphs.length=0;const e=xb.SceneCoordinators.get(this.config.scene)??[],t=e.indexOf(this);-1!==t&&e.splice(t,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach((i=>{const s={};i.serialize(s,t),e._flowGraphs.push(s)}))}static Parse(e,t){const i=t.valueParseFunction??lb,s=new xb({scene:t.scene});return e._flowGraphs?.forEach((e=>{vb.Parse(e,{coordinator:s,valueParseFunction:i,pathConverter:t.pathConverter})})),s}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new g,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}xb.SceneCoordinators=new Map;class Tb extends ub{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class Sb extends Tb{constructor(e){super(e),this.message=this.registerDataInput("message",YE)}_execute(e){const t=this.message.getValue(e);J.Log(t),this.out._activateSignal(e)}getClassName(){return Sb.ClassName}}Sb.ClassName="FGConsoleLogBlock",u(Sb.ClassName,Sb);class Eb extends Tb{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,YE)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return Eb.ClassName}}Eb.ClassName="FGSetVariableBlock",u(Eb.ClassName,Eb);const bb=new RegExp(/\{(\w+)\}/g);class Cb{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=bb.exec(e);for(;i;){const[,s]=i;this.templatedInputs.push(t.registerDataInput(s,sb)),i=bb.exec(e)}}getAccessor(e,t){let i=this.path;for(const e of this.templatedInputs){const s=e.getValue(t).value;i=i.replace(`{${e.name}}`,s.toString())}return e.convert(i)}}class yb extends Tb{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",YE),this.templateComponent=new Cb(e.path,this)}_execute(e){const t=this.a.getValue(e),i=this.templateComponent.getAccessor(this.config.pathConverter,e);i.info.set(t,i.object),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path}getClassName(){return yb.ClassName}}yb.ClassName="FGSetPropertyBlock",u("FGSetPropertyBlock",yb);class Ab extends Tb{constructor(e){super(e),this.config=e;for(let e=0;et.getValue(e)));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return Ab.ClassName}}Ab.ClassName="FGSendCustomEventBlock",u("FGSendCustomEventBlock",Ab),u("FGBranchBlock",class extends ub{constructor(e){super(e),this.condition=this.registerDataInput("condition",KE),this.onTrue=this._registerSignalOutput("onTrue"),this.onFalse=this._registerSignalOutput("onFalse")}_execute(e){this.condition.getValue(e)?this.onTrue._activateSignal(e):this.onFalse._activateSignal(e)}getClassName(){return"FGBranchBlock"}});class Rb extends Tb{constructor(e={startIndex:new HE(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",sb),this.value=this.registerDataOutput("value",sb)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const t=this.value.getValue(e);t.values)this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",r);else{const t=s-(r-i);this.timeRemaining.setValue(t,e)}}getClassName(){return"FGThrottleBlock"}});class Ib extends db{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",$E)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(void 0!==t&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],s=e.configuration.scene,r=new t_({timeout:t,contextObservable:s.onBeforeRenderObservable,onEnded:()=>this._onEnded(r,e)});r.start(),i.push(r),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],s=i.indexOf(e);-1!==s?i.splice(s,1):Ii.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningTimers")||[];for(const e of t)e.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return Ib.ClassName}}Ib.ClassName="FGTimerBlock",u("FGTimerBlock",Ib),u("FGMultiGateBlock",class extends ub{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",$E),this.config.startIndex=void 0!==this.config.startIndex?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let e=0;e=this.config.numberOutputFlows&&this.config.loop)r=0;else if(r>=this.config.numberOutputFlows&&!this.config.loop)return;if(s=s.filter((e=>e!==r)),0===s.length)for(let e=0;e=0&&(i[e+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every((e=>e))){this.out._activateSignal(e);for(let e=0;e=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}),u("FGFlipFlopBlock",class extends ub{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",KE)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}});class Mb extends ub{constructor(e){super(e),this.config=e,this.outFlows=[];for(let e=0;ethis._onAnimationEnd(t,e)));this.runningAnimatable.setValue(t,e),n.push(t)}e._setExecutionVariable(this,"runningAnimatables",n)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){const i=t._getExecutionVariable(this,"runningAnimatables")??[],s=i.indexOf(e);-1!==s&&i.splice(s,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningAnimatables")??[];for(const e of t)e.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return Db.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}Db.ClassName="FGPlayAnimationBlock",u(Db.ClassName,Db),u("FGStopAnimationBlock",class extends Tb{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",YE)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}),u("FGPauseAnimationBlock",class extends Tb{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",YE)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}),u("FGConditionalDataBlock",class extends hb{constructor(e){super(e),this.condition=this.registerDataInput("condition",KE),this.trueValue=this.registerDataInput("trueValue",YE),this.falseValue=this.registerDataInput("falseValue",YE),this.output=this.registerDataOutput("output",YE)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}});class Ob extends hb{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,YE)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return Ob.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}Ob.ClassName="FGGetVariableBlock",u(Ob.ClassName,Ob),u("FGCoordinateTransformBlock",class extends hb{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",YE),this.destinationSystem=this.registerDataInput("destinationSystem",YE),this.inputCoordinates=this.registerDataInput("inputCoordinates",QE),this.outputCoordinates=this.registerDataOutput("outputCoordinates",QE)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),s=this.inputCoordinates.getValue(e),r=t.getWorldMatrix(),n=i.getWorldMatrix(),o=U.Matrix[0].copyFrom(n);o.invert();const a=U.Matrix[1];o.multiplyToRef(r,a);const l=this.outputCoordinates.getValue(e);w.TransformCoordinatesToRef(s,a,l)}getClassName(){return"FGCoordinateTransformBlock"}}),u("FGConstantBlock",class extends hb{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",function(e){switch(typeof e){case"string":return jE;case"number":return $E;case"boolean":return KE;case"object":return e instanceof N?qE:e instanceof w?QE:e instanceof F?ZE:e instanceof Y?eb:e instanceof j?tb:e instanceof L?ib:e instanceof HE?sb:YE;default:return YE}}(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=ab){super.serialize(e),t("value",this.config.value,e.config)}});class Nb extends hb{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",YE),this.templateComponent=new Cb(e.path,this)}_updateOutputs(e){const t=this.templateComponent.getAccessor(this.config.pathConverter,e),i=t.info.get(t.object);this.value.setValue(i,e)}getClassName(){return Nb.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}Nb.ClassName="FGGetPropertyBlock",u(Nb.ClassName,Nb);const wb="cachedOperationValue",Fb="cachedExecutionId";class Lb extends hb{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,Fb),i=e._getExecutionVariable(this,wb);if(void 0!==i&&t===e.executionId)this.value.setValue(i,e);else{const t=this._doOperation(e);e._setExecutionVariable(this,wb,t),e._setExecutionVariable(this,Fb,e.executionId),this.value.setValue(t,e)}}}class Bb extends Lb{constructor(e,t,i,s,r,n){super(i,n),this._operation=s,this._className=r,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e))}getClassName(){return this._className}}class Vb extends Lb{constructor(e,t,i,s,r){super(t,r),this._operation=i,this._className=s,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}const Ub="FGLogic",kb="AndBlock",Gb="OrBlock",zb="NotBlock";u(`${Ub}${kb}`,class extends Bb{constructor(e){super(KE,KE,KE,((e,t)=>e&&t),`${Ub}${kb}`,e)}}),u(`${Ub}${Gb}`,class extends Bb{constructor(e){super(KE,KE,KE,((e,t)=>e||t),`${Ub}${Gb}`,e)}}),u(`${Ub}${zb}`,class extends Vb{constructor(e){super(KE,KE,(e=>!e),`${Ub}${zb}`,e)}});class Wb extends Lb{constructor(e,t,i,s){super(e,s),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class Hb extends Lb{constructor(e,t,i,s,r,n,o){super(s,o),this._operation=r,this._className=n,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t),this.c=this.registerDataInput("c",i)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e),this.c.getValue(e))}getClassName(){return this._className}}function Xb(e){return e.getClassName?e.getClassName():""}function Yb(e,t){return"Vector2"===e&&"Vector2"===t||"Vector3"===e&&"Vector3"===t||"Vector4"===e&&"Vector4"===t}function jb(e,t){return"Matrix"===e&&"Matrix"===t}function $b(e,t){return"FlowGraphInteger"===e&&"FlowGraphInteger"===t}class Kb extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicAdd(e,t)),Kb.ClassName,e)}_polymorphicAdd(e,t){const i=Xb(e),s=Xb(t);return Yb(i,s)||jb(i,s)||$b(i,s)?e.add(t):e+t}}Kb.ClassName="FGAddBlock",u(Kb.ClassName,Kb);class qb extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicAdd(e,t)),qb.ClassName,e)}_polymorphicAdd(e,t){const i=Xb(e),s=Xb(t);return Yb(i,s)||$b(i,s)?e.subtract(t):jb(i,s)?e.add(t.scale(-1)):e-t}}qb.ClassName="FGSubBlock",u(qb.ClassName,qb);class Qb extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicMultiply(e,t)),Qb.ClassName,e)}_polymorphicMultiply(e,t){const i=Xb(e),s=Xb(t);return Yb(i,s)||$b(i,s)?e.multiply(t):jb(i,s)?B.FromValues(e.m[0]*t.m[0],e.m[4]*t.m[4],e.m[8]*t.m[8],e.m[12]*t.m[12],e.m[1]*t.m[1],e.m[5]*t.m[5],e.m[9]*t.m[9],e.m[13]*t.m[13],e.m[2]*t.m[2],e.m[6]*t.m[6],e.m[10]*t.m[10],e.m[14]*t.m[14],e.m[3]*t.m[3],e.m[7]*t.m[7],e.m[11]*t.m[11],e.m[15]*t.m[15]):e*t}}Qb.ClassName="FGMultiplyBlock",u(Qb.ClassName,Qb);class Zb extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicDivide(e,t)),Zb.ClassName,e)}_polymorphicDivide(e,t){const i=Xb(e),s=Xb(t);return Yb(i,s)||$b(i,s)?e.divide(t):jb(i,s)?B.FromValues(e.m[0]/t.m[0],e.m[4]/t.m[4],e.m[8]/t.m[8],e.m[12]/t.m[12],e.m[1]/t.m[1],e.m[5]/t.m[5],e.m[9]/t.m[9],e.m[13]/t.m[13],e.m[2]/t.m[2],e.m[6]/t.m[6],e.m[10]/t.m[10],e.m[14]/t.m[14],e.m[3]/t.m[3],e.m[7]/t.m[7],e.m[11]/t.m[11],e.m[15]/t.m[15]):e/t}}Zb.ClassName="FGDivideBlock",u(Zb.ClassName,Zb);class Jb extends Wb{constructor(e){super($E,(()=>Math.random()),Jb.ClassName,e)}}Jb.ClassName="FGRandomBlock",u(Jb.ClassName,Jb);class eC extends Bb{constructor(e){super(YE,YE,$E,((e,t)=>this._polymorphicDot(e,t)),eC.ClassName,e)}_polymorphicDot(e,t){switch(Xb(e)){case"Vector2":return N.Dot(e,t);case"Vector3":return w.Dot(e,t);case"Vector4":return F.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}eC.ClassName="FGDotBlock",u(eC.ClassName,eC);class tC extends Wb{constructor(e){super($E,(()=>Math.E),tC.ClassName,e)}}tC.ClassName="FGEBlock",u(tC.ClassName,tC);class iC extends Wb{constructor(e){super($E,(()=>Math.PI),iC.ClassName,e)}}iC.ClassName="FGPIBlock",u(iC.ClassName,iC);class sC extends Wb{constructor(e){super($E,(()=>Number.POSITIVE_INFINITY),sC.ClassName,e)}}sC.ClassName="FGInfBlock",u(sC.ClassName,sC);class rC extends Wb{constructor(e){super($E,(()=>Number.NaN),rC.ClassName,e)}}function nC(e,t){switch(Xb(e)){case"FlowGraphInteger":return new HE(t(e.value));case"Vector2":return new N(t(e.x),t(e.y));case"Vector3":return new w(t(e.x),t(e.y),t(e.z));case"Vector4":return new F(t(e.x),t(e.y),t(e.z),t(e.w));case"Matrix":return B.FromValues(t(e.m[0]),t(e.m[4]),t(e.m[8]),t(e.m[12]),t(e.m[1]),t(e.m[5]),t(e.m[9]),t(e.m[13]),t(e.m[2]),t(e.m[6]),t(e.m[10]),t(e.m[14]),t(e.m[3]),t(e.m[7]),t(e.m[11]),t(e.m[15]));default:return t(e)}}rC.ClassName="FGNaNBlock",u(rC.ClassName,rC);class oC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicAbs(e)),oC.ClassName,e)}_polymorphicAbs(e){return nC(e,Math.abs)}}oC.ClassName="FGAbsBlock",u(oC.ClassName,oC);class aC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicSign(e)),aC.ClassName,e)}_polymorphicSign(e){return nC(e,Math.sign)}}aC.ClassName="FGSignBlock",u(aC.ClassName,aC);class lC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicTrunc(e)),lC.ClassName,e)}_polymorphicTrunc(e){return nC(e,Math.trunc)}}lC.ClassName="FGTruncBlock",u(lC.ClassName,lC);class hC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicFloor(e)),hC.ClassName,e)}_polymorphicFloor(e){return nC(e,Math.floor)}}hC.ClassName="FGFloorBlock",u(hC.ClassName,hC);class cC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicCeiling(e)),cC.ClassName,e)}_polymorphicCeiling(e){return nC(e,Math.ceil)}}cC.ClassName="FGCeilBlock",u(cC.ClassName,cC);class uC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicFract(e)),uC.ClassName,e)}_polymorphicFract(e){return nC(e,(e=>e-Math.floor(e)))}}uC.ClassName="FGFractBlock",u(uC.ClassName,uC);class dC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicNeg(e)),dC.ClassName,e)}_polymorphicNeg(e){return nC(e,(e=>-e))}}function pC(e,t,i){switch(Xb(e)){case"FlowGraphInteger":return new HE(i(e.value,t.value));case"Vector2":return new N(i(e.x,t.x),i(e.y,t.y));case"Vector3":return new w(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z));case"Vector4":return new F(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z),i(e.w,t.w));case"Matrix":return B.FromValues(i(e.m[0],t.m[0]),i(e.m[4],t.m[4]),i(e.m[8],t.m[8]),i(e.m[12],t.m[12]),i(e.m[1],t.m[1]),i(e.m[5],t.m[5]),i(e.m[9],t.m[9]),i(e.m[13],t.m[13]),i(e.m[2],t.m[2]),i(e.m[6],t.m[6]),i(e.m[10],t.m[10]),i(e.m[14],t.m[14]),i(e.m[3],t.m[3]),i(e.m[7],t.m[7]),i(e.m[11],t.m[11]),i(e.m[15],t.m[15]));default:return i(e,t)}}dC.ClassName="FGNegBlock",u(dC.ClassName,dC);class fC extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicRemainder(e,t)),fC.ClassName,e)}_polymorphicRemainder(e,t){return pC(e,t,((e,t)=>e%t))}}fC.ClassName="FGRemainderBlock",u(fC.ClassName,fC);class _C extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicMin(e,t)),_C.ClassName,e)}_polymorphicMin(e,t){return pC(e,t,Math.min)}}_C.ClassName="FGMinBlock",u(_C.ClassName,_C);class mC extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicMax(e,t)),mC.ClassName,e)}_polymorphicMax(e,t){return pC(e,t,Math.max)}}function gC(e,t,i){return Math.min(Math.max(e,Math.min(t,i)),Math.max(t,i))}function vC(e,t,i,s){switch(Xb(e)){case"FlowGraphInteger":return new HE(s(e.value,t.value,i.value));case"Vector2":return new N(s(e.x,t.x,i.x),s(e.y,t.y,i.y));case"Vector3":return new w(s(e.x,t.x,i.x),s(e.y,t.y,i.y),s(e.z,t.z,i.z));case"Vector4":return new F(s(e.x,t.x,i.x),s(e.y,t.y,i.y),s(e.z,t.z,i.z),s(e.w,t.w,i.w));case"Matrix":return B.FromValues(s(e.m[0],t.m[0],i.m[0]),s(e.m[4],t.m[4],i.m[4]),s(e.m[8],t.m[8],i.m[8]),s(e.m[12],t.m[12],i.m[12]),s(e.m[1],t.m[1],i.m[1]),s(e.m[5],t.m[5],i.m[5]),s(e.m[9],t.m[9],i.m[9]),s(e.m[13],t.m[13],i.m[13]),s(e.m[2],t.m[2],i.m[2]),s(e.m[6],t.m[6],i.m[6]),s(e.m[10],t.m[10],i.m[10]),s(e.m[14],t.m[14],i.m[14]),s(e.m[3],t.m[3],i.m[3]),s(e.m[7],t.m[7],i.m[7]),s(e.m[11],t.m[11],i.m[11]),s(e.m[15],t.m[15],i.m[15]));default:return s(e,t,i)}}mC.ClassName="FGMaxBlock",u(mC.ClassName,mC);class xC extends Hb{constructor(e){super(YE,YE,YE,YE,((e,t,i)=>this._polymorphicClamp(e,t,i)),xC.ClassName,e)}_polymorphicClamp(e,t,i){return vC(e,t,i,gC)}}function TC(e){return Math.min(Math.max(e,0),1)}xC.ClassName="FGClampBlock",u(xC.ClassName,xC);class SC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicSaturate(e)),SC.ClassName,e)}_polymorphicSaturate(e){return nC(e,TC)}}SC.ClassName="FGSaturateBlock",u(SC.ClassName,SC);class EC extends Hb{constructor(e){super(YE,YE,YE,YE,((e,t,i)=>this._polymorphicInterpolate(e,t,i)),EC.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return vC(e,t,i,this._interpolate)}}EC.ClassName="FGInterpolateBlock",u(EC.ClassName,EC);class bC extends Bb{constructor(e){super(YE,YE,KE,((e,t)=>this._polymorphicEq(e,t)),bC.ClassName,e)}_polymorphicEq(e,t){const i=Xb(e),s=Xb(t);return Yb(i,s)||jb(i,s)||$b(i,s)?e.equals(t):e===t}}function CC(e,t,i){const s=Xb(e);if(s===Xb(t)){if(""===s)return i(e,t);if("FlowGraphInteger"===s)return i(e.value,t.value);throw new Error(`Cannot compare ${e} and ${t}`)}throw new Error(`${e} and ${t} are of different types.`)}bC.ClassName="FGEqBlock",u(bC.ClassName,bC);class yC extends Bb{constructor(e){super(YE,YE,KE,((e,t)=>this._polymorphicLessThan(e,t)),yC.ClassName,e)}_polymorphicLessThan(e,t){return CC(e,t,((e,t)=>ethis._polymorphicLessThanOrEqual(e,t)),AC.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return CC(e,t,((e,t)=>e<=t))}}AC.ClassName="FGLessThanOrEqualBlock";class RC extends Bb{constructor(e){super(YE,YE,KE,((e,t)=>this._polymorphicGreaterThan(e,t)),RC.ClassName,e)}_polymorphicGreaterThan(e,t){return CC(e,t,((e,t)=>e>t))}}RC.ClassName="FGGreaterThanBlock",u(RC.ClassName,RC);class IC extends Bb{constructor(e){super(YE,YE,KE,((e,t)=>this._polymorphicGreaterThanOrEqual(e,t)),IC.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return CC(e,t,((e,t)=>e>=t))}}IC.ClassName="FGGreaterThanOrEqualBlock",u(IC.ClassName,IC);class PC extends Vb{constructor(e){super(YE,KE,(e=>this._polymorphicIsNan(e)),PC.ClassName,e)}_polymorphicIsNan(e){const t=Xb(e);if(""===t)return isNaN(e);if("FlowGraphInteger"===t)return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}PC.ClassName="FGIsNanBlock",u(PC.ClassName,PC);class MC extends Vb{constructor(e){super(YE,KE,(e=>this._polymorphicIsInf(e)),MC.ClassName,e)}_polymorphicIsInf(e){const t=Xb(e);if(""===t)return!isFinite(e);if("FlowGraphInteger"===t)return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}MC.ClassName="FGIsInfBlock";class DC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicDegToRad(e)),DC.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return nC(e,this._degToRad)}}DC.ClassName="FGDegToRadBlock",u(DC.ClassName,DC);class OC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicRadToDeg(e)),OC.ClassName,e)}_radToDeg(e){return 180*e/Math.PI}_polymorphicRadToDeg(e){return nC(e,this._radToDeg)}}OC.ClassName="FGRadToDegBlock",u(OC.ClassName,OC);class NC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicSin(e)),NC.ClassName,e)}_polymorphicSin(e){return nC(e,Math.sin)}}NC.ClassName="FGSinBlock",u(NC.ClassName,NC);class wC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicCos(e)),wC.ClassName,e)}_polymorphicCos(e){return nC(e,Math.cos)}}wC.ClassName="FGCosBlock",u(wC.ClassName,wC);class FC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicTan(e)),FC.ClassName,e)}_polymorphicTan(e){return nC(e,Math.tan)}}FC.ClassName="FGTanBlock",u(FC.ClassName,FC);class LC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicAsin(e)),LC.ClassName,e)}_polymorphicAsin(e){return nC(e,Math.asin)}}LC.ClassName="FGAsinBlock",u(LC.ClassName,LC);class BC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicAcos(e)),BC.ClassName,e)}_polymorphicAcos(e){return nC(e,Math.acos)}}BC.ClassName="FGAcosBlock",u(BC.ClassName,BC);class VC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicAtan(e)),VC.ClassName,e)}_polymorphicAtan(e){return nC(e,Math.atan)}}VC.ClassName="FGAtanBlock",u(VC.ClassName,VC);class UC extends Bb{constructor(e){super(YE,YE,YE,((e,t)=>this._polymorphicAtan2(e,t)),UC.ClassName,e)}_polymorphicAtan2(e,t){return pC(e,t,Math.atan2)}}UC.ClassName="FGAtan2Block",u(UC.ClassName,UC);class kC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicSinh(e)),kC.ClassName,e)}_polymorphicSinh(e){return nC(e,Math.sinh)}}kC.ClassName="FGSinhBlock",u(kC.ClassName,kC);class GC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicCosh(e)),GC.ClassName,e)}_polymorphicCosh(e){return nC(e,Math.cosh)}}GC.ClassName="FGCoshBlock",u(GC.ClassName,GC);class zC extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicTanh(e)),zC.ClassName,e)}_polymorphicTanh(e){return nC(e,Math.tanh)}}zC.ClassName="FGTanhBlock",u(zC.ClassName,zC);class WC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicAsinh(e)),WC.ClassName,e)}_polymorphicAsinh(e){return nC(e,Math.asinh)}}WC.ClassName="FGAsinhBlock",u(WC.ClassName,WC);class HC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicAcosh(e)),HC.ClassName,e)}_polymorphicAcosh(e){return nC(e,Math.acosh)}}HC.ClassName="FGAcoshBlock",u(HC.ClassName,HC);class XC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicAtanh(e)),XC.ClassName,e)}_polymorphicAtanh(e){return nC(e,Math.atanh)}}XC.ClassName="FGAtanhBlock",u(XC.ClassName,XC);class YC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicExp(e)),YC.ClassName,e)}_polymorphicExp(e){return nC(e,Math.exp)}}YC.ClassName="FGExpBlock",u(YC.ClassName,YC);class jC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicLog(e)),jC.ClassName,e)}_polymorphicLog(e){return nC(e,Math.log)}}jC.ClassName="FGLogBlock",u(jC.ClassName,jC);class $C extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicLog2(e)),$C.ClassName,e)}_polymorphicLog2(e){return nC(e,Math.log2)}}$C.ClassName="FGLog2Block",u($C.ClassName,$C);class KC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicLog10(e)),KC.ClassName,e)}_polymorphicLog10(e){return nC(e,Math.log10)}}KC.ClassName="FGLog10Block",u(KC.ClassName,KC);class qC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicSqrt(e)),qC.ClassName,e)}_polymorphicSqrt(e){return nC(e,Math.sqrt)}}qC.ClassName="FGSqrtBlock",u(qC.ClassName,qC);class QC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicCubeRoot(e)),QC.ClassName,e)}_polymorphicCubeRoot(e){return nC(e,Math.cbrt)}}QC.ClassName="FGCubeRootBlock",u(QC.ClassName,QC);class ZC extends Bb{constructor(e){super(YE,$E,$E,((e,t)=>this._polymorphicPow(e,t)),ZC.ClassName,e)}_polymorphicPow(e,t){return pC(e,t,Math.pow)}}ZC.ClassName="FGPowBlock",u(ZC.ClassName,ZC);class JC extends Vb{constructor(e){super(YE,$E,(e=>this._polymorphicLength(e)),JC.ClassName,e)}_polymorphicLength(e){switch(Xb(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}JC.ClassName="FGLengthBlock",u(JC.ClassName,JC);class ey extends Vb{constructor(e){super(YE,YE,(e=>this._polymorphicNormalize(e)),ey.ClassName,e)}_polymorphicNormalize(e){switch(Xb(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}ey.ClassName="FGNormalizeBlock",u(ey.ClassName,ey);class ty extends Bb{constructor(e){super(QE,QE,QE,((e,t)=>w.Cross(e,t)),ty.ClassName,e)}}ty.ClassName="FGCrossBlock",u(ty.ClassName,ty);class iy extends Bb{constructor(e){super(qE,$E,qE,((e,t)=>N.Transform(e,B.RotationZ(t))),iy.ClassName,e)}}iy.ClassName="FGRotate2DBlock",u(iy.ClassName,iy);class sy extends Hb{constructor(e){super(QE,QE,$E,QE,((e,t,i)=>w.TransformCoordinates(e,B.RotationAxis(t,i))),sy.ClassName,e)}}sy.ClassName="FGRotate3DBlock",u(sy.ClassName,sy);class ry extends Vb{constructor(e){super(JE,JE,(e=>B.Transpose(e)),ry.ClassName,e)}}ry.ClassName="FGTransposeBlock",u(ry.ClassName,ry);class ny extends Vb{constructor(e){super(JE,$E,(e=>e.determinant()),ny.ClassName,e)}}ny.ClassName="FGDeterminantBlock",u(ny.ClassName,ny);class oy extends Vb{constructor(e){super(JE,JE,(e=>B.Invert(e)),oy.ClassName,e)}}oy.ClassName="FGInvertMatrixBlock",u(oy.ClassName,oy);class ay extends Bb{constructor(e){super(JE,JE,JE,((e,t)=>t.multiply(e)),ay.ClassName,e)}}ay.ClassName="FGMatMulBlock",u(ay.ClassName,ay);class ly extends Vb{constructor(e){super(sb,sb,(e=>new HE(~e.value)),ly.ClassName,e)}}ly.ClassName="FGBitwiseNotBlock",u(ly.ClassName,ly);class hy extends Bb{constructor(e){super(sb,sb,sb,((e,t)=>new HE(e.value&t.value)),hy.ClassName,e)}}hy.ClassName="FGBitwiseAndBlock",u(hy.ClassName,hy);class cy extends Bb{constructor(e){super(sb,sb,sb,((e,t)=>new HE(e.value|t.value)),cy.ClassName,e)}}cy.ClassName="FGBitwiseOrBlock",u(cy.ClassName,cy);class uy extends Bb{constructor(e){super(sb,sb,sb,((e,t)=>new HE(e.value^t.value)),uy.ClassName,e)}}uy.ClassName="FGBitwiseXorBlock",u(uy.ClassName,uy);class dy extends Bb{constructor(e){super(sb,sb,sb,((e,t)=>new HE(e.value<new HE(e.value>>t.value)),py.ClassName,e)}}py.ClassName="FGBitwiseRightShiftBlock",u(py.ClassName,py);class fy extends Vb{constructor(e){super(sb,sb,(e=>new HE(Math.clz32(e.value))),fy.ClassName,e)}}fy.ClassName="FGCountLeadingZerosBlock",u(fy.ClassName,fy);class _y extends Vb{constructor(e){super(sb,sb,(e=>new HE(e.value?31-Math.clz32(e.value&-e.value):32)),_y.ClassName,e)}}_y.ClassName="FGCountTrailingZerosBlock",u(_y.ClassName,_y);class my extends Vb{constructor(e){super(sb,sb,(e=>new HE(function(e){let t=0;for(;e;)t+=1&e,e>>=1;return t}(e.value))),my.ClassName,e)}}my.ClassName="FGCountOneBitsBlock",u(my.ClassName,my);class gy extends pb{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const t=e.configuration.scene.onReadyObservable.add((()=>{this._execute(e)}));e._setExecutionVariable(this,"sceneReadyObserver",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return gy.ClassName}}gy.ClassName="FGSceneReadyEventBlock",u("FGSceneReadyEventBlock",gy);class vy extends pb{constructor(e){super(e),this.config=e;for(let e=0;e{for(let i=0;i{this._execute(e)}));e._setExecutionVariable(this,"sceneBeforeRender",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return xy.ClassName}}xy.ClassName="FGSceneTickEventBlock",u(xy.ClassName,xy);class Ty{constructor(e,t){this.jscad=e,this.vecHelper=t}extrudeLinear(e){const t=e.geometry.length&&e.geometry.length>0,i=t?e.geometry:[e.geometry];let s=this.jscad.extrusions.extrudeLinear({height:e.height,twistAngle:Hs.FromDegrees(e.twistAngle).radians(),twistSteps:e.twistSteps},...i);return t&&!s.length&&(s=[s]),s}extrudeRectangular(e){const t=e.geometry.length&&e.geometry.length>0,i=t?e.geometry:[e.geometry];let s=this.jscad.extrusions.extrudeRectangular({height:e.height,size:e.size},...i);return t&&!s.length&&(s=[s]),s}extrudeRectangularPoints(e){const t=e.points.map((e=>[e[0],e[1]])),i=this.vecHelper.removeConsecutiveDuplicates(t),s=this.jscad.geometries.path2.fromPoints({},i);return this.extrudeRectangular({height:e.height,size:e.size,geometry:s})}extrudeRotate(e){const t={angle:Hs.FromDegrees(e.angle).radians(),startAngle:Hs.FromDegrees(e.startAngle).radians(),overflow:"cap",segments:e.segments};return this.jscad.extrusions.extrudeRotate(t,e.polygon)}}class Sy{constructor(e,t){this.jscad=e,this.vecHelper=t}createFromPoints(e){const t=e.points.map((e=>[e[0],e[1]]));return this.removeDuplicatesAndCreateFromPoints(t,e.closed)}createPathsFromPoints(e){return e.pointsLists.map((e=>{const t=e.map((e=>[e[0],e[1]]));return t.length>1&&this.vecHelper.vectorsTheSame(t[0],t[t.length-1],1e-5)?this.removeDuplicatesAndCreateFromPoints(t,!0):this.removeDuplicatesAndCreateFromPoints(t,!1)}))}createFromPolyline(e){const t=e.polyline.points.map((e=>[e[0],e[1]]));return this.removeDuplicatesAndCreateFromPoints(t,e.closed)}createEmpty(){return this.jscad.geometries.path2.create()}close(e){return this.jscad.geometries.path2.close(e.path)}appendPoints(e){const t=e.points.map((e=>[e[0],e[1]])),i=this.vecHelper.removeConsecutiveDuplicates(t);return this.jscad.geometries.path2.appendPoints(i,e.path)}appendPolyline(e){const t=e.polyline.points.map((e=>[e[0],e[1]]));return this.appendPoints({points:t,path:e.path})}appendArc(e){const t=[e.endPoint[0],e.endPoint[1]],i=[e.radiusX,e.radiusY];return this.jscad.geometries.path2.appendArc({endpoint:t,radius:i,xaxisrotation:Hs.FromDegrees(e.xAxisRotation).radians(),clockwise:e.clockwise,large:e.large,segments:e.segments},e.path)}removeDuplicatesAndCreateFromPoints(e,t){const i=this.vecHelper.removeConsecutiveDuplicates(e);let s=this.jscad.geometries.path2.fromPoints({},i);return t&&(s=this.jscad.geometries.path2.close(s)),s}}class Ey{constructor(e,t){this.jscad=e,this.vecHelper=t}createFromPoints(e){const t=e.points.map((e=>[e[0],e[1]]));return this.removeDuplicatesAndCreateFromPoints(t)}createFromPolyline(e){const t=e.polyline.points.map((e=>[e[0],e[1]]));return this.removeDuplicatesAndCreateFromPoints(t)}createFromCurve(e){const t=e.curve.tessellate().map((e=>[e[0],e[1]]));return this.removeDuplicatesAndCreateFromPoints(t)}createFromPath(e){return this.removeDuplicatesAndCreateFromPoints(e.path.points)}circle(e){return this.jscad.primitives.circle({center:e.center,radius:e.radius,segments:e.segments})}ellipse(e){return this.jscad.primitives.ellipse({center:e.center,radius:[e.radius[0],e.radius[1]],segments:e.segments})}rectangle(e){return this.jscad.primitives.rectangle({center:[e.center[0],e.center[1]],size:[e.width,e.length]})}roundedRectangle(e){return this.jscad.primitives.roundedRectangle({center:[e.center[0],e.center[1]],size:[e.width,e.length],roundRadius:e.roundRadius,segments:e.segments})}square(e){return this.jscad.primitives.square({center:[e.center[0],e.center[1]],size:e.size})}star(e){return this.jscad.primitives.star({center:[e.center[0],e.center[1]],vertices:e.vertices,density:e.density,outerRadius:e.outerRadius,innerRadius:e.innerRadius,startAngle:Hs.FromDegrees(e.startAngle).radians()})}removeDuplicatesAndCreateFromPoints(e){const t=this.vecHelper.removeConsecutiveDuplicates(e);return this.jscad.primitives.polygon({points:t})}}class by{constructor(e){this.jscad=e}cube(e){return this.jscad.primitives.cube({center:[e.center[0],e.center[1],e.center[2]],size:e.size})}cubesOnCenterPoints(e){return e.centers.map((t=>this.cube({center:t,size:e.size})))}cuboid(e){return this.jscad.primitives.cuboid({center:[e.center[0],e.center[1],e.center[2]],size:[e.width,e.height,e.length]})}cuboidsOnCenterPoints(e){return e.centers.map((t=>this.cuboid({center:t,width:e.width,length:e.length,height:e.height})))}cylinderElliptic(e){return this.jscad.primitives.cylinderElliptic({center:[e.center[0],e.center[1],e.center[2]],height:e.height,startRadius:[e.startRadius[0],e.startRadius[1]],endRadius:[e.endRadius[0],e.endRadius[1]],segments:e.segments})}cylinderEllipticOnCenterPoints(e){return e.centers.map((t=>this.cylinderElliptic({center:t,height:e.height,startRadius:e.startRadius,endRadius:e.endRadius,segments:e.segments})))}cylinder(e){return this.jscad.primitives.cylinder({center:[e.center[0],e.center[1],e.center[2]],height:e.height,radius:e.radius,segments:e.segments})}cylindersOnCenterPoints(e){return e.centers.map((t=>this.cylinder({center:t,height:e.height,radius:e.radius,segments:e.segments})))}ellipsoid(e){return this.jscad.primitives.ellipsoid({center:[e.center[0],e.center[1],e.center[2]],radius:[e.radius[0],e.radius[1],e.radius[2]],segments:e.segments,axes:[[-1,0,0],[0,-1,0],[0,0,-1]]})}ellipsoidsOnCenterPoints(e){return e.centers.map((t=>this.ellipsoid({center:t,radius:e.radius,segments:e.segments})))}geodesicSphere(e){let t=this.jscad.primitives.geodesicSphere({radius:e.radius,frequency:e.frequency});return t=this.jscad.transforms.translate([e.center[0],e.center[1],e.center[2]],t),t}geodesicSpheresOnCenterPoints(e){return e.centers.map((t=>this.geodesicSphere({center:t,radius:e.radius,frequency:e.frequency})))}roundedCuboid(e){return this.jscad.primitives.roundedCuboid({center:[e.center[0],e.center[1],e.center[2]],size:[e.width,e.height,e.length],roundRadius:e.roundRadius,segments:e.segments})}roundedCuboidsOnCenterPoints(e){return e.centers.map((t=>this.roundedCuboid({center:t,width:e.width,height:e.height,length:e.length,roundRadius:e.roundRadius,segments:e.segments})))}roundedCylinder(e){return this.jscad.primitives.roundedCylinder({center:[e.center[0],e.center[1],e.center[2]],height:e.height,radius:e.radius,roundRadius:e.roundRadius,segments:e.segments})}roundedCylindersOnCenterPoints(e){return e.centers.map((t=>this.roundedCylinder({center:t,radius:e.radius,roundRadius:e.roundRadius,segments:e.segments,height:e.height})))}sphere(e){return this.jscad.primitives.sphere({center:[e.center[0],e.center[1],e.center[2]],radius:e.radius,segments:e.segments})}spheresOnCenterPoints(e){return e.centers.map((t=>this.sphere({center:t,radius:e.radius,segments:e.segments})))}torus(e){return this.jscad.primitives.torus({center:[e.center[0],e.center[1],e.center[2]],innerRadius:e.innerRadius,outerRadius:e.outerRadius,innerSegments:e.innerSegments,outerSegments:e.outerSegments,innerRotation:Hs.FromDegrees(e.innerRotation).radians(),outerRotation:Hs.FromDegrees(e.outerRotation).radians(),startAngle:Hs.FromDegrees(e.startAngle).radians()})}fromPolygonPoints(e){const t=e.polygonPoints.map((e=>e.reverse()));return this.jscad.geometries.geom3.fromPoints(t)}}class Cy{constructor(e){this.jscad=e}cylindricalText(e){const t=this.createVectorText(e);return this.adjustTextToBeOnCenter(t),t.map((t=>{const i=t.map((t=>this.jscad.primitives.cylinder({center:[t[0],t[1],0],height:e.extrusionHeight,radius:e.extrusionSize,segments:e.segments})));return this.jscad.hulls.hullChain(...i)}))}sphericalText(e){const t=this.createVectorText(e);return this.adjustTextToBeOnCenter(t),t.map((t=>{const i=t.map((t=>this.jscad.primitives.sphere({center:[t[0],t[1],0],radius:e.radius,segments:e.segments})));return this.jscad.hulls.hullChain(...i)}))}adjustTextToBeOnCenter(e){let t=0;e.forEach((e=>{e.forEach((e=>{e[0]>t&&(t=e[0])}))}));const i=t/2;e.forEach((e=>{e.forEach((e=>{let t=e[0];t-=i,e[0]=t}))}))}createVectorText(e){return this.jscad.text.vectorText({input:e.text,xOffset:e.xOffset,yOffset:e.yOffset,height:e.height,lineSpacing:e.lineSpacing,letterSpacing:e.letterSpacing,align:e.align,extrudeOffset:e.extrudeOffset})}}class yy{constructor(e){this.jscad=e}hullChain(e){return this.jscad.hulls.hullChain(...e.meshes)}hull(e){return this.jscad.hulls.hull(...e.meshes)}}class Ay{constructor(e){this.jscad=e}colorize(e){const t=e.geometry,i=e.color;return this.jscad.colors.colorize(this.jscad.colors.hexToRgb(i),t)}}class Ry{constructor(e){this.getArrayDepth=e=>Array.isArray(e)?1+Math.max(...e.map(this.getArrayDepth)):0;const t=new r;this.booleans=new h(e),this.expansions=new l(e),this.extrusions=new Ty(e,t),this.hulls=new yy(e),this.path=new Sy(e,t),this.polygon=new Ey(e,t),this.shapes=new by(e),this.text=new Cy(e),this.colors=new Ay(e),this.jscad=e}shapesToMeshes(e){return e.meshes.map((t=>this.shapeToMesh(Object.assign(Object.assign({},e),{mesh:t}))))}shapeToMesh(e){let t=[];if(e.mesh.toPolygons)t=e.mesh.toPolygons();else if(e.mesh.polygons)t=e.mesh.polygons;else if(e.mesh.sides||e.mesh.vertices){const i=this.extrusions.extrudeLinear({height:.001,twistAngle:0,twistSteps:1,geometry:e.mesh});i.toPolygons?t=i.toPolygons():i.polygons&&(t=i.polygons)}const i=[],s=[];let r=0;for(const e of t)if(3===e.vertices.length)e.vertices.forEach((e=>{i.push(e[0],e[1],e[2]),s.push(r),r++}));else{const t=[],n=e.vertices,o=n[0];for(let e=n.length-3;e>=0;e--)t.push([o,n[e+1],n[e+2]]);t.forEach(((e,t)=>{e.forEach((e=>{i.push(e[0],e[1],e[2]),s.push(r),r++}))}))}return{positions:i,normals:[],indices:s,transforms:e.mesh.transforms}}transformSolids(e){return e.meshes.map((t=>this.transformSolid({mesh:t,transformation:e.transformation})))}transformSolid(e){const t=e.transformation;let i=this.jscad.geometries.geom3.clone(e.mesh);return 2===this.getArrayDepth(t)?t.forEach((e=>{i=this.jscad.transforms.transform(e,i)})):3===this.getArrayDepth(t)?t.forEach((e=>{e.forEach((e=>{i=this.jscad.transforms.transform(e,i)}))})):i=this.jscad.transforms.transform(t,i),i}downloadSolidSTL(e){const t=this.jscad.STLSERIALIZER.serialize({binary:!0},e.mesh);return{blob:new Blob(t,{type:"application/sla"})}}downloadGeometryDxf(e){const t=this.jscad.DXFSERIALIZER.serialize({},e.geometry);return{blob:new Blob(t)}}downloadSolidsSTL(e){const t=this.jscad.STLSERIALIZER.serialize({binary:!0},...e.meshes);return{blob:new Blob(t,{type:"application/sla"})}}}let Iy,Py;Promise.resolve().then(i.bind(i,263)).then((function(e){var t;t=e.default(),Py=new s(t),Iy=new Ry(t),postMessage("jscad-initialised"),postMessage("jscad-initialised")})),addEventListener("message",(function(e){((e,t)=>{let i;t("busy");try{if("startedTheRun"!==e.action.functionName&&"cleanAllCache"!==e.action.functionName){const t=e.action.functionName.split(".");i=2===t.length?Py.cacheOp(e.action,(()=>Iy[t[0]][t[1]](e.action.inputs))):Py.cacheOp(e.action,(()=>Iy[e.action.functionName](e.action.inputs)))}"startedTheRun"===e.action.functionName&&(Py&&Object.keys(Py.usedHashes).length>1e4&&Py.cleanAllCache(),i={}),"cleanAllCache"===e.action.functionName&&(Py.cleanAllCache(),i={}),t({uid:e.uid,result:i})}catch(i){let s,r;e&&e.action&&e.action.inputs&&(s=`Input values were: {${Object.keys(e.action.inputs).map((t=>`${t}: ${e.action.inputs[t]}`)).join(",")}}. `),e&&e.action&&e.action.functionName&&(r=`- ${e.action.functionName}`),t({uid:e.uid,result:void 0,error:`JSCAD computation failed when executing function ${r}. ${s}Original message: ${i}`})}})(e.data,postMessage)}))},725:()=>{},439:()=>{},699:()=>{}},t={};function i(s){var r=t[s];if(void 0!==r)return r.exports;var n=t[s]={exports:{}};return e[s](n,n.exports,i),n.exports}i.d=(e,t)=>{for(var s in t)i.o(t,s)&&!i.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i(263),i(568)})(); \ No newline at end of file diff --git a/workers/bitbybit-occt-webworker.js b/workers/bitbybit-occt-webworker.js index 44c6679..293f0eb 100644 --- a/workers/bitbybit-occt-webworker.js +++ b/workers/bitbybit-occt-webworker.js @@ -1,2 +1,2 @@ /*! For license information please see bitbybit-occt-webworker.js.LICENSE.txt */ -(()=>{var e={725:()=>{},439:()=>{},699:()=>{},256:()=>{}},t={};function r(i){var n=t[i];if(void 0!==n)return n.exports;var s=t[i]={exports:{}};return e[i](s,s.exports,r),s.exports}r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{"use strict";var e={};r.r(e),r.d(e,{Base:()=>W,OCCT:()=>U});var t={};r.r(t),r.d(t,{LodDto:()=>Ge,lodEnum:()=>Be});var i={};r.r(i),r.d(i,{Part:()=>He});var n={};r.r(n),r.d(n,{SerenitySwirlData:()=>ze,SerenitySwirlDto:()=>Ve});var s={};r.r(s),r.d(s,{ArabicArchwayData:()=>$e,ArabicArchwayDrawingPart:()=>Ye,ArabicArchwayDrawingPartShapes:()=>Xe,ArabicArchwayDto:()=>qe,ArabicArchwayDtoBase:()=>je});var o={};r.r(o),r.d(o,{ArabicArchway:()=>s,SerenitySwirl:()=>n});var a={};r.r(a),r.d(a,{EternalLoveData:()=>Qe,EternalLoveDto:()=>Je,EternalLoveDtoBase:()=>Ze});var c={};r.r(c),r.d(c,{EternalLove:()=>a});var h={};r.r(h),r.d(h,{CalmCupData:()=>tt,CalmCupDto:()=>et,CalmCupDtoBase:()=>Ke});var l={};r.r(l),r.d(l,{DragonCupData:()=>nt,DragonCupDto:()=>it,DragonCupDtoBase:()=>rt,DragonCupModelDto:()=>st});var u={};r.r(u),r.d(u,{CalmCup:()=>h,DragonCup:()=>l});var d={};r.r(d),r.d(d,{PhoneNestData:()=>ct,PhoneNestDrawDto:()=>pt,PhoneNestDrawingPart:()=>ht,PhoneNestDrawingPartShapes:()=>lt,PhoneNestDto:()=>at,PhoneNestDtoBase:()=>ot,PhoneNestMainPart:()=>ut,PhoneNestModelDto:()=>dt});var p={};r.r(p),r.d(p,{PhoneNest:()=>d});var f={};r.r(f),r.d(f,{SpicyBoxData:()=>vt,SpicyBoxDto:()=>gt,SpicyBoxDtoBase:()=>ft,SpicyBoxModelDto:()=>mt});var g={};r.r(g),r.d(g,{SpicyBox:()=>f});var v={};r.r(v),r.d(v,{Boxes:()=>g,Cups:()=>u,Desktop:()=>p,Medals:()=>c,Vases:()=>o});var m={};r.r(m),r.d(m,{ZenHideoutData:()=>bt,ZenHideoutDrawingPart:()=>wt,ZenHideoutDrawingPartShapes:()=>Et,ZenHideoutDto:()=>St,ZenHideoutDtoBase:()=>yt});var y={};r.r(y),r.d(y,{ZenHideout:()=>m});var S={};r.r(S),r.d(S,{BeamPart:()=>Ft,CeilingPart:()=>Ht,ColumnPart:()=>Rt,CornerEntranceDto:()=>zt,CornerEntrancePart:()=>Wt,CornerPart:()=>Dt,CornerStairDto:()=>It,CornerStairPart:()=>Ut,FloorPart:()=>Vt,Houses:()=>y,RoofBeamsPart:()=>Bt,RoofCoverOneSidedDto:()=>Nt,RoofCoverPart:()=>Gt,RoofPanelPart:()=>Mt,RoofPart:()=>Lt,SandwitchPanelDto:()=>Ct,SandwitchPanelFlexDto:()=>At,SandwitchPart:()=>_t,SandwitchPartFlex:()=>Ot,WindowCornerDto:()=>Tt,WindowCornerPart:()=>Pt,WindowRectangularDto:()=>xt,WindowRectangularPart:()=>kt});var b={};r.r(b),r.d(b,{WingtipVillaData:()=>qt,WingtipVillaDto:()=>jt});var w={};r.r(w),r.d(w,{ChirpyChaletData:()=>Yt,ChirpyChaletDto:()=>$t});var E={};r.r(E),r.d(E,{ChirpyChalet:()=>w,WingtipVilla:()=>b});var T={};r.r(T),r.d(T,{BirdHouses:()=>E});var x={};r.r(x),r.d(x,{SnakeChairData:()=>Jt,SnakeChairDrawDto:()=>rr,SnakeChairDrawingPart:()=>Qt,SnakeChairDrawingPartShapes:()=>Kt,SnakeChairDto:()=>Zt,SnakeChairDtoBase:()=>Xt,SnakeChairMainPart:()=>er,SnakeChairModelDto:()=>tr});var k={};r.r(k),r.d(k,{SnakeChair:()=>x});var P={};r.r(P),r.d(P,{ElegantTableData:()=>sr,ElegantTableDrawDto:()=>dr,ElegantTableDrawingPart:()=>or,ElegantTableDrawingPartShapes:()=>ar,ElegantTableDto:()=>nr,ElegantTableDtoBase:()=>ir,ElegantTableLegByIndexDto:()=>lr,ElegantTableLegPart:()=>cr,ElegantTableModelDto:()=>ur,ElegantTableTopPart:()=>hr});var C={};r.r(C),r.d(C,{GoodCoffeeTableData:()=>gr,GoodCoffeeTableDrawDto:()=>Tr,GoodCoffeeTableDrawingPart:()=>vr,GoodCoffeeTableDrawingPartShapes:()=>mr,GoodCoffeeTableDto:()=>fr,GoodCoffeeTableDtoBase:()=>pr,GoodCoffeeTableLegByIndexDto:()=>wr,GoodCoffeeTableLegPart:()=>yr,GoodCoffeeTableModelDto:()=>Er,GoodCoffeeTableShelfPart:()=>Sr,GoodCoffeeTableTopPart:()=>br});var A={};r.r(A),r.d(A,{SnakeTableData:()=>Pr,SnakeTableDrawDto:()=>Dr,SnakeTableDrawingPart:()=>Cr,SnakeTableDrawingPartShapes:()=>Ar,SnakeTableDto:()=>kr,SnakeTableDtoBase:()=>xr,SnakeTableMainPart:()=>_r,SnakeTableModelDto:()=>Or});var _={};r.r(_),r.d(_,{ElegantTable:()=>P,GoodCoffeeTable:()=>C,SnakeTable:()=>A});var O={};r.r(O),r.d(O,{Chairs:()=>k,Tables:()=>_});var D={};r.r(D),r.d(D,{Architecture:()=>S,Enums:()=>t,Furniture:()=>O,KidsCorner:()=>T,Shared:()=>i,ThreeDPrinting:()=>v});var R={};r.r(R),r.d(R,{FontDefinition:()=>Ir,Text3DData:()=>Br,Text3DDto:()=>Fr,Text3DFaceDefinitionDto:()=>Wr,Text3DFaceDto:()=>Lr,Text3DLetterByIndexDto:()=>Mr,Text3DModelDto:()=>Ur,Texts3DFaceDto:()=>Nr,faceTextVarEnum:()=>Ue,faceTypeEnum:()=>We,fontVariantsEnum:()=>Ie,fontsEnum:()=>Me,fontsModel:()=>Rr,recAlignmentEnum:()=>Ne});var F={};r.r(F),r.d(F,{PyramidSimpeByIndexDto:()=>zr,PyramidSimpleAffectorsDto:()=>Hr,PyramidSimpleCellPart:()=>Kr,PyramidSimpleData:()=>Vr,PyramidSimpleDto:()=>Gr,PyramidSimpleFacePart:()=>ei,PyramidSimpleModelCellDto:()=>Yr,PyramidSimpleModelCellsDto:()=>qr,PyramidSimpleModelCellsIndexDto:()=>$r,PyramidSimpleModelDto:()=>jr,PyramidSimpleModelFaceCellIndexDto:()=>Zr,PyramidSimpleModelFaceCellsUIndexDto:()=>Jr,PyramidSimpleModelFaceCellsVIndexDto:()=>Qr,PyramidSimpleModelFaceIndexDto:()=>Xr});var L={};r.r(L),r.d(L,{PyramidSimple:()=>F});var B={};r.r(B),r.d(B,{FacePatterns:()=>L});var M={};r.r(M),r.d(M,{outputShapeEnum:()=>ti});var I,U,W,N,G={};r.r(G),r.d(G,{Enums:()=>M,Patterns:()=>B,Text3D:()=>R}),(N=I||(I={})).loading="loading",N.loaded="loaded",N.initialised="initialised",N.computing="computing";class H{starLines(e,t,r,i,n){let s=[];const o=2*Math.PI/r;for(let i=0;i=i&&(e=i-1e-6,console.warn("width first is bigger than length second, to make it work, width second is set to length first - 1e-6")),r>=t&&(r=t-1e-6,console.warn("width second is bigger than length first, to make it work, width second is set to length first - 1e-6")),[[0,0,0],[t,0,0],[t,0,e],[r,0,e],[r,0,i],[0,0,i]]}polygonLMiddle(e,t,r,i){return e>=i&&(e=i-1e-6,console.warn("width first is bigger than length second, to make it work, width second is set to length first - 1e-6")),r>=t&&(r=t-1e-6,console.warn("width second is bigger than length first, to make it work, width second is set to length first - 1e-6")),[[r/2,0,e/2],[r/2,0,i],[-r/2,0,i],[-r/2,0,-e/2],[t,0,-e/2],[t,0,e/2]]}}class V{constructor(){this.tolerance=1e-5}degToRad(e){return e*(Math.PI/180)}remap(e,t,r,i,n){return(e-t)/(r-t)*(n-i)+i}removeAllDuplicateVectors(e,t=1e-7){const r=[];return e.forEach((e=>{r.some((r=>this.vectorsTheSame(e,r,t)))||r.push(e)})),r}removeConsecutiveDuplicates(e,t=!0){const r=[];if(e.length>1){for(let t=1;te.map(((e,r)=>e+t[r]))),[0,0,0]).map((t=>t/e.length))}magnitude(e){return Math.sqrt(e.reduce(((e,t)=>e+t*t),0))}normalize(e){const t=this.magnitude(e);return e.map((e=>e/t))}translatePoint(e,t,r){return[e[0]+t[0]*r,e[1]+t[1]*r,e[2]+t[2]*r]}distanceBetweenPoints(e,t){const r=t[0]-e[0],i=t[1]-e[1],n=t[2]-e[2];return Math.sqrt(r*r+i*i+n*n)}}!function(e){let t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v;!function(e){e.arc="arc",e.intersection="intersection",e.tangent="tangent"}(t=e.joinTypeEnum||(e.joinTypeEnum={})),function(e){e.skin="skin",e.pipe="pipe",e.rectoVerso="rectoVerso"}(r=e.bRepOffsetModeEnum||(e.bRepOffsetModeEnum={})),function(e){e.approxChordLength="approxChordLength",e.approxCentripetal="approxCentripetal",e.approxIsoParametric="approxIsoParametric"}(i=e.approxParametrizationTypeEnum||(e.approxParametrizationTypeEnum={})),function(e){e.outside="outside",e.inside="inside",e.middle="middle"}(n=e.directionEnum||(e.directionEnum={})),function(e){e.iges="iges",e.step="step"}(s=e.fileTypeEnum||(e.fileTypeEnum={})),function(e){e.forward="forward",e.reversed="reversed",e.internal="internal",e.external="external"}(o=e.topAbsOrientationEnum||(e.topAbsOrientationEnum={})),function(e){e.in="in",e.out="out",e.on="on",e.unknown="unknown"}(a=e.topAbsStateEnum||(e.topAbsStateEnum={})),function(e){e.unknown="unknown",e.vertex="vertex",e.edge="edge",e.wire="wire",e.face="face",e.shell="shell",e.solid="solid",e.compSolid="compSolid",e.compound="compound",e.shape="shape"}(c=e.shapeTypeEnum||(e.shapeTypeEnum={})),function(e){e.unqualified="unqualified",e.enclosing="enclosing",e.enclosed="enclosed",e.outside="outside",e.noqualifier="noqualifier"}(h=e.gccEntPositionEnum||(e.gccEntPositionEnum={})),function(e){e.keepSide1="keepSide1",e.keepSide2="keepSide2",e.all="all"}(l=e.positionResultEnum||(e.positionResultEnum={})),function(e){e.none="none",e.keepSide1="keepSide1",e.keepSide2="keepSide2"}(u=e.circleInclusionEnum||(e.circleInclusionEnum={})),function(e){e.none="none",e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(d=e.twoCircleInclusionEnum||(e.twoCircleInclusionEnum={})),function(e){e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(p=e.fourSidesStrictEnum||(e.fourSidesStrictEnum={})),function(e){e.outside="outside",e.inside="inside"}(f=e.twoSidesStrictEnum||(e.twoSidesStrictEnum={})),function(e){e.allWithAll="allWithAll",e.inOrder="inOrder",e.inOrderClosed="inOrderClosed"}(g=e.combinationCirclesForFaceEnum||(e.combinationCirclesForFaceEnum={})),function(e){e[e.curve=0]="curve",e[e.edge=1]="edge",e[e.wire=2]="wire",e[e.face=3]="face"}(v=e.typeSpecificityEnum||(e.typeSpecificityEnum={})),e.DecomposedMeshDto=class{constructor(e,t){void 0!==e&&(this.faceList=e),void 0!==t&&(this.edgeList=t)}},e.DecomposedFaceDto=class{},e.DecomposedEdgeDto=class{},e.ShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.PointDto=class{constructor(e){this.point=[0,0,0],void 0!==e&&(this.point=e)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.ConstraintTanLinesFromPtToCircleDto=class{constructor(e,t,r,i,n){this.tolerance=1e-7,this.positionResult=l.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.positionResult=i),void 0!==n&&(this.circleRemainder=n)}},e.ConstraintTanLinesFromTwoPtsToCircleDto=class{constructor(e,t,r,i,n,s){this.tolerance=1e-7,this.positionResult=l.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point1=t),void 0!==r&&(this.point1=r),void 0!==i&&(this.tolerance=i),void 0!==n&&(this.positionResult=n),void 0!==s&&(this.circleRemainder=s)}},e.ConstraintTanLinesOnTwoCirclesDto=class{constructor(e,t,r,i,n){this.tolerance=1e-7,this.positionResult=l.all,this.circleRemainders=d.none,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.positionResult=i),void 0!==n&&(this.circleRemainders=n)}},e.ConstraintTanCirclesOnTwoCirclesDto=class{constructor(e,t,r,i){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.radius=i)}},e.ConstraintTanCirclesOnCircleAndPntDto=class{constructor(e,t,r,i){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.radius=i)}},e.CurveAndSurfaceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t)}},e.FilletTwoEdgesInPlaneDto=class{constructor(e,t,r,i,n,s){this.planeOrigin=[0,0,0],this.planeDirection=[0,1,0],this.radius=.3,this.solution=-1,void 0!==e&&(this.edge1=e),void 0!==t&&(this.edge2=t),void 0!==r&&(this.planeOrigin=r),void 0!==i&&(this.planeDirection=i),void 0!==n&&(this.radius=n),void 0!==s&&(this.solution=s)}},e.ClosestPointsOnShapeFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.SplitWireOnPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.ClosestPointsOnShapesFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shapes=e),void 0!==t&&(this.points=t)}},e.ClosestPointsBetweenTwoShapesDto=class{constructor(e,t){void 0!==e&&(this.shape1=e),void 0!==t&&(this.shape2=t)}},e.FaceFromSurfaceAndWireDto=class{constructor(e,t,r){this.inside=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.wire=t),void 0!==r&&(this.inside=r)}},e.WireOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wire=e),void 0!==t&&(this.face=t)}},e.DrawShapeDto=class{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shape=e),void 0!==t&&(this.faceOpacity=t),void 0!==r&&(this.edgeOpacity=r),void 0!==i&&(this.edgeColour=i),void 0!==n&&(this.faceMaterial=n),void 0!==s&&(this.faceColour=s),void 0!==l&&(this.vertexColour=l),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==c&&(this.drawFaces=c),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdgeIndexes=p),void 0!==f&&(this.edgeIndexHeight=f),void 0!==g&&(this.edgeIndexColour=g),void 0!==v&&(this.drawFaceIndexes=v),void 0!==m&&(this.faceIndexHeight=m),void 0!==y&&(this.faceIndexColour=y)}},e.DrawShapesDto=class{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shapes=e),void 0!==t&&(this.faceOpacity=t),void 0!==r&&(this.edgeOpacity=r),void 0!==i&&(this.edgeColour=i),void 0!==n&&(this.faceMaterial=n),void 0!==s&&(this.faceColour=s),void 0!==l&&(this.vertexColour=l),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==c&&(this.drawFaces=c),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdgeIndexes=p),void 0!==f&&(this.edgeIndexHeight=f),void 0!==g&&(this.edgeIndexColour=g),void 0!==v&&(this.drawFaceIndexes=v),void 0!==m&&(this.faceIndexHeight=m),void 0!==y&&(this.faceIndexColour=y)}},e.FaceSubdivisionDto=class{constructor(e,t,r,i,n,s,o,a,c){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepU=!1,this.removeStartEdgeU=!1,this.removeEndEdgeU=!1,this.shiftHalfStepV=!1,this.removeStartEdgeV=!1,this.removeEndEdgeV=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==r&&(this.nrDivisionsV=r),void 0!==i&&(this.shiftHalfStepU=i),void 0!==n&&(this.removeStartEdgeU=n),void 0!==s&&(this.removeEndEdgeU=s),void 0!==o&&(this.shiftHalfStepV=o),void 0!==a&&(this.removeStartEdgeV=a),void 0!==c&&(this.removeEndEdgeV=c)}},e.FaceSubdivisionControlledDto=class{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepNthU=0,this.shiftHalfStepUOffsetN=0,this.removeStartEdgeNthU=0,this.removeStartEdgeUOffsetN=0,this.removeEndEdgeNthU=0,this.removeEndEdgeUOffsetN=0,this.shiftHalfStepNthV=0,this.shiftHalfStepVOffsetN=0,this.removeStartEdgeNthV=0,this.removeStartEdgeVOffsetN=0,this.removeEndEdgeNthV=0,this.removeEndEdgeVOffsetN=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==r&&(this.nrDivisionsV=r),void 0!==i&&(this.shiftHalfStepNthU=i),void 0!==n&&(this.shiftHalfStepUOffsetN=n),void 0!==s&&(this.removeStartEdgeNthU=s),void 0!==o&&(this.removeStartEdgeUOffsetN=o),void 0!==a&&(this.removeEndEdgeNthU=a),void 0!==c&&(this.removeEndEdgeUOffsetN=c),void 0!==h&&(this.shiftHalfStepNthV=h),void 0!==l&&(this.shiftHalfStepVOffsetN=l),void 0!==u&&(this.removeStartEdgeNthV=u),void 0!==d&&(this.removeStartEdgeVOffsetN=d),void 0!==p&&(this.removeEndEdgeNthV=p),void 0!==f&&(this.removeEndEdgeVOffsetN=f)}},e.FaceLinearSubdivisionDto=class{constructor(e,t,r,i,n,s,o){this.isU=!0,this.param=.5,this.nrPoints=10,this.shiftHalfStep=!1,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==r&&(this.param=r),void 0!==i&&(this.nrPoints=i),void 0!==n&&(this.shiftHalfStep=n),void 0!==s&&(this.removeStartPoint=s),void 0!==o&&(this.removeEndPoint=o)}},e.DataOnUVDto=class{constructor(e,t,r){this.paramU=.5,this.paramV=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.paramU=t),void 0!==r&&(this.paramV=r)}},e.DataOnUVsDto=class{constructor(e,t){this.paramsUV=[[.5,.5]],void 0!==e&&(this.shape=e),void 0!==t&&(this.paramsUV=t)}},e.PolygonDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolygonsDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polygons=e),void 0!==t&&(this.returnCompound=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolylinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.returnCompound=t)}},e.SquareDto=class{constructor(e,t,r){this.size=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t),void 0!==r&&(this.direction=r)}},e.RectangleDto=class{constructor(e,t,r,i){this.width=1,this.length=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==r&&(this.center=r),void 0!==i&&(this.direction=i)}},e.LPolygonDto=class{constructor(e,t,r,i,s,o,a,c){this.widthFirst=1,this.lengthFirst=2,this.widthSecond=.5,this.lengthSecond=2,this.align=n.outside,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.widthFirst=e),void 0!==t&&(this.lengthFirst=t),void 0!==r&&(this.widthSecond=r),void 0!==i&&(this.lengthSecond=i),void 0!==s&&(this.align=s),void 0!==o&&(this.rotation=o),void 0!==a&&(this.center=a),void 0!==c&&(this.direction=c)}},e.BoxDto=class{constructor(e,t,r,i){this.width=1,this.length=2,this.height=3,this.center=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==r&&(this.height=r),void 0!==i&&(this.center=i)}},e.CubeDto=class{constructor(e,t){this.size=1,this.center=[0,0,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t)}},e.BoxFromCornerDto=class{constructor(e,t,r,i){this.width=1,this.length=2,this.height=3,this.corner=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==r&&(this.height=r),void 0!==i&&(this.corner=i)}},e.SphereDto=class{constructor(e,t){this.radius=1,this.center=[0,0,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.ConeDto=class{constructor(e,t,r,i,n,s){this.radius1=2,this.radius2=1,this.height=2,this.angle=360,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius1=e),void 0!==t&&(this.radius2=t),void 0!==r&&(this.height=r),void 0!==i&&(this.angle=i),void 0!==n&&(this.center=n),void 0!==s&&(this.direction=s)}},e.LineDto=class{constructor(e,t){this.start=[0,0,0],this.end=[0,1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.returnCompound=t)}},e.ArcEdgeTwoPointsTangentDto=class{constructor(e,t,r){this.start=[0,0,0],this.tangentVec=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.tangentVec=t),void 0!==r&&(this.end=r)}},e.ArcEdgeCircleTwoPointsDto=class{constructor(e,t,r,i){this.start=[0,0,0],this.end=[0,0,1],this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.start=t),void 0!==r&&(this.end=r),void 0!==i&&(this.sense=i)}},e.ArcEdgeCircleTwoAnglesDto=class{constructor(e,t,r,i){this.alphaAngle1=0,this.alphaAngle2=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle1=t),void 0!==r&&(this.alphaAngle2=r),void 0!==i&&(this.sense=i)}},e.ArcEdgeCirclePointAngleDto=class{constructor(e,t,r,i){this.alphaAngle=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle=t),void 0!==i&&(this.sense=i)}},e.ArcEdgeThreePointsDto=class{constructor(e,t,r){this.start=[0,0,0],this.middle=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.middle=t),void 0!==r&&(this.end=r)}},e.CylinderDto=class{constructor(e,t,r,i){this.radius=1,this.height=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.height=t),void 0!==r&&(this.center=r),void 0!==i&&(this.direction=i)}},e.CylindersOnLinesDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.lines=t)}},e.FilletDto=class{constructor(e,t,r,i){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==r&&(this.radiusList=r),void 0!==i&&(this.indexes=i)}},e.FilletEdgesListDto=class{constructor(e,t,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radiusList=r)}},e.FilletEdgesListOneRadiusDto=class{constructor(e,t,r){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radius=r)}},e.FilletEdgeVariableRadiusDto=class{constructor(e,t,r,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.radiusList=r),void 0!==i&&(this.paramsU=i)}},e.FilletEdgesVariableRadiusDto=class{constructor(e,t,r,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radiusLists=r),void 0!==i&&(this.paramsULists=i)}},e.FilletEdgesSameVariableRadiusDto=class{constructor(e,t,r,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radiusList=r),void 0!==i&&(this.paramsU=i)}},e.Fillet3DWireDto=class{constructor(e,t,r,i,n){this.radius=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==r&&(this.direction=r),void 0!==i&&(this.radiusList=i),void 0!==n&&(this.indexes=n)}},e.ChamferDto=class{constructor(e,t,r,i){this.distance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.distance=t),void 0!==r&&(this.distanceList=r),void 0!==i&&(this.indexes=i)}},e.ChamferEdgesListDto=class{constructor(e,t,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.distanceList=r)}},e.ChamferEdgeDistAngleDto=class{constructor(e,t,r,i,n){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.face=r),void 0!==i&&(this.distance=i),void 0!==n&&(this.angle=n)}},e.ChamferEdgeTwoDistancesDto=class{constructor(e,t,r,i,n){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.face=r),void 0!==i&&(this.distance1=i),void 0!==n&&(this.distance2=n)}},e.ChamferEdgesTwoDistancesListsDto=class{constructor(e,t,r,i,n){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distances1=i),void 0!==n&&(this.distances2=n)}},e.ChamferEdgesTwoDistancesDto=class{constructor(e,t,r,i,n){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distance1=i),void 0!==n&&(this.distance2=n)}},e.ChamferEdgesDistsAnglesDto=class{constructor(e,t,r,i,n){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distances=i),void 0!==n&&(this.angles=n)}},e.ChamferEdgesDistAngleDto=class{constructor(e,t,r,i,n){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distance=i),void 0!==n&&(this.angle=n)}},e.BSplineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BSplinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bSplines=e),void 0!==t&&(this.returnCompound=t)}},e.WireFromTwoCirclesTanDto=class{constructor(e,t,r,i,n){this.keepLines=f.outside,this.circleRemainders=p.outside,this.tolerance=1e-7,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==r&&(this.keepLines=r),void 0!==i&&(this.circleRemainders=i),void 0!==n&&(this.tolerance=n)}},e.FaceFromMultipleCircleTanWiresDto=class{constructor(e,t,r,i){this.combination=g.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.circles=e),void 0!==t&&(this.combination=t),void 0!==r&&(this.unify=r),void 0!==i&&(this.tolerance=i)}},e.FaceFromMultipleCircleTanWireCollectionsDto=class{constructor(e,t,r,i){this.combination=g.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.listsOfCircles=e),void 0!==t&&(this.combination=t),void 0!==r&&(this.unify=r),void 0!==i&&(this.tolerance=i)}},e.ZigZagBetweenTwoWiresDto=class{constructor(e,t,r,i,n,s){this.nrZigZags=20,this.divideByEqualDistance=!1,this.zigZagsPerEdge=!0,void 0!==e&&(this.wire1=e),void 0!==t&&(this.wire2=t),void 0!==r&&(this.nrZigZags=r),void 0!==i&&(this.inverse=i),void 0!==n&&(this.divideByEqualDistance=n),void 0!==s&&(this.zigZagsPerEdge=s)}},e.InterpolationDto=class{constructor(e,t,r){this.periodic=!1,this.tolerance=1e-7,void 0!==e&&(this.points=e),void 0!==t&&(this.periodic=t),void 0!==r&&(this.tolerance=r)}},e.InterpolateWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.interpolations=e),void 0!==t&&(this.returnCompound=t)}},e.BezierDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BezierWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bezierWires=e),void 0!==t&&(this.returnCompound=t)}},e.DivideDto=class{constructor(e,t,r,i){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==r&&(this.removeStartPoint=r),void 0!==i&&(this.removeEndPoint=i)}},e.ProjectWireDto=class{constructor(e,t,r){this.direction=[0,1,0],void 0!==e&&(this.wire=e),void 0!==t&&(this.shape=t),void 0!==r&&(this.direction=r)}},e.WiresToPointsDto=class{constructor(e,t,r,i,n,s){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==r&&(this.curvatureDeflection=r),void 0!==i&&(this.minimumOfPoints=i),void 0!==n&&(this.uTolerance=n),void 0!==s&&(this.minimumLength=s)}},e.EdgesToPointsDto=class{constructor(e,t,r,i,n,s){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==r&&(this.curvatureDeflection=r),void 0!==i&&(this.minimumOfPoints=i),void 0!==n&&(this.uTolerance=n),void 0!==s&&(this.minimumLength=s)}},e.ProjectWiresDto=class{constructor(e,t,r){this.direction=[0,1,0],void 0!==e&&(this.wires=e),void 0!==t&&(this.shape=t),void 0!==r&&(this.direction=r)}},e.DivideShapesDto=class{constructor(e,t,r,i){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==r&&(this.removeStartPoint=r),void 0!==i&&(this.removeEndPoint=i)}},e.DataOnGeometryAtParamDto=class{constructor(e,t){this.param=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t)}},e.PointInFaceDto=class{constructor(e,t,r,i){this.tEdgeParam=.5,this.distance2DParam=.5,void 0!==e&&(this.face=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.tEdgeParam=r),void 0!==i&&(this.distance2DParam=i)}},e.DataOnGeometryAtLengthDto=class{constructor(e,t){this.length=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.length=t)}},e.CircleDto=class{constructor(e,t,r){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==r&&(this.direction=r)}},e.LoftDto=class{constructor(e,t){this.makeSolid=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t)}},e.LoftAdvancedDto=class{constructor(e,t,r,n,s,o,a,c,h,l,u,d){this.makeSolid=!1,this.closed=!1,this.periodic=!1,this.straight=!1,this.nrPeriodicSections=10,this.useSmoothing=!1,this.maxUDegree=3,this.tolerance=1e-7,this.parType=i.approxCentripetal,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t),void 0!==r&&(this.closed=r),void 0!==n&&(this.periodic=n),void 0!==s&&(this.straight=s),void 0!==o&&(this.nrPeriodicSections=o),void 0!==a&&(this.useSmoothing=a),void 0!==c&&(this.maxUDegree=c),void 0!==h&&(this.tolerance=h),void 0!==l&&(this.parType=l),void 0!==u&&(this.startVertex=u),void 0!==d&&(this.endVertex=d)}},e.OffsetDto=class{constructor(e,t,r,i){this.distance=.2,this.tolerance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.face=t),void 0!==r&&(this.distance=r),void 0!==i&&(this.tolerance=i)}},e.OffsetAdvancedDto=class{constructor(e,r,i,n,s,o){this.distance=.2,this.tolerance=.1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==r&&(this.face=r),void 0!==i&&(this.distance=i),void 0!==n&&(this.tolerance=n),void 0!==s&&(this.joinType=s),void 0!==o&&(this.removeIntEdges=o)}},e.RevolveDto=class{constructor(e,t,r,i){this.angle=360,this.direction=[0,1,0],this.copy=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==r&&(this.direction=r),void 0!==i&&(this.copy=i)}},e.ShapeShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.WiresOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t)}},e.PipeWiresCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.radius=t)}},e.PipeWireCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t)}},e.PipePolygonWireNGonDto=class{constructor(e,t,r){this.radius=.1,this.nrCorners=6,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==r&&(this.nrCorners=r)}},e.ExtrudeDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t)}},e.ExtrudeShapesDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.direction=t)}},e.SplitDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.UnionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.DifferenceDto=class{constructor(e,t,r){this.keepEdges=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t),void 0!==r&&(this.keepEdges=r)}},e.IntersectionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.ShapeDto=class{constructor(e){void 0!==e&&(this.shape=e)}},e.CompareShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.otherShape=t)}},e.FixSmallEdgesInWireDto=class{constructor(e,t,r){this.lockvtx=!1,this.precsmall=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.lockvtx=t),void 0!==r&&(this.precsmall=r)}},e.BasicShapeRepairDto=class{constructor(e,t,r,i){this.precision=.001,this.maxTolerance=.01,this.minTolerance=1e-4,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==r&&(this.maxTolerance=r),void 0!==i&&(this.minTolerance=i)}},e.FixClosedDto=class{constructor(e,t){this.precision=-.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t)}},e.ShapesWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.ShapeWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.tolerance=t)}},e.ShapeIndexDto=class{constructor(e,t){this.index=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.EdgeIndexDto=class{constructor(e,t){this.index=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.RotationExtrudeDto=class{constructor(e,t,r){this.height=1,this.angle=360,void 0!==e&&(this.shape=e),void 0!==t&&(this.height=t),void 0!==r&&(this.angle=r)}},e.ThickSolidByJoinDto=class{constructor(e,r,i,n,s,o,a,c){this.offset=1,this.tolerance=.001,this.intersection=!1,this.selfIntersection=!1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==r&&(this.shapes=r),void 0!==i&&(this.offset=i),void 0!==n&&(this.tolerance=n),void 0!==s&&(this.intersection=s),void 0!==o&&(this.selfIntersection=o),void 0!==a&&(this.joinType=a),void 0!==c&&(this.removeIntEdges=c)}},e.TransformDto=class{constructor(e,t,r,i,n){this.translation=[0,0,0],this.rotationAxis=[0,1,0],this.rotationAngle=0,this.scaleFactor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t),void 0!==r&&(this.rotationAxis=r),void 0!==i&&(this.rotationAngle=i),void 0!==n&&(this.scaleFactor=n)}},e.TransformShapesDto=class{constructor(e,t,r,i,n){this.translations=[[0,0,0]],this.rotationAxes=[[0,1,0]],this.rotationAngles=[0],this.scaleFactors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t),void 0!==r&&(this.rotationAxes=r),void 0!==i&&(this.rotationAngles=i),void 0!==n&&(this.scaleFactors=n)}},e.TranslateDto=class{constructor(e,t){this.translation=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t)}},e.TranslateShapesDto=class{constructor(e,t){this.translations=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t)}},e.AlignDto=class{constructor(e,t,r,i,n){this.fromOrigin=[0,0,0],this.fromDirection=[0,0,1],this.toOrigin=[0,1,0],this.toDirection=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.fromOrigin=t),void 0!==r&&(this.fromDirection=r),void 0!==i&&(this.toOrigin=i),void 0!==n&&(this.toDirection=n)}},e.AlignShapesDto=class{constructor(e,t,r,i,n){this.fromOrigins=[[0,0,0]],this.fromDirections=[[0,0,1]],this.toOrigins=[[0,1,0]],this.toDirections=[[0,1,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.fromOrigins=t),void 0!==r&&(this.fromDirections=r),void 0!==i&&(this.toOrigins=i),void 0!==n&&(this.toDirections=n)}},e.MirrorDto=class{constructor(e,t,r){this.origin=[0,0,0],this.direction=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==r&&(this.direction=r)}},e.MirrorShapesDto=class{constructor(e,t,r){this.origins=[[0,0,0]],this.directions=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==r&&(this.directions=r)}},e.MirrorAlongNormalDto=class{constructor(e,t,r){this.origin=[0,0,0],this.normal=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==r&&(this.normal=r)}},e.MirrorAlongNormalShapesDto=class{constructor(e,t,r){this.origins=[[0,0,0]],this.normals=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==r&&(this.normals=r)}},e.AlignAndTranslateDto=class{constructor(e,t,r){this.direction=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.center=r)}},e.UnifySameDomainDto=class{constructor(e,t,r,i){this.unifyEdges=!0,this.unifyFaces=!0,this.concatBSplines=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.unifyEdges=t),void 0!==r&&(this.unifyFaces=r),void 0!==i&&(this.concatBSplines=i)}},e.FilterFacePointsDto=class{constructor(e,t,r,i,n,s,o,a,c){this.tolerance=1e-4,this.useBndBox=!1,this.gapTolerance=.1,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.useBndBox=i),void 0!==n&&(this.gapTolerance=n),void 0!==s&&(this.keepIn=s),void 0!==o&&(this.keepOn=o),void 0!==a&&(this.keepOut=a),void 0!==c&&(this.keepUnknown=c)}},e.FilterSolidPointsDto=class{constructor(e,t,r,i,n,s,o){this.tolerance=1e-4,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.keepIn=i),void 0!==n&&(this.keepOn=n),void 0!==s&&(this.keepOut=s),void 0!==o&&(this.keepUnknown=o)}},e.AlignAndTranslateShapesDto=class{constructor(e,t,r){this.directions=[[0,1,0]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.directions=t),void 0!==r&&(this.centers=r)}},e.RotateDto=class{constructor(e,t,r){this.axis=[0,0,1],this.angle=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.axis=t),void 0!==r&&(this.angle=r)}},e.RotateAroundCenterDto=class{constructor(e,t,r,i){this.angle=0,this.center=[0,0,0],this.axis=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==r&&(this.center=r),void 0!==i&&(this.axis=i)}},e.RotateShapesDto=class{constructor(e,t,r){this.angles=[0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.axes=t),void 0!==r&&(this.angles=r)}},e.RotateAroundCenterShapesDto=class{constructor(e,t,r,i){this.angles=[0],this.centers=[[0,0,0]],this.axes=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.angles=t),void 0!==r&&(this.centers=r),void 0!==i&&(this.axes=i)}},e.ScaleDto=class{constructor(e,t){this.factor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.factor=t)}},e.ScaleShapesDto=class{constructor(e,t){this.factors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.factors=t)}},e.Scale3DDto=class{constructor(e,t,r){this.scale=[1,1,1],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.scale=t),void 0!==r&&(this.center=r)}},e.Scale3DShapesDto=class{constructor(e,t,r){this.scales=[[1,1,1]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.scales=t),void 0!==r&&(this.centers=r)}},e.ShapeToMeshDto=class{constructor(e,t,r){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==r&&(this.adjustYtoZ=r)}},e.ShapesToMeshesDto=class{constructor(e,t,r){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.precision=t),void 0!==r&&(this.adjustYtoZ=r)}},e.SaveStepDto=class{constructor(e,t,r,i){this.fileName="shape.step",this.adjustYtoZ=!1,this.tryDownload=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==r&&(this.adjustYtoZ=r),void 0!==i&&(this.tryDownload=i)}},e.SaveStlDto=class{constructor(e,t,r,i,n,s){this.fileName="shape.stl",this.precision=.01,this.adjustYtoZ=!1,this.tryDownload=!0,this.binary=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==r&&(this.precision=r),void 0!==i&&(this.adjustYtoZ=i),void 0!==n&&(this.tryDownload=n),void 0!==s&&(this.binary=s)}},e.ImportStepIgesFromTextDto=class{constructor(e,t,r){this.fileType=s.step,this.adjustZtoY=!0,void 0!==e&&(this.text=e),void 0!==t&&(this.fileType=t),void 0!==r&&(this.adjustZtoY=r)}},e.ImportStepIgesDto=class{constructor(e,t){this.adjustZtoY=!0,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.adjustZtoY=t)}},e.LoadStepOrIgesDto=class{constructor(e,t,r){this.fileName="shape.igs",this.adjustZtoY=!0,void 0!==e&&(this.filetext=e),void 0!==t&&(this.fileName=t),void 0!==r&&(this.adjustZtoY=r)}},e.CompoundShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.ThisckSolidSimpleDto=class{constructor(e,t){this.offset=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t)}},e.Offset3DWireDto=class{constructor(e,t,r){this.offset=1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t),void 0!==r&&(this.direction=r)}},e.FaceFromWireDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.planar=t)}},e.FaceFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.FacesFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.SewDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.FaceIsoCurveAtParamDto=class{constructor(e,t,r){this.dir="u",void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t),void 0!==r&&(this.dir=r)}},e.DivideFaceToUVPointsDto=class{constructor(e,t,r,i){this.nrOfPointsU=10,this.nrOfPointsV=10,this.flat=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfPointsU=t),void 0!==r&&(this.nrOfPointsV=r),void 0!==i&&(this.flat=i)}},e.Geom2dEllipseDto=class{constructor(e,t,r,i,n){this.center=[0,0],this.direction=[1,0],this.radiusMinor=1,this.radiusMajor=2,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.radiusMinor=r),void 0!==i&&(this.radiusMajor=i),void 0!==n&&(this.sense=n)}},e.Geom2dCircleDto=class{constructor(e,t,r,i){this.center=[0,0],this.direction=[1,0],this.radius=1,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.radius=r),void 0!==i&&(this.sense=i)}},e.ChristmasTreeDto=class{constructor(e,t,r,i,n,s,o,a,c,h){this.height=6,this.innerDist=1.5,this.outerDist=3,this.nrSkirts=5,this.trunkHeight=1,this.trunkWidth=1,this.half=!1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.innerDist=t),void 0!==r&&(this.outerDist=r),void 0!==i&&(this.nrSkirts=i),void 0!==n&&(this.trunkHeight=n),void 0!==s&&(this.trunkWidth=s),void 0!==o&&(this.half=o),void 0!==a&&(this.rotation=a),void 0!==c&&(this.origin=c),void 0!==h&&(this.direction=h)}},e.StarDto=class{constructor(e,t,r,i,n,s,o){this.center=[0,0,0],this.direction=[0,1,0],this.numRays=7,this.half=!1,void 0!==e&&(this.outerRadius=e),void 0!==t&&(this.innerRadius=t),void 0!==r&&(this.numRays=r),void 0!==i&&(this.center=i),void 0!==n&&(this.direction=n),void 0!==s&&(this.offsetOuterEdges=s),void 0!==o&&(this.half=o)}},e.ParallelogramDto=class{constructor(e,t,r,i,n,s){this.center=[0,0,0],this.direction=[0,1,0],this.aroundCenter=!0,this.width=2,this.height=1,this.angle=15,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.aroundCenter=r),void 0!==i&&(this.width=i),void 0!==n&&(this.height=n),void 0!==s&&(this.angle=s)}},e.Heart2DDto=class{constructor(e,t,r,i){this.center=[0,0,0],this.direction=[0,1,0],this.rotation=0,this.sizeApprox=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.rotation=r),void 0!==i&&(this.sizeApprox=i)}},e.NGonWireDto=class{constructor(e,t,r,i){this.center=[0,0,0],this.direction=[0,1,0],this.nrCorners=6,this.radius=1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.nrCorners=r),void 0!==i&&(this.radius=i)}},e.EllipseDto=class{constructor(e,t,r,i){this.center=[0,0,0],this.direction=[0,1,0],this.radiusMinor=1,this.radiusMajor=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.radiusMinor=r),void 0!==i&&(this.radiusMajor=i)}},e.GeomCylindricalSurfaceDto=class{constructor(e,t,r){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==r&&(this.direction=r)}},e.Geom2dTrimmedCurveDto=class{constructor(e,t,r,i,n){this.u1=0,this.u2=1,this.sense=!0,this.adjustPeriodic=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.u1=t),void 0!==r&&(this.u2=r),void 0!==i&&(this.sense=i),void 0!==n&&(this.adjustPeriodic=n)}},e.Geom2dSegmentDto=class{constructor(e,t){this.start=[0,0],this.end=[1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.SliceDto=class{constructor(e,t,r){this.step=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.step=t),void 0!==r&&(this.direction=r)}},e.SliceInStepPatternDto=class{constructor(e,t,r){this.steps=[.1,.2],this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.steps=t),void 0!==r&&(this.direction=r)}}}(U||(U={})),function(e){let t;!function(e){e.default="default",e.clearSky="clearSky",e.city="city"}(t=e.skyboxEnum||(e.skyboxEnum={}))}(W||(W={}));class z{constructor(e,t){this.occ=e,this.och=t}geom2dEllipse(e){const t=this.och.entitiesService.gpAx2d(e.center,e.direction),r=new this.occ.Geom2d_Ellipse_2(t,e.radiusMajor,e.radiusMinor,e.sense);return t.delete(),r}geom2dCircle(e){const t=this.och.entitiesService.gpAx2d(e.center,e.direction),r=new this.occ.Geom2d_Circle_2(t,e.radius,e.sense);return t.delete(),r}geom2dTrimmedCurve(e){const t=new this.occ.Handle_Geom2d_Curve_2(e.shape);return new this.occ.Geom2d_TrimmedCurve(t,e.u1,e.u2,e.sense,e.adjustPeriodic)}geom2dSegment(e){const t=this.och.entitiesService.gpPnt2d(e.start),r=this.och.entitiesService.gpPnt2d(e.end),i=new this.occ.GCE2d_MakeSegment_1(t,r),n=i.Value().get();return t.delete(),r.delete(),i.delete(),n}get2dPointFrom2dCurveOnParam(e){const t=e.shape.Value(e.param),r=[t.X(),t.Y()];return t.delete(),r}geomCircleCurve(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.curve)}geomEllipseCurve(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.curve)}}class j{constructor(e,t){this.occ=e,this.och=t}cylindricalSurface(e){const t=this.och.entitiesService.gpAx3(e.center,e.direction),r=new this.occ.Geom_CylindricalSurface_1(t,e.radius);return t.delete(),r}surfaceFromFace(e){return this.och.surfaceFromFace(e)}}class q{constructor(e,t){this.curves=new z(e,t),this.surfaces=new j(e,t)}}class ${constructor(e,t){this.occ=e,this.och=t}makeEdgeFromGeom2dCurveAndSurface(e){return this.och.edgesService.makeEdgeFromGeom2dCurveAndSurface(e)}line(e){return this.och.edgesService.lineEdge(e)}arcThroughThreePoints(e){return this.och.edgesService.arcThroughThreePoints(e)}arcThroughTwoPointsAndTangent(e){return this.och.edgesService.arcThroughTwoPointsAndTangent(e)}arcFromCircleAndTwoPoints(e){return this.och.edgesService.arcFromCircleAndTwoPoints(e)}arcFromCircleAndTwoAngles(e){return this.och.edgesService.arcFromCircleAndTwoAngles(e)}arcFromCirclePointAndAngle(e){return this.och.edgesService.arcFromCirclePointAndAngle(e)}createCircleEdge(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.edge)}createEllipseEdge(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.edge)}removeInternalEdges(e){const t=new this.occ.ShapeUpgrade_UnifySameDomain_2(e.shape,!0,!0,!1);t.Build();const r=t.Shape();return t.delete(),r}getEdge(e){return this.och.shapeGettersService.getEdge(e)}edgesToPoints(e){return this.och.edgesService.edgesToPoints(e)}reversedEdge(e){const t=e.shape.Reversed(),r=this.och.converterService.getActualTypeOfShape(t);return t.delete(),r}pointOnEdgeAtParam(e){return this.och.edgesService.pointOnEdgeAtParam(e)}tangentOnEdgeAtParam(e){return this.och.edgesService.tangentOnEdgeAtParam(e)}startPointOnEdge(e){return this.och.edgesService.startPointOnEdge(e)}endPointOnEdge(e){return this.och.edgesService.endPointOnEdge(e)}pointOnEdgeAtLength(e){return this.och.edgesService.pointOnEdgeAtLength(e)}tangentOnEdgeAtLength(e){return this.och.edgesService.tangentOnEdgeAtLength(e)}divideEdgeByParamsToPoints(e){return this.och.edgesService.divideEdgeByParamsToPoints(e)}divideEdgeByEqualDistanceToPoints(e){return this.och.edgesService.divideEdgeByEqualDistanceToPoints(e)}getEdges(e){return this.och.shapeGettersService.getEdges(e)}getEdgesAlongWire(e){return this.och.edgesService.getEdgesAlongWire(e)}getCircularEdgesAlongWire(e){return this.och.edgesService.getCircularEdgesAlongWire(e)}getLinearEdgesAlongWire(e){return this.och.edgesService.getLinearEdgesAlongWire(e)}getEdgeLength(e){return this.och.edgesService.getEdgeLength(e)}getEdgesLengths(e){return this.och.edgesService.getEdgesLengths(e)}getEdgeCenterOfMass(e){return this.och.geomService.getLinearCenterOfMass(e)}getEdgesCentersOfMass(e){return this.och.edgesService.getEdgesCentersOfMass(e)}getCornerPointsOfEdgesForShape(e){return this.och.edgesService.getCornerPointsOfEdgesForShape(e)}getCircularEdgeCenterPoint(e){return this.och.edgesService.getCircularEdgeCenterPoint(e)}getCircularEdgeRadius(e){return this.och.edgesService.getCircularEdgeRadius(e)}getCircularEdgePlaneDirection(e){return this.och.edgesService.getCircularEdgePlaneDirection(e)}constraintTanLinesFromTwoPtsToCircle(e){return this.och.edgesService.constraintTanLinesFromTwoPtsToCircle(e)}constraintTanLinesFromPtToCircle(e){return this.och.edgesService.constraintTanLinesFromPtToCircle(e)}constraintTanLinesOnTwoCircles(e){return this.och.edgesService.constraintTanLinesOnTwoCircles(e)}constraintTanCirclesOnTwoCircles(e){return this.och.edgesService.constraintTanCirclesOnTwoCircles(e)}constraintTanCirclesOnCircleAndPnt(e){return this.och.edgesService.constraintTanCirclesOnCircleAndPnt(e)}}class Y{constructor(e,t){this.occ=e,this.och=t}createFaceFromWire(e){return this.och.facesService.createFaceFromWire(e)}createFaceFromWires(e){return this.och.facesService.createFaceFromWires(e)}createFacesFromWires(e){return this.och.facesService.createFacesFromWires(e)}faceFromSurface(e){return this.och.facesService.faceFromSurface(e)}faceFromSurfaceAndWire(e){return this.och.facesService.faceFromSurfaceAndWire(e)}getUMinBound(e){return this.och.facesService.getUMinBound(e)}getUMaxBound(e){return this.och.facesService.getUMaxBound(e)}getVMinBound(e){return this.och.facesService.getVMinBound(e)}getVMaxBound(e){return this.och.facesService.getVMaxBound(e)}subdivideToPointsControlled(e){return this.och.facesService.subdivideToPointsControlled(e)}subdivideToPoints(e){return this.och.facesService.subdivideToPoints(e)}subdivideToNormals(e){return this.och.facesService.subdivideToNormals(e)}subdivideToPointsOnParam(e){return this.och.facesService.subdivideToPointsOnParam(e)}subdivideToUVOnParam(e){return this.och.facesService.subdivideToUVOnParam(e)}subdivideToUV(e){return this.och.facesService.subdivideToUV(e)}uvOnFace(e){return this.och.facesService.uvOnFace(e)}pointsOnUVs(e){return this.och.facesService.pointsOnUVs(e)}normalsOnUVs(e){return this.och.facesService.normalsOnUVs(e)}pointOnUV(e){return this.och.facesService.pointOnUV(e)}normalOnUV(e){return this.och.facesService.faceNormalOnUV(e)}createPolygonFace(e){return this.och.facesService.createPolygonFace(e)}createCircleFace(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.face)}createEllipseFace(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.face)}createSquareFace(e){return this.och.facesService.createSquareFace(e)}createRectangleFace(e){return this.och.facesService.createRectangleFace(e)}createFaceFromMultipleCircleTanWireCollections(e){return this.och.facesService.createFaceFromMultipleCircleTanWireCollections(e)}createFaceFromMultipleCircleTanWires(e){return this.och.facesService.createFaceFromMultipleCircleTanWires(e)}getFace(e){return this.och.shapeGettersService.getFace(e)}getFaces(e){return this.och.shapeGettersService.getFaces(e)}reversedFace(e){const t=e.shape.Reversed(),r=this.och.converterService.getActualTypeOfShape(t);return t.delete(),r}getFaceArea(e){return this.och.facesService.getFaceArea(e)}getFacesAreas(e){return this.och.facesService.getFacesAreas(e)}getFaceCenterOfMass(e){return this.och.facesService.getFaceCenterOfMass(e)}getFacesCentersOfMass(e){return this.och.facesService.getFacesCentersOfMass(e)}filterFacePoints(e){return this.och.facesService.filterFacePoints(e)}}class X{constructor(e,t){this.occ=e,this.och=t}makeCompound(e){return this.och.converterService.makeCompound(e)}}class Z{constructor(e,t){this.occ=e,this.och=t}vertexFromPoint(e){return this.och.entitiesService.makeVertex(e.point)}verticesFromPoints(e){return e.points.map((e=>this.vertexFromPoint({point:e})))}verticesCompoundFromPoints(e){const t=this.verticesFromPoints(e);return this.och.converterService.makeCompound({shapes:t})}getVertices(e){return this.och.shapeGettersService.getVertices(e)}getVerticesAsPoints(e){return this.och.verticesService.getVerticesAsPoints(e)}verticesToPoints(e){return this.och.verticesService.verticesToPoints(e)}vertexToPoint(e){return this.och.converterService.vertexToPoint(e)}}class J{constructor(e,t){this.occ=e,this.och=t}purgeInternalEdges(e){const t=new this.occ.TopOpeBRepTool_PurgeInternalEdges(e.shape,!0);if(t.Perform(),t.IsDone())return t.Shape();throw new Error("Could not purge internal edges for the shape")}unifySameDomain(e){const t=new this.occ.ShapeUpgrade_UnifySameDomain_2(e.shape,e.unifyEdges,e.unifyFaces,e.concatBSplines);return t.Build(),t.Shape()}isClosed(e){return e.shape.Closed_1()}isConvex(e){return e.shape.Convex_1()}isChecked(e){return e.shape.Checked_1()}isFree(e){return e.shape.Free_1()}isInfinite(e){return e.shape.Infinite_1()}isModified(e){return e.shape.Modified_1()}isLocked(e){return e.shape.Locked_1()}isNull(e){return e.shape.IsNull()}isEqual(e){return e.shape.IsEqual(e.otherShape)}isNotEqual(e){return e.shape.IsNotEqual(e.otherShape)}isPartner(e){return e.shape.IsPartner(e.otherShape)}isSame(e){return e.shape.IsSame(e.otherShape)}getOrientation(e){const t=e.shape.Orientation_1();let r;return t===this.occ.TopAbs_Orientation.TopAbs_FORWARD?r=U.topAbsOrientationEnum.forward:t===this.occ.TopAbs_Orientation.TopAbs_REVERSED?r=U.topAbsOrientationEnum.reversed:t===this.occ.TopAbs_Orientation.TopAbs_INTERNAL?r=U.topAbsOrientationEnum.internal:t===this.occ.TopAbs_Orientation.TopAbs_EXTERNAL&&(r=U.topAbsOrientationEnum.external),r}getShapeType(e){return this.och.enumService.getShapeTypeEnum(e.shape)}}class Q{constructor(e,t){this.occ=e,this.och=t}sewFaces(e){return this.och.shellsService.sewFaces(e)}isClosed(e){return this.occ.BRep_Tool.IsClosed_1(e.shape)}getShellSurfaceArea(e){return this.och.shellsService.getShellSurfaceArea(e)}}class K{constructor(e,t){this.occ=e,this.och=t}fromClosedShell(e){return this.och.solidsService.fromClosedShell(e)}createBox(e){return this.och.solidsService.createBox(e)}createCube(e){return this.och.solidsService.createCube(e)}createBoxFromCorner(e){return this.och.solidsService.createBoxFromCorner(e)}createCylinder(e){return this.och.solidsService.createCylinder(e)}createCylindersOnLines(e){return this.och.solidsService.createCylindersOnLines(e)}createSphere(e){return this.och.solidsService.createSphere(e)}createCone(e){return this.och.solidsService.createCone(e)}getSolidSurfaceArea(e){return this.och.solidsService.getSolidSurfaceArea(e)}getSolidVolume(e){return this.och.solidsService.getSolidVolume(e)}getSolidsVolumes(e){return this.och.solidsService.getSolidsVolumes(e)}getSolidCenterOfMass(e){return this.och.solidsService.getSolidCenterOfMass(e)}getSolidsCentersOfMass(e){return this.och.solidsService.getSolidsCentersOfMass(e)}getSolids(e){return this.och.solidsService.getSolids(e)}filterSolidPoints(e){return this.och.solidsService.filterSolidPoints(e)}}class ee{constructor(e,t){this.occ=e,this.och=t}createPolygonWire(e){return this.och.wiresService.createPolygonWire(e)}createPolygons(e){const t=e.polygons.map((e=>this.createPolygonWire(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createPolylineWire(e){return this.och.wiresService.createPolylineWire(e)}createPolylines(e){const t=e.polylines.map((e=>this.createPolylineWire(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createLineWire(e){return this.och.wiresService.createLineWire(e)}createLines(e){const t=e.lines.map((e=>this.createLineWire(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createBezier(e){return this.och.wiresService.createBezier(e)}createBezierWires(e){const t=e.bezierWires.map((e=>this.createBezier(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}interpolatePoints(e){return this.och.wiresService.interpolatePoints(e)}interpolateWires(e){const t=e.interpolations.map((e=>this.interpolatePoints(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}splitOnPoints(e){return this.och.wiresService.splitOnPoints(e)}combineEdgesAndWiresIntoAWire(e){return this.och.converterService.combineEdgesAndWiresIntoAWire(e)}createWireFromEdge(e){return this.och.wiresService.createWireFromEdges(e)}addEdgesAndWiresToWire(e){return this.och.wiresService.addEdgesAndWiresToWire(e)}createBSpline(e){return this.och.wiresService.createBSpline(e)}createBSplines(e){const t=e.bSplines.map((e=>this.createBSpline(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createZigZagBetweenTwoWires(e){return this.och.wiresService.createZigZagBetweenTwoWires(e)}divideWireByParamsToPoints(e){return this.och.wiresService.divideWireByParamsToPoints(e)}divideWiresByParamsToPoints(e){return e.shapes.map((t=>this.divideWireByParamsToPoints(Object.assign(Object.assign({},e),{shape:t}))))}divideWireByEqualDistanceToPoints(e){return this.och.wiresService.divideWireByEqualDistanceToPoints(e)}divideWiresByEqualDistanceToPoints(e){return e.shapes.map((t=>this.divideWireByEqualDistanceToPoints(Object.assign(Object.assign({},e),{shape:t}))))}pointOnWireAtParam(e){return this.och.wiresService.pointOnWireAtParam(e)}pointOnWireAtLength(e){return this.och.wiresService.pointOnWireAtLength(e)}tangentOnWireAtParam(e){return this.och.wiresService.tangentOnWireAtParam(e)}tangentOnWireAtLength(e){return this.och.wiresService.tangentOnWireAtLength(e)}derivativesOnWireAtLength(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1),i=new this.occ.GCPnts_AbscissaPoint_2(r,e.length,r.FirstParameter()),n=i.Parameter(),s=this.och.entitiesService.gpPnt([0,0,0]),o=this.och.entitiesService.gpVec([0,0,0]),a=this.och.entitiesService.gpVec([0,0,0]),c=this.och.entitiesService.gpVec([0,0,0]);r.D3(n,s,o,a,c);const h=[[o.X(),o.Y(),o.Z()],[a.X(),a.Y(),a.Z()],[c.X(),c.Y(),c.Z()]];return o.delete(),a.delete(),c.delete(),r.delete(),i.delete(),s.delete(),h}derivativesOnWireAtParam(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1),i=this.och.entitiesService.gpPnt([0,0,0]),n=this.och.entitiesService.gpVec([0,0,0]),s=this.och.entitiesService.gpVec([0,0,0]),o=this.och.entitiesService.gpVec([0,0,0]),a=this.och.vecHelper.remap(e.param,0,1,r.FirstParameter(),r.LastParameter());r.D3(a,i,n,s,o);const c=[[n.X(),n.Y(),n.Z()],[s.X(),s.Y(),s.Z()],[o.X(),o.Y(),o.Z()]];return n.delete(),s.delete(),o.delete(),r.delete(),i.delete(),c}startPointOnWire(e){return this.och.wiresService.startPointOnWire(e)}endPointOnWire(e){return this.och.wiresService.endPointOnWire(e)}createCircleWire(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.wire)}createEllipseWire(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.wire)}createSquareWire(e){return this.och.wiresService.createSquareWire(e)}createStarWire(e){return this.och.wiresService.createStarWire(e)}createChristmasTreeWire(e){return this.och.wiresService.createChristmasTreeWire(e)}createParallelogramWire(e){return this.och.wiresService.createParallelogramWire(e)}createHeartWire(e){return this.och.wiresService.createHeartWire(e)}createNGonWire(e){return this.och.wiresService.createNGonWire(e)}createRectangleWire(e){return this.och.wiresService.createRectangleWire(e)}createLPolygonWire(e){return this.och.wiresService.createLPolygonWire(e)}getWire(e){return this.och.shapeGettersService.getWire(e)}getWires(e){return this.och.shapeGettersService.getWires(e)}getWireLength(e){return this.och.wiresService.getWireLength(e)}getWiresLengths(e){return this.och.wiresService.getWiresLengths(e)}getWireCenterOfMass(e){return this.och.wiresService.getWireCenterOfMass(e)}getWiresCentersOfMass(e){return e.shapes.map((e=>this.och.wiresService.getWireCenterOfMass({shape:e})))}reversedWire(e){const t=e.shape.Reversed(),r=this.och.converterService.getActualTypeOfShape(t);return t.delete(),r}reversedWireFromReversedEdges(e){const t=e.shape,r=this.och.edgesService.getEdgesAlongWire({shape:t}).map((e=>this.och.converterService.getActualTypeOfShape(e.Reversed()))),i=this.och.converterService.combineEdgesAndWiresIntoAWire({shapes:r.reverse()}),n=this.och.converterService.getActualTypeOfShape(i);return i.delete(),r.forEach((e=>e.delete())),n}placeWireOnFace(e){const t=e.wire,r=e.face,i=this.och.surfaceFromFace({shape:r});return this.och.wiresService.placeWire(t,i)}placeWiresOnFace(e){const t=e.wires,r=e.face,i=this.och.surfaceFromFace({shape:r});return t.map((e=>this.och.wiresService.placeWire(e,i)))}closeOpenWire(e){const t=e.shape,r=this.och.wiresService.startPointOnWire({shape:t}),i=this.och.wiresService.endPointOnWire({shape:t});if(this.och.vecHelper.vectorsTheSame(r,i,1e-7))return t;const n=this.createLineWire({start:i,end:r}),s=this.addEdgesAndWiresToWire({shape:t,shapes:[n]});return n.delete(),s}project(e){const t=e.wire,r=this.och.entitiesService.gpDir(e.direction),i=new this.occ.BRepProj_Projection_1(t,e.shape,r),n=i.Shape();return r.delete(),i.delete(),n}wiresToPoints(e){const t=this.getWires({shape:e.shape}),r=[];return t.forEach((t=>{const i=this.och.edgesService.edgesToPoints(Object.assign(Object.assign({},e),{shape:t})).flat(),n=this.och.vecHelper.removeConsecutiveDuplicates(i,!1);r.push(n)})),r}projectWires(e){const t=[];return e.wires.forEach((r=>{const i=this.och.entitiesService.gpDir(e.direction),n=new this.occ.BRepProj_Projection_1(r,e.shape,i),s=n.Shape();t.push(s),i.delete(),n.delete()})),t}createWireFromTwoCirclesTan(e){return this.och.wiresService.createWireFromTwoCirclesTan(e)}}class te{constructor(e,t){this.vertex=new Z(e,t),this.edge=new $(e,t),this.wire=new ee(e,t),this.face=new Y(e,t),this.shell=new Q(e,t),this.solid=new K(e,t),this.compound=new X(e,t),this.shape=new J(e,t)}}class re{constructor(e){this.occ=e}BRep_Tool_Range_1(e,t,r){return this.occ.BRep_Tool.Range_1(e,t,r)}BRep_Tool_Curve_2(e,t,r){return this.occ.BRep_Tool.Curve_2(e,t,r)}BRepTools_UVBounds_1(e,t,r,i,n){return this.occ.BRepTools.UVBounds_1(e,t,r,i,n)}}class ie{constructor(e){this.occ=e}forEachWire(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_WIRE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_WIRE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Wire_2(i.Current()));i.delete()}forEachEdge(e,t){const r={};let i=0;const n=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(n.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);n.More();n.Next()){const e=this.occ.TopoDS.Edge_1(n.Current()),s=e.HashCode(1e8);Object.prototype.hasOwnProperty.call(r,s)||(r[s]=i,i++,t(i,e))}return n.delete(),r}forEachEdgeAlongWire(e,t){const r={};let i=0;const n=new this.occ.BRepTools_WireExplorer_1;for(n.Init_1(e);n.More();n.Next()){const e=this.occ.TopoDS.Edge_1(n.Current()),s=e.HashCode(1e8);Object.prototype.hasOwnProperty.call(r,s)||(r[s]=i,i++,t(i,e))}return n.delete(),r}forEachFace(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_FACE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_FACE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Face_1(i.Current()));i.delete()}forEachShell(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_SHELL,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_SHELL,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Shell_1(i.Current()));i.delete()}forEachVertex(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Vertex_1(i.Current()));i.delete()}forEachSolid(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_SOLID,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_SOLID,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Solid_2(i.Current()));i.delete()}}class ne{constructor(e){this.occ=e}getShapeTypeEnum(e){let t=U.shapeTypeEnum.unknown;const r=e.ShapeType();return t=r===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?U.shapeTypeEnum.edge:r===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE?U.shapeTypeEnum.wire:r===this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX?U.shapeTypeEnum.vertex:r===this.occ.TopAbs_ShapeEnum.TopAbs_SOLID?U.shapeTypeEnum.solid:r===this.occ.TopAbs_ShapeEnum.TopAbs_SHELL?U.shapeTypeEnum.shell:r===this.occ.TopAbs_ShapeEnum.TopAbs_FACE?U.shapeTypeEnum.face:r===this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID?U.shapeTypeEnum.compSolid:r===this.occ.TopAbs_ShapeEnum.TopAbs_COMPOUND?U.shapeTypeEnum.compound:U.shapeTypeEnum.shape,t}getGccEntPositionFromEnum(e){let t=this.occ.GccEnt_Position.GccEnt_noqualifier;return t=e===U.gccEntPositionEnum.unqualified?this.occ.GccEnt_Position.GccEnt_unqualified:e===U.gccEntPositionEnum.enclosed?this.occ.GccEnt_Position.GccEnt_enclosed:e===U.gccEntPositionEnum.enclosing?this.occ.GccEnt_Position.GccEnt_enclosing:e===U.gccEntPositionEnum.outside?this.occ.GccEnt_Position.GccEnt_outside:(U.gccEntPositionEnum.noqualifier,this.occ.GccEnt_Position.GccEnt_noqualifier),t}getTopAbsStateEnum(e){let t=U.topAbsStateEnum.unknown;return t=e===this.occ.TopAbs_State.TopAbs_IN?U.topAbsStateEnum.in:e===this.occ.TopAbs_State.TopAbs_OUT?U.topAbsStateEnum.out:e===this.occ.TopAbs_State.TopAbs_ON?U.topAbsStateEnum.on:U.topAbsStateEnum.unknown,t}convertFourSidesStrictEnumToTwoCircleInclusionEnum(e){return e===U.fourSidesStrictEnum.inside?U.twoCircleInclusionEnum.inside:e===U.fourSidesStrictEnum.outside?U.twoCircleInclusionEnum.outside:e===U.fourSidesStrictEnum.insideOutside?U.twoCircleInclusionEnum.insideOutside:e===U.fourSidesStrictEnum.outsideInside?U.twoCircleInclusionEnum.outsideInside:U.twoCircleInclusionEnum.none}}class se{constructor(e){this.occ=e}getActualTypeOfShape(e){let t=e;return t=e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?this.occ.TopoDS.Edge_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE?this.occ.TopoDS.Wire_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX?this.occ.TopoDS.Vertex_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SOLID?this.occ.TopoDS.Solid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SHELL?this.occ.TopoDS.Shell_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_FACE?this.occ.TopoDS.Face_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID?this.occ.TopoDS.CompSolid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPOUND?this.occ.TopoDS.Compound_1(e):e,t}combineEdgesAndWiresIntoAWire(e){if(void 0===e.shapes)throw Error("Shapes are not defined");const t=new this.occ.BRepBuilderAPI_MakeWire_1;if(e.shapes.forEach((e=>{e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?t.Add_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE&&t.Add_2(e)})),t.IsDone()){this.occ.BRepLib.BuildCurves3d_1(t.Wire(),1e-7,this.occ.GeomAbs_Shape.GeomAbs_C1,14,0);const e=t.Wire();return t.delete(),e}{let e;const r=t.Error();throw t.delete(),r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_DisconnectedWire?e="Wire is disconnected and can not be constructed":r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_EmptyWire?e="Wire is empty and can not be constructed":r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_NonManifoldWire?e="Wire is non manifold and can not be constructed":r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_WireDone&&(e="Wire is done"),new Error(e)}}vertexToPoint(e){const t=this.occ.BRep_Tool.Pnt(e.shape),r=[t.X(),t.Y(),t.Z()];return t.delete(),r}getGeomCurveFromEdge(e,t,r){const i=e.Location_1();return this.occ.BRep_Tool.Curve_1(e,i,t,r).get()}makeCompound(e){const t=new this.occ.TopoDS_Compound,r=new this.occ.BRep_Builder;return r.MakeCompound(t),e.shapes.forEach((e=>{const i=new this.occ.BRepBuilderAPI_Copy_2(e,!0,!1),n=i.Shape();r.Add(t,n),i.delete(),n.delete()})),r.delete(),t}makeCompoundIfNeeded(e,t){if(t){const t=this.makeCompound({shapes:e});return e.forEach((e=>e.delete())),t}return e}}class oe{constructor(e){this.occ=e}createCircle(e,t,r,i){const n=this.gcMakeCircle(t,r,e);if(i===U.typeSpecificityEnum.curve)return n;{const e=this.bRepBuilderAPIMakeEdge(n);if(i===U.typeSpecificityEnum.edge)return e;{const t=this.bRepBuilderAPIMakeWire(e);if(i===U.typeSpecificityEnum.wire)return e.delete(),t;if(i===U.typeSpecificityEnum.face)return this.bRepBuilderAPIMakeFaceFromWire(t,!0)}}return n}createEllipse(e,t,r,i,n){const s=this.gcMakeEllipse(r,i,e,t);if(n===U.typeSpecificityEnum.curve)return s;{const e=this.bRepBuilderAPIMakeEdge(s);if(n===U.typeSpecificityEnum.edge)return e;{const t=this.bRepBuilderAPIMakeWire(e);if(n===U.typeSpecificityEnum.wire)return e.delete(),t;if(n===U.typeSpecificityEnum.face)return this.bRepBuilderAPIMakeFaceFromWire(t,!0)}}return s}makeVertex(e){const t=this.gpPnt(e),r=new this.occ.BRepBuilderAPI_MakeVertex(t),i=r.Vertex();return t.delete(),r.delete(),i}gpPnt2d(e){return new this.occ.gp_Pnt2d_3(e[0],e[1])}gpPnt(e){return new this.occ.gp_Pnt_3(e[0],e[1],e[2])}gpVec(e){return new this.occ.gp_Vec_4(e[0],e[1],e[2])}gpXYZ(e){return new this.occ.gp_XYZ_2(e[0],e[1],e[2])}gpVec2d(e){return new this.occ.gp_Vec2d_4(e[0],e[1])}gpDir(e){return new this.occ.gp_Dir_4(e[0],e[1],e[2])}gpDir2d(e){return new this.occ.gp_Dir2d_4(e[0],e[1])}gcMakeCircle(e,t,r){const i=new this.occ.GC_MakeCircle_2(this.gpAx2(e,t),r),n=i.Value().get();return i.delete(),n}gcMakeEllipse(e,t,r,i){const n=this.gpAx2(e,t),s=new this.occ.GC_MakeEllipse_2(n,i,r);if(s.IsDone()){const e=s.Value().get();return s.delete(),n.delete(),e}throw new Error("Ellipse could not be created.")}bRepBuilderAPIMakeEdge(e){const t=this.castToHandleGeomCurve(e),r=new this.occ.BRepBuilderAPI_MakeEdge_24(t),i=r.Edge();return r.delete(),t.delete(),i}bRepBuilderAPIMakeWire(e){const t=new this.occ.BRepBuilderAPI_MakeWire_2(e),r=t.Wire();return t.delete(),r}bRepBuilderAPIMakeShell(e){const t=this.occ.BRep_Tool.Surface_2(e),r=new this.occ.BRepBuilderAPI_MakeShell_2(t,!1),i=r.Shell();return r.delete(),t.delete(),i}bRepBuilderAPIMakeFaceFromWires(e,t){let r;const i=[];return e.forEach((e=>{if(i.length>0){const t=new this.occ.BRepBuilderAPI_MakeFace_22(i[i.length-1],e);i.push(t.Face()),t.delete()}else{const r=new this.occ.BRepBuilderAPI_MakeFace_15(e,t);i.push(r.Face()),r.delete()}})),i.length>0&&(r=i.pop(),i.forEach((e=>e.delete()))),r}bRepBuilderAPIMakeFaceFromWire(e,t){const r=new this.occ.BRepBuilderAPI_MakeFace_15(e,t),i=r.Face();return r.delete(),i}bRepBuilderAPIMakeFaceFromSurface(e,t){const r=new this.occ.Handle_Geom_Surface_2(e),i=new this.occ.BRepBuilderAPI_MakeFace_8(r,t),n=i.Face();return i.delete(),r.delete(),n}bRepBuilderAPIMakeFaceFromSurfaceAndWire(e,t,r){const i=new this.occ.Handle_Geom_Surface_2(e),n=new this.occ.BRepBuilderAPI_MakeFace_21(i,t,r),s=n.Face();return n.delete(),i.delete(),s}bRepPrimAPIMakeSphere(e,t,r){const i=this.gpAx2(e,t),n=new this.occ.BRepPrimAPI_MakeSphere_9(i,r),s=n.Shape();return n.delete(),i.delete(),s}gpAx3(e,t){return new this.occ.gp_Ax3_4(this.gpPnt(e),this.gpDir(t))}gpAx2(e,t){return new this.occ.gp_Ax2_3(this.gpPnt(e),this.gpDir(t))}gpAx2FromTwoVectors(e,t,r){return new this.occ.gp_Ax2_2(this.gpPnt(e),this.gpDir(t),this.gpDir(r))}gpAx1(e,t){return new this.occ.gp_Ax1_2(this.gpPnt(e),this.gpDir(t))}gpAx2d(e,t){const r=this.gpPnt2d(e),i=this.gpDir2d(t);return new this.occ.gp_Ax2d_2(r,i)}gpAx22d(e,t,r){const i=this.gpPnt2d(e),n=this.gpDir2d(t),s=this.gpDir2d(r),o=new this.occ.gp_Ax22d_2(i,n,s);return n.delete(),s.delete(),i.delete(),o}gpPln(e,t){const r=this.gpPnt(e),i=this.gpDir(t),n=new this.occ.gp_Pln_3(r,i);return r.delete(),i.delete(),n}bRepPrimAPIMakeCylinder(e,t,r,i){const n=this.gpAx2(e,t),s=new this.occ.BRepPrimAPI_MakeCylinder_3(n,r,i),o=s.Shape();return s.delete(),n.delete(),o}bRepPrimAPIMakeCylinderBetweenPoints(e,t,r){const i=this.gpPnt(e),n=this.gpPnt(t),s=new this.occ.gp_Vec_5(i,n),o=s.Magnitude(),a=this.gpAx2(e,[s.X(),s.Y(),s.Z()]),c=new this.occ.BRepPrimAPI_MakeCylinder_3(a,r,o),h=c.Shape();return c.delete(),a.delete(),i.delete(),n.delete(),s.delete(),h}bRepPrimAPIMakeBox(e,t,r,i){const n=this.gpPnt([-e/2+i[0],-r/2+i[1],-t/2+i[2]]),s=new this.occ.BRepPrimAPI_MakeBox_3(n,e,r,t),o=s.Shape();return s.delete(),n.delete(),o}castToHandleGeomCurve(e){return new this.occ.Handle_Geom_Curve_2(e)}}class ae{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.occ=e,this.enumService=t,this.entitiesService=r,this.converterService=i,this.booleansService=n,this.shapeGettersService=s,this.edgesService=o,this.transformsService=a,this.vecHelper=c,this.wiresService=h,this.facesService=l,this.shellsService=u}loftAdvanced(e){if(e.periodic&&!e.closed)throw new Error("Cant construct periodic non closed loft.");const t=new this.occ.BRepOffsetAPI_ThruSections(e.makeSolid,e.straight,e.tolerance),r=[],i=[];if(e.startVertex){const r=this.entitiesService.makeVertex(e.startVertex);t.AddVertex(r),i.push(r)}if(e.closed&&!e.periodic)e.shapes.push(e.shapes[0]);else if(e.closed&&e.periodic){const i=[];e.shapes.forEach((t=>{this.enumService.getShapeTypeEnum(t)===U.shapeTypeEnum.edge&&(t=this.entitiesService.bRepBuilderAPIMakeWire(t));const r=this.wiresService.divideWireByParamsToPoints({shape:t,nrOfDivisions:e.nrPeriodicSections,removeStartPoint:!1,removeEndPoint:!1});i.push(r)}));for(let n=0;n<=e.nrPeriodicSections;n++){const s=i.map((e=>e[n])),o=this.wiresService.interpolatePoints({points:s,tolerance:e.tolerance,periodic:!0});t.AddWire(o),r.push(o)}}e.periodic||e.shapes.forEach((e=>{t.AddWire(e)}));const n=[];if(e.endVertex){const r=this.entitiesService.makeVertex(e.endVertex);t.AddVertex(r),n.push(r)}let s;e.useSmoothing&&t.SetSmoothing(e.useSmoothing),e.maxUDegree&&t.SetMaxDegree(e.maxUDegree),e.parType===U.approxParametrizationTypeEnum.approxChordLength?s=this.occ.Approx_ParametrizationType.Approx_ChordLength:e.parType===U.approxParametrizationTypeEnum.approxCentripetal?s=this.occ.Approx_ParametrizationType.Approx_Centripetal:e.parType===U.approxParametrizationTypeEnum.approxIsoParametric&&(s=this.occ.Approx_ParametrizationType.Approx_IsoParametric),s&&t.SetParType(s),t.CheckCompatibility(!1);const o=t.Shape(),a=this.converterService.getActualTypeOfShape(o);return o.delete(),t.delete(),r.forEach((e=>e.delete())),i.forEach((e=>e.delete())),n.forEach((e=>e.delete())),a}closestPointsBetweenTwoShapes(e,t){const r=new this.occ.Message_ProgressRange_1,i=new this.occ.BRepExtrema_DistShapeShape_2(e,t,this.occ.Extrema_ExtFlag.Extrema_ExtFlag_MIN,this.occ.Extrema_ExtAlgo.Extrema_ExtAlgo_Grad,r),n=new this.occ.Message_ProgressRange_1;if(i.Perform(n),i.IsDone()&&i.NbSolution()>0){const e=i.PointOnShape1(1),t=i.PointOnShape2(1);return[[e.X(),e.Y(),e.Z()],[t.X(),t.Y(),t.Z()]]}throw new Error("Closest points could not be found.")}closestPointsOnShapeFromPoints(e){return e.points.map((e=>this.entitiesService.makeVertex(e))).map((t=>this.closestPointsBetweenTwoShapes(t,e.shape))).map((e=>e[1]))}closestPointsOnShapesFromPoints(e){const t=e.points.map((e=>this.entitiesService.makeVertex(e))),r=[];return e.shapes.forEach((e=>{const i=t.map((t=>this.closestPointsBetweenTwoShapes(t,e)));r.push(...i.map((e=>e[1])))})),r}distancesToShapeFromPoints(e){return e.points.map((e=>this.entitiesService.makeVertex(e))).map((t=>this.closestPointsBetweenTwoShapes(t,e.shape))).map((e=>this.vecHelper.distanceBetweenPoints(e[0],e[1])))}loft(e){const t=new this.occ.BRepOffsetAPI_ThruSections(e.makeSolid,!1,1e-6);e.shapes.forEach((e=>{this.enumService.getShapeTypeEnum(e)===U.shapeTypeEnum.edge&&(e=this.entitiesService.bRepBuilderAPIMakeWire(e)),t.AddWire(e)})),t.CheckCompatibility(!1);const r=t.Shape(),i=this.converterService.getActualTypeOfShape(r);return r.delete(),t.delete(),i}offset(e){return this.offsetAdv({shape:e.shape,face:e.face,distance:e.distance,tolerance:e.tolerance,joinType:U.joinTypeEnum.arc,removeIntEdges:!1})}offsetAdv(e){if(e.tolerance||(e.tolerance=.1),0===e.distance)return e.shape;let t;const r=this.getJoinType(e.joinType),i=this.occ.BRepOffset_Mode.BRepOffset_Skin,n=[];if(this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.wire||this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge){let s;this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge?(s=this.entitiesService.bRepBuilderAPIMakeWire(e.shape),n.push(s)):s=e.shape;try{t=new this.occ.BRepOffsetAPI_MakeOffset_1,e.face?t.Init_1(e.face,r,!1):t.Init_2(r,!1),t.AddWire(s);const i=new this.occ.Message_ProgressRange_1;t.Build(i),t.Perform(e.distance,0)}catch(n){t=new this.occ.BRepOffsetAPI_MakeOffsetShape,t.PerformByJoin(s,e.distance,e.tolerance,i,!1,!1,r,e.removeIntEdges,new this.occ.Message_ProgressRange_1)}}else{const n=e.shape;t=new this.occ.BRepOffsetAPI_MakeOffsetShape,t.PerformByJoin(n,e.distance,e.tolerance,i,!1,!1,r,e.removeIntEdges,new this.occ.Message_ProgressRange_1)}const s=t.Shape(),o=this.converterService.getActualTypeOfShape(s);return s.delete(),t&&t.delete(),n.forEach((e=>e.delete())),o}offset3DWire(e){const t=this.extrude({shape:e.shape,direction:e.direction}),r=this.makeThickSolidSimple({shape:t,offset:e.offset}),i=this.shapeGettersService.getEdges({shape:e.shape}).length,n=(4*i+2)/2-1,s=n-i+1,o=[];let a;this.shapeGettersService.getFaces({shape:r}).forEach(((e,t)=>{if(t>=s&&t<=n){const t=this.shapeGettersService.getEdges({shape:e})[2];o.push(t)}}));try{a=this.converterService.combineEdgesAndWiresIntoAWire({shapes:o}),a=a.Reversed(),a=this.converterService.getActualTypeOfShape(a)}catch(e){return a=o,a}return a}extrudeShapes(e){return e.shapes.map((t=>{const r=this.extrude({shape:t,direction:e.direction}),i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}))}extrude(e){const t=new this.occ.gp_Vec_4(e.direction[0],e.direction[1],e.direction[2]),r=new this.occ.BRepPrimAPI_MakePrism_1(e.shape,t,!1,!0),i=r.Shape();return r.delete(),t.delete(),i}splitShapeWithShapes(e){const t=new this.occ.TopTools_ListOfShape_1;return e.shapes.forEach((e=>{t.Append_1(e)})),this.occ.BitByBitDev.BitSplit(e.shape,t)}revolve(e){let t;if(e.angle||(e.angle=360),e.direction||(e.direction=[0,0,1]),e.angle>=360){const r=new this.occ.gp_Pnt_3(0,0,0),i=new this.occ.gp_Dir_4(e.direction[0],e.direction[1],e.direction[2]),n=new this.occ.gp_Ax1_2(r,i),s=new this.occ.BRepPrimAPI_MakeRevol_2(e.shape,n,e.copy);t=s.Shape(),s.delete(),r.delete(),i.delete(),n.delete()}else{const r=new this.occ.gp_Pnt_3(0,0,0),i=new this.occ.gp_Dir_4(e.direction[0],e.direction[1],e.direction[2]),n=new this.occ.gp_Ax1_2(r,i),s=new this.occ.BRepPrimAPI_MakeRevol_1(e.shape,n,.0174533*e.angle,e.copy);t=s.Shape(),s.delete(),r.delete(),i.delete(),n.delete()}const r=this.converterService.getActualTypeOfShape(t);return t.delete(),r}rotatedExtrude(e){const t=this.transformsService.translate({translation:[0,e.height,0],shape:e.shape}),r=this.transformsService.rotate({axis:[0,1,0],angle:e.angle,shape:t}),i=this.wiresService.createBSpline({points:[[0,0,0],[0,e.height,0]],closed:!1}),n=[];for(let t=0;t<=30;t++){const r=t/30;n.push([20*Math.sin(r*e.angle*.0174533),e.height*r,20*Math.cos(r*e.angle*.0174533)])}const s=this.wiresService.createBSpline({points:n,closed:!1}),o=new this.occ.BRepOffsetAPI_MakePipeShell(i);o.SetMode_5(s,!0,this.occ.BRepFill_TypeOfContact.BRepFill_NoContact),o.Add_1(e.shape,!1,!1),o.Add_1(r,!1,!1),o.Build(new this.occ.Message_ProgressRange_1),o.MakeSolid();const a=o.Shape(),c=this.converterService.getActualTypeOfShape(a);return a.delete(),o.delete(),s.delete(),i.delete(),r.delete(),t.delete(),c}pipe(e){const t=new this.occ.BRepOffsetAPI_MakePipeShell(e.shape);e.shapes.forEach((e=>{t.Add_1(e,!1,!1)})),t.Build(new this.occ.Message_ProgressRange_1),t.MakeSolid();const r=t.Shape(),i=this.converterService.getActualTypeOfShape(r);return r.delete(),t.delete(),i}pipePolylineWireNGon(e){const t=e.shape,r=[],i=this.shapeGettersService.getEdges({shape:t});i.forEach(((t,n)=>{const s=this.edgesService.startPointOnEdge({shape:t}),o=this.edgesService.tangentOnEdgeAtParam({shape:t,param:0});let a,c=o;if(n>0&&n{n.Add_1(e,!1,!1)})),n.Build(new this.occ.Message_ProgressRange_1),n.MakeSolid();const s=n.Shape(),o=this.converterService.getActualTypeOfShape(s);return s.delete(),n.delete(),o}pipeWireCylindrical(e){const t=e.shape,r=[],i=this.shapeGettersService.getEdges({shape:t});i.forEach(((t,n)=>{const s=this.edgesService.startPointOnEdge({shape:t}),o=this.edgesService.tangentOnEdgeAtParam({shape:t,param:0});let a,c=o;if(n>0&&n{n.Add_1(e,!1,!1)})),n.Build(new this.occ.Message_ProgressRange_1),n.MakeSolid();const s=n.Shape(),o=this.converterService.getActualTypeOfShape(s);return s.delete(),n.delete(),o}pipeWiresCylindrical(e){return e.shapes.map((t=>this.pipeWireCylindrical({shape:t,radius:e.radius})))}makeThickSolidSimple(e){const t=new this.occ.BRepOffsetAPI_MakeThickSolid;t.MakeThickSolidBySimple(e.shape,e.offset),t.Build(new this.occ.Message_ProgressRange_1);const r=t.Shape(),i=this.converterService.getActualTypeOfShape(r);let n=i;if(e.offset>0){const e=this.shapeGettersService.getFaces({shape:i}).map((e=>e.Reversed()));n=this.shellsService.sewFaces({shapes:e,tolerance:1e-7}),i.delete()}return t.delete(),r.delete(),n}makeThickSolidByJoin(e){const t=new this.occ.TopTools_ListOfShape_1;e.shapes.forEach((e=>{t.Append_1(e)}));const r=new this.occ.BRepOffsetAPI_MakeThickSolid,i=this.getJoinType(e.joinType);r.MakeThickSolidByJoin(e.shape,t,e.offset,e.tolerance,this.occ.BRepOffset_Mode.BRepOffset_Skin,e.intersection,e.selfIntersection,i,e.removeIntEdges,new this.occ.Message_ProgressRange_1);const n=r.Shape(),s=this.converterService.getActualTypeOfShape(n);return n.delete(),r.delete(),t.delete(),s}getJoinType(e){let t;switch(e){case U.joinTypeEnum.arc:t=this.occ.GeomAbs_JoinType.GeomAbs_Arc;break;case U.joinTypeEnum.intersection:t=this.occ.GeomAbs_JoinType.GeomAbs_Intersection;break;case U.joinTypeEnum.tangent:t=this.occ.GeomAbs_JoinType.GeomAbs_Tangent}return t}getBRepOffsetMode(e){let t;switch(e){case U.bRepOffsetModeEnum.skin:t=this.occ.BRepOffset_Mode.BRepOffset_Skin;break;case U.bRepOffsetModeEnum.pipe:t=this.occ.BRepOffset_Mode.BRepOffset_Pipe;break;case U.bRepOffsetModeEnum.rectoVerso:t=this.occ.BRepOffset_Mode.BRepOffset_RectoVerso}return t}slice(e){if(e.step<=0)throw new Error("Step needs to be positive.");const{bbox:t,transformedShape:r}=this.createBBoxAndTransformShape(e.shape,e.direction),i=[];if(!t.IsThin(1e-4)){const{minY:n,maxY:s,maxDist:o}=this.computeBounds(t),a=[];for(let t=n;t=h?c:h;return l*=1.2,{minY:i,maxY:n,maxDist:l}}applySlices(e,t,r,i){const n=[];if(this.enumService.getShapeTypeEnum(e)===U.shapeTypeEnum.solid)n.push(e);else{const t=this.shapeGettersService.getSolids({shape:e});n.push(...t)}if(0===n.length)throw new Error("No solids found to slice.");n.forEach((e=>{const n=new U.IntersectionDto;n.keepEdges=!0,n.shapes=[e];const s=this.converterService.makeCompound({shapes:t});n.shapes.push(s),this.booleansService.intersection(n).forEach((e=>{if(e&&!e.IsNull()){const t=this.transformsService.align({shape:e,fromOrigin:[0,0,0],fromDirection:[0,1,0],toOrigin:[0,0,0],toDirection:r});i.push(t)}}))}))}}class ce{constructor(e,t,r,i){this.occ=e,this.converterService=t,this.entitiesService=r,this.vecHelper=i}alignAndTranslate(e){const t=this.align({shape:e.shape,fromOrigin:[0,0,0],fromDirection:[0,1,0],toOrigin:[0,0,0],toDirection:e.direction}),r=this.translate({shape:t,translation:e.center});return t.delete(),r}translate(e){const t=new this.occ.gp_Trsf_1,r=new this.occ.gp_Vec_4(e.translation[0],e.translation[1],e.translation[2]);t.SetTranslation_1(r);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.converterService.getActualTypeOfShape(n);return n.delete(),t.delete(),i.delete(),r.delete(),s}mirror(e){const t=new this.occ.gp_Trsf_1,r=this.entitiesService.gpAx1(e.origin,e.direction);t.SetMirror_2(r);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.converterService.getActualTypeOfShape(n);return n.delete(),i.delete(),t.delete(),r.delete(),s}mirrorAlongNormal(e){const t=new this.occ.gp_Trsf_1,r=this.entitiesService.gpAx2(e.origin,e.normal);t.SetMirror_3(r);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.converterService.getActualTypeOfShape(n);return r.delete(),n.delete(),i.delete(),t.delete(),s}rotate(e){let t;if(0!==e.angle){const t=new this.occ.gp_Trsf_1,r=new this.occ.gp_Vec_4(e.axis[0],e.axis[1],e.axis[2]),i=new this.occ.gp_Dir_4(e.axis[0],e.axis[1],e.axis[2]),n=new this.occ.gp_Pnt_3(0,0,0),s=new this.occ.gp_Ax1_2(n,i);t.SetRotation_1(s,this.vecHelper.degToRad(e.angle));const o=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),a=o.Shape(),c=this.converterService.getActualTypeOfShape(a);return a.delete(),r.delete(),i.delete(),n.delete(),s.delete(),o.delete(),t.delete(),c}t=e.shape;const r=this.converterService.getActualTypeOfShape(t);return 0!==e.angle&&t.delete(),r}align(e){const t=new this.occ.gp_Trsf_1,r=this.entitiesService.gpAx3(e.fromOrigin,e.fromDirection),i=this.entitiesService.gpAx3(e.toOrigin,e.toDirection);t.SetDisplacement(r,i);const n=new this.occ.TopLoc_Location_2(t),s=e.shape.Moved(n,!1);t.delete(),r.delete(),i.delete();const o=this.converterService.getActualTypeOfShape(s);return s.delete(),o}}class he{constructor(e,t){this.occ=e,this.shapeGettersService=t}intersection(e){if(e.shapes.length<2)throw new Error("Intersection requires 2 or more shapes to be given");const t=e.shapes[0];let r=[];for(let i=1;i0&&(r=r.map((e=>{const t=new this.occ.ShapeUpgrade_UnifySameDomain_2(e,!0,!0,!1);t.Build();const r=t.Shape();return t.delete(),r}))),r}difference(e){let t=e.shape;const r=e.shapes;for(let e=0;e{t++})),t}getSolidFromCompound(e,t){if(!e||e.ShapeType()>this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID||e.IsNull())return console.error("Not a compound shape!"),e;t||(t=0);let r=e,i=0;return this.iteratorService.forEachSolid(e,((e,n)=>{e===t&&(r=this.occ.TopoDS.Solid_1(n)),i++})),0===i&&console.error("NO SOLIDS FOUND IN SHAPE!"),r.hash=e.hash+1,r}getEdges(e){if(e.shape&&this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge)return[e.shape];if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is of incorrect type");const t=[];return this.iteratorService.forEachEdge(e.shape,((e,r)=>{t.push(r)})),t}getEdge(e){if(!e.shape||e.shape.ShapeType&&e.shape.ShapeType()>this.occ.TopAbs_ShapeEnum.TopAbs_WIRE||e.shape.IsNull())throw new Error("Edge can not be found for shape that is not provided or is of incorrect type");e.index||(e.index=0);let t={},r=!1;if(this.iteratorService.forEachEdge(e.shape,((i,n)=>{i===e.index&&(t=n,r=!0)})),r)return t;throw new Error(`Edge can not be found for shape on index ${e.index}`)}getWires(e){const t=[];return this.iteratorService.forEachWire(e.shape,((e,r)=>{t.push(r)})),t}getWire(e){if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is null");const t=this.enumService.getShapeTypeEnum(e.shape);if(t===U.shapeTypeEnum.wire||t===U.shapeTypeEnum.edge||t===U.shapeTypeEnum.vertex)throw new Error("Shape is of incorrect type");let r;if(e.index||(e.index=0),this.iteratorService.forEachWire(e.shape,((t,i)=>{t===e.index&&(r=this.occ.TopoDS.Wire_1(i))})),!r)throw Error("Wire not found");return r}getFaces(e){const t=[];return this.iteratorService.forEachFace(e.shape,((e,r)=>{t.push(r)})),t}getSolids(e){const t=[];return this.iteratorService.forEachSolid(e.shape,((e,r)=>{t.push(r)})),t}getFace(e){if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is null");const t=this.enumService.getShapeTypeEnum(e.shape);if(t===U.shapeTypeEnum.wire||t===U.shapeTypeEnum.edge||t===U.shapeTypeEnum.vertex)throw new Error("Shape is of incorrect type");e.index||(e.index=0);let r={},i=0;if(this.iteratorService.forEachFace(e.shape,((t,n)=>{t===e.index&&(r=this.occ.TopoDS.Face_1(n)),i++})),i{t.push(r)})),t}}class ue{constructor(e,t,r,i,n,s,o,a,c,h){this.occ=e,this.occRefReturns=t,this.shapeGettersService=r,this.entitiesService=i,this.iteratorService=n,this.converterService=s,this.enumService=o,this.geomService=a,this.transformsService=c,this.vecHelper=h}getCornerPointsOfEdgesForShape(e){const t=this.shapeGettersService.getEdges(e);let r=[];return t.forEach((e=>{const t={current:0},i={current:0},n=this.occRefReturns.BRep_Tool_Curve_2(e,t,i);try{const e=n.get();if(e){const n=e.Value(t.current),s=e.Value(i.current),o=[n.X(),n.Y(),n.Z()],a=[s.X(),s.Y(),s.Z()];n.delete(),s.delete(),r.push(o),r.push(a)}}catch(e){console.log(e)}})),r.length>0&&(r=this.vecHelper.removeAllDuplicateVectors(r)),r}getCircularEdgesAlongWire(e){return this.getEdgesAlongWire(e).filter((e=>this.isEdgeCircular({shape:e})))}getLinearEdgesAlongWire(e){return this.getEdgesAlongWire(e).filter((e=>this.isEdgeLinear({shape:e})))}getEdgesAlongWire(e){if(e.shape&&this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge)return[e.shape];if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is of incorrect type");const t=[],r=this.fixEdgeOrientationsAlongWire(e);return this.iteratorService.forEachEdgeAlongWire(r,((e,r)=>{t.push(r)})),t}fixEdgeOrientationsAlongWire(e){const t=[];return this.iteratorService.forEachEdgeAlongWire(e.shape,((e,r)=>{t.push(r)})),this.converterService.combineEdgesAndWiresIntoAWire({shapes:t})}arcThroughThreePoints(e){const t=this.entitiesService.gpPnt(e.start),r=this.entitiesService.gpPnt(e.middle),i=this.entitiesService.gpPnt(e.end),n=new this.occ.GC_MakeArcOfCircle_4(t,r,i),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),r.delete(),i.delete(),n.delete(),s.delete(),o.delete(),a}arcThroughTwoPointsAndTangent(e){const t=this.entitiesService.gpPnt(e.start),r=this.entitiesService.gpVec(e.tangentVec),i=this.entitiesService.gpPnt(e.end),n=new this.occ.GC_MakeArcOfCircle_5(t,r,i),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),r.delete(),i.delete(),n.delete(),s.delete(),o.delete(),a}arcFromCircleAndTwoAngles(e){const t=this.getGpCircleFromEdge({shape:e.circle}),r=this.vecHelper.degToRad(e.alphaAngle1),i=this.vecHelper.degToRad(e.alphaAngle2),n=new this.occ.GC_MakeArcOfCircle_1(t,r,i,e.sense),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),n.delete(),s.delete(),o.delete(),a}arcFromCirclePointAndAngle(e){const t=this.getGpCircleFromEdge({shape:e.circle}),r=this.vecHelper.degToRad(e.alphaAngle),i=this.entitiesService.gpPnt(e.point),n=new this.occ.GC_MakeArcOfCircle_2(t,i,r,e.sense),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),n.delete(),i.delete(),s.delete(),o.delete(),a}lineEdge(e){const t=this.entitiesService.gpPnt(e.start),r=this.entitiesService.gpPnt(e.end),i=new this.occ.GC_MakeSegment_1(t,r).Value(),n=i.get(),s=new this.occ.Handle_Geom_Curve_2(n),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return o.delete(),s.delete(),t.delete(),r.delete(),i.delete(),n.delete(),a}getEdgeLength(e){const t=e.shape,r=new this.occ.GProp_GProps_1;this.occ.BRepGProp.LinearProperties(t,r,!1,!1);const i=r.Mass();return r.delete(),i}getEdgesLengths(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getEdgeLength({shape:e})))}getEdgesCentersOfMass(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.geomService.getLinearCenterOfMass({shape:e})))}edgesToPoints(e){const t=this.enumService.getShapeTypeEnum(e.shape);let r=[];r=t===U.shapeTypeEnum.edge?[e.shape]:t===U.shapeTypeEnum.wire?this.getEdgesAlongWire({shape:e.shape}):this.shapeGettersService.getEdges({shape:e.shape});const i=[],n=r.map((e=>this.startPointOnEdge({shape:e})));return r.forEach((t=>{const r=[],n=new this.occ.TopLoc_Location_1,s=new this.occ.BRepAdaptor_Curve_2(t),o=new this.occ.GCPnts_TangentialDeflection_2(s,e.angularDeflection,e.curvatureDeflection,e.minimumOfPoints,e.uTolerance,e.minimumLength),a=o.NbPoints(),c=[];for(let e=0;ee.delete())),n.delete(),s.delete(),o.delete()})),i.forEach(((e,t)=>{const r=this.vecHelper.distanceBetweenPoints(e[0],n[t]);this.vecHelper.distanceBetweenPoints(n[t],e[e.length-1]){const r=new this.occ.GCPnts_AbscissaPoint_2(t,e,t.FirstParameter()),i=r.Parameter();return r.delete(),i})).map((e=>{const r=this.entitiesService.gpPnt([0,0,0]);t.D0(e,r);const i=[r.X(),r.Y(),r.Z()];return r.delete(),i}))}divideCurveToNrSegments(e,t,r){const i=e.shape,n=[];for(let i=0;i<=e.nrOfDivisions;i++){const s=i/e.nrOfDivisions,o=this.vecHelper.remap(s,0,1,t,r);n.push(o)}return e.removeStartPoint&&n.shift(),e.removeEndPoint&&n.pop(),n.map((e=>{const t=this.entitiesService.gpPnt([0,0,0]);i.D0(e,t);const r=[t.X(),t.Y(),t.Z()];return t.delete(),r}))}startPointOnCurve(e){const t=e.shape,r=this.entitiesService.gpPnt([0,0,0]);t.D0(t.FirstParameter(),r);const i=[r.X(),r.Y(),r.Z()];return r.delete(),i}endPointOnCurve(e){const t=e.shape,r=this.entitiesService.gpPnt([0,0,0]);t.D0(t.LastParameter(),r);const i=[r.X(),r.Y(),r.Z()];return r.delete(),i}getLinearCenterOfMass(e){const t=e.shape,r=new this.occ.GProp_GProps_1;this.occ.BRepGProp.LinearProperties(t,r,!1,!1);const i=r.CentreOfMass(),n=[i.X(),i.Y(),i.Z()];return r.delete(),n}}class pe{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.occ=e,this.occRefReturns=t,this.vecHelper=r,this.shapesHelperService=i,this.shapeGettersService=n,this.transformsService=s,this.enumService=o,this.entitiesService=a,this.converterService=c,this.geomService=h,this.edgesService=l,this.booleansService=u}getWireLength(e){return this.shapeGettersService.getEdges(e).map((e=>this.edgesService.getEdgeLength({shape:e}))).reduce(((e,t)=>e+t),0)}getWiresLengths(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getWireLength({shape:e})))}createRectangleWire(e){const t=e.width/2,r=e.length/2,i=[[t,0,r],[-t,0,r],[-t,0,-r],[t,0,-r]].reverse(),n=this.createPolygonWire({points:i}),s=this.transformsService.alignAndTranslate({shape:n,direction:e.direction,center:e.center});return n.delete(),s}createSquareWire(e){return this.createRectangleWire({width:e.size,length:e.size,center:e.center,direction:e.direction})}createChristmasTreeWire(e){const t=this.createLineWire({start:[e.innerDist,0,0],end:[0,e.height,0]}),r=this.createLineWire({start:[e.outerDist,0,0],end:[0,e.height,0]}),i=this.divideWireByEqualDistanceToPoints({shape:t,nrOfDivisions:e.nrSkirts,removeEndPoint:!1,removeStartPoint:!1}),n=this.divideWireByEqualDistanceToPoints({shape:r,nrOfDivisions:e.nrSkirts,removeEndPoint:!1,removeStartPoint:!1}),s=[];if(e.trunkWidth>0&&e.trunkHeight>0?(s.push([0,-e.trunkHeight,0]),s.push([e.trunkWidth/2,-e.trunkHeight,0]),s.push([e.trunkWidth/2,0,0])):s.push([0,0,0]),i.forEach(((t,r)=>{const i=n[r];0===r?s.push(i):0!==r&&r[-e[0],e[1],e[2]]));e.pop(),s.push(...e.reverse())}let o;if(e.trunkHeight>0&&e.trunkWidth>0){const t=s.map((t=>[t[0],t[1]+e.trunkHeight,t[2]]));o=this.createPolylineWire({points:t})}else o=this.createPolylineWire({points:s});const a=this.transformsService.rotate({shape:o,angle:e.rotation,axis:[0,1,0]});return this.transformsService.alignAndTranslate({shape:a,direction:e.direction,center:e.origin})}createStarWire(e){const t=this.shapesHelperService.starLines(e.innerRadius,e.outerRadius,e.numRays,e.half,e.offsetOuterEdges),r=[];t.forEach((e=>{r.push(this.edgesService.lineEdge(e))}));const i=this.converterService.combineEdgesAndWiresIntoAWire({shapes:r}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return i.delete(),n}createParallelogramWire(e){const t=this.shapesHelperService.parallelogram(e.width,e.height,e.angle,e.aroundCenter),r=[];t.forEach((e=>{r.push(this.edgesService.lineEdge(e))}));const i=this.converterService.combineEdgesAndWiresIntoAWire({shapes:r}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return i.delete(),n}createHeartWire(e){const t=e.sizeApprox/2,r=[[0,0,.7*t],[t/6,0,.9*t],[t/2,0,t],[.75*t,0,.9*t],[t,0,t/4],[t/2,0,-t/2],[0,0,-t]],i=r.map((e=>[-e[0],e[1],e[2]])),n=1e-5,s=this.interpolatePoints({points:r,periodic:!1,tolerance:n}),o=this.interpolatePoints({points:i.reverse(),periodic:!1,tolerance:n}),a=this.converterService.combineEdgesAndWiresIntoAWire({shapes:[s,o]}),c=this.transformsService.rotate({shape:a,angle:e.rotation,axis:[0,1,0]}),h=this.transformsService.alignAndTranslate({shape:c,direction:e.direction,center:e.center});return a.delete(),c.delete(),s.delete(),o.delete(),h}createNGonWire(e){const t=this.shapesHelperService.ngon(e.nrCorners,e.radius,[0,0]),r=[];t.forEach((e=>{r.push(this.edgesService.lineEdge(e))}));const i=this.converterService.combineEdgesAndWiresIntoAWire({shapes:r}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return i.delete(),n}createLPolygonWire(e){let t;switch(e.align){case U.directionEnum.outside:t=this.shapesHelperService.polygonL(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond);break;case U.directionEnum.inside:t=this.shapesHelperService.polygonLInverted(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond);break;case U.directionEnum.middle:t=this.shapesHelperService.polygonLMiddle(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond);break;default:t=this.shapesHelperService.polygonL(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond)}const r=this.createPolygonWire({points:t}),i=this.transformsService.rotate({shape:r,angle:e.rotation,axis:[0,1,0]}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return r.delete(),i.delete(),n}createPolygonWire(e){const t=[];for(let r=0;re.delete())),void t.delete();{const e=i.get(),n=new this.occ.Handle_Geom_Curve_2(e),s=new this.occ.BRepBuilderAPI_MakeEdge_24(n),o=s.Edge(),a=new this.occ.BRepBuilderAPI_MakeWire_2(o),c=a.Wire();return i.Nullify(),i.delete(),n.Nullify(),n.delete(),s.delete(),o.delete(),a.delete(),r.forEach((e=>e.delete())),t.delete(),c}}splitOnPoints(e){const t=1e-7,r=this.startPointOnWire({shape:e.shape}),i=this.endPointOnWire({shape:e.shape}),n=this.vecHelper.vectorsTheSame(i,r,t);n||(e.points.some((e=>this.vecHelper.vectorsTheSame(e,r,t)))||e.points.push(r),e.points.some((e=>this.vecHelper.vectorsTheSame(e,i,t)))||e.points.push(i));const s=this.createLines({lines:e.points.map((e=>({start:e,end:[e[0],e[1]+t,e[2]]}))),returnCompound:!1}),o=this.booleansService.difference({shape:e.shape,shapes:s,keepEdges:!0}),a=this.shapeGettersService.getEdges({shape:o}),c=[];a.forEach((r=>{const i=c[c.length-1],n=this.edgesService.endPointOnEdge({shape:r}),s=this.edgesService.startPointOnEdge({shape:r}),o=e.points.some((e=>this.vecHelper.vectorsTheSame(n,e,t))),a=e.points.some((e=>this.vecHelper.vectorsTheSame(s,e,t)));o&&!a?c.push([r]):!o&&a?i?i.push(r):c.push([r]):o&&a?c.push([r]):o||a||(i?i.push(r):c.push([r]))}));const h=[];if(c.forEach((e=>{const t=this.converterService.combineEdgesAndWiresIntoAWire({shapes:e});h.push(t)})),n&&h.length>1){const r=this.endPointOnWire({shape:h[0]}),i=this.startPointOnWire({shape:h[h.length-1]});if(this.vecHelper.vectorsTheSame(r,i,t)&&!e.points.find((e=>this.vecHelper.vectorsTheSame(e,r,t)))){const e=this.addEdgesAndWiresToWire({shape:h[h.length-1],shapes:[h[0]]});h[0]=e,h.pop()}}return h}createLines(e){const t=e.lines.map((e=>this.createLineWire(e))).filter((e=>void 0!==e));return this.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createWireFromTwoCirclesTan(e){const t=this.shapeGettersService.getEdges({shape:e.circle1}),r=this.shapeGettersService.getEdges({shape:e.circle2});if(1===t.length&&1===r.length){const i=t[0],n=r[0],s=this.edgesService.constraintTanLinesOnTwoCircles({circle1:i,circle2:n,positionResult:e.keepLines===U.twoSidesStrictEnum.outside?U.positionResultEnum.keepSide2:U.positionResultEnum.keepSide1,circleRemainders:this.enumService.convertFourSidesStrictEnumToTwoCircleInclusionEnum(e.circleRemainders),tolerance:e.tolerance}),o=this.converterService.combineEdgesAndWiresIntoAWire({shapes:s});return s.forEach((e=>e.delete())),i.delete(),n.delete(),o}throw new Error("Could not find the edges of the provided circle wires.")}createZigZagBetweenTwoWires(e){const t=e.wire1,r=e.wire2;let i=[],n=[];if(e.zigZagsPerEdge){const s=this.edgesService.getEdgesAlongWire({shape:t}),o=this.edgesService.getEdgesAlongWire({shape:r});e.divideByEqualDistance?(i=s.map((t=>this.edgesService.divideEdgeByEqualDistanceToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1}))),n=o.map((t=>this.edgesService.divideEdgeByEqualDistanceToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1})))):(i=s.map((t=>this.edgesService.divideEdgeByParamsToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1}))),n=o.map((t=>this.edgesService.divideEdgeByParamsToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1}))))}else e.divideByEqualDistance?(i=[this.divideWireByEqualDistanceToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1})],n=[this.divideWireByEqualDistanceToPoints({shape:r,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1})]):(i=[this.divideWireByParamsToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1})],n=[this.divideWireByParamsToPoints({shape:r,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1})]);const s=i.map(((t,r)=>{const i=n[r],s=[];for(let r=0;re.delete())),t.delete(),i.delete(),n.Nullify(),n.delete(),o.Nullify(),o.delete(),a.delete(),c.delete(),h.delete(),l}createBezier(e){const t=new this.occ.TColgp_Array1OfPnt_2(1,e.points.length+(e.closed?1:0));for(let r=1;r<=e.points.length;r++)t.SetValue(r,this.entitiesService.gpPnt(e.points[r-1]));e.closed&&t.SetValue(e.points.length+1,t.Value(1));const r=new this.occ.Geom_BezierCurve_1(t),i=new this.occ.Handle_Geom_Curve_2(r),n=new this.occ.BRepBuilderAPI_MakeEdge_24(i),s=n.Edge(),o=new this.occ.BRepBuilderAPI_MakeWire_2(s),a=o.Wire();return o.delete(),n.delete(),s.delete(),i.delete(),t.delete(),a}addEdgesAndWiresToWire(e){const t=new this.occ.BRepBuilderAPI_MakeWire_1;let r;if(t.Add_2(e.shape),e.shapes.forEach((e=>{e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?t.Add_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE&&t.Add_2(e)})),!t.IsDone())throw new Error("Wire could not be constructed. Check if edges and wires do not have disconnected elements.");return r=t.Wire(),t.delete(),r}startPointOnWire(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1);return this.geomService.startPointOnCurve(Object.assign(Object.assign({},e),{shape:r}))}endPointOnWire(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1);return this.geomService.endPointOnCurve(Object.assign(Object.assign({},e),{shape:r}))}placeWire(e,t){const r=this.shapeGettersService.getEdges({shape:e}),i=[];r.forEach((e=>{const r={current:0},n={current:0};this.occRefReturns.BRep_Tool_Range_1(e,r,n);const s=this.occRefReturns.BRep_Tool_Curve_2(e,r,n);if(!s.IsNull()){const e=this.entitiesService.gpPln([0,0,0],[0,1,0]),o=this.occ.GeomAPI.To2d(s,e),a=o.get(),c=this.edgesService.makeEdgeFromGeom2dCurveAndSurfaceBounded({curve:a,surface:t},r.current,n.current);c&&i.push(c),e.delete(),o.delete()}s.delete()})),r.forEach((e=>e.delete()));const n=this.converterService.combineEdgesAndWiresIntoAWire({shapes:i});return i.forEach((e=>e.delete())),n}}class fe{constructor(e,t,r,i,n,s,o,a){this.occ=e,this.occRefReturns=t,this.entitiesService=r,this.enumService=i,this.shapeGettersService=n,this.converterService=s,this.booleansService=o,this.wiresService=a}createFaceFromWire(e){let t;if(this.enumService.getShapeTypeEnum(e.shape)!==U.shapeTypeEnum.wire)throw new Error("Provided input shape is not a wire");if(e.planar){const r=this.occ.TopoDS.Wire_1(e.shape);t=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(r,e.planar),r.delete()}else{const r=3,i=15,n=2,s=!1,o=1e-5,a=1e-4,c=.01,h=.1,l=8,u=9,d=new this.occ.BRepFill_Filling(r,i,n,s,o,a,c,h,l,u),p=this.shapeGettersService.getEdges(e);if(p.forEach((e=>{d.Add_1(e,this.occ.GeomAbs_Shape.GeomAbs_C0,!0)})),d.Build(),!d.IsDone())throw new Error("Could not create non planar face");t=d.Face(),d.delete(),p.forEach((e=>e.delete()))}return t}getFaceArea(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.SurfaceProperties_1(e.shape,t,!1,!1);const r=t.Mass();return t.delete(),r}getFacesAreas(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getFaceArea({shape:e})))}getFaceCenterOfMass(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.SurfaceProperties_1(e.shape,t,!1,!1);const r=t.CentreOfMass(),i=[r.X(),r.Y(),r.Z()];return t.delete(),r.delete(),i}getFacesCentersOfMass(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getFaceCenterOfMass({shape:e})))}filterFacePoints(e){const t=[];if(e.points.length>0){const r=new this.occ.BRepClass_FaceClassifier_1;return e.points.forEach((i=>{const n=this.entitiesService.gpPnt(i);r.Perform_2(e.shape,n,e.tolerance,e.useBndBox,e.gapTolerance);const s=r.State(),o=this.enumService.getTopAbsStateEnum(s);e.keepOn&&o===U.topAbsStateEnum.on&&t.push(i),e.keepIn&&o===U.topAbsStateEnum.in&&t.push(i),e.keepOut&&o===U.topAbsStateEnum.out&&t.push(i),e.keepUnknown&&o===U.topAbsStateEnum.unknown&&t.push(i),n.delete()})),r.delete(),t}return[]}createSquareFace(e){const t=this.wiresService.createSquareWire(e),r=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(t,!0);return t.delete(),r}createRectangleFace(e){const t=this.wiresService.createRectangleWire(e),r=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(t,!0);return t.delete(),r}createFaceFromMultipleCircleTanWires(e){const t=e.circles,r=[];if(e.combination===U.combinationCirclesForFaceEnum.allWithAll)for(let i=0;ithis.createFaceFromWire({shape:t,planar:e.planar})))}faceFromSurface(e){const t=this.entitiesService.bRepBuilderAPIMakeFaceFromSurface(e.shape,e.tolerance);if(t.IsNull())throw t.delete(),new Error("Could not construct a face from the surface. Check if surface is not infinite.");return t}faceFromSurfaceAndWire(e){const t=this.entitiesService.bRepBuilderAPIMakeFaceFromSurfaceAndWire(e.surface,e.wire,e.inside);if(t.IsNull())throw t.delete(),new Error("Could not construct a face from the surface. Check if surface is not infinite.");return t}getUMinBound(e){const t=e.shape,{uMin:r}=this.getUVBounds(t);return r}getUMaxBound(e){const t=e.shape,{uMax:r}=this.getUVBounds(t);return r}getVMinBound(e){const t=e.shape,{vMin:r}=this.getUVBounds(t);return r}getVMaxBound(e){const t=e.shape,{vMax:r}=this.getUVBounds(t);return r}subdivideToPointsControlled(e){if(void 0===e.shape)throw Error("Face not defined");const t=e.shape,r=this.occ.BRep_Tool.Surface_2(t),i=r.get(),{uMin:n,uMax:s,vMin:o,vMax:a}=this.getUVBounds(t),c=[];for(let t=0;t{const t=i+(n-i)*e[0],a=s+(o-s)*e[1],c=this.entitiesService.gpPnt([0,0,0]);r.D0(t,a,c);const h=[c.X(),c.Y(),c.Z()];return c.delete(),h}))}normalsOnUVs(e){if(void 0===e.shape)throw Error("Face not defined");const t=e.shape,r=this.occ.BRep_Tool.Surface_2(t),{uMin:i,uMax:n,vMin:s,vMax:o}=this.getUVBounds(t),a=e.paramsUV.map((e=>{const t=i+(n-i)*e[0],a=s+(o-s)*e[1],c=this.entitiesService.gpDir([0,1,0]);this.occ.GeomLib.NormEstim(r,this.entitiesService.gpPnt2d([t,a]),1e-7,c);const h=[c.X(),c.Y(),c.Z()];return c.delete(),h}));return r.delete(),a}pointOnUV(e){if(void 0===e.shape)throw Error("Face not defined");const t=e.shape,r=this.occ.BRep_Tool.Surface_2(t),i=r.get(),{uMin:n,uMax:s,vMin:o,vMax:a}=this.getUVBounds(t),c=n+(s-n)*e.paramU,h=o+(a-o)*e.paramV,l=this.entitiesService.gpPnt([0,0,0]);i.D0(c,h,l);const u=[l.X(),l.Y(),l.Z()];return l.delete(),r.delete(),u}normalOnUV(e){return this.faceNormalOnUV(e)}createPolygonFace(e){const t=this.wiresService.createPolygonWire(e),r=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(t,!1);return t.delete(),r}}class ge{constructor(e,t){this.occ=e,this.shapeGettersService=t}getVerticesAsPoints(e){const t=this.shapeGettersService.getVertices(e);return this.verticesToPoints({shapes:t})}verticesToPoints(e){return e.shapes.map((e=>{const t=this.occ.BRep_Tool.Pnt(e),r=[t.X(),t.Y(),t.Z()];return t.delete(),r}))}}class ve{constructor(e,t,r,i){this.occ=e,this.shapeGettersService=t,this.converterService=r,this.facesService=i}getShellSurfaceArea(e){const t=this.shapeGettersService.getFaces(e);return this.facesService.getFacesAreas({shapes:t}).reduce(((e,t)=>e+t),0)}sewFaces(e){const t=new this.occ.BRepBuilderAPI_Sewing(e.tolerance,!0,!0,!0,!1);e.shapes.forEach((e=>{t.Add(e)}));const r=new this.occ.Message_ProgressRange_1;t.Perform(r);const i=t.SewedShape(),n=this.converterService.getActualTypeOfShape(i);return t.delete(),r.delete(),i.delete(),n}}class me{constructor(e,t,r,i,n,s,o,a,c){this.occ=e,this.vecHelper=t,this.iteratorService=r,this.converterService=i,this.entitiesService=n,this.transformsService=s,this.shapeGettersService=o,this.edgesService=a,this.operationsService=c}filletEdges(e){if(!e.indexes||e.indexes.length&&0===e.indexes.length){if(void 0===e.radius)throw Error("Radius not defined");const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational),r=new this.occ.TopExp_Explorer_2(e.shape,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE),i=[];for(;r.More();){const n=this.occ.TopoDS.Edge_1(r.Current());i.push(n),t.Add_2(e.radius,n),r.Next()}const n=t.Shape();return t.delete(),r.delete(),i.forEach((e=>e.delete())),n}if(e.indexes&&e.indexes.length>0){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);let r,i=0,n=0;const s=e.indexes;if(this.iteratorService.forEachEdge(e.shape,((r,o)=>{if(s.includes(r)){let r=e.radius;if(e.radiusList&&(r=e.radiusList[n],n++),void 0===r)throw Error("Radius not defined, or radiusList not correct length");t.Add_2(r,o),i++}})),0===i)throw new Error("Fillet Edges Not Found! Make sure you are looking at the object _before_ the Fillet is applied!");r=t.Shape(),t.delete();const o=this.converterService.getActualTypeOfShape(r);return r.delete(),o}}filletEdgesListOneRadius(e){if(e.edges&&e.edges.length>0){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach((r=>{t.Add_2(e.radius,r)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgesList(e){if(e.edges&&e.edges.length>0&&e.radiusList&&e.radiusList.length>0&&e.edges.length===e.radiusList.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach(((r,i)=>{t.Add_2(e.radiusList[i],r)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgeVariableRadius(e){if(e.paramsU&&e.paramsU.length>0&&e.radiusList&&e.radiusList.length>0&&e.paramsU.length===e.radiusList.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);this.assignVariableFilletToEdge(e,t);const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgesSameVariableRadius(e){if(e.edges&&e.edges.length>0&&e.radiusList&&e.radiusList.length>0&&e.paramsU.length===e.radiusList.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach((r=>{this.assignVariableFilletToEdge({edge:r,paramsU:e.paramsU,radiusList:e.radiusList,shape:e.shape},t)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgesVariableRadius(e){if(e.edges&&e.edges.length>0&&e.radiusLists&&e.radiusLists.length>0&&e.paramsULists.length===e.radiusLists.length&&e.paramsULists.length===e.edges.length&&e.radiusLists.length===e.edges.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach(((r,i)=>{this.assignVariableFilletToEdge({edge:r,paramsU:e.paramsULists[i],radiusList:e.radiusLists[i],shape:e.shape},t)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}assignVariableFilletToEdge(e,t){const r=new this.occ.TColgp_Array1OfPnt2d_2(1,e.paramsU.length);e.paramsU.forEach(((t,i)=>{r.SetValue(i+1,this.entitiesService.gpPnt2d([t,e.radiusList[i]]))})),t.Add_5(r,e.edge)}chamferEdges(e){if(!e.indexes||e.indexes.length&&0===e.indexes.length){if(void 0===e.distance)throw Error("Distance is undefined");const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape),r=new this.occ.TopExp_Explorer_2(e.shape,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE),i=[];for(;r.More();){const n=this.occ.TopoDS.Edge_1(r.Current());i.push(n),t.Add_2(e.distance,n),r.Next()}const n=t.Shape();return t.delete(),r.delete(),i.forEach((e=>e.delete())),n}if(e.indexes&&e.indexes.length>0){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);let r,i=0,n=0;const s=e.indexes;this.iteratorService.forEachEdge(e.shape,((r,o)=>{if(s.includes(r)){let r=e.distance;if(e.distanceList&&(r=e.distanceList[n],n++),void 0===r)throw Error("Distance not defined and/or distance list incorrect length");t.Add_2(r,o),i++}})),0===i?(console.error("Chamfer Edges Not Found! Make sure you are looking at the object _before_ the Fillet is applied!"),r=e.shape):r=t.Shape(),t.delete();const o=this.converterService.getActualTypeOfShape(r);return r.delete(),o}}chamferEdgesList(e){if(e.edges&&e.edges.length>0&&e.distanceList&&e.distanceList.length>0&&e.edges.length===e.distanceList.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{const n=e.distanceList[i];if(void 0===n)throw Error("Distance is not defined");t.Add_2(n,r)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgeTwoDistances(e){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);t.Add_3(e.distance1,e.distance2,e.edge,e.face);const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}chamferEdgesTwoDistances(e){if(e.edges&&e.edges.length>0&&e.edges.length===e.faces.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{t.Add_3(e.distance1,e.distance2,r,e.faces[i])}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgesTwoDistancesLists(e){if(e.edges&&e.edges.length>0&&e.faces&&e.faces.length>0&&e.distances1&&e.distances1.length>0&&e.distances2&&e.distances2.length>0&&e.edges.length===e.faces.length&&e.edges.length===e.distances1.length&&e.edges.length===e.distances2.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{t.Add_3(e.distances1[i],e.distances2[i],r,e.faces[i])}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgeDistAngle(e){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape),r=this.vecHelper.degToRad(e.angle);t.AddDA(e.distance,r,e.edge,e.face);const i=t.Shape();t.delete();const n=this.converterService.getActualTypeOfShape(i);return i.delete(),n}chamferEdgesDistsAngles(e){if(e.edges&&e.edges.length>0&&e.faces&&e.faces.length>0&&e.distances&&e.distances.length>0&&e.angles&&e.angles.length>0&&e.edges.length===e.distances.length&&e.edges.length===e.faces.length&&e.edges.length===e.angles.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{const n=this.vecHelper.degToRad(e.angles[i]);t.AddDA(e.distances[i],n,r,e.faces[i])}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgesDistAngle(e){if(e.edges&&e.edges.length>0&&e.faces&&e.faces.length>0&&e.edges.length===e.faces.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape),r=this.vecHelper.degToRad(e.angle);e.edges.forEach(((i,n)=>{t.AddDA(e.distance,r,i,e.faces[n])}));const i=t.Shape();t.delete();const n=this.converterService.getActualTypeOfShape(i);return i.delete(),n}}fillet3DWire(e){let t=!1;if(e.radiusList&&e.radiusList.length>0&&e.indexes&&e.indexes.length>0){if(e.radiusList.length!==e.indexes.length)throw new Error("Radius list and indexes are not the same length");t=!0}let r=this.edgesService.fixEdgeOrientationsAlongWire({shape:e.shape});if(t&&e.shape.Closed_1()){const t=this.edgesService.getEdgesAlongWire({shape:e.shape}),i=t.shift(),n=[...t,i];r=this.converterService.combineEdgesAndWiresIntoAWire({shapes:n})}else r=this.converterService.getActualTypeOfShape(e.shape.Reversed());const i=this.operationsService.extrude({shape:r,direction:e.direction});let n=e.indexes;if(t){const t=e.indexes.filter((e=>e>2)),r=Math.max(...t),i=[5];let s=5;for(let e=0;ee.shape.Closed_1()?t<=2?t:i[t-3]:1===t?2:i[t-2]))}const s=this.filletEdges({shape:i,radius:e.radius,indexes:n,radiusList:e.radiusList}),o=[],a=this.shapeGettersService.getFaces({shape:s});a.forEach(((e,t)=>{const r=this.shapeGettersService.getEdges({shape:e})[3];o.push(r)}));const c=this.converterService.combineEdgesAndWiresIntoAWire({shapes:o}),h=this.transformsService.translate({shape:c,translation:e.direction.map((e=>-e))});return i.delete(),s.delete(),a.forEach((e=>e.delete())),o.forEach((e=>e.delete())),h}}class ye{constructor(e,t,r,i,n,s,o){this.occ=e,this.shapeGettersService=t,this.facesService=r,this.enumService=i,this.entitiesService=n,this.converterService=s,this.transformsService=o}fromClosedShell(e){const t=this.converterService.getActualTypeOfShape(e.shape),r=new this.occ.BRepBuilderAPI_MakeSolid_3(t),i=r.Solid();return r.delete(),t.delete(),i}createBox(e){return this.entitiesService.bRepPrimAPIMakeBox(e.width,e.length,e.height,e.center)}createCube(e){return this.entitiesService.bRepPrimAPIMakeBox(e.size,e.size,e.size,e.center)}createBoxFromCorner(e){const t=this.entitiesService.bRepPrimAPIMakeBox(e.width,e.length,e.height,e.corner),r=this.transformsService.translate({shape:t,translation:[e.width/2,e.height/2,e.length/2]});return t.delete(),r}createCylinder(e){return this.entitiesService.bRepPrimAPIMakeCylinder(e.center,e.direction?e.direction:[0,1,0],e.radius,e.height)}createCylindersOnLines(e){return e.lines.map((t=>this.entitiesService.bRepPrimAPIMakeCylinderBetweenPoints(t.start,t.end,e.radius)))}createSphere(e){return this.entitiesService.bRepPrimAPIMakeSphere(e.center,[0,0,1],e.radius)}createCone(e){const t=this.entitiesService.gpAx2(e.center,e.direction),r=new this.occ.BRepPrimAPI_MakeCone_4(t,e.radius1,e.radius2,e.height,e.angle),i=r.Shape();return r.delete(),t.delete(),i}filterSolidPoints(e){const t=[];if(e.points.length>0){const r=new this.occ.BRepClass3d_SolidClassifier_1;return r.Load(e.shape),e.points.forEach((i=>{const n=this.entitiesService.gpPnt(i);r.Perform(n,e.tolerance);const s=r.State(),o=this.enumService.getTopAbsStateEnum(s);e.keepOn&&o===U.topAbsStateEnum.on&&t.push(i),e.keepIn&&o===U.topAbsStateEnum.in&&t.push(i),e.keepOut&&o===U.topAbsStateEnum.out&&t.push(i),e.keepUnknown&&o===U.topAbsStateEnum.unknown&&t.push(i),n.delete()})),r.delete(),t}return[]}getSolidVolume(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.VolumeProperties_1(e.shape,t,!0,!1,!1);const r=t.Mass();return t.delete(),r}getSolidSurfaceArea(e){const t=this.shapeGettersService.getFaces(e);return this.facesService.getFacesAreas({shapes:t}).reduce(((e,t)=>e+t),0)}getSolidsVolumes(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getSolidVolume({shape:e})))}getSolidCenterOfMass(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.VolumeProperties_1(e.shape,t,!0,!1,!1);const r=t.CentreOfMass(),i=[r.X(),r.Y(),r.Z()];return t.delete(),r.delete(),i}getSolidsCentersOfMass(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getSolidCenterOfMass({shape:e})))}getSolids(e){return this.shapeGettersService.getSolids(e)}}class Se{constructor(e,t,r){this.vecHelper=e,this.shapesHelperService=t,this.occ=r,this.occRefReturns=new re(r),this.iteratorService=new ie(r),this.enumService=new ne(r),this.converterService=new se(r),this.entitiesService=new oe(r),this.shapeGettersService=new le(r,this.enumService,this.iteratorService),this.geomService=new de(r,this.vecHelper,this.entitiesService),this.booleansService=new he(r,this.shapeGettersService),this.transformsService=new ce(r,this.converterService,this.entitiesService,this.vecHelper),this.verticesService=new ge(r,this.shapeGettersService),this.edgesService=new ue(r,this.occRefReturns,this.shapeGettersService,this.entitiesService,this.iteratorService,this.converterService,this.enumService,this.geomService,this.transformsService,this.vecHelper),this.wiresService=new pe(r,this.occRefReturns,this.vecHelper,this.shapesHelperService,this.shapeGettersService,this.transformsService,this.enumService,this.entitiesService,this.converterService,this.geomService,this.edgesService,this.booleansService),this.facesService=new fe(r,this.occRefReturns,this.entitiesService,this.enumService,this.shapeGettersService,this.converterService,this.booleansService,this.wiresService),this.shellsService=new ve(r,this.shapeGettersService,this.converterService,this.facesService),this.solidsService=new ye(r,this.shapeGettersService,this.facesService,this.enumService,this.entitiesService,this.converterService,this.transformsService),this.operationsService=new ae(r,this.enumService,this.entitiesService,this.converterService,this.booleansService,this.shapeGettersService,this.edgesService,this.transformsService,this.vecHelper,this.wiresService,this.facesService,this.shellsService),this.filletsService=new me(r,this.vecHelper,this.iteratorService,this.converterService,this.entitiesService,this.transformsService,this.shapeGettersService,this.edgesService,this.operationsService)}surfaceFromFace(e){const t=e.shape;return this.occ.BRep_Tool.Surface_2(t).get()}}class be{constructor(e,t){this.occ=e,this.och=t}union(e){return this.och.booleansService.union(e)}difference(e){return this.och.booleansService.difference(e)}intersection(e){const t=this.och.booleansService.intersection(e);return this.och.converterService.makeCompound({shapes:t})}}class we{constructor(e,t){this.occ=e,this.och=t}saveShapeSTEP(e){const t=e.shape;let r;if(e.adjustYtoZ){const t=this.och.transformsService.rotate({shape:e.shape,axis:[1,0,0],angle:-90});r=this.och.transformsService.mirrorAlongNormal({shape:t,origin:[0,0,0],normal:[0,0,1]}),t.delete()}const i=new this.occ.STEPControl_Writer_1;let n;n=r||t;const s=new this.occ.Message_ProgressRange_1;let o,a;try{o=i.Transfer(n,this.occ.STEPControl_StepModelType.STEPControl_AsIs,!0,s)}catch(e){throw new Error("Failed when calling writer.Transfer.")}if(o!==this.occ.IFSelect_ReturnStatus.IFSelect_RetDone)throw new Error("Failed when transfering to step writer.");if(i.Write("x")!==this.occ.IFSelect_ReturnStatus.IFSelect_RetDone)throw new Error("Failed when writing step file.");{const e=this.occ.FS.readFile("/x",{encoding:"utf8"});this.occ.FS.unlink("/x"),a=e}return r&&r.delete(),s.delete(),a}loadSTEPorIGES(e){const t=e.fileName,r=e.filetext,i=(()=>{switch(t.toLowerCase().split(".").pop()){case"step":case"stp":return"step";case"iges":case"igs":return"iges";default:return}})();let n;if(this.occ.FS.createDataFile("/",`file.${i}`,r,!0,!0,!0),"step"===i)n=new this.occ.STEPControl_Reader_1;else{if("iges"!==i)return void console.error("opencascade can't parse this extension! (yet)");n=new this.occ.IGESControl_Reader_1}if(n.ReadFile(`file.${i}`)===this.occ.IFSelect_ReturnStatus.IFSelect_RetDone){const t=new this.occ.Message_ProgressRange_1;n.TransferRoots(t),t.delete();let r,s=n.OneShape();if(e.adjustZtoY){const e=this.och.transformsService.mirrorAlongNormal({shape:s,origin:[0,0,0],normal:[0,0,1]});r=this.och.transformsService.rotate({shape:e,axis:[1,0,0],angle:90}),e.delete()}return this.occ.FS.unlink(`/file.${i}`),r&&(s.delete(),s=r),s}console.error("Something in OCCT went wrong trying to read "+t)}}class Ee{constructor(e,t){this.occ=e,this.och=t}closestPointsBetweenTwoShapes(e){return this.och.operationsService.closestPointsBetweenTwoShapes(e.shape1,e.shape2)}closestPointsOnShapeFromPoints(e){return this.och.operationsService.closestPointsOnShapeFromPoints(e)}closestPointsOnShapesFromPoints(e){return this.och.operationsService.closestPointsOnShapesFromPoints(e)}distancesToShapeFromPoints(e){return this.och.operationsService.distancesToShapeFromPoints(e)}loft(e){return this.och.operationsService.loft(e)}loftAdvanced(e){return this.och.operationsService.loftAdvanced(e)}offset(e){return this.och.operationsService.offset(e)}offsetAdv(e){return this.och.operationsService.offsetAdv(e)}offset3DWire(e){return this.och.operationsService.offset3DWire(e)}extrudeShapes(e){return this.och.operationsService.extrudeShapes(e)}extrude(e){return this.och.operationsService.extrude(e)}splitShapeWithShapes(e){return this.och.operationsService.splitShapeWithShapes(e)}revolve(e){return this.och.operationsService.revolve(e)}rotatedExtrude(e){return this.och.operationsService.rotatedExtrude(e)}pipe(e){return this.och.operationsService.pipe(e)}pipePolylineWireNGon(e){return this.och.operationsService.pipePolylineWireNGon(e)}pipeWireCylindrical(e){return this.och.operationsService.pipeWireCylindrical(e)}pipeWiresCylindrical(e){return this.och.operationsService.pipeWiresCylindrical(e)}makeThickSolidSimple(e){return this.och.operationsService.makeThickSolidSimple(e)}makeThickSolidByJoin(e){return this.och.operationsService.makeThickSolidByJoin(e)}slice(e){return this.och.operationsService.slice(e)}sliceInStepPattern(e){return this.och.operationsService.sliceInStepPattern(e)}}class Te{constructor(e,t){this.occ=e,this.och=t}transform(e){const t=this.scale({shape:e.shape,factor:e.scaleFactor}),r=this.rotate({shape:t,axis:e.rotationAxis,angle:e.rotationAngle}),i=this.translate({shape:r,translation:e.translation});return t.delete(),r.delete(),i}rotate(e){return this.och.transformsService.rotate(e)}rotateAroundCenter(e){const t=this.translate({shape:e.shape,translation:e.center.map((e=>-e))}),r=e.angle,i=this.rotate({shape:t,axis:e.axis,angle:r}),n=this.translate({shape:i,translation:e.center});return i.delete(),t.delete(),n}align(e){return this.och.transformsService.align(e)}alignAndTranslate(e){return this.och.transformsService.alignAndTranslate(e)}translate(e){return this.och.transformsService.translate(e)}scale(e){const t=new this.occ.gp_Trsf_1,r=this.och.entitiesService.gpPnt([0,0,0]);t.SetScale(r,e.factor);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.och.converterService.getActualTypeOfShape(n);return r.delete(),t.delete(),i.delete(),n.delete(),s}scale3d(e){const t=this.translate({shape:e.shape,translation:e.center.map((e=>-e))}),r=new this.occ.gp_GTrsf_1,i=e.scale,n=new this.occ.gp_Mat_2(i[0],0,0,0,i[1],0,0,0,i[2]);let s;r.SetVectorialPart(n);try{const i=new this.occ.BRepBuilderAPI_GTransform_2(t,r,!1),n=new this.occ.Message_ProgressRange_1;i.Build(n);const o=i.Shape();s=this.translate({shape:o,translation:e.center}),i.delete(),o.delete(),n.delete()}catch(e){throw new Error("Could not scale the shape")}return t.delete(),r.delete(),n.delete(),s}mirror(e){return this.och.transformsService.mirror(e)}mirrorAlongNormal(e){return this.och.transformsService.mirrorAlongNormal(e)}transformShapes(e){return this.checkIfListsEqualLength([e.shapes,e.translations,e.rotationAxes,e.rotationAngles,e.scaleFactors]),e.shapes.map(((t,r)=>this.transform({shape:t,translation:e.translations[r],rotationAxis:e.rotationAxes[r],rotationAngle:e.rotationAngles[r],scaleFactor:e.scaleFactors[r]})))}rotateShapes(e){return this.checkIfListsEqualLength([e.shapes,e.axes,e.angles]),e.shapes.map(((t,r)=>this.rotate({shape:t,axis:e.axes[r],angle:e.angles[r]})))}rotateAroundCenterShapes(e){return this.checkIfListsEqualLength([e.shapes,e.axes,e.angles]),e.shapes.map(((t,r)=>this.rotateAroundCenter({shape:t,axis:e.axes[r],angle:e.angles[r],center:e.centers[r]})))}alignShapes(e){return this.checkIfListsEqualLength([e.shapes,e.fromOrigins,e.fromDirections,e.toOrigins,e.toDirections]),e.shapes.map(((t,r)=>this.align({shape:t,fromOrigin:e.fromOrigins[r],fromDirection:e.fromDirections[r],toOrigin:e.toOrigins[r],toDirection:e.toDirections[r]})))}alignAndTranslateShapes(e){return this.checkIfListsEqualLength([e.shapes,e.centers,e.directions]),e.shapes.map(((t,r)=>this.alignAndTranslate({shape:t,center:e.centers[r],direction:e.directions[r]})))}translateShapes(e){return this.checkIfListsEqualLength([e.shapes,e.translations]),e.shapes.map(((t,r)=>this.translate({shape:t,translation:e.translations[r]})))}scaleShapes(e){return this.checkIfListsEqualLength([e.shapes,e.factors]),e.shapes.map(((t,r)=>this.scale({shape:t,factor:e.factors[r]})))}scale3dShapes(e){return this.checkIfListsEqualLength([e.shapes,e.scales,e.centers]),e.shapes.map(((t,r)=>this.scale3d({shape:t,scale:e.scales[r],center:e.centers[r]})))}mirrorShapes(e){return this.checkIfListsEqualLength([e.shapes,e.directions,e.origins]),e.shapes.map(((t,r)=>this.mirror({shape:t,origin:e.origins[r],direction:e.directions[r]})))}mirrorAlongNormalShapes(e){return this.checkIfListsEqualLength([e.shapes,e.normals,e.origins]),e.shapes.map(((t,r)=>this.mirrorAlongNormal({shape:t,normal:e.normals[r],origin:e.origins[r]})))}checkIfListsEqualLength(e){const t=e[0].length;if(e.some((e=>e.length!==t)))throw new Error("Some of the list lengths are not the same. For this operation to work all lists need to be of equal length")}}class xe{constructor(e,t){this.occ=e,this.och=t}filletEdges(e){return this.och.filletsService.filletEdges(e)}filletEdgesList(e){return this.och.filletsService.filletEdgesList(e)}filletEdgesListOneRadius(e){return this.och.filletsService.filletEdgesListOneRadius(e)}filletEdgeVariableRadius(e){return this.och.filletsService.filletEdgeVariableRadius(e)}filletEdgesVariableRadius(e){return this.och.filletsService.filletEdgesVariableRadius(e)}filletEdgesSameVariableRadius(e){return this.och.filletsService.filletEdgesSameVariableRadius(e)}chamferEdges(e){return this.och.filletsService.chamferEdges(e)}chamferEdgesList(e){return this.och.filletsService.chamferEdgesList(e)}chamferEdgeDistAngle(e){return this.och.filletsService.chamferEdgeDistAngle(e)}chamferEdgesDistAngle(e){return this.och.filletsService.chamferEdgesDistAngle(e)}chamferEdgesDistsAngles(e){return this.och.filletsService.chamferEdgesDistsAngles(e)}chamferEdgeTwoDistances(e){return this.och.filletsService.chamferEdgeTwoDistances(e)}chamferEdgesTwoDistances(e){return this.och.filletsService.chamferEdgesTwoDistances(e)}chamferEdgesTwoDistancesLists(e){return this.och.filletsService.chamferEdgesTwoDistancesLists(e)}filletTwoEdgesInPlaneIntoAWire(e){const t=this.och.entitiesService.gpPln(e.planeOrigin,e.planeDirection),r=new this.occ.ChFi2d_FilletAlgo_3(e.edge1,e.edge2,t);r.Perform(e.radius);const i=this.och.entitiesService.gpPnt(e.planeOrigin),n=new this.occ.TopoDS_Edge,s=new this.occ.TopoDS_Edge;let o=-1;void 0!==e.solution&&(o=e.solution);const a=r.Result(i,n,s,o),c=this.och.converterService.combineEdgesAndWiresIntoAWire({shapes:[n,a,s]});return r.delete(),i.delete(),t.delete(),n.delete(),s.delete(),a.delete(),c}fillet3DWire(e){return this.och.filletsService.fillet3DWire(e)}fillet2d(e){if(e.indexes&&e.radiusList&&e.radiusList.length!==e.indexes.length)throw new Error("When using radius list, length of the list must match index list of corners that you want to fillet.");let t,r=!1;if(e.shape.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_FACE)t=this.och.converterService.getActualTypeOfShape(e.shape),r=!0;else{if(e.shape.ShapeType()!==this.occ.TopAbs_ShapeEnum.TopAbs_WIRE)throw new Error("You can only fillet a 2d wire or a 2d face.");{const r=new this.occ.BRepBuilderAPI_MakeFace_15(e.shape,!0),i=new this.occ.Message_ProgressRange_1;r.Build(i);const n=r.Shape();t=this.och.converterService.getActualTypeOfShape(n),n.delete(),i.delete(),r.delete()}}const i=new this.occ.BRepFilletAPI_MakeFillet2d_2(t),n=new this.occ.TopExp_Explorer_2(e.shape,this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);let s=1;const o=[];for(;n.More();n.Next()){const e=this.occ.TopoDS.Vertex_1(n.Current());s%2==0&&o.push(e),s++}r||e.shape.Closed_1()||o.pop();let a=0;o.forEach(((t,r)=>{e.indexes?e.indexes.includes(r+1)&&(this.applyRadiusToVertex(e,i,t,a),a++):this.applyRadiusToVertex(e,i,t,r)}));const c=new this.occ.Message_ProgressRange_1;let h;if(i.Build(c),r)h=i.Shape();else if(i.IsDone()){const e=i.Shape(),t=this.och.shapeGettersService.getWires({shape:e});1===t.length&&(h=t[0])}else{const r=this.och.facesService.faceNormalOnUV({shape:t,paramU:.5,paramV:.5});h=this.fillet3DWire({shape:e.shape,radius:e.radius,radiusList:e.radiusList,indexes:e.indexes,direction:r})}return n.delete(),i.delete(),c.delete(),o.forEach((e=>e.delete())),h}applyRadiusToVertex(e,t,r,i){if(e.radiusList){const n=e.radiusList;t.AddFillet(r,n[i])}else e.radius&&t.AddFillet(r,e.radius)}}class ke{constructor(e,t){this.occ=e,this.och=t}fixEdgeOrientationsAlongWire(e){return this.och.edgesService.fixEdgeOrientationsAlongWire(e)}basicShapeRepair(e){const t=new this.occ.ShapeFix_Shape_1;t.Init(e.shape),t.SetPrecision(e.precision),t.SetMaxTolerance(e.maxTolerance),t.SetMinTolerance(e.minTolerance);const r=new this.occ.Message_ProgressRange_1;t.Perform(r),r.delete();const i=t.Shape();return t.delete(),i}fixSmallEdgeOnWire(e){const t=new this.occ.ShapeFix_Wire_1;return t.Load_1(e.shape),t.FixSmall_1(e.lockvtx,e.precsmall),t.Perform(),t.Wire()}}class Pe{constructor(e,t){this.occ=e,this.och=t,this.shapes=new te(e,t),this.geom=new q(e,t),this.transforms=new Te(e,t),this.operations=new Ee(e,t),this.booleans=new be(e,t),this.fillets=new xe(e,t),this.shapeFix=new ke(e,t),this.io=new we(e,t)}shapesToMeshes(e){return e.shapes.map((t=>this.shapeToMesh({shape:t,precision:e.precision,adjustYtoZ:e.adjustYtoZ})))}shapeToMesh(e){const t=[],r=[],i=[];let n=e.shape;if(n.IsNull())return{faceList:t,edgeList:r,pointsList:[]};if(this.occ.BRepTools.Clean(n,!0),e.adjustYtoZ){const t=this.och.transformsService.rotate({shape:e.shape,axis:[1,0,0],angle:-90}),r=this.och.transformsService.mirrorAlongNormal({shape:t,origin:[0,0,0],normal:[0,0,1]});t.delete(),n.delete(),n=r}const s=[],o=this.och.shapeGettersService.getFaces({shape:n});let a;o&&o.length&&(a=new this.occ.BRepMesh_IncrementalMesh_2(n,e.precision,!1,.5,!1),o.forEach(((e,r)=>{const i=new this.occ.TopLoc_Location_1,n=this.occ.BRep_Tool.Triangulation(e,i,0);if(n.IsNull())return void console.error("Encountered Null Face!");const o={vertex_coord:[],normal_coord:[],uvs:[],tri_indexes:[],vertex_coord_vec:[],number_of_triangles:0,face_index:r},a=new this.occ.Poly_Connect_2(n),c=n.get();o.vertex_coord=new Array(3*c.NbNodes()),o.vertex_coord_vec=[];for(let e=0;e{const n={vertex_coord:[],edge_index:-1},s=new this.occ.TopLoc_Location_1,o=new this.occ.BRepAdaptor_Curve_2(t),a=new this.occ.GCPnts_TangentialDeflection_2(o,e.precision,.1,2,1e-9,1e-7);n.vertex_coord=[];const c=a.NbPoints(),h=[];for(let e=0;ee.delete())),s.delete(),o.delete(),a.delete(),this.occ.BRepTools.Clean(t,!0)}));const c=this.och.shapeGettersService.getVertices({shape:n});return c.length>0&&c.forEach((e=>{const t=this.occ.BRep_Tool.Pnt(e);i.push([t.X(),t.Y(),t.Z()]),t.delete()})),a&&a.Delete(),this.occ.BRepTools.Clean(n,!0),{faceList:t,edgeList:r,pointsList:i}}}var Ce,Ae=(Ce=(Ce="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(e){var t,i;(e=void 0!==(e=e||{})?e:{}).ready=new Promise((function(e,r){t=e,i=r}));var n,s,o,a,c,h,l=Object.assign({},e),u=[],d="./this.program",p=(e,t)=>{throw t},f="object"==typeof window,g="function"==typeof importScripts,v="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";v?(m=g?r(699).dirname(m)+"/":"//",h=()=>{c||(a=r(439),c=r(699))},n=function(e,t){return h(),e=c.normalize(e),a.readFileSync(e,t?void 0:"utf8")},o=e=>{var t=n(e,!0);return t.buffer||(t=new Uint8Array(t)),t},s=(e,t,r)=>{h(),e=c.normalize(e),a.readFile(e,(function(e,i){e?r(e):t(i.buffer)}))},process.argv.length>1&&(d=process.argv[1].replace(/\\/g,"/")),u=process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof yr))throw e})),process.on("unhandledRejection",(function(e){throw e})),p=(e,t)=>{if(te())throw process.exitCode=e,t;var r;(r=t)instanceof yr||S("exiting due to exception: "+r),process.exit(e)},e.inspect=function(){return"[Emscripten Module object]"}):(f||g)&&(g?m=self.location.href:"undefined"!=typeof document&&document.currentScript&&(m=document.currentScript.src),Ce&&(m=Ce),m=0!==m.indexOf("blob:")?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",n=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},g&&(o=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),s=(e,t,r)=>{var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=()=>{200==i.status||0==i.status&&i.response?t(i.response):r()},i.onerror=r,i.send(null)});var y=e.print||console.log.bind(console),S=e.printErr||console.warn.bind(console);Object.assign(e,l),l=null,e.arguments&&(u=e.arguments),e.thisProgram&&(d=e.thisProgram),e.quit&&(p=e.quit);var b;function w(e){w.shown||(w.shown={}),w.shown[e]||(w.shown[e]=1,S(e))}e.wasmBinary&&(b=e.wasmBinary);var E,T=e.noExitRuntime||!0;"object"!=typeof WebAssembly&&ae("no native wasm support detected");var x,k=!1;function P(e,t){e||ae(t)}var C="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function A(e,t,r){for(var i=(t>>>=0)+r,n=t;e[n]&&!(n>=i);)++n;if(n-t>16&&e.buffer&&C)return C.decode(e.subarray(t,n));for(var s="";t>10,56320|1023&h)}}else s+=String.fromCharCode((31&o)<<6|a)}else s+=String.fromCharCode(o)}return s}function _(e,t){return(e>>>=0)?A(B,e,t):""}function O(e,t,r,i){if(!(i>0))return 0;for(var n=r>>>=0,s=r+i-1,o=0;o=55296&&a<=57343&&(a=65536+((1023&a)<<10)|1023&e.charCodeAt(++o)),a<=127){if(r>=s)break;t[r++>>>0]=a}else if(a<=2047){if(r+1>=s)break;t[r++>>>0]=192|a>>6,t[r++>>>0]=128|63&a}else if(a<=65535){if(r+2>=s)break;t[r++>>>0]=224|a>>12,t[r++>>>0]=128|a>>6&63,t[r++>>>0]=128|63&a}else{if(r+3>=s)break;t[r++>>>0]=240|a>>18,t[r++>>>0]=128|a>>12&63,t[r++>>>0]=128|a>>6&63,t[r++>>>0]=128|63&a}}return t[r>>>0]=0,r-n}function D(e,t,r){return O(e,B,t,r)}function R(e){for(var t=0,r=0;r=55296&&i<=57343&&(i=65536+((1023&i)<<10)|1023&e.charCodeAt(++r)),i<=127?++t:t+=i<=2047?2:i<=65535?3:4}return t}var F,L,B,M,I,U,W,N,G,H="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0;function V(e,t){for(var r=e,i=r>>1,n=i+t/2;!(i>=n)&&I[i>>>0];)++i;if((r=i<<1)-e>32&&H)return H.decode(B.subarray(e>>>0,r>>>0));for(var s="",o=0;!(o>=t/2);++o){var a=M[e+2*o>>>1];if(0==a)break;s+=String.fromCharCode(a)}return s}function z(e,t,r){if(void 0===r&&(r=2147483647),r<2)return 0;for(var i=t,n=(r-=2)<2*e.length?r/2:e.length,s=0;s>>1]=o,t+=2}return M[t>>>1]=0,t-i}function j(e){return 2*e.length}function q(e,t){for(var r=0,i="";!(r>=t/4);){var n=U[e+4*r>>>2];if(0==n)break;if(++r,n>=65536){var s=n-65536;i+=String.fromCharCode(55296|s>>10,56320|1023&s)}else i+=String.fromCharCode(n)}return i}function $(e,t,r){if(void 0===r&&(r=2147483647),r<4)return 0;for(var i=t>>>=0,n=i+r-4,s=0;s=55296&&o<=57343&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++s)),U[t>>>2]=o,(t+=4)+4>n)break}return U[t>>>2]=0,t-i}function Y(e){for(var t=0,r=0;r=55296&&i<=57343&&++r,t+=4}return t}function X(e){var t=R(e)+1,r=ur(t);return r&&O(e,L,r,t),r}function Z(t){F=t,e.HEAP8=L=new Int8Array(t),e.HEAP16=M=new Int16Array(t),e.HEAP32=U=new Int32Array(t),e.HEAPU8=B=new Uint8Array(t),e.HEAPU16=I=new Uint16Array(t),e.HEAPU32=W=new Uint32Array(t),e.HEAPF32=N=new Float32Array(t),e.HEAPF64=G=new Float64Array(t)}e.INITIAL_MEMORY;var J,Q=[],K=[],ee=[];function te(){return T}var re=0,ie=null,ne=null;function se(t){re++,e.monitorRunDependencies&&e.monitorRunDependencies(re)}function oe(t){if(re--,e.monitorRunDependencies&&e.monitorRunDependencies(re),0==re&&(null!==ie&&(clearInterval(ie),ie=null),ne)){var r=ne;ne=null,r()}}function ae(t){e.onAbort&&e.onAbort(t),S(t="Aborted("+t+")"),k=!0,x=1,t+=". Build with -sASSERTIONS for more info.";var r=new WebAssembly.RuntimeError(t);throw i(r),r}var ce,he,le,ue;function de(e){return e.startsWith("data:application/octet-stream;base64,")}function pe(e){return e.startsWith("file://")}function fe(e){try{if(e==ce&&b)return new Uint8Array(b);if(o)return o(e);throw"both async and sync fetching of the wasm failed"}catch(e){ae(e)}}function ge(t){for(;t.length>0;){var r=t.shift();if("function"!=typeof r){var i=r.func;"number"==typeof i?void 0===r.arg?me(i)():me(i)(r.arg):i(void 0===r.arg?null:r.arg)}else r(e)}}de(ce="bitbybit-dev-occt.wasm")||(he=ce,ce=e.locateFile?e.locateFile(he,m):m+he);var ve=[];function me(e){var t=ve[e];return t||(e>=ve.length&&(ve.length=e+1),ve[e]=t=J.get(e)),t}function ye(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){W[this.ptr+4>>>2]=e},this.get_type=function(){return W[this.ptr+4>>>2]},this.set_destructor=function(e){W[this.ptr+8>>>2]=e},this.get_destructor=function(){return W[this.ptr+8>>>2]},this.set_refcount=function(e){U[this.ptr>>>2]=e},this.set_caught=function(e){e=e?1:0,L[this.ptr+12>>>0]=e},this.get_caught=function(){return 0!=L[this.ptr+12>>>0]},this.set_rethrown=function(e){e=e?1:0,L[this.ptr+13>>>0]=e},this.get_rethrown=function(){return 0!=L[this.ptr+13>>>0]},this.init=function(e,t){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(t),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var e=U[this.ptr>>>2];U[this.ptr>>>2]=e+1},this.release_ref=function(){var e=U[this.ptr>>>2];return U[this.ptr>>>2]=e-1,1===e},this.set_adjusted_ptr=function(e){W[this.ptr+16>>>2]=e},this.get_adjusted_ptr=function(){return W[this.ptr+16>>>2]},this.get_exception_ptr=function(){if(mr(this.get_type()))return W[this.excPtr>>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var Se={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var r=0,i=e.length-1;i>=0;i--){var n=e[i];"."===n?e.splice(i,1):".."===n?(e.splice(i,1),r++):r&&(e.splice(i,1),r--)}if(t)for(;r;r--)e.unshift("..");return e},normalize:e=>{var t=Se.isAbs(e),r="/"===e.substr(-1);return(e=Se.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=Se.splitPath(e),r=t[0],i=t[1];return r||i?(i&&(i=i.substr(0,i.length-1)),r+i):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=Se.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments,0);return Se.normalize(e.join("/"))},join2:(e,t)=>Se.normalize(e+"/"+t)},be={resolve:function(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var i=r>=0?arguments[r]:xe.cwd();if("string"!=typeof i)throw new TypeError("Arguments to path.resolve must be strings");if(!i)return"";e=i+"/"+e,t=Se.isAbs(i)}return(t?"/":"")+(e=Se.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||"."},relative:(e,t)=>{function r(e){for(var t=0;t=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=be.resolve(e).substr(1),t=be.resolve(t).substr(1);for(var i=r(e.split("/")),n=r(t.split("/")),s=Math.min(i.length,n.length),o=s,a=0;a0?r.slice(0,i).toString("utf-8"):null}else"undefined"!=typeof window&&"function"==typeof window.prompt?null!==(t=window.prompt("Input: "))&&(t+="\n"):"function"==typeof readline&&null!==(t=readline())&&(t+="\n");if(!t)return null;e.input=cr(t,!0)}return e.input.shift()},put_char:function(e,t){null===t||10===t?(y(A(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},flush:function(e){e.output&&e.output.length>0&&(y(A(e.output,0)),e.output=[])}},default_tty1_ops:{put_char:function(e,t){null===t||10===t?(S(A(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},flush:function(e){e.output&&e.output.length>0&&(S(A(e.output,0)),e.output=[])}}};function Ee(e){e=function(e,t){return 65536*Math.ceil(e/65536)}(e);var t=vr(65536,e);return t?(function(e,t){B.fill(0,e,e+t)}(t,e),t):0}var Te={ops_table:null,mount:function(e){return Te.createNode(null,"/",16895,0)},createNode:function(e,t,r,i){if(xe.isBlkdev(r)||xe.isFIFO(r))throw new xe.ErrnoError(63);Te.ops_table||(Te.ops_table={dir:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr,lookup:Te.node_ops.lookup,mknod:Te.node_ops.mknod,rename:Te.node_ops.rename,unlink:Te.node_ops.unlink,rmdir:Te.node_ops.rmdir,readdir:Te.node_ops.readdir,symlink:Te.node_ops.symlink},stream:{llseek:Te.stream_ops.llseek}},file:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr},stream:{llseek:Te.stream_ops.llseek,read:Te.stream_ops.read,write:Te.stream_ops.write,allocate:Te.stream_ops.allocate,mmap:Te.stream_ops.mmap,msync:Te.stream_ops.msync}},link:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr,readlink:Te.node_ops.readlink},stream:{}},chrdev:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr},stream:xe.chrdev_stream_ops}});var n=xe.createNode(e,t,r,i);return xe.isDir(n.mode)?(n.node_ops=Te.ops_table.dir.node,n.stream_ops=Te.ops_table.dir.stream,n.contents={}):xe.isFile(n.mode)?(n.node_ops=Te.ops_table.file.node,n.stream_ops=Te.ops_table.file.stream,n.usedBytes=0,n.contents=null):xe.isLink(n.mode)?(n.node_ops=Te.ops_table.link.node,n.stream_ops=Te.ops_table.link.stream):xe.isChrdev(n.mode)&&(n.node_ops=Te.ops_table.chrdev.node,n.stream_ops=Te.ops_table.chrdev.stream),n.timestamp=Date.now(),e&&(e.contents[t]=n,e.timestamp=n.timestamp),n},getFileDataAsTypedArray:function(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage:function(e,t){t>>>=0;var r=e.contents?e.contents.length:0;if(!(r>=t)){t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));var i=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(i.subarray(0,e.usedBytes),0)}},resizeFileStorage:function(e,t){if(t>>>=0,e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var r=e.contents;e.contents=new Uint8Array(t),r&&e.contents.set(r.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr:function(e){var t={};return t.dev=xe.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,xe.isDir(e.mode)?t.size=4096:xe.isFile(e.mode)?t.size=e.usedBytes:xe.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr:function(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&Te.resizeFileStorage(e,t.size)},lookup:function(e,t){throw xe.genericErrors[44]},mknod:function(e,t,r,i){return Te.createNode(e,t,r,i)},rename:function(e,t,r){if(xe.isDir(e.mode)){var i;try{i=xe.lookupNode(t,r)}catch(e){}if(i)for(var n in i.contents)throw new xe.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=r,t.contents[r]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink:function(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir:function(e,t){var r=xe.lookupNode(e,t);for(var i in r.contents)throw new xe.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir:function(e){var t=[".",".."];for(var r in e.contents)e.contents.hasOwnProperty(r)&&t.push(r);return t},symlink:function(e,t,r){var i=Te.createNode(e,t,41471,0);return i.link=r,i},readlink:function(e){if(!xe.isLink(e.mode))throw new xe.ErrnoError(28);return e.link}},stream_ops:{read:function(e,t,r,i,n){var s=e.node.contents;if(n>=e.node.usedBytes)return 0;var o=Math.min(e.node.usedBytes-n,i);if(o>8&&s.subarray)t.set(s.subarray(n,n+o),r);else for(var a=0;a0||r+t>>=0,L.set(a,s>>>0)}else o=!1,s=a.byteOffset;return{ptr:s,allocated:o}},msync:function(e,t,r,i,n){if(!xe.isFile(e.node.mode))throw new xe.ErrnoError(43);return 2&n||Te.stream_ops.write(e,t,0,i,r,!1),0}}},xe={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(e,t={})=>{if(!(e=be.resolve(xe.cwd(),e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new xe.ErrnoError(32);for(var r=Se.normalizeArray(e.split("/").filter((e=>!!e)),!1),i=xe.root,n="/",s=0;s40)throw new xe.ErrnoError(32)}}return{path:n,node:i}},getPath:e=>{for(var t;;){if(xe.isRoot(e)){var r=e.mount.mountpoint;return t?"/"!==r[r.length-1]?r+"/"+t:r+t:r}t=t?e.name+"/"+t:e.name,e=e.parent}},hashName:(e,t)=>{for(var r=0,i=0;i>>0)%xe.nameTable.length},hashAddNode:e=>{var t=xe.hashName(e.parent.id,e.name);e.name_next=xe.nameTable[t],xe.nameTable[t]=e},hashRemoveNode:e=>{var t=xe.hashName(e.parent.id,e.name);if(xe.nameTable[t]===e)xe.nameTable[t]=e.name_next;else for(var r=xe.nameTable[t];r;){if(r.name_next===e){r.name_next=e.name_next;break}r=r.name_next}},lookupNode:(e,t)=>{var r=xe.mayLookup(e);if(r)throw new xe.ErrnoError(r,e);for(var i=xe.hashName(e.id,t),n=xe.nameTable[i];n;n=n.name_next){var s=n.name;if(n.parent.id===e.id&&s===t)return n}return xe.lookup(e,t)},createNode:(e,t,r,i)=>{var n=new xe.FSNode(e,t,r,i);return xe.hashAddNode(n),n},destroyNode:e=>{xe.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>!(49152&~e),flagModes:{r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},modeStringToFlags:e=>{var t=xe.flagModes[e];if(void 0===t)throw new Error("Unknown file open mode: "+e);return t},flagsToPermissionString:e=>{var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:(e,t)=>xe.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup:e=>xe.nodePermissions(e,"x")||(e.node_ops.lookup?0:2),mayCreate:(e,t)=>{try{return xe.lookupNode(e,t),20}catch(e){}return xe.nodePermissions(e,"wx")},mayDelete:(e,t,r)=>{var i;try{i=xe.lookupNode(e,t)}catch(e){return e.errno}var n=xe.nodePermissions(e,"wx");if(n)return n;if(r){if(!xe.isDir(i.mode))return 54;if(xe.isRoot(i)||xe.getPath(i)===xe.cwd())return 10}else if(xe.isDir(i.mode))return 31;return 0},mayOpen:(e,t)=>e?xe.isLink(e.mode)?32:xe.isDir(e.mode)&&("r"!==xe.flagsToPermissionString(t)||512&t)?31:xe.nodePermissions(e,xe.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd:(e=0,t=xe.MAX_OPEN_FDS)=>{for(var r=e;r<=t;r++)if(!xe.streams[r])return r;throw new xe.ErrnoError(33)},getStream:e=>xe.streams[e],createStream:(e,t,r)=>{xe.FSStream||(xe.FSStream=function(){this.shared={}},xe.FSStream.prototype={},Object.defineProperties(xe.FSStream.prototype,{object:{get:function(){return this.node},set:function(e){this.node=e}},isRead:{get:function(){return 1!=(2097155&this.flags)}},isWrite:{get:function(){return!!(2097155&this.flags)}},isAppend:{get:function(){return 1024&this.flags}},flags:{get:function(){return this.shared.flags},set:function(e){this.shared.flags=e}},position:{get:function(){return this.shared.position},set:function(e){this.shared.position=e}}})),e=Object.assign(new xe.FSStream,e);var i=xe.nextfd(t,r);return e.fd=i,xe.streams[i]=e,e},closeStream:e=>{xe.streams[e]=null},chrdev_stream_ops:{open:e=>{var t=xe.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:()=>{throw new xe.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice:(e,t)=>{xe.devices[e]={stream_ops:t}},getDevice:e=>xe.devices[e],getMounts:e=>{for(var t=[],r=[e];r.length;){var i=r.pop();t.push(i),r.push.apply(r,i.mounts)}return t},syncfs:(e,t)=>{"function"==typeof e&&(t=e,e=!1),xe.syncFSRequests++,xe.syncFSRequests>1&&S("warning: "+xe.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work");var r=xe.getMounts(xe.root.mount),i=0;function n(e){return xe.syncFSRequests--,t(e)}function s(e){if(e)return s.errored?void 0:(s.errored=!0,n(e));++i>=r.length&&n(null)}r.forEach((t=>{if(!t.type.syncfs)return s(null);t.type.syncfs(t,e,s)}))},mount:(e,t,r)=>{var i,n="/"===r,s=!r;if(n&&xe.root)throw new xe.ErrnoError(10);if(!n&&!s){var o=xe.lookupPath(r,{follow_mount:!1});if(r=o.path,i=o.node,xe.isMountpoint(i))throw new xe.ErrnoError(10);if(!xe.isDir(i.mode))throw new xe.ErrnoError(54)}var a={type:e,opts:t,mountpoint:r,mounts:[]},c=e.mount(a);return c.mount=a,a.root=c,n?xe.root=c:i&&(i.mounted=a,i.mount&&i.mount.mounts.push(a)),c},unmount:e=>{var t=xe.lookupPath(e,{follow_mount:!1});if(!xe.isMountpoint(t.node))throw new xe.ErrnoError(28);var r=t.node,i=r.mounted,n=xe.getMounts(i);Object.keys(xe.nameTable).forEach((e=>{for(var t=xe.nameTable[e];t;){var r=t.name_next;n.includes(t.mount)&&xe.destroyNode(t),t=r}})),r.mounted=null;var s=r.mount.mounts.indexOf(i);r.mount.mounts.splice(s,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod:(e,t,r)=>{var i=xe.lookupPath(e,{parent:!0}).node,n=Se.basename(e);if(!n||"."===n||".."===n)throw new xe.ErrnoError(28);var s=xe.mayCreate(i,n);if(s)throw new xe.ErrnoError(s);if(!i.node_ops.mknod)throw new xe.ErrnoError(63);return i.node_ops.mknod(i,n,t,r)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,xe.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,xe.mknod(e,t,0)),mkdirTree:(e,t)=>{for(var r=e.split("/"),i="",n=0;n(void 0===r&&(r=t,t=438),t|=8192,xe.mknod(e,t,r)),symlink:(e,t)=>{if(!be.resolve(e))throw new xe.ErrnoError(44);var r=xe.lookupPath(t,{parent:!0}).node;if(!r)throw new xe.ErrnoError(44);var i=Se.basename(t),n=xe.mayCreate(r,i);if(n)throw new xe.ErrnoError(n);if(!r.node_ops.symlink)throw new xe.ErrnoError(63);return r.node_ops.symlink(r,i,e)},rename:(e,t)=>{var r,i,n=Se.dirname(e),s=Se.dirname(t),o=Se.basename(e),a=Se.basename(t);if(r=xe.lookupPath(e,{parent:!0}).node,i=xe.lookupPath(t,{parent:!0}).node,!r||!i)throw new xe.ErrnoError(44);if(r.mount!==i.mount)throw new xe.ErrnoError(75);var c,h=xe.lookupNode(r,o),l=be.relative(e,s);if("."!==l.charAt(0))throw new xe.ErrnoError(28);if("."!==(l=be.relative(t,n)).charAt(0))throw new xe.ErrnoError(55);try{c=xe.lookupNode(i,a)}catch(e){}if(h!==c){var u=xe.isDir(h.mode),d=xe.mayDelete(r,o,u);if(d)throw new xe.ErrnoError(d);if(d=c?xe.mayDelete(i,a,u):xe.mayCreate(i,a))throw new xe.ErrnoError(d);if(!r.node_ops.rename)throw new xe.ErrnoError(63);if(xe.isMountpoint(h)||c&&xe.isMountpoint(c))throw new xe.ErrnoError(10);if(i!==r&&(d=xe.nodePermissions(r,"w")))throw new xe.ErrnoError(d);xe.hashRemoveNode(h);try{r.node_ops.rename(h,i,a)}catch(e){throw e}finally{xe.hashAddNode(h)}}},rmdir:e=>{var t=xe.lookupPath(e,{parent:!0}).node,r=Se.basename(e),i=xe.lookupNode(t,r),n=xe.mayDelete(t,r,!0);if(n)throw new xe.ErrnoError(n);if(!t.node_ops.rmdir)throw new xe.ErrnoError(63);if(xe.isMountpoint(i))throw new xe.ErrnoError(10);t.node_ops.rmdir(t,r),xe.destroyNode(i)},readdir:e=>{var t=xe.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new xe.ErrnoError(54);return t.node_ops.readdir(t)},unlink:e=>{var t=xe.lookupPath(e,{parent:!0}).node;if(!t)throw new xe.ErrnoError(44);var r=Se.basename(e),i=xe.lookupNode(t,r),n=xe.mayDelete(t,r,!1);if(n)throw new xe.ErrnoError(n);if(!t.node_ops.unlink)throw new xe.ErrnoError(63);if(xe.isMountpoint(i))throw new xe.ErrnoError(10);t.node_ops.unlink(t,r),xe.destroyNode(i)},readlink:e=>{var t=xe.lookupPath(e).node;if(!t)throw new xe.ErrnoError(44);if(!t.node_ops.readlink)throw new xe.ErrnoError(28);return be.resolve(xe.getPath(t.parent),t.node_ops.readlink(t))},stat:(e,t)=>{var r=xe.lookupPath(e,{follow:!t}).node;if(!r)throw new xe.ErrnoError(44);if(!r.node_ops.getattr)throw new xe.ErrnoError(63);return r.node_ops.getattr(r)},lstat:e=>xe.stat(e,!0),chmod:(e,t,r)=>{var i;if(!(i="string"==typeof e?xe.lookupPath(e,{follow:!r}).node:e).node_ops.setattr)throw new xe.ErrnoError(63);i.node_ops.setattr(i,{mode:4095&t|-4096&i.mode,timestamp:Date.now()})},lchmod:(e,t)=>{xe.chmod(e,t,!0)},fchmod:(e,t)=>{var r=xe.getStream(e);if(!r)throw new xe.ErrnoError(8);xe.chmod(r.node,t)},chown:(e,t,r,i)=>{var n;if(!(n="string"==typeof e?xe.lookupPath(e,{follow:!i}).node:e).node_ops.setattr)throw new xe.ErrnoError(63);n.node_ops.setattr(n,{timestamp:Date.now()})},lchown:(e,t,r)=>{xe.chown(e,t,r,!0)},fchown:(e,t,r)=>{var i=xe.getStream(e);if(!i)throw new xe.ErrnoError(8);xe.chown(i.node,t,r)},truncate:(e,t)=>{if(t<0)throw new xe.ErrnoError(28);var r;if(!(r="string"==typeof e?xe.lookupPath(e,{follow:!0}).node:e).node_ops.setattr)throw new xe.ErrnoError(63);if(xe.isDir(r.mode))throw new xe.ErrnoError(31);if(!xe.isFile(r.mode))throw new xe.ErrnoError(28);var i=xe.nodePermissions(r,"w");if(i)throw new xe.ErrnoError(i);r.node_ops.setattr(r,{size:t,timestamp:Date.now()})},ftruncate:(e,t)=>{var r=xe.getStream(e);if(!r)throw new xe.ErrnoError(8);if(!(2097155&r.flags))throw new xe.ErrnoError(28);xe.truncate(r.node,t)},utime:(e,t,r)=>{var i=xe.lookupPath(e,{follow:!0}).node;i.node_ops.setattr(i,{timestamp:Math.max(t,r)})},open:(t,r,i)=>{if(""===t)throw new xe.ErrnoError(44);var n;if(i=void 0===i?438:i,i=64&(r="string"==typeof r?xe.modeStringToFlags(r):r)?4095&i|32768:0,"object"==typeof t)n=t;else{t=Se.normalize(t);try{n=xe.lookupPath(t,{follow:!(131072&r)}).node}catch(e){}}var s=!1;if(64&r)if(n){if(128&r)throw new xe.ErrnoError(20)}else n=xe.mknod(t,i,0),s=!0;if(!n)throw new xe.ErrnoError(44);if(xe.isChrdev(n.mode)&&(r&=-513),65536&r&&!xe.isDir(n.mode))throw new xe.ErrnoError(54);if(!s){var o=xe.mayOpen(n,r);if(o)throw new xe.ErrnoError(o)}512&r&&!s&&xe.truncate(n,0),r&=-131713;var a=xe.createStream({node:n,path:xe.getPath(n),flags:r,seekable:!0,position:0,stream_ops:n.stream_ops,ungotten:[],error:!1});return a.stream_ops.open&&a.stream_ops.open(a),!e.logReadFiles||1&r||(xe.readFiles||(xe.readFiles={}),t in xe.readFiles||(xe.readFiles[t]=1)),a},close:e=>{if(xe.isClosed(e))throw new xe.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{xe.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek:(e,t,r)=>{if(xe.isClosed(e))throw new xe.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new xe.ErrnoError(70);if(0!=r&&1!=r&&2!=r)throw new xe.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,r),e.ungotten=[],e.position},read:(e,t,r,i,n)=>{if(r>>>=0,i<0||n<0)throw new xe.ErrnoError(28);if(xe.isClosed(e))throw new xe.ErrnoError(8);if(1==(2097155&e.flags))throw new xe.ErrnoError(8);if(xe.isDir(e.node.mode))throw new xe.ErrnoError(31);if(!e.stream_ops.read)throw new xe.ErrnoError(28);var s=void 0!==n;if(s){if(!e.seekable)throw new xe.ErrnoError(70)}else n=e.position;var o=e.stream_ops.read(e,t,r,i,n);return s||(e.position+=o),o},write:(e,t,r,i,n,s)=>{if(r>>>=0,i<0||n<0)throw new xe.ErrnoError(28);if(xe.isClosed(e))throw new xe.ErrnoError(8);if(!(2097155&e.flags))throw new xe.ErrnoError(8);if(xe.isDir(e.node.mode))throw new xe.ErrnoError(31);if(!e.stream_ops.write)throw new xe.ErrnoError(28);e.seekable&&1024&e.flags&&xe.llseek(e,0,2);var o=void 0!==n;if(o){if(!e.seekable)throw new xe.ErrnoError(70)}else n=e.position;var a=e.stream_ops.write(e,t,r,i,n,s);return o||(e.position+=a),a},allocate:(e,t,r)=>{if(xe.isClosed(e))throw new xe.ErrnoError(8);if(t<0||r<=0)throw new xe.ErrnoError(28);if(!(2097155&e.flags))throw new xe.ErrnoError(8);if(!xe.isFile(e.node.mode)&&!xe.isDir(e.node.mode))throw new xe.ErrnoError(43);if(!e.stream_ops.allocate)throw new xe.ErrnoError(138);e.stream_ops.allocate(e,t,r)},mmap:(e,t,r,i,n)=>{if(2&i&&!(2&n)&&2!=(2097155&e.flags))throw new xe.ErrnoError(2);if(1==(2097155&e.flags))throw new xe.ErrnoError(2);if(!e.stream_ops.mmap)throw new xe.ErrnoError(43);return e.stream_ops.mmap(e,t,r,i,n)},msync:(e,t,r,i,n)=>(r>>>=0,e&&e.stream_ops.msync?e.stream_ops.msync(e,t,r,i,n):0),munmap:e=>0,ioctl:(e,t,r)=>{if(!e.stream_ops.ioctl)throw new xe.ErrnoError(59);return e.stream_ops.ioctl(e,t,r)},readFile:(e,t={})=>{if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error('Invalid encoding type "'+t.encoding+'"');var r,i=xe.open(e,t.flags),n=xe.stat(e).size,s=new Uint8Array(n);return xe.read(i,s,0,n,0),"utf8"===t.encoding?r=A(s,0):"binary"===t.encoding&&(r=s),xe.close(i),r},writeFile:(e,t,r={})=>{r.flags=r.flags||577;var i=xe.open(e,r.flags,r.mode);if("string"==typeof t){var n=new Uint8Array(R(t)+1),s=O(t,n,0,n.length);xe.write(i,n,0,s,void 0,r.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");xe.write(i,t,0,t.byteLength,void 0,r.canOwn)}xe.close(i)},cwd:()=>xe.currentPath,chdir:e=>{var t=xe.lookupPath(e,{follow:!0});if(null===t.node)throw new xe.ErrnoError(44);if(!xe.isDir(t.node.mode))throw new xe.ErrnoError(54);var r=xe.nodePermissions(t.node,"x");if(r)throw new xe.ErrnoError(r);xe.currentPath=t.path},createDefaultDirectories:()=>{xe.mkdir("/tmp"),xe.mkdir("/home"),xe.mkdir("/home/web_user")},createDefaultDevices:()=>{xe.mkdir("/dev"),xe.registerDevice(xe.makedev(1,3),{read:()=>0,write:(e,t,r,i,n)=>i}),xe.mkdev("/dev/null",xe.makedev(1,3)),we.register(xe.makedev(5,0),we.default_tty_ops),we.register(xe.makedev(6,0),we.default_tty1_ops),xe.mkdev("/dev/tty",xe.makedev(5,0)),xe.mkdev("/dev/tty1",xe.makedev(6,0));var e=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return function(){return crypto.getRandomValues(e),e[0]}}if(v)try{var t=r(725);return function(){return t.randomBytes(1)[0]}}catch(e){}return function(){ae("randomDevice")}}();xe.createDevice("/dev","random",e),xe.createDevice("/dev","urandom",e),xe.mkdir("/dev/shm"),xe.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{xe.mkdir("/proc");var e=xe.mkdir("/proc/self");xe.mkdir("/proc/self/fd"),xe.mount({mount:()=>{var t=xe.createNode(e,"fd",16895,73);return t.node_ops={lookup:(e,t)=>{var r=+t,i=xe.getStream(r);if(!i)throw new xe.ErrnoError(8);var n={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>i.path}};return n.parent=n,n}},t}},{},"/proc/self/fd")},createStandardStreams:()=>{e.stdin?xe.createDevice("/dev","stdin",e.stdin):xe.symlink("/dev/tty","/dev/stdin"),e.stdout?xe.createDevice("/dev","stdout",null,e.stdout):xe.symlink("/dev/tty","/dev/stdout"),e.stderr?xe.createDevice("/dev","stderr",null,e.stderr):xe.symlink("/dev/tty1","/dev/stderr"),xe.open("/dev/stdin",0),xe.open("/dev/stdout",1),xe.open("/dev/stderr",1)},ensureErrnoError:()=>{xe.ErrnoError||(xe.ErrnoError=function(e,t){this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},xe.ErrnoError.prototype=new Error,xe.ErrnoError.prototype.constructor=xe.ErrnoError,[44].forEach((e=>{xe.genericErrors[e]=new xe.ErrnoError(e),xe.genericErrors[e].stack=""})))},staticInit:()=>{xe.ensureErrnoError(),xe.nameTable=new Array(4096),xe.mount(Te,{},"/"),xe.createDefaultDirectories(),xe.createDefaultDevices(),xe.createSpecialDirectories(),xe.filesystems={MEMFS:Te}},init:(t,r,i)=>{xe.init.initialized=!0,xe.ensureErrnoError(),e.stdin=t||e.stdin,e.stdout=r||e.stdout,e.stderr=i||e.stderr,xe.createStandardStreams()},quit:()=>{xe.init.initialized=!1;for(var e=0;e{var r=0;return e&&(r|=365),t&&(r|=146),r},findObject:(e,t)=>{var r=xe.analyzePath(e,t);return r.exists?r.object:null},analyzePath:(e,t)=>{try{e=(i=xe.lookupPath(e,{follow:!t})).path}catch(e){}var r={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var i=xe.lookupPath(e,{parent:!0});r.parentExists=!0,r.parentPath=i.path,r.parentObject=i.node,r.name=Se.basename(e),i=xe.lookupPath(e,{follow:!t}),r.exists=!0,r.path=i.path,r.object=i.node,r.name=i.node.name,r.isRoot="/"===i.path}catch(e){r.error=e.errno}return r},createPath:(e,t,r,i)=>{e="string"==typeof e?e:xe.getPath(e);for(var n=t.split("/").reverse();n.length;){var s=n.pop();if(s){var o=Se.join2(e,s);try{xe.mkdir(o)}catch(e){}e=o}}return o},createFile:(e,t,r,i,n)=>{var s=Se.join2("string"==typeof e?e:xe.getPath(e),t),o=xe.getMode(i,n);return xe.create(s,o)},createDataFile:(e,t,r,i,n,s)=>{var o=t;e&&(e="string"==typeof e?e:xe.getPath(e),o=t?Se.join2(e,t):e);var a=xe.getMode(i,n),c=xe.create(o,a);if(r){if("string"==typeof r){for(var h=new Array(r.length),l=0,u=r.length;l{var n=Se.join2("string"==typeof e?e:xe.getPath(e),t),s=xe.getMode(!!r,!!i);xe.createDevice.major||(xe.createDevice.major=64);var o=xe.makedev(xe.createDevice.major++,0);return xe.registerDevice(o,{open:e=>{e.seekable=!1},close:e=>{i&&i.buffer&&i.buffer.length&&i(10)},read:(e,t,i,n,s)=>{for(var o=0,a=0;a{for(var o=0;o{if(e.isDevice||e.isFolder||e.link||e.contents)return!0;if("undefined"!=typeof XMLHttpRequest)throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");if(!n)throw new Error("Cannot load without read() or XMLHttpRequest.");try{e.contents=cr(n(e.url),!0),e.usedBytes=e.contents.length}catch(e){throw new xe.ErrnoError(29)}},createLazyFile:(e,t,r,i,n)=>{function s(){this.lengthKnown=!1,this.chunks=[]}if(s.prototype.get=function(e){if(!(e>this.length-1||e<0)){var t=e%this.chunkSize,r=e/this.chunkSize|0;return this.getter(r)[t]}},s.prototype.setDataGetter=function(e){this.getter=e},s.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",r,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+r+". Status: "+e.status);var t,i=Number(e.getResponseHeader("Content-length")),n=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,s=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,o=1048576;n||(o=i);var a=this;a.setDataGetter((e=>{var t=e*o,n=(e+1)*o-1;if(n=Math.min(n,i-1),void 0===a.chunks[e]&&(a.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>i-1)throw new Error("only "+i+" bytes available! programmer error!");var n=new XMLHttpRequest;if(n.open("GET",r,!1),i!==o&&n.setRequestHeader("Range","bytes="+e+"-"+t),n.responseType="arraybuffer",n.overrideMimeType&&n.overrideMimeType("text/plain; charset=x-user-defined"),n.send(null),!(n.status>=200&&n.status<300||304===n.status))throw new Error("Couldn't load "+r+". Status: "+n.status);return void 0!==n.response?new Uint8Array(n.response||[]):cr(n.responseText||"",!0)})(t,n)),void 0===a.chunks[e])throw new Error("doXHR failed!");return a.chunks[e]})),!s&&i||(o=i=1,i=this.getter(0).length,o=i,y("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=i,this._chunkSize=o,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!g)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var o=new s;Object.defineProperties(o,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var a={isDevice:!1,contents:o}}else a={isDevice:!1,url:r};var c=xe.createFile(e,t,a,i,n);a.contents?c.contents=a.contents:a.url&&(c.contents=null,c.url=a.url),Object.defineProperties(c,{usedBytes:{get:function(){return this.contents.length}}});var h={};function l(e,t,r,i,n){var s=e.node.contents;if(n>=s.length)return 0;var o=Math.min(s.length-n,i);if(s.slice)for(var a=0;a{var t=c.stream_ops[e];h[e]=function(){return xe.forceLoadFile(c),t.apply(null,arguments)}})),h.read=(e,t,r,i,n)=>(xe.forceLoadFile(c),l(e,t,r,i,n)),h.mmap=(e,t,r,i,n)=>{xe.forceLoadFile(c);var s=Ee(t);if(!s)throw new xe.ErrnoError(48);return l(e,L,s,t,r),{ptr:s,allocated:!0}},c.stream_ops=h,c},createPreloadedFile:(e,t,r,i,n,o,a,c,h,l)=>{var u=t?be.resolve(Se.join2(e,t)):e;function d(r){function s(r){l&&l(),c||xe.createDataFile(e,t,r,i,n,h),o&&o(),oe()}Nt.handledByPreloadPlugin(r,u,s,(()=>{a&&a(),oe()}))||s(r)}se(),"string"==typeof r?function(e,t,r,i){var n="al "+e;s(e,(function(t){P(t,'Loading data file "'+e+'" failed (no arrayBuffer).'),d(new Uint8Array(t)),n&&oe()}),(function(t){if(!r)throw'Loading data file "'+e+'" failed.';r()})),n&&se()}(r,0,a):d(r)},indexedDB:()=>window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,DB_NAME:()=>"EM_FS_"+window.location.pathname,DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:(e,t,r)=>{t=t||(()=>{}),r=r||(()=>{});var i=xe.indexedDB();try{var n=i.open(xe.DB_NAME(),xe.DB_VERSION)}catch(e){return r(e)}n.onupgradeneeded=()=>{y("creating db"),n.result.createObjectStore(xe.DB_STORE_NAME)},n.onsuccess=()=>{var i=n.result.transaction([xe.DB_STORE_NAME],"readwrite"),s=i.objectStore(xe.DB_STORE_NAME),o=0,a=0,c=e.length;function h(){0==a?t():r()}e.forEach((e=>{var t=s.put(xe.analyzePath(e).object.contents,e);t.onsuccess=()=>{++o+a==c&&h()},t.onerror=()=>{a++,o+a==c&&h()}})),i.onerror=r},n.onerror=r},loadFilesFromDB:(e,t,r)=>{t=t||(()=>{}),r=r||(()=>{});var i=xe.indexedDB();try{var n=i.open(xe.DB_NAME(),xe.DB_VERSION)}catch(e){return r(e)}n.onupgradeneeded=r,n.onsuccess=()=>{var i=n.result;try{var s=i.transaction([xe.DB_STORE_NAME],"readonly")}catch(e){return void r(e)}var o=s.objectStore(xe.DB_STORE_NAME),a=0,c=0,h=e.length;function l(){0==c?t():r()}e.forEach((e=>{var t=o.get(e);t.onsuccess=()=>{xe.analyzePath(e).exists&&xe.unlink(e),xe.createDataFile(Se.dirname(e),Se.basename(e),t.result,!0,!0,!0),++a+c==h&&l()},t.onerror=()=>{c++,a+c==h&&l()}})),s.onerror=r},n.onerror=r}},ke={DEFAULT_POLLMASK:5,calculateAt:function(e,t,r){if(Se.isAbs(t))return t;var i;if(-100===e)i=xe.cwd();else{var n=xe.getStream(e);if(!n)throw new xe.ErrnoError(8);i=n.path}if(0==t.length){if(!r)throw new xe.ErrnoError(44);return i}return Se.join2(i,t)},doStat:function(e,t,r){try{var i=e(t)}catch(e){if(e&&e.node&&Se.normalize(t)!==Se.normalize(xe.getPath(e.node)))return-54;throw e}return U[r>>>2]=i.dev,U[r+4>>>2]=0,U[r+8>>>2]=i.ino,U[r+12>>>2]=i.mode,U[r+16>>>2]=i.nlink,U[r+20>>>2]=i.uid,U[r+24>>>2]=i.gid,U[r+28>>>2]=i.rdev,U[r+32>>>2]=0,ue=[i.size>>>0,(le=i.size,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[r+40>>>2]=ue[0],U[r+44>>>2]=ue[1],U[r+48>>>2]=4096,U[r+52>>>2]=i.blocks,U[r+56>>>2]=i.atime.getTime()/1e3|0,U[r+60>>>2]=0,U[r+64>>>2]=i.mtime.getTime()/1e3|0,U[r+68>>>2]=0,U[r+72>>>2]=i.ctime.getTime()/1e3|0,U[r+76>>>2]=0,ue=[i.ino>>>0,(le=i.ino,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[r+80>>>2]=ue[0],U[r+84>>>2]=ue[1],0},doMsync:function(e,t,r,i,n){var s=B.slice(e,e+r);xe.msync(t,s,n,r,i)},varargs:void 0,get:function(){return ke.varargs+=4,U[ke.varargs-4>>>2]},getStr:function(e){return _(e)},getStreamFromFD:function(e){var t=xe.getStream(e);if(!t)throw new xe.ErrnoError(8);return t}},Pe="To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking";function Ae(e){switch(e){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+e)}}var _e=void 0;function Oe(e){for(var t="",r=e;B[r>>>0];)t+=_e[B[r++>>>0]];return t}var De={},Re={},Fe={},Le=48,Be=57;function Me(e){if(void 0===e)return"_unknown";var t=(e=e.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return t>=Le&&t<=Be?"_"+e:e}function Ie(e,t){return e=Me(e),new Function("body","return function "+e+'() {\n "use strict"; return body.apply(this, arguments);\n};\n')(t)}function Ue(e,t){var r=Ie(t,(function(e){this.name=t,this.message=e;var r=new Error(e).stack;void 0!==r&&(this.stack=this.toString()+"\n"+r.replace(/^Error(:[^\n]*)?\n/,""))}));return r.prototype=Object.create(e.prototype),r.prototype.constructor=r,r.prototype.toString=function(){return void 0===this.message?this.name:this.name+": "+this.message},r}var We=void 0;function Ne(e){throw new We(e)}var Ge=void 0;function He(e){throw new Ge(e)}function Ve(e,t,r){function i(t){var i=r(t);i.length!==e.length&&He("Mismatched type converter count");for(var n=0;n{Re.hasOwnProperty(e)?n[t]=Re[e]:(s.push(e),De.hasOwnProperty(e)||(De[e]=[]),De[e].push((()=>{n[t]=Re[e],++o===s.length&&i(n)})))})),0===s.length&&i(n)}function ze(e,t,r={}){if(!("argPackAdvance"in t))throw new TypeError("registerType registeredInstance requires argPackAdvance");var i=t.name;if(e||Ne('type "'+i+'" must have a positive integer typeid pointer'),Re.hasOwnProperty(e)){if(r.ignoreDuplicateRegistrations)return;Ne("Cannot register type '"+i+"' twice")}if(Re[e]=t,delete Fe[e],De.hasOwnProperty(e)){var n=De[e];delete De[e],n.forEach((e=>e()))}}function je(e){Ne(e.$$.ptrType.registeredClass.name+" instance already deleted")}var qe=!1;function $e(e){}function Ye(e){e.count.value-=1,0===e.count.value&&function(e){e.smartPtr?e.smartPtrType.rawDestructor(e.smartPtr):e.ptrType.registeredClass.rawDestructor(e.ptr)}(e)}function Xe(e,t,r){if(t===r)return e;if(void 0===r.baseClass)return null;var i=Xe(e,t,r.baseClass);return null===i?null:r.downcast(i)}var Ze={};var Je=[];function Qe(){for(;Je.length;){var e=Je.pop();e.$$.deleteScheduled=!1,e.delete()}}var Ke=void 0;var et={};function tt(e,t){return t.ptrType&&t.ptr||He("makeClassHandle requires ptr and ptrType"),!!t.smartPtrType!=!!t.smartPtr&&He("Both smartPtrType and smartPtr must be specified"),t.count={value:1},rt(Object.create(e,{$$:{value:t}}))}function rt(e){return"undefined"==typeof FinalizationRegistry?(rt=e=>e,e):(qe=new FinalizationRegistry((e=>{Ye(e.$$)})),rt=e=>{var t=e.$$;if(t.smartPtr){var r={$$:t};qe.register(e,r,e)}return e},$e=e=>qe.unregister(e),rt(e))}function it(){}function nt(e,t,r){if(void 0===e[t].overloadTable){var i=e[t];e[t]=function(){return e[t].overloadTable.hasOwnProperty(arguments.length)||Ne("Function '"+r+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+e[t].overloadTable+")!"),e[t].overloadTable[arguments.length].apply(this,arguments)},e[t].overloadTable=[],e[t].overloadTable[i.argCount]=i}}function st(t,r,i){e.hasOwnProperty(t)?((void 0===i||void 0!==e[t].overloadTable&&void 0!==e[t].overloadTable[i])&&Ne("Cannot register public name '"+t+"' twice"),nt(e,t,t),e.hasOwnProperty(i)&&Ne("Cannot register multiple overloads of a function with the same number of arguments ("+i+")!"),e[t].overloadTable[i]=r):(e[t]=r,void 0!==i&&(e[t].numArguments=i))}function ot(e,t,r,i,n,s,o,a){this.name=e,this.constructor=t,this.instancePrototype=r,this.rawDestructor=i,this.baseClass=n,this.getActualType=s,this.upcast=o,this.downcast=a,this.pureVirtualFunctions=[]}function at(e,t,r){for(;t!==r;)t.upcast||Ne("Expected null or instance of "+r.name+", got an instance of "+t.name),e=t.upcast(e),t=t.baseClass;return e}function ct(e,t){if(null===t)return this.isReference&&Ne("null is not a valid "+this.name),0;t.$$||Ne('Cannot pass "'+At(t)+'" as a '+this.name),t.$$.ptr||Ne("Cannot pass deleted object as a pointer of type "+this.name);var r=t.$$.ptrType.registeredClass;return at(t.$$.ptr,r,this.registeredClass)}function ht(e,t){var r;if(null===t)return this.isReference&&Ne("null is not a valid "+this.name),this.isSmartPointer?(r=this.rawConstructor(),null!==e&&e.push(this.rawDestructor,r),r):0;t.$$||Ne('Cannot pass "'+At(t)+'" as a '+this.name),t.$$.ptr||Ne("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&t.$$.ptrType.isConst&&Ne("Cannot convert argument of type "+(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name)+" to parameter type "+this.name);var i=t.$$.ptrType.registeredClass;if(r=at(t.$$.ptr,i,this.registeredClass),this.isSmartPointer)switch(void 0===t.$$.smartPtr&&Ne("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:t.$$.smartPtrType===this?r=t.$$.smartPtr:Ne("Cannot convert argument of type "+(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:r=t.$$.smartPtr;break;case 2:if(t.$$.smartPtrType===this)r=t.$$.smartPtr;else{var n=t.clone();r=this.rawShare(r,kt.toHandle((function(){n.delete()}))),null!==e&&e.push(this.rawDestructor,r)}break;default:Ne("Unsupporting sharing policy")}return r}function lt(e,t){if(null===t)return this.isReference&&Ne("null is not a valid "+this.name),0;t.$$||Ne('Cannot pass "'+At(t)+'" as a '+this.name),t.$$.ptr||Ne("Cannot pass deleted object as a pointer of type "+this.name),t.$$.ptrType.isConst&&Ne("Cannot convert argument of type "+t.$$.ptrType.name+" to parameter type "+this.name);var r=t.$$.ptrType.registeredClass;return at(t.$$.ptr,r,this.registeredClass)}function ut(e){return this.fromWireType(W[e>>>2])}function dt(e,t,r,i,n,s,o,a,c,h,l){this.name=e,this.registeredClass=t,this.isReference=r,this.isConst=i,this.isSmartPointer=n,this.pointeeType=s,this.sharingPolicy=o,this.rawGetPointee=a,this.rawConstructor=c,this.rawShare=h,this.rawDestructor=l,n||void 0!==t.baseClass?this.toWireType=ht:i?(this.toWireType=ct,this.destructorFunction=null):(this.toWireType=lt,this.destructorFunction=null)}function pt(t,r){var i,n,s,o=(t=Oe(t)).includes("j")?(i=t,n=r,s=[],function(){return s.length=0,Object.assign(s,arguments),function(t,r,i){return t.includes("j")?function(t,r,i){var n=e["dynCall_"+t];return i&&i.length?n.apply(null,[r].concat(i)):n.call(null,r)}(t,r,i):me(r).apply(null,i)}(i,n,s)}):me(r);return"function"!=typeof o&&Ne("unknown function pointer with signature "+t+": "+r),o}var ft=void 0;function gt(e){var t=fr(e),r=Oe(t);return dr(t),r}function vt(e,t){var r=[],i={};throw t.forEach((function e(t){i[t]||Re[t]||(Fe[t]?Fe[t].forEach(e):(r.push(t),i[t]=!0))})),new ft(e+": "+r.map(gt).join([", "]))}function mt(e,t){if(!(e instanceof Function))throw new TypeError("new_ called with constructor type "+typeof e+" which is not a function");var r=Ie(e.name||"unknownFunctionName",(function(){}));r.prototype=e.prototype;var i=new r,n=e.apply(i,t);return n instanceof Object?n:i}function yt(e){for(;e.length;){var t=e.pop();e.pop()(t)}}function St(e,t,r,i,n){var s=t.length;s<2&&Ne("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var o=null!==t[1]&&null!==r,a=!1,c=1;c0?", ":"")+u),d+=(h?"var rv = ":"")+"invoker(fn"+(u.length>0?", ":"")+u+");\n",a)d+="runDestructors(destructors);\n";else for(c=o?1:2;c>2)+i>>>0]);return r}function wt(e,t,r){return e instanceof Object||Ne(r+' with invalid "this": '+e),e instanceof t.registeredClass.constructor||Ne(r+' incompatible with "this" of type '+e.constructor.name),e.$$.ptr||Ne("cannot call emscripten binding method "+r+" on deleted object"),at(e.$$.ptr,e.$$.ptrType.registeredClass,t.registeredClass)}var Et=[],Tt=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function xt(e){e>4&&0==--Tt[e].refcount&&(Tt[e]=void 0,Et.push(e))}var kt={toValue:e=>(e||Ne("Cannot use deleted val. handle = "+e),Tt[e].value),toHandle:e=>{switch(e){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:var t=Et.length?Et.pop():Tt.length;return Tt[t]={refcount:1,value:e},t}}};function Pt(e,t,r){switch(t){case 0:return function(e){var t=r?L:B;return this.fromWireType(t[e>>>0])};case 1:return function(e){var t=r?M:I;return this.fromWireType(t[e>>>1])};case 2:return function(e){var t=r?U:W;return this.fromWireType(t[e>>>2])};default:throw new TypeError("Unknown integer type: "+e)}}function Ct(e,t){var r=Re[e];return void 0===r&&Ne(t+" has unknown type "+gt(e)),r}function At(e){if(null===e)return"null";var t=typeof e;return"object"===t||"array"===t||"function"===t?e.toString():""+e}function _t(e,t){switch(t){case 2:return function(e){return this.fromWireType(N[e>>>2])};case 3:return function(e){return this.fromWireType(G[e>>>3])};default:throw new TypeError("Unknown float type: "+e)}}function Ot(e,t,r){switch(t){case 0:return r?function(e){return L[e>>>0]}:function(e){return B[e>>>0]};case 1:return r?function(e){return M[e>>>1]}:function(e){return I[e>>>1]};case 2:return r?function(e){return U[e>>>2]}:function(e){return W[e>>>2]};default:throw new TypeError("Unknown integer type: "+e)}}var Dt={};function Rt(e){var t=Dt[e];return void 0===t?Oe(e):t}var Ft=[];function Lt(){return"object"==typeof globalThis?globalThis:Function("return this")()}var Bt,Mt=[];function It(t,r){if(Nt.mainLoop.timingMode=t,Nt.mainLoop.timingValue=r,!Nt.mainLoop.func)return 1;if(Nt.mainLoop.running||(Nt.mainLoop.running=!0),0==t)Nt.mainLoop.scheduler=function(){var e=0|Math.max(0,Nt.mainLoop.tickStartTime+r-Bt());setTimeout(Nt.mainLoop.runner,e)},Nt.mainLoop.method="timeout";else if(1==t)Nt.mainLoop.scheduler=function(){Nt.requestAnimationFrame(Nt.mainLoop.runner)},Nt.mainLoop.method="rAF";else if(2==t){if("undefined"==typeof setImmediate){var i=[],n="setimmediate";addEventListener("message",(function(e){e.data!==n&&e.data.target!==n||(e.stopPropagation(),i.shift()())}),!0),setImmediate=function(t){i.push(t),g?(void 0===e.setImmediates&&(e.setImmediates=[]),e.setImmediates.push(t),postMessage({target:n})):postMessage(n,"*")}}Nt.mainLoop.scheduler=function(){setImmediate(Nt.mainLoop.runner)},Nt.mainLoop.method="immediate"}return 0}function Ut(e,t){if(!k)if(t)e();else try{e()}catch(e){!function(e){if(e instanceof yr||"unwind"==e)return x;p(1,e)}(e)}}function Wt(e,t){return setTimeout((function(){Ut(e)}),t)}Bt=v?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.now();var Nt={mainLoop:{running:!1,scheduler:null,method:"",currentlyRunningMainloop:0,func:null,arg:0,timingMode:0,timingValue:0,currentFrameNumber:0,queue:[],pause:function(){Nt.mainLoop.scheduler=null,Nt.mainLoop.currentlyRunningMainloop++},resume:function(){Nt.mainLoop.currentlyRunningMainloop++;var e=Nt.mainLoop.timingMode,t=Nt.mainLoop.timingValue,r=Nt.mainLoop.func;Nt.mainLoop.func=null,function(e,t,r,i,n){P(!Nt.mainLoop.func,"emscripten_set_main_loop: there can only be one main loop function at once: call emscripten_cancel_main_loop to cancel the previous one before setting a new one with different parameters."),Nt.mainLoop.func=e,Nt.mainLoop.arg=i;var s=Nt.mainLoop.currentlyRunningMainloop;function o(){return!(s0){var t=Date.now(),r=Nt.mainLoop.queue.shift();if(r.func(r.arg),Nt.mainLoop.remainingBlockers){var i=Nt.mainLoop.remainingBlockers,n=i%1==0?i-1:Math.floor(i);r.counted?Nt.mainLoop.remainingBlockers=n:(n+=.5,Nt.mainLoop.remainingBlockers=(8*i+n)/9)}if(y('main loop blocker "'+r.name+'" took '+(Date.now()-t)+" ms"),Nt.mainLoop.updateStatus(),!o())return;setTimeout(Nt.mainLoop.runner,0)}else o()&&(Nt.mainLoop.currentFrameNumber=Nt.mainLoop.currentFrameNumber+1|0,1==Nt.mainLoop.timingMode&&Nt.mainLoop.timingValue>1&&Nt.mainLoop.currentFrameNumber%Nt.mainLoop.timingValue!=0?Nt.mainLoop.scheduler():(0==Nt.mainLoop.timingMode&&(Nt.mainLoop.tickStartTime=Bt()),Nt.mainLoop.runIter(e),o()&&("object"==typeof SDL&&SDL.audio&&SDL.audio.queueNewAudioData&&SDL.audio.queueNewAudioData(),Nt.mainLoop.scheduler())))}}(r,0,0,Nt.mainLoop.arg),It(e,t),Nt.mainLoop.scheduler()},updateStatus:function(){if(e.setStatus){var t=e.statusMessage||"Please wait...",r=Nt.mainLoop.remainingBlockers,i=Nt.mainLoop.expectedBlockers;r?r{P(a.complete,"Image "+t+" could not be decoded");var i=document.createElement("canvas");i.width=a.width,i.height=a.height,i.getContext("2d").drawImage(a,0,0),ir[t]=i,Nt.URLObject.revokeObjectURL(o),r&&r(e)},a.onerror=e=>{y("Image "+o+" could not be decoded"),i&&i()},a.src=o}};e.preloadPlugins.push(t);var r={canHandle:function(t){return!e.noAudioDecoding&&t.substr(-4)in{".ogg":1,".wav":1,".mp3":1}},handle:function(e,t,r,i){var n=!1;function s(i){n||(n=!0,nr[t]=i,r&&r(e))}function o(){n||(n=!0,nr[t]=new Audio,i&&i())}if(!Nt.hasBlobConstructor)return o();try{var a=new Blob([e],{type:Nt.getMimetype(t)})}catch(e){return o()}var c=Nt.URLObject.createObjectURL(a),h=new Audio;h.addEventListener("canplaythrough",(function(){s(h)}),!1),h.onerror=function(r){n||(y("warning: browser could not fully decode audio "+t+", trying slower base64 approach"),h.src="data:audio/x-"+t.substr(-3)+";base64,"+function(e){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r="",i=0,n=0,s=0;s=6;){var o=i>>n-6&63;n-=6,r+=t[o]}return 2==n?(r+=t[(3&i)<<4],r+="=="):4==n&&(r+=t[(15&i)<<2],r+="="),r}(e),s(h))},h.src=c,Wt((function(){s(h)}),1e4)}};e.preloadPlugins.push(r);var i=e.canvas;i&&(i.requestPointerLock=i.requestPointerLock||i.mozRequestPointerLock||i.webkitRequestPointerLock||i.msRequestPointerLock||function(){},i.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock||document.msExitPointerLock||function(){},i.exitPointerLock=i.exitPointerLock.bind(document),document.addEventListener("pointerlockchange",n,!1),document.addEventListener("mozpointerlockchange",n,!1),document.addEventListener("webkitpointerlockchange",n,!1),document.addEventListener("mspointerlockchange",n,!1),e.elementPointerLock&&i.addEventListener("click",(function(t){!Nt.pointerLock&&e.canvas.requestPointerLock&&(e.canvas.requestPointerLock(),t.preventDefault())}),!1))}function n(){Nt.pointerLock=document.pointerLockElement===e.canvas||document.mozPointerLockElement===e.canvas||document.webkitPointerLockElement===e.canvas||document.msPointerLockElement===e.canvas}},handledByPreloadPlugin:function(t,r,i,n){Nt.init();var s=!1;return e.preloadPlugins.forEach((function(e){s||e.canHandle(r)&&(e.handle(t,r,i,n),s=!0)})),s},createContext:function(t,r,i,n){if(r&&e.ctx&&t==e.canvas)return e.ctx;var s,o;if(r){var a={antialias:!1,alpha:!1,majorVersion:1};if(n)for(var c in n)a[c]=n[c];void 0!==$t&&(o=$t.createContext(t,a))&&(s=$t.getContext(o).GLctx)}else s=t.getContext("2d");return s?(i&&(r||P(void 0===rr,"cannot set in module if GLctx is used, but we are a non-GL context that would replace it"),e.ctx=s,r&&$t.makeContextCurrent(o),e.useWebGL=r,Nt.moduleContextCreatedCallbacks.forEach((function(e){e()})),Nt.init()),s):null},destroyContext:function(e,t,r){},fullscreenHandlersInstalled:!1,lockPointer:void 0,resizeCanvas:void 0,requestFullscreen:function(t,r){Nt.lockPointer=t,Nt.resizeCanvas=r,void 0===Nt.lockPointer&&(Nt.lockPointer=!0),void 0===Nt.resizeCanvas&&(Nt.resizeCanvas=!1);var i=e.canvas;function n(){Nt.isFullscreen=!1;var t=i.parentNode;(document.fullscreenElement||document.mozFullScreenElement||document.msFullscreenElement||document.webkitFullscreenElement||document.webkitCurrentFullScreenElement)===t?(i.exitFullscreen=Nt.exitFullscreen,Nt.lockPointer&&i.requestPointerLock(),Nt.isFullscreen=!0,Nt.resizeCanvas?Nt.setFullscreenCanvasSize():Nt.updateCanvasDimensions(i)):(t.parentNode.insertBefore(i,t),t.parentNode.removeChild(t),Nt.resizeCanvas?Nt.setWindowedCanvasSize():Nt.updateCanvasDimensions(i)),e.onFullScreen&&e.onFullScreen(Nt.isFullscreen),e.onFullscreen&&e.onFullscreen(Nt.isFullscreen)}Nt.fullscreenHandlersInstalled||(Nt.fullscreenHandlersInstalled=!0,document.addEventListener("fullscreenchange",n,!1),document.addEventListener("mozfullscreenchange",n,!1),document.addEventListener("webkitfullscreenchange",n,!1),document.addEventListener("MSFullscreenChange",n,!1));var s=document.createElement("div");i.parentNode.insertBefore(s,i),s.appendChild(i),s.requestFullscreen=s.requestFullscreen||s.mozRequestFullScreen||s.msRequestFullscreen||(s.webkitRequestFullscreen?function(){s.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT)}:null)||(s.webkitRequestFullScreen?function(){s.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT)}:null),s.requestFullscreen()},exitFullscreen:function(){return!!Nt.isFullscreen&&((document.exitFullscreen||document.cancelFullScreen||document.mozCancelFullScreen||document.msExitFullscreen||document.webkitCancelFullScreen||function(){}).apply(document,[]),!0)},nextRAF:0,fakeRequestAnimationFrame:function(e){var t=Date.now();if(0===Nt.nextRAF)Nt.nextRAF=t+1e3/60;else for(;t+2>=Nt.nextRAF;)Nt.nextRAF+=1e3/60;var r=Math.max(Nt.nextRAF-t,0);setTimeout(e,r)},requestAnimationFrame:function(e){"function"!=typeof requestAnimationFrame?(0,Nt.fakeRequestAnimationFrame)(e):requestAnimationFrame(e)},safeSetTimeout:function(e){return Wt(e)},safeRequestAnimationFrame:function(e){return Nt.requestAnimationFrame((function(){Ut(e)}))},getMimetype:function(e){return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",bmp:"image/bmp",ogg:"audio/ogg",wav:"audio/wav",mp3:"audio/mpeg"}[e.substr(e.lastIndexOf(".")+1)]},getUserMedia:function(e){window.getUserMedia||(window.getUserMedia=navigator.getUserMedia||navigator.mozGetUserMedia),window.getUserMedia(e)},getMovementX:function(e){return e.movementX||e.mozMovementX||e.webkitMovementX||0},getMovementY:function(e){return e.movementY||e.mozMovementY||e.webkitMovementY||0},getMouseWheelDelta:function(e){var t=0;switch(e.type){case"DOMMouseScroll":t=e.detail/3;break;case"mousewheel":t=e.wheelDelta/120;break;case"wheel":switch(t=e.deltaY,e.deltaMode){case 0:t/=100;break;case 1:t/=3;break;case 2:t*=80;break;default:throw"unrecognized mouse wheel delta mode: "+e.deltaMode}break;default:throw"unrecognized mouse wheel event: "+e.type}return t},mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,touches:{},lastTouches:{},calculateMouseEvent:function(t){if(Nt.pointerLock)"mousemove"!=t.type&&"mozMovementX"in t?Nt.mouseMovementX=Nt.mouseMovementY=0:(Nt.mouseMovementX=Nt.getMovementX(t),Nt.mouseMovementY=Nt.getMovementY(t)),"undefined"!=typeof SDL?(Nt.mouseX=SDL.mouseX+Nt.mouseMovementX,Nt.mouseY=SDL.mouseY+Nt.mouseMovementY):(Nt.mouseX+=Nt.mouseMovementX,Nt.mouseY+=Nt.mouseMovementY);else{var r=e.canvas.getBoundingClientRect(),i=e.canvas.width,n=e.canvas.height,s=void 0!==window.scrollX?window.scrollX:window.pageXOffset,o=void 0!==window.scrollY?window.scrollY:window.pageYOffset;if("touchstart"===t.type||"touchend"===t.type||"touchmove"===t.type){var a=t.touch;if(void 0===a)return;var c=a.pageX-(s+r.left),h=a.pageY-(o+r.top),l={x:c*=i/r.width,y:h*=n/r.height};if("touchstart"===t.type)Nt.lastTouches[a.identifier]=l,Nt.touches[a.identifier]=l;else if("touchend"===t.type||"touchmove"===t.type){var u=Nt.touches[a.identifier];u||(u=l),Nt.lastTouches[a.identifier]=u,Nt.touches[a.identifier]=l}return}var d=t.pageX-(s+r.left),p=t.pageY-(o+r.top);d*=i/r.width,p*=n/r.height,Nt.mouseMovementX=d-Nt.mouseX,Nt.mouseMovementY=p-Nt.mouseY,Nt.mouseX=d,Nt.mouseY=p}},resizeListeners:[],updateResizeListeners:function(){var t=e.canvas;Nt.resizeListeners.forEach((function(e){e(t.width,t.height)}))},setCanvasSize:function(t,r,i){var n=e.canvas;Nt.updateCanvasDimensions(n,t,r),i||Nt.updateResizeListeners()},windowedWidth:0,windowedHeight:0,setFullscreenCanvasSize:function(){if("undefined"!=typeof SDL){var t=W[SDL.screen>>>2];t|=8388608,U[SDL.screen>>>2]=t}Nt.updateCanvasDimensions(e.canvas),Nt.updateResizeListeners()},setWindowedCanvasSize:function(){if("undefined"!=typeof SDL){var t=W[SDL.screen>>>2];t&=-8388609,U[SDL.screen>>>2]=t}Nt.updateCanvasDimensions(e.canvas),Nt.updateResizeListeners()},updateCanvasDimensions:function(t,r,i){r&&i?(t.widthNative=r,t.heightNative=i):(r=t.widthNative,i=t.heightNative);var n=r,s=i;if(e.forcedAspectRatio&&e.forcedAspectRatio>0&&(n/s>>16),Z(E.buffer),1}catch(e){}}var Ht={};function Vt(){if(!Vt.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:d||"./this.program"};for(var t in Ht)void 0===Ht[t]?delete e[t]:e[t]=Ht[t];var r=[];for(var t in e)r.push(t+"="+e[t]);Vt.strings=r}return Vt.strings}function zt(e){for(var t=e.split("."),r=0;r<4;r++){var i=Number(t[r]);if(isNaN(i))return null;t[r]=i}return(t[0]|t[1]<<8|t[2]<<16|t[3]<<24)>>>0}function jt(e){return parseInt(e)}var qt={address_map:{id:1,addrs:{},names:{}},lookup_name:function(e){var t,r=zt(e);if(null!==r)return e;if(null!==(r=function(e){var t,r,i,n,s=[];if(!/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i.test(e))return null;if("::"===e)return[0,0,0,0,0,0,0,0];for((e=e.startsWith("::")?e.replace("::","Z:"):e.replace("::",":Z:")).indexOf(".")>0?((t=(e=e.replace(new RegExp("[.]","g"),":")).split(":"))[t.length-4]=jt(t[t.length-4])+256*jt(t[t.length-3]),t[t.length-3]=jt(t[t.length-2])+256*jt(t[t.length-1]),t=t.slice(0,t.length-2)):t=e.split(":"),i=0,n=0,r=0;r>>2]:-1;n+=_(U[r+4*s>>>2],o<0?void 0:o)}return n},createContext:function(e,t){if(!e.getContextSafariWebGL2Fixed){function i(t,r){var i=e.getContextSafariWebGL2Fixed(t,r);return"webgl"==t==i instanceof WebGLRenderingContext?i:null}e.getContextSafariWebGL2Fixed=e.getContext,e.getContext=i}var r=e.getContext("webgl",t);return r?$t.registerContext(r,t):0},registerContext:function(e,t){var r=$t.getNewId($t.contexts),i={handle:r,attributes:t,version:t.majorVersion,GLctx:e};return e.canvas&&(e.canvas.GLctxObject=i),$t.contexts[r]=i,(void 0===t.enableExtensionsByDefault||t.enableExtensionsByDefault)&&$t.initExtensions(i),r},makeContextCurrent:function(t){return $t.currentContext=$t.contexts[t],e.ctx=rr=$t.currentContext&&$t.currentContext.GLctx,!(t&&!rr)},getContext:function(e){return $t.contexts[e]},deleteContext:function(e){$t.currentContext===$t.contexts[e]&&($t.currentContext=null),"object"==typeof JSEvents&&JSEvents.removeAllHandlersOnTarget($t.contexts[e].GLctx.canvas),$t.contexts[e]&&$t.contexts[e].GLctx.canvas&&($t.contexts[e].GLctx.canvas.GLctxObject=void 0),$t.contexts[e]=null},initExtensions:function(e){if(e||(e=$t.currentContext),!e.initExtensionsDone){e.initExtensionsDone=!0;var t,r=e.GLctx;!function(e){var t=e.getExtension("ANGLE_instanced_arrays");t&&(e.vertexAttribDivisor=function(e,r){t.vertexAttribDivisorANGLE(e,r)},e.drawArraysInstanced=function(e,r,i,n){t.drawArraysInstancedANGLE(e,r,i,n)},e.drawElementsInstanced=function(e,r,i,n,s){t.drawElementsInstancedANGLE(e,r,i,n,s)})}(r),function(e){var t=e.getExtension("OES_vertex_array_object");t&&(e.createVertexArray=function(){return t.createVertexArrayOES()},e.deleteVertexArray=function(e){t.deleteVertexArrayOES(e)},e.bindVertexArray=function(e){t.bindVertexArrayOES(e)},e.isVertexArray=function(e){return t.isVertexArrayOES(e)})}(r),function(e){var t=e.getExtension("WEBGL_draw_buffers");t&&(e.drawBuffers=function(e,r){t.drawBuffersWEBGL(e,r)})}(r),r.disjointTimerQueryExt=r.getExtension("EXT_disjoint_timer_query"),(t=r).multiDrawWebgl=t.getExtension("WEBGL_multi_draw"),(r.getSupportedExtensions()||[]).forEach((function(e){e.includes("lose_context")||e.includes("debug")||r.getExtension(e)}))}}};function Yt(e){return"]"==e.slice(-1)&&e.lastIndexOf("[")}function Xt(e){var t=rr.currentProgram;if(t){var r=t.uniformLocsById[e];return"number"==typeof r&&(t.uniformLocsById[e]=r=rr.getUniformLocation(t,t.uniformArrayNamesById[e]+(r>0?"["+r+"]":""))),r}$t.recordError(1282)}var Zt=[],Jt=[];function Qt(e){return e%4==0&&(e%100!=0||e%400==0)}var Kt=[31,29,31,30,31,30,31,31,30,31,30,31],er=[31,28,31,30,31,30,31,31,30,31,30,31];var tr=function(e,t,r,i){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=xe.nextInode++,this.name=t,this.mode=r,this.node_ops={},this.stream_ops={},this.rdev=i};Object.defineProperties(tr.prototype,{read:{get:function(){return!(365&~this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return!(146&~this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}},isFolder:{get:function(){return xe.isDir(this.mode)}},isDevice:{get:function(){return xe.isChrdev(this.mode)}}}),xe.FSNode=tr,xe.staticInit(),function(){for(var e=new Array(256),t=0;t<256;++t)e[t]=String.fromCharCode(t);_e=e}(),We=e.BindingError=Ue(Error,"BindingError"),Ge=e.InternalError=Ue(Error,"InternalError"),it.prototype.isAliasOf=function(e){if(!(this instanceof it))return!1;if(!(e instanceof it))return!1;for(var t=this.$$.ptrType.registeredClass,r=this.$$.ptr,i=e.$$.ptrType.registeredClass,n=e.$$.ptr;t.baseClass;)r=t.upcast(r),t=t.baseClass;for(;i.baseClass;)n=i.upcast(n),i=i.baseClass;return t===i&&r===n},it.prototype.clone=function(){if(this.$$.ptr||je(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var e,t=rt(Object.create(Object.getPrototypeOf(this),{$$:{value:(e=this.$$,{count:e.count,deleteScheduled:e.deleteScheduled,preservePointerOnDelete:e.preservePointerOnDelete,ptr:e.ptr,ptrType:e.ptrType,smartPtr:e.smartPtr,smartPtrType:e.smartPtrType})}}));return t.$$.count.value+=1,t.$$.deleteScheduled=!1,t},it.prototype.delete=function(){this.$$.ptr||je(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ne("Object already scheduled for deletion"),$e(this),Ye(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},it.prototype.isDeleted=function(){return!this.$$.ptr},it.prototype.deleteLater=function(){return this.$$.ptr||je(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ne("Object already scheduled for deletion"),Je.push(this),1===Je.length&&Ke&&Ke(Qe),this.$$.deleteScheduled=!0,this},e.getInheritedInstanceCount=function(){return Object.keys(et).length},e.getLiveInheritedInstances=function(){var e=[];for(var t in et)et.hasOwnProperty(t)&&e.push(et[t]);return e},e.flushPendingDeletes=Qe,e.setDelayFunction=function(e){Ke=e,Je.length&&Ke&&Ke(Qe)},dt.prototype.getPointee=function(e){return this.rawGetPointee&&(e=this.rawGetPointee(e)),e},dt.prototype.destructor=function(e){this.rawDestructor&&this.rawDestructor(e)},dt.prototype.argPackAdvance=8,dt.prototype.readValueFromPointer=ut,dt.prototype.deleteObject=function(e){null!==e&&e.delete()},dt.prototype.fromWireType=function(e){var t=this.getPointee(e);if(!t)return this.destructor(e),null;var r=function(e,t){return t=function(e,t){for(void 0===t&&Ne("ptr should not be undefined");e.baseClass;)t=e.upcast(t),e=e.baseClass;return t}(e,t),et[t]}(this.registeredClass,t);if(void 0!==r){if(0===r.$$.count.value)return r.$$.ptr=t,r.$$.smartPtr=e,r.clone();var i=r.clone();return this.destructor(e),i}function n(){return this.isSmartPointer?tt(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:t,smartPtrType:this,smartPtr:e}):tt(this.registeredClass.instancePrototype,{ptrType:this,ptr:e})}var s,o=this.registeredClass.getActualType(t),a=Ze[o];if(!a)return n.call(this);s=this.isConst?a.constPointerType:a.pointerType;var c=Xe(t,this.registeredClass,s.registeredClass);return null===c?n.call(this):this.isSmartPointer?tt(s.registeredClass.instancePrototype,{ptrType:s,ptr:c,smartPtrType:this,smartPtr:e}):tt(s.registeredClass.instancePrototype,{ptrType:s,ptr:c})},ft=e.UnboundTypeError=Ue(Error,"UnboundTypeError"),e.count_emval_handles=function(){for(var e=0,t=5;t0?r:R(e)+1,n=new Array(i),s=O(e,n,0,n.length);return t&&(n.length=s),n}var hr,lr={na:function(){return e.HEAP8.length},g:function(e,t,r,i){ae("Assertion failed: "+_(e)+", at: "+[t?_(t):"unknown filename",r,i?_(i):"unknown function"])},b:function(e){return ur(e+24)+24},c:function(e,t,r){throw new ye(e).init(t,r),e},Z:function(e,t){try{return e=ke.getStr(e),xe.chmod(e,t),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},_:function(e,t,r,i){try{if(t=ke.getStr(t),t=ke.calculateAt(e,t),-8&r)return-28;var n=xe.lookupPath(t,{follow:!0}).node;if(!n)return-44;var s="";return 4&r&&(s+="r"),2&r&&(s+="w"),1&r&&(s+="x"),s&&xe.nodePermissions(n,s)?-2:0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},r:function(e,t,r){ke.varargs=r;try{var i=ke.getStreamFromFD(e);switch(t){case 0:return(n=ke.get())<0?-28:xe.createStream(i,n).fd;case 1:case 2:case 6:case 7:return 0;case 3:return i.flags;case 4:var n=ke.get();return i.flags|=n,0;case 5:return n=ke.get(),M[n+0>>>1]=2,0;case 16:case 8:default:return-28;case 9:return 28,U[pr()>>>2]=28,-1}}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},Q:function(e,t){try{var r=ke.getStreamFromFD(e);return ke.doStat(xe.stat,r.path,t)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},I:function(e,t,r){try{var i=ke.getStreamFromFD(e);i.getdents||(i.getdents=xe.readdir(i.path));for(var n=280,s=0,o=xe.llseek(i,0,1),a=Math.floor(o/n);a>>0,(le=c,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[t+s>>>2]=ue[0],U[t+s+4>>>2]=ue[1],ue=[(a+1)*n>>>0,(le=(a+1)*n,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[t+s+8>>>2]=ue[0],U[t+s+12>>>2]=ue[1],M[t+s+16>>>1]=280,L[t+s+18>>>0]=h,D(l,t+s+19,256),s+=n,a+=1}return xe.llseek(i,a*n,0),s}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},$:function(e,t,r){ke.varargs=r;try{var i=ke.getStreamFromFD(e);switch(t){case 21509:case 21505:case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:case 21523:case 21524:return i.tty?0:-59;case 21519:if(!i.tty)return-59;var n=ke.get();return U[n>>>2]=0,0;case 21520:return i.tty?-28:-59;case 21531:return n=ke.get(),xe.ioctl(i,t,n);default:ae("bad ioctl syscall "+t)}}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},N:function(e,t){try{return e=ke.getStr(e),ke.doStat(xe.lstat,e,t)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},K:function(e,t,r){try{return t=ke.getStr(t),t=ke.calculateAt(e,t),"/"===(t=Se.normalize(t))[t.length-1]&&(t=t.substr(0,t.length-1)),xe.mkdir(t,r,0),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},O:function(e,t,r,i){try{t=ke.getStr(t);var n=256&i,s=4096&i;return i&=-4353,t=ke.calculateAt(e,t,s),ke.doStat(n?xe.lstat:xe.stat,t,r)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},v:function(e,t,r,i){ke.varargs=i;try{t=ke.getStr(t),t=ke.calculateAt(e,t);var n=i?ke.get():0;return xe.open(t,r,n).fd}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},H:function(e){try{return e=ke.getStr(e),xe.rmdir(e),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},P:function(e,t){try{return e=ke.getStr(e),ke.doStat(xe.stat,e,t)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},F:function(e,t,r){try{return t=ke.getStr(t),t=ke.calculateAt(e,t),0===r?xe.unlink(t):512===r?xe.rmdir(t):ae("Invalid flags passed to unlinkat"),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},W:function(e){},Y:function(e,t){ae(Pe)},X:function(e,t){ae(Pe)},B:function(e,t,r,i,n){},ba:function(e,t,r,i,n){var s=Ae(r);ze(e,{name:t=Oe(t),fromWireType:function(e){return!!e},toWireType:function(e,t){return t?i:n},argPackAdvance:8,readValueFromPointer:function(e){var i;if(1===r)i=L;else if(2===r)i=M;else{if(4!==r)throw new TypeError("Unknown boolean type size: "+t);i=U}return this.fromWireType(i[e>>>s])},destructorFunction:null})},d:function(t,r,i,n,s,o,a,c,h,l,u,d,p){u=Oe(u),o=pt(s,o),c&&(c=pt(a,c)),l&&(l=pt(h,l)),p=pt(d,p);var f=Me(u);st(f,(function(){vt("Cannot construct "+u+" due to unbound types",[n])})),Ve([t,r,i],n?[n]:[],(function(r){var i,s;r=r[0],s=n?(i=r.registeredClass).instancePrototype:it.prototype;var a=Ie(f,(function(){if(Object.getPrototypeOf(this)!==h)throw new We("Use 'new' to construct "+u);if(void 0===d.constructor_body)throw new We(u+" has no accessible constructor");var e=d.constructor_body[arguments.length];if(void 0===e)throw new We("Tried to invoke ctor of "+u+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(d.constructor_body).toString()+") parameters instead!");return e.apply(this,arguments)})),h=Object.create(s,{constructor:{value:a}});a.prototype=h;var d=new ot(u,a,h,p,i,o,c,l),g=new dt(u,d,!0,!1,!1),v=new dt(u+"*",d,!1,!1,!1),m=new dt(u+" const*",d,!1,!0,!1);return Ze[t]={pointerType:v,constPointerType:m},function(t,r,i){e.hasOwnProperty(t)||He("Replacing nonexistant public symbol"),e[t].overloadTable,e[t]=r,e[t].argCount=i}(f,a),[g,v,m]}))},f:function(e,t,r,i,n,s,o){var a=bt(r,i);t=Oe(t),s=pt(n,s),Ve([],[e],(function(e){var i=(e=e[0]).name+"."+t;function n(){vt("Cannot call "+i+" due to unbound types",a)}t.startsWith("@@")&&(t=Symbol[t.substring(2)]);var c=e.registeredClass.constructor;return void 0===c[t]?(n.argCount=r-1,c[t]=n):(nt(c,t,i),c[t].overloadTable[r-1]=n),Ve([],a,(function(e){var n=[e[0],null].concat(e.slice(1)),a=St(i,n,null,s,o);return void 0===c[t].overloadTable?(a.argCount=r-1,c[t]=a):c[t].overloadTable[r-1]=a,[]})),[]}))},e:function(e,t,r,i,n,s){P(t>0);var o=bt(t,r);n=pt(i,n),Ve([],[e],(function(e){var r="constructor "+(e=e[0]).name;if(void 0===e.registeredClass.constructor_body&&(e.registeredClass.constructor_body=[]),void 0!==e.registeredClass.constructor_body[t-1])throw new We("Cannot register multiple constructors with identical number of parameters ("+(t-1)+") for class '"+e.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return e.registeredClass.constructor_body[t-1]=()=>{vt("Cannot construct "+e.name+" due to unbound types",o)},Ve([],o,(function(i){return i.splice(1,0,null),e.registeredClass.constructor_body[t-1]=St(r,i,null,n,s),[]})),[]}))},a:function(e,t,r,i,n,s,o,a){var c=bt(r,i);t=Oe(t),s=pt(n,s),Ve([],[e],(function(e){var i=(e=e[0]).name+"."+t;function n(){vt("Cannot call "+i+" due to unbound types",c)}t.startsWith("@@")&&(t=Symbol[t.substring(2)]),a&&e.registeredClass.pureVirtualFunctions.push(t);var h=e.registeredClass.instancePrototype,l=h[t];return void 0===l||void 0===l.overloadTable&&l.className!==e.name&&l.argCount===r-2?(n.argCount=r-2,n.className=e.name,h[t]=n):(nt(h,t,i),h[t].overloadTable[r-2]=n),Ve([],c,(function(n){var a=St(i,n,e,s,o);return void 0===h[t].overloadTable?(a.argCount=r-2,h[t]=a):h[t].overloadTable[r-2]=a,[]})),[]}))},k:function(e,t,r,i,n,s,o,a,c,h){t=Oe(t),n=pt(i,n),Ve([],[e],(function(e){var i=(e=e[0]).name+"."+t,l={get:function(){vt("Cannot access "+i+" due to unbound types",[r,o])},enumerable:!0,configurable:!0};return l.set=c?()=>{vt("Cannot access "+i+" due to unbound types",[r,o])}:e=>{Ne(i+" is a read-only property")},Object.defineProperty(e.registeredClass.instancePrototype,t,l),Ve([],c?[r,o]:[r],(function(r){var o=r[0],l={get:function(){var t=wt(this,e,i+" getter");return o.fromWireType(n(s,t))},enumerable:!0};if(c){c=pt(a,c);var u=r[1];l.set=function(t){var r=wt(this,e,i+" setter"),n=[];c(h,r,u.toWireType(n,t)),yt(n)}}return Object.defineProperty(e.registeredClass.instancePrototype,t,l),[]})),[]}))},aa:function(e,t){ze(e,{name:t=Oe(t),fromWireType:function(e){var t=kt.toValue(e);return xt(e),t},toWireType:function(e,t){return kt.toHandle(t)},argPackAdvance:8,readValueFromPointer:ut,destructorFunction:null})},i:function(e,t,r,i){var n=Ae(r);function s(){}t=Oe(t),s.values={},ze(e,{name:t,constructor:s,fromWireType:function(e){return this.constructor.values[e]},toWireType:function(e,t){return t.value},argPackAdvance:8,readValueFromPointer:Pt(t,n,i),destructorFunction:null}),st(t,s)},h:function(e,t,r){var i=Ct(e,"enum");t=Oe(t);var n=i.constructor,s=Object.create(i.constructor.prototype,{value:{value:r},constructor:{value:Ie(i.name+"_"+t,(function(){}))}});n.values[r]=s,n[t]=s},y:function(e,t,r){var i=Ae(r);ze(e,{name:t=Oe(t),fromWireType:function(e){return e},toWireType:function(e,t){return t},argPackAdvance:8,readValueFromPointer:_t(t,i),destructorFunction:null})},l:function(e,t,r,i,n){t=Oe(t),-1===n&&(n=4294967295);var s=Ae(r),o=e=>e;if(0===i){var a=32-8*r;o=e=>e<>>a}var c=t.includes("unsigned");ze(e,{name:t,fromWireType:o,toWireType:c?function(e,t){return this.name,t>>>0}:function(e,t){return this.name,t},argPackAdvance:8,readValueFromPointer:Ot(t,s,0!==i),destructorFunction:null})},j:function(e,t,r){var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t];function n(e){var t=W,r=t[(e>>=2)>>>0],n=t[e+1>>>0];return new i(F,n,r)}ze(e,{name:r=Oe(r),fromWireType:n,argPackAdvance:8,readValueFromPointer:n},{ignoreDuplicateRegistrations:!0})},x:function(e,t){var r="std::string"===(t=Oe(t));ze(e,{name:t,fromWireType:function(e){var t,i=W[e>>>2];if(r)for(var n=e+4,s=0;s<=i;++s){var o=e+4+s;if(s==i||0==B[o>>>0]){var a=_(n,o-n);void 0===t?t=a:(t+=String.fromCharCode(0),t+=a),n=o+1}}else{var c=new Array(i);for(s=0;s>>0]);t=c.join("")}return dr(e),t},toWireType:function(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var i="string"==typeof t;i||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||Ne("Cannot pass non-string to std::string");var n=(r&&i?()=>R(t):()=>t.length)(),s=ur(4+n+1);if(W[(s>>>=0)>>>2]=n,r&&i)D(t,s+4,n+1);else if(i)for(var o=0;o255&&(dr(s),Ne("String has UTF-16 code units that do not fit in 8 bits")),B[s+4+o>>>0]=a}else for(o=0;o>>0]=t[o];return null!==e&&e.push(dr,s),s},argPackAdvance:8,readValueFromPointer:ut,destructorFunction:function(e){dr(e)}})},s:function(e,t,r){var i,n,s,o,a;r=Oe(r),2===t?(i=V,n=z,o=j,s=()=>I,a=1):4===t&&(i=q,n=$,o=Y,s=()=>W,a=2),ze(e,{name:r,fromWireType:function(e){for(var r,n=W[e>>>2],o=s(),c=e+4,h=0;h<=n;++h){var l=e+4+h*t;if(h==n||0==o[l>>>a]){var u=i(c,l-c);void 0===r?r=u:(r+=String.fromCharCode(0),r+=u),c=l+t}}return dr(e),r},toWireType:function(e,i){"string"!=typeof i&&Ne("Cannot pass non-string to C++ string type "+r);var s=o(i),c=ur(4+s+t);return W[(c>>>=0)>>>2]=s>>a,n(i,c+4,s+t),null!==e&&e.push(dr,c),c},argPackAdvance:8,readValueFromPointer:ut,destructorFunction:function(e){dr(e)}})},ca:function(e,t){ze(e,{isVoid:!0,name:t=Oe(t),argPackAdvance:0,fromWireType:function(){},toWireType:function(e,t){}})},T:function(){return Date.now()},S:function(){return!0},n:function(e,t,r){e=kt.toValue(e),t=Ct(t,"emval::as");var i=[],n=kt.toHandle(i);return U[r>>>2]=n,t.toWireType(i,e)},sa:function(e,t,r,i,n){return(e=Ft[e])(t=kt.toValue(t),r=Rt(r),function(e){var t=[];return U[e>>>2]=kt.toHandle(t),t}(i),n)},wa:xt,ta:function(e){return 0===e?kt.toHandle(Lt()):(e=Rt(e),kt.toHandle(Lt()[e]))},ra:function(e,t){var r=function(e,t){for(var r=new Array(e),i=0;i>>2],"parameter "+i);return r}(e,t),i=r[0],n=i.name+"_$"+r.slice(1).map((function(e){return e.name})).join("_")+"$",s=Mt[n];if(void 0!==s)return s;for(var o=["retType"],a=[i],c="",h=0;h4&&(Tt[e].refcount+=1)},qa:function(e){return kt.toHandle(Rt(e))},ua:function(e){yt(kt.toValue(e)),xt(e)},o:function(e,t,r){e=kt.toValue(e),t=kt.toValue(t),r=kt.toValue(r),e[t]=r},m:function(e,t){var r=(e=Ct(e,"_emval_take_value")).readValueFromPointer(t);return kt.toHandle(r)},va:function(e){return e=kt.toValue(e),kt.toHandle(typeof e)},U:function(e,t){var r=new Date(1e3*U[e>>>2]);U[t>>>2]=r.getSeconds(),U[t+4>>>2]=r.getMinutes(),U[t+8>>>2]=r.getHours(),U[t+12>>>2]=r.getDate(),U[t+16>>>2]=r.getMonth(),U[t+20>>>2]=r.getFullYear()-1900,U[t+24>>>2]=r.getDay();var i=new Date(r.getFullYear(),0,1),n=(r.getTime()-i.getTime())/864e5|0;U[t+28>>>2]=n,U[t+36>>>2]=-60*r.getTimezoneOffset();var s=new Date(r.getFullYear(),6,1).getTimezoneOffset(),o=i.getTimezoneOffset(),a=0|(s!=o&&r.getTimezoneOffset()==Math.min(o,s));U[t+32>>>2]=a},J:function(e,t,r,i,n,s){try{e>>>=0;var o=xe.getStream(n);o&&(2&r&&ke.doMsync(e,o,t,i,s),xe.munmap(o))}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},V:function e(t,r,i){e.called||(e.called=!0,function(e,t,r){var i=(new Date).getFullYear(),n=new Date(i,0,1),s=new Date(i,6,1),o=n.getTimezoneOffset(),a=s.getTimezoneOffset(),c=Math.max(o,a);function h(e){var t=e.toTimeString().match(/\(([A-Za-z ]+)\)$/);return t?t[1]:"GMT"}U[e>>>2]=60*c,U[t>>>2]=Number(o!=a);var l=h(n),u=h(s),d=X(l),p=X(u);a>>2]=d,W[r+4>>>2]=p):(W[r>>>2]=p,W[r+4>>>2]=d)}(t,r,i))},u:function(){ae("")},G:function(){return 4294901760},da:function(e,t,r){(0|e)===e&&(e=_(e)),e=be.resolve(e);var i=ir[e];if(i){var n=i.getContext("2d").getImageData(0,0,i.width,i.height),s=ur(i.width*i.height*4);return B.set(n.data,s>>>0),U[t>>>2]=i.width,U[r>>>2]=i.height,s}return 0},R:function(e,t,r){B.copyWithin(e>>>0,t>>>0,t+r>>>0)},E:function(e){var t,r=B.length,i=4294901760;if((e>>>=0)>i)return!1;for(var n=1;n<=4;n*=2){var s=r*(1+.2/n);if(s=Math.min(s,e+100663296),Gt(Math.min(i,(t=Math.max(e,s))+(65536-t%65536)%65536)))return!0}return!1},L:function(e,t){var r=0;return Vt().forEach((function(i,n){var s=t+r;W[e+4*n>>>2]=s,function(e,t,r){for(var i=0;i>>0]=e.charCodeAt(i);L[t>>>0]=0}(i,s),r+=i.length+1})),0},M:function(e,t){var r=Vt();W[e>>>2]=r.length;var i=0;return r.forEach((function(e){i+=e.length+1})),W[t>>>2]=i,0},oa:function(t){!function(t,r){var i;x=t,x=i=t,te()||(e.onExit&&e.onExit(i),k=!0),p(i,new yr(i))}(t)},p:function(e){try{var t=ke.getStreamFromFD(e);return xe.close(t),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}},w:function(e,t,r,i){try{var n=function(e,t,r,i){for(var n=0,s=0;s>>2],a=W[t+4>>>2];t+=8;var c=xe.read(e,L,o,a,undefined);if(c<0)return-1;if(n+=c,c>>2]=n,0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}},A:function(e,t,r,i,n){try{var s=(c=r)+2097152>>>0<4194305-!!(a=t)?(a>>>0)+4294967296*c:NaN;if(isNaN(s))return 61;var o=ke.getStreamFromFD(e);return xe.llseek(o,s,i),ue=[o.position>>>0,(le=o.position,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[n>>>2]=ue[0],U[n+4>>>2]=ue[1],o.getdents&&0===s&&0===i&&(o.getdents=null),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}var a,c},q:function(e,t,r,i){try{var n=function(e,t,r,i){for(var n=0,s=0;s>>2],a=W[t+4>>>2];t+=8;var c=xe.write(e,L,o,a,undefined);if(c<0)return-1;n+=c}return n}(ke.getStreamFromFD(e),t,r);return W[i>>>2]=n,0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}},pa:function(e){return function(e){var t=ur(20),r=ur(e.length+1);D(e,r,e.length+1),W[t>>>2]=r;var i=ur(4);W[i>>>2]=0,W[t+4>>>2]=i,U[t+8>>>2]=2,U[t+12>>>2]=4;var n=ur(12);return W[n>>>2]=n+8,W[n+4>>>2]=0,U[n+8>>>2]=zt(qt.lookup_name(e)),W[t+16>>>2]=n,t}(_(e))},ma:function(e,t){if(t=_(t),e=$t.programs[e]){!function(e){var t,r,i=e.uniformLocsById,n=e.uniformSizeAndIdsByName;if(!i)for(e.uniformLocsById=i={},e.uniformArrayNamesById={},t=0;t0?o.slice(0,c):o,l=e.uniformIdCounter;for(e.uniformIdCounter+=a,n[h]=[a,l],r=0;r0&&(i=jt(t.slice(s+1))>>>0,n=t.slice(0,s));var o=e.uniformSizeAndIdsByName[n];if(o&&i>>2],i[n+1]=N[r+(4*n+4)>>>2];else i=N.subarray(r>>>2,r+8*t>>>2);rr.uniform2fv(Xt(e),i)},ja:function(e,t,r){if(t<=144)for(var i=Jt[2*t-1],n=0;n<2*t;n+=2)i[n]=U[r+4*n>>>2],i[n+1]=U[r+(4*n+4)>>>2];else i=U.subarray(r>>>2,r+8*t>>>2);rr.uniform2iv(Xt(e),i)},fa:function(e,t,r){if(t<=96)for(var i=Zt[3*t-1],n=0;n<3*t;n+=3)i[n]=N[r+4*n>>>2],i[n+1]=N[r+(4*n+4)>>>2],i[n+2]=N[r+(4*n+8)>>>2];else i=N.subarray(r>>>2,r+12*t>>>2);rr.uniform3fv(Xt(e),i)},ia:function(e,t,r){if(t<=96)for(var i=Jt[3*t-1],n=0;n<3*t;n+=3)i[n]=U[r+4*n>>>2],i[n+1]=U[r+(4*n+4)>>>2],i[n+2]=U[r+(4*n+8)>>>2];else i=U.subarray(r>>>2,r+12*t>>>2);rr.uniform3iv(Xt(e),i)},ea:function(e,t,r){if(t<=72){var i=Zt[4*t-1],n=N;r>>=2;for(var s=0;s<4*t;s+=4){var o=r+s;i[s]=n[o>>>0],i[s+1]=n[o+1>>>0],i[s+2]=n[o+2>>>0],i[s+3]=n[o+3>>>0]}}else i=N.subarray(r>>>2,r+16*t>>>2);rr.uniform4fv(Xt(e),i)},ha:function(e,t,r){if(t<=72)for(var i=Jt[4*t-1],n=0;n<4*t;n+=4)i[n]=U[r+4*n>>>2],i[n+1]=U[r+(4*n+4)>>>2],i[n+2]=U[r+(4*n+8)>>>2],i[n+3]=U[r+(4*n+12)>>>2];else i=U.subarray(r>>>2,r+16*t>>>2);rr.uniform4iv(Xt(e),i)},C:function(e){},D:function(e,t,r,i){return function(e,t,r,i){var n=U[i+40>>>2],s={tm_sec:U[i>>>2],tm_min:U[i+4>>>2],tm_hour:U[i+8>>>2],tm_mday:U[i+12>>>2],tm_mon:U[i+16>>>2],tm_year:U[i+20>>>2],tm_wday:U[i+24>>>2],tm_yday:U[i+28>>>2],tm_isdst:U[i+32>>>2],tm_gmtoff:U[i+36>>>2],tm_zone:n?_(n):""},o=_(r),a={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var c in a)o=o.replace(new RegExp(c,"g"),a[c]);var h=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],l=["January","February","March","April","May","June","July","August","September","October","November","December"];function u(e,t,r){for(var i="number"==typeof e?e.toString():e||"";i.length0?1:0}var i;return 0===(i=r(e.getFullYear()-t.getFullYear()))&&0===(i=r(e.getMonth()-t.getMonth()))&&(i=r(e.getDate()-t.getDate())),i}function f(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function g(e){var t=function(e,t){for(var r=new Date(e.getTime());t>0;){var i=Qt(r.getFullYear()),n=r.getMonth(),s=(i?Kt:er)[n];if(!(t>s-r.getDate()))return r.setDate(r.getDate()+t),r;t-=s-r.getDate()+1,r.setDate(1),n<11?r.setMonth(n+1):(r.setMonth(0),r.setFullYear(r.getFullYear()+1))}return r}(new Date(e.tm_year+1900,0,1),e.tm_yday),r=new Date(t.getFullYear(),0,4),i=new Date(t.getFullYear()+1,0,4),n=f(r),s=f(i);return p(n,t)<=0?p(s,t)<=0?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var v={"%a":function(e){return h[e.tm_wday].substring(0,3)},"%A":function(e){return h[e.tm_wday]},"%b":function(e){return l[e.tm_mon].substring(0,3)},"%B":function(e){return l[e.tm_mon]},"%C":function(e){return d((e.tm_year+1900)/100|0,2)},"%d":function(e){return d(e.tm_mday,2)},"%e":function(e){return u(e.tm_mday,2," ")},"%g":function(e){return g(e).toString().substring(2)},"%G":function(e){return g(e)},"%H":function(e){return d(e.tm_hour,2)},"%I":function(e){var t=e.tm_hour;return 0==t?t=12:t>12&&(t-=12),d(t,2)},"%j":function(e){return d(e.tm_mday+function(e,t){for(var r=0,i=0;i<=t;r+=e[i++]);return r}(Qt(e.tm_year+1900)?Kt:er,e.tm_mon-1),3)},"%m":function(e){return d(e.tm_mon+1,2)},"%M":function(e){return d(e.tm_min,2)},"%n":function(){return"\n"},"%p":function(e){return e.tm_hour>=0&&e.tm_hour<12?"AM":"PM"},"%S":function(e){return d(e.tm_sec,2)},"%t":function(){return"\t"},"%u":function(e){return e.tm_wday||7},"%U":function(e){var t=e.tm_yday+7-e.tm_wday;return d(Math.floor(t/7),2)},"%V":function(e){var t=Math.floor((e.tm_yday+7-(e.tm_wday+6)%7)/7);if((e.tm_wday+371-e.tm_yday-2)%7<=2&&t++,t){if(53==t){var r=(e.tm_wday+371-e.tm_yday)%7;4==r||3==r&&Qt(e.tm_year)||(t=1)}}else{t=52;var i=(e.tm_wday+7-e.tm_yday-1)%7;(4==i||5==i&&Qt(e.tm_year%400-1))&&t++}return d(t,2)},"%w":function(e){return e.tm_wday},"%W":function(e){var t=e.tm_yday+7-(e.tm_wday+6)%7;return d(Math.floor(t/7),2)},"%y":function(e){return(e.tm_year+1900).toString().substring(2)},"%Y":function(e){return e.tm_year+1900},"%z":function(e){var t=e.tm_gmtoff,r=t>=0;return t=(t=Math.abs(t)/60)/60*100+t%60,(r?"+":"-")+String("0000"+t).slice(-4)},"%Z":function(e){return e.tm_zone},"%%":function(){return"%"}};for(var c in o=o.replace(/%%/g,"\0\0"),v)o.includes(c)&&(o=o.replace(new RegExp(c,"g"),v[c](s)));var m=cr(o=o.replace(/\0\0/g,"%"),!1);return m.length>t?0:(function(e,t){L.set(e,t>>>0)}(m,e),m.length-1)}(e,t,r,i)}},ur=(function(){var t={a:lr};function r(t,r){var i,n=t.exports;e.asm=n,Z((E=e.asm.xa).buffer),J=e.asm.Ea,i=e.asm.ya,K.unshift(i),oe()}function n(e){r(e.instance)}function o(e){return function(){if(!b&&(f||g)){if("function"==typeof fetch&&!pe(ce))return fetch(ce,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+ce+"'";return e.arrayBuffer()})).catch((function(){return fe(ce)}));if(s)return new Promise((function(e,t){s(ce,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return fe(ce)}))}().then((function(e){return WebAssembly.instantiate(e,t)})).then((function(e){return e})).then(e,(function(e){S("failed to asynchronously prepare wasm: "+e),ae(e)}))}if(se(),e.instantiateWasm)try{return e.instantiateWasm(t,r)}catch(e){return S("Module.instantiateWasm callback failed with error: "+e),!1}(b||"function"!=typeof WebAssembly.instantiateStreaming||de(ce)||pe(ce)||v||"function"!=typeof fetch?o(n):fetch(ce,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,t).then(n,(function(e){return S("wasm streaming compile failed: "+e),S("falling back to ArrayBuffer instantiation"),o(n)}))}))).catch(i)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.ya).apply(null,arguments)},e._malloc=function(){return(ur=e._malloc=e.asm.za).apply(null,arguments)}),dr=e._free=function(){return(dr=e._free=e.asm.Aa).apply(null,arguments)},pr=e.___errno_location=function(){return(pr=e.___errno_location=e.asm.Ba).apply(null,arguments)},fr=e.___getTypeName=function(){return(fr=e.___getTypeName=e.asm.Ca).apply(null,arguments)},gr=(e.___embind_register_native_and_builtin_types=function(){return(e.___embind_register_native_and_builtin_types=e.asm.Da).apply(null,arguments)},e._htons=function(){return(gr=e._htons=e.asm.Fa).apply(null,arguments)}),vr=e._emscripten_builtin_memalign=function(){return(vr=e._emscripten_builtin_memalign=e.asm.Ga).apply(null,arguments)},mr=e.___cxa_is_pointer_type=function(){return(mr=e.___cxa_is_pointer_type=e.asm.Ha).apply(null,arguments)};function yr(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function Sr(r){function i(){hr||(hr=!0,e.calledRun=!0,k||(e.noFSInit||xe.init.initialized||xe.init(),xe.ignorePermissions=!1,we.init(),ge(K),t(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),function(){if(e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;)t=e.postRun.shift(),ee.unshift(t);var t;ge(ee)}()))}r=r||u,re>0||(function(){if(e.preRun)for("function"==typeof e.preRun&&(e.preRun=[e.preRun]);e.preRun.length;)t=e.preRun.shift(),Q.unshift(t);var t;ge(Q)}(),re>0||(e.setStatus?(e.setStatus("Running..."),setTimeout((function(){setTimeout((function(){e.setStatus("")}),1),i()}),1)):i()))}if(e.dynCall_jiji=function(){return(e.dynCall_jiji=e.asm.Ia).apply(null,arguments)},e.dynCall_viijii=function(){return(e.dynCall_viijii=e.asm.Ja).apply(null,arguments)},e.dynCall_iiiiij=function(){return(e.dynCall_iiiiij=e.asm.Ka).apply(null,arguments)},e.dynCall_iiiiijj=function(){return(e.dynCall_iiiiijj=e.asm.La).apply(null,arguments)},e.dynCall_iiiiiijj=function(){return(e.dynCall_iiiiiijj=e.asm.Ma).apply(null,arguments)},e.dynCall_viiiiji=function(){return(e.dynCall_viiiiji=e.asm.Na).apply(null,arguments)},e.dynCall_viiijj=function(){return(e.dynCall_viiijj=e.asm.Oa).apply(null,arguments)},e.FS=xe,ne=function e(){hr||Sr(),hr||(ne=e)},e.run=Sr,e.preInit)for("function"==typeof e.preInit&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.pop()();return Sr(),e.ready});const _e=Ae;class Oe{constructor(e){this.occ=e,this.hashesFromPreviousRun={},this.usedHashes={},this.argCache={}}cleanAllCache(){Object.keys(this.usedHashes).forEach((e=>{if(this.argCache[e])try{const t=this.argCache[e];this.occ.BRepTools.Clean(t,!0),this.occ.BRepTools.CleanGeometry(t),t.delete()}catch(e){}})),this.argCache={},this.usedHashes={},this.hashesFromPreviousRun={}}cleanCacheForHash(e){if(this.argCache[e])try{const t=this.argCache[e];this.occ.BRepTools.Clean(t,!0),this.occ.BRepTools.CleanGeometry(t),t.delete()}catch(e){}delete this.argCache[e],delete this.usedHashes[e],delete this.hashesFromPreviousRun[e]}cleanUpCache(){}isOCCTObject(e){return null!=e&&!Array.isArray(e)&&void 0!==e.$$||Array.isArray(e)&&e.length>0&&void 0!==e[0].$$}cacheOp(e,t){let r=null;const i=this.computeHash(e);this.usedHashes[i]=i,this.hashesFromPreviousRun[i]=i;const n=this.checkCache(i);if(n)this.isOCCTObject(n)?(r=n,r.hash=n.hash):n.value&&(r=n.value);else if(r=t(),Array.isArray(r)&&this.isOCCTObject(r))r.forEach(((t,r)=>{const i=this.computeHash(Object.assign(Object.assign({},e),{index:r}));t.hash=i,this.addToCache(i,t)}));else if(this.isOCCTObject(r))r.hash=i,this.addToCache(i,r);else if(r.compound&&r.data&&r.shapes&&r.shapes.length>0){const t=r,n=this.computeHash(Object.assign(Object.assign({},e),{index:"compound"}));t.compound.hash=n,this.addToCache(n,t.compound),t.shapes.forEach(((t,r)=>{const i=this.computeHash(Object.assign(Object.assign({},e),{index:r}));t.shape.hash=i,this.addToCache(i,t.shape)})),this.addToCache(i,{value:t})}else this.addToCache(i,{value:r});return r}checkCache(e){return this.argCache[e]||null}addToCache(e,t){const r=t;return r.hash=e,this.argCache[e]=r,e}computeHash(e,t){let r=JSON.stringify(e);r=r.replace(/(\"ptr\"\:(-?[0-9]*?)\,)/g,""),r=r.replace(/(\"ptr\"\:(-?[0-9]*))/g,""),r.includes("ptr")&&console.error("YOU DONE MESSED UP YOUR REGEX.");const i=Math.random.toString()+r;return t?i:this.stringToHash(i)}stringToHash(e){let t=0;if(0===e.length)return t;for(let r=0;re.hash!==t.hash||e.ptr!==t.ptr))}dupShape(e){return e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE?this.occ.TopoDS.Wire_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SHELL?this.occ.TopoDS.Shell_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?this.occ.TopoDS.Edge_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SOLID?this.occ.TopoDS.Solid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_FACE?this.occ.TopoDS.Face_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPOUND?this.occ.TopoDS.Compound_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID?this.occ.TopoDS.CompSolid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX?this.occ.TopoDS.Vertex_1(e):void 0}}let De,Re,Fe;class Le{static distributeBetweenBounds(e,t,r,i=!1){const n=[];let s=r;for(i&&n.push(s);s>t;)s-=e,n.push(s);return n}static computeSideA(e,t){const r=e*Math.PI/180,i=t/Math.cos(r),n=Math.pow(i,2)-Math.pow(t,2);return Math.sqrt(n)}static computeSideAFromHypotenuseAndAngle(e,t){const r=e*Math.PI/180;return t*Math.sin(r)}static computeHypotenuse(e,t){return t/Math.cos(e*Math.PI/180)}}var Be,Me,Ie,Ue,We,Ne;!function(e){e.low="low",e.middle="middle",e.high="high"}(Be||(Be={}));class Ge{constructor(){this.lod=Be.low}}class He{}class Ve{constructor(e,t,r,i,n,s,o,a,c){this.swirl=.6,this.nrOfDivisions=10,this.addRadiusNarrow=.4,this.addRadiusWide=.2,this.addMiddleHeight=1.6,this.addTopHeight=1.5,this.thickness=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.swirl=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==r&&(this.addRadiusNarrow=r),void 0!==i&&(this.addRadiusWide=i),void 0!==n&&(this.addMiddleHeight=n),void 0!==s&&(this.addTopHeight=s),void 0!==o&&(this.thickness=o),void 0!==a&&(this.rotation=a),void 0!==c&&(this.origin=c)}}class ze{constructor(){this.type="parametric-model",this.name="serenitySwirl"}}class je{}class qe{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.profilePoints=[[2,0,0],[4,5,0],[1.5,10,0],[3,14,0]],this.nrOfSides=6,this.nrOfVerticalArches=4,this.archCenterThickness=.8,this.edgesThickness=.2,this.thickness=1,this.baseHeight=.4,this.patchHoles=!0,this.lod=Be.high,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],this.scale=[1,1,1],void 0!==e&&(this.nrOfSides=e),void 0!==t&&(this.nrOfVerticalArches=t),void 0!==r&&(this.archCenterThickness=r),void 0!==i&&(this.edgesThickness=i),void 0!==n&&(this.thickness=n),void 0!==s&&(this.baseHeight=s),void 0!==o&&(this.patchHoles=o),void 0!==a&&(this.lod=a),void 0!==c&&(this.rotation=c),void 0!==h&&(this.origin=h),void 0!==l&&(this.direction=l),void 0!==u&&(this.scale=u)}}class $e{constructor(){this.type="parametric-model",this.name="arabicArchway"}}class Ye{}class Xe{}class Ze{}class Je{constructor(e,t,r,i,n,s,o,a){this.textHeading="LOVE YOU",this.textName="NORA",this.fullModel=!0,this.thickness=6,this.decorationThickness=1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textHeading=e),void 0!==t&&(this.textName=t),void 0!==r&&(this.fullModel=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.decorationThickness=n),void 0!==s&&(this.rotation=s),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a)}}class Qe{constructor(){this.type="parametric-model",this.name="eternalLove"}}class Ke{}class et{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.height=6,this.radiusBottom=4,this.radiusTopOffset=2,this.thickness=.6,this.fillet=.2,this.nrOfHandles=1,this.handleDist=2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==r&&(this.radiusTopOffset=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.fillet=n),void 0!==s&&(this.nrOfHandles=s),void 0!==o&&(this.handleDist=o),void 0!==a&&(this.precision=a),void 0!==c&&(this.rotation=c),void 0!==h&&(this.scale=h),void 0!==l&&(this.origin=l),void 0!==u&&(this.direction=u)}}class tt{constructor(){this.type="parametric-model",this.name="calmCup"}}class rt{}class it{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y,S,b){this.height=8,this.radiusBottom=4,this.radiusTopOffset=2,this.radiusMidOffset=2,this.rotationTopAngle=20,this.rotationMidAngle=20,this.nrSkinCellsVertical=5,this.nrSkinCellsHorizontal=10,this.nrSkinCellDivisionsTop=1,this.nrSkinCellDivisionsBottom=3,this.skinCellOuterHeight=.4,this.skinCellInnerHeight=.3,this.skinCellBottomHeight=.4,this.skinCellTopHeight=.4,this.thickness=.6,this.bottomThickness=1,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==r&&(this.radiusTopOffset=r),void 0!==i&&(this.radiusMidOffset=i),void 0!==n&&(this.rotationTopAngle=n),void 0!==s&&(this.rotationMidAngle=s),void 0!==o&&(this.nrSkinCellsVertical=o),void 0!==a&&(this.nrSkinCellsHorizontal=a),void 0!==c&&(this.nrSkinCellDivisionsTop=c),void 0!==h&&(this.nrSkinCellDivisionsBottom=h),void 0!==l&&(this.skinCellOuterHeight=l),void 0!==u&&(this.skinCellInnerHeight=u),void 0!==d&&(this.skinCellBottomHeight=d),void 0!==p&&(this.skinCellTopHeight=p),void 0!==f&&(this.thickness=f),void 0!==g&&(this.bottomThickness=g),void 0!==v&&(this.precision=v),void 0!==m&&(this.rotation=m),void 0!==y&&(this.scale=y),void 0!==S&&(this.origin=S),void 0!==b&&(this.direction=b)}}class nt{constructor(){this.type="parametric-model",this.name="dragonCup"}}class st{}class ot{}class at{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m){this.heightBottom=5,this.heightTop=16,this.widthBack=25,this.widthFront=10,this.length=16,this.backOffset=6,this.thickness=.4,this.applyOrnaments=!1,this.filletRadius=2,this.phoneHeight=16.8,this.phoneWidth=7.8,this.phoneThickness=.7,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.heightBottom=e),void 0!==t&&(this.heightTop=t),void 0!==r&&(this.widthBack=r),void 0!==i&&(this.widthFront=i),void 0!==n&&(this.length=n),void 0!==s&&(this.backOffset=s),void 0!==o&&(this.thickness=o),void 0!==a&&(this.applyOrnaments=a),void 0!==c&&(this.filletRadius=c),void 0!==h&&(this.phoneHeight=h),void 0!==l&&(this.phoneWidth=l),void 0!==u&&(this.phoneThickness=u),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdges=p),void 0!==f&&(this.rotation=f),void 0!==g&&(this.scale=g),void 0!==v&&(this.origin=v),void 0!==m&&(this.direction=m)}}class ct{constructor(){this.type="parametric-model",this.name="phoneNest"}}class ht extends He{}class lt{}class ut extends He{}class dt{}class pt{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class ft{}class gt{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y){this.textTop="Pepper",this.textFront="For Your Spicy Needs",this.nrSides=4,this.nrOffsets=1,this.height=6,this.radiusBase=4,this.radiusOffset=2,this.coverHeight=1,this.baseHeight=1,this.thickness=.6,this.ornamentalThickness=.1,this.nrOrnamnetsPerSide=10,this.invertOrnaments=!1,this.fillet=.2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textTop=e),void 0!==t&&(this.textFront=t),void 0!==r&&(this.nrSides=r),void 0!==i&&(this.nrOffsets=i),void 0!==n&&(this.height=n),void 0!==s&&(this.coverHeight=s),void 0!==o&&(this.baseHeight=o),void 0!==a&&(this.radiusBase=a),void 0!==c&&(this.radiusOffset=c),void 0!==h&&(this.thickness=h),void 0!==l&&(this.ornamentalThickness=l),void 0!==u&&(this.nrOrnamnetsPerSide=u),void 0!==d&&(this.invertOrnaments=d),void 0!==p&&(this.fillet=p),void 0!==f&&(this.precision=f),void 0!==g&&(this.rotation=g),void 0!==v&&(this.scale=v),void 0!==m&&(this.origin=m),void 0!==y&&(this.direction=y)}}class vt{constructor(){this.type="parametric-model",this.name="spicyBox"}}class mt{}class yt{}class St{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y,S,b,w,E,T,x,k,P,C,A,_){this.widthFirstWing=4,this.lengthFirstWing=10,this.terraceWidth=3,this.widthSecondWing=5,this.lengthSecondWing=10,this.heightWalls=3,this.roofAngleFirstWing=15,this.roofAngleSecondWing=25,this.roofOffset=.5,this.roofInsideOverhang=.5,this.roofMaxDistAttachmentBeams=.8,this.roofAttachmentBeamWidth=.2,this.roofAttachmentBeamHeight=.05,this.roofOutsideOverhang=.5,this.columnSize=.3,this.ceilingBeamHeight=.25,this.ceilingBeamWidth=.1,this.nrCeilingBeamsBetweenColumns=3,this.distBetweenColumns=2,this.floorHeight=.1,this.groundLevel=.6,this.facadePanelThickness=.05,this.windowWidthOffset=.1,this.windowHeightOffset=.2,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05,this.lod=Be.high,this.skinOpacity=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.widthFirstWing=e),void 0!==t&&(this.lengthFirstWing=t),void 0!==r&&(this.terraceWidth=r),void 0!==i&&(this.widthSecondWing=i),void 0!==n&&(this.lengthSecondWing=n),void 0!==s&&(this.heightWalls=s),void 0!==o&&(this.roofAngleFirstWing=o),void 0!==a&&(this.roofAngleSecondWing=a),void 0!==c&&(this.roofOffset=c),void 0!==h&&(this.roofInsideOverhang=h),void 0!==l&&(this.roofMaxDistAttachmentBeams=l),void 0!==u&&(this.roofAttachmentBeamWidth=u),void 0!==d&&(this.roofAttachmentBeamHeight=d),void 0!==p&&(this.roofOutsideOverhang=p),void 0!==f&&(this.columnSize=f),void 0!==g&&(this.ceilingBeamHeight=g),void 0!==v&&(this.ceilingBeamWidth=v),void 0!==m&&(this.nrCeilingBeamsBetweenColumns=m),void 0!==y&&(this.distBetweenColumns=y),void 0!==S&&(this.floorHeight=S),void 0!==b&&(this.groundLevel=b),void 0!==w&&(this.facadePanelThickness=w),void 0!==E&&(this.windowWidthOffset=E),void 0!==T&&(this.windowHeightOffset=T),void 0!==x&&(this.windowFrameThickness=x),void 0!==k&&(this.windowGlassFrameThickness=k),void 0!==P&&(this.lod=P),void 0!==C&&(this.skinOpacity=C),void 0!==A&&(this.rotation=A),void 0!==_&&(this.origin=_)}}class bt{constructor(){this.type="parametric-model",this.name="zenHideout"}}class wt{}class Et{}class Tt{constructor(){this.wallThickness=.4,this.facadePanelThickness=.05,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThckness=.05,this.height=3,this.lengthFirst=1,this.lengthSecond=2,this.rotation=0}}class xt{constructor(){this.thickness=.3,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThickness=.05,this.height=3,this.width=1,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0]}}class kt extends xt{}class Pt extends Tt{}class Ct{constructor(){this.name="sandwitch-panel",this.createWindow=!0,this.createInnerPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelWidth=.4,this.exteriorPanelHeight=3,this.exteriorPanelThickness=.05,this.exteriorPanelBottomOffset=0,this.interiorPanelWidth=.4,this.interiorPanelHeight=3,this.interiorPanelThickness=.05,this.interiorPanelBottomOffset=0,this.windowWidthOffset=0,this.windowHeightOffset=0,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05}}class At{constructor(){this.name="sandwitch-panel-flex",this.createInteriorPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelThickness=.05,this.interiorPanelThickness=.05,this.interiorPanelPolygonPoints=[],this.exteriorPanelPolygonPoints=[]}}class _t extends Ct{}class Ot extends At{}class Dt{}class Rt{}class Ft{}class Lt{}class Bt{}class Mt{}class It{constructor(){this.invert=!1,this.widthFirstLanding=1,this.widthSecondLanding=1,this.lengthFirstWing=2,this.lengthSecondWing=1,this.maxWishedStepHeight=.25,this.stepHeightWidthProportion=1.35,this.totalHeight=1,this.rotation=0,this.origin=[0,0,0]}}class Ut extends It{}class Wt{}class Nt{constructor(){this.name="roof-cover",this.roofAngle=15,this.roofLength=3,this.roofWidth=3,this.roofOutsideOverhang=.5,this.roofInsideOverhang=1,this.roofOverhangFacade=.1,this.roofThickness=.05,this.roofCoverHeight=.3,this.rotation=0,this.lod=Be.high,this.center=[0,0,0],this.direction=[0,1,0]}}class Gt extends Nt{}class Ht{}class Vt{}class zt{constructor(){this.widthFirstWing=1,this.widthSecondWing=2,this.lengthStairFirstWing=2,this.lengthStairSecondWing=1,this.lengthWallFirstWing=2,this.lengthWallSecondWing=1,this.facadePanelThickness=.05,this.wallThickness=3,this.wallHeightExterior=3,this.wallHeightInterior=3,this.windowFrameOffsetTop=.3,this.windowFrameThickness=.1,this.glassFrameThickness=.05,this.doorWidth=1,this.windowWidthOffset=.3,this.stairTotalHeight=1,this.createStair=!1,this.flipDirection=!1,this.rotation=0,this.origin=[0,0,0]}}class jt{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.5,this.holeDiameter=1.5,this.holeDistToBottom=2.5,this.stickLength=1.2,this.stickDiameter=.5,this.baseAttachmentHeight=2,this.roofOverhang=1,this.rotation=0,this.chimneyHeight=1,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==r&&(this.interiorHeight=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.holeDiameter=n),void 0!==s&&(this.holeDistToBottom=s),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==c&&(this.baseAttachmentHeight=c),void 0!==h&&(this.roofOverhang=h),void 0!==l&&(this.rotation=l),void 0!==u&&(this.chimneyHeight=u),void 0!==d&&(this.origin=d)}}class qt{constructor(){this.type="parametric-model",this.name="wingtipVilla"}}class $t{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.3,this.holeDiameter=1.2,this.holeDistToBottom=2.5,this.stickLength=.9,this.stickDiameter=.3,this.baseAttachmentHeight=2,this.roofOverhang=.5,this.roofAngle=20,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==r&&(this.interiorHeight=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.holeDiameter=n),void 0!==s&&(this.holeDistToBottom=s),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==c&&(this.baseAttachmentHeight=c),void 0!==h&&(this.roofOverhang=h),void 0!==l&&(this.roofAngle=l),void 0!==u&&(this.rotation=u),void 0!==d&&(this.origin=d)}}class Yt{constructor(){this.type="parametric-model",this.name="chirpyChalet"}}class Xt{}class Zt{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f){this.sittingHeight=.45,this.backRestOffset=.1,this.backRestHeight=.7,this.width=.45,this.length=.45,this.thickness=.05,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.sittingHeight=e),void 0!==t&&(this.backRestOffset=t),void 0!==r&&(this.backRestHeight=r),void 0!==i&&(this.width=i),void 0!==n&&(this.length=n),void 0!==s&&(this.thickness=s),void 0!==o&&(this.nrOrnamentPlanks=o),void 0!==a&&(this.ornamentDepth=a),void 0!==c&&(this.filletRadius=c),void 0!==h&&(this.precision=h),void 0!==l&&(this.drawEdges=l),void 0!==u&&(this.rotation=u),void 0!==d&&(this.scale=d),void 0!==p&&(this.origin=p),void 0!==f&&(this.direction=f)}}class Jt{constructor(){this.type="parametric-model",this.name="snakeChair"}}class Qt extends He{}class Kt{}class er extends He{}class tr{}class rr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class ir{}class nr{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g){this.height=.74,this.width=1,this.length=2,this.topThickness=.02,this.topOffset=.03,this.bottomThickness=.05,this.minFillet=.2,this.radiusLegTop=.03,this.radiusLegBottom=.01,this.nrLegPairs=2,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==r&&(this.length=r),void 0!==i&&(this.topThickness=i),void 0!==n&&(this.topOffset=n),void 0!==s&&(this.bottomThickness=s),void 0!==o&&(this.minFillet=o),void 0!==a&&(this.radiusLegTop=a),void 0!==c&&(this.radiusLegBottom=c),void 0!==h&&(this.nrLegPairs=h),void 0!==l&&(this.precision=l),void 0!==u&&(this.drawEdges=u),void 0!==d&&(this.rotation=d),void 0!==p&&(this.scale=p),void 0!==f&&(this.origin=f),void 0!==g&&(this.direction=g)}}class sr{constructor(){this.type="parametric-model",this.name="elegantTable"}}class or extends He{}class ar{}class cr extends He{}class hr extends He{}class lr{constructor(){this.index=0}}class ur{}class dr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class pr{}class fr{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m){this.height=.4,this.width=1,this.length=1.2,this.chamfer=.01,this.topThickness=.05,this.topGlassOffset=.2,this.glassThickness=.005,this.glassHolderLength=.02,this.shelfTopOffset=.15,this.shelfThickness=.03,this.legWidth=.1,this.legDepth=.05,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==r&&(this.length=r),void 0!==i&&(this.chamfer=i),void 0!==n&&(this.topThickness=n),void 0!==s&&(this.topGlassOffset=s),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassHolderLength=a),void 0!==c&&(this.shelfTopOffset=c),void 0!==h&&(this.shelfThickness=h),void 0!==l&&(this.legWidth=l),void 0!==u&&(this.legDepth=u),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdges=p),void 0!==f&&(this.rotation=f),void 0!==g&&(this.scale=g),void 0!==v&&(this.origin=v),void 0!==m&&(this.direction=m)}}class gr{constructor(){this.type="parametric-model",this.name="goodCoffeeTable"}}class vr extends He{}class mr{}class yr extends He{}class Sr extends He{}class br extends He{}class wr{constructor(){this.index=0}}class Er{}class Tr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class xr{}class kr{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v){this.height=.74,this.width=1,this.length=2,this.supportLength=.5,this.shelfHeight=.2,this.thickness=.05,this.glassThickness=.005,this.glassOffset=0,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==r&&(this.length=r),void 0!==i&&(this.supportLength=i),void 0!==n&&(this.shelfHeight=n),void 0!==s&&(this.thickness=s),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassOffset=a),void 0!==c&&(this.nrOrnamentPlanks=c),void 0!==h&&(this.ornamentDepth=h),void 0!==l&&(this.filletRadius=l),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdges=d),void 0!==p&&(this.rotation=p),void 0!==f&&(this.scale=f),void 0!==g&&(this.origin=g),void 0!==v&&(this.direction=v)}}class Pr{constructor(){this.type="parametric-model",this.name="snakeTable"}}class Cr extends He{}class Ar{}class _r extends He{}class Or{}class Dr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}!function(e){e.Aboreto="Aboreto",e.Bungee="Bungee",e.IndieFlower="IndieFlower",e.Lugrasimo="Lugrasimo",e.Orbitron="Orbitron",e.Roboto="Roboto",e.RobotoSlab="RobotoSlab",e.Silkscreen="Silkscreen",e.Tektur="Tektur",e.Workbench="Workbench"}(Me||(Me={})),function(e){e.Regular="Regular",e.Black="Black",e.Bold="Bold",e.ExtraBold="ExtraBold",e.Medium="Medium",e.SemiBold="SemiBold",e.BlackItalic="BlackItalic",e.BoldItalic="BoldItalic",e.Italic="Italic",e.Light="Light",e.LightItalic="LightItalic",e.MediumItalic="MediumItalic",e.Thin="Thin",e.ThinItalic="ThinItalic",e.ExtraLight="ExtraLight"}(Ie||(Ie={})),function(e){e.separatedExtrusion="separatedExtrusion",e.integratedExtrusion="integratedExtrusion",e.cutout="cutout"}(Ue||(Ue={})),function(e){e.compound="compound",e.cutout="originalCutout",e.cutoutInsideCharacter="cutoutInsideCharacter"}(We||(We={})),function(e){e.leftTop="leftTop",e.leftMiddle="leftMiddle",e.leftBottom="leftBottom",e.centerTop="centerTop",e.centerMiddle="centerMiddle",e.centerBottom="centerBottom",e.rightTop="rightTop",e.rightMiddle="rightMiddle",e.rightBottom="rightBottom"}(Ne||(Ne={}));const Rr=[{key:"Aboreto",variants:["Regular"]},{key:"Bungee",variants:["Regular"]},{key:"IndieFlower",variants:["Regular"]},{key:"Lugrasimo",variants:["Regular"]},{key:"Orbitron",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Roboto",variants:["Black","BlackItalic","Bold","BoldItalic","Italic","Light","LightItalic","Medium","MediumItalic","Regular","Thin","ThinItalic"]},{key:"RobotoSlab",variants:["Black","Bold","ExtraBold","ExtraLight","Light","Medium","Regular","SemiBold","Thin"]},{key:"Silkscreen",variants:["Bold","Regular"]},{key:"Tektur",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Workbench",variants:["Regular"]}];class Fr{constructor(e,t,r,i,n,s,o,a,c){this.text="bitbybit.dev",this.fontType=Me.Roboto,this.fontVariant=Ie.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.origin=[0,0,0],this.direction=[0,1,0],this.originAlignment=Ne.centerMiddle,void 0!==e&&(this.text=e),void 0!==t&&(this.fontType=t),void 0!==r&&(this.fontVariant=r),void 0!==i&&(this.fontSize=i),void 0!==n&&(this.height=n),void 0!==s&&(this.rotation=s),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a),void 0!==c&&(this.originAlignment=c)}}class Lr{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.facePlanar=!1,this.faceTextVar=Ue.separatedExtrusion,this.text="bitbybit.dev",this.fontType=Me.Roboto,this.fontVariant=Ie.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=Ne.centerMiddle,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==r&&(this.faceTextVar=r),void 0!==i&&(this.text=i),void 0!==n&&(this.fontType=n),void 0!==s&&(this.fontVariant=s),void 0!==o&&(this.fontSize=o),void 0!==a&&(this.height=a),void 0!==c&&(this.rotation=c),void 0!==h&&(this.originParamU=h),void 0!==l&&(this.originParamV=l),void 0!==u&&(this.originAlignment=u)}}class Br{constructor(){this.type="parametric-model",this.name="text3d"}}class Mr{constructor(){this.index=0}}class Ir{}class Ur{}class Wr{constructor(e,t,r,i,n,s,o,a,c,h){this.faceTextVar=Ue.separatedExtrusion,this.text="bitbybit.dev",this.fontType=Me.Roboto,this.fontVariant=Ie.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=Ne.centerMiddle,void 0!==e&&(this.faceTextVar=e),void 0!==t&&(this.text=t),void 0!==r&&(this.fontType=r),void 0!==i&&(this.fontVariant=i),void 0!==n&&(this.fontSize=n),void 0!==s&&(this.height=s),void 0!==o&&(this.rotation=o),void 0!==a&&(this.originParamU=a),void 0!==c&&(this.originParamV=c),void 0!==h&&(this.originAlignment=h)}}class Nr{constructor(e,t,r){this.facePlanar=!1,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==r&&(this.definitions=r)}}class Gr{constructor(e,t,r,i){this.uNumber=10,this.vNumber=10,this.height=.2,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==i&&(this.height=i)}}class Hr{constructor(e,t,r,i,n,s,o){this.uNumber=10,this.vNumber=5,this.defaultHeight=.2,this.affectMinHeight=0,this.affectMaxHeight=1,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==t&&(this.affectorPoints=t),void 0!==r&&(this.uNumber=r),void 0!==i&&(this.vNumber=i),void 0!==n&&(this.affectMinHeight=n),void 0!==s&&(this.affectMaxHeight=s),void 0!==o&&(this.precision=o)}}class Vr{constructor(){this.type="parametric-model",this.name="patternsFacePatternPyramidSimple"}}class zr{constructor(){this.index=0}}class jr{}class qr{}class $r{}class Yr{}class Xr{constructor(){this.faceIndex=0}}class Zr{constructor(){this.faceIndex=0,this.uIndex=0,this.vIndex=0}}class Jr{constructor(){this.faceIndex=0,this.uIndex=0}}class Qr{constructor(){this.faceIndex=0,this.vIndex=0}}class Kr{}class ei{}var ti,ri,ii;!function(e){e.wire="wire",e.face="face",e.solid="solid"}(ti||(ti={}));class ni{static parse(e,t,r){const i=[e];let n=0;for(;i.length>0;){const e=i.pop();if("object"==typeof e&&null!==e)if(Array.isArray(e))for(let t=0;t{const a=o.shapes[e];if(a){const c=t.transforms.rotate({shape:a,angle:r,axis:[0,1,0]}),h=t.transforms.alignAndTranslate({shape:c,direction:i,center:n});1!==s[0]||1!==s[1]||1!==s[2]?(o.shapes[e]=t.transforms.scale3d({shape:h,scale:s,center:n}),h.delete()):o.shapes[e]=h,c.delete()}})),Object.keys(o).forEach((e=>{const a=o[e];a&&Array.isArray(a)?o[e]=a.map((e=>e&&"object"==typeof e&&null!==e&&e.shapes?this.alignAndTranslateShapesWithChildren(e,t,r,i,n,s):e)):a&&"object"==typeof a&&null!==a&&a.shapes&&(o[e]=this.alignAndTranslateShapesWithChildren(a,t,r,i,n,s))})),o}static deleteAllShapes(e){Object.keys(e.shapes).forEach((t=>{e.shapes[t].delete()})),Object.keys(e).forEach((t=>{const r=e[t];r&&Array.isArray(r)?r.forEach((e=>{e&&"object"==typeof e&&null!==e&&e.shapes&&this.deleteAllShapes(e)})):r&&"object"==typeof r&&null!==r&&r.shapes&&this.deleteAllShapes(r)}))}static deepCopy(e){const t=Object.assign(Object.assign({},e),{shapes:Object.assign({},e.shapes)});return Object.keys(e).forEach((r=>{const i=e[r];i&&"object"==typeof i&&null!==i?i.shapes&&(t[r]=this.deepCopy(i)):i&&Array.isArray(i)&&(t[r]=i.map((e=>e&&"object"==typeof e&&null!==e&&e.shapes?this.deepCopy(e):e)))})),t}}class si{constructor(e,t,r){this.occtService=e,this.dependencies=r,this.occtAdv=t}wingtipVilla(e){return function(e,t){!function(e){let t;if(["interiorWidth","interiorLength","interiorHeight","chimneyHeight","roofOverhang","thickness","holeDiameter","holeDistToBottom","stickDiameter","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.interiorWidth<=0?t=`interior width can't be ${e.interiorWidth}, which is lower or equal to 0`:e.interiorLength<=0?t=`interior length can't be ${e.interiorLength}, which is lower or equal to 0`:e.interiorHeight<=0?t=`interior height can't be ${e.interiorHeight}, which is lower or equal to 0`:e.chimneyHeight<=0?t=`chimney height can't be ${e.chimneyHeight}, which is lower or equal to 0`:e.interiorWidthe.holeDistToBottom&&(t="The stick diameter is larger than the hole's distance to bottom. Stick can't fit the surface. Model can't be made."),t)throw new Error(t)}(e);const r=e.baseAttachmentHeight,i=e.roofOverhang,n=e.chimneyHeight,s=(e.interiorWidth+2*e.thickness)/2,o=Le.computeSideA(45,s),a=function(e,t){const r=Math.pow(e,2)+Math.pow(t,2);return Math.sqrt(r)}(o,s),c=e.thickness,h=[],l=t.shapes.wire.createPolygonWire({points:[[-s,-r-c,0],[s,-r-c,0],[s,e.interiorHeight,0],[0,e.interiorHeight+o,0],[-s,e.interiorHeight,0]].reverse()});h.push(l);const u=e.interiorLength+e.thickness,d=t.shapes.wire.createPolygonWire({points:[[-s,-c,u],[s,-c,u],[s,e.interiorHeight,u],[0,e.interiorHeight+o,u],[-s,e.interiorHeight,u]].reverse()});h.push(d);const p=t.shapes.wire.createCircleWire({radius:e.holeDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom+e.holeDiameter/2,u]});h.push(p);const f=t.shapes.wire.createCircleWire({radius:e.stickDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom/2,u+c]});h.push(f);const g=t.shapes.face.createFaceFromWire({shape:f,planar:!0});h.push(g);const v=t.operations.extrude({shape:g,direction:[0,0,e.stickLength]}),m=t.shapes.solid.createBoxFromCorner({corner:[-s+c,-c,c],width:e.interiorWidth,length:e.interiorLength,height:c}),y=t.shapes.solid.createBoxFromCorner({corner:[-s,-c,c],width:c,length:e.interiorLength,height:e.interiorHeight+c}),S=t.shapes.solid.createBoxFromCorner({corner:[s-c,-c,c],width:c,length:e.interiorLength,height:e.interiorHeight+c}),b=t.shapes.solid.createBoxFromCorner({corner:[0,0,0],width:a+i,length:e.interiorLength+2*c+i,height:c}),w=t.shapes.solid.createBoxFromCorner({corner:[0,-c,0],width:a+i+c,length:e.interiorLength+2*c+i,height:c}),E=t.transforms.rotate({shape:b,angle:-45,axis:[0,0,1]});h.push(E);const T=t.transforms.translate({shape:E,translation:[0,e.interiorHeight+o,0]}),x=t.shapes.edge.getCornerPointsOfEdgesForShape({shape:T}),k=t.transforms.rotate({shape:w,angle:225,axis:[0,0,1]});h.push(k);const P=t.transforms.translate({shape:k,translation:x[3]}),C=t.shapes.face.createFaceFromWire({shape:l,planar:!0});h.push(C);const A=t.operations.makeThickSolidSimple({shape:C,offset:-e.thickness}),_=t.shapes.face.createFaceFromWire({shape:d,planar:!0});h.push(_);const O=t.operations.splitShapeWithShapes({shape:_,shapes:[p]});h.push(O);const D=t.shapes.face.getFace({shape:O,index:0});h.push(D);const R=t.operations.makeThickSolidSimple({shape:D,offset:-e.thickness}),F=function(e,t,r){const i=e.shapes.face.getFaces({shape:t})[3],n=e.shapes.face.getFaceCenterOfMass({shape:i}),s=e.transforms.scale3d({shape:i,scale:[.3,.3,.3],center:n}),o=e.shapes.edge.getCornerPointsOfEdgesForShape({shape:s}),a=o[0],c=o[1],h=o[2],l=o[3],u=Math.max(a[1],c[1],h[1],l[1]),d=[a[0],u+r,a[2]],p=[c[0],u+r,c[2]],f=[h[0],u+r,h[2]],g=[l[0],u+r,l[2]],v=e.shapes.wire.createPolygonWire({points:[a,c,h,l]}),m=e.shapes.wire.createPolygonWire({points:[d,p,f,g]}),y=e.operations.loft({shapes:[v,m],makeSolid:!0});return i.delete(),s.delete(),v.delete(),m.delete(),y}(t,T,n),L=[m,A,R,y,S,T,P,v,t.shapes.compound.makeCompound({shapes:[T,P]}),t.shapes.compound.makeCompound({shapes:[A,R,y,S]}),F],B=L.map(((r,i)=>{const n=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]});return t.transforms.translate({shape:n,translation:e.origin})})),M=t.shapes.compound.makeCompound({shapes:B});return L.forEach((e=>e.delete())),h.forEach((e=>e.delete())),{compound:M,shapes:B.map(((e,t)=>({id:t.toString(),shape:e}))),data:{type:"parametric-model",name:"wingtipVilla",roof:{compound:"8",shapes:["5","6"]},walls:{compound:"9",shapes:["1","2","3","4"]},floor:{shape:"0"},stick:{shape:"7"},chimney:{shape:"10"},basicPoints:[{kind:"origin",point:e.origin}]}}}(e,this.occtService)}chirpyChalet(e){return function(e,t){!function(e){let t;if(["interiorWidth","interiorLength","interiorHeight","roofAngle","roofOverhang","thickness","holeDiameter","holeDistToBottom","stickDiameter","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.interiorWidth<=0?t=`interior width can't be ${e.interiorWidth}, which is lower or equal to 0`:e.interiorLength<=0?t=`interior length can't be ${e.interiorLength}, which is lower or equal to 0`:e.interiorHeight<=0?t=`interior height can't be ${e.interiorHeight}, which is lower or equal to 0`:e.interiorWidthe.holeDistToBottom&&(t="The stick diameter is larger than the hole's distance to bottom. Stick can't fit the surface. Model can't be made."),t)throw new Error(t)}(e);const r=e.baseAttachmentHeight,i=e.roofOverhang,n=e.roofAngle,s=e.interiorWidth/2,o=e.interiorLength+2*e.thickness,a=Le.computeSideA(n,o),c=Le.computeSideA(n,o-e.thickness),h=function(e,t){const r=Math.pow(e,2)+Math.pow(t,2);return Math.sqrt(r)}(a,o),l=e.thickness,u=[],d=t.shapes.wire.createPolygonWire({points:[[-s,-r-l,0],[s,-r-l,0],[s,e.interiorHeight+c,0],[-s,e.interiorHeight+c,0]].reverse()});u.push(d);const p=e.interiorLength+e.thickness,f=t.shapes.wire.createPolygonWire({points:[[-s,-l,p],[s,-l,p],[s,e.interiorHeight,p],[-s,e.interiorHeight,p]].reverse()});u.push(f);const g=t.shapes.wire.createCircleWire({radius:e.holeDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom+e.holeDiameter/2,p]});u.push(g);const v=t.shapes.wire.createCircleWire({radius:e.stickDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom/2,p+l]});u.push(v);const m=t.shapes.face.createFaceFromWire({shape:v,planar:!0});u.push(m);const y=t.operations.extrude({shape:m,direction:[0,0,e.stickLength]}),S=t.shapes.solid.createBoxFromCorner({corner:[-s,-l,l],width:e.interiorWidth,length:e.interiorLength,height:l}),b=t.shapes.wire.createPolygonWire({points:[[-s,-l,0],[-s,-l,p+l],[-s,e.interiorHeight,p+l],[-s,e.interiorHeight+a,0]].reverse()}),w=t.shapes.face.createFaceFromWire({shape:b,planar:!0}),E=t.operations.extrude({shape:w,direction:[-l,0,0]}),T=t.transforms.translate({shape:E,translation:[e.interiorWidth+l,0,0]}),x=t.shapes.solid.createBoxFromCorner({corner:[-s-l-i,0,0],width:e.interiorWidth+2*l+2*i,length:h+i,height:l}),k=t.transforms.rotate({shape:x,angle:n,axis:[1,0,0]});u.push(k);const P=t.transforms.translate({shape:k,translation:[0,e.interiorHeight+a,0]}),C=t.shapes.face.createFaceFromWire({shape:d,planar:!0});u.push(C);const A=t.operations.makeThickSolidSimple({shape:C,offset:-e.thickness}),_=t.shapes.face.createFaceFromWire({shape:f,planar:!0});u.push(_);const O=t.operations.splitShapeWithShapes({shape:_,shapes:[g]});u.push(O);const D=t.shapes.face.getFace({shape:O,index:0});u.push(D);const R=t.operations.makeThickSolidSimple({shape:D,offset:-e.thickness}),F=[S,A,R,E,T,P,y,t.shapes.compound.makeCompound({shapes:[P]}),t.shapes.compound.makeCompound({shapes:[A,R,E,T]})],L=F.map(((r,i)=>{const n=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]});return t.transforms.translate({shape:n,translation:e.origin})})),B=t.shapes.compound.makeCompound({shapes:L});return F.forEach((e=>e.delete())),u.forEach((e=>e.delete())),{compound:B,shapes:L.map(((e,t)=>({id:t.toString(),shape:e}))),data:{type:"parametric-model",name:"chirpyChalet",roof:{compound:"7",shapes:["5","6"]},walls:{compound:"8",shapes:["1","2","3","4"]},floor:{shape:"0"},stick:{shape:"6"},basicPoints:[{kind:"origin",point:e.origin}]}}}(e,this.occtService)}serenitySwirl(t){return function(t,r,i){if(function(e){let t;if(["swirl","nrOfDivisions","addRadiusNarrow","addRadiusWide","addMiddleHeight","addTopHeight","thickness","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.swirl<0?t="swirl value should be between 0 and 1":e.nrOfDivisions<=0?t=`nrOfDivisions can't be ${e.nrOfDivisions}, which is lower or equal to 0`:e.addRadiusNarrow<0?t=`addRadiusNarrow can't be ${e.addRadiusNarrow}, which is lower then 0`:e.addRadiusWide<0?t=`addRadiusWide can't be ${e.addRadiusWide}, which is lower then 0`:e.addMiddleHeight<=0?t=`addMiddleHeight can't be ${e.addMiddleHeight}, which is lower or equal to 0`:e.addTopHeight<=0?t=`addTopHeight can't be ${e.addTopHeight}, which is lower or equal to 0`:e.thickness<=0?t=`thickness can't be ${e.thickness}, which is lower or equal to 0`:3!==e.origin.length&&(t="The origin should be a vector of 3 numbers."),t)throw new Error(t)}(t),!i.serenitySwirl)throw new Error("Could not compute, to use Serenity Swirl algorithm you must be subscribed.");try{const n=`\n ${i.serenitySwirl}\n `;return new Function(n).apply({inputs:t,occt:r,Inputs:e})}catch(e){throw new Error(e)}}(t,this.occtService,this.dependencies)}arabicArchway(t){return function(t,r,i){if(function(e){let t;if(["nrOfSides","thickness","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.nrOfSides<0?t="swirl value should be between 0 and 1":e.nrOfSides<3?t=`nrOfSides can't be ${e.nrOfSides}, which is lower to 3`:e.nrOfSides>30?t=`nrOfSides can't be ${e.nrOfSides}, which is higher then 30`:e.thickness<=0?t=`thickness can't be ${e.thickness}, which is lower or equal to 0`:3!==e.origin.length&&(t="The origin should be a vector of 3 numbers."),t)throw new Error(t)}(t),!i.arabicArchway)throw new Error("Could not compute, to use Arabic Archway algorithm you must be subscribed.");try{const n=`\n ${i.arabicArchway}\n `;return new Function(n).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.dependencies)}eternalLove(t){return function(t,r,i,n){if(!n.eternalLove)throw new Error("Could not compute, to use Eternal Love algorithm you must be subscribed to our silver plan.");try{const s=`\n ${n.eternalLove}\n `;return new Function(s).apply({inputs:t,occt:r,occtAdv:i,Inputs:e,Text3D:R})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}calmCup(t){return function(t,r,i,n){if(function(e){let t;if(["height","radiusBottom","radiusTopOffset","thickness","fillet","nrOfHandles","handleDist","precision","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.height<6*e.thickness?t="Height must be at least 6 times greater than thickness.":e.radiusBottom<=0?t="Radius bottom must be greater than 0.":e.thickness<=0?t="Thickness must be greater than 0.":e.fillet<0||e.fillet>e.thickness/2?t="Fillet must be greater than 0 and less than half of the thickness.":e.handleDist<=2*e.thickness?t="Handle distance from cup must be greater than 2 times the thickness.":e.nrOfHandles<0||e.nrOfHandles>2?t="Nr of handles must be between 0 and 2.":e.radiusTopOffset>.75*e.radiusBottom&&(t="Top offset radius must be less than 0.75 times the bottom radius."),t)throw new Error(t)}(t),!n.calmCup)throw new Error("Could not compute, to use Calm Cup algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.calmCup}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}spicyBox(t){return function(t,r,i,n){if(!n.spicyBox)throw new Error("Could not compute, to use Spicy Box algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.spicyBox}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}dragonCup(t){return function(t,r,i,n){if(function(e){let t;if(["height","radiusBottom","radiusTopOffset","thickness","nrSkinCellsHorizontal","nrSkinCellsVertical","precision","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.radiusBottom<=0?t="Radius bottom must be greater than 0.":e.thickness<=0?t="Thickness must be greater than 0.":e.nrSkinCellsHorizontal<=2?t="Nr of horizontal skin cells must be larger than 2.":e.nrSkinCellsVertical<1&&(t="Nr of horizontal skin cells must be larger than 0."),t)throw new Error(t)}(t),!n.dragonCup)throw new Error("Could not compute, to use Dragon Cup algorithm you must be subscribed to our silver plan.");try{const s=`\n ${n.dragonCup}\n `;return new Function(s).apply({inputs:t,occt:r,occtAdv:i,Inputs:e,Advanced:G})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}zenHideout(t){return function(t,r,i){if(function(e){let t;if([].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),t)throw new Error(t)}(t),!i.zenHideout)throw new Error("Could not compute, to use Zen Hideout algorithm you must be subscribed.");try{const n=`\n ${i.zenHideout}\n `;return new Function(n).apply({inputs:t,occt:r,Inputs:e,Things:D,MathHelper:Le,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.dependencies)}elegantTable(t){return function(t,r,i,n){if(!n.elegantTable)throw new Error("Could not compute, to use Elegant Table algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.elegantTable}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}goodCoffeeTable(t){return function(t,r,i,n){if(function(e){let t;if(["height","width","length","topThickness","topGlassOffset","glassThickness","glassHolderLength","chamfer","legWidth","legDepth","precision","rotation","scale"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.height<=e.topThickness?t="Height must be greated then top thickness.":e.width<=0?t="Width must be greater than 0.":e.width<=2*(e.topGlassOffset+e.glassHolderLength)?t="Width must be greater than two top glass offsets and glass holder lengths.":e.length<=0?t="Length must be greater than 0.":e.length<=2*(e.topGlassOffset+e.glassHolderLength)?t="Length must be greater than two top glass offsets and glass holder lengths.":e.topThickness<=2*e.glassThickness?t="Table top thickness must be greater 2 x glass thickness.":e.glassThickness<=0?t="Glass thickness must be greater than 0":e.glassHolderLengthe.height-e.topThickness-e.shelfThickness?t=`Shelf top offset is larger than ${e.height-e.topThickness-e.shelfThickness}, which make it go underground.`:e.chamfer>=e.topThickness/2?t="Chamfer distance must be lower or equal than half of the top thickness.":e.chamfer>=e.shelfThickness/2?t="Chamfer distance must be lower or equal than half of the shelf thickness.":e.chamfer>=e.topGlassOffset/2?t="Chamfer distance must be lower or equal than half of the top glass offset.":e.chamfer>=e.legWidth/2?t="Chamfer distance must be lower or equal than half of the leg width.":e.chamfer>=e.legDepth/2?t="Chamfer distance must be lower or equal than half of the leg depth.":e.width<=2*e.legWidth?t="Width of the table must be greater or equal to the width of the two legs.":e.length<=2*e.legDepth?t="Length of the table must be greater or equal to the length of the two legs.":e.legDepth>=e.topGlassOffset+e.glassHolderLength?t="The depth of the leg must be lower or equal to the sum of glass offset and glass holder length.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!n.goodCoffeeTable)throw new Error("Could not compute, to use Good Coffee Table algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.goodCoffeeTable}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}snakeChair(t){return function(t,r,i,n){if(function(e){let t;if(["sittingHeight","backRestOffset","backRestHeight","width","length","thickness","ornamentDepth","nrOrnamentPlanks","filletRadius","precision","rotation","scale"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.sittingHeight<=2*e.thickness?t="Sitting height must be greater than 2 x thickness.":e.backRestOffset<0?t="Back rest offset can't be negative.":e.backRestHeight<=0?t="Back rest height must be greater than 0":e.width<=0?t="Width must be greater than 0.":e.length<=2*e.thickness?t="Length height must be greater than 2 x thickness.":e.thickness<=0?t="Width must be greater than 0.":e.nrOrnamentPlanks<0?t="Number of ornament planks must be greater than 0":e.filletRadius<=0?t="Fillet radius must be greater than 0.":e.filletRadius>=e.sittingHeight/2?t="Fillet radius must be lower than half of the sitting height.":e.filletRadius>=e.length/2?t="Fillet radius must be lower than half of the length.":e.filletRadius>=e.backRestHeight/2?t="Fillet radius must be lower than half of the back height.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!n.snakeChair)throw new Error("Could not compute, to use Snake Chair algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.snakeChair}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}snakeTable(t){return function(t,r,i,n){if(function(e){let t;if(["height","width","length","shelfHeight","supportLength","glassThickness","glassOffset","thickness","ornamentDepth","nrOrnamentPlanks","filletRadius","precision","rotation","scale"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.height<=2*e.thickness?t="Sitting height must be greater than 2 x thickness.":e.width<=0?t="Width must be greater than 0.":e.length<=2*e.thickness?t="Length height must be greater than 2 x thickness.":e.thickness<=0?t="Width must be greater than 0.":e.nrOrnamentPlanks<0?t="Number of ornament planks must be greater than 0":e.filletRadius<=0?t="Fillet radius must be greater than 0.":e.filletRadius>=e.height/2?t="Fillet radius must be lower than half of the sitting height.":e.filletRadius>=e.length/2?t="Fillet radius must be lower than half of the length.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!n.snakeTable)throw new Error("Could not compute, to use Snake Table algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.snakeTable}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}phoneNest(t){return function(t,r,i,n){if(!n.phoneNest)throw new Error("Could not compute, to use Phone Nest algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.phoneNest}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}}function oi(e,t,r,i){const n=r.find((t=>t.name===`${e.fontType}-${e.fontVariant}`));if(!n)throw new Error(`Font ${e.fontType}-${e.fontVariant}.ttf does not exist. Current font probably does not have corresponding variant.`);const s=n.font.getPath(e.text,0,0,e.fontSize),o=[];let a=n.font.getPaths(e.text,0,0,e.fontSize,{});const c=n.font.getAdvanceWidth(e.text,e.fontSize),h=s.getBoundingBox();switch(e.originAlignment){case Ne.leftBottom:break;case Ne.leftMiddle:a=n.font.getPaths(e.text,0,(h.y2-h.y1)/2,e.fontSize,{});break;case Ne.leftTop:a=n.font.getPaths(e.text,0,h.y2-h.y1,e.fontSize,{});break;case Ne.centerBottom:a=n.font.getPaths(e.text,-(h.x2-h.x1)/2,0,e.fontSize,{});break;case Ne.centerMiddle:a=n.font.getPaths(e.text,-(h.x2-h.x1)/2,(h.y2-h.y1)/2,e.fontSize,{});break;case Ne.centerTop:a=n.font.getPaths(e.text,-(h.x2-h.x1)/2,h.y2-h.y1,e.fontSize,{});break;case Ne.rightBottom:a=n.font.getPaths(e.text,-(h.x2-h.x1),0,e.fontSize,{});break;case Ne.rightMiddle:a=n.font.getPaths(e.text,-(h.x2-h.x1),(h.y2-h.y1)/2,e.fontSize,{});break;case Ne.rightTop:a=n.font.getPaths(e.text,-(h.x2-h.x1),h.y2-h.y1,e.fontSize,{})}a.forEach((e=>{const r=e.commands,n=[];let s,a,c;for(let e=0;e0?new i.BRepBuilderAPI_MakeFace_22(n[n.length-1],c.Wire()):new i.BRepBuilderAPI_MakeFace_15(c.Wire(),!0),n.push(e.Face()),e.delete(),c.delete()}catch(e){console.error("We could not create faces from this font probably due to self intersections! You should try removing weird characters and pick a more reliable font like 'Roboto'.")}else if("L"===o.type){const e=[-o.x,0,o.y];if(a[0]===e[0]&&a[2]===e[2])continue;const r=t.shapes.edge.line({start:a,end:e});c.Add_1(r),r.delete(),a=e}else if("Q"===o.type){const e=[-o.x1,0,o.y1],r=[-o.x,0,o.y],i=[a,e,r],n=t.shapes.wire.createBezier({points:i,closed:!1});c.Add_2(n),n.delete(),a=r}else if("C"===o.type){const e=[-o.x,0,o.y],r=[a,[-o.x1,0,o.y1],[-o.x2,0,o.y2],e],i=t.shapes.wire.createBezier({points:r,closed:!1});c.Add_2(i),i.delete(),a=e}}if(void 0!==n[n.length-1]){const e=n[n.length-1],r=new U.BasicShapeRepairDto;r.shape=e,r.minTolerance=1e-8,r.maxTolerance=1e-4,r.precision=.001;const i=t.shapeFix.basicShapeRepair(r);e.delete(),o.push(i)}}));const l=new Br;if(l.advanceWidth=c,l.boundingBox={x1:h.x1,y1:h.y1,x2:h.x2,y2:h.y2},e.height>0){const r=o.map((r=>t.operations.extrude({shape:r,direction:[0,e.height,0]})));o.forEach((e=>e.delete()));const i=r.map((r=>{const i=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]}),n=t.transforms.alignAndTranslate({shape:i,center:e.origin,direction:e.direction});return i.delete(),n}));i.reverse();const n=t.shapes.solid.getSolidsCentersOfMass({shapes:i});l.characterCenterCoordinates=n;const s=t.shapes.compound.makeCompound({shapes:i});return l.characterParts=i.map(((e,t)=>({id:`character-${t.toString()}`,shapes:{compound:e}}))),ai(l,s)}{const r=o.map((r=>{const i=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]}),n=t.transforms.alignAndTranslate({shape:i,center:e.origin,direction:e.direction});return i.delete(),n}));r.reverse(),o.forEach((e=>e.delete()));const i=t.shapes.face.getFacesCentersOfMass({shapes:r});l.characterCenterCoordinates=i;const n=t.shapes.compound.makeCompound({shapes:r});return l.characterParts=r.map(((e,t)=>({id:`character-${t.toString()}`,shapes:{compound:e}}))),ai(l,n)}}function ai(e,t){if(e){const r=[],i=ni.parse(e,r,"text-3d");return{compound:t,shapes:[{id:"1",shape:t},...r],data:Object.assign({compound:"1"},i)}}}String.prototype.codePointAt||(ii=function(e){if(null==this)throw TypeError();var t=String(this),r=t.length,i=e?Number(e):0;if(i!=i&&(i=0),!(i<0||i>=r)){var n,s=t.charCodeAt(i);return s>=55296&&s<=56319&&r>i+1&&(n=t.charCodeAt(i+1))>=56320&&n<=57343?1024*(s-55296)+n-56320+65536:s}},(ri=function(){try{var e={},t=Object.defineProperty,r=t(e,e,e)&&t}catch(e){}return r}())?ri(String.prototype,"codePointAt",{value:ii,configurable:!0,writable:!0}):String.prototype.codePointAt=ii);function ci(){this.table=new Uint16Array(16),this.trans=new Uint16Array(288)}function hi(e,t){this.source=e,this.sourceIndex=0,this.tag=0,this.bitcount=0,this.dest=t,this.destLen=0,this.ltree=new ci,this.dtree=new ci}var li=new ci,ui=new ci,di=new Uint8Array(30),pi=new Uint16Array(30),fi=new Uint8Array(30),gi=new Uint16Array(30),vi=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),mi=new ci,yi=new Uint8Array(320);function Si(e,t,r,i){var n,s;for(n=0;n>>=1,t}function Ti(e,t,r){if(!t)return r;for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>16-t;return e.tag>>>=t,e.bitcount-=t,i+r}function xi(e,t){for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>=1,++n,r+=t.table[n],i-=t.table[n]}while(i>=0);return e.tag=s,e.bitcount-=n,t.trans[r+i]}function ki(e,t,r){var i,n,s,o,a,c;for(i=Ti(e,5,257),n=Ti(e,5,1),s=Ti(e,4,4),o=0;o<19;++o)yi[o]=0;for(o=0;o8;)e.sourceIndex--,e.bitcount-=8;if((t=256*(t=e.source[e.sourceIndex+1])+e.source[e.sourceIndex])!==(65535&~(256*e.source[e.sourceIndex+3]+e.source[e.sourceIndex+2])))return-3;for(e.sourceIndex+=4,r=t;r;--r)e.dest[e.destLen++]=e.source[e.sourceIndex++];return e.bitcount=0,0}!function(e,t){var r;for(r=0;r<7;++r)e.table[r]=0;for(e.table[7]=24,e.table[8]=152,e.table[9]=112,r=0;r<24;++r)e.trans[r]=256+r;for(r=0;r<144;++r)e.trans[24+r]=r;for(r=0;r<8;++r)e.trans[168+r]=280+r;for(r=0;r<112;++r)e.trans[176+r]=144+r;for(r=0;r<5;++r)t.table[r]=0;for(t.table[5]=32,r=0;r<32;++r)t.trans[r]=r}(li,ui),Si(di,pi,4,3),Si(fi,gi,2,1),di[28]=0,pi[28]=258;var Ai=function(e,t){var r,i,n=new hi(e,t);do{switch(r=Ei(n),Ti(n,2,0)){case 0:i=Ci(n);break;case 1:i=Pi(n,li,ui);break;case 2:ki(n,n.ltree,n.dtree),i=Pi(n,n.ltree,n.dtree);break;default:i=-3}if(0!==i)throw new Error("Data error")}while(!r);return n.destLenthis.x2&&(this.x2=e)),"number"==typeof t&&((isNaN(this.y1)||isNaN(this.y2))&&(this.y1=t,this.y2=t),tthis.y2&&(this.y2=t))},Oi.prototype.addX=function(e){this.addPoint(e,null)},Oi.prototype.addY=function(e){this.addPoint(null,e)},Oi.prototype.addBezier=function(e,t,r,i,n,s,o,a){var c=[e,t],h=[r,i],l=[n,s],u=[o,a];this.addPoint(e,t),this.addPoint(o,a);for(var d=0;d<=1;d++){var p=6*c[d]-12*h[d]+6*l[d],f=-3*c[d]+9*h[d]-9*l[d]+3*u[d],g=3*h[d]-3*c[d];if(0!==f){var v=Math.pow(p,2)-4*g*f;if(!(v<0)){var m=(-p+Math.sqrt(v))/(2*f);0=0&&i>0&&(r+=" "),r+=t(n)}return r}e=void 0!==e?e:2;for(var i="",n=0;n"},Di.prototype.toDOMElement=function(e){var t=this.toPathData(e),r=document.createElementNS("http://www.w3.org/2000/svg","path");return r.setAttribute("d",t),r};var Li={fail:Ri,argument:Fi,assert:Fi},Bi=2147483648,Mi={},Ii={},Ui={};function Wi(e){return function(){return e}}Ii.BYTE=function(e){return Li.argument(e>=0&&e<=255,"Byte value should be between 0 and 255."),[e]},Ui.BYTE=Wi(1),Ii.CHAR=function(e){return[e.charCodeAt(0)]},Ui.CHAR=Wi(1),Ii.CHARARRAY=function(e){void 0===e&&(e="",console.warn("Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name."));for(var t=[],r=0;r>8&255,255&e]},Ui.USHORT=Wi(2),Ii.SHORT=function(e){return e>=32768&&(e=-(65536-e)),[e>>8&255,255&e]},Ui.SHORT=Wi(2),Ii.UINT24=function(e){return[e>>16&255,e>>8&255,255&e]},Ui.UINT24=Wi(3),Ii.ULONG=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.ULONG=Wi(4),Ii.LONG=function(e){return e>=Bi&&(e=-(2*Bi-e)),[e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.LONG=Wi(4),Ii.FIXED=Ii.ULONG,Ui.FIXED=Ui.ULONG,Ii.FWORD=Ii.SHORT,Ui.FWORD=Ui.SHORT,Ii.UFWORD=Ii.USHORT,Ui.UFWORD=Ui.USHORT,Ii.LONGDATETIME=function(e){return[0,0,0,0,e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.LONGDATETIME=Wi(8),Ii.TAG=function(e){return Li.argument(4===e.length,"Tag should be exactly 4 ASCII characters."),[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]},Ui.TAG=Wi(4),Ii.Card8=Ii.BYTE,Ui.Card8=Ui.BYTE,Ii.Card16=Ii.USHORT,Ui.Card16=Ui.USHORT,Ii.OffSize=Ii.BYTE,Ui.OffSize=Ui.BYTE,Ii.SID=Ii.USHORT,Ui.SID=Ui.USHORT,Ii.NUMBER=function(e){return e>=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?Ii.NUMBER16(e):Ii.NUMBER32(e)},Ui.NUMBER=function(e){return Ii.NUMBER(e).length},Ii.NUMBER16=function(e){return[28,e>>8&255,255&e]},Ui.NUMBER16=Wi(3),Ii.NUMBER32=function(e){return[29,e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.NUMBER32=Wi(5),Ii.REAL=function(e){var t=e.toString(),r=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(t);if(r){var i=parseFloat("1e"+((r[2]?+r[2]:0)+r[1].length));t=(Math.round(e*i)/i).toString()}for(var n="",s=0,o=t.length;s>8&255,t[t.length]=255&i}return t},Ui.UTF16=function(e){return 2*e.length};var Ni={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};Mi.MACSTRING=function(e,t,r,i){var n=Ni[i];if(void 0!==n){for(var s="",o=0;o=-128&&e<=127}function zi(e,t,r){for(var i=0,n=e.length;t>8&255,c+256&255)}return s}Ii.MACSTRING=function(e,t){var r=function(e){if(!Gi)for(var t in Gi={},Ni)Gi[t]=new String(t);var r=Gi[e];if(void 0!==r){if(Hi){var i=Hi.get(r);if(void 0!==i)return i}var n=Ni[e];if(void 0!==n){for(var s={},o=0;o=128&&void 0===(s=r[s]))return;i[n]=s}return i}},Ui.MACSTRING=function(e,t){var r=Ii.MACSTRING(e,t);return void 0!==r?r.length:0},Ii.VARDELTAS=function(e){for(var t=0,r=[];t=-128&&i<=127?ji(e,t,r):qi(e,t,r)}return r},Ii.INDEX=function(e){for(var t=1,r=[t],i=[],n=0;n>8,t[u+1]=255&d,t=t.concat(i[l])}return t},Ui.TABLE=function(e){for(var t=0,r=e.fields.length,i=0;i0)return new hn(this.data,this.offset+t).parseStruct(e)},hn.prototype.parsePointer32=function(e){var t=this.parseOffset32();if(t>0)return new hn(this.data,this.offset+t).parseStruct(e)},hn.prototype.parseListOfLists=function(e){for(var t=this.parseOffset16List(),r=t.length,i=this.relativeOffset,n=new Array(r),s=0;s=0;n-=1){var s=un.getUShort(e,t+4+8*n),o=un.getUShort(e,t+4+8*n+2);if(3===s&&(0===o||1===o||10===o)||0===s&&(0===o||1===o||2===o||3===o||4===o)){i=un.getULong(e,t+4+8*n+4);break}}if(-1===i)throw new Error("No valid cmap sub-tables found.");var a=new un.Parser(e,t+i);if(r.format=a.parseUShort(),12===r.format)!function(e,t){var r;t.parseUShort(),e.length=t.parseULong(),e.language=t.parseULong(),e.groupCount=r=t.parseULong(),e.glyphIndexMap={};for(var i=0;i>1,t.skip("uShort",3),e.glyphIndexMap={};for(var o=new un.Parser(r,i+n+14),a=new un.Parser(r,i+n+16+2*s),c=new un.Parser(r,i+n+16+4*s),h=new un.Parser(r,i+n+16+6*s),l=i+n+16+8*s,u=0;u0;t-=1)if(e.get(t).unicode>65535){console.log("Adding CMAP format 12 (needed!)"),r=!1;break}var i=[{name:"version",type:"USHORT",value:0},{name:"numTables",type:"USHORT",value:r?1:2},{name:"platformID",type:"USHORT",value:3},{name:"encodingID",type:"USHORT",value:1},{name:"offset",type:"ULONG",value:r?12:20}];r||(i=i.concat([{name:"cmap12PlatformID",type:"USHORT",value:3},{name:"cmap12EncodingID",type:"USHORT",value:10},{name:"cmap12Offset",type:"ULONG",value:0}])),i=i.concat([{name:"format",type:"USHORT",value:4},{name:"cmap4Length",type:"USHORT",value:0},{name:"language",type:"USHORT",value:0},{name:"segCountX2",type:"USHORT",value:0},{name:"searchRange",type:"USHORT",value:0},{name:"entrySelector",type:"USHORT",value:0},{name:"rangeShift",type:"USHORT",value:0}]);var n=new rn.Table("cmap",i);for(n.segments=[],t=0;t>4,s=15&i;if(15===n)break;if(t+=r[n],15===s)break;t+=r[s]}return parseFloat(t)}(e);if(t>=32&&t<=246)return t-139;if(t>=247&&t<=250)return 256*(t-247)+e.parseByte()+108;if(t>=251&&t<=254)return 256*-(t-251)-e.parseByte()-108;throw new Error("Invalid b0 "+t)}function Dn(e,t,r){t=void 0!==t?t:0;var i=new un.Parser(e,t),n=[],s=[];for(r=void 0!==r?r:e.length;i.relativeOffset>1,d.length=0,f=!0}return function r(h){for(var y,S,T,x,k,P,C,A,_,O,D,R,F=0;F1&&!f&&(b=d.shift()+l,f=!0),m+=d.pop(),w(v,m);break;case 5:for(;d.length>0;)v+=d.shift(),m+=d.shift(),u.lineTo(v,m);break;case 6:for(;d.length>0&&(v+=d.shift(),u.lineTo(v,m),0!==d.length);)m+=d.shift(),u.lineTo(v,m);break;case 7:for(;d.length>0&&(m+=d.shift(),u.lineTo(v,m),0!==d.length);)v+=d.shift(),u.lineTo(v,m);break;case 8:for(;d.length>0;)i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+d.shift(),u.curveTo(i,n,s,o,v,m);break;case 10:k=d.pop()+c,(P=a[k])&&r(P);break;case 11:return;case 12:switch(L=h[F],F+=1,L){case 35:i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),C=s+d.shift(),A=o+d.shift(),_=C+d.shift(),O=A+d.shift(),D=_+d.shift(),R=O+d.shift(),v=D+d.shift(),m=R+d.shift(),d.shift(),u.curveTo(i,n,s,o,C,A),u.curveTo(_,O,D,R,v,m);break;case 34:i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),C=s+d.shift(),A=o,_=C+d.shift(),O=o,D=_+d.shift(),R=m,v=D+d.shift(),u.curveTo(i,n,s,o,C,A),u.curveTo(_,O,D,R,v,m);break;case 36:i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),C=s+d.shift(),A=o,_=C+d.shift(),O=o,D=_+d.shift(),R=O+d.shift(),v=D+d.shift(),u.curveTo(i,n,s,o,C,A),u.curveTo(_,O,D,R,v,m);break;case 37:i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),C=s+d.shift(),A=o+d.shift(),_=C+d.shift(),O=A+d.shift(),D=_+d.shift(),R=O+d.shift(),Math.abs(D-v)>Math.abs(R-m)?v=D+d.shift():m=R+d.shift(),u.curveTo(i,n,s,o,C,A),u.curveTo(_,O,D,R,v,m);break;default:console.log("Glyph "+t.index+": unknown operator 1200"+L),d.length=0}break;case 14:d.length>0&&!f&&(b=d.shift()+l,f=!0),g&&(u.closePath(),g=!1);break;case 19:case 20:E(),F+=p+7>>3;break;case 21:d.length>2&&!f&&(b=d.shift()+l,f=!0),m+=d.pop(),w(v+=d.pop(),m);break;case 22:d.length>1&&!f&&(b=d.shift()+l,f=!0),w(v+=d.pop(),m);break;case 24:for(;d.length>2;)i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+d.shift(),u.curveTo(i,n,s,o,v,m);v+=d.shift(),m+=d.shift(),u.lineTo(v,m);break;case 25:for(;d.length>6;)v+=d.shift(),m+=d.shift(),u.lineTo(v,m);i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+d.shift(),u.curveTo(i,n,s,o,v,m);break;case 26:for(d.length%2&&(v+=d.shift());d.length>0;)i=v,n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s,m=o+d.shift(),u.curveTo(i,n,s,o,v,m);break;case 27:for(d.length%2&&(m+=d.shift());d.length>0;)i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o,u.curveTo(i,n,s,o,v,m);break;case 28:y=h[F],S=h[F+1],d.push((y<<24|S<<16)>>16),F+=2;break;case 29:k=d.pop()+e.gsubrsBias,(P=e.gsubrs[k])&&r(P);break;case 30:for(;d.length>0&&(i=v,n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m),0!==d.length);)i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),m=o+d.shift(),v=s+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m);break;case 31:for(;d.length>0&&(i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),m=o+d.shift(),v=s+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m),0!==d.length);)i=v,n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m);break;default:L<32?console.log("Glyph "+t.index+": unknown operator "+L):L<247?d.push(L-139):L<251?(y=h[F],F+=1,d.push(256*(L-247)+y+108)):L<255?(y=h[F],F+=1,d.push(256*-(L-251)-y-108)):(y=h[F],S=h[F+1],T=h[F+2],x=h[F+3],F+=4,d.push((y<<24|S<<16|T<<8|x)/65536))}}}(r),t.advanceWidth=b,u}function Nn(e,t){var r,i=fn.indexOf(e);return i>=0&&(r=i),(i=t.indexOf(e))>=0?r=i+fn.length:(r=fn.length+t.length,t.push(e)),r}function Gn(e,t,r){for(var i={},n=0;n=i)throw new Error("CFF table CID Font FDSelect has bad FD index value "+n+" (FD count "+i+")");s.push(n)}else{if(3!==a)throw new Error("CFF Table CID Font FDSelect table has unsupported format "+a);var h,l=o.parseCard16(),u=o.parseCard16();if(0!==u)throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID "+u);for(var d=0;d=i)throw new Error("CFF table CID Font FDSelect has bad FD index value "+n+" (FD count "+i+")");if(h>r)throw new Error("CFF Table CID Font FDSelect format 3 range has bad GID "+h);for(;u=1&&(r.ulCodePageRange1=i.parseULong(),r.ulCodePageRange2=i.parseULong()),r.version>=2&&(r.sxHeight=i.parseShort(),r.sCapHeight=i.parseShort(),r.usDefaultChar=i.parseUShort(),r.usBreakChar=i.parseUShort(),r.usMaxContent=i.parseUShort()),r},make:function(e){return new rn.Table("OS/2",[{name:"version",type:"USHORT",value:3},{name:"xAvgCharWidth",type:"SHORT",value:0},{name:"usWeightClass",type:"USHORT",value:0},{name:"usWidthClass",type:"USHORT",value:0},{name:"fsType",type:"USHORT",value:0},{name:"ySubscriptXSize",type:"SHORT",value:650},{name:"ySubscriptYSize",type:"SHORT",value:699},{name:"ySubscriptXOffset",type:"SHORT",value:0},{name:"ySubscriptYOffset",type:"SHORT",value:140},{name:"ySuperscriptXSize",type:"SHORT",value:650},{name:"ySuperscriptYSize",type:"SHORT",value:699},{name:"ySuperscriptXOffset",type:"SHORT",value:0},{name:"ySuperscriptYOffset",type:"SHORT",value:479},{name:"yStrikeoutSize",type:"SHORT",value:49},{name:"yStrikeoutPosition",type:"SHORT",value:258},{name:"sFamilyClass",type:"SHORT",value:0},{name:"bFamilyType",type:"BYTE",value:0},{name:"bSerifStyle",type:"BYTE",value:0},{name:"bWeight",type:"BYTE",value:0},{name:"bProportion",type:"BYTE",value:0},{name:"bContrast",type:"BYTE",value:0},{name:"bStrokeVariation",type:"BYTE",value:0},{name:"bArmStyle",type:"BYTE",value:0},{name:"bLetterform",type:"BYTE",value:0},{name:"bMidline",type:"BYTE",value:0},{name:"bXHeight",type:"BYTE",value:0},{name:"ulUnicodeRange1",type:"ULONG",value:0},{name:"ulUnicodeRange2",type:"ULONG",value:0},{name:"ulUnicodeRange3",type:"ULONG",value:0},{name:"ulUnicodeRange4",type:"ULONG",value:0},{name:"achVendID",type:"CHARARRAY",value:"XXXX"},{name:"fsSelection",type:"USHORT",value:0},{name:"usFirstCharIndex",type:"USHORT",value:0},{name:"usLastCharIndex",type:"USHORT",value:0},{name:"sTypoAscender",type:"SHORT",value:0},{name:"sTypoDescender",type:"SHORT",value:0},{name:"sTypoLineGap",type:"SHORT",value:0},{name:"usWinAscent",type:"USHORT",value:0},{name:"usWinDescent",type:"USHORT",value:0},{name:"ulCodePageRange1",type:"ULONG",value:0},{name:"ulCodePageRange2",type:"ULONG",value:0},{name:"sxHeight",type:"SHORT",value:0},{name:"sCapHeight",type:"SHORT",value:0},{name:"usDefaultChar",type:"USHORT",value:0},{name:"usBreakChar",type:"USHORT",value:0},{name:"usMaxContext",type:"USHORT",value:0}],e)},unicodeRanges:ls,getUnicodeRange:function(e){for(var t=0;t=r.begin&&e=mn.length){var o=i.parseChar();r.names.push(i.parseString(o))}break;case 2.5:r.numberOfGlyphs=i.parseUShort(),r.offset=new Array(r.numberOfGlyphs);for(var a=0;at.value.tag?1:-1})),t.fields=t.fields.concat(i),t.fields=t.fields.concat(n),t}function Es(e,t,r){for(var i=0;i0)return e.glyphs.get(n).getMetrics()}return r}function Ts(e){for(var t=0,r=0;rv||void 0===t)&&v>0&&(t=v),h 123 are reserved for internal usage");p|=1<0?Xn.make(R):void 0,B=ds.make(),M=jn.make(e.glyphs,{version:e.getEnglishName("version"),fullName:A,familyName:P,weightName:C,postScriptName:_,unitsPerEm:e.unitsPerEm,fontBBox:[0,S.yMin,S.ascender,S.advanceWidthMax]}),I=e.metas&&Object.keys(e.metas).length>0?ms.make(e.metas):void 0,U=[b,w,E,T,F,k,B,M,x];L&&U.push(L),e.tables.gsub&&U.push(vs.make(e.tables.gsub)),I&&U.push(I);for(var W=ws(U),N=Ss(W.encode()),G=W.fields,H=!1,V=0;V>>1,s=e[n].tag;if(s===t)return n;s>>1,s=e[n];if(s===t)return n;s>>1,o=(r=e[s]).start;if(o===t)return r;o0)return t>(r=e[i-1]).end?0:r}function As(e,t){this.font=e,this.tableName=t}function _s(e){As.call(this,e,"gpos")}function Os(e){As.call(this,e,"gsub")}function Ds(e,t){var r=e.length;if(r!==t.length)return!1;for(var i=0;i0?(s=e.parseByte(),t&n||(s=-s),s=r+s):s=(t&n)>0?r:r+e.parseShort(),s}function Bs(e,t,r){var i,n,s=new un.Parser(t,r);if(e.numberOfContours=s.parseShort(),e._xMin=s.parseShort(),e._yMin=s.parseShort(),e._xMax=s.parseShort(),e._yMax=s.parseShort(),e.numberOfContours>0){for(var o=e.endPointIndices=[],a=0;a0)for(var u=s.parseByte(),d=0;d0){var p,f=[];if(h>0){for(var g=0;g=0,f.push(p);for(var v=0,m=0;m0?(2&i)>0?(w.dx=s.parseShort(),w.dy=s.parseShort()):w.matchedPoints=[s.parseUShort(),s.parseUShort()]:(2&i)>0?(w.dx=s.parseChar(),w.dy=s.parseChar()):w.matchedPoints=[s.parseByte(),s.parseByte()],(8&i)>0?w.xScale=w.yScale=s.parseF2Dot14():(64&i)>0?(w.xScale=s.parseF2Dot14(),w.yScale=s.parseF2Dot14()):(128&i)>0&&(w.xScale=s.parseF2Dot14(),w.scale01=s.parseF2Dot14(),w.scale10=s.parseF2Dot14(),w.yScale=s.parseF2Dot14()),e.components.push(w),b=!!(32&i)}if(256&i){e.instructionLength=s.parseUShort(),e.instructions=[];for(var E=0;Et.points.length-1||i.matchedPoints[1]>n.points.length-1)throw Error("Matched points out of range in "+t.name);var o=t.points[i.matchedPoints[0]],a=n.points[i.matchedPoints[1]],c={xScale:i.xScale,scale01:i.scale01,scale10:i.scale10,yScale:i.yScale,dx:0,dy:0};a=Ms([a],c)[0],c.dx=o.x-a.x,c.dy=o.y-a.y,s=Ms(n.points,c)}t.points=t.points.concat(s)}}return Is(t.points)}As.prototype={searchTag:ks,binSearch:Ps,getTable:function(e){var t=this.font.tables[this.tableName];return!t&&e&&(t=this.font.tables[this.tableName]=this.createDefaultTable()),t},getScriptNames:function(){var e=this.getTable();return e?e.scripts.map((function(e){return e.tag})):[]},getDefaultScriptName:function(){var e=this.getTable();if(e){for(var t=!1,r=0;r=0)return i[n].script;if(t){var s={tag:e,script:{defaultLangSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]},langSysRecords:[]}};return i.splice(-1-n,0,s),s.script}}},getLangSysTable:function(e,t,r){var i=this.getScriptTable(e,r);if(i){if(!t||"dflt"===t||"DFLT"===t)return i.defaultLangSys;var n=ks(i.langSysRecords,t);if(n>=0)return i.langSysRecords[n].langSys;if(r){var s={tag:t,langSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]}};return i.langSysRecords.splice(-1-n,0,s),s.langSys}}},getFeatureTable:function(e,t,r,i){var n=this.getLangSysTable(e,t,i);if(n){for(var s,o=n.featureIndexes,a=this.font.tables[this.tableName].features,c=0;c=a[h-1].tag,"Features must be added in alphabetical order."),s={tag:r,feature:{params:0,lookupListIndexes:[]}},a.push(s),o.push(h),s.feature}}},getLookupTables:function(e,t,r,i,n){var s=this.getFeatureTable(e,t,r,n),o=[];if(s){for(var a,c=s.lookupListIndexes,h=this.font.tables[this.tableName].lookups,l=0;l=0?r:-1;case 2:var i=Cs(e.ranges,t);return i?i.index+t-i.start:-1}},expandCoverage:function(e){if(1===e.format)return e.glyphs;for(var t=[],r=e.ranges,i=0;i1,'Multiple: "by" must be an array of two or more ids');var n=Rs(this.getLookupTables(r,i,e,2,!0)[0],1,{substFormat:1,coverage:{format:1,glyphs:[]},sequences:[]});Li.assert(1===n.coverage.format,"Multiple: unable to modify coverage table format "+n.coverage.format);var s=t.sub,o=this.binSearch(n.coverage.glyphs,s);o<0&&(o=-1-o,n.coverage.glyphs.splice(o,0,s),n.sequences.splice(o,0,0)),n.sequences[o]=t.by},Os.prototype.addAlternate=function(e,t,r,i){var n=Rs(this.getLookupTables(r,i,e,3,!0)[0],1,{substFormat:1,coverage:{format:1,glyphs:[]},alternateSets:[]});Li.assert(1===n.coverage.format,"Alternate: unable to modify coverage table format "+n.coverage.format);var s=t.sub,o=this.binSearch(n.coverage.glyphs,s);o<0&&(o=-1-o,n.coverage.glyphs.splice(o,0,s),n.alternateSets.splice(o,0,0)),n.alternateSets[o]=t.by},Os.prototype.addLigature=function(e,t,r,i){var n=this.getLookupTables(r,i,e,4,!0)[0],s=n.subtables[0];s||(s={substFormat:1,coverage:{format:1,glyphs:[]},ligatureSets:[]},n.subtables[0]=s),Li.assert(1===s.coverage.format,"Ligature: unable to modify coverage table format "+s.coverage.format);var o=t.sub[0],a=t.sub.slice(1),c={ligGlyph:t.by,components:a},h=this.binSearch(s.coverage.glyphs,o);if(h>=0){for(var l=s.ligatureSets[h],u=0;u=176&&r<=183)n+=r-176+1;else if(r>=184&&r<=191)n+=2*(r-184+1);else if(t&&1===s&&27===r)break}while(s>0);e.ip=n}function co(e,t){exports.DEBUG&&console.log(t.step,"SVTCA["+e.axis+"]"),t.fv=t.pv=t.dpv=e}function ho(e,t){exports.DEBUG&&console.log(t.step,"SPVTCA["+e.axis+"]"),t.pv=t.dpv=e}function lo(e,t){exports.DEBUG&&console.log(t.step,"SFVTCA["+e.axis+"]"),t.fv=e}function uo(e,t){var r,i,n=t.stack,s=n.pop(),o=n.pop(),a=t.z2[s],c=t.z1[o];exports.DEBUG&&console.log("SPVTL["+e+"]",s,o),e?(r=a.y-c.y,i=c.x-a.x):(r=c.x-a.x,i=c.y-a.y),t.pv=t.dpv=to(r,i)}function po(e,t){var r,i,n=t.stack,s=n.pop(),o=n.pop(),a=t.z2[s],c=t.z1[o];exports.DEBUG&&console.log("SFVTL["+e+"]",s,o),e?(r=a.y-c.y,i=c.x-a.x):(r=c.x-a.x,i=c.y-a.y),t.fv=to(r,i)}function fo(e){exports.DEBUG&&console.log(e.step,"POP[]"),e.stack.pop()}function go(e,t){var r=t.stack.pop(),i=t.z0[r],n=t.fv,s=t.pv;exports.DEBUG&&console.log(t.step,"MDAP["+e+"]",r);var o=s.distance(i,io);e&&(o=t.round(o)),n.setRelative(i,io,o,s),n.touch(i),t.rp0=t.rp1=r}function vo(e,t){var r,i,n,s=t.z2,o=s.length-2;exports.DEBUG&&console.log(t.step,"IUP["+e.axis+"]");for(var a=0;a1?"loop "+(t.loop-a)+": ":"")+"SHP["+(e?"rp1":"rp2")+"]",h)}t.loop=1}function yo(e,t){var r=t.stack,i=e?t.rp1:t.rp2,n=(e?t.z0:t.z1)[i],s=t.fv,o=t.pv,a=r.pop(),c=t.z2[t.contours[a]],h=c;exports.DEBUG&&console.log(t.step,"SHC["+e+"]",a);var l=o.distance(n,n,!1,!0);do{h!==n&&s.setRelative(h,h,l,o),h=h.nextPointOnContour}while(h!==c)}function So(e,t){var r,i,n=t.stack,s=e?t.rp1:t.rp2,o=(e?t.z0:t.z1)[s],a=t.fv,c=t.pv,h=n.pop();switch(exports.DEBUG&&console.log(t.step,"SHZ["+e+"]",h),h){case 0:r=t.tZone;break;case 1:r=t.gZone;break;default:throw new Error("Invalid zone")}for(var l=c.distance(o,o,!1,!0),u=r.length-2,d=0;d",a),t.stack.push(Math.round(64*a))}function xo(e,t){var r=t.stack,i=r.pop(),n=t.fv,s=t.pv,o=t.ppem,a=t.deltaBase+16*(e-1),c=t.deltaShift,h=t.z0;exports.DEBUG&&console.log(t.step,"DELTAP["+e+"]",i,r);for(var l=0;l>4)===o){var p=(15&d)-8;p>=0&&p++,exports.DEBUG&&console.log(t.step,"DELTAPFIX",u,"by",p*c);var f=h[u];n.setRelative(f,f,p*c,s)}}}function ko(e,t){var r=t.stack,i=r.pop();exports.DEBUG&&console.log(t.step,"ROUND[]"),r.push(64*t.round(i/64))}function Po(e,t){var r=t.stack,i=r.pop(),n=t.ppem,s=t.deltaBase+16*(e-1),o=t.deltaShift;exports.DEBUG&&console.log(t.step,"DELTAC["+e+"]",i,r);for(var a=0;a>4)===n){var l=(15&h)-8;l>=0&&l++;var u=l*o;exports.DEBUG&&console.log(t.step,"DELTACFIX",c,"by",u),t.cvt[c]+=u}}}function Co(e,t){var r,i,n=t.stack,s=n.pop(),o=n.pop(),a=t.z2[s],c=t.z1[o];exports.DEBUG&&console.log(t.step,"SDPVTL["+e+"]",s,o),e?(r=a.y-c.y,i=c.x-a.x):(r=c.x-a.x,i=c.y-a.y),t.dpv=to(r,i)}function Ao(e,t){var r=t.stack,i=t.prog,n=t.ip;exports.DEBUG&&console.log(t.step,"PUSHB["+e+"]");for(var s=0;s=0?1:-1,a=Math.abs(a),e&&(h=s.cvt[u],i&&Math.abs(a-h)":"_")+(i?"R":"_")+(0===n?"Gr":1===n?"Bl":2===n?"Wh":"")+"]",e?u+"("+s.cvt[u]+","+h+")":"",d,"(d =",o,"->",c*a,")"),s.rp1=s.rp0,s.rp2=d,t&&(s.rp0=d)}function Do(e){this.char=e,this.state={},this.activeState=null}function Ro(e,t,r){this.contextName=r,this.startIndex=e,this.endOffset=t}function Fo(e,t,r){this.contextName=e,this.openRange=null,this.ranges=[],this.checkStart=t,this.checkEnd=r}function Lo(e,t){this.context=e,this.index=t,this.length=e.length,this.current=e[t],this.backtrack=e.slice(0,t),this.lookahead=e.slice(t+1)}function Bo(e){this.eventId=e,this.subscribers=[]}function Mo(e){var t=this,r=["start","end","next","newToken","contextStart","contextEnd","insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD","updateContextsRanges"];r.forEach((function(e){Object.defineProperty(t.events,e,{value:new Bo(e)})})),e&&r.forEach((function(r){var i=e[r];"function"==typeof i&&t.events[r].subscribe(i)})),["insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD"].forEach((function(e){t.events[e].subscribe(t.updateContextsRanges)}))}function Io(e){this.tokens=[],this.registeredContexts={},this.contextCheckers=[],this.events={},this.registeredModifiers=[],Mo.call(this,e)}function Uo(e){return/[\u0600-\u065F\u066A-\u06D2\u06FA-\u06FF]/.test(e)}function Wo(e){return/[\u0630\u0690\u0621\u0631\u0661\u0671\u0622\u0632\u0672\u0692\u06C2\u0623\u0673\u0693\u06C3\u0624\u0694\u06C4\u0625\u0675\u0695\u06C5\u06E5\u0676\u0696\u06C6\u0627\u0677\u0697\u06C7\u0648\u0688\u0698\u06C8\u0689\u0699\u06C9\u068A\u06CA\u066B\u068B\u06CB\u068C\u068D\u06CD\u06FD\u068E\u06EE\u06FE\u062F\u068F\u06CF\u06EF]/.test(e)}function No(e){return/[\u0600-\u0605\u060C-\u060E\u0610-\u061B\u061E\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED]/.test(e)}function Go(e){return/[A-z]/.test(e)}function Ho(e){this.font=e,this.features={}}function Vo(e){this.id=e.id,this.tag=e.tag,this.substitution=e.substitution}function zo(e,t){if(!e)return-1;switch(t.format){case 1:return t.glyphs.indexOf(e);case 2:for(var r=t.ranges,i=0;i=n.start&&e<=n.end){var s=e-n.start;return n.index+s}}break;default:return-1}return-1}function jo(e,t){return-1===zo(e,t.coverage)?null:e+t.deltaGlyphId}function qo(e,t){var r=zo(e,t.coverage);return-1===r?null:t.substitute[r]}function $o(e,t){for(var r=[],i=0;i2)){var r=this.font,i=this._prepState;if(!i||i.ppem!==t){var n=this._fpgmState;if(!n){so.prototype=no,(n=this._fpgmState=new so("fpgm",r.tables.fpgm)).funcs=[],n.font=r,exports.DEBUG&&(console.log("---EXEC FPGM---"),n.step=-1);try{Ns(n)}catch(e){return console.log("Hinting error in FPGM:"+e),void(this._errorState=3)}}so.prototype=n,(i=this._prepState=new so("prep",r.tables.prep)).ppem=t;var s=r.tables.cvt;if(s)for(var o=i.cvt=new Array(s.length),a=t/r.unitsPerEm,c=0;c1))try{return Gs(e,i)}catch(e){return this._errorState<1&&(console.log("Hinting error:"+e),console.log("Note: further hinting errors are silenced")),void(this._errorState=1)}}},Gs=function(e,t){var r,i,n,s=t.ppem/t.font.unitsPerEm,o=s,a=e.components;if(so.prototype=t,a){var c=t.font;i=[],r=[];for(var h=0;h1?"loop "+(e.loop-r)+": ":"")+"SHPIX[]",o,n),i.setRelative(a,a,n),i.touch(a)}e.loop=1},function(e){for(var t=e.stack,r=e.rp1,i=e.rp2,n=e.loop,s=e.z0[r],o=e.z1[i],a=e.fv,c=e.dpv,h=e.z2;n--;){var l=t.pop(),u=h[l];exports.DEBUG&&console.log(e.step,(e.loop>1?"loop "+(e.loop-n)+": ":"")+"IP[]",l,r,"<->",i),a.interpolate(u,s,o,c),a.touch(u)}e.loop=1},bo.bind(void 0,0),bo.bind(void 0,1),function(e){for(var t=e.stack,r=e.rp0,i=e.z0[r],n=e.loop,s=e.fv,o=e.pv,a=e.z1;n--;){var c=t.pop(),h=a[c];exports.DEBUG&&console.log(e.step,(e.loop>1?"loop "+(e.loop-n)+": ":"")+"ALIGNRP[]",c),s.setRelative(h,i,0,o),s.touch(h)}e.loop=1},function(e){exports.DEBUG&&console.log(e.step,"RTDG[]"),e.round=$s},wo.bind(void 0,0),wo.bind(void 0,1),function(e){var t=e.prog,r=e.ip,i=e.stack,n=t[++r];exports.DEBUG&&console.log(e.step,"NPUSHB[]",n);for(var s=0;sr?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"GTEQ[]",r,i),t.push(i>=r?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"EQ[]",r,i),t.push(r===i?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"NEQ[]",r,i),t.push(r!==i?1:0)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"ODD[]",r),t.push(Math.trunc(r)%2?1:0)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"EVEN[]",r),t.push(Math.trunc(r)%2?0:1)},function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"IF[]",t),t||(ao(e,!0),exports.DEBUG&&console.log(e.step,"EIF[]"))},function(e){exports.DEBUG&&console.log(e.step,"EIF[]")},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"AND[]",r,i),t.push(r&&i?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"OR[]",r,i),t.push(r||i?1:0)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"NOT[]",r),t.push(r?0:1)},xo.bind(void 0,1),function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SDB[]",t),e.deltaBase=t},function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SDS[]",t),e.deltaShift=Math.pow(.5,t)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"ADD[]",r,i),t.push(i+r)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"SUB[]",r,i),t.push(i-r)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"DIV[]",r,i),t.push(64*i/r)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"MUL[]",r,i),t.push(i*r/64)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"ABS[]",r),t.push(Math.abs(r))},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"NEG[]",r),t.push(-r)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"FLOOR[]",r),t.push(64*Math.floor(r/64))},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"CEILING[]",r),t.push(64*Math.ceil(r/64))},ko.bind(void 0,0),ko.bind(void 0,1),ko.bind(void 0,2),ko.bind(void 0,3),void 0,void 0,void 0,void 0,function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"WCVTF[]",r,i),e.cvt[i]=r*e.ppem/e.font.unitsPerEm},xo.bind(void 0,2),xo.bind(void 0,3),Po.bind(void 0,1),Po.bind(void 0,2),Po.bind(void 0,3),function(e){var t,r=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"SROUND[]",r),e.round=Js,192&r){case 0:t=.5;break;case 64:t=1;break;case 128:t=2;break;default:throw new Error("invalid SROUND value")}switch(e.srPeriod=t,48&r){case 0:e.srPhase=0;break;case 16:e.srPhase=.25*t;break;case 32:e.srPhase=.5*t;break;case 48:e.srPhase=.75*t;break;default:throw new Error("invalid SROUND value")}r&=15,e.srThreshold=0===r?0:(r/8-.5)*t},function(e){var t,r=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"S45ROUND[]",r),e.round=Js,192&r){case 0:t=Math.sqrt(2)/2;break;case 64:t=Math.sqrt(2);break;case 128:t=2*Math.sqrt(2);break;default:throw new Error("invalid S45ROUND value")}switch(e.srPeriod=t,48&r){case 0:e.srPhase=0;break;case 16:e.srPhase=.25*t;break;case 32:e.srPhase=.5*t;break;case 48:e.srPhase=.75*t;break;default:throw new Error("invalid S45ROUND value")}r&=15,e.srThreshold=0===r?0:(r/8-.5)*t},void 0,void 0,function(e){exports.DEBUG&&console.log(e.step,"ROFF[]"),e.round=js},void 0,function(e){exports.DEBUG&&console.log(e.step,"RUTG[]"),e.round=Xs},function(e){exports.DEBUG&&console.log(e.step,"RDTG[]"),e.round=Zs},fo,fo,void 0,void 0,void 0,void 0,void 0,function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SCANCTRL[]",t)},Co.bind(void 0,0),Co.bind(void 0,1),function(e){var t=e.stack,r=t.pop(),i=0;exports.DEBUG&&console.log(e.step,"GETINFO[]",r),1&r&&(i=35),32&r&&(i|=4096),t.push(i)},void 0,function(e){var t=e.stack,r=t.pop(),i=t.pop(),n=t.pop();exports.DEBUG&&console.log(e.step,"ROLL[]"),t.push(i),t.push(r),t.push(n)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"MAX[]",r,i),t.push(Math.max(i,r))},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"MIN[]",r,i),t.push(Math.min(i,r))},function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SCANTYPE[]",t)},function(e){var t=e.stack.pop(),r=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"INSTCTRL[]",t,r),t){case 1:return void(e.inhibitGridFit=!!r);case 2:return void(e.ignoreCvt=!!r);default:throw new Error("invalid INSTCTRL[] selector")}},void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,Ao.bind(void 0,1),Ao.bind(void 0,2),Ao.bind(void 0,3),Ao.bind(void 0,4),Ao.bind(void 0,5),Ao.bind(void 0,6),Ao.bind(void 0,7),Ao.bind(void 0,8),_o.bind(void 0,1),_o.bind(void 0,2),_o.bind(void 0,3),_o.bind(void 0,4),_o.bind(void 0,5),_o.bind(void 0,6),_o.bind(void 0,7),_o.bind(void 0,8),Oo.bind(void 0,0,0,0,0,0),Oo.bind(void 0,0,0,0,0,1),Oo.bind(void 0,0,0,0,0,2),Oo.bind(void 0,0,0,0,0,3),Oo.bind(void 0,0,0,0,1,0),Oo.bind(void 0,0,0,0,1,1),Oo.bind(void 0,0,0,0,1,2),Oo.bind(void 0,0,0,0,1,3),Oo.bind(void 0,0,0,1,0,0),Oo.bind(void 0,0,0,1,0,1),Oo.bind(void 0,0,0,1,0,2),Oo.bind(void 0,0,0,1,0,3),Oo.bind(void 0,0,0,1,1,0),Oo.bind(void 0,0,0,1,1,1),Oo.bind(void 0,0,0,1,1,2),Oo.bind(void 0,0,0,1,1,3),Oo.bind(void 0,0,1,0,0,0),Oo.bind(void 0,0,1,0,0,1),Oo.bind(void 0,0,1,0,0,2),Oo.bind(void 0,0,1,0,0,3),Oo.bind(void 0,0,1,0,1,0),Oo.bind(void 0,0,1,0,1,1),Oo.bind(void 0,0,1,0,1,2),Oo.bind(void 0,0,1,0,1,3),Oo.bind(void 0,0,1,1,0,0),Oo.bind(void 0,0,1,1,0,1),Oo.bind(void 0,0,1,1,0,2),Oo.bind(void 0,0,1,1,0,3),Oo.bind(void 0,0,1,1,1,0),Oo.bind(void 0,0,1,1,1,1),Oo.bind(void 0,0,1,1,1,2),Oo.bind(void 0,0,1,1,1,3),Oo.bind(void 0,1,0,0,0,0),Oo.bind(void 0,1,0,0,0,1),Oo.bind(void 0,1,0,0,0,2),Oo.bind(void 0,1,0,0,0,3),Oo.bind(void 0,1,0,0,1,0),Oo.bind(void 0,1,0,0,1,1),Oo.bind(void 0,1,0,0,1,2),Oo.bind(void 0,1,0,0,1,3),Oo.bind(void 0,1,0,1,0,0),Oo.bind(void 0,1,0,1,0,1),Oo.bind(void 0,1,0,1,0,2),Oo.bind(void 0,1,0,1,0,3),Oo.bind(void 0,1,0,1,1,0),Oo.bind(void 0,1,0,1,1,1),Oo.bind(void 0,1,0,1,1,2),Oo.bind(void 0,1,0,1,1,3),Oo.bind(void 0,1,1,0,0,0),Oo.bind(void 0,1,1,0,0,1),Oo.bind(void 0,1,1,0,0,2),Oo.bind(void 0,1,1,0,0,3),Oo.bind(void 0,1,1,0,1,0),Oo.bind(void 0,1,1,0,1,1),Oo.bind(void 0,1,1,0,1,2),Oo.bind(void 0,1,1,0,1,3),Oo.bind(void 0,1,1,1,0,0),Oo.bind(void 0,1,1,1,0,1),Oo.bind(void 0,1,1,1,0,2),Oo.bind(void 0,1,1,1,0,3),Oo.bind(void 0,1,1,1,1,0),Oo.bind(void 0,1,1,1,1,1),Oo.bind(void 0,1,1,1,1,2),Oo.bind(void 0,1,1,1,1,3)],Do.prototype.setState=function(e,t){return this.state[e]=t,this.activeState={key:e,value:this.state[e]},this.activeState},Do.prototype.getState=function(e){return this.state[e]||null},Io.prototype.inboundIndex=function(e){return e>=0&&e0&&e<=this.lookahead.length:return this.lookahead[e-1];default:return null}},Io.prototype.rangeToText=function(e){if(e instanceof Ro)return this.getRangeTokens(e).map((function(e){return e.char})).join("")},Io.prototype.getText=function(){return this.tokens.map((function(e){return e.char})).join("")},Io.prototype.getContext=function(e){return this.registeredContexts[e]||null},Io.prototype.on=function(e,t){var r=this.events[e];return r?r.subscribe(t):null},Io.prototype.dispatch=function(e,t){var r=this,i=this.events[e];i instanceof Bo&&i.subscribers.forEach((function(e){e.apply(r,t||[])}))},Io.prototype.registerContextChecker=function(e,t,r){if(this.getContext(e))return{FAIL:"context name '"+e+"' is already registered."};if("function"!=typeof t)return{FAIL:"missing context start check."};if("function"!=typeof r)return{FAIL:"missing context end check."};var i=new Fo(e,t,r);return this.registeredContexts[e]=i,this.contextCheckers.push(i),i},Io.prototype.getRangeTokens=function(e){var t=e.startIndex+e.endOffset;return[].concat(this.tokens.slice(e.startIndex,t))},Io.prototype.getContextRanges=function(e){var t=this.getContext(e);return t?t.ranges:{FAIL:"context checker '"+e+"' is not registered."}},Io.prototype.resetContextsRanges=function(){var e=this.registeredContexts;for(var t in e)e.hasOwnProperty(t)&&(e[t].ranges=[])},Io.prototype.updateContextsRanges=function(){this.resetContextsRanges();for(var e=this.tokens.map((function(e){return e.char})),t=0;t=0;r--){var i=t[r],n=Wo(i),s=No(i);if(!n&&!s)return!0;if(n)return!1}return!1}(o)&&(h|=1),function(e){if(Wo(e.current))return!1;for(var t=0;t=1.2&&(n.markGlyphSets=r.parsePointer(Pa)),n}},Aa=new Array(10);Aa[1]=function(){var e=this.offset+this.relativeOffset,t=this.parseUShort();return 1===t?{posFormat:1,coverage:this.parsePointer(hn.coverage),value:this.parseValueRecord()}:2===t?{posFormat:2,coverage:this.parsePointer(hn.coverage),values:this.parseValueRecordList()}:void Li.assert(!1,"0x"+e.toString(16)+": GPOS lookup type 1 format must be 1 or 2.")},Aa[2]=function(){var e=this.offset+this.relativeOffset,t=this.parseUShort();Li.assert(1===t||2===t,"0x"+e.toString(16)+": GPOS lookup type 2 format must be 1 or 2.");var r=this.parsePointer(hn.coverage),i=this.parseUShort(),n=this.parseUShort();if(1===t)return{posFormat:t,coverage:r,valueFormat1:i,valueFormat2:n,pairSets:this.parseList(hn.pointer(hn.list((function(){return{secondGlyph:this.parseUShort(),value1:this.parseValueRecord(i),value2:this.parseValueRecord(n)}}))))};if(2===t){var s=this.parsePointer(hn.classDef),o=this.parsePointer(hn.classDef),a=this.parseUShort(),c=this.parseUShort();return{posFormat:t,coverage:r,valueFormat1:i,valueFormat2:n,classDef1:s,classDef2:o,class1Count:a,class2Count:c,classRecords:this.parseList(a,hn.list(c,(function(){return{value1:this.parseValueRecord(i),value2:this.parseValueRecord(n)}})))}}},Aa[3]=function(){return{error:"GPOS Lookup 3 not supported"}},Aa[4]=function(){return{error:"GPOS Lookup 4 not supported"}},Aa[5]=function(){return{error:"GPOS Lookup 5 not supported"}},Aa[6]=function(){return{error:"GPOS Lookup 6 not supported"}},Aa[7]=function(){return{error:"GPOS Lookup 7 not supported"}},Aa[8]=function(){return{error:"GPOS Lookup 8 not supported"}},Aa[9]=function(){return{error:"GPOS Lookup 9 not supported"}};var _a=new Array(10),Oa={parse:function(e,t){var r=new hn(e,t=t||0),i=r.parseVersion(1);return Li.argument(1===i||1.1===i,"Unsupported GPOS table version "+i),1===i?{version:i,scripts:r.parseScriptList(),features:r.parseFeatureList(),lookups:r.parseLookupList(Aa)}:{version:i,scripts:r.parseScriptList(),features:r.parseFeatureList(),lookups:r.parseLookupList(Aa),variations:r.parseFeatureVariationsList()}},make:function(e){return new rn.Table("GPOS",[{name:"version",type:"ULONG",value:65536},{name:"scripts",type:"TABLE",value:new rn.ScriptList(e.scripts)},{name:"features",type:"TABLE",value:new rn.FeatureList(e.features)},{name:"lookups",type:"TABLE",value:new rn.LookupList(e.lookups,_a)}])}},Da={parse:function(e,t){var r=new un.Parser(e,t),i=r.parseUShort();if(0===i)return function(e){var t={};e.skip("uShort");var r=e.parseUShort();Li.argument(0===r,"Unsupported kern sub-table version."),e.skip("uShort",2);var i=e.parseUShort();e.skip("uShort",3);for(var n=0;n1&&console.warn("Only the first kern subtable is supported."),e.skip("uLong");var r=255&e.parseUShort();if(e.skip("uShort"),0===r){var i=e.parseUShort();e.skip("uShort",3);for(var n=0;n{try{void 0!==e&&Array.isArray(e)&&0===e.length&&t({});const r=e?Rr.filter((t=>e.includes(t.key))):Rr,i=r.reduce(((e,t)=>e+t.variants.length),0);let n=0;r.forEach((e=>{e.variants.forEach((r=>{const s=e.key,o=`${s}-${r}`;!function(e,t,r){r=null==r?{}:r;var i="undefined"!=typeof window||r.isUrl?La:Fa;new Promise((function(n,s){i(e,(function(e,i){if(e){if(t)return t(e);s(e)}var o;try{o=Ia(i,r)}catch(e){if(t)return t(e,null);s(e)}if(t)return t(null,o);n(o)}))}))}(`https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.15.12/fonts/${s}/${o}.ttf`,((e,a)=>{e||(this.fonts.push({name:o,type:s,variant:r,font:a}),n++,n===i&&t({}))}),{isUrl:!0})}))}))}catch(e){r(e)}}))},new((i=void 0)||(i=Promise))((function(e,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i((function(e){e(r)}))).then(o,a)}c((n=n.apply(t,r||[])).next())}));var t,r,i,n}text3d(e){return oi(e,this.occtService,this.fonts,this.occ)}text3dFace(t){return function(t,r,i,n,s,o){if(!o.text3dFace)throw new Error("Could not compute, to use Text 3D Face algorithm you must be subscribed to our silver or gold plan.");try{const a=`\n ${o.text3dFace}\n `,c=new Function(a),h={name:"text3dFace"};return c.apply({inputs:t,occt:r,fonts:i,occ:n,vectorHelper:s,Inputs:e,Advanced:G,ShapeParser:ni,text3d:oi,method:h})}catch(e){throw new Error(e)}}(t,this.occtService,this.fonts,this.occ,this.vectorHelper,this.dependencies)}texts3dFace(t){return function(t,r,i,n,s,o){if(!o.text3dFace)throw new Error("Could not compute, to use Texts 3D Face algorithm you must be subscribed to our silver or gold plan.");try{const a=`\n ${o.text3dFace}\n `,c=new Function(a),h={name:"texts3dFace"};return c.apply({inputs:t,occt:r,fonts:i,occ:n,vectorHelper:s,Inputs:e,Advanced:G,ShapeParser:ni,text3d:oi,method:h})}catch(e){throw new Error(e)}}(t,this.occtService,this.fonts,this.occ,this.vectorHelper,this.dependencies)}pyramidSimple(t){return function(t,r,i,n,s){if(function(e){let t;if(["uNumber","vNumber","height","precision"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.uNumber<=0?t="U number mus be greater than 0.":e.vNumber<=0?t="V number must be greater than 0.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!s.patternsFacePatternPyramidSimple)throw new Error("Could not compute, to use Pyramid Simple algorithm you must be subscribed to our silver or gold plan.");try{const o=`\n ${s.patternsFacePatternPyramidSimple}\n `,a=new Function(o),c={name:"pyramidSimple"};return a.apply({inputs:t,occt:r,occ:i,vectorHelper:n,Inputs:e,Advanced:G,ShapeParser:ni,method:c})}catch(e){throw new Error(e)}}(t,this.occtService,this.occ,this.vectorHelper,this.dependencies)}pyramidSimpleAffectors(t){return function(t,r,i,n,s){if(function(e){let t;if(["uNumber","vNumber","defaultHeight","affectMinHeight","affectMaxHeight","precision"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.uNumber<=0?t="U number mus be greater than 0.":e.vNumber<=0?t="V number must be greater than 0.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!s.patternsFacePatternPyramidSimple)throw new Error("Could not compute, to use Pyramid Simple Affectors algorithm you must be subscribed to our silver or gold plan.");try{const o=`\n ${s.patternsFacePatternPyramidSimple}\n `,a=new Function(o),c={name:"pyramidSimpleAffectors"};return a.apply({inputs:t,occt:r,occ:i,vectorHelper:n,Inputs:e,Advanced:G,ShapeParser:ni,method:c})}catch(e){throw new Error(e)}}(t,this.occtService,this.occ,this.vectorHelper,this.dependencies)}}class Wa{constructor(e){this.dependencies={serenitySwirl:void 0};const t=new V,r=new H;this.occtService=new Pe(e,new Se(t,r,e)),this.advanced=new Ua(this.occtService,this.dependencies,e,t),this.things=new si(this.occtService,this.advanced,this.dependencies)}}var Na=function(){return Na=Object.assign||function(e){for(var t,r=1,i=arguments.length;r0&&n[n.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!n||a[1]>n[0]&&a[1]{Re=new Oe(e);const i=new V,n=new H;De=new Pe(e,new Se(i,n,e)),t&&(De.plugins=t,Fe&&Object.keys(Fe).forEach((e=>{De.plugins.dependencies[e]=Fe[e]}))),postMessage("occ-initialised")})(e,t),postMessage("occ-initialised"),[2]}}))}))})):((e,t)=>{let r;t("busy");try{if("shapeToMesh"!==e.action.functionName&&"shapesToMeshes"!==e.action.functionName&&"deleteShape"!==e.action.functionName&&"deleteShapes"!==e.action.functionName&&"startedTheRun"!==e.action.functionName&&"cleanAllCache"!==e.action.functionName&&"addOc"!==e.action.functionName&&"saveShapeSTEP"!==e.action.functionName){Object.keys(e.action.inputs).forEach((t=>{const r=e.action.inputs[t];r&&r.type&&"occ-shape"===r.type&&r.hash&&(e.action.inputs[t]=Re.checkCache(e.action.inputs[t].hash)),r&&Array.isArray(r)&&r.length>0&&(r[0].type&&"occ-shape"===r[0].type&&r[0].hash?e.action.inputs[t]=e.action.inputs[t].map((e=>Re.checkCache(e.hash))):Array.isArray(r[0])&&r[0][0].type&&"occ-shape"===r[0][0].type&&r[0][0].hash&&(e.action.inputs[t]=e.action.inputs[t].map((e=>e.map((e=>Re.checkCache(e.hash)))))))}));const t=e.action.functionName.split(".");let i;if(i=3===t.length?Re.cacheOp(e.action,(()=>De[t[0]][t[1]][t[2]](e.action.inputs))):2===t.length?Re.cacheOp(e.action,(()=>De[t[0]][t[1]](e.action.inputs))):Re.cacheOp(e.action,(()=>De[e.action.functionName](e.action.inputs))),Re.isOCCTObject(i))r=Array.isArray(i)?i.map((e=>({hash:e.hash,type:"occ-shape"}))):{hash:i.hash,type:"occ-shape"};else if(i.compound&&i.data&&i.shapes&&i.shapes.length>0){const e=i;e.shapes=e.shapes.map((e=>({id:e.id,shape:{hash:e.shape.hash,type:"occ-shape"}}))),e.compound={hash:e.compound.hash,type:"occ-shape"},r=e}else r=i}if("saveShapeSTEP"===e.action.functionName&&(e.action.inputs.shape=Re.checkCache(e.action.inputs.shape.hash),r=De.io.saveShapeSTEP(e.action.inputs)),"addOc"===e.action.functionName&&(De&&De.plugins?Object.keys(e.action.inputs).forEach((t=>{De.plugins.dependencies[t]=e.action.inputs[t]})):Fe=e.action.inputs),"shapeToMesh"===e.action.functionName&&(e.action.inputs.shape=Re.checkCache(e.action.inputs.shape.hash),r=De.shapeToMesh(e.action.inputs)),"shapesToMeshes"===e.action.functionName){if(!(e.action.inputs.shapes&&e.action.inputs.shapes.length>0))throw new Error("No shapes detected");e.action.inputs.shapes=e.action.inputs.shapes.map((e=>Re.checkCache(e.hash))),r=De.shapesToMeshes(e.action.inputs)}"deleteShape"===e.action.functionName&&(Re.cleanCacheForHash(e.action.inputs.shape.hash),r={}),"deleteShapes"===e.action.functionName&&(e.action.inputs.shapes.forEach((e=>Re.cleanCacheForHash(e.hash))),r={}),"startedTheRun"===e.action.functionName&&(Re&&Object.keys(Re.usedHashes).length>1e4&&Re.cleanAllCache(),r={}),"cleanAllCache"===e.action.functionName&&(Re.cleanAllCache(),r={}),t({uid:e.uid,result:r})}catch(r){let i,n;e&&e.action&&e.action.inputs&&(i=`Input values were: {${Object.keys(e.action.inputs).map((t=>`${t}: ${JSON.stringify(e.action.inputs[t])}`)).join(",")}}. `),e&&e.action&&e.action.functionName&&(n=`- ${e.action.functionName}`),t({uid:e.uid,result:void 0,error:`OCCT computation failed. ${r} While executing function ${n}. ${i}`})}})(d,postMessage)}))})()})(); \ No newline at end of file +(()=>{var e={725:()=>{},439:()=>{},699:()=>{},256:()=>{}},t={};function r(i){var n=t[i];if(void 0!==n)return n.exports;var s=t[i]={exports:{}};return e[i](s,s.exports,r),s.exports}r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{"use strict";var e={};r.r(e),r.d(e,{Base:()=>W,OCCT:()=>U});var t={};r.r(t),r.d(t,{LodDto:()=>Ge,lodEnum:()=>Be});var i={};r.r(i),r.d(i,{Part:()=>He});var n={};r.r(n),r.d(n,{SerenitySwirlData:()=>ze,SerenitySwirlDto:()=>Ve});var s={};r.r(s),r.d(s,{ArabicArchwayData:()=>$e,ArabicArchwayDrawingPart:()=>Ye,ArabicArchwayDrawingPartShapes:()=>Xe,ArabicArchwayDto:()=>qe,ArabicArchwayDtoBase:()=>je});var o={};r.r(o),r.d(o,{ArabicArchway:()=>s,SerenitySwirl:()=>n});var a={};r.r(a),r.d(a,{EternalLoveData:()=>Qe,EternalLoveDto:()=>Je,EternalLoveDtoBase:()=>Ze});var c={};r.r(c),r.d(c,{EternalLove:()=>a});var h={};r.r(h),r.d(h,{CalmCupData:()=>tt,CalmCupDto:()=>et,CalmCupDtoBase:()=>Ke});var l={};r.r(l),r.d(l,{DragonCupData:()=>nt,DragonCupDto:()=>it,DragonCupDtoBase:()=>rt,DragonCupModelDto:()=>st});var u={};r.r(u),r.d(u,{CalmCup:()=>h,DragonCup:()=>l});var d={};r.r(d),r.d(d,{PhoneNestData:()=>ct,PhoneNestDrawDto:()=>pt,PhoneNestDrawingPart:()=>ht,PhoneNestDrawingPartShapes:()=>lt,PhoneNestDto:()=>at,PhoneNestDtoBase:()=>ot,PhoneNestMainPart:()=>ut,PhoneNestModelDto:()=>dt});var p={};r.r(p),r.d(p,{PhoneNest:()=>d});var f={};r.r(f),r.d(f,{SpicyBoxData:()=>vt,SpicyBoxDto:()=>gt,SpicyBoxDtoBase:()=>ft,SpicyBoxModelDto:()=>mt});var g={};r.r(g),r.d(g,{SpicyBox:()=>f});var v={};r.r(v),r.d(v,{Boxes:()=>g,Cups:()=>u,Desktop:()=>p,Medals:()=>c,Vases:()=>o});var m={};r.r(m),r.d(m,{ZenHideoutData:()=>bt,ZenHideoutDrawingPart:()=>wt,ZenHideoutDrawingPartShapes:()=>Et,ZenHideoutDto:()=>St,ZenHideoutDtoBase:()=>yt});var y={};r.r(y),r.d(y,{ZenHideout:()=>m});var S={};r.r(S),r.d(S,{BeamPart:()=>Ft,CeilingPart:()=>Ht,ColumnPart:()=>Rt,CornerEntranceDto:()=>zt,CornerEntrancePart:()=>Wt,CornerPart:()=>Dt,CornerStairDto:()=>It,CornerStairPart:()=>Ut,FloorPart:()=>Vt,Houses:()=>y,RoofBeamsPart:()=>Bt,RoofCoverOneSidedDto:()=>Nt,RoofCoverPart:()=>Gt,RoofPanelPart:()=>Mt,RoofPart:()=>Lt,SandwitchPanelDto:()=>Ct,SandwitchPanelFlexDto:()=>At,SandwitchPart:()=>_t,SandwitchPartFlex:()=>Ot,WindowCornerDto:()=>Tt,WindowCornerPart:()=>Pt,WindowRectangularDto:()=>xt,WindowRectangularPart:()=>kt});var b={};r.r(b),r.d(b,{WingtipVillaData:()=>qt,WingtipVillaDto:()=>jt});var w={};r.r(w),r.d(w,{ChirpyChaletData:()=>Yt,ChirpyChaletDto:()=>$t});var E={};r.r(E),r.d(E,{ChirpyChalet:()=>w,WingtipVilla:()=>b});var T={};r.r(T),r.d(T,{BirdHouses:()=>E});var x={};r.r(x),r.d(x,{SnakeChairData:()=>Jt,SnakeChairDrawDto:()=>rr,SnakeChairDrawingPart:()=>Qt,SnakeChairDrawingPartShapes:()=>Kt,SnakeChairDto:()=>Zt,SnakeChairDtoBase:()=>Xt,SnakeChairMainPart:()=>er,SnakeChairModelDto:()=>tr});var k={};r.r(k),r.d(k,{SnakeChair:()=>x});var P={};r.r(P),r.d(P,{ElegantTableData:()=>sr,ElegantTableDrawDto:()=>dr,ElegantTableDrawingPart:()=>or,ElegantTableDrawingPartShapes:()=>ar,ElegantTableDto:()=>nr,ElegantTableDtoBase:()=>ir,ElegantTableLegByIndexDto:()=>lr,ElegantTableLegPart:()=>cr,ElegantTableModelDto:()=>ur,ElegantTableTopPart:()=>hr});var C={};r.r(C),r.d(C,{GoodCoffeeTableData:()=>gr,GoodCoffeeTableDrawDto:()=>Tr,GoodCoffeeTableDrawingPart:()=>vr,GoodCoffeeTableDrawingPartShapes:()=>mr,GoodCoffeeTableDto:()=>fr,GoodCoffeeTableDtoBase:()=>pr,GoodCoffeeTableLegByIndexDto:()=>wr,GoodCoffeeTableLegPart:()=>yr,GoodCoffeeTableModelDto:()=>Er,GoodCoffeeTableShelfPart:()=>Sr,GoodCoffeeTableTopPart:()=>br});var A={};r.r(A),r.d(A,{SnakeTableData:()=>Pr,SnakeTableDrawDto:()=>Dr,SnakeTableDrawingPart:()=>Cr,SnakeTableDrawingPartShapes:()=>Ar,SnakeTableDto:()=>kr,SnakeTableDtoBase:()=>xr,SnakeTableMainPart:()=>_r,SnakeTableModelDto:()=>Or});var _={};r.r(_),r.d(_,{ElegantTable:()=>P,GoodCoffeeTable:()=>C,SnakeTable:()=>A});var O={};r.r(O),r.d(O,{Chairs:()=>k,Tables:()=>_});var D={};r.r(D),r.d(D,{Architecture:()=>S,Enums:()=>t,Furniture:()=>O,KidsCorner:()=>T,Shared:()=>i,ThreeDPrinting:()=>v});var R={};r.r(R),r.d(R,{FontDefinition:()=>Ir,Text3DData:()=>Br,Text3DDto:()=>Fr,Text3DFaceDefinitionDto:()=>Wr,Text3DFaceDto:()=>Lr,Text3DLetterByIndexDto:()=>Mr,Text3DModelDto:()=>Ur,Texts3DFaceDto:()=>Nr,faceTextVarEnum:()=>Ue,faceTypeEnum:()=>We,fontVariantsEnum:()=>Ie,fontsEnum:()=>Me,fontsModel:()=>Rr,recAlignmentEnum:()=>Ne});var F={};r.r(F),r.d(F,{PyramidSimpeByIndexDto:()=>zr,PyramidSimpleAffectorsDto:()=>Hr,PyramidSimpleCellPart:()=>Kr,PyramidSimpleData:()=>Vr,PyramidSimpleDto:()=>Gr,PyramidSimpleFacePart:()=>ei,PyramidSimpleModelCellDto:()=>Yr,PyramidSimpleModelCellsDto:()=>qr,PyramidSimpleModelCellsIndexDto:()=>$r,PyramidSimpleModelDto:()=>jr,PyramidSimpleModelFaceCellIndexDto:()=>Zr,PyramidSimpleModelFaceCellsUIndexDto:()=>Jr,PyramidSimpleModelFaceCellsVIndexDto:()=>Qr,PyramidSimpleModelFaceIndexDto:()=>Xr});var L={};r.r(L),r.d(L,{PyramidSimple:()=>F});var B={};r.r(B),r.d(B,{FacePatterns:()=>L});var M={};r.r(M),r.d(M,{outputShapeEnum:()=>ti});var I,U,W,N,G={};r.r(G),r.d(G,{Enums:()=>M,Patterns:()=>B,Text3D:()=>R}),(N=I||(I={})).loading="loading",N.loaded="loaded",N.initialised="initialised",N.computing="computing";class H{starLines(e,t,r,i,n){let s=[];const o=2*Math.PI/r;for(let i=0;i=i&&(e=i-1e-6,console.warn("width first is bigger than length second, to make it work, width second is set to length first - 1e-6")),r>=t&&(r=t-1e-6,console.warn("width second is bigger than length first, to make it work, width second is set to length first - 1e-6")),[[0,0,0],[t,0,0],[t,0,e],[r,0,e],[r,0,i],[0,0,i]]}polygonLMiddle(e,t,r,i){return e>=i&&(e=i-1e-6,console.warn("width first is bigger than length second, to make it work, width second is set to length first - 1e-6")),r>=t&&(r=t-1e-6,console.warn("width second is bigger than length first, to make it work, width second is set to length first - 1e-6")),[[r/2,0,e/2],[r/2,0,i],[-r/2,0,i],[-r/2,0,-e/2],[t,0,-e/2],[t,0,e/2]]}}class V{constructor(){this.tolerance=1e-5}degToRad(e){return e*(Math.PI/180)}remap(e,t,r,i,n){return(e-t)/(r-t)*(n-i)+i}removeAllDuplicateVectors(e,t=1e-7){const r=[];return e.forEach((e=>{r.some((r=>this.vectorsTheSame(e,r,t)))||r.push(e)})),r}removeConsecutiveDuplicates(e,t=!0){const r=[];if(e.length>1){for(let t=1;te.map(((e,r)=>e+t[r]))),[0,0,0]).map((t=>t/e.length))}magnitude(e){return Math.sqrt(e.reduce(((e,t)=>e+t*t),0))}normalize(e){const t=this.magnitude(e);return e.map((e=>e/t))}translatePoint(e,t,r){return[e[0]+t[0]*r,e[1]+t[1]*r,e[2]+t[2]*r]}distanceBetweenPoints(e,t){const r=t[0]-e[0],i=t[1]-e[1],n=t[2]-e[2];return Math.sqrt(r*r+i*i+n*n)}}!function(e){let t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v;!function(e){e.arc="arc",e.intersection="intersection",e.tangent="tangent"}(t=e.joinTypeEnum||(e.joinTypeEnum={})),function(e){e.skin="skin",e.pipe="pipe",e.rectoVerso="rectoVerso"}(r=e.bRepOffsetModeEnum||(e.bRepOffsetModeEnum={})),function(e){e.approxChordLength="approxChordLength",e.approxCentripetal="approxCentripetal",e.approxIsoParametric="approxIsoParametric"}(i=e.approxParametrizationTypeEnum||(e.approxParametrizationTypeEnum={})),function(e){e.outside="outside",e.inside="inside",e.middle="middle"}(n=e.directionEnum||(e.directionEnum={})),function(e){e.iges="iges",e.step="step"}(s=e.fileTypeEnum||(e.fileTypeEnum={})),function(e){e.forward="forward",e.reversed="reversed",e.internal="internal",e.external="external"}(o=e.topAbsOrientationEnum||(e.topAbsOrientationEnum={})),function(e){e.in="in",e.out="out",e.on="on",e.unknown="unknown"}(a=e.topAbsStateEnum||(e.topAbsStateEnum={})),function(e){e.unknown="unknown",e.vertex="vertex",e.edge="edge",e.wire="wire",e.face="face",e.shell="shell",e.solid="solid",e.compSolid="compSolid",e.compound="compound",e.shape="shape"}(c=e.shapeTypeEnum||(e.shapeTypeEnum={})),function(e){e.unqualified="unqualified",e.enclosing="enclosing",e.enclosed="enclosed",e.outside="outside",e.noqualifier="noqualifier"}(h=e.gccEntPositionEnum||(e.gccEntPositionEnum={})),function(e){e.keepSide1="keepSide1",e.keepSide2="keepSide2",e.all="all"}(l=e.positionResultEnum||(e.positionResultEnum={})),function(e){e.none="none",e.keepSide1="keepSide1",e.keepSide2="keepSide2"}(u=e.circleInclusionEnum||(e.circleInclusionEnum={})),function(e){e.none="none",e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(d=e.twoCircleInclusionEnum||(e.twoCircleInclusionEnum={})),function(e){e.outside="outside",e.inside="inside",e.outsideInside="outsideInside",e.insideOutside="insideOutside"}(p=e.fourSidesStrictEnum||(e.fourSidesStrictEnum={})),function(e){e.outside="outside",e.inside="inside"}(f=e.twoSidesStrictEnum||(e.twoSidesStrictEnum={})),function(e){e.allWithAll="allWithAll",e.inOrder="inOrder",e.inOrderClosed="inOrderClosed"}(g=e.combinationCirclesForFaceEnum||(e.combinationCirclesForFaceEnum={})),function(e){e[e.curve=0]="curve",e[e.edge=1]="edge",e[e.wire=2]="wire",e[e.face=3]="face"}(v=e.typeSpecificityEnum||(e.typeSpecificityEnum={})),e.DecomposedMeshDto=class{constructor(e,t){void 0!==e&&(this.faceList=e),void 0!==t&&(this.edgeList=t)}},e.DecomposedFaceDto=class{},e.DecomposedEdgeDto=class{},e.ShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.PointDto=class{constructor(e){this.point=[0,0,0],void 0!==e&&(this.point=e)}},e.PointsDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.ConstraintTanLinesFromPtToCircleDto=class{constructor(e,t,r,i,n){this.tolerance=1e-7,this.positionResult=l.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.positionResult=i),void 0!==n&&(this.circleRemainder=n)}},e.ConstraintTanLinesFromTwoPtsToCircleDto=class{constructor(e,t,r,i,n,s){this.tolerance=1e-7,this.positionResult=l.all,this.circleRemainder=u.none,void 0!==e&&(this.circle=e),void 0!==t&&(this.point1=t),void 0!==r&&(this.point1=r),void 0!==i&&(this.tolerance=i),void 0!==n&&(this.positionResult=n),void 0!==s&&(this.circleRemainder=s)}},e.ConstraintTanLinesOnTwoCirclesDto=class{constructor(e,t,r,i,n){this.tolerance=1e-7,this.positionResult=l.all,this.circleRemainders=d.none,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.positionResult=i),void 0!==n&&(this.circleRemainders=n)}},e.ConstraintTanCirclesOnTwoCirclesDto=class{constructor(e,t,r,i){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.radius=i)}},e.ConstraintTanCirclesOnCircleAndPntDto=class{constructor(e,t,r,i){this.tolerance=1e-7,this.radius=.3,void 0!==e&&(this.circle=e),void 0!==t&&(this.point=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.radius=i)}},e.CurveAndSurfaceDto=class{constructor(e,t){void 0!==e&&(this.curve=e),void 0!==t&&(this.surface=t)}},e.FilletTwoEdgesInPlaneDto=class{constructor(e,t,r,i,n,s){this.planeOrigin=[0,0,0],this.planeDirection=[0,1,0],this.radius=.3,this.solution=-1,void 0!==e&&(this.edge1=e),void 0!==t&&(this.edge2=t),void 0!==r&&(this.planeOrigin=r),void 0!==i&&(this.planeDirection=i),void 0!==n&&(this.radius=n),void 0!==s&&(this.solution=s)}},e.ClosestPointsOnShapeFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.SplitWireOnPointsDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t)}},e.ClosestPointsOnShapesFromPointsDto=class{constructor(e,t){void 0!==e&&(this.shapes=e),void 0!==t&&(this.points=t)}},e.ClosestPointsBetweenTwoShapesDto=class{constructor(e,t){void 0!==e&&(this.shape1=e),void 0!==t&&(this.shape2=t)}},e.FaceFromSurfaceAndWireDto=class{constructor(e,t,r){this.inside=!0,void 0!==e&&(this.surface=e),void 0!==t&&(this.wire=t),void 0!==r&&(this.inside=r)}},e.WireOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wire=e),void 0!==t&&(this.face=t)}},e.DrawShapeDto=class{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shape=e),void 0!==t&&(this.faceOpacity=t),void 0!==r&&(this.edgeOpacity=r),void 0!==i&&(this.edgeColour=i),void 0!==n&&(this.faceMaterial=n),void 0!==s&&(this.faceColour=s),void 0!==l&&(this.vertexColour=l),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==c&&(this.drawFaces=c),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdgeIndexes=p),void 0!==f&&(this.edgeIndexHeight=f),void 0!==g&&(this.edgeIndexColour=g),void 0!==v&&(this.drawFaceIndexes=v),void 0!==m&&(this.faceIndexHeight=m),void 0!==y&&(this.faceIndexColour=y)}},e.DrawShapesDto=class{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y){this.faceOpacity=1,this.edgeOpacity=1,this.edgeColour="#ffffff",this.faceColour="#ff0000",this.edgeWidth=2,this.drawEdges=!0,this.drawFaces=!0,this.drawVertices=!1,this.vertexColour="#ffaaff",this.vertexSize=.03,this.precision=.01,this.drawEdgeIndexes=!1,this.edgeIndexHeight=.06,this.edgeIndexColour="#ff00ff",this.drawFaceIndexes=!1,this.faceIndexHeight=.06,this.faceIndexColour="#0000ff",void 0!==e&&(this.shapes=e),void 0!==t&&(this.faceOpacity=t),void 0!==r&&(this.edgeOpacity=r),void 0!==i&&(this.edgeColour=i),void 0!==n&&(this.faceMaterial=n),void 0!==s&&(this.faceColour=s),void 0!==l&&(this.vertexColour=l),void 0!==u&&(this.vertexSize=u),void 0!==o&&(this.edgeWidth=o),void 0!==a&&(this.drawEdges=a),void 0!==c&&(this.drawFaces=c),void 0!==h&&(this.drawVertices=h),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdgeIndexes=p),void 0!==f&&(this.edgeIndexHeight=f),void 0!==g&&(this.edgeIndexColour=g),void 0!==v&&(this.drawFaceIndexes=v),void 0!==m&&(this.faceIndexHeight=m),void 0!==y&&(this.faceIndexColour=y)}},e.FaceSubdivisionDto=class{constructor(e,t,r,i,n,s,o,a,c){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepU=!1,this.removeStartEdgeU=!1,this.removeEndEdgeU=!1,this.shiftHalfStepV=!1,this.removeStartEdgeV=!1,this.removeEndEdgeV=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==r&&(this.nrDivisionsV=r),void 0!==i&&(this.shiftHalfStepU=i),void 0!==n&&(this.removeStartEdgeU=n),void 0!==s&&(this.removeEndEdgeU=s),void 0!==o&&(this.shiftHalfStepV=o),void 0!==a&&(this.removeStartEdgeV=a),void 0!==c&&(this.removeEndEdgeV=c)}},e.FaceSubdivisionControlledDto=class{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f){this.nrDivisionsU=10,this.nrDivisionsV=10,this.shiftHalfStepNthU=0,this.shiftHalfStepUOffsetN=0,this.removeStartEdgeNthU=0,this.removeStartEdgeUOffsetN=0,this.removeEndEdgeNthU=0,this.removeEndEdgeUOffsetN=0,this.shiftHalfStepNthV=0,this.shiftHalfStepVOffsetN=0,this.removeStartEdgeNthV=0,this.removeStartEdgeVOffsetN=0,this.removeEndEdgeNthV=0,this.removeEndEdgeVOffsetN=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrDivisionsU=t),void 0!==r&&(this.nrDivisionsV=r),void 0!==i&&(this.shiftHalfStepNthU=i),void 0!==n&&(this.shiftHalfStepUOffsetN=n),void 0!==s&&(this.removeStartEdgeNthU=s),void 0!==o&&(this.removeStartEdgeUOffsetN=o),void 0!==a&&(this.removeEndEdgeNthU=a),void 0!==c&&(this.removeEndEdgeUOffsetN=c),void 0!==h&&(this.shiftHalfStepNthV=h),void 0!==l&&(this.shiftHalfStepVOffsetN=l),void 0!==u&&(this.removeStartEdgeNthV=u),void 0!==d&&(this.removeStartEdgeVOffsetN=d),void 0!==p&&(this.removeEndEdgeNthV=p),void 0!==f&&(this.removeEndEdgeVOffsetN=f)}},e.FaceLinearSubdivisionDto=class{constructor(e,t,r,i,n,s,o){this.isU=!0,this.param=.5,this.nrPoints=10,this.shiftHalfStep=!1,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.isU=t),void 0!==r&&(this.param=r),void 0!==i&&(this.nrPoints=i),void 0!==n&&(this.shiftHalfStep=n),void 0!==s&&(this.removeStartPoint=s),void 0!==o&&(this.removeEndPoint=o)}},e.DataOnUVDto=class{constructor(e,t,r){this.paramU=.5,this.paramV=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.paramU=t),void 0!==r&&(this.paramV=r)}},e.DataOnUVsDto=class{constructor(e,t){this.paramsUV=[[.5,.5]],void 0!==e&&(this.shape=e),void 0!==t&&(this.paramsUV=t)}},e.PolygonDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolygonsDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polygons=e),void 0!==t&&(this.returnCompound=t)}},e.PolylineDto=class{constructor(e){void 0!==e&&(this.points=e)}},e.PolylinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.polylines=e),void 0!==t&&(this.returnCompound=t)}},e.SquareDto=class{constructor(e,t,r){this.size=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t),void 0!==r&&(this.direction=r)}},e.RectangleDto=class{constructor(e,t,r,i){this.width=1,this.length=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==r&&(this.center=r),void 0!==i&&(this.direction=i)}},e.LPolygonDto=class{constructor(e,t,r,i,s,o,a,c){this.widthFirst=1,this.lengthFirst=2,this.widthSecond=.5,this.lengthSecond=2,this.align=n.outside,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.widthFirst=e),void 0!==t&&(this.lengthFirst=t),void 0!==r&&(this.widthSecond=r),void 0!==i&&(this.lengthSecond=i),void 0!==s&&(this.align=s),void 0!==o&&(this.rotation=o),void 0!==a&&(this.center=a),void 0!==c&&(this.direction=c)}},e.BoxDto=class{constructor(e,t,r,i){this.width=1,this.length=2,this.height=3,this.center=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==r&&(this.height=r),void 0!==i&&(this.center=i)}},e.CubeDto=class{constructor(e,t){this.size=1,this.center=[0,0,0],void 0!==e&&(this.size=e),void 0!==t&&(this.center=t)}},e.BoxFromCornerDto=class{constructor(e,t,r,i){this.width=1,this.length=2,this.height=3,this.corner=[0,0,0],void 0!==e&&(this.width=e),void 0!==t&&(this.length=t),void 0!==r&&(this.height=r),void 0!==i&&(this.corner=i)}},e.SphereDto=class{constructor(e,t){this.radius=1,this.center=[0,0,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t)}},e.ConeDto=class{constructor(e,t,r,i,n,s){this.radius1=2,this.radius2=1,this.height=2,this.angle=360,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius1=e),void 0!==t&&(this.radius2=t),void 0!==r&&(this.height=r),void 0!==i&&(this.angle=i),void 0!==n&&(this.center=n),void 0!==s&&(this.direction=s)}},e.LineDto=class{constructor(e,t){this.start=[0,0,0],this.end=[0,1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.LinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.lines=e),void 0!==t&&(this.returnCompound=t)}},e.ArcEdgeTwoPointsTangentDto=class{constructor(e,t,r){this.start=[0,0,0],this.tangentVec=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.tangentVec=t),void 0!==r&&(this.end=r)}},e.ArcEdgeCircleTwoPointsDto=class{constructor(e,t,r,i){this.start=[0,0,0],this.end=[0,0,1],this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.start=t),void 0!==r&&(this.end=r),void 0!==i&&(this.sense=i)}},e.ArcEdgeCircleTwoAnglesDto=class{constructor(e,t,r,i){this.alphaAngle1=0,this.alphaAngle2=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle1=t),void 0!==r&&(this.alphaAngle2=r),void 0!==i&&(this.sense=i)}},e.ArcEdgeCirclePointAngleDto=class{constructor(e,t,r,i){this.alphaAngle=90,this.sense=!0,void 0!==e&&(this.circle=e),void 0!==t&&(this.alphaAngle=t),void 0!==i&&(this.sense=i)}},e.ArcEdgeThreePointsDto=class{constructor(e,t,r){this.start=[0,0,0],this.middle=[0,1,0],this.end=[0,0,1],void 0!==e&&(this.start=e),void 0!==t&&(this.middle=t),void 0!==r&&(this.end=r)}},e.CylinderDto=class{constructor(e,t,r,i){this.radius=1,this.height=2,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.height=t),void 0!==r&&(this.center=r),void 0!==i&&(this.direction=i)}},e.CylindersOnLinesDto=class{constructor(e,t){void 0!==e&&(this.radius=e),void 0!==t&&(this.lines=t)}},e.FilletDto=class{constructor(e,t,r,i){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==r&&(this.radiusList=r),void 0!==i&&(this.indexes=i)}},e.FilletEdgesListDto=class{constructor(e,t,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radiusList=r)}},e.FilletEdgesListOneRadiusDto=class{constructor(e,t,r){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radius=r)}},e.FilletEdgeVariableRadiusDto=class{constructor(e,t,r,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.radiusList=r),void 0!==i&&(this.paramsU=i)}},e.FilletEdgesVariableRadiusDto=class{constructor(e,t,r,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radiusLists=r),void 0!==i&&(this.paramsULists=i)}},e.FilletEdgesSameVariableRadiusDto=class{constructor(e,t,r,i){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.radiusList=r),void 0!==i&&(this.paramsU=i)}},e.Fillet3DWireDto=class{constructor(e,t,r,i,n){this.radius=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==r&&(this.direction=r),void 0!==i&&(this.radiusList=i),void 0!==n&&(this.indexes=n)}},e.ChamferDto=class{constructor(e,t,r,i){this.distance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.distance=t),void 0!==r&&(this.distanceList=r),void 0!==i&&(this.indexes=i)}},e.ChamferEdgesListDto=class{constructor(e,t,r){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.distanceList=r)}},e.ChamferEdgeDistAngleDto=class{constructor(e,t,r,i,n){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.face=r),void 0!==i&&(this.distance=i),void 0!==n&&(this.angle=n)}},e.ChamferEdgeTwoDistancesDto=class{constructor(e,t,r,i,n){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.face=r),void 0!==i&&(this.distance1=i),void 0!==n&&(this.distance2=n)}},e.ChamferEdgesTwoDistancesListsDto=class{constructor(e,t,r,i,n){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distances1=i),void 0!==n&&(this.distances2=n)}},e.ChamferEdgesTwoDistancesDto=class{constructor(e,t,r,i,n){this.distance1=.1,this.distance2=.2,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distance1=i),void 0!==n&&(this.distance2=n)}},e.ChamferEdgesDistsAnglesDto=class{constructor(e,t,r,i,n){void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distances=i),void 0!==n&&(this.angles=n)}},e.ChamferEdgesDistAngleDto=class{constructor(e,t,r,i,n){this.distance=.1,this.angle=45,void 0!==e&&(this.shape=e),void 0!==t&&(this.edges=t),void 0!==r&&(this.faces=r),void 0!==i&&(this.distance=i),void 0!==n&&(this.angle=n)}},e.BSplineDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BSplinesDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bSplines=e),void 0!==t&&(this.returnCompound=t)}},e.WireFromTwoCirclesTanDto=class{constructor(e,t,r,i,n){this.keepLines=f.outside,this.circleRemainders=p.outside,this.tolerance=1e-7,void 0!==e&&(this.circle1=e),void 0!==t&&(this.circle2=t),void 0!==r&&(this.keepLines=r),void 0!==i&&(this.circleRemainders=i),void 0!==n&&(this.tolerance=n)}},e.FaceFromMultipleCircleTanWiresDto=class{constructor(e,t,r,i){this.combination=g.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.circles=e),void 0!==t&&(this.combination=t),void 0!==r&&(this.unify=r),void 0!==i&&(this.tolerance=i)}},e.FaceFromMultipleCircleTanWireCollectionsDto=class{constructor(e,t,r,i){this.combination=g.allWithAll,this.unify=!0,this.tolerance=1e-7,void 0!==e&&(this.listsOfCircles=e),void 0!==t&&(this.combination=t),void 0!==r&&(this.unify=r),void 0!==i&&(this.tolerance=i)}},e.ZigZagBetweenTwoWiresDto=class{constructor(e,t,r,i,n,s){this.nrZigZags=20,this.divideByEqualDistance=!1,this.zigZagsPerEdge=!0,void 0!==e&&(this.wire1=e),void 0!==t&&(this.wire2=t),void 0!==r&&(this.nrZigZags=r),void 0!==i&&(this.inverse=i),void 0!==n&&(this.divideByEqualDistance=n),void 0!==s&&(this.zigZagsPerEdge=s)}},e.InterpolationDto=class{constructor(e,t,r){this.periodic=!1,this.tolerance=1e-7,void 0!==e&&(this.points=e),void 0!==t&&(this.periodic=t),void 0!==r&&(this.tolerance=r)}},e.InterpolateWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.interpolations=e),void 0!==t&&(this.returnCompound=t)}},e.BezierDto=class{constructor(e,t){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.closed=t)}},e.BezierWeightsDto=class{constructor(e,t,r){this.closed=!1,void 0!==e&&(this.points=e),void 0!==t&&(this.weights=t),void 0!==r&&(this.closed=r)}},e.BezierWiresDto=class{constructor(e,t){this.returnCompound=!1,void 0!==e&&(this.bezierWires=e),void 0!==t&&(this.returnCompound=t)}},e.DivideDto=class{constructor(e,t,r,i){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==r&&(this.removeStartPoint=r),void 0!==i&&(this.removeEndPoint=i)}},e.ProjectWireDto=class{constructor(e,t,r){this.direction=[0,1,0],void 0!==e&&(this.wire=e),void 0!==t&&(this.shape=t),void 0!==r&&(this.direction=r)}},e.WiresToPointsDto=class{constructor(e,t,r,i,n,s){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==r&&(this.curvatureDeflection=r),void 0!==i&&(this.minimumOfPoints=i),void 0!==n&&(this.uTolerance=n),void 0!==s&&(this.minimumLength=s)}},e.EdgesToPointsDto=class{constructor(e,t,r,i,n,s){this.angularDeflection=.1,this.curvatureDeflection=.1,this.minimumOfPoints=2,this.uTolerance=1e-9,this.minimumLength=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.angularDeflection=t),void 0!==r&&(this.curvatureDeflection=r),void 0!==i&&(this.minimumOfPoints=i),void 0!==n&&(this.uTolerance=n),void 0!==s&&(this.minimumLength=s)}},e.ProjectWiresDto=class{constructor(e,t,r){this.direction=[0,1,0],void 0!==e&&(this.wires=e),void 0!==t&&(this.shape=t),void 0!==r&&(this.direction=r)}},e.DivideShapesDto=class{constructor(e,t,r,i){this.nrOfDivisions=10,this.removeStartPoint=!1,this.removeEndPoint=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==r&&(this.removeStartPoint=r),void 0!==i&&(this.removeEndPoint=i)}},e.DataOnGeometryAtParamDto=class{constructor(e,t){this.param=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t)}},e.PointInFaceDto=class{constructor(e,t,r,i){this.tEdgeParam=.5,this.distance2DParam=.5,void 0!==e&&(this.face=e),void 0!==t&&(this.edge=t),void 0!==r&&(this.tEdgeParam=r),void 0!==i&&(this.distance2DParam=i)}},e.DataOnGeometryAtLengthDto=class{constructor(e,t){this.length=.5,void 0!==e&&(this.shape=e),void 0!==t&&(this.length=t)}},e.CircleDto=class{constructor(e,t,r){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==r&&(this.direction=r)}},e.LoftDto=class{constructor(e,t){this.makeSolid=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t)}},e.LoftAdvancedDto=class{constructor(e,t,r,n,s,o,a,c,h,l,u,d){this.makeSolid=!1,this.closed=!1,this.periodic=!1,this.straight=!1,this.nrPeriodicSections=10,this.useSmoothing=!1,this.maxUDegree=3,this.tolerance=1e-7,this.parType=i.approxCentripetal,void 0!==e&&(this.shapes=e),void 0!==t&&(this.makeSolid=t),void 0!==r&&(this.closed=r),void 0!==n&&(this.periodic=n),void 0!==s&&(this.straight=s),void 0!==o&&(this.nrPeriodicSections=o),void 0!==a&&(this.useSmoothing=a),void 0!==c&&(this.maxUDegree=c),void 0!==h&&(this.tolerance=h),void 0!==l&&(this.parType=l),void 0!==u&&(this.startVertex=u),void 0!==d&&(this.endVertex=d)}},e.OffsetDto=class{constructor(e,t,r,i){this.distance=.2,this.tolerance=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.face=t),void 0!==r&&(this.distance=r),void 0!==i&&(this.tolerance=i)}},e.OffsetAdvancedDto=class{constructor(e,r,i,n,s,o){this.distance=.2,this.tolerance=.1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==r&&(this.face=r),void 0!==i&&(this.distance=i),void 0!==n&&(this.tolerance=n),void 0!==s&&(this.joinType=s),void 0!==o&&(this.removeIntEdges=o)}},e.RevolveDto=class{constructor(e,t,r,i){this.angle=360,this.direction=[0,1,0],this.copy=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==r&&(this.direction=r),void 0!==i&&(this.copy=i)}},e.ShapeShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.WiresOnFaceDto=class{constructor(e,t){void 0!==e&&(this.wires=e),void 0!==t&&(this.face=t)}},e.PipeWiresCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.radius=t)}},e.PipeWireCylindricalDto=class{constructor(e,t){this.radius=.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t)}},e.PipePolygonWireNGonDto=class{constructor(e,t,r){this.radius=.1,this.nrCorners=6,void 0!==e&&(this.shape=e),void 0!==t&&(this.radius=t),void 0!==r&&(this.nrCorners=r)}},e.ExtrudeDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t)}},e.ExtrudeShapesDto=class{constructor(e,t){this.direction=[0,1,0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.direction=t)}},e.SplitDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t)}},e.UnionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.DifferenceDto=class{constructor(e,t,r){this.keepEdges=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.shapes=t),void 0!==r&&(this.keepEdges=r)}},e.IntersectionDto=class{constructor(e,t){this.keepEdges=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.keepEdges=t)}},e.ShapeDto=class{constructor(e){void 0!==e&&(this.shape=e)}},e.CompareShapesDto=class{constructor(e,t){void 0!==e&&(this.shape=e),void 0!==t&&(this.otherShape=t)}},e.FixSmallEdgesInWireDto=class{constructor(e,t,r){this.lockvtx=!1,this.precsmall=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.lockvtx=t),void 0!==r&&(this.precsmall=r)}},e.BasicShapeRepairDto=class{constructor(e,t,r,i){this.precision=.001,this.maxTolerance=.01,this.minTolerance=1e-4,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==r&&(this.maxTolerance=r),void 0!==i&&(this.minTolerance=i)}},e.FixClosedDto=class{constructor(e,t){this.precision=-.1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t)}},e.ShapesWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.ShapeWithToleranceDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shape=e),void 0!==t&&(this.tolerance=t)}},e.ShapeIndexDto=class{constructor(e,t){this.index=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.EdgeIndexDto=class{constructor(e,t){this.index=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.index=t)}},e.RotationExtrudeDto=class{constructor(e,t,r){this.height=1,this.angle=360,void 0!==e&&(this.shape=e),void 0!==t&&(this.height=t),void 0!==r&&(this.angle=r)}},e.ThickSolidByJoinDto=class{constructor(e,r,i,n,s,o,a,c){this.offset=1,this.tolerance=.001,this.intersection=!1,this.selfIntersection=!1,this.joinType=t.arc,this.removeIntEdges=!1,void 0!==e&&(this.shape=e),void 0!==r&&(this.shapes=r),void 0!==i&&(this.offset=i),void 0!==n&&(this.tolerance=n),void 0!==s&&(this.intersection=s),void 0!==o&&(this.selfIntersection=o),void 0!==a&&(this.joinType=a),void 0!==c&&(this.removeIntEdges=c)}},e.TransformDto=class{constructor(e,t,r,i,n){this.translation=[0,0,0],this.rotationAxis=[0,1,0],this.rotationAngle=0,this.scaleFactor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t),void 0!==r&&(this.rotationAxis=r),void 0!==i&&(this.rotationAngle=i),void 0!==n&&(this.scaleFactor=n)}},e.TransformShapesDto=class{constructor(e,t,r,i,n){this.translations=[[0,0,0]],this.rotationAxes=[[0,1,0]],this.rotationAngles=[0],this.scaleFactors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t),void 0!==r&&(this.rotationAxes=r),void 0!==i&&(this.rotationAngles=i),void 0!==n&&(this.scaleFactors=n)}},e.TranslateDto=class{constructor(e,t){this.translation=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.translation=t)}},e.TranslateShapesDto=class{constructor(e,t){this.translations=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.translations=t)}},e.AlignDto=class{constructor(e,t,r,i,n){this.fromOrigin=[0,0,0],this.fromDirection=[0,0,1],this.toOrigin=[0,1,0],this.toDirection=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.fromOrigin=t),void 0!==r&&(this.fromDirection=r),void 0!==i&&(this.toOrigin=i),void 0!==n&&(this.toDirection=n)}},e.AlignShapesDto=class{constructor(e,t,r,i,n){this.fromOrigins=[[0,0,0]],this.fromDirections=[[0,0,1]],this.toOrigins=[[0,1,0]],this.toDirections=[[0,1,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.fromOrigins=t),void 0!==r&&(this.fromDirections=r),void 0!==i&&(this.toOrigins=i),void 0!==n&&(this.toDirections=n)}},e.MirrorDto=class{constructor(e,t,r){this.origin=[0,0,0],this.direction=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==r&&(this.direction=r)}},e.MirrorShapesDto=class{constructor(e,t,r){this.origins=[[0,0,0]],this.directions=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==r&&(this.directions=r)}},e.MirrorAlongNormalDto=class{constructor(e,t,r){this.origin=[0,0,0],this.normal=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.origin=t),void 0!==r&&(this.normal=r)}},e.MirrorAlongNormalShapesDto=class{constructor(e,t,r){this.origins=[[0,0,0]],this.normals=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.origins=t),void 0!==r&&(this.normals=r)}},e.AlignAndTranslateDto=class{constructor(e,t,r){this.direction=[0,1,0],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.center=r)}},e.UnifySameDomainDto=class{constructor(e,t,r,i){this.unifyEdges=!0,this.unifyFaces=!0,this.concatBSplines=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.unifyEdges=t),void 0!==r&&(this.unifyFaces=r),void 0!==i&&(this.concatBSplines=i)}},e.FilterFacePointsDto=class{constructor(e,t,r,i,n,s,o,a,c){this.tolerance=1e-4,this.useBndBox=!1,this.gapTolerance=.1,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.useBndBox=i),void 0!==n&&(this.gapTolerance=n),void 0!==s&&(this.keepIn=s),void 0!==o&&(this.keepOn=o),void 0!==a&&(this.keepOut=a),void 0!==c&&(this.keepUnknown=c)}},e.FilterSolidPointsDto=class{constructor(e,t,r,i,n,s,o){this.tolerance=1e-4,this.keepIn=!0,this.keepOn=!0,this.keepOut=!1,this.keepUnknown=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.points=t),void 0!==r&&(this.tolerance=r),void 0!==i&&(this.keepIn=i),void 0!==n&&(this.keepOn=n),void 0!==s&&(this.keepOut=s),void 0!==o&&(this.keepUnknown=o)}},e.AlignAndTranslateShapesDto=class{constructor(e,t,r){this.directions=[[0,1,0]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.directions=t),void 0!==r&&(this.centers=r)}},e.RotateDto=class{constructor(e,t,r){this.axis=[0,0,1],this.angle=0,void 0!==e&&(this.shape=e),void 0!==t&&(this.axis=t),void 0!==r&&(this.angle=r)}},e.RotateAroundCenterDto=class{constructor(e,t,r,i){this.angle=0,this.center=[0,0,0],this.axis=[0,0,1],void 0!==e&&(this.shape=e),void 0!==t&&(this.angle=t),void 0!==r&&(this.center=r),void 0!==i&&(this.axis=i)}},e.RotateShapesDto=class{constructor(e,t,r){this.angles=[0],void 0!==e&&(this.shapes=e),void 0!==t&&(this.axes=t),void 0!==r&&(this.angles=r)}},e.RotateAroundCenterShapesDto=class{constructor(e,t,r,i){this.angles=[0],this.centers=[[0,0,0]],this.axes=[[0,0,1]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.angles=t),void 0!==r&&(this.centers=r),void 0!==i&&(this.axes=i)}},e.ScaleDto=class{constructor(e,t){this.factor=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.factor=t)}},e.ScaleShapesDto=class{constructor(e,t){this.factors=[1],void 0!==e&&(this.shapes=e),void 0!==t&&(this.factors=t)}},e.Scale3DDto=class{constructor(e,t,r){this.scale=[1,1,1],this.center=[0,0,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.scale=t),void 0!==r&&(this.center=r)}},e.Scale3DShapesDto=class{constructor(e,t,r){this.scales=[[1,1,1]],this.centers=[[0,0,0]],void 0!==e&&(this.shapes=e),void 0!==t&&(this.scales=t),void 0!==r&&(this.centers=r)}},e.ShapeToMeshDto=class{constructor(e,t,r){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.precision=t),void 0!==r&&(this.adjustYtoZ=r)}},e.ShapesToMeshesDto=class{constructor(e,t,r){this.precision=.01,this.adjustYtoZ=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.precision=t),void 0!==r&&(this.adjustYtoZ=r)}},e.SaveStepDto=class{constructor(e,t,r,i){this.fileName="shape.step",this.adjustYtoZ=!1,this.tryDownload=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==r&&(this.adjustYtoZ=r),void 0!==i&&(this.tryDownload=i)}},e.SaveStlDto=class{constructor(e,t,r,i,n,s){this.fileName="shape.stl",this.precision=.01,this.adjustYtoZ=!1,this.tryDownload=!0,this.binary=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.fileName=t),void 0!==r&&(this.precision=r),void 0!==i&&(this.adjustYtoZ=i),void 0!==n&&(this.tryDownload=n),void 0!==s&&(this.binary=s)}},e.ImportStepIgesFromTextDto=class{constructor(e,t,r){this.fileType=s.step,this.adjustZtoY=!0,void 0!==e&&(this.text=e),void 0!==t&&(this.fileType=t),void 0!==r&&(this.adjustZtoY=r)}},e.ImportStepIgesDto=class{constructor(e,t){this.adjustZtoY=!0,void 0!==e&&(this.assetFile=e),void 0!==t&&(this.adjustZtoY=t)}},e.LoadStepOrIgesDto=class{constructor(e,t,r){this.fileName="shape.igs",this.adjustZtoY=!0,void 0!==e&&(this.filetext=e),void 0!==t&&(this.fileName=t),void 0!==r&&(this.adjustZtoY=r)}},e.CompoundShapesDto=class{constructor(e){void 0!==e&&(this.shapes=e)}},e.ThisckSolidSimpleDto=class{constructor(e,t){this.offset=1,void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t)}},e.Offset3DWireDto=class{constructor(e,t,r){this.offset=1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.offset=t),void 0!==r&&(this.direction=r)}},e.FaceFromWireDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.planar=t)}},e.FaceFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.FacesFromWiresDto=class{constructor(e,t){this.planar=!1,void 0!==e&&(this.shapes=e),void 0!==t&&(this.planar=t)}},e.SewDto=class{constructor(e,t){this.tolerance=1e-7,void 0!==e&&(this.shapes=e),void 0!==t&&(this.tolerance=t)}},e.FaceIsoCurveAtParamDto=class{constructor(e,t,r){this.dir="u",void 0!==e&&(this.shape=e),void 0!==t&&(this.param=t),void 0!==r&&(this.dir=r)}},e.DivideFaceToUVPointsDto=class{constructor(e,t,r,i){this.nrOfPointsU=10,this.nrOfPointsV=10,this.flat=!1,void 0!==e&&(this.shape=e),void 0!==t&&(this.nrOfPointsU=t),void 0!==r&&(this.nrOfPointsV=r),void 0!==i&&(this.flat=i)}},e.Geom2dEllipseDto=class{constructor(e,t,r,i,n){this.center=[0,0],this.direction=[1,0],this.radiusMinor=1,this.radiusMajor=2,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.radiusMinor=r),void 0!==i&&(this.radiusMajor=i),void 0!==n&&(this.sense=n)}},e.Geom2dCircleDto=class{constructor(e,t,r,i){this.center=[0,0],this.direction=[1,0],this.radius=1,this.sense=!1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.radius=r),void 0!==i&&(this.sense=i)}},e.ChristmasTreeDto=class{constructor(e,t,r,i,n,s,o,a,c,h){this.height=6,this.innerDist=1.5,this.outerDist=3,this.nrSkirts=5,this.trunkHeight=1,this.trunkWidth=1,this.half=!1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.innerDist=t),void 0!==r&&(this.outerDist=r),void 0!==i&&(this.nrSkirts=i),void 0!==n&&(this.trunkHeight=n),void 0!==s&&(this.trunkWidth=s),void 0!==o&&(this.half=o),void 0!==a&&(this.rotation=a),void 0!==c&&(this.origin=c),void 0!==h&&(this.direction=h)}},e.StarDto=class{constructor(e,t,r,i,n,s,o){this.center=[0,0,0],this.direction=[0,1,0],this.numRays=7,this.half=!1,void 0!==e&&(this.outerRadius=e),void 0!==t&&(this.innerRadius=t),void 0!==r&&(this.numRays=r),void 0!==i&&(this.center=i),void 0!==n&&(this.direction=n),void 0!==s&&(this.offsetOuterEdges=s),void 0!==o&&(this.half=o)}},e.ParallelogramDto=class{constructor(e,t,r,i,n,s){this.center=[0,0,0],this.direction=[0,1,0],this.aroundCenter=!0,this.width=2,this.height=1,this.angle=15,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.aroundCenter=r),void 0!==i&&(this.width=i),void 0!==n&&(this.height=n),void 0!==s&&(this.angle=s)}},e.Heart2DDto=class{constructor(e,t,r,i){this.center=[0,0,0],this.direction=[0,1,0],this.rotation=0,this.sizeApprox=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.rotation=r),void 0!==i&&(this.sizeApprox=i)}},e.NGonWireDto=class{constructor(e,t,r,i){this.center=[0,0,0],this.direction=[0,1,0],this.nrCorners=6,this.radius=1,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.nrCorners=r),void 0!==i&&(this.radius=i)}},e.EllipseDto=class{constructor(e,t,r,i){this.center=[0,0,0],this.direction=[0,1,0],this.radiusMinor=1,this.radiusMajor=2,void 0!==e&&(this.center=e),void 0!==t&&(this.direction=t),void 0!==r&&(this.radiusMinor=r),void 0!==i&&(this.radiusMajor=i)}},e.GeomCylindricalSurfaceDto=class{constructor(e,t,r){this.radius=1,this.center=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.radius=e),void 0!==t&&(this.center=t),void 0!==r&&(this.direction=r)}},e.Geom2dTrimmedCurveDto=class{constructor(e,t,r,i,n){this.u1=0,this.u2=1,this.sense=!0,this.adjustPeriodic=!0,void 0!==e&&(this.shape=e),void 0!==t&&(this.u1=t),void 0!==r&&(this.u2=r),void 0!==i&&(this.sense=i),void 0!==n&&(this.adjustPeriodic=n)}},e.Geom2dSegmentDto=class{constructor(e,t){this.start=[0,0],this.end=[1,0],void 0!==e&&(this.start=e),void 0!==t&&(this.end=t)}},e.SliceDto=class{constructor(e,t,r){this.step=.1,this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.step=t),void 0!==r&&(this.direction=r)}},e.SliceInStepPatternDto=class{constructor(e,t,r){this.steps=[.1,.2],this.direction=[0,1,0],void 0!==e&&(this.shape=e),void 0!==t&&(this.steps=t),void 0!==r&&(this.direction=r)}}}(U||(U={})),function(e){let t;!function(e){e.default="default",e.clearSky="clearSky",e.city="city"}(t=e.skyboxEnum||(e.skyboxEnum={}))}(W||(W={}));class z{constructor(e,t){this.occ=e,this.och=t}geom2dEllipse(e){const t=this.och.entitiesService.gpAx2d(e.center,e.direction),r=new this.occ.Geom2d_Ellipse_2(t,e.radiusMajor,e.radiusMinor,e.sense);return t.delete(),r}geom2dCircle(e){const t=this.och.entitiesService.gpAx2d(e.center,e.direction),r=new this.occ.Geom2d_Circle_2(t,e.radius,e.sense);return t.delete(),r}geom2dTrimmedCurve(e){const t=new this.occ.Handle_Geom2d_Curve_2(e.shape);return new this.occ.Geom2d_TrimmedCurve(t,e.u1,e.u2,e.sense,e.adjustPeriodic)}geom2dSegment(e){const t=this.och.entitiesService.gpPnt2d(e.start),r=this.och.entitiesService.gpPnt2d(e.end),i=new this.occ.GCE2d_MakeSegment_1(t,r),n=i.Value().get();return t.delete(),r.delete(),i.delete(),n}get2dPointFrom2dCurveOnParam(e){const t=e.shape.Value(e.param),r=[t.X(),t.Y()];return t.delete(),r}geomCircleCurve(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.curve)}geomEllipseCurve(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.curve)}}class j{constructor(e,t){this.occ=e,this.och=t}cylindricalSurface(e){const t=this.och.entitiesService.gpAx3(e.center,e.direction),r=new this.occ.Geom_CylindricalSurface_1(t,e.radius);return t.delete(),r}surfaceFromFace(e){return this.och.surfaceFromFace(e)}}class q{constructor(e,t){this.curves=new z(e,t),this.surfaces=new j(e,t)}}class ${constructor(e,t){this.occ=e,this.och=t}makeEdgeFromGeom2dCurveAndSurface(e){return this.och.edgesService.makeEdgeFromGeom2dCurveAndSurface(e)}line(e){return this.och.edgesService.lineEdge(e)}arcThroughThreePoints(e){return this.och.edgesService.arcThroughThreePoints(e)}arcThroughTwoPointsAndTangent(e){return this.och.edgesService.arcThroughTwoPointsAndTangent(e)}arcFromCircleAndTwoPoints(e){return this.och.edgesService.arcFromCircleAndTwoPoints(e)}arcFromCircleAndTwoAngles(e){return this.och.edgesService.arcFromCircleAndTwoAngles(e)}arcFromCirclePointAndAngle(e){return this.och.edgesService.arcFromCirclePointAndAngle(e)}createCircleEdge(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.edge)}createEllipseEdge(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.edge)}removeInternalEdges(e){const t=new this.occ.ShapeUpgrade_UnifySameDomain_2(e.shape,!0,!0,!1);t.Build();const r=t.Shape();return t.delete(),r}getEdge(e){return this.och.shapeGettersService.getEdge(e)}edgesToPoints(e){return this.och.edgesService.edgesToPoints(e)}reversedEdge(e){const t=e.shape.Reversed(),r=this.och.converterService.getActualTypeOfShape(t);return t.delete(),r}pointOnEdgeAtParam(e){return this.och.edgesService.pointOnEdgeAtParam(e)}tangentOnEdgeAtParam(e){return this.och.edgesService.tangentOnEdgeAtParam(e)}startPointOnEdge(e){return this.och.edgesService.startPointOnEdge(e)}endPointOnEdge(e){return this.och.edgesService.endPointOnEdge(e)}pointOnEdgeAtLength(e){return this.och.edgesService.pointOnEdgeAtLength(e)}tangentOnEdgeAtLength(e){return this.och.edgesService.tangentOnEdgeAtLength(e)}divideEdgeByParamsToPoints(e){return this.och.edgesService.divideEdgeByParamsToPoints(e)}divideEdgeByEqualDistanceToPoints(e){return this.och.edgesService.divideEdgeByEqualDistanceToPoints(e)}getEdges(e){return this.och.shapeGettersService.getEdges(e)}getEdgesAlongWire(e){return this.och.edgesService.getEdgesAlongWire(e)}getCircularEdgesAlongWire(e){return this.och.edgesService.getCircularEdgesAlongWire(e)}getLinearEdgesAlongWire(e){return this.och.edgesService.getLinearEdgesAlongWire(e)}getEdgeLength(e){return this.och.edgesService.getEdgeLength(e)}getEdgesLengths(e){return this.och.edgesService.getEdgesLengths(e)}getEdgeCenterOfMass(e){return this.och.geomService.getLinearCenterOfMass(e)}getEdgesCentersOfMass(e){return this.och.edgesService.getEdgesCentersOfMass(e)}getCornerPointsOfEdgesForShape(e){return this.och.edgesService.getCornerPointsOfEdgesForShape(e)}getCircularEdgeCenterPoint(e){return this.och.edgesService.getCircularEdgeCenterPoint(e)}getCircularEdgeRadius(e){return this.och.edgesService.getCircularEdgeRadius(e)}getCircularEdgePlaneDirection(e){return this.och.edgesService.getCircularEdgePlaneDirection(e)}constraintTanLinesFromTwoPtsToCircle(e){return this.och.edgesService.constraintTanLinesFromTwoPtsToCircle(e)}constraintTanLinesFromPtToCircle(e){return this.och.edgesService.constraintTanLinesFromPtToCircle(e)}constraintTanLinesOnTwoCircles(e){return this.och.edgesService.constraintTanLinesOnTwoCircles(e)}constraintTanCirclesOnTwoCircles(e){return this.och.edgesService.constraintTanCirclesOnTwoCircles(e)}constraintTanCirclesOnCircleAndPnt(e){return this.och.edgesService.constraintTanCirclesOnCircleAndPnt(e)}}class Y{constructor(e,t){this.occ=e,this.och=t}createFaceFromWire(e){return this.och.facesService.createFaceFromWire(e)}createFaceFromWires(e){return this.och.facesService.createFaceFromWires(e)}createFacesFromWires(e){return this.och.facesService.createFacesFromWires(e)}faceFromSurface(e){return this.och.facesService.faceFromSurface(e)}faceFromSurfaceAndWire(e){return this.och.facesService.faceFromSurfaceAndWire(e)}getUMinBound(e){return this.och.facesService.getUMinBound(e)}getUMaxBound(e){return this.och.facesService.getUMaxBound(e)}getVMinBound(e){return this.och.facesService.getVMinBound(e)}getVMaxBound(e){return this.och.facesService.getVMaxBound(e)}subdivideToPointsControlled(e){return this.och.facesService.subdivideToPointsControlled(e)}subdivideToPoints(e){return this.och.facesService.subdivideToPoints(e)}subdivideToNormals(e){return this.och.facesService.subdivideToNormals(e)}subdivideToPointsOnParam(e){return this.och.facesService.subdivideToPointsOnParam(e)}subdivideToUVOnParam(e){return this.och.facesService.subdivideToUVOnParam(e)}subdivideToUV(e){return this.och.facesService.subdivideToUV(e)}uvOnFace(e){return this.och.facesService.uvOnFace(e)}pointsOnUVs(e){return this.och.facesService.pointsOnUVs(e)}normalsOnUVs(e){return this.och.facesService.normalsOnUVs(e)}pointOnUV(e){return this.och.facesService.pointOnUV(e)}normalOnUV(e){return this.och.facesService.faceNormalOnUV(e)}createPolygonFace(e){return this.och.facesService.createPolygonFace(e)}createCircleFace(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.face)}createEllipseFace(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.face)}createSquareFace(e){return this.och.facesService.createSquareFace(e)}createRectangleFace(e){return this.och.facesService.createRectangleFace(e)}createFaceFromMultipleCircleTanWireCollections(e){return this.och.facesService.createFaceFromMultipleCircleTanWireCollections(e)}createFaceFromMultipleCircleTanWires(e){return this.och.facesService.createFaceFromMultipleCircleTanWires(e)}getFace(e){return this.och.shapeGettersService.getFace(e)}getFaces(e){return this.och.shapeGettersService.getFaces(e)}reversedFace(e){const t=e.shape.Reversed(),r=this.och.converterService.getActualTypeOfShape(t);return t.delete(),r}getFaceArea(e){return this.och.facesService.getFaceArea(e)}getFacesAreas(e){return this.och.facesService.getFacesAreas(e)}getFaceCenterOfMass(e){return this.och.facesService.getFaceCenterOfMass(e)}getFacesCentersOfMass(e){return this.och.facesService.getFacesCentersOfMass(e)}filterFacePoints(e){return this.och.facesService.filterFacePoints(e)}}class X{constructor(e,t){this.occ=e,this.och=t}makeCompound(e){return this.och.converterService.makeCompound(e)}}class Z{constructor(e,t){this.occ=e,this.och=t}vertexFromPoint(e){return this.och.entitiesService.makeVertex(e.point)}verticesFromPoints(e){return e.points.map((e=>this.vertexFromPoint({point:e})))}verticesCompoundFromPoints(e){const t=this.verticesFromPoints(e);return this.och.converterService.makeCompound({shapes:t})}getVertices(e){return this.och.shapeGettersService.getVertices(e)}getVerticesAsPoints(e){return this.och.verticesService.getVerticesAsPoints(e)}verticesToPoints(e){return this.och.verticesService.verticesToPoints(e)}vertexToPoint(e){return this.och.converterService.vertexToPoint(e)}}class J{constructor(e,t){this.occ=e,this.och=t}purgeInternalEdges(e){const t=new this.occ.TopOpeBRepTool_PurgeInternalEdges(e.shape,!0);if(t.Perform(),t.IsDone())return t.Shape();throw new Error("Could not purge internal edges for the shape")}unifySameDomain(e){const t=new this.occ.ShapeUpgrade_UnifySameDomain_2(e.shape,e.unifyEdges,e.unifyFaces,e.concatBSplines);return t.Build(),t.Shape()}isClosed(e){return e.shape.Closed_1()}isConvex(e){return e.shape.Convex_1()}isChecked(e){return e.shape.Checked_1()}isFree(e){return e.shape.Free_1()}isInfinite(e){return e.shape.Infinite_1()}isModified(e){return e.shape.Modified_1()}isLocked(e){return e.shape.Locked_1()}isNull(e){return e.shape.IsNull()}isEqual(e){return e.shape.IsEqual(e.otherShape)}isNotEqual(e){return e.shape.IsNotEqual(e.otherShape)}isPartner(e){return e.shape.IsPartner(e.otherShape)}isSame(e){return e.shape.IsSame(e.otherShape)}getOrientation(e){const t=e.shape.Orientation_1();let r;return t===this.occ.TopAbs_Orientation.TopAbs_FORWARD?r=U.topAbsOrientationEnum.forward:t===this.occ.TopAbs_Orientation.TopAbs_REVERSED?r=U.topAbsOrientationEnum.reversed:t===this.occ.TopAbs_Orientation.TopAbs_INTERNAL?r=U.topAbsOrientationEnum.internal:t===this.occ.TopAbs_Orientation.TopAbs_EXTERNAL&&(r=U.topAbsOrientationEnum.external),r}getShapeType(e){return this.och.enumService.getShapeTypeEnum(e.shape)}}class Q{constructor(e,t){this.occ=e,this.och=t}sewFaces(e){return this.och.shellsService.sewFaces(e)}isClosed(e){return this.occ.BRep_Tool.IsClosed_1(e.shape)}getShellSurfaceArea(e){return this.och.shellsService.getShellSurfaceArea(e)}}class K{constructor(e,t){this.occ=e,this.och=t}fromClosedShell(e){return this.och.solidsService.fromClosedShell(e)}createBox(e){return this.och.solidsService.createBox(e)}createCube(e){return this.och.solidsService.createCube(e)}createBoxFromCorner(e){return this.och.solidsService.createBoxFromCorner(e)}createCylinder(e){return this.och.solidsService.createCylinder(e)}createCylindersOnLines(e){return this.och.solidsService.createCylindersOnLines(e)}createSphere(e){return this.och.solidsService.createSphere(e)}createCone(e){return this.och.solidsService.createCone(e)}getSolidSurfaceArea(e){return this.och.solidsService.getSolidSurfaceArea(e)}getSolidVolume(e){return this.och.solidsService.getSolidVolume(e)}getSolidsVolumes(e){return this.och.solidsService.getSolidsVolumes(e)}getSolidCenterOfMass(e){return this.och.solidsService.getSolidCenterOfMass(e)}getSolidsCentersOfMass(e){return this.och.solidsService.getSolidsCentersOfMass(e)}getSolids(e){return this.och.solidsService.getSolids(e)}filterSolidPoints(e){return this.och.solidsService.filterSolidPoints(e)}}class ee{constructor(e,t){this.occ=e,this.och=t}createPolygonWire(e){return this.och.wiresService.createPolygonWire(e)}createPolygons(e){const t=e.polygons.map((e=>this.createPolygonWire(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createPolylineWire(e){return this.och.wiresService.createPolylineWire(e)}createPolylines(e){const t=e.polylines.map((e=>this.createPolylineWire(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createLineWire(e){return this.och.wiresService.createLineWire(e)}createLines(e){const t=e.lines.map((e=>this.createLineWire(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createBezier(e){return this.och.wiresService.createBezier(e)}createBezierWires(e){const t=e.bezierWires.map((e=>this.createBezier(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createBezierWeights(e){return this.och.wiresService.createBezierWeights(e)}interpolatePoints(e){return this.och.wiresService.interpolatePoints(e)}interpolateWires(e){const t=e.interpolations.map((e=>this.interpolatePoints(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}splitOnPoints(e){return this.och.wiresService.splitOnPoints(e)}combineEdgesAndWiresIntoAWire(e){return this.och.converterService.combineEdgesAndWiresIntoAWire(e)}createWireFromEdge(e){return this.och.wiresService.createWireFromEdges(e)}addEdgesAndWiresToWire(e){return this.och.wiresService.addEdgesAndWiresToWire(e)}createBSpline(e){return this.och.wiresService.createBSpline(e)}createBSplines(e){const t=e.bSplines.map((e=>this.createBSpline(e))).filter((e=>void 0!==e));return this.och.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createZigZagBetweenTwoWires(e){return this.och.wiresService.createZigZagBetweenTwoWires(e)}divideWireByParamsToPoints(e){return this.och.wiresService.divideWireByParamsToPoints(e)}divideWiresByParamsToPoints(e){return e.shapes.map((t=>this.divideWireByParamsToPoints(Object.assign(Object.assign({},e),{shape:t}))))}divideWireByEqualDistanceToPoints(e){return this.och.wiresService.divideWireByEqualDistanceToPoints(e)}divideWiresByEqualDistanceToPoints(e){return e.shapes.map((t=>this.divideWireByEqualDistanceToPoints(Object.assign(Object.assign({},e),{shape:t}))))}pointOnWireAtParam(e){return this.och.wiresService.pointOnWireAtParam(e)}pointOnWireAtLength(e){return this.och.wiresService.pointOnWireAtLength(e)}tangentOnWireAtParam(e){return this.och.wiresService.tangentOnWireAtParam(e)}tangentOnWireAtLength(e){return this.och.wiresService.tangentOnWireAtLength(e)}derivativesOnWireAtLength(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1),i=new this.occ.GCPnts_AbscissaPoint_2(r,e.length,r.FirstParameter()),n=i.Parameter(),s=this.och.entitiesService.gpPnt([0,0,0]),o=this.och.entitiesService.gpVec([0,0,0]),a=this.och.entitiesService.gpVec([0,0,0]),c=this.och.entitiesService.gpVec([0,0,0]);r.D3(n,s,o,a,c);const h=[[o.X(),o.Y(),o.Z()],[a.X(),a.Y(),a.Z()],[c.X(),c.Y(),c.Z()]];return o.delete(),a.delete(),c.delete(),r.delete(),i.delete(),s.delete(),h}derivativesOnWireAtParam(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1),i=this.och.entitiesService.gpPnt([0,0,0]),n=this.och.entitiesService.gpVec([0,0,0]),s=this.och.entitiesService.gpVec([0,0,0]),o=this.och.entitiesService.gpVec([0,0,0]),a=this.och.vecHelper.remap(e.param,0,1,r.FirstParameter(),r.LastParameter());r.D3(a,i,n,s,o);const c=[[n.X(),n.Y(),n.Z()],[s.X(),s.Y(),s.Z()],[o.X(),o.Y(),o.Z()]];return n.delete(),s.delete(),o.delete(),r.delete(),i.delete(),c}startPointOnWire(e){return this.och.wiresService.startPointOnWire(e)}endPointOnWire(e){return this.och.wiresService.endPointOnWire(e)}createCircleWire(e){return this.och.entitiesService.createCircle(e.radius,e.center,e.direction,U.typeSpecificityEnum.wire)}createEllipseWire(e){return this.och.entitiesService.createEllipse(e.radiusMinor,e.radiusMajor,e.center,e.direction,U.typeSpecificityEnum.wire)}createSquareWire(e){return this.och.wiresService.createSquareWire(e)}createStarWire(e){return this.och.wiresService.createStarWire(e)}createChristmasTreeWire(e){return this.och.wiresService.createChristmasTreeWire(e)}createParallelogramWire(e){return this.och.wiresService.createParallelogramWire(e)}createHeartWire(e){return this.och.wiresService.createHeartWire(e)}createNGonWire(e){return this.och.wiresService.createNGonWire(e)}createRectangleWire(e){return this.och.wiresService.createRectangleWire(e)}createLPolygonWire(e){return this.och.wiresService.createLPolygonWire(e)}getWire(e){return this.och.shapeGettersService.getWire(e)}getWires(e){return this.och.shapeGettersService.getWires(e)}getWireLength(e){return this.och.wiresService.getWireLength(e)}getWiresLengths(e){return this.och.wiresService.getWiresLengths(e)}getWireCenterOfMass(e){return this.och.wiresService.getWireCenterOfMass(e)}getWiresCentersOfMass(e){return e.shapes.map((e=>this.och.wiresService.getWireCenterOfMass({shape:e})))}reversedWire(e){const t=e.shape.Reversed(),r=this.och.converterService.getActualTypeOfShape(t);return t.delete(),r}reversedWireFromReversedEdges(e){const t=e.shape,r=this.och.edgesService.getEdgesAlongWire({shape:t}).map((e=>this.och.converterService.getActualTypeOfShape(e.Reversed()))),i=this.och.converterService.combineEdgesAndWiresIntoAWire({shapes:r.reverse()}),n=this.och.converterService.getActualTypeOfShape(i);return i.delete(),r.forEach((e=>e.delete())),n}placeWireOnFace(e){const t=e.wire,r=e.face,i=this.och.surfaceFromFace({shape:r});return this.och.wiresService.placeWire(t,i)}placeWiresOnFace(e){const t=e.wires,r=e.face,i=this.och.surfaceFromFace({shape:r});return t.map((e=>this.och.wiresService.placeWire(e,i)))}closeOpenWire(e){const t=e.shape,r=this.och.wiresService.startPointOnWire({shape:t}),i=this.och.wiresService.endPointOnWire({shape:t});if(this.och.vecHelper.vectorsTheSame(r,i,1e-7))return t;const n=this.createLineWire({start:i,end:r}),s=this.addEdgesAndWiresToWire({shape:t,shapes:[n]});return n.delete(),s}project(e){const t=e.wire,r=this.och.entitiesService.gpDir(e.direction),i=new this.occ.BRepProj_Projection_1(t,e.shape,r),n=i.Shape();return r.delete(),i.delete(),n}wiresToPoints(e){const t=this.getWires({shape:e.shape}),r=[];return t.forEach((t=>{const i=this.och.edgesService.edgesToPoints(Object.assign(Object.assign({},e),{shape:t})).flat(),n=this.och.vecHelper.removeConsecutiveDuplicates(i,!1);r.push(n)})),r}projectWires(e){const t=[];return e.wires.forEach((r=>{const i=this.och.entitiesService.gpDir(e.direction),n=new this.occ.BRepProj_Projection_1(r,e.shape,i),s=n.Shape();t.push(s),i.delete(),n.delete()})),t}createWireFromTwoCirclesTan(e){return this.och.wiresService.createWireFromTwoCirclesTan(e)}}class te{constructor(e,t){this.vertex=new Z(e,t),this.edge=new $(e,t),this.wire=new ee(e,t),this.face=new Y(e,t),this.shell=new Q(e,t),this.solid=new K(e,t),this.compound=new X(e,t),this.shape=new J(e,t)}}class re{constructor(e){this.occ=e}BRep_Tool_Range_1(e,t,r){return this.occ.BRep_Tool.Range_1(e,t,r)}BRep_Tool_Curve_2(e,t,r){return this.occ.BRep_Tool.Curve_2(e,t,r)}BRepTools_UVBounds_1(e,t,r,i,n){return this.occ.BRepTools.UVBounds_1(e,t,r,i,n)}}class ie{constructor(e){this.occ=e}forEachWire(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_WIRE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_WIRE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Wire_2(i.Current()));i.delete()}forEachEdge(e,t){const r={};let i=0;const n=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(n.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);n.More();n.Next()){const e=this.occ.TopoDS.Edge_1(n.Current()),s=e.HashCode(1e8);Object.prototype.hasOwnProperty.call(r,s)||(r[s]=i,i++,t(i,e))}return n.delete(),r}forEachEdgeAlongWire(e,t){const r={};let i=0;const n=new this.occ.BRepTools_WireExplorer_1;for(n.Init_1(e);n.More();n.Next()){const e=this.occ.TopoDS.Edge_1(n.Current()),s=e.HashCode(1e8);Object.prototype.hasOwnProperty.call(r,s)||(r[s]=i,i++,t(i,e))}return n.delete(),r}forEachFace(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_FACE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_FACE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Face_1(i.Current()));i.delete()}forEachShell(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_SHELL,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_SHELL,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Shell_1(i.Current()));i.delete()}forEachVertex(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Vertex_1(i.Current()));i.delete()}forEachSolid(e,t){let r=0;const i=new this.occ.TopExp_Explorer_2(e,this.occ.TopAbs_ShapeEnum.TopAbs_SOLID,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);for(i.Init(e,this.occ.TopAbs_ShapeEnum.TopAbs_SOLID,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);i.More();i.Next())t(r++,this.occ.TopoDS.Solid_2(i.Current()));i.delete()}}class ne{constructor(e){this.occ=e}getShapeTypeEnum(e){let t=U.shapeTypeEnum.unknown;const r=e.ShapeType();return t=r===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?U.shapeTypeEnum.edge:r===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE?U.shapeTypeEnum.wire:r===this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX?U.shapeTypeEnum.vertex:r===this.occ.TopAbs_ShapeEnum.TopAbs_SOLID?U.shapeTypeEnum.solid:r===this.occ.TopAbs_ShapeEnum.TopAbs_SHELL?U.shapeTypeEnum.shell:r===this.occ.TopAbs_ShapeEnum.TopAbs_FACE?U.shapeTypeEnum.face:r===this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID?U.shapeTypeEnum.compSolid:r===this.occ.TopAbs_ShapeEnum.TopAbs_COMPOUND?U.shapeTypeEnum.compound:U.shapeTypeEnum.shape,t}getGccEntPositionFromEnum(e){let t=this.occ.GccEnt_Position.GccEnt_noqualifier;return t=e===U.gccEntPositionEnum.unqualified?this.occ.GccEnt_Position.GccEnt_unqualified:e===U.gccEntPositionEnum.enclosed?this.occ.GccEnt_Position.GccEnt_enclosed:e===U.gccEntPositionEnum.enclosing?this.occ.GccEnt_Position.GccEnt_enclosing:e===U.gccEntPositionEnum.outside?this.occ.GccEnt_Position.GccEnt_outside:(U.gccEntPositionEnum.noqualifier,this.occ.GccEnt_Position.GccEnt_noqualifier),t}getTopAbsStateEnum(e){let t=U.topAbsStateEnum.unknown;return t=e===this.occ.TopAbs_State.TopAbs_IN?U.topAbsStateEnum.in:e===this.occ.TopAbs_State.TopAbs_OUT?U.topAbsStateEnum.out:e===this.occ.TopAbs_State.TopAbs_ON?U.topAbsStateEnum.on:U.topAbsStateEnum.unknown,t}convertFourSidesStrictEnumToTwoCircleInclusionEnum(e){return e===U.fourSidesStrictEnum.inside?U.twoCircleInclusionEnum.inside:e===U.fourSidesStrictEnum.outside?U.twoCircleInclusionEnum.outside:e===U.fourSidesStrictEnum.insideOutside?U.twoCircleInclusionEnum.insideOutside:e===U.fourSidesStrictEnum.outsideInside?U.twoCircleInclusionEnum.outsideInside:U.twoCircleInclusionEnum.none}}class se{constructor(e){this.occ=e}getActualTypeOfShape(e){let t=e;return t=e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?this.occ.TopoDS.Edge_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE?this.occ.TopoDS.Wire_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX?this.occ.TopoDS.Vertex_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SOLID?this.occ.TopoDS.Solid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SHELL?this.occ.TopoDS.Shell_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_FACE?this.occ.TopoDS.Face_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID?this.occ.TopoDS.CompSolid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPOUND?this.occ.TopoDS.Compound_1(e):e,t}combineEdgesAndWiresIntoAWire(e){if(void 0===e.shapes)throw Error("Shapes are not defined");const t=new this.occ.BRepBuilderAPI_MakeWire_1;if(e.shapes.forEach((e=>{e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?t.Add_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE&&t.Add_2(e)})),t.IsDone()){this.occ.BRepLib.BuildCurves3d_1(t.Wire(),1e-7,this.occ.GeomAbs_Shape.GeomAbs_C1,14,0);const e=t.Wire();return t.delete(),e}{let e;const r=t.Error();throw t.delete(),r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_DisconnectedWire?e="Wire is disconnected and can not be constructed":r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_EmptyWire?e="Wire is empty and can not be constructed":r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_NonManifoldWire?e="Wire is non manifold and can not be constructed":r===this.occ.BRepBuilderAPI_WireError.BRepBuilderAPI_WireDone&&(e="Wire is done"),new Error(e)}}vertexToPoint(e){const t=this.occ.BRep_Tool.Pnt(e.shape),r=[t.X(),t.Y(),t.Z()];return t.delete(),r}getGeomCurveFromEdge(e,t,r){const i=e.Location_1();return this.occ.BRep_Tool.Curve_1(e,i,t,r).get()}makeCompound(e){const t=new this.occ.TopoDS_Compound,r=new this.occ.BRep_Builder;return r.MakeCompound(t),e.shapes.forEach((e=>{const i=new this.occ.BRepBuilderAPI_Copy_2(e,!0,!1),n=i.Shape();r.Add(t,n),i.delete(),n.delete()})),r.delete(),t}makeCompoundIfNeeded(e,t){if(t){const t=this.makeCompound({shapes:e});return e.forEach((e=>e.delete())),t}return e}}class oe{constructor(e){this.occ=e}createCircle(e,t,r,i){const n=this.gcMakeCircle(t,r,e);if(i===U.typeSpecificityEnum.curve)return n;{const e=this.bRepBuilderAPIMakeEdge(n);if(i===U.typeSpecificityEnum.edge)return e;{const t=this.bRepBuilderAPIMakeWire(e);if(i===U.typeSpecificityEnum.wire)return e.delete(),t;if(i===U.typeSpecificityEnum.face)return this.bRepBuilderAPIMakeFaceFromWire(t,!0)}}return n}createEllipse(e,t,r,i,n){const s=this.gcMakeEllipse(r,i,e,t);if(n===U.typeSpecificityEnum.curve)return s;{const e=this.bRepBuilderAPIMakeEdge(s);if(n===U.typeSpecificityEnum.edge)return e;{const t=this.bRepBuilderAPIMakeWire(e);if(n===U.typeSpecificityEnum.wire)return e.delete(),t;if(n===U.typeSpecificityEnum.face)return this.bRepBuilderAPIMakeFaceFromWire(t,!0)}}return s}makeVertex(e){const t=this.gpPnt(e),r=new this.occ.BRepBuilderAPI_MakeVertex(t),i=r.Vertex();return t.delete(),r.delete(),i}gpPnt2d(e){return new this.occ.gp_Pnt2d_3(e[0],e[1])}gpPnt(e){return new this.occ.gp_Pnt_3(e[0],e[1],e[2])}gpVec(e){return new this.occ.gp_Vec_4(e[0],e[1],e[2])}gpXYZ(e){return new this.occ.gp_XYZ_2(e[0],e[1],e[2])}gpVec2d(e){return new this.occ.gp_Vec2d_4(e[0],e[1])}gpDir(e){return new this.occ.gp_Dir_4(e[0],e[1],e[2])}gpDir2d(e){return new this.occ.gp_Dir2d_4(e[0],e[1])}gcMakeCircle(e,t,r){const i=new this.occ.GC_MakeCircle_2(this.gpAx2(e,t),r),n=i.Value().get();return i.delete(),n}gcMakeEllipse(e,t,r,i){const n=this.gpAx2(e,t),s=new this.occ.GC_MakeEllipse_2(n,i,r);if(s.IsDone()){const e=s.Value().get();return s.delete(),n.delete(),e}throw new Error("Ellipse could not be created.")}bRepBuilderAPIMakeEdge(e){const t=this.castToHandleGeomCurve(e),r=new this.occ.BRepBuilderAPI_MakeEdge_24(t),i=r.Edge();return r.delete(),t.delete(),i}bRepBuilderAPIMakeWire(e){const t=new this.occ.BRepBuilderAPI_MakeWire_2(e),r=t.Wire();return t.delete(),r}bRepBuilderAPIMakeShell(e){const t=this.occ.BRep_Tool.Surface_2(e),r=new this.occ.BRepBuilderAPI_MakeShell_2(t,!1),i=r.Shell();return r.delete(),t.delete(),i}bRepBuilderAPIMakeFaceFromWires(e,t){let r;const i=[];return e.forEach((e=>{if(i.length>0){const t=new this.occ.BRepBuilderAPI_MakeFace_22(i[i.length-1],e);i.push(t.Face()),t.delete()}else{const r=new this.occ.BRepBuilderAPI_MakeFace_15(e,t);i.push(r.Face()),r.delete()}})),i.length>0&&(r=i.pop(),i.forEach((e=>e.delete()))),r}bRepBuilderAPIMakeFaceFromWire(e,t){const r=new this.occ.BRepBuilderAPI_MakeFace_15(e,t),i=r.Face();return r.delete(),i}bRepBuilderAPIMakeFaceFromSurface(e,t){const r=new this.occ.Handle_Geom_Surface_2(e),i=new this.occ.BRepBuilderAPI_MakeFace_8(r,t),n=i.Face();return i.delete(),r.delete(),n}bRepBuilderAPIMakeFaceFromSurfaceAndWire(e,t,r){const i=new this.occ.Handle_Geom_Surface_2(e),n=new this.occ.BRepBuilderAPI_MakeFace_21(i,t,r),s=n.Face();return n.delete(),i.delete(),s}bRepPrimAPIMakeSphere(e,t,r){const i=this.gpAx2(e,t),n=new this.occ.BRepPrimAPI_MakeSphere_9(i,r),s=n.Shape();return n.delete(),i.delete(),s}gpAx3(e,t){return new this.occ.gp_Ax3_4(this.gpPnt(e),this.gpDir(t))}gpAx2(e,t){return new this.occ.gp_Ax2_3(this.gpPnt(e),this.gpDir(t))}gpAx2FromTwoVectors(e,t,r){return new this.occ.gp_Ax2_2(this.gpPnt(e),this.gpDir(t),this.gpDir(r))}gpAx1(e,t){return new this.occ.gp_Ax1_2(this.gpPnt(e),this.gpDir(t))}gpAx2d(e,t){const r=this.gpPnt2d(e),i=this.gpDir2d(t);return new this.occ.gp_Ax2d_2(r,i)}gpAx22d(e,t,r){const i=this.gpPnt2d(e),n=this.gpDir2d(t),s=this.gpDir2d(r),o=new this.occ.gp_Ax22d_2(i,n,s);return n.delete(),s.delete(),i.delete(),o}gpPln(e,t){const r=this.gpPnt(e),i=this.gpDir(t),n=new this.occ.gp_Pln_3(r,i);return r.delete(),i.delete(),n}bRepPrimAPIMakeCylinder(e,t,r,i){const n=this.gpAx2(e,t),s=new this.occ.BRepPrimAPI_MakeCylinder_3(n,r,i),o=s.Shape();return s.delete(),n.delete(),o}bRepPrimAPIMakeCylinderBetweenPoints(e,t,r){const i=this.gpPnt(e),n=this.gpPnt(t),s=new this.occ.gp_Vec_5(i,n),o=s.Magnitude(),a=this.gpAx2(e,[s.X(),s.Y(),s.Z()]),c=new this.occ.BRepPrimAPI_MakeCylinder_3(a,r,o),h=c.Shape();return c.delete(),a.delete(),i.delete(),n.delete(),s.delete(),h}bRepPrimAPIMakeBox(e,t,r,i){const n=this.gpPnt([-e/2+i[0],-r/2+i[1],-t/2+i[2]]),s=new this.occ.BRepPrimAPI_MakeBox_3(n,e,r,t),o=s.Shape();return s.delete(),n.delete(),o}castToHandleGeomCurve(e){return new this.occ.Handle_Geom_Curve_2(e)}}class ae{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.occ=e,this.enumService=t,this.entitiesService=r,this.converterService=i,this.booleansService=n,this.shapeGettersService=s,this.edgesService=o,this.transformsService=a,this.vecHelper=c,this.wiresService=h,this.facesService=l,this.shellsService=u}loftAdvanced(e){if(e.periodic&&!e.closed)throw new Error("Cant construct periodic non closed loft.");const t=new this.occ.BRepOffsetAPI_ThruSections(e.makeSolid,e.straight,e.tolerance),r=[],i=[];if(e.startVertex){const r=this.entitiesService.makeVertex(e.startVertex);t.AddVertex(r),i.push(r)}if(e.closed&&!e.periodic)e.shapes.push(e.shapes[0]);else if(e.closed&&e.periodic){const i=[];e.shapes.forEach((t=>{this.enumService.getShapeTypeEnum(t)===U.shapeTypeEnum.edge&&(t=this.entitiesService.bRepBuilderAPIMakeWire(t));const r=this.wiresService.divideWireByParamsToPoints({shape:t,nrOfDivisions:e.nrPeriodicSections,removeStartPoint:!1,removeEndPoint:!1});i.push(r)}));for(let n=0;n<=e.nrPeriodicSections;n++){const s=i.map((e=>e[n])),o=this.wiresService.interpolatePoints({points:s,tolerance:e.tolerance,periodic:!0});t.AddWire(o),r.push(o)}}e.periodic||e.shapes.forEach((e=>{t.AddWire(e)}));const n=[];if(e.endVertex){const r=this.entitiesService.makeVertex(e.endVertex);t.AddVertex(r),n.push(r)}let s;e.useSmoothing&&t.SetSmoothing(e.useSmoothing),e.maxUDegree&&t.SetMaxDegree(e.maxUDegree),e.parType===U.approxParametrizationTypeEnum.approxChordLength?s=this.occ.Approx_ParametrizationType.Approx_ChordLength:e.parType===U.approxParametrizationTypeEnum.approxCentripetal?s=this.occ.Approx_ParametrizationType.Approx_Centripetal:e.parType===U.approxParametrizationTypeEnum.approxIsoParametric&&(s=this.occ.Approx_ParametrizationType.Approx_IsoParametric),s&&t.SetParType(s),t.CheckCompatibility(!1);const o=t.Shape(),a=this.converterService.getActualTypeOfShape(o);return o.delete(),t.delete(),r.forEach((e=>e.delete())),i.forEach((e=>e.delete())),n.forEach((e=>e.delete())),a}closestPointsBetweenTwoShapes(e,t){const r=new this.occ.Message_ProgressRange_1,i=new this.occ.BRepExtrema_DistShapeShape_2(e,t,this.occ.Extrema_ExtFlag.Extrema_ExtFlag_MIN,this.occ.Extrema_ExtAlgo.Extrema_ExtAlgo_Grad,r),n=new this.occ.Message_ProgressRange_1;if(i.Perform(n),i.IsDone()&&i.NbSolution()>0){const e=i.PointOnShape1(1),t=i.PointOnShape2(1);return[[e.X(),e.Y(),e.Z()],[t.X(),t.Y(),t.Z()]]}throw new Error("Closest points could not be found.")}closestPointsOnShapeFromPoints(e){return e.points.map((e=>this.entitiesService.makeVertex(e))).map((t=>this.closestPointsBetweenTwoShapes(t,e.shape))).map((e=>e[1]))}closestPointsOnShapesFromPoints(e){const t=e.points.map((e=>this.entitiesService.makeVertex(e))),r=[];return e.shapes.forEach((e=>{const i=t.map((t=>this.closestPointsBetweenTwoShapes(t,e)));r.push(...i.map((e=>e[1])))})),r}distancesToShapeFromPoints(e){return e.points.map((e=>this.entitiesService.makeVertex(e))).map((t=>this.closestPointsBetweenTwoShapes(t,e.shape))).map((e=>this.vecHelper.distanceBetweenPoints(e[0],e[1])))}loft(e){const t=new this.occ.BRepOffsetAPI_ThruSections(e.makeSolid,!1,1e-6);e.shapes.forEach((e=>{this.enumService.getShapeTypeEnum(e)===U.shapeTypeEnum.edge&&(e=this.entitiesService.bRepBuilderAPIMakeWire(e)),t.AddWire(e)})),t.CheckCompatibility(!1);const r=t.Shape(),i=this.converterService.getActualTypeOfShape(r);return r.delete(),t.delete(),i}offset(e){return this.offsetAdv({shape:e.shape,face:e.face,distance:e.distance,tolerance:e.tolerance,joinType:U.joinTypeEnum.arc,removeIntEdges:!1})}offsetAdv(e){if(e.tolerance||(e.tolerance=.1),0===e.distance)return e.shape;let t;const r=this.getJoinType(e.joinType),i=this.occ.BRepOffset_Mode.BRepOffset_Skin,n=[];if(this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.wire||this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge){let s;this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge?(s=this.entitiesService.bRepBuilderAPIMakeWire(e.shape),n.push(s)):s=e.shape;try{t=new this.occ.BRepOffsetAPI_MakeOffset_1,e.face?t.Init_1(e.face,r,!1):t.Init_2(r,!1),t.AddWire(s);const i=new this.occ.Message_ProgressRange_1;t.Build(i),t.Perform(e.distance,0)}catch(n){t=new this.occ.BRepOffsetAPI_MakeOffsetShape,t.PerformByJoin(s,e.distance,e.tolerance,i,!1,!1,r,e.removeIntEdges,new this.occ.Message_ProgressRange_1)}}else{const n=e.shape;t=new this.occ.BRepOffsetAPI_MakeOffsetShape,t.PerformByJoin(n,e.distance,e.tolerance,i,!1,!1,r,e.removeIntEdges,new this.occ.Message_ProgressRange_1)}const s=t.Shape(),o=this.converterService.getActualTypeOfShape(s);return s.delete(),t&&t.delete(),n.forEach((e=>e.delete())),o}offset3DWire(e){const t=this.extrude({shape:e.shape,direction:e.direction}),r=this.makeThickSolidSimple({shape:t,offset:e.offset}),i=this.shapeGettersService.getEdges({shape:e.shape}).length,n=(4*i+2)/2-1,s=n-i+1,o=[];let a;this.shapeGettersService.getFaces({shape:r}).forEach(((e,t)=>{if(t>=s&&t<=n){const t=this.shapeGettersService.getEdges({shape:e})[2];o.push(t)}}));try{a=this.converterService.combineEdgesAndWiresIntoAWire({shapes:o}),a=a.Reversed(),a=this.converterService.getActualTypeOfShape(a)}catch(e){return a=o,a}return a}extrudeShapes(e){return e.shapes.map((t=>{const r=this.extrude({shape:t,direction:e.direction}),i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}))}extrude(e){const t=new this.occ.gp_Vec_4(e.direction[0],e.direction[1],e.direction[2]),r=new this.occ.BRepPrimAPI_MakePrism_1(e.shape,t,!1,!0),i=r.Shape();return r.delete(),t.delete(),i}splitShapeWithShapes(e){const t=new this.occ.TopTools_ListOfShape_1;return e.shapes.forEach((e=>{t.Append_1(e)})),this.occ.BitByBitDev.BitSplit(e.shape,t)}revolve(e){let t;if(e.angle||(e.angle=360),e.direction||(e.direction=[0,0,1]),e.angle>=360){const r=new this.occ.gp_Pnt_3(0,0,0),i=new this.occ.gp_Dir_4(e.direction[0],e.direction[1],e.direction[2]),n=new this.occ.gp_Ax1_2(r,i),s=new this.occ.BRepPrimAPI_MakeRevol_2(e.shape,n,e.copy);t=s.Shape(),s.delete(),r.delete(),i.delete(),n.delete()}else{const r=new this.occ.gp_Pnt_3(0,0,0),i=new this.occ.gp_Dir_4(e.direction[0],e.direction[1],e.direction[2]),n=new this.occ.gp_Ax1_2(r,i),s=new this.occ.BRepPrimAPI_MakeRevol_1(e.shape,n,.0174533*e.angle,e.copy);t=s.Shape(),s.delete(),r.delete(),i.delete(),n.delete()}const r=this.converterService.getActualTypeOfShape(t);return t.delete(),r}rotatedExtrude(e){const t=this.transformsService.translate({translation:[0,e.height,0],shape:e.shape}),r=this.transformsService.rotate({axis:[0,1,0],angle:e.angle,shape:t}),i=this.wiresService.createBSpline({points:[[0,0,0],[0,e.height,0]],closed:!1}),n=[];for(let t=0;t<=30;t++){const r=t/30;n.push([20*Math.sin(r*e.angle*.0174533),e.height*r,20*Math.cos(r*e.angle*.0174533)])}const s=this.wiresService.createBSpline({points:n,closed:!1}),o=new this.occ.BRepOffsetAPI_MakePipeShell(i);o.SetMode_5(s,!0,this.occ.BRepFill_TypeOfContact.BRepFill_NoContact),o.Add_1(e.shape,!1,!1),o.Add_1(r,!1,!1),o.Build(new this.occ.Message_ProgressRange_1),o.MakeSolid();const a=o.Shape(),c=this.converterService.getActualTypeOfShape(a);return a.delete(),o.delete(),s.delete(),i.delete(),r.delete(),t.delete(),c}pipe(e){const t=new this.occ.BRepOffsetAPI_MakePipeShell(e.shape);e.shapes.forEach((e=>{t.Add_1(e,!1,!1)})),t.Build(new this.occ.Message_ProgressRange_1),t.MakeSolid();const r=t.Shape(),i=this.converterService.getActualTypeOfShape(r);return r.delete(),t.delete(),i}pipePolylineWireNGon(e){const t=e.shape,r=[],i=this.shapeGettersService.getEdges({shape:t});i.forEach(((t,n)=>{const s=this.edgesService.startPointOnEdge({shape:t}),o=this.edgesService.tangentOnEdgeAtParam({shape:t,param:0});let a,c=o;if(n>0&&n{n.Add_1(e,!1,!1)})),n.Build(new this.occ.Message_ProgressRange_1),n.MakeSolid();const s=n.Shape(),o=this.converterService.getActualTypeOfShape(s);return s.delete(),n.delete(),o}pipeWireCylindrical(e){const t=e.shape,r=[],i=this.shapeGettersService.getEdges({shape:t});i.forEach(((t,n)=>{const s=this.edgesService.startPointOnEdge({shape:t}),o=this.edgesService.tangentOnEdgeAtParam({shape:t,param:0});let a,c=o;if(n>0&&n{n.Add_1(e,!1,!1)})),n.Build(new this.occ.Message_ProgressRange_1),n.MakeSolid();const s=n.Shape(),o=this.converterService.getActualTypeOfShape(s);return s.delete(),n.delete(),o}pipeWiresCylindrical(e){return e.shapes.map((t=>this.pipeWireCylindrical({shape:t,radius:e.radius})))}makeThickSolidSimple(e){const t=new this.occ.BRepOffsetAPI_MakeThickSolid;t.MakeThickSolidBySimple(e.shape,e.offset),t.Build(new this.occ.Message_ProgressRange_1);const r=t.Shape(),i=this.converterService.getActualTypeOfShape(r);let n=i;if(e.offset>0){const e=this.shapeGettersService.getFaces({shape:i}).map((e=>e.Reversed()));n=this.shellsService.sewFaces({shapes:e,tolerance:1e-7}),i.delete()}return t.delete(),r.delete(),n}makeThickSolidByJoin(e){const t=new this.occ.TopTools_ListOfShape_1;e.shapes.forEach((e=>{t.Append_1(e)}));const r=new this.occ.BRepOffsetAPI_MakeThickSolid,i=this.getJoinType(e.joinType);r.MakeThickSolidByJoin(e.shape,t,e.offset,e.tolerance,this.occ.BRepOffset_Mode.BRepOffset_Skin,e.intersection,e.selfIntersection,i,e.removeIntEdges,new this.occ.Message_ProgressRange_1);const n=r.Shape(),s=this.converterService.getActualTypeOfShape(n);return n.delete(),r.delete(),t.delete(),s}getJoinType(e){let t;switch(e){case U.joinTypeEnum.arc:t=this.occ.GeomAbs_JoinType.GeomAbs_Arc;break;case U.joinTypeEnum.intersection:t=this.occ.GeomAbs_JoinType.GeomAbs_Intersection;break;case U.joinTypeEnum.tangent:t=this.occ.GeomAbs_JoinType.GeomAbs_Tangent}return t}getBRepOffsetMode(e){let t;switch(e){case U.bRepOffsetModeEnum.skin:t=this.occ.BRepOffset_Mode.BRepOffset_Skin;break;case U.bRepOffsetModeEnum.pipe:t=this.occ.BRepOffset_Mode.BRepOffset_Pipe;break;case U.bRepOffsetModeEnum.rectoVerso:t=this.occ.BRepOffset_Mode.BRepOffset_RectoVerso}return t}slice(e){if(e.step<=0)throw new Error("Step needs to be positive.");const{bbox:t,transformedShape:r}=this.createBBoxAndTransformShape(e.shape,e.direction),i=[];if(!t.IsThin(1e-4)){const{minY:n,maxY:s,maxDist:o}=this.computeBounds(t),a=[];for(let t=n;t=h?c:h;return l*=1.2,{minY:i,maxY:n,maxDist:l}}applySlices(e,t,r,i){const n=[];if(this.enumService.getShapeTypeEnum(e)===U.shapeTypeEnum.solid)n.push(e);else{const t=this.shapeGettersService.getSolids({shape:e});n.push(...t)}if(0===n.length)throw new Error("No solids found to slice.");n.forEach((e=>{const n=new U.IntersectionDto;n.keepEdges=!0,n.shapes=[e];const s=this.converterService.makeCompound({shapes:t});n.shapes.push(s),this.booleansService.intersection(n).forEach((e=>{if(e&&!e.IsNull()){const t=this.transformsService.align({shape:e,fromOrigin:[0,0,0],fromDirection:[0,1,0],toOrigin:[0,0,0],toDirection:r});i.push(t)}}))}))}}class ce{constructor(e,t,r,i){this.occ=e,this.converterService=t,this.entitiesService=r,this.vecHelper=i}alignAndTranslate(e){const t=this.align({shape:e.shape,fromOrigin:[0,0,0],fromDirection:[0,1,0],toOrigin:[0,0,0],toDirection:e.direction}),r=this.translate({shape:t,translation:e.center});return t.delete(),r}translate(e){const t=new this.occ.gp_Trsf_1,r=new this.occ.gp_Vec_4(e.translation[0],e.translation[1],e.translation[2]);t.SetTranslation_1(r);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.converterService.getActualTypeOfShape(n);return n.delete(),t.delete(),i.delete(),r.delete(),s}mirror(e){const t=new this.occ.gp_Trsf_1,r=this.entitiesService.gpAx1(e.origin,e.direction);t.SetMirror_2(r);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.converterService.getActualTypeOfShape(n);return n.delete(),i.delete(),t.delete(),r.delete(),s}mirrorAlongNormal(e){const t=new this.occ.gp_Trsf_1,r=this.entitiesService.gpAx2(e.origin,e.normal);t.SetMirror_3(r);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.converterService.getActualTypeOfShape(n);return r.delete(),n.delete(),i.delete(),t.delete(),s}rotate(e){let t;if(0!==e.angle){const t=new this.occ.gp_Trsf_1,r=new this.occ.gp_Vec_4(e.axis[0],e.axis[1],e.axis[2]),i=new this.occ.gp_Dir_4(e.axis[0],e.axis[1],e.axis[2]),n=new this.occ.gp_Pnt_3(0,0,0),s=new this.occ.gp_Ax1_2(n,i);t.SetRotation_1(s,this.vecHelper.degToRad(e.angle));const o=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),a=o.Shape(),c=this.converterService.getActualTypeOfShape(a);return a.delete(),r.delete(),i.delete(),n.delete(),s.delete(),o.delete(),t.delete(),c}t=e.shape;const r=this.converterService.getActualTypeOfShape(t);return 0!==e.angle&&t.delete(),r}align(e){const t=new this.occ.gp_Trsf_1,r=this.entitiesService.gpAx3(e.fromOrigin,e.fromDirection),i=this.entitiesService.gpAx3(e.toOrigin,e.toDirection);t.SetDisplacement(r,i);const n=new this.occ.TopLoc_Location_2(t),s=e.shape.Moved(n,!1);t.delete(),r.delete(),i.delete();const o=this.converterService.getActualTypeOfShape(s);return s.delete(),o}}class he{constructor(e,t){this.occ=e,this.shapeGettersService=t}intersection(e){if(e.shapes.length<2)throw new Error("Intersection requires 2 or more shapes to be given");const t=e.shapes[0];let r=[];for(let i=1;i0&&(r=r.map((e=>{const t=new this.occ.ShapeUpgrade_UnifySameDomain_2(e,!0,!0,!1);t.Build();const r=t.Shape();return t.delete(),r}))),r}difference(e){let t=e.shape;const r=e.shapes;for(let e=0;e{t++})),t}getSolidFromCompound(e,t){if(!e||e.ShapeType()>this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID||e.IsNull())return console.error("Not a compound shape!"),e;t||(t=0);let r=e,i=0;return this.iteratorService.forEachSolid(e,((e,n)=>{e===t&&(r=this.occ.TopoDS.Solid_1(n)),i++})),0===i&&console.error("NO SOLIDS FOUND IN SHAPE!"),r.hash=e.hash+1,r}getEdges(e){if(e.shape&&this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge)return[e.shape];if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is of incorrect type");const t=[];return this.iteratorService.forEachEdge(e.shape,((e,r)=>{t.push(r)})),t}getEdge(e){if(!e.shape||e.shape.ShapeType&&e.shape.ShapeType()>this.occ.TopAbs_ShapeEnum.TopAbs_WIRE||e.shape.IsNull())throw new Error("Edge can not be found for shape that is not provided or is of incorrect type");e.index||(e.index=0);let t={},r=!1;if(this.iteratorService.forEachEdge(e.shape,((i,n)=>{i===e.index&&(t=n,r=!0)})),r)return t;throw new Error(`Edge can not be found for shape on index ${e.index}`)}getWires(e){const t=[];return this.iteratorService.forEachWire(e.shape,((e,r)=>{t.push(r)})),t}getWire(e){if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is null");const t=this.enumService.getShapeTypeEnum(e.shape);if(t===U.shapeTypeEnum.wire||t===U.shapeTypeEnum.edge||t===U.shapeTypeEnum.vertex)throw new Error("Shape is of incorrect type");let r;if(e.index||(e.index=0),this.iteratorService.forEachWire(e.shape,((t,i)=>{t===e.index&&(r=this.occ.TopoDS.Wire_1(i))})),!r)throw Error("Wire not found");return r}getFaces(e){const t=[];return this.iteratorService.forEachFace(e.shape,((e,r)=>{t.push(r)})),t}getSolids(e){const t=[];return this.iteratorService.forEachSolid(e.shape,((e,r)=>{t.push(r)})),t}getFace(e){if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is null");const t=this.enumService.getShapeTypeEnum(e.shape);if(t===U.shapeTypeEnum.wire||t===U.shapeTypeEnum.edge||t===U.shapeTypeEnum.vertex)throw new Error("Shape is of incorrect type");e.index||(e.index=0);let r={},i=0;if(this.iteratorService.forEachFace(e.shape,((t,n)=>{t===e.index&&(r=this.occ.TopoDS.Face_1(n)),i++})),i{t.push(r)})),t}}class ue{constructor(e,t,r,i,n,s,o,a,c,h){this.occ=e,this.occRefReturns=t,this.shapeGettersService=r,this.entitiesService=i,this.iteratorService=n,this.converterService=s,this.enumService=o,this.geomService=a,this.transformsService=c,this.vecHelper=h}getCornerPointsOfEdgesForShape(e){const t=this.shapeGettersService.getEdges(e);let r=[];return t.forEach((e=>{const t={current:0},i={current:0},n=this.occRefReturns.BRep_Tool_Curve_2(e,t,i);try{const e=n.get();if(e){const n=e.Value(t.current),s=e.Value(i.current),o=[n.X(),n.Y(),n.Z()],a=[s.X(),s.Y(),s.Z()];n.delete(),s.delete(),r.push(o),r.push(a)}}catch(e){console.log(e)}})),r.length>0&&(r=this.vecHelper.removeAllDuplicateVectors(r)),r}getCircularEdgesAlongWire(e){return this.getEdgesAlongWire(e).filter((e=>this.isEdgeCircular({shape:e})))}getLinearEdgesAlongWire(e){return this.getEdgesAlongWire(e).filter((e=>this.isEdgeLinear({shape:e})))}getEdgesAlongWire(e){if(e.shape&&this.enumService.getShapeTypeEnum(e.shape)===U.shapeTypeEnum.edge)return[e.shape];if(!e.shape||e.shape.IsNull())throw new Error("Shape is not provided or is of incorrect type");const t=[],r=this.fixEdgeOrientationsAlongWire(e);return this.iteratorService.forEachEdgeAlongWire(r,((e,r)=>{t.push(r)})),t}fixEdgeOrientationsAlongWire(e){const t=[];return this.iteratorService.forEachEdgeAlongWire(e.shape,((e,r)=>{t.push(r)})),this.converterService.combineEdgesAndWiresIntoAWire({shapes:t})}arcThroughThreePoints(e){const t=this.entitiesService.gpPnt(e.start),r=this.entitiesService.gpPnt(e.middle),i=this.entitiesService.gpPnt(e.end),n=new this.occ.GC_MakeArcOfCircle_4(t,r,i),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),r.delete(),i.delete(),n.delete(),s.delete(),o.delete(),a}arcThroughTwoPointsAndTangent(e){const t=this.entitiesService.gpPnt(e.start),r=this.entitiesService.gpVec(e.tangentVec),i=this.entitiesService.gpPnt(e.end),n=new this.occ.GC_MakeArcOfCircle_5(t,r,i),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),r.delete(),i.delete(),n.delete(),s.delete(),o.delete(),a}arcFromCircleAndTwoAngles(e){const t=this.getGpCircleFromEdge({shape:e.circle}),r=this.vecHelper.degToRad(e.alphaAngle1),i=this.vecHelper.degToRad(e.alphaAngle2),n=new this.occ.GC_MakeArcOfCircle_1(t,r,i,e.sense),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),n.delete(),s.delete(),o.delete(),a}arcFromCirclePointAndAngle(e){const t=this.getGpCircleFromEdge({shape:e.circle}),r=this.vecHelper.degToRad(e.alphaAngle),i=this.entitiesService.gpPnt(e.point),n=new this.occ.GC_MakeArcOfCircle_2(t,i,r,e.sense),s=new this.occ.Handle_Geom_Curve_2(n.Value().get()),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return t.delete(),n.delete(),i.delete(),s.delete(),o.delete(),a}lineEdge(e){const t=this.entitiesService.gpPnt(e.start),r=this.entitiesService.gpPnt(e.end),i=new this.occ.GC_MakeSegment_1(t,r).Value(),n=i.get(),s=new this.occ.Handle_Geom_Curve_2(n),o=new this.occ.BRepBuilderAPI_MakeEdge_24(s),a=o.Edge();return o.delete(),s.delete(),t.delete(),r.delete(),i.delete(),n.delete(),a}getEdgeLength(e){const t=e.shape,r=new this.occ.GProp_GProps_1;this.occ.BRepGProp.LinearProperties(t,r,!1,!1);const i=r.Mass();return r.delete(),i}getEdgesLengths(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getEdgeLength({shape:e})))}getEdgesCentersOfMass(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.geomService.getLinearCenterOfMass({shape:e})))}edgesToPoints(e){const t=this.enumService.getShapeTypeEnum(e.shape);let r=[];r=t===U.shapeTypeEnum.edge?[e.shape]:t===U.shapeTypeEnum.wire?this.getEdgesAlongWire({shape:e.shape}):this.shapeGettersService.getEdges({shape:e.shape});const i=[],n=r.map((e=>this.startPointOnEdge({shape:e})));return r.forEach((t=>{const r=[],n=new this.occ.TopLoc_Location_1,s=new this.occ.BRepAdaptor_Curve_2(t),o=new this.occ.GCPnts_TangentialDeflection_2(s,e.angularDeflection,e.curvatureDeflection,e.minimumOfPoints,e.uTolerance,e.minimumLength),a=o.NbPoints(),c=[];for(let e=0;ee.delete())),n.delete(),s.delete(),o.delete()})),i.forEach(((e,t)=>{const r=this.vecHelper.distanceBetweenPoints(e[0],n[t]);this.vecHelper.distanceBetweenPoints(n[t],e[e.length-1]){const r=new this.occ.GCPnts_AbscissaPoint_2(t,e,t.FirstParameter()),i=r.Parameter();return r.delete(),i})).map((e=>{const r=this.entitiesService.gpPnt([0,0,0]);t.D0(e,r);const i=[r.X(),r.Y(),r.Z()];return r.delete(),i}))}divideCurveToNrSegments(e,t,r){const i=e.shape,n=[];for(let i=0;i<=e.nrOfDivisions;i++){const s=i/e.nrOfDivisions,o=this.vecHelper.remap(s,0,1,t,r);n.push(o)}return e.removeStartPoint&&n.shift(),e.removeEndPoint&&n.pop(),n.map((e=>{const t=this.entitiesService.gpPnt([0,0,0]);i.D0(e,t);const r=[t.X(),t.Y(),t.Z()];return t.delete(),r}))}startPointOnCurve(e){const t=e.shape,r=this.entitiesService.gpPnt([0,0,0]);t.D0(t.FirstParameter(),r);const i=[r.X(),r.Y(),r.Z()];return r.delete(),i}endPointOnCurve(e){const t=e.shape,r=this.entitiesService.gpPnt([0,0,0]);t.D0(t.LastParameter(),r);const i=[r.X(),r.Y(),r.Z()];return r.delete(),i}getLinearCenterOfMass(e){const t=e.shape,r=new this.occ.GProp_GProps_1;this.occ.BRepGProp.LinearProperties(t,r,!1,!1);const i=r.CentreOfMass(),n=[i.X(),i.Y(),i.Z()];return r.delete(),n}}class pe{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.occ=e,this.occRefReturns=t,this.vecHelper=r,this.shapesHelperService=i,this.shapeGettersService=n,this.transformsService=s,this.enumService=o,this.entitiesService=a,this.converterService=c,this.geomService=h,this.edgesService=l,this.booleansService=u}getWireLength(e){return this.shapeGettersService.getEdges(e).map((e=>this.edgesService.getEdgeLength({shape:e}))).reduce(((e,t)=>e+t),0)}getWiresLengths(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getWireLength({shape:e})))}createRectangleWire(e){const t=e.width/2,r=e.length/2,i=[[t,0,r],[-t,0,r],[-t,0,-r],[t,0,-r]].reverse(),n=this.createPolygonWire({points:i}),s=this.transformsService.alignAndTranslate({shape:n,direction:e.direction,center:e.center});return n.delete(),s}createSquareWire(e){return this.createRectangleWire({width:e.size,length:e.size,center:e.center,direction:e.direction})}createChristmasTreeWire(e){const t=this.createLineWire({start:[e.innerDist,0,0],end:[0,e.height,0]}),r=this.createLineWire({start:[e.outerDist,0,0],end:[0,e.height,0]}),i=this.divideWireByEqualDistanceToPoints({shape:t,nrOfDivisions:e.nrSkirts,removeEndPoint:!1,removeStartPoint:!1}),n=this.divideWireByEqualDistanceToPoints({shape:r,nrOfDivisions:e.nrSkirts,removeEndPoint:!1,removeStartPoint:!1}),s=[];if(e.trunkWidth>0&&e.trunkHeight>0?(s.push([0,-e.trunkHeight,0]),s.push([e.trunkWidth/2,-e.trunkHeight,0]),s.push([e.trunkWidth/2,0,0])):s.push([0,0,0]),i.forEach(((t,r)=>{const i=n[r];0===r?s.push(i):0!==r&&r[-e[0],e[1],e[2]]));e.pop(),s.push(...e.reverse())}let o;if(e.trunkHeight>0&&e.trunkWidth>0){const t=s.map((t=>[t[0],t[1]+e.trunkHeight,t[2]]));o=this.createPolylineWire({points:t})}else o=this.createPolylineWire({points:s});const a=this.transformsService.rotate({shape:o,angle:e.rotation,axis:[0,1,0]});return this.transformsService.alignAndTranslate({shape:a,direction:e.direction,center:e.origin})}createStarWire(e){const t=this.shapesHelperService.starLines(e.innerRadius,e.outerRadius,e.numRays,e.half,e.offsetOuterEdges),r=[];t.forEach((e=>{r.push(this.edgesService.lineEdge(e))}));const i=this.converterService.combineEdgesAndWiresIntoAWire({shapes:r}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return i.delete(),n}createParallelogramWire(e){const t=this.shapesHelperService.parallelogram(e.width,e.height,e.angle,e.aroundCenter),r=[];t.forEach((e=>{r.push(this.edgesService.lineEdge(e))}));const i=this.converterService.combineEdgesAndWiresIntoAWire({shapes:r}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return i.delete(),n}createHeartWire(e){const t=e.sizeApprox/2,r=[[0,0,.7*t],[t/6,0,.9*t],[t/2,0,t],[.75*t,0,.9*t],[t,0,t/4],[t/2,0,-t/2],[0,0,-t]],i=r.map((e=>[-e[0],e[1],e[2]])),n=1e-5,s=this.interpolatePoints({points:r,periodic:!1,tolerance:n}),o=this.interpolatePoints({points:i.reverse(),periodic:!1,tolerance:n}),a=this.converterService.combineEdgesAndWiresIntoAWire({shapes:[s,o]}),c=this.transformsService.rotate({shape:a,angle:e.rotation,axis:[0,1,0]}),h=this.transformsService.alignAndTranslate({shape:c,direction:e.direction,center:e.center});return a.delete(),c.delete(),s.delete(),o.delete(),h}createNGonWire(e){const t=this.shapesHelperService.ngon(e.nrCorners,e.radius,[0,0]),r=[];t.forEach((e=>{r.push(this.edgesService.lineEdge(e))}));const i=this.converterService.combineEdgesAndWiresIntoAWire({shapes:r}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return i.delete(),n}createLPolygonWire(e){let t;switch(e.align){case U.directionEnum.outside:t=this.shapesHelperService.polygonL(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond);break;case U.directionEnum.inside:t=this.shapesHelperService.polygonLInverted(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond);break;case U.directionEnum.middle:t=this.shapesHelperService.polygonLMiddle(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond);break;default:t=this.shapesHelperService.polygonL(e.widthFirst,e.lengthFirst,e.widthSecond,e.lengthSecond)}const r=this.createPolygonWire({points:t}),i=this.transformsService.rotate({shape:r,angle:e.rotation,axis:[0,1,0]}),n=this.transformsService.alignAndTranslate({shape:i,direction:e.direction,center:e.center});return r.delete(),i.delete(),n}createPolygonWire(e){const t=[];for(let r=0;re.delete())),void t.delete();{const e=i.get(),n=new this.occ.Handle_Geom_Curve_2(e),s=new this.occ.BRepBuilderAPI_MakeEdge_24(n),o=s.Edge(),a=new this.occ.BRepBuilderAPI_MakeWire_2(o),c=a.Wire();return i.Nullify(),i.delete(),n.Nullify(),n.delete(),s.delete(),o.delete(),a.delete(),r.forEach((e=>e.delete())),t.delete(),c}}splitOnPoints(e){const t=1e-7,r=this.startPointOnWire({shape:e.shape}),i=this.endPointOnWire({shape:e.shape}),n=this.vecHelper.vectorsTheSame(i,r,t);n||(e.points.some((e=>this.vecHelper.vectorsTheSame(e,r,t)))||e.points.push(r),e.points.some((e=>this.vecHelper.vectorsTheSame(e,i,t)))||e.points.push(i));const s=this.createLines({lines:e.points.map((e=>({start:e,end:[e[0],e[1]+t,e[2]]}))),returnCompound:!1}),o=this.booleansService.difference({shape:e.shape,shapes:s,keepEdges:!0}),a=this.shapeGettersService.getEdges({shape:o}),c=[];a.forEach((r=>{const i=c[c.length-1],n=this.edgesService.endPointOnEdge({shape:r}),s=this.edgesService.startPointOnEdge({shape:r}),o=e.points.some((e=>this.vecHelper.vectorsTheSame(n,e,t))),a=e.points.some((e=>this.vecHelper.vectorsTheSame(s,e,t)));o&&!a?c.push([r]):!o&&a?i?i.push(r):c.push([r]):o&&a?c.push([r]):o||a||(i?i.push(r):c.push([r]))}));const h=[];if(c.forEach((e=>{const t=this.converterService.combineEdgesAndWiresIntoAWire({shapes:e});h.push(t)})),n&&h.length>1){const r=this.endPointOnWire({shape:h[0]}),i=this.startPointOnWire({shape:h[h.length-1]});if(this.vecHelper.vectorsTheSame(r,i,t)&&!e.points.find((e=>this.vecHelper.vectorsTheSame(e,r,t)))){const e=this.addEdgesAndWiresToWire({shape:h[h.length-1],shapes:[h[0]]});h[0]=e,h.pop()}}return h}createLines(e){const t=e.lines.map((e=>this.createLineWire(e))).filter((e=>void 0!==e));return this.converterService.makeCompoundIfNeeded(t,e.returnCompound)}createWireFromTwoCirclesTan(e){const t=this.shapeGettersService.getEdges({shape:e.circle1}),r=this.shapeGettersService.getEdges({shape:e.circle2});if(1===t.length&&1===r.length){const i=t[0],n=r[0],s=this.edgesService.constraintTanLinesOnTwoCircles({circle1:i,circle2:n,positionResult:e.keepLines===U.twoSidesStrictEnum.outside?U.positionResultEnum.keepSide2:U.positionResultEnum.keepSide1,circleRemainders:this.enumService.convertFourSidesStrictEnumToTwoCircleInclusionEnum(e.circleRemainders),tolerance:e.tolerance}),o=this.converterService.combineEdgesAndWiresIntoAWire({shapes:s});return s.forEach((e=>e.delete())),i.delete(),n.delete(),o}throw new Error("Could not find the edges of the provided circle wires.")}createZigZagBetweenTwoWires(e){const t=e.wire1,r=e.wire2;let i=[],n=[];if(e.zigZagsPerEdge){const s=this.edgesService.getEdgesAlongWire({shape:t}),o=this.edgesService.getEdgesAlongWire({shape:r});e.divideByEqualDistance?(i=s.map((t=>this.edgesService.divideEdgeByEqualDistanceToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1}))),n=o.map((t=>this.edgesService.divideEdgeByEqualDistanceToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1})))):(i=s.map((t=>this.edgesService.divideEdgeByParamsToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1}))),n=o.map((t=>this.edgesService.divideEdgeByParamsToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1}))))}else e.divideByEqualDistance?(i=[this.divideWireByEqualDistanceToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1})],n=[this.divideWireByEqualDistanceToPoints({shape:r,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1})]):(i=[this.divideWireByParamsToPoints({shape:t,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1})],n=[this.divideWireByParamsToPoints({shape:r,nrOfDivisions:2*e.nrZigZags,removeEndPoint:!1,removeStartPoint:!1})]);const s=i.map(((t,r)=>{const i=n[r],s=[];for(let r=0;re.delete())),t.delete(),i.delete(),n.Nullify(),n.delete(),o.Nullify(),o.delete(),a.delete(),c.delete(),h.delete(),l}createBezier(e){const t=new this.occ.TColgp_Array1OfPnt_2(1,e.points.length+(e.closed?1:0));for(let r=1;r<=e.points.length;r++)t.SetValue(r,this.entitiesService.gpPnt(e.points[r-1]));e.closed&&t.SetValue(e.points.length+1,t.Value(1));const r=new this.occ.Geom_BezierCurve_1(t),i=new this.occ.Handle_Geom_Curve_2(r),n=new this.occ.BRepBuilderAPI_MakeEdge_24(i),s=n.Edge(),o=new this.occ.BRepBuilderAPI_MakeWire_2(s),a=o.Wire();return o.delete(),n.delete(),s.delete(),i.delete(),t.delete(),a}createBezierWeights(e){if(!e.closed&&e.points.length!==e.weights.length)throw new Error("Number of points and weights must be the same when bezier is not clsoed.");if(e.closed&&e.points.length!==e.weights.length-1)throw new Error("Number of points must be one less than number of weights when bezier is clsoed.");const t=new this.occ.TColgp_Array1OfPnt_2(1,e.points.length+(e.closed?1:0));for(let r=1;r<=e.points.length;r++)t.SetValue(r,this.entitiesService.gpPnt(e.points[r-1]));e.closed&&t.SetValue(e.points.length+1,t.Value(1));const r=new this.occ.TColStd_Array1OfReal_2(1,e.weights.length);for(let t=1;t<=e.weights.length;t++)r.SetValue(t,e.weights[t-1]);const i=new this.occ.Geom_BezierCurve_2(t,r),n=new this.occ.Handle_Geom_Curve_2(i),s=new this.occ.BRepBuilderAPI_MakeEdge_24(n),o=s.Edge(),a=new this.occ.BRepBuilderAPI_MakeWire_2(o),c=a.Wire();return a.delete(),s.delete(),o.delete(),n.delete(),t.delete(),r.delete(),c}addEdgesAndWiresToWire(e){const t=new this.occ.BRepBuilderAPI_MakeWire_1;let r;if(t.Add_2(e.shape),e.shapes.forEach((e=>{e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?t.Add_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE&&t.Add_2(e)})),!t.IsDone())throw new Error("Wire could not be constructed. Check if edges and wires do not have disconnected elements.");return r=t.Wire(),t.delete(),r}startPointOnWire(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1);return this.geomService.startPointOnCurve(Object.assign(Object.assign({},e),{shape:r}))}endPointOnWire(e){const t=e.shape,r=new this.occ.BRepAdaptor_CompCurve_2(t,!1);return this.geomService.endPointOnCurve(Object.assign(Object.assign({},e),{shape:r}))}placeWire(e,t){const r=this.shapeGettersService.getEdges({shape:e}),i=[];r.forEach((e=>{const r={current:0},n={current:0};this.occRefReturns.BRep_Tool_Range_1(e,r,n);const s=this.occRefReturns.BRep_Tool_Curve_2(e,r,n);if(!s.IsNull()){const e=this.entitiesService.gpPln([0,0,0],[0,1,0]),o=this.occ.GeomAPI.To2d(s,e),a=o.get(),c=this.edgesService.makeEdgeFromGeom2dCurveAndSurfaceBounded({curve:a,surface:t},r.current,n.current);c&&i.push(c),e.delete(),o.delete()}s.delete()})),r.forEach((e=>e.delete()));const n=this.converterService.combineEdgesAndWiresIntoAWire({shapes:i});return i.forEach((e=>e.delete())),n}}class fe{constructor(e,t,r,i,n,s,o,a){this.occ=e,this.occRefReturns=t,this.entitiesService=r,this.enumService=i,this.shapeGettersService=n,this.converterService=s,this.booleansService=o,this.wiresService=a}createFaceFromWire(e){let t;if(this.enumService.getShapeTypeEnum(e.shape)!==U.shapeTypeEnum.wire)throw new Error("Provided input shape is not a wire");if(e.planar){const r=this.occ.TopoDS.Wire_1(e.shape);t=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(r,e.planar),r.delete()}else{const r=3,i=15,n=2,s=!1,o=1e-5,a=1e-4,c=.01,h=.1,l=8,u=9,d=new this.occ.BRepFill_Filling(r,i,n,s,o,a,c,h,l,u),p=this.shapeGettersService.getEdges(e);if(p.forEach((e=>{d.Add_1(e,this.occ.GeomAbs_Shape.GeomAbs_C0,!0)})),d.Build(),!d.IsDone())throw new Error("Could not create non planar face");t=d.Face(),d.delete(),p.forEach((e=>e.delete()))}return t}getFaceArea(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.SurfaceProperties_1(e.shape,t,!1,!1);const r=t.Mass();return t.delete(),r}getFacesAreas(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getFaceArea({shape:e})))}getFaceCenterOfMass(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.SurfaceProperties_1(e.shape,t,!1,!1);const r=t.CentreOfMass(),i=[r.X(),r.Y(),r.Z()];return t.delete(),r.delete(),i}getFacesCentersOfMass(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getFaceCenterOfMass({shape:e})))}filterFacePoints(e){const t=[];if(e.points.length>0){const r=new this.occ.BRepClass_FaceClassifier_1;return e.points.forEach((i=>{const n=this.entitiesService.gpPnt(i);r.Perform_2(e.shape,n,e.tolerance,e.useBndBox,e.gapTolerance);const s=r.State(),o=this.enumService.getTopAbsStateEnum(s);e.keepOn&&o===U.topAbsStateEnum.on&&t.push(i),e.keepIn&&o===U.topAbsStateEnum.in&&t.push(i),e.keepOut&&o===U.topAbsStateEnum.out&&t.push(i),e.keepUnknown&&o===U.topAbsStateEnum.unknown&&t.push(i),n.delete()})),r.delete(),t}return[]}createSquareFace(e){const t=this.wiresService.createSquareWire(e),r=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(t,!0);return t.delete(),r}createRectangleFace(e){const t=this.wiresService.createRectangleWire(e),r=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(t,!0);return t.delete(),r}createFaceFromMultipleCircleTanWires(e){const t=e.circles,r=[];if(e.combination===U.combinationCirclesForFaceEnum.allWithAll)for(let i=0;ithis.createFaceFromWire({shape:t,planar:e.planar})))}faceFromSurface(e){const t=this.entitiesService.bRepBuilderAPIMakeFaceFromSurface(e.shape,e.tolerance);if(t.IsNull())throw t.delete(),new Error("Could not construct a face from the surface. Check if surface is not infinite.");return t}faceFromSurfaceAndWire(e){const t=this.entitiesService.bRepBuilderAPIMakeFaceFromSurfaceAndWire(e.surface,e.wire,e.inside);if(t.IsNull())throw t.delete(),new Error("Could not construct a face from the surface. Check if surface is not infinite.");return t}getUMinBound(e){const t=e.shape,{uMin:r}=this.getUVBounds(t);return r}getUMaxBound(e){const t=e.shape,{uMax:r}=this.getUVBounds(t);return r}getVMinBound(e){const t=e.shape,{vMin:r}=this.getUVBounds(t);return r}getVMaxBound(e){const t=e.shape,{vMax:r}=this.getUVBounds(t);return r}subdivideToPointsControlled(e){if(void 0===e.shape)throw Error("Face not defined");const t=e.shape,r=this.occ.BRep_Tool.Surface_2(t),i=r.get(),{uMin:n,uMax:s,vMin:o,vMax:a}=this.getUVBounds(t),c=[];for(let t=0;t{const t=i+(n-i)*e[0],a=s+(o-s)*e[1],c=this.entitiesService.gpPnt([0,0,0]);r.D0(t,a,c);const h=[c.X(),c.Y(),c.Z()];return c.delete(),h}))}normalsOnUVs(e){if(void 0===e.shape)throw Error("Face not defined");const t=e.shape,r=this.occ.BRep_Tool.Surface_2(t),{uMin:i,uMax:n,vMin:s,vMax:o}=this.getUVBounds(t),a=e.paramsUV.map((e=>{const t=i+(n-i)*e[0],a=s+(o-s)*e[1],c=this.entitiesService.gpDir([0,1,0]);this.occ.GeomLib.NormEstim(r,this.entitiesService.gpPnt2d([t,a]),1e-7,c);const h=[c.X(),c.Y(),c.Z()];return c.delete(),h}));return r.delete(),a}pointOnUV(e){if(void 0===e.shape)throw Error("Face not defined");const t=e.shape,r=this.occ.BRep_Tool.Surface_2(t),i=r.get(),{uMin:n,uMax:s,vMin:o,vMax:a}=this.getUVBounds(t),c=n+(s-n)*e.paramU,h=o+(a-o)*e.paramV,l=this.entitiesService.gpPnt([0,0,0]);i.D0(c,h,l);const u=[l.X(),l.Y(),l.Z()];return l.delete(),r.delete(),u}normalOnUV(e){return this.faceNormalOnUV(e)}createPolygonFace(e){const t=this.wiresService.createPolygonWire(e),r=this.entitiesService.bRepBuilderAPIMakeFaceFromWire(t,!1);return t.delete(),r}}class ge{constructor(e,t){this.occ=e,this.shapeGettersService=t}getVerticesAsPoints(e){const t=this.shapeGettersService.getVertices(e);return this.verticesToPoints({shapes:t})}verticesToPoints(e){return e.shapes.map((e=>{const t=this.occ.BRep_Tool.Pnt(e),r=[t.X(),t.Y(),t.Z()];return t.delete(),r}))}}class ve{constructor(e,t,r,i){this.occ=e,this.shapeGettersService=t,this.converterService=r,this.facesService=i}getShellSurfaceArea(e){const t=this.shapeGettersService.getFaces(e);return this.facesService.getFacesAreas({shapes:t}).reduce(((e,t)=>e+t),0)}sewFaces(e){const t=new this.occ.BRepBuilderAPI_Sewing(e.tolerance,!0,!0,!0,!1);e.shapes.forEach((e=>{t.Add(e)}));const r=new this.occ.Message_ProgressRange_1;t.Perform(r);const i=t.SewedShape(),n=this.converterService.getActualTypeOfShape(i);return t.delete(),r.delete(),i.delete(),n}}class me{constructor(e,t,r,i,n,s,o,a,c){this.occ=e,this.vecHelper=t,this.iteratorService=r,this.converterService=i,this.entitiesService=n,this.transformsService=s,this.shapeGettersService=o,this.edgesService=a,this.operationsService=c}filletEdges(e){if(!e.indexes||e.indexes.length&&0===e.indexes.length){if(void 0===e.radius)throw Error("Radius not defined");const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational),r=new this.occ.TopExp_Explorer_2(e.shape,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE),i=[];for(;r.More();){const n=this.occ.TopoDS.Edge_1(r.Current());i.push(n),t.Add_2(e.radius,n),r.Next()}const n=t.Shape();return t.delete(),r.delete(),i.forEach((e=>e.delete())),n}if(e.indexes&&e.indexes.length>0){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);let r,i=0,n=0;const s=e.indexes;if(this.iteratorService.forEachEdge(e.shape,((r,o)=>{if(s.includes(r)){let r=e.radius;if(e.radiusList&&(r=e.radiusList[n],n++),void 0===r)throw Error("Radius not defined, or radiusList not correct length");t.Add_2(r,o),i++}})),0===i)throw new Error("Fillet Edges Not Found! Make sure you are looking at the object _before_ the Fillet is applied!");r=t.Shape(),t.delete();const o=this.converterService.getActualTypeOfShape(r);return r.delete(),o}}filletEdgesListOneRadius(e){if(e.edges&&e.edges.length>0){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach((r=>{t.Add_2(e.radius,r)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgesList(e){if(e.edges&&e.edges.length>0&&e.radiusList&&e.radiusList.length>0&&e.edges.length===e.radiusList.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach(((r,i)=>{t.Add_2(e.radiusList[i],r)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgeVariableRadius(e){if(e.paramsU&&e.paramsU.length>0&&e.radiusList&&e.radiusList.length>0&&e.paramsU.length===e.radiusList.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);this.assignVariableFilletToEdge(e,t);const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgesSameVariableRadius(e){if(e.edges&&e.edges.length>0&&e.radiusList&&e.radiusList.length>0&&e.paramsU.length===e.radiusList.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach((r=>{this.assignVariableFilletToEdge({edge:r,paramsU:e.paramsU,radiusList:e.radiusList,shape:e.shape},t)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}filletEdgesVariableRadius(e){if(e.edges&&e.edges.length>0&&e.radiusLists&&e.radiusLists.length>0&&e.paramsULists.length===e.radiusLists.length&&e.paramsULists.length===e.edges.length&&e.radiusLists.length===e.edges.length){const t=new this.occ.BRepFilletAPI_MakeFillet(e.shape,this.occ.ChFi3d_FilletShape.ChFi3d_Rational);e.edges.forEach(((r,i)=>{this.assignVariableFilletToEdge({edge:r,paramsU:e.paramsULists[i],radiusList:e.radiusLists[i],shape:e.shape},t)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}assignVariableFilletToEdge(e,t){const r=new this.occ.TColgp_Array1OfPnt2d_2(1,e.paramsU.length);e.paramsU.forEach(((t,i)=>{r.SetValue(i+1,this.entitiesService.gpPnt2d([t,e.radiusList[i]]))})),t.Add_5(r,e.edge)}chamferEdges(e){if(!e.indexes||e.indexes.length&&0===e.indexes.length){if(void 0===e.distance)throw Error("Distance is undefined");const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape),r=new this.occ.TopExp_Explorer_2(e.shape,this.occ.TopAbs_ShapeEnum.TopAbs_EDGE,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE),i=[];for(;r.More();){const n=this.occ.TopoDS.Edge_1(r.Current());i.push(n),t.Add_2(e.distance,n),r.Next()}const n=t.Shape();return t.delete(),r.delete(),i.forEach((e=>e.delete())),n}if(e.indexes&&e.indexes.length>0){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);let r,i=0,n=0;const s=e.indexes;this.iteratorService.forEachEdge(e.shape,((r,o)=>{if(s.includes(r)){let r=e.distance;if(e.distanceList&&(r=e.distanceList[n],n++),void 0===r)throw Error("Distance not defined and/or distance list incorrect length");t.Add_2(r,o),i++}})),0===i?(console.error("Chamfer Edges Not Found! Make sure you are looking at the object _before_ the Fillet is applied!"),r=e.shape):r=t.Shape(),t.delete();const o=this.converterService.getActualTypeOfShape(r);return r.delete(),o}}chamferEdgesList(e){if(e.edges&&e.edges.length>0&&e.distanceList&&e.distanceList.length>0&&e.edges.length===e.distanceList.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{const n=e.distanceList[i];if(void 0===n)throw Error("Distance is not defined");t.Add_2(n,r)}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgeTwoDistances(e){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);t.Add_3(e.distance1,e.distance2,e.edge,e.face);const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}chamferEdgesTwoDistances(e){if(e.edges&&e.edges.length>0&&e.edges.length===e.faces.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{t.Add_3(e.distance1,e.distance2,r,e.faces[i])}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgesTwoDistancesLists(e){if(e.edges&&e.edges.length>0&&e.faces&&e.faces.length>0&&e.distances1&&e.distances1.length>0&&e.distances2&&e.distances2.length>0&&e.edges.length===e.faces.length&&e.edges.length===e.distances1.length&&e.edges.length===e.distances2.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{t.Add_3(e.distances1[i],e.distances2[i],r,e.faces[i])}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgeDistAngle(e){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape),r=this.vecHelper.degToRad(e.angle);t.AddDA(e.distance,r,e.edge,e.face);const i=t.Shape();t.delete();const n=this.converterService.getActualTypeOfShape(i);return i.delete(),n}chamferEdgesDistsAngles(e){if(e.edges&&e.edges.length>0&&e.faces&&e.faces.length>0&&e.distances&&e.distances.length>0&&e.angles&&e.angles.length>0&&e.edges.length===e.distances.length&&e.edges.length===e.faces.length&&e.edges.length===e.angles.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape);e.edges.forEach(((r,i)=>{const n=this.vecHelper.degToRad(e.angles[i]);t.AddDA(e.distances[i],n,r,e.faces[i])}));const r=t.Shape();t.delete();const i=this.converterService.getActualTypeOfShape(r);return r.delete(),i}}chamferEdgesDistAngle(e){if(e.edges&&e.edges.length>0&&e.faces&&e.faces.length>0&&e.edges.length===e.faces.length){const t=new this.occ.BRepFilletAPI_MakeChamfer(e.shape),r=this.vecHelper.degToRad(e.angle);e.edges.forEach(((i,n)=>{t.AddDA(e.distance,r,i,e.faces[n])}));const i=t.Shape();t.delete();const n=this.converterService.getActualTypeOfShape(i);return i.delete(),n}}fillet3DWire(e){let t=!1;if(e.radiusList&&e.radiusList.length>0&&e.indexes&&e.indexes.length>0){if(e.radiusList.length!==e.indexes.length)throw new Error("Radius list and indexes are not the same length");t=!0}let r=this.edgesService.fixEdgeOrientationsAlongWire({shape:e.shape});if(t&&e.shape.Closed_1()){const t=this.edgesService.getEdgesAlongWire({shape:e.shape}),i=t.shift(),n=[...t,i];r=this.converterService.combineEdgesAndWiresIntoAWire({shapes:n})}else r=this.converterService.getActualTypeOfShape(e.shape.Reversed());const i=this.operationsService.extrude({shape:r,direction:e.direction});let n=e.indexes;if(t){const t=e.indexes.filter((e=>e>2)),r=Math.max(...t),i=[5];let s=5;for(let e=0;ee.shape.Closed_1()?t<=2?t:i[t-3]:1===t?2:i[t-2]))}const s=this.filletEdges({shape:i,radius:e.radius,indexes:n,radiusList:e.radiusList}),o=[],a=this.shapeGettersService.getFaces({shape:s});a.forEach(((e,t)=>{const r=this.shapeGettersService.getEdges({shape:e})[3];o.push(r)}));const c=this.converterService.combineEdgesAndWiresIntoAWire({shapes:o}),h=this.transformsService.translate({shape:c,translation:e.direction.map((e=>-e))});return i.delete(),s.delete(),a.forEach((e=>e.delete())),o.forEach((e=>e.delete())),h}}class ye{constructor(e,t,r,i,n,s,o){this.occ=e,this.shapeGettersService=t,this.facesService=r,this.enumService=i,this.entitiesService=n,this.converterService=s,this.transformsService=o}fromClosedShell(e){const t=this.converterService.getActualTypeOfShape(e.shape),r=new this.occ.BRepBuilderAPI_MakeSolid_3(t),i=r.Solid();return r.delete(),t.delete(),i}createBox(e){return this.entitiesService.bRepPrimAPIMakeBox(e.width,e.length,e.height,e.center)}createCube(e){return this.entitiesService.bRepPrimAPIMakeBox(e.size,e.size,e.size,e.center)}createBoxFromCorner(e){const t=this.entitiesService.bRepPrimAPIMakeBox(e.width,e.length,e.height,e.corner),r=this.transformsService.translate({shape:t,translation:[e.width/2,e.height/2,e.length/2]});return t.delete(),r}createCylinder(e){return this.entitiesService.bRepPrimAPIMakeCylinder(e.center,e.direction?e.direction:[0,1,0],e.radius,e.height)}createCylindersOnLines(e){return e.lines.map((t=>this.entitiesService.bRepPrimAPIMakeCylinderBetweenPoints(t.start,t.end,e.radius)))}createSphere(e){return this.entitiesService.bRepPrimAPIMakeSphere(e.center,[0,0,1],e.radius)}createCone(e){const t=this.entitiesService.gpAx2(e.center,e.direction),r=new this.occ.BRepPrimAPI_MakeCone_4(t,e.radius1,e.radius2,e.height,e.angle),i=r.Shape();return r.delete(),t.delete(),i}filterSolidPoints(e){const t=[];if(e.points.length>0){const r=new this.occ.BRepClass3d_SolidClassifier_1;return r.Load(e.shape),e.points.forEach((i=>{const n=this.entitiesService.gpPnt(i);r.Perform(n,e.tolerance);const s=r.State(),o=this.enumService.getTopAbsStateEnum(s);e.keepOn&&o===U.topAbsStateEnum.on&&t.push(i),e.keepIn&&o===U.topAbsStateEnum.in&&t.push(i),e.keepOut&&o===U.topAbsStateEnum.out&&t.push(i),e.keepUnknown&&o===U.topAbsStateEnum.unknown&&t.push(i),n.delete()})),r.delete(),t}return[]}getSolidVolume(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.VolumeProperties_1(e.shape,t,!0,!1,!1);const r=t.Mass();return t.delete(),r}getSolidSurfaceArea(e){const t=this.shapeGettersService.getFaces(e);return this.facesService.getFacesAreas({shapes:t}).reduce(((e,t)=>e+t),0)}getSolidsVolumes(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getSolidVolume({shape:e})))}getSolidCenterOfMass(e){const t=new this.occ.GProp_GProps_1;this.occ.BRepGProp.VolumeProperties_1(e.shape,t,!0,!1,!1);const r=t.CentreOfMass(),i=[r.X(),r.Y(),r.Z()];return t.delete(),r.delete(),i}getSolidsCentersOfMass(e){if(void 0===e.shapes)throw Error("Shapes are not defined");return e.shapes.map((e=>this.getSolidCenterOfMass({shape:e})))}getSolids(e){return this.shapeGettersService.getSolids(e)}}class Se{constructor(e,t,r){this.vecHelper=e,this.shapesHelperService=t,this.occ=r,this.occRefReturns=new re(r),this.iteratorService=new ie(r),this.enumService=new ne(r),this.converterService=new se(r),this.entitiesService=new oe(r),this.shapeGettersService=new le(r,this.enumService,this.iteratorService),this.geomService=new de(r,this.vecHelper,this.entitiesService),this.booleansService=new he(r,this.shapeGettersService),this.transformsService=new ce(r,this.converterService,this.entitiesService,this.vecHelper),this.verticesService=new ge(r,this.shapeGettersService),this.edgesService=new ue(r,this.occRefReturns,this.shapeGettersService,this.entitiesService,this.iteratorService,this.converterService,this.enumService,this.geomService,this.transformsService,this.vecHelper),this.wiresService=new pe(r,this.occRefReturns,this.vecHelper,this.shapesHelperService,this.shapeGettersService,this.transformsService,this.enumService,this.entitiesService,this.converterService,this.geomService,this.edgesService,this.booleansService),this.facesService=new fe(r,this.occRefReturns,this.entitiesService,this.enumService,this.shapeGettersService,this.converterService,this.booleansService,this.wiresService),this.shellsService=new ve(r,this.shapeGettersService,this.converterService,this.facesService),this.solidsService=new ye(r,this.shapeGettersService,this.facesService,this.enumService,this.entitiesService,this.converterService,this.transformsService),this.operationsService=new ae(r,this.enumService,this.entitiesService,this.converterService,this.booleansService,this.shapeGettersService,this.edgesService,this.transformsService,this.vecHelper,this.wiresService,this.facesService,this.shellsService),this.filletsService=new me(r,this.vecHelper,this.iteratorService,this.converterService,this.entitiesService,this.transformsService,this.shapeGettersService,this.edgesService,this.operationsService)}surfaceFromFace(e){const t=e.shape;return this.occ.BRep_Tool.Surface_2(t).get()}}class be{constructor(e,t){this.occ=e,this.och=t}union(e){return this.och.booleansService.union(e)}difference(e){return this.och.booleansService.difference(e)}intersection(e){const t=this.och.booleansService.intersection(e);return this.och.converterService.makeCompound({shapes:t})}}class we{constructor(e,t){this.occ=e,this.och=t}saveShapeSTEP(e){const t=e.shape;let r;if(e.adjustYtoZ){const t=this.och.transformsService.rotate({shape:e.shape,axis:[1,0,0],angle:-90});r=this.och.transformsService.mirrorAlongNormal({shape:t,origin:[0,0,0],normal:[0,0,1]}),t.delete()}const i=new this.occ.STEPControl_Writer_1;let n;n=r||t;const s=new this.occ.Message_ProgressRange_1;let o,a;try{o=i.Transfer(n,this.occ.STEPControl_StepModelType.STEPControl_AsIs,!0,s)}catch(e){throw new Error("Failed when calling writer.Transfer.")}if(o!==this.occ.IFSelect_ReturnStatus.IFSelect_RetDone)throw new Error("Failed when transfering to step writer.");if(i.Write("x")!==this.occ.IFSelect_ReturnStatus.IFSelect_RetDone)throw new Error("Failed when writing step file.");{const e=this.occ.FS.readFile("/x",{encoding:"utf8"});this.occ.FS.unlink("/x"),a=e}return r&&r.delete(),s.delete(),a}loadSTEPorIGES(e){const t=e.fileName,r=e.filetext,i=(()=>{switch(t.toLowerCase().split(".").pop()){case"step":case"stp":return"step";case"iges":case"igs":return"iges";default:return}})();let n;if(this.occ.FS.createDataFile("/",`file.${i}`,r,!0,!0,!0),"step"===i)n=new this.occ.STEPControl_Reader_1;else{if("iges"!==i)return void console.error("opencascade can't parse this extension! (yet)");n=new this.occ.IGESControl_Reader_1}if(n.ReadFile(`file.${i}`)===this.occ.IFSelect_ReturnStatus.IFSelect_RetDone){const t=new this.occ.Message_ProgressRange_1;n.TransferRoots(t),t.delete();let r,s=n.OneShape();if(e.adjustZtoY){const e=this.och.transformsService.mirrorAlongNormal({shape:s,origin:[0,0,0],normal:[0,0,1]});r=this.och.transformsService.rotate({shape:e,axis:[1,0,0],angle:90}),e.delete()}return this.occ.FS.unlink(`/file.${i}`),r&&(s.delete(),s=r),s}console.error("Something in OCCT went wrong trying to read "+t)}}class Ee{constructor(e,t){this.occ=e,this.och=t}closestPointsBetweenTwoShapes(e){return this.och.operationsService.closestPointsBetweenTwoShapes(e.shape1,e.shape2)}closestPointsOnShapeFromPoints(e){return this.och.operationsService.closestPointsOnShapeFromPoints(e)}closestPointsOnShapesFromPoints(e){return this.och.operationsService.closestPointsOnShapesFromPoints(e)}distancesToShapeFromPoints(e){return this.och.operationsService.distancesToShapeFromPoints(e)}loft(e){return this.och.operationsService.loft(e)}loftAdvanced(e){return this.och.operationsService.loftAdvanced(e)}offset(e){return this.och.operationsService.offset(e)}offsetAdv(e){return this.och.operationsService.offsetAdv(e)}offset3DWire(e){return this.och.operationsService.offset3DWire(e)}extrudeShapes(e){return this.och.operationsService.extrudeShapes(e)}extrude(e){return this.och.operationsService.extrude(e)}splitShapeWithShapes(e){return this.och.operationsService.splitShapeWithShapes(e)}revolve(e){return this.och.operationsService.revolve(e)}rotatedExtrude(e){return this.och.operationsService.rotatedExtrude(e)}pipe(e){return this.och.operationsService.pipe(e)}pipePolylineWireNGon(e){return this.och.operationsService.pipePolylineWireNGon(e)}pipeWireCylindrical(e){return this.och.operationsService.pipeWireCylindrical(e)}pipeWiresCylindrical(e){return this.och.operationsService.pipeWiresCylindrical(e)}makeThickSolidSimple(e){return this.och.operationsService.makeThickSolidSimple(e)}makeThickSolidByJoin(e){return this.och.operationsService.makeThickSolidByJoin(e)}slice(e){return this.och.operationsService.slice(e)}sliceInStepPattern(e){return this.och.operationsService.sliceInStepPattern(e)}}class Te{constructor(e,t){this.occ=e,this.och=t}transform(e){const t=this.scale({shape:e.shape,factor:e.scaleFactor}),r=this.rotate({shape:t,axis:e.rotationAxis,angle:e.rotationAngle}),i=this.translate({shape:r,translation:e.translation});return t.delete(),r.delete(),i}rotate(e){return this.och.transformsService.rotate(e)}rotateAroundCenter(e){const t=this.translate({shape:e.shape,translation:e.center.map((e=>-e))}),r=e.angle,i=this.rotate({shape:t,axis:e.axis,angle:r}),n=this.translate({shape:i,translation:e.center});return i.delete(),t.delete(),n}align(e){return this.och.transformsService.align(e)}alignAndTranslate(e){return this.och.transformsService.alignAndTranslate(e)}translate(e){return this.och.transformsService.translate(e)}scale(e){const t=new this.occ.gp_Trsf_1,r=this.och.entitiesService.gpPnt([0,0,0]);t.SetScale(r,e.factor);const i=new this.occ.BRepBuilderAPI_Transform_2(e.shape,t,!0),n=i.Shape(),s=this.och.converterService.getActualTypeOfShape(n);return r.delete(),t.delete(),i.delete(),n.delete(),s}scale3d(e){const t=this.translate({shape:e.shape,translation:e.center.map((e=>-e))}),r=new this.occ.gp_GTrsf_1,i=e.scale,n=new this.occ.gp_Mat_2(i[0],0,0,0,i[1],0,0,0,i[2]);let s;r.SetVectorialPart(n);try{const i=new this.occ.BRepBuilderAPI_GTransform_2(t,r,!1),n=new this.occ.Message_ProgressRange_1;i.Build(n);const o=i.Shape();s=this.translate({shape:o,translation:e.center}),i.delete(),o.delete(),n.delete()}catch(e){throw new Error("Could not scale the shape")}return t.delete(),r.delete(),n.delete(),s}mirror(e){return this.och.transformsService.mirror(e)}mirrorAlongNormal(e){return this.och.transformsService.mirrorAlongNormal(e)}transformShapes(e){return this.checkIfListsEqualLength([e.shapes,e.translations,e.rotationAxes,e.rotationAngles,e.scaleFactors]),e.shapes.map(((t,r)=>this.transform({shape:t,translation:e.translations[r],rotationAxis:e.rotationAxes[r],rotationAngle:e.rotationAngles[r],scaleFactor:e.scaleFactors[r]})))}rotateShapes(e){return this.checkIfListsEqualLength([e.shapes,e.axes,e.angles]),e.shapes.map(((t,r)=>this.rotate({shape:t,axis:e.axes[r],angle:e.angles[r]})))}rotateAroundCenterShapes(e){return this.checkIfListsEqualLength([e.shapes,e.axes,e.angles]),e.shapes.map(((t,r)=>this.rotateAroundCenter({shape:t,axis:e.axes[r],angle:e.angles[r],center:e.centers[r]})))}alignShapes(e){return this.checkIfListsEqualLength([e.shapes,e.fromOrigins,e.fromDirections,e.toOrigins,e.toDirections]),e.shapes.map(((t,r)=>this.align({shape:t,fromOrigin:e.fromOrigins[r],fromDirection:e.fromDirections[r],toOrigin:e.toOrigins[r],toDirection:e.toDirections[r]})))}alignAndTranslateShapes(e){return this.checkIfListsEqualLength([e.shapes,e.centers,e.directions]),e.shapes.map(((t,r)=>this.alignAndTranslate({shape:t,center:e.centers[r],direction:e.directions[r]})))}translateShapes(e){return this.checkIfListsEqualLength([e.shapes,e.translations]),e.shapes.map(((t,r)=>this.translate({shape:t,translation:e.translations[r]})))}scaleShapes(e){return this.checkIfListsEqualLength([e.shapes,e.factors]),e.shapes.map(((t,r)=>this.scale({shape:t,factor:e.factors[r]})))}scale3dShapes(e){return this.checkIfListsEqualLength([e.shapes,e.scales,e.centers]),e.shapes.map(((t,r)=>this.scale3d({shape:t,scale:e.scales[r],center:e.centers[r]})))}mirrorShapes(e){return this.checkIfListsEqualLength([e.shapes,e.directions,e.origins]),e.shapes.map(((t,r)=>this.mirror({shape:t,origin:e.origins[r],direction:e.directions[r]})))}mirrorAlongNormalShapes(e){return this.checkIfListsEqualLength([e.shapes,e.normals,e.origins]),e.shapes.map(((t,r)=>this.mirrorAlongNormal({shape:t,normal:e.normals[r],origin:e.origins[r]})))}checkIfListsEqualLength(e){const t=e[0].length;if(e.some((e=>e.length!==t)))throw new Error("Some of the list lengths are not the same. For this operation to work all lists need to be of equal length")}}class xe{constructor(e,t){this.occ=e,this.och=t}filletEdges(e){return this.och.filletsService.filletEdges(e)}filletEdgesList(e){return this.och.filletsService.filletEdgesList(e)}filletEdgesListOneRadius(e){return this.och.filletsService.filletEdgesListOneRadius(e)}filletEdgeVariableRadius(e){return this.och.filletsService.filletEdgeVariableRadius(e)}filletEdgesVariableRadius(e){return this.och.filletsService.filletEdgesVariableRadius(e)}filletEdgesSameVariableRadius(e){return this.och.filletsService.filletEdgesSameVariableRadius(e)}chamferEdges(e){return this.och.filletsService.chamferEdges(e)}chamferEdgesList(e){return this.och.filletsService.chamferEdgesList(e)}chamferEdgeDistAngle(e){return this.och.filletsService.chamferEdgeDistAngle(e)}chamferEdgesDistAngle(e){return this.och.filletsService.chamferEdgesDistAngle(e)}chamferEdgesDistsAngles(e){return this.och.filletsService.chamferEdgesDistsAngles(e)}chamferEdgeTwoDistances(e){return this.och.filletsService.chamferEdgeTwoDistances(e)}chamferEdgesTwoDistances(e){return this.och.filletsService.chamferEdgesTwoDistances(e)}chamferEdgesTwoDistancesLists(e){return this.och.filletsService.chamferEdgesTwoDistancesLists(e)}filletTwoEdgesInPlaneIntoAWire(e){const t=this.och.entitiesService.gpPln(e.planeOrigin,e.planeDirection),r=new this.occ.ChFi2d_FilletAlgo_3(e.edge1,e.edge2,t);r.Perform(e.radius);const i=this.och.entitiesService.gpPnt(e.planeOrigin),n=new this.occ.TopoDS_Edge,s=new this.occ.TopoDS_Edge;let o=-1;void 0!==e.solution&&(o=e.solution);const a=r.Result(i,n,s,o),c=this.och.converterService.combineEdgesAndWiresIntoAWire({shapes:[n,a,s]});return r.delete(),i.delete(),t.delete(),n.delete(),s.delete(),a.delete(),c}fillet3DWire(e){return this.och.filletsService.fillet3DWire(e)}fillet2d(e){if(e.indexes&&e.radiusList&&e.radiusList.length!==e.indexes.length)throw new Error("When using radius list, length of the list must match index list of corners that you want to fillet.");let t,r=!1;if(e.shape.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_FACE)t=this.och.converterService.getActualTypeOfShape(e.shape),r=!0;else{if(e.shape.ShapeType()!==this.occ.TopAbs_ShapeEnum.TopAbs_WIRE)throw new Error("You can only fillet a 2d wire or a 2d face.");{const r=new this.occ.BRepBuilderAPI_MakeFace_15(e.shape,!0),i=new this.occ.Message_ProgressRange_1;r.Build(i);const n=r.Shape();t=this.och.converterService.getActualTypeOfShape(n),n.delete(),i.delete(),r.delete()}}const i=new this.occ.BRepFilletAPI_MakeFillet2d_2(t),n=new this.occ.TopExp_Explorer_2(e.shape,this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX,this.occ.TopAbs_ShapeEnum.TopAbs_SHAPE);let s=1;const o=[];for(;n.More();n.Next()){const e=this.occ.TopoDS.Vertex_1(n.Current());s%2==0&&o.push(e),s++}r||e.shape.Closed_1()||o.pop();let a=0;o.forEach(((t,r)=>{e.indexes?e.indexes.includes(r+1)&&(this.applyRadiusToVertex(e,i,t,a),a++):this.applyRadiusToVertex(e,i,t,r)}));const c=new this.occ.Message_ProgressRange_1;let h;if(i.Build(c),r)h=i.Shape();else if(i.IsDone()){const e=i.Shape(),t=this.och.shapeGettersService.getWires({shape:e});1===t.length&&(h=t[0])}else{const r=this.och.facesService.faceNormalOnUV({shape:t,paramU:.5,paramV:.5});h=this.fillet3DWire({shape:e.shape,radius:e.radius,radiusList:e.radiusList,indexes:e.indexes,direction:r})}return n.delete(),i.delete(),c.delete(),o.forEach((e=>e.delete())),h}applyRadiusToVertex(e,t,r,i){if(e.radiusList){const n=e.radiusList;t.AddFillet(r,n[i])}else e.radius&&t.AddFillet(r,e.radius)}}class ke{constructor(e,t){this.occ=e,this.och=t}fixEdgeOrientationsAlongWire(e){return this.och.edgesService.fixEdgeOrientationsAlongWire(e)}basicShapeRepair(e){const t=new this.occ.ShapeFix_Shape_1;t.Init(e.shape),t.SetPrecision(e.precision),t.SetMaxTolerance(e.maxTolerance),t.SetMinTolerance(e.minTolerance);const r=new this.occ.Message_ProgressRange_1;t.Perform(r),r.delete();const i=t.Shape();return t.delete(),i}fixSmallEdgeOnWire(e){const t=new this.occ.ShapeFix_Wire_1;return t.Load_1(e.shape),t.FixSmall_1(e.lockvtx,e.precsmall),t.Perform(),t.Wire()}}class Pe{constructor(e,t){this.occ=e,this.och=t,this.shapes=new te(e,t),this.geom=new q(e,t),this.transforms=new Te(e,t),this.operations=new Ee(e,t),this.booleans=new be(e,t),this.fillets=new xe(e,t),this.shapeFix=new ke(e,t),this.io=new we(e,t)}shapesToMeshes(e){return e.shapes.map((t=>this.shapeToMesh({shape:t,precision:e.precision,adjustYtoZ:e.adjustYtoZ})))}shapeToMesh(e){const t=[],r=[],i=[];let n=e.shape;if(n.IsNull())return{faceList:t,edgeList:r,pointsList:[]};if(this.occ.BRepTools.Clean(n,!0),e.adjustYtoZ){const t=this.och.transformsService.rotate({shape:e.shape,axis:[1,0,0],angle:-90}),r=this.och.transformsService.mirrorAlongNormal({shape:t,origin:[0,0,0],normal:[0,0,1]});t.delete(),n.delete(),n=r}const s=[],o=this.och.shapeGettersService.getFaces({shape:n});let a;o&&o.length&&(a=new this.occ.BRepMesh_IncrementalMesh_2(n,e.precision,!1,.5,!1),o.forEach(((e,r)=>{const i=new this.occ.TopLoc_Location_1,n=this.occ.BRep_Tool.Triangulation(e,i,0);if(n.IsNull())return void console.error("Encountered Null Face!");const o={vertex_coord:[],normal_coord:[],uvs:[],tri_indexes:[],vertex_coord_vec:[],number_of_triangles:0,face_index:r},a=new this.occ.Poly_Connect_2(n),c=n.get();o.vertex_coord=new Array(3*c.NbNodes()),o.vertex_coord_vec=[];for(let e=0;e{const n={vertex_coord:[],edge_index:-1},s=new this.occ.TopLoc_Location_1,o=new this.occ.BRepAdaptor_Curve_2(t),a=new this.occ.GCPnts_TangentialDeflection_2(o,e.precision,.1,2,1e-9,1e-7);n.vertex_coord=[];const c=a.NbPoints(),h=[];for(let e=0;ee.delete())),s.delete(),o.delete(),a.delete(),this.occ.BRepTools.Clean(t,!0)}));const c=this.och.shapeGettersService.getVertices({shape:n});return c.length>0&&c.forEach((e=>{const t=this.occ.BRep_Tool.Pnt(e);i.push([t.X(),t.Y(),t.Z()]),t.delete()})),a&&a.Delete(),this.occ.BRepTools.Clean(n,!0),{faceList:t,edgeList:r,pointsList:i}}}var Ce,Ae=(Ce=(Ce="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(e){var t,i;(e=void 0!==(e=e||{})?e:{}).ready=new Promise((function(e,r){t=e,i=r}));var n,s,o,a,c,h,l=Object.assign({},e),u=[],d="./this.program",p=(e,t)=>{throw t},f="object"==typeof window,g="function"==typeof importScripts,v="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";v?(m=g?r(699).dirname(m)+"/":"//",h=()=>{c||(a=r(439),c=r(699))},n=function(e,t){return h(),e=c.normalize(e),a.readFileSync(e,t?void 0:"utf8")},o=e=>{var t=n(e,!0);return t.buffer||(t=new Uint8Array(t)),t},s=(e,t,r)=>{h(),e=c.normalize(e),a.readFile(e,(function(e,i){e?r(e):t(i.buffer)}))},process.argv.length>1&&(d=process.argv[1].replace(/\\/g,"/")),u=process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof yr))throw e})),process.on("unhandledRejection",(function(e){throw e})),p=(e,t)=>{if(te())throw process.exitCode=e,t;var r;(r=t)instanceof yr||S("exiting due to exception: "+r),process.exit(e)},e.inspect=function(){return"[Emscripten Module object]"}):(f||g)&&(g?m=self.location.href:"undefined"!=typeof document&&document.currentScript&&(m=document.currentScript.src),Ce&&(m=Ce),m=0!==m.indexOf("blob:")?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",n=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},g&&(o=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),s=(e,t,r)=>{var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=()=>{200==i.status||0==i.status&&i.response?t(i.response):r()},i.onerror=r,i.send(null)});var y=e.print||console.log.bind(console),S=e.printErr||console.warn.bind(console);Object.assign(e,l),l=null,e.arguments&&(u=e.arguments),e.thisProgram&&(d=e.thisProgram),e.quit&&(p=e.quit);var b;function w(e){w.shown||(w.shown={}),w.shown[e]||(w.shown[e]=1,S(e))}e.wasmBinary&&(b=e.wasmBinary);var E,T=e.noExitRuntime||!0;"object"!=typeof WebAssembly&&ae("no native wasm support detected");var x,k=!1;function P(e,t){e||ae(t)}var C="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function A(e,t,r){for(var i=(t>>>=0)+r,n=t;e[n]&&!(n>=i);)++n;if(n-t>16&&e.buffer&&C)return C.decode(e.subarray(t,n));for(var s="";t>10,56320|1023&h)}}else s+=String.fromCharCode((31&o)<<6|a)}else s+=String.fromCharCode(o)}return s}function _(e,t){return(e>>>=0)?A(B,e,t):""}function O(e,t,r,i){if(!(i>0))return 0;for(var n=r>>>=0,s=r+i-1,o=0;o=55296&&a<=57343&&(a=65536+((1023&a)<<10)|1023&e.charCodeAt(++o)),a<=127){if(r>=s)break;t[r++>>>0]=a}else if(a<=2047){if(r+1>=s)break;t[r++>>>0]=192|a>>6,t[r++>>>0]=128|63&a}else if(a<=65535){if(r+2>=s)break;t[r++>>>0]=224|a>>12,t[r++>>>0]=128|a>>6&63,t[r++>>>0]=128|63&a}else{if(r+3>=s)break;t[r++>>>0]=240|a>>18,t[r++>>>0]=128|a>>12&63,t[r++>>>0]=128|a>>6&63,t[r++>>>0]=128|63&a}}return t[r>>>0]=0,r-n}function D(e,t,r){return O(e,B,t,r)}function R(e){for(var t=0,r=0;r=55296&&i<=57343&&(i=65536+((1023&i)<<10)|1023&e.charCodeAt(++r)),i<=127?++t:t+=i<=2047?2:i<=65535?3:4}return t}var F,L,B,M,I,U,W,N,G,H="undefined"!=typeof TextDecoder?new TextDecoder("utf-16le"):void 0;function V(e,t){for(var r=e,i=r>>1,n=i+t/2;!(i>=n)&&I[i>>>0];)++i;if((r=i<<1)-e>32&&H)return H.decode(B.subarray(e>>>0,r>>>0));for(var s="",o=0;!(o>=t/2);++o){var a=M[e+2*o>>>1];if(0==a)break;s+=String.fromCharCode(a)}return s}function z(e,t,r){if(void 0===r&&(r=2147483647),r<2)return 0;for(var i=t,n=(r-=2)<2*e.length?r/2:e.length,s=0;s>>1]=o,t+=2}return M[t>>>1]=0,t-i}function j(e){return 2*e.length}function q(e,t){for(var r=0,i="";!(r>=t/4);){var n=U[e+4*r>>>2];if(0==n)break;if(++r,n>=65536){var s=n-65536;i+=String.fromCharCode(55296|s>>10,56320|1023&s)}else i+=String.fromCharCode(n)}return i}function $(e,t,r){if(void 0===r&&(r=2147483647),r<4)return 0;for(var i=t>>>=0,n=i+r-4,s=0;s=55296&&o<=57343&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++s)),U[t>>>2]=o,(t+=4)+4>n)break}return U[t>>>2]=0,t-i}function Y(e){for(var t=0,r=0;r=55296&&i<=57343&&++r,t+=4}return t}function X(e){var t=R(e)+1,r=ur(t);return r&&O(e,L,r,t),r}function Z(t){F=t,e.HEAP8=L=new Int8Array(t),e.HEAP16=M=new Int16Array(t),e.HEAP32=U=new Int32Array(t),e.HEAPU8=B=new Uint8Array(t),e.HEAPU16=I=new Uint16Array(t),e.HEAPU32=W=new Uint32Array(t),e.HEAPF32=N=new Float32Array(t),e.HEAPF64=G=new Float64Array(t)}e.INITIAL_MEMORY;var J,Q=[],K=[],ee=[];function te(){return T}var re=0,ie=null,ne=null;function se(t){re++,e.monitorRunDependencies&&e.monitorRunDependencies(re)}function oe(t){if(re--,e.monitorRunDependencies&&e.monitorRunDependencies(re),0==re&&(null!==ie&&(clearInterval(ie),ie=null),ne)){var r=ne;ne=null,r()}}function ae(t){e.onAbort&&e.onAbort(t),S(t="Aborted("+t+")"),k=!0,x=1,t+=". Build with -sASSERTIONS for more info.";var r=new WebAssembly.RuntimeError(t);throw i(r),r}var ce,he,le,ue;function de(e){return e.startsWith("data:application/octet-stream;base64,")}function pe(e){return e.startsWith("file://")}function fe(e){try{if(e==ce&&b)return new Uint8Array(b);if(o)return o(e);throw"both async and sync fetching of the wasm failed"}catch(e){ae(e)}}function ge(t){for(;t.length>0;){var r=t.shift();if("function"!=typeof r){var i=r.func;"number"==typeof i?void 0===r.arg?me(i)():me(i)(r.arg):i(void 0===r.arg?null:r.arg)}else r(e)}}de(ce="bitbybit-dev-occt.wasm")||(he=ce,ce=e.locateFile?e.locateFile(he,m):m+he);var ve=[];function me(e){var t=ve[e];return t||(e>=ve.length&&(ve.length=e+1),ve[e]=t=J.get(e)),t}function ye(e){this.excPtr=e,this.ptr=e-24,this.set_type=function(e){W[this.ptr+4>>>2]=e},this.get_type=function(){return W[this.ptr+4>>>2]},this.set_destructor=function(e){W[this.ptr+8>>>2]=e},this.get_destructor=function(){return W[this.ptr+8>>>2]},this.set_refcount=function(e){U[this.ptr>>>2]=e},this.set_caught=function(e){e=e?1:0,L[this.ptr+12>>>0]=e},this.get_caught=function(){return 0!=L[this.ptr+12>>>0]},this.set_rethrown=function(e){e=e?1:0,L[this.ptr+13>>>0]=e},this.get_rethrown=function(){return 0!=L[this.ptr+13>>>0]},this.init=function(e,t){this.set_adjusted_ptr(0),this.set_type(e),this.set_destructor(t),this.set_refcount(0),this.set_caught(!1),this.set_rethrown(!1)},this.add_ref=function(){var e=U[this.ptr>>>2];U[this.ptr>>>2]=e+1},this.release_ref=function(){var e=U[this.ptr>>>2];return U[this.ptr>>>2]=e-1,1===e},this.set_adjusted_ptr=function(e){W[this.ptr+16>>>2]=e},this.get_adjusted_ptr=function(){return W[this.ptr+16>>>2]},this.get_exception_ptr=function(){if(mr(this.get_type()))return W[this.excPtr>>>2];var e=this.get_adjusted_ptr();return 0!==e?e:this.excPtr}}var Se={isAbs:e=>"/"===e.charAt(0),splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var r=0,i=e.length-1;i>=0;i--){var n=e[i];"."===n?e.splice(i,1):".."===n?(e.splice(i,1),r++):r&&(e.splice(i,1),r--)}if(t)for(;r;r--)e.unshift("..");return e},normalize:e=>{var t=Se.isAbs(e),r="/"===e.substr(-1);return(e=Se.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e},dirname:e=>{var t=Se.splitPath(e),r=t[0],i=t[1];return r||i?(i&&(i=i.substr(0,i.length-1)),r+i):"."},basename:e=>{if("/"===e)return"/";var t=(e=(e=Se.normalize(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments,0);return Se.normalize(e.join("/"))},join2:(e,t)=>Se.normalize(e+"/"+t)},be={resolve:function(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var i=r>=0?arguments[r]:xe.cwd();if("string"!=typeof i)throw new TypeError("Arguments to path.resolve must be strings");if(!i)return"";e=i+"/"+e,t=Se.isAbs(i)}return(t?"/":"")+(e=Se.normalizeArray(e.split("/").filter((e=>!!e)),!t).join("/"))||"."},relative:(e,t)=>{function r(e){for(var t=0;t=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=be.resolve(e).substr(1),t=be.resolve(t).substr(1);for(var i=r(e.split("/")),n=r(t.split("/")),s=Math.min(i.length,n.length),o=s,a=0;a0?r.slice(0,i).toString("utf-8"):null}else"undefined"!=typeof window&&"function"==typeof window.prompt?null!==(t=window.prompt("Input: "))&&(t+="\n"):"function"==typeof readline&&null!==(t=readline())&&(t+="\n");if(!t)return null;e.input=cr(t,!0)}return e.input.shift()},put_char:function(e,t){null===t||10===t?(y(A(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},flush:function(e){e.output&&e.output.length>0&&(y(A(e.output,0)),e.output=[])}},default_tty1_ops:{put_char:function(e,t){null===t||10===t?(S(A(e.output,0)),e.output=[]):0!=t&&e.output.push(t)},flush:function(e){e.output&&e.output.length>0&&(S(A(e.output,0)),e.output=[])}}};function Ee(e){e=function(e,t){return 65536*Math.ceil(e/65536)}(e);var t=vr(65536,e);return t?(function(e,t){B.fill(0,e,e+t)}(t,e),t):0}var Te={ops_table:null,mount:function(e){return Te.createNode(null,"/",16895,0)},createNode:function(e,t,r,i){if(xe.isBlkdev(r)||xe.isFIFO(r))throw new xe.ErrnoError(63);Te.ops_table||(Te.ops_table={dir:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr,lookup:Te.node_ops.lookup,mknod:Te.node_ops.mknod,rename:Te.node_ops.rename,unlink:Te.node_ops.unlink,rmdir:Te.node_ops.rmdir,readdir:Te.node_ops.readdir,symlink:Te.node_ops.symlink},stream:{llseek:Te.stream_ops.llseek}},file:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr},stream:{llseek:Te.stream_ops.llseek,read:Te.stream_ops.read,write:Te.stream_ops.write,allocate:Te.stream_ops.allocate,mmap:Te.stream_ops.mmap,msync:Te.stream_ops.msync}},link:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr,readlink:Te.node_ops.readlink},stream:{}},chrdev:{node:{getattr:Te.node_ops.getattr,setattr:Te.node_ops.setattr},stream:xe.chrdev_stream_ops}});var n=xe.createNode(e,t,r,i);return xe.isDir(n.mode)?(n.node_ops=Te.ops_table.dir.node,n.stream_ops=Te.ops_table.dir.stream,n.contents={}):xe.isFile(n.mode)?(n.node_ops=Te.ops_table.file.node,n.stream_ops=Te.ops_table.file.stream,n.usedBytes=0,n.contents=null):xe.isLink(n.mode)?(n.node_ops=Te.ops_table.link.node,n.stream_ops=Te.ops_table.link.stream):xe.isChrdev(n.mode)&&(n.node_ops=Te.ops_table.chrdev.node,n.stream_ops=Te.ops_table.chrdev.stream),n.timestamp=Date.now(),e&&(e.contents[t]=n,e.timestamp=n.timestamp),n},getFileDataAsTypedArray:function(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage:function(e,t){t>>>=0;var r=e.contents?e.contents.length:0;if(!(r>=t)){t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));var i=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(i.subarray(0,e.usedBytes),0)}},resizeFileStorage:function(e,t){if(t>>>=0,e.usedBytes!=t)if(0==t)e.contents=null,e.usedBytes=0;else{var r=e.contents;e.contents=new Uint8Array(t),r&&e.contents.set(r.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}},node_ops:{getattr:function(e){var t={};return t.dev=xe.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,xe.isDir(e.mode)?t.size=4096:xe.isFile(e.mode)?t.size=e.usedBytes:xe.isLink(e.mode)?t.size=e.link.length:t.size=0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr:function(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&Te.resizeFileStorage(e,t.size)},lookup:function(e,t){throw xe.genericErrors[44]},mknod:function(e,t,r,i){return Te.createNode(e,t,r,i)},rename:function(e,t,r){if(xe.isDir(e.mode)){var i;try{i=xe.lookupNode(t,r)}catch(e){}if(i)for(var n in i.contents)throw new xe.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=r,t.contents[r]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink:function(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir:function(e,t){var r=xe.lookupNode(e,t);for(var i in r.contents)throw new xe.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir:function(e){var t=[".",".."];for(var r in e.contents)e.contents.hasOwnProperty(r)&&t.push(r);return t},symlink:function(e,t,r){var i=Te.createNode(e,t,41471,0);return i.link=r,i},readlink:function(e){if(!xe.isLink(e.mode))throw new xe.ErrnoError(28);return e.link}},stream_ops:{read:function(e,t,r,i,n){var s=e.node.contents;if(n>=e.node.usedBytes)return 0;var o=Math.min(e.node.usedBytes-n,i);if(o>8&&s.subarray)t.set(s.subarray(n,n+o),r);else for(var a=0;a0||r+t>>=0,L.set(a,s>>>0)}else o=!1,s=a.byteOffset;return{ptr:s,allocated:o}},msync:function(e,t,r,i,n){if(!xe.isFile(e.node.mode))throw new xe.ErrnoError(43);return 2&n||Te.stream_ops.write(e,t,0,i,r,!1),0}}},xe={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(e,t={})=>{if(!(e=be.resolve(xe.cwd(),e)))return{path:"",node:null};if((t=Object.assign({follow_mount:!0,recurse_count:0},t)).recurse_count>8)throw new xe.ErrnoError(32);for(var r=Se.normalizeArray(e.split("/").filter((e=>!!e)),!1),i=xe.root,n="/",s=0;s40)throw new xe.ErrnoError(32)}}return{path:n,node:i}},getPath:e=>{for(var t;;){if(xe.isRoot(e)){var r=e.mount.mountpoint;return t?"/"!==r[r.length-1]?r+"/"+t:r+t:r}t=t?e.name+"/"+t:e.name,e=e.parent}},hashName:(e,t)=>{for(var r=0,i=0;i>>0)%xe.nameTable.length},hashAddNode:e=>{var t=xe.hashName(e.parent.id,e.name);e.name_next=xe.nameTable[t],xe.nameTable[t]=e},hashRemoveNode:e=>{var t=xe.hashName(e.parent.id,e.name);if(xe.nameTable[t]===e)xe.nameTable[t]=e.name_next;else for(var r=xe.nameTable[t];r;){if(r.name_next===e){r.name_next=e.name_next;break}r=r.name_next}},lookupNode:(e,t)=>{var r=xe.mayLookup(e);if(r)throw new xe.ErrnoError(r,e);for(var i=xe.hashName(e.id,t),n=xe.nameTable[i];n;n=n.name_next){var s=n.name;if(n.parent.id===e.id&&s===t)return n}return xe.lookup(e,t)},createNode:(e,t,r,i)=>{var n=new xe.FSNode(e,t,r,i);return xe.hashAddNode(n),n},destroyNode:e=>{xe.hashRemoveNode(e)},isRoot:e=>e===e.parent,isMountpoint:e=>!!e.mounted,isFile:e=>32768==(61440&e),isDir:e=>16384==(61440&e),isLink:e=>40960==(61440&e),isChrdev:e=>8192==(61440&e),isBlkdev:e=>24576==(61440&e),isFIFO:e=>4096==(61440&e),isSocket:e=>!(49152&~e),flagModes:{r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},modeStringToFlags:e=>{var t=xe.flagModes[e];if(void 0===t)throw new Error("Unknown file open mode: "+e);return t},flagsToPermissionString:e=>{var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},nodePermissions:(e,t)=>xe.ignorePermissions||(!t.includes("r")||292&e.mode)&&(!t.includes("w")||146&e.mode)&&(!t.includes("x")||73&e.mode)?0:2,mayLookup:e=>xe.nodePermissions(e,"x")||(e.node_ops.lookup?0:2),mayCreate:(e,t)=>{try{return xe.lookupNode(e,t),20}catch(e){}return xe.nodePermissions(e,"wx")},mayDelete:(e,t,r)=>{var i;try{i=xe.lookupNode(e,t)}catch(e){return e.errno}var n=xe.nodePermissions(e,"wx");if(n)return n;if(r){if(!xe.isDir(i.mode))return 54;if(xe.isRoot(i)||xe.getPath(i)===xe.cwd())return 10}else if(xe.isDir(i.mode))return 31;return 0},mayOpen:(e,t)=>e?xe.isLink(e.mode)?32:xe.isDir(e.mode)&&("r"!==xe.flagsToPermissionString(t)||512&t)?31:xe.nodePermissions(e,xe.flagsToPermissionString(t)):44,MAX_OPEN_FDS:4096,nextfd:(e=0,t=xe.MAX_OPEN_FDS)=>{for(var r=e;r<=t;r++)if(!xe.streams[r])return r;throw new xe.ErrnoError(33)},getStream:e=>xe.streams[e],createStream:(e,t,r)=>{xe.FSStream||(xe.FSStream=function(){this.shared={}},xe.FSStream.prototype={},Object.defineProperties(xe.FSStream.prototype,{object:{get:function(){return this.node},set:function(e){this.node=e}},isRead:{get:function(){return 1!=(2097155&this.flags)}},isWrite:{get:function(){return!!(2097155&this.flags)}},isAppend:{get:function(){return 1024&this.flags}},flags:{get:function(){return this.shared.flags},set:function(e){this.shared.flags=e}},position:{get:function(){return this.shared.position},set:function(e){this.shared.position=e}}})),e=Object.assign(new xe.FSStream,e);var i=xe.nextfd(t,r);return e.fd=i,xe.streams[i]=e,e},closeStream:e=>{xe.streams[e]=null},chrdev_stream_ops:{open:e=>{var t=xe.getDevice(e.node.rdev);e.stream_ops=t.stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek:()=>{throw new xe.ErrnoError(70)}},major:e=>e>>8,minor:e=>255&e,makedev:(e,t)=>e<<8|t,registerDevice:(e,t)=>{xe.devices[e]={stream_ops:t}},getDevice:e=>xe.devices[e],getMounts:e=>{for(var t=[],r=[e];r.length;){var i=r.pop();t.push(i),r.push.apply(r,i.mounts)}return t},syncfs:(e,t)=>{"function"==typeof e&&(t=e,e=!1),xe.syncFSRequests++,xe.syncFSRequests>1&&S("warning: "+xe.syncFSRequests+" FS.syncfs operations in flight at once, probably just doing extra work");var r=xe.getMounts(xe.root.mount),i=0;function n(e){return xe.syncFSRequests--,t(e)}function s(e){if(e)return s.errored?void 0:(s.errored=!0,n(e));++i>=r.length&&n(null)}r.forEach((t=>{if(!t.type.syncfs)return s(null);t.type.syncfs(t,e,s)}))},mount:(e,t,r)=>{var i,n="/"===r,s=!r;if(n&&xe.root)throw new xe.ErrnoError(10);if(!n&&!s){var o=xe.lookupPath(r,{follow_mount:!1});if(r=o.path,i=o.node,xe.isMountpoint(i))throw new xe.ErrnoError(10);if(!xe.isDir(i.mode))throw new xe.ErrnoError(54)}var a={type:e,opts:t,mountpoint:r,mounts:[]},c=e.mount(a);return c.mount=a,a.root=c,n?xe.root=c:i&&(i.mounted=a,i.mount&&i.mount.mounts.push(a)),c},unmount:e=>{var t=xe.lookupPath(e,{follow_mount:!1});if(!xe.isMountpoint(t.node))throw new xe.ErrnoError(28);var r=t.node,i=r.mounted,n=xe.getMounts(i);Object.keys(xe.nameTable).forEach((e=>{for(var t=xe.nameTable[e];t;){var r=t.name_next;n.includes(t.mount)&&xe.destroyNode(t),t=r}})),r.mounted=null;var s=r.mount.mounts.indexOf(i);r.mount.mounts.splice(s,1)},lookup:(e,t)=>e.node_ops.lookup(e,t),mknod:(e,t,r)=>{var i=xe.lookupPath(e,{parent:!0}).node,n=Se.basename(e);if(!n||"."===n||".."===n)throw new xe.ErrnoError(28);var s=xe.mayCreate(i,n);if(s)throw new xe.ErrnoError(s);if(!i.node_ops.mknod)throw new xe.ErrnoError(63);return i.node_ops.mknod(i,n,t,r)},create:(e,t)=>(t=void 0!==t?t:438,t&=4095,t|=32768,xe.mknod(e,t,0)),mkdir:(e,t)=>(t=void 0!==t?t:511,t&=1023,t|=16384,xe.mknod(e,t,0)),mkdirTree:(e,t)=>{for(var r=e.split("/"),i="",n=0;n(void 0===r&&(r=t,t=438),t|=8192,xe.mknod(e,t,r)),symlink:(e,t)=>{if(!be.resolve(e))throw new xe.ErrnoError(44);var r=xe.lookupPath(t,{parent:!0}).node;if(!r)throw new xe.ErrnoError(44);var i=Se.basename(t),n=xe.mayCreate(r,i);if(n)throw new xe.ErrnoError(n);if(!r.node_ops.symlink)throw new xe.ErrnoError(63);return r.node_ops.symlink(r,i,e)},rename:(e,t)=>{var r,i,n=Se.dirname(e),s=Se.dirname(t),o=Se.basename(e),a=Se.basename(t);if(r=xe.lookupPath(e,{parent:!0}).node,i=xe.lookupPath(t,{parent:!0}).node,!r||!i)throw new xe.ErrnoError(44);if(r.mount!==i.mount)throw new xe.ErrnoError(75);var c,h=xe.lookupNode(r,o),l=be.relative(e,s);if("."!==l.charAt(0))throw new xe.ErrnoError(28);if("."!==(l=be.relative(t,n)).charAt(0))throw new xe.ErrnoError(55);try{c=xe.lookupNode(i,a)}catch(e){}if(h!==c){var u=xe.isDir(h.mode),d=xe.mayDelete(r,o,u);if(d)throw new xe.ErrnoError(d);if(d=c?xe.mayDelete(i,a,u):xe.mayCreate(i,a))throw new xe.ErrnoError(d);if(!r.node_ops.rename)throw new xe.ErrnoError(63);if(xe.isMountpoint(h)||c&&xe.isMountpoint(c))throw new xe.ErrnoError(10);if(i!==r&&(d=xe.nodePermissions(r,"w")))throw new xe.ErrnoError(d);xe.hashRemoveNode(h);try{r.node_ops.rename(h,i,a)}catch(e){throw e}finally{xe.hashAddNode(h)}}},rmdir:e=>{var t=xe.lookupPath(e,{parent:!0}).node,r=Se.basename(e),i=xe.lookupNode(t,r),n=xe.mayDelete(t,r,!0);if(n)throw new xe.ErrnoError(n);if(!t.node_ops.rmdir)throw new xe.ErrnoError(63);if(xe.isMountpoint(i))throw new xe.ErrnoError(10);t.node_ops.rmdir(t,r),xe.destroyNode(i)},readdir:e=>{var t=xe.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new xe.ErrnoError(54);return t.node_ops.readdir(t)},unlink:e=>{var t=xe.lookupPath(e,{parent:!0}).node;if(!t)throw new xe.ErrnoError(44);var r=Se.basename(e),i=xe.lookupNode(t,r),n=xe.mayDelete(t,r,!1);if(n)throw new xe.ErrnoError(n);if(!t.node_ops.unlink)throw new xe.ErrnoError(63);if(xe.isMountpoint(i))throw new xe.ErrnoError(10);t.node_ops.unlink(t,r),xe.destroyNode(i)},readlink:e=>{var t=xe.lookupPath(e).node;if(!t)throw new xe.ErrnoError(44);if(!t.node_ops.readlink)throw new xe.ErrnoError(28);return be.resolve(xe.getPath(t.parent),t.node_ops.readlink(t))},stat:(e,t)=>{var r=xe.lookupPath(e,{follow:!t}).node;if(!r)throw new xe.ErrnoError(44);if(!r.node_ops.getattr)throw new xe.ErrnoError(63);return r.node_ops.getattr(r)},lstat:e=>xe.stat(e,!0),chmod:(e,t,r)=>{var i;if(!(i="string"==typeof e?xe.lookupPath(e,{follow:!r}).node:e).node_ops.setattr)throw new xe.ErrnoError(63);i.node_ops.setattr(i,{mode:4095&t|-4096&i.mode,timestamp:Date.now()})},lchmod:(e,t)=>{xe.chmod(e,t,!0)},fchmod:(e,t)=>{var r=xe.getStream(e);if(!r)throw new xe.ErrnoError(8);xe.chmod(r.node,t)},chown:(e,t,r,i)=>{var n;if(!(n="string"==typeof e?xe.lookupPath(e,{follow:!i}).node:e).node_ops.setattr)throw new xe.ErrnoError(63);n.node_ops.setattr(n,{timestamp:Date.now()})},lchown:(e,t,r)=>{xe.chown(e,t,r,!0)},fchown:(e,t,r)=>{var i=xe.getStream(e);if(!i)throw new xe.ErrnoError(8);xe.chown(i.node,t,r)},truncate:(e,t)=>{if(t<0)throw new xe.ErrnoError(28);var r;if(!(r="string"==typeof e?xe.lookupPath(e,{follow:!0}).node:e).node_ops.setattr)throw new xe.ErrnoError(63);if(xe.isDir(r.mode))throw new xe.ErrnoError(31);if(!xe.isFile(r.mode))throw new xe.ErrnoError(28);var i=xe.nodePermissions(r,"w");if(i)throw new xe.ErrnoError(i);r.node_ops.setattr(r,{size:t,timestamp:Date.now()})},ftruncate:(e,t)=>{var r=xe.getStream(e);if(!r)throw new xe.ErrnoError(8);if(!(2097155&r.flags))throw new xe.ErrnoError(28);xe.truncate(r.node,t)},utime:(e,t,r)=>{var i=xe.lookupPath(e,{follow:!0}).node;i.node_ops.setattr(i,{timestamp:Math.max(t,r)})},open:(t,r,i)=>{if(""===t)throw new xe.ErrnoError(44);var n;if(i=void 0===i?438:i,i=64&(r="string"==typeof r?xe.modeStringToFlags(r):r)?4095&i|32768:0,"object"==typeof t)n=t;else{t=Se.normalize(t);try{n=xe.lookupPath(t,{follow:!(131072&r)}).node}catch(e){}}var s=!1;if(64&r)if(n){if(128&r)throw new xe.ErrnoError(20)}else n=xe.mknod(t,i,0),s=!0;if(!n)throw new xe.ErrnoError(44);if(xe.isChrdev(n.mode)&&(r&=-513),65536&r&&!xe.isDir(n.mode))throw new xe.ErrnoError(54);if(!s){var o=xe.mayOpen(n,r);if(o)throw new xe.ErrnoError(o)}512&r&&!s&&xe.truncate(n,0),r&=-131713;var a=xe.createStream({node:n,path:xe.getPath(n),flags:r,seekable:!0,position:0,stream_ops:n.stream_ops,ungotten:[],error:!1});return a.stream_ops.open&&a.stream_ops.open(a),!e.logReadFiles||1&r||(xe.readFiles||(xe.readFiles={}),t in xe.readFiles||(xe.readFiles[t]=1)),a},close:e=>{if(xe.isClosed(e))throw new xe.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{xe.closeStream(e.fd)}e.fd=null},isClosed:e=>null===e.fd,llseek:(e,t,r)=>{if(xe.isClosed(e))throw new xe.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new xe.ErrnoError(70);if(0!=r&&1!=r&&2!=r)throw new xe.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,r),e.ungotten=[],e.position},read:(e,t,r,i,n)=>{if(r>>>=0,i<0||n<0)throw new xe.ErrnoError(28);if(xe.isClosed(e))throw new xe.ErrnoError(8);if(1==(2097155&e.flags))throw new xe.ErrnoError(8);if(xe.isDir(e.node.mode))throw new xe.ErrnoError(31);if(!e.stream_ops.read)throw new xe.ErrnoError(28);var s=void 0!==n;if(s){if(!e.seekable)throw new xe.ErrnoError(70)}else n=e.position;var o=e.stream_ops.read(e,t,r,i,n);return s||(e.position+=o),o},write:(e,t,r,i,n,s)=>{if(r>>>=0,i<0||n<0)throw new xe.ErrnoError(28);if(xe.isClosed(e))throw new xe.ErrnoError(8);if(!(2097155&e.flags))throw new xe.ErrnoError(8);if(xe.isDir(e.node.mode))throw new xe.ErrnoError(31);if(!e.stream_ops.write)throw new xe.ErrnoError(28);e.seekable&&1024&e.flags&&xe.llseek(e,0,2);var o=void 0!==n;if(o){if(!e.seekable)throw new xe.ErrnoError(70)}else n=e.position;var a=e.stream_ops.write(e,t,r,i,n,s);return o||(e.position+=a),a},allocate:(e,t,r)=>{if(xe.isClosed(e))throw new xe.ErrnoError(8);if(t<0||r<=0)throw new xe.ErrnoError(28);if(!(2097155&e.flags))throw new xe.ErrnoError(8);if(!xe.isFile(e.node.mode)&&!xe.isDir(e.node.mode))throw new xe.ErrnoError(43);if(!e.stream_ops.allocate)throw new xe.ErrnoError(138);e.stream_ops.allocate(e,t,r)},mmap:(e,t,r,i,n)=>{if(2&i&&!(2&n)&&2!=(2097155&e.flags))throw new xe.ErrnoError(2);if(1==(2097155&e.flags))throw new xe.ErrnoError(2);if(!e.stream_ops.mmap)throw new xe.ErrnoError(43);return e.stream_ops.mmap(e,t,r,i,n)},msync:(e,t,r,i,n)=>(r>>>=0,e&&e.stream_ops.msync?e.stream_ops.msync(e,t,r,i,n):0),munmap:e=>0,ioctl:(e,t,r)=>{if(!e.stream_ops.ioctl)throw new xe.ErrnoError(59);return e.stream_ops.ioctl(e,t,r)},readFile:(e,t={})=>{if(t.flags=t.flags||0,t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw new Error('Invalid encoding type "'+t.encoding+'"');var r,i=xe.open(e,t.flags),n=xe.stat(e).size,s=new Uint8Array(n);return xe.read(i,s,0,n,0),"utf8"===t.encoding?r=A(s,0):"binary"===t.encoding&&(r=s),xe.close(i),r},writeFile:(e,t,r={})=>{r.flags=r.flags||577;var i=xe.open(e,r.flags,r.mode);if("string"==typeof t){var n=new Uint8Array(R(t)+1),s=O(t,n,0,n.length);xe.write(i,n,0,s,void 0,r.canOwn)}else{if(!ArrayBuffer.isView(t))throw new Error("Unsupported data type");xe.write(i,t,0,t.byteLength,void 0,r.canOwn)}xe.close(i)},cwd:()=>xe.currentPath,chdir:e=>{var t=xe.lookupPath(e,{follow:!0});if(null===t.node)throw new xe.ErrnoError(44);if(!xe.isDir(t.node.mode))throw new xe.ErrnoError(54);var r=xe.nodePermissions(t.node,"x");if(r)throw new xe.ErrnoError(r);xe.currentPath=t.path},createDefaultDirectories:()=>{xe.mkdir("/tmp"),xe.mkdir("/home"),xe.mkdir("/home/web_user")},createDefaultDevices:()=>{xe.mkdir("/dev"),xe.registerDevice(xe.makedev(1,3),{read:()=>0,write:(e,t,r,i,n)=>i}),xe.mkdev("/dev/null",xe.makedev(1,3)),we.register(xe.makedev(5,0),we.default_tty_ops),we.register(xe.makedev(6,0),we.default_tty1_ops),xe.mkdev("/dev/tty",xe.makedev(5,0)),xe.mkdev("/dev/tty1",xe.makedev(6,0));var e=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return function(){return crypto.getRandomValues(e),e[0]}}if(v)try{var t=r(725);return function(){return t.randomBytes(1)[0]}}catch(e){}return function(){ae("randomDevice")}}();xe.createDevice("/dev","random",e),xe.createDevice("/dev","urandom",e),xe.mkdir("/dev/shm"),xe.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{xe.mkdir("/proc");var e=xe.mkdir("/proc/self");xe.mkdir("/proc/self/fd"),xe.mount({mount:()=>{var t=xe.createNode(e,"fd",16895,73);return t.node_ops={lookup:(e,t)=>{var r=+t,i=xe.getStream(r);if(!i)throw new xe.ErrnoError(8);var n={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>i.path}};return n.parent=n,n}},t}},{},"/proc/self/fd")},createStandardStreams:()=>{e.stdin?xe.createDevice("/dev","stdin",e.stdin):xe.symlink("/dev/tty","/dev/stdin"),e.stdout?xe.createDevice("/dev","stdout",null,e.stdout):xe.symlink("/dev/tty","/dev/stdout"),e.stderr?xe.createDevice("/dev","stderr",null,e.stderr):xe.symlink("/dev/tty1","/dev/stderr"),xe.open("/dev/stdin",0),xe.open("/dev/stdout",1),xe.open("/dev/stderr",1)},ensureErrnoError:()=>{xe.ErrnoError||(xe.ErrnoError=function(e,t){this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message="FS error"},xe.ErrnoError.prototype=new Error,xe.ErrnoError.prototype.constructor=xe.ErrnoError,[44].forEach((e=>{xe.genericErrors[e]=new xe.ErrnoError(e),xe.genericErrors[e].stack=""})))},staticInit:()=>{xe.ensureErrnoError(),xe.nameTable=new Array(4096),xe.mount(Te,{},"/"),xe.createDefaultDirectories(),xe.createDefaultDevices(),xe.createSpecialDirectories(),xe.filesystems={MEMFS:Te}},init:(t,r,i)=>{xe.init.initialized=!0,xe.ensureErrnoError(),e.stdin=t||e.stdin,e.stdout=r||e.stdout,e.stderr=i||e.stderr,xe.createStandardStreams()},quit:()=>{xe.init.initialized=!1;for(var e=0;e{var r=0;return e&&(r|=365),t&&(r|=146),r},findObject:(e,t)=>{var r=xe.analyzePath(e,t);return r.exists?r.object:null},analyzePath:(e,t)=>{try{e=(i=xe.lookupPath(e,{follow:!t})).path}catch(e){}var r={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var i=xe.lookupPath(e,{parent:!0});r.parentExists=!0,r.parentPath=i.path,r.parentObject=i.node,r.name=Se.basename(e),i=xe.lookupPath(e,{follow:!t}),r.exists=!0,r.path=i.path,r.object=i.node,r.name=i.node.name,r.isRoot="/"===i.path}catch(e){r.error=e.errno}return r},createPath:(e,t,r,i)=>{e="string"==typeof e?e:xe.getPath(e);for(var n=t.split("/").reverse();n.length;){var s=n.pop();if(s){var o=Se.join2(e,s);try{xe.mkdir(o)}catch(e){}e=o}}return o},createFile:(e,t,r,i,n)=>{var s=Se.join2("string"==typeof e?e:xe.getPath(e),t),o=xe.getMode(i,n);return xe.create(s,o)},createDataFile:(e,t,r,i,n,s)=>{var o=t;e&&(e="string"==typeof e?e:xe.getPath(e),o=t?Se.join2(e,t):e);var a=xe.getMode(i,n),c=xe.create(o,a);if(r){if("string"==typeof r){for(var h=new Array(r.length),l=0,u=r.length;l{var n=Se.join2("string"==typeof e?e:xe.getPath(e),t),s=xe.getMode(!!r,!!i);xe.createDevice.major||(xe.createDevice.major=64);var o=xe.makedev(xe.createDevice.major++,0);return xe.registerDevice(o,{open:e=>{e.seekable=!1},close:e=>{i&&i.buffer&&i.buffer.length&&i(10)},read:(e,t,i,n,s)=>{for(var o=0,a=0;a{for(var o=0;o{if(e.isDevice||e.isFolder||e.link||e.contents)return!0;if("undefined"!=typeof XMLHttpRequest)throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");if(!n)throw new Error("Cannot load without read() or XMLHttpRequest.");try{e.contents=cr(n(e.url),!0),e.usedBytes=e.contents.length}catch(e){throw new xe.ErrnoError(29)}},createLazyFile:(e,t,r,i,n)=>{function s(){this.lengthKnown=!1,this.chunks=[]}if(s.prototype.get=function(e){if(!(e>this.length-1||e<0)){var t=e%this.chunkSize,r=e/this.chunkSize|0;return this.getter(r)[t]}},s.prototype.setDataGetter=function(e){this.getter=e},s.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open("HEAD",r,!1),e.send(null),!(e.status>=200&&e.status<300||304===e.status))throw new Error("Couldn't load "+r+". Status: "+e.status);var t,i=Number(e.getResponseHeader("Content-length")),n=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t,s=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t,o=1048576;n||(o=i);var a=this;a.setDataGetter((e=>{var t=e*o,n=(e+1)*o-1;if(n=Math.min(n,i-1),void 0===a.chunks[e]&&(a.chunks[e]=((e,t)=>{if(e>t)throw new Error("invalid range ("+e+", "+t+") or no bytes requested!");if(t>i-1)throw new Error("only "+i+" bytes available! programmer error!");var n=new XMLHttpRequest;if(n.open("GET",r,!1),i!==o&&n.setRequestHeader("Range","bytes="+e+"-"+t),n.responseType="arraybuffer",n.overrideMimeType&&n.overrideMimeType("text/plain; charset=x-user-defined"),n.send(null),!(n.status>=200&&n.status<300||304===n.status))throw new Error("Couldn't load "+r+". Status: "+n.status);return void 0!==n.response?new Uint8Array(n.response||[]):cr(n.responseText||"",!0)})(t,n)),void 0===a.chunks[e])throw new Error("doXHR failed!");return a.chunks[e]})),!s&&i||(o=i=1,i=this.getter(0).length,o=i,y("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=i,this._chunkSize=o,this.lengthKnown=!0},"undefined"!=typeof XMLHttpRequest){if(!g)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var o=new s;Object.defineProperties(o,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var a={isDevice:!1,contents:o}}else a={isDevice:!1,url:r};var c=xe.createFile(e,t,a,i,n);a.contents?c.contents=a.contents:a.url&&(c.contents=null,c.url=a.url),Object.defineProperties(c,{usedBytes:{get:function(){return this.contents.length}}});var h={};function l(e,t,r,i,n){var s=e.node.contents;if(n>=s.length)return 0;var o=Math.min(s.length-n,i);if(s.slice)for(var a=0;a{var t=c.stream_ops[e];h[e]=function(){return xe.forceLoadFile(c),t.apply(null,arguments)}})),h.read=(e,t,r,i,n)=>(xe.forceLoadFile(c),l(e,t,r,i,n)),h.mmap=(e,t,r,i,n)=>{xe.forceLoadFile(c);var s=Ee(t);if(!s)throw new xe.ErrnoError(48);return l(e,L,s,t,r),{ptr:s,allocated:!0}},c.stream_ops=h,c},createPreloadedFile:(e,t,r,i,n,o,a,c,h,l)=>{var u=t?be.resolve(Se.join2(e,t)):e;function d(r){function s(r){l&&l(),c||xe.createDataFile(e,t,r,i,n,h),o&&o(),oe()}Nt.handledByPreloadPlugin(r,u,s,(()=>{a&&a(),oe()}))||s(r)}se(),"string"==typeof r?function(e,t,r,i){var n="al "+e;s(e,(function(t){P(t,'Loading data file "'+e+'" failed (no arrayBuffer).'),d(new Uint8Array(t)),n&&oe()}),(function(t){if(!r)throw'Loading data file "'+e+'" failed.';r()})),n&&se()}(r,0,a):d(r)},indexedDB:()=>window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB,DB_NAME:()=>"EM_FS_"+window.location.pathname,DB_VERSION:20,DB_STORE_NAME:"FILE_DATA",saveFilesToDB:(e,t,r)=>{t=t||(()=>{}),r=r||(()=>{});var i=xe.indexedDB();try{var n=i.open(xe.DB_NAME(),xe.DB_VERSION)}catch(e){return r(e)}n.onupgradeneeded=()=>{y("creating db"),n.result.createObjectStore(xe.DB_STORE_NAME)},n.onsuccess=()=>{var i=n.result.transaction([xe.DB_STORE_NAME],"readwrite"),s=i.objectStore(xe.DB_STORE_NAME),o=0,a=0,c=e.length;function h(){0==a?t():r()}e.forEach((e=>{var t=s.put(xe.analyzePath(e).object.contents,e);t.onsuccess=()=>{++o+a==c&&h()},t.onerror=()=>{a++,o+a==c&&h()}})),i.onerror=r},n.onerror=r},loadFilesFromDB:(e,t,r)=>{t=t||(()=>{}),r=r||(()=>{});var i=xe.indexedDB();try{var n=i.open(xe.DB_NAME(),xe.DB_VERSION)}catch(e){return r(e)}n.onupgradeneeded=r,n.onsuccess=()=>{var i=n.result;try{var s=i.transaction([xe.DB_STORE_NAME],"readonly")}catch(e){return void r(e)}var o=s.objectStore(xe.DB_STORE_NAME),a=0,c=0,h=e.length;function l(){0==c?t():r()}e.forEach((e=>{var t=o.get(e);t.onsuccess=()=>{xe.analyzePath(e).exists&&xe.unlink(e),xe.createDataFile(Se.dirname(e),Se.basename(e),t.result,!0,!0,!0),++a+c==h&&l()},t.onerror=()=>{c++,a+c==h&&l()}})),s.onerror=r},n.onerror=r}},ke={DEFAULT_POLLMASK:5,calculateAt:function(e,t,r){if(Se.isAbs(t))return t;var i;if(-100===e)i=xe.cwd();else{var n=xe.getStream(e);if(!n)throw new xe.ErrnoError(8);i=n.path}if(0==t.length){if(!r)throw new xe.ErrnoError(44);return i}return Se.join2(i,t)},doStat:function(e,t,r){try{var i=e(t)}catch(e){if(e&&e.node&&Se.normalize(t)!==Se.normalize(xe.getPath(e.node)))return-54;throw e}return U[r>>>2]=i.dev,U[r+4>>>2]=0,U[r+8>>>2]=i.ino,U[r+12>>>2]=i.mode,U[r+16>>>2]=i.nlink,U[r+20>>>2]=i.uid,U[r+24>>>2]=i.gid,U[r+28>>>2]=i.rdev,U[r+32>>>2]=0,ue=[i.size>>>0,(le=i.size,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[r+40>>>2]=ue[0],U[r+44>>>2]=ue[1],U[r+48>>>2]=4096,U[r+52>>>2]=i.blocks,U[r+56>>>2]=i.atime.getTime()/1e3|0,U[r+60>>>2]=0,U[r+64>>>2]=i.mtime.getTime()/1e3|0,U[r+68>>>2]=0,U[r+72>>>2]=i.ctime.getTime()/1e3|0,U[r+76>>>2]=0,ue=[i.ino>>>0,(le=i.ino,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[r+80>>>2]=ue[0],U[r+84>>>2]=ue[1],0},doMsync:function(e,t,r,i,n){var s=B.slice(e,e+r);xe.msync(t,s,n,r,i)},varargs:void 0,get:function(){return ke.varargs+=4,U[ke.varargs-4>>>2]},getStr:function(e){return _(e)},getStreamFromFD:function(e){var t=xe.getStream(e);if(!t)throw new xe.ErrnoError(8);return t}},Pe="To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking";function Ae(e){switch(e){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+e)}}var _e=void 0;function Oe(e){for(var t="",r=e;B[r>>>0];)t+=_e[B[r++>>>0]];return t}var De={},Re={},Fe={},Le=48,Be=57;function Me(e){if(void 0===e)return"_unknown";var t=(e=e.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return t>=Le&&t<=Be?"_"+e:e}function Ie(e,t){return e=Me(e),new Function("body","return function "+e+'() {\n "use strict"; return body.apply(this, arguments);\n};\n')(t)}function Ue(e,t){var r=Ie(t,(function(e){this.name=t,this.message=e;var r=new Error(e).stack;void 0!==r&&(this.stack=this.toString()+"\n"+r.replace(/^Error(:[^\n]*)?\n/,""))}));return r.prototype=Object.create(e.prototype),r.prototype.constructor=r,r.prototype.toString=function(){return void 0===this.message?this.name:this.name+": "+this.message},r}var We=void 0;function Ne(e){throw new We(e)}var Ge=void 0;function He(e){throw new Ge(e)}function Ve(e,t,r){function i(t){var i=r(t);i.length!==e.length&&He("Mismatched type converter count");for(var n=0;n{Re.hasOwnProperty(e)?n[t]=Re[e]:(s.push(e),De.hasOwnProperty(e)||(De[e]=[]),De[e].push((()=>{n[t]=Re[e],++o===s.length&&i(n)})))})),0===s.length&&i(n)}function ze(e,t,r={}){if(!("argPackAdvance"in t))throw new TypeError("registerType registeredInstance requires argPackAdvance");var i=t.name;if(e||Ne('type "'+i+'" must have a positive integer typeid pointer'),Re.hasOwnProperty(e)){if(r.ignoreDuplicateRegistrations)return;Ne("Cannot register type '"+i+"' twice")}if(Re[e]=t,delete Fe[e],De.hasOwnProperty(e)){var n=De[e];delete De[e],n.forEach((e=>e()))}}function je(e){Ne(e.$$.ptrType.registeredClass.name+" instance already deleted")}var qe=!1;function $e(e){}function Ye(e){e.count.value-=1,0===e.count.value&&function(e){e.smartPtr?e.smartPtrType.rawDestructor(e.smartPtr):e.ptrType.registeredClass.rawDestructor(e.ptr)}(e)}function Xe(e,t,r){if(t===r)return e;if(void 0===r.baseClass)return null;var i=Xe(e,t,r.baseClass);return null===i?null:r.downcast(i)}var Ze={};var Je=[];function Qe(){for(;Je.length;){var e=Je.pop();e.$$.deleteScheduled=!1,e.delete()}}var Ke=void 0;var et={};function tt(e,t){return t.ptrType&&t.ptr||He("makeClassHandle requires ptr and ptrType"),!!t.smartPtrType!=!!t.smartPtr&&He("Both smartPtrType and smartPtr must be specified"),t.count={value:1},rt(Object.create(e,{$$:{value:t}}))}function rt(e){return"undefined"==typeof FinalizationRegistry?(rt=e=>e,e):(qe=new FinalizationRegistry((e=>{Ye(e.$$)})),rt=e=>{var t=e.$$;if(t.smartPtr){var r={$$:t};qe.register(e,r,e)}return e},$e=e=>qe.unregister(e),rt(e))}function it(){}function nt(e,t,r){if(void 0===e[t].overloadTable){var i=e[t];e[t]=function(){return e[t].overloadTable.hasOwnProperty(arguments.length)||Ne("Function '"+r+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+e[t].overloadTable+")!"),e[t].overloadTable[arguments.length].apply(this,arguments)},e[t].overloadTable=[],e[t].overloadTable[i.argCount]=i}}function st(t,r,i){e.hasOwnProperty(t)?((void 0===i||void 0!==e[t].overloadTable&&void 0!==e[t].overloadTable[i])&&Ne("Cannot register public name '"+t+"' twice"),nt(e,t,t),e.hasOwnProperty(i)&&Ne("Cannot register multiple overloads of a function with the same number of arguments ("+i+")!"),e[t].overloadTable[i]=r):(e[t]=r,void 0!==i&&(e[t].numArguments=i))}function ot(e,t,r,i,n,s,o,a){this.name=e,this.constructor=t,this.instancePrototype=r,this.rawDestructor=i,this.baseClass=n,this.getActualType=s,this.upcast=o,this.downcast=a,this.pureVirtualFunctions=[]}function at(e,t,r){for(;t!==r;)t.upcast||Ne("Expected null or instance of "+r.name+", got an instance of "+t.name),e=t.upcast(e),t=t.baseClass;return e}function ct(e,t){if(null===t)return this.isReference&&Ne("null is not a valid "+this.name),0;t.$$||Ne('Cannot pass "'+At(t)+'" as a '+this.name),t.$$.ptr||Ne("Cannot pass deleted object as a pointer of type "+this.name);var r=t.$$.ptrType.registeredClass;return at(t.$$.ptr,r,this.registeredClass)}function ht(e,t){var r;if(null===t)return this.isReference&&Ne("null is not a valid "+this.name),this.isSmartPointer?(r=this.rawConstructor(),null!==e&&e.push(this.rawDestructor,r),r):0;t.$$||Ne('Cannot pass "'+At(t)+'" as a '+this.name),t.$$.ptr||Ne("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&t.$$.ptrType.isConst&&Ne("Cannot convert argument of type "+(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name)+" to parameter type "+this.name);var i=t.$$.ptrType.registeredClass;if(r=at(t.$$.ptr,i,this.registeredClass),this.isSmartPointer)switch(void 0===t.$$.smartPtr&&Ne("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:t.$$.smartPtrType===this?r=t.$$.smartPtr:Ne("Cannot convert argument of type "+(t.$$.smartPtrType?t.$$.smartPtrType.name:t.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:r=t.$$.smartPtr;break;case 2:if(t.$$.smartPtrType===this)r=t.$$.smartPtr;else{var n=t.clone();r=this.rawShare(r,kt.toHandle((function(){n.delete()}))),null!==e&&e.push(this.rawDestructor,r)}break;default:Ne("Unsupporting sharing policy")}return r}function lt(e,t){if(null===t)return this.isReference&&Ne("null is not a valid "+this.name),0;t.$$||Ne('Cannot pass "'+At(t)+'" as a '+this.name),t.$$.ptr||Ne("Cannot pass deleted object as a pointer of type "+this.name),t.$$.ptrType.isConst&&Ne("Cannot convert argument of type "+t.$$.ptrType.name+" to parameter type "+this.name);var r=t.$$.ptrType.registeredClass;return at(t.$$.ptr,r,this.registeredClass)}function ut(e){return this.fromWireType(W[e>>>2])}function dt(e,t,r,i,n,s,o,a,c,h,l){this.name=e,this.registeredClass=t,this.isReference=r,this.isConst=i,this.isSmartPointer=n,this.pointeeType=s,this.sharingPolicy=o,this.rawGetPointee=a,this.rawConstructor=c,this.rawShare=h,this.rawDestructor=l,n||void 0!==t.baseClass?this.toWireType=ht:i?(this.toWireType=ct,this.destructorFunction=null):(this.toWireType=lt,this.destructorFunction=null)}function pt(t,r){var i,n,s,o=(t=Oe(t)).includes("j")?(i=t,n=r,s=[],function(){return s.length=0,Object.assign(s,arguments),function(t,r,i){return t.includes("j")?function(t,r,i){var n=e["dynCall_"+t];return i&&i.length?n.apply(null,[r].concat(i)):n.call(null,r)}(t,r,i):me(r).apply(null,i)}(i,n,s)}):me(r);return"function"!=typeof o&&Ne("unknown function pointer with signature "+t+": "+r),o}var ft=void 0;function gt(e){var t=fr(e),r=Oe(t);return dr(t),r}function vt(e,t){var r=[],i={};throw t.forEach((function e(t){i[t]||Re[t]||(Fe[t]?Fe[t].forEach(e):(r.push(t),i[t]=!0))})),new ft(e+": "+r.map(gt).join([", "]))}function mt(e,t){if(!(e instanceof Function))throw new TypeError("new_ called with constructor type "+typeof e+" which is not a function");var r=Ie(e.name||"unknownFunctionName",(function(){}));r.prototype=e.prototype;var i=new r,n=e.apply(i,t);return n instanceof Object?n:i}function yt(e){for(;e.length;){var t=e.pop();e.pop()(t)}}function St(e,t,r,i,n){var s=t.length;s<2&&Ne("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var o=null!==t[1]&&null!==r,a=!1,c=1;c0?", ":"")+u),d+=(h?"var rv = ":"")+"invoker(fn"+(u.length>0?", ":"")+u+");\n",a)d+="runDestructors(destructors);\n";else for(c=o?1:2;c>2)+i>>>0]);return r}function wt(e,t,r){return e instanceof Object||Ne(r+' with invalid "this": '+e),e instanceof t.registeredClass.constructor||Ne(r+' incompatible with "this" of type '+e.constructor.name),e.$$.ptr||Ne("cannot call emscripten binding method "+r+" on deleted object"),at(e.$$.ptr,e.$$.ptrType.registeredClass,t.registeredClass)}var Et=[],Tt=[{},{value:void 0},{value:null},{value:!0},{value:!1}];function xt(e){e>4&&0==--Tt[e].refcount&&(Tt[e]=void 0,Et.push(e))}var kt={toValue:e=>(e||Ne("Cannot use deleted val. handle = "+e),Tt[e].value),toHandle:e=>{switch(e){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:var t=Et.length?Et.pop():Tt.length;return Tt[t]={refcount:1,value:e},t}}};function Pt(e,t,r){switch(t){case 0:return function(e){var t=r?L:B;return this.fromWireType(t[e>>>0])};case 1:return function(e){var t=r?M:I;return this.fromWireType(t[e>>>1])};case 2:return function(e){var t=r?U:W;return this.fromWireType(t[e>>>2])};default:throw new TypeError("Unknown integer type: "+e)}}function Ct(e,t){var r=Re[e];return void 0===r&&Ne(t+" has unknown type "+gt(e)),r}function At(e){if(null===e)return"null";var t=typeof e;return"object"===t||"array"===t||"function"===t?e.toString():""+e}function _t(e,t){switch(t){case 2:return function(e){return this.fromWireType(N[e>>>2])};case 3:return function(e){return this.fromWireType(G[e>>>3])};default:throw new TypeError("Unknown float type: "+e)}}function Ot(e,t,r){switch(t){case 0:return r?function(e){return L[e>>>0]}:function(e){return B[e>>>0]};case 1:return r?function(e){return M[e>>>1]}:function(e){return I[e>>>1]};case 2:return r?function(e){return U[e>>>2]}:function(e){return W[e>>>2]};default:throw new TypeError("Unknown integer type: "+e)}}var Dt={};function Rt(e){var t=Dt[e];return void 0===t?Oe(e):t}var Ft=[];function Lt(){return"object"==typeof globalThis?globalThis:Function("return this")()}var Bt,Mt=[];function It(t,r){if(Nt.mainLoop.timingMode=t,Nt.mainLoop.timingValue=r,!Nt.mainLoop.func)return 1;if(Nt.mainLoop.running||(Nt.mainLoop.running=!0),0==t)Nt.mainLoop.scheduler=function(){var e=0|Math.max(0,Nt.mainLoop.tickStartTime+r-Bt());setTimeout(Nt.mainLoop.runner,e)},Nt.mainLoop.method="timeout";else if(1==t)Nt.mainLoop.scheduler=function(){Nt.requestAnimationFrame(Nt.mainLoop.runner)},Nt.mainLoop.method="rAF";else if(2==t){if("undefined"==typeof setImmediate){var i=[],n="setimmediate";addEventListener("message",(function(e){e.data!==n&&e.data.target!==n||(e.stopPropagation(),i.shift()())}),!0),setImmediate=function(t){i.push(t),g?(void 0===e.setImmediates&&(e.setImmediates=[]),e.setImmediates.push(t),postMessage({target:n})):postMessage(n,"*")}}Nt.mainLoop.scheduler=function(){setImmediate(Nt.mainLoop.runner)},Nt.mainLoop.method="immediate"}return 0}function Ut(e,t){if(!k)if(t)e();else try{e()}catch(e){!function(e){if(e instanceof yr||"unwind"==e)return x;p(1,e)}(e)}}function Wt(e,t){return setTimeout((function(){Ut(e)}),t)}Bt=v?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.now();var Nt={mainLoop:{running:!1,scheduler:null,method:"",currentlyRunningMainloop:0,func:null,arg:0,timingMode:0,timingValue:0,currentFrameNumber:0,queue:[],pause:function(){Nt.mainLoop.scheduler=null,Nt.mainLoop.currentlyRunningMainloop++},resume:function(){Nt.mainLoop.currentlyRunningMainloop++;var e=Nt.mainLoop.timingMode,t=Nt.mainLoop.timingValue,r=Nt.mainLoop.func;Nt.mainLoop.func=null,function(e,t,r,i,n){P(!Nt.mainLoop.func,"emscripten_set_main_loop: there can only be one main loop function at once: call emscripten_cancel_main_loop to cancel the previous one before setting a new one with different parameters."),Nt.mainLoop.func=e,Nt.mainLoop.arg=i;var s=Nt.mainLoop.currentlyRunningMainloop;function o(){return!(s0){var t=Date.now(),r=Nt.mainLoop.queue.shift();if(r.func(r.arg),Nt.mainLoop.remainingBlockers){var i=Nt.mainLoop.remainingBlockers,n=i%1==0?i-1:Math.floor(i);r.counted?Nt.mainLoop.remainingBlockers=n:(n+=.5,Nt.mainLoop.remainingBlockers=(8*i+n)/9)}if(y('main loop blocker "'+r.name+'" took '+(Date.now()-t)+" ms"),Nt.mainLoop.updateStatus(),!o())return;setTimeout(Nt.mainLoop.runner,0)}else o()&&(Nt.mainLoop.currentFrameNumber=Nt.mainLoop.currentFrameNumber+1|0,1==Nt.mainLoop.timingMode&&Nt.mainLoop.timingValue>1&&Nt.mainLoop.currentFrameNumber%Nt.mainLoop.timingValue!=0?Nt.mainLoop.scheduler():(0==Nt.mainLoop.timingMode&&(Nt.mainLoop.tickStartTime=Bt()),Nt.mainLoop.runIter(e),o()&&("object"==typeof SDL&&SDL.audio&&SDL.audio.queueNewAudioData&&SDL.audio.queueNewAudioData(),Nt.mainLoop.scheduler())))}}(r,0,0,Nt.mainLoop.arg),It(e,t),Nt.mainLoop.scheduler()},updateStatus:function(){if(e.setStatus){var t=e.statusMessage||"Please wait...",r=Nt.mainLoop.remainingBlockers,i=Nt.mainLoop.expectedBlockers;r?r{P(a.complete,"Image "+t+" could not be decoded");var i=document.createElement("canvas");i.width=a.width,i.height=a.height,i.getContext("2d").drawImage(a,0,0),ir[t]=i,Nt.URLObject.revokeObjectURL(o),r&&r(e)},a.onerror=e=>{y("Image "+o+" could not be decoded"),i&&i()},a.src=o}};e.preloadPlugins.push(t);var r={canHandle:function(t){return!e.noAudioDecoding&&t.substr(-4)in{".ogg":1,".wav":1,".mp3":1}},handle:function(e,t,r,i){var n=!1;function s(i){n||(n=!0,nr[t]=i,r&&r(e))}function o(){n||(n=!0,nr[t]=new Audio,i&&i())}if(!Nt.hasBlobConstructor)return o();try{var a=new Blob([e],{type:Nt.getMimetype(t)})}catch(e){return o()}var c=Nt.URLObject.createObjectURL(a),h=new Audio;h.addEventListener("canplaythrough",(function(){s(h)}),!1),h.onerror=function(r){n||(y("warning: browser could not fully decode audio "+t+", trying slower base64 approach"),h.src="data:audio/x-"+t.substr(-3)+";base64,"+function(e){for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r="",i=0,n=0,s=0;s=6;){var o=i>>n-6&63;n-=6,r+=t[o]}return 2==n?(r+=t[(3&i)<<4],r+="=="):4==n&&(r+=t[(15&i)<<2],r+="="),r}(e),s(h))},h.src=c,Wt((function(){s(h)}),1e4)}};e.preloadPlugins.push(r);var i=e.canvas;i&&(i.requestPointerLock=i.requestPointerLock||i.mozRequestPointerLock||i.webkitRequestPointerLock||i.msRequestPointerLock||function(){},i.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock||document.msExitPointerLock||function(){},i.exitPointerLock=i.exitPointerLock.bind(document),document.addEventListener("pointerlockchange",n,!1),document.addEventListener("mozpointerlockchange",n,!1),document.addEventListener("webkitpointerlockchange",n,!1),document.addEventListener("mspointerlockchange",n,!1),e.elementPointerLock&&i.addEventListener("click",(function(t){!Nt.pointerLock&&e.canvas.requestPointerLock&&(e.canvas.requestPointerLock(),t.preventDefault())}),!1))}function n(){Nt.pointerLock=document.pointerLockElement===e.canvas||document.mozPointerLockElement===e.canvas||document.webkitPointerLockElement===e.canvas||document.msPointerLockElement===e.canvas}},handledByPreloadPlugin:function(t,r,i,n){Nt.init();var s=!1;return e.preloadPlugins.forEach((function(e){s||e.canHandle(r)&&(e.handle(t,r,i,n),s=!0)})),s},createContext:function(t,r,i,n){if(r&&e.ctx&&t==e.canvas)return e.ctx;var s,o;if(r){var a={antialias:!1,alpha:!1,majorVersion:1};if(n)for(var c in n)a[c]=n[c];void 0!==$t&&(o=$t.createContext(t,a))&&(s=$t.getContext(o).GLctx)}else s=t.getContext("2d");return s?(i&&(r||P(void 0===rr,"cannot set in module if GLctx is used, but we are a non-GL context that would replace it"),e.ctx=s,r&&$t.makeContextCurrent(o),e.useWebGL=r,Nt.moduleContextCreatedCallbacks.forEach((function(e){e()})),Nt.init()),s):null},destroyContext:function(e,t,r){},fullscreenHandlersInstalled:!1,lockPointer:void 0,resizeCanvas:void 0,requestFullscreen:function(t,r){Nt.lockPointer=t,Nt.resizeCanvas=r,void 0===Nt.lockPointer&&(Nt.lockPointer=!0),void 0===Nt.resizeCanvas&&(Nt.resizeCanvas=!1);var i=e.canvas;function n(){Nt.isFullscreen=!1;var t=i.parentNode;(document.fullscreenElement||document.mozFullScreenElement||document.msFullscreenElement||document.webkitFullscreenElement||document.webkitCurrentFullScreenElement)===t?(i.exitFullscreen=Nt.exitFullscreen,Nt.lockPointer&&i.requestPointerLock(),Nt.isFullscreen=!0,Nt.resizeCanvas?Nt.setFullscreenCanvasSize():Nt.updateCanvasDimensions(i)):(t.parentNode.insertBefore(i,t),t.parentNode.removeChild(t),Nt.resizeCanvas?Nt.setWindowedCanvasSize():Nt.updateCanvasDimensions(i)),e.onFullScreen&&e.onFullScreen(Nt.isFullscreen),e.onFullscreen&&e.onFullscreen(Nt.isFullscreen)}Nt.fullscreenHandlersInstalled||(Nt.fullscreenHandlersInstalled=!0,document.addEventListener("fullscreenchange",n,!1),document.addEventListener("mozfullscreenchange",n,!1),document.addEventListener("webkitfullscreenchange",n,!1),document.addEventListener("MSFullscreenChange",n,!1));var s=document.createElement("div");i.parentNode.insertBefore(s,i),s.appendChild(i),s.requestFullscreen=s.requestFullscreen||s.mozRequestFullScreen||s.msRequestFullscreen||(s.webkitRequestFullscreen?function(){s.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT)}:null)||(s.webkitRequestFullScreen?function(){s.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT)}:null),s.requestFullscreen()},exitFullscreen:function(){return!!Nt.isFullscreen&&((document.exitFullscreen||document.cancelFullScreen||document.mozCancelFullScreen||document.msExitFullscreen||document.webkitCancelFullScreen||function(){}).apply(document,[]),!0)},nextRAF:0,fakeRequestAnimationFrame:function(e){var t=Date.now();if(0===Nt.nextRAF)Nt.nextRAF=t+1e3/60;else for(;t+2>=Nt.nextRAF;)Nt.nextRAF+=1e3/60;var r=Math.max(Nt.nextRAF-t,0);setTimeout(e,r)},requestAnimationFrame:function(e){"function"!=typeof requestAnimationFrame?(0,Nt.fakeRequestAnimationFrame)(e):requestAnimationFrame(e)},safeSetTimeout:function(e){return Wt(e)},safeRequestAnimationFrame:function(e){return Nt.requestAnimationFrame((function(){Ut(e)}))},getMimetype:function(e){return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",bmp:"image/bmp",ogg:"audio/ogg",wav:"audio/wav",mp3:"audio/mpeg"}[e.substr(e.lastIndexOf(".")+1)]},getUserMedia:function(e){window.getUserMedia||(window.getUserMedia=navigator.getUserMedia||navigator.mozGetUserMedia),window.getUserMedia(e)},getMovementX:function(e){return e.movementX||e.mozMovementX||e.webkitMovementX||0},getMovementY:function(e){return e.movementY||e.mozMovementY||e.webkitMovementY||0},getMouseWheelDelta:function(e){var t=0;switch(e.type){case"DOMMouseScroll":t=e.detail/3;break;case"mousewheel":t=e.wheelDelta/120;break;case"wheel":switch(t=e.deltaY,e.deltaMode){case 0:t/=100;break;case 1:t/=3;break;case 2:t*=80;break;default:throw"unrecognized mouse wheel delta mode: "+e.deltaMode}break;default:throw"unrecognized mouse wheel event: "+e.type}return t},mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,touches:{},lastTouches:{},calculateMouseEvent:function(t){if(Nt.pointerLock)"mousemove"!=t.type&&"mozMovementX"in t?Nt.mouseMovementX=Nt.mouseMovementY=0:(Nt.mouseMovementX=Nt.getMovementX(t),Nt.mouseMovementY=Nt.getMovementY(t)),"undefined"!=typeof SDL?(Nt.mouseX=SDL.mouseX+Nt.mouseMovementX,Nt.mouseY=SDL.mouseY+Nt.mouseMovementY):(Nt.mouseX+=Nt.mouseMovementX,Nt.mouseY+=Nt.mouseMovementY);else{var r=e.canvas.getBoundingClientRect(),i=e.canvas.width,n=e.canvas.height,s=void 0!==window.scrollX?window.scrollX:window.pageXOffset,o=void 0!==window.scrollY?window.scrollY:window.pageYOffset;if("touchstart"===t.type||"touchend"===t.type||"touchmove"===t.type){var a=t.touch;if(void 0===a)return;var c=a.pageX-(s+r.left),h=a.pageY-(o+r.top),l={x:c*=i/r.width,y:h*=n/r.height};if("touchstart"===t.type)Nt.lastTouches[a.identifier]=l,Nt.touches[a.identifier]=l;else if("touchend"===t.type||"touchmove"===t.type){var u=Nt.touches[a.identifier];u||(u=l),Nt.lastTouches[a.identifier]=u,Nt.touches[a.identifier]=l}return}var d=t.pageX-(s+r.left),p=t.pageY-(o+r.top);d*=i/r.width,p*=n/r.height,Nt.mouseMovementX=d-Nt.mouseX,Nt.mouseMovementY=p-Nt.mouseY,Nt.mouseX=d,Nt.mouseY=p}},resizeListeners:[],updateResizeListeners:function(){var t=e.canvas;Nt.resizeListeners.forEach((function(e){e(t.width,t.height)}))},setCanvasSize:function(t,r,i){var n=e.canvas;Nt.updateCanvasDimensions(n,t,r),i||Nt.updateResizeListeners()},windowedWidth:0,windowedHeight:0,setFullscreenCanvasSize:function(){if("undefined"!=typeof SDL){var t=W[SDL.screen>>>2];t|=8388608,U[SDL.screen>>>2]=t}Nt.updateCanvasDimensions(e.canvas),Nt.updateResizeListeners()},setWindowedCanvasSize:function(){if("undefined"!=typeof SDL){var t=W[SDL.screen>>>2];t&=-8388609,U[SDL.screen>>>2]=t}Nt.updateCanvasDimensions(e.canvas),Nt.updateResizeListeners()},updateCanvasDimensions:function(t,r,i){r&&i?(t.widthNative=r,t.heightNative=i):(r=t.widthNative,i=t.heightNative);var n=r,s=i;if(e.forcedAspectRatio&&e.forcedAspectRatio>0&&(n/s>>16),Z(E.buffer),1}catch(e){}}var Ht={};function Vt(){if(!Vt.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:d||"./this.program"};for(var t in Ht)void 0===Ht[t]?delete e[t]:e[t]=Ht[t];var r=[];for(var t in e)r.push(t+"="+e[t]);Vt.strings=r}return Vt.strings}function zt(e){for(var t=e.split("."),r=0;r<4;r++){var i=Number(t[r]);if(isNaN(i))return null;t[r]=i}return(t[0]|t[1]<<8|t[2]<<16|t[3]<<24)>>>0}function jt(e){return parseInt(e)}var qt={address_map:{id:1,addrs:{},names:{}},lookup_name:function(e){var t,r=zt(e);if(null!==r)return e;if(null!==(r=function(e){var t,r,i,n,s=[];if(!/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i.test(e))return null;if("::"===e)return[0,0,0,0,0,0,0,0];for((e=e.startsWith("::")?e.replace("::","Z:"):e.replace("::",":Z:")).indexOf(".")>0?((t=(e=e.replace(new RegExp("[.]","g"),":")).split(":"))[t.length-4]=jt(t[t.length-4])+256*jt(t[t.length-3]),t[t.length-3]=jt(t[t.length-2])+256*jt(t[t.length-1]),t=t.slice(0,t.length-2)):t=e.split(":"),i=0,n=0,r=0;r>>2]:-1;n+=_(U[r+4*s>>>2],o<0?void 0:o)}return n},createContext:function(e,t){if(!e.getContextSafariWebGL2Fixed){function i(t,r){var i=e.getContextSafariWebGL2Fixed(t,r);return"webgl"==t==i instanceof WebGLRenderingContext?i:null}e.getContextSafariWebGL2Fixed=e.getContext,e.getContext=i}var r=e.getContext("webgl",t);return r?$t.registerContext(r,t):0},registerContext:function(e,t){var r=$t.getNewId($t.contexts),i={handle:r,attributes:t,version:t.majorVersion,GLctx:e};return e.canvas&&(e.canvas.GLctxObject=i),$t.contexts[r]=i,(void 0===t.enableExtensionsByDefault||t.enableExtensionsByDefault)&&$t.initExtensions(i),r},makeContextCurrent:function(t){return $t.currentContext=$t.contexts[t],e.ctx=rr=$t.currentContext&&$t.currentContext.GLctx,!(t&&!rr)},getContext:function(e){return $t.contexts[e]},deleteContext:function(e){$t.currentContext===$t.contexts[e]&&($t.currentContext=null),"object"==typeof JSEvents&&JSEvents.removeAllHandlersOnTarget($t.contexts[e].GLctx.canvas),$t.contexts[e]&&$t.contexts[e].GLctx.canvas&&($t.contexts[e].GLctx.canvas.GLctxObject=void 0),$t.contexts[e]=null},initExtensions:function(e){if(e||(e=$t.currentContext),!e.initExtensionsDone){e.initExtensionsDone=!0;var t,r=e.GLctx;!function(e){var t=e.getExtension("ANGLE_instanced_arrays");t&&(e.vertexAttribDivisor=function(e,r){t.vertexAttribDivisorANGLE(e,r)},e.drawArraysInstanced=function(e,r,i,n){t.drawArraysInstancedANGLE(e,r,i,n)},e.drawElementsInstanced=function(e,r,i,n,s){t.drawElementsInstancedANGLE(e,r,i,n,s)})}(r),function(e){var t=e.getExtension("OES_vertex_array_object");t&&(e.createVertexArray=function(){return t.createVertexArrayOES()},e.deleteVertexArray=function(e){t.deleteVertexArrayOES(e)},e.bindVertexArray=function(e){t.bindVertexArrayOES(e)},e.isVertexArray=function(e){return t.isVertexArrayOES(e)})}(r),function(e){var t=e.getExtension("WEBGL_draw_buffers");t&&(e.drawBuffers=function(e,r){t.drawBuffersWEBGL(e,r)})}(r),r.disjointTimerQueryExt=r.getExtension("EXT_disjoint_timer_query"),(t=r).multiDrawWebgl=t.getExtension("WEBGL_multi_draw"),(r.getSupportedExtensions()||[]).forEach((function(e){e.includes("lose_context")||e.includes("debug")||r.getExtension(e)}))}}};function Yt(e){return"]"==e.slice(-1)&&e.lastIndexOf("[")}function Xt(e){var t=rr.currentProgram;if(t){var r=t.uniformLocsById[e];return"number"==typeof r&&(t.uniformLocsById[e]=r=rr.getUniformLocation(t,t.uniformArrayNamesById[e]+(r>0?"["+r+"]":""))),r}$t.recordError(1282)}var Zt=[],Jt=[];function Qt(e){return e%4==0&&(e%100!=0||e%400==0)}var Kt=[31,29,31,30,31,30,31,31,30,31,30,31],er=[31,28,31,30,31,30,31,31,30,31,30,31];var tr=function(e,t,r,i){e||(e=this),this.parent=e,this.mount=e.mount,this.mounted=null,this.id=xe.nextInode++,this.name=t,this.mode=r,this.node_ops={},this.stream_ops={},this.rdev=i};Object.defineProperties(tr.prototype,{read:{get:function(){return!(365&~this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return!(146&~this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}},isFolder:{get:function(){return xe.isDir(this.mode)}},isDevice:{get:function(){return xe.isChrdev(this.mode)}}}),xe.FSNode=tr,xe.staticInit(),function(){for(var e=new Array(256),t=0;t<256;++t)e[t]=String.fromCharCode(t);_e=e}(),We=e.BindingError=Ue(Error,"BindingError"),Ge=e.InternalError=Ue(Error,"InternalError"),it.prototype.isAliasOf=function(e){if(!(this instanceof it))return!1;if(!(e instanceof it))return!1;for(var t=this.$$.ptrType.registeredClass,r=this.$$.ptr,i=e.$$.ptrType.registeredClass,n=e.$$.ptr;t.baseClass;)r=t.upcast(r),t=t.baseClass;for(;i.baseClass;)n=i.upcast(n),i=i.baseClass;return t===i&&r===n},it.prototype.clone=function(){if(this.$$.ptr||je(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var e,t=rt(Object.create(Object.getPrototypeOf(this),{$$:{value:(e=this.$$,{count:e.count,deleteScheduled:e.deleteScheduled,preservePointerOnDelete:e.preservePointerOnDelete,ptr:e.ptr,ptrType:e.ptrType,smartPtr:e.smartPtr,smartPtrType:e.smartPtrType})}}));return t.$$.count.value+=1,t.$$.deleteScheduled=!1,t},it.prototype.delete=function(){this.$$.ptr||je(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ne("Object already scheduled for deletion"),$e(this),Ye(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},it.prototype.isDeleted=function(){return!this.$$.ptr},it.prototype.deleteLater=function(){return this.$$.ptr||je(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ne("Object already scheduled for deletion"),Je.push(this),1===Je.length&&Ke&&Ke(Qe),this.$$.deleteScheduled=!0,this},e.getInheritedInstanceCount=function(){return Object.keys(et).length},e.getLiveInheritedInstances=function(){var e=[];for(var t in et)et.hasOwnProperty(t)&&e.push(et[t]);return e},e.flushPendingDeletes=Qe,e.setDelayFunction=function(e){Ke=e,Je.length&&Ke&&Ke(Qe)},dt.prototype.getPointee=function(e){return this.rawGetPointee&&(e=this.rawGetPointee(e)),e},dt.prototype.destructor=function(e){this.rawDestructor&&this.rawDestructor(e)},dt.prototype.argPackAdvance=8,dt.prototype.readValueFromPointer=ut,dt.prototype.deleteObject=function(e){null!==e&&e.delete()},dt.prototype.fromWireType=function(e){var t=this.getPointee(e);if(!t)return this.destructor(e),null;var r=function(e,t){return t=function(e,t){for(void 0===t&&Ne("ptr should not be undefined");e.baseClass;)t=e.upcast(t),e=e.baseClass;return t}(e,t),et[t]}(this.registeredClass,t);if(void 0!==r){if(0===r.$$.count.value)return r.$$.ptr=t,r.$$.smartPtr=e,r.clone();var i=r.clone();return this.destructor(e),i}function n(){return this.isSmartPointer?tt(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:t,smartPtrType:this,smartPtr:e}):tt(this.registeredClass.instancePrototype,{ptrType:this,ptr:e})}var s,o=this.registeredClass.getActualType(t),a=Ze[o];if(!a)return n.call(this);s=this.isConst?a.constPointerType:a.pointerType;var c=Xe(t,this.registeredClass,s.registeredClass);return null===c?n.call(this):this.isSmartPointer?tt(s.registeredClass.instancePrototype,{ptrType:s,ptr:c,smartPtrType:this,smartPtr:e}):tt(s.registeredClass.instancePrototype,{ptrType:s,ptr:c})},ft=e.UnboundTypeError=Ue(Error,"UnboundTypeError"),e.count_emval_handles=function(){for(var e=0,t=5;t0?r:R(e)+1,n=new Array(i),s=O(e,n,0,n.length);return t&&(n.length=s),n}var hr,lr={na:function(){return e.HEAP8.length},g:function(e,t,r,i){ae("Assertion failed: "+_(e)+", at: "+[t?_(t):"unknown filename",r,i?_(i):"unknown function"])},b:function(e){return ur(e+24)+24},c:function(e,t,r){throw new ye(e).init(t,r),e},Z:function(e,t){try{return e=ke.getStr(e),xe.chmod(e,t),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},_:function(e,t,r,i){try{if(t=ke.getStr(t),t=ke.calculateAt(e,t),-8&r)return-28;var n=xe.lookupPath(t,{follow:!0}).node;if(!n)return-44;var s="";return 4&r&&(s+="r"),2&r&&(s+="w"),1&r&&(s+="x"),s&&xe.nodePermissions(n,s)?-2:0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},r:function(e,t,r){ke.varargs=r;try{var i=ke.getStreamFromFD(e);switch(t){case 0:return(n=ke.get())<0?-28:xe.createStream(i,n).fd;case 1:case 2:case 6:case 7:return 0;case 3:return i.flags;case 4:var n=ke.get();return i.flags|=n,0;case 5:return n=ke.get(),M[n+0>>>1]=2,0;case 16:case 8:default:return-28;case 9:return 28,U[pr()>>>2]=28,-1}}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},Q:function(e,t){try{var r=ke.getStreamFromFD(e);return ke.doStat(xe.stat,r.path,t)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},I:function(e,t,r){try{var i=ke.getStreamFromFD(e);i.getdents||(i.getdents=xe.readdir(i.path));for(var n=280,s=0,o=xe.llseek(i,0,1),a=Math.floor(o/n);a>>0,(le=c,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[t+s>>>2]=ue[0],U[t+s+4>>>2]=ue[1],ue=[(a+1)*n>>>0,(le=(a+1)*n,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[t+s+8>>>2]=ue[0],U[t+s+12>>>2]=ue[1],M[t+s+16>>>1]=280,L[t+s+18>>>0]=h,D(l,t+s+19,256),s+=n,a+=1}return xe.llseek(i,a*n,0),s}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},$:function(e,t,r){ke.varargs=r;try{var i=ke.getStreamFromFD(e);switch(t){case 21509:case 21505:case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:case 21523:case 21524:return i.tty?0:-59;case 21519:if(!i.tty)return-59;var n=ke.get();return U[n>>>2]=0,0;case 21520:return i.tty?-28:-59;case 21531:return n=ke.get(),xe.ioctl(i,t,n);default:ae("bad ioctl syscall "+t)}}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},N:function(e,t){try{return e=ke.getStr(e),ke.doStat(xe.lstat,e,t)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},K:function(e,t,r){try{return t=ke.getStr(t),t=ke.calculateAt(e,t),"/"===(t=Se.normalize(t))[t.length-1]&&(t=t.substr(0,t.length-1)),xe.mkdir(t,r,0),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},O:function(e,t,r,i){try{t=ke.getStr(t);var n=256&i,s=4096&i;return i&=-4353,t=ke.calculateAt(e,t,s),ke.doStat(n?xe.lstat:xe.stat,t,r)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},v:function(e,t,r,i){ke.varargs=i;try{t=ke.getStr(t),t=ke.calculateAt(e,t);var n=i?ke.get():0;return xe.open(t,r,n).fd}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},H:function(e){try{return e=ke.getStr(e),xe.rmdir(e),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},P:function(e,t){try{return e=ke.getStr(e),ke.doStat(xe.stat,e,t)}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},F:function(e,t,r){try{return t=ke.getStr(t),t=ke.calculateAt(e,t),0===r?xe.unlink(t):512===r?xe.rmdir(t):ae("Invalid flags passed to unlinkat"),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},W:function(e){},Y:function(e,t){ae(Pe)},X:function(e,t){ae(Pe)},B:function(e,t,r,i,n){},ba:function(e,t,r,i,n){var s=Ae(r);ze(e,{name:t=Oe(t),fromWireType:function(e){return!!e},toWireType:function(e,t){return t?i:n},argPackAdvance:8,readValueFromPointer:function(e){var i;if(1===r)i=L;else if(2===r)i=M;else{if(4!==r)throw new TypeError("Unknown boolean type size: "+t);i=U}return this.fromWireType(i[e>>>s])},destructorFunction:null})},d:function(t,r,i,n,s,o,a,c,h,l,u,d,p){u=Oe(u),o=pt(s,o),c&&(c=pt(a,c)),l&&(l=pt(h,l)),p=pt(d,p);var f=Me(u);st(f,(function(){vt("Cannot construct "+u+" due to unbound types",[n])})),Ve([t,r,i],n?[n]:[],(function(r){var i,s;r=r[0],s=n?(i=r.registeredClass).instancePrototype:it.prototype;var a=Ie(f,(function(){if(Object.getPrototypeOf(this)!==h)throw new We("Use 'new' to construct "+u);if(void 0===d.constructor_body)throw new We(u+" has no accessible constructor");var e=d.constructor_body[arguments.length];if(void 0===e)throw new We("Tried to invoke ctor of "+u+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(d.constructor_body).toString()+") parameters instead!");return e.apply(this,arguments)})),h=Object.create(s,{constructor:{value:a}});a.prototype=h;var d=new ot(u,a,h,p,i,o,c,l),g=new dt(u,d,!0,!1,!1),v=new dt(u+"*",d,!1,!1,!1),m=new dt(u+" const*",d,!1,!0,!1);return Ze[t]={pointerType:v,constPointerType:m},function(t,r,i){e.hasOwnProperty(t)||He("Replacing nonexistant public symbol"),e[t].overloadTable,e[t]=r,e[t].argCount=i}(f,a),[g,v,m]}))},f:function(e,t,r,i,n,s,o){var a=bt(r,i);t=Oe(t),s=pt(n,s),Ve([],[e],(function(e){var i=(e=e[0]).name+"."+t;function n(){vt("Cannot call "+i+" due to unbound types",a)}t.startsWith("@@")&&(t=Symbol[t.substring(2)]);var c=e.registeredClass.constructor;return void 0===c[t]?(n.argCount=r-1,c[t]=n):(nt(c,t,i),c[t].overloadTable[r-1]=n),Ve([],a,(function(e){var n=[e[0],null].concat(e.slice(1)),a=St(i,n,null,s,o);return void 0===c[t].overloadTable?(a.argCount=r-1,c[t]=a):c[t].overloadTable[r-1]=a,[]})),[]}))},e:function(e,t,r,i,n,s){P(t>0);var o=bt(t,r);n=pt(i,n),Ve([],[e],(function(e){var r="constructor "+(e=e[0]).name;if(void 0===e.registeredClass.constructor_body&&(e.registeredClass.constructor_body=[]),void 0!==e.registeredClass.constructor_body[t-1])throw new We("Cannot register multiple constructors with identical number of parameters ("+(t-1)+") for class '"+e.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return e.registeredClass.constructor_body[t-1]=()=>{vt("Cannot construct "+e.name+" due to unbound types",o)},Ve([],o,(function(i){return i.splice(1,0,null),e.registeredClass.constructor_body[t-1]=St(r,i,null,n,s),[]})),[]}))},a:function(e,t,r,i,n,s,o,a){var c=bt(r,i);t=Oe(t),s=pt(n,s),Ve([],[e],(function(e){var i=(e=e[0]).name+"."+t;function n(){vt("Cannot call "+i+" due to unbound types",c)}t.startsWith("@@")&&(t=Symbol[t.substring(2)]),a&&e.registeredClass.pureVirtualFunctions.push(t);var h=e.registeredClass.instancePrototype,l=h[t];return void 0===l||void 0===l.overloadTable&&l.className!==e.name&&l.argCount===r-2?(n.argCount=r-2,n.className=e.name,h[t]=n):(nt(h,t,i),h[t].overloadTable[r-2]=n),Ve([],c,(function(n){var a=St(i,n,e,s,o);return void 0===h[t].overloadTable?(a.argCount=r-2,h[t]=a):h[t].overloadTable[r-2]=a,[]})),[]}))},k:function(e,t,r,i,n,s,o,a,c,h){t=Oe(t),n=pt(i,n),Ve([],[e],(function(e){var i=(e=e[0]).name+"."+t,l={get:function(){vt("Cannot access "+i+" due to unbound types",[r,o])},enumerable:!0,configurable:!0};return l.set=c?()=>{vt("Cannot access "+i+" due to unbound types",[r,o])}:e=>{Ne(i+" is a read-only property")},Object.defineProperty(e.registeredClass.instancePrototype,t,l),Ve([],c?[r,o]:[r],(function(r){var o=r[0],l={get:function(){var t=wt(this,e,i+" getter");return o.fromWireType(n(s,t))},enumerable:!0};if(c){c=pt(a,c);var u=r[1];l.set=function(t){var r=wt(this,e,i+" setter"),n=[];c(h,r,u.toWireType(n,t)),yt(n)}}return Object.defineProperty(e.registeredClass.instancePrototype,t,l),[]})),[]}))},aa:function(e,t){ze(e,{name:t=Oe(t),fromWireType:function(e){var t=kt.toValue(e);return xt(e),t},toWireType:function(e,t){return kt.toHandle(t)},argPackAdvance:8,readValueFromPointer:ut,destructorFunction:null})},i:function(e,t,r,i){var n=Ae(r);function s(){}t=Oe(t),s.values={},ze(e,{name:t,constructor:s,fromWireType:function(e){return this.constructor.values[e]},toWireType:function(e,t){return t.value},argPackAdvance:8,readValueFromPointer:Pt(t,n,i),destructorFunction:null}),st(t,s)},h:function(e,t,r){var i=Ct(e,"enum");t=Oe(t);var n=i.constructor,s=Object.create(i.constructor.prototype,{value:{value:r},constructor:{value:Ie(i.name+"_"+t,(function(){}))}});n.values[r]=s,n[t]=s},y:function(e,t,r){var i=Ae(r);ze(e,{name:t=Oe(t),fromWireType:function(e){return e},toWireType:function(e,t){return t},argPackAdvance:8,readValueFromPointer:_t(t,i),destructorFunction:null})},l:function(e,t,r,i,n){t=Oe(t),-1===n&&(n=4294967295);var s=Ae(r),o=e=>e;if(0===i){var a=32-8*r;o=e=>e<>>a}var c=t.includes("unsigned");ze(e,{name:t,fromWireType:o,toWireType:c?function(e,t){return this.name,t>>>0}:function(e,t){return this.name,t},argPackAdvance:8,readValueFromPointer:Ot(t,s,0!==i),destructorFunction:null})},j:function(e,t,r){var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][t];function n(e){var t=W,r=t[(e>>=2)>>>0],n=t[e+1>>>0];return new i(F,n,r)}ze(e,{name:r=Oe(r),fromWireType:n,argPackAdvance:8,readValueFromPointer:n},{ignoreDuplicateRegistrations:!0})},x:function(e,t){var r="std::string"===(t=Oe(t));ze(e,{name:t,fromWireType:function(e){var t,i=W[e>>>2];if(r)for(var n=e+4,s=0;s<=i;++s){var o=e+4+s;if(s==i||0==B[o>>>0]){var a=_(n,o-n);void 0===t?t=a:(t+=String.fromCharCode(0),t+=a),n=o+1}}else{var c=new Array(i);for(s=0;s>>0]);t=c.join("")}return dr(e),t},toWireType:function(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var i="string"==typeof t;i||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||Ne("Cannot pass non-string to std::string");var n=(r&&i?()=>R(t):()=>t.length)(),s=ur(4+n+1);if(W[(s>>>=0)>>>2]=n,r&&i)D(t,s+4,n+1);else if(i)for(var o=0;o255&&(dr(s),Ne("String has UTF-16 code units that do not fit in 8 bits")),B[s+4+o>>>0]=a}else for(o=0;o>>0]=t[o];return null!==e&&e.push(dr,s),s},argPackAdvance:8,readValueFromPointer:ut,destructorFunction:function(e){dr(e)}})},s:function(e,t,r){var i,n,s,o,a;r=Oe(r),2===t?(i=V,n=z,o=j,s=()=>I,a=1):4===t&&(i=q,n=$,o=Y,s=()=>W,a=2),ze(e,{name:r,fromWireType:function(e){for(var r,n=W[e>>>2],o=s(),c=e+4,h=0;h<=n;++h){var l=e+4+h*t;if(h==n||0==o[l>>>a]){var u=i(c,l-c);void 0===r?r=u:(r+=String.fromCharCode(0),r+=u),c=l+t}}return dr(e),r},toWireType:function(e,i){"string"!=typeof i&&Ne("Cannot pass non-string to C++ string type "+r);var s=o(i),c=ur(4+s+t);return W[(c>>>=0)>>>2]=s>>a,n(i,c+4,s+t),null!==e&&e.push(dr,c),c},argPackAdvance:8,readValueFromPointer:ut,destructorFunction:function(e){dr(e)}})},ca:function(e,t){ze(e,{isVoid:!0,name:t=Oe(t),argPackAdvance:0,fromWireType:function(){},toWireType:function(e,t){}})},T:function(){return Date.now()},S:function(){return!0},n:function(e,t,r){e=kt.toValue(e),t=Ct(t,"emval::as");var i=[],n=kt.toHandle(i);return U[r>>>2]=n,t.toWireType(i,e)},sa:function(e,t,r,i,n){return(e=Ft[e])(t=kt.toValue(t),r=Rt(r),function(e){var t=[];return U[e>>>2]=kt.toHandle(t),t}(i),n)},wa:xt,ta:function(e){return 0===e?kt.toHandle(Lt()):(e=Rt(e),kt.toHandle(Lt()[e]))},ra:function(e,t){var r=function(e,t){for(var r=new Array(e),i=0;i>>2],"parameter "+i);return r}(e,t),i=r[0],n=i.name+"_$"+r.slice(1).map((function(e){return e.name})).join("_")+"$",s=Mt[n];if(void 0!==s)return s;for(var o=["retType"],a=[i],c="",h=0;h4&&(Tt[e].refcount+=1)},qa:function(e){return kt.toHandle(Rt(e))},ua:function(e){yt(kt.toValue(e)),xt(e)},o:function(e,t,r){e=kt.toValue(e),t=kt.toValue(t),r=kt.toValue(r),e[t]=r},m:function(e,t){var r=(e=Ct(e,"_emval_take_value")).readValueFromPointer(t);return kt.toHandle(r)},va:function(e){return e=kt.toValue(e),kt.toHandle(typeof e)},U:function(e,t){var r=new Date(1e3*U[e>>>2]);U[t>>>2]=r.getSeconds(),U[t+4>>>2]=r.getMinutes(),U[t+8>>>2]=r.getHours(),U[t+12>>>2]=r.getDate(),U[t+16>>>2]=r.getMonth(),U[t+20>>>2]=r.getFullYear()-1900,U[t+24>>>2]=r.getDay();var i=new Date(r.getFullYear(),0,1),n=(r.getTime()-i.getTime())/864e5|0;U[t+28>>>2]=n,U[t+36>>>2]=-60*r.getTimezoneOffset();var s=new Date(r.getFullYear(),6,1).getTimezoneOffset(),o=i.getTimezoneOffset(),a=0|(s!=o&&r.getTimezoneOffset()==Math.min(o,s));U[t+32>>>2]=a},J:function(e,t,r,i,n,s){try{e>>>=0;var o=xe.getStream(n);o&&(2&r&&ke.doMsync(e,o,t,i,s),xe.munmap(o))}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return-e.errno}},V:function e(t,r,i){e.called||(e.called=!0,function(e,t,r){var i=(new Date).getFullYear(),n=new Date(i,0,1),s=new Date(i,6,1),o=n.getTimezoneOffset(),a=s.getTimezoneOffset(),c=Math.max(o,a);function h(e){var t=e.toTimeString().match(/\(([A-Za-z ]+)\)$/);return t?t[1]:"GMT"}U[e>>>2]=60*c,U[t>>>2]=Number(o!=a);var l=h(n),u=h(s),d=X(l),p=X(u);a>>2]=d,W[r+4>>>2]=p):(W[r>>>2]=p,W[r+4>>>2]=d)}(t,r,i))},u:function(){ae("")},G:function(){return 4294901760},da:function(e,t,r){(0|e)===e&&(e=_(e)),e=be.resolve(e);var i=ir[e];if(i){var n=i.getContext("2d").getImageData(0,0,i.width,i.height),s=ur(i.width*i.height*4);return B.set(n.data,s>>>0),U[t>>>2]=i.width,U[r>>>2]=i.height,s}return 0},R:function(e,t,r){B.copyWithin(e>>>0,t>>>0,t+r>>>0)},E:function(e){var t,r=B.length,i=4294901760;if((e>>>=0)>i)return!1;for(var n=1;n<=4;n*=2){var s=r*(1+.2/n);if(s=Math.min(s,e+100663296),Gt(Math.min(i,(t=Math.max(e,s))+(65536-t%65536)%65536)))return!0}return!1},L:function(e,t){var r=0;return Vt().forEach((function(i,n){var s=t+r;W[e+4*n>>>2]=s,function(e,t,r){for(var i=0;i>>0]=e.charCodeAt(i);L[t>>>0]=0}(i,s),r+=i.length+1})),0},M:function(e,t){var r=Vt();W[e>>>2]=r.length;var i=0;return r.forEach((function(e){i+=e.length+1})),W[t>>>2]=i,0},oa:function(t){!function(t,r){var i;x=t,x=i=t,te()||(e.onExit&&e.onExit(i),k=!0),p(i,new yr(i))}(t)},p:function(e){try{var t=ke.getStreamFromFD(e);return xe.close(t),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}},w:function(e,t,r,i){try{var n=function(e,t,r,i){for(var n=0,s=0;s>>2],a=W[t+4>>>2];t+=8;var c=xe.read(e,L,o,a,undefined);if(c<0)return-1;if(n+=c,c>>2]=n,0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}},A:function(e,t,r,i,n){try{var s=(c=r)+2097152>>>0<4194305-!!(a=t)?(a>>>0)+4294967296*c:NaN;if(isNaN(s))return 61;var o=ke.getStreamFromFD(e);return xe.llseek(o,s,i),ue=[o.position>>>0,(le=o.position,+Math.abs(le)>=1?le>0?(0|Math.min(+Math.floor(le/4294967296),4294967295))>>>0:~~+Math.ceil((le-+(~~le>>>0))/4294967296)>>>0:0)],U[n>>>2]=ue[0],U[n+4>>>2]=ue[1],o.getdents&&0===s&&0===i&&(o.getdents=null),0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}var a,c},q:function(e,t,r,i){try{var n=function(e,t,r,i){for(var n=0,s=0;s>>2],a=W[t+4>>>2];t+=8;var c=xe.write(e,L,o,a,undefined);if(c<0)return-1;n+=c}return n}(ke.getStreamFromFD(e),t,r);return W[i>>>2]=n,0}catch(e){if(void 0===xe||!(e instanceof xe.ErrnoError))throw e;return e.errno}},pa:function(e){return function(e){var t=ur(20),r=ur(e.length+1);D(e,r,e.length+1),W[t>>>2]=r;var i=ur(4);W[i>>>2]=0,W[t+4>>>2]=i,U[t+8>>>2]=2,U[t+12>>>2]=4;var n=ur(12);return W[n>>>2]=n+8,W[n+4>>>2]=0,U[n+8>>>2]=zt(qt.lookup_name(e)),W[t+16>>>2]=n,t}(_(e))},ma:function(e,t){if(t=_(t),e=$t.programs[e]){!function(e){var t,r,i=e.uniformLocsById,n=e.uniformSizeAndIdsByName;if(!i)for(e.uniformLocsById=i={},e.uniformArrayNamesById={},t=0;t0?o.slice(0,c):o,l=e.uniformIdCounter;for(e.uniformIdCounter+=a,n[h]=[a,l],r=0;r0&&(i=jt(t.slice(s+1))>>>0,n=t.slice(0,s));var o=e.uniformSizeAndIdsByName[n];if(o&&i>>2],i[n+1]=N[r+(4*n+4)>>>2];else i=N.subarray(r>>>2,r+8*t>>>2);rr.uniform2fv(Xt(e),i)},ja:function(e,t,r){if(t<=144)for(var i=Jt[2*t-1],n=0;n<2*t;n+=2)i[n]=U[r+4*n>>>2],i[n+1]=U[r+(4*n+4)>>>2];else i=U.subarray(r>>>2,r+8*t>>>2);rr.uniform2iv(Xt(e),i)},fa:function(e,t,r){if(t<=96)for(var i=Zt[3*t-1],n=0;n<3*t;n+=3)i[n]=N[r+4*n>>>2],i[n+1]=N[r+(4*n+4)>>>2],i[n+2]=N[r+(4*n+8)>>>2];else i=N.subarray(r>>>2,r+12*t>>>2);rr.uniform3fv(Xt(e),i)},ia:function(e,t,r){if(t<=96)for(var i=Jt[3*t-1],n=0;n<3*t;n+=3)i[n]=U[r+4*n>>>2],i[n+1]=U[r+(4*n+4)>>>2],i[n+2]=U[r+(4*n+8)>>>2];else i=U.subarray(r>>>2,r+12*t>>>2);rr.uniform3iv(Xt(e),i)},ea:function(e,t,r){if(t<=72){var i=Zt[4*t-1],n=N;r>>=2;for(var s=0;s<4*t;s+=4){var o=r+s;i[s]=n[o>>>0],i[s+1]=n[o+1>>>0],i[s+2]=n[o+2>>>0],i[s+3]=n[o+3>>>0]}}else i=N.subarray(r>>>2,r+16*t>>>2);rr.uniform4fv(Xt(e),i)},ha:function(e,t,r){if(t<=72)for(var i=Jt[4*t-1],n=0;n<4*t;n+=4)i[n]=U[r+4*n>>>2],i[n+1]=U[r+(4*n+4)>>>2],i[n+2]=U[r+(4*n+8)>>>2],i[n+3]=U[r+(4*n+12)>>>2];else i=U.subarray(r>>>2,r+16*t>>>2);rr.uniform4iv(Xt(e),i)},C:function(e){},D:function(e,t,r,i){return function(e,t,r,i){var n=U[i+40>>>2],s={tm_sec:U[i>>>2],tm_min:U[i+4>>>2],tm_hour:U[i+8>>>2],tm_mday:U[i+12>>>2],tm_mon:U[i+16>>>2],tm_year:U[i+20>>>2],tm_wday:U[i+24>>>2],tm_yday:U[i+28>>>2],tm_isdst:U[i+32>>>2],tm_gmtoff:U[i+36>>>2],tm_zone:n?_(n):""},o=_(r),a={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var c in a)o=o.replace(new RegExp(c,"g"),a[c]);var h=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],l=["January","February","March","April","May","June","July","August","September","October","November","December"];function u(e,t,r){for(var i="number"==typeof e?e.toString():e||"";i.length0?1:0}var i;return 0===(i=r(e.getFullYear()-t.getFullYear()))&&0===(i=r(e.getMonth()-t.getMonth()))&&(i=r(e.getDate()-t.getDate())),i}function f(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function g(e){var t=function(e,t){for(var r=new Date(e.getTime());t>0;){var i=Qt(r.getFullYear()),n=r.getMonth(),s=(i?Kt:er)[n];if(!(t>s-r.getDate()))return r.setDate(r.getDate()+t),r;t-=s-r.getDate()+1,r.setDate(1),n<11?r.setMonth(n+1):(r.setMonth(0),r.setFullYear(r.getFullYear()+1))}return r}(new Date(e.tm_year+1900,0,1),e.tm_yday),r=new Date(t.getFullYear(),0,4),i=new Date(t.getFullYear()+1,0,4),n=f(r),s=f(i);return p(n,t)<=0?p(s,t)<=0?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var v={"%a":function(e){return h[e.tm_wday].substring(0,3)},"%A":function(e){return h[e.tm_wday]},"%b":function(e){return l[e.tm_mon].substring(0,3)},"%B":function(e){return l[e.tm_mon]},"%C":function(e){return d((e.tm_year+1900)/100|0,2)},"%d":function(e){return d(e.tm_mday,2)},"%e":function(e){return u(e.tm_mday,2," ")},"%g":function(e){return g(e).toString().substring(2)},"%G":function(e){return g(e)},"%H":function(e){return d(e.tm_hour,2)},"%I":function(e){var t=e.tm_hour;return 0==t?t=12:t>12&&(t-=12),d(t,2)},"%j":function(e){return d(e.tm_mday+function(e,t){for(var r=0,i=0;i<=t;r+=e[i++]);return r}(Qt(e.tm_year+1900)?Kt:er,e.tm_mon-1),3)},"%m":function(e){return d(e.tm_mon+1,2)},"%M":function(e){return d(e.tm_min,2)},"%n":function(){return"\n"},"%p":function(e){return e.tm_hour>=0&&e.tm_hour<12?"AM":"PM"},"%S":function(e){return d(e.tm_sec,2)},"%t":function(){return"\t"},"%u":function(e){return e.tm_wday||7},"%U":function(e){var t=e.tm_yday+7-e.tm_wday;return d(Math.floor(t/7),2)},"%V":function(e){var t=Math.floor((e.tm_yday+7-(e.tm_wday+6)%7)/7);if((e.tm_wday+371-e.tm_yday-2)%7<=2&&t++,t){if(53==t){var r=(e.tm_wday+371-e.tm_yday)%7;4==r||3==r&&Qt(e.tm_year)||(t=1)}}else{t=52;var i=(e.tm_wday+7-e.tm_yday-1)%7;(4==i||5==i&&Qt(e.tm_year%400-1))&&t++}return d(t,2)},"%w":function(e){return e.tm_wday},"%W":function(e){var t=e.tm_yday+7-(e.tm_wday+6)%7;return d(Math.floor(t/7),2)},"%y":function(e){return(e.tm_year+1900).toString().substring(2)},"%Y":function(e){return e.tm_year+1900},"%z":function(e){var t=e.tm_gmtoff,r=t>=0;return t=(t=Math.abs(t)/60)/60*100+t%60,(r?"+":"-")+String("0000"+t).slice(-4)},"%Z":function(e){return e.tm_zone},"%%":function(){return"%"}};for(var c in o=o.replace(/%%/g,"\0\0"),v)o.includes(c)&&(o=o.replace(new RegExp(c,"g"),v[c](s)));var m=cr(o=o.replace(/\0\0/g,"%"),!1);return m.length>t?0:(function(e,t){L.set(e,t>>>0)}(m,e),m.length-1)}(e,t,r,i)}},ur=(function(){var t={a:lr};function r(t,r){var i,n=t.exports;e.asm=n,Z((E=e.asm.xa).buffer),J=e.asm.Ea,i=e.asm.ya,K.unshift(i),oe()}function n(e){r(e.instance)}function o(e){return function(){if(!b&&(f||g)){if("function"==typeof fetch&&!pe(ce))return fetch(ce,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+ce+"'";return e.arrayBuffer()})).catch((function(){return fe(ce)}));if(s)return new Promise((function(e,t){s(ce,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return fe(ce)}))}().then((function(e){return WebAssembly.instantiate(e,t)})).then((function(e){return e})).then(e,(function(e){S("failed to asynchronously prepare wasm: "+e),ae(e)}))}if(se(),e.instantiateWasm)try{return e.instantiateWasm(t,r)}catch(e){return S("Module.instantiateWasm callback failed with error: "+e),!1}(b||"function"!=typeof WebAssembly.instantiateStreaming||de(ce)||pe(ce)||v||"function"!=typeof fetch?o(n):fetch(ce,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,t).then(n,(function(e){return S("wasm streaming compile failed: "+e),S("falling back to ArrayBuffer instantiation"),o(n)}))}))).catch(i)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.ya).apply(null,arguments)},e._malloc=function(){return(ur=e._malloc=e.asm.za).apply(null,arguments)}),dr=e._free=function(){return(dr=e._free=e.asm.Aa).apply(null,arguments)},pr=e.___errno_location=function(){return(pr=e.___errno_location=e.asm.Ba).apply(null,arguments)},fr=e.___getTypeName=function(){return(fr=e.___getTypeName=e.asm.Ca).apply(null,arguments)},gr=(e.___embind_register_native_and_builtin_types=function(){return(e.___embind_register_native_and_builtin_types=e.asm.Da).apply(null,arguments)},e._htons=function(){return(gr=e._htons=e.asm.Fa).apply(null,arguments)}),vr=e._emscripten_builtin_memalign=function(){return(vr=e._emscripten_builtin_memalign=e.asm.Ga).apply(null,arguments)},mr=e.___cxa_is_pointer_type=function(){return(mr=e.___cxa_is_pointer_type=e.asm.Ha).apply(null,arguments)};function yr(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function Sr(r){function i(){hr||(hr=!0,e.calledRun=!0,k||(e.noFSInit||xe.init.initialized||xe.init(),xe.ignorePermissions=!1,we.init(),ge(K),t(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),function(){if(e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;)t=e.postRun.shift(),ee.unshift(t);var t;ge(ee)}()))}r=r||u,re>0||(function(){if(e.preRun)for("function"==typeof e.preRun&&(e.preRun=[e.preRun]);e.preRun.length;)t=e.preRun.shift(),Q.unshift(t);var t;ge(Q)}(),re>0||(e.setStatus?(e.setStatus("Running..."),setTimeout((function(){setTimeout((function(){e.setStatus("")}),1),i()}),1)):i()))}if(e.dynCall_jiji=function(){return(e.dynCall_jiji=e.asm.Ia).apply(null,arguments)},e.dynCall_viijii=function(){return(e.dynCall_viijii=e.asm.Ja).apply(null,arguments)},e.dynCall_iiiiij=function(){return(e.dynCall_iiiiij=e.asm.Ka).apply(null,arguments)},e.dynCall_iiiiijj=function(){return(e.dynCall_iiiiijj=e.asm.La).apply(null,arguments)},e.dynCall_iiiiiijj=function(){return(e.dynCall_iiiiiijj=e.asm.Ma).apply(null,arguments)},e.dynCall_viiiiji=function(){return(e.dynCall_viiiiji=e.asm.Na).apply(null,arguments)},e.dynCall_viiijj=function(){return(e.dynCall_viiijj=e.asm.Oa).apply(null,arguments)},e.FS=xe,ne=function e(){hr||Sr(),hr||(ne=e)},e.run=Sr,e.preInit)for("function"==typeof e.preInit&&(e.preInit=[e.preInit]);e.preInit.length>0;)e.preInit.pop()();return Sr(),e.ready});const _e=Ae;class Oe{constructor(e){this.occ=e,this.hashesFromPreviousRun={},this.usedHashes={},this.argCache={}}cleanAllCache(){Object.keys(this.usedHashes).forEach((e=>{if(this.argCache[e])try{const t=this.argCache[e];this.occ.BRepTools.Clean(t,!0),this.occ.BRepTools.CleanGeometry(t),t.delete()}catch(e){}})),this.argCache={},this.usedHashes={},this.hashesFromPreviousRun={}}cleanCacheForHash(e){if(this.argCache[e])try{const t=this.argCache[e];this.occ.BRepTools.Clean(t,!0),this.occ.BRepTools.CleanGeometry(t),t.delete()}catch(e){}delete this.argCache[e],delete this.usedHashes[e],delete this.hashesFromPreviousRun[e]}cleanUpCache(){}isOCCTObject(e){return null!=e&&!Array.isArray(e)&&void 0!==e.$$||Array.isArray(e)&&e.length>0&&void 0!==e[0].$$}cacheOp(e,t){let r=null;const i=this.computeHash(e);this.usedHashes[i]=i,this.hashesFromPreviousRun[i]=i;const n=this.checkCache(i);if(n)this.isOCCTObject(n)?(r=n,r.hash=n.hash):n.value&&(r=n.value);else if(r=t(),Array.isArray(r)&&this.isOCCTObject(r))r.forEach(((t,r)=>{const i=this.computeHash(Object.assign(Object.assign({},e),{index:r}));t.hash=i,this.addToCache(i,t)}));else if(this.isOCCTObject(r))r.hash=i,this.addToCache(i,r);else if(r.compound&&r.data&&r.shapes&&r.shapes.length>0){const t=r,n=this.computeHash(Object.assign(Object.assign({},e),{index:"compound"}));t.compound.hash=n,this.addToCache(n,t.compound),t.shapes.forEach(((t,r)=>{const i=this.computeHash(Object.assign(Object.assign({},e),{index:r}));t.shape.hash=i,this.addToCache(i,t.shape)})),this.addToCache(i,{value:t})}else this.addToCache(i,{value:r});return r}checkCache(e){return this.argCache[e]||null}addToCache(e,t){const r=t;return r.hash=e,this.argCache[e]=r,e}computeHash(e,t){let r=JSON.stringify(e);r=r.replace(/(\"ptr\"\:(-?[0-9]*?)\,)/g,""),r=r.replace(/(\"ptr\"\:(-?[0-9]*))/g,""),r.includes("ptr")&&console.error("YOU DONE MESSED UP YOUR REGEX.");const i=Math.random.toString()+r;return t?i:this.stringToHash(i)}stringToHash(e){let t=0;if(0===e.length)return t;for(let r=0;re.hash!==t.hash||e.ptr!==t.ptr))}dupShape(e){return e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_WIRE?this.occ.TopoDS.Wire_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SHELL?this.occ.TopoDS.Shell_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_EDGE?this.occ.TopoDS.Edge_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_SOLID?this.occ.TopoDS.Solid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_FACE?this.occ.TopoDS.Face_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPOUND?this.occ.TopoDS.Compound_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_COMPSOLID?this.occ.TopoDS.CompSolid_1(e):e.ShapeType()===this.occ.TopAbs_ShapeEnum.TopAbs_VERTEX?this.occ.TopoDS.Vertex_1(e):void 0}}let De,Re,Fe;class Le{static distributeBetweenBounds(e,t,r,i=!1){const n=[];let s=r;for(i&&n.push(s);s>t;)s-=e,n.push(s);return n}static computeSideA(e,t){const r=e*Math.PI/180,i=t/Math.cos(r),n=Math.pow(i,2)-Math.pow(t,2);return Math.sqrt(n)}static computeSideAFromHypotenuseAndAngle(e,t){const r=e*Math.PI/180;return t*Math.sin(r)}static computeHypotenuse(e,t){return t/Math.cos(e*Math.PI/180)}}var Be,Me,Ie,Ue,We,Ne;!function(e){e.low="low",e.middle="middle",e.high="high"}(Be||(Be={}));class Ge{constructor(){this.lod=Be.low}}class He{}class Ve{constructor(e,t,r,i,n,s,o,a,c){this.swirl=.6,this.nrOfDivisions=10,this.addRadiusNarrow=.4,this.addRadiusWide=.2,this.addMiddleHeight=1.6,this.addTopHeight=1.5,this.thickness=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.swirl=e),void 0!==t&&(this.nrOfDivisions=t),void 0!==r&&(this.addRadiusNarrow=r),void 0!==i&&(this.addRadiusWide=i),void 0!==n&&(this.addMiddleHeight=n),void 0!==s&&(this.addTopHeight=s),void 0!==o&&(this.thickness=o),void 0!==a&&(this.rotation=a),void 0!==c&&(this.origin=c)}}class ze{constructor(){this.type="parametric-model",this.name="serenitySwirl"}}class je{}class qe{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.profilePoints=[[2,0,0],[4,5,0],[1.5,10,0],[3,14,0]],this.nrOfSides=6,this.nrOfVerticalArches=4,this.archCenterThickness=.8,this.edgesThickness=.2,this.thickness=1,this.baseHeight=.4,this.patchHoles=!0,this.lod=Be.high,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],this.scale=[1,1,1],void 0!==e&&(this.nrOfSides=e),void 0!==t&&(this.nrOfVerticalArches=t),void 0!==r&&(this.archCenterThickness=r),void 0!==i&&(this.edgesThickness=i),void 0!==n&&(this.thickness=n),void 0!==s&&(this.baseHeight=s),void 0!==o&&(this.patchHoles=o),void 0!==a&&(this.lod=a),void 0!==c&&(this.rotation=c),void 0!==h&&(this.origin=h),void 0!==l&&(this.direction=l),void 0!==u&&(this.scale=u)}}class $e{constructor(){this.type="parametric-model",this.name="arabicArchway"}}class Ye{}class Xe{}class Ze{}class Je{constructor(e,t,r,i,n,s,o,a){this.textHeading="LOVE YOU",this.textName="NORA",this.fullModel=!0,this.thickness=6,this.decorationThickness=1,this.rotation=0,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textHeading=e),void 0!==t&&(this.textName=t),void 0!==r&&(this.fullModel=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.decorationThickness=n),void 0!==s&&(this.rotation=s),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a)}}class Qe{constructor(){this.type="parametric-model",this.name="eternalLove"}}class Ke{}class et{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.height=6,this.radiusBottom=4,this.radiusTopOffset=2,this.thickness=.6,this.fillet=.2,this.nrOfHandles=1,this.handleDist=2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==r&&(this.radiusTopOffset=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.fillet=n),void 0!==s&&(this.nrOfHandles=s),void 0!==o&&(this.handleDist=o),void 0!==a&&(this.precision=a),void 0!==c&&(this.rotation=c),void 0!==h&&(this.scale=h),void 0!==l&&(this.origin=l),void 0!==u&&(this.direction=u)}}class tt{constructor(){this.type="parametric-model",this.name="calmCup"}}class rt{}class it{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y,S,b){this.height=8,this.radiusBottom=4,this.radiusTopOffset=2,this.radiusMidOffset=2,this.rotationTopAngle=20,this.rotationMidAngle=20,this.nrSkinCellsVertical=5,this.nrSkinCellsHorizontal=10,this.nrSkinCellDivisionsTop=1,this.nrSkinCellDivisionsBottom=3,this.skinCellOuterHeight=.4,this.skinCellInnerHeight=.3,this.skinCellBottomHeight=.4,this.skinCellTopHeight=.4,this.thickness=.6,this.bottomThickness=1,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.radiusBottom=t),void 0!==r&&(this.radiusTopOffset=r),void 0!==i&&(this.radiusMidOffset=i),void 0!==n&&(this.rotationTopAngle=n),void 0!==s&&(this.rotationMidAngle=s),void 0!==o&&(this.nrSkinCellsVertical=o),void 0!==a&&(this.nrSkinCellsHorizontal=a),void 0!==c&&(this.nrSkinCellDivisionsTop=c),void 0!==h&&(this.nrSkinCellDivisionsBottom=h),void 0!==l&&(this.skinCellOuterHeight=l),void 0!==u&&(this.skinCellInnerHeight=u),void 0!==d&&(this.skinCellBottomHeight=d),void 0!==p&&(this.skinCellTopHeight=p),void 0!==f&&(this.thickness=f),void 0!==g&&(this.bottomThickness=g),void 0!==v&&(this.precision=v),void 0!==m&&(this.rotation=m),void 0!==y&&(this.scale=y),void 0!==S&&(this.origin=S),void 0!==b&&(this.direction=b)}}class nt{constructor(){this.type="parametric-model",this.name="dragonCup"}}class st{}class ot{}class at{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m){this.heightBottom=5,this.heightTop=16,this.widthBack=25,this.widthFront=10,this.length=16,this.backOffset=6,this.thickness=.4,this.applyOrnaments=!1,this.filletRadius=2,this.phoneHeight=16.8,this.phoneWidth=7.8,this.phoneThickness=.7,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.heightBottom=e),void 0!==t&&(this.heightTop=t),void 0!==r&&(this.widthBack=r),void 0!==i&&(this.widthFront=i),void 0!==n&&(this.length=n),void 0!==s&&(this.backOffset=s),void 0!==o&&(this.thickness=o),void 0!==a&&(this.applyOrnaments=a),void 0!==c&&(this.filletRadius=c),void 0!==h&&(this.phoneHeight=h),void 0!==l&&(this.phoneWidth=l),void 0!==u&&(this.phoneThickness=u),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdges=p),void 0!==f&&(this.rotation=f),void 0!==g&&(this.scale=g),void 0!==v&&(this.origin=v),void 0!==m&&(this.direction=m)}}class ct{constructor(){this.type="parametric-model",this.name="phoneNest"}}class ht extends He{}class lt{}class ut extends He{}class dt{}class pt{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class ft{}class gt{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y){this.textTop="Pepper",this.textFront="For Your Spicy Needs",this.nrSides=4,this.nrOffsets=1,this.height=6,this.radiusBase=4,this.radiusOffset=2,this.coverHeight=1,this.baseHeight=1,this.thickness=.6,this.ornamentalThickness=.1,this.nrOrnamnetsPerSide=10,this.invertOrnaments=!1,this.fillet=.2,this.precision=.01,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.textTop=e),void 0!==t&&(this.textFront=t),void 0!==r&&(this.nrSides=r),void 0!==i&&(this.nrOffsets=i),void 0!==n&&(this.height=n),void 0!==s&&(this.coverHeight=s),void 0!==o&&(this.baseHeight=o),void 0!==a&&(this.radiusBase=a),void 0!==c&&(this.radiusOffset=c),void 0!==h&&(this.thickness=h),void 0!==l&&(this.ornamentalThickness=l),void 0!==u&&(this.nrOrnamnetsPerSide=u),void 0!==d&&(this.invertOrnaments=d),void 0!==p&&(this.fillet=p),void 0!==f&&(this.precision=f),void 0!==g&&(this.rotation=g),void 0!==v&&(this.scale=v),void 0!==m&&(this.origin=m),void 0!==y&&(this.direction=y)}}class vt{constructor(){this.type="parametric-model",this.name="spicyBox"}}class mt{}class yt{}class St{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m,y,S,b,w,E,T,x,k,P,C,A,_){this.widthFirstWing=4,this.lengthFirstWing=10,this.terraceWidth=3,this.widthSecondWing=5,this.lengthSecondWing=10,this.heightWalls=3,this.roofAngleFirstWing=15,this.roofAngleSecondWing=25,this.roofOffset=.5,this.roofInsideOverhang=.5,this.roofMaxDistAttachmentBeams=.8,this.roofAttachmentBeamWidth=.2,this.roofAttachmentBeamHeight=.05,this.roofOutsideOverhang=.5,this.columnSize=.3,this.ceilingBeamHeight=.25,this.ceilingBeamWidth=.1,this.nrCeilingBeamsBetweenColumns=3,this.distBetweenColumns=2,this.floorHeight=.1,this.groundLevel=.6,this.facadePanelThickness=.05,this.windowWidthOffset=.1,this.windowHeightOffset=.2,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05,this.lod=Be.high,this.skinOpacity=1,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.widthFirstWing=e),void 0!==t&&(this.lengthFirstWing=t),void 0!==r&&(this.terraceWidth=r),void 0!==i&&(this.widthSecondWing=i),void 0!==n&&(this.lengthSecondWing=n),void 0!==s&&(this.heightWalls=s),void 0!==o&&(this.roofAngleFirstWing=o),void 0!==a&&(this.roofAngleSecondWing=a),void 0!==c&&(this.roofOffset=c),void 0!==h&&(this.roofInsideOverhang=h),void 0!==l&&(this.roofMaxDistAttachmentBeams=l),void 0!==u&&(this.roofAttachmentBeamWidth=u),void 0!==d&&(this.roofAttachmentBeamHeight=d),void 0!==p&&(this.roofOutsideOverhang=p),void 0!==f&&(this.columnSize=f),void 0!==g&&(this.ceilingBeamHeight=g),void 0!==v&&(this.ceilingBeamWidth=v),void 0!==m&&(this.nrCeilingBeamsBetweenColumns=m),void 0!==y&&(this.distBetweenColumns=y),void 0!==S&&(this.floorHeight=S),void 0!==b&&(this.groundLevel=b),void 0!==w&&(this.facadePanelThickness=w),void 0!==E&&(this.windowWidthOffset=E),void 0!==T&&(this.windowHeightOffset=T),void 0!==x&&(this.windowFrameThickness=x),void 0!==k&&(this.windowGlassFrameThickness=k),void 0!==P&&(this.lod=P),void 0!==C&&(this.skinOpacity=C),void 0!==A&&(this.rotation=A),void 0!==_&&(this.origin=_)}}class bt{constructor(){this.type="parametric-model",this.name="zenHideout"}}class wt{}class Et{}class Tt{constructor(){this.wallThickness=.4,this.facadePanelThickness=.05,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThckness=.05,this.height=3,this.lengthFirst=1,this.lengthSecond=2,this.rotation=0}}class xt{constructor(){this.thickness=.3,this.glassFrameThickness=.02,this.glassThickness=.005,this.frameThickness=.05,this.height=3,this.width=1,this.rotation=0,this.center=[0,0,0],this.direction=[0,1,0]}}class kt extends xt{}class Pt extends Tt{}class Ct{constructor(){this.name="sandwitch-panel",this.createWindow=!0,this.createInnerPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelWidth=.4,this.exteriorPanelHeight=3,this.exteriorPanelThickness=.05,this.exteriorPanelBottomOffset=0,this.interiorPanelWidth=.4,this.interiorPanelHeight=3,this.interiorPanelThickness=.05,this.interiorPanelBottomOffset=0,this.windowWidthOffset=0,this.windowHeightOffset=0,this.windowFrameThickness=.1,this.windowGlassFrameThickness=.05}}class At{constructor(){this.name="sandwitch-panel-flex",this.createInteriorPanel=!0,this.createExteriorPanel=!0,this.wallWidth=.3,this.exteriorPanelThickness=.05,this.interiorPanelThickness=.05,this.interiorPanelPolygonPoints=[],this.exteriorPanelPolygonPoints=[]}}class _t extends Ct{}class Ot extends At{}class Dt{}class Rt{}class Ft{}class Lt{}class Bt{}class Mt{}class It{constructor(){this.invert=!1,this.widthFirstLanding=1,this.widthSecondLanding=1,this.lengthFirstWing=2,this.lengthSecondWing=1,this.maxWishedStepHeight=.25,this.stepHeightWidthProportion=1.35,this.totalHeight=1,this.rotation=0,this.origin=[0,0,0]}}class Ut extends It{}class Wt{}class Nt{constructor(){this.name="roof-cover",this.roofAngle=15,this.roofLength=3,this.roofWidth=3,this.roofOutsideOverhang=.5,this.roofInsideOverhang=1,this.roofOverhangFacade=.1,this.roofThickness=.05,this.roofCoverHeight=.3,this.rotation=0,this.lod=Be.high,this.center=[0,0,0],this.direction=[0,1,0]}}class Gt extends Nt{}class Ht{}class Vt{}class zt{constructor(){this.widthFirstWing=1,this.widthSecondWing=2,this.lengthStairFirstWing=2,this.lengthStairSecondWing=1,this.lengthWallFirstWing=2,this.lengthWallSecondWing=1,this.facadePanelThickness=.05,this.wallThickness=3,this.wallHeightExterior=3,this.wallHeightInterior=3,this.windowFrameOffsetTop=.3,this.windowFrameThickness=.1,this.glassFrameThickness=.05,this.doorWidth=1,this.windowWidthOffset=.3,this.stairTotalHeight=1,this.createStair=!1,this.flipDirection=!1,this.rotation=0,this.origin=[0,0,0]}}class jt{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.5,this.holeDiameter=1.5,this.holeDistToBottom=2.5,this.stickLength=1.2,this.stickDiameter=.5,this.baseAttachmentHeight=2,this.roofOverhang=1,this.rotation=0,this.chimneyHeight=1,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==r&&(this.interiorHeight=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.holeDiameter=n),void 0!==s&&(this.holeDistToBottom=s),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==c&&(this.baseAttachmentHeight=c),void 0!==h&&(this.roofOverhang=h),void 0!==l&&(this.rotation=l),void 0!==u&&(this.chimneyHeight=u),void 0!==d&&(this.origin=d)}}class qt{constructor(){this.type="parametric-model",this.name="wingtipVilla"}}class $t{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d){this.interiorWidth=3,this.interiorLength=3,this.interiorHeight=5,this.thickness=.3,this.holeDiameter=1.2,this.holeDistToBottom=2.5,this.stickLength=.9,this.stickDiameter=.3,this.baseAttachmentHeight=2,this.roofOverhang=.5,this.roofAngle=20,this.rotation=0,this.origin=[0,0,0],void 0!==e&&(this.interiorWidth=e),void 0!==t&&(this.interiorLength=t),void 0!==r&&(this.interiorHeight=r),void 0!==i&&(this.thickness=i),void 0!==n&&(this.holeDiameter=n),void 0!==s&&(this.holeDistToBottom=s),void 0!==o&&(this.stickLength=o),void 0!==a&&(this.stickDiameter=a),void 0!==c&&(this.baseAttachmentHeight=c),void 0!==h&&(this.roofOverhang=h),void 0!==l&&(this.roofAngle=l),void 0!==u&&(this.rotation=u),void 0!==d&&(this.origin=d)}}class Yt{constructor(){this.type="parametric-model",this.name="chirpyChalet"}}class Xt{}class Zt{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f){this.sittingHeight=.45,this.backRestOffset=.1,this.backRestHeight=.7,this.width=.45,this.length=.45,this.thickness=.05,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.sittingHeight=e),void 0!==t&&(this.backRestOffset=t),void 0!==r&&(this.backRestHeight=r),void 0!==i&&(this.width=i),void 0!==n&&(this.length=n),void 0!==s&&(this.thickness=s),void 0!==o&&(this.nrOrnamentPlanks=o),void 0!==a&&(this.ornamentDepth=a),void 0!==c&&(this.filletRadius=c),void 0!==h&&(this.precision=h),void 0!==l&&(this.drawEdges=l),void 0!==u&&(this.rotation=u),void 0!==d&&(this.scale=d),void 0!==p&&(this.origin=p),void 0!==f&&(this.direction=f)}}class Jt{constructor(){this.type="parametric-model",this.name="snakeChair"}}class Qt extends He{}class Kt{}class er extends He{}class tr{}class rr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class ir{}class nr{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g){this.height=.74,this.width=1,this.length=2,this.topThickness=.02,this.topOffset=.03,this.bottomThickness=.05,this.minFillet=.2,this.radiusLegTop=.03,this.radiusLegBottom=.01,this.nrLegPairs=2,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==r&&(this.length=r),void 0!==i&&(this.topThickness=i),void 0!==n&&(this.topOffset=n),void 0!==s&&(this.bottomThickness=s),void 0!==o&&(this.minFillet=o),void 0!==a&&(this.radiusLegTop=a),void 0!==c&&(this.radiusLegBottom=c),void 0!==h&&(this.nrLegPairs=h),void 0!==l&&(this.precision=l),void 0!==u&&(this.drawEdges=u),void 0!==d&&(this.rotation=d),void 0!==p&&(this.scale=p),void 0!==f&&(this.origin=f),void 0!==g&&(this.direction=g)}}class sr{constructor(){this.type="parametric-model",this.name="elegantTable"}}class or extends He{}class ar{}class cr extends He{}class hr extends He{}class lr{constructor(){this.index=0}}class ur{}class dr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class pr{}class fr{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v,m){this.height=.4,this.width=1,this.length=1.2,this.chamfer=.01,this.topThickness=.05,this.topGlassOffset=.2,this.glassThickness=.005,this.glassHolderLength=.02,this.shelfTopOffset=.15,this.shelfThickness=.03,this.legWidth=.1,this.legDepth=.05,this.precision=.001,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==r&&(this.length=r),void 0!==i&&(this.chamfer=i),void 0!==n&&(this.topThickness=n),void 0!==s&&(this.topGlassOffset=s),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassHolderLength=a),void 0!==c&&(this.shelfTopOffset=c),void 0!==h&&(this.shelfThickness=h),void 0!==l&&(this.legWidth=l),void 0!==u&&(this.legDepth=u),void 0!==d&&(this.precision=d),void 0!==p&&(this.drawEdges=p),void 0!==f&&(this.rotation=f),void 0!==g&&(this.scale=g),void 0!==v&&(this.origin=v),void 0!==m&&(this.direction=m)}}class gr{constructor(){this.type="parametric-model",this.name="goodCoffeeTable"}}class vr extends He{}class mr{}class yr extends He{}class Sr extends He{}class br extends He{}class wr{constructor(){this.index=0}}class Er{}class Tr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}class xr{}class kr{constructor(e,t,r,i,n,s,o,a,c,h,l,u,d,p,f,g,v){this.height=.74,this.width=1,this.length=2,this.supportLength=.5,this.shelfHeight=.2,this.thickness=.05,this.glassThickness=.005,this.glassOffset=0,this.nrOrnamentPlanks=7,this.ornamentDepth=.01,this.filletRadius=.05,this.precision=.01,this.drawEdges=!0,this.rotation=0,this.scale=1,this.origin=[0,0,0],this.direction=[0,1,0],void 0!==e&&(this.height=e),void 0!==t&&(this.width=t),void 0!==r&&(this.length=r),void 0!==i&&(this.supportLength=i),void 0!==n&&(this.shelfHeight=n),void 0!==s&&(this.thickness=s),void 0!==o&&(this.glassThickness=o),void 0!==a&&(this.glassOffset=a),void 0!==c&&(this.nrOrnamentPlanks=c),void 0!==h&&(this.ornamentDepth=h),void 0!==l&&(this.filletRadius=l),void 0!==u&&(this.precision=u),void 0!==d&&(this.drawEdges=d),void 0!==p&&(this.rotation=p),void 0!==f&&(this.scale=f),void 0!==g&&(this.origin=g),void 0!==v&&(this.direction=v)}}class Pr{constructor(){this.type="parametric-model",this.name="snakeTable"}}class Cr extends He{}class Ar{}class _r extends He{}class Or{}class Dr{constructor(){this.drawFaces=!0,this.precision=.001,this.drawEdges=!0,this.edgeColour="#ffffff",this.edgeWidth=.06}}!function(e){e.Aboreto="Aboreto",e.Bungee="Bungee",e.IndieFlower="IndieFlower",e.Lugrasimo="Lugrasimo",e.Orbitron="Orbitron",e.Roboto="Roboto",e.RobotoSlab="RobotoSlab",e.Silkscreen="Silkscreen",e.Tektur="Tektur",e.Workbench="Workbench"}(Me||(Me={})),function(e){e.Regular="Regular",e.Black="Black",e.Bold="Bold",e.ExtraBold="ExtraBold",e.Medium="Medium",e.SemiBold="SemiBold",e.BlackItalic="BlackItalic",e.BoldItalic="BoldItalic",e.Italic="Italic",e.Light="Light",e.LightItalic="LightItalic",e.MediumItalic="MediumItalic",e.Thin="Thin",e.ThinItalic="ThinItalic",e.ExtraLight="ExtraLight"}(Ie||(Ie={})),function(e){e.separatedExtrusion="separatedExtrusion",e.integratedExtrusion="integratedExtrusion",e.cutout="cutout"}(Ue||(Ue={})),function(e){e.compound="compound",e.cutout="originalCutout",e.cutoutInsideCharacter="cutoutInsideCharacter"}(We||(We={})),function(e){e.leftTop="leftTop",e.leftMiddle="leftMiddle",e.leftBottom="leftBottom",e.centerTop="centerTop",e.centerMiddle="centerMiddle",e.centerBottom="centerBottom",e.rightTop="rightTop",e.rightMiddle="rightMiddle",e.rightBottom="rightBottom"}(Ne||(Ne={}));const Rr=[{key:"Aboreto",variants:["Regular"]},{key:"Bungee",variants:["Regular"]},{key:"IndieFlower",variants:["Regular"]},{key:"Lugrasimo",variants:["Regular"]},{key:"Orbitron",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Roboto",variants:["Black","BlackItalic","Bold","BoldItalic","Italic","Light","LightItalic","Medium","MediumItalic","Regular","Thin","ThinItalic"]},{key:"RobotoSlab",variants:["Black","Bold","ExtraBold","ExtraLight","Light","Medium","Regular","SemiBold","Thin"]},{key:"Silkscreen",variants:["Bold","Regular"]},{key:"Tektur",variants:["Black","Bold","ExtraBold","Medium","Regular","SemiBold"]},{key:"Workbench",variants:["Regular"]}];class Fr{constructor(e,t,r,i,n,s,o,a,c){this.text="bitbybit.dev",this.fontType=Me.Roboto,this.fontVariant=Ie.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.origin=[0,0,0],this.direction=[0,1,0],this.originAlignment=Ne.centerMiddle,void 0!==e&&(this.text=e),void 0!==t&&(this.fontType=t),void 0!==r&&(this.fontVariant=r),void 0!==i&&(this.fontSize=i),void 0!==n&&(this.height=n),void 0!==s&&(this.rotation=s),void 0!==o&&(this.origin=o),void 0!==a&&(this.direction=a),void 0!==c&&(this.originAlignment=c)}}class Lr{constructor(e,t,r,i,n,s,o,a,c,h,l,u){this.facePlanar=!1,this.faceTextVar=Ue.separatedExtrusion,this.text="bitbybit.dev",this.fontType=Me.Roboto,this.fontVariant=Ie.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=Ne.centerMiddle,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==r&&(this.faceTextVar=r),void 0!==i&&(this.text=i),void 0!==n&&(this.fontType=n),void 0!==s&&(this.fontVariant=s),void 0!==o&&(this.fontSize=o),void 0!==a&&(this.height=a),void 0!==c&&(this.rotation=c),void 0!==h&&(this.originParamU=h),void 0!==l&&(this.originParamV=l),void 0!==u&&(this.originAlignment=u)}}class Br{constructor(){this.type="parametric-model",this.name="text3d"}}class Mr{constructor(){this.index=0}}class Ir{}class Ur{}class Wr{constructor(e,t,r,i,n,s,o,a,c,h){this.faceTextVar=Ue.separatedExtrusion,this.text="bitbybit.dev",this.fontType=Me.Roboto,this.fontVariant=Ie.Regular,this.fontSize=1.5,this.height=.2,this.rotation=180,this.originParamU=.5,this.originParamV=.5,this.originAlignment=Ne.centerMiddle,void 0!==e&&(this.faceTextVar=e),void 0!==t&&(this.text=t),void 0!==r&&(this.fontType=r),void 0!==i&&(this.fontVariant=i),void 0!==n&&(this.fontSize=n),void 0!==s&&(this.height=s),void 0!==o&&(this.rotation=o),void 0!==a&&(this.originParamU=a),void 0!==c&&(this.originParamV=c),void 0!==h&&(this.originAlignment=h)}}class Nr{constructor(e,t,r){this.facePlanar=!1,void 0!==e&&(this.face=e),void 0!==t&&(this.facePlanar=t),void 0!==r&&(this.definitions=r)}}class Gr{constructor(e,t,r,i){this.uNumber=10,this.vNumber=10,this.height=.2,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==i&&(this.height=i)}}class Hr{constructor(e,t,r,i,n,s,o){this.uNumber=10,this.vNumber=5,this.defaultHeight=.2,this.affectMinHeight=0,this.affectMaxHeight=1,this.precision=.01,void 0!==e&&(this.faces=e),void 0!==t&&(this.affectorPoints=t),void 0!==r&&(this.uNumber=r),void 0!==i&&(this.vNumber=i),void 0!==n&&(this.affectMinHeight=n),void 0!==s&&(this.affectMaxHeight=s),void 0!==o&&(this.precision=o)}}class Vr{constructor(){this.type="parametric-model",this.name="patternsFacePatternPyramidSimple"}}class zr{constructor(){this.index=0}}class jr{}class qr{}class $r{}class Yr{}class Xr{constructor(){this.faceIndex=0}}class Zr{constructor(){this.faceIndex=0,this.uIndex=0,this.vIndex=0}}class Jr{constructor(){this.faceIndex=0,this.uIndex=0}}class Qr{constructor(){this.faceIndex=0,this.vIndex=0}}class Kr{}class ei{}var ti,ri,ii;!function(e){e.wire="wire",e.face="face",e.solid="solid"}(ti||(ti={}));class ni{static parse(e,t,r){const i=[e];let n=0;for(;i.length>0;){const e=i.pop();if("object"==typeof e&&null!==e)if(Array.isArray(e))for(let t=0;t{const a=o.shapes[e];if(a){const c=t.transforms.rotate({shape:a,angle:r,axis:[0,1,0]}),h=t.transforms.alignAndTranslate({shape:c,direction:i,center:n});1!==s[0]||1!==s[1]||1!==s[2]?(o.shapes[e]=t.transforms.scale3d({shape:h,scale:s,center:n}),h.delete()):o.shapes[e]=h,c.delete()}})),Object.keys(o).forEach((e=>{const a=o[e];a&&Array.isArray(a)?o[e]=a.map((e=>e&&"object"==typeof e&&null!==e&&e.shapes?this.alignAndTranslateShapesWithChildren(e,t,r,i,n,s):e)):a&&"object"==typeof a&&null!==a&&a.shapes&&(o[e]=this.alignAndTranslateShapesWithChildren(a,t,r,i,n,s))})),o}static deleteAllShapes(e){Object.keys(e.shapes).forEach((t=>{e.shapes[t].delete()})),Object.keys(e).forEach((t=>{const r=e[t];r&&Array.isArray(r)?r.forEach((e=>{e&&"object"==typeof e&&null!==e&&e.shapes&&this.deleteAllShapes(e)})):r&&"object"==typeof r&&null!==r&&r.shapes&&this.deleteAllShapes(r)}))}static deepCopy(e){const t=Object.assign(Object.assign({},e),{shapes:Object.assign({},e.shapes)});return Object.keys(e).forEach((r=>{const i=e[r];i&&"object"==typeof i&&null!==i?i.shapes&&(t[r]=this.deepCopy(i)):i&&Array.isArray(i)&&(t[r]=i.map((e=>e&&"object"==typeof e&&null!==e&&e.shapes?this.deepCopy(e):e)))})),t}}class si{constructor(e,t,r){this.occtService=e,this.dependencies=r,this.occtAdv=t}wingtipVilla(e){return function(e,t){!function(e){let t;if(["interiorWidth","interiorLength","interiorHeight","chimneyHeight","roofOverhang","thickness","holeDiameter","holeDistToBottom","stickDiameter","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.interiorWidth<=0?t=`interior width can't be ${e.interiorWidth}, which is lower or equal to 0`:e.interiorLength<=0?t=`interior length can't be ${e.interiorLength}, which is lower or equal to 0`:e.interiorHeight<=0?t=`interior height can't be ${e.interiorHeight}, which is lower or equal to 0`:e.chimneyHeight<=0?t=`chimney height can't be ${e.chimneyHeight}, which is lower or equal to 0`:e.interiorWidthe.holeDistToBottom&&(t="The stick diameter is larger than the hole's distance to bottom. Stick can't fit the surface. Model can't be made."),t)throw new Error(t)}(e);const r=e.baseAttachmentHeight,i=e.roofOverhang,n=e.chimneyHeight,s=(e.interiorWidth+2*e.thickness)/2,o=Le.computeSideA(45,s),a=function(e,t){const r=Math.pow(e,2)+Math.pow(t,2);return Math.sqrt(r)}(o,s),c=e.thickness,h=[],l=t.shapes.wire.createPolygonWire({points:[[-s,-r-c,0],[s,-r-c,0],[s,e.interiorHeight,0],[0,e.interiorHeight+o,0],[-s,e.interiorHeight,0]].reverse()});h.push(l);const u=e.interiorLength+e.thickness,d=t.shapes.wire.createPolygonWire({points:[[-s,-c,u],[s,-c,u],[s,e.interiorHeight,u],[0,e.interiorHeight+o,u],[-s,e.interiorHeight,u]].reverse()});h.push(d);const p=t.shapes.wire.createCircleWire({radius:e.holeDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom+e.holeDiameter/2,u]});h.push(p);const f=t.shapes.wire.createCircleWire({radius:e.stickDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom/2,u+c]});h.push(f);const g=t.shapes.face.createFaceFromWire({shape:f,planar:!0});h.push(g);const v=t.operations.extrude({shape:g,direction:[0,0,e.stickLength]}),m=t.shapes.solid.createBoxFromCorner({corner:[-s+c,-c,c],width:e.interiorWidth,length:e.interiorLength,height:c}),y=t.shapes.solid.createBoxFromCorner({corner:[-s,-c,c],width:c,length:e.interiorLength,height:e.interiorHeight+c}),S=t.shapes.solid.createBoxFromCorner({corner:[s-c,-c,c],width:c,length:e.interiorLength,height:e.interiorHeight+c}),b=t.shapes.solid.createBoxFromCorner({corner:[0,0,0],width:a+i,length:e.interiorLength+2*c+i,height:c}),w=t.shapes.solid.createBoxFromCorner({corner:[0,-c,0],width:a+i+c,length:e.interiorLength+2*c+i,height:c}),E=t.transforms.rotate({shape:b,angle:-45,axis:[0,0,1]});h.push(E);const T=t.transforms.translate({shape:E,translation:[0,e.interiorHeight+o,0]}),x=t.shapes.edge.getCornerPointsOfEdgesForShape({shape:T}),k=t.transforms.rotate({shape:w,angle:225,axis:[0,0,1]});h.push(k);const P=t.transforms.translate({shape:k,translation:x[3]}),C=t.shapes.face.createFaceFromWire({shape:l,planar:!0});h.push(C);const A=t.operations.makeThickSolidSimple({shape:C,offset:-e.thickness}),_=t.shapes.face.createFaceFromWire({shape:d,planar:!0});h.push(_);const O=t.operations.splitShapeWithShapes({shape:_,shapes:[p]});h.push(O);const D=t.shapes.face.getFace({shape:O,index:0});h.push(D);const R=t.operations.makeThickSolidSimple({shape:D,offset:-e.thickness}),F=function(e,t,r){const i=e.shapes.face.getFaces({shape:t})[3],n=e.shapes.face.getFaceCenterOfMass({shape:i}),s=e.transforms.scale3d({shape:i,scale:[.3,.3,.3],center:n}),o=e.shapes.edge.getCornerPointsOfEdgesForShape({shape:s}),a=o[0],c=o[1],h=o[2],l=o[3],u=Math.max(a[1],c[1],h[1],l[1]),d=[a[0],u+r,a[2]],p=[c[0],u+r,c[2]],f=[h[0],u+r,h[2]],g=[l[0],u+r,l[2]],v=e.shapes.wire.createPolygonWire({points:[a,c,h,l]}),m=e.shapes.wire.createPolygonWire({points:[d,p,f,g]}),y=e.operations.loft({shapes:[v,m],makeSolid:!0});return i.delete(),s.delete(),v.delete(),m.delete(),y}(t,T,n),L=[m,A,R,y,S,T,P,v,t.shapes.compound.makeCompound({shapes:[T,P]}),t.shapes.compound.makeCompound({shapes:[A,R,y,S]}),F],B=L.map(((r,i)=>{const n=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]});return t.transforms.translate({shape:n,translation:e.origin})})),M=t.shapes.compound.makeCompound({shapes:B});return L.forEach((e=>e.delete())),h.forEach((e=>e.delete())),{compound:M,shapes:B.map(((e,t)=>({id:t.toString(),shape:e}))),data:{type:"parametric-model",name:"wingtipVilla",roof:{compound:"8",shapes:["5","6"]},walls:{compound:"9",shapes:["1","2","3","4"]},floor:{shape:"0"},stick:{shape:"7"},chimney:{shape:"10"},basicPoints:[{kind:"origin",point:e.origin}]}}}(e,this.occtService)}chirpyChalet(e){return function(e,t){!function(e){let t;if(["interiorWidth","interiorLength","interiorHeight","roofAngle","roofOverhang","thickness","holeDiameter","holeDistToBottom","stickDiameter","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.interiorWidth<=0?t=`interior width can't be ${e.interiorWidth}, which is lower or equal to 0`:e.interiorLength<=0?t=`interior length can't be ${e.interiorLength}, which is lower or equal to 0`:e.interiorHeight<=0?t=`interior height can't be ${e.interiorHeight}, which is lower or equal to 0`:e.interiorWidthe.holeDistToBottom&&(t="The stick diameter is larger than the hole's distance to bottom. Stick can't fit the surface. Model can't be made."),t)throw new Error(t)}(e);const r=e.baseAttachmentHeight,i=e.roofOverhang,n=e.roofAngle,s=e.interiorWidth/2,o=e.interiorLength+2*e.thickness,a=Le.computeSideA(n,o),c=Le.computeSideA(n,o-e.thickness),h=function(e,t){const r=Math.pow(e,2)+Math.pow(t,2);return Math.sqrt(r)}(a,o),l=e.thickness,u=[],d=t.shapes.wire.createPolygonWire({points:[[-s,-r-l,0],[s,-r-l,0],[s,e.interiorHeight+c,0],[-s,e.interiorHeight+c,0]].reverse()});u.push(d);const p=e.interiorLength+e.thickness,f=t.shapes.wire.createPolygonWire({points:[[-s,-l,p],[s,-l,p],[s,e.interiorHeight,p],[-s,e.interiorHeight,p]].reverse()});u.push(f);const g=t.shapes.wire.createCircleWire({radius:e.holeDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom+e.holeDiameter/2,p]});u.push(g);const v=t.shapes.wire.createCircleWire({radius:e.stickDiameter/2,direction:[0,0,1],center:[0,e.holeDistToBottom/2,p+l]});u.push(v);const m=t.shapes.face.createFaceFromWire({shape:v,planar:!0});u.push(m);const y=t.operations.extrude({shape:m,direction:[0,0,e.stickLength]}),S=t.shapes.solid.createBoxFromCorner({corner:[-s,-l,l],width:e.interiorWidth,length:e.interiorLength,height:l}),b=t.shapes.wire.createPolygonWire({points:[[-s,-l,0],[-s,-l,p+l],[-s,e.interiorHeight,p+l],[-s,e.interiorHeight+a,0]].reverse()}),w=t.shapes.face.createFaceFromWire({shape:b,planar:!0}),E=t.operations.extrude({shape:w,direction:[-l,0,0]}),T=t.transforms.translate({shape:E,translation:[e.interiorWidth+l,0,0]}),x=t.shapes.solid.createBoxFromCorner({corner:[-s-l-i,0,0],width:e.interiorWidth+2*l+2*i,length:h+i,height:l}),k=t.transforms.rotate({shape:x,angle:n,axis:[1,0,0]});u.push(k);const P=t.transforms.translate({shape:k,translation:[0,e.interiorHeight+a,0]}),C=t.shapes.face.createFaceFromWire({shape:d,planar:!0});u.push(C);const A=t.operations.makeThickSolidSimple({shape:C,offset:-e.thickness}),_=t.shapes.face.createFaceFromWire({shape:f,planar:!0});u.push(_);const O=t.operations.splitShapeWithShapes({shape:_,shapes:[g]});u.push(O);const D=t.shapes.face.getFace({shape:O,index:0});u.push(D);const R=t.operations.makeThickSolidSimple({shape:D,offset:-e.thickness}),F=[S,A,R,E,T,P,y,t.shapes.compound.makeCompound({shapes:[P]}),t.shapes.compound.makeCompound({shapes:[A,R,E,T]})],L=F.map(((r,i)=>{const n=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]});return t.transforms.translate({shape:n,translation:e.origin})})),B=t.shapes.compound.makeCompound({shapes:L});return F.forEach((e=>e.delete())),u.forEach((e=>e.delete())),{compound:B,shapes:L.map(((e,t)=>({id:t.toString(),shape:e}))),data:{type:"parametric-model",name:"chirpyChalet",roof:{compound:"7",shapes:["5","6"]},walls:{compound:"8",shapes:["1","2","3","4"]},floor:{shape:"0"},stick:{shape:"6"},basicPoints:[{kind:"origin",point:e.origin}]}}}(e,this.occtService)}serenitySwirl(t){return function(t,r,i){if(function(e){let t;if(["swirl","nrOfDivisions","addRadiusNarrow","addRadiusWide","addMiddleHeight","addTopHeight","thickness","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.swirl<0?t="swirl value should be between 0 and 1":e.nrOfDivisions<=0?t=`nrOfDivisions can't be ${e.nrOfDivisions}, which is lower or equal to 0`:e.addRadiusNarrow<0?t=`addRadiusNarrow can't be ${e.addRadiusNarrow}, which is lower then 0`:e.addRadiusWide<0?t=`addRadiusWide can't be ${e.addRadiusWide}, which is lower then 0`:e.addMiddleHeight<=0?t=`addMiddleHeight can't be ${e.addMiddleHeight}, which is lower or equal to 0`:e.addTopHeight<=0?t=`addTopHeight can't be ${e.addTopHeight}, which is lower or equal to 0`:e.thickness<=0?t=`thickness can't be ${e.thickness}, which is lower or equal to 0`:3!==e.origin.length&&(t="The origin should be a vector of 3 numbers."),t)throw new Error(t)}(t),!i.serenitySwirl)throw new Error("Could not compute, to use Serenity Swirl algorithm you must be subscribed.");try{const n=`\n ${i.serenitySwirl}\n `;return new Function(n).apply({inputs:t,occt:r,Inputs:e})}catch(e){throw new Error(e)}}(t,this.occtService,this.dependencies)}arabicArchway(t){return function(t,r,i){if(function(e){let t;if(["nrOfSides","thickness","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),e.nrOfSides<0?t="swirl value should be between 0 and 1":e.nrOfSides<3?t=`nrOfSides can't be ${e.nrOfSides}, which is lower to 3`:e.nrOfSides>30?t=`nrOfSides can't be ${e.nrOfSides}, which is higher then 30`:e.thickness<=0?t=`thickness can't be ${e.thickness}, which is lower or equal to 0`:3!==e.origin.length&&(t="The origin should be a vector of 3 numbers."),t)throw new Error(t)}(t),!i.arabicArchway)throw new Error("Could not compute, to use Arabic Archway algorithm you must be subscribed.");try{const n=`\n ${i.arabicArchway}\n `;return new Function(n).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.dependencies)}eternalLove(t){return function(t,r,i,n){if(!n.eternalLove)throw new Error("Could not compute, to use Eternal Love algorithm you must be subscribed to our silver plan.");try{const s=`\n ${n.eternalLove}\n `;return new Function(s).apply({inputs:t,occt:r,occtAdv:i,Inputs:e,Text3D:R})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}calmCup(t){return function(t,r,i,n){if(function(e){let t;if(["height","radiusBottom","radiusTopOffset","thickness","fillet","nrOfHandles","handleDist","precision","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.height<6*e.thickness?t="Height must be at least 6 times greater than thickness.":e.radiusBottom<=0?t="Radius bottom must be greater than 0.":e.thickness<=0?t="Thickness must be greater than 0.":e.fillet<0||e.fillet>e.thickness/2?t="Fillet must be greater than 0 and less than half of the thickness.":e.handleDist<=2*e.thickness?t="Handle distance from cup must be greater than 2 times the thickness.":e.nrOfHandles<0||e.nrOfHandles>2?t="Nr of handles must be between 0 and 2.":e.radiusTopOffset>.75*e.radiusBottom&&(t="Top offset radius must be less than 0.75 times the bottom radius."),t)throw new Error(t)}(t),!n.calmCup)throw new Error("Could not compute, to use Calm Cup algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.calmCup}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}spicyBox(t){return function(t,r,i,n){if(!n.spicyBox)throw new Error("Could not compute, to use Spicy Box algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.spicyBox}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}dragonCup(t){return function(t,r,i,n){if(function(e){let t;if(["height","radiusBottom","radiusTopOffset","thickness","nrSkinCellsHorizontal","nrSkinCellsVertical","precision","rotation"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.radiusBottom<=0?t="Radius bottom must be greater than 0.":e.thickness<=0?t="Thickness must be greater than 0.":e.nrSkinCellsHorizontal<=2?t="Nr of horizontal skin cells must be larger than 2.":e.nrSkinCellsVertical<1&&(t="Nr of horizontal skin cells must be larger than 0."),t)throw new Error(t)}(t),!n.dragonCup)throw new Error("Could not compute, to use Dragon Cup algorithm you must be subscribed to our silver plan.");try{const s=`\n ${n.dragonCup}\n `;return new Function(s).apply({inputs:t,occt:r,occtAdv:i,Inputs:e,Advanced:G})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}zenHideout(t){return function(t,r,i){if(function(e){let t;if([].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number`)})),t)throw new Error(t)}(t),!i.zenHideout)throw new Error("Could not compute, to use Zen Hideout algorithm you must be subscribed.");try{const n=`\n ${i.zenHideout}\n `;return new Function(n).apply({inputs:t,occt:r,Inputs:e,Things:D,MathHelper:Le,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.dependencies)}elegantTable(t){return function(t,r,i,n){if(!n.elegantTable)throw new Error("Could not compute, to use Elegant Table algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.elegantTable}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}goodCoffeeTable(t){return function(t,r,i,n){if(function(e){let t;if(["height","width","length","topThickness","topGlassOffset","glassThickness","glassHolderLength","chamfer","legWidth","legDepth","precision","rotation","scale"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.height<=e.topThickness?t="Height must be greated then top thickness.":e.width<=0?t="Width must be greater than 0.":e.width<=2*(e.topGlassOffset+e.glassHolderLength)?t="Width must be greater than two top glass offsets and glass holder lengths.":e.length<=0?t="Length must be greater than 0.":e.length<=2*(e.topGlassOffset+e.glassHolderLength)?t="Length must be greater than two top glass offsets and glass holder lengths.":e.topThickness<=2*e.glassThickness?t="Table top thickness must be greater 2 x glass thickness.":e.glassThickness<=0?t="Glass thickness must be greater than 0":e.glassHolderLengthe.height-e.topThickness-e.shelfThickness?t=`Shelf top offset is larger than ${e.height-e.topThickness-e.shelfThickness}, which make it go underground.`:e.chamfer>=e.topThickness/2?t="Chamfer distance must be lower or equal than half of the top thickness.":e.chamfer>=e.shelfThickness/2?t="Chamfer distance must be lower or equal than half of the shelf thickness.":e.chamfer>=e.topGlassOffset/2?t="Chamfer distance must be lower or equal than half of the top glass offset.":e.chamfer>=e.legWidth/2?t="Chamfer distance must be lower or equal than half of the leg width.":e.chamfer>=e.legDepth/2?t="Chamfer distance must be lower or equal than half of the leg depth.":e.width<=2*e.legWidth?t="Width of the table must be greater or equal to the width of the two legs.":e.length<=2*e.legDepth?t="Length of the table must be greater or equal to the length of the two legs.":e.legDepth>=e.topGlassOffset+e.glassHolderLength?t="The depth of the leg must be lower or equal to the sum of glass offset and glass holder length.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!n.goodCoffeeTable)throw new Error("Could not compute, to use Good Coffee Table algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.goodCoffeeTable}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}snakeChair(t){return function(t,r,i,n){if(function(e){let t;if(["sittingHeight","backRestOffset","backRestHeight","width","length","thickness","ornamentDepth","nrOrnamentPlanks","filletRadius","precision","rotation","scale"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.sittingHeight<=2*e.thickness?t="Sitting height must be greater than 2 x thickness.":e.backRestOffset<0?t="Back rest offset can't be negative.":e.backRestHeight<=0?t="Back rest height must be greater than 0":e.width<=0?t="Width must be greater than 0.":e.length<=2*e.thickness?t="Length height must be greater than 2 x thickness.":e.thickness<=0?t="Width must be greater than 0.":e.nrOrnamentPlanks<0?t="Number of ornament planks must be greater than 0":e.filletRadius<=0?t="Fillet radius must be greater than 0.":e.filletRadius>=e.sittingHeight/2?t="Fillet radius must be lower than half of the sitting height.":e.filletRadius>=e.length/2?t="Fillet radius must be lower than half of the length.":e.filletRadius>=e.backRestHeight/2?t="Fillet radius must be lower than half of the back height.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!n.snakeChair)throw new Error("Could not compute, to use Snake Chair algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.snakeChair}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}snakeTable(t){return function(t,r,i,n){if(function(e){let t;if(["height","width","length","shelfHeight","supportLength","glassThickness","glassOffset","thickness","ornamentDepth","nrOrnamentPlanks","filletRadius","precision","rotation","scale"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.height<=2*e.thickness?t="Sitting height must be greater than 2 x thickness.":e.width<=0?t="Width must be greater than 0.":e.length<=2*e.thickness?t="Length height must be greater than 2 x thickness.":e.thickness<=0?t="Width must be greater than 0.":e.nrOrnamentPlanks<0?t="Number of ornament planks must be greater than 0":e.filletRadius<=0?t="Fillet radius must be greater than 0.":e.filletRadius>=e.height/2?t="Fillet radius must be lower than half of the sitting height.":e.filletRadius>=e.length/2?t="Fillet radius must be lower than half of the length.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!n.snakeTable)throw new Error("Could not compute, to use Snake Table algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.snakeTable}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}phoneNest(t){return function(t,r,i,n){if(!n.phoneNest)throw new Error("Could not compute, to use Phone Nest algorithm you must be subscribed to our silver plan.");try{const i=`\n ${n.phoneNest}\n `;return new Function(i).apply({inputs:t,occt:r,Inputs:e,Things:D,ShapeParser:ni})}catch(e){throw new Error(e)}}(t,this.occtService,this.occtAdv,this.dependencies)}}function oi(e,t,r,i){const n=r.find((t=>t.name===`${e.fontType}-${e.fontVariant}`));if(!n)throw new Error(`Font ${e.fontType}-${e.fontVariant}.ttf does not exist. Current font probably does not have corresponding variant.`);const s=n.font.getPath(e.text,0,0,e.fontSize),o=[];let a=n.font.getPaths(e.text,0,0,e.fontSize,{});const c=n.font.getAdvanceWidth(e.text,e.fontSize),h=s.getBoundingBox();switch(e.originAlignment){case Ne.leftBottom:break;case Ne.leftMiddle:a=n.font.getPaths(e.text,0,(h.y2-h.y1)/2,e.fontSize,{});break;case Ne.leftTop:a=n.font.getPaths(e.text,0,h.y2-h.y1,e.fontSize,{});break;case Ne.centerBottom:a=n.font.getPaths(e.text,-(h.x2-h.x1)/2,0,e.fontSize,{});break;case Ne.centerMiddle:a=n.font.getPaths(e.text,-(h.x2-h.x1)/2,(h.y2-h.y1)/2,e.fontSize,{});break;case Ne.centerTop:a=n.font.getPaths(e.text,-(h.x2-h.x1)/2,h.y2-h.y1,e.fontSize,{});break;case Ne.rightBottom:a=n.font.getPaths(e.text,-(h.x2-h.x1),0,e.fontSize,{});break;case Ne.rightMiddle:a=n.font.getPaths(e.text,-(h.x2-h.x1),(h.y2-h.y1)/2,e.fontSize,{});break;case Ne.rightTop:a=n.font.getPaths(e.text,-(h.x2-h.x1),h.y2-h.y1,e.fontSize,{})}a.forEach((e=>{const r=e.commands,n=[];let s,a,c;for(let e=0;e0?new i.BRepBuilderAPI_MakeFace_22(n[n.length-1],c.Wire()):new i.BRepBuilderAPI_MakeFace_15(c.Wire(),!0),n.push(e.Face()),e.delete(),c.delete()}catch(e){console.error("We could not create faces from this font probably due to self intersections! You should try removing weird characters and pick a more reliable font like 'Roboto'.")}else if("L"===o.type){const e=[-o.x,0,o.y];if(a[0]===e[0]&&a[2]===e[2])continue;const r=t.shapes.edge.line({start:a,end:e});c.Add_1(r),r.delete(),a=e}else if("Q"===o.type){const e=[-o.x1,0,o.y1],r=[-o.x,0,o.y],i=[a,e,r],n=t.shapes.wire.createBezier({points:i,closed:!1});c.Add_2(n),n.delete(),a=r}else if("C"===o.type){const e=[-o.x,0,o.y],r=[a,[-o.x1,0,o.y1],[-o.x2,0,o.y2],e],i=t.shapes.wire.createBezier({points:r,closed:!1});c.Add_2(i),i.delete(),a=e}}if(void 0!==n[n.length-1]){const e=n[n.length-1],r=new U.BasicShapeRepairDto;r.shape=e,r.minTolerance=1e-8,r.maxTolerance=1e-4,r.precision=.001;const i=t.shapeFix.basicShapeRepair(r);e.delete(),o.push(i)}}));const l=new Br;if(l.advanceWidth=c,l.boundingBox={x1:h.x1,y1:h.y1,x2:h.x2,y2:h.y2},e.height>0){const r=o.map((r=>t.operations.extrude({shape:r,direction:[0,e.height,0]})));o.forEach((e=>e.delete()));const i=r.map((r=>{const i=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]}),n=t.transforms.alignAndTranslate({shape:i,center:e.origin,direction:e.direction});return i.delete(),n}));i.reverse();const n=t.shapes.solid.getSolidsCentersOfMass({shapes:i});l.characterCenterCoordinates=n;const s=t.shapes.compound.makeCompound({shapes:i});return l.characterParts=i.map(((e,t)=>({id:`character-${t.toString()}`,shapes:{compound:e}}))),ai(l,s)}{const r=o.map((r=>{const i=t.transforms.rotate({shape:r,angle:e.rotation,axis:[0,1,0]}),n=t.transforms.alignAndTranslate({shape:i,center:e.origin,direction:e.direction});return i.delete(),n}));r.reverse(),o.forEach((e=>e.delete()));const i=t.shapes.face.getFacesCentersOfMass({shapes:r});l.characterCenterCoordinates=i;const n=t.shapes.compound.makeCompound({shapes:r});return l.characterParts=r.map(((e,t)=>({id:`character-${t.toString()}`,shapes:{compound:e}}))),ai(l,n)}}function ai(e,t){if(e){const r=[],i=ni.parse(e,r,"text-3d");return{compound:t,shapes:[{id:"1",shape:t},...r],data:Object.assign({compound:"1"},i)}}}String.prototype.codePointAt||(ii=function(e){if(null==this)throw TypeError();var t=String(this),r=t.length,i=e?Number(e):0;if(i!=i&&(i=0),!(i<0||i>=r)){var n,s=t.charCodeAt(i);return s>=55296&&s<=56319&&r>i+1&&(n=t.charCodeAt(i+1))>=56320&&n<=57343?1024*(s-55296)+n-56320+65536:s}},(ri=function(){try{var e={},t=Object.defineProperty,r=t(e,e,e)&&t}catch(e){}return r}())?ri(String.prototype,"codePointAt",{value:ii,configurable:!0,writable:!0}):String.prototype.codePointAt=ii);function ci(){this.table=new Uint16Array(16),this.trans=new Uint16Array(288)}function hi(e,t){this.source=e,this.sourceIndex=0,this.tag=0,this.bitcount=0,this.dest=t,this.destLen=0,this.ltree=new ci,this.dtree=new ci}var li=new ci,ui=new ci,di=new Uint8Array(30),pi=new Uint16Array(30),fi=new Uint8Array(30),gi=new Uint16Array(30),vi=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),mi=new ci,yi=new Uint8Array(320);function Si(e,t,r,i){var n,s;for(n=0;n>>=1,t}function Ti(e,t,r){if(!t)return r;for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>16-t;return e.tag>>>=t,e.bitcount-=t,i+r}function xi(e,t){for(;e.bitcount<24;)e.tag|=e.source[e.sourceIndex++]<>>=1,++n,r+=t.table[n],i-=t.table[n]}while(i>=0);return e.tag=s,e.bitcount-=n,t.trans[r+i]}function ki(e,t,r){var i,n,s,o,a,c;for(i=Ti(e,5,257),n=Ti(e,5,1),s=Ti(e,4,4),o=0;o<19;++o)yi[o]=0;for(o=0;o8;)e.sourceIndex--,e.bitcount-=8;if((t=256*(t=e.source[e.sourceIndex+1])+e.source[e.sourceIndex])!==(65535&~(256*e.source[e.sourceIndex+3]+e.source[e.sourceIndex+2])))return-3;for(e.sourceIndex+=4,r=t;r;--r)e.dest[e.destLen++]=e.source[e.sourceIndex++];return e.bitcount=0,0}!function(e,t){var r;for(r=0;r<7;++r)e.table[r]=0;for(e.table[7]=24,e.table[8]=152,e.table[9]=112,r=0;r<24;++r)e.trans[r]=256+r;for(r=0;r<144;++r)e.trans[24+r]=r;for(r=0;r<8;++r)e.trans[168+r]=280+r;for(r=0;r<112;++r)e.trans[176+r]=144+r;for(r=0;r<5;++r)t.table[r]=0;for(t.table[5]=32,r=0;r<32;++r)t.trans[r]=r}(li,ui),Si(di,pi,4,3),Si(fi,gi,2,1),di[28]=0,pi[28]=258;var Ai=function(e,t){var r,i,n=new hi(e,t);do{switch(r=Ei(n),Ti(n,2,0)){case 0:i=Ci(n);break;case 1:i=Pi(n,li,ui);break;case 2:ki(n,n.ltree,n.dtree),i=Pi(n,n.ltree,n.dtree);break;default:i=-3}if(0!==i)throw new Error("Data error")}while(!r);return n.destLenthis.x2&&(this.x2=e)),"number"==typeof t&&((isNaN(this.y1)||isNaN(this.y2))&&(this.y1=t,this.y2=t),tthis.y2&&(this.y2=t))},Oi.prototype.addX=function(e){this.addPoint(e,null)},Oi.prototype.addY=function(e){this.addPoint(null,e)},Oi.prototype.addBezier=function(e,t,r,i,n,s,o,a){var c=[e,t],h=[r,i],l=[n,s],u=[o,a];this.addPoint(e,t),this.addPoint(o,a);for(var d=0;d<=1;d++){var p=6*c[d]-12*h[d]+6*l[d],f=-3*c[d]+9*h[d]-9*l[d]+3*u[d],g=3*h[d]-3*c[d];if(0!==f){var v=Math.pow(p,2)-4*g*f;if(!(v<0)){var m=(-p+Math.sqrt(v))/(2*f);0=0&&i>0&&(r+=" "),r+=t(n)}return r}e=void 0!==e?e:2;for(var i="",n=0;n"},Di.prototype.toDOMElement=function(e){var t=this.toPathData(e),r=document.createElementNS("http://www.w3.org/2000/svg","path");return r.setAttribute("d",t),r};var Li={fail:Ri,argument:Fi,assert:Fi},Bi=2147483648,Mi={},Ii={},Ui={};function Wi(e){return function(){return e}}Ii.BYTE=function(e){return Li.argument(e>=0&&e<=255,"Byte value should be between 0 and 255."),[e]},Ui.BYTE=Wi(1),Ii.CHAR=function(e){return[e.charCodeAt(0)]},Ui.CHAR=Wi(1),Ii.CHARARRAY=function(e){void 0===e&&(e="",console.warn("Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name."));for(var t=[],r=0;r>8&255,255&e]},Ui.USHORT=Wi(2),Ii.SHORT=function(e){return e>=32768&&(e=-(65536-e)),[e>>8&255,255&e]},Ui.SHORT=Wi(2),Ii.UINT24=function(e){return[e>>16&255,e>>8&255,255&e]},Ui.UINT24=Wi(3),Ii.ULONG=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.ULONG=Wi(4),Ii.LONG=function(e){return e>=Bi&&(e=-(2*Bi-e)),[e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.LONG=Wi(4),Ii.FIXED=Ii.ULONG,Ui.FIXED=Ui.ULONG,Ii.FWORD=Ii.SHORT,Ui.FWORD=Ui.SHORT,Ii.UFWORD=Ii.USHORT,Ui.UFWORD=Ui.USHORT,Ii.LONGDATETIME=function(e){return[0,0,0,0,e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.LONGDATETIME=Wi(8),Ii.TAG=function(e){return Li.argument(4===e.length,"Tag should be exactly 4 ASCII characters."),[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]},Ui.TAG=Wi(4),Ii.Card8=Ii.BYTE,Ui.Card8=Ui.BYTE,Ii.Card16=Ii.USHORT,Ui.Card16=Ui.USHORT,Ii.OffSize=Ii.BYTE,Ui.OffSize=Ui.BYTE,Ii.SID=Ii.USHORT,Ui.SID=Ui.USHORT,Ii.NUMBER=function(e){return e>=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?Ii.NUMBER16(e):Ii.NUMBER32(e)},Ui.NUMBER=function(e){return Ii.NUMBER(e).length},Ii.NUMBER16=function(e){return[28,e>>8&255,255&e]},Ui.NUMBER16=Wi(3),Ii.NUMBER32=function(e){return[29,e>>24&255,e>>16&255,e>>8&255,255&e]},Ui.NUMBER32=Wi(5),Ii.REAL=function(e){var t=e.toString(),r=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(t);if(r){var i=parseFloat("1e"+((r[2]?+r[2]:0)+r[1].length));t=(Math.round(e*i)/i).toString()}for(var n="",s=0,o=t.length;s>8&255,t[t.length]=255&i}return t},Ui.UTF16=function(e){return 2*e.length};var Ni={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæøṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};Mi.MACSTRING=function(e,t,r,i){var n=Ni[i];if(void 0!==n){for(var s="",o=0;o=-128&&e<=127}function zi(e,t,r){for(var i=0,n=e.length;t>8&255,c+256&255)}return s}Ii.MACSTRING=function(e,t){var r=function(e){if(!Gi)for(var t in Gi={},Ni)Gi[t]=new String(t);var r=Gi[e];if(void 0!==r){if(Hi){var i=Hi.get(r);if(void 0!==i)return i}var n=Ni[e];if(void 0!==n){for(var s={},o=0;o=128&&void 0===(s=r[s]))return;i[n]=s}return i}},Ui.MACSTRING=function(e,t){var r=Ii.MACSTRING(e,t);return void 0!==r?r.length:0},Ii.VARDELTAS=function(e){for(var t=0,r=[];t=-128&&i<=127?ji(e,t,r):qi(e,t,r)}return r},Ii.INDEX=function(e){for(var t=1,r=[t],i=[],n=0;n>8,t[u+1]=255&d,t=t.concat(i[l])}return t},Ui.TABLE=function(e){for(var t=0,r=e.fields.length,i=0;i0)return new hn(this.data,this.offset+t).parseStruct(e)},hn.prototype.parsePointer32=function(e){var t=this.parseOffset32();if(t>0)return new hn(this.data,this.offset+t).parseStruct(e)},hn.prototype.parseListOfLists=function(e){for(var t=this.parseOffset16List(),r=t.length,i=this.relativeOffset,n=new Array(r),s=0;s=0;n-=1){var s=un.getUShort(e,t+4+8*n),o=un.getUShort(e,t+4+8*n+2);if(3===s&&(0===o||1===o||10===o)||0===s&&(0===o||1===o||2===o||3===o||4===o)){i=un.getULong(e,t+4+8*n+4);break}}if(-1===i)throw new Error("No valid cmap sub-tables found.");var a=new un.Parser(e,t+i);if(r.format=a.parseUShort(),12===r.format)!function(e,t){var r;t.parseUShort(),e.length=t.parseULong(),e.language=t.parseULong(),e.groupCount=r=t.parseULong(),e.glyphIndexMap={};for(var i=0;i>1,t.skip("uShort",3),e.glyphIndexMap={};for(var o=new un.Parser(r,i+n+14),a=new un.Parser(r,i+n+16+2*s),c=new un.Parser(r,i+n+16+4*s),h=new un.Parser(r,i+n+16+6*s),l=i+n+16+8*s,u=0;u0;t-=1)if(e.get(t).unicode>65535){console.log("Adding CMAP format 12 (needed!)"),r=!1;break}var i=[{name:"version",type:"USHORT",value:0},{name:"numTables",type:"USHORT",value:r?1:2},{name:"platformID",type:"USHORT",value:3},{name:"encodingID",type:"USHORT",value:1},{name:"offset",type:"ULONG",value:r?12:20}];r||(i=i.concat([{name:"cmap12PlatformID",type:"USHORT",value:3},{name:"cmap12EncodingID",type:"USHORT",value:10},{name:"cmap12Offset",type:"ULONG",value:0}])),i=i.concat([{name:"format",type:"USHORT",value:4},{name:"cmap4Length",type:"USHORT",value:0},{name:"language",type:"USHORT",value:0},{name:"segCountX2",type:"USHORT",value:0},{name:"searchRange",type:"USHORT",value:0},{name:"entrySelector",type:"USHORT",value:0},{name:"rangeShift",type:"USHORT",value:0}]);var n=new rn.Table("cmap",i);for(n.segments=[],t=0;t>4,s=15&i;if(15===n)break;if(t+=r[n],15===s)break;t+=r[s]}return parseFloat(t)}(e);if(t>=32&&t<=246)return t-139;if(t>=247&&t<=250)return 256*(t-247)+e.parseByte()+108;if(t>=251&&t<=254)return 256*-(t-251)-e.parseByte()-108;throw new Error("Invalid b0 "+t)}function Dn(e,t,r){t=void 0!==t?t:0;var i=new un.Parser(e,t),n=[],s=[];for(r=void 0!==r?r:e.length;i.relativeOffset>1,d.length=0,f=!0}return function r(h){for(var y,S,T,x,k,P,C,A,_,O,D,R,F=0;F1&&!f&&(b=d.shift()+l,f=!0),m+=d.pop(),w(v,m);break;case 5:for(;d.length>0;)v+=d.shift(),m+=d.shift(),u.lineTo(v,m);break;case 6:for(;d.length>0&&(v+=d.shift(),u.lineTo(v,m),0!==d.length);)m+=d.shift(),u.lineTo(v,m);break;case 7:for(;d.length>0&&(m+=d.shift(),u.lineTo(v,m),0!==d.length);)v+=d.shift(),u.lineTo(v,m);break;case 8:for(;d.length>0;)i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+d.shift(),u.curveTo(i,n,s,o,v,m);break;case 10:k=d.pop()+c,(P=a[k])&&r(P);break;case 11:return;case 12:switch(L=h[F],F+=1,L){case 35:i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),C=s+d.shift(),A=o+d.shift(),_=C+d.shift(),O=A+d.shift(),D=_+d.shift(),R=O+d.shift(),v=D+d.shift(),m=R+d.shift(),d.shift(),u.curveTo(i,n,s,o,C,A),u.curveTo(_,O,D,R,v,m);break;case 34:i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),C=s+d.shift(),A=o,_=C+d.shift(),O=o,D=_+d.shift(),R=m,v=D+d.shift(),u.curveTo(i,n,s,o,C,A),u.curveTo(_,O,D,R,v,m);break;case 36:i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),C=s+d.shift(),A=o,_=C+d.shift(),O=o,D=_+d.shift(),R=O+d.shift(),v=D+d.shift(),u.curveTo(i,n,s,o,C,A),u.curveTo(_,O,D,R,v,m);break;case 37:i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),C=s+d.shift(),A=o+d.shift(),_=C+d.shift(),O=A+d.shift(),D=_+d.shift(),R=O+d.shift(),Math.abs(D-v)>Math.abs(R-m)?v=D+d.shift():m=R+d.shift(),u.curveTo(i,n,s,o,C,A),u.curveTo(_,O,D,R,v,m);break;default:console.log("Glyph "+t.index+": unknown operator 1200"+L),d.length=0}break;case 14:d.length>0&&!f&&(b=d.shift()+l,f=!0),g&&(u.closePath(),g=!1);break;case 19:case 20:E(),F+=p+7>>3;break;case 21:d.length>2&&!f&&(b=d.shift()+l,f=!0),m+=d.pop(),w(v+=d.pop(),m);break;case 22:d.length>1&&!f&&(b=d.shift()+l,f=!0),w(v+=d.pop(),m);break;case 24:for(;d.length>2;)i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+d.shift(),u.curveTo(i,n,s,o,v,m);v+=d.shift(),m+=d.shift(),u.lineTo(v,m);break;case 25:for(;d.length>6;)v+=d.shift(),m+=d.shift(),u.lineTo(v,m);i=v+d.shift(),n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+d.shift(),u.curveTo(i,n,s,o,v,m);break;case 26:for(d.length%2&&(v+=d.shift());d.length>0;)i=v,n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s,m=o+d.shift(),u.curveTo(i,n,s,o,v,m);break;case 27:for(d.length%2&&(m+=d.shift());d.length>0;)i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o,u.curveTo(i,n,s,o,v,m);break;case 28:y=h[F],S=h[F+1],d.push((y<<24|S<<16)>>16),F+=2;break;case 29:k=d.pop()+e.gsubrsBias,(P=e.gsubrs[k])&&r(P);break;case 30:for(;d.length>0&&(i=v,n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m),0!==d.length);)i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),m=o+d.shift(),v=s+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m);break;case 31:for(;d.length>0&&(i=v+d.shift(),n=m,s=i+d.shift(),o=n+d.shift(),m=o+d.shift(),v=s+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m),0!==d.length);)i=v,n=m+d.shift(),s=i+d.shift(),o=n+d.shift(),v=s+d.shift(),m=o+(1===d.length?d.shift():0),u.curveTo(i,n,s,o,v,m);break;default:L<32?console.log("Glyph "+t.index+": unknown operator "+L):L<247?d.push(L-139):L<251?(y=h[F],F+=1,d.push(256*(L-247)+y+108)):L<255?(y=h[F],F+=1,d.push(256*-(L-251)-y-108)):(y=h[F],S=h[F+1],T=h[F+2],x=h[F+3],F+=4,d.push((y<<24|S<<16|T<<8|x)/65536))}}}(r),t.advanceWidth=b,u}function Nn(e,t){var r,i=fn.indexOf(e);return i>=0&&(r=i),(i=t.indexOf(e))>=0?r=i+fn.length:(r=fn.length+t.length,t.push(e)),r}function Gn(e,t,r){for(var i={},n=0;n=i)throw new Error("CFF table CID Font FDSelect has bad FD index value "+n+" (FD count "+i+")");s.push(n)}else{if(3!==a)throw new Error("CFF Table CID Font FDSelect table has unsupported format "+a);var h,l=o.parseCard16(),u=o.parseCard16();if(0!==u)throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID "+u);for(var d=0;d=i)throw new Error("CFF table CID Font FDSelect has bad FD index value "+n+" (FD count "+i+")");if(h>r)throw new Error("CFF Table CID Font FDSelect format 3 range has bad GID "+h);for(;u=1&&(r.ulCodePageRange1=i.parseULong(),r.ulCodePageRange2=i.parseULong()),r.version>=2&&(r.sxHeight=i.parseShort(),r.sCapHeight=i.parseShort(),r.usDefaultChar=i.parseUShort(),r.usBreakChar=i.parseUShort(),r.usMaxContent=i.parseUShort()),r},make:function(e){return new rn.Table("OS/2",[{name:"version",type:"USHORT",value:3},{name:"xAvgCharWidth",type:"SHORT",value:0},{name:"usWeightClass",type:"USHORT",value:0},{name:"usWidthClass",type:"USHORT",value:0},{name:"fsType",type:"USHORT",value:0},{name:"ySubscriptXSize",type:"SHORT",value:650},{name:"ySubscriptYSize",type:"SHORT",value:699},{name:"ySubscriptXOffset",type:"SHORT",value:0},{name:"ySubscriptYOffset",type:"SHORT",value:140},{name:"ySuperscriptXSize",type:"SHORT",value:650},{name:"ySuperscriptYSize",type:"SHORT",value:699},{name:"ySuperscriptXOffset",type:"SHORT",value:0},{name:"ySuperscriptYOffset",type:"SHORT",value:479},{name:"yStrikeoutSize",type:"SHORT",value:49},{name:"yStrikeoutPosition",type:"SHORT",value:258},{name:"sFamilyClass",type:"SHORT",value:0},{name:"bFamilyType",type:"BYTE",value:0},{name:"bSerifStyle",type:"BYTE",value:0},{name:"bWeight",type:"BYTE",value:0},{name:"bProportion",type:"BYTE",value:0},{name:"bContrast",type:"BYTE",value:0},{name:"bStrokeVariation",type:"BYTE",value:0},{name:"bArmStyle",type:"BYTE",value:0},{name:"bLetterform",type:"BYTE",value:0},{name:"bMidline",type:"BYTE",value:0},{name:"bXHeight",type:"BYTE",value:0},{name:"ulUnicodeRange1",type:"ULONG",value:0},{name:"ulUnicodeRange2",type:"ULONG",value:0},{name:"ulUnicodeRange3",type:"ULONG",value:0},{name:"ulUnicodeRange4",type:"ULONG",value:0},{name:"achVendID",type:"CHARARRAY",value:"XXXX"},{name:"fsSelection",type:"USHORT",value:0},{name:"usFirstCharIndex",type:"USHORT",value:0},{name:"usLastCharIndex",type:"USHORT",value:0},{name:"sTypoAscender",type:"SHORT",value:0},{name:"sTypoDescender",type:"SHORT",value:0},{name:"sTypoLineGap",type:"SHORT",value:0},{name:"usWinAscent",type:"USHORT",value:0},{name:"usWinDescent",type:"USHORT",value:0},{name:"ulCodePageRange1",type:"ULONG",value:0},{name:"ulCodePageRange2",type:"ULONG",value:0},{name:"sxHeight",type:"SHORT",value:0},{name:"sCapHeight",type:"SHORT",value:0},{name:"usDefaultChar",type:"USHORT",value:0},{name:"usBreakChar",type:"USHORT",value:0},{name:"usMaxContext",type:"USHORT",value:0}],e)},unicodeRanges:ls,getUnicodeRange:function(e){for(var t=0;t=r.begin&&e=mn.length){var o=i.parseChar();r.names.push(i.parseString(o))}break;case 2.5:r.numberOfGlyphs=i.parseUShort(),r.offset=new Array(r.numberOfGlyphs);for(var a=0;at.value.tag?1:-1})),t.fields=t.fields.concat(i),t.fields=t.fields.concat(n),t}function Es(e,t,r){for(var i=0;i0)return e.glyphs.get(n).getMetrics()}return r}function Ts(e){for(var t=0,r=0;rv||void 0===t)&&v>0&&(t=v),h 123 are reserved for internal usage");p|=1<0?Xn.make(R):void 0,B=ds.make(),M=jn.make(e.glyphs,{version:e.getEnglishName("version"),fullName:A,familyName:P,weightName:C,postScriptName:_,unitsPerEm:e.unitsPerEm,fontBBox:[0,S.yMin,S.ascender,S.advanceWidthMax]}),I=e.metas&&Object.keys(e.metas).length>0?ms.make(e.metas):void 0,U=[b,w,E,T,F,k,B,M,x];L&&U.push(L),e.tables.gsub&&U.push(vs.make(e.tables.gsub)),I&&U.push(I);for(var W=ws(U),N=Ss(W.encode()),G=W.fields,H=!1,V=0;V>>1,s=e[n].tag;if(s===t)return n;s>>1,s=e[n];if(s===t)return n;s>>1,o=(r=e[s]).start;if(o===t)return r;o0)return t>(r=e[i-1]).end?0:r}function As(e,t){this.font=e,this.tableName=t}function _s(e){As.call(this,e,"gpos")}function Os(e){As.call(this,e,"gsub")}function Ds(e,t){var r=e.length;if(r!==t.length)return!1;for(var i=0;i0?(s=e.parseByte(),t&n||(s=-s),s=r+s):s=(t&n)>0?r:r+e.parseShort(),s}function Bs(e,t,r){var i,n,s=new un.Parser(t,r);if(e.numberOfContours=s.parseShort(),e._xMin=s.parseShort(),e._yMin=s.parseShort(),e._xMax=s.parseShort(),e._yMax=s.parseShort(),e.numberOfContours>0){for(var o=e.endPointIndices=[],a=0;a0)for(var u=s.parseByte(),d=0;d0){var p,f=[];if(h>0){for(var g=0;g=0,f.push(p);for(var v=0,m=0;m0?(2&i)>0?(w.dx=s.parseShort(),w.dy=s.parseShort()):w.matchedPoints=[s.parseUShort(),s.parseUShort()]:(2&i)>0?(w.dx=s.parseChar(),w.dy=s.parseChar()):w.matchedPoints=[s.parseByte(),s.parseByte()],(8&i)>0?w.xScale=w.yScale=s.parseF2Dot14():(64&i)>0?(w.xScale=s.parseF2Dot14(),w.yScale=s.parseF2Dot14()):(128&i)>0&&(w.xScale=s.parseF2Dot14(),w.scale01=s.parseF2Dot14(),w.scale10=s.parseF2Dot14(),w.yScale=s.parseF2Dot14()),e.components.push(w),b=!!(32&i)}if(256&i){e.instructionLength=s.parseUShort(),e.instructions=[];for(var E=0;Et.points.length-1||i.matchedPoints[1]>n.points.length-1)throw Error("Matched points out of range in "+t.name);var o=t.points[i.matchedPoints[0]],a=n.points[i.matchedPoints[1]],c={xScale:i.xScale,scale01:i.scale01,scale10:i.scale10,yScale:i.yScale,dx:0,dy:0};a=Ms([a],c)[0],c.dx=o.x-a.x,c.dy=o.y-a.y,s=Ms(n.points,c)}t.points=t.points.concat(s)}}return Is(t.points)}As.prototype={searchTag:ks,binSearch:Ps,getTable:function(e){var t=this.font.tables[this.tableName];return!t&&e&&(t=this.font.tables[this.tableName]=this.createDefaultTable()),t},getScriptNames:function(){var e=this.getTable();return e?e.scripts.map((function(e){return e.tag})):[]},getDefaultScriptName:function(){var e=this.getTable();if(e){for(var t=!1,r=0;r=0)return i[n].script;if(t){var s={tag:e,script:{defaultLangSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]},langSysRecords:[]}};return i.splice(-1-n,0,s),s.script}}},getLangSysTable:function(e,t,r){var i=this.getScriptTable(e,r);if(i){if(!t||"dflt"===t||"DFLT"===t)return i.defaultLangSys;var n=ks(i.langSysRecords,t);if(n>=0)return i.langSysRecords[n].langSys;if(r){var s={tag:t,langSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]}};return i.langSysRecords.splice(-1-n,0,s),s.langSys}}},getFeatureTable:function(e,t,r,i){var n=this.getLangSysTable(e,t,i);if(n){for(var s,o=n.featureIndexes,a=this.font.tables[this.tableName].features,c=0;c=a[h-1].tag,"Features must be added in alphabetical order."),s={tag:r,feature:{params:0,lookupListIndexes:[]}},a.push(s),o.push(h),s.feature}}},getLookupTables:function(e,t,r,i,n){var s=this.getFeatureTable(e,t,r,n),o=[];if(s){for(var a,c=s.lookupListIndexes,h=this.font.tables[this.tableName].lookups,l=0;l=0?r:-1;case 2:var i=Cs(e.ranges,t);return i?i.index+t-i.start:-1}},expandCoverage:function(e){if(1===e.format)return e.glyphs;for(var t=[],r=e.ranges,i=0;i1,'Multiple: "by" must be an array of two or more ids');var n=Rs(this.getLookupTables(r,i,e,2,!0)[0],1,{substFormat:1,coverage:{format:1,glyphs:[]},sequences:[]});Li.assert(1===n.coverage.format,"Multiple: unable to modify coverage table format "+n.coverage.format);var s=t.sub,o=this.binSearch(n.coverage.glyphs,s);o<0&&(o=-1-o,n.coverage.glyphs.splice(o,0,s),n.sequences.splice(o,0,0)),n.sequences[o]=t.by},Os.prototype.addAlternate=function(e,t,r,i){var n=Rs(this.getLookupTables(r,i,e,3,!0)[0],1,{substFormat:1,coverage:{format:1,glyphs:[]},alternateSets:[]});Li.assert(1===n.coverage.format,"Alternate: unable to modify coverage table format "+n.coverage.format);var s=t.sub,o=this.binSearch(n.coverage.glyphs,s);o<0&&(o=-1-o,n.coverage.glyphs.splice(o,0,s),n.alternateSets.splice(o,0,0)),n.alternateSets[o]=t.by},Os.prototype.addLigature=function(e,t,r,i){var n=this.getLookupTables(r,i,e,4,!0)[0],s=n.subtables[0];s||(s={substFormat:1,coverage:{format:1,glyphs:[]},ligatureSets:[]},n.subtables[0]=s),Li.assert(1===s.coverage.format,"Ligature: unable to modify coverage table format "+s.coverage.format);var o=t.sub[0],a=t.sub.slice(1),c={ligGlyph:t.by,components:a},h=this.binSearch(s.coverage.glyphs,o);if(h>=0){for(var l=s.ligatureSets[h],u=0;u=176&&r<=183)n+=r-176+1;else if(r>=184&&r<=191)n+=2*(r-184+1);else if(t&&1===s&&27===r)break}while(s>0);e.ip=n}function co(e,t){exports.DEBUG&&console.log(t.step,"SVTCA["+e.axis+"]"),t.fv=t.pv=t.dpv=e}function ho(e,t){exports.DEBUG&&console.log(t.step,"SPVTCA["+e.axis+"]"),t.pv=t.dpv=e}function lo(e,t){exports.DEBUG&&console.log(t.step,"SFVTCA["+e.axis+"]"),t.fv=e}function uo(e,t){var r,i,n=t.stack,s=n.pop(),o=n.pop(),a=t.z2[s],c=t.z1[o];exports.DEBUG&&console.log("SPVTL["+e+"]",s,o),e?(r=a.y-c.y,i=c.x-a.x):(r=c.x-a.x,i=c.y-a.y),t.pv=t.dpv=to(r,i)}function po(e,t){var r,i,n=t.stack,s=n.pop(),o=n.pop(),a=t.z2[s],c=t.z1[o];exports.DEBUG&&console.log("SFVTL["+e+"]",s,o),e?(r=a.y-c.y,i=c.x-a.x):(r=c.x-a.x,i=c.y-a.y),t.fv=to(r,i)}function fo(e){exports.DEBUG&&console.log(e.step,"POP[]"),e.stack.pop()}function go(e,t){var r=t.stack.pop(),i=t.z0[r],n=t.fv,s=t.pv;exports.DEBUG&&console.log(t.step,"MDAP["+e+"]",r);var o=s.distance(i,io);e&&(o=t.round(o)),n.setRelative(i,io,o,s),n.touch(i),t.rp0=t.rp1=r}function vo(e,t){var r,i,n,s=t.z2,o=s.length-2;exports.DEBUG&&console.log(t.step,"IUP["+e.axis+"]");for(var a=0;a1?"loop "+(t.loop-a)+": ":"")+"SHP["+(e?"rp1":"rp2")+"]",h)}t.loop=1}function yo(e,t){var r=t.stack,i=e?t.rp1:t.rp2,n=(e?t.z0:t.z1)[i],s=t.fv,o=t.pv,a=r.pop(),c=t.z2[t.contours[a]],h=c;exports.DEBUG&&console.log(t.step,"SHC["+e+"]",a);var l=o.distance(n,n,!1,!0);do{h!==n&&s.setRelative(h,h,l,o),h=h.nextPointOnContour}while(h!==c)}function So(e,t){var r,i,n=t.stack,s=e?t.rp1:t.rp2,o=(e?t.z0:t.z1)[s],a=t.fv,c=t.pv,h=n.pop();switch(exports.DEBUG&&console.log(t.step,"SHZ["+e+"]",h),h){case 0:r=t.tZone;break;case 1:r=t.gZone;break;default:throw new Error("Invalid zone")}for(var l=c.distance(o,o,!1,!0),u=r.length-2,d=0;d",a),t.stack.push(Math.round(64*a))}function xo(e,t){var r=t.stack,i=r.pop(),n=t.fv,s=t.pv,o=t.ppem,a=t.deltaBase+16*(e-1),c=t.deltaShift,h=t.z0;exports.DEBUG&&console.log(t.step,"DELTAP["+e+"]",i,r);for(var l=0;l>4)===o){var p=(15&d)-8;p>=0&&p++,exports.DEBUG&&console.log(t.step,"DELTAPFIX",u,"by",p*c);var f=h[u];n.setRelative(f,f,p*c,s)}}}function ko(e,t){var r=t.stack,i=r.pop();exports.DEBUG&&console.log(t.step,"ROUND[]"),r.push(64*t.round(i/64))}function Po(e,t){var r=t.stack,i=r.pop(),n=t.ppem,s=t.deltaBase+16*(e-1),o=t.deltaShift;exports.DEBUG&&console.log(t.step,"DELTAC["+e+"]",i,r);for(var a=0;a>4)===n){var l=(15&h)-8;l>=0&&l++;var u=l*o;exports.DEBUG&&console.log(t.step,"DELTACFIX",c,"by",u),t.cvt[c]+=u}}}function Co(e,t){var r,i,n=t.stack,s=n.pop(),o=n.pop(),a=t.z2[s],c=t.z1[o];exports.DEBUG&&console.log(t.step,"SDPVTL["+e+"]",s,o),e?(r=a.y-c.y,i=c.x-a.x):(r=c.x-a.x,i=c.y-a.y),t.dpv=to(r,i)}function Ao(e,t){var r=t.stack,i=t.prog,n=t.ip;exports.DEBUG&&console.log(t.step,"PUSHB["+e+"]");for(var s=0;s=0?1:-1,a=Math.abs(a),e&&(h=s.cvt[u],i&&Math.abs(a-h)":"_")+(i?"R":"_")+(0===n?"Gr":1===n?"Bl":2===n?"Wh":"")+"]",e?u+"("+s.cvt[u]+","+h+")":"",d,"(d =",o,"->",c*a,")"),s.rp1=s.rp0,s.rp2=d,t&&(s.rp0=d)}function Do(e){this.char=e,this.state={},this.activeState=null}function Ro(e,t,r){this.contextName=r,this.startIndex=e,this.endOffset=t}function Fo(e,t,r){this.contextName=e,this.openRange=null,this.ranges=[],this.checkStart=t,this.checkEnd=r}function Lo(e,t){this.context=e,this.index=t,this.length=e.length,this.current=e[t],this.backtrack=e.slice(0,t),this.lookahead=e.slice(t+1)}function Bo(e){this.eventId=e,this.subscribers=[]}function Mo(e){var t=this,r=["start","end","next","newToken","contextStart","contextEnd","insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD","updateContextsRanges"];r.forEach((function(e){Object.defineProperty(t.events,e,{value:new Bo(e)})})),e&&r.forEach((function(r){var i=e[r];"function"==typeof i&&t.events[r].subscribe(i)})),["insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD"].forEach((function(e){t.events[e].subscribe(t.updateContextsRanges)}))}function Io(e){this.tokens=[],this.registeredContexts={},this.contextCheckers=[],this.events={},this.registeredModifiers=[],Mo.call(this,e)}function Uo(e){return/[\u0600-\u065F\u066A-\u06D2\u06FA-\u06FF]/.test(e)}function Wo(e){return/[\u0630\u0690\u0621\u0631\u0661\u0671\u0622\u0632\u0672\u0692\u06C2\u0623\u0673\u0693\u06C3\u0624\u0694\u06C4\u0625\u0675\u0695\u06C5\u06E5\u0676\u0696\u06C6\u0627\u0677\u0697\u06C7\u0648\u0688\u0698\u06C8\u0689\u0699\u06C9\u068A\u06CA\u066B\u068B\u06CB\u068C\u068D\u06CD\u06FD\u068E\u06EE\u06FE\u062F\u068F\u06CF\u06EF]/.test(e)}function No(e){return/[\u0600-\u0605\u060C-\u060E\u0610-\u061B\u061E\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED]/.test(e)}function Go(e){return/[A-z]/.test(e)}function Ho(e){this.font=e,this.features={}}function Vo(e){this.id=e.id,this.tag=e.tag,this.substitution=e.substitution}function zo(e,t){if(!e)return-1;switch(t.format){case 1:return t.glyphs.indexOf(e);case 2:for(var r=t.ranges,i=0;i=n.start&&e<=n.end){var s=e-n.start;return n.index+s}}break;default:return-1}return-1}function jo(e,t){return-1===zo(e,t.coverage)?null:e+t.deltaGlyphId}function qo(e,t){var r=zo(e,t.coverage);return-1===r?null:t.substitute[r]}function $o(e,t){for(var r=[],i=0;i2)){var r=this.font,i=this._prepState;if(!i||i.ppem!==t){var n=this._fpgmState;if(!n){so.prototype=no,(n=this._fpgmState=new so("fpgm",r.tables.fpgm)).funcs=[],n.font=r,exports.DEBUG&&(console.log("---EXEC FPGM---"),n.step=-1);try{Ns(n)}catch(e){return console.log("Hinting error in FPGM:"+e),void(this._errorState=3)}}so.prototype=n,(i=this._prepState=new so("prep",r.tables.prep)).ppem=t;var s=r.tables.cvt;if(s)for(var o=i.cvt=new Array(s.length),a=t/r.unitsPerEm,c=0;c1))try{return Gs(e,i)}catch(e){return this._errorState<1&&(console.log("Hinting error:"+e),console.log("Note: further hinting errors are silenced")),void(this._errorState=1)}}},Gs=function(e,t){var r,i,n,s=t.ppem/t.font.unitsPerEm,o=s,a=e.components;if(so.prototype=t,a){var c=t.font;i=[],r=[];for(var h=0;h1?"loop "+(e.loop-r)+": ":"")+"SHPIX[]",o,n),i.setRelative(a,a,n),i.touch(a)}e.loop=1},function(e){for(var t=e.stack,r=e.rp1,i=e.rp2,n=e.loop,s=e.z0[r],o=e.z1[i],a=e.fv,c=e.dpv,h=e.z2;n--;){var l=t.pop(),u=h[l];exports.DEBUG&&console.log(e.step,(e.loop>1?"loop "+(e.loop-n)+": ":"")+"IP[]",l,r,"<->",i),a.interpolate(u,s,o,c),a.touch(u)}e.loop=1},bo.bind(void 0,0),bo.bind(void 0,1),function(e){for(var t=e.stack,r=e.rp0,i=e.z0[r],n=e.loop,s=e.fv,o=e.pv,a=e.z1;n--;){var c=t.pop(),h=a[c];exports.DEBUG&&console.log(e.step,(e.loop>1?"loop "+(e.loop-n)+": ":"")+"ALIGNRP[]",c),s.setRelative(h,i,0,o),s.touch(h)}e.loop=1},function(e){exports.DEBUG&&console.log(e.step,"RTDG[]"),e.round=$s},wo.bind(void 0,0),wo.bind(void 0,1),function(e){var t=e.prog,r=e.ip,i=e.stack,n=t[++r];exports.DEBUG&&console.log(e.step,"NPUSHB[]",n);for(var s=0;sr?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"GTEQ[]",r,i),t.push(i>=r?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"EQ[]",r,i),t.push(r===i?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"NEQ[]",r,i),t.push(r!==i?1:0)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"ODD[]",r),t.push(Math.trunc(r)%2?1:0)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"EVEN[]",r),t.push(Math.trunc(r)%2?0:1)},function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"IF[]",t),t||(ao(e,!0),exports.DEBUG&&console.log(e.step,"EIF[]"))},function(e){exports.DEBUG&&console.log(e.step,"EIF[]")},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"AND[]",r,i),t.push(r&&i?1:0)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"OR[]",r,i),t.push(r||i?1:0)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"NOT[]",r),t.push(r?0:1)},xo.bind(void 0,1),function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SDB[]",t),e.deltaBase=t},function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SDS[]",t),e.deltaShift=Math.pow(.5,t)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"ADD[]",r,i),t.push(i+r)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"SUB[]",r,i),t.push(i-r)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"DIV[]",r,i),t.push(64*i/r)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"MUL[]",r,i),t.push(i*r/64)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"ABS[]",r),t.push(Math.abs(r))},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"NEG[]",r),t.push(-r)},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"FLOOR[]",r),t.push(64*Math.floor(r/64))},function(e){var t=e.stack,r=t.pop();exports.DEBUG&&console.log(e.step,"CEILING[]",r),t.push(64*Math.ceil(r/64))},ko.bind(void 0,0),ko.bind(void 0,1),ko.bind(void 0,2),ko.bind(void 0,3),void 0,void 0,void 0,void 0,function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"WCVTF[]",r,i),e.cvt[i]=r*e.ppem/e.font.unitsPerEm},xo.bind(void 0,2),xo.bind(void 0,3),Po.bind(void 0,1),Po.bind(void 0,2),Po.bind(void 0,3),function(e){var t,r=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"SROUND[]",r),e.round=Js,192&r){case 0:t=.5;break;case 64:t=1;break;case 128:t=2;break;default:throw new Error("invalid SROUND value")}switch(e.srPeriod=t,48&r){case 0:e.srPhase=0;break;case 16:e.srPhase=.25*t;break;case 32:e.srPhase=.5*t;break;case 48:e.srPhase=.75*t;break;default:throw new Error("invalid SROUND value")}r&=15,e.srThreshold=0===r?0:(r/8-.5)*t},function(e){var t,r=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"S45ROUND[]",r),e.round=Js,192&r){case 0:t=Math.sqrt(2)/2;break;case 64:t=Math.sqrt(2);break;case 128:t=2*Math.sqrt(2);break;default:throw new Error("invalid S45ROUND value")}switch(e.srPeriod=t,48&r){case 0:e.srPhase=0;break;case 16:e.srPhase=.25*t;break;case 32:e.srPhase=.5*t;break;case 48:e.srPhase=.75*t;break;default:throw new Error("invalid S45ROUND value")}r&=15,e.srThreshold=0===r?0:(r/8-.5)*t},void 0,void 0,function(e){exports.DEBUG&&console.log(e.step,"ROFF[]"),e.round=js},void 0,function(e){exports.DEBUG&&console.log(e.step,"RUTG[]"),e.round=Xs},function(e){exports.DEBUG&&console.log(e.step,"RDTG[]"),e.round=Zs},fo,fo,void 0,void 0,void 0,void 0,void 0,function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SCANCTRL[]",t)},Co.bind(void 0,0),Co.bind(void 0,1),function(e){var t=e.stack,r=t.pop(),i=0;exports.DEBUG&&console.log(e.step,"GETINFO[]",r),1&r&&(i=35),32&r&&(i|=4096),t.push(i)},void 0,function(e){var t=e.stack,r=t.pop(),i=t.pop(),n=t.pop();exports.DEBUG&&console.log(e.step,"ROLL[]"),t.push(i),t.push(r),t.push(n)},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"MAX[]",r,i),t.push(Math.max(i,r))},function(e){var t=e.stack,r=t.pop(),i=t.pop();exports.DEBUG&&console.log(e.step,"MIN[]",r,i),t.push(Math.min(i,r))},function(e){var t=e.stack.pop();exports.DEBUG&&console.log(e.step,"SCANTYPE[]",t)},function(e){var t=e.stack.pop(),r=e.stack.pop();switch(exports.DEBUG&&console.log(e.step,"INSTCTRL[]",t,r),t){case 1:return void(e.inhibitGridFit=!!r);case 2:return void(e.ignoreCvt=!!r);default:throw new Error("invalid INSTCTRL[] selector")}},void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,Ao.bind(void 0,1),Ao.bind(void 0,2),Ao.bind(void 0,3),Ao.bind(void 0,4),Ao.bind(void 0,5),Ao.bind(void 0,6),Ao.bind(void 0,7),Ao.bind(void 0,8),_o.bind(void 0,1),_o.bind(void 0,2),_o.bind(void 0,3),_o.bind(void 0,4),_o.bind(void 0,5),_o.bind(void 0,6),_o.bind(void 0,7),_o.bind(void 0,8),Oo.bind(void 0,0,0,0,0,0),Oo.bind(void 0,0,0,0,0,1),Oo.bind(void 0,0,0,0,0,2),Oo.bind(void 0,0,0,0,0,3),Oo.bind(void 0,0,0,0,1,0),Oo.bind(void 0,0,0,0,1,1),Oo.bind(void 0,0,0,0,1,2),Oo.bind(void 0,0,0,0,1,3),Oo.bind(void 0,0,0,1,0,0),Oo.bind(void 0,0,0,1,0,1),Oo.bind(void 0,0,0,1,0,2),Oo.bind(void 0,0,0,1,0,3),Oo.bind(void 0,0,0,1,1,0),Oo.bind(void 0,0,0,1,1,1),Oo.bind(void 0,0,0,1,1,2),Oo.bind(void 0,0,0,1,1,3),Oo.bind(void 0,0,1,0,0,0),Oo.bind(void 0,0,1,0,0,1),Oo.bind(void 0,0,1,0,0,2),Oo.bind(void 0,0,1,0,0,3),Oo.bind(void 0,0,1,0,1,0),Oo.bind(void 0,0,1,0,1,1),Oo.bind(void 0,0,1,0,1,2),Oo.bind(void 0,0,1,0,1,3),Oo.bind(void 0,0,1,1,0,0),Oo.bind(void 0,0,1,1,0,1),Oo.bind(void 0,0,1,1,0,2),Oo.bind(void 0,0,1,1,0,3),Oo.bind(void 0,0,1,1,1,0),Oo.bind(void 0,0,1,1,1,1),Oo.bind(void 0,0,1,1,1,2),Oo.bind(void 0,0,1,1,1,3),Oo.bind(void 0,1,0,0,0,0),Oo.bind(void 0,1,0,0,0,1),Oo.bind(void 0,1,0,0,0,2),Oo.bind(void 0,1,0,0,0,3),Oo.bind(void 0,1,0,0,1,0),Oo.bind(void 0,1,0,0,1,1),Oo.bind(void 0,1,0,0,1,2),Oo.bind(void 0,1,0,0,1,3),Oo.bind(void 0,1,0,1,0,0),Oo.bind(void 0,1,0,1,0,1),Oo.bind(void 0,1,0,1,0,2),Oo.bind(void 0,1,0,1,0,3),Oo.bind(void 0,1,0,1,1,0),Oo.bind(void 0,1,0,1,1,1),Oo.bind(void 0,1,0,1,1,2),Oo.bind(void 0,1,0,1,1,3),Oo.bind(void 0,1,1,0,0,0),Oo.bind(void 0,1,1,0,0,1),Oo.bind(void 0,1,1,0,0,2),Oo.bind(void 0,1,1,0,0,3),Oo.bind(void 0,1,1,0,1,0),Oo.bind(void 0,1,1,0,1,1),Oo.bind(void 0,1,1,0,1,2),Oo.bind(void 0,1,1,0,1,3),Oo.bind(void 0,1,1,1,0,0),Oo.bind(void 0,1,1,1,0,1),Oo.bind(void 0,1,1,1,0,2),Oo.bind(void 0,1,1,1,0,3),Oo.bind(void 0,1,1,1,1,0),Oo.bind(void 0,1,1,1,1,1),Oo.bind(void 0,1,1,1,1,2),Oo.bind(void 0,1,1,1,1,3)],Do.prototype.setState=function(e,t){return this.state[e]=t,this.activeState={key:e,value:this.state[e]},this.activeState},Do.prototype.getState=function(e){return this.state[e]||null},Io.prototype.inboundIndex=function(e){return e>=0&&e0&&e<=this.lookahead.length:return this.lookahead[e-1];default:return null}},Io.prototype.rangeToText=function(e){if(e instanceof Ro)return this.getRangeTokens(e).map((function(e){return e.char})).join("")},Io.prototype.getText=function(){return this.tokens.map((function(e){return e.char})).join("")},Io.prototype.getContext=function(e){return this.registeredContexts[e]||null},Io.prototype.on=function(e,t){var r=this.events[e];return r?r.subscribe(t):null},Io.prototype.dispatch=function(e,t){var r=this,i=this.events[e];i instanceof Bo&&i.subscribers.forEach((function(e){e.apply(r,t||[])}))},Io.prototype.registerContextChecker=function(e,t,r){if(this.getContext(e))return{FAIL:"context name '"+e+"' is already registered."};if("function"!=typeof t)return{FAIL:"missing context start check."};if("function"!=typeof r)return{FAIL:"missing context end check."};var i=new Fo(e,t,r);return this.registeredContexts[e]=i,this.contextCheckers.push(i),i},Io.prototype.getRangeTokens=function(e){var t=e.startIndex+e.endOffset;return[].concat(this.tokens.slice(e.startIndex,t))},Io.prototype.getContextRanges=function(e){var t=this.getContext(e);return t?t.ranges:{FAIL:"context checker '"+e+"' is not registered."}},Io.prototype.resetContextsRanges=function(){var e=this.registeredContexts;for(var t in e)e.hasOwnProperty(t)&&(e[t].ranges=[])},Io.prototype.updateContextsRanges=function(){this.resetContextsRanges();for(var e=this.tokens.map((function(e){return e.char})),t=0;t=0;r--){var i=t[r],n=Wo(i),s=No(i);if(!n&&!s)return!0;if(n)return!1}return!1}(o)&&(h|=1),function(e){if(Wo(e.current))return!1;for(var t=0;t=1.2&&(n.markGlyphSets=r.parsePointer(Pa)),n}},Aa=new Array(10);Aa[1]=function(){var e=this.offset+this.relativeOffset,t=this.parseUShort();return 1===t?{posFormat:1,coverage:this.parsePointer(hn.coverage),value:this.parseValueRecord()}:2===t?{posFormat:2,coverage:this.parsePointer(hn.coverage),values:this.parseValueRecordList()}:void Li.assert(!1,"0x"+e.toString(16)+": GPOS lookup type 1 format must be 1 or 2.")},Aa[2]=function(){var e=this.offset+this.relativeOffset,t=this.parseUShort();Li.assert(1===t||2===t,"0x"+e.toString(16)+": GPOS lookup type 2 format must be 1 or 2.");var r=this.parsePointer(hn.coverage),i=this.parseUShort(),n=this.parseUShort();if(1===t)return{posFormat:t,coverage:r,valueFormat1:i,valueFormat2:n,pairSets:this.parseList(hn.pointer(hn.list((function(){return{secondGlyph:this.parseUShort(),value1:this.parseValueRecord(i),value2:this.parseValueRecord(n)}}))))};if(2===t){var s=this.parsePointer(hn.classDef),o=this.parsePointer(hn.classDef),a=this.parseUShort(),c=this.parseUShort();return{posFormat:t,coverage:r,valueFormat1:i,valueFormat2:n,classDef1:s,classDef2:o,class1Count:a,class2Count:c,classRecords:this.parseList(a,hn.list(c,(function(){return{value1:this.parseValueRecord(i),value2:this.parseValueRecord(n)}})))}}},Aa[3]=function(){return{error:"GPOS Lookup 3 not supported"}},Aa[4]=function(){return{error:"GPOS Lookup 4 not supported"}},Aa[5]=function(){return{error:"GPOS Lookup 5 not supported"}},Aa[6]=function(){return{error:"GPOS Lookup 6 not supported"}},Aa[7]=function(){return{error:"GPOS Lookup 7 not supported"}},Aa[8]=function(){return{error:"GPOS Lookup 8 not supported"}},Aa[9]=function(){return{error:"GPOS Lookup 9 not supported"}};var _a=new Array(10),Oa={parse:function(e,t){var r=new hn(e,t=t||0),i=r.parseVersion(1);return Li.argument(1===i||1.1===i,"Unsupported GPOS table version "+i),1===i?{version:i,scripts:r.parseScriptList(),features:r.parseFeatureList(),lookups:r.parseLookupList(Aa)}:{version:i,scripts:r.parseScriptList(),features:r.parseFeatureList(),lookups:r.parseLookupList(Aa),variations:r.parseFeatureVariationsList()}},make:function(e){return new rn.Table("GPOS",[{name:"version",type:"ULONG",value:65536},{name:"scripts",type:"TABLE",value:new rn.ScriptList(e.scripts)},{name:"features",type:"TABLE",value:new rn.FeatureList(e.features)},{name:"lookups",type:"TABLE",value:new rn.LookupList(e.lookups,_a)}])}},Da={parse:function(e,t){var r=new un.Parser(e,t),i=r.parseUShort();if(0===i)return function(e){var t={};e.skip("uShort");var r=e.parseUShort();Li.argument(0===r,"Unsupported kern sub-table version."),e.skip("uShort",2);var i=e.parseUShort();e.skip("uShort",3);for(var n=0;n1&&console.warn("Only the first kern subtable is supported."),e.skip("uLong");var r=255&e.parseUShort();if(e.skip("uShort"),0===r){var i=e.parseUShort();e.skip("uShort",3);for(var n=0;n{try{void 0!==e&&Array.isArray(e)&&0===e.length&&t({});const r=e?Rr.filter((t=>e.includes(t.key))):Rr,i=r.reduce(((e,t)=>e+t.variants.length),0);let n=0;r.forEach((e=>{e.variants.forEach((r=>{const s=e.key,o=`${s}-${r}`;!function(e,t,r){r=null==r?{}:r;var i="undefined"!=typeof window||r.isUrl?La:Fa;new Promise((function(n,s){i(e,(function(e,i){if(e){if(t)return t(e);s(e)}var o;try{o=Ia(i,r)}catch(e){if(t)return t(e,null);s(e)}if(t)return t(null,o);n(o)}))}))}(`https://cdn.jsdelivr.net/gh/bitbybit-dev/bitbybit-assets@0.15.13/fonts/${s}/${o}.ttf`,((e,a)=>{e||(this.fonts.push({name:o,type:s,variant:r,font:a}),n++,n===i&&t({}))}),{isUrl:!0})}))}))}catch(e){r(e)}}))},new((i=void 0)||(i=Promise))((function(e,s){function o(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i((function(e){e(r)}))).then(o,a)}c((n=n.apply(t,r||[])).next())}));var t,r,i,n}text3d(e){return oi(e,this.occtService,this.fonts,this.occ)}text3dFace(t){return function(t,r,i,n,s,o){if(!o.text3dFace)throw new Error("Could not compute, to use Text 3D Face algorithm you must be subscribed to our silver or gold plan.");try{const a=`\n ${o.text3dFace}\n `,c=new Function(a),h={name:"text3dFace"};return c.apply({inputs:t,occt:r,fonts:i,occ:n,vectorHelper:s,Inputs:e,Advanced:G,ShapeParser:ni,text3d:oi,method:h})}catch(e){throw new Error(e)}}(t,this.occtService,this.fonts,this.occ,this.vectorHelper,this.dependencies)}texts3dFace(t){return function(t,r,i,n,s,o){if(!o.text3dFace)throw new Error("Could not compute, to use Texts 3D Face algorithm you must be subscribed to our silver or gold plan.");try{const a=`\n ${o.text3dFace}\n `,c=new Function(a),h={name:"texts3dFace"};return c.apply({inputs:t,occt:r,fonts:i,occ:n,vectorHelper:s,Inputs:e,Advanced:G,ShapeParser:ni,text3d:oi,method:h})}catch(e){throw new Error(e)}}(t,this.occtService,this.fonts,this.occ,this.vectorHelper,this.dependencies)}pyramidSimple(t){return function(t,r,i,n,s){if(function(e){let t;if(["uNumber","vNumber","height","precision"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.uNumber<=0?t="U number mus be greater than 0.":e.vNumber<=0?t="V number must be greater than 0.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!s.patternsFacePatternPyramidSimple)throw new Error("Could not compute, to use Pyramid Simple algorithm you must be subscribed to our silver or gold plan.");try{const o=`\n ${s.patternsFacePatternPyramidSimple}\n `,a=new Function(o),c={name:"pyramidSimple"};return a.apply({inputs:t,occt:r,occ:i,vectorHelper:n,Inputs:e,Advanced:G,ShapeParser:ni,method:c})}catch(e){throw new Error(e)}}(t,this.occtService,this.occ,this.vectorHelper,this.dependencies)}pyramidSimpleAffectors(t){return function(t,r,i,n,s){if(function(e){let t;if(["uNumber","vNumber","defaultHeight","affectMinHeight","affectMaxHeight","precision"].forEach((r=>{isNaN(e[r])&&(t=`"${r}" must be a number.`)})),e.uNumber<=0?t="U number mus be greater than 0.":e.vNumber<=0?t="V number must be greater than 0.":e.precision<=0&&(t="Precision must be greater than 0."),t)throw new Error(t)}(t),!s.patternsFacePatternPyramidSimple)throw new Error("Could not compute, to use Pyramid Simple Affectors algorithm you must be subscribed to our silver or gold plan.");try{const o=`\n ${s.patternsFacePatternPyramidSimple}\n `,a=new Function(o),c={name:"pyramidSimpleAffectors"};return a.apply({inputs:t,occt:r,occ:i,vectorHelper:n,Inputs:e,Advanced:G,ShapeParser:ni,method:c})}catch(e){throw new Error(e)}}(t,this.occtService,this.occ,this.vectorHelper,this.dependencies)}}class Wa{constructor(e){this.dependencies={serenitySwirl:void 0};const t=new V,r=new H;this.occtService=new Pe(e,new Se(t,r,e)),this.advanced=new Ua(this.occtService,this.dependencies,e,t),this.things=new si(this.occtService,this.advanced,this.dependencies)}}var Na=function(){return Na=Object.assign||function(e){for(var t,r=1,i=arguments.length;r0&&n[n.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!n||a[1]>n[0]&&a[1]{Re=new Oe(e);const i=new V,n=new H;De=new Pe(e,new Se(i,n,e)),t&&(De.plugins=t,Fe&&Object.keys(Fe).forEach((e=>{De.plugins.dependencies[e]=Fe[e]}))),postMessage("occ-initialised")})(e,t),postMessage("occ-initialised"),[2]}}))}))})):((e,t)=>{let r;t("busy");try{if("shapeToMesh"!==e.action.functionName&&"shapesToMeshes"!==e.action.functionName&&"deleteShape"!==e.action.functionName&&"deleteShapes"!==e.action.functionName&&"startedTheRun"!==e.action.functionName&&"cleanAllCache"!==e.action.functionName&&"addOc"!==e.action.functionName&&"saveShapeSTEP"!==e.action.functionName){Object.keys(e.action.inputs).forEach((t=>{const r=e.action.inputs[t];r&&r.type&&"occ-shape"===r.type&&r.hash&&(e.action.inputs[t]=Re.checkCache(e.action.inputs[t].hash)),r&&Array.isArray(r)&&r.length>0&&(r[0].type&&"occ-shape"===r[0].type&&r[0].hash?e.action.inputs[t]=e.action.inputs[t].map((e=>Re.checkCache(e.hash))):Array.isArray(r[0])&&r[0][0].type&&"occ-shape"===r[0][0].type&&r[0][0].hash&&(e.action.inputs[t]=e.action.inputs[t].map((e=>e.map((e=>Re.checkCache(e.hash)))))))}));const t=e.action.functionName.split(".");let i;if(i=3===t.length?Re.cacheOp(e.action,(()=>De[t[0]][t[1]][t[2]](e.action.inputs))):2===t.length?Re.cacheOp(e.action,(()=>De[t[0]][t[1]](e.action.inputs))):Re.cacheOp(e.action,(()=>De[e.action.functionName](e.action.inputs))),Re.isOCCTObject(i))r=Array.isArray(i)?i.map((e=>({hash:e.hash,type:"occ-shape"}))):{hash:i.hash,type:"occ-shape"};else if(i.compound&&i.data&&i.shapes&&i.shapes.length>0){const e=i;e.shapes=e.shapes.map((e=>({id:e.id,shape:{hash:e.shape.hash,type:"occ-shape"}}))),e.compound={hash:e.compound.hash,type:"occ-shape"},r=e}else r=i}if("saveShapeSTEP"===e.action.functionName&&(e.action.inputs.shape=Re.checkCache(e.action.inputs.shape.hash),r=De.io.saveShapeSTEP(e.action.inputs)),"addOc"===e.action.functionName&&(De&&De.plugins?Object.keys(e.action.inputs).forEach((t=>{De.plugins.dependencies[t]=e.action.inputs[t]})):Fe=e.action.inputs),"shapeToMesh"===e.action.functionName&&(e.action.inputs.shape=Re.checkCache(e.action.inputs.shape.hash),r=De.shapeToMesh(e.action.inputs)),"shapesToMeshes"===e.action.functionName){if(!(e.action.inputs.shapes&&e.action.inputs.shapes.length>0))throw new Error("No shapes detected");e.action.inputs.shapes=e.action.inputs.shapes.map((e=>Re.checkCache(e.hash))),r=De.shapesToMeshes(e.action.inputs)}"deleteShape"===e.action.functionName&&(Re.cleanCacheForHash(e.action.inputs.shape.hash),r={}),"deleteShapes"===e.action.functionName&&(e.action.inputs.shapes.forEach((e=>Re.cleanCacheForHash(e.hash))),r={}),"startedTheRun"===e.action.functionName&&(Re&&Object.keys(Re.usedHashes).length>1e4&&Re.cleanAllCache(),r={}),"cleanAllCache"===e.action.functionName&&(Re.cleanAllCache(),r={}),t({uid:e.uid,result:r})}catch(r){let i,n;e&&e.action&&e.action.inputs&&(i=`Input values were: {${Object.keys(e.action.inputs).map((t=>`${t}: ${JSON.stringify(e.action.inputs[t])}`)).join(",")}}. `),e&&e.action&&e.action.functionName&&(n=`- ${e.action.functionName}`),t({uid:e.uid,result:void 0,error:`OCCT computation failed. ${r} While executing function ${n}. ${i}`})}})(d,postMessage)}))})()})(); \ No newline at end of file